New perf dashboard erroneously clears zoom when poping history items
[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 repositoryId = repository.get('id');
280         CommitLogs.fetchForTimeRange(repositoryId, 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(repositoryId);
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         if (App.domainsAreEqual(overviewSelection, this.get('mainPlotDomain')))
684             return;
685         this.set('mainPlotDomain', overviewSelection || this.get('overviewDomain'));
686         Ember.run.debounce(this, 'propagateZoom', 100);
687     }.observes('overviewSelection'),
688     _sharedDomainChanged: function ()
689     {
690         var newDomain = this.get('parentController').get('sharedDomain');
691         if (App.domainsAreEqual(newDomain, this.get('overviewDomain')))
692             return;
693         this.set('overviewDomain', newDomain);
694         if (!this.get('overviewSelection'))
695             this.set('mainPlotDomain', newDomain);
696     }.observes('parentController.sharedDomain').on('init'),
697     propagateZoom: function ()
698     {
699         this.get('parentController').set('sharedZoom', this.get('mainPlotDomain'));
700     },
701     _sharedZoomChanged: function ()
702     {
703         var newSelection = this.get('parentController').get('sharedZoom');
704         if (App.domainsAreEqual(newSelection, this.get('mainPlotDomain')))
705             return;
706         this.set('mainPlotDomain', newSelection);
707         this.set('overviewSelection', newSelection);
708     }.observes('parentController.sharedZoom').on('init'),
709     _updateDetails: function ()
710     {
711         var selectedPoints = this.get('selectedPoints');
712         var currentPoint = this.get('currentItem');
713         if (!selectedPoints && !currentPoint) {
714             this.set('details', null);
715             return;
716         }
717
718         var currentMeasurement;
719         var oldMeasurement;
720         if (currentPoint) {
721             currentMeasurement = currentPoint.measurement;
722             var previousPoint = currentPoint.series.previousPoint(currentPoint);
723             oldMeasurement = previousPoint ? previousPoint.measurement : null;
724         } else {
725             currentMeasurement = selectedPoints[selectedPoints.length - 1].measurement;
726             oldMeasurement = selectedPoints[0].measurement;            
727         }
728
729         var formattedRevisions = currentMeasurement.formattedRevisions(oldMeasurement);
730         var revisions = App.Manifest.get('repositories')
731             .filter(function (repository) { return formattedRevisions[repository.get('id')]; })
732             .map(function (repository) {
733             var revision = Ember.Object.create(formattedRevisions[repository.get('id')]);
734             revision['url'] = revision.previousRevision
735                 ? repository.urlForRevisionRange(revision.previousRevision, revision.currentRevision)
736                 : repository.urlForRevision(revision.currentRevision);
737             revision['name'] = repository.get('name');
738             revision['repository'] = repository;
739             return revision; 
740         });
741
742         var buildNumber = null;
743         var buildURL = null;
744         if (currentPoint) {
745             buildNumber = currentMeasurement.buildNumber();
746             var builder = App.Manifest.builder(currentMeasurement.builderId());
747             if (builder)
748                 buildURL = builder.urlFromBuildNumber(buildNumber);
749         }
750
751         this.set('details', Ember.Object.create({
752             currentValue: currentMeasurement.mean().toFixed(2),
753             oldValue: oldMeasurement && selectedPoints ? oldMeasurement.mean().toFixed(2) : null,
754             buildNumber: buildNumber,
755             buildURL: buildURL,
756             buildTime: currentMeasurement.formattedBuildTime(),
757             revisions: revisions,
758         }));
759         this._updateCanAnalyze();
760     }.observes('currentItem', 'selectedPoints'),
761     _updateCanAnalyze: function ()
762     {
763         var points = this.get('selectedPoints');
764         this.set('cannotAnalyze', !this.get('newAnalysisTaskName') || !points || points.length < 2);
765     }.observes('newAnalysisTaskName'),
766 });
767
768
769 App.AnalysisRoute = Ember.Route.extend({
770     model: function () {
771         return this.store.findAll('analysisTask').then(function (tasks) {
772             return Ember.Object.create({'tasks': tasks});
773         });
774     },
775 });
776
777 App.AnalysisTaskRoute = Ember.Route.extend({
778     model: function (param)
779     {
780         return this.store.find('analysisTask', param.taskId);
781     },
782 });
783
784 App.AnalysisTaskController = Ember.Controller.extend({
785     label: Ember.computed.alias('model.name'),
786     platform: Ember.computed.alias('model.platform'),
787     metric: Ember.computed.alias('model.metric'),
788     testGroups: Ember.computed.alias('model.testGroups'),
789     testSets: [],
790     roots: [],
791     bugTrackers: [],
792     possibleRepetitionCounts: [1, 2, 3, 4, 5, 6],
793     _taskUpdated: function ()
794     {
795         var model = this.get('model');
796         if (!model)
797             return;
798
799         var platformId = model.get('platform').get('id');
800         var metricId = model.get('metric').get('id');
801         App.Manifest.fetch(this.store).then(this._fetchedManifest.bind(this));
802         App.Manifest.fetchRunsWithPlatformAndMetric(this.store, platformId, metricId).then(this._fetchedRuns.bind(this));
803     }.observes('model').on('init'),
804     _fetchedManifest: function ()
805     {
806         var trackerIdToBugNumber = {};
807         this.get('model').get('bugs').forEach(function (bug) {
808             trackerIdToBugNumber[bug.get('bugTracker').get('id')] = bug.get('number');
809         });
810
811         this.set('bugTrackers', App.Manifest.get('bugTrackers').map(function (bugTracker) {
812             var bugNumber = trackerIdToBugNumber[bugTracker.get('id')];
813             return Ember.ObjectProxy.create({
814                 content: bugTracker,
815                 bugNumber: bugNumber,
816                 editedBugNumber: bugNumber,
817             });
818         }));
819     },
820     _fetchedRuns: function (data)
821     {
822         var runs = data.runs;
823
824         var currentTimeSeries = runs.current.timeSeriesByCommitTime();
825         if (!currentTimeSeries)
826             return; // FIXME: Report an error.
827
828         var start = currentTimeSeries.findPointByMeasurementId(this.get('model').get('startRun'));
829         var end = currentTimeSeries.findPointByMeasurementId(this.get('model').get('endRun'));
830         if (!start || !end)
831             return; // FIXME: Report an error.
832
833         var highlightedItems = {};
834         highlightedItems[start.measurement.id()] = true;
835         highlightedItems[end.measurement.id()] = true;
836
837         var formatedPoints = currentTimeSeries.seriesBetweenPoints(start, end).map(function (point, index) {
838             return {
839                 id: point.measurement.id(),
840                 measurement: point.measurement,
841                 label: 'Point ' + (index + 1),
842                 value: point.value + (runs.unit ? ' ' + runs.unit : ''),
843             };
844         });
845
846         var margin = (end.time - start.time) * 0.1;
847         this.set('chartData', runs);
848         this.set('chartDomain', [start.time - margin, +end.time + margin]);
849         this.set('highlightedItems', highlightedItems);
850         this.set('analysisPoints', formatedPoints);
851     },
852     testSets: function ()
853     {
854         var analysisPoints = this.get('analysisPoints');
855         if (!analysisPoints)
856             return;
857         var pointOptions = [{value: ' ', label: 'None'}]
858             .concat(analysisPoints.map(function (point) { return {value: point.id, label: point.label}; }));
859         return [
860             Ember.Object.create({name: "A", options: pointOptions, selection: pointOptions[1]}),
861             Ember.Object.create({name: "B", options: pointOptions, selection: pointOptions[pointOptions.length - 1]}),
862         ];
863     }.property('analysisPoints'),
864     _rootChangedForTestSet: function ()
865     {
866         var sets = this.get('testSets');
867         var roots = this.get('roots');
868         if (!sets || !roots)
869             return;
870
871         sets.forEach(function (testSet, setIndex) {
872             var currentSelection = testSet.get('selection');
873             if (currentSelection == testSet.get('previousSelection'))
874                 return;
875             testSet.set('previousSelection', currentSelection);
876             var pointIndex = testSet.get('options').indexOf(currentSelection);
877
878             roots.forEach(function (root) {
879                 var set = root.sets[setIndex];
880                 set.set('selection', set.revisions[pointIndex]);
881             });
882         });
883
884     }.observes('testSets.@each.selection'),
885     updateRoots: function ()
886     {
887         var analysisPoints = this.get('analysisPoints');
888         if (!analysisPoints)
889             return;
890         var repositoryToRevisions = {};
891         analysisPoints.forEach(function (point, pointIndex) {
892             var revisions = point.measurement.formattedRevisions();
893             for (var repositoryId in revisions) {
894                 if (!repositoryToRevisions[repositoryId])
895                     repositoryToRevisions[repositoryId] = new Array(analysisPoints.length);
896                 var revision = revisions[repositoryId];
897                 repositoryToRevisions[repositoryId][pointIndex] = {
898                     label: point.label + ': ' + revision.label,
899                     value: revision.currentRevision,
900                 };
901             }
902         });
903
904         var self = this;
905         this.get('model').get('triggerable').then(function (triggerable) {
906             if (!triggerable)
907                 return;
908
909             self.set('roots', triggerable.get('acceptedRepositories').map(function (repository) {
910                 var repositoryId = repository.get('id');
911                 var revisions = [{value: ' ', label: 'None'}].concat(repositoryToRevisions[repositoryId]);
912                 return Ember.Object.create({
913                     name: repository.get('name'),
914                     sets: [
915                         Ember.Object.create({name: 'A[' + repositoryId + ']',
916                             revisions: revisions,
917                             selection: revisions[1]}),
918                         Ember.Object.create({name: 'B[' + repositoryId + ']',
919                             revisions: revisions,
920                             selection: revisions[revisions.length - 1]}),
921                     ],
922                 });
923             }));
924         });
925     }.observes('analysisPoints'),
926     actions: {
927         associateBug: function (bugTracker, bugNumber)
928         {
929             var model = this.get('model');
930             this.store.createRecord('bug',
931                 {task: this.get('model'), bugTracker: bugTracker.get('content'), number: bugNumber}).save().then(function () {
932                     // FIXME: Should we notify the user?
933                 }, function (error) {
934                     alert('Failed to associate the bug: ' + error);
935                 });
936         },
937         createTestGroup: function (name, repetitionCount)
938         {
939             var roots = {};
940             this.get('roots').map(function (root) {
941                 roots[root.get('name')] = root.get('sets').map(function (item) { return item.get('selection').value; });
942             });
943             App.TestGroup.create(this.get('model'), name, roots, repetitionCount).then(function () {
944                 
945             });
946         },
947     },
948 });