Perf dashboard should have the ability to post A/B testing builds
[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('charts', {path: 'charts'});
5     this.resource('analysis', {path: 'analysis'});
6     this.resource('analysisTask', {path: 'analysis/task/:taskId'});
7 });
8
9 App.DashboardRow = Ember.Object.extend({
10     header: null,
11     cells: [],
12
13     init: function ()
14     {
15         this._super();
16
17         var cellsInfo = this.get('cellsInfo') || [];
18         var columnCount = this.get('columnCount');
19         while (cellsInfo.length < columnCount)
20             cellsInfo.push([]);
21
22         this.set('cells', cellsInfo.map(this._createPane.bind(this)));
23     },
24     addPane: function (paneInfo)
25     {
26         var pane = this._createPane(paneInfo);
27         this.get('cells').pushObject(pane);
28         this.set('columnCount', this.get('columnCount') + 1);
29     },
30     _createPane: function (paneInfo)
31     {
32         if (!paneInfo || !paneInfo.length || (!paneInfo[0] && !paneInfo[1]))
33             paneInfo = null;
34
35         var pane = App.Pane.create({
36             store: this.get('store'),
37             platformId: paneInfo ? paneInfo[0] : null,
38             metricId: paneInfo ? paneInfo[1] : null,
39         });
40
41         return App.DashboardPaneProxyForPicker.create({content: pane});
42     },
43 });
44
45 App.DashboardPaneProxyForPicker = Ember.ObjectProxy.extend({
46     _platformOrMetricIdChanged: function ()
47     {
48         var self = this;
49         App.buildPopup(this.get('store'), 'choosePane', this)
50             .then(function (platforms) { self.set('pickerData', platforms); });
51     }.observes('platformId', 'metricId').on('init'),
52     paneList: function () {
53         return App.encodePrettifiedJSON([[this.get('platformId'), this.get('metricId'), null, null, false]]);
54     }.property('platformId', 'metricId'),
55 });
56
57 App.IndexController = Ember.Controller.extend({
58     queryParams: ['grid', 'numberOfDays'],
59     _previousGrid: {},
60     headerColumns: [],
61     rows: [],
62     numberOfDays: 30,
63     editMode: false,
64
65     gridChanged: function ()
66     {
67         var grid = this.get('grid');
68         if (grid === this._previousGrid)
69             return;
70
71         var dashboard = null;
72         if (grid) {
73             dashboard = App.Dashboard.create({serialized: grid});
74             if (!dashboard.get('headerColumns').length)
75                 dashboard = null;
76         }
77         if (!dashboard)
78             dashboard = App.Manifest.get('defaultDashboard');
79         if (!dashboard)
80             return;
81
82         var headerColumns = dashboard.get('headerColumns');
83         this.set('headerColumns', headerColumns);
84         var columnCount = headerColumns.length;
85         this.set('columnCount', columnCount);
86
87         var store = this.store;
88         this.set('rows', dashboard.get('rows').map(function (rowParam) {
89             return App.DashboardRow.create({
90                 store: store,
91                 header: rowParam[0],
92                 cellsInfo: rowParam.slice(1),
93                 columnCount: columnCount,
94             })
95         }));
96
97         this.set('emptyRow', new Array(columnCount));
98     }.observes('grid', 'App.Manifest.defaultDashboard').on('init'),
99
100     updateGrid: function()
101     {
102         var headers = this.get('headerColumns').map(function (header) { return header.label; });
103         var table = [headers].concat(this.get('rows').map(function (row) {
104             return [row.get('header')].concat(row.get('cells').map(function (pane) {
105                 var platformAndMetric = [pane.get('platformId'), pane.get('metricId')];
106                 return platformAndMetric[0] || platformAndMetric[1] ? platformAndMetric : [];
107             }));
108         }));
109         this._previousGrid = JSON.stringify(table);
110         this.set('grid', this._previousGrid);
111     },
112
113     _sharedDomainChanged: function ()
114     {
115         var numberOfDays = this.get('numberOfDays');
116         if (!numberOfDays)
117             return;
118
119         numberOfDays = parseInt(numberOfDays);
120         var present = Date.now();
121         var past = present - numberOfDays * 24 * 3600 * 1000;
122         this.set('sharedDomain', [past, present]);
123     }.observes('numberOfDays').on('init'),
124
125     actions: {
126         setNumberOfDays: function (numberOfDays)
127         {
128             this.set('numberOfDays', numberOfDays);
129         },
130         choosePane: function (param)
131         {
132             var pane = param.position;
133             pane.set('platformId', param.platform.get('id'));
134             pane.set('metricId', param.metric.get('id'));
135         },
136         addColumn: function ()
137         {
138             this.get('headerColumns').pushObject({
139                 label: this.get('newColumnHeader'),
140                 index: this.get('headerColumns').length,
141             });
142             this.get('rows').forEach(function (row) {
143                 row.addPane();
144             });
145             this.set('newColumnHeader', null);
146         },
147         removeColumn: function (index)
148         {
149             this.get('headerColumns').removeAt(index);
150             this.get('rows').forEach(function (row) {
151                 row.get('cells').removeAt(index);
152             });
153         },
154         addRow: function ()
155         {
156             this.get('rows').pushObject(App.DashboardRow.create({
157                 store: this.store,
158                 header: this.get('newRowHeader'),
159                 columnCount: this.get('columnCount'),
160             }));
161             this.set('newRowHeader', null);
162         },
163         removeRow: function (row)
164         {
165             this.get('rows').removeObject(row);
166         },
167         resetPane: function (pane)
168         {
169             pane.set('platformId', null);
170             pane.set('metricId', null);
171         },
172         toggleEditMode: function ()
173         {
174             this.toggleProperty('editMode');
175             if (!this.get('editMode'))
176                 this.updateGrid();
177         },
178     },
179
180     init: function ()
181     {
182         this._super();
183         App.Manifest.fetch(this.get('store'));
184     }
185 });
186
187 App.NumberOfDaysControlView = Ember.View.extend({
188     classNames: ['controls'],
189     templateName: 'number-of-days-controls',
190     didInsertElement: function ()
191     {
192         this._matchingElements(this._previousNumberOfDaysClass).addClass('active');
193     },
194     _numberOfDaysChanged: function ()
195     {
196         this._matchingElements(this._previousNumberOfDaysClass).removeClass('active');
197
198         var newNumberOfDaysClass = 'numberOfDaysIs' + this.get('numberOfDays');
199         this._matchingElements(this._previousNumberOfDaysClass).addClass('active');
200         this._previousNumberOfDaysClass = newNumberOfDaysClass;
201     }.observes('numberOfDays').on('init'),
202     _matchingElements: function (className)
203     {
204         var element = this.get('element');
205         if (!element)
206             return $([]);
207         return $(element.getElementsByClassName(className));
208     }
209 });
210
211 App.StartTimeSliderView = Ember.View.extend({
212     templateName: 'start-time-slider',
213     classNames: ['start-time-slider'],
214     startTime: Date.now() - 7 * 24 * 3600 * 1000,
215     oldestStartTime: null,
216     _numberOfDaysView: null,
217     _slider: null,
218     _startTimeInSlider: null,
219     _currentNumberOfDays: null,
220     _MILLISECONDS_PER_DAY: 24 * 3600 * 1000,
221
222     didInsertElement: function ()
223     {
224         this.oldestStartTime = Date.now() - 365 * 24 * 3600 * 1000;
225         this._slider = $(this.get('element')).find('input');
226         this._numberOfDaysView = $(this.get('element')).find('.numberOfDays');
227         this._sliderRangeChanged();
228         this._slider.change(this._sliderMoved.bind(this));
229     },
230     _sliderRangeChanged: function ()
231     {
232         var minimumNumberOfDays = 1;
233         var maximumNumberOfDays = this._timeInPastToNumberOfDays(this.get('oldestStartTime'));
234         var precision = 1000; // FIXME: Compute this from maximumNumberOfDays.
235         var slider = this._slider;
236         slider.attr('min', Math.floor(Math.log(Math.max(1, minimumNumberOfDays)) * precision) / precision);
237         slider.attr('max', Math.ceil(Math.log(maximumNumberOfDays) * precision) / precision);
238         slider.attr('step', 1 / precision);
239         this._startTimeChanged();
240     }.observes('oldestStartTime'),
241     _sliderMoved: function ()
242     {
243         this._currentNumberOfDays = Math.round(Math.exp(this._slider.val()));
244         this._numberOfDaysView.text(this._currentNumberOfDays);
245         this._startTimeInSlider = this._numberOfDaysToTimeInPast(this._currentNumberOfDays);
246         this.set('startTime', this._startTimeInSlider);
247     },
248     _startTimeChanged: function ()
249     {
250         var startTime = this.get('startTime');
251         if (startTime == this._startTimeSetBySlider)
252             return;
253         this._currentNumberOfDays = this._timeInPastToNumberOfDays(startTime);
254
255         if (this._slider) {
256             this._numberOfDaysView.text(this._currentNumberOfDays);
257             this._slider.val(Math.log(this._currentNumberOfDays));
258             this._startTimeInSlider = startTime;
259         }
260     }.observes('startTime').on('init'),
261     _timeInPastToNumberOfDays: function (timeInPast)
262     {
263         return Math.max(1, Math.round((Date.now() - timeInPast) / this._MILLISECONDS_PER_DAY));
264     },
265     _numberOfDaysToTimeInPast: function (numberOfDays)
266     {
267         return Date.now() - numberOfDays * this._MILLISECONDS_PER_DAY;
268     },
269 });
270
271 App.Pane = Ember.Object.extend({
272     platformId: null,
273     platform: null,
274     metricId: null,
275     metric: null,
276     selectedItem: null,
277     searchCommit: function (repository, keyword) {
278         var self = this;
279         var repositoryName = repository.get('id');
280         CommitLogs.fetchForTimeRange(repositoryName, null, null, keyword).then(function (commits) {
281             if (self.isDestroyed || !self.get('chartData') || !commits.length)
282                 return;
283             var currentRuns = self.get('chartData').current.timeSeriesByCommitTime().series();
284             if (!currentRuns.length)
285                 return;
286
287             var highlightedItems = {};
288             var commitIndex = 0;
289             for (var runIndex = 0; runIndex < currentRuns.length && commitIndex < commits.length; runIndex++) {
290                 var measurement = currentRuns[runIndex].measurement;
291                 var commitTime = measurement.commitTimeForRepository(repositoryName);
292                 if (!commitTime)
293                     continue;
294                 if (commits[commitIndex].time <= commitTime) {
295                     highlightedItems[measurement.id()] = true;
296                     do {
297                         commitIndex++;
298                     } while (commitIndex < commits.length && commits[commitIndex].time <= commitTime);
299                 }
300             }
301
302             self.set('highlightedItems', highlightedItems);
303         }, function () {
304             // FIXME: Report errors
305             this.set('highlightedItems', {});
306         });
307     },
308     _fetch: function () {
309         var platformId = this.get('platformId');
310         var metricId = this.get('metricId');
311         if (!platformId && !metricId) {
312             this.set('empty', true);
313             return;
314         }
315         this.set('empty', false);
316         this.set('platform', null);
317         this.set('chartData', null);
318         this.set('metric', null);
319         this.set('failure', null);
320
321         if (!this._isValidId(platformId))
322             this.set('failure', platformId ? 'Invalid platform id:' + platformId : 'Platform id was not specified');
323         else if (!this._isValidId(metricId))
324             this.set('failure', metricId ? 'Invalid metric id:' + metricId : 'Metric id was not specified');
325         else {
326             var self = this;
327
328             App.Manifest.fetchRunsWithPlatformAndMetric(this.get('store'), platformId, metricId).then(function (result) {
329                 self.set('platform', result.platform);
330                 self.set('metric', result.metric);
331                 self.set('chartData', result.runs);
332             }, function (result) {
333                 if (!result || typeof(result) === "string")
334                     self.set('failure', 'Failed to fetch the JSON with an error: ' + result);
335                 else if (!result.platform)
336                     self.set('failure', 'Could not find the platform "' + platformId + '"');
337                 else if (!result.metric)
338                     self.set('failure', 'Could not find the metric "' + metricId + '"');
339                 else
340                     self.set('failure', 'An internal error');
341             });
342
343             this.fetchAnalyticRanges();
344         }
345     }.observes('platformId', 'metricId').on('init'),
346     fetchAnalyticRanges: function ()
347     {
348         var platformId = this.get('platformId');
349         var metricId = this.get('metricId');
350         var self = this;
351         this.get('store')
352             .find('analysisTask', {platform: platformId, metric: metricId})
353             .then(function (tasks) {
354                 self.set('analyticRanges', tasks.filter(function (task) { return task.get('startRun') && task.get('endRun'); }));
355             });
356     },
357     _isValidId: function (id)
358     {
359         if (typeof(id) == "number")
360             return true;
361         if (typeof(id) == "string")
362             return !!id.match(/^[A-Za-z0-9_]+$/);
363         return false;
364     }
365 });
366
367 App.encodePrettifiedJSON = function (plain)
368 {
369     function numberIfPossible(string) {
370         return string == parseInt(string) ? parseInt(string) : string;
371     }
372
373     function recursivelyConvertNumberIfPossible(input) {
374         if (input instanceof Array) {
375             return input.map(recursivelyConvertNumberIfPossible);
376         }
377         return numberIfPossible(input);
378     }
379
380     return JSON.stringify(recursivelyConvertNumberIfPossible(plain))
381         .replace(/\[/g, '(').replace(/\]/g, ')').replace(/\,/g, '-');
382 }
383
384 App.decodePrettifiedJSON = function (encoded)
385 {
386     var parsed = encoded.replace(/\(/g, '[').replace(/\)/g, ']').replace(/\-/g, ',');
387     try {
388         return JSON.parse(parsed);
389     } catch (exception) {
390         return null;
391     }
392 }
393
394 App.ChartsController = Ember.Controller.extend({
395     queryParams: ['paneList', 'zoom', 'since'],
396     needs: ['pane'],
397     _currentEncodedPaneList: null,
398     panes: [],
399     platforms: null,
400     sharedZoom: null,
401     startTime: null,
402     present: Date.now(),
403     defaultSince: Date.now() - 7 * 24 * 3600 * 1000,
404
405     addPane: function (pane)
406     {
407         this.panes.unshiftObject(pane);
408     },
409
410     removePane: function (pane)
411     {
412         this.panes.removeObject(pane);
413     },
414
415     refreshPanes: function()
416     {
417         var paneList = this.get('paneList');
418         if (paneList === this._currentEncodedPaneList)
419             return;
420
421         var panes = this._parsePaneList(paneList || '[]');
422         if (!panes) {
423             console.log('Failed to parse', jsonPaneList, exception);
424             return;
425         }
426         this.set('panes', panes);
427         this._currentEncodedPaneList = paneList;
428     }.observes('paneList').on('init'),
429
430     refreshZoom: function()
431     {
432         var zoom = this.get('zoom');
433         if (!zoom) {
434             this.set('sharedZoom', null);
435             return;
436         }
437
438         zoom = zoom.split('-');
439         var selection = new Array(2);
440         try {
441             selection[0] = new Date(parseFloat(zoom[0]));
442             selection[1] = new Date(parseFloat(zoom[1]));
443         } catch (error) {
444             console.log('Failed to parse the zoom', zoom);
445         }
446         this.set('sharedZoom', selection);
447
448         var startTime = this.get('startTime');
449         if (startTime && startTime > selection[0])
450             this.set('startTime', selection[0]);
451
452     }.observes('zoom').on('init'),
453
454     _startTimeChanged: function () {
455         this.set('sharedDomain', [this.get('startTime'), this.get('present')]);
456         this._scheduleQueryStringUpdate();
457     }.observes('startTime'),
458
459     _sinceChanged: function () {
460         var since = parseInt(this.get('since'));
461         if (isNaN(since))
462             since = this.defaultSince;
463         this.set('startTime', new Date(since));
464     }.observes('since').on('init'),
465
466     _parsePaneList: function (encodedPaneList)
467     {
468         var parsedPaneList = App.decodePrettifiedJSON(encodedPaneList);
469         if (!parsedPaneList)
470             return null;
471
472         // Don't re-create all panes.
473         var self = this;
474         return parsedPaneList.map(function (paneInfo) {
475             var timeRange = null;
476             if (paneInfo[3] && paneInfo[3] instanceof Array) {
477                 var timeRange = paneInfo[3];
478                 try {
479                     timeRange = [new Date(timeRange[0]), new Date(timeRange[1])];
480                 } catch (error) {
481                     console.log("Failed to parse the time range:", timeRange, error);
482                 }
483             }
484             return App.Pane.create({
485                 store: self.store,
486                 info: paneInfo,
487                 platformId: paneInfo[0],
488                 metricId: paneInfo[1],
489                 selectedItem: paneInfo[2],
490                 timeRange: timeRange,
491                 timeRangeIsLocked: !!paneInfo[4],
492             });
493         });
494     },
495
496     _serializePaneList: function (panes)
497     {
498         if (!panes.length)
499             return undefined;
500         return App.encodePrettifiedJSON(panes.map(function (pane) {
501             return [
502                 pane.get('platformId'),
503                 pane.get('metricId'),
504                 pane.get('selectedItem'),
505                 pane.get('timeRange') ? pane.get('timeRange').map(function (date) { return date.getTime() }) : null,
506                 !!pane.get('timeRangeIsLocked'),
507             ];
508         }));
509     },
510
511     _scheduleQueryStringUpdate: function ()
512     {
513         Ember.run.debounce(this, '_updateQueryString', 1000);
514     }.observes('sharedZoom', 'panes.@each.platform', 'panes.@each.metric', 'panes.@each.selectedItem',
515         'panes.@each.timeRange', 'panes.@each.timeRangeIsLocked'),
516
517     _updateQueryString: function ()
518     {
519         this._currentEncodedPaneList = this._serializePaneList(this.get('panes'));
520         this.set('paneList', this._currentEncodedPaneList);
521
522         var zoom = undefined;
523         var sharedZoom = this.get('sharedZoom');
524         if (sharedZoom && !App.domainsAreEqual(sharedZoom, this.get('sharedDomain')))
525             zoom = +sharedZoom[0] + '-' + +sharedZoom[1];
526         this.set('zoom', zoom);
527
528         if (this.get('startTime') - this.defaultSince)
529             this.set('since', this.get('startTime') - 0);
530     },
531
532     actions: {
533         addPaneByMetricAndPlatform: function (param)
534         {
535             this.addPane(App.Pane.create({
536                 store: this.store,
537                 platformId: param.platform.get('id'),
538                 metricId: param.metric.get('id'),
539                 showingDetails: false
540             }));
541         },
542     },
543
544     init: function ()
545     {
546         this._super();
547         var self = this;
548         App.buildPopup(this.store, 'addPaneByMetricAndPlatform').then(function (platforms) {
549             self.set('platforms', platforms);
550         });
551     },
552 });
553
554 App.buildPopup = function(store, action, position)
555 {
556     return App.Manifest.fetch(store).then(function () {
557         return App.Manifest.get('platforms').map(function (platform) {
558             return App.PlatformProxyForPopup.create({content: platform,
559                 action: action, position: position});
560         });
561     });
562 }
563
564 App.PlatformProxyForPopup = Ember.ObjectProxy.extend({
565     children: function ()
566     {
567         var platform = this.content;
568         var containsTest = this.content.containsTest.bind(this.content);
569         var action = this.get('action');
570         var position = this.get('position');
571         return App.Manifest.get('topLevelTests')
572             .filter(containsTest)
573             .map(function (test) {
574                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
575             });
576     }.property('App.Manifest.topLevelTests'),
577 });
578
579 App.TestProxyForPopup = Ember.ObjectProxy.extend({
580     platform: null,
581     children: function ()
582     {
583         var platform = this.get('platform');
584         var action = this.get('action');
585         var position = this.get('position');
586
587         var childTests = this.get('childTests')
588             .filter(function (test) { return platform.containsTest(test); })
589             .map(function (test) {
590                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
591             });
592
593         var metrics = this.get('metrics')
594             .filter(function (metric) { return platform.containsMetric(metric); })
595             .map(function (metric) {
596                 var aggregator = metric.get('aggregator');
597                 return {
598                     actionName: action,
599                     actionArgument: {platform: platform, metric: metric, position:position},
600                     label: metric.get('label')
601                 };
602             });
603
604         if (childTests.length && metrics.length)
605             metrics.push({isSeparator: true});
606
607         return metrics.concat(childTests);
608     }.property('childTests', 'metrics'),
609 });
610
611 App.domainsAreEqual = function (domain1, domain2) {
612     return (!domain1 && !domain2) || (domain1 && domain2 && !(domain1[0] - domain2[0]) && !(domain1[1] - domain2[1]));
613 }
614
615 App.PaneController = Ember.ObjectController.extend({
616     needs: ['charts'],
617     sharedTime: Ember.computed.alias('parentController.sharedTime'),
618     sharedSelection: Ember.computed.alias('parentController.sharedSelection'),
619     selection: null,
620     actions: {
621         toggleDetails: function()
622         {
623             this.toggleProperty('showingDetails');
624         },
625         close: function ()
626         {
627             this.parentController.removePane(this.get('model'));
628         },
629         toggleBugsPane: function ()
630         {
631             if (this.toggleProperty('showingAnalysisPane'))
632                 this.set('showingSearchPane', false);
633         },
634         createAnalysisTask: function ()
635         {
636             var name = this.get('newAnalysisTaskName');
637             var points = this.get('selectedPoints');
638             Ember.assert('The analysis name should not be empty', name);
639             Ember.assert('There should be at least two points in the range', points && points.length >= 2);
640
641             var newWindow = window.open();
642             var self = this;
643             App.AnalysisTask.create(name, points[0].measurement, points[points.length - 1].measurement).then(function (data) {
644                 // FIXME: Update the UI to show the new analysis task.
645                 var url = App.Router.router.generate('analysisTask', data['taskId']);
646                 newWindow.location.href = '#' + url;
647                 self.get('model').fetchAnalyticRanges();
648             }, function (error) {
649                 newWindow.close();
650                 if (error === 'DuplicateAnalysisTask') {
651                     // FIXME: Duplicate this error more gracefully.
652                 }
653                 alert(error);
654             });
655         },
656         toggleSearchPane: function ()
657         {
658             if (!App.Manifest.repositoriesWithReportedCommits)
659                 return;
660             var model = this.get('model');
661             if (!model.get('commitSearchRepository'))
662                 model.set('commitSearchRepository', App.Manifest.repositoriesWithReportedCommits[0]);
663             if (this.toggleProperty('showingSearchPane'))
664                 this.set('showingAnalysisPane', false);
665         },
666         searchCommit: function () {
667             var model = this.get('model');
668             model.searchCommit(model.get('commitSearchRepository'), model.get('commitSearchKeyword'));                
669         },
670         zoomed: function (selection)
671         {
672             this.set('mainPlotDomain', selection ? selection : this.get('overviewDomain'));
673             Ember.run.debounce(this, 'propagateZoom', 100);
674         },
675     },
676     _detailsChanged: function ()
677     {
678         this.set('showingAnalysisPane', false);
679     }.observes('details'),
680     _overviewSelectionChanged: function ()
681     {
682         var overviewSelection = this.get('overviewSelection');
683         this.set('mainPlotDomain', overviewSelection || this.get('overviewDomain'));
684         Ember.run.debounce(this, 'propagateZoom', 100);
685     }.observes('overviewSelection'),
686     _sharedDomainChanged: function ()
687     {
688         var newDomain = this.get('parentController').get('sharedDomain');
689         if (App.domainsAreEqual(newDomain, this.get('overviewDomain')))
690             return;
691         this.set('overviewDomain', newDomain);
692         if (!this.get('overviewSelection'))
693             this.set('mainPlotDomain', newDomain);
694     }.observes('parentController.sharedDomain').on('init'),
695     propagateZoom: function ()
696     {
697         this.get('parentController').set('sharedZoom', this.get('mainPlotDomain'));
698     },
699     _sharedZoomChanged: function ()
700     {
701         var newSelection = this.get('parentController').get('sharedZoom');
702         if (App.domainsAreEqual(newSelection, this.get('mainPlotDomain')))
703             return;
704         this.set('overviewSelection', newSelection);
705     }.observes('parentController.sharedZoom').on('init'),
706     _updateDetails: function ()
707     {
708         var selectedPoints = this.get('selectedPoints');
709         var currentPoint = this.get('currentItem');
710         if (!selectedPoints && !currentPoint) {
711             this.set('details', null);
712             return;
713         }
714
715         var currentMeasurement;
716         var oldMeasurement;
717         if (currentPoint) {
718             currentMeasurement = currentPoint.measurement;
719             var previousPoint = currentPoint.series.previousPoint(currentPoint);
720             oldMeasurement = previousPoint ? previousPoint.measurement : null;
721         } else {
722             currentMeasurement = selectedPoints[selectedPoints.length - 1].measurement;
723             oldMeasurement = selectedPoints[0].measurement;            
724         }
725
726         var formattedRevisions = currentMeasurement.formattedRevisions(oldMeasurement);
727         var revisions = App.Manifest.get('repositories')
728             .filter(function (repository) { return formattedRevisions[repository.get('id')]; })
729             .map(function (repository) {
730             var repositoryName = repository.get('id');
731             var revision = Ember.Object.create(formattedRevisions[repositoryName]);
732             revision['url'] = revision.previousRevision
733                 ? repository.urlForRevisionRange(revision.previousRevision, revision.currentRevision)
734                 : repository.urlForRevision(revision.currentRevision);
735             revision['name'] = repositoryName;
736             revision['repository'] = repository;
737             return revision; 
738         });
739
740         var buildNumber = null;
741         var buildURL = null;
742         if (currentPoint) {
743             buildNumber = currentMeasurement.buildNumber();
744             var builder = App.Manifest.builder(currentMeasurement.builderId());
745             if (builder)
746                 buildURL = builder.urlFromBuildNumber(buildNumber);
747         }
748
749         this.set('details', Ember.Object.create({
750             currentValue: currentMeasurement.mean().toFixed(2),
751             oldValue: oldMeasurement && selectedPoints ? oldMeasurement.mean().toFixed(2) : null,
752             buildNumber: buildNumber,
753             buildURL: buildURL,
754             buildTime: currentMeasurement.formattedBuildTime(),
755             revisions: revisions,
756         }));
757         this._updateCanAnalyze();
758     }.observes('currentItem', 'selectedPoints'),
759     _updateCanAnalyze: function ()
760     {
761         var points = this.get('selectedPoints');
762         this.set('cannotAnalyze', !this.get('newAnalysisTaskName') || !points || points.length < 2);
763     }.observes('newAnalysisTaskName'),
764 });
765
766
767 App.AnalysisRoute = Ember.Route.extend({
768     model: function () {
769         return this.store.findAll('analysisTask').then(function (tasks) {
770             return Ember.Object.create({'tasks': tasks});
771         });
772     },
773 });
774
775 App.AnalysisTaskRoute = Ember.Route.extend({
776     model: function (param)
777     {
778         return this.store.find('analysisTask', param.taskId);
779     },
780 });
781
782 App.AnalysisTaskController = Ember.Controller.extend({
783     label: Ember.computed.alias('model.name'),
784     platform: Ember.computed.alias('model.platform'),
785     metric: Ember.computed.alias('model.metric'),
786     testGroups: Ember.computed.alias('model.testGroups'),
787     testSets: [],
788     roots: [],
789     bugTrackers: [],
790     possibleRepetitionCounts: [1, 2, 3, 4, 5, 6],
791     _taskUpdated: function ()
792     {
793         var model = this.get('model');
794         if (!model)
795             return;
796
797         var platformId = model.get('platform').get('id');
798         var metricId = model.get('metric').get('id');
799         App.Manifest.fetch(this.store).then(this._fetchedManifest.bind(this));
800         App.Manifest.fetchRunsWithPlatformAndMetric(this.store, platformId, metricId).then(this._fetchedRuns.bind(this));
801     }.observes('model').on('init'),
802     _fetchedManifest: function ()
803     {
804         var trackerIdToBugNumber = {};
805         this.get('model').get('bugs').forEach(function (bug) {
806             trackerIdToBugNumber[bug.get('bugTracker').get('id')] = bug.get('number');
807         });
808
809         this.set('bugTrackers', App.Manifest.get('bugTrackers').map(function (bugTracker) {
810             var bugNumber = trackerIdToBugNumber[bugTracker.get('id')];
811             return Ember.ObjectProxy.create({
812                 content: bugTracker,
813                 bugNumber: bugNumber,
814                 editedBugNumber: bugNumber,
815             });
816         }));
817     },
818     _fetchedRuns: function (data)
819     {
820         var runs = data.runs;
821
822         var currentTimeSeries = runs.current.timeSeriesByCommitTime();
823         if (!currentTimeSeries)
824             return; // FIXME: Report an error.
825
826         var start = currentTimeSeries.findPointByMeasurementId(this.get('model').get('startRun'));
827         var end = currentTimeSeries.findPointByMeasurementId(this.get('model').get('endRun'));
828         if (!start || !end)
829             return; // FIXME: Report an error.
830
831         var markedPoints = {};
832         markedPoints[start.measurement.id()] = true;
833         markedPoints[end.measurement.id()] = true;
834
835         var formatedPoints = currentTimeSeries.seriesBetweenPoints(start, end).map(function (point, index) {
836             return {
837                 id: point.measurement.id(),
838                 measurement: point.measurement,
839                 label: 'Point ' + (index + 1),
840                 value: point.value + (runs.unit ? ' ' + runs.unit : ''),
841             };
842         });
843
844         var margin = (end.time - start.time) * 0.1;
845         this.set('chartData', runs);
846         this.set('chartDomain', [start.time - margin, +end.time + margin]);
847         this.set('markedPoints', markedPoints);
848         this.set('analysisPoints', formatedPoints);
849     },
850     testSets: function ()
851     {
852         var analysisPoints = this.get('analysisPoints');
853         if (!analysisPoints)
854             return;
855         var pointOptions = [{value: ' ', label: 'None'}]
856             .concat(analysisPoints.map(function (point) { return {value: point.id, label: point.label}; }));
857         return [
858             Ember.Object.create({name: "A", options: pointOptions, selection: pointOptions[1]}),
859             Ember.Object.create({name: "B", options: pointOptions, selection: pointOptions[pointOptions.length - 1]}),
860         ];
861     }.property('analysisPoints'),
862     _rootChangedForTestSet: function ()
863     {
864         var sets = this.get('testSets');
865         var roots = this.get('roots');
866         if (!sets || !roots)
867             return;
868
869         sets.forEach(function (testSet, setIndex) {
870             var currentSelection = testSet.get('selection');
871             if (currentSelection == testSet.get('previousSelection'))
872                 return;
873             testSet.set('previousSelection', currentSelection);
874             var pointIndex = testSet.get('options').indexOf(currentSelection);
875
876             roots.forEach(function (root) {
877                 var set = root.sets[setIndex];
878                 set.set('selection', set.revisions[pointIndex]);
879             });
880         });
881
882     }.observes('testSets.@each.selection'),
883     updateRoots: function ()
884     {
885         var analysisPoints = this.get('analysisPoints');
886         if (!analysisPoints)
887             return;
888         var repositoryToRevisions = {};
889         analysisPoints.forEach(function (point, pointIndex) {
890             var revisions = point.measurement.formattedRevisions();
891             for (var repositoryName in revisions) {
892                 if (!repositoryToRevisions[repositoryName])
893                     repositoryToRevisions[repositoryName] = new Array(analysisPoints.length);
894                 var revision = revisions[repositoryName];
895                 repositoryToRevisions[repositoryName][pointIndex] = {
896                     label: point.label + ': ' + revision.label,
897                     value: revision.currentRevision,
898                 };
899             }
900         });
901
902         var self = this;
903         this.get('model').get('triggerable').then(function (triggerable) {
904             if (!triggerable)
905                 return;
906
907             self.set('roots', triggerable.get('acceptedRepositories').map(function (repository) {
908                 var repositoryName = repository.get('id');
909                 var revisions = [{value: ' ', label: 'None'}].concat(repositoryToRevisions[repositoryName]);
910                 return Ember.Object.create({
911                     name: repositoryName,
912                     sets: [
913                         Ember.Object.create({name: 'A[' + repositoryName + ']',
914                             revisions: revisions,
915                             selection: revisions[1]}),
916                         Ember.Object.create({name: 'B[' + repositoryName + ']',
917                             revisions: revisions,
918                             selection: revisions[revisions.length - 1]}),
919                     ],
920                 });
921             }));
922         });
923     }.observes('analysisPoints'),
924     actions: {
925         associateBug: function (bugTracker, bugNumber)
926         {
927             var model = this.get('model');
928             this.store.createRecord('bug',
929                 {task: this.get('model'), bugTracker: bugTracker.get('content'), number: bugNumber}).save().then(function () {
930                     // FIXME: Should we notify the user?
931                 }, function (error) {
932                     alert('Failed to associate the bug: ' + error);
933                 });
934         },
935         createTestGroup: function (name, repetitionCount)
936         {
937             var roots = {};
938             this.get('roots').map(function (root) {
939                 roots[root.get('name')] = root.get('sets').map(function (item) { return item.get('selection').value; });
940             });
941             App.TestGroup.create(this.get('model'), name, roots, repetitionCount).then(function () {
942                 
943             });
944         },
945     },
946 });