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