Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 78 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "maolan-engine"
version = "0.4.22"
version = "0.4.23"
edition = "2024"
description = "Audio engine for the Maolan DAW with audio/MIDI tracks, routing, export, and out-of-process CLAP/VST3/LV2 plugin support"
license = "BSD-2-Clause"
Expand All @@ -24,6 +24,7 @@ tracing = { version = "0.1.44", features = ["release_max_level_debug"] }
midly = { version = "0.5.3", optional = true }
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"
toml = "1.2.1"
maolan-plugin-protocol = { version = "0.0.21", optional = true }
uuid = { version = "1.29.0", features = ["v4"] }
fearless_simd = { version = "1.2.0", features = ["force_support_fallback"] }
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
mod audio;
#[cfg(feature = "audio")]
pub mod audio_codec;
pub mod preferences;
pub mod wav_stream;
#[cfg(target_os = "macos")]
pub mod audio_devices {
Expand Down
101 changes: 101 additions & 0 deletions src/preferences.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
use std::path::Path;

use serde::{Deserialize, Serialize};

/// Shared default audio device selections stored by Maolan applications.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct AudioDevicePreferences {
pub default_output_device_id: Option<String>,
pub default_input_device_id: Option<String>,
}

impl AudioDevicePreferences {
pub fn from_toml_str(contents: &str) -> Result<Self, toml::de::Error> {
toml::from_str(contents)
}

/// Replaces these device settings in a TOML document while preserving its other values.
pub fn update_toml_str(&self, contents: &str) -> Result<String, String> {
let mut value = if contents.trim().is_empty() {
toml::Value::Table(toml::map::Map::new())
} else {
toml::from_str::<toml::Value>(contents).map_err(|error| error.to_string())?
};
let table = value
.as_table_mut()
.ok_or_else(|| String::from("Audio device settings require a TOML table."))?;
update_id(
table,
"default_output_device_id",
&self.default_output_device_id,
);
update_id(
table,
"default_input_device_id",
&self.default_input_device_id,
);
toml::to_string_pretty(&value).map_err(|error| error.to_string())
}

pub fn load_from_path(path: &Path) -> Self {
std::fs::read_to_string(path)
.ok()
.and_then(|contents| Self::from_toml_str(&contents).ok())
.unwrap_or_default()
}

pub fn save_to_path(&self, path: &Path) -> Result<(), String> {
let contents = match std::fs::read_to_string(path) {
Ok(contents) => contents,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(error) => return Err(error.to_string()),
};
let updated = self.update_toml_str(&contents)?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
}
std::fs::write(path, updated).map_err(|error| error.to_string())
}
}

fn update_id(table: &mut toml::map::Map<String, toml::Value>, key: &str, id: &Option<String>) {
if let Some(id) = id
.as_deref()
.filter(|id| !id.is_empty() && *id != "__auto__")
{
table.insert(key.to_string(), toml::Value::String(id.to_string()));
} else {
table.remove(key);
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn update_toml_preserves_other_preferences() {
let preferences = AudioDevicePreferences {
default_output_device_id: Some(String::from("/dev/dsp5")),
default_input_device_id: Some(String::from("/dev/dsp5")),
};
let updated = preferences
.update_toml_str("theme = \"dark\"\ndefault_output_device_id = \"out2\"\n")
.unwrap();
let parsed = AudioDevicePreferences::from_toml_str(&updated).unwrap();
assert_eq!(parsed, preferences);
assert!(updated.contains("theme = \"dark\""));
}

#[test]
fn update_toml_removes_unset_device_ids() {
let updated = AudioDevicePreferences::default()
.update_toml_str(
"default_output_device_id = \"old\"\ndefault_input_device_id = \"old\"\n",
)
.unwrap();
assert!(!updated.contains("default_output_device_id"));
assert!(!updated.contains("default_input_device_id"));
}
}
Loading