pikopiko 0.1.0

MML parser, compiler and chiptune player for games, with diagnostics designed for tools and AI.
Documentation
//! ファイルの変更の見張り(ホットリロード用、`std` のみ)。
//!
//! 曲を書き換えたら、ゲームや `pikopiko play --watch` を動かしたまま音を差し替えたい。そのために、
//! 曲が読み込んだすべてのファイル(本文・`#include`・`#sample`)の更新時刻と大きさを、一定の間隔で
//! 見比べて、変わったら知らせる。OS のファイル通知は使わない(依存を増やさず、WASM や小さい環境の
//! 方針と離れないため。スタジオも同じ方式)。
//!
//! 使い方:
//!
//! 1. [`WatchedFiles`] を `CompileOptions::include` に渡してコンパイルする(読んだファイルを覚える)。
//! 2. [`Watcher::new`] に `files.paths()` と間隔を渡す。
//! 3. 描画やゲームのフレームの合間に [`Watcher::poll`] を呼ぶ。`true` が返ったら、同じ設定でコンパイルし直し、
//!    診断に誤りがなければ [`resume_tick`] で位置を引き継いで新しい曲に差し替える(誤りなら古い曲を鳴らし続ける)。
//!
//! 守っている約束:
//! - 見張りは書き込みも確保もほとんどしない(見比べるときに `metadata` を読むだけ)。
//! - ファイルが消えた・現れた場合も変更として知らせる(保存の途中で一瞬なくなるエディターがある)。

use crate::compiler::diagnostic::Message;
use crate::compiler::include::{Files, Include, Included};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime};

/// 見張りの間隔の既定。
pub const DEFAULT_INTERVAL: Duration = Duration::from_millis(250);

/// ファイルの状態の目印(更新時刻と大きさ)。ファイルがなければ `None`。
type Stamp = Option<(SystemTime, u64)>;

fn stamp(path: &Path) -> Stamp {
    let meta = std::fs::metadata(path).ok()?;
    Some((meta.modified().ok()?, meta.len()))
}

/// 一定の間隔でファイルの目印を見比べる見張り。
#[derive(Debug)]
pub struct Watcher {
    entries: Vec<(PathBuf, Stamp)>,
    interval: Duration,
    last: Instant,
}

impl Watcher {
    /// `paths` を見張る。いまの状態を覚えるので、作った直後の [`poll`](Watcher::poll) は `false`。
    pub fn new(paths: impl IntoIterator<Item = PathBuf>, interval: Duration) -> Self {
        let entries = paths
            .into_iter()
            .map(|p| {
                let s = stamp(&p);
                (p, s)
            })
            .collect();
        Watcher {
            entries,
            interval,
            last: Instant::now(),
        }
    }

    /// 見張るファイルを入れ替える(コンパイルし直して、読むファイルが変わったとき)。いまの状態を覚える。
    pub fn set_paths(&mut self, paths: impl IntoIterator<Item = PathBuf>) {
        *self = Watcher::new(paths, self.interval);
    }

    /// 間隔が過ぎていれば見比べ、変わったものがあれば `true`(その状態を覚え直すので、続けて呼んでも
    /// 同じ変更では 1 回しか `true` にならない)。間隔の途中では何もせず `false`。
    pub fn poll(&mut self) -> bool {
        if self.last.elapsed() < self.interval {
            return false;
        }
        self.check()
    }

    /// 間隔を待たずに今すぐ見比べる。
    pub fn check(&mut self) -> bool {
        self.last = Instant::now();
        let mut changed = false;
        for (path, old) in &mut self.entries {
            let now = stamp(path);
            if now != *old {
                *old = now;
                changed = true;
            }
        }
        changed
    }

    /// 見張っているファイル。
    pub fn paths(&self) -> impl Iterator<Item = &Path> {
        self.entries.iter().map(|(p, _)| p.as_path())
    }
}

/// 読んだファイルのパスを覚える [`Files`]。コンパイルのあとに [`paths`](WatchedFiles::paths) で、
/// 曲が読み込んだものを見張りに渡す。
#[derive(Debug)]
pub struct WatchedFiles {
    files: Files,
    seen: Mutex<Vec<PathBuf>>,
}

impl WatchedFiles {
    /// 曲のファイルのパスから作る(そのファイルのあるフォルダーを基準にする)。
    pub fn beside(file: impl AsRef<Path>) -> Self {
        WatchedFiles {
            files: Files::beside(file),
            seen: Mutex::new(Vec::new()),
        }
    }

    fn remember(&self, path: PathBuf) {
        if let Ok(mut seen) = self.seen.lock() {
            if !seen.contains(&path) {
                seen.push(path);
            }
        }
    }

    /// これまでに読んだファイルのパス(読んだ順)。
    pub fn paths(&self) -> Vec<PathBuf> {
        self.seen.lock().map(|s| s.clone()).unwrap_or_default()
    }
}

impl Include for WatchedFiles {
    fn load(&self, path: &str, from: Option<&str>) -> Result<Included, Message> {
        let inc = self.files.load(path, from)?;
        // 名前は正規化した完全なパス(Files の約束)
        self.remember(PathBuf::from(&inc.name));
        Ok(inc)
    }

    fn load_bytes(&self, path: &str) -> Result<Arc<[u8]>, Message> {
        let bytes = self.files.load_bytes(path)?;
        let full = self.files.base().join(path);
        self.remember(std::fs::canonicalize(&full).unwrap_or(full));
        Ok(bytes)
    }
}

/// 差し替えるときに、新しい曲で再生を続ける位置(tick)。位置が新しい曲の長さを超えるときは、
/// 曲の頭(0)へ戻る。`length_ticks` が 0(長さのない曲)のときも 0。
pub fn resume_tick(position: u64, new_length_ticks: u64) -> u64 {
    if position < new_length_ticks {
        position
    } else {
        0
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn temp(name: &str) -> PathBuf {
        let dir =
            std::env::temp_dir().join(format!("pikopiko-watch-{name}-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn unchanged_files_are_quiet() {
        let dir = temp("quiet");
        let f = dir.join("a.mml");
        std::fs::write(&f, "A c").unwrap();
        let mut w = Watcher::new([f], Duration::ZERO);
        assert!(!w.check());
        assert!(!w.poll());
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn a_rewrite_is_reported_once() {
        let dir = temp("rewrite");
        let f = dir.join("a.mml");
        std::fs::write(&f, "A c").unwrap();
        let mut w = Watcher::new([f.clone()], Duration::ZERO);
        // 大きさが変われば、更新時刻の細かさに関わらず変わったと分かる
        std::fs::write(&f, "A c d e").unwrap();
        assert!(w.check());
        assert!(!w.check());
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn a_removed_or_new_file_counts_as_a_change() {
        let dir = temp("gone");
        let f = dir.join("a.mml");
        let mut w = Watcher::new([f.clone()], Duration::ZERO);
        assert!(!w.check());
        std::fs::write(&f, "A c").unwrap();
        assert!(w.check());
        std::fs::remove_file(&f).unwrap();
        assert!(w.check());
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn poll_waits_for_the_interval() {
        let dir = temp("interval");
        let f = dir.join("a.mml");
        std::fs::write(&f, "A c").unwrap();
        let mut w = Watcher::new([f.clone()], Duration::from_secs(3600));
        std::fs::write(&f, "A c d e").unwrap();
        assert!(!w.poll(), "間隔の途中では見比べない");
        assert!(w.check(), "check は待たない");
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn watched_files_remember_what_the_song_read() {
        let dir = temp("recorded");
        std::fs::write(dir.join("riff.mml"), "$riff = c d e").unwrap();
        let main = dir.join("main.mml");
        std::fs::write(&main, "#include \"riff.mml\"\nA $riff").unwrap();
        let files = WatchedFiles::beside(&main);
        let opts = crate::CompileOptions {
            include: Some(&files),
            ..Default::default()
        };
        let (song, diags) = crate::compile_with("#include \"riff.mml\"\nA $riff", &opts);
        assert!(song.is_some(), "{diags:?}");
        let paths = files.paths();
        assert_eq!(paths.len(), 1);
        assert!(paths[0].ends_with("riff.mml"));
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn resume_keeps_the_position_or_returns_to_the_start() {
        assert_eq!(resume_tick(100, 1000), 100);
        assert_eq!(resume_tick(1000, 1000), 0);
        assert_eq!(resume_tick(5000, 1000), 0);
        assert_eq!(resume_tick(10, 0), 0);
    }
}