133 lines
9.2 KiB
Rust
133 lines
9.2 KiB
Rust
use std::{path::PathBuf,sync::{Arc,Mutex,Weak,atomic::{AtomicU64,Ordering}},thread};
|
|
use tokio::sync::{mpsc,watch};
|
|
|
|
pub mod app {
|
|
pub mod connections;
|
|
pub mod media_binding;
|
|
pub mod server_actions;
|
|
pub mod runtime;
|
|
}
|
|
pub mod services;
|
|
pub mod media;
|
|
pub mod platform;
|
|
pub mod ui;
|
|
#[cfg(feature="test-harness")]
|
|
pub mod smoke;
|
|
slint::include_modules!();
|
|
|
|
#[derive(Clone,Debug)]
|
|
pub struct AppConfig {
|
|
pub build_version:&'static str,
|
|
pub profile_dir:Option<PathBuf>,
|
|
pub mobile_container:Option<PathBuf>,
|
|
pub allow_os_actions:bool,
|
|
pub network_enabled:bool,
|
|
}
|
|
impl Default for AppConfig {
|
|
fn default()->Self{Self{build_version:env!("CARGO_PKG_VERSION"),profile_dir:None,mobile_container:None,allow_os_actions:true,network_enabled:true}}
|
|
}
|
|
impl AppConfig {
|
|
pub fn isolated(profile:PathBuf)->Self{Self{profile_dir:Some(profile),allow_os_actions:false,network_enabled:false,..Self::default()}}
|
|
}
|
|
#[derive(Debug,thiserror::Error)]
|
|
pub enum AppError {
|
|
#[error("native interface: {0}")] Platform(#[from] slint::PlatformError),
|
|
#[error(transparent)] Service(#[from] services::ServiceError),
|
|
#[error(transparent)] Io(#[from] std::io::Error),
|
|
#[error("native smoke: {0}")] Smoke(String),
|
|
}
|
|
// Platform callbacks can outlive a stopped runtime in the same mobile process.
|
|
// Never reuse an attachment token when that process creates another runtime.
|
|
static NEXT_UI_GENERATION:AtomicU64=AtomicU64::new(0);
|
|
|
|
/// Process services contain no Slint object or Activity reference. The worker retains only a Weak
|
|
/// reference back to this handle, so dropping the last UI/call lease requests orderly termination.
|
|
pub struct AppRuntime {
|
|
pub(crate) config:AppConfig,
|
|
pub(crate) commands:mpsc::Sender<app::runtime::RuntimeCommand>,
|
|
pub(crate) cancel:watch::Sender<bool>,
|
|
pub(crate) snapshots:watch::Receiver<Arc<app::runtime::model::Snapshot>>,
|
|
pub(crate) effects:Mutex<mpsc::Receiver<app::runtime::events::UiEffect>>,
|
|
pub(crate) services:Mutex<Weak<app::runtime::context::RuntimeServices>>,
|
|
pub(crate) wake:Mutex<Option<Arc<dyn Fn()+Send+Sync>>>,
|
|
pub(crate) pending_wake:std::sync::atomic::AtomicBool,
|
|
pub(crate) active_ui:AtomicU64,
|
|
pub(crate) finished:watch::Receiver<Option<services::Result<()>>>,
|
|
pub(crate) worker:Mutex<Option<thread::JoinHandle<()>>>,
|
|
#[cfg(not(any(target_os="android",target_os="ios")))]
|
|
pub(crate) desktop:Mutex<Option<platform::desktop::DesktopHandle>>,
|
|
}
|
|
impl AppRuntime {
|
|
pub fn start(config:AppConfig)->Result<Arc<Self>,AppError>{app::runtime::start(config)}
|
|
pub fn snapshot(&self)->Arc<app::runtime::model::Snapshot>{self.snapshots.borrow().clone()}
|
|
pub fn subscribe(&self)->watch::Receiver<Arc<app::runtime::model::Snapshot>>{self.snapshots.clone()}
|
|
pub fn build_description(&self)->String{format!("Version {}\nRust + Slint 1.18.1\n{} / {}",self.config.build_version,std::env::consts::OS,std::env::consts::ARCH)}
|
|
pub fn policy(&self)->platform::resources::ActionPolicy{platform::resources::ActionPolicy{allow_os_actions:self.config.allow_os_actions}}
|
|
pub fn next_ui_generation(&self)->u64 {
|
|
self.release_held();
|
|
let generation=NEXT_UI_GENERATION.fetch_update(Ordering::AcqRel,Ordering::Acquire,|g|g.checked_add(1)).expect("UI generation exhausted")+1;
|
|
self.active_ui.store(generation,Ordering::Release);generation
|
|
}
|
|
pub fn ui_generation(&self)->u64{self.active_ui.load(Ordering::Acquire)}
|
|
pub fn current_ui_generation(&self)->Option<u64>{Some(self.ui_generation()).filter(|g|*g!=0)}
|
|
pub fn is_ui_current(&self,generation:u64)->bool{generation!=0&&self.ui_generation()==generation}
|
|
pub fn release_ui(&self,generation:u64){
|
|
if self.active_ui.compare_exchange(generation,0,Ordering::AcqRel,Ordering::Acquire).is_ok(){
|
|
self.release_held();self.wake.lock().expect("UI wake").take();
|
|
#[cfg(not(any(target_os="android",target_os="ios")))] self.desktop.lock().expect("desktop handle").take();
|
|
let _=self.commands.try_send(app::runtime::RuntimeCommand::Detached(generation));
|
|
}
|
|
}
|
|
pub fn release_held(&self){if let Some(ctx)=self.services.lock().expect("runtime services").upgrade(){app::runtime::controller::release_immediate(&ctx);let stop=ctx.transmission.lock().ok().and_then(|mut tx|tx.whisper.release(None));if let Some(stop)=stop{if self.commands.try_send(app::runtime::RuntimeCommand::WhisperStop(stop)).is_err(){self.cancel.send_replace(true);}}}}
|
|
fn release_screen(&self,target:&ui::shell::Target){if let Some(ctx)=self.services.lock().expect("runtime services").upgrade(){
|
|
let delay=ctx.profile().ok().map(|profile|profile.prefs.get()["pttReleaseDelay"].clone());
|
|
let revoke=if let Ok(mut tx)=ctx.transmission.lock(){if tx.key.as_ref()!=target.session.as_ref(){return}let removed=tx.ptt_holders.remove("screen");if removed{tx.revision=tx.revision.wrapping_add(1);if tx.ptt_holders.is_empty(){tx.release_at=delay.filter(|d|d["active"]==true).and_then(|d|d["ms"].as_u64()).map(|ms|std::time::Instant::now()+std::time::Duration::from_millis(ms));}}removed&&!tx.whisper.held()}else{true};
|
|
if revoke{ctx.audio.revoke_capture();}
|
|
}}
|
|
pub fn dispatch_shell(&self,action:ui::shell::ShellAction)->services::Result<()>{
|
|
if let ui::shell::ShellAction::PushToTalk{target,held:false}=&action{self.release_screen(target);}
|
|
self.enqueue(app::runtime::RuntimeCommand::Shell(action))
|
|
}
|
|
pub fn dispatch_settings(&self,action:ui::settings::SettingsAction)->services::Result<()>{self.enqueue(app::runtime::RuntimeCommand::Settings(action))}
|
|
pub fn dispatch_chat(&self,action:ui::chat::ChatAction)->services::Result<()>{self.enqueue(app::runtime::RuntimeCommand::Chat(action))}
|
|
pub fn platform_event(&self,event:platform::lifecycle::PlatformEvent){
|
|
use platform::lifecycle::PlatformEvent::*;
|
|
let generation=match &event{Visibility{ui_generation,..}|UiDestroyed{ui_generation}|Insets{ui_generation,..}|Accessibility{ui_generation,..}|DesktopTheme{ui_generation,..}|DesktopWindow{ui_generation,..}|PhysicalKey{ui_generation,..}|Focus{ui_generation,..}=>Some(*ui_generation),_=>None};
|
|
if generation.is_some_and(|generation|!self.is_ui_current(generation)){return}
|
|
#[cfg(target_os="android")]
|
|
if let AndroidCallAudio{key,token,revision,..}=&event {
|
|
if !platform::android::voice_audio_current(key,*token,*revision){return}
|
|
self.release_held();
|
|
}
|
|
#[cfg(target_os="android")]
|
|
if matches!(&event,Visibility{visible:false,..}){self.release_held();}
|
|
if matches!(&event,Focus{focused:false,..}|UiDestroyed{..}|AudioInterruption{began:true,..}|AudioRouteChanged|NetworkChanged|PermissionChanged{permission:platform::lifecycle::Permission::Microphone,granted:false}|CallLeaseEnded{..}|Quit){self.release_held();}
|
|
if self.enqueue(app::runtime::RuntimeCommand::Platform(event)).is_err(){self.cancel.send_replace(true);}
|
|
}
|
|
fn enqueue(&self,command:app::runtime::RuntimeCommand)->services::Result<()>{self.commands.try_send(command).map_err(|_|services::ServiceError::new("runtime_busy","Application action queue is full or stopped; retry the action"))}
|
|
pub(crate) fn notify_ui(&self){if !self.pending_wake.swap(true,Ordering::AcqRel){if let Some(wake)=self.wake.lock().expect("UI wake").as_ref(){wake();}}}
|
|
pub(crate) fn set_waker(&self,wake:Arc<dyn Fn()+Send+Sync>){*self.wake.lock().expect("UI wake")=Some(wake);self.pending_wake.store(false,Ordering::Release);self.notify_ui();}
|
|
pub(crate) fn drain_effects(&self)->Vec<app::runtime::events::UiEffect>{self.pending_wake.store(false,Ordering::Release);let mut effects=self.effects.lock().expect("UI effects");let mut batch=Vec::new();while let Ok(effect)=effects.try_recv(){batch.push(effect)}batch}
|
|
#[cfg(not(any(target_os="android",target_os="ios")))]
|
|
pub fn desktop_handle(&self)->Option<platform::desktop::DesktopHandle>{self.desktop.lock().expect("desktop handle").clone()}
|
|
pub async fn shutdown(&self)->services::Result<()> {
|
|
self.release_held();self.cancel.send_replace(true);let mut done=self.finished.clone();
|
|
let result=loop{if let Some(result)=done.borrow_and_update().clone(){break result}done.changed().await.map_err(|_|services::ServiceError::new("worker_stopped","Application worker ended without a shutdown result"))?;};
|
|
let worker=self.worker.lock().expect("runtime worker").take();
|
|
if let Some(worker)=worker{tokio::task::spawn_blocking(move||worker.join()).await.map_err(|_|services::ServiceError::new("worker_join","Application worker join failed"))?.map_err(|_|services::ServiceError::new("worker_panicked","Application worker panicked"))?;}result
|
|
}
|
|
}
|
|
impl Drop for AppRuntime {fn drop(&mut self){self.cancel.send_replace(true);}}
|
|
|
|
pub fn attach_ui(runtime:Arc<AppRuntime>)->Result<(),AppError>{let generation=runtime.next_ui_generation();attach_ui_with_generation(runtime,generation)}
|
|
pub fn attach_ui_with_generation(runtime:Arc<AppRuntime>,generation:u64)->Result<(),AppError>{
|
|
use slint::ComponentHandle;
|
|
let attachment=ui::application::bind(runtime,generation)?;
|
|
attachment.window().run()?;
|
|
if let Some(error)=attachment.take_startup_error(){return Err(error.into())}
|
|
Ok(())
|
|
}
|
|
#[cfg(target_os="android")]
|
|
#[unsafe(no_mangle)]
|
|
pub fn android_main(app:slint::android::AndroidApp){platform::android::run(app);}
|