use crate::color::Color;
use crate::event::{Cursor, Event, Key};
use crate::geom::{Rect, Size, pt};
use crate::platform::{Clipboard, Window};
use crate::preferences::Preferences;
use crate::surface::Surface;
use crate::theme::ContrastColors;
use crate::ui::Ui;
use crate::web_input::{Did, Pointer};
use crate::web_mirror::Mirror;
use std::cell::RefCell;
use std::path::PathBuf;
use std::time::Duration;
#[link(wasm_import_module = "taut")]
unsafe extern "C" {
fn present(pixels: *const u8, x: u32, y: u32, width: u32, height: u32);
fn wake(after_ms: f64);
fn set_cursor(shape: u32);
fn set_title(text: *const u8, length: usize);
fn text_field(x: f32, y: f32, width: f32, height: f32, on: u32);
fn clipboard_set(text: *const u8, length: usize);
fn mirror(json: *const u8, length: usize);
fn log(text: *const u8, length: usize);
fn now() -> f64;
fn clock() -> f64;
fn zone() -> f64;
fn storage_get(key: *const u8, length: usize) -> i32;
fn storage_set(key: *const u8, key_length: usize, value: *const u8, value_length: usize) -> u32;
fn open_link(link: *const u8, length: usize);
fn ask_file(accept: *const u8, length: usize, saving: u32);
fn download(name: *const u8, name_length: usize, bytes: *const u8, length: usize);
fn font_file(nth: u32, face: *mut u32) -> usize;
fn take(into: *mut u8);
pub(crate) fn text_metrics(font: *const u8, length: usize, sizes: *mut f32);
pub(crate) fn text_measure(font: *const u8, length: usize, text: *const u8, text_length: usize, stops: *mut f32, count: usize) -> f32;
pub(crate) fn text_draw(font: *const u8, length: usize, text: *const u8, text_length: usize, place: *mut f32) -> usize;
}
pub(crate) fn took(length: usize) -> Vec<u8> {
let mut bytes = vec![0u8; length];
unsafe { take(bytes.as_mut_ptr()) };
bytes
}
pub(crate) fn say(text: &str) {
unsafe { log(text.as_ptr(), text.len()) };
}
pub(crate) fn unix_ms() -> f64 {
unsafe { clock() }
}
pub(crate) fn unix_seconds() -> u64 {
(unix_ms() / 1000.0).max(0.0) as u64
}
pub(crate) fn zone_ahead() -> i64 {
(unsafe { zone() } * 60.0) as i64
}
pub(crate) fn stored(key: &str) -> Option<String> {
let length = unsafe { storage_get(key.as_ptr(), key.len()) };
let length = usize::try_from(length).ok()?;
String::from_utf8(took(length)).ok()
}
pub(crate) fn store(key: &str, value: &str) -> bool {
unsafe { storage_set(key.as_ptr(), key.len(), value.as_ptr(), value.len()) != 0 }
}
pub(crate) fn open(link: &str) {
unsafe { open_link(link.as_ptr(), link.len()) };
}
pub(crate) fn save_as(name: &str, bytes: &[u8]) {
unsafe { download(name.as_ptr(), name.len(), bytes.as_ptr(), bytes.len()) };
}
fn page_fonts() -> Vec<(u32, Vec<u8>)> {
let mut fonts = Vec::new();
for nth in 0..4 {
let mut face = 0;
let length = unsafe { font_file(nth, &mut face) };
if length > 0 {
fonts.push((face, took(length)));
}
}
fonts
}
pub(crate) fn system_text() -> Box<dyn crate::text::TextSystem> {
let mut files = page_fonts().into_iter().filter_map(|(face, bytes)| crate::font_file::FontFile::read(bytes).map(|file| (face, file)));
let browser = Box::new(crate::web_text::SystemText::default());
let Some((_, regular)) = files.next() else { return browser };
let mut fonts = crate::font_file::AppFonts::new(regular);
for (face, file) in files {
fonts = match face {
1 => fonts.bold(file),
2 => fonts.mono(file),
_ => fonts.italic(file),
};
}
Box::new(fonts.fallback(browser))
}
struct PageClipboard;
impl Clipboard for PageClipboard {
fn get(&mut self) -> Option<String> {
CLIPBOARD.with_borrow(|text| (!text.is_empty()).then(|| text.clone()))
}
fn set(&mut self, text: &str) {
CLIPBOARD.set(text.into());
unsafe { clipboard_set(text.as_ptr(), text.len()) };
}
}
thread_local! {
static HOST: RefCell<Option<Host>> = const { RefCell::new(None) };
static CLIPBOARD: RefCell<String> = const { RefCell::new(String::new()) };
static PICKED: RefCell<Vec<(PathBuf, Vec<u8>)>> = const { RefCell::new(Vec::new()) };
}
pub(crate) fn picked(path: &std::path::Path) -> Option<Vec<u8>> {
PICKED.with_borrow(|picked| picked.iter().find(|(name, _)| name == path).map(|(_, bytes)| bytes.clone()))
}
struct Host {
app: Box<dyn FnMut(&mut Ui)>,
ui: Ui,
surface: Surface,
rgba: Vec<u8>,
size: Size,
scale: f32,
rerun: bool,
drawn: bool,
started: f64,
mirror: Mirror,
told: u64,
cursor: Cursor,
ime: Option<Rect>,
title: String,
told_windows: bool,
}
impl Host {
fn tick(&mut self) {
let ms = (unsafe { now() } - self.started).max(0.0);
self.ui.set_time(Duration::from_secs_f64(ms / 1000.0));
self.rerun |= self.ui.wake_in() == Some(Duration::ZERO);
}
fn describe(&mut self) {
self.tick();
if !self.rerun || self.size.w <= 0.0 {
return;
}
self.ui.resize(self.size, self.scale);
self.ui.run(&mut self.app);
let _ = self.ui.take_closing();
(self.rerun, self.drawn) = (false, false);
if !self.told_windows && self.ui.windows().next().is_some() {
say("taut: a page shows one window; second windows are not shown on the web");
self.told_windows = true;
}
self.follow();
let (version, announced) = (self.ui.access_version(), self.ui.announced());
if version == self.told && announced.is_empty() {
return;
}
self.told = version;
if let Some(json) = self.mirror.update(self.ui.access_nodes(), announced) {
unsafe { mirror(json.as_ptr(), json.len()) };
}
}
fn follow(&mut self) {
if let Some(title) = self.ui.take_title().filter(|title| *title != self.title) {
unsafe { set_title(title.as_ptr(), title.len()) };
self.title = title;
}
if std::mem::replace(&mut self.cursor, self.ui.cursor()) != self.cursor {
unsafe { set_cursor(self.cursor as u32) };
}
let ime = self.ui.ime_area();
if ime != self.ime || ime.is_some() {
let place = ime.unwrap_or_default();
unsafe { text_field(place.x, place.y, place.w, place.h, ime.is_some() as u32 + self.ui.password_focused() as u32) };
}
self.ime = ime;
if let Some(asked) = self.ui.take_file_dialog_request() {
let accept = asked.endings.join(",");
unsafe { ask_file(accept.as_ptr(), accept.len(), asked.saving as u32) };
if asked.saving {
self.ui.file_dialog_answered(Some(PathBuf::from("/downloads").join(asked.name)));
self.rerun = true;
}
}
}
fn draw(&mut self) {
if self.drawn {
return;
}
self.drawn = true;
for [left, top, right, bottom] in self.surface.update(&mut self.ui) {
let (width, height) = (right - left, bottom - top);
self.rgba.clear();
for row in top..bottom {
let from = row * self.surface.width;
self.rgba.extend(self.surface.pixels[from + left..from + right].iter().flat_map(|pixel| straight(*pixel)));
}
unsafe { present(self.rgba.as_ptr(), left as u32, top as u32, width as u32, height as u32) };
}
let _ = self.ui.changed();
}
fn schedule(&self) {
let after = match (self.rerun || !self.drawn, self.ui.wake_in()) {
_ if self.size.w <= 0.0 => -1.0,
(true, _) => 0.0,
(false, Some(wait)) => wait.as_secs_f64() * 1000.0,
(false, None) => -1.0,
};
unsafe { wake(after) };
}
fn hear(&mut self, event: Event) {
self.rerun |= self.ui.event(event);
}
}
fn straight(pixel: u32) -> [u8; 4] {
let alpha = pixel >> 24;
let [blue, green, red, _] = pixel.to_le_bytes();
if alpha == 255 || alpha == 0 {
return [red, green, blue, alpha as u8];
}
let part = |channel: u8| ((u32::from(channel) * 255 + alpha / 2) / alpha).min(255) as u8;
[part(red), part(green), part(blue), alpha as u8]
}
fn with_host(work: impl FnOnce(&mut Host)) {
HOST.with(|host| {
let Ok(mut host) = host.try_borrow_mut() else { return };
if let Some(host) = host.as_mut() {
work(host);
}
});
}
fn now_and_later(host: &mut Host) {
host.describe();
host.schedule();
}
pub fn run(window: Window, app: impl FnMut(&mut Ui) + 'static) {
std::panic::set_hook(Box::new(|told| say(&format!("taut: {told}"))));
let mut ui = Ui::new(system_text(), Box::new(PageClipboard));
if window.transparent {
ui.theme.bg = Color::NONE;
}
ui.set_screen_reader(true);
ui.set_native_file_dialog(true);
let started = unsafe { now() };
unsafe { set_title(window.title.as_ptr(), window.title.len()) };
let host = Host {
app: Box::new(app),
ui,
surface: Surface::default(),
rgba: Vec::new(),
size: Size { w: 0.0, h: 0.0 },
scale: 1.0,
rerun: true,
drawn: false,
started,
mirror: Mirror::default(),
told: 0,
cursor: Cursor::Arrow,
ime: None,
title: window.title.into(),
told_windows: false,
};
HOST.set(Some(host));
unsafe { wake(0.0) };
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Waker;
impl Waker {
pub fn wake(&self) {
with_host(|host| {
host.rerun = true;
host.schedule();
});
}
}
#[unsafe(no_mangle)]
pub extern "C" fn taut_alloc(length: usize) -> *mut u8 {
let mut room = std::mem::ManuallyDrop::new(Vec::<u8>::with_capacity(length.max(1)));
room.as_mut_ptr()
}
fn given(at: *mut u8, length: usize) -> Vec<u8> {
unsafe { Vec::from_raw_parts(at, length, length.max(1)) }
}
fn given_text(at: *mut u8, length: usize) -> String {
String::from_utf8(given(at, length)).unwrap_or_default()
}
#[unsafe(no_mangle)]
pub extern "C" fn taut_size(width: f32, height: f32, scale: f32) {
with_host(|host| {
if width <= 0.0 {
host.surface = Surface::default();
}
(host.size, host.scale, host.rerun) = (Size { w: width.max(0.0), h: height.max(0.0) }, scale.max(0.25), true);
host.schedule();
});
}
#[unsafe(no_mangle)]
pub extern "C" fn taut_frame() {
with_host(|host| {
host.describe();
host.draw();
host.schedule();
});
}
#[unsafe(no_mangle)]
pub extern "C" fn taut_looks(dark: u32, contrast: u32, still: u32, accent: i32) {
let dark = dark != 0;
let high_contrast = (contrast != 0).then_some(if dark { ContrastColors::DARK } else { ContrastColors::LIGHT });
let accent = u32::try_from(accent).ok().map(Color::rgb);
let preferences = Preferences { dark, accent, high_contrast, reduced_motion: still != 0, ..Preferences::default() };
with_host(|host| {
host.rerun |= host.ui.set_preferences(preferences);
host.schedule();
});
}
#[unsafe(no_mangle)]
#[allow(clippy::too_many_arguments)]
pub extern "C" fn taut_pointer(did: u32, kind: u32, id: u32, primary: u32, x: f32, y: f32, button: i32, buttons: u32, pressure: f32, tilt_x: f32, tilt_y: f32, twist: f32, mods: u32) {
let did = Did::of(did);
let event = Pointer { did, kind, id, primary: primary != 0, at: pt(x, y), button, buttons, pressure, tilt: [tilt_x, tilt_y], twist, mods: crate::web_input::mods(mods) };
with_host(|host| {
crate::web_input::pointer(event, cfg!(feature = "touch")).into_iter().for_each(|event| host.hear(event));
match did {
Did::Down | Did::Up => now_and_later(host),
_ => host.schedule(),
}
});
}
#[unsafe(no_mangle)]
pub extern "C" fn taut_wheel(x: f32, y: f32, dx: f32, dy: f32, delta_mode: u32, mods: u32) {
with_host(|host| {
let (right, down) = crate::web_input::wheel(dx, dy, delta_mode, [host.size.w, host.size.h]);
host.hear(Event::Move(pt(x, y)));
let zoom = mods & crate::web_input::CTRL != 0;
host.hear(if zoom { Event::Zoom(crate::touch::wheel_zoom(-down / crate::web_input::NOTCH)) } else { Event::Wheel(right, down) });
host.schedule();
});
}
#[unsafe(no_mangle)]
pub extern "C" fn taut_key(down: u32, key: *mut u8, key_length: usize, code: *mut u8, code_length: usize, mods: u32, field: u32) -> u32 {
let (name, code) = (given_text(key, key_length), given_text(code, code_length));
let held = crate::web_input::mods(mods);
let key = crate::web_input::key(&name, &code, held);
let mut stops = false;
with_host(|host| {
host.hear(Event::ModifiersChanged(held));
let Some(key) = key else { return };
if down == 0 {
host.hear(Event::KeyUp(key));
return host.schedule();
}
host.hear(Event::Key(key, held));
if let Some(text) = crate::web_input::typed(&name, held).filter(|_| field == 0) {
host.hear(Event::Text(text.into()));
}
stops = crate::web_input::stops(Some(key), held);
now_and_later(host);
});
stops as u32
}
#[unsafe(no_mangle)]
pub extern "C" fn taut_text(text: *mut u8, length: usize) {
let text = given_text(text, length);
with_host(|host| {
if !text.is_empty() {
host.hear(Event::Text(text));
}
now_and_later(host);
});
}
#[unsafe(no_mangle)]
pub extern "C" fn taut_paste(text: *mut u8, length: usize) {
CLIPBOARD.set(given_text(text, length));
with_host(|host| {
host.hear(Event::Key(Key::Char('v'), crate::event::Mods::CTRL));
now_and_later(host);
});
}
#[unsafe(no_mangle)]
pub extern "C" fn taut_clipboard(text: *mut u8, length: usize) {
CLIPBOARD.set(given_text(text, length));
}
#[unsafe(no_mangle)]
pub extern "C" fn taut_focus(on: u32) {
with_host(|host| {
host.hear(Event::Focused(on != 0));
host.schedule();
});
}
#[unsafe(no_mangle)]
pub extern "C" fn taut_reader(key: *mut u8, length: usize, action: u32) {
let Some(id) = crate::web_mirror::id_of(&given_text(key, length)) else { return };
with_host(|host| {
match action {
0 => host.ui.press_for_reader(id),
_ => host.ui.show_for_reader(id),
}
host.rerun = true;
now_and_later(host);
});
}
#[unsafe(no_mangle)]
pub extern "C" fn taut_file(name: *mut u8, name_length: usize, bytes: *mut u8, length: usize) {
let name = given_text(name, name_length);
let bytes = given(bytes, length);
let file = (!name.is_empty()).then(|| PathBuf::from("/picked").join(name));
if let Some(file) = &file {
PICKED.with_borrow_mut(|picked| {
picked.retain(|(kept, _)| kept != file);
picked.push((file.clone(), bytes));
});
}
with_host(|host| {
host.ui.file_dialog_answered(file);
host.rerun = true;
host.schedule();
});
}
#[unsafe(no_mangle)]
pub extern "C" fn taut_close() {
with_host(|host| {
host.ui.request_close();
host.rerun = true;
host.describe();
});
}