22570f5e53cba774ea5273955017ca67e8d1c7fc
   1// Copyright (C) 2007, Fredrik Kuivinen <frekui@gmail.com>
   2//               2007, Petr Baudis <pasky@suse.cz>
   3//          2008-2009, Jakub Narebski <jnareb@gmail.com>
   4
   5/**
   6 * @fileOverview JavaScript code for gitweb (git web interface).
   7 * @license GPLv2 or later
   8 */
   9
  10/*
  11 * This code uses DOM methods instead of (nonstandard) innerHTML
  12 * to modify page.
  13 *
  14 * innerHTML is non-standard IE extension, though supported by most
  15 * browsers; however Firefox up to version 1.5 didn't implement it in
  16 * a strict mode (application/xml+xhtml mimetype).
  17 *
  18 * Also my simple benchmarks show that using elem.firstChild.data =
  19 * 'content' is slightly faster than elem.innerHTML = 'content'.  It
  20 * is however more fragile (text element fragment must exists), and
  21 * less feature-rich (we cannot add HTML).
  22 *
  23 * Note that DOM 2 HTML is preferred over generic DOM 2 Core; the
  24 * equivalent using DOM 2 Core is usually shown in comments.
  25 */
  26
  27
  28/* ============================================================ */
  29/* generic utility functions */
  30
  31
  32/**
  33 * pad number N with nonbreakable spaces on the left, to WIDTH characters
  34 * example: padLeftStr(12, 3, '&nbsp;') == '&nbsp;12'
  35 *          ('&nbsp;' is nonbreakable space)
  36 *
  37 * @param {Number|String} input: number to pad
  38 * @param {Number} width: visible width of output
  39 * @param {String} str: string to prefix to string, e.g. '&nbsp;'
  40 * @returns {String} INPUT prefixed with (WIDTH - INPUT.length) x STR
  41 */
  42function padLeftStr(input, width, str) {
  43        var prefix = '';
  44
  45        width -= input.toString().length;
  46        while (width > 1) {
  47                prefix += str;
  48                width--;
  49        }
  50        return prefix + input;
  51}
  52
  53/**
  54 * Pad INPUT on the left to SIZE width, using given padding character CH,
  55 * for example padLeft('a', 3, '_') is '__a'.
  56 *
  57 * @param {String} input: input value converted to string.
  58 * @param {Number} width: desired length of output.
  59 * @param {String} ch: single character to prefix to string.
  60 *
  61 * @returns {String} Modified string, at least SIZE length.
  62 */
  63function padLeft(input, width, ch) {
  64        var s = input + "";
  65        while (s.length < width) {
  66                s = ch + s;
  67        }
  68        return s;
  69}
  70
  71/**
  72 * Create XMLHttpRequest object in cross-browser way
  73 * @returns XMLHttpRequest object, or null
  74 */
  75function createRequestObject() {
  76        try {
  77                return new XMLHttpRequest();
  78        } catch (e) {}
  79        try {
  80                return window.createRequest();
  81        } catch (e) {}
  82        try {
  83                return new ActiveXObject("Msxml2.XMLHTTP");
  84        } catch (e) {}
  85        try {
  86                return new ActiveXObject("Microsoft.XMLHTTP");
  87        } catch (e) {}
  88
  89        return null;
  90}
  91
  92/* ============================================================ */
  93/* utility/helper functions (and variables) */
  94
  95var xhr;        // XMLHttpRequest object
  96var projectUrl; // partial query + separator ('?' or ';')
  97
  98// 'commits' is an associative map. It maps SHA1s to Commit objects.
  99var commits = {};
 100
 101/**
 102 * constructor for Commit objects, used in 'blame'
 103 * @class Represents a blamed commit
 104 * @param {String} sha1: SHA-1 identifier of a commit
 105 */
 106function Commit(sha1) {
 107        if (this instanceof Commit) {
 108                this.sha1 = sha1;
 109                this.nprevious = 0; /* number of 'previous', effective parents */
 110        } else {
 111                return new Commit(sha1);
 112        }
 113}
 114
 115/* ............................................................ */
 116/* progress info, timing, error reporting */
 117
 118var blamedLines = 0;
 119var totalLines  = '???';
 120var div_progress_bar;
 121var div_progress_info;
 122
 123/**
 124 * Detects how many lines does a blamed file have,
 125 * This information is used in progress info
 126 *
 127 * @returns {Number|String} Number of lines in file, or string '...'
 128 */
 129function countLines() {
 130        var table =
 131                document.getElementById('blame_table') ||
 132                document.getElementsByTagName('table')[0];
 133
 134        if (table) {
 135                return table.getElementsByTagName('tr').length - 1; // for header
 136        } else {
 137                return '...';
 138        }
 139}
 140
 141/**
 142 * update progress info and length (width) of progress bar
 143 *
 144 * @globals div_progress_info, div_progress_bar, blamedLines, totalLines
 145 */
 146function updateProgressInfo() {
 147        if (!div_progress_info) {
 148                div_progress_info = document.getElementById('progress_info');
 149        }
 150        if (!div_progress_bar) {
 151                div_progress_bar = document.getElementById('progress_bar');
 152        }
 153        if (!div_progress_info && !div_progress_bar) {
 154                return;
 155        }
 156
 157        var percentage = Math.floor(100.0*blamedLines/totalLines);
 158
 159        if (div_progress_info) {
 160                div_progress_info.firstChild.data  = blamedLines + ' / ' + totalLines +
 161                        ' (' + padLeftStr(percentage, 3, '&nbsp;') + '%)';
 162        }
 163
 164        if (div_progress_bar) {
 165                //div_progress_bar.setAttribute('style', 'width: '+percentage+'%;');
 166                div_progress_bar.style.width = percentage + '%';
 167        }
 168}
 169
 170
 171var t_interval_server = '';
 172var cmds_server = '';
 173var t0 = new Date();
 174
 175/**
 176 * write how much it took to generate data, and to run script
 177 *
 178 * @globals t0, t_interval_server, cmds_server
 179 */
 180function writeTimeInterval() {
 181        var info_time = document.getElementById('generating_time');
 182        if (!info_time || !t_interval_server) {
 183                return;
 184        }
 185        var t1 = new Date();
 186        info_time.firstChild.data += ' + (' +
 187                t_interval_server + ' sec server blame_data / ' +
 188                (t1.getTime() - t0.getTime())/1000 + ' sec client JavaScript)';
 189
 190        var info_cmds = document.getElementById('generating_cmd');
 191        if (!info_time || !cmds_server) {
 192                return;
 193        }
 194        info_cmds.firstChild.data += ' + ' + cmds_server;
 195}
 196
 197/**
 198 * show an error message alert to user within page (in prohress info area)
 199 * @param {String} str: plain text error message (no HTML)
 200 *
 201 * @globals div_progress_info
 202 */
 203function errorInfo(str) {
 204        if (!div_progress_info) {
 205                div_progress_info = document.getElementById('progress_info');
 206        }
 207        if (div_progress_info) {
 208                div_progress_info.className = 'error';
 209                div_progress_info.firstChild.data = str;
 210        }
 211}
 212
 213/* ............................................................ */
 214/* coloring rows during blame_data (git blame --incremental) run */
 215
 216/**
 217 * used to extract N from 'colorN', where N is a number,
 218 * @constant
 219 */
 220var colorRe = /\bcolor([0-9]*)\b/;
 221
 222/**
 223 * return N if <tr class="colorN">, otherwise return null
 224 * (some browsers require CSS class names to begin with letter)
 225 *
 226 * @param {HTMLElement} tr: table row element to check
 227 * @param {String} tr.className: 'class' attribute of tr element
 228 * @returns {Number|null} N if tr.className == 'colorN', otherwise null
 229 *
 230 * @globals colorRe
 231 */
 232function getColorNo(tr) {
 233        if (!tr) {
 234                return null;
 235        }
 236        var className = tr.className;
 237        if (className) {
 238                var match = colorRe.exec(className);
 239                if (match) {
 240                        return parseInt(match[1], 10);
 241                }
 242        }
 243        return null;
 244}
 245
 246var colorsFreq = [0, 0, 0];
 247/**
 248 * return one of given possible colors (curently least used one)
 249 * example: chooseColorNoFrom(2, 3) returns 2 or 3
 250 *
 251 * @param {Number[]} arguments: one or more numbers
 252 *        assumes that  1 <= arguments[i] <= colorsFreq.length
 253 * @returns {Number} Least used color number from arguments
 254 * @globals colorsFreq
 255 */
 256function chooseColorNoFrom() {
 257        // choose the color which is least used
 258        var colorNo = arguments[0];
 259        for (var i = 1; i < arguments.length; i++) {
 260                if (colorsFreq[arguments[i]-1] < colorsFreq[colorNo-1]) {
 261                        colorNo = arguments[i];
 262                }
 263        }
 264        colorsFreq[colorNo-1]++;
 265        return colorNo;
 266}
 267
 268/**
 269 * given two neigbour <tr> elements, find color which would be different
 270 * from color of both of neighbours; used to 3-color blame table
 271 *
 272 * @param {HTMLElement} tr_prev
 273 * @param {HTMLElement} tr_next
 274 * @returns {Number} color number N such that
 275 * colorN != tr_prev.className && colorN != tr_next.className
 276 */
 277function findColorNo(tr_prev, tr_next) {
 278        var color_prev = getColorNo(tr_prev);
 279        var color_next = getColorNo(tr_next);
 280
 281
 282        // neither of neighbours has color set
 283        // THEN we can use any of 3 possible colors
 284        if (!color_prev && !color_next) {
 285                return chooseColorNoFrom(1,2,3);
 286        }
 287
 288        // either both neighbours have the same color,
 289        // or only one of neighbours have color set
 290        // THEN we can use any color except given
 291        var color;
 292        if (color_prev === color_next) {
 293                color = color_prev; // = color_next;
 294        } else if (!color_prev) {
 295                color = color_next;
 296        } else if (!color_next) {
 297                color = color_prev;
 298        }
 299        if (color) {
 300                return chooseColorNoFrom((color % 3) + 1, ((color+1) % 3) + 1);
 301        }
 302
 303        // neighbours have different colors
 304        // THEN there is only one color left
 305        return (3 - ((color_prev + color_next) % 3));
 306}
 307
 308/* ............................................................ */
 309/* coloring rows like 'blame' after 'blame_data' finishes */
 310
 311/**
 312 * returns true if given row element (tr) is first in commit group
 313 * to be used only after 'blame_data' finishes (after processing)
 314 *
 315 * @param {HTMLElement} tr: table row
 316 * @returns {Boolean} true if TR is first in commit group
 317 */
 318function isStartOfGroup(tr) {
 319        return tr.firstChild.className === 'sha1';
 320}
 321
 322/**
 323 * change colors to use zebra coloring (2 colors) instead of 3 colors
 324 * concatenate neighbour commit groups belonging to the same commit
 325 *
 326 * @globals colorRe
 327 */
 328function fixColorsAndGroups() {
 329        var colorClasses = ['light', 'dark'];
 330        var linenum = 1;
 331        var tr, prev_group;
 332        var colorClass = 0;
 333        var table =
 334                document.getElementById('blame_table') ||
 335                document.getElementsByTagName('table')[0];
 336
 337        while ((tr = document.getElementById('l'+linenum))) {
 338        // index origin is 0, which is table header; start from 1
 339        //while ((tr = table.rows[linenum])) { // <- it is slower
 340                if (isStartOfGroup(tr, linenum, document)) {
 341                        if (prev_group &&
 342                            prev_group.firstChild.firstChild.href ===
 343                                    tr.firstChild.firstChild.href) {
 344                                // we have to concatenate groups
 345                                var prev_rows = prev_group.firstChild.rowSpan || 1;
 346                                var curr_rows =         tr.firstChild.rowSpan || 1;
 347                                prev_group.firstChild.rowSpan = prev_rows + curr_rows;
 348                                //tr.removeChild(tr.firstChild);
 349                                tr.deleteCell(0); // DOM2 HTML way
 350                        } else {
 351                                colorClass = (colorClass + 1) % 2;
 352                                prev_group = tr;
 353                        }
 354                }
 355                var tr_class = tr.className;
 356                tr.className = tr_class.replace(colorRe, colorClasses[colorClass]);
 357                linenum++;
 358        }
 359}
 360
 361/* ............................................................ */
 362/* time and data */
 363
 364/**
 365 * used to extract hours and minutes from timezone info, e.g '-0900'
 366 * @constant
 367 */
 368var tzRe = /^([+-][0-9][0-9])([0-9][0-9])$/;
 369
 370/**
 371 * return date in local time formatted in iso-8601 like format
 372 * 'yyyy-mm-dd HH:MM:SS +/-ZZZZ' e.g. '2005-08-07 21:49:46 +0200'
 373 *
 374 * @param {Number} epoch: seconds since '00:00:00 1970-01-01 UTC'
 375 * @param {String} timezoneInfo: numeric timezone '(+|-)HHMM'
 376 * @returns {String} date in local time in iso-8601 like format
 377 *
 378 * @globals tzRe
 379 */
 380function formatDateISOLocal(epoch, timezoneInfo) {
 381        var match = tzRe.exec(timezoneInfo);
 382        // date corrected by timezone
 383        var localDate = new Date(1000 * (epoch +
 384                (parseInt(match[1],10)*3600 + parseInt(match[2],10)*60)));
 385        var localDateStr = // e.g. '2005-08-07'
 386                localDate.getUTCFullYear()                 + '-' +
 387                padLeft(localDate.getUTCMonth()+1, 2, '0') + '-' +
 388                padLeft(localDate.getUTCDate(),    2, '0');
 389        var localTimeStr = // e.g. '21:49:46'
 390                padLeft(localDate.getUTCHours(),   2, '0') + ':' +
 391                padLeft(localDate.getUTCMinutes(), 2, '0') + ':' +
 392                padLeft(localDate.getUTCSeconds(), 2, '0');
 393
 394        return localDateStr + ' ' + localTimeStr + ' ' + timezoneInfo;
 395}
 396
 397/* ............................................................ */
 398/* unquoting/unescaping filenames */
 399
 400/**#@+
 401 * @constant
 402 */
 403var escCodeRe = /\\([^0-7]|[0-7]{1,3})/g;
 404var octEscRe = /^[0-7]{1,3}$/;
 405var maybeQuotedRe = /^\"(.*)\"$/;
 406/**#@-*/
 407
 408/**
 409 * unquote maybe git-quoted filename
 410 * e.g. 'aa' -> 'aa', '"a\ta"' -> 'a    a'
 411 *
 412 * @param {String} str: git-quoted string
 413 * @returns {String} Unquoted and unescaped string
 414 *
 415 * @globals escCodeRe, octEscRe, maybeQuotedRe
 416 */
 417function unquote(str) {
 418        function unq(seq) {
 419                var es = {
 420                        // character escape codes, aka escape sequences (from C)
 421                        // replacements are to some extent JavaScript specific
 422                        t: "\t",   // tab            (HT, TAB)
 423                        n: "\n",   // newline        (NL)
 424                        r: "\r",   // return         (CR)
 425                        f: "\f",   // form feed      (FF)
 426                        b: "\b",   // backspace      (BS)
 427                        a: "\x07", // alarm (bell)   (BEL)
 428                        e: "\x1B", // escape         (ESC)
 429                        v: "\v"    // vertical tab   (VT)
 430                };
 431
 432                if (seq.search(octEscRe) !== -1) {
 433                        // octal char sequence
 434                        return String.fromCharCode(parseInt(seq, 8));
 435                } else if (seq in es) {
 436                        // C escape sequence, aka character escape code
 437                        return es[seq];
 438                }
 439                // quoted ordinary character
 440                return seq;
 441        }
 442
 443        var match = str.match(maybeQuotedRe);
 444        if (match) {
 445                str = match[1];
 446                // perhaps str = eval('"'+str+'"'); would be enough?
 447                str = str.replace(escCodeRe,
 448                        function (substr, p1, offset, s) { return unq(p1); });
 449        }
 450        return str;
 451}
 452
 453/* ============================================================ */
 454/* main part: parsing response */
 455
 456/**
 457 * Function called for each blame entry, as soon as it finishes.
 458 * It updates page via DOM manipulation, adding sha1 info, etc.
 459 *
 460 * @param {Commit} commit: blamed commit
 461 * @param {Object} group: object representing group of lines,
 462 *                        which blame the same commit (blame entry)
 463 *
 464 * @globals blamedLines
 465 */
 466function handleLine(commit, group) {
 467        /*
 468           This is the structure of the HTML fragment we are working
 469           with:
 470
 471           <tr id="l123" class="">
 472             <td class="sha1" title=""><a href=""> </a></td>
 473             <td class="linenr"><a class="linenr" href="">123</a></td>
 474             <td class="pre"># times (my ext3 doesn&#39;t).</td>
 475           </tr>
 476        */
 477
 478        var resline = group.resline;
 479
 480        // format date and time string only once per commit
 481        if (!commit.info) {
 482                /* e.g. 'Kay Sievers, 2005-08-07 21:49:46 +0200' */
 483                commit.info = commit.author + ', ' +
 484                        formatDateISOLocal(commit.authorTime, commit.authorTimezone);
 485        }
 486
 487        // color depends on group of lines, not only on blamed commit
 488        var colorNo = findColorNo(
 489                document.getElementById('l'+(resline-1)),
 490                document.getElementById('l'+(resline+group.numlines))
 491        );
 492
 493        // loop over lines in commit group
 494        for (var i = 0; i < group.numlines; i++, resline++) {
 495                var tr = document.getElementById('l'+resline);
 496                if (!tr) {
 497                        break;
 498                }
 499                /*
 500                        <tr id="l123" class="">
 501                          <td class="sha1" title=""><a href=""> </a></td>
 502                          <td class="linenr"><a class="linenr" href="">123</a></td>
 503                          <td class="pre"># times (my ext3 doesn&#39;t).</td>
 504                        </tr>
 505                */
 506                var td_sha1  = tr.firstChild;
 507                var a_sha1   = td_sha1.firstChild;
 508                var a_linenr = td_sha1.nextSibling.firstChild;
 509
 510                /* <tr id="l123" class=""> */
 511                var tr_class = '';
 512                if (colorNo !== null) {
 513                        tr_class = 'color'+colorNo;
 514                }
 515                if (commit.boundary) {
 516                        tr_class += ' boundary';
 517                }
 518                if (commit.nprevious === 0) {
 519                        tr_class += ' no-previous';
 520                } else if (commit.nprevious > 1) {
 521                        tr_class += ' multiple-previous';
 522                }
 523                tr.className = tr_class;
 524
 525                /* <td class="sha1" title="?" rowspan="?"><a href="?">?</a></td> */
 526                if (i === 0) {
 527                        td_sha1.title = commit.info;
 528                        td_sha1.rowSpan = group.numlines;
 529
 530                        a_sha1.href = projectUrl + 'a=commit;h=' + commit.sha1;
 531                        a_sha1.firstChild.data = commit.sha1.substr(0, 8);
 532                        if (group.numlines >= 2) {
 533                                var fragment = document.createDocumentFragment();
 534                                var br   = document.createElement("br");
 535                                var text = document.createTextNode(
 536                                        commit.author.match(/\b([A-Z])\B/g).join(''));
 537                                if (br && text) {
 538                                        var elem = fragment || td_sha1;
 539                                        elem.appendChild(br);
 540                                        elem.appendChild(text);
 541                                        if (fragment) {
 542                                                td_sha1.appendChild(fragment);
 543                                        }
 544                                }
 545                        }
 546                } else {
 547                        //tr.removeChild(td_sha1); // DOM2 Core way
 548                        tr.deleteCell(0); // DOM2 HTML way
 549                }
 550
 551                /* <td class="linenr"><a class="linenr" href="?">123</a></td> */
 552                var linenr_commit =
 553                        ('previous' in commit ? commit.previous : commit.sha1);
 554                var linenr_filename =
 555                        ('file_parent' in commit ? commit.file_parent : commit.filename);
 556                a_linenr.href = projectUrl + 'a=blame_incremental' +
 557                        ';hb=' + linenr_commit +
 558                        ';f='  + encodeURIComponent(linenr_filename) +
 559                        '#l' + (group.srcline + i);
 560
 561                blamedLines++;
 562
 563                //updateProgressInfo();
 564        }
 565}
 566
 567// ----------------------------------------------------------------------
 568
 569var inProgress = false;   // are we processing response
 570
 571/**#@+
 572 * @constant
 573 */
 574var sha1Re = /^([0-9a-f]{40}) ([0-9]+) ([0-9]+) ([0-9]+)/;
 575var infoRe = /^([a-z-]+) ?(.*)/;
 576var endRe  = /^END ?([^ ]*) ?(.*)/;
 577/**@-*/
 578
 579var curCommit = new Commit();
 580var curGroup  = {};
 581
 582var pollTimer = null;
 583
 584/**
 585 * Parse output from 'git blame --incremental [...]', received via
 586 * XMLHttpRequest from server (blamedataUrl), and call handleLine
 587 * (which updates page) as soon as blame entry is completed.
 588 *
 589 * @param {String[]} lines: new complete lines from blamedata server
 590 *
 591 * @globals commits, curCommit, curGroup, t_interval_server, cmds_server
 592 * @globals sha1Re, infoRe, endRe
 593 */
 594function processBlameLines(lines) {
 595        var match;
 596
 597        for (var i = 0, len = lines.length; i < len; i++) {
 598
 599                if ((match = sha1Re.exec(lines[i]))) {
 600                        var sha1 = match[1];
 601                        var srcline  = parseInt(match[2], 10);
 602                        var resline  = parseInt(match[3], 10);
 603                        var numlines = parseInt(match[4], 10);
 604
 605                        var c = commits[sha1];
 606                        if (!c) {
 607                                c = new Commit(sha1);
 608                                commits[sha1] = c;
 609                        }
 610                        curCommit = c;
 611
 612                        curGroup.srcline = srcline;
 613                        curGroup.resline = resline;
 614                        curGroup.numlines = numlines;
 615
 616                } else if ((match = infoRe.exec(lines[i]))) {
 617                        var info = match[1];
 618                        var data = match[2];
 619                        switch (info) {
 620                        case 'filename':
 621                                curCommit.filename = unquote(data);
 622                                // 'filename' information terminates the entry
 623                                handleLine(curCommit, curGroup);
 624                                updateProgressInfo();
 625                                break;
 626                        case 'author':
 627                                curCommit.author = data;
 628                                break;
 629                        case 'author-time':
 630                                curCommit.authorTime = parseInt(data, 10);
 631                                break;
 632                        case 'author-tz':
 633                                curCommit.authorTimezone = data;
 634                                break;
 635                        case 'previous':
 636                                curCommit.nprevious++;
 637                                // store only first 'previous' header
 638                                if (!'previous' in curCommit) {
 639                                        var parts = data.split(' ', 2);
 640                                        curCommit.previous    = parts[0];
 641                                        curCommit.file_parent = unquote(parts[1]);
 642                                }
 643                                break;
 644                        case 'boundary':
 645                                curCommit.boundary = true;
 646                                break;
 647                        } // end switch
 648
 649                } else if ((match = endRe.exec(lines[i]))) {
 650                        t_interval_server = match[1];
 651                        cmds_server = match[2];
 652
 653                } else if (lines[i] !== '') {
 654                        // malformed line
 655
 656                } // end if (match)
 657
 658        } // end for (lines)
 659}
 660
 661/**
 662 * Process new data and return pointer to end of processed part
 663 *
 664 * @param {String} unprocessed: new data (from nextReadPos)
 665 * @param {Number} nextReadPos: end of last processed data
 666 * @return {Number} end of processed data (new value for nextReadPos)
 667 */
 668function processData(unprocessed, nextReadPos) {
 669        var lastLineEnd = unprocessed.lastIndexOf('\n');
 670        if (lastLineEnd !== -1) {
 671                var lines = unprocessed.substring(0, lastLineEnd).split('\n');
 672                nextReadPos += lastLineEnd + 1 /* 1 == '\n'.length */;
 673
 674                processBlameLines(lines);
 675        } // end if
 676
 677        return nextReadPos;
 678}
 679
 680/**
 681 * Handle XMLHttpRequest errors
 682 *
 683 * @param {XMLHttpRequest} xhr: XMLHttpRequest object
 684 *
 685 * @globals pollTimer, commits, inProgress
 686 */
 687function handleError(xhr) {
 688        errorInfo('Server error: ' +
 689                xhr.status + ' - ' + (xhr.statusText || 'Error contacting server'));
 690
 691        clearInterval(pollTimer);
 692        commits = {}; // free memory
 693
 694        inProgress = false;
 695}
 696
 697/**
 698 * Called after XMLHttpRequest finishes (loads)
 699 *
 700 * @param {XMLHttpRequest} xhr: XMLHttpRequest object (unused)
 701 *
 702 * @globals pollTimer, commits, inProgress
 703 */
 704function responseLoaded(xhr) {
 705        clearInterval(pollTimer);
 706
 707        fixColorsAndGroups();
 708        writeTimeInterval();
 709        commits = {}; // free memory
 710
 711        inProgress = false;
 712}
 713
 714/**
 715 * handler for XMLHttpRequest onreadystatechange event
 716 * @see startBlame
 717 *
 718 * @globals xhr, inProgress
 719 */
 720function handleResponse() {
 721
 722        /*
 723         * xhr.readyState
 724         *
 725         *  Value  Constant (W3C)    Description
 726         *  -------------------------------------------------------------------
 727         *  0      UNSENT            open() has not been called yet.
 728         *  1      OPENED            send() has not been called yet.
 729         *  2      HEADERS_RECEIVED  send() has been called, and headers
 730         *                           and status are available.
 731         *  3      LOADING           Downloading; responseText holds partial data.
 732         *  4      DONE              The operation is complete.
 733         */
 734
 735        if (xhr.readyState !== 4 && xhr.readyState !== 3) {
 736                return;
 737        }
 738
 739        // the server returned error
 740        if (xhr.readyState === 3 && xhr.status !== 200) {
 741                return;
 742        }
 743        if (xhr.readyState === 4 && xhr.status !== 200) {
 744                handleError(xhr);
 745                return;
 746        }
 747
 748        // In konqueror xhr.responseText is sometimes null here...
 749        if (xhr.responseText === null) {
 750                return;
 751        }
 752
 753        // in case we were called before finished processing
 754        if (inProgress) {
 755                return;
 756        } else {
 757                inProgress = true;
 758        }
 759
 760        // extract new whole (complete) lines, and process them
 761        while (xhr.prevDataLength !== xhr.responseText.length) {
 762                if (xhr.readyState === 4 &&
 763                    xhr.prevDataLength === xhr.responseText.length) {
 764                        break;
 765                }
 766
 767                xhr.prevDataLength = xhr.responseText.length;
 768                var unprocessed = xhr.responseText.substring(xhr.nextReadPos);
 769                xhr.nextReadPos = processData(unprocessed, xhr.nextReadPos);
 770        } // end while
 771
 772        // did we finish work?
 773        if (xhr.readyState === 4 &&
 774            xhr.prevDataLength === xhr.responseText.length) {
 775                responseLoaded(xhr);
 776        }
 777
 778        inProgress = false;
 779}
 780
 781// ============================================================
 782// ------------------------------------------------------------
 783
 784/**
 785 * Incrementally update line data in blame_incremental view in gitweb.
 786 *
 787 * @param {String} blamedataUrl: URL to server script generating blame data.
 788 * @param {String} bUrl: partial URL to project, used to generate links.
 789 *
 790 * Called from 'blame_incremental' view after loading table with
 791 * file contents, a base for blame view.
 792 *
 793 * @globals xhr, t0, projectUrl, div_progress_bar, totalLines, pollTimer
 794*/
 795function startBlame(blamedataUrl, bUrl) {
 796
 797        xhr = createRequestObject();
 798        if (!xhr) {
 799                errorInfo('ERROR: XMLHttpRequest not supported');
 800                return;
 801        }
 802
 803        t0 = new Date();
 804        projectUrl = bUrl + (bUrl.indexOf('?') === -1 ? '?' : ';');
 805        if ((div_progress_bar = document.getElementById('progress_bar'))) {
 806                //div_progress_bar.setAttribute('style', 'width: 100%;');
 807                div_progress_bar.style.cssText = 'width: 100%;';
 808        }
 809        totalLines = countLines();
 810        updateProgressInfo();
 811
 812        /* add extra properties to xhr object to help processing response */
 813        xhr.prevDataLength = -1;  // used to detect if we have new data
 814        xhr.nextReadPos = 0;      // where unread part of response starts
 815
 816        xhr.onreadystatechange = handleResponse;
 817        //xhr.onreadystatechange = function () { handleResponse(xhr); };
 818
 819        xhr.open('GET', blamedataUrl);
 820        xhr.setRequestHeader('Accept', 'text/plain');
 821        xhr.send(null);
 822
 823        // not all browsers call onreadystatechange event on each server flush
 824        // poll response using timer every second to handle this issue
 825        pollTimer = setInterval(xhr.onreadystatechange, 1000);
 826}
 827
 828// end of gitweb.js