1use std::cell::RefCell;
5use std::collections::BTreeMap;
6use std::path::{Path, PathBuf};
7use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
8use std::sync::{Arc, Mutex, mpsc};
9use std::thread::ThreadId;
10
11use mln_actor::{RunLoop, RunLoopHandle};
12use mln_storage::http_header_transform::{HttpHeaderTransform, HttpHeaders};
13use mln_storage::resource::Kind;
14use mln_storage::resource_transform::{FinishedCallback, ResourceTransform};
15use mln_storage::{DatabaseFileSource, FileSource, FileSourceManager, FileSourceType, ResourceOptions};
16use mln_text::GlyphCache;
17use mln_util::error::Error;
18use mln_util::sync::MutexExt;
19
20use crate::completion::{Completion, Resolver};
21use crate::event::{EventHandler, RuntimeEvent};
22use crate::map::{Applied, Map, MapEntry, MapId, MapOptions, MapShared, Published};
23use crate::offline::Offline;
24use crate::resources::{CacheDatabaseOperation, ProviderFileSource, ResourceHooks, ResourceProvider};
25
26#[derive(Clone, Debug, Default, PartialEq, Eq)]
28pub struct RuntimeOptions {
29 pub asset_path: Option<PathBuf>,
33 pub cache_path: Option<PathBuf>,
37}
38
39#[derive(Clone)]
52pub struct Runtime {
53 pub(crate) shared: Arc<RuntimeShared>,
54}
55
56impl std::fmt::Debug for Runtime {
57 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58 f.debug_struct("Runtime").field("thread", &self.shared.thread).finish()
59 }
60}
61
62struct Lifecycle {
63 released: bool,
64 live_maps: usize,
65 shut_down: bool,
66}
67
68pub(crate) struct RuntimeShared {
69 run_loop: RunLoopHandle,
70 queued: Arc<AtomicUsize>,
72 thread: ThreadId,
73 lifecycle: Mutex<Lifecycle>,
74 next_map_id: AtomicU64,
75 pub(crate) glyph_cache: Arc<GlyphCache>,
78}
79
80impl RuntimeShared {
81 pub(crate) fn post(&self, task: impl FnOnce(&mut RuntimeCore, &mut Outbox) + Send + 'static) {
84 self.queued.fetch_add(1, Ordering::SeqCst);
85 self.run_loop.invoke(move || run(task, true));
86 }
87
88 pub(crate) fn post_or<V: Send + 'static>(
93 &self,
94 value: V,
95 task: impl FnOnce(&mut RuntimeCore, &mut Outbox, V) + Send + 'static,
96 instead: impl FnOnce(V),
97 ) {
98 let lifecycle = self.lifecycle.lock_unpoisoned();
100 if lifecycle.shut_down {
101 drop(lifecycle);
102 instead(value);
103 } else {
104 self.post(move |core, outbox| task(core, outbox, value));
105 }
106 }
107
108 pub(crate) fn thread(&self) -> ThreadId {
109 self.thread
110 }
111
112 pub(crate) fn completion<T: Send + 'static>(&self) -> (Completion<T>, Resolver<T>) {
114 Completion::new(Some(self.thread))
115 }
116
117 fn check_live(&self) -> Result<(), Error> {
118 if self.lifecycle.lock_unpoisoned().released { Err(released()) } else { Ok(()) }
119 }
120
121 pub(crate) fn map_released(&self) {
124 let shut_down = {
125 let mut lifecycle = self.lifecycle.lock_unpoisoned();
126 lifecycle.live_maps -= 1;
127 let shut_down = lifecycle.released && lifecycle.live_maps == 0 && !lifecycle.shut_down;
128 lifecycle.shut_down |= shut_down;
129 shut_down
130 };
131 if shut_down {
132 self.shut_down(None);
133 }
134 }
135
136 fn shut_down(&self, done: Option<Resolver<()>>) {
138 let run_loop = self.run_loop.clone();
139 self.run_loop.invoke(move || {
140 let core = CORE.with(|core| core.borrow_mut().take());
141 drop(core);
142 if let Some(done) = done {
143 done.resolve(Ok(()));
144 }
145 run_loop.stop();
146 });
147 }
148}
149
150impl Drop for RuntimeShared {
151 fn drop(&mut self) {
152 if !self.lifecycle.get_mut_unpoisoned().shut_down {
153 self.shut_down(None);
154 }
155 }
156}
157
158fn released() -> Error {
159 Error::invalid_state("the runtime was released")
160}
161
162thread_local! {
163 static CORE: RefCell<Option<RuntimeCore>> = const { RefCell::new(None) };
165}
166
167pub(crate) fn post(run_loop: &RunLoopHandle, task: impl FnOnce(&mut RuntimeCore, &mut Outbox) + Send + 'static) {
169 run_loop.invoke(move || run(task, false));
170}
171
172fn run(task: impl FnOnce(&mut RuntimeCore, &mut Outbox), in_burst: bool) {
177 let mut outbox = Outbox::default();
178 let unrun = CORE.with(|core| match core.borrow_mut().as_mut() {
179 Some(core) => {
180 if in_burst {
181 core.begin_burst_task();
182 }
183 task(core, &mut outbox);
184 if in_burst {
185 core.end_burst_task(&mut outbox);
186 }
187 None
188 }
189 None => Some(task),
190 });
191 drop(unrun);
192 outbox.deliver();
193}
194
195#[derive(Default)]
199pub(crate) struct Outbox {
200 deliveries: Vec<Box<dyn FnOnce()>>,
201}
202
203impl Outbox {
204 pub(crate) fn push(&mut self, delivery: impl FnOnce() + 'static) {
205 self.deliveries.push(Box::new(delivery));
206 }
207
208 pub(crate) fn resolve<T: 'static>(&mut self, resolver: Resolver<T>, result: Result<T, Error>) {
209 self.push(move || resolver.resolve(result));
210 }
211
212 pub(crate) fn deliver(self) {
213 for delivery in self.deliveries {
214 delivery();
215 }
216 }
217}
218
219pub(crate) struct RuntimeCore {
221 pub(crate) maps: BTreeMap<MapId, MapEntry>,
223 pub(crate) event_handler: Option<EventHandler>,
224 hooks: Arc<ResourceHooks>,
225 file_sources: FileSourceManager,
226 resource_options: ResourceOptions,
227 _loader: Option<Arc<dyn FileSource>>,
230 database: Option<Arc<dyn FileSource>>,
231 network: Option<Arc<dyn FileSource>>,
232 pub(crate) run_loop: RunLoopHandle,
233 queued: Arc<AtomicUsize>,
235 burst_left: usize,
237 holding: bool,
239}
240
241impl RuntimeCore {
242 fn new(resource_options: ResourceOptions, run_loop: RunLoopHandle, queued: Arc<AtomicUsize>) -> Self {
243 let hooks = Arc::new(ResourceHooks::default());
244 let file_sources = FileSourceManager::new();
245 let network_hooks = hooks.clone();
246 file_sources.register_file_source_factory(
247 FileSourceType::Network,
248 Arc::new(move |_: &FileSourceManager, options: &ResourceOptions| {
249 Arc::new(ProviderFileSource::new(options, network_hooks.clone())) as Arc<dyn FileSource>
250 }),
251 );
252 let network = file_sources.get_file_source(FileSourceType::Network, &resource_options);
253 let database = file_sources.get_file_source(FileSourceType::Database, &resource_options);
254 let loader = file_sources.get_file_source(FileSourceType::ResourceLoader, &resource_options);
255 RuntimeCore {
256 maps: BTreeMap::new(),
257 event_handler: None,
258 hooks,
259 file_sources,
260 resource_options,
261 _loader: loader,
262 database,
263 network,
264 run_loop,
265 queued,
266 burst_left: 0,
267 holding: false,
268 }
269 }
270
271 fn begin_burst_task(&mut self) {
278 let queued = self.queued.fetch_sub(1, Ordering::SeqCst);
279 if self.burst_left == 0 {
280 self.burst_left = queued;
281 self.holding = queued > 1;
282 if self.holding {
283 self.maps.values_mut().for_each(|entry| entry.core.hold_updates());
284 }
285 }
286 }
287
288 fn end_burst_task(&mut self, outbox: &mut Outbox) {
291 self.burst_left = self.burst_left.saturating_sub(1);
292 if self.burst_left > 0 || !std::mem::take(&mut self.holding) {
293 return;
294 }
295 let ids: Vec<MapId> = self.maps.keys().copied().collect();
296 for id in ids {
297 if let Some(entry) = self.maps.get_mut(&id) {
298 entry.core.release_updates();
299 }
300 crate::map::flush(self, id, outbox);
301 }
302 }
303
304 pub(crate) fn file_sources(&self) -> (&FileSourceManager, &ResourceOptions) {
305 (&self.file_sources, &self.resource_options)
306 }
307
308 pub(crate) fn send_events(&self, events: Vec<RuntimeEvent>, outbox: &mut Outbox) {
310 if events.is_empty() {
311 return;
312 }
313 if let Some(handler) = self.event_handler.clone() {
314 outbox.push(move || handler(&events));
315 }
316 }
317
318 pub(crate) fn database(&self) -> Result<&DatabaseFileSource, Error> {
320 self.database
321 .as_ref()
322 .and_then(|database| database.as_any())
323 .and_then(|database| database.downcast_ref::<DatabaseFileSource>())
324 .ok_or_else(|| Error::unsupported("the runtime has no cache database"))
325 }
326
327 fn network(&self) -> Result<&Arc<dyn FileSource>, Error> {
328 self.network.as_ref().ok_or_else(|| Error::unsupported("the runtime has no network file source"))
329 }
330}
331
332pub(crate) fn reply_on<T: Send + 'static, E: Into<Error>>(
335 run_loop: RunLoopHandle,
336 resolver: Resolver<T>,
337) -> impl FnOnce(Result<T, E>) + Send + 'static {
338 move |result| {
339 let result = result.map_err(Into::into);
340 post(&run_loop, move |_, outbox| outbox.resolve(resolver, result));
341 }
342}
343
344fn resource_options(options: &RuntimeOptions) -> Result<ResourceOptions, Error> {
347 let mut resource_options = ResourceOptions::default();
348 if let Some(asset_path) = &options.asset_path {
349 resource_options = resource_options.with_asset_path(utf8(asset_path, "asset path")?);
350 }
351 #[cfg(target_os = "android")]
352 if options.asset_path.is_none() {
353 resource_options = resource_options.with_asset_path(mln_storage::android::APP_ASSETS);
354 }
355 if let Some(cache_path) = &options.cache_path {
356 let path = utf8(cache_path, "cache path")?;
357 std::fs::OpenOptions::new()
358 .read(true)
359 .write(true)
360 .create(true)
361 .truncate(false)
362 .open(cache_path)
363 .map_err(|error| Error::invalid_argument(format!("can't open the cache database {path}: {error}")))?;
364 resource_options = resource_options.with_cache_path(path);
365 }
366 Ok(resource_options)
367}
368
369fn utf8<'a>(path: &'a Path, what: &str) -> Result<&'a str, Error> {
370 path.to_str().ok_or_else(|| Error::invalid_argument(format!("the {what} {} isn't UTF-8", path.display())))
371}
372
373impl Runtime {
374 pub fn new(options: &RuntimeOptions) -> Result<Runtime, Error> {
379 let resource_options = resource_options(options)?;
380 let (started, start) = mpsc::channel();
381 let queued = Arc::new(AtomicUsize::new(0));
382 let core_queued = Arc::clone(&queued);
383 let thread = mln_util::thread::builder("Runtime")
384 .spawn(move || {
385 let run_loop = RunLoop::new();
386 let core = RuntimeCore::new(resource_options, run_loop.handle(), core_queued);
387 CORE.with(|cell| *cell.borrow_mut() = Some(core));
388 let _ = started.send(run_loop.handle());
389 run_loop.run();
390 let core = CORE.with(|cell| cell.borrow_mut().take());
391 drop(core);
392 })
393 .map_err(|error| Error::native(format!("can't start the runtime's thread: {error}")))?;
394 let thread_id = thread.thread().id();
395 drop(thread);
398 let run_loop = start.recv().map_err(|_| Error::native("the runtime's thread stopped as it started"))?;
399 Ok(Runtime {
400 shared: Arc::new(RuntimeShared {
401 run_loop,
402 queued,
403 thread: thread_id,
404 lifecycle: Mutex::new(Lifecycle { released: false, live_maps: 0, shut_down: false }),
405 next_map_id: AtomicU64::new(1),
406 glyph_cache: Arc::default(),
407 }),
408 })
409 }
410
411 fn command<T: Send + 'static>(
413 &self,
414 command: impl FnOnce(&mut RuntimeCore, &mut Outbox, Resolver<T>) + Send + 'static,
415 ) -> Result<Completion<T>, Error> {
416 self.shared.check_live()?;
417 let (completion, resolver) = self.shared.completion();
418 self.shared.post(move |core, outbox| command(core, outbox, resolver));
419 Ok(completion)
420 }
421
422 fn apply<T: Send + 'static>(
424 &self,
425 apply: impl FnOnce(&mut RuntimeCore) -> Result<T, Error> + Send + 'static,
426 ) -> Result<Completion<T>, Error> {
427 self.command(move |core, outbox, resolver| {
428 let result = apply(core);
429 outbox.resolve(resolver, result);
430 })
431 }
432
433 pub fn create_map(&self, options: MapOptions) -> Result<(Map, Completion<Applied>), Error> {
443 let size = options.map.size();
444 let pixel_ratio = options.map.pixel_ratio();
445 if size.is_empty() {
446 return Err(Error::invalid_argument("the map's size must not be empty"));
447 }
448 if !pixel_ratio.is_finite() || pixel_ratio <= 0.0 {
449 return Err(Error::invalid_argument("the map's pixel ratio must be finite and positive"));
450 }
451 {
452 let mut lifecycle = self.shared.lifecycle.lock_unpoisoned();
453 if lifecycle.released {
454 return Err(released());
455 }
456 lifecycle.live_maps += 1;
457 }
458 let id = MapId(self.shared.next_map_id.fetch_add(1, Ordering::Relaxed));
459 let published = Arc::new(Published::new(options.event_mask));
460 let map = Map::new(MapShared::new(id, self.shared.clone(), &options, published.clone()));
461 let (completion, resolver) = self.shared.completion();
462 self.shared.post(move |core, outbox| crate::map::create(core, id, &options, published, resolver, outbox));
463 Ok((map, completion))
464 }
465
466 pub fn set_event_handler(
469 &self,
470 handler: impl Fn(&[RuntimeEvent]) + Send + Sync + 'static,
471 ) -> Result<Completion<()>, Error> {
472 let handler: EventHandler = Arc::new(handler);
473 self.command(move |core, outbox, resolver| {
474 let previous = core.event_handler.replace(handler);
475 outbox.push(move || drop(previous));
476 outbox.resolve(resolver, Ok(()));
477 })
478 }
479
480 pub fn clear_event_handler(&self) -> Result<Completion<()>, Error> {
482 self.command(move |core, outbox, resolver| {
483 let previous = core.event_handler.take();
484 outbox.push(move || drop(previous));
485 outbox.resolve(resolver, Ok(()));
486 })
487 }
488
489 pub fn set_resource_provider(&self, provider: impl ResourceProvider) -> Result<Completion<()>, Error> {
492 self.replace_provider(Some(Box::new(provider)))
493 }
494
495 pub fn clear_resource_provider(&self) -> Result<Completion<()>, Error> {
498 self.replace_provider(None)
499 }
500
501 fn replace_provider(&self, provider: Option<Box<dyn ResourceProvider>>) -> Result<Completion<()>, Error> {
502 self.command(move |core, outbox, resolver| {
503 let previous = core.hooks.set_provider(provider);
504 outbox.push(move || drop(previous));
505 outbox.resolve(resolver, Ok(()));
506 })
507 }
508
509 pub fn set_resource_transform(
514 &self,
515 transform: impl Fn(Kind, &str, FinishedCallback) + Send + Sync + 'static,
516 ) -> Result<Completion<()>, Error> {
517 let transform = ResourceTransform::new(Some(Arc::new(transform)));
518 self.apply(move |core| {
519 core.network()?.set_resource_transform(transform);
520 core.hooks.set_transform_set(true);
521 Ok(())
522 })
523 }
524
525 pub fn clear_resource_transform(&self) -> Result<Completion<()>, Error> {
527 self.apply(move |core| {
528 core.network()?.set_resource_transform(ResourceTransform::default());
529 core.hooks.set_transform_set(false);
530 Ok(())
531 })
532 }
533
534 pub fn set_http_header_transform(
544 &self,
545 transform: impl Fn(Kind, &str) -> HttpHeaders + Send + Sync + 'static,
546 ) -> Result<Completion<()>, Error> {
547 if cfg!(target_family = "wasm") {
548 return Err(Error::unsupported("the browser sends the requests and sets their headers"));
549 }
550 let transform = HttpHeaderTransform::new(Some(Arc::new(move |kind: Kind, url: &str| {
551 crate::resources::sanitize_headers(transform(kind, url))
552 })));
553 self.apply(move |core| {
554 core.network()?.set_http_header_transform(transform);
555 Ok(())
556 })
557 }
558
559 pub fn clear_http_header_transform(&self) -> Result<Completion<()>, Error> {
561 self.apply(move |core| {
562 core.network()?.set_http_header_transform(HttpHeaderTransform::default());
563 Ok(())
564 })
565 }
566
567 pub fn run_cache_database_operation(&self, operation: CacheDatabaseOperation) -> Result<Completion<()>, Error> {
569 self.command(move |core, outbox, resolver| {
570 let database = match core.database() {
571 Ok(database) => database,
572 Err(error) => return outbox.resolve(resolver, Err(error)),
573 };
574 let reply = reply_on(core.run_loop.clone(), resolver);
575 match operation {
576 CacheDatabaseOperation::Clear => database.clear_ambient_cache(reply),
577 CacheDatabaseOperation::Invalidate => database.invalidate_ambient_cache(reply),
578 CacheDatabaseOperation::Pack => database.pack_database(reply),
579 CacheDatabaseOperation::Reset => database.reset_database(reply),
580 }
581 })
582 }
583
584 pub fn set_maximum_ambient_cache_size(&self, size: u64) -> Result<Completion<()>, Error> {
587 self.command(move |core, outbox, resolver| match core.database() {
588 Ok(database) => database.set_maximum_ambient_cache_size(size, reply_on(core.run_loop.clone(), resolver)),
589 Err(error) => outbox.resolve(resolver, Err(error)),
590 })
591 }
592
593 #[must_use]
595 pub fn offline(&self) -> Offline<'_> {
596 Offline::new(self)
597 }
598
599 pub fn release(&self) -> Result<Completion<()>, Error> {
606 {
607 let mut lifecycle = self.shared.lifecycle.lock_unpoisoned();
608 if lifecycle.released {
609 return Err(released());
610 }
611 if lifecycle.live_maps > 0 {
612 return Err(Error::invalid_state("release the runtime's maps first"));
613 }
614 lifecycle.released = true;
615 lifecycle.shut_down = true;
616 }
617 let (completion, resolver) = self.shared.completion();
618 self.shared.shut_down(Some(resolver));
619 Ok(completion)
620 }
621
622 pub fn dispose(&self) -> Result<(), Error> {
626 let shut_down = {
627 let mut lifecycle = self.shared.lifecycle.lock_unpoisoned();
628 if lifecycle.released {
629 return Err(released());
630 }
631 lifecycle.released = true;
632 let shut_down = lifecycle.live_maps == 0;
633 lifecycle.shut_down |= shut_down;
634 shut_down
635 };
636 if shut_down {
637 self.shared.shut_down(None);
638 }
639 Ok(())
640 }
641
642 pub(crate) fn offline_command<T: Send + 'static>(
644 &self,
645 command: impl FnOnce(&DatabaseFileSource, &RuntimeCore, Resolver<T>) + Send + 'static,
646 ) -> Result<Completion<T>, Error> {
647 self.command(move |core, outbox, resolver| match core.database() {
648 Ok(database) => command(database, core, resolver),
649 Err(error) => outbox.resolve(resolver, Err(error)),
650 })
651 }
652}
653
654const _: () = {
656 const fn assert_send_sync<T: Send + Sync>() {}
657 assert_send_sync::<Runtime>();
658 assert_send_sync::<Map>();
659};