// SPDX-FileCopyrightText: 2012-2023 MOD Audio UG // SPDX-License-Identifier: AGPL-3.0-or-later function Desktop(elements) { var self = this // The elements below are expected to be all defined in HTML and passed as parameter elements = $.extend({ titleBox: $('
'), performanceTitleBox: $('
'), zoomIn: $('
'), zoomOut: $('
'), addMidiButton: $('
'), midiPortsWindow: $('
'), midiPortsList: $('
'), pedalPresetsWindow: $('
'), pedalPresetsList: $('
'), pedalPresetsOverlay: $('
'), updateDeviceWindow: $('
'), saveBox: $('
'), saveButton: $('
'), saveAsButton: $('
'), resetButton: $('
'), cvAddressingButton: $('
'), snapshotSaveButton: $('
'), snapshotSaveAsButton: $('
'), snapshotManageButton: $('
'), transportButton: $('
'), transportWindow: $('
'), transportPlay: $('
'), transportBPB: $('
'), transportBPM: $('
'), transportSyncMode: $('
'), effectBox: $('
'), effectBoxTrigger: $('
'), cloudPluginBox: $('
'), cloudPluginBoxTrigger: $('
'), pedalboardTrigger: $('
'), fileManagerBox: $('
'), fileManagerBoxTrigger: $('
'), performanceBox: $('
'), performanceBoxTrigger: $('
'), pedalboardBox: $('
'), pedalboardBoxTrigger: $('
'), bankBox: $('
'), bankBoxTrigger: $('
'), bankList: $('
'), bankPedalboardList: $('
'), bankSearchResult: $('
'), shareButton: $('
'), shareWindow: $('
'), inputBox: $('
'), presetSaveBox: $('
'), devicesIcon: $('
'), devicesWindow: $('
'), statusIcon: $('
'), settingsIcon: $('
'), upgradeIcon: $('
'), upgradeWindow: $('
'), bypassLeftButton: $('
'), bypassRightButton: $('
'), bufferSizeButton: $('
'), xrunsButton: $('
'), cpuStatsButton: $('
'), cpuButton: $('
'), cpuLoadWindow: $('
'), cpuLoadList: $('
'), cpuLoadSummary: $('
'), }, elements) this.installationQueue = new InstallationQueue() this.windowManager = new WindowManager() this.pluginIndexer = lunr(function () { this.field('data') this.ref('id') this.requireAllTerms = true }) this.pedalboardIndexer = lunr(function () { this.field('data') this.ref('id') this.requireAllTerms = true }) this.pluginIndexerData = {} this.pedalboardIndexerData = {} this.previousPedalboardList = null this.cvAddressing = false this.resetPluginIndexer = function (plugins) { self.pluginIndexer = lunr(function () { this.field('data') this.ref('id') this.requireAllTerms = true }) var i, plugin for (i in plugins) { plugin = plugins[i] self.pluginIndexer.add({ id: plugin.uri, data: [plugin.uri, plugin.name, plugin.brand, plugin.comment, plugin.category.join(" ")].join(" "), }) } self.pluginIndexerData = plugins } this.pedalboardStatsSuccess = false; this.pedalboardStats = {}; this.resetPedalboardStats = function() { this.pedalboardStatsSuccess = false; if (! CLOUD_TERMS_ACCEPTED) { return } $.ajax({ url: SITEURL + '/pedalboards/stats', type: 'GET', success: function(stats) { self.pedalboardStatsSuccess = true; self.pedalboardStats = stats; }, cache: false }) }; this.getPedalboardHref = function(uri, unstable) { if (!this.pedalboardStatsSuccess) { return null; } var base64Uri = btoa(uri); if (!this.pedalboardStats[base64Uri]) { return null; } var encodedUri = encodeURIComponent(uri); if (unstable) { encodedUri += '&unstable=true'; } return PEDALBOARDS_URL + '/?plugin_uri=' + encodedUri; }; this.midiDevices = new MidiPortsWindow({ midiPortsWindow: elements.midiPortsWindow, midiPortsList: elements.midiPortsList, }) this.hardwareManager = new HardwareManager({ address: function (instanceAndSymbol, addressing, callback) { $.ajax({ url: '/effect/parameter/address/' + instanceAndSymbol, type: 'POST', data: JSON.stringify(addressing), success: function (resp) { if (resp) { self.setPedalboardAsModified(true) callback(true) } else { new Bug("Couldn't address parameter, not allowed") callback(false) } }, error: function () { new Bug("Couldn't address parameter, server error") callback(false) }, cache: false, dataType: 'json' }) }, setEnabled: function (instance, portSymbol, enabled, feedback, forceAddress, momentaryMode) { if (!enabled && feedback === undefined) { console.warn("ERROR setEnabled called as false, but with undefined feedback") feedback = true } if (instance == "/pedalboard") { self.transportControls.setControlEnabled(portSymbol, enabled, feedback, forceAddress, momentaryMode) return } self.pedalboard.pedalboard('setPortEnabled', instance, portSymbol, enabled, feedback, forceAddress, momentaryMode) }, renderForm: function (instance, port) { var label if (instance == "/pedalboard") { label = "Pedalboard" } else { label = self.pedalboard.pedalboard('getLabel', instance) } if (port.symbol == ':bypass' || port.symbol == ':presets') { context = { label: label, name: port.symbol == ':bypass' ? "On/Off" : port.name } return Mustache.render(TEMPLATES.bypass_addressing, context) } context = { label: label, name: port.shortName } return Mustache.render(TEMPLATES.addressing, context) }, isApp: function() { return self.isApp; }, }) this.pedalPresets = new SnapshotsManager({ pedalPresetsWindow: elements.pedalPresetsWindow, pedalPresetsList: elements.pedalPresetsList, pedalPresetsOverlay: elements.pedalPresetsOverlay, hardwareManager: self.hardwareManager, renamedCallback: function (name) { const newTitle = (self.title || 'Untitled') + " - " + (name || 'Default') self.titleBox.text(newTitle) self.performanceTitleBox.text(newTitle) } }) this.isApp = false this.title = '' this.cloudAccessToken = null this.cloudHardwareDeviceVersions = null this.pedalboardBundle = null this.pedalboardEmpty = true this.pedalboardModified = false this.pedalboardPresetId = 0 this.pedalboardPresetName = '' this.pedalboardDemoPluginsNotified = false this.loadingPeldaboardForFirstTime = true this.licenseManager = null this.pedalboard = self.makePedalboard(elements.pedalboard, elements.effectBox) elements.zoomIn.click(function () { self.pedalboard.pedalboard('zoomIn') }) elements.zoomOut.click(function () { self.pedalboard.pedalboard('zoomOut') }) var ajaxFactory = function (url, errorMessage) { return function (callback) { $.ajax({ url: url, success: callback, error: function () { new Error(errorMessage) }, cache: false, dataType: 'json' }) } } elements.pedalboardTrigger.click(function () { self.windowManager.closeWindows(null, true) }) this.titleBox = elements.titleBox this.performanceTitleBox = elements.performanceTitleBox this.ParameterSet = function (paramchange) { $.ajax({ url: '/effect/parameter/set/' , type: 'POST', contentType: 'application/json', data: JSON.stringify(paramchange), success: function (resp) { if (!resp) { new Bug("Couldn't address parameter, not allowed") } }, error: function () { new Bug ("Couldn't address parameter, server error") }, cache: false, global: false, dataType: 'json' }) } this.cloudPluginListFunction = function (callback) { $.ajax({ method: 'GET', url: '/effect/list', success: callback, cache: false, dataType: 'json', }) } this.cloudPluginSearchFunction = function (query, callback) { $.ajax({ method: 'GET', url: '/effect/search', query: query, success: callback, cache: false, dataType: 'json' }) } this.pedalboardListFunction = function (callback) { if (self.previousPedalboardList != null && callback) { callback(self.previousPedalboardList) return } $.ajax({ method: 'GET', url: '/pedalboard/list', success: function(pedals) { var allpedals = {} for (var i=0; i') if (isUpdating) { block.html('

Auto-update in progress, please wait...

') } else { block.html('

Disconnected

') var re = $("
Reload
").appendTo(block); re.css("background-image", "url(img/icons/25/reload.png)"); re.click(function () { location.reload(); }); } $('body').append(block).css('overflow', 'hidden') $('#wrapper').css('z-index', -1) $('#plugins-library').css('z-index', -1) $('#cloud-plugins-library').css('z-index', -1) $('#performance').css('z-index', -1) $('#pedalboards-library').css('z-index', -1) $('#bank-library').css('z-index', -1) $('#main-menu').css('z-index', -1) ws.close() } this.init = function () { $(".mod-init-hidden").removeClass("mod-init-hidden"); $("body").addClass("initialized"); } this.authenticateDevice = function (callback) { $.ajax({ method: 'GET', url: SITEURL + '/devices/nonce', cache: false, success: function (resp) { if (!resp || !resp.nonce) { callback(false) return } $.ajax({ url: '/auth/nonce', type: 'POST', cache: false, contentType: 'application/json', dataType: 'json', data: JSON.stringify(resp), success: function (resp) { if (!resp || !resp.message) { //$('#mod-cloud-plugins').hide() callback(false) console.log("Webserver does not support MOD tokens, downloads will not be possible") return; } $.ajax({ url: SITEURL + '/devices/tokens', type: 'POST', cache: false, contentType: 'application/json', dataType: 'json', data: JSON.stringify(resp), success: function (resp) { if (!resp || !resp.message) { callback(false) return; } var license_info = resp.license_info; if (resp['upgrade']) { $.ajax({ method: 'GET', url: resp['image-href'], cache: false, contentType: 'application/json', success: function (data) { elements.upgradeWindow.upgradeWindow('setup', resp['upgrade-required'], data) }, error: function () { elements.upgradeWindow.upgradeWindow('setErrored') }, }) } else { elements.upgradeWindow.upgradeWindow('setUpdated') } $.ajax({ url: '/auth/token', type: 'POST', cache: false, contentType: 'application/json', dataType: 'json', data: JSON.stringify(resp), success: function (resp) { self.cloudAccessToken = resp.access_token; var opts = { from_args: { headers: { 'Authorization' : 'MOD ' + resp.access_token } } } if (self.licenseManager === null) { self.licenseManager = new LicenseManager() self.licenseManager.addLicenses(license_info, function(installed) { if (installed > 0) { var s = installed > 1 ? 's' : '' new Notification('info', installed + ' plugin'+s+' licensed') } }) } callback(true, opts); }, error: function () { callback(false); }, }) }, error: function () { callback(false) }, }) }, error: function () { callback(false) }, }) }, error: function () { callback(false) }, }) } this.setPedalboardAsModified = function (modified) { this.pedalboardModified = modified if (modified) { elements.saveButton.addClass('unmodified-changes') } else { elements.saveButton.removeClass('unmodified-changes') } } elements.devicesIcon.statusTooltip() this.ccDeviceManager = new ControlChainDeviceManager({ devicesIcon: elements.devicesIcon, devicesWindow: elements.devicesWindow, updateInfoWindow: elements.updateDeviceWindow, setIconTooltip: function (msg) { elements.devicesIcon.statusTooltip('message', msg, true) }, showNotification: function (msg) { if (! self.loadingPeldaboardForFirstTime) { new Notification('info', msg, 5000) } }, cancelDownload: function (callback) { $.ajax({ url: '/controlchain/cancel/', type: 'POST', success: function () { callback() }, error: function () { callback() }, cache: false, dataType: 'json' }) }, }) this.ccDeviceAdded = function (dev_uri, label, labelsuffix, version) { self.ccDeviceManager.deviceAdded(dev_uri, label+labelsuffix, version) self.checkHardwareDeviceVersion(dev_uri, label, version) } this.ccDeviceRemoved = function (dev_uri, label, version) { self.ccDeviceManager.deviceRemoved(dev_uri, label, version) elements.upgradeWindow.upgradeWindow('cancelDeviceSetup', dev_uri) } this.ccDeviceUpdateFinished = function () { elements.upgradeWindow.upgradeWindow('setUpdated') elements.upgradeWindow.hide() self.ccDeviceManager.hideUpdateWindow() new Notification("info", "Control Chain device firmware update complete!") } this.cpuLoadPanel = new CpuLoadPanel({ window: elements.cpuLoadWindow, list: elements.cpuLoadList, summary: elements.cpuLoadSummary, pedalboard: elements.pedalboard, }) this.transportControls = new TransportControls({ transportButton: elements.transportButton, transportWindow: elements.transportWindow, transportPlay: elements.transportPlay, transportBPB: elements.transportBPB, transportBPM: elements.transportBPM, transportSyncMode: elements.transportSyncMode, openAddressingDialog: function (port, label) { self.hardwareManager.open("/pedalboard", port, label) }, setNewBeatsPerMinuteValue: function (bpm) { self.hardwareManager.setBeatsPerMinuteValue(bpm) }, removeBPMHardwareMapping: function(syncMode) { var instanceAndSymbol = "/pedalboard/:bpm" if (self.hardwareManager.removeHardwareMappping(instanceAndSymbol)) { var source = syncMode === "link" ? "Ableton Link" : "MIDI" new Notification('info', 'BPM addressing removed, incompatible with ' + source + ' sync mode', 8000) } self.setPedalboardAsModified(true) }, setSyncMode: function(syncMode, callback) { $.ajax({ url: '/pedalboard/transport/set_sync_mode/' + syncMode, type: 'POST', success: function (resp) { if (resp) { callback(true) } else { new Bug("Couldn't set new sync mode") callback(false) } }, error: function () { new Bug("Couldn't set new sync mode, server error") callback(false) }, cache: false, dataType: 'json' }) }, unaddressPort: function (portSymbol, syncMode, callback) { var addressing = { uri : kNullAddressURI, label : "", minimum: 0, maximum: 0, value : 0, steps : 0, } var instanceAndSymbol = "/pedalboard/" + portSymbol $.ajax({ url: '/effect/parameter/address/' + instanceAndSymbol, type: 'POST', data: JSON.stringify(addressing), success: function (resp) { if (resp) { if (self.hardwareManager.removeHardwareMappping(instanceAndSymbol)) { var source = syncMode === "link" ? "Ableton Link" : "MIDI" new Notification('info', 'BPM addressing removed, incompatible with ' + source + ' sync mode', 8000) } self.setPedalboardAsModified(true) callback(true) } else { new Bug("Couldn't address parameter") callback(false) } }, error: function () { new Bug("Couldn't address parameter, server error") callback(false) }, cache: false, dataType: 'json' }) }, }) this.checkHardwareDeviceVersion = function (dev_uri, label, version) { if (self.cloudAccessToken == null) { self.authenticateDevice(function (ok) { if (ok && self.cloudAccessToken != null) { self.checkHardwareDeviceVersion(dev_uri, label, version) } else { console.log("Notice: failed to check device version") } }) return } if (self.cloudHardwareDeviceVersions == null) { $.ajax({ method: 'GET', url: CONTROLCHAIN_URL + '/versions', success: function (resp) { if (!resp) { console.log("Notice: failed to get latest device version") return } if (resp.api_version != 1) { return } self.cloudHardwareDeviceVersions = resp self.checkHardwareDeviceVersion(dev_uri, label, version) }, error: function (resp) { console.log("Notice: failed to get latest device version") }, cache: false, dataType: 'json' }) return } var devs = self.cloudHardwareDeviceVersions.devices if (! devs || Object.keys(devs).length == 0) { return } var dev = devs[dev_uri] if (! dev) { return } var majminor = VERSION.split(".").slice(0, 2).join(".") var cloudversion = dev[majminor] if (! cloudversion) { cloudversion = dev["latest"] if (! cloudversion) { return } } if (compareVersions(version.split("."), cloudversion.split("."), 3) < 0) { data = { 'uri': dev_uri, 'label': label, 'download-url': CONTROLCHAIN_URL + "/file/" + label + cloudversion + ".bin", 'release-url': "http://wiki.moddevices.com/wiki/Control_Chain_Releases#" + label + "," + cloudversion } elements.upgradeWindow.upgradeWindow('setupDevice', data) } } this.validatePlugins = function (uris, callback) { $.ajax({ url: SITEURL + '/pedalboards/validate/', method: 'POST', contentType: 'application/json', data: JSON.stringify({ uris: uris, }), success: function (resp) { if (! resp.result) { callback(false) return } callback(true) }, error: function (resp) { new Bug("Couldn't validate pedalboard, error:
" + resp.statusText) }, cache: false, dataType: 'json' }) } this.saveConfigValue = function (key, value, callback) { $.ajax({ url: '/config/set', type: 'POST', data: { key : key, value: value, }, success: function () { if (callback) { callback(true) PREFERENCES[key] = value } }, error: function () { if (callback) { callback(false) } }, cache: false, dataType: 'json' }) } this.setupDeviceAuthentication = function () { self.authenticateDevice(function (ok) { if (ok) { console.log("MOD authentication succeeded") self.resetPedalboardStats(); } else { console.log("MOD authentication failed") self.upgradeWindow.upgradeWindow('setErrored') } }) } this.setupMatomo = function() { // Analytics is for the desktop app only; a MOD device never loads the tracker if (USING_MOD_DEVICE) { return } var _mtm = window._mtm = window._mtm || []; _mtm.push({'mtm.startTime': (new Date().getTime()), 'event': 'mtm.Start'}); (function() { var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.async=true; g.src='https://cdn.matomo.cloud/modaudio.matomo.cloud/container_DfEOyKDN.js'; s.parentNode.insertBefore(g,s); })(); } this.effectBox = self.makeEffectBox(elements.effectBox, elements.effectBoxTrigger) this.performanceBox = self.makePerformanceBox(elements.performanceBox, elements.performanceBoxTrigger) this.cloudPluginBox = self.makeCloudPluginBox(elements.cloudPluginBox, elements.cloudPluginBoxTrigger) this.pedalboardBox = self.makePedalboardBox(elements.pedalboardBox, elements.pedalboardBoxTrigger) this.bankBox = self.makeBankBox(elements.bankBox, elements.bankBoxTrigger) this.fileManagerBox = self.makeFileManagerBox(elements.fileManagerBox, elements.fileManagerBoxTrigger) this.getPluginsData = function (uris, callback) { $.ajax({ url: '/effect/bulk/', type: 'POST', contentType: 'application/json', data: JSON.stringify(uris), success: callback, cache: false, dataType: 'json' }) } this.installMissingPlugins = function (plugins, callback) { if (self.isApp) { new Notification('warn', "Cannot load this pedalboard, some plugins are missing", 4000) callback(false) return } var missingCount = 0 var versions = {} var uris = [] var error = false // make list of uris for (var i in plugins) { var plugin = plugins[i] if (uris.indexOf(plugin.uri) < 0) { versions[plugin.uri] = [plugin.builder || 0, plugin.minorVersion, plugin.microVersion, plugin.release || 0] uris.push(plugin.uri) } } var finalCallback = function () { self.previousPedalboardList = null if (error && !confirm("Failed to install some required plugins, do you want to load the pedalboard anyway?")) { callback(false) return } callback(true) } var installPlugin = function (uri, data) { missingCount++ self.installationQueue.installUsingURI(uri, function (resp, bundlename) { if (! resp.ok) { error = true } missingCount-- if (missingCount == 0) { finalCallback() } }) } var installMissing = function (data) { for (var i in uris) { var uri = uris[i] var localplugin = data[uri] if (localplugin == null) { installPlugin(uri, data) } else { var version = [localplugin.builder || 0, localplugin.minorVersion, localplugin.microVersion, localplugin.release || 0] if (compareVersions(version, versions[uri]) < 0) { installPlugin(uri, data) } } } if (missingCount == 0) { finalCallback() } } this.getPluginsData(uris, installMissing) }, this.loadRemotePedalboard = function (pedalboard_id) { if (! CLOUD_TERMS_ACCEPTED) { return } self.windowManager.closeWindows(null, true) if (self.cloudAccessToken == null) { self.authenticateDevice(function (ok) { if (ok && self.cloudAccessToken != null) { self.loadRemotePedalboard(pedalboard_id) } else { new Notification('error', "Cannot load remote pedalboards, authentication failure") } }) return } $.ajax({ url: startsWith(pedalboard_id, 'https://') ? pedalboard_id : (SITEURL + '/pedalboards/' + pedalboard_id), contentType: 'application/json', success: function (resp) { if (resp.data.stable === false && PREFERENCES['show-unstable-plugins'] !== "true") { new Notification('error', 'This pedalboard contains beta plugins. To load it, you need to enable beta plugins in Settings -> Developer'); return; } self.reset(function () { self.installMissingPlugins(resp.data.plugins, function (ok) { if (ok) { var transfer = new SimpleTransference(resp.file_href, '/pedalboard/load_web/', { from_args: { headers: { 'Authorization' : 'MOD ' + self.cloudAccessToken } }}) transfer.reauthorizeDownload = self.authenticateDevice transfer.reportFinished = function () { self.pedalboardEmpty = false self.setPedalboardAsModified(true) } transfer.reportError = function (error) { new Bug("Couldn't load pedalboard, reason:
" + error) } transfer.start() } else { self.pedalboard.data('wait').stop() } }) }, true) }, error: function (resp) { new Bug("Couldn't get pedalboard info, error:
" + resp.statusText) }, cache: false, dataType: 'json' }) }, this.waitForScreenshot = function (generate, bundlepath, callback) { pending_pedalboard_screenshots.push(bundlepath) if (generate) { $.ajax({ url: "/pedalboard/image/generate?bundlepath="+escape(bundlepath), success: function (resp) { callback(resp.ok) }, error: function () { callback(false) }, cache: false, dataType: 'json' }) } else { $.ajax({ url: "/pedalboard/image/wait?bundlepath="+escape(bundlepath), success: function (resp) { callback(resp.ok) }, error: function () { callback(false) }, cache: false, dataType: 'json' }) } }, this.saveBox = elements.saveBox.saveBox({ save: function (windotTitle, name, asNew, callback) { $.ajax({ url: '/pedalboard/save', type: 'POST', data: { title: name, asNew: asNew ? 1 : 0 }, success: function (result) { if (result.ok) { // dummy call to keep 1 ajax request active while screenshot is generated self.waitForScreenshot(false, result.bundlepath, function(){}) // all set callback(true, result.bundlepath, result.title) _paq.push(['trackEvent', 'pedalboard', 'pedalboard-save']) } else { callback(false, "Failed to save") } }, error: function (resp) { self.saveBox.hide() callback(false, "Couldn't save pedalboard") }, cache: false, dataType: 'json' }); } }) this.presetSaveBox = elements.presetSaveBox.saveBox({ save: function (windotTitle, name, asNew, callback) { callback(true, "", name) } }) this.inputBox = elements.inputBox.inputBox({}) elements.addMidiButton.click(function () { self.showMidiDeviceList() }) elements.saveButton.click(function () { self.saveCurrentPedalboard(false) }) elements.saveAsButton.click(function () { self.saveCurrentPedalboard(true) }) elements.cvAddressingButton.click(function () { // Show/hide CV checkboxes if ($(this).hasClass('selected')) { $('body').find('.output-cv-checkbox').hide() } else { $('body').find('.output-cv-checkbox').show() } // Toggle cvAddressing and button state self.cvAddressing = !self.cvAddressing self.pedalboard.pedalboard('setCvAddressing', self.cvAddressing) $(this).toggleClass('selected') }) elements.resetButton.click(function () { self.reset(function () { $.ajax({ url: '/pedalboard/load_bundle/', type: 'POST', data: { bundlepath: DEFAULT_PEDALBOARD, isDefault: '1', }, cache: false, dataType: 'json' }) }) }) elements.snapshotSaveButton.click(function () { if (self.pedalboardPresetId < 0) { return new Notification('warn', 'Nothing to save', 1500) } $.ajax({ url: '/snapshot/save', method: 'POST', success: function () { new Notification('info', 'Pedalboard snapshot saved', 2000) }, error: function () { new Bug("Failed to save pedalboard snapshot") }, cache: false, dataType: 'json', }) }) elements.snapshotSaveAsButton.click(function () { var addressed = !!self.hardwareManager.addressingsByPortSymbol['/pedalboard/:presets'] if (addressed) { return new Notification("warn", "Cannot change snapshot while addressed to hardware", 3000) } desktop.openPresetSaveWindow("Saving Snapshot", "", function (newName) { $.ajax({ url: '/snapshot/saveas', data: { title: newName, }, success: function (resp) { if (! resp.ok) { return } self.pedalboardPresetId = resp.id self.pedalboardPresetName = resp.title const newTitle = (self.title || 'Untitled') + " - " + resp.title self.titleBox.text(newTitle) self.performanceTitleBox.text(newTitle) new Notification('info', 'Pedalboard snapshot saved', 2000) }, error: function () { new Bug("Failed to save pedalboard snapshot") }, cache: false, dataType: 'json', }) }) }) elements.snapshotManageButton.click(function () { var addressed = !!self.hardwareManager.addressingsByPortSymbol['/pedalboard/:presets'] var feedback = true if (addressed) { console.log(self.hardwareManager.addressingsData['/pedalboard/:presets']) feedback = self.hardwareManager.addressingsData['/pedalboard/:presets'].feedback } self.pedalPresets.start(self.pedalboardPresetId, addressed, feedback) }) elements.bypassLeftButton.click(function () { self.triggerTrueBypass("Left", !$(this).hasClass("bypassed")) }) elements.bypassRightButton.click(function () { self.triggerTrueBypass("Right", !$(this).hasClass("bypassed")) }) elements.bufferSizeButton.click(function () { var newsize if ($(this).text() == "128 frames") { newsize = '256' } else { newsize = '128' } $.ajax({ url: '/set_buffersize/' + newsize, method: 'POST', cache: false, success: function (resp) { if (! resp.ok) { new Bug("Couldn't set new buffer size") } }, error: function () { new Bug("Communication failure") }, }) }) elements.xrunsButton.click(function () { if (cached_xruns == 0) { return } $.ajax({ url: '/reset_xruns/', method: 'POST', cache: false, success: function (ok) { if (ok) { cached_xruns = 0 $("#mod-xruns").text("0 Xruns") } } }) }) elements.cpuButton.click(function () { self.cpuLoadPanel.toggle() }) elements.cpuLoadWindow.find('.js-close').click(function () { self.cpuLoadPanel.close() }) elements.cpuLoadWindow.find('.js-reset-peaks').click(function () { self.cpuLoadPanel.reset() }) elements.cpuLoadWindow.click(function (e) { if (e.target === this) { self.cpuLoadPanel.close() } }) elements.cpuStatsButton.click(function () { $.ajax({ url: '/switch_cpu_freq/', method: 'POST', cache: false, success: function (ok) { if (! ok) { new Bug("Couldn't set new cpu frequency") } }, error: function () { new Bug("Communication failure") }, }) }) elements.shareButton.click(function () { var share = function () { if (self.pedalboardEmpty) { return new Notification('warn', 'Nothing to share', 1500) } var uris = self.pedalboard.pedalboard('getLoadedPluginURIs') if (uris.length == 0) { return new Notification('warn', 'No plugins loaded, cannot share', 1500) } self.validatePlugins(uris, function (stable) { elements.shareWindow.shareBox('open', self.pedalboardBundle, self.title, stable) }) } if (self.pedalboardModified || ! (self.pedalboardEmpty || self.pedalboardBundle)) { if (confirm('There are unsaved modifications, pedalboard must first be saved. Save it?')) { self.saveCurrentPedalboard(false, share) } } else { share() } }) elements.shareWindow.shareBox({ recordStart: ajaxFactory('/recording/start', "Can't record. Probably a connection problem."), recordStop: ajaxFactory('/recording/stop', "Can't stop record. Probably a connection problem. Please try stopping again"), playStart: function (startCallback, stopCallback) { $.ajax({ url: '/recording/play/start', success: function (resp) { $.ajax({ url: '/recording/play/wait', success: stopCallback, error: function () { new Error("Couln't check when sample playing has ended") }, cache: false, dataType: 'json' }) startCallback(resp) }, error: function () { new Error("Can't play. Probably a connection problem.") }, cache: false, dataType: 'json' }) }, playStop: ajaxFactory('/recording/play/stop', "Can't stop playing. Probably a connection problem. Please try stopping again"), recordDownload: ajaxFactory('/recording/download', "Can't download recording. Probably a connection problem."), recordReset: ajaxFactory('/recording/reset', "Can't reset your recording. Probably a connection problem."), share: function (data, callback) { if (! data.reauthorized) { // save user data $.ajax({ url: '/save_user_id/', method: 'POST', data: data, success: function () {}, error: function () {}, cache: false, global: false, dataType: 'json', }) } if (! CLOUD_TERMS_ACCEPTED) { return } if (self.cloudAccessToken == null) { self.authenticateDevice(function (ok) { if (ok && self.cloudAccessToken != null) { elements.shareWindow.shareBox('share', data, callback) } else { callback({ ok: false, error: "authentication failure" }) } }) return } // pack & upload to cloud $.ajax({ url: SITEURL + '/pedalboards/', method: 'POST', contentType: 'application/json', headers: { 'Authorization' : 'MOD ' + self.cloudAccessToken }, data: JSON.stringify({ author : data.name, email : data.email, description: data.description, title : data.title, hidden : data.hidden, }), success: function (resp) { var transfer = new SimpleTransference('/pedalboard/pack_bundle/?bundlepath=' + escape(self.pedalboardBundle), resp.upload_href, { to_args: { headers: { 'Authorization' : 'MOD ' + self.cloudAccessToken } }}) transfer.reauthorizeUpload = self.authenticateDevice; transfer.reportFinished = function (resp2) { callback({ ok: true, id: resp.id, }) } transfer.reportError = function (error) { callback({ ok: false, error: "Failed to upload pedalboard to cloud (missing screenshot?)", }) } transfer.start() }, error: function (resp) { if (resp.status == 401 && ! data.reauthorized) { console.log("Pedalboard share unauthorized, retrying authentication...") data.reauthorized = true self.authenticateDevice(function (ok, options) { if (ok) { console.log("Authentication succeeded") self.options = $.extend(self.options, options) elements.shareWindow.shareBox('share', data, callback) } else { console.log("Authentication failed") callback({ ok: false, error: resp.statusText }) } }) return; } callback({ ok: false, error: resp.statusText }) }, cache: false, dataType: 'json' }) }, waitForScreenshot: self.waitForScreenshot, }) elements.statusIcon.statusTooltip() this.networkStatus = new NetworkStatus({ icon: elements.statusIcon, notify: function (msg) { elements.statusIcon.statusTooltip('message', msg, true) } }) elements.settingsIcon.click(function() { document.location.href = '/settings'; }) elements.settingsIcon.statusTooltip() elements.pedalboardTrigger.statusTooltip() elements.performanceBoxTrigger.statusTooltip() elements.pedalboardBoxTrigger.statusTooltip() elements.bankBoxTrigger.statusTooltip() elements.cloudPluginBoxTrigger.statusTooltip() elements.fileManagerBoxTrigger.statusTooltip() this.upgradeWindow = elements.upgradeWindow.upgradeWindow({ icon: elements.upgradeIcon, windowManager: self.windowManager, startUpgrade: function (callback) { $.ajax({ type: 'POST', url: '/update/begin', success: function (ok) { callback(ok) }, error: function () { callback(false) }, cache: false, dataType: 'json', }) }, startDeviceUpgrade: function () { self.ccDeviceManager.showUpdateWindow() }, }) this.onPedalboardLoadComplete = function (callback) { if (callback) { callback() } } // this callback is called when the pedalboard is loaded for the first time this.onPedalboardFirstLoadComplete = function (callback) { // The plugin bar does not depend on the board, so the first fit no longer waits for // its list (and 300-odd thumbnails on a device) to load. self.effectBox.effectBox('search', function () { setTimeout(function () { // if is a touch device, open performance view by default if (self.isTouchDevice) { elements.performanceBoxTrigger.click() } }, 500) }) self.onPedalboardLoadComplete(callback) } var prevent = function (ev) { ev.preventDefault() } $('body')[0].addEventListener('gesturestart', prevent) $('body')[0].addEventListener('gesturechange', prevent) $('body')[0].addEventListener('touchmove', prevent) $('body')[0].addEventListener('dblclick', prevent) } Desktop.prototype.makePedalboard = function (el, effectBox) { var self = this el.pedalboard({ windowManager: self.windowManager, hardwareManager: self.hardwareManager, bottomMargin: effectBox.height(), cvAddressing: self.cvAddressing, pluginLoad: function (uri, instance, x, y, callback, errorCallback) { var firstTry = true var add = function () { $.ajax({ url: '/effect/add/' + instance + '?x=' + x + '&y=' + y + '&uri=' + escape(uri), success: function (pluginData) { if (pluginData) { callback(pluginData) } else { new Notification('error', 'Error adding effect') if (errorCallback) errorCallback() } }, error: function (resp) { new Notification('error', 'Error adding effect. Probably a connection problem.') if (errorCallback) errorCallback() }, cache: false, dataType: 'json' }) } add() }, pluginRemove: function (instance, callback) { $.ajax({ url: '/effect/remove/' + instance, success: function (resp) { if (resp) callback() else new Notification("error", "Couldn't remove effect") }, cache: false, dataType: 'json' }) }, pluginPresetLoad: function (instance, uri, callback) { $.ajax({ url: '/effect/preset/load/' + instance, data: { uri: uri }, success: function (resp) { callback(resp) }, error: function () { }, cache: false, dataType: 'json' }) }, pluginPresetSaveNew: function (instance, name, callback) { $.ajax({ url: '/effect/preset/save_new/' + instance, data: { name: name }, success: function (resp) { callback(resp) }, error: function () { }, cache: false, dataType: 'json' }) }, pluginPresetSaveReplace: function (instance, uri, bundlepath, name, callback) { $.ajax({ url: '/effect/preset/save_replace/' + instance, data: { uri : uri, bundle: bundlepath, name : name }, success: function (resp) { callback(resp) }, error: function () { }, cache: false, dataType: 'json' }) }, // .modpreset download of the current plugin settings pluginPresetExport: function (instance, name, callback) { var xhr = new XMLHttpRequest() xhr.open('GET', '/effect/preset/export' + instance + '?name=' + encodeURIComponent(name) + '&_=' + Date.now()) xhr.responseType = 'blob' xhr.onload = function () { if (xhr.status != 200) { var reader = new FileReader() reader.onload = function () { callback({ ok: false, error: reader.result || "Export failed" }) } reader.readAsText(xhr.response) return } var filename = xhr.getResponseHeader('X-Modpreset-Filename') || 'preset.modpreset' var url = URL.createObjectURL(xhr.response) var a = $('').attr('href', url).attr('download', filename).appendTo('body') a[0].click() setTimeout(function () { a.remove() URL.revokeObjectURL(url) }, 1000) callback({ ok: true, filename: filename, leftOut: parseInt(xhr.getResponseHeader('X-Modpreset-Left-Out') || '0'), }) } xhr.onerror = function () { callback({ ok: false, error: "Export failed" }) } xhr.send() }, // .modpreset file (a File from an ) installed as a user preset pluginPresetImport: function (instance, file, callback) { $.ajax({ url: '/effect/preset/import' + instance, method: 'POST', data: file, processData: false, contentType: 'application/octet-stream', success: function (resp) { callback(resp) }, error: function () { callback({ ok: false, error: "Import failed" }) }, cache: false, dataType: 'json' }) }, pluginPresetDelete: function (instance, uri, bundlepath, callback) { $.ajax({ url: '/effect/preset/delete/' + instance, data: { uri : uri, bundle: bundlepath }, success: function (resp) { callback(resp) }, error: function () { }, cache: false, dataType: 'json' }) }, portConnect: function (fromPort, toPort, callback) { var urlParam = fromPort + ',' + toPort $.ajax({ url: '/effect/connect/' + urlParam, success: function (resp) { callback(resp) if (!resp) { console.log('erro') } }, cache: false, dataType: 'json' }) }, portDisconnect: function (fromPort, toPort, callback) { var urlParam = fromPort + ',' + toPort $.ajax({ url: '/effect/disconnect/' + urlParam, success: function () { callback(true) }, cache: false, dataType: 'json' }) }, reset: function (callback) { $.ajax({ url: '/reset', success: function (resp) { if (!resp) { return new Notification('error', "Couldn't reset pedalboard") } self.title = '' self.pedalboardBundle = null self.pedalboardEmpty = true self.pedalboardPresetId = 0 self.pedalboardPresetName = '' self.pedalboardDemoPluginsNotified = false self.titleBox.text('Untitled') self.performanceTitleBox.text('Untitled') self.titleBox.addClass("blend") self.transportControls.resetControlsEnabled() self.setPedalboardAsModified(false) callback(true) }, error: function () { new Bug("Couldn't reset pedalboard") }, cache: false }) }, getPluginsData: self.getPluginsData, showPluginInfo: function (pluginData) { pluginData.installedVersion = [pluginData.builder, pluginData.minorVersion, pluginData.microVersion, pluginData.release] self.effectBox.effectBox('showPluginInfo', pluginData) }, showExternalUI: function (instance) { ws.send(sprintf("show_external_ui %s", instance)) }, pluginParameterChange: function (port, value) { self.setPedalboardAsModified(true) ws.send(sprintf("param_set %s %f", port, value)) }, pluginPatchGet: function (instance, uri) { ws.send(sprintf("patch_get %s %s", instance, uri)) }, pluginPatchSet: function (instance, uri, valuetype, value) { self.setPedalboardAsModified(true) ws.send(sprintf("patch_set %s %s %s %s", instance, uri, valuetype, value)) }, pluginMove: function (instance, x, y) { self.setPedalboardAsModified(true) ws.send(sprintf("plugin_pos %s %f %f", instance, x, y)) }, /* * Set the label of a plugin instance * label: string or null, undefined, empty string to reset to default */ pluginLabelSet: function (instance, label) { self.setPedalboardAsModified(true) ws.send(sprintf("plugin_label %s %s", instance, label?.replace(/ /g, '_'))) }, /* * Set if the plugin instance should be displayed on the performance view * visible: true to display, else false */ performancePluginVisibilitySet: function (instance, visible) { self.setPedalboardAsModified(true) ws.send(sprintf("performance_plugin_visibility %s %s", instance, (visible ? "1" : "0"))) }, /* * Set if the order of the plugin instance in the performance view * index: order */ performancePluginIndexSet: function (instance, index) { self.setPedalboardAsModified(true) ws.send(sprintf("performance_plugin_index %s %d", instance, index)) }, windowSize: function (width, height) { // FIXME if (ws && width > 0 && height > 0) { ws.send(sprintf("pb_size %f %f", width, height)) } }, pedalboardFinishedLoading: function (callback) { if (self.loadingPeldaboardForFirstTime) { self.loadingPeldaboardForFirstTime = false self.onPedalboardFirstLoadComplete(callback) } else { self.onPedalboardLoadComplete(callback) } }, addCVAddressingPluginPort: function (uri, name, callback) { $.ajax({ url: '/pedalboard/cv_addressing_plugin_port/add', type: 'POST', data: { uri: uri, name: name, }, success: function (resp) { if (!resp) { return new Notification('error', "Couldn't add CV port") } callback(resp) }, error: function () { new Bug("Couldn't add CV port") }, cache: false, dataType: 'json' }) }, removeCVAddressingPluginPort: function (uri, callback) { $.ajax({ url: '/pedalboard/cv_addressing_plugin_port/remove', type: 'POST', data: { uri: uri, }, success: function (resp) { if (!resp) { return new Notification('error', "Couldn't remove CV port") } callback(resp) }, error: function () { new Bug("Couldn't remove CV port") }, cache: false, dataType: 'json' }) }, notifyDemoPluginLoaded: function () { if (self.pedalboardDemoPluginsNotified) { return } self.pedalboardDemoPluginsNotified = true new Notification('warn', 'This pedalboard contains a trial plugin.
Using trial plugins will intentionally mute the audio at regular intervals.') }, }); // Bind events el.bind('modified', function () { self.pedalboardEmpty = false self.setPedalboardAsModified(true) }) /* el.bind('dragStart', function () { self.windowManager.closeWindows(null, true) }) */ el.bind('pluginDragStart', function () { self.effectBox.addClass('fade') }) el.bind('pluginDragStop', function () { self.effectBox.removeClass('fade') }) return el } Desktop.prototype.makePedalboardBox = function (el, trigger) { var self = this return el.pedalboardBox({ trigger: trigger, windowManager: this.windowManager, list: self.pedalboardListFunction, search: self.pedalboardSearchFunction, saveConfigValue: self.saveConfigValue, exportFile: function (pedalboard) { self.exportPedalboardFile(pedalboard) }, importFile: function (file, callback) { self.importPedalboardFile(file, callback) }, remove: function (pedalboard, callback) { if (!confirm(sprintf('The pedalboard "%s" will be permanently removed! Confirm?', pedalboard.title))) return $.ajax({ url: '/pedalboard/remove/', data: { bundlepath: pedalboard.bundle }, success: function () { new Notification("info", sprintf('Pedalboard "%s" removed', pedalboard.title), 1000) self.previousPedalboardList = null callback() }, error: function () { new Bug("Couldn't remove pedalboard") }, cache: false }) }, load: function (bundlepath, broken, callback) { if (!broken) { self.loadPedalboard(bundlepath, callback) return } $.ajax({ url: '/pedalboard/info/', data: { bundlepath: bundlepath }, success: function (pbinfo) { self.reset(function () { self.installMissingPlugins(pbinfo.plugins, function (ok) { if (ok) { self.loadPedalboard(bundlepath, callback) } else { self.pedalboard.data('wait').stop() } }) }) }, error: function () { new Bug("Couldn't load pedalboard") }, cache: false }) }, }) } Desktop.prototype.makePerformanceBox = function (el, trigger) { return el.performanceBox({ trigger: trigger, windowManager: this.windowManager, pedalboard: this.pedalboard, pedalPresets: this.pedalPresets, saveConfigValue: self.saveConfigValue, }) } Desktop.prototype.makeEffectBox = function (el, trigger) { var self = this return el.effectBox({ trigger: trigger, windowManager: this.windowManager, pedalboard: this.pedalboard, saveConfigValue: this.saveConfigValue, }) } Desktop.prototype.makeCloudPluginBox = function (el, trigger) { var self = this return el.cloudPluginBox({ trigger: trigger, windowManager: this.windowManager, list: self.cloudPluginListFunction, removePluginBundles: function (bundles, callback) { if (!confirm('You are about to remove this plugin and any other in the same bundle. This may break pedalboards that depend on them.')) return self.previousPedalboardList = null $.ajax({ url: '/package/uninstall', data: JSON.stringify(bundles), method: 'POST', success: function(resp) { if (resp.ok) { callback(resp) } else { new Notification('error', "Could not uninstall bundle: " + resp.error) } }, error: function () { new Notification('error', "Failed to uninstall plugin") }, cache: false, dataType: 'json' }) }, upgradePluginURI: function (uri, callback) { self.previousPedalboardList = null self.installationQueue.installUsingURI(uri, callback) }, installPluginURI: function (uri, callback) { self.previousPedalboardList = null self.installationQueue.installUsingURI(uri, callback) } }) } Desktop.prototype.makeBankBox = function (el, trigger) { var self = this el.bankBox({ trigger: trigger, windowManager: this.windowManager, list: self.pedalboardListFunction, search: self.pedalboardSearchFunction, load: function (callback) { $.ajax({ url: '/banks', success: callback, error: function () { new Bug("Couldn't load banks") }, cache: false, dataType: 'json', }) }, save: function (data, callback) { $.ajax({ type: 'POST', url: '/banks/save', data: JSON.stringify(data), success: callback, error: function () { new Bug("Couldn't save banks") }, cache: false, }) }, copyFactoryPedalboard: function (bundlepath, title, callback) { $.ajax({ url: '/pedalboard/factorycopy/', data: { bundlepath: bundlepath, title: title, }, success: function (resp) { if (resp) { self.previousPedalboardList = null new Notification('warning', 'Factory pedalboard was duplicated into the User Pedalboards Library') callback(resp) } else { new Bug("Could not copy factory pedalboard") } }, error: function () { new Bug("Failed to copy factory pedalboard") }, cache: false }) }, }) } Desktop.prototype.makeFileManagerBox = function (el, trigger) { var self = this el.fileManagerBox({ trigger: trigger, windowManager: this.windowManager, }) } Desktop.prototype.reset = function (callback, skipConfirmDialog) { if (this.pedalboardModified && !skipConfirmDialog && !confirm("There are unsaved modifications that will be lost. Are you sure?")) { return } this.pedalboard.data('wait').start('Loading pedalboard...') this.pedalboard.pedalboard('reset', callback) } Desktop.prototype.updateAllPlugins = function () { this.effectBox.effectBox('search') } Desktop.prototype.updatePluginList = function (added, removed) { // TODO console.log("ADDED:", added) console.log("REMOVED:", removed) for (var i in added) { var uri = added[i] } for (var i in removed) { var uri = removed[i] } this.effectBox.effectBox('search') } Desktop.prototype.showMidiDeviceList = function () { this.midiDevices.start() } Desktop.prototype.triggerTrueBypass = function (channelName, bypassed) { var self = this; $.ajax({ url: '/truebypass/' + channelName + '/' + (bypassed ? "true" : "false"), cache: false, dataType: 'json', success: function (ok) { if (ok) { self.setTrueBypassButton(channelName, bypassed); } } }) } Desktop.prototype.setTrueBypassButton = function (channelName, state) { if (typeof state === "string") state = eval(state); var b = $("#mod-bypass" + channelName); b[(state ? "add" : "remove") + "Class"]("bypassed"); } // .modpedalboard download of a saved pedalboard (Developer Mode, always on MOD Desktop) Desktop.prototype.exportPedalboardFile = function (pedalboard) { if (pedalboard.bundle == this.pedalboardBundle && this.pedalboardModified) { new Notification('warn', 'This pedalboard has unsaved changes: the export holds the last saved version', 5000) } var xhr = new XMLHttpRequest() xhr.open('GET', '/pedalboard/file/export/?bundlepath=' + encodeURIComponent(pedalboard.bundle) + '&_=' + Date.now()) xhr.responseType = 'blob' xhr.onload = function () { if (xhr.status != 200) { var reader = new FileReader() reader.onload = function () { new Notification('error', 'Export failed: ' + $('
').text(reader.result || "unknown error").html(), 6000) } reader.readAsText(xhr.response) return } var filename = xhr.getResponseHeader('X-Modpedalboard-Filename') || ('pedalboard' + PEDALBOARD_FILE_EXTENSION) var files = parseInt(xhr.getResponseHeader('X-Modpedalboard-Files') || '0') var url = URL.createObjectURL(xhr.response) var a = $('').attr('href', url).attr('download', filename).appendTo('body') a[0].click() setTimeout(function () { a.remove() URL.revokeObjectURL(url) }, 1000) var msg = 'Pedalboard exported as ' + $('
').text(filename).html() if (files > 0) { msg += '
The ' + files + ' user file' + (files == 1 ? '' : 's') + ' it uses (NAM models, IRs, ...) are not included.' } new Notification('info', msg, 6000) } xhr.onerror = function () { new Notification('error', 'Export failed: communication failure', 6000) } xhr.send() } // .modpedalboard file loaded as an unsaved pedalboard: check, install missing plugins (devices), load Desktop.prototype.importPedalboardFile = function (file, closeWindow) { var self = this $.ajax({ url: '/pedalboard/file/import/', method: 'POST', data: file, processData: false, contentType: 'application/octet-stream', cache: false, dataType: 'json', success: function (resp) { if (! resp.ok) { new Notification('error', 'Import failed: ' + $('
').text(resp.error).html(), 6000) return } var notes = [] if (resp.missingFiles.length > 0) { notes.push(resp.missingFiles.length + ' user file' + (resp.missingFiles.length == 1 ? ' is' : 's are') + ' missing on this unit: ' + $('
').text(resp.missingFiles.slice(0, 5).join(', ')).html() + (resp.missingFiles.length > 5 ? ', ...' : '')) } if (self.isApp && resp.missingPlugins.length > 0) { notes.push(resp.missingPlugins.length + ' plugin' + (resp.missingPlugins.length == 1 ? ' is' : 's are') + ' not available on MOD Desktop and will be left out') } closeWindow() self.reset(function () { var load = function (ok) { if (! ok) { self.pedalboard.data('wait').stop() return } $.ajax({ url: '/pedalboard/file/load/', method: 'POST', data: { token: resp.token }, cache: false, dataType: 'json', success: function (lresp) { if (! lresp.ok) { self.pedalboard.data('wait').stop() new Notification('error', 'Import failed: ' + $('
').text(lresp.error).html(), 6000) return } self.pedalboardEmpty = false self.setPedalboardAsModified(true) var msg = 'Imported "' + $('
').text(resp.title).html() + '": save it to add it to your pedalboards' if (notes.length > 0) { msg += '
' + notes.join('
') } new Notification(notes.length > 0 ? 'warn' : 'info', msg, 8000) }, error: function () { self.pedalboard.data('wait').stop() new Bug("Couldn't load the imported pedalboard") }, }) } if (self.isApp || resp.missingPlugins.length == 0) { load(true) } else { self.installMissingPlugins(resp.plugins, load) } }) }, error: function () { new Notification('error', 'Import failed: communication failure', 6000) }, }) } Desktop.prototype.loadPedalboard = function (bundlepath, callback) { var self = this self.reset(function () { $.ajax({ url: '/pedalboard/load_bundle/', type: 'POST', data: { bundlepath: bundlepath }, success: function (resp) { if (! resp.ok) { callback(false) return } self.title = resp.name self.pedalboardBundle = bundlepath self.pedalboardEmpty = false self.pedalboardDemoPluginsNotified = false self.setPedalboardAsModified(false) self.titleBox.text(resp.name); self.performanceTitleBox.text(resp.name); self.titleBox.removeClass("blend"); callback(true) _paq.push(['trackEvent', 'pedalboard', 'pedalboard-load']); }, error: function () { new Bug("Couldn't load pedalboard") }, cache: false, dataType: 'json' }) }) } Desktop.prototype.saveCurrentPedalboard = function (asNew, callback) { var self = this if (self.pedalboardEmpty && ! self.pedalboardModified) { new Notification('warn', 'Nothing to save', 1500) return } self.saveBox.saveBox('save', "", self.title, asNew, function (ok, errorOrPath, title) { if (!ok) { new Error(errorOrPath) return } if (asNew || title || ! self.title) { self.titleBox.removeClass("blend"); self.previousPedalboardList = null } self.title = title self.pedalboardBundle = errorOrPath self.pedalboardEmpty = false self.setPedalboardAsModified(false) const newTitle = title + " - " + self.pedalboardPresetName self.titleBox.text(newTitle) self.performanceTitleBox.text(newTitle) if (self.previousPedalboardList != null) { for (var i=0; i 0) { self.createCart(shopClient) } resolve(products) }, reject) }) } Desktop.prototype.fetchShopProduct = function(uri) { var self = this var shopClient = ShopifyBuy.buildClient(SHOPIFY_CLIENT_OPTIONS); // TODO would be more efficient to query one single product, // but don't know how to query by variant's SKU return shopClient.fetchAllProducts().then(function(products) { for (var i in products) { if (uri == products[i].selectedVariant.attrs.variant.sku) { self.createCart(shopClient) return products[i] } } }) } Desktop.prototype.createCart = function(shopClient) { var self = this ShopifyBuy.UI.onReady(shopClient).then(function (ui) { ui.createComponent('cart', { moneyFormat: '%E2%82%AC%7B%7Bamount%7D%7D', options: SHOPIFY_PRODUCT_OPTIONS }).then(function(cart) { self.cart = cart; }) self.windowManager.registerShopify(ui); }) } Desktop.prototype.createBuyButton = function(shopifyId) { var shopClient = ShopifyBuy.buildClient(SHOPIFY_CLIENT_OPTIONS); ShopifyBuy.UI.onReady(shopClient).then(function (ui) { var node = document.getElementById('product-component-'+shopifyId); var button = $('
ADD TO CART
').appendTo(node); ui.createComponent('product', { id: [shopifyId], node: node, moneyFormat: '%E2%82%AC%7B%7Bamount%7D%7D', options: SHOPIFY_PRODUCT_OPTIONS }); }); } Desktop.prototype.waitForLicenses = function(deviceToken) { var self = this; var poll = function() { $.ajax({ url: SITEURL + '/licenses/requests/'+deviceToken, method: 'GET', headers: { 'Authorization' : 'MOD ' + self.cloudAccessToken }, success: function(result) { if (self.licenseManager === null || !result.fulfilled) { setTimeout(poll, 5000); return; } self.licenseManager.addLicenses(result.license_info, function() { var s = result.license_info.length > 1 ? 's' : '' var msg = result.license_info.length + ' new plugin'+s+' purchased' new Notification('info', msg); var uris = result.license_info.map(function(l) { return l.plugin_uri }); if (self.cart) { self.cart.empty() self.cart.close() } }) }, error: function() { new Notification('error', "Can't get licenses from Cloud, please reload interface after finishing your purchase"); } }); } setTimeout(poll, 5000); } Desktop.prototype.license = function(uri) { var container = $('[mod-uri="'+escape(uri)+'"]') container.find('.price').removeClass('price').addClass('licensed').html('') container.find('.description-price').removeClass('description-price').addClass('description-licensed').html('') container.find('.demo-mask').remove() container.find('.buy-button').remove() container.find('button').each(function(index, button) { $(button).html($(button).html().replace(/\s+Trial/, '')) }); this.pedalboard.pedalboard('license', uri) } /* * Ask user for a text input * windowTitle: title of the window * value: default value * callback: function(newValue) called when user clicks ok * okLabel: label of the ok button (default: 'Ok') */ Desktop.prototype.openInputBoxWindow = function (windowTitle, value, callback, okLabel, validateCallback) { this.inputBox.inputBox('show', windowTitle, value, callback, okLabel, validateCallback) } JqueryClass('inputBox', { init: function (options) { var self = $(this) options = $.extend({ }, options) self.data(options) self.data('disabled', false) var done = function () { // call the user callback self.inputBox('_onResult', false) return false } self.find('.js-done').click(done).prop('disabled',true) self.find('.js-cancel').click(function () { if (self.data('disabled')) { return false } self.inputBox('_onResult', true) self.hide() return false }) self.find('input').keyup(function () { var value = self.find('input').val() const isValid = self.inputBox('_validate', value) self.find('.js-done').prop('disabled', isValid ? false : true); }) self.keydown(function (e) { if (self.data('disabled')) { return false } if (e.keyCode == 13) { return done() } if (e.keyCode == 27) { self.inputBox('_onResult', true) self.hide() return false } }) return self }, /* * Show the input box * windowTitle: title of the window * value: default value * callback: function(newValue) called when user clicks ok * okLabel: label of the ok button (default: 'Ok') * isValidCallback: optional function(newValue) called when user changes the text, should return true if the value is valid */ show: function (windowTitle, value, callback, okLabel, isValidCallback) { var self = $(this) if (!okLabel) { okLabel = 'Save' } var saveButton = self.find('.js-done') saveButton.text(okLabel) self.find('input').val(value) self.data('callback', callback) self.data('isValidCallback', isValidCallback) if (windowTitle) { self.find('h1').text(windowTitle) } self.show() self.focus() const input = self.find('input') input.focus(function() { $(this).select(); } ) input.focus() }, _validate: function (value) { var self = $(this) const isValidCallback = self.data('isValidCallback') let isValid = true if (isValidCallback) { isValid = isValidCallback(value) } else { // default validation: non empty isValid = value && value.length > 0 } return isValid }, _onResult: function (cancelled) { var self = $(this) var newValue = self.find('input').val() if (!cancelled) { if (!self.inputBox('_validate', newValue)) { new Bug("Input not valid") return } } self.data('disabled', true) self.find('.js-cancel').prop('disabled', true) self.find('.js-done').prop('disabled', true) let returnValue = undefined try { returnValue = self.data('callback')(newValue, cancelled) } catch (e) { console.warn('Input box callback failed:', e) } if (returnValue !== false) { self.hide() } self.data('disabled', false) self.find('.js-cancel').prop('disabled', false) self.find('.js-done').prop('disabled', false) return } }) JqueryClass('saveBox', { init: function (options) { var self = $(this) options = $.extend({ save: function (windowTitle, name, asNew, callback) { callback(false, "Not Implemented") } }, options) self.data(options) self.data('disabled', false) var save = function () { self.saveBox('send') return false } self.find('.js-save').click(save).prop('disabled',true) self.find('.js-cancel-saving').click(function () { if (self.data('disabled')) { return false } self.hide() return false }) self.find('input').keyup(function () { self.find('.js-save').prop('disabled', this.value.length == 0 ? true : false); }) self.keydown(function (e) { if (self.data('disabled')) { return false } if (e.keyCode == 13) { return save() } if (e.keyCode == 27) { self.hide() return false } }) return self }, save: function (windowTitle, name, asNew, callback) { var self = $(this) self.find('input').val(name) self.data('asNew', asNew) self.data('callback', callback) if (windowTitle) { self.find('h1').text(windowTitle) } if (name && !asNew) { self.saveBox('send') } else { self.saveBox('edit') } }, edit: function () { var self = $(this) self.find('.js-save').prop('disabled', self.find('input').val().length == 0 ? true : false); self.show() self.focus() self.find('input').focus() }, send: function () { var self = $(this) var title = self.find('input').val() var asNew = self.data('asNew') if (title.length == 0) { new Bug("Cannot save with an empty name!") return } self.data('disabled', true) self.find('.js-cancel-saving').prop('disabled', true) self.find('.js-save').prop('disabled', true) self.data('save')("", title, asNew, function (ok, errorOrPath, realTitle) { if (! ok) { new Bug(errorOrPath) } self.hide() self.data('disabled', false) self.find('.js-cancel-saving').prop('disabled', false) self.find('.js-save').prop('disabled', false) self.data('callback')(true, errorOrPath, realTitle) }) return } }) JqueryClass('statusTooltip', { init: function () { var self = $(this) var tooltip = $('
').appendTo($('body')) tooltip.data('arrow', $('
').appendTo(tooltip)) $('
').appendTo(tooltip) tooltip.hide() self.data('tooltip', tooltip) self.bind('mouseover', function () { self.statusTooltip('showTooltip') }) self.bind('mouseout', function () { tooltip.stop().animate({ opacity: 0 }, 200, function () { $(this).hide() }) }) // Special case for bottom left mod-plugins icon // arrow should be on the left, not on the right if (self.attr('id') === "mod-plugins") { var arrow = tooltip.data('arrow'); arrow.css('left', 14); } return self }, status: function (status) { var self = $(this) if (self.data('status')) self.removeClass(self.data('status')) self.data('status', status) self.addClass(status) }, message: function (message, silent, timeout) { var self = $(this) var oldMsg = self.data('message') self.data('message', message) if (!silent && oldMsg != message) self.statusTooltip('showTooltip', timeout || 1500) }, showTooltip: function (timeout) { var self = $(this) var msg = self.data('message') if (!msg) return var tooltip = self.data('tooltip') tooltip.find('.text').html(self.data('message')) tooltip.show().stop().animate({ opacity: 1 }, 200) // Adjust tooltip position in case window has been resized self.statusTooltip('updatePosition') if (timeout) { setTimeout(function () { tooltip.stop().animate({ opacity: 0 }, 200, function () { $(this).hide() }) }, timeout) } }, updatePosition: function() { var self = $(this) var tooltip = self.data('tooltip') tooltip.css('right', $(window).width() - self.position().left - self.width()) // Special case for bottom left mod-plugins icon if (self.attr('id') === "mod-plugins") { tooltip.css('right', $(window).width() - self.position().left - self.width() + tooltip.position().left); } } }) // Tools for developers and beta testers, each switched on its own in Settings > User Interface. // A tool never set on its own follows the old "dev-mode" switch, so units that had Developer Mode on keep everything. // Install All and Update All were one switch ("ui-store-all") before they got one each; that value is their default. var UI_TOOLS = ['ui-xruns', 'ui-buffersize', 'ui-cpu-stats', 'ui-ping-times', 'ui-store-install-all', 'ui-store-update-all', 'ui-share'] var UI_TOOL_FALLBACK = { 'ui-store-install-all': 'ui-store-all', 'ui-store-update-all': 'ui-store-all', } function ui_tool_value(key) { var value = PREFERENCES[key] if (value !== "on" && value !== "off" && UI_TOOL_FALLBACK[key]) { value = PREFERENCES[UI_TOOL_FALLBACK[key]] } if (value !== "on" && value !== "off") { value = PREFERENCES['dev-mode'] } return value } function ui_tool_enabled(key) { return ui_tool_value(key) == "on" } function apply_ui_tools() { var toggle = function (selector, enabled) { if (enabled) { $(selector).show() } else { $(selector).hide() } } // install all / update all plugins, one switch each toggle('#cloud_install_all', ui_tool_enabled('ui-store-install-all')) toggle('#cloud_update_all', ui_tool_enabled('ui-store-update-all')) // network and controller ping times toggle('#mod-status', ui_tool_enabled('ui-ping-times')) // xrun counter toggle('#mod-xruns', ui_tool_enabled('ui-xruns')) // buffer size button toggle('#mod-buffersize', ui_tool_enabled('ui-buffersize')) // CPU speed and temperature, not available on the Duo toggle('#mod-cpu-stats', ui_tool_enabled('ui-cpu-stats') && PLATFORM != "duo") // preset and pedalboard Export / Import buttons (MOD Desktop always shows them) if (ui_tool_enabled('ui-share') || USING_MOD_DESKTOP) { $('body').addClass('preset-share pedalboard-share') } else { $('body').removeClass('preset-share pedalboard-share') } // the status bar items moved: adjust the tooltips and the transport window if (ui_tool_enabled('ui-ping-times')) { $('#mod-status').statusTooltip('updatePosition') } $('#mod-devices').statusTooltip('updatePosition') $('#mod-settings').statusTooltip('updatePosition') // the transport window opens above its icon; the items on its right push the icon to the left var transportRight = 310 $('#mod-status, #mod-cpu-stats, #mod-xruns, #mod-buffersize').each(function () { if ($(this).is(':visible')) { transportRight += $(this).outerWidth(true) } }) $('#mod-transport-window').css({ right: transportRight + 'px' }) } // Console helpers, kept from the old Developer Mode: switch every tool on or off at once. function set_all_ui_tools(value) { for (var i in UI_TOOLS) { PREFERENCES[UI_TOOLS[i]] = value desktop.saveConfigValue(UI_TOOLS[i], value) } PREFERENCES['dev-mode'] = value desktop.saveConfigValue("dev-mode", value) apply_ui_tools() } function enable_dev_mode() { set_all_ui_tools("on") return "Dev mode enabled!" } function disable_dev_mode() { set_all_ui_tools("off") return "Dev mode disabled!" }