jam-cloud/web/app/assets/javascripts/gear_wizard.js

747 lines
22 KiB
JavaScript

(function (context, $) {
"use strict";
context.JK = context.JK || {};
context.JK.GearWizard = function (app) {
var $dialog = null;
var $wizardSteps = null;
var $currentWizardStep = null;
var step = 0;
var $templateSteps = null;
var $templateButtons = null;
var $templateAudioPort = null;
var $ftueButtons = null;
var self = null;
var operatingSystem = null;
// populated by loadDevices
var deviceInformation = null;
var musicInputPorts = null;
var musicOutputPorts = null;
// SELECT DEVICE STATE
var validScore = false;
// SELECT TRACKS STATE
var TOTAL_STEPS = 7;
var STEP_INTRO = 0;
var STEP_SELECT_DEVICE = 1;
var STEP_SELECT_TRACKS = 2;
var STEP_SELECT_CHAT = 3;
var STEP_DIRECT_MONITOR = 4;
var STEP_ROUTER_NETWORK = 5;
var STEP_SUCCESS = 6;
var PROFILE_DEV_SEP_TOKEN = '^';
var iCheckIgnore = false;
var audioDeviceBehavior = {
MacOSX_builtin: {
display: 'MacOSX Built-In',
videoURL: undefined
},
MACOSX_interface: {
display: 'MacOSX external interface',
videoURL: undefined
},
Win32_wdm: {
display: 'Windows WDM',
videoURL: undefined
},
Win32_asio: {
display: 'Windows ASIO',
videoURL: undefined
},
Win32_asio4all: {
display: 'Windows ASIO4ALL',
videoURL: undefined
},
Linux: {
display: 'Linux',
videoURL: undefined
}
}
function beforeShowIntro() {
var $watchVideo = $currentWizardStep.find('.watch-video');
var videoUrl = 'https://www.youtube.com/watch?v=VexH4834o9I';
if (operatingSystem == "Win32") {
$watchVideo.attr('href', 'https://www.youtube.com/watch?v=VexH4834o9I');
}
$watchVideo.attr('href', videoUrl);
}
function beforeSelectDevice() {
var $watchVideoInput = $currentWizardStep.find('.watch-video.audio-input');
var $watchVideoOutput = $currentWizardStep.find('.watch-video.audio-output');
var $audioInput = $currentWizardStep.find('.select-audio-input-device');
var $audioOutput = $currentWizardStep.find('.select-audio-output-device');
var $bufferIn = $currentWizardStep.find('.select-buffer-in');
var $bufferOut = $currentWizardStep.find('.select-buffer-out');
var $frameSize = $currentWizardStep.find('.select-frame-size');
var $inputPorts = $currentWizardStep.find('.input-ports');
var $outputPorts = $currentWizardStep.find('.output-ports');
var $scoreReport = $currentWizardStep.find('.results');
var $latencyScore = $scoreReport.find('.latency-score');
var $ioRateScore = $scoreReport.find('.io-rate-score');
var $ioVarScore = $scoreReport.find('.io-var-score');
var $nextButton = $ftueButtons.find('.btn-next');
// should return one of:
// * MacOSX_builtin
// * MACOSX_interface
// * Win32_wdm
// * Win32_asio
// * Win32_asio4all
// * Linux
function determineDeviceType(deviceId, displayName) {
if (operatingSystem == "MacOSX") {
if (displayName.toLowerCase().trim() == "built-in") {
return "MacOSX_builtin";
}
else {
return "MacOSX_interface";
}
}
else if (operatingSystem == "Win32") {
if (context.jamClient.FTUEIsMusicDeviceWDM(deviceId)) {
return "Win32_wdm";
}
else if (displayName.toLowerCase().indexOf("asio4all") > -1) {
return "Win32_asio4all"
}
else {
return "Win32_asio";
}
}
else {
return "Linux";
}
}
function loadDevices() {
var devices = context.jamClient.FTUEGetDevices(false);
var loadedDevices = {};
// augment these devices by determining their type
context._.each(devices, function (displayName, deviceId) {
var deviceInfo = {};
deviceInfo.id = deviceId;
deviceInfo.type = determineDeviceType(deviceId, displayName);
deviceInfo.displayType = audioDeviceBehavior[deviceInfo.type].display;
deviceInfo.displayName = displayName;
loadedDevices[deviceId] = deviceInfo;
logger.debug("loaded device: ", deviceInfo);
})
deviceInformation = loadedDevices;
logger.debug(context.JK.dlen(deviceInformation) + " devices loaded.", deviceInformation);
}
// returns a deviceInfo hash for the device matching the deviceId, or undefined.
function findDevice(deviceId) {
return deviceInformation[deviceId];
}
function selectedAudioInput() {
return $audioInput.val();
}
function selectedAudioOutput() {
return $audioOutput.val();
}
function selectedFramesize() {
return parseFloat($frameSize.val());
}
function selectedBufferIn() {
return parseFloat($frameSize.val());
}
function selectedBufferOut() {
return parseFloat($frameSize.val());
}
function initializeNextButtonState() {
$nextButton.removeClass('button-orange button-grey');
if (validScore) $nextButton.addClass('button-orange');
else $nextButton.addClass('button-grey');
}
function initializeAudioInput() {
var optionsHtml = '';
optionsHtml = '<option selected="selected" value="">Choose...</option>';
context._.each(deviceInformation, function (deviceInfo, deviceId) {
console.log(arguments)
optionsHtml += '<option title="' + deviceInfo.displayName + '" value="' + deviceId + '">' + deviceInfo.displayName + '</option>';
});
$audioInput.html(optionsHtml);
context.JK.dropdown($audioInput);
initializeAudioInputChanged();
}
function initializeAudioOutput() {
var optionsHtml = '';
optionsHtml = '<option selected="selected" value="">Same as Input...</option>';
context._.each(deviceInformation, function (deviceInfo, deviceId) {
optionsHtml += '<option title="' + deviceInfo.displayName + '" value="' + deviceId + '">' + deviceInfo.displayName + '</option>';
});
$audioOutput.html(optionsHtml);
context.JK.dropdown($audioOutput);
initializeAudioOutputChanged();
}
function initializeFramesize() {
context.JK.dropdown($frameSize);
}
function initializeBuffers() {
context.JK.dropdown($bufferIn);
context.JK.dropdown($bufferOut);
}
// finds out if the $port argument is from a different port pair than what's currently selected
function isNewlySelectedPair($port) {
var portId = $port.attr('data-id');
// get all inputs currently selected except this one
var $selectedInputs = $inputPorts.find('input[type="checkbox"]:checked').filter('[data-id="' + portId + '"]');
console.log("$selectedInputs", $selectedInputs);
var isNewlySelected = true;
context._.each($selectedInputs, function($current) {
var testPairInfo = $($current).data('pair');
context._.each(testPairInfo.ports, function(port) {
// if we can find the newly selected item in this pair, then it's not a different pair...
if(port.id == portId) {
isNewlySelected = false;
return false; // break loop
}
});
if(isNewlySelected) return false; // break loop
});
return isNewlySelected;
}
// set checkbox state for all items in the pair
function setCheckedForAllInPair($portBox, pairInfo, checked, signalBackend) {
context._.each(pairInfo.ports, function(port) {
var portId = port.id;
var $input = $portBox.find('input[type="checkbox"][data-id="' + portId + '"]');
if($input.is(':checked') != checked) {
if(checked) {
$input.iCheck('check').attr('checked', 'checked');
//context.jamClient.FTUESetMusicInput2($input.id);
}
else {
$input.iCheck('uncheck').removeAttr('checked');
//context.jamClient.FTUEUnsetMusicInput2($input.id);
}
}
})
}
function inputPortChanged() {
if(iCheckIgnore) return;
var $checkbox = $(this);
var portId = $checkbox.data('data-id');
var inputPortChecked = $checkbox.is(':checked');
console.log('inputPortChecked: ' + inputPortChecked);
if(inputPortChecked) {
if(isNewlySelectedPair($checkbox)) {
setCheckedForAllInPair($inputPorts, $checkbox.data('pair'), true, true);
}
else {
//context.jamClient.FTUESetMusicInput2($input.id);
}
}
else {
// context.jamClient.FTUEUnsetMusicInput2($input.id);;
}
}
// should be called in a ifChanged callback if you want to cancel. bleh.
function cancelICheckChange($checkbox) {
iCheckIgnore = true;
var checked = $checkbox.is(':checked');
setTimeout(function() {
if(checked) $checkbox.iCheck('uncheck').removeAttr('checked');
else $checkbox.iCheck('check').attr('checked', 'checked');
iCheckIgnore = false;
}, 1);
}
function outputPortChanged() {
if(iCheckIgnore) return;
var $checkbox = $(this);
var portId = $checkbox.data('data-id');
var outputPortChecked = $checkbox.is(':checked');
console.log('outputPortChecked: ' + outputPortChecked);
if(outputPortChecked) {
var $selectedInputs = $outputPorts.find('input[type="checkbox"]:checked').filter('[data-id="' + portId + '"]');
$selectedInputs.iCheck('uncheck').removeAttr('checked');
var pairInfo = $checkbox.data('pair');
setCheckedForAllInPair($outputPorts, pairInfo, true, false);
console.log("Setting music output");
context.jamClient.FTUESetMusicOutput(pairInfo.ports.map(function(i) {return i.id}).join(PROFILE_DEV_SEP_TOKEN));
}
else {
context.JK.Banner.showAlert('You must have at least one output pair selected.');
// can't allow uncheck of last output
cancelICheckChange($checkbox);
}
}
function initializeInputPorts(inputPorts) {
context._.each(inputPorts, function(inputPairs) {
// there is no guarantee that a pair has two items.
context._.each(inputPairs.ports, function(inputInPair) {
var inputPort = $(context._.template($templateAudioPort.html(), inputInPair, { variable: 'data' }));
var $checkbox = inputPort.find('input');
$checkbox.data('pair', inputPairs); // so when it's selected, we can see what other ports, if any, are in the same pair
context.JK.checkbox($checkbox);
$checkbox.on('ifChanged', inputPortChanged);
$inputPorts.append(inputPort);
});
});
}
function initializeOutputPorts(outputPorts) {
var first = true;
context._.each(outputPorts, function(outputPairs) {
context._.each(outputPairs.ports, function(outputInPair) {
var outputPort = $(context._.template($templateAudioPort.html(), outputInPair, { variable: 'data' }));
var $checkbox = outputPort.find('input');
$checkbox.data('pair', outputPairs); // so when it's selected, we can see what other ports, if any, are in the same pair
context.JK.checkbox($checkbox);
$checkbox.on('ifChanged', outputPortChanged);
$outputPorts.append(outputPort);
});
if(first) {
first = false;
setCheckedForAllInPair($outputPorts, outputPairs, true, false);
}
});
}
function initializeFormElements() {
if (!deviceInformation) throw "devices are not initialized";
initializeAudioInput();
initializeAudioOutput();
initializeFramesize();
initializeBuffers();
}
function resetFrameBuffers() {
$frameSize.val('2.5');
$bufferIn.val('0');
$bufferOut.val('0');
}
function clearInputPorts() {
$inputPorts.empty();
}
function clearOutputPorts() {
$outputPorts.empty();
}
function resetScoreReport() {
$ioRateScore.empty();
$ioVarScore.empty();
$latencyScore.empty();
}
function updateScoreReport(latencyResult) {
var latencyClass = "neutral";
var latencyValue = 'N/A';
var validLatency = false;
if (latencyResult && latencyResult.latencyknown) {
var latencyValue = latencyResult.latency;
latencyValue = Math.round(latencyValue * 100) / 100;
if (latencyValue <= 10) {
latencyClass = "good";
validLatency = true;
} else if (latency.latency <= 20) {
latencyClass = "acceptable";
validLatency = true;
} else {
latencyClass = "bad";
}
}
validScore = validLatency; // validScore may become based on IO variance too
$latencyScore.html(latencyValue + ' ms');
}
function audioInputDeviceUnselected() {
validScore = false;
initializeNextButtonState();
resetFrameBuffers();
clearInputPorts();
}
function renderScoringStarted() {
validScore = false;
initializeNextButtonState();
resetScoreReport();
}
function renderScoringStopped() {
initializeNextButtonState();
}
// Given a latency structure, update the view.
function newFtueUpdateLatencyView(latency) {
var $report = $('.ftue-new .latency .report');
var $instructions = $('.ftue-new .latency .instructions');
var latencyClass = "neutral";
var latencyValue = "N/A";
var $saveButton = $('#btn-ftue-2-save');
if (latency && latency.latencyknown) {
latencyValue = latency.latency;
// Round latency to two decimal places.
latencyValue = Math.round(latencyValue * 100) / 100;
if (latency.latency <= 10) {
latencyClass = "good";
setSaveButtonState($saveButton, true);
} else if (latency.latency <= 20) {
latencyClass = "acceptable";
setSaveButtonState($saveButton, true);
} else {
latencyClass = "bad";
setSaveButtonState($saveButton, false);
}
} else {
latencyClass = "unknown";
setSaveButtonState($saveButton, false);
}
$('.ms-label', $report).html(latencyValue);
$('p', $report).html('milliseconds');
$report.removeClass('good acceptable bad unknown');
$report.addClass(latencyClass);
var instructionClasses = ['neutral', 'good', 'acceptable', 'unknown', 'bad', 'start', 'loading'];
$.each(instructionClasses, function (idx, val) {
$('p.' + val, $instructions).hide();
});
if (latency === 'loading') {
$('p.loading', $instructions).show();
} else {
$('p.' + latencyClass, $instructions).show();
renderStopNewFtueLatencyTesting();
}
}
function initializeWatchVideo() {
$watchVideoInput.unbind('click').click(function () {
var audioDevice = findDevice(selectedAudioInput());
if (!audioDevice) {
context.JK.Banner.showAlert('You must first choose an Audio Input Device so that we can determine which video to show you.');
}
else {
var videoURL = audioDeviceBehavior[audioDevice.type].videoURL;
if (videoURL) {
$(this).attr('href', videoURL);
return true;
}
else {
context.JK.Banner.showAlert('No help video for this type of device (' + audioDevice.displayType + ')');
}
}
return false;
});
$watchVideoOutput.unbind('click').click(function () {
var audioDevice = findDevice(selectedAudioOutput());
if (!audioDevice) {
throw "this button should be hidden";
}
else {
var videoURL = audioDeviceBehavior[audioDevice.type].videoURL;
if (videoURL) {
$(this).attr('href', videoURL);
return true;
}
else {
context.JK.Banner.showAlert('No help video for this type of device (' + audioDevice.displayType + ')');
}
}
return false;
});
}
function initializeAudioInputChanged() {
$audioInput.unbind('change').change(function (evt) {
var audioDeviceId = selectedAudioInput();
if (!audioDeviceId) {
audioInputDeviceUnselected();
return false;
}
var audioDevice = findDevice(selectedAudioInput());
if (!audioDevice) {
context.JK.alertSupportedNeeded('Unable to find device information for: ' + audioDeviceId);
return false;
}
renderScoringStarted();
jamClient.FTUESetMusicDevice(audioDeviceId);
// enumerate input and output ports
musicInputPorts = jamClient.FTUEGetMusicInputs2();
console.log(JSON.stringify(musicInputPorts));
// [{"inputs":[{"id":"i~5~Built-in Microph~0~0","name":"Built-in Microph - Left"},{"id":"i~5~Built-in Microph~1~0","name":"Built-in Microph - Right"}]}]
musicOutputPorts = jamClient.FTUEGetMusicOutputs2();
console.log(JSON.stringify(musicOutputPorts));
// [{"outputs":[{"id":"o~5~Built-in Output~0~0","name":"Built-in Output - Left"},{"id":"o~5~Built-in Output~1~0","name":"Built-in Output - Right"}]}]
initializeInputPorts(musicInputPorts);
initializeOutputPorts(musicOutputPorts);
jamClient.FTUESetInputLatency(selectedAudioInput());
jamClient.FTUESetOutputLatency(selectedAudioOutput());
jamClient.FTUESetFrameSize(selectedFramesize());
logger.debug("Calling FTUESave(false)");
jamClient.FTUESave(false);
var latency = jamClient.FTUEGetExpectedLatency();
console.log("FTUEGetExpectedLatency: %o", latency);
updateScoreReport(latency);
renderScoringStopped();
});
}
function initializeAudioOutputChanged() {
}
function initializeStep() {
loadDevices();
initializeFormElements();
initializeNextButtonState();
initializeWatchVideo();
}
initializeStep();
}
function beforeSelectTracks() {
}
function beforeSelectChat() {
}
function beforeDirectMonitor() {
}
function beforeTestNetwork() {
}
function beforeSuccess() {
}
var STEPS = {
0: {
beforeShow: beforeShowIntro
},
1: {
beforeShow: beforeSelectDevice
},
2: {
beforeShow: beforeSelectTracks
},
3: {
beforeShow: beforeSelectChat
},
4: {
beforeShow: beforeDirectMonitor
},
5: {
beforeShow: beforeTestNetwork
},
6: {
beforeShow: beforeSuccess
}
}
function beforeShowStep($step) {
var stepInfo = STEPS[step];
if (!stepInfo) {
throw "unknown step: " + step;
}
stepInfo.beforeShow.call(self);
}
function moveToStep() {
var $nextWizardStep = $wizardSteps.filter($('[layout-wizard-step=' + step + ']'));
$wizardSteps.hide();
$currentWizardStep = $nextWizardStep;
var $ftueSteps = $(context._.template($templateSteps.html(), {}, { variable: 'data' }));
var $activeStep = $ftueSteps.find('.ftue-stepnumber[data-step-number="' + step + '"]');
$activeStep.addClass('.active');
$activeStep.next().show(); // show the .ftue-step-title
$currentWizardStep.find('.ftuesteps').replaceWith($ftueSteps);
beforeShowStep($currentWizardStep);
$currentWizardStep.show();
// update buttons
var $ftueButtonsContent = $(context._.template($templateButtons.html(), {}, {variable: 'data'}));
var $btnBack = $ftueButtonsContent.find('.btn-back');
var $btnNext = $ftueButtonsContent.find('.btn-next');
var $btnClose = $ftueButtonsContent.find('.btn-close');
var $btnCancel = $ftueButtonsContent.find('.btn-cancel');
// hide back button if 1st step or last step
if (step == 0 && step == TOTAL_STEPS - 1) {
$btnBack.hide();
}
// hide next button if not on last step
if (step == TOTAL_STEPS - 1) {
$btnNext.hide();
}
// hide close if on last step
if (step != TOTAL_STEPS - 1) {
$btnClose.hide();
}
// hide cancel if not on last step
if (step == TOTAL_STEPS - 1) {
$btnCancel.hide();
}
$btnNext.on('click', next);
$btnBack.on('click', back);
$btnClose.on('click', closeDialog);
$btnCancel.on('click', closeDialog);
$ftueButtons.empty();
$ftueButtons.append($ftueButtonsContent);
}
function reset() {
$currentWizardStep = null;
}
function beforeShow(args) {
step = args.d1;
if (!step) step = 0;
step = parseInt(step);
moveToStep();
}
function afterShow() {
}
function afterHide() {
}
function back() {
if ($(this).is('.button-grey')) return;
step = step - 1;
moveToStep();
return false;
}
function next() {
if ($(this).is('.button-grey')) return;
step = step + 1;
moveToStep();
return false;
}
function closeDialog() {
app.layout.closeDialog('gear-wizard');
return false;
}
function events() {
}
function route() {
}
function initialize() {
var dialogBindings = { beforeShow: beforeShow, afterShow: afterShow, afterHide: afterHide };
app.bindDialog('gear-wizard', dialogBindings);
$dialog = $('#gear-wizard-dialog');
$wizardSteps = $dialog.find('.wizard-step');
$templateSteps = $('#template-ftuesteps');
$templateButtons = $('#template-ftue-buttons');
$templateAudioPort = $('#template-audio-port');
$ftueButtons = $dialog.find('.ftue-buttons');
operatingSystem = context.jamClient.GetOSAsString();
events();
}
this.initialize = initialize;
self = this;
return this;
};
})(window, jQuery);