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