Skip to content

The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.

refactor(ui): the settings sheet is a pane behind a message

Jareer00fe2a582e30
diff --git a/src/crates/concat/src/lib.rs b/src/crates/concat/src/lib.rs
index 02fddb64..3daf5716 100644
--- a/src/crates/concat/src/lib.rs
+++ b/src/crates/concat/src/lib.rs
@@ -52,6 +52,7 @@ use dock::{Dock, SEAT_MIN_GRAB, SEAT_MIN_H, SEAT_MIN_W};
use host::{Host, Shell, on_ui};
use panes::Msg;
use panes::export::ExportMsg;
+use panes::settings::SettingsMsg;
use studio::{Models, OUTPUTS, RESOLUTIONS, START_RATES, Studio};
use ui::*;
@@ -949,8 +950,7 @@ pub fn run() -> Result<(), slint::PlatformError> {
state.handle(Msg::Export(ExportMsg::Open));
}));
app.on_open_settings(on_window!(|state| {
- state.refresh_models();
- state.settings.open = true;
+ state.handle(Msg::Settings(SettingsMsg::Open));
}));
// The theme is one bool on the Theme global, and every colour in the
// tree is a binding away from it; it is also remembered.
@@ -968,7 +968,7 @@ pub fn run() -> Result<(), slint::PlatformError> {
state.handle(Msg::Export(ExportMsg::Close));
}));
app.on_settings_closed(on_window!(|state| {
- state.settings.open = false;
+ state.handle(Msg::Settings(SettingsMsg::Close));
}));
app.on_export_name_edited(on_window!(|state, name: SharedString| {
state.handle(Msg::Export(ExportMsg::NameEdited(name.to_string())));
@@ -1006,96 +1006,55 @@ pub fn run() -> Result<(), slint::PlatformError> {
// ── settings ──
app.on_settings_page_changed(on_window!(|state, index: i32| {
- state.settings.tab = index;
+ state.handle(Msg::Settings(SettingsMsg::PageChanged(index)));
}));
app.on_settings_show_log(on_window!(|state| {
- // The file this run is writing, when there is one, so the manager
- // opens with it selected; the folder when there is not, which is
- // still where the previous runs are.
- let target = concat_host::logs::current()
- .map(std::path::Path::to_path_buf)
- .unwrap_or_else(|| concat_host::logs::folder(&state.host.dirs));
- if let Err(error) = platform::reveal(&target.to_string_lossy()) {
- state.notify(&i18n::tf("Could not show the log: {0}", &[&error]), true);
- }
+ state.handle(Msg::Settings(SettingsMsg::ShowLog));
}));
app.on_settings_language_changed(on_window!(|state, index: i32| {
- let index = index.max(0) as usize;
- if let Some(language) = state.languages.get(index).cloned() {
- state.settings.language = index;
- state.prefs.locale = Some(language.code.clone());
- // The words change on the publish that follows: Rust's on
- // their way through `t`, the tree's through `I18n.lang`.
- i18n::select(&language.code, &state.host.dirs);
- }
- state.prefs.save(&state.host.dirs);
+ state.handle(Msg::Settings(SettingsMsg::LanguageChanged(index)));
}));
app.on_settings_playhead_stops_changed(on_window!(|state, on: bool| {
- state.settings.playhead_stops = on;
- state.prefs.playhead_stops_at_end = on;
- state.prefs.save(&state.host.dirs);
- // A playhead already out past the end comes back in when the
- // switch goes on; seek does the clamp.
- let at = state.playhead;
- state.seek(at);
+ state.handle(Msg::Settings(SettingsMsg::PlayheadStopsChanged(on)));
}));
app.on_settings_custom_context_actions_changed(on_window!(|state, on: bool| {
- state.settings.custom_context_actions = on;
- state.prefs.custom_context_actions = on;
- state.prefs.save(&state.host.dirs);
+ state.handle(Msg::Settings(SettingsMsg::CustomContextActionsChanged(on)));
}));
-
app.on_settings_download_source_changed(on_window!(|state, index: i32| {
- use concat_host::models::SourcePreference;
- let index = (index.max(0) as usize).min(SourcePreference::ALL.len() - 1);
- state.settings.download_source = index;
- state.prefs.download_source = Some(SourcePreference::ALL[index].name().to_owned());
- state.prefs.save(&state.host.dirs);
- state.apply_download_source();
+ state.handle(Msg::Settings(SettingsMsg::DownloadSourceChanged(index)));
}));
app.on_settings_download_base_edited(on_window!(|state, text: SharedString| {
- let base = text.trim().to_owned();
- state.settings.download_base = base.clone();
- state.prefs.download_base = (!base.is_empty()).then_some(base);
- state.prefs.save(&state.host.dirs);
- state.apply_download_source();
+ state.handle(Msg::Settings(SettingsMsg::DownloadBaseEdited(
+ text.to_string(),
+ )));
}));
app.on_settings_server_enabled_changed(on_window!(|state, on: bool| {
- state.prefs.server.enabled = on;
- state.prefs.save(&state.host.dirs);
- state.apply_server();
+ state.handle(Msg::Settings(SettingsMsg::ServerEnabledChanged(on)));
}));
app.on_settings_server_listen_edited(on_window!(|state, text: SharedString| {
- let listen = text.trim().to_owned();
- state.prefs.server.listen = if listen.is_empty() {
- prefs::DEFAULT_LISTEN.to_owned()
- } else {
- listen
- };
- state.prefs.save(&state.host.dirs);
- state.apply_server();
+ state.handle(Msg::Settings(SettingsMsg::ServerListenEdited(
+ text.to_string(),
+ )));
}));
app.on_settings_server_token_edited(on_window!(|state, text: SharedString| {
- state.prefs.server.token = text.trim().to_owned();
- state.prefs.save(&state.host.dirs);
- state.apply_server();
+ state.handle(Msg::Settings(SettingsMsg::ServerTokenEdited(
+ text.to_string(),
+ )));
}));
app.on_settings_server_token_generated(on_window!(|state| {
- state.prefs.server.token = Studio::new_token();
- state.prefs.save(&state.host.dirs);
- state.apply_server();
+ state.handle(Msg::Settings(SettingsMsg::ServerTokenGenerated));
}));
app.on_model_activated(on_window!(|state, id: SharedString| {
- state.model_activate(id.as_str());
+ state.handle(Msg::Settings(SettingsMsg::ModelActivated(id.to_string())));
}));
app.on_model_download(on_window!(|state, id: SharedString| {
- state.model_download(id.as_str());
+ state.handle(Msg::Settings(SettingsMsg::ModelDownload(id.to_string())));
}));
app.on_model_cancel(on_window!(|state, id: SharedString| {
- state.model_cancel(id.as_str());
+ state.handle(Msg::Settings(SettingsMsg::ModelCancel(id.to_string())));
}));
app.on_model_remove(on_window!(|state, id: SharedString| {
- state.model_remove(id.as_str());
+ state.handle(Msg::Settings(SettingsMsg::ModelRemove(id.to_string())));
}));
// ── the tray's sound and word tools ──
@@ -1183,10 +1142,7 @@ pub fn run() -> Result<(), slint::PlatformError> {
"template" => state.save_template(),
"speech" => state.speech_open(),
"clear-cache" => state.clear_project_cache(),
- "settings" => {
- state.refresh_models();
- state.settings.open = true;
- }
+ "settings" => state.handle(Msg::Settings(SettingsMsg::Open)),
"close-project" => state.close_project(),
"undo" => state.undo(),
"redo" => state.redo(),
diff --git a/src/crates/concat/src/panes/mod.rs b/src/crates/concat/src/panes/mod.rs
index abe48737..122b4a1b 100644
--- a/src/crates/concat/src/panes/mod.rs
+++ b/src/crates/concat/src/panes/mod.rs
@@ -14,10 +14,13 @@
//! export sheet is the first, and the shape the rest follow.
pub mod export;
+pub mod settings;
/// One thing that happened, to one pane.
#[derive(Clone, Debug)]
pub enum Msg {
/// To the export sheet.
Export(export::ExportMsg),
+ /// To the settings sheet.
+ Settings(settings::SettingsMsg),
}
diff --git a/src/crates/concat/src/panes/settings.rs b/src/crates/concat/src/panes/settings.rs
new file mode 100644
index 00000000..94908b26
--- /dev/null
+++ b/src/crates/concat/src/panes/settings.rs
@@ -0,0 +1,619 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
+
+//! The settings sheet: the preferences, the two model lists, and the API
+//! server's switch.
+//!
+//! Everything on the sheet is a preference or follows from one, so most
+//! messages do three things: change the pane, write the preference, and
+//! apply it - to the downloaders, to the server, to the words on screen.
+//! The model lists are the one part with a worker behind them: a download
+//! reports as [`SettingsMsg::ModelProgress`] and ends as
+//! [`SettingsMsg::ModelFinished`], and the lists are rebuilt from what is
+//! on disk after anything that could have changed it.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use concat_host::models::SourcePreference;
+use slint::SharedString;
+
+use crate::host::{on_ui, spawn};
+use crate::i18n::{self, t, tf};
+use crate::panes::Msg;
+use crate::platform;
+use crate::prefs;
+use crate::studio::Studio;
+use crate::ui::{ModelData, SettingsData};
+
+/// Everything that can happen to the settings sheet.
+#[derive(Clone, Debug)]
+pub enum SettingsMsg {
+ /// The preferences read back on launch, and applied.
+ Restore,
+ /// The sheet is asked for: the menu, the tray or the shortcut.
+ Open,
+ Close,
+ PageChanged(i32),
+ /// Show this run's log in the file manager.
+ ShowLog,
+ LanguageChanged(i32),
+ PlayheadStopsChanged(bool),
+ CustomContextActionsChanged(bool),
+ DownloadSourceChanged(i32),
+ DownloadBaseEdited(String),
+ ServerEnabledChanged(bool),
+ ServerListenEdited(String),
+ ServerTokenEdited(String),
+ ServerTokenGenerated,
+ /// Make this the model the engine uses.
+ ModelActivated(String),
+ ModelDownload(String),
+ ModelCancel(String),
+ ModelRemove(String),
+ /// A download's worker reporting where it is.
+ ModelProgress {
+ id: String,
+ /// Megabytes so far.
+ fetched: f32,
+ /// Megabytes in all, when the server said.
+ total: Option<f32>,
+ unpacking: bool,
+ },
+ /// A download's worker is done: the model on disk, or why not.
+ ModelFinished {
+ id: String,
+ result: Result<(), String>,
+ },
+}
+
+/// One downloadable model, as the settings sheet shows it.
+#[derive(Clone, Debug)]
+pub struct ModelState {
+ pub id: String,
+ pub name: String,
+ pub note: String,
+ pub megabytes: f32,
+ pub accuracy: i32,
+ pub installed: bool,
+ pub active: bool,
+ /// Megabytes fetched so far while a download runs.
+ pub fetched: Option<f32>,
+ pub unpacking: bool,
+}
+
+impl ModelState {
+ /// The model as one row of the sheet's list.
+ fn row(&self) -> ModelData {
+ let total = self.megabytes;
+ let fetched = self.fetched.unwrap_or(0.0);
+ ModelData {
+ id: self.id.as_str().into(),
+ name: self.name.as_str().into(),
+ note: self.note.as_str().into(),
+ size: format!("{total:.0} MB").into(),
+ accuracy: self.accuracy,
+ installed: self.installed,
+ active: self.active && self.installed,
+ downloading: self.fetched.is_some(),
+ progress: if total > 0.0 {
+ (fetched / total).min(1.0)
+ } else {
+ 0.0
+ },
+ transferred: if self.unpacking {
+ t("Unpacking…").into()
+ } else {
+ tf(
+ "{0} MB of {1} MB",
+ &[&format!("{fetched:.0}"), &format!("{total:.0}")],
+ )
+ .into()
+ },
+ eta: SharedString::new(),
+ }
+ }
+}
+
+/// The models of a kind that are on disk, in the settings' order: the
+/// rows of a sheet's model list.
+pub fn installed(models: &[ModelState]) -> Vec<&ModelState> {
+ models.iter().filter(|model| model.installed).collect()
+}
+
+/// The settings sheet's state.
+#[derive(Default)]
+pub struct SettingsPane {
+ pub open: bool,
+ pub tab: i32,
+ pub language: usize,
+ /// The switch that keeps the playhead inside the content.
+ pub playhead_stops: bool,
+ /// Show flip/reverse in clip context menu.
+ pub custom_context_actions: bool,
+ /// Index into `SourcePreference::ALL`: where model downloads look first.
+ pub download_source: usize,
+ /// The base URL of a custom download source.
+ pub download_base: String,
+ /// Why the server is not running when the switch is on: the bind that
+ /// failed. Empty while it runs, or is off.
+ pub server_error: String,
+ /// The transcriber models, installed or not.
+ pub transcribers: Vec<ModelState>,
+ /// The voice models, installed or not.
+ pub voices: Vec<ModelState>,
+}
+
+impl SettingsPane {
+ /// Applies one message. The studio is the rest of the window; while
+ /// this runs the studio's copy of the pane is a blank it must not read.
+ pub fn update(&mut self, msg: SettingsMsg, studio: &mut Studio) {
+ match msg {
+ SettingsMsg::Restore => {
+ self.language = studio
+ .languages
+ .iter()
+ .position(|language| {
+ Some(language.code.as_str()) == studio.prefs.locale.as_deref()
+ })
+ .unwrap_or(0);
+ self.playhead_stops = studio.prefs.playhead_stops_at_end;
+ self.custom_context_actions = studio.prefs.custom_context_actions;
+ self.download_source = Self::download_source(studio).0;
+ self.download_base = studio.prefs.download_base.clone().unwrap_or_default();
+ Self::apply_download_source(studio);
+ self.apply_server(studio);
+ self.refresh(studio);
+ }
+ SettingsMsg::Open => {
+ self.refresh(studio);
+ self.open = true;
+ }
+ SettingsMsg::Close => self.open = false,
+ SettingsMsg::PageChanged(index) => self.tab = index,
+ SettingsMsg::ShowLog => {
+ // The file this run is writing, when there is one, so the
+ // manager opens with it selected; the folder when there is
+ // not, which is still where the previous runs are.
+ let target = concat_host::logs::current()
+ .map(std::path::Path::to_path_buf)
+ .unwrap_or_else(|| concat_host::logs::folder(&studio.host.dirs));
+ if let Err(error) = platform::reveal(&target.to_string_lossy()) {
+ studio.notify(&i18n::tf("Could not show the log: {0}", &[&error]), true);
+ }
+ }
+ SettingsMsg::LanguageChanged(index) => {
+ let index = index.max(0) as usize;
+ if let Some(language) = studio.languages.get(index).cloned() {
+ self.language = index;
+ studio.prefs.locale = Some(language.code.clone());
+ // The words change on the publish that follows: Rust's
+ // on their way through `t`, the tree's through
+ // `I18n.lang`.
+ i18n::select(&language.code, &studio.host.dirs);
+ }
+ studio.prefs.save(&studio.host.dirs);
+ }
+ SettingsMsg::PlayheadStopsChanged(on) => {
+ self.playhead_stops = on;
+ studio.prefs.playhead_stops_at_end = on;
+ studio.prefs.save(&studio.host.dirs);
+ // A playhead already out past the end comes back in when
+ // the switch goes on; seek does the clamp.
+ let at = studio.playhead;
+ studio.seek(at);
+ }
+ SettingsMsg::CustomContextActionsChanged(on) => {
+ self.custom_context_actions = on;
+ studio.prefs.custom_context_actions = on;
+ studio.prefs.save(&studio.host.dirs);
+ }
+ SettingsMsg::DownloadSourceChanged(index) => {
+ let index = (index.max(0) as usize).min(SourcePreference::ALL.len() - 1);
+ self.download_source = index;
+ studio.prefs.download_source = Some(SourcePreference::ALL[index].name().to_owned());
+ studio.prefs.save(&studio.host.dirs);
+ Self::apply_download_source(studio);
+ }
+ SettingsMsg::DownloadBaseEdited(text) => {
+ let base = text.trim().to_owned();
+ self.download_base = base.clone();
+ studio.prefs.download_base = (!base.is_empty()).then_some(base);
+ studio.prefs.save(&studio.host.dirs);
+ Self::apply_download_source(studio);
+ }
+ SettingsMsg::ServerEnabledChanged(on) => {
+ studio.prefs.server.enabled = on;
+ studio.prefs.save(&studio.host.dirs);
+ self.apply_server(studio);
+ }
+ SettingsMsg::ServerListenEdited(text) => {
+ let listen = text.trim().to_owned();
+ studio.prefs.server.listen = if listen.is_empty() {
+ prefs::DEFAULT_LISTEN.to_owned()
+ } else {
+ listen
+ };
+ studio.prefs.save(&studio.host.dirs);
+ self.apply_server(studio);
+ }
+ SettingsMsg::ServerTokenEdited(text) => {
+ studio.prefs.server.token = text.trim().to_owned();
+ studio.prefs.save(&studio.host.dirs);
+ self.apply_server(studio);
+ }
+ SettingsMsg::ServerTokenGenerated => {
+ studio.prefs.server.token = new_token();
+ studio.prefs.save(&studio.host.dirs);
+ self.apply_server(studio);
+ }
+ SettingsMsg::ModelActivated(id) => {
+ if self.is_transcriber(&id) {
+ studio.prefs.transcriber_model = Some(id);
+ } else {
+ studio.prefs.tts_model = Some(id);
+ }
+ studio.prefs.save(&studio.host.dirs);
+ self.refresh(studio);
+ }
+ SettingsMsg::ModelDownload(id) => self.download(&id, studio),
+ SettingsMsg::ModelCancel(id) => {
+ if self.is_transcriber(&id) {
+ studio.host.transcriber.cancel_download();
+ } else {
+ studio.host.speech.cancel_download();
+ }
+ }
+ SettingsMsg::ModelRemove(id) => {
+ let result = if self.is_transcriber(&id) {
+ studio.host.transcriber.delete_model(&studio.host.dirs, &id)
+ } else {
+ studio.host.speech.delete_model(&studio.host.dirs, &id)
+ };
+ if let Err(error) = result {
+ studio.notify(&error, true);
+ }
+ self.refresh(studio);
+ }
+ SettingsMsg::ModelProgress {
+ id,
+ fetched,
+ total,
+ unpacking,
+ } => {
+ if let Some(model) = self.model_mut(&id) {
+ model.fetched = Some(fetched);
+ model.unpacking = unpacking;
+ if let Some(total) = total {
+ model.megabytes = total;
+ }
+ }
+ }
+ SettingsMsg::ModelFinished { id, result } => {
+ if let Some(model) = self.model_mut(&id) {
+ model.fetched = None;
+ model.unpacking = false;
+ }
+ match result {
+ Ok(()) => {
+ studio.notify(&t("Model ready"), false);
+ if self.is_transcriber(&id) && studio.prefs.transcriber_model.is_none() {
+ studio.prefs.transcriber_model = Some(id.clone());
+ } else if !self.is_transcriber(&id) && studio.prefs.tts_model.is_none() {
+ studio.prefs.tts_model = Some(id.clone());
+ }
+ studio.prefs.save(&studio.host.dirs);
+ }
+ Err(error) => studio.notify(&error, true),
+ }
+ self.refresh(studio);
+ }
+ }
+ }
+
+ /// The remembered download source: its place in the menu, and itself.
+ pub fn download_source(studio: &Studio) -> (usize, SourcePreference) {
+ let preference =
+ SourcePreference::parse(studio.prefs.download_source.as_deref().unwrap_or_default());
+ let index = SourcePreference::ALL
+ .iter()
+ .position(|candidate| *candidate == preference)
+ .unwrap_or(0);
+ (index, preference)
+ }
+
+ /// Tells the downloaders where to look first, from the preferences.
+ fn apply_download_source(studio: &Studio) {
+ let (_, preference) = Self::download_source(studio);
+ concat_host::models::set_preference(
+ preference,
+ studio.prefs.download_base.as_deref().unwrap_or_default(),
+ );
+ }
+
+ /// Starts or stops the API's server to match the preferences. A server
+ /// already running is stopped first, so an edited address or token
+ /// takes effect; a bind that fails turns the switch back off and says
+ /// why on the page.
+ fn apply_server(&mut self, studio: &mut Studio) {
+ if let Some(server) = studio.host.server.take() {
+ server.stop();
+ }
+ self.server_error.clear();
+ let prefs = &studio.prefs.server;
+ if !prefs.enabled {
+ return;
+ }
+ let started = prefs
+ .listen
+ .trim()
+ .parse::<std::net::SocketAddr>()
+ .map_err(|_| {
+ tf(
+ "{0} is not an address like 127.0.0.1:7420",
+ &[&prefs.listen],
+ )
+ })
+ .and_then(|address| {
+ let config = concat_server::Config {
+ json: Some(address),
+ token: Some(prefs.token.clone()).filter(|token| !token.is_empty()),
+ ..concat_server::Config::default()
+ };
+ concat_server::Server::start(config, concat_api::Api::new)
+ });
+ match started {
+ Ok(server) => studio.host.server = Some(server),
+ Err(error) => {
+ studio.prefs.server.enabled = false;
+ studio.prefs.save(&studio.host.dirs);
+ self.server_error = error.clone();
+ studio.notify(&error, true);
+ }
+ }
+ }
+
+ /// What the Remote page says under the switch.
+ fn server_status(&self, studio: &Studio) -> String {
+ match &studio.host.server {
+ Some(server) => {
+ let address = server
+ .json_addr()
+ .map(|address| address.to_string())
+ .unwrap_or_default();
+ tf(
+ "Listening on {0} · {1} connected",
+ &[&address, &server.connections()],
+ )
+ }
+ None if !self.server_error.is_empty() => self.server_error.clone(),
+ None => t("Off"),
+ }
+ }
+
+ /// The two model lists, from what is on disk. A download in flight
+ /// keeps its progress across the rebuild.
+ fn refresh(&mut self, studio: &mut Studio) {
+ let dirs = &studio.host.dirs;
+ let downloading: HashMap<String, (Option<f32>, bool)> = self
+ .transcribers
+ .iter()
+ .chain(self.voices.iter())
+ .filter(|model| model.fetched.is_some())
+ .map(|model| (model.id.clone(), (model.fetched, model.unpacking)))
+ .collect();
+ let chosen_transcriber = studio.prefs.transcriber_model.clone();
+ let chosen_voice = studio.prefs.tts_model.clone();
+ if let Ok(status) = concat_speech::Transcriber::status(dirs) {
+ self.transcribers = status
+ .models
+ .iter()
+ .map(|model| {
+ let (fetched, unpacking) =
+ downloading.get(&model.id).copied().unwrap_or((None, false));
+ ModelState {
+ id: model.id.clone(),
+ name: model.label.clone(),
+ note: model.blurb.clone(),
+ megabytes: model.size_bytes as f32 / 1_000_000.0,
+ accuracy: if model.id.starts_with("tiny") {
+ 2
+ } else if model.id.starts_with("base") {
+ 3
+ } else {
+ 4
+ },
+ installed: model.downloaded,
+ active: chosen_transcriber.as_deref() == Some(model.id.as_str()),
+ fetched,
+ unpacking,
+ }
+ })
+ .collect();
+ }
+ if let Ok(status) = concat_speech::Speech::status(dirs) {
+ studio.speakers = status.voices.clone();
+ self.voices = status
+ .models
+ .iter()
+ .map(|model| {
+ let (fetched, unpacking) =
+ downloading.get(&model.id).copied().unwrap_or((None, false));
+ ModelState {
+ id: model.id.clone(),
+ name: model.label.clone(),
+ note: model.blurb.clone(),
+ megabytes: model.size_bytes as f32 / 1_000_000.0,
+ accuracy: if model.id.contains("int8") { 4 } else { 5 },
+ installed: model.downloaded,
+ active: chosen_voice.as_deref() == Some(model.id.as_str()),
+ fetched,
+ unpacking,
+ }
+ })
+ .collect();
+ }
+ // An engine with nothing chosen falls back to whatever is installed,
+ // rather than silently having no model at all.
+ for list in [&mut self.transcribers, &mut self.voices] {
+ if !list.iter().any(|model| model.active && model.installed)
+ && let Some(first) = list.iter_mut().find(|model| model.installed)
+ {
+ first.active = true;
+ }
+ }
+ }
+
+ fn is_transcriber(&self, id: &str) -> bool {
+ self.transcribers.iter().any(|model| model.id == id)
+ }
+
+ fn model_mut(&mut self, id: &str) -> Option<&mut ModelState> {
+ self.transcribers
+ .iter_mut()
+ .chain(self.voices.iter_mut())
+ .find(|model| model.id == id)
+ }
+
+ /// Starts a download on a worker. Its reports come back as messages.
+ fn download(&mut self, id: &str, studio: &Studio) {
+ let transcriber = self.is_transcriber(id);
+ let Some(model) = self.model_mut(id) else {
+ return;
+ };
+ if model.installed || model.fetched.is_some() {
+ return;
+ }
+ model.fetched = Some(0.0);
+ let id = id.to_owned();
+ let dirs = studio.host.dirs.clone();
+ let whisper = Arc::clone(&studio.host.transcriber);
+ let kokoro = Arc::clone(&studio.host.speech);
+ spawn(
+ move || {
+ let report = |progress: concat_speech::DownloadProgress| {
+ let msg = SettingsMsg::ModelProgress {
+ id: progress.id,
+ fetched: progress.received as f32 / 1_000_000.0,
+ total: (progress.total > 0).then(|| progress.total as f32 / 1_000_000.0),
+ unpacking: progress.unpacking,
+ };
+ on_ui(move |studio, _, _| studio.handle(Msg::Settings(msg)));
+ };
+ let result = if transcriber {
+ whisper.download_model(&dirs, &id, report)
+ } else {
+ kokoro.download_model(&dirs, &id, report)
+ };
+ (id, result)
+ },
+ |studio, _, _, (id, result)| {
+ studio.handle(Msg::Settings(SettingsMsg::ModelFinished { id, result }));
+ },
+ );
+ }
+
+ /// The transcriber list's rows.
+ pub fn transcriber_rows(&self) -> Vec<ModelData> {
+ self.transcribers.iter().map(ModelState::row).collect()
+ }
+
+ /// The voice list's rows.
+ pub fn voice_rows(&self) -> Vec<ModelData> {
+ self.voices.iter().map(ModelState::row).collect()
+ }
+
+ /// The sheet as Slint shows it.
+ pub fn data(&self, studio: &Studio) -> SettingsData {
+ SettingsData {
+ open: self.open,
+ tab: self.tab,
+ language: self.language as i32,
+ playhead_stops: self.playhead_stops,
+ custom_context_actions: self.custom_context_actions,
+ download_source: self.download_source as i32,
+ download_base: self.download_base.as_str().into(),
+ server_enabled: studio.prefs.server.enabled,
+ server_listen: studio.prefs.server.listen.as_str().into(),
+ server_token: studio.prefs.server.token.as_str().into(),
+ server_status: self.server_status(studio).into(),
+ disk: {
+ let on_disk: Vec<&ModelState> = installed(&self.transcribers)
+ .into_iter()
+ .chain(installed(&self.voices))
+ .collect();
+ let megabytes: f32 = on_disk.iter().map(|model| model.megabytes).sum();
+ tf(
+ "{0} installed · {1} MB on disk",
+ &[&on_disk.len(), &format!("{megabytes:.0}")],
+ )
+ .into()
+ },
+ version: env!("CARGO_PKG_VERSION").into(),
+ engine: format!("concat-engine · FFmpeg {}", concat_media::linked_version()).into(),
+ }
+ }
+}
+
+/// A fresh token: 128 bits from the OS's randomness, as the standard
+/// library hands it out through its hasher's seed, spelled in hex.
+pub fn new_token() -> String {
+ use std::hash::{BuildHasher, Hasher};
+ let word = |salt: u64| {
+ let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
+ hasher.write_u64(salt);
+ hasher.finish()
+ };
+ format!("{:016x}{:016x}", word(1), word(2))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_token_is_thirty_two_hex_digits_and_never_the_same_twice() {
+ let a = new_token();
+ let b = new_token();
+ assert_eq!(a.len(), 32);
+ assert!(a.bytes().all(|byte| byte.is_ascii_hexdigit()));
+ assert_ne!(a, b);
+ }
+
+ #[test]
+ fn a_row_shows_the_download_as_a_fraction_of_the_whole() {
+ let model = ModelState {
+ id: "base".into(),
+ name: "Base".into(),
+ note: String::new(),
+ megabytes: 200.0,
+ accuracy: 3,
+ installed: false,
+ active: true,
+ fetched: Some(50.0),
+ unpacking: false,
+ };
+ let row = model.row();
+ assert!(row.downloading);
+ assert!(!row.active, "a model that is not installed is not active");
+ assert!((row.progress - 0.25).abs() < 1e-6);
+ }
+
+ #[test]
+ fn installed_keeps_the_settings_order() {
+ let model = |id: &str, installed: bool| ModelState {
+ id: id.into(),
+ name: id.into(),
+ note: String::new(),
+ megabytes: 1.0,
+ accuracy: 1,
+ installed,
+ active: false,
+ fetched: None,
+ unpacking: false,
+ };
+ let list = [model("a", true), model("b", false), model("c", true)];
+ let ids: Vec<&str> = installed(&list).iter().map(|m| m.id.as_str()).collect();
+ assert_eq!(ids, ["a", "c"]);
+ }
+}
diff --git a/src/crates/concat/src/studio.rs b/src/crates/concat/src/studio.rs
index 2c88ad72..0b3ca653 100644
--- a/src/crates/concat/src/studio.rs
+++ b/src/crates/concat/src/studio.rs
@@ -54,6 +54,7 @@ use crate::host::{
window_start,
};
use crate::i18n::{self, t, tf};
+use crate::panes::settings::installed;
use crate::prefs::Preferences;
use crate::presets::{self, TextPreset};
use crate::ui::*;
@@ -266,25 +267,6 @@ pub(crate) fn home_folder(name: &str) -> String {
.unwrap_or_default()
}
-/// The settings sheet's state.
-#[derive(Default)]
-pub struct SettingsState {
- pub open: bool,
- pub tab: i32,
- pub language: usize,
- /// The switch that keeps the playhead inside the content.
- pub playhead_stops: bool,
- /// Show flip/reverse in clip context menu.
- pub custom_context_actions: bool,
- /// Index into `SourcePreference::ALL`: where model downloads look first.
- pub download_source: usize,
- /// The base URL of a custom download source.
- pub download_base: String,
- /// Why the server is not running when the switch is on: the bind that
- /// failed. Empty while it runs, or is off.
- pub server_error: String,
-}
-
/// The missing media relink dialog state.
#[derive(Default)]
pub struct RelinkState {
@@ -301,21 +283,6 @@ pub struct ToastState {
pub failed: bool,
}
-/// One downloadable model, as the settings sheet shows it.
-#[derive(Clone)]
-pub struct ModelState {
- pub id: String,
- pub name: String,
- pub note: String,
- pub megabytes: f32,
- pub accuracy: i32,
- pub installed: bool,
- pub active: bool,
- /// Megabytes fetched so far while a download runs.
- pub fetched: Option<f32>,
- pub unpacking: bool,
-}
-
/// The form on the launch screen.
pub struct StartState {
pub name: String,
@@ -716,10 +683,8 @@ pub struct Studio {
// ── the sheets and menus ──
pub export: crate::panes::export::ExportPane,
- pub settings: SettingsState,
+ pub settings: crate::panes::settings::SettingsPane,
pub relink: RelinkState,
- pub transcribers: Vec<ModelState>,
- pub voices: Vec<ModelState>,
pub open_menu: i32,
pub menu_bar_token: i32,
pub menu_target: Option<String>,
@@ -1396,10 +1361,8 @@ impl Studio {
preview_wanted: false,
preview_failed: false,
export: Default::default(),
- settings: SettingsState::default(),
+ settings: crate::panes::settings::SettingsPane::default(),
relink: RelinkState::default(),
- transcribers: Vec::new(),
- voices: Vec::new(),
open_menu: -1,
menu_bar_token: 0,
menu_target: None,
@@ -1443,17 +1406,9 @@ impl Studio {
pending_stroke: None,
host,
};
- studio.settings.language = studio
- .languages
- .iter()
- .position(|language| Some(language.code.as_str()) == studio.prefs.locale.as_deref())
- .unwrap_or(0);
- studio.settings.playhead_stops = studio.prefs.playhead_stops_at_end;
- studio.settings.download_source = studio.download_source().0;
- studio.settings.download_base = studio.prefs.download_base.clone().unwrap_or_default();
- studio.apply_download_source();
- studio.apply_server();
- studio.refresh_models();
+ studio.handle(crate::panes::Msg::Settings(
+ crate::panes::settings::SettingsMsg::Restore,
+ ));
studio
}
@@ -5186,194 +5141,21 @@ impl Studio {
pane.update(msg, self);
self.export = pane;
}
- }
- }
-
- // ── speech ──
-
- /// The settings sheet's two model lists, from what is on disk.
- pub fn refresh_models(&mut self) {
- let dirs = &self.host.dirs;
- let downloading: HashMap<String, (Option<f32>, bool)> = self
- .transcribers
- .iter()
- .chain(self.voices.iter())
- .filter(|model| model.fetched.is_some())
- .map(|model| (model.id.clone(), (model.fetched, model.unpacking)))
- .collect();
- let chosen_transcriber = self.prefs.transcriber_model.clone();
- let chosen_voice = self.prefs.tts_model.clone();
- if let Ok(status) = concat_speech::Transcriber::status(dirs) {
- self.transcribers = status
- .models
- .iter()
- .map(|model| {
- let (fetched, unpacking) =
- downloading.get(&model.id).copied().unwrap_or((None, false));
- ModelState {
- id: model.id.clone(),
- name: model.label.clone(),
- note: model.blurb.clone(),
- megabytes: model.size_bytes as f32 / 1_000_000.0,
- accuracy: if model.id.starts_with("tiny") {
- 2
- } else if model.id.starts_with("base") {
- 3
- } else {
- 4
- },
- installed: model.downloaded,
- active: chosen_transcriber.as_deref() == Some(model.id.as_str()),
- fetched,
- unpacking,
- }
- })
- .collect();
- }
- if let Ok(status) = concat_speech::Speech::status(dirs) {
- self.speakers = status.voices.clone();
- self.voices = status
- .models
- .iter()
- .map(|model| {
- let (fetched, unpacking) =
- downloading.get(&model.id).copied().unwrap_or((None, false));
- ModelState {
- id: model.id.clone(),
- name: model.label.clone(),
- note: model.blurb.clone(),
- megabytes: model.size_bytes as f32 / 1_000_000.0,
- accuracy: if model.id.contains("int8") { 4 } else { 5 },
- installed: model.downloaded,
- active: chosen_voice.as_deref() == Some(model.id.as_str()),
- fetched,
- unpacking,
- }
- })
- .collect();
- }
- // An engine with nothing chosen falls back to whatever is installed,
- // rather than silently having no model at all.
- for list in [&mut self.transcribers, &mut self.voices] {
- if !list.iter().any(|model| model.active && model.installed)
- && let Some(first) = list.iter_mut().find(|model| model.installed)
- {
- first.active = true;
+ crate::panes::Msg::Settings(msg) => {
+ let mut pane = std::mem::take(&mut self.settings);
+ pane.update(msg, self);
+ self.settings = pane;
}
}
}
- fn is_transcriber(&self, id: &str) -> bool {
- self.transcribers.iter().any(|model| model.id == id)
- }
-
- pub fn model_activate(&mut self, id: &str) {
- if self.is_transcriber(id) {
- self.prefs.transcriber_model = Some(id.to_owned());
- } else {
- self.prefs.tts_model = Some(id.to_owned());
- }
- self.prefs.save(&self.host.dirs);
- self.refresh_models();
- }
-
- pub fn model_download(&mut self, id: &str) {
- let transcriber = self.is_transcriber(id);
- let list = if transcriber {
- &mut self.transcribers
- } else {
- &mut self.voices
- };
- let Some(model) = list.iter_mut().find(|model| model.id == id) else {
- return;
- };
- if model.installed || model.fetched.is_some() {
- return;
- }
- model.fetched = Some(0.0);
- let id = id.to_owned();
- let dirs = self.host.dirs.clone();
- let whisper = Arc::clone(&self.host.transcriber);
- let kokoro = Arc::clone(&self.host.speech);
- spawn(
- move || {
- let report = |progress: concat_speech::DownloadProgress| {
- on_ui(move |studio, _, _| {
- for list in [&mut studio.transcribers, &mut studio.voices] {
- if let Some(model) =
- list.iter_mut().find(|model| model.id == progress.id)
- {
- model.fetched = Some(progress.received as f32 / 1_000_000.0);
- model.unpacking = progress.unpacking;
- if progress.total > 0 {
- model.megabytes = progress.total as f32 / 1_000_000.0;
- }
- }
- }
- });
- };
- let result = if transcriber {
- whisper.download_model(&dirs, &id, report)
- } else {
- kokoro.download_model(&dirs, &id, report)
- };
- (id, result)
- },
- |studio, _, _, (id, result)| {
- for list in [&mut studio.transcribers, &mut studio.voices] {
- if let Some(model) = list.iter_mut().find(|model| model.id == id) {
- model.fetched = None;
- model.unpacking = false;
- }
- }
- match result {
- Ok(()) => {
- studio.notify(&t("Model ready"), false);
- if studio.is_transcriber(&id) && studio.prefs.transcriber_model.is_none() {
- studio.prefs.transcriber_model = Some(id.clone());
- } else if !studio.is_transcriber(&id) && studio.prefs.tts_model.is_none() {
- studio.prefs.tts_model = Some(id.clone());
- }
- studio.prefs.save(&studio.host.dirs);
- }
- Err(error) => studio.notify(&error, true),
- }
- studio.refresh_models();
- },
- );
- }
-
- pub fn model_cancel(&mut self, id: &str) {
- if self.is_transcriber(id) {
- self.host.transcriber.cancel_download();
- } else {
- self.host.speech.cancel_download();
- }
- }
-
- pub fn model_remove(&mut self, id: &str) {
- let result = if self.is_transcriber(id) {
- self.host.transcriber.delete_model(&self.host.dirs, id)
- } else {
- self.host.speech.delete_model(&self.host.dirs, id)
- };
- if let Err(error) = result {
- self.notify(&error, true);
- }
- self.refresh_models();
- }
-
- /// The models of a kind that are on disk, in the settings' order: the
- /// rows of a sheet's model list.
- fn installed(models: &[ModelState]) -> Vec<&ModelState> {
- models.iter().filter(|model| model.installed).collect()
- }
+ // ── speech ──
/// Opens the captions sheet with the chosen model already picked. What
/// it captions is decided here, not asked: the selected clip's sound
/// when one clip with sound is selected, and a script otherwise.
pub fn captions_open(&mut self) {
- let installed = Self::installed(&self.transcribers);
+ let installed = installed(&self.settings.transcribers);
let model = installed.iter().position(|model| model.active).unwrap_or(0);
let clip = self
.sole_selection()
@@ -5466,7 +5248,7 @@ impl Studio {
self.captions.message = t("This clip has no file to transcribe");
return;
};
- let Some(model) = Self::installed(&self.transcribers)
+ let Some(model) = installed(&self.settings.transcribers)
.get(self.captions.model)
.map(|model| model.id.clone())
else {
@@ -5545,7 +5327,7 @@ impl Studio {
.and_then(|id| self.clip(&id))
.filter(|clip| clip.kind == model::ClipKind::Text)
.cloned();
- let installed = Self::installed(&self.voices);
+ let installed = installed(&self.settings.voices);
let model = installed.iter().position(|model| model.active).unwrap_or(0);
let wanted = self.prefs.tts_voice.unwrap_or(DEFAULT_VOICE);
let voice = self
@@ -5574,7 +5356,7 @@ impl Studio {
self.speech.message = t("Nothing to read yet");
return;
}
- let Some(model) = Self::installed(&self.voices)
+ let Some(model) = installed(&self.settings.voices)
.get(self.speech.model)
.map(|model| model.id.clone())
else {
@@ -5807,99 +5589,6 @@ impl Studio {
sync(&models.dividers, out.dividers);
}
- /// The remembered download source: its place in the menu, and itself.
- pub fn download_source(&self) -> (usize, concat_host::models::SourcePreference) {
- use concat_host::models::SourcePreference;
- let preference =
- SourcePreference::parse(self.prefs.download_source.as_deref().unwrap_or_default());
- let index = SourcePreference::ALL
- .iter()
- .position(|candidate| *candidate == preference)
- .unwrap_or(0);
- (index, preference)
- }
-
- /// Starts or stops the API's server to match the preferences. A server
- /// already running is stopped first, so an edited address or token
- /// takes effect; a bind that fails turns the switch back off and says
- /// why on the page.
- pub fn apply_server(&mut self) {
- if let Some(server) = self.host.server.take() {
- server.stop();
- }
- self.settings.server_error.clear();
- let prefs = &self.prefs.server;
- if !prefs.enabled {
- return;
- }
- let started = prefs
- .listen
- .trim()
- .parse::<std::net::SocketAddr>()
- .map_err(|_| {
- tf(
- "{0} is not an address like 127.0.0.1:7420",
- &[&prefs.listen],
- )
- })
- .and_then(|address| {
- let config = concat_server::Config {
- json: Some(address),
- token: Some(prefs.token.clone()).filter(|token| !token.is_empty()),
- ..concat_server::Config::default()
- };
- concat_server::Server::start(config, concat_api::Api::new)
- });
- match started {
- Ok(server) => self.host.server = Some(server),
- Err(error) => {
- self.prefs.server.enabled = false;
- self.prefs.save(&self.host.dirs);
- self.settings.server_error = error.clone();
- self.notify(&error, true);
- }
- }
- }
-
- /// What the Remote page says under the switch.
- fn server_status(&self) -> String {
- match &self.host.server {
- Some(server) => {
- let address = server
- .json_addr()
- .map(|address| address.to_string())
- .unwrap_or_default();
- tf(
- "Listening on {0} · {1} connected",
- &[&address, &server.connections()],
- )
- }
- None if !self.settings.server_error.is_empty() => self.settings.server_error.clone(),
- None => t("Off"),
- }
- }
-
- /// A fresh token: 128 bits from the OS's randomness, as the standard
- /// library hands it out through its hasher's seed, spelled in hex.
- pub fn new_token() -> String {
- use std::hash::{BuildHasher, Hasher};
- let word = |salt: u64| {
- let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
- hasher.write_u64(salt);
- hasher.finish()
- };
- format!("{:016x}{:016x}", word(1), word(2))
- }
-
- /// Tells the downloaders where to look first, from the preferences.
- pub fn apply_download_source(&self) {
- let (_, preference) = self.download_source();
- concat_host::models::set_preference(
- preference,
- self.prefs.download_base.as_deref().unwrap_or_default(),
- );
- }
-
/// Shows the compact dock, or the wide one, keeping whichever is put
/// away whole; see `COMPACT_WIDTH`.
pub fn set_compact(&mut self, compact: bool) {
@@ -6837,56 +6526,26 @@ impl Studio {
editor.set_menu_token(self.menu_token);
app.set_export(self.export.data(self));
- app.set_settings(SettingsData {
- open: self.settings.open,
- tab: self.settings.tab,
- language: self.settings.language as i32,
- playhead_stops: self.settings.playhead_stops,
- custom_context_actions: self.prefs.custom_context_actions,
- download_source: self.settings.download_source as i32,
- download_base: self.settings.download_base.as_str().into(),
- server_enabled: self.prefs.server.enabled,
- server_listen: self.prefs.server.listen.as_str().into(),
- server_token: self.prefs.server.token.as_str().into(),
- server_status: self.server_status().into(),
- disk: {
- let installed: Vec<&ModelState> = self
- .transcribers
+ app.set_settings(self.settings.data(self));
+ sync(&models.transcribers, self.settings.transcriber_rows());
+ sync(&models.voices, self.settings.voice_rows());
+ app.set_relink(RelinkData {
+ open: self.relink.open,
+ items: slint::ModelRc::new(VecModel::from(
+ self.relink
+ .items
.iter()
- .chain(self.voices.iter())
- .filter(|model| model.installed)
- .collect();
-
- let relink_data = RelinkData {
- open: self.relink.open,
- items: slint::ModelRc::new(VecModel::from(
- self.relink
- .items
- .iter()
- .map(|item| MissingMediaItem {
- id: item.id.clone().into(),
- name: item.name.clone().into(),
- path: item.path.clone().into(),
- })
- .collect::<Vec<_>>(),
- )),
- };
- app.set_relink(relink_data);
- let on_disk: f32 = installed.iter().map(|model| model.megabytes).sum();
- tf(
- "{0} installed · {1} MB on disk",
- &[&installed.len(), &format!("{on_disk:.0}")],
- )
- .into()
- },
- version: env!("CARGO_PKG_VERSION").into(),
- engine: format!("concat-engine · FFmpeg {}", concat_media::linked_version()).into(),
+ .map(|item| MissingMediaItem {
+ id: item.id.clone().into(),
+ name: item.name.clone().into(),
+ path: item.path.clone().into(),
+ })
+ .collect::<Vec<_>>(),
+ )),
});
- sync(&models.transcribers, Self::model_rows(&self.transcribers));
- sync(&models.voices, Self::model_rows(&self.voices));
// The speech sheets, and the lists they choose from.
- let transcribers = Self::installed(&self.transcribers);
+ let transcribers = installed(&self.settings.transcribers);
sync(
&models.caption_models,
transcribers
@@ -6913,7 +6572,7 @@ impl Studio {
ready: !transcribers.is_empty(),
message: self.captions.message.as_str().into(),
});
- let voices = Self::installed(&self.voices);
+ let voices = installed(&self.settings.voices);
sync(
&models.speech_models,
voices
@@ -6972,41 +6631,6 @@ impl Studio {
}
}
- fn model_rows(models: &[ModelState]) -> Vec<ModelData> {
- models
- .iter()
- .map(|model| {
- let total = model.megabytes;
- let fetched = model.fetched.unwrap_or(0.0);
- ModelData {
- id: model.id.as_str().into(),
- name: model.name.as_str().into(),
- note: model.note.as_str().into(),
- size: format!("{total:.0} MB").into(),
- accuracy: model.accuracy,
- installed: model.installed,
- active: model.active && model.installed,
- downloading: model.fetched.is_some(),
- progress: if total > 0.0 {
- (fetched / total).min(1.0)
- } else {
- 0.0
- },
- transferred: if model.unpacking {
- t("Unpacking…").into()
- } else {
- tf(
- "{0} MB of {1} MB",
- &[&format!("{fetched:.0}"), &format!("{total:.0}")],
- )
- .into()
- },
- eta: SharedString::new(),
- }
- })
- .collect()
- }
-
/// The right-click menu for the clip it was opened on.
fn menu(&self) -> Vec<MenuItemData> {
let Some(clip) = self.menu_target.as_ref().and_then(|id| self.clip(id)) else {