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