// SPDX-FileCopyrightText: 2012-2023 MOD Audio UG // SPDX-License-Identifier: AGPL-3.0-or-later $.ui.intersect = function(draggable, droppable, toleranceMode) { if (!droppable.offset) { return false; } var draggableLeft, draggableTop, x1 = (draggable.positionAbs || draggable.position.absolute).left, y1 = (draggable.positionAbs || draggable.position.absolute).top, x2 = x1 + draggable.helperProportions.width, y2 = y1 + draggable.helperProportions.height, l = droppable.offset.left, t = droppable.offset.top, r = l + droppable.proportions.width, b = t + droppable.proportions.height; switch (toleranceMode) { case "custom": return (l < x1 + (draggable.helperProportions.width / 2) && // Right Half x2 - (draggable.helperProportions.width / 2) < r && // Left Half t < y1 + (draggable.helperProportions.height / 2.5) && // Bottom Half y2 - (draggable.helperProportions.height / 2.5) < b ); // Top Half case "custom-replace": { var scale = draggable.helper.data('scale'); if (!scale) { return false; } x1 = draggable.helper.offset().left; y1 = draggable.helper.offset().top; x2 = x1 + draggable.helper.children().width() * scale; y2 = y1 + draggable.helper.children().height() * scale; r = l + droppable.proportions.width * scale; b = t + droppable.proportions.height * scale; /* helper code for display drag and drop areas $('#dropable-area').css({ left: l, width: r - l, top: t, height: b - t, }) $('#draggable-area').css({ left: x1, top: y1, width: x2 - x1, height: y2 - y1, }) */ // touch return ( (y1 >= t && y1 <= b) || // Top edge touching (y2 >= t && y2 <= b) || // Bottom edge touching (y1 < t && y2 > b) // Surrounded vertically ) && ( (x1 >= l && x1 <= r) || // Left edge touching (x2 >= l && x2 <= r) || // Right edge touching (x1 < l && x2 > r) // Surrounded horizontally ); } case "fit": return (l <= x1 && x2 <= r && t <= y1 && y2 <= b); case "intersect": return (l < x1 + (draggable.helperProportions.width / 2) && // Right Half x2 - (draggable.helperProportions.width / 2) < r && // Left Half t < y1 + (draggable.helperProportions.height / 2) && // Bottom Half y2 - (draggable.helperProportions.height / 2) < b ); // Top Half case "pointer": draggableLeft = ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left); draggableTop = ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top); return isOverAxis( draggableTop, t, droppable.proportions().height ) && isOverAxis( draggableLeft, l, droppable.proportions().width ); case "touch": return ( (y1 >= t && y1 <= b) || // Top edge touching (y2 >= t && y2 <= b) || // Bottom edge touching (y1 < t && y2 > b) // Surrounded vertically ) && ( (x1 >= l && x1 <= r) || // Left edge touching (x2 >= l && x2 <= r) || // Right edge touching (x1 < l && x2 > r) // Surrounded horizontally ); default: return false; } }; JqueryClass('pedalboard', { init: function (options) { var self = $(this) options = $.extend({ // baseScale is the initial scale (zoom level) of the pedalboard // The scale is the transform scale() css property that the pedalboard has baseScale: 0.5, // maxScale is the maximum zoom. maxScale: 1, // wherever to skip zoom animations skipAnimations: false, // WindowManager instance windowManager: new WindowManager(), // HardwareManager instance, must be specified hardwareManager: null, // Wait object, used to show waiting message to user wait: new WaitMessage(self), // current z index (last plugin added or moved around) z_index: 30, // This is a margin, in pixels, that will be disconsidered from pedalboard height when calculating // hardware ports positioning bottomMargin: 0, cvAddressing: false, // Below are functions that application uses to integrate functionality to pedalboard. // They all receive a callback as last parameter, which must be called with a true value // to indicate that operation was successfully executed. // In case of error, application is expected to communicate error to user and then call the // callback with false value. The pedalboard will silently try to keep consistency, with // no garantees. (TODO: do something if consistency can't be achieved) // Loads a plugin with given plugin uri and instance // Application MUST use this instance. Overriding this is mandatory. pluginLoad: function (uri, instance, x, y, callback, errorCallback) { callback(true) }, // Removes the plugin given by instance pluginRemove: function (instance, callback) { callback(true) }, // Loads a preset pluginPresetLoad: function (instance, uri, callback) { callback(true) }, // Save a new preset pluginPresetSaveNew: function (instance, name, callback) { callback({ok:false}) }, // Save a preset, replacing an existing one pluginPresetSaveReplace: function (instance, uri, bundlepath, name, callback) { callback({ok:false}) }, // Delete a preset pluginPresetDelete: function (instance, uri, bundlepath, callback) { callback(true) }, // Export the current plugin settings as a .modpreset file pluginPresetExport: function (instance, name, callback) { callback({ok:false}) }, // Import a .modpreset file as a user preset pluginPresetImport: function (instance, file, callback) { callback({ok:false}) }, // Changes the parameter of a plugin's control port pluginParameterChange: function (port, value) {}, // Get value of a plugin parameter pluginPatchGet: function (instance, uri) {}, // Set value of a plugin parameter pluginPatchSet: function (instance, uri, valuetype, value) {}, // Connects two ports portConnect: function (fromPort, toPort, callback) { callback(true) }, // Disconnect two ports portDisconnect: function (fromPort, toPort, callback) { callback(true) }, // Removes all plugins reset: function (callback) { callback(true) }, // Marks the position of a plugin pluginMove: function (instance, x, y) {}, // Takes a list of plugin URIs and gets a dictionary containing all those plugins's data, // indexed by URI getPluginsData: function (uris, callback) { callback({}) }, // Show dialog with plugin info, same as clicking on the bottom plugin bar showPluginInfo: function (pluginData) { }, // Show the plugin's native UI, in an external desktop window showExternalUI: function (instance) { }, // Sets the size of the pedalboard windowSize: function (width, height) {}, // inform dekstop instance that pedalboard has finished loading pedalboardFinishedLoading: function (callback) { callback() }, // Add new plugin cv output port to available addressable cv ports // or update existing cv port's name addCVAddressingPluginPort: function (uri, label, callback) { callback(true) }, // Remove plugin cv output port from available addressable cv ports removeCVAddressingPluginPort: function (uri, callback) { callback(true) }, // Show notification that we are using a demo plugin notifyDemoPluginLoaded: function () { }, }, options) self.pedalboard('wrapApplicationFunctions', options, [ 'pluginLoad', 'pluginRemove', 'pluginPresetLoad', 'pluginPresetSaveNew', 'pluginPresetSaveReplace', 'pluginPresetDelete', 'pluginPresetExport', 'pluginPresetImport', 'pluginParameterChange', 'pluginPatchGet', 'pluginPatchSet', 'pluginMove', 'portConnect', 'portDisconnect', 'reset', 'getPluginsData' ]) self.data(options) // When bypassApplication is set to true, the applicationFunctions provided by options will be bypassed self.data('bypassApplication', false) // minScale holds the minimum scale of the pedalboard. It's initialized as being the base scale // and gets smaller as pedalboard size grows self.data('minScale', options.baseScale) self.data('instanceCounter', -1) self.data('overCount', 0) // Holds all plugins loaded, indexed by instance self.data('plugins', {}) // Instances currently selected by shift-drag or shift-click, indexed by instance self.data('selected', {}) // Hardware inputs and outputs, which have an instance of -1 and symbol as given by application self.data('hwInputs', []) self.data('hwOutputs', []) // connectionManager keeps track of all connections self.data('connectionManager', new ConnectionManager()) // pending scheduleAdapt debounce, and since when it has been waiting self.data('adaptTimer', null) self.data('adaptWaitingSince', 0) // widgets on the arrive list self.data('callbacksToArrive', {}) // replacement plugin, used for recreating connections self.data('replacementPlugin', null) // teleported cables: names spoken for, and the boxes currently drawn for them self.data('teleportNames', {}) self.data('teleportBoxes', {}) // What each output was last called, so toggling a teleport back on restores your // label. Never counts as in use -- uniqueness reads teleportNames only -- and is // not serialised. self.data('teleportNamesRemembered', {}) // teleported cables named by a map that arrived before their connection existed // (applyTeleports, during a bundle load), keyed "from -> to" same as the saved // form -- consumed by connect() once the cable actually shows up self.data('pendingTeleports', {}) // true while resetData is tearing a pedalboard down, so teleportsChanged prunes // in memory but does not POST the shrinking map to the server -- see resetData self.data('teleportsTeardown', false) // the label size is a preference, so it has to be applied before any box is drawn self.pedalboard('applyTeleportScale') // t3k integration self.data('T3KIntegration', new T3KIntegration(self, T3K_API_KEY)) //'t3k_pub_7uGZokPvXdxakAUSGVxh_5HXH5PjIdoY')) // Pedalboard itself will get big dimensions and will have it's scale and position changed dinamically // often. So, let's wrap it inside an element with same original dimensions and positioning, with overflow // hidden, so that the visible part of the pedalboard is always occupying the area that was initially determined // by the css. var parent = $('
') parent.css({ width: self.width(), height: self.height(), position: self.css('position'), top: self.css('top'), left: self.css('left'), overflow: 'hidden' }) parent.insertAfter(self) self.appendTo(parent) self.pedalboard('resetSize') // Pedalboard is expected to be the main element in screen. So, the original margins relative to window will be // stored, so that when window is resized, pedalboard is resized too, keeping that margins self.data('offset', self.offset()) self.data('hmargins', $(window).width() - self.parent().width()) self.data('vmargins', $(window).height() - self.parent().height()) self.data('topmargin', self.offset().top) if (! options.skipAnimations) { var resizeTimeout; function resizeThrottler() { if (resizeTimeout) { clearTimeout(resizeTimeout); } resizeTimeout = setTimeout(function() { resizeTimeout = null; self.pedalboard('fitToWindow'); }, 250); } window.addEventListener("resize", resizeThrottler, false); //$(window).resize(resizeThrottler) } // Create background element to catch dropped jacks // Must be much bigger than screen, so that nothing can be // dropped outside it even if mouse goes outside window var bg = $('
') bg.addClass('ignore-arrive') bg.css({ width: '300%', height: '300%', position: 'absolute', top: '-100%', left: '-100%' }) self.append(bg) bg.droppable({ accept: '[mod-role=output-jack]', greedy: true, drop: function (event, ui) { var jack = ui.draggable self.pedalboard('disconnect', jack) }, }) self.data('background', bg) // Create a blank SVG containing some fancy f/x for later use self.svg({ onLoad: function (svg) { var _svg = svg._svg; _svg.setAttribute("id", "styleSVG"); var defs = svg.defs(); for (var i = 1; i <= 20; i+=1) { var filter = document.createElementNS("http://www.w3.org/2000/svg", 'filter'); filter.setAttribute("id", "blur_" + i); filter.setAttribute("x", "0"); filter.setAttribute("y", "0"); var blur = document.createElementNS("http://www.w3.org/2000/svg", 'feGaussianBlur'); blur.setAttribute("stdDeviation", i / 10); filter.appendChild(blur); defs.appendChild(filter); } }}); // Hovering a port traces every cable touching it. Delegated rather than bound per // jack: jacks come and go with every connection, and a port is what knows all of // its cables. Hardware ports carry mod-port too, so they trace as well. self.on('mouseenter', '[mod-port]', function () { self.pedalboard('traceFrom', $(this)) }) self.on('mouseleave', '[mod-port]', function () { self.pedalboard('clearTracing') }) // What the teleport key will act on. Tracked separately from the tracing hover above, which // deliberately ignores ports with nothing connected. self.on('mouseenter', '[mod-port]', function () { self.data('hoverPort', $(this)) }) self.on('mouseleave', '[mod-port]', function () { self.data('hoverPort', null) }) self.on('mouseenter', '[mod-role=output-jack]', function () { self.data('hoverJack', $(this)) }) // A teleported cable is a stub barely long enough to hover, so its label has to be // a trace target too -- that is the part of it you can actually put a pointer on. self.on('mouseenter', '.mod-teleport', function () { var source = $(this).data('sourcePort') if (source) { self.pedalboard('traceFrom', source) } }) self.on('mouseleave', '.mod-teleport', function () { self.pedalboard('clearTracing') }) self.on('mouseleave', '[mod-role=output-jack]', function () { self.data('hoverJack', null) }) // Dragging the pedalboard moves the view area, shift-dragging selects plugins. // preventDrag is already set here if the mousedown landed on a plugin or a jack, // as their own handlers fire first on the way up self.mousedown(function (e) { if (self.data('preventDrag')) { return } if (e.shiftKey) { self.pedalboard('marquee', e) } else { self.pedalboard('setSelection', {}) self.pedalboard('drag', e) } }) // TELEPORT_KEY splits whatever the pointer is on. Never while typing, and never // while a cable is being dragged. $(document).keydown(function (e) { if (e.ctrlKey || e.metaKey || e.altKey) { return } // e.which on keydown is a keyCode, NOT a character code: F4 is 115, and // String.fromCharCode(115) is 's', so comparing as text fired this on F4 too. // A letter's keyCode is its upper-case char code, which is what to match. if (e.which !== TELEPORT_KEY.toUpperCase().charCodeAt(0)) { return } // keydown auto-repeats about 30 times a second; holding the key would toggle // dozens of times, and each toggle-off drops the output's name // jQuery 1.9 copies a fixed property list onto its event object and `repeat` // is not on it, so this has to come off the native event if (e.originalEvent && e.originalEvent.repeat) { return } var tag = (e.target.tagName || '').toLowerCase() if (tag == 'input' || tag == 'textarea' || tag == 'select' || e.target.isContentEditable) { return } if (self.pedalboard('connecting')) { return } var target = self.pedalboard('teleportTarget') if (! target.length) { return } e.preventDefault() self.pedalboard('toggleTeleport', target) }) // Right-clicking a port offers the same split/join as TELEPORT_KEY, for anyone who // does not know the key. Ports with no cables keep the browser's own menu. self.on('contextmenu', '[mod-port], [mod-role=output-jack]', function (e) { if (self.pedalboard('connecting')) { return } var target = self.pedalboard('teleportTarget') if (! target.length) { return } e.preventDefault() e.stopPropagation() var joining = true for (var i = 0; i < target.length; i++) { if (! target[i].data('teleported')) { joining = false break } } $('.mod-teleport-menu').remove() var plural = target.length > 1 ? 's' : '' var menu = $('
') .css({ left: e.clientX, top: e.clientY }) .appendTo('body') var close = function () { menu.remove() $(document).off('.teleportmenu') } var item = function (label, action, key) { var row = $('
').text(label).appendTo(menu).on('click', function () { close() action() }) // the shortcut, so the menu teaches it if (key) { $('').text(key).appendTo(row) } } item((joining ? 'Join cable' : 'Split cable') + plural, function () { self.pedalboard('toggleTeleport', target) }, TELEPORT_KEY) // same cables as the split: one jack of an expanded input, else all on the port item('Disconnect' + (target.length > 1 ? ' all' : ''), function () { for (var j = 0; j < target.length; j++) { self.pedalboard('disconnect', target[j]) } }) menu.on('mousedown', function (ev) { ev.stopPropagation() }) $(document).on('mousedown.teleportmenu keydown.teleportmenu wheel.teleportmenu', close) }) // Delete removes the selection. Bound on the document because the pedalboard is // not focusable, and ignored while typing so the plugin settings windows, the // save dialog and the plugin search all keep working. Backspace counts too, for // keyboards whose only delete key is that one $(document).keydown(function (e) { if (e.which != 46 && e.which != 8) { return } var tag = (e.target.tagName || '').toLowerCase() if (tag == 'input' || tag == 'textarea' || tag == 'select' || e.target.isContentEditable) { return } if (! Object.keys(self.data('selected')).length) { return } e.preventDefault() self.pedalboard('removeSelected') }) // The mouse wheel is used to zoom in and out. // A wheel gesture is locked to zooming-or-widget on its FIRST event: while zooming, // the pan clamp can slide a knob under a cursor that started over the background, // and the rest of the gesture must not start editing that knob's value. // Capture phase, so we can decide before the widget's own mousewheel handler runs. var gestureEnd = 0, gestureIsZoom = false var wheelZoom = function (ev) { if (ev.timeStamp > gestureEnd) { // ask the event target, not the geometry: an open enumeration list // overflows the box of the control port it lives in, so hit-testing // bounding boxes calls it background and swallows the list's scrolling gestureIsZoom = !self.pedalboard('wheelClaimedByWidget', ev.target) } // 300ms of quiet ends a gesture, raise it if slow scrolling breaks a zoom in two gestureEnd = ev.timeStamp + 300 if (!gestureIsZoom) { return } // this gesture is ours, keep it away from whatever is under the cursor now ev.preventDefault() ev.stopPropagation() var maxS = self.data('maxScale') var minS = self.data('minScale') var step = (maxS - minS) / 5 var steps = ev.wheelDelta != null ? ev.wheelDelta / 120 : -ev.detail / 3 var scale = self.data('scale') var newScale = scale + steps * step newScale = Math.min(maxS, newScale) newScale = Math.max(minS, newScale) if (newScale == scale) return var canvasX = (ev.pageX - self.offset().left) / scale var canvasY = (ev.pageY - self.offset().top) / scale var screenX = ev.pageX - self.parent().offset().left var screenY = ev.pageY - self.parent().offset().top self.pedalboard('zoom', newScale, canvasX, canvasY, screenX, screenY, 0) } // same event names jquery.mousewheel binds, so stopPropagation actually shields the knobs self[0].addEventListener('mousewheel', wheelZoom, true) self[0].addEventListener('DOMMouseScroll', wheelZoom, true) self.pedalboard('initGestures') // To add plugins to pedalboard, user drags and drops a plugin element, // one that has been registered with registerAvailablePlugin self.droppable({ accept: '[mod-role=available-plugin]', drop: function (event, ui) { if (ui.helper.consumed) return // TODO Check if this really necessary var scale = self.data('scale') ui.draggable.trigger('pluginAdded', { x: (ui.helper.offset().left - self.offset().left) / scale, y: (ui.helper.offset().top - self.offset().top) / scale, width: ui.helper.children().width(), height: ui.helper.children().height() }) var uri = unescape(ui.draggable.attr('mod-uri')); var count = self.find('.mod-actions').length; _paq.push(['trackEvent', 'plugin', 'plugin-add', uri, count]); } }) self.disableSelection() return self }, setCvAddressing: function (cvAddressing) { var self = $(this); self.data('cvAddressing', cvAddressing); }, initGestures: function () { var self = $(this) // Gestures for tablets var startScale, canvasX, canvasY self[0].addEventListener('gesturestart', function (ev) { if (ev.handled) return startScale = self.data('scale') canvasX = (ev.pageX - self.offset().left) / startScale canvasY = (ev.pageY - self.offset().top) / startScale ev.preventDefault() }) self[0].addEventListener('gesturechange', function (ev) { if (ev.handled) return var maxS = self.data('maxScale') var minS = self.data('minScale') var scale = self.data('scale') var newScale = startScale * ev.scale newScale = Math.min(maxS, newScale) newScale = Math.max(minS, newScale) var screenX = ev.pageX - self.parent().offset().left var screenY = ev.pageY - self.parent().offset().top self.pedalboard('zoom', newScale, canvasX, canvasY, screenX, screenY, 0) ev.preventDefault() }) self[0].addEventListener('dblclick', function (ev) { if (ev.handled) return self.pedalboard('zoomOut') ev.preventDefault() }) }, // Does anything between a wheel event's target and the pedalboard want the wheel // for itself? Asking the target beats hit-testing bounding boxes: an open // enumeration list overflows the box of the control port it belongs to, so a // geometric test calls it background and the list never gets to scroll. wheelClaimedByWidget: function (target) { var root = this[0] for (var el = target; el && el !== root; el = el.parentElement) { // knobs and other value controls -- the wheel edits them if (el.getAttribute && el.getAttribute('mod-role') === 'input-control-port') return true // anything that can actually scroll, e.g. an open .mod-enumerated-list. // scrollHeight first: it is free, getComputedStyle is not. if (el.scrollHeight > el.clientHeight) { var overflow = window.getComputedStyle(el).overflowY if (overflow === 'auto' || overflow === 'scroll') return true } } return false }, // This wrap all application functions to provide a way to bypass all of them when desired wrapApplicationFunctions: function (options, functions) { var self = $(this) var factory = function (key, closure) { return function () { var callback = arguments[arguments.length - 1] if (self.data('bypassApplication')) { callback(true) } else { closure.apply(this, arguments) } } } // First, let's wrap all application functions to provide a way to bypass all of them when desired for (var i in functions) options[functions[i]] = factory(functions[i], options[functions[i]]) }, fakeLoadFromServerData: function (data, callback, bypassApplication) { var self = $(this) console.log("PEDALBOARD_DATA") console.log(data) /* * Unserialization will first call all application callbacks and after everything is done, * build the pedalboard in screen. * To do that, it takes 3 queues to work on (plugins, hw-ports, and connections), and as it's working * on them, it queues actions to be done when everything is ready. * To work on the instances and connections queues, it uses two asynchronous recursive functions * that will process next element element and gives itself as callback for the application. */ // Let's avoid modifying original data data = $.extend({}, data) // We might want to bypass application self.data('bypassApplication', false) var ourCallback = function () { if (callback) callback() } // Queue closures to all actions needed after everything is loaded var finalActions = [] var finish = function () { for (var i in finalActions) finalActions[i]() self.data('bypassApplication', false) setTimeout(function () { if (! self.pedalboard('fitToWindow')) { self.pedalboard('adapt', true) } ourCallback() }, 1) } var loadPlugin, createHardwarePorts, connect // Loads the next plugin in queue. Gets as parameter a data structure containing // information on all plugins loadPlugin = function (pluginsData) { var plugin = data.plugins.pop() if (plugin == null) { // Queue is empty, let's create the hardware ports now return createHardwarePorts() } var pluginData = pluginsData[plugin.uri] if (pluginData == null) { console.log("Missing plugin:", plugin.uri) loadPlugin(pluginsData) return } var instance if (plugin.instance) { instance = '/graph/' + plugin.instance } else { instance = self.pedalboard('generateInstance', pluginData.uri) } self.data('pluginLoad')(plugin.uri, instance, plugin.x, plugin.y, function (ok) { if (!ok) { return } var symbol, value for (var i in plugin.ports) { symbol = plugin.ports[i].symbol value = plugin.ports[i].value self.pedalboard('setPortWidgetsValue', instance, symbol, value) } self.pedalboard('addPlugin', pluginData, instance, plugin.label, plugin.bypassed, plugin.x, plugin.y, {}, function () { loadPlugin(pluginsData) } ) }) } // Create needed hardware ports createHardwarePorts = function () { if (data.hardware) { var symbol for (var i=1, count=data.hardware.audio_ins; i<=count; i++) { symbol = (i < 3) ? ('/graph/capture_' + i) : ('/graph/audio_from_slave_' + (i-2)) var hw = $('
') self.pedalboard('addHardwareOutput', hw, symbol, 'audio') } for (var i=1, count=data.hardware.audio_outs; i<=count; i++) { symbol = (i < 3) ? ('/graph/playback_' + i) : ('/graph/audio_to_slave_' + (i-2)) var hw = $('
') self.pedalboard('addHardwareInput', hw, '/graph/playback_' + i, 'audio') } for (var i=1, count=data.hardware.cv_ins; i<=count; i++) { var hw = $('
') self.pedalboard('addHardwareOutput', hw, '/graph/cv_capture_' + i + '_in', 'cv') } for (var i=1, count=data.hardware.cv_outs; i<=count; i++) { var hw = $('
') self.pedalboard('addHardwareInput', hw, '/graph/cv_playback_' + i + '_out', 'cv') } if (data.hardware.serial_midi_in) { var hw = $('
') self.pedalboard('addHardwareOutput', hw, '/graph/serial_midi_in', 'midi') } if (data.hardware.serial_midi_out) { var hw = $('
') self.pedalboard('addHardwareInput', hw, '/graph/serial_midi_out', 'midi') } if (data.hardware.midi_merger_in) { var hw = $('
') self.pedalboard('addHardwareOutput', hw, '/graph/midi_merger_in', 'midi') } if (data.hardware.midi_merger_out) { var hw = $('
') self.pedalboard('addHardwareInput', hw, '/graph/midi_merger_out', 'midi') } var portdata, pindex, prefix for (var i in data.hardware.midi_ins) { portdata = data.hardware.midi_ins[i] pindex = parseInt(portdata.symbol.replace("midi_capture_",""))+1 var hw = $('
') self.pedalboard('addHardwareOutput', hw, '/graph/' + portdata.symbol, 'midi') } for (var i in data.hardware.midi_outs) { portdata = data.hardware.midi_outs[i] pindex = parseInt(portdata.symbol.replace("midi_playback_",""))+1 prefix = portdata.name === 'MIDI Loopback' ? 'Virtual' : 'Hardware' var hw = $('
') self.pedalboard('addHardwareInput', hw, '/graph/' + portdata.symbol, 'midi') } } self.pedalboard('positionHardwarePorts') return connect() } // Loads next connection in queue var connect = function () { var conn = data.connections.pop() if (conn == null) // Queue is empty, let's load everything return finish() var source = conn.source var target = conn.target self.data('portConnect')(source, target, function (ok) { if (!ok) { return } finalActions.push(function () { var plugins = $.extend({ 'system': self }, self.data('plugins')) var output = $('[mod-port="/graph/' + source + '"]') var input = $('[mod-port="/graph/' + target + '"]') self.pedalboard('connect', output.find('[mod-role=output-jack]'), input) }) connect() }) } var uris = [] for (var i in data.plugins) uris.push(data.plugins[i].uri) if (data.width > 0 && data.height > 0) { // FIXME: finish this self.css({ width: data.width, height: data.height, position: 'absolute' }) } self.data('getPluginsData')(uris, loadPlugin) }, // Register hardware inputs and outputs, elements that will be used to represent the audio inputs and outputs // that interface with the hardware. // Note that these are considered inputs and outputs from the pedalboard point of view: the outputs are // expected to be a source of sound, and so it's an input from the user perspective; the input is the // sound destination, so will be an output to user. addHardwareInput: function (element, symbol, portType) { var self = $(this) element.attr('mod-role', 'input-' + portType + '-port') element.attr('mod-port-symbol', symbol) element.attr('mod-port', symbol) self.pedalboard('makeInput', element, '') self.data('hwInputs').push(element) self.append(element) }, addHardwareOutput: function (element, symbol, portType) { var self = $(this) element.attr('mod-role', 'output-' + portType + '-port') element.attr('mod-port-symbol', symbol) element.attr('mod-port', symbol) self.pedalboard('makeOutput', element, '') self.data('hwOutputs').push(element) self.append(element) }, /* Make this element a draggable item that can be used to add effects to this pedalboard. * Plugin adding has the following workflow: * 1 - Application registers an HTML element as being an available plugin * 2 - User drags this element and drops in Pedalboard * 3 - Pedalboard calls a the application callback (pluginLoad option), with plugin uri, instanceID and * another callback. * 4 - Application loads the plugin with given instance and calls the pedalboard callback, * or communicate error to user * 5 - Pedalboard renders the plugin * Parameters are: * - Plugin is a data structure as parsed by mod-python's modcommon.lv2.Plugin class. * - draggableOptions will be passed as parameter to the draggable jquery ui plugin */ registerAvailablePlugin: function (element, pluginData, draggableOptions) { var self = $(this) element.bind('pluginAdded', function (e, position) { var waiter = self.data('wait') var instance = self.pedalboard('generateInstance', pluginData.uri) waiter.startPlugin(instance, position) var pluginLoad = self.data('pluginLoad') pluginLoad(pluginData.uri, instance, position.x, position.y, function () { /* self.pedalboard('addPlugin', pluginData, instance, false, position.x, position.y) setTimeout(function () { self.pedalboard('adapt', true) }, 1) */ waiter.stopPlugin(instance, false) }, function () { self.data('replacementPlugin', null) waiter.stopPlugin(instance, false) }) }) element.attr('mod-io-type', pluginData.iotype) var options = { defaultIconTemplate: DEFAULT_ICON_TEMPLATE, dummy: true, } var thumb = element.children(".thumb"); var img = thumb.children("img"); element.draggable($.extend(draggableOptions, { helper: function (event) { var dummy = $('
'); var imgrect = img.position(); imgrect.width = img.width(); imgrect.height = img.height(); var clickpos = { x: event.offsetX, y: event.offsetY }; var clickperc = { x: Math.min(imgrect.width, Math.max(0, (event.offsetX - imgrect.left))) / imgrect.width, y: Math.min(imgrect.height, Math.max(0, (event.offsetY - imgrect.top))) / imgrect.height }; var pad = { left: parseInt(element.css("padding-left")), top: parseInt(element.css("padding-top")) }; var renderedVersion = [pluginData.builder, pluginData.microVersion, pluginData.minorVersion, pluginData.release].join('_'); console.log(pluginData.buildEnvironment) dummy.data('overIcons', []) dummy.data('scale', self.data('scale')) $.ajax({ url: '/effect/get', data: { uri: pluginData.uri, version: VERSION, plugin_version: renderedVersion, }, success: function (plugin) { new GUI(plugin, options).renderDummyIcon(function (icon) { dummy.attr('class', icon.attr('class')) dummy.addClass('dragging') dummy.css("transformOrigin", "0 0"); dummy.css("visibility", "hidden"); var children = icon.children(); var settle = function () { var scale = self.data('scale'); var trans = 'scale(' + scale + ') '; var w = icon.width(); var h = icon.height(); var tx = (pad.left + clickpos.x) / scale - clickperc.x * w; var ty = (pad.top + clickpos.y) / scale - clickperc.y * h; trans += 'translate(' + tx + 'px, ' + ty + 'px) '; dummy.css({ webkitTransform: trans, MozTransform: trans, msTransform: trans, transform: trans, }) dummy.data('scale', scale); } children.resize(function () { icon.width(children.width()); icon.height(children.height()); settle(); dummy.css("visibility", "visible"); }) dummy.append(children); }) }, cache: !!pluginData.buildEnvironment, dataType: 'json' }) $('body').append(dummy) return dummy }, handle: thumb })) }, // Resize pedalboard size to fit whole window // This is a bit buggy, because if window size is reduced, a plugin may get out of the pedalboard // area and become unreacheble. To correct this, scaling must also be considered when calculating // dimensions fitToWindow: function () { var self = $(this) var old = { width: self.width(), height: self.height() } self.parent().css({ width: $(window).width() - self.data('hmargins'), height: $(window).height() - self.data('vmargins') }) var scale = self.data('baseScale') self.css({ width: self.parent().width() / scale, height: self.parent().height() / scale, }) var zoom = self.data('currentZoom') if (!zoom) { return false } zoom.screenX = zoom.screenX * self.width() / old.width zoom.screenY = zoom.screenY * self.height() / old.height self.data('windowSize')(self.width(), self.height()) self.pedalboard('zoom', Math.min(self.data('scale'), scale), zoom.canvasX, zoom.canvasY, zoom.screenX, zoom.screenY, 0) self.pedalboard('adapt', true) return true }, // Prevents dragging of whole dashboard when dragging of effect or jack starts preventDrag: function (prevent) { $(this).data('preventDrag', prevent) }, // Replaces the current selection. Keys of `selected` are plugin instances setSelection: function (selected) { var self = $(this) var plugins = self.data('plugins') for (var instance in plugins) { if (plugins[instance] && plugins[instance].length) { plugins[instance].toggleClass('mod-selected', !!selected[instance]) } } // lets the stylesheet fade everything that is not selected self.toggleClass('mod-has-selection', Object.keys(selected).length > 0) self.data('selected', selected) }, // Adds or removes a single plugin from the selection, for shift-click toggleSelected: function (instance) { var self = $(this) var selected = self.data('selected') if (selected[instance]) { delete selected[instance] } else { selected[instance] = true } self.pedalboard('setSelection', selected) }, // Removes every selected plugin. Asks first when more than one is going, since there // is no undo and a stray Delete could otherwise take out a whole board removeSelected: function () { var self = $(this) var plugins = self.data('plugins') // snapshot the keys: removing a plugin drops it from the selection as it goes var instances = Object.keys(self.data('selected')) if (! instances.length) { return } if (instances.length > 1 && ! confirm('Remove ' + instances.length + ' plugins from the pedalboard?')) { return } self.pedalboard('finishConnection') for (var i = 0; i < instances.length; i++) { var plugin = plugins[instances[i]] if (! plugin || ! plugin.length) { continue } // ports is only needed so removePlugin can drop the plugin's cv outputs from // the hardware manager; addPlugin stashes it on the icon for us self.pedalboard('removePlugin', instances[i], plugin.data('ports')) } self.pedalboard('setSelection', {}) }, // Shift-dragging the background rubber-bands a box and selects what it touches. // The box lives in the unscaled parent, so it needs no scale math, and the hit test // uses getBoundingClientRect, which is already in the same screen space marquee: function (start) { var self = $(this) var box = $('
').appendTo(self.parent()) var parentRect = self.parent()[0].getBoundingClientRect() var rectOf = function (e) { return { left: Math.min(start.clientX, e.clientX), right: Math.max(start.clientX, e.clientX), top: Math.min(start.clientY, e.clientY), bottom: Math.max(start.clientY, e.clientY) } } var moveHandler = function (e) { var r = rectOf(e) box.css({ left: r.left - parentRect.left, top: r.top - parentRect.top, width: r.right - r.left, height: r.bottom - r.top }) } var upHandler = function (e) { $(document).unbind('mousemove', moveHandler) $(document).unbind('mouseup', upHandler) box.remove() var r = rectOf(e) if (r.right - r.left < 4 && r.bottom - r.top < 4) { // a shift-click with no drag, leave the selection alone return } var selected = {} var plugins = self.data('plugins') for (var instance in plugins) { if (! plugins[instance] || ! plugins[instance].length) { continue } var b = plugins[instance][0].getBoundingClientRect() if (b.right > r.left && b.left < r.right && b.bottom > r.top && b.top < r.bottom) { selected[instance] = true } } self.pedalboard('setSelection', selected) } $(document).bind('mousemove', moveHandler) $(document).bind('mouseup', upHandler) }, // Called when a plugin drag starts. If that plugin is selected, remember where every // other selected plugin sits so the drag can move them all by the same delta startGroupDrag: function (instance) { var self = $(this) var plugins = self.data('plugins') var selected = self.data('selected') self.data('dragGroup', null) if (! selected[instance]) { return } var group = [] for (var other in selected) { if (other == instance || ! plugins[other] || ! plugins[other].length) { continue } group.push({ instance: other, icon: plugins[other], left: parseInt(plugins[other].css('left')), top: parseInt(plugins[other].css('top')) }) } if (! group.length) { return } self.data('dragGroup', group) self.data('dragOrigin', { left: parseInt(plugins[instance].css('left')), top: parseInt(plugins[instance].css('top')) }) }, // Moves the rest of the selection to follow the dragged plugin. left/top are the // dragged plugin's new position, in canvas units dragGroupTo: function (left, top) { var self = $(this) var group = self.data('dragGroup') if (! group) { return } var origin = self.data('dragOrigin') var dx = left - origin.left var dy = top - origin.top for (var i = 0; i < group.length; i++) { group[i].icon.css({ left: group[i].left + dx, top: group[i].top + dy }) self.pedalboard('drawPluginJacks', group[i].icon) } }, // Persists the new position of every plugin that moved along with the dragged one finishGroupDrag: function () { var self = $(this) var group = self.data('dragGroup') if (! group) { return } for (var i = 0; i < group.length; i++) { self.data('pluginMove')(group[i].instance, parseInt(group[i].icon.css('left')), parseInt(group[i].icon.css('top'))) } self.data('dragGroup', null) }, // Moves the viewable area of the pedalboard drag: function (start) { var self = $(this) self.trigger('dragStart') var scale = self.data('scale') var canvasX = (start.pageX - self.offset().left) / scale var canvasY = (start.pageY - self.offset().top) / scale var screenX = start.pageX - self.parent().offset().left var screenY = start.pageY - self.parent().offset().top var moveHandler = function (e) { if (self.data('preventDrag')) return self.pedalboard('zoom', scale, canvasX, canvasY, screenX + e.pageX - start.pageX, screenY + e.pageY - start.pageY, 0) } var upHandler = function (e) { $(document).unbind('mouseup', upHandler) $(document).unbind('mousemove', moveHandler) } $(document).bind('mousemove', moveHandler) $(document).bind('mouseup', upHandler) }, // Changes the viewing scale of the pedalboard and position it in a way that // the (canvasX, canvasY) point of pedalboard will match the (screenX, screenY) // position of the screen. This way, when user uses the mousewheel to zoom, the // mouse will remain in the same point of the pedalboard while scale is changed. // Duration is the time in miliseconds used to animate the zoom, default is 400. zoom: function (scale, canvasX, canvasY, screenX, screenY, duration) { var self = $(this) self.data('currentZoom', { scale: scale, canvasX: canvasX, canvasY: canvasY, screenX: screenX, screenY: screenY }) // This is the offset put by browser, must be compensated var autoOffsetX = -self.width() * (scale - 1) / 2 var autoOffsetY = -self.height() * (scale - 1) / 2 // This is the position of this point in pixels var absoluteX = canvasX * scale var absoluteY = canvasY * scale var offsetX = -autoOffsetX - absoluteX + screenX var offsetY = -autoOffsetY - absoluteY + screenY var maxOffsetX = -autoOffsetX var minOffsetX = -autoOffsetX - self.width() * scale + self.parent().width() var maxOffsetY = -autoOffsetY var minOffsetY = -autoOffsetY - self.height() * scale + self.parent().height() offsetX = Math.max(minOffsetX, offsetX) offsetX = Math.min(maxOffsetX, offsetX) offsetY = Math.max(minOffsetY, offsetY) offsetY = Math.min(maxOffsetY, offsetY) self.data('offsetX', offsetX) self.data('offsetY', offsetY) if (self.data('skipAnimations')) { duration = 0 } else if (duration == null) { duration = 400 } // workaround some browsers that send a zero value at step start, which is an invalid scale var usingInitialZero = false var oldScale = self.data('scale') var newScale = scale self.animate({ scale: scale, top: offsetY, left: offsetX }, { duration: duration, step: function (value, prop) { if (prop.prop != 'scale') { return } // if we receive a value of 0, which is impossible for the scale variable, trigger workaround if (value == 0) { usingInitialZero = true } if (usingInitialZero) { var per = value / newScale value = (oldScale * (1.0 - per)) + (newScale * per) } self.css({ webkitTransform: 'scale(' + value + ')', MozTransform: 'scale(' + value + ')', msTransform: 'scale(' + value + ')', transform: 'scale(' + value + ')', }) self.data('scale', value) }, }) }, // Changes the scale of the pedalboard and centers view on (x, y) zoomAt: function (scale, x, y, duration) { var self = $(this) var screenX = self.parent().width() / 2 var screenY = self.parent().height() / 2 self.pedalboard('zoom', scale, x, y, screenX, screenY, duration) }, // Zoom to desired plugin focusPlugin: function (plugin) { var self = $(this) var scale = self.data('scale') var x = plugin.position().left / scale + plugin.width() / 2 var y = plugin.position().top / scale + plugin.height() / 2 self.pedalboard('zoomAt', 1, x, y) }, // Increase zoom level zoomIn: function () { var self = $(this) var scale = self.data('scale') var newScale if (scale == 1) return if (scale >= 0.5) newScale = 1 else newScale = 0.5 if (newScale > scale) { var x = $(window).width() / 2 var y = $(window).height() / 2 var canvasX = (x - self.offset().left) / scale var canvasY = (y - self.offset().top) / scale var screenX = x - self.parent().offset().left var screenY = y - self.parent().offset().top self.pedalboard('zoom', newScale, canvasX, canvasY, screenX, screenY, 500) } }, // Decrease zoom level zoomOut: function () { var self = $(this) var scale = self.data('scale') var newScale if (scale == self.data('minScale')) return if (scale <= 0.5) newScale = self.data('minScale') else newScale = 0.5 if (newScale < scale) { var x = $(window).width() / 2 var y = $(window).height() / 2 var canvasX = (x - self.offset().left) / scale var canvasY = (y - self.offset().top) / scale var screenX = x - self.parent().offset().left var screenY = y - self.parent().offset().top self.pedalboard('zoom', newScale, canvasX, canvasY, screenX, screenY, 500) } }, // Enlarge the pedalboard to a minimum size capable of accommodating all plugins. adapt: function (forcedUpdate) { var self = $(this) // A board with no room to show in (a page not laid out yet, or hidden) has nothing // to fit: every size below would divide by zero and leave the scale NaN for good. // The next adapt, from the load or a resize, fits it once there is room. if (! self.parent().width() || ! self.parent().height()) { return } // First, get the minmum bounding rectangle, // given by minX, maxX, minY and maxY var minX, maxX, minY, maxY, padX, padY, w, h, x, y, plugin, pos //var pedals = self.find('.js-effect') var plugins = self.data('plugins') var scale = self.data('scale') // Seeded from the size resetSize starts with rather than from the current canvas. // Seeding with self.width()/height() made the box the union of canvas-and-plugins, // so the canvas could only ever grow - deleting or moving plugins inwards left the // vacated space behind forever. The floor already carries the viewport aspect // ratio, which is what the ratio lock further down expects. // Only the right and bottom are reclaimed this way, and neither moves a plugin. // Left and top slack still cannot be given back without shifting every plugin. minX = 0 maxX = self.parent().width() / self.data('baseScale') minY = 0 maxY = self.parent().height() / self.data('baseScale') var instance // Keep one more plugin's worth of empty canvas past the outermost plugin, so // there is always somewhere to drop the next one instead of having to shove one // against an edge you cannot see past first. The unit is the biggest plugin // currently on the board, so the gap is literally "one more of these fits". // 150 is the old fixed margin, kept as the floor and as the empty board case. // // Right and bottom only. Growing left or up is implemented as a shift of every // plugin (the minX/minY branches below), which runs through pluginMove and so // rewrites and re-persists every saved position and marks the board modified. // Those two sides still grow on demand when a plugin is actually dragged there. padX = 150 padY = 150 for (instance in plugins) { plugin = plugins[instance] if (!plugin.position) continue padX = Math.max(padX, plugin.width()) padY = Math.max(padY, plugin.height()) } for (instance in plugins) { plugin = plugins[instance] // A plugin still loading is a placeholder holding the position from its add // message, with no size yet. Its position alone is counted, so the board is // fitted as soon as the load starts instead of after every GUI has arrived. // No size or margin is guessed: the canvas only grows, so a guess too big // would stay, while one too small is corrected by the fit that ends the load. if (!plugin.position) { if (plugin.x !== undefined) { maxX = Math.max(maxX, plugin.x) maxY = Math.max(maxY, plugin.y) } continue } pos = plugin.position() w = plugin.width() h = plugin.height() x = pos.left / scale y = pos.top / scale minX = Math.min(minX, x) maxX = Math.max(maxX, x + w + padX) minY = Math.min(minY, y) maxY = Math.max(maxY, y + h + padY) } // Now calculate how much to increase in width and height, // and how much to move in left and top var wDif = 0 var hDif = 0 var left = 0 var top = 0 w = self.width() h = self.height() if (minX < 0) { wDif -= minX left -= minX } if (minY < 0) { hDif -= minY top -= minY } // Unconditional, so these can come out negative and give space back. They used to // be guarded by maxX > w / maxY > h, which is why the canvas could only grow: once // maxX is the floor rather than the current width, the guard is false whenever // there is slack to reclaim and adapt fell straight through to its early return. // The result is w + wDif == maxX - minX, i.e. exactly the box we want, in either // direction. Only the right and bottom move; left and top still need the shift. wDif += maxX - w hDif += maxY - h // Nothing has changed, or only by rounding: the zoomed positions make the target // wobble a pixel either way while knob images load, and each fit redraws every // cable. Compared against the current canvas, so a real change still lands once // it adds up to 2px. if (Math.abs(wDif) < 2 && Math.abs(hDif) < 2 && ! forcedUpdate) { return } var scale = self.data('scale') // now let's modify desired width and height to keep // screen ratio var ratio = w / h w += wDif h += hDif if (ratio > w / h) // we have to increase width to keep ratio w = ratio * h else if (ratio < w / h) // increse height to keep ratio h = w / ratio var time = (self.data('skipAnimations') || forcedUpdate) ? 0 : 400 // Move animate everything: move plugins, scale and position // canvas var drawFactory = function (plugin) { return function () { self.pedalboard('drawPluginJacks', plugin) } } // move plugins for (instance in plugins) { plugin = plugins[instance] if (!plugin.position) continue pos = plugin.position() old_x = Math.round(pos.left / scale) old_y = Math.round(pos.top / scale) x = parseInt(plugin.css('left')) + left y = parseInt(plugin.css('top')) + top if (old_x == x && old_y == y) { continue } plugin.animate({ left: x, top: y }, { duration: time, step: drawFactory(plugin), complete: drawFactory(plugin) }) self.data('pluginMove')(instance, x, y) } var viewWidth = self.parent().width() var viewHeight = self.parent().height() var newScale = viewWidth / w self.data('minScale', newScale) // if we are at scale 1, it is very much likely that we do not want to zoom out now // keep current scale if that is the case if (scale == 1 && ! forcedUpdate) { var width = viewWidth / newScale var height = viewHeight / newScale self.width(width) self.height(height) self.pedalboard('positionHardwarePorts') return } // workaround some browsers that send a zero value at step start, which is an invalid scale var usingInitialZero = false var oldScale = scale self.animate({ scale: newScale, }, { duration: time, step: function (scale, prop) { if (prop.prop != 'scale') { return } // if we receive a scale of 0, which is impossible for the scale variable, trigger workaround if (scale == 0) { usingInitialZero = true } if (usingInitialZero) { var per = scale / newScale scale = (oldScale * (1.0 - per)) + (newScale * per) } var width = viewWidth / scale var height = viewHeight / scale var offsetX = (viewWidth - width) / 2 var offsetY = (viewHeight - height) / 2 self.width(width) self.height(height) self.css({ webkitTransform: 'scale(' + scale + ')', MozTransform: 'scale(' + scale + ')', msTransform: 'scale(' + scale + ')', transform: 'scale(' + scale + ')', top: offsetY, left: offsetX, }) self.pedalboard('positionHardwarePorts') self.data('scale', scale) self.data('offsetX', offsetX) self.data('offsetY', offsetY) }, }) }, scheduleAdapt: function (forcedUpdate) { var self = $(this) if (self.data('skipAnimations')) { return } if (forcedUpdate) { self.data('adaptForcedUpdate', true) } if (! self.data('adaptWaitingSince')) { self.data('adaptWaitingSince', Date.now()) } // A plain debounce: runs 200ms after the last call. Every plugin that arrives and // every knob image that loads calls this, so a load is one burst of calls. This // used to add time per call instead, which pushed the first fit (and the loading // screen and plugin bar waiting on it) out to its 5s cap on any real pedalboard. var callAdaptLater = function () { // Not while the board is still arriving: a load in progress, or a plugin whose // GUI is not drawn yet (a placeholder without position() until it is). Its // size and cables come with it. A plugin that never arrives // stops holding things up after 10s. // Deliberately not document.readyState: it only turns "complete" once every // image has loaded, knob images included, which on a device is seconds after // the last plugin. The page's CSS is in by the time a load can start anyway. var pending = typeof pb_loading !== 'undefined' && pb_loading var plugins = self.data('plugins') for (var instance in plugins) { if (! plugins[instance].position) { pending = true break } } if (pending && Date.now() - self.data('adaptWaitingSince') < 10000) { self.data('adaptTimer', setTimeout(callAdaptLater, 200)) return } var forcedUpdate = self.data('adaptForcedUpdate') self.data('adaptForcedUpdate', false) self.data('adaptWaitingSince', 0) self.data('adaptTimer', null) self.pedalboard('positionHardwarePorts') self.data('pedalboardFinishedLoading')(function () { self.pedalboard('adapt', forcedUpdate) self.data('wait').stopIfNeeded() // Only the adapt that ends a LOAD -- scheduleAdapt(true) comes solely // from loading_end. Firing on the others would discard the pending map // on any quiet moment, mid-load or mid-reroute. The flag is sticky // until consumed, so it survives coalescing with the false calls. if (forcedUpdate) { self.pedalboard('finishTeleportLoad') } }) } // The fit that ends a load waits for the board to be complete, not for a quiet // moment: on a device knob images keep arriving for seconds after the last plugin, // and restarting the timer for each of them held that fit back until the last one. if (self.data('adaptForcedUpdate') && self.data('adaptTimer')) { return } clearTimeout(self.data('adaptTimer')) self.data('adaptTimer', setTimeout(callAdaptLater, 200)) }, // Position the hardware ports as to be evenly distributed vertically in pedalboard. // Output ports are positioned at left and input ports at right. positionHardwarePorts: function () { var self = $(this) var height = self.height() - self.data('bottomMargin') var adjust = function (elements, css) { var top = height / (elements.length + 1) var i, el elements.sort(function(e1, e2) { var e1_audio = e1.hasClass('mod-audio-output') || e1.hasClass('mod-audio-input') var e2_audio = e2.hasClass('mod-audio-output') || e2.hasClass('mod-audio-input') var e1_midi = e1.hasClass('mod-midi-output') || e1.hasClass('mod-midi-input') var e2_midi = e2.hasClass('mod-midi-output') || e2.hasClass('mod-midi-input') var e1_cv = e1.hasClass('mod-cv-output') || e1.hasClass('mod-cv-input') var e2_cv = e2.hasClass('mod-cv-output') || e2.hasClass('mod-cv-input') // FIXME - there's got to be a better way.. if ((e1_audio && e2_audio) || (e1_midi && e2_midi) || (e1_cv && e2_cv)) { return (parseInt(e1.attr('mod-port-index')) > parseInt(e2.attr('mod-port-index'))) ? 1 : -1; } else if (e1_cv || e2_cv) { return e1_cv ? 1 : -1; } else { return e1_midi ? 1 : -1; } }) for (i = 0; i < elements.length; i++) { el = elements[i] el.css($.extend(css, { top: top * (i + 1) - el.height() / 2 })) } } adjust(self.data('hwInputs'), { right: 0 }) adjust(self.data('hwOutputs'), { left: 0 }) // Redraw all cables that connect to or from hardware ports //self.data('connectionManager').iterateInstance(':system:', function (jack) { self.data('connectionManager').iterate(function (jack) { self.pedalboard('drawJack', jack) }) }, // Resets the pedalboard size and zoom to initial configuration resetSize: function () { var self = $(this) var scale = self.data('baseScale') var w = self.parent().width() / scale var h = self.parent().height() / scale self.css({ width: w, height: h, position: 'absolute' }) self.data('minScale', scale) self.pedalboard('zoomAt', scale, w / 2, h / 2, 0) self.data('windowSize')(self.width(), self.height()) self.pedalboard('positionHardwarePorts') }, /********* * Plugins */ // Generate an instance for a new plugin. // TODO: check with ingen if instance does not exist generateInstance: function (uri) { var self = $(this) // copied from ingen's algorithm to get a valid instance symbol var last_uri_delim = function (s) { for (var i = s.length-1; i > 0; --i) { switch(s[i]) { case '/': case '?': case '#': case ':': return i } } return -1 } var re = /[^_a-zA-Z0-9]+/g var instance = uri var last_delim = last_uri_delim(instance) while (last_delim != -1 && !instance.substr(last_delim, instance.length-1).match(/[a-zA-Z0-9]/)) { instance = instance.substr(0, last_delim) last_delim = last_uri_delim(instance) } instance = instance.substr(last_delim+1, instance.length-1).replace(re, "_") if (instance[0].match(/[0-9]/)) // instance names cant start with numbers instance = "_" + instance var i = 1; instance = '/graph/' + instance // the prefix "/graph/cv_" is reserved, make sure we dont use it if (instance === '/graph/cv') { instance = instance + 'x' } if (instance in self.data('plugins')) { instance = instance + "_1" while (instance in self.data('plugins')) { i = i + 1 instance = instance.slice(0, -1) + i } } return instance }, // Adds a plugin to pedalboard. This is called after the application loads the plugin with the // instance, now we need to put it in screen. addPlugin: function (pluginData, instance, label, bypassed, x, y, guiOptions, renderCallback, skipModified) { var self = $(this) var scale = self.data('scale') var obj = {} var options = $.extend({ dragStart: function () { self.trigger('pluginDragStart', instance) obj.icon.addClass('dragging') obj.icon.css({'z-index': self.data('z_index')+1}) self.data('z_index', self.data('z_index')+1) self.pedalboard('startGroupDrag', instance) return true }, drag: function (e, ui) { self.trigger('pluginDrag', instance) var scale = self.data('scale') ui.position.left /= scale ui.position.top /= scale self.pedalboard('dragGroupTo', ui.position.left, ui.position.top) self.trigger('modified') self.pedalboard('drawPluginJacks', obj.icon) }, dragStop: function (e, ui) { self.trigger('pluginDragStop') self.trigger('modified') self.pedalboard('drawPluginJacks', obj.icon) obj.icon.removeClass('dragging') self.data('pluginMove')(instance, ui.position.left, ui.position.top) self.pedalboard('finishGroupDrag') self.pedalboard('adapt', false) }, click: function (event) { if (event.shiftKey) { // A port has its own shift-click, which toggles its vu meter, and the // ports sit inside the plugin, so the click reaches here too on its // way up. Selecting is for the plugin's own body only. closest() // rather than is(), because the click can land on a jack or on some // other decoration inside the port. if ($(event.target).closest('[mod-port]').length) { return } self.pedalboard('toggleSelected', instance) return } obj.icon.css({'z-index': self.data('z_index')+1}) self.pedalboard('drawPluginJacks', obj.icon) self.data('z_index', self.data('z_index')+1) // only zoom-in if event was triggered by a click on the drag-handle // this prevents zoom-in when dragging a control and releasing the mouse over an empty area of the plugin if (! $(event.target).hasClass("mod-drag-handle")) return; // setTimeout avoids cable drawing bug setTimeout(function () { self.pedalboard('focusPlugin', obj.icon) }, 0) }, change: function (port, value) { self.data('pluginParameterChange')(port, value) }, patchGet: function (uri) { self.data('pluginPatchGet')(instance, uri) }, patchSet: function (uri, valuetype, value) { self.data('pluginPatchSet')(instance, uri, valuetype, value) }, presetLoad: function (uri) { self.data('pluginPresetLoad')(instance, uri, function (ok) { if (ok) { // TODO Handle this error } }) }, presetSaveNew: function (name, callback) { self.data('pluginPresetSaveNew')(instance, name, function (resp) { if (resp.ok) { callback(resp) } }) }, presetSaveReplace: function (uri, bundlepath, name, callback) { self.data('pluginPresetSaveReplace')(instance, uri, bundlepath, name, function (resp) { if (resp.ok) { callback(resp) } }) }, presetDelete: function (uri, bundlepath, callback) { self.data('pluginPresetDelete')(instance, uri, bundlepath, function (ok) { if (ok) { callback() } }) }, presetExport: function (name, callback) { self.data('pluginPresetExport')(instance, name, callback) }, presetImport: function (file, callback) { self.data('pluginPresetImport')(instance, file, callback) }, bypassed: bypassed ? 1 : 0, defaultIconTemplate: DEFAULT_ICON_TEMPLATE, defaultSettingsTemplate: DEFAULT_SETTINGS_TEMPLATE }, guiOptions) /* FIXME this is not used anywhere. remove? var preset_list = [] for (var key in pluginData['presets']) { preset_list.push({ label: pluginData['presets'][key]['label'], uri: pluginData['presets'][key]['uri'] }) } pluginData = $.extend({ preset_list: preset_list }, pluginData) */ var pluginGui = new GUI(pluginData, options) pluginGui.label = label pluginGui.render(instance, function (icon, settings) { obj.icon = icon icon.attr('mod-uri', escape(pluginData.uri)); if (pluginData.licensed < 0) { // This is a TRIAL plugin icon.find('[mod-role="drag-handle"]').addClass('demo-plugin').addClass('demo-plugin-light'); self.data('notifyDemoPluginLoaded')() } self.data('plugins')[instance] = icon if (! skipModified) { self.trigger('modified') } icon.data('uri', pluginData.uri) icon.data('ports', pluginData.ports) icon.data('gui', pluginGui) icon.data('settings', settings) icon.data('instance', instance) var address, symbol, port /* var hardware = self.data('hardwareManager') hardware.instanceAdded(instance) */ var addressFactory = function (port) { return function () { if ($(this).hasClass("disabled")) { return } var hardware = self.data('hardwareManager') hardware.open(instance, port, pluginData.label) } } for (symbol in pluginGui.controls) { port = pluginGui.controls[symbol] if (symbol == ':bypass') { if (pluginData.bypassable === false) { // host-implemented plugin without a bypass: no switch and no addressing for it settings.find('.mod-switch.bypass').hide() continue } address = settings.find('[mod-role=bypass-address]') } else if (symbol == ':presets') { address = settings.find('[mod-role=presets-address]') } else { address = settings.find('[mod-role=input-control-address][mod-port-symbol=' + symbol + ']') } if (address.length == 0) { continue } address.click(addressFactory(port)) } // Find elements with mod-role of audio/midi input/output ports and assign functionality to them var types = ['audio', 'midi', 'cv'] var directions = ['input', 'output'] var j, k, type, direction, method, element for (i = 0; i < types.length; i++) { type = types[i] for (j = 0; j < directions.length; j++) { direction = directions[j] if (!pluginData.ports[type] || !pluginData.ports[type][direction]) continue for (k = 0; k < pluginData.ports[type][direction].length; k++) { symbol = pluginData.ports[type][direction][k].symbol element = icon.find('[mod-role=' + direction + '-' + type + '-port][mod-port-symbol=' + symbol + ']') if (element.length == 0) continue // call either makeInput or makeOutput var method = 'make' + direction.charAt(0).toUpperCase() + direction.slice(1) self.pedalboard(method, element, instance) } } } icon.mousedown(function () { self.pedalboard('preventDrag', true) var upHandler = function () { self.pedalboard('preventDrag', false) $('body').unbind('mouseup', upHandler) } $('body').bind('mouseup', upHandler) }) icon.attr('mod-io-type', pluginData.iotype) icon.droppable({ accept: '[mod-role=available-plugin][mod-io-type="'+pluginData.iotype+'"]', tolerance: 'custom-replace', activeClass: 'possible-replaceable-drop', drop: function (event, ui) { // icon.removeClass('replaceable-drop') var overIcons = ui.helper.data('overIcons'); if (overIcons.length === 0 || overIcons[overIcons.length-1] != icon) { return; } ui.helper.data('overIcons', []); var instance = event.target.getAttribute('mod-instance') var connMgr = self.data('connectionManager') var replacement = { 'instance': instance, 'audio': [], 'midi': [], } connMgr.iterateInstance(instance, function (jack) { var input = jack.data('destination') var inport = input.attr('mod-port') var output = jack.data('origin') var outport = output.attr('mod-port') // Captured here because this is the last moment it exists: removing // the plugin below destroys these jacks, and the lifetime rule then // drops the name. close() puts both back when it recreates the cable. var teleport = jack.data('teleported') ? self.pedalboard('teleportName', output) : null var type if (input.hasClass('mod-audio-input')) { type = 'audio' } else if (input.hasClass('mod-midi-input')) { type = 'midi' } else { return } if (startsWith(inport, instance+'/')) { var symbol = inport.slice(instance.length+1) console.log(symbol, pluginData.ports[type]['input']) for (var i = 0; i < pluginData.ports[type]['input'].length; i++) { if (pluginData.ports[type]['input'][i].symbol == symbol) { inport = i break; } } } if (startsWith(outport, instance+'/')) { var symbol = outport.slice(instance.length+1) console.log(symbol, pluginData.ports[type]['output']) for (var i = 0; i < pluginData.ports[type]['output'].length; i++) { if (pluginData.ports[type]['output'][i].symbol == symbol) { outport = i break; } } } replacement[type].push([inport, outport, teleport]) }) console.log(replacement) self.data('replacementPlugin', replacement) self.pedalboard('removePlugin', instance, pluginData.ports) }, over: function (event, ui) { var overIcons = ui.helper.data('overIcons'); if (overIcons.length !== 0) { var oldIcon = overIcons[overIcons.length-1] oldIcon.removeClass('replaceable-drop') oldIcon.find('[mod-role="drag-handle"]').removeClass('replaceable-drop') } icon.addClass('replaceable-drop') icon.find('[mod-role="drag-handle"]').addClass('replaceable-drop') overIcons.push(icon) }, out: function (event, ui) { var overIcons = ui.helper.data('overIcons'); remove_from_array(overIcons, icon) if (icon.hasClass('replaceable-drop')) { icon.removeClass('replaceable-drop') icon.find('[mod-role="drag-handle"]').removeClass('replaceable-drop') if (overIcons.length !== 0) { var oldIcon = overIcons[overIcons.length-1] oldIcon.addClass('replaceable-drop') oldIcon.find('[mod-role="drag-handle"]').removeClass('replaceable-drop') } } }, }) var actions = $('
').addClass('ignore-arrive').addClass('mod-actions').appendTo(icon) if (pluginData.hasExternalUI) { $('
').addClass('mod-external-ui').click(function () { self.pedalboard('finishConnection') self.data('showExternalUI')(instance) return false }).appendTo(actions) } $('
').addClass('mod-information').click(function () { self.pedalboard('finishConnection') self.data('showPluginInfo')(pluginData) return false }).appendTo(actions) $('
').addClass('mod-settings').click(function () { self.pedalboard('finishConnection') settings.window('open') return false }).appendTo(actions) $('
').addClass('mod-remove').click(function () { self.pedalboard('finishConnection') self.pedalboard('removePlugin', instance, pluginData.ports) return false }).appendTo(actions) settings.window({ windowName: "Plugin Settings", windowManager: self.data('windowManager') }).appendTo($('body')) icon.css({ 'z-index': self.data('z_index'), position: 'absolute', left: x, top: y }).appendTo(self) // adjust position of cv out checkboxes if needed var lastCvPosY = -1, lastCvElem for (k = 0; k < pluginData.ports['cv']['output'].length; k++) { symbol = pluginData.ports['cv']['output'][k].symbol element = icon.find('[mod-role=' + direction + '-' + type + '-port][mod-port-symbol=' + symbol + ']') if (element.length == 0) continue var curCvPosY = element.position().top if (lastCvPosY != -1 && Math.abs(curCvPosY - lastCvPosY) < 50) { element.find('.output-cv-checkbox').css({left:'50px',top:'10px'}) lastCvElem.find('.output-cv-checkbox').css({left:'50px',top:'10px'}) } lastCvElem = element lastCvPosY = curCvPosY } self.data('z_index', self.data('z_index')+1) if (renderCallback) renderCallback() }) var replacementPlugin = self.data('replacementPlugin') self.data('replacementPlugin', null) if (replacementPlugin) { var hasConnectionsErrors = 0, connectionsDone = 0, connectionsToDo = replacementPlugin.audio.length + replacementPlugin.midi.length; function finalizeConnection(ok) { hasConnectionsErrors |= !ok; if (++connectionsDone == connectionsToDo && hasConnectionsErrors) { new Notification('error', "Failed to automatically reconnect all ports", 5000) } } for (var i in replacementPlugin.audio) { var ports = replacementPlugin.audio[i] var inport, outport if (typeof(ports[0]) === 'number') { inport = pluginData.ports['audio']['input'][ports[0]] if (inport === undefined) { continue } inport = instance+'/'+inport.symbol } else { inport = replacementPlugin.audio[i][0] } if (typeof(ports[1]) === 'number') { outport = pluginData.ports['audio']['output'][ports[1]] if (outport === undefined) { continue } outport = instance+'/'+outport.symbol } else { outport = replacementPlugin.audio[i][1] } var teleportKey = self.pedalboard('restoreReplacedTeleport', ports[2], outport, inport) self.data('portConnect')(outport, inport, self.pedalboard('replacedConnectionDone', teleportKey, finalizeConnection)) } for (var i in replacementPlugin.midi) { var ports = replacementPlugin.midi[i] var inport, outport if (typeof(ports[0]) === 'number') { inport = pluginData.ports['midi']['input'][ports[0]] if (inport === undefined) { continue } inport = instance+'/'+inport.symbol } else { inport = replacementPlugin.midi[i][0] } if (typeof(ports[1]) === 'number') { outport = pluginData.ports['midi']['output'][ports[1]] if (outport === undefined) { continue } outport = instance+'/'+outport.symbol } else { outport = replacementPlugin.midi[i][1] } var teleportKey = self.pedalboard('restoreReplacedTeleport', ports[2], outport, inport) self.data('portConnect')(outport, inport, self.pedalboard('replacedConnectionDone', teleportKey, finalizeConnection)) } } }, // Remove "Trial" watermark from all instances of a plugin license: function(uri) { var self = $(this); var plugins = self.data('plugins'); var icon; for (var instance in plugins) { icon = plugins[instance] if (icon && icon.data && icon.data('uri') == uri) { icon.find('[mod-role="drag-handle"]').removeClass('demo-plugin').removeClass('demo-plugin-light'); } } }, getLabel: function (instance) { var plugin = $(this).data('plugins')[instance] if (plugin && plugin.data) { return plugin.data('label') } return "effect" }, getGui: function (instance) { var plugin = $(this).data('plugins')[instance] if (plugin && plugin.data) { return plugin.data('gui') } return null }, getLoadedPluginURIs: function () { var plugin, plugins = $(this).data('plugins') var uri, uris = {} for (var i in plugins) { plugin = plugins[i] if (plugin != null && plugin.data != null) { uri = plugin.data('uri') if (uri != null) { uris[uri] = true } } } return Object.keys(uris) }, setPortEnabled: function (instance, symbol, enabled, feedback, forceAddress, momentaryMode) { var self = $(this) var targetname = '.mod-pedal[mod-instance="'+instance+'"]' var callbackId = instance+'/'+symbol+":enabled" var gui = self.pedalboard('getGui', instance) if (gui && self.find(targetname).length) { if (enabled || feedback) { gui.enable(symbol) } else { gui.disable(symbol) } if (forceAddress) { gui.addressPort(symbol, feedback, momentaryMode) } } else { var cb = function () { delete self.data('callbacksToArrive')[callbackId] self.unbindArrive(targetname, cb) var gui = self.pedalboard('getGui', instance) if (enabled || feedback) { gui.enable(symbol) } else { gui.disable(symbol) } if (forceAddress) { gui.addressPort(symbol, feedback, momentaryMode) } } self.pedalboard('addUniqueCallbackToArrive', cb, targetname, callbackId) } }, setPortWidgetsValue: function (instance, symbol, value) { var self = $(this) var targetname = '.mod-pedal[mod-instance="'+instance+'"]' var callbackId = instance+'/'+symbol+":value" var gui = self.pedalboard('getGui', instance) if (gui && self.find(targetname).length) { gui.setPortWidgetsValue(symbol, value, null, true) } else { var cb = function () { delete self.data('callbacksToArrive')[callbackId] self.unbindArrive(targetname, cb) var gui = self.pedalboard('getGui', instance) gui.setPortWidgetsValue(symbol, value, null, true) } self.pedalboard('addUniqueCallbackToArrive', cb, targetname, callbackId) } }, setOutputPortValue: function (instance, symbol, value) { var self = $(this) var gui = self.pedalboard('getGui', instance) if (gui) { gui.setOutputPortValue(symbol, value) } else { var targetname = '.mod-pedal[mod-instance="'+instance+'"]' var callbackId = instance+'/'+symbol+":value" var cb = function () { delete self.data('callbacksToArrive')[callbackId] self.unbindArrive(targetname, cb) var gui = self.pedalboard('getGui', instance) gui.setOutputPortValue(symbol, value) } self.pedalboard('addUniqueCallbackToArrive', cb, targetname, callbackId) } }, setReadableParameterValue: function (instance, uri, valuetype, valuedata) { var self = $(this) var gui = self.pedalboard('getGui', instance) if (gui) { gui.setReadableParameterValue(uri, valuetype, valuedata) } else { var targetname = '.mod-pedal[mod-instance="'+instance+'"]' var callbackId = instance+'@'+uri+'@value' var cb = function () { delete self.data('callbacksToArrive')[callbackId] self.unbindArrive(targetname, cb) var gui = self.pedalboard('getGui', instance) gui.setReadableParameterValue(uri, valuetype, valuedata) } self.pedalboard('addUniqueCallbackToArrive', cb, targetname, callbackId) } }, setWritableParameterValue: function (instance, uri, valuetype, valuedata) { var self = $(this) var targetname = '.mod-pedal[mod-instance="'+instance+'"]' var callbackId = instance+'@'+uri+'@value' var gui = self.pedalboard('getGui', instance) if (gui && self.find(targetname).length) { gui.setWritableParameterValue(uri, valuetype, valuedata, null, true) } else { var cb = function () { delete self.data('callbacksToArrive')[callbackId] self.unbindArrive(targetname, cb) var gui = self.pedalboard('getGui', instance) gui.setWritableParameterValue(uri, valuetype, valuedata, null, true) } self.pedalboard('addUniqueCallbackToArrive', cb, targetname, callbackId) } }, selectPreset: function (instance, value) { var self = $(this) var gui = self.pedalboard('getGui', instance) if (gui) { gui.selectPreset(value) } else { var targetname = '.mod-pedal[mod-instance="'+instance+'"]' var callbackId = instance+'/'+":presets" var cb = function () { delete self.data('callbacksToArrive')[callbackId] self.unbindArrive(targetname, cb) var gui = self.pedalboard('getGui', instance) gui.selectPreset(value) } self.pedalboard('addUniqueCallbackToArrive', cb, targetname, callbackId) } }, addUniqueCallbackToArrive: function (cb, targetname, callbackId) { var self = $(this); var callbacks = self.data('callbacksToArrive'), currentCallback = callbacks[callbackId]; if (currentCallback) { self.unbindArrive(targetname, currentCallback) } callbacks[callbackId] = cb self.arrive(targetname, cb) }, // Redraw all connections from or to a plugin drawPluginJacks: function (plugin) { var self = $(this) var myjacks = [] var connMgr = self.data('connectionManager') connMgr.iterateInstance(plugin.data('instance'), function (jack) { myjacks.push($(jack.data('svg')._container)) }) $('.hasSVG.cable-connected').filter(function(e) {!(e in myjacks)}).css({'z-index': 0}) connMgr.iterateInstance(plugin.data('instance'), function (jack) { self.pedalboard('drawJack', jack) $(jack.data('svg')._container).css({ 'z-index': self.data("z_index")-1, 'pointer-events': 'none'}) }) }, // Removes a plugin from pedalboard. (from the system?) // Calls application removal function with proper removal callback removePlugin: function (instance, ports) { var self = $(this) var pluginRemove = self.data('pluginRemove') pluginRemove(instance, function () { // Remove plugin's cv output ports from harware manager if (ports && ports.cv && ports.cv.output) { for (var i = 0; i < ports.cv.output.length; i++) { self.data('hardwareManager').removeCvOutputPort('/cv' + instance + '/' + ports.cv.output[i].symbol) } } }) }, removeItemFromCanvas: function (instance) { var self = $(this) var plugins = self.data('plugins') var connMgr = self.data('connectionManager') if (instance in plugins) { connMgr.iterateInstance(instance, function (jack) { var input = jack.data('destination') jack.data('canvas').remove() jack.remove() self.pedalboard('packJacks', input) }) connMgr.removeInstance(instance) self.data('hardwareManager').removeInstance(instance) var plugin = plugins[instance] // plugin might have failed to register if (plugin && plugin.data) { var pluginGui = plugin.data('gui') pluginGui && pluginGui.triggerJS({ type: 'end' }) } if (plugin && plugin.length) { plugin.remove() } delete plugins[instance] delete self.data('selected')[instance] // nothing else asks the canvas to reconsider its size after a removal, and // scheduleAdapt debounces, so deleting several plugins recalculates once self.pedalboard('scheduleAdapt', false) } else { connMgr.iterate(function (jack) { var input = jack.data('destination') var inport = input.attr('mod-port') var output = jack.data('origin') var outport = output.attr('mod-port') if (inport != instance && outport != instance) return connMgr.disconnect(outport, inport) jack.data('canvas').remove() jack.remove() self.pedalboard('packJacks', input) if (!connMgr.origIndex[outport] || Object.keys(connMgr.origIndex[outport]).length == 0) { output.addClass('output-disconnected') output.removeClass('output-connected') } }) var inputs = self.data('hwInputs') var outputs = self.data('hwOutputs') var hwsToRemove = [] inputs.forEach(function (hw) { if (hw.attr("mod-port-symbol") == instance) { hwsToRemove.push(hw) } }) for (var i in hwsToRemove) { hwsToRemove[i].remove() remove_from_array(inputs, hwsToRemove[i]) } hwsToRemove = [] outputs.forEach(function (hw) { if (hw.attr("mod-port-symbol") == instance) { hwsToRemove.push(hw) } }) for (var i in hwsToRemove) { hwsToRemove[i].remove() remove_from_array(outputs, hwsToRemove[i]) } self.pedalboard('positionHardwarePorts') } // Both branches above remove jacks with a bare jack.remove(), so nothing here // reaches teleportsChanged on its own. [] because the jacks are already gone: this // only re-derives which names are still spoken for. self.pedalboard('teleportsChanged', []) }, // Highlight all inputs to which a jack can be connected (any inputs that are not from same // instance and are not already connected). Highlight parameter indicates if we want highlighting // on or off. If highlight parameter is false, no jack is needed. highlightInputs: function (highlight, jack) { var self = $(this) var connMgr = self.data('connectionManager') if (!highlight) { self.find('[mod-role=input-audio-port]').removeClass('input-connecting') self.find('[mod-role=input-midi-port]').removeClass('input-connecting') self.find('[mod-role=input-cv-port]').removeClass('input-connecting') self.find('[mod-role=input-audio-port]').removeClass('input-connecting-highlight') self.find('[mod-role=input-midi-port]').removeClass('input-connecting-highlight') self.find('[mod-role=input-cv-port]').removeClass('input-connecting-highlight') return } var output = jack.data('origin') var fromPort = output.attr('mod-port') var portType = output.data('portType') self.find('[mod-role=input-' + portType + '-port]').each(function () { $(this).addClass('input-connecting') }); }, // Removes all plugins and restore pedalboard initial state, so that a new pedalboard // can be created reset: function (callback) { var self = $(this) self.data('bypassApplication', false) self.data('callbacksToArrive', {}) // Its own teardown window, around this loop only. It must not span the async // callback below -- resetData opens its own in there, and a flag left raised // across the gap would swallow real edits if that callback never fires. var connMgr = self.data('connectionManager') self.data('teleportsTeardown', true) try { connMgr.iterate(function (jack) { self.pedalboard('disconnect', jack) }) } finally { // a throw in here must not leave the flag raised: it would silently swallow // every teleport POST for the rest of the session self.data('teleportsTeardown', false) } self.data('reset')(function (ok) { if (!ok) { return } self.pedalboard('resetData') if (callback) { callback() } }) }, // Removes all pedalboard data resetData: function () { var self = $(this) // destroyJack runs per jack and each call POSTs, which would race the next // board's load. The in-memory prune still runs; only the network call waits. self.data('teleportsTeardown', true) try { // Nothing re-seeds these on a blank board: applyTeleports only runs when a // bundle is loaded, so a key parked by the previous board would survive. Port // ids are identical across boards, so wiring capture_1 -> playback_1 on the // new one would silently come up teleported under the old board's name. self.data('pendingTeleports', {}) self.data('teleportNames', {}) self.data('teleportNamesRemembered', {}) // teleportGen is deliberately NOT cleared: it is the server's, and resetData // runs twice per reset with the server's message landing between the two. self.data('hardwareManager').reset() var connMgr = self.data('connectionManager') connMgr.iterate(function(jack) { self.pedalboard('destroyJack', jack); }) connMgr.reset() var plugins = self.data('plugins') for (var instance in plugins) { var plugin = plugins[instance] // plugin might have failed to register if (plugin && plugin.data) { var pluginGui = plugin.data('gui') pluginGui && pluginGui.triggerJS({ type: 'end' }) } if (plugin && plugin.length) { plugin.remove() } } self.data('plugins', {}) self.pedalboard('resetSize') } finally { // a throw anywhere above must not leave the flag raised: it would silently // swallow every teleport POST for the rest of the session self.data('teleportsTeardown', false) } }, // Make element an audio/midi inputs, to which jacks can be dragged to make connections makeInput: function (element, instance) { var self = $(this) var symbol = element.attr('mod-port-symbol') var portType = element.attr('mod-role').split(/-/)[1] element.addClass('mod-input') element.addClass('mod-' + portType + '-input') element.addClass('input-disconnected') element.data('instance', instance) element.data('symbol', symbol) element.data('portType', portType) if (instance != "") element.attr('mod-port', instance + "/" + symbol) else element.attr('mod-port', symbol) element.droppable({ accept: '[mod-role=output-jack]', tolerance: 'custom', drop: function (event, ui) { var overCount = self.data('overCount'); self.data('overCount', 0); self.data('background').droppable('enable') var jack = ui.draggable var outputType = jack.parent().attr('mod-role').split(/-/)[1] var inputType = element.attr('mod-role').split(/-/)[1] if (outputType != inputType) { return } self.pedalboard('do_connect', jack, element, overCount) element.removeClass('input-connecting-highlight') }, over: function (event, ui) { var outputType = ui.draggable.parent().attr('mod-role').split(/-/)[1] var inputType = element.attr('mod-role').split(/-/)[1] if (outputType != inputType) return element.addClass('input-connecting-highlight') var overCount = self.data('overCount')+1; self.data('overCount', overCount); if (overCount == 1) { self.data('background').droppable('disable') } }, out: function (event, ui) { element.removeClass('input-connecting-highlight') var overCount = self.data('overCount')-1; if (overCount < 0) { overCount = 0 } self.data('overCount', overCount); if (overCount == 0) { self.data('background').droppable('enable') } }, greedy: true, }) element.click(function () { var connection = self.data('ongoingConnection') if (connection) { self.pedalboard('do_connect', connection.jack, element) } else { self.pedalboard('expandInput', element) } }) }, // Make element an audio output, which contain jacks that can be dragged to // inputs to make connections makeOutput: function (element, instance) { var self = $(this) var symbol = element.attr('mod-port-symbol') var portType = element.attr('mod-role').split(/-/)[1] element.addClass('mod-output') element.addClass('mod-' + portType + '-output') element.addClass('output-disconnected') element.data('instance', instance) element.data('symbol', symbol) element.data('portType', portType) if (instance != "") element.attr('mod-port', instance + "/" + symbol) else element.attr('mod-port', symbol) self.pedalboard('spawnJack', element) element.click(function (e) { // Do not start connection if cv addressing checkbox or text input clicked if (!$(e.target).is('input') && !$(e.target).hasClass('checkmark') && !$(e.target).hasClass('checkbox-container')) { self.pedalboard('startConnection', element) } }) }, // Creates a jack element inside an output. This jack can then be dragged and dropped // inside an input to connect them. // Each jack knows it's origin's instance and symbol, and also tracks several elements // that are created with it to draw fancy cables. spawnJack: function (output) { var self = $(this) var jack = $('
').appendTo(output) jack.attr('mod-role', 'output-jack') jack.addClass('mod-output-jack') jack.addClass('jack-disconnected') // Track the origin of the jack jack.data('origin', output) // Indicates if this jack is connected to an input or not, and to which input jack.data('connected', false) jack.data('destination', null) // Create a canvas occupying the whole screen, which will be used to draw this // jack's cable. // The cable is composed by three lines with different style: one for the cable, // one for the background shadow and one for the reflecting light. var canvas = $('
'); canvas.addClass('ignore-arrive'); // named so the tracing css can dim every cable without also catching the canvas // that startConnection makes for a cable being dragged canvas.addClass('mod-cable-canvas'); if (output.attr("class").search("mod-audio-") >= 0) canvas.addClass("mod-audio"); else if (output.attr("class").search("mod-midi-") >= 0) canvas.addClass("mod-midi"); else if (output.attr("class").search("mod-cv-") >= 0) canvas.addClass("mod-cv"); // Add checkbox + text inputs next to output cv ports for addressings if (output.attr('mod-role') === 'output-cv-port' && output.find('.output-cv-checkbox').length === 0) { var port = output.attr("mod-port"); var portSymbol = output.attr("mod-port-symbol"); var cvPort = '/cv' + port; var addedPort = self.data('hardwareManager').cvOutputPorts.find(function (port) { return port.uri === cvPort; }); var cvCheckboxInput = $('
'); cvCheckboxInput.addClass('ignore-arrive'); // Append checkbox var checkbox = $(''); var checkboxContainer = $(''); checkbox.appendTo(checkboxContainer); $('').appendTo(checkboxContainer); checkboxContainer.appendTo(cvCheckboxInput); // Append text input var textInput = $(''); textInput.appendTo(cvCheckboxInput); cvCheckboxInput.addClass('output-cv-checkbox'); cvCheckboxInput.appendTo(output); if (!self.data('cvAddressing')) { cvCheckboxInput.hide() } // Disable inputs for hardware cv ports var defaultText = output.attr("title") if ( portSymbol === "/graph/cv_exp_pedal" || portSymbol === "/graph/cv_capture_1" || portSymbol === "/graph/cv_capture_2" ) { checkbox.prop('disabled', true); checkbox.prop('checked', true); textInput.prop('disabled', true); } else { // Add default displayed name to plugins CV ports var instance = port .split("/graph/")[1] .split("/")[0] .replace(/^\w/, function(chr) { return chr.toUpperCase(); }); defaultText = instance + " " + defaultText if (addedPort) { defaultText = addedPort.name; checkbox.prop('checked', true); } else { textInput.hide(); } } textInput.val(defaultText); checkbox.change(function () { var name = textInput.val(); if ($(this).prop('checked')) { // Register new addressable cv port self.data('addCVAddressingPluginPort')(cvPort, name, function (resp) { if (resp && resp.ok) { self.data('hardwareManager').addCvOutputPort(cvPort, name, resp.operational_mode); // Show and highlight text input textInput.show(); textInput.select(); } }); } else { // Unregister cv port self.data('removeCVAddressingPluginPort')(cvPort, function (resp) { if (resp) { self.data('hardwareManager').removeCvOutputPort(cvPort); // Hide text input again textInput.hide(); } }); } }) textInput.change(function () { var name = $(this).val(); self.data('addCVAddressingPluginPort')(cvPort, name, function (resp) { if (resp && resp.ok) { self.data('hardwareManager').addCvOutputPort(cvPort, name, resp.operational_mode); } }); }); textInput.keydown(function (e) { if (e.keyCode === 13) { $(this).blur(); } }); } canvas.css({ width: '100%', height: '100%', position: 'absolute', top: 0, left: 0 }) self.append(canvas) canvas.svg() var svg = canvas.find('svg') svg.css({ width: '100%', height: '100%', position: 'absolute', top: 0, left: 0 }) jack.data('canvas', canvas) svg = canvas.svg('get') jack.data('svg', svg) canvas.data('pathShadow', svg.createPath()) canvas.data('pathCable', svg.createPath()) canvas.data('pathLight', svg.createPath()) jack.draggable({ revert: 'invalid', revertDuration: 0, start: function () { // Prevents dragging of whole pedalboard while jack is being dragged self.pedalboard('preventDrag', true) // If user has started a connection by clicking a jack, this drag will // end it self.pedalboard('finishConnection') // the cable about to be dragged is drawn into this jack's own canvas, so // any trace still running would dim it along with the rest self.pedalboard('clearTracing') // Highlight all inputs in which this jack can be dropped self.pedalboard('highlightInputs', true, jack) // While jack is being dragged, all related elements receive // the "*-connecting" class jack.removeClass('jack-disconnected') jack.removeClass('jack-connected') jack.addClass('jack-connecting') output.addClass('output-connecting') canvas.removeClass('cable-connected') canvas.addClass('cable-connecting') var cur = jack.data('destination') if (cur) cur.removeClass('input-connected') }, drag: function (e, ui) { var scale = self.data('scale') ui.position.top /= scale ui.position.left /= scale jack.css({ marginTop: 0 }) self.pedalboard('drawJack', jack, true) }, stop: function () { self.pedalboard('preventDrag', false) self.pedalboard('highlightInputs', false) jack.removeClass('jack-connecting') output.removeClass('output-connecting') canvas.removeClass('cable-connecting') if (!jack.hasClass('jack-connected')) { jack.addClass('jack-disconnected') jack.css({ top: 'auto', left: 'auto', marginTop: 'auto', }) // if jack output previous sibling has a margin-bottom, // adjust jack top position in accordance if (jack.data('origin') && jack.data('origin').prev() && jack.data('origin').prev().css('margin-bottom')) { jack.css('top', parseInt(jack.css('top')) - parseInt(jack.data('origin').prev().css('margin-bottom'))) } } self.pedalboard('drawJack', jack) } }) // draggable puts position relative in jack. this messes with layout and is not necessary // in this case, because we'll recalculate the position during drag anyway because of scaling jack.css('position', 'absolute') canvas.click(function () { self.pedalboard('colapseInput') self.pedalboard('finishConnection') }) return jack }, destroyJack: function (jack) { var self = $(this) var output = jack.data('origin') var input = jack.data('destination') // Looked up while the connection is still there, because that is what identifies // the pair. A merged stereo cable is painted into one half's canvas, so losing // either half leaves the wrong thing on screen - a cable with a leg dangling // where its partner used to land, or nothing at all - until what is left of the // pair is redrawn on its own var pair = self.pedalboard('stereoPartnerJack', jack) self.pedalboard('clearTracing') self.data('connectionManager').disconnect(output.attr('mod-port'), input.attr('mod-port')) jack.data('canvas').remove() jack.remove() // after the remove, not before: teleportedJacks() walks the live dom, so a jack // still in it counts itself and the prune lags a cable behind self.pedalboard('teleportsChanged', []) self.pedalboard('packJacks', input) if (pair) { self.pedalboard('drawJack', pair.jack) } }, // The port element that `element` forms a stereo pair with, or null. `first` tells // whether `element` is the left/odd half of that pair, which is the half that owns // the drawing of the merged cable. stereoPartner: function (element) { var self = $(this) // Off unless turned on in Settings (and always off where there are no preferences, // like the screenshot renderer): every connection then draws as its own cable, // which is what the rest of the code does anyway when nothing pairs up. if (typeof PREFERENCES === 'undefined' || PREFERENCES['merge-stereo-cables'] != "true") { return null } var counterpart = stereoCounterpart(element.data('symbol')) if (! counterpart) { return null } var instance = element.data('instance') var port = instance ? instance + '/' + counterpart.symbol : counterpart.symbol var partner = self.find('[mod-port="' + port + '"]') // Guessing the name is not enough. It has to be a port that exists, and one that // faces the same way and carries the same kind of signal, or "gain_1" pairs with // a control port and a hardware capture pairs with a playback if (partner.length !== 1 || partner.hasClass('mod-output') !== element.hasClass('mod-output') || partner.data('portType') !== element.data('portType')) { return null } return { element: partner, first: counterpart.first } }, // The jack that pairs with `jack` to make one stereo cable, plus whether `jack` is // the left/odd half. That is a stereo pair wired straight across, or one output into // both halves of a stereo input (mono into stereo), or both halves of a stereo output // into one input (stereo into mono): the ends that coincide meet in one point. Null // when there is no pair: the ports do not name themselves as one, they are crossed // over, or nothing matching is wired up on the other side. stereoPartnerJack: function (jack) { var self = $(this) var input = jack.data('destination') if (! jack.data('connected') || ! input) { return null } var origin = jack.data('origin') var output = self.pedalboard('stereoPartner', origin) var dest = self.pedalboard('stereoPartner', input) var origIndex = self.data('connectionManager').origIndex var jackBetween = function (from, to) { return (origIndex[from.attr('mod-port')] || {})[to.attr('mod-port')] || null } var partner // A pair wired straight across is one cable. L to R and R to L is a channel swap, // and drawing that as one cable would hide what it does if (output && dest && dest.first === output.first) { partner = jackBetween(output.element, dest.element) if (partner) { return { jack: partner, first: output.first } } } // the same output into the other half of the input's pair if (dest) { partner = jackBetween(origin, dest.element) if (partner) { return { jack: partner, first: dest.first } } } // the other half of the output's pair into the same input if (output) { partner = jackBetween(output.element, input) if (partner) { return { jack: partner, first: output.first } } } return null }, // Origin and destination anchor points of one jack's cable, in canvas coordinates jackCoords: function (jack, force) { var self = $(this) var source = jack.data('origin') var scale = self.data('scale') // Cable will follow a cubic bezier curve, which is defined by 4 points. They are: // P0 (xi, yi) - starting point // P3 (xo, yo) - the destination point // P1 (xo - deltaX, yi) and P2 (xi + deltaX, yo): define the curve // Gets origin and destination coordinates var xi = source.offset().left / scale - self.offset().left / scale + source.width() var yi = source.offset().top / scale - self.offset().top / scale + source.height() / 2 var xo = jack.offset().left / scale - self.offset().left / scale var jackOffsetTop = jack.offset().top // Adjust jack offset top position // that is sometimes biased by jack destination previous sibling margin bottom if (!force && parseInt(jack.css('top')) === 0 && parseInt(jack.css('bottom')) === 0) { jackOffsetTop = jack.offset().top - jack.position().top } var yo = jackOffsetTop / scale - self.offset().top / scale + jack.height() / 2 return { xi: xi, yi: yi, xo: xo, yo: yo } }, // How far a teleport's stub runs before it meets its box. // (TELEPORT_STUB is defined at the bottom of this file, beside cableDeltaX) // The name of the point an output feeds, or null if it has none. teleportName: function (port) { var self = $(this) return self.data('teleportNames')[port.attr('mod-port')] || null }, // Every jack currently drawn as a teleport. Walked rather than indexed: teleports are // changed by hand, a few at a time, so there is nothing here worth an index. teleportedJacks: function () { var self = $(this) var out = [] self.find('[mod-role=output-jack]').each(function () { var jack = $(this) if (jack.data('teleported') && jack.data('connected')) { out.push(jack) } }) return out }, // The cables the teleport key acts on. A jack inside an expanded input is a single cable and wins, // because that is the whole reason for expanding an input; otherwise it is every cable // on the hovered port, whichever way round the port is. teleportTarget: function () { var self = $(this) var jack = self.data('hoverJack') if (jack && jack.data('connected') && jack.closest('.expanded').length) { return [jack] } var port = self.data('hoverPort') if (! port) { return [] } var jacks = self.pedalboard('jacksAtPort', port) var out = [] for (var i = 0; i < jacks.length; i++) { if (jacks[i] && jacks[i].data('connected')) { out.push(jacks[i]) } } return out }, // Turns the given cables into teleports, or back if they are all already on. Follows a // stereo partner in BOTH directions: un-teleporting one leg at a time would leave the // pair half-teleported, which is what the rule exists to prevent. toggleTeleport: function (jacks) { var self = $(this) var i if (! jacks.length) { return } var turningOff = true for (i = 0; i < jacks.length; i++) { if (! jacks[i].data('teleported')) { turningOff = false break } } var todo = [] var seen = [] for (i = 0; i < jacks.length; i++) { var group = [jacks[i]] var pair = self.pedalboard('stereoPartnerJack', jacks[i]) if (pair && pair.jack.data('connected')) { group.push(pair.jack) } for (var g = 0; g < group.length; g++) { if (seen.indexOf(group[g][0]) < 0) { seen.push(group[g][0]) todo.push(group[g]) } } } for (i = 0; i < todo.length; i++) { var jack = todo[i] jack.data('teleported', ! turningOff) if (! turningOff) { // an output with no name yet gets one, unique by construction var output = jack.data('origin') if (! self.pedalboard('teleportName', output)) { var names = self.data('teleportNames') var key = output.attr('mod-port') var last = self.data('teleportNamesRemembered')[key] if (last && teleportNameAvailable(last, key, names)) { // what you called it last time, unless someone else has taken it names[key] = last } else { var pluginName = self.pedalboard('teleportPluginName', output) var portName = output.attr('title') || output.data('symbol') || '' // The left half of a stereo pair names the pair, since that is the // one box shown for it: "Sitar Audio Output", not "... Output 1". var pair = self.pedalboard('stereoPartnerJack', jack) if (pair && pair.first && pair.jack.data('connected')) { var other = pair.jack.data('origin') var shared = teleportPairPortName(portName, other.attr('title') || other.data('symbol') || '') // hardware has no plugin name to fall back on, so keep the port's if (shared || pluginName) { portName = shared } } names[key] = teleportDefaultName(pluginName, portName, names) } } } } self.pedalboard('teleportsChanged', todo) self.trigger('modified') }, // The plugin a port belongs to, by the name shown on its pedal, for use in a default // teleport name. The plugin's own label wins over the effect's -- the same order // updateGlobalVUMeterPluginInfo uses. Hardware ports belong to no plugin and get an // empty string, which teleportDefaultName handles by using the port name alone. teleportPluginName: function (port) { var self = $(this) var instance = port.data('instance') if (! instance) { return '' } // getGui, not data('plugins') directly: host.js leaves a bare {} placeholder while // /effect/get is in flight, and {} is truthy but has no .data. getGui guards it. var gui = self.pedalboard('getGui', instance) if (! gui) { return '' } return gui.label || (gui.effect ? gui.effect.label : '') || '' }, // THE lifetime rule: a name exists exactly as long as one of its output's cables is // teleported. Split out of teleportsChanged so finishTeleportLoad can apply it without // posting or marking the board modified. pruneTeleportNames: function () { var self = $(this) var names = self.data('teleportNames') var used = {} var live = self.pedalboard('teleportedJacks') for (var i = 0; i < live.length; i++) { used[live[i].data('origin').attr('mod-port')] = true } // A cable with no jack right now still counts if it is parked in pendingTeleports: // during a load its connection has not arrived yet, and during a re-route the jack // carrying it is destroyed and replaced. Either way the name must survive the gap. var pending = self.data('pendingTeleports') for (var key in pending) { used[key.split(TELEPORT_ARROW)[0]] = true } var remembered = self.data('teleportNamesRemembered') for (var port in names) { if (! used[port]) { // keep it recallable, but stop it occupying the namespace remembered[port] = names[port] delete names[port] } } }, // Everything that changes a teleport ends here: prune names, drop dead boxes, redraw, // and post the map so it reaches the next save. Marking the board modified is the // caller's job. teleportsChanged: function (jacks) { var self = $(this) var i self.pedalboard('pruneTeleportNames') self.pedalboard('pruneTeleportBoxes') for (i = 0; i < (jacks || []).length; i++) { self.pedalboard('drawJack', jacks[i]) } // No generation means no board has been handed to us yet, so nothing to post // about. The teardown flag saves pointless writes; the generation is what makes a // late one harmless. var gen = self.data('teleportGen') if (! self.data('teleportsTeardown') && gen !== null && gen !== undefined) { $.ajax({ url: '/pedalboard/teleports/', type: 'POST', data: { teleports: JSON.stringify(self.pedalboard('serialiseTeleports')), gen: gen, }, cache: false, dataType: 'json', }) } // A trace names the canvas each cable was painted into when the pointer arrived. // Teleporting moves that paint and adds boxes that did not exist to be lit, so the // stale trace dims the very cable under the pointer. Recompute, behind the redraws // above, which are what create the boxes. if (self.hasClass('mod-tracing')) { setTimeout(function () { var hovered = self.data('hoverPort') if (! hovered) { return } self.pedalboard('clearTracing') self.pedalboard('traceFrom', hovered) }, 0) } }, // The saved shape, built from the live jacks rather than from a stored key set. A jack // dragged to another input is disconnected and reconnected as the SAME element, so a // set keyed by "out -> in" would see one key vanish and an unrelated one appear; the // flag rides on the jack instead and the key comes out right here. serialiseTeleports: function () { var self = $(this) var jacks = self.pedalboard('teleportedJacks') var cables = [] for (var i = 0; i < jacks.length; i++) { cables.push({ from: jacks[i].data('origin').attr('mod-port'), to: jacks[i].data('destination').attr('mod-port') }) } return teleportSerialise(self.data('teleportNames'), cables) }, // Applies a map that arrived with a pedalboard. Names are usable at once; most cables // are not, because their plugins are still being built by an async /effect/get. Those // are parked in pendingTeleports and consumed by connect() as each cable appears. // Deliberately not via teleportsChanged, which would post straight back. applyTeleports: function (data) { var self = $(this) var parsed = teleportDeserialise(data) var manager = self.data('connectionManager') // this map belongs to THIS load: started fresh, so a cable left unplaced by a // previous board can never latch onto a connection in the next one var pending = {} var i self.data('teleportNames', parsed.names) self.data('pendingTeleports', pending) // the generation this map belongs to, echoed back on every POST so the server can // drop a write computed from a board that has since been torn down self.data('teleportGen', (data && typeof data.gen === 'number') ? data.gen : null) for (i = 0; i < parsed.cables.length; i++) { var from = parsed.cables[i].from var to = parsed.cables[i].to var byDest = manager.origIndex[from] var jack = byDest ? byDest[to] : null if (jack) { jack.data('teleported', true) } else { pending[from + TELEPORT_ARROW + to] = true } } var jacks = self.pedalboard('teleportedJacks') self.pedalboard('pruneTeleportBoxes') for (i = 0; i < jacks.length; i++) { self.pedalboard('drawJack', jacks[i]) } }, // Once a load finishes, anything still pending named a cable that never showed up, so // it is dropped rather than left to latch onto a later connection. Prunes directly // rather than via teleportsChanged, which would post back and dirty the board. finishTeleportLoad: function () { var self = $(this) self.data('pendingTeleports', {}) self.pedalboard('pruneTeleportNames') }, // Applies a name the user typed. Empty removes the teleport from this output's cables. // A name another output holds is refused and the caller restores the old text -- // silently renumbering it, or taking it off the other output, would both be worse. setTeleportName: function (port, typed) { var self = $(this) var names = self.data('teleportNames') var key = port.attr('mod-port') var name = (typed || '').trim() var affected = [] var jacks = self.pedalboard('teleportedJacks') var i for (i = 0; i < jacks.length; i++) { if (jacks[i].data('origin').attr('mod-port') === key) { affected.push(jacks[i]) } } // The box under the pointer is about to be replaced or removed, so its mouseleave // will never arrive and the trace would stay on with nothing to clear it -- the // board sits dimmed until something else happens. destroyJack does this for the // same reason. self.pedalboard('clearTracing') if (! name) { // A pair is teleported together (toggleTeleport), and its box stands for both // halves, so clearing it un-teleports both -- not just the half that owns the // name, which would leave the other alone as a teleport of its own. var partners = [] for (i = 0; i < affected.length; i++) { var pair = self.pedalboard('stereoPartnerJack', affected[i]) if (pair && pair.jack.data('teleported')) { partners.push(pair.jack) } } affected = affected.concat(partners) for (i = 0; i < affected.length; i++) { affected[i].data('teleported', false) } delete names[key] // an explicit discard, so the remembered copy goes too -- otherwise an earlier // toggle-off would quietly bring the old label back on the next teleport delete self.data('teleportNamesRemembered')[key] self.pedalboard('teleportsChanged', affected) self.trigger('modified') return true } if (! teleportNameAvailable(name, key, names)) { return false } names[key] = name self.pedalboard('teleportsChanged', affected) self.trigger('modified') return true }, // How many teleported cables arrive at one input. They all draw their box at the same // place, so past one only the topmost is visible and the rest are hidden behind it. teleportsIntoPort: function (port) { var self = $(this) var wanted = port.attr('mod-port') var jacks = self.pedalboard('teleportedJacks') var n = 0 for (var i = 0; i < jacks.length; i++) { var dest = jacks[i].data('destination') if (dest && dest.attr('mod-port') === wanted) { n++ } } return n }, // The count shown over a pile of boxes at one input, so a stack of them does not read // as a single teleport. One badge per input rather than one per box: they are all at // the same spot, and which of them ends up on top is not something to depend on. teleportBadge: function (port) { var self = $(this) var boxes = self.data('teleportBoxes') var key = 'badge ' + port.attr('mod-port') var badge = boxes[key] if (! badge) { badge = $('
').addClass('ignore-arrive mod-teleport-badge') badge.attr('title', 'Several teleports arrive here -- click to fan them out') badge.on('mousedown', function (e) { e.stopPropagation() }) // as above: a second click on the badge must not zoom the board out badge.on('dblclick', function (e) { e.stopPropagation() }) badge.on('click', function (e) { e.stopPropagation() self.pedalboard('expandInput', port) }) badge.appendTo(self) boxes[key] = badge } badge.data('port', port) return badge }, // The box at one end of a teleport. Keyed by side, port and name, so an output with // one name shows one box however many cables leave it, and an input shows one box per // distinct name arriving. Boxes are html, not svg: they take text and a caret, and the // canvas holding the svg has pointer-events:none anyway. teleportBox: function (side, port, name) { var self = $(this) var boxes = self.data('teleportBoxes') var key = side + ' ' + port.attr('mod-port') + ' ' + name var box = boxes[key] if (! box) { box = $('') box.addClass('ignore-arrive mod-teleport mod-teleport-' + side) if (side === 'in') { // Only the output end is editable; the input ends mirror it. Kept out of // the tab order as well as read-only -- it is a label, and anything that // invites you to type in it is a lie, since the text lives on the output. box.attr('readonly', 'readonly') box.attr('tabindex', '-1') } box.appendTo(self) if (side === 'out') { box.on('keydown', function (e) { // do not let the board's own shortcuts see the typing e.stopPropagation() if (e.keyCode === 13) { $(this).blur() } else if (e.keyCode === 27) { $(this).val($(this).data('committed')).blur() } }) box.on('focus', function () { $(this).data('committed', $(this).val()) }) box.on('blur', function () { var typed = $(this).val() // nothing typed, nothing to commit -- this is also what makes Escape a // real cancel, since it puts the committed text back before blurring if (typed === $(this).data('committed')) { return } if (! self.pedalboard('setTeleportName', $(this).data('port'), typed)) { $(this).val($(this).data('committed')) $(this).addClass('mod-teleport-clash') var flashing = $(this) setTimeout(function () { flashing.removeClass('mod-teleport-clash') }, 900) } }) } if (side === 'in') { // The label is what you can actually hit when several teleports stack at // one input -- the input itself is behind them. Same action as clicking // the port: fan the jacks out so each box gets its own cable. box.on('click', function (e) { e.stopPropagation() self.pedalboard('expandInput', $(this).data('port')) }) } // Both ends swallow mousedown, or a click on a label pans the board. The // read-only end also refuses focus: it is still an , so preventDefault // is what stops a caret appearing in a field you cannot type into. The click // still fires, which is what fans the stack out. box.on('mousedown', function (e) { e.stopPropagation() if (side === 'in') { e.preventDefault() } }) // Stopped from reaching the board, which double-click-zooms out, and body, // where desktop.js preventDefaults every dblclick and kills the selection. // Only the editable end selects: doing it on the mirror suggests you can // change it there. box.on('dblclick', function (e) { e.stopPropagation() if (side === 'out') { this.select() } }) boxes[key] = box } box.data('port', port) // the box is narrower than some names, so the full one is on hover box.attr('title', name) // do not fight the caret while the user is typing in this very box if (document.activeElement !== box[0]) { box.val(name) } return box }, // Drops boxes that no teleported cable asks for any more. Called when teleports // change -- a keypress, a rename, a disconnect -- not on every redraw, because a // redraw happens on every drag tick and changes nothing about which boxes exist. pruneTeleportBoxes: function () { var self = $(this) var boxes = self.data('teleportBoxes') var live = {} var jacks = self.pedalboard('teleportedJacks') for (var i = 0; i < jacks.length; i++) { var jack = jacks[i] var name = self.pedalboard('teleportName', jack.data('origin')) if (! name) { continue } // the left half's boxes stand for a merged pair; the right half has none var tpair = self.pedalboard('teleportPair', jack) if (tpair && tpair.right[0] === jack[0]) { continue } live['out ' + jack.data('origin').attr('mod-port') + ' ' + name] = true live['in ' + jack.data('destination').attr('mod-port') + ' ' + name] = true } for (var key in boxes) { // A badge is keyed by input port, not by name, so the name-based sweep below // says nothing about it. It goes when its input no longer has a pile to count // -- including when the last teleport there is removed, after which // drawTeleportJack never runs for that input again to take it down itself. if (key.indexOf('badge ') === 0) { var bport = boxes[key].data('port') if (! bport || ! bport.closest('body').length || self.pedalboard('teleportsIntoPort', bport) < 2) { boxes[key].remove() delete boxes[key] } continue } if (! live[key]) { boxes[key].remove() delete boxes[key] } } }, // Puts a teleport back on a cable a plugin replacement is recreating: the old jack is // gone, so both the flag and the name went with it. Parks the cable so connect() flags // whichever jack carries it. Only reclaims the name if it is still free. restoreReplacedTeleport: function (name, outport, inport) { var self = $(this) if (! name) { return null } var names = self.data('teleportNames') if (! names[outport] && teleportNameAvailable(name, outport, names)) { names[outport] = name } if (! names[outport]) { return null } var key = outport + TELEPORT_ARROW + inport self.data('pendingTeleports')[key] = true // Handed back so the caller can drop it if the reconnect is refused. A key nobody // consumes is not harmless: pruneTeleportNames counts a parked key as in use, so // the name would sit in the namespace with no cable and no box until the next load. // do_connect does the same on its own failure path. return key }, // Wraps the replacement's finalizeConnection so a refused reconnect also un-parks the // teleport key restoreReplacedTeleport put down for it. replacedConnectionDone: function (key, finalize) { var self = $(this) return function (ok) { if (! ok && key) { delete self.data('pendingTeleports')[key] // the key was the only thing keeping that name alive; without this it sits // in the namespace with no cable and no box, refusing itself to others self.pedalboard('pruneTeleportNames') } finalize(ok) } }, // The canvas actually carrying a jack's paint, and which half of it the jack is. Both // halves of a merged stereo pair are painted together into the left half's canvas and // the right half's is emptied, so hovering either half lights the left one; leg says // which of the two sets of legs is the hovered jack's own. An unmerged cable is all // one thing, so its leg is null. litCanvas: function (jack) { var self = $(this) // A merged teleported pair is painted whole into its left half's canvas too, and // lit whole: its legs are too short to be worth telling apart. var tpair = self.pedalboard('teleportPair', jack) if (tpair) { return { canvas: tpair.left.data('canvas'), leg: null, partner: tpair.left[0] === jack[0] ? tpair.right : tpair.left } } var pair = self.pedalboard('stereoPartnerJack', jack) // Same guard as drawStereoJack: a teleported pair is painted into two separate // canvases, not merged into the left half's, so resolving to the partner's canvas // here would light the wrong cable (or the partner's, and never this jack's own) // whenever either half of the pair is teleported. if (pair && pair.jack.data('connected') && ! jack.data('teleported') && ! pair.jack.data('teleported')) { return { canvas: (pair.first ? jack : pair.jack).data('canvas'), leg: pair.first ? 0 : 1, partner: pair.jack } } return { canvas: jack.data('canvas'), leg: null, partner: null } }, // Every jack touching a port. origIndex is keyed by output port and destIndex by // input port, each holding a map of the other end to its jack, so one lookup in each // covers a port whichever way round it is. jacksAtPort: function (port) { var self = $(this) var name = port.attr('mod-port') var manager = self.data('connectionManager') var jacks = [] if (! name || ! manager) { return jacks } var indexes = [manager.origIndex[name], manager.destIndex[name]] for (var i = 0; i < indexes.length; i++) { for (var otherEnd in indexes[i]) { jacks.push(indexes[i][otherEnd]) } } return jacks }, // True while a new cable is being made, either by dragging a jack out of an output or // by the click to start, click to finish path. Tracing keeps out of the way then: the // cable being dragged is drawn into its own jack's canvas, which the dimming would // catch, so the one cable the pointer is carrying is the one that would go dim. connecting: function () { var self = $(this) return !! self.data('ongoingConnection') || self.find('.jack-connecting').length > 0 }, // Lights every cable on a port, and the jacks at both ends of each. A port with // nothing connected traces nothing at all, which is what keeps the spare jack an // output always holds for dragging from dimming the board and lighting nothing. traceFrom: function (port) { var self = $(this) if (self.pedalboard('connecting')) { return } var jacks = self.pedalboard('jacksAtPort', port) var traced = 0 for (var i = 0; i < jacks.length; i++) { var jack = jacks[i] if (! jack || ! jack.data('connected')) { continue } var lit = self.pedalboard('litCanvas', jack) lit.canvas.attr('data-cable-lit', lit.leg === null ? '' : lit.leg) jack.attr('data-jack-lit', '') // a teleported cable's boxes are not inside the canvas the tracing lights, so // they have to be picked out by name if (jack.data('teleported')) { // a merged pair's boxes are its left half's var tpair = self.pedalboard('teleportPair', jack) var owner = tpair ? tpair.left : jack var tname = self.pedalboard('teleportName', owner.data('origin')) if (tname) { // read the boxes, never teleportBox(): that CREATES one on a key miss // and tracing has no business placing it, so a miss would leave an // unpositioned box sitting at the origin var boxes = self.data('teleportBoxes') var outBox = boxes['out ' + owner.data('origin').attr('mod-port') + ' ' + tname] var inBox = boxes['in ' + owner.data('destination').attr('mod-port') + ' ' + tname] if (outBox) { outBox.attr('data-teleport-lit', '') } if (inBox) { inBox.attr('data-teleport-lit', '') } } } // both jacks of a merged pair belong to the one cable being traced if (lit.partner) { lit.partner.attr('data-jack-lit', '') } traced++ } if (traced) { self.addClass('mod-tracing') } }, // Ends a trace. Sweeps rather than remembering what it lit, because a trace can cover // any number of cables, and because destroyJack calls this for a jack removed under // the pointer, which never gets a mouseleave of its own. clearTracing: function () { var self = $(this) self.find('[data-cable-lit]').removeAttr('data-cable-lit') self.find('[data-jack-lit]').removeAttr('data-jack-lit') self.find('[data-teleport-lit]').removeAttr('data-teleport-lit') self.removeClass('mod-tracing') }, // A stereo pair running to a matching stereo pair is drawn as one cable that splits // into a Y at each end, rather than as two cables following the same route. Both // halves keep their own jack, canvas and host connection - only the paint is merged. // Returns false when this jack is not half of a mergeable pair, and the caller then // draws an ordinary cable. drawStereoJack: function (jack, force) { var self = $(this) var pair = self.pedalboard('stereoPartnerJack', jack) // The partner is still in the connection index between a disconnect and the host // confirming it, so its own connected flag is what says the pair is still whole if (! pair || ! pair.jack.data('connected')) { return false } // a merged pair is one cable running end to end, which a teleported cable is not. // the teleport key takes both halves together, so this normally sees both or neither if (jack.data('teleported') || pair.jack.data('teleported')) { return false } // The left half's canvas carries the whole cable and the right half's is emptied, // so redrawing either half on its own still leaves both of them right var left = pair.first ? jack : pair.jack var right = pair.first ? pair.jack : jack var rightSvg = right.data('svg') if (rightSvg) { rightSvg.clear() } right.data('canvas').removeClass('mod-stereo') var l = self.pedalboard('jackCoords', left, force) var r = self.pedalboard('jackCoords', right, force) self.pedalboard('drawStereoBezier', left.data('canvas'), { x: l.xi, y: l.yi }, { x: r.xi, y: r.yi }, { x: l.xo, y: l.yo }, { x: r.xo, y: r.yo }, '') return true }, // Draws a cable from jack's source (the output) to it's current position // Force parameter will force drawing when jack is disconnected drawJack: function (jack, force) { var self = $(this) // We used settimeout so that drawing will occur after all events are processed. This avoids some bad // user experience setTimeout(function () { var svg = jack.data('svg') if (!svg) // maybe jack has just been disconnected and so no drawing is necessary return svg.clear() // If this jack is not connected and if (!jack.data('connected') && !force) return // A teleported cable is drawn split: two stubs and a box at each end. A teleported // stereo pair is split the same way, but as one -- its legs meet at each end and // one box stands for both. It is never merged into a cable running end to end. if (jack.data('teleported') && self.pedalboard('drawTeleportPairJack', jack, force)) return if (jack.data('teleported') && self.pedalboard('drawTeleportJack', jack, force)) return if (self.pedalboard('drawStereoJack', jack, force)) return var c = self.pedalboard('jackCoords', jack, force) self.pedalboard('drawBezier', jack.data('canvas'), c.xi, c.yi, c.xo, c.yo, '') }, 0) }, // A teleported cable is two short stubs rather than one long curve: out of the output // into its box, and out of the destination's box into the input. Straight lines -- // over this distance a bezier is indistinguishable from one and costs more to read. drawTeleportBezier: function (canvas, outFrom, outTo, inFrom, inTo) { var svg = canvas.svg('get') if (! svg) { return } svg.clear() canvas.removeClass('mod-stereo') var parts = [['pathShadow', 'shadow'], ['pathCable', 'cable'], ['pathLight', 'light']] for (var i = 0; i < parts.length; i++) { var path = canvas.data(parts[i][0]) path.reset() path.move(outFrom.x, outFrom.y).line(outTo.x, outTo.y) path.move(inFrom.x, inFrom.y).line(inTo.x, inTo.y) svg.path(null, path, { class_: parts[i][1] }) } }, // Resizes the labels from the teleport-label-scale preference. One stylesheet rule // rather than per-box, so it reaches boxes made later too. The numbers are // dashboard.css's at scale 1; box and text scale together. applyTeleportScale: function () { var self = $(this) var scale = 1 if (typeof PREFERENCES !== 'undefined' && PREFERENCES['teleport-label-scale']) { var wanted = parseFloat(PREFERENCES['teleport-label-scale']) if (wanted > 0) { scale = wanted } } var sheet = $('#mod-teleport-scale') if (! sheet.length) { sheet = $('