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