use std::cell::RefCell;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, mpsc};
use std::thread::ThreadId;
use mln_actor::{RunLoop, RunLoopHandle};
use mln_storage::http_header_transform::{HttpHeaderTransform, HttpHeaders};
use mln_storage::resource::Kind;
use mln_storage::resource_transform::{FinishedCallback, ResourceTransform};
use mln_storage::{DatabaseFileSource, FileSource, FileSourceManager, FileSourceType, ResourceOptions};
use mln_text::GlyphCache;
use mln_util::error::Error;
use mln_util::sync::MutexExt;
use crate::completion::{Completion, Resolver};
use crate::event::{EventHandler, RuntimeEvent};
use crate::map::{Applied, Map, MapEntry, MapId, MapOptions, MapShared, Published};
use crate::offline::Offline;
use crate::resources::{CacheDatabaseOperation, ProviderFileSource, ResourceHooks, ResourceProvider};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RuntimeOptions {
pub asset_path: Option<PathBuf>,
pub cache_path: Option<PathBuf>,
}
#[derive(Clone)]
pub struct Runtime {
pub(crate) shared: Arc<RuntimeShared>,
}
impl std::fmt::Debug for Runtime {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Runtime").field("thread", &self.shared.thread).finish()
}
}
struct Lifecycle {
released: bool,
live_maps: usize,
shut_down: bool,
}
pub(crate) struct RuntimeShared {
run_loop: RunLoopHandle,
queued: Arc<AtomicUsize>,
thread: ThreadId,
lifecycle: Mutex<Lifecycle>,
next_map_id: AtomicU64,
pub(crate) glyph_cache: Arc<GlyphCache>,
}
impl RuntimeShared {
pub(crate) fn post(&self, task: impl FnOnce(&mut RuntimeCore, &mut Outbox) + Send + 'static) {
self.queued.fetch_add(1, Ordering::SeqCst);
self.run_loop.invoke(move || run(task, true));
}
pub(crate) fn post_or<V: Send + 'static>(
&self,
value: V,
task: impl FnOnce(&mut RuntimeCore, &mut Outbox, V) + Send + 'static,
instead: impl FnOnce(V),
) {
let lifecycle = self.lifecycle.lock_unpoisoned();
if lifecycle.shut_down {
drop(lifecycle);
instead(value);
} else {
self.post(move |core, outbox| task(core, outbox, value));
}
}
pub(crate) fn thread(&self) -> ThreadId {
self.thread
}
pub(crate) fn completion<T: Send + 'static>(&self) -> (Completion<T>, Resolver<T>) {
Completion::new(Some(self.thread))
}
fn check_live(&self) -> Result<(), Error> {
if self.lifecycle.lock_unpoisoned().released { Err(released()) } else { Ok(()) }
}
pub(crate) fn map_released(&self) {
let shut_down = {
let mut lifecycle = self.lifecycle.lock_unpoisoned();
lifecycle.live_maps -= 1;
let shut_down = lifecycle.released && lifecycle.live_maps == 0 && !lifecycle.shut_down;
lifecycle.shut_down |= shut_down;
shut_down
};
if shut_down {
self.shut_down(None);
}
}
fn shut_down(&self, done: Option<Resolver<()>>) {
let run_loop = self.run_loop.clone();
self.run_loop.invoke(move || {
let core = CORE.with(|core| core.borrow_mut().take());
drop(core);
if let Some(done) = done {
done.resolve(Ok(()));
}
run_loop.stop();
});
}
}
impl Drop for RuntimeShared {
fn drop(&mut self) {
if !self.lifecycle.get_mut_unpoisoned().shut_down {
self.shut_down(None);
}
}
}
fn released() -> Error {
Error::invalid_state("the runtime was released")
}
thread_local! {
static CORE: RefCell<Option<RuntimeCore>> = const { RefCell::new(None) };
}
pub(crate) fn post(run_loop: &RunLoopHandle, task: impl FnOnce(&mut RuntimeCore, &mut Outbox) + Send + 'static) {
run_loop.invoke(move || run(task, false));
}
fn run(task: impl FnOnce(&mut RuntimeCore, &mut Outbox), in_burst: bool) {
let mut outbox = Outbox::default();
let unrun = CORE.with(|core| match core.borrow_mut().as_mut() {
Some(core) => {
if in_burst {
core.begin_burst_task();
}
task(core, &mut outbox);
if in_burst {
core.end_burst_task(&mut outbox);
}
None
}
None => Some(task),
});
drop(unrun);
outbox.deliver();
}
#[derive(Default)]
pub(crate) struct Outbox {
deliveries: Vec<Box<dyn FnOnce()>>,
}
impl Outbox {
pub(crate) fn push(&mut self, delivery: impl FnOnce() + 'static) {
self.deliveries.push(Box::new(delivery));
}
pub(crate) fn resolve<T: 'static>(&mut self, resolver: Resolver<T>, result: Result<T, Error>) {
self.push(move || resolver.resolve(result));
}
pub(crate) fn deliver(self) {
for delivery in self.deliveries {
delivery();
}
}
}
pub(crate) struct RuntimeCore {
pub(crate) maps: BTreeMap<MapId, MapEntry>,
pub(crate) event_handler: Option<EventHandler>,
hooks: Arc<ResourceHooks>,
file_sources: FileSourceManager,
resource_options: ResourceOptions,
_loader: Option<Arc<dyn FileSource>>,
database: Option<Arc<dyn FileSource>>,
network: Option<Arc<dyn FileSource>>,
pub(crate) run_loop: RunLoopHandle,
queued: Arc<AtomicUsize>,
burst_left: usize,
holding: bool,
}
impl RuntimeCore {
fn new(resource_options: ResourceOptions, run_loop: RunLoopHandle, queued: Arc<AtomicUsize>) -> Self {
let hooks = Arc::new(ResourceHooks::default());
let file_sources = FileSourceManager::new();
let network_hooks = hooks.clone();
file_sources.register_file_source_factory(
FileSourceType::Network,
Arc::new(move |_: &FileSourceManager, options: &ResourceOptions| {
Arc::new(ProviderFileSource::new(options, network_hooks.clone())) as Arc<dyn FileSource>
}),
);
let network = file_sources.get_file_source(FileSourceType::Network, &resource_options);
let database = file_sources.get_file_source(FileSourceType::Database, &resource_options);
let loader = file_sources.get_file_source(FileSourceType::ResourceLoader, &resource_options);
RuntimeCore {
maps: BTreeMap::new(),
event_handler: None,
hooks,
file_sources,
resource_options,
_loader: loader,
database,
network,
run_loop,
queued,
burst_left: 0,
holding: false,
}
}
fn begin_burst_task(&mut self) {
let queued = self.queued.fetch_sub(1, Ordering::SeqCst);
if self.burst_left == 0 {
self.burst_left = queued;
self.holding = queued > 1;
if self.holding {
self.maps.values_mut().for_each(|entry| entry.core.hold_updates());
}
}
}
fn end_burst_task(&mut self, outbox: &mut Outbox) {
self.burst_left = self.burst_left.saturating_sub(1);
if self.burst_left > 0 || !std::mem::take(&mut self.holding) {
return;
}
let ids: Vec<MapId> = self.maps.keys().copied().collect();
for id in ids {
if let Some(entry) = self.maps.get_mut(&id) {
entry.core.release_updates();
}
crate::map::flush(self, id, outbox);
}
}
pub(crate) fn file_sources(&self) -> (&FileSourceManager, &ResourceOptions) {
(&self.file_sources, &self.resource_options)
}
pub(crate) fn send_events(&self, events: Vec<RuntimeEvent>, outbox: &mut Outbox) {
if events.is_empty() {
return;
}
if let Some(handler) = self.event_handler.clone() {
outbox.push(move || handler(&events));
}
}
pub(crate) fn database(&self) -> Result<&DatabaseFileSource, Error> {
self.database
.as_ref()
.and_then(|database| database.as_any())
.and_then(|database| database.downcast_ref::<DatabaseFileSource>())
.ok_or_else(|| Error::unsupported("the runtime has no cache database"))
}
fn network(&self) -> Result<&Arc<dyn FileSource>, Error> {
self.network.as_ref().ok_or_else(|| Error::unsupported("the runtime has no network file source"))
}
}
pub(crate) fn reply_on<T: Send + 'static, E: Into<Error>>(
run_loop: RunLoopHandle,
resolver: Resolver<T>,
) -> impl FnOnce(Result<T, E>) + Send + 'static {
move |result| {
let result = result.map_err(Into::into);
post(&run_loop, move |_, outbox| outbox.resolve(resolver, result));
}
}
fn resource_options(options: &RuntimeOptions) -> Result<ResourceOptions, Error> {
let mut resource_options = ResourceOptions::default();
if let Some(asset_path) = &options.asset_path {
resource_options = resource_options.with_asset_path(utf8(asset_path, "asset path")?);
}
#[cfg(target_os = "android")]
if options.asset_path.is_none() {
resource_options = resource_options.with_asset_path(mln_storage::android::APP_ASSETS);
}
if let Some(cache_path) = &options.cache_path {
let path = utf8(cache_path, "cache path")?;
std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(cache_path)
.map_err(|error| Error::invalid_argument(format!("can't open the cache database {path}: {error}")))?;
resource_options = resource_options.with_cache_path(path);
}
Ok(resource_options)
}
fn utf8<'a>(path: &'a Path, what: &str) -> Result<&'a str, Error> {
path.to_str().ok_or_else(|| Error::invalid_argument(format!("the {what} {} isn't UTF-8", path.display())))
}
impl Runtime {
pub fn new(options: &RuntimeOptions) -> Result<Runtime, Error> {
let resource_options = resource_options(options)?;
let (started, start) = mpsc::channel();
let queued = Arc::new(AtomicUsize::new(0));
let core_queued = Arc::clone(&queued);
let thread = mln_util::thread::builder("Runtime")
.spawn(move || {
let run_loop = RunLoop::new();
let core = RuntimeCore::new(resource_options, run_loop.handle(), core_queued);
CORE.with(|cell| *cell.borrow_mut() = Some(core));
let _ = started.send(run_loop.handle());
run_loop.run();
let core = CORE.with(|cell| cell.borrow_mut().take());
drop(core);
})
.map_err(|error| Error::native(format!("can't start the runtime's thread: {error}")))?;
let thread_id = thread.thread().id();
drop(thread);
let run_loop = start.recv().map_err(|_| Error::native("the runtime's thread stopped as it started"))?;
Ok(Runtime {
shared: Arc::new(RuntimeShared {
run_loop,
queued,
thread: thread_id,
lifecycle: Mutex::new(Lifecycle { released: false, live_maps: 0, shut_down: false }),
next_map_id: AtomicU64::new(1),
glyph_cache: Arc::default(),
}),
})
}
fn command<T: Send + 'static>(
&self,
command: impl FnOnce(&mut RuntimeCore, &mut Outbox, Resolver<T>) + Send + 'static,
) -> Result<Completion<T>, Error> {
self.shared.check_live()?;
let (completion, resolver) = self.shared.completion();
self.shared.post(move |core, outbox| command(core, outbox, resolver));
Ok(completion)
}
fn apply<T: Send + 'static>(
&self,
apply: impl FnOnce(&mut RuntimeCore) -> Result<T, Error> + Send + 'static,
) -> Result<Completion<T>, Error> {
self.command(move |core, outbox, resolver| {
let result = apply(core);
outbox.resolve(resolver, result);
})
}
pub fn create_map(&self, options: MapOptions) -> Result<(Map, Completion<Applied>), Error> {
let size = options.map.size();
let pixel_ratio = options.map.pixel_ratio();
if size.is_empty() {
return Err(Error::invalid_argument("the map's size must not be empty"));
}
if !pixel_ratio.is_finite() || pixel_ratio <= 0.0 {
return Err(Error::invalid_argument("the map's pixel ratio must be finite and positive"));
}
{
let mut lifecycle = self.shared.lifecycle.lock_unpoisoned();
if lifecycle.released {
return Err(released());
}
lifecycle.live_maps += 1;
}
let id = MapId(self.shared.next_map_id.fetch_add(1, Ordering::Relaxed));
let published = Arc::new(Published::new(options.event_mask));
let map = Map::new(MapShared::new(id, self.shared.clone(), &options, published.clone()));
let (completion, resolver) = self.shared.completion();
self.shared.post(move |core, outbox| crate::map::create(core, id, &options, published, resolver, outbox));
Ok((map, completion))
}
pub fn set_event_handler(
&self,
handler: impl Fn(&[RuntimeEvent]) + Send + Sync + 'static,
) -> Result<Completion<()>, Error> {
let handler: EventHandler = Arc::new(handler);
self.command(move |core, outbox, resolver| {
let previous = core.event_handler.replace(handler);
outbox.push(move || drop(previous));
outbox.resolve(resolver, Ok(()));
})
}
pub fn clear_event_handler(&self) -> Result<Completion<()>, Error> {
self.command(move |core, outbox, resolver| {
let previous = core.event_handler.take();
outbox.push(move || drop(previous));
outbox.resolve(resolver, Ok(()));
})
}
pub fn set_resource_provider(&self, provider: impl ResourceProvider) -> Result<Completion<()>, Error> {
self.replace_provider(Some(Box::new(provider)))
}
pub fn clear_resource_provider(&self) -> Result<Completion<()>, Error> {
self.replace_provider(None)
}
fn replace_provider(&self, provider: Option<Box<dyn ResourceProvider>>) -> Result<Completion<()>, Error> {
self.command(move |core, outbox, resolver| {
let previous = core.hooks.set_provider(provider);
outbox.push(move || drop(previous));
outbox.resolve(resolver, Ok(()));
})
}
pub fn set_resource_transform(
&self,
transform: impl Fn(Kind, &str, FinishedCallback) + Send + Sync + 'static,
) -> Result<Completion<()>, Error> {
let transform = ResourceTransform::new(Some(Arc::new(transform)));
self.apply(move |core| {
core.network()?.set_resource_transform(transform);
core.hooks.set_transform_set(true);
Ok(())
})
}
pub fn clear_resource_transform(&self) -> Result<Completion<()>, Error> {
self.apply(move |core| {
core.network()?.set_resource_transform(ResourceTransform::default());
core.hooks.set_transform_set(false);
Ok(())
})
}
pub fn set_http_header_transform(
&self,
transform: impl Fn(Kind, &str) -> HttpHeaders + Send + Sync + 'static,
) -> Result<Completion<()>, Error> {
if cfg!(target_family = "wasm") {
return Err(Error::unsupported("the browser sends the requests and sets their headers"));
}
let transform = HttpHeaderTransform::new(Some(Arc::new(move |kind: Kind, url: &str| {
crate::resources::sanitize_headers(transform(kind, url))
})));
self.apply(move |core| {
core.network()?.set_http_header_transform(transform);
Ok(())
})
}
pub fn clear_http_header_transform(&self) -> Result<Completion<()>, Error> {
self.apply(move |core| {
core.network()?.set_http_header_transform(HttpHeaderTransform::default());
Ok(())
})
}
pub fn run_cache_database_operation(&self, operation: CacheDatabaseOperation) -> Result<Completion<()>, Error> {
self.command(move |core, outbox, resolver| {
let database = match core.database() {
Ok(database) => database,
Err(error) => return outbox.resolve(resolver, Err(error)),
};
let reply = reply_on(core.run_loop.clone(), resolver);
match operation {
CacheDatabaseOperation::Clear => database.clear_ambient_cache(reply),
CacheDatabaseOperation::Invalidate => database.invalidate_ambient_cache(reply),
CacheDatabaseOperation::Pack => database.pack_database(reply),
CacheDatabaseOperation::Reset => database.reset_database(reply),
}
})
}
pub fn set_maximum_ambient_cache_size(&self, size: u64) -> Result<Completion<()>, Error> {
self.command(move |core, outbox, resolver| match core.database() {
Ok(database) => database.set_maximum_ambient_cache_size(size, reply_on(core.run_loop.clone(), resolver)),
Err(error) => outbox.resolve(resolver, Err(error)),
})
}
#[must_use]
pub fn offline(&self) -> Offline<'_> {
Offline::new(self)
}
pub fn release(&self) -> Result<Completion<()>, Error> {
{
let mut lifecycle = self.shared.lifecycle.lock_unpoisoned();
if lifecycle.released {
return Err(released());
}
if lifecycle.live_maps > 0 {
return Err(Error::invalid_state("release the runtime's maps first"));
}
lifecycle.released = true;
lifecycle.shut_down = true;
}
let (completion, resolver) = self.shared.completion();
self.shared.shut_down(Some(resolver));
Ok(completion)
}
pub fn dispose(&self) -> Result<(), Error> {
let shut_down = {
let mut lifecycle = self.shared.lifecycle.lock_unpoisoned();
if lifecycle.released {
return Err(released());
}
lifecycle.released = true;
let shut_down = lifecycle.live_maps == 0;
lifecycle.shut_down |= shut_down;
shut_down
};
if shut_down {
self.shared.shut_down(None);
}
Ok(())
}
pub(crate) fn offline_command<T: Send + 'static>(
&self,
command: impl FnOnce(&DatabaseFileSource, &RuntimeCore, Resolver<T>) + Send + 'static,
) -> Result<Completion<T>, Error> {
self.command(move |core, outbox, resolver| match core.database() {
Ok(database) => command(database, core, resolver),
Err(error) => outbox.resolve(resolver, Err(error)),
})
}
}
const _: () = {
const fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<Runtime>();
assert_send_sync::<Map>();
};