1 window.App = Ember.Application.create();
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'});
11 App.DashboardRow = Ember.Object.extend({
19 var cellsInfo = this.get('cellsInfo') || [];
20 var columnCount = this.get('columnCount');
21 while (cellsInfo.length < columnCount)
24 this.set('cells', cellsInfo.map(this._createPane.bind(this)));
26 addPane: function (paneInfo)
28 var pane = this._createPane(paneInfo);
29 this.get('cells').pushObject(pane);
30 this.set('columnCount', this.get('columnCount') + 1);
32 _createPane: function (paneInfo)
34 if (!paneInfo || !paneInfo.length || (!paneInfo[0] && !paneInfo[1]))
37 var pane = App.Pane.create({
38 store: this.get('store'),
39 platformId: paneInfo ? paneInfo[0] : null,
40 metricId: paneInfo ? paneInfo[1] : null,
43 return App.DashboardPaneProxyForPicker.create({content: pane});
47 App.DashboardPaneProxyForPicker = Ember.ObjectProxy.extend({
48 _platformOrMetricIdChanged: function ()
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'),
59 App.IndexRoute = Ember.Route.extend({
60 beforeModel: function ()
63 App.Manifest.fetch(this.store).then(function () {
64 self.transitionTo('dashboard', App.Manifest.defaultDashboardName());
69 App.DashboardRoute = Ember.Route.extend({
70 model: function (param)
72 return App.Manifest.fetch(this.store).then(function () {
73 return App.Manifest.dashboardByName(param.name);
78 App.CustomDashboardRoute = Ember.Route.extend({
79 controllerName: 'dashboard',
80 model: function (param)
82 return this.store.createRecord('dashboard', {serialized: param.grid});
84 renderTemplate: function()
86 this.render('dashboard');
90 App.DashboardController = Ember.Controller.extend({
91 queryParams: ['grid', 'numberOfDays'],
97 modelChanged: function ()
99 var dashboard = this.get('model');
103 var headerColumns = dashboard.get('headerColumns');
104 this.set('headerColumns', headerColumns);
105 var columnCount = headerColumns.length;
106 this.set('columnCount', columnCount);
108 var store = this.store;
109 this.set('rows', dashboard.get('rows').map(function (rowParam) {
110 return App.DashboardRow.create({
113 cellsInfo: rowParam.slice(1),
114 columnCount: columnCount,
118 this.set('emptyRow', new Array(columnCount));
119 }.observes('model').on('init'),
121 computeGrid: function()
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 : [];
130 return JSON.stringify(table);
133 _sharedDomainChanged: function ()
135 var numberOfDays = this.get('numberOfDays');
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'),
147 setNumberOfDays: function (numberOfDays)
149 this.set('numberOfDays', numberOfDays);
151 choosePane: function (param)
153 var pane = param.position;
154 pane.set('platformId', param.platform.get('id'));
155 pane.set('metricId', param.metric.get('id'));
157 addColumn: function ()
159 this.get('headerColumns').pushObject({
160 label: this.get('newColumnHeader'),
161 index: this.get('headerColumns').length,
163 this.get('rows').forEach(function (row) {
166 this.set('newColumnHeader', null);
168 removeColumn: function (index)
170 this.get('headerColumns').removeAt(index);
171 this.get('rows').forEach(function (row) {
172 row.get('cells').removeAt(index);
177 this.get('rows').pushObject(App.DashboardRow.create({
179 header: this.get('newRowHeader'),
180 columnCount: this.get('columnCount'),
182 this.set('newRowHeader', null);
184 removeRow: function (row)
186 this.get('rows').removeObject(row);
188 resetPane: function (pane)
190 pane.set('platformId', null);
191 pane.set('metricId', null);
193 toggleEditMode: function ()
195 this.toggleProperty('editMode');
196 if (this.get('editMode'))
197 this.transitionToRoute('dashboard', 'custom', {name: null, queryParams: {grid: this.computeGrid()}});
199 this.set('grid', this.computeGrid());
206 App.Manifest.fetch(this.get('store'));
210 App.NumberOfDaysControlView = Ember.View.extend({
211 classNames: ['controls'],
212 templateName: 'number-of-days-controls',
213 didInsertElement: function ()
215 this._matchingElements(this._previousNumberOfDaysClass).addClass('active');
217 _numberOfDaysChanged: function ()
219 this._matchingElements(this._previousNumberOfDaysClass).removeClass('active');
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)
227 var element = this.get('element');
230 return $(element.getElementsByClassName(className));
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,
241 _startTimeInSlider: null,
242 _currentNumberOfDays: null,
243 _MILLISECONDS_PER_DAY: 24 * 3600 * 1000,
245 didInsertElement: function ()
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));
253 _sliderRangeChanged: function ()
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 ()
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);
271 _startTimeChanged: function ()
273 var startTime = this.get('startTime');
274 if (startTime == this._startTimeSetBySlider)
276 this._currentNumberOfDays = this._timeInPastToNumberOfDays(startTime);
279 this._numberOfDaysView.text(this._currentNumberOfDays);
280 this._slider.val(Math.log(this._currentNumberOfDays));
281 this._startTimeInSlider = startTime;
283 }.observes('startTime').on('init'),
284 _timeInPastToNumberOfDays: function (timeInPast)
286 return Math.max(1, Math.round((Date.now() - timeInPast) / this._MILLISECONDS_PER_DAY));
288 _numberOfDaysToTimeInPast: function (numberOfDays)
290 return Date.now() - numberOfDays * this._MILLISECONDS_PER_DAY;
294 App.Pane = Ember.Object.extend({
300 searchCommit: function (repository, keyword) {
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)
306 var currentRuns = self.get('chartData').current.series();
307 if (!currentRuns.length)
310 var highlightedItems = {};
312 for (var runIndex = 0; runIndex < currentRuns.length && commitIndex < commits.length; runIndex++) {
313 var measurement = currentRuns[runIndex].measurement;
314 var commitTime = measurement.commitTimeForRepository(repositoryId);
317 if (commits[commitIndex].time <= commitTime) {
318 highlightedItems[measurement.id()] = true;
321 } while (commitIndex < commits.length && commits[commitIndex].time <= commitTime);
325 self.set('highlightedItems', highlightedItems);
327 // FIXME: Report errors
328 this.set('highlightedItems', {});
331 _fetch: function () {
332 var platformId = this.get('platformId');
333 var metricId = this.get('metricId');
334 if (!platformId && !metricId) {
335 this.set('empty', true);
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);
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');
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 + '"');
364 self.set('failure', 'An internal error');
367 this.fetchAnalyticRanges();
369 }.observes('platformId', 'metricId').on('init'),
370 fetchAnalyticRanges: function ()
372 var platformId = this.get('platformId');
373 var metricId = this.get('metricId');
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'); }));
381 _isValidId: function (id)
383 if (typeof(id) == "number")
385 if (typeof(id) == "string")
386 return !!id.match(/^[A-Za-z0-9_]+$/);
389 computeStatus: function (currentPoint, previousPoint)
391 var chartData = this.get('chartData');
392 var diffFromBaseline = this._relativeDifferentToLaterPointInTimeSeries(currentPoint, chartData.baseline);
393 var diffFromTarget = this._relativeDifferentToLaterPointInTimeSeries(currentPoint, chartData.target);
397 var formatter = d3.format('.3p');
399 var smallerIsBetter = chartData.smallerIsBetter;
400 if (diffFromBaseline !== undefined && diffFromBaseline > 0 == smallerIsBetter) {
401 label = formatter(Math.abs(diffFromBaseline)) + ' ' + (smallerIsBetter ? 'above' : 'below') + ' baseline';
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';
409 var valueDelta = previousPoint ? chartData.deltaFormatter(currentPoint.value - previousPoint.value) : null;
410 return {className: className, label: label, currentValue: chartData.formatter(currentPoint.value), valueDelta: valueDelta};
412 _relativeDifferentToLaterPointInTimeSeries: function (currentPoint, timeSeries)
414 if (!currentPoint || !timeSeries)
417 var referencePoint = timeSeries.findPointAfterTime(currentPoint.time);
421 return (currentPoint.value - referencePoint.value) / referencePoint.value;
423 latestStatus: function ()
425 var chartData = this.get('chartData');
426 if (!chartData || !chartData.current)
429 var lastPoint = chartData.current.lastPoint();
433 return this.computeStatus(lastPoint, chartData.current.previousPoint(lastPoint));
434 }.property('chartData'),
435 updateStatisticsTools: function ()
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')));
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')));
445 _cloneStrategy: function (strategy)
447 var parameterList = (strategy.parameterList || []).map(function (param) { return Ember.Object.create(param); });
448 return Ember.Object.create({
450 label: strategy.label,
451 description: strategy.description,
452 parameterList: parameterList,
453 execute: strategy.execute,
456 _configureStrategy: function (strategies, config)
458 if (!config || !config[0])
462 var chosenStrategy = strategies.find(function (strategy) { return strategy.id == id });
466 if (chosenStrategy.parameterList) {
467 for (var i = 0; i < chosenStrategy.parameterList.length; i++)
468 chosenStrategy.parameterList[i].value = parseFloat(config[i + 1]);
471 return chosenStrategy;
473 _computeChartData: function ()
475 if (!this.get('fetchedData'))
478 var chartData = App.createChartData(this.get('fetchedData'));
479 chartData.movingAverage = this._computeMovingAverage(chartData);
481 this._updateStrategyConfigIfNeeded(this.get('chosenMovingAverageStrategy'), 'movingAverageConfig');
482 this._updateStrategyConfigIfNeeded(this.get('chosenEnvelopingStrategy'), 'envelopingConfig');
484 this.set('chartData', chartData);
485 }.observes('chosenMovingAverageStrategy', 'chosenMovingAverageStrategy.parameterList.@each.value',
486 'chosenEnvelopingStrategy', 'chosenEnvelopingStrategy.parameterList.@each.value'),
487 _computeMovingAverage: function (chartData)
489 var currentTimeSeriesData = chartData.current.series();
490 var movingAverageStrategy = this.get('chosenMovingAverageStrategy');
491 if (!movingAverageStrategy || !movingAverageStrategy.execute)
494 var movingAverageValues = this._executeStrategy(movingAverageStrategy, currentTimeSeriesData);
495 if (!movingAverageValues)
498 var envelopeDelta = null;
499 var envelopingStrategy = this.get('chosenEnvelopingStrategy');
500 if (envelopingStrategy && envelopingStrategy.execute)
501 envelopeDelta = this._executeStrategy(envelopingStrategy, currentTimeSeriesData, [movingAverageValues]);
503 return new TimeSeries(currentTimeSeriesData.map(function (point, index) {
504 var value = movingAverageValues[index];
506 measurement: point.measurement,
509 interval: envelopeDelta !== null ? [value - envelopeDelta, value + envelopeDelta] : null,
513 _executeStrategy: function (strategy, currentTimeSeriesData, additionalArguments)
515 var parameters = (strategy.parameterList || []).map(function (param) {
516 var parsed = parseFloat(param.value);
517 return Math.min(param.max || Infinity, Math.max(param.min || -Infinity, isNaN(parsed) ? 0 : parsed));
519 parameters.push(currentTimeSeriesData.map(function (point) { return point.value }));
520 return strategy.execute.apply(window, parameters.concat(additionalArguments));
522 _updateStrategyConfigIfNeeded: function (strategy, configName)
525 if (strategy && strategy.execute)
526 config = [strategy.id].concat((strategy.parameterList || []).map(function (param) { return param.value; }));
528 if (JSON.stringify(config) != JSON.stringify(this.get(configName)))
529 this.set(configName, config);
533 App.createChartData = function (data)
535 var runs = data.runs;
537 current: runs.current.timeSeriesByCommitTime(),
538 baseline: runs.baseline ? runs.baseline.timeSeriesByCommitTime() : null,
539 target: runs.target ? runs.target.timeSeriesByCommitTime() : null,
541 formatter: data.useSI ? d3.format('.4s') : d3.format('.4g'),
542 deltaFormatter: data.useSI ? d3.format('+.2s') : d3.format('+.2g'),
543 smallerIsBetter: data.smallerIsBetter,
547 App.encodePrettifiedJSON = function (plain)
549 function numberIfPossible(string) {
550 return string == parseInt(string) ? parseInt(string) : string;
553 function recursivelyConvertNumberIfPossible(input) {
554 if (input instanceof Array) {
555 return input.map(recursivelyConvertNumberIfPossible);
557 return numberIfPossible(input);
560 return JSON.stringify(recursivelyConvertNumberIfPossible(plain))
561 .replace(/\[/g, '(').replace(/\]/g, ')').replace(/\,/g, '-');
564 App.decodePrettifiedJSON = function (encoded)
566 var parsed = encoded.replace(/\(/g, '[').replace(/\)/g, ']').replace(/\-/g, ',');
568 return JSON.parse(parsed);
569 } catch (exception) {
574 App.ChartsController = Ember.Controller.extend({
575 queryParams: ['paneList', 'zoom', 'since'],
577 _currentEncodedPaneList: null,
583 defaultSince: Date.now() - 7 * 24 * 3600 * 1000,
585 addPane: function (pane)
587 this.panes.unshiftObject(pane);
590 removePane: function (pane)
592 this.panes.removeObject(pane);
595 refreshPanes: function()
597 var paneList = this.get('paneList');
598 if (paneList === this._currentEncodedPaneList)
601 var panes = this._parsePaneList(paneList || '[]');
603 console.log('Failed to parse', jsonPaneList, exception);
606 this.set('panes', panes);
607 this._currentEncodedPaneList = paneList;
608 }.observes('paneList').on('init'),
610 refreshZoom: function()
612 var zoom = this.get('zoom');
614 this.set('sharedZoom', null);
618 zoom = zoom.split('-');
619 var selection = new Array(2);
621 selection[0] = new Date(parseFloat(zoom[0]));
622 selection[1] = new Date(parseFloat(zoom[1]));
624 console.log('Failed to parse the zoom', zoom);
626 this.set('sharedZoom', selection);
628 var startTime = this.get('startTime');
629 if (startTime && startTime > selection[0])
630 this.set('startTime', selection[0]);
632 }.observes('zoom').on('init'),
634 _startTimeChanged: function () {
635 this.set('sharedDomain', [this.get('startTime'), this.get('present')]);
636 this._scheduleQueryStringUpdate();
637 }.observes('startTime'),
639 _sinceChanged: function () {
640 var since = parseInt(this.get('since'));
642 since = this.defaultSince;
643 this.set('startTime', new Date(since));
644 }.observes('since').on('init'),
646 _parsePaneList: function (encodedPaneList)
648 var parsedPaneList = App.decodePrettifiedJSON(encodedPaneList);
652 // FIXME: Don't re-create all panes.
654 return parsedPaneList.map(function (paneInfo) {
655 var timeRange = null;
656 var selectedItem = null;
657 if (paneInfo[2] instanceof Array) {
658 var timeRange = paneInfo[2];
660 timeRange = [new Date(timeRange[0]), new Date(timeRange[1])];
662 console.log("Failed to parse the time range:", timeRange, error);
665 selectedItem = paneInfo[2];
667 return App.Pane.create({
670 platformId: paneInfo[0],
671 metricId: paneInfo[1],
672 selectedItem: selectedItem,
673 timeRange: timeRange,
674 movingAverageConfig: paneInfo[3],
675 envelopingConfig: paneInfo[4],
680 _serializePaneList: function (panes)
685 return App.encodePrettifiedJSON(panes.map(function (pane) {
687 pane.get('platformId'),
688 pane.get('metricId'),
689 pane.get('timeRange') ? pane.get('timeRange').map(function (date) { return date.getTime() }) : pane.get('selectedItem'),
690 pane.get('movingAverageConfig'),
691 pane.get('envelopingConfig'),
696 _scheduleQueryStringUpdate: function ()
698 Ember.run.debounce(this, '_updateQueryString', 1000);
699 }.observes('sharedZoom', 'panes.@each.platform', 'panes.@each.metric', 'panes.@each.selectedItem', 'panes.@each.timeRange',
700 'panes.@each.movingAverageConfig', 'panes.@each.envelopingConfig'),
702 _updateQueryString: function ()
704 this._currentEncodedPaneList = this._serializePaneList(this.get('panes'));
705 this.set('paneList', this._currentEncodedPaneList);
707 var zoom = undefined;
708 var sharedZoom = this.get('sharedZoom');
709 if (sharedZoom && !App.domainsAreEqual(sharedZoom, this.get('sharedDomain')))
710 zoom = +sharedZoom[0] + '-' + +sharedZoom[1];
711 this.set('zoom', zoom);
713 if (this.get('startTime') - this.defaultSince)
714 this.set('since', this.get('startTime') - 0);
718 addPaneByMetricAndPlatform: function (param)
720 this.addPane(App.Pane.create({
722 platformId: param.platform.get('id'),
723 metricId: param.metric.get('id'),
724 showingDetails: false
733 App.buildPopup(this.store, 'addPaneByMetricAndPlatform').then(function (platforms) {
734 self.set('platforms', platforms);
739 App.buildPopup = function(store, action, position)
741 return App.Manifest.fetch(store).then(function () {
742 return App.Manifest.get('platforms').map(function (platform) {
743 return App.PlatformProxyForPopup.create({content: platform,
744 action: action, position: position});
749 App.PlatformProxyForPopup = Ember.ObjectProxy.extend({
750 children: function ()
752 var platform = this.content;
753 var containsTest = this.content.containsTest.bind(this.content);
754 var action = this.get('action');
755 var position = this.get('position');
756 return App.Manifest.get('topLevelTests')
757 .filter(containsTest)
758 .map(function (test) {
759 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
761 }.property('App.Manifest.topLevelTests'),
764 App.TestProxyForPopup = Ember.ObjectProxy.extend({
766 children: function ()
768 var platform = this.get('platform');
769 var action = this.get('action');
770 var position = this.get('position');
772 var childTests = this.get('childTests')
773 .filter(function (test) { return platform.containsTest(test); })
774 .map(function (test) {
775 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
778 var metrics = this.get('metrics')
779 .filter(function (metric) { return platform.containsMetric(metric); })
780 .map(function (metric) {
781 var aggregator = metric.get('aggregator');
784 actionArgument: {platform: platform, metric: metric, position:position},
785 label: metric.get('label')
789 if (childTests.length && metrics.length)
790 metrics.push({isSeparator: true});
792 return metrics.concat(childTests);
793 }.property('childTests', 'metrics'),
796 App.domainsAreEqual = function (domain1, domain2) {
797 return (!domain1 && !domain2) || (domain1 && domain2 && !(domain1[0] - domain2[0]) && !(domain1[1] - domain2[1]));
800 App.PaneController = Ember.ObjectController.extend({
802 sharedTime: Ember.computed.alias('parentController.sharedTime'),
803 sharedSelection: Ember.computed.alias('parentController.sharedSelection'),
806 toggleDetails: function()
808 this.toggleProperty('showingDetails');
812 this.parentController.removePane(this.get('model'));
814 toggleBugsPane: function ()
816 if (this.toggleProperty('showingAnalysisPane')) {
817 this.set('showingSearchPane', false);
818 this.set('showingStatPane', false);
821 createAnalysisTask: function ()
823 var name = this.get('newAnalysisTaskName');
824 var points = this.get('selectedPoints');
825 Ember.assert('The analysis name should not be empty', name);
826 Ember.assert('There should be at least two points in the range', points && points.length >= 2);
828 var newWindow = window.open();
830 App.AnalysisTask.create(name, points[0].measurement, points[points.length - 1].measurement).then(function (data) {
831 // FIXME: Update the UI to show the new analysis task.
832 var url = App.Router.router.generate('analysisTask', data['taskId']);
833 newWindow.location.href = '#' + url;
834 self.get('model').fetchAnalyticRanges();
835 }, function (error) {
837 if (error === 'DuplicateAnalysisTask') {
838 // FIXME: Duplicate this error more gracefully.
843 toggleSearchPane: function ()
845 if (!App.Manifest.repositoriesWithReportedCommits)
847 var model = this.get('model');
848 if (!model.get('commitSearchRepository'))
849 model.set('commitSearchRepository', App.Manifest.repositoriesWithReportedCommits[0]);
850 if (this.toggleProperty('showingSearchPane')) {
851 this.set('showingAnalysisPane', false);
852 this.set('showingStatPane', false);
855 searchCommit: function () {
856 var model = this.get('model');
857 model.searchCommit(model.get('commitSearchRepository'), model.get('commitSearchKeyword'));
859 toggleStatPane: function ()
861 if (this.toggleProperty('showingStatPane')) {
862 this.set('showingSearchPane', false);
863 this.set('showingAnalysisPane', false);
866 zoomed: function (selection)
868 this.set('mainPlotDomain', selection ? selection : this.get('overviewDomain'));
869 Ember.run.debounce(this, 'propagateZoom', 100);
872 _detailsChanged: function ()
874 this.set('showingAnalysisPane', false);
875 }.observes('details'),
876 _overviewSelectionChanged: function ()
878 var overviewSelection = this.get('overviewSelection');
879 if (App.domainsAreEqual(overviewSelection, this.get('mainPlotDomain')))
881 this.set('mainPlotDomain', overviewSelection || this.get('overviewDomain'));
882 Ember.run.debounce(this, 'propagateZoom', 100);
883 }.observes('overviewSelection'),
884 _sharedDomainChanged: function ()
886 var newDomain = this.get('parentController').get('sharedDomain');
887 if (App.domainsAreEqual(newDomain, this.get('overviewDomain')))
889 this.set('overviewDomain', newDomain);
890 if (!this.get('overviewSelection'))
891 this.set('mainPlotDomain', newDomain);
892 }.observes('parentController.sharedDomain').on('init'),
893 propagateZoom: function ()
895 this.get('parentController').set('sharedZoom', this.get('mainPlotDomain'));
897 _sharedZoomChanged: function ()
899 var newSelection = this.get('parentController').get('sharedZoom');
900 if (App.domainsAreEqual(newSelection, this.get('mainPlotDomain')))
902 this.set('mainPlotDomain', newSelection || this.get('overviewDomain'));
903 this.set('overviewSelection', newSelection);
904 }.observes('parentController.sharedZoom').on('init'),
905 _updateDetails: function ()
907 var selectedPoints = this.get('selectedPoints');
908 var currentPoint = this.get('currentItem');
909 if (!selectedPoints && !currentPoint) {
910 this.set('details', null);
914 var currentMeasurement;
917 previousPoint = currentPoint.series.previousPoint(currentPoint);
919 currentPoint = selectedPoints[selectedPoints.length - 1];
920 previousPoint = selectedPoints[0];
922 var currentMeasurement = currentPoint.measurement;
923 var oldMeasurement = previousPoint ? previousPoint.measurement : null;
925 var formattedRevisions = currentMeasurement.formattedRevisions(oldMeasurement);
926 var revisions = App.Manifest.get('repositories')
927 .filter(function (repository) { return formattedRevisions[repository.get('id')]; })
928 .map(function (repository) {
929 var revision = Ember.Object.create(formattedRevisions[repository.get('id')]);
930 revision['url'] = revision.previousRevision
931 ? repository.urlForRevisionRange(revision.previousRevision, revision.currentRevision)
932 : repository.urlForRevision(revision.currentRevision);
933 revision['name'] = repository.get('name');
934 revision['repository'] = repository;
938 var buildNumber = null;
940 if (!selectedPoints) {
941 buildNumber = currentMeasurement.buildNumber();
942 var builder = App.Manifest.builder(currentMeasurement.builderId());
944 buildURL = builder.urlFromBuildNumber(buildNumber);
947 this.set('details', Ember.Object.create({
948 status: this.get('model').computeStatus(currentPoint, previousPoint),
949 buildNumber: buildNumber,
951 buildTime: currentMeasurement.formattedBuildTime(),
952 revisions: revisions,
954 this._updateCanAnalyze();
955 }.observes('currentItem', 'selectedPoints'),
956 _updateCanAnalyze: function ()
958 var points = this.get('selectedPoints');
959 this.set('cannotAnalyze', !this.get('newAnalysisTaskName') || !points || points.length < 2);
960 }.observes('newAnalysisTaskName'),
964 App.AnalysisRoute = Ember.Route.extend({
966 return this.store.findAll('analysisTask').then(function (tasks) {
967 return Ember.Object.create({'tasks': tasks});
972 App.AnalysisTaskRoute = Ember.Route.extend({
973 model: function (param)
975 return this.store.find('analysisTask', param.taskId);
979 App.AnalysisTaskController = Ember.Controller.extend({
980 label: Ember.computed.alias('model.name'),
981 platform: Ember.computed.alias('model.platform'),
982 metric: Ember.computed.alias('model.metric'),
983 testGroups: Ember.computed.alias('model.testGroups'),
987 possibleRepetitionCounts: [1, 2, 3, 4, 5, 6],
988 _taskUpdated: function ()
990 var model = this.get('model');
994 var platformId = model.get('platform').get('id');
995 var metricId = model.get('metric').get('id');
996 App.Manifest.fetch(this.store).then(this._fetchedManifest.bind(this));
997 App.Manifest.fetchRunsWithPlatformAndMetric(this.store, platformId, metricId).then(this._fetchedRuns.bind(this));
998 }.observes('model').on('init'),
999 _fetchedManifest: function ()
1001 var trackerIdToBugNumber = {};
1002 this.get('model').get('bugs').forEach(function (bug) {
1003 trackerIdToBugNumber[bug.get('bugTracker').get('id')] = bug.get('number');
1006 this.set('bugTrackers', App.Manifest.get('bugTrackers').map(function (bugTracker) {
1007 var bugNumber = trackerIdToBugNumber[bugTracker.get('id')];
1008 return Ember.ObjectProxy.create({
1009 content: bugTracker,
1010 bugNumber: bugNumber,
1011 editedBugNumber: bugNumber,
1015 _fetchedRuns: function (data)
1017 var runs = data.runs;
1019 var currentTimeSeries = runs.current.timeSeriesByCommitTime();
1020 if (!currentTimeSeries)
1021 return; // FIXME: Report an error.
1023 var start = currentTimeSeries.findPointByMeasurementId(this.get('model').get('startRun'));
1024 var end = currentTimeSeries.findPointByMeasurementId(this.get('model').get('endRun'));
1026 return; // FIXME: Report an error.
1028 var highlightedItems = {};
1029 highlightedItems[start.measurement.id()] = true;
1030 highlightedItems[end.measurement.id()] = true;
1032 var chartData = App.createChartData(data);
1033 var formatedPoints = currentTimeSeries.seriesBetweenPoints(start, end).map(function (point, index) {
1035 id: point.measurement.id(),
1036 measurement: point.measurement,
1037 label: 'Point ' + (index + 1),
1038 value: chartData.formatter(point.value) + (data.unit ? ' ' + data.unit : ''),
1042 var margin = (end.time - start.time) * 0.1;
1043 this.set('chartData', chartData);
1044 this.set('chartDomain', [start.time - margin, +end.time + margin]);
1045 this.set('highlightedItems', highlightedItems);
1046 this.set('analysisPoints', formatedPoints);
1048 testSets: function ()
1050 var analysisPoints = this.get('analysisPoints');
1051 if (!analysisPoints)
1053 var pointOptions = [{value: ' ', label: 'None'}]
1054 .concat(analysisPoints.map(function (point) { return {value: point.id, label: point.label}; }));
1056 Ember.Object.create({name: "A", options: pointOptions, selection: pointOptions[1]}),
1057 Ember.Object.create({name: "B", options: pointOptions, selection: pointOptions[pointOptions.length - 1]}),
1059 }.property('analysisPoints'),
1060 _rootChangedForTestSet: function ()
1062 var sets = this.get('testSets');
1063 var roots = this.get('roots');
1064 if (!sets || !roots)
1067 sets.forEach(function (testSet, setIndex) {
1068 var currentSelection = testSet.get('selection');
1069 if (currentSelection == testSet.get('previousSelection'))
1071 testSet.set('previousSelection', currentSelection);
1072 var pointIndex = testSet.get('options').indexOf(currentSelection);
1074 roots.forEach(function (root) {
1075 var set = root.sets[setIndex];
1076 set.set('selection', set.revisions[pointIndex]);
1080 }.observes('testSets.@each.selection'),
1081 updateRoots: function ()
1083 var analysisPoints = this.get('analysisPoints');
1084 if (!analysisPoints)
1086 var repositoryToRevisions = {};
1087 analysisPoints.forEach(function (point, pointIndex) {
1088 var revisions = point.measurement.formattedRevisions();
1089 for (var repositoryId in revisions) {
1090 if (!repositoryToRevisions[repositoryId])
1091 repositoryToRevisions[repositoryId] = new Array(analysisPoints.length);
1092 var revision = revisions[repositoryId];
1093 repositoryToRevisions[repositoryId][pointIndex] = {
1094 label: point.label + ': ' + revision.label,
1095 value: revision.currentRevision,
1101 this.get('model').get('triggerable').then(function (triggerable) {
1105 self.set('roots', triggerable.get('acceptedRepositories').map(function (repository) {
1106 var repositoryId = repository.get('id');
1107 var revisions = [{value: ' ', label: 'None'}].concat(repositoryToRevisions[repositoryId]);
1108 return Ember.Object.create({
1109 name: repository.get('name'),
1111 Ember.Object.create({name: 'A[' + repositoryId + ']',
1112 revisions: revisions,
1113 selection: revisions[1]}),
1114 Ember.Object.create({name: 'B[' + repositoryId + ']',
1115 revisions: revisions,
1116 selection: revisions[revisions.length - 1]}),
1121 }.observes('analysisPoints'),
1123 associateBug: function (bugTracker, bugNumber)
1125 var model = this.get('model');
1126 this.store.createRecord('bug',
1127 {task: this.get('model'), bugTracker: bugTracker.get('content'), number: bugNumber}).save().then(function () {
1128 // FIXME: Should we notify the user?
1129 }, function (error) {
1130 alert('Failed to associate the bug: ' + error);
1133 createTestGroup: function (name, repetitionCount)
1136 this.get('roots').map(function (root) {
1137 roots[root.get('name')] = root.get('sets').map(function (item) { return item.get('selection').value; });
1139 App.TestGroup.create(this.get('model'), name, roots, repetitionCount).then(function () {