04dab60ce3da60066ef118ecd2e234dca468ef10
[WebKit-https.git] / Websites / perf.webkit.org / public / v2 / app.js
1 window.App = Ember.Application.create();
2
3 App.Router.map(function () {
4     this.resource('customDashboard', {path: 'dashboard/custom'});
5     this.resource('dashboard', {path: 'dashboard/:name'});
6     this.resource('charts', {path: 'charts'});
7     this.resource('analysis', {path: 'analysis'});
8     this.resource('analysisTask', {path: 'analysis/task/:taskId'});
9 });
10
11 App.DashboardRow = Ember.Object.extend({
12     header: null,
13     cells: [],
14
15     init: function ()
16     {
17         this._super();
18
19         var cellsInfo = this.get('cellsInfo') || [];
20         var columnCount = this.get('columnCount');
21         while (cellsInfo.length < columnCount)
22             cellsInfo.push([]);
23
24         this.set('cells', cellsInfo.map(this._createPane.bind(this)));
25     },
26     addPane: function (paneInfo)
27     {
28         var pane = this._createPane(paneInfo);
29         this.get('cells').pushObject(pane);
30         this.set('columnCount', this.get('columnCount') + 1);
31     },
32     _createPane: function (paneInfo)
33     {
34         if (!paneInfo || !paneInfo.length || (!paneInfo[0] && !paneInfo[1]))
35             paneInfo = null;
36
37         var pane = App.Pane.create({
38             store: this.get('store'),
39             platformId: paneInfo ? paneInfo[0] : null,
40             metricId: paneInfo ? paneInfo[1] : null,
41         });
42
43         return App.DashboardPaneProxyForPicker.create({content: pane});
44     },
45 });
46
47 App.DashboardPaneProxyForPicker = Ember.ObjectProxy.extend({
48     _platformOrMetricIdChanged: function ()
49     {
50         var self = this;
51         App.buildPopup(this.get('store'), 'choosePane', this)
52             .then(function (platforms) { self.set('pickerData', platforms); });
53     }.observes('platformId', 'metricId').on('init'),
54     paneList: function () {
55         return App.encodePrettifiedJSON([[this.get('platformId'), this.get('metricId'), null, null, 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         if (!movingAverageIsSetByUser)
590             return null;
591
592         var movingAverageValues = Statistics.executeStrategy(movingAverageStrategy, rawValues);
593         if (!movingAverageValues)
594             return null;
595
596         var testRangeCandidates = [];
597         if (movingAverageStrategy && movingAverageStrategy.isSegmentation && testRangeSelectionStrategy && testRangeSelectionStrategy.execute)
598             testRangeCandidates = Statistics.executeStrategy(testRangeSelectionStrategy, rawValues, [movingAverageValues]);
599
600         if (envelopingStrategy && envelopingStrategy.execute) {
601             var envelopeDelta = Statistics.executeStrategy(envelopingStrategy, rawValues, [movingAverageValues]);
602             var anomalies = {};
603             if (anomalyDetectionStrategies.length) {
604                 var isAnomalyArray = new Array(currentTimeSeriesData.length);
605                 for (var strategy of anomalyDetectionStrategies) {
606                     var anomalyLengths = Statistics.executeStrategy(strategy, rawValues, [movingAverageValues, envelopeDelta]);
607                     for (var i = 0; i < currentTimeSeriesData.length; i++)
608                         isAnomalyArray[i] = isAnomalyArray[i] || anomalyLengths[i];
609                 }
610                 for (var i = 0; i < isAnomalyArray.length; i++) {
611                     if (!isAnomalyArray[i])
612                         continue;
613                     anomalies[currentTimeSeriesData[i].measurement.id()] = true;
614                     while (isAnomalyArray[i] && i < isAnomalyArray.length)
615                         ++i;
616                 }
617             }
618         }
619
620         var movingAverageTimeSeries = null;
621         if (movingAverageIsSetByUser) {
622             movingAverageTimeSeries = new TimeSeries(currentTimeSeriesData.map(function (point, index) {
623                 var value = movingAverageValues[index];
624                 return {
625                     measurement: point.measurement,
626                     time: point.time,
627                     value: value,
628                     interval: envelopeDelta !== null ? [value - envelopeDelta, value + envelopeDelta] : null,
629                 }
630             }));
631         }
632
633         return {
634             movingAverage: movingAverageTimeSeries,
635             anomalies: anomalies,
636             testRangeCandidates: testRangeCandidates,
637         };
638     },
639     _updateStrategyConfigIfNeeded: function (strategy, configName)
640     {
641         var config = null;
642         if (strategy && strategy.execute)
643             config = [strategy.id].concat((strategy.parameterList || []).map(function (param) { return param.value; }));
644
645         if (JSON.stringify(config) != JSON.stringify(this.get(configName)))
646             this.set(configName, config);
647     },
648     _updateDetails: function ()
649     {
650         var selectedPoints = this.get('selectedPoints');
651         var currentPoint = this.get('hoveredOrSelectedItem');
652         if (!selectedPoints && !currentPoint) {
653             this.set('details', null);
654             return;
655         }
656
657         var currentMeasurement;
658         var previousPoint;
659         if (!selectedPoints)
660             previousPoint = currentPoint.series.previousPoint(currentPoint);
661         else {
662             currentPoint = selectedPoints[selectedPoints.length - 1];
663             previousPoint = selectedPoints[0];
664         }
665         var currentMeasurement = currentPoint.measurement;
666         var oldMeasurement = previousPoint ? previousPoint.measurement : null;
667
668         var formattedRevisions = currentMeasurement.formattedRevisions(oldMeasurement);
669         var revisions = App.Manifest.get('repositories')
670             .filter(function (repository) { return formattedRevisions[repository.get('id')]; })
671             .map(function (repository) {
672             var revision = Ember.Object.create(formattedRevisions[repository.get('id')]);
673             revision['url'] = revision.previousRevision
674                 ? repository.urlForRevisionRange(revision.previousRevision, revision.currentRevision)
675                 : repository.urlForRevision(revision.currentRevision);
676             revision['name'] = repository.get('name');
677             revision['repository'] = repository;
678             return revision; 
679         });
680
681         var buildNumber = null;
682         var buildURL = null;
683         if (!selectedPoints) {
684             buildNumber = currentMeasurement.buildNumber();
685             var builder = App.Manifest.builder(currentMeasurement.builderId());
686             if (builder)
687                 buildURL = builder.urlFromBuildNumber(buildNumber);
688         }
689
690         this.set('details', Ember.Object.create({
691             status: this.computeStatus(currentPoint, previousPoint),
692             buildNumber: buildNumber,
693             buildURL: buildURL,
694             buildTime: currentMeasurement.formattedBuildTime(),
695             revisions: revisions,
696         }));
697     }.observes('hoveredOrSelectedItem', 'selectedPoints'),
698 });
699
700 App.encodePrettifiedJSON = function (plain)
701 {
702     function numberIfPossible(string) {
703         return string == parseInt(string) ? parseInt(string) : string;
704     }
705
706     function recursivelyConvertNumberIfPossible(input) {
707         if (input instanceof Array) {
708             return input.map(recursivelyConvertNumberIfPossible);
709         }
710         return numberIfPossible(input);
711     }
712
713     return JSON.stringify(recursivelyConvertNumberIfPossible(plain))
714         .replace(/\[/g, '(').replace(/\]/g, ')').replace(/\,/g, '-');
715 }
716
717 App.decodePrettifiedJSON = function (encoded)
718 {
719     var parsed = encoded.replace(/\(/g, '[').replace(/\)/g, ']').replace(/\-/g, ',');
720     try {
721         return JSON.parse(parsed);
722     } catch (exception) {
723         return null;
724     }
725 }
726
727 App.ChartsController = Ember.Controller.extend({
728     queryParams: ['paneList', 'zoom', 'since'],
729     needs: ['pane'],
730     _currentEncodedPaneList: null,
731     panes: [],
732     platforms: null,
733     sharedZoom: null,
734     startTime: null,
735     present: Date.now(),
736     defaultSince: Date.now() - 7 * 24 * 3600 * 1000,
737
738     addPane: function (pane)
739     {
740         this.panes.unshiftObject(pane);
741     },
742
743     removePane: function (pane)
744     {
745         this.panes.removeObject(pane);
746     },
747
748     refreshPanes: function()
749     {
750         var paneList = this.get('paneList');
751         if (paneList === this._currentEncodedPaneList)
752             return;
753
754         var panes = this._parsePaneList(paneList || '[]');
755         if (!panes) {
756             console.log('Failed to parse', jsonPaneList, exception);
757             return;
758         }
759         this.set('panes', panes);
760         this._currentEncodedPaneList = paneList;
761     }.observes('paneList').on('init'),
762
763     refreshZoom: function()
764     {
765         var zoom = this.get('zoom');
766         if (!zoom) {
767             this.set('sharedZoom', null);
768             return;
769         }
770
771         zoom = zoom.split('-');
772         var selection = new Array(2);
773         try {
774             selection[0] = new Date(parseFloat(zoom[0]));
775             selection[1] = new Date(parseFloat(zoom[1]));
776         } catch (error) {
777             console.log('Failed to parse the zoom', zoom);
778         }
779         this.set('sharedZoom', selection);
780
781         var startTime = this.get('startTime');
782         if (startTime && startTime > selection[0])
783             this.set('startTime', selection[0]);
784
785     }.observes('zoom').on('init'),
786
787     _startTimeChanged: function () {
788         this.set('sharedDomain', [this.get('startTime'), this.get('present')]);
789         this._scheduleQueryStringUpdate();
790     }.observes('startTime'),
791
792     _sinceChanged: function () {
793         var since = parseInt(this.get('since'));
794         if (isNaN(since))
795             since = this.defaultSince;
796         this.set('startTime', new Date(since));
797     }.observes('since').on('init'),
798
799     _parsePaneList: function (encodedPaneList)
800     {
801         var parsedPaneList = App.decodePrettifiedJSON(encodedPaneList);
802         if (!parsedPaneList)
803             return null;
804
805         // FIXME: Don't re-create all panes.
806         var self = this;
807         return parsedPaneList.map(function (paneInfo) {
808             var timeRange = null;
809             var selectedItem = null;
810             if (paneInfo[2] instanceof Array) {
811                 var timeRange = paneInfo[2];
812                 try {
813                     timeRange = [new Date(timeRange[0]), new Date(timeRange[1])];
814                 } catch (error) {
815                     console.log("Failed to parse the time range:", timeRange, error);
816                 }
817             } else
818                 selectedItem = paneInfo[2];
819
820             return App.Pane.create({
821                 store: self.store,
822                 info: paneInfo,
823                 platformId: paneInfo[0],
824                 metricId: paneInfo[1],
825                 selectedItem: selectedItem,
826                 timeRange: timeRange,
827                 showFullYAxis: paneInfo[3],
828                 movingAverageConfig: paneInfo[4],
829                 envelopingConfig: paneInfo[5],
830                 testRangeSelectionConfig: paneInfo[6],
831             });
832         });
833     },
834
835     _serializePaneList: function (panes)
836     {
837         if (!panes.length)
838             return undefined;
839         var self = this;
840         return App.encodePrettifiedJSON(panes.map(function (pane) {
841             return [
842                 pane.get('platformId'),
843                 pane.get('metricId'),
844                 pane.get('timeRange') ? pane.get('timeRange').map(function (date) { return date.getTime() }) : pane.get('selectedItem'),
845                 pane.get('showFullYAxis'),
846                 pane.get('movingAverageConfig'),
847                 pane.get('envelopingConfig'),
848                 pane.get('testRangeSelectionConfig'),
849             ];
850         }));
851     },
852
853     _scheduleQueryStringUpdate: function ()
854     {
855         Ember.run.debounce(this, '_updateQueryString', 1000);
856     }.observes('sharedZoom', 'panes.@each.platform', 'panes.@each.metric', 'panes.@each.selectedItem', 'panes.@each.timeRange',
857         'panes.@each.showFullYAxis', 'panes.@each.movingAverageConfig', 'panes.@each.envelopingConfig', 'panes.@each.testRangeSelectionConfig'),
858
859     _updateQueryString: function ()
860     {
861         this._currentEncodedPaneList = this._serializePaneList(this.get('panes'));
862         this.set('paneList', this._currentEncodedPaneList);
863
864         var zoom = undefined;
865         var sharedZoom = this.get('sharedZoom');
866         if (sharedZoom && !App.domainsAreEqual(sharedZoom, this.get('sharedDomain')))
867             zoom = +sharedZoom[0] + '-' + +sharedZoom[1];
868         this.set('zoom', zoom);
869
870         if (this.get('startTime') - this.defaultSince)
871             this.set('since', this.get('startTime') - 0);
872     },
873
874     actions: {
875         addPaneByMetricAndPlatform: function (param)
876         {
877             this.addPane(App.Pane.create({
878                 store: this.store,
879                 platformId: param.platform.get('id'),
880                 metricId: param.metric.get('id'),
881                 showingDetails: false
882             }));
883         },
884     },
885
886     init: function ()
887     {
888         this._super();
889         var self = this;
890         App.buildPopup(this.store, 'addPaneByMetricAndPlatform').then(function (platforms) {
891             self.set('platforms', platforms);
892         });
893     },
894 });
895
896 App.buildPopup = function(store, action, position)
897 {
898     return App.Manifest.fetch(store).then(function () {
899         return App.Manifest.get('platforms').sortBy('label').map(function (platform) {
900             return App.PlatformProxyForPopup.create({content: platform,
901                 action: action, position: position});
902         });
903     });
904 }
905
906 App.PlatformProxyForPopup = Ember.ObjectProxy.extend({
907     children: function ()
908     {
909         var platform = this.content;
910         var containsTest = this.content.containsTest.bind(this.content);
911         var action = this.get('action');
912         var position = this.get('position');
913         return App.Manifest.get('topLevelTests')
914             .filter(containsTest)
915             .map(function (test) {
916                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
917             });
918     }.property('App.Manifest.topLevelTests'),
919 });
920
921 App.TestProxyForPopup = Ember.ObjectProxy.extend({
922     platform: null,
923     children: function ()
924     {
925         var platform = this.get('platform');
926         var action = this.get('action');
927         var position = this.get('position');
928
929         var childTests = this.get('childTests')
930             .filter(function (test) { return platform.containsTest(test); })
931             .map(function (test) {
932                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
933             });
934
935         var metrics = this.get('metrics')
936             .filter(function (metric) { return platform.containsMetric(metric); })
937             .map(function (metric) {
938                 var aggregator = metric.get('aggregator');
939                 return {
940                     actionName: action,
941                     actionArgument: {platform: platform, metric: metric, position:position},
942                     label: metric.get('label')
943                 };
944             });
945
946         if (childTests.length && metrics.length)
947             metrics.push({isSeparator: true});
948
949         return metrics.concat(childTests);
950     }.property('childTests', 'metrics'),
951 });
952
953 App.domainsAreEqual = function (domain1, domain2) {
954     return (!domain1 && !domain2) || (domain1 && domain2 && !(domain1[0] - domain2[0]) && !(domain1[1] - domain2[1]));
955 }
956
957 App.PaneController = Ember.ObjectController.extend({
958     needs: ['charts'],
959     sharedTime: Ember.computed.alias('parentController.sharedTime'),
960     sharedSelection: Ember.computed.alias('parentController.sharedSelection'),
961     selection: null,
962     actions: {
963         toggleDetails: function()
964         {
965             this.toggleProperty('showingDetails');
966         },
967         close: function ()
968         {
969             this.parentController.removePane(this.get('model'));
970         },
971         toggleBugsPane: function ()
972         {
973             if (this.toggleProperty('showingAnalysisPane')) {
974                 this.set('showingSearchPane', false);
975                 this.set('showingStatPane', false);
976             }
977         },
978         toggleShowOutlier: function ()
979         {
980             var pane = this.get('model');
981             pane.toggleProperty('showOutlier');
982             var chartData = pane.get('chartData');
983             if (!chartData)
984                 return;
985             pane._setNewChartData(chartData);
986         },
987         createAnalysisTask: function ()
988         {
989             var name = this.get('newAnalysisTaskName');
990             var points = this.get('selectedPoints');
991             Ember.assert('The analysis name should not be empty', name);
992             Ember.assert('There should be at least two points in the range', points && points.length >= 2);
993
994             var newWindow = window.open();
995             var self = this;
996             App.AnalysisTask.create(name, points[0].measurement, points[points.length - 1].measurement).then(function (data) {
997                 // FIXME: Update the UI to show the new analysis task.
998                 var url = App.Router.router.generate('analysisTask', data['taskId']);
999                 newWindow.location.href = '#' + url;
1000                 self.get('model').fetchAnalyticRanges();
1001             }, function (error) {
1002                 newWindow.close();
1003                 if (error === 'DuplicateAnalysisTask') {
1004                     // FIXME: Duplicate this error more gracefully.
1005                 }
1006                 alert(error);
1007             });
1008         },
1009         toggleSearchPane: function ()
1010         {
1011             if (!App.Manifest.repositoriesWithReportedCommits)
1012                 return;
1013             var model = this.get('model');
1014             if (!model.get('commitSearchRepository'))
1015                 model.set('commitSearchRepository', App.Manifest.repositoriesWithReportedCommits[0]);
1016             if (this.toggleProperty('showingSearchPane')) {
1017                 this.set('showingAnalysisPane', false);
1018                 this.set('showingStatPane', false);
1019             }
1020         },
1021         searchCommit: function () {
1022             var model = this.get('model');
1023             model.searchCommit(model.get('commitSearchRepository'), model.get('commitSearchKeyword'));                
1024         },
1025         toggleStatPane: function ()
1026         {
1027             if (this.toggleProperty('showingStatPane')) {
1028                 this.set('showingSearchPane', false);
1029                 this.set('showingAnalysisPane', false);
1030             }
1031         },
1032         zoomed: function (selection)
1033         {
1034             this.set('mainPlotDomain', selection ? selection : this.get('overviewDomain'));
1035             if (selection)
1036                 this.set('overviewSelection', selection);
1037             Ember.run.debounce(this, 'propagateZoom', 100);
1038         },
1039     },
1040     _overviewSelectionChanged: function ()
1041     {
1042         var overviewSelection = this.get('overviewSelection');
1043         if (App.domainsAreEqual(overviewSelection, this.get('mainPlotDomain')))
1044             return;
1045         this.set('mainPlotDomain', overviewSelection || this.get('overviewDomain'));
1046         Ember.run.debounce(this, 'propagateZoom', 100);
1047     }.observes('overviewSelection'),
1048     _sharedDomainChanged: function ()
1049     {
1050         var newDomain = this.get('parentController').get('sharedDomain');
1051         if (App.domainsAreEqual(newDomain, this.get('overviewDomain')))
1052             return;
1053         this.set('overviewDomain', newDomain);
1054         if (!this.get('overviewSelection'))
1055             this.set('mainPlotDomain', newDomain);
1056     }.observes('parentController.sharedDomain').on('init'),
1057     propagateZoom: function ()
1058     {
1059         this.get('parentController').set('sharedZoom', this.get('mainPlotDomain'));
1060     },
1061     _sharedZoomChanged: function ()
1062     {
1063         var newSelection = this.get('parentController').get('sharedZoom');
1064         if (App.domainsAreEqual(newSelection, this.get('mainPlotDomain')))
1065             return;
1066         this.set('mainPlotDomain', newSelection || this.get('overviewDomain'));
1067         this.set('overviewSelection', newSelection);
1068     }.observes('parentController.sharedZoom').on('init'),
1069     _updateCanAnalyze: function ()
1070     {
1071         var pane = this.get('model');
1072         var points = pane.get('selectedPoints');
1073         this.set('cannotAnalyze', !this.get('newAnalysisTaskName') || !points || points.length < 2);
1074         this.set('cannotMarkOutlier', !!points || !this.get('selectedItem'));
1075
1076         var selectedMeasurement = this.selectedMeasurement();
1077         this.set('selectedItemIsMarkedOutlier', selectedMeasurement && selectedMeasurement.markedOutlier());
1078
1079     }.observes('newAnalysisTaskName', 'model.selectedPoints', 'model.selectedItem').on('init'),
1080     selectedMeasurement: function () {
1081         var chartData = this.get('model').get('chartData');
1082         var selectedItem = this.get('selectedItem');
1083         if (!chartData || !selectedItem)
1084             return null;
1085         var point = chartData.current.findPointByMeasurementId(selectedItem);
1086         Ember.assert('selectedItem should always be in the current chart data', point);
1087         return point.measurement;
1088     },
1089     showOutlierTitle: function ()
1090     {
1091         return this.get('showOutlier') ? 'Hide outliers' : 'Show outliers';
1092     }.property('showOutlier'),
1093     _selectedItemIsMarkedOutlierDidChange: function ()
1094     {
1095         var selectedMeasurement = this.selectedMeasurement();
1096         if (!selectedMeasurement)
1097             return;
1098         var selectedItemIsMarkedOutlier = this.get('selectedItemIsMarkedOutlier');
1099         if (selectedMeasurement.markedOutlier() == selectedItemIsMarkedOutlier)
1100             return;
1101         var pane = this.get('model');
1102         selectedMeasurement.setMarkedOutlier(!!selectedItemIsMarkedOutlier).then(function () {
1103             alert(selectedItemIsMarkedOutlier ? 'Marked the point as an outlier' : 'The point is no longer marked as an outlier');
1104             pane.refetchRuns();
1105         }, function (error) {
1106             alert('Failed to update the status:' + error);
1107         });
1108     }.observes('selectedItemIsMarkedOutlier'),
1109 });
1110
1111 App.AnalysisRoute = Ember.Route.extend({
1112     model: function () {
1113         return this.store.findAll('analysisTask').then(function (tasks) {
1114             return Ember.Object.create({'tasks': tasks.sortBy('createdAt').toArray().reverse()});
1115         });
1116     },
1117 });
1118
1119 App.AnalysisTaskRoute = Ember.Route.extend({
1120     model: function (param)
1121     {
1122         return this.store.find('analysisTask', param.taskId);
1123     },
1124 });
1125
1126 App.AnalysisTaskController = Ember.Controller.extend({
1127     label: Ember.computed.alias('model.name'),
1128     platform: Ember.computed.alias('model.platform'),
1129     metric: Ember.computed.alias('model.metric'),
1130     details: Ember.computed.alias('pane.details'),
1131     roots: [],
1132     bugTrackers: [],
1133     possibleRepetitionCounts: [1, 2, 3, 4, 5, 6],
1134     analysisResultOptions: [
1135         {label: 'Still in investigation', result: null},
1136         {label: 'Inconclusive', result: 'inconclusive', needed: true},
1137         {label: 'Definite progression', result: 'progression', needed: true},
1138         {label: 'Definite regression', result: 'regression', needed: true},
1139         {label: 'No change', result: 'unchanged', needsFeedback: true},
1140     ],
1141     shouldNotHaveBeenCreated: false,
1142     needsFeedback: function ()
1143     {
1144         var chosen = this.get('chosenAnalysisResult');
1145         return chosen && chosen.needsFeedback;
1146     }.property('chosenAnalysisResult'),
1147     _updateChosenAnalysisResult: function ()
1148     {
1149         var analysisTask = this.get('model');
1150         if (!analysisTask)
1151             return;
1152         var currentResult = analysisTask.get('result');
1153         for (var option of this.analysisResultOptions) {
1154             if (option.result == currentResult) {
1155                 this.set('chosenAnalysisResult', option);
1156                 break;                
1157             }
1158         }
1159     }.observes('model'),
1160     _taskUpdated: function ()
1161     {
1162         var model = this.get('model');
1163         if (!model)
1164             return;
1165
1166         App.Manifest.fetch(this.store).then(this._fetchedManifest.bind(this));
1167         this.set('pane', App.Pane.create({
1168             store: this.store,
1169             platformId: model.get('platform').get('id'),
1170             metricId: model.get('metric').get('id'),
1171         }));
1172
1173         var self = this;
1174         model.get('testGroups').then(function (groups) {
1175             self.set('testGroupPanes', groups.map(function (group) { return App.TestGroupPane.create({content: group}); }));
1176         });
1177     }.observes('model', 'model.testGroups').on('init'),
1178     _fetchedManifest: function ()
1179     {
1180         var trackerIdToBugNumber = {};
1181         this.get('model').get('bugs').forEach(function (bug) {
1182             trackerIdToBugNumber[bug.get('bugTracker').get('id')] = bug.get('number');
1183         });
1184
1185         this.set('bugTrackers', App.Manifest.get('bugTrackers').map(function (bugTracker) {
1186             var bugNumber = trackerIdToBugNumber[bugTracker.get('id')];
1187             return Ember.ObjectProxy.create({
1188                 elementId: 'bug-' + bugTracker.get('id'),
1189                 content: bugTracker,
1190                 bugNumber: bugNumber,
1191                 bugUrl: bugTracker.urlFromBugNumber(bugNumber),
1192                 editedBugNumber: bugNumber,
1193             });
1194         }));
1195     },
1196     _chartDataChanged: function ()
1197     {
1198         var pane = this.get('pane');
1199         if (!pane)
1200             return;
1201
1202         var chartData = pane.get('chartData');
1203         if (!chartData)
1204             return null;
1205
1206         var currentTimeSeries = chartData.current;
1207         if (!currentTimeSeries)
1208             return null; // FIXME: Report an error.
1209
1210         var start = currentTimeSeries.findPointByMeasurementId(this.get('model').get('startRun'));
1211         var end = currentTimeSeries.findPointByMeasurementId(this.get('model').get('endRun'));
1212         if (!start || !end)
1213             return null; // FIXME: Report an error.
1214
1215         var highlightedItems = {};
1216         highlightedItems[start.measurement.id()] = true;
1217         highlightedItems[end.measurement.id()] = true;
1218
1219         var formatedPoints = currentTimeSeries.seriesBetweenPoints(start, end).map(function (point, index) {
1220             return {
1221                 id: point.measurement.id(),
1222                 measurement: point.measurement,
1223                 label: 'Point ' + (index + 1),
1224                 value: chartData.formatter(point.value),
1225             };
1226         });
1227
1228         var margin = (end.time - start.time) * 0.1;
1229         this.set('highlightedItems', highlightedItems);
1230         this.set('overviewEndPoints', [start, end]);
1231         this.set('analysisPoints', formatedPoints);
1232
1233         var overviewDomain = [start.time - margin, +end.time + margin];
1234
1235         var testGroupPanes = this.get('testGroupPanes');
1236         if (testGroupPanes) {
1237             testGroupPanes.setEach('overviewPane', pane);
1238             testGroupPanes.setEach('overviewDomain', overviewDomain);
1239         }
1240
1241         this.set('overviewDomain', overviewDomain);
1242     }.observes('pane.chartData'),
1243     updateRootConfigurations: function ()
1244     {
1245         var analysisPoints = this.get('analysisPoints');
1246         if (!analysisPoints)
1247             return;
1248         var repositoryToRevisions = {};
1249         analysisPoints.forEach(function (point, pointIndex) {
1250             var revisions = point.measurement.formattedRevisions();
1251             for (var repositoryId in revisions) {
1252                 if (!repositoryToRevisions[repositoryId])
1253                     repositoryToRevisions[repositoryId] = new Array(analysisPoints.length);
1254                 var revision = revisions[repositoryId];
1255                 repositoryToRevisions[repositoryId][pointIndex] = {
1256                     label: point.label + ': ' + revision.label,
1257                     value: revision.currentRevision,
1258                 };
1259             }
1260         });
1261
1262         var self = this;
1263         this.get('model').get('triggerable').then(function (triggerable) {
1264             if (!triggerable)
1265                 return;
1266
1267             self.set('configurations', ['A', 'B']);
1268             self.set('rootConfigurations', triggerable.get('acceptedRepositories').map(function (repository) {
1269                 var repositoryId = repository.get('id');
1270                 var options = [{label: 'None'}].concat((repositoryToRevisions[repositoryId] || []).map(function (option, index) {
1271                     if (!option || !option['value'])
1272                         return {value: '', label: analysisPoints[index].label + ': None'}; 
1273                     return option;
1274                 }));
1275                 return Ember.Object.create({
1276                     repository: repository,
1277                     name: repository.get('name'),
1278                     sets: [
1279                         Ember.Object.create({name: 'A[' + repositoryId + ']',
1280                             options: options,
1281                             selection: options[1]}),
1282                         Ember.Object.create({name: 'B[' + repositoryId + ']',
1283                             options: options,
1284                             selection: options[options.length - 1]}),
1285                     ],
1286                 });
1287             }));
1288         });
1289     }.observes('analysisPoints'),
1290     actions: {
1291         addBug: function (bugTracker, bugNumber)
1292         {
1293             var model = this.get('model');
1294             if (!bugTracker)
1295                 bugTracker = this.get('bugTrackers').objectAt(0);
1296             var bug = {task: this.get('model'), bugTracker: bugTracker.get('content'), number: bugNumber};
1297             this.store.createRecord('bug', bug).save().then(function () {
1298                 alert('Associated the ' + bugTracker.get('name') + ' ' + bugNumber + ' with this analysis.');
1299             }, function (error) {
1300                 alert('Failed to associate the bug: ' + error);
1301             });
1302         },
1303         deleteBug: function (bug)
1304         {
1305             bug.destroyRecord().then(function () {
1306                 alert('Successfully deassociated the bug.');
1307             }, function (error) {
1308                 alert('Failed to disassociate the bug: ' + error);
1309             });
1310         },
1311         saveStatus: function ()
1312         {
1313             var chosenResult = this.get('chosenAnalysisResult');
1314             var analysisTask = this.get('model');
1315             analysisTask.set('result', chosenResult.result);
1316             if (chosenResult.needed)
1317                 analysisTask.set('needed', true);
1318             else if (chosenResult.needsFeedback && this.get('notNeeded'))
1319                 analysisTask.set('needed', false);
1320             else
1321                 analysisTask.set('needed', null);
1322
1323             analysisTask.saveStatus().then(function () {
1324                 alert('Saved the status');
1325             }, function (error) {
1326                 alert('Failed to save the status: ' + error);
1327             });
1328         },
1329         createTestGroup: function (name, repetitionCount)
1330         {
1331             var analysisTask = this.get('model');
1332             if (analysisTask.get('testGroups').isAny('name', name)) {
1333                 alert('Cannot create two test groups of the same name.');
1334                 return;
1335             }
1336
1337             var roots = {};
1338             var rootConfigurations = this.get('rootConfigurations').toArray();
1339             for (var root of rootConfigurations) {
1340                 var sets = root.get('sets');
1341                 var hasSelection = function (item) { return item.get('selection') && item.get('selection').value; };
1342                 if (!sets.any(hasSelection))
1343                     continue;
1344                 if (!sets.every(hasSelection)) {
1345                     alert('Only some configuration specifies ' + root.get('name'));
1346                     return;
1347                 }
1348                 roots[root.get('name')] = sets.map(function (item) { return item.get('selection').value; });                
1349             }
1350
1351             App.TestGroup.create(analysisTask, name, roots, repetitionCount).then(function () {
1352             }, function (error) {
1353                 alert('Failed to create a new test group:' + error);
1354             });
1355         },
1356         toggleShowRequestList: function (configuration)
1357         {
1358             configuration.toggleProperty('showRequestList');
1359         }
1360     },
1361     _updateRootsBySelectedPoints: function ()
1362     {
1363         var rootConfigurations = this.get('rootConfigurations');
1364         var pane = this.get('pane');
1365         if (!rootConfigurations || !pane)
1366             return;
1367
1368         var rootSetPoints;
1369         var selectedPoints = pane.get('selectedPoints');
1370         if (selectedPoints && selectedPoints.length >= 2)
1371             rootSetPoints = [selectedPoints[0], selectedPoints[selectedPoints.length - 1]];
1372         else
1373             rootSetPoints = this.get('overviewEndPoints');
1374         if (!rootSetPoints)
1375             return;
1376
1377         rootConfigurations.forEach(function (root) {
1378             root.get('sets').forEach(function (set, setIndex) {
1379                 if (setIndex >= rootSetPoints.length)
1380                     return;
1381                 var targetRevision = rootSetPoints[setIndex].measurement.revisionForRepository(root.get('repository').get('id'));
1382                 var selectedOption;
1383                 if (targetRevision)
1384                     selectedOption = set.get('options').find(function (option) { return option.value == targetRevision; });
1385                 set.set('selection', selectedOption || set.get('options')[0]);
1386             });
1387         });
1388
1389     }.observes('pane.selectedPoints'),
1390 });
1391
1392 App.TestGroupPane = Ember.ObjectProxy.extend({
1393     _populate: function ()
1394     {
1395         var buildRequests = this.get('buildRequests');
1396         var testResults = this.get('testResults');
1397         if (!buildRequests || !testResults)
1398             return [];
1399
1400         var repositories = this._computeRepositoryList();
1401         this.set('repositories', repositories);
1402
1403         var requestsByRooSet = this._groupRequestsByConfigurations(buildRequests);
1404
1405         var configurations = [];
1406         var index = 0;
1407         var range = {min: Infinity, max: -Infinity};
1408         for (var rootSetId in requestsByRooSet) {
1409             var configLetter = String.fromCharCode('A'.charCodeAt(0) + index++);
1410             configurations.push(this._createConfigurationSummary(requestsByRooSet[rootSetId], configLetter, range));
1411         }
1412
1413         var margin = 0.1 * (range.max - range.min);
1414         range.max += margin;
1415         range.min -= margin;
1416
1417         this.set('configurations', configurations);
1418
1419         var probabilityFormatter = d3.format('.2p');
1420         var comparisons = [];
1421         for (var i = 0; i < configurations.length - 1; i++) {
1422             var summary1 = configurations[i].summary;
1423             for (var j = i + 1; j < configurations.length; j++) {
1424                 var summary2 = configurations[j].summary;
1425
1426                 var valueDelta = testResults.deltaFormatter(summary2.value - summary1.value);
1427                 var relativeDelta = d3.format('+.2p')((summary2.value - summary1.value) / summary1.value);
1428
1429                 var stat = this._computeStatisticalSignificance(summary1.measuredValues, summary2.measuredValues);
1430                 comparisons.push({
1431                     label: summary1.configLetter + ' / ' + summary2.configLetter,
1432                     difference: isNaN(summary1.value) || isNaN(summary2.value) ? 'N/A' : valueDelta + ' (' + relativeDelta + ') ',
1433                     result: stat,
1434                 });
1435             }
1436         }
1437         this.set('comparisons', comparisons);
1438     }.observes('testResults', 'buildRequests'),
1439     _computeStatisticalSignificance: function (values1, values2)
1440     {
1441         var tFormatter = d3.format('.3g');
1442         var probabilityFormatter = d3.format('.2p');
1443         var statistics = Statistics.probabilityRangeForWelchsT(values1, values2);
1444         if (isNaN(statistics.t) || isNaN(statistics.degreesOfFreedom))
1445             return 'N/A';
1446
1447         var details = ' (t=' + tFormatter(statistics.t) + ' df=' + tFormatter(statistics.degreesOfFreedom) + ')';
1448
1449         if (!statistics.range[0])
1450             return 'Not significant' + details;
1451
1452         var lowerLimit = probabilityFormatter(statistics.range[0]);
1453         if (!statistics.range[1])
1454             return 'Significance > ' + lowerLimit + details;
1455
1456         return lowerLimit + ' < Significance < ' + probabilityFormatter(statistics.range[1]) + details;
1457     },
1458     _updateReferenceChart: function ()
1459     {
1460         var configurations = this.get('configurations');
1461         var chartData = this.get('overviewPane') ? this.get('overviewPane').get('chartData') : null;
1462         if (!configurations || !chartData || this.get('referenceChart'))
1463             return;
1464
1465         var currentTimeSeries = chartData.current;
1466         if (!currentTimeSeries)
1467             return;
1468
1469         var repositories = this.get('repositories');
1470         var highlightedItems = {};
1471         var failedToFindPoint = false;
1472         configurations.forEach(function (config) {
1473             var revisions = {};
1474             config.get('rootSet').get('roots').forEach(function (root) {
1475                 revisions[root.get('repository').get('id')] = root.get('revision');
1476             });
1477             var point = currentTimeSeries.findPointByRevisions(revisions);
1478             if (!point) {
1479                 failedToFindPoint = true;
1480                 return;
1481             }
1482             highlightedItems[point.measurement.id()] = true;
1483         });
1484         if (failedToFindPoint)
1485             return;
1486
1487         this.set('referenceChart', {
1488             data: chartData,
1489             highlightedItems: highlightedItems,
1490         });
1491     }.observes('configurations', 'overviewPane.chartData'),
1492     _computeRepositoryList: function ()
1493     {
1494         var specifiedRepositories = new Ember.Set();
1495         (this.get('rootSets') || []).forEach(function (rootSet) {
1496             (rootSet.get('roots') || []).forEach(function (root) {
1497                 specifiedRepositories.add(root.get('repository'));
1498             });
1499         });
1500         var reportedRepositories = new Ember.Set();
1501         var testResults = this.get('testResults');
1502         (this.get('buildRequests') || []).forEach(function (request) {
1503             var point = testResults.current.findPointByBuild(request.get('build'));
1504             if (!point)
1505                 return;
1506
1507             var revisionByRepositoryId = point.measurement.formattedRevisions();
1508             for (var repositoryId in revisionByRepositoryId) {
1509                 var repository = App.Manifest.repository(repositoryId);
1510                 if (!specifiedRepositories.contains(repository))
1511                     reportedRepositories.add(repository);
1512             }
1513         });
1514         return specifiedRepositories.sortBy('name').concat(reportedRepositories.sortBy('name'));
1515     },
1516     _groupRequestsByConfigurations: function (requests, repositoryList)
1517     {
1518         var rootSetIdToRequests = {};
1519         var testGroup = this;
1520         requests.forEach(function (request) {
1521             var rootSetId = request.get('rootSet').get('id');
1522             if (!rootSetIdToRequests[rootSetId])
1523                 rootSetIdToRequests[rootSetId] = [];
1524             rootSetIdToRequests[rootSetId].push(request);
1525         });
1526         return rootSetIdToRequests;
1527     },
1528     _createConfigurationSummary: function (buildRequests, configLetter, range)
1529     {
1530         var repositories = this.get('repositories');
1531         var testResults = this.get('testResults');
1532         var requests = buildRequests.map(function (originalRequest) {
1533             var point = testResults.current.findPointByBuild(originalRequest.get('build'));
1534             var revisionByRepositoryId = point ? point.measurement.formattedRevisions() : {};
1535             return Ember.ObjectProxy.create({
1536                 content: originalRequest,
1537                 revisionList: repositories.map(function (repository, index) {
1538                     return (revisionByRepositoryId[repository.get('id')] || {label:null}).label;
1539                 }),
1540                 value: point ? point.value : null,
1541                 valueRange: range,
1542                 formattedValue: point ? testResults.formatter(point.value) : null,
1543                 buildLabel: point ? 'Build ' + point.measurement.buildNumber() : null,
1544             });
1545         });
1546
1547         var rootSet = requests ? requests[0].get('rootSet') : null;
1548         var summaryRevisions = repositories.map(function (repository, index) {
1549             var revision = rootSet ? rootSet.revisionForRepository(repository) : null;
1550             if (!revision)
1551                 return requests[0].get('revisionList')[index];
1552             return Measurement.formatRevisionRange(revision).label;
1553         });
1554
1555         requests.forEach(function (request) {
1556             var revisionList = request.get('revisionList');
1557             repositories.forEach(function (repository, index) {
1558                 if (revisionList[index] == summaryRevisions[index])
1559                     revisionList[index] = null;
1560             });
1561         });
1562
1563         var valuesInConfig = requests.mapBy('value').filter(function (value) { return typeof(value) === 'number' && !isNaN(value); });
1564         var sum = Statistics.sum(valuesInConfig);
1565         var ciDelta = Statistics.confidenceIntervalDelta(0.95, valuesInConfig.length, sum, Statistics.squareSum(valuesInConfig));
1566         var mean = sum / valuesInConfig.length;
1567
1568         range.min = Math.min(range.min, Statistics.min(valuesInConfig));
1569         range.max = Math.max(range.max, Statistics.max(valuesInConfig));
1570         if (ciDelta && !isNaN(ciDelta)) {
1571             range.min = Math.min(range.min, mean - ciDelta);
1572             range.max = Math.max(range.max, mean + ciDelta);
1573         }
1574
1575         var summary = Ember.Object.create({
1576             isAverage: true,
1577             configLetter: configLetter,
1578             revisionList: summaryRevisions,
1579             formattedValue: isNaN(mean) ? null : testResults.formatWithDeltaAndUnit(mean, ciDelta),
1580             value: mean,
1581             measuredValues: valuesInConfig,
1582             confidenceIntervalDelta: ciDelta,
1583             valueRange: range,
1584             statusLabel: App.BuildRequest.aggregateStatuses(requests),
1585         });
1586
1587         return Ember.Object.create({summary: summary, requests: requests, rootSet: rootSet});
1588     },
1589 });
1590
1591 App.BoxPlotComponent = Ember.Component.extend({
1592     classNames: ['box-plot'],
1593     range: null,
1594     value: null,
1595     delta: null,
1596     didInsertElement: function ()
1597     {
1598         var element = this.get('element');
1599         var svg = d3.select(element).append('svg')
1600             .attr('viewBox', '0 0 100 20')
1601             .attr('preserveAspectRatio', 'none')
1602             .style({width: '100%', height: '100%'});
1603
1604         this._percentageRect = svg
1605             .append('rect')
1606             .attr('x', 0)
1607             .attr('y', 0)
1608             .attr('width', 0)
1609             .attr('height', 20)
1610             .attr('class', 'percentage');
1611
1612         this._deltaRect = svg
1613             .append('rect')
1614             .attr('x', 0)
1615             .attr('y', 5)
1616             .attr('width', 0)
1617             .attr('height', 10)
1618             .attr('class', 'delta')
1619             .attr('opacity', 0.5)
1620         this._updateBars();
1621     },
1622     _updateBars: function ()
1623     {
1624         if (!this._percentageRect || typeof(this._percentage) !== 'number' || isNaN(this._percentage))
1625             return;
1626
1627         this._percentageRect.attr('width', this._percentage);
1628         if (typeof(this._delta) === 'number' && !isNaN(this._delta)) {
1629             this._deltaRect.attr('x', this._percentage - this._delta);
1630             this._deltaRect.attr('width', this._delta * 2);
1631         }
1632     },
1633     valueChanged: function ()
1634     {
1635         var range = this.get('range');
1636         var value = this.get('value');
1637         if (!range || !value)
1638             return;
1639         var scalingFactor = 100 / (range.max - range.min);
1640         var percentage = (value - range.min) * scalingFactor;
1641         this._percentage = percentage;
1642         this._delta = this.get('delta') * scalingFactor;
1643         this._updateBars();
1644     }.observes('value', 'range').on('init'),
1645 });