New perf dashboard shows too much space around interesting data points
[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('customDashboard', {path: 'dashboard/custom'});
5     this.resource('dashboard', {path: 'dashboard/:name'});
6     this.resource('charts', {path: 'charts'});
7     this.resource('analysis', {path: 'analysis'});
8     this.resource('analysisTask', {path: 'analysis/task/:taskId'});
9 });
10
11 App.DashboardRow = Ember.Object.extend({
12     header: null,
13     cells: [],
14
15     init: function ()
16     {
17         this._super();
18
19         var cellsInfo = this.get('cellsInfo') || [];
20         var columnCount = this.get('columnCount');
21         while (cellsInfo.length < columnCount)
22             cellsInfo.push([]);
23
24         this.set('cells', cellsInfo.map(this._createPane.bind(this)));
25     },
26     addPane: function (paneInfo)
27     {
28         var pane = this._createPane(paneInfo);
29         this.get('cells').pushObject(pane);
30         this.set('columnCount', this.get('columnCount') + 1);
31     },
32     _createPane: function (paneInfo)
33     {
34         if (!paneInfo || !paneInfo.length || (!paneInfo[0] && !paneInfo[1]))
35             paneInfo = null;
36
37         var pane = App.Pane.create({
38             store: this.get('store'),
39             platformId: paneInfo ? paneInfo[0] : null,
40             metricId: paneInfo ? paneInfo[1] : null,
41         });
42
43         return App.DashboardPaneProxyForPicker.create({content: pane});
44     },
45 });
46
47 App.DashboardPaneProxyForPicker = Ember.ObjectProxy.extend({
48     _platformOrMetricIdChanged: function ()
49     {
50         var self = this;
51         App.buildPopup(this.get('store'), 'choosePane', this)
52             .then(function (platforms) { self.set('pickerData', platforms); });
53     }.observes('platformId', 'metricId').on('init'),
54     paneList: function () {
55         return App.encodePrettifiedJSON([[this.get('platformId'), this.get('metricId'), null, null, false]]);
56     }.property('platformId', 'metricId'),
57 });
58
59 App.IndexRoute = Ember.Route.extend({
60     beforeModel: function ()
61     {
62         var self = this;
63         App.Manifest.fetch(this.store).then(function () {
64             self.transitionTo('dashboard', App.Manifest.defaultDashboardName());
65         });
66     },
67 });
68
69 App.DashboardRoute = Ember.Route.extend({
70     model: function (param)
71     {
72         return App.Manifest.fetch(this.store).then(function () {
73             return App.Manifest.dashboardByName(param.name);
74         });
75     },
76 });
77
78 App.CustomDashboardRoute = Ember.Route.extend({
79     controllerName: 'dashboard',
80     model: function (param)
81     {
82         return this.store.createRecord('dashboard', {serialized: param.grid});
83     },
84     renderTemplate: function()
85     {
86         this.render('dashboard');
87     }
88 });
89
90 App.DashboardController = Ember.Controller.extend({
91     queryParams: ['grid', 'numberOfDays'],
92     headerColumns: [],
93     rows: [],
94     numberOfDays: 7,
95     editMode: false,
96
97     modelChanged: function ()
98     {
99         var dashboard = this.get('model');
100         if (!dashboard)
101             return;
102
103         var headerColumns = dashboard.get('headerColumns');
104         this.set('headerColumns', headerColumns);
105         var columnCount = headerColumns.length;
106         this.set('columnCount', columnCount);
107
108         var store = this.store;
109         this.set('rows', dashboard.get('rows').map(function (rowParam) {
110             return App.DashboardRow.create({
111                 store: store,
112                 header: rowParam[0],
113                 cellsInfo: rowParam.slice(1),
114                 columnCount: columnCount,
115             })
116         }));
117
118         this.set('emptyRow', new Array(columnCount));
119     }.observes('model').on('init'),
120
121     computeGrid: function()
122     {
123         var headers = this.get('headerColumns').map(function (header) { return header.label; });
124         var table = [headers].concat(this.get('rows').map(function (row) {
125             return [row.get('header')].concat(row.get('cells').map(function (pane) {
126                 var platformAndMetric = [pane.get('platformId'), pane.get('metricId')];
127                 return platformAndMetric[0] || platformAndMetric[1] ? platformAndMetric : [];
128             }));
129         }));
130         return JSON.stringify(table);
131     },
132
133     _sharedDomainChanged: function ()
134     {
135         var numberOfDays = this.get('numberOfDays');
136         if (!numberOfDays)
137             return;
138
139         numberOfDays = parseInt(numberOfDays);
140         var present = Date.now();
141         var past = present - numberOfDays * 24 * 3600 * 1000;
142         this.set('since', past);
143         this.set('sharedDomain', [past, present]);
144     }.observes('numberOfDays').on('init'),
145
146     actions: {
147         setNumberOfDays: function (numberOfDays)
148         {
149             this.set('numberOfDays', numberOfDays);
150         },
151         choosePane: function (param)
152         {
153             var pane = param.position;
154             pane.set('platformId', param.platform.get('id'));
155             pane.set('metricId', param.metric.get('id'));
156         },
157         addColumn: function ()
158         {
159             this.get('headerColumns').pushObject({
160                 label: this.get('newColumnHeader'),
161                 index: this.get('headerColumns').length,
162             });
163             this.get('rows').forEach(function (row) {
164                 row.addPane();
165             });
166             this.set('newColumnHeader', null);
167         },
168         removeColumn: function (index)
169         {
170             this.get('headerColumns').removeAt(index);
171             this.get('rows').forEach(function (row) {
172                 row.get('cells').removeAt(index);
173             });
174         },
175         addRow: function ()
176         {
177             this.get('rows').pushObject(App.DashboardRow.create({
178                 store: this.store,
179                 header: this.get('newRowHeader'),
180                 columnCount: this.get('columnCount'),
181             }));
182             this.set('newRowHeader', null);
183         },
184         removeRow: function (row)
185         {
186             this.get('rows').removeObject(row);
187         },
188         resetPane: function (pane)
189         {
190             pane.set('platformId', null);
191             pane.set('metricId', null);
192         },
193         toggleEditMode: function ()
194         {
195             this.toggleProperty('editMode');
196             if (this.get('editMode'))
197                 this.transitionToRoute('dashboard', 'custom', {name: null, queryParams: {grid: this.computeGrid()}});
198             else
199                 this.set('grid', this.computeGrid());
200         },
201     },
202
203     init: function ()
204     {
205         this._super();
206         App.Manifest.fetch(this.get('store'));
207     }
208 });
209
210 App.NumberOfDaysControlView = Ember.View.extend({
211     classNames: ['controls'],
212     templateName: 'number-of-days-controls',
213     didInsertElement: function ()
214     {
215         this._matchingElements(this._previousNumberOfDaysClass).addClass('active');
216     },
217     _numberOfDaysChanged: function ()
218     {
219         this._matchingElements(this._previousNumberOfDaysClass).removeClass('active');
220
221         var newNumberOfDaysClass = 'numberOfDaysIs' + this.get('numberOfDays');
222         this._matchingElements(this._previousNumberOfDaysClass).addClass('active');
223         this._previousNumberOfDaysClass = newNumberOfDaysClass;
224     }.observes('numberOfDays').on('init'),
225     _matchingElements: function (className)
226     {
227         var element = this.get('element');
228         if (!element)
229             return $([]);
230         return $(element.getElementsByClassName(className));
231     }
232 });
233
234 App.StartTimeSliderView = Ember.View.extend({
235     templateName: 'start-time-slider',
236     classNames: ['start-time-slider'],
237     startTime: Date.now() - 7 * 24 * 3600 * 1000,
238     oldestStartTime: null,
239     _numberOfDaysView: null,
240     _slider: null,
241     _startTimeInSlider: null,
242     _currentNumberOfDays: null,
243     _MILLISECONDS_PER_DAY: 24 * 3600 * 1000,
244
245     didInsertElement: function ()
246     {
247         this.oldestStartTime = Date.now() - 365 * 24 * 3600 * 1000;
248         this._slider = $(this.get('element')).find('input');
249         this._numberOfDaysView = $(this.get('element')).find('.numberOfDays');
250         this._sliderRangeChanged();
251         this._slider.change(this._sliderMoved.bind(this));
252     },
253     _sliderRangeChanged: function ()
254     {
255         var minimumNumberOfDays = 1;
256         var maximumNumberOfDays = this._timeInPastToNumberOfDays(this.get('oldestStartTime'));
257         var precision = 1000; // FIXME: Compute this from maximumNumberOfDays.
258         var slider = this._slider;
259         slider.attr('min', Math.floor(Math.log(Math.max(1, minimumNumberOfDays)) * precision) / precision);
260         slider.attr('max', Math.ceil(Math.log(maximumNumberOfDays) * precision) / precision);
261         slider.attr('step', 1 / precision);
262         this._startTimeChanged();
263     }.observes('oldestStartTime'),
264     _sliderMoved: function ()
265     {
266         this._currentNumberOfDays = Math.round(Math.exp(this._slider.val()));
267         this._numberOfDaysView.text(this._currentNumberOfDays);
268         this._startTimeInSlider = this._numberOfDaysToTimeInPast(this._currentNumberOfDays);
269         this.set('startTime', this._startTimeInSlider);
270     },
271     _startTimeChanged: function ()
272     {
273         var startTime = this.get('startTime');
274         if (startTime == this._startTimeSetBySlider)
275             return;
276         this._currentNumberOfDays = this._timeInPastToNumberOfDays(startTime);
277
278         if (this._slider) {
279             this._numberOfDaysView.text(this._currentNumberOfDays);
280             this._slider.val(Math.log(this._currentNumberOfDays));
281             this._startTimeInSlider = startTime;
282         }
283     }.observes('startTime').on('init'),
284     _timeInPastToNumberOfDays: function (timeInPast)
285     {
286         return Math.max(1, Math.round((Date.now() - timeInPast) / this._MILLISECONDS_PER_DAY));
287     },
288     _numberOfDaysToTimeInPast: function (numberOfDays)
289     {
290         return Date.now() - numberOfDays * this._MILLISECONDS_PER_DAY;
291     },
292 });
293
294 App.Pane = Ember.Object.extend({
295     platformId: null,
296     platform: null,
297     metricId: null,
298     metric: null,
299     selectedItem: null,
300     showFullYAxis: false,
301     searchCommit: function (repository, keyword) {
302         var self = this;
303         var repositoryId = repository.get('id');
304         CommitLogs.fetchForTimeRange(repositoryId, null, null, keyword).then(function (commits) {
305             if (self.isDestroyed || !self.get('chartData') || !commits.length)
306                 return;
307             var currentRuns = self.get('chartData').current.series();
308             if (!currentRuns.length)
309                 return;
310
311             var highlightedItems = {};
312             var commitIndex = 0;
313             for (var runIndex = 0; runIndex < currentRuns.length && commitIndex < commits.length; runIndex++) {
314                 var measurement = currentRuns[runIndex].measurement;
315                 var commitTime = measurement.commitTimeForRepository(repositoryId);
316                 if (!commitTime)
317                     continue;
318                 if (commits[commitIndex].time <= commitTime) {
319                     highlightedItems[measurement.id()] = true;
320                     do {
321                         commitIndex++;
322                     } while (commitIndex < commits.length && commits[commitIndex].time <= commitTime);
323                 }
324             }
325
326             self.set('highlightedItems', highlightedItems);
327         }, function () {
328             // FIXME: Report errors
329             this.set('highlightedItems', {});
330         });
331     },
332     _fetch: function () {
333         var platformId = this.get('platformId');
334         var metricId = this.get('metricId');
335         if (!platformId && !metricId) {
336             this.set('empty', true);
337             return;
338         }
339         this.set('empty', false);
340         this.set('platform', null);
341         this.set('chartData', null);
342         this.set('metric', null);
343         this.set('failure', null);
344
345         if (!this._isValidId(platformId))
346             this.set('failure', platformId ? 'Invalid platform id:' + platformId : 'Platform id was not specified');
347         else if (!this._isValidId(metricId))
348             this.set('failure', metricId ? 'Invalid metric id:' + metricId : 'Metric id was not specified');
349         else {
350             var self = this;
351
352             App.Manifest.fetchRunsWithPlatformAndMetric(this.get('store'), platformId, metricId).then(function (result) {
353                 self.set('platform', result.platform);
354                 self.set('metric', result.metric);
355                 self.set('fetchedData', result);
356                 self._computeChartData();
357             }, function (result) {
358                 if (!result || typeof(result) === "string")
359                     self.set('failure', 'Failed to fetch the JSON with an error: ' + result);
360                 else if (!result.platform)
361                     self.set('failure', 'Could not find the platform "' + platformId + '"');
362                 else if (!result.metric)
363                     self.set('failure', 'Could not find the metric "' + metricId + '"');
364                 else
365                     self.set('failure', 'An internal error');
366             });
367
368             this.fetchAnalyticRanges();
369         }
370     }.observes('platformId', 'metricId').on('init'),
371     fetchAnalyticRanges: function ()
372     {
373         var platformId = this.get('platformId');
374         var metricId = this.get('metricId');
375         var self = this;
376         this.get('store')
377             .find('analysisTask', {platform: platformId, metric: metricId})
378             .then(function (tasks) {
379                 self.set('analyticRanges', tasks.filter(function (task) { return task.get('startRun') && task.get('endRun'); }));
380             });
381     },
382     _isValidId: function (id)
383     {
384         if (typeof(id) == "number")
385             return true;
386         if (typeof(id) == "string")
387             return !!id.match(/^[A-Za-z0-9_]+$/);
388         return false;
389     },
390     computeStatus: function (currentPoint, previousPoint)
391     {
392         var chartData = this.get('chartData');
393         var diffFromBaseline = this._relativeDifferentToLaterPointInTimeSeries(currentPoint, chartData.baseline);
394         var diffFromTarget = this._relativeDifferentToLaterPointInTimeSeries(currentPoint, chartData.target);
395
396         var label = '';
397         var className = '';
398         var formatter = d3.format('.3p');
399
400         var smallerIsBetter = chartData.smallerIsBetter;
401         if (diffFromBaseline !== undefined && diffFromBaseline > 0 == smallerIsBetter) {
402             label = formatter(Math.abs(diffFromBaseline)) + ' ' + (smallerIsBetter ? 'above' : 'below') + ' baseline';
403             className = 'worse';
404         } else if (diffFromTarget !== undefined && diffFromTarget < 0 == smallerIsBetter) {
405             label = formatter(Math.abs(diffFromTarget)) + ' ' + (smallerIsBetter ? 'below' : 'above') + ' target';
406             className = 'better';
407         } else if (diffFromTarget !== undefined)
408             label = formatter(Math.abs(diffFromTarget)) + ' until target';
409
410         var valueDelta = previousPoint ? chartData.deltaFormatter(currentPoint.value - previousPoint.value) : null;
411         return {className: className, label: label, currentValue: chartData.formatter(currentPoint.value), valueDelta: valueDelta};
412     },
413     _relativeDifferentToLaterPointInTimeSeries: function (currentPoint, timeSeries)
414     {
415         if (!currentPoint || !timeSeries)
416             return undefined;
417
418         var referencePoint = timeSeries.findPointAfterTime(currentPoint.time);
419         if (!referencePoint)
420             return undefined;
421
422         return (currentPoint.value - referencePoint.value) / referencePoint.value;
423     },
424     latestStatus: function ()
425     {
426         var chartData = this.get('chartData');
427         if (!chartData || !chartData.current)
428             return null;
429
430         var lastPoint = chartData.current.lastPoint();
431         if (!lastPoint)
432             return null;
433
434         return this.computeStatus(lastPoint, chartData.current.previousPoint(lastPoint));
435     }.property('chartData'),
436     updateStatisticsTools: function ()
437     {
438         var movingAverageStrategies = Statistics.MovingAverageStrategies.map(this._cloneStrategy.bind(this));
439         this.set('movingAverageStrategies', [{label: 'None'}].concat(movingAverageStrategies));
440         this.set('chosenMovingAverageStrategy', this._configureStrategy(movingAverageStrategies, this.get('movingAverageConfig')));
441
442         var envelopingStrategies = Statistics.EnvelopingStrategies.map(this._cloneStrategy.bind(this));
443         this.set('envelopingStrategies', [{label: 'None'}].concat(envelopingStrategies));
444         this.set('chosenEnvelopingStrategy', this._configureStrategy(envelopingStrategies, this.get('envelopingConfig')));
445     }.on('init'),
446     _cloneStrategy: function (strategy)
447     {
448         var parameterList = (strategy.parameterList || []).map(function (param) { return Ember.Object.create(param); });
449         return Ember.Object.create({
450             id: strategy.id,
451             label: strategy.label,
452             description: strategy.description,
453             parameterList: parameterList,
454             execute: strategy.execute,
455         });
456     },
457     _configureStrategy: function (strategies, config)
458     {
459         if (!config || !config[0])
460             return null;
461
462         var id = config[0];
463         var chosenStrategy = strategies.find(function (strategy) { return strategy.id == id });
464         if (!chosenStrategy)
465             return null;
466
467         if (chosenStrategy.parameterList) {
468             for (var i = 0; i < chosenStrategy.parameterList.length; i++)
469                 chosenStrategy.parameterList[i].value = parseFloat(config[i + 1]);
470         }
471
472         return chosenStrategy;
473     },
474     _computeChartData: function ()
475     {
476         if (!this.get('fetchedData'))
477             return;
478
479         var chartData = App.createChartData(this.get('fetchedData'));
480
481         var movingAverageStrategy = this.get('chosenMovingAverageStrategy');
482         this._updateStrategyConfigIfNeeded(movingAverageStrategy, 'movingAverageConfig');
483
484         var envelopingStrategy = this.get('chosenEnvelopingStrategy');
485         this._updateStrategyConfigIfNeeded(envelopingStrategy, 'envelopingConfig');
486
487         chartData.movingAverage = this._computeMovingAverageAndOutliers(chartData, movingAverageStrategy, envelopingStrategy);
488
489         this.set('chartData', chartData);
490     }.observes('chosenMovingAverageStrategy', 'chosenMovingAverageStrategy.parameterList.@each.value',
491         'chosenEnvelopingStrategy', 'chosenEnvelopingStrategy.parameterList.@each.value'),
492     _computeMovingAverageAndOutliers: function (chartData, movingAverageStrategy, envelopingStrategy)
493     {
494         var currentTimeSeriesData = chartData.current.series();
495         var movingAverageIsSetByUser = movingAverageStrategy && movingAverageStrategy.execute;
496         var movingAverageValues = this._executeStrategy(
497             movingAverageIsSetByUser ? movingAverageStrategy : Statistics.MovingAverageStrategies[0], currentTimeSeriesData);
498         if (!movingAverageValues)
499             return null;
500
501         var envelopeIsSetByUser = envelopingStrategy && envelopingStrategy.execute;
502         var envelopeDelta = this._executeStrategy(envelopeIsSetByUser ? envelopingStrategy : Statistics.EnvelopingStrategies[0],
503             currentTimeSeriesData, [movingAverageValues]);
504
505         for (var i = 0; i < currentTimeSeriesData.length; i++) {
506             var currentValue = currentTimeSeriesData[i].value;
507             var movingAverageValue = movingAverageValues[i];
508             if (currentValue < movingAverageValue - envelopeDelta || movingAverageValue + envelopeDelta < currentValue)
509                 currentTimeSeriesData[i].isOutlier = true;
510         }
511         if (!envelopeIsSetByUser)
512             envelopeDelta = null;
513
514         if (movingAverageIsSetByUser) {
515             return new TimeSeries(currentTimeSeriesData.map(function (point, index) {
516                 var value = movingAverageValues[index];
517                 return {
518                     measurement: point.measurement,
519                     time: point.time,
520                     value: value,
521                     interval: envelopeDelta !== null ? [value - envelopeDelta, value + envelopeDelta] : null,
522                 }
523             }));            
524         }
525     },
526     _executeStrategy: function (strategy, currentTimeSeriesData, additionalArguments)
527     {
528         var parameters = (strategy.parameterList || []).map(function (param) {
529             var parsed = parseFloat(param.value);
530             return Math.min(param.max || Infinity, Math.max(param.min || -Infinity, isNaN(parsed) ? 0 : parsed));
531         });
532         parameters.push(currentTimeSeriesData.map(function (point) { return point.value }));
533         return strategy.execute.apply(window, parameters.concat(additionalArguments));
534     },
535     _updateStrategyConfigIfNeeded: function (strategy, configName)
536     {
537         var config = null;
538         if (strategy && strategy.execute)
539             config = [strategy.id].concat((strategy.parameterList || []).map(function (param) { return param.value; }));
540
541         if (JSON.stringify(config) != JSON.stringify(this.get(configName)))
542             this.set(configName, config);
543     },
544 });
545
546 App.createChartData = function (data)
547 {
548     var runs = data.runs;
549     return {
550         current: runs.current.timeSeriesByCommitTime(),
551         baseline: runs.baseline ? runs.baseline.timeSeriesByCommitTime() : null,
552         target: runs.target ? runs.target.timeSeriesByCommitTime() : null,
553         unit: data.unit,
554         formatter: data.useSI ? d3.format('.4s') : d3.format('.4g'),
555         deltaFormatter: data.useSI ? d3.format('+.2s') : d3.format('+.2g'),
556         smallerIsBetter: data.smallerIsBetter,
557     };
558 }
559
560 App.encodePrettifiedJSON = function (plain)
561 {
562     function numberIfPossible(string) {
563         return string == parseInt(string) ? parseInt(string) : string;
564     }
565
566     function recursivelyConvertNumberIfPossible(input) {
567         if (input instanceof Array) {
568             return input.map(recursivelyConvertNumberIfPossible);
569         }
570         return numberIfPossible(input);
571     }
572
573     return JSON.stringify(recursivelyConvertNumberIfPossible(plain))
574         .replace(/\[/g, '(').replace(/\]/g, ')').replace(/\,/g, '-');
575 }
576
577 App.decodePrettifiedJSON = function (encoded)
578 {
579     var parsed = encoded.replace(/\(/g, '[').replace(/\)/g, ']').replace(/\-/g, ',');
580     try {
581         return JSON.parse(parsed);
582     } catch (exception) {
583         return null;
584     }
585 }
586
587 App.ChartsController = Ember.Controller.extend({
588     queryParams: ['paneList', 'zoom', 'since'],
589     needs: ['pane'],
590     _currentEncodedPaneList: null,
591     panes: [],
592     platforms: null,
593     sharedZoom: null,
594     startTime: null,
595     present: Date.now(),
596     defaultSince: Date.now() - 7 * 24 * 3600 * 1000,
597
598     addPane: function (pane)
599     {
600         this.panes.unshiftObject(pane);
601     },
602
603     removePane: function (pane)
604     {
605         this.panes.removeObject(pane);
606     },
607
608     refreshPanes: function()
609     {
610         var paneList = this.get('paneList');
611         if (paneList === this._currentEncodedPaneList)
612             return;
613
614         var panes = this._parsePaneList(paneList || '[]');
615         if (!panes) {
616             console.log('Failed to parse', jsonPaneList, exception);
617             return;
618         }
619         this.set('panes', panes);
620         this._currentEncodedPaneList = paneList;
621     }.observes('paneList').on('init'),
622
623     refreshZoom: function()
624     {
625         var zoom = this.get('zoom');
626         if (!zoom) {
627             this.set('sharedZoom', null);
628             return;
629         }
630
631         zoom = zoom.split('-');
632         var selection = new Array(2);
633         try {
634             selection[0] = new Date(parseFloat(zoom[0]));
635             selection[1] = new Date(parseFloat(zoom[1]));
636         } catch (error) {
637             console.log('Failed to parse the zoom', zoom);
638         }
639         this.set('sharedZoom', selection);
640
641         var startTime = this.get('startTime');
642         if (startTime && startTime > selection[0])
643             this.set('startTime', selection[0]);
644
645     }.observes('zoom').on('init'),
646
647     _startTimeChanged: function () {
648         this.set('sharedDomain', [this.get('startTime'), this.get('present')]);
649         this._scheduleQueryStringUpdate();
650     }.observes('startTime'),
651
652     _sinceChanged: function () {
653         var since = parseInt(this.get('since'));
654         if (isNaN(since))
655             since = this.defaultSince;
656         this.set('startTime', new Date(since));
657     }.observes('since').on('init'),
658
659     _parsePaneList: function (encodedPaneList)
660     {
661         var parsedPaneList = App.decodePrettifiedJSON(encodedPaneList);
662         if (!parsedPaneList)
663             return null;
664
665         // FIXME: Don't re-create all panes.
666         var self = this;
667         return parsedPaneList.map(function (paneInfo) {
668             var timeRange = null;
669             var selectedItem = null;
670             if (paneInfo[2] instanceof Array) {
671                 var timeRange = paneInfo[2];
672                 try {
673                     timeRange = [new Date(timeRange[0]), new Date(timeRange[1])];
674                 } catch (error) {
675                     console.log("Failed to parse the time range:", timeRange, error);
676                 }
677             } else
678                 selectedItem = paneInfo[2];
679
680             return App.Pane.create({
681                 store: self.store,
682                 info: paneInfo,
683                 platformId: paneInfo[0],
684                 metricId: paneInfo[1],
685                 selectedItem: selectedItem,
686                 timeRange: timeRange,
687                 showFullYAxis: paneInfo[3],
688                 movingAverageConfig: paneInfo[4],
689                 envelopingConfig: paneInfo[5],
690             });
691         });
692     },
693
694     _serializePaneList: function (panes)
695     {
696         if (!panes.length)
697             return undefined;
698         var self = this;
699         return App.encodePrettifiedJSON(panes.map(function (pane) {
700             return [
701                 pane.get('platformId'),
702                 pane.get('metricId'),
703                 pane.get('timeRange') ? pane.get('timeRange').map(function (date) { return date.getTime() }) : pane.get('selectedItem'),
704                 pane.get('showFullYAxis'),
705                 pane.get('movingAverageConfig'),
706                 pane.get('envelopingConfig'),
707             ];
708         }));
709     },
710
711     _scheduleQueryStringUpdate: function ()
712     {
713         Ember.run.debounce(this, '_updateQueryString', 1000);
714     }.observes('sharedZoom', 'panes.@each.platform', 'panes.@each.metric', 'panes.@each.selectedItem', 'panes.@each.timeRange',
715         'panes.@each.showFullYAxis', 'panes.@each.movingAverageConfig', 'panes.@each.envelopingConfig'),
716
717     _updateQueryString: function ()
718     {
719         this._currentEncodedPaneList = this._serializePaneList(this.get('panes'));
720         this.set('paneList', this._currentEncodedPaneList);
721
722         var zoom = undefined;
723         var sharedZoom = this.get('sharedZoom');
724         if (sharedZoom && !App.domainsAreEqual(sharedZoom, this.get('sharedDomain')))
725             zoom = +sharedZoom[0] + '-' + +sharedZoom[1];
726         this.set('zoom', zoom);
727
728         if (this.get('startTime') - this.defaultSince)
729             this.set('since', this.get('startTime') - 0);
730     },
731
732     actions: {
733         addPaneByMetricAndPlatform: function (param)
734         {
735             this.addPane(App.Pane.create({
736                 store: this.store,
737                 platformId: param.platform.get('id'),
738                 metricId: param.metric.get('id'),
739                 showingDetails: false
740             }));
741         },
742     },
743
744     init: function ()
745     {
746         this._super();
747         var self = this;
748         App.buildPopup(this.store, 'addPaneByMetricAndPlatform').then(function (platforms) {
749             self.set('platforms', platforms);
750         });
751     },
752 });
753
754 App.buildPopup = function(store, action, position)
755 {
756     return App.Manifest.fetch(store).then(function () {
757         return App.Manifest.get('platforms').map(function (platform) {
758             return App.PlatformProxyForPopup.create({content: platform,
759                 action: action, position: position});
760         });
761     });
762 }
763
764 App.PlatformProxyForPopup = Ember.ObjectProxy.extend({
765     children: function ()
766     {
767         var platform = this.content;
768         var containsTest = this.content.containsTest.bind(this.content);
769         var action = this.get('action');
770         var position = this.get('position');
771         return App.Manifest.get('topLevelTests')
772             .filter(containsTest)
773             .map(function (test) {
774                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
775             });
776     }.property('App.Manifest.topLevelTests'),
777 });
778
779 App.TestProxyForPopup = Ember.ObjectProxy.extend({
780     platform: null,
781     children: function ()
782     {
783         var platform = this.get('platform');
784         var action = this.get('action');
785         var position = this.get('position');
786
787         var childTests = this.get('childTests')
788             .filter(function (test) { return platform.containsTest(test); })
789             .map(function (test) {
790                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
791             });
792
793         var metrics = this.get('metrics')
794             .filter(function (metric) { return platform.containsMetric(metric); })
795             .map(function (metric) {
796                 var aggregator = metric.get('aggregator');
797                 return {
798                     actionName: action,
799                     actionArgument: {platform: platform, metric: metric, position:position},
800                     label: metric.get('label')
801                 };
802             });
803
804         if (childTests.length && metrics.length)
805             metrics.push({isSeparator: true});
806
807         return metrics.concat(childTests);
808     }.property('childTests', 'metrics'),
809 });
810
811 App.domainsAreEqual = function (domain1, domain2) {
812     return (!domain1 && !domain2) || (domain1 && domain2 && !(domain1[0] - domain2[0]) && !(domain1[1] - domain2[1]));
813 }
814
815 App.PaneController = Ember.ObjectController.extend({
816     needs: ['charts'],
817     sharedTime: Ember.computed.alias('parentController.sharedTime'),
818     sharedSelection: Ember.computed.alias('parentController.sharedSelection'),
819     selection: null,
820     actions: {
821         toggleDetails: function()
822         {
823             this.toggleProperty('showingDetails');
824         },
825         close: function ()
826         {
827             this.parentController.removePane(this.get('model'));
828         },
829         toggleBugsPane: function ()
830         {
831             if (this.toggleProperty('showingAnalysisPane')) {
832                 this.set('showingSearchPane', false);
833                 this.set('showingStatPane', false);
834             }
835         },
836         createAnalysisTask: function ()
837         {
838             var name = this.get('newAnalysisTaskName');
839             var points = this.get('selectedPoints');
840             Ember.assert('The analysis name should not be empty', name);
841             Ember.assert('There should be at least two points in the range', points && points.length >= 2);
842
843             var newWindow = window.open();
844             var self = this;
845             App.AnalysisTask.create(name, points[0].measurement, points[points.length - 1].measurement).then(function (data) {
846                 // FIXME: Update the UI to show the new analysis task.
847                 var url = App.Router.router.generate('analysisTask', data['taskId']);
848                 newWindow.location.href = '#' + url;
849                 self.get('model').fetchAnalyticRanges();
850             }, function (error) {
851                 newWindow.close();
852                 if (error === 'DuplicateAnalysisTask') {
853                     // FIXME: Duplicate this error more gracefully.
854                 }
855                 alert(error);
856             });
857         },
858         toggleSearchPane: function ()
859         {
860             if (!App.Manifest.repositoriesWithReportedCommits)
861                 return;
862             var model = this.get('model');
863             if (!model.get('commitSearchRepository'))
864                 model.set('commitSearchRepository', App.Manifest.repositoriesWithReportedCommits[0]);
865             if (this.toggleProperty('showingSearchPane')) {
866                 this.set('showingAnalysisPane', false);
867                 this.set('showingStatPane', false);
868             }
869         },
870         searchCommit: function () {
871             var model = this.get('model');
872             model.searchCommit(model.get('commitSearchRepository'), model.get('commitSearchKeyword'));                
873         },
874         toggleStatPane: function ()
875         {
876             if (this.toggleProperty('showingStatPane')) {
877                 this.set('showingSearchPane', false);
878                 this.set('showingAnalysisPane', false);
879             }
880         },
881         zoomed: function (selection)
882         {
883             this.set('mainPlotDomain', selection ? selection : this.get('overviewDomain'));
884             Ember.run.debounce(this, 'propagateZoom', 100);
885         },
886     },
887     _detailsChanged: function ()
888     {
889         this.set('showingAnalysisPane', false);
890     }.observes('details'),
891     _overviewSelectionChanged: function ()
892     {
893         var overviewSelection = this.get('overviewSelection');
894         if (App.domainsAreEqual(overviewSelection, this.get('mainPlotDomain')))
895             return;
896         this.set('mainPlotDomain', overviewSelection || this.get('overviewDomain'));
897         Ember.run.debounce(this, 'propagateZoom', 100);
898     }.observes('overviewSelection'),
899     _sharedDomainChanged: function ()
900     {
901         var newDomain = this.get('parentController').get('sharedDomain');
902         if (App.domainsAreEqual(newDomain, this.get('overviewDomain')))
903             return;
904         this.set('overviewDomain', newDomain);
905         if (!this.get('overviewSelection'))
906             this.set('mainPlotDomain', newDomain);
907     }.observes('parentController.sharedDomain').on('init'),
908     propagateZoom: function ()
909     {
910         this.get('parentController').set('sharedZoom', this.get('mainPlotDomain'));
911     },
912     _sharedZoomChanged: function ()
913     {
914         var newSelection = this.get('parentController').get('sharedZoom');
915         if (App.domainsAreEqual(newSelection, this.get('mainPlotDomain')))
916             return;
917         this.set('mainPlotDomain', newSelection || this.get('overviewDomain'));
918         this.set('overviewSelection', newSelection);
919     }.observes('parentController.sharedZoom').on('init'),
920     _updateDetails: function ()
921     {
922         var selectedPoints = this.get('selectedPoints');
923         var currentPoint = this.get('currentItem');
924         if (!selectedPoints && !currentPoint) {
925             this.set('details', null);
926             return;
927         }
928
929         var currentMeasurement;
930         var previousPoint;
931         if (!selectedPoints)
932             previousPoint = currentPoint.series.previousPoint(currentPoint);
933         else {
934             currentPoint = selectedPoints[selectedPoints.length - 1];
935             previousPoint = selectedPoints[0];
936         }
937         var currentMeasurement = currentPoint.measurement;
938         var oldMeasurement = previousPoint ? previousPoint.measurement : null;
939
940         var formattedRevisions = currentMeasurement.formattedRevisions(oldMeasurement);
941         var revisions = App.Manifest.get('repositories')
942             .filter(function (repository) { return formattedRevisions[repository.get('id')]; })
943             .map(function (repository) {
944             var revision = Ember.Object.create(formattedRevisions[repository.get('id')]);
945             revision['url'] = revision.previousRevision
946                 ? repository.urlForRevisionRange(revision.previousRevision, revision.currentRevision)
947                 : repository.urlForRevision(revision.currentRevision);
948             revision['name'] = repository.get('name');
949             revision['repository'] = repository;
950             return revision; 
951         });
952
953         var buildNumber = null;
954         var buildURL = null;
955         if (!selectedPoints) {
956             buildNumber = currentMeasurement.buildNumber();
957             var builder = App.Manifest.builder(currentMeasurement.builderId());
958             if (builder)
959                 buildURL = builder.urlFromBuildNumber(buildNumber);
960         }
961
962         this.set('details', Ember.Object.create({
963             status: this.get('model').computeStatus(currentPoint, previousPoint),
964             buildNumber: buildNumber,
965             buildURL: buildURL,
966             buildTime: currentMeasurement.formattedBuildTime(),
967             revisions: revisions,
968         }));
969         this._updateCanAnalyze();
970     }.observes('currentItem', 'selectedPoints'),
971     _updateCanAnalyze: function ()
972     {
973         var points = this.get('selectedPoints');
974         this.set('cannotAnalyze', !this.get('newAnalysisTaskName') || !points || points.length < 2);
975     }.observes('newAnalysisTaskName'),
976 });
977
978
979 App.AnalysisRoute = Ember.Route.extend({
980     model: function () {
981         return this.store.findAll('analysisTask').then(function (tasks) {
982             return Ember.Object.create({'tasks': tasks});
983         });
984     },
985 });
986
987 App.AnalysisTaskRoute = Ember.Route.extend({
988     model: function (param)
989     {
990         return this.store.find('analysisTask', param.taskId);
991     },
992 });
993
994 App.AnalysisTaskController = Ember.Controller.extend({
995     label: Ember.computed.alias('model.name'),
996     platform: Ember.computed.alias('model.platform'),
997     metric: Ember.computed.alias('model.metric'),
998     testGroups: Ember.computed.alias('model.testGroups'),
999     testSets: [],
1000     roots: [],
1001     bugTrackers: [],
1002     possibleRepetitionCounts: [1, 2, 3, 4, 5, 6],
1003     _taskUpdated: function ()
1004     {
1005         var model = this.get('model');
1006         if (!model)
1007             return;
1008
1009         var platformId = model.get('platform').get('id');
1010         var metricId = model.get('metric').get('id');
1011         App.Manifest.fetch(this.store).then(this._fetchedManifest.bind(this));
1012         App.Manifest.fetchRunsWithPlatformAndMetric(this.store, platformId, metricId).then(this._fetchedRuns.bind(this));
1013     }.observes('model').on('init'),
1014     _fetchedManifest: function ()
1015     {
1016         var trackerIdToBugNumber = {};
1017         this.get('model').get('bugs').forEach(function (bug) {
1018             trackerIdToBugNumber[bug.get('bugTracker').get('id')] = bug.get('number');
1019         });
1020
1021         this.set('bugTrackers', App.Manifest.get('bugTrackers').map(function (bugTracker) {
1022             var bugNumber = trackerIdToBugNumber[bugTracker.get('id')];
1023             return Ember.ObjectProxy.create({
1024                 content: bugTracker,
1025                 bugNumber: bugNumber,
1026                 editedBugNumber: bugNumber,
1027             });
1028         }));
1029     },
1030     _fetchedRuns: function (data)
1031     {
1032         var runs = data.runs;
1033
1034         var currentTimeSeries = runs.current.timeSeriesByCommitTime();
1035         if (!currentTimeSeries)
1036             return; // FIXME: Report an error.
1037
1038         var start = currentTimeSeries.findPointByMeasurementId(this.get('model').get('startRun'));
1039         var end = currentTimeSeries.findPointByMeasurementId(this.get('model').get('endRun'));
1040         if (!start || !end)
1041             return; // FIXME: Report an error.
1042
1043         var highlightedItems = {};
1044         highlightedItems[start.measurement.id()] = true;
1045         highlightedItems[end.measurement.id()] = true;
1046
1047         var chartData = App.createChartData(data);
1048         var formatedPoints = currentTimeSeries.seriesBetweenPoints(start, end).map(function (point, index) {
1049             return {
1050                 id: point.measurement.id(),
1051                 measurement: point.measurement,
1052                 label: 'Point ' + (index + 1),
1053                 value: chartData.formatter(point.value) + (data.unit ? ' ' + data.unit : ''),
1054             };
1055         });
1056
1057         var margin = (end.time - start.time) * 0.1;
1058         this.set('chartData', chartData);
1059         this.set('chartDomain', [start.time - margin, +end.time + margin]);
1060         this.set('highlightedItems', highlightedItems);
1061         this.set('analysisPoints', formatedPoints);
1062     },
1063     testSets: function ()
1064     {
1065         var analysisPoints = this.get('analysisPoints');
1066         if (!analysisPoints)
1067             return;
1068         var pointOptions = [{value: ' ', label: 'None'}]
1069             .concat(analysisPoints.map(function (point) { return {value: point.id, label: point.label}; }));
1070         return [
1071             Ember.Object.create({name: "A", options: pointOptions, selection: pointOptions[1]}),
1072             Ember.Object.create({name: "B", options: pointOptions, selection: pointOptions[pointOptions.length - 1]}),
1073         ];
1074     }.property('analysisPoints'),
1075     _rootChangedForTestSet: function ()
1076     {
1077         var sets = this.get('testSets');
1078         var roots = this.get('roots');
1079         if (!sets || !roots)
1080             return;
1081
1082         sets.forEach(function (testSet, setIndex) {
1083             var currentSelection = testSet.get('selection');
1084             if (currentSelection == testSet.get('previousSelection'))
1085                 return;
1086             testSet.set('previousSelection', currentSelection);
1087             var pointIndex = testSet.get('options').indexOf(currentSelection);
1088
1089             roots.forEach(function (root) {
1090                 var set = root.sets[setIndex];
1091                 set.set('selection', set.revisions[pointIndex]);
1092             });
1093         });
1094
1095     }.observes('testSets.@each.selection'),
1096     updateRoots: function ()
1097     {
1098         var analysisPoints = this.get('analysisPoints');
1099         if (!analysisPoints)
1100             return;
1101         var repositoryToRevisions = {};
1102         analysisPoints.forEach(function (point, pointIndex) {
1103             var revisions = point.measurement.formattedRevisions();
1104             for (var repositoryId in revisions) {
1105                 if (!repositoryToRevisions[repositoryId])
1106                     repositoryToRevisions[repositoryId] = new Array(analysisPoints.length);
1107                 var revision = revisions[repositoryId];
1108                 repositoryToRevisions[repositoryId][pointIndex] = {
1109                     label: point.label + ': ' + revision.label,
1110                     value: revision.currentRevision,
1111                 };
1112             }
1113         });
1114
1115         var self = this;
1116         this.get('model').get('triggerable').then(function (triggerable) {
1117             if (!triggerable)
1118                 return;
1119
1120             self.set('roots', triggerable.get('acceptedRepositories').map(function (repository) {
1121                 var repositoryId = repository.get('id');
1122                 var revisions = [{value: ' ', label: 'None'}].concat(repositoryToRevisions[repositoryId]);
1123                 return Ember.Object.create({
1124                     name: repository.get('name'),
1125                     sets: [
1126                         Ember.Object.create({name: 'A[' + repositoryId + ']',
1127                             revisions: revisions,
1128                             selection: revisions[1]}),
1129                         Ember.Object.create({name: 'B[' + repositoryId + ']',
1130                             revisions: revisions,
1131                             selection: revisions[revisions.length - 1]}),
1132                     ],
1133                 });
1134             }));
1135         });
1136     }.observes('analysisPoints'),
1137     actions: {
1138         associateBug: function (bugTracker, bugNumber)
1139         {
1140             var model = this.get('model');
1141             this.store.createRecord('bug',
1142                 {task: this.get('model'), bugTracker: bugTracker.get('content'), number: bugNumber}).save().then(function () {
1143                     // FIXME: Should we notify the user?
1144                 }, function (error) {
1145                     alert('Failed to associate the bug: ' + error);
1146                 });
1147         },
1148         createTestGroup: function (name, repetitionCount)
1149         {
1150             var roots = {};
1151             this.get('roots').map(function (root) {
1152                 roots[root.get('name')] = root.get('sets').map(function (item) { return item.get('selection').value; });
1153             });
1154             App.TestGroup.create(this.get('model'), name, roots, repetitionCount).then(function () {
1155                 
1156             });
1157         },
1158     },
1159 });