diff --git a/Cargo.lock b/Cargo.lock index 6e4fd21..aa1e682 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -196,6 +196,18 @@ dependencies = [ "libc", ] +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + [[package]] name = "arboard" version = "3.7.0" @@ -244,6 +256,59 @@ dependencies = [ "libloading", ] +[[package]] +name = "askama" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6024d73179f43f15ccd2b881bfea6fee7f3a46ec53f33b52210dea749ebebaa4" +dependencies = [ + "askama_macros", + "itoa", + "percent-encoding", + "serde", + "serde_json", +] + +[[package]] +name = "askama_derive" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071ee5ebf2138e3ad180e0aacf6940c2cab5e6d8333741d9925c7bee2b153f39" +dependencies = [ + "askama_parser", + "basic-toml", + "glob", + "memchr", + "proc-macro2", + "quote", + "rustc-hash 2.1.3", + "serde", + "serde_derive", + "syn 3.0.9", +] + +[[package]] +name = "askama_macros" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "643e1c7cbb6aec1d920332fe51a7c0d8219e273dcb8602db03f5263e4d16487b" +dependencies = [ + "askama_derive", +] + +[[package]] +name = "askama_parser" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c5ae75772275d268b03ab8bdccdd12117b6169ee23256942b34e46c9f476583" +dependencies = [ + "rustc-hash 2.1.3", + "serde", + "serde_derive", + "unicode-ident", + "winnow", +] + [[package]] name = "async-broadcast" version = "0.7.2" @@ -436,6 +501,15 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "basic-toml" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a" +dependencies = [ + "serde", +] + [[package]] name = "bit-set" version = "0.10.0" @@ -609,6 +683,39 @@ dependencies = [ "wayland-client", ] +[[package]] +name = "camino" +version = "1.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbad30e4b4c14a39e3cc8aed085a12a327257c316619c93581e017bc52be591" +dependencies = [ + "serde_core", +] + +[[package]] +name = "cargo-platform" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0061da739915fae12ea00e16397555ed4371a6bb285431aab930f61b0aa4ba" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "cargo_metadata" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef987d17b0a113becdd19d3d0022d04d7ef41f9efe4f3fb63ac44ba61df3ade9" +dependencies = [ + "camino", + "cargo-platform", + "semver", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "cc" version = "1.8.0" @@ -714,6 +821,45 @@ dependencies = [ "zip", ] +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + [[package]] name = "clipboard-win" version = "5.4.1" @@ -1437,6 +1583,15 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs-err" +version = "3.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5c95b673b8f6f7235229ae11c5642d81b04c2e64c1e2fb417bc0cf73ca45f29" +dependencies = [ + "autocfg", +] + [[package]] name = "futures-core" version = "0.3.34" @@ -1564,6 +1719,12 @@ dependencies = [ "vello_common", ] +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + [[package]] name = "glow" version = "0.17.0" @@ -1642,6 +1803,17 @@ dependencies = [ "gl_generator", ] +[[package]] +name = "goblin" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b363a30c165f666402fe6a3024d3bec7ebc898f96a4a23bd1c99f8dbf3f4f47" +dependencies = [ + "log", + "plain", + "scroll", +] + [[package]] name = "gpu-allocator" version = "0.28.0" @@ -1720,6 +1892,12 @@ dependencies = [ "foldhash 0.2.0", ] +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + [[package]] name = "hermit-abi" version = "0.5.3" @@ -1891,6 +2069,8 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown 0.17.1", + "serde", + "serde_core", ] [[package]] @@ -2191,6 +2371,12 @@ dependencies = [ "unicase", ] +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -2211,6 +2397,17 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "mobile-api" +version = "0.9.0" +dependencies = [ + "chess-core", + "chess-import", + "shakmaty", + "thiserror 2.0.21", + "uniffi", +] + [[package]] name = "moxcms" version = "0.8.1" @@ -2313,6 +2510,16 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + [[package]] name = "nom" version = "8.0.0" @@ -3523,6 +3730,26 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "scroll" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ab8598aa408498679922eff7fa985c25d58a90771bd6be794434c5277eab1a6" +dependencies = [ + "scroll_derive", +] + +[[package]] +name = "scroll_derive" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1783eabc414609e28a5ba76aee5ddd52199f7107a0b24c2e9746a1ecc34a683d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "self_cell" version = "1.3.0" @@ -3534,6 +3761,10 @@ name = "semver" version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] [[package]] name = "serde" @@ -3721,6 +3952,12 @@ version = "1.16.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" +[[package]] +name = "smawk" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8e2fb0f499abb4d162f2bedad68f5ef91a1682b5a03596ddb67efd37768d100" + [[package]] name = "smithay-client-toolkit" version = "0.19.2" @@ -3823,6 +4060,12 @@ dependencies = [ "float-cmp", ] +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "subtle" version = "2.6.1" @@ -4075,6 +4318,16 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "textwrap" +version = "0.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ecfad6c3abc80a577f2b91c1e412ee57e7a060d430b553c1b0c940974ebcd49" +dependencies = [ + "smawk", + "unicode-width", +] + [[package]] name = "thiserror" version = "1.0.69" @@ -4264,7 +4517,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" dependencies = [ "memchr", - "nom", + "nom 8.0.0", "petgraph", ] @@ -4337,6 +4590,127 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "uniffi" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76407f5f396a2c949a069eff4a9fca9ce462410eb872bffef4c2b7b89804a77a" +dependencies = [ + "anyhow", + "camino", + "cargo_metadata", + "clap", + "uniffi_bindgen", + "uniffi_core", + "uniffi_macros", + "uniffi_pipeline", +] + +[[package]] +name = "uniffi_bindgen" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3df3ced8f0eda3de99f6d50820e8628f443da8e4f447f477d1403ceba29dacbd" +dependencies = [ + "anyhow", + "askama", + "camino", + "cargo_metadata", + "fs-err", + "glob", + "goblin", + "heck", + "indexmap", + "once_cell", + "serde", + "tempfile", + "textwrap", + "toml", + "uniffi_internal_macros", + "uniffi_meta", + "uniffi_pipeline", + "uniffi_udl", +] + +[[package]] +name = "uniffi_core" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7530ae8efeaaa488622865966763fe0294832779fff80508c36d69c6a874a6a" +dependencies = [ + "anyhow", + "bytes", + "once_cell", + "static_assertions", +] + +[[package]] +name = "uniffi_internal_macros" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f4bad017164375d99450d70495014810d15a84ba9da6ed14b9628b1424223ba" +dependencies = [ + "anyhow", + "indexmap", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "uniffi_macros" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b855a58da153739ce6e863f6e296edc3716a093768c4d3d957f17f5e4317c60" +dependencies = [ + "camino", + "fs-err", + "once_cell", + "proc-macro2", + "quote", + "serde", + "syn 2.0.119", + "toml", + "uniffi_meta", +] + +[[package]] +name = "uniffi_meta" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af0c88664a9cb9559856f5a250283c9708923b303170e2e5c7db8f4ad65e9459" +dependencies = [ + "anyhow", + "siphasher", + "uniffi_internal_macros", + "uniffi_pipeline", +] + +[[package]] +name = "uniffi_pipeline" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d00f5c044b4a3dca0b1226c92ddaeea626f337470e22180dd182160c87a06b0b" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "tempfile", + "uniffi_internal_macros", +] + +[[package]] +name = "uniffi_udl" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55dfd9c778d6b39cb5acd541d9ff63431974035d2bad83c897b766a6ee3152ac" +dependencies = [ + "anyhow", + "textwrap", + "uniffi_meta", + "weedle2", +] + [[package]] name = "untrusted" version = "0.9.0" @@ -4723,6 +5097,15 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "weedle2" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "998d2c24ec099a87daf9467808859f9d82b61f1d9c9701251aea037f514eae0e" +dependencies = [ + "nom 7.1.3", +] + [[package]] name = "weezl" version = "0.1.12" diff --git a/Cargo.toml b/Cargo.toml index cbbbac4..abc595d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,12 @@ [workspace] resolver = "3" -members = ["crates/chess-core", "crates/chess-import", "crates/uci", "apps/desktop"] +members = [ + "crates/chess-core", + "crates/chess-import", + "crates/uci", + "crates/mobile-api", + "apps/desktop", +] [workspace.package] version = "0.9.0" diff --git a/apps/desktop/src/notation.rs b/apps/desktop/src/notation.rs index c45d720..b9849cf 100644 --- a/apps/desktop/src/notation.rs +++ b/apps/desktop/src/notation.rs @@ -7,7 +7,7 @@ use crate::i18n::tr; use crate::review::{Mark, judgement_color, judgement_name, judgement_symbol}; use crate::translate_ui::Mark as Translated; use chess_core::shakmaty::{Color, Position}; -use chess_core::{CommentPart, Game, Nag, NodeId, parse_comment}; +use chess_core::{Game, Nag, NodeId}; use egui::{Align2, Color32, FontId, RichText, Sense, Stroke, Ui, vec2}; pub struct Notation<'a> { @@ -362,34 +362,9 @@ fn move_glyph(nags: &[Nag]) -> (String, Option) { (s, color) } +/// The text of comments as shown (see [`chess_core::comment_display_text`]). pub fn comment_text(comments: &[String]) -> String { - let mut out = String::new(); - for c in comments { - for part in parse_comment(c) { - if let CommentPart::Text(t) = part { - // Single line breaks are formatting, not content: reflow to the panel width. - // A blank line starts a new paragraph (book chapters imported from ChessBase). - let mut blank = false; - for line in t.lines() { - if line.trim().is_empty() { - blank = true; - continue; - } - if blank && !out.is_empty() { - out.push_str("\n\n"); - } - blank = false; - for word in line.split_whitespace() { - if !out.is_empty() && !out.ends_with('\n') { - out.push(' '); - } - out.push_str(word); - } - } - } - } - } - out + chess_core::comment_display_text(comments) } fn block_frame(ui: &Ui) -> egui::Frame { diff --git a/crates/chess-core/src/comment.rs b/crates/chess-core/src/comment.rs index 2d127fa..cddb032 100644 --- a/crates/chess-core/src/comment.rs +++ b/crates/chess-core/src/comment.rs @@ -127,6 +127,37 @@ fn command(name: &str, payload: &str) -> Annotation { } } +/// The text of a node's comments as a reader sees it: board commands (`[%cal]`, +/// `[%clk]`, …) left out, single line breaks reflowed (they are formatting), a blank +/// line kept as a paragraph break (book chapters imported from ChessBase). +pub fn comment_display_text(comments: &[String]) -> String { + let mut out = String::new(); + for c in comments { + for part in parse_comment(c) { + if let CommentPart::Text(t) = part { + let mut blank = false; + for line in t.lines() { + if line.trim().is_empty() { + blank = true; + continue; + } + if blank && !out.is_empty() { + out.push_str("\n\n"); + } + blank = false; + for word in line.split_whitespace() { + if !out.is_empty() && !out.ends_with('\n') { + out.push(' '); + } + out.push_str(word); + } + } + } + } + } + out +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/chess-core/src/lib.rs b/crates/chess-core/src/lib.rs index e7da93c..5f3f385 100644 --- a/crates/chess-core/src/lib.rs +++ b/crates/chess-core/src/lib.rs @@ -14,7 +14,7 @@ pub mod pgn; pub mod repair; pub mod start; -pub use comment::{Annotation, CommentPart, ShapeColor, parse_comment}; +pub use comment::{Annotation, CommentPart, ShapeColor, comment_display_text, parse_comment}; pub use database::{OpenError, PgnDatabase, SourceFingerprint}; pub use diagnostic::{Diagnostic, DiagnosticCode, Severity, SourceLocation}; pub use edit::{EditError, EditOutcome}; diff --git a/crates/chess-import/src/lib.rs b/crates/chess-import/src/lib.rs index 4b326a7..64f1460 100644 --- a/crates/chess-import/src/lib.rs +++ b/crates/chess-import/src/lib.rs @@ -363,6 +363,73 @@ pub fn open( }) } +/// Opens a database given as its content, without the file system (Android hands +/// over file descriptors, not paths): PGN, `.zip`, `.7z` and `.cbv`; `name` is the file +/// name, for its extension. A ChessBase database is several files: see +/// [`open_chessbase_files`]. +pub fn open_bytes( + name: &str, + bytes: Vec, + progress: &mut dyn FnMut(ScanProgress), + cancel: &AtomicBool, +) -> Result { + let ext = name + .rsplit_once('.') + .map(|(_, e)| e.to_lowercase()) + .unwrap_or_default(); + match ext.as_str() { + "cbz" => return Err(ImportError::Unsupported(Unsupported::Encrypted)), + "2cbh" => return Err(ImportError::Unsupported(Unsupported::ChessBase2)), + "cbh" => { + return Err(ImportError::Corrupt( + "a ChessBase database is several files: open its folder".into(), + )); + } + _ => {} + } + if let Some(kind) = archive::sniff(&bytes) { + let format = match kind { + archive::Kind::Zip => Format::Zip, + archive::Kind::SevenZip => Format::SevenZip, + }; + let (pgn, notes) = open_archive(&bytes, kind, cancel)?; + return finish(pgn, format, notes, progress, cancel); + } + if ext == "cbv" || cbv::looks_like_cbv(&bytes) && ext != "pgn" { + let part = open_cbv(&bytes)?; + return finish( + part.pgn, + Format::ChessBaseArchive, + part.notes, + progress, + cancel, + ); + } + let db = PgnDatabase::from_bytes(bytes, None, progress, cancel)?; + Ok(Opened { + db: Database::Pgn(PgnDb::new(db)), + format: Format::Pgn, + notes: Vec::new(), + }) +} + +/// Opens a ChessBase database from the contents of its files (`.cbh`, `.cbg`, +/// `.cba`, …: `files` are (file name, content)), converted into PGN in memory like the +/// databases inside archives. Meant for databases of a phone's size, not Mega. +pub fn open_chessbase_files( + cbh_name: &str, + files: &[(String, Vec)], + progress: &mut dyn FnMut(ScanProgress), + cancel: &AtomicBool, +) -> Result { + let members = chessbase::Files::from_members( + cbh_name, + files.iter().map(|(n, d)| (n.as_str(), d.as_slice())), + ); + let part = convert_chessbase(&members)?; + finish(part.pgn, Format::ChessBase, part.notes, progress, cancel) +} + /// A converted part of a database: UTF-8 PGN and notes. struct Part { pgn: String, diff --git a/crates/chess-import/tests/formats.rs b/crates/chess-import/tests/formats.rs index 372fd92..cad488c 100644 --- a/crates/chess-import/tests/formats.rs +++ b/crates/chess-import/tests/formats.rs @@ -46,6 +46,28 @@ fn plain_pgn_is_unchanged() { assert!(o.notes.is_empty()); } +#[test] +fn pgn_and_archives_open_from_bytes() { + let never = AtomicBool::new(false); + let pgn = chess_import::open_bytes("game.pgn", GAME.as_bytes().to_vec(), &mut |_| {}, &never) + .expect("opens"); + assert_eq!(pgn.format, Format::Pgn); + assert_eq!(pgn.db.len(), 1); + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + zip.start_file("one.pgn", zip::write::SimpleFileOptions::default()) + .expect("entry"); + zip.write_all(GAME.as_bytes()).expect("data"); + let bytes = zip.finish().expect("zip").into_inner(); + let z = chess_import::open_bytes("games.zip", bytes, &mut |_| {}, &never).expect("opens"); + assert_eq!(z.format, Format::Zip); + assert_eq!(z.db.raw_text(0), pgn.db.raw_text(0)); + // A .cbh alone is not a database. + assert!(matches!( + chess_import::open_bytes("base.cbh", vec![0; 46], &mut |_| {}, &never), + Err(ImportError::Corrupt(_)) + )); +} + #[test] fn zip_with_legacy_pgn_and_folders() { let dir = TempDir::new("zip"); @@ -150,6 +172,41 @@ fn unpacked_chessbase_database_matches_its_archive() { assert_eq!(from_disk.format, Format::ChessBase); let from_archive = open(&archive).expect("opens"); assert_eq!(from_disk.db.len(), from_archive.db.len()); + // The same without the file system (Android): the archive as bytes, the database + // as the contents of its files. + let never = AtomicBool::new(false); + let name = archive.file_name().unwrap().to_string_lossy().into_owned(); + let bytes = std::fs::read(&archive).expect("read"); + let archive_bytes = chess_import::open_bytes(&name, bytes, &mut |_| {}, &never).expect("opens"); + let files: Vec<(String, Vec)> = std::fs::read_dir(&dir.0) + .expect("dir") + .flatten() + .map(|e| { + let p = e.path(); + ( + p.file_name().unwrap().to_string_lossy().into_owned(), + std::fs::read(&p).expect("read"), + ) + }) + .collect(); + let cbh_name = cbh.file_name().unwrap().to_string_lossy().into_owned(); + let from_files = + chess_import::open_chessbase_files(&cbh_name, &files, &mut |_| {}, &never).expect("opens"); + assert_eq!(from_files.format, Format::ChessBase); + assert_eq!(from_files.db.len(), from_disk.db.len()); + assert_eq!(archive_bytes.db.len(), from_archive.db.len()); + for i in 0..from_disk.db.len() { + assert_eq!( + from_files.db.raw_text(i), + from_disk.db.raw_text(i), + "record {i}" + ); + assert_eq!( + archive_bytes.db.raw_text(i), + from_archive.db.raw_text(i), + "record {i}" + ); + } for i in 0..from_disk.db.len() { assert_eq!( from_disk.db.raw_text(i), diff --git a/crates/mobile-api/Cargo.toml b/crates/mobile-api/Cargo.toml new file mode 100644 index 0000000..6e93841 --- /dev/null +++ b/crates/mobile-api/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "mobile-api" +description = "The ChessPenguin core for the Android app: databases, game lists, games (UniFFI)" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lib] +crate-type = ["cdylib", "lib"] +name = "mobile_api" + +[[bin]] +# Generates the Kotlin bindings from the built library (`cargo run --bin uniffi-bindgen`). +name = "uniffi-bindgen" +path = "src/bin/uniffi-bindgen.rs" +required-features = ["bindgen"] + +[features] +bindgen = ["uniffi/cli"] + +[dependencies] +chess-core.workspace = true +chess-import.workspace = true +shakmaty.workspace = true +thiserror.workspace = true +uniffi = "0.32.2" diff --git a/crates/mobile-api/src/bin/uniffi-bindgen.rs b/crates/mobile-api/src/bin/uniffi-bindgen.rs new file mode 100644 index 0000000..f6cff6c --- /dev/null +++ b/crates/mobile-api/src/bin/uniffi-bindgen.rs @@ -0,0 +1,3 @@ +fn main() { + uniffi::uniffi_bindgen_main() +} diff --git a/crates/mobile-api/src/lib.rs b/crates/mobile-api/src/lib.rs new file mode 100644 index 0000000..7b9d948 --- /dev/null +++ b/crates/mobile-api/src/lib.rs @@ -0,0 +1,438 @@ +//! The ChessPenguin core for the Android app (docs/research/android-stack.md): open a +//! database the way Android hands files over (a file descriptor, or the files of a +//! ChessBase folder), list its games a page at a time, give a game as a tree of moves +//! with the positions, ready for the board and the notation. Bindings: UniFFI. +//! +//! Databases are read only; nothing here writes a file. + +use std::sync::Arc; +use std::sync::atomic::AtomicBool; + +use chess_core::{Game, MoveKind, NodeId}; + +uniffi::setup_scaffolding!(); + +/// What went wrong opening or reading a database, in words for the user (the Kotlin +/// side shows them as they are, or picks its own text by kind). +#[derive(Debug, thiserror::Error, uniffi::Error)] +pub enum ApiError { + /// The file could not be read. + #[error("{message}")] + Io { message: String }, + /// A known format that cannot be read (password, ChessBase 2CBH). + #[error("{message}")] + Unsupported { message: String }, + /// The file is damaged or not a database. + #[error("{message}")] + Corrupt { message: String }, + /// An archive without a database inside. + #[error("no PGN or ChessBase database in the archive")] + Empty, + /// No game with this number. + #[error("no game {index}")] + NoGame { index: u32 }, +} + +impl From for ApiError { + fn from(e: chess_import::ImportError) -> Self { + use chess_import::ImportError as E; + match e { + E::Io { source, .. } => ApiError::Io { + message: source.to_string(), + }, + E::Unsupported(u) => ApiError::Unsupported { + message: u.to_string(), + }, + E::Corrupt(m) => ApiError::Corrupt { message: m }, + E::Empty => ApiError::Empty, + E::Cancelled => ApiError::Io { + message: "cancelled".into(), + }, + } + } +} + +/// An open database. +#[derive(uniffi::Object)] +pub struct Database { + db: chess_import::Database, + format: String, + notes: Vec, +} + +/// One line of the game list. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct GameRow { + /// The game's number in the database (0-based), for [`Database::game`]. + pub index: u32, + pub white: String, + pub black: String, + /// "1-0", "0-1", "1/2-1/2" or "*". + pub result: String, + /// As in PGN: "1858.??.??". + pub date: String, + pub event: String, + pub eco: String, + pub white_elo: String, + pub black_elo: String, +} + +/// A PGN tag. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct Tag { + pub name: String, + pub value: String, +} + +/// A position in the game: the root (the start position) or the one after a move. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct MoveNode { + /// The node's id (the root is 0); `children` and `parent` refer to these. + pub id: u32, + pub parent: Option, + /// The moves from here: the main line first, then the variations. + pub children: Vec, + /// SAN of the move that led here ("" for the root), always Latin letters. + pub san: String, + /// The move's number and side: 12 and true for "12.Nf3", 12 and false for "12…Nf6". + pub move_number: u32, + pub white: bool, + /// Numeric annotation glyphs ($1 = "!") and their symbols ("!", "+-", …). + pub nags: Vec, + pub nag_symbols: String, + /// Comments as shown: board commands left out, lines reflowed. + pub comment_before: String, + pub comment_after: String, + /// The position here, and the squares of the move that led to it (for highlighting). + pub fen: String, + pub from_square: Option, + pub to_square: Option, + /// A null move ("--") of a study. + pub null_move: bool, + /// On the main line of the game (not inside a variation). + pub main_line: bool, +} + +/// A game ready to show. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct GameData { + pub tags: Vec, + pub result: String, + /// Every node: `nodes[0]` is the root; a node's id is its place in this list. + pub nodes: Vec, + /// Problems found reading the game, one line each. + pub notes: Vec, +} + +fn never() -> AtomicBool { + AtomicBool::new(false) +} + +fn wrap(opened: chess_import::Opened) -> Arc { + Arc::new(Database { + db: opened.db, + format: opened.format.label().to_owned(), + notes: opened.notes, + }) +} + +/// Opens a database file (PGN, `.zip`, `.7z`, `.cbv`) from a file descriptor; the +/// descriptor is taken over and closed (on Android: `ParcelFileDescriptor.detachFd()`). +/// `name` is the file's name, for its extension. +#[cfg(unix)] +#[uniffi::export] +pub fn open_file(name: String, fd: i32) -> Result, ApiError> { + let bytes = read_fd(fd)?; + open_bytes(name, bytes) +} + +#[cfg(unix)] +fn read_fd(fd: i32) -> Result, ApiError> { + use std::io::Read; + use std::os::fd::FromRawFd; + if fd < 0 { + return Err(ApiError::Io { + message: "no file".into(), + }); + } + // SAFETY: the caller hands the descriptor over (detached from its owner); the File + // owns and closes it. + let mut file = unsafe { std::fs::File::from_raw_fd(fd) }; + let mut bytes = Vec::new(); + file.read_to_end(&mut bytes).map_err(|e| ApiError::Io { + message: e.to_string(), + })?; + Ok(bytes) +} + +/// Opens a database file given as its content. +#[uniffi::export] +pub fn open_bytes(name: String, bytes: Vec) -> Result, ApiError> { + Ok(wrap(chess_import::open_bytes( + &name, + bytes, + &mut |_| {}, + &never(), + )?)) +} + +/// A file of a ChessBase database folder: its name and descriptor (taken over). +#[derive(Debug, Clone, uniffi::Record)] +pub struct FolderFile { + pub name: String, + pub fd: i32, +} + +/// Opens the ChessBase database `cbh_name` from the files of its folder (the `.cbh` +/// and the files beside it with the same name; others are closed unread). +#[cfg(unix)] +#[uniffi::export] +pub fn open_chessbase(cbh_name: String, files: Vec) -> Result, ApiError> { + let stem = cbh_name + .rsplit_once('.') + .map_or(cbh_name.as_str(), |(s, _)| s); + let mut contents = Vec::new(); + for f in files { + let same = f.name.rsplit_once('.').is_some_and(|(s, _)| s == stem); + if same { + contents.push((f.name, read_fd(f.fd)?)); + } else { + // Closed without reading. + drop(read_fd_closed(f.fd)); + } + } + Ok(wrap(chess_import::open_chessbase_files( + &cbh_name, + &contents, + &mut |_| {}, + &never(), + )?)) +} + +#[cfg(unix)] +fn read_fd_closed(fd: i32) -> Option { + use std::os::fd::FromRawFd; + // SAFETY: as in `read_fd`: the descriptor is ours to close. + (fd >= 0).then(|| unsafe { std::fs::File::from_raw_fd(fd) }) +} + +/// Opens a database by its path (tests, tools; the app uses descriptors). +#[uniffi::export] +pub fn open_path(path: String) -> Result, ApiError> { + Ok(wrap(chess_import::open( + std::path::Path::new(&path), + &mut |_| {}, + &never(), + )?)) +} + +#[uniffi::export] +impl Database { + /// The number of games. + pub fn len(&self) -> u32 { + self.db.len() as u32 + } + + pub fn is_empty(&self) -> bool { + self.db.is_empty() + } + + /// What the database was read from ("PGN", "ChessBase", "zip", …). + pub fn format(&self) -> String { + self.format.clone() + } + + /// Remarks about the conversion, one line each. + pub fn notes(&self) -> Vec { + self.notes.clone() + } + + /// Up to `count` lines of the game list from `start` on. + pub fn rows(&self, start: u32, count: u32) -> Vec { + let Some(pgn) = self.db.as_pgn() else { + return Vec::new(); + }; + pgn.entries() + .iter() + .skip(start as usize) + .take(count as usize) + .map(|e| { + let tag = |name: &str| e.tag(name).unwrap_or("").to_owned(); + GameRow { + index: e.index as u32, + white: tag("White"), + black: tag("Black"), + result: tag("Result"), + date: tag("Date"), + event: tag("Event"), + eco: tag("ECO"), + white_elo: tag("WhiteElo"), + black_elo: tag("BlackElo"), + } + }) + .collect() + } + + /// The game `index`, ready to show. + pub fn game(&self, index: u32) -> Result { + let parsed = self + .db + .load_game(index as usize) + .ok_or(ApiError::NoGame { index })?; + Ok(game_data(&parsed.game, &parsed.diagnostics)) + } +} + +fn game_data(game: &Game, diagnostics: &[chess_core::Diagnostic]) -> GameData { + // Ids in tree order (the root first, each line before its variations' tails), mapped + // to their places in the list. + let mut order = vec![NodeId::ROOT]; + let mut i = 0; + while i < order.len() { + let id = order[i]; + order.extend(game.children(id).iter().copied()); + i += 1; + } + let place = |id: NodeId| order.iter().position(|x| *x == id).map(|p| p as u32); + let main: std::collections::HashSet = game.mainline().into_iter().collect(); + let nodes = order + .iter() + .map(|&id| { + let node = game.node(id); + let mv = game.game_move(id); + let (move_number, color) = game.move_number(id).unwrap_or((0, shakmaty::Color::White)); + let uci = mv.and_then(|m| m.uci()); + let squares = uci + .as_deref() + .filter(|u| u.len() >= 4) + .map(|u| (u[0..2].to_owned(), u[2..4].to_owned())); + let nags: Vec = node + .map(|n| n.nags().iter().map(|g| g.0).collect()) + .unwrap_or_default(); + MoveNode { + id: place(id).unwrap_or(0), + parent: game.parent(id).and_then(place), + children: game.children(id).iter().filter_map(|c| place(*c)).collect(), + san: mv.map(|m| m.san.clone()).unwrap_or_default(), + move_number, + white: color == shakmaty::Color::White, + nag_symbols: node + .map(|n| { + n.nags() + .iter() + .filter_map(|g| g.symbol()) + .collect::>() + .join("") + }) + .unwrap_or_default(), + nags, + comment_before: node + .map(|n| chess_core::comment_display_text(n.comments_before())) + .unwrap_or_default(), + comment_after: node + .map(|n| chess_core::comment_display_text(n.comments_after())) + .unwrap_or_default(), + fen: game.fen(id).unwrap_or_default(), + from_square: squares.as_ref().map(|s| s.0.clone()), + to_square: squares.map(|s| s.1), + null_move: mv.is_some_and(|m| matches!(m.kind, MoveKind::Null)), + main_line: id == NodeId::ROOT || main.contains(&id), + } + }) + .collect(); + GameData { + tags: game + .tags() + .iter() + .map(|(n, v)| Tag { + name: n.clone(), + value: v.clone(), + }) + .collect(), + result: game.result().as_str().to_owned(), + nodes, + notes: diagnostics.iter().map(|d| d.message.clone()).collect(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn classics() -> Arc { + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../examples/classics.pgn"); + open_path(path.into()).expect("the sample opens") + } + + #[test] + fn rows_come_a_page_at_a_time() { + let db = classics(); + assert!(db.len() >= 2); + let first = db.rows(0, 1); + assert_eq!(first.len(), 1); + assert_eq!(first[0].index, 0); + assert!(!first[0].white.is_empty()); + assert_eq!(db.rows(1, 100).len() as u32, db.len() - 1); + assert!(db.rows(db.len(), 10).is_empty()); + } + + #[test] + fn a_game_is_a_tree_with_positions() { + let db = classics(); + let g = db.game(0).expect("a game"); + let root = &g.nodes[0]; + assert_eq!(root.id, 0); + assert_eq!(root.parent, None); + assert!(root.fen.starts_with("rnbqkbnr/pppppppp")); + let first = &g.nodes[root.children[0] as usize]; + assert_eq!(first.parent, Some(0)); + assert!(first.white && first.move_number == 1); + assert!(first.from_square.is_some() && first.to_square.is_some()); + assert!(first.main_line); + // Every child points back to its parent, ids are places in the list. + for (i, n) in g.nodes.iter().enumerate() { + assert_eq!(n.id as usize, i); + for &c in &n.children { + assert_eq!(g.nodes[c as usize].parent, Some(n.id)); + } + } + assert!(matches!(db.game(db.len()), Err(ApiError::NoGame { .. }))); + } + + #[test] + fn comments_and_variations_come_along() { + // The Opera game of the samples has comments and a variation. + let db = classics(); + let g = db.game(0).expect("a game"); + assert!( + g.nodes + .iter() + .any(|n| !n.comment_after.is_empty() && !n.comment_after.contains("[%")) + ); + assert!(g.nodes.iter().any(|n| !n.main_line)); + } + + #[test] + fn bytes_open_like_files() { + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../examples/classics.pgn"); + let bytes = std::fs::read(path).expect("read"); + let db = open_bytes("classics.pgn".into(), bytes).expect("opens"); + assert_eq!(db.len(), classics().len()); + assert_eq!(db.format(), classics().format()); + assert!(matches!( + open_bytes("x.cbh".into(), vec![0; 46]), + Err(ApiError::Corrupt { .. }) + )); + } + + #[cfg(unix)] + #[test] + fn a_descriptor_is_read_and_closed() { + use std::os::fd::IntoRawFd; + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../examples/classics.pgn"); + let fd = std::fs::File::open(path).expect("open").into_raw_fd(); + let db = open_file("classics.pgn".into(), fd).expect("opens"); + assert_eq!(db.len(), classics().len()); + assert!(open_file("x.pgn".into(), -1).is_err()); + } +}