116 lines
5.1 KiB
Rust
116 lines
5.1 KiB
Rust
//! The debug dev loop: an app's page scripts are read from disk whenever a tab's init scripts are
|
|
//! built, and when one of those files changes every tab webview is rebuilt on its current URL, so
|
|
//! the new script is injected within a second or two without restarting the app.
|
|
//!
|
|
//! This module exists only in debug builds (`cfg(debug_assertions)`, see `lib.rs`); release builds
|
|
//! contain no file read, no path string and no watcher. An app names its files with
|
|
//! [`page_script!`](crate::page_script) in `SiteHooks::init_scripts`; the files it names are the ones
|
|
//! watched. Change detection is `devmode`'s debounced signature watcher (a file must keep its
|
|
//! size and modification time for `DEBOUNCE`, so a half-written bundle never loads).
|
|
//!
|
|
//! Why the tabs are rebuilt rather than reloaded: a webview's document-start scripts are fixed at
|
|
//! creation, so a plain reload would run the old copy. The rebuild reuses `tabs_sync`'s
|
|
//! profile-change path (close, then create with the current init scripts) on the shell's last
|
|
//! layout, with each tab's live URL, so route and layout are kept (scroll position is not).
|
|
|
|
use crate::app::{self, tabs_sync};
|
|
use crate::devmode::{self, Watcher};
|
|
use crate::{host, policy, tabs::TabLayout};
|
|
use std::collections::{BTreeMap, BTreeSet};
|
|
use std::path::PathBuf;
|
|
use std::sync::Mutex;
|
|
use std::time::Instant;
|
|
use tauri::{AppHandle, Manager};
|
|
|
|
/// Marks a tab's recorded profile as stale so `tabs_sync` rebuilds its webview.
|
|
const STALE: &str = "\u{0}dev-reload";
|
|
|
|
static FILES: Mutex<BTreeSet<PathBuf>> = Mutex::new(BTreeSet::new());
|
|
static LAYOUT: Mutex<Option<(Vec<TabLayout>, Option<[f64; 2]>)>> = Mutex::new(None);
|
|
|
|
/// `path` read from disk (and watched from now on), or `embedded` when it is missing or empty.
|
|
pub fn from_disk(path: &str, embedded: &str) -> String {
|
|
let path = PathBuf::from(path);
|
|
let read = std::fs::read_to_string(&path).ok().filter(|text| !text.trim().is_empty());
|
|
if let Ok(mut files) = FILES.lock() {
|
|
files.insert(path);
|
|
}
|
|
read.unwrap_or_else(|| embedded.to_owned())
|
|
}
|
|
|
|
/// The shell's latest layout (from `tabs_sync`), to rebuild the tabs from.
|
|
pub(crate) fn remember_layout(items: &[TabLayout], viewport: Option<[f64; 2]>) {
|
|
if let Ok(mut layout) = LAYOUT.lock() {
|
|
*layout = Some((items.to_vec(), viewport));
|
|
}
|
|
}
|
|
|
|
/// Starts the watcher thread (debug builds, from the host's setup).
|
|
pub(crate) fn start(app: &AppHandle) {
|
|
let app = app.clone();
|
|
std::thread::Builder::new().name("wb-dev-loop".into()).spawn(move || watch_loop(app)).ok();
|
|
}
|
|
|
|
fn scan() -> BTreeMap<PathBuf, devmode::Signature> {
|
|
let files = FILES.lock().map(|files| files.clone()).unwrap_or_default();
|
|
files.into_iter().filter_map(|path| devmode::signature(&path).map(|sig| (path, sig))).collect()
|
|
}
|
|
|
|
fn watch_loop(app: AppHandle) {
|
|
let mut watcher: Watcher<PathBuf> = Watcher::new();
|
|
let mut known = 0;
|
|
loop {
|
|
std::thread::sleep(devmode::POLL);
|
|
let current = scan();
|
|
// A newly named file (the first tab just built its scripts) becomes part of the baseline.
|
|
if current.len() != known {
|
|
known = current.len();
|
|
watcher.reset();
|
|
}
|
|
let changes = watcher.observe(Instant::now(), current);
|
|
if !changes.is_empty() {
|
|
let names: Vec<String> = changes.iter().filter_map(|change| change.target().file_name()).map(|name| name.to_string_lossy().into_owned()).collect();
|
|
let started = Instant::now();
|
|
reload_tabs(&app);
|
|
eprintln!("[wayBetter dev] {} changed: tabs rebuilt in {} ms", names.join(", "), started.elapsed().as_millis());
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Rebuilds every tab webview (fresh init scripts) on its current URL.
|
|
fn reload_tabs(app: &AppHandle) {
|
|
let Some((mut items, viewport)) = LAYOUT.lock().ok().and_then(|layout| layout.clone()) else { return };
|
|
let Some(shell) = app.get_webview(policy::SHELL_LABEL) else { return };
|
|
for item in &mut items {
|
|
let Some(tab) = host::tab_webview(app, &item.id) else { continue };
|
|
if let Ok(url) = tab.url() {
|
|
if matches!(url.scheme(), "http" | "https") {
|
|
item.url = url.to_string();
|
|
}
|
|
}
|
|
if let Ok(mut data) = app::profiles(app) {
|
|
data.tab_profiles.insert(policy::tab_label(&item.id), STALE.to_owned());
|
|
}
|
|
}
|
|
if let Err(error) = tauri::async_runtime::block_on(tabs_sync(shell, app.clone(), items, viewport)) {
|
|
eprintln!("[wayBetter dev] tab rebuild failed: {error}");
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn from_disk_reads_the_file_and_falls_back_to_the_embedded_copy() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let file = dir.path().join("runtime.js");
|
|
let path = file.to_str().unwrap();
|
|
assert_eq!(from_disk(path, "embedded"), "embedded", "missing file");
|
|
std::fs::write(&file, " \n").unwrap();
|
|
assert_eq!(from_disk(path, "embedded"), "embedded", "empty file");
|
|
std::fs::write(&file, "fresh();").unwrap();
|
|
assert_eq!(from_disk(path, "embedded"), "fresh();");
|
|
assert!(scan().contains_key(&file), "a named file is watched");
|
|
}
|
|
}
|