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