profview.js 46.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

"use strict"

function $(id) {
  return document.getElementById(id);
}

11 12 13 14 15 16
function removeAllChildren(element) {
  while (element.firstChild) {
    element.removeChild(element.firstChild);
  }
}

17
let components;
18
function createViews() {
19 20 21 22 23 24
  components = [
    new CallTreeView(),
    new TimelineView(),
    new HelpView(),
    new SummaryView(),
    new ModeBarView(),
25
    new ScriptSourceView(),
26
  ];
27 28 29 30 31
}

function emptyState() {
  return {
    file : null,
32
    mode : null,
33
    currentCodeId : null,
34
    viewingSource: false,
35 36
    start : 0,
    end : Infinity,
37 38 39
    timelineSize : {
      width : 0,
      height : 0
40 41 42 43 44
    },
    callTree : {
      attribution : "js-exclude-bc",
      categories : "code-type",
      sort : "time"
45 46
    },
    sourceData: null
47 48 49 50 51 52 53 54 55 56 57
  };
}

function setCallTreeState(state, callTreeState) {
  state = Object.assign({}, state);
  state.callTree = callTreeState;
  return state;
}

let main = {
  currentState : emptyState(),
58
  renderPending : false,
59 60

  setMode(mode) {
61
    if (mode !== main.currentState.mode) {
62 63 64 65 66 67 68 69 70 71 72

      function setCallTreeModifiers(attribution, categories, sort) {
        let callTreeState = Object.assign({}, main.currentState.callTree);
        callTreeState.attribution = attribution;
        callTreeState.categories = categories;
        callTreeState.sort = sort;
        return callTreeState;
      }

      let state = Object.assign({}, main.currentState);

73 74
      switch (mode) {
        case "bottom-up":
75 76
          state.callTree =
              setCallTreeModifiers("js-exclude-bc", "code-type", "time");
77 78
          break;
        case "top-down":
79 80
          state.callTree =
              setCallTreeModifiers("js-exclude-bc", "none", "time");
81 82
          break;
        case "function-list":
83 84
          state.callTree =
              setCallTreeModifiers("js-exclude-bc", "code-type", "own-time");
85 86
          break;
      }
87 88 89 90

      state.mode = mode;

      main.currentState = state;
91 92 93 94 95
      main.delayRender();
    }
  },

  setCallTreeAttribution(attribution) {
96
    if (attribution !== main.currentState.attribution) {
97 98 99 100 101 102 103 104
      let callTreeState = Object.assign({}, main.currentState.callTree);
      callTreeState.attribution = attribution;
      main.currentState = setCallTreeState(main.currentState,  callTreeState);
      main.delayRender();
    }
  },

  setCallTreeSort(sort) {
105
    if (sort !== main.currentState.sort) {
106 107 108 109 110 111 112 113
      let callTreeState = Object.assign({}, main.currentState.callTree);
      callTreeState.sort = sort;
      main.currentState = setCallTreeState(main.currentState,  callTreeState);
      main.delayRender();
    }
  },

  setCallTreeCategories(categories) {
114
    if (categories !== main.currentState.categories) {
115 116 117 118 119 120 121 122
      let callTreeState = Object.assign({}, main.currentState.callTree);
      callTreeState.categories = categories;
      main.currentState = setCallTreeState(main.currentState,  callTreeState);
      main.delayRender();
    }
  },

  setViewInterval(start, end) {
123 124
    if (start !== main.currentState.start ||
        end !== main.currentState.end) {
125 126 127 128 129 130 131
      main.currentState = Object.assign({}, main.currentState);
      main.currentState.start = start;
      main.currentState.end = end;
      main.delayRender();
    }
  },

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
  updateSources(file) {
    let statusDiv = $("source-status");
    if (!file) {
      statusDiv.textContent = "";
      return;
    }
    if (!file.scripts || file.scripts.length === 0) {
      statusDiv.textContent =
          "Script source not available. Run profiler with --log-source-code.";
      return;
    }
    statusDiv.textContent = "Script source is available.";
    main.currentState.sourceData = new SourceData(file);
  },

147
  setFile(file) {
148
    if (file !== main.currentState.file) {
149 150
      let lastMode = main.currentState.mode || "summary";
      main.currentState = emptyState();
151
      main.currentState.file = file;
152
      main.updateSources(file);
153
      main.setMode(lastMode);
154 155 156 157
      main.delayRender();
    }
  },

158
  setCurrentCode(codeId) {
159
    if (codeId !== main.currentState.currentCodeId) {
160 161 162 163 164 165
      main.currentState = Object.assign({}, main.currentState);
      main.currentState.currentCodeId = codeId;
      main.delayRender();
    }
  },

166 167 168 169 170 171 172 173
  setViewingSource(value) {
    if (main.currentState.viewingSource !== value) {
      main.currentState = Object.assign({}, main.currentState);
      main.currentState.viewingSource = value;
      main.delayRender();
    }
  },

174
  onResize() {
175
    main.delayRender();
176 177 178 179 180 181 182 183
  },

  onLoad() {
    function loadHandler(evt) {
      let f = evt.target.files[0];
      if (f) {
        let reader = new FileReader();
        reader.onload = function(event) {
184
          main.setFile(JSON.parse(event.target.result));
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
        };
        reader.onerror = function(event) {
          console.error(
              "File could not be read! Code " + event.target.error.code);
        };
        reader.readAsText(f);
      } else {
        main.setFile(null);
      }
    }
    $("fileinput").addEventListener(
        "change", loadHandler, false);
    createViews();
  },

  delayRender()  {
201 202 203 204 205
    if (main.renderPending) return;
    main.renderPending = true;

    window.requestAnimationFrame(() => {
      main.renderPending = false;
206 207 208 209 210 211 212
      for (let c of components) {
        c.render(main.currentState);
      }
    });
  }
};

213 214
const CATEGORY_COLOR = "#f5f5f5";
const bucketDescriptors =
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
  [{
    kinds: ["JS_OPT"],
    color: "#64dd17",
    backgroundColor: "#80e27e",
    text: "JS Optimized"
  },
  {
    kinds: ["JS_TURBOPROP"],
    color: "#693eb8",
    backgroundColor: "#a6c452",
    text: "JS Turboprop"
  },
  {
    kinds: ["JS_BASELINE"],
    color: "#b3005b",
    backgroundColor: "#ff9e80",
    text: "JS Baseline"
  },
  {
    kinds: ["JS_UNOPT", "BC"],
    color: "#dd2c00",
    backgroundColor: "#ff9e80",
    text: "JS Unoptimized"
  },
  {
    kinds: ["IC"],
    color: "#ff6d00",
    backgroundColor: "#ffab40",
    text: "IC"
  },
  {
    kinds: ["STUB", "BUILTIN", "REGEXP"],
    color: "#ffd600",
    backgroundColor: "#ffea00",
    text: "Other generated"
  },
  {
    kinds: ["CPP", "LIB"],
    color: "#304ffe",
    backgroundColor: "#6ab7ff",
    text: "C++"
  },
  {
    kinds: ["CPP_EXT"],
    color: "#003c8f",
    backgroundColor: "#c0cfff",
    text: "C++/external"
  },
  {
    kinds: ["CPP_PARSE"],
    color: "#aa00ff",
    backgroundColor: "#ffb2ff",
    text: "C++/Parser"
  },
  {
    kinds: ["CPP_COMP_BC"],
    color: "#43a047",
    backgroundColor: "#88c399",
    text: "C++/Bytecode compiler"
  },
  {
    kinds: ["CPP_COMP_BASELINE"],
    color: "#43a047",
    backgroundColor: "#5a8000",
    text: "C++/Baseline compiler"
  },
  {
    kinds: ["CPP_COMP"],
    color: "#00e5ff",
    backgroundColor: "#6effff",
    text: "C++/Compiler"
  },
  {
    kinds: ["CPP_GC"],
    color: "#6200ea",
    backgroundColor: "#e1bee7",
    text: "C++/GC"
  },
  {
    kinds: ["UNKNOWN"],
    color: "#bdbdbd",
    backgroundColor: "#efefef",
    text: "Unknown"
  }
  ];
300

301
let kindToBucketDescriptor = {};
302 303 304 305 306 307 308
for (let i = 0; i < bucketDescriptors.length; i++) {
  let bucket = bucketDescriptors[i];
  for (let j = 0; j < bucket.kinds.length; j++) {
    kindToBucketDescriptor[bucket.kinds[j]] = bucket;
  }
}

309 310 311 312 313 314 315 316 317 318 319 320
function bucketFromKind(kind) {
  for (let i = 0; i < bucketDescriptors.length; i++) {
    let bucket = bucketDescriptors[i];
    for (let j = 0; j < bucket.kinds.length; j++) {
      if (bucket.kinds[j] === kind) {
        return bucket;
      }
    }
  }
  return null;
}

321 322 323 324
function codeTypeToText(type) {
  switch (type) {
    case "UNKNOWN":
      return "Unknown";
325
    case "CPP_PARSE":
326
      return "C++ Parser";
327 328 329 330 331
    case "CPP_COMP_BASELINE":
      return "C++ Baseline Compiler";
    case "CPP_COMP_BC":
      return "C++ Bytecode Compiler";
    case "CPP_COMP":
332
      return "C++ Compiler";
333
    case "CPP_GC":
334
      return "C++ GC";
335
    case "CPP_EXT":
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
      return "C++ External";
    case "CPP":
      return "C++";
    case "LIB":
      return "Library";
    case "IC":
      return "IC";
    case "BC":
      return "Bytecode";
    case "STUB":
      return "Stub";
    case "BUILTIN":
      return "Builtin";
    case "REGEXP":
      return "RegExp";
351
    case "JS_OPT":
352
      return "JS opt";
353
    case "JS_TURBOPROP":
354
      return "JS Turboprop";
355 356 357
    case "JS_BASELINE":
      return "JS Baseline";
    case "JS_UNOPT":
358 359 360 361 362
      return "JS unopt";
  }
  console.error("Unknown type: " + type);
}

363
function createTypeNode(type) {
364 365 366 367 368 369 370
  if (type === "CAT") {
    return document.createTextNode("");
  }
  let span = document.createElement("span");
  span.classList.add("code-type-chip");
  span.textContent = codeTypeToText(type);

371
  return span;
372 373 374 375 376 377 378 379 380 381
}

function filterFromFilterId(id) {
  switch (id) {
    case "full-tree":
      return (type, kind) => true;
    case "js-funs":
      return (type, kind) => type !== 'CODE';
    case "js-exclude-bc":
      return (type, kind) =>
382
          type !== 'CODE' || kind !== "BytecodeHandler";
383 384 385
  }
}

386
function createIndentNode(indent) {
387 388
  let div = document.createElement("div");
  div.style.display = "inline-block";
389
  div.style.width = (indent + 0.5) + "em";
390 391 392
  return div;
}

393 394 395 396 397 398
function createArrowNode() {
  let span = document.createElement("span");
  span.classList.add("tree-row-arrow");
  return span;
}

399 400 401
function createFunctionNode(name, codeId) {
  let nameElement = document.createElement("span");
  nameElement.appendChild(document.createTextNode(name));
402 403 404 405 406 407 408 409 410 411
  nameElement.classList.add("tree-row-name");
  if (codeId !== -1) {
    nameElement.classList.add("codeid-link");
    nameElement.onclick = (event) => {
      main.setCurrentCode(codeId);
      // Prevent the click from bubbling to the row and causing it to
      // collapse/expand.
      event.stopPropagation();
    };
  }
412 413 414
  return nameElement;
}

415 416 417 418 419 420 421 422 423 424 425 426 427 428
function createViewSourceNode(codeId) {
  let linkElement = document.createElement("span");
  linkElement.appendChild(document.createTextNode("View source"));
  linkElement.classList.add("view-source-link");
  linkElement.onclick = (event) => {
    main.setCurrentCode(codeId);
    main.setViewingSource(true);
    // Prevent the click from bubbling to the row and causing it to
    // collapse/expand.
    event.stopPropagation();
  };
  return linkElement;
}

429 430 431
const COLLAPSED_ARROW = "\u25B6";
const EXPANDED_ARROW = "\u25BC";

432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
class CallTreeView {
  constructor() {
    this.element = $("calltree");
    this.treeElement = $("calltree-table");
    this.selectAttribution = $("calltree-attribution");
    this.selectCategories = $("calltree-categories");
    this.selectSort = $("calltree-sort");

    this.selectAttribution.onchange = () => {
      main.setCallTreeAttribution(this.selectAttribution.value);
    };

    this.selectCategories.onchange = () => {
      main.setCallTreeCategories(this.selectCategories.value);
    };

    this.selectSort.onchange = () => {
      main.setCallTreeSort(this.selectSort.value);
    };

    this.currentState = null;
  }

  sortFromId(id) {
    switch (id) {
      case "time":
458 459 460 461
        return (c1, c2) => {
          if (c1.ticks < c2.ticks) return 1;
          else if (c1.ticks > c2.ticks) return -1;
          return c2.ownTicks - c1.ownTicks;
462
        };
463
      case "own-time":
464 465 466 467
        return (c1, c2) => {
          if (c1.ownTicks < c2.ownTicks) return 1;
          else if (c1.ownTicks > c2.ownTicks) return -1;
          return c2.ticks - c1.ticks;
468
        };
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
      case "category-time":
        return (c1, c2) => {
          if (c1.type === c2.type) return c2.ticks - c1.ticks;
          if (c1.type < c2.type) return 1;
          return -1;
        };
      case "category-own-time":
        return (c1, c2) => {
          if (c1.type === c2.type) return c2.ownTicks - c1.ownTicks;
          if (c1.type < c2.type) return 1;
          return -1;
        };
    }
  }

  expandTree(tree, indent) {
    let index = 0;
    let id = "R/";
    let row = tree.row;

    if (row) {
      index = row.rowIndex;
      id = row.id;

493 494 495 496 497
      tree.arrow.textContent = EXPANDED_ARROW;
      // Collapse the children when the row is clicked again.
      let expandHandler = row.onclick;
      row.onclick = () => {
        this.collapseRow(tree, expandHandler);
498 499 500 501 502
      }
    }

    // Collect the children, and sort them by ticks.
    let children = [];
503
    let filter =
504
        filterFromFilterId(this.currentState.callTree.attribution);
505 506 507 508 509 510 511
    for (let childId in tree.children) {
      let child = tree.children[childId];
      if (child.ticks > 0) {
        children.push(child);
        if (child.delayedExpansion) {
          expandTreeNode(this.currentState.file, child, filter);
        }
512 513 514 515 516 517 518 519 520
      }
    }
    children.sort(this.sortFromId(this.currentState.callTree.sort));

    for (let i = 0; i < children.length; i++) {
      let node = children[i];
      let row = this.rows.insertRow(index);
      row.id = id + i + "/";

521 522 523
      if (node.type === "CAT") {
        row.style.backgroundColor = CATEGORY_COLOR;
      } else {
524 525 526 527 528 529 530 531 532 533 534 535
        row.style.backgroundColor = bucketFromKind(node.type).backgroundColor;
      }

      // Inclusive time % cell.
      let c = row.insertCell();
      c.textContent = (node.ticks * 100 / this.tickCount).toFixed(2) + "%";
      c.style.textAlign = "right";
      // Percent-of-parent cell.
      c = row.insertCell();
      c.textContent = (node.ticks * 100 / tree.ticks).toFixed(2) + "%";
      c.style.textAlign = "right";
      // Exclusive time % cell.
536
      if (this.currentState.mode !== "bottom-up") {
537 538 539 540 541 542 543
        c = row.insertCell(-1);
        c.textContent = (node.ownTicks * 100 / this.tickCount).toFixed(2) + "%";
        c.style.textAlign = "right";
      }

      // Create the name cell.
      let nameCell = row.insertCell();
544 545 546 547
      nameCell.appendChild(createIndentNode(indent + 1));
      let arrow = createArrowNode();
      nameCell.appendChild(arrow);
      nameCell.appendChild(createTypeNode(node.type));
548
      nameCell.appendChild(createFunctionNode(node.name, node.codeId));
549
      if (main.currentState.sourceData &&
550 551 552
          node.codeId >= 0 &&
          main.currentState.sourceData.hasSource(
              this.currentState.file.code[node.codeId].func)) {
553 554
        nameCell.appendChild(createViewSourceNode(node.codeId));
      }
555 556 557 558 559

      // Inclusive ticks cell.
      c = row.insertCell();
      c.textContent = node.ticks;
      c.style.textAlign = "right";
560
      if (this.currentState.mode !== "bottom-up") {
561 562 563 564 565 566
        // Exclusive ticks cell.
        c = row.insertCell(-1);
        c.textContent = node.ownTicks;
        c.style.textAlign = "right";
      }
      if (node.children.length > 0) {
567 568
        arrow.textContent = COLLAPSED_ARROW;
        row.onclick = () => { this.expandTree(node, indent + 1); };
569 570 571
      }

      node.row = row;
572
      node.arrow = arrow;
573 574 575 576 577

      index++;
    }
  }

578
  collapseRow(tree, expandHandler) {
579 580 581 582 583 584 585 586
    let row = tree.row;
    let id = row.id;
    let index = row.rowIndex;
    while (row.rowIndex < this.rows.rows.length &&
        this.rows.rows[index].id.startsWith(id)) {
      this.rows.deleteRow(index);
    }

587 588
    tree.arrow.textContent = COLLAPSED_ARROW;
    row.onclick = expandHandler;
589 590
  }

591
  fillSelects(mode, calltree) {
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
    function addOptions(e, values, current) {
      while (e.options.length > 0) {
        e.remove(0);
      }
      for (let i = 0; i < values.length; i++) {
        let option = document.createElement("option");
        option.value = values[i].value;
        option.textContent = values[i].text;
        e.appendChild(option);
      }
      e.value = current;
    }

    let attributions = [
        { value : "js-exclude-bc",
          text : "Attribute bytecode handlers to caller" },
        { value : "full-tree",
          text : "Count each code object separately" },
        { value : "js-funs",
          text : "Attribute non-functions to JS functions"  }
    ];

614
    switch (mode) {
615 616 617 618 619 620 621 622 623 624 625 626 627 628
      case "bottom-up":
        addOptions(this.selectAttribution, attributions, calltree.attribution);
        addOptions(this.selectCategories, [
            { value : "code-type", text : "Code type" },
            { value : "none", text : "None" }
        ], calltree.categories);
        addOptions(this.selectSort, [
            { value : "time", text : "Time (including children)" },
            { value : "category-time", text : "Code category, time" },
        ], calltree.sort);
        return;
      case "top-down":
        addOptions(this.selectAttribution, attributions, calltree.attribution);
        addOptions(this.selectCategories, [
629 630
            { value : "none", text : "None" },
            { value : "rt-entry", text : "Runtime entries" }
631 632 633 634 635 636 637 638 639 640 641
        ], calltree.categories);
        addOptions(this.selectSort, [
            { value : "time", text : "Time (including children)" },
            { value : "own-time", text : "Own time" },
            { value : "category-time", text : "Code category, time" },
            { value : "category-own-time", text : "Code category, own time"}
        ], calltree.sort);
        return;
      case "function-list":
        addOptions(this.selectAttribution, attributions, calltree.attribution);
        addOptions(this.selectCategories, [
642
            { value : "code-type", text : "Code type" },
643 644 645 646 647 648 649 650 651 652 653 654 655
            { value : "none", text : "None" }
        ], calltree.categories);
        addOptions(this.selectSort, [
            { value : "own-time", text : "Own time" },
            { value : "time", text : "Time (including children)" },
            { value : "category-own-time", text : "Code category, own time"},
            { value : "category-time", text : "Code category, time" },
        ], calltree.sort);
        return;
    }
    console.error("Unexpected mode");
  }

656 657 658 659 660 661 662 663 664 665 666
  static isCallTreeMode(mode) {
    switch (mode) {
      case "bottom-up":
      case "top-down":
      case "function-list":
        return true;
      default:
        return false;
    }
  }

667 668
  render(newState) {
    let oldState = this.currentState;
669
    if (!newState.file || !CallTreeView.isCallTreeMode(newState.mode)) {
670
      this.element.style.display = "none";
671
      this.currentState = null;
672 673 674 675 676 677 678 679
      return;
    }

    this.currentState = newState;
    if (oldState) {
      if (newState.file === oldState.file &&
          newState.start === oldState.start &&
          newState.end === oldState.end &&
680
          newState.mode === oldState.mode &&
681 682 683 684 685 686 687 688 689 690
          newState.callTree.attribution === oldState.callTree.attribution &&
          newState.callTree.categories === oldState.callTree.categories &&
          newState.callTree.sort === oldState.callTree.sort) {
        // No change => just return.
        return;
      }
    }

    this.element.style.display = "inherit";

691 692
    let mode = this.currentState.mode;
    if (!oldState || mode !== oldState.mode) {
693 694 695
      // Technically, we should also call this if attribution, categories or
      // sort change, but the selection is already highlighted by the combobox
      // itself, so we do need to do anything here.
696
      this.fillSelects(newState.mode, newState.callTree);
697 698
    }

699
    let ownTimeClass = (mode === "bottom-up") ? "numeric-hidden" : "numeric";
700
    let ownTimeTh = $(this.treeElement.id + "-own-time-header");
701
    ownTimeTh.classList = ownTimeClass;
702
    let ownTicksTh = $(this.treeElement.id + "-own-ticks-header");
703
    ownTicksTh.classList = ownTimeClass;
704 705 706

    // Build the tree.
    let stackProcessor;
707
    let filter = filterFromFilterId(this.currentState.callTree.attribution);
708
    if (mode === "top-down") {
709 710 711 712 713 714 715
      if (this.currentState.callTree.categories === "rt-entry") {
        stackProcessor =
            new RuntimeCallTreeProcessor();
      } else {
        stackProcessor =
            new PlainCallTreeProcessor(filter, false);
      }
716
    } else if (mode === "function-list") {
717 718
      stackProcessor = new FunctionListTree(
          filter, this.currentState.callTree.categories === "code-type");
719 720 721

    } else {
      console.assert(mode === "bottom-up");
722
      if (this.currentState.callTree.categories === "none") {
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
        stackProcessor =
            new PlainCallTreeProcessor(filter, true);
      } else {
        console.assert(this.currentState.callTree.categories === "code-type");
        stackProcessor =
            new CategorizedCallTreeProcessor(filter, true);
      }
    }
    this.tickCount =
        generateTree(this.currentState.file,
                     this.currentState.start,
                     this.currentState.end,
                     stackProcessor);
    // TODO(jarin) Handle the case when tick count is negative.

    this.tree = stackProcessor.tree;

    // Remove old content of the table, replace with new one.
    let oldRows = this.treeElement.getElementsByTagName("tbody");
    let newRows = document.createElement("tbody");
    this.rows = newRows;

    // Populate the table.
    this.expandTree(this.tree, 0);

    // Swap in the new rows.
    this.treeElement.replaceChild(newRows, oldRows[0]);
  }
}

class TimelineView {
  constructor() {
    this.element = $("timeline");
    this.canvas = $("timeline-canvas");
    this.legend = $("timeline-legend");
758
    this.currentCode = $("timeline-currentCode");
759 760 761 762 763 764 765 766 767

    this.canvas.onmousedown = this.onMouseDown.bind(this);
    this.canvas.onmouseup = this.onMouseUp.bind(this);
    this.canvas.onmousemove = this.onMouseMove.bind(this);

    this.selectionStart = null;
    this.selectionEnd = null;
    this.selecting = false;

768
    this.fontSize = 12;
769
    this.imageOffset = Math.round(this.fontSize * 1.2);
770 771
    this.functionTimelineHeight = 24;
    this.functionTimelineTickHeight = 16;
772

773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
    this.currentState = null;
  }

  onMouseDown(e) {
    this.selectionStart =
        e.clientX - this.canvas.getBoundingClientRect().left;
    this.selectionEnd = this.selectionStart + 1;
    this.selecting = true;
  }

  onMouseMove(e) {
    if (this.selecting) {
      this.selectionEnd =
          e.clientX - this.canvas.getBoundingClientRect().left;
      this.drawSelection();
    }
  }

  onMouseUp(e) {
    if (this.selectionStart !== null) {
      let x = e.clientX - this.canvas.getBoundingClientRect().left;
      if (Math.abs(x - this.selectionStart) < 10) {
        this.selectionStart = null;
        this.selectionEnd = null;
        let ctx = this.canvas.getContext("2d");
798
        ctx.drawImage(this.buffer, 0, this.imageOffset);
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
      } else {
        this.selectionEnd = x;
        this.drawSelection();
      }
      let file = this.currentState.file;
      if (file) {
        let start = this.selectionStart === null ? 0 : this.selectionStart;
        let end = this.selectionEnd === null ? Infinity : this.selectionEnd;
        let firstTime = file.ticks[0].tm;
        let lastTime = file.ticks[file.ticks.length - 1].tm;

        let width = this.buffer.width;

        start = (start / width) * (lastTime - firstTime) + firstTime;
        end = (end / width) * (lastTime - firstTime) + firstTime;

        if (end < start) {
          let temp = start;
          start = end;
          end = temp;
        }

        main.setViewInterval(start, end);
      }
    }
    this.selecting = false;
  }

  drawSelection() {
    let ctx = this.canvas.getContext("2d");

830 831 832 833 834 835
    // Draw the timeline image.
    ctx.drawImage(this.buffer, 0, this.imageOffset);

    // Draw the current interval highlight.
    let left;
    let right;
836 837
    if (this.selectionStart !== null && this.selectionEnd !== null) {
      ctx.fillStyle = "rgba(0, 0, 0, 0.3)";
838 839
      left = Math.min(this.selectionStart, this.selectionEnd);
      right = Math.max(this.selectionStart, this.selectionEnd);
840 841 842
      let height = this.buffer.height - this.functionTimelineHeight;
      ctx.fillRect(0, this.imageOffset, left, height);
      ctx.fillRect(right, this.imageOffset, this.buffer.width - right, height);
843 844 845
    } else {
      left = 0;
      right = this.buffer.width;
846 847
    }

848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
    // Draw the scale text.
    let file = this.currentState.file;
    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, this.canvas.width, this.imageOffset);
    if (file && file.ticks.length > 0) {
      let firstTime = file.ticks[0].tm;
      let lastTime = file.ticks[file.ticks.length - 1].tm;

      let leftTime =
          firstTime + left / this.canvas.width * (lastTime - firstTime);
      let rightTime =
          firstTime + right / this.canvas.width * (lastTime - firstTime);

      let leftText = (leftTime / 1000000).toFixed(3) + "s";
      let rightText = (rightTime / 1000000).toFixed(3) + "s";

      ctx.textBaseline = 'top';
      ctx.font = this.fontSize + "px Arial";
      ctx.fillStyle = "black";

      let leftWidth = ctx.measureText(leftText).width;
      let rightWidth = ctx.measureText(rightText).width;

      let leftStart = left - leftWidth / 2;
      let rightStart = right - rightWidth / 2;

      if (leftStart < 0) leftStart = 0;
      if (rightStart + rightWidth > this.canvas.width) {
        rightStart = this.canvas.width - rightWidth;
      }
      if (leftStart + leftWidth > rightStart) {
        if (leftStart > this.canvas.width - (rightStart - rightWidth)) {
          rightStart = leftStart + leftWidth;

        } else {
          leftStart = rightStart - leftWidth;
        }
      }

      ctx.fillText(leftText, leftStart, 0);
      ctx.fillText(rightText, rightStart, 0);
    }
  }
891 892 893 894 895 896 897 898 899

  render(newState) {
    let oldState = this.currentState;

    if (!newState.file) {
      this.element.style.display = "none";
      return;
    }

900 901
    let width = Math.round(document.documentElement.clientWidth - 20);
    let height = Math.round(document.documentElement.clientHeight / 5);
902

903
    if (oldState) {
904 905
      if (width === oldState.timelineSize.width &&
          height === oldState.timelineSize.height &&
906
          newState.file === oldState.file &&
907
          newState.currentCodeId === oldState.currentCodeId &&
908 909 910 911 912 913
          newState.start === oldState.start &&
          newState.end === oldState.end) {
        // No change, nothing to do.
        return;
      }
    }
914
    this.currentState = newState;
915 916
    this.currentState.timelineSize.width = width;
    this.currentState.timelineSize.height = height;
917 918 919

    this.element.style.display = "inherit";

920 921 922 923 924 925 926 927 928
    let file = this.currentState.file;

    const minPixelsPerBucket = 10;
    const minTicksPerBucket = 8;
    let maxBuckets = Math.round(file.ticks.length / minTicksPerBucket);
    let bucketCount = Math.min(
        Math.round(width / minPixelsPerBucket), maxBuckets);

    // Make sure the canvas has the right dimensions.
929
    this.canvas.width = width;
930 931 932 933
    this.canvas.height  = height;

    // Make space for the selection text.
    height -= this.imageOffset;
934

935 936
    let currentCodeId = this.currentState.currentCodeId;

937 938 939 940 941 942 943 944 945 946
    let firstTime = file.ticks[0].tm;
    let lastTime = file.ticks[file.ticks.length - 1].tm;
    let start = Math.max(this.currentState.start, firstTime);
    let end = Math.min(this.currentState.end, lastTime);

    this.selectionStart = (start - firstTime) / (lastTime - firstTime) * width;
    this.selectionEnd = (end - firstTime) / (lastTime - firstTime) * width;

    let stackProcessor = new CategorySampler(file, bucketCount);
    generateTree(file, 0, Infinity, stackProcessor);
947 948 949 950
    let codeIdProcessor = new FunctionTimelineProcessor(
      currentCodeId,
      filterFromFilterId(this.currentState.callTree.attribution));
    generateTree(file, 0, Infinity, codeIdProcessor);
951 952 953

    let buffer = document.createElement("canvas");

954 955
    buffer.width = width;
    buffer.height = height;
956 957

    // Calculate the bar heights for each bucket.
958
    let graphHeight = height - this.functionTimelineHeight;
959 960 961 962 963 964
    let buckets = stackProcessor.buckets;
    let bucketsGraph = [];
    for (let i = 0; i < buckets.length; i++) {
      let sum = 0;
      let bucketData = [];
      let total = buckets[i].total;
965 966 967 968 969 970 971 972 973 974 975 976 977
      if (total > 0) {
        for (let j = 0; j < bucketDescriptors.length; j++) {
          let desc = bucketDescriptors[j];
          for (let k = 0; k < desc.kinds.length; k++) {
            sum += buckets[i][desc.kinds[k]];
          }
          bucketData.push(Math.round(graphHeight * sum / total));
        }
      } else {
        // No ticks fell into this bucket. Fill with "Unknown."
        for (let j = 0; j < bucketDescriptors.length; j++) {
          let desc = bucketDescriptors[j];
          bucketData.push(desc.text === "Unknown" ? graphHeight : 0);
978 979 980 981 982
        }
      }
      bucketsGraph.push(bucketData);
    }

983
    // Draw the category graph into the buffer.
984
    let bucketWidth = width / (bucketsGraph.length - 1);
985 986 987 988
    let ctx = buffer.getContext('2d');
    for (let i = 0; i < bucketsGraph.length - 1; i++) {
      let bucketData = bucketsGraph[i];
      let nextBucketData = bucketsGraph[i + 1];
989 990
      let x1 = Math.round(i * bucketWidth);
      let x2 = Math.round((i + 1) * bucketWidth);
991 992
      for (let j = 0; j < bucketData.length; j++) {
        ctx.beginPath();
993 994
        ctx.moveTo(x1, j > 0 ? bucketData[j - 1] : 0);
        ctx.lineTo(x2, j > 0 ? nextBucketData[j - 1] : 0);
995 996
        ctx.lineTo(x2, nextBucketData[j]);
        ctx.lineTo(x1, bucketData[j]);
997 998 999 1000 1001
        ctx.closePath();
        ctx.fillStyle = bucketDescriptors[j].color;
        ctx.fill();
      }
    }
1002 1003

    // Draw the function ticks.
1004
    let functionTimelineYOffset = graphHeight;
1005 1006 1007
    let functionTimelineTickHeight = this.functionTimelineTickHeight;
    let functionTimelineHalfHeight =
        Math.round(functionTimelineTickHeight / 2);
1008
    let timestampScaler = width / (lastTime - firstTime);
1009
    let timestampToX = (t) => Math.round((t - firstTime) * timestampScaler);
1010 1011 1012 1013 1014
    ctx.fillStyle = "white";
    ctx.fillRect(
      0,
      functionTimelineYOffset,
      buffer.width,
1015
      this.functionTimelineHeight);
1016 1017
    for (let i = 0; i < codeIdProcessor.blocks.length; i++) {
      let block = codeIdProcessor.blocks[i];
1018 1019
      let bucket = kindToBucketDescriptor[block.kind];
      ctx.fillStyle = bucket.color;
1020
      ctx.fillRect(
1021
        timestampToX(block.start),
1022 1023
        functionTimelineYOffset,
        Math.max(1, Math.round((block.end - block.start) * timestampScaler)),
1024 1025
        block.topOfStack ?
            functionTimelineTickHeight : functionTimelineHalfHeight);
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
    }
    ctx.strokeStyle = "black";
    ctx.lineWidth = "1";
    ctx.beginPath();
    ctx.moveTo(0, functionTimelineYOffset + 0.5);
    ctx.lineTo(buffer.width, functionTimelineYOffset + 0.5);
    ctx.stroke();
    ctx.strokeStyle = "rgba(0,0,0,0.2)";
    ctx.lineWidth = "1";
    ctx.beginPath();
    ctx.moveTo(0, functionTimelineYOffset + functionTimelineHalfHeight - 0.5);
    ctx.lineTo(buffer.width,
        functionTimelineYOffset + functionTimelineHalfHeight - 0.5);
    ctx.stroke();
1040

1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
    // Draw marks for optimizations and deoptimizations in the function
    // timeline.
    if (currentCodeId && currentCodeId >= 0 &&
        file.code[currentCodeId].func) {
      let y = Math.round(functionTimelineYOffset + functionTimelineTickHeight +
          (this.functionTimelineHeight - functionTimelineTickHeight) / 2);
      let func = file.functions[file.code[currentCodeId].func];
      for (let i = 0; i < func.codes.length; i++) {
        let code = file.code[func.codes[i]];
        if (code.kind === "Opt") {
          if (code.deopt) {
            // Draw deoptimization mark.
            let x = timestampToX(code.deopt.tm);
            ctx.lineWidth = 0.7;
            ctx.strokeStyle = "red";
            ctx.beginPath();
            ctx.moveTo(x - 3, y - 3);
            ctx.lineTo(x + 3, y + 3);
            ctx.stroke();
            ctx.beginPath();
            ctx.moveTo(x - 3, y + 3);
            ctx.lineTo(x + 3, y - 3);
            ctx.stroke();
          }
          // Draw optimization mark.
          let x = timestampToX(code.tm);
          ctx.lineWidth = 0.7;
          ctx.strokeStyle = "blue";
          ctx.beginPath();
          ctx.moveTo(x - 3, y - 3);
          ctx.lineTo(x, y);
          ctx.stroke();
          ctx.beginPath();
          ctx.moveTo(x - 3, y + 3);
          ctx.lineTo(x, y);
          ctx.stroke();
        } else {
          // Draw code creation mark.
          let x = Math.round(timestampToX(code.tm));
          ctx.beginPath();
          ctx.fillStyle = "black";
          ctx.arc(x, y, 3, 0, 2 * Math.PI);
          ctx.fill();
        }
      }
    }

1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
    // Remember stuff for later.
    this.buffer = buffer;

    // Draw the buffer.
    this.drawSelection();

    // (Re-)Populate the graph legend.
    while (this.legend.cells.length > 0) {
      this.legend.deleteCell(0);
    }
    let cell = this.legend.insertCell(-1);
    cell.textContent = "Legend: ";
    cell.style.padding = "1ex";
    for (let i = 0; i < bucketDescriptors.length; i++) {
      let cell = this.legend.insertCell(-1);
      cell.style.padding = "1ex";
      let desc = bucketDescriptors[i];
      let div = document.createElement("div");
      div.style.display = "inline-block";
      div.style.width = "0.6em";
      div.style.height = "1.2ex";
      div.style.backgroundColor = desc.color;
      div.style.borderStyle = "solid";
      div.style.borderWidth = "1px";
      div.style.borderColor = "Black";
      cell.appendChild(div);
      cell.appendChild(document.createTextNode(" " + desc.text));
    }
1116

1117
    removeAllChildren(this.currentCode);
1118 1119 1120 1121 1122 1123
    if (currentCodeId) {
      let currentCode = file.code[currentCodeId];
      this.currentCode.appendChild(document.createTextNode(currentCode.name));
    } else {
      this.currentCode.appendChild(document.createTextNode("<none>"));
    }
1124 1125 1126
  }
}

1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
class ModeBarView {
  constructor() {
    let modeBar = this.element = $("mode-bar");

    function addMode(id, text, active) {
      let div = document.createElement("div");
      div.classList = "mode-button" + (active ? " active-mode-button" : "");
      div.id = "mode-" + id;
      div.textContent = text;
      div.onclick = () => {
        if (main.currentState.mode === id) return;
        let old = $("mode-" + main.currentState.mode);
        old.classList = "mode-button";
        div.classList = "mode-button active-mode-button";
        main.setMode(id);
      };
      modeBar.appendChild(div);
    }

    addMode("summary", "Summary", true);
    addMode("bottom-up", "Bottom up");
    addMode("top-down", "Top down");
    addMode("function-list", "Functions");
  }

  render(newState) {
    if (!newState.file) {
      this.element.style.display = "none";
      return;
    }

    this.element.style.display = "inherit";
  }
}

class SummaryView {
  constructor() {
    this.element = $("summary");
    this.currentState = null;
  }

  render(newState) {
    let oldState = this.currentState;

    if (!newState.file || newState.mode !== "summary") {
      this.element.style.display = "none";
      this.currentState = null;
      return;
    }

    this.currentState = newState;
    if (oldState) {
      if (newState.file === oldState.file &&
          newState.start === oldState.start &&
          newState.end === oldState.end) {
        // No change, nothing to do.
        return;
      }
    }

    this.element.style.display = "inherit";
1188
    removeAllChildren(this.element);
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208

    let stats = computeOptimizationStats(
        this.currentState.file, newState.start, newState.end);

    let table = document.createElement("table");
    let rows = document.createElement("tbody");

    function addRow(text, number, indent) {
      let row = rows.insertRow(-1);
      let textCell = row.insertCell(-1);
      textCell.textContent = text;
      let numberCell = row.insertCell(-1);
      numberCell.textContent = number;
      if (indent) {
        textCell.style.textIndent = indent + "em";
        numberCell.style.textIndent = indent + "em";
      }
      return row;
    }

1209 1210 1211 1212
    function makeCollapsible(row, arrow) {
      arrow.textContent = EXPANDED_ARROW;
      let expandHandler = row.onclick;
      row.onclick = () => {
1213 1214 1215 1216 1217 1218
        let id = row.id;
        let index = row.rowIndex + 1;
        while (index < rows.rows.length &&
          rows.rows[index].id.startsWith(id)) {
          rows.deleteRow(index);
        }
1219 1220
        arrow.textContent = COLLAPSED_ARROW;
        row.onclick = expandHandler;
1221 1222 1223
      }
    }

1224
    function expandDeoptInstances(row, arrow, instances, indent, kind) {
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
      let index = row.rowIndex;
      for (let i = 0; i < instances.length; i++) {
        let childRow = rows.insertRow(index + 1);
        childRow.id = row.id + i + "/";

        let deopt = instances[i].deopt;

        let textCell = childRow.insertCell(-1);
        textCell.appendChild(document.createTextNode(deopt.posText));
        textCell.style.textIndent = indent + "em";
        let reasonCell = childRow.insertCell(-1);
        reasonCell.appendChild(
            document.createTextNode("Reason: " + deopt.reason));
        reasonCell.style.textIndent = indent + "em";
      }
1240
      makeCollapsible(row, arrow);
1241 1242
    }

1243
    function expandDeoptFunctionList(row, arrow, list, indent, kind) {
1244 1245 1246 1247 1248 1249
      let index = row.rowIndex;
      for (let i = 0; i < list.length; i++) {
        let childRow = rows.insertRow(index + 1);
        childRow.id = row.id + i + "/";

        let textCell = childRow.insertCell(-1);
1250 1251 1252
        textCell.appendChild(createIndentNode(indent));
        let childArrow = createArrowNode();
        textCell.appendChild(childArrow);
1253 1254 1255 1256 1257 1258 1259
        textCell.appendChild(
            createFunctionNode(list[i].f.name, list[i].f.codes[0]));

        let numberCell = childRow.insertCell(-1);
        numberCell.textContent = list[i].instances.length;
        numberCell.style.textIndent = indent + "em";

1260 1261
        childArrow.textContent = COLLAPSED_ARROW;
        childRow.onclick = () => {
1262
          expandDeoptInstances(
1263
              childRow, childArrow, list[i].instances, indent + 1);
1264 1265
        };
      }
1266
      makeCollapsible(row, arrow);
1267 1268
    }

1269
    function expandOptimizedFunctionList(row, arrow, list, indent, kind) {
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
      let index = row.rowIndex;
      for (let i = 0; i < list.length; i++) {
        let childRow = rows.insertRow(index + 1);
        childRow.id = row.id + i + "/";

        let textCell = childRow.insertCell(-1);
        textCell.appendChild(
            createFunctionNode(list[i].f.name, list[i].f.codes[0]));
        textCell.style.textIndent = indent + "em";

        let numberCell = childRow.insertCell(-1);
        numberCell.textContent = list[i].instances.length;
        numberCell.style.textIndent = indent + "em";
      }
1284
      makeCollapsible(row, arrow);
1285 1286 1287 1288 1289 1290
    }

    function addExpandableRow(text, list, indent, kind) {
      let row = rows.insertRow(-1);

      row.id = "opt-table/" + kind + "/";
1291
      row.style.backgroundColor = CATEGORY_COLOR;
1292 1293

      let textCell = row.insertCell(-1);
1294 1295 1296
      textCell.appendChild(createIndentNode(indent));
      let arrow = createArrowNode();
      textCell.appendChild(arrow);
1297 1298 1299 1300 1301 1302 1303 1304 1305
      textCell.appendChild(document.createTextNode(text));

      let numberCell = row.insertCell(-1);
      numberCell.textContent = list.count;
      if (indent) {
        numberCell.style.textIndent = indent + "em";
      }

      if (list.count > 0) {
1306
        arrow.textContent = COLLAPSED_ARROW;
1307
        if (kind === "opt") {
1308
          row.onclick = () => {
1309
            expandOptimizedFunctionList(
1310
                row, arrow, list.functions, indent + 1, kind);
1311 1312
          };
        } else {
1313
          row.onclick = () => {
1314
            expandDeoptFunctionList(
1315
                row, arrow, list.functions, indent + 1, kind);
1316 1317 1318 1319 1320 1321 1322 1323
          };
        }
      }
      return row;
    }

    addRow("Total function count:", stats.functionCount);
    addRow("Optimized function count:", stats.optimizedFunctionCount, 1);
1324 1325 1326
    if (stats.turbopropOptimizedFunctionCount != 0) {
      addRow("Turboprop optimized function count:", stats.turbopropOptimizedFunctionCount, 1);
    }
1327 1328 1329
    addRow("Deoptimized function count:", stats.deoptimizedFunctionCount, 2);

    addExpandableRow("Optimization count:", stats.optimizations, 0, "opt");
1330 1331 1332
    if (stats.turbopropOptimizedFunctionCount != 0) {
      addExpandableRow("Turboprop Optimization count:", stats.turbopropOptimizations, 0, "tp");
    }
1333 1334 1335 1336 1337 1338
    let deoptCount = stats.eagerDeoptimizations.count +
        stats.softDeoptimizations.count + stats.lazyDeoptimizations.count;
    addRow("Deoptimization count:", deoptCount);
    addExpandableRow("Eager:", stats.eagerDeoptimizations, 1, "eager");
    addExpandableRow("Lazy:", stats.lazyDeoptimizations, 1, "lazy");
    addExpandableRow("Soft:", stats.softDeoptimizations, 1, "soft");
1339 1340 1341 1342 1343 1344
    if (stats.softBailouts.count != 0) {
      addExpandableRow("SoftBailout:", stats.softBailouts, 1, "softbailout");
    }
    if (stats.eagerBailouts.count != 0) {
      addExpandableRow("EagerBailout:", stats.eagerBailouts, 1, "eagerbailout");
    }
1345 1346 1347 1348 1349 1350

    table.appendChild(rows);
    this.element.appendChild(table);
  }
}

1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
class ScriptSourceView {
  constructor() {
    this.table = $("source-viewer");
    this.hideButton = $("source-viewer-hide-button");
    this.hideButton.onclick = () => {
      main.setViewingSource(false);
    };
  }

  render(newState) {
    let oldState = this.currentState;
    if (!newState.file || !newState.viewingSource) {
      this.table.style.display = "none";
      this.hideButton.style.display = "none";
      this.currentState = null;
      return;
    }
    if (oldState) {
      if (newState.file === oldState.file &&
          newState.currentCodeId === oldState.currentCodeId &&
          newState.viewingSource === oldState.viewingSource) {
        // No change, nothing to do.
        return;
      }
    }
    this.currentState = newState;

    this.table.style.display = "inline-block";
    this.hideButton.style.display = "inline";
    removeAllChildren(this.table);

1382 1383
    let functionId =
        this.currentState.file.code[this.currentState.currentCodeId].func;
1384
    let sourceView =
1385
        this.currentState.sourceData.generateSourceView(functionId);
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
    for (let i = 0; i < sourceView.source.length; i++) {
      let sampleCount = sourceView.lineSampleCounts[i] || 0;
      let sampleProportion = sourceView.samplesTotal > 0 ?
                             sampleCount / sourceView.samplesTotal : 0;
      let heatBucket;
      if (sampleProportion === 0) {
        heatBucket = "line-none";
      } else if (sampleProportion < 0.2) {
        heatBucket = "line-cold";
      } else if (sampleProportion < 0.4) {
        heatBucket = "line-mediumcold";
      } else if (sampleProportion < 0.6) {
        heatBucket = "line-mediumhot";
      } else if (sampleProportion < 0.8) {
        heatBucket = "line-hot";
      } else {
        heatBucket = "line-superhot";
      }

      let row = this.table.insertRow(-1);

      let lineNumberCell = row.insertCell(-1);
      lineNumberCell.classList.add("source-line-number");
      lineNumberCell.textContent = i + sourceView.firstLineNumber;

      let sampleCountCell = row.insertCell(-1);
      sampleCountCell.classList.add(heatBucket);
      sampleCountCell.textContent = sampleCount;

      let sourceLineCell = row.insertCell(-1);
      sourceLineCell.classList.add(heatBucket);
      sourceLineCell.textContent = sourceView.source[i];
    }

    $("timeline-currentCode").scrollIntoView();
  }
}

class SourceData {
  constructor(file) {
    this.scripts = new Map();
1427 1428
    for (let i = 0; i < file.scripts.length; i++) {
      const scriptBlock = file.scripts[i];
1429
      if (scriptBlock === null) continue; // Array may be sparse.
1430
      if (scriptBlock.source === undefined) continue;
1431
      let source = scriptBlock.source.split("\n");
1432
      this.scripts.set(i, source);
1433 1434 1435 1436 1437
    }

    this.functions = new Map();
    for (let codeId = 0; codeId < file.code.length; ++codeId) {
      let codeBlock = file.code[codeId];
1438
      if (codeBlock.source && codeBlock.func !== undefined) {
1439
        let data = this.functions.get(codeBlock.func);
1440
        if (!data) {
1441 1442
          data = new FunctionSourceData(codeBlock.source.script,
                                        codeBlock.source.start,
1443
                                        codeBlock.source.end);
1444
          this.functions.set(codeBlock.func, data);
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
        }
        data.addSourceBlock(codeId, codeBlock.source);
      }
    }

    for (let tick of file.ticks) {
      let stack = tick.s;
      for (let i = 0; i < stack.length; i += 2) {
        let codeId = stack[i];
        if (codeId < 0) continue;
1455
        let functionId = file.code[codeId].func;
1456
        if (this.functions.has(functionId)) {
1457
          let codeOffset = stack[i + 1];
1458
          this.functions.get(functionId).addOffsetSample(codeId, codeOffset);
1459 1460 1461 1462 1463
        }
      }
    }
  }

1464 1465
  getScript(scriptId) {
    return this.scripts.get(scriptId);
1466 1467
  }

1468
  getLineForScriptOffset(script, scriptOffset) {
1469 1470 1471 1472 1473 1474 1475 1476 1477
    let line = 0;
    let charsConsumed = 0;
    for (; line < script.length; ++line) {
      charsConsumed += script[line].length + 1; // Add 1 for newline.
      if (charsConsumed > scriptOffset) break;
    }
    return line;
  }

1478 1479
  hasSource(functionId) {
    return this.functions.has(functionId);
1480 1481
  }

1482 1483 1484 1485 1486
  generateSourceView(functionId) {
    console.assert(this.hasSource(functionId));
    let data = this.functions.get(functionId);
    let scriptId = data.scriptId;
    let script = this.getScript(scriptId);
1487
    let firstLineNumber =
1488
        this.getLineForScriptOffset(script, data.startScriptOffset);
1489
    let lastLineNumber =
1490
        this.getLineForScriptOffset(script, data.endScriptOffset);
1491 1492 1493 1494 1495 1496 1497 1498 1499
    let lines = script.slice(firstLineNumber, lastLineNumber + 1);
    normalizeLeadingWhitespace(lines);

    let samplesTotal = 0;
    let lineSampleCounts = [];
    for (let [codeId, block] of data.codes) {
      block.offsets.forEach((sampleCount, codeOffset) => {
        let sourceOffset = block.positionTable.getScriptOffset(codeOffset);
        let lineNumber =
1500
            this.getLineForScriptOffset(script, sourceOffset) - firstLineNumber;
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
        samplesTotal += sampleCount;
        lineSampleCounts[lineNumber] =
            (lineSampleCounts[lineNumber] || 0) + sampleCount;
      });
    }

    return {
      source: lines,
      lineSampleCounts: lineSampleCounts,
      samplesTotal: samplesTotal,
      firstLineNumber: firstLineNumber + 1  // Source code is 1-indexed.
    };
  }
}

class FunctionSourceData {
1517 1518
  constructor(scriptId, startScriptOffset, endScriptOffset) {
    this.scriptId = scriptId;
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
    this.startScriptOffset = startScriptOffset;
    this.endScriptOffset = endScriptOffset;

    this.codes = new Map();
  }

  addSourceBlock(codeId, source) {
    this.codes.set(codeId, {
      positionTable: new SourcePositionTable(source.positions),
      offsets: []
    });
  }

  addOffsetSample(codeId, codeOffset) {
    let codeIdOffsets = this.codes.get(codeId).offsets;
    codeIdOffsets[codeOffset] = (codeIdOffsets[codeOffset] || 0) + 1;
  }
}

class SourcePositionTable {
  constructor(encodedTable) {
    this.offsetTable = [];
    let offsetPairRegex = /C([0-9]+)O([0-9]+)/g;
    while (true) {
      let regexResult = offsetPairRegex.exec(encodedTable);
      if (!regexResult) break;
      let codeOffset = parseInt(regexResult[1]);
      let scriptOffset = parseInt(regexResult[2]);
      if (isNaN(codeOffset) || isNaN(scriptOffset)) continue;
      this.offsetTable.push(codeOffset, scriptOffset);
    }
  }

  getScriptOffset(codeOffset) {
    console.assert(codeOffset >= 0);
    for (let i = this.offsetTable.length - 2; i >= 0; i -= 2) {
      if (this.offsetTable[i] <= codeOffset) {
        return this.offsetTable[i + 1];
      }
    }
    return this.offsetTable[1];
  }
}

1563 1564 1565 1566 1567 1568 1569 1570 1571
class HelpView {
  constructor() {
    this.element = $("help");
  }

  render(newState) {
    this.element.style.display = newState.file ? "none" : "inherit";
  }
}