New perf dashboard's chart UI is buggy
[WebKit-https.git] / Websites / perf.webkit.org / public / v2 / app.js
1 window.App = Ember.Application.create();
2
3 App.Router.map(function () {
4     this.resource('charts', {path: 'charts'});
5     this.resource('analysis', {path: 'analysis'});
6     this.resource('analysisTask', {path: 'analysis/task/:taskId'});
7 });
8
9 App.DashboardRow = Ember.Object.extend({
10     header: null,
11     cells: [],
12
13     init: function ()
14     {
15         this._super();
16
17         var cellsInfo = this.get('cellsInfo') || [];
18         var columnCount = this.get('columnCount');
19         while (cellsInfo.length < columnCount)
20             cellsInfo.push([]);
21
22         this.set('cells', cellsInfo.map(this._createPane.bind(this)));
23     },
24     addPane: function (paneInfo)
25     {
26         var pane = this._createPane(paneInfo);
27         this.get('cells').pushObject(pane);
28         this.set('columnCount', this.get('columnCount') + 1);
29     },
30     _createPane: function (paneInfo)
31     {
32         if (!paneInfo || !paneInfo.length || (!paneInfo[0] && !paneInfo[1]))
33             paneInfo = null;
34
35         var pane = App.Pane.create({
36             store: this.get('store'),
37             platformId: paneInfo ? paneInfo[0] : null,
38             metricId: paneInfo ? paneInfo[1] : null,
39         });
40
41         return App.DashboardPaneProxyForPicker.create({content: pane});
42     },
43 });
44
45 App.DashboardPaneProxyForPicker = Ember.ObjectProxy.extend({
46     _platformOrMetricIdChanged: function ()
47     {
48         var self = this;
49         App.buildPopup(this.get('store'), 'choosePane', this)
50             .then(function (platforms) { self.set('pickerData', platforms); });
51     }.observes('platformId', 'metricId').on('init'),
52     paneList: function () {
53         return App.encodePrettifiedJSON([[this.get('platformId'), this.get('metricId'), null, null, false]]);
54     }.property('platformId', 'metricId'),
55 });
56
57 App.IndexController = Ember.Controller.extend({
58     queryParams: ['grid', 'numberOfDays'],
59     _previousGrid: {},
60     headerColumns: [],
61     rows: [],
62     numberOfDays: 30,
63     editMode: false,
64
65     gridChanged: function ()
66     {
67         var grid = this.get('grid');
68         if (grid === this._previousGrid)
69             return;
70
71         var dashboard = null;
72         if (grid) {
73             dashboard = App.Dashboard.create({serialized: grid});
74             if (!dashboard.get('headerColumns').length)
75                 dashboard = null;
76         }
77         if (!dashboard)
78             dashboard = App.Manifest.get('defaultDashboard');
79         if (!dashboard)
80             return;
81
82         var headerColumns = dashboard.get('headerColumns');
83         this.set('headerColumns', headerColumns);
84         var columnCount = headerColumns.length;
85         this.set('columnCount', columnCount);
86
87         var store = this.store;
88         this.set('rows', dashboard.get('rows').map(function (rowParam) {
89             return App.DashboardRow.create({
90                 store: store,
91                 header: rowParam[0],
92                 cellsInfo: rowParam.slice(1),
93                 columnCount: columnCount,
94             })
95         }));
96
97         this.set('emptyRow', new Array(columnCount));
98     }.observes('grid', 'App.Manifest.defaultDashboard').on('init'),
99
100     updateGrid: function()
101     {
102         var headers = this.get('headerColumns').map(function (header) { return header.label; });
103         var table = [headers].concat(this.get('rows').map(function (row) {
104             return [row.get('header')].concat(row.get('cells').map(function (pane) {
105                 var platformAndMetric = [pane.get('platformId'), pane.get('metricId')];
106                 return platformAndMetric[0] || platformAndMetric[1] ? platformAndMetric : [];
107             }));
108         }));
109         this._previousGrid = JSON.stringify(table);
110         this.set('grid', this._previousGrid);
111     },
112
113     _sharedDomainChanged: function ()
114     {
115         var numberOfDays = this.get('numberOfDays');
116         if (!numberOfDays)
117             return;
118
119         numberOfDays = parseInt(numberOfDays);
120         var present = Date.now();
121         var past = present - numberOfDays * 24 * 3600 * 1000;
122         this.set('sharedDomain', [past, present]);
123     }.observes('numberOfDays').on('init'),
124
125     actions: {
126         setNumberOfDays: function (numberOfDays)
127         {
128             this.set('numberOfDays', numberOfDays);
129         },
130         choosePane: function (param)
131         {
132             var pane = param.position;
133             pane.set('platformId', param.platform.get('id'));
134             pane.set('metricId', param.metric.get('id'));
135         },
136         addColumn: function ()
137         {
138             this.get('headerColumns').pushObject({
139                 label: this.get('newColumnHeader'),
140                 index: this.get('headerColumns').length,
141             });
142             this.get('rows').forEach(function (row) {
143                 row.addPane();
144             });
145             this.set('newColumnHeader', null);
146         },
147         removeColumn: function (index)
148         {
149             this.get('headerColumns').removeAt(index);
150             this.get('rows').forEach(function (row) {
151                 row.get('cells').removeAt(index);
152             });
153         },
154         addRow: function ()
155         {
156             this.get('rows').pushObject(App.DashboardRow.create({
157                 store: this.store,
158                 header: this.get('newRowHeader'),
159                 columnCount: this.get('columnCount'),
160             }));
161             this.set('newRowHeader', null);
162         },
163         removeRow: function (row)
164         {
165             this.get('rows').removeObject(row);
166         },
167         resetPane: function (pane)
168         {
169             pane.set('platformId', null);
170             pane.set('metricId', null);
171         },
172         toggleEditMode: function ()
173         {
174             this.toggleProperty('editMode');
175             if (!this.get('editMode'))
176                 this.updateGrid();
177         },
178     },
179
180     init: function ()
181     {
182         this._super();
183         App.Manifest.fetch(this.get('store'));
184     }
185 });
186
187 App.NumberOfDaysControlView = Ember.View.extend({
188     classNames: ['controls'],
189     templateName: 'number-of-days-controls',
190     didInsertElement: function ()
191     {
192         this._matchingElements(this._previousNumberOfDaysClass).addClass('active');
193     },
194     _numberOfDaysChanged: function ()
195     {
196         this._matchingElements(this._previousNumberOfDaysClass).removeClass('active');
197
198         var newNumberOfDaysClass = 'numberOfDaysIs' + this.get('numberOfDays');
199         this._matchingElements(this._previousNumberOfDaysClass).addClass('active');
200         this._previousNumberOfDaysClass = newNumberOfDaysClass;
201     }.observes('numberOfDays').on('init'),
202     _matchingElements: function (className)
203     {
204         var element = this.get('element');
205         if (!element)
206             return $([]);
207         return $(element.getElementsByClassName(className));
208     }
209 });
210
211 App.StartTimeSliderView = Ember.View.extend({
212     templateName: 'start-time-slider',
213     classNames: ['start-time-slider'],
214     startTime: Date.now() - 7 * 24 * 3600 * 1000,
215     oldestStartTime: null,
216     _numberOfDaysView: null,
217     _slider: null,
218     _startTimeInSlider: null,
219     _currentNumberOfDays: null,
220     _MILLISECONDS_PER_DAY: 24 * 3600 * 1000,
221
222     didInsertElement: function ()
223     {
224         this.oldestStartTime = Date.now() - 365 * 24 * 3600 * 1000;
225         this._slider = $(this.get('element')).find('input');
226         this._numberOfDaysView = $(this.get('element')).find('.numberOfDays');
227         this._sliderRangeChanged();
228         this._slider.change(this._sliderMoved.bind(this));
229     },
230     _sliderRangeChanged: function ()
231     {
232         var minimumNumberOfDays = 1;
233         var maximumNumberOfDays = this._timeInPastToNumberOfDays(this.get('oldestStartTime'));
234         var precision = 1000; // FIXME: Compute this from maximumNumberOfDays.
235         var slider = this._slider;
236         slider.attr('min', Math.floor(Math.log(Math.max(1, minimumNumberOfDays)) * precision) / precision);
237         slider.attr('max', Math.ceil(Math.log(maximumNumberOfDays) * precision) / precision);
238         slider.attr('step', 1 / precision);
239         this._startTimeChanged();
240     }.observes('oldestStartTime'),
241     _sliderMoved: function ()
242     {
243         this._currentNumberOfDays = Math.round(Math.exp(this._slider.val()));
244         this._numberOfDaysView.text(this._currentNumberOfDays);
245         this._startTimeInSlider = this._numberOfDaysToTimeInPast(this._currentNumberOfDays);
246         this.set('startTime', this._startTimeInSlider);
247     },
248     _startTimeChanged: function ()
249     {
250         var startTime = this.get('startTime');
251         if (startTime == this._startTimeSetBySlider)
252             return;
253         this._currentNumberOfDays = this._timeInPastToNumberOfDays(startTime);
254
255         if (this._slider) {
256             this._numberOfDaysView.text(this._currentNumberOfDays);
257             this._slider.val(Math.log(this._currentNumberOfDays));
258             this._startTimeInSlider = startTime;
259         }
260     }.observes('startTime').on('init'),
261     _timeInPastToNumberOfDays: function (timeInPast)
262     {
263         return Math.max(1, Math.round((Date.now() - timeInPast) / this._MILLISECONDS_PER_DAY));
264     },
265     _numberOfDaysToTimeInPast: function (numberOfDays)
266     {
267         return Date.now() - numberOfDays * this._MILLISECONDS_PER_DAY;
268     },
269 });
270
271 App.Pane = Ember.Object.extend({
272     platformId: null,
273     platform: null,
274     metricId: null,
275     metric: null,
276     selectedItem: null,
277     searchCommit: function (repository, keyword) {
278         var self = this;
279         var repositoryName = repository.get('id');
280         CommitLogs.fetchForTimeRange(repositoryName, null, null, keyword).then(function (commits) {
281             if (self.isDestroyed || !self.get('chartData') || !commits.length)
282                 return;
283             var currentRuns = self.get('chartData').current.timeSeriesByCommitTime().series();
284             if (!currentRuns.length)
285                 return;
286
287             var highlightedItems = {};
288             var commitIndex = 0;
289             for (var runIndex = 0; runIndex < currentRuns.length && commitIndex < commits.length; runIndex++) {
290                 var measurement = currentRuns[runIndex].measurement;
291                 var commitTime = measurement.commitTimeForRepository(repositoryName);
292                 if (!commitTime)
293                     continue;
294                 if (commits[commitIndex].time <= commitTime) {
295                     highlightedItems[measurement.id()] = true;
296                     do {
297                         commitIndex++;
298                     } while (commitIndex < commits.length && commits[commitIndex].time <= commitTime);
299                 }
300             }
301
302             self.set('highlightedItems', highlightedItems);
303         }, function () {
304             // FIXME: Report errors
305             this.set('highlightedItems', {});
306         });
307     },
308     _fetch: function () {
309         var platformId = this.get('platformId');
310         var metricId = this.get('metricId');
311         if (!platformId && !metricId) {
312             this.set('empty', true);
313             return;
314         }
315         this.set('empty', false);
316         this.set('platform', null);
317         this.set('chartData', null);
318         this.set('metric', null);
319         this.set('failure', null);
320
321         if (!this._isValidId(platformId))
322             this.set('failure', platformId ? 'Invalid platform id:' + platformId : 'Platform id was not specified');
323         else if (!this._isValidId(metricId))
324             this.set('failure', metricId ? 'Invalid metric id:' + metricId : 'Metric id was not specified');
325         else {
326             var self = this;
327
328             App.Manifest.fetchRunsWithPlatformAndMetric(this.get('store'), platformId, metricId).then(function (result) {
329                 self.set('platform', result.platform);
330                 self.set('metric', result.metric);
331                 self.set('chartData', result.runs);
332             }, function (result) {
333                 if (!result || typeof(result) === "string")
334                     self.set('failure', 'Failed to fetch the JSON with an error: ' + result);
335                 else if (!result.platform)
336                     self.set('failure', 'Could not find the platform "' + platformId + '"');
337                 else if (!result.metric)
338                     self.set('failure', 'Could not find the metric "' + metricId + '"');
339                 else
340                     self.set('failure', 'An internal error');
341             });
342
343             this.fetchAnalyticRanges();
344         }
345     }.observes('platformId', 'metricId').on('init'),
346     fetchAnalyticRanges: function ()
347     {
348         var platformId = this.get('platformId');
349         var metricId = this.get('metricId');
350         var self = this;
351         this.get('store')
352             .find('analysisTask', {platform: platformId, metric: metricId})
353             .then(function (tasks) {
354                 self.set('analyticRanges', tasks.filter(function (task) { return task.get('startRun') && task.get('endRun'); }));
355             });
356     },
357     _isValidId: function (id)
358     {
359         if (typeof(id) == "number")
360             return true;
361         if (typeof(id) == "string")
362             return !!id.match(/^[A-Za-z0-9_]+$/);
363         return false;
364     }
365 });
366
367 App.encodePrettifiedJSON = function (plain)
368 {
369     function numberIfPossible(string) {
370         return string == parseInt(string) ? parseInt(string) : string;
371     }
372
373     function recursivelyConvertNumberIfPossible(input) {
374         if (input instanceof Array) {
375             return input.map(recursivelyConvertNumberIfPossible);
376         }
377         return numberIfPossible(input);
378     }
379
380     return JSON.stringify(recursivelyConvertNumberIfPossible(plain))
381         .replace(/\[/g, '(').replace(/\]/g, ')').replace(/\,/g, '-');
382 }
383
384 App.decodePrettifiedJSON = function (encoded)
385 {
386     var parsed = encoded.replace(/\(/g, '[').replace(/\)/g, ']').replace(/\-/g, ',');
387     try {
388         return JSON.parse(parsed);
389     } catch (exception) {
390         return null;
391     }
392 }
393
394 App.ChartsController = Ember.Controller.extend({
395     queryParams: ['paneList', 'zoom', 'since'],
396     needs: ['pane'],
397     _currentEncodedPaneList: null,
398     panes: [],
399     platforms: null,
400     sharedZoom: null,
401     startTime: null,
402     present: Date.now(),
403     defaultSince: Date.now() - 7 * 24 * 3600 * 1000,
404
405     addPane: function (pane)
406     {
407         this.panes.unshiftObject(pane);
408     },
409
410     removePane: function (pane)
411     {
412         this.panes.removeObject(pane);
413     },
414
415     refreshPanes: function()
416     {
417         var paneList = this.get('paneList');
418         if (paneList === this._currentEncodedPaneList)
419             return;
420
421         var panes = this._parsePaneList(paneList || '[]');
422         if (!panes) {
423             console.log('Failed to parse', jsonPaneList, exception);
424             return;
425         }
426         this.set('panes', panes);
427         this._currentEncodedPaneList = paneList;
428     }.observes('paneList').on('init'),
429
430     refreshZoom: function()
431     {
432         var zoom = this.get('zoom');
433         if (!zoom) {
434             this.set('sharedZoom', null);
435             return;
436         }
437
438         zoom = zoom.split('-');
439         var selection = new Array(2);
440         try {
441             selection[0] = new Date(parseFloat(zoom[0]));
442             selection[1] = new Date(parseFloat(zoom[1]));
443         } catch (error) {
444             console.log('Failed to parse the zoom', zoom);
445         }
446         this.set('sharedZoom', selection);
447
448         var startTime = this.get('startTime');
449         if (startTime && startTime > selection[0])
450             this.set('startTime', selection[0]);
451
452     }.observes('zoom').on('init'),
453
454     _startTimeChanged: function () {
455         this.set('sharedDomain', [this.get('startTime'), this.get('present')]);
456         this._scheduleQueryStringUpdate();
457     }.observes('startTime'),
458
459     _sinceChanged: function () {
460         var since = parseInt(this.get('since'));
461         if (isNaN(since))
462             since = this.defaultSince;
463         this.set('startTime', new Date(since));
464     }.observes('since').on('init'),
465
466     _parsePaneList: function (encodedPaneList)
467     {
468         var parsedPaneList = App.decodePrettifiedJSON(encodedPaneList);
469         if (!parsedPaneList)
470             return null;
471
472         // Don't re-create all panes.
473         var self = this;
474         return parsedPaneList.map(function (paneInfo) {
475             var timeRange = null;
476             if (paneInfo[3] && paneInfo[3] instanceof Array) {
477                 var timeRange = paneInfo[3];
478                 try {
479                     timeRange = [new Date(timeRange[0]), new Date(timeRange[1])];
480                 } catch (error) {
481                     console.log("Failed to parse the time range:", timeRange, error);
482                 }
483             }
484             return App.Pane.create({
485                 store: self.store,
486                 info: paneInfo,
487                 platformId: paneInfo[0],
488                 metricId: paneInfo[1],
489                 selectedItem: paneInfo[2],
490                 timeRange: timeRange,
491                 timeRangeIsLocked: !!paneInfo[4],
492             });
493         });
494     },
495
496     _serializePaneList: function (panes)
497     {
498         if (!panes.length)
499             return undefined;
500         return App.encodePrettifiedJSON(panes.map(function (pane) {
501             return [
502                 pane.get('platformId'),
503                 pane.get('metricId'),
504                 pane.get('selectedItem'),
505                 pane.get('timeRange') ? pane.get('timeRange').map(function (date) { return date.getTime() }) : null,
506                 !!pane.get('timeRangeIsLocked'),
507             ];
508         }));
509     },
510
511     _scheduleQueryStringUpdate: function ()
512     {
513         Ember.run.debounce(this, '_updateQueryString', 1000);
514     }.observes('sharedZoom', 'panes.@each.platform', 'panes.@each.metric', 'panes.@each.selectedItem',
515         'panes.@each.timeRange', 'panes.@each.timeRangeIsLocked'),
516
517     _updateQueryString: function ()
518     {
519         this._currentEncodedPaneList = this._serializePaneList(this.get('panes'));
520         this.set('paneList', this._currentEncodedPaneList);
521
522         var zoom = undefined;
523         var sharedZoom = this.get('sharedZoom');
524         if (sharedZoom && !App.domainsAreEqual(sharedZoom, this.get('sharedDomain')))
525             zoom = +sharedZoom[0] + '-' + +sharedZoom[1];
526         this.set('zoom', zoom);
527
528         if (this.get('startTime') - this.defaultSince)
529             this.set('since', this.get('startTime') - 0);
530     },
531
532     actions: {
533         addPaneByMetricAndPlatform: function (param)
534         {
535             this.addPane(App.Pane.create({
536                 store: this.store,
537                 platformId: param.platform.get('id'),
538                 metricId: param.metric.get('id'),
539                 showingDetails: false
540             }));
541         },
542     },
543
544     init: function ()
545     {
546         this._super();
547         var self = this;
548         App.buildPopup(this.store, 'addPaneByMetricAndPlatform').then(function (platforms) {
549             self.set('platforms', platforms);
550         });
551     },
552 });
553
554 App.buildPopup = function(store, action, position)
555 {
556     return App.Manifest.fetch(store).then(function () {
557         return App.Manifest.get('platforms').map(function (platform) {
558             return App.PlatformProxyForPopup.create({content: platform,
559                 action: action, position: position});
560         });
561     });
562 }
563
564 App.PlatformProxyForPopup = Ember.ObjectProxy.extend({
565     children: function ()
566     {
567         var platform = this.content;
568         var containsTest = this.content.containsTest.bind(this.content);
569         var action = this.get('action');
570         var position = this.get('position');
571         return App.Manifest.get('topLevelTests')
572             .filter(containsTest)
573             .map(function (test) {
574                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
575             });
576     }.property('App.Manifest.topLevelTests'),
577 });
578
579 App.TestProxyForPopup = Ember.ObjectProxy.extend({
580     platform: null,
581     children: function ()
582     {
583         var platform = this.get('platform');
584         var action = this.get('action');
585         var position = this.get('position');
586
587         var childTests = this.get('childTests')
588             .filter(function (test) { return platform.containsTest(test); })
589             .map(function (test) {
590                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
591             });
592
593         var metrics = this.get('metrics')
594             .filter(function (metric) { return platform.containsMetric(metric); })
595             .map(function (metric) {
596                 var aggregator = metric.get('aggregator');
597                 return {
598                     actionName: action,
599                     actionArgument: {platform: platform, metric: metric, position:position},
600                     label: metric.get('label')
601                 };
602             });
603
604         if (childTests.length && metrics.length)
605             metrics.push({isSeparator: true});
606
607         return metrics.concat(childTests);
608     }.property('childTests', 'metrics'),
609 });
610
611 App.domainsAreEqual = function (domain1, domain2) {
612     return (!domain1 && !domain2) || (domain1 && domain2 && !(domain1[0] - domain2[0]) && !(domain1[1] - domain2[1]));
613 }
614
615 App.PaneController = Ember.ObjectController.extend({
616     needs: ['charts'],
617     sharedTime: Ember.computed.alias('parentController.sharedTime'),
618     sharedSelection: Ember.computed.alias('parentController.sharedSelection'),
619     selection: null,
620     actions: {
621         toggleDetails: function()
622         {
623             this.toggleProperty('showingDetails');
624         },
625         close: function ()
626         {
627             this.parentController.removePane(this.get('model'));
628         },
629         toggleBugsPane: function ()
630         {
631             if (this.toggleProperty('showingAnalysisPane'))
632                 this.set('showingSearchPane', false);
633         },
634         createAnalysisTask: function ()
635         {
636             var name = this.get('newAnalysisTaskName');
637             var points = this.get('selectedPoints');
638             Ember.assert('The analysis name should not be empty', name);
639             Ember.assert('There should be at least two points in the range', points && points.length >= 2);
640
641             var newWindow = window.open();
642             var self = this;
643             App.AnalysisTask.create(name, points[0].measurement, points[points.length - 1].measurement).then(function (data) {
644                 // FIXME: Update the UI to show the new analysis task.
645                 var url = App.Router.router.generate('analysisTask', data['taskId']);
646                 newWindow.location.href = '#' + url;
647                 self.get('model').fetchAnalyticRanges();
648             }, function (error) {
649                 newWindow.close();
650                 if (error === 'DuplicateAnalysisTask') {
651                     // FIXME: Duplicate this error more gracefully.
652                 }
653                 alert(error);
654             });
655         },
656         toggleSearchPane: function ()
657         {
658             if (!App.Manifest.repositoriesWithReportedCommits)
659                 return;
660             var model = this.get('model');
661             if (!model.get('commitSearchRepository'))
662                 model.set('commitSearchRepository', App.Manifest.repositoriesWithReportedCommits[0]);
663             if (this.toggleProperty('showingSearchPane'))
664                 this.set('showingAnalysisPane', false);
665         },
666         searchCommit: function () {
667             var model = this.get('model');
668             model.searchCommit(model.get('commitSearchRepository'), model.get('commitSearchKeyword'));                
669         },
670         zoomed: function (selection)
671         {
672             this.set('mainPlotDomain', selection ? selection : this.get('overviewDomain'));
673             Ember.run.debounce(this, 'propagateZoom', 100);
674         },
675     },
676     _detailsChanged: function ()
677     {
678         this.set('showingAnalysisPane', false);
679     }.observes('details'),
680     _overviewSelectionChanged: function ()
681     {
682         var overviewSelection = this.get('overviewSelection');
683         this.set('mainPlotDomain', overviewSelection || this.get('overviewDomain'));
684         Ember.run.debounce(this, 'propagateZoom', 100);
685     }.observes('overviewSelection'),
686     _sharedDomainChanged: function ()
687     {
688         var newDomain = this.get('parentController').get('sharedDomain');
689         if (App.domainsAreEqual(newDomain, this.get('overviewDomain')))
690             return;
691         this.set('overviewDomain', newDomain);
692         if (!this.get('overviewSelection'))
693             this.set('mainPlotDomain', newDomain);
694     }.observes('parentController.sharedDomain').on('init'),
695     propagateZoom: function ()
696     {
697         this.get('parentController').set('sharedZoom', this.get('mainPlotDomain'));
698     },
699     _sharedZoomChanged: function ()
700     {
701         var newSelection = this.get('parentController').get('sharedZoom');
702         if (App.domainsAreEqual(newSelection, this.get('mainPlotDomain')))
703             return;
704         this.set('overviewSelection', newSelection);
705     }.observes('parentController.sharedZoom').on('init'),
706     _updateDetails: function ()
707     {
708         var selectedPoints = this.get('selectedPoints');
709         var currentPoint = this.get('currentItem');
710         if (!selectedPoints && !currentPoint) {
711             this.set('details', null);
712             return;
713         }
714
715         var currentMeasurement;
716         var oldMeasurement;
717         if (currentPoint) {
718             currentMeasurement = currentPoint.measurement;
719             var previousPoint = currentPoint.series.previousPoint(currentPoint);
720             oldMeasurement = previousPoint ? previousPoint.measurement : null;
721         } else {
722             currentMeasurement = selectedPoints[selectedPoints.length - 1].measurement;
723             oldMeasurement = selectedPoints[0].measurement;            
724         }
725
726         var formattedRevisions = currentMeasurement.formattedRevisions(oldMeasurement);
727         var revisions = App.Manifest.get('repositories')
728             .filter(function (repository) { return formattedRevisions[repository.get('id')]; })
729             .map(function (repository) {
730             var repositoryName = repository.get('id');
731             var revision = Ember.Object.create(formattedRevisions[repositoryName]);
732             revision['url'] = revision.previousRevision
733                 ? repository.urlForRevisionRange(revision.previousRevision, revision.currentRevision)
734                 : repository.urlForRevision(revision.currentRevision);
735             revision['name'] = repositoryName;
736             revision['repository'] = repository;
737             return revision; 
738         });
739
740         var buildNumber = null;
741         var buildURL = null;
742         if (currentPoint) {
743             buildNumber = currentMeasurement.buildNumber();
744             var builder = App.Manifest.builder(currentMeasurement.builderId());
745             if (builder)
746                 buildURL = builder.urlFromBuildNumber(buildNumber);
747         }
748
749         this.set('details', Ember.Object.create({
750             currentValue: currentMeasurement.mean().toFixed(2),
751             oldValue: oldMeasurement && selectedPoints ? oldMeasurement.mean().toFixed(2) : null,
752             buildNumber: buildNumber,
753             buildURL: buildURL,
754             buildTime: currentMeasurement.formattedBuildTime(),
755             revisions: revisions,
756         }));
757         this._updateCanAnalyze();
758     }.observes('currentItem', 'selectedPoints'),
759     _updateCanAnalyze: function ()
760     {
761         var points = this.get('selectedPoints');
762         this.set('cannotAnalyze', !this.get('newAnalysisTaskName') || !points || points.length < 2);
763     }.observes('newAnalysisTaskName'),
764 });
765
766 App.InteractiveChartComponent = Ember.Component.extend({
767     chartData: null,
768     showXAxis: true,
769     showYAxis: true,
770     interactive: false,
771     enableSelection: true,
772     classNames: ['chart'],
773     init: function ()
774     {
775         this._super();
776         this._needsConstruction = true;
777         this._eventHandlers = [];
778         $(window).resize(this._updateDimensionsIfNeeded.bind(this));
779     },
780     chartDataDidChange: function ()
781     {
782         var chartData = this.get('chartData');
783         if (!chartData)
784             return;
785         this._needsConstruction = true;
786         this._constructGraphIfPossible(chartData);
787     }.observes('chartData').on('init'),
788     didInsertElement: function ()
789     {
790         var chartData = this.get('chartData');
791         if (chartData)
792             this._constructGraphIfPossible(chartData);
793     },
794     willClearRender: function ()
795     {
796         this._eventHandlers.forEach(function (item) {
797             $(item[0]).off(item[1], item[2]);
798         })
799     },
800     _attachEventListener: function(target, eventName, listener)
801     {
802         this._eventHandlers.push([target, eventName, listener]);
803         $(target).on(eventName, listener);
804     },
805     _constructGraphIfPossible: function (chartData)
806     {
807         if (!this._needsConstruction || !this.get('element'))
808             return;
809
810         var element = this.get('element');
811
812         this._x = d3.time.scale();
813         this._y = d3.scale.linear();
814
815         // FIXME: Tear down the old SVG element.
816         this._svgElement = d3.select(element).append("svg")
817                 .attr("width", "100%")
818                 .attr("height", "100%");
819
820         var svg = this._svg = this._svgElement.append("g");
821
822         var clipId = element.id + "-clip";
823         this._clipPath = svg.append("defs").append("clipPath")
824             .attr("id", clipId)
825             .append("rect");
826
827         if (this.get('showXAxis')) {
828             this._xAxis = d3.svg.axis().scale(this._x).orient("bottom").ticks(6);
829             this._xAxisLabels = svg.append("g")
830                 .attr("class", "x axis");
831         }
832
833         if (this.get('showYAxis')) {
834             this._yAxis = d3.svg.axis().scale(this._y).orient("left").ticks(6).tickFormat(d3.format("s"));
835             this._yAxisLabels = svg.append("g")
836                 .attr("class", "y axis");
837         }
838
839         this._clippedContainer = svg.append("g")
840             .attr("clip-path", "url(#" + clipId + ")");
841
842         var xScale = this._x;
843         var yScale = this._y;
844         this._timeLine = d3.svg.line()
845             .x(function(point) { return xScale(point.time); })
846             .y(function(point) { return yScale(point.value); });
847
848         this._confidenceArea = d3.svg.area()
849 //            .interpolate("cardinal")
850             .x(function(point) { return xScale(point.time); })
851             .y0(function(point) { return point.interval ? yScale(point.interval[0]) : null; })
852             .y1(function(point) { return point.interval ? yScale(point.interval[1]) : null; });
853
854         if (this._paths)
855             this._paths.forEach(function (path) { path.remove(); });
856         this._paths = [];
857         if (this._areas)
858             this._areas.forEach(function (area) { area.remove(); });
859         this._areas = [];
860         if (this._dots)
861             this._dots.forEach(function (dot) { dots.remove(); });
862         this._dots = [];
863         if (this._highlights)
864             this._highlights.forEach(function (highlight) { highlight.remove(); });
865         this._highlights = [];
866
867         this._currentTimeSeries = chartData.current.timeSeriesByCommitTime();
868         this._currentTimeSeriesData = this._currentTimeSeries.series();
869         this._baselineTimeSeries = chartData.baseline ? chartData.baseline.timeSeriesByCommitTime() : null;
870         this._targetTimeSeries = chartData.target ? chartData.target.timeSeriesByCommitTime() : null;
871
872         this._yAxisUnit = chartData.unit;
873
874         var minMax = this._minMaxForAllTimeSeries();
875         var smallEnoughValue = minMax[0] - (minMax[1] - minMax[0]) * 10;
876         var largeEnoughValue = minMax[1] + (minMax[1] - minMax[0]) * 10;
877
878         // FIXME: Flip the sides based on smallerIsBetter-ness.
879         if (this._baselineTimeSeries) {
880             var data = this._baselineTimeSeries.series();
881             this._areas.push(this._clippedContainer
882                 .append("path")
883                 .datum(data.map(function (point) { return {time: point.time, value: point.value, interval: point.interval ? point.interval : [point.value, largeEnoughValue]}; }))
884                 .attr("class", "area baseline"));
885         }
886         if (this._targetTimeSeries) {
887             var data = this._targetTimeSeries.series();
888             this._areas.push(this._clippedContainer
889                 .append("path")
890                 .datum(data.map(function (point) { return {time: point.time, value: point.value, interval: point.interval ? point.interval : [smallEnoughValue, point.value]}; }))
891                 .attr("class", "area target"));
892         }
893
894         this._areas.push(this._clippedContainer
895             .append("path")
896             .datum(this._currentTimeSeriesData)
897             .attr("class", "area"));
898
899         this._paths.push(this._clippedContainer
900             .append("path")
901             .datum(this._currentTimeSeriesData)
902             .attr("class", "commit-time-line"));
903
904         this._dots.push(this._clippedContainer
905             .selectAll(".dot")
906                 .data(this._currentTimeSeriesData)
907             .enter().append("circle")
908                 .attr("class", "dot")
909                 .attr("r", this.get('chartPointRadius') || 1));
910
911         if (this.get('interactive')) {
912             this._attachEventListener(element, "mousemove", this._mouseMoved.bind(this));
913             this._attachEventListener(element, "mouseleave", this._mouseLeft.bind(this));
914             this._attachEventListener(element, "mousedown", this._mouseDown.bind(this));
915             this._attachEventListener($(element).parents("[tabindex]"), "keydown", this._keyPressed.bind(this));
916
917             this._currentItemLine = this._clippedContainer
918                 .append("line")
919                 .attr("class", "current-item");
920
921             this._currentItemCircle = this._clippedContainer
922                 .append("circle")
923                 .attr("class", "dot current-item")
924                 .attr("r", 3);
925         }
926
927         this._brush = null;
928         if (this.get('enableSelection')) {
929             this._brush = d3.svg.brush()
930                 .x(this._x)
931                 .on("brush", this._brushChanged.bind(this));
932
933             this._brushRect = this._clippedContainer
934                 .append("g")
935                 .attr("class", "x brush");
936         }
937
938         this._updateDomain();
939         this._updateDimensionsIfNeeded();
940
941         // Work around the fact the brush isn't set if we updated it synchronously here.
942         setTimeout(this._selectionChanged.bind(this), 0);
943
944         setTimeout(this._selectedItemChanged.bind(this), 0);
945
946         this._needsConstruction = false;
947
948         this._rangesChanged();
949     },
950     _updateDomain: function ()
951     {
952         var xDomain = this.get('domain');
953         var intrinsicXDomain = this._computeXAxisDomain(this._currentTimeSeriesData);
954         if (!xDomain)
955             xDomain = intrinsicXDomain;
956         var currentDomain = this._x.domain();
957         if (currentDomain && App.domainsAreEqual(currentDomain, xDomain))
958             return currentDomain;
959
960         var yDomain = this._computeYAxisDomain(xDomain[0], xDomain[1]);
961         this._x.domain(xDomain);
962         this._y.domain(yDomain);
963         return xDomain;
964     },
965     _updateDimensionsIfNeeded: function (newSelection)
966     {
967         var element = $(this.get('element'));
968
969         var newTotalWidth = element.width();
970         var newTotalHeight = element.height();
971         if (this._totalWidth == newTotalWidth && this._totalHeight == newTotalHeight)
972             return;
973
974         this._totalWidth = newTotalWidth;
975         this._totalHeight = newTotalHeight;
976
977         if (!this._rem)
978             this._rem = parseFloat(getComputedStyle(document.documentElement).fontSize);
979         var rem = this._rem;
980
981         var padding = 0.5 * rem;
982         var margin = {top: padding, right: padding, bottom: padding, left: padding};
983         if (this._xAxis)
984             margin.bottom += rem;
985         if (this._yAxis)
986             margin.left += 3 * rem;
987
988         this._margin = margin;
989         this._contentWidth = this._totalWidth - margin.left - margin.right;
990         this._contentHeight = this._totalHeight - margin.top - margin.bottom;
991
992         this._svg.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
993
994         this._clipPath
995             .attr("width", this._contentWidth)
996             .attr("height", this._contentHeight);
997
998         this._x.range([0, this._contentWidth]);
999         this._y.range([this._contentHeight, 0]);
1000
1001         if (this._xAxis) {
1002             this._xAxis.tickSize(-this._contentHeight);
1003             this._xAxisLabels.attr("transform", "translate(0," + this._contentHeight + ")");
1004         }
1005
1006         if (this._yAxis)
1007             this._yAxis.tickSize(-this._contentWidth);
1008
1009         if (this._currentItemLine) {
1010             this._currentItemLine
1011                 .attr("y1", 0)
1012                 .attr("y2", margin.top + this._contentHeight);
1013         }
1014
1015         this._relayoutDataAndAxes(this._currentSelection());
1016     },
1017     _updateBrush: function ()
1018     {
1019         this._brushRect
1020             .call(this._brush)
1021         .selectAll("rect")
1022             .attr("y", 1)
1023             .attr("height", this._contentHeight - 2);
1024         this._updateSelectionToolbar();
1025     },
1026     _relayoutDataAndAxes: function (selection)
1027     {
1028         var timeline = this._timeLine;
1029         this._paths.forEach(function (path) { path.attr("d", timeline); });
1030
1031         var confidenceArea = this._confidenceArea;
1032         this._areas.forEach(function (path) { path.attr("d", confidenceArea); });
1033
1034         var xScale = this._x;
1035         var yScale = this._y;
1036         this._dots.forEach(function (dot) {
1037             dot
1038                 .attr("cx", function(measurement) { return xScale(measurement.time); })
1039                 .attr("cy", function(measurement) { return yScale(measurement.value); });
1040         });
1041         this._updateMarkedDots();
1042         this._updateHighlightPositions();
1043         this._updateRangeBarRects();
1044
1045         if (this._brush) {
1046             if (selection)
1047                 this._brush.extent(selection);
1048             else
1049                 this._brush.clear();
1050             this._updateBrush();
1051         }
1052
1053         this._updateCurrentItemIndicators();
1054
1055         if (this._xAxis)
1056             this._xAxisLabels.call(this._xAxis);
1057         if (!this._yAxis)
1058             return;
1059
1060         this._yAxisLabels.call(this._yAxis);
1061         if (this._yAxisUnitContainer)
1062             this._yAxisUnitContainer.remove();
1063         this._yAxisUnitContainer = this._yAxisLabels.append("text")
1064             .attr("x", 0.5 * this._rem)
1065             .attr("y", 0.2 * this._rem)
1066             .attr("dy", 0.8 * this._rem)
1067             .style("text-anchor", "start")
1068             .style("z-index", "100")
1069             .text(this._yAxisUnit);
1070     },
1071     _updateMarkedDots: function () {
1072         var markedPoints = this.get('markedPoints') || {};
1073         var defaultDotRadius = this.get('chartPointRadius') || 1;
1074         this._dots.forEach(function (dot) {
1075             dot.classed('marked', function (point) { return markedPoints[point.measurement.id()]; });
1076             dot.attr('r', function (point) {
1077                 return markedPoints[point.measurement.id()] ? defaultDotRadius * 1.5 : defaultDotRadius; });
1078         });
1079     }.observes('markedPoints'),
1080     _updateHighlightPositions: function () {
1081         var xScale = this._x;
1082         var yScale = this._y;
1083         var y2 = this._margin.top + this._contentHeight;
1084         this._highlights.forEach(function (highlight) {
1085             highlight
1086                 .attr("y1", 0)
1087                 .attr("y2", y2)
1088                 .attr("y", function(measurement) { return yScale(measurement.value); })
1089                 .attr("x1", function(measurement) { return xScale(measurement.time); })
1090                 .attr("x2", function(measurement) { return xScale(measurement.time); });
1091         });
1092     },
1093     _computeXAxisDomain: function (timeSeries)
1094     {
1095         var extent = d3.extent(timeSeries, function(point) { return point.time; });
1096         var margin = 3600 * 1000; // Use x.inverse to compute the right amount from a margin.
1097         return [+extent[0] - margin, +extent[1] + margin];
1098     },
1099     _computeYAxisDomain: function (startTime, endTime)
1100     {
1101         var range = this._minMaxForAllTimeSeries(startTime, endTime);
1102         var min = range[0];
1103         var max = range[1];
1104         if (max < min)
1105             min = max = 0;
1106         var diff = max - min;
1107         var margin = diff * 0.05;
1108
1109         yExtent = [min - margin, max + margin];
1110 //        if (yMin !== undefined)
1111 //            yExtent[0] = parseInt(yMin);
1112         return yExtent;
1113     },
1114     _minMaxForAllTimeSeries: function (startTime, endTime)
1115     {
1116         var currentRange = this._currentTimeSeries.minMaxForTimeRange(startTime, endTime);
1117         var baselineRange = this._baselineTimeSeries ? this._baselineTimeSeries.minMaxForTimeRange(startTime, endTime) : [Number.MAX_VALUE, Number.MIN_VALUE];
1118         var targetRange = this._targetTimeSeries ? this._targetTimeSeries.minMaxForTimeRange(startTime, endTime) : [Number.MAX_VALUE, Number.MIN_VALUE];
1119         return [
1120             Math.min(currentRange[0], baselineRange[0], targetRange[0]),
1121             Math.max(currentRange[1], baselineRange[1], targetRange[1]),
1122         ];
1123     },
1124     _currentSelection: function ()
1125     {
1126         return this._brush && !this._brush.empty() ? this._brush.extent() : null;
1127     },
1128     _domainChanged: function ()
1129     {
1130         var selection = this._currentSelection() || this.get('sharedSelection');
1131         var newXDomain = this._updateDomain();
1132
1133         if (selection && newXDomain && selection[0] <= newXDomain[0] && newXDomain[1] <= selection[1])
1134             selection = null; // Otherwise the user has no way of clearing the selection.
1135
1136         this._relayoutDataAndAxes(selection);
1137     }.observes('domain'),
1138     _selectionChanged: function ()
1139     {
1140         this._updateSelection(this.get('selection'));
1141     }.observes('selection'),
1142     _updateSelection: function (newSelection)
1143     {
1144         if (!this._brush)
1145             return;
1146
1147         var currentSelection = this._currentSelection();
1148         if (newSelection && currentSelection && App.domainsAreEqual(newSelection, currentSelection))
1149             return;
1150
1151         var domain = this._x.domain();
1152         if (!newSelection || App.domainsAreEqual(domain, newSelection))
1153             this._brush.clear();
1154         else
1155             this._brush.extent(newSelection);
1156         this._updateBrush();
1157
1158         this._setCurrentSelection(newSelection);
1159     },
1160     _brushChanged: function ()
1161     {
1162         if (this._brush.empty()) {
1163             if (!this._brushExtent)
1164                 return;
1165
1166             this.set('selectionIsLocked', false);
1167             this._setCurrentSelection(undefined);
1168
1169             // Avoid locking the indicator in _mouseDown when the brush was cleared in the same mousedown event.
1170             this._brushJustChanged = true;
1171             var self = this;
1172             setTimeout(function () {
1173                 self._brushJustChanged = false;
1174             }, 0);
1175
1176             return;
1177         }
1178
1179         this.set('selectionIsLocked', true);
1180         this._setCurrentSelection(this._brush.extent());
1181     },
1182     _keyPressed: function (event)
1183     {
1184         if (!this._currentItemIndex || this._currentSelection())
1185             return;
1186
1187         var newIndex;
1188         switch (event.keyCode) {
1189         case 37: // Left
1190             newIndex = this._currentItemIndex - 1;
1191             break;
1192         case 39: // Right
1193             newIndex = this._currentItemIndex + 1;
1194             break;
1195         case 38: // Up
1196         case 40: // Down
1197         default:
1198             return;
1199         }
1200
1201         // Unlike mousemove, keydown shouldn't move off the edge.
1202         if (this._currentTimeSeriesData[newIndex])
1203             this._setCurrentItem(newIndex);
1204     },
1205     _mouseMoved: function (event)
1206     {
1207         if (!this._margin || this._currentSelection() || this._currentItemLocked)
1208             return;
1209
1210         var point = this._mousePointInGraph(event);
1211
1212         this._selectClosestPointToMouseAsCurrentItem(point);
1213     },
1214     _mouseLeft: function (event)
1215     {
1216         if (!this._margin || this._currentItemLocked)
1217             return;
1218
1219         this._selectClosestPointToMouseAsCurrentItem(null);
1220     },
1221     _mouseDown: function (event)
1222     {
1223         if (!this._margin || this._currentSelection() || this._brushJustChanged)
1224             return;
1225
1226         var point = this._mousePointInGraph(event);
1227         if (!point)
1228             return;
1229
1230         if (this._currentItemLocked) {
1231             this._currentItemLocked = false;
1232             this.set('selectedItem', null);
1233             return;
1234         }
1235
1236         this._currentItemLocked = true;
1237         this._selectClosestPointToMouseAsCurrentItem(point);
1238     },
1239     _mousePointInGraph: function (event)
1240     {
1241         var offset = $(this.get('element')).offset();
1242         if (!offset || !$(event.target).closest('svg').length)
1243             return null;
1244
1245         var point = {
1246             x: event.pageX - offset.left - this._margin.left,
1247             y: event.pageY - offset.top - this._margin.top
1248         };
1249
1250         var xScale = this._x;
1251         var yScale = this._y;
1252         var xDomain = xScale.domain();
1253         var yDomain = yScale.domain();
1254         if (point.x >= xScale(xDomain[0]) && point.x <= xScale(xDomain[1])
1255             && point.y <= yScale(yDomain[0]) && point.y >= yScale(yDomain[1]))
1256             return point;
1257
1258         return null;
1259     },
1260     _selectClosestPointToMouseAsCurrentItem: function (point)
1261     {
1262         var xScale = this._x;
1263         var yScale = this._y;
1264         var distanceHeuristics = function (m) {
1265             var mX = xScale(m.time);
1266             var mY = yScale(m.value);
1267             var xDiff = mX - point.x;
1268             var yDiff = mY - point.y;
1269             return xDiff * xDiff + yDiff * yDiff / 16; // Favor horizontal affinity.
1270         };
1271         distanceHeuristics = function (m) {
1272             return Math.abs(xScale(m.time) - point.x);
1273         }
1274
1275         var newItemIndex;
1276         if (point && !this._currentSelection()) {
1277             var distances = this._currentTimeSeriesData.map(distanceHeuristics);
1278             var minDistance = Number.MAX_VALUE;
1279             for (var i = 0; i < distances.length; i++) {
1280                 if (distances[i] < minDistance) {
1281                     newItemIndex = i;
1282                     minDistance = distances[i];
1283                 }
1284             }
1285         }
1286
1287         this._setCurrentItem(newItemIndex);
1288         this._updateSelectionToolbar();
1289     },
1290     _currentTimeChanged: function ()
1291     {
1292         if (!this._margin || this._currentSelection() || this._currentItemLocked)
1293             return
1294
1295         var currentTime = this.get('currentTime');
1296         if (currentTime) {
1297             for (var i = 0; i < this._currentTimeSeriesData.length; i++) {
1298                 var point = this._currentTimeSeriesData[i];
1299                 if (point.time >= currentTime) {
1300                     this._setCurrentItem(i, /* doNotNotify */ true);
1301                     return;
1302                 }
1303             }
1304         }
1305         this._setCurrentItem(undefined, /* doNotNotify */ true);
1306     }.observes('currentTime'),
1307     _setCurrentItem: function (newItemIndex, doNotNotify)
1308     {
1309         if (newItemIndex === this._currentItemIndex) {
1310             if (this._currentItemLocked)
1311                 this.set('selectedItem', this.get('currentItem') ? this.get('currentItem').measurement.id() : null);
1312             return;
1313         }
1314
1315         var newItem = this._currentTimeSeriesData[newItemIndex];
1316         this._brushExtent = undefined;
1317         this._currentItemIndex = newItemIndex;
1318
1319         if (!newItem) {
1320             this._currentItemLocked = false;
1321             this.set('selectedItem', null);
1322         }
1323
1324         this._updateCurrentItemIndicators();
1325
1326         if (!doNotNotify)
1327             this.set('currentTime', newItem ? newItem.time : undefined);
1328
1329         this.set('currentItem', newItem);
1330         if (this._currentItemLocked)
1331             this.set('selectedItem', newItem ? newItem.measurement.id() : null);
1332     },
1333     _selectedItemChanged: function ()
1334     {
1335         if (!this._margin)
1336             return;
1337
1338         var selectedId = this.get('selectedItem');
1339         var currentItem = this.get('currentItem');
1340         if (currentItem && currentItem.measurement.id() == selectedId)
1341             return;
1342
1343         var series = this._currentTimeSeriesData;
1344         var selectedItemIndex = undefined;
1345         for (var i = 0; i < series.length; i++) {
1346             if (series[i].measurement.id() == selectedId) {
1347                 this._updateSelection(null);
1348                 this._currentItemLocked = true;
1349                 this._setCurrentItem(i);
1350                 this._updateSelectionToolbar();
1351                 return;
1352             }
1353         }
1354     }.observes('selectedItem').on('init'),
1355     _highlightedItemsChanged: function () {
1356         if (!this._margin)
1357             return;
1358
1359         var highlightedItems = this.get('highlightedItems');
1360
1361         var data = this._currentTimeSeriesData.filter(function (item) { return highlightedItems[item.measurement.id()]; });
1362
1363         if (this._highlights.length)
1364             this._highlights.forEach(function (highlight) { highlight.remove(); });
1365
1366         this._highlights.push(this._clippedContainer
1367             .selectAll(".highlight")
1368                 .data(data)
1369             .enter().append("line")
1370                 .attr("class", "highlight"));
1371
1372         this._updateHighlightPositions();
1373
1374     }.observes('highlightedItems'),
1375     _rangesChanged: function ()
1376     {
1377         if (!this._currentTimeSeries)
1378             return;
1379
1380         function midPoint(firstPoint, secondPoint) {
1381             if (firstPoint && secondPoint)
1382                 return (+firstPoint.time + +secondPoint.time) / 2;
1383             if (firstPoint)
1384                 return firstPoint.time;
1385             return secondPoint.time;
1386         }
1387         var currentTimeSeries = this._currentTimeSeries;
1388         var linkRoute = this.get('rangeRoute');
1389         this.set('rangeBars', (this.get('ranges') || []).map(function (range) {
1390             var start = currentTimeSeries.findPointByMeasurementId(range.get('startRun'));
1391             var end = currentTimeSeries.findPointByMeasurementId(range.get('endRun'));
1392             return Ember.Object.create({
1393                 startTime: midPoint(currentTimeSeries.previousPoint(start), start),
1394                 endTime: midPoint(end, currentTimeSeries.nextPoint(end)),
1395                 range: range,
1396                 left: null,
1397                 right: null,
1398                 rowIndex: null,
1399                 top: null,
1400                 bottom: null,
1401                 linkRoute: linkRoute,
1402                 linkId: range.get('id'),
1403                 label: range.get('label'),
1404             });
1405         }));
1406
1407         this._updateRangeBarRects();
1408     }.observes('ranges'),
1409     _updateRangeBarRects: function () {
1410         var rangeBars = this.get('rangeBars');
1411         if (!rangeBars || !rangeBars.length)
1412             return;
1413
1414         var xScale = this._x;
1415         var yScale = this._y;
1416
1417         // Expand the width of each range as needed and sort ranges by the left-edge of ranges.
1418         var minWidth = 3;
1419         var sortedBars = rangeBars.map(function (bar) {
1420             var left = xScale(bar.get('startTime'));
1421             var right = xScale(bar.get('endTime'));
1422             if (right - left < minWidth) {
1423                 left -= minWidth / 2;
1424                 right += minWidth / 2;
1425             }
1426             bar.set('left', left);
1427             bar.set('right', right);
1428             return bar;
1429         }).sort(function (first, second) { return first.get('left') - second.get('left'); });
1430
1431         // At this point, left edges of all ranges prior to a range R1 is on the left of R1.
1432         // Place R1 into a row in which right edges of all ranges prior to R1 is on the left of R1 to avoid overlapping ranges.
1433         var rows = [];
1434         sortedBars.forEach(function (bar) {
1435             var rowIndex = 0;
1436             for (; rowIndex < rows.length; rowIndex++) {
1437                 var currentRow = rows[rowIndex];
1438                 if (currentRow[currentRow.length - 1].get('right') < bar.get('left')) {
1439                     currentRow.push(bar);
1440                     break;
1441                 }
1442             }
1443             if (rowIndex >= rows.length)
1444                 rows.push([bar]);
1445             bar.set('rowIndex', rowIndex);
1446         });
1447         var rowHeight = 0.6 * this._rem;
1448         var firstRowTop = this._contentHeight - rows.length * rowHeight;
1449         var barHeight = 0.5 * this._rem;
1450
1451         $(this.get('element')).find('.rangeBarsContainerInlineStyle').css({
1452             left: this._margin.left + 'px',
1453             top: this._margin.top + firstRowTop + 'px',
1454             width: this._contentWidth + 'px',
1455             height: rows.length * barHeight + 'px',
1456             overflow: 'hidden',
1457             position: 'absolute',
1458         });
1459
1460         var margin = this._margin;
1461         sortedBars.forEach(function (bar) {
1462             var top = bar.get('rowIndex') * rowHeight;
1463             var height = barHeight;
1464             var left = bar.get('left');
1465             var width = bar.get('right') - left;
1466             bar.set('inlineStyle', 'left: ' + left + 'px; top: ' + top + 'px; width: ' + width + 'px; height: ' + height + 'px;');
1467         });
1468     },
1469     _updateCurrentItemIndicators: function ()
1470     {
1471         if (!this._currentItemLine)
1472             return;
1473
1474         var item = this._currentTimeSeriesData[this._currentItemIndex];
1475         if (!item) {
1476             this._currentItemLine.attr("x1", -1000).attr("x2", -1000);
1477             this._currentItemCircle.attr("cx", -1000);
1478             return;
1479         }
1480
1481         var x = this._x(item.time);
1482         var y = this._y(item.value);
1483
1484         this._currentItemLine
1485             .attr("x1", x)
1486             .attr("x2", x);
1487
1488         this._currentItemCircle
1489             .attr("cx", x)
1490             .attr("cy", y);
1491     },
1492     _setCurrentSelection: function (newSelection)
1493     {
1494         if (this._brushExtent === newSelection)
1495             return;
1496
1497         var points = null;
1498         if (newSelection) {
1499             points = this._currentTimeSeriesData
1500                 .filter(function (point) { return point.time >= newSelection[0] && point.time <= newSelection[1]; });
1501             if (!points.length)
1502                 points = null;
1503         }
1504
1505         this._brushExtent = newSelection;
1506         this._setCurrentItem(undefined);
1507         this._updateSelectionToolbar();
1508
1509         if (!App.domainsAreEqual(this.get('selection'), newSelection))
1510             this.set('selection', newSelection);
1511         this.set('selectedPoints', points);
1512     },
1513     _updateSelectionToolbar: function ()
1514     {
1515         if (!this.get('interactive'))
1516             return;
1517
1518         var selection = this._currentSelection();
1519         var selectionToolbar = $(this.get('element')).children('.selection-toolbar');
1520         if (selection) {
1521             var left = this._x(selection[0]);
1522             var right = this._x(selection[1]);
1523             selectionToolbar
1524                 .css({left: this._margin.left + right, top: this._margin.top + this._contentHeight})
1525                 .show();
1526         } else
1527             selectionToolbar.hide();
1528     },
1529     actions: {
1530         zoom: function ()
1531         {
1532             this.sendAction('zoom', this._currentSelection());
1533             this.set('selection', null);
1534         },
1535         openRange: function (range)
1536         {
1537             this.sendAction('openRange', range);
1538         },
1539     },
1540 });
1541
1542
1543
1544 App.CommitsViewerComponent = Ember.Component.extend({
1545     repository: null,
1546     revisionInfo: null,
1547     commits: null,
1548     commitsChanged: function ()
1549     {
1550         var revisionInfo = this.get('revisionInfo');
1551
1552         var to = revisionInfo.get('currentRevision');
1553         var from = revisionInfo.get('previousRevision');
1554         var repository = this.get('repository');
1555         if (!from || !repository || !repository.get('hasReportedCommits'))
1556             return;
1557
1558         var self = this;
1559         CommitLogs.fetchForTimeRange(repository.get('id'), from, to).then(function (commits) {
1560             if (self.isDestroyed)
1561                 return;
1562             self.set('commits', commits.map(function (commit) {
1563                 return Ember.Object.create({
1564                     repository: repository,
1565                     revision: commit.revision,
1566                     url: repository.urlForRevision(commit.revision),
1567                     author: commit.authorName || commit.authorEmail,
1568                     message: commit.message ? commit.message.substr(0, 75) : null,
1569                 });
1570             }));
1571         }, function () {
1572             if (!self.isDestroyed)
1573                 self.set('commits', []);
1574         })
1575     }.observes('repository').observes('revisionInfo').on('init'),
1576 });
1577
1578
1579 App.AnalysisRoute = Ember.Route.extend({
1580     model: function () {
1581         return this.store.findAll('analysisTask').then(function (tasks) {
1582             return Ember.Object.create({'tasks': tasks});
1583         });
1584     },
1585 });
1586
1587 App.AnalysisTaskRoute = Ember.Route.extend({
1588     model: function (param)
1589     {
1590         return this.store.find('analysisTask', param.taskId);
1591     },
1592 });
1593
1594 App.AnalysisTaskController = Ember.Controller.extend({
1595     label: Ember.computed.alias('model.name'),
1596     platform: Ember.computed.alias('model.platform'),
1597     metric: Ember.computed.alias('model.metric'),
1598     testSets: [],
1599     roots: [],
1600     bugTrackers: [],
1601     _taskUpdated: function ()
1602     {
1603         var model = this.get('model');
1604         if (!model)
1605             return;
1606
1607         var platformId = model.get('platform').get('id');
1608         var metricId = model.get('metric').get('id');
1609         App.Manifest.fetch(this.store).then(this._fetchedManifest.bind(this));
1610         App.Manifest.fetchRunsWithPlatformAndMetric(this.store, platformId, metricId).then(this._fetchedRuns.bind(this));
1611     }.observes('model').on('init'),
1612     _fetchedManifest: function ()
1613     {
1614         var trackerIdToBugNumber = {};
1615         this.get('model').get('bugs').forEach(function (bug) {
1616             trackerIdToBugNumber[bug.get('bugTracker').get('id')] = bug.get('number');
1617         });
1618
1619         this.set('bugTrackers', App.Manifest.get('bugTrackers').map(function (bugTracker) {
1620             var bugNumber = trackerIdToBugNumber[bugTracker.get('id')];
1621             return Ember.ObjectProxy.create({
1622                 content: bugTracker,
1623                 bugNumber: bugNumber,
1624                 editedBugNumber: bugNumber,
1625             });
1626         }));
1627     },
1628     _fetchedRuns: function (data)
1629     {
1630         var runs = data.runs;
1631
1632         var currentTimeSeries = runs.current.timeSeriesByCommitTime();
1633         if (!currentTimeSeries)
1634             return; // FIXME: Report an error.
1635
1636         var start = currentTimeSeries.findPointByMeasurementId(this.get('model').get('startRun'));
1637         var end = currentTimeSeries.findPointByMeasurementId(this.get('model').get('endRun'));
1638         if (!start || !end)
1639             return; // FIXME: Report an error.
1640
1641         var markedPoints = {};
1642         markedPoints[start.measurement.id()] = true;
1643         markedPoints[end.measurement.id()] = true;
1644
1645         var formatedPoints = currentTimeSeries.seriesBetweenPoints(start, end).map(function (point, index) {
1646             return {
1647                 id: point.measurement.id(),
1648                 measurement: point.measurement,
1649                 label: 'Point ' + (index + 1),
1650                 value: point.value + (runs.unit ? ' ' + runs.unit : ''),
1651             };
1652         });
1653
1654         var margin = (end.time - start.time) * 0.1;
1655         this.set('chartData', runs);
1656         this.set('chartDomain', [start.time - margin, +end.time + margin]);
1657         this.set('markedPoints', markedPoints);
1658         this.set('analysisPoints', formatedPoints);
1659     },
1660     testSets: function ()
1661     {
1662         var analysisPoints = this.get('analysisPoints');
1663         if (!analysisPoints)
1664             return;
1665         var pointOptions = [{value: ' ', label: 'None'}]
1666             .concat(analysisPoints.map(function (point) { return {value: point.id, label: point.label}; }));
1667         return [
1668             Ember.Object.create({name: "A", options: pointOptions, selection: pointOptions[1]}),
1669             Ember.Object.create({name: "B", options: pointOptions, selection: pointOptions[pointOptions.length - 1]}),
1670         ];
1671     }.property('analysisPoints'),
1672     _rootChangedForTestSet: function ()
1673     {
1674         var sets = this.get('testSets');
1675         var roots = this.get('roots');
1676         if (!sets || !roots)
1677             return;
1678
1679         sets.forEach(function (testSet, setIndex) {
1680             var currentSelection = testSet.get('selection');
1681             if (currentSelection == testSet.get('previousSelection'))
1682                 return;
1683             testSet.set('previousSelection', currentSelection);
1684             var pointIndex = testSet.get('options').indexOf(currentSelection);
1685
1686             roots.forEach(function (root) {
1687                 var set = root.sets[setIndex];
1688                 set.set('selection', set.revisions[pointIndex]);
1689             });
1690         });
1691
1692     }.observes('testSets.@each.selection'),
1693     roots: function ()
1694     {
1695         var analysisPoints = this.get('analysisPoints');
1696         if (!analysisPoints)
1697             return [];
1698         var repositoryToRevisions = {};
1699         analysisPoints.forEach(function (point, pointIndex) {
1700             var revisions = point.measurement.formattedRevisions();
1701             for (var repositoryName in revisions) {
1702                 if (!repositoryToRevisions[repositoryName])
1703                     repositoryToRevisions[repositoryName] = new Array(analysisPoints.length);
1704                 var revision = revisions[repositoryName];
1705                 repositoryToRevisions[repositoryName][pointIndex] = {
1706                     label: point.label + ': ' + revision.label,
1707                     value: revision.currentRevision,
1708                 };
1709             }
1710         });
1711
1712         var roots = [];
1713         for (var repositoryName in repositoryToRevisions) {
1714             var revisions = [{value: ' ', label: 'None'}].concat(repositoryToRevisions[repositoryName]);
1715             roots.push(Ember.Object.create({
1716                 name: repositoryName,
1717                 sets: [
1718                     Ember.Object.create({name: 'A[' + repositoryName + ']',
1719                         revisions: revisions,
1720                         selection: revisions[1]}),
1721                     Ember.Object.create({name: 'B[' + repositoryName + ']',
1722                         revisions: revisions,
1723                         selection: revisions[revisions.length - 1]}),
1724                 ],
1725             }));
1726         }
1727         return roots;
1728     }.property('analysisPoints'),
1729     actions: {
1730         associateBug: function (bugTracker, bugNumber)
1731         {
1732             var model = this.get('model');
1733             this.store.createRecord('bug',
1734                 {task: this.get('model'), bugTracker: bugTracker.get('content'), number: bugNumber}).save().then(function () {
1735                     // FIXME: Should we notify the user?
1736                 }, function (error) {
1737                     alert('Failed to associate the bug: ' + error);
1738                 });
1739         }
1740     },
1741 });