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