Skip to content

Commit

Permalink
module level cleanup, modified thread communication
Browse files Browse the repository at this point in the history
  • Loading branch information
chipnertkj committed May 8, 2024
1 parent 97b33f0 commit 1c95b18
Show file tree
Hide file tree
Showing 22 changed files with 372 additions and 200 deletions.
66 changes: 66 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ once_cell = "1.19"
chrono = { version = "0.4", features = ["serde"] }
rb = { version = "0.4" }
derive_more = { version = "0.99", features = ["nightly"] }
cowstr = { version = "1.3", features = ["serde"] }
## tracing
tracing = "0.1"
tracing-subscriber = { version = "0.3" }
Expand Down
1 change: 1 addition & 0 deletions backend/lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ gen_value = { workspace = true }
once_cell = { workspace = true }
rb = { workspace = true }
tauri = { workspace = true }
cowstr.workspace = true
97 changes: 2 additions & 95 deletions backend/lib/src/app_data.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use self::app_state::AppState;
use crate::{common, AppThread, ThreadMsg};
use common::app::{BackendMsg, BackendResponse, FrontendMsg, FrontendRequest};
pub mod msg;

mod app_state;
use self::app_state::AppState;

/// All data required for managing the application.
///
Expand All @@ -25,96 +24,4 @@ impl AppData {
pub fn tauri_app(&self) -> &tauri::AppHandle {
&self.tauri_app
}

/// Handles a message from the parent thread.
/// Returns `true` if the app should quit.
pub fn handle_msg(&mut self, msg: ThreadMsg) -> bool {
match msg {
// Handle frontend message.
ThreadMsg::Frontend(msg) => self.handle_frontend_msg(msg),
// Quit.
ThreadMsg::Exit => return true,
};
false
}

/// Handles messages from the frontend.
fn handle_frontend_msg(&mut self, msg: FrontendMsg) {
match msg {
FrontendMsg::Request(request) => {
self.handle_frontend_request(request)
}
}
}

/// Handles the request and sends a response to the frontend.
fn handle_frontend_request(&mut self, request: FrontendRequest) {
// Handle request and prepare response.
let response = match request {
FrontendRequest::BackendAppState => {
self.backend_app_state_response()
}
FrontendRequest::Settings => self.backend_settings_response(),
FrontendRequest::UseDefaultSettings => {
self.use_default_settings_response()
}
};

// Send response.
AppThread::send_message(
&self.tauri_app,
BackendMsg::Response(response),
);
}

/// Reply with current state.
fn backend_app_state_response(&mut self) -> BackendResponse {
// Get state and convert it to `BackendAppState`.
let app_state = (&self.state).into();

// Prepare response.
BackendResponse::BackendAppState(app_state)
}

/// Reply with current settings.
fn backend_settings_response(&mut self) -> BackendResponse {
// Get settings.
let settings_opt = match self.state {
AppState::Idle { ref settings } => Some(settings.clone()),
_ => None,
};

// Prepare response.
BackendResponse::Settings(settings_opt)
}

/// Set default settings and reply with a copy.
pub fn use_default_settings_response(&mut self) -> BackendResponse {
// Apply and return settings.
match self.state {
// Fail gracefully if in the middle of reading settings.
AppState::ReadingSettings => {
tracing::error!("Frontend attempted to set settings to default while backend was still reading config.");
}
// Change state to idle if awaiting config.
AppState::AwaitConfig { .. } => {
self.state = AppState::Idle {
settings: Default::default(),
};
}
// Modify if idle.
AppState::Idle { ref mut settings } => {
*settings = Default::default();
}
// Modify if editing a project.
AppState::Edit {
ref mut settings, ..
} => {
*settings = Default::default();
}
}

// Prepare response.
BackendResponse::UseDefaultSettings(Default::default())
}
}
4 changes: 3 additions & 1 deletion backend/lib/src/app_data/app_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ impl From<&AppState> for BackendAppState {
match app {
AppState::ReadingSettings => BackendAppState::ReadingSettings,
AppState::AwaitConfig { ref reason } => {
BackendAppState::AwaitConfig { reason: *reason }
BackendAppState::AwaitConfig {
reason: reason.clone(),
}
}
AppState::Idle { .. } => BackendAppState::Idle,
AppState::Edit { .. } => BackendAppState::Editor,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use chipbox_common as common;
use cowstr::CowStr;
use std::str::FromStr;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
Expand All @@ -13,20 +14,20 @@ impl From<HostId> for cpal::HostId {

#[derive(Debug)]
pub enum ParseError {
Invalid(String),
WrongPlatform(String),
Invalid { value: CowStr },
WrongPlatform { value: CowStr },
}

impl std::fmt::Display for ParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ParseError::Invalid(s) => {
write!(f, "`{s}` is not convertible to a valid host id")
ParseError::Invalid { value } => {
write!(f, "`{value}` is not convertible to a valid host id")
}
ParseError::WrongPlatform(s) => {
ParseError::WrongPlatform { value } => {
write!(
f,
"host `{s}` is not supported on this platform ({platform})",
"host `{value}` is not supported on this platform ({platform})",
platform = std::env::consts::OS
)
}
Expand All @@ -38,7 +39,7 @@ impl std::error::Error for ParseError {}

impl FromStr for HostId {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
fn from_str(value: &str) -> Result<Self, Self::Err> {
const WASAPI: &str = "wasapi";
const ASIO: &str = "asio";
const JACK: &str = "jack";
Expand All @@ -53,7 +54,7 @@ impl FromStr for HostId {
NULL,
];

match s.to_lowercase().as_str() {
match value.to_lowercase().as_str() {
#[cfg(target_os = "windows")]
WASAPI => Ok(Self(cpal::HostId::Wasapi)),
#[cfg(target_os = "windows")]
Expand Down Expand Up @@ -94,10 +95,14 @@ impl FromStr for HostId {
)))]
NULL => Ok(Self(cpal::HostId::Null)),
_ => {
if SUPPORTED_BACKENDS.contains(&s) {
Err(ParseError::WrongPlatform(s.into()))
if SUPPORTED_BACKENDS.contains(&value) {
Err(ParseError::WrongPlatform {
value: value.into(),
})
} else {
Err(ParseError::Invalid(s.into()))
Err(ParseError::Invalid {
value: value.into(),
})
}
}
}
Expand Down
27 changes: 27 additions & 0 deletions backend/lib/src/app_data/msg.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use self::request::handle_frontend_request;

use super::AppData;
use crate::{common, ThreadMsg};
use common::app::msg::FrontendMsg;
mod request;

/// Handles a message from the parent thread.
/// Returns `true` if the app should quit.
pub fn handle_thread_msg(app_data: &mut AppData, msg: ThreadMsg) -> bool {
match msg {
// Handle frontend message.
ThreadMsg::Frontend(msg) => handle_frontend_msg(app_data, msg),
// Quit.
ThreadMsg::Exit => return true,
};
false
}

/// Handles messages from the frontend.
fn handle_frontend_msg(app_data: &mut AppData, msg: FrontendMsg) {
match msg {
FrontendMsg::Request(request) => {
handle_frontend_request(app_data, request)
}
}
}
27 changes: 27 additions & 0 deletions backend/lib/src/app_data/msg/request.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use crate::app_data::AppData;
use crate::{common, AppThread};
use common::app::msg::request::FrontendRequest;
use common::app::msg::BackendMsg;

mod backend_response;

/// Handles the request and sends a response to the frontend.
pub(super) fn handle_frontend_request(
app_data: &mut AppData,
request: FrontendRequest,
) {
// Handle request and prepare response.
let response = match request {
FrontendRequest::AppState => backend_response::app_state(app_data),
FrontendRequest::Settings => backend_response::settings(app_data),
FrontendRequest::UseDefaultSettings => {
backend_response::use_default_settings(app_data)
}
};

// Send response.
AppThread::send_message(
&app_data.tauri_app,
BackendMsg::Response(response),
);
}
Loading

0 comments on commit 1c95b18

Please sign in to comment.