Unreviewed build fix.
[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.timeSeriesByCommitTime().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', result.runs);
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.encodePrettifiedJSON = function (plain)
369 {
370     function numberIfPossible(string) {
371         return string == parseInt(string) ? parseInt(string) : string;
372     }
373
374     function recursivelyConvertNumberIfPossible(input) {
375         if (input instanceof Array) {
376             return input.map(recursivelyConvertNumberIfPossible);
377         }
378         return numberIfPossible(input);
379     }
380
381     return JSON.stringify(recursivelyConvertNumberIfPossible(plain))
382         .replace(/\[/g, '(').replace(/\]/g, ')').replace(/\,/g, '-');
383 }
384
385 App.decodePrettifiedJSON = function (encoded)
386 {
387     var parsed = encoded.replace(/\(/g, '[').replace(/\)/g, ']').replace(/\-/g, ',');
388     try {
389         return JSON.parse(parsed);
390     } catch (exception) {
391         return null;
392     }
393 }
394
395 App.ChartsController = Ember.Controller.extend({
396     queryParams: ['paneList', 'zoom', 'since'],
397     needs: ['pane'],
398     _currentEncodedPaneList: null,
399     panes: [],
400     platforms: null,
401     sharedZoom: null,
402     startTime: null,
403     present: Date.now(),
404     defaultSince: Date.now() - 7 * 24 * 3600 * 1000,
405
406     addPane: function (pane)
407     {
408         this.panes.unshiftObject(pane);
409     },
410
411     removePane: function (pane)
412     {
413         this.panes.removeObject(pane);
414     },
415
416     refreshPanes: function()
417     {
418         var paneList = this.get('paneList');
419         if (paneList === this._currentEncodedPaneList)
420             return;
421
422         var panes = this._parsePaneList(paneList || '[]');
423         if (!panes) {
424             console.log('Failed to parse', jsonPaneList, exception);
425             return;
426         }
427         this.set('panes', panes);
428         this._currentEncodedPaneList = paneList;
429     }.observes('paneList').on('init'),
430
431     refreshZoom: function()
432     {
433         var zoom = this.get('zoom');
434         if (!zoom) {
435             this.set('sharedZoom', null);
436             return;
437         }
438
439         zoom = zoom.split('-');
440         var selection = new Array(2);
441         try {
442             selection[0] = new Date(parseFloat(zoom[0]));
443             selection[1] = new Date(parseFloat(zoom[1]));
444         } catch (error) {
445             console.log('Failed to parse the zoom', zoom);
446         }
447         this.set('sharedZoom', selection);
448
449         var startTime = this.get('startTime');
450         if (startTime && startTime > selection[0])
451             this.set('startTime', selection[0]);
452
453     }.observes('zoom').on('init'),
454
455     _startTimeChanged: function () {
456         this.set('sharedDomain', [this.get('startTime'), this.get('present')]);
457         this._scheduleQueryStringUpdate();
458     }.observes('startTime'),
459
460     _sinceChanged: function () {
461         var since = parseInt(this.get('since'));
462         if (isNaN(since))
463             since = this.defaultSince;
464         this.set('startTime', new Date(since));
465     }.observes('since').on('init'),
466
467     _parsePaneList: function (encodedPaneList)
468     {
469         var parsedPaneList = App.decodePrettifiedJSON(encodedPaneList);
470         if (!parsedPaneList)
471             return null;
472
473         // Don't re-create all panes.
474         var self = this;
475         return parsedPaneList.map(function (paneInfo) {
476             var timeRange = null;
477             if (paneInfo[3] && paneInfo[3] instanceof Array) {
478                 var timeRange = paneInfo[3];
479                 try {
480                     timeRange = [new Date(timeRange[0]), new Date(timeRange[1])];
481                 } catch (error) {
482                     console.log("Failed to parse the time range:", timeRange, error);
483                 }
484             }
485             return App.Pane.create({
486                 store: self.store,
487                 info: paneInfo,
488                 platformId: paneInfo[0],
489                 metricId: paneInfo[1],
490                 selectedItem: paneInfo[2],
491                 timeRange: timeRange,
492                 timeRangeIsLocked: !!paneInfo[4],
493             });
494         });
495     },
496
497     _serializePaneList: function (panes)
498     {
499         if (!panes.length)
500             return undefined;
501         return App.encodePrettifiedJSON(panes.map(function (pane) {
502             return [
503                 pane.get('platformId'),
504                 pane.get('metricId'),
505                 pane.get('selectedItem'),
506                 pane.get('timeRange') ? pane.get('timeRange').map(function (date) { return date.getTime() }) : null,
507                 !!pane.get('timeRangeIsLocked'),
508             ];
509         }));
510     },
511
512     _scheduleQueryStringUpdate: function ()
513     {
514         Ember.run.debounce(this, '_updateQueryString', 1000);
515     }.observes('sharedZoom', 'panes.@each.platform', 'panes.@each.metric', 'panes.@each.selectedItem',
516         'panes.@each.timeRange', 'panes.@each.timeRangeIsLocked'),
517
518     _updateQueryString: function ()
519     {
520         this._currentEncodedPaneList = this._serializePaneList(this.get('panes'));
521         this.set('paneList', this._currentEncodedPaneList);
522
523         var zoom = undefined;
524         var sharedZoom = this.get('sharedZoom');
525         if (sharedZoom && !App.domainsAreEqual(sharedZoom, this.get('sharedDomain')))
526             zoom = +sharedZoom[0] + '-' + +sharedZoom[1];
527         this.set('zoom', zoom);
528
529         if (this.get('startTime') - this.defaultSince)
530             this.set('since', this.get('startTime') - 0);
531     },
532
533     actions: {
534         addPaneByMetricAndPlatform: function (param)
535         {
536             this.addPane(App.Pane.create({
537                 store: this.store,
538                 platformId: param.platform.get('id'),
539                 metricId: param.metric.get('id'),
540                 showingDetails: false
541             }));
542         },
543     },
544
545     init: function ()
546     {
547         this._super();
548         var self = this;
549         App.buildPopup(this.store, 'addPaneByMetricAndPlatform').then(function (platforms) {
550             self.set('platforms', platforms);
551         });
552     },
553 });
554
555 App.buildPopup = function(store, action, position)
556 {
557     return App.Manifest.fetch(store).then(function () {
558         return App.Manifest.get('platforms').map(function (platform) {
559             return App.PlatformProxyForPopup.create({content: platform,
560                 action: action, position: position});
561         });
562     });
563 }
564
565 App.PlatformProxyForPopup = Ember.ObjectProxy.extend({
566     children: function ()
567     {
568         var platform = this.content;
569         var containsTest = this.content.containsTest.bind(this.content);
570         var action = this.get('action');
571         var position = this.get('position');
572         return App.Manifest.get('topLevelTests')
573             .filter(containsTest)
574             .map(function (test) {
575                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
576             });
577     }.property('App.Manifest.topLevelTests'),
578 });
579
580 App.TestProxyForPopup = Ember.ObjectProxy.extend({
581     platform: null,
582     children: function ()
583     {
584         var platform = this.get('platform');
585         var action = this.get('action');
586         var position = this.get('position');
587
588         var childTests = this.get('childTests')
589             .filter(function (test) { return platform.containsTest(test); })
590             .map(function (test) {
591                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
592             });
593
594         var metrics = this.get('metrics')
595             .filter(function (metric) { return platform.containsMetric(metric); })
596             .map(function (metric) {
597                 var aggregator = metric.get('aggregator');
598                 return {
599                     actionName: action,
600                     actionArgument: {platform: platform, metric: metric, position:position},
601                     label: metric.get('label')
602                 };
603             });
604
605         if (childTests.length && metrics.length)
606             metrics.push({isSeparator: true});
607
608         return metrics.concat(childTests);
609     }.property('childTests', 'metrics'),
610 });
611
612 App.domainsAreEqual = function (domain1, domain2) {
613     return (!domain1 && !domain2) || (domain1 && domain2 && !(domain1[0] - domain2[0]) && !(domain1[1] - domain2[1]));
614 }
615
616 App.PaneController = Ember.ObjectController.extend({
617     needs: ['charts'],
618     sharedTime: Ember.computed.alias('parentController.sharedTime'),
619     sharedSelection: Ember.computed.alias('parentController.sharedSelection'),
620     selection: null,
621     actions: {
622         toggleDetails: function()
623         {
624             this.toggleProperty('showingDetails');
625         },
626         close: function ()
627         {
628             this.parentController.removePane(this.get('model'));
629         },
630         toggleBugsPane: function ()
631         {
632             if (this.toggleProperty('showingAnalysisPane'))
633                 this.set('showingSearchPane', false);
634         },
635         createAnalysisTask: function ()
636         {
637             var name = this.get('newAnalysisTaskName');
638             var points = this.get('selectedPoints');
639             Ember.assert('The analysis name should not be empty', name);
640             Ember.assert('There should be at least two points in the range', points && points.length >= 2);
641
642             var newWindow = window.open();
643             var self = this;
644             App.AnalysisTask.create(name, points[0].measurement, points[points.length - 1].measurement).then(function (data) {
645                 // FIXME: Update the UI to show the new analysis task.
646                 var url = App.Router.router.generate('analysisTask', data['taskId']);
647                 newWindow.location.href = '#' + url;
648                 self.get('model').fetchAnalyticRanges();
649             }, function (error) {
650                 newWindow.close();
651                 if (error === 'DuplicateAnalysisTask') {
652                     // FIXME: Duplicate this error more gracefully.
653                 }
654                 alert(error);
655             });
656         },
657         toggleSearchPane: function ()
658         {
659             if (!App.Manifest.repositoriesWithReportedCommits)
660                 return;
661             var model = this.get('model');
662             if (!model.get('commitSearchRepository'))
663                 model.set('commitSearchRepository', App.Manifest.repositoriesWithReportedCommits[0]);
664             if (this.toggleProperty('showingSearchPane'))
665                 this.set('showingAnalysisPane', false);
666         },
667         searchCommit: function () {
668             var model = this.get('model');
669             model.searchCommit(model.get('commitSearchRepository'), model.get('commitSearchKeyword'));                
670         },
671         zoomed: function (selection)
672         {
673             this.set('mainPlotDomain', selection ? selection : this.get('overviewDomain'));
674             Ember.run.debounce(this, 'propagateZoom', 100);
675         },
676     },
677     _detailsChanged: function ()
678     {
679         this.set('showingAnalysisPane', false);
680     }.observes('details'),
681     _overviewSelectionChanged: function ()
682     {
683         var overviewSelection = this.get('overviewSelection');
684         if (App.domainsAreEqual(overviewSelection, this.get('mainPlotDomain')))
685             return;
686         this.set('mainPlotDomain', overviewSelection || this.get('overviewDomain'));
687         Ember.run.debounce(this, 'propagateZoom', 100);
688     }.observes('overviewSelection'),
689     _sharedDomainChanged: function ()
690     {
691         var newDomain = this.get('parentController').get('sharedDomain');
692         if (App.domainsAreEqual(newDomain, this.get('overviewDomain')))
693             return;
694         this.set('overviewDomain', newDomain);
695         if (!this.get('overviewSelection'))
696             this.set('mainPlotDomain', newDomain);
697     }.observes('parentController.sharedDomain').on('init'),
698     propagateZoom: function ()
699     {
700         this.get('parentController').set('sharedZoom', this.get('mainPlotDomain'));
701     },
702     _sharedZoomChanged: function ()
703     {
704         var newSelection = this.get('parentController').get('sharedZoom');
705         if (App.domainsAreEqual(newSelection, this.get('mainPlotDomain')))
706             return;
707         this.set('mainPlotDomain', newSelection);
708         this.set('overviewSelection', newSelection);
709     }.observes('parentController.sharedZoom').on('init'),
710     _updateDetails: function ()
711     {
712         var selectedPoints = this.get('selectedPoints');
713         var currentPoint = this.get('currentItem');
714         if (!selectedPoints && !currentPoint) {
715             this.set('details', null);
716             return;
717         }
718
719         var currentMeasurement;
720         var oldMeasurement;
721         if (currentPoint) {
722             currentMeasurement = currentPoint.measurement;
723             var previousPoint = currentPoint.series.previousPoint(currentPoint);
724             oldMeasurement = previousPoint ? previousPoint.measurement : null;
725         } else {
726             currentMeasurement = selectedPoints[selectedPoints.length - 1].measurement;
727             oldMeasurement = selectedPoints[0].measurement;            
728         }
729
730         var formattedRevisions = currentMeasurement.formattedRevisions(oldMeasurement);
731         var revisions = App.Manifest.get('repositories')
732             .filter(function (repository) { return formattedRevisions[repository.get('id')]; })
733             .map(function (repository) {
734             var revision = Ember.Object.create(formattedRevisions[repository.get('id')]);
735             revision['url'] = revision.previousRevision
736                 ? repository.urlForRevisionRange(revision.previousRevision, revision.currentRevision)
737                 : repository.urlForRevision(revision.currentRevision);
738             revision['name'] = repository.get('name');
739             revision['repository'] = repository;
740             return revision; 
741         });
742
743         var buildNumber = null;
744         var buildURL = null;
745         if (currentPoint) {
746             buildNumber = currentMeasurement.buildNumber();
747             var builder = App.Manifest.builder(currentMeasurement.builderId());
748             if (builder)
749                 buildURL = builder.urlFromBuildNumber(buildNumber);
750         }
751
752         this.set('details', Ember.Object.create({
753             currentValue: currentMeasurement.mean().toFixed(2),
754             oldValue: oldMeasurement && selectedPoints ? oldMeasurement.mean().toFixed(2) : null,
755             buildNumber: buildNumber,
756             buildURL: buildURL,
757             buildTime: currentMeasurement.formattedBuildTime(),
758             revisions: revisions,
759         }));
760         this._updateCanAnalyze();
761     }.observes('currentItem', 'selectedPoints'),
762     _updateCanAnalyze: function ()
763     {
764         var points = this.get('selectedPoints');
765         this.set('cannotAnalyze', !this.get('newAnalysisTaskName') || !points || points.length < 2);
766     }.observes('newAnalysisTaskName'),
767 });
768
769
770 App.AnalysisRoute = Ember.Route.extend({
771     model: function () {
772         return this.store.findAll('analysisTask').then(function (tasks) {
773             return Ember.Object.create({'tasks': tasks});
774         });
775     },
776 });
777
778 App.AnalysisTaskRoute = Ember.Route.extend({
779     model: function (param)
780     {
781         return this.store.find('analysisTask', param.taskId);
782     },
783 });
784
785 App.AnalysisTaskController = Ember.Controller.extend({
786     label: Ember.computed.alias('model.name'),
787     platform: Ember.computed.alias('model.platform'),
788     metric: Ember.computed.alias('model.metric'),
789     testGroups: Ember.computed.alias('model.testGroups'),
790     testSets: [],
791     roots: [],
792     bugTrackers: [],
793     possibleRepetitionCounts: [1, 2, 3, 4, 5, 6],
794     _taskUpdated: function ()
795     {
796         var model = this.get('model');
797         if (!model)
798             return;
799
800         var platformId = model.get('platform').get('id');
801         var metricId = model.get('metric').get('id');
802         App.Manifest.fetch(this.store).then(this._fetchedManifest.bind(this));
803         App.Manifest.fetchRunsWithPlatformAndMetric(this.store, platformId, metricId).then(this._fetchedRuns.bind(this));
804     }.observes('model').on('init'),
805     _fetchedManifest: function ()
806     {
807         var trackerIdToBugNumber = {};
808         this.get('model').get('bugs').forEach(function (bug) {
809             trackerIdToBugNumber[bug.get('bugTracker').get('id')] = bug.get('number');
810         });
811
812         this.set('bugTrackers', App.Manifest.get('bugTrackers').map(function (bugTracker) {
813             var bugNumber = trackerIdToBugNumber[bugTracker.get('id')];
814             return Ember.ObjectProxy.create({
815                 content: bugTracker,
816                 bugNumber: bugNumber,
817                 editedBugNumber: bugNumber,
818             });
819         }));
820     },
821     _fetchedRuns: function (data)
822     {
823         var runs = data.runs;
824
825         var currentTimeSeries = runs.current.timeSeriesByCommitTime();
826         if (!currentTimeSeries)
827             return; // FIXME: Report an error.
828
829         var start = currentTimeSeries.findPointByMeasurementId(this.get('model').get('startRun'));
830         var end = currentTimeSeries.findPointByMeasurementId(this.get('model').get('endRun'));
831         if (!start || !end)
832             return; // FIXME: Report an error.
833
834         var highlightedItems = {};
835         highlightedItems[start.measurement.id()] = true;
836         highlightedItems[end.measurement.id()] = true;
837
838         var formatedPoints = currentTimeSeries.seriesBetweenPoints(start, end).map(function (point, index) {
839             return {
840                 id: point.measurement.id(),
841                 measurement: point.measurement,
842                 label: 'Point ' + (index + 1),
843                 value: point.value + (runs.unit ? ' ' + runs.unit : ''),
844             };
845         });
846
847         var margin = (end.time - start.time) * 0.1;
848         this.set('chartData', runs);
849         this.set('chartDomain', [start.time - margin, +end.time + margin]);
850         this.set('highlightedItems', highlightedItems);
851         this.set('analysisPoints', formatedPoints);
852     },
853     testSets: function ()
854     {
855         var analysisPoints = this.get('analysisPoints');
856         if (!analysisPoints)
857             return;
858         var pointOptions = [{value: ' ', label: 'None'}]
859             .concat(analysisPoints.map(function (point) { return {value: point.id, label: point.label}; }));
860         return [
861             Ember.Object.create({name: "A", options: pointOptions, selection: pointOptions[1]}),
862             Ember.Object.create({name: "B", options: pointOptions, selection: pointOptions[pointOptions.length - 1]}),
863         ];
864     }.property('analysisPoints'),
865     _rootChangedForTestSet: function ()
866     {
867         var sets = this.get('testSets');
868         var roots = this.get('roots');
869         if (!sets || !roots)
870             return;
871
872         sets.forEach(function (testSet, setIndex) {
873             var currentSelection = testSet.get('selection');
874             if (currentSelection == testSet.get('previousSelection'))
875                 return;
876             testSet.set('previousSelection', currentSelection);
877             var pointIndex = testSet.get('options').indexOf(currentSelection);
878
879             roots.forEach(function (root) {
880                 var set = root.sets[setIndex];
881                 set.set('selection', set.revisions[pointIndex]);
882             });
883         });
884
885     }.observes('testSets.@each.selection'),
886     updateRoots: function ()
887     {
888         var analysisPoints = this.get('analysisPoints');
889         if (!analysisPoints)
890             return;
891         var repositoryToRevisions = {};
892         analysisPoints.forEach(function (point, pointIndex) {
893             var revisions = point.measurement.formattedRevisions();
894             for (var repositoryId in revisions) {
895                 if (!repositoryToRevisions[repositoryId])
896                     repositoryToRevisions[repositoryId] = new Array(analysisPoints.length);
897                 var revision = revisions[repositoryId];
898                 repositoryToRevisions[repositoryId][pointIndex] = {
899                     label: point.label + ': ' + revision.label,
900                     value: revision.currentRevision,
901                 };
902             }
903         });
904
905         var self = this;
906         this.get('model').get('triggerable').then(function (triggerable) {
907             if (!triggerable)
908                 return;
909
910             self.set('roots', triggerable.get('acceptedRepositories').map(function (repository) {
911                 var repositoryId = repository.get('id');
912                 var revisions = [{value: ' ', label: 'None'}].concat(repositoryToRevisions[repositoryId]);
913                 return Ember.Object.create({
914                     name: repository.get('name'),
915                     sets: [
916                         Ember.Object.create({name: 'A[' + repositoryId + ']',
917                             revisions: revisions,
918                             selection: revisions[1]}),
919                         Ember.Object.create({name: 'B[' + repositoryId + ']',
920                             revisions: revisions,
921                             selection: revisions[revisions.length - 1]}),
922                     ],
923                 });
924             }));
925         });
926     }.observes('analysisPoints'),
927     actions: {
928         associateBug: function (bugTracker, bugNumber)
929         {
930             var model = this.get('model');
931             this.store.createRecord('bug',
932                 {task: this.get('model'), bugTracker: bugTracker.get('content'), number: bugNumber}).save().then(function () {
933                     // FIXME: Should we notify the user?
934                 }, function (error) {
935                     alert('Failed to associate the bug: ' + error);
936                 });
937         },
938         createTestGroup: function (name, repetitionCount)
939         {
940             var roots = {};
941             this.get('roots').map(function (root) {
942                 roots[root.get('name')] = root.get('sets').map(function (item) { return item.get('selection').value; });
943             });
944             App.TestGroup.create(this.get('model'), name, roots, repetitionCount).then(function () {
945                 
946             });
947         },
948     },
949 });