New perf dashboard should have the ability to overlay moving average with an envelope
[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     searchCommit: function (repository, keyword) {
301         var self = this;
302         var repositoryId = repository.get('id');
303         CommitLogs.fetchForTimeRange(repositoryId, null, null, keyword).then(function (commits) {
304             if (self.isDestroyed || !self.get('chartData') || !commits.length)
305                 return;
306             var currentRuns = self.get('chartData').current.series();
307             if (!currentRuns.length)
308                 return;
309
310             var highlightedItems = {};
311             var commitIndex = 0;
312             for (var runIndex = 0; runIndex < currentRuns.length && commitIndex < commits.length; runIndex++) {
313                 var measurement = currentRuns[runIndex].measurement;
314                 var commitTime = measurement.commitTimeForRepository(repositoryId);
315                 if (!commitTime)
316                     continue;
317                 if (commits[commitIndex].time <= commitTime) {
318                     highlightedItems[measurement.id()] = true;
319                     do {
320                         commitIndex++;
321                     } while (commitIndex < commits.length && commits[commitIndex].time <= commitTime);
322                 }
323             }
324
325             self.set('highlightedItems', highlightedItems);
326         }, function () {
327             // FIXME: Report errors
328             this.set('highlightedItems', {});
329         });
330     },
331     _fetch: function () {
332         var platformId = this.get('platformId');
333         var metricId = this.get('metricId');
334         if (!platformId && !metricId) {
335             this.set('empty', true);
336             return;
337         }
338         this.set('empty', false);
339         this.set('platform', null);
340         this.set('chartData', null);
341         this.set('metric', null);
342         this.set('failure', null);
343
344         if (!this._isValidId(platformId))
345             this.set('failure', platformId ? 'Invalid platform id:' + platformId : 'Platform id was not specified');
346         else if (!this._isValidId(metricId))
347             this.set('failure', metricId ? 'Invalid metric id:' + metricId : 'Metric id was not specified');
348         else {
349             var self = this;
350
351             App.Manifest.fetchRunsWithPlatformAndMetric(this.get('store'), platformId, metricId).then(function (result) {
352                 self.set('platform', result.platform);
353                 self.set('metric', result.metric);
354                 self.set('fetchedData', result);
355                 self._computeChartData();
356             }, function (result) {
357                 if (!result || typeof(result) === "string")
358                     self.set('failure', 'Failed to fetch the JSON with an error: ' + result);
359                 else if (!result.platform)
360                     self.set('failure', 'Could not find the platform "' + platformId + '"');
361                 else if (!result.metric)
362                     self.set('failure', 'Could not find the metric "' + metricId + '"');
363                 else
364                     self.set('failure', 'An internal error');
365             });
366
367             this.fetchAnalyticRanges();
368         }
369     }.observes('platformId', 'metricId').on('init'),
370     fetchAnalyticRanges: function ()
371     {
372         var platformId = this.get('platformId');
373         var metricId = this.get('metricId');
374         var self = this;
375         this.get('store')
376             .find('analysisTask', {platform: platformId, metric: metricId})
377             .then(function (tasks) {
378                 self.set('analyticRanges', tasks.filter(function (task) { return task.get('startRun') && task.get('endRun'); }));
379             });
380     },
381     _isValidId: function (id)
382     {
383         if (typeof(id) == "number")
384             return true;
385         if (typeof(id) == "string")
386             return !!id.match(/^[A-Za-z0-9_]+$/);
387         return false;
388     },
389     computeStatus: function (currentPoint, previousPoint)
390     {
391         var chartData = this.get('chartData');
392         var diffFromBaseline = this._relativeDifferentToLaterPointInTimeSeries(currentPoint, chartData.baseline);
393         var diffFromTarget = this._relativeDifferentToLaterPointInTimeSeries(currentPoint, chartData.target);
394
395         var label = '';
396         var className = '';
397         var formatter = d3.format('.3p');
398
399         var smallerIsBetter = chartData.smallerIsBetter;
400         if (diffFromBaseline !== undefined && diffFromBaseline > 0 == smallerIsBetter) {
401             label = formatter(Math.abs(diffFromBaseline)) + ' ' + (smallerIsBetter ? 'above' : 'below') + ' baseline';
402             className = 'worse';
403         } else if (diffFromTarget !== undefined && diffFromTarget < 0 == smallerIsBetter) {
404             label = formatter(Math.abs(diffFromTarget)) + ' ' + (smallerIsBetter ? 'below' : 'above') + ' target';
405             className = 'better';
406         } else if (diffFromTarget !== undefined)
407             label = formatter(Math.abs(diffFromTarget)) + ' until target';
408
409         var valueDelta = previousPoint ? chartData.deltaFormatter(currentPoint.value - previousPoint.value) : null;
410         return {className: className, label: label, currentValue: chartData.formatter(currentPoint.value), valueDelta: valueDelta};
411     },
412     _relativeDifferentToLaterPointInTimeSeries: function (currentPoint, timeSeries)
413     {
414         if (!currentPoint || !timeSeries)
415             return undefined;
416
417         var referencePoint = timeSeries.findPointAfterTime(currentPoint.time);
418         if (!referencePoint)
419             return undefined;
420
421         return (currentPoint.value - referencePoint.value) / referencePoint.value;
422     },
423     latestStatus: function ()
424     {
425         var chartData = this.get('chartData');
426         if (!chartData || !chartData.current)
427             return null;
428
429         var lastPoint = chartData.current.lastPoint();
430         if (!lastPoint)
431             return null;
432
433         return this.computeStatus(lastPoint, chartData.current.previousPoint(lastPoint));
434     }.property('chartData'),
435     updateStatisticsTools: function ()
436     {
437         var movingAverageStrategies = Statistics.MovingAverageStrategies.map(this._cloneStrategy.bind(this));
438         this.set('movingAverageStrategies', [{label: 'None'}].concat(movingAverageStrategies));
439         this.set('chosenMovingAverageStrategy', this._configureStrategy(movingAverageStrategies, this.get('movingAverageConfig')));
440
441         var envelopingStrategies = Statistics.EnvelopingStrategies.map(this._cloneStrategy.bind(this));
442         this.set('envelopingStrategies', [{label: 'None'}].concat(envelopingStrategies));
443         this.set('chosenEnvelopingStrategy', this._configureStrategy(envelopingStrategies, this.get('envelopingConfig')));
444     }.on('init'),
445     _cloneStrategy: function (strategy)
446     {
447         var parameterList = (strategy.parameterList || []).map(function (param) { return Ember.Object.create(param); });
448         return Ember.Object.create({
449             id: strategy.id,
450             label: strategy.label,
451             description: strategy.description,
452             parameterList: parameterList,
453             execute: strategy.execute,
454         });
455     },
456     _configureStrategy: function (strategies, config)
457     {
458         if (!config || !config[0])
459             return null;
460
461         var id = config[0];
462         var chosenStrategy = strategies.find(function (strategy) { return strategy.id == id });
463         if (!chosenStrategy)
464             return null;
465
466         for (var i = 0; i < chosenStrategy.parameters.length; i++)
467             chosenStrategy.parameters[i] = parseFloat(config[i + 1]);
468
469         return chosenStrategy;
470     },
471     _computeChartData: function ()
472     {
473         if (!this.get('fetchedData'))
474             return;
475
476         var chartData = App.createChartData(this.get('fetchedData'));
477         chartData.movingAverage = this._computeMovingAverage(chartData);
478
479         this._updateStrategyConfigIfNeeded(this.get('chosenMovingAverageStrategy'), 'movingAverageConfig');
480         this._updateStrategyConfigIfNeeded(this.get('chosenEnvelopingStrategy'), 'envelopingConfig');
481
482         this.set('chartData', chartData);
483     }.observes('chosenMovingAverageStrategy', 'chosenMovingAverageStrategy.parameterList.@each.value',
484         'chosenEnvelopingStrategy', 'chosenEnvelopingStrategy.parameterList.@each.value'),
485     _computeMovingAverage: function (chartData)
486     {
487         var currentTimeSeriesData = chartData.current.series();
488         var movingAverageStrategy = this.get('chosenMovingAverageStrategy');
489         if (!movingAverageStrategy || !movingAverageStrategy.execute)
490             return null;
491
492         var movingAverageValues = this._executeStrategy(movingAverageStrategy, currentTimeSeriesData);
493         if (!movingAverageValues)
494             return null;
495
496         var envelopeDelta = null;
497         var envelopingStrategy = this.get('chosenEnvelopingStrategy');
498         if (envelopingStrategy && envelopingStrategy.execute)
499             envelopeDelta = this._executeStrategy(envelopingStrategy, currentTimeSeriesData, [movingAverageValues]);
500         
501         return new TimeSeries(currentTimeSeriesData.map(function (point, index) {
502             var value = movingAverageValues[index];
503             return {
504                 measurement: point.measurement,
505                 time: point.time,
506                 value: value,
507                 interval: envelopeDelta !== null ? [value - envelopeDelta, value + envelopeDelta] : null,
508             }
509         }));
510     },
511     _executeStrategy: function (strategy, currentTimeSeriesData, additionalArguments)
512     {
513         var parameters = (strategy.parameterList || []).map(function (param) {
514             var parsed = parseFloat(param.value);
515             return Math.min(param.max || Infinity, Math.max(param.min || -Infinity, isNaN(parsed) ? 0 : parsed));
516         });
517         parameters.push(currentTimeSeriesData.map(function (point) { return point.value }));
518         return strategy.execute.apply(window, parameters.concat(additionalArguments));
519     },
520     _updateStrategyConfigIfNeeded: function (strategy, configName)
521     {
522         var config = null;
523         if (strategy && strategy.execute)
524             config = [strategy.id].concat((strategy.parameterList || []).map(function (param) { return param.value; }));
525
526         if (JSON.stringify(config) != JSON.stringify(this.get(configName)))
527             this.set(configName, config);
528     },
529 });
530
531 App.createChartData = function (data)
532 {
533     var runs = data.runs;
534     return {
535         current: runs.current.timeSeriesByCommitTime(),
536         baseline: runs.baseline ? runs.baseline.timeSeriesByCommitTime() : null,
537         target: runs.target ? runs.target.timeSeriesByCommitTime() : null,
538         unit: data.unit,
539         formatter: data.useSI ? d3.format('.4s') : d3.format('.4g'),
540         deltaFormatter: data.useSI ? d3.format('+.2s') : d3.format('+.2g'),
541         smallerIsBetter: data.smallerIsBetter,
542     };
543 }
544
545 App.encodePrettifiedJSON = function (plain)
546 {
547     function numberIfPossible(string) {
548         return string == parseInt(string) ? parseInt(string) : string;
549     }
550
551     function recursivelyConvertNumberIfPossible(input) {
552         if (input instanceof Array) {
553             return input.map(recursivelyConvertNumberIfPossible);
554         }
555         return numberIfPossible(input);
556     }
557
558     return JSON.stringify(recursivelyConvertNumberIfPossible(plain))
559         .replace(/\[/g, '(').replace(/\]/g, ')').replace(/\,/g, '-');
560 }
561
562 App.decodePrettifiedJSON = function (encoded)
563 {
564     var parsed = encoded.replace(/\(/g, '[').replace(/\)/g, ']').replace(/\-/g, ',');
565     try {
566         return JSON.parse(parsed);
567     } catch (exception) {
568         return null;
569     }
570 }
571
572 App.ChartsController = Ember.Controller.extend({
573     queryParams: ['paneList', 'zoom', 'since'],
574     needs: ['pane'],
575     _currentEncodedPaneList: null,
576     panes: [],
577     platforms: null,
578     sharedZoom: null,
579     startTime: null,
580     present: Date.now(),
581     defaultSince: Date.now() - 7 * 24 * 3600 * 1000,
582
583     addPane: function (pane)
584     {
585         this.panes.unshiftObject(pane);
586     },
587
588     removePane: function (pane)
589     {
590         this.panes.removeObject(pane);
591     },
592
593     refreshPanes: function()
594     {
595         var paneList = this.get('paneList');
596         if (paneList === this._currentEncodedPaneList)
597             return;
598
599         var panes = this._parsePaneList(paneList || '[]');
600         if (!panes) {
601             console.log('Failed to parse', jsonPaneList, exception);
602             return;
603         }
604         this.set('panes', panes);
605         this._currentEncodedPaneList = paneList;
606     }.observes('paneList').on('init'),
607
608     refreshZoom: function()
609     {
610         var zoom = this.get('zoom');
611         if (!zoom) {
612             this.set('sharedZoom', null);
613             return;
614         }
615
616         zoom = zoom.split('-');
617         var selection = new Array(2);
618         try {
619             selection[0] = new Date(parseFloat(zoom[0]));
620             selection[1] = new Date(parseFloat(zoom[1]));
621         } catch (error) {
622             console.log('Failed to parse the zoom', zoom);
623         }
624         this.set('sharedZoom', selection);
625
626         var startTime = this.get('startTime');
627         if (startTime && startTime > selection[0])
628             this.set('startTime', selection[0]);
629
630     }.observes('zoom').on('init'),
631
632     _startTimeChanged: function () {
633         this.set('sharedDomain', [this.get('startTime'), this.get('present')]);
634         this._scheduleQueryStringUpdate();
635     }.observes('startTime'),
636
637     _sinceChanged: function () {
638         var since = parseInt(this.get('since'));
639         if (isNaN(since))
640             since = this.defaultSince;
641         this.set('startTime', new Date(since));
642     }.observes('since').on('init'),
643
644     _parsePaneList: function (encodedPaneList)
645     {
646         var parsedPaneList = App.decodePrettifiedJSON(encodedPaneList);
647         if (!parsedPaneList)
648             return null;
649
650         // FIXME: Don't re-create all panes.
651         var self = this;
652         return parsedPaneList.map(function (paneInfo) {
653             var timeRange = null;
654             var selectedItem = null;
655             if (paneInfo[2] instanceof Array) {
656                 var timeRange = paneInfo[2];
657                 try {
658                     timeRange = [new Date(timeRange[0]), new Date(timeRange[1])];
659                 } catch (error) {
660                     console.log("Failed to parse the time range:", timeRange, error);
661                 }
662             } else
663                 selectedItem = paneInfo[2];
664
665             return App.Pane.create({
666                 store: self.store,
667                 info: paneInfo,
668                 platformId: paneInfo[0],
669                 metricId: paneInfo[1],
670                 selectedItem: selectedItem,
671                 timeRange: timeRange,
672                 movingAverageConfig: paneInfo[3],
673                 envelopingConfig: paneInfo[4],
674             });
675         });
676     },
677
678     _serializePaneList: function (panes)
679     {
680         if (!panes.length)
681             return undefined;
682         var self = this;
683         return App.encodePrettifiedJSON(panes.map(function (pane) {
684             return [
685                 pane.get('platformId'),
686                 pane.get('metricId'),
687                 pane.get('timeRange') ? pane.get('timeRange').map(function (date) { return date.getTime() }) : pane.get('selectedItem'),
688                 pane.get('movingAverageConfig'),
689                 pane.get('envelopingConfig'),
690             ];
691         }));
692     },
693
694     _scheduleQueryStringUpdate: function ()
695     {
696         Ember.run.debounce(this, '_updateQueryString', 1000);
697     }.observes('sharedZoom', 'panes.@each.platform', 'panes.@each.metric', 'panes.@each.selectedItem', 'panes.@each.timeRange',
698         'panes.@each.movingAverageConfig', 'panes.@each.envelopingConfig'),
699
700     _updateQueryString: function ()
701     {
702         this._currentEncodedPaneList = this._serializePaneList(this.get('panes'));
703         this.set('paneList', this._currentEncodedPaneList);
704
705         var zoom = undefined;
706         var sharedZoom = this.get('sharedZoom');
707         if (sharedZoom && !App.domainsAreEqual(sharedZoom, this.get('sharedDomain')))
708             zoom = +sharedZoom[0] + '-' + +sharedZoom[1];
709         this.set('zoom', zoom);
710
711         if (this.get('startTime') - this.defaultSince)
712             this.set('since', this.get('startTime') - 0);
713     },
714
715     actions: {
716         addPaneByMetricAndPlatform: function (param)
717         {
718             this.addPane(App.Pane.create({
719                 store: this.store,
720                 platformId: param.platform.get('id'),
721                 metricId: param.metric.get('id'),
722                 showingDetails: false
723             }));
724         },
725     },
726
727     init: function ()
728     {
729         this._super();
730         var self = this;
731         App.buildPopup(this.store, 'addPaneByMetricAndPlatform').then(function (platforms) {
732             self.set('platforms', platforms);
733         });
734     },
735 });
736
737 App.buildPopup = function(store, action, position)
738 {
739     return App.Manifest.fetch(store).then(function () {
740         return App.Manifest.get('platforms').map(function (platform) {
741             return App.PlatformProxyForPopup.create({content: platform,
742                 action: action, position: position});
743         });
744     });
745 }
746
747 App.PlatformProxyForPopup = Ember.ObjectProxy.extend({
748     children: function ()
749     {
750         var platform = this.content;
751         var containsTest = this.content.containsTest.bind(this.content);
752         var action = this.get('action');
753         var position = this.get('position');
754         return App.Manifest.get('topLevelTests')
755             .filter(containsTest)
756             .map(function (test) {
757                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
758             });
759     }.property('App.Manifest.topLevelTests'),
760 });
761
762 App.TestProxyForPopup = Ember.ObjectProxy.extend({
763     platform: null,
764     children: function ()
765     {
766         var platform = this.get('platform');
767         var action = this.get('action');
768         var position = this.get('position');
769
770         var childTests = this.get('childTests')
771             .filter(function (test) { return platform.containsTest(test); })
772             .map(function (test) {
773                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
774             });
775
776         var metrics = this.get('metrics')
777             .filter(function (metric) { return platform.containsMetric(metric); })
778             .map(function (metric) {
779                 var aggregator = metric.get('aggregator');
780                 return {
781                     actionName: action,
782                     actionArgument: {platform: platform, metric: metric, position:position},
783                     label: metric.get('label')
784                 };
785             });
786
787         if (childTests.length && metrics.length)
788             metrics.push({isSeparator: true});
789
790         return metrics.concat(childTests);
791     }.property('childTests', 'metrics'),
792 });
793
794 App.domainsAreEqual = function (domain1, domain2) {
795     return (!domain1 && !domain2) || (domain1 && domain2 && !(domain1[0] - domain2[0]) && !(domain1[1] - domain2[1]));
796 }
797
798 App.PaneController = Ember.ObjectController.extend({
799     needs: ['charts'],
800     sharedTime: Ember.computed.alias('parentController.sharedTime'),
801     sharedSelection: Ember.computed.alias('parentController.sharedSelection'),
802     selection: null,
803     actions: {
804         toggleDetails: function()
805         {
806             this.toggleProperty('showingDetails');
807         },
808         close: function ()
809         {
810             this.parentController.removePane(this.get('model'));
811         },
812         toggleBugsPane: function ()
813         {
814             if (this.toggleProperty('showingAnalysisPane')) {
815                 this.set('showingSearchPane', false);
816                 this.set('showingStatPane', false);
817             }
818         },
819         createAnalysisTask: function ()
820         {
821             var name = this.get('newAnalysisTaskName');
822             var points = this.get('selectedPoints');
823             Ember.assert('The analysis name should not be empty', name);
824             Ember.assert('There should be at least two points in the range', points && points.length >= 2);
825
826             var newWindow = window.open();
827             var self = this;
828             App.AnalysisTask.create(name, points[0].measurement, points[points.length - 1].measurement).then(function (data) {
829                 // FIXME: Update the UI to show the new analysis task.
830                 var url = App.Router.router.generate('analysisTask', data['taskId']);
831                 newWindow.location.href = '#' + url;
832                 self.get('model').fetchAnalyticRanges();
833             }, function (error) {
834                 newWindow.close();
835                 if (error === 'DuplicateAnalysisTask') {
836                     // FIXME: Duplicate this error more gracefully.
837                 }
838                 alert(error);
839             });
840         },
841         toggleSearchPane: function ()
842         {
843             if (!App.Manifest.repositoriesWithReportedCommits)
844                 return;
845             var model = this.get('model');
846             if (!model.get('commitSearchRepository'))
847                 model.set('commitSearchRepository', App.Manifest.repositoriesWithReportedCommits[0]);
848             if (this.toggleProperty('showingSearchPane')) {
849                 this.set('showingAnalysisPane', false);
850                 this.set('showingStatPane', false);
851             }
852         },
853         searchCommit: function () {
854             var model = this.get('model');
855             model.searchCommit(model.get('commitSearchRepository'), model.get('commitSearchKeyword'));                
856         },
857         toggleStatPane: function ()
858         {
859             if (this.toggleProperty('showingStatPane')) {
860                 this.set('showingSearchPane', false);
861                 this.set('showingAnalysisPane', false);
862             }
863         },
864         zoomed: function (selection)
865         {
866             this.set('mainPlotDomain', selection ? selection : this.get('overviewDomain'));
867             Ember.run.debounce(this, 'propagateZoom', 100);
868         },
869     },
870     _detailsChanged: function ()
871     {
872         this.set('showingAnalysisPane', false);
873     }.observes('details'),
874     _overviewSelectionChanged: function ()
875     {
876         var overviewSelection = this.get('overviewSelection');
877         if (App.domainsAreEqual(overviewSelection, this.get('mainPlotDomain')))
878             return;
879         this.set('mainPlotDomain', overviewSelection || this.get('overviewDomain'));
880         Ember.run.debounce(this, 'propagateZoom', 100);
881     }.observes('overviewSelection'),
882     _sharedDomainChanged: function ()
883     {
884         var newDomain = this.get('parentController').get('sharedDomain');
885         if (App.domainsAreEqual(newDomain, this.get('overviewDomain')))
886             return;
887         this.set('overviewDomain', newDomain);
888         if (!this.get('overviewSelection'))
889             this.set('mainPlotDomain', newDomain);
890     }.observes('parentController.sharedDomain').on('init'),
891     propagateZoom: function ()
892     {
893         this.get('parentController').set('sharedZoom', this.get('mainPlotDomain'));
894     },
895     _sharedZoomChanged: function ()
896     {
897         var newSelection = this.get('parentController').get('sharedZoom');
898         if (App.domainsAreEqual(newSelection, this.get('mainPlotDomain')))
899             return;
900         this.set('mainPlotDomain', newSelection || this.get('overviewDomain'));
901         this.set('overviewSelection', newSelection);
902     }.observes('parentController.sharedZoom').on('init'),
903     _updateDetails: function ()
904     {
905         var selectedPoints = this.get('selectedPoints');
906         var currentPoint = this.get('currentItem');
907         if (!selectedPoints && !currentPoint) {
908             this.set('details', null);
909             return;
910         }
911
912         var currentMeasurement;
913         var previousPoint;
914         if (!selectedPoints)
915             previousPoint = currentPoint.series.previousPoint(currentPoint);
916         else {
917             currentPoint = selectedPoints[selectedPoints.length - 1];
918             previousPoint = selectedPoints[0];
919         }
920         var currentMeasurement = currentPoint.measurement;
921         var oldMeasurement = previousPoint ? previousPoint.measurement : null;
922
923         var formattedRevisions = currentMeasurement.formattedRevisions(oldMeasurement);
924         var revisions = App.Manifest.get('repositories')
925             .filter(function (repository) { return formattedRevisions[repository.get('id')]; })
926             .map(function (repository) {
927             var revision = Ember.Object.create(formattedRevisions[repository.get('id')]);
928             revision['url'] = revision.previousRevision
929                 ? repository.urlForRevisionRange(revision.previousRevision, revision.currentRevision)
930                 : repository.urlForRevision(revision.currentRevision);
931             revision['name'] = repository.get('name');
932             revision['repository'] = repository;
933             return revision; 
934         });
935
936         var buildNumber = null;
937         var buildURL = null;
938         if (!selectedPoints) {
939             buildNumber = currentMeasurement.buildNumber();
940             var builder = App.Manifest.builder(currentMeasurement.builderId());
941             if (builder)
942                 buildURL = builder.urlFromBuildNumber(buildNumber);
943         }
944
945         this.set('details', Ember.Object.create({
946             status: this.get('model').computeStatus(currentPoint, previousPoint),
947             buildNumber: buildNumber,
948             buildURL: buildURL,
949             buildTime: currentMeasurement.formattedBuildTime(),
950             revisions: revisions,
951         }));
952         this._updateCanAnalyze();
953     }.observes('currentItem', 'selectedPoints'),
954     _updateCanAnalyze: function ()
955     {
956         var points = this.get('selectedPoints');
957         this.set('cannotAnalyze', !this.get('newAnalysisTaskName') || !points || points.length < 2);
958     }.observes('newAnalysisTaskName'),
959 });
960
961
962 App.AnalysisRoute = Ember.Route.extend({
963     model: function () {
964         return this.store.findAll('analysisTask').then(function (tasks) {
965             return Ember.Object.create({'tasks': tasks});
966         });
967     },
968 });
969
970 App.AnalysisTaskRoute = Ember.Route.extend({
971     model: function (param)
972     {
973         return this.store.find('analysisTask', param.taskId);
974     },
975 });
976
977 App.AnalysisTaskController = Ember.Controller.extend({
978     label: Ember.computed.alias('model.name'),
979     platform: Ember.computed.alias('model.platform'),
980     metric: Ember.computed.alias('model.metric'),
981     testGroups: Ember.computed.alias('model.testGroups'),
982     testSets: [],
983     roots: [],
984     bugTrackers: [],
985     possibleRepetitionCounts: [1, 2, 3, 4, 5, 6],
986     _taskUpdated: function ()
987     {
988         var model = this.get('model');
989         if (!model)
990             return;
991
992         var platformId = model.get('platform').get('id');
993         var metricId = model.get('metric').get('id');
994         App.Manifest.fetch(this.store).then(this._fetchedManifest.bind(this));
995         App.Manifest.fetchRunsWithPlatformAndMetric(this.store, platformId, metricId).then(this._fetchedRuns.bind(this));
996     }.observes('model').on('init'),
997     _fetchedManifest: function ()
998     {
999         var trackerIdToBugNumber = {};
1000         this.get('model').get('bugs').forEach(function (bug) {
1001             trackerIdToBugNumber[bug.get('bugTracker').get('id')] = bug.get('number');
1002         });
1003
1004         this.set('bugTrackers', App.Manifest.get('bugTrackers').map(function (bugTracker) {
1005             var bugNumber = trackerIdToBugNumber[bugTracker.get('id')];
1006             return Ember.ObjectProxy.create({
1007                 content: bugTracker,
1008                 bugNumber: bugNumber,
1009                 editedBugNumber: bugNumber,
1010             });
1011         }));
1012     },
1013     _fetchedRuns: function (data)
1014     {
1015         var runs = data.runs;
1016
1017         var currentTimeSeries = runs.current.timeSeriesByCommitTime();
1018         if (!currentTimeSeries)
1019             return; // FIXME: Report an error.
1020
1021         var start = currentTimeSeries.findPointByMeasurementId(this.get('model').get('startRun'));
1022         var end = currentTimeSeries.findPointByMeasurementId(this.get('model').get('endRun'));
1023         if (!start || !end)
1024             return; // FIXME: Report an error.
1025
1026         var highlightedItems = {};
1027         highlightedItems[start.measurement.id()] = true;
1028         highlightedItems[end.measurement.id()] = true;
1029
1030         var chartData = App.createChartData(data);
1031         var formatedPoints = currentTimeSeries.seriesBetweenPoints(start, end).map(function (point, index) {
1032             return {
1033                 id: point.measurement.id(),
1034                 measurement: point.measurement,
1035                 label: 'Point ' + (index + 1),
1036                 value: chartData.formatter(point.value) + (data.unit ? ' ' + data.unit : ''),
1037             };
1038         });
1039
1040         var margin = (end.time - start.time) * 0.1;
1041         this.set('chartData', chartData);
1042         this.set('chartDomain', [start.time - margin, +end.time + margin]);
1043         this.set('highlightedItems', highlightedItems);
1044         this.set('analysisPoints', formatedPoints);
1045     },
1046     testSets: function ()
1047     {
1048         var analysisPoints = this.get('analysisPoints');
1049         if (!analysisPoints)
1050             return;
1051         var pointOptions = [{value: ' ', label: 'None'}]
1052             .concat(analysisPoints.map(function (point) { return {value: point.id, label: point.label}; }));
1053         return [
1054             Ember.Object.create({name: "A", options: pointOptions, selection: pointOptions[1]}),
1055             Ember.Object.create({name: "B", options: pointOptions, selection: pointOptions[pointOptions.length - 1]}),
1056         ];
1057     }.property('analysisPoints'),
1058     _rootChangedForTestSet: function ()
1059     {
1060         var sets = this.get('testSets');
1061         var roots = this.get('roots');
1062         if (!sets || !roots)
1063             return;
1064
1065         sets.forEach(function (testSet, setIndex) {
1066             var currentSelection = testSet.get('selection');
1067             if (currentSelection == testSet.get('previousSelection'))
1068                 return;
1069             testSet.set('previousSelection', currentSelection);
1070             var pointIndex = testSet.get('options').indexOf(currentSelection);
1071
1072             roots.forEach(function (root) {
1073                 var set = root.sets[setIndex];
1074                 set.set('selection', set.revisions[pointIndex]);
1075             });
1076         });
1077
1078     }.observes('testSets.@each.selection'),
1079     updateRoots: function ()
1080     {
1081         var analysisPoints = this.get('analysisPoints');
1082         if (!analysisPoints)
1083             return;
1084         var repositoryToRevisions = {};
1085         analysisPoints.forEach(function (point, pointIndex) {
1086             var revisions = point.measurement.formattedRevisions();
1087             for (var repositoryId in revisions) {
1088                 if (!repositoryToRevisions[repositoryId])
1089                     repositoryToRevisions[repositoryId] = new Array(analysisPoints.length);
1090                 var revision = revisions[repositoryId];
1091                 repositoryToRevisions[repositoryId][pointIndex] = {
1092                     label: point.label + ': ' + revision.label,
1093                     value: revision.currentRevision,
1094                 };
1095             }
1096         });
1097
1098         var self = this;
1099         this.get('model').get('triggerable').then(function (triggerable) {
1100             if (!triggerable)
1101                 return;
1102
1103             self.set('roots', triggerable.get('acceptedRepositories').map(function (repository) {
1104                 var repositoryId = repository.get('id');
1105                 var revisions = [{value: ' ', label: 'None'}].concat(repositoryToRevisions[repositoryId]);
1106                 return Ember.Object.create({
1107                     name: repository.get('name'),
1108                     sets: [
1109                         Ember.Object.create({name: 'A[' + repositoryId + ']',
1110                             revisions: revisions,
1111                             selection: revisions[1]}),
1112                         Ember.Object.create({name: 'B[' + repositoryId + ']',
1113                             revisions: revisions,
1114                             selection: revisions[revisions.length - 1]}),
1115                     ],
1116                 });
1117             }));
1118         });
1119     }.observes('analysisPoints'),
1120     actions: {
1121         associateBug: function (bugTracker, bugNumber)
1122         {
1123             var model = this.get('model');
1124             this.store.createRecord('bug',
1125                 {task: this.get('model'), bugTracker: bugTracker.get('content'), number: bugNumber}).save().then(function () {
1126                     // FIXME: Should we notify the user?
1127                 }, function (error) {
1128                     alert('Failed to associate the bug: ' + error);
1129                 });
1130         },
1131         createTestGroup: function (name, repetitionCount)
1132         {
1133             var roots = {};
1134             this.get('roots').map(function (root) {
1135                 roots[root.get('name')] = root.get('sets').map(function (item) { return item.get('selection').value; });
1136             });
1137             App.TestGroup.create(this.get('model'), name, roots, repetitionCount).then(function () {
1138                 
1139             });
1140         },
1141     },
1142 });