2015-01-30 03:31:43 -07:00
<!DOCTYPE HTML>
< html >
< head i18n-values = "dir:textdirection;" >
< meta http-equiv = "Content-Type" content = "text/html; charset=utf-8" >
2015-06-18 08:27:29 -06:00
< polymer-element name = "tr-ui-b-toolbar-button" noscript = "noscript" >
2015-06-14 13:52:57 -06:00
< template >
2015-01-30 03:31:43 -07:00
< style >
2015-06-14 13:52:57 -06:00
:host {
2015-06-18 08:27:29 -06:00
background-color: #f8f8f8;
border: 1px solid rgba(0, 0, 0, 0.5);
color: rgba(0,0,0,0.8);
text-align: center;
2015-06-14 13:52:57 -06:00
}
2015-06-18 08:27:29 -06:00
:host(:hover) {
background-color: rgba(255, 255, 255, 1.0);
border-color: rgba(0, 0, 0, 0.8);
box-shadow: 0 0 .05em rgba(0, 0, 0, 0.4);
color: rgba(0, 0, 0, 1);
2015-06-14 13:52:57 -06:00
}
< / style >
< content > < / content >
< / template >
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-tab-view" constructor = "TracingAnalysisTabView" >
2015-01-30 03:31:43 -07:00
< template >
< style >
:host {
display: flex;
flex-flow: column nowrap;
overflow: hidden;
box-sizing: border-box;
}
tab-strip[tabs-hidden] {
display: none;
}
tab-strip {
background-color: rgb(236, 236, 236);
border-bottom: 1px solid #8e8e8e;
display: flex;
flex: 0 0 auto;
flex-flow: row;
overflow-x: auto;
padding: 0 10px 0 10px;
font-size: 12px;
}
tab-button {
display: block;
flex: 0 0 auto;
padding: 4px 15px 1px 15px;
margin-top: 2px;
}
tab-button[selected=true] {
background-color: white;
border: 1px solid rgb(163, 163, 163);
border-bottom: none;
padding: 3px 14px 1px 14px;
}
tabs-content-container {
display: flex;
flex: 1 1 auto;
overflow: auto;
width: 100%;
}
::content > * {
flex: 1 1 auto;
}
::content > *:not([selected]) {
display: none;
}
button-label {
display: inline;
}
2015-06-14 13:52:57 -06:00
tab-strip-heading {
display: block;
flex: 0 0 auto;
padding: 4px 15px 1px 15px;
margin-top: 2px;
margin-before: 20px;
margin-after: 10px;
}
#tsh {
display: inline;
font-weight: bold;
}
2015-01-30 03:31:43 -07:00
< / style >
< tab-strip >
2015-06-14 13:52:57 -06:00
< tab-strip-heading id = "tshh" >
< span id = "tsh" > < / span >
< / tab-strip-heading >
2015-01-30 03:31:43 -07:00
< template repeat = "{{tab in tabs_}}" >
< tab-button button-id = "{{ tab.id }}" on-click = "{{ tabButtonSelectHandler_ }}" selected = "{{ selectedTab_.id === tab.id }}" >
< button-label > {{ tab.label ? tab.label : 'No Label'}}< / button-label >
< / tab-button >
< / template >
< / tab-strip >
< tabs-content-container id = "content-container" >
< content > < / content >
< / tabs-content-container >
< / template >
2015-06-18 08:27:29 -06:00
< / polymer-element > < template id = "overlay-template" >
2015-06-14 13:52:57 -06:00
< style >
2015-06-18 08:27:29 -06:00
overlay-mask {
left: 0;
padding: 8px;
position: absolute;
top: 0;
z-index: 1000;
font-family: sans-serif;
-webkit-justify-content: center;
background: rgba(0, 0, 0, 0.8);
display: -webkit-flex;
height: 100%;
left: 0;
position: fixed;
top: 0;
width: 100%;
2015-06-14 13:52:57 -06:00
}
2015-06-18 08:27:29 -06:00
overlay-mask:focus {
outline: none;
2015-06-14 13:52:57 -06:00
}
2015-06-18 08:27:29 -06:00
overlay-vertical-centering-container {
-webkit-justify-content: center;
-webkit-flex-direction: column;
display: -webkit-flex;
}
overlay-frame {
z-index: 1100;
background: rgb(255, 255, 255);
border: 1px solid #ccc;
margin: 75px;
display: -webkit-flex;
-webkit-flex-direction: column;
min-height: 0;
}
title-bar {
-webkit-align-items: center;
-webkit-flex-direction: row;
border-bottom: 1px solid #ccc;
background-color: #ddd;
display: -webkit-flex;
padding: 5px;
-webkit-flex: 0 0 auto;
}
title {
display: inline;
font-weight: bold;
-webkit-box-flex: 1;
-webkit-flex: 1 1 auto;
}
close-button {
-webkit-align-self: flex-end;
border: 1px solid #eee;
background-color: #999;
font-size: 10pt;
font-weight: bold;
padding: 2px;
text-align: center;
width: 16px;
}
close-button:hover {
background-color: #ddd;
border-color: black;
cursor: pointer;
}
overlay-content {
display: -webkit-flex;
-webkit-flex: 1 1 auto;
-webkit-flex-direction: column;
overflow-y: auto;
padding: 10px;
min-width: 300px;
min-height: 0;
}
button-bar {
-webkit-align-items: baseline;
border-top: 1px solid #ccc;
display: -webkit-flex;
-webkit-flex: 0 0 auto;
-webkit-flex-direction: row-reverse;
padding: 4px;
}
< / style >
< overlay-mask >
< overlay-vertical-centering-container >
< overlay-frame >
< title-bar >
< title > < / title >
< close-button > & #x2715< / close-button >
< / title-bar >
< overlay-content >
< content > < / content >
< / overlay-content >
< button-bar > < / button-bar >
< / overlay-frame >
< / overlay-vertical-centering-container >
< / overlay-mask >
< / template > < polymer-element name = "tr-ui-a-sub-view" >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-analysis-link" is = "a" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: inline;
color: -webkit-link;
cursor: pointer;
text-decoration: underline;
/* TODO(nduca): Whitespace is forced to normal here because the
analysis_results.css forces everything under it to pre. This is insane.
When that horrible evil class dies, then we can rip this white-space
restriction out.
*/
white-space: normal;
cursor: pointer;
}
< / style >
< content > < / content >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < style >
* /deep/ .labeled-checkbox {
display: flex;
white-space: nowrap;
}
< / style > < polymer-element name = "tr-ui-b-table" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: flex;
flex-direction: column;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
table {
font-size: 12px;
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
flex: 1 1 auto;
align-self: stretch;
border-collapse: separate;
border-spacing: 0;
border-width: 0;
-webkit-user-select: initial;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
tr > td {
padding: 2px 4px 2px 4px;
vertical-align: text-top;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
tr:focus,
td:focus {
outline: 1px dotted rgba(0,0,0,0.1);
outline-offset: 0;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
button.toggle-button {
height: 15px;
line-height: 60%;
vertical-align: middle;
width: 100%;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
button > * {
height: 15px;
vertical-align: middle;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
td.button-column {
width: 30px;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
table > thead > tr > td.sensitive:hover {
background-color: #fcfcfc;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
table > thead > tr > td {
font-weight: bold;
text-align: left;
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
background-color: #eee;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
border-top: 1px solid #ffffff;
border-bottom: 1px solid #aaa;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
table > tfoot {
background-color: #eee;
font-weight: bold;
}
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
/* Selection. */
table > tbody.row-selection-mode > tr[selected],
table > tbody.cell-selection-mode > tr > td[selected] {
background-color: rgb(103, 199, 165); /* turquoise */
}
table > tbody.cell-selection-mode.row-highlight-enabled >
tr.highlighted-row {
background-color: rgb(213, 236, 229); /* light turquoise */
2015-06-14 13:52:57 -06:00
}
2015-06-18 08:27:29 -06:00
/* Hover. */
table > tbody.row-selection-mode >
tr:hover:not(.empty-row):not([selected]),
table > tbody.cell-selection-mode >
tr:not(.empty-row):not(.highlighted-row) >
td.supports-selection:hover:not([selected]),
2015-06-14 13:52:57 -06:00
table > tfoot > tr:hover {
2015-06-18 08:27:29 -06:00
background-color: #e6e6e6; /* grey */
}
table > tbody.cell-selection-mode.row-highlight-enabled >
tr:hover:not(.empty-row):not(.highlighted-row) {
background-color: #f6f6f6; /* light grey */
}
/* Hover on selected and highlighted elements. */
table > tbody.row-selection-mode > tr:hover[selected],
table > tbody.cell-selection-mode > tr > td:hover[selected],
table > tbody.cell-selection-mode > tr.highlighted-row > td:hover {
background-color: rgb(171, 217, 202); /* semi-light turquoise */
2015-06-14 13:52:57 -06:00
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
table > tbody > tr.empty-row > td {
color: #666;
font-style: italic;
text-align: center;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
table > tbody.has-footer > tr:last-child > td {
border-bottom: 1px solid #aaa;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
table > tfoot > tr:first-child > td {
border-top: 1px solid #ffffff;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
expand-button {
-webkit-user-select: none;
display: inline-block;
cursor: pointer;
font-size: 9px;
min-width: 8px;
max-width: 8px;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
.button-expanded {
transform: rotate(90deg);
}
< / style >
< table >
< thead id = "head" >
< / thead >
< tbody id = "body" >
< / tbody >
< tfoot id = "foot" >
< / tfoot >
< / table >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
< / polymer-element >
< polymer-element name = "tr-ui-b-table-header-cell" on-tap = "onTap_" >
< template >
< style >
:host {
-webkit-user-select: none;
display: flex;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
span {
flex: 0 1 auto;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
side-element {
-webkit-user-select: none;
flex: 1 0 auto;
padding-left: 4px;
vertical-align: top;
font-size: 15px;
font-family: sans-serif;
display: inline;
line-height: 85%;
}
< / style >
< span id = "title" > < / span > < side-element id = "side" > < / side-element >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-u-time-duration-span" >
< template >
< style >
:host {
display: flex;
flex-direction: row;
align-items: center;
}
#warning {
margin-left: 4px;
font-size: 66%;
}
< / style >
< span id = "content" > < / span >
< span id = "warning" style = "display:none" > ⚠ < / span >
< / template >
< / polymer-element > < polymer-element name = "tr-ui-u-time-stamp-span" >
< template >
< / template >
< / polymer-element > < polymer-element name = "tr-ui-u-size-in-bytes-span" >
< template >
< style >
:host {
display: flex;
flex-direction: row;
align-items: center;
}
< / style >
< span id = "content" > < / span >
< / template >
< / polymer-element > < polymer-element name = "tr-ui-a-generic-object-view" is = "HTMLUnknownElement" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: block;
font-family: monospace;
}
< / style >
< div id = "content" >
< / div >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
< / polymer-element >
2015-06-18 08:27:29 -06:00
< polymer-element name = "tr-ui-a-generic-object-view-with-label" is = "HTMLUnknownElement" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: block;
}
< / style >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-stack-frame" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: flex;
flex-direction: row;
align-items: center;
}
< / style >
2015-06-18 08:27:29 -06:00
< tr-ui-a-generic-object-view id = "ov" >
< / tr-ui-a-generic-object-view >
2015-06-14 13:52:57 -06:00
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-single-event-sub-view" extends = "tr-ui-a-sub-view" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: flex;
flex-direction: column;
}
#table {
flex: 1 1 auto;
align-self: stretch;
}
< / style >
< tr-ui-b-table id = "table" >
< / tr-ui-b-table >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-related-events" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: flex;
flex-direction: column;
}
#table {
flex: 1 1 auto;
align-self: stretch;
}
< / style >
< tr-ui-b-table id = "table" > < / tr-ui-b-table >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-single-thread-slice-sub-view" extends = "tr-ui-a-sub-view" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: flex;
flex-direction: row;
}
#events {
display: flex;
flex-direction: column;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
< / style >
2015-06-18 08:27:29 -06:00
< tr-ui-a-single-event-sub-view id = "content" > < / tr-ui-a-single-event-sub-view >
2015-06-14 13:52:57 -06:00
< div id = "events" >
2015-06-18 08:27:29 -06:00
< tr-ui-a-related-events id = "relatedEvents" >
< / tr-ui-a-related-events >
2015-06-14 13:52:57 -06:00
< / div >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-selection-summary-table" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: flex;
}
#table {
flex: 1 1 auto;
align-self: stretch;
}
< / style >
< tr-ui-b-table id = "table" >
< / tr-ui-b-table >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-multi-event-summary-table" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: flex;
}
#table {
flex: 1 1 auto;
align-self: stretch;
}
< / style >
< tr-ui-b-table id = "table" >
< / tr-ui-b-table >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-multi-event-details-table" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: flex;
flex-direction: column;
}
#table {
flex: 1 1 auto;
align-self: stretch;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
#titletable {
font-weight: bold;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
#title-info {
font-size: 12px;
}
< / style >
< tr-ui-b-table id = "titletable" >
< / tr-ui-b-table >
< tr-ui-b-table id = "table" >
< / tr-ui-b-table >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-multi-event-sub-view" extends = "tr-ui-a-sub-view" >
2015-06-14 13:52:57 -06:00
< template >
2015-01-30 03:31:43 -07:00
< style >
2015-06-14 13:52:57 -06:00
:host {
display: flex;
overflow: auto;
}
#content {
display: flex;
flex-direction: column;
flex: 0 1 auto;
align-self: stretch;
}
#content > * {
flex: 0 0 auto;
align-self: stretch;
}
2015-06-18 08:27:29 -06:00
tr-ui-a-multi-event-summary-table {
2015-06-14 13:52:57 -06:00
border-bottom: 1px solid #aaa;
}
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
tr-ui-a-selection-summary-table {
2015-06-14 13:52:57 -06:00
margin-top: 1.25em;
border-top: 1px solid #aaa;
background-color: #eee;
font-weight: bold;
margin-bottom: 1.25em;
border-bottom: 1px solid #aaa;
}
< / style >
< div id = "content" > < / div >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-multi-thread-slice-sub-view" extends = "tr-ui-a-sub-view" >
2015-06-14 13:52:57 -06:00
< template >
2015-01-30 03:31:43 -07:00
< style >
2015-06-14 13:52:57 -06:00
:host {
display: flex;
}
#content {
display: flex;
flex: 1 1 auto;
}
2015-06-18 08:27:29 -06:00
#content > tr-ui-a-related-events {
2015-06-14 13:52:57 -06:00
margin-left: 8px;
}
< / style >
< div id = "content" > < / div >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-single-async-slice-sub-view" extends = "tr-ui-a-single-event-sub-view" >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-multi-async-slice-sub-view" extends = "tr-ui-a-sub-view" >
2015-06-14 13:52:57 -06:00
< template >
2015-01-30 03:31:43 -07:00
< style >
2015-06-14 13:52:57 -06:00
:host {
display: flex;
}
< / style >
2015-06-18 08:27:29 -06:00
< tr-ui-a-multi-event-sub-view id = "content" > < / tr-ui-a-multi-event-sub-view >
2015-06-14 13:52:57 -06:00
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-single-cpu-slice-sub-view" extends = "tr-ui-a-sub-view" >
2015-06-14 13:52:57 -06:00
< template >
< style >
table {
border-collapse: collapse;
border-width: 0;
margin-bottom: 25px;
width: 100%;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
table tr > td:first-child {
padding-left: 2px;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
table tr > td {
padding: 2px 4px 2px 4px;
vertical-align: text-top;
width: 150px;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
table td td {
padding: 0 0 0 0;
width: auto;
}
tr {
vertical-align: top;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
tr:nth-child(2n+0) {
background-color: #e2e2e2;
}
< / style >
< table >
< tr >
< td > Running process:< / td > < td id = "process-name" > < / td >
< / tr >
< tr >
< td > Running thread:< / td > < td id = "thread-name" > < / td >
< / tr >
< tr >
< td > Start:< / td > < td id = "start" > < / td >
< / tr >
< tr >
< td > Duration:< / td > < td id = "duration" > < / td >
< / tr >
< tr >
< td > Active slices:< / td > < td id = "running-thread" > < / td >
< / tr >
< tr >
< td > Args:< / td >
< td >
2015-06-18 08:27:29 -06:00
< tr-ui-a-generic-object-view id = "args" >
< / tr-ui-a-generic-object-view >
2015-06-14 13:52:57 -06:00
< / td >
< / tr >
< / table >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-multi-cpu-slice-sub-view" extends = "tr-ui-a-sub-view" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: flex;
}
#content {
flex: 1 1 auto;
}
< / style >
2015-06-18 08:27:29 -06:00
< tr-ui-a-multi-event-sub-view id = "content" > < / tr-ui-a-multi-event-sub-view >
2015-06-14 13:52:57 -06:00
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-single-thread-time-slice-sub-view" extends = "tr-ui-a-sub-view" >
2015-06-14 13:52:57 -06:00
< template >
< style >
table {
border-collapse: collapse;
border-width: 0;
margin-bottom: 25px;
width: 100%;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
table tr > td:first-child {
padding-left: 2px;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
table tr > td {
padding: 2px 4px 2px 4px;
vertical-align: text-top;
width: 150px;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
table td td {
padding: 0 0 0 0;
width: auto;
}
tr {
vertical-align: top;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
tr:nth-child(2n+0) {
background-color: #e2e2e2;
}
< / style >
< table >
< tr >
< td > Running process:< / td > < td id = "process-name" > < / td >
< / tr >
< tr >
< td > Running thread:< / td > < td id = "thread-name" > < / td >
< / tr >
< tr >
< td > State:< / td >
< td > < b > < span id = "state" > < / span > < / b > < / td >
< / tr >
< tr >
< td > Start:< / td > < td id = "start" > < / td >
< / tr >
< tr >
< td > Duration:< / td > < td id = "duration" > < / td >
< / tr >
< tr >
< td > On CPU:< / td > < td id = "on-cpu" > < / td >
< / tr >
< tr >
< td > Running instead:< / td > < td id = "running-instead" > < / td >
< / tr >
< tr >
< td > Args:< / td > < td id = "args" > < / td >
< / tr >
< / table >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-multi-thread-time-slice-sub-view" extends = "tr-ui-a-sub-view" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: flex;
}
#content {
flex: 1 1 auto;
}
< / style >
2015-06-18 08:27:29 -06:00
< tr-ui-a-multi-event-sub-view id = "content" > < / tr-ui-a-multi-event-sub-view >
2015-06-14 13:52:57 -06:00
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-single-instant-event-sub-view" extends = "tr-ui-a-sub-view" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: block;
}
< / style >
< div id = "content" > < / div >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-multi-instant-event-sub-view" extends = "tr-ui-a-sub-view" >
2015-06-14 13:52:57 -06:00
< template >
2015-01-30 03:31:43 -07:00
< style >
2015-06-14 13:52:57 -06:00
:host {
display: block;
}
< / style >
< div id = "content" > < / div >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
< / polymer-element > < style >
.analysis-header{font-weight:bold}.analysis-results{font-family:monospace;white-space:pre}.analysis-results *{-webkit-user-select:text!important;cursor:text}.analysis-table{border-collapse:collapse;border-width:0;margin-bottom:25px;width:100%}.analysis-table tr>td:first-child{padding-left:2px}.analysis-table tr>td{padding:2px 4px 2px 4px;vertical-align:text-top;width:150px}.analysis-table td td{padding:0 0 0 0;width:auto}.analysis-table-header{text-align:left}.analysis-table-row{vertical-align:top}.analysis-table-row:nth-child(2n+0){background-color:#e2e2e2}.analysis-table-row-inverted:nth-child(2n+1){background-color:#e2e2e2}.selection-changing-link{color:-webkit-link;cursor:pointer;text-decoration:underline}.analysis-table thead{background-color:#e2e2e2;font-weight:bold}.analysis-table tfoot{font-weight:bold}
2015-06-18 08:27:29 -06:00
< / style > < polymer-element name = "tr-ui-a-counter-sample-sub-view" extends = "tr-ui-a-sub-view" >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-single-flow-event-sub-view" extends = "tr-ui-a-single-event-sub-view" >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-multi-flow-event-sub-view" extends = "tr-ui-a-sub-view" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: flex;
}
< / style >
2015-06-18 08:27:29 -06:00
< tr-ui-a-multi-event-sub-view id = "content" > < / tr-ui-a-multi-event-sub-view >
2015-06-14 13:52:57 -06:00
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-single-object-instance-sub-view" extends = "tr-ui-a-sub-view" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: block;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
#snapshots > * {
display: block;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
:host {
overflow: auto;
display: block;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
* {
-webkit-user-select: text;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
.title {
border-bottom: 1px solid rgb(128, 128, 128);
font-size: 110%;
font-weight: bold;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
td, th {
font-family: monospace;
vertical-align: top;
}
< / style >
< div id = "content" > < / div >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-single-object-snapshot-sub-view" extends = "tr-ui-a-sub-view" >
2015-06-14 13:52:57 -06:00
< template >
2015-01-30 03:31:43 -07:00
< style >
2015-06-14 13:52:57 -06:00
#args {
white-space: pre;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
:host {
overflow: auto;
display: flex;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
* {
-webkit-user-select: text;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
.title {
border-bottom: 1px solid rgb(128, 128, 128);
font-size: 110%;
font-weight: bold;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
td, th {
font-family: monospace;
vertical-align: top;
}
< / style >
< content > < / content >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-multi-object-sub-view" extends = "tr-ui-a-sub-view" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: flex;
}
< / style >
< tr-ui-b-table id = "content" > < / tr-ui-b-table >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-single-sample-sub-view" extends = "tr-ui-a-sub-view" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: flex;
}
< / style >
< tr-ui-b-table id = "content" > < / tr-ui-b-table >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-multi-sample-sub-view" extends = "tr-ui-a-sub-view" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: block;
}
< / style >
< div id = "content" > < / div >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-single-interaction-record-sub-view" extends = "tr-ui-a-sub-view" >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-multi-interaction-record-sub-view" extends = "tr-ui-a-sub-view" >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-alert-sub-view" extends = "tr-ui-a-sub-view" >
2015-06-14 13:52:57 -06:00
< template >
2015-01-30 03:31:43 -07:00
< style >
2015-06-14 13:52:57 -06:00
:host {
display: flex;
flex-direction: column;
}
#table {
flex: 1 1 auto;
align-self: stretch;
}
< / style >
< tr-ui-b-table id = "table" >
< / tr-ui-b-table >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-single-frame-sub-view" extends = "tr-ui-a-sub-view" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: flex;
flex-direction: column;
}
#asv {
flex: 0 0 auto;
align-self: stretch;
}
< / style >
2015-06-18 08:27:29 -06:00
< tr-ui-a-alert-sub-view id = "asv" >
< / tr-ui-a-alert-sub-view >
2015-06-14 13:52:57 -06:00
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-multi-frame-sub-view" extends = "tr-ui-a-sub-view" >
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
< / polymer-element > < polymer-element name = "tr-ui-b-color-legend" >
< template >
2015-01-30 03:31:43 -07:00
< style >
2015-06-14 13:52:57 -06:00
:host {
display: inline-block;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
#square {
font-size: 150%; /* Make the square bigger. */
line-height: 0%; /* Prevent the square from increasing legend height. */
}
< / style >
< span id = "square" > < / span >
< span id = "label" > < / span >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-memory-dump-allocator-details-pane" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: flex;
flex-direction: column;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
#label {
flex: 0 0 auto;
padding: 8px;
background-color: #eee;
border-bottom: 1px solid #8e8e8e;
border-top: 1px solid white;
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
font-size: 15px;
font-weight: bold;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
#contents {
flex: 1 0 auto;
align-self: stretch;
font-size: 12px;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
#contents .info-text {
padding: 8px;
color: #666;
font-style: italic;
text-align: center;
}
< / style >
< div id = "label" > Allocator details< / div >
< div id = "contents" > < / div >
< / template >
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-memory-dump-vm-regions-details-pane" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: flex;
flex-direction: column;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
#label {
flex: 0 0 auto;
padding: 8px;
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
background-color: #eee;
border-bottom: 1px solid #8e8e8e;
border-top: 1px solid white;
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
font-size: 15px;
font-weight: bold;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
#contents {
flex: 1 0 auto;
align-self: stretch;
font-size: 12px;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
#contents .info-text {
padding: 8px;
color: #666;
font-style: italic;
text-align: center;
}
< / style >
< div id = "label" > Memory maps< / div >
< div id = "contents" > < / div >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-memory-dump-overview-pane" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: flex;
flex-direction: column;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
#label {
flex: 0 0 auto;
padding: 8px;
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
background-color: #eee;
border-bottom: 1px solid #8e8e8e;
border-top: 1px solid white;
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
font-size: 15px;
font-weight: bold;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
#table {
flex: 1 0 auto;
align-self: stretch;
}
< / style >
< div id = "label" > Overview< / div >
< tr-ui-b-table id = "table" >
< / tr-ui-b-table >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-memory-dump-view" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: flex;
flex-direction: column;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
#overview_pane,
#details_pane_container {
flex: 0 0 auto;
}
< / style >
2015-06-18 08:27:29 -06:00
< tr-ui-a-memory-dump-overview-pane id = "overview_pane" >
< / tr-ui-a-memory-dump-overview-pane >
2015-06-14 13:52:57 -06:00
< div id = "details_pane_container" >
< / div >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-single-process-memory-dump-sub-view" extends = "tr-ui-a-sub-view" >
2015-06-14 13:52:57 -06:00
< template >
2015-06-18 08:27:29 -06:00
< tr-ui-a-memory-dump-view id = "memory_dump_view" >
< / tr-ui-a-memory-dump-view >
2015-06-14 13:52:57 -06:00
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-multi-process-memory-dump-sub-view" extends = "tr-ui-a-sub-view" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: flex;
}
< / style >
< tr-ui-b-table id = "content" > < / tr-ui-b-table >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-single-global-memory-dump-sub-view" extends = "tr-ui-a-sub-view" >
2015-06-14 13:52:57 -06:00
< template >
2015-06-18 08:27:29 -06:00
< tr-ui-a-memory-dump-view id = "memory_dump_view" >
< / tr-ui-a-memory-dump-view >
2015-06-14 13:52:57 -06:00
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-multi-global-memory-dump-sub-view" extends = "tr-ui-a-sub-view" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
display: flex;
}
< / style >
< tr-ui-b-table id = "content" > < / tr-ui-b-table >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-a-analysis-view" >
2015-06-14 13:52:57 -06:00
< template >
< style >
:host {
background-color: white;
display: flex;
flex-direction: column;
height: 275px;
overflow: auto;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
:host(.tall-mode) {
height: 525px;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
::content > * {
flex: 1 0 auto;
}
< / style >
< content > < / content >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
< / polymer-element > < style >
.track-button{background-color:rgba(255,255,255,0.5);border:1px solid rgba(0,0,0,0.1);color:rgba(0,0,0,0.2);font-size:10px;height:12px;text-align:center;width:12px}.track-button:hover{background-color:rgba(255,255,255,1.0);border:1px solid rgba(0,0,0,0.5);box-shadow:0 0 .05em rgba(0,0,0,0.4);color:rgba(0,0,0,1)}.track-close-button{left:2px;position:absolute;top:2px}.track-collapse-button{left:3px;position:absolute;top:2px}
< / style > < style >
.drawing-container{-webkit-box-flex:1;display:inline;overflow:auto;overflow-x:hidden;position:relative}.drawing-container-canvas{-webkit-box-flex:1;display:block;pointer-events:none;position:absolute;top:0}
< / style > < style >
.heading-track{-webkit-box-align:stretch;-webkit-box-orient:horizontal;display:-webkit-box;margin:0;padding:0 5px 0 0}.heading-track>heading{-webkit-box-sizing:border-box;background-color:rgb(243,245,247);border-right:1px solid #8e8e8e;box-sizing:border-box;display:-webkit-flex;-webkit-flex-direction:row;align-items:center;overflow-x:hidden;padding-right:5px;text-align:left;text-overflow:ellipsis;white-space:nowrap}.heading-track>heading>.heading-arrow{-webkit-flex:0 0 auto;margin-left:5px;margin-right:5px;width:8px;font-family:sans-serif}
< / style > < style >
.chart-track {
height: 30px;
position: relative;
}
< / style > < style >
.letter-dot-track {
height: 18px;
}
< / style > < style >
.object-instance-track{height:18px}
< / style > < style >
.rect-track{height:18px}
< / style > < style >
.spacing-track{height:4px}
< / style > < style >
.thread-track{-webkit-box-orient:vertical;display:-webkit-box;position:relative}
< / style > < style >
.process-track-header{-webkit-flex:0 0 auto;background-image:-webkit-gradient(linear,0 0,100% 0,from(#E5E5E5),to(#D1D1D1));border-bottom:1px solid #8e8e8e;border-top:1px solid white;font-size:75%}.process-track-name:before{content:'\25B8';padding:0 5px}.process-track-base.expanded .process-track-name:before{content:'\25BE'}
< / style > < style >
.model-track {
-webkit-box-flex: 1;
}
< / style > < style >
.ruler-track{height:12px}.ruler-track.tall-mode{height:30px}
< / style > < style >
2015-06-18 08:27:29 -06:00
* /deep/ .mouse-mode-selector{-webkit-user-drag:element;-webkit-user-select:none;background:#DDD;border:1px solid #BBB;border-radius:4px;box-shadow:0 1px 2px rgba(0,0,0,0.2);left:calc(100% - 120px);position:absolute;top:100px;user-select:none;width:29px;z-index:20}* /deep/ .mouse-mode-icon{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAChCAYAAACbBNzvAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABV0RVh0Q3JlYXRpb24gVGltZQA3LzE2LzEzRNEKUwAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNui8sowAAA9aSURBVHic7V1rTFvl//+UrgUmZWMpbLa6cLErwpYxkqLGkjAG88WSbmumGUllvlmAJctMRtybvlHrLXiJUekMIZuYSCL5gS+EuLIXGEGjqCsllCEW6xQECgzWG7S05/+C/zkp9LTn0gsL6ych9JzznOdzPj19Luf5PN/nCN59913ixRdfRFdXFxLx/2GDgCAIYmpqCoWFhUjE/4cNae+99x4AIFH/Hzak7nDqDu+wOyyw2WzEdl9EMpG23ReQbKQE73Q8coJ3bfcFWK1W/Pbbb/D7/UhLi/37DwaDEIvFKC8vR0lJSdjxbRVstVoxPDyMxx9/HAUFBcjMzIRAIOCdXzAYhNvtht1ux/DwMACEid5WwSMjI3jyySdRXFwMsVgMoVAYk2CCIJCZmYns7GyMjo5iZGQkPoKXl5exd+9e3hdGIhgMIj8/H5mZmRCJRIyCyQ5NJBAEgUAgAKFQiIKCAiwsLISl4VxoHA4H+vv74Xa7uZ4aBqFQiOzsbIhEIojFYojFYohEItq/8fFxXLlyBUtLSxHThOaxZ88eCIXC2AWPj48DAH799deYBaelpUEoFLL6++qrrwAAH3zwAav0YrGYthLkJHh6ehpzc3MAgPn5eUxPT8csWiAQMJbboaEhmM1mAIDFYsHQ0BDvPDkJtlgsYdt+v59LFrxw/fr1sG2Xy8UrL06C6+vrw7bFYjEvYi747rvvwrYlEgmvvDjV0g6HI+p2ohBP3qh32OFwoLe3l1VGvb29sNvtvC8kFCMjI9DpdKzS6nQ6mEwm1nnTPg/7/X6MjY1hcnKS/VX+P/bu3YuysjLk5uYypv36669x8uRJZGRkQCQSwev1oqOjAz09PZx5CwsLcenSJRw+fBh+vx+rq6swmUx46aWXNqWjvcMDAwO8xAIbnZKBgQFeNXhzczMvscBGp6S5uRk//vhj1HS0grVaLYqLi3kRy+Vy1NXVRe0RRcKNGzeg0Wh48apUKnR1daG6ujpqOtpKy+VyQa1Wo6SkBLdv38aFCxeoY5988gn1+fLly9TnL774ApWVlXjiiSfgdDqxtrbG+aJ9Ph/0ej3OnDkDvV6PW7duUceOHDlCfR4dHaU+v/DCC7h27RrUajWcTidWV1ejctAKJggCKysryMzMhE6nw+zsLO3Joft1Oh0ePHiApaUlduqi8BYVFaGvr48Vb19fHyfeqM2Sz+dj3QTEs4lKJC+njsfWJoptkxUrtjZRbJssOnASXFtbG3U7UXjrrbeibnMBJ8FZWVkoKysDABQUFCArK4s3MRcoFArqrlZXV0OhUPDOi5Ngn8+Hw4cPQyqV4tlnn4XP5+NNTIIgmH0An8+HV155BUqlEq+++ior3kAgQLuf84jH2toajh8/jvX1da6n0sLj8SAjI4MxHUEQ+PTTT1nlSRAEHjx4QHtsW8e0RCIR7HY79uzZE/GOcEUgEEAgEMDff/8NkUgUdnxbBR85cgRmsxkCgQD5+fkRh2XYIhAI4P79+5iamoLD4cCxY8fC0myr4KeeegoCgQBWqxVzc3NIS0uLedQyGAxi165dKC8vR1FRUVialHu405ESvNPxyAlOuYfJRMo9fFjdw3iBq3vIBDbu4bYK3uoextKtJEH2yWNyD8nyEG8wuYcffvgha3cxru6h3W5Hf39/QoyzaE6fyWRCQ0MDZ+MsLu7h8vIyent7sby8zIk8VkxNTUGn08Fms8UlP04Nn9/vR39/f9w8JLZwu91obGzk5CFFAq+Wfnh4mDKok4mWlha0trbGlAfvrs3k5CQGBgaSYoiHoqenB1evXk2OIb4VDocDJpMp6eXaYrGgsbGRV7mOufPq8XgwMDCQ9HI9NzeHq1evci7XvDseUqkUWq0W6enpCAaDcDqd8Hq9fLNjDaVSiRs3bkAikfDi5XSHxWIxampqAAALCwsYGhrC7Ows5ufnEypWIpHAYDAAACYmJnD9+nXevJwEnzp1CjKZDBUVFQCAsbGxpJTfjz76CFVVVWhqagIAdHR08G6XWQuuqanB7t274fV6UVpaiuzsbAAbTzyJhMFggEKhgNfrRX19PWQyGQDAaDTyyo+V4JqaGshkMsricLlcOH78OICNCWp8p0cwwWAwoKqqahPvG2+8AWDji+7u7uacJyvBMpksrKxkZWVR0yLGxsY4E7NBVVVVGK9CoaCmRXR0dHDOk5VguorB5/OhoqICYrE4YZ2PSLxXrlyBRCLhNcE1pufh1dVVXLx4EWlpaRGnJzCBjXtId87g4GBU3ri5h1uJ5+fnY8mCtXvIhTflHoYg5R4mEyn3MAl45KyWlOCdjkdOcMo9TCZS7mHKPeSGhLmH5LBOrAGXXN1DcliHrgdFgsk95CzYbrfDbDbD7/ejrKwstpmtNO5hJJhMJrS2tsLtdqOpqQlarTZi2mjuIWvBfr8fZrN50/iz2WzG9PQ0nn/+edonEzZgij10uVwwGo2bxp+NRiOGhobw+uuv005hjtk9JENz6AbbyWCuRESp2Ww2NDc30w62WywW6HQ6zoOIrO5wbm4uzp8/j5WVFXR2dm46VldXh3379mF5eTku86dDUVxcjK6uLthstrClqrq6unDo0CHOvKwE+/1+LC4uUqG0oZiYmIhaicQCkvfu3bthxwYGBnhVmpy6NnSD7kxxQvEA3Zo+fIsQJ8F040j379/nRcwFdF4037FwToLphkUXFxd5EXMB3chkUgQ7nc6wfT6fL+Gm+H///Re2z+Vy8TLFGSut/v5+RsPsm2++AbDR84pXLFNDQwPjelxnz54FsBFK+/nnn7PKl/EOa7VaVmHvYrE4au+HK27evMkq7F0ikeDmzZus82UU7HK5qG8yGs6ePct73gUdfD4f2tvbGdO1t7dzaocZBRMEAaFQSBnhdKipqYFQKORlm0TjzcvLo4xwOhgMBuTl5XHiZVVp+f1+yGQy2iDq4uJiyGSyhFRcfr8fVVVVtEHUGo0GVVVVnHlZ19JerxdqtRpSqZTaJ5VKoVarEzrdwev1Qq/XQ6lUUvuUSiX0ej0vXk7N0srKCjQaDbXmjUajwcrKCmfSULD5Oa6srKCtrQ0SiQQSiQRtbW2MvHFzD0MrsXhUUmzdw9BKjKmSiqt7SBBE3Conru4hOa8kWqBnyj3cgl0EQcQ0cMYWW3kIgkiKe7iVV2C1Won09PSYxLCB1+tFZmYmtb22tobt4E1LBimATaQAkiKWjveR85ZSgnc6Uu5hMpFyD1PuITekYg/ZxB52dXXFTMo2n1D38NSpU7zjDEP/yHzisnJpIsBm5dJ45rntgpONuITTJirctqWlJabjdGAUvNUEp0NouxcvtLa2MgZhmUwmzqKjCrbb7aw9HC5pmWAymVivb2kymTgFe0RslrbeNTa1rtlshkgkQn5+PusL2Iqtd42NdWM0GpGVlYWTJ08ypo14h/nGI8Uax8Q3XJbteREFV1ZW8iLmex6Ja9euJfS8iD9puVyOmpoa3L59G8DmVUq3glzNlAzoimVgvrq6GmlpadDr9QA2r1K6FeRqpmRAFxveiIK9Xi8VZ/jLL78whulUVFTELJbkJ
< / style >
< style >
* /deep/ .tool-button{background-position:center center;background-repeat:no-repeat;border-bottom:1px solid #BCBCBC;border-top:1px solid #F1F1F1;cursor:pointer;height:30px}* /deep/ .tool-button.active{cursor:auto}
< / style >
< template id = "mouse-mode-selector-template" >
< div class = "drag-handle" > < / div >
< div class = "buttons" >
< / div >
< / template > < style >
2015-06-14 13:52:57 -06:00
body *{-webkit-user-select:none;box-sizing:border-box}
< / style >
< style >
.timeline-track-view *{-webkit-user-select:none;cursor:default}.timeline-track-view .tool-button{cursor:pointer}.timeline-track-view{-webkit-box-orient:vertical;display:-webkit-box;position:relative}.model-track-container{-webkit-box-flex:1;overflow:auto}.drag-box{background-color:rgba(0,0,255,0.25);border:1px solid rgb(0,0,96);font-size:75%;position:fixed}.timeline-track-view>.hint-text{position:absolute;bottom:6px;right:6px;font-size:8pt}
2015-06-18 08:27:29 -06:00
< / style > < polymer-element name = "tr-ui-find-control" constructor = "TracingFindControl" >
2015-01-30 03:31:43 -07:00
< template >
< style >
2015-06-18 08:27:29 -06:00
:host {
2015-01-30 03:31:43 -07:00
-webkit-user-select: none;
display: -webkit-flex;
position: relative;
}
input {
-webkit-user-select: auto;
background-color: #f8f8f8;
border: 1px solid rgba(0, 0, 0, 0.5);
box-sizing: border-box;
2015-06-18 08:27:29 -06:00
margin: 0;
2015-01-30 03:31:43 -07:00
padding: 0;
width: 170px;
}
input:focus {
background-color: white;
}
2015-06-18 08:27:29 -06:00
tr-ui-b-toolbar-button {
2015-01-30 03:31:43 -07:00
border-left: none;
font-size: 14px;
2015-06-18 08:27:29 -06:00
margin: 0;
2015-01-30 03:31:43 -07:00
}
#hitCount {
left: 0;
opacity: 0.25;
pointer-events: none;
position: absolute;
text-align: right;
top: 2px;
2015-06-18 08:27:29 -06:00
width: 167px;
2015-01-30 03:31:43 -07:00
z-index: 1;
}
#spinner {
visibility: hidden;
width: 8px;
height: 8px;
left: 154px;
pointer-events: none;
position: absolute;
top: 4px;
z-index: 1;
border: 2px solid transparent;
border-bottom: 2px solid rgba(0, 0, 0, 0.5);
border-right: 2px solid rgba(0, 0, 0, 0.5);
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin { 100% { transform: rotate(360deg); } }
< / style >
< input type = "text" id = "filter" on-input = "{{ filterTextChanged }}" on-keypress = "{{ filterKeyPress }}" on-keydown = "{{ filterKeyDown }}" on-blur = "{{ filterBlur }}" on-focus = "{{ filterFocus }}" on-mouseup = "{{ filterMouseUp }}" / >
< div id = "spinner" > < / div >
2015-06-18 08:27:29 -06:00
< tr-ui-b-toolbar-button on-click = "{{ findPrevious }}" >
←
< / tr-ui-b-toolbar-button >
< tr-ui-b-toolbar-button on-click = "{{ findNext }}" >
→
< / tr-ui-b-toolbar-button >
2015-01-30 03:31:43 -07:00
< div id = "hitCount" > 0 of 0< / div >
< / template >
2015-06-14 13:52:57 -06:00
< / polymer-element > < polymer-element name = "tracing-scripting-control" constructor = "TracingScriptingControl" >
< template >
2015-01-30 03:31:43 -07:00
< style >
2015-06-14 13:52:57 -06:00
:host {
flex: 1 1 auto;
}
.root {
font-family: monospace;
cursor: text;
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
padding: 2px;
margin: 2px;
border: 1px solid rgba(0, 0, 0, 0.5);
background: white;
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
height: 100px;
overflow-y: auto;
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
transition-property: opacity, height, padding, margin;
transition-duration: .2s;
transition-timing-function: ease-out;
}
.hidden {
margin-top: 0px;
margin-bottom: 0px;
padding-top: 0px;
padding-bottom: 0px;
height: 0px;
opacity: 0;
}
.focused {
outline: auto 5px -webkit-focus-ring-color;
}
#history {
-webkit-user-select: text;
color: #777;
}
#prompt {
-webkit-user-select: text;
-webkit-user-modify: read-write-plaintext-only;
text-overflow: clip !important;
text-decoration: none !important;
}
#prompt:focus {
outline: none;
}
#prompt br {
display: none;
}
#prompt ::before {
content: ">";
color: #468;
}
< / style >
< div id = "root" class = "root hidden" tabindex = "0" on-focus = "{{ onConsoleFocus }}" >
< div id = "history" > < / div >
< div id = "prompt" on-keypress = "{{ promptKeyPress }}" on-keydown = "{{ promptKeyDown }}" on-blur = "{{ onConsoleBlur }}" >
< / div > < / div > < / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-side-panel" >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-side-panel-container" is = "HTMLUnknownElement" >
2015-06-14 13:52:57 -06:00
< template >
2015-01-30 03:31:43 -07:00
< style >
2015-06-14 13:52:57 -06:00
:host {
align-items: stretch;
display: -webkit-flex;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
:host([expanded]) > active-panel-container {
-webkit-flex: 1 1 auto;
border-left: 1px solid black;
display: -webkit-flex;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
:host(:not([expanded])) > active-panel-container {
display: none;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
active-panel-container {
display: flex;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
tab-strip {
-webkit-flex: 0 0 auto;
-webkit-flex-direction: column;
-webkit-user-select: none;
background-color: rgb(236, 236, 236);
border-left: 1px solid black;
cursor: default;
display: -webkit-flex;
min-width: 18px; /* workaround for flexbox and writing-mode mixing bug */
padding: 10px 0 10px 0;
font-size: 12px;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
tab-strip > tab-strip-label {
-webkit-writing-mode: vertical-rl;
display: inline;
margin-right: 1px;
min-height: 20px;
padding: 15px 3px 15px 1px;
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
tab-strip >
tab-strip-label:not([enabled]) {
color: rgb(128, 128, 128);
}
2015-01-30 03:31:43 -07:00
2015-06-14 13:52:57 -06:00
tab-strip > tab-strip-label[selected] {
background-color: white;
border: 1px solid rgb(163, 163, 163);
border-left: none;
padding: 14px 2px 14px 1px;
}
< / style >
< active-panel-container id = "active_panel_container" >
< / active-panel-container >
< tab-strip id = "tab_strip" > < / tab-strip >
< / template >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
< / polymer-element > < polymer-element name = "tr-ui-b-dropdown" >
< template >
< style >
:host {
position: relative;
display: flex;
}
#outer {
display: flex;
flex: 0 0 auto;
padding: 1px 4px 1px 4px;
-webkit-user-select: none;
cursor: default;
font-size: 12px;
}
#state {
display: flex;
flex: 0 0 auto;
margin-left: 2px;
margin-right: 0px;
flex: 0 0 auto;
}
#icon {
display: flex;
flex: 0 0 auto;
flex: 0 0 auto;
}
dialog {
position: absolute;
padding: 0;
border: 0;
margin: 0;
}
dialog::backdrop {
background: rgba(0,0,0,.05);
}
#dialog-frame {
background-color: #fff;
display: flex;
flex-direction: column;
flex: 1 1 auto;
padding: 6px;
border: 1px solid black;
-webkit-user-select: none;
cursor: default;
}
< / style >
< tr-ui-b-toolbar-button id = "outer" >
< div id = "icon" > ⚙ < / div >
< div id = "state" > ▾ < / div >
< / tr-ui-b-toolbar-button >
< dialog id = "dialog" >
< div id = "dialog-frame" >
< content > < / content >
< / div >
< / dialog >
< / template >
2015-06-14 13:52:57 -06:00
< / polymer-element > < style >
2015-06-18 08:27:29 -06:00
* /deep/ x-drag-handle{-webkit-user-select:none;box-sizing:border-box;display:block}* /deep/ x-drag-handle.horizontal-drag-handle{background-image:-webkit-gradient(linear,0 0,0 100%,from(#E5E5E5),to(#D1D1D1));border-bottom:1px solid #8e8e8e;border-top:1px solid white;cursor:ns-resize;height:7px;position:relative;z-index:10}* /deep/ x-drag-handle.vertical-drag-handle{background-image:-webkit-gradient(linear,0 0,100% 0,from(#E5E5E5),to(#D1D1D1));border-left:1px solid white;border-right:1px solid #8e8e8e;cursor:ew-resize;position:relative;width:7px;z-index:10}
< / style > < style >
x-timeline-view{-webkit-flex-direction:column;cursor:default;display:-webkit-flex;font-family:sans-serif;padding:0}x-timeline-view>.control>.title{font-size:14px;height:22px;padding-left:2px;padding-right:8px;padding-top:2px;flex:1 0 auto}x-timeline-view>.control{background-color:#e6e6e6;background-image:-webkit-gradient(linear,0 0,0 100%,from(#E5E5E5),to(#D1D1D1));flex:0 0 auto;overflow-x:auto}x-timeline-view>.control>.bar{display:flex}x-timeline-view>.control::-webkit-scrollbar{height:0px}x-timeline-view>.control>.bar>#right-controls{height:21px;margin-left:auto}x-timeline-view>.control>#collapsing-controls{display:-webkit-flex}x-timeline-view>.control .controls{display:-webkit-flex;flex:0 0 auto}x-timeline-view>.control>.bar>span{padding-left:5px;padding-right:10px}x-timeline-view>.control>.bar>.controls button,x-timeline-view>.control>.bar>.controls label,x-timeline-view>.control>.bar>.controls tr-ui-b-toolbar-button,x-timeline-view>.control>.bar>.controls tr-ui-b-dropdown,x-timeline-view>.control>.bar>.controls tr-ui-find-control{font-size:14px;margin:1px 1px 1px 0}x-timeline-view>.control>.bar>.spacer{-webkit-flex:1 1 auto}x-timeline-view>middle-container{-webkit-flex:1 1 auto;-webkit-flex-direction:row;border-bottom:1px solid #8e8e8e;display:-webkit-flex;min-height:0}x-timeline-view>middle-container>track-view-container{-webkit-flex:1 1 auto;display:-webkit-flex;min-height:0;min-width:0}x-timeline-view>middle-container>track-view-container>*{-webkit-flex:1 1 auto}x-timeline-view>middle-container>x-timeline-view-side-panel-container{-webkit-flex:0 0 auto}x-timeline-view>x-drag-handle{-webkit-flex:0 0 auto}x-timeline-view>tr-ui-a-analysis-view{-webkit-flex:0 0 auto}x-timeline-view .selection{margin:2px}x-timeline-view .selection ul{margin:0}tr-ui-b-toolbar-button{min-width:23px}.view-info-button{padding-left:4px;padding-right:4px;width:auto}.view-info-button:hover{border:solid 1px}.metadata-dialog-text{font-family:monospace;overflow:auto;white-space:pre}.view-help-text{-webkit-flex:1 1 auto;-webkit-flex-direction:row;display:-webkit-flex;width:700px}.view-help-text .column{width:50%}.view-help-text h2{font-size:1.2em;margin:0;margin-top:5px;text-align:center}.view-help-text h3{margin:0;margin-left:126px;margin-top:10px}.view-help-text .pair{-webkit-flex:1 1 auto;-webkit-flex-direction:row;display:-webkit-flex}.view-help-text .command{font-family:monospace;margin-right:5px;text-align:right;width:150px}.view-help-text .action{font-size:0.9em;text-align:left;width:200px}.view-help-text .mouse-mode-icon{border:1px solid #888;border-radius:3px;box-shadow:inset 0 0 2px rgba(0,0,0,0.3);display:inline-block;height:26px;margin-right:1px;position:relative;top:4px;width:27px;zoom:0.75}.view-help-text .mouse-mode-icon.pan-mode{background-position:-1px -11px}.view-help-text .mouse-mode-icon.select-mode{background-position:-1px -41px}.view-help-text .mouse-mode-icon.zoom-mode{background-position:-1px -71px}.view-help-text .mouse-mode-icon.timing-mode{background-position:-1px -101px}
2015-06-14 13:52:57 -06:00
< / style >
2015-01-30 03:31:43 -07:00
2015-06-18 08:27:29 -06:00
2015-01-30 03:31:43 -07:00
< template id = "timeline-view-template" >
< div class = "control" >
2015-06-14 13:52:57 -06:00
< div class = "bar" >
2015-01-30 03:31:43 -07:00
< div id = "left-controls" class = "controls" > < / div >
< div class = "title" > ^_^< / div >
< div id = "right-controls" class = "controls" > < / div >
< / div >
2015-06-14 13:52:57 -06:00
< div id = "collapsing-controls" class = "controls" > < / div >
< / div >
2015-01-30 03:31:43 -07:00
< middle-container >
< track-view-container > < / track-view-container >
2015-06-18 08:27:29 -06:00
< tr-ui-side-panel-container > < / tr-ui-side-panel-container >
2015-01-30 03:31:43 -07:00
< / middle-container >
< x-drag-handle > < / x-drag-handle >
2015-06-18 08:27:29 -06:00
< tr-ui-a-analysis-view id = "analysis" > < / tr-ui-a-analysis-view >
2015-01-30 03:31:43 -07:00
< / template >
< template id = "help-btn-template" >
2015-06-18 08:27:29 -06:00
< tr-ui-b-toolbar-button class = "view-help-button" >
?
< / tr-ui-b-toolbar-button >
2015-01-30 03:31:43 -07:00
< div class = "view-help-text" >
< div class = "column left" >
< h2 > Navigation< / h2 >
< div class = "pair" >
< div class = "command" > w/s< / div >
< div class = "action" > Zoom in/out (+shift: faster)< / div >
< / div >
< div class = "pair" >
< div class = "command" > a/d< / div >
< div class = "action" > Pan left/right (+shift: faster)< / div >
< / div >
< div class = "pair" >
< div class = "command" > → /shift-TAB< / div >
< div class = "action" > Select previous event< / div >
< / div >
< div class = "pair" >
< div class = "command" > ← /TAB< / div >
< div class = "action" > Select next event< / div >
< / div >
< h2 > Mouse Controls< / h2 >
< div class = "pair" >
< div class = "command" > click< / div >
< div class = "action" > Select event< / div >
< / div >
< div class = "pair" >
< div class = "command" > alt-mousewheel< / div >
< div class = "action" > Zoom in/out< / div >
< / div >
< h3 >
< span class = "mouse-mode-icon select-mode" > < / span >
Select mode
< / h3 >
< div class = "pair" >
< div class = "command" > drag< / div >
< div class = "action" > Box select< / div >
< / div >
< div class = "pair" >
< div class = "command" > double click< / div >
< div class = "action" > Select all events with same title< / div >
< / div >
< h3 >
< span class = "mouse-mode-icon pan-mode" > < / span >
Pan mode
< / h3 >
< div class = "pair" >
< div class = "command" > drag< / div >
< div class = "action" > Pan the view< / div >
< / div >
< h3 >
< span class = "mouse-mode-icon zoom-mode" > < / span >
Zoom mode
< / h3 >
< div class = "pair" >
< div class = "command" > drag< / div >
< div class = "action" > Zoom in/out by dragging up/down< / div >
< / div >
< h3 >
< span class = "mouse-mode-icon timing-mode" > < / span >
Timing mode
< / h3 >
< div class = "pair" >
< div class = "command" > drag< / div >
< div class = "action" > Create or move markers< / div >
< / div >
< div class = "pair" >
< div class = "command" > double click< / div >
< div class = "action" > Set marker range to slice< / div >
< / div >
< / div >
< div class = "column right" >
< h2 > General< / h2 >
< div class = "pair" >
< div class = "command" > 1-4< / div >
< div class = "action" > Switch mouse mode< / div >
< / div >
< div class = "pair" >
< div class = "command" > shift< / div >
< div class = "action" > Hold for temporary select< / div >
< / div >
< div class = "pair" >
< div class = "command" > space< / div >
< div class = "action" > Hold for temporary pan< / div >
< / div >
< div class = "pair" >
< div class = "command" > < span class = "mod" > < / span > < / div >
< div class = "action" > Hold for temporary zoom< / div >
< / div >
< div class = "pair" >
< div class = "command" > /< / div >
< div class = "action" > Search< / div >
< / div >
< div class = "pair" >
< div class = "command" > enter< / div >
< div class = "action" > Step through search results< / div >
< / div >
< div class = "pair" >
< div class = "command" > f< / div >
< div class = "action" > Zoom into selection< / div >
< / div >
< div class = "pair" >
< div class = "command" > z/0< / div >
< div class = "action" > Reset zoom and pan< / div >
< / div >
< div class = "pair" >
< div class = "command" > g/G< / div >
< div class = "action" > Toggle 60hz grid< / div >
< / div >
< div class = "pair" >
< div class = "command" > v< / div >
< div class = "action" > Highlight VSync< / div >
< / div >
< div class = "pair" >
< div class = "command" > h< / div >
< div class = "action" > Toggle low/high details< / div >
< / div >
< div class = "pair" >
< div class = "command" > m< / div >
< div class = "action" > Mark current selection< / div >
< / div >
< div class = "pair" >
2015-06-14 13:52:57 -06:00
< div class = "command" > `< / div >
< div class = "action" > Show or hide the scripting console< / div >
< / div >
< div class = "pair" >
2015-01-30 03:31:43 -07:00
< div class = "command" > ?< / div >
< div class = "action" > Show help< / div >
< / div >
< / div >
< / div >
< / template >
< template id = "metadata-btn-template" >
< div class = "button view-metadata-button view-info-button" > Metadata< / div >
< div class = "info-button-text metadata-dialog-text" > < / div >
< / template >
2015-06-14 13:52:57 -06:00
< template id = "console-btn-template" >
2015-06-18 08:27:29 -06:00
< tr-ui-b-toolbar-button class = "view-console-button" >
»
< / tr-ui-b-toolbar-button >
2015-06-14 13:52:57 -06:00
< / template > < script >
2015-01-30 03:31:43 -07:00
// Copyright (c) 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/* WARNING: This file is auto generated.
*
* Do not edit directly.
*/
/**
* @license
* Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
2015-06-14 13:52:57 -06:00
// @version 0.5.5
window.PolymerGestures={},function(a){var b=!1,c=document.createElement("meta");if(c.createShadowRoot){var d=c.createShadowRoot(),e=document.createElement("span");d.appendChild(e),c.addEventListener("testpath",function(a){a.path&&(b=a.path[0]===e),a.stopPropagation()}); var f=new CustomEvent("testpath",{bubbles:!0});document.head.appendChild(c),e.dispatchEvent(f),c.parentNode.removeChild(c),d=e=null}c=null;var g={shadow:function(a){return a?a.shadowRoot||a.webkitShadowRoot:void 0},canTarget:function(a){return a& & Boolean(a.elementFromPoint)},targetingShadow:function(a){var b=this.shadow(a);return this.canTarget(b)?b:void 0},olderShadow:function(a){var b=a.olderShadowRoot;if(!b){var c=a.querySelector("shadow");c& & (b=c.olderShadowRoot)}return b},allShadows:function(a){for(var b=[],c=this.shadow(a);c;)b.push(c),c=this.olderShadow(c);return b},searchRoot:function(a,b,c){var d,e;return a?(d=a.elementFromPoint(b,c),d?e=this.targetingShadow(d):a!==document& & (e=this.olderShadow(a)),this.searchRoot(e,b,c)||d):void 0},owner:function(a){if(!a)return document;for(var b=a;b.parentNode;)b=b.parentNode;return b.nodeType!=Node.DOCUMENT_NODE& & b.nodeType!=Node.DOCUMENT_FRAGMENT_NODE& & (b=document),b},findTarget:function(a){if(b& & a.path& & a.path.length)return a.path[0];var c=a.clientX,d=a.clientY,e=this.owner(a.target);return e.elementFromPoint(c,d)||(e=document),this.searchRoot(e,c,d)},findTouchAction:function(a){var c;if(b& & a.path& & a.path.length){for(var d=a.path,e=0;e< d.length ; e + + ) if ( c = d[e],c.nodeType===Node.ELEMENT_NODE&&c.hasAttribute("touch-action"))return c . getAttribute ( " touch-action " ) } else for ( c = a.target;c;){if(c.nodeType===Node.ELEMENT_NODE&&c.hasAttribute("touch-action"))return c . getAttribute ( " touch-action " ) ; c = c.parentNode||c.host}return"auto"},LCA:function(a,b){if(a===b)return a ; if ( a & & ! b ) return a ; if ( b & & ! a ) return b ; if ( ! b & & ! a ) return document ; if ( a . contains & & a . contains ( b ) ) return a ; if ( b . contains & & b . contains ( a ) ) return b ; var c = this.depth(a),d=this.depth(b),e=c-d;for(e > =0?a=this.walk(a,e):b=this.walk(b,-e);a&&b&&a!==b; )a=a.parentNode||a.host,b=b.parentNode||b.host;return a},walk:function(a,b){for(var c=0;a&&b>c; c++)a=a.parentNode||a.host;return a},depth:function(a){for(var b=0;a;)b++,a=a.parentNode||a.host;return b},deepContains:function(a,b){var c=this.LCA(a,b);return c===a},insideNode:function(a,b,c){var d=a.getBoundingClientRect();return d.left< =b& & b< =d.right& & d.top< =c& & c< =d.bottom},path:function(a){var c;if(b&&a.path&&a.path.length)c=a.path; else{c=[];for(var d=this.findTarget(a);d;)c.push(d),d=d.parentNode||d.host}return c}};a.targetFinding=g,a.findTarget=g.findTarget.bind(g),a.deepContains=g.deepContains.bind(g),a.insideNode=g.insideNode}(window.PolymerGestures),function(){function a(a){return"html /deep/ "+b(a)}function b(a){return'[touch-action="'+a+'"]'}function c(a){return"{ -ms-touch-action: "+a+"; touch-action: "+a+";}"}var d=["none","auto","pan-x","pan-y",{rule:"pan-x pan-y",selectors:["pan-x pan-y","pan-y pan-x"]},"manipulation"],e="",f="string"==typeof document.head.style.touchAction,g=!window.ShadowDOMPolyfill&&document.head.createShadowRoot; if(f){d.forEach(function(d){String(d)===d?(e+=b(d)+c(d)+"\n",g&&(e+=a(d)+c(d)+"\n")):(e+=d.selectors.map(b)+c(d.rule)+"\n",g&&(e+=d.selectors.map(a)+c(d.rule)+"\n"))}); var h=document.createElement("style");h.textContent=e,document.head.appendChild(h)}}(),function(a){var b=["bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget","pageX","pageY"],c=[!1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,0,0],d=function(){return function(){}},e={preventTap:d,makeBaseEvent:function(a,b){var c=document.createEvent("Event");return c.initEvent(a,b.bubbles||!1,b.cancelable||!1),c.preventTap=e.preventTap(c),c},makeGestureEvent:function(a,b){b=b||Object.create(null);for(var c,d=this.makeBaseEvent(a,b),e=0,f=Object.keys(b);e< f.length ; e + + ) c = f[e],"bubbles"!==c&&"cancelable"!==c&&(d[c]=b[c]);return d } , makePointerEvent:function ( a , d ) { d = d||Object.create(null);for(var e , f = this.makeBaseEvent(a,d),g=2;g<b.length;g++)e=b[g],f[e]=d[e]
var ab=H,bb=L;a.esprima={parse:R}}(this),function(a){"use strict";function b(a,b,d,e){var f;try{if(f=c(a),f.scopeIdent& & (d.nodeType!==Node.ELEMENT_NODE||"TEMPLATE"!==d.tagName||"bind"!==b& & "repeat"!==b))throw Error("as and in can only be used within < template bind / repeat > ")}catch(g){return void console.error("Invalid expression syntax: "+a,g)}return function(a,b,c){var d=f.getBinding(a,e,c);return f.scopeIdent& & d& & (b.polymerExpressionScopeIdent_=f.scopeIdent,f.indexIdent& & (b.polymerExpressionIndexIdent_=f.indexIdent)),d}}function c(a){var b=q[a];if(!b){var c=new j;esprima.parse(a,c),b=new l(c),q[a]=b}return b}function d(a){this.value=a,this.valueFn_=void 0}function e(a){this.name=a,this.path=Path.get(a)}function f(a,b,c){this.computed="["==c,this.dynamicDeps="function"==typeof a||a.dynamicDeps||this.computed& & !(b instanceof d),this.simplePath=!this.dynamicDeps& & (b instanceof e||b instanceof d)& & (a instanceof f||a instanceof e),this.object=this.simplePath?a:i(a),this.property=!this.computed||this.simplePath?b:i(b)}function g(a,b){this.name=a,this.args=[];for(var c=0;c< b.length ; c + + ) this . args [ c ] = i ( b [ c ] ) } function h ( ) { throw Error ( " Not Implemented " ) } function i ( a ) { return " function " = = typeof a ? a:a . valueFn ( ) } function j ( ) { this . expression = null,this.filters=[],this.deps={},this.currentPath=void 0 , this . scopeIdent = void 0 , this . indexIdent = void 0 , this . dynamicDeps = !1}function k ( a ) { this . value_ = a}function l ( a ) { if ( this . scopeIdent = a.scopeIdent,this.indexIdent=a.indexIdent,!a.expression)throw Error ( " No expression found . " ) ; this . expression = a.expression,i(this.expression),this.filters=a.filters,this.dynamicDeps=a.dynamicDeps}function m ( a ) { return String ( a ) . replace ( / [ A-Z ] / g , function ( a ) { return " - " + a . toLowerCase ( ) } ) } function n ( a , b ) { for ( ; a [ t ] & & ! Object . prototype . hasOwnProperty . call ( a , b ) ; ) a = a[t];return a } function o ( a ) { switch ( a ) { case " " :return ! 1 ; case " false " :case " null " :case " true " :return ! 0 } return isNaN ( Number ( a ) ) ? ! 1: ! 0 } function p ( ) { } var q = Object.create(null);d.prototype={valueFn:function(){if(!this.valueFn_){var a = this.value;this.valueFn_=function(){return a } } return this . valueFn_ } } , e . prototype = {valueFn:function(){if(!this.valueFn_){var a = (this.name,this.path);this.valueFn_=function(b,c){return c & & c . addPath ( b , a ) , a . getValueFrom ( b ) } } return this . valueFn_ } , setValue:function ( a , b ) { return 1 = =this.path.length&&(a=n(a,this.path[0])),this.path.setValueFrom(a,b)}},f.prototype={get fullPath ( ) { if ( ! this . fullPath_ ) { var a = this.object instanceof f ? this . object . fullPath . slice ( ) : [ this . object . name ] ; a . push ( this . property instanceof e ? this . property . name:this . property . value ) , this . fullPath_ = Path.get(a)}return this . fullPath_ } , valueFn:function ( ) { if ( ! this . valueFn_ ) { var a = this.object;if(this.simplePath){var b = this.fullPath;this.valueFn_=function(a,c){return c & & c . addPath ( a , b ) , b . getValueFrom ( a ) } } else if ( this . computed ) { var c = this.property;this.valueFn_=function(b,d,e){var f = a(b,d,e),g=c(b,d,e);return d & & d . addPath ( f , [ g ] ) , f ? f [ g ] :void 0 } } else { var b = Path.get(this.property.name);this.valueFn_=function(c,d,e){var f = a(c,d,e);return d & & d . addPath ( f , b ) , b . getValueFrom ( f ) } } } return this . valueFn_ } , setValue:function ( a , b ) { if ( this . simplePath ) return this . fullPath . setValueFrom ( a , b ) , b ; var c = this.object(a),d=this.property instanceof e ? this . property . name:this . property ( a ) ; return c [ d ] = b } } , g . prototype = {transform:function(a,b,c,d,e){var f = a,g=f[this.name];if(!g&&(g=c[this.name],!g))return void console . error ( " Cannot find function or filter: " + this . name ) ; if ( d ? g = g.toModel:"function"==typeof g . toDOM & & ( g = g.toDOM),"function"!=typeof g ) return void console . error ( " Cannot find function or filter: " + this . name ) ; for ( var h = e||[],j=0;j<this.args.length;j++)h.push(i(this.args[j])(a,b,c));return g . apply ( f , h ) } } ; var r = {"+":function(a){return+a},"-":function(a){return-a},"!":function(a){return!a}},s={"+":function(a,b){return a + b } , " - " :function ( a , b ) { return a-b } , " * " :function ( a , b ) { return a * b } , " / " :function ( a , b ) { return a / b } , " % " :function ( a , b ) { return a % b } , " < " :function ( a , b ) { return b > a},">":function(a,b){return a>b},"< =":function(a,b){return b>=a},">=":function(a,b){return a>=b},"==":function(a,b){return a==b},"!=":function(a,b){return a!=b},"==="
return q(this,d.open(r(this))),t(this,a,e)},HTMLSelectElement.prototype.bind=function(a,c,d){if("selectedindex"===a& & (a="selectedIndex"),"selectedIndex"!==a& & "value"!==a)return HTMLElement.prototype.bind.call(this,a,c,d);if(this.removeAttribute(a),d)return j(this,a,c);var e=c,f=m(this,a,e);return j(this,a,e.open(k(this,a))),b(this,a,f)}}(this),function(a){"use strict";function b(a){if(!a)throw new Error("Assertion failed")}function c(a){for(var b;b=a.parentNode;)a=b;return a}function d(a,b){if(b){for(var d,e="#"+b;!d&&(a=c(a),a.protoContent_?d=a.protoContent_.querySelector(e):a.getElementById&&(d=a.getElementById(b)),!d&&a.templateCreator_); )a=a.templateCreator_;return d}}function e(a){return"template"==a.tagName& & "http://www.w3.org/2000/svg"==a.namespaceURI}function f(a){return"TEMPLATE"==a.tagName& & "http://www.w3.org/1999/xhtml"==a.namespaceURI}function g(a){return Boolean(L[a.tagName]& & a.hasAttribute("template"))}function h(a){return void 0===a.isTemplate_& & (a.isTemplate_="TEMPLATE"==a.tagName||g(a)),a.isTemplate_}function i(a,b){var c=a.querySelectorAll(N);h(a)& & b(a),G(c,b)}function j(a){function b(a){HTMLTemplateElement.decorate(a)||j(a.content)}i(a,b)}function k(a,b){Object.getOwnPropertyNames(b).forEach(function(c){Object.defineProperty(a,c,Object.getOwnPropertyDescriptor(b,c))})}function l(a){var b=a.ownerDocument;if(!b.defaultView)return b;var c=b.templateContentsOwner_;if(!c){for(c=b.implementation.createHTMLDocument("");c.lastChild;)c.removeChild(c.lastChild);b.templateContentsOwner_=c}return c}function m(a){if(!a.stagingDocument_){var b=a.ownerDocument;if(!b.stagingDocument_){b.stagingDocument_=b.implementation.createHTMLDocument(""),b.stagingDocument_.isStagingDocument=!0;var c=b.stagingDocument_.createElement("base");c.href=document.baseURI,b.stagingDocument_.head.appendChild(c),b.stagingDocument_.stagingDocument_=b.stagingDocument_}a.stagingDocument_=b.stagingDocument_}return a.stagingDocument_}function n(a){var b=a.ownerDocument.createElement("template");a.parentNode.insertBefore(b,a);for(var c=a.attributes,d=c.length;d-->0;){var e=c[d];K[e.name]& & ("template"!==e.name& & b.setAttribute(e.name,e.value),a.removeAttribute(e.name))}return b}function o(a){var b=a.ownerDocument.createElement("template");a.parentNode.insertBefore(b,a);for(var c=a.attributes,d=c.length;d-->0;){var e=c[d];b.setAttribute(e.name,e.value),a.removeAttribute(e.name)}return a.parentNode.removeChild(a),b}function p(a,b,c){var d=a.content;if(c)return void d.appendChild(b);for(var e;e=b.firstChild;)d.appendChild(e)}function q(a){P?a.__proto__=HTMLTemplateElement.prototype:k(a,HTMLTemplateElement.prototype)}function r(a){a.setModelFn_||(a.setModelFn_=function(){a.setModelFnScheduled_=!1;var b=z(a,a.delegate_&&a.delegate_.prepareBinding); w(a,b,a.model_)}),a.setModelFnScheduled_||(a.setModelFnScheduled_=!0,Observer.runEOM_(a.setModelFn_))}function s(a,b,c,d){if(a& & a.length){for(var e,f=a.length,g=0,h=0,i=0,j=!0;f>h;){var g=a.indexOf("{{",h),k=a.indexOf("[[",h),l=!1,m="}}";if(k>=0&&(0>g||g>k)&&(g=k,l=!0,m="]]"),i=0>g?-1:a.indexOf(m,g+2),0>i){if(!e)return; e.push(a.slice(h));break}e=e||[],e.push(a.slice(h,g));var n=a.slice(g+2,i).trim();e.push(l),j=j&&l; var o=d&&d(n,b,c); e.push(null==o?Path.get(n):null),e.push(o),h=i+2}return h===f& & e.push(""),e.hasOnePath=5===e.length,e.isSimplePath=e.hasOnePath& & ""==e[0]& & ""==e[4],e.onlyOneTime=j,e.combinator=function(a){for(var b=e[0],c=1;c< e.length ; c + = 4 ) { var d = e.hasOnePath?a:a[(c-1)/4];void 0 ! = = d & & ( b + = d ) , b + = e [ c + 3 ] } return b } , e } } function t ( a , b , c , d ) { if ( b . hasOnePath ) { var e = b[3],f=e?e(d,c,!0):b[2].getValueFrom(d);return b . isSimplePath ? f:b . combinator ( f ) } for ( var g = [],h=1;h<b.length;h+=4){var e = b[h+2];g[(h-1)/4]=e?e(d,c):b[h+1].getValueFrom(d)}return b . combinator ( g ) } function u ( a , b , c , d ) { var e = b[3],f=e?e(d,c,!1):new PathObserver ( d , b [ 2 ] ) ; return b . isSimplePath ? f:new ObserverTransform ( f , b . combinator ) } function v ( a , b , c , d ) { if ( b . onlyOneTime ) return t ( a , b , c , d ) ; if ( b . hasOnePath ) return u ( a , b , c , d ) ; for ( var e = new CompoundObserver , f = 1;f<b.length;f+=4){var g = b[f],h=b[f+2];if(h){var i = h(d,c,g);g?e.addPath(i):e.addObserver(i)}else{var j =
2015-06-18 08:27:29 -06:00
b.events& & Object.keys(a).length>0& & console.log("[%s] addHostListeners:",this.localName,a);for(var c in a){var d=a[c];PolymerGestures.addEventListener(this,c,this.element.getEventHandler(this,this,d))}},dispatchMethod:function(a,c,d){if(a){b.events& & console.group("[%s] dispatch [%s]",a.localName,c);var e="function"==typeof c?c:a[c];e&&e[d?"apply":"call"](a,d),b.events&&console.groupEnd(),Polymer.flush()}}}; a.api.instance.events=d,a.addEventListener=function(a,b,c,d){PolymerGestures.addEventListener(wrap(a),b,c,d)},a.removeEventListener=function(a,b,c,d){PolymerGestures.removeEventListener(wrap(a),b,c,d)}}(Polymer),function(a){var b={copyInstanceAttributes:function(){var a=this._instanceAttributes;for(var b in a)this.hasAttribute(b)||this.setAttribute(b,a[b])},takeAttributes:function(){if(this._publishLC)for(var a,b=0,c=this.attributes,d=c.length;(a=c[b])&&d>b; b++)this.attributeToProperty(a.name,a.value)},attributeToProperty:function(b,c){var b=this.propertyForAttribute(b);if(b){if(c&&c.search(a.bindPattern)>=0)return; var d=this[b],c=this.deserializeValue(c,d);c!==d& & (this[b]=c)}},propertyForAttribute:function(a){var b=this._publishLC&&this._publishLC[a]; return b},deserializeValue:function(b,c){return a.deserializeValue(b,c)},serializeValue:function(a,b){return"boolean"===b?a?"":void 0:"object"!==b& & "function"!==b& & void 0!==a?a:void 0},reflectPropertyToAttribute:function(a){var b=typeof this[a],c=this.serializeValue(this[a],b);void 0!==c?this.setAttribute(a,c):"boolean"===b&&this.removeAttribute(a)}}; a.api.instance.attributes=b}(Polymer),function(a){function b(a,b){return a===b?0!==a||1/a===1/b:f(a)& & f(b)?!0:a!==a& & b!==b}function c(a,b){return void 0===b& & null===a?b:null===b||void 0===b?a:b}var d=window.WebComponents?WebComponents.flags.log:{},e={object:void 0,type:"update",name:void 0,oldValue:void 0},f=Number.isNaN||function(a){return"number"==typeof a& & isNaN(a)},g={createPropertyObserver:function(){var a=this._observeNames;if(a& & a.length){var b=this._propertyObserver=new CompoundObserver(!0);this.registerObserver(b);for(var c,d=0,e=a.length;e>d&&(c=a[d]); d++)b.addPath(this,c),this.observeArrayValue(c,this[c],null)}},openPropertyObserver:function(){this._propertyObserver& & this._propertyObserver.open(this.notifyPropertyChanges,this)},notifyPropertyChanges:function(a,b,c){var d,e,f={};for(var g in b)if(d=c[2*g+1],e=this.observe[d]){var h=b[g],i=a[g];this.observeArrayValue(d,i,h),f[e]||(void 0!==h& & null!==h||void 0!==i& & null!==i)& & (f[e]=!0,this.invokeMethod(e,[h,i,arguments]))}},invokeMethod:function(a,b){var c=this[a]||a;"function"==typeof c& & c.apply(this,b)},deliverChanges:function(){this._propertyObserver& & this._propertyObserver.deliver()},observeArrayValue:function(a,b,c){var e=this.observe[a];if(e& & (Array.isArray(c)& & (d.observe& & console.log("[%s] observeArrayValue: unregister observer [%s]",this.localName,a),this.closeNamedObserver(a+"__array")),Array.isArray(b))){d.observe& & console.log("[%s] observeArrayValue: register observer [%s]",this.localName,a,b);var f=new ArrayObserver(b);f.open(function(a){this.invokeMethod(e,[a])},this),this.registerNamedObserver(a+"__array",f)}},emitPropertyChangeRecord:function(a,c,d){if(!b(c,d)& & (this._propertyChanged(a,c,d),Observer.hasObjectObserve)){var f=this._objectNotifier;f||(f=this._objectNotifier=Object.getNotifier(this)),e.object=this,e.name=a,e.oldValue=d,f.notify(e)}},_propertyChanged:function(a){this.reflect[a]& & this.reflectPropertyToAttribute(a)},bindProperty:function(a,b,d){if(d)return void(this[a]=b);var e=this.element.prototype.computed;if(e& & e[a]){var f=a+"ComputedBoundObservable_";return void(this[f]=b)}return this.bindToAccessor(a,b,c)},bindToAccessor:function(a,c,d){function e(b,c){j[f]=b;var d=j[h];d& & "function"==typeof d.setValue& & d.setValue(b),j.emitPropertyChangeRecord(a,b,c)}var f=a+"_",g=a+"Observable_",h=a+"ComputedBoundObservable_";this[g]=c;var i=this[f],j=this,k=c.open(e);if(d& & !b(i,k)){var l=d(i,k);b(k,l)||(k=l,c.setValue&&c.setValue(k))}e(k,i); var m={close:function(){c.close(),j[g]=void 0,j[h]=void 0}};return this.registerObserver(m),m},createComputedProp
function exportPath(name){var parts=name.split('.');var cur=global;for(var part;parts.length&&(part=parts.shift()); ){if(part in cur){cur=cur[part];}else{cur=cur[part]={};}}
return cur;};function isDefined(name){var parts=name.split('.');var curObject=global;for(var i=0;i< parts.length ; i + + ) { var partName = parts[i];var nextObject = curObject[partName];if(nextObject===undefined)
2015-06-14 13:52:57 -06:00
return false;curObject=nextObject;}
2015-06-18 08:27:29 -06:00
return true;}
var panicElement=undefined;var rawPanicMessages=[];function showPanicElementIfNeeded(){if(panicElement)
return;var panicOverlay=document.createElement('div');panicOverlay.style.backgroundColor='white';panicOverlay.style.border='3px solid red';panicOverlay.style.boxSizing='border-box';panicOverlay.style.color='black';panicOverlay.style.display='-webkit-flex';panicOverlay.style.height='100%';panicOverlay.style.left=0;panicOverlay.style.padding='8px';panicOverlay.style.position='fixed';panicOverlay.style.top=0;panicOverlay.style.webkitFlexDirection='column';panicOverlay.style.width='100%';panicElement=document.createElement('div');panicElement.style.webkitFlex='1 1 auto';panicElement.style.overflow='auto';panicOverlay.appendChild(panicElement);if(!document.body){setTimeout(function(){document.body.appendChild(panicOverlay);},150);}else{document.body.appendChild(panicOverlay);}}
function showPanic(panicTitle,panicDetails){if(panicDetails instanceof Error)
panicDetails=panicDetails.stack;showPanicElementIfNeeded();var panicMessageEl=document.createElement('div');panicMessageEl.innerHTML='< h2 id = "message" > < / h2 > '+'< pre id = "details" > < / pre > ';panicMessageEl.querySelector('#message').textContent=panicTitle;panicMessageEl.querySelector('#details').textContent=panicDetails;panicElement.appendChild(panicMessageEl);rawPanicMessages.push({title:panicTitle,details:panicDetails});}
function hasPanic(){return rawPanicMessages.length!==0;}
function getPanicText(){return rawPanicMessages.map(function(msg){return msg.title;}).join(', ');}
function exportTo(namespace,fn){var obj=exportPath(namespace);var exports=fn();for(var propertyName in exports){var propertyDescriptor=Object.getOwnPropertyDescriptor(exports,propertyName);if(propertyDescriptor)
Object.defineProperty(obj,propertyName,propertyDescriptor);}};function initialize(){tr.doc=document;tr.isMac=/Mac/.test(navigator.platform);tr.isWindows=/Win/.test(navigator.platform);tr.isChromeOS=/CrOS/.test(navigator.userAgent);tr.isLinux=/Linux/.test(navigator.userAgent);}
return{initialize:initialize,exportTo:exportTo,isDefined:isDefined,showPanic:showPanic,hasPanic:hasPanic,getPanicText:getPanicText};})();tr.initialize();'use strict';tr.exportTo('tr.b',function(){function Settings(){return Settings;};document.head.addEventListener('tr-unittest-will-run',function(){Settings.setAlternativeStorageInstance(global.sessionStorage);});function SessionSettings(){return SessionSettings;}
2015-06-14 13:52:57 -06:00
function AddStaticStorageFunctionsToClass_(input_class,storage){input_class.storage_=storage;input_class.get=function(key,opt_default,opt_namespace){key=input_class.namespace_(key,opt_namespace);var rawVal=input_class.storage_.getItem(key);if(rawVal===null||rawVal===undefined)
return opt_default;try{return JSON.parse(rawVal).value;}catch(e){input_class.storage_.removeItem(input_class.namespace_(key,opt_namespace));return opt_default;}};input_class.set=function(key,value,opt_namespace){if(value===undefined)
throw new Error('Settings.set: value must not be undefined');var v=JSON.stringify({value:value});input_class.storage_.setItem(input_class.namespace_(key,opt_namespace),v);};input_class.keys=function(opt_namespace){var result=[];opt_namespace=opt_namespace||'';for(var i=0;i< input_class.storage_.length ; i + + ) { var key = input_class.storage_.key(i);if(input_class.isnamespaced_(key,opt_namespace))
result.push(input_class.unnamespace_(key,opt_namespace));}
return result;};input_class.isnamespaced_=function(key,opt_namespace){return key.indexOf(input_class.normalize_(opt_namespace))==0;};input_class.namespace_=function(key,opt_namespace){return input_class.normalize_(opt_namespace)+key;};input_class.unnamespace_=function(key,opt_namespace){return key.replace(input_class.normalize_(opt_namespace),'');};input_class.normalize_=function(opt_namespace){return input_class.NAMESPACE+(opt_namespace?opt_namespace+'.':'');};input_class.setAlternativeStorageInstance=function(instance){input_class.storage_=instance;};input_class.getAlternativeStorageInstance=function(){if(input_class.storage_===localStorage)
2015-06-18 08:27:29 -06:00
return undefined;return input_class.storage_;};input_class.NAMESPACE='trace-viewer';};AddStaticStorageFunctionsToClass_(Settings,localStorage);AddStaticStorageFunctionsToClass_(SessionSettings,sessionStorage);return{Settings:Settings,SessionSettings:SessionSettings};});'use strict';tr.exportTo('tr.b',function(){function asArray(arrayish){var values=[];for(var i=0;i< arrayish.length ; i + + )
2015-06-14 13:52:57 -06:00
values.push(arrayish[i]);return values;}
function compareArrays(x,y,elementCmp){var minLength=Math.min(x.length,y.length);for(var i=0;i< minLength ; i + + ) { var tmp = elementCmp(x[i],y[i]);if(tmp)
return tmp;}
if(x.length==y.length)
return 0;if(x[i]===undefined)
return-1;return 1;}
function comparePossiblyUndefinedValues(x,y,cmp,opt_this){if(x!==undefined& & y!==undefined)
return cmp.call(opt_this,x,y);if(x!==undefined)
return-1;if(y!==undefined)
return 1;return 0;}
function concatenateArrays(){var values=[];for(var i=0;i< arguments.length ; i + + ) { if ( ! ( arguments [ i ] instanceof Array ) )
throw new Error('Arguments '+i+'is not an array');values.push.apply(values,arguments[i]);}
return values;}
function concatenateObjects(){var result={};for(var i=0;i< arguments.length ; i + + ) { var object = arguments[i];for(var j in object ) { result [ j ] = object [ j ] ; } }
return result;}
function dictionaryKeys(dict){var keys=[];for(var key in dict)
keys.push(key);return keys;}
function dictionaryValues(dict){var values=[];for(var key in dict)
values.push(dict[key]);return values;}
function dictionaryLength(dict){var n=0;for(var key in dict)
n++;return n;}
function group(ary,fn){return ary.reduce(function(accumulator,curr){var key=fn(curr);if(key in accumulator)
accumulator[key].push(curr);else
accumulator[key]=[curr];return accumulator;},{});}
function iterItems(dict,fn,opt_this){opt_this=opt_this||this;var keys=Object.keys(dict);for(var i=0;i< keys.length ; i + + ) { var key = keys[i];fn.call(opt_this,key,dict[key]);}}
function mapItems(dict,fn,opt_this){opt_this=opt_this||this;var result={};var keys=Object.keys(dict);for(var i=0;i< keys.length ; i + + ) { var key = keys[i];result[key]=fn.call(opt_this,key,dict[key]);}
return result;}
function iterObjectFieldsRecursively(object,func){if(!(object instanceof Object))
return;if(object instanceof Array){for(var i=0;i< object.length ; i + + ) { func ( object , i , object [ i ] ) ; iterObjectFieldsRecursively ( object [ i ] , func ) ; }
return;}
for(var key in object){var value=object[key];func(object,key,value);iterObjectFieldsRecursively(value,func);}}
function identity(d){return d;}
function findFirstIndexInArray(ary,opt_func,opt_this){var func=opt_func||identity;for(var i=0;i< ary.length ; i + + ) { if ( func . call ( opt_this , ary [ i ] , i ) )
return i;}
return-1;}
function findFirstInArray(ary,opt_func,opt_this){var i=findFirstIndexInArray(ary,opt_func,opt_func);if(i===-1)
return undefined;return ary[i];}
2015-06-18 08:27:29 -06:00
return{asArray:asArray,concatenateArrays:concatenateArrays,concatenateObjects:concatenateObjects,compareArrays:compareArrays,comparePossiblyUndefinedValues:comparePossiblyUndefinedValues,dictionaryLength:dictionaryLength,dictionaryKeys:dictionaryKeys,dictionaryValues:dictionaryValues,group:group,iterItems:iterItems,mapItems:mapItems,iterObjectFieldsRecursively:iterObjectFieldsRecursively,identity:identity,findFirstIndexInArray:findFirstIndexInArray,findFirstInArray:findFirstInArray};});'use strict';Polymer('tr-ui-a-tab-view',{ready:function(){this.$.tshh.style.display='none';this.tabs_=[];this.selectedTab_=undefined;for(var i=0;i< this.children.length ; i + + )
2015-06-14 13:52:57 -06:00
this.processAddedChild_(this.children[i]);this.childrenObserver_=new MutationObserver(this.childrenUpdated_.bind(this));this.childrenObserver_.observe(this,{childList:'true'});},get tabStripHeadingText(){return this.$.tsh.textContent;},set tabStripHeadingText(tabStripHeadingText){this.$.tsh.textContent=tabStripHeadingText;if(!!tabStripHeadingText)
this.$.tshh.style.display='';else
this.$.tshh.style.display='none';},get selectedTab(){this.childrenUpdated_(this.childrenObserver_.takeRecords(),this.childrenObserver_);if(this.selectedTab_)
return this.selectedTab_.content;return undefined;},set selectedTab(content){this.childrenUpdated_(this.childrenObserver_.takeRecords(),this.childrenObserver_);if(content===undefined||content===null){this.changeSelectedTabById_(undefined);return;}
var contentTabId=undefined;for(var i=0;i< this.tabs_.length ; i + + )
if(this.tabs_[i].content===content){contentTabId=this.tabs_[i].id;break;}
if(contentTabId===undefined){console.warn('Tab not in tabs list. Ignoring changed selection.');return;}
this.changeSelectedTabById_(contentTabId);},get tabsHidden(){var ts=this.shadowRoot.querySelector('tab-strip');return ts.hasAttribute('tabs-hidden');},set tabsHidden(tabsHidden){tabsHidden=!!tabsHidden;var ts=this.shadowRoot.querySelector('tab-strip');if(tabsHidden)
ts.setAttribute('tabs-hidden',true);else
ts.removeAttribute('tabs-hidden');},processAddedChild_:function(child){var observerAttributeSelected=new MutationObserver(this.childAttributesChanged_.bind(this));var observerAttributeTabLabel=new MutationObserver(this.childAttributesChanged_.bind(this));var tabObject={id:this.tabs_.length,content:child,label:child.getAttribute('tab-label'),observers:{forAttributeSelected:observerAttributeSelected,forAttributeTabLabel:observerAttributeTabLabel},savedScrollTop:0,savedScrollLeft:0};this.tabs_.push(tabObject);if(child.hasAttribute('selected')){if(this.selectedTab_)
child.removeAttribute('selected');else
this.setSelectedTabById_(tabObject.id);}
var previousSelected=child.selected;var tabView=this;Object.defineProperty(child,'selected',{configurable:true,set:function(value){if(value){tabView.changeSelectedTabById_(tabObject.id);return;}
var wasSelected=tabView.selectedTab_===tabObject;if(wasSelected)
tabView.changeSelectedTabById_(undefined);},get:function(){return this.hasAttribute('selected');}});if(previousSelected)
child.selected=previousSelected;observerAttributeSelected.observe(child,{attributeFilter:['selected']});observerAttributeTabLabel.observe(child,{attributeFilter:['tab-label']});},processRemovedChild_:function(child){for(var i=0;i< this.tabs_.length ; i + + ) { this . tabs_ [ i ] . id = i;if(this.tabs_[i].content===child){this.tabs_[i].observers.forAttributeSelected.disconnect();this.tabs_[i].observers.forAttributeTabLabel.disconnect();if(this.tabs_[i]===this.selectedTab_){this.clearSelectedTab_();this.fire('selected-tab-change');}
child.removeAttribute('selected');delete child.selected;this.tabs_.splice(i,1);i--;}}},childAttributesChanged_:function(mutations,observer){var tabObject=undefined;for(var i=0;i< this.tabs_.length ; i + + ) { var observers = this.tabs_[i].observers;if(observers.forAttributeSelected===observer||observers.forAttributeTabLabel===observer){tabObject=this.tabs_[i];break;}}
if(!tabObject)
return;for(var i=0;i< mutations.length ; i + + ) { var node = tabObject.content;if(mutations[i].attributeName==='tab-label')
tabObject.label=node.getAttribute('tab-label');if(mutations[i].attributeName==='selected'){var nodeIsSelected=node.hasAttribute('selected');if(nodeIsSelected)
this.changeSelectedTabById_(tabObject.id);else
this.changeSelectedTabById_(undefined);}}},childrenUpdated_:function(mutations,observer){mutations.forEach(function(mutation){for(var i=0;i< mutation.removedNodes.length ; i + + )
this.processRemovedChild_(mutation.removedNodes[i]);for(var i=0;i< mutation.addedNodes.length ; i + + )
this.processAddedChild_(mutation.addedNodes[i]);},this);},tabButtonSelectHandler_:function(event,detail,sender){this.changeSelectedTabById_(sender.getAttribute('button-id'));},changeSelectedTabById_:function(id){var newTab=id!==undefined?this.tabs_[id]:undefined;var changed=this.selectedTab_!==newTab;this.saveCurrentTabScrollPosition_();this.clearSelectedTab_();if(id!==undefined){this.setSelectedTabById_(id);this.restoreCurrentTabScrollPosition_();}
if(changed)
2015-06-18 08:27:29 -06:00
this.fire('selected-tab-change');},setSelectedTabById_:function(id){this.selectedTab_=this.tabs_[id];this.selectedTab_.observers.forAttributeSelected.disconnect();this.selectedTab_.content.setAttribute('selected','selected');this.selectedTab_.observers.forAttributeSelected.observe(this.selectedTab_.content,{attributeFilter:['selected']});},saveCurrentTabScrollPosition_:function(){if(this.selectedTab_){this.selectedTab_.savedScrollTop=this.$['content-container'].scrollTop;this.selectedTab_.savedScrollLeft=this.$['content-container'].scrollLeft;}},restoreCurrentTabScrollPosition_:function(){if(this.selectedTab_){this.$['content-container'].scrollTop=this.selectedTab_.savedScrollTop;this.$['content-container'].scrollLeft=this.selectedTab_.savedScrollLeft;}},clearSelectedTab_:function(){if(this.selectedTab_){this.selectedTab_.observers.forAttributeSelected.disconnect();this.selectedTab_.content.removeAttribute('selected');this.selectedTab_.observers.forAttributeSelected.observe(this.selectedTab_.content,{attributeFilter:['selected']});this.selectedTab_=undefined;}}});'use strict';tr.exportTo('tr.b',function(){function EventTarget(){}
EventTarget.decorate=function(target){for(var k in EventTarget.prototype){if(k=='decorate')
continue;var v=EventTarget.prototype[k];if(typeof v!=='function')
continue;target[k]=v;}};EventTarget.prototype={addEventListener:function(type,handler){if(!this.listeners_)
this.listeners_=Object.create(null);if(!(type in this.listeners_)){this.listeners_[type]=[handler];}else{var handlers=this.listeners_[type];if(handlers.indexOf(handler)< 0 )
handlers.push(handler);}},removeEventListener:function(type,handler){if(!this.listeners_)
return;if(type in this.listeners_){var handlers=this.listeners_[type];var index=handlers.indexOf(handler);if(index>=0){if(handlers.length==1)
delete this.listeners_[type];else
handlers.splice(index,1);}}},dispatchEvent:function(event){if(!this.listeners_)
return true;var self=this;event.__defineGetter__('target',function(){return self;});var realPreventDefault=event.preventDefault;event.preventDefault=function(){realPreventDefault.call(this);this.rawReturnValue=false;};var type=event.type;var prevented=0;if(type in this.listeners_){var handlers=this.listeners_[type].concat();for(var i=0,handler;handler=handlers[i];i++){if(handler.handleEvent)
prevented|=handler.handleEvent.call(handler,event)===false;else
prevented|=handler.call(this,event)===false;}}
return!prevented&&event.rawReturnValue; },hasEventListener:function(type){return this.listeners_[type]!==undefined;}};var EventTargetHelper={decorate:function(target){for(var k in EventTargetHelper){if(k=='decorate')
continue;var v=EventTargetHelper[k];if(typeof v!=='function')
continue;target[k]=v;}
target.listenerCounts_={};},addEventListener:function(type,listener,useCapture){this.__proto__.addEventListener.call(this,type,listener,useCapture);if(this.listenerCounts_[type]===undefined)
this.listenerCounts_[type]=0;this.listenerCounts_[type]++;},removeEventListener:function(type,listener,useCapture){this.__proto__.removeEventListener.call(this,type,listener,useCapture);this.listenerCounts_[type]--;},hasEventListener:function(type){return this.listenerCounts_[type]>0;}};return{EventTarget:EventTarget,EventTargetHelper:EventTargetHelper};});'use strict';tr.exportTo('tr.b',function(){function Event(type,opt_bubbles,opt_preventable){var e=tr.doc.createEvent('Event');e.initEvent(type,!!opt_bubbles,!!opt_preventable);e.__proto__=global.Event.prototype;return e;};Event.prototype={__proto__:global.Event.prototype};function dispatchSimpleEvent(target,type,opt_bubbles,opt_cancelable){var e=new Event(type,opt_bubbles,opt_cancelable);return target.dispatchEvent(e);}
return{Event:Event,dispatchSimpleEvent:dispatchSimpleEvent};});'use strict';tr.exportTo('tr.b',function(){var nextGUID=1;var GUID={allocate:function(){return nextGUID++;},getLastGuid:function(){return nextGUID-1;}};return{GUID:GUID};});'use strict';tr.exportTo('tr.b',function(){function Range(){this.isEmpty_=true;this.min_=undefined;this.max_=undefined;};Range.prototype={__proto__:Object.prototype,reset:function(){this.isEmpty_=true;this.min_=undefined;this.max_=undefined;},get isEmpty(){return this.isEmpty_;},addRange:function(range){if(range.isEmpty)
2015-06-14 13:52:57 -06:00
return;this.addValue(range.min);this.addValue(range.max);},addValue:function(value){if(this.isEmpty_){this.max_=value;this.min_=value;this.isEmpty_=false;return;}
this.max_=Math.max(this.max_,value);this.min_=Math.min(this.min_,value);},set min(min){this.isEmpty_=false;this.min_=min;},get min(){if(this.isEmpty_)
return undefined;return this.min_;},get max(){if(this.isEmpty_)
return undefined;return this.max_;},set max(max){this.isEmpty_=false;this.max_=max;},get range(){if(this.isEmpty_)
return undefined;return this.max_-this.min_;},get center(){return(this.min_+this.max_)*0.5;},equals:function(that){if(this.isEmpty& & that.isEmpty)
return true;if(this.isEmpty!=that.isEmpty)
return false;return this.min===that.min&&this.max===that.max; },containsRange:function(range){if(this.isEmpty||range.isEmpty)
return false;return this.min< =range.min&&this.max>=range.max; },containsExplicitRange:function(min,max){if(this.isEmpty)
return false;return this.min< =min&&this.max>=max; },intersectsRange:function(range){if(this.isEmpty||range.isEmpty)
return false;return!(range.max< this.min | | range . min > this.max);},intersectsExplicitRange:function(min,max){if(this.isEmpty)
return false;return!(max< this.min | | min > this.max);}};Range.fromExplicitRange=function(min,max){var range=new Range();range.min=min;range.max=max;return range;};Range.compareByMinTimes=function(a,b){if(!a.isEmpty& & !b.isEmpty)
return a.min_-b.min_;if(a.isEmpty& & !b.isEmpty)
return-1;if(!a.isEmpty& & b.isEmpty)
return 1;return 0;};return{Range:Range};});'use strict';tr.exportTo('tr.b',function(){function max(a,b){if(a===undefined)
return b;if(b===undefined)
return a;return Math.max(a,b);}
function IntervalTree(beginPositionCb,endPositionCb){this.beginPositionCb_=beginPositionCb;this.endPositionCb_=endPositionCb;this.root_=undefined;this.size_=0;}
IntervalTree.prototype={insert:function(datum){var startPosition=this.beginPositionCb_(datum);var endPosition=this.endPositionCb_(datum);var node=new IntervalTreeNode(datum,startPosition,endPosition);this.size_++;this.root_=this.insertNode_(this.root_,node);this.root_.colour=Colour.BLACK;return datum;},insertNode_:function(root,node){if(root===undefined)
return node;if(root.leftNode& & root.leftNode.isRed& & root.rightNode& & root.rightNode.isRed)
this.flipNodeColour_(root);if(node.key< root.key )
root.leftNode=this.insertNode_(root.leftNode,node);else if(node.key===root.key)
root.merge(node);else
root.rightNode=this.insertNode_(root.rightNode,node);if(root.rightNode& & root.rightNode.isRed& & (root.leftNode===undefined||!root.leftNode.isRed))
root=this.rotateLeft_(root);if(root.leftNode& & root.leftNode.isRed& & root.leftNode.leftNode& & root.leftNode.leftNode.isRed)
root=this.rotateRight_(root);return root;},rotateRight_:function(node){var sibling=node.leftNode;node.leftNode=sibling.rightNode;sibling.rightNode=node;sibling.colour=node.colour;node.colour=Colour.RED;return sibling;},rotateLeft_:function(node){var sibling=node.rightNode;node.rightNode=sibling.leftNode;sibling.leftNode=node;sibling.colour=node.colour;node.colour=Colour.RED;return sibling;},flipNodeColour_:function(node){node.colour=this.flipColour_(node.colour);node.leftNode.colour=this.flipColour_(node.leftNode.colour);node.rightNode.colour=this.flipColour_(node.rightNode.colour);},flipColour_:function(colour){return colour===Colour.RED?Colour.BLACK:Colour.RED;},updateHighValues:function(){this.updateHighValues_(this.root_);},updateHighValues_:function(node){if(node===undefined)
return undefined;node.maxHighLeft=this.updateHighValues_(node.leftNode);node.maxHighRight=this.updateHighValues_(node.rightNode);return max(max(node.maxHighLeft,node.highValue),node.maxHighRight);},validateFindArguments_:function(queryLow,queryHigh){if(queryLow===undefined||queryHigh===undefined)
throw new Error('queryLow and queryHigh must be defined');if((typeof queryLow!=='number')||(typeof queryHigh!=='number'))
throw new Error('queryLow and queryHigh must be numbers');},findIntersection:function(queryLow,queryHigh){this.validateFindArguments_(queryLow,queryHigh);if(this.root_===undefined)
return[];var ret=[];this.root_.appendIntersectionsInto_(ret,queryLow,queryHigh);return ret;},get size(){return this.size_;},get root(){return this.root_;},dump_:function(){if(this.root_===undefined)
return[];return this.root_.dump();}};var Colour={RED:'red',BLACK:'black'};function IntervalTreeNode(datum,lowValue,highValue){this.lowValue_=lowValue;this.data_=[{datum:datum,high:highValue,low:lowValue}];this.colour_=Colour.RED;this.parentNode_=undefined;this.leftNode_=undefined;this.rightNode_=undefined;this.maxHighLeft_=undefined;this.maxHighRight_=undefined;}
IntervalTreeNode.prototype={appendIntersectionsInto_:function(ret,queryLow,queryHigh){if(this.lowValue_>=queryHigh){if(!this.leftNode_)
return;return this.leftNode_.appendIntersectionsInto_(ret,queryLow,queryHigh);}
if(this.maxHighLeft_>queryLow){this.leftNode_.appendIntersectionsInto_(ret,queryLow,queryHigh);}
if(this.highValue>queryLow){for(var i=(this.data.length-1);i>=0;--i){if(this.data[i].high< queryLow )
break;ret.push(this.data[i].datum);}}
if(this.rightNode_){this.rightNode_.appendIntersectionsInto_(ret,queryLow,queryHigh);}},get colour(){return this.colour_;},set colour(colour){this.colour_=colour;},get key(){return this.lowValue_;},get lowValue(){return this.lowValue_;},get highValue(){return this.data_[this.data_.length-1].high;},set leftNode(left){this.leftNode_=left;},get leftNode(){return this.leftNode_;},get hasLeftNode(){return this.leftNode_!==undefined;},set rightNode(right){this.rightNode_=right;},get rightNode(){return this.rightNode_;},get hasRightNode(){return this.rightNode_!==undefined;},set parentNode(parent){this.parentNode_=parent;},get parentNode(){return this.parentNode_;},get isRootNode(){return this.parentNode_===undefined;},set maxHighLeft(high){this.maxHighLeft_=high;},get maxHighLeft(){return this.maxHighLeft_;},set maxHighRight(high){this.maxHighRight_=high;},get maxHighRight(){return this.maxHighRight_;},get data(){return this.data_;},get isRed(){return this.colour_===Colour.RED;},merge:function(node){for(var i=0;i< node.data.length ; i + + )
this.data_.push(node.data[i]);this.data_.sort(function(a,b){return a.high-b.high;});},dump:function(){var ret={};if(this.leftNode_)
ret['left']=this.leftNode_.dump();ret['data']=this.data_.map(function(d){return[d.low,d.high];});if(this.rightNode_)
2015-06-18 08:27:29 -06:00
ret['right']=this.rightNode_.dump();return ret;}};return{IntervalTree:IntervalTree};});'use strict';tr.exportTo('tr.b',function(){function addSingletonGetter(ctor){ctor.getInstance=function(){return ctor.instance_||(ctor.instance_=new ctor());};}
function normalizeException(e){if(typeof(e)=='string'){return{message:e,stack:['< unknown > ']};}
return{message:e.message,stack:e.stack?e.stack:['< unknown > ']};}
function stackTrace(){var stack=new Error().stack+'';stack=stack.split('\n');return stack.slice(2);}
function getUsingPath(path,from_dict){var parts=path.split('.');var cur=from_dict;for(var part;parts.length&&(part=parts.shift()); ){if(!parts.length){return cur[part];}else if(part in cur){cur=cur[part];}else{return undefined;}}
return undefined;}
return{addSingletonGetter:addSingletonGetter,normalizeException:normalizeException,stackTrace:stackTrace,getUsingPath:getUsingPath};});'use strict';tr.exportTo('tr.b',function(){var recordRAFStacks=false;var pendingPreAFs=[];var pendingRAFs=[];var pendingIdleCallbacks=[];var currentRAFDispatchList=undefined;var rafScheduled=false;function scheduleRAF(){if(rafScheduled)
2015-06-14 13:52:57 -06:00
return;rafScheduled=true;if(window.requestAnimationFrame){window.requestAnimationFrame(processRequests);}else{var delta=Date.now()-window.performance.now();window.webkitRequestAnimationFrame(function(domTimeStamp){processRequests(domTimeStamp-delta);});}}
function onAnimationFrameError(e,opt_stack){if(opt_stack)
console.log(opt_stack);if(e.message)
console.error(e.message,e.stack);else
console.error(e);}
function runTask(task,frameBeginTime){try{task.callback.call(task.context,frameBeginTime);}catch(e){tr.b.onAnimationFrameError(e,task.stack);}}
function processRequests(frameBeginTime){var rafCompletionDeadline=frameBeginTime+10;rafScheduled=false;var currentPreAFs=pendingPreAFs;currentRAFDispatchList=pendingRAFs;pendingPreAFs=[];pendingRAFs=[];var hasRAFTasks=currentPreAFs.length||currentRAFDispatchList.length;for(var i=0;i< currentPreAFs.length ; i + + )
runTask(currentPreAFs[i],frameBeginTime);while(currentRAFDispatchList.length>0)
runTask(currentRAFDispatchList.shift(),frameBeginTime);currentRAFDispatchList=undefined;if(!hasRAFTasks){while(pendingIdleCallbacks.length>0){runTask(pendingIdleCallbacks.shift());if(window.performance.now()>=rafCompletionDeadline)
break;}}
if(pendingIdleCallbacks.length>0)
scheduleRAF();}
function getStack_(){if(!recordRAFStacks)
return'';var stackLines=tr.b.stackTrace();stackLines.shift();return stackLines.join('\n');}
function requestPreAnimationFrame(callback,opt_this){pendingPreAFs.push({callback:callback,context:opt_this||window,stack:getStack_()});scheduleRAF();}
function requestAnimationFrameInThisFrameIfPossible(callback,opt_this){if(!currentRAFDispatchList){requestAnimationFrame(callback,opt_this);return;}
currentRAFDispatchList.push({callback:callback,context:opt_this||window,stack:getStack_()});return;}
function requestAnimationFrame(callback,opt_this){pendingRAFs.push({callback:callback,context:opt_this||window,stack:getStack_()});scheduleRAF();}
function requestIdleCallback(callback,opt_this){pendingIdleCallbacks.push({callback:callback,context:opt_this||window,stack:getStack_()});scheduleRAF();}
function forcePendingRAFTasksToRun(frameBeginTime){if(!rafScheduled)
return;processRequests(frameBeginTime);}
return{onAnimationFrameError:onAnimationFrameError,requestPreAnimationFrame:requestPreAnimationFrame,requestAnimationFrame:requestAnimationFrame,requestAnimationFrameInThisFrameIfPossible:requestAnimationFrameInThisFrameIfPossible,requestIdleCallback:requestIdleCallback,forcePendingRAFTasksToRun:forcePendingRAFTasksToRun};});'use strict';tr.exportTo('tr.b',function(){function Task(runCb,thisArg){if(runCb!==undefined& & thisArg===undefined)
throw new Error('Almost certainly, you meant to pass a thisArg.');this.runCb_=runCb;this.thisArg_=thisArg;this.afterTask_=undefined;this.subTasks_=[];}
Task.prototype={subTask:function(cb,thisArg){if(cb instanceof Task)
this.subTasks_.push(cb);else
this.subTasks_.push(new Task(cb,thisArg));return this.subTasks_[this.subTasks_.length-1];},run:function(){if(this.runCb_!==undefined)
this.runCb_.call(this.thisArg_,this);var subTasks=this.subTasks_;this.subTasks_=undefined;if(!subTasks.length)
return this.afterTask_;for(var i=1;i< subTasks.length ; i + + )
subTasks[i-1].afterTask_=subTasks[i];subTasks[subTasks.length-1].afterTask_=this.afterTask_;return subTasks[0];},after:function(cb,thisArg){if(this.afterTask_)
throw new Error('Has an after task already');if(cb instanceof Task)
this.afterTask_=cb;else
this.afterTask_=new Task(cb,thisArg);return this.afterTask_;},enqueue:function(cb,thisArg){var lastTask=this;while(lastTask.afterTask_)
lastTask=lastTask.afterTask_;return lastTask.after(cb,thisArg);}};Task.RunSynchronously=function(task){var curTask=task;while(curTask)
curTask=curTask.run();}
Task.RunWhenIdle=function(task){return new Promise(function(resolve,reject){var curTask=task;function runAnother(){try{curTask=curTask.run();}catch(e){reject(e);console.error(e.stack);return;}
if(curTask){tr.b.requestIdleCallback(runAnother);return;}
resolve();}
tr.b.requestIdleCallback(runAnother);});}
2015-06-18 08:27:29 -06:00
return{Task:Task};});'use strict';tr.exportTo('tr.b.units',function(){var ms={suffix:'ms',roundedLess:function(a,b){return Math.round(a*1000)< Math.round ( b * 1000 ) ; } , format:function ( ts ) { var tsRounded = Math.round(ts*1000.0)/1000.0;var n = new Number ( tsRounded ) ; return n . toLocaleString ( undefined , { minimumFractionDigits:3 } ) + ' ms ' ; } } ; var ns = {suffix:'ns',roundedLess:function(a,b){return Math . round ( a * 1000000 ) < Math . round ( b * 1000000 ) ; } , format:function ( ts ) { var tsRounded = Math.round(ts*1000000.0);var n = new Number ( tsRounded ) ; return n . toLocaleString ( undefined , { maximumFractionDigits:0 } ) + ' ns ' ; } } ; var Time = {supportedUnits:{ms:ms,ns:ns},reset:function(){this.currentDisplayUnit=ms;},currentDisplayUnit_:ms,get currentDisplayUnit ( ) { return this . currentDisplayUnit_ ; } , set currentDisplayUnit ( value ) { if ( this . currentDisplayUnit_ = =value)
return;this.currentDisplayUnit_=value;this.dispatchEvent(new Event('display-unit-changed'));},timestampFromUs:function(us){return us/1000;},maybeTimestampFromUs:function(us){return us===undefined?undefined:us/1000;}};tr.b.EventTarget.decorate(Time);return{Time:Time};});'use strict';tr.exportTo('tr.b',function(){function dispatchPropertyChange(target,propertyName,newValue,oldValue,opt_bubbles,opt_cancelable){var e=new tr.b.Event(propertyName+'Change',opt_bubbles,opt_cancelable);e.propertyName=propertyName;e.newValue=newValue;e.oldValue=oldValue;var error;e.throwError=function(err){error=err;};target.dispatchEvent(e);if(error)
throw error;}
function setPropertyAndDispatchChange(obj,propertyName,newValue){var privateName=propertyName+'_';var oldValue=obj[propertyName];obj[privateName]=newValue;if(oldValue!==newValue)
tr.b.dispatchPropertyChange(obj,propertyName,newValue,oldValue,true,false);}
function getAttributeName(jsName){return jsName.replace(/([A-Z])/g,'-$1').toLowerCase();}
function getPrivateName(name){return name+'_tr_';}
var PropertyKind={JS:'js',ATTR:'attr',BOOL_ATTR:'boolAttr'};function getGetter(name,kind){switch(kind){case PropertyKind.JS:var privateName=getPrivateName(name);return function(){return this[privateName];};case PropertyKind.ATTR:var attributeName=getAttributeName(name);return function(){return this.getAttribute(attributeName);};case PropertyKind.BOOL_ATTR:var attributeName=getAttributeName(name);return function(){return this.hasAttribute(attributeName);};}}
function getSetter(name,kind,opt_setHook,opt_bubbles,opt_cancelable){switch(kind){case PropertyKind.JS:var privateName=getPrivateName(name);return function(value){var oldValue=this[privateName];if(value!==oldValue){this[privateName]=value;if(opt_setHook)
opt_setHook.call(this,value,oldValue);dispatchPropertyChange(this,name,value,oldValue,opt_bubbles,opt_cancelable);}};case PropertyKind.ATTR:var attributeName=getAttributeName(name);return function(value){var oldValue=this.getAttribute(attributeName);if(value!==oldValue){if(value==undefined)
this.removeAttribute(attributeName);else
this.setAttribute(attributeName,value);if(opt_setHook)
opt_setHook.call(this,value,oldValue);dispatchPropertyChange(this,name,value,oldValue,opt_bubbles,opt_cancelable);}};case PropertyKind.BOOL_ATTR:var attributeName=getAttributeName(name);return function(value){var oldValue=(this.getAttribute(attributeName)===name);if(value!==oldValue){if(value)
this.setAttribute(attributeName,name);else
this.removeAttribute(attributeName);if(opt_setHook)
opt_setHook.call(this,value,oldValue);dispatchPropertyChange(this,name,value,oldValue,opt_bubbles,opt_cancelable);}};}}
function defineProperty(obj,name,opt_kind,opt_setHook,opt_bubbles,opt_cancelable){console.error("Don't use tr.b.defineProperty");if(typeof obj=='function')
obj=obj.prototype;var kind=opt_kind||PropertyKind.JS;if(!obj.__lookupGetter__(name))
obj.__defineGetter__(name,getGetter(name,kind));if(!obj.__lookupSetter__(name))
obj.__defineSetter__(name,getSetter(name,kind,opt_setHook,opt_bubbles,opt_cancelable));}
return{PropertyKind:PropertyKind,defineProperty:defineProperty,dispatchPropertyChange:dispatchPropertyChange,setPropertyAndDispatchChange:setPropertyAndDispatchChange};});'use strict';tr.exportTo('tr.ui.b',function(){function decorate(source,constr){var elements;if(typeof source=='string')
elements=tr.doc.querySelectorAll(source);else
elements=[source];for(var i=0,el;el=elements[i];i++){if(!(el instanceof constr))
constr.decorate(el);}}
function define(className,opt_parentConstructor,opt_tagNS){if(typeof className=='function'){throw new Error('Passing functions as className is deprecated. Please '+'use (className, opt_parentConstructor) to subclass');}
var className=className.toLowerCase();if(opt_parentConstructor& & !opt_parentConstructor.tagName)
throw new Error('opt_parentConstructor was not '+'created by tr.ui.b.define');var tagName=className;var tagNS=undefined;if(opt_parentConstructor){if(opt_tagNS)
throw new Error('Must not specify tagNS if parentConstructor is given');var parent=opt_parentConstructor;while(parent&&parent.tagName){tagName=parent.tagName; tagNS=parent.tagNS;parent=parent.parentConstructor;}}else{tagNS=opt_tagNS;}
function f(){if(opt_parentConstructor& & f.prototype.__proto__!=opt_parentConstructor.prototype){throw new Error(className+' prototye\'s __proto__ field is messed up. '+'It MUST be the prototype of '+opt_parentConstructor.tagName);}
var el;if(tagNS===undefined)
el=tr.doc.createElement(tagName);else
el=tr.doc.createElementNS(tagNS,tagName);f.decorate.call(this,el,arguments);return el;}
f.decorate=function(el){el.__proto__=f.prototype;el.decorate.apply(el,arguments[1]);el.constructor=f;};f.className=className;f.tagName=tagName;f.tagNS=tagNS;f.parentConstructor=(opt_parentConstructor?opt_parentConstructor:undefined);f.toString=function(){if(!f.parentConstructor)
return f.tagName;return f.parentConstructor.toString()+'::'+f.className;};return f;}
function elementIsChildOf(el,potentialParent){if(el==potentialParent)
return false;var cur=el;while(cur.parentNode){if(cur==potentialParent)
return true;cur=cur.parentNode;}
return false;};return{decorate:decorate,define:define,elementIsChildOf:elementIsChildOf};});(function(){"use strict";var e={};typeof exports=="undefined"?typeof define=="function"& & typeof define.amd=="object"& & define.amd?(e.exports={},define(function(){return e.exports})):e.exports=window:e.exports=exports,function(e){if(!t)var t=1e-6;if(!n)var n=typeof Float32Array!="undefined"?Float32Array:Array;var r={};r.setMatrixArrayType=function(e){n=e},typeof e!="undefined"&&(e.glMatrix=r); var i={};i.create=function(){var e=new n(2);return e[0]=0,e[1]=0,e},i.clone=function(e){var t=new n(2);return t[0]=e[0],t[1]=e[1],t},i.fromValues=function(e,t){var r=new n(2);return r[0]=e,r[1]=t,r},i.copy=function(e,t){return e[0]=t[0],e[1]=t[1],e},i.set=function(e,t,n){return e[0]=t,e[1]=n,e},i.add=function(e,t,n){return e[0]=t[0]+n[0],e[1]=t[1]+n[1],e},i.subtract=function(e,t,n){return e[0]=t[0]-n[0],e[1]=t[1]-n[1],e},i.sub=i.subtract,i.multiply=function(e,t,n){return e[0]=t[0]*n[0],e[1]=t[1]*n[1],e},i.mul=i.multiply,i.divide=function(e,t,n){return e[0]=t[0]/n[0],e[1]=t[1]/n[1],e},i.div=i.divide,i.min=function(e,t,n){return e[0]=Math.min(t[0],n[0]),e[1]=Math.min(t[1],n[1]),e},i.max=function(e,t,n){return e[0]=Math.max(t[0],n[0]),e[1]=Math.max(t[1],n[1]),e},i.scale=function(e,t,n){return e[0]=t[0]*n,e[1]=t[1]*n,e},i.distance=function(e,t){var n=t[0]-e[0],r=t[1]-e[1];return Math.sqrt(n*n+r*r)},i.dist=i.distance,i.squaredDistance=function(e,t){var n=t[0]-e[0],r=t[1]-e[1];return n*n+r*r},i.sqrDist=i.squaredDistance,i.length=function(e){var t=e[0],n=e[1];return Math.sqrt(t*t+n*n)},i.len=i.length,i.squaredLength=function(e){var t=e[0],n=e[1];return t*t+n*n},i.sqrLen=i.squaredLength,i.negate=function(e,t){return e[0]=-t[0],e[1]=-t[1],e},i.normalize=function(e,t){var n=t[0],r=t[1],i=n*n+r*r;return i>0& & (i=1/Math.sqrt(i),e[0]=t[0]*i,e[1]=t[1]*i),e},i.dot=function(e,t){return e[0]*t[0]+e[1]*t[1]},i.cross=function(e,t,n){var r=t[0]*n[1]-t[1]*n[0];return e[0]=e[1]=0,e[2]=r,e},i.lerp=function(e,t,n,r){var i=t[0],s=t[1];return e[0]=i+r*(n[0]-i),e[1]=s+r*(n[1]-s),e},i.transformMat2=function(e,t,n){var r=t[0],i=t[1];return e[0]=n[0]*r+n[2]*i,e[1]=n[1]*r+n[3]*i,e},i.transformMat2d=function(e,t,n){var r=t[0],i=t[1];return e[0]=n[0]*r+n[2]*i+n[4],e[1]=n[1]*r+n[3]*i+n[5],e},i.transformMat3=function(e,t,n){var r=t[0],i=t[1];return e[0]=n[0]*r+n[3]*i+n[6],e[1]=n[1]*r+n[4]*i+n[7],e},i.transformMat4=function(e,t,n){var r=t[0],i=t[1];return e[0]=n[0]*r+n[4]*i+n[12],e[1]=n[1]*r+n[5]*i+n[13],e},i.forEach=function(){var e=i.create();return function(t,n,r,i,s,o){var u,a;n||(n=2),r||(r=0),i?a=Math.min(i*n+r,t.length):a=t.length;for(u=r;u< a ; u + = n ) e [ 0 ] = t [ u ] , e [ 1 ] = t [ u + 1 ] , s ( e , e , o ) , t [ u ] = e [ 0 ] , t [ u + 1 ] = e [ 1 ] ; return t } } ( ) , i . str = function(e){return"vec2("+e[0]+", " + e [ 1 ] + " ) " } , typeof e ! = " undefined " & & ( e . vec2 = i);var s = {};s.create=function(){var e = new n ( 3 ) ; return e [ 0 ] = 0 , e [ 1 ] = 0 , e [ 2 ] = 0 , e } , s . clone = function(e){var t = new n ( 3 ) ; return t [ 0 ] = e [ 0 ] , t [ 1 ] = e [ 1 ] , t [ 2 ] = e [ 2 ] , t } , s . fromValues = function(e,t,r){var i = new n ( 3 ) ; return i [ 0 ] = e , i [ 1 ] = t , i [ 2 ] = r , i } , s . copy = function(e,t){return e [ 0 ] = t [ 0 ] , e [ 1 ] = t [ 1 ] , e [ 2 ] = t [ 2 ] , e } , s . set = function(e,t,n,r){return e [ 0 ] = t , e [ 1 ] = n , e [ 2 ] = r , e } , s . add = function(e,t,n){return e [ 0 ] = t [ 0 ] + n [ 0 ] , e [ 1 ] = t [ 1 ] + n [ 1 ] , e [ 2 ] = t [ 2 ] + n [ 2 ] , e } , s . subtract = function(e,t,n){return e [ 0 ] = t [ 0 ] -n [ 0 ] , e [ 1 ] = t [ 1 ] -n [ 1 ] , e [ 2 ] = t [ 2 ] -n [ 2 ] , e } , s . sub = s.subtract,s.multiply=function(e,t,n){return e [ 0 ] = t [ 0 ] * n [ 0 ] , e [ 1 ] = t [ 1 ] * n [ 1 ] , e [ 2 ] = t [ 2 ] * n [ 2 ] , e } , s . mul = s.multiply,s.divide=function(e,t,n){return e [ 0 ] = t [ 0 ] / n [ 0 ] , e [ 1 ] = t [ 1 ] / n [ 1 ] , e [ 2 ] = t [ 2 ] / n [ 2 ] , e } , s . div = s.divide,s.min=function(e,t,n){return e [ 0 ] = Math . min ( t [ 0 ] , n [ 0 ] ) , e [ 1 ] = Math . min ( t [ 1 ] , n [ 1 ] ) , e [ 2 ] = Math . min ( t [ 2 ] , n [ 2 ] ) , e } , s . max = function(e,t,n){return e [ 0 ] = Math . max ( t [ 0 ] , n [ 0 ] ) , e [ 1 ] = Math . max ( t [ 1 ] , n [ 1 ] ) , e [ 2 ] = Math . max ( t [ 2 ] , n [ 2 ] ) , e } , s . scale = function(e,t,n){return e [ 0 ] = t [ 0 ] * n , e [ 1 ] = t [ 1 ] * n , e [ 2 ] = t [ 2 ] * n , e } , s . distance = function(e,t){var n = t[0]-e[0],r=t[1]-e[1],i=t[2]-e[2];return Math . sqrt ( n * n + r * r + i * i ) } , s . dist = s.distance,s.squaredDistance=function(e,t){var n = t[0]-e[0],r=t[1]-e[1],i=t[2]-e[2];return n * n + r * r + i * i } , s . sqrDist = s.squaredDistance,s.length=function(e){var t = e[0],n=e[1],r=e[2];return Math . sqrt ( t * t + n * n + r
function lerp(percentage,lo,hi){var range=hi-lo;return lo+percentage*range;}
function normalize(value,lo,hi){return(value-lo)/(hi-lo);}
function deg2rad(deg){return(Math.PI*deg)/180.0;}
var tmp_vec2=vec2.create();var tmp_vec2b=vec2.create();var tmp_vec4=vec4.create();var tmp_mat2d=mat2d.create();vec2.createFromArray=function(arr){if(arr.length!=2)
throw new Error('Should be length 2');var v=vec2.create();vec2.set(v,arr[0],arr[1]);return v;};vec2.createXY=function(x,y){var v=vec2.create();vec2.set(v,x,y);return v;};vec2.toString=function(a){return'['+a[0]+', '+a[1]+']';};vec2.addTwoScaledUnitVectors=function(out,u1,scale1,u2,scale2){vec2.scale(tmp_vec2,u1,scale1);vec2.scale(tmp_vec2b,u2,scale2);vec2.add(out,tmp_vec2,tmp_vec2b);};vec2.interpolatePiecewiseFunction=function(points,x){if(x< points [ 0 ] [ 0 ] )
return points[0][1];for(var i=1;i< points.length ; + + i ) { if ( x < points [ i ] [ 0 ] ) { var percent = normalize(x,points[i-1][0],points[i][0]);return lerp ( percent , points [ i-1 ] [ 1 ] , points [ i ] [ 1 ] ) ; } }
return points[points.length-1][1];};vec3.createXYZ=function(x,y,z){var v=vec3.create();vec3.set(v,x,y,z);return v;};vec3.toString=function(a){return'vec3('+a[0]+', '+a[1]+', '+a[2]+')';}
mat2d.translateXY=function(out,x,y){vec2.set(tmp_vec2,x,y);mat2d.translate(out,out,tmp_vec2);}
mat2d.scaleXY=function(out,x,y){vec2.set(tmp_vec2,x,y);mat2d.scale(out,out,tmp_vec2);}
vec4.unitize=function(out,a){out[0]=a[0]/a[3];out[1]=a[1]/a[3];out[2]=a[2]/a[3];out[3]=1;return out;}
vec2.copyFromVec4=function(out,a){vec4.unitize(tmp_vec4,a);vec2.copy(out,tmp_vec4);}
return{clamp:clamp,lerp:lerp,normalize:normalize,deg2rad:deg2rad};});'use strict';tr.exportTo('tr.b',function(){function Rect(){this.x=0;this.y=0;this.width=0;this.height=0;};Rect.fromXYWH=function(x,y,w,h){var rect=new Rect();rect.x=x;rect.y=y;rect.width=w;rect.height=h;return rect;}
Rect.fromArray=function(ary){if(ary.length!=4)
throw new Error('ary.length must be 4');var rect=new Rect();rect.x=ary[0];rect.y=ary[1];rect.width=ary[2];rect.height=ary[3];return rect;}
Rect.prototype={__proto__:Object.prototype,get left(){return this.x;},get top(){return this.y;},get right(){return this.x+this.width;},get bottom(){return this.y+this.height;},toString:function(){return'Rect('+this.x+', '+this.y+', '+
this.width+', '+this.height+')';},toArray:function(){return[this.x,this.y,this.width,this.height];},clone:function(){var rect=new Rect();rect.x=this.x;rect.y=this.y;rect.width=this.width;rect.height=this.height;return rect;},enlarge:function(pad){var rect=new Rect();this.enlargeFast(rect,pad);return rect;},enlargeFast:function(out,pad){out.x=this.x-pad;out.y=this.y-pad;out.width=this.width+2*pad;out.height=this.height+2*pad;return out;},size:function(){return{width:this.width,height:this.height};},scale:function(s){var rect=new Rect();this.scaleFast(rect,s);return rect;},scaleSize:function(s){return Rect.fromXYWH(this.x,this.y,this.width*s,this.height*s);},scaleFast:function(out,s){out.x=this.x*s;out.y=this.y*s;out.width=this.width*s;out.height=this.height*s;return out;},translate:function(v){var rect=new Rect();this.translateFast(rect,v);return rect;},translateFast:function(out,v){out.x=this.x+v[0];out.y=this.x+v[1];out.width=this.width;out.height=this.height;return out;},asUVRectInside:function(containingRect){var rect=new Rect();rect.x=(this.x-containingRect.x)/containingRect.width;rect.y=(this.y-containingRect.y)/containingRect.height;rect.width=this.width/containingRect.width;rect.height=this.height/containingRect.height;return rect;},intersects:function(that){var ok=true;ok&=this.x<that.right; ok&=this.right>that.x; ok&=this.y<that.bottom; ok&=this.bottom>that.y; return ok;},equalTo:function(rect){return rect&&(this.x===rect.x)&&(this.y===rect.y)&&(this.width===rect.width)&&(this.height===rect.height); }};return{Rect:Rect};});'use strict';tr.exportTo('tr.ui.b',function(){function instantiateTemplate(selector,doc){doc=doc||document;var el=doc.querySelector(selector);if(!el)
throw new Error('Element not found');return el.createInstance();}
function windowRectForElement(element){var position=[element.offsetLeft,element.offsetTop];var size=[element.offsetWidth,element.offsetHeight];var node=element.offsetParent;while(node){position[0]+=node.offsetLeft;position[1]+=node.offsetTop;node=node.offsetParent;}
return tr.b.Rect.fromXYWH(position[0],position[1],size[0],size[1]);}
function scrollIntoViewIfNeeded(el){var pr=el.parentElement.getBoundingClientRect();var cr=el.getBoundingClientRect();if(cr.top< pr.top ) { el . scrollIntoView ( true ) ; } else if ( cr . bottom > pr.bottom){el.scrollIntoView(false);}}
return{instantiateTemplate:instantiateTemplate,windowRectForElement:windowRectForElement,scrollIntoViewIfNeeded:scrollIntoViewIfNeeded};});'use strict';tr.exportTo('tr.ui.b',function(){var THIS_DOC=document.currentScript.ownerDocument;var Overlay=tr.ui.b.define('overlay');Overlay.prototype={__proto__:HTMLDivElement.prototype,decorate:function(){this.classList.add('overlay');this.parentEl_=this.ownerDocument.body;this.visible_=false;this.userCanClose_=true;this.onKeyDown_=this.onKeyDown_.bind(this);this.onClick_=this.onClick_.bind(this);this.onFocusIn_=this.onFocusIn_.bind(this);this.onDocumentClick_=this.onDocumentClick_.bind(this);this.onClose_=this.onClose_.bind(this);this.addEventListener('visibleChange',tr.ui.b.Overlay.prototype.onVisibleChange_.bind(this),true);var createShadowRoot=this.createShadowRoot||this.webkitCreateShadowRoot;this.shadow_=createShadowRoot.call(this);this.shadow_.appendChild(tr.ui.b.instantiateTemplate('#overlay-template',THIS_DOC));this.closeBtn_=this.shadow_.querySelector('close-button');this.closeBtn_.addEventListener('click',this.onClose_);this.shadow_.querySelector('overlay-frame').addEventListener('click',this.onClick_);this.observer_=new WebKitMutationObserver(this.didButtonBarMutate_.bind(this));this.observer_.observe(this.shadow_.querySelector('button-bar'),{childList:true});Object.defineProperty(this,'title',{get:function(){return this.shadow_.querySelector('title').textContent;},set:function(title){this.shadow_.querySelector('title').textContent=title;}});},set userCanClose(userCanClose){this.userCanClose_=userCanClose;this.closeBtn_.style.display=userCanClose?'block':'none';},get buttons(){return this.shadow_.querySelector('button-bar');},get visible(){return this.visible_;},set visible(newValue){if(this.visible_===newValue)
return;tr.b.setPropertyAndDispatchChange(this,'visible',newValue);},onVisibleChange_:function(){this.visible_?this.show_():this.hide_();},show_:function(){this.parentEl_.appendChild(this);if(this.userCanClose_){this.addEventListener('keydown',this.onKeyDown_.bind(this));this.addEventListener('click',this.onDocumentClick_.bind(this));}
this.parentEl_.addEventListener('focusin',this.onFocusIn_);this.tabIndex=0;var focusEl=undefined;var elList=this.querySelectorAll('button, input, list, select, a');if(elList.length>0){if(elList[0]===this.closeBtn_){if(elList.length>1)
focusEl=elList[1];}else{focusEl=elList[0];}}
if(focusEl===undefined)
focusEl=this;focusEl.focus();},hide_:function(){this.parentEl_.removeChild(this);this.parentEl_.removeEventListener('focusin',this.onFocusIn_);if(this.closeBtn_)
this.closeBtn_.removeEventListener(this.onClose_);document.removeEventListener('keydown',this.onKeyDown_);document.removeEventListener('click',this.onDocumentClick_);},onClose_:function(e){this.visible=false;if((e.type!='keydown')||(e.type==='keydown'& & e.keyCode===27))
e.stopPropagation();e.preventDefault();tr.b.dispatchSimpleEvent(this,'closeclick');},onFocusIn_:function(e){if(e.target===this)
return;window.setTimeout(function(){this.focus();},0);e.preventDefault();e.stopPropagation();},didButtonBarMutate_:function(e){var hasButtons=this.buttons.children.length>0;if(hasButtons)
this.shadow_.querySelector('button-bar').style.display=undefined;else
this.shadow_.querySelector('button-bar').style.display='none';},onKeyDown_:function(e){if(e.keyCode===9&&e.shiftKey&&e.target===this){e.preventDefault(); return;}
if(e.keyCode!==27)
return;this.onClose_(e);},onClick_:function(e){e.stopPropagation();},onDocumentClick_:function(e){if(!this.userCanClose_)
return;this.onClose_(e);}};Overlay.showError=function(msg,opt_err){var o=new Overlay();o.title='Error';o.textContent=msg;if(opt_err){var e=tr.b.normalizeException(opt_err);var stackDiv=document.createElement('pre');stackDiv.textContent=e.stack;stackDiv.style.paddingLeft='8px';stackDiv.style.margin=0;o.appendChild(stackDiv);}
var b=document.createElement('button');b.textContent='OK';b.addEventListener('click',function(){o.visible=false;});o.buttons.appendChild(b);o.visible=true;return o;}
return{Overlay:Overlay};});'use strict';tr.exportTo('tr.c',function(){function matchLower(value,pattern){return value.toLowerCase().indexOf(pattern)!==-1;}
2015-06-14 13:52:57 -06:00
function Filter(){}
Filter.prototype={__proto__:Object.prototype,matchCounter:function(counter){return true;},matchCpu:function(cpu){return true;},matchProcess:function(process){return true;},matchSlice:function(slice){return true;},matchThread:function(thread){return true;}};function TitleOrCategoryFilter(text){Filter.call(this);this.text_=text.toLowerCase();if(!text.length)
throw new Error('Filter text is empty.');}
TitleOrCategoryFilter.prototype={__proto__:Filter.prototype,matchSlice:function(slice){if(slice.title===undefined& & slice.category===undefined)
return false;return matchLower(slice.title,this.text_)||(!!slice.category&&matchLower(slice.category,this.text_)); }};function ExactTitleFilter(text){Filter.call(this);this.text_=text;if(!text.length)
throw new Error('Filter text is empty.');}
ExactTitleFilter.prototype={__proto__:Filter.prototype,matchSlice:function(slice){return slice.title===this.text_;}};return{Filter:Filter,TitleOrCategoryFilter:TitleOrCategoryFilter,ExactTitleFilter:ExactTitleFilter};});'use strict';tr.exportTo('tr.b',function(){function RegisteredTypeInfo(constructor,metadata){this.constructor=constructor;this.metadata=metadata;};var BASIC_REGISTRY_MODE='BASIC_REGISTRY_MODE';var TYPE_BASED_REGISTRY_MODE='TYPE_BASED_REGISTRY_MODE';var ALL_MODES={BASIC_REGISTRY_MODE:true,TYPE_BASED_REGISTRY_MODE:true};function ExtensionRegistryOptions(mode){if(mode===undefined)
throw new Error('Mode is required');if(!ALL_MODES[mode])
throw new Error('Not a mode.');this.mode_=mode;this.defaultMetadata_={};this.defaultConstructor_=undefined;this.mandatoryBaseClass_=undefined;this.defaultTypeInfo_=undefined;this.frozen_=false;}
ExtensionRegistryOptions.prototype={freeze:function(){if(this.frozen_)
throw new Error('Frozen');this.frozen_=true;},get mode(){return this.mode_;},get defaultMetadata(){return this.defaultMetadata_;},set defaultMetadata(defaultMetadata){if(this.frozen_)
throw new Error('Frozen');this.defaultMetadata_=defaultMetadata;this.defaultTypeInfo_=undefined;},get defaultConstructor(){return this.defaultConstructor_;},set defaultConstructor(defaultConstructor){if(this.frozen_)
throw new Error('Frozen');this.defaultConstructor_=defaultConstructor;this.defaultTypeInfo_=undefined;},get defaultTypeInfo(){if(this.defaultTypeInfo_===undefined& & this.defaultConstructor_){this.defaultTypeInfo_=new RegisteredTypeInfo(this.defaultConstructor,this.defaultMetadata);}
return this.defaultTypeInfo_;},validateConstructor:function(constructor){if(!this.mandatoryBaseClass)
return;var curProto=constructor.prototype.__proto__;var ok=false;while(curProto){if(curProto===this.mandatoryBaseClass.prototype){ok=true;break;}
curProto=curProto.__proto__;}
if(!ok)
throw new Error(constructor+'must be subclass of '+registry);}};return{BASIC_REGISTRY_MODE:BASIC_REGISTRY_MODE,TYPE_BASED_REGISTRY_MODE:TYPE_BASED_REGISTRY_MODE,ExtensionRegistryOptions:ExtensionRegistryOptions,RegisteredTypeInfo:RegisteredTypeInfo};});'use strict';tr.exportTo('tr.b',function(){var RegisteredTypeInfo=tr.b.RegisteredTypeInfo;var ExtensionRegistryOptions=tr.b.ExtensionRegistryOptions;function decorateBasicExtensionRegistry(registry,extensionRegistryOptions){var savedStateStack=[];registry.registeredTypeInfos_=[];registry.register=function(constructor,opt_metadata){if(registry.findIndexOfRegisteredConstructor(constructor)!==undefined)
throw new Error('Handler already registered for '+constructor);extensionRegistryOptions.validateConstructor(constructor);var metadata={};for(var k in extensionRegistryOptions.defaultMetadata)
metadata[k]=extensionRegistryOptions.defaultMetadata[k];if(opt_metadata){for(var k in opt_metadata)
metadata[k]=opt_metadata[k];}
2015-06-18 08:27:29 -06:00
var typeInfo=new RegisteredTypeInfo(constructor,metadata);var e=new tr.b.Event('will-register');e.typeInfo=typeInfo;registry.dispatchEvent(e);registry.registeredTypeInfos_.push(typeInfo);e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.pushCleanStateBeforeTest=function(){savedStateStack.push(registry.registeredTypeInfos_);registry.registeredTypeInfos_=[];var e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.popCleanStateAfterTest=function(){registry.registeredTypeInfos_=savedStateStack[0];savedStateStack.splice(0,1);var e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.findIndexOfRegisteredConstructor=function(constructor){for(var i=0;i< registry.registeredTypeInfos_.length ; i + + )
2015-06-14 13:52:57 -06:00
if(registry.registeredTypeInfos_[i].constructor==constructor)
return i;return undefined;};registry.unregister=function(constructor){var foundIndex=registry.findIndexOfRegisteredConstructor(constructor);if(foundIndex===undefined)
2015-06-18 08:27:29 -06:00
throw new Error(constructor+' not registered');registry.registeredTypeInfos_.splice(foundIndex,1);var e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.getAllRegisteredTypeInfos=function(){return registry.registeredTypeInfos_;};registry.findTypeInfo=function(constructor){var foundIndex=this.findIndexOfRegisteredConstructor(constructor);if(foundIndex!==undefined)
2015-06-14 13:52:57 -06:00
return this.registeredTypeInfos_[foundIndex];return undefined;};registry.findTypeInfoMatching=function(predicate,opt_this){opt_this=opt_this?opt_this:undefined;for(var i=0;i< registry.registeredTypeInfos_.length ; + + i ) { var typeInfo = registry.registeredTypeInfos_[i];if(predicate.call(opt_this,typeInfo))
return typeInfo;}
return extensionRegistryOptions.defaultTypeInfo;};}
return{_decorateBasicExtensionRegistry:decorateBasicExtensionRegistry};});'use strict';tr.exportTo('tr.b',function(){var categoryPartsFor={};function getCategoryParts(category){var parts=categoryPartsFor[category];if(parts!==undefined)
return parts;parts=category.split(',');categoryPartsFor[category]=parts;return parts;}
return{getCategoryParts:getCategoryParts};});'use strict';tr.exportTo('tr.b',function(){var getCategoryParts=tr.b.getCategoryParts;var RegisteredTypeInfo=tr.b.RegisteredTypeInfo;var ExtensionRegistryOptions=tr.b.ExtensionRegistryOptions;function decorateTypeBasedExtensionRegistry(registry,extensionRegistryOptions){var savedStateStack=[];registry.registeredTypeInfos_=[];registry.categoryPartToTypeInfoMap_={};registry.typeNameToTypeInfoMap_={};registry.register=function(constructor,metadata){extensionRegistryOptions.validateConstructor(constructor);var typeInfo=new RegisteredTypeInfo(constructor,metadata||extensionRegistryOptions.defaultMetadata);typeInfo.typeNames=[];typeInfo.categoryParts=[];if(metadata& & metadata.typeName)
typeInfo.typeNames.push(metadata.typeName);if(metadata&&metadata.typeNames){typeInfo.typeNames.push.apply(typeInfo.typeNames,metadata.typeNames); }
if(metadata&&metadata.categoryParts){typeInfo.categoryParts.push.apply(typeInfo.categoryParts,metadata.categoryParts); }
if(typeInfo.typeNames.length===0& & typeInfo.categoryParts.length===0)
throw new Error('typeName or typeNames must be provided');typeInfo.typeNames.forEach(function(typeName){if(registry.typeNameToTypeInfoMap_[typeName])
2015-06-18 08:27:29 -06:00
throw new Error('typeName '+typeName+' already registered');});typeInfo.categoryParts.forEach(function(categoryPart){if(registry.categoryPartToTypeInfoMap_[categoryPart]){throw new Error('categoryPart '+categoryPart+' already registered');}});var e=new tr.b.Event('will-register');e.typeInfo=typeInfo;registry.dispatchEvent(e);typeInfo.typeNames.forEach(function(typeName){registry.typeNameToTypeInfoMap_[typeName]=typeInfo;});typeInfo.categoryParts.forEach(function(categoryPart){registry.categoryPartToTypeInfoMap_[categoryPart]=typeInfo;});registry.registeredTypeInfos_.push(typeInfo);var e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.pushCleanStateBeforeTest=function(){savedStateStack.push({registeredTypeInfos:registry.registeredTypeInfos_,typeNameToTypeInfoMap:registry.typeNameToTypeInfoMap_,categoryPartToTypeInfoMap:registry.categoryPartToTypeInfoMap_});registry.registeredTypeInfos_=[];registry.typeNameToTypeInfoMap_={};registry.categoryPartToTypeInfoMap_={};var e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.popCleanStateAfterTest=function(){var state=savedStateStack[0];savedStateStack.splice(0,1);registry.registeredTypeInfos_=state.registeredTypeInfos;registry.typeNameToTypeInfoMap_=state.typeNameToTypeInfoMap;registry.categoryPartToTypeInfoMap_=state.categoryPartToTypeInfoMap;var e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.unregister=function(constructor){var typeInfoIndex=-1;for(var i=0;i< registry.registeredTypeInfos_.length ; i + + ) { if ( registry . registeredTypeInfos_ [ i ] . constructor = =constructor){typeInfoIndex=i;break;}}
2015-06-14 13:52:57 -06:00
if(typeInfoIndex===-1)
2015-06-18 08:27:29 -06:00
throw new Error(constructor+' not registered');var typeInfo=registry.registeredTypeInfos_[typeInfoIndex];registry.registeredTypeInfos_.splice(typeInfoIndex,1);typeInfo.typeNames.forEach(function(typeName){delete registry.typeNameToTypeInfoMap_[typeName];});typeInfo.categoryParts.forEach(function(categoryPart){delete registry.categoryPartToTypeInfoMap_[categoryPart];});var e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.getTypeInfo=function(category,typeName){if(category){var categoryParts=getCategoryParts(category);for(var i=0;i< categoryParts.length ; i + + ) { var categoryPart = categoryParts[i];if(registry.categoryPartToTypeInfoMap_[categoryPart])
2015-06-14 13:52:57 -06:00
return registry.categoryPartToTypeInfoMap_[categoryPart];}}
if(registry.typeNameToTypeInfoMap_[typeName])
return registry.typeNameToTypeInfoMap_[typeName];return extensionRegistryOptions.defaultTypeInfo;};registry.getConstructor=function(category,typeName){var typeInfo=registry.getTypeInfo(category,typeName);if(typeInfo)
return typeInfo.constructor;return undefined;};}
return{_decorateTypeBasedExtensionRegistry:decorateTypeBasedExtensionRegistry};});'use strict';tr.exportTo('tr.b',function(){function decorateExtensionRegistry(registry,registryOptions){if(registry.register)
throw new Error('Already has registry');registryOptions.freeze();if(registryOptions.mode==tr.b.BASIC_REGISTRY_MODE){tr.b._decorateBasicExtensionRegistry(registry,registryOptions);}else if(registryOptions.mode==tr.b.TYPE_BASED_REGISTRY_MODE){tr.b._decorateTypeBasedExtensionRegistry(registry,registryOptions);}else{throw new Error('Unrecognized mode');}
if(registry.addEventListener===undefined)
tr.b.EventTarget.decorate(registry);}
return{decorateExtensionRegistry:decorateExtensionRegistry};});'use strict';tr.exportTo('tr.c',function(){function Auditor(model){}
Auditor.prototype={__proto__:Object.prototype,runAnnotate:function(){},runAudit:function(){}};var options=new tr.b.ExtensionRegistryOptions(tr.b.BASIC_REGISTRY_MODE);options.defaultMetadata={};options.mandatoryBaseClass=Auditor;tr.b.decorateExtensionRegistry(Auditor,options);return{Auditor:Auditor};});'use strict';tr.exportTo('tr.importer',function(){function Importer(){}
Importer.prototype={__proto__:Object.prototype,isTraceDataContainer:function(){return false;},extractSubtraces:function(){return[];},importEvents:function(){},importSampleData:function(){},finalizeImport:function(){},joinRefs:function(){}};var options=new tr.b.ExtensionRegistryOptions(tr.b.BASIC_REGISTRY_MODE);options.defaultMetadata={};options.mandatoryBaseClass=Importer;tr.b.decorateExtensionRegistry(Importer,options);Importer.findImporterFor=function(eventData){var typeInfo=Importer.findTypeInfoMatching(function(ti){return ti.constructor.canImport(eventData);});if(typeInfo)
return typeInfo.constructor;return undefined;};return{Importer:Importer};});'use strict';tr.exportTo('tr.importer',function(){var Importer=tr.importer.Importer;function EmptyImporter(events){this.importPriority=0;};EmptyImporter.canImport=function(eventData){if(eventData instanceof Array& & eventData.length==0)
return true;if(typeof(eventData)==='string'||eventData instanceof String){return eventData.length==0;}
return false;};EmptyImporter.prototype={__proto__:Importer.prototype};Importer.register(EmptyImporter);return{EmptyImporter:EmptyImporter};});'use strict';tr.exportTo('tr.model',function(){function EventContainer(){this.important=true;this.bounds=undefined;}
EventContainer.prototype={get stableId(){throw new Error('Not implemented');},updateBounds:function(){throw new Error('Not implemented');},shiftTimestampsForward:function(amount){throw new Error('Not implemented');},iterateAllEventsInThisContainer:function(eventTypePredicate,callback,opt_this){throw new Error('Not implemented');},iterateAllChildEventContainers:function(callback,opt_this){throw new Error('Not implemented');},iterateAllEvents:function(callback,opt_this){this.iterateAllEventContainers(function(ec){ec.iterateAllEventsInThisContainer(function(eventType){return true;},callback,opt_this);});},iterateAllEventContainers:function(callback,opt_this){function visit(ec){callback.call(opt_this,ec);ec.iterateAllChildEventContainers(visit);}
visit(this);}};return{EventContainer:EventContainer};});'use strict';tr.exportTo('tr.model',function(){function Device(model){if(!model)
throw new Error('Must provide a model.');tr.model.EventContainer.call(this);this.bounds=new tr.b.Range();this.guid=tr.b.GUID.allocate();};Device.compare=function(x,y){return x.guid-y.guid;};Device.prototype={__proto__:tr.model.EventContainer.prototype,compareTo:function(that){return Device.compare(this,that);},get userFriendlyName(){return'Device';},get userFriendlyDetails(){return'Device';},get stableId(){return'Device';},getSettingsKey:function(){return'device';},get counters(){return{};},updateBounds:function(){this.bounds.reset();},shiftTimestampsForward:function(amount){},addCategoriesToDict:function(categoriesDict){},iterateAllEventsInThisContainer:function(eventTypePredicate,callback,opt_this){},iterateAllChildEventContainers:function(callback,opt_this){}};return{Device:Device};});'use strict';tr.exportTo('tr.model',function(){var SelectionState={NONE:0,SELECTED:1,HIGHLIGHTED:2,DIMMED:3};return{SelectionState:SelectionState};});'use strict';tr.exportTo('tr.model',function(){var SelectionState=tr.model.SelectionState;function SelectableItem(modelItem){this.modelItem_=modelItem;}
SelectableItem.prototype={get modelItem(){return this.modelItem_;},get selected(){return this.selectionState===SelectionState.SELECTED;},addToSelection:function(selection){var modelItem=this.modelItem_;if(!modelItem)
return;selection.push(modelItem);},addToTrackMap:function(eventToTrackMap,track){var modelItem=this.modelItem_;if(!modelItem)
return;eventToTrackMap.addEvent(modelItem,track);}};return{SelectableItem:SelectableItem};});'use strict';tr.exportTo('tr.model',function(){var SelectableItem=tr.model.SelectableItem;var SelectionState=tr.model.SelectionState;var categoryPartsFor={};function getCategoryParts(category){var parts=categoryPartsFor[category];if(parts!==undefined)
return parts;parts=category.split(',');categoryPartsFor[category]=parts;return parts;}
2015-06-18 08:27:29 -06:00
function Event(){SelectableItem.call(this,this);this.guid_=tr.b.GUID.allocate();this.selectionState=SelectionState.NONE;this.associatedAlerts=new tr.c.Selection();this.info=undefined;}
2015-06-14 13:52:57 -06:00
Event.prototype={__proto__:SelectableItem.prototype,get guid(){return this.guid_;}};function EventRegistry(){}
var options=new tr.b.ExtensionRegistryOptions(tr.b.BASIC_REGISTRY_MODE);options.mandatoryBaseType=Event;tr.b.decorateExtensionRegistry(EventRegistry,options);EventRegistry.addEventListener('will-register',function(e){var metadata=e.typeInfo.metadata;if(metadata.name===undefined)
throw new Error('Registered events must provide name metadata');var i=tr.b.findFirstInArray(EventRegistry.getAllRegisteredTypeInfos(),function(x){return x.metadata.name===metadata.name;});if(i!==undefined)
throw new Error('Event type with that name already registered');if(metadata.pluralName===undefined)
throw new Error('Registered events must provide pluralName metadata');if(metadata.singleViewElementName===undefined){throw new Error('Registered events must provide '+'singleViewElementName metadata');}
if(metadata.multiViewElementName===undefined){throw new Error('Registered events must provide '+'multiViewElementName metadata');}});var eventsByTypeName=undefined;EventRegistry.getEventTypeInfoByTypeName=function(typeName){if(eventsByTypeName===undefined){eventsByTypeName={};EventRegistry.getAllRegisteredTypeInfos().forEach(function(typeInfo){eventsByTypeName[typeInfo.metadata.name]=typeInfo;});}
return eventsByTypeName[typeName];}
EventRegistry.addEventListener('registry-changed',function(){eventsByTypeName=undefined;});function convertCamelCaseToTitleCase(name){var result=name.replace(/[A-Z]/g,' $&'); result=result.charAt(0).toUpperCase()+result.slice(1);return result;}
2015-06-18 08:27:29 -06:00
EventRegistry.getUserFriendlySingularName=function(typeName){var typeInfo=EventRegistry.getEventTypeInfoByTypeName(typeName);var str=typeInfo.metadata.name;return convertCamelCaseToTitleCase(str);};EventRegistry.getUserFriendlyPluralName=function(typeName){var typeInfo=EventRegistry.getEventTypeInfoByTypeName(typeName);var str=typeInfo.metadata.pluralName;return convertCamelCaseToTitleCase(str);};return{Event:Event,EventRegistry:EventRegistry};});'use strict';tr.exportTo('tr.b.units',function(){function tsString(ts){return tr.b.units.Time.currentDisplayUnit.format(ts);}
2015-06-14 13:52:57 -06:00
return{tsString:tsString};});'use strict';tr.exportTo('tr.b',function(){function findLowIndexInSortedArray(ary,mapFn,loVal){if(ary.length==0)
return 1;var low=0;var high=ary.length-1;var i,comparison;var hitPos=-1;while(low< =high){i=Math.floor((low+high)/2);comparison=mapFn(ary[i])-loVal;if(comparison< 0 ) { low = i+1;continue;}else if ( comparison > 0){high=i-1;continue;}else{hitPos=i;high=i-1;}}
return hitPos!=-1?hitPos:low;}
function findIndexInSortedIntervals(ary,mapLoFn,mapWidthFn,loVal){var first=findLowIndexInSortedArray(ary,mapLoFn,loVal);if(first==0){if(loVal>=mapLoFn(ary[0])& & loVal< mapLoFn ( ary [ 0 ] ) + mapWidthFn ( ary [ 0 ] , 0 ) ) { return 0 ; } else { return-1 ; } } else if ( first < ary . length ) { if ( loVal > =mapLoFn(ary[first])& & loVal< mapLoFn ( ary [ first ] ) + mapWidthFn ( ary [ first ] , first ) ) { return first ; } else if ( loVal > =mapLoFn(ary[first-1])& & loVal< mapLoFn ( ary [ first-1 ] ) +
mapWidthFn(ary[first-1],first-1)){return first-1;}else{return ary.length;}}else if(first==ary.length){if(loVal>=mapLoFn(ary[first-1])& & loVal< mapLoFn ( ary [ first-1 ] ) +
mapWidthFn(ary[first-1],first-1)){return first-1;}else{return ary.length;}}else{return ary.length;}}
function findIndexInSortedClosedIntervals(ary,mapLoFn,mapHiFn,val){var i=findLowIndexInSortedArray(ary,mapLoFn,val);if(i===0){if(val>=mapLoFn(ary[0],0)& & val< =mapHiFn(ary[0],0)){return 0;}else{return-1;}}else if(i< ary.length ) { if ( val > =mapLoFn(ary[i-1],i-1)& & val< =mapHiFn(ary[i-1],i-1)){return i-1;}else if(val>=mapLoFn(ary[i],i)& & val< =mapHiFn(ary[i],i)){return i;}else{return ary.length;}}else if(i==ary.length){if(val>=mapLoFn(ary[i-1],i-1)& & val< =mapHiFn(ary[i-1],i-1)){return i-1;}else{return ary.length;}}else{return ary.length;}}
function iterateOverIntersectingIntervals(ary,mapLoFn,mapWidthFn,loVal,hiVal,cb){if(ary.length==0)
return;if(loVal>hiVal)return;var i=findLowIndexInSortedArray(ary,mapLoFn,loVal);if(i==-1){return;}
if(i>0){var hi=mapLoFn(ary[i-1])+mapWidthFn(ary[i-1],i-1);if(hi>=loVal){cb(ary[i-1],i-1);}}
if(i==ary.length){return;}
for(var n=ary.length;i< n ; i + + ) { var lo = mapLoFn(ary[i]);if(lo > =hiVal)
break;cb(ary[i],i);}}
function getIntersectingIntervals(ary,mapLoFn,mapWidthFn,loVal,hiVal){var tmp=[];iterateOverIntersectingIntervals(ary,mapLoFn,mapWidthFn,loVal,hiVal,function(d){tmp.push(d);});return tmp;}
function findClosestElementInSortedArray(ary,mapFn,val,maxDiff){if(ary.length===0)
return null;var aftIdx=findLowIndexInSortedArray(ary,mapFn,val);var befIdx=aftIdx>0?aftIdx-1:0;if(aftIdx===ary.length)
aftIdx-=1;var befDiff=Math.abs(val-mapFn(ary[befIdx]));var aftDiff=Math.abs(val-mapFn(ary[aftIdx]));if(befDiff>maxDiff& & aftDiff>maxDiff)
return null;var idx=befDiff< aftDiff ? befIdx:aftIdx ; return ary [ idx ] ; }
function findClosestIntervalInSortedIntervals(ary,mapLoFn,mapHiFn,val,maxDiff){if(ary.length===0)
return null;var idx=findLowIndexInSortedArray(ary,mapLoFn,val);if(idx>0)
idx-=1;var hiInt=ary[idx];var loInt=hiInt;if(val>mapHiFn(hiInt)& & idx+1< ary.length )
loInt=ary[idx+1];var loDiff=Math.abs(val-mapLoFn(loInt));var hiDiff=Math.abs(val-mapHiFn(hiInt));if(loDiff>maxDiff& & hiDiff>maxDiff)
return null;if(loDiff< hiDiff )
return loInt;else
return hiInt;}
return{findLowIndexInSortedArray:findLowIndexInSortedArray,findIndexInSortedIntervals:findIndexInSortedIntervals,findIndexInSortedClosedIntervals:findIndexInSortedClosedIntervals,iterateOverIntersectingIntervals:iterateOverIntersectingIntervals,getIntersectingIntervals:getIntersectingIntervals,findClosestElementInSortedArray:findClosestElementInSortedArray,findClosestIntervalInSortedIntervals:findClosestIntervalInSortedIntervals};});'use strict';tr.exportTo('tr.model',function(){function CounterSample(series,timestamp,value){tr.model.Event.call(this);this.series_=series;this.timestamp_=timestamp;this.value_=value;}
CounterSample.groupByTimestamp=function(samples){var samplesByTimestamp=tr.b.group(samples,function(sample){return sample.timestamp;});var timestamps=tr.b.dictionaryKeys(samplesByTimestamp);timestamps.sort();var groups=[];for(var i=0;i< timestamps.length ; i + + ) { var ts = timestamps[i];var group = samplesByTimestamp[ts];group.sort(function(x,y){return x . series . seriesIndex-y . series . seriesIndex ; } ) ; groups . push ( group ) ; }
return groups;}
CounterSample.prototype={__proto__:tr.model.Event.prototype,get series(){return this.series_;},get timestamp(){return this.timestamp_;},get value(){return this.value_;},set timestamp(timestamp){this.timestamp_=timestamp;},addBoundsToRange:function(range){range.addValue(this.timestamp);},getSampleIndex:function(){return tr.b.findLowIndexInSortedArray(this.series.timestamps,function(x){return x;},this.timestamp_);},get userFriendlyName(){return'Counter sample from '+this.series_.title+' at '+
2015-06-18 08:27:29 -06:00
tr.b.units.tsString(this.timestamp);}};tr.model.EventRegistry.register(CounterSample,{name:'counterSample',pluralName:'counterSamples',singleViewElementName:'tr-ui-a-counter-sample-sub-view',multiViewElementName:'tr-ui-a-counter-sample-sub-view'});return{CounterSample:CounterSample};});'use strict';tr.exportTo('tr.model',function(){var CounterSample=tr.model.CounterSample;function CounterSeries(name,color){tr.model.EventContainer.call(this);this.guid_=tr.b.GUID.allocate();this.name_=name;this.color_=color;this.timestamps_=[];this.samples_=[];this.counter=undefined;this.seriesIndex=undefined;}
2015-06-14 13:52:57 -06:00
CounterSeries.prototype={__proto__:tr.model.EventContainer.prototype,get length(){return this.timestamps_.length;},get name(){return this.name_;},get color(){return this.color_;},get samples(){return this.samples_;},get timestamps(){return this.timestamps_;},getSample:function(idx){return this.samples_[idx];},getTimestamp:function(idx){return this.timestamps_[idx];},addCounterSample:function(ts,val){var sample=new CounterSample(this,ts,val);this.addSample(sample);return sample;},addSample:function(sample){this.timestamps_.push(sample.timestamp);this.samples_.push(sample);},getStatistics:function(sampleIndices){var sum=0;var min=Number.MAX_VALUE;var max=-Number.MAX_VALUE;for(var i=0;i< sampleIndices.length ; + + i ) { var sample = this.getSample(sampleIndices[i]).value;sum+=sample;min=Math.min(sample,min);max=Math.max(sample,max);}
return{min:min,max:max,avg:(sum/sampleIndices.length),start:this.getSample(sampleIndices[0]).value,end:this.getSample(sampleIndices.length-1).value};},shiftTimestampsForward:function(amount){for(var i=0;i< this.timestamps_.length ; + + i ) { this . timestamps_ [ i ] + = amount ; this . samples_ [ i ] . timestamp = this.timestamps_[i];}},iterateAllEventsInThisContainer:function(eventTypePredicate,callback,opt_this){if(eventTypePredicate.call(opt_this,tr.model.CounterSample)){this.samples_.forEach(callback,opt_this);}},iterateAllChildEventContainers:function(callback,opt_this){}};return{CounterSeries:CounterSeries};});'use strict ' ; tr . exportTo ( ' tr . model ' , function ( ) { function Counter ( parent , id , category , name ) { tr . model . EventContainer . call ( this ) ; this . guid_ = tr.b.GUID.allocate();this.parent_=parent;this.id_=id;this.category_=category||'';this.name_=name;this.series_=[];this.totals=[];this.bounds=new tr . b . Range ( ) ; }
Counter.prototype={__proto__:tr.model.EventContainer.prototype,get guid(){return this.guid_;},get parent(){return this.parent_;},get id(){return this.id_;},get category(){return this.category_;},get name(){return this.name_;},iterateAllEventsInThisContainer:function(eventTypePredicate,callback,opt_this){},iterateAllChildEventContainers:function(callback,opt_this){for(var i=0;i< this.series_.length ; i + + )
callback.call(opt_this,this.series_[i]);},set timestamps(arg){throw new Error('Bad counter API. No cookie.');},set seriesNames(arg){throw new Error('Bad counter API. No cookie.');},set seriesColors(arg){throw new Error('Bad counter API. No cookie.');},set samples(arg){throw new Error('Bad counter API. No cookie.');},addSeries:function(series){series.counter=this;series.seriesIndex=this.series_.length;this.series_.push(series);return series;},getSeries:function(idx){return this.series_[idx];},get series(){return this.series_;},get numSeries(){return this.series_.length;},get numSamples(){if(this.series_.length===0)
return 0;return this.series_[0].length;},get timestamps(){if(this.series_.length===0)
return[];return this.series_[0].timestamps;},getSampleStatistics:function(sampleIndices){sampleIndices.sort();var ret=[];this.series_.forEach(function(series){ret.push(series.getStatistics(sampleIndices));});return ret;},shiftTimestampsForward:function(amount){for(var i=0;i< this.series_.length ; + + i )
this.series_[i].shiftTimestampsForward(amount);},updateBounds:function(){this.totals=[];this.maxTotal=0;this.bounds.reset();if(this.series_.length===0)
return;var firstSeries=this.series_[0];var lastSeries=this.series_[this.series_.length-1];this.bounds.addValue(firstSeries.getTimestamp(0));this.bounds.addValue(lastSeries.getTimestamp(lastSeries.length-1));var numSeries=this.numSeries;this.maxTotal=-Infinity;for(var i=0;i< firstSeries.length ; + + i ) { var total = 0;this.series_.forEach(function(series){total+=series.getSample(i).value;this.totals.push(total);}.bind(this));this.maxTotal=Math.max(total,this.maxTotal);}}};Counter.compare=function(x,y){var tmp = x.parent.compareTo(y);if(tmp!=0)
return tmp;var tmp=x.name.localeCompare(y.name);if(tmp==0)
return x.tid-y.tid;return tmp;};return{Counter:Counter};});'use strict';tr.exportTo('tr.model',function(){function TimedEvent(start){tr.model.Event.call(this);this.start=start;this.duration=0;this.cpuStart=undefined;this.cpuDuration=undefined;}
2015-06-18 08:27:29 -06:00
TimedEvent.prototype={__proto__:tr.model.Event.prototype,get end(){return this.start+this.duration;},addBoundsToRange:function(range){range.addValue(this.start);range.addValue(this.end);},bounds:function(that,precisionUnit){if(precisionUnit===undefined){precisionUnit=tr.b.units.Time.supportedUnits.ms;}
var startsBefore=precisionUnit.roundedLess(that.start,this.start);var endsAfter=precisionUnit.roundedLess(this.end,that.end);return!startsBefore&&!endsAfter; }};return{TimedEvent:TimedEvent};});'use strict';tr.exportTo('tr.model',function(){function Slice(category,title,colorId,start,args,opt_duration,opt_cpuStart,opt_cpuDuration,opt_argsStripped){tr.model.TimedEvent.call(this,start);this.category=category||'';this.title=title;this.colorId=colorId;this.args=args;this.startStackFrame=undefined;this.endStackFrame=undefined;this.didNotFinish=false;this.inFlowEvents=[];this.outFlowEvents=[];this.subSlices=[];this.selfTime=undefined;this.cpuSelfTime=undefined;this.important=false;this.parentContainer=undefined;this.argsStripped=false;if(opt_duration!==undefined)
2015-06-14 13:52:57 -06:00
this.duration=opt_duration;if(opt_cpuStart!==undefined)
this.cpuStart=opt_cpuStart;if(opt_cpuDuration!==undefined)
2015-06-18 08:27:29 -06:00
this.cpuDuration=opt_cpuDuration;if(opt_argsStripped!==undefined)
this.argsStripped=true;}
2015-06-14 13:52:57 -06:00
Slice.prototype={__proto__:tr.model.TimedEvent.prototype,get analysisTypeName(){return this.title;},get userFriendlyName(){return'Slice '+this.title+' at '+
tr.b.units.tsString(this.start);},findDescendentSlice:function(targetTitle){if(!this.subSlices)
return undefined;for(var i=0;i< this.subSlices.length ; i + + ) { if ( this . subSlices [ i ] . title = =targetTitle)
return this.subSlices[i];var slice=this.subSlices[i].findDescendentSlice(targetTitle);if(slice)return slice;}
return undefined;},get mostTopLevelSlice(){var curSlice=this;while(curSlice.parentSlice)
curSlice=curSlice.parentSlice;return curSlice;},iterateAllSubsequentSlices:function(callback,opt_this){var parentStack=[];var started=false;var topmostSlice=this.mostTopLevelSlice;parentStack.push(topmostSlice);while(parentStack.length!==0){var curSlice=parentStack.pop();if(started)
callback.call(opt_this,curSlice);else
started=(curSlice.guid===this.guid);for(var i=curSlice.subSlices.length-1;i>=0;i--){parentStack.push(curSlice.subSlices[i]);}}},get subsequentSlices(){var res=[];this.iterateAllSubsequentSlices(function(subseqSlice){res.push(subseqSlice);});return res;},iterateAllAncestors:function(callback,opt_this){var curSlice=this;while(curSlice.parentSlice){curSlice=curSlice.parentSlice;callback.call(opt_this,curSlice);}},get ancestorSlices(){var res=[];this.iterateAllAncestors(function(ancestor){res.push(ancestor);});return res;},get ancestorAndSubsequentSlices(){var res=[];res.push(this);this.iterateAllAncestors(function(aSlice){res.push(aSlice);});this.iterateAllSubsequentSlices(function(sSlice){res.push(sSlice);});return res;},iterateAllDescendents:function(callback,opt_this){this.subSlices.forEach(callback,opt_this);this.subSlices.forEach(function(subSlice){subSlice.iterateAllDescendents(callback,opt_this);},opt_this);},get descendentSlices(){var res=[];this.iterateAllDescendents(function(des){res.push(des);});return res;}};return{Slice:Slice};});'use strict';tr.exportTo('tr.model',function(){var Slice=tr.model.Slice;var SCHEDULING_STATE={DEBUG:'Debug',EXIT_DEAD:'Exit Dead',RUNNABLE:'Runnable',RUNNING:'Running',SLEEPING:'Sleeping',STOPPED:'Stopped',TASK_DEAD:'Task Dead',UNINTR_SLEEP:'Uninterruptible Sleep',UNINTR_SLEEP_WAKE_KILL:'Uninterruptible Sleep | WakeKill',UNINTR_SLEEP_WAKING:'Uninterruptible Sleep | Waking',UNKNOWN:'UNKNOWN',WAKE_KILL:'Wakekill',WAKING:'Waking',ZOMBIE:'Zombie'};function ThreadTimeSlice(thread,schedulingState,cat,start,args,opt_duration){Slice.call(this,cat,schedulingState,this.getColorForState_(schedulingState),start,args,opt_duration);this.thread=thread;this.schedulingState=schedulingState;this.cpuOnWhichThreadWasRunning=undefined;}
2015-06-18 08:27:29 -06:00
ThreadTimeSlice.prototype={__proto__:Slice.prototype,getColorForState_:function(state){var getColorIdForReservedName=tr.ui.b.getColorIdForReservedName;switch(state){case SCHEDULING_STATE.RUNNABLE:return getColorIdForReservedName('thread_state_runnable');case SCHEDULING_STATE.RUNNING:return getColorIdForReservedName('thread_state_running');case SCHEDULING_STATE.SLEEPING:return getColorIdForReservedName('thread_state_sleeping');case SCHEDULING_STATE.DEBUG:case SCHEDULING_STATE.EXIT_DEAD:case SCHEDULING_STATE.STOPPED:case SCHEDULING_STATE.TASK_DEAD:case SCHEDULING_STATE.UNINTR_SLEEP:case SCHEDULING_STATE.UNINTR_SLEEP_WAKE_KILL:case SCHEDULING_STATE.UNINTR_SLEEP_WAKING:case SCHEDULING_STATE.UNKNOWN:case SCHEDULING_STATE.WAKE_KILL:case SCHEDULING_STATE.WAKING:case SCHEDULING_STATE.ZOMBIE:return getColorIdForReservedName('thread_state_iowait');default:return getColorIdForReservedName('thread_state_unknown');}},get analysisTypeName(){return'tr.ui.analysis.ThreadTimeSlice';},getAssociatedCpuSlice:function(){if(!this.cpuOnWhichThreadWasRunning)
2015-06-14 13:52:57 -06:00
return undefined;var cpuSlices=this.cpuOnWhichThreadWasRunning.slices;for(var i=0;i< cpuSlices.length ; i + + ) { var cpuSlice = cpuSlices[i];if(cpuSlice.start!==this.start)
continue;if(cpuSlice.duration!==this.duration)
continue;return cpuSlice;}
return undefined;},getCpuSliceThatTookCpu:function(){if(this.cpuOnWhichThreadWasRunning)
return undefined;var curIndex=this.thread.indexOfTimeSlice(this);var cpuSliceWhenLastRunning;while(curIndex>=0){var curSlice=this.thread.timeSlices[curIndex];if(!curSlice.cpuOnWhichThreadWasRunning){curIndex--;continue;}
cpuSliceWhenLastRunning=curSlice.getAssociatedCpuSlice();break;}
if(!cpuSliceWhenLastRunning)
return undefined;var cpu=cpuSliceWhenLastRunning.cpu;var indexOfSliceOnCpuWhenLastRunning=cpu.indexOf(cpuSliceWhenLastRunning);var nextRunningSlice=cpu.slices[indexOfSliceOnCpuWhenLastRunning+1];if(!nextRunningSlice)
return undefined;if(Math.abs(nextRunningSlice.start-cpuSliceWhenLastRunning.end)< 0.00001 )
2015-06-18 08:27:29 -06:00
return nextRunningSlice;return undefined;}};tr.model.EventRegistry.register(ThreadTimeSlice,{name:'threadTimeSlice',pluralName:'threadTimeSlices',singleViewElementName:'tr-ui-a-single-thread-time-slice-sub-view',multiViewElementName:'tr-ui-a-multi-thread-time-slice-sub-view'});return{ThreadTimeSlice:ThreadTimeSlice,SCHEDULING_STATE:SCHEDULING_STATE};});'use strict';tr.exportTo('tr.model',function(){var Slice=tr.model.Slice;function CpuSlice(cat,title,colorId,start,args,opt_duration){Slice.apply(this,arguments);this.threadThatWasRunning=undefined;this.cpu=undefined;}
CpuSlice.prototype={__proto__:Slice.prototype,get analysisTypeName(){return'tr.ui.analysis.CpuSlice';},getAssociatedTimeslice:function(){if(!this.threadThatWasRunning)
2015-06-14 13:52:57 -06:00
return undefined;var timeSlices=this.threadThatWasRunning.timeSlices;for(var i=0;i< timeSlices.length ; i + + ) { var timeSlice = timeSlices[i];if(timeSlice.start!==this.start)
continue;if(timeSlice.duration!==this.duration)
continue;return timeSlice;}
2015-06-18 08:27:29 -06:00
return undefined;}};tr.model.EventRegistry.register(CpuSlice,{name:'cpuSlice',pluralName:'cpuSlices',singleViewElementName:'tr-ui-a-single-cpu-slice-sub-view',multiViewElementName:'tr-ui-a-multi-cpu-slice-sub-view'});return{CpuSlice:CpuSlice};});'use strict';tr.exportTo('tr.model',function(){var Counter=tr.model.Counter;var Slice=tr.model.Slice;var CpuSlice=tr.model.CpuSlice;function Cpu(kernel,number){if(kernel===undefined||number===undefined)
2015-06-14 13:52:57 -06:00
throw new Error('Missing arguments');this.kernel=kernel;this.cpuNumber=number;this.slices=[];this.counters={};this.bounds=new tr.b.Range();this.samples_=undefined;this.lastActiveTimestamp_=undefined;this.lastActiveThread_=undefined;this.lastActiveName_=undefined;this.lastActiveArgs_=undefined;};Cpu.prototype={iterateAllEventsInThisContainer:function(eventTypePredicate,callback,opt_this){if(eventTypePredicate.call(opt_this,tr.model.CpuSlice))
this.slices.forEach(callback,opt_this);if(this.samples_){if(eventTypePredicate.call(opt_this,tr.model.Sample))
this.samples_.forEach(callback,opt_this);}},iterateAllChildEventContainers:function(callback,opt_this){for(var id in this.counters)
callback.call(opt_this,this.counters[id]);},getOrCreateCounter:function(cat,name){var id;if(cat.length)
id=cat+'.'+name;else
id=name;if(!this.counters[id])
this.counters[id]=new Counter(this,id,cat,name);return this.counters[id];},shiftTimestampsForward:function(amount){for(var sI=0;sI< this.slices.length ; sI + + )
this.slices[sI].start=(this.slices[sI].start+amount);for(var id in this.counters)
this.counters[id].shiftTimestampsForward(amount);},updateBounds:function(){this.bounds.reset();if(this.slices.length){this.bounds.addValue(this.slices[0].start);this.bounds.addValue(this.slices[this.slices.length-1].end);}
for(var id in this.counters){this.counters[id].updateBounds();this.bounds.addRange(this.counters[id].bounds);}
if(this.samples_&&this.samples_.length){this.bounds.addValue(this.samples_[0].start); this.bounds.addValue(this.samples_[this.samples_.length-1].end);}},createSubSlices:function(){this.samples_=this.kernel.model.samples.filter(function(sample){return sample.cpu==this;},this);},addCategoriesToDict:function(categoriesDict){for(var i=0;i< this.slices.length ; i + + )
categoriesDict[this.slices[i].category]=true;for(var id in this.counters)
categoriesDict[this.counters[id].category]=true;for(var i=0;i< this.samples_.length ; i + + )
categoriesDict[this.samples_[i].category]=true;},get userFriendlyName(){return'CPU '+this.cpuNumber;},indexOf:function(cpuSlice){var i=tr.b.findLowIndexInSortedArray(this.slices,function(slice){return slice.start;},cpuSlice.start);if(this.slices[i]!==cpuSlice)
return undefined;return i;},closeActiveThread:function(end_timestamp,args){if(this.lastActiveThread_==undefined||this.lastActiveThread_==0)
return;if(end_timestamp< this.lastActiveTimestamp_ ) { throw new Error ( ' The end timestamp of a thread running on CPU ' +
this.cpuNumber+' is before its start timestamp.');}
for(var key in args){this.lastActiveArgs_[key]=args[key];}
var duration=end_timestamp-this.lastActiveTimestamp_;var slice=new tr.model.CpuSlice('',this.lastActiveName_,tr.ui.b.getColorIdForGeneralPurposeString(this.lastActiveName_),this.lastActiveTimestamp_,this.lastActiveArgs_,duration);slice.cpu=this;this.slices.push(slice);this.lastActiveTimestamp_=undefined;this.lastActiveThread_=undefined;this.lastActiveName_=undefined;this.lastActiveArgs_=undefined;},switchActiveThread:function(timestamp,old_thread_args,new_thread_id,new_thread_name,new_thread_args){this.closeActiveThread(timestamp,old_thread_args);this.lastActiveTimestamp_=timestamp;this.lastActiveThread_=new_thread_id;this.lastActiveName_=new_thread_name;this.lastActiveArgs_=new_thread_args;},get samples(){return this.samples_;}};Cpu.compare=function(x,y){return x.cpuNumber-y.cpuNumber;};return{Cpu:Cpu};});'use strict';tr.exportTo('tr.model',function(){function ObjectSnapshot(objectInstance,ts,args){tr.model.Event.call(this);this.objectInstance=objectInstance;this.ts=ts;this.args=args;}
ObjectSnapshot.prototype={__proto__:tr.model.Event.prototype,preInitialize:function(){},initialize:function(){},addBoundsToRange:function(range){range.addValue(this.ts);},get userFriendlyName(){return'Snapshot of '+
this.objectInstance.typeName+' '+
this.objectInstance.id+' @ '+
2015-06-18 08:27:29 -06:00
tr.b.units.tsString(this.ts);}};tr.model.EventRegistry.register(ObjectSnapshot,{name:'objectSnapshot',pluralName:'objectSnapshots',singleViewElementName:'tr-ui-a-single-object-snapshot-sub-view',multiViewElementName:'tr-ui-a-multi-object-sub-view'});var options=new tr.b.ExtensionRegistryOptions(tr.b.TYPE_BASED_REGISTRY_MODE);options.mandatoryBaseClass=ObjectSnapshot;options.defaultConstructor=ObjectSnapshot;tr.b.decorateExtensionRegistry(ObjectSnapshot,options);return{ObjectSnapshot:ObjectSnapshot};});'use strict';tr.exportTo('tr.model',function(){var ObjectSnapshot=tr.model.ObjectSnapshot;function ObjectInstance(parent,id,category,name,creationTs,opt_baseTypeName){tr.model.Event.call(this);this.parent=parent;this.id=id;this.category=category;this.baseTypeName=opt_baseTypeName?opt_baseTypeName:name;this.name=name;this.creationTs=creationTs;this.creationTsWasExplicit=false;this.deletionTs=Number.MAX_VALUE;this.deletionTsWasExplicit=false;this.colorId=0;this.bounds=new tr.b.Range();this.snapshots=[];this.hasImplicitSnapshots=false;}
2015-06-14 13:52:57 -06:00
ObjectInstance.prototype={__proto__:tr.model.Event.prototype,get typeName(){return this.name;},addBoundsToRange:function(range){range.addRange(this.bounds);},addSnapshot:function(ts,args,opt_name,opt_baseTypeName){if(ts< this.creationTs )
throw new Error('Snapshots must be >= instance.creationTs');if(ts>=this.deletionTs)
throw new Error('Snapshots cannot be added after '+'an objects deletion timestamp.');var lastSnapshot;if(this.snapshots.length>0){lastSnapshot=this.snapshots[this.snapshots.length-1];if(lastSnapshot.ts==ts)
throw new Error('Snapshots already exists at this time!');if(ts< lastSnapshot.ts ) { throw new Error ( ' Snapshots must be added in increasing timestamp order ' ) ; } }
if(opt_name& & (this.name!=opt_name)){if(!opt_baseTypeName)
throw new Error('Must provide base type name for name update');if(this.baseTypeName!=opt_baseTypeName)
throw new Error('Cannot update type name: base types dont match');this.name=opt_name;}
var snapshotConstructor=tr.model.ObjectSnapshot.getConstructor(this.category,this.name);var snapshot=new snapshotConstructor(this,ts,args);this.snapshots.push(snapshot);return snapshot;},wasDeleted:function(ts){var lastSnapshot;if(this.snapshots.length>0){lastSnapshot=this.snapshots[this.snapshots.length-1];if(lastSnapshot.ts>ts)
throw new Error('Instance cannot be deleted at ts='+
ts+'. A snapshot exists that is older.');}
this.deletionTs=ts;this.deletionTsWasExplicit=true;},preInitialize:function(){for(var i=0;i< this.snapshots.length ; i + + )
this.snapshots[i].preInitialize();},initialize:function(){for(var i=0;i< this.snapshots.length ; i + + )
this.snapshots[i].initialize();},getSnapshotAt:function(ts){if(ts< this.creationTs ) { if ( this . creationTsWasExplicit )
throw new Error('ts must be within lifetime of this instance');return this.snapshots[0];}
if(ts>this.deletionTs)
throw new Error('ts must be within lifetime of this instance');var snapshots=this.snapshots;var i=tr.b.findIndexInSortedIntervals(snapshots,function(snapshot){return snapshot.ts;},function(snapshot,i){if(i==snapshots.length-1)
return snapshots[i].objectInstance.deletionTs;return snapshots[i+1].ts-snapshots[i].ts;},ts);if(i< 0 ) { return this . snapshots [ 0 ] ; }
if(i>=this.snapshots.length)
return this.snapshots[this.snapshots.length-1];return this.snapshots[i];},updateBounds:function(){this.bounds.reset();this.bounds.addValue(this.creationTs);if(this.deletionTs!=Number.MAX_VALUE)
this.bounds.addValue(this.deletionTs);else if(this.snapshots.length>0)
this.bounds.addValue(this.snapshots[this.snapshots.length-1].ts);},shiftTimestampsForward:function(amount){this.creationTs+=amount;if(this.deletionTs!=Number.MAX_VALUE)
2015-06-18 08:27:29 -06:00
this.deletionTs+=amount;this.snapshots.forEach(function(snapshot){snapshot.ts+=amount;});},get userFriendlyName(){return this.typeName+' object '+this.id;}};tr.model.EventRegistry.register(ObjectInstance,{name:'objectInstance',pluralName:'objectInstances',singleViewElementName:'tr-ui-a-single-object-instance-sub-view',multiViewElementName:'tr-ui-a-multi-object-sub-view'});var options=new tr.b.ExtensionRegistryOptions(tr.b.TYPE_BASED_REGISTRY_MODE);options.mandatoryBaseClass=ObjectInstance;options.defaultConstructor=ObjectInstance;tr.b.decorateExtensionRegistry(ObjectInstance,options);return{ObjectInstance:ObjectInstance};});'use strict';tr.exportTo('tr.model',function(){function TimeToObjectInstanceMap(createObjectInstanceFunction,parent,id){this.createObjectInstanceFunction_=createObjectInstanceFunction;this.parent=parent;this.id=id;this.instances=[];}
2015-06-14 13:52:57 -06:00
TimeToObjectInstanceMap.prototype={idWasCreated:function(category,name,ts){if(this.instances.length==0){this.instances.push(this.createObjectInstanceFunction_(this.parent,this.id,category,name,ts));this.instances[0].creationTsWasExplicit=true;return this.instances[0];}
var lastInstance=this.instances[this.instances.length-1];if(ts< lastInstance.deletionTs ) { throw new Error ( ' Mutation of the TimeToObjectInstanceMap must be ' + ' done in ascending timestamp order . ' ) ; }
lastInstance=this.createObjectInstanceFunction_(this.parent,this.id,category,name,ts);lastInstance.creationTsWasExplicit=true;this.instances.push(lastInstance);return lastInstance;},addSnapshot:function(category,name,ts,args,opt_baseTypeName){if(this.instances.length==0){this.instances.push(this.createObjectInstanceFunction_(this.parent,this.id,category,name,ts,opt_baseTypeName));}
var i=tr.b.findIndexInSortedIntervals(this.instances,function(inst){return inst.creationTs;},function(inst){return inst.deletionTs-inst.creationTs;},ts);var instance;if(i< 0 ) { instance = this.instances[0];if(ts > instance.deletionTs||instance.creationTsWasExplicit){throw new Error('At the provided timestamp, no instance was still alive');}
if(instance.snapshots.length!=0){throw new Error('Cannot shift creationTs forward, '+'snapshots have been added. First snap was at ts='+
instance.snapshots[0].ts+' and creationTs was '+
instance.creationTs);}
instance.creationTs=ts;}else if(i>=this.instances.length){instance=this.instances[this.instances.length-1];if(ts>=instance.deletionTs){instance=this.createObjectInstanceFunction_(this.parent,this.id,category,name,ts,opt_baseTypeName);this.instances.push(instance);}else{var lastValidIndex;for(var i=this.instances.length-1;i>=0;i--){var tmp=this.instances[i];if(ts>=tmp.deletionTs)
break;if(tmp.creationTsWasExplicit==false& & tmp.snapshots.length==0)
lastValidIndex=i;}
if(lastValidIndex===undefined){throw new Error('Cannot add snapshot. No instance was alive that was mutable.');}
instance=this.instances[lastValidIndex];instance.creationTs=ts;}}else{instance=this.instances[i];}
return instance.addSnapshot(ts,args,name,opt_baseTypeName);},get lastInstance(){if(this.instances.length==0)
return undefined;return this.instances[this.instances.length-1];},idWasDeleted:function(category,name,ts){if(this.instances.length==0){this.instances.push(this.createObjectInstanceFunction_(this.parent,this.id,category,name,ts));}
var lastInstance=this.instances[this.instances.length-1];if(ts< lastInstance.creationTs )
throw new Error('Cannot delete a id before it was crated');if(lastInstance.deletionTs==Number.MAX_VALUE){lastInstance.wasDeleted(ts);return lastInstance;}
if(ts< lastInstance.deletionTs )
throw new Error('id was already deleted earlier.');lastInstance=this.createObjectInstanceFunction_(this.parent,this.id,category,name,ts);this.instances.push(lastInstance);lastInstance.wasDeleted(ts);return lastInstance;},getInstanceAt:function(ts){var i=tr.b.findIndexInSortedIntervals(this.instances,function(inst){return inst.creationTs;},function(inst){return inst.deletionTs-inst.creationTs;},ts);if(i< 0 ) { if ( this . instances [ 0 ] . creationTsWasExplicit )
return undefined;return this.instances[0];}else if(i>=this.instances.length){return undefined;}
return this.instances[i];},logToConsole:function(){for(var i=0;i< this.instances.length ; i + + ) { var instance = this.instances[i];var cEF = '' ; var dEF = '' ; if ( instance . creationTsWasExplicit )
cEF='(explicitC)';if(instance.deletionTsWasExplicit)
dEF='(explicit)';console.log(instance.creationTs,cEF,instance.deletionTs,dEF,instance.category,instance.name,instance.snapshots.length+' snapshots');}}};return{TimeToObjectInstanceMap:TimeToObjectInstanceMap};});'use strict';tr.exportTo('tr.model',function(){var ObjectInstance=tr.model.ObjectInstance;var ObjectSnapshot=tr.model.ObjectSnapshot;function ObjectCollection(parent){tr.model.EventContainer.call(this);this.parent=parent;this.bounds=new tr.b.Range();this.instanceMapsById_={};this.instancesByTypeName_={};this.createObjectInstance_=this.createObjectInstance_.bind(this);}
ObjectCollection.prototype={__proto__:tr.model.EventContainer.prototype,iterateAllChildEventContainers:function(callback,opt_this){},iterateAllEventsInThisContainer:function(eventTypePredicate,callback,opt_this){var bI=!!eventTypePredicate.call(opt_this,ObjectInstance);var bS=!!eventTypePredicate.call(opt_this,ObjectSnapshot);if(bI===false& & bS===false)
return;this.iterObjectInstances(function(instance){if(bI)
callback.call(opt_this,instance);if(bS)
instance.snapshots.forEach(callback,opt_this);},opt_this);},createObjectInstance_:function(parent,id,category,name,creationTs,opt_baseTypeName){var constructor=tr.model.ObjectInstance.getConstructor(category,name);var instance=new constructor(parent,id,category,name,creationTs,opt_baseTypeName);var typeName=instance.typeName;var instancesOfTypeName=this.instancesByTypeName_[typeName];if(!instancesOfTypeName){instancesOfTypeName=[];this.instancesByTypeName_[typeName]=instancesOfTypeName;}
instancesOfTypeName.push(instance);return instance;},getOrCreateInstanceMap_:function(id){var instanceMap=this.instanceMapsById_[id];if(instanceMap)
return instanceMap;instanceMap=new tr.model.TimeToObjectInstanceMap(this.createObjectInstance_,this.parent,id);this.instanceMapsById_[id]=instanceMap;return instanceMap;},idWasCreated:function(id,category,name,ts){var instanceMap=this.getOrCreateInstanceMap_(id);return instanceMap.idWasCreated(category,name,ts);},addSnapshot:function(id,category,name,ts,args,opt_baseTypeName){var instanceMap=this.getOrCreateInstanceMap_(id);var snapshot=instanceMap.addSnapshot(category,name,ts,args,opt_baseTypeName);if(snapshot.objectInstance.category!=category){var msg='Added snapshot name='+name+' with cat='+category+' impossible. It instance was created/snapshotted with cat='+
snapshot.objectInstance.category+' name='+
snapshot.objectInstance.name;throw new Error(msg);}
if(opt_baseTypeName& & snapshot.objectInstance.baseTypeName!=opt_baseTypeName){throw new Error('Could not add snapshot with baseTypeName='+
opt_baseTypeName+'. It '+'was previously created with name='+
snapshot.objectInstance.baseTypeName);}
if(snapshot.objectInstance.name!=name){throw new Error('Could not add snapshot with name='+name+'. It '+'was previously created with name='+
snapshot.objectInstance.name);}
return snapshot;},idWasDeleted:function(id,category,name,ts){var instanceMap=this.getOrCreateInstanceMap_(id);var deletedInstance=instanceMap.idWasDeleted(category,name,ts);if(!deletedInstance)
return;if(deletedInstance.category!=category){var msg='Deleting object '+deletedInstance.name+' with a different category '+'than when it was created. It previous had cat='+
deletedInstance.category+' but the delete command '+'had cat='+category;throw new Error(msg);}
if(deletedInstance.baseTypeName!=name){throw new Error('Deletion requested for name='+
name+' could not proceed: '+'An existing object with baseTypeName='+
deletedInstance.baseTypeName+' existed.');}},autoDeleteObjects:function(maxTimestamp){tr.b.iterItems(this.instanceMapsById_,function(id,i2imap){var lastInstance=i2imap.lastInstance;if(lastInstance.deletionTs!=Number.MAX_VALUE)
return;i2imap.idWasDeleted(lastInstance.category,lastInstance.name,maxTimestamp);lastInstance.deletionTsWasExplicit=false;});},getObjectInstanceAt:function(id,ts){var instanceMap=this.instanceMapsById_[id];if(!instanceMap)
return undefined;return instanceMap.getInstanceAt(ts);},getSnapshotAt:function(id,ts){var instance=this.getObjectInstanceAt(id,ts);if(!instance)
2015-06-18 08:27:29 -06:00
return undefined;return instance.getSnapshotAt(ts);},iterObjectInstances:function(iter,opt_this){opt_this=opt_this||this;tr.b.iterItems(this.instanceMapsById_,function(id,i2imap){i2imap.instances.forEach(iter,opt_this);});},getAllObjectInstances:function(){var instances=[];this.iterObjectInstances(function(i){instances.push(i);});return instances;},getAllInstancesNamed:function(name){return this.instancesByTypeName_[name];},getAllInstancesByTypeName:function(){return this.instancesByTypeName_;},preInitializeAllObjects:function(){this.iterObjectInstances(function(instance){instance.preInitialize();});},initializeAllObjects:function(){this.iterObjectInstances(function(instance){instance.initialize();});},initializeInstances:function(){this.iterObjectInstances(function(instance){instance.initialize();});},updateBounds:function(){this.bounds.reset();this.iterObjectInstances(function(instance){instance.updateBounds();this.bounds.addRange(instance.bounds);},this);},shiftTimestampsForward:function(amount){this.iterObjectInstances(function(instance){instance.shiftTimestampsForward(amount);});},addCategoriesToDict:function(categoriesDict){this.iterObjectInstances(function(instance){categoriesDict[instance.category]=true;});}};return{ObjectCollection:ObjectCollection};});'use strict';tr.exportTo('tr.model',function(){var Slice=tr.model.Slice;function ThreadSlice(cat,title,colorId,start,args,opt_duration,opt_cpuStart,opt_cpuDuration,opt_argsStripped){Slice.call(this,cat,title,colorId,start,args,opt_duration,opt_cpuStart,opt_cpuDuration,opt_argsStripped);this.subSlices=[];}
ThreadSlice.prototype={__proto__:Slice.prototype};tr.model.EventRegistry.register(ThreadSlice,{name:'slice',pluralName:'slices',singleViewElementName:'tr-ui-a-single-thread-slice-sub-view',multiViewElementName:'tr-ui-a-multi-thread-slice-sub-view'});return{ThreadSlice:ThreadSlice};});'use strict';tr.exportTo('tr.ui.b',function(){function boundChannel(v){return Math.min(255,Math.max(0,Math.floor(v)));}
2015-06-14 13:52:57 -06:00
function brightenColor(c){var k;if(c.r>=240& & c.g>=240& & c.b>=240)
k=0.80;else
k=1.45;return{r:boundChannel(c.r*k),g:boundChannel(c.g*k),b:boundChannel(c.b*k)};}
function desaturateColor(c){var value=boundChannel((c.r+c.g+c.b)/3);return{r:value,g:value,b:value};}
function colorToRGBString(c){return'rgb('+c.r+','+c.g+','+c.b+')';}
function colorToRGBAString(c,a){return'rgba('+c.r+','+c.g+','+c.b+','+a+')';}
return{brightenColor:brightenColor,desaturateColor:desaturateColor,colorToRGBString:colorToRGBString,colorToRGBAString:colorToRGBAString};});'use strict';tr.exportTo('tr.ui.b',function(){var colorToRGBString=tr.ui.b.colorToRGBString;var colorToRGBAString=tr.ui.b.colorToRGBAString;var generalPurposeColors=[{r:138,g:113,b:152},{r:175,g:112,b:133},{r:127,g:135,b:225},{r:93,g:81,b:137},{r:116,g:143,b:119},{r:178,g:214,b:122},{r:87,g:109,b:147},{r:119,g:155,b:95},{r:114,g:180,b:160},{r:132,g:85,b:103},{r:157,g:210,b:150},{r:148,g:94,b:86},{r:164,g:108,b:138},{r:139,g:191,b:150},{r:110,g:99,b:145},{r:80,g:129,b:109},{r:125,g:140,b:149},{r:93,g:124,b:132},{r:140,g:85,b:140},{r:104,g:163,b:162},{r:132,g:141,b:178},{r:131,g:105,b:147},{r:135,g:183,b:98},{r:152,g:134,b:177},{r:141,g:188,b:141},{r:133,g:160,b:210},{r:126,g:186,b:148},{r:112,g:198,b:205},{r:180,g:122,b:195},{r:203,g:144,b:152}];var reservedColorsByName={thread_state_iowait:{r:182,g:125,b:143},thread_state_running:{r:126,g:200,b:148},thread_state_runnable:{r:133,g:160,b:210},thread_state_sleeping:{r:240,g:240,b:240},thread_state_unknown:{r:199,g:155,b:125},memory_dump:{r:0,g:0,b:180},generic_work:{r:125,g:125,b:125},good:{r:0,g:125,b:0},bad:{r:180,g:125,b:0},terrible:{r:180,g:0,b:0},black:{r:0,g:0,b:0},rail_response:{r:67,g:135,b:253},rail_animate:{r:244,g:74,b:63},rail_idle:{r:238,g:142,b:0},rail_load:{r:13,g:168,b:97},used_memory_column:{r:0,g:0,b:255},older_used_memory_column:{r:153,g:204,b:255},tracing_memory_column:{r:153,g:153,b:153}};var numGeneralPurposeColorIds=generalPurposeColors.length;var numReservedColorIds=tr.b.dictionaryLength(reservedColorsByName);var paletteRaw=(function(){var paletteBase=[];paletteBase.push.apply(paletteBase,generalPurposeColors);paletteBase.push.apply(paletteBase,tr.b.dictionaryValues(reservedColorsByName));return paletteBase.concat(paletteBase.map(tr.ui.b.brightenColor),paletteBase.map(tr.ui.b.desaturateColor));})();var palette=paletteRaw.map(colorToRGBString);var highlightIdBoost=paletteRaw.length/3;var desaturateIdBoost=(paletteRaw.length/3)*2;var reservedColorNameToIdMap=(function(){var m={};var i=generalPurposeColors.length;tr.b.iterItems(reservedColorsByName,function(key,value){m[key]=i++;});return m;})();function getStringHash(name){var hash=0;for(var i=0;i< name.length ; + + i )
hash=(hash+37*hash+11*name.charCodeAt(i))%0xFFFFFFFF;return hash;}
function getColorPalette(){return palette;}
function getRawColorPalette(){return paletteRaw;}
function getColorPaletteHighlightIdBoost(){return highlightIdBoost;}
function getColorPaletteDesaturateIdBoost(){return desaturateIdBoost;}
function getColorIdForReservedName(name){var id=reservedColorNameToIdMap[name];if(id===undefined)
throw new Error('Unrecognized color ')+name;return id;}
var stringColorIdCache={};function getColorIdForGeneralPurposeString(string){if(stringColorIdCache[string]===undefined){var hash=getStringHash(string);stringColorIdCache[string]=hash%numGeneralPurposeColorIds;}
return stringColorIdCache[string];}
var paletteProperties={numGeneralPurposeColorIds:numGeneralPurposeColorIds,highlightIdBoost:highlightIdBoost,desaturateIdBoost:desaturateIdBoost};return{getRawColorPalette:getRawColorPalette,getColorPalette:getColorPalette,paletteProperties:paletteProperties,getColorPaletteHighlightIdBoost:getColorPaletteHighlightIdBoost,getColorPaletteDesaturateIdBoost:getColorPaletteDesaturateIdBoost,getColorIdForReservedName:getColorIdForReservedName,getStringHash:getStringHash,getColorIdForGeneralPurposeString:getColorIdForGeneralPurposeString};});'use strict';tr.exportTo('tr.model',function(){var Slice=tr.model.Slice;function getSliceLo(s){return s.start;}
function getSliceHi(s){return s.end;}
2015-06-18 08:27:29 -06:00
function SliceGroup(parentContainer,opt_sliceConstructor,opt_name){this.guid_=tr.b.GUID.allocate();this.parentContainer_=parentContainer;var sliceConstructor=opt_sliceConstructor||Slice;this.sliceConstructor=sliceConstructor;this.openPartialSlices_=[];this.slices=[];this.bounds=new tr.b.Range();this.topLevelSlices=[];this.haveTopLevelSlicesBeenBuilt=false;this.name_=opt_name;if(this.model===undefined)
throw new Error('SliceGroup must have model defined.');}
SliceGroup.prototype={__proto__:tr.model.EventContainer.prototype,get guid(){return this.guid_;},get parentContainer(){return this.parentContainer_;},get model(){return this.parentContainer_.model;},get stableId(){return this.parentContainer_.stableId+'.SliceGroup';},getSettingsKey:function(){if(!this.name_)
2015-06-14 13:52:57 -06:00
return undefined;var parentKey=this.parentContainer_.getSettingsKey();if(!parentKey)
2015-06-18 08:27:29 -06:00
return undefined;return parentKey+'.'+this.name;},get length(){return this.slices.length;},pushSlice:function(slice){this.haveTopLevelSlicesBeenBuilt=false;slice.parentContainer=this.parentContainer_;this.slices.push(slice);return slice;},pushSlices:function(slices){this.haveTopLevelSlicesBeenBuilt=false;slices.forEach(function(slice){slice.parentContainer=this.parentContainer_;this.slices.push(slice);},this);},beginSlice:function(category,title,ts,opt_args,opt_tts,opt_argsStripped){if(this.openPartialSlices_.length){var prevSlice=this.openPartialSlices_[this.openPartialSlices_.length-1];if(ts< prevSlice.start )
2015-06-14 13:52:57 -06:00
throw new Error('Slices must be added in increasing timestamp order');}
2015-06-18 08:27:29 -06:00
var colorId=tr.ui.b.getColorIdForGeneralPurposeString(title);var slice=new this.sliceConstructor(category,title,colorId,ts,opt_args?opt_args:{},null,opt_tts,undefined,opt_argsStripped);this.openPartialSlices_.push(slice);slice.didNotFinish=true;this.pushSlice(slice);return slice;},isTimestampValidForBeginOrEnd:function(ts){if(!this.openPartialSlices_.length)
2015-06-14 13:52:57 -06:00
return true;var top=this.openPartialSlices_[this.openPartialSlices_.length-1];return ts>=top.start;},get openSliceCount(){return this.openPartialSlices_.length;},get mostRecentlyOpenedPartialSlice(){if(!this.openPartialSlices_.length)
return undefined;return this.openPartialSlices_[this.openPartialSlices_.length-1];},endSlice:function(ts,opt_tts){if(!this.openSliceCount)
throw new Error('endSlice called without an open slice');var slice=this.openPartialSlices_[this.openSliceCount-1];this.openPartialSlices_.splice(this.openSliceCount-1,1);if(ts< slice.start )
throw new Error('Slice '+slice.title+' end time is before its start.');slice.duration=ts-slice.start;slice.didNotFinish=false;if(opt_tts& & slice.cpuStart!==undefined)
2015-06-18 08:27:29 -06:00
slice.cpuDuration=opt_tts-slice.cpuStart;return slice;},pushCompleteSlice:function(category,title,ts,duration,tts,cpuDuration,opt_args,opt_argsStripped){var colorId=tr.ui.b.getColorIdForGeneralPurposeString(title);var slice=new this.sliceConstructor(category,title,colorId,ts,opt_args?opt_args:{},duration,tts,cpuDuration,opt_argsStripped);if(duration===undefined)
2015-06-14 13:52:57 -06:00
slice.didNotFinish=true;this.pushSlice(slice);return slice;},autoCloseOpenSlices:function(opt_maxTimestamp){if(!opt_maxTimestamp){this.updateBounds();opt_maxTimestamp=this.bounds.max;}
for(var sI=0;sI< this.slices.length ; sI + + ) { var slice = this.slices[sI];if(slice.didNotFinish)
slice.duration=opt_maxTimestamp-slice.start;}
this.openPartialSlices_=[];},shiftTimestampsForward:function(amount){for(var sI=0;sI< this.slices.length ; sI + + ) { var slice = this.slices[sI];slice.start=(slice.start+amount);}},updateBounds:function(){this.bounds.reset();for(var i = 0;i<this.slices.length;i++){this.bounds.addValue(this.slices[i].start);this.bounds.addValue(this.slices[i].end);}},copySlice:function(slice){var newSlice = new this . sliceConstructor ( slice . category , slice . title , slice . colorId , slice . start , slice . args , slice . duration , slice . cpuStart , slice . cpuDuration ) ; newSlice . didNotFinish = slice.didNotFinish;return newSlice ; } , iterateAllEventsInThisContainer:function ( eventTypePredicate , callback , opt_this ) { if ( eventTypePredicate . call ( opt_this , this . sliceConstructor ) )
this.slices.forEach(callback,opt_this);},iterateAllChildEventContainers:function(callback,opt_this){},getSlicesOfName:function(title){var slices=[];for(var i=0;i< this.slices.length ; i + + ) { if ( this . slices [ i ] . title = =title){slices.push(this.slices[i]);}}
return slices;},iterSlicesInTimeRange:function(callback,start,end){var ret=[];tr.b.iterateOverIntersectingIntervals(this.topLevelSlices,function(s){return s.start;},function(s){return s.duration;},start,end,function(topLevelSlice){callback(topLevelSlice);topLevelSlice.iterateAllDescendents(callback);});return ret;},findSliceAtTs:function(ts){if(!this.haveTopLevelSlicesBeenBuilt)
throw new Error('Nope');var i=tr.b.findIndexInSortedClosedIntervals(this.topLevelSlices,getSliceLo,getSliceHi,ts);if(i==-1||i==this.topLevelSlices.length)
return undefined;var curSlice=this.topLevelSlices[i];while(true){var i=tr.b.findIndexInSortedClosedIntervals(curSlice.subSlices,getSliceLo,getSliceHi,ts);if(i==-1||i==curSlice.subSlices.length)
return curSlice;curSlice=curSlice.subSlices[i];}},findNextSliceAfter:function(ts,refGuid){var i=tr.b.findLowIndexInSortedArray(this.slices,getSliceLo,ts);if(i===this.slices.length)
return undefined;for(;i< this.slices.length ; i + + ) { var slice = this.slices[i];if(slice.start > ts)
return slice;if(slice.guid< =refGuid)
continue;return slice;}
return undefined;},createSubSlices:function(){this.haveTopLevelSlicesBeenBuilt=true;this.createSubSlicesImpl_();if(this.parentContainer.timeSlices)
this.addCpuTimeToSubslices_(this.parentContainer.timeSlices);this.slices.forEach(function(slice){var selfTime=slice.duration;for(var i=0;i< slice.subSlices.length ; i + + )
selfTime-=slice.subSlices[i].duration;slice.selfTime=selfTime;if(slice.cpuDuration===undefined)
return;var cpuSelfTime=slice.cpuDuration;for(var i=0;i< slice.subSlices.length ; i + + ) { if ( slice . subSlices [ i ] . cpuDuration ! = = undefined )
cpuSelfTime-=slice.subSlices[i].cpuDuration;}
2015-06-18 08:27:29 -06:00
slice.cpuSelfTime=cpuSelfTime;});},createSubSlicesImpl_:function(){var precisionUnit=this.model.intrinsicTimeUnit;function addSliceIfBounds(root,child){if(root.bounds(child,precisionUnit)){if(root.subSlices& & root.subSlices.length>0){if(addSliceIfBounds(root.subSlices[root.subSlices.length-1],child))
2015-06-14 13:52:57 -06:00
return true;}
child.parentSlice=root;if(root.subSlices===undefined)
root.subSlices=[];root.subSlices.push(child);return true;}
return false;}
if(!this.slices.length)
return;var ops=[];for(var i=0;i< this.slices.length ; i + + ) { if ( this . slices [ i ] . subSlices )
this.slices[i].subSlices.splice(0,this.slices[i].subSlices.length);ops.push(i);}
var originalSlices=this.slices;ops.sort(function(ix,iy){var x=originalSlices[ix];var y=originalSlices[iy];if(x.start!=y.start)
return x.start-y.start;return ix-iy;});var slices=new Array(this.slices.length);for(var i=0;i< ops.length ; i + + ) { slices [ i ] = originalSlices [ ops [ i ] ] ; }
var rootSlice=slices[0];this.topLevelSlices=[];this.topLevelSlices.push(rootSlice);for(var i=1;i< slices.length ; i + + ) { var slice = slices[i];if(!addSliceIfBounds(rootSlice,slice)){rootSlice=slice;this.topLevelSlices.push(rootSlice);}}
this.slices=slices;},addCpuTimeToSubslices_:function(timeSlices){var SCHEDULING_STATE=tr.model.SCHEDULING_STATE;var sliceIdx=0;timeSlices.forEach(function(timeSlice){if(timeSlice.schedulingState==SCHEDULING_STATE.RUNNING){while(sliceIdx< this.topLevelSlices.length ) { if ( this . addCpuTimeToSubslice_ ( this . topLevelSlices [ sliceIdx ] , timeSlice ) ) { sliceIdx + + ; } else { break ; } } } } , this ) ; } , addCpuTimeToSubslice_:function ( slice , timeSlice ) { if ( slice . start > timeSlice.end||slice.end< timeSlice.start )
return slice.end< =timeSlice.end;var duration=timeSlice.duration;if(slice.start>timeSlice.start)
duration-=slice.start-timeSlice.start;if(timeSlice.end>slice.end)
duration-=timeSlice.end-slice.end;if(slice.cpuDuration){slice.cpuDuration+=duration;}else{slice.cpuDuration=duration;}
for(var i=0;i< slice.subSlices.length ; i + + ) { this . addCpuTimeToSubslice_ ( slice . subSlices [ i ] , timeSlice ) ; }
return slice.end< =timeSlice.end;}};SliceGroup.merge=function(groupA,groupB){if(groupA.openPartialSlices_.length>0)
throw new Error('groupA has open partial slices');if(groupB.openPartialSlices_.length>0)
throw new Error('groupB has open partial slices');if(groupA.parentContainer!=groupB.parentContainer)
throw new Error('Different parent threads. Cannot merge');if(groupA.sliceConstructor!=groupB.sliceConstructor)
throw new Error('Different slice constructors. Cannot merge');var result=new SliceGroup(groupA.parentContainer,groupA.sliceConstructor,groupA.name_);var slicesA=groupA.slices;var slicesB=groupB.slices;var idxA=0;var idxB=0;var openA=[];var openB=[];var splitOpenSlices=function(when){for(var i=0;i< openB.length ; i + + ) { var oldSlice = openB[i];var oldEnd = oldSlice.end;if(when<oldSlice.start||oldEnd<when){throw new Error ( ' slice should not be split ' ) ; }
var newSlice=result.copySlice(oldSlice);newSlice.start=when;newSlice.duration=oldEnd-when;if(newSlice.title.indexOf(' (cont.)')==-1)
newSlice.title+=' (cont.)';oldSlice.duration=when-oldSlice.start;openB[i]=newSlice;result.pushSlice(newSlice);}};var closeOpenSlices=function(upTo){while(openA.length>0||openB.length>0){var nextA=openA[openA.length-1];var nextB=openB[openB.length-1];var endA=nextA&&nextA.end; var endB=nextB&&nextB.end; if((endA===undefined||endA>upTo)&&(endB===undefined||endB>upTo)){return; }
if(endB===undefined||endA< endB ) { splitOpenSlices ( endA ) ; openA . pop ( ) ; } else { openB . pop ( ) ; } } } ; while ( idxA < slicesA . length | | idxB < slicesB . length ) { var sA = slicesA[idxA];var sB = slicesB[idxB];var nextSlice , isFromB ; if ( sA = ==undefined||(sB!==undefined&&sA.start > sB.start)){nextSlice=result.copySlice(sB);isFromB=true;idxB++;}else{nextSlice=result.copySlice(sA);isFromB=false;idxA++;}
closeOpenSlices(nextSlice.start);result.pushSlice(nextSlice);if(isFromB){openB.push(nextSlice);}else{splitOpenSlices(nextSlice.start);openA.push(nextSlice);}}
2015-06-18 08:27:29 -06:00
closeOpenSlices();return result;};return{SliceGroup:SliceGroup};});'use strict';tr.exportTo('tr.model',function(){function AsyncSlice(category,title,colorId,start,args,duration,opt_isTopLevel,opt_cpuStart,opt_cpuDuration,opt_argsStripped){tr.model.TimedEvent.call(this,start);this.category=category||'';this.title=title;this.colorId=colorId;this.args=args;this.startStackFrame=undefined;this.endStackFrame=undefined;this.didNotFinish=false;this.important=false;this.subSlices=[];this.parentContainer=undefined;this.id=undefined;this.startThread=undefined;this.endThread=undefined;this.cpuStart=undefined;this.cpuDuration=undefined;this.argsStripped=false;this.duration=duration;this.isTopLevel=(opt_isTopLevel===true);if(opt_cpuStart!==undefined)
2015-06-14 13:52:57 -06:00
this.cpuStart=opt_cpuStart;if(opt_cpuDuration!==undefined)
2015-06-18 08:27:29 -06:00
this.cpuDuration=opt_cpuDuration;if(opt_argsStripped!==undefined)
this.argsStripped=opt_argsStripped;};AsyncSlice.prototype={__proto__:tr.model.TimedEvent.prototype,get analysisTypeName(){return this.title;},get viewSubGroupTitle(){return this.title;},get userFriendlyName(){return'Async slice '+this.title+' at '+
2015-06-14 13:52:57 -06:00
tr.b.units.tsString(this.start);},findDescendentSlice:function(targetTitle){if(!this.subSlices)
return undefined;for(var i=0;i< this.subSlices.length ; i + + ) { if ( this . subSlices [ i ] . title = =targetTitle)
return this.subSlices[i];var slice=this.subSlices[i].findDescendentSlice(targetTitle);if(slice)return slice;}
2015-06-18 08:27:29 -06:00
return undefined;},iterateAllDescendents:function(callback,opt_this){this.subSlices.forEach(callback,opt_this);this.subSlices.forEach(function(subSlice){subSlice.iterateAllDescendents(callback,opt_this);},opt_this);},compareTo:function(that){return this.title.localeCompare(that.title);}};tr.model.EventRegistry.register(AsyncSlice,{name:'asyncSlice',pluralName:'asyncSlices',singleViewElementName:'tr-ui-a-single-async-slice-sub-view',multiViewElementName:'tr-ui-a-multi-async-slice-sub-view'});var options=new tr.b.ExtensionRegistryOptions(tr.b.TYPE_BASED_REGISTRY_MODE);options.mandatoryBaseClass=AsyncSlice;options.defaultConstructor=AsyncSlice;tr.b.decorateExtensionRegistry(AsyncSlice,options);return{AsyncSlice:AsyncSlice};});'use strict';tr.exportTo('tr.model',function(){function AsyncSliceGroup(parentContainer,opt_name){this.parentContainer_=parentContainer;this.guid_=tr.b.GUID.allocate();this.slices=[];this.bounds=new tr.b.Range();this.name_=opt_name;this.viewSubGroups_=undefined;}
2015-06-14 13:52:57 -06:00
AsyncSliceGroup.prototype={__proto__:tr.model.EventContainer.prototype,get guid(){return this.guid_;},get parentContainer(){return this.parentContainer_;},get model(){return this.parentContainer_.parent.model;},get stableId(){return this.parentContainer_.stableId+'.AsyncSliceGroup';},getSettingsKey:function(){if(!this.name_)
return undefined;var parentKey=this.parentContainer_.getSettingsKey();if(!parentKey)
return undefined;return parentKey+'.'+this.name_;},push:function(slice){slice.parentContainer=this.parentContainer;this.slices.push(slice);return slice;},get length(){return this.slices.length;},shiftTimestampsForward:function(amount){for(var sI=0;sI< this.slices.length ; sI + + ) { var slice = this.slices[sI];slice.start=(slice.start+amount);var shiftSubSlices = function(subSlices){if(subSlices===undefined||subSlices.length===0)
return;for(var sJ=0;sJ< subSlices.length ; sJ + + ) { subSlices [ sJ ] . start + = amount ; shiftSubSlices ( subSlices [ sJ ] . subSlices ) ; } } ; shiftSubSlices ( slice . subSlices ) ; } } , updateBounds:function ( ) { this . bounds . reset ( ) ; for ( var i = 0;i<this.slices.length;i++){this.bounds.addValue(this.slices[i].start);this.bounds.addValue(this.slices[i].end);}},get viewSubGroups ( ) { if ( this . viewSubGroups_ = ==undefined){var prefix = '' ; if ( this . name ! = = undefined )
prefix=this.name+'.';else
prefix='';var subGroupsByTitle={};for(var i=0;i< this.slices.length ; + + i ) { var slice = this.slices[i];var subGroupTitle = slice.viewSubGroupTitle;if(!subGroupsByTitle[subGroupTitle]){subGroupsByTitle[subGroupTitle]=new AsyncSliceGroup ( this . parentContainer_ , prefix + subGroupTitle ) ; }
subGroupsByTitle[subGroupTitle].push(slice);}
this.viewSubGroups_=tr.b.dictionaryValues(subGroupsByTitle);this.viewSubGroups_.sort(function(a,b){return a.slices[0].compareTo(b.slices[0]);});}
return this.viewSubGroups_;},iterateAllEventsInThisContainer:function(eventTypePredicate,callback,opt_this){if(eventTypePredicate.call(opt_this,tr.model.AsyncSlice)){for(var i=0;i< this.slices.length ; i + + ) { var slice = this.slices[i];callback.call(opt_this,slice);if(slice.subSlices)
slice.subSlices.forEach(callback,opt_this);}}},iterateAllChildEventContainers:function(callback,opt_this){}};return{AsyncSliceGroup:AsyncSliceGroup};});'use strict';tr.exportTo('tr.model',function(){var Slice=tr.model.Slice;var SliceGroup=tr.model.SliceGroup;var AsyncSlice=tr.model.AsyncSlice;var AsyncSliceGroup=tr.model.AsyncSliceGroup;var ThreadSlice=tr.model.ThreadSlice;var ThreadTimeSlice=tr.model.ThreadTimeSlice;function Thread(parent,tid){this.guid_=tr.b.GUID.allocate();if(!parent)
throw new Error('Parent must be provided.');this.parent=parent;this.sortIndex=0;this.tid=tid;this.name=undefined;this.samples_=undefined;var that=this;this.sliceGroup=new SliceGroup(this,ThreadSlice,'slices');this.timeSlices=undefined;this.kernelSliceGroup=new SliceGroup(this,ThreadSlice,'kernel-slices');this.asyncSliceGroup=new AsyncSliceGroup(this,'async-slices');this.bounds=new tr.b.Range();}
2015-06-18 08:27:29 -06:00
Thread.prototype={__proto__:tr.model.EventContainer.prototype,get guid(){return this.guid_;},get model(){return this.parent.model;},get stableId(){return this.parent.stableId+'.'+this.tid;},compareTo:function(that){return Thread.compare(this,that);},iterateAllChildEventContainers:function(callback,opt_this){if(this.sliceGroup.length)
2015-06-14 13:52:57 -06:00
callback.call(opt_this,this.sliceGroup);if(this.kernelSliceGroup.length)
callback.call(opt_this,this.kernelSliceGroup);if(this.asyncSliceGroup.length)
callback.call(opt_this,this.asyncSliceGroup);},iterateAllEventsInThisContainer:function(eventTypePredicate,callback,opt_this){if(this.timeSlices& & this.timeSlices.length){if(eventTypePredicate.call(opt_this,ThreadTimeSlice))
this.timeSlices.forEach(callback,opt_this);}},iterateAllPersistableObjects:function(cb){cb(this);if(this.sliceGroup.length)
cb(this.sliceGroup);this.asyncSliceGroup.viewSubGroups.forEach(cb);},shiftTimestampsForward:function(amount){this.sliceGroup.shiftTimestampsForward(amount);if(this.timeSlices){for(var i=0;i< this.timeSlices.length ; i + + ) { var slice = this.timeSlices[i];slice.start+=amount;}}
this.kernelSliceGroup.shiftTimestampsForward(amount);this.asyncSliceGroup.shiftTimestampsForward(amount);},get isEmpty(){if(this.sliceGroup.length)
return false;if(this.sliceGroup.openSliceCount)
return false;if(this.timeSlices& & this.timeSlices.length)
return false;if(this.kernelSliceGroup.length)
return false;if(this.asyncSliceGroup.length)
return false;if(this.samples_.length)
return false;return true;},updateBounds:function(){this.bounds.reset();this.sliceGroup.updateBounds();this.bounds.addRange(this.sliceGroup.bounds);this.kernelSliceGroup.updateBounds();this.bounds.addRange(this.kernelSliceGroup.bounds);this.asyncSliceGroup.updateBounds();this.bounds.addRange(this.asyncSliceGroup.bounds);if(this.timeSlices&&this.timeSlices.length){this.bounds.addValue(this.timeSlices[0].start); this.bounds.addValue(this.timeSlices[this.timeSlices.length-1].end);}
if(this.samples_&&this.samples_.length){this.bounds.addValue(this.samples_[0].start); this.bounds.addValue(this.samples_[this.samples_.length-1].end);}},addCategoriesToDict:function(categoriesDict){for(var i=0;i< this.sliceGroup.length ; i + + )
2015-06-18 08:27:29 -06:00
categoriesDict[this.sliceGroup.slices[i].category]=true;for(var i=0;i< this.kernelSliceGroup.length ; i + + )
categoriesDict[this.kernelSliceGroup.slices[i].category]=true;for(var i=0;i< this.asyncSliceGroup.length ; i + + )
categoriesDict[this.asyncSliceGroup.slices[i].category]=true;if(this.samples_){for(var i=0;i< this.samples_.length ; i + + )
categoriesDict[this.samples_[i].category]=true;}},autoCloseOpenSlices:function(opt_maxTimestamp){this.sliceGroup.autoCloseOpenSlices(opt_maxTimestamp);this.kernelSliceGroup.autoCloseOpenSlices(opt_maxTimestamp);},mergeKernelWithUserland:function(){if(this.kernelSliceGroup.length>0){var newSlices=SliceGroup.merge(this.sliceGroup,this.kernelSliceGroup);this.sliceGroup.slices=newSlices.slices;this.kernelSliceGroup=new SliceGroup(this);this.updateBounds();}},createSubSlices:function(){this.sliceGroup.createSubSlices();this.samples_=this.parent.model.samples.filter(function(sample){return sample.thread==this;},this);},get userFriendlyName(){return this.name||this.tid;},get userFriendlyDetails(){return'tid: '+this.tid+
(this.name?', name: '+this.name:'');},getSettingsKey:function(){if(!this.name)
return undefined;var parentKey=this.parent.getSettingsKey();if(!parentKey)
return undefined;return parentKey+'.'+this.name;},indexOfTimeSlice:function(timeSlice){var i=tr.b.findLowIndexInSortedArray(this.timeSlices,function(slice){return slice.start;},timeSlice.start);if(this.timeSlices[i]!==timeSlice)
return undefined;return i;},getSchedulingStatsForRange:function(start,end){var stats={};if(!this.timeSlices)return stats;function addStatsForSlice(threadTimeSlice){var overlapStart=Math.max(threadTimeSlice.start,start);var overlapEnd=Math.min(threadTimeSlice.end,end);var schedulingState=threadTimeSlice.schedulingState;if(!(schedulingState in stats))
stats[schedulingState]=0;stats[schedulingState]+=overlapEnd-overlapStart;}
tr.b.iterateOverIntersectingIntervals(this.timeSlices,function(x){return x.start;},function(x){return x.end;},start,end,addStatsForSlice);return stats;},get samples(){return this.samples_;}};Thread.compare=function(x,y){var tmp=x.parent.compareTo(y.parent);if(tmp)
return tmp;tmp=x.sortIndex-y.sortIndex;if(tmp)
return tmp;tmp=tr.b.comparePossiblyUndefinedValues(x.name,y.name,function(x,y){return x.localeCompare(y);});if(tmp)
return tmp;return x.tid-y.tid;};return{Thread:Thread};});'use strict';tr.exportTo('tr.model',function(){var Thread=tr.model.Thread;var Counter=tr.model.Counter;function ProcessBase(model){if(!model)
2015-06-14 13:52:57 -06:00
throw new Error('Must provide a model');tr.model.EventContainer.call(this);this.guid_=tr.b.GUID.allocate();this.model=model;this.threads={};this.counters={};this.objects=new tr.model.ObjectCollection(this);this.bounds=new tr.b.Range();this.sortIndex=0;};ProcessBase.compare=function(x,y){return x.sortIndex-y.sortIndex;};ProcessBase.prototype={__proto__:tr.model.EventContainer.prototype,get guid(){return this.guid_;},get stableId(){throw new Error('Not implemented');},iterateAllChildEventContainers:function(callback,opt_this){for(var tid in this.threads)
callback.call(opt_this,this.threads[tid]);for(var id in this.counters)
callback.call(opt_this,this.counters[id]);callback.call(opt_this,this.objects);},iterateAllEventsInThisContainer:function(eventTypePredicate,callback,opt_this){},iterateAllPersistableObjects:function(cb){cb(this);for(var tid in this.threads)
this.threads[tid].iterateAllPersistableObjects(cb);},get numThreads(){var n=0;for(var p in this.threads){n++;}
return n;},shiftTimestampsForward:function(amount){for(var tid in this.threads)
this.threads[tid].shiftTimestampsForward(amount);for(var id in this.counters)
this.counters[id].shiftTimestampsForward(amount);this.objects.shiftTimestampsForward(amount);},autoCloseOpenSlices:function(opt_maxTimestamp){for(var tid in this.threads){var thread=this.threads[tid];thread.autoCloseOpenSlices(opt_maxTimestamp);}},autoDeleteObjects:function(maxTimestamp){this.objects.autoDeleteObjects(maxTimestamp);},preInitializeObjects:function(){this.objects.preInitializeAllObjects();},initializeObjects:function(){this.objects.initializeAllObjects();},mergeKernelWithUserland:function(){for(var tid in this.threads){var thread=this.threads[tid];thread.mergeKernelWithUserland();}},updateBounds:function(){this.bounds.reset();for(var tid in this.threads){this.threads[tid].updateBounds();this.bounds.addRange(this.threads[tid].bounds);}
for(var id in this.counters){this.counters[id].updateBounds();this.bounds.addRange(this.counters[id].bounds);}
this.objects.updateBounds();this.bounds.addRange(this.objects.bounds);},addCategoriesToDict:function(categoriesDict){for(var tid in this.threads)
this.threads[tid].addCategoriesToDict(categoriesDict);for(var id in this.counters)
categoriesDict[this.counters[id].category]=true;this.objects.addCategoriesToDict(categoriesDict);},findAllThreadsMatching:function(predicate,opt_this){var threads=[];for(var tid in this.threads){var thread=this.threads[tid];if(predicate.call(opt_this,thread))
threads.push(thread);}
return threads;},findAllThreadsNamed:function(name){var threads=this.findAllThreadsMatching(function(thread){if(!thread.name)
return false;return thread.name===name;});return threads;},findAtMostOneThreadNamed:function(name){var threads=this.findAllThreadsNamed(name);if(threads.length===0)
return undefined;if(threads.length>1)
throw new Error('Expected no more than one '+name);return threads[0];},pruneEmptyContainers:function(){var threadsToKeep={};for(var tid in this.threads){var thread=this.threads[tid];if(!thread.isEmpty)
threadsToKeep[tid]=thread;}
this.threads=threadsToKeep;},getThread:function(tid){return this.threads[tid];},getOrCreateThread:function(tid){if(!this.threads[tid])
this.threads[tid]=new Thread(this,tid);return this.threads[tid];},getOrCreateCounter:function(cat,name){var id=cat+'.'+name;if(!this.counters[id])
this.counters[id]=new Counter(this,id,cat,name);return this.counters[id];},getSettingsKey:function(){throw new Error('Not implemented');},createSubSlices:function(){for(var tid in this.threads)
this.threads[tid].createSubSlices();}};return{ProcessBase:ProcessBase};});'use strict';tr.exportTo('tr.model',function(){var Cpu=tr.model.Cpu;var ProcessBase=tr.model.ProcessBase;function Kernel(model){ProcessBase.call(this,model);this.cpus={};this.softwareMeasuredCpuCount_=undefined;};Kernel.compare=function(x,y){return 0;};Kernel.prototype={__proto__:ProcessBase.prototype,compareTo:function(that){return Kernel.compare(this,that);},get userFriendlyName(){return'Kernel';},get userFriendlyDetails(){return'Kernel';},get stableId(){return'Kernel';},getOrCreateCpu:function(cpuNumber){if(!this.cpus[cpuNumber])
this.cpus[cpuNumber]=new Cpu(this,cpuNumber);return this.cpus[cpuNumber];},get softwareMeasuredCpuCount(){return this.softwareMeasuredCpuCount_;},set softwareMeasuredCpuCount(softwareMeasuredCpuCount){if(this.softwareMeasuredCpuCount_!==undefined& & this.softwareMeasuredCpuCount_!==softwareMeasuredCpuCount){throw new Error('Cannot change the softwareMeasuredCpuCount once it is set');}
this.softwareMeasuredCpuCount_=softwareMeasuredCpuCount;},get bestGuessAtCpuCount(){var realCpuCount=tr.b.dictionaryLength(this.cpus);if(realCpuCount!==0)
return realCpuCount;return this.softwareMeasuredCpuCount;},shiftTimestampsForward:function(amount){ProcessBase.prototype.shiftTimestampsForward.call(this,amount);for(var cpuNumber in this.cpus)
this.cpus[cpuNumber].shiftTimestampsForward(amount);},updateBounds:function(){ProcessBase.prototype.updateBounds.call(this);for(var cpuNumber in this.cpus){var cpu=this.cpus[cpuNumber];cpu.updateBounds();this.bounds.addRange(cpu.bounds);}},createSubSlices:function(){ProcessBase.prototype.createSubSlices.call(this);for(var cpuNumber in this.cpus){var cpu=this.cpus[cpuNumber];cpu.createSubSlices();}},addCategoriesToDict:function(categoriesDict){ProcessBase.prototype.addCategoriesToDict.call(this,categoriesDict);for(var cpuNumber in this.cpus)
this.cpus[cpuNumber].addCategoriesToDict(categoriesDict);},getSettingsKey:function(){return'kernel';},iterateAllChildEventContainers:function(callback,opt_this){ProcessBase.prototype.iterateAllChildEventContainers.call(this,callback,opt_this);for(var cpuId in this.cpus)
2015-06-18 08:27:29 -06:00
callback.call(opt_this,this.cpus[cpuId]);},iterateAllEventsInThisContainer:function(eventTypePredicate,callback,opt_this){ProcessBase.prototype.iterateAllEventsInThisContainer.call(this,eventTypePredicate,callback,opt_this);}};return{Kernel:Kernel};});'use strict';tr.exportTo('tr.model',function(){function Attribute(units){this.units=units;this.infos=[];}
2015-06-14 13:52:57 -06:00
Attribute.fromDictIfPossible=function(dict,opt_model){var typeInfo=Attribute.findTypeInfoMatching(function(typeInfo){return typeInfo.metadata.type===dict.type;});if(typeInfo===undefined){if(opt_model){opt_model.importWarning({type:'attribute_parse_error',message:'Unknown attribute type \''+dict.type+'\'.'});}
return UnknownAttribute.fromDict(dict,opt_model);}
return typeInfo.constructor.fromDict(dict,opt_model);};Attribute.findCommonTraits=function(attributes,opt_model){var commonTraits;for(var i=0;i< attributes.length ; i + + ) { var attribute = attributes[i];if(attribute===undefined)
continue;var attributeConstructor=attribute.constructor;var attributeUnits=attribute.units;if(commonTraits===undefined){commonTraits={constructor:attributeConstructor,units:attributeUnits};}else if(attributeConstructor!==commonTraits.constructor){if(opt_model){opt_model.importWarning({type:'attribute_parse_error',message:'Attribute with different types: '+
commonTraits.constructor+' and '+attributeConstructor+'.'});}
commonTraits={constructor:UnknownAttribute,units:undefined};break;}else if(attributeUnits!==commonTraits.units){if(opt_model){opt_model.importWarning({type:'attribute_parse_error',message:'Attribute with different units: '+commonTraits.units+' and '+attributeUnits+'.'});}
commonTraits={constructor:UnknownAttribute,units:undefined};break;}}
return commonTraits;};Attribute.aggregate=function(childAttributes,existingParentAttribute,opt_model){var definedChildAttributes=childAttributes.filter(function(childAttribute){return childAttribute!==undefined;});var traits=Attribute.findCommonTraits(definedChildAttributes,opt_model);if(traits===undefined)
return existingParentAttribute;var constructor=traits.constructor;if(constructor.merge===undefined)
return existingParentAttribute;var mergedAttribute=constructor.merge(definedChildAttributes,traits.units,opt_model);if(existingParentAttribute===undefined)
return mergedAttribute;existingParentAttribute.useMergedAttribute(mergedAttribute,opt_model);return existingParentAttribute;}
Attribute.fromTraceValue=function(dict,opt_model){throw new Error('Not implemented');};Attribute.prototype.useMergedAttribute=function(mergedAttribute,opt_model){if(mergedAttribute.constructor!==this.constructor){if(opt_model){opt_model.importWarning({type:'attribute_parse_error',message:'Attribute with different types: '+this.constructor+' and '+mergedAttribute.constructor+'.'});}}else if(mergedAttribute.units!==this.units){if(opt_model){opt_model.importWarning({type:'attribute_parse_error',message:'Attribute with different units: '+this.units+' and '+mergedAttribute.units+'.'});}}};var options=new tr.b.ExtensionRegistryOptions(tr.b.BASIC_REGISTRY_MODE);options.mandatoryBaseType=Attribute;tr.b.decorateExtensionRegistry(Attribute,options);Attribute.addEventListener('will-register',function(e){if(!e.typeInfo.constructor.hasOwnProperty('fromDict'))
throw new Error('Attributes must have fromDict method');if(!e.typeInfo.metadata.type)
throw new Error('Attributes must provide type');if(e.typeInfo.constructor.prototype.constructor!==e.typeInfo.constructor)
throw new Error('Attribute prototypes must provide constructor.');});function ScalarAttribute(units,value){Attribute.call(this,units);this.value=value;}
ScalarAttribute.fromDict=function(dict){return new ScalarAttribute(dict.units,parseInt(dict.value,16));};ScalarAttribute.merge=function(childAttributes,units){var sum=0;childAttributes.forEach(function(childAttribute){sum+=childAttribute.value;});return new ScalarAttribute(units,sum);}
ScalarAttribute.prototype.__proto__=Attribute.prototype;Attribute.register(ScalarAttribute,{type:'scalar'});function StringAttribute(units,value){Attribute.call(this,units);this.value=value;}
StringAttribute.fromDict=function(dict){return new StringAttribute(dict.units,dict.value);};Attribute.register(StringAttribute,{type:'string'});function UnknownAttribute(units,opt_value){Attribute.call(this,units,opt_value);this.value=opt_value;}
2015-06-18 08:27:29 -06:00
UnknownAttribute.fromDict=function(dict){return new UnknownAttribute(dict.units);};UnknownAttribute.prototype.__proto__=Attribute.prototype;function AttributeInfo(type,message){this.type=type;this.message=message;}
var AttributeInfoType={INFORMATION:0,WARNING:1,LINK:2};return{Attribute:Attribute,ScalarAttribute:ScalarAttribute,StringAttribute:StringAttribute,UnknownAttribute:UnknownAttribute,AttributeInfo:AttributeInfo,AttributeInfoType:AttributeInfoType};});'use strict';tr.exportTo('tr.model',function(){function ContainerMemoryDump(start){tr.model.TimedEvent.call(this,start);this.memoryAllocatorDumps_=undefined;this.memoryAllocatorDumpsByFullName_=undefined;};ContainerMemoryDump.prototype={__proto__:tr.model.TimedEvent.prototype,shiftTimestampsForward:function(amount){this.start+=amount;},get memoryAllocatorDumps(){return this.memoryAllocatorDumps_;},set memoryAllocatorDumps(memoryAllocatorDumps){this.memoryAllocatorDumps_=memoryAllocatorDumps;this.memoryAllocatorDumpsByFullName_=undefined;},getMemoryAllocatorDumpByFullName:function(fullName){if(this.memoryAllocatorDumps_===undefined)
2015-06-14 13:52:57 -06:00
return undefined;if(this.memoryAllocatorDumpsByFullName_===undefined){var index={};function addDumpsToIndex(dumps){dumps.forEach(function(dump){index[dump.fullName]=dump;addDumpsToIndex(dump.children);});};addDumpsToIndex(this.memoryAllocatorDumps_);this.memoryAllocatorDumpsByFullName_=index;}
2015-06-18 08:27:29 -06:00
return this.memoryAllocatorDumpsByFullName_[fullName];}};return{ContainerMemoryDump:ContainerMemoryDump};});'use strict';tr.exportTo('tr.model',function(){function MemoryAllocatorDump(containerMemoryDump,fullName,opt_guid){this.fullName=fullName;this.parent=undefined;this.children=[];this.attributes={};this.containerMemoryDump=containerMemoryDump;this.owns=undefined;this.ownedBy=[];this.retains=[];this.retainedBy=[];this.guid=opt_guid;};MemoryAllocatorDump.prototype={get name(){return this.fullName.substring(this.fullName.lastIndexOf('/')+1);},isDescendantOf:function(otherDump){var dump=this;while(dump!==undefined){if(dump===otherDump)
return true;dump=dump.parent;}
return false;},addAttribute:function(name,value){if(name in this.attributes)
throw new Error('Duplicate attribute name: '+name+'.');this.attributes[name]=value;},aggregateAttributes:function(opt_model){var attributes={};this.children.forEach(function(child){child.aggregateAttributes(opt_model);tr.b.iterItems(child.attributes,function(name){attributes[name]=true;},this);},this);tr.b.iterItems(attributes,function(name){var childAttributes=this.children.map(function(child){return child.attributes[name];},this);var currentAttribute=this.attributes[name];this.attributes[name]=tr.model.Attribute.aggregate(childAttributes,currentAttribute,opt_model);},this);},getValidSizeAttributeOrUndefined:function(sizeAttrName,opt_model){var sizeAttr=this.attributes[sizeAttrName];if(sizeAttr===undefined)
2015-06-14 13:52:57 -06:00
return undefined;if(!(sizeAttr instanceof tr.model.ScalarAttribute)){if(opt_model!==undefined){opt_model.importWarning({type:'memory_dump_parse_error',message:'\''+sizeAttrName+'\' attribute of memory allocator '+'dump \''+memoryAllocatorDump.fullName+'\' is not a scalar.'});}
return undefined;}
2015-06-18 08:27:29 -06:00
return sizeAttr;}};function MemoryAllocatorDumpLink(source,target,opt_importance){this.source=source;this.target=target;this.importance=opt_importance;}
return{MemoryAllocatorDump:MemoryAllocatorDump,MemoryAllocatorDumpLink:MemoryAllocatorDumpLink};});'use strict';tr.exportTo('tr.model',function(){var DISCOUNTED_ALLOCATOR_NAMES=['winheap','malloc'];function ProcessMemoryDump(globalMemoryDump,process,start){tr.model.ContainerMemoryDump.call(this,start);this.process=process;this.globalMemoryDump=globalMemoryDump;this.totalResidentBytes=undefined;this.vmRegions_=undefined;this.tracingMemoryDiscounted_=false;};ProcessMemoryDump.prototype={__proto__:tr.model.ContainerMemoryDump.prototype,get userFriendlyName(){return'Process memory dump at '+tr.b.units.tsString(this.start);},get vmRegions(){throw new Error('VM regions must be accessed through the mostRecentVmRegions field');},set vmRegions(vmRegions){this.vmRegions_=vmRegions;},get hasOwnVmRegions(){return this.vmRegions_!==undefined;},getMostRecentTotalVmRegionStat:function(statName){if(this.mostRecentVmRegions===undefined)
2015-06-14 13:52:57 -06:00
return undefined;var total=0;this.mostRecentVmRegions.forEach(function(vmRegion){var statValue=vmRegion.byteStats[statName];if(statValue===undefined)
return;total+=statValue;});return total;},discountTracingOverhead:function(opt_model){if(this.tracingMemoryDiscounted_)
return;this.tracingMemoryDiscounted_=true;var tracingDump=this.getMemoryAllocatorDumpByFullName('tracing');if(tracingDump===undefined)
2015-06-18 08:27:29 -06:00
return;var tracingResidentSizeAttr=tracingDump.getValidSizeAttributeOrUndefined('resident_size',opt_model);if(tracingResidentSizeAttr!==undefined){var tracingResidentSize=tracingResidentSizeAttr.value;if(this.totalResidentBytes!==undefined)
2015-06-14 13:52:57 -06:00
this.totalResidentBytes-=tracingResidentSize;if(this.vmRegions_!==undefined){this.vmRegions_.push(VMRegion.fromDict({mappedFile:'[discounted tracing overhead]',byteStats:{privateDirtyResident:-tracingResidentSize,proportionalResident:-tracingResidentSize}}));}}
2015-06-18 08:27:29 -06:00
var tracingSizeAttr=tracingDump.getValidSizeAttributeOrUndefined('size',opt_model);if(tracingSizeAttr!==undefined){var tracingSize=tracingSizeAttr.value;var hasDiscountedFromAllocatorDumps=DISCOUNTED_ALLOCATOR_NAMES.some(function(allocatorName){var dump=this.getMemoryAllocatorDumpByFullName(allocatorName);if(dump===undefined)
return false;var overheadSizeAttribute=new tr.model.ScalarAttribute('bytes',-tracingSize);var overheadDump=new tr.model.MemoryAllocatorDump(this,allocatorName+'/discounted_tracing_overhead');overheadDump.parent=dump;overheadDump.addAttribute('size',overheadSizeAttribute);dump.children.push(overheadDump);var dumpSizeAttr=dump.getValidSizeAttributeOrUndefined('size',opt_model);if(dumpSizeAttr!==undefined)
2015-06-14 13:52:57 -06:00
dumpSizeAttr.value-=tracingSize;return true;},this);if(hasDiscountedFromAllocatorDumps)
this.memoryAllocatorDumps=this.memoryAllocatorDumps;}}};ProcessMemoryDump.hookUpMostRecentVmRegionsLinks=function(processDumps){var mostRecentVmRegions=undefined;processDumps.forEach(function(processDump){if(processDump.vmRegions_!==undefined)
mostRecentVmRegions=processDump.vmRegions_;processDump.mostRecentVmRegions=mostRecentVmRegions;});};function VMRegion(startAddress,sizeInBytes,protectionFlags,mappedFile,byteStats){this.startAddress=startAddress;this.sizeInBytes=sizeInBytes;this.protectionFlags=protectionFlags;this.mappedFile=mappedFile;this.byteStats=byteStats;};VMRegion.PROTECTION_FLAG_READ=4;VMRegion.PROTECTION_FLAG_WRITE=2;VMRegion.PROTECTION_FLAG_EXECUTE=1;VMRegion.prototype={get protectionFlagsToString(){if(this.protectionFlags===undefined)
return undefined;return((this.protectionFlags& VMRegion.PROTECTION_FLAG_READ?'r':'-')+
(this.protectionFlags& VMRegion.PROTECTION_FLAG_WRITE?'w':'-')+
(this.protectionFlags&VMRegion.PROTECTION_FLAG_EXECUTE?'x':'-')); }};VMRegion.fromDict=function(dict){return new VMRegion(dict.startAddress,dict.sizeInBytes,dict.protectionFlags,dict.mappedFile,VMRegionByteStats.fromDict(dict.byteStats));};function VMRegionByteStats(privateCleanResident,privateDirtyResident,sharedCleanResident,sharedDirtyResident,proportionalResident,swapped){this.privateCleanResident=privateCleanResident;this.privateDirtyResident=privateDirtyResident;this.sharedCleanResident=sharedCleanResident;this.sharedDirtyResident=sharedDirtyResident;this.proportionalResident=proportionalResident;this.swapped=swapped;}
VMRegionByteStats.fromDict=function(dict){return new VMRegionByteStats(dict.privateCleanResident,dict.privateDirtyResident,dict.sharedCleanResident,dict.sharedDirtyResident,dict.proportionalResident,dict.swapped);}
2015-06-18 08:27:29 -06:00
tr.model.EventRegistry.register(ProcessMemoryDump,{name:'processMemoryDump',pluralName:'processMemoryDumps',singleViewElementName:'tr-ui-a-single-process-memory-dump-sub-view',multiViewElementName:'tr-ui-a-multi-process-memory-dump-sub-view'});return{ProcessMemoryDump:ProcessMemoryDump,VMRegion:VMRegion,VMRegionByteStats:VMRegionByteStats};});'use strict';tr.exportTo('tr.model',function(){var ProcessBase=tr.model.ProcessBase;var ProcessInstantEvent=tr.model.ProcessInstantEvent;var Frame=tr.model.Frame;var ProcessMemoryDump=tr.model.ProcessMemoryDump;function Process(model,pid){if(model===undefined)
2015-06-14 13:52:57 -06:00
throw new Error('model must be provided');if(pid===undefined)
throw new Error('pid must be provided');tr.model.ProcessBase.call(this,model);this.pid=pid;this.name=undefined;this.labels=[];this.instantEvents=[];this.memoryDumps=[];this.frames=[];};Process.compare=function(x,y){var tmp=tr.model.ProcessBase.compare(x,y);if(tmp)
return tmp;tmp=tr.b.comparePossiblyUndefinedValues(x.name,y.name,function(x,y){return x.localeCompare(y);});if(tmp)
return tmp;tmp=tr.b.compareArrays(x.labels,y.labels,function(x,y){return x.localeCompare(y);});if(tmp)
return tmp;return x.pid-y.pid;};Process.prototype={__proto__:tr.model.ProcessBase.prototype,get stableId(){return this.pid;},compareTo:function(that){return Process.compare(this,that);},iterateAllChildEventContainers:function(callback,opt_this){ProcessBase.prototype.iterateAllChildEventContainers.call(this,callback,opt_this);},iterateAllEventsInThisContainer:function(eventTypePredicate,callback,opt_this){ProcessBase.prototype.iterateAllEventsInThisContainer.call(this,eventTypePredicate,callback,opt_this);if(eventTypePredicate.call(opt_this,ProcessInstantEvent))
this.instantEvents.forEach(callback,opt_this);if(eventTypePredicate.call(opt_this,Frame))
this.frames.forEach(callback,opt_this);if(eventTypePredicate.call(opt_this,ProcessMemoryDump))
this.memoryDumps.forEach(callback,opt_this);},pushInstantEvent:function(instantEvent){this.instantEvents.push(instantEvent);},addLabelIfNeeded:function(labelName){for(var i=0;i< this.labels.length ; i + + ) { if ( this . labels [ i ] = = = labelName )
return;}
this.labels.push(labelName);},get userFriendlyName(){var res;if(this.name)
res=this.name+' (pid '+this.pid+')';else
res='Process '+this.pid;if(this.labels.length)
res+=': '+this.labels.join(', ');return res;},get userFriendlyDetails(){if(this.name)
return this.name+' (pid '+this.pid+')';return'pid: '+this.pid;},getSettingsKey:function(){if(!this.name)
return undefined;if(!this.labels.length)
return'processes.'+this.name;return'processes.'+this.name+'.'+this.labels.join('.');},shiftTimestampsForward:function(amount){for(var id in this.instantEvents)
this.instantEvents[id].start+=amount;for(var i=0;i< this.frames.length ; i + + )
this.frames[i].shiftTimestampsForward(amount);for(var i=0;i< this.memoryDumps.length ; i + + )
this.memoryDumps[i].shiftTimestampsForward(amount);tr.model.ProcessBase.prototype.shiftTimestampsForward.apply(this,arguments);},updateBounds:function(){tr.model.ProcessBase.prototype.updateBounds.apply(this);for(var i=0;i< this.frames.length ; i + + )
this.frames[i].addBoundsToRange(this.bounds);for(var i=0;i< this.memoryDumps.length ; i + + )
this.memoryDumps[i].addBoundsToRange(this.bounds);},sortMemoryDumps:function(){this.memoryDumps.sort(function(x,y){return x.start-y.start;});tr.model.ProcessMemoryDump.hookUpMostRecentVmRegionsLinks(this.memoryDumps);}};return{Process:Process};});'use strict';tr.exportTo('tr.model',function(){function Sample(cpu,thread,title,start,leafStackFrame,opt_weight,opt_args){tr.model.TimedEvent.call(this,start);this.title=title;this.cpu=cpu;this.thread=thread;this.leafStackFrame=leafStackFrame;this.weight=opt_weight;this.args=opt_args||{};}
Sample.prototype={__proto__:tr.model.TimedEvent.prototype,get colorId(){return this.leafStackFrame.colorId;},get stackTrace(){return this.leafStackFrame.stackTrace;},getUserFriendlyStackTrace:function(){return this.leafStackFrame.getUserFriendlyStackTrace();},get userFriendlyName(){return'Sample '+' at '+
2015-06-18 08:27:29 -06:00
tr.b.units.tsString(this.start);}};tr.model.EventRegistry.register(Sample,{name:'sample',pluralName:'samples',singleViewElementName:'tr-ui-a-single-sample-sub-view',multiViewElementName:'tr-ui-a-multi-sample-sub-view'});return{Sample:Sample};});'use strict';tr.exportTo('tr.model',function(){function StackFrame(parentFrame,id,category,title,colorId){if(id===undefined)
2015-06-14 13:52:57 -06:00
throw new Error('id must be given');this.parentFrame_=parentFrame;this.id=id;this.category=category||'';this.title=title;this.colorId=colorId;this.children=[];if(this.parentFrame_)
this.parentFrame_.addChild(this);}
StackFrame.prototype={get parentFrame(){return this.parentFrame_;},set parentFrame(parentFrame){if(this.parentFrame_)
this.parentFrame_.removeChild(this);this.parentFrame_=parentFrame;if(this.parentFrame_)
this.parentFrame_.addChild(this);},addChild:function(child){this.children.push(child);},removeChild:function(child){var i=this.children.indexOf(child.id);if(i==-1)
throw new Error('omg');this.children.splice(i,1);},removeAllChildren:function(){for(var i=0;i< this.children.length ; i + + )
this.children[i].parentFrame_=undefined;this.children.splice(0,this.children.length);},get stackTrace(){var stack=[];var cur=this;while(cur){stack.push(cur);cur=cur.parentFrame;}
stack.reverse();return stack;},getUserFriendlyStackTrace:function(){return this.stackTrace.map(function(x){return x.category+': '+x.title;});}};return{StackFrame:StackFrame};});'use strict';tr.exportTo('tr.model',function(){var InstantEventType={GLOBAL:1,PROCESS:2};function InstantEvent(category,title,colorId,start,args){tr.model.TimedEvent.call(this);this.category=category||'';this.title=title;this.colorId=colorId;this.start=start;this.args=args;this.type=undefined;};InstantEvent.prototype={__proto__:tr.model.TimedEvent.prototype};function GlobalInstantEvent(category,title,colorId,start,args){InstantEvent.apply(this,arguments);this.type=InstantEventType.GLOBAL;};GlobalInstantEvent.prototype={__proto__:InstantEvent.prototype,get userFriendlyName(){return'Global instant event '+this.title+' @ '+
this.tsString(start);}};function ProcessInstantEvent(category,title,colorId,start,args){InstantEvent.apply(this,arguments);this.type=InstantEventType.PROCESS;};ProcessInstantEvent.prototype={__proto__:InstantEvent.prototype,get userFriendlyName(){return'Process-level instant event '+this.title+' @ '+
2015-06-18 08:27:29 -06:00
this.tsString(start);}};tr.model.EventRegistry.register(InstantEvent,{name:'instantEvent',pluralName:'instantEvents',singleViewElementName:'tr-ui-a-single-instant-event-sub-view',multiViewElementName:'tr-ui-a-multi-instant-event-sub-view'});return{GlobalInstantEvent:GlobalInstantEvent,ProcessInstantEvent:ProcessInstantEvent,InstantEventType:InstantEventType,InstantEvent:InstantEvent};});'use strict';tr.exportTo('tr.model',function(){function FlowEvent(category,id,title,colorId,start,args,opt_duration){tr.model.TimedEvent.call(this,start);this.category=category||'';this.title=title;this.colorId=colorId;this.start=start;this.args=args;this.id=id;this.startSlice=undefined;this.endSlice=undefined;if(opt_duration!==undefined)
2015-06-14 13:52:57 -06:00
this.duration=opt_duration;}
FlowEvent.prototype={__proto__:tr.model.TimedEvent.prototype,get userFriendlyName(){return'Flow event named '+this.title+' at '+
2015-06-18 08:27:29 -06:00
tr.b.units.tsString(this.timestamp);}};tr.model.EventRegistry.register(FlowEvent,{name:'flowEvent',pluralName:'flowEvents',singleViewElementName:'tr-ui-a-single-flow-event-sub-view',multiViewElementName:'tr-ui-a-multi-flow-event-sub-view'});return{FlowEvent:FlowEvent};});'use strict';tr.exportTo('tr.b.units',function(){var UNIT_PREFIXES=['','Ki','Mi','Gi','Ti'];function SizeInBytes(numBytes){this.numBytes=numBytes;};SizeInBytes.prototype={toString:function(){return SizeInBytes.format(this.numBytes);}};SizeInBytes.format=function(numBytes){var signPrefix='';if(numBytes< 0 ) { signPrefix = '-' ; numBytes = -numBytes;}
var i=0;while(numBytes>=1024&&i<UNIT_PREFIXES.length-1){numBytes/=1024; i++;}
return signPrefix+numBytes.toFixed(1)+' '+UNIT_PREFIXES[i]+'B';};return{SizeInBytes:SizeInBytes};});'use strict';tr.exportTo('tr.model',function(){function GlobalMemoryDump(model,start){tr.model.ContainerMemoryDump.call(this,start);this.model=model;this.processMemoryDumps={};}
var SIZE_ATTRIBUTE_NAME='size';GlobalMemoryDump.prototype={__proto__:tr.model.ContainerMemoryDump.prototype,get userFriendlyName(){return'Global memory dump at '+tr.b.units.tsString(this.start);},calculateGraphAttributes:function(){this.calculateSizes();this.aggregateAttributes();this.discountTracingOverhead();},calculateSizes:function(){this.traverseAllocatorDumpsInDepthFirstPostOrder(this.calculateMemoryAllocatorDumpSize_);},calculateMemoryAllocatorDumpSize_:function(dump){var shouldDefineSize=false;function getDependencySize(dependencyDump){var attr=dependencyDump.attributes[SIZE_ATTRIBUTE_NAME];if(attr===undefined)
return 0;shouldDefineSize=true;return attr.value;}
var sizeAttribute=dump.getValidSizeAttributeOrUndefined(SIZE_ATTRIBUTE_NAME,this.model);var size=0;var infos=[];var checkDependentSizeIsConsistent=function(){};if(sizeAttribute!==undefined){size=sizeAttribute.value;shouldDefineSize=true;checkDependentSizeIsConsistent=function(dependentSize,dependentName){if(size>=dependentSize)
return;var messageSuffix=' ('+tr.b.units.SizeInBytes.format(size)+') is less than '+dependentName+' ('+
tr.b.units.SizeInBytes.format(dependentSize)+').';this.model.importWarning({type:'memory_dump_parse_error',message:'Size provided by memory allocator dump \''+
dump.fullName+'\''+messageSuffix});infos.push(new tr.model.AttributeInfo(tr.model.AttributeInfoType.WARNING,'Size provided by this memory allocator dump'+messageSuffix));}.bind(this);}
var aggregatedChildrenSize=0;var allOverlaps={};dump.children.forEach(function(childDump){function aggregateDescendantDump(descendantDump){var ownedDumpLink=descendantDump.owns;if(ownedDumpLink!==undefined& & ownedDumpLink.target.isDescendantOf(dump)){var ownedDescendantDump=ownedDumpLink.target;var ownedChildDump=ownedDescendantDump;while(ownedChildDump.parent!==dump)
ownedChildDump=ownedChildDump.parent;if(childDump!==ownedChildDump){var overlap=getDependencySize(descendantDump);if(overlap>0){var ownedChildOverlaps=allOverlaps[ownedChildDump.name];if(ownedChildOverlaps===undefined)
allOverlaps[ownedChildDump.name]=ownedChildOverlaps={};var previousTotalOverlap=ownedChildOverlaps[childDump.name]||0;var updatedTotalOverlap=previousTotalOverlap+overlap;ownedChildOverlaps[childDump.name]=updatedTotalOverlap;}}
return;}
if(descendantDump.children.length===0){aggregatedChildrenSize+=getDependencySize(descendantDump);return;}
descendantDump.children.forEach(aggregateDescendantDump);}
aggregateDescendantDump(childDump);});dump.children.forEach(function(childDump){var childOverlaps=allOverlaps[childDump.name];if(childOverlaps===undefined)
return;var message=tr.b.dictionaryValues(tr.b.mapItems(childOverlaps,function(ownerChildName,overlap){return'This memory allocator dump overlaps with its sibling \''+
ownerChildName+'\' ('+
tr.b.units.SizeInBytes.format(overlap)+').';})).join(' ');childDump.attributes[SIZE_ATTRIBUTE_NAME].infos.push(new tr.model.AttributeInfo(tr.model.AttributeInfoType.INFORMATION,message));});checkDependentSizeIsConsistent(aggregatedChildrenSize,'the aggregated size of its children');var largestOwnerSize=0;dump.ownedBy.forEach(function(ownershipLink){var owner=ownershipLink.source;var ownerSize=getDependencySize(owner);largestOwnerSize=Math.max(largestOwnerSize,ownerSize);});checkDependentSizeIsConsistent(largestOwnerSize,'the size of its largest owner');if(!shouldDefineSize){dump.attributes[SIZE_ATTRIBUTE_NAME]=undefined;return;}
size=Math.max(size,aggregatedChildrenSize,largestOwnerSize);var sizeAttribute=new tr.model.ScalarAttribute('bytes',size);sizeAttribute.infos=infos;dump.attributes[SIZE_ATTRIBUTE_NAME]=sizeAttribute;if(aggregatedChildrenSize< size & & dump . children ! = = undefined & & dump . children . length > 0){var virtualChild=new tr.model.MemoryAllocatorDump(dump.containerMemoryDump,dump.fullName+'/< unspecified > ');virtualChild.parent=dump;dump.children.unshift(virtualChild);virtualChild.attributes[SIZE_ATTRIBUTE_NAME]=new tr.model.ScalarAttribute('bytes',size-aggregatedChildrenSize);}},aggregateAttributes:function(){this.iterateRootAllocatorDumps(function(dump){dump.aggregateAttributes(this.model);});},discountTracingOverhead:function(){tr.b.iterItems(this.processMemoryDumps,function(pid,dump){dump.discountTracingOverhead(this.model);},this);},iterateContainerDumps:function(fn){fn.call(this,this);tr.b.iterItems(this.processMemoryDumps,function(pid,processDump){fn.call(this,processDump);},this);},iterateRootAllocatorDumps:function(fn){this.iterateContainerDumps(function(containerDump){var memoryAllocatorDumps=containerDump.memoryAllocatorDumps;if(memoryAllocatorDumps===undefined)
return;memoryAllocatorDumps.forEach(fn,this);});},traverseAllocatorDumpsInDepthFirstPostOrder:function(fn){var visitedDumps=new WeakSet();var openDumps=new WeakSet();function visit(dump){if(visitedDumps.has(dump))
return;if(openDumps.has(dump))
throw new Error(dump.userFriendlyName+' contains a cycle');openDumps.add(dump);dump.ownedBy.forEach(function(ownershipLink){visit.call(this,ownershipLink.source);},this);dump.children.forEach(visit,this);fn.call(this,dump);openDumps.delete(dump);visitedDumps.add(dump);}
this.iterateRootAllocatorDumps(visit);}};tr.model.EventRegistry.register(GlobalMemoryDump,{name:'globalMemoryDump',pluralName:'globalMemoryDumps',singleViewElementName:'tr-ui-a-single-global-memory-dump-sub-view',multiViewElementName:'tr-ui-a-multi-global-memory-dump-sub-view'});return{GlobalMemoryDump:GlobalMemoryDump};});'use strict';tr.exportTo('tr.model',function(){function EventInfo(title,description,docLinks){this.title=title;this.description=description;this.docLinks=docLinks;this.colorId=tr.ui.b.getColorIdForGeneralPurposeString(title);}
return{EventInfo:EventInfo};});'use strict';tr.exportTo('tr.model',function(){function Alert(info,start,opt_associatedEvents,opt_args){tr.model.TimedEvent.call(this,start);this.info=info;this.args=opt_args||{};this.associatedEvents=new tr.c.Selection(opt_associatedEvents);this.associatedEvents.forEach(function(event){event.associatedAlerts.push(this);},this);}
2015-06-14 13:52:57 -06:00
Alert.prototype={__proto__:tr.model.TimedEvent.prototype,get title(){return this.info.title;},get colorId(){return this.info.colorId;},get userFriendlyName(){return'Alert '+this.title+' at '+
2015-06-18 08:27:29 -06:00
tr.b.units.tsString(this.start);}};tr.model.EventRegistry.register(Alert,{name:'alert',pluralName:'alerts',singleViewElementName:'tr-ui-a-alert-sub-view',multiViewElementName:'tr-ui-a-alert-sub-view'});return{Alert:Alert};});'use strict';tr.exportTo('tr.model',function(){function InteractionRecord(title,colorId,start,duration){tr.model.TimedEvent.call(this,start);this.title=title;this.colorId=colorId;this.duration=duration;this.args={};this.associatedEvents=new tr.c.Selection();}
2015-06-14 13:52:57 -06:00
InteractionRecord.prototype={__proto__:tr.model.TimedEvent.prototype,get subSlices(){return[];},get userFriendlyName(){return this.title+' interaction at '+
2015-06-18 08:27:29 -06:00
tr.b.units.tsString(this.start);}};tr.model.EventRegistry.register(InteractionRecord,{name:'interaction',pluralName:'interactions',singleViewElementName:'tr-ui-a-single-interaction-record-sub-view',multiViewElementName:'tr-ui-a-multi-interaction-record-sub-view'});return{InteractionRecord:InteractionRecord};});'use strict';tr.exportTo('tr.model',function(){function ModelIndices(model){this.flowEventsById_={};model.flowEvents.forEach(function(fe){if(fe.id!==undefined){if(!this.flowEventsById_.hasOwnProperty(fe.id)){this.flowEventsById_[fe.id]=new Array();}
2015-06-14 13:52:57 -06:00
this.flowEventsById_[fe.id].push(fe);}},this);}
ModelIndices.prototype={addEventWithId:function(id,event){if(!this.flowEventsById_.hasOwnProperty(id)){this.flowEventsById_[id]=new Array();}
this.flowEventsById_[id].push(event);},getFlowEventsWithId:function(id){if(!this.flowEventsById_.hasOwnProperty(id))
return[];return this.flowEventsById_[id];}};return{ModelIndices:ModelIndices};});'use strict';tr.exportTo('tr',function(){var Importer=tr.importer.Importer;var Process=tr.model.Process;var Device=tr.model.Device;var Kernel=tr.model.Kernel;var GlobalMemoryDump=tr.model.GlobalMemoryDump;var GlobalInstantEvent=tr.model.GlobalInstantEvent;var FlowEvent=tr.model.FlowEvent;var Alert=tr.model.Alert;var InteractionRecord=tr.model.InteractionRecord;var Sample=tr.model.Sample;function ImportOptions(){this.shiftWorldToZero=true;this.pruneEmptyContainers=true;this.customizeModelCallback=undefined;var auditorTypes=tr.c.Auditor.getAllRegisteredTypeInfos();this.auditorConstructors=auditorTypes.map(function(typeInfo){return typeInfo.constructor;});}
ImportOptions.fromArguments=function(args,argsStartIndex){var arg0=args[argsStartIndex+0];if(typeof arg0==='object'){if(!(arg0 instanceof ImportOptions))
throw new Error('Unexpected');return arg0;}
var options=new ImportOptions();if(args[argsStartIndex]!==undefined)
options.shiftWorldToZero=args[argsStartIndex];if(args[argsStartIndex+1]!==undefined)
options.pruneEmptyContainers=args[argsStartIndex+1];if(args[argsStartIndex+2])
options.customizeModelCallback=args[argsStartIndex+2];return options;}
function ClockSyncRecord(name,ts,args){this.name=name;this.ts=ts;this.args=args;}
2015-06-18 08:27:29 -06:00
function Model(opt_eventData,opt_options){tr.model.EventContainer.call(this);tr.b.EventTarget.decorate(this);this.faviconHue='blue';this.device=new Device(this);this.kernel=new Kernel(this);this.processes={};this.metadata=[];this.categories=[];this.bounds=new tr.b.Range();this.instantEvents=[];this.flowEvents=[];this.clockSyncRecords=[];this.intrinsicTimeUnit_=undefined;this.stackFrames={};this.samples=[];this.alerts=[];this.interaction_records=[];this.flowIntervalTree=new tr.b.IntervalTree(function(f){return f.start;},function(f){return f.end;});this.globalMemoryDumps=[];this.annotationsByGuid_={};this.importWarnings_=[];this.reportedImportWarnings_={};this.modelIndices=undefined;var options=ImportOptions.fromArguments(arguments,1);if(opt_eventData)
2015-06-14 13:52:57 -06:00
this.importTraces([opt_eventData],options);}
Model.prototype={__proto__:tr.model.EventContainer.prototype,iterateAllEventsInThisContainer:function(eventTypePredicate,callback,opt_this){if(eventTypePredicate.call(opt_this,GlobalMemoryDump))
this.globalMemoryDumps.forEach(callback,opt_this);if(eventTypePredicate.call(opt_this,GlobalInstantEvent))
this.instantEvents.forEach(callback,opt_this);if(eventTypePredicate.call(opt_this,FlowEvent))
this.flowEvents.forEach(callback,opt_this);if(eventTypePredicate.call(opt_this,Alert))
this.alerts.forEach(callback,opt_this);if(eventTypePredicate.call(opt_this,InteractionRecord))
this.interaction_records.forEach(callback,opt_this);if(eventTypePredicate.call(opt_this,Sample))
this.samples.forEach(callback,opt_this);},iterateAllChildEventContainers:function(callback,opt_this){callback.call(opt_this,this.device);callback.call(opt_this,this.kernel);for(var pid in this.processes)
callback.call(opt_this,this.processes[pid]);},iterateAllPersistableObjects:function(callback){this.kernel.iterateAllPersistableObjects(callback);for(var pid in this.processes)
this.processes[pid].iterateAllPersistableObjects(callback);},updateBounds:function(){this.bounds.reset();var bounds=this.bounds;this.iterateAllChildEventContainers(function(ec){ec.updateBounds();bounds.addRange(ec.bounds);});this.iterateAllEventsInThisContainer(function(eventConstructor){return true;},function(event){event.addBoundsToRange(bounds);});},shiftWorldToZero:function(){var shiftAmount=-this.bounds.min;this.iterateAllChildEventContainers(function(ec){ec.shiftTimestampsForward(shiftAmount);});this.iterateAllEventsInThisContainer(function(eventConstructor){return true;},function(event){event.start+=shiftAmount;});this.updateBounds();},get numProcesses(){var n=0;for(var p in this.processes)
n++;return n;},getProcess:function(pid){return this.processes[pid];},getOrCreateProcess:function(pid){if(!this.processes[pid])
this.processes[pid]=new Process(this,pid);return this.processes[pid];},pushInstantEvent:function(instantEvent){this.instantEvents.push(instantEvent);},addStackFrame:function(stackFrame){if(this.stackFrames[stackFrame.id])
throw new Error('Stack frame already exists');this.stackFrames[stackFrame.id]=stackFrame;return stackFrame;},addInteractionRecord:function(ir1){this.interaction_records.push(ir1);},getClockSyncRecordsNamed:function(name){return this.clockSyncRecords.filter(function(x){return x.name===name;});},updateCategories_:function(){var categoriesDict={};this.device.addCategoriesToDict(categoriesDict);this.kernel.addCategoriesToDict(categoriesDict);for(var pid in this.processes)
this.processes[pid].addCategoriesToDict(categoriesDict);this.categories=[];for(var category in categoriesDict)
if(category!='')
this.categories.push(category);},getAllThreads:function(){var threads=[];for(var tid in this.kernel.threads){threads.push(process.threads[tid]);}
for(var pid in this.processes){var process=this.processes[pid];for(var tid in process.threads){threads.push(process.threads[tid]);}}
return threads;},getAllProcesses:function(){var processes=[];for(var pid in this.processes)
processes.push(this.processes[pid]);return processes;},getAllCounters:function(){var counters=[];counters.push.apply(counters,tr.b.dictionaryValues(this.device.counters));counters.push.apply(counters,tr.b.dictionaryValues(this.kernel.counters));for(var pid in this.processes){var process=this.processes[pid];for(var tid in process.counters){counters.push(process.counters[tid]);}}
return counters;},getAnnotationByGUID:function(guid){return this.annotationsByGuid_[guid];},addAnnotation:function(annotation){if(!annotation.guid)
throw new Error('Annotation with undefined guid given');this.annotationsByGuid_[annotation.guid]=annotation;tr.b.dispatchSimpleEvent(this,'annotationChange');},removeAnnotation:function(annotation){this.annotationsByGuid_[annotation.guid].onRemove();delete this.annotationsByGuid_[annotation.guid];tr.b.dispatchSimpleEvent(this,'annotationChange');},getAllAnnotations:function(){return tr.b.dictionaryValues(this.annotationsByGuid_);},findAllThreadsNamed:function(name){var namedThreads=[];namedThreads.push.apply(namedThreads,this.kernel.findAllThreadsNamed(name));for(var pid in this.processes){namedThreads.push.apply(namedThreads,this.processes[pid].findAllThreadsNamed(name));}
return namedThreads;},createImporter_:function(eventData){var importerConstructor=tr.importer.Importer.findImporterFor(eventData);if(!importerConstructor)
throw new Error('Could not find an importer for the provided eventData.');var importer=new importerConstructor(this,eventData);return importer;},importTraces:function(traces,opt_options){var progressMeter={update:function(msg){}};var options=ImportOptions.fromArguments(arguments,1);var task=this.createImportTracesTask(progressMeter,traces,options);tr.b.Task.RunSynchronously(task);},importTracesWithProgressDialog:function(traces,opt_options){var options=ImportOptions.fromArguments(arguments,1);var overlay=tr.ui.b.Overlay();overlay.title='Importing...';overlay.userCanClose=false;overlay.msgEl=document.createElement('div');overlay.appendChild(overlay.msgEl);overlay.msgEl.style.margin='20px';overlay.update=function(msg){this.msgEl.textContent=msg;}
overlay.visible=true;var task=this.createImportTracesTask(overlay,traces,options);var promise=tr.b.Task.RunWhenIdle(task);promise.then(function(){overlay.visible=false;},function(err){overlay.visible=false;});return promise;},hasEventDataDecoder_:function(importers){if(importers.length===0)
return false;for(var i=0;i< importers.length ; + + i ) { if ( ! importers [ i ] . isTraceDataContainer ( ) )
return true;}
return false;},createImportTracesTask:function(progressMeter,traces,opt_options){var options=ImportOptions.fromArguments(arguments,2);if(this.importing_)
throw new Error('Already importing.');this.importing_=true;var importTask=new tr.b.Task(function(){progressMeter.update('I will now import your traces for you...');},this);var lastTask=importTask;var importers=[];lastTask=lastTask.after(function(){traces=traces.slice(0);progressMeter.update('Creating importers...');for(var i=0;i< traces.length ; + + i )
importers.push(this.createImporter_(traces[i]));for(var i=0;i< importers.length ; i + + ) { var subtraces = importers[i].extractSubtraces();for(var j = 0;j<subtraces.length;j++){try{traces.push(subtraces[j]);importers.push(this.createImporter_(subtraces[j]));}catch(error){console.warn(error.name+': ' + error . message ) ; continue ; } } }
if(traces.length& & !this.hasEventDataDecoder_(importers)){throw new Error('Could not find an importer for '+'the provided eventData.');}
importers.sort(function(x,y){return x.importPriority-y.importPriority;});},this);lastTask=lastTask.after(function(task){importers.forEach(function(importer,index){task.subTask(function(){progressMeter.update('Importing '+(index+1)+' of '+importers.length);importer.importEvents();},this);},this);},this);if(options.customizeModelCallback){lastTask=lastTask.after(function(task){options.customizeModelCallback(this);},this);}
lastTask=lastTask.after(function(task){importers.forEach(function(importer,index){progressMeter.update('Importing sample data '+(index+1)+'/'+importers.length);importer.importSampleData();},this);},this);lastTask=lastTask.after(function(){progressMeter.update('Autoclosing open slices...');this.samples.sort(function(x,y){return x.start-y.start;});this.updateBounds();this.kernel.autoCloseOpenSlices(this.bounds.max);for(var pid in this.processes)
this.processes[pid].autoCloseOpenSlices(this.bounds.max);this.kernel.createSubSlices();for(var pid in this.processes)
this.processes[pid].createSubSlices();},this);lastTask=lastTask.after(function(task){importers.forEach(function(importer,index){progressMeter.update('Finalizing import '+(index+1)+'/'+importers.length);importer.finalizeImport();},this);},this);lastTask=lastTask.after(function(){progressMeter.update('Initializing objects (step 1/2)...');for(var pid in this.processes)
this.processes[pid].preInitializeObjects();},this);if(options.pruneEmptyContainers){lastTask=lastTask.after(function(){progressMeter.update('Pruning empty containers...');this.kernel.pruneEmptyContainers();for(var pid in this.processes){this.processes[pid].pruneEmptyContainers();}},this);}
lastTask=lastTask.after(function(){progressMeter.update('Merging kernel with userland...');for(var pid in this.processes)
this.processes[pid].mergeKernelWithUserland();},this);var auditors=[];lastTask=lastTask.after(function(){progressMeter.update('Adding arbitrary data to model...');auditors=options.auditorConstructors.map(function(auditorConstructor){return new auditorConstructor(this);},this);auditors.forEach(function(auditor){auditor.runAnnotate();});},this);lastTask=lastTask.after(function(){progressMeter.update('Computing final world bounds...');this.updateBounds();this.updateCategories_();if(options.shiftWorldToZero)
this.shiftWorldToZero();},this);lastTask=lastTask.after(function(){progressMeter.update('Building flow event map...');for(var i=0;i< this.flowEvents.length ; + + i ) { var flowEvent = this.flowEvents[i];this.flowIntervalTree.insert(flowEvent);}
this.flowIntervalTree.updateHighValues();},this);lastTask=lastTask.after(function(){progressMeter.update('Joining object refs...');for(var i=0;i< importers.length ; i + + )
importers[i].joinRefs();},this);lastTask=lastTask.after(function(){progressMeter.update('Cleaning up undeleted objects...');for(var pid in this.processes)
this.processes[pid].autoDeleteObjects(this.bounds.max);},this);lastTask=lastTask.after(function(){progressMeter.update('Sorting memory dumps...');this.globalMemoryDumps.sort(function(x,y){return x.start-y.start;});for(var pid in this.processes)
this.processes[pid].sortMemoryDumps();},this);lastTask=lastTask.after(function(){progressMeter.update('Calculating memory dump graph attributes...');this.globalMemoryDumps.forEach(function(dump){dump.calculateGraphAttributes();});},this);lastTask=lastTask.after(function(){progressMeter.update('Initializing objects (step 2/2)...');for(var pid in this.processes)
this.processes[pid].initializeObjects();},this);lastTask=lastTask.after(function(){progressMeter.update('Building flow event indices...');this.modelIndices=new tr.model.ModelIndices(this);},this);lastTask=lastTask.after(function(){progressMeter.update('Running auditors...');auditors.forEach(function(auditor){auditor.runAudit();});this.interaction_records.sort(function(x,y){return x.start-y.start;});this.alerts.sort(function(x,y){return x.start-y.start;});this.updateBounds();},this);lastTask.after(function(){this.importing_=false;},this);return importTask;},importWarning:function(data){this.importWarnings_.push(data);if(this.reportedImportWarnings_[data.type]===true)
2015-06-18 08:27:29 -06:00
return;console.warn(data.message);this.reportedImportWarnings_[data.type]=true;},get intrinsicTimeUnit(){if(this.intrinsicTimeUnit_===undefined)
return tr.b.units.Time.supportedUnits.ms;return this.intrinsicTimeUnit_;},set intrinsicTimeUnit(value){if(this.intrinsicTimeUnit_===value)
return;if(this.intrinsicTimeUnit_!==undefined)
throw new Error('Intrinsic time unit already set');this.intrinsicTimeUnit_=value;},get hasImportWarnings(){return(this.importWarnings_.length>0);},get importWarnings(){return this.importWarnings_;}};return{ImportOptions:ImportOptions,ClockSyncRecord:ClockSyncRecord,Model:Model};});'use strict';tr.exportTo('tr.c',function(){var EventRegistry=tr.model.EventRegistry;var RequestSelectionChangeEvent=tr.b.Event.bind(undefined,'requestSelectionChange',true,false);function Selection(opt_events){this.sunburst_zoom_level=undefined;this.bounds_dirty_=true;this.bounds_=new tr.b.Range();this.length_=0;this.guid_=tr.b.GUID.allocate();this.pushed_guids_={};if(opt_events){if(opt_events instanceof Array){for(var i=0;i< opt_events.length ; i + + )
2015-06-14 13:52:57 -06:00
this.push(opt_events[i]);}else{this.push(opt_events);}}}
Selection.prototype={__proto__:Object.prototype,get bounds(){if(this.bounds_dirty_){this.bounds_.reset();for(var i=0;i< this.length_ ; i + + )
this[i].addBoundsToRange(this.bounds_);this.bounds_dirty_=false;}
return this.bounds_;},get duration(){if(this.bounds_.isEmpty)
return 0;return this.bounds_.max-this.bounds_.min;},get length(){return this.length_;},get guid(){return this.guid_;},clear:function(){for(var i=0;i< this.length_ ; + + i )
delete this[i];this.length_=0;this.bounds_dirty_=true;},push:function(event){if(event.guid==undefined)
throw new Error('Event must have a GUID');if(this.contains(event))
return event;this.pushed_guids_[event.guid]=true;this[this.length_++]=event;this.bounds_dirty_=true;return event;},contains:function(event){return this.pushed_guids_[event.guid];},addSelection:function(selection){for(var i=0;i< selection.length ; i + + )
this.push(selection[i]);},subSelection:function(index,count){count=count||1;var selection=new Selection();selection.bounds_dirty_=true;if(index< 0 | | index + count > this.length_)
throw new Error('Index out of bounds');for(var i=index;i< index + count ; i + + )
selection.push(this[i]);return selection;},equals:function(that){if(this.length!==that.length)
return false;for(var i=0;i< this.length ; i + + ) { var event = this[i];if(that.pushed_guids_[event.guid]===undefined)
return false;}
return true;},getEventsOrganizedByBaseType:function(opt_pruneEmpty){var events={};var allTypeInfos=EventRegistry.getAllRegisteredTypeInfos();allTypeInfos.forEach(function(eventTypeInfo){events[eventTypeInfo.metadata.name]=new Selection();if(this.sunburst_zoom_level!==undefined)
events[eventTypeInfo.metadata.name].sunburst_zoom_level=this.sunburst_zoom_level;},this);this.forEach(function(event,i){var maxEventIndex=-1;var maxEventTypeInfo=undefined;allTypeInfos.forEach(function(eventTypeInfo,eventIndex){if(!(event instanceof eventTypeInfo.constructor))
return;if(eventIndex>maxEventIndex){maxEventIndex=eventIndex;maxEventTypeInfo=eventTypeInfo;}});if(maxEventIndex==-1){console.log(event);throw new Error('Unrecognized event type');}
events[maxEventTypeInfo.metadata.name].push(event);});if(opt_pruneEmpty){var prunedEvents={};for(var eventType in events){if(events[eventType].length>0)
prunedEvents[eventType]=events[eventType];}
return prunedEvents;}else{return events;}},getEventsOrganizedByTitle:function(){var eventsByTitle={};for(var i=0;i< this.length ; i + + ) { var event = this[i];if(event.title===undefined)
throw new Error('An event didn\'t have a title!');if(eventsByTitle[event.title]==undefined){eventsByTitle[event.title]=[];}
eventsByTitle[event.title].push(event);}
return eventsByTitle;},enumEventsOfType:function(type,func){for(var i=0;i< this.length_ ; i + + )
if(this[i]instanceof type)
func(this[i]);},get userFriendlyName(){if(this.length===0){throw new Error('Empty selection');}
var eventsByBaseType=this.getEventsOrganizedByBaseType(true);var eventTypeName=tr.b.dictionaryKeys(eventsByBaseType)[0];if(this.length===1){var tmp=EventRegistry.getUserFriendlySingularName(eventTypeName);return this[0].userFriendlyName;}
var numEventTypes=tr.b.dictionaryLength(eventsByBaseType);if(numEventTypes!==1){return this.length+' events of various types';}
var tmp=EventRegistry.getUserFriendlyPluralName(eventTypeName);return this.length+' '+tmp;},getShiftedSelection:function(viewport,offset){var newSelection=new Selection();for(var i=0;i< this.length_ ; i + + ) { var event = this[i];if(event instanceof tr . model . FlowEvent ) { if ( offset > 0){newSelection.push(event.endSlice);}else if(offset< 0 ) { newSelection . push ( event . startSlice ) ; } else { }
continue;}
var track=viewport.trackForEvent(event);track.addEventNearToProvidedEventToSelection(event,offset,newSelection);}
if(newSelection.length==0)
2015-06-18 08:27:29 -06:00
return undefined;return newSelection;},filter:function(fn,opt_this){var res=new Selection();this.forEach(function(slice){if(fn.call(this,slice))
res.push(slice);},opt_this);return res;},forEach:function(fn,opt_this){for(var i=0;i< this.length ; i + + )
2015-06-14 13:52:57 -06:00
fn.call(opt_this,this[i],i);},map:function(fn,opt_this){var res=[];for(var i=0;i< this.length ; i + + )
res.push(fn.call(opt_this,this[i],i));return res;},every:function(fn,opt_this){for(var i=0;i< this.length ; i + + )
if(!fn.call(opt_this,this[i],i))
return false;return true;},some:function(fn,opt_this){for(var i=0;i< this.length ; i + + )
if(fn.call(opt_this,this[i],i))
2015-06-18 08:27:29 -06:00
return true;return false;}};return{Selection:Selection,RequestSelectionChangeEvent:RequestSelectionChangeEvent};});'use strict';Polymer('tr-ui-a-sub-view',{set tabLabel(label){return this.setAttribute('tab-label',label);},get tabLabel(){return this.getAttribute('tab-label');},get requiresTallView(){return false;},get relatedEventsToHighlight(){return undefined;},set selection(selection){throw new Error('Not implemented!');},get selection(){throw new Error('Not implemented!');}});'use strict';Polymer('tr-ui-a-analysis-link',{ready:function(){this.addEventListener('click',this.onClicked_.bind(this));this.selection_=undefined;},get selection(){return this.selection_;},set selection(selection){this.selection_=selection;this.textContent=selection.userFriendlyName;},setSelectionAndContent:function(selection,opt_textContent){this.selection_=selection;if(opt_textContent)
2015-06-14 13:52:57 -06:00
this.textContent=opt_textContent;},onClicked_:function(){if(!this.selection_)
return;var event=new tr.c.RequestSelectionChangeEvent();if(typeof this.selection_==='function')
event.selection=this.selection_();else
2015-06-18 08:27:29 -06:00
event.selection=this.selection_;this.dispatchEvent(event);}});'use strict';tr.exportTo('tr.b.units',function(){function TimeDuration(duration){this.duration=duration;};TimeDuration.prototype={toString:function(){return TimeDuration.format(this.duration);}};TimeDuration.format=function(duration){return tr.b.units.Time.currentDisplayUnit.format(duration);};return{TimeDuration:TimeDuration};});'use strict';tr.exportTo('tr.b.units',function(){function TimeStamp(timestamp){this.timestamp=timestamp;};TimeStamp.prototype={toString:function(){return TimeStamp.format(this.timestamp);}};TimeStamp.format=function(timestamp){return tr.b.units.Time.currentDisplayUnit.format(timestamp);};return{TimeStamp:TimeStamp};});'use strict';tr.exportTo('tr.ui.b',function(){function createSpan(opt_dictionary){var spanEl=document.createElement('span');if(opt_dictionary){if(opt_dictionary.className)
spanEl.className=opt_dictionary.className;if(opt_dictionary.textContent)
spanEl.textContent=opt_dictionary.textContent;if(opt_dictionary.parent)
opt_dictionary.parent.appendChild(spanEl);if(opt_dictionary.bold)
spanEl.style.fontWeight='bold';if(opt_dictionary.marginLeft)
spanEl.style.marginLeft=opt_dictionary.marginLeft;if(opt_dictionary.marginRight)
spanEl.style.marginRight=opt_dictionary.marginRight;if(opt_dictionary.backgroundColor)
spanEl.style.backgroundColor=opt_dictionary.backgroundColor;if(opt_dictionary.color)
spanEl.style.color=opt_dictionary.color;}
return spanEl;};function createDiv(opt_dictionary){var divEl=document.createElement('div');if(opt_dictionary){if(opt_dictionary.className)
divEl.className=opt_dictionary.className;if(opt_dictionary.parent)
opt_dictionary.parent.appendChild(divEl);if(opt_dictionary.textContent)
divEl.textContent=opt_dictionary.textContent;if(opt_dictionary.maxWidth)
divEl.style.maxWidth=opt_dictionary.maxWidth;}
return divEl;};function createScopedStyle(styleContent){var styleEl=document.createElement('style');styleEl.scoped=true;styleEl.innerHTML=styleContent;return styleEl;}
function valuesEqual(a,b){if(a instanceof Array& & b instanceof Array)
return a.length===b.length&&JSON.stringify(a)===JSON.stringify(b); return a===b;}
function createSelector(targetEl,targetElProperty,settingsKey,defaultValue,items,opt_namespace){var defaultValueIndex;for(var i=0;i< items.length ; i + + ) { var item = items[i];if(valuesEqual(item.value,defaultValue)){defaultValueIndex=i;break;}}
if(defaultValueIndex===undefined)
throw new Error('defaultValue must be in the items list');var selectorEl=document.createElement('select');selectorEl.addEventListener('change',onChange);for(var i=0;i< items.length ; i + + ) { var item = items[i];var optionEl = document.createElement('option');optionEl.textContent=item.label;optionEl.targetPropertyValue=item.value;selectorEl.appendChild(optionEl);}
function onChange(e){var value=selectorEl.selectedOptions[0].targetPropertyValue;tr.b.Settings.set(settingsKey,value,opt_namespace);targetEl[targetElProperty]=value;}
var oldSetter=targetEl.__lookupSetter__('selectedIndex');selectorEl.__defineGetter__('selectedValue',function(v){return selectorEl.children[selectorEl.selectedIndex].targetPropertyValue;});selectorEl.__defineSetter__('selectedValue',function(v){for(var i=0;i< selectorEl.children.length ; i + + ) { var value = selectorEl.children[i].targetPropertyValue;if(valuesEqual(value,v)){var changed = selectorEl.selectedIndex!=i;if(changed){selectorEl.selectedIndex=i;onChange();}
return;}}
throw new Error('Not a valid value');});var initialValue=tr.b.Settings.get(settingsKey,defaultValue,opt_namespace);var didSet=false;for(var i=0;i< selectorEl.children.length ; i + + ) { if ( valuesEqual ( selectorEl . children [ i ] . targetPropertyValue , initialValue ) ) { didSet = true;targetEl[targetElProperty]=initialValue;selectorEl.selectedIndex=i;break;}}
if(!didSet){selectorEl.selectedIndex=defaultValueIndex;targetEl[targetElProperty]=defaultValue;}
return selectorEl;}
function createEditCategorySpan(optionGroupEl,targetEl){var spanEl=createSpan({className:'edit-categories'});spanEl.textContent='Edit categories';spanEl.classList.add('labeled-option');spanEl.addEventListener('click',function(){targetEl.onClickEditCategories();});return spanEl;}
function createOptionGroup(targetEl,targetElProperty,settingsKey,defaultValue,items){function onChange(){var value=[];if(this.value.length)
value=this.value.split(',');tr.b.Settings.set(settingsKey,value);targetEl[targetElProperty]=value;}
var optionGroupEl=createSpan({className:'labeled-option-group'});var initialValue=tr.b.Settings.get(settingsKey,defaultValue);for(var i=0;i< items.length ; + + i ) { var item = items[i];var id = 'category-preset-' + item . label . replace ( / / g , ' - ' ) ; var radioEl = document.createElement('input');radioEl.type='radio';radioEl.setAttribute('id',id);radioEl.setAttribute('name','category-presets-group');radioEl.setAttribute('value',item.value);radioEl.addEventListener('change',onChange.bind(radioEl,targetEl,targetElProperty,settingsKey));if(valuesEqual(initialValue,item.value))
radioEl.checked=true;var labelEl=document.createElement('label');labelEl.textContent=item.label;labelEl.setAttribute('for',id);var spanEl=createSpan({className:'labeled-option'});spanEl.appendChild(radioEl);spanEl.appendChild(labelEl);spanEl.__defineSetter__('checked',function(opt_bool){var changed=radioEl.checked!==(!!opt_bool);if(!changed)
return;radioEl.checked=!!opt_bool;onChange();});spanEl.__defineGetter__('checked',function(){return radioEl.checked;});optionGroupEl.appendChild(spanEl);}
optionGroupEl.appendChild(createEditCategorySpan(optionGroupEl,targetEl));if(!initialValue.length)
optionGroupEl.classList.add('categories-expanded');targetEl[targetElProperty]=initialValue;return optionGroupEl;}
var nextCheckboxId=1;function createCheckBox(targetEl,targetElProperty,settingsKey,defaultValue,label){var buttonEl=document.createElement('input');buttonEl.type='checkbox';var initialValue=tr.b.Settings.get(settingsKey,defaultValue);buttonEl.checked=!!initialValue;if(targetEl)
targetEl[targetElProperty]=initialValue;function onChange(){tr.b.Settings.set(settingsKey,buttonEl.checked);if(targetEl)
targetEl[targetElProperty]=buttonEl.checked;}
buttonEl.addEventListener('change',onChange);var id='#checkbox-'+nextCheckboxId++;var spanEl=createSpan({className:'labeled-checkbox'});buttonEl.setAttribute('id',id);var labelEl=document.createElement('label');labelEl.textContent=label;labelEl.setAttribute('for',id);spanEl.appendChild(buttonEl);spanEl.appendChild(labelEl);spanEl.__defineSetter__('checked',function(opt_bool){var changed=buttonEl.checked!==(!!opt_bool);if(!changed)
return;buttonEl.checked=!!opt_bool;onChange();});spanEl.__defineGetter__('checked',function(){return buttonEl.checked;});return spanEl;}
function isElementAttachedToDocument(el){var cur=el;while(cur.parentNode)
cur=cur.parentNode;return(cur===el.ownerDocument||cur.nodeName==='#document-fragment');}
function asHTMLOrTextNode(value,opt_ownerDocument){if(value instanceof Node)
return value;var ownerDocument=opt_ownerDocument||document;return ownerDocument.createTextNode(value);}
return{createSpan:createSpan,createDiv:createDiv,createScopedStyle:createScopedStyle,createSelector:createSelector,createOptionGroup:createOptionGroup,createCheckBox:createCheckBox,isElementAttachedToDocument:isElementAttachedToDocument,asHTMLOrTextNode:asHTMLOrTextNode};});'use strict';(function(){var RIGHT_ARROW=String.fromCharCode(0x25b6);var UNSORTED_ARROW=String.fromCharCode(0x25BF);var ASCENDING_ARROW=String.fromCharCode(0x25BE);var DESCENDING_ARROW=String.fromCharCode(0x25B4);var BASIC_INDENTATION=8;Polymer('tr-ui-b-table',{created:function(){this.supportsSelection_=false;this.cellSelectionMode_=false;this.selectedTableRowInfo_=undefined;this.selectedColumnIndex_=undefined;this.tableColumns_=[];this.tableRows_=[];this.tableRowsInfo_=[];this.tableFooterRows_=[];this.sortColumnIndex_=undefined;this.sortDescending_=false;this.columnsWithExpandButtons_=[];this.headerCells_=[];this.showHeader_=true;this.emptyValue_=undefined;this.subRowsPropertyName_='subRows';},ready:function(){this.$.body.addEventListener('keydown',this.onKeyDown_.bind(this),true);},clear:function(){this.supportsSelection_=false;this.cellSelectionMode_=false;this.selectedTableRowInfo_=undefined;this.selectedColumnIndex_=undefined;this.textContent='';this.tableColumns_=[];this.tableRows_=[];this.tableRowsInfo_=new WeakMap();this.tableFooterRows_=[];this.tableFooterRowsInfo_=new WeakMap();this.sortColumnIndex_=undefined;this.sortDescending_=false;this.columnsWithExpandButtons_=[];this.headerCells_=[];this.subRowsPropertyName_='subRows';},get showHeader(){return this.showHeader_;},set showHeader(showHeader){this.showHeader_=showHeader;this.scheduleRebuildHeaders_();},set subRowsPropertyName(name){this.subRowsPropertyName_=name;},get emptyValue(){return this.emptyValue_;},set emptyValue(emptyValue){var previousEmptyValue=this.emptyValue_;this.emptyValue_=emptyValue;if(this.tableRows_.length===0& & emptyValue!==previousEmptyValue)
2015-06-14 13:52:57 -06:00
this.scheduleRebuildBody_();},set tableColumns(columns){var columnsWithExpandButtons=[];for(var i=0;i< columns.length ; i + + ) { if ( columns [ i ] . showExpandButtons )
columnsWithExpandButtons.push(i);}
if(columnsWithExpandButtons.length===0){columnsWithExpandButtons=[0];}
for(var i=0;i< columns.length ; i + + ) { var colInfo = columns[i];if(colInfo.width===undefined)
continue;var hasExpandButton=columnsWithExpandButtons.indexOf(i)!==-1;var w=colInfo.width;if(w){if(/\d+px/.test(w)){continue;}else if(/\d+%/.test(w)){if(hasExpandButton){throw new Error('Columns cannot be %-sized and host '+' an expand button');}}else{throw new Error('Unrecognized width string');}}}
this.tableColumns_=columns;this.headerCells_=[];this.columnsWithExpandButtons_=columnsWithExpandButtons;this.sortColumnIndex=undefined;this.scheduleRebuildHeaders_();this.tableRows=this.tableRows_;},get tableColumns(){return this.tableColumns_;},set tableRows(rows){this.selectedTableRowInfo_=undefined;this.selectedColumnIndex_=undefined;this.maybeUpdateSelectedRow_();this.tableRows_=rows;this.tableRowsInfo_=new WeakMap();this.scheduleRebuildBody_();},get tableRows(){return this.tableRows_;},set footerRows(rows){this.tableFooterRows_=rows;this.tableFooterRowsInfo_=new WeakMap();this.scheduleRebuildFooter_();},get footerRows(){return this.tableFooterRows_;},set sortColumnIndex(number){if(number===undefined){this.sortColumnIndex_=undefined;this.updateHeaderArrows_();return;}
if(this.tableColumns_.length< =number)
throw new Error('Column number '+number+' is out of bounds.');if(!this.tableColumns_[number].cmp)
throw new Error('Column '+number+' does not have a comparator.');this.sortColumnIndex_=number;this.updateHeaderArrows_();this.scheduleRebuildBody_();},get sortColumnIndex(){return this.sortColumnIndex_;},set sortDescending(value){var newValue=!!value;if(newValue!==this.sortDescending_){this.sortDescending_=newValue;this.updateHeaderArrows_();this.scheduleRebuildBody_();}},get sortDescending(){return this.sortDescending_;},updateHeaderArrows_:function(){for(var i=0;i< this.headerCells_.length ; i + + ) { if ( ! this . tableColumns_ [ i ] . cmp ) { this . headerCells_ [ i ] . sideContent = '' ; continue ; }
if(i!==this.sortColumnIndex_){this.headerCells_[i].sideContent=UNSORTED_ARROW;continue;}
this.headerCells_[i].sideContent=this.sortDescending_?DESCENDING_ARROW:ASCENDING_ARROW;}},sortRows_:function(rows){rows.sort(function(rowA,rowB){if(this.sortDescending_)
return this.tableColumns_[this.sortColumnIndex_].cmp(rowB.userRow,rowA.userRow);return this.tableColumns_[this.sortColumnIndex_].cmp(rowA.userRow,rowB.userRow);}.bind(this));for(var i=0;i< rows.length ; i + + ) { if ( rows [ i ] . isExpanded )
this.sortRows_(rows[i][this.subRowsPropertyName_]);}},generateHeaderColumns_:function(){this.headerCells_=[];this.$.head.textContent='';if(!this.showHeader_)
return;var tr=this.appendNewElement_(this.$.head,'tr');for(var i=0;i< this.tableColumns_.length ; i + + ) { var td = this.appendNewElement_(tr,'td');var headerCell = document.createElement('tr-ui-b-table-header-cell');if(this.showHeader)
headerCell.cellTitle=this.tableColumns_[i].title;else
headerCell.cellTitle='';if(this.tableColumns_[i].cmp){td.classList.add('sensitive');headerCell.tapCallback=this.createSortCallback_(i);if(this.sortColumnIndex_===i)
headerCell.sideContent=this.sortDescending_?DESCENDING_ARROW:ASCENDING_ARROW;else
headerCell.sideContent=UNSORTED_ARROW;}
td.appendChild(headerCell);this.headerCells_.push(headerCell);}},applySizes_:function(){if(this.tableRows_.length===0& & !this.showHeader)
return;var rowToRemoveSizing;var rowToSize;if(this.showHeader){rowToSize=this.$.head.children[0];rowToRemoveSizing=this.$.body.children[0];}else{rowToSize=this.$.body.children[0];rowToRemoveSizing=this.$.head.children[0];}
for(var i=0;i< this.tableColumns_.length ; i + + ) { if ( rowToRemoveSizing & & rowToRemoveSizing . children [ i ] ) { var tdToRemoveSizing = rowToRemoveSizing.children[i];tdToRemoveSizing.style.minWidth='';tdToRemoveSizing.style.width='';}
var td=rowToSize.children[i];var delta;if(this.columnsWithExpandButtons_.indexOf(i)!==-1){td.style.paddingLeft=BASIC_INDENTATION+'px';delta=BASIC_INDENTATION+'px';}else{delta=undefined;}
function calc(base,delta){if(delta)
return'calc('+base+' - '+delta+')';else
return base;}
var w=this.tableColumns_[i].width;if(w){if(/\d+px/.test(w)){td.style.minWidth=calc(w,delta);}else if(/\d+%/.test(w)){td.style.width=w;}else{throw new Error('Unrecognized width string: '+w);}}}},createSortCallback_:function(columnNumber){return function(){var previousIndex=this.sortColumnIndex;this.sortColumnIndex=columnNumber;if(previousIndex!==columnNumber)
this.sortDescending=false;else
this.sortDescending=!this.sortDescending;}.bind(this);},generateTableRowNodes_:function(tableSection,userRows,rowInfoMap,indentation,lastAddedRow,parentRowInfo){if(this.sortColumnIndex_!==undefined&&tableSection===this.$.body){userRows=userRows.slice(); userRows.sort(function(rowA,rowB){var c=this.tableColumns_[this.sortColumnIndex_].cmp(rowA,rowB);if(this.sortDescending_)
c=-c;return c;}.bind(this));}
for(var i=0;i< userRows.length ; i + + ) { var userRow = userRows[i];var rowInfo = this.getOrCreateRowInfoFor_(rowInfoMap,userRow,parentRowInfo);var htmlNode = this.getHTMLNodeForRowInfo_(tableSection,rowInfo,rowInfoMap,indentation);if(lastAddedRow===undefined){tableSection.insertBefore(htmlNode,tableSection.firstChild);}else{var nextSiblingOfLastAdded = lastAddedRow.nextSibling;tableSection.insertBefore(htmlNode,nextSiblingOfLastAdded);}
this.updateTabIndexForTableRowNode_(htmlNode);lastAddedRow=htmlNode;if(!rowInfo.isExpanded)
continue;lastAddedRow=this.generateTableRowNodes_(tableSection,userRow[this.subRowsPropertyName_],rowInfoMap,indentation+1,lastAddedRow,rowInfo);}
return lastAddedRow;},getOrCreateRowInfoFor_:function(rowInfoMap,userRow,parentRowInfo){if(rowInfoMap.has(userRow))
return rowInfoMap.get(userRow);var rowInfo={userRow:userRow,htmlNode:undefined,isExpanded:userRow.isExpanded||false,parentRowInfo:parentRowInfo};rowInfoMap.set(userRow,rowInfo);return rowInfo;},getHTMLNodeForRowInfo_:function(tableSection,rowInfo,rowInfoMap,indentation){if(rowInfo.htmlNode)
2015-06-18 08:27:29 -06:00
return rowInfo.htmlNode;var INDENT_SPACE=indentation*16;var INDENT_SPACE_NO_BUTTON=indentation*16+BASIC_INDENTATION;var trElement=this.ownerDocument.createElement('tr');rowInfo.htmlNode=trElement;rowInfo.indentation=indentation;trElement.rowInfo=rowInfo;for(var i=0;i< this.tableColumns_.length ; ) { var td = this.appendNewElement_(trElement,'td');td.columnIndex=i;var column = this.tableColumns_[i];var value = column.value(rowInfo.userRow);var colSpan = column.colSpan?column.colSpan:1;td.style.colSpan=colSpan;if(column.textAlign){td.style.textAlign=column.textAlign;}
2015-06-14 13:52:57 -06:00
if(this.doesColumnIndexSupportSelection(i))
td.classList.add('supports-selection');if(this.columnsWithExpandButtons_.indexOf(i)!=-1){if(rowInfo.userRow[this.subRowsPropertyName_]&&rowInfo.userRow[this.subRowsPropertyName_].length>0){td.style.paddingLeft=INDENT_SPACE+'px'; var expandButton=this.appendNewElement_(td,'expand-button');expandButton.textContent=RIGHT_ARROW;if(rowInfo.isExpanded)
expandButton.classList.add('button-expanded');}else{td.style.paddingLeft=INDENT_SPACE_NO_BUTTON+'px';}}
2015-06-18 08:27:29 -06:00
td.appendChild(tr.ui.b.asHTMLOrTextNode(value,this.ownerDocument));i+=colSpan;}
2015-06-14 13:52:57 -06:00
var needsClickListener=false;if(this.columnsWithExpandButtons_.length)
needsClickListener=true;else if(tableSection==this.$.body)
2015-06-18 08:27:29 -06:00
needsClickListener=true;if(needsClickListener){trElement.addEventListener('click',function(e){e.stopPropagation();if(e.target.tagName=='EXPAND-BUTTON'){this.setExpandedForUserRow_(tableSection,rowInfoMap,rowInfo.userRow,!rowInfo.isExpanded);return;}
function getTD(cur){if(cur===trElement)
throw new Error('woah');if(cur.parentElement===trElement)
2015-06-14 13:52:57 -06:00
return cur;return getTD(cur.parentElement);}
if(this.supportsSelection_){var isAlreadySelected=false;var tdThatWasClicked=getTD(e.target);if(!this.cellSelectionMode_){isAlreadySelected=this.selectedTableRowInfo_===rowInfo;}else{isAlreadySelected=this.selectedTableRowInfo_===rowInfo;isAlreadySelected&=(this.selectedColumnIndex_===tdThatWasClicked.columnIndex); }
if(isAlreadySelected){if(rowInfo.userRow[this.subRowsPropertyName_]&&rowInfo.userRow[this.subRowsPropertyName_].length){this.setExpandedForUserRow_(tableSection,rowInfoMap,rowInfo.userRow,!rowInfo.isExpanded); }}else{this.didTableRowInfoGetClicked_(rowInfo,tdThatWasClicked.columnIndex);}}else{if(rowInfo.userRow[this.subRowsPropertyName_]&&rowInfo.userRow[this.subRowsPropertyName_].length){this.setExpandedForUserRow_(tableSection,rowInfoMap,rowInfo.userRow,!rowInfo.isExpanded); }}}.bind(this));}
return rowInfo.htmlNode;},removeSubNodes_:function(tableSection,rowInfo,rowInfoMap){if(rowInfo.userRow[this.subRowsPropertyName_]===undefined)
return;for(var i=0;i< rowInfo.userRow [ this . subRowsPropertyName_ ] . length ; i + + ) { var subRow = rowInfo.userRow[this.subRowsPropertyName_][i];var subRowInfo = rowInfoMap.get(subRow);if(!subRowInfo)
continue;var subNode=subRowInfo.htmlNode;if(subNode&&subNode.parentNode===tableSection){tableSection.removeChild(subNode); this.removeSubNodes_(tableSection,subRowInfo,rowInfoMap);}}},scheduleRebuildHeaders_:function(){this.headerDirty_=true;this.scheduleRebuild_();},scheduleRebuildBody_:function(){this.bodyDirty_=true;this.scheduleRebuild_();},scheduleRebuildFooter_:function(){this.footerDirty_=true;this.scheduleRebuild_();},scheduleRebuild_:function(){if(this.rebuildPending_)
return;this.rebuildPending_=true;setTimeout(function(){this.rebuildPending_=false;this.rebuild();}.bind(this),0);},rebuildIfNeeded_:function(){this.rebuild();},rebuild:function(){var wasBodyOrHeaderDirty=this.headerDirty_||this.bodyDirty_;if(this.headerDirty_){this.generateHeaderColumns_();this.headerDirty_=false;}
2015-06-18 08:27:29 -06:00
if(this.bodyDirty_){this.$.body.textContent='';this.generateTableRowNodes_(this.$.body,this.tableRows_,this.tableRowsInfo_,0,undefined,undefined);if(this.tableRows_.length===0& & this.emptyValue_!==undefined){var trElement=this.ownerDocument.createElement('tr');this.$.body.appendChild(trElement);trElement.classList.add('empty-row');var td=this.ownerDocument.createElement('td');trElement.appendChild(td);td.colSpan=this.tableColumns_.length;var emptyValue=this.emptyValue_;td.appendChild(tr.ui.b.asHTMLOrTextNode(emptyValue,this.ownerDocument));}
2015-06-14 13:52:57 -06:00
this.bodyDirty_=false;}
if(wasBodyOrHeaderDirty)
this.applySizes_();if(this.footerDirty_){this.$.foot.textContent='';this.generateTableRowNodes_(this.$.foot,this.tableFooterRows_,this.tableFooterRowsInfo_,0,undefined,undefined);if(this.tableFooterRowsInfo_.length){this.$.body.classList.add('has-footer');}else{this.$.body.classList.remove('has-footer');}
this.footerDirty_=false;}},appendNewElement_:function(parent,tagName){var element=parent.ownerDocument.createElement(tagName);parent.appendChild(element);return element;},getExpandedForTableRow:function(userRow){this.rebuildIfNeeded_();var rowInfo=this.tableRowsInfo_.get(userRow);if(rowInfo===undefined)
throw new Error('Row has not been seen, must expand its parents');return rowInfo.isExpanded;},setExpandedForTableRow:function(userRow,expanded){this.rebuildIfNeeded_();var rowInfo=this.tableRowsInfo_.get(userRow);if(rowInfo===undefined)
throw new Error('Row has not been seen, must expand its parents');return this.setExpandedForUserRow_(this.$.body,this.tableRowsInfo_,userRow,expanded);},setExpandedForUserRow_:function(tableSection,rowInfoMap,userRow,expanded){this.rebuildIfNeeded_();var rowInfo=rowInfoMap.get(userRow);if(rowInfo===undefined)
throw new Error('Row has not been seen, must expand its parents');rowInfo.isExpanded=!!expanded;if(rowInfo.htmlNode===undefined)
return;if(rowInfo.htmlNode.parentElement!==tableSection)
return;var expandButton=rowInfo.htmlNode.querySelector('expand-button');if(rowInfo.isExpanded){expandButton.classList.add('button-expanded');var lastAddedRow=rowInfo.htmlNode;if(rowInfo.userRow[this.subRowsPropertyName_]){this.generateTableRowNodes_(tableSection,rowInfo.userRow[this.subRowsPropertyName_],rowInfoMap,rowInfo.indentation+1,lastAddedRow,rowInfo);}}else{expandButton.classList.remove('button-expanded');this.removeSubNodes_(tableSection,rowInfo,rowInfoMap);}
2015-06-18 08:27:29 -06:00
this.maybeUpdateSelectedRow_();},get supportsSelection(){return this.supportsSelection_;},set supportsSelection(supportsSelection){this.rebuildIfNeeded_();this.supportsSelection_=!!supportsSelection;this.didSelectionStateChange_();},get cellSelectionMode(){return this.cellSelectionMode_;},set cellSelectionMode(cellSelectionMode){this.rebuildIfNeeded_();this.cellSelectionMode_=!!cellSelectionMode;this.didSelectionStateChange_();},get rowHighlightEnabled(){return this.rowHighlightEnabled_;},set rowHighlightEnabled(rowHighlightEnabled){this.rebuildIfNeeded_();this.rowHighlightEnabled_=!!rowHighlightEnabled;this.didSelectionStateChange_();},didSelectionStateChange_:function(){if(!this.supportsSelection_){this.$.body.classList.remove('cell-selection-mode');this.$.body.classList.remove('row-selection-mode');this.$.body.classList.remove('row-highlight-enabled');}else if(!this.cellSelectionMode_){this.$.body.classList.remove('cell-selection-mode');this.$.body.classList.add('row-selection-mode');this.$.body.classList.remove('row-highlight-enabled');}else{this.$.body.classList.add('cell-selection-mode');this.$.body.classList.remove('row-selection-mode');if(this.rowHighlightEnabled_)
this.$.body.classList.add('row-highlight-enabled');else
this.$.body.classList.remove('row-highlight-enabled');}
2015-06-14 13:52:57 -06:00
for(var i=0;i< this. $ . body . children . length ; i + + )
this.updateTabIndexForTableRowNode_(this.$.body.children[i]);this.maybeUpdateSelectedRow_();},maybeUpdateSelectedRow_:function(){if(this.selectedTableRowInfo_===undefined)
2015-06-18 08:27:29 -06:00
return;if(!this.supportsSelection_){this.removeSelectedState_();this.selectedTableRowInfo_=undefined;return;}
2015-06-14 13:52:57 -06:00
function isVisible(rowInfo){if(!rowInfo.htmlNode)
return false;return!!rowInfo.htmlNode.parentElement;}
2015-06-18 08:27:29 -06:00
if(isVisible(this.selectedTableRowInfo_)){this.updateSelectedState_();return;}
this.removeSelectedState_();var curRowInfo=this.selectedTableRowInfo_;while(curRowInfo& & !isVisible(curRowInfo))
2015-06-14 13:52:57 -06:00
curRowInfo=curRowInfo.parentRowInfo;this.selectedTableRowInfo_=curRowInfo;if(this.selectedTableRowInfo_)
2015-06-18 08:27:29 -06:00
this.updateSelectedState_();},didTableRowInfoGetClicked_:function(rowInfo,columnIndex){if(!this.supportsSelection_)
2015-06-14 13:52:57 -06:00
return;if(this.cellSelectionMode_){if(!this.doesColumnIndexSupportSelection(columnIndex))
return;}
if(this.selectedTableRowInfo_!==rowInfo)
this.selectedTableRow=rowInfo.userRow;if(this.selectedColumnIndex!==columnIndex)
this.selectedColumnIndex=columnIndex;},get selectedTableRow(){if(!this.selectedTableRowInfo_)
return undefined;return this.selectedTableRowInfo_.userRow;},set selectedTableRow(userRow){this.rebuildIfNeeded_();if(!this.supportsSelection_)
throw new Error('Selection is off. Set supportsSelection=true.');var rowInfo=this.tableRowsInfo_.get(userRow);if(rowInfo===undefined)
throw new Error('Row has not been seen, must expand its parents');var e=this.prepareToChangeSelection_();this.selectedTableRowInfo_=rowInfo;if(this.cellSelectionMode_){if(this.selectedTableRowInfo_& & this.selectedColumnIndex_===undefined){var i=this.getFirstSelectableColumnIndex_();if(i==-1)
throw new Error('nope');this.selectedColumnIndex_=i;}}else{this.selectedColumnIndex_=undefined;}
this.updateSelectedState_();this.dispatchEvent(e);},updateTabIndexForTableRowNode_:function(row){if(this.supportsSelection_){if(!this.cellSelectionMode_){row.tabIndex=0;}else{for(var i=0;i< this.tableColumns_.length ; i + + ) { if ( ! this . doesColumnIndexSupportSelection ( i ) )
continue;row.children[i].tabIndex=0;}}}else{if(!this.cellSelectionMode_){row.removeAttribute('tabIndex');}else{for(var i=0;i< this.tableColumns_.length ; i + + ) { if ( ! this . doesColumnIndexSupportSelection ( i ) )
continue;row.children[i].removeAttribute('tabIndex');}}}},prepareToChangeSelection_:function(){var e=new Event('selection-changed');var previousSelectedRowInfo=this.selectedTableRowInfo_;if(previousSelectedRowInfo)
e.previousSelectedTableRow=previousSelectedRowInfo.userRow;else
2015-06-18 08:27:29 -06:00
e.previousSelectedTableRow=undefined;this.removeSelectedState_();return e;},removeSelectedState_:function(){this.setSelectedState_(false);},updateSelectedState_:function(){this.setSelectedState_(true);},setSelectedState_:function(select){if(this.selectedTableRowInfo_===undefined)
return;var tableRowNode=this.selectedTableRowInfo_.htmlNode;if(this.cellSelectionMode_& & this.rowHighlightEnabled_){if(select)
tableRowNode.classList.add('highlighted-row');else
tableRowNode.classList.remove('highlighted-row');}
var node=this.getSelectableNodeGivenTableRowNode_(tableRowNode);if(select)
node.setAttribute('selected',true);else
node.removeAttribute('selected');},doesColumnIndexSupportSelection:function(columnIndex){var columnInfo=this.tableColumns_[columnIndex];var scs=columnInfo.supportsCellSelection;if(scs===false)
2015-06-14 13:52:57 -06:00
return false;return true;},getFirstSelectableColumnIndex_:function(){for(var i=0;i< this.tableColumns_.length ; i + + ) { if ( this . doesColumnIndexSupportSelection ( i ) )
return i;}
return-1;},getSelectableNodeGivenTableRowNode_:function(htmlNode){if(!this.cellSelectionMode_){return htmlNode;}else{return htmlNode.children[this.selectedColumnIndex_];}},get selectedColumnIndex(){if(!this.supportsSelection_)
return undefined;if(!this.cellSelectionMode_)
return undefined;return this.selectedColumnIndex_;},set selectedColumnIndex(selectedColumnIndex){this.rebuildIfNeeded_();if(!this.supportsSelection_)
throw new Error('Selection is off. Set supportsSelection=true.');if(selectedColumnIndex< 0 | | selectedColumnIndex > =this.tableColumns_.length)
throw new Error('Invalid index');if(!this.doesColumnIndexSupportSelection(selectedColumnIndex))
throw new Error('Selection is not supported on this column');var e=this.prepareToChangeSelection_();this.selectedColumnIndex_=selectedColumnIndex;if(this.selectedColumnIndex_===undefined)
this.selectedTableRowInfo_=undefined;this.updateSelectedState_();this.dispatchEvent(e);},onKeyDown_:function(e){if(this.supportsSelection_===false)
return;if(this.selectedTableRowInfo_===undefined)
return;var code_to_command_names={37:'ARROW_LEFT',38:'ARROW_UP',39:'ARROW_RIGHT',40:'ARROW_DOWN'};var cmdName=code_to_command_names[e.keyCode];if(cmdName===undefined)
2015-06-18 08:27:29 -06:00
return;e.stopPropagation();e.preventDefault();this.performKeyCommand_(cmdName);},performKeyCommand_:function(cmdName){this.rebuildIfNeeded_();var rowInfo=this.selectedTableRowInfo_;var htmlNode=rowInfo.htmlNode;if(cmdName==='ARROW_UP'){var prev=htmlNode.previousElementSibling;if(prev){tr.ui.b.scrollIntoViewIfNeeded(prev);this.selectedTableRow=prev.rowInfo.userRow;this.focusSelected_();return;}
2015-06-14 13:52:57 -06:00
return;}
2015-06-18 08:27:29 -06:00
if(cmdName==='ARROW_DOWN'){var next=htmlNode.nextElementSibling;if(next){tr.ui.b.scrollIntoViewIfNeeded(next);this.selectedTableRow=next.rowInfo.userRow;this.focusSelected_();return;}
2015-06-14 13:52:57 -06:00
return;}
if(cmdName==='ARROW_RIGHT'){if(this.cellSelectionMode_){var newIndex=this.selectedColumnIndex_+1;if(newIndex>=this.tableColumns_.length)
return;if(!this.doesColumnIndexSupportSelection(newIndex))
return;this.selectedColumnIndex=newIndex;this.focusSelected_();return;}else{if(rowInfo.userRow[this.subRowsPropertyName_]===undefined)
return;if(rowInfo.userRow[this.subRowsPropertyName_].length===0)
return;if(!rowInfo.isExpanded)
this.setExpandedForTableRow(rowInfo.userRow,true);this.selectedTableRow=rowInfo.userRow[this.subRowsPropertyName_][0];this.focusSelected_();return;}}
if(cmdName==='ARROW_LEFT'){if(this.cellSelectionMode_){var newIndex=this.selectedColumnIndex_-1;if(newIndex< 0 )
return;if(!this.doesColumnIndexSupportSelection(newIndex))
return;this.selectedColumnIndex=newIndex;this.focusSelected_();return;}else{if(rowInfo.isExpanded){this.setExpandedForTableRow(rowInfo.userRow,false);this.focusSelected_();return;}
var parentRowInfo=rowInfo.parentRowInfo;if(parentRowInfo){this.selectedTableRow=parentRowInfo.userRow;this.focusSelected_();return;}
return;}}
throw new Error('Unrecognized command');},focusSelected_:function(){if(!this.selectedTableRowInfo_)
2015-06-18 08:27:29 -06:00
return;var node=this.getSelectableNodeGivenTableRowNode_(this.selectedTableRowInfo_.htmlNode);node.focus();}});})();'use strict';Polymer('tr-ui-b-table-header-cell',{created:function(){this.tapCallback_=undefined;this.cellTitle_='';},set cellTitle(value){this.cellTitle_=value;var titleNode=tr.ui.b.asHTMLOrTextNode(this.cellTitle_,this.ownerDocument);this.$.title.innerText='';this.$.title.appendChild(titleNode);},get cellTitle(){return this.cellTitle_;},clearSideContent:function(){this.$.side.textContent='';},set sideContent(content){this.$.side.textContent=content;},get sideContent(){return this.$.side.textContent;},set tapCallback(callback){this.style.cursor='pointer';this.tapCallback_=callback;},get tapCallback(){return this.tapCallback_;},onTap_:function(){if(this.tapCallback_)
this.tapCallback_();}});'use strict';tr.exportTo('tr.b',function(){function _iterateElementDeeplyImpl(element,cb,thisArg,includeElement){if(includeElement){if(cb.call(thisArg,element))
return true;}
if(element.shadowRoot){if(_iterateElementDeeplyImpl(element.shadowRoot,cb,thisArg,false))
return true;}
for(var i=0;i< element.children.length ; i + + ) { if ( _iterateElementDeeplyImpl ( element . children [ i ] , cb , thisArg , true ) )
return true;}}
function iterateElementDeeply(element,cb,thisArg){_iterateElementDeeplyImpl(element,cb,thisArg,false);}
function findDeepElementMatchingPredicate(element,predicate){var foundElement=undefined;function matches(element){var match=predicate(element);if(!match)
return false;foundElement=element;return true;}
iterateElementDeeply(element,matches);return foundElement;}
function findDeepElementsMatchingPredicate(element,predicate){var foundElements=[];function matches(element){var match=predicate(element);if(match){foundElements.push(element);}
return false;}
iterateElementDeeply(element,matches);return foundElements;}
function findDeepElementMatching(element,selector){return findDeepElementMatchingPredicate(element,function(element){return element.matches(selector);});}
function findDeepElementsMatching(element,selector){return findDeepElementsMatchingPredicate(element,function(element){return element.matches(selector);});}
function findDeepElementWithTextContent(element,re){return findDeepElementMatchingPredicate(element,function(element){if(element.children.length!==0)
return false;return re.test(element.textContent);});}
return{iterateElementDeeply:iterateElementDeeply,findDeepElementMatching:findDeepElementMatching,findDeepElementsMatching:findDeepElementsMatching,findDeepElementMatchingPredicate:findDeepElementMatchingPredicate,findDeepElementsMatchingPredicate:findDeepElementsMatchingPredicate,findDeepElementWithTextContent:findDeepElementWithTextContent};});'use strict';tr.exportTo('tr.ui.units',function(){function createTimeSpan(duration){if(duration===undefined)
return'';var span=document.createElement('tr-ui-u-time-duration-span');span.duration=duration;return span;}
tr.b.units.Time.addEventListener('display-unit-changed',function(e){tr.b.findDeepElementsMatching(document.body,'tr-ui-u-time-duration-span').forEach(function(el){el.updateContent_();});});return{createTimeSpan:createTimeSpan};});'use strict';Polymer('tr-ui-u-time-duration-span',{ready:function(){this.warning_=undefined;this.duration_=undefined;},get duration(){return this.duration_;},set duration(duration){if(duration instanceof tr.b.units.TimeDuration)
this.duration_=duration.duration;else
this.duration_=duration;this.updateContent_();},updateContent_:function(){var content=tr.b.units.TimeDuration.format(this.duration_);this.$.content.textContent=content;},get warning(){return this.warning_;},set warning(warning){this.warning_=warning;var warningEl=this.$.warning;if(this.warning_){warningEl.title=warning;warningEl.style.display='';}else{warningEl.title='';warningEl.style.display='none';}}});'use strict';tr.exportTo('tr.ui.units',function(){function createTimeStampSpan(timestamp){if(timestamp===undefined)
return'';var span=document.createElement('tr-ui-u-time-stamp-span');span.timestamp=timestamp;return span;}
tr.b.units.Time.addEventListener('display-unit-changed',function(e){tr.b.findDeepElementsMatching(document.body,'tr-ui-u-time-stamp-span').forEach(function(el){el.updateContent_();});});return{createTimeStampSpan:createTimeStampSpan};});'use strict';Polymer('tr-ui-u-time-stamp-span',{ready:function(){this.timestamp_=undefined;},get timestamp(){return this.timestamp_;},set timestamp(timestamp){if(timestamp instanceof tr.b.units.TimeStamp)
this.timestamp_=timestamp.timestamp;else
this.timestamp_=timestamp;this.updateContent_();},updateContent_:function(){var content=tr.b.units.TimeStamp.format(this.timestamp_);this.shadowRoot.textContent=content;}});'use strict';Polymer('tr-ui-u-size-in-bytes-span',{ready:function(){this.$.content.textContent=String.fromCharCode(9888);this.numBytes_=undefined;},get numBytes(){return this.numBytes_;},set numBytes(numBytesOrSizeInBytes){if(numBytesOrSizeInBytes instanceof tr.b.units.SizeInBytes)
this.numBytes_=numBytesOrSizeInBytes.numBytes;else
this.numBytes_=numBytesOrSizeInBytes;this.$.content.textContent=tr.b.units.SizeInBytes.format(this.numBytes_);},get stringContent(){return this.$.content.textContent;}});'use strict';function isTable(object){if(!(object instanceof Array)||(object.length< 2 ) ) return false ; for ( var colName in object [ 0 ] ) { if ( typeof colName ! = = ' string ' ) return false ; }
2015-06-14 13:52:57 -06:00
for(var i=0;i< object.length ; + + i ) { if ( ! ( object [ i ] instanceof Object ) ) return false ; for ( var colName in object [ i ] ) { if ( i & & ( object [ 0 ] [ colName ] = = = undefined ) ) return false ; var cellType = typeof object [ i ] [ colName ] ; if ( cellType ! = = ' string ' & & cellType ! = ' number ' ) return false ; }
if(i){for(var colName in object[0]){if(object[i][colName]===undefined)return false;}}}
return true;}
2015-06-18 08:27:29 -06:00
Polymer('tr-ui-a-generic-object-view',{ready:function(){this.object_=undefined;},get object(){return this.object_;},set object(object){this.object_=object;this.updateContents_();},updateContents_:function(){this.$.content.textContent='';this.appendElementsForType_('',this.object_,0,0,5,'');},appendElementsForType_:function(label,object,indent,depth,maxDepth,suffix){if(depth>maxDepth){this.appendSimpleText_(label,indent,'< recursion limit reached > ',suffix);return;}
2015-06-14 13:52:57 -06:00
if(object===undefined){this.appendSimpleText_(label,indent,'undefined',suffix);return;}
if(object===null){this.appendSimpleText_(label,indent,'null',suffix);return;}
if(!(object instanceof Object)){var type=typeof object;if(type=='string'){var objectReplaced=false;if((object[0]=='{'&&object[object.length-1]=='}')||(object[0]=='['&&object[object.length-1]==']')){try{object=JSON.parse(object); objectReplaced=true;}catch(e){}}
if(!objectReplaced){if(object.indexOf('\n')!==-1){var lines=object.split('\n');lines.forEach(function(line,i){var text,ioff,ll,ss;if(i==0){text='"'+line;ioff=0;ll=label;ss='';}else if(i< lines.length-1 ) { text = line;ioff=1;ll='';ss='';}else{text=line+'"';ioff=1;ll='';ss=suffix;}
var el=this.appendSimpleText_(ll,indent+ioff*label.length+ioff,text,ss);el.style.whiteSpace='pre';return el;},this);return;}else{this.appendSimpleText_(label,indent,'"'+object+'"',suffix);return;}}
else{}}else{return this.appendSimpleText_(label,indent,object,suffix);}}
2015-06-18 08:27:29 -06:00
if(object instanceof tr.model.ObjectSnapshot){var link=document.createElement('tr-ui-a-analysis-link');link.selection=new tr.c.Selection(object);this.appendElementWithLabel_(label,indent,link,suffix);return;}
if(object instanceof tr.model.ObjectInstance){var link=document.createElement('tr-ui-a-analysis-link');link.selection=new tr.c.Selection(object);this.appendElementWithLabel_(label,indent,link,suffix);return;}
2015-06-14 13:52:57 -06:00
if(object instanceof tr.b.Rect){this.appendSimpleText_(label,indent,object.toString(),suffix);return;}
if(object instanceof tr.b.units.SizeInBytes){var el=this.ownerDocument.createElement('tr-ui-u-size-in-bytes-span');el.numBytes=object.numBytes;this.appendElementWithLabel_(label,indent,el,suffix);return;}
if(object instanceof tr.b.units.TimeDuration){var el=this.ownerDocument.createElement('tr-ui-u-time-duration-span');el.duration=object.duration;this.appendElementWithLabel_(label,indent,el,suffix);return;}
if(object instanceof tr.b.units.TimeStamp){var el=this.ownerDocument.createElement('tr-ui-u-time-stamp-span');el.timestamp=object.timestamp;this.appendElementWithLabel_(label,indent,el,suffix);return;}
if(object instanceof Array){this.appendElementsForArray_(label,object,indent,depth,maxDepth,suffix);return;}
this.appendElementsForObject_(label,object,indent,depth,maxDepth,suffix);},appendElementsForArray_:function(label,object,indent,depth,maxDepth,suffix){if(object.length==0){this.appendSimpleText_(label,indent,'[]',suffix);return;}
if(isTable(object)){var table=document.createElement('tr-ui-b-table');var columns=[];tr.b.iterItems(object[0],function(colName){columns.push({title:colName,value:function(row){return row[colName];}});});table.tableColumns=columns;table.tableRows=object;this.appendElementWithLabel_(label,indent,table,suffix);table.rebuild();return;}
this.appendElementsForType_(label+'[',object[0],indent,depth+1,maxDepth,object.length>1?',':']'+suffix);for(var i=1;i< object.length ; i + + ) { this . appendElementsForType_ ( ' ' , object [ i ] , indent + label . length + 1 , depth + 1 , maxDepth , i < object . length-1 ? ' , ' : ' ] ' + suffix ) ; }
return;},appendElementsForObject_:function(label,object,indent,depth,maxDepth,suffix){var keys=tr.b.dictionaryKeys(object);if(keys.length==0){this.appendSimpleText_(label,indent,'{}',suffix);return;}
this.appendElementsForType_(label+'{'+keys[0]+': ',object[keys[0]],indent,depth,maxDepth,keys.length>1?',':'}'+suffix);for(var i=1;i< keys.length ; i + + ) { this . appendElementsForType_ ( keys [ i ] + ' : ' , object [ keys [ i ] ] , indent + label . length + 1 , depth + 1 , maxDepth , i < keys . length-1 ? ' , ' : ' } ' + suffix ) ; } } , appendElementWithLabel_:function ( label , indent , dataElement , suffix ) { var row = document.createElement('div');var indentSpan = document.createElement('span');indentSpan.style.whiteSpace='pre';for(var i = 0;i<indent;i++)
2015-06-18 08:27:29 -06:00
indentSpan.textContent+=' ';row.appendChild(indentSpan);var labelSpan=document.createElement('span');labelSpan.textContent=label;row.appendChild(labelSpan);row.appendChild(dataElement);var suffixSpan=document.createElement('span');suffixSpan.textContent=suffix;row.appendChild(suffixSpan);row.dataElement=dataElement;this.$.content.appendChild(row);},appendSimpleText_:function(label,indent,text,suffix){var el=this.ownerDocument.createElement('span');el.textContent=text;this.appendElementWithLabel_(label,indent,el,suffix);return el;}});'use strict';Polymer('tr-ui-a-generic-object-view-with-label',{ready:function(){this.labelEl_=document.createElement('div');this.genericObjectView_=document.createElement('tr-ui-a-generic-object-view');this.shadowRoot.appendChild(this.labelEl_);this.shadowRoot.appendChild(this.genericObjectView_);},get label(){return this.labelEl_.textContent;},set label(label){this.labelEl_.textContent=label;},get object(){return this.genericObjectView_.object;},set object(object){this.genericObjectView_.object=object;}});'use strict';Polymer('tr-ui-a-stack-frame',{ready:function(){this.stackFrame_=undefined;},get stackFrame(){return this.stackFrame_;},set stackFrame(stackFrame){this.stackFrame_=stackFrame;this.$.ov.object=stackFrame.getUserFriendlyStackTrace();}});'use strict';Polymer('tr-ui-a-single-event-sub-view',{ready:function(){this.currentSelection_=undefined;this.$.table.tableColumns=[{title:'Label',value:function(row){return row.name;},width:'150px'},{title:'Value',width:'100%',value:function(row){return row.value;}}];this.$.table.showHeader=false;},get selection(){return this.currentSelection_;},set selection(selection){if(selection.length!==1)
2015-06-14 13:52:57 -06:00
throw new Error('Only supports single slices');this.setSelectionWithoutErrorChecks(selection);},setSelectionWithoutErrorChecks:function(selection){this.currentSelection_=selection;this.updateContents_();},getEventRows_:function(event){var rows=[];if(event.error)
rows.push({name:'Error',value:event.error});if(event.title)
rows.push({name:'Title',value:event.title});if(event.category)
rows.push({name:'Category',value:event.category});var startEl=document.createElement('tr-ui-u-time-stamp-span');startEl.timestamp=event.start;rows.push({name:'Start',value:startEl});if(event.duration){var wallDurationEl=document.createElement('tr-ui-u-time-duration-span');wallDurationEl.duration=event.duration;rows.push({name:'Wall Duration',value:wallDurationEl});}
if(event.cpuDuration){var cpuDurationEl=document.createElement('tr-ui-u-time-duration-span');cpuDurationEl.duration=event.cpuDuration;rows.push({name:'CPU Duration',value:cpuDurationEl});}
if(event.subSlices!==undefined& & event.subSlices.length!==0){if(event.selfTime){var selfTimeEl=document.createElement('tr-ui-u-time-duration-span');selfTimeEl.duration=event.selfTime;rows.push({name:'Self Time',value:selfTimeEl});}
if(event.cpuSelfTime){var cpuSelfTimeEl=document.createElement('tr-ui-u-time-duration-span');cpuSelfTimeEl.duration=event.cpuSelfTime;if(event.cpuSelfTime>event.selfTime){cpuSelfTimeEl.warning=' Note that CPU Self Time is larger than Self Time. '+'This is a known limitation of this system, which occurs '+'due to several subslices, rounding issues, and imprecise '+'time at which we get cpu- and real-time.';}
rows.push({name:'CPU Self Time',value:cpuSelfTimeEl});}}
if(event.durationInUserTime){var durationInUserTimeEl=document.createElement('tr-ui-u-time-duration-span');durationInUserTimeEl.duration=event.durationInUserTime;rows.push({name:'Duration (U)',value:durationInUserTimeEl});}
2015-06-18 08:27:29 -06:00
function createStackFrameEl(sf){var sfEl=document.createElement('tr-ui-a-stack-frame');sfEl.stackFrame=sf;return sfEl;}
2015-06-14 13:52:57 -06:00
if(event.startStackFrame& & event.endStackFrame){if(event.startStackFrame===event.endStackFrame){rows.push({name:'Start+End Stack Trace',value:createStackFrameEl(event.startStackFrame)});}else{rows.push({name:'Start Stack Trace',value:createStackFrameEl(event.startStackFrame)});rows.push({name:'End Stack Trace',value:createStackFrameEl(event.endStackFrame)});}}else if(event.startStackFrame){rows.push({name:'Start Stack Trace',value:createStackFrameEl(event.startStackFrame)});}else if(event.endStackFrame){rows.push({name:'End Stack Trace',value:createStackFrameEl(event.endStackFrame)});}
if(event.info){var descriptionEl=tr.ui.b.createDiv({textContent:event.info.description,maxWidth:'300px'});rows.push({name:'Description',value:descriptionEl});if(event.info.docLinks){event.info.docLinks.forEach(function(linkObject){var linkEl=document.createElement('a');linkEl.target='_blank';linkEl.href=linkObject.href;linkEl.textContent=linkObject.textContent;rows.push({name:linkObject.label,value:linkEl});});}}
2015-06-18 08:27:29 -06:00
if(event.associatedAlerts.length){var alertSubRows=[];event.associatedAlerts.forEach(function(alert){var linkEl=document.createElement('tr-ui-a-analysis-link');linkEl.setSelectionAndContent(function(){return new tr.c.Selection(alert);},alert.info.description);alertSubRows.push({name:alert.title,value:linkEl});});rows.push({name:'Alerts',value:'',isExpanded:true,subRows:alertSubRows});}
2015-06-14 13:52:57 -06:00
return rows;},addArgsToRows_:function(rows,args){var n=0;for(var argName in args){n+=1;}
2015-06-18 08:27:29 -06:00
if(n>0){var subRows=[];for(var argName in args){var argView=document.createElement('tr-ui-a-generic-object-view');argView.object=args[argName];subRows.push({name:argName,value:argView});}
2015-06-14 13:52:57 -06:00
rows.push({name:'Args',value:'',isExpanded:true,subRows:subRows});}
return rows;},updateContents_:function(){if(this.currentSelection_===undefined){this.$.table.rows=[];this.$.table.rebuild();return;}
2015-06-18 08:27:29 -06:00
var event=this.currentSelection_[0];var rows=this.getEventRows_(event);if(event.argsStripped)
rows.push({name:'Args',value:'Stripped'});else
this.addArgsToRows_(rows,event.args);this.$.table.tableRows=rows;this.$.table.rebuild();}});'use strict';tr.exportTo('tr.ui.analysis',function(){var FLOW_IN=0x1;var FLOW_OUT=0x2;var FLOW_IN_OUT=FLOW_IN|FLOW_OUT;function FlowClassifier(){this.numEvents_=0;this.eventsByGUID_={};}
2015-06-14 13:52:57 -06:00
FlowClassifier.prototype={getFS_:function(event){var fs=this.eventsByGUID_[event.guid];if(fs===undefined){this.numEvents_++;fs={state:0,event:event};this.eventsByGUID_[event.guid]=fs;}
return fs;},addInFlow:function(event){var fs=this.getFS_(event);fs.state|=FLOW_IN;return event;},addOutFlow:function(event){var fs=this.getFS_(event);fs.state|=FLOW_OUT;return event;},hasEvents:function(){return this.numEvents_>0;},get inFlowEvents(){var selection=new tr.c.Selection();for(var guid in this.eventsByGUID_){var fs=this.eventsByGUID_[guid];if(fs.state===FLOW_IN)
selection.push(fs.event);}
return selection;},get outFlowEvents(){var selection=new tr.c.Selection();for(var guid in this.eventsByGUID_){var fs=this.eventsByGUID_[guid];if(fs.state===FLOW_OUT)
selection.push(fs.event);}
return selection;},get internalFlowEvents(){var selection=new tr.c.Selection();for(var guid in this.eventsByGUID_){var fs=this.eventsByGUID_[guid];if(fs.state===FLOW_IN_OUT)
selection.push(fs.event);}
2015-06-18 08:27:29 -06:00
return selection;}};return{FlowClassifier:FlowClassifier};});'use strict';Polymer('tr-ui-a-related-events',{ready:function(){this.eventGroups_=[];this.$.table.tableColumns=[{title:'Event(s)',value:function(row){var typeEl=document.createElement('span');typeEl.innerText=row.type;if(row.tooltip)
typeEl.title=row.tooltip;return typeEl;},width:'150px'},{title:'Link',width:'100%',value:function(row){var linkEl=document.createElement('tr-ui-a-analysis-link');if(row.name)
2015-06-14 13:52:57 -06:00
linkEl.setSelectionAndContent(row.selection,row.name);else
2015-06-18 08:27:29 -06:00
linkEl.selection=row.selection;return linkEl;}}];},hasRelatedEvents:function(){return(this.eventGroups_&&this.eventGroups_.length>0); },addRelatedEvents:function(selection){this.addConnectedFlows_(selection);this.addConnectedEvents_(selection);this.addAncestorsAndDescendents_(selection);this.updateContents_();},addConnectedFlows_:function(selection){var classifier=new tr.ui.analysis.FlowClassifier();selection.forEach(function(slice){if(slice.inFlowEvents){slice.inFlowEvents.forEach(function(flow){classifier.addInFlow(flow);});}
2015-06-14 13:52:57 -06:00
if(slice.outFlowEvents){slice.outFlowEvents.forEach(function(flow){classifier.addOutFlow(flow);});}});if(!classifier.hasEvents())
return;var addToEventGroups=function(type,flowEvent){this.eventGroups_.push({type:type,selection:new tr.c.Selection(flowEvent),name:flowEvent.title});};classifier.inFlowEvents.forEach(addToEventGroups.bind(this,'Incoming flow'));classifier.outFlowEvents.forEach(addToEventGroups.bind(this,'Outgoing flow'));classifier.internalFlowEvents.forEach(addToEventGroups.bind(this,'Internal flow'));},addConnectedEvents_:function(selection){if(selection.length===1)
this.addConnectedEventsForSlice_(selection[0]);else
this.addConnectedEventsForSelection_(selection);},addAncestorsAndDescendents_:function(selection){if(selection.length===1)
this.addAncestorsAndDescendentsForSlice_(selection[0]);else
this.addAncestorsAndDescendentsForSelection_(selection);},addConnectedEventsForSlice_:function(slice){var precedingEventsSelection=undefined;var followingEventsSelection=undefined;if(slice.inFlowEvents& & slice.inFlowEvents.length!==0){precedingEventsSelection=new tr.c.Selection();this.recursivelyAddConnectedEvents_(precedingEventsSelection,slice,function(event){return event.inFlowEvents;});this.eventGroups_.push({type:'Preceding events',tooltip:'All preceding events connected to this one by flow arrows.',selection:precedingEventsSelection});}
if(slice.outFlowEvents& & slice.outFlowEvents.length!==0){followingEventsSelection=new tr.c.Selection();this.recursivelyAddConnectedEvents_(followingEventsSelection,slice,function(event){return event.outFlowEvents;});this.eventGroups_.push({type:'Following events',tooltip:'All following events connected to this one by flow arrows.',selection:followingEventsSelection});}
if(precedingEventsSelection& & followingEventsSelection){var allEventsSelection=new tr.c.Selection();for(var i=0;i< precedingEventsSelection.length ; + + i )
allEventsSelection.push(precedingEventsSelection[i]);for(var i=0;i< followingEventsSelection.length ; + + i )
allEventsSelection.push(followingEventsSelection[i]);this.eventGroups_.push({type:'All connected events',tooltip:'All events connected to this one by flow arrows.',selection:allEventsSelection});}},addConnectedEventsForSelection_:function(selection){var allEventsSelection=new tr.c.Selection();selection.forEach(function(slice){this.recursivelyAddConnectedEvents_(allEventsSelection,slice,function(event){var flows=[];if(event.inFlowEvents)
flows=flows.concat(event.inFlowEvents);if(event.outFlowEvents)
flows=flows.concat(event.outFlowEvents);return flows;});}.bind(this));if(allEventsSelection.length>selection.length){this.eventGroups_.push({type:'All connected events',tooltip:'All events connected to this selection by flow arrows.',selection:allEventsSelection});}},recursivelyAddConnectedEvents_:function(selection,event,getFlows){if(!event||selection.contains(event))
return;selection.push(event);var flowEvents=getFlows(event);if(!flowEvents)
return;for(var i=0;i< flowEvents.length ; + + i ) { selection . push ( flowEvents [ i ] ) ; this . recursivelyAddConnectedEvents_ ( selection , flowEvents [ i ] . startSlice , getFlows ) ; this . recursivelyAddConnectedEvents_ ( selection , flowEvents [ i ] . endSlice , getFlows ) ; } } , addAncestorsAndDescendentsForSlice_:function ( slice ) { if ( ! slice . iterateAllAncestors | | ! slice . iterateAllDescendents )
return;var ancestorsSelection=new tr.c.Selection(slice);var descendentsSelection=new tr.c.Selection(slice);var allSlicesSelection=new tr.c.Selection(slice);slice.iterateAllAncestors(function(otherSlice){ancestorsSelection.push(otherSlice);});slice.iterateAllDescendents(function(otherSlice){descendentsSelection.push(otherSlice);});if(ancestorsSelection.length>1){this.eventGroups_.push({type:'Ancestors',tooltip:'All slices above this one on this thread.',selection:ancestorsSelection});}
if(descendentsSelection.length>1){this.eventGroups_.push({type:'Descendents',tooltip:'All slices below this one on this thread.',selection:descendentsSelection});}
if(ancestorsSelection.length>1& & descendentsSelection.length>1){for(var i=0;i< ancestorsSelection.length ; + + i )
allSlicesSelection.push(ancestorsSelection[i]);for(var i=0;i< descendentsSelection.length ; + + i )
allSlicesSelection.push(descendentsSelection[i]);this.eventGroups_.push({type:'Hierarchy',tooltip:'All slices above or below this one on this thread.',selection:allSlicesSelection});}},addAncestorsAndDescendentsForSelection_:function(selection){var allSlicesSelection=new tr.c.Selection();selection.forEach(function(slice){allSlicesSelection.push(slice);if(slice.iterateAllAncestors&&slice.iterateAllDescendents){slice.iterateAllAncestors(function(otherSlice){allSlicesSelection.push(otherSlice); });slice.iterateAllDescendents(function(otherSlice){allSlicesSelection.push(otherSlice);});}}.bind(this));if(allSlicesSelection.length>selection.length){this.eventGroups_.push({type:'All hierarchies',tooltip:'All slices above or below any slice in the selection.',selection:allSlicesSelection});}},updateContents_:function(){var table=this.$.table;if(this.eventGroups_===undefined)
table.tableRows=[];else
2015-06-18 08:27:29 -06:00
table.tableRows=this.eventGroups_.slice();table.rebuild();}});'use strict';Polymer('tr-ui-a-single-thread-slice-sub-view',{get selection(){return this.$.content.selection;},set selection(selection){this.$.content.selection=selection;this.$.relatedEvents.addRelatedEvents(selection);if(this.$.relatedEvents.hasRelatedEvents())
2015-06-14 13:52:57 -06:00
this.$.relatedEvents.style.display='';else
2015-06-18 08:27:29 -06:00
this.$.relatedEvents.style.display='none';}});'use strict';Polymer('tr-ui-a-selection-summary-table',{created:function(){this.selection_=new tr.b.Range();},ready:function(){this.$.table.showHeader=false;this.$.table.tableColumns=[{title:'Name',value:function(row){return row.title;},width:'350px'},{title:'Value',width:'100%',value:function(row){return row.value;}}];},get selection(){return this.selection_;},set selection(selection){this.selection_=selection;this.updateContents_();},updateContents_:function(){var selection=this.selection_;var rows=[];var hasRange;if(this.selection_& & (!selection.bounds.isEmpty))
2015-06-14 13:52:57 -06:00
hasRange=true;else
hasRange=false;rows.push({title:'Selection start',value:hasRange?tr.ui.units.createTimeStampSpan(selection.bounds.min):'< empty > '});rows.push({title:'Selection extent',value:hasRange?tr.ui.units.createTimeSpan(selection.bounds.range):'< empty > '});this.$.table.tableRows=rows;this.$.table.rebuild();}});'use strict';tr.exportTo('tr.b',function(){function identity(d){return d;}
function Statistics(){}
Statistics.sum=function(ary,opt_func,opt_this){var func=opt_func||identity;var ret=0;for(var i=0;i< ary.length ; i + + )
ret+=func.call(opt_this,ary[i],i);return ret;};Statistics.mean=function(ary,opt_func,opt_this){return Statistics.sum(ary,opt_func,opt_this)/ary.length;};Statistics.variance=function(ary,opt_func,opt_this){var func=opt_func||identity;var mean=Statistics.mean(ary,func,opt_this);var sumOfSquaredDistances=Statistics.sum(ary,function(d,i){var v=func.call(this,d,i)-mean;return v*v;},opt_this);return sumOfSquaredDistances/(ary.length-1);};Statistics.stddev=function(ary,opt_func,opt_this){return Math.sqrt(Statistics.variance(ary,opt_func,opt_this));};Statistics.max=function(ary,opt_func,opt_this){var func=opt_func||identity;var ret=-Infinity;for(var i=0;i< ary.length ; i + + )
ret=Math.max(ret,func.call(opt_this,ary[i],i));return ret;};Statistics.min=function(ary,opt_func,opt_this){var func=opt_func||identity;var ret=Infinity;for(var i=0;i< ary.length ; i + + )
ret=Math.min(ret,func.call(opt_this,ary[i],i));return ret;};Statistics.range=function(ary,opt_func,opt_this){var func=opt_func||identity;var ret=new tr.b.Range();for(var i=0;i< ary.length ; i + + )
ret.addValue(func.call(opt_this,ary[i],i));return ret;}
Statistics.percentile=function(ary,percent,opt_func,opt_this){if(!(percent>=0& & percent< =1))
throw new Error('percent must be [0,1]');var func=opt_func||identity;var tmp=new Array(ary.length);for(var i=0;i< ary.length ; i + + )
2015-06-18 08:27:29 -06:00
tmp[i]=func.call(opt_this,ary[i],i);tmp.sort();var idx=Math.floor((ary.length-1)*percent);return tmp[idx];};return{Statistics:Statistics};});'use strict';tr.exportTo('tr.ui.analysis',function(){function MultiEventSummary(title,events){this.title=title;this.duration_=undefined;this.selfTime_=undefined;this.events_=events;this.cpuTimesComputed_=false;this.cpuSelfTime_=undefined;this.cpuDuration_=undefined;this.untotallableArgs_=[];this.totalledArgs_=undefined;};MultiEventSummary.prototype={get duration(){if(this.duration_===undefined){this.duration_=tr.b.Statistics.sum(this.events_,function(event){return event.duration;});}
2015-06-14 13:52:57 -06:00
return this.duration_;},get cpuSelfTime(){this.computeCpuTimesIfNeeded_();return this.cpuSelfTime_;},get cpuDuration(){this.computeCpuTimesIfNeeded_();return this.cpuDuration_;},computeCpuTimesIfNeeded_:function(){if(this.cpuTimesComputed_)
return;this.cpuTimesComputed_=true;var cpuSelfTime=0;var cpuDuration=0;var hasCpuData=false;for(var i=0;i< this.events_.length ; i + + ) { var event = this.events_[i];if(event.cpuDuration!==undefined){cpuDuration+=event.cpuDuration;hasCpuData=true;}
if(event.cpuSelfTime!==undefined){cpuSelfTime+=event.cpuSelfTime;hasCpuData=true;}}
if(hasCpuData){this.cpuDuration_=cpuDuration;this.cpuSelfTime_=cpuSelfTime;}},get selfTime(){if(this.selfTime_===undefined){this.selfTime_=0;for(var i=0;i< this.events_.length ; i + + ) { if ( this . events_ [ i ] . selfTime ! = = undefined )
this.selfTime_+=this.events[i].selfTime;}}
return this.selfTime_;},get events(){return this.events_;},get numEvents(){return this.events_.length;},get numAlerts(){if(this.numAlerts_===undefined){this.numAlerts_=tr.b.Statistics.sum(this.events_,function(event){return event.associatedAlerts.length;});}
return this.numAlerts_;},get untotallableArgs(){this.updateArgsIfNeeded_();return this.untotallableArgs_;},get totalledArgs(){this.updateArgsIfNeeded_();return this.totalledArgs_;},updateArgsIfNeeded_:function(){if(this.totalledArgs_!==undefined)
return;var untotallableArgs={};var totalledArgs={};for(var i=0;i< this.events_.length ; i + + ) { var event = this.events_[i];for(var argName in event . args ) { var argVal = event.args[argName];var type = typeof argVal ; if ( type ! = = ' number ' ) { untotallableArgs [ argName ] = true ; delete totalledArgs [ argName ] ; continue ; }
if(untotallableArgs[argName]){continue;}
if(totalledArgs[argName]===undefined)
totalledArgs[argName]=0;totalledArgs[argName]+=argVal;}}
2015-06-18 08:27:29 -06:00
this.untotallableArgs_=tr.b.dictionaryKeys(untotallableArgs);this.totalledArgs_=totalledArgs;}};return{MultiEventSummary:MultiEventSummary};});'use strict';Polymer('tr-ui-a-multi-event-summary-table',{ready:function(){this.showTotals_=false;this.eventsHaveDuration_=true;this.eventsHaveSubRows_=true;this.eventsByTitle_=undefined;},updateTableColumns_:function(rows){var hasCpuData=false;var hasAlerts=false;rows.forEach(function(row){if(row.cpuDuration!==undefined)
2015-06-14 13:52:57 -06:00
hasCpuData=true;if(row.cpuSelfTime!==undefined)
hasCpuData=true;if(row.numAlerts)
hasAlerts=true;});var columns=[];columns.push({title:'Name',value:function(row){if(row.title==='Totals')
2015-06-18 08:27:29 -06:00
return'Totals';var linkEl=document.createElement('tr-ui-a-analysis-link');linkEl.setSelectionAndContent(function(){return new tr.c.Selection(row.events);},row.title);return linkEl;},width:'350px',cmp:function(rowA,rowB){return rowA.title.localeCompare(rowB.title);}});if(this.eventsHaveDuration_){columns.push({title:'Wall Duration (ms)',value:function(row){return tr.ui.units.createTimeSpan(row.duration);},width:'< upated further down > ',cmp:function(rowA,rowB){return rowA.duration-rowB.duration;}});}
2015-06-14 13:52:57 -06:00
if(this.eventsHaveDuration_& & hasCpuData){columns.push({title:'CPU Duration (ms)',value:function(row){return tr.ui.units.createTimeSpan(row.cpuDuration);},width:'< upated further down > ',cmp:function(rowA,rowB){return rowA.cpuDuration-rowB.cpuDuration;}});}
if(this.eventsHaveSubRows_& & this.eventsHaveDuration_){columns.push({title:'Self time (ms)',value:function(row){return tr.ui.units.createTimeSpan(row.selfTime);},width:'< upated further down > ',cmp:function(rowA,rowB){return rowA.selfTime-rowB.selfTime;}});}
if(this.eventsHaveSubRows_& & this.eventsHaveDuration_& & hasCpuData){columns.push({title:'CPU Self Time (ms)',value:function(row){return tr.ui.units.createTimeSpan(row.cpuSelfTime);},width:'< upated further down > ',cmp:function(rowA,rowB){return rowA.cpuSelfTime-rowB.cpuSelfTime;}});}
columns.push({title:'Occurrences',value:function(row){return row.numEvents;},width:'< upated further down > ',cmp:function(rowA,rowB){return rowA.numEvents-rowB.numEvents;}});var alertsColumnIndex;if(hasAlerts){columns.push({title:'Num Alerts',value:function(row){return row.numAlerts;},width:'< upated further down > ',cmp:function(rowA,rowB){return rowA.numAlerts-rowB.numAlerts;}});alertsColumnIndex=columns.length-1;}
var colWidthPercentage;if(columns.length==1)
colWidthPercentage='100%';else
colWidthPercentage=(100/(columns.length-1)).toFixed(3)+'%';for(var i=1;i< columns.length ; i + + )
columns[i].width=colWidthPercentage;this.$.table.tableColumns=columns;if(hasAlerts){this.$.table.sortColumnIndex=alertsColumnIndex;this.$.table.sortDescending=true;}},configure:function(config){if(config.eventsByTitle===undefined)
throw new Error('Required: eventsByTitle');if(config.showTotals!==undefined)
this.showTotals_=config.showTotals;else
this.showTotals_=true;if(config.eventsHaveDuration!==undefined)
this.eventsHaveDuration_=config.eventsHaveDuration;else
this.eventsHaveDuration_=true;if(config.eventsHaveSubRows!==undefined)
this.eventsHaveSubRows_=config.eventsHaveSubRows;else
this.eventsHaveSubRows_=true;this.eventsByTitle_=config.eventsByTitle;this.updateContents_();},get showTotals(){return this.showTotals_;},set showTotals(showTotals){this.showTotals_=showTotals;this.updateContents_();},get eventsHaveDuration(){return this.eventsHaveDuration_;},set eventsHaveDuration(eventsHaveDuration){this.eventsHaveDuration_=eventsHaveDuration;this.updateContents_();},get eventsHaveSubRows(){return this.eventsHaveSubRows_;},set eventsHaveSubRows(eventsHaveSubRows){this.eventsHaveSubRows_=eventsHaveSubRows;this.updateContents_();},get eventsByTitle(){return this.eventsByTitle_;},set eventsByTitle(eventsByTitle){this.eventsByTitle_=eventsByTitle;this.updateContents_();},get selectionBounds(){return this.selectionBounds_;},set selectionBounds(selectionBounds){this.selectionBounds_=selectionBounds;this.updateContents_();},updateContents_:function(){var eventsByTitle;if(this.eventsByTitle_!==undefined)
eventsByTitle=this.eventsByTitle_;else
2015-06-18 08:27:29 -06:00
eventsByTitle=[];var allEvents=[];var rows=[];tr.b.iterItems(eventsByTitle,function(title,eventsOfSingleTitle){allEvents.push.apply(allEvents,eventsOfSingleTitle);var row=new tr.ui.analysis.MultiEventSummary(title,eventsOfSingleTitle);rows.push(row);});this.updateTableColumns_(rows);this.$.table.tableRows=rows;var footerRows=[];if(this.showTotals_){footerRows.push(new tr.ui.analysis.MultiEventSummary('Totals',allEvents));}
this.$.table.footerRows=footerRows;this.$.table.rebuild();}});'use strict';Polymer('tr-ui-a-multi-event-details-table',{created:function(){this.selection_=undefined;this.eventsHaveDuration_=true;this.eventsHaveSubRows_=true;},ready:function(){this.initTitleTable_();},get eventsHaveDuration(){return this.eventsHaveDuration_;},set eventsHaveDuration(eventsHaveDuration){this.eventsHaveDuration_=eventsHaveDuration;this.updateContents_();},get eventsHaveSubRows(){return this.eventsHaveSubRows_;},set eventsHaveSubRows(eventsHaveSubRows){this.eventsHaveSubRows_=eventsHaveSubRows;this.updateContents_();},get selection(){return this.selection_;},set selection(selection){this.selection_=selection;this.updateContents_();},updateContents_:function(){var selection=this.selection_;this.updateTitleTable_();if(this.selection_===undefined){this.$.table.tableRows=[];this.$.table.tableFooterRows=[];this.$.table.rebuild();return;}
var summary=new tr.ui.analysis.MultiEventSummary('Totals',this.selection_);this.updateColumns_(summary);this.updateRows_(summary);this.$.table.rebuild();},initTitleTable_:function(){var table=this.$.titletable;table.showHeader=false;table.tableColumns=[{title:'Title',value:function(row){return row.title;},width:'350px'},{title:'Value',width:'100%',value:function(row){return row.value;}}];},updateTitleTable_:function(){var title;if(this.selection_& & this.selection_.length)
2015-06-14 13:52:57 -06:00
title=this.selection_[0].title;else
title='< No selection > ';var table=this.$.titletable;table.tableRows=[{title:'Title',value:title}];},updateColumns_:function(summary){var hasCpuData;if(summary.cpuDuration!==undefined)
hasCpuData=true;if(summary.cpuSelfTime!==undefined)
hasCpuData=true;var colWidthPercentage;if(hasCpuData)
colWidthPercentage='20%';else
2015-06-18 08:27:29 -06:00
colWidthPercentage='33.3333%';var columns=[];columns.push({title:'Start',value:function(row){if(row.__proto__===tr.ui.analysis.MultiEventSummary.prototype){return row.title;}
var linkEl=document.createElement('tr-ui-a-analysis-link');linkEl.setSelectionAndContent(function(){return new tr.c.Selection(row.event);});linkEl.appendChild(tr.ui.units.createTimeStampSpan(row.start));return linkEl;},width:'350px',cmp:function(rowA,rowB){return rowA.start-rowB.start;}});if(this.eventsHaveDuration_){columns.push({title:'Wall Duration (ms)',value:function(row){return tr.ui.units.createTimeSpan(row.duration);},width:'< upated further down > ',cmp:function(rowA,rowB){return rowA.duration-rowB.duration;}});}
2015-06-14 13:52:57 -06:00
if(this.eventsHaveDuration_& & hasCpuData){columns.push({title:'CPU Duration (ms)',value:function(row){return tr.ui.units.createTimeSpan(row.cpuDuration);},width:'< upated further down > ',cmp:function(rowA,rowB){return rowA.cpuDuration-rowB.cpuDuration;}});}
if(this.eventsHaveSubRows_& & this.eventsHaveDuration_){columns.push({title:'Self time (ms)',value:function(row){return tr.ui.units.createTimeSpan(row.selfTime);},width:'< upated further down > ',cmp:function(rowA,rowB){return rowA.selfTime-rowB.selfTime;}});}
if(this.eventsHaveSubRows_& & this.eventsHaveDuration_& & hasCpuData){columns.push({title:'CPU Self Time (ms)',value:function(row){return tr.ui.units.createTimeSpan(row.cpuSelfTime);},width:'< upated further down > ',cmp:function(rowA,rowB){return rowA.cpuSelfTime-rowB.cpuSelfTime;}});}
2015-06-18 08:27:29 -06:00
var argKeys=tr.b.dictionaryKeys(summary.totalledArgs);argKeys.sort();var otherKeys=summary.untotallableArgs.slice(0);otherKeys.sort();argKeys.push.apply(argKeys,otherKeys);var keysWithColumns=argKeys.slice(0,4);var keysInOtherColumn=argKeys.slice(4);keysWithColumns.forEach(function(argKey){var hasTotal=summary.totalledArgs[argKey];var colDesc={title:'Arg: '+argKey,value:function(row){if(row.__proto__!==tr.ui.analysis.MultiEventSummary.prototype){var argView=document.createElement('tr-ui-a-generic-object-view');argView.object=row.args[argKey];return argView;}
2015-06-14 13:52:57 -06:00
if(hasTotal)
return row.totalledArgs[argKey];return'';},width:'< upated further down > '};if(hasTotal){colDesc.cmp=function(rowA,rowB){return rowA.args[argKey]-rowB.args[argKey];}}
2015-06-18 08:27:29 -06:00
columns.push(colDesc);});if(keysInOtherColumn.length){columns.push({title:'Other Args',value:function(row){if(row.__proto__===tr.ui.analysis.MultiEventSummary.prototype)
return'';var argView=document.createElement('tr-ui-a-generic-object-view');var obj={};for(var i=0;i< keysInOtherColumn.length ; i + + )
2015-06-14 13:52:57 -06:00
obj[keysInOtherColumn[i]]=row.args[keysInOtherColumn[i]];argView.object=obj;return argView;},width:'< upated further down > '});}
var colWidthPercentage;if(columns.length==1)
colWidthPercentage='100%';else
colWidthPercentage=(100/(columns.length-1)).toFixed(3)+'%';for(var i=1;i< columns.length ; i + + )
columns[i].width=colWidthPercentage;this.$.table.tableColumns=columns;},updateRows_:function(summary){this.$.table.sortColumnIndex=0;function Row(event){this.event=event;}
2015-06-18 08:27:29 -06:00
Row.prototype={get start(){return this.event.start;},get duration(){return this.event.duration;},get cpuDuration(){return this.event.cpuDuration;},get selfTime(){return this.event.selfTime;},get cpuSelfTime(){return this.event.cpuSelfTime;},get args(){return this.event.args;}};this.$.table.tableRows=this.selection_.map(function(event){return new Row(event);});this.$.table.footerRows=[summary];}});'use strict';Polymer('tr-ui-a-multi-event-sub-view',{created:function(){this.currentSelection_=undefined;this.eventsHaveDuration_=true;this.eventsHaveSubRows_=true;},set selection(selection){if(selection.length< =1)
2015-06-14 13:52:57 -06:00
throw new Error('Only supports multiple items');this.setSelectionWithoutErrorChecks(selection);},get selection(){return this.currentSelection_;},setSelectionWithoutErrorChecks:function(selection){this.currentSelection_=selection;this.updateContents_();},get eventsHaveDuration(){return this.eventsHaveDuration_;},set eventsHaveDuration(eventsHaveDuration){this.eventsHaveDuration_=eventsHaveDuration;this.updateContents_();},get eventsHaveSubRows(){return this.eventsHaveSubRows_;},set eventsHaveSubRows(eventsHaveSubRows){this.eventsHaveSubRows_=eventsHaveSubRows;this.updateContents_();},updateContents_:function(){var selection=this.currentSelection_;this.$.content.textContent='';if(!selection)
2015-06-18 08:27:29 -06:00
return;var eventsByTitle=selection.getEventsOrganizedByTitle();var numTitles=tr.b.dictionaryLength(eventsByTitle);var summaryTableEl=document.createElement('tr-ui-a-multi-event-summary-table');summaryTableEl.configure({showTotals:numTitles>1,eventsByTitle:eventsByTitle,eventsHaveDuration:this.eventsHaveDuration_,eventsHaveSubRows:this.eventsHaveSubRows_});this.$.content.appendChild(summaryTableEl);var selectionSummaryTableEl=document.createElement('tr-ui-a-selection-summary-table');selectionSummaryTableEl.selection=this.currentSelection_;this.$.content.appendChild(selectionSummaryTableEl);if(numTitles===1){var detailsTableEl=document.createElement('tr-ui-a-multi-event-details-table');detailsTableEl.eventsHaveDuration=this.eventsHaveDuration_;detailsTableEl.eventsHaveSubRows=this.eventsHaveSubRows_;detailsTableEl.selection=selection;this.$.content.appendChild(detailsTableEl);}}});'use strict';Polymer('tr-ui-a-multi-thread-slice-sub-view',{created:function(){this.selection_=undefined;},get selection(){return this.selection_;},set selection(selection){this.selection_=selection;if(window.RasterTaskView!==undefined){if(tr.e.cc.RasterTaskSelection.supports(selection)){var ltvSelection=new tr.e.cc.RasterTaskSelection(selection);var ltv=new tr.ui.e.chrome.cc.LayerTreeHostImplSnapshotView();ltv.objectSnapshot=ltvSelection.containingSnapshot;ltv.selection=ltvSelection;ltv.extraHighlightsByLayerId=ltvSelection.extraHighlightsByLayerId;this.$.content.textContent='';this.$.content.appendChild(ltv);this.requiresTallView_=true;return;}}
this.$.content.textContent='';var mesv=document.createElement('tr-ui-a-multi-event-sub-view');mesv.selection=selection;this.$.content.appendChild(mesv);var relatedEvents=document.createElement('tr-ui-a-related-events');relatedEvents.addRelatedEvents(selection);if(relatedEvents.hasRelatedEvents()){this.$.content.appendChild(relatedEvents);}},get requiresTallView(){if(this.$.content.children.length===0)
return false;var childTagName=this.$.content.children[0].tagName;if(childTagName==='TR-UI-A-MULTI-EVENT-SUB-VIEW')
return false;return true;}});'use strict';Polymer('tr-ui-a-single-async-slice-sub-view',{getEventRows_:function(event){var rows=this.__proto__.__proto__.getEventRows_(event);rows.splice(0,0,{name:'ID',value:event.id});return rows;},get relatedEventsToHighlight(){if(!this.currentSelection_)
return undefined;return this.currentSelection_[0].associatedEvents;}});'use strict';Polymer('tr-ui-a-multi-async-slice-sub-view',{get selection(){return this.$.content.selection;},set selection(selection){this.$.content.selection=selection;},get relatedEventsToHighlight(){if(!this.$.content.selection)
return undefined;var selection=new tr.c.Selection();this.$.content.selection.forEach(function(asyncEvent){if(!asyncEvent.associatedEvents)
2015-06-14 13:52:57 -06:00
return;asyncEvent.associatedEvents.forEach(function(event){selection.push(event);});});if(selection.length)
2015-06-18 08:27:29 -06:00
return selection;return undefined;}});'use strict';Polymer('tr-ui-a-single-cpu-slice-sub-view',{created:function(){this.currentSelection_=undefined;},get selection(){return this.currentSelection_;},set selection(selection){if(selection.length!==1)
2015-06-14 13:52:57 -06:00
throw new Error('Only supports single slices');if(!(selection[0]instanceof tr.model.CpuSlice))
throw new Error('Only supports thread time slices');this.currentSelection_=selection;var cpuSlice=selection[0];var thread=cpuSlice.threadThatWasRunning;var shadowRoot=this.shadowRoot;if(thread){shadowRoot.querySelector('#process-name').textContent=thread.parent.userFriendlyName;shadowRoot.querySelector('#thread-name').textContent=thread.userFriendlyName;}else{shadowRoot.querySelector('#process-name').parentElement.style.display='none';shadowRoot.querySelector('#thread-name').textContent=cpuSlice.title;}
2015-06-18 08:27:29 -06:00
shadowRoot.querySelector('#start').textContent=tr.b.units.tsString(cpuSlice.start);shadowRoot.querySelector('#duration').textContent=tr.b.units.tsString(cpuSlice.duration);var runningThreadEl=shadowRoot.querySelector('#running-thread');var timeSlice=cpuSlice.getAssociatedTimeslice();if(!timeSlice){runningThreadEl.parentElement.style.display='none';}else{var threadLink=document.createElement('tr-ui-a-analysis-link');threadLink.selection=new tr.c.Selection(timeSlice);threadLink.textContent='Click to select';runningThreadEl.parentElement.style.display='';runningThreadEl.textContent='';runningThreadEl.appendChild(threadLink);}
shadowRoot.querySelector('#args').object=cpuSlice.args;}});'use strict';Polymer('tr-ui-a-multi-cpu-slice-sub-view',{ready:function(){this.$.content.eventsHaveSubRows=false;},get selection(){return this.$.content.selection;},set selection(selection){this.$.content.setSelectionWithoutErrorChecks(selection);}});'use strict';Polymer('tr-ui-a-single-thread-time-slice-sub-view',{created:function(){this.currentSelection_=undefined;},get selection(){return this.currentSelection_;},set selection(selection){if(selection.length!==1)
2015-06-14 13:52:57 -06:00
throw new Error('Only supports single slices');if(!(selection[0]instanceof tr.model.ThreadTimeSlice))
2015-06-18 08:27:29 -06:00
throw new Error('Only supports thread time slices');this.currentSelection_=selection;var timeSlice=selection[0];var thread=timeSlice.thread;var shadowRoot=this.shadowRoot;shadowRoot.querySelector('#state').textContent=timeSlice.title;var stateColor=tr.ui.b.getColorPalette()[timeSlice.colorId];shadowRoot.querySelector('#state').style.backgroundColor=stateColor;shadowRoot.querySelector('#process-name').textContent=thread.parent.userFriendlyName;shadowRoot.querySelector('#thread-name').textContent=thread.userFriendlyName;shadowRoot.querySelector('#start').textContent=tr.b.units.tsString(timeSlice.start);shadowRoot.querySelector('#duration').textContent=tr.b.units.tsString(timeSlice.duration);var onCpuEl=shadowRoot.querySelector('#on-cpu');onCpuEl.textContent='';var runningInsteadEl=shadowRoot.querySelector('#running-instead');if(timeSlice.cpuOnWhichThreadWasRunning){runningInsteadEl.parentElement.removeChild(runningInsteadEl);var cpuLink=document.createElement('tr-ui-a-analysis-link');cpuLink.selection=new tr.c.Selection(timeSlice.getAssociatedCpuSlice());cpuLink.textContent=timeSlice.cpuOnWhichThreadWasRunning.userFriendlyName;onCpuEl.appendChild(cpuLink);}else{onCpuEl.parentElement.removeChild(onCpuEl);var cpuSliceThatTookCpu=timeSlice.getCpuSliceThatTookCpu();if(cpuSliceThatTookCpu){var cpuLink=document.createElement('tr-ui-a-analysis-link');cpuLink.selection=new tr.c.Selection(cpuSliceThatTookCpu);if(cpuSliceThatTookCpu.thread)
2015-06-14 13:52:57 -06:00
cpuLink.textContent=cpuSliceThatTookCpu.thread.userFriendlyName;else
cpuLink.textContent=cpuSliceThatTookCpu.title;runningInsteadEl.appendChild(cpuLink);}else{runningInsteadEl.parentElement.removeChild(runningInsteadEl);}}
2015-06-18 08:27:29 -06:00
var argsEl=shadowRoot.querySelector('#args');if(tr.b.dictionaryKeys(timeSlice.args).length>0){var argsView=document.createElement('tr-ui-a-generic-object-view');argsView.object=timeSlice.args;argsEl.parentElement.style.display='';argsEl.textContent='';argsEl.appendChild(argsView);}else{argsEl.parentElement.style.display='none';}}});'use strict';Polymer('tr-ui-a-multi-thread-time-slice-sub-view',{ready:function(){this.$.content.eventsHaveSubRows=false;},get selection(){return this.$.content.selection;},set selection(selection){this.$.content.setSelectionWithoutErrorChecks(selection);}});'use strict';Polymer('tr-ui-a-single-instant-event-sub-view',{created:function(){this.currentSelection_=undefined;},set selection(selection){this.$.content.textContent='';var realView=document.createElement('tr-ui-a-single-event-sub-view');realView.setSelectionWithoutErrorChecks(selection);this.$.content.appendChild(realView);this.currentSelection_=selection;},get selection(){return this.currentSelection_;}});'use strict';Polymer('tr-ui-a-multi-instant-event-sub-view',{created:function(){this.currentSelection_=undefined;},set selection(selection){this.$.content.textContent='';var realView=document.createElement('tr-ui-a-multi-event-sub-view');realView.eventsHaveDuration=false;realView.eventsHaveSubRows=false;this.$.content.appendChild(realView);realView.setSelectionWithoutErrorChecks(selection);this.currentSelection_=selection;},get selection(){return this.currentSelection_;}});'use strict';tr.exportTo('tr.ui.analysis',function(){var AnalysisResults=tr.ui.b.define('div');AnalysisResults.prototype={__proto__:HTMLDivElement.prototype,decorate:function(){this.className='analysis-results';},get requiresTallView(){return true;},clear:function(){this.textContent='';},createSelectionChangingLink:function(text,selectionGenerator,opt_tooltip){var el=this.ownerDocument.createElement('tr-ui-a-analysis-link');function wrap(){return selectionGenerator();}
2015-06-14 13:52:57 -06:00
wrap.userFriendlyName=text;el.selection=wrap;if(opt_tooltip)
el.title=opt_tooltip;return el;},appendElement_:function(parent,tagName,opt_text){var n=parent.ownerDocument.createElement(tagName);parent.appendChild(n);if(opt_text!=undefined)
n.textContent=opt_text;return n;},appendText_:function(parent,text){var textElement=parent.ownerDocument.createTextNode(text);parent.appendChild(textNode);return textNode;},appendTableCell_:function(table,row,cellnum,text,opt_warning){var td=this.appendElement_(row,'td',text);td.className=table.className+'-col-'+cellnum;if(opt_warning){var span=document.createElement('span');span.textContent=' '+String.fromCharCode(9888);span.title=opt_warning;td.appendChild(span);}
return td;},appendTableCell:function(table,row,text){return this.appendTableCell_(table,row,row.children.length,text);},appendTableCellWithTooltip_:function(table,row,cellnum,text,tooltip){if(tooltip){var td=this.appendElement_(row,'td');td.className=table.className+'-col-'+cellnum;var span=this.appendElement_(td,'span',text);span.className='tooltip';span.title=tooltip;return td;}else{return this.appendTableCell_(table,row,cellnum,text);}},appendHeader:function(label){var header=this.appendElement_(this,'span',label);header.className='analysis-header';return header;},appendInfo:function(label,value){var div=this.appendElement_(this,'div');div.label=this.appendElement_(div,'b',label);div.value=this.appendElement_(div,'span',value);return div;},appendTable:function(className,numColumns){var table=this.appendElement_(this,'table');table.className=className+' analysis-table';table.numColumns=numColumns;return table;},appendHeadRow:function(table){if(table.headerRow)
throw new Error('Only one header row allowed.');if(table.tbody||table.tfoot)
throw new Error('Cannot add a header row after data rows have been added.');table.headerRow=this.appendElement_(this.appendElement_(table,'thead'),'tr');table.headerRow.className='analysis-table-header';return table.headerRow;},appendBodyRow:function(table){if(table.tfoot)
throw new Error('Cannot add a tbody row after footer rows have been added.');if(!table.tbody)
table.tbody=this.appendElement_(table,'tbody');var row=this.appendElement_(table.tbody,'tr');if(table.headerRow)
row.className='analysis-table-row';else
row.className='analysis-table-row-inverted';return row;},appendFootRow:function(table){if(!table.tfoot){table.tfoot=this.appendElement_(table,'tfoot');table.tfoot.rowsClassName=((table.headerRow?1:0)+
(table.tbody?table.tbody.rows.length:0))%2?'analysis-table-row':'analysis-table-row-inverted';}
var row=this.appendElement_(table.tfoot,'tr');row.className=table.tfoot.rowsClassName;return row;},appendSpacingRow:function(table,opt_inFoot){if(table.tfoot||opt_inFoot)
var row=this.appendFootRow(table);else
var row=this.appendBodyRow(table);for(var i=0;i< table.numColumns ; i + + )
this.appendTableCell_(table,row,i,' ');},appendInfoRow:function(table,label,opt_value,opt_inFoot){if(table.tfoot||opt_inFoot)
var row=this.appendFootRow(table);else
2015-06-18 08:27:29 -06:00
var row=this.appendBodyRow(table);this.appendTableCell_(table,row,0,label);if(opt_value!==undefined){var objectView=document.createElement('tr-ui-a-generic-object-view');objectView.object=opt_value;objectView.classList.add('analysis-table-col-1');objectView.style.display='table-cell';row.appendChild(objectView);}else{this.appendTableCell_(table,row,1,'');}
2015-06-14 13:52:57 -06:00
for(var i=2;i< table.numColumns ; i + + )
this.appendTableCell_(table,row,i,'');},appendInfoRowTime:function(table,label,time,opt_inFoot,opt_warning){if(table.tfoot||opt_inFoot)
var row=this.appendFootRow(table);else
var row=this.appendBodyRow(table);this.appendTableCell_(table,row,0,label);this.appendTableCell_(table,row,1,tr.b.units.tsString(time),opt_warning);},appendDetailsRow:function(table,start,duration,selfTime,args,opt_selectionGenerator,opt_cpuDuration,opt_inFoot){if(opt_inFoot){var row=this.appendFootRow(table);this.appendTableCell(table,row,'Totals');}
else{var row=this.appendBodyRow(table);if(opt_selectionGenerator){var labelEl=this.appendTableCell(table,row,tr.b.units.tsString(start));labelEl.textContent='';labelEl.appendChild(this.createSelectionChangingLink(tr.b.units.tsString(start),opt_selectionGenerator,''));}else{this.appendTableCell(table,row,tr.b.units.tsString(start));}}
if(duration!==null)
this.appendTableCell(table,row,tr.b.units.tsString(duration));if(opt_cpuDuration)
this.appendTableCell(table,row,opt_cpuDuration!=''?tr.b.units.tsString(opt_cpuDuration):'');if(selfTime!==null)
this.appendTableCell(table,row,tr.b.units.tsString(selfTime));var argsCell=this.appendTableCell(table,row,'');var n=0;for(var argName in args){n+=1;}
2015-06-18 08:27:29 -06:00
if(n>0){for(var argName in args){var argVal=args[argName];var objectView=document.createElement('tr-ui-a-generic-object-view');objectView.object=argVal;var argsRow=this.appendElement_(this.appendElement_(argsCell,'table'),'tr');this.appendElement_(argsRow,'td',argName+':');this.appendElement_(argsRow,'td').appendChild(objectView);}}},appendDataRow:function(table,label,opt_duration,opt_cpuDuration,opt_selfTime,opt_cpuSelfTime,opt_occurrences,opt_percentage,opt_statistics,opt_selectionGenerator,opt_inFoot){var tooltip=undefined;if(opt_statistics){var stddevRounded=Math.round(opt_statistics.avg_stddev*1000)/1000;tooltip='Min Duration:\u0009'+
2015-06-14 13:52:57 -06:00
tr.b.units.tsString(opt_statistics.min)+' \u000DMax Duration:\u0009'+
tr.b.units.tsString(opt_statistics.max)+' \u000DAvg Duration:\u0009'+
tr.b.units.tsString(opt_statistics.avg)+' (\u03C3 = '+stddevRounded+')';if(opt_statistics.start){tooltip+='\u000DStart Time:\u0009'+
tr.b.units.tsString(opt_statistics.start);}
if(opt_statistics.end){tooltip+='\u000DEnd Time:\u0009'+
tr.b.units.tsString(opt_statistics.end);}
if(opt_statistics.frequency& & opt_statistics.frequency_stddev){var fR=Math.round(opt_statistics.frequency*1000)/1000;var fSR=Math.round(opt_statistics.frequency_stddev*1000)/1000;tooltip+='\u000DFrequency:\u0009'+
fR+' occurrences/s (\u03C3 = '+fSR+')';}}
if(table.tfoot||opt_inFoot)
var row=this.appendFootRow(table);else
var row=this.appendBodyRow(table);var cellNum=0;if(!opt_selectionGenerator){this.appendTableCellWithTooltip_(table,row,cellNum,label,tooltip);}else{var labelEl=this.appendTableCellWithTooltip_(table,row,cellNum,label,tooltip);if(labelEl){labelEl.textContent='';labelEl.appendChild(this.createSelectionChangingLink(label,opt_selectionGenerator,tooltip));}}
cellNum++;if(opt_duration!==null){if(opt_duration){if(opt_duration instanceof Array){this.appendTableCellWithTooltip_(table,row,cellNum,'['+opt_duration.join(', ')+']',tooltip);}else{this.appendTableCellWithTooltip_(table,row,cellNum,tr.b.units.tsString(opt_duration),tooltip);}}else{this.appendTableCell_(table,row,cellNum,'');}
cellNum++;}
if(opt_cpuDuration!==null){if(opt_cpuDuration!=''){this.appendTableCellWithTooltip_(table,row,cellNum,tr.b.units.tsString(opt_cpuDuration),tooltip);}else{this.appendTableCell_(table,row,cellNum,'');}
cellNum++;}
if(opt_selfTime!==null){if(opt_selfTime){this.appendTableCellWithTooltip_(table,row,cellNum,tr.b.units.tsString(opt_selfTime),tooltip);}else{this.appendTableCell_(table,row,cellNum,'');}
cellNum++;}
if(opt_cpuSelfTime!==null){if(opt_cpuSelfTime){this.appendTableCellWithTooltip_(table,row,cellNum,tr.b.units.tsString(opt_cpuSelfTime),tooltip);}else{this.appendTableCell_(table,row,cellNum,'');}
cellNum++;}
if(opt_percentage!==null){if(opt_percentage){this.appendTableCellWithTooltip_(table,row,cellNum,opt_percentage,tooltip);}else{this.appendTableCell_(table,row,cellNum,'');}
cellNum++;}
if(opt_occurrences){this.appendTableCellWithTooltip_(table,row,cellNum,String(opt_occurrences),tooltip);}else{this.appendTableCell_(table,row,cellNum,'');}
2015-06-18 08:27:29 -06:00
cellNum++;}};return{AnalysisResults:AnalysisResults};});'use strict';(function(){var CounterSample=tr.model.CounterSample;Polymer('tr-ui-a-counter-sample-sub-view',{created:function(){this.currentSelection_=undefined;},get selection(){return this.currentSelection_;},set selection(selection){var results=new tr.ui.analysis.AnalysisResults();this.appendChild(results);this.analyzeCounterSamples_(results,selection);},analyzeCounterSamples_:function(results,allSamples){var samplesByCounter={};for(var i=0;i< allSamples.length ; i + + ) { var ctr = allSamples[i].series.counter;if(!samplesByCounter[ctr.guid])
2015-06-14 13:52:57 -06:00
samplesByCounter[ctr.guid]=[];samplesByCounter[ctr.guid].push(allSamples[i]);}
for(var guid in samplesByCounter){var samples=samplesByCounter[guid];var ctr=samples[0].series.counter;var timestampGroups=CounterSample.groupByTimestamp(samples);if(timestampGroups.length==1)
this.analyzeSingleCounterTimestamp_(results,ctr,timestampGroups[0]);else
this.analyzeMultipleCounterTimestamps_(results,ctr,timestampGroups);}},analyzeSingleCounterTimestamp_:function(results,ctr,samplesWithSameTimestamp){results.appendHeader('Selected counter:');var table=results.appendTable('analysis-counter-table',2);results.appendInfoRow(table,'Title',ctr.name);results.appendInfoRowTime(table,'Timestamp',samplesWithSameTimestamp[0].timestamp);for(var i=0;i< samplesWithSameTimestamp.length ; i + + ) { var sample = samplesWithSameTimestamp[i];results.appendInfoRow(table,sample.series.name,sample.value);}},analyzeMultipleCounterTimestamps_:function(results,ctr,samplesByTimestamp){results.appendHeader('Counter ' + ctr . name ) ; var table = results.appendTable('analysis-counter-table',2);var sampleIndices = [];for(var i = 0;i<samplesByTimestamp.length;i++)
sampleIndices.push(samplesByTimestamp[i][0].getSampleIndex());var stats=ctr.getSampleStatistics(sampleIndices);for(var i=0;i< stats.length ; i + + ) { var samples = [];for(var k = 0;k<sampleIndices.length;++k)
2015-06-18 08:27:29 -06:00
samples.push(ctr.getSeries(i).getSample(sampleIndices[k]).value);results.appendDataRow(table,ctr.name+': series('+ctr.getSeries(i).name+')',samples,null,null,null,samples.length,null,stats[i]);}}});})();'use strict';Polymer('tr-ui-a-single-flow-event-sub-view',{getEventRows_:function(event){var rows=this.__proto__.__proto__.getEventRows_(event);rows.splice(0,0,{name:'ID',value:event.id});function createLinkTo(slice){var linkEl=document.createElement('tr-ui-a-analysis-link');linkEl.setSelectionAndContent(function(){return new tr.c.Selection(slice);});linkEl.textContent=slice.userFriendlyName;return linkEl;}
rows.push({name:'From',value:createLinkTo(event.startSlice)});rows.push({name:'To',value:createLinkTo(event.endSlice)});return rows;}});'use strict';Polymer('tr-ui-a-multi-flow-event-sub-view',{ready:function(){this.$.content.eventsHaveDuration=false;this.$.content.eventsHaveSubRows=false;},set selection(selection){this.$.content.selection=selection;},get selection(){return this.$.content.selection;}});'use strict';tr.exportTo('tr.ui.analysis',function(){var ObjectInstanceView=tr.ui.b.define('object-instance-view');ObjectInstanceView.prototype={__proto__:HTMLUnknownElement.prototype,decorate:function(){this.objectInstance_=undefined;},get requiresTallView(){return true;},set modelEvent(obj){this.objectInstance=obj;},get modelEvent(){return this.objectInstance;},get objectInstance(){return this.objectInstance_;},set objectInstance(i){this.objectInstance_=i;this.updateContents();},updateContents:function(){throw new Error('Not implemented');}};var options=new tr.b.ExtensionRegistryOptions(tr.b.TYPE_BASED_REGISTRY_MODE);options.mandatoryBaseClass=ObjectInstanceView;options.defaultMetadata={showInTrackView:true};tr.b.decorateExtensionRegistry(ObjectInstanceView,options);return{ObjectInstanceView:ObjectInstanceView};});'use strict';Polymer('tr-ui-a-single-object-instance-sub-view',{created:function(){this.currentSelection_=undefined;},get requiresTallView(){if(this.$.content.children.length===0)
2015-06-14 13:52:57 -06:00
return false;if(this.$.content.children[0]instanceof
2015-06-18 08:27:29 -06:00
tr.ui.analysis.ObjectInstanceView)
2015-06-14 13:52:57 -06:00
return this.$.content.children[0].requiresTallView;},get selection(){return this.currentSelection_;},set selection(selection){if(selection.length!==1)
throw new Error('Only supports single item selections');if(!(selection[0]instanceof tr.model.ObjectInstance))
2015-06-18 08:27:29 -06:00
throw new Error('Only supports object instances');this.$.content.textContent='';this.currentSelection_=selection;var instance=selection[0];var typeInfo=tr.ui.analysis.ObjectInstanceView.getTypeInfo(instance.category,instance.typeName);if(typeInfo){var customView=new typeInfo.constructor();this.$.content.appendChild(customView);customView.modelEvent=instance;}else{this.appendGenericAnalysis_(instance);}},appendGenericAnalysis_:function(instance){var html='';html+='< div class = "title" > '+
2015-06-14 13:52:57 -06:00
instance.typeName+' '+
instance.id+'< / div > \n';html+='< table > ';html+='< tr > ';html+='< tr > < td > creationTs:< / td > < td > '+
instance.creationTs+'< / td > < / tr > \n';if(instance.deletionTs!=Number.MAX_VALUE){html+='< tr > < td > deletionTs:< / td > < td > '+
instance.deletionTs+'< / td > < / tr > \n';}else{html+='< tr > < td > deletionTs:< / td > < td > not deleted< / td > < / tr > \n';}
2015-06-18 08:27:29 -06:00
html+='< tr > < td > snapshots:< / td > < td id = "snapshots" > < / td > < / tr > \n';html+='< / table > ';this.$.content.innerHTML=html;var snapshotsEl=this.$.content.querySelector('#snapshots');instance.snapshots.forEach(function(snapshot){var snapshotLink=document.createElement('tr-ui-a-analysis-link');snapshotLink.selection=new tr.c.Selection(snapshot);snapshotsEl.appendChild(snapshotLink);});}});'use strict';tr.exportTo('tr.ui.analysis',function(){var ObjectSnapshotView=tr.ui.b.define('object-snapshot-view');ObjectSnapshotView.prototype={__proto__:HTMLUnknownElement.prototype,decorate:function(){this.objectSnapshot_=undefined;},get requiresTallView(){return true;},set modelEvent(obj){this.objectSnapshot=obj;},get modelEvent(){return this.objectSnapshot;},get objectSnapshot(){return this.objectSnapshot_;},set objectSnapshot(i){this.objectSnapshot_=i;this.updateContents();},updateContents:function(){throw new Error('Not implemented');}};var options=new tr.b.ExtensionRegistryOptions(tr.b.TYPE_BASED_REGISTRY_MODE);options.mandatoryBaseClass=ObjectSnapshotView;options.defaultMetadata={showInstances:true,showInTrackView:true};tr.b.decorateExtensionRegistry(ObjectSnapshotView,options);return{ObjectSnapshotView:ObjectSnapshotView};});'use strict';Polymer('tr-ui-a-single-object-snapshot-sub-view',{created:function(){this.currentSelection_=undefined;},get requiresTallView(){if(this.children.length===0)
return false;if(this.children[0]instanceof tr.ui.analysis.ObjectSnapshotView)
2015-06-14 13:52:57 -06:00
return this.children[0].requiresTallView;},get selection(){return this.currentSelection_;},set selection(selection){if(selection.length!==1)
throw new Error('Only supports single item selections');if(!(selection[0]instanceof tr.model.ObjectSnapshot))
2015-06-18 08:27:29 -06:00
throw new Error('Only supports object instances');this.textContent='';this.currentSelection_=selection;var snapshot=selection[0];var typeInfo=tr.ui.analysis.ObjectSnapshotView.getTypeInfo(snapshot.objectInstance.category,snapshot.objectInstance.typeName);if(typeInfo){var customView=new typeInfo.constructor();this.appendChild(customView);customView.modelEvent=snapshot;}else{this.appendGenericAnalysis_(snapshot);}},appendGenericAnalysis_:function(snapshot){var instance=snapshot.objectInstance;var html='';html+='< div class = "title" > Snapshot of < a id = "instance-link" > < / a > @ '+
tr.b.units.tsString(snapshot.ts)+'< / div > \n';html+='< table > ';html+='< tr > ';html+='< tr > < td > args:< / td > < td id = "args" > < / td > < / tr > \n';html+='< / table > ';this.innerHTML=html;var instanceLinkEl=document.createElement('tr-ui-a-analysis-link');instanceLinkEl.selection=new tr.c.Selection(instance);var tmp=this.querySelector('#instance-link');tmp.parentElement.replaceChild(instanceLinkEl,tmp);var argsEl=this.querySelector('#args');argsEl.textContent='';var objectView=document.createElement('tr-ui-a-generic-object-view');objectView.object=snapshot.args;argsEl.appendChild(objectView);}});'use strict';Polymer('tr-ui-a-multi-object-sub-view',{created:function(){this.currentSelection_=undefined;},ready:function(){this.$.content.showHeader=false;},get selection(){return this.currentSelection_;},set selection(selection){this.currentSelection_=selection;var objectEvents=tr.b.asArray(selection).sort(tr.b.Range.compareByMinTimes);var table=this.$.content;table.tableColumns=[{title:'First',value:function(event){if(event instanceof tr.model.ObjectSnapshot)
2015-06-14 13:52:57 -06:00
return tr.ui.units.createTimeStampSpan(event.ts);var spanEl=document.createElement('span');spanEl.appendChild(tr.ui.units.createTimeStampSpan(event.creationTs));spanEl.appendChild(tr.ui.b.createSpan({textContent:'-',marginLeft:'4px',marginRight:'4px'}));if(event.deletionTs!=Number.MAX_VALUE){spanEl.appendChild(tr.ui.units.createTimeStampSpan(event.deletionTs));}
2015-06-18 08:27:29 -06:00
return spanEl;},width:'200px'},{title:'Second',value:function(event){var linkEl=document.createElement('tr-ui-a-analysis-link');linkEl.setSelectionAndContent(function(){return new tr.c.Selection(event);},event.userFriendlyName);return linkEl;},width:'100%'}];table.tableRows=objectEvents;table.rebuild();}});'use strict';Polymer('tr-ui-a-single-sample-sub-view',{created:function(){this.currentSelection_=undefined;},ready:function(){this.$.content.tableColumns=[{title:'FirstColumn',value:function(row){return row.title;},width:'250px'},{title:'SecondColumn',value:function(row){return row.value;},width:'100%'}];this.$.content.showHeader=false;},get selection(){return this.currentSelection_;},set selection(selection){this.currentSelection_=selection;if(this.currentSelection_===undefined){this.$.content.tableRows=[];return;}
var sample=this.currentSelection_[0];var table=this.$.content;var rows=[];rows.push({title:'Title',value:sample.title});rows.push({title:'Sample time',value:tr.ui.units.createTimeStampSpan(sample.start)});var sfEl=document.createElement('tr-ui-a-stack-frame');sfEl.stackFrame=sample.leafStackFrame;rows.push({title:'Stack trace',value:sfEl});table.tableRows=rows;table.rebuild();}});'use strict';Polymer('tr-ui-a-multi-sample-sub-view',{created:function(){this.currentSelection_=undefined;},get requiresTallView(){return true;},set selection(selection){this.$.content.textContent='';this.currentSelection_=selection;if(tr.isDefined('tr.ui.e.analysis.SamplingSummaryPanel')){var panel=new tr.ui.e.analysis.SamplingSummaryPanel();this.$.content.appendChild(panel);panel.selection=selection;}else{this.$.content.textContent='SamplingSummaryPanel not installed. :(';}},get selection(){return this.currentSelection_;}});'use strict';Polymer('tr-ui-a-single-interaction-record-sub-view',{created:function(){this.currentSelection_=undefined;},set selection(selection){this.textContent='';var realView=document.createElement('tr-ui-a-single-event-sub-view');this.appendChild(realView);realView.setSelectionWithoutErrorChecks(selection);this.currentSelection_=selection;},get relatedEventsToHighlight(){if(!this.currentSelection_)
return undefined;return this.currentSelection_[0].associatedEvents;}});'use strict';Polymer('tr-ui-a-multi-interaction-record-sub-view',{created:function(){this.currentSelection_=undefined;},set selection(selection){this.currentSelection_=selection;this.textContent='';var realView=document.createElement('tr-ui-a-multi-event-sub-view');this.appendChild(realView);realView.setSelectionWithoutErrorChecks(selection);this.currentSelection_=selection;},get selection(){return this.currentSelection_;},get relatedEventsToHighlight(){if(!this.currentSelection_)
return undefined;var selection=new tr.c.Selection();this.currentSelection_.forEach(function(ir){ir.associatedEvents.forEach(function(event){selection.push(event);});});return selection;}});'use strict';Polymer('tr-ui-a-alert-sub-view',{ready:function(){this.currentSelection_=undefined;this.$.table.tableColumns=[{title:'Label',value:function(row){return row.name;},width:'150px'},{title:'Value',width:'100%',value:function(row){return row.value;}}];this.$.table.showHeader=false;},get selection(){return this.currentSelection_;},set selection(selection){this.currentSelection_=selection;this.updateContents_();},getRowsForSingleAlert_:function(alert){var rows=[];for(var argName in alert.args){var argView=document.createElement('tr-ui-a-generic-object-view');argView.object=alert.args[argName];rows.push({name:argName,value:argView});}
if(alert.associatedEvents.length){alert.associatedEvents.forEach(function(event,i){var linkEl=document.createElement('tr-ui-a-analysis-link');linkEl.setSelectionAndContent(function(){return event;},event.title);var valueString='';if(event instanceof tr.model.TimedEvent)
2015-06-14 13:52:57 -06:00
valueString='took '+event.duration.toFixed(2)+'ms';rows.push({name:linkEl,value:valueString});});}
var descriptionEl=tr.ui.b.createDiv({textContent:alert.info.description,maxWidth:'300px'});rows.push({name:'Description',value:descriptionEl});if(alert.info.docLinks){alert.info.docLinks.forEach(function(linkObject){var linkEl=document.createElement('a');linkEl.target='_blank';linkEl.href=linkObject.href;linkEl.textContent=linkObject.textContent;rows.push({name:linkObject.label,value:linkEl});});}
return rows;},getRowsForAlerts_:function(alerts){if(alerts.length==1){var rows=[{name:'Alert',value:alerts[0].title}];var detailRows=this.getRowsForSingleAlert_(alerts[0]);rows.push.apply(rows,detailRows);return rows;}else{return alerts.map(function(alert){return{name:'Alert',value:alert.title,isExpanded:alerts.size< 10 , subRows:this . getRowsForSingleAlert_ ( alert ) } ; } , this ) ; } } , updateContents_:function ( ) { if ( this . currentSelection_ = ==undefined){this.$.table.rows=[];this.$.table.rebuild();return;}
2015-06-18 08:27:29 -06:00
var alerts=this.currentSelection_;this.$.table.tableRows=this.getRowsForAlerts_(alerts);this.$.table.rebuild();}});'use strict';Polymer('tr-ui-a-single-frame-sub-view',{ready:function(){this.currentSelection_=undefined;},get selection(){return this.currentSelection_;},set selection(selection){if(selection.length!=1)
throw new Error('Only supports single frame!');this.currentSelection_=selection;this.$.asv.selection=selection[0].associatedAlerts;},get relatedEventsToHighlight(){if(!this.currentSelection_)
return undefined;return this.currentSelection_[0].associatedEvents;}});'use strict';Polymer('tr-ui-a-multi-frame-sub-view',{created:function(){this.currentSelection_=undefined;},set selection(selection){this.textContent='';var realView=document.createElement('tr-ui-a-multi-event-sub-view');realView.eventsHaveDuration=false;realView.eventsHaveSubRows=false;this.appendChild(realView);realView.setSelectionWithoutErrorChecks(selection);this.currentSelection_=selection;},get selection(){return this.currentSelection_;},get relatedEventsToHighlight(){if(!this.currentSelection_)
2015-06-14 13:52:57 -06:00
return undefined;var selection=new tr.c.Selection();this.currentSelection_.forEach(function(frameEvent){frameEvent.associatedEvents.forEach(function(event){selection.push(event);});});return selection;}});'use strict';Polymer('tr-ui-b-color-legend',{ready:function(){var blackSquareCharCode=9632;this.$.square.innerText=String.fromCharCode(blackSquareCharCode);this.label_=undefined;},get label(){return this.label_;},set label(label){this.label_=label;if(this.label_===undefined){this.$.square.style.color='initial';this.$.label.innerText='';return;}
2015-06-18 08:27:29 -06:00
var paletteRaw=tr.ui.b.getRawColorPalette();var colorId=tr.ui.b.getColorIdForGeneralPurposeString(this.label_);var color=tr.ui.b.colorToRGBString(paletteRaw[colorId]);this.$.square.style.color=color;this.$.label.innerText=this.label_;}});'use strict';tr.exportTo('tr.ui.analysis',function(){function MemoryColumn(name,title,units,cellGetter){this.name=name;this.title=title;this.units=units;this.cell=cellGetter;this.color=undefined;}
2015-06-14 13:52:57 -06:00
MemoryColumn.fromRows=function(rows,cellKey,opt_titleBuilder){var columnTraits={};function gatherTraits(row){if(row===undefined)
return;var attrCells=row[cellKey];tr.b.iterItems(attrCells,function(attrName,attrCell){if(attrCell===undefined)
return;var attrValue=attrCell.attr;if(attrValue===undefined)
return;var existingTraits=columnTraits[attrName];if(existingTraits===undefined){columnTraits[attrName]={constructor:attrValue.constructor,units:attrValue.units};return;}
if(existingTraits.constructor!==attrValue.constructor||existingTraits.units!==attrValue.units){existingTraits.constructor=tr.model.UnknownAttribute;existingTraits.units=undefined;}});if(row.subRows!==undefined)
row.subRows.forEach(gatherTraits);};rows.forEach(gatherTraits);var titleBuilder=opt_titleBuilder||tr.b.identity;var columns=[];tr.b.iterItems(columnTraits,function(columnName,columnTraits){var cellGetter=fieldGetter(cellKey,columnName);var title=titleBuilder(columnName);columns.push(MemoryColumn.fromAttributeTraits(columnName,title,columnTraits,cellGetter));});return columns;};MemoryColumn.fromAttributeTraits=function(name,title,traits,cellGetter){var constructor;if(traits.constructor===tr.model.ScalarAttribute)
constructor=ScalarMemoryColumn;else
constructor=MemoryColumn;return new constructor(name,title,traits.units,cellGetter);};MemoryColumn.spaceEqually=function(columns){var columnWidth=(100/columns.length).toFixed(3)+'%';columns.forEach(function(column){column.width=columnWidth;});};MemoryColumn.sortByImportance=function(columns,importanceRules){var positions=columns.map(function(column,srcIndex){return{importance:column.getImportance(importanceRules),srcIndex:srcIndex,column:column};});positions.sort(function(a,b){if(a.importance===b.importance)
2015-06-18 08:27:29 -06:00
return a.srcIndex-b.srcIndex;return b.importance-a.importance;});positions.forEach(function(position,dstIndex){columns[dstIndex]=position.column;});};MemoryColumn.iconFromAttributeInfoType=function(type){switch(type){case tr.model.AttributeInfoType.WARNING:return{symbol:String.fromCharCode(9888),color:'red'};case tr.model.AttributeInfoType.LINK:return{symbol:String.fromCharCode(9903)};default:return{symbol:String.fromCharCode(9432),color:'blue'};}
throw new Error('Unreachable');};MemoryColumn.prototype={attr:function(row){var cell=this.cell(row);if(cell===undefined)
2015-06-14 13:52:57 -06:00
return undefined;return cell.attr;},value:function(row){var attr=this.attr(row);if(attr===undefined)
2015-06-18 08:27:29 -06:00
return'';return this.formatDefinedAttribute(attr);},formatDefinedAttribute:function(attr){var formattedValue=this.formatDefinedAttributeValue(attr);var color;if(typeof this.color==='function')
color=this.color(attr);else
color=this.color;if(color===undefined& & attr.infos.length===0)
return formattedValue;var attrEl=document.createElement('span');attrEl.style.display='flex';attrEl.style.alignItems='center';attrEl.appendChild(tr.ui.b.asHTMLOrTextNode(formattedValue));attr.infos.forEach(function(info){var infoEl=document.createElement('span');infoEl.style.paddingLeft='4px';infoEl.style.cursor='help';infoEl.style.fontWeight='bold';var icon=MemoryColumn.iconFromAttributeInfoType(info.type);infoEl.textContent=icon.symbol;if(icon.color!==undefined)
infoEl.style.color=icon.color;infoEl.title=info.message;attrEl.appendChild(infoEl);},this);if(color!==undefined)
attrEl.style.color=color;return attrEl;},formatDefinedAttributeValue:function(attr){return String(attr.value);},cmp:function(rowA,rowB){var attrA=this.attr(rowA);var attrB=this.attr(rowB);if(attrA===undefined& & attrB===undefined)
2015-06-14 13:52:57 -06:00
return 0;if(attrA===undefined)
return-1;if(attrB===undefined)
return 1;return this.compareDefinedAttributes(attrA,attrB);},compareDefinedAttributes:function(attrA,attrB){var strA=String(attrA.value);var strB=String(attrB.value);return strA.localeCompare(strB);},getImportance:function(importanceRules){if(importanceRules.length===0)
return 0;for(var i=0;i< importanceRules.length ; i + + ) { var importanceRule = importanceRules[i];if(this.matchesNameCondition(importanceRule.condition))
return importanceRule.importance;}
var minImportance=importanceRules[0].importance;for(var i=1;i< importanceRules.length ; i + + ) { minImportance = Math.min(minImportance,importanceRules[i].importance);}
return minImportance-1;},matchesNameCondition:function(condition){if(condition===undefined)
return true;if(typeof(condition)==='string')
return this.name===condition;return condition.test(this.name);}};function ScalarMemoryColumn(name,title,units,cellGetter){MemoryColumn.call(this,name,title,units,cellGetter);}
2015-06-18 08:27:29 -06:00
ScalarMemoryColumn.prototype={__proto__:MemoryColumn.prototype,formatDefinedAttributeValue:function(attr){if(this.units==='bytes'){var sizeEl=document.createElement('tr-ui-u-size-in-bytes-span');sizeEl.numBytes=attr.value;return sizeEl;}
return MemoryColumn.prototype.formatDefinedAttributeValue.call(this,attr);},compareDefinedAttributes:function(attrA,attrB){return attrA.value-attrB.value;}};function MemoryCell(attr){this.attr=attr;}
2015-06-14 13:52:57 -06:00
MemoryCell.extractAttribute=function(cell){if(cell===undefined)
return undefined;return cell.attr;};function fieldGetter(){var fields=tr.b.asArray(arguments);return function(row){var value=row;for(var i=0;i< fields.length ; i + + )
value=value[fields[i]];return value;};}
var RECURSIVE_EXPANSION_MAX_SUB_ROW_COUNT=10;function expandTableRowsRecursively(table){function expandRowRecursively(row){if(row.subRows===undefined||row.subRows.length===0)
return;if(row.subRows.length>RECURSIVE_EXPANSION_MAX_SUB_ROW_COUNT)
return;table.setExpandedForTableRow(row,true);row.subRows.forEach(expandRowRecursively);}
table.tableRows.forEach(expandRowRecursively);}
function aggregateTableRowCellsRecursively(row,cellKey){var subRows=row.subRows;if(subRows===undefined)
return;subRows.forEach(function(subRow){aggregateTableRowCellsRecursively(subRow,cellKey);});aggregateTableRowCells(row,subRows,cellKey);}
function aggregateTableRowCells(row,subRows,cellKey){var rowCells=row[cellKey];if(rowCells===undefined)
row[cellKey]=rowCells={};var subRowCellNames={};subRows.forEach(function(subRow){var subRowCells=subRow[cellKey];if(subRowCells===undefined)
return;tr.b.iterItems(subRowCells,function(columnName){subRowCellNames[columnName]=true;});});tr.b.iterItems(subRowCellNames,function(cellName){var subRowAttributes=subRows.map(function(subRow){var subRowCells=subRow[cellKey];if(subRowCells===undefined)
return undefined;return MemoryCell.extractAttribute(subRowCells[cellName]);},this);var existingRowCell=rowCells[cellName];var existingRowAttribute=MemoryCell.extractAttribute(existingRowCell);var aggregatedAttribute=tr.model.Attribute.aggregate(subRowAttributes,existingRowAttribute);if(existingRowCell!==undefined){existingRowCell.attr=aggregatedAttribute;}else{rowCells[cellName]=new MemoryCell(aggregatedAttribute);}});}
2015-06-18 08:27:29 -06:00
return{MemoryColumn:MemoryColumn,ScalarMemoryColumn:ScalarMemoryColumn,MemoryCell:MemoryCell,fieldGetter:fieldGetter,expandTableRowsRecursively:expandTableRowsRecursively,aggregateTableRowCellsRecursively:aggregateTableRowCellsRecursively,aggregateTableRowCells:aggregateTableRowCells};});'use strict';(function(){var IMPORTANCE_RULES=[{condition:'size',importance:10},{condition:'page_size',importance:0},{condition:/size/,importance:5},{importance:0}];Polymer('tr-ui-a-memory-dump-allocator-details-pane',{created:function(){this.memoryAllocatorDump_=undefined;},ready:function(){this.updateContents_();},set memoryAllocatorDump(memoryAllocatorDump){this.memoryAllocatorDump_=memoryAllocatorDump;this.updateContents_();},get memoryAllocatorDump(){return this.memoryAllocatorDump_;},updateContents_:function(){this.$.contents.textContent='';if(this.memoryAllocatorDump_===undefined){var infoText=this.ownerDocument.createElement('div');this.$.contents.appendChild(infoText);infoText.classList.add('info-text');infoText.innerText='No memory allocator dump selected';return;}
var rows=this.createRows_();var columns=this.createColumns_(rows);var table=this.ownerDocument.createElement('tr-ui-b-table');this.$.contents.appendChild(table);table.supportsSelection=true;table.tableRows=rows;table.tableColumns=columns;table.rebuild();tr.ui.analysis.expandTableRowsRecursively(table);},createRows_:function(){var createAllocatorRow=function(allocatorDump){var cells=tr.b.mapItems(allocatorDump.attributes,function(attrName,attrValue){return new tr.ui.analysis.MemoryCell(attrValue);});var row={title:allocatorDump.name,cells:cells};if(allocatorDump.children.length>0)
row.subRows=allocatorDump.children.map(createAllocatorRow);return row;};var rows=[createAllocatorRow(this.memoryAllocatorDump_)];return rows;},createColumns_:function(rows){var titleColumn={title:'Allocator',value:function(row){return row.title;},width:'200px',cmp:function(rowA,rowB){return rowA.title.localeCompare(rowB.title);}};var attributeColumns=tr.ui.analysis.MemoryColumn.fromRows(rows,'cells');tr.ui.analysis.MemoryColumn.spaceEqually(attributeColumns);tr.ui.analysis.MemoryColumn.sortByImportance(attributeColumns,IMPORTANCE_RULES);var columns=[titleColumn].concat(attributeColumns);return columns;}});})();'use strict';(function(){var CLASSIFICATION_RULES={name:'Total',children:[{name:'Android',file:/^\/dev\/ashmem(?!\/libc malloc)/,children:[{name:'Java runtime',file:/^\/dev\/ashmem\/dalvik-/,children:[{name:'Spaces',file:/\/dalvik-(alloc|main|large object|non moving|zygote) space/,children:[{name:'Normal',file:/\/dalvik-(alloc|main)/},{name:'Large',file:/\/dalvik-large object/},{name:'Zygote',file:/\/dalvik-zygote/},{name:'Non-moving',file:/\/dalvik-non moving/}]},{name:'Linear Alloc',file:/\/dalvik-LinearAlloc/},{name:'Indirect Reference Table',file:/\/dalvik-indirect.ref/},{name:'Cache',file:/\/dalvik-jit-code-cache/},{name:'Accounting'}]},{name:'Cursor',file:/\/CursorWindow/},{name:'Ashmem'}]},{name:'Native heap',file:/^((\[heap\])|(\[anon:)|(\/dev\/ashmem\/libc malloc)|$)/},{name:'Stack',file:/^\[stack/},{name:'Files',file:/\.((((jar)|(apk)|(ttf)|(odex)|(oat)|(arg))$)|(dex)|(so))/,children:[{name:'so',file:/\.so/},{name:'jar',file:/\.jar$/},{name:'apk',file:/\.apk$/},{name:'ttf',file:/\.ttf$/},{name:'dex',file:/\.((dex)|(odex$))/},{name:'oat',file:/\.oat$/},{name:'art',file:/\.art$/}]},{name:'Devices',file:/(^\/dev\/)|(anon_inode:dmabuf)/,children:[{name:'GPU',file:/\/((nv)|(mali)|(kgsl))/},{name:'DMA',file:/anon_inode:dmabuf/}]},{name:'Discounted tracing overhead',file:/\[discounted tracing overhead\]/}]};function createEmptyRow(rule){var row={title:rule.name,rule:rule,cells:{},subRows:[]};if(rule.children!==undefined)
2015-06-14 13:52:57 -06:00
row.subRows=rule.children.map(createEmptyRow);return row;}
function hexString(address,is64BitAddress){var hexPadding=is64BitAddress?'0000000000000000':'00000000';if(address===undefined)
return undefined;return(hexPadding+address.toString(16)).substr(-hexPadding.length);}
function classifyVMRegion(row,vmRegion,is64BitAddress){var rule=row.rule;if(rule===undefined||rule.children===undefined||rule.children.length===0){var mappedFile=vmRegion.mappedFile||'';var cells={};function addCellIfValueDefined(columnName,attrClass,units,value){if(value===undefined)
2015-06-18 08:27:29 -06:00
return;var attr=new attrClass(units,value);var cell=new tr.ui.analysis.MemoryCell(attr);cells[columnName]=cell;}
2015-06-14 13:52:57 -06:00
function addBytesCellIfValueDefined(columnName,value){addCellIfValueDefined(columnName,tr.model.ScalarAttribute,'bytes',value);}
addCellIfValueDefined('Start address',tr.model.StringAttribute,'',hexString(vmRegion.startAddress,is64BitAddress));addBytesCellIfValueDefined('Virtual size',vmRegion.sizeInBytes);addCellIfValueDefined('Protection flags',tr.model.StringAttribute,'',vmRegion.protectionFlagsToString);addBytesCellIfValueDefined('PSS',vmRegion.byteStats.proportionalResident);addBytesCellIfValueDefined('Private dirty',vmRegion.byteStats.privateDirtyResident);addBytesCellIfValueDefined('Private clean',vmRegion.byteStats.privateCleanResident);addBytesCellIfValueDefined('Shared dirty',vmRegion.byteStats.sharedDirtyResident);addBytesCellIfValueDefined('Shared clean',vmRegion.byteStats.sharedCleanResident);addBytesCellIfValueDefined('Swapped',vmRegion.byteStats.swapped);row.subRows.push({title:mappedFile,cells:cells});return;}
function vmRegionMatchesChildRule(childRule){var fileRegExp=childRule.file;if(fileRegExp===undefined)
return true;return fileRegExp.test(vmRegion.mappedFile);}
var matchedChildRuleIndex=tr.b.findFirstIndexInArray(rule.children,vmRegionMatchesChildRule);if(matchedChildRuleIndex===-1){matchedChildRuleIndex=rule.children.length;if(matchedChildRuleIndex>=row.subRows.length){row.subRows.push({title:'Other',cells:{},subRows:[]});}}
classifyVMRegion(row.subRows[matchedChildRuleIndex],vmRegion,is64BitAddress);}
2015-06-18 08:27:29 -06:00
Polymer('tr-ui-a-memory-dump-vm-regions-details-pane',{created:function(){this.vmRegions_=undefined;},ready:function(){this.updateContents_();},set vmRegions(vmRegions){this.vmRegions_=vmRegions;this.updateContents_();},get vmRegions(){return this.vmRegions_;},updateContents_:function(){this.$.contents.textContent='';if(this.vmRegions_===undefined){var infoText=this.ownerDocument.createElement('div');this.$.contents.appendChild(infoText);infoText.classList.add('info-text');infoText.innerText='No memory maps selected';return;}
var rows=this.createRows_();var columns=this.createColumns_(rows);var table=this.ownerDocument.createElement('tr-ui-b-table');this.$.contents.appendChild(table);table.supportsSelection=true;table.tableRows=rows;table.tableColumns=columns;table.rebuild();tr.ui.analysis.expandTableRowsRecursively(table);},createRows_:function(){var is64BitAddress=this.vmRegions_.some(function(vmRegion){if(vmRegion.startAddress===undefined)
return;return vmRegion.startAddress>=4294967296;});var rootRow=createEmptyRow(CLASSIFICATION_RULES);this.vmRegions_.map(function(vmRegion){classifyVMRegion(rootRow,vmRegion,is64BitAddress);});tr.ui.analysis.aggregateTableRowCellsRecursively(rootRow,'cells');return[rootRow];},createColumns_:function(rows){var titleColumn={title:'Mapped file',value:function(row){return row.title;},width:'200px',cmp:function(rowA,rowB){return rowA.title.localeCompare(rowB.title);}};var attributeColumns=tr.ui.analysis.MemoryColumn.fromRows(rows,'cells');tr.ui.analysis.MemoryColumn.spaceEqually(attributeColumns);var columns=[titleColumn].concat(attributeColumns);return columns;}});})();'use strict';(function(){var IMPORTANCE_RULES=[{condition:'tracing',importance:0},{importance:1}];var SETTINGS_KEY='selected_cell';var SETTINGS_NAMESPACE='analysis.memory_dump_overview_pane';var LINK_SYMBOL=String.fromCharCode(9903);Polymer('tr-ui-a-memory-dump-overview-pane',{created:function(){this.processMemoryDumps_=undefined;},ready:function(){this.$.table.supportsSelection=true;this.$.table.cellSelectionMode=true;this.$.table.rowHighlightEnabled=true;this.$.table.addEventListener('selection-changed',function(tableEvent){tableEvent.stopPropagation();var paneEvent=new Event('selected-memory-cell-changed');this.dispatchEvent(paneEvent);this.storeSelection_();}.bind(this));},set processMemoryDumps(processMemoryDumps){this.processMemoryDumps_=processMemoryDumps;this.updateContents_();},get processMemoryDumps(){return this.processMemoryDumps_;},get selectedMemoryCell(){var selectedTableRow=this.$.table.selectedTableRow;if(!selectedTableRow)
2015-06-14 13:52:57 -06:00
return undefined;var selectedColumnIndex=this.$.table.selectedColumnIndex;if(selectedColumnIndex===undefined)
2015-06-18 08:27:29 -06:00
return undefined;var selectedColumn=this.$.table.tableColumns[selectedColumnIndex];var selectedMemoryCell=selectedColumn.cell(selectedTableRow);return selectedMemoryCell;},updateContents_:function(){var processMemoryDumps=this.processMemoryDumps_||[];var rows=processMemoryDumps.map(function(processMemoryDump){function buildVMRegionsPane(){var pane=document.createElement('tr-ui-a-memory-dump-vm-regions-details-pane');pane.vmRegions=processMemoryDump.mostRecentVmRegions;return pane;}
var usedMemorySizes={};var totalResident=processMemoryDump.totalResidentBytes;if(totalResident!==undefined){var cell=new tr.ui.analysis.MemoryCell(new tr.model.ScalarAttribute('bytes',totalResident));cell.buildDetailsPane=buildVMRegionsPane;usedMemorySizes['Total resident']=cell;}
function addByteStatCell(byteStatName,columnTitle){var byteStat=processMemoryDump.getMostRecentTotalVmRegionStat(byteStatName);if(byteStat!==undefined){var attr=new tr.model.ScalarAttribute('bytes',byteStat);if(!processMemoryDump.hasOwnVmRegions){attr.infos.push(new tr.model.AttributeInfo(tr.model.AttributeInfoType.LINK,'Older value (process did not dump memory maps).'));attr.isOlderValue=true;}
var cell=new tr.ui.analysis.MemoryCell(attr);cell.buildDetailsPane=buildVMRegionsPane;usedMemorySizes[columnTitle]=cell;}}
addByteStatCell('proportionalResident','PSS');addByteStatCell('privateDirtyResident','Private dirty');addByteStatCell('swapped','Swapped');var allocatorSizes={};if(processMemoryDump.memoryAllocatorDumps!==undefined){processMemoryDump.memoryAllocatorDumps.forEach(function(dump){var attr=dump.attributes['size'];var cell=new tr.ui.analysis.MemoryCell(attr);cell.buildDetailsPane=function(){var pane=document.createElement('tr-ui-a-memory-dump-allocator-details-pane');pane.memoryAllocatorDump=dump;return pane;};allocatorSizes[dump.fullName]=cell;},this);}
return{title:processMemoryDump.process.userFriendlyName,usedMemorySizes:usedMemorySizes,allocatorSizes:allocatorSizes};},this);this.$.table.tableRows=rows;if(rows.length>1){var totalRow={title:'Total',noLegend:true};tr.ui.analysis.aggregateTableRowCells(totalRow,rows,'usedMemorySizes');tr.ui.analysis.aggregateTableRowCells(totalRow,rows,'allocatorSizes');this.$.table.footerRows=[totalRow];}
2015-06-14 13:52:57 -06:00
this.updateColumns_(rows);this.$.table.rebuild();this.restoreSelection_();},updateColumns_:function(rows){var titleColumn={title:'Process',value:function(row){if(row.noLegend)
2015-06-18 08:27:29 -06:00
return row.title;var titleEl=document.createElement('tr-ui-b-color-legend');titleEl.label=row.title;return titleEl;},width:'200px',cmp:function(rowA,rowB){return rowA.title.localeCompare(rowB.title);},supportsCellSelection:false};var usedMemorySizeColumns=tr.ui.analysis.MemoryColumn.fromRows(rows,'usedMemorySizes');var allocatorSizeColumns=tr.ui.analysis.MemoryColumn.fromRows(rows,'allocatorSizes',function(allocatorName){var titleEl=document.createElement('tr-ui-b-color-legend');titleEl.label=allocatorName;return titleEl;});tr.ui.analysis.MemoryColumn.sortByImportance(allocatorSizeColumns,IMPORTANCE_RULES);var tracingColumn=tr.b.findFirstInArray(allocatorSizeColumns,function(column){return column.name==='tracing';});if(tracingColumn!==undefined){var tracingColumnColor=tr.ui.b.getColorPalette()[tr.ui.b.getColorIdForReservedName('tracing_memory_column')];tracingColumn.title=tr.ui.b.createSpan({textContent:'tracing',color:tracingColumnColor});tracingColumn.color=tracingColumnColor;}
usedMemorySizeColumns.forEach(function(column){var olderUsedMemoryColumnColor=tr.ui.b.getColorPalette()[tr.ui.b.getColorIdForReservedName('older_used_memory_column')];var usedMemoryColumnColor=tr.ui.b.getColorPalette()[tr.ui.b.getColorIdForReservedName('used_memory_column')];column.title=tr.ui.b.createSpan({textContent:column.title,color:usedMemoryColumnColor});column.color=function(attr){return attr.isOlderValue?olderUsedMemoryColumnColor:usedMemoryColumnColor;}});var sizeColumns=usedMemorySizeColumns.concat(allocatorSizeColumns);tr.ui.analysis.MemoryColumn.spaceEqually(sizeColumns);var columns=[titleColumn].concat(sizeColumns);this.$.table.tableColumns=columns;},storeSelection_:function(){var selectedRowTitle;var selectedRow=this.$.table.selectedTableRow;if(selectedRow!==undefined)
2015-06-14 13:52:57 -06:00
selectedRowTitle=selectedRow.title;var selectedColumnName;var selectedColumnIndex=this.$.table.selectedColumnIndex;if(selectedColumnIndex!==undefined){var selectedColumn=this.$.table.tableColumns[selectedColumnIndex];selectedColumnName=selectedColumn.name;}
tr.b.SessionSettings.set(SETTINGS_KEY,{rowTitle:selectedRowTitle,columnName:selectedColumnName},SETTINGS_NAMESPACE);},restoreSelection_:function(){var settings=tr.b.SessionSettings.get(SETTINGS_KEY,{},SETTINGS_NAMESPACE);if(settings.rowTitle===undefined||settings.columnName===undefined)
return;var selectedColumnName=settings.columnName;var selectedColumnIndex=tr.b.findFirstIndexInArray(this.$.table.tableColumns,function(column){return column.name===selectedColumnName;});if(selectedColumnIndex< 0 )
return;var selectedRowTitle=settings.rowTitle;var selectedRow=tr.b.findFirstInArray(this.$.table.tableRows,function(row){return row.title===selectedRowTitle;});if(selectedRow===undefined)
2015-06-18 08:27:29 -06:00
return;this.$.table.selectedTableRow=selectedRow;this.$.table.selectedColumnIndex=selectedColumnIndex;}});})();'use strict';Polymer('tr-ui-a-memory-dump-view',{created:function(){this.processMemoryDumps_=undefined;},ready:function(){this.$.overview_pane.addEventListener('selected-memory-cell-changed',this.updateDetailsPane_.bind(this));},set processMemoryDumps(processMemoryDumps){this.processMemoryDumps_=processMemoryDumps;this.$.overview_pane.processMemoryDumps=this.processMemoryDumps_;this.updateDetailsPane_();},get processMemoryDumps(){return this.processMemoryDumps_;},updateDetailsPane_:function(){this.$.details_pane_container.textContent='';var selectedMemoryCell=this.$.overview_pane.selectedMemoryCell;if(!selectedMemoryCell||!selectedMemoryCell.buildDetailsPane)
return;this.$.details_pane_container.appendChild(selectedMemoryCell.buildDetailsPane());}});'use strict';Polymer('tr-ui-a-single-process-memory-dump-sub-view',{set selection(selection){if(selection.length!==1)
2015-06-14 13:52:57 -06:00
throw new Error('Only supports a single process memory dump');if(!(selection[0]instanceof tr.model.ProcessMemoryDump))
2015-06-18 08:27:29 -06:00
throw new Error('Only supports process memory dumps');this.currentSelection_=selection;this.$.memory_dump_view.processMemoryDumps=[selection[0]];},get selection(){return this.currentSelection_;},get requiresTallView(){return true;}});'use strict';Polymer('tr-ui-a-multi-process-memory-dump-sub-view',{created:function(){this.currentSelection_=undefined;},get selection(){return this.currentSelection_;},set selection(selection){this.currentSelection_=selection;selection=tr.b.asArray(selection).sort(tr.b.Range.compareByMinTimes);var table=this.$.content;table.tableColumns=[{title:'Dump',value:function(row){var linkEl=document.createElement('tr-ui-a-analysis-link');linkEl.setSelectionAndContent(function(){return new tr.c.Selection(row);});var spanEl=document.createElement('span');spanEl.textContent='Process memory dump at ';linkEl.appendChild(spanEl);linkEl.appendChild(tr.ui.units.createTimeStampSpan(row.start));return linkEl;}}];table.showHeader=false;table.tableRows=selection;table.rebuild();}});'use strict';Polymer('tr-ui-a-single-global-memory-dump-sub-view',{set selection(selection){if(selection.length!==1)
2015-06-14 13:52:57 -06:00
throw new Error('Only supports a single global memory dump');if(!(selection[0]instanceof tr.model.GlobalMemoryDump))
2015-06-18 08:27:29 -06:00
throw new Error('Only supports global memory dumps');this.currentSelection_=selection;this.$.memory_dump_view.processMemoryDumps=tr.b.dictionaryValues(selection[0].processMemoryDumps);},get selection(){return this.currentSelection_;},get requiresTallView(){return true;}});'use strict';Polymer('tr-ui-a-multi-global-memory-dump-sub-view',{created:function(){this.currentSelection_=undefined;},get selection(){return this.currentSelection_;},set selection(selection){this.currentSelection_=selection;selection=tr.b.asArray(selection).sort(tr.b.Range.compareByMinTimes);var table=this.$.content;table.tableColumns=[{title:'Dump',value:function(row){var linkEl=document.createElement('tr-ui-a-analysis-link');linkEl.setSelectionAndContent(function(){return new tr.c.Selection(row);});var spanEl=document.createElement('span');spanEl.textContent='Global memory dump at ';linkEl.appendChild(spanEl);linkEl.appendChild(tr.ui.units.createTimeStampSpan(row.start));return linkEl;}}];table.showHeader=false;table.tableRows=selection;table.rebuild();}});'use strict';tr.exportTo('tr.ui.b',function(){Object.observe(Polymer.elements,clearPolymerElementCaches);var elementsByName=undefined;var elementsThatExtend=undefined;var elementSubclasses=undefined;function clearPolymerElementCaches(){elementsByName={};elementsThatExtend=undefined;elementSubclasses={};}
function buildElementMapsIfNeeded(){if(elementsThatExtend!==undefined& & elementsByName!==undefined)
return;elementsByName={};elementsThatExtend={};Polymer.elements.forEach(function(element){if(elementsByName[element.name])
throw new Error('Something is strange: dupe polymer element names');elementsByName[element.name]=element;if(element.extends){if(elementsThatExtend[element.extends]===undefined)
elementsThatExtend[element.extends]=[];elementsThatExtend[element.extends].push(element.name);}});}
function getPolymerElementNamed(tagName){buildElementMapsIfNeeded();return elementsByName[tagName];}
function getPolymerElementsThatSubclass(tagName){if(Polymer.waitingFor().length){throw new Error('There are unresolved polymer elements. '+'Wait until Polymer.whenReady');}
buildElementMapsIfNeeded();var element=getPolymerElementNamed(tagName);if(!element)
throw new Error(tagName+' is not a polymer element');if(elementSubclasses===undefined)
elementSubclasses={};if(elementSubclasses[tagName]===undefined){var immediateSubElements=elementsThatExtend[element.name];var allSubElements=[];if(immediateSubElements!==undefined&&immediateSubElements.length){immediateSubElements.forEach(function(subElement){allSubElements.push(subElement); allSubElements.push.apply(allSubElements,getPolymerElementsThatSubclass(subElement));});}
elementSubclasses[tagName]=allSubElements;}
return elementSubclasses[tagName];}
return{getPolymerElementNamed:getPolymerElementNamed,getPolymerElementsThatSubclass:getPolymerElementsThatSubclass};});'use strict';(function(){var EventRegistry=tr.model.EventRegistry;Polymer('tr-ui-a-analysis-view',{ready:function(){this.tabView_=document.createElement('tr-ui-a-tab-view');this.tabView_.style.flex='1 1 auto';this.appendChild(this.tabView_);this.selectionController_=undefined;this.onSelectedTabChange_=this.onSelectedTabChange_.bind(this);this.onSelectionChanged_=this.onSelectionChanged_.bind(this);this.lastSeenSelection_=new tr.c.Selection();},set tallMode(value){if(value)
2015-06-14 13:52:57 -06:00
this.classList.add('tall-mode');else
this.classList.remove('tall-mode');},get tallMode(){return this.classList.contains('tall-mode');},get tabView(){return this.tabView_;},get selectionController(){return this.selectionController_;},set selectionController(selectionController){if(this.selectionController){this.selectionController_.removeEventListener('change',this.onSelectionChanged_);}
this.selectionController_=selectionController;if(this.selectionController){this.selectionController_.addEventListener('change',this.onSelectionChanged_);}
this.onSelectionChanged_();},get selection(){return this.selectionController_.selection;},onSelectionChanged_:function(e){var selection=this.selectionController_.selection;var selectionHasSameValue=this.lastSeenSelection_.equals(selection);this.lastSeenSelection_=selection;if(selectionHasSameValue)
return;var lastSelectedTabTagName;var lastSelectedTabTypeName;if(this.tabView_.selectedTab){lastSelectedTabTagName=this.tabView_.selectedTab.tagName;lastSelectedTabTypeName=this.tabView_.selectedTab._eventTypeName;}
this.tallMode=false;var previouslySelectedTab=this.tabView_.selectedTab;this.tabView_.removeEventListener('selected-tab-change',this.onSelectedTabChange_);this.tabView_.textContent='';if(selection.length==0){this.tabView_.tabStripHeadingText='Nothing selected. Tap stuff.';}else if(selection.length==1){this.tabView_.tabStripHeadingText='1 item selected: ';}else{this.tabView_.tabStripHeadingText=selection.length+' items selected: ';}
var eventsByBaseTypeName=selection.getEventsOrganizedByBaseType(true);var numBaseTypesToAnalyze=tr.b.dictionaryLength(eventsByBaseTypeName);for(var eventTypeName in eventsByBaseTypeName){var subSelection=eventsByBaseTypeName[eventTypeName];var subView=this.createSubViewForSelection_(eventTypeName,subSelection);subView._eventTypeName=eventTypeName;this.tabView_.appendChild(subView);subView.selection=subSelection;}
var tab;if(lastSelectedTabTagName)
tab=this.tabView_.querySelector(lastSelectedTabTagName);if(!tab& & lastSelectedTabTypeName){var tab=tr.b.findFirstInArray(this.tabView_.children,function(tab){return tab._eventTypeName===lastSelectedTabTypeName;});}
if(!tab)
tab=this.tabView_.firstChild;this.tabView_.selectedTab=tab;if(this.tabView_.selectedTab!==previouslySelectedTab)
this.onSelectedTabChange_();this.tabView_.addEventListener('selected-tab-change',this.onSelectedTabChange_);},createSubViewForSelection_:function(eventTypeName,subSelection){var eventTypeInfo=EventRegistry.getEventTypeInfoByTypeName(eventTypeName);var singleMode=subSelection.length==1;var tagName;if(subSelection.length===1)
tagName=eventTypeInfo.metadata.singleViewElementName;else
2015-06-18 08:27:29 -06:00
tagName=eventTypeInfo.metadata.multiViewElementName;if(!tr.ui.b.getPolymerElementNamed(tagName))
2015-06-14 13:52:57 -06:00
throw new Error('Element not registered: '+tagName);var subView=document.createElement(tagName);var camelLabel;if(subSelection.length===1)
camelLabel=EventRegistry.getUserFriendlySingularName(eventTypeName);else
camelLabel=EventRegistry.getUserFriendlyPluralName(eventTypeName);subView.tabLabel=camelLabel+' ('+subSelection.length+')';return subView;},onSelectedTabChange_:function(){var selectionController=this.selectionController_;if(this.tabView_.selectedTab){var selectedTab=this.tabView_.selectedTab;this.tallMode=selectedTab.requiresTallView;if(selectionController){var rlth=selectedTab.relatedEventsToHighlight;selectionController.changeAnalysisViewRelatedEvents(rlth);}}else{this.tallMode=false;if(selectionController)
2015-06-18 08:27:29 -06:00
selectionController.changeAnalysisViewRelatedEvents(undefined);}}});})();'use strict';tr.exportTo('tr.ui.b',function(){var FaviconsByHue={blue:'data:image/vndmicrosofticon;base64,AAABAAIAEBAAAAEAIABoBAAAJgAAACAgAAABACAAqBAAAI4EAAAoAAAAEAAAACAAAAABACAAAAAAAAAEAAASCwAAEgsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAjj8xAGArIgqOPzE8nUY3dqJJOJeiSTiXnUY3do4/MTxhKyIKjkAxAAAAAAAAAAAAAAAAAAAAAABQJBwAAAAAAZJBMzSoSzqlsU8+6bRQP/21UT//tVE//7RQP/2wTz3ppko6pY9AMjQAAAABTyMbAAAAAAB7e3sAAP//AKFSRE+wTz3dtVE//7VRP/+1UT//tVE//7VRP/+zUD7/sE89/7BOPf+qTDvdl0M0TwAAAABWJx4A+fn5ANjd3TnIiX7ftVA9/7VRP/+1UT//tVE//7VRP/+xTz3/rE08/6xMO/+sTDv/rE08/6dKOt+SQTM5q0w7ALO0tA3v8fGu05uR/7NMOf+0Tzz/tE88/7RPPv+uTT3/p0o7/6ZJOv+mSTr/pkk6/6ZJOv+mSjr/n0Y4rnIwKg3h4eFK9/j48N2zrP/FeGr/xnps/8Z6bP/AaUv/tlw1/7RbNf+1WzX/tFs1/7RbNf+0WzX/tFs1/7NbNPCqWy1K7e3tjPn5+f/49vX/9vLy//by8v/28vH/8bZv/+6RH//ukyP/7pMj/+6SI//ukiP/7pMj/+2SIv/qjyL/34kfjPHx8bL5+fn/+fn5//n5+f/5+fr/+fn5//W7cP/zlB3/85Yh//OWIf/zliH/85Yh//GVIf/rkR//6ZAf/+KLHrLz8/O2+fn5//n5+f/5+fn/+fn5//n5+f/1unD/85Qd//OWIf/zliH/85Yh//CUIP/mjh//44we/+OMHv/diR628vLymfn5+f/5+fn/+fn5//n5+f/5+fn/9bx0//OXI//zmCb/85gm/++VIv/hjB//3Yoe/92KHv/dih7/2IYdmfHx8Vz4+Pj3+fn5//n5+f/5+fn/+fn5//jo0//33bv/9929//bbtf/euDX/06oJ/9OrC//Tqwv/06oM98yfD1zr6+sY9/f3xvn5+f/5+fn/+fn5//n5+f/5+vv/+fv8//n7/f/3+PH/3Ms6/9O8AP/UvQD/1L0A/9K8AMbItAAY////APT09Fb4+Pjy+fn5//n5+f/5+fn/+fn5//n5+f/5+fr/9/bu/9zKOf/TuwD/1LwA/9S8APLQuABW3cQAAOzs7ADm5uYF9vb2ePn5+fT5+fn/+fn5//n5+f/5+fn/+fn6//f27v/cyTn/07sA/9S8APTRugB4w60ABcmyAAAAAAAA8PDwAOzs7Ab29vZd+Pj40vn5+fz5+fn/+fn5//n5+f/49/H/5Ndu/NjEIdLSugBdybIABsy1AAAAAAAAAAAAAAAAAADn5+cAqKioAPT09CH39/dy+Pj4tvj4+NX4+PjV+Pj4tvX063Lt6MMhOQAAAM+/RAAAAAAAAAAAAPAPAADAAwAAwAMAAIABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIABAACAAQAAwAMAAPAPAAAoAAAAIAAAAEAAAAABACAAAAAAAAAQAAASCwAAEgsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABCwUEDDgZExxWJx4tYiwiN2IsIjdWJx4tOBkTHAsFBAwAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wAbDAkKZS0jMYs+MWydRjeipko6x6tMO9utTTzjrU0846tMO9umSjrHnUY3oos+MWxlLSMxGwwJCv///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgZFAAPBwUHcjMoPJtFNpqsTTzhs1A+/LVRP/+2UT//tVE//7VRP/+1UT//tVE//7ZRP/+1UT//s1A+/KxNPOGbRTaacTInPA8HBQc4GRMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/yp4AUCQcGZVDNICtTjzktVE//7VRP/+1UT//tVE//7VRP/+1UT//tVE//7VRP/+1UT//tVE//7VRP/+0UT//s1A+/7JQPv+rTDvkkkEzgE8jGxn/xZoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAA////AGswJSqiSTivs1A++7VRP/+1UT//tVE//7VRP/+1UT//tVE//7VRP/+1UT//tVE//7VRP/+1UT//tFA+/7FPPf+xTz3/sU89/7FPPf+vTj37nkc3r2guJCr///8AAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwMDAP/DogB/VEwsqE09v7VRP/+1UT//tVE//7VRP/+1UT//tVE//7VRP/+1UT//tVE//7VRP/+1UT//tVE//7NQPv+vTj3/r049/69OPf+vTj3/r049/69OPf+uTjz/oUg4v20xJiz/nnsAAgEBAAAAAAAAAAAAAAAAAAAAAAD19fUAkp2fHdK2sbW5W0r/tVA+/7VRP/+1UT//tVE//7VRP/+1UT//tVE//7VRP/+1UT//tVE//7VRP/+yUD7/rU08/6xNPP+tTTz/rU08/61NPP+tTTz/rU08/61NPP+sTTz/nkY3tWAqIR2pSzsAAAAAAAAAAAAAAAAAeXl5ADY2Ngnd39+O6tbT/blbSv+1UD7/tVE//7VRP/+1UT//tVE//7VRP/+1UT//tVE//7VRP/+1UT//slA+/6xNPP+rTDv/q0w7/6tMO/+rTDv/q0w7/6tMO/+rTDv/q0w7/6tMO/+qTDv9lkM0jiUQDQlSJR0AAAAAAAAAAAD///8AxMTES/X29u3s2NX/uVtK/7VQPv+1UT//tVE//7VRP/+1UT//tVE//7VRP/+1UT//tVE//7FPPv+qTDv/qEs6/6hLOv+oSzr/qEs6/6hLOv+oSzr/qEs6/6hLOv+oSzr/qEs6/6lLOv+lSTnthDsuS/+TcgAAAAAAm5ubAHBwcA/o6Oix+vv8/+zY1P+5W0r/tVA+/7VRP/+1UT//tVE//7VRP/+1UT//tVE//7VRP/+xTz3/qEs6/6ZKOv+mSjr/pko6/6ZKOv+mSjr/pko6/6ZKOv+mSjr/pko6/6ZKOv+mSjr/pko6/6ZKOv+bRTaxSiEaD2cuJAD///8AycnJRfX19fD6+/z/69fU/7hYR/+0Tjv/tE48/7ROPP+0Tjz/tE48/7ROPP+0Tz3/r04+/6VJOv+jSDn/o0g5/6NIOf+jSDn/o0g5/6NIOf+jSDn/o0g5/6NIOf+jSDr/o0g5/6NIOf+jSDn/o0g6/6BHOfCCOS9F0FxKAAAAAALk5OSN+fn5//n6+v/y5+X/05uS/9CTiP/QlIn/0JSJ/9CUif/QlIn/0JSK/8yGb//AaDb/vWc0/71nNf+9ZzT/vWc0/71nNP+9ZjT/vWY0/71mNP+9ZjT/vGY0/7xmNP+8ZjT/vGY0/7xmNP+8ZjT/u2U0/7FiLY0AAAACk5OTFu/v78X5+fn/+fn5//n5+f/5+vr/+fn5//n5+f/5+fn/+fn5//n5+f/5+/3/99iy//KWI//ylSH/8ZUh//GVIf/xlSH/8ZUh//GVIf/xlSH/8ZUh//GVIf/xlSH/8ZUh//GVIf/xlSH/8ZUh//CUIf/vkyD/5Y0fxY1XExbDw8Mz9PT05fn5+f/5+fn/+fn5//n5+f/5+fn/+fn5//n5+f/5+fn/+fn5//n7/f/32LL/85cj//OWIf/zliH/85Yh
2015-06-14 13:52:57 -06:00
task=operation;else
task=new tr.b.Task(operation,this);if(this.activeTask_){this.activeTask_=this.activeTask_.enqueue(task);}else{this.activeTask_=task;this.activePromise_=Task.RunWhenIdle(this.activeTask_);this.activePromise_.then(function(){this.activePromise_=undefined;this.activeTask_=undefined;}.bind(this));}},startFiltering:function(filterText){var sc=this.selectionController_;if(!sc)
return;this.enqueueOperation_(function(){this.filterHits_=new tr.c.Selection();this.currentHitIndex_=-1;}.bind(this));var stateFromString;try{stateFromString=sc.uiStateFromString(filterText);}catch(e){this.enqueueOperation_(function(){var overlay=new tr.ui.b.Overlay();overlay.textContent=e.message;overlay.title='UI State Navigation Error';overlay.visible=true;});return this.activePromise_;}
if(stateFromString!==undefined){this.enqueueOperation_(sc.navToPosition.bind(this,stateFromString,true));}else{if(filterText.length===0){this.enqueueOperation_(sc.findTextCleared.bind(sc));}else{var filter=new tr.c.TitleOrCategoryFilter(filterText);var filterHits=new tr.c.Selection();this.enqueueOperation_(sc.addAllEventsMatchingFilterToSelectionAsTask(filter,filterHits));this.enqueueOperation_(function(){this.filterHits_=filterHits;sc.findTextChangedTo(filterHits);}.bind(this));}}
return this.activePromise_;},get filterHits(){return this.filterHits_;},get currentHitIndex(){return this.currentHitIndex_;},find_:function(dir){var firstHit=this.currentHitIndex_===-1;if(firstHit& & dir< 0 )
this.currentHitIndex_=0;var N=this.filterHits.length;this.currentHitIndex_=(this.currentHitIndex_+dir+N)%N;if(!this.selectionController_)
2015-06-18 08:27:29 -06:00
return;this.selectionController_.findFocusChangedTo(this.filterHits.subSelection(this.currentHitIndex_,1));},findNext:function(){this.find_(1);},findPrevious:function(){this.find_(-1);}};return{FindController:FindController};});'use strict';tr.exportTo('tr.ui.b',function(){var paletteRaw=tr.ui.b.getRawColorPalette();var palette=tr.ui.b.getColorPalette();var SelectionState=tr.model.SelectionState;var EventPresenter={getSelectableItemColor:function(item){var colorId=item.colorId+this.getColorIdOffset_(item);return palette[colorId];},getColorIdOffset_:function(event){if(event.selectionState===SelectionState.SELECTED)
2015-06-14 13:52:57 -06:00
return tr.ui.b.paletteProperties.highlightIdBoost;else if(event.selectionState===SelectionState.DIMMED)
return tr.ui.b.paletteProperties.desaturateIdBoost;return 0;},getTextColor:function(event){if(event.selectionState===SelectionState.DIMMED)
return'rgb(60,60,60)';return'rgb(0,0,0)';},getSliceColorId:function(slice){return slice.colorId+this.getColorIdOffset_(slice);},getSliceAlpha:function(slice,async){var alpha=1;if(async)
2015-06-18 08:27:29 -06:00
alpha*=0.3;return alpha;},getInstantSliceColor:function(instant){var colorId=instant.colorId+this.getColorIdOffset_(instant);return tr.ui.b.colorToRGBAString(paletteRaw[colorId],1.0);},getObjectInstanceColor:function(instance){var colorId=instance.colorId+this.getColorIdOffset_(instance);return tr.ui.b.colorToRGBAString(paletteRaw[colorId],0.25);},getObjectSnapshotColor:function(snapshot){var colorId=snapshot.objectInstance.colorId+this.getColorIdOffset_(snapshot);return palette[colorId];},getCounterSeriesColor:function(colorId,selectionState,opt_alphaMultiplier){var event={selectionState:selectionState};return tr.ui.b.colorToRGBAString(paletteRaw[colorId+this.getColorIdOffset_(event)],(opt_alphaMultiplier!==undefined?opt_alphaMultiplier:1.0));},getBarSnapshotColor:function(snapshot,offset){var colorId=(snapshot.objectInstance.colorId+offset)%tr.ui.b.paletteProperties.numGeneralPurposeColorIds;colorId+=this.getColorIdOffset_(snapshot);return tr.ui.b.colorToRGBAString(paletteRaw[colorId],1.0);}};return{EventPresenter:EventPresenter};});'use strict';tr.exportTo('tr.ui.b',function(){var elidedTitleCacheDict={};var elidedTitleCache=new ElidedTitleCache();function ElidedTitleCache(){this.textWidthMap={};}
2015-06-14 13:52:57 -06:00
ElidedTitleCache.prototype={get:function(ctx,pixWidth,title,width,sliceDuration){var elidedDict=elidedTitleCacheDict[title];if(!elidedDict){elidedDict={};elidedTitleCacheDict[title]=elidedDict;}
var elidedDictForPixWidth=elidedDict[pixWidth];if(!elidedDictForPixWidth){elidedDict[pixWidth]={};elidedDictForPixWidth=elidedDict[pixWidth];}
var stringWidthPair=elidedDictForPixWidth[sliceDuration];if(stringWidthPair===undefined){var newtitle=title;var elided=false;while(this.labelWidthWorld(ctx,newtitle,pixWidth)>sliceDuration){if(newtitle.length*0.75< 1 )
break;newtitle=newtitle.substring(0,newtitle.length*0.75);elided=true;}
if(elided& & newtitle.length>3)
newtitle=newtitle.substring(0,newtitle.length-3)+'...';stringWidthPair=new ElidedStringWidthPair(newtitle,this.labelWidth(ctx,newtitle));elidedDictForPixWidth[sliceDuration]=stringWidthPair;}
return stringWidthPair;},quickMeasureText_:function(ctx,text){var w=this.textWidthMap[text];if(!w){w=ctx.measureText(text).width;this.textWidthMap[text]=w;}
return w;},labelWidth:function(ctx,title){return this.quickMeasureText_(ctx,title)+2;},labelWidthWorld:function(ctx,title,pixWidth){return this.labelWidth(ctx,title)*pixWidth;}};function ElidedStringWidthPair(string,width){this.string=string;this.width=width;}
2015-06-18 08:27:29 -06:00
return{ElidedTitleCache:ElidedTitleCache};});'use strict';tr.exportTo('tr.ui.b',function(){var elidedTitleCache=new tr.ui.b.ElidedTitleCache();var palette=tr.ui.b.getColorPalette();var EventPresenter=tr.ui.b.EventPresenter;var blackColorId=tr.ui.b.getColorIdForReservedName('black');var THIN_SLICE_HEIGHT=4;var SLICE_WAITING_WIDTH_DRAW_THRESHOLD=3;var SLICE_ACTIVE_WIDTH_DRAW_THRESHOLD=1;var SHOULD_ELIDE_TEXT=true;function drawLine(ctx,x1,y1,x2,y2){ctx.moveTo(x1,y1);ctx.lineTo(x2,y2);}
2015-06-14 13:52:57 -06:00
function drawTriangle(ctx,x1,y1,x2,y2,x3,y3){ctx.beginPath();ctx.moveTo(x1,y1);ctx.lineTo(x2,y2);ctx.lineTo(x3,y3);ctx.closePath();}
function drawArrow(ctx,x1,y1,x2,y2,arrowLength,arrowWidth){var dx=x2-x1;var dy=y2-y1;var len=Math.sqrt(dx*dx+dy*dy);var perc=(len-arrowLength)/len;var bx=x1+perc*dx;var by=y1+perc*dy;var ux=dx/len;var uy=dy/len;var ax=uy*arrowWidth;var ay=-ux*arrowWidth;ctx.beginPath();drawLine(ctx,x1,y1,x2,y2);ctx.stroke();drawTriangle(ctx,bx+ax,by+ay,x2,y2,bx-ax,by-ay);ctx.fill();}
function drawSlices(ctx,dt,viewLWorld,viewRWorld,viewHeight,slices,async){var pixelRatio=window.devicePixelRatio||1;var pixWidth=dt.xViewVectorToWorld(1);var height=viewHeight*pixelRatio;var darkRectHeight=THIN_SLICE_HEIGHT*pixelRatio;if(height< darkRectHeight )
2015-06-18 08:27:29 -06:00
darkRectHeight=0;var lightRectHeight=height-darkRectHeight;ctx.save();dt.applyTransformToCanvas(ctx);var rect=new tr.ui.b.FastRectRenderer(ctx,2*pixWidth,2*pixWidth,palette);rect.setYandH(0,height);var lowSlice=tr.b.findLowIndexInSortedArray(slices,function(slice){return slice.start+slice.duration;},viewLWorld);var hadTopLevel=false;for(var i=lowSlice;i< slices.length ; + + i ) { var slice = slices[i];var x = slice.start;if(x > viewRWorld)
2015-06-14 13:52:57 -06:00
break;var w=pixWidth;if(slice.duration>0){w=Math.max(slice.duration,0.000001);if(w< pixWidth )
w=pixWidth;}
var colorId=EventPresenter.getSliceColorId(slice);var alpha=EventPresenter.getSliceAlpha(slice,async);var lightAlpha=alpha*0.70;if(slice.isTopLevel){rect.setYandH(3,height-3);hadTopLevel=true;}else{rect.setYandH(0,height);}
if(!slice.cpuDuration){rect.fillRect(x,w,colorId,alpha);continue;}
var activeWidth=w*(slice.cpuDuration/slice.duration);var waitingWidth=w-activeWidth;if(activeWidth< SLICE_ACTIVE_WIDTH_DRAW_THRESHOLD * pixWidth ) { activeWidth = 0;waitingWidth=w;}
if(waitingWidth< SLICE_WAITING_WIDTH_DRAW_THRESHOLD * pixWidth ) { activeWidth = w;waitingWidth=0;}
if(activeWidth>0){rect.fillRect(x,activeWidth,colorId,alpha);}
if(waitingWidth>0){rect.setYandH(0,lightRectHeight);rect.fillRect(x+activeWidth-pixWidth,waitingWidth+pixWidth,colorId,lightAlpha);rect.setYandH(lightRectHeight,darkRectHeight);rect.fillRect(x+activeWidth-pixWidth,waitingWidth+pixWidth,colorId,alpha);rect.setYandH(0,height);}}
rect.flush();if(async&&hadTopLevel){rect.setYandH(2,1); for(var i=lowSlice;i< slices.length ; + + i ) { var slice = slices[i];var x = slice.start;if(x > viewRWorld)
break;if(!slice.isTopLevel)
continue;var w=pixWidth;if(slice.duration>0){w=Math.max(slice.duration,0.000001);if(w< pixWidth )
w=pixWidth;}
rect.fillRect(x,w,blackColorId,0.7);}
rect.flush();}
ctx.restore();}
function drawInstantSlicesAsLines(ctx,dt,viewLWorld,viewRWorld,viewHeight,slices,lineWidthInPixels){var pixelRatio=window.devicePixelRatio||1;var height=viewHeight*pixelRatio;var pixWidth=dt.xViewVectorToWorld(1);ctx.save();ctx.lineWidth=pixWidth*lineWidthInPixels*pixelRatio;dt.applyTransformToCanvas(ctx);ctx.beginPath();var lowSlice=tr.b.findLowIndexInSortedArray(slices,function(slice){return slice.start;},viewLWorld);for(var i=lowSlice;i< slices.length ; + + i ) { var slice = slices[i];var x = slice.start;if(x > viewRWorld)
break;ctx.strokeStyle=EventPresenter.getInstantSliceColor(slice);ctx.beginPath();ctx.moveTo(x,0);ctx.lineTo(x,height);ctx.stroke();}
ctx.restore();}
function drawLabels(ctx,dt,viewLWorld,viewRWorld,slices,async,fontSize,yOffset){var pixelRatio=window.devicePixelRatio||1;var pixWidth=dt.xViewVectorToWorld(1);ctx.save();ctx.textAlign='center';ctx.textBaseline='top';ctx.font=(fontSize*pixelRatio)+'px sans-serif';if(async)
ctx.font='italic '+ctx.font;var cY=yOffset*pixelRatio;var lowSlice=tr.b.findLowIndexInSortedArray(slices,function(slice){return slice.start+slice.duration;},viewLWorld);var quickDiscardThresshold=pixWidth*20;for(var i=lowSlice;i< slices.length ; + + i ) { var slice = slices[i];if(slice.start > viewRWorld)
break;if(slice.duration< =quickDiscardThresshold)
continue;var title=slice.title+
(slice.didNotFinish?' (Did Not Finish)':'');var drawnTitle=title;var drawnWidth=elidedTitleCache.labelWidth(ctx,drawnTitle);var fullLabelWidth=elidedTitleCache.labelWidthWorld(ctx,drawnTitle,pixWidth);if(SHOULD_ELIDE_TEXT& & fullLabelWidth>slice.duration){var elidedValues=elidedTitleCache.get(ctx,pixWidth,drawnTitle,drawnWidth,slice.duration);drawnTitle=elidedValues.string;drawnWidth=elidedValues.width;}
if(drawnWidth*pixWidth< slice.duration ) { ctx . fillStyle = EventPresenter.getTextColor(slice);var cX = dt.xWorldToView(slice.start+0.5*slice.duration);ctx.fillText(drawnTitle,cX,cY,drawnWidth);}}
ctx.restore();}
2015-06-18 08:27:29 -06:00
return{drawSlices:drawSlices,drawInstantSlicesAsLines:drawInstantSlicesAsLines,drawLabels:drawLabels,drawLine:drawLine,drawTriangle:drawTriangle,drawArrow:drawArrow,elidedTitleCache_:elidedTitleCache,THIN_SLICE_HEIGHT:THIN_SLICE_HEIGHT};});'use strict';tr.exportTo('tr.ui',function(){function SnapIndicator(y,height){this.y=y;this.height=height;}
2015-06-14 13:52:57 -06:00
function TimelineInterestRange(vp){this.viewport_=vp;this.range_=new tr.b.Range();this.leftSelected_=false;this.rightSelected_=false;this.leftSnapIndicator_=undefined;this.rightSnapIndicator_=undefined;}
TimelineInterestRange.prototype={get isEmpty(){return this.range_.isEmpty;},reset:function(){this.range_.reset();this.leftSelected_=false;this.rightSelected_=false;this.leftSnapIndicator_=undefined;this.rightSnapIndicator_=undefined;this.viewport_.dispatchChangeEvent();},get min(){return this.range_.min;},set min(min){this.range_.min=min;this.viewport_.dispatchChangeEvent();},get max(){return this.range_.max;},set max(max){this.range_.max=max;this.viewport_.dispatchChangeEvent();},set:function(range){this.range_.reset();this.range_.addRange(range);this.viewport_.dispatchChangeEvent();},setMinAndMax:function(min,max){this.range_.min=min;this.range_.max=max;this.viewport_.dispatchChangeEvent();},get range(){return this.range_.range;},asRangeObject:function(){var range=new tr.b.Range();range.addRange(this.range_);return range;},get leftSelected(){return this.leftSelected_;},set leftSelected(leftSelected){if(this.leftSelected_==leftSelected)
return;this.leftSelected_=leftSelected;this.viewport_.dispatchChangeEvent();},get rightSelected(){return this.rightSelected_;},set rightSelected(rightSelected){if(this.rightSelected_==rightSelected)
return;this.rightSelected_=rightSelected;this.viewport_.dispatchChangeEvent();},get leftSnapIndicator(){return this.leftSnapIndicator_;},set leftSnapIndicator(leftSnapIndicator){this.leftSnapIndicator_=leftSnapIndicator;this.viewport_.dispatchChangeEvent();},get rightSnapIndicator(){return this.rightSnapIndicator_;},set rightSnapIndicator(rightSnapIndicator){this.rightSnapIndicator_=rightSnapIndicator;this.viewport_.dispatchChangeEvent();},draw:function(ctx,viewLWorld,viewRWorld){if(this.range_.isEmpty)
return;var dt=this.viewport_.currentDisplayTransform;var markerLWorld=this.min;var markerRWorld=this.max;var markerLView=Math.round(dt.xWorldToView(markerLWorld));var markerRView=Math.round(dt.xWorldToView(markerRWorld));ctx.fillStyle='rgba(0, 0, 0, 0.2)';if(markerLWorld>viewLWorld){ctx.fillRect(dt.xWorldToView(viewLWorld),0,markerLView,ctx.canvas.height);}
if(markerRWorld< viewRWorld ) { ctx . fillRect ( markerRView , 0 , dt . xWorldToView ( viewRWorld ) , ctx . canvas . height ) ; }
var pixelRatio=window.devicePixelRatio||1;ctx.lineWidth=Math.round(pixelRatio);if(this.range_.range>0){this.drawLine_(ctx,viewLWorld,viewRWorld,ctx.canvas.height,this.min,this.leftSelected_);this.drawLine_(ctx,viewLWorld,viewRWorld,ctx.canvas.height,this.max,this.rightSelected_);}else{this.drawLine_(ctx,viewLWorld,viewRWorld,ctx.canvas.height,this.min,this.leftSelected_||this.rightSelected_);}
ctx.lineWidth=1;},drawLine_:function(ctx,viewLWorld,viewRWorld,height,ts,selected){if(ts< viewLWorld | | ts > =viewRWorld)
2015-06-18 08:27:29 -06:00
return;var dt=this.viewport_.currentDisplayTransform;var viewX=Math.round(dt.xWorldToView(ts));ctx.save();ctx.translate((Math.round(ctx.lineWidth)%2)/2,0);ctx.beginPath();tr.ui.b.drawLine(ctx,viewX,0,viewX,height);if(selected)
2015-06-14 13:52:57 -06:00
ctx.strokeStyle='rgb(255, 0, 0)';else
ctx.strokeStyle='rgb(0, 0, 0)';ctx.stroke();ctx.restore();},drawIndicators:function(ctx,viewLWorld,viewRWorld){if(this.leftSnapIndicator_){this.drawIndicator_(ctx,viewLWorld,viewRWorld,this.range_.min,this.leftSnapIndicator_,this.leftSelected_);}
if(this.rightSnapIndicator_){this.drawIndicator_(ctx,viewLWorld,viewRWorld,this.range_.max,this.rightSnapIndicator_,this.rightSelected_);}},drawIndicator_:function(ctx,viewLWorld,viewRWorld,xWorld,si,selected){var dt=this.viewport_.currentDisplayTransform;var viewX=Math.round(dt.xWorldToView(xWorld));ctx.save();ctx.translate((Math.round(ctx.lineWidth)%2)/2,0);var pixelRatio=window.devicePixelRatio||1;var viewY=si.y*devicePixelRatio;var viewHeight=si.height*devicePixelRatio;var arrowSize=4*pixelRatio;if(selected)
ctx.fillStyle='rgb(255, 0, 0)';else
2015-06-18 08:27:29 -06:00
ctx.fillStyle='rgb(0, 0, 0)';tr.ui.b.drawTriangle(ctx,viewX-arrowSize*0.75,viewY,viewX+arrowSize*0.75,viewY,viewX,viewY+arrowSize);ctx.fill();tr.ui.b.drawTriangle(ctx,viewX-arrowSize*0.75,viewY+viewHeight,viewX+arrowSize*0.75,viewY+viewHeight,viewX,viewY+viewHeight-arrowSize);ctx.fill();ctx.restore();}};return{SnapIndicator:SnapIndicator,TimelineInterestRange:TimelineInterestRange};});'use strict';tr.exportTo('tr.ui',function(){function TimelineDisplayTransform(opt_that){if(opt_that){this.set(opt_that);return;}
2015-06-14 13:52:57 -06:00
this.scaleX=1;this.panX=0;this.panY=0;}
TimelineDisplayTransform.prototype={set:function(that){this.scaleX=that.scaleX;this.panX=that.panX;this.panY=that.panY;},clone:function(){return new TimelineDisplayTransform(this);},equals:function(that){var eq=true;if(that===undefined||that===null)
return false;eq&=this.panX===that.panX; eq&=this.panY===that.panY; eq&=this.scaleX===that.scaleX; return!!eq;},almostEquals:function(that){var eq=true;if(that===undefined||that===null)
return false;eq&=Math.abs(this.panX-that.panX)<0.001; eq&=Math.abs(this.panY-that.panY)<0.001; eq&=Math.abs(this.scaleX-that.scaleX)<0.001; return!!eq;},incrementPanXInViewUnits:function(xDeltaView){this.panX+=this.xViewVectorToWorld(xDeltaView);},xPanWorldPosToViewPos:function(worldX,viewX,viewWidth){if(typeof viewX=='string'){if(viewX==='left'){viewX=0;}else if(viewX==='center'){viewX=viewWidth/2;}else if(viewX==='right'){viewX=viewWidth-1;}else{throw new Error('viewX must be left|center|right or number.');}}
this.panX=(viewX/this.scaleX)-worldX;},xPanWorldBoundsIntoView:function(worldMin,worldMax,viewWidth){if(this.xWorldToView(worldMin)< 0 )
this.xPanWorldPosToViewPos(worldMin,'left',viewWidth);else if(this.xWorldToView(worldMax)>viewWidth)
2015-06-18 08:27:29 -06:00
this.xPanWorldPosToViewPos(worldMax,'right',viewWidth);},xSetWorldBounds:function(worldMin,worldMax,viewWidth){var worldWidth=worldMax-worldMin;var scaleX=viewWidth/worldWidth;var panX=-worldMin;this.setPanAndScale(panX,scaleX);},setPanAndScale:function(p,s){this.scaleX=s;this.panX=p;},xWorldToView:function(x){return(x+this.panX)*this.scaleX;},xWorldVectorToView:function(x){return x*this.scaleX;},xViewToWorld:function(x){return(x/this.scaleX)-this.panX;},xViewVectorToWorld:function(x){return x/this.scaleX;},applyTransformToCanvas:function(ctx){ctx.transform(this.scaleX,0,0,1,this.panX*this.scaleX,0);}};return{TimelineDisplayTransform:TimelineDisplayTransform};});'use strict';tr.exportTo('tr.ui.tracks',function(){function ContainerToTrackMap(){this.stableIdToTrackMap_={};}
ContainerToTrackMap.prototype={addContainer:function(container,track){if(!track)
throw new Error('Must provide a track.');this.stableIdToTrackMap_[container.stableId]=track;},clear:function(){this.stableIdToTrackMap_={};},getTrackByStableId:function(stableId){return this.stableIdToTrackMap_[stableId];}};return{ContainerToTrackMap:ContainerToTrackMap};});'use strict';tr.exportTo('tr.ui.tracks',function(){function EventToTrackMap(){}
EventToTrackMap.prototype={addEvent:function(event,track){if(!track)
throw new Error('Must provide a track.');this[event.guid]=track;}};return{EventToTrackMap:EventToTrackMap};});'use strict';tr.exportTo('tr.ui.b',function(){function Animation(){}
2015-06-14 13:52:57 -06:00
Animation.prototype={canTakeOverFor:function(existingAnimation){throw new Error('Not implemented');},takeOverFor:function(existingAnimation,newStartTimestamp,target){throw new Error('Not implemented');},start:function(timestamp,target){throw new Error('Not implemented');},didStopEarly:function(timestamp,target,willBeTakenOverByAnotherAnimation){},tick:function(timestamp,target){throw new Error('Not implemented');}};return{Animation:Animation};});'use strict';tr.exportTo('tr.ui.b',function(){function AnimationController(){tr.b.EventTarget.call(this);this.target_=undefined;this.activeAnimation_=undefined;this.tickScheduled_=false;}
AnimationController.prototype={__proto__:tr.b.EventTarget.prototype,get target(){return this.target_;},set target(target){if(this.activeAnimation_)
throw new Error('Cannot change target while animation is running.');if(target.cloneAnimationState===undefined||typeof target.cloneAnimationState!=='function')
throw new Error('target must have a cloneAnimationState function');this.target_=target;},get activeAnimation(){return this.activeAnimation_;},get hasActiveAnimation(){return!!this.activeAnimation_;},queueAnimation:function(animation,opt_now){if(this.target_===undefined)
throw new Error('Cannot queue animations without a target');var now;if(opt_now!==undefined)
now=opt_now;else
now=window.performance.now();if(this.activeAnimation_){var done=this.activeAnimation_.tick(now,this.target_);if(done)
this.activeAnimation_=undefined;}
if(this.activeAnimation_){if(animation.canTakeOverFor(this.activeAnimation_)){this.activeAnimation_.didStopEarly(now,this.target_,true);animation.takeOverFor(this.activeAnimation_,now,this.target_);}else{this.activeAnimation_.didStopEarly(now,this.target_,false);}}
this.activeAnimation_=animation;this.activeAnimation_.start(now,this.target_);if(this.tickScheduled_)
return;this.tickScheduled_=true;tr.b.requestAnimationFrame(this.tickActiveAnimation_,this);},cancelActiveAnimation:function(opt_now){if(!this.activeAnimation_)
return;var now;if(opt_now!==undefined)
now=opt_now;else
now=window.performance.now();this.activeAnimation_.didStopEarly(now,this.target_,false);this.activeAnimation_=undefined;},tickActiveAnimation_:function(frameBeginTime){this.tickScheduled_=false;if(!this.activeAnimation_)
return;if(this.target_===undefined){this.activeAnimation_.didStopEarly(frameBeginTime,this.target_,false);return;}
var oldTargetState=this.target_.cloneAnimationState();var done=this.activeAnimation_.tick(frameBeginTime,this.target_);if(done)
this.activeAnimation_=undefined;if(this.activeAnimation_){this.tickScheduled_=true;tr.b.requestAnimationFrame(this.tickActiveAnimation_,this);}
2015-06-18 08:27:29 -06:00
if(oldTargetState){var e=new Event('didtick');e.oldTargetState=oldTargetState;this.dispatchEvent(e,false,false);}}};return{AnimationController:AnimationController};});'use strict';tr.exportTo('tr.ui',function(){var TimelineDisplayTransform=tr.ui.TimelineDisplayTransform;var TimelineInterestRange=tr.ui.TimelineInterestRange;function TimelineViewport(parentEl){this.parentEl_=parentEl;this.modelTrackContainer_=undefined;this.currentDisplayTransform_=new TimelineDisplayTransform();this.initAnimationController_();this.showFlowEvents_=false;this.highlightVSync_=false;this.highDetails_=false;this.gridTimebase_=0;this.gridStep_=1000/60;this.gridEnabled_=false;this.hasCalledSetupFunction_=false;this.onResize_=this.onResize_.bind(this);this.onModelTrackControllerScroll_=this.onModelTrackControllerScroll_.bind(this);this.checkForAttachInterval_=setInterval(this.checkForAttach_.bind(this),250);this.majorMarkPositions=[];this.interestRange_=new TimelineInterestRange(this);this.eventToTrackMap_=new tr.ui.tracks.EventToTrackMap();this.containerToTrackMap=new tr.ui.tracks.ContainerToTrackMap();}
2015-06-14 13:52:57 -06:00
TimelineViewport.prototype={__proto__:tr.b.EventTarget.prototype,setWhenPossible:function(fn){this.pendingSetFunction_=fn;},get isAttachedToDocumentOrInTestMode(){if(this.parentEl_===undefined)
return;return tr.ui.b.isElementAttachedToDocument(this.parentEl_);},onResize_:function(){this.dispatchChangeEvent();},checkForAttach_:function(){if(!this.isAttachedToDocumentOrInTestMode||this.clientWidth==0)
return;if(!this.iframe_){this.iframe_=document.createElement('iframe');this.iframe_.style.cssText='position:absolute;width:100%;height:0;border:0;visibility:hidden;';this.parentEl_.appendChild(this.iframe_);this.iframe_.contentWindow.addEventListener('resize',this.onResize_);}
var curSize=this.parentEl_.clientWidth+'x'+
this.parentEl_.clientHeight;if(this.pendingSetFunction_){this.lastSize_=curSize;try{this.pendingSetFunction_();}catch(ex){console.log('While running setWhenPossible:',ex.message?ex.message+'\n'+ex.stack:ex.stack);}
this.pendingSetFunction_=undefined;}
window.clearInterval(this.checkForAttachInterval_);this.checkForAttachInterval_=undefined;},dispatchChangeEvent:function(){tr.b.dispatchSimpleEvent(this,'change');},detach:function(){if(this.checkForAttachInterval_){window.clearInterval(this.checkForAttachInterval_);this.checkForAttachInterval_=undefined;}
if(this.iframe_){this.iframe_.removeEventListener('resize',this.onResize_);this.parentEl_.removeChild(this.iframe_);}},initAnimationController_:function(){this.dtAnimationController_=new tr.ui.b.AnimationController();this.dtAnimationController_.addEventListener('didtick',function(e){this.onCurentDisplayTransformChange_(e.oldTargetState);}.bind(this));var that=this;this.dtAnimationController_.target={get panX(){return that.currentDisplayTransform_.panX;},set panX(panX){that.currentDisplayTransform_.panX=panX;},get panY(){return that.currentDisplayTransform_.panY;},set panY(panY){that.currentDisplayTransform_.panY=panY;},get scaleX(){return that.currentDisplayTransform_.scaleX;},set scaleX(scaleX){that.currentDisplayTransform_.scaleX=scaleX;},cloneAnimationState:function(){return that.currentDisplayTransform_.clone();},xPanWorldPosToViewPos:function(xWorld,xView){that.currentDisplayTransform_.xPanWorldPosToViewPos(xWorld,xView,that.modelTrackContainer_.canvas.clientWidth);}};},get currentDisplayTransform(){return this.currentDisplayTransform_;},setDisplayTransformImmediately:function(displayTransform){this.dtAnimationController_.cancelActiveAnimation();var oldDisplayTransform=this.dtAnimationController_.target.cloneAnimationState();this.currentDisplayTransform_.set(displayTransform);this.onCurentDisplayTransformChange_(oldDisplayTransform);},queueDisplayTransformAnimation:function(animation){if(!(animation instanceof tr.ui.b.Animation))
throw new Error('animation must be instanceof tr.ui.b.Animation');this.dtAnimationController_.queueAnimation(animation);},onCurentDisplayTransformChange_:function(oldDisplayTransform){if(this.modelTrackContainer_){this.currentDisplayTransform.panY=tr.b.clamp(this.currentDisplayTransform.panY,0,this.modelTrackContainer_.scrollHeight-
this.modelTrackContainer_.clientHeight);}
var changed=!this.currentDisplayTransform.equals(oldDisplayTransform);var yChanged=this.currentDisplayTransform.panY!==oldDisplayTransform.panY;if(yChanged)
this.modelTrackContainer_.scrollTop=this.currentDisplayTransform.panY;if(changed)
this.dispatchChangeEvent();},onModelTrackControllerScroll_:function(e){if(this.dtAnimationController_.activeAnimation& & this.dtAnimationController_.activeAnimation.affectsPanY)
this.dtAnimationController_.cancelActiveAnimation();var panY=this.modelTrackContainer_.scrollTop;this.currentDisplayTransform_.panY=panY;},get modelTrackContainer(){return this.modelTrackContainer_;},set modelTrackContainer(m){if(this.modelTrackContainer_)
this.modelTrackContainer_.removeEventListener('scroll',this.onModelTrackControllerScroll_);this.modelTrackContainer_=m;this.modelTrackContainer_.addEventListener('scroll',this.onModelTrackControllerScroll_);},get showFlowEvents(){return this.showFlowEvents_;},set showFlowEvents(showFlowEvents){this.showFlowEvents_=showFlowEvents;this.dispatchChangeEvent();},get highlightVSync(){return this.highlightVSync_;},set highlightVSync(highlightVSync){this.highlightVSync_=highlightVSync;this.dispatchChangeEvent();},get highDetails(){return this.highDetails_;},set highDetails(highDetails){this.highDetails_=highDetails;this.dispatchChangeEvent();},get gridEnabled(){return this.gridEnabled_;},set gridEnabled(enabled){if(this.gridEnabled_==enabled)
return;this.gridEnabled_=enabled&&true; this.dispatchChangeEvent();},get gridTimebase(){return this.gridTimebase_;},set gridTimebase(timebase){if(this.gridTimebase_==timebase)
2015-06-18 08:27:29 -06:00
return;this.gridTimebase_=timebase;this.dispatchChangeEvent();},get gridStep(){return this.gridStep_;},get interestRange(){return this.interestRange_;},drawMajorMarkLines:function(ctx){ctx.save();ctx.translate((Math.round(ctx.lineWidth)%2)/2,0);ctx.beginPath();for(var idx in this.majorMarkPositions){var x=Math.floor(this.majorMarkPositions[idx]);tr.ui.b.drawLine(ctx,x,0,x,ctx.canvas.height);}
2015-06-14 13:52:57 -06:00
ctx.strokeStyle='#ddd';ctx.stroke();ctx.restore();},drawGridLines:function(ctx,viewLWorld,viewRWorld){if(!this.gridEnabled)
2015-06-18 08:27:29 -06:00
return;var dt=this.currentDisplayTransform;var x=this.gridTimebase;ctx.save();ctx.translate((Math.round(ctx.lineWidth)%2)/2,0);ctx.beginPath();while(x< viewRWorld ) { if ( x > =viewLWorld){var vx=Math.floor(dt.xWorldToView(x));tr.ui.b.drawLine(ctx,vx,0,vx,ctx.canvas.height);}
2015-06-14 13:52:57 -06:00
x+=this.gridStep;}
2015-06-18 08:27:29 -06:00
ctx.strokeStyle='rgba(255, 0, 0, 0.25)';ctx.stroke();ctx.restore();},rebuildEventToTrackMap:function(){this.eventToTrackMap_=new tr.ui.tracks.EventToTrackMap();this.modelTrackContainer_.addEventsToTrackMap(this.eventToTrackMap_);},rebuildContainerToTrackMap:function(){this.containerToTrackMap.clear();this.modelTrackContainer_.addContainersToTrackMap(this.containerToTrackMap);},trackForEvent:function(event){return this.eventToTrackMap_[event.guid];}};return{TimelineViewport:TimelineViewport};});'use strict';tr.exportTo('tr.ui',function(){var kDefaultPanAnimatoinDurationMs=100.0;function TimelineDisplayTransformPanAnimation(deltaX,deltaY,opt_durationMs){this.deltaX=deltaX;this.deltaY=deltaY;if(opt_durationMs===undefined)
2015-06-14 13:52:57 -06:00
this.durationMs=kDefaultPanAnimatoinDurationMs;else
this.durationMs=opt_durationMs;this.startPanX=undefined;this.startPanY=undefined;this.startTimeMs=undefined;}
TimelineDisplayTransformPanAnimation.prototype={__proto__:tr.ui.b.Animation.prototype,get affectsPanY(){return this.deltaY!==0;},canTakeOverFor:function(existingAnimation){return existingAnimation instanceof TimelineDisplayTransformPanAnimation;},takeOverFor:function(existing,timestamp,target){var remainingDeltaXOnExisting=existing.goalPanX-target.panX;var remainingDeltaYOnExisting=existing.goalPanY-target.panY;var remainingTimeOnExisting=timestamp-(existing.startTimeMs+existing.durationMs);remainingTimeOnExisting=Math.max(remainingTimeOnExisting,0);this.deltaX+=remainingDeltaXOnExisting;this.deltaY+=remainingDeltaYOnExisting;this.durationMs+=remainingTimeOnExisting;},start:function(timestamp,target){this.startTimeMs=timestamp;this.startPanX=target.panX;this.startPanY=target.panY;},tick:function(timestamp,target){var percentDone=(timestamp-this.startTimeMs)/this.durationMs;percentDone=tr.b.clamp(percentDone,0,1);target.panX=tr.b.lerp(percentDone,this.startPanX,this.goalPanX);if(this.affectsPanY)
target.panY=tr.b.lerp(percentDone,this.startPanY,this.goalPanY);return timestamp>=this.startTimeMs+this.durationMs;},get goalPanX(){return this.startPanX+this.deltaX;},get goalPanY(){return this.startPanY+this.deltaY;}};function TimelineDisplayTransformZoomToAnimation(goalFocalPointXWorld,goalFocalPointXView,goalFocalPointY,zoomInRatioX,opt_durationMs){this.goalFocalPointXWorld=goalFocalPointXWorld;this.goalFocalPointXView=goalFocalPointXView;this.goalFocalPointY=goalFocalPointY;this.zoomInRatioX=zoomInRatioX;if(opt_durationMs===undefined)
this.durationMs=kDefaultPanAnimatoinDurationMs;else
this.durationMs=opt_durationMs;this.startTimeMs=undefined;this.startScaleX=undefined;this.goalScaleX=undefined;this.startPanY=undefined;}
TimelineDisplayTransformZoomToAnimation.prototype={__proto__:tr.ui.b.Animation.prototype,get affectsPanY(){return this.startPanY!=this.goalFocalPointY;},canTakeOverFor:function(existingAnimation){return false;},takeOverFor:function(existingAnimation,timestamp,target){this.goalScaleX=target.scaleX*this.zoomInRatioX;},start:function(timestamp,target){this.startTimeMs=timestamp;this.startScaleX=target.scaleX;this.goalScaleX=this.zoomInRatioX*target.scaleX;this.startPanY=target.panY;},tick:function(timestamp,target){var percentDone=(timestamp-this.startTimeMs)/this.durationMs;percentDone=tr.b.clamp(percentDone,0,1);target.scaleX=tr.b.lerp(percentDone,this.startScaleX,this.goalScaleX);if(this.affectsPanY){target.panY=tr.b.lerp(percentDone,this.startPanY,this.goalFocalPointY);}
2015-06-18 08:27:29 -06:00
target.xPanWorldPosToViewPos(this.goalFocalPointXWorld,this.goalFocalPointXView);return timestamp>=this.startTimeMs+this.durationMs;}};return{TimelineDisplayTransformPanAnimation:TimelineDisplayTransformPanAnimation,TimelineDisplayTransformZoomToAnimation:TimelineDisplayTransformZoomToAnimation};});'use strict';tr.exportTo('tr.c',function(){var constants={HEADING_WIDTH:250};return{constants:constants};});'use strict';tr.exportTo('tr.ui.b',function(){var constants=tr.c.constants;function TimingTool(viewport,targetElement){this.viewport_=viewport;this.onMouseMove_=this.onMouseMove_.bind(this);this.onDblClick_=this.onDblClick_.bind(this);this.targetElement_=targetElement;this.isMovingLeftEdge_=false;};TimingTool.prototype={onEnterTiming:function(e){this.targetElement_.addEventListener('mousemove',this.onMouseMove_);this.targetElement_.addEventListener('dblclick',this.onDblClick_);},onBeginTiming:function(e){if(!this.isTouchPointInsideTrackBounds_(e.clientX,e.clientY))
2015-06-14 13:52:57 -06:00
return;var pt=this.getSnappedToEventPosition_(e);this.mouseDownAt_(pt.x,pt.y);this.updateSnapIndicators_(pt);},updateSnapIndicators_:function(pt){if(!pt.snapped)
return;var ir=this.viewport_.interestRange;if(ir.min===pt.x)
2015-06-18 08:27:29 -06:00
ir.leftSnapIndicator=new tr.ui.SnapIndicator(pt.y,pt.height);if(ir.max===pt.x)
ir.rightSnapIndicator=new tr.ui.SnapIndicator(pt.y,pt.height);},onUpdateTiming:function(e){var pt=this.getSnappedToEventPosition_(e);this.mouseMoveAt_(pt.x,pt.y,true);this.updateSnapIndicators_(pt);},onEndTiming:function(e){this.mouseUp_();},onExitTiming:function(e){this.targetElement_.removeEventListener('mousemove',this.onMouseMove_);this.targetElement_.removeEventListener('dblclick',this.onDblClick_);},onMouseMove_:function(e){if(e.button)
2015-06-14 13:52:57 -06:00
return;var worldX=this.getWorldXFromEvent_(e);this.mouseMoveAt_(worldX,e.clientY,false);},onDblClick_:function(e){console.error('not implemented');},isTouchPointInsideTrackBounds_:function(clientX,clientY){if(!this.viewport_||!this.viewport_.modelTrackContainer||!this.viewport_.modelTrackContainer.canvas)
return false;var canvas=this.viewport_.modelTrackContainer.canvas;var canvasRect=canvas.getBoundingClientRect();if(clientX>=canvasRect.left& & clientX< =canvasRect.right& & clientY>=canvasRect.top& & clientY< =canvasRect.bottom)
return true;return false;},mouseDownAt_:function(worldX,y){var ir=this.viewport_.interestRange;var dt=this.viewport_.currentDisplayTransform;var pixelRatio=window.devicePixelRatio||1;var nearnessThresholdWorld=dt.xViewVectorToWorld(6*pixelRatio);if(ir.isEmpty){ir.setMinAndMax(worldX,worldX);ir.rightSelected=true;this.isMovingLeftEdge_=false;return;}
if(Math.abs(worldX-ir.min)< nearnessThresholdWorld ) { ir . leftSelected = true;ir.min=worldX;this.isMovingLeftEdge_=true;return;}
if(Math.abs(worldX-ir.max)< nearnessThresholdWorld ) { ir . rightSelected = true;ir.max=worldX;this.isMovingLeftEdge_=false;return;}
ir.setMinAndMax(worldX,worldX);ir.rightSelected=true;this.isMovingLeftEdge_=false;},mouseMoveAt_:function(worldX,y,mouseDown){var ir=this.viewport_.interestRange;if(mouseDown){this.updateMovingEdge_(worldX);return;}
var ir=this.viewport_.interestRange;var dt=this.viewport_.currentDisplayTransform;var pixelRatio=window.devicePixelRatio||1;var nearnessThresholdWorld=dt.xViewVectorToWorld(6*pixelRatio);if(Math.abs(worldX-ir.min)< nearnessThresholdWorld ) { ir . leftSelected = true;ir.rightSelected=false;return;}
if(Math.abs(worldX-ir.max)< nearnessThresholdWorld ) { ir . leftSelected = false;ir.rightSelected=true;return;}
ir.leftSelected=false;ir.rightSelected=false;return;},updateMovingEdge_:function(newWorldX){var ir=this.viewport_.interestRange;var a=ir.min;var b=ir.max;if(this.isMovingLeftEdge_)
a=newWorldX;else
b=newWorldX;if(a< =b)
ir.setMinAndMax(a,b);else
ir.setMinAndMax(b,a);if(ir.min==newWorldX){this.isMovingLeftEdge_=true;ir.leftSelected=true;ir.rightSelected=false;}else{this.isMovingLeftEdge_=false;ir.leftSelected=false;ir.rightSelected=true;}},mouseUp_:function(){var dt=this.viewport_.currentDisplayTransform;var ir=this.viewport_.interestRange;ir.leftSelected=false;ir.rightSelected=false;var pixelRatio=window.devicePixelRatio||1;var minWidthValue=dt.xViewVectorToWorld(2*pixelRatio);if(ir.range< minWidthValue )
ir.reset();},getWorldXFromEvent_:function(e){var pixelRatio=window.devicePixelRatio||1;var canvas=this.viewport_.modelTrackContainer.canvas;var worldOffset=canvas.getBoundingClientRect().left;var viewX=(e.clientX-worldOffset)*pixelRatio;return this.viewport_.currentDisplayTransform.xViewToWorld(viewX);},getSnappedToEventPosition_:function(e){var pixelRatio=window.devicePixelRatio||1;var EVENT_SNAP_RANGE=16*pixelRatio;var modelTrackContainer=this.viewport_.modelTrackContainer;var modelTrackContainerRect=modelTrackContainer.getBoundingClientRect();var viewport=this.viewport_;var dt=viewport.currentDisplayTransform;var worldMaxDist=dt.xViewVectorToWorld(EVENT_SNAP_RANGE);var worldX=this.getWorldXFromEvent_(e);var mouseY=e.clientY;var selection=new tr.c.Selection();modelTrackContainer.addClosestEventToSelection(worldX,worldMaxDist,mouseY,mouseY,selection);if(!selection.length){modelTrackContainer.addClosestEventToSelection(worldX,worldMaxDist,modelTrackContainerRect.top,modelTrackContainerRect.bottom,selection);}
var minDistX=worldMaxDist;var minDistY=Infinity;var pixWidth=dt.xViewVectorToWorld(1);var result={x:worldX,y:mouseY-modelTrackContainerRect.top,height:0,snapped:false};var eventBounds=new tr.b.Range();for(var i=0;i< selection.length ; i + + ) { var event = selection[i];var track = viewport.trackForEvent(event);var trackRect = track.getBoundingClientRect();eventBounds.reset();event.addBoundsToRange(eventBounds);var eventX ; if ( Math . abs ( eventBounds . min-worldX ) < Math . abs ( eventBounds . max-worldX ) ) { eventX = eventBounds.min;}else{eventX=eventBounds.max;}
var distX=eventX-worldX;var eventY=trackRect.top;var eventHeight=trackRect.height;var distY=Math.abs(eventY+eventHeight/2-mouseY);if((distX< =minDistX||Math.abs(distX-minDistX)< pixWidth ) & & distY < minDistY ) { minDistX = distX;minDistY=distY;result.x=eventX;result.y=eventY+
modelTrackContainer.scrollTop-modelTrackContainerRect.top;result.height=eventHeight;result.snapped=true;}}
2015-06-18 08:27:29 -06:00
return result;}};return{TimingTool:TimingTool};});'use strict';tr.exportTo('tr.ui.b',function(){var ContainerThatDecoratesItsChildren=tr.ui.b.define('div');ContainerThatDecoratesItsChildren.prototype={__proto__:HTMLUnknownElement.prototype,decorate:function(){this.observer_=new WebKitMutationObserver(this.didMutate_.bind(this));this.observer_.observe(this,{childList:true});Object.defineProperty(this,'textContent',{get:undefined,set:this.onSetTextContent_});},appendChild:function(x){HTMLUnknownElement.prototype.appendChild.call(this,x);this.didMutate_(this.observer_.takeRecords());},insertBefore:function(x,y){HTMLUnknownElement.prototype.insertBefore.call(this,x,y);this.didMutate_(this.observer_.takeRecords());},removeChild:function(x){HTMLUnknownElement.prototype.removeChild.call(this,x);this.didMutate_(this.observer_.takeRecords());},replaceChild:function(x,y){HTMLUnknownElement.prototype.replaceChild.call(this,x,y);this.didMutate_(this.observer_.takeRecords());},onSetTextContent_:function(textContent){if(textContent!='')
2015-06-14 13:52:57 -06:00
throw new Error('textContent can only be set to \'\'.');this.clear();},clear:function(){while(this.lastChild)
HTMLUnknownElement.prototype.removeChild.call(this,this.lastChild);this.didMutate_(this.observer_.takeRecords());},didMutate_:function(records){this.beginDecorating_();for(var i=0;i< records.length ; i + + ) { var addedNodes = records[i].addedNodes;if(addedNodes){for(var j = 0;j<addedNodes.length;j++)
this.decorateChild_(addedNodes[j]);}
var removedNodes=records[i].removedNodes;if(removedNodes){for(var j=0;j< removedNodes.length ; j + + ) { this . undecorateChild_ ( removedNodes [ j ] ) ; } } }
2015-06-18 08:27:29 -06:00
this.doneDecoratingForNow_();},decorateChild_:function(child){throw new Error('Not implemented');},undecorateChild_:function(child){throw new Error('Not implemented');},beginDecorating_:function(){},doneDecoratingForNow_:function(){}};return{ContainerThatDecoratesItsChildren:ContainerThatDecoratesItsChildren};});'use strict';tr.exportTo('tr.ui.tracks',function(){var Track=tr.ui.b.define('track',tr.ui.b.ContainerThatDecoratesItsChildren);Track.prototype={__proto__:tr.ui.b.ContainerThatDecoratesItsChildren.prototype,decorate:function(viewport){tr.ui.b.ContainerThatDecoratesItsChildren.prototype.decorate.call(this);if(viewport===undefined)
throw new Error('viewport is required when creating a Track.');this.viewport_=viewport;this.classList.add('track');},get viewport(){return this.viewport_;},get drawingContainer(){var cur=this;while(cur){if(cur instanceof tr.ui.tracks.DrawingContainer)
2015-06-14 13:52:57 -06:00
return cur;cur=cur.parentElement;}
return undefined;},get eventContainer(){},invalidateDrawingContainer:function(){var dc=this.drawingContainer;if(dc)
dc.invalidate();},context:function(){if(!this.parentNode)
return undefined;if(!this.parentNode.context)
throw new Error('Parent container does not support context() method.');return this.parentNode.context();},decorateChild_:function(childTrack){},undecorateChild_:function(childTrack){if(childTrack.detach)
childTrack.detach();},updateContents_:function(){},drawTrack:function(type){var ctx=this.context();var pixelRatio=window.devicePixelRatio||1;var bounds=this.getBoundingClientRect();var canvasBounds=ctx.canvas.getBoundingClientRect();ctx.save();ctx.translate(0,pixelRatio*(bounds.top-canvasBounds.top));var dt=this.viewport.currentDisplayTransform;var viewLWorld=dt.xViewToWorld(0);var viewRWorld=dt.xViewToWorld(bounds.width*pixelRatio);this.draw(type,viewLWorld,viewRWorld);ctx.restore();},draw:function(type,viewLWorld,viewRWorld){},addEventsToTrackMap:function(eventToTrackMap){},addContainersToTrackMap:function(containerToTrackMap){},addIntersectingEventsInRangeToSelection:function(loVX,hiVX,loVY,hiVY,selection){var pixelRatio=window.devicePixelRatio||1;var dt=this.viewport.currentDisplayTransform;var viewPixWidthWorld=dt.xViewVectorToWorld(1);var loWX=dt.xViewToWorld(loVX*pixelRatio);var hiWX=dt.xViewToWorld(hiVX*pixelRatio);var clientRect=this.getBoundingClientRect();var a=Math.max(loVY,clientRect.top);var b=Math.min(hiVY,clientRect.bottom);if(a>b)
return;this.addIntersectingEventsInRangeToSelectionInWorldSpace(loWX,hiWX,viewPixWidthWorld,selection);},addIntersectingEventsInRangeToSelectionInWorldSpace:function(loWX,hiWX,viewPixWidthWorld,selection){},addClosestEventToSelection:function(worldX,worldMaxDist,loY,hiY,selection){},addClosestInstantEventToSelection:function(instantEvents,worldX,worldMaxDist,selection){var instantEvent=tr.b.findClosestElementInSortedArray(instantEvents,function(x){return x.start;},worldX,worldMaxDist);if(!instantEvent)
2015-06-18 08:27:29 -06:00
return;selection.push(instantEvent);}};return{Track:Track};});'use strict';tr.exportTo('tr.ui.tracks',function(){var DrawType={GENERAL_EVENT:1,INSTANT_EVENT:2,BACKGROUND:3,GRID:4,FLOW_ARROWS:5,MARKERS:6,HIGHLIGHTS:7,ANNOTATIONS:8};var DrawingContainer=tr.ui.b.define('drawing-container',tr.ui.tracks.Track);DrawingContainer.prototype={__proto__:tr.ui.tracks.Track.prototype,decorate:function(viewport){tr.ui.tracks.Track.prototype.decorate.call(this,viewport);this.classList.add('drawing-container');this.canvas_=document.createElement('canvas');this.canvas_.className='drawing-container-canvas';this.canvas_.style.left=tr.c.constants.HEADING_WIDTH+'px';this.appendChild(this.canvas_);this.ctx_=this.canvas_.getContext('2d');this.viewportChange_=this.viewportChange_.bind(this);this.viewport.addEventListener('change',this.viewportChange_);},get canvas(){return this.canvas_;},context:function(){return this.ctx_;},viewportChange_:function(){this.invalidate();},invalidate:function(){if(this.rafPending_)
return;this.rafPending_=true;tr.b.requestPreAnimationFrame(this.preDraw_,this);},preDraw_:function(){this.rafPending_=false;this.updateCanvasSizeIfNeeded_();tr.b.requestAnimationFrameInThisFrameIfPossible(this.draw_,this);},draw_:function(){this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height);var typesToDraw=[DrawType.BACKGROUND,DrawType.HIGHLIGHTS,DrawType.GRID,DrawType.INSTANT_EVENT,DrawType.GENERAL_EVENT,DrawType.MARKERS,DrawType.ANNOTATIONS,DrawType.FLOW_ARROWS];for(var idx in typesToDraw){for(var i=0;i< this.children.length ; + + i ) { if ( ! ( this . children [ i ] instanceof tr . ui . tracks . Track ) )
2015-06-14 13:52:57 -06:00
continue;this.children[i].drawTrack(typesToDraw[idx]);}}
var pixelRatio=window.devicePixelRatio||1;var bounds=this.canvas_.getBoundingClientRect();var dt=this.viewport.currentDisplayTransform;var viewLWorld=dt.xViewToWorld(0);var viewRWorld=dt.xViewToWorld(bounds.width*pixelRatio);this.viewport.drawGridLines(this.ctx_,viewLWorld,viewRWorld);},updateCanvasSizeIfNeeded_:function(){var visibleChildTracks=tr.b.asArray(this.children).filter(this.visibleFilter_);var thisBounds=this.getBoundingClientRect();var firstChildTrackBounds=visibleChildTracks[0].getBoundingClientRect();var lastChildTrackBounds=visibleChildTracks[visibleChildTracks.length-1].getBoundingClientRect();var innerWidth=firstChildTrackBounds.width-
tr.c.constants.HEADING_WIDTH;var innerHeight=lastChildTrackBounds.bottom-firstChildTrackBounds.top;var pixelRatio=window.devicePixelRatio||1;if(this.canvas_.width!=innerWidth*pixelRatio){this.canvas_.width=innerWidth*pixelRatio;this.canvas_.style.width=innerWidth+'px';}
2015-06-18 08:27:29 -06:00
if(this.canvas_.height!=innerHeight*pixelRatio){this.canvas_.height=innerHeight*pixelRatio;this.canvas_.style.height=innerHeight+'px';}},visibleFilter_:function(element){if(!(element instanceof tr.ui.tracks.Track))
return false;return window.getComputedStyle(element).display!=='none';},addClosestEventToSelection:function(worldX,worldMaxDist,loY,hiY,selection){for(var i=0;i< this.children.length ; + + i ) { if ( ! ( this . children [ i ] instanceof tr . ui . tracks . Track ) )
2015-06-14 13:52:57 -06:00
continue;var trackClientRect=this.children[i].getBoundingClientRect();var a=Math.max(loY,trackClientRect.top);var b=Math.min(hiY,trackClientRect.bottom);if(a< =b){this.children[i].addClosestEventToSelection(worldX,worldMaxDist,loY,hiY,selection);}}
2015-06-18 08:27:29 -06:00
tr.ui.tracks.Track.prototype.addClosestEventToSelection.apply(this,arguments);},addEventsToTrackMap:function(eventToTrackMap){for(var i=0;i< this.children.length ; + + i ) { if ( ! ( this . children [ i ] instanceof tr . ui . tracks . Track ) )
continue;this.children[i].addEventsToTrackMap(eventToTrackMap);}},addContainersToTrackMap:function(containerToTrackMap){for(var i=0;i< this.children.length ; + + i ) { if ( ! ( this . children [ i ] instanceof tr . ui . tracks . Track ) )
continue;this.children[i].addContainersToTrackMap(containerToTrackMap);}}};return{DrawingContainer:DrawingContainer,DrawType:DrawType};});'use strict';tr.exportTo('tr.ui.tracks',function(){function Highlighter(viewport){if(viewport===undefined){throw new Error('viewport must be provided');}
this.viewport_=viewport;};Highlighter.prototype={__proto__:Object.prototype,processModel:function(model){throw new Error('processModel implementation missing');},drawHighlight:function(ctx,dt,viewLWorld,viewRWorld,viewHeight){throw new Error('drawHighlight implementation missing');}};var options=new tr.b.ExtensionRegistryOptions(tr.b.BASIC_REGISTRY_MODE);options.defaultMetadata={};options.mandatoryBaseClass=Highlighter;tr.b.decorateExtensionRegistry(Highlighter,options);return{Highlighter:Highlighter};});'use strict';tr.exportTo('tr.ui.tracks',function(){var Task=tr.b.Task;var ContainerTrack=tr.ui.b.define('container-track',tr.ui.tracks.Track);ContainerTrack.prototype={__proto__:tr.ui.tracks.Track.prototype,decorate:function(viewport){tr.ui.tracks.Track.prototype.decorate.call(this,viewport);},detach:function(){this.textContent='';},get tracks_(){var tracks=[];for(var i=0;i< this.children.length ; i + + ) { if ( this . children [ i ] . classList . contains ( ' track ' ) )
2015-06-14 13:52:57 -06:00
tracks.push(this.children[i]);}
2015-06-18 08:27:29 -06:00
return tracks;},drawTrack:function(type){for(var i=0;i< this.children.length ; + + i ) { if ( ! ( this . children [ i ] instanceof tr . ui . tracks . Track ) )
2015-06-14 13:52:57 -06:00
continue;this.children[i].drawTrack(type);}},addIntersectingEventsInRangeToSelection:function(loVX,hiVX,loY,hiY,selection){for(var i=0;i< this.tracks_.length ; i + + ) { var trackClientRect = this.tracks_[i].getBoundingClientRect();var a = Math.max(loY,trackClientRect.top);var b = Math.min(hiY,trackClientRect.bottom);if(a<=b)
this.tracks_[i].addIntersectingEventsInRangeToSelection(loVX,hiVX,loY,hiY,selection);}
2015-06-18 08:27:29 -06:00
tr.ui.tracks.Track.prototype.addIntersectingEventsInRangeToSelection.apply(this,arguments);},addEventsToTrackMap:function(eventToTrackMap){for(var i=0;i< this.children.length ; + + i )
2015-06-14 13:52:57 -06:00
this.children[i].addEventsToTrackMap(eventToTrackMap);},addAllEventsMatchingFilterToSelection:function(filter,selection){for(var i=0;i< this.tracks_.length ; i + + )
this.tracks_[i].addAllEventsMatchingFilterToSelection(filter,selection);},addAllEventsMatchingFilterToSelectionAsTask:function(filter,selection){var task=new Task();for(var i=0;i< this.tracks_.length ; i + + ) { task . subTask ( function ( i ) { return function ( ) { this . tracks_ [ i ] . addAllEventsMatchingFilterToSelection ( filter , selection ) ; } } ( i ) , this ) ; }
return task;},addClosestEventToSelection:function(worldX,worldMaxDist,loY,hiY,selection){for(var i=0;i< this.tracks_.length ; i + + ) { var trackClientRect = this.tracks_[i].getBoundingClientRect();var a = Math.max(loY,trackClientRect.top);var b = Math.min(hiY,trackClientRect.bottom);if(a<=b){this.tracks_[i].addClosestEventToSelection(worldX,worldMaxDist,loY,hiY,selection);}}
2015-06-18 08:27:29 -06:00
tr.ui.tracks.Track.prototype.addClosestEventToSelection.apply(this,arguments);}};return{ContainerTrack:ContainerTrack};});'use strict';tr.exportTo('tr.ui.tracks',function(){function ChartAxis(opt_min,opt_max){this.guid_=tr.b.GUID.allocate();this.bounds=new tr.b.Range();if(opt_min!==undefined)
2015-06-14 13:52:57 -06:00
this.bounds.addValue(opt_min);if(opt_max!==undefined)
this.bounds.addValue(opt_max);};ChartAxis.prototype={get guid(){return this.guid_;},valueToUnitRange:function(value){if(this.bounds.isEmpty)
throw new Error('Chart axis bounds are empty');var bounds=this.bounds;if(bounds.range===0)
return 0;return(value-bounds.min)/bounds.range;},autoSetFromSeries:function(series,opt_config){var range=new tr.b.Range();series.forEach(function(s){range.addRange(s.range);},this);this.autoSetFromRange(range,opt_config);},autoSetFromRange:function(range,opt_config){if(range.isEmpty)
return;var bounds=this.bounds;if(bounds.isEmpty){bounds.addRange(range);return;}
if(!opt_config)
return;var useRangeMin=(opt_config.expandMin&&range.min<bounds.min||opt_config.shrinkMin&&range.min>bounds.min); var useRangeMax=(opt_config.expandMax&&range.max>bounds.max||opt_config.shrinkMax&&range.max<bounds.max); if(!useRangeMin& & !useRangeMax)
return;if(useRangeMin&&useRangeMax){bounds.min=range.min; bounds.max=range.max;return;}
if(useRangeMin){bounds.min=Math.min(range.min,bounds.max);}else{bounds.max=Math.max(range.max,bounds.min);}}};return{ChartAxis:ChartAxis};});'use strict';tr.exportTo('tr.model',function(){var SelectableItem=tr.model.SelectableItem;var SelectionState=tr.model.SelectionState;function ProxySelectableItem(modelItem){SelectableItem.call(this,modelItem);};ProxySelectableItem.prototype={__proto__:SelectableItem.prototype,get selectionState(){var modelItem=this.modelItem_;if(modelItem===undefined)
2015-06-18 08:27:29 -06:00
return SelectionState.NONE;return modelItem.selectionState;}};return{ProxySelectableItem:ProxySelectableItem};});'use strict';tr.exportTo('tr.ui.tracks',function(){function ChartPoint(modelItem,x,y,opt_yBase){tr.model.ProxySelectableItem.call(this,modelItem);this.x=x;this.y=y;this.yBase=opt_yBase;};ChartPoint.prototype={__proto__:tr.model.ProxySelectableItem.prototype};return{ChartPoint:ChartPoint};});'use strict';tr.exportTo('tr.ui.tracks',function(){var DOWN_ARROW=String.fromCharCode(0x25BE);var RIGHT_ARROW=String.fromCharCode(0x25B8);var HeadingTrack=tr.ui.b.define('heading-track',tr.ui.tracks.Track);HeadingTrack.prototype={__proto__:tr.ui.tracks.Track.prototype,decorate:function(viewport){tr.ui.tracks.Track.prototype.decorate.call(this,viewport);this.classList.add('heading-track');this.headingDiv_=document.createElement('heading');this.headingDiv_.style.width=tr.c.constants.HEADING_WIDTH+'px';this.headingDiv_.addEventListener('click',this.onHeadingDivClicked_.bind(this));this.heading_='';this.expanded_=undefined;this.selectionGenerator_=undefined;this.updateContents_();},get heading(){return this.heading_;},set heading(text){this.heading_=text;this.updateContents_();},set tooltip(text){this.headingDiv_.title=text;},set selectionGenerator(generator){this.selectionGenerator_=generator;this.updateContents_();},get expanded(){return this.expanded_;},set expanded(expanded){expanded=expanded;if(this.expanded_==expanded)
2015-06-14 13:52:57 -06:00
return;this.expanded_=expanded;this.expandedStateChanged_();},expandedStateChanged_:function(){this.updateHeadigDiv_();},onHeadingDivClicked_:function(){var e=new Event('heading-clicked',{'bubbles':true});this.dispatchEvent(e);},updateContents_:function(){this.updateHeadigDiv_();},updateHeadigDiv_:function(){this.headingDiv_.innerHTML='';var span=document.createElement('span');span.classList.add('heading-arrow');if(this.expanded===true)
span.textContent=DOWN_ARROW;else if(this.expanded===false)
span.textContent=RIGHT_ARROW;else
2015-06-18 08:27:29 -06:00
span.textContent='';this.headingDiv_.appendChild(span);if(this.selectionGenerator_){this.headingLink_=document.createElement('tr-ui-a-analysis-link');this.headingLink_.selection=this.selectionGenerator_;this.headingLink_.textContent='';this.headingDiv_.appendChild(this.headingLink_);this.headingLink_.appendChild(document.createTextNode(this.heading_));}else{span=document.createElement('span');span.textContent=this.heading_;this.headingDiv_.appendChild(span);}
this.appendChild(this.headingDiv_);},draw:function(type,viewLWorld,viewRWorld){throw new Error('draw implementation missing');}};return{HeadingTrack:HeadingTrack};});'use strict';tr.exportTo('tr.ui.tracks',function(){var EventPresenter=tr.ui.b.EventPresenter;var SelectionState=tr.model.SelectionState;var ChartSeriesType={LINE:0,AREA:1};var DEFAULT_RENDERING_CONFIG={chartType:ChartSeriesType.LINE,selectedPointSize:4,unselectedPointSize:3,colorId:0,lineWidth:1,skipDistance:1,unselectedPointDensityTransparent:0.10,unselectedPointDensityOpaque:0.05,backgroundOpacity:0.5};var LAST_POINT_WIDTH=16;var ChartSeriesComponent={BACKGROUND:0,LINE:1,DOTS:2};function ChartSeries(points,axis,opt_renderingConfig){this.points=points;this.axis=axis;this.useRenderingConfig_(opt_renderingConfig);}
2015-06-14 13:52:57 -06:00
ChartSeries.prototype={useRenderingConfig_:function(opt_renderingConfig){var config=opt_renderingConfig||{};tr.b.iterItems(DEFAULT_RENDERING_CONFIG,function(key,defaultValue){var value=config[key];if(value===undefined)
value=defaultValue;this[key+'_']=value;},this);this.topPadding=this.bottomPadding=Math.max(this.selectedPointSize_,this.unselectedPointSize_)/2;},get range(){var range=new tr.b.Range();this.points.forEach(function(point){range.addValue(point.y);},this);return range;},draw:function(ctx,transform,highDetails){if(this.points===undefined||this.points.length===0)
return;if(this.chartType_===ChartSeriesType.AREA){this.drawComponent_(ctx,transform,ChartSeriesComponent.BACKGROUND,highDetails);}
if(this.chartType_===ChartSeriesType.LINE||highDetails){this.drawComponent_(ctx,transform,ChartSeriesComponent.LINE,highDetails);}
this.drawComponent_(ctx,transform,ChartSeriesComponent.DOTS,highDetails);},drawComponent_:function(ctx,transform,component,highDetails){var extraPixels=0;if(component===ChartSeriesComponent.DOTS){extraPixels=Math.max(this.selectedPointSize_,this.unselectedPointSize_);}
var leftViewX=transform.leftViewX-extraPixels*transform.pixelRatio;var rightViewX=transform.rightViewX+
extraPixels*transform.pixelRatio;var leftTimestamp=transform.leftTimestamp-extraPixels;var rightTimestamp=transform.rightTimestamp+extraPixels;var firstVisibleIndex=tr.b.findLowIndexInSortedArray(this.points,function(point){return point.x;},leftTimestamp);var lastVisibleIndex=tr.b.findLowIndexInSortedArray(this.points,function(point){return point.x;},rightTimestamp);if(lastVisibleIndex>=this.points.length||this.points[lastVisibleIndex].x>rightTimestamp){lastVisibleIndex--;}
var viewSkipDistance=this.skipDistance_*transform.pixelRatio;var circleRadius;var squareSize;var squareHalfSize;var squareOpacity;switch(component){case ChartSeriesComponent.DOTS:ctx.strokeStyle=EventPresenter.getCounterSeriesColor(this.colorId_,SelectionState.NONE);ctx.lineWidth=transform.pixelRatio;circleRadius=(this.selectedPointSize_/2)*transform.pixelRatio;squareSize=this.unselectedPointSize_*transform.pixelRatio;squareHalfSize=squareSize/2;if(!highDetails){squareOpacity=0;break;}
var visibleIndexRange=lastVisibleIndex-firstVisibleIndex;if(visibleIndexRange< =0){squareOpacity=1;break;}
var visibleViewXRange=transform.worldXToViewX(this.points[lastVisibleIndex].x)-
transform.worldXToViewX(this.points[firstVisibleIndex].x);if(visibleViewXRange===0){squareOpacity=1;break;}
var density=visibleIndexRange/visibleViewXRange;var clampedDensity=tr.b.clamp(density,this.unselectedPointDensityOpaque_,this.unselectedPointDensityTransparent_);var densityRange=this.unselectedPointDensityTransparent_-
this.unselectedPointDensityOpaque_;squareOpacity=(this.unselectedPointDensityTransparent_-clampedDensity)/densityRange;break;case ChartSeriesComponent.LINE:ctx.strokeStyle=EventPresenter.getCounterSeriesColor(this.colorId_,SelectionState.NONE);ctx.lineWidth=this.lineWidth_*transform.pixelRatio;break;case ChartSeriesComponent.BACKGROUND:break;default:throw new Error('Invalid component: '+component);}
var previousViewX=undefined;var previousViewY=undefined;var previousViewYBase=undefined;var lastSelectionState=undefined;var baseSteps=undefined;var startIndex=Math.max(firstVisibleIndex-1,0);for(var i=startIndex;i< this.points.length ; i + + ) { var currentPoint = this.points[i];var currentViewX = transform.worldXToViewX(currentPoint.x);if(currentViewX > rightViewX){if(previousViewX!==undefined){previousViewX=currentViewX=rightViewX;if(component===ChartSeriesComponent.BACKGROUND||component===ChartSeriesComponent.LINE){ctx.lineTo(currentViewX,previousViewY);}}
break;}
if(i+1< this.points.length ) { var nextPoint = this.points[i+1];var nextViewX = transform.worldXToViewX(nextPoint.x);if(previousViewX!==undefined&&nextViewX-previousViewX<=viewSkipDistance&&nextViewX<rightViewX){continue;}
if(currentViewX< leftViewX ) { currentViewX = leftViewX;}}
if(previousViewX!==undefined&¤tViewX-previousViewX<viewSkipDistance){currentViewX=previousViewX+viewSkipDistance; }
var currentViewY=Math.round(transform.worldYToViewY(currentPoint.y));var currentViewYBase;if(currentPoint.yBase===undefined){currentViewYBase=transform.outerBottomViewY;}else{currentViewYBase=Math.round(transform.worldYToViewY(currentPoint.yBase));}
var currentSelectionState=currentPoint.selectionState;switch(component){case ChartSeriesComponent.DOTS:if(currentSelectionState!==lastSelectionState){if(currentSelectionState===SelectionState.SELECTED){ctx.fillStyle=EventPresenter.getCounterSeriesColor(this.colorId_,currentSelectionState);}else if(squareOpacity>0){ctx.fillStyle=EventPresenter.getCounterSeriesColor(this.colorId_,currentSelectionState,squareOpacity);}}
if(currentSelectionState===SelectionState.SELECTED){ctx.beginPath();ctx.arc(currentViewX,currentViewY,circleRadius,0,2*Math.PI);ctx.fill();ctx.stroke();}else if(squareOpacity>0){ctx.fillRect(currentViewX-squareHalfSize,currentViewY-squareHalfSize,squareSize,squareSize);}
break;case ChartSeriesComponent.LINE:if(previousViewX===undefined){ctx.beginPath();ctx.moveTo(currentViewX,currentViewY);}else{ctx.lineTo(currentViewX,previousViewY);}
ctx.lineTo(currentViewX,currentViewY);break;case ChartSeriesComponent.BACKGROUND:if(previousViewX!==undefined)
ctx.lineTo(currentViewX,previousViewY);if(currentSelectionState!==lastSelectionState){if(previousViewX!==undefined){var previousBaseStepViewX=currentViewX;for(var j=baseSteps.length-1;j>=0;j--){var baseStep=baseSteps[j];var baseStepViewX=baseStep.viewX;var baseStepViewY=baseStep.viewY;ctx.lineTo(previousBaseStepViewX,baseStepViewY);ctx.lineTo(baseStepViewX,baseStepViewY);previousBaseStepViewX=baseStepViewX;}
ctx.closePath();ctx.fill();}
ctx.beginPath();ctx.fillStyle=EventPresenter.getCounterSeriesColor(this.colorId_,currentSelectionState,this.backgroundOpacity_);ctx.moveTo(currentViewX,currentViewYBase);baseSteps=[];}
if(currentViewYBase!==previousViewYBase||currentSelectionState!==lastSelectionState){baseSteps.push({viewX:currentViewX,viewY:currentViewYBase});}
ctx.lineTo(currentViewX,currentViewY);break;default:throw new Error('Not reachable');}
previousViewX=currentViewX;previousViewY=currentViewY;previousViewYBase=currentViewYBase;lastSelectionState=currentSelectionState;}
if(previousViewX!==undefined){switch(component){case ChartSeriesComponent.DOTS:break;case ChartSeriesComponent.LINE:ctx.stroke();break;case ChartSeriesComponent.BACKGROUND:var previousBaseStepViewX=currentViewX;for(var j=baseSteps.length-1;j>=0;j--){var baseStep=baseSteps[j];var baseStepViewX=baseStep.viewX;var baseStepViewY=baseStep.viewY;ctx.lineTo(previousBaseStepViewX,baseStepViewY);ctx.lineTo(baseStepViewX,baseStepViewY);previousBaseStepViewX=baseStepViewX;}
ctx.closePath();ctx.fill();break;default:throw new Error('Not reachable');}}},addIntersectingEventsInRangeToSelectionInWorldSpace:function(loWX,hiWX,viewPixWidthWorld,selection){var points=this.points;function getPointWidth(point,i){if(i===points.length-1)
return LAST_POINT_WIDTH*viewPixWidthWorld;var nextPoint=points[i+1];return nextPoint.x-point.x;}
function selectPoint(point){point.addToSelection(selection);}
tr.b.iterateOverIntersectingIntervals(this.points,function(point){return point.x},getPointWidth,loWX,hiWX,selectPoint);},addEventNearToProvidedEventToSelection:function(event,offset,selection){if(this.points===undefined)
return false;var index=tr.b.findFirstIndexInArray(this.points,function(point){return point.modelItem===event;},this);if(index===-1)
return false;var newIndex=index+offset;if(newIndex< 0 | | newIndex > =this.points.length)
return false;this.points[newIndex].addToSelection(selection);return true;},addClosestEventToSelection:function(worldX,worldMaxDist,loY,hiY,selection){if(this.points===undefined)
return;var item=tr.b.findClosestElementInSortedArray(this.points,function(point){return point.x},worldX,worldMaxDist);if(!item)
2015-06-18 08:27:29 -06:00
return;item.addToSelection(selection);}};return{ChartSeries:ChartSeries,ChartSeriesType:ChartSeriesType};});'use strict';tr.exportTo('tr.ui.tracks',function(){function ChartTransform(displayTransform,axis,trackWidth,trackHeight,topPadding,bottomPadding,pixelRatio){this.pixelRatio=pixelRatio;this.leftViewX=0;this.rightViewX=trackWidth;this.leftTimestamp=displayTransform.xViewToWorld(this.leftViewX);this.rightTimestamp=displayTransform.xViewToWorld(this.rightViewX);this.displayTransform_=displayTransform;this.outerTopViewY=0;this.innerTopViewY=topPadding;this.innerBottomViewY=trackHeight-bottomPadding;this.outerBottomViewY=trackHeight;this.axis_=axis;this.innerHeight_=this.innerBottomViewY-this.innerTopViewY;};ChartTransform.prototype={worldXToViewX:function(worldX){return this.displayTransform_.xWorldToView(worldX);},viewXToWorldX:function(viewX){return this.displayTransform_.xViewToWorld(viewX);},worldYToViewY:function(worldY){var innerHeightCoefficient=1-this.axis_.valueToUnitRange(worldY);return innerHeightCoefficient*this.innerHeight_+this.innerTopViewY;}};return{ChartTransform:ChartTransform};});'use strict';tr.exportTo('tr.ui.tracks',function(){var ChartTrack=tr.ui.b.define('chart-track',tr.ui.tracks.HeadingTrack);ChartTrack.prototype={__proto__:tr.ui.tracks.HeadingTrack.prototype,decorate:function(viewport){tr.ui.tracks.HeadingTrack.prototype.decorate.call(this,viewport);this.classList.add('chart-track');this.series_=undefined;this.axisGuidToAxisData_=undefined;this.topPadding_=undefined;this.bottomPadding_=undefined;},get series(){return this.series_;},set series(series){this.series_=series;this.calculateAxisDataAndPadding_();this.invalidateDrawingContainer();},get height(){return window.getComputedStyle(this).height;},set height(height){this.style.height=height;this.invalidateDrawingContainer();},get hasVisibleContent(){return!!this.series&&this.series.length>0; },calculateAxisDataAndPadding_:function(){if(!this.series_){this.axisGuidToAxisData_=undefined;this.topPadding_=undefined;this.bottomPadding_=undefined;return;}
2015-06-14 13:52:57 -06:00
var axisGuidToAxisData={};var topPadding=0;var bottomPadding=0;this.series_.forEach(function(series){var axis=series.axis;var axisGuid=axis.guid;if(!(axisGuid in axisGuidToAxisData)){axisGuidToAxisData[axisGuid]={axis:axis,series:[]};}
2015-06-18 08:27:29 -06:00
axisGuidToAxisData[axisGuid].series.push(series);topPadding=Math.max(topPadding,series.topPadding);bottomPadding=Math.max(bottomPadding,series.bottomPadding);},this);this.axisGuidToAxisData_=axisGuidToAxisData;this.topPadding_=topPadding;this.bottomPadding_=bottomPadding;},draw:function(type,viewLWorld,viewRWorld){switch(type){case tr.ui.tracks.DrawType.GENERAL_EVENT:this.drawChart_(viewLWorld,viewRWorld);break;}},drawChart_:function(viewLWorld,viewRWorld){if(!this.series_)
return;var ctx=this.context();var displayTransform=this.viewport.currentDisplayTransform;var pixelRatio=window.devicePixelRatio||1;var bounds=this.getBoundingClientRect();var highDetails=this.viewport.highDetails;var width=bounds.width*pixelRatio;var height=bounds.height*pixelRatio;var topPadding=this.topPadding_*pixelRatio;var bottomPadding=this.bottomPadding_*pixelRatio;ctx.save();ctx.beginPath();ctx.rect(0,0,width,height);ctx.clip();this.series_.forEach(function(series){var chartTransform=new tr.ui.tracks.ChartTransform(displayTransform,series.axis,width,height,topPadding,bottomPadding,pixelRatio);series.draw(ctx,chartTransform,highDetails);},this);ctx.restore();},addEventsToTrackMap:function(eventToTrackMap){this.series_.forEach(function(series){series.points.forEach(function(point){point.addToTrackMap(eventToTrackMap,this);},this);},this);},addIntersectingEventsInRangeToSelectionInWorldSpace:function(loWX,hiWX,viewPixWidthWorld,selection){this.series_.forEach(function(series){series.addIntersectingEventsInRangeToSelectionInWorldSpace(loWX,hiWX,viewPixWidthWorld,selection);},this);},addEventNearToProvidedEventToSelection:function(event,offset,selection){var foundItem=false;this.series_.forEach(function(series){foundItem=foundItem||series.addEventNearToProvidedEventToSelection(event,offset,selection);},this);return foundItem;},addAllEventsMatchingFilterToSelection:function(filter,selection){},addClosestEventToSelection:function(worldX,worldMaxDist,loY,hiY,selection){this.series_.forEach(function(series){series.addClosestEventToSelection(worldX,worldMaxDist,loY,hiY,selection);},this);},autoSetAllAxes:function(opt_config){tr.b.iterItems(this.axisGuidToAxisData_,function(axisGuid,axisData){var axis=axisData.axis;var series=axisData.series;axis.autoSetFromSeries(series,opt_config);},this);},autoSetAxis:function(axis,opt_config){var series=this.axisGuidToAxisData_[axis.guid].series;axis.autoSetFromSeries(series,opt_config);}};return{ChartTrack:ChartTrack};});'use strict';tr.exportTo('tr.ui.tracks',function(){var CounterTrack=tr.ui.b.define('counter-track',tr.ui.tracks.ChartTrack);CounterTrack.prototype={__proto__:tr.ui.tracks.ChartTrack.prototype,decorate:function(viewport){tr.ui.tracks.ChartTrack.prototype.decorate.call(this,viewport);this.classList.add('counter-track');},get counter(){return this.chart;},set counter(counter){this.heading=counter.name+': ';this.series=CounterTrack.buildChartSeriesFromCounter(counter);this.autoSetAllAxes({expandMax:true});},getModelEventFromItem:function(chartValue){return chartValue;}};CounterTrack.buildChartSeriesFromCounter=function(counter){var numSeries=counter.series.length;var totals=counter.totals;var chartAxis=new tr.ui.tracks.ChartAxis(0,undefined);var chartSeries=counter.series.map(function(series,seriesIndex){var chartPoints=series.samples.map(function(sample,sampleIndex){var total=totals[sampleIndex*numSeries+seriesIndex];return new tr.ui.tracks.ChartPoint(sample,sample.timestamp,total);});var renderingConfig={chartType:tr.ui.tracks.ChartSeriesType.AREA,colorId:series.color};return new tr.ui.tracks.ChartSeries(chartPoints,chartAxis,renderingConfig);});chartSeries.reverse();return chartSeries;};return{CounterTrack:CounterTrack};});'use strict';tr.exportTo('tr.ui.tracks',function(){var EventPresenter=tr.ui.b.EventPresenter;var SelectionState=tr.model.SelectionState;var LetterDotTrack=tr.ui.b.define('letter-dot-track',tr.ui.tracks.HeadingTrack);LetterDotTrack.prototype={__proto__:tr.ui.tracks.HeadingTrack.prototype,decorate:function(viewport){tr.ui.tracks.HeadingTrack.prototype.decorate.call(this,viewport);this.classList.add('letter-dot-track');this.items_=undefined;},get items(){return this.items_;},set items(items){this.items_=items;this.invalidateDrawingContainer();},get height(){return window.getComputedStyle(this).height;},set height(height){this.style.height=height;},get dumpRadiusView(){return 7*(window.devicePixelRatio||1);},draw:function(type,viewLWorld,viewRWorld){if(this.items_===undefined)
return;switch(type){case tr.ui.tracks.DrawType.GENERAL_EVENT:this.drawLetterDots_(viewLWorld,viewRWorld);break;}},drawLetterDots_:function(viewLWorld,viewRWorld){var ctx=this.context();var pixelRatio=window.devicePixelRatio||1;var bounds=this.getBoundingClientRect();var height=bounds.height*pixelRatio;var halfHeight=height*0.5;var twoPi=Math.PI*2;var palette=tr.ui.b.getColorPalette();var highlightIdBoost=tr.ui.b.paletteProperties.highlightIdBoost;var dt=this.viewport.currentDisplayTransform;var dumpRadiusView=this.dumpRadiusView;var itemRadiusWorld=dt.xViewVectorToWorld(height);var items=this.items_;var loI=tr.b.findLowIndexInSortedArray(items,function(item){return item.start;},viewLWorld);var oldFont=ctx.font;ctx.font='400 '+Math.floor(9*pixelRatio)+'px Arial';ctx.strokeStyle='rgb(0,0,0)';ctx.textBaseline='middle';ctx.textAlign='center';var drawItems=function(selected){for(var i=loI;i< items.length ; + + i ) { var item = items[i];var x = item.start;if(x-itemRadiusWorld > viewRWorld)
2015-06-14 13:52:57 -06:00
break;if(item.selected!==selected)
continue;var xView=dt.xWorldToView(x);ctx.fillStyle=EventPresenter.getSelectableItemColor(item);ctx.beginPath();ctx.arc(xView,halfHeight,dumpRadiusView+0.5,0,twoPi);ctx.fill();if(item.selected){ctx.lineWidth=3;ctx.strokeStyle='rgb(100,100,0)';ctx.stroke();ctx.beginPath();ctx.arc(xView,halfHeight,dumpRadiusView,0,twoPi);ctx.lineWidth=1.5;ctx.strokeStyle='rgb(255,255,0)';ctx.stroke();}else{ctx.lineWidth=1;ctx.strokeStyle='rgb(0,0,0)';ctx.stroke();}
ctx.fillStyle='rgb(255, 255, 255)';ctx.fillText(item.dotLetter,xView,halfHeight);}};drawItems(false);drawItems(true);ctx.lineWidth=1;ctx.font=oldFont;},addEventsToTrackMap:function(eventToTrackMap){if(this.items_===undefined)
return;this.items_.forEach(function(item){item.addToTrackMap(eventToTrackMap,this);},this);},addIntersectingEventsInRangeToSelectionInWorldSpace:function(loWX,hiWX,viewPixWidthWorld,selection){if(this.items_===undefined)
return;var itemRadiusWorld=viewPixWidthWorld*this.dumpRadiusView;tr.b.iterateOverIntersectingIntervals(this.items_,function(x){return x.start-itemRadiusWorld;},function(x){return 2*itemRadiusWorld;},loWX,hiWX,function(item){item.addToSelection(selection);}.bind(this));},addEventNearToProvidedEventToSelection:function(event,offset,selection){if(this.items_===undefined)
return;var items=this.items_;var index=tr.b.findFirstIndexInArray(items,function(item){return item.modelItem===event;});if(index===-1)
return false;var newIndex=index+offset;if(newIndex>=0&&newIndex<items.length){items[newIndex].addToSelection(selection); return true;}
return false;},addAllEventsMatchingFilterToSelection:function(filter,selection){},addClosestEventToSelection:function(worldX,worldMaxDist,loY,hiY,selection){if(this.items_===undefined)
return;var item=tr.b.findClosestElementInSortedArray(this.items_,function(x){return x.start;},worldX,worldMaxDist);if(!item)
2015-06-18 08:27:29 -06:00
return;item.addToSelection(selection);}};function LetterDot(modelItem,dotLetter,colorId,start){tr.model.ProxySelectableItem.call(this,modelItem);this.dotLetter=dotLetter;this.colorId=colorId;this.start=start;};LetterDot.prototype={__proto__:tr.model.ProxySelectableItem.prototype};return{LetterDotTrack:LetterDotTrack,LetterDot:LetterDot};});'use strict';tr.exportTo('tr.ui.tracks',function(){var palette=tr.ui.b.getColorPalette();var startCompare=function(x,y){return x.start-y.start;}
var FrameTrack=tr.ui.b.define('frame-track',tr.ui.tracks.LetterDotTrack);FrameTrack.prototype={__proto__:tr.ui.tracks.LetterDotTrack.prototype,decorate:function(viewport){tr.ui.tracks.LetterDotTrack.prototype.decorate.call(this,viewport);this.heading='Frames';this.frames_=undefined;this.items=undefined;},get frames(){return this.frames_;},set frames(frames){this.frames_=frames;if(frames===undefined)
return;this.frames_=this.frames_.slice();this.frames_.sort(startCompare);this.items=this.frames_.map(function(frame){return new FrameDot(frame);});}};function FrameDot(frame){tr.ui.tracks.LetterDot.call(this,frame,'F',frame.colorId,frame.start);}
FrameDot.prototype={__proto__:tr.ui.tracks.LetterDot.prototype};return{FrameTrack:FrameTrack};});'use strict';tr.exportTo('tr.model',function(){var Settings=tr.b.Settings;function ModelSettings(model){this.model=model;this.objectsByKey_=[];this.nonuniqueKeys_=[];this.buildObjectsByKeyMap_();this.removeNonuniqueKeysFromSettings_();this.ephemeralSettingsByGUID_={};}
ModelSettings.prototype={buildObjectsByKeyMap_:function(){var objects=[];this.model.iterateAllPersistableObjects(function(o){objects.push(o);});var objectsByKey={};var NONUNIQUE_KEY='nonuniqueKey';for(var i=0;i< objects.length ; i + + ) { var object = objects[i];var objectKey = object.getSettingsKey();if(!objectKey)
continue;if(objectsByKey[objectKey]===undefined){objectsByKey[objectKey]=object;continue;}
objectsByKey[objectKey]=NONUNIQUE_KEY;}
var nonuniqueKeys={};tr.b.dictionaryKeys(objectsByKey).forEach(function(objectKey){if(objectsByKey[objectKey]!==NONUNIQUE_KEY)
return;delete objectsByKey[objectKey];nonuniqueKeys[objectKey]=true;});this.nonuniqueKeys=nonuniqueKeys;this.objectsByKey_=objectsByKey;},removeNonuniqueKeysFromSettings_:function(){var settings=Settings.get('trace_model_settings',{});var settingsChanged=false;tr.b.dictionaryKeys(settings).forEach(function(objectKey){if(!this.nonuniqueKeys[objectKey])
return;settingsChanged=true;delete settings[objectKey];},this);if(settingsChanged)
Settings.set('trace_model_settings',settings);},hasUniqueSettingKey:function(object){var objectKey=object.getSettingsKey();if(!objectKey)
return false;return this.objectsByKey_[objectKey]!==undefined;},getSettingFor:function(object,objectLevelKey,defaultValue){var objectKey=object.getSettingsKey();if(!objectKey||!this.objectsByKey_[objectKey]){var settings=this.getEphemeralSettingsFor_(object);var ephemeralValue=settings[objectLevelKey];if(ephemeralValue!==undefined)
return ephemeralValue;return defaultValue;}
var settings=Settings.get('trace_model_settings',{});if(!settings[objectKey])
settings[objectKey]={};var value=settings[objectKey][objectLevelKey];if(value!==undefined)
return value;return defaultValue;},setSettingFor:function(object,objectLevelKey,value){var objectKey=object.getSettingsKey();if(!objectKey||!this.objectsByKey_[objectKey]){this.getEphemeralSettingsFor_(object)[objectLevelKey]=value;return;}
var settings=Settings.get('trace_model_settings',{});if(!settings[objectKey])
settings[objectKey]={};if(settings[objectKey][objectLevelKey]===value)
return;settings[objectKey][objectLevelKey]=value;Settings.set('trace_model_settings',settings);},getEphemeralSettingsFor_:function(object){if(object.guid===undefined)
throw new Error('Only objects with GUIDs can be persisted');if(this.ephemeralSettingsByGUID_[object.guid]===undefined)
this.ephemeralSettingsByGUID_[object.guid]={};return this.ephemeralSettingsByGUID_[object.guid];}};return{ModelSettings:ModelSettings};});'use strict';tr.exportTo('tr.ui.tracks',function(){var MultiRowTrack=tr.ui.b.define('multi-row-track',tr.ui.tracks.ContainerTrack);MultiRowTrack.prototype={__proto__:tr.ui.tracks.ContainerTrack.prototype,decorate:function(viewport){tr.ui.tracks.ContainerTrack.prototype.decorate.call(this,viewport);this.tooltip_='';this.heading_='';this.groupingSource_=undefined;this.itemsToGroup_=undefined;this.defaultToCollapsedWhenSubRowCountMoreThan=1;this.itemsGroupedOnLastUpdateContents_=undefined;this.currentSubRows_=[];this.expanded_=true;},get itemsToGroup(){return this.itemsToGroup_;},setItemsToGroup:function(itemsToGroup,opt_groupingSource){this.itemsToGroup_=itemsToGroup;this.groupingSource_=opt_groupingSource;this.updateContents_();this.updateExpandedStateFromGroupingSource_();},get heading(){return this.heading_;},set heading(h){this.heading_=h;this.updateContents_();},get tooltip(){return this.tooltip_;},set tooltip(t){this.tooltip_=t;this.updateContents_();},get subRows(){return this.currentSubRows_;},get hasVisibleContent(){return this.children.length>0;},get expanded(){return this.expanded_;},set expanded(expanded){expanded=expanded;if(this.expanded_==expanded)
2015-06-14 13:52:57 -06:00
return;this.expanded_=expanded;this.expandedStateChanged_();},onHeadingClicked_:function(e){if(this.subRows.length< =1)
return;this.expanded=!this.expanded;if(this.groupingSource_){var modelSettings=new tr.model.ModelSettings(this.groupingSource_.model);modelSettings.setSettingFor(this.groupingSource_,'expanded',this.expanded);}
e.stopPropagation();},updateExpandedStateFromGroupingSource_:function(){if(this.groupingSource_){var numSubRows=this.subRows.length;var modelSettings=new tr.model.ModelSettings(this.groupingSource_.model);if(numSubRows>1){var defaultExpanded;if(numSubRows>this.defaultToCollapsedWhenSubRowCountMoreThan){defaultExpanded=false;}else{defaultExpanded=true;}
this.expanded=modelSettings.getSettingFor(this.groupingSource_,'expanded',defaultExpanded);}else{this.expanded=undefined;}}},expandedStateChanged_:function(){var minH=Math.max(2,Math.ceil(18/this.children.length));var h=(this.expanded_?18:minH)+'px';for(var i=0;i< this.children.length ; i + + )
this.children[i].height=h;if(this.children.length>0)
2015-06-18 08:27:29 -06:00
this.children[0].expanded=this.expanded;},updateContents_:function(){tr.ui.tracks.ContainerTrack.prototype.updateContents_.call(this);if(!this.itemsToGroup_){this.updateHeadingAndTooltip_();this.currentSubRows_=[];return;}
2015-06-14 13:52:57 -06:00
if(this.areArrayContentsSame_(this.itemsGroupedOnLastUpdateContents_,this.itemsToGroup_)){this.updateHeadingAndTooltip_();return;}
this.itemsGroupedOnLastUpdateContents_=this.itemsToGroup_;this.detach();if(!this.itemsToGroup_.length){this.currentSubRows_=[];return;}
var subRows=this.buildSubRows_(this.itemsToGroup_);this.currentSubRows_=subRows;for(var srI=0;srI< subRows.length ; srI + + ) { var subRow = subRows[srI];if(!subRow.length)
continue;var track=this.addSubTrack_(subRow);track.addEventListener('heading-clicked',this.onHeadingClicked_.bind(this));}
this.updateHeadingAndTooltip_();this.expandedStateChanged_();},updateHeadingAndTooltip_:function(){if(!this.firstChild)
return;this.firstChild.heading=this.heading_;this.firstChild.tooltip=this.tooltip_;},buildSubRows_:function(itemsToGroup){throw new Error('Not implemented');},addSubTrack_:function(subRowItems){throw new Error('Not implemented');},areArrayContentsSame_:function(a,b){if(!a||!b)
return false;if(!a.length||!b.length)
return false;if(a.length!=b.length)
return false;for(var i=0;i< a.length ; + + i ) { if ( a [ i ] ! = b [ i ] )
return false;}
2015-06-18 08:27:29 -06:00
return true;}};return{MultiRowTrack:MultiRowTrack};});'use strict';tr.exportTo('tr.ui.tracks',function(){var SelectionState=tr.model.SelectionState;var EventPresenter=tr.ui.b.EventPresenter;var ObjectInstanceTrack=tr.ui.b.define('object-instance-track',tr.ui.tracks.HeadingTrack);ObjectInstanceTrack.prototype={__proto__:tr.ui.tracks.HeadingTrack.prototype,decorate:function(viewport){tr.ui.tracks.HeadingTrack.prototype.decorate.call(this,viewport);this.classList.add('object-instance-track');this.objectInstances_=[];this.objectSnapshots_=[];},get objectInstances(){return this.objectInstances_;},set objectInstances(objectInstances){if(!objectInstances||objectInstances.length==0){this.heading='';this.objectInstances_=[];this.objectSnapshots_=[];return;}
this.heading=objectInstances[0].typeName;this.objectInstances_=objectInstances;this.objectSnapshots_=[];this.objectInstances_.forEach(function(instance){this.objectSnapshots_.push.apply(this.objectSnapshots_,instance.snapshots);},this);this.objectSnapshots_.sort(function(a,b){return a.ts-b.ts;});},get height(){return window.getComputedStyle(this).height;},set height(height){this.style.height=height;},get snapshotRadiusView(){return 7*(window.devicePixelRatio||1);},draw:function(type,viewLWorld,viewRWorld){switch(type){case tr.ui.tracks.DrawType.GENERAL_EVENT:this.drawLetterDots_(viewLWorld,viewRWorld);break;}},drawLetterDots_:function(viewLWorld,viewRWorld){var ctx=this.context();var pixelRatio=window.devicePixelRatio||1;var bounds=this.getBoundingClientRect();var height=bounds.height*pixelRatio;var halfHeight=height*0.5;var twoPi=Math.PI*2;var dt=this.viewport.currentDisplayTransform;var snapshotRadiusView=this.snapshotRadiusView;var snapshotRadiusWorld=dt.xViewVectorToWorld(height);var loI;ctx.save();dt.applyTransformToCanvas(ctx);var objectInstances=this.objectInstances_;var loI=tr.b.findLowIndexInSortedArray(objectInstances,function(instance){return instance.deletionTs;},viewLWorld);ctx.strokeStyle='rgb(0,0,0)';for(var i=loI;i< objectInstances.length ; + + i ) { var instance = objectInstances[i];var x = instance.creationTs;if(x > viewRWorld)
2015-06-14 13:52:57 -06:00
break;var right=instance.deletionTs==Number.MAX_VALUE?viewRWorld:instance.deletionTs;ctx.fillStyle=EventPresenter.getObjectInstanceColor(instance);ctx.fillRect(x,pixelRatio,right-x,height-2*pixelRatio);}
ctx.restore();var objectSnapshots=this.objectSnapshots_;loI=tr.b.findLowIndexInSortedArray(objectSnapshots,function(snapshot){return snapshot.ts+snapshotRadiusWorld;},viewLWorld);for(var i=loI;i< objectSnapshots.length ; + + i ) { var snapshot = objectSnapshots[i];var x = snapshot.ts;if(x-snapshotRadiusWorld > viewRWorld)
break;var xView=dt.xWorldToView(x);ctx.fillStyle=EventPresenter.getObjectSnapshotColor(snapshot);ctx.beginPath();ctx.arc(xView,halfHeight,snapshotRadiusView,0,twoPi);ctx.fill();if(snapshot.selected){ctx.lineWidth=5;ctx.strokeStyle='rgb(100,100,0)';ctx.stroke();ctx.beginPath();ctx.arc(xView,halfHeight,snapshotRadiusView-1,0,twoPi);ctx.lineWidth=2;ctx.strokeStyle='rgb(255,255,0)';ctx.stroke();}else{ctx.lineWidth=1;ctx.strokeStyle='rgb(0,0,0)';ctx.stroke();}}
ctx.lineWidth=1;var selectionState=SelectionState.NONE;if(objectInstances.length&&objectInstances[0].selectionState===SelectionState.DIMMED){selectionState=SelectionState.DIMMED; }
if(selectionState===SelectionState.DIMMED){var width=bounds.width*pixelRatio;ctx.fillStyle='rgba(255,255,255,0.5)';ctx.fillRect(0,0,width,height);ctx.restore();}},addEventsToTrackMap:function(eventToTrackMap){if(this.objectInstance_!==undefined){this.objectInstance_.forEach(function(obj){eventToTrackMap.addEvent(obj,this);},this);}
if(this.objectSnapshots_!==undefined){this.objectSnapshots_.forEach(function(obj){eventToTrackMap.addEvent(obj,this);},this);}},addIntersectingEventsInRangeToSelectionInWorldSpace:function(loWX,hiWX,viewPixWidthWorld,selection){var foundSnapshot=false;function onSnapshot(snapshot){selection.push(snapshot);foundSnapshot=true;}
var snapshotRadiusView=this.snapshotRadiusView;var snapshotRadiusWorld=viewPixWidthWorld*snapshotRadiusView;tr.b.iterateOverIntersectingIntervals(this.objectSnapshots_,function(x){return x.ts-snapshotRadiusWorld;},function(x){return 2*snapshotRadiusWorld;},loWX,hiWX,onSnapshot);if(foundSnapshot)
return;tr.b.iterateOverIntersectingIntervals(this.objectInstances_,function(x){return x.creationTs;},function(x){return x.deletionTs-x.creationTs;},loWX,hiWX,selection.push.bind(selection));},addEventNearToProvidedEventToSelection:function(event,offset,selection){var events;if(event instanceof tr.model.ObjectSnapshot)
events=this.objectSnapshots_;else if(event instanceof tr.model.ObjectInstance)
events=this.objectInstances_;else
throw new Error('Unrecognized event');var index=events.indexOf(event);var newIndex=index+offset;if(newIndex>=0&&newIndex<events.length){selection.push(events[newIndex]); return true;}
return false;},addAllEventsMatchingFilterToSelection:function(filter,selection){},addClosestEventToSelection:function(worldX,worldMaxDist,loY,hiY,selection){var snapshot=tr.b.findClosestElementInSortedArray(this.objectSnapshots_,function(x){return x.ts;},worldX,worldMaxDist);if(!snapshot)
2015-06-18 08:27:29 -06:00
return;selection.push(snapshot);}};var options=new tr.b.ExtensionRegistryOptions(tr.b.TYPE_BASED_REGISTRY_MODE);tr.b.decorateExtensionRegistry(ObjectInstanceTrack,options);return{ObjectInstanceTrack:ObjectInstanceTrack};});'use strict';tr.exportTo('tr.ui.tracks',function(){var ObjectInstanceGroupTrack=tr.ui.b.define('object-instance-group-track',tr.ui.tracks.MultiRowTrack);ObjectInstanceGroupTrack.prototype={__proto__:tr.ui.tracks.MultiRowTrack.prototype,decorate:function(viewport){tr.ui.tracks.MultiRowTrack.prototype.decorate.call(this,viewport);this.classList.add('object-instance-group-track');this.objectInstances_=undefined;},get objectInstances(){return this.itemsToGroup;},set objectInstances(objectInstances){this.setItemsToGroup(objectInstances);},addSubTrack_:function(objectInstances){var hasMultipleRows=this.subRows.length>1;var track=new tr.ui.tracks.ObjectInstanceTrack(this.viewport);track.objectInstances=objectInstances;this.appendChild(track);return track;},buildSubRows_:function(objectInstances){objectInstances.sort(function(x,y){return x.creationTs-y.creationTs;});var subRows=[];for(var i=0;i< objectInstances.length ; i + + ) { var objectInstance = objectInstances[i];var found = false;for(var j = 0;j<subRows.length;j++){var subRow = subRows[j];var lastItemInSubRow = subRow[subRow.length-1];if(objectInstance.creationTs > =lastItemInSubRow.deletionTs){found=true;subRow.push(objectInstance);break;}}
2015-06-14 13:52:57 -06:00
if(!found){var subRow=[objectInstance];subRows.push(subRow);}}
2015-06-18 08:27:29 -06:00
return subRows;},updateHeadingAndTooltip_:function(){}};return{ObjectInstanceGroupTrack:ObjectInstanceGroupTrack};});'use strict';tr.exportTo('tr.ui.b',function(){function FastRectRenderer(ctx,minRectSize,maxMergeDist,pallette){this.ctx_=ctx;this.minRectSize_=minRectSize;this.maxMergeDist_=maxMergeDist;this.pallette_=pallette;}
2015-06-14 13:52:57 -06:00
FastRectRenderer.prototype={y_:0,h_:0,merging_:false,mergeStartX_:0,mergeCurRight_:0,mergedColorId_:0,mergedAlpha_:0,setYandH:function(y,h){if(this.y_===y& & this.h_===h)
return;this.flush();this.y_=y;this.h_=h;},fillRect:function(x,w,colorId,alpha){var r=x+w;if(w< this.minRectSize_ ) { if ( r-this . mergeStartX_ > this.maxMergeDist_)
this.flush();if(!this.merging_){this.merging_=true;this.mergeStartX_=x;this.mergeCurRight_=r;this.mergedColorId_=colorId;this.mergedAlpha_=alpha;}else{this.mergeCurRight_=r;if(this.mergedAlpha_< alpha | | ( this . mergedAlpha_ = ==alpha&&this.mergedColorId_<colorId)){this.mergedAlpha_=alpha;this.mergedColorId_=colorId;}}}else{if(this.merging_)
2015-06-18 08:27:29 -06:00
this.flush();this.ctx_.fillStyle=this.pallette_[colorId];this.ctx_.globalAlpha=alpha;this.ctx_.fillRect(x,this.y_,w,this.h_);}},flush:function(){if(this.merging_){this.ctx_.fillStyle=this.pallette_[this.mergedColorId_];this.ctx_.globalAlpha=this.mergedAlpha_;this.ctx_.fillRect(this.mergeStartX_,this.y_,this.mergeCurRight_-this.mergeStartX_,this.h_);this.merging_=false;}}};return{FastRectRenderer:FastRectRenderer};});'use strict';tr.exportTo('tr.ui.tracks',function(){var RectTrack=tr.ui.b.define('rect-track',tr.ui.tracks.HeadingTrack);RectTrack.prototype={__proto__:tr.ui.tracks.HeadingTrack.prototype,decorate:function(viewport){tr.ui.tracks.HeadingTrack.prototype.decorate.call(this,viewport);this.classList.add('rect-track');this.asyncStyle_=false;this.rects_=null;},get asyncStyle(){return this.asyncStyle_;},set asyncStyle(v){this.asyncStyle_=!!v;},get rects(){return this.rects_;},set rects(rects){this.rects_=rects||[];this.invalidateDrawingContainer();},get height(){return window.getComputedStyle(this).height;},set height(height){this.style.height=height;this.invalidateDrawingContainer();},get hasVisibleContent(){return this.rects_.length>0;},draw:function(type,viewLWorld,viewRWorld){switch(type){case tr.ui.tracks.DrawType.GENERAL_EVENT:this.drawRects_(viewLWorld,viewRWorld);break;}},drawRects_:function(viewLWorld,viewRWorld){var ctx=this.context();ctx.save();var bounds=this.getBoundingClientRect();tr.ui.b.drawSlices(ctx,this.viewport.currentDisplayTransform,viewLWorld,viewRWorld,bounds.height,this.rects_,this.asyncStyle_);ctx.restore();if(bounds.height< =6)
2015-06-14 13:52:57 -06:00
return;var fontSize,yOffset;if(bounds.height< 15 ) { fontSize = 6;yOffset=1.0;}else{fontSize=10;yOffset=2.5;}
2015-06-18 08:27:29 -06:00
tr.ui.b.drawLabels(ctx,this.viewport.currentDisplayTransform,viewLWorld,viewRWorld,this.rects_,this.asyncStyle_,fontSize,yOffset);},addEventsToTrackMap:function(eventToTrackMap){if(this.rects_===undefined||this.rects_===null)
2015-06-14 13:52:57 -06:00
return;this.rects_.forEach(function(rect){rect.addToTrackMap(eventToTrackMap,this);},this);},addIntersectingEventsInRangeToSelectionInWorldSpace:function(loWX,hiWX,viewPixWidthWorld,selection){function onRect(rect){rect.addToSelection(selection);}
onRect=onRect.bind(this);tr.b.iterateOverIntersectingIntervals(this.rects_,function(x){return x.start;},function(x){return x.duration;},loWX,hiWX,onRect);},addEventNearToProvidedEventToSelection:function(event,offset,selection){var index=tr.b.findFirstIndexInArray(this.rects_,function(rect){return rect.modelItem===event;});if(index===-1)
return false;var newIndex=index+offset;if(newIndex< 0 | | newIndex > =this.rects_.length)
return false;this.rects_[newIndex].addToSelection(selection);return true;},addAllEventsMatchingFilterToSelection:function(filter,selection){for(var i=0;i< this.rects_.length ; + + i ) { var modelItem = this.rects_[i].modelItem;if(!modelItem)
continue;if(filter.matchSlice(modelItem))
selection.push(modelItem);}},addClosestEventToSelection:function(worldX,worldMaxDist,loY,hiY,selection){var rect=tr.b.findClosestIntervalInSortedIntervals(this.rects_,function(x){return x.start;},function(x){return x.end;},worldX,worldMaxDist);if(!rect)
2015-06-18 08:27:29 -06:00
return;rect.addToSelection(selection);}};function Rect(modelItem,title,colorId,start,duration){tr.model.ProxySelectableItem.call(this,modelItem);this.title=title;this.colorId=colorId;this.start=start;this.duration=duration;this.end=start+duration;};Rect.prototype={__proto__:tr.model.ProxySelectableItem.prototype};return{RectTrack:RectTrack,Rect:Rect};});'use strict';tr.exportTo('tr.ui.tracks',function(){var ProcessSummaryTrack=tr.ui.b.define('process-summary-track',tr.ui.tracks.RectTrack);ProcessSummaryTrack.buildRectsFromProcess=function(process){if(!process)
2015-06-14 13:52:57 -06:00
return[];var ops=[];var pushOp=function(isStart,time,slice){ops.push({isStart:isStart,time:time,slice:slice});};for(var tid in process.threads){var sliceGroup=process.threads[tid].sliceGroup;sliceGroup.topLevelSlices.forEach(function(slice){pushOp(true,slice.start,undefined);pushOp(false,slice.end,undefined);});sliceGroup.slices.forEach(function(slice){if(slice.important){pushOp(true,slice.start,slice);pushOp(false,slice.end,slice);}});}
2015-06-18 08:27:29 -06:00
ops.sort(function(a,b){return a.time-b.time;});var rects=[];var genericColorId=tr.ui.b.getColorIdForReservedName('generic_work');var pushRect=function(start,end,slice){rects.push(new tr.ui.tracks.Rect(slice,slice?slice.title:'',slice?slice.colorId:genericColorId,start,end-start));}
2015-06-14 13:52:57 -06:00
var depth=0;var currentSlice=undefined;var lastStart=undefined;ops.forEach(function(op){depth+=op.isStart?1:-1;if(currentSlice){if(!op.isStart&&op.slice==currentSlice){pushRect(lastStart,op.time,currentSlice); lastStart=depth>=1?op.time:undefined;currentSlice=undefined;}}else{if(op.isStart){if(depth==1){lastStart=op.time;currentSlice=op.slice;}else if(op.slice){if(op.time!=lastStart){pushRect(lastStart,op.time,undefined);lastStart=op.time;}
2015-06-18 08:27:29 -06:00
currentSlice=op.slice;}}else{if(depth==0){pushRect(lastStart,op.time,undefined);lastStart=undefined;}}}});return rects;};ProcessSummaryTrack.prototype={__proto__:tr.ui.tracks.RectTrack.prototype,decorate:function(viewport){tr.ui.tracks.RectTrack.prototype.decorate.call(this,viewport);},get process(){return this.process_;},set process(process){this.process_=process;this.rects=ProcessSummaryTrack.buildRectsFromProcess(process);}};return{ProcessSummaryTrack:ProcessSummaryTrack};});'use strict';tr.exportTo('tr.ui.tracks',function(){var SpacingTrack=tr.ui.b.define('spacing-track',tr.ui.tracks.HeadingTrack);SpacingTrack.prototype={__proto__:tr.ui.tracks.HeadingTrack.prototype,decorate:function(viewport){tr.ui.tracks.HeadingTrack.prototype.decorate.call(this,viewport);this.classList.add('spacing-track');},draw:function(type,viewLWorld,viewRWorld){},addAllEventsMatchingFilterToSelection:function(filter,selection){}};return{SpacingTrack:SpacingTrack};});'use strict';tr.exportTo('tr.ui.tracks',function(){var SampleTrack=tr.ui.b.define('sample-track',tr.ui.tracks.RectTrack);SampleTrack.prototype={__proto__:tr.ui.tracks.RectTrack.prototype,decorate:function(viewport){tr.ui.tracks.RectTrack.prototype.decorate.call(this,viewport);},get samples(){return this.rects;},set samples(samples){this.rects=samples;}};return{SampleTrack:SampleTrack};});'use strict';tr.exportTo('tr.ui.tracks',function(){var SliceTrack=tr.ui.b.define('slice-track',tr.ui.tracks.RectTrack);SliceTrack.prototype={__proto__:tr.ui.tracks.RectTrack.prototype,decorate:function(viewport){tr.ui.tracks.RectTrack.prototype.decorate.call(this,viewport);},get slices(){return this.rects;},set slices(slices){this.rects=slices;}};return{SliceTrack:SliceTrack};});'use strict';tr.exportTo('tr.ui.tracks',function(){var SliceGroupTrack=tr.ui.b.define('slice-group-track',tr.ui.tracks.MultiRowTrack);SliceGroupTrack.prototype={__proto__:tr.ui.tracks.MultiRowTrack.prototype,decorate:function(viewport){tr.ui.tracks.MultiRowTrack.prototype.decorate.call(this,viewport);this.classList.add('slice-group-track');this.group_=undefined;this.defaultToCollapsedWhenSubRowCountMoreThan=100;},addSubTrack_:function(slices){var track=new tr.ui.tracks.SliceTrack(this.viewport);track.slices=slices;this.appendChild(track);return track;},get group(){return this.group_;},set group(group){this.group_=group;this.setItemsToGroup(this.group_.slices,this.group_);},get eventContainer(){return this.group;},addContainersToTrackMap:function(containerToTrackMap){containerToTrackMap.addContainer(this.group,this);},buildSubRows_:function(slices){var precisionUnit=this.group.model.intrinsicTimeUnit;if(!slices.length)
2015-06-14 13:52:57 -06:00
return[];var ops=[];for(var i=0;i< slices.length ; i + + ) { if ( slices [ i ] . subSlices )
slices[i].subSlices.splice(0,slices[i].subSlices.length);ops.push(i);}
ops.sort(function(ix,iy){var x=slices[ix];var y=slices[iy];if(x.start!=y.start)
return x.start-y.start;return ix-iy;});var subRows=[[]];this.badSlices_=[];for(var i=0;i< ops.length ; i + + ) { var op = ops[i];var slice = slices[op];var inserted = false;for(var j = subRows.length-1;j > =0;j--){if(subRows[j].length==0)
continue;var insertedSlice=subRows[j][subRows[j].length-1];if(slice.start< insertedSlice.start ) { this . badSlices_ . push ( slice ) ; inserted = true;}
2015-06-18 08:27:29 -06:00
if(insertedSlice.bounds(slice,precisionUnit)){while(subRows.length< =j+1)
2015-06-14 13:52:57 -06:00
subRows.push([]);subRows[j+1].push(slice);if(insertedSlice.subSlices)
insertedSlice.subSlices.push(slice);inserted=true;break;}}
if(inserted)
continue;subRows[0].push(slice);}
2015-06-18 08:27:29 -06:00
return subRows;}};return{SliceGroupTrack:SliceGroupTrack};});'use strict';tr.exportTo('tr.ui.tracks',function(){var AsyncSliceGroupTrack=tr.ui.b.define('async-slice-group-track',tr.ui.tracks.MultiRowTrack);AsyncSliceGroupTrack.prototype={__proto__:tr.ui.tracks.MultiRowTrack.prototype,decorate:function(viewport){tr.ui.tracks.MultiRowTrack.prototype.decorate.call(this,viewport);this.classList.add('async-slice-group-track');this.group_=undefined;},addSubTrack_:function(slices){var track=new tr.ui.tracks.SliceTrack(this.viewport);track.slices=slices;this.appendChild(track);track.asyncStyle=true;return track;},get group(){return this.group_;},set group(group){this.group_=group;this.setItemsToGroup(this.group_.slices,this.group_);},get eventContainer(){return this.group;},addContainersToTrackMap:function(containerToTrackMap){containerToTrackMap.addContainer(this.group,this);},buildSubRows_:function(slices,opt_skipSort){if(!opt_skipSort){slices.sort(function(x,y){return x.start-y.start;});}
2015-06-14 13:52:57 -06:00
var findLevel=function(sliceToPut,rows,n){if(n>=rows.length)
return true;var subRow=rows[n];var lastSliceInSubRow=subRow[subRow.length-1];if(sliceToPut.start>=lastSliceInSubRow.end){if(sliceToPut.subSlices===undefined||sliceToPut.subSlices.length===0){return true;}
for(var i=0;i< sliceToPut.subSlices.length ; i + + ) { if ( ! findLevel ( sliceToPut . subSlices [ i ] , rows , n + 1 ) )
return false;}
return true;}
return false;}
var subRows=[];for(var i=0;i< slices.length ; i + + ) { var slice = slices[i];var found = false;var index = subRows.length;for(var j = 0;j<subRows.length;j++){if(findLevel(slice,subRows,j)){found=true;index=j;break;}}
if(!found)
subRows.push([]);subRows[index].push(slice);var fitSubSlicesRecursively=function(subSlices,level,rows){if(subSlices===undefined||subSlices.length===0)
return;if(level===rows.length)
rows.push([]);for(var h=0;h< subSlices.length ; h + + ) { rows [ level ] . push ( subSlices [ h ] ) ; fitSubSlicesRecursively ( subSlices [ h ] . subSlices , level + 1 , rows ) ; } }
fitSubSlicesRecursively(slice.subSlices,index+1,subRows);}
2015-06-18 08:27:29 -06:00
return subRows;}};return{AsyncSliceGroupTrack:AsyncSliceGroupTrack};});'use strict';tr.exportTo('tr.ui.tracks',function(){var ThreadTrack=tr.ui.b.define('thread-track',tr.ui.tracks.ContainerTrack);ThreadTrack.prototype={__proto__:tr.ui.tracks.ContainerTrack.prototype,decorate:function(viewport){tr.ui.tracks.ContainerTrack.prototype.decorate.call(this,viewport);this.classList.add('thread-track');},get thread(){return this.thread_;},set thread(thread){this.thread_=thread;this.updateContents_();},get hasVisibleContent(){return this.tracks_.length>0;},get eventContainer(){return this.thread;},addContainersToTrackMap:function(containerToTrackMap){containerToTrackMap.addContainer(this.thread,this);for(var i=0;i< this.childNodes.length ; + + i )
2015-06-14 13:52:57 -06:00
this.childNodes[i].addContainersToTrackMap(containerToTrackMap);},updateContents_:function(){this.detach();if(!this.thread_)
return;this.heading=this.thread_.userFriendlyName+': ';this.tooltip=this.thread_.userFriendlyDetails;if(this.thread_.asyncSliceGroup.length)
2015-06-18 08:27:29 -06:00
this.appendAsyncSliceTracks_();this.appendThreadSamplesTracks_();if(this.thread_.timeSlices){var timeSlicesTrack=new tr.ui.tracks.SliceTrack(this.viewport);timeSlicesTrack.heading='';timeSlicesTrack.height=tr.ui.b.THIN_SLICE_HEIGHT+'px';timeSlicesTrack.slices=this.thread_.timeSlices;if(timeSlicesTrack.hasVisibleContent)
2015-06-14 13:52:57 -06:00
this.appendChild(timeSlicesTrack);}
2015-06-18 08:27:29 -06:00
if(this.thread_.sliceGroup.length){var track=new tr.ui.tracks.SliceGroupTrack(this.viewport);track.heading=this.thread_.userFriendlyName;track.tooltip=this.thread_.userFriendlyDetails;track.group=this.thread_.sliceGroup;if(track.hasVisibleContent)
this.appendChild(track);}},appendAsyncSliceTracks_:function(){var subGroups=this.thread_.asyncSliceGroup.viewSubGroups;subGroups.forEach(function(subGroup){var asyncTrack=new tr.ui.tracks.AsyncSliceGroupTrack(this.viewport);var title=subGroup.slices[0].viewSubGroupTitle;asyncTrack.group=subGroup;asyncTrack.heading=title;if(asyncTrack.hasVisibleContent)
2015-06-14 13:52:57 -06:00
this.appendChild(asyncTrack);},this);},appendThreadSamplesTracks_:function(){var threadSamples=this.thread_.samples;if(threadSamples===undefined||threadSamples.length===0)
return;var samplesByTitle={};threadSamples.forEach(function(sample){if(samplesByTitle[sample.title]===undefined)
2015-06-18 08:27:29 -06:00
samplesByTitle[sample.title]=[];samplesByTitle[sample.title].push(sample);});var sampleTitles=tr.b.dictionaryKeys(samplesByTitle);sampleTitles.sort();sampleTitles.forEach(function(sampleTitle){var samples=samplesByTitle[sampleTitle];var samplesTrack=new tr.ui.tracks.SampleTrack(this.viewport);samplesTrack.group=this.thread_;samplesTrack.samples=samples;samplesTrack.heading=this.thread_.userFriendlyName+': '+
2015-06-14 13:52:57 -06:00
sampleTitle;samplesTrack.tooltip=this.thread_.userFriendlyDetails;samplesTrack.selectionGenerator=function(){var selection=new tr.c.Selection();for(var i=0;i< samplesTrack.samples.length ; i + + ) { selection . push ( samplesTrack . samples [ i ] ) ; }
return selection;};this.appendChild(samplesTrack);},this);},collapsedDidChange:function(collapsed){if(collapsed){var h=parseInt(this.tracks[0].height);for(var i=0;i< this.tracks.length ; + + i ) { if ( h > 2){this.tracks[i].height=Math.floor(h)+'px';}else{this.tracks[i].style.display='none';}
2015-06-18 08:27:29 -06:00
h=h*0.5;}}else{for(var i=0;i< this.tracks.length ; + + i ) { this . tracks [ i ] . height = this.tracks[0].height;this.tracks[i].style.display='';}}}};return{ThreadTrack:ThreadTrack};});'use strict ' ; tr . exportTo ( ' tr . ui . tracks ' , function ( ) { var ObjectSnapshotView = tr.ui.analysis.ObjectSnapshotView;var ObjectInstanceView = tr.ui.analysis.ObjectInstanceView;var SpacingTrack = tr.ui.tracks.SpacingTrack;var ProcessTrackBase = tr.ui.b.define('process-track-base',tr.ui.tracks.ContainerTrack);ProcessTrackBase.prototype={__proto__:tr.ui.tracks.ContainerTrack.prototype,decorate:function(viewport){tr.ui.tracks.ContainerTrack.prototype.decorate.call(this,viewport);this.processBase_=undefined;this.classList.add('process-track-base');this.classList.add('expanded');this.processNameEl_=tr.ui.b.createSpan();this.processNameEl_.classList.add('process-track-name');this.headerEl_=tr.ui.b.createDiv({className:'process-track-header'});this.headerEl_.appendChild(this.processNameEl_);this.headerEl_.addEventListener('click',this.onHeaderClick_.bind(this));this.appendChild(this.headerEl_);},get processBase ( ) { return this . processBase_ ; } , set processBase ( processBase ) { this . processBase_ = processBase;if(this.processBase_){var modelSettings = new tr . model . ModelSettings ( this . processBase_ . model ) ; var defaultValue = this.processBase_.important;this.expanded=modelSettings.getSettingFor(this.processBase_,'expanded',defaultValue);}
2015-06-14 13:52:57 -06:00
this.updateContents_();},get expanded(){return this.classList.contains('expanded');},set expanded(expanded){expanded=!!expanded;if(this.expanded===expanded)
return;this.classList.toggle('expanded');this.viewport_.dispatchChangeEvent();if(!this.processBase_)
return;var modelSettings=new tr.model.ModelSettings(this.processBase_.model);modelSettings.setSettingFor(this.processBase_,'expanded',expanded);this.updateContents_();this.viewport.rebuildEventToTrackMap();this.viewport.rebuildContainerToTrackMap();},get hasVisibleContent(){if(this.expanded)
return this.children.length>1;return true;},onHeaderClick_:function(e){e.stopPropagation();e.preventDefault();this.expanded=!this.expanded;},updateContents_:function(){this.tracks_.forEach(function(track){this.removeChild(track);},this);if(!this.processBase_)
return;this.processNameEl_.textContent=this.processBase_.userFriendlyName;this.headerEl_.title=this.processBase_.userFriendlyDetails;this.willAppendTracks_();if(this.expanded){this.appendMemoryDumpTrack_();this.appendObjectInstanceTracks_();this.appendCounterTracks_();this.appendFrameTrack_();this.appendThreadTracks_();}else{this.appendSummaryTrack_();}
2015-06-18 08:27:29 -06:00
this.didAppendTracks_();},addEventsToTrackMap:function(eventToTrackMap){this.tracks_.forEach(function(track){track.addEventsToTrackMap(eventToTrackMap);});},willAppendTracks_:function(){},didAppendTracks_:function(){},appendMemoryDumpTrack_:function(){},appendSummaryTrack_:function(){var track=new tr.ui.tracks.ProcessSummaryTrack(this.viewport);track.process=this.process;if(!track.hasVisibleContent)
2015-06-14 13:52:57 -06:00
return;this.appendChild(track);},appendFrameTrack_:function(){var frames=this.process?this.process.frames:undefined;if(!frames||!frames.length)
2015-06-18 08:27:29 -06:00
return;var track=new tr.ui.tracks.FrameTrack(this.viewport);track.frames=frames;this.appendChild(track);this.backgroundProvider=track;},appendObjectInstanceTracks_:function(){var instancesByTypeName=this.processBase_.objects.getAllInstancesByTypeName();var instanceTypeNames=tr.b.dictionaryKeys(instancesByTypeName);instanceTypeNames.sort();var didAppendAtLeastOneTrack=false;instanceTypeNames.forEach(function(typeName){var allInstances=instancesByTypeName[typeName];var instanceViewInfo=ObjectInstanceView.getTypeInfo(undefined,typeName);var snapshotViewInfo=ObjectSnapshotView.getTypeInfo(undefined,typeName);if(instanceViewInfo& & !instanceViewInfo.metadata.showInTrackView)
2015-06-14 13:52:57 -06:00
instanceViewInfo=undefined;if(snapshotViewInfo& & !snapshotViewInfo.metadata.showInTrackView)
snapshotViewInfo=undefined;var hasViewInfo=instanceViewInfo||snapshotViewInfo;var visibleInstances=[];for(var i=0;i< allInstances.length ; i + + ) { var instance = allInstances[i];if(instance.snapshots.length===0)
continue;if(instance.hasImplicitSnapshots& & !hasViewInfo)
continue;visibleInstances.push(instance);}
if(visibleInstances.length===0)
2015-06-18 08:27:29 -06:00
return;var trackConstructor=tr.ui.tracks.ObjectInstanceTrack.getConstructor(undefined,typeName);if(!trackConstructor){var snapshotViewInfo=ObjectSnapshotView.getTypeInfo(undefined,typeName);if(snapshotViewInfo&&snapshotViewInfo.metadata.showInstances){trackConstructor=tr.ui.tracks.ObjectInstanceGroupTrack; }else{trackConstructor=tr.ui.tracks.ObjectInstanceTrack;}}
2015-06-14 13:52:57 -06:00
var track=new trackConstructor(this.viewport);track.objectInstances=visibleInstances;this.appendChild(track);didAppendAtLeastOneTrack=true;},this);if(didAppendAtLeastOneTrack)
2015-06-18 08:27:29 -06:00
this.appendChild(new SpacingTrack(this.viewport));},appendCounterTracks_:function(){var counters=tr.b.dictionaryValues(this.processBase.counters);counters.sort(tr.model.Counter.compare);counters.forEach(function(counter){var track=new tr.ui.tracks.CounterTrack(this.viewport);track.counter=counter;this.appendChild(track);this.appendChild(new SpacingTrack(this.viewport));}.bind(this));},appendThreadTracks_:function(){var threads=tr.b.dictionaryValues(this.processBase.threads);threads.sort(tr.model.Thread.compare);threads.forEach(function(thread){var track=new tr.ui.tracks.ThreadTrack(this.viewport);track.thread=thread;if(!track.hasVisibleContent)
return;this.appendChild(track);this.appendChild(new SpacingTrack(this.viewport));}.bind(this));}};return{ProcessTrackBase:ProcessTrackBase};});'use strict';tr.exportTo('tr.ui.tracks',function(){var CpuTrack=tr.ui.b.define('cpu-track',tr.ui.tracks.ContainerTrack);CpuTrack.prototype={__proto__:tr.ui.tracks.ContainerTrack.prototype,decorate:function(viewport){tr.ui.tracks.ContainerTrack.prototype.decorate.call(this,viewport);this.classList.add('cpu-track');this.detailedMode_=true;},get cpu(){return this.cpu_;},set cpu(cpu){this.cpu_=cpu;this.updateContents_();},get detailedMode(){return this.detailedMode_;},set detailedMode(detailedMode){this.detailedMode_=detailedMode;this.updateContents_();},get tooltip(){return this.tooltip_;},set tooltip(value){this.tooltip_=value;this.updateContents_();},get hasVisibleContent(){if(this.cpu_===undefined)
2015-06-14 13:52:57 -06:00
return false;var cpu=this.cpu_;if(cpu.slices.length)
return true;if(cpu.samples& & cpu.samples.length)
return true;if(tr.b.dictionaryLength(cpu.counters)>0)
return true;return false;},updateContents_:function(){this.detach();if(!this.cpu_)
2015-06-18 08:27:29 -06:00
return;var slices=this.cpu_.slices;if(slices.length){var track=new tr.ui.tracks.SliceTrack(this.viewport);track.slices=slices;track.heading=this.cpu_.userFriendlyName+':';this.appendChild(track);}
if(this.detailedMode_){this.appendSamplesTracks_();for(var counterName in this.cpu_.counters){var counter=this.cpu_.counters[counterName];track=new tr.ui.tracks.CounterTrack(this.viewport);track.heading=this.cpu_.userFriendlyName+' '+
2015-06-14 13:52:57 -06:00
counter.name+':';track.counter=counter;this.appendChild(track);}}},appendSamplesTracks_:function(){var samples=this.cpu_.samples;if(samples===undefined||samples.length===0)
return;var samplesByTitle={};samples.forEach(function(sample){if(samplesByTitle[sample.title]===undefined)
2015-06-18 08:27:29 -06:00
samplesByTitle[sample.title]=[];samplesByTitle[sample.title].push(sample);});var sampleTitles=tr.b.dictionaryKeys(samplesByTitle);sampleTitles.sort();sampleTitles.forEach(function(sampleTitle){var samples=samplesByTitle[sampleTitle];var samplesTrack=new tr.ui.tracks.SliceTrack(this.viewport);samplesTrack.group=this.cpu_;samplesTrack.slices=samples;samplesTrack.heading=this.cpu_.userFriendlyName+': '+
2015-06-14 13:52:57 -06:00
sampleTitle;samplesTrack.tooltip=this.cpu_.userFriendlyDetails;samplesTrack.selectionGenerator=function(){var selection=new tr.c.Selection();for(var i=0;i< samplesTrack.slices.length ; i + + ) { selection . push ( samplesTrack . slices [ i ] ) ; }
2015-06-18 08:27:29 -06:00
return selection;};this.appendChild(samplesTrack);},this);}};return{CpuTrack:CpuTrack};});'use strict';tr.exportTo('tr.ui.tracks',function(){var Cpu=tr.model.Cpu;var CpuTrack=tr.ui.tracks.cpu_track;var ProcessTrackBase=tr.ui.tracks.ProcessTrackBase;var SpacingTrack=tr.ui.tracks.SpacingTrack;var KernelTrack=tr.ui.b.define('kernel-track',ProcessTrackBase);KernelTrack.prototype={__proto__:ProcessTrackBase.prototype,decorate:function(viewport){ProcessTrackBase.prototype.decorate.call(this,viewport);},set kernel(kernel){this.processBase=kernel;},get kernel(){return this.processBase;},get eventContainer(){return this.kernel;},get hasVisibleContent(){return this.children.length>1;},addContainersToTrackMap:function(containerToTrackMap){containerToTrackMap.addContainer(this.kernel,this);},willAppendTracks_:function(){var cpus=tr.b.dictionaryValues(this.kernel.cpus);cpus.sort(tr.model.Cpu.compare);var didAppendAtLeastOneTrack=false;for(var i=0;i< cpus.length ; + + i ) { var cpu = cpus[i];var track = new tr . ui . tracks . CpuTrack ( this . viewport ) ; track . detailedMode = this.expanded;track.cpu=cpu;if(!track.hasVisibleContent)
2015-06-14 13:52:57 -06:00
continue;this.appendChild(track);didAppendAtLeastOneTrack=true;}
if(didAppendAtLeastOneTrack)
2015-06-18 08:27:29 -06:00
this.appendChild(new SpacingTrack(this.viewport));}};return{KernelTrack:KernelTrack};});'use strict';tr.exportTo('tr.ui.tracks',function(){var AlertTrack=tr.ui.b.define('alert-track',tr.ui.tracks.LetterDotTrack);AlertTrack.prototype={__proto__:tr.ui.tracks.LetterDotTrack.prototype,decorate:function(viewport){tr.ui.tracks.LetterDotTrack.prototype.decorate.call(this,viewport);this.heading='Alerts';this.alerts_=undefined;},get alerts(){return this.alerts_;},set alerts(alerts){this.alerts_=alerts;if(alerts===undefined){this.items=undefined;return;}
this.items=this.alerts_.map(function(alert){return new tr.ui.tracks.LetterDot(alert,String.fromCharCode(9888),alert.colorId,alert.start);});}};return{AlertTrack:AlertTrack};});'use strict';tr.exportTo('tr.ui.tracks',function(){var ALLOCATOR_SIZE_ATTRIBUTE_NAME='size';function addDictionary(dstDict,srcDict){tr.b.iterItems(srcDict,function(key,value){var existingValue=dstDict[key];if(existingValue===undefined)
2015-06-14 13:52:57 -06:00
existingValue=0;dstDict[key]=existingValue+value;});}
function getProcessMemoryDumpAllocatorSizes(processMemoryDump){var allocatorDumps=processMemoryDump.memoryAllocatorDumps;if(allocatorDumps===undefined)
return{};var allocatorSizes={};allocatorDumps.forEach(function(allocatorDump){if(allocatorDump.fullName==='tracing')
2015-06-18 08:27:29 -06:00
return;var allocatorSize=allocatorDump.attributes[ALLOCATOR_SIZE_ATTRIBUTE_NAME];if(allocatorSize===undefined)
2015-06-14 13:52:57 -06:00
return;var allocatorSizeValue=allocatorSize.value;if(allocatorSizeValue===undefined)
return;allocatorSizes[allocatorDump.fullName]=allocatorSizeValue;});return allocatorSizes;};function getGlobalMemoryDumpAllocatorSizes(globalMemoryDump){var globalAllocatorSizes={};tr.b.iterItems(globalMemoryDump.processMemoryDumps,function(pid,processMemoryDump){addDictionary(globalAllocatorSizes,getProcessMemoryDumpAllocatorSizes(processMemoryDump));});return globalAllocatorSizes;}
function buildAllocatedMemoryChartSeries(memoryDumps,memoryDumpToAllocatorSizesFn){var allocatorNameToPoints={};var dumpsData=memoryDumps.map(function(memoryDump){var allocatorSizes=memoryDumpToAllocatorSizesFn(memoryDump);tr.b.iterItems(allocatorSizes,function(allocatorName){allocatorNameToPoints[allocatorName]=[];});return{dump:memoryDump,sizes:allocatorSizes};});if(Object.keys(allocatorNameToPoints).length===0)
2015-06-18 08:27:29 -06:00
return undefined;dumpsData.forEach(function(dumpData){var memoryDump=dumpData.dump;var allocatorSizes=dumpData.sizes;tr.b.iterItems(allocatorNameToPoints,function(allocatorName,points){var allocatorSize=allocatorSizes[allocatorName]||0;points.push(new tr.ui.tracks.ChartPoint(memoryDump,memoryDump.start,allocatorSize));});});var axis=new tr.ui.tracks.ChartAxis(0);var series=[];tr.b.iterItems(allocatorNameToPoints,function(allocatorName,points){var colorId=tr.ui.b.getColorIdForGeneralPurposeString(allocatorName);var renderingConfig={chartType:tr.ui.tracks.ChartSeriesType.LINE,colorId:colorId};series.push(new tr.ui.tracks.ChartSeries(points,axis,renderingConfig));});return series;}
function buildMemoryLetterDots(memoryDumps){var memoryColorId=tr.ui.b.getColorIdForReservedName('memory_dump');return memoryDumps.map(function(memoryDump){return new tr.ui.tracks.LetterDot(memoryDump,'M',memoryColorId,memoryDump.start);});}
2015-06-14 13:52:57 -06:00
function buildGlobalUsedMemoryChartSeries(globalMemoryDumps){var containsVmRegions=globalMemoryDumps.some(function(globalDump){for(var pid in globalDump.processMemoryDumps)
if(globalDump.processMemoryDumps[pid].mostRecentVmRegions)
return true;return false;});if(!containsVmRegions)
return undefined;var pidToProcess={};globalMemoryDumps.forEach(function(globalDump){tr.b.iterItems(globalDump.processMemoryDumps,function(pid,processDump){pidToProcess[pid]=processDump.process;});});var pidToPoints={};tr.b.iterItems(pidToProcess,function(pid,process){pidToPoints[pid]=[];});globalMemoryDumps.forEach(function(globalDump){var pssBase=0;tr.b.iterItems(pidToPoints,function(pid,points){var processMemoryDump=globalDump.processMemoryDumps[pid];var pss;if(processMemoryDump===undefined){pss=0;}else{pss=processMemoryDump.getMostRecentTotalVmRegionStat('proportionalResident');if(pss===undefined){pss=0;}}
2015-06-18 08:27:29 -06:00
var cumulativePss=pssBase+pss;points.push(new tr.ui.tracks.ChartPoint(globalDump,globalDump.start,cumulativePss,pssBase));pssBase=cumulativePss;});});var axis=new tr.ui.tracks.ChartAxis(0);var series=[];tr.b.iterItems(pidToPoints,function(pid,points){var process=pidToProcess[pid];var colorId=tr.ui.b.getColorIdForGeneralPurposeString(process.userFriendlyName);var renderingConfig={chartType:tr.ui.tracks.ChartSeriesType.AREA,colorId:colorId,backgroundOpacity:0.8};series.push(new tr.ui.tracks.ChartSeries(points,axis,renderingConfig));});series.reverse();return series;}
2015-06-14 13:52:57 -06:00
function buildProcessAllocatedMemoryChartSeries(processMemoryDumps){return buildAllocatedMemoryChartSeries(processMemoryDumps,getProcessMemoryDumpAllocatorSizes);}
function buildGlobalAllocatedMemoryChartSeries(globalMemoryDumps){return buildAllocatedMemoryChartSeries(globalMemoryDumps,getGlobalMemoryDumpAllocatorSizes);}
2015-06-18 08:27:29 -06:00
return{buildMemoryLetterDots:buildMemoryLetterDots,buildGlobalUsedMemoryChartSeries:buildGlobalUsedMemoryChartSeries,buildProcessAllocatedMemoryChartSeries:buildProcessAllocatedMemoryChartSeries,buildGlobalAllocatedMemoryChartSeries:buildGlobalAllocatedMemoryChartSeries};});'use strict';tr.exportTo('tr.ui.tracks',function(){var USED_MEMORY_TRACK_HEIGHT=50;var ALLOCATED_MEMORY_TRACK_HEIGHT=50;var GlobalMemoryDumpTrack=tr.ui.b.define('global-memory-dump-track',tr.ui.tracks.ContainerTrack);GlobalMemoryDumpTrack.prototype={__proto__:tr.ui.tracks.ContainerTrack.prototype,decorate:function(viewport){tr.ui.tracks.ContainerTrack.prototype.decorate.call(this,viewport);this.memoryDumps_=undefined;},get memoryDumps(){return this.memoryDumps_;},set memoryDumps(memoryDumps){this.memoryDumps_=memoryDumps;this.updateContents_();},updateContents_:function(){this.tracks_.forEach(function(track){this.removeChild(track);},this);if(!this.memoryDumps_||!this.memoryDumps_.length)
return;this.appendDumpDotsTrack_();this.appendUsedMemoryTrack_();this.appendAllocatedMemoryTrack_();},appendDumpDotsTrack_:function(){var items=tr.ui.tracks.buildMemoryLetterDots(this.memoryDumps_);if(!items)
return;var track=new tr.ui.tracks.LetterDotTrack(this.viewport);track.heading='Memory Dumps';track.items=items;this.appendChild(track);},appendUsedMemoryTrack_:function(){var series=tr.ui.tracks.buildGlobalUsedMemoryChartSeries(this.memoryDumps_);if(!series)
return;var track=new tr.ui.tracks.ChartTrack(this.viewport);track.heading='Used memory (per process)';track.height=USED_MEMORY_TRACK_HEIGHT+'px';track.series=series;track.autoSetAllAxes({expandMax:true});this.appendChild(track);},appendAllocatedMemoryTrack_:function(){var series=tr.ui.tracks.buildGlobalAllocatedMemoryChartSeries(this.memoryDumps_);if(!series)
return;var track=new tr.ui.tracks.ChartTrack(this.viewport);track.heading='Allocated memory (per allocator)';track.height=ALLOCATED_MEMORY_TRACK_HEIGHT+'px';track.series=series;track.autoSetAllAxes({expandMax:true});this.appendChild(track);}};return{GlobalMemoryDumpTrack:GlobalMemoryDumpTrack};});'use strict';tr.exportTo('tr.ui.tracks',function(){var ALLOCATED_MEMORY_TRACK_HEIGHT=50;var ProcessMemoryDumpTrack=tr.ui.b.define('process-memory-dump-track',tr.ui.tracks.ContainerTrack);ProcessMemoryDumpTrack.prototype={__proto__:tr.ui.tracks.ContainerTrack.prototype,decorate:function(viewport){tr.ui.tracks.ContainerTrack.prototype.decorate.call(this,viewport);this.memoryDumps_=undefined;},get memoryDumps(){return this.memoryDumps_;},set memoryDumps(memoryDumps){this.memoryDumps_=memoryDumps;this.updateContents_();},updateContents_:function(){this.tracks_.forEach(function(track){this.removeChild(track);},this);if(!this.memoryDumps_||!this.memoryDumps_.length)
return;this.appendAllocatedMemoryTrack_();},appendAllocatedMemoryTrack_:function(){var series=tr.ui.tracks.buildProcessAllocatedMemoryChartSeries(this.memoryDumps_);if(!series)
return;var track=new tr.ui.tracks.ChartTrack(this.viewport);track.heading='Allocated memory (per allocator)';track.height=ALLOCATED_MEMORY_TRACK_HEIGHT+'px';track.series=series;track.autoSetAllAxes({expandMax:true});this.appendChild(track);}};return{ProcessMemoryDumpTrack:ProcessMemoryDumpTrack};});'use strict';tr.exportTo('tr.ui.tracks',function(){var ProcessTrackBase=tr.ui.tracks.ProcessTrackBase;var ProcessTrack=tr.ui.b.define('process-track',ProcessTrackBase);ProcessTrack.prototype={__proto__:ProcessTrackBase.prototype,decorate:function(viewport){tr.ui.tracks.ProcessTrackBase.prototype.decorate.call(this,viewport);},drawTrack:function(type){switch(type){case tr.ui.tracks.DrawType.INSTANT_EVENT:if(!this.processBase.instantEvents||this.processBase.instantEvents.length===0)
break;var ctx=this.context();var pixelRatio=window.devicePixelRatio||1;var bounds=this.getBoundingClientRect();var canvasBounds=ctx.canvas.getBoundingClientRect();ctx.save();ctx.translate(0,pixelRatio*(bounds.top-canvasBounds.top));var dt=this.viewport.currentDisplayTransform;var viewLWorld=dt.xViewToWorld(0);var viewRWorld=dt.xViewToWorld(bounds.width*pixelRatio);tr.ui.b.drawInstantSlicesAsLines(ctx,this.viewport.currentDisplayTransform,viewLWorld,viewRWorld,bounds.height,this.processBase.instantEvents,2);ctx.restore();break;case tr.ui.tracks.DrawType.BACKGROUND:this.drawBackground_();return;}
tr.ui.tracks.ContainerTrack.prototype.drawTrack.call(this,type);},drawBackground_:function(){var ctx=this.context();var canvasBounds=ctx.canvas.getBoundingClientRect();var pixelRatio=window.devicePixelRatio||1;var draw=false;ctx.fillStyle='#eee';for(var i=0;i< this.children.length ; + + i ) { if ( ! ( this . children [ i ] instanceof tr . ui . tracks . Track ) | | ( this . children [ i ] instanceof tr . ui . tracks . SpacingTrack ) )
2015-06-14 13:52:57 -06:00
continue;draw=!draw;if(!draw)
2015-06-18 08:27:29 -06:00
continue;var bounds=this.children[i].getBoundingClientRect();ctx.fillRect(0,pixelRatio*(bounds.top-canvasBounds.top),ctx.canvas.width,pixelRatio*bounds.height);}},set process(process){this.processBase=process;},get process(){return this.processBase;},get eventContainer(){return this.process;},addContainersToTrackMap:function(containerToTrackMap){containerToTrackMap.addContainer(this.process,this);this.tracks_.forEach(function(track){track.addContainersToTrackMap(containerToTrackMap);});},appendMemoryDumpTrack_:function(){var processMemoryDumps=this.process.memoryDumps;if(processMemoryDumps.length){var pmdt=new tr.ui.tracks.ProcessMemoryDumpTrack(this.viewport_);pmdt.memoryDumps=processMemoryDumps;this.appendChild(pmdt);}},addIntersectingEventsInRangeToSelectionInWorldSpace:function(loWX,hiWX,viewPixWidthWorld,selection){function onPickHit(instantEvent){selection.push(instantEvent);}
tr.b.iterateOverIntersectingIntervals(this.processBase.instantEvents,function(x){return x.start;},function(x){return x.duration;},loWX,hiWX,onPickHit.bind(this));tr.ui.tracks.ContainerTrack.prototype.addIntersectingEventsInRangeToSelectionInWorldSpace.apply(this,arguments);},addClosestEventToSelection:function(worldX,worldMaxDist,loY,hiY,selection){this.addClosestInstantEventToSelection(this.processBase.instantEvents,worldX,worldMaxDist,selection);tr.ui.tracks.ContainerTrack.prototype.addClosestEventToSelection.apply(this,arguments);}};return{ProcessTrack:ProcessTrack};});'use strict';tr.exportTo('tr.ui.tracks',function(){function HackyMultiRowTrack(viewport,model){var mrt=new tr.ui.tracks.MultiRowTrack(viewport);mrt.heading='Interactions';mrt.buildSubRows_=function(slices){slices.sort(function(x,y){var r=x.title.localeCompare(y.title);if(r)
return r;return x.start-y.start;});return tr.ui.tracks.AsyncSliceGroupTrack.prototype.buildSubRows_.call({},slices,true);};mrt.addSubTrack_=function(slices){var track=new tr.ui.tracks.SliceTrack(this.viewport);track.slices=slices;this.appendChild(track);return track;};mrt.setItemsToGroup(model.interaction_records,{guid:tr.b.GUID.allocate(),model:model,getSettingsKey:function(){return undefined;}});return mrt;}
var SelectionState=tr.model.SelectionState;var EventPresenter=tr.ui.b.EventPresenter;var ModelTrack=tr.ui.b.define('model-track',tr.ui.tracks.ContainerTrack);ModelTrack.prototype={__proto__:tr.ui.tracks.ContainerTrack.prototype,decorate:function(viewport){tr.ui.tracks.ContainerTrack.prototype.decorate.call(this,viewport);this.classList.add('model-track');var typeInfos=tr.ui.tracks.Highlighter.getAllRegisteredTypeInfos();this.highlighters_=typeInfos.map(function(typeInfo){return new typeInfo.constructor(viewport);});this.upperMode_=false;this.annotationViews_=[];},get upperMode(){return this.upperMode_;},set upperMode(upperMode){this.upperMode_=upperMode;this.updateContents_();},detach:function(){tr.ui.tracks.ContainerTrack.prototype.detach.call(this);},get model(){return this.model_;},set model(model){this.model_=model;this.updateContents_();this.model_.addEventListener('annotationChange',this.updateAnnotations_.bind(this));},get hasVisibleContent(){return this.children.length>0;},updateContents_:function(){this.textContent='';if(!this.model_)
2015-06-14 13:52:57 -06:00
return;if(this.upperMode_)
this.updateContentsForUpperMode_();else
this.updateContentsForLowerMode_();},updateContentsForUpperMode_:function(){},updateContentsForLowerMode_:function(){if(this.model_.interaction_records.length){var mrt=new HackyMultiRowTrack(this.viewport_,this.model_);this.appendChild(mrt);}
2015-06-18 08:27:29 -06:00
if(this.model_.alerts.length){var at=new tr.ui.tracks.AlertTrack(this.viewport_);at.alerts=this.model_.alerts;this.appendChild(at);}
if(this.model_.globalMemoryDumps.length){var gmdt=new tr.ui.tracks.GlobalMemoryDumpTrack(this.viewport_);gmdt.memoryDumps=this.model_.globalMemoryDumps;this.appendChild(gmdt);}
this.appendKernelTrack_();var processes=this.model_.getAllProcesses();processes.sort(tr.model.Process.compare);for(var i=0;i< processes.length ; + + i ) { var process = processes[i];var track = new tr . ui . tracks . ProcessTrack ( this . viewport ) ; track . process = process;if(!track.hasVisibleContent)
2015-06-14 13:52:57 -06:00
continue;this.appendChild(track);}
this.viewport_.rebuildEventToTrackMap();this.viewport_.rebuildContainerToTrackMap();for(var i=0;i< this.highlighters_.length ; i + + ) { this . highlighters_ [ i ] . processModel ( this . model_ ) ; }
this.updateAnnotations_();},updateAnnotations_:function(){this.annotationViews_=[];var annotations=this.model_.getAllAnnotations();for(var i=0;i< annotations.length ; i + + ) { this . annotationViews_ . push ( annotations [ i ] . getOrCreateView ( this . viewport_ ) ) ; }
this.invalidateDrawingContainer();},addEventsToTrackMap:function(eventToTrackMap){if(!this.model_)
return;var tracks=this.children;for(var i=0;i< tracks.length ; + + i )
tracks[i].addEventsToTrackMap(eventToTrackMap);if(this.instantEvents===undefined)
return;var vp=this.viewport_;this.instantEvents.forEach(function(ev){eventToTrackMap.addEvent(ev,this);}.bind(this));},addContainersToTrackMap:function(containerToTrackMap){var tracks=this.children;for(var i=0;i< tracks.length ; + + i )
2015-06-18 08:27:29 -06:00
tracks[i].addContainersToTrackMap(containerToTrackMap);},appendKernelTrack_:function(){var kernel=this.model.kernel;var track=new tr.ui.tracks.KernelTrack(this.viewport);track.kernel=this.model.kernel;if(!track.hasVisibleContent)
2015-06-14 13:52:57 -06:00
return;this.appendChild(track);},drawTrack:function(type){var ctx=this.context();if(!this.model_)
2015-06-18 08:27:29 -06:00
return;var pixelRatio=window.devicePixelRatio||1;var bounds=this.getBoundingClientRect();var canvasBounds=ctx.canvas.getBoundingClientRect();ctx.save();ctx.translate(0,pixelRatio*(bounds.top-canvasBounds.top));var dt=this.viewport.currentDisplayTransform;var viewLWorld=dt.xViewToWorld(0);var viewRWorld=dt.xViewToWorld(bounds.width*pixelRatio);switch(type){case tr.ui.tracks.DrawType.GRID:this.viewport.drawMajorMarkLines(ctx);ctx.restore();return;case tr.ui.tracks.DrawType.FLOW_ARROWS:if(this.model_.flowIntervalTree.size===0){ctx.restore();return;}
this.drawFlowArrows_(viewLWorld,viewRWorld);ctx.restore();return;case tr.ui.tracks.DrawType.INSTANT_EVENT:if(!this.model_.instantEvents||this.model_.instantEvents.length===0)
break;tr.ui.b.drawInstantSlicesAsLines(ctx,this.viewport.currentDisplayTransform,viewLWorld,viewRWorld,bounds.height,this.model_.instantEvents,4);break;case tr.ui.tracks.DrawType.MARKERS:if(!this.viewport.interestRange.isEmpty){this.viewport.interestRange.draw(ctx,viewLWorld,viewRWorld);this.viewport.interestRange.drawIndicators(ctx,viewLWorld,viewRWorld);}
ctx.restore();return;case tr.ui.tracks.DrawType.HIGHLIGHTS:for(var i=0;i< this.highlighters_.length ; i + + ) { this . highlighters_ [ i ] . drawHighlight ( ctx , dt , viewLWorld , viewRWorld , bounds . height ) ; }
ctx.restore();return;case tr.ui.tracks.DrawType.ANNOTATIONS:for(var i=0;i< this.annotationViews_.length ; i + + ) { this . annotationViews_ [ i ] . draw ( ctx ) ; }
2015-06-14 13:52:57 -06:00
ctx.restore();return;}
2015-06-18 08:27:29 -06:00
ctx.restore();tr.ui.tracks.ContainerTrack.prototype.drawTrack.call(this,type);},drawFlowArrows_:function(viewLWorld,viewRWorld){var ctx=this.context();var dt=this.viewport.currentDisplayTransform;dt.applyTransformToCanvas(ctx);var pixWidth=dt.xViewVectorToWorld(1);ctx.strokeStyle='rgba(0, 0, 0, 0.4)';ctx.fillStyle='rgba(0, 0, 0, 0.4)';ctx.lineWidth=pixWidth>1.0?1:pixWidth;var events=this.model_.flowIntervalTree.findIntersection(viewLWorld,viewRWorld);var onlyHighlighted=!this.viewport.showFlowEvents;var canvasBounds=ctx.canvas.getBoundingClientRect();for(var i=0;i< events.length ; + + i ) { if ( onlyHighlighted & & events [ i ] . selectionState ! = = SelectionState . SELECTED & & events [ i ] . selectionState ! = = SelectionState . HIGHLIGHTED )
2015-06-14 13:52:57 -06:00
continue;this.drawFlowArrow_(ctx,events[i],canvasBounds,pixWidth);}},drawFlowArrow_:function(ctx,flowEvent,canvasBounds,pixWidth){var pixelRatio=window.devicePixelRatio||1;var startTrack=this.viewport.trackForEvent(flowEvent.startSlice);var endTrack=this.viewport.trackForEvent(flowEvent.endSlice);if(startTrack===undefined||endTrack===undefined)
return;var startBounds=startTrack.getBoundingClientRect();var endBounds=endTrack.getBoundingClientRect();if(flowEvent.selectionState==SelectionState.SELECTED){ctx.shadowBlur=1;ctx.shadowColor='red';ctx.shadowOffsety=2;ctx.strokeStyle='red';}else if(flowEvent.selectionState==SelectionState.HIGHLIGHTED){ctx.shadowBlur=1;ctx.shadowColor='red';ctx.shadowOffsety=2;ctx.strokeStyle='red';}else if(flowEvent.selectionState==SelectionState.DIMMED){ctx.shadowBlur=0;ctx.shadowOffsetX=0;ctx.strokeStyle='rgba(0, 0, 0, 0.2)';}else{var hasBoost=false;var startSlice=flowEvent.startSlice;hasBoost|=startSlice.selectionState===SelectionState.SELECTED;hasBoost|=startSlice.selectionState===SelectionState.HIGHLIGHTED;var endSlice=flowEvent.endSlice;hasBoost|=endSlice.selectionState===SelectionState.SELECTED;hasBoost|=endSlice.selectionState===SelectionState.HIGHLIGHTED;if(hasBoost){ctx.shadowBlur=1;ctx.shadowColor='rgba(255, 0, 0, 0.4)';ctx.shadowOffsety=2;ctx.strokeStyle='rgba(255, 0, 0, 0.4)';}else{ctx.shadowBlur=0;ctx.shadowOffsetX=0;ctx.strokeStyle='rgba(0, 0, 0, 0.4)';}}
var startSize=startBounds.left+startBounds.top+
startBounds.bottom+startBounds.right;var endSize=endBounds.left+endBounds.top+
endBounds.bottom+endBounds.right;if(startSize===0& & endSize===0)
return;var startY=this.calculateTrackY_(startTrack,canvasBounds);var endY=this.calculateTrackY_(endTrack,canvasBounds);var pixelStartY=pixelRatio*startY;var pixelEndY=pixelRatio*endY;var half=(flowEvent.end-flowEvent.start)/2;ctx.beginPath();ctx.moveTo(flowEvent.start,pixelStartY);ctx.bezierCurveTo(flowEvent.start+half,pixelStartY,flowEvent.start+half,pixelEndY,flowEvent.end,pixelEndY);ctx.stroke();var arrowWidth=5*pixWidth*pixelRatio;var distance=flowEvent.end-flowEvent.start;if(distance< =(2*arrowWidth))
2015-06-18 08:27:29 -06:00
return;var tipX=flowEvent.end;var tipY=pixelEndY;var arrowHeight=(endBounds.height/4)*pixelRatio;tr.ui.b.drawTriangle(ctx,tipX,tipY,tipX-arrowWidth,tipY-arrowHeight,tipX-arrowWidth,tipY+arrowHeight);ctx.fill();},calculateTrackY_:function(track,canvasBounds){var bounds=track.getBoundingClientRect();var size=bounds.left+bounds.top+bounds.bottom+bounds.right;if(size===0)
2015-06-14 13:52:57 -06:00
return this.calculateTrackY_(track.parentNode,canvasBounds);return bounds.top-canvasBounds.top+(bounds.height/2);},addIntersectingEventsInRangeToSelectionInWorldSpace:function(loWX,hiWX,viewPixWidthWorld,selection){function onPickHit(instantEvent){selection.push(instantEvent);}
2015-06-18 08:27:29 -06:00
tr.b.iterateOverIntersectingIntervals(this.model_.instantEvents,function(x){return x.start;},function(x){return x.duration;},loWX,hiWX,onPickHit.bind(this));tr.ui.tracks.ContainerTrack.prototype.addIntersectingEventsInRangeToSelectionInWorldSpace.apply(this,arguments);},addClosestEventToSelection:function(worldX,worldMaxDist,loY,hiY,selection){this.addClosestInstantEventToSelection(this.model_.instantEvents,worldX,worldMaxDist,selection);tr.ui.tracks.ContainerTrack.prototype.addClosestEventToSelection.apply(this,arguments);}};return{ModelTrack:ModelTrack};});'use strict';tr.exportTo('tr.ui.tracks',function(){var RulerTrack=tr.ui.b.define('ruler-track',tr.ui.tracks.HeadingTrack);var logOf10=Math.log(10);function log10(x){return Math.log(x)/logOf10;}
RulerTrack.prototype={__proto__:tr.ui.tracks.HeadingTrack.prototype,decorate:function(viewport){tr.ui.tracks.HeadingTrack.prototype.decorate.call(this,viewport);this.classList.add('ruler-track');this.strings_secs_=[];this.strings_msecs_=[];this.strings_usecs_=[];this.strings_nsecs_=[];this.viewportChange_=this.viewportChange_.bind(this);viewport.addEventListener('change',this.viewportChange_);},detach:function(){tr.ui.tracks.HeadingTrack.prototype.detach.call(this);this.viewport.removeEventListener('change',this.viewportChange_);},viewportChange_:function(){if(this.viewport.interestRange.isEmpty)
2015-06-14 13:52:57 -06:00
this.classList.remove('tall-mode');else
2015-06-18 08:27:29 -06:00
this.classList.add('tall-mode');},draw:function(type,viewLWorld,viewRWorld){switch(type){case tr.ui.tracks.DrawType.GRID:this.drawGrid_(viewLWorld,viewRWorld);break;case tr.ui.tracks.DrawType.MARKERS:if(!this.viewport.interestRange.isEmpty)
2015-06-14 13:52:57 -06:00
this.viewport.interestRange.draw(this.context(),viewLWorld,viewRWorld);break;}},drawGrid_:function(viewLWorld,viewRWorld){var ctx=this.context();var pixelRatio=window.devicePixelRatio||1;var canvasBounds=ctx.canvas.getBoundingClientRect();var trackBounds=this.getBoundingClientRect();var width=canvasBounds.width*pixelRatio;var height=trackBounds.height*pixelRatio;var hasInterestRange=!this.viewport.interestRange.isEmpty;var rulerHeight=hasInterestRange?(height*2)/5:height;var vp=this.viewport;var dt=vp.currentDisplayTransform;var idealMajorMarkDistancePix=150*pixelRatio;var idealMajorMarkDistanceWorld=dt.xViewVectorToWorld(idealMajorMarkDistancePix);var majorMarkDistanceWorld;var conservativeGuess=Math.pow(10,Math.ceil(log10(idealMajorMarkDistanceWorld)));var divisors=[10,5,2,1];for(var i=0;i< divisors.length ; + + i ) { var tightenedGuess = conservativeGuess/divisors[i];if(dt.xWorldVectorToView(tightenedGuess)<idealMajorMarkDistancePix)
continue;majorMarkDistanceWorld=conservativeGuess/divisors[i-1];break;}
var unit;var unitDivisor;var tickLabels=undefined;if(majorMarkDistanceWorld< 0.0001 ) { unit = 'ns' ; unitDivisor = 0.000001;tickLabels=this.strings_nsecs_;}else if ( majorMarkDistanceWorld < 0 . 1 ) { unit = 'us' ; unitDivisor = 0.001;tickLabels=this.strings_usecs_;}else if ( majorMarkDistanceWorld < 100 ) { unit = 'ms' ; unitDivisor = 1;tickLabels=this.strings_msecs_;}else{unit='s';unitDivisor=1000;tickLabels=this.strings_secs_;}
var numTicksPerMajor=5;var minorMarkDistanceWorld=majorMarkDistanceWorld/numTicksPerMajor;var minorMarkDistancePx=dt.xWorldVectorToView(minorMarkDistanceWorld);var firstMajorMark=Math.floor(viewLWorld/majorMarkDistanceWorld)*majorMarkDistanceWorld;var minorTickH=Math.floor(rulerHeight*0.25);ctx.save();var pixelRatio=window.devicePixelRatio||1;ctx.lineWidth=Math.round(pixelRatio);var crispLineCorrection=(ctx.lineWidth%2)/2;ctx.translate(crispLineCorrection,-crispLineCorrection);ctx.fillStyle='rgb(0, 0, 0)';ctx.strokeStyle='rgb(0, 0, 0)';ctx.textAlign='left';ctx.textBaseline='top';ctx.font=(9*pixelRatio)+'px sans-serif';vp.majorMarkPositions=[];ctx.beginPath();for(var curX=firstMajorMark;curX< viewRWorld ; curX + = majorMarkDistanceWorld ) { var curXView = Math.floor(dt.xWorldToView(curX));var unitValue = curX/unitDivisor;var roundedUnitValue = Math.round(unitValue*100000)/100000;if(!tickLabels[roundedUnitValue])
2015-06-18 08:27:29 -06:00
tickLabels[roundedUnitValue]=roundedUnitValue+' '+unit;ctx.fillText(tickLabels[roundedUnitValue],curXView+(2*pixelRatio),0);vp.majorMarkPositions.push(curXView);tr.ui.b.drawLine(ctx,curXView,0,curXView,rulerHeight);for(var i=1;i< numTicksPerMajor ; + + i ) { var xView = Math.floor(curXView+minorMarkDistancePx*i);tr.ui.b.drawLine(ctx,xView,rulerHeight-minorTickH,xView,rulerHeight);}}
ctx.strokeStyle='rgb(0, 0, 0)';tr.ui.b.drawLine(ctx,0,height,width,height);ctx.stroke();if(!hasInterestRange)
return;tr.ui.b.drawLine(ctx,0,rulerHeight,width,rulerHeight);ctx.stroke();var displayDistance;var displayTextColor='rgb(0,0,0)';var arrowSpacing=10*pixelRatio;var arrowColor='rgb(128,121,121)';var arrowPosY=rulerHeight*1.75;var arrowWidthView=3*pixelRatio;var arrowLengthView=10*pixelRatio;var spaceForArrowsView=2*(arrowWidthView+arrowSpacing);ctx.textBaseline='middle';ctx.font=(14*pixelRatio)+'px sans-serif';var textPosY=arrowPosY;var interestRange=vp.interestRange;if(interestRange.range===0){var markerWorld=interestRange.min;var markerView=dt.xWorldToView(markerWorld);var displayValue=markerWorld/unitDivisor;displayValue=Math.abs((Math.round(displayValue*1000)/1000));var textToDraw=displayValue+' '+unit;var textLeftView=markerView+4*pixelRatio;var textWidthView=ctx.measureText(textToDraw).width;if(textLeftView+textWidthView>width)
2015-06-14 13:52:57 -06:00
textLeftView=markerView-4*pixelRatio-textWidthView;ctx.fillStyle=displayTextColor;ctx.fillText(textToDraw,textLeftView,textPosY);return;}
var leftMarker=interestRange.min;var rightMarker=interestRange.max;var leftMarkerView=dt.xWorldToView(leftMarker);var rightMarkerView=dt.xWorldToView(rightMarker);var distanceBetweenMarkers=interestRange.range;var distanceBetweenMarkersView=dt.xWorldVectorToView(distanceBetweenMarkers);var positionInMiddleOfMarkersView=leftMarkerView+(distanceBetweenMarkersView/2);if(distanceBetweenMarkers< 0.0001 ) { unit = 'ns' ; unitDivisor = 0.000001;}else if ( distanceBetweenMarkers < 0 . 1 ) { unit = 'us' ; unitDivisor = 0.001;}else if ( distanceBetweenMarkers < 100 ) { unit = 'ms' ; unitDivisor = 1;}else{unit='s';unitDivisor=1000;}
displayDistance=distanceBetweenMarkers/unitDivisor;var roundedDisplayDistance=Math.abs((Math.round(displayDistance*1000)/1000));var textToDraw=roundedDisplayDistance+' '+unit;var textWidthView=ctx.measureText(textToDraw).width;var spaceForArrowsAndTextView=textWidthView+spaceForArrowsView+arrowSpacing;var textLeftView=positionInMiddleOfMarkersView-textWidthView/2;var textRightView=textLeftView+textWidthView;if(spaceForArrowsAndTextView>distanceBetweenMarkersView){textLeftView=rightMarkerView+2*arrowSpacing;if(textLeftView+textWidthView>width)
2015-06-18 08:27:29 -06:00
textLeftView=leftMarkerView-2*arrowSpacing-textWidthView;ctx.fillStyle=displayTextColor;ctx.fillText(textToDraw,textLeftView,textPosY);ctx.strokeStyle=arrowColor;ctx.beginPath();tr.ui.b.drawLine(ctx,leftMarkerView,arrowPosY,rightMarkerView,arrowPosY);ctx.stroke();ctx.fillStyle=arrowColor;tr.ui.b.drawArrow(ctx,leftMarkerView-1.5*arrowSpacing,arrowPosY,leftMarkerView,arrowPosY,arrowLengthView,arrowWidthView);tr.ui.b.drawArrow(ctx,rightMarkerView+1.5*arrowSpacing,arrowPosY,rightMarkerView,arrowPosY,arrowLengthView,arrowWidthView);}else if(spaceForArrowsView< =distanceBetweenMarkersView){var leftArrowStart;var rightArrowStart;if(spaceForArrowsAndTextView< =distanceBetweenMarkersView){ctx.fillStyle=displayTextColor;ctx.fillText(textToDraw,textLeftView,textPosY);leftArrowStart=textLeftView-arrowSpacing;rightArrowStart=textRightView+arrowSpacing;}else{leftArrowStart=positionInMiddleOfMarkersView;rightArrowStart=positionInMiddleOfMarkersView;}
ctx.strokeStyle=arrowColor;ctx.fillStyle=arrowColor;tr.ui.b.drawArrow(ctx,leftArrowStart,arrowPosY,leftMarkerView,arrowPosY,arrowLengthView,arrowWidthView);tr.ui.b.drawArrow(ctx,rightArrowStart,arrowPosY,rightMarkerView,arrowPosY,arrowLengthView,arrowWidthView);}
2015-06-14 13:52:57 -06:00
ctx.restore();},addIntersectingEventsInRangeToSelection:function(loVX,hiVX,loY,hiY,selection){},addAllEventsMatchingFilterToSelection:function(filter,selection){}};return{RulerTrack:RulerTrack};});'use strict';tr.exportTo('tr.model',function(){function Annotation(){this.guid_=tr.b.GUID.allocate();this.view_=undefined;};Annotation.fromDictIfPossible=function(args){if(args.typeName===undefined)
throw new Error('Missing typeName argument');var typeInfo=Annotation.findTypeInfoMatching(function(typeInfo){return typeInfo.metadata.typeName===args.typeName;});if(typeInfo===undefined)
return undefined;return typeInfo.constructor.fromDict(args);};Annotation.fromDict=function(){throw new Error('Not implemented');}
Annotation.prototype={get guid(){return this.guid_;},onRemove:function(){},toDict:function(){throw new Error('Not implemented');},getOrCreateView:function(viewport){if(!this.view_)
this.view_=this.createView_(viewport);return this.view_;},createView_:function(){throw new Error('Not implemented');}};var options=new tr.b.ExtensionRegistryOptions(tr.b.BASIC_REGISTRY_MODE);options.mandatoryBaseType=Annotation;tr.b.decorateExtensionRegistry(Annotation,options);Annotation.addEventListener('will-register',function(e){if(!e.typeInfo.constructor.hasOwnProperty('fromDict'))
throw new Error('Must have fromDict method');if(!e.typeInfo.metadata.typeName)
2015-06-18 08:27:29 -06:00
throw new Error('Registered Annotations must provide typeName');});return{Annotation:Annotation};});'use strict';tr.exportTo('tr.ui.annotations',function(){function AnnotationView(viewport,annotation){}
AnnotationView.prototype={draw:function(ctx){throw new Error('Not implemented');}};return{AnnotationView:AnnotationView};});'use strict';tr.exportTo('tr.ui.annotations',function(){function XMarkerAnnotationView(viewport,annotation){this.viewport_=viewport;this.annotation_=annotation;}
XMarkerAnnotationView.prototype={__proto__:tr.ui.annotations.AnnotationView.prototype,draw:function(ctx){var dt=this.viewport_.currentDisplayTransform;var viewX=dt.xWorldToView(this.annotation_.timestamp);ctx.beginPath();tr.ui.b.drawLine(ctx,viewX,0,viewX,ctx.canvas.height);ctx.strokeStyle=this.annotation_.strokeStyle;ctx.stroke();}};return{XMarkerAnnotationView:XMarkerAnnotationView};});'use strict';tr.exportTo('tr.model',function(){function XMarkerAnnotation(timestamp){tr.model.Annotation.apply(this,arguments);this.timestamp=timestamp;this.strokeStyle='rgba(0, 0, 255, 0.5)';}
2015-06-14 13:52:57 -06:00
XMarkerAnnotation.fromDict=function(dict){return new XMarkerAnnotation(dict.args.timestamp);}
2015-06-18 08:27:29 -06:00
XMarkerAnnotation.prototype={__proto__:tr.model.Annotation.prototype,toDict:function(){return{typeName:'xmarker',args:{timestamp:this.timestamp}};},createView_:function(viewport){return new tr.ui.annotations.XMarkerAnnotationView(viewport,this);}};tr.model.Annotation.register(XMarkerAnnotation,{typeName:'xmarker'});return{XMarkerAnnotation:XMarkerAnnotation};});'use strict';tr.exportTo('tr.ui.b',function(){function KeyEventManager(opt_document){this.document_=opt_document||document;if(KeyEventManager.instance)
throw new Error('KeyEventManager is a singleton.');this.onEvent_=this.onEvent_.bind(this);this.document_.addEventListener('keydown',this.onEvent_);this.document_.addEventListener('keypress',this.onEvent_);this.document_.addEventListener('keyup',this.onEvent_);this.listeners_=[];}
KeyEventManager.instance=undefined;document.head.addEventListener('tr-unittest-will-run',function(){if(KeyEventManager.instance){KeyEventManager.instance.destroy();KeyEventManager.instance=undefined;}
KeyEventManager.instance=new KeyEventManager();});KeyEventManager.prototype={addListener:function(type,handler,thisArg){if(!thisArg.keyEventManagerGuid_){thisArg.keyEventManagerGuid_=tr.b.GUID.allocate();thisArg.keyEventManagerRefCount_=0;}
thisArg.classList.add('key-event-manager-target');thisArg.keyEventManagerRefCount_++;var guid=thisArg.keyEventManagerGuid_;this.listeners_.push({guid:guid,type:type,handler:handler});},onEvent_:function(event){var preventDefaultState=undefined;var stopPropagationCalled=false;var oldPreventDefault=event.preventDefault;event.preventDefault=function(){preventDefaultState=false;oldPreventDefault.call(this);};var oldStopPropagation=event.stopPropagation;event.stopPropagation=function(){stopPropagationCalled=true;oldStopPropagation.call(this);};event.stopImmediatePropagation=function(){throw new Error('Not implemented');};var possibleThisArgs=this.document_.querySelectorAll('.key-event-manager-target');var possibleThisArgsByGUID={};for(var i=0;i< possibleThisArgs.length ; i + + ) { possibleThisArgsByGUID [ possibleThisArgs [ i ] . keyEventManagerGuid_ ] = possibleThisArgs [ i ] ; }
var listeners=this.listeners_.concat();var type=event.type;var prevented=0;for(var i=0;i< listeners.length ; i + + ) { var listener = listeners[i];if(listener.type!==type)
continue;var thisArg=possibleThisArgsByGUID[listener.guid];if(!thisArg)
continue;var handler=listener.handler;if(handler.handleEvent)
prevented|=handler.handleEvent.call(handler,event)===false;else
prevented|=handler.call(thisArg,event)===false;if(stopPropagationCalled)
break;}
return!prevented&&preventDefaultState; },removeListener:function(type,handler,thisArg){if(thisArg.keyEventManagerGuid_===undefined)
throw new Error('Was not registered with KeyEventManager');if(thisArg.keyEventManagerRefCount_===0)
throw new Error('No events were registered on the provided thisArg');for(var i=0;i< this.listeners_.length ; i + + ) { var listener = this.listeners_[i];if(listener.type==type&&listener.handler==handler&&listener.guid==thisArg.keyEventManagerGuid_){thisArg.keyEventManagerRefCount_--;if(thisArg.keyEventManagerRefCount_===0)
thisArg.classList.remove('key-event-manager-target');this.listeners_.splice(i,1);return;}}
throw new Error('Listener not found');},destroy:function(){this.listeners_.splice(0);this.document_.removeEventListener('keydown',this.onEvent_);this.document_.removeEventListener('keypress',this.onEvent_);this.document_.removeEventListener('keyup',this.onEvent_);},dispatchFakeEvent:function(type,args){var e=new KeyboardEvent(type,args);return KeyEventManager.instance.onEvent_.call(undefined,e);}};KeyEventManager.instance=new KeyEventManager();return{KeyEventManager:KeyEventManager};});'use strict';tr.exportTo('tr.ui.b',function(){function MouseTracker(opt_targetElement){this.onMouseDown_=this.onMouseDown_.bind(this);this.onMouseMove_=this.onMouseMove_.bind(this);this.onMouseUp_=this.onMouseUp_.bind(this);this.targetElement=opt_targetElement;}
MouseTracker.prototype={get targetElement(){return this.targetElement_;},set targetElement(targetElement){if(this.targetElement_)
this.targetElement_.removeEventListener('mousedown',this.onMouseDown_);this.targetElement_=targetElement;if(this.targetElement_)
this.targetElement_.addEventListener('mousedown',this.onMouseDown_);},onMouseDown_:function(e){if(e.button!==0)
return true;e=this.remakeEvent_(e,'mouse-tracker-start');this.targetElement_.dispatchEvent(e);document.addEventListener('mousemove',this.onMouseMove_);document.addEventListener('mouseup',this.onMouseUp_);this.targetElement_.addEventListener('blur',this.onMouseUp_);this.savePreviousUserSelect_=document.body.style['-webkit-user-select'];document.body.style['-webkit-user-select']='none';e.preventDefault();return true;},onMouseMove_:function(e){e=this.remakeEvent_(e,'mouse-tracker-move');this.targetElement_.dispatchEvent(e);},onMouseUp_:function(e){document.removeEventListener('mousemove',this.onMouseMove_);document.removeEventListener('mouseup',this.onMouseUp_);this.targetElement_.removeEventListener('blur',this.onMouseUp_);document.body.style['-webkit-user-select']=this.savePreviousUserSelect_;e=this.remakeEvent_(e,'mouse-tracker-end');this.targetElement_.dispatchEvent(e);},remakeEvent_:function(e,newType){var remade=new tr.b.Event(newType,true,true);remade.x=e.x;remade.y=e.y;remade.offsetX=e.offsetX;remade.offsetY=e.offsetY;remade.clientX=e.clientX;remade.clientY=e.clientY;return remade;}};function trackMouseMovesUntilMouseUp(mouseMoveHandler,opt_mouseUpHandler){function cleanupAndDispatchToMouseUp(e){document.removeEventListener('mousemove',mouseMoveHandler);document.removeEventListener('mouseup',cleanupAndDispatchToMouseUp);if(opt_mouseUpHandler)
opt_mouseUpHandler(e);}
document.addEventListener('mousemove',mouseMoveHandler);document.addEventListener('mouseup',cleanupAndDispatchToMouseUp);}
return{MouseTracker:MouseTracker,trackMouseMovesUntilMouseUp:trackMouseMovesUntilMouseUp};});'use strict';tr.exportTo('tr.ui.b',function(){var THIS_DOC=document.currentScript.ownerDocument;var MIN_MOUSE_SELECTION_DISTANCE=4;var MOUSE_SELECTOR_MODE={};MOUSE_SELECTOR_MODE.SELECTION=0x1;MOUSE_SELECTOR_MODE.PANSCAN=0x2;MOUSE_SELECTOR_MODE.ZOOM=0x4;MOUSE_SELECTOR_MODE.TIMING=0x8;MOUSE_SELECTOR_MODE.ROTATE=0x10;MOUSE_SELECTOR_MODE.ALL_MODES=0x1F;var allModeInfo={};allModeInfo[MOUSE_SELECTOR_MODE.PANSCAN]={title:'pan',className:'pan-scan-mode-button',eventNames:{enter:'enterpan',begin:'beginpan',update:'updatepan',end:'endpan',exit:'exitpan'}};allModeInfo[MOUSE_SELECTOR_MODE.SELECTION]={title:'selection',className:'selection-mode-button',eventNames:{enter:'enterselection',begin:'beginselection',update:'updateselection',end:'endselection',exit:'exitselection'}};allModeInfo[MOUSE_SELECTOR_MODE.ZOOM]={title:'zoom',className:'zoom-mode-button',eventNames:{enter:'enterzoom',begin:'beginzoom',update:'updatezoom',end:'endzoom',exit:'exitzoom'}};allModeInfo[MOUSE_SELECTOR_MODE.TIMING]={title:'timing',className:'timing-mode-button',eventNames:{enter:'entertiming',begin:'begintiming',update:'updatetiming',end:'endtiming',exit:'exittiming'}};allModeInfo[MOUSE_SELECTOR_MODE.ROTATE]={title:'rotate',className:'rotate-mode-button',eventNames:{enter:'enterrotate',begin:'beginrotate',update:'updaterotate',end:'endrotate',exit:'exitrotate'}};var MODIFIER={SHIFT:0x1,SPACE:0x2,CMD_OR_CTRL:0x4};var MouseModeSelector=tr.ui.b.define('div');MouseModeSelector.prototype={__proto__:HTMLDivElement.prototype,decorate:function(opt_targetElement){this.classList.add('mouse-mode-selector');var node=tr.ui.b.instantiateTemplate('#mouse-mode-selector-template',THIS_DOC);this.appendChild(node);this.buttonsEl_=this.querySelector('.buttons');this.dragHandleEl_=this.querySelector('.drag-handle');this.supportedModeMask=MOUSE_SELECTOR_MODE.ALL_MODES;this.initialRelativeMouseDownPos_={x:0,y:0};this.defaultMode_=MOUSE_SELECTOR_MODE.PANSCAN;this.settingsKey_=undefined;this.mousePos_={x:0,y:0};this.mouseDownPos_={x:0,y:0};this.dragHandleEl_.addEventListener('mousedown',this.onDragHandleMouseDown_.bind(this));this.onMouseDown_=this.onMouseDown_.bind(this);this.onMouseMove_=this.onMouseMove_.bind(this);this.onMouseUp_=this.onMouseUp_.bind(this);this.buttonsEl_.addEventListener('mouseup',this.onButtonMouseUp_);this.buttonsEl_.addEventListener('mousedown',this.onButtonMouseDown_);this.buttonsEl_.addEventListener('click',this.onButtonPress_.bind(this));tr.ui.b.KeyEventManager.instance.addListener('keydown',this.onKeyDown_,this);tr.ui.b.KeyEventManager.instance.addListener('keyup',this.onKeyUp_,this);this.keyCodeCondition=undefined;this.mode_=undefined;this.modeToKeyCodeMap_={};this.modifierToModeMap_={};this.targetElement=opt_targetElement;this.spacePressed_=false;this.modeBeforeAlternativeModeActivated_=null;this.isInteracting_=false;this.isClick_=false;},get targetElement(){return this.targetElement_;},set targetElement(target){if(this.targetElement_)
this.targetElement_.removeEventListener('mousedown',this.onMouseDown_);this.targetElement_=target;if(this.targetElement_)
this.targetElement_.addEventListener('mousedown',this.onMouseDown_);},get defaultMode(){return this.defaultMode_;},set defaultMode(defaultMode){this.defaultMode_=defaultMode;},get settingsKey(){return this.settingsKey_;},set settingsKey(settingsKey){this.settingsKey_=settingsKey;if(!this.settingsKey_)
return;var mode=tr.b.Settings.get(this.settingsKey_+'.mode',undefined);if(allModeInfo[mode]===undefined)
mode=undefined;if((mode& this.supportedModeMask_)===0)
mode=undefined;if(!mode)
mode=this.defaultMode_;this.mode=mode;var pos=tr.b.Settings.get(this.settingsKey_+'.pos',undefined);if(pos)
this.pos=pos;},get supportedModeMask(){return this.supportedModeMask_;},set supportedModeMask(supportedModeMask){if(this.mode& & (supportedModeMask& this.mode)===0)
throw new Error('supportedModeMask must include current mode.');function createButtonForMode(mode){var button=document.createElement('div');button.mode=mode;button.title=allModeInfo[mode].title;button.classList.add('tool-button');button.classList.add(allModeInfo[mode].className);return button;}
this.supportedModeMask_=supportedModeMask;this.buttonsEl_.textContent='';for(var modeName in MOUSE_SELECTOR_MODE){if(modeName=='ALL_MODES')
continue;var mode=MOUSE_SELECTOR_MODE[modeName];if((this.supportedModeMask_& mode)===0)
continue;this.buttonsEl_.appendChild(createButtonForMode(mode));}},get mode(){return this.currentMode_;},set mode(newMode){if(newMode!==undefined){if(typeof newMode!=='number')
throw new Error('Mode must be a number');if((newMode& this.supportedModeMask_)===0)
throw new Error('Cannot switch to this mode, it is not supported');if(allModeInfo[newMode]===undefined)
throw new Error('Unrecognized mode');}
var modeInfo;if(this.currentMode_===newMode)
return;if(this.currentMode_){modeInfo=allModeInfo[this.currentMode_];var buttonEl=this.buttonsEl_.querySelector('.'+modeInfo.className);if(buttonEl)
buttonEl.classList.remove('active');if(this.isInteracting_){var mouseEvent=this.createEvent_(allModeInfo[this.mode].eventNames.end);this.dispatchEvent(mouseEvent);}
tr.b.dispatchSimpleEvent(this,modeInfo.eventNames.exit,true);}
this.currentMode_=newMode;if(this.currentMode_){modeInfo=allModeInfo[this.currentMode_];var buttonEl=this.buttonsEl_.querySelector('.'+modeInfo.className);if(buttonEl)
buttonEl.classList.add('active');this.mouseDownPos_.x=this.mousePos_.x;this.mouseDownPos_.y=this.mousePos_.y;if(!this.isInAlternativeMode_)
tr.b.dispatchSimpleEvent(this,modeInfo.eventNames.enter,true);if(this.isInteracting_){var mouseEvent=this.createEvent_(allModeInfo[this.mode].eventNames.begin);this.dispatchEvent(mouseEvent);}}
if(this.settingsKey_& & !this.isInAlternativeMode_)
tr.b.Settings.set(this.settingsKey_+'.mode',this.mode);},setKeyCodeForMode:function(mode,keyCode){if((mode& this.supportedModeMask_)===0)
throw new Error('Mode not supported');this.modeToKeyCodeMap_[mode]=keyCode;if(!this.buttonsEl_)
return;var modeInfo=allModeInfo[mode];var buttonEl=this.buttonsEl_.querySelector('.'+modeInfo.className);if(buttonEl){buttonEl.title=modeInfo.title+' ('+String.fromCharCode(keyCode)+')';}},setKeyCodeCondition:function(callback){this.keyCodeCondition=callback;},setCurrentMousePosFromEvent_:function(e){this.mousePos_.x=e.clientX;this.mousePos_.y=e.clientY;},createEvent_:function(eventName,sourceEvent){var event=new tr.b.Event(eventName,true);event.clientX=this.mousePos_.x;event.clientY=this.mousePos_.y;event.deltaX=this.mousePos_.x-this.mouseDownPos_.x;event.deltaY=this.mousePos_.y-this.mouseDownPos_.y;event.mouseDownX=this.mouseDownPos_.x;event.mouseDownY=this.mouseDownPos_.y;event.didPreventDefault=false;event.preventDefault=function(){event.didPreventDefault=true;if(sourceEvent)
sourceEvent.preventDefault();};event.stopPropagation=function(){sourceEvent.stopPropagation();};event.stopImmediatePropagation=function(){throw new Error('Not implemented');};return event;},onMouseDown_:function(e){if(e.button!==0)
return;this.setCurrentMousePosFromEvent_(e);var mouseEvent=this.createEvent_(allModeInfo[this.mode].eventNames.begin,e);this.dispatchEvent(mouseEvent);this.isInteracting_=true;this.isClick_=true;tr.ui.b.trackMouseMovesUntilMouseUp(this.onMouseMove_,this.onMouseUp_);},onMouseMove_:function(e){this.setCurrentMousePosFromEvent_(e);var mouseEvent=this.createEvent_(allModeInfo[this.mode].eventNames.update,e);this.dispatchEvent(mouseEvent);if(this.isInteracting_)
this.checkIsClick_(e);},onMouseUp_:function(e){if(e.button!==0)
return;var mouseEvent=this.createEvent_(allModeInfo[this.mode].eventNames.end,e);mouseEvent.isClick=this.isClick_;this.dispatchEvent(mouseEvent);if(this.isClick_& & !mouseEvent.didPreventDefault)
this.dispatchClickEvents_(e);this.isInteracting_=false;this.updateAlternativeModeState_(e);},onButtonMouseDown_:function(e){e.preventDefault();e.stopImmediatePropagation();},onButtonMouseUp_:function(e){e.preventDefault();e.stopImmediatePropagation();},onButtonPress_:function(e){this.modeBeforeAlternativeModeActivated_=undefined;this.mode=e.target.mode;e.preventDefault();},onKeyDown_:function(e){if(e.keyCode===' '.charCodeAt(0))
this.spacePressed_=true;this.updateAlternativeModeState_(e);},onKeyUp_:function(e){if(e.keyCode===' '.charCodeAt(0))
this.spacePressed_=false;if(this.keyCodeCondition!=undefined&&!this.keyCodeCondition()){return; }
var didHandleKey=false;tr.b.iterItems(this.modeToKeyCodeMap_,function(modeStr,keyCode){if(e.keyCode===keyCode){this.modeBeforeAlternativeModeActivated_=undefined;var mode=parseInt(modeStr);this.mode=mode;didHandleKey=true;}},this);if(didHandleKey){e.preventDefault();e.stopPropagation();return;}
this.updateAlternativeModeState_(e);},updateAlternativeModeState_:function(e){var shiftPressed=e.shiftKey;var spacePressed=this.spacePressed_;var cmdOrCtrlPressed=(tr.isMac&&e.metaKey)||(!tr.isMac&&e.ctrlKey); var smm=this.supportedModeMask_;var newMode;var isNewModeAnAlternativeMode=false;if(shiftPressed&&(this.modifierToModeMap_[MODIFIER.SHIFT]&smm)!==0){newMode=this.modifierToModeMap_[MODIFIER.SHIFT]; isNewModeAnAlternativeMode=true;}else if(spacePressed&&(this.modifierToModeMap_[MODIFIER.SPACE]&smm)!==0){newMode=this.modifierToModeMap_[MODIFIER.SPACE]; isNewModeAnAlternativeMode=true;}else if(cmdOrCtrlPressed&&(this.modifierToModeMap_[MODIFIER.CMD_OR_CTRL]&smm)!==0){newMode=this.modifierToModeMap_[MODIFIER.CMD_OR_CTRL]; isNewModeAnAlternativeMode=true;}else{if(this.isInAlternativeMode_){newMode=this.modeBeforeAlternativeModeActivated_;isNewModeAnAlternativeMode=false;}else{newMode=undefined;}}
if(this.mode===newMode||newMode===undefined)
return;if(isNewModeAnAlternativeMode)
this.modeBeforeAlternativeModeActivated_=this.mode;this.mode=newMode;},get isInAlternativeMode_(){return!!this.modeBeforeAlternativeModeActivated_;},setModifierForAlternateMode:function(mode,modifier){this.modifierToModeMap_[modifier]=mode;},get pos(){return{x:parseInt(this.style.left),y:parseInt(this.style.top)};},set pos(pos){pos=this.constrainPositionToBounds_(pos);this.style.left=pos.x+'px';this.style.top=pos.y+'px';if(this.settingsKey_)
tr.b.Settings.set(this.settingsKey_+'.pos',this.pos);},constrainPositionToBounds_:function(pos){var parent=this.offsetParent||document.body;var parentRect=tr.ui.b.windowRectForElement(parent);var top=0;var bottom=parentRect.height-this.offsetHeight;var left=0;var right=parentRect.width-this.offsetWidth;var res={};res.x=Math.max(pos.x,left);res.x=Math.min(res.x,right);res.y=Math.max(pos.y,top);res.y=Math.min(res.y,bottom);return res;},onDragHandleMouseDown_:function(e){e.preventDefault();e.stopImmediatePropagation();var mouseDownPos={x:e.clientX-this.offsetLeft,y:e.clientY-this.offsetTop};tr.ui.b.trackMouseMovesUntilMouseUp(function(e){var pos={};pos.x=e.clientX-mouseDownPos.x;pos.y=e.clientY-mouseDownPos.y;this.pos=pos;}.bind(this));},checkIsClick_:function(e){if(!this.isInteracting_||!this.isClick_)
return;var deltaX=this.mousePos_.x-this.mouseDownPos_.x;var deltaY=this.mousePos_.y-this.mouseDownPos_.y;var minDist=MIN_MOUSE_SELECTION_DISTANCE;if(deltaX*deltaX+deltaY*deltaY>minDist*minDist)
this.isClick_=false;},dispatchClickEvents_:function(e){if(!this.isClick_)
return;var eventNames=allModeInfo[MOUSE_SELECTOR_MODE.SELECTION].eventNames;var mouseEvent=this.createEvent_(eventNames.begin);this.dispatchEvent(mouseEvent);mouseEvent=this.createEvent_(eventNames.end);this.dispatchEvent(mouseEvent);}};return{MIN_MOUSE_SELECTION_DISTANCE:MIN_MOUSE_SELECTION_DISTANCE,MouseModeSelector:MouseModeSelector,MOUSE_SELECTOR_MODE:MOUSE_SELECTOR_MODE,MODIFIER:MODIFIER};});'use strict';tr.exportTo('tr.ui',function(){var Selection=tr.c.Selection;var SelectionState=tr.model.SelectionState;var Viewport=tr.ui.TimelineViewport;var tempDisplayTransform=new tr.ui.TimelineDisplayTransform();function intersectRect_(r1,r2){var results=new Object;if(r2.left>r1.right||r2.right< r1.left | | r2 . top > r1.bottom||r2.bottom< r1.top ) { return false ; }
2015-06-14 13:52:57 -06:00
results.left=Math.max(r1.left,r2.left);results.top=Math.max(r1.top,r2.top);results.right=Math.min(r1.right,r2.right);results.bottom=Math.min(r1.bottom,r2.bottom);results.width=(results.right-results.left);results.height=(results.bottom-results.top);return results;}
2015-06-18 08:27:29 -06:00
var TimelineTrackView=tr.ui.b.define('div');TimelineTrackView.prototype={__proto__:HTMLDivElement.prototype,model_:null,decorate:function(timelineView){this.classList.add('timeline-track-view');this.timelineView_=timelineView;this.viewport_=new Viewport(this);this.viewportDisplayTransformAtMouseDown_=null;this.selectionController_=undefined;this.rulerTrackContainer_=new tr.ui.tracks.DrawingContainer(this.viewport_);this.appendChild(this.rulerTrackContainer_);this.rulerTrackContainer_.invalidate();this.rulerTrack_=new tr.ui.tracks.RulerTrack(this.viewport_);this.rulerTrackContainer_.appendChild(this.rulerTrack_);this.upperModelTrack_=new tr.ui.tracks.ModelTrack(this.viewport_);this.upperModelTrack_.upperMode=true;this.rulerTrackContainer_.appendChild(this.upperModelTrack_);this.modelTrackContainer_=new tr.ui.tracks.DrawingContainer(this.viewport_);this.appendChild(this.modelTrackContainer_);this.modelTrackContainer_.style.display='block';this.modelTrackContainer_.invalidate();this.viewport_.modelTrackContainer=this.modelTrackContainer_;this.modelTrack_=new tr.ui.tracks.ModelTrack(this.viewport_);this.modelTrackContainer_.appendChild(this.modelTrack_);this.timingTool_=new tr.ui.b.TimingTool(this.viewport_,this);this.initMouseModeSelector();this.dragBox_=this.ownerDocument.createElement('div');this.dragBox_.className='drag-box';this.appendChild(this.dragBox_);this.hideDragBox_();this.initHintText_();this.onSelectionChanged_=this.onSelectionChanged_.bind(this);this.bindEventListener_(document,'keypress',this.onKeypress_,this);this.bindEventListener_(document,'keydown',this.onKeydown_,this);this.bindEventListener_(document,'keyup',this.onKeyup_,this);this.bindEventListener_(this,'dblclick',this.onDblClick_,this);this.bindEventListener_(this,'mousewheel',this.onMouseWheel_,this);this.bindEventListener_(this,'mousedown',this.onMouseDown_,this);this.addEventListener('mousemove',this.onMouseMove_);this.addEventListener('touchstart',this.onTouchStart_);this.addEventListener('touchmove',this.onTouchMove_);this.addEventListener('touchend',this.onTouchEnd_);this.mouseViewPosAtMouseDown_={x:0,y:0};this.lastMouseViewPos_={x:0,y:0};this.lastTouchViewPositions_=[];this.alert_=undefined;this.isPanningAndScanning_=false;this.isZooming_=false;},bindEventListener_:function(object,event,func,target){if(!this.boundListeners_)
2015-06-14 13:52:57 -06:00
this.boundListeners_=[];var boundFunc=func.bind(target);this.boundListeners_.push({object:object,event:event,boundFunc:boundFunc});object.addEventListener(event,boundFunc);},initMouseModeSelector:function(){this.mouseModeSelector_=new tr.ui.b.MouseModeSelector(this);this.appendChild(this.mouseModeSelector_);this.mouseModeSelector_.addEventListener('beginpan',this.onBeginPanScan_.bind(this));this.mouseModeSelector_.addEventListener('updatepan',this.onUpdatePanScan_.bind(this));this.mouseModeSelector_.addEventListener('endpan',this.onEndPanScan_.bind(this));this.mouseModeSelector_.addEventListener('beginselection',this.onBeginSelection_.bind(this));this.mouseModeSelector_.addEventListener('updateselection',this.onUpdateSelection_.bind(this));this.mouseModeSelector_.addEventListener('endselection',this.onEndSelection_.bind(this));this.mouseModeSelector_.addEventListener('beginzoom',this.onBeginZoom_.bind(this));this.mouseModeSelector_.addEventListener('updatezoom',this.onUpdateZoom_.bind(this));this.mouseModeSelector_.addEventListener('endzoom',this.onEndZoom_.bind(this));this.mouseModeSelector_.addEventListener('entertiming',this.timingTool_.onEnterTiming.bind(this.timingTool_));this.mouseModeSelector_.addEventListener('begintiming',this.timingTool_.onBeginTiming.bind(this.timingTool_));this.mouseModeSelector_.addEventListener('updatetiming',this.timingTool_.onUpdateTiming.bind(this.timingTool_));this.mouseModeSelector_.addEventListener('endtiming',this.timingTool_.onEndTiming.bind(this.timingTool_));this.mouseModeSelector_.addEventListener('exittiming',this.timingTool_.onExitTiming.bind(this.timingTool_));var m=tr.ui.b.MOUSE_SELECTOR_MODE;this.mouseModeSelector_.supportedModeMask=m.SELECTION|m.PANSCAN|m.ZOOM|m.TIMING;this.mouseModeSelector_.settingsKey='timelineTrackView.mouseModeSelector';this.mouseModeSelector_.setKeyCodeForMode(m.PANSCAN,'2'.charCodeAt(0));this.mouseModeSelector_.setKeyCodeForMode(m.SELECTION,'1'.charCodeAt(0));this.mouseModeSelector_.setKeyCodeForMode(m.ZOOM,'3'.charCodeAt(0));this.mouseModeSelector_.setKeyCodeForMode(m.TIMING,'4'.charCodeAt(0));this.mouseModeSelector_.setKeyCodeCondition(function(){return this.listenToKeys_;}.bind(this));this.mouseModeSelector_.setModifierForAlternateMode(m.SELECTION,tr.ui.b.MODIFIER.SHIFT);this.mouseModeSelector_.setModifierForAlternateMode(m.PANSCAN,tr.ui.b.MODIFIER.SPACE);this.mouseModeSelector_.setModifierForAlternateMode(m.ZOOM,tr.ui.b.MODIFIER.CMD_OR_CTRL);},get selectionController(){return this.selectionController_;},set selectionController(selectionController){if(this.selectionController_){this.selectionController_.removeEventListener('change',this.onSelectionChanged_);}
this.selectionController_=selectionController;if(this.selectionController_){this.selectionController_.addEventListener('change',this.onSelectionChanged_);}},onSelectionChanged_:function(){this.showHintText_('Press \'m\' to mark current selection');this.viewport_.dispatchChangeEvent();},set selection(selection){throw new Error('DO NOT CALL THIS');},set highlight(highlight){throw new Error('DO NOT CALL THIS');},detach:function(){this.modelTrack_.detach();this.upperModelTrack_.detach();for(var i=0;i< this.boundListeners_.length ; i + + ) { var binding = this.boundListeners_[i];binding.object.removeEventListener(binding.event,binding.boundFunc);}
this.boundListeners_=undefined;this.viewport_.detach();},get viewport(){return this.viewport_;},get model(){return this.model_;},set model(model){if(!model)
throw new Error('Model cannot be null');var modelInstanceChanged=this.model_!==model;this.model_=model;this.modelTrack_.model=model;this.upperModelTrack_.model=model;if(modelInstanceChanged)
this.viewport_.setWhenPossible(this.setInitialViewport_.bind(this));tr.b.setPropertyAndDispatchChange(this,'model',model);},get hasVisibleContent(){return this.modelTrack_.hasVisibleContent||this.upperModelTrack_.hasVisibleContent;},setInitialViewport_:function(){this.modelTrackContainer_.updateCanvasSizeIfNeeded_();var w=this.modelTrackContainer_.canvas.width;var min;var range;if(this.model_.bounds.isEmpty){min=0;range=1000;}else if(this.model_.bounds.range===0){min=this.model_.bounds.min;range=1000;}else{min=this.model_.bounds.min;range=this.model_.bounds.range;}
var boost=range*0.15;tempDisplayTransform.set(this.viewport_.currentDisplayTransform);tempDisplayTransform.xSetWorldBounds(min-boost,min+range+boost,w);this.viewport_.setDisplayTransformImmediately(tempDisplayTransform);},addAllEventsMatchingFilterToSelectionAsTask:function(filter,selection){var modelTrack=this.modelTrack_;var firstT=modelTrack.addAllEventsMatchingFilterToSelectionAsTask(filter,selection);var lastT=firstT.after(function(){this.upperModelTrack_.addAllEventsMatchingFilterToSelection(filter,selection);},this);return firstT;},get focusElement(){if(this.focusElement_)
return this.focusElement_;return this.parentElement;},set focusElement(value){this.focusElement_=value;},get listenToKeys_(){if(!this.viewport_.isAttachedToDocumentOrInTestMode)
return false;if(document.activeElement instanceof TracingFindControl)
return false;if(document.activeElement instanceof TracingScriptingControl)
return false;if(!this.focusElement_)
return true;if(this.focusElement.tabIndex>=0){if(document.activeElement==this.focusElement)
2015-06-18 08:27:29 -06:00
return true;return tr.ui.b.elementIsChildOf(document.activeElement,this.focusElement);}
2015-06-14 13:52:57 -06:00
return true;},onMouseMove_:function(e){if(this.isZooming_)
return;this.storeLastMousePos_(e);},onTouchStart_:function(e){this.storeLastTouchPositions_(e);this.focusElements_();},onTouchMove_:function(e){e.preventDefault();this.onUpdateTransformForTouch_(e);},onTouchEnd_:function(e){this.storeLastTouchPositions_(e);this.focusElements_();},onKeypress_:function(e){var vp=this.viewport_;if(!this.listenToKeys_)
return;if(document.activeElement.nodeName=='INPUT')
return;var viewWidth=this.modelTrackContainer_.canvas.clientWidth;var curMouseV,curCenterW;switch(e.keyCode){case 119:case 44:this.zoomBy_(1.5,true);break;case 115:case 111:this.zoomBy_(1/1.5,true);break;case 103:this.onGridToggle_(true);break;case 71:this.onGridToggle_(false);break;case 87:case 60:this.zoomBy_(10,true);break;case 83:case 79:this.zoomBy_(1/10,true);break;case 97:this.queueSmoothPan_(viewWidth*0.3,0);break;case 100:case 101:this.queueSmoothPan_(viewWidth*-0.3,0);break;case 65:this.queueSmoothPan_(viewWidth*0.5,0);break;case 68:this.queueSmoothPan_(viewWidth*-0.5,0);break;case 48:this.setInitialViewport_();break;case 102:this.zoomToSelection();break;case'm'.charCodeAt(0):this.setCurrentSelectionAsInterestRange_();break;case 104:this.toggleHighDetails_();break;}},onKeydown_:function(e){if(!this.listenToKeys_)
return;var sel;var vp=this.viewport_;var viewWidth=this.modelTrackContainer_.canvas.clientWidth;switch(e.keyCode){case 37:sel=this.selectionController_.selection.getShiftedSelection(this.viewport,-1);if(sel){this.selectionController.changeSelectionFromTimeline(sel);this.panToSelection();e.preventDefault();}else{this.queueSmoothPan_(viewWidth*0.3,0);}
break;case 39:sel=this.selectionController_.selection.getShiftedSelection(this.viewport,1);if(sel){this.selectionController.changeSelectionFromTimeline(sel);this.panToSelection();e.preventDefault();}else{this.queueSmoothPan_(-viewWidth*0.3,0);}
break;case 9:if(this.focusElement.tabIndex==-1){if(e.shiftKey)
this.selectPrevious_(e);else
this.selectNext_(e);e.preventDefault();}
break;}},onKeyup_:function(e){if(!this.listenToKeys_)
return;if(!e.shiftKey){if(this.dragBeginEvent_){this.setDragBoxPosition_(this.dragBoxXStart_,this.dragBoxYStart_,this.dragBoxXEnd_,this.dragBoxYEnd_);}}},onDblClick_:function(e){if(this.mouseModeSelector_.mode!==tr.ui.b.MOUSE_SELECTOR_MODE.SELECTION)
return;var curSelection=this.selectionController_.selection;if(!curSelection.length||!curSelection[0].title)
return;var selection=new Selection();var filter=new tr.c.ExactTitleFilter(curSelection[0].title);this.modelTrack_.addAllEventsMatchingFilterToSelection(filter,selection);this.selectionController.changeSelectionFromTimeline(selection);},onMouseWheel_:function(e){if(!e.altKey)
return;var delta=e.wheelDelta/120;var zoomScale=Math.pow(1.5,delta);this.zoomBy_(zoomScale);e.preventDefault();},onMouseDown_:function(e){if(this.mouseModeSelector_.mode!==tr.ui.b.MOUSE_SELECTOR_MODE.SELECTION)
return;if(e.target!==this.rulerTrack_)
return;this.dragBeginEvent_=undefined;if(this.xNavStringMarker_){this.model.removeAnnotation(this.xNavStringMarker_);this.xNavStringMarker_=undefined;}
var dt=this.viewport_.currentDisplayTransform;tr.ui.b.trackMouseMovesUntilMouseUp(function(e){if(e.target===this.rulerTrack_)
2015-06-18 08:27:29 -06:00
return;var relativePosition=this.extractRelativeMousePosition_(e);var loc=tr.ui.b.Location.fromViewCoordinates(this.viewport_,relativePosition.x,relativePosition.y);if(!loc)
2015-06-14 13:52:57 -06:00
return;if(this.guideLineAnnotation_===undefined){this.guideLineAnnotation_=new tr.model.XMarkerAnnotation(loc.xWorld);this.model.addAnnotation(this.guideLineAnnotation_);}else{this.guideLineAnnotation_.timestamp=loc.xWorld;this.modelTrackContainer_.invalidate();}
2015-06-18 08:27:29 -06:00
var state=new tr.ui.b.UIState(loc,this.viewport_.currentDisplayTransform.scaleX);this.timelineView_.setFindCtlText(state.toUserFriendlyString(this.viewport_));}.bind(this));},queueSmoothPan_:function(viewDeltaX,deltaY){var deltaX=this.viewport_.currentDisplayTransform.xViewVectorToWorld(viewDeltaX);var animation=new tr.ui.TimelineDisplayTransformPanAnimation(deltaX,deltaY);this.viewport_.queueDisplayTransformAnimation(animation);},zoomBy_:function(scale,smooth){if(scale< =0){return;}
smooth=!!smooth;var vp=this.viewport_;var viewWidth=this.modelTrackContainer_.canvas.clientWidth;var pixelRatio=window.devicePixelRatio||1;var goalFocalPointXView=this.lastMouseViewPos_.x*pixelRatio;var goalFocalPointXWorld=vp.currentDisplayTransform.xViewToWorld(goalFocalPointXView);if(smooth){var animation=new tr.ui.TimelineDisplayTransformZoomToAnimation(goalFocalPointXWorld,goalFocalPointXView,vp.currentDisplayTransform.panY,scale);vp.queueDisplayTransformAnimation(animation);}else{tempDisplayTransform.set(vp.currentDisplayTransform);tempDisplayTransform.scaleX=tempDisplayTransform.scaleX*scale;tempDisplayTransform.xPanWorldPosToViewPos(goalFocalPointXWorld,goalFocalPointXView,viewWidth);vp.setDisplayTransformImmediately(tempDisplayTransform);}},zoomToSelection:function(){if(!this.selectionController.selectionOfInterest.length)
2015-06-14 13:52:57 -06:00
return;var bounds=this.selectionController.selectionOfInterest.bounds;if(!bounds.range)
2015-06-18 08:27:29 -06:00
return;var worldCenter=bounds.center;var viewCenter=this.modelTrackContainer_.canvas.width/2;var adjustedWorldRange=bounds.range*1.25;var newScale=this.modelTrackContainer_.canvas.width/adjustedWorldRange;var zoomInRatio=newScale/this.viewport_.currentDisplayTransform.scaleX;var animation=new tr.ui.TimelineDisplayTransformZoomToAnimation(worldCenter,viewCenter,this.viewport_.currentDisplayTransform.panY,zoomInRatio);this.viewport_.queueDisplayTransformAnimation(animation);},panToSelection:function(){if(!this.selectionController.selectionOfInterest.length)
return;var bounds=this.selectionController.selectionOfInterest.bounds;var worldCenter=bounds.center;var viewWidth=this.modelTrackContainer_.canvas.width;var dt=this.viewport_.currentDisplayTransform;if(false&&!bounds.range){if(dt.xWorldToView(bounds.center)<0||dt.xWorldToView(bounds.center)>viewWidth){tempDisplayTransform.set(dt); tempDisplayTransform.xPanWorldPosToViewPos(worldCenter,'center',viewWidth);var deltaX=tempDisplayTransform.panX-dt.panX;var animation=new tr.ui.TimelineDisplayTransformPanAnimation(deltaX,0);this.viewport_.queueDisplayTransformAnimation(animation);}
2015-06-14 13:52:57 -06:00
return;}
2015-06-18 08:27:29 -06:00
tempDisplayTransform.set(dt);tempDisplayTransform.xPanWorldBoundsIntoView(bounds.min,bounds.max,viewWidth);var deltaX=tempDisplayTransform.panX-dt.panX;var animation=new tr.ui.TimelineDisplayTransformPanAnimation(deltaX,0);this.viewport_.queueDisplayTransformAnimation(animation);},navToPosition:function(uiState,showNavLine){var location=uiState.location;var scaleX=uiState.scaleX;var track=location.getContainingTrack(this.viewport_);var worldCenter=location.xWorld;var viewCenter=this.modelTrackContainer_.canvas.width/5;var zoomInRatio=scaleX/this.viewport_.currentDisplayTransform.scaleX;track.scrollIntoViewIfNeeded();var animation=new tr.ui.TimelineDisplayTransformZoomToAnimation(worldCenter,viewCenter,this.viewport_.currentDisplayTransform.panY,zoomInRatio);this.viewport_.queueDisplayTransformAnimation(animation);if(!showNavLine)
2015-06-14 13:52:57 -06:00
return;if(this.xNavStringMarker_)
this.model.removeAnnotation(this.xNavStringMarker_);this.xNavStringMarker_=new tr.model.XMarkerAnnotation(worldCenter);this.model.addAnnotation(this.xNavStringMarker_);},setCurrentSelectionAsInterestRange_:function(){var selectionBounds=this.selectionController_.selection.bounds;if(selectionBounds.empty){this.viewport_.interestRange.reset();return;}
if(this.viewport_.interestRange.min==selectionBounds.min& & this.viewport_.interestRange.max==selectionBounds.max)
this.viewport_.interestRange.reset();else
this.viewport_.interestRange.set(selectionBounds);},toggleHighDetails_:function(){this.viewport_.highDetails=!this.viewport_.highDetails;},hideDragBox_:function(){this.dragBox_.style.left='-1000px';this.dragBox_.style.top='-1000px';this.dragBox_.style.width=0;this.dragBox_.style.height=0;},setDragBoxPosition_:function(xStart,yStart,xEnd,yEnd){var loY=Math.min(yStart,yEnd);var hiY=Math.max(yStart,yEnd);var loX=Math.min(xStart,xEnd);var hiX=Math.max(xStart,xEnd);var modelTrackRect=this.modelTrack_.getBoundingClientRect();var dragRect={left:loX,top:loY,width:hiX-loX,height:hiY-loY};dragRect.right=dragRect.left+dragRect.width;dragRect.bottom=dragRect.top+dragRect.height;var modelTrackContainerRect=this.modelTrackContainer_.getBoundingClientRect();var clipRect={left:modelTrackContainerRect.left,top:modelTrackContainerRect.top,right:modelTrackContainerRect.right,bottom:modelTrackContainerRect.bottom};var headingWidth=window.getComputedStyle(this.querySelector('heading')).width;var trackTitleWidth=parseInt(headingWidth);clipRect.left=clipRect.left+trackTitleWidth;var finalDragBox=intersectRect_(clipRect,dragRect);this.dragBox_.style.left=finalDragBox.left+'px';this.dragBox_.style.width=finalDragBox.width+'px';this.dragBox_.style.top=finalDragBox.top+'px';this.dragBox_.style.height=finalDragBox.height+'px';this.dragBox_.style.whiteSpace='nowrap';var pixelRatio=window.devicePixelRatio||1;var canv=this.modelTrackContainer_.canvas;var dt=this.viewport_.currentDisplayTransform;var loWX=dt.xViewToWorld((loX-canv.offsetLeft)*pixelRatio);var hiWX=dt.xViewToWorld((hiX-canv.offsetLeft)*pixelRatio);this.dragBox_.textContent=tr.b.units.tsString((hiWX-loWX));var e=new tr.b.Event('selectionChanging');e.loWX=loWX;e.hiWX=hiWX;this.dispatchEvent(e);},onGridToggle_:function(left){var selection=this.selectionController_.selection;var tb=left?selection.bounds.min:selection.bounds.max;if(this.viewport_.gridEnabled&&this.viewport_.gridSide===left&&this.viewport_.gridInitialTimebase===tb){this.viewport_.gridside=undefined; this.viewport_.gridEnabled=false;this.viewport_.gridInitialTimebase=undefined;return;}
var numIntervalsSinceStart=Math.ceil((tb-this.model_.bounds.min)/this.viewport_.gridStep_);this.viewport_.gridEnabled=true;this.viewport_.gridSide=left;this.viewport_.gridInitialTimebase=tb;this.viewport_.gridTimebase=tb-
(numIntervalsSinceStart+1)*this.viewport_.gridStep_;},storeLastMousePos_:function(e){this.lastMouseViewPos_=this.extractRelativeMousePosition_(e);},storeLastTouchPositions_:function(e){this.lastTouchViewPositions_=this.extractRelativeTouchPositions_(e);},extractRelativeMousePosition_:function(e){var canv=this.modelTrackContainer_.canvas;return{x:e.clientX-canv.offsetLeft,y:e.clientY-canv.offsetTop};},extractRelativeTouchPositions_:function(e){var canv=this.modelTrackContainer_.canvas;var touches=[];for(var i=0;i< e.touches.length ; + + i ) { touches . push ( { x:e . touches [ i ] . clientX-canv . offsetLeft , y:e . touches [ i ] . clientY-canv . offsetTop } ) ; }
return touches;},storeInitialMouseDownPos_:function(e){var position=this.extractRelativeMousePosition_(e);this.mouseViewPosAtMouseDown_.x=position.x;this.mouseViewPosAtMouseDown_.y=position.y;},focusElements_:function(){if(document.activeElement)
document.activeElement.blur();if(this.focusElement.tabIndex>=0)
this.focusElement.focus();},storeInitialInteractionPositionsAndFocus_:function(e){this.storeInitialMouseDownPos_(e);this.storeLastMousePos_(e);this.focusElements_();},onBeginPanScan_:function(e){var vp=this.viewport_;this.viewportDisplayTransformAtMouseDown_=vp.currentDisplayTransform.clone();this.isPanningAndScanning_=true;this.storeInitialInteractionPositionsAndFocus_(e);e.preventDefault();},onUpdatePanScan_:function(e){if(!this.isPanningAndScanning_)
return;var viewWidth=this.modelTrackContainer_.canvas.clientWidth;var pixelRatio=window.devicePixelRatio||1;var xDeltaView=pixelRatio*(this.lastMouseViewPos_.x-
this.mouseViewPosAtMouseDown_.x);var yDelta=this.lastMouseViewPos_.y-
this.mouseViewPosAtMouseDown_.y;tempDisplayTransform.set(this.viewportDisplayTransformAtMouseDown_);tempDisplayTransform.incrementPanXInViewUnits(xDeltaView);tempDisplayTransform.panY-=yDelta;this.viewport_.setDisplayTransformImmediately(tempDisplayTransform);e.preventDefault();e.stopPropagation();this.storeLastMousePos_(e);},onEndPanScan_:function(e){this.isPanningAndScanning_=false;this.storeLastMousePos_(e);if(!e.isClick)
e.preventDefault();},onBeginSelection_:function(e){var canv=this.modelTrackContainer_.canvas;var rect=this.modelTrack_.getBoundingClientRect();var canvRect=canv.getBoundingClientRect();var inside=rect&&e.clientX>=rect.left&&e.clientX<rect.right&&e.clientY>=rect.top&&e.clientY<rect.bottom&&e.clientX>=canvRect.left&&e.clientX<canvRect.right; if(!inside)
return;this.dragBeginEvent_=e;this.storeInitialInteractionPositionsAndFocus_(e);e.preventDefault();},onUpdateSelection_:function(e){if(!this.dragBeginEvent_)
return;this.dragBoxXStart_=this.dragBeginEvent_.clientX;this.dragBoxXEnd_=e.clientX;this.dragBoxYStart_=this.dragBeginEvent_.clientY;this.dragBoxYEnd_=e.clientY;this.setDragBoxPosition_(this.dragBoxXStart_,this.dragBoxYStart_,this.dragBoxXEnd_,this.dragBoxYEnd_);},onEndSelection_:function(e){e.preventDefault();if(!this.dragBeginEvent_)
return;this.hideDragBox_();var eDown=this.dragBeginEvent_;this.dragBeginEvent_=null;var loY=Math.min(eDown.clientY,e.clientY);var hiY=Math.max(eDown.clientY,e.clientY);var loX=Math.min(eDown.clientX,e.clientX);var hiX=Math.max(eDown.clientX,e.clientX);var canv=this.modelTrackContainer_.canvas;var worldOffset=canv.getBoundingClientRect().left;var loVX=loX-worldOffset;var hiVX=hiX-worldOffset;var selection=new Selection();this.modelTrack_.addIntersectingEventsInRangeToSelection(loVX,hiVX,loY,hiY,selection);this.selectionController_.changeSelectionFromTimeline(selection);},onBeginZoom_:function(e){this.isZooming_=true;this.storeInitialInteractionPositionsAndFocus_(e);e.preventDefault();},onUpdateZoom_:function(e){if(!this.isZooming_)
return;var newPosition=this.extractRelativeMousePosition_(e);var zoomScaleValue=1+(this.lastMouseViewPos_.y-
newPosition.y)*0.01;this.zoomBy_(zoomScaleValue,false);this.storeLastMousePos_(e);},onEndZoom_:function(e){this.isZooming_=false;if(!e.isClick)
e.preventDefault();},computeTouchCenter_:function(positions){var xSum=0;var ySum=0;for(var i=0;i< positions.length ; + + i ) { xSum + = positions [ i ] . x ; ySum + = positions [ i ] . y ; }
return{x:xSum/positions.length,y:ySum/positions.length};},computeTouchSpan_:function(positions){var xMin=Number.MAX_VALUE;var yMin=Number.MAX_VALUE;var xMax=Number.MIN_VALUE;var yMax=Number.MIN_VALUE;for(var i=0;i< positions.length ; + + i ) { xMin = Math.min(xMin,positions[i].x);yMin=Math.min(yMin,positions[i].y);xMax=Math.max(xMax,positions[i].x);yMax=Math.max(yMax,positions[i].y);}
return Math.sqrt((xMin-xMax)*(xMin-xMax)+
(yMin-yMax)*(yMin-yMax));},onUpdateTransformForTouch_:function(e){var newPositions=this.extractRelativeTouchPositions_(e);var currentPositions=this.lastTouchViewPositions_;var newCenter=this.computeTouchCenter_(newPositions);var currentCenter=this.computeTouchCenter_(currentPositions);var newSpan=this.computeTouchSpan_(newPositions);var currentSpan=this.computeTouchSpan_(currentPositions);var vp=this.viewport_;var viewWidth=this.modelTrackContainer_.canvas.clientWidth;var pixelRatio=window.devicePixelRatio||1;var xDelta=pixelRatio*(newCenter.x-currentCenter.x);var yDelta=newCenter.y-currentCenter.y;var zoomScaleValue=currentSpan>10?newSpan/currentSpan:1;var viewFocus=pixelRatio*newCenter.x;var worldFocus=vp.currentDisplayTransform.xViewToWorld(viewFocus);tempDisplayTransform.set(vp.currentDisplayTransform);tempDisplayTransform.scaleX*=zoomScaleValue;tempDisplayTransform.xPanWorldPosToViewPos(worldFocus,viewFocus,viewWidth);tempDisplayTransform.incrementPanXInViewUnits(xDelta);tempDisplayTransform.panY-=yDelta;vp.setDisplayTransformImmediately(tempDisplayTransform);this.storeLastTouchPositions_(e);},initHintText_:function(){this.hintTextBox_=this.ownerDocument.createElement('div');this.hintTextBox_.className='hint-text';this.hintTextBox_.style.display='none';this.appendChild(this.hintTextBox_);this.pendingHintTextClearTimeout_=undefined;},showHintText_:function(text){if(this.pendingHintTextClearTimeout_){window.clearTimeout(this.pendingHintTextClearTimeout_);this.pendingHintTextClearTimeout_=undefined;}
2015-06-18 08:27:29 -06:00
this.pendingHintTextClearTimeout_=setTimeout(this.hideHintText_.bind(this),1000);this.hintTextBox_.textContent=text;this.hintTextBox_.style.display='';},hideHintText_:function(){this.pendingHintTextClearTimeout_=undefined;this.hintTextBox_.style.display='none';}};return{TimelineTrackView:TimelineTrackView};});'use strict';Polymer('tr-ui-find-control',{filterKeyDown:function(e){if(e.keyCode===27)
2015-06-14 13:52:57 -06:00
return;e.stopPropagation();if(e.keyCode!==13)return;e.shiftKey?this.findPrevious():this.findNext();},filterKeyPress:function(e){if(e.keyCode===27)
return;e.stopPropagation();},filterBlur:function(e){this.updateHitCountEl();},filterFocus:function(e){this.$.filter.select();},filterMouseUp:function(e){e.preventDefault();},get controller(){return this.controller_;},set controller(c){this.controller_=c;this.updateHitCountEl();},focus:function(){this.$.filter.focus();},get hasFocus(){return this===document.activeElement;},filterTextChanged:function(){this.$.hitCount.textContent='';this.$.spinner.style.visibility='visible';this.controller.startFiltering(this.$.filter.value).then(function(){this.$.spinner.style.visibility='hidden';this.updateHitCountEl();}.bind(this));},findNext:function(){if(this.controller)
this.controller.findNext();this.updateHitCountEl();},findPrevious:function(){if(this.controller)
this.controller.findPrevious();this.updateHitCountEl();},updateHitCountEl:function(){if(!this.controller||!this.hasFocus){this.$.hitCount.textContent='';return;}
2015-06-18 08:27:29 -06:00
var n=this.controller.filterHits.length;var i=n===0?-1:this.controller.currentHitIndex;this.$.hitCount.textContent=(i+1)+' of '+n;},setText:function(string){this.$.filter.value=string;}});'use strict';tr.exportTo('tr.ui.b',function(){var Selection=tr.c.Selection;var SelectionState=tr.model.SelectionState;function BrushingState(){this.guid_=tr.b.GUID.allocate();this.selection_=new Selection();this.findMatches_=new Selection();this.analysisViewRelatedEvents_=new Selection();this.appliedToModel_=undefined;}
2015-06-14 13:52:57 -06:00
BrushingState.prototype={get guid(){return this.guid_;},clone:function(){var that=new BrushingState();that.selection_=this.selection_;that.findMatches_=this.findMatches_;that.analysisViewRelatedEvents_=this.analysisViewRelatedEvents_;return that;},equals:function(that){if(!this.selection_.equals(that.selection_))
return false;if(!this.findMatches_.equals(that.findMatches_))
return false;if(!this.analysisViewRelatedEvents_.equals(that.analysisViewRelatedEvents_)){return false;}
return true;},get selectionOfInterest(){if(this.selection_.length)
return this.selection_;if(this.highlight_.length)
return this.highlight_;if(this.analysisViewRelatedEvents_.length)
return this.analysisViewRelatedEvents_;return this.selection_;},get selection(){return this.selection_;},set selection(selection){if(this.appliedToModel_)
throw new Error('Cannot mutate this state right now');if(selection===undefined)
selection=new Selection();this.selection_=selection;},get findMatches(){return this.findMatches_;},set findMatches(findMatches){if(this.appliedToModel_)
throw new Error('Cannot mutate this state right now');if(findMatches===undefined)
findMatches=new Selection();this.findMatches_=findMatches;},get analysisViewRelatedEvents(){return this.analysisViewRelatedEvents_;},set analysisViewRelatedEvents(analysisViewRelatedEvents){if(this.appliedToModel_)
throw new Error('Cannot mutate this state right now');if(analysisViewRelatedEvents===undefined)
analysisViewRelatedEvents=new Selection();this.analysisViewRelatedEvents_=analysisViewRelatedEvents;},get isAppliedToModel(){return this.appliedToModel_!==undefined;},get hasHighlight_(){return this.findMatches_.length>0||this.analysisViewRelatedEvents_.length>0;},applyToModelSelectionState:function(model){this.appliedToModel_=model;if(!this.hasHighlight_){this.selection_.forEach(function(e){e.selectionState=SelectionState.SELECTED;});return;}
model.iterateAllEvents(function(e){var selectionState;if(this.selection_.contains(e)){selectionState=SelectionState.SELECTED;}else if(this.findMatches_.contains(e)){selectionState=SelectionState.HIGHLIGHTED;}else if(this.analysisViewRelatedEvents_.contains(e)){selectionState=SelectionState.HIGHLIGHTED;}else{selectionState=SelectionState.DIMMED;}
e.selectionState=selectionState;}.bind(this));},transferModelOwnershipToClone:function(that){if(!this.appliedToModel_)
throw new Error('Not applied');that.appliedToModel_=this.appliedToModel_;this.appliedToModel_=undefined;},unapplyFromModelSelectionState:function(){if(!this.appliedToModel_)
throw new Error('Not applied');var model=this.appliedToModel_;this.appliedToModel_=undefined;if(!this.hasHighlight_){this.selection_.forEach(function(e){e.selectionState=SelectionState.NONE;});return;}
2015-06-18 08:27:29 -06:00
model.iterateAllEvents(function(e){e.selectionState=SelectionState.NONE;});}};return{BrushingState:BrushingState};});'use strict';tr.exportTo('tr.ui.b',function(){function YComponent(stableId,yPercentOffset){this.stableId=stableId;this.yPercentOffset=yPercentOffset;}
YComponent.prototype={toDict:function(){return{stableId:this.stableId,yPercentOffset:this.yPercentOffset};}};function Location(xWorld,yComponents){this.xWorld_=xWorld;this.yComponents_=yComponents;};Location.fromViewCoordinates=function(viewport,viewX,viewY){var dt=viewport.currentDisplayTransform;var xWorld=dt.xViewToWorld(viewX);var yComponents=[];var elem=document.elementFromPoint(viewX+viewport.modelTrackContainer.canvas.offsetLeft,viewY+viewport.modelTrackContainer.canvas.offsetTop);while(elem instanceof tr.ui.tracks.Track){if(elem.eventContainer){var boundRect=elem.getBoundingClientRect();var yPercentOffset=(viewY-boundRect.top)/boundRect.height;yComponents.push(new YComponent(elem.eventContainer.stableId,yPercentOffset));}
2015-06-14 13:52:57 -06:00
elem=elem.parentElement;}
if(yComponents.length==0)
return;return new Location(xWorld,yComponents);}
2015-06-18 08:27:29 -06:00
Location.fromStableIdAndTimestamp=function(viewport,stableId,ts){var xWorld=ts;var yComponents=[];var containerToTrack=viewport.containerToTrackMap;var elem=containerToTrack.getTrackByStableId(stableId);if(!elem)
return;var firstY=elem.getBoundingClientRect().top;while(elem instanceof tr.ui.tracks.Track){if(elem.eventContainer){var boundRect=elem.getBoundingClientRect();var yPercentOffset=(firstY-boundRect.top)/boundRect.height;yComponents.push(new YComponent(elem.eventContainer.stableId,yPercentOffset));}
2015-06-14 13:52:57 -06:00
elem=elem.parentElement;}
if(yComponents.length==0)
return;return new Location(xWorld,yComponents);}
2015-06-18 08:27:29 -06:00
Location.prototype={get xWorld(){return this.xWorld_;},getContainingTrack:function(viewport){var containerToTrack=viewport.containerToTrackMap;for(var i in this.yComponents_){var yComponent=this.yComponents_[i];var track=containerToTrack.getTrackByStableId(yComponent.stableId);if(track!==undefined)
return track;}},toViewCoordinates:function(viewport){var dt=viewport.currentDisplayTransform;var containerToTrack=viewport.containerToTrackMap;var viewX=dt.xWorldToView(this.xWorld_);var viewY=-1;for(var index in this.yComponents_){var yComponent=this.yComponents_[index];var track=containerToTrack.getTrackByStableId(yComponent.stableId);if(track!==undefined){var boundRect=track.getBoundingClientRect();viewY=yComponent.yPercentOffset*boundRect.height+boundRect.top;break;}}
return{viewX:viewX,viewY:viewY};},toDict:function(){return{xWorld:this.xWorld_,yComponents:this.yComponents_};}};return{Location:Location};});'use strict';tr.exportTo('tr.ui.b',function(){var Location=tr.ui.b.Location;function UIState(location,scaleX){this.location_=location;this.scaleX_=scaleX;};UIState.fromUserFriendlyString=function(model,viewport,stateString){var navByFinderPattern=/^(-?\d+(\.\d+)?)@(.+)x(\d+(\.\d+)?)$/g;var match=navByFinderPattern.exec(stateString);if(!match)
2015-06-14 13:52:57 -06:00
return;var timestamp=parseFloat(match[1]);var stableId=match[3];var scaleX=parseFloat(match[4]);if(scaleX< =0)
2015-06-18 08:27:29 -06:00
throw new Error('Invalid ScaleX value in UI State string.');if(!viewport.containerToTrackMap.getTrackByStableId(stableId))
throw new Error('Invalid StableID given in UI State String.');var loc=tr.ui.b.Location.fromStableIdAndTimestamp(viewport,stableId,timestamp);return new UIState(loc,scaleX);}
UIState.prototype={get location(){return this.location_;},get scaleX(){return this.scaleX_;},toUserFriendlyString:function(viewport){var timestamp=this.location_.xWorld;var stableId=this.location_.getContainingTrack(viewport).eventContainer.stableId;var scaleX=this.scaleX_;return timestamp.toFixed(5)+'@'+stableId+'x'+scaleX.toFixed(5);},toDict:function(){return{location:this.location_.toDict(),scaleX:this.scaleX_};}};return{UIState:UIState};});'use strict';tr.exportTo('tr.c',function(){var BrushingState=tr.ui.b.BrushingState;var Selection=tr.c.Selection;var SelectionState=tr.model.SelectionState;var Viewport=tr.ui.TimelineViewport;function SelectionController(timelineView){tr.b.EventTarget.call(this);this.timelineView_=timelineView;this.currentBrushingState_=new BrushingState();this.onPopState_=this.onPopState_.bind(this);this.historyEnabled_=false;this.selections_={};}
2015-06-14 13:52:57 -06:00
SelectionController.prototype={__proto__:tr.b.EventTarget.prototype,dispatchChangeEvent_:function(){var e=new tr.b.Event('change',false,false);this.dispatchEvent(e);},get model(){if(!this.timelineView_)
return undefined;return this.timelineView_.model;},get trackView(){if(!this.timelineView_)
return undefined;return this.timelineView_.trackView;},get viewport(){if(!this.timelineView_)
return undefined;if(!this.timelineView_.trackView)
return undefined;return this.timelineView_.trackView.viewport;},get historyEnabled(){return this.historyEnabled_;},set historyEnabled(historyEnabled){this.historyEnabled_=!!historyEnabled;if(historyEnabled)
window.addEventListener('popstate',this.onPopState_);else
window.removeEventListener('popstate',this.onPopState_);},modelWillChange:function(){if(this.currentBrushingState_.isAppliedToModel)
this.currentBrushingState_.unapplyFromModelSelectionState();},modelDidChange:function(){this.selections_={};this.currentBrushingState_.applyToModelSelectionState(this.model);var e=new tr.b.Event('model-changed',false,false);this.dispatchEvent(e);},onUserInitiatedSelectionChange_:function(){var selection=this.selection;if(this.historyEnabled){this.selections_[selection.guid]=selection;var state={selection_guid:selection.guid};window.history.pushState(state,document.title);}},onPopState_:function(e){if(e.state===null)
return;var selection=this.selections_[e.state.selection_guid];if(selection){var newState=this.currentBrushingState_.clone();newState.selection=selection;this.currentBrushingState=newState;}
e.stopPropagation();},get selection(){return this.currentBrushingState_.selection;},get findMatches(){return this.currentBrushingState_.findMatches;},get selectionOfInterest(){return this.currentBrushingState_.selectionOfInterest;},get currentBrushingState(){return this.currentBrushingState_;},set currentBrushingState(newBrushingState){if(newBrushingState.isAppliedToModel)
2015-06-18 08:27:29 -06:00
throw new Error('Cannot apply this state, it is applied');var hasValueChanged=!this.currentBrushingState_.equals(newBrushingState);if(newBrushingState!==this.currentBrushingState_&&!hasValueChanged){if(this.currentBrushingState_.isAppliedToModel){this.currentBrushingState_.transferModelOwnershipToClone(newBrushingState); }
this.currentBrushingState_=newBrushingState;return;}
2015-06-14 13:52:57 -06:00
if(this.currentBrushingState_.isAppliedToModel)
this.currentBrushingState_.unapplyFromModelSelectionState();this.currentBrushingState_=newBrushingState;if(this.model)
this.currentBrushingState_.applyToModelSelectionState(this.model);this.dispatchChangeEvent_();},addAllEventsMatchingFilterToSelectionAsTask:function(filter,selection){var timelineView=this.timelineView_.trackView;if(!timelineView)
return new tr.b.Task();return timelineView.addAllEventsMatchingFilterToSelectionAsTask(filter,selection);},findTextChangedTo:function(allPossibleMatches){var newBrushingState=this.currentBrushingState_.clone();newBrushingState.findMatches=allPossibleMatches;this.currentBrushingState=newBrushingState;},findFocusChangedTo:function(currentFocus){var newBrushingState=this.currentBrushingState_.clone();newBrushingState.selection=currentFocus;this.currentBrushingState=newBrushingState;this.onUserInitiatedSelectionChange_();},findTextCleared:function(){if(this.xNavStringMarker_!==undefined){this.model.removeAnnotation(this.xNavStringMarker_);this.xNavStringMarker_=undefined;}
if(this.guideLineAnnotation_!==undefined){this.model.removeAnnotation(this.guideLineAnnotation_);this.guideLineAnnotation_=undefined;}
2015-06-18 08:27:29 -06:00
var newBrushingState=this.currentBrushingState_.clone();newBrushingState.selection=new Selection();newBrushingState.findMatches=new Selection();this.currentBrushingState=newBrushingState;this.onUserInitiatedSelectionChange_();},uiStateFromString:function(string){return tr.ui.b.UIState.fromUserFriendlyString(this.model,this.viewport,string);},navToPosition:function(uiState,showNavLine){this.trackView.navToPosition(uiState,showNavLine);},changeSelectionFromTimeline:function(selection){var newBrushingState=this.currentBrushingState_.clone();newBrushingState.selection=selection;newBrushingState.findMatches=new Selection();this.currentBrushingState=newBrushingState;this.onUserInitiatedSelectionChange_();},showScriptControlSelection:function(selection){var newBrushingState=this.currentBrushingState_.clone();newBrushingState.selection=selection;newBrushingState.findMatches=new Selection();this.currentBrushingState=newBrushingState;},changeSelectionFromRequestSelectionChangeEvent:function(selection){var newBrushingState=this.currentBrushingState_.clone();newBrushingState.selection=selection;newBrushingState.findMatches=new Selection();this.currentBrushingState=newBrushingState;this.onUserInitiatedSelectionChange_();},changeAnalysisViewRelatedEvents:function(selection){var newBrushingState=this.currentBrushingState_.clone();newBrushingState.analysisViewRelatedEvents=selection;this.currentBrushingState=newBrushingState;}};return{SelectionController:SelectionController};});'use strict';tr.exportTo('tr.c',function(){function ScriptingObject(){}
2015-06-14 13:52:57 -06:00
ScriptingObject.prototype={onModelChanged:function(){}};return{ScriptingObject:ScriptingObject};});'use strict';tr.exportTo('tr.c',function(){function ScriptingController(selectionController){this.selectionController_=selectionController;this.scriptObjectNames_=[];this.scriptObjectValues_=[];this.selectionController.addEventListener('model-changed',this.onModelChanged_.bind(this));var typeInfos=ScriptingObjectRegistry.getAllRegisteredTypeInfos();typeInfos.forEach(function(typeInfo){this.addScriptObject(typeInfo.metadata.name,typeInfo.constructor);window[typeInfo.metadata.name]=typeInfo.constructor;}.bind(this));}
function ScriptingObjectRegistry(){}
var options=new tr.b.ExtensionRegistryOptions(tr.b.BASIC_REGISTRY_MODE);tr.b.decorateExtensionRegistry(ScriptingObjectRegistry,options);ScriptingController.prototype={get selectionController(){return this.selectionController_;},onModelChanged_:function(){this.scriptObjectValues_.forEach(function(v){if(v.onModelChanged)
v.onModelChanged();});},addScriptObject:function(name,value){this.scriptObjectNames_.push(name);this.scriptObjectValues_.push(value);},executeCommand:function(command){var f=new Function(this.scriptObjectNames_,'return eval('+command+')');return f.apply(null,this.scriptObjectValues_);}};return{ScriptingController:ScriptingController,ScriptingObjectRegistry:ScriptingObjectRegistry};});'use strict';tr.exportTo('tr.e.tquery',function(){function Context(){this.event=undefined;this.ancestors=[];}
Context.prototype={push:function(event){var ctx=new Context();ctx.ancestors=this.ancestors.slice();ctx.ancestors.push(event);return ctx;},pop:function(event){var ctx=new Context();ctx.event=this.ancestors[this.ancestors.length-1];ctx.ancestors=this.ancestors.slice(0,this.ancestors.length-1);return ctx;}};return{Context:Context};});'use strict';tr.exportTo('tr.e.tquery',function(){function Filter(){tr.c.ScriptingObject.call(this);}
Filter.normalizeFilterExpression=function(filterExpression){if(filterExpression instanceof String||typeof(filterExpression)=='string'||filterExpression instanceof RegExp){var filter=new tr.e.tquery.FilterHasTitle(filterExpression);return filter;}
return filterExpression;};Filter.prototype={__proto__:tr.c.ScriptingObject.prototype,evaluate:function(context){throw new Error('Not implemented');},matchValue_:function(value,expected){if(expected instanceof RegExp)
return expected.test(value);else if(expected instanceof Function)
return expected(value);return value===expected;}};return{Filter:Filter};});'use strict';tr.exportTo('tr.e.tquery',function(){function FilterAllOf(opt_subExpressions){tr.e.tquery.Filter.call(this);this.subExpressions=opt_subExpressions||[];}
FilterAllOf.prototype={__proto__:tr.e.tquery.Filter.prototype,set subExpressions(exprs){this.subExpressions_=[];for(var i=0;i< exprs.length ; i + + ) { this . subExpressions_ . push ( tr . e . tquery . Filter . normalizeFilterExpression ( exprs [ i ] ) ) ; } } , get subExpressions ( ) { return this . subExpressions_ ; } , evaluate:function ( context ) { if ( ! this . subExpressions . length )
return true;for(var i=0;i< this.subExpressions.length ; i + + ) { if ( ! this . subExpressions [ i ] . evaluate ( context ) )
return false;}
return true;}};tr.c.ScriptingObjectRegistry.register(function(){var exprs=[];for(var i=0;i< arguments.length ; i + + ) { exprs . push ( arguments [ i ] ) ; }
return new FilterAllOf(exprs);},{name:'allOf'});return{FilterAllOf:FilterAllOf};});'use strict';tr.exportTo('tr.e.tquery',function(){function FilterAnyOf(opt_subExpressions){tr.e.tquery.Filter.call(this);this.subExpressions=opt_subExpressions||[];};FilterAnyOf.prototype={__proto__:tr.e.tquery.Filter.prototype,set subExpressions(exprs){this.subExpressions_=[];for(var i=0;i< exprs.length ; i + + ) { this . subExpressions_ . push ( tr . e . tquery . Filter . normalizeFilterExpression ( exprs [ i ] ) ) ; } } , get subExpressions ( ) { return this . subExpressions_ ; } , evaluate:function ( context ) { if ( ! this . subExpressions . length )
return true;for(var i=0;i< this.subExpressions.length ; i + + ) { if ( this . subExpressions [ i ] . evaluate ( context ) )
return true;}
return false;}};tr.c.ScriptingObjectRegistry.register(function(){var exprs=[];for(var i=0;i< arguments.length ; i + + ) { exprs . push ( arguments [ i ] ) ; }
return new FilterAnyOf(exprs);},{name:'anyOf'});return{FilterAnyOf:FilterAnyOf};});'use strict';tr.exportTo('tr.e.tquery',function(){function FilterHasAncestor(opt_subExpression){this.subExpression=opt_subExpression;};FilterHasAncestor.prototype={__proto__:tr.e.tquery.Filter.prototype,set subExpression(expr){this.subExpression_=tr.e.tquery.Filter.normalizeFilterExpression(expr);},get subExpression(){return this.subExpression_;},evaluate:function(context){if(!this.subExpression)
return context.ancestors.length>0;while(context.ancestors.length){context=context.pop();if(this.subExpression.evaluate(context))
return true;}
return false;}};tr.c.ScriptingObjectRegistry.register(function(subExpression){return new FilterHasAncestor(subExpression);},{name:'hasAncestor'});return{FilterHasAncestor:FilterHasAncestor};});'use strict';tr.exportTo('tr.e.tquery',function(){function FilterHasDuration(minValueOrExpected,opt_maxValue){if(minValueOrExpected!==undefined&&opt_maxValue!==undefined){this.minValue=minValueOrExpected; this.maxValue=opt_maxValue;}else{this.expected=minValueOrExpected;}};FilterHasDuration.prototype={__proto__:tr.e.tquery.Filter.prototype,evaluate:function(context){if(context.event.duration===undefined)
return false;if(this.minValue!==undefined& & this.maxValue!==undefined){return context.event.duration>=this.minValue&&context.event.duration<=this.maxValue; }
return this.matchValue_(context.event.duration,this.expected);}};tr.c.ScriptingObjectRegistry.register(function(minValueOrExpected,opt_maxValue){return new FilterHasDuration(minValueOrExpected,opt_maxValue);},{name:'hasDuration'});return{FilterHasDuration:FilterHasDuration};});'use strict';tr.exportTo('tr.e.tquery',function(){function FilterHasTitle(expected){tr.e.tquery.Filter.call(this);this.expected=expected;}
FilterHasTitle.prototype={__proto__:tr.e.tquery.Filter.prototype,evaluate:function(context){return this.matchValue_(context.event.title,this.expected);}};tr.c.ScriptingObjectRegistry.register(function(expected){var filter=new tr.e.tquery.FilterHasTitle(expected);return filter;},{name:'hasTitle'});return{FilterHasTitle:FilterHasTitle};});'use strict';tr.exportTo('tr.e.tquery',function(){function FilterIsTopLevel(opt_subExpression){this.subExpression=opt_subExpression;}
FilterIsTopLevel.prototype={__proto__:tr.e.tquery.Filter.prototype,set subExpression(expr){this.subExpression_=tr.e.tquery.Filter.normalizeFilterExpression(expr);},get subExpression(){return this.subExpression_;},evaluate:function(context){if(context.ancestors.length>0)
return false;if(!this.subExpression)
return true;return this.subExpression.evaluate(context);}};tr.c.ScriptingObjectRegistry.register(function(subExpression){return new FilterIsTopLevel(subExpression);},{name:'isTopLevel'});return{FilterIsTopLevel:FilterIsTopLevel};});'use strict';tr.exportTo('tr.e.tquery',function(){function TQuery(selectionController){tr.c.ScriptingObject.call(this);this.selectionController_=selectionController;this.parent_=undefined;this.filterExpression_=undefined;this.selection_=undefined;};TQuery.prototype={__proto__:tr.c.ScriptingObject.prototype,onModelChanged:function(){this.selection_=undefined;},get selectionController(){return this.selectionController_;},filter:function(filterExpression){var result=new TQuery(this.selectionController_);result.parent_=this;result.filterExpression_=tr.e.tquery.Filter.normalizeFilterExpression(filterExpression);return result;},createFilterTaskGraph_:function(){var nodes=[];var node=this;while(node!==undefined){nodes.push(node);node=node.parent_;}
var rootTask=new tr.b.Task();var lastTask=rootTask;for(var i=nodes.length-1;i>=0;i--){var node=nodes[i];if(node.selection_!==undefined)
continue;node.selection_=new tr.c.Selection();if(node.parent_===undefined){lastTask=lastTask.after(this.selectEverythingAsTask_(node.selection_));}else{var prevNode=nodes[i+1];lastTask=this.createFilterTaskForNode_(lastTask,node,prevNode);}}
return{rootTask:rootTask,lastTask:lastTask,lastNode:node};},createFilterTaskForNode_:function(lastTask,node,prevNode){return lastTask.after(function(){node.evaluateFilterExpression_(prevNode.selection_,node.selection_);},this);},evaluateFilterExpression_:function(inputSelection,outputSelection){var seenEvents={};inputSelection.forEach(function(event){var context=new tr.e.tquery.Context();context.event=event;this.evaluateFilterExpressionForEvent_(context,inputSelection,outputSelection,seenEvents);}.bind(this));},evaluateFilterExpressionForEvent_:function(context,inputSelection,outputSelection,seenEvents){var event=context.event;if(inputSelection.contains(event)&&!seenEvents[event.guid]){seenEvents[event.guid]=true; if(!this.filterExpression_||this.filterExpression_.evaluate(context))
outputSelection.push(event);}
if(!event.subSlices)
return;context=context.push(event);for(var i=0;i< event.subSlices.length ; i + + ) { context . event = event.subSlices[i];this.evaluateFilterExpressionForEvent_(context,inputSelection,outputSelection,seenEvents);}},show:function(){var graph = this.createFilterTaskGraph_();graph.lastTask=graph.lastTask.after(function(){this.selectionController.showScriptControlSelection(graph.lastNode.selection_);},this);return graph . rootTask ; } , selectEverythingAsTask_:function ( selection ) { var passThroughFilter = new tr . c . Filter ( ) ; var filterTask = this.selectionController.addAllEventsMatchingFilterToSelectionAsTask(passThroughFilter,selection);return filterTask ; } , get selection ( ) { if ( this . selection_ = ==undefined){var graph = this.createFilterTaskGraph_();tr.b.Task.RunSynchronously(graph.rootTask);}
return this.selection_;}};tr.c.ScriptingObjectRegistry.register(new TQuery(),{name:'$t'});return{TQuery:TQuery};});'use strict';Polymer('tracing-scripting-control',{_isEnterKey:function(event){return event.keyCode!==229&&event.keyIdentifier==='Enter'; },_setFocused:function(focused){var promptEl=this.$.prompt;if(focused){promptEl.focus();this.$.root.classList.add('focused');if(promptEl.innerText.length>0){var sel=window.getSelection();sel.collapse(promptEl.firstChild,promptEl.innerText.length);}}else{promptEl.blur();this.$.root.classList.remove('focused');var parent=promptEl.parentElement;var nextEl=promptEl.nextSibling;promptEl.remove();parent.insertBefore(promptEl,nextEl);}},onConsoleFocus:function(e){e.stopPropagation();this._setFocused(true);},onConsoleBlur:function(e){e.stopPropagation();this._setFocused(false);},promptKeyDown:function(e){e.stopPropagation();if(!this._isEnterKey(e))
return;var promptEl=this.$.prompt;var command=promptEl.innerText;if(command.length===0)
return;promptEl.innerText='';this.addLine_(String.fromCharCode(187)+' '+command);try{var result=this.controller_.executeCommand(command);}catch(e){result=e.stack||e.stackTrace;}
if(result instanceof tr.b.Task){tr.b.Task.RunWhenIdle(result);}else{this.addLine_(result);}},addLine_:function(line){var historyEl=this.$.history;if(historyEl.innerText.length!==0)
2015-06-18 08:27:29 -06:00
historyEl.innerText+='\n';historyEl.innerText+=line;},promptKeyPress:function(e){e.stopPropagation();},toggleVisibility:function(){var root=this.$.root;if(!this.visible){root.classList.remove('hidden');this._setFocused(true);}else{root.classList.add('hidden');this._setFocused(false);}},get hasFocus(){return this===document.activeElement;},get visible(){var root=this.$.root;return!root.classList.contains('hidden');},get controller(){return this.controller_;},set controller(c){this.controller_=c;}});'use strict';Polymer('tr-ui-side-panel',{ready:function(){this.objectInstance_=undefined;},get rangeOfInterest(){throw new Error('Not implemented');},set rangeOfInterest(rangeOfInterest){throw new Error('Not implemented');},get selection(){throw new Error('Not implemented');},set selection(selection){throw new Error('Not implemented');},get model(){throw new Error('Not implemented');},set model(model){throw new Error('Not implemented');},get listeningToKeys(){throw new Error('Not implemented');},supportsModel:function(m){throw new Error('Not implemented');}});'use strict';Polymer('tr-ui-side-panel-container',{ready:function(){this.activePanelContainer_=this.$.active_panel_container;this.tabStrip_=this.$.tab_strip;this.rangeOfInterest_=new tr.b.Range();this.selectionController_=undefined;this.onSelectionChanged_=this.onSelectionChanged_.bind(this);this.onModelChanged_=this.onModelChanged_.bind(this);},get selectionController(){return this.selectionController_;},set selectionController(selectionController){if(this.selectionController){this.selectionController_.removeEventListener('change',this.onSelectionChanged_);this.selectionController_.removeEventListener('model-changed',this.onModelChanged_);}
2015-06-14 13:52:57 -06:00
this.selectionController_=selectionController;if(this.selectionController){this.selectionController_.addEventListener('change',this.onSelectionChanged_);this.selectionController_.addEventListener('model-changed',this.onModelChanged_);}},get selection(){return this.selectionController_.selection;},onSelectionChanged_:function(){if(this.activePanel)
this.activePanel.selection=this.selection;},get model(){return this.selectionController_.model;},onModelChanged_:function(){this.activePanelType_=undefined;this.updateContents_();},get expanded(){this.hasAttribute('expanded');},get activePanel(){if(this.activePanelContainer_.children.length===0)
return undefined;return this.activePanelContainer_.children[0];},get activePanelType(){return this.activePanelType_;},set activePanelType(panelType){if(this.model===undefined)
throw new Error('Cannot activate panel without a model');var panel=undefined;if(panelType)
panel=document.createElement(panelType);if(panel!==undefined& & !panel.supportsModel(this.model))
throw new Error('Cannot activate panel: does not support this model');if(this.activePanelType){this.getLabelElementForPanelType_(this.activePanelType).removeAttribute('selected');}
this.activePanelContainer_.textContent='';if(panelType===undefined){this.removeAttribute('expanded');this.activePanelType_=undefined;return;}
this.getLabelElementForPanelType_(panelType).setAttribute('selected',true);this.setAttribute('expanded',true);this.activePanelContainer_.appendChild(panel);panel.rangeOfInterest=this.rangeOfInterest_;panel.selection=this.selection_;panel.model=this.model;this.activePanelType_=panelType;},getPanelTypeForConstructor_:function(constructor){for(var i=0;i< this.tabStrip_.children.length ; i + + ) { if ( this . tabStrip_ . children [ i ] . panelType . constructor = =constructor)
return this.tabStrip_.children[i].panelType;}},getLabelElementForPanelType_:function(panelType){for(var i=0;i< this.tabStrip_.children.length ; i + + ) { if ( this . tabStrip_ . children [ i ] . panelType = =panelType)
return this.tabStrip_.children[i];}
2015-06-18 08:27:29 -06:00
return undefined;},updateContents_:function(){var previouslyActivePanelType=this.activePanelType;this.tabStrip_.textContent='';var supportedPanelTypes=[];var panelTypes=tr.ui.b.getPolymerElementsThatSubclass('tr-ui-side-panel');panelTypes.forEach(function(panelType){var labelEl=document.createElement('tab-strip-label');var panel=document.createElement(panelType);labelEl.textContent=panel.textLabel;labelEl.panelType=panelType;var supported=panel.supportsModel(this.model);if(this.model&&supported.supported){supportedPanelTypes.push(panelType); labelEl.setAttribute('enabled',true);labelEl.addEventListener('click',function(){this.activePanelType=this.activePanelType===panelType?undefined:panelType;}.bind(this));}else{labelEl.title='Not supported for the current trace: '+
2015-06-14 13:52:57 -06:00
supported.reason;labelEl.style.display='none';}
this.tabStrip_.appendChild(labelEl);},this);if(previouslyActivePanelType&&supportedPanelTypes.indexOf(previouslyActivePanelType)!=-1){this.activePanelType=previouslyActivePanelType; this.setAttribute('expanded',true);}else{this.activePanelContainer_.textContent='';this.removeAttribute('expanded');}},get rangeOfInterest(){return this.rangeOfInterest_;},set rangeOfInterest(range){if(range==undefined)
throw new Error('Must not be undefined');this.rangeOfInterest_=range;if(this.activePanel)
2015-06-18 08:27:29 -06:00
this.activePanel.rangeOfInterest=range;}});'use strict';Polymer('tr-ui-b-dropdown',{ready:function(){this.$.outer.addEventListener('click',this.onOuterClick_.bind(this));this.$.dialog.addEventListener('click',this.onDialogClick_.bind(this));this.$.dialog.addEventListener('cancel',this.onDialogCancel_.bind(this));},get iconElement(){return this.$.icon;},onOuterClick_:function(e){var or=this.$.outer.getBoundingClientRect();var inside=true;inside&=e.clientX>=or.left; inside&=e.clientX<or.right; inside&=e.clientY>=or.top; inside&=e.clientY<or.bottom; if(!inside)
return;e.preventDefault();if(!this.isOpen)
this.show();else
this.close();},show:function(){if(this.isOpen)
return;this.$.outer.classList.add('open');var ddr=this.$.outer.getBoundingClientRect();var rW=Math.max(ddr.width,150);this.$.dialog.style.minWidth=rW+'px';this.$.dialog.showModal();var ddw=this.$.outer.getBoundingClientRect().width;var w=this.$.dialog.getBoundingClientRect().width;this.$.dialog.style.top=ddr.bottom-1+'px';this.$.dialog.style.left=ddr.left+'px';},onDialogClick_:function(e){if(!this.isOpen)
return;var dr=this.$.dialog.getBoundingClientRect();var inside=true;inside&=e.clientX>=dr.left; inside&=e.clientX<dr.right; inside&=e.clientY>=dr.top; inside&=e.clientY<dr.bottom; if(!inside){e.preventDefault();this.close();}},onDialogCancel_:function(e){e.preventDefault();this.close();},close:function(){if(!this.isOpen)
return;this.$.dialog.close();this.$.outer.classList.remove('open');},get isOpen(){return this.$.dialog.hasAttribute('open');}});'use strict';tr.exportTo('tr.ui.b',function(){var DragHandle=tr.ui.b.define('x-drag-handle');DragHandle.prototype={__proto__:HTMLDivElement.prototype,decorate:function(){this.lastMousePos_=0;this.onMouseMove_=this.onMouseMove_.bind(this);this.onMouseUp_=this.onMouseUp_.bind(this);this.addEventListener('mousedown',this.onMouseDown_);this.target_=undefined;this.horizontal=true;this.observer_=new WebKitMutationObserver(this.didTargetMutate_.bind(this));this.targetSizesByModeKey_={};},get modeKey_(){return this.target_.className==''?'.':this.target_.className;},get target(){return this.target_;},set target(target){this.observer_.disconnect();this.target_=target;if(!this.target_)
return;this.observer_.observe(this.target_,{attributes:true,attributeFilter:['class']});},get horizontal(){return this.horizontal_;},set horizontal(h){this.horizontal_=h;if(this.horizontal_)
this.className='horizontal-drag-handle';else
this.className='vertical-drag-handle';},get vertical(){return!this.horizontal_;},set vertical(v){this.horizontal=!v;},forceMutationObserverFlush_:function(){var records=this.observer_.takeRecords();if(records.length)
this.didTargetMutate_(records);},didTargetMutate_:function(e){var modeSize=this.targetSizesByModeKey_[this.modeKey_];if(modeSize!==undefined){this.setTargetSize_(modeSize);return;}
this.target_.style[this.targetStyleKey_]='';},get targetStyleKey_(){return this.horizontal_?'height':'width';},getTargetSize_:function(){var targetStyleKey=this.targetStyleKey_;if(!this.target_.style[targetStyleKey]){this.target_.style[targetStyleKey]=window.getComputedStyle(this.target_)[targetStyleKey];}
var size=parseInt(this.target_.style[targetStyleKey]);this.targetSizesByModeKey_[this.modeKey_]=size;return size;},setTargetSize_:function(s){this.target_.style[this.targetStyleKey_]=s+'px';this.targetSizesByModeKey_[this.modeKey_]=s;},applyDelta_:function(delta){var curSize=this.getTargetSize_();var newSize;if(this.target_===this.nextElementSibling){newSize=curSize+delta;}else{newSize=curSize-delta;}
this.setTargetSize_(newSize);},onMouseMove_:function(e){var curMousePos=this.horizontal_?e.clientY:e.clientX;var delta=this.lastMousePos_-curMousePos;this.applyDelta_(delta);this.lastMousePos_=curMousePos;e.preventDefault();return true;},onMouseDown_:function(e){if(!this.target_)
return;this.forceMutationObserverFlush_();this.lastMousePos_=this.horizontal_?e.clientY:e.clientX;document.addEventListener('mousemove',this.onMouseMove_);document.addEventListener('mouseup',this.onMouseUp_);e.preventDefault();return true;},onMouseUp_:function(e){document.removeEventListener('mousemove',this.onMouseMove_);document.removeEventListener('mouseup',this.onMouseUp_);e.preventDefault();}};return{DragHandle:DragHandle};});'use strict';tr.exportTo('tr.ui',function(){var THIS_DOC=document.currentScript.ownerDocument;var TimelineView=tr.ui.b.define('x-timeline-view');TimelineView.prototype={__proto__:HTMLUnknownElement.prototype,decorate:function(){var node=tr.ui.b.instantiateTemplate('#timeline-view-template',THIS_DOC);this.appendChild(node);this.titleEl_=this.querySelector('.title');this.leftControlsEl_=this.querySelector('#left-controls');this.rightControlsEl_=this.querySelector('#right-controls');this.collapsingControlsEl_=this.querySelector('#collapsing-controls');this.sidePanelContainer_=this.querySelector('tr-ui-side-panel-container');this.trackViewContainer_=this.querySelector('track-view-container');this.selectionController_=new tr.c.SelectionController(this);this.selectionController_.historyEnabled=true;this.findCtl_=new TracingFindControl();this.findCtl_.controller=new tr.ui.FindController(this.selectionController_);this.findCtl_.addEventListener('keydown',function(e){if(e.keyCode===27){this.focus();e.preventDefault();}}.bind(this));this.scriptingCtl_=new TracingScriptingControl();this.scriptingCtl_.controller=new tr.c.ScriptingController(this.selectionController_);this.sidePanelContainer_.selectionController=this.selectionController_;if(window.tr.e&&window.tr.e.rail&&window.tr.e.rail.RAILScore){this.railScoreSpan_=document.createElement('tr-ui-e-rail-rail-score-span'); this.rightControls.appendChild(this.railScoreSpan_);}else{this.railScoreSpan_=undefined;}
this.optionsDropdown_=document.createElement('tr-ui-b-dropdown');this.optionsDropdown_.iconElement.textContent='View Options';this.showFlowEvents_=false;this.optionsDropdown_.appendChild(tr.ui.b.createCheckBox(this,'showFlowEvents','tr.ui.TimelineView.showFlowEvents',false,'Flow events'));this.highlightVSync_=false;this.highlightVSyncCheckbox_=tr.ui.b.createCheckBox(this,'highlightVSync','tr.ui.TimelineView.highlightVSync',false,'Highlight VSync');this.optionsDropdown_.appendChild(this.highlightVSyncCheckbox_);this.rightControls.appendChild(this.createMetadataButton_());this.rightControls.appendChild(this.optionsDropdown_);this.rightControls.appendChild(this.findCtl_);this.rightControls.appendChild(this.createConsoleButton_());this.rightControls.appendChild(this.createHelpButton_());this.collapsingControls.appendChild(this.scriptingCtl_);this.dragEl_=this.querySelector('x-drag-handle');tr.ui.b.decorate(this.dragEl_,tr.ui.b.DragHandle);this.analysisEl_=this.querySelector('#analysis');this.analysisEl_.selectionController=this.selectionController_;this.addEventListener('requestSelectionChange',function(e){var sc=this.selectionController_;sc.changeSelectionFromRequestSelectionChangeEvent(e.selection);}.bind(this));this.onViewportChanged_=this.onViewportChanged_.bind(this);document.addEventListener('keydown',this.onKeyDown_.bind(this),true);document.addEventListener('keypress',this.onKeypress_.bind(this),true);this.dragEl_.target=this.analysisEl_;},updateDocumentFavicon:function(){var hue;if(!this.model)
2015-06-14 13:52:57 -06:00
hue='blue';else
2015-06-18 08:27:29 -06:00
hue=this.model.faviconHue;var faviconData=tr.ui.b.FaviconsByHue[hue];if(faviconData===undefined)
faviconData=tr.ui.b.FaviconsByHue['blue'];var link=document.head.querySelector('link[rel="shortcut icon"]');if(!link){link=document.createElement('link');link.rel='shortcut icon';document.head.appendChild(link);}
2015-06-14 13:52:57 -06:00
link.href=faviconData;},get showFlowEvents(){return this.showFlowEvents_;},set showFlowEvents(showFlowEvents){this.showFlowEvents_=showFlowEvents;if(!this.trackView_)
return;this.trackView_.viewport.showFlowEvents=showFlowEvents;},get highlightVSync(){return this.highlightVSync_;},set highlightVSync(highlightVSync){this.highlightVSync_=highlightVSync;if(!this.trackView_)
2015-06-18 08:27:29 -06:00
return;this.trackView_.viewport.highlightVSync=highlightVSync;},createHelpButton_:function(){var node=tr.ui.b.instantiateTemplate('#help-btn-template',THIS_DOC);var showEl=node.querySelector('.view-help-button');var helpTextEl=node.querySelector('.view-help-text');var dlg=new tr.ui.b.Overlay();dlg.title='chrome://tracing Help';dlg.classList.add('view-help-overlay');dlg.appendChild(node);function onClick(e){dlg.visible=!dlg.visible;var mod=tr.isMac?'cmd ':'ctrl';var spans=helpTextEl.querySelectorAll('span.mod');for(var i=0;i< spans.length ; i + + ) { spans [ i ] . textContent = mod;}
2015-06-14 13:52:57 -06:00
e.stopPropagation();return false;}
2015-06-18 08:27:29 -06:00
showEl.addEventListener('click',onClick.bind(this));return showEl;},createConsoleButton_:function(){var node=tr.ui.b.instantiateTemplate('#console-btn-template',THIS_DOC);var toggleEl=node.querySelector('.view-console-button');function onClick(e){this.scriptingCtl_.toggleVisibility();e.stopPropagation();return false;}
toggleEl.addEventListener('click',onClick.bind(this));return toggleEl;},createMetadataButton_:function(){var node=tr.ui.b.instantiateTemplate('#metadata-btn-template',THIS_DOC);var showEl=node.querySelector('.view-metadata-button');var textEl=node.querySelector('.info-button-text');var dlg=new tr.ui.b.Overlay();dlg.title='Metadata for trace';dlg.classList.add('view-metadata-overlay');dlg.appendChild(node);function onClick(e){dlg.visible=true;var metadataStrings=[];var model=this.model;for(var data in model.metadata){var meta=model.metadata[data];var name=JSON.stringify(meta.name);var value=JSON.stringify(meta.value,undefined,' ');metadataStrings.push(name+': '+value);}
2015-06-14 13:52:57 -06:00
textEl.textContent=metadataStrings.join('\n');e.stopPropagation();return false;}
showEl.addEventListener('click',onClick.bind(this));function updateVisibility(){showEl.style.display=(this.model&&this.model.metadata.length)?'':'none'; }
var updateVisibility_=updateVisibility.bind(this);updateVisibility_();this.addEventListener('modelChange',updateVisibility_);return showEl;},get leftControls(){return this.leftControlsEl_;},get rightControls(){return this.rightControlsEl_;},get collapsingControls(){return this.collapsingControlsEl_;},get viewTitle(){return this.titleEl_.textContent.substring(this.titleEl_.textContent.length-2);},set viewTitle(text){if(text===undefined){this.titleEl_.textContent='';this.titleEl_.hidden=true;return;}
this.titleEl_.hidden=false;this.titleEl_.textContent=text;},get model(){if(this.trackView_)
return this.trackView_.model;return undefined;},set model(model){var modelInstanceChanged=model!=this.model;var modelValid=model&&!model.bounds.isEmpty; if(modelInstanceChanged){if(this.railScoreSpan_)
this.railScoreSpan_.railScore=undefined;this.trackViewContainer_.textContent='';if(this.trackView_){this.trackView_.viewport.removeEventListener('change',this.onViewportChanged_);this.trackView_.selectionController=undefined;this.trackView_.detach();this.trackView_=undefined;}
this.selectionController_.modelWillChange();}
2015-06-18 08:27:29 -06:00
if(modelValid& & !this.trackView_){this.trackView_=new tr.ui.TimelineTrackView(this);this.trackView.selectionController=this.selectionController_;this.trackView_.focusElement=this.focusElement_?this.focusElement_:this.parentElement;this.trackViewContainer_.appendChild(this.trackView_);this.trackView_.viewport.addEventListener('change',this.onViewportChanged_);}
2015-06-14 13:52:57 -06:00
if(modelValid){this.trackView_.model=model;this.trackView_.viewport.showFlowEvents=this.showFlowEvents;this.trackView_.viewport.highlightVSync=this.highlightVSync;if(this.railScoreSpan_){var railScore=tr.e.rail.RAILScore.fromModel(model);this.railScoreSpan_.railScore=railScore;}}
if(modelInstanceChanged){tr.b.dispatchSimpleEvent(this,'modelChange');this.selectionController_.modelDidChange();this.onViewportChanged_();}},get selectionController(){return this.selectionController_;},get trackView(){return this.trackView_;},get settings(){if(!this.settings_)
this.settings_=new tr.b.Settings();return this.settings_;},set focusElement(value){this.focusElement_=value;if(this.trackView_)
this.trackView_.focusElement=value;},get focusElement(){if(this.focusElement_)
return this.focusElement_;return this.parentElement;},get listenToKeys_(){if(!tr.ui.b.isElementAttachedToDocument(this))
return;if(document.activeElement.type==='textarea')
return false;if(this.sidePanelContainer_.activePanel& & this.sidePanelContainer_.activePanel.listeningToKeys)
return false;if(!this.focusElement_)
return true;if(this.focusElement.tabIndex>=0)
return document.activeElement==this.focusElement;return true;},onKeyDown_:function(e){if(!this.listenToKeys_)
return;},onKeypress_:function(e){if(!this.listenToKeys_)
return;switch(e.keyCode){case'`'.charCodeAt(0):this.scriptingCtl_.toggleVisibility();if(!this.scriptingCtl_.hasFocus)
this.focus();e.preventDefault();break;}
if(this.scriptingCtl_.hasFocus)
return;switch(e.keyCode){case'/'.charCodeAt(0):if(this.findCtl_.hasFocus)
this.focus();else
this.findCtl_.focus();e.preventDefault();break;case'?'.charCodeAt(0):this.querySelector('.view-help-button').click();e.preventDefault();break;}
if(this.findCtl_.hasFocus)
return;switch(e.keyCode){case'v'.charCodeAt(0):this.toggleHighlightVSync_();e.preventDefault();break;}},onViewportChanged_:function(e){var spc=this.sidePanelContainer_;if(!this.trackView_){spc.rangeOfInterest.reset();return;}
var vr=this.trackView_.viewport.interestRange.asRangeObject();if(!spc.rangeOfInterest.equals(vr))
2015-06-18 08:27:29 -06:00
spc.rangeOfInterest=vr;},toggleHighlightVSync_:function(){this.highlightVSyncCheckbox_.checked=!this.highlightVSyncCheckbox_.checked;},setFindCtlText:function(string){this.findCtl_.setText(string);}};return{TimelineView:TimelineView};});'use strict';tr.exportTo('tr',function(){var TraceViewer=tr.ui.b.define('trace-viewer',tr.ui.TimelineView);TraceViewer.prototype={__proto__:tr.ui.TimelineView.prototype,decorate:function(opt_url){tr.ui.TimelineView.prototype.decorate.call(this);if(opt_url===undefined)
2015-06-14 13:52:57 -06:00
return;var url=opt_url;var that=this;var req=new XMLHttpRequest();var is_binary=/[.]gz$/.test(url)||/[.]zip$/.test(url);req.overrideMimeType('text/plain; charset=x-user-defined');req.open('GET',url,true);if(is_binary)
req.responseType='arraybuffer';req.onreadystatechange=function(aEvt){if(req.readyState==4){window.setTimeout(function(){if(req.status==200){onResult(is_binary?req.response:req.responseText);}else{onResultFail(req.status);}},0);}};req.send(null);function onResultFail(err){var overlay=new tr.ui.b.Overlay();overlay.textContent=err+': '+url+' could not be loaded';overlay.title='Failed to fetch data';overlay.visible=true;}
var model;function onResult(result){model=new tr.Model();var p=model.importTracesWithProgressDialog([result],true);p.then(onModelLoaded,onImportFail);}
function onModelLoaded(){that.model=model;that.viewTitle=url;if(that.timeline)
that.timeline.focusElement=that;}
function onImportFail(){var overlay=new tr.ui.b.Overlay();overlay.textContent=tr.b.normalizeException(err).message;overlay.title='Import error';overlay.visible=true;}}};return{TraceViewer:TraceViewer};});'use strict';tr.exportTo('tr.b',function(){var tmpVec2s=[];for(var i=0;i< 8 ; i + + )
tmpVec2s[i]=vec2.create();var tmpVec2a=vec4.create();var tmpVec4a=vec4.create();var tmpVec4b=vec4.create();var tmpMat4=mat4.create();var tmpMat4b=mat4.create();var p00=vec2.createXY(0,0);var p10=vec2.createXY(1,0);var p01=vec2.createXY(0,1);var p11=vec2.createXY(1,1);var lerpingVecA=vec2.create();var lerpingVecB=vec2.create();function lerpVec2(out,a,b,amt){vec2.scale(lerpingVecA,a,amt);vec2.scale(lerpingVecB,b,1-amt);vec2.add(out,lerpingVecA,lerpingVecB);vec2.normalize(out,out);return out;}
function Quad(){this.p1=vec2.create();this.p2=vec2.create();this.p3=vec2.create();this.p4=vec2.create();}
Quad.fromXYWH=function(x,y,w,h){var q=new Quad();vec2.set(q.p1,x,y);vec2.set(q.p2,x+w,y);vec2.set(q.p3,x+w,y+h);vec2.set(q.p4,x,y+h);return q;}
Quad.fromRect=function(r){return new Quad.fromXYWH(r.x,r.y,r.width,r.height);}
Quad.from4Vecs=function(p1,p2,p3,p4){var q=new Quad();vec2.set(q.p1,p1[0],p1[1]);vec2.set(q.p2,p2[0],p2[1]);vec2.set(q.p3,p3[0],p3[1]);vec2.set(q.p4,p4[0],p4[1]);return q;}
Quad.from8Array=function(arr){if(arr.length!=8)
throw new Error('Array must be 8 long');var q=new Quad();q.p1[0]=arr[0];q.p1[1]=arr[1];q.p2[0]=arr[2];q.p2[1]=arr[3];q.p3[0]=arr[4];q.p3[1]=arr[5];q.p4[0]=arr[6];q.p4[1]=arr[7];return q;};Quad.prototype={pointInside:function(point){return pointInImplicitQuad(point,this.p1,this.p2,this.p3,this.p4);},boundingRect:function(){var x0=Math.min(this.p1[0],this.p2[0],this.p3[0],this.p4[0]);var y0=Math.min(this.p1[1],this.p2[1],this.p3[1],this.p4[1]);var x1=Math.max(this.p1[0],this.p2[0],this.p3[0],this.p4[0]);var y1=Math.max(this.p1[1],this.p2[1],this.p3[1],this.p4[1]);return new tr.b.Rect.fromXYWH(x0,y0,x1-x0,y1-y0);},clone:function(){var q=new Quad();vec2.copy(q.p1,this.p1);vec2.copy(q.p2,this.p2);vec2.copy(q.p3,this.p3);vec2.copy(q.p4,this.p4);return q;},scale:function(s){var q=new Quad();this.scaleFast(q,s);return q;},scaleFast:function(dstQuad,s){vec2.copy(dstQuad.p1,this.p1,s);vec2.copy(dstQuad.p2,this.p2,s);vec2.copy(dstQuad.p3,this.p3,s);vec2.copy(dstQuad.p3,this.p3,s);},isRectangle:function(){var bounds=this.boundingRect();return(bounds.x==this.p1[0]&&bounds.y==this.p1[1]&&bounds.width==this.p2[0]-this.p1[0]&&bounds.y==this.p2[1]&&bounds.width==this.p3[0]-this.p1[0]&&bounds.height==this.p3[1]-this.p2[1]&&bounds.x==this.p4[0]&&bounds.height==this.p4[1]-this.p2[1]); },projectUnitRect:function(rect){var q=new Quad();this.projectUnitRectFast(q,rect);return q;},projectUnitRectFast:function(dstQuad,rect){var v12=tmpVec2s[0];var v14=tmpVec2s[1];var v23=tmpVec2s[2];var v43=tmpVec2s[3];var l12,l14,l23,l43;vec2.sub(v12,this.p2,this.p1);l12=vec2.length(v12);vec2.scale(v12,v12,1/l12);vec2.sub(v14,this.p4,this.p1);l14=vec2.length(v14);vec2.scale(v14,v14,1/l14);vec2.sub(v23,this.p3,this.p2);l23=vec2.length(v23);vec2.scale(v23,v23,1/l23);vec2.sub(v43,this.p3,this.p4);l43=vec2.length(v43);vec2.scale(v43,v43,1/l43);var b12=tmpVec2s[0];var b14=tmpVec2s[1];var b23=tmpVec2s[2];var b43=tmpVec2s[3];lerpVec2(b12,v12,v43,rect.y);lerpVec2(b43,v12,v43,1-rect.bottom);lerpVec2(b14,v14,v23,rect.x);lerpVec2(b23,v14,v23,1-rect.right);vec2.addTwoScaledUnitVectors(tmpVec2a,b12,l12*rect.x,b14,l14*rect.y);vec2.add(dstQuad.p1,this.p1,tmpVec2a);vec2.addTwoScaledUnitVectors(tmpVec2a,b12,l12*-(1.0-rect.right),b23,l23*rect.y);vec2.add(dstQuad.p2,this.p2,tmpVec2a);vec2.addTwoScaledUnitVectors(tmpVec2a,b43,l43*-(1.0-rect.right),b23,l23*-(1.0-rect.bottom));vec2.add(dstQuad.p3,this.p3,tmpVec2a);vec2.addTwoScaledUnitVectors(tmpVec2a,b43,l43*rect.left,b14,l14*-(1.0-rect.bottom));vec2.add(dstQuad.p4,this.p4,tmpVec2a);},toString:function(){return'Quad('+
vec2.toString(this.p1)+', '+
vec2.toString(this.p2)+', '+
vec2.toString(this.p3)+', '+
vec2.toString(this.p4)+')';}};function sign(p1,p2,p3){return(p1[0]-p3[0])*(p2[1]-p3[1])-
(p2[0]-p3[0])*(p1[1]-p3[1]);}
function pointInTriangle2(pt,p1,p2,p3){var b1=sign(pt,p1,p2)< 0.0 ; var b2 = sign(pt,p2,p3)<0.0;var b3 = sign(pt,p3,p1)<0.0;return((b1==b2)&&(b2==b3));}
function pointInImplicitQuad(point,p1,p2,p3,p4){return pointInTriangle2(point,p1,p2,p3)||pointInTriangle2(point,p1,p3,p4);}
2015-06-18 08:27:29 -06:00
return{pointInTriangle2:pointInTriangle2,pointInImplicitQuad:pointInImplicitQuad,Quad:Quad};});'use strict';tr.exportTo('tr.ui.annotations',function(){function RectAnnotationView(viewport,annotation){this.viewport_=viewport;this.annotation_=annotation;}
RectAnnotationView.prototype={__proto__:tr.ui.annotations.AnnotationView.prototype,draw:function(ctx){var dt=this.viewport_.currentDisplayTransform;var startCoords=this.annotation_.startLocation.toViewCoordinates(this.viewport_);var endCoords=this.annotation_.endLocation.toViewCoordinates(this.viewport_);var startY=startCoords.viewY-ctx.canvas.getBoundingClientRect().top;var sizeY=endCoords.viewY-startCoords.viewY;if(startY+sizeY< 0 ) { startY = sizeY;}else if ( startY < 0 ) { startY = 0;}
2015-06-14 13:52:57 -06:00
ctx.fillStyle=this.annotation_.fillStyle;ctx.fillRect(startCoords.viewX,startY,endCoords.viewX-startCoords.viewX,sizeY);}};return{RectAnnotationView:RectAnnotationView};});'use strict';tr.exportTo('tr.model',function(){function RectAnnotation(start,end){tr.model.Annotation.apply(this,arguments);this.startLocation_=start;this.endLocation_=end;this.fillStyle='rgba(255, 180, 0, 0.3)';}
2015-06-18 08:27:29 -06:00
RectAnnotation.fromDict=function(dict){var args=dict.args;var startLoc=new tr.ui.b.Location(args.start.xWorld,args.start.yComponents);var endLoc=new tr.ui.b.Location(args.end.xWorld,args.end.yComponents);return new tr.model.RectAnnotation(startLoc,endLoc);}
RectAnnotation.prototype={__proto__:tr.model.Annotation.prototype,get startLocation(){return this.startLocation_;},get endLocation(){return this.endLocation_;},toDict:function(){return{typeName:'rect',args:{start:this.startLocation.toDict(),end:this.endLocation.toDict()}};},createView_:function(viewport){return new tr.ui.annotations.RectAnnotationView(viewport,this);}};tr.model.Annotation.register(RectAnnotation,{typeName:'rect'});return{RectAnnotation:RectAnnotation};});'use strict';tr.exportTo('tr.ui.annotations',function(){function CommentBoxAnnotationView(viewport,annotation){this.viewport_=viewport;this.annotation_=annotation;this.textArea_=undefined;this.styleWidth=250;this.styleHeight=50;this.fontSize=10;this.rightOffset=50;this.topOffset=25;}
CommentBoxAnnotationView.prototype={__proto__:tr.ui.annotations.AnnotationView.prototype,removeTextArea:function(){this.textArea_.parentNode.removeChild(this.textArea_);},draw:function(ctx){var coords=this.annotation_.location.toViewCoordinates(this.viewport_);if(coords.viewX< 0 ) { if ( this . textArea_ )
2015-06-14 13:52:57 -06:00
this.textArea_.style.visibility='hidden';return;}
if(!this.textArea_){this.textArea_=document.createElement('textarea');this.textArea_.style.position='absolute';this.textArea_.readOnly=true;this.textArea_.value=this.annotation_.text;this.textArea_.style.zIndex=1;ctx.canvas.parentNode.appendChild(this.textArea_);}
this.textArea_.style.width=this.styleWidth+'px';this.textArea_.style.height=this.styleHeight+'px';this.textArea_.style.fontSize=this.fontSize+'px';this.textArea_.style.visibility='visible';this.textArea_.style.left=coords.viewX+ctx.canvas.getBoundingClientRect().left+
this.rightOffset+'px';this.textArea_.style.top=coords.viewY-ctx.canvas.getBoundingClientRect().top-
2015-06-18 08:27:29 -06:00
this.topOffset+'px';ctx.strokeStyle='rgb(0, 0, 0)';ctx.lineWidth=2;ctx.beginPath();tr.ui.b.drawLine(ctx,coords.viewX,coords.viewY-ctx.canvas.getBoundingClientRect().top,coords.viewX+this.rightOffset,coords.viewY-this.topOffset-
2015-06-14 13:52:57 -06:00
ctx.canvas.getBoundingClientRect().top);ctx.stroke();}};return{CommentBoxAnnotationView:CommentBoxAnnotationView};});'use strict';tr.exportTo('tr.model',function(){function CommentBoxAnnotation(location,text){tr.model.Annotation.apply(this,arguments);this.location=location;this.text=text;}
2015-06-18 08:27:29 -06:00
CommentBoxAnnotation.fromDict=function(dict){var args=dict.args;var location=new tr.ui.b.Location(args.location.xWorld,args.location.yComponents);return new tr.model.CommentBoxAnnotation(location,args.text);};CommentBoxAnnotation.prototype={__proto__:tr.model.Annotation.prototype,onRemove:function(){this.view_.removeTextArea();},toDict:function(){return{typeName:'comment_box',args:{text:this.text,location:this.location.toDict()}};},createView_:function(viewport){return new tr.ui.annotations.CommentBoxAnnotationView(viewport,this);}};tr.model.Annotation.register(CommentBoxAnnotation,{typeName:'comment_box'});return{CommentBoxAnnotation:CommentBoxAnnotation};});'use strict';tr.exportTo('tr.e.importer',function(){var Importer=tr.importer.Importer;function deepCopy(value){if(!(value instanceof Object)){if(value===undefined||value===null)
2015-06-14 13:52:57 -06:00
return value;if(typeof value=='string')
return value.substring();if(typeof value=='boolean')
return value;if(typeof value=='number')
return value;throw new Error('Unrecognized: '+typeof value);}
var object=value;if(object instanceof Array){var res=new Array(object.length);for(var i=0;i< object.length ; i + + )
res[i]=deepCopy(object[i]);return res;}
if(object.__proto__!=Object.prototype)
throw new Error('Can only clone simple types');var res={};for(var key in object){res[key]=deepCopy(object[key]);}
return res;}
2015-06-18 08:27:29 -06:00
var timestampFromUs=tr.b.units.Time.timestampFromUs;var maybeTimestampFromUs=tr.b.units.Time.maybeTimestampFromUs;function TraceEventImporter(model,eventData){this.importPriority=1;this.model_=model;this.events_=undefined;this.sampleEvents_=undefined;this.stackFrameEvents_=undefined;this.systemTraceEvents_=undefined;this.eventsWereFromString_=false;this.softwareMeasuredCpuCount_=undefined;this.allAsyncEvents_=[];this.allFlowEvents_=[];this.allObjectEvents_=[];this.traceEventSampleStackFramesByName_={};this.allMemoryDumpEvents_={};if(typeof(eventData)==='string'||eventData instanceof String){eventData=eventData.trim();if(eventData[0]==='['){eventData=eventData.replace(/\s*,\s*$/,'');if(eventData[eventData.length-1]!==']')
2015-06-14 13:52:57 -06:00
eventData=eventData+']';}
this.events_=JSON.parse(eventData);this.eventsWereFromString_=true;}else{this.events_=eventData;}
2015-06-18 08:27:29 -06:00
this.traceAnnotations_=this.events_.traceAnnotations;if(this.events_.traceEvents){var container=this.events_;this.events_=this.events_.traceEvents;this.systemTraceEvents_=container.systemTraceEvents;this.sampleEvents_=container.samples;this.stackFrameEvents_=container.stackFrames;if(container.displayTimeUnit){var unitName=container.displayTimeUnit;var unit=tr.b.units.Time.supportedUnits[unitName];if(unit===undefined){throw new Error('Unit '+unitName+' is not supported.');}
this.model_.intrinsicTimeUnit=unit;}
for(var fieldName in container){if(fieldName==='traceEvents'||fieldName==='systemTraceEvents'||fieldName==='samples'||fieldName==='stackFrames'||fieldName==='traceAnnotations')
2015-06-14 13:52:57 -06:00
continue;this.model_.metadata.push({name:fieldName,value:container[fieldName]});}}}
TraceEventImporter.canImport=function(eventData){if(typeof(eventData)==='string'||eventData instanceof String){eventData=eventData.trim();return eventData[0]=='{'||eventData[0]=='[';}
if(eventData instanceof Array& & eventData.length& & eventData[0].ph)
return true;if(eventData.traceEvents){if(eventData.traceEvents instanceof Array){if(eventData.traceEvents.length& & eventData.traceEvents[0].ph)
return true;if(eventData.samples.length& & eventData.stackFrames!==undefined)
return true;}}
return false;};TraceEventImporter.prototype={__proto__:Importer.prototype,extractSubtraces:function(){var tmp=this.systemTraceEvents_;this.systemTraceEvents_=undefined;return tmp?[tmp]:[];},deepCopyIfNeeded_:function(obj){if(obj===undefined)
obj={};if(this.eventsWereFromString_)
return obj;return deepCopy(obj);},processAsyncEvent:function(event){var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);this.allAsyncEvents_.push({sequenceNumber:this.allAsyncEvents_.length,event:event,thread:thread});},processFlowEvent:function(event){var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);this.allFlowEvents_.push({refGuid:tr.b.GUID.getLastGuid(),sequenceNumber:this.allFlowEvents_.length,event:event,thread:thread});},processCounterEvent:function(event){var ctr_name;if(event.id!==undefined)
ctr_name=event.name+'['+event.id+']';else
ctr_name=event.name;var ctr=this.model_.getOrCreateProcess(event.pid).getOrCreateCounter(event.cat,ctr_name);if(ctr.numSeries===0){for(var seriesName in event.args){ctr.addSeries(new tr.model.CounterSeries(seriesName,tr.ui.b.getColorIdForGeneralPurposeString(ctr.name+'.'+seriesName)));}
if(ctr.numSeries===0){this.model_.importWarning({type:'counter_parse_error',message:'Expected counter '+event.name+' to have at least one argument to use as a value.'});delete ctr.parent.counters[ctr.name];return;}}
2015-06-18 08:27:29 -06:00
var ts=timestampFromUs(event.ts);ctr.series.forEach(function(series){var val=event.args[series.name]?event.args[series.name]:0;series.addCounterSample(ts,val);});},processObjectEvent:function(event){var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);this.allObjectEvents_.push({sequenceNumber:this.allObjectEvents_.length,event:event,thread:thread});},processDurationEvent:function(event){var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);var ts=timestampFromUs(event.ts);if(!thread.sliceGroup.isTimestampValidForBeginOrEnd(ts)){this.model_.importWarning({type:'duration_parse_error',message:'Timestamps are moving backward.'});return;}
if(event.ph=='B'){var slice=thread.sliceGroup.beginSlice(event.cat,event.name,timestampFromUs(event.ts),this.deepCopyIfNeeded_(event.args),timestampFromUs(event.tts),event.argsStripped);slice.startStackFrame=this.getStackFrameForEvent_(event);}else if(event.ph=='I'||event.ph=='i'){if(event.s!==undefined& & event.s!=='t')
throw new Error('This should never happen');thread.sliceGroup.beginSlice(event.cat,event.name,timestampFromUs(event.ts),this.deepCopyIfNeeded_(event.args),timestampFromUs(event.tts));var slice=thread.sliceGroup.endSlice(timestampFromUs(event.ts),timestampFromUs(event.tts));slice.startStackFrame=this.getStackFrameForEvent_(event);slice.endStackFrame=undefined;}else{if(!thread.sliceGroup.openSliceCount){this.model_.importWarning({type:'duration_parse_error',message:'E phase event without a matching B phase event.'});return;}
var slice=thread.sliceGroup.endSlice(timestampFromUs(event.ts),timestampFromUs(event.tts));if(event.name& & slice.title!=event.name){this.model_.importWarning({type:'title_match_error',message:'Titles do not match. Title is '+
2015-06-14 13:52:57 -06:00
slice.title+' in openSlice, and is '+
event.name+' in endSlice'});}
slice.endStackFrame=this.getStackFrameForEvent_(event);this.mergeArgsInto_(slice.args,event.args,slice.title);}},mergeArgsInto_:function(dstArgs,srcArgs,eventName){for(var arg in srcArgs){if(dstArgs[arg]!==undefined){this.model_.importWarning({type:'arg_merge_error',message:'Different phases of '+eventName+' provided values for argument '+arg+'.'+' The last provided value will be used.'});}
2015-06-18 08:27:29 -06:00
dstArgs[arg]=this.deepCopyIfNeeded_(srcArgs[arg]);}},processCompleteEvent:function(event){var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);var slice=thread.sliceGroup.pushCompleteSlice(event.cat,event.name,timestampFromUs(event.ts),maybeTimestampFromUs(event.dur),maybeTimestampFromUs(event.tts),maybeTimestampFromUs(event.tdur),this.deepCopyIfNeeded_(event.args),event.argsStripped);slice.startStackFrame=this.getStackFrameForEvent_(event);slice.endStackFrame=this.getStackFrameForEvent_(event,true);},processMetadataEvent:function(event){if(event.argsStripped)
return;if(event.name=='process_name'){var process=this.model_.getOrCreateProcess(event.pid);process.name=event.args.name;}else if(event.name=='process_labels'){var process=this.model_.getOrCreateProcess(event.pid);var labels=event.args.labels.split(',');for(var i=0;i< labels.length ; i + + )
2015-06-14 13:52:57 -06:00
process.addLabelIfNeeded(labels[i]);}else if(event.name=='process_sort_index'){var process=this.model_.getOrCreateProcess(event.pid);process.sortIndex=event.args.sort_index;}else if(event.name=='thread_name'){var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);thread.name=event.args.name;}else if(event.name=='thread_sort_index'){var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);thread.sortIndex=event.args.sort_index;}else if(event.name=='num_cpus'){var n=event.args.number;if(this.softwareMeasuredCpuCount_!==undefined)
n=Math.max(n,this.softwareMeasuredCpuCount_);this.softwareMeasuredCpuCount_=n;}else{this.model_.importWarning({type:'metadata_parse_error',message:'Unrecognized metadata name: '+event.name});}},processInstantEvent:function(event){if(event.s=='t'||event.s===undefined){this.processDurationEvent(event);return;}
var constructor;switch(event.s){case'g':constructor=tr.model.GlobalInstantEvent;break;case'p':constructor=tr.model.ProcessInstantEvent;break;default:this.model_.importWarning({type:'instant_parse_error',message:'I phase event with unknown "s" field value.'});return;}
2015-06-18 08:27:29 -06:00
var colorId=tr.ui.b.getColorIdForGeneralPurposeString(event.name);var instantEvent=new constructor(event.cat,event.name,colorId,timestampFromUs(event.ts),this.deepCopyIfNeeded_(event.args));switch(instantEvent.type){case tr.model.InstantEventType.GLOBAL:this.model_.pushInstantEvent(instantEvent);break;case tr.model.InstantEventType.PROCESS:var process=this.model_.getOrCreateProcess(event.pid);process.pushInstantEvent(instantEvent);break;default:throw new Error('Unknown instant event type: '+event.s);}},processTraceSampleEvent:function(event){var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);var stackFrame=this.getStackFrameForEvent_(event);if(stackFrame===undefined){stackFrame=this.traceEventSampleStackFramesByName_[event.name];}
2015-06-14 13:52:57 -06:00
if(stackFrame===undefined){var id='te-'+tr.b.GUID.allocate();stackFrame=new tr.model.StackFrame(undefined,id,event.cat,event.name,tr.ui.b.getColorIdForGeneralPurposeString(event.name));this.model_.addStackFrame(stackFrame);this.traceEventSampleStackFramesByName_[event.name]=stackFrame;}
2015-06-18 08:27:29 -06:00
var sample=new tr.model.Sample(undefined,thread,'TRACE_EVENT_SAMPLE',timestampFromUs(event.ts),stackFrame,1,this.deepCopyIfNeeded_(event.args));this.model_.samples.push(sample);},getOrCreateMemoryDumpEvents_:function(dumpId){if(this.allMemoryDumpEvents_[dumpId]===undefined){this.allMemoryDumpEvents_[dumpId]={global:undefined,process:[]};}
2015-06-14 13:52:57 -06:00
return this.allMemoryDumpEvents_[dumpId];},processMemoryDumpEvent:function(event){if(event.id===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:event.ph+' phase event without a dump ID.'});return;}
var events=this.getOrCreateMemoryDumpEvents_(event.id);if(event.ph==='v'){events.process.push(event);}else if(event.ph==='V'){if(events.global!==undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Multiple V phase events with the same dump ID.'});return;}
events.global=event;}else{throw new Error('Invalid memory dump event phase "'+event.ph+'".');}},importEvents:function(){var csr=new tr.ClockSyncRecord('ftrace_importer',0,{});this.model_.clockSyncRecords.push(csr);if(this.stackFrameEvents_)
this.importStackFrames_();if(this.traceAnnotations_)
2015-06-18 08:27:29 -06:00
this.importAnnotations_();var events=this.events_;for(var eI=0;eI< events.length ; eI + + ) { var event = events[eI];if(event.args==='__stripped__'){event.argsStripped=true;event.args=undefined;}
if(event.ph==='B'||event.ph==='E'){this.processDurationEvent(event);}else if(event.ph==='X'){this.processCompleteEvent(event);}else if(event.ph==='b'||event.ph==='e'||event.ph==='n'||event.ph==='S'||event.ph==='F'||event.ph==='T'||event.ph==='p'){this.processAsyncEvent(event);}else if(event.ph=='I'||event.ph=='i'){this.processInstantEvent(event);}else if(event.ph=='P'){this.processTraceSampleEvent(event);}else if(event.ph=='C'){this.processCounterEvent(event);}else if(event.ph=='M'){this.processMetadataEvent(event);}else if(event.ph==='N'||event.ph==='D'||event.ph==='O'){this.processObjectEvent(event);}else if(event.ph==='s'||event.ph==='t'||event.ph==='f'){this.processFlowEvent(event);}else if(event.ph==='v'||event.ph==='V'){this.processMemoryDumpEvent(event);}else{this.model_.importWarning({type:'parse_error',message:'Unrecognized event phase: '+
2015-06-14 13:52:57 -06:00
event.ph+' ('+event.name+')'});}}},importStackFrames_:function(){var m=this.model_;var events=this.stackFrameEvents_;for(var id in events){var event=events[id];var textForColor=event.category?event.category:event.name;var frame=new tr.model.StackFrame(undefined,'g'+id,event.category,event.name,tr.ui.b.getColorIdForGeneralPurposeString(textForColor));m.addStackFrame(frame);}
for(var id in events){var event=events[id];if(event.parent===undefined)
continue;var frame=m.stackFrames['g'+id];if(frame===undefined)
throw new Error('omg');var parentFrame;if(event.parent===undefined){parentFrame=undefined;}else{parentFrame=m.stackFrames['g'+event.parent];if(parentFrame===undefined)
throw new Error('omg');}
frame.parentFrame=parentFrame;}},importAnnotations_:function(){for(var id in this.traceAnnotations_){var annotation=tr.model.Annotation.fromDictIfPossible(this.traceAnnotations_[id]);if(!annotation){this.model_.importWarning({type:'annotation_warning',message:'Unrecognized traceAnnotation typeName \"'+
this.traceAnnotations_[id].typeName+'\"'});continue;}
this.model_.addAnnotation(annotation);}},finalizeImport:function(){if(this.softwareMeasuredCpuCount_!==undefined){this.model_.kernel.softwareMeasuredCpuCount=this.softwareMeasuredCpuCount_;}
this.createAsyncSlices_();this.createFlowSlices_();this.createExplicitObjects_();this.createImplicitObjects_();this.createMemoryDumps_();},getStackFrameForEvent_:function(event,opt_lookForEndEvent){var sf;var stack;if(opt_lookForEndEvent){sf=event.esf;stack=event.estack;}else{sf=event.sf;stack=event.stack;}
if(stack!==undefined& & sf!==undefined){this.model_.importWarning({type:'stack_frame_and_stack_error',message:'Event at '+event.ts+' cannot have both a stack and a stackframe.'});return undefined;}
if(stack!==undefined)
return this.model_.resolveStackToStackFrame_(event.pid,stack);if(sf===undefined)
return undefined;var stackFrame=this.model_.stackFrames['g'+sf];if(stackFrame===undefined){this.model_.importWarning({type:'sample_import_error',message:'No frame for '+sf});return;}
return stackFrame;},resolveStackToStackFrame_:function(pid,stack){return undefined;},importSampleData:function(){if(!this.sampleEvents_)
return;var m=this.model_;var events=this.sampleEvents_;if(this.events_.length===0){for(var i=0;i< events.length ; i + + ) { var event = events[i];m.getOrCreateProcess(event.tid).getOrCreateThread(event.tid);}}
var threadsByTid={};m.getAllThreads().forEach(function(t){threadsByTid[t.tid]=t;});for(var i=0;i< events.length ; i + + ) { var event = events[i];var thread = threadsByTid[event.tid];if(thread===undefined){m.importWarning({type:'sample_import_error',message:'Thread ' + events . tid + ' not found ' } ) ; continue ; }
var cpu;if(event.cpu!==undefined)
2015-06-18 08:27:29 -06:00
cpu=m.kernel.getOrCreateCpu(event.cpu);var stackFrame=this.getStackFrameForEvent_(event);var sample=new tr.model.Sample(cpu,thread,event.name,timestampFromUs(event.ts),stackFrame,event.weight);m.samples.push(sample);}},joinRefs:function(){this.joinObjectRefs_();},createAsyncSlices_:function(){if(this.allAsyncEvents_.length===0)
2015-06-14 13:52:57 -06:00
return;this.allAsyncEvents_.sort(function(x,y){var d=x.event.ts-y.event.ts;if(d!==0)
return d;return x.sequenceNumber-y.sequenceNumber;});var legacyEvents=[];var nestableAsyncEventsByKey={};for(var i=0;i< this.allAsyncEvents_.length ; i + + ) { var asyncEventState = this.allAsyncEvents_[i];var event = asyncEventState.event;if(event.ph==='S'||event.ph==='F'||event.ph==='T'||event.ph==='p'){legacyEvents.push(asyncEventState);continue;}
if(event.cat===undefined){this.model_.importWarning({type:'async_slice_parse_error',message:'Nestable async events (ph: b, e, or n) require a '+'cat parameter.'});continue;}
if(event.name===undefined){this.model_.importWarning({type:'async_slice_parse_error',message:'Nestable async events (ph: b, e, or n) require a '+'name parameter.'});continue;}
if(event.id===undefined){this.model_.importWarning({type:'async_slice_parse_error',message:'Nestable async events (ph: b, e, or n) require an '+'id parameter.'});continue;}
var key=event.cat+':'+event.id;if(nestableAsyncEventsByKey[key]===undefined)
nestableAsyncEventsByKey[key]=[];nestableAsyncEventsByKey[key].push(asyncEventState);}
this.createLegacyAsyncSlices_(legacyEvents);for(var key in nestableAsyncEventsByKey){var eventStateEntries=nestableAsyncEventsByKey[key];var parentStack=[];for(var i=0;i< eventStateEntries.length ; + + i ) { var eventStateEntry = eventStateEntries[i];if(eventStateEntry.event.ph==='e'){var parentIndex = -1;for(var k = parentStack.length-1;k > =0;--k){if(parentStack[k].event.name===eventStateEntry.event.name){parentIndex=k;break;}}
if(parentIndex===-1){eventStateEntry.finished=false;}else{parentStack[parentIndex].end=eventStateEntry;while(parentIndex< parentStack.length ) { parentStack . pop ( ) ; } } }
if(parentStack.length>0)
eventStateEntry.parentEntry=parentStack[parentStack.length-1];if(eventStateEntry.event.ph==='b')
parentStack.push(eventStateEntry);}
var topLevelSlices=[];for(var i=0;i< eventStateEntries.length ; + + i ) { var eventStateEntry = eventStateEntries[i];if(eventStateEntry.event.ph==='e'&&eventStateEntry.finished===undefined){continue;}
var startState=undefined;var endState=undefined;var sliceArgs=eventStateEntry.event.args||{};var sliceError=undefined;if(eventStateEntry.event.ph==='n'){startState=eventStateEntry;endState=eventStateEntry;}else if(eventStateEntry.event.ph==='b'){if(eventStateEntry.end===undefined){eventStateEntry.end=eventStateEntries[eventStateEntries.length-1];sliceError='Slice has no matching END. End time has been adjusted.';this.model_.importWarning({type:'async_slice_parse_error',message:'Nestable async BEGIN event at '+
eventStateEntry.event.ts+' with name='+
eventStateEntry.event.name+' and id='+eventStateEntry.event.id+' was unmatched.'});}else{var concatenateArguments=function(args1,args2){if(args1.params===undefined||args2.params===undefined)
return tr.b.concatenateObjects(args1,args2);var args3={};args3.params=tr.b.concatenateObjects(args1.params,args2.params);return tr.b.concatenateObjects(args1,args2,args3);}
var endArgs=eventStateEntry.end.event.args||{};sliceArgs=concatenateArguments(sliceArgs,endArgs);}
startState=eventStateEntry;endState=eventStateEntry.end;}else{sliceError='Slice has no matching BEGIN. Start time has been adjusted.';this.model_.importWarning({type:'async_slice_parse_error',message:'Nestable async END event at '+
eventStateEntry.event.ts+' with name='+
eventStateEntry.event.name+' and id='+eventStateEntry.event.id+' was unmatched.'});startState=eventStateEntries[0];endState=eventStateEntry;}
2015-06-18 08:27:29 -06:00
var isTopLevel=(eventStateEntry.parentEntry===undefined);var asyncSliceConstructor=tr.model.AsyncSlice.getConstructor(eventStateEntry.event.cat,eventStateEntry.event.name);var thread_start=undefined;var thread_duration=undefined;if(startState.event.tts&&startState.event.use_async_tts){thread_start=timestampFromUs(startState.event.tts); if(endState.event.tts){var thread_end=timestampFromUs(endState.event.tts);thread_duration=thread_end-thread_start;}}
var slice=new asyncSliceConstructor(eventStateEntry.event.cat,eventStateEntry.event.name,tr.ui.b.getColorIdForGeneralPurposeString(eventStateEntry.event.name),timestampFromUs(startState.event.ts),sliceArgs,timestampFromUs(endState.event.ts-startState.event.ts),isTopLevel,thread_start,thread_duration,startState.event.argsStripped);slice.startThread=startState.thread;slice.endThread=endState.thread;slice.id=key;if(sliceError!==undefined)
2015-06-14 13:52:57 -06:00
slice.error=sliceError;eventStateEntry.slice=slice;if(isTopLevel){topLevelSlices.push(slice);}else if(eventStateEntry.parentEntry.slice!==undefined){eventStateEntry.parentEntry.slice.subSlices.push(slice);}}
for(var si=0;si< topLevelSlices.length ; si + + ) { topLevelSlices [ si ] . startThread . asyncSliceGroup . push ( topLevelSlices [ si ] ) ; } } } , createLegacyAsyncSlices_:function ( legacyEvents ) { if ( legacyEvents . length = ==0)
return;legacyEvents.sort(function(x,y){var d=x.event.ts-y.event.ts;if(d!=0)
return d;return x.sequenceNumber-y.sequenceNumber;});var asyncEventStatesByNameThenID={};for(var i=0;i< legacyEvents.length ; i + + ) { var asyncEventState = legacyEvents[i];var event = asyncEventState.event;var name = event.name;if(name===undefined){this.model_.importWarning({type:'async_slice_parse_error',message:'Async events ( ph: S , T , p , or F ) require a name ' + ' parameter . ' } ) ; continue ; }
var id=event.id;if(id===undefined){this.model_.importWarning({type:'async_slice_parse_error',message:'Async events (ph: S, T, p, or F) require an id parameter.'});continue;}
if(event.ph==='S'){if(asyncEventStatesByNameThenID[name]===undefined)
asyncEventStatesByNameThenID[name]={};if(asyncEventStatesByNameThenID[name][id]){this.model_.importWarning({type:'async_slice_parse_error',message:'At '+event.ts+', a slice of the same id '+id+' was alrady open.'});continue;}
asyncEventStatesByNameThenID[name][id]=[];asyncEventStatesByNameThenID[name][id].push(asyncEventState);}else{if(asyncEventStatesByNameThenID[name]===undefined){this.model_.importWarning({type:'async_slice_parse_error',message:'At '+event.ts+', no slice named '+name+' was open.'});continue;}
if(asyncEventStatesByNameThenID[name][id]===undefined){this.model_.importWarning({type:'async_slice_parse_error',message:'At '+event.ts+', no slice named '+name+' with id='+id+' was open.'});continue;}
2015-06-18 08:27:29 -06:00
var events=asyncEventStatesByNameThenID[name][id];events.push(asyncEventState);if(event.ph==='F'){var asyncSliceConstructor=tr.model.AsyncSlice.getConstructor(events[0].event.cat,name);var slice=new asyncSliceConstructor(events[0].event.cat,name,tr.ui.b.getColorIdForGeneralPurposeString(name),timestampFromUs(events[0].event.ts),tr.b.concatenateObjects(events[0].event.args,events[events.length-1].event.args),timestampFromUs(event.ts-events[0].event.ts),true,undefined,undefined,events[0].event.argsStripped);slice.startThread=events[0].thread;slice.endThread=asyncEventState.thread;slice.id=id;var stepType=events[1].event.ph;var isValid=true;for(var j=1;j< events.length-1 ; + + j ) { if ( events [ j ] . event . ph = =='T'||events[j].event.ph==='p'){isValid=this.assertStepTypeMatches_(stepType,events[j]);if(!isValid)
2015-06-14 13:52:57 -06:00
break;}
if(events[j].event.ph==='S'){this.model_.importWarning({type:'async_slice_parse_error',message:'At '+event.event.ts+', a slice named '+
event.event.name+' with id='+event.event.id+' had a step before the start event.'});continue;}
if(events[j].event.ph==='F'){this.model_.importWarning({type:'async_slice_parse_error',message:'At '+event.event.ts+', a slice named '+
event.event.name+' with id='+event.event.id+' had a step after the finish event.'});continue;}
2015-06-18 08:27:29 -06:00
var startIndex=j+(stepType==='T'?0:-1);var endIndex=startIndex+1;var subName=events[j].event.name;if(!events[j].event.argsStripped& & (events[j].event.ph==='T'||events[j].event.ph==='p'))
subName=subName+':'+events[j].event.args.step;var asyncSliceConstructor=tr.model.AsyncSlice.getConstructor(events[0].event.cat,subName);var subSlice=new asyncSliceConstructor(events[0].event.cat,subName,tr.ui.b.getColorIdForGeneralPurposeString(subName+j),timestampFromUs(events[startIndex].event.ts),this.deepCopyIfNeeded_(events[j].event.args),timestampFromUs(events[endIndex].event.ts-events[startIndex].event.ts),undefined,undefined,events[startIndex].event.argsStripped);subSlice.startThread=events[startIndex].thread;subSlice.endThread=events[endIndex].thread;subSlice.id=id;slice.subSlices.push(subSlice);}
2015-06-14 13:52:57 -06:00
if(isValid){slice.startThread.asyncSliceGroup.push(slice);}
delete asyncEventStatesByNameThenID[name][id];}}}},assertStepTypeMatches_:function(stepType,event){if(stepType!=event.event.ph){this.model_.importWarning({type:'async_slice_parse_error',message:'At '+event.event.ts+', a slice named '+
event.event.name+' with id='+event.event.id+' had both begin and end steps, which is not allowed.'});return false;}
return true;},createFlowSlices_:function(){if(this.allFlowEvents_.length===0)
return;var that=this;function validateFlowEvent(){if(event.name===undefined){that.model_.importWarning({type:'flow_slice_parse_error',message:'Flow events (ph: s, t or f) require a name parameter.'});return false;}
if(event.id===undefined){that.model_.importWarning({type:'flow_slice_parse_error',message:'Flow events (ph: s, t or f) require an id parameter.'});return false;}
return true;}
2015-06-18 08:27:29 -06:00
function createFlowEvent(thread,event,refGuid){var ts=timestampFromUs(event.ts);var startSlice=thread.sliceGroup.findSliceAtTs(ts);if(startSlice===undefined)
return undefined;var flowEvent=new tr.model.FlowEvent(event.cat,event.id,event.name,tr.ui.b.getColorIdForGeneralPurposeString(event.name),timestampFromUs(event.ts),that.deepCopyIfNeeded_(event.args));flowEvent.startSlice=startSlice;startSlice.outFlowEvents.push(flowEvent);return flowEvent;}
function finishFlowEventWith(flowEvent,thread,event,refGuid,bindToParent){var endSlice;var ts=timestampFromUs(event.ts);if(bindToParent){endSlice=thread.sliceGroup.findSliceAtTs(ts);}else{endSlice=thread.sliceGroup.findNextSliceAfter(ts,refGuid);}
2015-06-14 13:52:57 -06:00
if(endSlice===undefined)
2015-06-18 08:27:29 -06:00
return false;endSlice.inFlowEvents.push(flowEvent);flowEvent.endSlice=endSlice;flowEvent.duration=ts-flowEvent.start;that.mergeArgsInto_(flowEvent.args,event.args,flowEvent.title);return true;}
2015-06-14 13:52:57 -06:00
this.allFlowEvents_.sort(function(x,y){var d=x.event.ts-y.event.ts;if(d!=0)
return d;return x.sequenceNumber-y.sequenceNumber;});var flowIdToEvent={};for(var i=0;i< this.allFlowEvents_.length ; + + i ) { var data = this.allFlowEvents_[i];var refGuid = data.refGuid;var event = data.event;var thread = data.thread;if(!validateFlowEvent(event))
continue;var flowEvent;if(event.ph==='s'){if(flowIdToEvent[event.id]){this.model_.importWarning({type:'flow_slice_start_error',message:'event id '+event.id+' already seen when '+'encountering start of flow event.'});continue;}
flowEvent=createFlowEvent(thread,event,refGuid);if(!flowEvent){this.model_.importWarning({type:'flow_slice_start_error',message:'event id '+event.id+' does not start '+'at an actual slice, so cannot be created.'});continue;}
flowIdToEvent[event.id]=flowEvent;}else if(event.ph==='t'||event.ph==='f'){flowEvent=flowIdToEvent[event.id];if(flowEvent===undefined){this.model_.importWarning({type:'flow_slice_ordering_error',message:'Found flow phase '+event.ph+' for id: '+event.id+' but no flow start found.'});continue;}
var bindToParent=event.ph==='t';if(event.ph==='f'){if(event.bp===undefined){if(event.cat.indexOf('input')>-1)
2015-06-18 08:27:29 -06:00
bindToParent=true;else if(event.cat.indexOf('ipc.flow')>-1)
2015-06-14 13:52:57 -06:00
bindToParent=true;}else{if(event.bp!=='e'){this.model_.importWarning({type:'flow_slice_bind_point_error',message:'Flow event with invalid binding point (event.bp).'});continue;}
bindToParent=true;}}
var ok=finishFlowEventWith(flowEvent,thread,event,refGuid,bindToParent);if(ok){that.model_.flowEvents.push(flowEvent);}else{this.model_.importWarning({type:'flow_slice_start_error',message:'event id '+event.id+' does not end '+'at an actual slice, so cannot be created.'});}
flowIdToEvent[event.id]=undefined;if(ok&&event.ph==='t'){flowEvent=createFlowEvent(thread,event); flowIdToEvent[event.id]=flowEvent;}}}},createExplicitObjects_:function(){if(this.allObjectEvents_.length==0)
return;function processEvent(objectEventState){var event=objectEventState.event;var thread=objectEventState.thread;if(event.name===undefined){this.model_.importWarning({type:'object_parse_error',message:'While processing '+JSON.stringify(event)+': '+'Object events require an name parameter.'});}
if(event.id===undefined){this.model_.importWarning({type:'object_parse_error',message:'While processing '+JSON.stringify(event)+': '+'Object events require an id parameter.'});}
2015-06-18 08:27:29 -06:00
var process=thread.parent;var ts=timestampFromUs(event.ts);var instance;if(event.ph=='N'){try{instance=process.objects.idWasCreated(event.id,event.cat,event.name,ts);}catch(e){this.model_.importWarning({type:'object_parse_error',message:'While processing create of '+
2015-06-14 13:52:57 -06:00
event.id+' at ts='+ts+': '+e});return;}}else if(event.ph=='O'){if(event.args.snapshot===undefined){this.model_.importWarning({type:'object_parse_error',message:'While processing '+event.id+' at ts='+ts+': '+'Snapshots must have args: {snapshot: ...}'});return;}
var snapshot;try{var args=this.deepCopyIfNeeded_(event.args.snapshot);var cat;if(args.cat){cat=args.cat;delete args.cat;}else{cat=event.cat;}
var baseTypename;if(args.base_type){baseTypename=args.base_type;delete args.base_type;}else{baseTypename=undefined;}
snapshot=process.objects.addSnapshot(event.id,cat,event.name,ts,args,baseTypename);snapshot.snapshottedOnThread=thread;}catch(e){this.model_.importWarning({type:'object_parse_error',message:'While processing snapshot of '+
event.id+' at ts='+ts+': '+e});return;}
instance=snapshot.objectInstance;}else if(event.ph=='D'){try{instance=process.objects.idWasDeleted(event.id,event.cat,event.name,ts);}catch(e){this.model_.importWarning({type:'object_parse_error',message:'While processing delete of '+
event.id+' at ts='+ts+': '+e});return;}}
if(instance){instance.colorId=tr.ui.b.getColorIdForGeneralPurposeString(instance.typeName);}}
this.allObjectEvents_.sort(function(x,y){var d=x.event.ts-y.event.ts;if(d!=0)
return d;return x.sequenceNumber-y.sequenceNumber;});var allObjectEvents=this.allObjectEvents_;for(var i=0;i< allObjectEvents.length ; i + + ) { var objectEventState = allObjectEvents[i];try{processEvent.call(this,objectEventState);}catch(e){this.model_.importWarning({type:'object_parse_error',message:e.message});}}},createImplicitObjects_:function(){tr.b.iterItems(this.model_.processes,function(pid,process){this.createImplicitObjectsForProcess_(process);},this);},createImplicitObjectsForProcess_:function(process){function processField ( referencingObject , referencingObjectFieldName , referencingObjectFieldValue , containingSnapshot ) { if ( ! referencingObjectFieldValue )
return;if(referencingObjectFieldValue instanceof
tr.model.ObjectSnapshot)
return null;if(referencingObjectFieldValue.id===undefined)
return;var implicitSnapshot=referencingObjectFieldValue;var rawId=implicitSnapshot.id;var m=/(.+)\/(.+)/.exec(rawId);if(!m)
throw new Error('Implicit snapshots must have names.');delete implicitSnapshot.id;var name=m[1];var id=m[2];var res;var cat;if(implicitSnapshot.cat!==undefined)
cat=implicitSnapshot.cat;else
cat=containingSnapshot.objectInstance.category;var baseTypename;if(implicitSnapshot.base_type)
baseTypename=implicitSnapshot.base_type;else
baseTypename=undefined;try{res=process.objects.addSnapshot(id,cat,name,containingSnapshot.ts,implicitSnapshot,baseTypename);}catch(e){this.model_.importWarning({type:'object_snapshot_parse_error',message:'While processing implicit snapshot of '+
rawId+' at ts='+containingSnapshot.ts+': '+e});return;}
res.objectInstance.hasImplicitSnapshots=true;res.containingSnapshot=containingSnapshot;res.snapshottedOnThread=containingSnapshot.snapshottedOnThread;referencingObject[referencingObjectFieldName]=res;if(!(res instanceof tr.model.ObjectSnapshot))
throw new Error('Created object must be instanceof snapshot');return res.args;}
function iterObject(object,func,containingSnapshot,thisArg){if(!(object instanceof Object))
return;if(object instanceof Array){for(var i=0;i< object.length ; i + + ) { var res = func.call(thisArg,object,i,object[i],containingSnapshot);if(res===null)
continue;if(res)
iterObject(res,func,containingSnapshot,thisArg);else
iterObject(object[i],func,containingSnapshot,thisArg);}
return;}
for(var key in object){var res=func.call(thisArg,object,key,object[key],containingSnapshot);if(res===null)
continue;if(res)
iterObject(res,func,containingSnapshot,thisArg);else
iterObject(object[key],func,containingSnapshot,thisArg);}}
process.objects.iterObjectInstances(function(instance){instance.snapshots.forEach(function(snapshot){if(snapshot.args.id!==undefined)
throw new Error('args cannot have an id field inside it');iterObject(snapshot.args,processField,snapshot,this);},this);},this);},createMemoryDumps_:function(){tr.b.iterItems(this.allMemoryDumpEvents_,function(id,events){var range=new tr.b.Range();if(events.global!==undefined)
2015-06-18 08:27:29 -06:00
range.addValue(timestampFromUs(events.global.ts));for(var i=0;i< events.process.length ; i + + )
range.addValue(timestampFromUs(events.process[i].ts));var globalMemoryDump=new tr.model.GlobalMemoryDump(this.model_,range.min);globalMemoryDump.duration=range.range;this.model_.globalMemoryDumps.push(globalMemoryDump);if(events.process.length===0){this.model_.importWarning({type:'memory_dump_parse_error',message:'No process memory dumps associated with global memory'+' dump '+id+'.'});}
2015-06-14 13:52:57 -06:00
var allMemoryAllocatorDumpsByGuid={};var globalMemoryAllocatorDumpsByFullName={};events.process.forEach(function(processEvent){var pid=processEvent.pid;if(pid in globalMemoryDump.processMemoryDumps){this.model_.importWarning({type:'memory_dump_parse_error',message:'Multiple process memory dumps with pid='+pid+' for dump id '+id+'.'});return;}
var dumps=processEvent.args.dumps;if(dumps===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'dumps not found in process memory dump for '+'pid='+pid+' and dump id='+id+'.'});return;}
2015-06-18 08:27:29 -06:00
var process=this.model_.getOrCreateProcess(pid);var processMemoryDump=new tr.model.ProcessMemoryDump(globalMemoryDump,process,timestampFromUs(processEvent.ts));if(dumps.process_totals===undefined||dumps.process_totals.resident_set_bytes===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Mandatory field resident_set_bytes not found in'+' process memory dump for pid='+pid+' and dump id='+id+'.'});processMemoryDump.totalResidentBytes=undefined;}else{processMemoryDump.totalResidentBytes=parseInt(dumps.process_totals.resident_set_bytes,16);}
2015-06-14 13:52:57 -06:00
if(dumps.process_mmaps& & dumps.process_mmaps.vm_regions){function parseByteStat(rawValue){if(rawValue===undefined)
return undefined;return parseInt(rawValue,16);}
processMemoryDump.vmRegions=dumps.process_mmaps.vm_regions.map(function(rawRegion){var byteStats=new tr.model.VMRegionByteStats(parseByteStat(rawRegion.bs.pc),parseByteStat(rawRegion.bs.pd),parseByteStat(rawRegion.bs.sc),parseByteStat(rawRegion.bs.sd),parseByteStat(rawRegion.bs.pss),parseByteStat(rawRegion.bs.sw));return new tr.model.VMRegion(parseInt(rawRegion.sa,16),parseInt(rawRegion.sz,16),rawRegion.pf,rawRegion.mf,byteStats);});}
var processMemoryAllocatorDumpsByFullName={};if(dumps.allocators!==undefined){tr.b.iterItems(dumps.allocators,function(fullName,rawAllocatorDump){var guid=rawAllocatorDump.guid;if(guid===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Memory allocator dump '+fullName+' from pid='+pid+' does not have a GUID.'});}
var GLOBAL_MEMORY_ALLOCATOR_DUMP_PREFIX='global/';var containerMemoryDump;var dstIndex;if(fullName.startsWith(GLOBAL_MEMORY_ALLOCATOR_DUMP_PREFIX)){fullName=fullName.substring(GLOBAL_MEMORY_ALLOCATOR_DUMP_PREFIX.length);containerMemoryDump=globalMemoryDump;dstIndex=globalMemoryAllocatorDumpsByFullName;}else{containerMemoryDump=processMemoryDump;dstIndex=processMemoryAllocatorDumpsByFullName;}
var allocatorDump=allMemoryAllocatorDumpsByGuid[guid];if(allocatorDump===undefined){if(fullName in dstIndex){this.model_.importWarning({type:'memory_dump_parse_error',message:'Multiple GUIDs provided for'+' memory allocator dump '+fullName+': '+
dstIndex[fullName].guid+', '+guid+' (ignored).'});return;}
allocatorDump=new tr.model.MemoryAllocatorDump(containerMemoryDump,fullName,guid);dstIndex[fullName]=allocatorDump;if(guid!==undefined)
allMemoryAllocatorDumpsByGuid[guid]=allocatorDump;}else{if(allocatorDump.containerMemoryDump!==containerMemoryDump){this.model_.importWarning({type:'memory_dump_parse_error',message:'Memory allocator dump '+fullName+' (GUID='+guid+') dumped in different contexts.'});return;}
if(allocatorDump.fullName!==fullName){this.model_.importWarning({type:'memory_dump_parse_error',message:'Memory allocator dump with GUID='+guid+' has multiple names: '+allocatorDump.fullName+', '+fullName+' (ignored).'});return;}}
var attributes=rawAllocatorDump.attrs;tr.b.iterItems(attributes,function(attrName,attrArgs){if(attrName in allocatorDump.attributes){this.model_.importWarning({type:'memory_dump_parse_error',message:'Multiple values provided for attribute '+
attrName+' of memory allocator dump '+fullName+' (GUID='+guid+').'});return;}
var attrValue=tr.model.Attribute.fromDictIfPossible(attrArgs);allocatorDump.addAttribute(attrName,attrValue);},this);},this);}
processMemoryDump.memoryAllocatorDumps=this.inferMemoryAllocatorDumpTree_(processMemoryAllocatorDumpsByFullName);process.memoryDumps.push(processMemoryDump);globalMemoryDump.processMemoryDumps[pid]=processMemoryDump;},this);globalMemoryDump.memoryAllocatorDumps=this.inferMemoryAllocatorDumpTree_(globalMemoryAllocatorDumpsByFullName);events.process.forEach(function(processEvent){var dumps=processEvent.args.dumps;if(dumps===undefined)
2015-06-18 08:27:29 -06:00
return;var edges=dumps.allocators_graph;if(edges===undefined)
2015-06-14 13:52:57 -06:00
return;edges.forEach(function(rawEdge){var sourceGuid=rawEdge.source;var sourceDump=allMemoryAllocatorDumpsByGuid[sourceGuid];if(sourceDump===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Edge is missing source memory allocator dump (GUID='+
sourceGuid+')'});return;}
var targetGuid=rawEdge.target;var targetDump=allMemoryAllocatorDumpsByGuid[targetGuid];if(targetDump===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Edge is missing target memory allocator dump (GUID='+
targetGuid+')'});return;}
var importance=rawEdge.importance;var edge=new tr.model.MemoryAllocatorDumpLink(sourceDump,targetDump,importance);switch(rawEdge.type){case'ownership':if(sourceDump.owns!==undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Memory allocator dump '+sourceDump.fullName+' (GUID='+sourceGuid+') already owns a memory'+' allocator dump ('+
sourceDump.owns.target.fullName+').'});return;}
sourceDump.owns=edge;targetDump.ownedBy.push(edge);break;case'retention':sourceDump.retains.push(edge);targetDump.retainedBy.push(edge);break;default:this.model_.importWarning({type:'memory_dump_parse_error',message:'Invalid edge type: '+rawEdge.type+' (source='+sourceGuid+', target='+targetGuid+', importance='+importance+').'});}},this);},this);},this);},inferMemoryAllocatorDumpTree_:function(memoryAllocatorDumpsByFullName){var rootAllocatorDumps=[];var fullNames=Object.keys(memoryAllocatorDumpsByFullName);fullNames.sort();fullNames.forEach(function(fullName){var allocatorDump=memoryAllocatorDumpsByFullName[fullName];while(true){var lastSlashIndex=fullName.lastIndexOf('/');if(lastSlashIndex===-1){rootAllocatorDumps.push(allocatorDump);break;}
var parentFullName=fullName.substring(0,lastSlashIndex);var parentAllocatorDump=memoryAllocatorDumpsByFullName[parentFullName];var parentAlreadyExisted=true;if(parentAllocatorDump===undefined){parentAlreadyExisted=false;parentAllocatorDump=new tr.model.MemoryAllocatorDump(allocatorDump.containerMemoryDump,parentFullName);memoryAllocatorDumpsByFullName[parentFullName]=parentAllocatorDump;}
allocatorDump.parent=parentAllocatorDump;parentAllocatorDump.children.push(allocatorDump);if(parentAlreadyExisted)
break;fullName=parentFullName;allocatorDump=parentAllocatorDump;}},this);return rootAllocatorDumps;},joinObjectRefs_:function(){tr.b.iterItems(this.model_.processes,function(pid,process){this.joinObjectRefsForProcess_(process);},this);},joinObjectRefsForProcess_:function(process){var patchupsToApply=[];tr.b.iterItems(process.threads,function(tid,thread){thread.asyncSliceGroup.slices.forEach(function(item){this.searchItemForIDRefs_(patchupsToApply,process.objects,'start',item);},this);thread.sliceGroup.slices.forEach(function(item){this.searchItemForIDRefs_(patchupsToApply,process.objects,'start',item);},this);},this);process.objects.iterObjectInstances(function(instance){instance.snapshots.forEach(function(item){this.searchItemForIDRefs_(patchupsToApply,process.objects,'ts',item);},this);},this);patchupsToApply.forEach(function(patchup){patchup.object[patchup.field]=patchup.value;});},searchItemForIDRefs_:function(patchupsToApply,objectCollection,itemTimestampField,item){if(!item.args)
throw new Error('item is missing its args');function handleField(object,fieldName,fieldValue){if(!fieldValue||(!fieldValue.id_ref& & !fieldValue.idRef))
return;var id=fieldValue.id_ref||fieldValue.idRef;var ts=item[itemTimestampField];var snapshot=objectCollection.getSnapshotAt(id,ts);if(!snapshot)
return;patchupsToApply.push({object:object,field:fieldName,value:snapshot});}
function iterObjectFieldsRecursively(object){if(!(object instanceof Object))
return;if((object instanceof tr.model.ObjectSnapshot)||(object instanceof Float32Array)||(object instanceof tr.b.Quad))
return;if(object instanceof Array){for(var i=0;i< object.length ; i + + ) { handleField ( object , i , object [ i ] ) ; iterObjectFieldsRecursively ( object [ i ] ) ; }
return;}
for(var key in object){var value=object[key];handleField(object,key,value);iterObjectFieldsRecursively(value);}}
2015-06-18 08:27:29 -06:00
iterObjectFieldsRecursively(item.args);}};tr.importer.Importer.register(TraceEventImporter);return{TraceEventImporter:TraceEventImporter};});'use strict';tr.exportTo('tr.ui.e.highlighter',function(){var Highlighter=tr.ui.tracks.Highlighter;function VSyncHighlighter(viewport){Highlighter.call(this,viewport);this.times_=[];}
2015-06-14 13:52:57 -06:00
VSyncHighlighter.VSYNC_HIGHLIGHT_COLOR={r:0,g:0,b:255};VSyncHighlighter.VSYNC_HIGHLIGHT_ALPHA=0.1;VSyncHighlighter.VSYNC_DENSITY_TRANSPARENT=0.20;VSyncHighlighter.VSYNC_DENSITY_OPAQUE=0.10;VSyncHighlighter.VSYNC_DENSITY_RANGE=VSyncHighlighter.VSYNC_DENSITY_TRANSPARENT-
VSyncHighlighter.VSYNC_DENSITY_OPAQUE;VSyncHighlighter.VSYNC_COUNTER_PRECISIONS={'android.VSYNC-app':15,'android.VSYNC':15};VSyncHighlighter.VSYNC_SLICE_PRECISIONS={'RenderWidgetHostViewAndroid::OnVSync':5,'VSYNC':10,'vblank':10,'DisplayLinkMac::GetVSyncParameters':5};VSyncHighlighter.findVSyncTimes=function(model){var times=[];var maxPrecision=Number.NEGATIVE_INFINITY;var maxTitle=undefined;var useInstead=function(title,precisions){if(title!=maxTitle){var precision=precisions[title];if(precision===undefined||precision< =maxPrecision){if(precision===maxPrecision){console.warn('Encountered two different VSync events ('+
maxTitle+', '+title+') with the same precision, '+'ignoring the newer one ('+title+')');}
return false;}
maxPrecision=precision;maxTitle=title;times=[];}
return true;}
for(var pid in model.processes){var process=model.processes[pid];for(var cid in process.counters){if(useInstead(cid,VSyncHighlighter.VSYNC_COUNTER_PRECISIONS)){var counter=process.counters[cid];for(var i=0;i< counter.series.length ; i + + ) { var series = counter.series[i];Array.prototype.push.apply(times,series.timestamps);}}}
for(var tid in process.threads){var thread=process.threads[tid];for(var i=0;i< thread.sliceGroup.slices.length ; i + + ) { var slice = thread.sliceGroup.slices[i];if(useInstead(slice.title,VSyncHighlighter.VSYNC_SLICE_PRECISIONS)){times.push(slice.start);}}}}
times.sort(function(x,y){return x-y;});return times;};VSyncHighlighter.generateStripes=function(times,minTime,maxTime){var stripes=[];var lowIndex=tr.b.findLowIndexInSortedArray(times,function(time){return time;},minTime);if(lowIndex>times.length){lowIndex=times.length;}
var highIndex=lowIndex-1;while(times[highIndex+1]< =maxTime){highIndex++;}
for(var i=lowIndex-(lowIndex%2);i< =highIndex;i+=2){var left=i< lowIndex ? minTime:times [ i ] ; var right = i+1 > highIndex?maxTime:times[i+1];stripes.push([left,right]);}
return stripes;}
VSyncHighlighter.prototype={__proto__:Highlighter.prototype,processModel:function(model){this.times_=VSyncHighlighter.findVSyncTimes(model);},drawHighlight:function(ctx,dt,viewLWorld,viewRWorld,viewHeight){if(!this.viewport_.highlightVSync){return;}
var stripes=VSyncHighlighter.generateStripes(this.times_,viewLWorld,viewRWorld);if(stripes.length==0){return;}
var stripeRange=stripes[stripes.length-1][1]-stripes[0][0];var stripeDensity=stripes.length/(dt.scaleX*stripeRange);var clampedStripeDensity=tr.b.clamp(stripeDensity,VSyncHighlighter.VSYNC_DENSITY_OPAQUE,VSyncHighlighter.VSYNC_DENSITY_TRANSPARENT);var opacity=(VSyncHighlighter.VSYNC_DENSITY_TRANSPARENT-clampedStripeDensity)/VSyncHighlighter.VSYNC_DENSITY_RANGE;if(opacity==0){return;}
2015-06-18 08:27:29 -06:00
var pixelRatio=window.devicePixelRatio||1;var height=viewHeight*pixelRatio;ctx.fillStyle=tr.ui.b.colorToRGBAString(VSyncHighlighter.VSYNC_HIGHLIGHT_COLOR,VSyncHighlighter.VSYNC_HIGHLIGHT_ALPHA*opacity);for(var i=0;i< stripes.length ; i + + ) { var xLeftView = dt.xWorldToView(stripes[i][0]);var xRightView = dt.xWorldToView(stripes[i][1]);ctx.fillRect(xLeftView,0,xRightView-xLeftView,height);}}};tr.ui.tracks.Highlighter.register(VSyncHighlighter);return{VSyncHighlighter:VSyncHighlighter};});
2015-01-30 03:31:43 -07:00
< / script >
< / head >
< body >
< / body >
< / html >