-------------------------------------------------------------------------------- --! @title UserPresetBrowser --! @brief A user preset manager: save, load, browse and list JSON presets --! @category AssetLoading --! --! A preset bar for a script's own settings, kept as .json files in the --! product's user folder (getUserLocation), so that they are shared by every --! host product (Falcon, UVI Workstation...) and survive a reinstall: --! --! - a hierarchical Menu lists the folder and its subfolders with listFiles: --! an entry is the file's path relative to the folder, "Leads/Saw", so each --! subfolder becomes a submenu. Prev / Next step through the whole list, --! across subfolders, and selecting an entry loads that file with loadData; --! Refresh lists the folder again, for files added outside the script, --! - "Save" writes the knobs with saveData under the name typed in the --! editable name Label, in the subfolder of the selected preset (the folder --! itself when none is selected); an existing file is overwritten. The --! folder is then listed again and the new entry selected, --! - "Save As..." and "Open..." go through browseForFile, so a preset can be --! written or read anywhere on disk, not only in the preset folder, --! - on first run the folder is empty: two presets are written, then listed. --! --! listFiles, loadData, saveData and browseForFile are asynchronous: the call --! returns at once and the callback runs once the disk work is done. Script --! callbacks may run on the audio thread, which is why the folder is never --! read synchronously. --! --! A preset file holds a format tag, a version number and one value per knob. --! The loader is tolerant: a key that is missing (a preset saved before a knob --! was added) keeps the knob's current value, and a newer version is loaded as --! far as it is understood. --! --! The knobs are persistent: the host restores them when a program loads, --! which calls their changed callbacks. The userReady guard (see --! @ref ExIRLoader "IRLoader") keeps that restore from flagging the preset as --! modified. The menu is not persistent: its entries are rebuilt from disk, so --! a saved index could point at another file. onSave stores the selected --! entry's relative path instead, "Leads/Saw", and onLoad hands it to the --! startup listing, which selects it again (the first entry if it is gone). --! --! @demonstrates saveData, loadData, browseForFile, listFiles, getUserLocation, editable Label, Menu, onSave, onLoad, userReady guard -------------------------------------------------------------------------------- local PRODUCT = "My Instrument" local FORMAT = "My Instrument preset" -- tells our presets from any other .json local VERSION = 1 local folder = getUserLocation(PRODUCT) .. "/Presets" -- Flipped in onInit, once the host has restored the persistent widgets. local userReady = false -- True while a preset writes the knobs, so that this does not count as an edit. local applying = false -------------------------------------------------------------------------------- -- UI -------------------------------------------------------------------------------- local knobs = { Knob{"Cutoff", 2000, 20, 20000, mapper = Mapper.Exponential, unit = Unit.Hertz, tooltip = "Filter cutoff frequency, saved in the preset"}, Knob{"Resonance", 0.2, 0, 1, unit = Unit.PercentNormalized, tooltip = "Filter resonance, saved in the preset"}, Knob{"Attack", 0.01, 0.001, 5, mapper = Mapper.Exponential, unit = Unit.Seconds, tooltip = "Envelope attack time, saved in the preset"}, Knob{"Release", 0.3, 0.01, 10, mapper = Mapper.Exponential, unit = Unit.Seconds, tooltip = "Envelope release time, saved in the preset"}, } -- Rows are the engine's default 20 px high, 5 px apart. A knob draws its dial -- as a square of its height and its name and value beside it, so 120 x 45 -- leaves those 70 px: room for "Resonance" and "20.00 kHz". for i, knob in ipairs(knobs) do knob.bounds = {10 + (i - 1) * 125, 65, 120, 45} end local prevButton = Button{"Prev", bounds = {10, 10, 44, 20}, tooltip = "Load the previous preset of the list"} local presetMenu = Menu{"Preset", {"(no preset)"}, bounds = {59, 10, 247, 20}, showLabel = false, persistent = false, hierarchical = true, tooltip = "Choose a preset to load; subfolders open as submenus"} local nextButton = Button{"Next", bounds = {311, 10, 44, 20}, tooltip = "Load the next preset of the list"} local refreshButton = Button{"Refresh", bounds = {360, 10, 70, 20}, tooltip = "Re-read the preset folder and its subfolders"} local openButton = Button{"Open", displayName = "Open...", bounds = {435, 10, 70, 20}, tooltip = "Load a preset file from anywhere on disk"} local nameLabel = Label{"Name", bounds = {10, 35, 345, 20}, editable = true, align = "left", backgroundColour = "222222", text = "Untitled", tooltip = "Preset name: click to type the name Save uses"} local saveButton = Button{"Save", bounds = {360, 35, 70, 20}, tooltip = "Save the current settings under the name above, in the folder of the selected preset"} local saveAsButton = Button{"SaveAs", displayName = "Save As...", bounds = {435, 35, 70, 20}, tooltip = "Save the current settings to a file you choose"} -- Full width: it shows whole file paths. local status = Label{"Status", bounds = {10, 115, 700, 20}, align = "left", textColour = "aaaaaa", text = "", tooltip = "Last action: the file loaded or saved, or what went wrong"} local function report(text, isError) print(text) status.text = text status.textColour = isError and "ff5555" or "aaaaaa" end -------------------------------------------------------------------------------- -- Presets -------------------------------------------------------------------------------- local presetPaths = {} -- menu index -> absolute path of the file local refresh -- defined below, called after each save -- Menu entry of a file: its path relative to the folder, "/" separated on every -- platform, without ".json". nil for a file outside the folder. local root = folder:gsub("\\", "/") .. "/" local function entryName(path) path = path:gsub("\\", "/") if path:sub(1, #root) ~= root then return nil end return (path:sub(#root + 1):gsub("%.json$", "")) end local function presetData(name) local values = {} for _, knob in ipairs(knobs) do values[knob.name] = knob.value end return {format = FORMAT, version = VERSION, name = name, values = values} end local function applyPreset(data, path) if type(data) ~= "table" or data.format ~= FORMAT or type(data.values) ~= "table" then report("Not a " .. PRODUCT .. " preset: " .. path, true) return end if (tonumber(data.version) or 0) > VERSION then print("Preset saved by a newer version, settings unknown to this one are ignored: " .. path) end applying = true for _, knob in ipairs(knobs) do local value = data.values[knob.name] if type(value) == "number" then -- a missing key keeps the current value knob:setValue(value) end end applying = false nameLabel.text = data.name or path:match("([^/\\]+)%.json$") or "Untitled" report("Loaded " .. path) end -- loadData does not call back when the file cannot be read, and a file that is -- not JSON raises an error before the callback: only the content can be checked. local function loadPreset(path) loadData(path, function(data) applyPreset(data, path) end) end local function savePreset(path, name) saveData(presetData(name), path, function(task) if task.success then report("Saved " .. path) else report("Could not save " .. path, true) end refresh(entryName(path)) end) end -- List the folder and its subfolders into the menu, then select the entry -- selectName ("Sub/Name") if any. Entries come sorted by path. refresh = function(selectName) listFiles(folder, "*.json", true, function(task) if task.error then report("listFiles: " .. task.error, true) end presetMenu:clear() presetPaths = {} local selected = 1 for _, entry in ipairs(task.result) do -- task.result is rebuilt on each read: read it once local name = entryName(entry.path) presetMenu:addItem(name) presetPaths[#presetPaths + 1] = entry.path if name == selectName then selected = #presetPaths end end if #presetPaths == 0 then presetMenu:addItem("(no preset)") end presetMenu:setValue(selected, false) -- show it without loading it again end) end -- A preset name becomes a file name: drop the characters no file system takes. local function fileNameFor(text) local name = text:gsub("[/\\:%*%?\"<>|]", ""):match("^%s*(.-)%s*$") return name ~= "" and name or nil end -------------------------------------------------------------------------------- -- Callbacks -------------------------------------------------------------------------------- for _, knob in ipairs(knobs) do knob.changed = function() -- In a real instrument the knob drives the sound here. The "modified" mark -- is skipped while the host restores the program or a preset is applied. if userReady and not applying then status.text = "Modified" status.textColour = "aaaaaa" end end end presetMenu.changed = function(self) if not userReady then return end local path = presetPaths[self.value] if path then loadPreset(path) end end local function step(delta) if #presetPaths == 0 then return end presetMenu:setValue((presetMenu.value - 1 + delta) % #presetPaths + 1) -- loads it end prevButton.changed = function() step(-1) end nextButton.changed = function() step(1) end refreshButton.changed = function() refresh(presetMenu.selectedText) end -- files added outside the script saveButton.changed = function() local name = fileNameFor(nameLabel.text) if not name then report("Type a preset name first", true) return end -- Next to the selected preset, so that a preset saved from a subfolder stays there. local current = presetPaths[presetMenu.value] local dir = current and current:match("^(.*)[/\\]") or folder savePreset(dir .. "/" .. name .. ".json", name) end saveAsButton.changed = function() local name = fileNameFor(nameLabel.text) or "Untitled" browseForFile("save", "Save preset", folder .. "/" .. name .. ".json", "*.json", function(task) if not task.success or task.result == "" then return end -- cancelled local path = task.result if not path:match("%.json$") then path = path .. ".json" end savePreset(path, path:match("([^/\\]+)%.json$")) end) end openButton.changed = function() browseForFile("open", "Open preset", folder, "*.json", function(task) if task.success and task.result ~= "" then loadPreset(task.result) end end) end -------------------------------------------------------------------------------- -- Startup -------------------------------------------------------------------------------- local factory = { Init = {Cutoff = 2000, Resonance = 0.2, Attack = 0.01, Release = 0.3}, Bright = {Cutoff = 12000, Resonance = 0.5, Attack = 0.005, Release = 1.2}, } -- Entry selected when the program was saved, set by onLoad. onLoad runs right -- after the main chunk, before the listing below calls back. local savedEntry -- First run: an empty folder gets the factory presets, then is listed. listFiles(folder, "*.json", true, function(task) if #task.result > 0 then refresh(savedEntry) return end saveData({format = FORMAT, version = VERSION, name = "Init", values = factory.Init}, folder .. "/Init.json", function() saveData({format = FORMAT, version = VERSION, name = "Bright", values = factory.Bright}, folder .. "/Bright.json", function() refresh("Init") end) end) end) function onInit() userReady = true end -- The menu index is not saved (see above): the entry's path relative to the -- folder is. nil for a preset opened from outside the folder. function onSave() local path = presetPaths[presetMenu.value] return {preset = path and entryName(path)} end function onLoad(data) if type(data) == "table" and type(data.preset) == "string" then savedEntry = data.preset end end makePerformanceView()