Perf dashboard should have a way of marking outliers
[WebKit.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, false]]);
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.fetchForTimeRange(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                     self._didFetchRuns(result);
357                     if (result.shouldRefetch)
358                         self.refetchRuns();
359                 }, this._handleFetchErrors.bind(this, platformId, metricId));
360             this.fetchAnalyticRanges();
361         }
362     }.observes('platformId', 'metricId').on('init'),
363     refetchRuns: function () {
364         var platform = this.get('platform');
365         var metric = this.get('metric');
366         Ember.assert('refetchRuns should be called only after platform and metric are resolved', platform && metric);
367
368         var useCache = false;
369         App.Manifest.fetchRunsWithPlatformAndMetric(this.get('store'), platform.get('id'), metric.get('id'), null, useCache)
370             .then(this._didFetchRuns.bind(this), this._handleFetchErrors.bind(this, platform.get('id'), metric.get('id')));
371     },
372     _didFetchRuns: function (result)
373     {
374         this.set('platform', result.platform);
375         this.set('metric', result.metric);
376         this._setNewChartData(result.data);
377     },
378     _setNewChartData: function (chartData)
379     {
380         var newChartData = {};
381         for (var property in chartData)
382             newChartData[property] = chartData[property];
383
384         var showOutlier = this.get('showOutlier');
385         newChartData.showOutlier(showOutlier);
386         this.set('chartData', newChartData);
387         this._updateMovingAverageAndEnvelope();
388
389         if (!this.get('anomalyDetectionStrategies').filterBy('enabled').length)
390             this._highlightPointsMarkedAsOutlier(newChartData);
391     },
392     _highlightPointsMarkedAsOutlier: function (newChartData)
393     {
394         var data = newChartData.current.series();
395         var items = {};
396         for (var i = 0; i < data.length; i++) {
397             if (data[i].measurement.markedOutlier())
398                 items[data[i].measurement.id()] = true;
399         }
400
401         this.set('highlightedItems', items);
402     },
403     _handleFetchErrors: function (platformId, metricId, result)
404     {
405         if (!result || typeof(result) === "string")
406             this.set('failure', 'Failed to fetch the JSON with an error: ' + result);
407         else if (!result.platform)
408             this.set('failure', 'Could not find the platform "' + platformId + '"');
409         else if (!result.metric)
410             this.set('failure', 'Could not find the metric "' + metricId + '"');
411         else
412             this.set('failure', 'An internal error');
413     },
414     fetchAnalyticRanges: function ()
415     {
416         var platformId = this.get('platformId');
417         var metricId = this.get('metricId');
418         var self = this;
419         this.get('store')
420             .find('analysisTask', {platform: platformId, metric: metricId})
421             .then(function (tasks) {
422                 self.set('analyticRanges', tasks.filter(function (task) { return task.get('startRun') && task.get('endRun'); }));
423             });
424     },
425     _isValidId: function (id)
426     {
427         if (typeof(id) == "number")
428             return true;
429         if (typeof(id) == "string")
430             return !!id.match(/^[A-Za-z0-9_]+$/);
431         return false;
432     },
433     computeStatus: function (currentPoint, previousPoint)
434     {
435         var chartData = this.get('chartData');
436         var diffFromBaseline = this._relativeDifferentToLaterPointInTimeSeries(currentPoint, chartData.baseline);
437         var diffFromTarget = this._relativeDifferentToLaterPointInTimeSeries(currentPoint, chartData.target);
438
439         var label = '';
440         var className = '';
441         var formatter = d3.format('.3p');
442
443         var smallerIsBetter = chartData.smallerIsBetter;
444         if (diffFromBaseline !== undefined && diffFromBaseline > 0 == smallerIsBetter) {
445             label = formatter(Math.abs(diffFromBaseline)) + ' ' + (smallerIsBetter ? 'above' : 'below') + ' baseline';
446             className = 'worse';
447         } else if (diffFromTarget !== undefined && diffFromTarget < 0 == smallerIsBetter) {
448             label = formatter(Math.abs(diffFromTarget)) + ' ' + (smallerIsBetter ? 'below' : 'above') + ' target';
449             className = 'better';
450         } else if (diffFromTarget !== undefined)
451             label = formatter(Math.abs(diffFromTarget)) + ' until target';
452
453         var valueDelta = null;
454         var relativeDelta = null;
455         if (previousPoint) {
456             valueDelta = chartData.deltaFormatter(currentPoint.value - previousPoint.value);
457             relativeDelta = d3.format('+.2p')((currentPoint.value - previousPoint.value) / previousPoint.value);
458         }
459         return {
460             className: className,
461             label: label,
462             currentValue: chartData.formatter(currentPoint.value),
463             valueDelta: valueDelta,
464             relativeDelta: relativeDelta,
465         };
466     },
467     _relativeDifferentToLaterPointInTimeSeries: function (currentPoint, timeSeries)
468     {
469         if (!currentPoint || !timeSeries)
470             return undefined;
471
472         var referencePoint = timeSeries.findPointAfterTime(currentPoint.time);
473         if (!referencePoint)
474             return undefined;
475
476         return (currentPoint.value - referencePoint.value) / referencePoint.value;
477     },
478     latestStatus: function ()
479     {
480         var chartData = this.get('chartData');
481         if (!chartData || !chartData.current)
482             return null;
483
484         var lastPoint = chartData.current.lastPoint();
485         if (!lastPoint)
486             return null;
487
488         return this.computeStatus(lastPoint, chartData.current.previousPoint(lastPoint));
489     }.property('chartData'),
490     updateStatisticsTools: function ()
491     {
492         var movingAverageStrategies = Statistics.MovingAverageStrategies.map(this._cloneStrategy.bind(this));
493         this.set('movingAverageStrategies', [{label: 'None'}].concat(movingAverageStrategies));
494         this.set('chosenMovingAverageStrategy', this._configureStrategy(movingAverageStrategies, this.get('movingAverageConfig')));
495
496         var envelopingStrategies = Statistics.EnvelopingStrategies.map(this._cloneStrategy.bind(this));
497         this.set('envelopingStrategies', [{label: 'None'}].concat(envelopingStrategies));
498         this.set('chosenEnvelopingStrategy', this._configureStrategy(envelopingStrategies, this.get('envelopingConfig')));
499
500         var anomalyDetectionStrategies = Statistics.AnomalyDetectionStrategy.map(this._cloneStrategy.bind(this));
501         this.set('anomalyDetectionStrategies', anomalyDetectionStrategies);
502     }.on('init'),
503     _cloneStrategy: function (strategy)
504     {
505         var parameterList = (strategy.parameterList || []).map(function (param) { return Ember.Object.create(param); });
506         return Ember.Object.create({
507             id: strategy.id,
508             label: strategy.label,
509             description: strategy.description,
510             parameterList: parameterList,
511             execute: strategy.execute,
512         });
513     },
514     _configureStrategy: function (strategies, config)
515     {
516         if (!config || !config[0])
517             return null;
518
519         var id = config[0];
520         var chosenStrategy = strategies.find(function (strategy) { return strategy.id == id });
521         if (!chosenStrategy)
522             return null;
523
524         if (chosenStrategy.parameterList) {
525             for (var i = 0; i < chosenStrategy.parameterList.length; i++)
526                 chosenStrategy.parameterList[i].value = parseFloat(config[i + 1]);
527         }
528
529         return chosenStrategy;
530     },
531     _updateMovingAverageAndEnvelope: function ()
532     {
533         var chartData = this.get('chartData');
534         if (!chartData)
535             return;
536
537         var movingAverageStrategy = this.get('chosenMovingAverageStrategy');
538         this._updateStrategyConfigIfNeeded(movingAverageStrategy, 'movingAverageConfig');
539
540         var envelopingStrategy = this.get('chosenEnvelopingStrategy');
541         this._updateStrategyConfigIfNeeded(envelopingStrategy, 'envelopingConfig');
542         
543         var anomalyDetectionStrategies = this.get('anomalyDetectionStrategies').filterBy('enabled');
544         var anomalies = {};
545         chartData.movingAverage = this._computeMovingAverageAndOutliers(chartData, movingAverageStrategy, envelopingStrategy, anomalyDetectionStrategies, anomalies);
546         this.set('highlightedItems', anomalies);
547     },
548     _movingAverageOrEnvelopeStrategyDidChange: function () {
549         var chartData = this.get('chartData');
550         if (!chartData)
551             return;
552         this._setNewChartData(chartData);
553     }.observes('chosenMovingAverageStrategy', 'chosenMovingAverageStrategy.parameterList.@each.value',
554         'chosenEnvelopingStrategy', 'chosenEnvelopingStrategy.parameterList.@each.value',
555         'anomalyDetectionStrategies.@each.enabled'),
556     _computeMovingAverageAndOutliers: function (chartData, movingAverageStrategy, envelopingStrategy, anomalyDetectionStrategies, anomalies)
557     {
558         var currentTimeSeriesData = chartData.current.series();
559         var movingAverageIsSetByUser = movingAverageStrategy && movingAverageStrategy.execute;
560         var movingAverageValues = this._executeStrategy(
561             movingAverageIsSetByUser ? movingAverageStrategy : Statistics.MovingAverageStrategies[0], currentTimeSeriesData);
562         if (!movingAverageValues)
563             return null;
564
565         var envelopeIsSetByUser = envelopingStrategy && envelopingStrategy.execute;
566         var envelopeDelta = this._executeStrategy(envelopeIsSetByUser ? envelopingStrategy : Statistics.EnvelopingStrategies[0],
567             currentTimeSeriesData, [movingAverageValues]);
568
569         for (var i = 0; i < currentTimeSeriesData.length; i++) {
570             var currentValue = currentTimeSeriesData[i].value;
571             var movingAverageValue = movingAverageValues[i];
572             if (currentValue < movingAverageValue - envelopeDelta || movingAverageValue + envelopeDelta < currentValue)
573                 currentTimeSeriesData[i].isOutlier = true;
574         }
575         if (!envelopeIsSetByUser)
576             envelopeDelta = null;
577
578         var isAnomalyArray = new Array(currentTimeSeriesData.length);
579         for (var strategy of anomalyDetectionStrategies) {
580             var anomalyLengths = this._executeStrategy(strategy, currentTimeSeriesData, [movingAverageValues, envelopeDelta]);
581             for (var i = 0; i < currentTimeSeriesData.length; i++)
582                 isAnomalyArray[i] = isAnomalyArray[i] || anomalyLengths[i];
583         }
584         for (var i = 0; i < isAnomalyArray.length; i++) {
585             if (!isAnomalyArray[i])
586                 continue;
587             anomalies[currentTimeSeriesData[i].measurement.id()] = true;
588             while (isAnomalyArray[i] && i < isAnomalyArray.length)
589                 ++i;
590         }
591
592         if (movingAverageIsSetByUser) {
593             return new TimeSeries(currentTimeSeriesData.map(function (point, index) {
594                 var value = movingAverageValues[index];
595                 return {
596                     measurement: point.measurement,
597                     time: point.time,
598                     value: value,
599                     interval: envelopeDelta !== null ? [value - envelopeDelta, value + envelopeDelta] : null,
600                 }
601             }));            
602         }
603     },
604     _executeStrategy: function (strategy, currentTimeSeriesData, additionalArguments)
605     {
606         var parameters = (strategy.parameterList || []).map(function (param) {
607             var parsed = parseFloat(param.value);
608             return Math.min(param.max || Infinity, Math.max(param.min || -Infinity, isNaN(parsed) ? 0 : parsed));
609         });
610         parameters.push(currentTimeSeriesData.map(function (point) { return point.value }));
611         return strategy.execute.apply(window, parameters.concat(additionalArguments));
612     },
613     _updateStrategyConfigIfNeeded: function (strategy, configName)
614     {
615         var config = null;
616         if (strategy && strategy.execute)
617             config = [strategy.id].concat((strategy.parameterList || []).map(function (param) { return param.value; }));
618
619         if (JSON.stringify(config) != JSON.stringify(this.get(configName)))
620             this.set(configName, config);
621     },
622     _updateDetails: function ()
623     {
624         var selectedPoints = this.get('selectedPoints');
625         var currentPoint = this.get('hoveredOrSelectedItem');
626         if (!selectedPoints && !currentPoint) {
627             this.set('details', null);
628             return;
629         }
630
631         var currentMeasurement;
632         var previousPoint;
633         if (!selectedPoints)
634             previousPoint = currentPoint.series.previousPoint(currentPoint);
635         else {
636             currentPoint = selectedPoints[selectedPoints.length - 1];
637             previousPoint = selectedPoints[0];
638         }
639         var currentMeasurement = currentPoint.measurement;
640         var oldMeasurement = previousPoint ? previousPoint.measurement : null;
641
642         var formattedRevisions = currentMeasurement.formattedRevisions(oldMeasurement);
643         var revisions = App.Manifest.get('repositories')
644             .filter(function (repository) { return formattedRevisions[repository.get('id')]; })
645             .map(function (repository) {
646             var revision = Ember.Object.create(formattedRevisions[repository.get('id')]);
647             revision['url'] = revision.previousRevision
648                 ? repository.urlForRevisionRange(revision.previousRevision, revision.currentRevision)
649                 : repository.urlForRevision(revision.currentRevision);
650             revision['name'] = repository.get('name');
651             revision['repository'] = repository;
652             return revision; 
653         });
654
655         var buildNumber = null;
656         var buildURL = null;
657         if (!selectedPoints) {
658             buildNumber = currentMeasurement.buildNumber();
659             var builder = App.Manifest.builder(currentMeasurement.builderId());
660             if (builder)
661                 buildURL = builder.urlFromBuildNumber(buildNumber);
662         }
663
664         this.set('details', Ember.Object.create({
665             status: this.computeStatus(currentPoint, previousPoint),
666             buildNumber: buildNumber,
667             buildURL: buildURL,
668             buildTime: currentMeasurement.formattedBuildTime(),
669             revisions: revisions,
670         }));
671     }.observes('hoveredOrSelectedItem', 'selectedPoints'),
672 });
673
674 App.encodePrettifiedJSON = function (plain)
675 {
676     function numberIfPossible(string) {
677         return string == parseInt(string) ? parseInt(string) : string;
678     }
679
680     function recursivelyConvertNumberIfPossible(input) {
681         if (input instanceof Array) {
682             return input.map(recursivelyConvertNumberIfPossible);
683         }
684         return numberIfPossible(input);
685     }
686
687     return JSON.stringify(recursivelyConvertNumberIfPossible(plain))
688         .replace(/\[/g, '(').replace(/\]/g, ')').replace(/\,/g, '-');
689 }
690
691 App.decodePrettifiedJSON = function (encoded)
692 {
693     var parsed = encoded.replace(/\(/g, '[').replace(/\)/g, ']').replace(/\-/g, ',');
694     try {
695         return JSON.parse(parsed);
696     } catch (exception) {
697         return null;
698     }
699 }
700
701 App.ChartsController = Ember.Controller.extend({
702     queryParams: ['paneList', 'zoom', 'since'],
703     needs: ['pane'],
704     _currentEncodedPaneList: null,
705     panes: [],
706     platforms: null,
707     sharedZoom: null,
708     startTime: null,
709     present: Date.now(),
710     defaultSince: Date.now() - 7 * 24 * 3600 * 1000,
711
712     addPane: function (pane)
713     {
714         this.panes.unshiftObject(pane);
715     },
716
717     removePane: function (pane)
718     {
719         this.panes.removeObject(pane);
720     },
721
722     refreshPanes: function()
723     {
724         var paneList = this.get('paneList');
725         if (paneList === this._currentEncodedPaneList)
726             return;
727
728         var panes = this._parsePaneList(paneList || '[]');
729         if (!panes) {
730             console.log('Failed to parse', jsonPaneList, exception);
731             return;
732         }
733         this.set('panes', panes);
734         this._currentEncodedPaneList = paneList;
735     }.observes('paneList').on('init'),
736
737     refreshZoom: function()
738     {
739         var zoom = this.get('zoom');
740         if (!zoom) {
741             this.set('sharedZoom', null);
742             return;
743         }
744
745         zoom = zoom.split('-');
746         var selection = new Array(2);
747         try {
748             selection[0] = new Date(parseFloat(zoom[0]));
749             selection[1] = new Date(parseFloat(zoom[1]));
750         } catch (error) {
751             console.log('Failed to parse the zoom', zoom);
752         }
753         this.set('sharedZoom', selection);
754
755         var startTime = this.get('startTime');
756         if (startTime && startTime > selection[0])
757             this.set('startTime', selection[0]);
758
759     }.observes('zoom').on('init'),
760
761     _startTimeChanged: function () {
762         this.set('sharedDomain', [this.get('startTime'), this.get('present')]);
763         this._scheduleQueryStringUpdate();
764     }.observes('startTime'),
765
766     _sinceChanged: function () {
767         var since = parseInt(this.get('since'));
768         if (isNaN(since))
769             since = this.defaultSince;
770         this.set('startTime', new Date(since));
771     }.observes('since').on('init'),
772
773     _parsePaneList: function (encodedPaneList)
774     {
775         var parsedPaneList = App.decodePrettifiedJSON(encodedPaneList);
776         if (!parsedPaneList)
777             return null;
778
779         // FIXME: Don't re-create all panes.
780         var self = this;
781         return parsedPaneList.map(function (paneInfo) {
782             var timeRange = null;
783             var selectedItem = null;
784             if (paneInfo[2] instanceof Array) {
785                 var timeRange = paneInfo[2];
786                 try {
787                     timeRange = [new Date(timeRange[0]), new Date(timeRange[1])];
788                 } catch (error) {
789                     console.log("Failed to parse the time range:", timeRange, error);
790                 }
791             } else
792                 selectedItem = paneInfo[2];
793
794             return App.Pane.create({
795                 store: self.store,
796                 info: paneInfo,
797                 platformId: paneInfo[0],
798                 metricId: paneInfo[1],
799                 selectedItem: selectedItem,
800                 timeRange: timeRange,
801                 showFullYAxis: paneInfo[3],
802                 movingAverageConfig: paneInfo[4],
803                 envelopingConfig: paneInfo[5],
804             });
805         });
806     },
807
808     _serializePaneList: function (panes)
809     {
810         if (!panes.length)
811             return undefined;
812         var self = this;
813         return App.encodePrettifiedJSON(panes.map(function (pane) {
814             return [
815                 pane.get('platformId'),
816                 pane.get('metricId'),
817                 pane.get('timeRange') ? pane.get('timeRange').map(function (date) { return date.getTime() }) : pane.get('selectedItem'),
818                 pane.get('showFullYAxis'),
819                 pane.get('movingAverageConfig'),
820                 pane.get('envelopingConfig'),
821             ];
822         }));
823     },
824
825     _scheduleQueryStringUpdate: function ()
826     {
827         Ember.run.debounce(this, '_updateQueryString', 1000);
828     }.observes('sharedZoom', 'panes.@each.platform', 'panes.@each.metric', 'panes.@each.selectedItem', 'panes.@each.timeRange',
829         'panes.@each.showFullYAxis', 'panes.@each.movingAverageConfig', 'panes.@each.envelopingConfig'),
830
831     _updateQueryString: function ()
832     {
833         this._currentEncodedPaneList = this._serializePaneList(this.get('panes'));
834         this.set('paneList', this._currentEncodedPaneList);
835
836         var zoom = undefined;
837         var sharedZoom = this.get('sharedZoom');
838         if (sharedZoom && !App.domainsAreEqual(sharedZoom, this.get('sharedDomain')))
839             zoom = +sharedZoom[0] + '-' + +sharedZoom[1];
840         this.set('zoom', zoom);
841
842         if (this.get('startTime') - this.defaultSince)
843             this.set('since', this.get('startTime') - 0);
844     },
845
846     actions: {
847         addPaneByMetricAndPlatform: function (param)
848         {
849             this.addPane(App.Pane.create({
850                 store: this.store,
851                 platformId: param.platform.get('id'),
852                 metricId: param.metric.get('id'),
853                 showingDetails: false
854             }));
855         },
856     },
857
858     init: function ()
859     {
860         this._super();
861         var self = this;
862         App.buildPopup(this.store, 'addPaneByMetricAndPlatform').then(function (platforms) {
863             self.set('platforms', platforms);
864         });
865     },
866 });
867
868 App.buildPopup = function(store, action, position)
869 {
870     return App.Manifest.fetch(store).then(function () {
871         return App.Manifest.get('platforms').map(function (platform) {
872             return App.PlatformProxyForPopup.create({content: platform,
873                 action: action, position: position});
874         });
875     });
876 }
877
878 App.PlatformProxyForPopup = Ember.ObjectProxy.extend({
879     children: function ()
880     {
881         var platform = this.content;
882         var containsTest = this.content.containsTest.bind(this.content);
883         var action = this.get('action');
884         var position = this.get('position');
885         return App.Manifest.get('topLevelTests')
886             .filter(containsTest)
887             .map(function (test) {
888                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
889             });
890     }.property('App.Manifest.topLevelTests'),
891 });
892
893 App.TestProxyForPopup = Ember.ObjectProxy.extend({
894     platform: null,
895     children: function ()
896     {
897         var platform = this.get('platform');
898         var action = this.get('action');
899         var position = this.get('position');
900
901         var childTests = this.get('childTests')
902             .filter(function (test) { return platform.containsTest(test); })
903             .map(function (test) {
904                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
905             });
906
907         var metrics = this.get('metrics')
908             .filter(function (metric) { return platform.containsMetric(metric); })
909             .map(function (metric) {
910                 var aggregator = metric.get('aggregator');
911                 return {
912                     actionName: action,
913                     actionArgument: {platform: platform, metric: metric, position:position},
914                     label: metric.get('label')
915                 };
916             });
917
918         if (childTests.length && metrics.length)
919             metrics.push({isSeparator: true});
920
921         return metrics.concat(childTests);
922     }.property('childTests', 'metrics'),
923 });
924
925 App.domainsAreEqual = function (domain1, domain2) {
926     return (!domain1 && !domain2) || (domain1 && domain2 && !(domain1[0] - domain2[0]) && !(domain1[1] - domain2[1]));
927 }
928
929 App.PaneController = Ember.ObjectController.extend({
930     needs: ['charts'],
931     sharedTime: Ember.computed.alias('parentController.sharedTime'),
932     sharedSelection: Ember.computed.alias('parentController.sharedSelection'),
933     selection: null,
934     actions: {
935         toggleDetails: function()
936         {
937             this.toggleProperty('showingDetails');
938         },
939         close: function ()
940         {
941             this.parentController.removePane(this.get('model'));
942         },
943         toggleBugsPane: function ()
944         {
945             if (this.toggleProperty('showingAnalysisPane')) {
946                 this.set('showingSearchPane', false);
947                 this.set('showingStatPane', false);
948             }
949         },
950         toggleShowOutlier: function ()
951         {
952             var pane = this.get('model');
953             pane.toggleProperty('showOutlier');
954             var chartData = pane.get('chartData');
955             if (!chartData)
956                 return;
957             pane._setNewChartData(chartData);
958         },
959         createAnalysisTask: function ()
960         {
961             var name = this.get('newAnalysisTaskName');
962             var points = this.get('selectedPoints');
963             Ember.assert('The analysis name should not be empty', name);
964             Ember.assert('There should be at least two points in the range', points && points.length >= 2);
965
966             var newWindow = window.open();
967             var self = this;
968             App.AnalysisTask.create(name, points[0].measurement, points[points.length - 1].measurement).then(function (data) {
969                 // FIXME: Update the UI to show the new analysis task.
970                 var url = App.Router.router.generate('analysisTask', data['taskId']);
971                 newWindow.location.href = '#' + url;
972                 self.get('model').fetchAnalyticRanges();
973             }, function (error) {
974                 newWindow.close();
975                 if (error === 'DuplicateAnalysisTask') {
976                     // FIXME: Duplicate this error more gracefully.
977                 }
978                 alert(error);
979             });
980         },
981         toggleSearchPane: function ()
982         {
983             if (!App.Manifest.repositoriesWithReportedCommits)
984                 return;
985             var model = this.get('model');
986             if (!model.get('commitSearchRepository'))
987                 model.set('commitSearchRepository', App.Manifest.repositoriesWithReportedCommits[0]);
988             if (this.toggleProperty('showingSearchPane')) {
989                 this.set('showingAnalysisPane', false);
990                 this.set('showingStatPane', false);
991             }
992         },
993         searchCommit: function () {
994             var model = this.get('model');
995             model.searchCommit(model.get('commitSearchRepository'), model.get('commitSearchKeyword'));                
996         },
997         toggleStatPane: function ()
998         {
999             if (this.toggleProperty('showingStatPane')) {
1000                 this.set('showingSearchPane', false);
1001                 this.set('showingAnalysisPane', false);
1002             }
1003         },
1004         zoomed: function (selection)
1005         {
1006             this.set('mainPlotDomain', selection ? selection : this.get('overviewDomain'));
1007             if (selection)
1008                 this.set('overviewSelection', selection);
1009             Ember.run.debounce(this, 'propagateZoom', 100);
1010         },
1011     },
1012     _overviewSelectionChanged: function ()
1013     {
1014         var overviewSelection = this.get('overviewSelection');
1015         if (App.domainsAreEqual(overviewSelection, this.get('mainPlotDomain')))
1016             return;
1017         this.set('mainPlotDomain', overviewSelection || this.get('overviewDomain'));
1018         Ember.run.debounce(this, 'propagateZoom', 100);
1019     }.observes('overviewSelection'),
1020     _sharedDomainChanged: function ()
1021     {
1022         var newDomain = this.get('parentController').get('sharedDomain');
1023         if (App.domainsAreEqual(newDomain, this.get('overviewDomain')))
1024             return;
1025         this.set('overviewDomain', newDomain);
1026         if (!this.get('overviewSelection'))
1027             this.set('mainPlotDomain', newDomain);
1028     }.observes('parentController.sharedDomain').on('init'),
1029     propagateZoom: function ()
1030     {
1031         this.get('parentController').set('sharedZoom', this.get('mainPlotDomain'));
1032     },
1033     _sharedZoomChanged: function ()
1034     {
1035         var newSelection = this.get('parentController').get('sharedZoom');
1036         if (App.domainsAreEqual(newSelection, this.get('mainPlotDomain')))
1037             return;
1038         this.set('mainPlotDomain', newSelection || this.get('overviewDomain'));
1039         this.set('overviewSelection', newSelection);
1040     }.observes('parentController.sharedZoom').on('init'),
1041     _updateCanAnalyze: function ()
1042     {
1043         var pane = this.get('model');
1044         var points = pane.get('selectedPoints');
1045         this.set('cannotAnalyze', !this.get('newAnalysisTaskName') || !points || points.length < 2);
1046         this.set('cannotMarkOutlier', !!points || !this.get('selectedItem'));
1047
1048         var selectedMeasurement = this.selectedMeasurement();
1049         this.set('selectedItemIsMarkedOutlier', selectedMeasurement && selectedMeasurement.markedOutlier());
1050
1051     }.observes('newAnalysisTaskName', 'model.selectedPoints', 'model.selectedItem').on('init'),
1052     selectedMeasurement: function () {
1053         var chartData = this.get('model').get('chartData');
1054         var selectedItem = this.get('selectedItem');
1055         if (!chartData || !selectedItem)
1056             return null;
1057         var point = chartData.current.findPointByMeasurementId(selectedItem);
1058         Ember.assert('selectedItem should always be in the current chart data', point);
1059         return point.measurement;
1060     },
1061     showOutlierTitle: function ()
1062     {
1063         return this.get('showOutlier') ? 'Hide outliers' : 'Show outliers';
1064     }.property('showOutlier'),
1065     _selectedItemIsMarkedOutlierDidChange: function ()
1066     {
1067         var selectedMeasurement = this.selectedMeasurement();
1068         if (!selectedMeasurement)
1069             return;
1070         var selectedItemIsMarkedOutlier = this.get('selectedItemIsMarkedOutlier');
1071         if (selectedMeasurement.markedOutlier() == selectedItemIsMarkedOutlier)
1072             return;
1073         var pane = this.get('model');
1074         selectedMeasurement.setMarkedOutlier(!!selectedItemIsMarkedOutlier).then(function () {
1075             pane.refetchRuns();
1076         }, function (error) {
1077             alert(error);
1078         });
1079     }.observes('selectedItemIsMarkedOutlier'),
1080 });
1081
1082 App.AnalysisRoute = Ember.Route.extend({
1083     model: function () {
1084         return this.store.findAll('analysisTask').then(function (tasks) {
1085             return Ember.Object.create({'tasks': tasks});
1086         });
1087     },
1088 });
1089
1090 App.AnalysisTaskRoute = Ember.Route.extend({
1091     model: function (param)
1092     {
1093         return this.store.find('analysisTask', param.taskId);
1094     },
1095 });
1096
1097 App.AnalysisTaskController = Ember.Controller.extend({
1098     label: Ember.computed.alias('model.name'),
1099     platform: Ember.computed.alias('model.platform'),
1100     metric: Ember.computed.alias('model.metric'),
1101     details: Ember.computed.alias('pane.details'),
1102     roots: [],
1103     bugTrackers: [],
1104     possibleRepetitionCounts: [1, 2, 3, 4, 5, 6],
1105     _taskUpdated: function ()
1106     {
1107         var model = this.get('model');
1108         if (!model)
1109             return;
1110
1111         App.Manifest.fetch(this.store).then(this._fetchedManifest.bind(this));
1112         this.set('pane', App.Pane.create({
1113             store: this.store,
1114             platformId: model.get('platform').get('id'),
1115             metricId: model.get('metric').get('id'),
1116         }));
1117
1118         var self = this;
1119         model.get('testGroups').then(function (groups) {
1120             self.set('testGroupPanes', groups.map(function (group) { return App.TestGroupPane.create({content: group}); }));
1121         });
1122     }.observes('model', 'model.testGroups').on('init'),
1123     _fetchedManifest: function ()
1124     {
1125         var trackerIdToBugNumber = {};
1126         this.get('model').get('bugs').forEach(function (bug) {
1127             trackerIdToBugNumber[bug.get('bugTracker').get('id')] = bug.get('number');
1128         });
1129
1130         this.set('bugTrackers', App.Manifest.get('bugTrackers').map(function (bugTracker) {
1131             var bugNumber = trackerIdToBugNumber[bugTracker.get('id')];
1132             return Ember.ObjectProxy.create({
1133                 content: bugTracker,
1134                 bugNumber: bugNumber,
1135                 editedBugNumber: bugNumber,
1136             });
1137         }));
1138     },
1139     _chartDataChanged: function ()
1140     {
1141         var pane = this.get('pane');
1142         if (!pane)
1143             return;
1144
1145         var chartData = pane.get('chartData');
1146         if (!chartData)
1147             return null;
1148
1149         var currentTimeSeries = chartData.current;
1150         if (!currentTimeSeries)
1151             return null; // FIXME: Report an error.
1152
1153         var start = currentTimeSeries.findPointByMeasurementId(this.get('model').get('startRun'));
1154         var end = currentTimeSeries.findPointByMeasurementId(this.get('model').get('endRun'));
1155         if (!start || !end)
1156             return null; // FIXME: Report an error.
1157
1158         var highlightedItems = {};
1159         highlightedItems[start.measurement.id()] = true;
1160         highlightedItems[end.measurement.id()] = true;
1161
1162         var formatedPoints = currentTimeSeries.seriesBetweenPoints(start, end).map(function (point, index) {
1163             return {
1164                 id: point.measurement.id(),
1165                 measurement: point.measurement,
1166                 label: 'Point ' + (index + 1),
1167                 value: chartData.formatWithUnit(point.value),
1168             };
1169         });
1170
1171         var margin = (end.time - start.time) * 0.1;
1172         this.set('highlightedItems', highlightedItems);
1173         this.set('overviewEndPoints', [start, end]);
1174         this.set('analysisPoints', formatedPoints);
1175
1176         var overviewDomain = [start.time - margin, +end.time + margin];
1177
1178         var testGroupPanes = this.get('testGroupPanes');
1179         if (testGroupPanes) {
1180             testGroupPanes.setEach('overviewPane', pane);
1181             testGroupPanes.setEach('overviewDomain', overviewDomain);
1182         }
1183
1184         this.set('overviewDomain', overviewDomain);
1185     }.observes('pane.chartData'),
1186     updateRootConfigurations: function ()
1187     {
1188         var analysisPoints = this.get('analysisPoints');
1189         if (!analysisPoints)
1190             return;
1191         var repositoryToRevisions = {};
1192         analysisPoints.forEach(function (point, pointIndex) {
1193             var revisions = point.measurement.formattedRevisions();
1194             for (var repositoryId in revisions) {
1195                 if (!repositoryToRevisions[repositoryId])
1196                     repositoryToRevisions[repositoryId] = new Array(analysisPoints.length);
1197                 var revision = revisions[repositoryId];
1198                 repositoryToRevisions[repositoryId][pointIndex] = {
1199                     label: point.label + ': ' + revision.label,
1200                     value: revision.currentRevision,
1201                 };
1202             }
1203         });
1204
1205         var self = this;
1206         this.get('model').get('triggerable').then(function (triggerable) {
1207             if (!triggerable)
1208                 return;
1209
1210             self.set('configurations', ['A', 'B']);
1211             self.set('rootConfigurations', triggerable.get('acceptedRepositories').map(function (repository) {
1212                 var repositoryId = repository.get('id');
1213                 var options = [{label: 'None'}].concat((repositoryToRevisions[repositoryId] || []).map(function (option, index) {
1214                     if (!option || !option['value'])
1215                         return {value: '', label: analysisPoints[index].label + ': None'}; 
1216                     return option;
1217                 }));
1218                 return Ember.Object.create({
1219                     repository: repository,
1220                     name: repository.get('name'),
1221                     sets: [
1222                         Ember.Object.create({name: 'A[' + repositoryId + ']',
1223                             options: options,
1224                             selection: options[1]}),
1225                         Ember.Object.create({name: 'B[' + repositoryId + ']',
1226                             options: options,
1227                             selection: options[options.length - 1]}),
1228                     ],
1229                 });
1230             }));
1231         });
1232     }.observes('analysisPoints'),
1233     actions: {
1234         associateBug: function (bugTracker, bugNumber)
1235         {
1236             var model = this.get('model');
1237             this.store.createRecord('bug',
1238                 {task: this.get('model'), bugTracker: bugTracker.get('content'), number: bugNumber}).save().then(function () {
1239                     // FIXME: Should we notify the user?
1240                 }, function (error) {
1241                     alert('Failed to associate the bug: ' + error);
1242                 });
1243         },
1244         createTestGroup: function (name, repetitionCount)
1245         {
1246             var analysisTask = this.get('model');
1247             if (analysisTask.get('testGroups').isAny('name', name)) {
1248                 alert('Cannot create two test groups of the same name.');
1249                 return;
1250             }
1251
1252             var roots = {};
1253             var rootConfigurations = this.get('rootConfigurations').toArray();
1254             for (var root of rootConfigurations) {
1255                 var sets = root.get('sets');
1256                 var hasSelection = function (item) { return item.get('selection') && item.get('selection').value; };
1257                 if (!sets.any(hasSelection))
1258                     continue;
1259                 if (!sets.every(hasSelection)) {
1260                     alert('Only some configuration specifies ' + root.get('name'));
1261                     return;
1262                 }
1263                 roots[root.get('name')] = sets.map(function (item) { return item.get('selection').value; });                
1264             }
1265
1266             App.TestGroup.create(analysisTask, name, roots, repetitionCount).then(function () {
1267             }, function (error) {
1268                 alert('Failed to create a new test group:' + error);
1269             });
1270         },
1271         toggleShowRequestList: function (configuration)
1272         {
1273             configuration.toggleProperty('showRequestList');
1274         }
1275     },
1276     _updateRootsBySelectedPoints: function ()
1277     {
1278         var rootConfigurations = this.get('rootConfigurations');
1279         var pane = this.get('pane');
1280         if (!rootConfigurations || !pane)
1281             return;
1282
1283         var rootSetPoints;
1284         var selectedPoints = pane.get('selectedPoints');
1285         if (selectedPoints && selectedPoints.length >= 2)
1286             rootSetPoints = [selectedPoints[0], selectedPoints[selectedPoints.length - 1]];
1287         else
1288             rootSetPoints = this.get('overviewEndPoints');
1289         if (!rootSetPoints)
1290             return;
1291
1292         rootConfigurations.forEach(function (root) {
1293             root.get('sets').forEach(function (set, setIndex) {
1294                 if (setIndex >= rootSetPoints.length)
1295                     return;
1296                 var targetRevision = rootSetPoints[setIndex].measurement.revisionForRepository(root.get('repository').get('id'));
1297                 var selectedOption;
1298                 if (targetRevision)
1299                     selectedOption = set.get('options').find(function (option) { return option.value == targetRevision; });
1300                 set.set('selection', selectedOption || set.get('options')[0]);
1301             });
1302         });
1303
1304     }.observes('pane.selectedPoints'),
1305 });
1306
1307 App.TestGroupPane = Ember.ObjectProxy.extend({
1308     _populate: function ()
1309     {
1310         var buildRequests = this.get('buildRequests');
1311         var testResults = this.get('testResults');
1312         if (!buildRequests || !testResults)
1313             return [];
1314
1315         var repositories = this._computeRepositoryList();
1316         this.set('repositories', repositories);
1317
1318         var requestsByRooSet = this._groupRequestsByConfigurations(buildRequests);
1319
1320         var configurations = [];
1321         var index = 0;
1322         var range = {min: Infinity, max: -Infinity};
1323         for (var rootSetId in requestsByRooSet) {
1324             var configLetter = String.fromCharCode('A'.charCodeAt(0) + index++);
1325             configurations.push(this._createConfigurationSummary(requestsByRooSet[rootSetId], configLetter, range));
1326         }
1327
1328         var margin = 0.1 * (range.max - range.min);
1329         range.max += margin;
1330         range.min -= margin;
1331
1332         this.set('configurations', configurations);
1333     }.observes('testResults', 'buildRequests'),
1334     _updateReferenceChart: function ()
1335     {
1336         var configurations = this.get('configurations');
1337         var chartData = this.get('overviewPane') ? this.get('overviewPane').get('chartData') : null;
1338         if (!configurations || !chartData || this.get('referenceChart'))
1339             return;
1340
1341         var currentTimeSeries = chartData.current;
1342         if (!currentTimeSeries)
1343             return;
1344
1345         var repositories = this.get('repositories');
1346         var highlightedItems = {};
1347         var failedToFindPoint = false;
1348         configurations.forEach(function (config) {
1349             var revisions = {};
1350             config.get('rootSet').get('roots').forEach(function (root) {
1351                 revisions[root.get('repository').get('id')] = root.get('revision');
1352             });
1353             var point = currentTimeSeries.findPointByRevisions(revisions);
1354             if (!point) {
1355                 failedToFindPoint = true;
1356                 return;
1357             }
1358             highlightedItems[point.measurement.id()] = true;
1359         });
1360         if (failedToFindPoint)
1361             return;
1362
1363         this.set('referenceChart', {
1364             data: chartData,
1365             highlightedItems: highlightedItems,
1366         });
1367     }.observes('configurations', 'overviewPane.chartData'),
1368     _computeRepositoryList: function ()
1369     {
1370         var specifiedRepositories = new Ember.Set();
1371         (this.get('rootSets') || []).forEach(function (rootSet) {
1372             (rootSet.get('roots') || []).forEach(function (root) {
1373                 specifiedRepositories.add(root.get('repository'));
1374             });
1375         });
1376         var reportedRepositories = new Ember.Set();
1377         var testResults = this.get('testResults');
1378         (this.get('buildRequests') || []).forEach(function (request) {
1379             var point = testResults.current.findPointByBuild(request.get('build'));
1380             if (!point)
1381                 return;
1382
1383             var revisionByRepositoryId = point.measurement.formattedRevisions();
1384             for (var repositoryId in revisionByRepositoryId) {
1385                 var repository = App.Manifest.repository(repositoryId);
1386                 if (!specifiedRepositories.contains(repository))
1387                     reportedRepositories.add(repository);
1388             }
1389         });
1390         return specifiedRepositories.sortBy('name').concat(reportedRepositories.sortBy('name'));
1391     },
1392     _groupRequestsByConfigurations: function (requests, repositoryList)
1393     {
1394         var rootSetIdToRequests = {};
1395         var testGroup = this;
1396         requests.forEach(function (request) {
1397             var rootSetId = request.get('rootSet').get('id');
1398             if (!rootSetIdToRequests[rootSetId])
1399                 rootSetIdToRequests[rootSetId] = [];
1400             rootSetIdToRequests[rootSetId].push(request);
1401         });
1402         return rootSetIdToRequests;
1403     },
1404     _createConfigurationSummary: function (buildRequests, configLetter, range)
1405     {
1406         var repositories = this.get('repositories');
1407         var testResults = this.get('testResults');
1408         var requests = buildRequests.map(function (originalRequest) {
1409             var point = testResults.current.findPointByBuild(originalRequest.get('build'));
1410             var revisionByRepositoryId = point ? point.measurement.formattedRevisions() : {};
1411             return Ember.ObjectProxy.create({
1412                 content: originalRequest,
1413                 revisionList: repositories.map(function (repository, index) {
1414                     return (revisionByRepositoryId[repository.get('id')] || {label:null}).label;
1415                 }),
1416                 value: point ? point.value : null,
1417                 valueRange: range,
1418                 formattedValue: point ? testResults.formatWithUnit(point.value) : null,
1419                 buildLabel: point ? 'Build ' + point.measurement.buildNumber() : null,
1420             });
1421         });
1422
1423         var rootSet = requests ? requests[0].get('rootSet') : null;
1424         var summaryRevisions = repositories.map(function (repository, index) {
1425             var revision = rootSet ? rootSet.revisionForRepository(repository) : null;
1426             if (!revision)
1427                 return requests[0].get('revisionList')[index];
1428             return Measurement.formatRevisionRange(revision).label;
1429         });
1430
1431         requests.forEach(function (request) {
1432             var revisionList = request.get('revisionList');
1433             repositories.forEach(function (repository, index) {
1434                 if (revisionList[index] == summaryRevisions[index])
1435                     revisionList[index] = null;
1436             });
1437         });
1438
1439         var valuesInConfig = requests.mapBy('value').filter(function (value) { return typeof(value) === 'number' && !isNaN(value); });
1440         var sum = Statistics.sum(valuesInConfig);
1441         var ciDelta = Statistics.confidenceIntervalDelta(0.95, valuesInConfig.length, sum, Statistics.squareSum(valuesInConfig));
1442         var mean = sum / valuesInConfig.length;
1443
1444         range.min = Math.min(range.min, Statistics.min(valuesInConfig));
1445         range.max = Math.max(range.max, Statistics.max(valuesInConfig));
1446         if (ciDelta && !isNaN(ciDelta)) {
1447             range.min = Math.min(range.min, mean - ciDelta);
1448             range.max = Math.max(range.max, mean + ciDelta);
1449         }
1450
1451         var summary = Ember.Object.create({
1452             isAverage: true,
1453             configLetter: configLetter,
1454             revisionList: summaryRevisions,
1455             formattedValue: isNaN(mean) ? null : testResults.formatWithDeltaAndUnit(mean, ciDelta),
1456             value: mean,
1457             confidenceIntervalDelta: ciDelta,
1458             valueRange: range,
1459             statusLabel: App.BuildRequest.aggregateStatuses(requests),
1460         });
1461
1462         return Ember.Object.create({summary: summary, items: requests, rootSet: rootSet});
1463     },
1464 });
1465
1466 App.BoxPlotComponent = Ember.Component.extend({
1467     classNames: ['box-plot'],
1468     range: null,
1469     value: null,
1470     delta: null,
1471     didInsertElement: function ()
1472     {
1473         var element = this.get('element');
1474         var svg = d3.select(element).append('svg')
1475             .attr('viewBox', '0 0 100 20')
1476             .attr('preserveAspectRatio', 'none')
1477             .style({width: '100%', height: '100%'});
1478
1479         this._percentageRect = svg
1480             .append('rect')
1481             .attr('x', 0)
1482             .attr('y', 0)
1483             .attr('width', 0)
1484             .attr('height', 20)
1485             .attr('class', 'percentage');
1486
1487         this._deltaRect = svg
1488             .append('rect')
1489             .attr('x', 0)
1490             .attr('y', 5)
1491             .attr('width', 0)
1492             .attr('height', 10)
1493             .attr('class', 'delta')
1494             .attr('opacity', 0.5)
1495         this._updateBars();
1496     },
1497     _updateBars: function ()
1498     {
1499         if (!this._percentageRect || typeof(this._percentage) !== 'number' || isNaN(this._percentage))
1500             return;
1501
1502         this._percentageRect.attr('width', this._percentage);
1503         if (typeof(this._delta) === 'number' && !isNaN(this._delta)) {
1504             this._deltaRect.attr('x', this._percentage - this._delta);
1505             this._deltaRect.attr('width', this._delta * 2);
1506         }
1507     },
1508     valueChanged: function ()
1509     {
1510         var range = this.get('range');
1511         var value = this.get('value');
1512         if (!range || !value)
1513             return;
1514         var scalingFactor = 100 / (range.max - range.min);
1515         var percentage = (value - range.min) * scalingFactor;
1516         this._percentage = percentage;
1517         this._delta = this.get('delta') * scalingFactor;
1518         this._updateBars();
1519     }.observes('value', 'range').on('init'),
1520 });