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