f80e5e4a0ffdbccd6447241e01e4b9081d5c8c5d
[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         if (!movingAverageStrategy || !movingAverageStrategy.execute) {
488             movingAverageStrategy = Statistics.MovingAverageStrategies[0];
489             chartData.hideMovingAverage = true;
490         }
491         if (!envelopingStrategy || !envelopingStrategy.execute) {
492             envelopingStrategy = Statistics.EnvelopingStrategies[0];
493             chartData.hideEnvelope = true;
494         }
495
496         chartData.movingAverage = this._computeMovingAverage(chartData, movingAverageStrategy, envelopingStrategy);
497
498         this.set('chartData', chartData);
499     }.observes('chosenMovingAverageStrategy', 'chosenMovingAverageStrategy.parameterList.@each.value',
500         'chosenEnvelopingStrategy', 'chosenEnvelopingStrategy.parameterList.@each.value'),
501     _computeMovingAverage: function (chartData, movingAverageStrategy, envelopingStrategy)
502     {
503         var currentTimeSeriesData = chartData.current.series();
504         var movingAverageValues = this._executeStrategy(movingAverageStrategy, currentTimeSeriesData);
505         if (!movingAverageValues)
506             return null;
507
508         var envelopeDelta = this._executeStrategy(envelopingStrategy, currentTimeSeriesData, [movingAverageValues]);
509
510         return new TimeSeries(currentTimeSeriesData.map(function (point, index) {
511             var value = movingAverageValues[index];
512             return {
513                 measurement: point.measurement,
514                 time: point.time,
515                 value: value,
516                 interval: envelopeDelta !== null ? [value - envelopeDelta, value + envelopeDelta] : null,
517             }
518         }));
519     },
520     _executeStrategy: function (strategy, currentTimeSeriesData, additionalArguments)
521     {
522         var parameters = (strategy.parameterList || []).map(function (param) {
523             var parsed = parseFloat(param.value);
524             return Math.min(param.max || Infinity, Math.max(param.min || -Infinity, isNaN(parsed) ? 0 : parsed));
525         });
526         parameters.push(currentTimeSeriesData.map(function (point) { return point.value }));
527         return strategy.execute.apply(window, parameters.concat(additionalArguments));
528     },
529     _updateStrategyConfigIfNeeded: function (strategy, configName)
530     {
531         var config = null;
532         if (strategy && strategy.execute)
533             config = [strategy.id].concat((strategy.parameterList || []).map(function (param) { return param.value; }));
534
535         if (JSON.stringify(config) != JSON.stringify(this.get(configName)))
536             this.set(configName, config);
537     },
538 });
539
540 App.createChartData = function (data)
541 {
542     var runs = data.runs;
543     return {
544         current: runs.current.timeSeriesByCommitTime(),
545         baseline: runs.baseline ? runs.baseline.timeSeriesByCommitTime() : null,
546         target: runs.target ? runs.target.timeSeriesByCommitTime() : null,
547         unit: data.unit,
548         formatter: data.useSI ? d3.format('.4s') : d3.format('.4g'),
549         deltaFormatter: data.useSI ? d3.format('+.2s') : d3.format('+.2g'),
550         smallerIsBetter: data.smallerIsBetter,
551     };
552 }
553
554 App.encodePrettifiedJSON = function (plain)
555 {
556     function numberIfPossible(string) {
557         return string == parseInt(string) ? parseInt(string) : string;
558     }
559
560     function recursivelyConvertNumberIfPossible(input) {
561         if (input instanceof Array) {
562             return input.map(recursivelyConvertNumberIfPossible);
563         }
564         return numberIfPossible(input);
565     }
566
567     return JSON.stringify(recursivelyConvertNumberIfPossible(plain))
568         .replace(/\[/g, '(').replace(/\]/g, ')').replace(/\,/g, '-');
569 }
570
571 App.decodePrettifiedJSON = function (encoded)
572 {
573     var parsed = encoded.replace(/\(/g, '[').replace(/\)/g, ']').replace(/\-/g, ',');
574     try {
575         return JSON.parse(parsed);
576     } catch (exception) {
577         return null;
578     }
579 }
580
581 App.ChartsController = Ember.Controller.extend({
582     queryParams: ['paneList', 'zoom', 'since'],
583     needs: ['pane'],
584     _currentEncodedPaneList: null,
585     panes: [],
586     platforms: null,
587     sharedZoom: null,
588     startTime: null,
589     present: Date.now(),
590     defaultSince: Date.now() - 7 * 24 * 3600 * 1000,
591
592     addPane: function (pane)
593     {
594         this.panes.unshiftObject(pane);
595     },
596
597     removePane: function (pane)
598     {
599         this.panes.removeObject(pane);
600     },
601
602     refreshPanes: function()
603     {
604         var paneList = this.get('paneList');
605         if (paneList === this._currentEncodedPaneList)
606             return;
607
608         var panes = this._parsePaneList(paneList || '[]');
609         if (!panes) {
610             console.log('Failed to parse', jsonPaneList, exception);
611             return;
612         }
613         this.set('panes', panes);
614         this._currentEncodedPaneList = paneList;
615     }.observes('paneList').on('init'),
616
617     refreshZoom: function()
618     {
619         var zoom = this.get('zoom');
620         if (!zoom) {
621             this.set('sharedZoom', null);
622             return;
623         }
624
625         zoom = zoom.split('-');
626         var selection = new Array(2);
627         try {
628             selection[0] = new Date(parseFloat(zoom[0]));
629             selection[1] = new Date(parseFloat(zoom[1]));
630         } catch (error) {
631             console.log('Failed to parse the zoom', zoom);
632         }
633         this.set('sharedZoom', selection);
634
635         var startTime = this.get('startTime');
636         if (startTime && startTime > selection[0])
637             this.set('startTime', selection[0]);
638
639     }.observes('zoom').on('init'),
640
641     _startTimeChanged: function () {
642         this.set('sharedDomain', [this.get('startTime'), this.get('present')]);
643         this._scheduleQueryStringUpdate();
644     }.observes('startTime'),
645
646     _sinceChanged: function () {
647         var since = parseInt(this.get('since'));
648         if (isNaN(since))
649             since = this.defaultSince;
650         this.set('startTime', new Date(since));
651     }.observes('since').on('init'),
652
653     _parsePaneList: function (encodedPaneList)
654     {
655         var parsedPaneList = App.decodePrettifiedJSON(encodedPaneList);
656         if (!parsedPaneList)
657             return null;
658
659         // FIXME: Don't re-create all panes.
660         var self = this;
661         return parsedPaneList.map(function (paneInfo) {
662             var timeRange = null;
663             var selectedItem = null;
664             if (paneInfo[2] instanceof Array) {
665                 var timeRange = paneInfo[2];
666                 try {
667                     timeRange = [new Date(timeRange[0]), new Date(timeRange[1])];
668                 } catch (error) {
669                     console.log("Failed to parse the time range:", timeRange, error);
670                 }
671             } else
672                 selectedItem = paneInfo[2];
673
674             return App.Pane.create({
675                 store: self.store,
676                 info: paneInfo,
677                 platformId: paneInfo[0],
678                 metricId: paneInfo[1],
679                 selectedItem: selectedItem,
680                 timeRange: timeRange,
681                 showFullYAxis: paneInfo[3],
682                 movingAverageConfig: paneInfo[4],
683                 envelopingConfig: paneInfo[5],
684             });
685         });
686     },
687
688     _serializePaneList: function (panes)
689     {
690         if (!panes.length)
691             return undefined;
692         var self = this;
693         return App.encodePrettifiedJSON(panes.map(function (pane) {
694             return [
695                 pane.get('platformId'),
696                 pane.get('metricId'),
697                 pane.get('timeRange') ? pane.get('timeRange').map(function (date) { return date.getTime() }) : pane.get('selectedItem'),
698                 pane.get('showFullYAxis'),
699                 pane.get('movingAverageConfig'),
700                 pane.get('envelopingConfig'),
701             ];
702         }));
703     },
704
705     _scheduleQueryStringUpdate: function ()
706     {
707         Ember.run.debounce(this, '_updateQueryString', 1000);
708     }.observes('sharedZoom', 'panes.@each.platform', 'panes.@each.metric', 'panes.@each.selectedItem', 'panes.@each.timeRange',
709         'panes.@each.showFullYAxis', 'panes.@each.movingAverageConfig', 'panes.@each.envelopingConfig'),
710
711     _updateQueryString: function ()
712     {
713         this._currentEncodedPaneList = this._serializePaneList(this.get('panes'));
714         this.set('paneList', this._currentEncodedPaneList);
715
716         var zoom = undefined;
717         var sharedZoom = this.get('sharedZoom');
718         if (sharedZoom && !App.domainsAreEqual(sharedZoom, this.get('sharedDomain')))
719             zoom = +sharedZoom[0] + '-' + +sharedZoom[1];
720         this.set('zoom', zoom);
721
722         if (this.get('startTime') - this.defaultSince)
723             this.set('since', this.get('startTime') - 0);
724     },
725
726     actions: {
727         addPaneByMetricAndPlatform: function (param)
728         {
729             this.addPane(App.Pane.create({
730                 store: this.store,
731                 platformId: param.platform.get('id'),
732                 metricId: param.metric.get('id'),
733                 showingDetails: false
734             }));
735         },
736     },
737
738     init: function ()
739     {
740         this._super();
741         var self = this;
742         App.buildPopup(this.store, 'addPaneByMetricAndPlatform').then(function (platforms) {
743             self.set('platforms', platforms);
744         });
745     },
746 });
747
748 App.buildPopup = function(store, action, position)
749 {
750     return App.Manifest.fetch(store).then(function () {
751         return App.Manifest.get('platforms').map(function (platform) {
752             return App.PlatformProxyForPopup.create({content: platform,
753                 action: action, position: position});
754         });
755     });
756 }
757
758 App.PlatformProxyForPopup = Ember.ObjectProxy.extend({
759     children: function ()
760     {
761         var platform = this.content;
762         var containsTest = this.content.containsTest.bind(this.content);
763         var action = this.get('action');
764         var position = this.get('position');
765         return App.Manifest.get('topLevelTests')
766             .filter(containsTest)
767             .map(function (test) {
768                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
769             });
770     }.property('App.Manifest.topLevelTests'),
771 });
772
773 App.TestProxyForPopup = Ember.ObjectProxy.extend({
774     platform: null,
775     children: function ()
776     {
777         var platform = this.get('platform');
778         var action = this.get('action');
779         var position = this.get('position');
780
781         var childTests = this.get('childTests')
782             .filter(function (test) { return platform.containsTest(test); })
783             .map(function (test) {
784                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
785             });
786
787         var metrics = this.get('metrics')
788             .filter(function (metric) { return platform.containsMetric(metric); })
789             .map(function (metric) {
790                 var aggregator = metric.get('aggregator');
791                 return {
792                     actionName: action,
793                     actionArgument: {platform: platform, metric: metric, position:position},
794                     label: metric.get('label')
795                 };
796             });
797
798         if (childTests.length && metrics.length)
799             metrics.push({isSeparator: true});
800
801         return metrics.concat(childTests);
802     }.property('childTests', 'metrics'),
803 });
804
805 App.domainsAreEqual = function (domain1, domain2) {
806     return (!domain1 && !domain2) || (domain1 && domain2 && !(domain1[0] - domain2[0]) && !(domain1[1] - domain2[1]));
807 }
808
809 App.PaneController = Ember.ObjectController.extend({
810     needs: ['charts'],
811     sharedTime: Ember.computed.alias('parentController.sharedTime'),
812     sharedSelection: Ember.computed.alias('parentController.sharedSelection'),
813     selection: null,
814     actions: {
815         toggleDetails: function()
816         {
817             this.toggleProperty('showingDetails');
818         },
819         close: function ()
820         {
821             this.parentController.removePane(this.get('model'));
822         },
823         toggleBugsPane: function ()
824         {
825             if (this.toggleProperty('showingAnalysisPane')) {
826                 this.set('showingSearchPane', false);
827                 this.set('showingStatPane', false);
828             }
829         },
830         createAnalysisTask: function ()
831         {
832             var name = this.get('newAnalysisTaskName');
833             var points = this.get('selectedPoints');
834             Ember.assert('The analysis name should not be empty', name);
835             Ember.assert('There should be at least two points in the range', points && points.length >= 2);
836
837             var newWindow = window.open();
838             var self = this;
839             App.AnalysisTask.create(name, points[0].measurement, points[points.length - 1].measurement).then(function (data) {
840                 // FIXME: Update the UI to show the new analysis task.
841                 var url = App.Router.router.generate('analysisTask', data['taskId']);
842                 newWindow.location.href = '#' + url;
843                 self.get('model').fetchAnalyticRanges();
844             }, function (error) {
845                 newWindow.close();
846                 if (error === 'DuplicateAnalysisTask') {
847                     // FIXME: Duplicate this error more gracefully.
848                 }
849                 alert(error);
850             });
851         },
852         toggleSearchPane: function ()
853         {
854             if (!App.Manifest.repositoriesWithReportedCommits)
855                 return;
856             var model = this.get('model');
857             if (!model.get('commitSearchRepository'))
858                 model.set('commitSearchRepository', App.Manifest.repositoriesWithReportedCommits[0]);
859             if (this.toggleProperty('showingSearchPane')) {
860                 this.set('showingAnalysisPane', false);
861                 this.set('showingStatPane', false);
862             }
863         },
864         searchCommit: function () {
865             var model = this.get('model');
866             model.searchCommit(model.get('commitSearchRepository'), model.get('commitSearchKeyword'));                
867         },
868         toggleStatPane: function ()
869         {
870             if (this.toggleProperty('showingStatPane')) {
871                 this.set('showingSearchPane', false);
872                 this.set('showingAnalysisPane', false);
873             }
874         },
875         zoomed: function (selection)
876         {
877             this.set('mainPlotDomain', selection ? selection : this.get('overviewDomain'));
878             Ember.run.debounce(this, 'propagateZoom', 100);
879         },
880     },
881     _detailsChanged: function ()
882     {
883         this.set('showingAnalysisPane', false);
884     }.observes('details'),
885     _overviewSelectionChanged: function ()
886     {
887         var overviewSelection = this.get('overviewSelection');
888         if (App.domainsAreEqual(overviewSelection, this.get('mainPlotDomain')))
889             return;
890         this.set('mainPlotDomain', overviewSelection || this.get('overviewDomain'));
891         Ember.run.debounce(this, 'propagateZoom', 100);
892     }.observes('overviewSelection'),
893     _sharedDomainChanged: function ()
894     {
895         var newDomain = this.get('parentController').get('sharedDomain');
896         if (App.domainsAreEqual(newDomain, this.get('overviewDomain')))
897             return;
898         this.set('overviewDomain', newDomain);
899         if (!this.get('overviewSelection'))
900             this.set('mainPlotDomain', newDomain);
901     }.observes('parentController.sharedDomain').on('init'),
902     propagateZoom: function ()
903     {
904         this.get('parentController').set('sharedZoom', this.get('mainPlotDomain'));
905     },
906     _sharedZoomChanged: function ()
907     {
908         var newSelection = this.get('parentController').get('sharedZoom');
909         if (App.domainsAreEqual(newSelection, this.get('mainPlotDomain')))
910             return;
911         this.set('mainPlotDomain', newSelection || this.get('overviewDomain'));
912         this.set('overviewSelection', newSelection);
913     }.observes('parentController.sharedZoom').on('init'),
914     _updateDetails: function ()
915     {
916         var selectedPoints = this.get('selectedPoints');
917         var currentPoint = this.get('currentItem');
918         if (!selectedPoints && !currentPoint) {
919             this.set('details', null);
920             return;
921         }
922
923         var currentMeasurement;
924         var previousPoint;
925         if (!selectedPoints)
926             previousPoint = currentPoint.series.previousPoint(currentPoint);
927         else {
928             currentPoint = selectedPoints[selectedPoints.length - 1];
929             previousPoint = selectedPoints[0];
930         }
931         var currentMeasurement = currentPoint.measurement;
932         var oldMeasurement = previousPoint ? previousPoint.measurement : null;
933
934         var formattedRevisions = currentMeasurement.formattedRevisions(oldMeasurement);
935         var revisions = App.Manifest.get('repositories')
936             .filter(function (repository) { return formattedRevisions[repository.get('id')]; })
937             .map(function (repository) {
938             var revision = Ember.Object.create(formattedRevisions[repository.get('id')]);
939             revision['url'] = revision.previousRevision
940                 ? repository.urlForRevisionRange(revision.previousRevision, revision.currentRevision)
941                 : repository.urlForRevision(revision.currentRevision);
942             revision['name'] = repository.get('name');
943             revision['repository'] = repository;
944             return revision; 
945         });
946
947         var buildNumber = null;
948         var buildURL = null;
949         if (!selectedPoints) {
950             buildNumber = currentMeasurement.buildNumber();
951             var builder = App.Manifest.builder(currentMeasurement.builderId());
952             if (builder)
953                 buildURL = builder.urlFromBuildNumber(buildNumber);
954         }
955
956         this.set('details', Ember.Object.create({
957             status: this.get('model').computeStatus(currentPoint, previousPoint),
958             buildNumber: buildNumber,
959             buildURL: buildURL,
960             buildTime: currentMeasurement.formattedBuildTime(),
961             revisions: revisions,
962         }));
963         this._updateCanAnalyze();
964     }.observes('currentItem', 'selectedPoints'),
965     _updateCanAnalyze: function ()
966     {
967         var points = this.get('selectedPoints');
968         this.set('cannotAnalyze', !this.get('newAnalysisTaskName') || !points || points.length < 2);
969     }.observes('newAnalysisTaskName'),
970 });
971
972
973 App.AnalysisRoute = Ember.Route.extend({
974     model: function () {
975         return this.store.findAll('analysisTask').then(function (tasks) {
976             return Ember.Object.create({'tasks': tasks});
977         });
978     },
979 });
980
981 App.AnalysisTaskRoute = Ember.Route.extend({
982     model: function (param)
983     {
984         return this.store.find('analysisTask', param.taskId);
985     },
986 });
987
988 App.AnalysisTaskController = Ember.Controller.extend({
989     label: Ember.computed.alias('model.name'),
990     platform: Ember.computed.alias('model.platform'),
991     metric: Ember.computed.alias('model.metric'),
992     testGroups: Ember.computed.alias('model.testGroups'),
993     testSets: [],
994     roots: [],
995     bugTrackers: [],
996     possibleRepetitionCounts: [1, 2, 3, 4, 5, 6],
997     _taskUpdated: function ()
998     {
999         var model = this.get('model');
1000         if (!model)
1001             return;
1002
1003         var platformId = model.get('platform').get('id');
1004         var metricId = model.get('metric').get('id');
1005         App.Manifest.fetch(this.store).then(this._fetchedManifest.bind(this));
1006         App.Manifest.fetchRunsWithPlatformAndMetric(this.store, platformId, metricId).then(this._fetchedRuns.bind(this));
1007     }.observes('model').on('init'),
1008     _fetchedManifest: function ()
1009     {
1010         var trackerIdToBugNumber = {};
1011         this.get('model').get('bugs').forEach(function (bug) {
1012             trackerIdToBugNumber[bug.get('bugTracker').get('id')] = bug.get('number');
1013         });
1014
1015         this.set('bugTrackers', App.Manifest.get('bugTrackers').map(function (bugTracker) {
1016             var bugNumber = trackerIdToBugNumber[bugTracker.get('id')];
1017             return Ember.ObjectProxy.create({
1018                 content: bugTracker,
1019                 bugNumber: bugNumber,
1020                 editedBugNumber: bugNumber,
1021             });
1022         }));
1023     },
1024     _fetchedRuns: function (data)
1025     {
1026         var runs = data.runs;
1027
1028         var currentTimeSeries = runs.current.timeSeriesByCommitTime();
1029         if (!currentTimeSeries)
1030             return; // FIXME: Report an error.
1031
1032         var start = currentTimeSeries.findPointByMeasurementId(this.get('model').get('startRun'));
1033         var end = currentTimeSeries.findPointByMeasurementId(this.get('model').get('endRun'));
1034         if (!start || !end)
1035             return; // FIXME: Report an error.
1036
1037         var highlightedItems = {};
1038         highlightedItems[start.measurement.id()] = true;
1039         highlightedItems[end.measurement.id()] = true;
1040
1041         var chartData = App.createChartData(data);
1042         var formatedPoints = currentTimeSeries.seriesBetweenPoints(start, end).map(function (point, index) {
1043             return {
1044                 id: point.measurement.id(),
1045                 measurement: point.measurement,
1046                 label: 'Point ' + (index + 1),
1047                 value: chartData.formatter(point.value) + (data.unit ? ' ' + data.unit : ''),
1048             };
1049         });
1050
1051         var margin = (end.time - start.time) * 0.1;
1052         this.set('chartData', chartData);
1053         this.set('chartDomain', [start.time - margin, +end.time + margin]);
1054         this.set('highlightedItems', highlightedItems);
1055         this.set('analysisPoints', formatedPoints);
1056     },
1057     testSets: function ()
1058     {
1059         var analysisPoints = this.get('analysisPoints');
1060         if (!analysisPoints)
1061             return;
1062         var pointOptions = [{value: ' ', label: 'None'}]
1063             .concat(analysisPoints.map(function (point) { return {value: point.id, label: point.label}; }));
1064         return [
1065             Ember.Object.create({name: "A", options: pointOptions, selection: pointOptions[1]}),
1066             Ember.Object.create({name: "B", options: pointOptions, selection: pointOptions[pointOptions.length - 1]}),
1067         ];
1068     }.property('analysisPoints'),
1069     _rootChangedForTestSet: function ()
1070     {
1071         var sets = this.get('testSets');
1072         var roots = this.get('roots');
1073         if (!sets || !roots)
1074             return;
1075
1076         sets.forEach(function (testSet, setIndex) {
1077             var currentSelection = testSet.get('selection');
1078             if (currentSelection == testSet.get('previousSelection'))
1079                 return;
1080             testSet.set('previousSelection', currentSelection);
1081             var pointIndex = testSet.get('options').indexOf(currentSelection);
1082
1083             roots.forEach(function (root) {
1084                 var set = root.sets[setIndex];
1085                 set.set('selection', set.revisions[pointIndex]);
1086             });
1087         });
1088
1089     }.observes('testSets.@each.selection'),
1090     updateRoots: function ()
1091     {
1092         var analysisPoints = this.get('analysisPoints');
1093         if (!analysisPoints)
1094             return;
1095         var repositoryToRevisions = {};
1096         analysisPoints.forEach(function (point, pointIndex) {
1097             var revisions = point.measurement.formattedRevisions();
1098             for (var repositoryId in revisions) {
1099                 if (!repositoryToRevisions[repositoryId])
1100                     repositoryToRevisions[repositoryId] = new Array(analysisPoints.length);
1101                 var revision = revisions[repositoryId];
1102                 repositoryToRevisions[repositoryId][pointIndex] = {
1103                     label: point.label + ': ' + revision.label,
1104                     value: revision.currentRevision,
1105                 };
1106             }
1107         });
1108
1109         var self = this;
1110         this.get('model').get('triggerable').then(function (triggerable) {
1111             if (!triggerable)
1112                 return;
1113
1114             self.set('roots', triggerable.get('acceptedRepositories').map(function (repository) {
1115                 var repositoryId = repository.get('id');
1116                 var revisions = [{value: ' ', label: 'None'}].concat(repositoryToRevisions[repositoryId]);
1117                 return Ember.Object.create({
1118                     name: repository.get('name'),
1119                     sets: [
1120                         Ember.Object.create({name: 'A[' + repositoryId + ']',
1121                             revisions: revisions,
1122                             selection: revisions[1]}),
1123                         Ember.Object.create({name: 'B[' + repositoryId + ']',
1124                             revisions: revisions,
1125                             selection: revisions[revisions.length - 1]}),
1126                     ],
1127                 });
1128             }));
1129         });
1130     }.observes('analysisPoints'),
1131     actions: {
1132         associateBug: function (bugTracker, bugNumber)
1133         {
1134             var model = this.get('model');
1135             this.store.createRecord('bug',
1136                 {task: this.get('model'), bugTracker: bugTracker.get('content'), number: bugNumber}).save().then(function () {
1137                     // FIXME: Should we notify the user?
1138                 }, function (error) {
1139                     alert('Failed to associate the bug: ' + error);
1140                 });
1141         },
1142         createTestGroup: function (name, repetitionCount)
1143         {
1144             var roots = {};
1145             this.get('roots').map(function (root) {
1146                 roots[root.get('name')] = root.get('sets').map(function (item) { return item.get('selection').value; });
1147             });
1148             App.TestGroup.create(this.get('model'), name, roots, repetitionCount).then(function () {
1149                 
1150             });
1151         },
1152     },
1153 });