The dashboard on new perf monitor should be configurable
[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     defaultSince: Date.now() - 7 * 24 * 3600 * 1000,
403
404     addPane: function (pane)
405     {
406         this.panes.unshiftObject(pane);
407     },
408
409     removePane: function (pane)
410     {
411         this.panes.removeObject(pane);
412     },
413
414     refreshPanes: function()
415     {
416         var paneList = this.get('paneList');
417         if (paneList === this._currentEncodedPaneList)
418             return;
419
420         var panes = this._parsePaneList(paneList || '[]');
421         if (!panes) {
422             console.log('Failed to parse', jsonPaneList, exception);
423             return;
424         }
425         this.set('panes', panes);
426         this._currentEncodedPaneList = paneList;
427     }.observes('paneList').on('init'),
428
429     refreshZoom: function()
430     {
431         var zoom = this.get('zoom');
432         if (!zoom) {
433             this.set('sharedZoom', null);
434             return;
435         }
436
437         zoom = zoom.split('-');
438         var selection = new Array(2);
439         try {
440             selection[0] = new Date(parseFloat(zoom[0]));
441             selection[1] = new Date(parseFloat(zoom[1]));
442         } catch (error) {
443             console.log('Failed to parse the zoom', zoom);
444         }
445         this.set('sharedZoom', selection);
446
447         var startTime = this.get('startTime');
448         if (startTime && startTime > selection[0])
449             this.set('startTime', selection[0]);
450
451     }.observes('zoom').on('init'),
452
453     updateSharedDomain: function ()
454     {
455         var panes = this.get('panes');
456         if (!panes.length)
457             return;
458
459         var union = [undefined, undefined];
460         for (var i = 0; i < panes.length; i++) {
461             var domain = panes[i].intrinsicDomain;
462             if (!domain)
463                 continue;
464             if (!union[0] || domain[0] < union[0])
465                 union[0] = domain[0];
466             if (!union[1] || domain[1] > union[1])
467                 union[1] = domain[1];
468         }
469         if (union[0] === undefined)
470             return;
471
472         var startTime = this.get('startTime');
473         var zoom = this.get('sharedZoom');
474         if (startTime)
475             union[0] = zoom ? Math.min(zoom[0], startTime) : startTime;
476
477         this.set('sharedDomain', union);
478     }.observes('panes.@each'),
479
480     _startTimeChanged: function () {
481         this.updateSharedDomain();
482         this._scheduleQueryStringUpdate();
483     }.observes('startTime'),
484
485     _sinceChanged: function () {
486         var since = parseInt(this.get('since'));
487         if (isNaN(since))
488             since = this.defaultSince;
489         this.set('startTime', new Date(since));
490     }.observes('since').on('init'),
491
492     _parsePaneList: function (encodedPaneList)
493     {
494         var parsedPaneList = App.decodePrettifiedJSON(encodedPaneList);
495         if (!parsedPaneList)
496             return null;
497
498         // Don't re-create all panes.
499         var self = this;
500         return parsedPaneList.map(function (paneInfo) {
501             var timeRange = null;
502             if (paneInfo[3] && paneInfo[3] instanceof Array) {
503                 var timeRange = paneInfo[3];
504                 try {
505                     timeRange = [new Date(timeRange[0]), new Date(timeRange[1])];
506                 } catch (error) {
507                     console.log("Failed to parse the time range:", timeRange, error);
508                 }
509             }
510             return App.Pane.create({
511                 store: self.store,
512                 info: paneInfo,
513                 platformId: paneInfo[0],
514                 metricId: paneInfo[1],
515                 selectedItem: paneInfo[2],
516                 timeRange: timeRange,
517                 timeRangeIsLocked: !!paneInfo[4],
518             });
519         });
520     },
521
522     _serializePaneList: function (panes)
523     {
524         if (!panes.length)
525             return undefined;
526         return App.encodePrettifiedJSON(panes.map(function (pane) {
527             return [
528                 pane.get('platformId'),
529                 pane.get('metricId'),
530                 pane.get('selectedItem'),
531                 pane.get('timeRange') ? pane.get('timeRange').map(function (date) { return date.getTime() }) : null,
532                 !!pane.get('timeRangeIsLocked'),
533             ];
534         }));
535     },
536
537     _scheduleQueryStringUpdate: function ()
538     {
539         Ember.run.debounce(this, '_updateQueryString', 500);
540     }.observes('sharedZoom')
541         .observes('panes.@each.platform', 'panes.@each.metric', 'panes.@each.selectedItem',
542         'panes.@each.timeRange', 'panes.@each.timeRangeIsLocked'),
543
544     _updateQueryString: function ()
545     {
546         this._currentEncodedPaneList = this._serializePaneList(this.get('panes'));
547         this.set('paneList', this._currentEncodedPaneList);
548
549         var zoom = undefined;
550         var selection = this.get('sharedZoom');
551         if (selection)
552             zoom = (selection[0] - 0) + '-' + (selection[1] - 0);
553         this.set('zoom', zoom);
554
555         if (this.get('startTime') - this.defaultSince)
556             this.set('since', this.get('startTime') - 0);
557     },
558
559     actions: {
560         addPaneByMetricAndPlatform: function (param)
561         {
562             this.addPane(App.Pane.create({
563                 store: this.store,
564                 platformId: param.platform.get('id'),
565                 metricId: param.metric.get('id'),
566                 showingDetails: false
567             }));
568         },
569     },
570
571     init: function ()
572     {
573         this._super();
574         var self = this;
575         App.buildPopup(this.store, 'addPaneByMetricAndPlatform').then(function (platforms) {
576             self.set('platforms', platforms);
577         });
578     },
579 });
580
581 App.buildPopup = function(store, action, position)
582 {
583     return App.Manifest.fetch(store).then(function () {
584         return App.Manifest.get('platforms').map(function (platform) {
585             return App.PlatformProxyForPopup.create({content: platform,
586                 action: action, position: position});
587         });
588     });
589 }
590
591 App.PlatformProxyForPopup = Ember.ObjectProxy.extend({
592     children: function ()
593     {
594         var platform = this.content;
595         var containsTest = this.content.containsTest.bind(this.content);
596         var action = this.get('action');
597         var position = this.get('position');
598         return App.Manifest.get('topLevelTests')
599             .filter(containsTest)
600             .map(function (test) {
601                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
602             });
603     }.property('App.Manifest.topLevelTests'),
604 });
605
606 App.TestProxyForPopup = Ember.ObjectProxy.extend({
607     platform: null,
608     children: function ()
609     {
610         var platform = this.get('platform');
611         var action = this.get('action');
612         var position = this.get('position');
613
614         var childTests = this.get('childTests')
615             .filter(function (test) { return platform.containsTest(test); })
616             .map(function (test) {
617                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
618             });
619
620         var metrics = this.get('metrics')
621             .filter(function (metric) { return platform.containsMetric(metric); })
622             .map(function (metric) {
623                 var aggregator = metric.get('aggregator');
624                 return {
625                     actionName: action,
626                     actionArgument: {platform: platform, metric: metric, position:position},
627                     label: metric.get('label')
628                 };
629             });
630
631         if (childTests.length && metrics.length)
632             metrics.push({isSeparator: true});
633
634         return metrics.concat(childTests);
635     }.property('childTests', 'metrics'),
636 });
637
638 App.PaneController = Ember.ObjectController.extend({
639     needs: ['charts'],
640     sharedTime: Ember.computed.alias('parentController.sharedTime'),
641     sharedSelection: Ember.computed.alias('parentController.sharedSelection'),
642     selection: null,
643     actions: {
644         toggleDetails: function()
645         {
646             this.toggleProperty('showingDetails');
647         },
648         close: function ()
649         {
650             this.parentController.removePane(this.get('model'));
651         },
652         toggleBugsPane: function ()
653         {
654             if (this.toggleProperty('showingAnalysisPane'))
655                 this.set('showingSearchPane', false);
656         },
657         createAnalysisTask: function ()
658         {
659             var name = this.get('newAnalysisTaskName');
660             var points = this._selectedPoints;
661             Ember.assert('The analysis name should not be empty', name);
662             Ember.assert('There should be at least two points in the range', points && points.length >= 2);
663
664             var newWindow = window.open();
665             var self = this;
666             App.AnalysisTask.create(name, points[0].measurement, points[points.length - 1].measurement).then(function (data) {
667                 // FIXME: Update the UI to show the new analysis task.
668                 var url = App.Router.router.generate('analysisTask', data['taskId']);
669                 newWindow.location.href = '#' + url;
670                 self.get('model').fetchAnalyticRanges();
671             }, function (error) {
672                 newWindow.close();
673                 if (error === 'DuplicateAnalysisTask') {
674                     // FIXME: Duplicate this error more gracefully.
675                 }
676                 alert(error);
677             });
678         },
679         toggleSearchPane: function ()
680         {
681             if (!App.Manifest.repositoriesWithReportedCommits)
682                 return;
683             var model = this.get('model');
684             if (!model.get('commitSearchRepository'))
685                 model.set('commitSearchRepository', App.Manifest.repositoriesWithReportedCommits[0]);
686             if (this.toggleProperty('showingSearchPane'))
687                 this.set('showingAnalysisPane', false);
688         },
689         searchCommit: function () {
690             var model = this.get('model');
691             model.searchCommit(model.get('commitSearchRepository'), model.get('commitSearchKeyword'));                
692         },
693         zoomed: function (selection)
694         {
695             this.set('mainPlotDomain', selection ? selection : this.get('overviewDomain'));
696             Ember.run.debounce(this, 'propagateZoom', 100);
697         },
698         overviewDomainChanged: function (domain, intrinsicDomain)
699         {
700             this.set('overviewDomain', domain);
701             this.set('intrinsicDomain', intrinsicDomain);
702             this.get('parentController').updateSharedDomain();
703         },
704         rangeChanged: function (extent, points)
705         {
706             if (!points) {
707                 this._hasRange = false;
708                 this.set('details', null);
709                 this.set('timeRange', null);
710                 return;
711             }
712             this._hasRange = true;
713             this._showDetails(points);
714             this.set('timeRange', extent);
715         },
716     },
717     _detailsChanged: function ()
718     {
719         this.set('showingAnalysisPane', false);
720     }.observes('details'),
721     _overviewSelectionChanged: function ()
722     {
723         var overviewSelection = this.get('overviewSelection');
724         this.set('mainPlotDomain', overviewSelection);
725         Ember.run.debounce(this, 'propagateZoom', 100);
726     }.observes('overviewSelection'),
727     _sharedDomainChanged: function ()
728     {
729         var newDomain = this.get('parentController').get('sharedDomain');
730         if (newDomain == this.get('overviewDomain'))
731             return;
732         this.set('overviewDomain', newDomain);
733         if (!this.get('overviewSelection'))
734             this.set('mainPlotDomain', newDomain);
735     }.observes('parentController.sharedDomain').on('init'),
736     propagateZoom: function ()
737     {
738         this.get('parentController').set('sharedZoom', this.get('mainPlotDomain'));
739     },
740     _sharedZoomChanged: function ()
741     {
742         var newSelection = this.get('parentController').get('sharedZoom');
743         if (newSelection == this.get('mainPlotDomain'))
744             return;
745         this.set('overviewSelection', newSelection);
746         this.set('mainPlotDomain', newSelection);
747     }.observes('parentController.sharedZoom').on('init'),
748     _currentItemChanged: function ()
749     {
750         if (this._hasRange)
751             return;
752         var point = this.get('currentItem');
753         if (!point || !point.measurement)
754             this.set('details', null);
755         else {
756             var previousPoint = point.series.previousPoint(point);
757             this._showDetails(previousPoint ? [previousPoint, point] : [point]);
758         }
759     }.observes('currentItem'),
760     _showDetails: function (points)
761     {
762         var isShowingEndPoint = !this._hasRange;
763         var currentMeasurement = points[points.length - 1].measurement;
764         var oldMeasurement = points[0].measurement;
765         var formattedRevisions = currentMeasurement.formattedRevisions(oldMeasurement);
766         var revisions = App.Manifest.get('repositories')
767             .filter(function (repository) { return formattedRevisions[repository.get('id')]; })
768             .map(function (repository) {
769             var repositoryName = repository.get('id');
770             var revision = Ember.Object.create(formattedRevisions[repositoryName]);
771             revision['url'] = revision.previousRevision
772                 ? repository.urlForRevisionRange(revision.previousRevision, revision.currentRevision)
773                 : repository.urlForRevision(revision.currentRevision);
774             revision['name'] = repositoryName;
775             revision['repository'] = repository;
776             return revision; 
777         });
778
779         var buildNumber = null;
780         var buildURL = null;
781         if (isShowingEndPoint) {
782             buildNumber = currentMeasurement.buildNumber();
783             var builder = App.Manifest.builder(currentMeasurement.builderId());
784             if (builder)
785                 buildURL = builder.urlFromBuildNumber(buildNumber);
786         }
787
788         this._selectedPoints = points;
789         this.set('details', Ember.Object.create({
790             currentValue: currentMeasurement.mean().toFixed(2),
791             oldValue: oldMeasurement && !isShowingEndPoint ? oldMeasurement.mean().toFixed(2) : null,
792             buildNumber: buildNumber,
793             buildURL: buildURL,
794             buildTime: currentMeasurement.formattedBuildTime(),
795             revisions: revisions,
796         }));
797         this._updateCanAnalyze();
798     },
799     _updateCanAnalyze: function ()
800     {
801         var points = this._selectedPoints;
802         this.set('cannotAnalyze', !this.get('newAnalysisTaskName') || !this._hasRange || !points || points.length < 2);
803     }.observes('newAnalysisTaskName'),
804 });
805
806 App.InteractiveChartComponent = Ember.Component.extend({
807     chartData: null,
808     showXAxis: true,
809     showYAxis: true,
810     interactive: false,
811     enableSelection: true,
812     classNames: ['chart'],
813     init: function ()
814     {
815         this._super();
816         this._needsConstruction = true;
817         this._eventHandlers = [];
818         $(window).resize(this._updateDimensionsIfNeeded.bind(this));
819     },
820     chartDataDidChange: function ()
821     {
822         var chartData = this.get('chartData');
823         if (!chartData)
824             return;
825         this._needsConstruction = true;
826         this._constructGraphIfPossible(chartData);
827     }.observes('chartData').on('init'),
828     didInsertElement: function ()
829     {
830         var chartData = this.get('chartData');
831         if (chartData)
832             this._constructGraphIfPossible(chartData);
833     },
834     willClearRender: function ()
835     {
836         this._eventHandlers.forEach(function (item) {
837             $(item[0]).off(item[1], item[2]);
838         })
839     },
840     _attachEventListener: function(target, eventName, listener)
841     {
842         this._eventHandlers.push([target, eventName, listener]);
843         $(target).on(eventName, listener);
844     },
845     _constructGraphIfPossible: function (chartData)
846     {
847         if (!this._needsConstruction || !this.get('element'))
848             return;
849
850         var element = this.get('element');
851
852         this._x = d3.time.scale();
853         this._y = d3.scale.linear();
854
855         // FIXME: Tear down the old SVG element.
856         this._svgElement = d3.select(element).append("svg")
857                 .attr("width", "100%")
858                 .attr("height", "100%");
859
860         var svg = this._svg = this._svgElement.append("g");
861
862         var clipId = element.id + "-clip";
863         this._clipPath = svg.append("defs").append("clipPath")
864             .attr("id", clipId)
865             .append("rect");
866
867         if (this.get('showXAxis')) {
868             this._xAxis = d3.svg.axis().scale(this._x).orient("bottom").ticks(6);
869             this._xAxisLabels = svg.append("g")
870                 .attr("class", "x axis");
871         }
872
873         if (this.get('showYAxis')) {
874             this._yAxis = d3.svg.axis().scale(this._y).orient("left").ticks(6).tickFormat(d3.format("s"));
875             this._yAxisLabels = svg.append("g")
876                 .attr("class", "y axis");
877         }
878
879         this._clippedContainer = svg.append("g")
880             .attr("clip-path", "url(#" + clipId + ")");
881
882         var xScale = this._x;
883         var yScale = this._y;
884         this._timeLine = d3.svg.line()
885             .x(function(point) { return xScale(point.time); })
886             .y(function(point) { return yScale(point.value); });
887
888         this._confidenceArea = d3.svg.area()
889 //            .interpolate("cardinal")
890             .x(function(point) { return xScale(point.time); })
891             .y0(function(point) { return point.interval ? yScale(point.interval[0]) : null; })
892             .y1(function(point) { return point.interval ? yScale(point.interval[1]) : null; });
893
894         if (this._paths)
895             this._paths.forEach(function (path) { path.remove(); });
896         this._paths = [];
897         if (this._areas)
898             this._areas.forEach(function (area) { area.remove(); });
899         this._areas = [];
900         if (this._dots)
901             this._dots.forEach(function (dot) { dots.remove(); });
902         this._dots = [];
903         if (this._highlights)
904             this._highlights.forEach(function (highlight) { highlight.remove(); });
905         this._highlights = [];
906
907         this._currentTimeSeries = chartData.current.timeSeriesByCommitTime();
908         this._currentTimeSeriesData = this._currentTimeSeries.series();
909         this._baselineTimeSeries = chartData.baseline ? chartData.baseline.timeSeriesByCommitTime() : null;
910         this._targetTimeSeries = chartData.target ? chartData.target.timeSeriesByCommitTime() : null;
911
912         this._yAxisUnit = chartData.unit;
913
914         var minMax = this._minMaxForAllTimeSeries();
915         var smallEnoughValue = minMax[0] - (minMax[1] - minMax[0]) * 10;
916         var largeEnoughValue = minMax[1] + (minMax[1] - minMax[0]) * 10;
917
918         // FIXME: Flip the sides based on smallerIsBetter-ness.
919         if (this._baselineTimeSeries) {
920             var data = this._baselineTimeSeries.series();
921             this._areas.push(this._clippedContainer
922                 .append("path")
923                 .datum(data.map(function (point) { return {time: point.time, value: point.value, interval: point.interval ? point.interval : [point.value, largeEnoughValue]}; }))
924                 .attr("class", "area baseline"));
925         }
926         if (this._targetTimeSeries) {
927             var data = this._targetTimeSeries.series();
928             this._areas.push(this._clippedContainer
929                 .append("path")
930                 .datum(data.map(function (point) { return {time: point.time, value: point.value, interval: point.interval ? point.interval : [smallEnoughValue, point.value]}; }))
931                 .attr("class", "area target"));
932         }
933
934         this._areas.push(this._clippedContainer
935             .append("path")
936             .datum(this._currentTimeSeriesData)
937             .attr("class", "area"));
938
939         this._paths.push(this._clippedContainer
940             .append("path")
941             .datum(this._currentTimeSeriesData)
942             .attr("class", "commit-time-line"));
943
944         this._dots.push(this._clippedContainer
945             .selectAll(".dot")
946                 .data(this._currentTimeSeriesData)
947             .enter().append("circle")
948                 .attr("class", "dot")
949                 .attr("r", this.get('chartPointRadius') || 1));
950
951         if (this.get('interactive')) {
952             this._attachEventListener(element, "mousemove", this._mouseMoved.bind(this));
953             this._attachEventListener(element, "mouseleave", this._mouseLeft.bind(this));
954             this._attachEventListener(element, "mousedown", this._mouseDown.bind(this));
955             this._attachEventListener($(element).parents("[tabindex]"), "keydown", this._keyPressed.bind(this));
956
957             this._currentItemLine = this._clippedContainer
958                 .append("line")
959                 .attr("class", "current-item");
960
961             this._currentItemCircle = this._clippedContainer
962                 .append("circle")
963                 .attr("class", "dot current-item")
964                 .attr("r", 3);
965         }
966
967         this._brush = null;
968         if (this.get('enableSelection')) {
969             this._brush = d3.svg.brush()
970                 .x(this._x)
971                 .on("brush", this._brushChanged.bind(this));
972
973             this._brushRect = this._clippedContainer
974                 .append("g")
975                 .attr("class", "x brush");
976         }
977
978         this._updateDomain();
979         this._updateDimensionsIfNeeded();
980
981         // Work around the fact the brush isn't set if we updated it synchronously here.
982         setTimeout(this._selectionChanged.bind(this), 0);
983
984         setTimeout(this._selectedItemChanged.bind(this), 0);
985
986         this._needsConstruction = false;
987
988         this._rangesChanged();
989     },
990     _updateDomain: function ()
991     {
992         var xDomain = this.get('domain');
993         var intrinsicXDomain = this._computeXAxisDomain(this._currentTimeSeriesData);
994         if (!xDomain)
995             xDomain = intrinsicXDomain;
996         var currentDomain = this._x.domain();
997         if (currentDomain && this._xDomainsAreSame(currentDomain, xDomain))
998             return currentDomain;
999
1000         var yDomain = this._computeYAxisDomain(xDomain[0], xDomain[1]);
1001         this._x.domain(xDomain);
1002         this._y.domain(yDomain);
1003         this.sendAction('domainChanged', xDomain, intrinsicXDomain);
1004         return xDomain;
1005     },
1006     _updateDimensionsIfNeeded: function (newSelection)
1007     {
1008         var element = $(this.get('element'));
1009
1010         var newTotalWidth = element.width();
1011         var newTotalHeight = element.height();
1012         if (this._totalWidth == newTotalWidth && this._totalHeight == newTotalHeight)
1013             return;
1014
1015         this._totalWidth = newTotalWidth;
1016         this._totalHeight = newTotalHeight;
1017
1018         if (!this._rem)
1019             this._rem = parseFloat(getComputedStyle(document.documentElement).fontSize);
1020         var rem = this._rem;
1021
1022         var padding = 0.5 * rem;
1023         var margin = {top: padding, right: padding, bottom: padding, left: padding};
1024         if (this._xAxis)
1025             margin.bottom += rem;
1026         if (this._yAxis)
1027             margin.left += 3 * rem;
1028
1029         this._margin = margin;
1030         this._contentWidth = this._totalWidth - margin.left - margin.right;
1031         this._contentHeight = this._totalHeight - margin.top - margin.bottom;
1032
1033         this._svg.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
1034
1035         this._clipPath
1036             .attr("width", this._contentWidth)
1037             .attr("height", this._contentHeight);
1038
1039         this._x.range([0, this._contentWidth]);
1040         this._y.range([this._contentHeight, 0]);
1041
1042         if (this._xAxis) {
1043             this._xAxis.tickSize(-this._contentHeight);
1044             this._xAxisLabels.attr("transform", "translate(0," + this._contentHeight + ")");
1045         }
1046
1047         if (this._yAxis)
1048             this._yAxis.tickSize(-this._contentWidth);
1049
1050         if (this._currentItemLine) {
1051             this._currentItemLine
1052                 .attr("y1", 0)
1053                 .attr("y2", margin.top + this._contentHeight);
1054         }
1055
1056         this._relayoutDataAndAxes(this._currentSelection());
1057     },
1058     _updateBrush: function ()
1059     {
1060         this._brushRect
1061             .call(this._brush)
1062         .selectAll("rect")
1063             .attr("y", 1)
1064             .attr("height", this._contentHeight - 2);
1065         this._updateSelectionToolbar();
1066     },
1067     _relayoutDataAndAxes: function (selection)
1068     {
1069         var timeline = this._timeLine;
1070         this._paths.forEach(function (path) { path.attr("d", timeline); });
1071
1072         var confidenceArea = this._confidenceArea;
1073         this._areas.forEach(function (path) { path.attr("d", confidenceArea); });
1074
1075         var xScale = this._x;
1076         var yScale = this._y;
1077         this._dots.forEach(function (dot) {
1078             dot
1079                 .attr("cx", function(measurement) { return xScale(measurement.time); })
1080                 .attr("cy", function(measurement) { return yScale(measurement.value); });
1081         });
1082         this._updateMarkedDots();
1083         this._updateHighlightPositions();
1084         this._updateRangeBarRects();
1085
1086         if (this._brush) {
1087             if (selection)
1088                 this._brush.extent(selection);
1089             else
1090                 this._brush.clear();
1091             this._updateBrush();
1092         }
1093
1094         this._updateCurrentItemIndicators();
1095
1096         if (this._xAxis)
1097             this._xAxisLabels.call(this._xAxis);
1098         if (!this._yAxis)
1099             return;
1100
1101         this._yAxisLabels.call(this._yAxis);
1102         if (this._yAxisUnitContainer)
1103             this._yAxisUnitContainer.remove();
1104         this._yAxisUnitContainer = this._yAxisLabels.append("text")
1105             .attr("x", 0.5 * this._rem)
1106             .attr("y", 0.2 * this._rem)
1107             .attr("dy", 0.8 * this._rem)
1108             .style("text-anchor", "start")
1109             .style("z-index", "100")
1110             .text(this._yAxisUnit);
1111     },
1112     _updateMarkedDots: function () {
1113         var markedPoints = this.get('markedPoints') || {};
1114         var defaultDotRadius = this.get('chartPointRadius') || 1;
1115         this._dots.forEach(function (dot) {
1116             dot.classed('marked', function (point) { return markedPoints[point.measurement.id()]; });
1117             dot.attr('r', function (point) {
1118                 return markedPoints[point.measurement.id()] ? defaultDotRadius * 1.5 : defaultDotRadius; });
1119         });
1120     }.observes('markedPoints'),
1121     _updateHighlightPositions: function () {
1122         var xScale = this._x;
1123         var yScale = this._y;
1124         var y2 = this._margin.top + this._contentHeight;
1125         this._highlights.forEach(function (highlight) {
1126             highlight
1127                 .attr("y1", 0)
1128                 .attr("y2", y2)
1129                 .attr("y", function(measurement) { return yScale(measurement.value); })
1130                 .attr("x1", function(measurement) { return xScale(measurement.time); })
1131                 .attr("x2", function(measurement) { return xScale(measurement.time); });
1132         });
1133     },
1134     _computeXAxisDomain: function (timeSeries)
1135     {
1136         var extent = d3.extent(timeSeries, function(point) { return point.time; });
1137         var margin = 3600 * 1000; // Use x.inverse to compute the right amount from a margin.
1138         return [+extent[0] - margin, +extent[1] + margin];
1139     },
1140     _computeYAxisDomain: function (startTime, endTime)
1141     {
1142         var range = this._minMaxForAllTimeSeries(startTime, endTime);
1143         var min = range[0];
1144         var max = range[1];
1145         if (max < min)
1146             min = max = 0;
1147         var diff = max - min;
1148         var margin = diff * 0.05;
1149
1150         yExtent = [min - margin, max + margin];
1151 //        if (yMin !== undefined)
1152 //            yExtent[0] = parseInt(yMin);
1153         return yExtent;
1154     },
1155     _minMaxForAllTimeSeries: function (startTime, endTime)
1156     {
1157         var currentRange = this._currentTimeSeries.minMaxForTimeRange(startTime, endTime);
1158         var baselineRange = this._baselineTimeSeries ? this._baselineTimeSeries.minMaxForTimeRange(startTime, endTime) : [Number.MAX_VALUE, Number.MIN_VALUE];
1159         var targetRange = this._targetTimeSeries ? this._targetTimeSeries.minMaxForTimeRange(startTime, endTime) : [Number.MAX_VALUE, Number.MIN_VALUE];
1160         return [
1161             Math.min(currentRange[0], baselineRange[0], targetRange[0]),
1162             Math.max(currentRange[1], baselineRange[1], targetRange[1]),
1163         ];
1164     },
1165     _currentSelection: function ()
1166     {
1167         return this._brush && !this._brush.empty() ? this._brush.extent() : null;
1168     },
1169     _domainChanged: function ()
1170     {
1171         var selection = this._currentSelection() || this.get('sharedSelection');
1172         var newXDomain = this._updateDomain();
1173
1174         if (selection && newXDomain && selection[0] <= newXDomain[0] && newXDomain[1] <= selection[1])
1175             selection = null; // Otherwise the user has no way of clearing the selection.
1176
1177         this._relayoutDataAndAxes(selection);
1178     }.observes('domain'),
1179     _selectionChanged: function ()
1180     {
1181         this._updateSelection(this.get('selection'));
1182     }.observes('selection'),
1183     _sharedSelectionChanged: function ()
1184     {
1185         if (this.get('selectionIsLocked'))
1186             return;
1187         this._updateSelection(this.get('sharedSelection'));
1188     }.observes('sharedSelection'),
1189     _updateSelection: function (newSelection)
1190     {
1191         if (!this._brush)
1192             return;
1193
1194         var currentSelection = this._currentSelection();
1195         if (newSelection && currentSelection && this._xDomainsAreSame(newSelection, currentSelection))
1196             return;
1197
1198         var domain = this._x.domain();
1199         if (!newSelection || this._xDomainsAreSame(domain, newSelection))
1200             this._brush.clear();
1201         else
1202             this._brush.extent(newSelection);
1203         this._updateBrush();
1204
1205         this._setCurrentSelection(newSelection);
1206     },
1207     _xDomainsAreSame: function (domain1, domain2)
1208     {
1209         return !(domain1[0] - domain2[0]) && !(domain1[1] - domain2[1]);
1210     },
1211     _brushChanged: function ()
1212     {
1213         if (this._brush.empty()) {
1214             if (!this._brushExtent)
1215                 return;
1216
1217             this.set('selectionIsLocked', false);
1218             this._setCurrentSelection(undefined);
1219
1220             // Avoid locking the indicator in _mouseDown when the brush was cleared in the same mousedown event.
1221             this._brushJustChanged = true;
1222             var self = this;
1223             setTimeout(function () {
1224                 self._brushJustChanged = false;
1225             }, 0);
1226
1227             return;
1228         }
1229
1230         this.set('selectionIsLocked', true);
1231         this._setCurrentSelection(this._brush.extent());
1232     },
1233     _keyPressed: function (event)
1234     {
1235         if (!this._currentItemIndex || this._currentSelection())
1236             return;
1237
1238         var newIndex;
1239         switch (event.keyCode) {
1240         case 37: // Left
1241             newIndex = this._currentItemIndex - 1;
1242             break;
1243         case 39: // Right
1244             newIndex = this._currentItemIndex + 1;
1245             break;
1246         case 38: // Up
1247         case 40: // Down
1248         default:
1249             return;
1250         }
1251
1252         // Unlike mousemove, keydown shouldn't move off the edge.
1253         if (this._currentTimeSeriesData[newIndex])
1254             this._setCurrentItem(newIndex);
1255     },
1256     _mouseMoved: function (event)
1257     {
1258         if (!this._margin || this._currentSelection() || this._currentItemLocked)
1259             return;
1260
1261         var point = this._mousePointInGraph(event);
1262
1263         this._selectClosestPointToMouseAsCurrentItem(point);
1264     },
1265     _mouseLeft: function (event)
1266     {
1267         if (!this._margin || this._currentItemLocked)
1268             return;
1269
1270         this._selectClosestPointToMouseAsCurrentItem(null);
1271     },
1272     _mouseDown: function (event)
1273     {
1274         if (!this._margin || this._currentSelection() || this._brushJustChanged)
1275             return;
1276
1277         var point = this._mousePointInGraph(event);
1278         if (!point)
1279             return;
1280
1281         if (this._currentItemLocked) {
1282             this._currentItemLocked = false;
1283             this.set('selectedItem', null);
1284             return;
1285         }
1286
1287         this._currentItemLocked = true;
1288         this._selectClosestPointToMouseAsCurrentItem(point);
1289     },
1290     _mousePointInGraph: function (event)
1291     {
1292         var offset = $(this.get('element')).offset();
1293         if (!offset || !$(event.target).closest('svg').length)
1294             return null;
1295
1296         var point = {
1297             x: event.pageX - offset.left - this._margin.left,
1298             y: event.pageY - offset.top - this._margin.top
1299         };
1300
1301         var xScale = this._x;
1302         var yScale = this._y;
1303         var xDomain = xScale.domain();
1304         var yDomain = yScale.domain();
1305         if (point.x >= xScale(xDomain[0]) && point.x <= xScale(xDomain[1])
1306             && point.y <= yScale(yDomain[0]) && point.y >= yScale(yDomain[1]))
1307             return point;
1308
1309         return null;
1310     },
1311     _selectClosestPointToMouseAsCurrentItem: function (point)
1312     {
1313         var xScale = this._x;
1314         var yScale = this._y;
1315         var distanceHeuristics = function (m) {
1316             var mX = xScale(m.time);
1317             var mY = yScale(m.value);
1318             var xDiff = mX - point.x;
1319             var yDiff = mY - point.y;
1320             return xDiff * xDiff + yDiff * yDiff / 16; // Favor horizontal affinity.
1321         };
1322         distanceHeuristics = function (m) {
1323             return Math.abs(xScale(m.time) - point.x);
1324         }
1325
1326         var newItemIndex;
1327         if (point && !this._currentSelection()) {
1328             var distances = this._currentTimeSeriesData.map(distanceHeuristics);
1329             var minDistance = Number.MAX_VALUE;
1330             for (var i = 0; i < distances.length; i++) {
1331                 if (distances[i] < minDistance) {
1332                     newItemIndex = i;
1333                     minDistance = distances[i];
1334                 }
1335             }
1336         }
1337
1338         this._setCurrentItem(newItemIndex);
1339         this._updateSelectionToolbar();
1340     },
1341     _currentTimeChanged: function ()
1342     {
1343         if (!this._margin || this._currentSelection() || this._currentItemLocked)
1344             return
1345
1346         var currentTime = this.get('currentTime');
1347         if (currentTime) {
1348             for (var i = 0; i < this._currentTimeSeriesData.length; i++) {
1349                 var point = this._currentTimeSeriesData[i];
1350                 if (point.time >= currentTime) {
1351                     this._setCurrentItem(i, /* doNotNotify */ true);
1352                     return;
1353                 }
1354             }
1355         }
1356         this._setCurrentItem(undefined, /* doNotNotify */ true);
1357     }.observes('currentTime'),
1358     _setCurrentItem: function (newItemIndex, doNotNotify)
1359     {
1360         if (newItemIndex === this._currentItemIndex) {
1361             if (this._currentItemLocked)
1362                 this.set('selectedItem', this.get('currentItem') ? this.get('currentItem').measurement.id() : null);
1363             return;
1364         }
1365
1366         var newItem = this._currentTimeSeriesData[newItemIndex];
1367         this._brushExtent = undefined;
1368         this._currentItemIndex = newItemIndex;
1369
1370         if (!newItem) {
1371             this._currentItemLocked = false;
1372             this.set('selectedItem', null);
1373         }
1374
1375         this._updateCurrentItemIndicators();
1376
1377         if (!doNotNotify)
1378             this.set('currentTime', newItem ? newItem.time : undefined);
1379
1380         this.set('currentItem', newItem);
1381         if (this._currentItemLocked)
1382             this.set('selectedItem', newItem ? newItem.measurement.id() : null);
1383     },
1384     _selectedItemChanged: function ()
1385     {
1386         if (!this._margin)
1387             return;
1388
1389         var selectedId = this.get('selectedItem');
1390         var currentItem = this.get('currentItem');
1391         if (currentItem && currentItem.measurement.id() == selectedId)
1392             return;
1393
1394         var series = this._currentTimeSeriesData;
1395         var selectedItemIndex = undefined;
1396         for (var i = 0; i < series.length; i++) {
1397             if (series[i].measurement.id() == selectedId) {
1398                 this._updateSelection(null);
1399                 this._currentItemLocked = true;
1400                 this._setCurrentItem(i);
1401                 this._updateSelectionToolbar();
1402                 return;
1403             }
1404         }
1405     }.observes('selectedItem').on('init'),
1406     _highlightedItemsChanged: function () {
1407         if (!this._margin)
1408             return;
1409
1410         var highlightedItems = this.get('highlightedItems');
1411
1412         var data = this._currentTimeSeriesData.filter(function (item) { return highlightedItems[item.measurement.id()]; });
1413
1414         if (this._highlights.length)
1415             this._highlights.forEach(function (highlight) { highlight.remove(); });
1416
1417         this._highlights.push(this._clippedContainer
1418             .selectAll(".highlight")
1419                 .data(data)
1420             .enter().append("line")
1421                 .attr("class", "highlight"));
1422
1423         this._updateHighlightPositions();
1424
1425     }.observes('highlightedItems'),
1426     _rangesChanged: function ()
1427     {
1428         if (!this._currentTimeSeries)
1429             return;
1430
1431         function midPoint(firstPoint, secondPoint) {
1432             if (firstPoint && secondPoint)
1433                 return (+firstPoint.time + +secondPoint.time) / 2;
1434             if (firstPoint)
1435                 return firstPoint.time;
1436             return secondPoint.time;
1437         }
1438         var currentTimeSeries = this._currentTimeSeries;
1439         var linkRoute = this.get('rangeRoute');
1440         this.set('rangeBars', (this.get('ranges') || []).map(function (range) {
1441             var start = currentTimeSeries.findPointByMeasurementId(range.get('startRun'));
1442             var end = currentTimeSeries.findPointByMeasurementId(range.get('endRun'));
1443             return Ember.Object.create({
1444                 startTime: midPoint(currentTimeSeries.previousPoint(start), start),
1445                 endTime: midPoint(end, currentTimeSeries.nextPoint(end)),
1446                 range: range,
1447                 left: null,
1448                 right: null,
1449                 rowIndex: null,
1450                 top: null,
1451                 bottom: null,
1452                 linkRoute: linkRoute,
1453                 linkId: range.get('id'),
1454                 label: range.get('label'),
1455             });
1456         }));
1457
1458         this._updateRangeBarRects();
1459     }.observes('ranges'),
1460     _updateRangeBarRects: function () {
1461         var rangeBars = this.get('rangeBars');
1462         if (!rangeBars || !rangeBars.length)
1463             return;
1464
1465         var xScale = this._x;
1466         var yScale = this._y;
1467
1468         // Expand the width of each range as needed and sort ranges by the left-edge of ranges.
1469         var minWidth = 3;
1470         var sortedBars = rangeBars.map(function (bar) {
1471             var left = xScale(bar.get('startTime'));
1472             var right = xScale(bar.get('endTime'));
1473             if (right - left < minWidth) {
1474                 left -= minWidth / 2;
1475                 right += minWidth / 2;
1476             }
1477             bar.set('left', left);
1478             bar.set('right', right);
1479             return bar;
1480         }).sort(function (first, second) { return first.get('left') - second.get('left'); });
1481
1482         // At this point, left edges of all ranges prior to a range R1 is on the left of R1.
1483         // 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.
1484         var rows = [];
1485         sortedBars.forEach(function (bar) {
1486             var rowIndex = 0;
1487             for (; rowIndex < rows.length; rowIndex++) {
1488                 var currentRow = rows[rowIndex];
1489                 if (currentRow[currentRow.length - 1].get('right') < bar.get('left')) {
1490                     currentRow.push(bar);
1491                     break;
1492                 }
1493             }
1494             if (rowIndex >= rows.length)
1495                 rows.push([bar]);
1496             bar.set('rowIndex', rowIndex);
1497         });
1498         var rowHeight = 0.6 * this._rem;
1499         var firstRowTop = this._contentHeight - rows.length * rowHeight;
1500         var barHeight = 0.5 * this._rem;
1501
1502         $(this.get('element')).find('.rangeBarsContainerInlineStyle').css({
1503             left: this._margin.left + 'px',
1504             top: this._margin.top + firstRowTop + 'px',
1505             width: this._contentWidth + 'px',
1506             height: rows.length * barHeight + 'px',
1507             overflow: 'hidden',
1508             position: 'absolute',
1509         });
1510
1511         var margin = this._margin;
1512         sortedBars.forEach(function (bar) {
1513             var top = bar.get('rowIndex') * rowHeight;
1514             var height = barHeight;
1515             var left = bar.get('left');
1516             var width = bar.get('right') - left;
1517             bar.set('inlineStyle', 'left: ' + left + 'px; top: ' + top + 'px; width: ' + width + 'px; height: ' + height + 'px;');
1518         });
1519     },
1520     _updateCurrentItemIndicators: function ()
1521     {
1522         if (!this._currentItemLine)
1523             return;
1524
1525         var item = this._currentTimeSeriesData[this._currentItemIndex];
1526         if (!item) {
1527             this._currentItemLine.attr("x1", -1000).attr("x2", -1000);
1528             this._currentItemCircle.attr("cx", -1000);
1529             return;
1530         }
1531
1532         var x = this._x(item.time);
1533         var y = this._y(item.value);
1534
1535         this._currentItemLine
1536             .attr("x1", x)
1537             .attr("x2", x);
1538
1539         this._currentItemCircle
1540             .attr("cx", x)
1541             .attr("cy", y);
1542     },
1543     _setCurrentSelection: function (newSelection)
1544     {
1545         if (this._brushExtent === newSelection)
1546             return;
1547
1548         var points = null;
1549         if (newSelection) {
1550             points = this._currentTimeSeriesData
1551                 .filter(function (point) { return point.time >= newSelection[0] && point.time <= newSelection[1]; });
1552             if (!points.length)
1553                 points = null;
1554         }
1555
1556         this._brushExtent = newSelection;
1557         this._setCurrentItem(undefined);
1558         this._updateSelectionToolbar();
1559
1560         this.set('sharedSelection', newSelection);
1561         this.sendAction('selectionChanged', newSelection, points);
1562     },
1563     _updateSelectionToolbar: function ()
1564     {
1565         if (!this.get('interactive'))
1566             return;
1567
1568         var selection = this._currentSelection();
1569         var selectionToolbar = $(this.get('element')).children('.selection-toolbar');
1570         if (selection) {
1571             var left = this._x(selection[0]);
1572             var right = this._x(selection[1]);
1573             selectionToolbar
1574                 .css({left: this._margin.left + right, top: this._margin.top + this._contentHeight})
1575                 .show();
1576         } else
1577             selectionToolbar.hide();
1578     },
1579     actions: {
1580         zoom: function ()
1581         {
1582             this.sendAction('zoom', this._currentSelection());
1583             this.set('selection', null);
1584         },
1585         openRange: function (range)
1586         {
1587             this.sendAction('openRange', range);
1588         },
1589     },
1590 });
1591
1592
1593
1594 App.CommitsViewerComponent = Ember.Component.extend({
1595     repository: null,
1596     revisionInfo: null,
1597     commits: null,
1598     commitsChanged: function ()
1599     {
1600         var revisionInfo = this.get('revisionInfo');
1601
1602         var to = revisionInfo.get('currentRevision');
1603         var from = revisionInfo.get('previousRevision');
1604         var repository = this.get('repository');
1605         if (!from || !repository || !repository.get('hasReportedCommits'))
1606             return;
1607
1608         var self = this;
1609         CommitLogs.fetchForTimeRange(repository.get('id'), from, to).then(function (commits) {
1610             if (self.isDestroyed)
1611                 return;
1612             self.set('commits', commits.map(function (commit) {
1613                 return Ember.Object.create({
1614                     repository: repository,
1615                     revision: commit.revision,
1616                     url: repository.urlForRevision(commit.revision),
1617                     author: commit.authorName || commit.authorEmail,
1618                     message: commit.message ? commit.message.substr(0, 75) : null,
1619                 });
1620             }));
1621         }, function () {
1622             if (!self.isDestroyed)
1623                 self.set('commits', []);
1624         })
1625     }.observes('repository').observes('revisionInfo').on('init'),
1626 });
1627
1628
1629 App.AnalysisRoute = Ember.Route.extend({
1630     model: function () {
1631         return this.store.findAll('analysisTask').then(function (tasks) {
1632             return Ember.Object.create({'tasks': tasks});
1633         });
1634     },
1635 });
1636
1637 App.AnalysisTaskRoute = Ember.Route.extend({
1638     model: function (param)
1639     {
1640         return this.store.find('analysisTask', param.taskId);
1641     },
1642 });
1643
1644 App.AnalysisTaskController = Ember.Controller.extend({
1645     label: Ember.computed.alias('model.name'),
1646     platform: Ember.computed.alias('model.platform'),
1647     metric: Ember.computed.alias('model.metric'),
1648     testSets: [],
1649     roots: [],
1650     bugTrackers: [],
1651     _taskUpdated: function ()
1652     {
1653         var model = this.get('model');
1654         if (!model)
1655             return;
1656
1657         var platformId = model.get('platform').get('id');
1658         var metricId = model.get('metric').get('id');
1659         App.Manifest.fetch(this.store).then(this._fetchedManifest.bind(this));
1660         App.Manifest.fetchRunsWithPlatformAndMetric(this.store, platformId, metricId).then(this._fetchedRuns.bind(this));
1661     }.observes('model').on('init'),
1662     _fetchedManifest: function ()
1663     {
1664         var trackerIdToBugNumber = {};
1665         this.get('model').get('bugs').forEach(function (bug) {
1666             trackerIdToBugNumber[bug.get('bugTracker').get('id')] = bug.get('number');
1667         });
1668
1669         this.set('bugTrackers', App.Manifest.get('bugTrackers').map(function (bugTracker) {
1670             var bugNumber = trackerIdToBugNumber[bugTracker.get('id')];
1671             return Ember.ObjectProxy.create({
1672                 content: bugTracker,
1673                 bugNumber: bugNumber,
1674                 editedBugNumber: bugNumber,
1675             });
1676         }));
1677     },
1678     _fetchedRuns: function (data) {
1679         var runs = data.runs;
1680
1681         var currentTimeSeries = runs.current.timeSeriesByCommitTime();
1682         if (!currentTimeSeries)
1683             return; // FIXME: Report an error.
1684
1685         var start = currentTimeSeries.findPointByMeasurementId(this.get('model').get('startRun'));
1686         var end = currentTimeSeries.findPointByMeasurementId(this.get('model').get('endRun'));
1687         if (!start || !end)
1688             return; // FIXME: Report an error.
1689
1690         var markedPoints = {};
1691         markedPoints[start.measurement.id()] = true;
1692         markedPoints[end.measurement.id()] = true;
1693
1694         var formatedPoints = currentTimeSeries.seriesBetweenPoints(start, end).map(function (point, index) {
1695             return {
1696                 id: point.measurement.id(),
1697                 measurement: point.measurement,
1698                 label: 'Point ' + (index + 1),
1699                 value: point.value + (runs.unit ? ' ' + runs.unit : ''),
1700             };
1701         });
1702
1703         var margin = (end.time - start.time) * 0.1;
1704         this.set('chartData', runs);
1705         this.set('chartDomain', [start.time - margin, +end.time + margin]);
1706         this.set('markedPoints', markedPoints);
1707         this.set('analysisPoints', formatedPoints);
1708     },
1709     testSets: function ()
1710     {
1711         var analysisPoints = this.get('analysisPoints');
1712         if (!analysisPoints)
1713             return;
1714         var pointOptions = [{value: ' ', label: 'None'}]
1715             .concat(analysisPoints.map(function (point) { return {value: point.id, label: point.label}; }));
1716         return [
1717             Ember.Object.create({name: "A", options: pointOptions, selection: pointOptions[1]}),
1718             Ember.Object.create({name: "B", options: pointOptions, selection: pointOptions[pointOptions.length - 1]}),
1719         ];
1720     }.property('analysisPoints'),
1721     _rootChangedForTestSet: function () {
1722         var sets = this.get('testSets');
1723         var roots = this.get('roots');
1724         if (!sets || !roots)
1725             return;
1726
1727         sets.forEach(function (testSet, setIndex) {
1728             var currentSelection = testSet.get('selection');
1729             if (currentSelection == testSet.get('previousSelection'))
1730                 return;
1731             testSet.set('previousSelection', currentSelection);
1732             var pointIndex = testSet.get('options').indexOf(currentSelection);
1733
1734             roots.forEach(function (root) {
1735                 var set = root.sets[setIndex];
1736                 set.set('selection', set.revisions[pointIndex]);
1737             });
1738         });
1739
1740     }.observes('testSets.@each.selection'),
1741     roots: function ()
1742     {
1743         var analysisPoints = this.get('analysisPoints');
1744         if (!analysisPoints)
1745             return [];
1746         var repositoryToRevisions = {};
1747         analysisPoints.forEach(function (point, pointIndex) {
1748             var revisions = point.measurement.formattedRevisions();
1749             for (var repositoryName in revisions) {
1750                 if (!repositoryToRevisions[repositoryName])
1751                     repositoryToRevisions[repositoryName] = new Array(analysisPoints.length);
1752                 var revision = revisions[repositoryName];
1753                 repositoryToRevisions[repositoryName][pointIndex] = {
1754                     label: point.label + ': ' + revision.label,
1755                     value: revision.currentRevision,
1756                 };
1757             }
1758         });
1759
1760         var roots = [];
1761         for (var repositoryName in repositoryToRevisions) {
1762             var revisions = [{value: ' ', label: 'None'}].concat(repositoryToRevisions[repositoryName]);
1763             roots.push(Ember.Object.create({
1764                 name: repositoryName,
1765                 sets: [
1766                     Ember.Object.create({name: 'A[' + repositoryName + ']',
1767                         revisions: revisions,
1768                         selection: revisions[1]}),
1769                     Ember.Object.create({name: 'B[' + repositoryName + ']',
1770                         revisions: revisions,
1771                         selection: revisions[revisions.length - 1]}),
1772                 ],
1773             }));
1774         }
1775         return roots;
1776     }.property('analysisPoints'),
1777     actions: {
1778         associateBug: function (bugTracker, bugNumber)
1779         {
1780             var model = this.get('model');
1781             this.store.createRecord('bug',
1782                 {task: this.get('model'), bugTracker: bugTracker.get('content'), number: bugNumber}).save().then(function () {
1783                     // FIXME: Should we notify the user?
1784                 }, function (error) {
1785                     alert('Failed to associate the bug: ' + error);
1786                 });
1787         }
1788     },
1789 });