v2 UI should have buttons to breakdown a test
[WebKit-https.git] / Websites / perf.webkit.org / public / v2 / app.js
1 window.App = Ember.Application.create();
2
3 App.Router.map(function () {
4     this.resource('customDashboard', {path: 'dashboard/custom'});
5     this.resource('dashboard', {path: 'dashboard/:name'});
6     this.resource('charts', {path: 'charts'});
7     this.resource('analysis', {path: 'analysis'});
8     this.resource('analysisTask', {path: 'analysis/task/:taskId'});
9 });
10
11 App.DashboardRow = Ember.Object.extend({
12     header: null,
13     cells: [],
14
15     init: function ()
16     {
17         this._super();
18
19         var cellsInfo = this.get('cellsInfo') || [];
20         var columnCount = this.get('columnCount');
21         while (cellsInfo.length < columnCount)
22             cellsInfo.push([]);
23
24         this.set('cells', cellsInfo.map(this._createPane.bind(this)));
25     },
26     addPane: function (paneInfo)
27     {
28         var pane = this._createPane(paneInfo);
29         this.get('cells').pushObject(pane);
30         this.set('columnCount', this.get('columnCount') + 1);
31     },
32     _createPane: function (paneInfo)
33     {
34         if (!paneInfo || !paneInfo.length || (!paneInfo[0] && !paneInfo[1]))
35             paneInfo = null;
36
37         var pane = App.Pane.create({
38             store: this.get('store'),
39             platformId: paneInfo ? paneInfo[0] : null,
40             metricId: paneInfo ? paneInfo[1] : null,
41         });
42
43         return App.DashboardPaneProxyForPicker.create({content: pane});
44     },
45 });
46
47 App.DashboardPaneProxyForPicker = Ember.ObjectProxy.extend({
48     _platformOrMetricIdChanged: function ()
49     {
50         var self = this;
51         App.buildPopup(this.get('store'), 'choosePane', this)
52             .then(function (platforms) { self.set('pickerData', platforms); });
53     }.observes('platformId', 'metricId').on('init'),
54     paneList: function () {
55         return App.encodePrettifiedJSON([[this.get('platformId'), this.get('metricId'), null, null, null, null, null]]);
56     }.property('platformId', 'metricId'),
57 });
58
59 App.IndexRoute = Ember.Route.extend({
60     beforeModel: function ()
61     {
62         var self = this;
63         App.Manifest.fetch(this.store).then(function () {
64             self.transitionTo('dashboard', App.Manifest.defaultDashboardName());
65         });
66     },
67 });
68
69 App.DashboardRoute = Ember.Route.extend({
70     model: function (param)
71     {
72         return App.Manifest.fetch(this.store).then(function () {
73             return App.Manifest.dashboardByName(param.name);
74         });
75     },
76 });
77
78 App.CustomDashboardRoute = Ember.Route.extend({
79     controllerName: 'dashboard',
80     model: function (param)
81     {
82         return this.store.createRecord('dashboard', {serialized: param.grid});
83     },
84     renderTemplate: function()
85     {
86         this.render('dashboard');
87     }
88 });
89
90 App.DashboardController = Ember.Controller.extend({
91     queryParams: ['grid', 'numberOfDays'],
92     headerColumns: [],
93     rows: [],
94     numberOfDays: 7,
95     editMode: false,
96
97     modelChanged: function ()
98     {
99         var dashboard = this.get('model');
100         if (!dashboard)
101             return;
102
103         var headerColumns = dashboard.get('headerColumns');
104         this.set('headerColumns', headerColumns);
105         var columnCount = headerColumns.length;
106         this.set('columnCount', columnCount);
107
108         var store = this.store;
109         this.set('rows', dashboard.get('rows').map(function (rowParam) {
110             return App.DashboardRow.create({
111                 store: store,
112                 header: rowParam[0],
113                 cellsInfo: rowParam.slice(1),
114                 columnCount: columnCount,
115             })
116         }));
117
118         this.set('emptyRow', new Array(columnCount));
119     }.observes('model').on('init'),
120
121     computeGrid: function()
122     {
123         var headers = this.get('headerColumns').map(function (header) { return header.label; });
124         var table = [headers].concat(this.get('rows').map(function (row) {
125             return [row.get('header')].concat(row.get('cells').map(function (pane) {
126                 var platformAndMetric = [pane.get('platformId'), pane.get('metricId')];
127                 return platformAndMetric[0] || platformAndMetric[1] ? platformAndMetric : [];
128             }));
129         }));
130         return JSON.stringify(table);
131     },
132
133     _sharedDomainChanged: function ()
134     {
135         var numberOfDays = this.get('numberOfDays');
136         if (!numberOfDays)
137             return;
138
139         numberOfDays = parseInt(numberOfDays);
140         var present = Date.now();
141         var past = present - numberOfDays * 24 * 3600 * 1000;
142         this.set('since', past);
143         this.set('sharedDomain', [past, present]);
144     }.observes('numberOfDays').on('init'),
145
146     actions: {
147         setNumberOfDays: function (numberOfDays)
148         {
149             this.set('numberOfDays', numberOfDays);
150         },
151         choosePane: function (param)
152         {
153             var pane = param.position;
154             pane.set('platformId', param.platform.get('id'));
155             pane.set('metricId', param.metric.get('id'));
156         },
157         addColumn: function ()
158         {
159             this.get('headerColumns').pushObject({
160                 label: this.get('newColumnHeader'),
161                 index: this.get('headerColumns').length,
162             });
163             this.get('rows').forEach(function (row) {
164                 row.addPane();
165             });
166             this.set('newColumnHeader', null);
167         },
168         removeColumn: function (index)
169         {
170             this.get('headerColumns').removeAt(index);
171             this.get('rows').forEach(function (row) {
172                 row.get('cells').removeAt(index);
173             });
174         },
175         addRow: function ()
176         {
177             this.get('rows').pushObject(App.DashboardRow.create({
178                 store: this.store,
179                 header: this.get('newRowHeader'),
180                 columnCount: this.get('columnCount'),
181             }));
182             this.set('newRowHeader', null);
183         },
184         removeRow: function (row)
185         {
186             this.get('rows').removeObject(row);
187         },
188         resetPane: function (pane)
189         {
190             pane.set('platformId', null);
191             pane.set('metricId', null);
192         },
193         toggleEditMode: function ()
194         {
195             this.toggleProperty('editMode');
196             if (this.get('editMode'))
197                 this.transitionToRoute('dashboard', 'custom', {name: null, queryParams: {grid: this.computeGrid()}});
198             else
199                 this.set('grid', this.computeGrid());
200         },
201     },
202
203     init: function ()
204     {
205         this._super();
206         App.Manifest.fetch(this.get('store'));
207     }
208 });
209
210 App.NumberOfDaysControlView = Ember.View.extend({
211     classNames: ['controls'],
212     templateName: 'number-of-days-controls',
213     didInsertElement: function ()
214     {
215         this._matchingElements(this._previousNumberOfDaysClass).addClass('active');
216     },
217     _numberOfDaysChanged: function ()
218     {
219         this._matchingElements(this._previousNumberOfDaysClass).removeClass('active');
220
221         var newNumberOfDaysClass = 'numberOfDaysIs' + this.get('numberOfDays');
222         this._matchingElements(this._previousNumberOfDaysClass).addClass('active');
223         this._previousNumberOfDaysClass = newNumberOfDaysClass;
224     }.observes('numberOfDays').on('init'),
225     _matchingElements: function (className)
226     {
227         var element = this.get('element');
228         if (!element)
229             return $([]);
230         return $(element.getElementsByClassName(className));
231     }
232 });
233
234 App.StartTimeSliderView = Ember.View.extend({
235     templateName: 'start-time-slider',
236     classNames: ['start-time-slider'],
237     startTime: Date.now() - 7 * 24 * 3600 * 1000,
238     oldestStartTime: null,
239     _numberOfDaysView: null,
240     _slider: null,
241     _startTimeInSlider: null,
242     _currentNumberOfDays: null,
243     _MILLISECONDS_PER_DAY: 24 * 3600 * 1000,
244
245     didInsertElement: function ()
246     {
247         this.oldestStartTime = Date.now() - 365 * 24 * 3600 * 1000;
248         this._slider = $(this.get('element')).find('input');
249         this._numberOfDaysView = $(this.get('element')).find('.numberOfDays');
250         this._sliderRangeChanged();
251         this._slider.change(this._sliderMoved.bind(this));
252     },
253     _sliderRangeChanged: function ()
254     {
255         var minimumNumberOfDays = 1;
256         var maximumNumberOfDays = this._timeInPastToNumberOfDays(this.get('oldestStartTime'));
257         var precision = 1000; // FIXME: Compute this from maximumNumberOfDays.
258         var slider = this._slider;
259         slider.attr('min', Math.floor(Math.log(Math.max(1, minimumNumberOfDays)) * precision) / precision);
260         slider.attr('max', Math.ceil(Math.log(maximumNumberOfDays) * precision) / precision);
261         slider.attr('step', 1 / precision);
262         this._startTimeChanged();
263     }.observes('oldestStartTime'),
264     _sliderMoved: function ()
265     {
266         this._currentNumberOfDays = Math.round(Math.exp(this._slider.val()));
267         this._numberOfDaysView.text(this._currentNumberOfDays);
268         this._startTimeInSlider = this._numberOfDaysToTimeInPast(this._currentNumberOfDays);
269         this.set('startTime', this._startTimeInSlider);
270     },
271     _startTimeChanged: function ()
272     {
273         var startTime = this.get('startTime');
274         if (startTime == this._startTimeSetBySlider)
275             return;
276         this._currentNumberOfDays = this._timeInPastToNumberOfDays(startTime);
277
278         if (this._slider) {
279             this._numberOfDaysView.text(this._currentNumberOfDays);
280             this._slider.val(Math.log(this._currentNumberOfDays));
281             this._startTimeInSlider = startTime;
282         }
283     }.observes('startTime').on('init'),
284     _timeInPastToNumberOfDays: function (timeInPast)
285     {
286         return Math.max(1, Math.round((Date.now() - timeInPast) / this._MILLISECONDS_PER_DAY));
287     },
288     _numberOfDaysToTimeInPast: function (numberOfDays)
289     {
290         return Date.now() - numberOfDays * this._MILLISECONDS_PER_DAY;
291     },
292 });
293
294 App.Pane = Ember.Object.extend({
295     platformId: null,
296     platform: null,
297     metricId: null,
298     metric: null,
299     selectedItem: null,
300     selectedPoints: null,
301     hoveredOrSelectedItem: null,
302     showFullYAxis: false,
303     searchCommit: function (repository, keyword) {
304         var self = this;
305         var repositoryId = repository.get('id');
306         CommitLogs.fetchCommits(repositoryId, null, null, keyword).then(function (commits) {
307             if (self.isDestroyed || !self.get('chartData') || !commits.length)
308                 return;
309             var currentRuns = self.get('chartData').current.series();
310             if (!currentRuns.length)
311                 return;
312
313             var highlightedItems = {};
314             var commitIndex = 0;
315             for (var runIndex = 0; runIndex < currentRuns.length && commitIndex < commits.length; runIndex++) {
316                 var measurement = currentRuns[runIndex].measurement;
317                 var commitTime = measurement.commitTimeForRepository(repositoryId);
318                 if (!commitTime)
319                     continue;
320                 if (commits[commitIndex].time <= commitTime) {
321                     highlightedItems[measurement.id()] = true;
322                     do {
323                         commitIndex++;
324                     } while (commitIndex < commits.length && commits[commitIndex].time <= commitTime);
325                 }
326             }
327
328             self.set('highlightedItems', highlightedItems);
329         }, function () {
330             // FIXME: Report errors
331             this.set('highlightedItems', {});
332         });
333     },
334     _fetch: function () {
335         var platformId = this.get('platformId');
336         var metricId = this.get('metricId');
337         if (!platformId && !metricId) {
338             this.set('empty', true);
339             return;
340         }
341         this.set('empty', false);
342         this.set('platform', null);
343         this.set('chartData', null);
344         this.set('metric', null);
345         this.set('failure', null);
346
347         if (!this._isValidId(platformId))
348             this.set('failure', platformId ? 'Invalid platform id:' + platformId : 'Platform id was not specified');
349         else if (!this._isValidId(metricId))
350             this.set('failure', metricId ? 'Invalid metric id:' + metricId : 'Metric id was not specified');
351         else {
352             var self = this;
353             var useCache = true;
354             App.Manifest.fetchRunsWithPlatformAndMetric(this.get('store'), platformId, metricId, null, useCache)
355                 .then(function (result) {
356                     if (result || result.shouldRefetch)
357                         self.refetchRuns(platformId, metricId);
358                     else
359                         self._didFetchRuns(result);
360                 }, this._handleFetchErrors.bind(this, platformId, metricId));
361             this.fetchAnalyticRanges();
362         }
363     }.observes('platformId', 'metricId').on('init'),
364     refetchRuns: function (platformId, metricId) {
365         if (!platformId)
366             platformId = this.get('platform').get('id');
367         if (!metricId)
368             metricId = this.get('metric').get('id');
369         Ember.assert('refetchRuns should be called only after platform and metric are resolved', platformId && metricId);
370
371         var useCache = false;
372         App.Manifest.fetchRunsWithPlatformAndMetric(this.get('store'), platformId, metricId, null, useCache)
373             .then(this._didFetchRuns.bind(this), this._handleFetchErrors.bind(this, platformId, metricId));
374     },
375     _didFetchRuns: function (result)
376     {
377         this.set('platform', result.platform);
378         this.set('metric', result.metric);
379         this._setNewChartData(result.data);
380     },
381     _setNewChartData: function (chartData)
382     {
383         var newChartData = {};
384         for (var property in chartData)
385             newChartData[property] = chartData[property];
386
387         var showOutlier = this.get('showOutlier');
388         newChartData.showOutlier(showOutlier);
389         this.set('chartData', newChartData);
390         this._updateMovingAverageAndEnvelope();
391
392         if (!this.get('anomalyDetectionStrategies').filterBy('enabled').length)
393             this._highlightPointsMarkedAsOutlier(newChartData);
394     },
395     _highlightPointsMarkedAsOutlier: function (newChartData)
396     {
397         var data = newChartData.current.series();
398         var items = {};
399         for (var i = 0; i < data.length; i++) {
400             if (data[i].measurement.markedOutlier())
401                 items[data[i].measurement.id()] = true;
402         }
403
404         this.set('highlightedItems', items);
405     },
406     _handleFetchErrors: function (platformId, metricId, result)
407     {
408         if (!result || typeof(result) === "string")
409             this.set('failure', 'Failed to fetch the JSON with an error: ' + result);
410         else if (!result.platform)
411             this.set('failure', 'Could not find the platform "' + platformId + '"');
412         else if (!result.metric)
413             this.set('failure', 'Could not find the metric "' + metricId + '"');
414         else
415             this.set('failure', 'An internal error');
416     },
417     fetchAnalyticRanges: function ()
418     {
419         var platformId = this.get('platformId');
420         var metricId = this.get('metricId');
421         var self = this;
422         this.get('store')
423             .find('analysisTask', {platform: platformId, metric: metricId})
424             .then(function (tasks) {
425                 self.set('analyticRanges', tasks.filter(function (task) { return task.get('startRun') && task.get('endRun'); }));
426             });
427     },
428     ranges: function ()
429     {
430         return this.getWithDefault('analyticRanges', []).concat(this.getWithDefault('testRangeCandidates', []));
431     }.property('analyticRanges', 'testRangeCandidates'),
432     _isValidId: function (id)
433     {
434         if (typeof(id) == "number")
435             return true;
436         if (typeof(id) == "string")
437             return !!id.match(/^[A-Za-z0-9_]+$/);
438         return false;
439     },
440     computeStatus: function (currentPoint, previousPoint)
441     {
442         var chartData = this.get('chartData');
443         var diffFromBaseline = this._relativeDifferentToLaterPointInTimeSeries(currentPoint, chartData.baseline);
444         var diffFromTarget = this._relativeDifferentToLaterPointInTimeSeries(currentPoint, chartData.target);
445
446         var label = '';
447         var className = '';
448         var formatter = d3.format('.3p');
449
450         var smallerIsBetter = chartData.smallerIsBetter;
451         if (diffFromBaseline !== undefined && diffFromBaseline > 0 == smallerIsBetter) {
452             label = formatter(Math.abs(diffFromBaseline)) + ' ' + (smallerIsBetter ? 'above' : 'below') + ' baseline';
453             className = 'worse';
454         } else if (diffFromTarget !== undefined && diffFromTarget < 0 == smallerIsBetter) {
455             label = formatter(Math.abs(diffFromTarget)) + ' ' + (smallerIsBetter ? 'below' : 'above') + ' target';
456             className = 'better';
457         } else if (diffFromTarget !== undefined)
458             label = formatter(Math.abs(diffFromTarget)) + ' until target';
459
460         var valueDelta = null;
461         var relativeDelta = null;
462         if (previousPoint) {
463             valueDelta = chartData.deltaFormatter(currentPoint.value - previousPoint.value);
464             relativeDelta = d3.format('+.2p')((currentPoint.value - previousPoint.value) / previousPoint.value);
465         }
466         return {
467             className: className,
468             label: label,
469             currentValue: chartData.formatter(currentPoint.value),
470             valueDelta: valueDelta,
471             relativeDelta: relativeDelta,
472         };
473     },
474     _relativeDifferentToLaterPointInTimeSeries: function (currentPoint, timeSeries)
475     {
476         if (!currentPoint || !timeSeries)
477             return undefined;
478
479         var referencePoint = timeSeries.findPointAfterTime(currentPoint.time);
480         if (!referencePoint)
481             return undefined;
482
483         return (currentPoint.value - referencePoint.value) / referencePoint.value;
484     },
485     latestStatus: function ()
486     {
487         var chartData = this.get('chartData');
488         if (!chartData || !chartData.current)
489             return null;
490
491         var lastPoint = chartData.current.lastPoint();
492         if (!lastPoint)
493             return null;
494
495         return this.computeStatus(lastPoint, chartData.current.previousPoint(lastPoint));
496     }.property('chartData'),
497     updateStatisticsTools: function ()
498     {
499         var movingAverageStrategies = Statistics.MovingAverageStrategies.map(this._cloneStrategy.bind(this));
500         this.set('movingAverageStrategies', [{label: 'None'}].concat(movingAverageStrategies));
501         this.set('chosenMovingAverageStrategy', this._configureStrategy(movingAverageStrategies, this.get('movingAverageConfig')));
502
503         var envelopingStrategies = Statistics.EnvelopingStrategies.map(this._cloneStrategy.bind(this));
504         this.set('envelopingStrategies', [{label: 'None'}].concat(envelopingStrategies));
505         this.set('chosenEnvelopingStrategy', this._configureStrategy(envelopingStrategies, this.get('envelopingConfig')));
506
507         var testRangeSelectionStrategies = Statistics.TestRangeSelectionStrategies.map(this._cloneStrategy.bind(this));
508         this.set('testRangeSelectionStrategies', [{label: 'None'}].concat(testRangeSelectionStrategies));
509         this.set('chosenTestRangeSelectionStrategy', this._configureStrategy(testRangeSelectionStrategies, this.get('testRangeSelectionConfig')));
510
511         var anomalyDetectionStrategies = Statistics.AnomalyDetectionStrategy.map(this._cloneStrategy.bind(this));
512         this.set('anomalyDetectionStrategies', anomalyDetectionStrategies);
513     }.on('init'),
514     _cloneStrategy: function (strategy)
515     {
516         var parameterList = (strategy.parameterList || []).map(function (param) { return Ember.Object.create(param); });
517         return Ember.Object.create({
518             id: strategy.id,
519             label: strategy.label,
520             isSegmentation: strategy.isSegmentation,
521             description: strategy.description,
522             parameterList: parameterList,
523             execute: strategy.execute,
524         });
525     },
526     _configureStrategy: function (strategies, config)
527     {
528         if (!config || !config[0])
529             return null;
530
531         var id = config[0];
532         var chosenStrategy = strategies.find(function (strategy) { return strategy.id == id });
533         if (!chosenStrategy)
534             return null;
535
536         if (chosenStrategy.parameterList) {
537             for (var i = 0; i < chosenStrategy.parameterList.length; i++)
538                 chosenStrategy.parameterList[i].value = parseFloat(config[i + 1]);
539         }
540
541         return chosenStrategy;
542     },
543     _updateMovingAverageAndEnvelope: function ()
544     {
545         var chartData = this.get('chartData');
546         if (!chartData)
547             return;
548
549         var movingAverageStrategy = this.get('chosenMovingAverageStrategy');
550         this._updateStrategyConfigIfNeeded(movingAverageStrategy, 'movingAverageConfig');
551
552         var envelopingStrategy = this.get('chosenEnvelopingStrategy');
553         this._updateStrategyConfigIfNeeded(envelopingStrategy, 'envelopingConfig');
554
555         var testRangeSelectionStrategy = this.get('chosenTestRangeSelectionStrategy');
556         this._updateStrategyConfigIfNeeded(testRangeSelectionStrategy, 'testRangeSelectionConfig');
557
558         var anomalyDetectionStrategies = this.get('anomalyDetectionStrategies').filterBy('enabled');
559         var result = this._computeMovingAverageAndOutliers(chartData, movingAverageStrategy, envelopingStrategy, testRangeSelectionStrategy, anomalyDetectionStrategies);
560         if (!result)
561             return;
562
563         chartData.movingAverage = result.movingAverage;
564         this.set('highlightedItems', result.anomalies);
565         var currentTimeSeriesData = chartData.current.series();
566         this.set('testRangeCandidates', result.testRangeCandidates.map(function (range) {
567             return Ember.Object.create({
568                 startRun: currentTimeSeriesData[range[0]].measurement.id(),
569                 endRun: currentTimeSeriesData[range[1]].measurement.id(),
570                 status: 'testingRange',
571             });
572         }));
573     },
574     _movingAverageOrEnvelopeStrategyDidChange: function () {
575         var chartData = this.get('chartData');
576         if (!chartData)
577             return;
578         this._setNewChartData(chartData);
579     }.observes('chosenMovingAverageStrategy', 'chosenMovingAverageStrategy.parameterList.@each.value',
580         'chosenEnvelopingStrategy', 'chosenEnvelopingStrategy.parameterList.@each.value',
581         'chosenTestRangeSelectionStrategy', 'chosenTestRangeSelectionStrategy.parameterList.@each.value',
582         'anomalyDetectionStrategies.@each.enabled'),
583     _computeMovingAverageAndOutliers: function (chartData, movingAverageStrategy, envelopingStrategy, testRangeSelectionStrategy, anomalyDetectionStrategies)
584     {
585         var currentTimeSeriesData = chartData.current.series();
586
587         var rawValues = chartData.current.rawValues();
588         var movingAverageIsSetByUser = movingAverageStrategy && movingAverageStrategy.execute;
589         if (!movingAverageIsSetByUser)
590             return null;
591
592         var movingAverageValues = Statistics.executeStrategy(movingAverageStrategy, rawValues);
593         if (!movingAverageValues)
594             return null;
595
596         var testRangeCandidates = [];
597         if (movingAverageStrategy && movingAverageStrategy.isSegmentation && testRangeSelectionStrategy && testRangeSelectionStrategy.execute)
598             testRangeCandidates = Statistics.executeStrategy(testRangeSelectionStrategy, rawValues, [movingAverageValues]);
599
600         if (envelopingStrategy && envelopingStrategy.execute) {
601             var envelopeDelta = Statistics.executeStrategy(envelopingStrategy, rawValues, [movingAverageValues]);
602             var anomalies = {};
603             if (anomalyDetectionStrategies.length) {
604                 var isAnomalyArray = new Array(currentTimeSeriesData.length);
605                 for (var strategy of anomalyDetectionStrategies) {
606                     var anomalyLengths = Statistics.executeStrategy(strategy, rawValues, [movingAverageValues, envelopeDelta]);
607                     for (var i = 0; i < currentTimeSeriesData.length; i++)
608                         isAnomalyArray[i] = isAnomalyArray[i] || anomalyLengths[i];
609                 }
610                 for (var i = 0; i < isAnomalyArray.length; i++) {
611                     if (!isAnomalyArray[i])
612                         continue;
613                     anomalies[currentTimeSeriesData[i].measurement.id()] = true;
614                     while (isAnomalyArray[i] && i < isAnomalyArray.length)
615                         ++i;
616                 }
617             }
618         }
619
620         var movingAverageTimeSeries = null;
621         if (movingAverageIsSetByUser) {
622             movingAverageTimeSeries = new TimeSeries(currentTimeSeriesData.map(function (point, index) {
623                 var value = movingAverageValues[index];
624                 return {
625                     measurement: point.measurement,
626                     time: point.time,
627                     value: value,
628                     interval: envelopeDelta !== null ? [value - envelopeDelta, value + envelopeDelta] : null,
629                 }
630             }));
631         }
632
633         return {
634             movingAverage: movingAverageTimeSeries,
635             anomalies: anomalies,
636             testRangeCandidates: testRangeCandidates,
637         };
638     },
639     _updateStrategyConfigIfNeeded: function (strategy, configName)
640     {
641         var config = null;
642         if (strategy && strategy.execute)
643             config = [strategy.id].concat((strategy.parameterList || []).map(function (param) { return param.value; }));
644
645         if (JSON.stringify(config) != JSON.stringify(this.get(configName)))
646             this.set(configName, config);
647     },
648     _updateDetails: function ()
649     {
650         var selectedPoints = this.get('selectedPoints');
651         var currentPoint = this.get('hoveredOrSelectedItem');
652         if (!selectedPoints && !currentPoint) {
653             this.set('details', null);
654             return;
655         }
656
657         var currentMeasurement;
658         var previousPoint;
659         if (!selectedPoints)
660             previousPoint = currentPoint.series.previousPoint(currentPoint);
661         else {
662             currentPoint = selectedPoints[selectedPoints.length - 1];
663             previousPoint = selectedPoints[0];
664         }
665         var currentMeasurement = currentPoint.measurement;
666         var oldMeasurement = previousPoint ? previousPoint.measurement : null;
667
668         var formattedRevisions = currentMeasurement.formattedRevisions(oldMeasurement);
669         var revisions = App.Manifest.get('repositories')
670             .filter(function (repository) { return formattedRevisions[repository.get('id')]; })
671             .map(function (repository) {
672             var revision = Ember.Object.create(formattedRevisions[repository.get('id')]);
673             revision['url'] = revision.previousRevision
674                 ? repository.urlForRevisionRange(revision.previousRevision, revision.currentRevision)
675                 : repository.urlForRevision(revision.currentRevision);
676             revision['name'] = repository.get('name');
677             revision['repository'] = repository;
678             return revision; 
679         });
680
681         var buildNumber = null;
682         var buildURL = null;
683         if (!selectedPoints) {
684             buildNumber = currentMeasurement.buildNumber();
685             var builder = App.Manifest.builder(currentMeasurement.builderId());
686             if (builder)
687                 buildURL = builder.urlFromBuildNumber(buildNumber);
688         }
689
690         this.set('details', Ember.Object.create({
691             status: this.computeStatus(currentPoint, previousPoint),
692             buildNumber: buildNumber,
693             buildURL: buildURL,
694             buildTime: currentMeasurement.formattedBuildTime(),
695             revisions: revisions,
696         }));
697     }.observes('hoveredOrSelectedItem', 'selectedPoints'),
698 });
699
700 App.encodePrettifiedJSON = function (plain)
701 {
702     function numberIfPossible(string) {
703         return string == parseInt(string) ? parseInt(string) : string;
704     }
705
706     function recursivelyConvertNumberIfPossible(input) {
707         if (input instanceof Array) {
708             return input.map(recursivelyConvertNumberIfPossible);
709         }
710         return numberIfPossible(input);
711     }
712
713     return JSON.stringify(recursivelyConvertNumberIfPossible(plain))
714         .replace(/\[/g, '(').replace(/\]/g, ')').replace(/\,/g, '-');
715 }
716
717 App.decodePrettifiedJSON = function (encoded)
718 {
719     var parsed = encoded.replace(/\(/g, '[').replace(/\)/g, ']').replace(/\-/g, ',');
720     try {
721         return JSON.parse(parsed);
722     } catch (exception) {
723         return null;
724     }
725 }
726
727 App.ChartsController = Ember.Controller.extend({
728     queryParams: ['paneList', 'zoom', 'since'],
729     needs: ['pane'],
730     _currentEncodedPaneList: null,
731     panes: [],
732     platforms: null,
733     sharedZoom: null,
734     startTime: null,
735     present: Date.now(),
736     defaultSince: Date.now() - 7 * 24 * 3600 * 1000,
737
738     addPane: function (pane)
739     {
740         this.panes.unshiftObject(pane);
741     },
742
743     removePane: function (pane)
744     {
745         this.panes.removeObject(pane);
746     },
747
748     refreshPanes: function()
749     {
750         var paneList = this.get('paneList');
751         if (paneList === this._currentEncodedPaneList)
752             return;
753
754         var panes = this._parsePaneList(paneList || '[]');
755         if (!panes) {
756             console.log('Failed to parse', jsonPaneList, exception);
757             return;
758         }
759         this.set('panes', panes);
760         this._currentEncodedPaneList = paneList;
761     }.observes('paneList').on('init'),
762
763     refreshZoom: function()
764     {
765         var zoom = this.get('zoom');
766         if (!zoom) {
767             this.set('sharedZoom', null);
768             return;
769         }
770
771         zoom = zoom.split('-');
772         var selection = new Array(2);
773         try {
774             selection[0] = new Date(parseFloat(zoom[0]));
775             selection[1] = new Date(parseFloat(zoom[1]));
776         } catch (error) {
777             console.log('Failed to parse the zoom', zoom);
778         }
779         this.set('sharedZoom', selection);
780
781         var startTime = this.get('startTime');
782         if (startTime && startTime > selection[0])
783             this.set('startTime', selection[0]);
784
785     }.observes('zoom').on('init'),
786
787     _startTimeChanged: function () {
788         this.set('sharedDomain', [this.get('startTime'), this.get('present')]);
789         this._scheduleQueryStringUpdate();
790     }.observes('startTime'),
791
792     _sinceChanged: function () {
793         var since = parseInt(this.get('since'));
794         if (isNaN(since))
795             since = this.defaultSince;
796         this.set('startTime', new Date(since));
797     }.observes('since').on('init'),
798
799     _parsePaneList: function (encodedPaneList)
800     {
801         var parsedPaneList = App.decodePrettifiedJSON(encodedPaneList);
802         if (!parsedPaneList)
803             return null;
804
805         // FIXME: Don't re-create all panes.
806         var self = this;
807         return parsedPaneList.map(function (paneInfo) {
808             var timeRange = null;
809             var selectedItem = null;
810             if (paneInfo[2] instanceof Array) {
811                 var timeRange = paneInfo[2];
812                 try {
813                     timeRange = [new Date(timeRange[0]), new Date(timeRange[1])];
814                 } catch (error) {
815                     console.log("Failed to parse the time range:", timeRange, error);
816                 }
817             } else
818                 selectedItem = paneInfo[2];
819
820             return App.Pane.create({
821                 store: self.store,
822                 info: paneInfo,
823                 platformId: paneInfo[0],
824                 metricId: paneInfo[1],
825                 selectedItem: selectedItem,
826                 timeRange: timeRange,
827                 showFullYAxis: paneInfo[3],
828                 movingAverageConfig: paneInfo[4],
829                 envelopingConfig: paneInfo[5],
830                 testRangeSelectionConfig: paneInfo[6],
831             });
832         });
833     },
834
835     _serializePaneList: function (panes)
836     {
837         if (!panes.length)
838             return undefined;
839         var self = this;
840         return App.encodePrettifiedJSON(panes.map(function (pane) {
841             return [
842                 pane.get('platformId'),
843                 pane.get('metricId'),
844                 pane.get('timeRange') ? pane.get('timeRange').map(function (date) { return date.getTime() }) : pane.get('selectedItem'),
845                 pane.get('showFullYAxis'),
846                 pane.get('movingAverageConfig'),
847                 pane.get('envelopingConfig'),
848                 pane.get('testRangeSelectionConfig'),
849             ];
850         }));
851     },
852
853     _scheduleQueryStringUpdate: function ()
854     {
855         Ember.run.debounce(this, '_updateQueryString', 1000);
856     }.observes('sharedZoom', 'panes.@each.platform', 'panes.@each.metric', 'panes.@each.selectedItem', 'panes.@each.timeRange',
857         'panes.@each.showFullYAxis', 'panes.@each.movingAverageConfig', 'panes.@each.envelopingConfig', 'panes.@each.testRangeSelectionConfig'),
858
859     _updateQueryString: function ()
860     {
861         this._currentEncodedPaneList = this._serializePaneList(this.get('panes'));
862         this.set('paneList', this._currentEncodedPaneList);
863
864         var zoom = undefined;
865         var sharedZoom = this.get('sharedZoom');
866         if (sharedZoom && !App.domainsAreEqual(sharedZoom, this.get('sharedDomain')))
867             zoom = +sharedZoom[0] + '-' + +sharedZoom[1];
868         this.set('zoom', zoom);
869
870         if (this.get('startTime') - this.defaultSince)
871             this.set('since', this.get('startTime') - 0);
872     },
873
874     actions: {
875         addPaneByMetricAndPlatform: function (param)
876         {
877             this.addPane(App.Pane.create({
878                 store: this.store,
879                 platformId: param.platform.get('id'),
880                 metricId: param.metric.get('id'),
881                 showingDetails: false
882             }));
883         },
884         addAlternativePanes: function (pane, platform, metrics)
885         {
886             var panes = this.panes;
887             var store = this.store;
888             var startingIndex = panes.indexOf(pane) + 1;
889             metrics.forEach(function (metric, index) {
890                 panes.insertAt(startingIndex + index, App.Pane.create({
891                     store: store,
892                     platformId: platform.get('id'),
893                     metricId: metric.get('id'),
894                     showingDetails: false
895                 }));
896             })
897         }
898     },
899
900     init: function ()
901     {
902         this._super();
903         var self = this;
904         App.buildPopup(this.store, 'addPaneByMetricAndPlatform').then(function (platforms) {
905             self.set('platforms', platforms);
906         });
907     },
908 });
909
910 App.buildPopup = function(store, action, position)
911 {
912     return App.Manifest.fetch(store).then(function () {
913         return App.Manifest.get('platforms').sortBy('label').map(function (platform) {
914             return App.PlatformProxyForPopup.create({content: platform,
915                 action: action, position: position});
916         });
917     });
918 }
919
920 App.PlatformProxyForPopup = Ember.ObjectProxy.extend({
921     children: function ()
922     {
923         var platform = this.content;
924         var containsTest = this.content.containsTest.bind(this.content);
925         var action = this.get('action');
926         var position = this.get('position');
927         return App.Manifest.get('topLevelTests')
928             .filter(containsTest)
929             .map(function (test) {
930                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
931             });
932     }.property('App.Manifest.topLevelTests'),
933 });
934
935 App.TestProxyForPopup = Ember.ObjectProxy.extend({
936     platform: null,
937     children: function ()
938     {
939         this._updateChildren();
940         return this._children;
941     }.property('childTests', 'metrics'),
942     actionName: function ()
943     {
944         this._updateChildren();
945         return this._actionName;
946     }.property('childTests', 'metrics'),
947     actionArgument: function ()
948     {
949         this._updateChildren();
950         return this._actionArgument;
951     }.property('childTests', 'metrics'),
952     _updateChildren: function ()
953     {
954         var platform = this.get('platform');
955         var action = this.get('action');
956         var position = this.get('position');
957
958         var childTests = this.get('childTests')
959             .filter(function (test) { return platform.containsTest(test); })
960             .map(function (test) {
961                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
962             });
963
964         var metrics = this.get('metrics')
965             .filter(function (metric) { return platform.containsMetric(metric); })
966             .map(function (metric) {
967                 var aggregator = metric.get('aggregator');
968                 return {
969                     actionName: action,
970                     actionArgument: {platform: platform, metric: metric, position:position},
971                     label: metric.get('label')
972                 };
973             });
974
975         if (childTests.length && metrics.length)
976             metrics.push({isSeparator: true});
977         else if (metrics.length == 1) {
978             this._actionName = action;
979             this._actionArgument = metrics[0].actionArgument;
980             return;
981         }
982
983         this._actionName = null;
984         this._actionArgument = null;
985         this._children = metrics.concat(childTests);
986     },
987 });
988
989 App.domainsAreEqual = function (domain1, domain2) {
990     return (!domain1 && !domain2) || (domain1 && domain2 && !(domain1[0] - domain2[0]) && !(domain1[1] - domain2[1]));
991 }
992
993 App.PaneController = Ember.ObjectController.extend({
994     needs: ['charts'],
995     sharedTime: Ember.computed.alias('parentController.sharedTime'),
996     sharedSelection: Ember.computed.alias('parentController.sharedSelection'),
997     selection: null,
998     actions: {
999         toggleDetails: function()
1000         {
1001             this.toggleProperty('showingDetails');
1002         },
1003         close: function ()
1004         {
1005             this.parentController.removePane(this.get('model'));
1006         },
1007         toggleBugsPane: function ()
1008         {
1009             if (this.toggleProperty('showingAnalysisPane')) {
1010                 this.set('showingSearchPane', false);
1011                 this.set('showingStatPane', false);
1012             }
1013         },
1014         toggleShowOutlier: function ()
1015         {
1016             var pane = this.get('model');
1017             pane.toggleProperty('showOutlier');
1018             var chartData = pane.get('chartData');
1019             if (!chartData)
1020                 return;
1021             pane._setNewChartData(chartData);
1022         },
1023         createAnalysisTask: function ()
1024         {
1025             var name = this.get('newAnalysisTaskName');
1026             var points = this.get('selectedPoints');
1027             Ember.assert('The analysis name should not be empty', name);
1028             Ember.assert('There should be at least two points in the range', points && points.length >= 2);
1029
1030             var newWindow = window.open();
1031             var self = this;
1032             App.AnalysisTask.create(name, points[0].measurement, points[points.length - 1].measurement).then(function (data) {
1033                 // FIXME: Update the UI to show the new analysis task.
1034                 var url = App.Router.router.generate('analysisTask', data['taskId']);
1035                 newWindow.location.href = '#' + url;
1036                 self.get('model').fetchAnalyticRanges();
1037             }, function (error) {
1038                 newWindow.close();
1039                 if (error === 'DuplicateAnalysisTask') {
1040                     // FIXME: Duplicate this error more gracefully.
1041                 }
1042                 alert(error);
1043             });
1044         },
1045         toggleSearchPane: function ()
1046         {
1047             if (!App.Manifest.repositoriesWithReportedCommits)
1048                 return;
1049             var model = this.get('model');
1050             if (!model.get('commitSearchRepository'))
1051                 model.set('commitSearchRepository', App.Manifest.repositoriesWithReportedCommits[0]);
1052             if (this.toggleProperty('showingSearchPane')) {
1053                 this.set('showingAnalysisPane', false);
1054                 this.set('showingStatPane', false);
1055             }
1056         },
1057         searchCommit: function () {
1058             var model = this.get('model');
1059             model.searchCommit(model.get('commitSearchRepository'), model.get('commitSearchKeyword'));                
1060         },
1061         toggleStatPane: function ()
1062         {
1063             if (this.toggleProperty('showingStatPane')) {
1064                 this.set('showingSearchPane', false);
1065                 this.set('showingAnalysisPane', false);
1066             }
1067         },
1068         zoomed: function (selection)
1069         {
1070             this.set('mainPlotDomain', selection ? selection : this.get('overviewDomain'));
1071             if (selection)
1072                 this.set('overviewSelection', selection);
1073             Ember.run.debounce(this, 'propagateZoom', 100);
1074         },
1075     },
1076     _overviewSelectionChanged: function ()
1077     {
1078         var overviewSelection = this.get('overviewSelection');
1079         if (App.domainsAreEqual(overviewSelection, this.get('mainPlotDomain')))
1080             return;
1081         this.set('mainPlotDomain', overviewSelection || this.get('overviewDomain'));
1082         Ember.run.debounce(this, 'propagateZoom', 100);
1083     }.observes('overviewSelection'),
1084     _sharedDomainChanged: function ()
1085     {
1086         var newDomain = this.get('parentController').get('sharedDomain');
1087         if (App.domainsAreEqual(newDomain, this.get('overviewDomain')))
1088             return;
1089         this.set('overviewDomain', newDomain);
1090         if (!this.get('overviewSelection'))
1091             this.set('mainPlotDomain', newDomain);
1092     }.observes('parentController.sharedDomain').on('init'),
1093     propagateZoom: function ()
1094     {
1095         this.get('parentController').set('sharedZoom', this.get('mainPlotDomain'));
1096     },
1097     _sharedZoomChanged: function ()
1098     {
1099         var newSelection = this.get('parentController').get('sharedZoom');
1100         if (App.domainsAreEqual(newSelection, this.get('mainPlotDomain')))
1101             return;
1102         this.set('mainPlotDomain', newSelection || this.get('overviewDomain'));
1103         this.set('overviewSelection', newSelection);
1104     }.observes('parentController.sharedZoom').on('init'),
1105     _updateCanAnalyze: function ()
1106     {
1107         var pane = this.get('model');
1108         var points = pane.get('selectedPoints');
1109         this.set('cannotAnalyze', !this.get('newAnalysisTaskName') || !points || points.length < 2);
1110         this.set('cannotMarkOutlier', !!points || !this.get('selectedItem'));
1111
1112         var selectedMeasurement = this.selectedMeasurement();
1113         this.set('selectedItemIsMarkedOutlier', selectedMeasurement && selectedMeasurement.markedOutlier());
1114
1115     }.observes('newAnalysisTaskName', 'model.selectedPoints', 'model.selectedItem').on('init'),
1116     selectedMeasurement: function () {
1117         var chartData = this.get('model').get('chartData');
1118         var selectedItem = this.get('selectedItem');
1119         if (!chartData || !selectedItem)
1120             return null;
1121         var point = chartData.current.findPointByMeasurementId(selectedItem);
1122         Ember.assert('selectedItem should always be in the current chart data', point);
1123         return point.measurement;
1124     },
1125     showOutlierTitle: function ()
1126     {
1127         return this.get('showOutlier') ? 'Hide outliers' : 'Show outliers';
1128     }.property('showOutlier'),
1129     _selectedItemIsMarkedOutlierDidChange: function ()
1130     {
1131         var selectedMeasurement = this.selectedMeasurement();
1132         if (!selectedMeasurement)
1133             return;
1134         var selectedItemIsMarkedOutlier = this.get('selectedItemIsMarkedOutlier');
1135         if (selectedMeasurement.markedOutlier() == selectedItemIsMarkedOutlier)
1136             return;
1137         var pane = this.get('model');
1138         selectedMeasurement.setMarkedOutlier(!!selectedItemIsMarkedOutlier).then(function () {
1139             alert(selectedItemIsMarkedOutlier ? 'Marked the point as an outlier' : 'The point is no longer marked as an outlier');
1140             pane.refetchRuns();
1141         }, function (error) {
1142             alert('Failed to update the status:' + error);
1143         });
1144     }.observes('selectedItemIsMarkedOutlier'),
1145     alternativePanes: function ()
1146     {
1147         var pane = this.get('model');
1148         var metric = pane.get('metric');
1149         var currentPlatform = pane.get('platform');
1150         var platforms = App.Manifest.get('platforms');
1151         if (!platforms || !metric)
1152             return;
1153
1154         var exitingPlatforms = {};
1155         this.get('parentController').get('panes').forEach(function (pane) {
1156             if (pane.get('metricId') == metric.get('id'))
1157                 exitingPlatforms[pane.get('platformId')] = true;
1158         });
1159
1160         var alternativePanes = platforms.filter(function (platform) {
1161             return !exitingPlatforms[platform.get('id')] && platform.containsMetric(metric);
1162         }).map(function (platform) {
1163             return {
1164                 pane: pane,
1165                 platform: platform,
1166                 metrics: [metric],
1167                 label: platform.get('label')
1168             };
1169         });
1170
1171         var childMetrics = metric.get('childMetrics');
1172         if (childMetrics && childMetrics.length) {
1173             alternativePanes.push({
1174                 pane: pane,
1175                 platform: currentPlatform,
1176                 metrics: childMetrics,
1177                 label: 'Breakdown',
1178             });
1179         }
1180
1181         return alternativePanes;
1182     }.property('model.metric', 'model.platform', 'App.Manifest.platforms',
1183         'parentController.panes.@each.platformId', 'parentController.panes.@each.metricId'),
1184 });
1185
1186 App.AnalysisRoute = Ember.Route.extend({
1187     model: function () {
1188         return this.store.findAll('analysisTask').then(function (tasks) {
1189             return Ember.Object.create({'tasks': tasks.sortBy('createdAt').toArray().reverse()});
1190         });
1191     },
1192 });
1193
1194 App.AnalysisTaskRoute = Ember.Route.extend({
1195     model: function (param)
1196     {
1197         return this.store.find('analysisTask', param.taskId);
1198     },
1199 });
1200
1201 App.AnalysisTaskController = Ember.Controller.extend({
1202     label: Ember.computed.alias('model.name'),
1203     platform: Ember.computed.alias('model.platform'),
1204     metric: Ember.computed.alias('model.metric'),
1205     details: Ember.computed.alias('pane.details'),
1206     roots: [],
1207     bugTrackers: [],
1208     possibleRepetitionCounts: [1, 2, 3, 4, 5, 6],
1209     analysisResultOptions: [
1210         {label: 'Still in investigation', result: null},
1211         {label: 'Inconclusive', result: 'inconclusive', needed: true},
1212         {label: 'Definite progression', result: 'progression', needed: true},
1213         {label: 'Definite regression', result: 'regression', needed: true},
1214         {label: 'No change', result: 'unchanged', needsFeedback: true},
1215     ],
1216     shouldNotHaveBeenCreated: false,
1217     needsFeedback: function ()
1218     {
1219         var chosen = this.get('chosenAnalysisResult');
1220         return chosen && chosen.needsFeedback;
1221     }.property('chosenAnalysisResult'),
1222     _updateChosenAnalysisResult: function ()
1223     {
1224         var analysisTask = this.get('model');
1225         if (!analysisTask)
1226             return;
1227         var currentResult = analysisTask.get('result');
1228         for (var option of this.analysisResultOptions) {
1229             if (option.result == currentResult) {
1230                 this.set('chosenAnalysisResult', option);
1231                 break;                
1232             }
1233         }
1234     }.observes('model'),
1235     _taskUpdated: function ()
1236     {
1237         var model = this.get('model');
1238         if (!model)
1239             return;
1240
1241         App.Manifest.fetch(this.store).then(this._fetchedManifest.bind(this));
1242         this.set('pane', App.Pane.create({
1243             store: this.store,
1244             platformId: model.get('platform').get('id'),
1245             metricId: model.get('metric').get('id'),
1246         }));
1247
1248         var self = this;
1249         model.get('testGroups').then(function (groups) {
1250             self.set('testGroupPanes', groups.map(function (group) { return App.TestGroupPane.create({content: group}); }));
1251         });
1252     }.observes('model', 'model.testGroups').on('init'),
1253     _fetchedManifest: function ()
1254     {
1255         var trackerIdToBugNumber = {};
1256         this.get('model').get('bugs').forEach(function (bug) {
1257             trackerIdToBugNumber[bug.get('bugTracker').get('id')] = bug.get('number');
1258         });
1259
1260         this.set('bugTrackers', App.Manifest.get('bugTrackers').map(function (bugTracker) {
1261             var bugNumber = trackerIdToBugNumber[bugTracker.get('id')];
1262             return Ember.ObjectProxy.create({
1263                 elementId: 'bug-' + bugTracker.get('id'),
1264                 content: bugTracker,
1265                 bugNumber: bugNumber,
1266                 bugUrl: bugTracker.urlFromBugNumber(bugNumber),
1267                 editedBugNumber: bugNumber,
1268             });
1269         }));
1270     },
1271     _chartDataChanged: function ()
1272     {
1273         var pane = this.get('pane');
1274         if (!pane)
1275             return;
1276
1277         var chartData = pane.get('chartData');
1278         if (!chartData)
1279             return null;
1280
1281         var currentTimeSeries = chartData.current;
1282         if (!currentTimeSeries)
1283             return null; // FIXME: Report an error.
1284
1285         var start = currentTimeSeries.findPointByMeasurementId(this.get('model').get('startRun'));
1286         var end = currentTimeSeries.findPointByMeasurementId(this.get('model').get('endRun'));
1287         if (!start || !end)
1288             return null; // FIXME: Report an error.
1289
1290         var highlightedItems = {};
1291         highlightedItems[start.measurement.id()] = true;
1292         highlightedItems[end.measurement.id()] = true;
1293
1294         var formatedPoints = currentTimeSeries.seriesBetweenPoints(start, end).map(function (point, index) {
1295             return {
1296                 id: point.measurement.id(),
1297                 measurement: point.measurement,
1298                 label: 'Point ' + (index + 1),
1299                 value: chartData.formatter(point.value),
1300             };
1301         });
1302
1303         var margin = (end.time - start.time) * 0.1;
1304         this.set('highlightedItems', highlightedItems);
1305         this.set('overviewEndPoints', [start, end]);
1306         this.set('analysisPoints', formatedPoints);
1307
1308         var overviewDomain = [start.time - margin, +end.time + margin];
1309
1310         var testGroupPanes = this.get('testGroupPanes');
1311         if (testGroupPanes) {
1312             testGroupPanes.setEach('overviewPane', pane);
1313             testGroupPanes.setEach('overviewDomain', overviewDomain);
1314         }
1315
1316         this.set('overviewDomain', overviewDomain);
1317     }.observes('pane.chartData'),
1318     updateRootConfigurations: function ()
1319     {
1320         var analysisPoints = this.get('analysisPoints');
1321         if (!analysisPoints)
1322             return;
1323         var repositoryToRevisions = {};
1324         analysisPoints.forEach(function (point, pointIndex) {
1325             var revisions = point.measurement.formattedRevisions();
1326             for (var repositoryId in revisions) {
1327                 if (!repositoryToRevisions[repositoryId])
1328                     repositoryToRevisions[repositoryId] = {commits: null, revisions: []};
1329                 var revision = revisions[repositoryId];
1330                 repositoryToRevisions[repositoryId].revisions[pointIndex] = {
1331                     label: point.label + ': ' + revision.label,
1332                     value: revision.currentRevision,
1333                 };
1334             }
1335         });
1336
1337         var commitsPromises = [];
1338         var repositoryToIndex = {};
1339         for (var repositoryId in repositoryToRevisions) {
1340             var revisions = repositoryToRevisions[repositoryId].revisions;
1341             repositoryToIndex[repositoryId] = commitsPromises.length;
1342             commitsPromises.push(CommitLogs.fetchCommits(repositoryId, revisions[0].value, revisions[revisions.length - 1].value));
1343         }
1344
1345         var self = this;
1346         this.get('model').get('triggerable').then(function (triggerable) {
1347             if (!triggerable)
1348                 return;
1349             Ember.RSVP.Promise.all(commitsPromises).then(function (commitsList) {
1350                 self.set('configurations', ['A', 'B']);
1351                 self.set('rootConfigurations', triggerable.get('acceptedRepositories').map(function (repository) {
1352                     return self._createConfiguration(repository, commitsList[repositoryToIndex[repository.get('id')]], analysisPoints);
1353                 }));
1354             });
1355         });
1356     }.observes('analysisPoints'),
1357     _createConfiguration: function(repository, commits, analysisPoints) {
1358         var repositoryId = repository.get('id');
1359
1360         var options = [{label: 'None'}];
1361         var revisionToPoints = {};
1362         analysisPoints.forEach(function (point, pointIndex) {
1363             var revision = point.measurement.revisionForRepository(repositoryId);
1364             if (!revision)
1365                 return;
1366             if (!revisionToPoints[revision])
1367                 revisionToPoints[revision] = [];
1368             revisionToPoints[revision].push(pointIndex);
1369         });
1370
1371         if (!commits || !commits.length) {
1372             commits = [];
1373             for (var revision in revisionToPoints)
1374                 commits.push({revision: revision});
1375         }
1376
1377         for (var commit of commits) {
1378             var revision = commit.revision;
1379             var label = Measurement.formatRevisionRange(revision).label;
1380             var points = revisionToPoints[revision];
1381             if (points) {
1382                 var serializedPoints = this._serializeNumbersSkippingConsecutiveEntries(revisionToPoints[revision]);
1383                 label += ' ' + ['(', points.length > 1 ? 'points' : 'point', serializedPoints, ')'].join(' ');
1384             }
1385             options.push({value: revision, label: label});
1386         }
1387
1388         return Ember.Object.create({
1389             repository: repository,
1390             name: repository.get('name'),
1391             sets: [
1392                 Ember.Object.create({name: 'A[' + repositoryId + ']',
1393                     options: options,
1394                     selection: options[1]}),
1395                 Ember.Object.create({name: 'B[' + repositoryId + ']',
1396                     options: options,
1397                     selection: options[options.length - 1]}),
1398             ]});
1399     },
1400     _serializeNumbersSkippingConsecutiveEntries: function (numbers) {
1401         var result = numbers[0];
1402         for (var i = 1; i < numbers.length; i++) {
1403             if (numbers[i - 1] + 1 == numbers[i]) {
1404                 while (numbers[i] + 1 == numbers[i + 1])
1405                     i++;
1406                 result += '-' + numbers[i];
1407                 continue;
1408             }
1409             result += ', ' + numbers[i]
1410         }
1411         return result;
1412     },
1413     actions: {
1414         addBug: function (bugTracker, bugNumber)
1415         {
1416             var model = this.get('model');
1417             if (!bugTracker)
1418                 bugTracker = this.get('bugTrackers').objectAt(0);
1419             var bug = {task: this.get('model'), bugTracker: bugTracker.get('content'), number: bugNumber};
1420             this.store.createRecord('bug', bug).save().then(function () {
1421                 alert('Associated the ' + bugTracker.get('name') + ' ' + bugNumber + ' with this analysis.');
1422             }, function (error) {
1423                 alert('Failed to associate the bug: ' + error);
1424             });
1425         },
1426         deleteBug: function (bug)
1427         {
1428             bug.destroyRecord().then(function () {
1429                 alert('Successfully deassociated the bug.');
1430             }, function (error) {
1431                 alert('Failed to disassociate the bug: ' + error);
1432             });
1433         },
1434         saveStatus: function ()
1435         {
1436             var chosenResult = this.get('chosenAnalysisResult');
1437             var analysisTask = this.get('model');
1438             analysisTask.set('result', chosenResult.result);
1439             if (chosenResult.needed)
1440                 analysisTask.set('needed', true);
1441             else if (chosenResult.needsFeedback && this.get('notNeeded'))
1442                 analysisTask.set('needed', false);
1443             else
1444                 analysisTask.set('needed', null);
1445
1446             analysisTask.saveStatus().then(function () {
1447                 alert('Saved the status');
1448             }, function (error) {
1449                 alert('Failed to save the status: ' + error);
1450             });
1451         },
1452         createTestGroup: function (name, repetitionCount)
1453         {
1454             var analysisTask = this.get('model');
1455             if (analysisTask.get('testGroups').isAny('name', name)) {
1456                 alert('Cannot create two test groups of the same name.');
1457                 return;
1458             }
1459
1460             var roots = {};
1461             var rootConfigurations = this.get('rootConfigurations').toArray();
1462             for (var root of rootConfigurations) {
1463                 var sets = root.get('sets');
1464                 var hasSelection = function (item) { return item.get('selection') && item.get('selection').value; };
1465                 if (!sets.any(hasSelection))
1466                     continue;
1467                 if (!sets.every(hasSelection)) {
1468                     alert('Only some configuration specifies ' + root.get('name'));
1469                     return;
1470                 }
1471                 roots[root.get('name')] = sets.map(function (item) { return item.get('selection').value; });                
1472             }
1473
1474             App.TestGroup.create(analysisTask, name, roots, repetitionCount).then(function () {
1475             }, function (error) {
1476                 alert('Failed to create a new test group:' + error);
1477             });
1478         },
1479         toggleShowRequestList: function (configuration)
1480         {
1481             configuration.toggleProperty('showRequestList');
1482         }
1483     },
1484     _updateRootsBySelectedPoints: function ()
1485     {
1486         var rootConfigurations = this.get('rootConfigurations');
1487         var pane = this.get('pane');
1488         if (!rootConfigurations || !pane)
1489             return;
1490
1491         var rootSetPoints;
1492         var selectedPoints = pane.get('selectedPoints');
1493         if (selectedPoints && selectedPoints.length >= 2)
1494             rootSetPoints = [selectedPoints[0], selectedPoints[selectedPoints.length - 1]];
1495         else
1496             rootSetPoints = this.get('overviewEndPoints');
1497         if (!rootSetPoints)
1498             return;
1499
1500         rootConfigurations.forEach(function (root) {
1501             root.get('sets').forEach(function (set, setIndex) {
1502                 if (setIndex >= rootSetPoints.length)
1503                     return;
1504                 var targetRevision = rootSetPoints[setIndex].measurement.revisionForRepository(root.get('repository').get('id'));
1505                 var selectedOption;
1506                 if (targetRevision)
1507                     selectedOption = set.get('options').find(function (option) { return option.value == targetRevision; });
1508                 set.set('selection', selectedOption || set.get('options')[0]);
1509             });
1510         });
1511
1512     }.observes('pane.selectedPoints'),
1513 });
1514
1515 App.TestGroupPane = Ember.ObjectProxy.extend({
1516     _populate: function ()
1517     {
1518         var buildRequests = this.get('buildRequests');
1519         var testResults = this.get('testResults');
1520         if (!buildRequests || !testResults)
1521             return [];
1522
1523         var repositories = this._computeRepositoryList();
1524         this.set('repositories', repositories);
1525
1526         var requestsByRooSet = this._groupRequestsByConfigurations(buildRequests);
1527
1528         var configurations = [];
1529         var index = 0;
1530         var range = {min: Infinity, max: -Infinity};
1531         for (var rootSetId in requestsByRooSet) {
1532             var configLetter = String.fromCharCode('A'.charCodeAt(0) + index++);
1533             configurations.push(this._createConfigurationSummary(requestsByRooSet[rootSetId], configLetter, range));
1534         }
1535
1536         var margin = 0.1 * (range.max - range.min);
1537         range.max += margin;
1538         range.min -= margin;
1539
1540         this.set('configurations', configurations);
1541
1542         var probabilityFormatter = d3.format('.2p');
1543         var comparisons = [];
1544         for (var i = 0; i < configurations.length - 1; i++) {
1545             var summary1 = configurations[i].summary;
1546             for (var j = i + 1; j < configurations.length; j++) {
1547                 var summary2 = configurations[j].summary;
1548
1549                 var valueDelta = testResults.deltaFormatter(summary2.value - summary1.value);
1550                 var relativeDelta = d3.format('+.2p')((summary2.value - summary1.value) / summary1.value);
1551
1552                 var stat = this._computeStatisticalSignificance(summary1.measuredValues, summary2.measuredValues);
1553                 comparisons.push({
1554                     label: summary1.configLetter + ' / ' + summary2.configLetter,
1555                     difference: isNaN(summary1.value) || isNaN(summary2.value) ? 'N/A' : valueDelta + ' (' + relativeDelta + ') ',
1556                     result: stat,
1557                 });
1558             }
1559         }
1560         this.set('comparisons', comparisons);
1561     }.observes('testResults', 'buildRequests'),
1562     _computeStatisticalSignificance: function (values1, values2)
1563     {
1564         var tFormatter = d3.format('.3g');
1565         var probabilityFormatter = d3.format('.2p');
1566         var statistics = Statistics.probabilityRangeForWelchsT(values1, values2);
1567         if (isNaN(statistics.t) || isNaN(statistics.degreesOfFreedom))
1568             return 'N/A';
1569
1570         var details = ' (t=' + tFormatter(statistics.t) + ' df=' + tFormatter(statistics.degreesOfFreedom) + ')';
1571
1572         if (!statistics.range[0])
1573             return 'Not significant' + details;
1574
1575         var lowerLimit = probabilityFormatter(statistics.range[0]);
1576         if (!statistics.range[1])
1577             return 'Significance > ' + lowerLimit + details;
1578
1579         return lowerLimit + ' < Significance < ' + probabilityFormatter(statistics.range[1]) + details;
1580     },
1581     _updateReferenceChart: function ()
1582     {
1583         var configurations = this.get('configurations');
1584         var chartData = this.get('overviewPane') ? this.get('overviewPane').get('chartData') : null;
1585         if (!configurations || !chartData || this.get('referenceChart'))
1586             return;
1587
1588         var currentTimeSeries = chartData.current;
1589         if (!currentTimeSeries)
1590             return;
1591
1592         var repositories = this.get('repositories');
1593         var highlightedItems = {};
1594         var failedToFindPoint = false;
1595         configurations.forEach(function (config) {
1596             var revisions = {};
1597             config.get('rootSet').get('roots').forEach(function (root) {
1598                 revisions[root.get('repository').get('id')] = root.get('revision');
1599             });
1600             var point = currentTimeSeries.findPointByRevisions(revisions);
1601             if (!point) {
1602                 failedToFindPoint = true;
1603                 return;
1604             }
1605             highlightedItems[point.measurement.id()] = true;
1606         });
1607         if (failedToFindPoint)
1608             return;
1609
1610         this.set('referenceChart', {
1611             data: chartData,
1612             highlightedItems: highlightedItems,
1613         });
1614     }.observes('configurations', 'overviewPane.chartData'),
1615     _computeRepositoryList: function ()
1616     {
1617         var specifiedRepositories = new Ember.Set();
1618         (this.get('rootSets') || []).forEach(function (rootSet) {
1619             (rootSet.get('roots') || []).forEach(function (root) {
1620                 specifiedRepositories.add(root.get('repository'));
1621             });
1622         });
1623         var reportedRepositories = new Ember.Set();
1624         var testResults = this.get('testResults');
1625         (this.get('buildRequests') || []).forEach(function (request) {
1626             var point = testResults.current.findPointByBuild(request.get('build'));
1627             if (!point)
1628                 return;
1629
1630             var revisionByRepositoryId = point.measurement.formattedRevisions();
1631             for (var repositoryId in revisionByRepositoryId) {
1632                 var repository = App.Manifest.repository(repositoryId);
1633                 if (!specifiedRepositories.contains(repository))
1634                     reportedRepositories.add(repository);
1635             }
1636         });
1637         return specifiedRepositories.sortBy('name').concat(reportedRepositories.sortBy('name'));
1638     },
1639     _groupRequestsByConfigurations: function (requests, repositoryList)
1640     {
1641         var rootSetIdToRequests = {};
1642         var testGroup = this;
1643         requests.forEach(function (request) {
1644             var rootSetId = request.get('rootSet').get('id');
1645             if (!rootSetIdToRequests[rootSetId])
1646                 rootSetIdToRequests[rootSetId] = [];
1647             rootSetIdToRequests[rootSetId].push(request);
1648         });
1649         return rootSetIdToRequests;
1650     },
1651     _createConfigurationSummary: function (buildRequests, configLetter, range)
1652     {
1653         var repositories = this.get('repositories');
1654         var testResults = this.get('testResults');
1655         var requests = buildRequests.map(function (originalRequest) {
1656             var point = testResults.current.findPointByBuild(originalRequest.get('build'));
1657             var revisionByRepositoryId = point ? point.measurement.formattedRevisions() : {};
1658             return Ember.ObjectProxy.create({
1659                 content: originalRequest,
1660                 revisionList: repositories.map(function (repository, index) {
1661                     return (revisionByRepositoryId[repository.get('id')] || {label:null}).label;
1662                 }),
1663                 value: point ? point.value : null,
1664                 valueRange: range,
1665                 formattedValue: point ? testResults.formatter(point.value) : null,
1666                 buildLabel: point ? 'Build ' + point.measurement.buildNumber() : null,
1667             });
1668         });
1669
1670         var rootSet = requests ? requests[0].get('rootSet') : null;
1671         var summaryRevisions = repositories.map(function (repository, index) {
1672             var revision = rootSet ? rootSet.revisionForRepository(repository) : null;
1673             if (!revision)
1674                 return requests[0].get('revisionList')[index];
1675             return Measurement.formatRevisionRange(revision).label;
1676         });
1677
1678         requests.forEach(function (request) {
1679             var revisionList = request.get('revisionList');
1680             repositories.forEach(function (repository, index) {
1681                 if (revisionList[index] == summaryRevisions[index])
1682                     revisionList[index] = null;
1683             });
1684         });
1685
1686         var valuesInConfig = requests.mapBy('value').filter(function (value) { return typeof(value) === 'number' && !isNaN(value); });
1687         var sum = Statistics.sum(valuesInConfig);
1688         var ciDelta = Statistics.confidenceIntervalDelta(0.95, valuesInConfig.length, sum, Statistics.squareSum(valuesInConfig));
1689         var mean = sum / valuesInConfig.length;
1690
1691         range.min = Math.min(range.min, Statistics.min(valuesInConfig));
1692         range.max = Math.max(range.max, Statistics.max(valuesInConfig));
1693         if (ciDelta && !isNaN(ciDelta)) {
1694             range.min = Math.min(range.min, mean - ciDelta);
1695             range.max = Math.max(range.max, mean + ciDelta);
1696         }
1697
1698         var summary = Ember.Object.create({
1699             isAverage: true,
1700             configLetter: configLetter,
1701             revisionList: summaryRevisions,
1702             formattedValue: isNaN(mean) ? null : testResults.formatWithDeltaAndUnit(mean, ciDelta),
1703             value: mean,
1704             measuredValues: valuesInConfig,
1705             confidenceIntervalDelta: ciDelta,
1706             valueRange: range,
1707             statusLabel: App.BuildRequest.aggregateStatuses(requests),
1708         });
1709
1710         return Ember.Object.create({summary: summary, requests: requests, rootSet: rootSet});
1711     },
1712 });
1713
1714 App.BoxPlotComponent = Ember.Component.extend({
1715     classNames: ['box-plot'],
1716     range: null,
1717     value: null,
1718     delta: null,
1719     didInsertElement: function ()
1720     {
1721         var element = this.get('element');
1722         var svg = d3.select(element).append('svg')
1723             .attr('viewBox', '0 0 100 20')
1724             .attr('preserveAspectRatio', 'none')
1725             .style({width: '100%', height: '100%'});
1726
1727         this._percentageRect = svg
1728             .append('rect')
1729             .attr('x', 0)
1730             .attr('y', 0)
1731             .attr('width', 0)
1732             .attr('height', 20)
1733             .attr('class', 'percentage');
1734
1735         this._deltaRect = svg
1736             .append('rect')
1737             .attr('x', 0)
1738             .attr('y', 5)
1739             .attr('width', 0)
1740             .attr('height', 10)
1741             .attr('class', 'delta')
1742             .attr('opacity', 0.5)
1743         this._updateBars();
1744     },
1745     _updateBars: function ()
1746     {
1747         if (!this._percentageRect || typeof(this._percentage) !== 'number' || isNaN(this._percentage))
1748             return;
1749
1750         this._percentageRect.attr('width', this._percentage);
1751         if (typeof(this._delta) === 'number' && !isNaN(this._delta)) {
1752             this._deltaRect.attr('x', this._percentage - this._delta);
1753             this._deltaRect.attr('width', this._delta * 2);
1754         }
1755     },
1756     valueChanged: function ()
1757     {
1758         var range = this.get('range');
1759         var value = this.get('value');
1760         if (!range || !value)
1761             return;
1762         var scalingFactor = 100 / (range.max - range.min);
1763         var percentage = (value - range.min) * scalingFactor;
1764         this._percentage = percentage;
1765         this._delta = this.get('delta') * scalingFactor;
1766         this._updateBars();
1767     }.observes('value', 'range').on('init'),
1768 });