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