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