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