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