summaryrefslogtreecommitdiffstats
path: root/src/bmweb/global.js
blob: e6b80d67e0b950eedfd1d141973e7c2135b326aa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
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
458
459
460
461
462
463
464
465
466
467
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the BM project on Qt Labs.
**
** This file may be used under the terms of the GNU General Public
** License version 2.0 or 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of
** this file.  Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/

function trim(s)
{
    var i;
    var j;
    for (i = 0; i < s.length && s[i] == ' '; ++i) ;
    for (j = s.length - 1; j >= i && s[j] == ' '; --j) ;
    return (i <= j) ? s.substr(i, (j - i) + 1) : "";
}

function server()
{
    val = trim(document.getElementById("customServer").value);
    if (val != "")
        return val;

    val = trim(document.getElementById("defaultServer").innerHTML);
    if (val != "")
        return val;

    return "";
}

function sendRequest(args, handleReply, handleError, omitServer)
{
    var request = new XMLHttpRequest(); // ### may not work in all browsers!

    // Register notification handler ...
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
//                alert("request.responseText: " + request.responseText);
                handleReply(eval('(' + request.responseText + ')'));
            } else {
//                alert("Error" + request.status + ": " + request.statusText);
                handleError("Error" + request.status + ": " + request.statusText);
            }
        }
    }

    // Set up URL ....
//    var command = "\"";
    var command = "";

    if (!omitServer) {
        var s = server();
        if (s != "") {
            command += "-server";
            command += " " + s;
        }
    }

    for (var i = 0; i < args.length; i++)
        command += (" " + args[i]);
//    command += "\"";
    command += "";
    var url = "http://" + location.host + "/cgi-bin/bmclientwrapper?command=" + command;


    // Send request ...
    // alert("sending request; URL: " + url);
    request.open("get", url);
    request.send(null);
}

function sendFileRequest(file, handleReply, handleError)
{
    var request = new XMLHttpRequest(); // ### may not work in all browsers!

    // Register notification handler ...
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
//                alert("request.responseText: " + request.responseText);
                handleReply(eval('(' + request.responseText + ')'));
            } else {
//                alert("Error" + request.status + ": " + request.statusText);
                handleError("Error" + request.status + ": " + request.statusText);
            }
        }
    }

    // Set up URL ....
    var url = "http://" + location.host + "/cgi-bin/bmclientwrapper";

    // Send request ...
    request.open("post", url);
    request.sendAsBinary(file.getAsBinary());
}

function setMessage(msg)
{
    document.getElementById("message").innerHTML = msg;
}

var startTime;

function startTiming()
{
    startTime = new Date();
}

function stopTiming(operation)
{
    stopTime = new Date();
    var elapsedSecs = (stopTime.getTime() - startTime.getTime()) / 1000;
    document.getElementById("timing").innerHTML =
        "elapsed secs (" + operation + "): " + elapsedSecs;
}

// Replaces word i in s with r.
// A word is assumed to be a consecutive sequence of non-whitespace characters.
// Words are indexed from 0 to n - 1 inclusive where n is the number of words in s.
// If i is negative, the word to be replaced is n + i.
function replaceWord(s, i, r)
{
    var ts = trim(s);
    var pos; // Index 0: Start position of ith word. Index 1: Next position after ith word,
             // or -1 if i is the last word.

    function wordPos(s, i)
    {
        var pos1;
        var pos2;
        for (j = 0, start = 0; j <= i; ++j, start = pos2) {
            var p1 = s.substring(start).search(/\S+/); // assert(pos1 >= 0);
            pos1 = start + p1;
            start = pos1;
            var p2 = s.substring(start).search(/\s+/);
            pos2 = start + p2;
        }
        return [pos1, pos2];
    }

    if (i >= 0) {
        pos = wordPos(ts, i);
    } else {
        pos = wordPos(ts.split('').reverse().join(''), -i - 1);
        var pos0 = pos[0];
        var pos1 = pos[1];
        pos[0] = ts.length - pos1;
        pos[1] = ts.length - pos0;
    }

    // Replace word ...
    var rs = ts.substring(0, pos[0]) + r;
    if (pos[1] != -1)
        rs += ts.substring(pos[1])

    return rs;
}

// Updates the href of the details link use case 1 (primary branch analysis).
function updateDetailsLink(idSuffix)
{
    detailsLink = document.getElementById("detailsLink" + idSuffix);
    href = detailsLink.getAttribute("href");
    href = replaceWord(href, 1, server());
    href = replaceWord(href, -3, maxDetailsHistory());
    href = replaceWord(href, -1, currTimestamp());
    detailsLink.setAttribute("href", href);
}

// Updates the href of the details link for use case 2 (primary/secondary branch comparison).
function updateDetailsLink2(idSuffix)
{
    detailsLink = document.getElementById("detailsLink" + idSuffix);
    href = detailsLink.getAttribute("href");
    href = replaceWord(href, 1, server());
    href = replaceWord(href, -4, maxDetailsHistory());
    href = replaceWord(href, -3, sharedTimeScale());
    href = replaceWord(href, -1, currTimestamp());
    detailsLink.setAttribute("href", href);
}

function initSections()
{
    function finalizeInit()
    {
        setMessage("");

        // Show initial section ...
        state_ = cookie.getDynamicProperties();
        if (state_["currentSection"] == ixSection().name()) {
            ixSection().install();
        } else if (state_["currentSection"] == psSection().name()) {
            psSection().install();
        } else if (state_["currentSection"] == bsSection().name()) {
            bsSection().install();
        } else if (state_["currentSection"] == settingsSection().name()) {
            settingsSection().install();
        } else {
            psSection().install(); // default
        }
    }

    function loadIXStateFromCookie()
    {
        loadStateFromCookie(ixSection(), finalizeInit);
    }

    function loadBSStateFromCookie()
    {
        loadStateFromCookie(bsSection(), loadIXStateFromCookie);
    }

    function loadPSStateFromCookie()
    {
        loadStateFromCookie(psSection(), loadBSStateFromCookie);
    }

    function resetIXSection()
    {
        ixSection().reset(loadPSStateFromCookie);
    }

    function resetBSSection()
    {
        if (Cookie.enabled()) {
            bsSection().reset(resetIXSection);
        } else {
            finalizeInit();
        }
    }

    function resetPSSection()
    {
        psSection().reset(resetBSSection);
    }

    function handleReply(reply)
    {
        if (reply.error) {
            setMessage("initialization failed: " + reply.error);
        } else {
            resetPSSection();
        }
    }

    function handleError(error)
    {
        setMessage("initialization failed: " + error);
    }

    setMessage("initializing ...");

    // Send a dummy request to the server just to check if it is alive and responding ...
    sendRequest(["get", "metrics"], handleReply, handleError);
}

function getDefaultServer()
{
    function handleReply(reply)
    {
        var name;
        var color;
        if (reply.error) {
//            alert("getDefaultServer() got error reply: " + reply.error);
            name = "none";
            color = "red";
        } else {
            name = reply.server;
            color = "green";
        }
        var defaultServer = document.getElementById("defaultServer");
        defaultServer.innerHTML = name;
        defaultServer.style.color = color;
    }

    function handleError(error)
    {
        alert("getDefaultServer() failed: " + error);
    }

    sendRequest(["get", "server"], handleReply, handleError, true);
}

function sharedTimeScale()
{
    return document.getElementById("sharedTimeScale").checked ? 1 : 0;
}

function getIntFromTextInput(id, defaultValue)
{
    var value = parseInt(document.getElementById(id).value);
    if (isNaN(value))
        value = defaultValue;
    return value;
}

function maxDetailsHistory()
{
    var mdh = parseInt(document.getElementById("maxDetailsHistory").value);
    if (isNaN(mdh))
        mdh = -1; // ### use e.g. 100 as default instead, in case the database is large?
    return mdh;
}

function maxBenchmarksPerScope()
{
    var mbps = parseInt(document.getElementById("maxBenchmarksPerScope").value);
    if (isNaN(mbps))
        mbps = -1; // ### use e.g. 100 as default instead, in case the database is large?
    return mbps;
}

function benchmarkFilter(id)
{
    var f = trim(document.getElementById(id).value);
    if (f == "")
        f = "*";
    return f;
}

function currTimestamp()
{
    var currDate = new Date();
    return Math.round(currDate.getTime() / 1000);
}

function disableTopSectionButtons(exceptId)
{
    var topSection = document.getElementById("topSection");
    var buttons = topSection.getElementsByTagName("input");
    var exceptButton = (exceptId != null) ? document.getElementById(exceptId) : null;
    for (var i = 0; i < buttons.length; ++i) {
        buttons[i].disabled = (buttons[i] != exceptButton);
    }
}

function hideAllSections()
{
    sectionParent = document.getElementById("section");
    var sections = sectionParent.getElementsByTagName("div");
    for (var i = 0; i < sections.length; ++i)
        hideElement(sections[i]);
}

function showElement(element)
{
    element.setAttribute("style", "display:block");
}

function hideElement(element)
{
    element.setAttribute("style", "display:none");
}

function removeElementChildren(element)
{
    while (element.childNodes.length >= 1)
        element.removeChild(element.lastChild);
}

function insertTitle(section, title)
{
    section.appendChild(document.createElement("br"));
    var span = section.appendChild(document.createElement("span"));
    span.setAttribute("class", "sectionTitle");
    span.appendChild(document.createTextNode(title));
}

function selectedOptions(id)
{
    var select = document.getElementById(id);
    if (!select)
        return [];
    var result = [];
    var options = select.options;
    for (i = 0; i < options.length; ++i) {
        if (options[i].selected)
            result = result.concat(options[i].value);
    }
    return result;
}

function sortOptions(id)
{
    var select = document.getElementById(id);
    if (!select)
        return;
    var optionValues = [];
    for (i = 0; i < select.options.length; ++i)
        optionValues[optionValues.length] = select.options[i].value;
    optionValues.sort(function(val1, val2) {
        return val1 > val2;
    });
    select.options.length = 0;
    for (i = 0; i < optionValues.length; ++i)
        select.options[select.options.length] = new Option(optionValues[i]);
}

function setDiffToleranceOptions(select)
{
    select.options[0] = new Option("0.00", "0.00");
    select.options[1] = new Option("0.01", "0.01");
    select.options[2] = new Option("0.02", "0.02");
    select.options[3] = new Option("0.05", "0.05");
    select.options[4] = new Option("0.10", "0.10");
    select.options[5] = new Option("0.20", "0.20");
    select.options[6] = new Option("0.50", "0.50");
    select.options[7] = new Option("1.00", "1.00");
}

function setStabToleranceOptions(select)
{
    select.options[0] = new Option("0", "0");
    select.options[1] = new Option("1", "1");
    select.options[2] = new Option("2", "2");
    select.options[3] = new Option("3", "3");
    select.options[4] = new Option("4", "4");
    select.options[5] = new Option("5", "5");
}

function matchesContext(contexts, candidate)
{
    for (var i = 0; i < contexts.length; ++i) {
        var context = contexts[i];
        var j;
        for (j = 0; j < candidate.length; ++j) {
            if ((candidate[j] != -1) && (candidate[j] != context[j]))
                break; // mismatch
        }
        if (j == candidate.length)
            return true; // no mismatch found for this context
    }
    return false; // mismatch found for all contexts
}

function ageText(msecs)
{
    var totSecs = Math.round(msecs / 1000);
    var secsInDay = 86400; // 24 * 60 * 60
    if (false) {
        // *** Option 1 ***
        var secs = totSecs % secsInDay;
        // Subtraction required to get integer division:
        var days = (totSecs - secs) / secsInDay;
        return days + " day" + ((days == 1) ? "" : "s") + " and " + secs + " secs ago";
    } else {
        // *** Option 2 ***
        //            return (totSecs / secsInDay).toFixed(2) + " days ago";
        return (totSecs / secsInDay).toFixed(2);
    }
}

function zeroPad2(s)
{
    return (s.length == 2) ? s : ("0" + s);
}

// ### refactor against other *Color functions?
function ageColor(msecs)
{
    var secs = Math.round(msecs / 1000);
    var secsInDay = 86400; // 24 * 60 * 60

    var minSecs = 0;
    var maxSecs = 31536000; // 365 * secsInDay

    var minR = 255;
    var minG = 128;
    var minB = 0;

    var maxR = 228;
    var maxG = 228;
    var maxB = 228;

    var frac = (secs - minSecs) / (maxSecs - minSecs);
    frac = Math.max(Math.min(frac, 1), 0);

    var r = Math.round((1 - frac) * minR + frac * maxR);
    var g = Math.round((1 - frac) * minG + frac * maxG);
    var b = Math.round((1 - frac) * minB + frac * maxB);
    var color =
        "#" + zeroPad2(r.toString(16)) + zeroPad2(g.toString(16))
        + zeroPad2(b.toString(16));
    return color;
}

function redToGreenColor(val, minAbsVal, maxAbsVal)
{
    if (Math.abs(val) < minAbsVal)
        return "#ffffff";

    var lo = -maxAbsVal;
    var hi = maxAbsVal;
    var frac = (val - lo) / (hi - lo);
    frac = Math.max(Math.min(frac, 1), 0);

    var val1 = Math.round(frac * 255 * 1.5);
    var val2 = Math.round((1 - frac) * 255 * 1.5);
    var r = (frac > 0.5) ? 255 : val1;
    var g = (frac < 0.5) ? 255 : val2;
    var b = (frac < 0.5) ? val1 : val2;
    var color =
        "#" + zeroPad2(r.toString(16)) + zeroPad2(g.toString(16))
        + zeroPad2(b.toString(16));
    return color;
}

function diffColor(diff)
{
    return redToGreenColor(diff, 0.0001, 0.01); // ### does this scaling interval make sense?
}

function trendColor(trend)
{
    // ### Does this scaling interval make sense? Since the trend line is computed from
    // the raw (i.e. unnormalized) time series, maybe only use three fixed colors
    // (for positive, zero, and negative trend)?
    return redToGreenColor(trend, 0.0001, 1);
}

function normalizedDifference(a, b)
{
    return (a == b) ? 0 : ((a - b) / (Math.max(Math.abs(a), Math.abs(b))));
}

function platformImage(platform)
{
    imageDir = "images/";
    map = [
        ["linux", "linux.png"],
        ["solaris", "solaris.png"],
        ["mac", "mac.png"],
        ["wince", "wince.png"],
        ["win", "windows.png"],
        ["s60", "s60.png"],
        ["symbian", "generic.png"]
    ];
    for (i = 0; i < map.length; ++i)
        if (platform.indexOf(map[i][0]) != -1)
            return imageDir + map[i][1];
    return imageDir + "defaultplatform.png";
}

function metricImage(metric)
{
    imageDir = "images/";
    map = [
        ["walltime", "walltime.png"],
        ["callgrind", "callgrind.png"]
    ];
    for (i = 0; i < map.length; ++i)
        if (map[i][0] == metric)
            return imageDir + map[i][1];
    return imageDir + "defaultmetric.png";
}

function arrayContains(a, v)
{
    for (i = 0; i < a.length; ++i)
        if (a[i] == v)
            return true;
    return false;
}

function appendSpans(elem)
{
    for (i = 1; i < arguments.length; ++i) {
        span = elem.appendChild(document.createElement("span"));
        span.title = arguments[i];
    }
}

function initialized()
{
    // ### the following trick may not work in all browsers (in Opera for instance?)
    if (!navigator.init) {
        navigator.init = true;
        return false;
    }
    return true;
}

function appendHelpLink(sectionElem, href)
{
    sectionElem.appendChild(document.createElement("br"));
    helpLink = sectionElem.appendChild(document.createElement("a"));
    helpLink.setAttribute("href", href);
    helpLink.appendChild(document.createTextNode("Help"));
}

function sectionElem2Name(sectionElem)
{
    if (sectionElem == ixSection().sectionElem)
        return ixSection().name();
    if (sectionElem == psSection().sectionElem)
        return psSection().name();
    if (sectionElem == bsSection().sectionElem)
        return bsSection().name();
    if (sectionElem == settingsSection().sectionElem)
        return settingsSection().name();
    return null;
}

function currentSection()
{
    var sectionElems = document.getElementById("section").getElementsByTagName("div");
    for (var i = 0; i < sectionElems.length; ++i) {
        if (sectionElems[i].getAttribute("style").indexOf("block") != -1) {
            return sectionElem2Name(sectionElems[i]);
        }
    }
    return null;
}

var cookie; // For keeping state across sessions

function saveStateToCookie()
{
    function appendCookieState(state) {
        for (var name in state) {
            cookie.setDynamicProperty(name, state[name]);
        }
    }

    appendCookieState(ixSection().state());
    appendCookieState(psSection().state());
    appendCookieState(bsSection().state());
    appendCookieState(settingsSection().state());

    cookie.setDynamicProperty("currentSection", currentSection());

    cookie.store();
}

function loadStateFromCookie(section, handleDone)
{
    section.setState(cookie.getDynamicProperties(), handleDone);
}

function initialize()
{
    function initialize_()
    {
//         if (initialized()) {
//             alert("already initialized!");
//             return;
//         }

        getDefaultServer();

        // Install event handlers ...
        document.getElementById("indexButton").setAttribute(
            "onclick", "try { ixSection().install(); } catch (ex) "
            + "{ alert('ixSection().install() failed: ' + ex); }");
        document.getElementById("platformSummaryButton").setAttribute(
            "onclick", "try { psSection().install(); } catch (ex) "
            + "{ alert('psSection().install() failed: ' + ex); }");
        document.getElementById("benchmarkSummaryButton").setAttribute(
            "onclick", "try { bsSection().install(); } catch (ex) "
            + "{ alert('bsSection().install() failed: ' + ex); }");
        document.getElementById("settingsButton").setAttribute(
            "onclick", "try { settingsSection().install(); } catch (ex) "
                + "{ alert('settingsSection().install() failed: ' + ex); }");

        // Create sections ...
        var sectionParent = document.getElementById("section");
        sectionParent.appendChild(ixSection().sectionElem);
        sectionParent.appendChild(psSection().sectionElem);
        sectionParent.appendChild(bsSection().sectionElem);
        sectionParent.appendChild(settingsSection().sectionElem);

        // If possible, load some state from a cookie ...
        if (Cookie.enabled()) {
            cookie = new Cookie("bmstate");
            window.onbeforeunload = function() { saveStateToCookie(); }
            loadStateFromCookie(settingsSection());
        }

        hideAllSections();
        disableTopSectionButtons("settingsButton");

        // Initialize sections (loading more state from the cookie etc.) ...
        initSections();
    }

    try { initialize_() } catch (ex) { alert("initialize_() failed: " + ex); }
}