From 171e2d5328a2cb5ce0df165ff0f6a8b896741eae Mon Sep 17 00:00:00 2001 From: AlienTech Software Date: Sat, 7 Nov 2026 13:36:00 -0800 Subject: [PATCH 1/8] feat(demo): refresh managed Welcome notebook on startup --- .github/web-build/bundle_demo.py | 61 + .github/web-build/test_bundle_demo.py | 49 + .github/web-build/web.diff | 88 +- .github/workflows/deploy-website.yml | 116 +- .github/workflows/packaging.yml | 10 +- .github/workflows/release.yml | 43 +- AGENTS.md | 6 +- Cargo.lock | 1 + SKILLS/nc-reelase-signoff/SKILL.md | 22 + .../references/0.0.6-lessons.md | 65 +- SKILLS/nc-ua/SKILL.md | 6 +- apps/notecraft-setup/src/lib.rs | 211 ++-- apps/notecraft-setup/src/main.rs | 31 +- apps/notecraft/Cargo.toml | 1 + apps/notecraft/src/main.rs | 33 +- crates/engine/src/sample.rs | 4 +- docs/demo/scripts/src/generator.rs | 1100 +++++++++++++++++ docs/demo/scripts/src/main.rs | 1027 +-------------- docs/releases/0.0.9/READINESS.md | 70 ++ docs/releases/0.0.9/RELEASE_NOTES.md | 2 +- docs/releasing.md | 47 +- docs/testing.md | 8 +- packaging/OSX/README.md | 48 +- packaging/OSX/issues.md | 16 +- packaging/OSX/package.sh | 68 +- packaging/OSX/test-stale.sh | 7 +- packaging/OSX/verify.sh | 56 +- packaging/installation artifacts.md | 133 +- packaging/linux/AppRun | 2 +- .../com.alientechsoftware.notecraft.desktop | 4 +- packaging/linux/nfpm.yaml | 3 - packaging/linux/package.sh | 44 +- packaging/linux/test.sh | 56 +- packaging/windows/notecraft.wxs | 31 +- packaging/windows/package.ps1 | 39 +- xtask/src/main.rs | 18 +- 36 files changed, 2001 insertions(+), 1525 deletions(-) create mode 100644 .github/web-build/bundle_demo.py create mode 100644 .github/web-build/test_bundle_demo.py create mode 100644 docs/demo/scripts/src/generator.rs create mode 100644 docs/releases/0.0.9/READINESS.md diff --git a/.github/web-build/bundle_demo.py b/.github/web-build/bundle_demo.py new file mode 100644 index 00000000..237ace28 --- /dev/null +++ b/.github/web-build/bundle_demo.py @@ -0,0 +1,61 @@ +from __future__ import annotations + +import argparse +import re +import zipfile +from pathlib import Path + + +REQUIRED_FILES = { + "html": ("_node.toml", "00-start/welcome/index.html"), + "cmgfm": ("_node.toml", "00-start/welcome/index.md"), +} + + +def bundle_demo(source: Path, destination: Path, version: str) -> None: + html_source = source / "html" + cmgfm_source = source / "cmgfm" + for required_root in (html_source, cmgfm_source): + if not (required_root / "_node.toml").is_file(): + raise ValueError(f"official demo format is missing metadata: {required_root}") + language_folders = [path for path in required_root.iterdir() if path.is_dir() and re.fullmatch(r"(?:1\d|2\d)-[a-z]{2}", path.name)] + if len(language_folders) != 13: + raise ValueError(f"official {required_root.name} demo has {len(language_folders)} language folders, expected 13") + for format_name, required_files in REQUIRED_FILES.items(): + format_root = source / format_name + for relative in required_files: + if not (format_root / relative).is_file(): + raise ValueError(f"official {format_name} demo is missing {relative}") + + expected_title = f"Welcome to NoteCraft (Ver {version})" + for format_name, required_files in REQUIRED_FILES.items(): + page = (source / format_name / required_files[1]).read_text(encoding="utf-8") + if version not in page: + raise ValueError(f"{format_name} Welcome page does not contain workspace version {version}") + if expected_title not in page: + raise ValueError(f"official {format_name} Welcome page does not name version {version}") + + destination.parent.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(destination, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as bundle: + for format_name in REQUIRED_FILES: + format_root = source / format_name + for path in sorted(format_root.rglob("*")): + if path.is_file(): + bundle.write(path, (Path(format_name) / path.relative_to(format_root)).as_posix()) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("source", type=Path) + parser.add_argument("destination", type=Path) + parser.add_argument("--version", required=True) + args = parser.parse_args() + if not re.fullmatch(r"\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?", args.version): + parser.error("--version must be a semantic version") + bundle_demo(args.source, args.destination, args.version) + print(f"Bundled both official Welcome notebook formats v{args.version} at {args.destination}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.github/web-build/test_bundle_demo.py b/.github/web-build/test_bundle_demo.py new file mode 100644 index 00000000..63e52b26 --- /dev/null +++ b/.github/web-build/test_bundle_demo.py @@ -0,0 +1,49 @@ +from __future__ import annotations + +import tempfile +import tomllib +import unittest +import zipfile +from pathlib import Path + +from bundle_demo import bundle_demo + + +class BundleDemoTests(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.root = Path(__file__).resolve().parents[2] + with (cls.root / "Cargo.toml").open("rb") as manifest: + cls.version = tomllib.load(manifest)["workspace"]["package"]["version"] + + def test_bundles_both_official_formats_with_release_version(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + archive = Path(temporary) / "welcome-notebook.zip" + bundle_demo(self.root / "docs" / "demo" / "DemoNotebook", archive, self.version) + + with zipfile.ZipFile(archive) as bundle: + names = set(bundle.namelist()) + self.assertIn("html/_node.toml", names) + self.assertIn("html/00-start/welcome/index.html", names) + self.assertIn("cmgfm/_node.toml", names) + self.assertIn("cmgfm/00-start/welcome/index.md", names) + for fmt in ("html", "cmgfm"): + languages = {name.split("/")[1] for name in names if name.startswith(f"{fmt}/") and len(name.split("/")) > 2} + languages = {name for name in languages if len(name) == 5 and name[:2].isdigit() and name[2] == "-"} + self.assertEqual(len(languages), 13, f"{fmt} should include every translated notebook") + html = bundle.read("html/00-start/welcome/index.html").decode() + cmgfm = bundle.read("cmgfm/00-start/welcome/index.md").decode() + for page in (html, cmgfm): + self.assertIn(f"Welcome to NoteCraft (Ver {self.version})", page) + self.assertIn(f"NoteCraft {self.version}. This notebook", page) + self.assertTrue((self.root / "docs/demo/DemoNotebook/cmgfm/00-start/welcome/index.md").is_file()) + + def test_rejects_a_demo_generated_for_a_different_release(self) -> None: + wrong_version = self.version + ".1" + with tempfile.TemporaryDirectory() as temporary: + with self.assertRaisesRegex(ValueError, "workspace version"): + bundle_demo(self.root / "docs" / "demo" / "DemoNotebook", Path(temporary) / "demo.zip", wrong_version) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/web-build/web.diff b/.github/web-build/web.diff index b4a455a6..989d9dc7 100644 --- a/.github/web-build/web.diff +++ b/.github/web-build/web.diff @@ -28,6 +28,7 @@ index 0000000..d9828a4 +notecraft-ui-egui = { workspace = true } +eframe = { workspace = true } +egui = { workspace = true } ++zip = { workspace = true } +wasm-bindgen = "0.2" +wasm-bindgen-futures = "0.4" +js-sys = "0.3" @@ -77,16 +78,15 @@ new file mode 100644 index 0000000..f4394fb --- /dev/null +++ b/apps/notecraft-web/src/main.rs -@@ -0,0 +1,339 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! NoteCraft in the browser, for Playground (patches/onenote.yaml in github.com/daijro/openplayground): the desktop +//! window (crates/ui-egui) on the page's canvas. +//! +//! The notebooks folder is `/NoteCraft`, in memory (crates/model/src/playground.rs). Playground's Files keep it as the -+//! same plain folders at `browser:/NoteCraft/…`: it is read from there at start, and every file NoteCraft writes or ++//! same plain folders at `browser:/NoteCraft/…`: it is read from there at start, and every file NoteCraft writes or +//! removes is written or removed there after the frame (through the page's `globalThis.playgroundFiles`). The standalone +//! site keeps personal settings in that browser's local storage; an invitation session stays transient. The first -+//! start makes the sample notebooks. A page opened from a Playground invitation (`?pg-session=`) keeps its ++//! start loads the official Welcome notebook as a separate notebook. A page opened from a Playground invitation (`?pg-session=`) keeps its +//! notebooks in the tab only, so joining someone's session never touches this browser's own notebooks. +//! Also: pictures in pages load from the in-memory folder, files dropped on the page can be inserted, and "Open in +//! NoteCraft" on a page file opens it (one of these notebooks') or copies it into a Quick Notes notebook. The CJK face @@ -101,6 +101,7 @@ index 0000000..f4394fb + use notecraft_store::Settings; + use notecraft_ui_egui::NoteCraftApp; + use std::cell::RefCell; ++ use std::io::{Cursor, Read as _}; + use std::path::Path; + use wasm_bindgen::{JsCast as _, JsValue, closure::Closure}; + @@ -149,6 +150,61 @@ index 0000000..f4394fb + Some(js_sys::Uint8Array::new(&wait(read.call0(&response).ok()).await?).to_vec()) + } + ++ /// Replaces only the managed browser Welcome notebook; sibling notebooks stay untouched. ++ async fn ensure_welcome_notebook() -> Result, String> { ++ let notebook = Path::new(ROOT).join("welcome-to-notecraft"); ++ let bytes = fetch("./welcome-notebook.zip").await.ok_or_else(|| "The release Welcome notebook could not be downloaded".to_string())?; ++ let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| format!("The release Welcome notebook archive is invalid: {e}"))?; ++ if archive.len() > 1000 { ++ return Err("The release Welcome notebook archive contains too many files".into()); ++ } ++ let mut files = Vec::with_capacity(archive.len()); ++ let mut total = 0_u64; ++ for index in 0..archive.len() { ++ let mut entry = archive.by_index(index).map_err(|e| format!("Could not read a Welcome notebook file: {e}"))?; ++ if entry.is_dir() { ++ continue; ++ } ++ let relative = entry.enclosed_name().ok_or_else(|| "The Welcome notebook archive has an unsafe path".to_string())?.to_path_buf(); ++ let components = relative.components().collect::>(); ++ if components.len() < 2 || !matches!(components[0].as_os_str().to_str(), Some("html" | "cmgfm")) { ++ return Err("The Welcome notebook archive has an unexpected path".into()); ++ } ++ total = total.saturating_add(entry.size()); ++ if total > 40 * 1024 * 1024 || entry.size() > 20 * 1024 * 1024 { ++ return Err("The Welcome notebook archive is larger than expected".into()); ++ } ++ let mut content = Vec::with_capacity(entry.size() as usize); ++ entry.read_to_end(&mut content).map_err(|e| format!("Could not unpack a Welcome notebook file: {e}"))?; ++ files.push((relative, content)); ++ } ++ for (format, page) in [("html", "00-start/welcome/index.html"), ("cmgfm", "00-start/welcome/index.md")] { ++ for required in [Path::new(format).join("_node.toml"), Path::new(format).join(page)] { ++ if !files.iter().any(|(name, _)| name == &required) { ++ return Err(format!("The Welcome notebook archive is missing {}", required.display())); ++ } ++ } ++ let languages = files ++ .iter() ++ .filter_map(|(name, _)| { ++ let mut parts = name.components(); ++ let first = parts.next()?.as_os_str().to_str()?; ++ let second = parts.next()?.as_os_str().to_str()?; ++ (first == format && second.len() == 5 && second.as_bytes()[0].is_ascii_digit()).then_some(second.to_owned()) ++ }) ++ .collect::>(); ++ if languages.len() != 13 { ++ return Err(format!("The {format} Welcome notebook has {} language folders; expected 13", languages.len())); ++ } ++ } ++ if fs::metadata(¬ebook).is_ok() { ++ fs::remove_dir_all(¬ebook).map_err(|e| format!("Could not replace the existing Welcome notebook: {e}"))?; ++ } ++ for (relative, content) in files { ++ fs::write(notebook.join(relative), content).map_err(|e| format!("Could not install the Welcome notebook: {e}"))?; ++ } ++ Ok(Some(notebook.join("00-start/welcome/index.html").to_string_lossy().into_owned())) ++ } + /// Follows the canvas's pen pointers: eframe turns them into mouse events and drops their pressure. + fn listen_to_the_pen(canvas: &web_sys::HtmlCanvasElement) { + use egui::TouchPhase::{Cancel, End, Move, Start}; @@ -217,7 +273,7 @@ index 0000000..f4394fb + !paths.is_empty() + } + -+ /// Picture links in pages (`file:///NoteCraft/…/assets/x.png`), read from the in-memory folder. ++ /// Picture links in pages (`file:///NoteCraft/…/assets/x.png`), read from the in-memory folder. + struct Files; + + impl egui::load::BytesLoader for Files { @@ -407,10 +463,13 @@ index 0000000..f4394fb + wasm_bindgen_futures::spawn_local(async { + let persist = !invited() && ["files", "write", "remove"].iter().all(|m| api().is_some_and(|a| get(&a, m).is_function())); + let local_settings = !persist && !invited(); -+ let had = persist && load().await; ++ if persist { ++ load().await; ++ } + if !persist && !invited() { + load_browser_settings(); + } ++ let welcome_page = if !invited() { Some(ensure_welcome_notebook().await) } else { None }; + let document = web_sys::window().and_then(|w| w.document()).expect("no document"); + let canvas = document + .get_element_by_id("notecraft_canvas") @@ -424,17 +483,12 @@ index 0000000..f4394fb + Box::new(move |cc| { + CTX.with(|c| c.set(cc.egui_ctx.clone()).ok()); + cc.egui_ctx.add_bytes_loader(std::sync::Arc::new(Files)); -+ let mut session = Session::new(Path::new(ROOT), Settings::at(SETTINGS)).map_err(|e| e.to_string())?; -+ // Give a fresh browser session a synthetic notebook to explore. -+ let first = !had && !invited(); -+ let sample = if first { -+ Some(notecraft_engine::sample::create_sample(&mut session, None).map_err(|e| e.to_string())?) -+ } else { -+ None -+ }; ++ let session = Session::new(Path::new(ROOT), Settings::at(SETTINGS)).map_err(|e| e.to_string())?; + let mut app = NoteCraftApp::new(session); -+ if let Some(sample) = sample { -+ app.open_path(&sample.md_page.to_string_lossy()); ++ if let Some(page) = welcome_page { ++ if let Some(page) = page.map_err(|e| e.to_string())? { ++ app.open_path(&page); ++ } + } + Ok(Box::new(Web { app, persist, local_settings, unsaved: None })) + }), @@ -865,9 +919,9 @@ index 0000000..f851b31 + STATE.set(State::Arrived(read)); + CTX.with_borrow(|c| c.as_ref().map(egui::Context::request_repaint)); + }); -+ Some("Reading the clipboard…") ++ Some("Reading the clipboard…") + } -+ State::Reading | State::Arrived(_) => Some("Reading the clipboard…"), ++ State::Reading | State::Arrived(_) => Some("Reading the clipboard…"), + }) +} + diff --git a/.github/workflows/deploy-website.yml b/.github/workflows/deploy-website.yml index 1a1c73a1..b40f7dc2 100644 --- a/.github/workflows/deploy-website.yml +++ b/.github/workflows/deploy-website.yml @@ -17,7 +17,7 @@ # --release` (the playground-web profile: LTO fat, one codegen unit) produces a working demo. # # What this buys, why the website lives in this repo instead of its own: -# - Every push to main that touches website/** redeploys the production site. +# - Changes to website code, workspace version, app crates, web-build patches, demo sources, or assets redeploy. # - Every pull_request gets its own live preview URL (Azure Static Web Apps' built-in preview # environments, free tier allows 3) — this is the whole reason the site is a subfolder here rather # than a separate repo: Azure's preview-per-PR only works when the Static Web App is linked to the @@ -35,15 +35,30 @@ on: paths: - "website/**" - ".github/workflows/deploy-website.yml" + - ".github/web-build/**" + - "Cargo.toml" + - "Cargo.lock" + - "rust-toolchain.toml" + - "apps/**" + - "crates/**" + - "docs/demo/**" + - "assets/**" pull_request: branches: [main] types: [opened, synchronize, reopened, closed] paths: - "website/**" - ".github/workflows/deploy-website.yml" + - ".github/web-build/**" + - "Cargo.toml" + - "Cargo.lock" + - "rust-toolchain.toml" + - "apps/**" + - "crates/**" + - "docs/demo/**" + - "assets/**" workflow_dispatch: - # Manual production redeploy with no website/** source change (e.g. to refresh the live demo - # after an app-only commit, which this workflow's path filters wouldn't otherwise trigger on). + # Manual production redeploy after a cancelled deployment or CDN issue. # Always builds and deploys from main's current tip. permissions: @@ -52,7 +67,8 @@ permissions: concurrency: group: deploy-website-${{ github.event.pull_request.number || 'production' }} - cancel-in-progress: true + # Supersede stale PR previews, but never cancel a production build/deploy halfway through. + cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: # Closing (or merging) a PR tears down its preview environment. No demo fetch needed for a close. @@ -92,6 +108,12 @@ jobs: - name: Install PyYAML run: pip install --quiet pyyaml + - name: Resolve workspace version + id: version + run: | + version="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"])')" + echo "value=$version" >> "$GITHUB_OUTPUT" + - name: Build the demo from source (no external build service) run: | set -eu @@ -115,6 +137,33 @@ jobs: "$f" -o "$f" done + - name: Build and test both User Assistance notebook formats + env: + NOTECRAFT_VERSION: ${{ steps.version.outputs.value }} + run: | + python3 .github/web-build/test_bundle_demo.py + python3 .github/web-build/bundle_demo.py \ + docs/demo/DemoNotebook website/demo/welcome-notebook.zip \ + --version "$NOTECRAFT_VERSION" + + - name: Verify built demo embeds the workspace version + env: + NOTECRAFT_VERSION: ${{ steps.version.outputs.value }} + run: | + python3 - <<'PY' + import os + from pathlib import Path + import sys + + version = os.environ["NOTECRAFT_VERSION"].encode() + wasm_files = list(Path("website/demo").glob("*.wasm")) + if not wasm_files: + sys.exit("No WebAssembly file was produced") + if not any(version in wasm.read_bytes() for wasm in wasm_files): + sys.exit(f"Built web demo does not embed workspace version {version.decode()}") + print(f"Built demo embeds NoteCraft {version.decode()}") + PY + - uses: Azure/static-web-apps-deploy@v1 with: azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN }} @@ -123,3 +172,62 @@ jobs: app_location: "website" output_location: "" skip_app_build: true + + - name: Verify deployed production demo version + if: github.event_name != 'pull_request' + env: + NOTECRAFT_VERSION: ${{ steps.version.outputs.value }} + VERIFY_QUERY: ${{ github.sha }} + run: | + python3 - <<'PY' + import os + import re + import sys + import time + import zipfile + from io import BytesIO + from urllib.error import URLError + from urllib.parse import urljoin + from urllib.request import urlopen + + base = "https://notecraft.cloud/demo/" + version = os.environ["NOTECRAFT_VERSION"].encode() + query = "?release-check=" + os.environ["VERIFY_QUERY"] + last_error = "no attempt made" + for attempt in range(1, 13): + try: + with urlopen(base + query, timeout=30) as response: + html = response.read().decode("utf-8") + match = re.search(r"['\"](\./[^'\"]+\.wasm)['\"]", html) + if not match: + raise RuntimeError("deployed demo index does not reference a WASM file") + wasm_url = urljoin(base, match.group(1)) + query + with urlopen(wasm_url, timeout=60) as response: + wasm = response.read() + if version not in wasm: + last_error = f"live WASM does not contain NoteCraft {version.decode()}" + raise RuntimeError(last_error) + with urlopen(base + "welcome-notebook.zip" + query, timeout=60) as response: + archive_bytes = response.read() + with zipfile.ZipFile(BytesIO(archive_bytes)) as notebook: + html = notebook.read("html/00-start/welcome/index.html").decode("utf-8") + cmgfm = notebook.read("cmgfm/00-start/welcome/index.md").decode("utf-8") + names = notebook.namelist() + title = f"Welcome to NoteCraft (Ver {version.decode()})" + if title not in html or title not in cmgfm: + last_error = f"live Welcome notebook formats do not match NoteCraft {version.decode()}" + raise RuntimeError(last_error) + if not all(name in names for name in ( + "html/_node.toml", "cmgfm/_node.toml", + "html/00-start/welcome/index.html", "cmgfm/00-start/welcome/index.md", + )): + last_error = "live Welcome notebook must contain both generated formats" + raise RuntimeError(last_error) + print(f"Live demo at {wasm_url} and both Welcome notebook formats embed NoteCraft {version.decode()}") + sys.exit(0) + except (URLError, TimeoutError, RuntimeError, zipfile.BadZipFile, KeyError, UnicodeDecodeError) as error: + last_error = str(error) + if attempt < 12: + time.sleep(10) + sys.exit(f"Live demo version verification failed after {attempt} attempts: {last_error}") + PY diff --git a/.github/workflows/packaging.yml b/.github/workflows/packaging.yml index 59f59a3f..be5998a2 100644 --- a/.github/workflows/packaging.yml +++ b/.github/workflows/packaging.yml @@ -102,20 +102,14 @@ jobs: - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: save-if: false - - name: Build app, setup app, DMG and CLI archive + - name: Build app, DMG and CLI archive run: packaging/OSX/package.sh --arch "${{ matrix.arch }}" - name: Reject stale or changed binaries run: packaging/OSX/test-stale.sh "${{ matrix.arch }}" - name: Reject mismatched source provenance run: bash packaging/OSX/test-provenance.sh - name: Verify package contents and mounted DMG - run: packaging/OSX/verify.sh "${{ matrix.arch }}" --expect-demo - - name: Build and verify a DMG with the optional notebook omitted - env: - DIST: ${{ runner.temp }}/notecraft-no-demo - run: | - packaging/OSX/package.sh --arch "${{ matrix.arch }}" --no-build --omit-demo --out "$DIST" - DIST="$DIST" packaging/OSX/verify.sh "${{ matrix.arch }}" --expect-no-demo + run: packaging/OSX/verify.sh "${{ matrix.arch }}" - uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 with: subject-path: | diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 49de6ca1..429526ff 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -16,10 +16,6 @@ on: description: "Successful Packaging workflow run ID whose artifacts should be published" required: true type: string - version: - description: "Version override for a test run, e.g. 0.1.0-rc.1 (empty: Cargo.toml)" - type: string - default: "" permissions: contents: read @@ -34,6 +30,7 @@ jobs: runs-on: ubuntu-24.04 timeout-minutes: 30 permissions: + actions: read # inspect and download the selected Packaging run contents: write # the draft release # Signing secrets, when they exist, live in the `release` environment. environment: release @@ -45,14 +42,12 @@ jobs: - name: Resolve the version id: v shell: bash - env: - INPUT_VERSION: ${{ inputs.version }} run: | - v="$INPUT_VERSION" - v="${v#v}" - if [ -z "$v" ]; then - v="$(awk '/^\[/ { p = ($0 == "[workspace.package]"); next } p && $1 == "version" { gsub(/[" ]/, "", $3); print $3; exit }' Cargo.toml)" + if [ "$GITHUB_REF" != "refs/heads/main" ]; then + echo "::error::Draft releases must be created from main" + exit 1 fi + v="$(awk '/^\[/ { p = ($0 == "[workspace.package]"); next } p && $1 == "version" { gsub(/[" ]/, "", $3); print $3; exit }' Cargo.toml)" if ! printf '%s' "$v" | grep -Eq '^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$'; then echo "::error::'$v' is not a version like 1.2.3 or 1.2.3-rc.1" exit 1 @@ -65,6 +60,34 @@ jobs: } >>"$GITHUB_OUTPUT" echo "### NoteCraft v$v (\`${GITHUB_SHA::9}\`)" >>"$GITHUB_STEP_SUMMARY" + - name: Verify the selected Packaging run matches this source + env: + PACKAGING_RUN_ID: ${{ inputs.packaging_run_id }} + EXPECTED_VERSION: ${{ steps.v.outputs.version }} + run: | + gh run view "$PACKAGING_RUN_ID" --repo "$GITHUB_REPOSITORY" \ + --json workflowName,conclusion,headBranch,headSha > "$RUNNER_TEMP/packaging-run.json" + python3 - "$GITHUB_SHA" "$EXPECTED_VERSION" "$RUNNER_TEMP/packaging-run.json" <<'PY' + import json + import sys + from pathlib import Path + + expected_sha, expected_version, metadata_path = sys.argv[1:] + run = json.loads(Path(metadata_path).read_text()) + problems = [] + if run.get("workflowName") != "Packaging": + problems.append(f"selected run is {run.get('workflowName')!r}, not Packaging") + if run.get("conclusion") != "success": + problems.append(f"selected Packaging run concluded {run.get('conclusion')!r}") + if run.get("headBranch") != "main": + problems.append(f"selected Packaging run used branch {run.get('headBranch')!r}, not main") + if run.get("headSha") != expected_sha: + problems.append(f"Packaging source {run.get('headSha')} does not match release source {expected_sha}") + if problems: + sys.exit("; ".join(problems)) + print(f"Packaging run matches main commit {expected_sha} and workspace version {expected_version}") + PY + - name: Download artifacts from the selected Packaging run run: gh run download "${{ inputs.packaging_run_id }}" --repo "$GITHUB_REPOSITORY" --dir dist --pattern 'notecraft-*' - name: Confirm packaging artifacts exist diff --git a/AGENTS.md b/AGENTS.md index 720dc09c..4636c00b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -102,9 +102,9 @@ NoteCraft is an open-source, clean-room recreation of the OneNote notebook exper - The Welcome notebook's authored content lives in `docs/demo/scripts/content`. `cargo xtask demo` generates `docs/demo/DemoNotebook`. The canonical `packaging/installation artifacts.md` contract - defines how installers deploy the generated User Assistance notebook separately - from application binaries. The current engine embedding and startup-copy path - are known legacy behavior that does not meet that contract; do not extend them. + defines how each platform bundles the generated User Assistance notebook and + how the app refreshes its dedicated per-user Welcome folder at startup. The + app replaces only `welcome-to-notecraft`; sibling user notebooks stay intact. Edit the authored content, regenerate the notebook, and use `cargo xtask demo-check` to confirm the checked-in bundle matches its source. Inspect Git status first and preserve unrelated edits to the source or generated notebook. diff --git a/Cargo.lock b/Cargo.lock index e976e614..a37ab3c2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2756,6 +2756,7 @@ dependencies = [ "image", "log", "notecraft-engine", + "notecraft-setup", "notecraft-store", "notecraft-ui-egui", "raw-window-handle", diff --git a/SKILLS/nc-reelase-signoff/SKILL.md b/SKILLS/nc-reelase-signoff/SKILL.md index 40d52034..08100ee3 100644 --- a/SKILLS/nc-reelase-signoff/SKILL.md +++ b/SKILLS/nc-reelase-signoff/SKILL.md @@ -42,6 +42,28 @@ requested `reelase` spelling for discoverability. 9. Confirm no automatic telemetry upload, local privacy wording, and release defaults. 10. Record exact commands, outputs, artifact paths, commit, tag candidate, known gaps, and manual checks. Do not push, publish, tag, or release without explicit owner approval. +11. For a GitHub draft, check the actual draft body and asset list after the final edit. Confirm + every embedded image URL returns HTTP 200 and renders in the draft preview; an uploaded GIF + asset alone does not make it appear inline. Resolve repository-relative links to stable URLs + that exist at the referenced ref. Re-read the draft URL after editing because an untagged draft + URL can change. +12. Check every shipped platform, including external Android build workflows. Verify the build + source commit and embedded/package version match the approved release. Do not attach an APK + from an older version or describe a platform as included when its verified artifact is absent. +13. Verify the hosted demo after deployment, not just the checked-in notebook: the latest + `Deploy website` run must be successful for the release source commit, and its live-version + check must match `[workspace.package] version` for both the WASM and the separate Welcome + notebook archive. Test the demo in a clean browser session and confirm it opens the official + `Welcome to NoteCraft` notebook, not the engine's generic sample. If deployment was cancelled, + rerun it from `main` and verify the live assets before signoff. +14. Keep deployment provenance aligned. Run desktop Packaging and Release from the same `main` + commit; confirm the Release workflow accepted that exact Packaging run. For Android, record + the external builder's source commit, APK package version, signing certificate identity, and + clean-install result. Android is a separate manual build today. Do not present the release as + platform-complete until every advertised platform has a verified artifact or its absence is + clearly called out. +15. Confirm every shipped User Assistance payload contains both generated formats and all 13 + languages. Both formats must pass parity checks before packaging. ## Platform signoff matrix diff --git a/SKILLS/nc-reelase-signoff/references/0.0.6-lessons.md b/SKILLS/nc-reelase-signoff/references/0.0.6-lessons.md index 43388091..60adf01e 100644 --- a/SKILLS/nc-reelase-signoff/references/0.0.6-lessons.md +++ b/SKILLS/nc-reelase-signoff/references/0.0.6-lessons.md @@ -98,6 +98,60 @@ check that would have caught it earlier. - Before saying a fix works, test the built artifact on a fresh profile. Several "fixed" claims in this release were checked only in the repository, which did not reproduce the VM's state. +## 11. Release draft images and links must resolve from the draft page + +- An image can be attached to a draft release and still be missing from the rendered description. + The body must contain an image embed, and its URL must be reachable by the renderer. +- A raw GitHub URL pinned to the release's target commit fails when the artwork was added to a + later commit. Confirm the file exists at the URL's exact ref. Prefer a stable committed raw URL + that returns HTTP 200, or a current release asset URL when its access behavior is verified. +- Rewrite all repository-relative links in the release body. They resolve in a repository file, + but not necessarily in a GitHub release description. +- After editing a draft, inspect the final rendered preview, image URL, asset URLs, and current + draft URL again. Drafts without a created tag can have an `untagged-*` URL; do not reuse an old + draft URL in the notes or handoff. + +## 12. Every platform artifact must match the release version + +- A green desktop Packaging matrix does not prove that Android is packaged. Check the Android + builder as a separate platform and require its NoteCraft APK artifact to pass the build and + package-version checks before attaching it. +- Some external Android workflows select the latest stable NoteCraft release tag. A draft + 0.x release may not be a stable tag available to that workflow, so it can silently build the + prior release. Verify the selected source ref and APK version instead of trusting the filename. +- If an Android build fails, record the concrete cause and leave the APK out. Never rename or + describe an older APK as the current release. + +## 13. A current demo source does not prove the hosted demo updated + +- A website deployment can be cancelled during its long WebAssembly build. A successful source + check and current notebook files do not prove Azure received that build. +- Trigger deployments when app code, crates, workspace version, web-build patches, demo source, or + assets change. Do not cancel an in-progress production deployment when a later run is queued. +- Check the built and live WebAssembly for the workspace version. A user can still see an older + notebook saved by the host, so verify the sample in a clean browser session too. + +## 14. Align source and version across deployment pipelines + +- Website deployment, desktop Packaging, GitHub Release, and Android builds are separate flows. + A successful run in one does not update the others. +- Run desktop Packaging and Release from the same `main` commit. The Release workflow should reject + a Packaging run from another commit, branch, or workflow and derive the tag version from the + workspace manifest. +- Android is built externally today. Record its source commit, APK package version, signing + certificate identity, and clean-install result separately. A filename alone is not proof. +- Check the live demo after deployment and use a clean browser profile when verifying its bundled + Welcome notebook. Keep a release provenance record with one source SHA and matching version for + each artifact. + +## 15. Build both page formats, ship the HTML User Assistance notebook + +- Generate HTML and CMGFM from the same authored demo source and keep format parity tests green. +- The User Assistance payload distributed on Windows, macOS, Linux, Android and the website is the + HTML notebook only. Do not confuse app support for CMGFM with a requirement to ship a CMGFM copy + of the Welcome notebook. +- Inspect each platform package and the website archive to confirm CMGFM files are absent. + ## Checklist for the next sign-off 1. Grep for the previous version string, and update `AGENTS.md` and `docs/releasing.md`. @@ -112,4 +166,13 @@ check that would have caught it earlier. 7. Run `cargo xtask ci` on the release branch. 8. Start the release workflow from `main`. Check the draft's body and image URL. Edit the body if it is generic. -9. Publish only when the owner says so. +9. For every body image, issue a request to the exact URL and check it in the rendered draft. Check + that all relative repository links were rewritten, then refresh the draft URL after the final + edit. +10. Verify one version-matched artifact per supported platform. Confirm Android's source commit, + APK package version, signing identity, and install result separately from desktop packaging. +11. Confirm website, desktop artifacts, and Android all report the intended source/version; explain + any platform that is still manual or missing from the release. +12. Owner's policy changed on 2026-11-07: verify both generated Welcome formats ship and the app + refreshes its managed copy at startup. Preserve all sibling user notebooks. +13. Publish only when the owner says so. diff --git a/SKILLS/nc-ua/SKILL.md b/SKILLS/nc-ua/SKILL.md index 74f4b78b..e73b21c0 100644 --- a/SKILLS/nc-ua/SKILL.md +++ b/SKILLS/nc-ua/SKILL.md @@ -42,9 +42,9 @@ The Welcome notebook is the User Assistance demo artifact. Its installation owne destinations, and preservation rules are defined only in `packaging/installation artifacts.md`. Its content source remains `docs/demo/scripts/content`; generated HTML and CMGFM outputs must stay in parity. -User Assistance work must not add app-startup copying or installer-specific behavior to content -code. Release evidence verifies the notebook after installation at the destination in the -canonical contract. +User Assistance content remains format-neutral and generated from its authored source. Platform +startup provisioning is owned by the app and the mechanisms in the canonical installation +contract; it refreshes only the managed Welcome notebook and preserves sibling notebooks. ## Product coverage ownership diff --git a/apps/notecraft-setup/src/lib.rs b/apps/notecraft-setup/src/lib.rs index afcf31c6..32d17f71 100644 --- a/apps/notecraft-setup/src/lib.rs +++ b/apps/notecraft-setup/src/lib.rs @@ -1,9 +1,7 @@ -use notecraft_store::Settings; use std::io; use std::path::{Path, PathBuf}; -const SETUP_MARKER: &str = "notecraft-setup-complete"; -const NOTEBOOK_NAME: &str = "welcome-to-notecraft"; +pub const NOTEBOOK_NAME: &str = "welcome-to-notecraft"; /// Finds the separate notebook folder beside the setup app on a mounted macOS DMG. pub fn macos_dmg_payload(executable: &Path) -> Option { @@ -15,60 +13,66 @@ pub fn macos_dmg_payload(executable: &Path) -> Option { #[derive(Clone, Debug, PartialEq, Eq)] pub enum SetupOutcome { Installed(PathBuf), - Existing(PathBuf), - AlreadyConfigured, - NoPayload, } -pub fn install_if_needed(settings: &Settings, payload: Option<&Path>, notebooks_root: &Path) -> io::Result { - if marker_path(settings).is_file() { - return Ok(SetupOutcome::AlreadyConfigured); - } - - let Some(payload) = payload else { - return Ok(SetupOutcome::NoPayload); - }; +/// Replaces only the app-managed Welcome notebook with the generated HTML and CMGFM editions. +/// Other notebooks in `notebooks_root` are never visited or changed. +pub fn refresh_demo(payload: &Path, notebooks_root: &Path) -> io::Result { validate_payload(payload)?; - let destination = notebooks_root.join(NOTEBOOK_NAME); - if destination.exists() { - mark_configured(settings)?; - return Ok(SetupOutcome::Existing(destination)); + if std::fs::symlink_metadata(&destination).is_ok_and(|metadata| metadata.file_type().is_symlink()) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "refusing to replace a symbolic link at the Welcome notebook path")); } - fs_create_dir_all(notebooks_root)?; let staging = notebooks_root.join(format!(".{NOTEBOOK_NAME}-installing-{}", unique_suffix())); + let backup = notebooks_root.join(format!(".{NOTEBOOK_NAME}-backup-{}", unique_suffix())); fs_create_dir(&staging)?; - let result = copy_tree(payload, &staging).and_then(|()| { - if destination.exists() { - return Ok(SetupOutcome::Existing(destination.clone())); - } - match fs_rename(&staging, &destination) { - Ok(()) => Ok(SetupOutcome::Installed(destination.clone())), - Err(_error) if destination.exists() => Ok(SetupOutcome::Existing(destination.clone())), - Err(error) => Err(error), + if let Err(error) = copy_tree(payload, &staging) { + remove_tree_if_present(&staging); + return Err(error); + } + let had_previous = destination.exists(); + if had_previous { + fs_rename(&destination, &backup)?; + } + if let Err(error) = fs_rename(&staging, &destination) { + if had_previous { + let _ = fs_rename(&backup, &destination); } - }); - if result.is_err() { remove_tree_if_present(&staging); + return Err(error); } - let outcome = result?; - remove_tree_if_present(&staging); - mark_configured(settings)?; - Ok(outcome) + remove_tree_if_present(&backup); + Ok(SetupOutcome::Installed(destination)) } fn validate_payload(payload: &Path) -> io::Result<()> { - for relative in [ - Path::new("html/_node.toml"), - Path::new("cmgfm/_node.toml"), - Path::new("html/00-start/welcome/index.html"), - Path::new("cmgfm/00-start/welcome/index.md"), - ] { - if !payload.join(relative).is_file() { + for (format, page) in [("html", "00-start/welcome/index.html"), ("cmgfm", "00-start/welcome/index.md")] { + for relative in [Path::new(format).join("_node.toml"), Path::new(format).join(page)] { + if !payload.join(&relative).is_file() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("the User Assistance payload is incomplete: missing {}", relative.display()), + )); + } + } + let format_root = payload.join(format); + let language_count = std::fs::read_dir(&format_root)? + .filter_map(Result::ok) + .filter(|entry| { + if !entry.file_type().is_ok_and(|kind| kind.is_dir()) { + return false; + } + let name = entry.file_name(); + let Some(name) = name.to_str() else { return false }; + let Some((number, language)) = name.split_once('-') else { return false }; + matches!(number.parse::(), Ok(10..=23)) && language.len() == 2 && language.bytes().all(|byte| byte.is_ascii_lowercase()) + }) + .count(); + if language_count != 13 { return Err(io::Error::new( io::ErrorKind::InvalidData, - format!("the User Assistance payload is incomplete: missing {}", relative.display()), + format!("the {format} User Assistance notebook has {language_count} language folders; expected 13"), )); } } @@ -116,18 +120,6 @@ fn remove_tree_if_present(path: &Path) { } } -fn marker_path(settings: &Settings) -> PathBuf { - settings.path().with_file_name(SETUP_MARKER) -} - -fn mark_configured(settings: &Settings) -> io::Result<()> { - let marker = marker_path(settings); - if let Some(parent) = marker.parent() { - std::fs::create_dir_all(parent)?; - } - std::fs::write(marker, b"User Assistance setup completed.\n") -} - #[cfg(test)] mod tests { use super::*; @@ -136,21 +128,37 @@ mod tests { fn payload(root: &Path) -> PathBuf { let source = root.join("payload"); - fs::create_dir_all(source.join("html/00-start/welcome")).expect("create HTML payload"); - fs::create_dir_all(source.join("cmgfm/00-start/welcome")).expect("create CMGFM payload"); - fs::write(source.join("html/_node.toml"), "kind = \"notebook\"\nformat = \"html\"\n").expect("HTML notebook metadata"); - fs::write(source.join("cmgfm/_node.toml"), "kind = \"notebook\"\nformat = \"cmgfm\"\n").expect("CMGFM notebook metadata"); - fs::write(source.join("html/00-start/welcome/index.html"), "authored HTML").expect("HTML page"); - fs::write(source.join("cmgfm/00-start/welcome/index.md"), "authored CMGFM").expect("CMGFM page"); + for (format, filename, content) in [("html", "index.html", "HTML format"), ("cmgfm", "index.md", "CMGFM format")] { + let variant = source.join(format); + fs::create_dir_all(variant.join("00-start/welcome")).expect("create format payload"); + fs::write(variant.join("_node.toml"), format!("kind = \"notebook\"\nformat = \"{format}\"\n")).expect("notebook metadata"); + fs::write(variant.join("00-start/welcome").join(filename), content).expect("welcome page"); + for (number, language) in [ + (10, "en"), + (11, "es"), + (12, "fr"), + (13, "de"), + (14, "hi"), + (15, "ru"), + (16, "zh"), + (17, "ja"), + (18, "ko"), + (20, "ar"), + (21, "fa"), + (22, "ur"), + (23, "he"), + ] { + fs::create_dir_all(variant.join(format!("{number}-{language}"))).expect("create language folder"); + } + } source } - fn fixture() -> (TempDir, Settings, PathBuf, PathBuf) { + fn fixture() -> (TempDir, PathBuf, PathBuf) { let temp = TempDir::new("notecraft-setup"); let source = payload(temp.path()); - let settings = Settings::at(temp.path().join("settings.toml")); let notebooks = temp.path().join("Documents/NoteCraft"); - (temp, settings, source, notebooks) + (temp, source, notebooks) } #[test] @@ -178,58 +186,71 @@ mod tests { #[test] fn official_generated_demo_is_a_valid_setup_payload() { let payload = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/demo/DemoNotebook"); - validate_payload(&payload).expect("official generated notebook has both supported formats"); + validate_payload(&payload).expect("official generated HTML and CMGFM notebooks are a valid setup payload"); } #[test] - fn installs_the_separate_payload_into_the_normal_notebooks_folder() { - let (_temp, settings, source, notebooks) = fixture(); - let outcome = install_if_needed(&settings, Some(&source), ¬ebooks).expect("install payload"); + fn refreshes_both_demo_formats_and_preserves_other_notebooks() { + let (_temp, source, notebooks) = fixture(); + let other = notebooks.join("My notebook"); + fs::create_dir_all(&other).expect("create user notebook"); + fs::write(other.join("notes.txt"), "user content").expect("write user content"); + let outcome = refresh_demo(&source, ¬ebooks).expect("install payload"); let destination = notebooks.join(NOTEBOOK_NAME); assert_eq!(outcome, SetupOutcome::Installed(destination.clone())); - assert_eq!(fs::read(destination.join("html/00-start/welcome/index.html")).expect("HTML"), b"authored HTML"); - assert_eq!(fs::read(destination.join("cmgfm/00-start/welcome/index.md")).expect("CMGFM"), b"authored CMGFM"); + assert_eq!(fs::read(destination.join("html/00-start/welcome/index.html")).expect("HTML format"), b"HTML format"); + assert_eq!(fs::read(destination.join("cmgfm/00-start/welcome/index.md")).expect("CMGFM format"), b"CMGFM format"); + assert_eq!(fs::read(other.join("notes.txt")).expect("user content"), b"user content"); } #[test] - fn an_existing_notebook_is_preserved_and_marked_configured() { - let (_temp, settings, source, notebooks) = fixture(); + fn an_existing_demo_is_replaced_but_sibling_notebooks_are_untouched() { + let (_temp, source, notebooks) = fixture(); let destination = notebooks.join(NOTEBOOK_NAME); - fs::create_dir_all(&destination).expect("create existing notebook"); - fs::write(destination.join("user-edit.txt"), "keep my edit").expect("write user edit"); - let outcome = install_if_needed(&settings, Some(&source), ¬ebooks).expect("keep existing notebook"); - assert_eq!(outcome, SetupOutcome::Existing(destination.clone())); - assert_eq!(fs::read(destination.join("user-edit.txt")).expect("user edit"), b"keep my edit"); - assert!(marker_path(&settings).is_file()); + fs::create_dir_all(destination.join("00-start/welcome")).expect("create existing demo"); + fs::write(destination.join("old-page.txt"), "old version").expect("write old demo"); + let other = notebooks.join("Work"); + fs::create_dir_all(&other).expect("create user notebook"); + fs::write(other.join("notes.txt"), "keep my notes").expect("write user notes"); + + let html = source.join("html/00-start/welcome/index.html"); + fs::write(html, "updated HTML").expect("update payload"); + let outcome = refresh_demo(&source, ¬ebooks).expect("replace existing demo"); + assert_eq!(outcome, SetupOutcome::Installed(destination.clone())); + assert!(!destination.join("old-page.txt").exists(), "stale demo data is removed"); + assert_eq!(fs::read(destination.join("html/00-start/welcome/index.html")).expect("new demo"), b"updated HTML"); + assert_eq!(fs::read(other.join("notes.txt")).expect("user notes"), b"keep my notes"); } #[test] - fn a_user_deletion_is_not_repaired_after_setup_was_completed() { - let (_temp, settings, source, notebooks) = fixture(); + fn a_missing_demo_is_recreated_on_next_launch() { + let (_temp, source, notebooks) = fixture(); let destination = notebooks.join(NOTEBOOK_NAME); - assert_eq!(install_if_needed(&settings, Some(&source), ¬ebooks).expect("initial install"), SetupOutcome::Installed(destination.clone())); + assert_eq!(refresh_demo(&source, ¬ebooks).expect("initial install"), SetupOutcome::Installed(destination.clone())); fs::remove_dir_all(&destination).expect("user deletes the notebook"); - settings.reset().expect("reset app preferences"); - assert_eq!(install_if_needed(&settings, Some(&source), ¬ebooks).expect("do not repair deletion"), SetupOutcome::AlreadyConfigured); - assert!(!destination.exists(), "the app installer must not recreate user-deleted content"); + assert_eq!(refresh_demo(&source, ¬ebooks).expect("refresh deleted demo"), SetupOutcome::Installed(destination.clone())); + assert!(destination.join("html/00-start/welcome/index.html").is_file(), "the app recreates its managed demo"); } #[test] - fn an_omitted_payload_is_a_normal_no_demo_setup() { - let (_temp, settings, _source, notebooks) = fixture(); - assert_eq!(install_if_needed(&settings, None, ¬ebooks).expect("optional payload may be omitted"), SetupOutcome::NoPayload); - assert!(!notebooks.exists(), "missing optional payload creates no notebook root"); + fn an_incomplete_payload_fails_without_replacing_the_existing_demo() { + let (_temp, source, notebooks) = fixture(); + fs::create_dir_all(notebooks.join(NOTEBOOK_NAME)).expect("create current demo"); + fs::write(notebooks.join(NOTEBOOK_NAME).join("keep.txt"), "current").expect("write current demo"); + fs::remove_file(source.join("html/00-start/welcome/index.html")).expect("remove required HTML page"); + assert_eq!(refresh_demo(&source, ¬ebooks).expect_err("reject incomplete payload").kind(), io::ErrorKind::InvalidData); + assert_eq!(fs::read(notebooks.join(NOTEBOOK_NAME).join("keep.txt")).expect("current demo"), b"current"); } #[test] - fn an_incomplete_payload_fails_without_leaving_a_partial_notebook() { - let (_temp, settings, source, notebooks) = fixture(); - fs::remove_file(source.join("cmgfm/00-start/welcome/index.md")).expect("remove required format page"); - assert_eq!( - install_if_needed(&settings, Some(&source), ¬ebooks).expect_err("reject incomplete payload").kind(), - io::ErrorKind::InvalidData - ); - assert!(!notebooks.join(NOTEBOOK_NAME).exists()); - assert_eq!(settings.get(SETUP_MARKER), None); + fn a_payload_missing_a_language_is_rejected_before_replacing_the_current_demo() { + let (_temp, source, notebooks) = fixture(); + let destination = notebooks.join(NOTEBOOK_NAME); + fs::create_dir_all(&destination).expect("create current demo"); + fs::write(destination.join("keep.txt"), "current").expect("write current demo"); + fs::remove_dir_all(source.join("html/23-he")).expect("remove one generated language"); + + assert_eq!(refresh_demo(&source, ¬ebooks).expect_err("reject incomplete languages").kind(), io::ErrorKind::InvalidData); + assert_eq!(fs::read(destination.join("keep.txt")).expect("current demo"), b"current"); } } diff --git a/apps/notecraft-setup/src/main.rs b/apps/notecraft-setup/src/main.rs index 7702cec1..898ad762 100644 --- a/apps/notecraft-setup/src/main.rs +++ b/apps/notecraft-setup/src/main.rs @@ -1,7 +1,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![cfg_attr(target_os = "windows", windows_subsystem = "windows")] -use notecraft_setup::{SetupOutcome, install_if_needed}; +use notecraft_setup::{SetupOutcome, refresh_demo}; use notecraft_store::{Settings, settings::default_notebooks_dir}; use std::path::{Path, PathBuf}; #[cfg(not(target_os = "macos"))] @@ -59,8 +59,9 @@ fn launch_desktop_app(executable: &Path) { }; let settings = Settings::default_location(); let payload = locate_payload(executable); + let payload = payload.as_deref().unwrap_or_else(|| fail("The generated Welcome notebook is missing from this installation.")); let notebooks = notecraft_store::settings::configured_notebooks_dir(&settings).unwrap_or_else(default_notebooks_dir); - let outcome = match install_if_needed(&settings, payload.as_deref(), ¬ebooks) { + let outcome = match refresh_demo(payload, ¬ebooks) { Ok(outcome) => outcome, Err(error) => fail(&format!("The User Assistance notebook could not be installed: {error}")), }; @@ -68,12 +69,8 @@ fn launch_desktop_app(executable: &Path) { let mut command = Command::new(app); let args: Vec = std::env::args().skip(1).collect(); if args.is_empty() { - match outcome { - SetupOutcome::Installed(path) | SetupOutcome::Existing(path) => { - command.arg("--open").arg(path); - } - SetupOutcome::AlreadyConfigured | SetupOutcome::NoPayload => {} - } + let SetupOutcome::Installed(path) = outcome; + command.arg("--open").arg(path); } else { command.args(args); } @@ -93,24 +90,10 @@ fn install_from_dmg(executable: &Path) { show_notice("The Welcome notebook is not included in this NoteCraft disk image. NoteCraft is ready to use."); return; }; - let prompt = format!("Install the optional Welcome notebook in {}? Existing notebook data will be left unchanged.", notebooks.display()); - if rfd::MessageDialog::new() - .set_level(rfd::MessageLevel::Info) - .set_buttons(rfd::MessageButtons::YesNo) - .set_title("Install NoteCraft Welcome Notebook") - .set_description(&prompt) - .show() - != rfd::MessageDialogResult::Yes - { - return; - } - match install_if_needed(&settings, Some(&payload), ¬ebooks) { + match refresh_demo(&payload, ¬ebooks) { Ok(SetupOutcome::Installed(path)) => { - show_notice(&format!("The Welcome notebook was installed in {}. You can now open NoteCraft from Applications.", path.display())) + show_notice(&format!("The Welcome notebook was refreshed in {}. You can now open NoteCraft from Applications.", path.display())) } - Ok(SetupOutcome::Existing(path)) => show_notice(&format!("A Welcome notebook already exists in {}. It was left unchanged.", path.display())), - Ok(SetupOutcome::AlreadyConfigured) => show_notice("Welcome notebook setup has already run. A notebook deleted later is not recreated."), - Ok(SetupOutcome::NoPayload) => show_notice("The Welcome notebook is not included in this disk image. NoteCraft is ready to use."), Err(error) => fail(&format!("The Welcome notebook could not be installed: {error}")), } } diff --git a/apps/notecraft/Cargo.toml b/apps/notecraft/Cargo.toml index 2aeacfc7..8a909836 100644 --- a/apps/notecraft/Cargo.toml +++ b/apps/notecraft/Cargo.toml @@ -15,6 +15,7 @@ workspace = true notecraft-engine = { workspace = true } notecraft-store = { workspace = true } notecraft-ui-egui = { workspace = true } +notecraft-setup = { path = "../notecraft-setup" } eframe = { workspace = true, features = ["clipboard"] } egui = { workspace = true } image = { workspace = true } diff --git a/apps/notecraft/src/main.rs b/apps/notecraft/src/main.rs index 302effcb..c3c2d2c2 100644 --- a/apps/notecraft/src/main.rs +++ b/apps/notecraft/src/main.rs @@ -70,6 +70,27 @@ fn should_remember_notebooks_root(root: &std::path::Path) -> bool { !root.starts_with(temp) } +/// Locates the generated HTML and CMGFM demo payload installed beside the app. +fn demo_payload(_executable: &std::path::Path) -> Option { + #[cfg(target_os = "windows")] + let installed = _executable.parent()?.join("demo").join("welcome-to-notecraft"); + + #[cfg(target_os = "linux")] + let installed = if let Some(appdir) = std::env::var_os("APPDIR") { + PathBuf::from(appdir).join("usr/share/notecraft/demo/welcome-to-notecraft") + } else { + PathBuf::from("/usr/share/notecraft/demo/welcome-to-notecraft") + }; + + #[cfg(target_os = "macos")] + let installed = _executable.parent()?.parent()?.join("Resources/demo/welcome-to-notecraft"); + + #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))] + let installed = _executable.parent()?.join("demo").join("welcome-to-notecraft"); + + if installed.is_dir() { Some(installed) } else { Some(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../docs/demo/DemoNotebook")) } +} + fn flag_value(args: &[String], name: &str) -> Option { args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned() } @@ -140,6 +161,15 @@ fn main() -> eframe::Result { } let root = notebooks_dir(&args); applog::info(&format!("notebooks folder: {}", root.display())); + let executable = match std::env::current_exe() { + Ok(path) => path, + Err(error) => fail(&format!("Could not locate the generated Welcome notebook payload: {error}")), + }; + let payload = demo_payload(&executable).unwrap_or_else(|| fail("Could not locate the generated Welcome notebook payload.")); + if let Err(error) = notecraft_setup::refresh_demo(&payload, &root) { + applog::line("ERROR", &format!("cannot refresh the managed Welcome notebook: {error}")); + fail(&format!("NoteCraft could not create or refresh the Welcome notebook: {error}")); + } let session = match Session::new(&root, Settings::default_location()) { Ok(s) => s, Err(e) => { @@ -159,8 +189,7 @@ fn main() -> eframe::Result { let _ = session.settings.set("privacy_welcome_seen", ""); applog::info("First-use flag set: privacy welcome dialog will show"); } - // Notebook setup is owned by the platform installer helper. This process only discovers - // notebooks from the normal root and opens a path the user or installer explicitly names. + // The app refreshes its own Welcome notebook before discovery; every other notebook remains user-owned. let mut startup_alerts: Vec<(&str, String)> = Vec::new(); // NoteCraft draws its own title bar unless the settings say the system's is wanted. diff --git a/crates/engine/src/sample.rs b/crates/engine/src/sample.rs index 642b86f5..71330068 100644 --- a/crates/engine/src/sample.rs +++ b/crates/engine/src/sample.rs @@ -1,5 +1,5 @@ -//! Sample notebooks: a small, fixed set of content that shows every feature. Used by the -//! tests, by the headless screenshot runner, by `notecraft-cli sample` and by the demo. +//! Generic sample notebooks used by tests, the headless screenshot runner, and +//! `notecraft-cli sample`. The release Welcome notebook is authored separately under `docs/demo`. use crate::{Output, Params, Session}; use std::path::PathBuf; diff --git a/docs/demo/scripts/src/generator.rs b/docs/demo/scripts/src/generator.rs new file mode 100644 index 00000000..355a8b0b --- /dev/null +++ b/docs/demo/scripts/src/generator.rs @@ -0,0 +1,1100 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +//! Builds full HTML and CMGFM Welcome notebooks under `docs/demo/DemoNotebook` from `docs/demo/scripts/content`. +//! +//! The two notebooks contain the same tour in thirteen languages. Every page and asset is +//! converted to the notebook's one format. Both generated formats are bundled by installers and +//! refreshed into the app-managed Welcome notebook at startup. +//! +//! The output is deterministic: the same content gives the same bytes, so `cargo xtask +//! demo-check` can fail when the checked-in notebook is older than its content. +//! +//! ```text +//! cargo xtask demo # build docs/demo/DemoNotebook/html and /cmgfm +//! cargo xtask demo html # build only docs/demo/DemoNotebook/html +//! cargo xtask demo cmgfm # build only docs/demo/DemoNotebook/cmgfm +//! cargo xtask demo both # explicitly build both formats +//! cargo xtask demo-check # build to a scratch folder and compare, without writing +//! ``` + +use notecraft_model::{kv, names}; +use notecraft_store::check; +use notecraft_store::links::{self, Link}; +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; + +const NOTEBOOK_TITLE: &str = "Welcome to NoteCraft"; +const VERSION_MARK: &str = "{{version}}"; +/// Every node carries this date, so a rebuild changes nothing but what the content changed. +const DATE: &str = "2026-10-18T00:00:00Z"; +const START_FOLDER: &str = "00-start"; +const START_TITLE: &str = "Start here"; +const HOW_TO_FOLDER: &str = "how-to"; +/// Put into the start page where the list of languages goes. +const LANGUAGES_MARK: &str = "{{languages}}"; + +/// One language of the tour. +struct Language { + /// ISO 639-1 code, also the content folder and part of the group's folder name. + code: &'static str, + /// The language's own name for itself, shown as the group's title and as the link. + name: &'static str, + /// Its English name, shown beside the link for a reader who cannot read the script. + english: &'static str, + /// The title of the How to section in that language. + how_to: &'static str, + rtl: bool, + /// The group's folder number: `10-en`, `20-ar`. Also decides its order in the tree. + number: u32, + color: &'static str, +} + +/// The thirteen languages the owner chose, left-to-right ones first. The How to titles are +/// the plain word for a short guide in each language; a native reader may improve them. +const LANGUAGES: &[Language] = &[ + Language { code: "en", name: "English", english: "English", how_to: "How to", rtl: false, number: 10, color: "purple" }, + Language { code: "es", name: "Español", english: "Spanish", how_to: "Cómo hacer", rtl: false, number: 11, color: "blue" }, + Language { code: "fr", name: "Français", english: "French", how_to: "Comment faire", rtl: false, number: 12, color: "teal" }, + Language { code: "de", name: "Deutsch", english: "German", how_to: "Anleitung", rtl: false, number: 13, color: "green" }, + Language { + code: "hi", name: "हिन्दी", english: "Hindi", how_to: "कैसे करें", rtl: false, number: 14, color: "yellow" + }, + Language { code: "ru", name: "Русский", english: "Russian", how_to: "Как сделать", rtl: false, number: 15, color: "orange" }, + Language { code: "zh", name: "中文(简体)", english: "Chinese, Simplified", how_to: "使用指南", rtl: false, number: 16, color: "red" }, + Language { code: "ja", name: "日本語", english: "Japanese", how_to: "使い方", rtl: false, number: 17, color: "magenta" }, + Language { code: "ko", name: "한국어", english: "Korean", how_to: "사용 방법", rtl: false, number: 18, color: "gray" }, + Language { code: "ar", name: "العربية", english: "Arabic", how_to: "كيف", rtl: true, number: 20, color: "purple" }, + Language { code: "fa", name: "فارسی", english: "Persian", how_to: "راهنما", rtl: true, number: 21, color: "blue" }, + Language { code: "ur", name: "اردو", english: "Urdu", how_to: "طریقہ", rtl: true, number: 22, color: "teal" }, + Language { code: "he", name: "עברית", english: "Hebrew", how_to: "איך", rtl: true, number: 23, color: "green" }, +]; + +impl Language { + fn folder(&self) -> String { + format!("{}-{}", self.number, self.code) + } +} + +/// One page as read from the content folder. +#[derive(Debug, Clone, PartialEq, Eq)] +struct Source { + /// From the file name: `20-write-a-page.md` is order 20, folder `write-a-page`. + order: u32, + slug: String, + title: String, + html: bool, + /// `rtl` or `ltr` when the front matter says; otherwise the language decides. + dir: Option, + /// The paragraphs this page justifies, by their position among its blocks, as the + /// page's head records them (`notecraft_model::justify`). Checked against the body when + /// the file is read, so a page edited without moving the number fails the build rather + /// than quietly justifying the wrong paragraph. + justify: Option, + body: String, +} + +/// What a build made, for the report and the tests. +#[derive(Debug, Default)] +struct Built { + languages: Vec, + pages: usize, +} + +pub(crate) fn run() -> ExitCode { + let task = std::env::args().nth(1).unwrap_or_else(|| "build".to_string()); + let selection = std::env::args().nth(2).unwrap_or_else(|| "both".to_string()); + let here = std::env::var("CARGO_MANIFEST_DIR").map(PathBuf::from).unwrap_or_else(|_| PathBuf::from(".")); + let content = here.join("content"); + // The pictures a demo page shows live with the repository's other art, attributed + // there: `docs/demo/scripts` is three levels down from the root. + let art = here.parent().and_then(|p| p.parent()).and_then(|p| p.parent()).map(|r| r.join("assets").join("demo")).unwrap_or_default(); + let out = here.parent().map(|p| p.join("DemoNotebook")).unwrap_or_else(|| PathBuf::from("DemoNotebook")); + let result = match task.as_str() { + "build" => workspace_version(&here).and_then(|v| { + let formats = selected_formats(&selection)?; + build_in_place(&content, &out, &art, &v, &formats) + }), + "check" => workspace_version(&here).and_then(|v| check_in_place(&content, &out, &art, &v)), + other => Err(format!("unknown task '{other}'. Tasks: build check")), + }; + match result { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("error: {e}"); + ExitCode::FAILURE + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum DemoFormat { + Html, + Cmgfm, +} + +fn selected_formats(selection: &str) -> Result, String> { + match selection { + "html" => Ok(vec![DemoFormat::Html]), + "cmgfm" => Ok(vec![DemoFormat::Cmgfm]), + "both" => Ok(vec![DemoFormat::Html, DemoFormat::Cmgfm]), + other => Err(format!("unknown format '{other}'. Choose html, cmgfm, or both")), + } +} + +fn workspace_version(here: &Path) -> Result { + let root = here.parent().and_then(Path::parent).and_then(Path::parent).ok_or_else(|| "cannot find repository root".to_string())?; + let manifest = fs::read_to_string(root.join("Cargo.toml")).map_err(|e| format!("read workspace manifest: {e}"))?; + let mut in_section = false; + for line in manifest.lines() { + let trimmed = line.trim(); + if trimmed.starts_with('[') { + in_section = trimmed == "[workspace.package]"; + } else if in_section + && let Some(rest) = trimmed.strip_prefix("version") + && let Some(value) = rest.trim_start().strip_prefix('=') + { + let version = value.trim().trim_matches('"'); + if !version.is_empty() { + return Ok(version.to_string()); + } + } + } + Err("workspace package version is missing".into()) +} + +/// Builds into `out`, replacing what is there. Only a folder that holds this notebook (or +/// nothing) is replaced, so a wrong path cannot delete someone's notes. +fn build_in_place(content: &Path, out: &Path, art: &Path, version: &str, formats: &[DemoFormat]) -> Result<(), String> { + if out.exists() { + let old_node = notecraft_store::tree::read_node(out); + let old_layout = old_node.as_ref().is_some_and(|n| n.title == NOTEBOOK_TITLE); + let html_node = notecraft_store::tree::read_node(&out.join("html")); + let cmgfm_node = notecraft_store::tree::read_node(&out.join("cmgfm")); + let paired_layout = html_node.as_ref().is_some_and(|node| node.title == NOTEBOOK_TITLE) + && cmgfm_node.as_ref().is_some_and(|node| node.title == NOTEBOOK_TITLE); + let partial_layout = html_node.as_ref().is_some_and(|node| node.title == NOTEBOOK_TITLE) + || cmgfm_node.as_ref().is_some_and(|node| node.title == NOTEBOOK_TITLE); + let selected_layout = formats.iter().any(|format| { + let path = out.join(format.folder()); + notecraft_store::tree::read_node(&path).is_some_and(|node| node.title == NOTEBOOK_TITLE) + }); + let ours = old_layout || paired_layout || partial_layout || selected_layout; + let empty = fs::read_dir(out).map(|mut rd| rd.next().is_none()).unwrap_or(false); + if !ours && !empty { + return Err(format!("{} exists and is not the Welcome notebook; not touching it", out.display())); + } + fs::remove_dir_all(out).map_err(|e| format!("cannot clear {}: {e}", out.display()))?; + } + let built = build(content, out, art, version, formats)?; + for format in formats { + verify(&out.join(format.folder()))?; + } + if formats.len() == 2 { + verify_pair(out)?; + } + println!( + "demo: built {} format(s) with {} languages ({}) and {} pages per format", + out.display(), + built.languages.len(), + built.languages.join(", "), + built.pages + ); + Ok(()) +} + +/// Builds into a scratch folder and compares it with `out`, file by file. +fn check_in_place(content: &Path, out: &Path, art: &Path, version: &str) -> Result<(), String> { + let scratch = std::env::temp_dir().join(format!("notecraft-demo-check-{}", std::process::id())); + let _ = fs::remove_dir_all(&scratch); + let fresh = scratch.join("DemoNotebook"); + let both = selected_formats("both")?; + let result = build(content, &fresh, art, version, &both).and_then(|_| verify_pair(&fresh)).and_then(|()| { + let want = snapshot(&fresh)?; + let have = snapshot(out)?; + let mut differences: Vec = Vec::new(); + for (path, bytes) in &want { + match have.get(path) { + None => differences.push(format!("missing: {path}")), + Some(b) if b != bytes => differences.push(format!("differs: {path}")), + Some(_) => {} + } + } + for path in have.keys() { + if !want.contains_key(path) { + differences.push(format!("extra: {path}")); + } + } + if differences.is_empty() { + println!("demo-check: {} files, {} up to date with its content", want.len(), out.display()); + Ok(()) + } else { + Err(format!("{} is out of date; run `cargo xtask demo`:\n {}", out.display(), differences.join("\n "))) + } + }); + let _ = fs::remove_dir_all(&scratch); + result +} + +/// Writes the notebook under `out`, which must not exist yet. +fn build(content: &Path, out: &Path, art: &Path, version: &str, formats: &[DemoFormat]) -> Result { + fs::create_dir_all(out).map_err(|e| format!("cannot create {}: {e}", out.display()))?; + let mut full = Built::default(); + for format in formats { + let variant = build_variant(content, &out.join(format.folder()), art, format.page_format(), version)?; + if full.languages.is_empty() { + full.languages = variant.languages.clone(); + } + full.pages = variant.pages; + } + Ok(full) +} + +impl DemoFormat { + fn folder(self) -> &'static str { + match self { + Self::Html => "html", + Self::Cmgfm => "cmgfm", + } + } + + fn page_format(self) -> notecraft_model::PageFormat { + match self { + Self::Html => notecraft_model::PageFormat::Html, + Self::Cmgfm => notecraft_model::PageFormat::Cmgfm, + } + } +} + +fn build_variant(content: &Path, out: &Path, art: &Path, target_format: notecraft_model::PageFormat, version: &str) -> Result { + let mut built = Built::default(); + fs::create_dir_all(out).map_err(|e| format!("cannot create {}: {e}", out.display()))?; + let format_name = match target_format { + notecraft_model::PageFormat::Html => "html", + notecraft_model::PageFormat::Cmgfm => "cmgfm", + }; + write(&out.join("_node.toml"), &node_toml("notebook", NOTEBOOK_TITLE, &id_for("notebook"), 10, Some(format_name), Some("purple")))?; + + // The languages with content, in table order. + let present: Vec<&Language> = LANGUAGES.iter().filter(|l| content.join(l.code).is_dir()).collect(); + if present.is_empty() { + return Err(format!("no language folder under {}", content.display())); + } + + // Start here: one page, with the list of languages where the mark is. + let start = out.join(START_FOLDER); + fs::create_dir_all(&start).map_err(|e| format!("cannot create {}: {e}", start.display()))?; + write(&start.join("_node.toml"), &node_toml("section", START_TITLE, &id_for(START_FOLDER), 10, None, None))?; + let start_page = read_source(&content.join("start").join("welcome.html"), 10)?; + let start_page = + Source { title: start_page.title.replace(VERSION_MARK, version), body: start_page.body.replace(VERSION_MARK, version), ..start_page }; + let list = language_list(&present); + let body = start_page.body.replace(LANGUAGES_MARK, &list); + let start_page = convert_source(Source { body, ..start_page }, target_format, &content.join("start").join("welcome.html"))?; + write_page(&start.join("welcome"), &start_page, &id_for("start/welcome"), None, art)?; + built.pages += 1; + + for (n, lang) in present.iter().enumerate() { + let group = out.join(lang.folder()); + fs::create_dir_all(&group).map_err(|e| format!("cannot create {}: {e}", group.display()))?; + let order = 20 + 10 * n as u32; + write(&group.join("_node.toml"), &node_toml("section-group", lang.name, &id_for(&lang.folder()), order, None, Some(lang.color)))?; + let section = group.join(HOW_TO_FOLDER); + fs::create_dir_all(§ion).map_err(|e| format!("cannot create {}: {e}", section.display()))?; + write(§ion.join("_node.toml"), &node_toml("section", lang.how_to, &id_for(&format!("{}/how-to", lang.folder())), 10, None, None))?; + let sources = read_sources(&content.join(lang.code))?; + if sources.is_empty() { + return Err(format!("{}: no pages", content.join(lang.code).display())); + } + let default_dir = if lang.rtl { Some("rtl") } else { None }; + for s in &sources { + let id = id_for(&format!("{}/how-to/{}", lang.folder(), s.slug)); + let page = section.join(&s.slug); + // A page with ink names it, as every page with ink must: the folder and the + // page's own words have to agree. See docs/dom_serialization/page-model.md section 5. + let inked = matches!(s.slug.as_str(), "pictures-and-files" | "shapes" | "handwriting-and-drawing"); + let s = if inked { + Source { + body: format!( + "{} + +![Ink](ink.svg) +", + s.body.trim_end() + ), + ..s.clone() + } + } else { + s.clone() + }; + let source_path = content.join(lang.code).join(format!("{}-{}.{}", s.order, s.slug, if s.html { "html" } else { "md" })); + let s = convert_source(s, target_format, &source_path)?; + write_page(&page, &s, &id, default_dir, art)?; + // Keep the pictures-and-files sample, and add dedicated shape and handwriting + // pages to show that ink can be drawn and edited on a page. + if s.slug == "pictures-and-files" { + write_ink(&page)?; + } else if s.slug == "shapes" { + write_shapes_ink(&page)?; + } else if s.slug == "handwriting-and-drawing" { + write_handwriting_ink(&page)?; + } + built.pages += 1; + } + built.languages.push(lang.code.to_string()); + } + Ok(built) +} + +/// The bullet list on the start page: each language's own name as the link, its English +/// name after it, and a note on the ones that read right to left. +fn language_list(present: &[&Language]) -> String { + let mut out = String::new(); + for l in present { + let note = if l.rtl { ", right to left" } else { "" }; + // The English name only when it adds something: "English, English" would not. + let english = if l.english == l.name { String::new() } else { format!(", {}", l.english) }; + out.push_str(&format!("
  • {}{english}{note}
  • \n", l.folder(), l.name)); + } + out.trim_end().to_string() +} + +/// Writes one page folder: `index.md` or `index.html` with the page's metadata, and +/// every picture the page names, copied in from the repository's own `assets/demo`. +fn write_page(dir: &Path, s: &Source, id: &str, default_dir: Option<&str>, art: &Path) -> Result<(), String> { + fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?; + let dir_value = s.dir.as_deref().or(default_dir); + // A page carries its title in its head, and the window draws it above the words. A + // body that opens with that same title as a heading would show it twice, so the + // heading comes off here and the content files keep it for reading on their own. + let s = &Source { body: without_title_heading(&s.body, &s.title), ..s.clone() }; + copy_assets(dir, &s.body, art)?; + let look = look_of(&s.slug); + if s.html { + write(&dir.join("index.html"), &html_page(&s.title, id, s.order, dir_value, &s.body, look, s.justify.as_deref())) + } else { + write(&dir.join("index.md"), &markdown_page(&s.title, id, s.order, dir_value, &s.body, look, s.justify.as_deref())) + } +} + +/// Converts a source page into the selected notebook format without changing its blocks or layout. +fn convert_source(mut source: Source, target: notecraft_model::PageFormat, path: &Path) -> Result { + let input = if source.html { notecraft_model::PageFormat::Html } else { notecraft_model::PageFormat::Cmgfm }; + if input == target { + return Ok(source); + } + let (blocks, containers) = notecraft_formats::boxes::read(input, &source.body); + let body = notecraft_formats::boxes::write(target, &blocks, containers.as_deref()); + let (converted_blocks, converted_containers) = notecraft_formats::boxes::read(target, &body); + if blocks != converted_blocks || containers != converted_containers { + let difference = blocks + .iter() + .zip(&converted_blocks) + .enumerate() + .find(|(_, (left, right))| left != right) + .map(|(index, (left, right))| format!("block {index}: {left:?} -> {right:?}")) + .unwrap_or_else(|| format!("{} blocks -> {} blocks", blocks.len(), converted_blocks.len())); + return Err(format!( + "{}: converting to {target:?} changed page content or layout ({difference}; layout {containers:?} -> {converted_containers:?})", + path.display() + )); + } + if let Some(justify) = &source.justify { + check_justify(path, justify, target == notecraft_model::PageFormat::Html, &body)?; + } + source.body = body; + source.html = target == notecraft_model::PageFormat::Html; + Ok(source) +} + +/// A body without the heading that only repeats the page's title. +fn without_title_heading(body: &str, title: &str) -> String { + let mut offset = 0; + for line_with_end in body.split_inclusive('\n') { + let line = line_with_end.trim_end_matches(['\r', '\n']).trim(); + if line.is_empty() || (line.starts_with("![") && line.ends_with(')')) { + offset += line_with_end.len(); + continue; + } + let is_echo = + line.strip_prefix("# ").map(str::trim) == Some(title.trim()) || line.eq_ignore_ascii_case(&format!("

    {}

    ", title.trim())); + if !is_echo { + return body.to_string(); + } + let after_heading = offset + line_with_end.len(); + let tail = body[after_heading..].trim_start_matches(['\r', '\n']); + return format!("{}{tail}", &body[..offset]); + } + body.to_string() +} + +/// Copies every `assets/...` a page names into that page's own `assets` folder. +/// +/// A page owns its files, so each page that shows a picture gets its own copy rather than +/// linking across the notebook. The pictures themselves live in the repository under +/// `assets/demo`, attributed there, and this is the only place they are copied from: a +/// page that names one that is not there fails the build rather than shipping a hole. +fn copy_assets(dir: &Path, body: &str, art: &Path) -> Result<(), String> { + for target in link_targets(body) { + let Some(name) = target.strip_prefix("assets/") else { continue }; + if name.is_empty() || name.contains('/') || name.contains("..") { + return Err(format!("{}: {target} is not a plain file name", dir.display())); + } + let from = art.join(name); + if !from.is_file() { + return Err(format!("{}: nothing at {}", dir.display(), from.display())); + } + let assets = dir.join("assets"); + fs::create_dir_all(&assets).map_err(|e| format!("cannot create {}: {e}", assets.display()))?; + fs::copy(&from, assets.join(name)).map_err(|e| format!("cannot copy {}: {e}", from.display(),))?; + } + Ok(()) +} + +/// A drawing for a page: a few strokes written as NoteCraft's own ink file. +/// +/// The demo should show what the pen leaves behind, and a page with ink in the folder is +/// the only honest way to show it. The strokes are drawn here with the same crate the pen +/// uses, so the file the demo ships is the file the pen would have written. +fn write_ink(dir: &Path) -> Result<(), String> { + use notecraft_ink::{Dab, Drawing, Rgb, Stroke, Tool}; + let mut drawing = Drawing::new(820.0, 1100.0); + + // A hand-drawn underline under the page's first heading, and a tick beside it. + let mut line = Stroke::new(Tool::Highlighter, Rgb(0xFF, 0xDD, 0x33), 14.0); + for i in 0..=18 { + let t = i as f32 / 18.0; + line.add(Dab { x: 60.0 + t * 300.0, y: 96.0 + (t * 6.2).sin() * 2.5, pressure: 0.55 + t * 0.2 }); + } + drawing.add(line); + + // Two strokes, not more: a stroke is stored as a filled outline, and an outline is + // some 30 KB a stroke. Thirteen languages carry a copy of this page. + let mut tick = Stroke::new(Tool::Pen, Rgb(0x1E, 0x8A, 0x44), 3.5); + for i in 0..=6 { + let t = i as f32 / 6.0; + tick.add(Dab { x: 400.0 + t * 14.0, y: 84.0 + t * 16.0, pressure: 0.4 + t * 0.4 }); + } + for i in 1..=9 { + let t = i as f32 / 9.0; + tick.add(Dab { x: 414.0 + t * 26.0, y: 100.0 - t * 30.0, pressure: 0.8 - t * 0.3 }); + } + drawing.add(tick); + + let svg = notecraft_ink::svg::write(&drawing, notecraft_ink::svg::Flavour::Editable); + write(&dir.join("ink.svg"), &svg) +} + +/// A two-column sheet of every shape offered by the Draw tab. +fn write_shapes_ink(dir: &Path) -> Result<(), String> { + use notecraft_ink::{Drawing, Rgb, Stroke, Tool}; + let mut drawing = Drawing::new(820.0, 800.0); + for (index, shape) in notecraft_ink::shapes::Shape::ALL.into_iter().enumerate() { + let column = index % 2; + let row = index / 2; + let x = 160.0 + column as f32 * 420.0; + let y = 300.0 + row as f32 * 100.0; + let dabs = notecraft_ink::shapes::trace(shape, (x, y), (x + 80.0, y + 60.0), 0.75); + let mut stroke = Stroke::new(Tool::Pen, Rgb(0x28, 0x57, 0x8a), 4.0); + for dab in dabs { + stroke.add(dab); + } + drawing.add(stroke); + } + let svg = notecraft_ink::svg::write(&drawing, notecraft_ink::svg::Flavour::Editable); + write(&dir.join("ink.svg"), &svg) +} + +/// Handwritten words and a small landscape, saved as editable pen strokes. +fn write_handwriting_ink(dir: &Path) -> Result<(), String> { + use notecraft_ink::{Dab, Drawing, Rgb, Stroke, Tool}; + let mut drawing = Drawing::new(820.0, 700.0); + let mut x = 70.0; + for ch in "Meet me at 3".chars() { + if ch == ' ' { + x += 24.0; + continue; + } + let paths: &[&[(f32, f32)]] = match ch { + 'M' => &[&[(0.0, 42.0), (0.0, 0.0), (14.0, 22.0), (28.0, 0.0), (28.0, 42.0)]], + 'e' => &[&[ + (27.0, 21.0), + (4.0, 21.0), + (6.0, 13.0), + (14.0, 7.0), + (22.0, 10.0), + (27.0, 18.0), + (25.0, 30.0), + (17.0, 37.0), + (9.0, 35.0), + (4.0, 28.0), + ]], + 't' => &[&[(14.0, 1.0), (14.0, 33.0), (19.0, 38.0), (25.0, 35.0)], &[(3.0, 13.0), (24.0, 13.0)]], + 'm' => &[&[(3.0, 39.0), (3.0, 12.0), (9.0, 7.0), (15.0, 13.0), (15.0, 39.0)], &[(15.0, 13.0), (22.0, 7.0), (29.0, 13.0), (29.0, 39.0)]], + 'a' => &[&[ + (25.0, 14.0), + (20.0, 7.0), + (11.0, 7.0), + (4.0, 15.0), + (3.0, 28.0), + (10.0, 37.0), + (19.0, 35.0), + (25.0, 27.0), + (25.0, 7.0), + (25.0, 39.0), + ]], + '3' => &[&[ + (4.0, 8.0), + (13.0, 2.0), + (23.0, 7.0), + (24.0, 15.0), + (17.0, 20.0), + (10.0, 21.0), + (19.0, 22.0), + (26.0, 29.0), + (23.0, 37.0), + (13.0, 41.0), + (4.0, 36.0), + ]], + _ => &[], + }; + for path in paths { + let mut stroke = Stroke::new(Tool::Pen, Rgb(0x22, 0x4f, 0x78), 4.2); + for (index, (px, py)) in path.iter().enumerate() { + stroke.add(Dab { x: x + px * 1.25, y: 200.0 + py * 1.25, pressure: if index % 2 == 0 { 0.72 } else { 0.88 } }); + } + drawing.add(stroke); + } + x += 40.0; + } + + // A sun, rolling hills and lake ripples. + let mut sun = Stroke::new(Tool::Pen, Rgb(0xd0, 0x70, 0x32), 3.5); + for i in 0..=32 { + let angle = i as f32 / 32.0 * std::f32::consts::TAU; + sun.add(Dab { x: 640.0 + angle.cos() * 28.0, y: 340.0 + angle.sin() * 28.0, pressure: 0.7 }); + } + drawing.add(sun); + let lines: &[&[(f32, f32)]] = &[ + &[ + (60.0, 400.0), + (130.0, 360.0), + (200.0, 385.0), + (270.0, 325.0), + (350.0, 390.0), + (425.0, 340.0), + (505.0, 390.0), + (580.0, 360.0), + (670.0, 405.0), + (760.0, 370.0), + ], + &[(65.0, 435.0), (170.0, 415.0), (260.0, 440.0), (370.0, 415.0), (500.0, 440.0), (625.0, 417.0), (760.0, 440.0)], + &[(110.0, 500.0), (190.0, 490.0), (270.0, 502.0), (350.0, 490.0), (430.0, 502.0), (510.0, 490.0), (600.0, 502.0), (700.0, 490.0)], + &[(130.0, 545.0), (220.0, 535.0), (310.0, 547.0), (400.0, 535.0), (490.0, 547.0), (580.0, 535.0), (680.0, 547.0)], + ]; + for (index, line) in lines.iter().enumerate() { + let colour = if index < 2 { Rgb(0x37, 0x76, 0x52) } else { Rgb(0x28, 0x65, 0x91) }; + let mut stroke = Stroke::new(Tool::Pen, colour, 3.8); + for (i, (x, y)) in line.iter().enumerate() { + stroke.add(Dab { x: *x, y: *y, pressure: if i % 2 == 0 { 0.68 } else { 0.82 } }); + } + drawing.add(stroke); + } + let svg = notecraft_ink::svg::write(&drawing, notecraft_ink::svg::Flavour::Editable); + write(&dir.join("ink.svg"), &svg) +} + +/// A `_node.toml` in the form `docs/folder-format.md` section 4 describes. +fn node_toml(kind: &str, title: &str, id: &str, order: u32, format: Option<&str>, color: Option<&str>) -> String { + let mut s = format!("kind = {}\ntitle = {}\nid = {}\n", kv::quote(kind), kv::quote(title), kv::quote(id)); + if let Some(f) = format { + s.push_str(&format!("format = {}\n", kv::quote(f))); + } + s.push_str(&format!("order = {order}\n")); + if let Some(c) = color { + s.push_str(&format!("color = {}\n", kv::quote(c))); + } + s.push_str(&format!("created = {}\n", kv::quote(DATE))); + s +} + +/// A Markdown page with the front matter the store writes (section 3.2 of the format). +fn markdown_page(title: &str, id: &str, order: u32, dir: Option<&str>, body: &str, look: Look, justify: Option<&str>) -> String { + let mut front = format!("---\nid: {id}\ntitle: {}\norder: {order}\ncreated: {DATE}\nupdated: {DATE}\n", kv::quote(title)); + if let Some(d) = dir { + front.push_str(&format!("dir: {d}\n")); + } + if let Some(j) = justify { + front.push_str(&format!("justify: {j}\n")); + } + if let Some(p) = look.paper { + front.push_str(&format!("paper: {p}\n")); + } + if let Some(c) = look.colour { + front.push_str(&format!("page-color: {c}\n")); + } + front.push_str("tags: []\n---\n\n"); + format!("{front}{}\n", body.trim_end()) +} + +/// The paper a demo page is drawn on and the colour behind it, so the notebook shows what +/// a page can look like as well as what it can say. +#[derive(Clone, Copy, Default)] +struct Look { + paper: Option<&'static str>, + colour: Option<&'static str>, +} + +/// Which pages are given paper of their own, by the folder they are written to. The rest +/// are drawn on the plain page the window opens with. +fn look_of(slug: &str) -> Look { + match slug { + // The page about writing is on ruled paper, as a page for writing on would be. + "write-a-page" => Look { paper: Some("college"), colour: None }, + // The one about tags is squared, and a little warm, so the two show side by side + // in the tree what paper and page colour do. + "tag-a-line" => Look { paper: Some("grid-medium"), colour: Some("yellow") }, + // The one about making it yours is coloured, with no lines. + "make-it-yours" => Look { paper: None, colour: Some("teal") }, + _ => Look::default(), + } +} + +/// An HTML page with the metadata in `` tags (section 3.1 of the format). +fn html_page(title: &str, id: &str, order: u32, dir: Option<&str>, body: &str, look: Look, justify: Option<&str>) -> String { + let t = escape(title); + let mut head = format!( + "\n\n\n\n{t}\n\n\n\n\n" + ); + if let Some(d) = dir { + head.push_str(&format!("\n")); + } + if let Some(j) = justify { + head.push_str(&format!("\n")); + } + if let Some(p) = look.paper { + head.push_str(&format!("\n")); + } + if let Some(c) = look.colour { + head.push_str(&format!("\n")); + } + format!("{head}\n\n{}\n\n\n", body.trim()) +} + +fn escape(s: &str) -> String { + s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) +} + +/// Every `NN-slug.md` or `NN-slug.html` in `dir`, in order. +fn read_sources(dir: &Path) -> Result, String> { + let mut names: Vec = fs::read_dir(dir) + .map_err(|e| format!("{}: {e}", dir.display()))? + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .filter(|p| p.is_file() && p.extension().is_some_and(|x| x == "md" || x == "html")) + .collect(); + names.sort(); + let mut out = Vec::new(); + for p in names { + let stem = p.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); + let (number, slug) = stem.split_once('-').ok_or_else(|| format!("{}: name it NN-slug.md", p.display()))?; + let order: u32 = number.parse().map_err(|_| format!("{}: '{number}' is not a number", p.display()))?; + if let Err(why) = names::validate_component(slug) { + return Err(format!("{}: folder name '{slug}': {why}", p.display())); + } + let mut s = read_source(&p, order)?; + s.slug = slug.to_string(); + out.push(s); + } + Ok(out) +} + +/// One content file: a `title:` (and optional `dir:`) front matter, then the body. +fn read_source(path: &Path, order: u32) -> Result { + let text = fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; + let text = text.trim_start_matches('\u{feff}').replace("\r\n", "\n"); + let (front, body) = split_front(&text).ok_or_else(|| format!("{}: no front matter (a --- block with a title)", path.display()))?; + let title = front_value(front, "title").ok_or_else(|| format!("{}: front matter has no title", path.display()))?; + let dir = front_value(front, "dir"); + if let Some(d) = &dir + && d != "rtl" + && d != "ltr" + { + return Err(format!("{}: dir must be rtl or ltr, not '{d}'", path.display())); + } + let html = path.extension().is_some_and(|x| x == "html"); + let slug = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); + let body = body.trim_start_matches('\n').to_string(); + let justify = front_value(front, "justify"); + if let Some(line) = &justify { + check_justify(path, line, html, &body)?; + } + Ok(Source { order, slug, title, html, dir, justify, body }) +} + +/// A page says which of its paragraphs fill the column by their position among its blocks. +/// A number is only as good as the body it was counted against, so it is counted again here, +/// with the reader the editor itself uses: a number that has drifted onto a heading, a table +/// or off the end of the page stops the build. +fn check_justify(path: &Path, line: &str, html: bool, body: &str) -> Result<(), String> { + let marked = notecraft_model::justify::parse(line); + if marked.is_empty() { + return Err(format!("{}: justify is block numbers separated by commas, not '{line}'", path.display())); + } + let format = if html { notecraft_model::PageFormat::Html } else { notecraft_model::PageFormat::Cmgfm }; + let blocks = notecraft_formats::boxes::read(format, body).0; + for (at, _) in marked.blocks() { + match blocks.get(*at) { + Some(notecraft_formats::Block::Paragraph(_)) => {} + Some(other) => return Err(format!("{}: justify names block {at}, which is a {}, not a paragraph", path.display(), name_of(other))), + None => return Err(format!("{}: justify names block {at}, and the page has {} blocks", path.display(), blocks.len())), + } + } + Ok(()) +} + +/// What a block is, for an error message. +fn name_of(block: ¬ecraft_formats::Block) -> &'static str { + use notecraft_formats::Block; + match block { + Block::Heading { .. } => "heading", + Block::Paragraph(_) => "paragraph", + Block::Item { .. } => "list item", + Block::Quote(_) => "quote", + Block::Code { .. } => "code block", + Block::Table { .. } => "table", + Block::Image { .. } => "picture", + Block::MathBlock(_) => "equation", + _ => "block of another kind", + } +} + +/// The lines between the first two `---` lines, and the rest. +fn split_front(text: &str) -> Option<(&str, &str)> { + let rest = text.strip_prefix("---\n")?; + let end = rest.find("\n---\n")?; + Some((&rest[..end], &rest[end + 5..])) +} + +fn front_value(front: &str, key: &str) -> Option { + front.lines().find_map(|l| l.split_once(':').filter(|(k, _)| k.trim() == key).map(|(_, v)| v.trim().trim_matches('"').to_string())) +} + +/// A stable 20-hex-character id from a name: the shape the store uses, without the clock. +/// Two FNV-1a hashes over the name and its reverse, so two names never share an id by a +/// one-character slip. +fn id_for(name: &str) -> String { + fn fnv(bytes: impl Iterator) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for b in bytes { + h ^= u64::from(b); + h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + h + } + let a = fnv(name.bytes()); + let b = fnv(name.bytes().rev()); + format!("{a:016x}{:04x}", (b & 0xffff) as u16) +} + +/// The checker finds no problem, and every link in every page leads somewhere. +fn verify(out: &Path) -> Result<(), String> { + let report = check::check_tree(out); + if !report.problems.is_empty() { + let list: Vec = report.problems.iter().map(|p| format!("{}: {}", p.path.display(), p.message)).collect(); + return Err(format!("the checker found problems:\n {}", list.join("\n "))); + } + let root = out.parent().ok_or("the notebook has no parent folder")?; + let mut broken = Vec::new(); + let mut checked = 0usize; + for (page, text) in pages_under(out)? { + for href in link_targets(&text) { + checked += 1; + match links::resolve(root, &page, &href) { + Link::Node(_) | Link::File(_) | Link::Web(_) => {} + Link::Missing(p) => broken.push(format!("{} -> {href} (nothing at {})", page.display(), p.display())), + Link::Outside => broken.push(format!("{} -> {href} (outside the notebook)", page.display())), + } + } + } + if broken.is_empty() { + println!("demo: {} nodes, {checked} links, all resolve", report.nodes); + Ok(()) + } else { + Err(format!("broken links:\n {}", broken.join("\n "))) + } +} + +fn verify_pair(out: &Path) -> Result<(), String> { + verify(&out.join("html"))?; + verify(&out.join("cmgfm")) +} + +/// Every page folder under `dir` with the text of its file. +fn pages_under(dir: &Path) -> Result, String> { + let mut out = Vec::new(); + for child in notecraft_store::tree::child_dirs(dir) { + if let Some((_, file)) = notecraft_store::tree::page_file(&child) { + let text = fs::read_to_string(&file).map_err(|e| format!("{}: {e}", file.display()))?; + out.push((child.clone(), text)); + } + out.extend(pages_under(&child)?); + } + Ok(out) +} + +/// Link targets in a page: `](target)` in Markdown, `href="..."` and `src="..."` in HTML. +fn link_targets(text: &str) -> Vec { + let mut out = Vec::new(); + let mut rest = text; + while let Some(i) = rest.find("](") { + let after = &rest[i + 2..]; + let Some(end) = after.find(')') else { break }; + let target = after[..end].split_whitespace().next().unwrap_or(""); + if !target.is_empty() && !target.starts_with('#') { + out.push(target.to_string()); + } + rest = &after[end..]; + } + for attr in ["href=\"", "src=\""] { + let mut rest = text; + while let Some(i) = rest.find(attr) { + let after = &rest[i + attr.len()..]; + let Some(end) = after.find('"') else { break }; + let target = after[..end].trim(); + if !target.is_empty() && !target.starts_with('#') { + out.push(target.to_string()); + } + rest = &after[end..]; + } + } + out +} + +/// Every file under `dir` by its relative path, with its bytes. +fn snapshot(dir: &Path) -> Result>, String> { + fn walk(base: &Path, dir: &Path, out: &mut BTreeMap>) -> Result<(), String> { + let rd = fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + for e in rd.filter_map(|e| e.ok()) { + let p = e.path(); + if p.is_dir() { + walk(base, &p, out)?; + } else { + let rel = p.strip_prefix(base).unwrap_or(&p).to_string_lossy().replace('\\', "/"); + out.insert(rel, fs::read(&p).map_err(|e| format!("{}: {e}", p.display()))?); + } + } + Ok(()) + } + let mut out = BTreeMap::new(); + if dir.exists() { + walk(dir, dir, &mut out)?; + } + Ok(out) +} + +fn write(path: &Path, text: &str) -> Result<(), String> { + fs::write(path, text).map_err(|e| format!("cannot write {}: {e}", path.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The repository's own art, which a page's pictures are copied from. + fn art_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..").join("..").join("..").join("assets").join("demo") + } + + fn content_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("content") + } + + fn scratch(label: &str) -> PathBuf { + let p = std::env::temp_dir().join(format!("notecraft-demo-test-{label}-{}", std::process::id())); + let _ = fs::remove_dir_all(&p); + p + } + + #[test] + fn ids_are_stable_and_distinct() { + assert_eq!(id_for("notebook"), id_for("notebook")); + assert_ne!(id_for("10-en/how-to/welcome"), id_for("11-es/how-to/welcome")); + assert_ne!(id_for("ab"), id_for("ba"), "the reverse hash tells anagrams apart"); + assert_eq!(id_for("x").len(), 20); + assert!(id_for("x").chars().all(|c| c.is_ascii_hexdigit())); + } + + #[test] + fn the_language_table_is_sound() { + let mut codes: Vec<&str> = LANGUAGES.iter().map(|l| l.code).collect(); + codes.sort_unstable(); + codes.dedup(); + assert_eq!(codes.len(), LANGUAGES.len(), "no code twice"); + let mut numbers: Vec = LANGUAGES.iter().map(|l| l.number).collect(); + numbers.sort_unstable(); + numbers.dedup(); + assert_eq!(numbers.len(), LANGUAGES.len(), "no folder number twice"); + assert_eq!(LANGUAGES.iter().filter(|l| l.rtl).count(), 4, "Arabic, Persian, Urdu, Hebrew"); + for l in LANGUAGES { + assert!(names::validate_component(&l.folder()).is_ok(), "{}", l.folder()); + assert!(["purple", "blue", "teal", "green", "yellow", "orange", "red", "magenta", "gray"].contains(&l.color), "{}: {}", l.code, l.color); + } + } + + #[test] + fn content_files_parse_and_name_their_folders() { + let en = read_sources(&content_dir().join("en")).expect("English content"); + assert!(en.len() >= 8, "eight pages at least, got {}", en.len()); + assert_eq!(en[0].slug, "welcome"); + assert_eq!(en[0].order, 10); + assert!(en.iter().any(|s| s.html), "one page shows the HTML format"); + let orders: Vec = en.iter().map(|s| s.order).collect(); + let mut sorted = orders.clone(); + sorted.sort_unstable(); + assert_eq!(orders, sorted, "files are read in order"); + let start = read_source(&content_dir().join("start").join("welcome.html"), 10).expect("HTML start page"); + assert!(start.html, "the notebook opens on its preferred format"); + assert!(start.body.contains(LANGUAGES_MARK)); + } + + #[test] + fn a_leading_banner_stays_first_without_repeating_the_page_title() { + let body = "![Banner](assets/banner-start.png)\n\n# Welcome to NoteCraft\n\nWords on the page.\n"; + assert_eq!(without_title_heading(body, "Welcome to NoteCraft"), "![Banner](assets/banner-start.png)\n\nWords on the page.\n"); + } + + #[test] + fn the_page_files_have_the_metadata_the_store_reads() { + let md = markdown_page("A \"quoted\" title", "abc", 20, Some("rtl"), "# Body\n", Look::default(), Some("2, 5")); + assert!(md.starts_with("---\nid: abc\ntitle: \"A \\\"quoted\\\" title\"\norder: 20\n")); + assert!(md.contains("\ndir: rtl\n")); + assert!(md.contains("\njustify: 2, 5\n"), "the justified paragraphs are a line in the head: {md}"); + assert!(md.ends_with("---\n\n# Body\n")); + let html = html_page("A ", "abc", 10, None, "

    x

    ", Look::default(), Some("0")); + + // A page given paper and a colour of its own carries both in its head. + let dressed = markdown_page( + "T", + "id", + 10, + None, + "words +", + Look { paper: Some("college"), colour: Some("yellow") }, + None, + ); + assert!( + dressed.contains( + " +paper: college +" + ) && dressed.contains( + " +page-color: yellow +" + ), + "{dressed}" + ); + let dressed_html = html_page("T", "id", 10, None, "

    x

    ", Look { paper: Some("grid-medium"), colour: None }, None); + assert!(dressed_html.contains("notecraft:paper"), "{dressed_html}"); + assert!(!dressed_html.contains("page-color"), "and says nothing about a colour it was not given"); + assert!(html.contains("A <b>")); + assert!(html.contains("name=\"notecraft:id\" content=\"abc\"")); + assert!(!html.contains("notecraft:dir")); + assert!(html.contains("notecraft:justify\" content=\"0\""), "the justified paragraphs are a meta tag: {html}"); + let node = node_toml("section-group", "Español", "id1", 30, None, Some("blue")); + assert_eq!( + node, + "kind = \"section-group\"\ntitle = \"Español\"\nid = \"id1\"\norder = 30\ncolor = \"blue\"\ncreated = \"2026-10-18T00:00:00Z\"\n" + ); + } + + #[test] + fn link_targets_are_found_in_both_formats() { + let md = "See [a](../a/) and [b](https://x.test \"t\") and [c](#top)."; + assert_eq!(link_targets(md), vec!["../a/", "https://x.test"]); + let html = "a t"; + assert_eq!(link_targets(html), vec!["../a/", "assets/p.png"]); + } + + /// Both full format editions build cleanly, contain the same tour, and rebuild identically. + #[test] + fn both_full_format_notebooks_build_cleanly_and_the_same_way_twice() { + let dir = scratch("build"); + let out = dir.join("DemoNotebook"); + let both = selected_formats("both").expect("both formats"); + let built = build(&content_dir(), &out, &art_dir(), "0.0.0-test", &both).expect("build"); + verify_pair(&out).expect("verify both notebooks"); + assert!(built.languages.contains(&"en".to_string())); + let html = out.join("html"); + let cmgfm = out.join("cmgfm"); + let html_tree = notecraft_store::tree::load_tree(&html).expect("HTML notebook tree"); + let cmgfm_tree = notecraft_store::tree::load_tree(&cmgfm).expect("CMGFM notebook tree"); + assert_eq!(html_tree.info.title, NOTEBOOK_TITLE); + assert_eq!(cmgfm_tree.info.title, NOTEBOOK_TITLE); + assert_eq!(html_tree.info.format, Some(notecraft_model::PageFormat::Html)); + assert_eq!(cmgfm_tree.info.format, Some(notecraft_model::PageFormat::Cmgfm)); + assert_eq!(html_tree.children.len(), cmgfm_tree.children.len(), "both editions have the same top-level sections"); + let first = html_tree.children.first().expect("a first child"); + assert_eq!(first.info.title, START_TITLE, "the start section sorts first"); + assert_eq!(first.children.len(), 1); + for (html_group, cmgfm_group) in html_tree.children.iter().zip(&cmgfm_tree.children) { + assert_eq!(html_group.info.title, cmgfm_group.info.title); + assert_eq!(html_group.children.len(), cmgfm_group.children.len(), "matching structure in {}", html_group.path.display()); + if html_group.info.kind == notecraft_model::NodeKind::SectionGroup { + assert_eq!(html_group.children.len(), 1, "one How to section in {}", html_group.path.display()); + assert!(html_group.children[0].children.len() >= 8, "the same pages in every language"); + } + } + let start = fs::read_to_string(html.join(START_FOLDER).join("welcome").join("index.html")).expect("HTML start page"); + assert!(start.contains("
  • English
  • "), "{start}"); + assert!(start.contains("
  • العربية, Arabic, right to left
  • "), "{start}"); + assert!(!start.contains(LANGUAGES_MARK)); + assert!(html.join("10-en").join("how-to").join("write-a-page").join("index.html").is_file()); + assert!(cmgfm.join("10-en").join("how-to").join("write-a-page").join("index.md").is_file()); + assert!(html.join("10-en").join("how-to").join("page-formats").join("index.html").is_file()); + let first_build = snapshot(&out).expect("snapshot"); + let again = dir.join("Again"); + build(&content_dir(), &again, &art_dir(), "0.0.0-test", &both).expect("build again"); + assert_eq!(snapshot(&again).expect("snapshot"), first_build, "deterministic"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_folder_that_is_not_the_welcome_notebook_is_left_alone() { + let dir = scratch("guard"); + let other = dir.join("Someone"); + fs::create_dir_all(&other).expect("dir"); + fs::write(other.join("_node.toml"), "kind = \"notebook\"\ntitle = \"Mine\"\nid = \"1\"\n").expect("node"); + let both = selected_formats("both").expect("both formats"); + let err = build_in_place(&content_dir(), &other, &art_dir(), "0.0.0-test", &both).expect_err("refused"); + assert!(err.contains("not touching it"), "{err}"); + assert!(other.join("_node.toml").is_file(), "nothing was deleted"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn individual_format_builds_write_only_the_selected_format() { + let dir = scratch("single-format"); + let out = dir.join("DemoNotebook"); + let html_only = selected_formats("html").expect("HTML selection"); + let built = build(&content_dir(), &out, &art_dir(), "0.0.0-test", &html_only).expect("HTML build"); + assert!(built.languages.contains(&"en".to_string())); + verify(&out.join("html")).expect("HTML notebook verifies"); + assert!(!out.join("cmgfm").exists(), "CMGFM is not generated for an HTML-only request"); + + let cmgfm_only = selected_formats("cmgfm").expect("CMGFM selection"); + let other_out = dir.join("CmgfmNotebook"); + build(&content_dir(), &other_out, &art_dir(), "0.0.0-test", &cmgfm_only).expect("CMGFM build"); + verify(&other_out.join("cmgfm")).expect("CMGFM notebook verifies"); + assert!(!other_out.join("html").exists(), "HTML is not generated for a CMGFM-only request"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn format_selection_rejects_unknown_values() { + let err = selected_formats("markdown").expect_err("unknown format rejected"); + assert!(err.contains("Choose html, cmgfm, or both"), "{err}"); + } +} diff --git a/docs/demo/scripts/src/main.rs b/docs/demo/scripts/src/main.rs index 8500427d..4f0d8193 100644 --- a/docs/demo/scripts/src/main.rs +++ b/docs/demo/scripts/src/main.rs @@ -1,1026 +1,5 @@ -#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -//! Builds full HTML and CMGFM Welcome notebooks under `docs/demo/DemoNotebook` from `docs/demo/scripts/content`. -//! -//! The two notebooks contain the same tour in thirteen languages. Every page and asset is -//! converted to the notebook's one format. The HTML copy is embedded in the app; the CMGFM -//! copy stays in the repository for comparison and testing. -//! -//! The output is deterministic: the same content gives the same bytes, so `cargo xtask -//! demo-check` can fail when the checked-in notebook is older than its content. -//! -//! ```text -//! cargo xtask demo # build docs/demo/DemoNotebook/html and /cmgfm -//! cargo xtask demo-check # build to a scratch folder and compare, without writing -//! ``` +mod generator; -use notecraft_model::{kv, names}; -use notecraft_store::check; -use notecraft_store::links::{self, Link}; -use std::collections::BTreeMap; -use std::fs; -use std::path::{Path, PathBuf}; -use std::process::ExitCode; - -const NOTEBOOK_TITLE: &str = "Welcome to NoteCraft"; -const VERSION_MARK: &str = "{{version}}"; -/// Every node carries this date, so a rebuild changes nothing but what the content changed. -const DATE: &str = "2026-10-18T00:00:00Z"; -const START_FOLDER: &str = "00-start"; -const START_TITLE: &str = "Start here"; -const HOW_TO_FOLDER: &str = "how-to"; -/// Put into the start page where the list of languages goes. -const LANGUAGES_MARK: &str = "{{languages}}"; - -/// One language of the tour. -struct Language { - /// ISO 639-1 code, also the content folder and part of the group's folder name. - code: &'static str, - /// The language's own name for itself, shown as the group's title and as the link. - name: &'static str, - /// Its English name, shown beside the link for a reader who cannot read the script. - english: &'static str, - /// The title of the How to section in that language. - how_to: &'static str, - rtl: bool, - /// The group's folder number: `10-en`, `20-ar`. Also decides its order in the tree. - number: u32, - color: &'static str, -} - -/// The thirteen languages the owner chose, left-to-right ones first. The How to titles are -/// the plain word for a short guide in each language; a native reader may improve them. -const LANGUAGES: &[Language] = &[ - Language { code: "en", name: "English", english: "English", how_to: "How to", rtl: false, number: 10, color: "purple" }, - Language { code: "es", name: "Español", english: "Spanish", how_to: "Cómo hacer", rtl: false, number: 11, color: "blue" }, - Language { code: "fr", name: "Français", english: "French", how_to: "Comment faire", rtl: false, number: 12, color: "teal" }, - Language { code: "de", name: "Deutsch", english: "German", how_to: "Anleitung", rtl: false, number: 13, color: "green" }, - Language { - code: "hi", name: "हिन्दी", english: "Hindi", how_to: "कैसे करें", rtl: false, number: 14, color: "yellow" - }, - Language { code: "ru", name: "Русский", english: "Russian", how_to: "Как сделать", rtl: false, number: 15, color: "orange" }, - Language { code: "zh", name: "中文(简体)", english: "Chinese, Simplified", how_to: "使用指南", rtl: false, number: 16, color: "red" }, - Language { code: "ja", name: "日本語", english: "Japanese", how_to: "使い方", rtl: false, number: 17, color: "magenta" }, - Language { code: "ko", name: "한국어", english: "Korean", how_to: "사용 방법", rtl: false, number: 18, color: "gray" }, - Language { code: "ar", name: "العربية", english: "Arabic", how_to: "كيف", rtl: true, number: 20, color: "purple" }, - Language { code: "fa", name: "فارسی", english: "Persian", how_to: "راهنما", rtl: true, number: 21, color: "blue" }, - Language { code: "ur", name: "اردو", english: "Urdu", how_to: "طریقہ", rtl: true, number: 22, color: "teal" }, - Language { code: "he", name: "עברית", english: "Hebrew", how_to: "איך", rtl: true, number: 23, color: "green" }, -]; - -impl Language { - fn folder(&self) -> String { - format!("{}-{}", self.number, self.code) - } -} - -/// One page as read from the content folder. -#[derive(Debug, Clone, PartialEq, Eq)] -struct Source { - /// From the file name: `20-write-a-page.md` is order 20, folder `write-a-page`. - order: u32, - slug: String, - title: String, - html: bool, - /// `rtl` or `ltr` when the front matter says; otherwise the language decides. - dir: Option, - /// The paragraphs this page justifies, by their position among its blocks, as the - /// page's head records them (`notecraft_model::justify`). Checked against the body when - /// the file is read, so a page edited without moving the number fails the build rather - /// than quietly justifying the wrong paragraph. - justify: Option, - body: String, -} - -/// What a build made, for the report and the tests. -#[derive(Debug, Default)] -struct Built { - languages: Vec, - pages: usize, -} - -fn main() -> ExitCode { - let task = std::env::args().nth(1).unwrap_or_else(|| "build".to_string()); - let here = std::env::var("CARGO_MANIFEST_DIR").map(PathBuf::from).unwrap_or_else(|_| PathBuf::from(".")); - let content = here.join("content"); - // The pictures a demo page shows live with the repository's other art, attributed - // there: `docs/demo/scripts` is three levels down from the root. - let art = here.parent().and_then(|p| p.parent()).and_then(|p| p.parent()).map(|r| r.join("assets").join("demo")).unwrap_or_default(); - let out = here.parent().map(|p| p.join("DemoNotebook")).unwrap_or_else(|| PathBuf::from("DemoNotebook")); - let result = match task.as_str() { - "build" => workspace_version(&here).and_then(|v| build_in_place(&content, &out, &art, &v)), - "check" => workspace_version(&here).and_then(|v| check_in_place(&content, &out, &art, &v)), - other => Err(format!("unknown task '{other}'. Tasks: build check")), - }; - match result { - Ok(()) => ExitCode::SUCCESS, - Err(e) => { - eprintln!("error: {e}"); - ExitCode::FAILURE - } - } -} - -fn workspace_version(here: &Path) -> Result { - let root = here.parent().and_then(Path::parent).and_then(Path::parent).ok_or_else(|| "cannot find repository root".to_string())?; - let manifest = fs::read_to_string(root.join("Cargo.toml")).map_err(|e| format!("read workspace manifest: {e}"))?; - let mut in_section = false; - for line in manifest.lines() { - let trimmed = line.trim(); - if trimmed.starts_with('[') { - in_section = trimmed == "[workspace.package]"; - } else if in_section - && let Some(rest) = trimmed.strip_prefix("version") - && let Some(value) = rest.trim_start().strip_prefix('=') - { - let version = value.trim().trim_matches('"'); - if !version.is_empty() { - return Ok(version.to_string()); - } - } - } - Err("workspace package version is missing".into()) -} - -/// Builds into `out`, replacing what is there. Only a folder that holds this notebook (or -/// nothing) is replaced, so a wrong path cannot delete someone's notes. -fn build_in_place(content: &Path, out: &Path, art: &Path, version: &str) -> Result<(), String> { - if out.exists() { - let old_node = notecraft_store::tree::read_node(out); - let old_layout = old_node.as_ref().is_some_and(|n| n.title == NOTEBOOK_TITLE); - let html_node = notecraft_store::tree::read_node(&out.join("html")); - let cmgfm_node = notecraft_store::tree::read_node(&out.join("cmgfm")); - let paired_layout = html_node.as_ref().is_some_and(|node| node.title == NOTEBOOK_TITLE) - && cmgfm_node.as_ref().is_some_and(|node| node.title == NOTEBOOK_TITLE); - let partial_layout = html_node.as_ref().is_some_and(|node| node.title == NOTEBOOK_TITLE) - || cmgfm_node.as_ref().is_some_and(|node| node.title == NOTEBOOK_TITLE); - let ours = old_layout || paired_layout || partial_layout; - let empty = fs::read_dir(out).map(|mut rd| rd.next().is_none()).unwrap_or(false); - if !ours && !empty { - return Err(format!("{} exists and is not the Welcome notebook; not touching it", out.display())); - } - fs::remove_dir_all(out).map_err(|e| format!("cannot clear {}: {e}", out.display()))?; - } - let built = build(content, out, art, version)?; - verify_pair(out)?; - println!( - "demo: built {} with {} languages ({}) and {} pages in each format", - out.display(), - built.languages.len(), - built.languages.join(", "), - built.pages - ); - Ok(()) -} - -/// Builds into a scratch folder and compares it with `out`, file by file. -fn check_in_place(content: &Path, out: &Path, art: &Path, version: &str) -> Result<(), String> { - let scratch = std::env::temp_dir().join(format!("notecraft-demo-check-{}", std::process::id())); - let _ = fs::remove_dir_all(&scratch); - let fresh = scratch.join("DemoNotebook"); - let result = build(content, &fresh, art, version).and_then(|_| verify_pair(&fresh)).and_then(|()| { - let want = snapshot(&fresh)?; - let have = snapshot(out)?; - let mut differences: Vec = Vec::new(); - for (path, bytes) in &want { - match have.get(path) { - None => differences.push(format!("missing: {path}")), - Some(b) if b != bytes => differences.push(format!("differs: {path}")), - Some(_) => {} - } - } - for path in have.keys() { - if !want.contains_key(path) { - differences.push(format!("extra: {path}")); - } - } - if differences.is_empty() { - println!("demo-check: {} files, {} up to date with its content", want.len(), out.display()); - Ok(()) - } else { - Err(format!("{} is out of date; run `cargo xtask demo`:\n {}", out.display(), differences.join("\n "))) - } - }); - let _ = fs::remove_dir_all(&scratch); - result -} - -/// Writes the notebook under `out`, which must not exist yet. -fn build(content: &Path, out: &Path, art: &Path, version: &str) -> Result { - fs::create_dir_all(out).map_err(|e| format!("cannot create {}: {e}", out.display()))?; - let mut full = Built::default(); - for (folder, format) in [("html", notecraft_model::PageFormat::Html), ("cmgfm", notecraft_model::PageFormat::Cmgfm)] { - let variant = build_variant(content, &out.join(folder), art, format, version)?; - if full.languages.is_empty() { - full.languages = variant.languages.clone(); - } - full.pages = variant.pages; - } - Ok(full) -} - -fn build_variant(content: &Path, out: &Path, art: &Path, target_format: notecraft_model::PageFormat, version: &str) -> Result { - let mut built = Built::default(); - fs::create_dir_all(out).map_err(|e| format!("cannot create {}: {e}", out.display()))?; - let format_name = match target_format { - notecraft_model::PageFormat::Html => "html", - notecraft_model::PageFormat::Cmgfm => "cmgfm", - }; - write(&out.join("_node.toml"), &node_toml("notebook", NOTEBOOK_TITLE, &id_for("notebook"), 10, Some(format_name), Some("purple")))?; - - // The languages with content, in table order. - let present: Vec<&Language> = LANGUAGES.iter().filter(|l| content.join(l.code).is_dir()).collect(); - if present.is_empty() { - return Err(format!("no language folder under {}", content.display())); - } - - // Start here: one page, with the list of languages where the mark is. - let start = out.join(START_FOLDER); - fs::create_dir_all(&start).map_err(|e| format!("cannot create {}: {e}", start.display()))?; - write(&start.join("_node.toml"), &node_toml("section", START_TITLE, &id_for(START_FOLDER), 10, None, None))?; - let start_page = read_source(&content.join("start").join("welcome.html"), 10)?; - let start_page = - Source { title: start_page.title.replace(VERSION_MARK, version), body: start_page.body.replace(VERSION_MARK, version), ..start_page }; - let list = language_list(&present); - let body = start_page.body.replace(LANGUAGES_MARK, &list); - let start_page = convert_source(Source { body, ..start_page }, target_format, &content.join("start").join("welcome.html"))?; - write_page(&start.join("welcome"), &start_page, &id_for("start/welcome"), None, art)?; - built.pages += 1; - - for (n, lang) in present.iter().enumerate() { - let group = out.join(lang.folder()); - fs::create_dir_all(&group).map_err(|e| format!("cannot create {}: {e}", group.display()))?; - let order = 20 + 10 * n as u32; - write(&group.join("_node.toml"), &node_toml("section-group", lang.name, &id_for(&lang.folder()), order, None, Some(lang.color)))?; - let section = group.join(HOW_TO_FOLDER); - fs::create_dir_all(§ion).map_err(|e| format!("cannot create {}: {e}", section.display()))?; - write(§ion.join("_node.toml"), &node_toml("section", lang.how_to, &id_for(&format!("{}/how-to", lang.folder())), 10, None, None))?; - let sources = read_sources(&content.join(lang.code))?; - if sources.is_empty() { - return Err(format!("{}: no pages", content.join(lang.code).display())); - } - let default_dir = if lang.rtl { Some("rtl") } else { None }; - for s in &sources { - let id = id_for(&format!("{}/how-to/{}", lang.folder(), s.slug)); - let page = section.join(&s.slug); - // A page with ink names it, as every page with ink must: the folder and the - // page's own words have to agree. See docs/dom_serialization/page-model.md section 5. - let inked = matches!(s.slug.as_str(), "pictures-and-files" | "shapes" | "handwriting-and-drawing"); - let s = if inked { - Source { - body: format!( - "{} - -![Ink](ink.svg) -", - s.body.trim_end() - ), - ..s.clone() - } - } else { - s.clone() - }; - let source_path = content.join(lang.code).join(format!("{}-{}.{}", s.order, s.slug, if s.html { "html" } else { "md" })); - let s = convert_source(s, target_format, &source_path)?; - write_page(&page, &s, &id, default_dir, art)?; - // Keep the pictures-and-files sample, and add dedicated shape and handwriting - // pages to show that ink can be drawn and edited on a page. - if s.slug == "pictures-and-files" { - write_ink(&page)?; - } else if s.slug == "shapes" { - write_shapes_ink(&page)?; - } else if s.slug == "handwriting-and-drawing" { - write_handwriting_ink(&page)?; - } - built.pages += 1; - } - built.languages.push(lang.code.to_string()); - } - Ok(built) -} - -/// The bullet list on the start page: each language's own name as the link, its English -/// name after it, and a note on the ones that read right to left. -fn language_list(present: &[&Language]) -> String { - let mut out = String::new(); - for l in present { - let note = if l.rtl { ", right to left" } else { "" }; - // The English name only when it adds something: "English, English" would not. - let english = if l.english == l.name { String::new() } else { format!(", {}", l.english) }; - out.push_str(&format!("
  • {}{english}{note}
  • \n", l.folder(), l.name)); - } - out.trim_end().to_string() -} - -/// Writes one page folder: `index.md` or `index.html` with the page's metadata, and -/// every picture the page names, copied in from the repository's own `assets/demo`. -fn write_page(dir: &Path, s: &Source, id: &str, default_dir: Option<&str>, art: &Path) -> Result<(), String> { - fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?; - let dir_value = s.dir.as_deref().or(default_dir); - // A page carries its title in its head, and the window draws it above the words. A - // body that opens with that same title as a heading would show it twice, so the - // heading comes off here and the content files keep it for reading on their own. - let s = &Source { body: without_title_heading(&s.body, &s.title), ..s.clone() }; - copy_assets(dir, &s.body, art)?; - let look = look_of(&s.slug); - if s.html { - write(&dir.join("index.html"), &html_page(&s.title, id, s.order, dir_value, &s.body, look, s.justify.as_deref())) - } else { - write(&dir.join("index.md"), &markdown_page(&s.title, id, s.order, dir_value, &s.body, look, s.justify.as_deref())) - } -} - -/// Converts a source page into the selected notebook format without changing its blocks or layout. -fn convert_source(mut source: Source, target: notecraft_model::PageFormat, path: &Path) -> Result { - let input = if source.html { notecraft_model::PageFormat::Html } else { notecraft_model::PageFormat::Cmgfm }; - if input == target { - return Ok(source); - } - let (blocks, containers) = notecraft_formats::boxes::read(input, &source.body); - let body = notecraft_formats::boxes::write(target, &blocks, containers.as_deref()); - let (converted_blocks, converted_containers) = notecraft_formats::boxes::read(target, &body); - if blocks != converted_blocks || containers != converted_containers { - let difference = blocks - .iter() - .zip(&converted_blocks) - .enumerate() - .find(|(_, (left, right))| left != right) - .map(|(index, (left, right))| format!("block {index}: {left:?} -> {right:?}")) - .unwrap_or_else(|| format!("{} blocks -> {} blocks", blocks.len(), converted_blocks.len())); - return Err(format!( - "{}: converting to {target:?} changed page content or layout ({difference}; layout {containers:?} -> {converted_containers:?})", - path.display() - )); - } - if let Some(justify) = &source.justify { - check_justify(path, justify, target == notecraft_model::PageFormat::Html, &body)?; - } - source.body = body; - source.html = target == notecraft_model::PageFormat::Html; - Ok(source) -} - -/// A body without the heading that only repeats the page's title. -fn without_title_heading(body: &str, title: &str) -> String { - let mut offset = 0; - for line_with_end in body.split_inclusive('\n') { - let line = line_with_end.trim_end_matches(['\r', '\n']).trim(); - if line.is_empty() || (line.starts_with("![") && line.ends_with(')')) { - offset += line_with_end.len(); - continue; - } - let is_echo = - line.strip_prefix("# ").map(str::trim) == Some(title.trim()) || line.eq_ignore_ascii_case(&format!("

    {}

    ", title.trim())); - if !is_echo { - return body.to_string(); - } - let after_heading = offset + line_with_end.len(); - let tail = body[after_heading..].trim_start_matches(['\r', '\n']); - return format!("{}{tail}", &body[..offset]); - } - body.to_string() -} - -/// Copies every `assets/...` a page names into that page's own `assets` folder. -/// -/// A page owns its files, so each page that shows a picture gets its own copy rather than -/// linking across the notebook. The pictures themselves live in the repository under -/// `assets/demo`, attributed there, and this is the only place they are copied from: a -/// page that names one that is not there fails the build rather than shipping a hole. -fn copy_assets(dir: &Path, body: &str, art: &Path) -> Result<(), String> { - for target in link_targets(body) { - let Some(name) = target.strip_prefix("assets/") else { continue }; - if name.is_empty() || name.contains('/') || name.contains("..") { - return Err(format!("{}: {target} is not a plain file name", dir.display())); - } - let from = art.join(name); - if !from.is_file() { - return Err(format!("{}: nothing at {}", dir.display(), from.display())); - } - let assets = dir.join("assets"); - fs::create_dir_all(&assets).map_err(|e| format!("cannot create {}: {e}", assets.display()))?; - fs::copy(&from, assets.join(name)).map_err(|e| format!("cannot copy {}: {e}", from.display(),))?; - } - Ok(()) -} - -/// A drawing for a page: a few strokes written as NoteCraft's own ink file. -/// -/// The demo should show what the pen leaves behind, and a page with ink in the folder is -/// the only honest way to show it. The strokes are drawn here with the same crate the pen -/// uses, so the file the demo ships is the file the pen would have written. -fn write_ink(dir: &Path) -> Result<(), String> { - use notecraft_ink::{Dab, Drawing, Rgb, Stroke, Tool}; - let mut drawing = Drawing::new(820.0, 1100.0); - - // A hand-drawn underline under the page's first heading, and a tick beside it. - let mut line = Stroke::new(Tool::Highlighter, Rgb(0xFF, 0xDD, 0x33), 14.0); - for i in 0..=18 { - let t = i as f32 / 18.0; - line.add(Dab { x: 60.0 + t * 300.0, y: 96.0 + (t * 6.2).sin() * 2.5, pressure: 0.55 + t * 0.2 }); - } - drawing.add(line); - - // Two strokes, not more: a stroke is stored as a filled outline, and an outline is - // some 30 KB a stroke. Thirteen languages carry a copy of this page. - let mut tick = Stroke::new(Tool::Pen, Rgb(0x1E, 0x8A, 0x44), 3.5); - for i in 0..=6 { - let t = i as f32 / 6.0; - tick.add(Dab { x: 400.0 + t * 14.0, y: 84.0 + t * 16.0, pressure: 0.4 + t * 0.4 }); - } - for i in 1..=9 { - let t = i as f32 / 9.0; - tick.add(Dab { x: 414.0 + t * 26.0, y: 100.0 - t * 30.0, pressure: 0.8 - t * 0.3 }); - } - drawing.add(tick); - - let svg = notecraft_ink::svg::write(&drawing, notecraft_ink::svg::Flavour::Editable); - write(&dir.join("ink.svg"), &svg) -} - -/// A two-column sheet of every shape offered by the Draw tab. -fn write_shapes_ink(dir: &Path) -> Result<(), String> { - use notecraft_ink::{Drawing, Rgb, Stroke, Tool}; - let mut drawing = Drawing::new(820.0, 800.0); - for (index, shape) in notecraft_ink::shapes::Shape::ALL.into_iter().enumerate() { - let column = index % 2; - let row = index / 2; - let x = 160.0 + column as f32 * 420.0; - let y = 300.0 + row as f32 * 100.0; - let dabs = notecraft_ink::shapes::trace(shape, (x, y), (x + 80.0, y + 60.0), 0.75); - let mut stroke = Stroke::new(Tool::Pen, Rgb(0x28, 0x57, 0x8a), 4.0); - for dab in dabs { - stroke.add(dab); - } - drawing.add(stroke); - } - let svg = notecraft_ink::svg::write(&drawing, notecraft_ink::svg::Flavour::Editable); - write(&dir.join("ink.svg"), &svg) -} - -/// Handwritten words and a small landscape, saved as editable pen strokes. -fn write_handwriting_ink(dir: &Path) -> Result<(), String> { - use notecraft_ink::{Dab, Drawing, Rgb, Stroke, Tool}; - let mut drawing = Drawing::new(820.0, 700.0); - let mut x = 70.0; - for ch in "Meet me at 3".chars() { - if ch == ' ' { - x += 24.0; - continue; - } - let paths: &[&[(f32, f32)]] = match ch { - 'M' => &[&[(0.0, 42.0), (0.0, 0.0), (14.0, 22.0), (28.0, 0.0), (28.0, 42.0)]], - 'e' => &[&[ - (27.0, 21.0), - (4.0, 21.0), - (6.0, 13.0), - (14.0, 7.0), - (22.0, 10.0), - (27.0, 18.0), - (25.0, 30.0), - (17.0, 37.0), - (9.0, 35.0), - (4.0, 28.0), - ]], - 't' => &[&[(14.0, 1.0), (14.0, 33.0), (19.0, 38.0), (25.0, 35.0)], &[(3.0, 13.0), (24.0, 13.0)]], - 'm' => &[&[(3.0, 39.0), (3.0, 12.0), (9.0, 7.0), (15.0, 13.0), (15.0, 39.0)], &[(15.0, 13.0), (22.0, 7.0), (29.0, 13.0), (29.0, 39.0)]], - 'a' => &[&[ - (25.0, 14.0), - (20.0, 7.0), - (11.0, 7.0), - (4.0, 15.0), - (3.0, 28.0), - (10.0, 37.0), - (19.0, 35.0), - (25.0, 27.0), - (25.0, 7.0), - (25.0, 39.0), - ]], - '3' => &[&[ - (4.0, 8.0), - (13.0, 2.0), - (23.0, 7.0), - (24.0, 15.0), - (17.0, 20.0), - (10.0, 21.0), - (19.0, 22.0), - (26.0, 29.0), - (23.0, 37.0), - (13.0, 41.0), - (4.0, 36.0), - ]], - _ => &[], - }; - for path in paths { - let mut stroke = Stroke::new(Tool::Pen, Rgb(0x22, 0x4f, 0x78), 4.2); - for (index, (px, py)) in path.iter().enumerate() { - stroke.add(Dab { x: x + px * 1.25, y: 200.0 + py * 1.25, pressure: if index % 2 == 0 { 0.72 } else { 0.88 } }); - } - drawing.add(stroke); - } - x += 40.0; - } - - // A sun, rolling hills and lake ripples. - let mut sun = Stroke::new(Tool::Pen, Rgb(0xd0, 0x70, 0x32), 3.5); - for i in 0..=32 { - let angle = i as f32 / 32.0 * std::f32::consts::TAU; - sun.add(Dab { x: 640.0 + angle.cos() * 28.0, y: 340.0 + angle.sin() * 28.0, pressure: 0.7 }); - } - drawing.add(sun); - let lines: &[&[(f32, f32)]] = &[ - &[ - (60.0, 400.0), - (130.0, 360.0), - (200.0, 385.0), - (270.0, 325.0), - (350.0, 390.0), - (425.0, 340.0), - (505.0, 390.0), - (580.0, 360.0), - (670.0, 405.0), - (760.0, 370.0), - ], - &[(65.0, 435.0), (170.0, 415.0), (260.0, 440.0), (370.0, 415.0), (500.0, 440.0), (625.0, 417.0), (760.0, 440.0)], - &[(110.0, 500.0), (190.0, 490.0), (270.0, 502.0), (350.0, 490.0), (430.0, 502.0), (510.0, 490.0), (600.0, 502.0), (700.0, 490.0)], - &[(130.0, 545.0), (220.0, 535.0), (310.0, 547.0), (400.0, 535.0), (490.0, 547.0), (580.0, 535.0), (680.0, 547.0)], - ]; - for (index, line) in lines.iter().enumerate() { - let colour = if index < 2 { Rgb(0x37, 0x76, 0x52) } else { Rgb(0x28, 0x65, 0x91) }; - let mut stroke = Stroke::new(Tool::Pen, colour, 3.8); - for (i, (x, y)) in line.iter().enumerate() { - stroke.add(Dab { x: *x, y: *y, pressure: if i % 2 == 0 { 0.68 } else { 0.82 } }); - } - drawing.add(stroke); - } - let svg = notecraft_ink::svg::write(&drawing, notecraft_ink::svg::Flavour::Editable); - write(&dir.join("ink.svg"), &svg) -} - -/// A `_node.toml` in the form `docs/folder-format.md` section 4 describes. -fn node_toml(kind: &str, title: &str, id: &str, order: u32, format: Option<&str>, color: Option<&str>) -> String { - let mut s = format!("kind = {}\ntitle = {}\nid = {}\n", kv::quote(kind), kv::quote(title), kv::quote(id)); - if let Some(f) = format { - s.push_str(&format!("format = {}\n", kv::quote(f))); - } - s.push_str(&format!("order = {order}\n")); - if let Some(c) = color { - s.push_str(&format!("color = {}\n", kv::quote(c))); - } - s.push_str(&format!("created = {}\n", kv::quote(DATE))); - s -} - -/// A Markdown page with the front matter the store writes (section 3.2 of the format). -fn markdown_page(title: &str, id: &str, order: u32, dir: Option<&str>, body: &str, look: Look, justify: Option<&str>) -> String { - let mut front = format!("---\nid: {id}\ntitle: {}\norder: {order}\ncreated: {DATE}\nupdated: {DATE}\n", kv::quote(title)); - if let Some(d) = dir { - front.push_str(&format!("dir: {d}\n")); - } - if let Some(j) = justify { - front.push_str(&format!("justify: {j}\n")); - } - if let Some(p) = look.paper { - front.push_str(&format!("paper: {p}\n")); - } - if let Some(c) = look.colour { - front.push_str(&format!("page-color: {c}\n")); - } - front.push_str("tags: []\n---\n\n"); - format!("{front}{}\n", body.trim_end()) -} - -/// The paper a demo page is drawn on and the colour behind it, so the notebook shows what -/// a page can look like as well as what it can say. -#[derive(Clone, Copy, Default)] -struct Look { - paper: Option<&'static str>, - colour: Option<&'static str>, -} - -/// Which pages are given paper of their own, by the folder they are written to. The rest -/// are drawn on the plain page the window opens with. -fn look_of(slug: &str) -> Look { - match slug { - // The page about writing is on ruled paper, as a page for writing on would be. - "write-a-page" => Look { paper: Some("college"), colour: None }, - // The one about tags is squared, and a little warm, so the two show side by side - // in the tree what paper and page colour do. - "tag-a-line" => Look { paper: Some("grid-medium"), colour: Some("yellow") }, - // The one about making it yours is coloured, with no lines. - "make-it-yours" => Look { paper: None, colour: Some("teal") }, - _ => Look::default(), - } -} - -/// An HTML page with the metadata in `` tags (section 3.1 of the format). -fn html_page(title: &str, id: &str, order: u32, dir: Option<&str>, body: &str, look: Look, justify: Option<&str>) -> String { - let t = escape(title); - let mut head = format!( - "\n\n\n\n{t}\n\n\n\n\n" - ); - if let Some(d) = dir { - head.push_str(&format!("\n")); - } - if let Some(j) = justify { - head.push_str(&format!("\n")); - } - if let Some(p) = look.paper { - head.push_str(&format!("\n")); - } - if let Some(c) = look.colour { - head.push_str(&format!("\n")); - } - format!("{head}\n\n{}\n\n\n", body.trim()) -} - -fn escape(s: &str) -> String { - s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) -} - -/// Every `NN-slug.md` or `NN-slug.html` in `dir`, in order. -fn read_sources(dir: &Path) -> Result, String> { - let mut names: Vec = fs::read_dir(dir) - .map_err(|e| format!("{}: {e}", dir.display()))? - .filter_map(|e| e.ok()) - .map(|e| e.path()) - .filter(|p| p.is_file() && p.extension().is_some_and(|x| x == "md" || x == "html")) - .collect(); - names.sort(); - let mut out = Vec::new(); - for p in names { - let stem = p.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); - let (number, slug) = stem.split_once('-').ok_or_else(|| format!("{}: name it NN-slug.md", p.display()))?; - let order: u32 = number.parse().map_err(|_| format!("{}: '{number}' is not a number", p.display()))?; - if let Err(why) = names::validate_component(slug) { - return Err(format!("{}: folder name '{slug}': {why}", p.display())); - } - let mut s = read_source(&p, order)?; - s.slug = slug.to_string(); - out.push(s); - } - Ok(out) -} - -/// One content file: a `title:` (and optional `dir:`) front matter, then the body. -fn read_source(path: &Path, order: u32) -> Result { - let text = fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; - let text = text.trim_start_matches('\u{feff}').replace("\r\n", "\n"); - let (front, body) = split_front(&text).ok_or_else(|| format!("{}: no front matter (a --- block with a title)", path.display()))?; - let title = front_value(front, "title").ok_or_else(|| format!("{}: front matter has no title", path.display()))?; - let dir = front_value(front, "dir"); - if let Some(d) = &dir - && d != "rtl" - && d != "ltr" - { - return Err(format!("{}: dir must be rtl or ltr, not '{d}'", path.display())); - } - let html = path.extension().is_some_and(|x| x == "html"); - let slug = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); - let body = body.trim_start_matches('\n').to_string(); - let justify = front_value(front, "justify"); - if let Some(line) = &justify { - check_justify(path, line, html, &body)?; - } - Ok(Source { order, slug, title, html, dir, justify, body }) -} - -/// A page says which of its paragraphs fill the column by their position among its blocks. -/// A number is only as good as the body it was counted against, so it is counted again here, -/// with the reader the editor itself uses: a number that has drifted onto a heading, a table -/// or off the end of the page stops the build. -fn check_justify(path: &Path, line: &str, html: bool, body: &str) -> Result<(), String> { - let marked = notecraft_model::justify::parse(line); - if marked.is_empty() { - return Err(format!("{}: justify is block numbers separated by commas, not '{line}'", path.display())); - } - let format = if html { notecraft_model::PageFormat::Html } else { notecraft_model::PageFormat::Cmgfm }; - let blocks = notecraft_formats::boxes::read(format, body).0; - for (at, _) in marked.blocks() { - match blocks.get(*at) { - Some(notecraft_formats::Block::Paragraph(_)) => {} - Some(other) => return Err(format!("{}: justify names block {at}, which is a {}, not a paragraph", path.display(), name_of(other))), - None => return Err(format!("{}: justify names block {at}, and the page has {} blocks", path.display(), blocks.len())), - } - } - Ok(()) -} - -/// What a block is, for an error message. -fn name_of(block: ¬ecraft_formats::Block) -> &'static str { - use notecraft_formats::Block; - match block { - Block::Heading { .. } => "heading", - Block::Paragraph(_) => "paragraph", - Block::Item { .. } => "list item", - Block::Quote(_) => "quote", - Block::Code { .. } => "code block", - Block::Table { .. } => "table", - Block::Image { .. } => "picture", - Block::MathBlock(_) => "equation", - _ => "block of another kind", - } -} - -/// The lines between the first two `---` lines, and the rest. -fn split_front(text: &str) -> Option<(&str, &str)> { - let rest = text.strip_prefix("---\n")?; - let end = rest.find("\n---\n")?; - Some((&rest[..end], &rest[end + 5..])) -} - -fn front_value(front: &str, key: &str) -> Option { - front.lines().find_map(|l| l.split_once(':').filter(|(k, _)| k.trim() == key).map(|(_, v)| v.trim().trim_matches('"').to_string())) -} - -/// A stable 20-hex-character id from a name: the shape the store uses, without the clock. -/// Two FNV-1a hashes over the name and its reverse, so two names never share an id by a -/// one-character slip. -fn id_for(name: &str) -> String { - fn fnv(bytes: impl Iterator) -> u64 { - let mut h: u64 = 0xcbf2_9ce4_8422_2325; - for b in bytes { - h ^= u64::from(b); - h = h.wrapping_mul(0x0000_0100_0000_01b3); - } - h - } - let a = fnv(name.bytes()); - let b = fnv(name.bytes().rev()); - format!("{a:016x}{:04x}", (b & 0xffff) as u16) -} - -/// The checker finds no problem, and every link in every page leads somewhere. -fn verify(out: &Path) -> Result<(), String> { - let report = check::check_tree(out); - if !report.problems.is_empty() { - let list: Vec = report.problems.iter().map(|p| format!("{}: {}", p.path.display(), p.message)).collect(); - return Err(format!("the checker found problems:\n {}", list.join("\n "))); - } - let root = out.parent().ok_or("the notebook has no parent folder")?; - let mut broken = Vec::new(); - let mut checked = 0usize; - for (page, text) in pages_under(out)? { - for href in link_targets(&text) { - checked += 1; - match links::resolve(root, &page, &href) { - Link::Node(_) | Link::File(_) | Link::Web(_) => {} - Link::Missing(p) => broken.push(format!("{} -> {href} (nothing at {})", page.display(), p.display())), - Link::Outside => broken.push(format!("{} -> {href} (outside the notebook)", page.display())), - } - } - } - if broken.is_empty() { - println!("demo: {} nodes, {checked} links, all resolve", report.nodes); - Ok(()) - } else { - Err(format!("broken links:\n {}", broken.join("\n "))) - } -} - -fn verify_pair(out: &Path) -> Result<(), String> { - verify(&out.join("html"))?; - verify(&out.join("cmgfm")) -} - -/// Every page folder under `dir` with the text of its file. -fn pages_under(dir: &Path) -> Result, String> { - let mut out = Vec::new(); - for child in notecraft_store::tree::child_dirs(dir) { - if let Some((_, file)) = notecraft_store::tree::page_file(&child) { - let text = fs::read_to_string(&file).map_err(|e| format!("{}: {e}", file.display()))?; - out.push((child.clone(), text)); - } - out.extend(pages_under(&child)?); - } - Ok(out) -} - -/// Link targets in a page: `](target)` in Markdown, `href="..."` and `src="..."` in HTML. -fn link_targets(text: &str) -> Vec { - let mut out = Vec::new(); - let mut rest = text; - while let Some(i) = rest.find("](") { - let after = &rest[i + 2..]; - let Some(end) = after.find(')') else { break }; - let target = after[..end].split_whitespace().next().unwrap_or(""); - if !target.is_empty() && !target.starts_with('#') { - out.push(target.to_string()); - } - rest = &after[end..]; - } - for attr in ["href=\"", "src=\""] { - let mut rest = text; - while let Some(i) = rest.find(attr) { - let after = &rest[i + attr.len()..]; - let Some(end) = after.find('"') else { break }; - let target = after[..end].trim(); - if !target.is_empty() && !target.starts_with('#') { - out.push(target.to_string()); - } - rest = &after[end..]; - } - } - out -} - -/// Every file under `dir` by its relative path, with its bytes. -fn snapshot(dir: &Path) -> Result>, String> { - fn walk(base: &Path, dir: &Path, out: &mut BTreeMap>) -> Result<(), String> { - let rd = fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?; - for e in rd.filter_map(|e| e.ok()) { - let p = e.path(); - if p.is_dir() { - walk(base, &p, out)?; - } else { - let rel = p.strip_prefix(base).unwrap_or(&p).to_string_lossy().replace('\\', "/"); - out.insert(rel, fs::read(&p).map_err(|e| format!("{}: {e}", p.display()))?); - } - } - Ok(()) - } - let mut out = BTreeMap::new(); - if dir.exists() { - walk(dir, dir, &mut out)?; - } - Ok(out) -} - -fn write(path: &Path, text: &str) -> Result<(), String> { - fs::write(path, text).map_err(|e| format!("cannot write {}: {e}", path.display())) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// The repository's own art, which a page's pictures are copied from. - fn art_dir() -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..").join("..").join("..").join("assets").join("demo") - } - - fn content_dir() -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("content") - } - - fn scratch(label: &str) -> PathBuf { - let p = std::env::temp_dir().join(format!("notecraft-demo-test-{label}-{}", std::process::id())); - let _ = fs::remove_dir_all(&p); - p - } - - #[test] - fn ids_are_stable_and_distinct() { - assert_eq!(id_for("notebook"), id_for("notebook")); - assert_ne!(id_for("10-en/how-to/welcome"), id_for("11-es/how-to/welcome")); - assert_ne!(id_for("ab"), id_for("ba"), "the reverse hash tells anagrams apart"); - assert_eq!(id_for("x").len(), 20); - assert!(id_for("x").chars().all(|c| c.is_ascii_hexdigit())); - } - - #[test] - fn the_language_table_is_sound() { - let mut codes: Vec<&str> = LANGUAGES.iter().map(|l| l.code).collect(); - codes.sort_unstable(); - codes.dedup(); - assert_eq!(codes.len(), LANGUAGES.len(), "no code twice"); - let mut numbers: Vec = LANGUAGES.iter().map(|l| l.number).collect(); - numbers.sort_unstable(); - numbers.dedup(); - assert_eq!(numbers.len(), LANGUAGES.len(), "no folder number twice"); - assert_eq!(LANGUAGES.iter().filter(|l| l.rtl).count(), 4, "Arabic, Persian, Urdu, Hebrew"); - for l in LANGUAGES { - assert!(names::validate_component(&l.folder()).is_ok(), "{}", l.folder()); - assert!(["purple", "blue", "teal", "green", "yellow", "orange", "red", "magenta", "gray"].contains(&l.color), "{}: {}", l.code, l.color); - } - } - - #[test] - fn content_files_parse_and_name_their_folders() { - let en = read_sources(&content_dir().join("en")).expect("English content"); - assert!(en.len() >= 8, "eight pages at least, got {}", en.len()); - assert_eq!(en[0].slug, "welcome"); - assert_eq!(en[0].order, 10); - assert!(en.iter().any(|s| s.html), "one page shows the HTML format"); - let orders: Vec = en.iter().map(|s| s.order).collect(); - let mut sorted = orders.clone(); - sorted.sort_unstable(); - assert_eq!(orders, sorted, "files are read in order"); - let start = read_source(&content_dir().join("start").join("welcome.html"), 10).expect("HTML start page"); - assert!(start.html, "the notebook opens on its preferred format"); - assert!(start.body.contains(LANGUAGES_MARK)); - } - - #[test] - fn a_leading_banner_stays_first_without_repeating_the_page_title() { - let body = "![Banner](assets/banner-start.png)\n\n# Welcome to NoteCraft\n\nWords on the page.\n"; - assert_eq!(without_title_heading(body, "Welcome to NoteCraft"), "![Banner](assets/banner-start.png)\n\nWords on the page.\n"); - } - - #[test] - fn the_page_files_have_the_metadata_the_store_reads() { - let md = markdown_page("A \"quoted\" title", "abc", 20, Some("rtl"), "# Body\n", Look::default(), Some("2, 5")); - assert!(md.starts_with("---\nid: abc\ntitle: \"A \\\"quoted\\\" title\"\norder: 20\n")); - assert!(md.contains("\ndir: rtl\n")); - assert!(md.contains("\njustify: 2, 5\n"), "the justified paragraphs are a line in the head: {md}"); - assert!(md.ends_with("---\n\n# Body\n")); - let html = html_page("A ", "abc", 10, None, "

    x

    ", Look::default(), Some("0")); - - // A page given paper and a colour of its own carries both in its head. - let dressed = markdown_page( - "T", - "id", - 10, - None, - "words -", - Look { paper: Some("college"), colour: Some("yellow") }, - None, - ); - assert!( - dressed.contains( - " -paper: college -" - ) && dressed.contains( - " -page-color: yellow -" - ), - "{dressed}" - ); - let dressed_html = html_page("T", "id", 10, None, "

    x

    ", Look { paper: Some("grid-medium"), colour: None }, None); - assert!(dressed_html.contains("notecraft:paper"), "{dressed_html}"); - assert!(!dressed_html.contains("page-color"), "and says nothing about a colour it was not given"); - assert!(html.contains("A <b>")); - assert!(html.contains("name=\"notecraft:id\" content=\"abc\"")); - assert!(!html.contains("notecraft:dir")); - assert!(html.contains("notecraft:justify\" content=\"0\""), "the justified paragraphs are a meta tag: {html}"); - let node = node_toml("section-group", "Español", "id1", 30, None, Some("blue")); - assert_eq!( - node, - "kind = \"section-group\"\ntitle = \"Español\"\nid = \"id1\"\norder = 30\ncolor = \"blue\"\ncreated = \"2026-10-18T00:00:00Z\"\n" - ); - } - - #[test] - fn link_targets_are_found_in_both_formats() { - let md = "See [a](../a/) and [b](https://x.test \"t\") and [c](#top)."; - assert_eq!(link_targets(md), vec!["../a/", "https://x.test"]); - let html = "a t"; - assert_eq!(link_targets(html), vec!["../a/", "assets/p.png"]); - } - - /// Both full format editions build cleanly, contain the same tour, and rebuild identically. - #[test] - fn both_full_format_notebooks_build_cleanly_and_the_same_way_twice() { - let dir = scratch("build"); - let out = dir.join("DemoNotebook"); - let built = build(&content_dir(), &out, &art_dir(), "0.0.0-test").expect("build"); - verify_pair(&out).expect("verify both notebooks"); - assert!(built.languages.contains(&"en".to_string())); - let html = out.join("html"); - let cmgfm = out.join("cmgfm"); - let html_tree = notecraft_store::tree::load_tree(&html).expect("HTML notebook tree"); - let cmgfm_tree = notecraft_store::tree::load_tree(&cmgfm).expect("CMGFM notebook tree"); - assert_eq!(html_tree.info.title, NOTEBOOK_TITLE); - assert_eq!(cmgfm_tree.info.title, NOTEBOOK_TITLE); - assert_eq!(html_tree.info.format, Some(notecraft_model::PageFormat::Html)); - assert_eq!(cmgfm_tree.info.format, Some(notecraft_model::PageFormat::Cmgfm)); - assert_eq!(html_tree.children.len(), cmgfm_tree.children.len(), "both editions have the same top-level sections"); - let first = html_tree.children.first().expect("a first child"); - assert_eq!(first.info.title, START_TITLE, "the start section sorts first"); - assert_eq!(first.children.len(), 1); - for (html_group, cmgfm_group) in html_tree.children.iter().zip(&cmgfm_tree.children) { - assert_eq!(html_group.info.title, cmgfm_group.info.title); - assert_eq!(html_group.children.len(), cmgfm_group.children.len(), "matching structure in {}", html_group.path.display()); - if html_group.info.kind == notecraft_model::NodeKind::SectionGroup { - assert_eq!(html_group.children.len(), 1, "one How to section in {}", html_group.path.display()); - assert!(html_group.children[0].children.len() >= 8, "the same pages in every language"); - } - } - let start = fs::read_to_string(html.join(START_FOLDER).join("welcome").join("index.html")).expect("HTML start page"); - assert!(start.contains("
  • English
  • "), "{start}"); - assert!(start.contains("
  • العربية, Arabic, right to left
  • "), "{start}"); - assert!(!start.contains(LANGUAGES_MARK)); - assert!(html.join("10-en").join("how-to").join("write-a-page").join("index.html").is_file()); - assert!(cmgfm.join("10-en").join("how-to").join("write-a-page").join("index.md").is_file()); - assert!(html.join("10-en").join("how-to").join("page-formats").join("index.html").is_file()); - let first_build = snapshot(&out).expect("snapshot"); - let again = dir.join("Again"); - build(&content_dir(), &again, &art_dir(), "0.0.0-test").expect("build again"); - assert_eq!(snapshot(&again).expect("snapshot"), first_build, "deterministic"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn a_folder_that_is_not_the_welcome_notebook_is_left_alone() { - let dir = scratch("guard"); - let other = dir.join("Someone"); - fs::create_dir_all(&other).expect("dir"); - fs::write(other.join("_node.toml"), "kind = \"notebook\"\ntitle = \"Mine\"\nid = \"1\"\n").expect("node"); - let err = build_in_place(&content_dir(), &other, &art_dir(), "0.0.0-test").expect_err("refused"); - assert!(err.contains("not touching it"), "{err}"); - assert!(other.join("_node.toml").is_file(), "nothing was deleted"); - let _ = fs::remove_dir_all(&dir); - } +fn main() -> std::process::ExitCode { + generator::run() } diff --git a/docs/releases/0.0.9/READINESS.md b/docs/releases/0.0.9/READINESS.md new file mode 100644 index 00000000..8aa8b195 --- /dev/null +++ b/docs/releases/0.0.9/READINESS.md @@ -0,0 +1,70 @@ +# NoteCraft v0.0.9 Readiness + +## Release identity + +| Field | Value | +|---|---| +| Release version | 0.0.9 | +| Release source commit | `f44d977` plus uncommitted changes on `fix/web-demo-version-deploy-guard` | +| Release branch or tag candidate | `fix/web-demo-version-deploy-guard`; no tag candidate set | +| Previous release tag | Not verified in this signoff run | +| Approved release scope reference | `docs/releases/0.0.9/RELEASE_NOTES.md` | +| Signoff owner | NoteCraft owner | + +This is a local readiness snapshot, not release approval. The source tree is dirty, so the built +files do not yet have an immutable source commit. Any artifact rebuilt after a source change needs +new evidence and a new hash. + +## Platform signoff matrix + +| Platform | Refactor demo | Build | Lint | Test | Gates | Install | Install test | Uploaded | Ready | +|---|---|---|---|---|---|---|---|---|---| +| web-WASM | PASS | PASS | PASS | PASS | PASS | BLOCKED | BLOCKED | NOT RUN | BLOCKED | +| Windows x64 MSI | PASS | PASS | PASS | PASS | PASS | BLOCKED | BLOCKED | NOT RUN | BLOCKED | +| Windows x64 portable | PASS | PASS | PASS | PASS | PASS | BLOCKED | BLOCKED | NOT RUN | BLOCKED | +| macOS | PASS | BLOCKED | PASS | PASS | PASS | BLOCKED | BLOCKED | NOT RUN | BLOCKED | +| Linux x64 tar.gz | PASS | PASS | PASS | PASS | PASS | BLOCKED | BLOCKED | NOT RUN | BLOCKED | +| Android APK | PASS | BLOCKED | PASS | PASS | PASS | BLOCKED | BLOCKED | NOT RUN | BLOCKED | + +### Evidence and blockers + +| Platform | Evidence | +|---|---| +| Shared demo | `cargo xtask demo html`, `cargo xtask demo cmgfm`, and `cargo xtask demo both` completed. `cargo xtask demo-check` reports 662 generated files current. `cargo test -p notecraft-formats --test format_parity` passed (2 tests). Both formats contain 13 locales. | +| Shared code gates | `cargo xtask ci` passed after the generator refactor. It includes format, clippy, workspace tests, layer, asset, docs, text and demo checks. `python .github/web-build/test_bundle_demo.py` passed (2 tests). `git diff --check` passed. | +| web-WASM | Fresh local Trunk and pinned Binaryen builds completed. `website/demo/notecraft-web-aaa2af09d8cd8925_bg.wasm` SHA-256: `672C72D2C52E973C00C5D9CB5B7E832EDB73BF3AE324723E1CF43E98F30DD286`; it embeds the `0.0.9` marker. On 2026-11-07, `https://notecraft.cloud/demo/` returned HTTP 200 and its referenced WASM returned HTTP 200 with the `0.0.9` marker, but `https://notecraft.cloud/demo/welcome-notebook.zip` returned HTTP 404. The release notebook archive is built locally at `website/demo/welcome-notebook.zip` (662 files: 331 per format; SHA-256 `ED977B51991E3C1FA5C4B0FFCECA9778A96E2D7370731BD10E6A1D85C2E577FD`). The live archive is absent, so first-load provisioning cannot succeed on the hosted site. Deployment and clean-browser install test remain blocked. | +| Windows x64 MSI | `dist/release/notecraft-0.0.9-windows-x64.msi` SHA-256: `1C3C280AA43189A00A6A5E66DA3B02242D2CCEF32FE58FAEA94AFA112C42AA21`. Package is unsigned. Clean VM install test and upload not run. | +| Windows x64 portable | `dist/release/notecraft-0.0.9-windows-x64-portable.zip` SHA-256: `1C0D7891542888CE310AD1A41C603433092FBD310071676C2E88E916258DD2D6`. Clean VM launch and upload not run. | +| Linux x64 tar.gz | `dist/linux/notecraft-0.0.9-linux-x86_64.tar.gz` SHA-256: `CBC30F4C443AF714ECC24EB164170CFF38659E075F0BB9046B884756E1529A85`. Package smoke test passed; install on a clean Linux target and upload not run. | +| macOS | Build requires a macOS runner. No current-candidate package or install result. | +| Android APK | The Android builder is external to this repository and has not been rebuilt from this candidate. No current-candidate APK or install result. | + +`PASS` on shared code checks records local command results; it does not establish release readiness. +Every platform remains `BLOCKED` until its artifact provenance, installation, clean-target test, +upload and deployment requirements are satisfied for one immutable source commit. + +## Release checklist + +| Done | Check | Evidence / status | +|---|---|---| +| [x] | Approved version is consistent in workspace metadata and local artifacts. | PASS: version 0.0.9. Release draft consistency not rechecked in this run. | +| [x] | Demo scripts and authored content are updated; HTML and CMGFM outputs are regenerated and parity-checked. | PASS: `cargo xtask demo both`, `cargo xtask demo-check`, and `cargo test -p notecraft-formats --test format_parity`. | +| [x] | Both generated formats and all 13 locales are present; developer copy is refreshed. | PASS: selected-format and both-format commands completed; `my-notebooks/welcome-notebook` refreshed from each output. | +| [x] | Formatting, lint, tests, static gates, and CI pass on the local candidate tree. | PASS: `cargo xtask ci`; `python .github/web-build/test_bundle_demo.py`; `git diff --check`. Tree remains uncommitted. | +| [ ] | Coverage is run and its result is recorded. | NOT RUN. | +| [ ] | Each platform has build, install, clean-install test, artifact, and provenance evidence. | BLOCKED: see platform matrix. | +| [ ] | Release notes match verified scope. | NOT RUN: notes exist but have not been reconciled against merged release scope in this signoff. | +| [ ] | `build_git.py` change list is reconciled with merged PRs. | NOT RUN. | +| [ ] | Release GIF is regenerated and verified in draft preview. | NOT RUN. | +| [ ] | Draft links, images, artifact list, hashes, known gaps, and recovery notes are reviewed. | NOT RUN. | + +## Next actions + +1. Finish and review the local changes, then create one immutable candidate commit after approval. +2. Rebuild platform artifacts from that exact commit; build macOS on a macOS runner and Android + through its external builder. +3. Install and launch each candidate on clean targets and verify demo provisioning and data + preservation. +4. Upload the exact artifacts, deploy the website from the same source commit, and verify the + hosted demo and release draft. +5. Run coverage and complete the remaining release checklist with immutable evidence links. diff --git a/docs/releases/0.0.9/RELEASE_NOTES.md b/docs/releases/0.0.9/RELEASE_NOTES.md index 3d67430a..6f1af044 100644 --- a/docs/releases/0.0.9/RELEASE_NOTES.md +++ b/docs/releases/0.0.9/RELEASE_NOTES.md @@ -6,7 +6,7 @@ - **Infinite canvas:** Draw in open page space beyond text blocks. - **Languages:** Interface localization across 13 locales, with French and Spanish User Assistance. - **Page organization:** UI improvements for creating pages and promoting them to sub-pages. -- **Installation:** Consistent installation across supported platforms, with the demo notebook provided as user content. +- **Installation:** The app refreshes the bundled HTML and CMGFM Welcome notebook in 13 languages at launch. Other notebooks are left unchanged. - **Importing:** Import test dataset and preserve section colours. ## About NoteCraft diff --git a/docs/releasing.md b/docs/releasing.md index 2a7996ca..a6bf0e9a 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -38,10 +38,28 @@ name or mark. 1. On `main`, with the gate green, keep the version as it is. Change it with `cargo xtask version set ` only when the owner has approved that exact number. Commit it. 2. Run Actions, Packaging, Run workflow on the approved commit. This manually builds and verifies - Linux, Windows, and macOS artifacts and uploads them without publishing anything. -3. After the Packaging run is green, run Actions, Release, Run workflow and enter that run ID. - Release downloads those exact artifacts and drafts `NoteCraft v`. Nothing is published. - Try the packages on clean machines, then publish the draft by hand. + Linux, Windows, and macOS artifacts and uploads them without publishing anything. Record its + source commit and the version from `[workspace.package]`. +3. Run Actions, Release, Run workflow from `main` at that same commit and enter that Packaging run + ID. The workflow rejects runs from another branch, commit, or workflow, and derives the release + version from the checked-out workspace. If `main` advanced, rerun Packaging for the new commit. + The workflow drafts `NoteCraft v`; it does not publish it. +4. Build Android separately through the approved ArtCraft Android builder. Record the NoteCraft + source commit and package version, verify the APK package metadata and signing certificate match + the intended release, then install it on a clean emulator/device. Attach it only after those + checks pass. Android is not built by this repository's Packaging workflow today. +5. For the website, wait for the `Deploy website` workflow on the same `main` commit to succeed. + It publishes the browser app and the separately version-checked Welcome notebook archive from + `docs/demo/DemoNotebook`. Its production check verifies both the served WASM and notebook + payload. Open the demo in a clean browser session and confirm it opens the official Welcome + notebook. If a production run is cancelled or fails, rerun it before signoff. +6. Review the draft's complete asset list and rendered notes, then test each platform package on a + clean target. Publish the draft only after the owner approves. + +The website, desktop release, and Android package are separate pipelines. Each bundles both +generated Welcome formats and provisions the managed Welcome notebook at app startup; the website +uses a static archive transport. The generic engine sample stays separate. Record and verify the +source revision and version for every artifact. ### Notes and the draft @@ -59,17 +77,16 @@ name or mark. ### Clean-machine check Before publishing, install the MSI on a machine that has never run NoteCraft. Follow the -`packaging/installation artifacts.md` contract for the expected user -notebook location and verify the installer places the Welcome notebook there before NoteCraft -launches through the separate `notecraft-setup` helper. Check both formats and all 13 language -folders. Also verify that app startup does not copy or replace it, and that edits and deletion -survive restart and upgrade. Clear old app settings only when the first-use privacy dialog itself -is under test; setup completion has its own marker. +`packaging/installation artifacts.md` contract for the expected user notebook location. Launch +NoteCraft and verify it creates or refreshes `welcome-to-notecraft` with both formats and all 13 +languages before loading the notebook tree. Place a sentinel user notebook beside it and verify it +is unchanged. Confirm an older Welcome notebook is replaced on restart; its edits are expected to +be replaced by the generated release content. | File | What it is | |---|---| | `notecraft--windows-x64.msi` | Per-machine installer: Program Files, Start menu shortcut | -| `notecraft--windows-x64-portable.zip` | App, `notecraft-setup.exe`, and CLI; helper installs the optional notebook on first launch | +| `notecraft--windows-x64-portable.zip` | App and CLI with the paired-format Welcome source | | `SHA256SUMS.txt` | SHA-256 of the two files above | Each file also gets a build provenance attestation. Check a download with @@ -94,10 +111,10 @@ the `release` environment of the repository, never in a file. - The MSI `UpgradeCode` in `packaging/windows/notecraft.wxs` is fixed once the first MSI is public. Changing it later stops new versions from replacing old ones. - The exes carry the app icon and version information (build.rs, winresource), and the packaging script checks both. -- Smoke test the artifact: it starts with no console window, the separate setup helper deploys the - optional User Assistance notebook before opening the page, a page can be edited, and a bad - notebooks folder shows an error box. Install, upgrade and uninstall must preserve user notebook - data. Use the canonical `packaging/installation artifacts.md` contract for the full checks. +- Smoke test the artifact: it starts with no console window, refreshes the managed Welcome notebook, + leaves sibling notebooks unchanged, and reports an invalid notebooks folder. Install, upgrade and + uninstall must preserve other user notebook data. Use the canonical + `packaging/installation artifacts.md` contract for the full checks. ## Building locally diff --git a/docs/testing.md b/docs/testing.md index 956f18f4..f5e8094a 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -1,6 +1,6 @@ # Testing NoteCraft -Last reviewed: 2026-10-17. +Last reviewed: 2026-11-07. Quality is not negotiable here, so the project is tested on several levels. The UI testing follows the method of the other Craft apps: no committed golden pictures, paired comparisons @@ -14,7 +14,9 @@ cargo xtask ci That runs, in order: `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`, the layer check, the asset attribution check, the documentation link check, the text style check, and the check that the Welcome notebook in -`docs/demo/DemoNotebook` is current with its content. Each can be run alone: +`docs/demo/DemoNotebook` is current with its content. The default `cargo xtask demo` generates +both formats. Use `cargo xtask demo html` or `cargo xtask demo cmgfm` to generate one format, +or `cargo xtask demo both` to request both explicitly. Each can be run alone: `cargo xtask fmt|clippy|test|layers|assets|docs|text|demo-check`. ## What is tested, and how @@ -26,6 +28,8 @@ link check, the text style check, and the check that the Welcome notebook in | Store tests | `crates/store` | The folder format on a real temporary folder: creating nodes, the format cascade, deep nesting, unusual titles, both formats, attachments, search, the checker. | | Engine tests | `crates/engine` | Every command through the registry, a full workflow with commands only, path confinement, and `hostile_params_never_panic`. | | Command line tests | `apps/notecraft-cli` | A whole session through the command line, and error paths. | +| Install provisioning tests | `apps/notecraft-setup` | Creates or replaces only the managed Welcome notebook, keeps sibling user notebooks unchanged, rejects incomplete payloads before replacing an existing copy, and refreshes a deleted copy on the next launch. | +| Install payload checks | `packaging/*`, `.github/web-build`, Android builder contract tests | Windows, Linux, macOS, Android and browser payloads include both generated formats and all 13 language folders; release page version and archive checks guard the website bundle. | | MCP tests | `crates/mcp` | The protocol lifecycle over a pipe, the tool list and its schemas, a notebook made, written, searched and checked through the tools, and the errors a tool reports instead of failing. | | UI behaviour tests | `crates/ui-egui/tests/ui.rs` | The real window, driven headlessly through the control methods: open a page, toolbar buttons, dialogs, default format, theme, restart with the saved theme, a real TCP control connection, accessibility labels. | | Pixel tests | same file | Rendered pixels have the theme's colours for all 14 themes; display math leaves ink where it should. | diff --git a/packaging/OSX/README.md b/packaging/OSX/README.md index fc3fb484..938abcdd 100644 --- a/packaging/OSX/README.md +++ b/packaging/OSX/README.md @@ -1,10 +1,9 @@ # NoteCraft macOS packaging guide -This directory contains the NoteCraft macOS app, notebook setup app, DMG and CLI archive scripts. -The DMG carries the application and optional User Assistance notebook as separate items. The -setup app installs the notebook into the user's normal notebooks folder with consent; NoteCraft -does not install or recreate it. Packages remain test artifacts until a maintainer completes -signing, notarization and clean-machine installation checks. +This directory contains the NoteCraft macOS app, DMG and CLI archive scripts. The app bundle +includes both generated Welcome notebook formats and refreshes the managed Welcome notebook when +it starts. It replaces only `welcome-to-notecraft`; sibling notebooks remain unchanged. Packages +remain test artifacts until a maintainer completes signing, notarization and clean-machine checks. ## Build and verify test packages @@ -14,23 +13,14 @@ Use macOS with Xcode Command Line Tools, the pinned Rust toolchain in `rust-tool ```sh rustup install packaging/OSX/package.sh --arch aarch64 -packaging/OSX/verify.sh aarch64 --expect-demo +packaging/OSX/verify.sh aarch64 packaging/OSX/test-stale.sh aarch64 bash packaging/OSX/test-provenance.sh ``` -The optional notebook may be omitted without changing the app: - -```sh -packaging/OSX/package.sh --arch aarch64 --omit-demo --out "$PWD/dist/macos-no-demo" -DIST="$PWD/dist/macos-no-demo" packaging/OSX/verify.sh aarch64 --expect-no-demo -``` - -The included-notebook DMG contains `NoteCraft.app`, `Install NoteCraft Welcome Notebook.app`, -`Welcome Notebook/`, an Applications link and a read-me file at its root. Drag the app to -Applications, run the separate setup app while the disk image is mounted, confirm the notebook -copy, then open NoteCraft. The setup app leaves an existing notebook untouched. If the payload is -omitted, the setup app explains that no notebook was included and the application remains usable. +The DMG contains `NoteCraft.app`, an Applications link and a read-me file at its root. Drag the +app to Applications and open it. NoteCraft creates or refreshes the Welcome notebook in the user's +notebook folder before loading the notebook tree. The default `--arch universal` builds both Apple targets and combines the GUI and CLI with `lipo`. `--arch x86_64` produces Intel-only packages. The DMG and separate CLI zip are written to @@ -59,23 +49,21 @@ requires the bundle number to equal that count. On a host that cannot execute a architecture, successful Cargo builds and matching records establish source provenance; runtime behavior still needs a native host check. -The app bundle contains its executables, icon, project licences, attribution and third-party -notices. It does not contain the demo notebook. When included, the separate `Welcome Notebook/` -folder at the DMG root carries both HTML and CMGFM formats; verification compares it with the -official source. The DMG verifier also checks the setup app, both app signatures, architecture -slices, source hashes and the no-payload variant. These package checks do not replace a clean -macOS installation test; see [the macOS installation gaps](issues.md) and the canonical +The app bundle contains its executables, icon, both generated Welcome notebook formats, project +licences, attribution and third-party notices. The DMG verifier compares the bundled notebooks +with their official generated source and checks signatures, architecture slices and source hashes. +These package checks do not replace a clean macOS installation test; see [the macOS installation gaps](issues.md) and the canonical `packaging/installation artifacts.md` contract. The standalone CLI zip can be extracted without installing the app. Both packages are signed ad-hoc by default for local testing. A downloaded ad-hoc package can be rejected by Gatekeeper; do not change system security settings to test it. -For a manual Finder check, use a disposable notebook directory. Open the DMG, drag -`NoteCraft.app` into Applications, run `Install NoteCraft Welcome Notebook.app` from the mounted -DMG and accept, then open the installed app. Confirm the notebook exists before NoteCraft starts, -edit it, quit, relaunch and confirm the edit remains. Run setup again and confirm it preserves the -edit. Remove only the test app after the check; keep the notebook directory to confirm app removal -does not remove notes. Repeat with a DMG built using `--omit-demo` and on Intel before release. +For a manual Finder check, use a disposable notebook directory containing a sentinel user notebook +and an older `welcome-to-notecraft`. Open the DMG, drag `NoteCraft.app` into Applications, then +launch it. Confirm the Welcome notebook has both formats and the current content, while the +sentinel notebook is unchanged. Quit and relaunch to verify refresh behavior. Remove only the test +app after the check; confirm app removal leaves the notebook root in place. Repeat on Intel before +release. The preferred direction is to follow the packaging tools and libraries already used by the ArtCraft applications, especially the sibling MailCraft macOS package. Do not introduce a new diff --git a/packaging/OSX/issues.md b/packaging/OSX/issues.md index eaf127ae..5ff4cd9f 100644 --- a/packaging/OSX/issues.md +++ b/packaging/OSX/issues.md @@ -5,21 +5,19 @@ cross-platform policy lives in the canonical `packaging/installation artifacts.m ## Current limitations -1. The DMG now keeps `NoteCraft.app`, the separate setup app and optional `Welcome Notebook/` - payload as sibling items. The setup app uses explicit consent and install-if-absent behavior. - Native macOS package execution has not yet been run from this Windows development host. -2. Clean-profile install, repeat setup, notebook edit/deletion, app upgrade and uninstall behavior - still need manual verification on Apple Silicon and Intel. +1. The app bundle carries both generated formats and refreshes the managed Welcome notebook on + launch. Native macOS package execution has not yet been run from this Windows development host. +2. Clean-profile launch, replacement of an older Welcome notebook, sibling notebook preservation, + app upgrade and uninstall behavior still need manual verification on Apple Silicon and Intel. 3. The package script supports ad-hoc signing for local smoke tests, but an ad-hoc app is not a distributable release. Developer ID signing, notarization, stapling and offline verification still require release credentials and a macOS runner. ## Required before macOS release signoff -- Verify the setup app's consent, failure recovery and existing-notebook preservation on macOS. -- Verify that the app bundle contains no notebook and the optional DMG sibling contains both - generated formats; verify a second DMG with the optional payload omitted. -- Test clean first launch, restart, upgrade, edit persistence, explicit restore and deletion on +- Verify that the app bundle contains both generated formats and the Welcome copy refreshes on + startup without modifying a sibling notebook. +- Test clean first launch, restart, upgrade, Welcome replacement and uninstall on Apple Silicon and Intel. - Record signing, notarization, stapling, checksums, runner versions and manual results in the release signoff record. diff --git a/packaging/OSX/package.sh b/packaging/OSX/package.sh index e3afa972..1ddd7790 100755 --- a/packaging/OSX/package.sh +++ b/packaging/OSX/package.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # Build a NoteCraft.app, a separate notebook setup app, DMG and CLI archive on macOS. -# Default: universal. Options: --arch aarch64|x86_64|universal, --out DIR, --no-build, --omit-demo. +# Default: universal. Options: --arch aarch64|x86_64|universal, --out DIR, --no-build. # CARGO_TARGET_DIR and DIST may override the build and distribution directories. set -euo pipefail @@ -8,13 +8,11 @@ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" ARCH=universal OUT="${DIST:-$ROOT/dist/macos}" BUILD=1 -INCLUDE_DEMO=1 while [[ $# -gt 0 ]]; do case "$1" in --arch) [[ $# -ge 2 ]] || { echo "--arch needs a value" >&2; exit 2; }; ARCH="$2"; shift 2 ;; --out) [[ $# -ge 2 ]] || { echo "--out needs a value" >&2; exit 2; }; OUT="$2"; shift 2 ;; --no-build) BUILD=0; shift ;; - --omit-demo) INCLUDE_DEMO=0; shift ;; -h|--help) sed -n '2,4p' "$0"; exit 0 ;; *) echo "unknown option: $1" >&2; exit 2 ;; esac @@ -60,7 +58,7 @@ echo "==> NoteCraft $VERSION ($ARCH)" if [[ "$BUILD" = 1 ]]; then rustup target add "${targets[@]}" for target in "${targets[@]}"; do - (cd "$ROOT" && CARGO_TARGET_DIR="$TARGET_ROOT" cargo build --locked --release --target "$target" -p notecraft -p notecraft-cli -p notecraft-setup) + (cd "$ROOT" && CARGO_TARGET_DIR="$TARGET_ROOT" cargo build --locked --release --target "$target" -p notecraft -p notecraft-cli) done fi # Both slices must be built from the same inputs, including local uncommitted work. @@ -80,30 +78,41 @@ trap 'exit 129' HUP trap 'exit 130' INT trap 'exit 143' TERM APP="$WORK/NoteCraft.app" -SETUP_APP="$WORK/Install NoteCraft Welcome Notebook.app" -mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources/licenses" "$SETUP_APP/Contents/MacOS" "$SETUP_APP/Contents/Resources" +mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources/licenses" +mkdir -p "$APP/Contents/Resources/demo" +ditto "$ROOT/docs/demo/DemoNotebook" "$APP/Contents/Resources/demo/welcome-to-notecraft" +for entry in html/_node.toml html/00-start/welcome/index.html cmgfm/_node.toml cmgfm/00-start/welcome/index.md; do + [[ -s "$APP/Contents/Resources/demo/welcome-to-notecraft/$entry" ]] || { echo "demo resource is missing $entry" >&2; exit 1; } +done +for format in html cmgfm; do + languages=0 + for folder in "$APP/Contents/Resources/demo/welcome-to-notecraft/$format"/*; do + [[ -d "$folder" ]] || continue + name="${folder##*/}" + if [[ "$name" =~ ^(1[0-9]|2[0-9])-[a-z]{2}$ ]]; then languages=$((languages + 1)); fi + done + [[ "$languages" = 13 ]] || { echo "$format demo has $languages language folders, expected 13" >&2; exit 1; } +done # --no-build accepts only binaries recorded by a successful package build. The record # binds both executable hashes to the Cargo version and source identity, including foreign slices. for target in "${targets[@]}"; do gui="$TARGET_ROOT/$target/release/notecraft" cli="$TARGET_ROOT/$target/release/notecraft-cli" - setup="$TARGET_ROOT/$target/release/notecraft-setup" record="$TARGET_ROOT/$target/release/.notecraft-osx-provenance" - [[ -x "$gui" && -x "$cli" && -x "$setup" ]] || { echo "missing executable for $target" >&2; exit 1; } + [[ -x "$gui" && -x "$cli" ]] || { echo "missing executable for $target" >&2; exit 1; } expected_arch="${target%%-*}" [[ "$expected_arch" = aarch64 ]] && expected_arch=arm64 - for binary in "$gui" "$cli" "$setup"; do + for binary in "$gui" "$cli"; do [[ "$(lipo -archs "$binary")" = "$expected_arch" ]] || { echo "wrong architecture: $binary" >&2; exit 1; } done gui_hash="$(sha256 "$gui")" cli_hash="$(sha256 "$cli")" - setup_hash="$(sha256 "$setup")" - expected_record="$(printf '%s\n%s\n%s\n%s\n%s' "$VERSION" "$target" "$gui_hash" "$cli_hash" "$setup_hash")" + expected_record="$(printf '%s\n%s\n%s\n%s' "$VERSION" "$target" "$gui_hash" "$cli_hash")" if [[ "$BUILD" = 0 ]]; then [[ -f "$record" && ! -L "$record" ]] || { echo "missing build provenance for $target; build this target with package.sh first" >&2; exit 1; } - [[ "$(head -n 5 "$record")" = "$expected_record" ]] || { echo "stale or changed executable for $target; rebuild without --no-build" >&2; exit 1; } - check_source_provenance "$(tail -n +6 "$record")" "$build_source" 1 + [[ "$(head -n 4 "$record")" = "$expected_record" ]] || { echo "stale or changed executable for $target; rebuild without --no-build" >&2; exit 1; } + check_source_provenance "$(tail -n +5 "$record")" "$build_source" 1 else if native_target "$target"; then check_version "$gui" notecraft @@ -117,18 +126,6 @@ for target in "${targets[@]}"; do fi done -setup_slices=() -for target in "${targets[@]}"; do - setup_slices+=("$TARGET_ROOT/$target/release/notecraft-setup") -done -if [[ "$ARCH" = universal ]]; then - lipo -create "${setup_slices[@]}" -output "$SETUP_APP/Contents/MacOS/notecraft-setup" -else - cp "${setup_slices[0]}" "$SETUP_APP/Contents/MacOS/notecraft-setup" -fi -chmod 755 "$SETUP_APP/Contents/MacOS/notecraft-setup" -lipo -info "$SETUP_APP/Contents/MacOS/notecraft-setup" - for binary in notecraft notecraft-cli; do slices=() for target in "${targets[@]}"; do @@ -152,11 +149,6 @@ sed -e "s|@VERSION@|${VERSION%%[-+]*}|g" -e "s|@FULL_VERSION@|$VERSION|g" \ -e "s|@BUILD@|$build_number|g" -e "s|@BUILD_SHA@|$build_sha|g" \ "$ROOT/packaging/OSX/Info.plist.in" > "$APP/Contents/Info.plist" plutil -lint "$APP/Contents/Info.plist" -sed -e "s|@VERSION@|${VERSION%%[-+]*}|g" -e "s|@FULL_VERSION@|$VERSION|g" \ - -e "s|@BUILD@|$build_number|g" -e "s|@BUILD_SHA@|$build_sha|g" \ - "$ROOT/packaging/OSX/Setup-Info.plist.in" > "$SETUP_APP/Contents/Info.plist" -plutil -lint "$SETUP_APP/Contents/Info.plist" - # Build the .icns from the checked-in PNG family; this keeps the source asset portable. ICONSET="$WORK/notecraft.iconset" mkdir -p "$ICONSET" @@ -166,7 +158,6 @@ for spec in "16:32" "32:64" "128:256" "256:512" "512:1024"; do sips -z "$source_size" "$source_size" "$ROOT/assets/brand/notecraft-512.png" --out "$ICONSET/icon_${size}x${size}@2x.png" >/dev/null done iconutil --convert icns "$ICONSET" --output "$APP/Contents/Resources/notecraft.icns" -cp "$APP/Contents/Resources/notecraft.icns" "$SETUP_APP/Contents/Resources/notecraft.icns" for file in LICENSE-MIT LICENSE-APACHE NOTICE; do install -m 644 "$ROOT/$file" "$APP/Contents/Resources/licenses/$file" @@ -188,12 +179,8 @@ sign() { } sign "$APP/Contents/MacOS/notecraft-cli" sign "$APP" -sign "$SETUP_APP/Contents/MacOS/notecraft-setup" -sign "$SETUP_APP" codesign --verify --strict --deep --verbose=2 "$APP" codesign --verify --strict --verbose=2 "$APP/Contents/MacOS/notecraft-cli" -codesign --verify --strict --deep --verbose=2 "$SETUP_APP" -codesign --verify --strict --verbose=2 "$SETUP_APP/Contents/MacOS/notecraft-setup" if [[ "$ARCH" = universal || ( "$ARCH" = aarch64 && "$(uname -m)" = arm64 ) || \ ( "$ARCH" = x86_64 && "$(uname -m)" = x86_64 ) ]]; then check_version "$APP/Contents/MacOS/notecraft" notecraft @@ -205,18 +192,9 @@ fi DMG_ROOT="$WORK/dmg" mkdir -p "$DMG_ROOT" ditto "$APP" "$DMG_ROOT/NoteCraft.app" -ditto "$SETUP_APP" "$DMG_ROOT/Install NoteCraft Welcome Notebook.app" -if [[ "$INCLUDE_DEMO" = 1 ]]; then - mkdir -p "$DMG_ROOT/Welcome Notebook" - ditto "$ROOT/docs/demo/DemoNotebook" "$DMG_ROOT/Welcome Notebook" - for entry in html/_node.toml cmgfm/_node.toml html/00-start/welcome/index.html cmgfm/00-start/welcome/index.md; do - [[ -s "$DMG_ROOT/Welcome Notebook/$entry" ]] || { echo "demo payload is missing $entry" >&2; exit 1; } - done -fi install -m 644 "$ROOT/packaging/OSX/DMG Read Me.txt" "$DMG_ROOT/Read Me First.txt" app_hash="$(sha256 "$DMG_ROOT/NoteCraft.app/Contents/MacOS/notecraft")" -setup_hash="$(sha256 "$DMG_ROOT/Install NoteCraft Welcome Notebook.app/Contents/MacOS/notecraft-setup")" -printf '%s\n%s\n%s\n%s\n%s\n' "$VERSION" "$ARCH" "$app_hash" "$setup_hash" "$build_source" > "$DMG_ROOT/BuildProvenance.txt" +printf '%s\n%s\n%s\n%s\n' "$VERSION" "$ARCH" "$app_hash" "$build_source" > "$DMG_ROOT/BuildProvenance.txt" ln -s /Applications "$DMG_ROOT/Applications" hdiutil create -volname "NoteCraft $VERSION" -srcfolder "$DMG_ROOT" -ov -format UDZO "$DMG" sign "$DMG" diff --git a/packaging/OSX/test-stale.sh b/packaging/OSX/test-stale.sh index a61056d7..04ea3cca 100755 --- a/packaging/OSX/test-stale.sh +++ b/packaging/OSX/test-stale.sh @@ -11,7 +11,7 @@ case "$ARCH" in *) echo "test-stale.sh expects aarch64 or x86_64" >&2; exit 2 ;; esac SOURCE="$SOURCE_ROOT/$TARGET/release" -for file in notecraft notecraft-cli notecraft-setup .notecraft-osx-provenance; do +for file in notecraft notecraft-cli .notecraft-osx-provenance; do [[ -f "$SOURCE/$file" ]] || { echo "run package.sh for $ARCH before test-stale.sh: missing $SOURCE/$file" >&2; exit 1; } done @@ -22,7 +22,7 @@ trap 'exit 130' INT trap 'exit 143' TERM DEST="$WORK/target/$TARGET/release" mkdir -p "$DEST" -cp "$SOURCE/notecraft" "$SOURCE/notecraft-cli" "$SOURCE/notecraft-setup" "$SOURCE/.notecraft-osx-provenance" "$DEST/" +cp "$SOURCE/notecraft" "$SOURCE/notecraft-cli" "$SOURCE/.notecraft-osx-provenance" "$DEST/" RECORD="$DEST/.notecraft-osx-provenance" expect_rejection() { @@ -43,6 +43,7 @@ cp "$SOURCE/.notecraft-osx-provenance" "$RECORD" printf 'changed' >> "$DEST/notecraft" expect_rejection cp "$SOURCE/.notecraft-osx-provenance" "$RECORD" -printf 'changed' >> "$DEST/notecraft-setup" +cp "$SOURCE/notecraft" "$DEST/notecraft" +printf 'changed' >> "$DEST/notecraft-cli" expect_rejection echo "stale version and changed binary rejected for $ARCH" diff --git a/packaging/OSX/verify.sh b/packaging/OSX/verify.sh index b606a0be..95dc09dc 100755 --- a/packaging/OSX/verify.sh +++ b/packaging/OSX/verify.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # Verify the staged package, mounted DMG and extracted CLI without installing either. -# Usage: packaging/OSX/verify.sh [aarch64|x86_64|universal] [--expect-demo|--expect-no-demo] +# Usage: packaging/OSX/verify.sh [aarch64|x86_64|universal] set -euo pipefail ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" @@ -27,11 +27,10 @@ check_cli_provenance() { [[ "$(cat "$manifest")" = "$expected" ]] || { echo "package provenance mismatch: $binary" >&2; exit 1; } } check_dmg_provenance() { - local manifest="$1" app="$2" setup="$3" expected app_hash setup_hash + local manifest="$1" app="$2" expected app_hash [[ -f "$manifest" ]] || { echo "missing DMG provenance: $manifest" >&2; exit 1; } app_hash="$(sha256 "$app")" - setup_hash="$(sha256 "$setup")" - expected="$(printf '%s\n%s\n%s\n%s\n%s' "$VERSION" "$ARCH" "$app_hash" "$setup_hash" "$build_source")" + expected="$(printf '%s\n%s\n%s\n%s' "$VERSION" "$ARCH" "$app_hash" "$build_source")" [[ "$(cat "$manifest")" = "$expected" ]] || { echo "DMG provenance mismatch" >&2; exit 1; } } check_architectures() { @@ -45,14 +44,6 @@ check_architectures() { done } ARCH="${1:-universal}" -EXPECT_DEMO="any" -if [[ $# -ge 2 ]]; then - case "$2" in - --expect-demo) EXPECT_DEMO=yes ;; - --expect-no-demo) EXPECT_DEMO=no ;; - *) echo "unknown option: $2" >&2; exit 2 ;; - esac -fi case "$ARCH" in aarch64) EXPECTED="arm64"; EXPECTED_COUNT=1 ;; x86_64) EXPECTED="x86_64"; EXPECTED_COUNT=1 ;; @@ -90,24 +81,25 @@ hdiutil attach -readonly -nobrowse -mountpoint "$MOUNT" "$DMG" >/dev/null mounted=1 [[ "$(readlink "$MOUNT/Applications")" = /Applications ]] APP="$MOUNT/NoteCraft.app" -SETUP_APP="$MOUNT/Install NoteCraft Welcome Notebook.app" [[ -x "$APP/Contents/MacOS/notecraft" && -x "$APP/Contents/MacOS/notecraft-cli" ]] [[ -s "$APP/Contents/Resources/notecraft.icns" ]] -[[ -x "$SETUP_APP/Contents/MacOS/notecraft-setup" && -s "$SETUP_APP/Contents/Resources/notecraft.icns" ]] -[[ ! -e "$APP/Contents/Resources/demo" ]] || { echo "the app bundle must not contain the demo notebook" >&2; exit 1; } +for entry in html/_node.toml html/00-start/welcome/index.html cmgfm/_node.toml cmgfm/00-start/welcome/index.md; do + [[ -s "$APP/Contents/Resources/demo/welcome-to-notecraft/$entry" ]] || { echo "the app bundle demo is missing $entry" >&2; exit 1; } +done +for format in html cmgfm; do + languages=0 + for folder in "$APP/Contents/Resources/demo/welcome-to-notecraft/$format"/*; do + [[ -d "$folder" ]] || continue + name="${folder##*/}" + if [[ "$name" =~ ^(1[0-9]|2[0-9])-[a-z]{2}$ ]]; then languages=$((languages + 1)); fi + done + [[ "$languages" = 13 ]] || { echo "$format demo has $languages language folders, expected 13" >&2; exit 1; } +done [[ -s "$MOUNT/Read Me First.txt" ]] for doc in licenses/LICENSE-MIT licenses/LICENSE-APACHE licenses/NOTICE ATTRIBUTION.md licenses/PDF-RENDERING-NOTICES.txt; do [[ -s "$APP/Contents/Resources/$doc" ]] || { echo "app notice missing: $doc" >&2; exit 1; } done -if [[ -d "$MOUNT/Welcome Notebook" ]]; then - [[ "$EXPECT_DEMO" != no ]] || { echo "unexpected optional demo payload in no-demo DMG" >&2; exit 1; } - for entry in html/_node.toml cmgfm/_node.toml html/00-start/welcome/index.html cmgfm/00-start/welcome/index.md; do - [[ -s "$MOUNT/Welcome Notebook/$entry" ]] || { echo "separate demo payload is missing $entry" >&2; exit 1; } - done - diff -rq "$ROOT/docs/demo/DemoNotebook" "$MOUNT/Welcome Notebook" -else - [[ "$EXPECT_DEMO" != yes ]] || { echo "expected separate Welcome Notebook payload is absent" >&2; exit 1; } -fi +diff -rq "$ROOT/docs/demo/DemoNotebook" "$APP/Contents/Resources/demo/welcome-to-notecraft" plutil -lint "$APP/Contents/Info.plist" [[ "$(plutil -extract CFBundleIdentifier raw -o - "$APP/Contents/Info.plist")" = com.alientechsoftware.notecraft ]] [[ "$(plutil -extract CFBundleExecutable raw -o - "$APP/Contents/Info.plist")" = notecraft ]] @@ -118,24 +110,12 @@ plutil -lint "$APP/Contents/Info.plist" [[ "$(plutil -extract NoteCraftBuildCommit raw -o - "$APP/Contents/Info.plist")" = "$build_sha" ]] codesign --verify --strict --deep --verbose=2 "$APP" codesign --verify --strict --verbose=2 "$APP/Contents/MacOS/notecraft-cli" -codesign --verify --strict --deep --verbose=2 "$SETUP_APP" -codesign --verify --strict --verbose=2 "$SETUP_APP/Contents/MacOS/notecraft-setup" -plutil -lint "$SETUP_APP/Contents/Info.plist" -[[ "$(plutil -extract CFBundleIdentifier raw -o - "$SETUP_APP/Contents/Info.plist")" = com.alientechsoftware.notecraft.setup ]] -[[ "$(plutil -extract CFBundleExecutable raw -o - "$SETUP_APP/Contents/Info.plist")" = notecraft-setup ]] -[[ "$(plutil -extract CFBundleShortVersionString raw -o - "$SETUP_APP/Contents/Info.plist")" = "${VERSION%%[-+]*}" ]] -[[ "$(plutil -extract NoteCraftVersion raw -o - "$SETUP_APP/Contents/Info.plist")" = "$VERSION" ]] -[[ "$(plutil -extract CFBundleVersion raw -o - "$SETUP_APP/Contents/Info.plist")" = "$build_number" ]] -[[ "$(plutil -extract NoteCraftBuildCommit raw -o - "$SETUP_APP/Contents/Info.plist")" = "$build_sha" ]] -check_dmg_provenance "$MOUNT/BuildProvenance.txt" "$APP/Contents/MacOS/notecraft" "$SETUP_APP/Contents/MacOS/notecraft-setup" +check_dmg_provenance "$MOUNT/BuildProvenance.txt" "$APP/Contents/MacOS/notecraft" check_architectures "$APP/Contents/MacOS/notecraft" check_architectures "$APP/Contents/MacOS/notecraft-cli" -check_architectures "$SETUP_APP/Contents/MacOS/notecraft-setup" ditto "$APP" "$WORK/NoteCraft.app" -ditto "$SETUP_APP" "$WORK/Install NoteCraft Welcome Notebook.app" codesign --verify --strict --deep --verbose=2 "$WORK/NoteCraft.app" -codesign --verify --strict --deep --verbose=2 "$WORK/Install NoteCraft Welcome Notebook.app" -check_dmg_provenance "$MOUNT/BuildProvenance.txt" "$WORK/NoteCraft.app/Contents/MacOS/notecraft" "$WORK/Install NoteCraft Welcome Notebook.app/Contents/MacOS/notecraft-setup" +check_dmg_provenance "$MOUNT/BuildProvenance.txt" "$WORK/NoteCraft.app/Contents/MacOS/notecraft" if [[ "$ARCH" = universal || ( "$ARCH" = aarch64 && "$(uname -m)" = arm64 ) || \ ( "$ARCH" = x86_64 && "$(uname -m)" = x86_64 ) ]]; then check_version "$WORK/NoteCraft.app/Contents/MacOS/notecraft" notecraft diff --git a/packaging/installation artifacts.md b/packaging/installation artifacts.md index 12c879c6..e80e1f61 100644 --- a/packaging/installation artifacts.md +++ b/packaging/installation artifacts.md @@ -1,56 +1,45 @@ # Installation artifacts -Status: product contract approved by the owner on 2026-11-06. This is the single authority for -installation artifact responsibilities and the User Assistance demo notebook. Windows and Linux -now use separate setup helpers. macOS DMGs carry the optional notebook beside the app and include -a separate, consented setup app. Clean installed-flow verification remains open for desktop. +Status: product contract updated by the owner on 2026-11-07. This is the single authority for +installation artifact responsibilities and the User Assistance demo notebook. Every app launch +refreshes the managed Welcome notebook from the generated content bundled with the application. ## Separate installation artifacts Every distribution has two logically separate artifacts: -1. **Application binaries**: executable code and runtime dependencies, deployed to the platform's - normal application location. -2. **User Assistance demo notebook**: user-facing notebook files, deployed to the target user's - normal `NoteCraft` notebooks folder. +1. **Application binaries and bundled source content**: executable code plus the two generated + Welcome notebook formats, deployed to the platform's normal application location. +2. **Managed Welcome notebook**: a per-user copy in the target user's normal `NoteCraft` + notebooks folder, refreshed by the app when it starts. -One outer download or installer may contain both artifacts. One MSI, DMG, APK, archive, or other -package can carry both. Its manifest, staging, and verification must still identify the binaries -and notebook as separate payloads. The notebook is not executable code and must not be compiled -into the app binary as a substitute for installation. +Each installer carries the generated content with the app so the app can provision it without a +separate setup download, helper choice, or network request. The content remains ordinary notebook +files; it is not executable code. The authored notebook source is `docs/demo/scripts/content`. `cargo xtask demo` generates the -official HTML and CMGFM versions under `docs/demo/DemoNotebook`. Both formats belong to the User -Assistance artifact and must remain in parity. Installers use these generated outputs, never -`my-notebooks/welcome-notebook` or another local test copy. +official HTML and CMGFM notebooks under `docs/demo/DemoNotebook`, each with all 13 languages. +Both are built, bundled, and tested for parity. Installers use this generated source, never +`my-notebooks/welcome-notebook` or another local test copy. NoteCraft supports both formats for +the Welcome notebook and for notebooks created or opened by users. ## Separation of responsibility -The installation tool owns deployment of both artifacts: +The running app owns the per-user copy: - Install application binaries in the application location. - Install the User Assistance notebook in the user's normal notebooks folder. -- On a fresh install, create the notebook only if it is absent. -- On upgrade, preserve an existing notebook, including user edits and deletion. +- At app startup, create or replace only `welcome-to-notecraft` from the bundled HTML and CMGFM + formats. This refreshes app-authored content on every launch. +- Preserve every sibling notebook and its contents. - On uninstall, remove application files only; leave user notebooks in place. -- Report installation failures through the installer or setup tool. +- If refreshing the Welcome notebook fails, report the error and preserve the existing copy. -Windows starts the separate `notecraft-setup` helper from the MSI finish action and its shortcuts. -Linux desktop entries and the AppImage launcher start the same helper. It runs in the signed-in -user's context, installs only when the User Assistance folder is absent, records completion outside -app preferences, and then opens NoteCraft. Linux system package scripts never write into a guessed -user's home. If a package omits the optional payload, the helper opens NoteCraft without copying -anything. - -The application does not install the notebook. It must not unpack, seed, copy, refresh, replace, -repair, or delete the notebook at startup or in response to an app update. After setup, the app -discovers and opens the already-installed notebook through its ordinary notebook discovery and -open behavior. If setup did not deploy it, the app does not silently compensate. - -After installation, the Welcome notebook is ordinary user-owned notebook data. Users can edit, -move, sync, back up, or delete it. App upgrades must not overwrite or recreate it. Android's -app-specific storage is removed by the OS when NoteCraft is uninstalled; retaining Android -notebooks after uninstall requires a future shared-storage design. +Desktop apps copy the generated source from the installed package or app bundle into the selected +user notebook root. Android refreshes from APK assets before opening the native app. Browser startup +refreshes it from the website archive on each non-invited session. The Welcome notebook's content +and edits are replaced with the release-authored version on app start; sibling notebooks are +untouched. Android app-specific storage follows Android's normal uninstall lifecycle. ## Platform installation contract @@ -62,55 +51,45 @@ do not guess a home or storage path when the platform provides an API. | Platform | Application binaries | User Assistance notebook | Installation owner | |---|---|---|---| -| Windows | Normal per-machine or per-user app location | Current user's Documents/NoteCraft/welcome-to-notecraft | MSI or its setup helper, running for the intended user | -| Linux | Normal package or portable-app location | Current user's Documents/NoteCraft/welcome-to-notecraft | A user-context setup tool; a system package script must not guess which user's home to modify | -| macOS | `NoteCraft.app` copied to Applications | Current user's Documents/NoteCraft/welcome-to-notecraft | Separate, consented `Install NoteCraft Welcome Notebook.app` in the DMG; dragging the app alone does not perform this step | -| Android | Installed APK application package | App-specific external files/NoteCraft/welcome-to-notecraft, beside notebooks created on-device | The APK's dedicated setup activity, before it opens the NoteCraft activity | - -An installation format that cannot perform the per-user notebook step by itself must provide a -separate installation/setup component with a clear user action. The Android setup activity is a -distinct installer entry point in the APK. It offers to install the optional payload or skip it, -then opens NoteCraft. The NoteCraft activity itself only discovers and opens notebooks. Do not -claim that an artifact installs the notebook until a clean installation proves the notebook is -present before the NoteCraft activity launches. - -## Current implementation gap - -Windows and Linux package staging now follows the separate-payload contract: - -- The Windows MSI and portable ZIP include the setup helper and support builds with the optional - notebook included or omitted. Both MSI variants compile; installation on a clean Windows profile, - upgrade and uninstall behavior still need a VM smoke test. -- Linux tar, Debian and AppImage packages include the setup helper and support builds with the - optional notebook included or omitted. Package builds and tar/DEB content smoke tests pass; - running the helper from an installed package and checking upgrade/uninstall behavior still need - a clean user-profile test. -- The helper and app share the saved notebook root. The app's current fallback is - Documents/NoteCraft under the user's home; redirected Windows Documents folders are not yet - resolved through the OS known-folder API. - -Android's separate APK setup flow passed a fresh tablet-emulator install on 2026-11-06: setup -installed the payload, NoteCraft opened its Welcome page from the app-specific notebook folder, and -a relaunch kept the notebook and bypassed setup. Android upgrade and user-deletion flows remain -unverified. +| Website demo | Browser app (JavaScript and WebAssembly) | `/NoteCraft/welcome-to-notecraft`, containing HTML and CMGFM | Browser startup refreshes it from the two-format archive | +| Windows | Normal per-machine or per-user app location | Current user's Documents/NoteCraft/welcome-to-notecraft | App startup copies from the package's bundled source | +| Linux | Normal package or portable-app location | Current user's Documents/NoteCraft/welcome-to-notecraft | App startup copies from the package's bundled source | +| macOS | `NoteCraft.app` copied to Applications | Current user's Documents/NoteCraft/welcome-to-notecraft | App startup copies from app resources | +| Android | Installed APK application package | App-specific external files/NoteCraft/welcome-to-notecraft | APK setup activity refreshes both asset formats before opening NoteCraft | + +The browser archive contains both directories under `docs/demo/DemoNotebook`, is version-checked +in the website workflow, and is loaded under the same `/NoteCraft` root as other browser notebooks. +The generic engine sample remains a separate sample notebook and is not the release Welcome +notebook. + +The Android launch activity refreshes the managed notebook from both APK asset formats before +opening the native app. + +## Current implementation status + +Desktop and mobile package staging follows the app-managed refresh contract: + +- The Windows MSI and portable ZIP include both generated formats. Clean VM refresh and + sibling-preservation checks remain required. +- Linux packages include both generated formats. Installed-run refresh and sibling-preservation + checks remain required. +- macOS bundles both formats in app resources; native launch verification remains required. + +Android stages both formats as APK assets and refreshes them before opening NoteCraft. Build and +emulator checks remain required. ## Installation verification For each supported artifact and platform, signoff proves: -1. The final package contains two separately identifiable payloads: app binaries and both - generated notebook formats. -2. A clean installation or first desktop setup places the notebook in the platform's expected - location before NoteCraft opens it. Android setup may be skipped when the package omits the - optional payload. -3. The app opens the installed notebook without creating or copying it at startup. -4. An edit survives app restart and application upgrade. Setup completion is separate from app - preferences so resetting preferences does not reinstall a deleted notebook. -5. A user-deleted notebook stays deleted after restart and upgrade. +1. The package contains both generated formats and all 13 languages. +2. App startup creates or replaces only `welcome-to-notecraft` in the platform notebook root. +3. A sentinel sibling notebook stays byte-for-byte unchanged. +4. Both format variants retain their page tree, assets, and metadata. +5. The managed Welcome notebook is refreshed from app content on restart. 6. Desktop uninstall removes app binaries and leaves the user's notebook untouched. Android uninstall removes app-specific notebook files as required by the OS storage model. -7. A failed notebook installation is reported by the installation tool; the app does not install - a fallback copy. +7. A failed refresh is reported and does not replace the existing copy with a partial notebook. Run `cargo xtask demo-check` and `cargo test -p notecraft-formats --test format_parity` for the source outputs. Then inspect the diff --git a/packaging/linux/AppRun b/packaging/linux/AppRun index d65904bd..94e30b61 100644 --- a/packaging/linux/AppRun +++ b/packaging/linux/AppRun @@ -1,4 +1,4 @@ #!/usr/bin/env bash set -euo pipefail HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -exec "$HERE/usr/bin/notecraft-setup" "$@" +exec "$HERE/usr/bin/notecraft" "$@" diff --git a/packaging/linux/com.alientechsoftware.notecraft.desktop b/packaging/linux/com.alientechsoftware.notecraft.desktop index 43dd1abb..6ad7680a 100644 --- a/packaging/linux/com.alientechsoftware.notecraft.desktop +++ b/packaging/linux/com.alientechsoftware.notecraft.desktop @@ -3,8 +3,8 @@ Type=Application Name=NoteCraft GenericName=Note Taking Application Comment=Notes as plain files in plain folders -Exec=notecraft-setup %U -TryExec=notecraft-setup +Exec=notecraft %U +TryExec=notecraft Icon=com.alientechsoftware.notecraft Terminal=false StartupNotify=true diff --git a/packaging/linux/nfpm.yaml b/packaging/linux/nfpm.yaml index 1b157d28..42844a09 100644 --- a/packaging/linux/nfpm.yaml +++ b/packaging/linux/nfpm.yaml @@ -16,9 +16,6 @@ contents: - src: ${STAGE}/usr/bin/notecraft dst: /usr/bin/notecraft file_info: { mode: 0755 } - - src: ${STAGE}/usr/bin/notecraft-setup - dst: /usr/bin/notecraft-setup - file_info: { mode: 0755 } - src: ${STAGE}/usr/share/applications/com.alientechsoftware.notecraft.desktop dst: /usr/share/applications/com.alientechsoftware.notecraft.desktop - src: ${STAGE}/usr/share/icons/hicolor/32x32/apps/com.alientechsoftware.notecraft.png diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index 1648bde1..e05327c1 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -2,14 +2,15 @@ # Build NoteCraft Linux release packages from one staged FHS tree. # # Usage: -# packaging/linux/package.sh [--skip-build] [--omit-demo] [--formats "tar appimage deb rpm"] +# packaging/linux/package.sh [--skip-build] [--formats "tar appimage deb rpm"] # # The default format is tar. AppImage needs appimagetool. Deb and rpm need nfpm. # Missing optional tools are reported as errors only when their format is requested. set -euo pipefail ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" -VERSION="$(sed -n 's/^version = "\([0-9][0-9.]*\(-[^\"]*\)\?\)"$/\1/p' "$ROOT/Cargo.toml" | head -n 1)" +VERSION="$(tr -d '\r' < "$ROOT/Cargo.toml" | sed -n '/^\[workspace.package\]/,/^\[/s/^version = "\([^"]*\)"$/\1/p' | head -n 1)" +[[ -n "$VERSION" ]] || { echo "could not read workspace package version from Cargo.toml" >&2; exit 1; } ARCH="$(uname -m)" case "$ARCH" in x86_64) NFPM_ARCH=amd64 ;; @@ -18,12 +19,10 @@ case "$ARCH" in esac SKIP_BUILD=0 -INCLUDE_DEMO=1 FORMATS="tar" while [[ $# -gt 0 ]]; do case "$1" in --skip-build) SKIP_BUILD=1; shift ;; - --omit-demo) INCLUDE_DEMO=0; shift ;; --formats) FORMATS="${2:?--formats needs a value}"; shift 2 ;; -h|--help) sed -n '2,9p' "$0"; exit 0 ;; *) echo "unknown argument: $1" >&2; exit 2 ;; @@ -47,15 +46,12 @@ mkdir -p "$DIST" rm -rf "$WORK" if [ "$SKIP_BUILD" = 0 ]; then - (cd "$ROOT" && cargo build --release --locked -p notecraft -p notecraft-setup) + (cd "$ROOT" && cargo build --release --locked -p notecraft) fi BIN="${CARGO_TARGET_DIR:-$ROOT/target}/release/notecraft" [ -x "$BIN" ] || { echo "release binary not found: $BIN" >&2; exit 1; } install -Dm755 "$BIN" "$STAGE/usr/bin/notecraft" -SETUP_BIN="${CARGO_TARGET_DIR:-$ROOT/target}/release/notecraft-setup" -[ -x "$SETUP_BIN" ] || { echo "setup helper not found: $SETUP_BIN" >&2; exit 1; } -install -Dm755 "$SETUP_BIN" "$STAGE/usr/bin/notecraft-setup" install -Dm644 "$ROOT/packaging/linux/com.alientechsoftware.notecraft.desktop" \ "$STAGE/usr/share/applications/com.alientechsoftware.notecraft.desktop" @@ -68,20 +64,21 @@ install -Dm644 "$ROOT/LICENSE-MIT" "$STAGE/usr/share/doc/notecraft/LICENSE-MIT" install -Dm644 "$ROOT/LICENSE-APACHE" "$STAGE/usr/share/doc/notecraft/LICENSE-APACHE" install -Dm644 "$ROOT/NOTICE" "$STAGE/usr/share/doc/notecraft/NOTICE" -if [ "$INCLUDE_DEMO" = 1 ]; then - # Keep the optional User Assistance notebook as a distinct payload beside the app binaries. - DEMO_SOURCE="$ROOT/docs/demo/DemoNotebook" - for format in html cmgfm; do - [ -d "$DEMO_SOURCE/$format" ] || { echo "required demo format is missing: $format" >&2; exit 1; } - done - DEMO_DEST="$STAGE/usr/share/notecraft/demo/welcome-to-notecraft" - mkdir -p "$DEMO_DEST" - cp -R "$DEMO_SOURCE/." "$DEMO_DEST/" - [ -f "$DEMO_DEST/html/_node.toml" ] && [ -f "$DEMO_DEST/cmgfm/_node.toml" ] && \ - [ -f "$DEMO_DEST/html/00-start/welcome/index.html" ] && [ -f "$DEMO_DEST/cmgfm/00-start/welcome/index.md" ] || { - echo "demo was not staged" >&2; exit 1; - } -fi +# The app copies both generated formats into the user's notebooks folder at startup. +DEMO_SOURCE="$ROOT/docs/demo/DemoNotebook" +for format in html cmgfm; do + [ -d "$DEMO_SOURCE/$format" ] || { echo "required $format demo format is missing" >&2; exit 1; } + [ -f "$DEMO_SOURCE/$format/_node.toml" ] || { echo "required $format demo notebook is missing" >&2; exit 1; } + count=$(find "$DEMO_SOURCE/$format" -mindepth 1 -maxdepth 1 -type d -regex '.*/\(1[0-9]\|2[0-9]\)-.*' | wc -l) + [ "$count" -eq 13 ] || { echo "$format demo has $count language folders, expected 13" >&2; exit 1; } +done +DEMO_DEST="$STAGE/usr/share/notecraft/demo/welcome-to-notecraft" +mkdir -p "$DEMO_DEST" +cp -R "$DEMO_SOURCE/." "$DEMO_DEST/" +[ -f "$DEMO_DEST/html/_node.toml" ] && [ -f "$DEMO_DEST/html/00-start/welcome/index.html" ] && \ + [ -f "$DEMO_DEST/cmgfm/_node.toml" ] && [ -f "$DEMO_DEST/cmgfm/00-start/welcome/index.md" ] || { + echo "paired demo payload was not staged" >&2; exit 1; +} if has_format tar; then mkdir -p "$DIST/tar" @@ -98,9 +95,6 @@ if has_format deb || has_format rpm; then -e "s|\${VERSION}|$VERSION|g" -e "s|\${NFPM_ARCH}|$NFPM_ARCH|g" ) - if [ "$INCLUDE_DEMO" = 0 ]; then - NFPM_SED_ARGS+=( -e '/^ - src: .*\/usr\/share\/notecraft\/demo\/$/,/^ type: tree$/d' ) - fi NFPM_ARCH="$NFPM_ARCH" VERSION="$VERSION" STAGE="$STAGE" \ sed "${NFPM_SED_ARGS[@]}" "$ROOT/packaging/linux/nfpm.yaml" > "$WORK/nfpm.yaml" for format in deb rpm; do diff --git a/packaging/linux/test.sh b/packaging/linux/test.sh index 9b14e6a4..b1bf843a 100755 --- a/packaging/linux/test.sh +++ b/packaging/linux/test.sh @@ -1,9 +1,10 @@ #!/usr/bin/env bash -# Smoke-test the dependency-light Linux tarball packaging path. +# Smoke-test Linux package staging and both generated Welcome notebook formats. set -euo pipefail ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" -VERSION="$(sed -n 's/^version = "\([0-9][0-9.]*\(-[^\"]*\)\?\)"$/\1/p' "$ROOT/Cargo.toml" | head -n 1)" +VERSION="$(tr -d '\r' < "$ROOT/Cargo.toml" | sed -n '/^\[workspace.package\]/,/^\[/s/^version = "\([^"]*\)"$/\1/p' | head -n 1)" +[[ -n "$VERSION" ]] || { echo "could not read workspace package version from Cargo.toml" >&2; exit 1; } DIST="$(mktemp -d)" trap 'rm -rf "$DIST"' EXIT @@ -15,45 +16,26 @@ ARCH="$(uname -m)" ARCHIVE="$DIST/notecraft-$VERSION-linux-$ARCH.tar.gz" [ -s "$ARCHIVE" ] || { echo "missing package: $ARCHIVE" >&2; exit 1; } tar -tzf "$ARCHIVE" | grep -Fx "notecraft-$VERSION-linux-$ARCH/bin/notecraft" >/dev/null -tar -tzf "$ARCHIVE" | grep -Fx "notecraft-$VERSION-linux-$ARCH/share/applications/com.alientechsoftware.notecraft.desktop" >/dev/null -tar -tzf "$ARCHIVE" | grep -Fx "notecraft-$VERSION-linux-$ARCH/share/icons/hicolor/256x256/apps/com.alientechsoftware.notecraft.png" >/dev/null -tar -tzf "$ARCHIVE" | grep -Fx "notecraft-$VERSION-linux-$ARCH/bin/notecraft-setup" >/dev/null -tar -tzf "$ARCHIVE" | grep -Fx "notecraft-$VERSION-linux-$ARCH/share/notecraft/demo/welcome-to-notecraft/html/_node.toml" >/dev/null -tar -tzf "$ARCHIVE" | grep -Fx "notecraft-$VERSION-linux-$ARCH/share/notecraft/demo/welcome-to-notecraft/cmgfm/_node.toml" >/dev/null -tar -tzf "$ARCHIVE" | grep -Fx "notecraft-$VERSION-linux-$ARCH/share/notecraft/demo/welcome-to-notecraft/html/00-start/welcome/index.html" >/dev/null -tar -tzf "$ARCHIVE" | grep -Fx "notecraft-$VERSION-linux-$ARCH/share/notecraft/demo/welcome-to-notecraft/cmgfm/00-start/welcome/index.md" >/dev/null -echo "linux packaging smoke test passed: $ARCHIVE" - -# A package without optional User Assistance files still carries the app and setup helper. -DIST="$DIST" "$ROOT/packaging/linux/package.sh" --skip-build --omit-demo --formats tar -[ -s "$ARCHIVE" ] || { echo "missing no-demo package: $ARCHIVE" >&2; exit 1; } -tar -tzf "$ARCHIVE" | grep -Fx "notecraft-$VERSION-linux-$ARCH/bin/notecraft" >/dev/null -tar -tzf "$ARCHIVE" | grep -Fx "notecraft-$VERSION-linux-$ARCH/bin/notecraft-setup" >/dev/null -if tar -tzf "$ARCHIVE" | grep -F "/share/notecraft/demo/" >/dev/null; then - echo "omitted User Assistance payload is present in the Linux package" >&2 - exit 1 -fi -echo "linux no-demo packaging smoke test passed" +for path in \ + "share/notecraft/demo/welcome-to-notecraft/html/_node.toml" \ + "share/notecraft/demo/welcome-to-notecraft/html/00-start/welcome/index.html" \ + "share/notecraft/demo/welcome-to-notecraft/cmgfm/_node.toml" \ + "share/notecraft/demo/welcome-to-notecraft/cmgfm/00-start/welcome/index.md"; do + tar -tzf "$ARCHIVE" | grep -Fx "notecraft-$VERSION-linux-$ARCH/$path" >/dev/null +done +for format in html cmgfm; do + count=$(tar -tzf "$ARCHIVE" | awk -F/ -v base="notecraft-$VERSION-linux-$ARCH" -v format="$format" \ + '$1 == base && $2 == "share" && $3 == "notecraft" && $4 == "demo" && $5 == "welcome-to-notecraft" && $6 == format && $7 ~ /^(1[0-9]|2[0-9])-[a-z][a-z]$/ { found[$7] = 1 } END { print length(found) }') + [ "$count" -eq 13 ] || { echo "$format package contains $count language folders, expected 13" >&2; exit 1; } +done +echo "linux paired-demo packaging smoke test passed: $ARCHIVE" if command -v nfpm >/dev/null 2>&1 && command -v dpkg-deb >/dev/null 2>&1; then PKG_DIST="$(mktemp -d)" trap 'rm -rf "$DIST" "$PKG_DIST"' EXIT DIST="$PKG_DIST" "$ROOT/packaging/linux/package.sh" --skip-build --formats deb DEB="$PKG_DIST/notecraft-$VERSION-linux-$ARCH.deb" - dpkg-deb -c "$DEB" | grep -F "/usr/bin/notecraft-setup" >/dev/null - dpkg-deb -c "$DEB" | - grep -F "/usr/share/notecraft/demo/welcome-to-notecraft/html/_node.toml" >/dev/null - dpkg-deb -c "$DEB" | - grep -F "/usr/share/notecraft/demo/welcome-to-notecraft/cmgfm/_node.toml" >/dev/null - dpkg-deb -c "$DEB" | - grep -F "/usr/share/notecraft/demo/welcome-to-notecraft/html/00-start/welcome/index.html" >/dev/null - OMIT_DIST="$(mktemp -d)" - DIST="$OMIT_DIST" "$ROOT/packaging/linux/package.sh" --skip-build --omit-demo --formats deb - OMIT_DEB="$OMIT_DIST/notecraft-$VERSION-linux-$ARCH.deb" - dpkg-deb -c "$OMIT_DEB" | grep -F "/usr/bin/notecraft-setup" >/dev/null - if dpkg-deb -c "$OMIT_DEB" | grep -F "/usr/share/notecraft/demo/" >/dev/null; then - echo "omitted User Assistance payload is present in the Debian package" >&2 - exit 1 - fi - echo "debian package setup-helper and optional-payload checks passed" + dpkg-deb -c "$DEB" | grep -F "/usr/share/notecraft/demo/welcome-to-notecraft/html/00-start/welcome/index.html" >/dev/null + dpkg-deb -c "$DEB" | grep -F "/usr/share/notecraft/demo/welcome-to-notecraft/cmgfm/00-start/welcome/index.md" >/dev/null + echo "debian paired-demo package checks passed" fi diff --git a/packaging/windows/notecraft.wxs b/packaging/windows/notecraft.wxs index 1ec2a43f..3186da3a 100644 --- a/packaging/windows/notecraft.wxs +++ b/packaging/windows/notecraft.wxs @@ -10,10 +10,8 @@ Per-machine install into Program Files with a Start Menu shortcut. The installer shows the standard WiX dialogs: welcome and licence, progress, and a finish page. - The app and optional notebook are separate payloads. On first launch, the distinct - notecraft-setup helper copies the notebook into the user's normal notebooks folder only when absent. - The helper records completion so an upgrade or user deletion never triggers a replacement. - Uninstall removes only the program files and the installer-owned copy under Program Files. + The app carries both generated Welcome notebook formats and refreshes only its dedicated + per-user Welcome notebook folder at startup. Other notebook folders remain unchanged. UpgradeCode and the component GUIDs below belong to NoteCraft alone. Never change the UpgradeCode after the first public release: Windows Installer would stop treating a new @@ -46,12 +44,12 @@ - + - + @@ -63,24 +61,14 @@ - - - - - - - - - - - + @@ -88,6 +76,11 @@ Description="NoteCraft note taking" WorkingDirectory="INSTALLFOLDER" Advertise="yes" Icon="NotecraftIcon.ico" IconIndex="0" /> + + + + + @@ -97,7 +90,7 @@ - + @@ -125,10 +118,8 @@ - - diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index 0ae03178..55165ae1 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -5,7 +5,7 @@ .DESCRIPTION Produces, in $env:DIST (default: dist/release): notecraft--windows-x64.msi per-machine installer (WiX v5) - notecraft--windows-x64-portable.zip NoteCraft app, setup helper, and CLI + notecraft--windows-x64-portable.zip NoteCraft app, bundled Welcome notebook, and CLI SHA256SUMS.txt checksums of the files above The binaries link the C runtime statically (+crt-static), so neither the MSI nor the portable @@ -28,7 +28,6 @@ param( [switch] $SkipBuild, [switch] $ZipOnly, - [switch] $OmitDemo, [string] $BridgeProject = (Join-Path $PSScriptRoot '..\..\tools\officeimo\OfficeIMO.NoteCraft.Bridge\OfficeIMO.NoteCraft.Bridge.csproj'), [string] $BridgeBinary = $env:NOTECRAFT_OFFICEIMO_BRIDGE ) @@ -68,7 +67,7 @@ if (-not $SkipBuild) { # proc-macros are unaffected. $flagVar = 'CARGO_TARGET_' + ($Target.ToUpper() -replace '-', '_') + '_RUSTFLAGS' [Environment]::SetEnvironmentVariable($flagVar, '-C target-feature=+crt-static') - Invoke-Native "cargo build ($Target)" { cargo build --release --locked -p notecraft -p notecraft-cli -p notecraft-setup --target $Target } + Invoke-Native "cargo build ($Target)" { cargo build --release --locked -p notecraft -p notecraft-cli --target $Target } } $Bin = Join-Path $TargetDir "$Target\release" @@ -81,7 +80,7 @@ function Get-PeHeader([string] $Path) { $pe = [BitConverter]::ToInt32($bytes, 0x3C) return @{ Machine = [BitConverter]::ToUInt16($bytes, $pe + 4); Subsystem = [BitConverter]::ToUInt16($bytes, $pe + 0x5C) } } -foreach ($check in @(@('notecraft.exe', 2), @('notecraft-cli.exe', 3), @('notecraft-setup.exe', 2))) { +foreach ($check in @(@('notecraft.exe', 2), @('notecraft-cli.exe', 3))) { $h = Get-PeHeader (Join-Path $Bin $check[0]) if ($h.Machine -ne 0x8664) { throw "$($check[0]) is for machine 0x$('{0:X}' -f $h.Machine), expected 0x8664 ($Arch)" } if ($h.Subsystem -ne $check[1]) { throw "$($check[0]) has PE subsystem $($h.Subsystem), expected $($check[1])" } @@ -111,27 +110,26 @@ foreach ($name in @('notecraft.exe', 'notecraft-cli.exe')) { $Stage = Join-Path $TargetDir "windows-package\$Arch" Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Stage | Out-Null -Copy-Item (Join-Path $Bin 'notecraft.exe'), (Join-Path $Bin 'notecraft-cli.exe'), (Join-Path $Bin 'notecraft-setup.exe') $Stage +Copy-Item (Join-Path $Bin 'notecraft.exe'), (Join-Path $Bin 'notecraft-cli.exe') $Stage -if (-not $OmitDemo) { - # Keep both generated formats in a distinct package payload beside the app binaries. + # The app copies both generated formats into the user's notebooks folder at startup. $DemoSource = Join-Path $Root 'docs\demo\DemoNotebook' foreach ($format in 'html', 'cmgfm') { - $formatDir = Join-Path $DemoSource $format - if (-not (Test-Path $formatDir -PathType Container)) { throw "required demo format is missing: $formatDir" } - if (-not (Test-Path (Join-Path $formatDir '_node.toml') -PathType Leaf)) { throw "required notebook metadata is missing: $formatDir\_node.toml" } - $files = @(Get-ChildItem -Path $formatDir -File -Recurse) - if ($files.Count -eq 0) { throw "demo format is empty: $formatDir" } - $languages = @(Get-ChildItem -Path $formatDir -Directory | Where-Object { $_.Name -match '^(1\d|2\d)-' }) - if ($languages.Count -ne 13) { throw "demo format $format has $($languages.Count) language folders, expected 13" } + $FormatRoot = Join-Path $DemoSource $format + if (-not (Test-Path $FormatRoot -PathType Container)) { throw "required $format demo format is missing: $FormatRoot" } + if (-not (Test-Path (Join-Path $FormatRoot '_node.toml') -PathType Leaf)) { throw "required $format notebook metadata is missing" } + $Languages = @(Get-ChildItem -Path $FormatRoot -Directory | Where-Object { $_.Name -match '^(1\d|2\d)-' }) + if ($Languages.Count -ne 13) { throw "$format demo has $($Languages.Count) language folders, expected 13" } } + $files = @(Get-ChildItem -Path $DemoSource -File -Recurse) + if ($files.Count -eq 0) { throw "generated demo formats are empty: $DemoSource" } $DemoStage = Join-Path $Stage 'demo\welcome-to-notecraft' New-Item -ItemType Directory -Force -Path $DemoStage | Out-Null Copy-Item (Join-Path $DemoSource '*') $DemoStage -Recurse - if (-not (Test-Path (Join-Path $DemoStage 'html\00-start\welcome\index.html'))) { - throw 'demo staging failed: HTML start page is missing' + if (-not (Test-Path (Join-Path $DemoStage 'html\00-start\welcome\index.html')) -or + -not (Test-Path (Join-Path $DemoStage 'cmgfm\00-start\welcome\index.md'))) { + throw 'demo staging failed: a format start page is missing' } -} # The importer is part of the Windows product, not an optional file that can silently be # omitted from a release. Build and stage the self-contained OfficeIMO bridge beside NoteCraft. @@ -145,7 +143,7 @@ $BridgeExe = Join-Path $BridgeStage 'importers\officeimo\win-x64\officeimo-notec if (-not (Test-Path $BridgeExe)) { throw "OfficeIMO bridge was not produced: $BridgeExe" } Copy-Item (Join-Path $BridgeStage 'importers') $Stage -Recurse -& (Join-Path $PSScriptRoot 'sign.ps1') (Join-Path $Stage 'notecraft.exe') (Join-Path $Stage 'notecraft-cli.exe') (Join-Path $Stage 'notecraft-setup.exe') +& (Join-Path $PSScriptRoot 'sign.ps1') (Join-Path $Stage 'notecraft.exe') (Join-Path $Stage 'notecraft-cli.exe') # The notices travel with the program: the installer and the portable zip both carry them, and the # licence texts they name, so a copy handed on alone still says what it contains. @@ -193,11 +191,10 @@ if (-not $ZipOnly) { $Msi = Join-Path $Dist "notecraft-$Version-windows-$Arch.msi" Invoke-Native 'wix build' { - $IncludeDemo = if ($OmitDemo) { 'no' } else { 'yes' } wix build (Join-Path $PSScriptRoot 'notecraft.wxs') -arch $Arch ` -ext WixToolset.UI.wixext -ext WixToolset.Util.wixext ` -d "Version=$MsiVersion" -d "BinDir=$Stage" -d "IconPath=$(Join-Path $Root 'assets\app-icon\notecraft.ico')" ` - -d "LicenseRtf=$LicenseRtf" -d "IncludeDemo=$IncludeDemo" ` + -d "LicenseRtf=$LicenseRtf" ` -o $Msi } # wix writes its debug symbols (.wixpdb) next to the MSI; keep them out of the release assets. @@ -213,7 +210,7 @@ New-Item -ItemType Directory -Force -Path $Portable | Out-Null Copy-Item (Join-Path $Stage '*.exe') $Portable Copy-Item (Join-Path $Stage 'importers') $Portable -Recurse Copy-Item (Join-Path $Stage 'licenses') $Portable -Recurse -if (-not $OmitDemo) { Copy-Item (Join-Path $Stage 'demo') $Portable -Recurse } +Copy-Item (Join-Path $Stage 'demo') $Portable -Recurse foreach ($f in 'README.md', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') { $p = Join-Path $Root $f if (Test-Path $p) { Copy-Item $p $Portable } diff --git a/xtask/src/main.rs b/xtask/src/main.rs index e95e55aa..acd5b054 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -19,6 +19,7 @@ //! check-branch [--push] the branch and history checks of quality levels L1 and L2 //! commit-msg FILE the commit message check, for the commit-msg hook //! version print the workspace version; `version set X.Y.Z[-pre]` changes it +//! demo [html|cmgfm|both] build one or both official demo formats (default: both) //! demo-copy [html|cmgfm] [--replace] copy one bundled demo format; --replace approves overwriting a changed scratch copy //! ``` @@ -47,9 +48,10 @@ const LAYERS: &[(&str, u8)] = &[ ("notecraft-engine", 4), ("notecraft-mcp", 5), ("notecraft-ui-egui", 6), + ("notecraft-setup", 6), ("notecraft", 7), + ("notecraft-web", 7), ("notecraft-cli", 7), - ("notecraft-setup", 7), ("xtask", 7), ("notecraft-demo", 7), ]; @@ -530,9 +532,19 @@ fn run(task: &str, options: &[String]) -> Result<(), String> { // The Welcome notebook (docs/demo/DemoNotebook) from its content, and the check that // the checked-in copy is current. "demo" => { - cargo(&root, &["run", "--quiet", "-p", "notecraft-demo", "--", "build"])?; + let selection = match options { + [] => "both".to_string(), + [format] if ["html", "cmgfm", "both"].contains(&format.as_str()) => format.clone(), + _ => return Err("usage: cargo xtask demo [html|cmgfm|both] (default: both)".into()), + }; + cargo(&root, &["run", "--quiet", "-p", "notecraft-demo", "--", "build", &selection])?; // The scratch copy is always replaced from docs/demo: the source is the one truth. - demo_copy(&root, &["html".into(), "--replace".into()]) + if selection == "both" { + demo_copy(&root, &["html".into(), "--replace".into()])?; + demo_copy(&root, &["cmgfm".into(), "--replace".into()]) + } else { + demo_copy(&root, &[selection, "--replace".into()]) + } } "demo-check" => cargo(&root, &["run", "--quiet", "-p", "notecraft-demo", "--", "check"]), "demo-copy" => Err("demo-copy accepts options; use `cargo xtask demo-copy [html|cmgfm] [--replace]`".into()), From 0eb95d1bf5e5951ccd8a68d88eff53a4186d3f7f Mon Sep 17 00:00:00 2001 From: AlienTech Software Date: Sat, 7 Nov 2026 13:37:22 -0800 Subject: [PATCH 2/8] docs(release): record 0.0.9 build readiness --- docs/releases/0.0.9/READINESS.md | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/docs/releases/0.0.9/READINESS.md b/docs/releases/0.0.9/READINESS.md index 8aa8b195..f0a55f0f 100644 --- a/docs/releases/0.0.9/READINESS.md +++ b/docs/releases/0.0.9/READINESS.md @@ -5,15 +5,15 @@ | Field | Value | |---|---| | Release version | 0.0.9 | -| Release source commit | `f44d977` plus uncommitted changes on `fix/web-demo-version-deploy-guard` | -| Release branch or tag candidate | `fix/web-demo-version-deploy-guard`; no tag candidate set | +| Release source commit | `171e2d5328a2cb5ce0df165ff0f6a8b896741eae` | +| Release branch or tag candidate | `release/0.0.9`; no tag candidate set | | Previous release tag | Not verified in this signoff run | | Approved release scope reference | `docs/releases/0.0.9/RELEASE_NOTES.md` | | Signoff owner | NoteCraft owner | -This is a local readiness snapshot, not release approval. The source tree is dirty, so the built -files do not yet have an immutable source commit. Any artifact rebuilt after a source change needs -new evidence and a new hash. +This is a local readiness snapshot, not release approval. The local WASM and archive were built from +the source tree immediately before it was committed as `171e2d5`; rebuild them from that exact commit +in CI to establish published artifact provenance. The working tree is clean. ## Platform signoff matrix @@ -50,7 +50,7 @@ upload and deployment requirements are satisfied for one immutable source commit | [x] | Approved version is consistent in workspace metadata and local artifacts. | PASS: version 0.0.9. Release draft consistency not rechecked in this run. | | [x] | Demo scripts and authored content are updated; HTML and CMGFM outputs are regenerated and parity-checked. | PASS: `cargo xtask demo both`, `cargo xtask demo-check`, and `cargo test -p notecraft-formats --test format_parity`. | | [x] | Both generated formats and all 13 locales are present; developer copy is refreshed. | PASS: selected-format and both-format commands completed; `my-notebooks/welcome-notebook` refreshed from each output. | -| [x] | Formatting, lint, tests, static gates, and CI pass on the local candidate tree. | PASS: `cargo xtask ci`; `python .github/web-build/test_bundle_demo.py`; `git diff --check`. Tree remains uncommitted. | +| [x] | Formatting, lint, tests, static gates, and CI pass on the local candidate tree. | PASS: `cargo xtask ci`; pre-commit L1 hooks; `python .github/web-build/test_bundle_demo.py`; `git diff --check`. Candidate is committed as `171e2d5`. | | [ ] | Coverage is run and its result is recorded. | NOT RUN. | | [ ] | Each platform has build, install, clean-install test, artifact, and provenance evidence. | BLOCKED: see platform matrix. | | [ ] | Release notes match verified scope. | NOT RUN: notes exist but have not been reconciled against merged release scope in this signoff. | @@ -60,11 +60,10 @@ upload and deployment requirements are satisfied for one immutable source commit ## Next actions -1. Finish and review the local changes, then create one immutable candidate commit after approval. -2. Rebuild platform artifacts from that exact commit; build macOS on a macOS runner and Android +1. Rebuild platform artifacts from `171e2d5328a2cb5ce0df165ff0f6a8b896741eae`; build macOS on a macOS runner and Android through its external builder. -3. Install and launch each candidate on clean targets and verify demo provisioning and data +2. Install and launch each candidate on clean targets and verify demo provisioning and data preservation. -4. Upload the exact artifacts, deploy the website from the same source commit, and verify the +3. Upload the exact artifacts, deploy the website from the same source commit, and verify the hosted demo and release draft. -5. Run coverage and complete the remaining release checklist with immutable evidence links. +4. Run coverage and complete the remaining release checklist with immutable evidence links. From 6898179d229bc4842b50a8c9f68f2ee54249f5a5 Mon Sep 17 00:00:00 2001 From: AlienTech Software Date: Sat, 7 Nov 2026 14:53:38 -0800 Subject: [PATCH 3/8] test(ui): make oversized control line test portable --- crates/ui-egui/src/control.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 399bd9e4..d8381a5d 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -288,9 +288,18 @@ mod tests { #[test] fn an_over_long_line_is_refused() { let (server, _h, _dir) = echo_server("ctl5"); - let long = format!(r#"{{"method":"x","pad":"{}"}}"#, "a".repeat(MAX_LINE)); - let replies = talk(server.port, &[long]); - assert_eq!(replies[0]["error"], "line too long"); + let mut stream = TcpStream::connect(("127.0.0.1", server.port)).expect("connect"); + stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + let mut reader = BufReader::new(stream.try_clone().expect("clone")); + + // Send exactly the byte at which the server rejects the line. Sending extra bytes + // lets the server close while the client is still writing, which races on macOS. + stream.write_all(&vec![b'a'; MAX_LINE + 1]).expect("write over-long line"); + + let mut response = String::new(); + assert_ne!(reader.read_line(&mut response).expect("read response"), 0, "server replies before closing"); + let response: Value = serde_json::from_str(&response).expect("JSON response"); + assert_eq!(response["error"], "line too long"); } #[test] From e3ece4b629f1b90654bfc27a947e35da4ebb0722 Mon Sep 17 00:00:00 2001 From: AlienTech Software Date: Sat, 7 Nov 2026 18:03:19 -0800 Subject: [PATCH 4/8] feat(demo): first-use Welcome wizard on Windows One dialog with five pages after installation or a preferences reset: welcome with the banner, logging level, page format (HTML or CMGFM, saved as the default), create the demo notebook in that format, and a thank-you page with Finish. It opens once; later versions do not show it. Installation copies no notebook content. The setup launchers no longer install or mark the wizard answered. The demo is installed only when the user chooses Yes and presses Finish, from the edition for the chosen format, at the notebook root so the notebook list finds it. Reset preferences reopens the wizard at once. Strings are in all 15 catalogs, written as UTF-8. Packaging contract, release notes and skills describe the Windows-only scope for 0.0.9. Co-Authored-By: Claude Haiku 5.5 --- SKILLS/nc-prod/SKILL.md | 13 +- SKILLS/nc-reelase-signoff/SKILL.md | 5 +- apps/notecraft-setup/src/lib.rs | 123 ++++++------ apps/notecraft-setup/src/main.rs | 81 ++------ apps/notecraft/src/main.rs | 16 +- crates/ui-egui/src/app.rs | 272 +++++++++++++++++++++++---- crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/tests/ui.rs | 119 +++++++++++- docs/releases/0.0.9/RELEASE_NOTES.md | 3 +- docs/releasing.md | 22 ++- i18n/ar-XB.tsv | 14 ++ i18n/ar.tsv | 14 ++ i18n/de.tsv | 14 ++ i18n/en-XA.tsv | 14 ++ i18n/en.tsv | 14 ++ i18n/es.tsv | 14 ++ i18n/fa.tsv | 14 ++ i18n/fr.tsv | 14 ++ i18n/he.tsv | 14 ++ i18n/hi.tsv | 14 ++ i18n/ja.tsv | 14 ++ i18n/ko.tsv | 14 ++ i18n/ru.tsv | 14 ++ i18n/ur.tsv | 14 ++ i18n/zh.tsv | 14 ++ packaging/OSX/DMG Read Me.txt | 17 +- packaging/OSX/README.md | 19 +- packaging/OSX/issues.md | 9 +- packaging/installation artifacts.md | 73 ++++--- packaging/linux/package.sh | 2 +- packaging/windows/notecraft.wxs | 7 +- 31 files changed, 753 insertions(+), 241 deletions(-) diff --git a/SKILLS/nc-prod/SKILL.md b/SKILLS/nc-prod/SKILL.md index 76617db9..5dae194c 100644 --- a/SKILLS/nc-prod/SKILL.md +++ b/SKILLS/nc-prod/SKILL.md @@ -71,10 +71,15 @@ repair must be atomic and must leave the original recoverable if interrupted. ### Installation responsibility -Application binaries and the User Assistance demo notebook are separate installation artifacts. -The installation tool deploys both; the application only discovers and opens the installed -notebook. The app must not install, copy, refresh, replace, repair, or delete it. The single -cross-platform contract is `packaging/installation artifacts.md`. +Application binaries and the User Assistance demo notebook remain separate artifacts, even when +one installer bundles both. Installation copies no notebook content. The app bundles the generated +editions as the source for a one-time first-use wizard: one dialog with five pages (welcome and +banner, logging level, page format, create the demo notebook, thank you). It opens once after +installation or a preferences reset and does not reopen for later app versions. Choosing Yes creates +or completely replaces the per-user `welcome-to-notecraft` copy in the chosen format only; No creates +nothing and leaves an existing copy alone. The app never changes sibling notebooks. For 0.0.9 the +wizard is implemented and verified on Windows only. The single cross-platform contract is +`packaging/installation artifacts.md`. --- diff --git a/SKILLS/nc-reelase-signoff/SKILL.md b/SKILLS/nc-reelase-signoff/SKILL.md index 08100ee3..5e316f10 100644 --- a/SKILLS/nc-reelase-signoff/SKILL.md +++ b/SKILLS/nc-reelase-signoff/SKILL.md @@ -35,8 +35,9 @@ requested `reelase` spelling for discoverability. screenshots, licenses, and attribution. Test installation in a clean VM, device, or browser when the release changes packaging or external bridges. Apply `packaging/installation artifacts.md` and the platform matrix below. Verify each artifact carries both generated formats and all 13 - demo locales. On first start, install the managed Welcome notebook only when its folder is - absent. Later starts preserve an existing Welcome notebook and a sentinel sibling notebook. + demo locales. The first-use wizard offers the managed Welcome notebook once, after installation or a + preferences reset; installation copies none. A sentinel sibling notebook must survive it. For + 0.0.9 the wizard is signed off on Windows only. Verify upgrade and uninstall behavior for each platform, including Android's app-specific data behavior. Record platform limits rather than treating a package build as an install test. 9. Confirm no automatic telemetry upload, local privacy wording, and release defaults. diff --git a/apps/notecraft-setup/src/lib.rs b/apps/notecraft-setup/src/lib.rs index 32d17f71..34c97430 100644 --- a/apps/notecraft-setup/src/lib.rs +++ b/apps/notecraft-setup/src/lib.rs @@ -10,15 +10,12 @@ pub fn macos_dmg_payload(executable: &Path) -> Option { payload.is_dir().then_some(payload) } -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum SetupOutcome { - Installed(PathBuf), -} - -/// Replaces only the app-managed Welcome notebook with the generated HTML and CMGFM editions. -/// Other notebooks in `notebooks_root` are never visited or changed. -pub fn refresh_demo(payload: &Path, notebooks_root: &Path) -> io::Result { - validate_payload(payload)?; +/// Installs one generated edition (`html` or `cmgfm`) of the release Welcome notebook as the +/// app-managed notebook folder. The edition's own `_node.toml` ends up directly under the +/// notebook folder, so the notebook list finds it. Other notebooks in `notebooks_root` are never +/// visited or changed. Returns the installed notebook folder. +pub fn install_edition(payload: &Path, notebooks_root: &Path, format: &str) -> io::Result { + validate_edition(payload, format)?; let destination = notebooks_root.join(NOTEBOOK_NAME); if std::fs::symlink_metadata(&destination).is_ok_and(|metadata| metadata.file_type().is_symlink()) { return Err(io::Error::new(io::ErrorKind::InvalidInput, "refusing to replace a symbolic link at the Welcome notebook path")); @@ -27,7 +24,7 @@ pub fn refresh_demo(payload: &Path, notebooks_root: &Path) -> io::Result io::Result io::Result<()> { - for (format, page) in [("html", "00-start/welcome/index.html"), ("cmgfm", "00-start/welcome/index.md")] { - for relative in [Path::new(format).join("_node.toml"), Path::new(format).join(page)] { - if !payload.join(&relative).is_file() { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - format!("the User Assistance payload is incomplete: missing {}", relative.display()), - )); - } +/// Checks that one edition is complete before anything in the notebooks folder is replaced. +fn validate_edition(payload: &Path, format: &str) -> io::Result<()> { + let page = match format { + "html" => "00-start/welcome/index.html", + "cmgfm" => "00-start/welcome/index.md", + other => { + return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("unknown page format {other:?}"))); } - let format_root = payload.join(format); - let language_count = std::fs::read_dir(&format_root)? - .filter_map(Result::ok) - .filter(|entry| { - if !entry.file_type().is_ok_and(|kind| kind.is_dir()) { - return false; - } - let name = entry.file_name(); - let Some(name) = name.to_str() else { return false }; - let Some((number, language)) = name.split_once('-') else { return false }; - matches!(number.parse::(), Ok(10..=23)) && language.len() == 2 && language.bytes().all(|byte| byte.is_ascii_lowercase()) - }) - .count(); - if language_count != 13 { + }; + let format_root = payload.join(format); + for relative in [Path::new("_node.toml").to_path_buf(), PathBuf::from(page)] { + if !format_root.join(&relative).is_file() { return Err(io::Error::new( io::ErrorKind::InvalidData, - format!("the {format} User Assistance notebook has {language_count} language folders; expected 13"), + format!("the User Assistance payload is incomplete: missing {format}/{}", relative.display()), )); } } + let language_count = std::fs::read_dir(&format_root)? + .filter_map(Result::ok) + .filter(|entry| { + if !entry.file_type().is_ok_and(|kind| kind.is_dir()) { + return false; + } + let name = entry.file_name(); + let Some(name) = name.to_str() else { return false }; + let Some((number, language)) = name.split_once('-') else { return false }; + matches!(number.parse::(), Ok(10..=23)) && language.len() == 2 && language.bytes().all(|byte| byte.is_ascii_lowercase()) + }) + .count(); + if language_count != 13 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("the {format} User Assistance notebook has {language_count} language folders; expected 13"), + )); + } Ok(()) } @@ -184,22 +187,24 @@ mod tests { } #[test] - fn official_generated_demo_is_a_valid_setup_payload() { + fn official_generated_demo_is_a_valid_payload_for_both_editions() { let payload = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/demo/DemoNotebook"); - validate_payload(&payload).expect("official generated HTML and CMGFM notebooks are a valid setup payload"); + validate_edition(&payload, "html").expect("official HTML edition is valid"); + validate_edition(&payload, "cmgfm").expect("official CMGFM edition is valid"); } #[test] - fn refreshes_both_demo_formats_and_preserves_other_notebooks() { + fn installs_only_the_chosen_edition_at_the_notebook_root() { let (_temp, source, notebooks) = fixture(); let other = notebooks.join("My notebook"); fs::create_dir_all(&other).expect("create user notebook"); fs::write(other.join("notes.txt"), "user content").expect("write user content"); - let outcome = refresh_demo(&source, ¬ebooks).expect("install payload"); - let destination = notebooks.join(NOTEBOOK_NAME); - assert_eq!(outcome, SetupOutcome::Installed(destination.clone())); - assert_eq!(fs::read(destination.join("html/00-start/welcome/index.html")).expect("HTML format"), b"HTML format"); - assert_eq!(fs::read(destination.join("cmgfm/00-start/welcome/index.md")).expect("CMGFM format"), b"CMGFM format"); + let destination = install_edition(&source, ¬ebooks, "cmgfm").expect("install CMGFM edition"); + + assert_eq!(destination, notebooks.join(NOTEBOOK_NAME)); + assert!(destination.join("_node.toml").is_file(), "the edition's notebook metadata is directly under the notebook folder"); + assert_eq!(fs::read(destination.join("00-start/welcome/index.md")).expect("CMGFM format"), b"CMGFM format"); + assert!(!destination.join("html").exists(), "the other edition is not installed"); assert_eq!(fs::read(other.join("notes.txt")).expect("user content"), b"user content"); } @@ -213,44 +218,48 @@ mod tests { fs::create_dir_all(&other).expect("create user notebook"); fs::write(other.join("notes.txt"), "keep my notes").expect("write user notes"); - let html = source.join("html/00-start/welcome/index.html"); - fs::write(html, "updated HTML").expect("update payload"); - let outcome = refresh_demo(&source, ¬ebooks).expect("replace existing demo"); - assert_eq!(outcome, SetupOutcome::Installed(destination.clone())); + fs::write(source.join("html/00-start/welcome/index.html"), "updated HTML").expect("update payload"); + assert_eq!(install_edition(&source, ¬ebooks, "html").expect("replace existing demo"), destination); assert!(!destination.join("old-page.txt").exists(), "stale demo data is removed"); - assert_eq!(fs::read(destination.join("html/00-start/welcome/index.html")).expect("new demo"), b"updated HTML"); + assert_eq!(fs::read(destination.join("00-start/welcome/index.html")).expect("new demo"), b"updated HTML"); assert_eq!(fs::read(other.join("notes.txt")).expect("user notes"), b"keep my notes"); } #[test] - fn a_missing_demo_is_recreated_on_next_launch() { + fn a_missing_demo_is_recreated_on_next_install() { let (_temp, source, notebooks) = fixture(); - let destination = notebooks.join(NOTEBOOK_NAME); - assert_eq!(refresh_demo(&source, ¬ebooks).expect("initial install"), SetupOutcome::Installed(destination.clone())); + let destination = install_edition(&source, ¬ebooks, "html").expect("initial install"); fs::remove_dir_all(&destination).expect("user deletes the notebook"); - assert_eq!(refresh_demo(&source, ¬ebooks).expect("refresh deleted demo"), SetupOutcome::Installed(destination.clone())); - assert!(destination.join("html/00-start/welcome/index.html").is_file(), "the app recreates its managed demo"); + assert_eq!(install_edition(&source, ¬ebooks, "html").expect("reinstall deleted demo"), destination); + assert!(destination.join("00-start/welcome/index.html").is_file(), "the app recreates its managed demo"); } #[test] - fn an_incomplete_payload_fails_without_replacing_the_existing_demo() { + fn an_incomplete_edition_fails_without_replacing_the_existing_demo() { let (_temp, source, notebooks) = fixture(); fs::create_dir_all(notebooks.join(NOTEBOOK_NAME)).expect("create current demo"); fs::write(notebooks.join(NOTEBOOK_NAME).join("keep.txt"), "current").expect("write current demo"); fs::remove_file(source.join("html/00-start/welcome/index.html")).expect("remove required HTML page"); - assert_eq!(refresh_demo(&source, ¬ebooks).expect_err("reject incomplete payload").kind(), io::ErrorKind::InvalidData); + assert_eq!(install_edition(&source, ¬ebooks, "html").expect_err("reject incomplete payload").kind(), io::ErrorKind::InvalidData); assert_eq!(fs::read(notebooks.join(NOTEBOOK_NAME).join("keep.txt")).expect("current demo"), b"current"); } #[test] - fn a_payload_missing_a_language_is_rejected_before_replacing_the_current_demo() { + fn an_edition_missing_a_language_is_rejected_before_replacing_the_current_demo() { let (_temp, source, notebooks) = fixture(); let destination = notebooks.join(NOTEBOOK_NAME); fs::create_dir_all(&destination).expect("create current demo"); fs::write(destination.join("keep.txt"), "current").expect("write current demo"); fs::remove_dir_all(source.join("html/23-he")).expect("remove one generated language"); - assert_eq!(refresh_demo(&source, ¬ebooks).expect_err("reject incomplete languages").kind(), io::ErrorKind::InvalidData); + assert_eq!(install_edition(&source, ¬ebooks, "html").expect_err("reject incomplete languages").kind(), io::ErrorKind::InvalidData); assert_eq!(fs::read(destination.join("keep.txt")).expect("current demo"), b"current"); } + + #[test] + fn an_unknown_format_is_rejected_before_anything_is_written() { + let (_temp, source, notebooks) = fixture(); + assert_eq!(install_edition(&source, ¬ebooks, "docx").expect_err("reject unknown format").kind(), io::ErrorKind::InvalidInput); + assert!(!notebooks.join(NOTEBOOK_NAME).exists()); + } } diff --git a/apps/notecraft-setup/src/main.rs b/apps/notecraft-setup/src/main.rs index 898ad762..67c2c41f 100644 --- a/apps/notecraft-setup/src/main.rs +++ b/apps/notecraft-setup/src/main.rs @@ -1,38 +1,14 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![cfg_attr(target_os = "windows", windows_subsystem = "windows")] -use notecraft_setup::{SetupOutcome, refresh_demo}; -use notecraft_store::{Settings, settings::default_notebooks_dir}; -use std::path::{Path, PathBuf}; -#[cfg(not(target_os = "macos"))] -use std::process::Command; - -fn locate_payload(executable: &Path) -> Option { - #[cfg(target_os = "windows")] - let candidate = executable.parent()?.join("demo").join("welcome-to-notecraft"); - - #[cfg(target_os = "linux")] - let candidate = if let Some(appdir) = std::env::var_os("APPDIR") { - PathBuf::from(appdir).join("usr/share/notecraft/demo/welcome-to-notecraft") - } else { - executable.parent()?.join("../share/notecraft/demo/welcome-to-notecraft") - }; - - #[cfg(target_os = "macos")] - let candidate = notecraft_setup::macos_dmg_payload(executable)?; - - #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))] - let candidate = executable.parent()?.join("demo").join("welcome-to-notecraft"); - - candidate.is_dir().then_some(candidate) -} +//! Launcher for the installed NoteCraft app. The Welcome notebook is no longer installed here: +//! the app's first-use wizard asks for the logging level, the page format and whether to add the +//! demo notebook, then installs the chosen edition itself. #[cfg(not(target_os = "macos"))] -fn sibling_app(executable: &Path) -> Option { - let name = if cfg!(windows) { "notecraft.exe" } else { "notecraft" }; - let path = executable.parent()?.join(name); - path.is_file().then_some(path) -} +use std::path::Path; +#[cfg(not(target_os = "macos"))] +use std::process::Command; fn main() { let executable = match std::env::current_exe() { @@ -42,7 +18,8 @@ fn main() { #[cfg(target_os = "macos")] { - install_from_dmg(&executable); + let _ = executable; + show_notice("NoteCraft is ready to use. The Welcome notebook is offered the first time you open NoteCraft."); } #[cfg(not(target_os = "macos"))] @@ -51,53 +28,27 @@ fn main() { } } +#[cfg(not(target_os = "macos"))] +fn sibling_app(executable: &Path) -> Option { + let name = if cfg!(windows) { "notecraft.exe" } else { "notecraft" }; + let path = executable.parent()?.join(name); + path.is_file().then_some(path) +} + #[cfg(not(target_os = "macos"))] fn launch_desktop_app(executable: &Path) { let app = match sibling_app(executable) { Some(path) => path, None => fail("The NoteCraft app is missing beside its setup tool. Reinstall NoteCraft and try again."), }; - let settings = Settings::default_location(); - let payload = locate_payload(executable); - let payload = payload.as_deref().unwrap_or_else(|| fail("The generated Welcome notebook is missing from this installation.")); - let notebooks = notecraft_store::settings::configured_notebooks_dir(&settings).unwrap_or_else(default_notebooks_dir); - let outcome = match refresh_demo(payload, ¬ebooks) { - Ok(outcome) => outcome, - Err(error) => fail(&format!("The User Assistance notebook could not be installed: {error}")), - }; - let mut command = Command::new(app); - let args: Vec = std::env::args().skip(1).collect(); - if args.is_empty() { - let SetupOutcome::Installed(path) = outcome; - command.arg("--open").arg(path); - } else { - command.args(args); - } - + command.args(std::env::args().skip(1)); match command.status() { Ok(status) => std::process::exit(status.code().unwrap_or(1)), Err(error) => fail(&format!("NoteCraft could not be opened: {error}")), } } -#[cfg(target_os = "macos")] -fn install_from_dmg(executable: &Path) { - let settings = Settings::default_location(); - let notebooks = notecraft_store::settings::configured_notebooks_dir(&settings).unwrap_or_else(default_notebooks_dir); - let payload = locate_payload(executable); - let Some(payload) = payload else { - show_notice("The Welcome notebook is not included in this NoteCraft disk image. NoteCraft is ready to use."); - return; - }; - match refresh_demo(&payload, ¬ebooks) { - Ok(SetupOutcome::Installed(path)) => { - show_notice(&format!("The Welcome notebook was refreshed in {}. You can now open NoteCraft from Applications.", path.display())) - } - Err(error) => fail(&format!("The Welcome notebook could not be installed: {error}")), - } -} - #[cfg(target_os = "macos")] fn show_notice(message: &str) { let _ = rfd::MessageDialog::new().set_level(rfd::MessageLevel::Info).set_title("NoteCraft Setup").set_description(message).show(); diff --git a/apps/notecraft/src/main.rs b/apps/notecraft/src/main.rs index c3c2d2c2..c39e2912 100644 --- a/apps/notecraft/src/main.rs +++ b/apps/notecraft/src/main.rs @@ -166,10 +166,6 @@ fn main() -> eframe::Result { Err(error) => fail(&format!("Could not locate the generated Welcome notebook payload: {error}")), }; let payload = demo_payload(&executable).unwrap_or_else(|| fail("Could not locate the generated Welcome notebook payload.")); - if let Err(error) = notecraft_setup::refresh_demo(&payload, &root) { - applog::line("ERROR", &format!("cannot refresh the managed Welcome notebook: {error}")); - fail(&format!("NoteCraft could not create or refresh the Welcome notebook: {error}")); - } let session = match Session::new(&root, Settings::default_location()) { Ok(s) => s, Err(e) => { @@ -184,12 +180,11 @@ fn main() -> eframe::Result { let remembered = std::fs::canonicalize(&root).unwrap_or_else(|_| root.clone()); let _ = session.settings.set("last_notebooks_root", &remembered.to_string_lossy()); } - // Reset first-use flag for testing (shows logging consent dialog again) + // Reset first-use flags so both current first-run prompts can be reviewed again. if args.iter().any(|arg| arg == "--first-use") { let _ = session.settings.set("privacy_welcome_seen", ""); - applog::info("First-use flag set: privacy welcome dialog will show"); + applog::info("First-use flag set: the first-use wizard will show"); } - // The app refreshes its own Welcome notebook before discovery; every other notebook remains user-owned. let mut startup_alerts: Vec<(&str, String)> = Vec::new(); // NoteCraft draws its own title bar unless the settings say the system's is wanted. @@ -228,7 +223,12 @@ fn main() -> eframe::Result { "NoteCraft", options, Box::new(move |cc| { - let mut app = NoteCraftApp::new(session).with_clipboard(clipboard); + let setup_payload = payload.clone(); + let mut app = NoteCraftApp::new(session) + .with_welcome_notebook_setup(move |notebooks_root, format| { + notecraft_setup::install_edition(&setup_payload, notebooks_root, format).map_err(|error| error.to_string()) + }) + .with_clipboard(clipboard); for (key, message) in startup_alerts.drain(..) { app.alert(key, "NoteCraft", &message); } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 0f0d4bae..15f6e586 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -452,10 +452,17 @@ enum Dialog { title: String, }, Symbols, - PrivacyWelcome { + /// The first-use wizard: one window with three steps. Step 0 is the local logging level, + /// step 1 the page format saved as the default, and step 2 whether to add the Welcome notebook + /// in that format. + FirstUseWizard { + step: u8, level: String, + format: PageFormat, + add_demo: bool, + error: Option, }, - /// A problem told to the user in a box. Ticking "do not alert me again" stops the box for + /// A problem told to the user in a box. /// A problem told to the user in a box. Ticking "do not alert me again" stops the box for /// this `key` for the rest of the session; the status line still says what happened. Alert { key: String, @@ -632,6 +639,7 @@ pub struct NoteCraftApp { /// The clipboard the app reads and writes. The system's, unless the app was built with another. clipboard: Box, open_attachment_warning_suppressed: bool, + welcome_notebook_setup: Option Result>>, } impl NoteCraftApp { @@ -673,6 +681,7 @@ impl NoteCraftApp { let privacy_welcome = session.settings.get("privacy_welcome_seen").is_none_or(|v| v.trim().is_empty()); let telemetry_level = session.settings.get("telemetry_level").unwrap_or_else(|| default_telemetry_level(cfg!(debug_assertions)).to_string()); log::info!("privacy welcome modal state: show={} telemetry_level={:?}", privacy_welcome, telemetry_level); + let wizard_format = session.settings.global_format().0; NoteCraftApp { session, nav: NavHistory::default(), @@ -686,7 +695,11 @@ impl NoteCraftApp { window_level_pending: false, frameless: false, editor: None, - dialog: if privacy_welcome { Some(Dialog::PrivacyWelcome { level: telemetry_level }) } else { None }, + dialog: if privacy_welcome { + Some(Dialog::FirstUseWizard { step: 0, level: telemetry_level, format: wizard_format, add_demo: true, error: None }) + } else { + None + }, import_job: None, status: crate::tl_id!("ui.ready_2").into(), status_is_error: false, @@ -737,9 +750,58 @@ impl NoteCraftApp { queued_alerts: VecDeque::new(), clipboard: Box::new(crate::clipboard::System), open_attachment_warning_suppressed: false, + welcome_notebook_setup: None, + } + } + + /// Installs the application-owned action behind the Welcome notebook step of the first-use + /// wizard. The callback gets the notebooks folder and the chosen format id, and returns the + /// installed notebook folder. The wizard opens once: on the first launch after installation, or + /// after the preferences are reset. It does not reopen for later versions. + pub fn with_welcome_notebook_setup(mut self, setup: impl FnMut(&Path, &str) -> Result + 'static) -> Self { + self.welcome_notebook_setup = Some(Box::new(setup)); + self + } + + /// The first-use wizard, starting at the logging step with the current settings. + fn first_use_wizard(&self) -> Dialog { + Dialog::FirstUseWizard { + step: 0, + level: self.session.settings.get("telemetry_level").unwrap_or_else(|| default_telemetry_level(cfg!(debug_assertions)).to_string()), + format: self.session.settings.global_format().0, + add_demo: true, + error: None, } } + /// Applies the wizard's answers: the logging level, the default page format, and, when chosen, + /// the Welcome notebook in that format. The wizard is marked seen only after every answer is saved, + /// so a failed install shows the wizard again on the next launch. + fn finish_first_use_wizard(&mut self, level: &str, format: PageFormat, add_demo: bool) -> Result<(), String> { + self.session.settings.set("telemetry_level", level).map_err(|error| error.to_string())?; + self.session.settings.set("privacy_welcome_seen", "true").map_err(|error| error.to_string())?; + self.session.settings.set_default_format(format).map_err(|error| error.to_string())?; + if add_demo { + self.save_now(); + if self.is_dirty() { + return Err("the current page could not be saved before replacing the Welcome notebook".to_string()); + } + let installed = { + let setup = self.welcome_notebook_setup.as_mut().ok_or_else(|| "the bundled Welcome notebook setup is unavailable".to_string())?; + setup(self.session.root(), format.id())? + }; + self.editor = None; + self.pad = None; + self.session.refresh(); + self.status_is_error = false; + self.open_path(&installed.join("00-start/welcome").to_string_lossy()); + if self.status_is_error { + return Err(self.status.clone()); + } + } + Ok(()) + } + pub fn session(&self) -> &Session { &self.session } @@ -4951,18 +5013,36 @@ impl NoteCraftApp { keep = false; } } - Dialog::PrivacyWelcome { level } => { - let mut accepted = false; - let mut denied = false; + Dialog::FirstUseWizard { step, level, format, add_demo, error } => { + let mut back = false; + let mut next = false; + let mut finish = false; + let last_step: u8 = 4; + let escape = ctx.input_mut(|input| input.consume_key(Modifiers::NONE, Key::Escape)); let screen = ctx.viewport_rect(); - egui::Area::new(egui::Id::new("privacy-welcome-modal-backdrop")).order(egui::Order::Foreground).fixed_pos(screen.min).show( + egui::Area::new(egui::Id::new("first-use-wizard-modal-backdrop")).order(egui::Order::Foreground).fixed_pos(screen.min).show( ctx, |ui| { let response = ui.allocate_rect(egui::Rect::from_min_size(egui::Pos2::ZERO, screen.size()), egui::Sense::click()); ui.painter().rect_filled(response.rect, 0.0, egui::Color32::from_black_alpha(150)); }, ); - egui::Window::new(crate::tl_id!("ui.welcome_to_notecraft")) + let panel = self.tokens.panel; + let dark = (u32::from(panel.r()) + u32::from(panel.g()) + u32::from(panel.b())) < 384; + let (banner_uri, banner_bytes) = if dark { + ("bytes://notecraft-wizard-banner-dark", crate::BANNER_DARK_PNG) + } else { + ("bytes://notecraft-wizard-banner-light", crate::BANNER_LIGHT_PNG) + }; + let title = match *step { + 0 => crate::tl_id!("ui.welcome_to_notecraft"), + 1 => crate::tl_id!("ui.local_collection_level"), + 2 => crate::tl_id!("ui.welcome_format_title"), + 3 => crate::tl_id!("ui.welcome_notebook_prompt_title"), + _ => crate::tl_id!("ui.welcome_wizard_done_title"), + } + .to_string(); + egui::Window::new(title.as_str()) .title_bar(false) .collapsible(false) .resizable(false) @@ -4970,39 +5050,86 @@ impl NoteCraftApp { .anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0)) .frame(modal_frame(&self.tokens)) .show(ctx, |ui| { - modal_title(ui, &self.tokens, crate::tl_id!("ui.welcome_to_notecraft")); ui.set_min_width(520.0); - ui.label(crate::tl_id!("ui.thank_you_for_trying_notecraft")); - ui.add_space(6.0); - ui.label(crate::tl_id!("ui.privacy_is_our_top_priority_all_logs_and_telemetry_s_d87cae4eac")); - ui.add_space(6.0); - ui.label(crate::tl_id!("ui.choose_a_local_collection_level_logging_is_off_by_de_5dfbe386e0")); - egui::ComboBox::from_label(crate::tl_id!("ui.local_collection_level")).selected_text(crate::tl!(level.as_str())).show_ui( - ui, - |ui| { - for choice in ["none", "usage", "warning", "error", "debug"] { - ui.selectable_value(level, choice.into(), crate::tl!(choice)); + if *step == 0 { + ui.add(egui::Image::from_bytes(banner_uri, banner_bytes).fit_to_exact_size(vec2(480.0, 240.0))); + ui.add_space(8.0); + } + modal_title(ui, &self.tokens, title.as_str()); + match *step { + 0 => { + ui.label(crate::tl_id!("ui.thank_you_for_trying_notecraft")); + } + 1 => { + ui.label(crate::tl_id!("ui.privacy_is_our_top_priority_all_logs_and_telemetry_s_d87cae4eac")); + ui.add_space(6.0); + ui.label(crate::tl_id!("ui.choose_a_local_collection_level_logging_is_off_by_de_5dfbe386e0")); + egui::ComboBox::from_label(crate::tl_id!("ui.local_collection_level")) + .selected_text(crate::tl!(level.as_str())) + .show_ui(ui, |ui| { + for choice in ["none", "usage", "warning", "error", "debug"] { + ui.selectable_value(level, choice.into(), crate::tl!(choice)); + } + }); + } + 2 => { + ui.label(crate::tl_id!("ui.welcome_format_body")); + ui.add_space(8.0); + for choice in PageFormat::ALL { + ui.radio_value(&mut *format, choice, choice.label()); } - }, - ); - ui.add_space(12.0); - ui.horizontal(|ui| { - if modal_button(ui, &self.tokens, crate::tl_id!("ui.accept"), true).clicked() { - accepted = true; } - if modal_button(ui, &self.tokens, crate::tl_id!("ui.deny"), false).clicked() { - denied = true; + 3 => { + ui.label(crate::tl_id!("ui.welcome_notebook_prompt_body")); + ui.label(crate::i18n::format_message_id("ui.welcome_notebook_prompt_format", &[("format", format.label())])); + ui.add_space(6.0); + ui.colored_label(self.tokens.warn, crate::tl_id!("ui.welcome_notebook_replace_warning")); + ui.add_space(8.0); + ui.radio_value(&mut *add_demo, true, crate::tl_id!("ui.welcome_notebook_add_yes")); + ui.radio_value(&mut *add_demo, false, crate::tl_id!("ui.welcome_notebook_add_no")); + } + _ => { + ui.label(crate::tl_id!("ui.welcome_wizard_done_body")); + } + } + if let Some(message) = error { + ui.add_space(8.0); + ui.colored_label( + self.tokens.warn, + crate::i18n::format_message_id("ui.welcome_notebook_action_failed", &[("error", message)]), + ); + } + ui.add_space(14.0); + ui.horizontal(|ui| { + if *step > 0 && modal_button(ui, &self.tokens, crate::tl_id!("ui.welcome_wizard_back"), false).clicked() { + back = true; } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if *step < last_step { + if modal_button(ui, &self.tokens, crate::tl_id!("ui.welcome_format_next"), true).clicked() { + next = true; + } + } else if modal_button(ui, &self.tokens, crate::tl_id!("ui.welcome_wizard_finish"), true).clicked() { + finish = true; + } + }); }); }); - if accepted { - let _ = self.session.settings.set("telemetry_level", level); - let _ = self.session.settings.set("privacy_welcome_seen", "true"); - keep = false; - } else if denied { - let _ = self.session.settings.set("telemetry_level", "none"); - let _ = self.session.settings.set("privacy_welcome_seen", "true"); - keep = false; + if back { + *step = step.saturating_sub(1); + } + if next { + *step = (*step + 1).min(last_step); + } + if escape && !finish && *step > 0 { + *step -= 1; + } + if finish { + let level = level.clone(); + match self.finish_first_use_wizard(&level, *format, *add_demo) { + Ok(()) => keep = false, + Err(message) => *error = Some(message), + } } } Dialog::Alert { key, title, message, suppress, suppress_forever } => { @@ -5064,7 +5191,7 @@ impl NoteCraftApp { }); if reset { match self.session.settings.reset() { - Ok(()) => self.say(crate::tl_id!("ui.app_preferences_reset_restart_notecraft_to_apply_every_default")), + Ok(()) => self.dialog = Some(self.first_use_wizard()), Err(e) => { self.complain(&crate::i18n::format_message_id("ui.could_not_reset_app_preferences_error", &[("error", &e.to_string())])) } @@ -6514,7 +6641,7 @@ mod alert_tests { let app = NoteCraftApp::new(session); // Dialog should be shown because privacy_welcome_seen is not in settings - assert!(matches!(app.dialog, Some(Dialog::PrivacyWelcome { .. })), "PrivacyWelcome dialog should show on first launch"); + assert!(matches!(app.dialog, Some(Dialog::FirstUseWizard { .. })), "PrivacyWelcome dialog should show on first launch"); } #[test] @@ -6529,6 +6656,73 @@ mod alert_tests { assert!(app.dialog.is_none(), "PrivacyWelcome dialog should not show after being dismissed"); } + #[test] + fn the_wizard_opens_once_after_install_and_not_for_later_versions() { + let t = notecraft_store::testing::TempDir::new("welcome-wizard-once"); + let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); + settings.set("privacy_welcome_seen", "true").expect("settings"); + let upgraded = Session::new(&t.path().join("notebooks"), settings.clone()).expect("upgraded session"); + let upgraded = NoteCraftApp::new(upgraded).with_welcome_notebook_setup(|root, _format| Ok(root.join("welcome-to-notecraft"))); + assert!(upgraded.dialog.is_none(), "an existing user is not shown the wizard again for a later version"); + + // A fresh install opens the wizard at the welcome page; finishing it saves every answer. + let fresh = notecraft_store::Settings::at(t.path().join("fresh.toml")); + let session = Session::new(&t.path().join("fresh-notebooks"), fresh.clone()).expect("fresh session"); + let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|root, _format| Ok(root.join("welcome-to-notecraft"))); + assert!(matches!(app.dialog, Some(Dialog::FirstUseWizard { step: 0, .. })), "a fresh install starts at the welcome page"); + assert!(app.finish_first_use_wizard("none", PageFormat::Html, false).is_ok()); + assert_eq!(fresh.get("privacy_welcome_seen").as_deref(), Some("true")); + + let again = Session::new(&t.path().join("fresh-notebooks"), fresh).expect("reopened session"); + let again = NoteCraftApp::new(again).with_welcome_notebook_setup(|root, _format| Ok(root.join("welcome-to-notecraft"))); + assert!(again.dialog.is_none(), "a finished wizard does not open again"); + } + + #[test] + fn welcome_notebook_prompt_waits_until_the_privacy_dialog_closes() { + let t = notecraft_store::testing::TempDir::new("welcome-prompt-after-privacy"); + let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); + let session = Session::new(&t.path().join("notebooks"), settings).expect("session"); + let app = NoteCraftApp::new(session).with_welcome_notebook_setup(|root, _format| Ok(root.join("welcome-to-notecraft"))); + + assert!(matches!(app.dialog, Some(Dialog::FirstUseWizard { step: 0, .. })), "the wizard opens at the logging step"); + assert!(app.queued_alerts.is_empty(), "the wizard is one window, so nothing waits behind it"); + } + + #[test] + fn failed_welcome_notebook_generation_keeps_the_prompt_and_does_not_record_a_choice() { + let t = notecraft_store::testing::TempDir::new("welcome-prompt-failure"); + let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); + settings.set("privacy_welcome_seen", "true").expect("settings"); + let session = Session::new(&t.path().join("notebooks"), settings.clone()).expect("session"); + let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|_, _| Err("copy failed".to_string())); + + assert!(app.finish_first_use_wizard("none", PageFormat::Cmgfm, true).is_err()); + + assert_eq!(settings.get("welcome_notebook_choice_version"), None, "a failed generation leaves the choice unanswered"); + } + + #[test] + fn the_wizard_installs_the_edition_for_the_chosen_format() { + let t = notecraft_store::testing::TempDir::new("welcome-wizard-format"); + let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); + settings.set("privacy_welcome_seen", "true").expect("settings"); + let session = Session::new(&t.path().join("notebooks"), settings.clone()).expect("session"); + let installed_format = std::rc::Rc::new(std::cell::RefCell::new(String::new())); + let recorder = installed_format.clone(); + let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(move |root, format| { + *recorder.borrow_mut() = format.to_string(); + let installed = root.join("welcome-to-notecraft"); + std::fs::create_dir_all(installed.join("00-start/welcome")).map_err(|error| error.to_string())?; + Ok(installed) + }); + + // Opening the fake folder's page can fail; the full install and open path is covered by the UI test. + let _ = app.finish_first_use_wizard("none", PageFormat::Cmgfm, true); + + assert_eq!(installed_format.borrow().as_str(), "cmgfm", "the chosen format reaches the install"); + } + /// `--first-use` writes `privacy_welcome_seen = ""` and keeps every other setting. #[test] fn first_use_flag_value_shows_the_privacy_welcome_again() { @@ -6538,7 +6732,7 @@ mod alert_tests { settings.set("theme_mode", "dark").expect("settings"); let session = Session::new(&t.path().join("notebooks"), settings).expect("session"); let app = NoteCraftApp::new(session); - assert!(matches!(app.dialog, Some(Dialog::PrivacyWelcome { .. })), "an emptied key counts as not seen"); + assert!(matches!(app.dialog, Some(Dialog::FirstUseWizard { .. })), "an emptied key counts as not seen"); assert_eq!(app.session.settings.get("theme_mode").as_deref(), Some("dark"), "other settings are kept"); } @@ -6565,7 +6759,7 @@ mod alert_tests { let app2 = NoteCraftApp::new(session2); // Dialog should reappear because settings file is gone - assert!(matches!(app2.dialog, Some(Dialog::PrivacyWelcome { .. })), "PrivacyWelcome dialog should reappear when settings file is deleted"); + assert!(matches!(app2.dialog, Some(Dialog::FirstUseWizard { .. })), "PrivacyWelcome dialog should reappear when settings file is deleted"); } #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 698173a0..fe374084 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -66,3 +66,6 @@ macro_rules! tl_id { /// The app icon (256 x 256, transparent corners). See ATTRIBUTION.md. pub const LOGO_PNG: &[u8] = include_bytes!("../../../assets/brand/notecraft-256.png"); +/// The brand banner for the first-use wizard, light and dark variants. +pub const BANNER_LIGHT_PNG: &[u8] = include_bytes!("../../../assets/brand/notecraft-social-light.png"); +pub const BANNER_DARK_PNG: &[u8] = include_bytes!("../../../assets/brand/notecraft-social-dark.png"); diff --git a/crates/ui-egui/tests/ui.rs b/crates/ui-egui/tests/ui.rs index a0a34f97..31bbc1f1 100644 --- a/crates/ui-egui/tests/ui.rs +++ b/crates/ui-egui/tests/ui.rs @@ -1507,6 +1507,106 @@ fn copy_tree(source: &std::path::Path, destination: &std::path::Path) { } } +#[test] +fn welcome_notebook_prompt_can_replace_and_open_the_release_copy() { + let t = TempDir::new("ui-welcome-prompt-yes"); + let s = session(&t); + s.settings.set("ui_language", "en").expect("English UI setting"); + s.settings.set("privacy_welcome_seen", "").expect("first use: the wizard opens"); + let source = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../docs/demo/DemoNotebook"); + let notebooks = t.path().join("notebooks"); + let destination = notebooks.join("welcome-to-notecraft"); + std::fs::create_dir_all(&destination).expect("old Welcome notebook"); + std::fs::write(destination.join("old-user-edit.txt"), "replace this managed copy").expect("old Welcome edit"); + let app = NoteCraftApp::new(s).with_welcome_notebook_setup(move |root, format| { + let destination = root.join("welcome-to-notecraft"); + if destination.exists() { + std::fs::remove_dir_all(&destination).map_err(|error| error.to_string())?; + } + copy_tree(&source.join(format), &destination); + Ok(destination) + }); + let mut h = harness(app, LIGHT); + // Welcome, logging, format, demo, thank you. + h.get_by_label("Next").click(); + settle(&mut h); + h.get_by_label("Next").click(); + settle(&mut h); + h.get_by_label("CommonMark + GFM").click(); + h.get_by_label("Next").click(); + settle(&mut h); + h.get_by_label("Yes, add it").click(); + h.get_by_label("Next").click(); + settle(&mut h); + h.get_by_label("Finish").click(); + settle(&mut h); + + assert!(!destination.join("old-user-edit.txt").exists(), "Yes replaces the old managed notebook completely"); + assert!(destination.join("_node.toml").is_file(), "the chosen edition is the notebook itself, so the notebook list finds it"); + assert!(destination.join("00-start/welcome/index.md").is_file(), "the chosen CMGFM release content is installed"); + assert!(!destination.join("html").exists(), "the other edition is not installed"); + assert_eq!(h.state().session().settings.default_format(), Some(notecraft_model::PageFormat::Cmgfm), "the format step saves the default"); + assert_eq!( + h.state().title(), + Some(format!("Welcome to NoteCraft (Ver {})", env!("CARGO_PKG_VERSION")).as_str()), + "the generated Welcome page is opened" + ); + assert_eq!(h.state().session().settings.get("privacy_welcome_seen").as_deref(), Some("true"), "finishing the wizard marks it seen"); +} + +#[test] +fn declining_the_welcome_notebook_prompt_does_not_create_it() { + let t = TempDir::new("ui-welcome-prompt-no"); + let s = session(&t); + s.settings.set("ui_language", "en").expect("English UI setting"); + s.settings.set("privacy_welcome_seen", "").expect("first use: the wizard opens"); + let app = NoteCraftApp::new(s).with_welcome_notebook_setup(|root, _format| { + let destination = root.join("welcome-to-notecraft"); + std::fs::create_dir_all(&destination).map_err(|error| error.to_string())?; + Ok(destination) + }); + let mut h = harness(app, LIGHT); + h.get_by_label("Next").click(); + settle(&mut h); + h.get_by_label("Next").click(); + settle(&mut h); + h.get_by_label("Next").click(); + settle(&mut h); + h.get_by_label("No, not now").click(); + h.get_by_label("Next").click(); + settle(&mut h); + h.get_by_label("Finish").click(); + settle(&mut h); + + assert!(!t.path().join("notebooks/welcome-to-notecraft").exists(), "No leaves the notebooks folder unchanged"); + assert_eq!(h.state().session().settings.get("privacy_welcome_seen").as_deref(), Some("true"), "finishing the wizard marks it seen"); +} + +#[test] +fn failed_welcome_notebook_generation_keeps_the_prompt_open() { + let t = TempDir::new("ui-welcome-prompt-error"); + let s = session(&t); + s.settings.set("ui_language", "en").expect("English UI setting"); + s.settings.set("privacy_welcome_seen", "").expect("first use: the wizard opens"); + let app = NoteCraftApp::new(s).with_welcome_notebook_setup(|_, _| Err("permission denied".to_string())); + let mut h = harness(app, LIGHT); + h.get_by_label("Next").click(); + settle(&mut h); + h.get_by_label("Next").click(); + settle(&mut h); + h.get_by_label("Next").click(); + settle(&mut h); + h.get_by_label("Yes, add it").click(); + h.get_by_label("Next").click(); + settle(&mut h); + h.get_by_label("Finish").click(); + settle(&mut h); + + let _ = h.get_by_label("Could not update the Welcome notebook: permission denied"); + assert_eq!(h.state().session().settings.get("welcome_notebook_choice_version"), None, "a failed copy is not remembered"); + assert!(!t.path().join("notebooks/welcome-to-notecraft").exists(), "a failed copy creates no partial notebook"); +} + #[test] fn an_empty_notebooks_folder_stays_empty_when_the_app_opens() { let t = TempDir::new("ui-empty-notebooks"); @@ -3659,26 +3759,35 @@ fn the_default_page_layout_recovers_after_an_initial_narrow_viewport() { assert!(wide > narrow + 200.0, "an unarranged page expands with the viewport: narrow={narrow}, wide={wide}"); } -/// Denying local collection is saved in the real settings file and suppresses the welcome dialog next launch. +/// Finishing the first-use wizard is saved in the real settings file and does not reopen on restart. #[test] -fn privacy_choice_survives_restarting_the_app() { +fn first_use_wizard_choices_survive_restarting_the_app() { let t = TempDir::new("ui-privacy-choice-restart"); let settings_path = t.path().join("settings.toml"); let s = Session::new(&t.path().join("notebooks"), Settings::at(&settings_path)).expect("session"); let mut h = sized_harness(NoteCraftApp::new(s), LIGHT, egui::vec2(900.0, 700.0)); settle(&mut h); - h.get_by_label("Deny").click(); + h.get_by_label("Next").click(); + settle(&mut h); + h.get_by_label("Next").click(); + settle(&mut h); + h.get_by_label("Next").click(); + settle(&mut h); + h.get_by_label("No, not now").click(); + h.get_by_label("Next").click(); + settle(&mut h); + h.get_by_label("Finish").click(); settle(&mut h); let settings = Settings::at(&settings_path); assert_eq!(settings.get("privacy_welcome_seen").as_deref(), Some("true")); - assert_eq!(settings.get("telemetry_level").as_deref(), Some("none")); + assert!(settings.get("telemetry_level").is_some(), "the logging step saves its level"); let s = Session::new(&t.path().join("notebooks"), settings).expect("reopened session"); let mut h = sized_harness(NoteCraftApp::new(s), LIGHT, egui::vec2(900.0, 700.0)); settle(&mut h); - assert_eq!(h.query_all_by_label("Deny").count(), 0, "a saved choice closes the welcome dialog on restart"); + assert_eq!(h.query_all_by_label("Finish").count(), 0, "a finished wizard does not open again on restart"); } /// A tab with many groups in a narrow window: the Draw tab has eleven, as OneNote's does, diff --git a/docs/releases/0.0.9/RELEASE_NOTES.md b/docs/releases/0.0.9/RELEASE_NOTES.md index 6f1af044..672f010c 100644 --- a/docs/releases/0.0.9/RELEASE_NOTES.md +++ b/docs/releases/0.0.9/RELEASE_NOTES.md @@ -6,7 +6,7 @@ - **Infinite canvas:** Draw in open page space beyond text blocks. - **Languages:** Interface localization across 13 locales, with French and Spanish User Assistance. - **Page organization:** UI improvements for creating pages and promoting them to sub-pages. -- **Installation:** The app refreshes the bundled HTML and CMGFM Welcome notebook in 13 languages at launch. Other notebooks are left unchanged. +- **First-use setup (Windows):** After installation, or after a preferences reset, NoteCraft opens one setup dialog: a welcome page with the banner, the local logging level, your page format (HTML or CommonMark + GFM), whether to add the Welcome notebook in that format (13 languages), and a thank-you page. It does not appear again for later app versions. Other notebooks are never replaced, and installation copies no notebook content. macOS, Linux, the website and Android are deferred for this flow in 0.0.9. - **Importing:** Import test dataset and preserve section colours. ## About NoteCraft @@ -51,3 +51,4 @@ to learn how to contribute. - [Playground](https://playground.daijro.dev/head/notecraft/) - [GitHub repository](https://github.com/AlienTechSoftware/notecraft) - [Discord](https://discord.com/channels/1359579021108842617/1559147620084088982) + diff --git a/docs/releasing.md b/docs/releasing.md index a6bf0e9a..e63de9b5 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -57,9 +57,10 @@ name or mark. clean target. Publish the draft only after the owner approves. The website, desktop release, and Android package are separate pipelines. Each bundles both -generated Welcome formats and provisions the managed Welcome notebook at app startup; the website -uses a static archive transport. The generic engine sample stays separate. Record and verify the -source revision and version for every artifact. +generated Welcome formats. Desktop NoteCraft runs the first-use wizard once after installation or +a preferences reset and creates the managed Welcome notebook only when the user chooses Yes. For +0.0.9 the wizard is verified on Windows only; the website and Android flows are deferred for it. The website uses a static archive transport. The generic engine sample stays +separate. Record and verify the source revision and version for every artifact. ### Notes and the draft @@ -78,10 +79,11 @@ source revision and version for every artifact. Before publishing, install the MSI on a machine that has never run NoteCraft. Follow the `packaging/installation artifacts.md` contract for the expected user notebook location. Launch -NoteCraft and verify it creates or refreshes `welcome-to-notecraft` with both formats and all 13 -languages before loading the notebook tree. Place a sentinel user notebook beside it and verify it -is unchanged. Confirm an older Welcome notebook is replaced on restart; its edits are expected to -be replaced by the generated release content. +NoteCraft and verify the first-use wizard appears: welcome page with the banner, logging, page format, +create the demo, then thank you. Choose Yes on the demo page and verify it creates +`welcome-to-notecraft` in the chosen format before opening it. Place a sentinel user notebook beside +it and verify it is unchanged. Restart and confirm the wizard does not appear again. Reset the +preferences and confirm it appears again. Confirm an upgrade does not show it. | File | What it is | |---|---| @@ -111,9 +113,9 @@ the `release` environment of the repository, never in a file. - The MSI `UpgradeCode` in `packaging/windows/notecraft.wxs` is fixed once the first MSI is public. Changing it later stops new versions from replacing old ones. - The exes carry the app icon and version information (build.rs, winresource), and the packaging script checks both. -- Smoke test the artifact: it starts with no console window, refreshes the managed Welcome notebook, - leaves sibling notebooks unchanged, and reports an invalid notebooks folder. Install, upgrade and - uninstall must preserve other user notebook data. Use the canonical +- Smoke test the artifact: it starts with no console window, asks before refreshing the managed + Welcome notebook, leaves sibling notebooks unchanged, and reports an invalid notebooks folder. + Install, upgrade and uninstall must preserve other user notebook data. Use the canonical `packaging/installation artifacts.md` contract for the full checks. ## Building locally diff --git a/i18n/ar-XB.tsv b/i18n/ar-XB.tsv index 76e653e6..93e43e5a 100644 --- a/i18n/ar-XB.tsv +++ b/i18n/ar-XB.tsv @@ -771,3 +771,17 @@ @id ui.zoom_in [[RLI]]$$$Zoom In@@@[[PDI]] @id ui.zoom_out [[RLI]]$$$Zoom Out@@@[[PDI]] @id ui.zoom_to_100 [[RLI]]$$$Zoom to 100%@@@[[PDI]] +@id ui.welcome_format_title [[RLI]]$$$Choose a page format@@@[[PDI]] +@id ui.welcome_format_body [[RLI]]$$$NoteCraft saves each page as HTML (recommended) or as CommonMark + GFM Markdown. New pages use the format you choose here. You can change it later.@@@[[PDI]] +@id ui.welcome_format_next [[RLI]]$$$Next@@@[[PDI]] +@id ui.welcome_notebook_prompt_format [[RLI]]$$$Format: {format}.@@@[[PDI]] +@id ui.welcome_notebook_prompt_title [[RLI]]$$$Add the Welcome notebook?@@@[[PDI]] +@id ui.welcome_notebook_prompt_body [[RLI]]$$$Add this release's Welcome notebook to your notebooks. If one already exists, it will be deleted and replaced with the new copy.@@@[[PDI]] +@id ui.welcome_notebook_replace_warning [[RLI]]$$$Changes made to the existing Welcome notebook will be lost. Other notebooks will not change.@@@[[PDI]] +@id ui.welcome_notebook_add_yes [[RLI]]$$$Yes, add it@@@[[PDI]] +@id ui.welcome_notebook_add_no [[RLI]]$$$No, not now@@@[[PDI]] +@id ui.welcome_notebook_action_failed [[RLI]]$$$Could not update the Welcome notebook: {error}@@@[[PDI]] +@id ui.welcome_wizard_back [[RLI]]$$$Back@@@[[PDI]] +@id ui.welcome_wizard_finish [[RLI]]$$$Finish@@@[[PDI]] +@id ui.welcome_wizard_done_title [[RLI]]$$$Thank you@@@[[PDI]] +@id ui.welcome_wizard_done_body [[RLI]]$$$NoteCraft is ready to use. Your choices are saved. This setup appears again only after you reset the preferences.@@@[[PDI]] diff --git a/i18n/ar.tsv b/i18n/ar.tsv index 1c6a3ab7..55e21040 100644 --- a/i18n/ar.tsv +++ b/i18n/ar.tsv @@ -771,3 +771,17 @@ @id ui.zoom_in تكبير @id ui.zoom_out تصغير @id ui.zoom_to_100 تكبير إلى 100% +@id ui.welcome_format_title اختر تنسيق الصفحة +@id ui.welcome_format_body يحفظ NoteCraft كل صفحة بصيغة HTML (موصى بها) أو Markdown من نوع CommonMark + GFM. تستخدم الصفحات الجديدة التنسيق الذي تختاره هنا. يمكنك تغييره لاحقا. +@id ui.welcome_format_next التالي +@id ui.welcome_notebook_prompt_format التنسيق: {format}. +@id ui.welcome_notebook_prompt_title هل تريد إضافة دفتر الترحيب؟ +@id ui.welcome_notebook_prompt_body أضف دفتر الترحيب الخاص بهذا الإصدار إلى دفاترك. إذا كان موجودا فستُحذف نسخته وتُستبدل بالنسخة الجديدة. +@id ui.welcome_notebook_replace_warning ستفقد التغييرات التي أجريتها على دفتر الترحيب الحالي. لن تتغير الدفاتر الأخرى. +@id ui.welcome_notebook_add_yes نعم، أضفه +@id ui.welcome_notebook_add_no لا، ليس الآن +@id ui.welcome_notebook_action_failed تعذر تحديث دفتر الترحيب: {error} +@id ui.welcome_wizard_back رجوع +@id ui.welcome_wizard_finish إنهاء +@id ui.welcome_wizard_done_title شكرا لك +@id ui.welcome_wizard_done_body أصبح NoteCraft جاهزا للاستخدام. تم حفظ اختياراتك. لن يظهر هذا الإعداد مرة أخرى إلا بعد إعادة ضبط التفضيلات. diff --git a/i18n/de.tsv b/i18n/de.tsv index bfee585f..63e8fc9c 100644 --- a/i18n/de.tsv +++ b/i18n/de.tsv @@ -771,3 +771,17 @@ @id ui.zoom_in Vergrößern @id ui.zoom_out Verkleinern @id ui.zoom_to_100 Auf 100 % zoomen +@id ui.welcome_format_title Seitenformat wählen +@id ui.welcome_format_body NoteCraft speichert jede Seite als HTML (empfohlen) oder als CommonMark-+ GFM-Markdown. Neue Seiten verwenden das hier gewählte Format. Du kannst es später ändern. +@id ui.welcome_format_next Weiter +@id ui.welcome_notebook_prompt_format Format: {format}. +@id ui.welcome_notebook_prompt_title Willkommensnotizbuch hinzufügen? +@id ui.welcome_notebook_prompt_body Füge das Willkommensnotizbuch dieser Version deinen Notizbüchern hinzu. Falls es bereits vorhanden ist, wird es gelöscht und durch die neue Kopie ersetzt. +@id ui.welcome_notebook_replace_warning Änderungen am vorhandenen Willkommensnotizbuch gehen verloren. Andere Notizbücher bleiben unverändert. +@id ui.welcome_notebook_add_yes Ja, hinzufügen +@id ui.welcome_notebook_add_no Nein, nicht jetzt +@id ui.welcome_notebook_action_failed Das Willkommensnotizbuch konnte nicht aktualisiert werden: {error} +@id ui.welcome_wizard_back Zurück +@id ui.welcome_wizard_finish Fertig +@id ui.welcome_wizard_done_title Vielen Dank +@id ui.welcome_wizard_done_body NoteCraft ist einsatzbereit. Deine Auswahl ist gespeichert. Diese Einrichtung erscheint erst wieder, wenn du die Einstellungen zurücksetzt. diff --git a/i18n/en-XA.tsv b/i18n/en-XA.tsv index 2d40ecb1..5ed8d142 100644 --- a/i18n/en-XA.tsv +++ b/i18n/en-XA.tsv @@ -771,3 +771,17 @@ @id ui.zoom_in $$$Zoom In@@@ @id ui.zoom_out $$$Zoom Out@@@ @id ui.zoom_to_100 $$$Zoom to 100%@@@ +@id ui.welcome_format_title $$$Choose a page format@@@ +@id ui.welcome_format_body $$$NoteCraft saves each page as HTML (recommended) or as CommonMark + GFM Markdown. New pages use the format you choose here. You can change it later.@@@ +@id ui.welcome_format_next $$$Next@@@ +@id ui.welcome_notebook_prompt_format $$$Format: {format}.@@@ +@id ui.welcome_notebook_prompt_title $$$Add the Welcome notebook?@@@ +@id ui.welcome_notebook_prompt_body $$$Add this release's Welcome notebook to your notebooks. If one already exists, it will be deleted and replaced with the new copy.@@@ +@id ui.welcome_notebook_replace_warning $$$Changes made to the existing Welcome notebook will be lost. Other notebooks will not change.@@@ +@id ui.welcome_notebook_add_yes $$$Yes, add it@@@ +@id ui.welcome_notebook_add_no $$$No, not now@@@ +@id ui.welcome_notebook_action_failed $$$Could not update the Welcome notebook: {error}@@@ +@id ui.welcome_wizard_back $$$Back@@@ +@id ui.welcome_wizard_finish $$$Finish@@@ +@id ui.welcome_wizard_done_title $$$Thank you@@@ +@id ui.welcome_wizard_done_body $$$NoteCraft is ready to use. Your choices are saved. This setup appears again only after you reset the preferences.@@@ diff --git a/i18n/en.tsv b/i18n/en.tsv index 799bd7ce..a4a2a78e 100644 --- a/i18n/en.tsv +++ b/i18n/en.tsv @@ -771,3 +771,17 @@ @id ui.zoom_in Zoom In @id ui.zoom_out Zoom Out @id ui.zoom_to_100 Zoom to 100% +@id ui.welcome_format_title Choose a page format +@id ui.welcome_format_body NoteCraft saves each page as HTML (recommended) or as CommonMark + GFM Markdown. New pages use the format you choose here. You can change it later. +@id ui.welcome_format_next Next +@id ui.welcome_notebook_prompt_format Format: {format}. +@id ui.welcome_notebook_prompt_title Add the Welcome notebook? +@id ui.welcome_notebook_prompt_body Add this release's Welcome notebook to your notebooks. If one already exists, it will be deleted and replaced with the new copy. +@id ui.welcome_notebook_replace_warning Changes made to the existing Welcome notebook will be lost. Other notebooks will not change. +@id ui.welcome_notebook_add_yes Yes, add it +@id ui.welcome_notebook_add_no No, not now +@id ui.welcome_notebook_action_failed Could not update the Welcome notebook: {error} +@id ui.welcome_wizard_back Back +@id ui.welcome_wizard_finish Finish +@id ui.welcome_wizard_done_title Thank you +@id ui.welcome_wizard_done_body NoteCraft is ready to use. Your choices are saved. This setup appears again only after you reset the preferences. diff --git a/i18n/es.tsv b/i18n/es.tsv index 128e0a7c..37a37350 100644 --- a/i18n/es.tsv +++ b/i18n/es.tsv @@ -771,3 +771,17 @@ @id ui.zoom_in Acercar @id ui.zoom_out Alejar @id ui.zoom_to_100 Zoom al 100 % +@id ui.welcome_format_title Elige un formato de página +@id ui.welcome_format_body NoteCraft guarda cada página como HTML (recomendado) o como Markdown CommonMark + GFM. Las páginas nuevas usan el formato que elijas aquí. Podrás cambiarlo más tarde. +@id ui.welcome_format_next Siguiente +@id ui.welcome_notebook_prompt_format Formato: {format}. +@id ui.welcome_notebook_prompt_title ¿Añadir el cuaderno de bienvenida? +@id ui.welcome_notebook_prompt_body Añade a tus cuadernos el cuaderno de bienvenida de esta versión. Si ya existe, se eliminará y se sustituirá por la copia nueva. +@id ui.welcome_notebook_replace_warning Se perderán los cambios hechos en el cuaderno de bienvenida actual. Los demás cuadernos no cambiarán. +@id ui.welcome_notebook_add_yes Sí, añadirlo +@id ui.welcome_notebook_add_no No, ahora no +@id ui.welcome_notebook_action_failed No se pudo actualizar el cuaderno de bienvenida: {error} +@id ui.welcome_wizard_back Atrás +@id ui.welcome_wizard_finish Terminar +@id ui.welcome_wizard_done_title Gracias +@id ui.welcome_wizard_done_body NoteCraft está listo para usar. Tus opciones están guardadas. Esta configuración solo volverá a aparecer si restableces las preferencias. diff --git a/i18n/fa.tsv b/i18n/fa.tsv index 8cbc5bb1..a8c9d072 100644 --- a/i18n/fa.tsv +++ b/i18n/fa.tsv @@ -771,3 +771,17 @@ @id ui.zoom_in بزرگنمایی به داخل @id ui.zoom_out بزرگنمایی به خارج @id ui.zoom_to_100 بزرگنمایی تا ۱۰۰٪ +@id ui.welcome_format_title قالب صفحه را انتخاب کنید +@id ui.welcome_format_body NoteCraft هر صفحه را به صورت HTML (توصیه می‌شود) یا Markdown با CommonMark + GFM ذخیره می‌کند. صفحه‌های جدید با قالبی که اینجا انتخاب می‌کنید ساخته می‌شوند. بعدا می‌توانید آن را تغییر دهید. +@id ui.welcome_format_next بعدی +@id ui.welcome_notebook_prompt_format قالب: {format}. +@id ui.welcome_notebook_prompt_title دفترچه خوش‌آمدگویی اضافه شود؟ +@id ui.welcome_notebook_prompt_body دفترچه خوش‌آمدگویی این نسخه را به دفترچه‌های شما اضافه کنید. اگر از قبل وجود داشته باشد، حذف و با نسخه جدید جایگزین می‌شود. +@id ui.welcome_notebook_replace_warning تغییرات دفترچه خوش‌آمدگویی فعلی از بین می‌رود. دفترچه‌های دیگر تغییر نمی‌کنند. +@id ui.welcome_notebook_add_yes بله، اضافه کن +@id ui.welcome_notebook_add_no نه، فعلا نه +@id ui.welcome_notebook_action_failed به‌روزرسانی دفترچه خوش‌آمدگویی ممکن نشد: {error} +@id ui.welcome_wizard_back قبلی +@id ui.welcome_wizard_finish پایان +@id ui.welcome_wizard_done_title متشکریم +@id ui.welcome_wizard_done_body NoteCraft آماده استفاده است. انتخاب‌های شما ذخیره شد. این راه‌اندازی تنها پس از بازنشانی تنظیمات دوباره نمایش داده می‌شود. diff --git a/i18n/fr.tsv b/i18n/fr.tsv index 6d9f87c2..37e58b96 100644 --- a/i18n/fr.tsv +++ b/i18n/fr.tsv @@ -771,3 +771,17 @@ @id ui.zoom_in Zoom avant @id ui.zoom_out Zoom arrière @id ui.zoom_to_100 Zoom à 100 % +@id ui.welcome_format_title Choisissez un format de page +@id ui.welcome_format_body NoteCraft enregistre chaque page en HTML (recommandé) ou en Markdown CommonMark + GFM. Les nouvelles pages utilisent le format choisi ici. Vous pourrez le modifier plus tard. +@id ui.welcome_format_next Suivant +@id ui.welcome_notebook_prompt_format Format : {format}. +@id ui.welcome_notebook_prompt_title Ajouter le carnet de bienvenue ? +@id ui.welcome_notebook_prompt_body Ajoutez le carnet de bienvenue de cette version à vos carnets. S'il existe déjà, il sera supprimé et remplacé par la nouvelle copie. +@id ui.welcome_notebook_replace_warning Les modifications apportées au carnet de bienvenue existant seront perdues. Les autres carnets ne changeront pas. +@id ui.welcome_notebook_add_yes Oui, l'ajouter +@id ui.welcome_notebook_add_no Non, pas maintenant +@id ui.welcome_notebook_action_failed Impossible de mettre à jour le carnet de bienvenue : {error} +@id ui.welcome_wizard_back Retour +@id ui.welcome_wizard_finish Terminer +@id ui.welcome_wizard_done_title Merci +@id ui.welcome_wizard_done_body NoteCraft est prêt à l'emploi. Vos choix sont enregistrés. Cette configuration ne réapparaîtra qu'après une réinitialisation des préférences. diff --git a/i18n/he.tsv b/i18n/he.tsv index bb7cc509..fc1dfd6f 100644 --- a/i18n/he.tsv +++ b/i18n/he.tsv @@ -771,3 +771,17 @@ @id ui.zoom_in הגדל תקריב @id ui.zoom_out הקטן תקריב @id ui.zoom_to_100 תקריב ל-100% +@id ui.welcome_format_title בחרו תבנית לדף +@id ui.welcome_format_body NoteCraft שומר כל דף כ-HTML (מומלץ) או כ-Markdown מסוג CommonMark + GFM. דפים חדשים ייווצרו בתבנית שתבחרו כאן. אפשר לשנות אותה מאוחר יותר. +@id ui.welcome_format_next הבא +@id ui.welcome_notebook_prompt_format תבנית: {format}. +@id ui.welcome_notebook_prompt_title להוסיף את מחברת הברוכים הבאים? +@id ui.welcome_notebook_prompt_body הוסיפו את מחברת הברוכים הבאים של גרסה זו למחברות שלכם. אם היא כבר קיימת, היא תימחק ותוחלף בעותק החדש. +@id ui.welcome_notebook_replace_warning שינויים שנעשו במחברת הברוכים הבאים הקיימת יאבדו. מחברות אחרות לא ישתנו. +@id ui.welcome_notebook_add_yes כן, הוסף +@id ui.welcome_notebook_add_no לא, לא עכשיו +@id ui.welcome_notebook_action_failed לא ניתן לעדכן את מחברת הברוכים הבאים: {error} +@id ui.welcome_wizard_back הקודם +@id ui.welcome_wizard_finish סיום +@id ui.welcome_wizard_done_title תודה +@id ui.welcome_wizard_done_body NoteCraft מוכן לשימוש. הבחירות שלכם נשמרו. ההגדרה הזו תופיע שוב רק אחרי איפוס ההעדפות. diff --git a/i18n/hi.tsv b/i18n/hi.tsv index 6711b9ae..cecd123b 100644 --- a/i18n/hi.tsv +++ b/i18n/hi.tsv @@ -771,3 +771,17 @@ @id ui.zoom_in ज़ूम इन @id ui.zoom_out ज़ूम आउट @id ui.zoom_to_100 100% पर ज़ूम करें +@id ui.welcome_format_title पेज का फ़ॉर्मेट चुनें +@id ui.welcome_format_body NoteCraft हर पेज को HTML (अनुशंसित) या CommonMark + GFM Markdown में सहेजता है। नए पेज यहाँ चुने गए फ़ॉर्मेट में बनेंगे। इसे बाद में बदला जा सकता है। +@id ui.welcome_format_next आगे +@id ui.welcome_notebook_prompt_format फ़ॉर्मेट: {format}। +@id ui.welcome_notebook_prompt_title स्वागत नोटबुक जोड़ें? +@id ui.welcome_notebook_prompt_body इस रिलीज़ की स्वागत नोटबुक अपनी नोटबुक में जोड़ें। यदि वह पहले से मौजूद है, तो उसे हटाकर नई कॉपी से बदल दिया जाएगा। +@id ui.welcome_notebook_replace_warning मौजूदा स्वागत नोटबुक में किए गए बदलाव खो जाएँगे। अन्य नोटबुक नहीं बदलेंगी। +@id ui.welcome_notebook_add_yes हाँ, जोड़ें +@id ui.welcome_notebook_add_no नहीं, अभी नहीं +@id ui.welcome_notebook_action_failed स्वागत नोटबुक अपडेट नहीं हो सकी: {error} +@id ui.welcome_wizard_back पीछे +@id ui.welcome_wizard_finish समाप्त +@id ui.welcome_wizard_done_title धन्यवाद +@id ui.welcome_wizard_done_body NoteCraft उपयोग के लिए तैयार है। आपकी पसंद सहेज ली गई है। यह सेटअप केवल प्राथमिकताएँ रीसेट करने के बाद फिर दिखेगा। diff --git a/i18n/ja.tsv b/i18n/ja.tsv index eb8eea0b..df459c96 100644 --- a/i18n/ja.tsv +++ b/i18n/ja.tsv @@ -771,3 +771,17 @@ @id ui.zoom_in ズームイン @id ui.zoom_out ズームアウト @id ui.zoom_to_100 100%にズーム +@id ui.welcome_format_title ページ形式を選択 +@id ui.welcome_format_body NoteCraft は各ページを HTML(推奨)または CommonMark + GFM の Markdown で保存します。新しいページはここで選んだ形式で作成されます。後から変更できます。 +@id ui.welcome_format_next 次へ +@id ui.welcome_notebook_prompt_format 形式: {format} +@id ui.welcome_notebook_prompt_title ようこそノートブックを追加しますか? +@id ui.welcome_notebook_prompt_body このバージョンのようこそノートブックをノートブックに追加します。既に存在する場合は削除され、新しいコピーに置き換えられます。 +@id ui.welcome_notebook_replace_warning 既存のようこそノートブックへの変更は失われます。他のノートブックは変更されません。 +@id ui.welcome_notebook_add_yes はい、追加します +@id ui.welcome_notebook_add_no いいえ、今はしない +@id ui.welcome_notebook_action_failed ようこそノートブックを更新できませんでした: {error} +@id ui.welcome_wizard_back 戻る +@id ui.welcome_wizard_finish 完了 +@id ui.welcome_wizard_done_title ありがとうございます +@id ui.welcome_wizard_done_body NoteCraft の準備ができました。選択内容は保存されています。この設定は環境設定をリセットしたときにだけ再表示されます。 diff --git a/i18n/ko.tsv b/i18n/ko.tsv index 65e91510..e0f10cc7 100644 --- a/i18n/ko.tsv +++ b/i18n/ko.tsv @@ -771,3 +771,17 @@ @id ui.zoom_in 확대 @id ui.zoom_out 축소 @id ui.zoom_to_100 100%로 확대 +@id ui.welcome_format_title 페이지 형식 선택 +@id ui.welcome_format_body NoteCraft는 각 페이지를 HTML(권장) 또는 CommonMark + GFM Markdown으로 저장합니다. 새 페이지는 여기서 고른 형식으로 만들어집니다. 나중에 바꿀 수 있습니다. +@id ui.welcome_format_next 다음 +@id ui.welcome_notebook_prompt_format 형식: {format} +@id ui.welcome_notebook_prompt_title 환영 노트북을 추가할까요? +@id ui.welcome_notebook_prompt_body 이 버전의 환영 노트북을 노트북에 추가합니다. 이미 있으면 삭제되고 새 복사본으로 바뀝니다. +@id ui.welcome_notebook_replace_warning 기존 환영 노트북에서 한 변경 내용은 사라집니다. 다른 노트북은 바뀌지 않습니다. +@id ui.welcome_notebook_add_yes 예, 추가합니다 +@id ui.welcome_notebook_add_no 아니요, 나중에요 +@id ui.welcome_notebook_action_failed 환영 노트북을 업데이트할 수 없습니다: {error} +@id ui.welcome_wizard_back 이전 +@id ui.welcome_wizard_finish 완료 +@id ui.welcome_wizard_done_title 감사합니다 +@id ui.welcome_wizard_done_body NoteCraft를 사용할 준비가 되었습니다. 선택한 내용은 저장되었습니다. 이 설정은 환경설정을 초기화한 뒤에만 다시 나타납니다. diff --git a/i18n/ru.tsv b/i18n/ru.tsv index a0659c6c..c37ae528 100644 --- a/i18n/ru.tsv +++ b/i18n/ru.tsv @@ -771,3 +771,17 @@ @id ui.zoom_in Увеличить @id ui.zoom_out Уменьшить @id ui.zoom_to_100 Масштаб 100% +@id ui.welcome_format_title Выберите формат страниц +@id ui.welcome_format_body NoteCraft сохраняет каждую страницу как HTML (рекомендуется) или как Markdown CommonMark + GFM. Новые страницы используют формат, выбранный здесь. Его можно изменить позже. +@id ui.welcome_format_next Далее +@id ui.welcome_notebook_prompt_format Формат: {format}. +@id ui.welcome_notebook_prompt_title Добавить приветственный блокнот? +@id ui.welcome_notebook_prompt_body Добавить приветственный блокнот этой версии в ваши блокноты. Если он уже есть, он будет удалён и заменён новой копией. +@id ui.welcome_notebook_replace_warning Изменения в текущем приветственном блокноте будут потеряны. Другие блокноты не изменятся. +@id ui.welcome_notebook_add_yes Да, добавить +@id ui.welcome_notebook_add_no Нет, не сейчас +@id ui.welcome_notebook_action_failed Не удалось обновить приветственный блокнот: {error} +@id ui.welcome_wizard_back Назад +@id ui.welcome_wizard_finish Готово +@id ui.welcome_wizard_done_title Спасибо +@id ui.welcome_wizard_done_body NoteCraft готов к работе. Ваш выбор сохранён. Эта настройка появится снова только после сброса параметров. diff --git a/i18n/ur.tsv b/i18n/ur.tsv index 60c24ab0..9c87e5b0 100644 --- a/i18n/ur.tsv +++ b/i18n/ur.tsv @@ -771,3 +771,17 @@ @id ui.zoom_in زوم ان @id ui.zoom_out زوم آؤٹ @id ui.zoom_to_100 100% تک زوم کریں +@id ui.welcome_format_title صفحے کا فارمیٹ منتخب کریں +@id ui.welcome_format_body NoteCraft ہر صفحہ HTML (تجویز کردہ) یا CommonMark + GFM Markdown میں محفوظ کرتا ہے۔ نئے صفحات اس فارمیٹ میں بنیں گے جو یہاں منتخب کیا جائے۔ آپ اسے بعد میں بدل سکتے ہیں۔ +@id ui.welcome_format_next آگے +@id ui.welcome_notebook_prompt_format فارمیٹ: {format}۔ +@id ui.welcome_notebook_prompt_title خوش آمدید نوٹ بک شامل کریں؟ +@id ui.welcome_notebook_prompt_body اس ریلیز کی خوش آمدید نوٹ بک اپنی نوٹ بکس میں شامل کریں۔ اگر وہ پہلے سے موجود ہے تو اسے حذف کر کے نئی کاپی سے بدل دیا جائے گا۔ +@id ui.welcome_notebook_replace_warning موجودہ خوش آمدید نوٹ بک میں کی گئی تبدیلیاں ضائع ہو جائیں گی۔ دوسری نوٹ بکس تبدیل نہیں ہوں گی۔ +@id ui.welcome_notebook_add_yes ہاں، شامل کریں +@id ui.welcome_notebook_add_no نہیں، ابھی نہیں +@id ui.welcome_notebook_action_failed خوش آمدید نوٹ بک اپ ڈیٹ نہیں ہو سکی: {error} +@id ui.welcome_wizard_back پیچھے +@id ui.welcome_wizard_finish ختم +@id ui.welcome_wizard_done_title شکریہ +@id ui.welcome_wizard_done_body NoteCraft استعمال کے لیے تیار ہے۔ آپ کا انتخاب محفوظ ہو گیا ہے۔ یہ ترتیب صرف ترجیحات دوبارہ ترتیب دینے کے بعد ظاہر ہوگی۔ diff --git a/i18n/zh.tsv b/i18n/zh.tsv index 1735a850..f503b0ab 100644 --- a/i18n/zh.tsv +++ b/i18n/zh.tsv @@ -771,3 +771,17 @@ @id ui.zoom_in 放大 @id ui.zoom_out 缩小 @id ui.zoom_to_100 缩放至 100% +@id ui.welcome_format_title 选择页面格式 +@id ui.welcome_format_body NoteCraft 会将每个页面保存为 HTML(推荐)或 CommonMark + GFM Markdown。新页面将使用您在此处选择的格式。以后可以更改。 +@id ui.welcome_format_next 下一步 +@id ui.welcome_notebook_prompt_format 格式:{format} +@id ui.welcome_notebook_prompt_title 添加欢迎笔记本? +@id ui.welcome_notebook_prompt_body 将本版本的欢迎笔记本添加到您的笔记本中。如果已存在,它将被删除并替换为新副本。 +@id ui.welcome_notebook_replace_warning 对现有欢迎笔记本所做的更改将丢失。其他笔记本不会改变。 +@id ui.welcome_notebook_add_yes 是,添加 +@id ui.welcome_notebook_add_no 否,暂不 +@id ui.welcome_notebook_action_failed 无法更新欢迎笔记本:{error} +@id ui.welcome_wizard_back 上一步 +@id ui.welcome_wizard_finish 完成 +@id ui.welcome_wizard_done_title 谢谢 +@id ui.welcome_wizard_done_body NoteCraft 已准备就绪。您的选择已保存。只有在重置偏好设置后,此设置才会再次出现。 diff --git a/packaging/OSX/DMG Read Me.txt b/packaging/OSX/DMG Read Me.txt index 92bcfd12..f750518e 100644 --- a/packaging/OSX/DMG Read Me.txt +++ b/packaging/OSX/DMG Read Me.txt @@ -2,13 +2,12 @@ NoteCraft for macOS Install the app 1. Drag NoteCraft.app to Applications. -2. Open Install NoteCraft Welcome Notebook.app from this disk image. -3. Choose Install to copy the optional Welcome notebook into your normal NoteCraft notebooks folder. - An existing notebook with the same name is preserved. -4. Open NoteCraft from Applications. +2. Open NoteCraft from Applications. +3. On the first launch after installation, NoteCraft opens a short setup: a welcome page, the local +logging level, your page format, and whether to add the Welcome notebook in that format. Choosing Yes +creates `welcome-to-notecraft` in your notebooks folder when you press Finish, then opens it. Changes +in an existing Welcome notebook will be lost. Other notebooks are unchanged. Choosing No creates +nothing. The setup does not appear again unless you reset the preferences. -The Welcome notebook is a separate user-owned folder. You can edit or delete it like any other -notebook. NoteCraft does not install or recreate it. If this disk image does not include the -Welcome Notebook folder, skip step 2 and open NoteCraft. - -You can also drag NoteCraft.app to Applications and use the app without the optional notebook. +The Welcome notebook is an ordinary user-owned folder. You can edit or delete it like any other +notebook. The app bundle includes the source used to create it. diff --git a/packaging/OSX/README.md b/packaging/OSX/README.md index 938abcdd..6114bcca 100644 --- a/packaging/OSX/README.md +++ b/packaging/OSX/README.md @@ -1,9 +1,10 @@ # NoteCraft macOS packaging guide This directory contains the NoteCraft macOS app, DMG and CLI archive scripts. The app bundle -includes both generated Welcome notebook formats and refreshes the managed Welcome notebook when -it starts. It replaces only `welcome-to-notecraft`; sibling notebooks remain unchanged. Packages -remain test artifacts until a maintainer completes signing, notarization and clean-machine checks. +includes both generated Welcome notebook formats as the source for the first-use setup. For 0.0.9 +the setup is verified on Windows only; the macOS check is deferred. It replaces only `welcome-to-notecraft`; sibling notebooks +remain unchanged. Packages remain test artifacts until a maintainer completes signing, +notarization and clean-machine checks. ## Build and verify test packages @@ -19,8 +20,8 @@ bash packaging/OSX/test-provenance.sh ``` The DMG contains `NoteCraft.app`, an Applications link and a read-me file at its root. Drag the -app to Applications and open it. NoteCraft creates or refreshes the Welcome notebook in the user's -notebook folder before loading the notebook tree. +app to Applications and open it. On first launch of each version, NoteCraft asks whether to add +the bundled Welcome notebook to the user's notebook folder. The default `--arch universal` builds both Apple targets and combines the GUI and CLI with `lipo`. `--arch x86_64` produces Intel-only packages. The DMG and separate CLI zip are written to @@ -60,10 +61,10 @@ Gatekeeper; do not change system security settings to test it. For a manual Finder check, use a disposable notebook directory containing a sentinel user notebook and an older `welcome-to-notecraft`. Open the DMG, drag `NoteCraft.app` into Applications, then -launch it. Confirm the Welcome notebook has both formats and the current content, while the -sentinel notebook is unchanged. Quit and relaunch to verify refresh behavior. Remove only the test -app after the check; confirm app removal leaves the notebook root in place. Repeat on Intel before -release. +launch it. Choose Yes and confirm the Welcome notebook has both formats and the current content, +the old Welcome files are gone, and the sentinel notebook is unchanged. Relaunch to confirm the +same version does not ask again. Remove only the test app after the check; confirm app removal +leaves the notebook root in place. Repeat on Intel before release. The preferred direction is to follow the packaging tools and libraries already used by the ArtCraft applications, especially the sibling MailCraft macOS package. Do not introduce a new diff --git a/packaging/OSX/issues.md b/packaging/OSX/issues.md index 5ff4cd9f..7c3049d3 100644 --- a/packaging/OSX/issues.md +++ b/packaging/OSX/issues.md @@ -5,8 +5,9 @@ cross-platform policy lives in the canonical `packaging/installation artifacts.m ## Current limitations -1. The app bundle carries both generated formats and refreshes the managed Welcome notebook on - launch. Native macOS package execution has not yet been run from this Windows development host. +1. The app bundle carries both generated formats. The first-use setup is deferred on macOS for 0.0.9 + by the owner's Windows-first decision (2026-11-08). Native macOS package execution has not yet been + run from this Windows development host. 2. Clean-profile launch, replacement of an older Welcome notebook, sibling notebook preservation, app upgrade and uninstall behavior still need manual verification on Apple Silicon and Intel. 3. The package script supports ad-hoc signing for local smoke tests, but an ad-hoc app is not a @@ -15,8 +16,8 @@ cross-platform policy lives in the canonical `packaging/installation artifacts.m ## Required before macOS release signoff -- Verify that the app bundle contains both generated formats and the Welcome copy refreshes on - startup without modifying a sibling notebook. +- Verify that the app bundle contains both generated formats, Yes replaces the Welcome copy, No + preserves it, and neither choice modifies a sibling notebook. - Test clean first launch, restart, upgrade, Welcome replacement and uninstall on Apple Silicon and Intel. - Record signing, notarization, stapling, checksums, runner versions and manual results in the diff --git a/packaging/installation artifacts.md b/packaging/installation artifacts.md index e80e1f61..268af142 100644 --- a/packaging/installation artifacts.md +++ b/packaging/installation artifacts.md @@ -1,8 +1,9 @@ # Installation artifacts Status: product contract updated by the owner on 2026-11-07. This is the single authority for -installation artifact responsibilities and the User Assistance demo notebook. Every app launch -refreshes the managed Welcome notebook from the generated content bundled with the application. +installation artifact responsibilities and the User Assistance demo notebook. The application +bundles the generated notebook and asks once per app version before creating or replacing the +per-user Welcome notebook. ## Separate installation artifacts @@ -11,11 +12,11 @@ Every distribution has two logically separate artifacts: 1. **Application binaries and bundled source content**: executable code plus the two generated Welcome notebook formats, deployed to the platform's normal application location. 2. **Managed Welcome notebook**: a per-user copy in the target user's normal `NoteCraft` - notebooks folder, refreshed by the app when it starts. + notebooks folder, created or replaced by the app only after the user chooses Yes. -Each installer carries the generated content with the app so the app can provision it without a -separate setup download, helper choice, or network request. The content remains ordinary notebook -files; it is not executable code. +Each installer carries the generated content with the app so NoteCraft can provision it without a +separate setup download or network request. The content remains ordinary notebook files; it is not +executable code. The authored notebook source is `docs/demo/scripts/content`. `cargo xtask demo` generates the official HTML and CMGFM notebooks under `docs/demo/DemoNotebook`, each with all 13 languages. @@ -25,21 +26,31 @@ the Welcome notebook and for notebooks created or opened by users. ## Separation of responsibility -The running app owns the per-user copy: +The running app owns the per-user copy after the user confirms: - Install application binaries in the application location. -- Install the User Assistance notebook in the user's normal notebooks folder. -- At app startup, create or replace only `welcome-to-notecraft` from the bundled HTML and CMGFM - formats. This refreshes app-authored content on every launch. +- Bundle the User Assistance source with the application binaries. +- Show the first-use wizard once: on the first launch after installation, or after the preferences + are reset. It is one dialog with five pages and Next at the bottom right: the welcome page with + the brand banner; the local logging level; the page format, HTML or CommonMark + GFM, saved as the + default; whether to create the demo notebook in that format; and a thank-you page with Finish. +- The wizard does not reopen for later app versions. Installation copies nothing into the notebooks + folder; the package ships the generated editions only as the wizard's source. +- On Yes on the demo page, create or completely replace only `welcome-to-notecraft` from the bundled + edition for the chosen format when Finish is pressed. The edition's notebook folder becomes the + managed notebook, so the notebook list finds it, and the Welcome page opens. The other format is + not installed. +- On No, leave any existing Welcome notebook unchanged and create none. - Preserve every sibling notebook and its contents. - On uninstall, remove application files only; leave user notebooks in place. -- If refreshing the Welcome notebook fails, report the error and preserve the existing copy. +- If creating or replacing the Welcome notebook fails, report the error and preserve the existing + copy. -Desktop apps copy the generated source from the installed package or app bundle into the selected -user notebook root. Android refreshes from APK assets before opening the native app. Browser startup -refreshes it from the website archive on each non-invited session. The Welcome notebook's content -and edits are replaced with the release-authored version on app start; sibling notebooks are -untouched. Android app-specific storage follows Android's normal uninstall lifecycle. +Desktop apps copy the chosen edition from the installed package or app bundle into the selected +user notebook root only after Yes in step 3. The desktop setup launcher installs nothing; it starts +NoteCraft. Android and the browser have separate startup paths; each must +apply the same per-version confirmation before replacing a user's Welcome notebook. Android +app-specific storage follows Android's normal uninstall lifecycle. ## Platform installation contract @@ -51,11 +62,11 @@ do not guess a home or storage path when the platform provides an API. | Platform | Application binaries | User Assistance notebook | Installation owner | |---|---|---|---| -| Website demo | Browser app (JavaScript and WebAssembly) | `/NoteCraft/welcome-to-notecraft`, containing HTML and CMGFM | Browser startup refreshes it from the two-format archive | -| Windows | Normal per-machine or per-user app location | Current user's Documents/NoteCraft/welcome-to-notecraft | App startup copies from the package's bundled source | -| Linux | Normal package or portable-app location | Current user's Documents/NoteCraft/welcome-to-notecraft | App startup copies from the package's bundled source | -| macOS | `NoteCraft.app` copied to Applications | Current user's Documents/NoteCraft/welcome-to-notecraft | App startup copies from app resources | -| Android | Installed APK application package | App-specific external files/NoteCraft/welcome-to-notecraft | APK setup activity refreshes both asset formats before opening NoteCraft | +| Website demo | Browser app (JavaScript and WebAssembly) | `/NoteCraft/welcome-to-notecraft`, containing HTML and CMGFM | Browser prompt must ask before copying from the two-format archive | +| Windows | Normal per-machine or per-user app location | Current user's Documents/NoteCraft/welcome-to-notecraft | First-use wizard copies the chosen edition from the package's bundled source after Yes | +| Linux | Normal package or portable-app location | Current user's Documents/NoteCraft/welcome-to-notecraft | First-use wizard copies the chosen edition from the package's bundled source after Yes | +| macOS | `NoteCraft.app` copied to Applications | Current user's Documents/NoteCraft/welcome-to-notecraft | First-use wizard copies the chosen edition from app resources after Yes | +| Android | Installed APK application package | App-specific external files/NoteCraft/welcome-to-notecraft | APK startup must ask before copying the asset formats | The browser archive contains both directories under `docs/demo/DemoNotebook`, is version-checked in the website workflow, and is loaded under the same `/NoteCraft` root as other browser notebooks. @@ -65,6 +76,13 @@ notebook. The Android launch activity refreshes the managed notebook from both APK asset formats before opening the native app. +## Platform scope for 0.0.9 (owner, 2026-11-08) + +The first-use wizard is implemented and verified on Windows only for this release. macOS, Linux, +the website and Android are deferred for the wizard flow: their packages keep shipping the generated +editions as the wizard's source, but no platform-specific wizard work or sign-off is claimed for them +in 0.0.9. Installation copies no notebook content on any platform. + ## Current implementation status Desktop and mobile package staging follows the app-managed refresh contract: @@ -74,6 +92,10 @@ Desktop and mobile package staging follows the app-managed refresh contract: - Linux packages include both generated formats. Installed-run refresh and sibling-preservation checks remain required. - macOS bundles both formats in app resources; native launch verification remains required. +- The desktop setup launcher no longer installs the Welcome notebook. The first-use wizard does, + and only for the format the user chose. Windows, Linux and macOS checks of the wizard remain + required. The macOS setup app now shows a notice and does not install anything; agent 3 must + revalidate that path. Android stages both formats as APK assets and refreshes them before opening NoteCraft. Build and emulator checks remain required. @@ -86,10 +108,13 @@ For each supported artifact and platform, signoff proves: 2. App startup creates or replaces only `welcome-to-notecraft` in the platform notebook root. 3. A sentinel sibling notebook stays byte-for-byte unchanged. 4. Both format variants retain their page tree, assets, and metadata. -5. The managed Welcome notebook is refreshed from app content on restart. -6. Desktop uninstall removes app binaries and leaves the user's notebook untouched. Android +5. Yes in step 3 replaces the managed Welcome notebook with the chosen edition only; No preserves + its current files. +6. The wizard opens once after installation or a preferences reset, and does not reopen after an + upgrade. Its format page saves the default format, and Finish saves every answer. +7. Desktop uninstall removes app binaries and leaves the user's notebook untouched. Android uninstall removes app-specific notebook files as required by the OS storage model. -7. A failed refresh is reported and does not replace the existing copy with a partial notebook. +8. A failed replacement is reported and does not replace the existing copy with a partial notebook. Run `cargo xtask demo-check` and `cargo test -p notecraft-formats --test format_parity` for the source outputs. Then inspect the diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index e05327c1..1e4f49fb 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -64,7 +64,7 @@ install -Dm644 "$ROOT/LICENSE-MIT" "$STAGE/usr/share/doc/notecraft/LICENSE-MIT" install -Dm644 "$ROOT/LICENSE-APACHE" "$STAGE/usr/share/doc/notecraft/LICENSE-APACHE" install -Dm644 "$ROOT/NOTICE" "$STAGE/usr/share/doc/notecraft/NOTICE" -# The app copies both generated formats into the user's notebooks folder at startup. +# The app offers both generated formats on first launch of each app version. DEMO_SOURCE="$ROOT/docs/demo/DemoNotebook" for format in html cmgfm; do [ -d "$DEMO_SOURCE/$format" ] || { echo "required $format demo format is missing" >&2; exit 1; } diff --git a/packaging/windows/notecraft.wxs b/packaging/windows/notecraft.wxs index 3186da3a..b4f4270a 100644 --- a/packaging/windows/notecraft.wxs +++ b/packaging/windows/notecraft.wxs @@ -10,8 +10,9 @@ Per-machine install into Program Files with a Start Menu shortcut. The installer shows the standard WiX dialogs: welcome and licence, progress, and a finish page. - The app carries both generated Welcome notebook formats and refreshes only its dedicated - per-user Welcome notebook folder at startup. Other notebook folders remain unchanged. + The app carries both generated Welcome notebook formats and asks once per app version before + creating or replacing its dedicated per-user Welcome notebook. Other notebook folders remain + unchanged. UpgradeCode and the component GUIDs below belong to NoteCraft alone. Never change the UpgradeCode after the first public release: Windows Installer would stop treating a new @@ -49,7 +50,7 @@ Impersonate="yes" Return="ignore" /> - + From 179989e0862ca30db616543e80d596ae1555ca48 Mon Sep 17 00:00:00 2001 From: AlienTech Software Date: Sat, 7 Nov 2026 18:46:43 -0800 Subject: [PATCH 5/8] fix(ui): remove the thank-you line from the wizard welcome page The welcome page keeps its banner and title. The closing thank-you page of the wizard is unchanged. Co-Authored-By: Claude Haiku 5.5 --- crates/ui-egui/src/app.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 15f6e586..8085a0b4 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -5057,9 +5057,7 @@ impl NoteCraftApp { } modal_title(ui, &self.tokens, title.as_str()); match *step { - 0 => { - ui.label(crate::tl_id!("ui.thank_you_for_trying_notecraft")); - } + 0 => {} 1 => { ui.label(crate::tl_id!("ui.privacy_is_our_top_priority_all_logs_and_telemetry_s_d87cae4eac")); ui.add_space(6.0); From 81c649018e98caf5118cbaf3879f052d20514d3f Mon Sep 17 00:00:00 2001 From: AlienTech Software Date: Sat, 7 Nov 2026 19:11:44 -0800 Subject: [PATCH 6/8] fix(ui): wizard logging step defaults to debug The first-use wizard opens its logging step on debug when no level is saved yet. The user's choice is still saved as they make it, and the app-wide telemetry default is unchanged. Co-Authored-By: Claude Haiku 5.5 --- crates/ui-egui/src/app.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 8085a0b4..a27c2c37 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -682,6 +682,7 @@ impl NoteCraftApp { let telemetry_level = session.settings.get("telemetry_level").unwrap_or_else(|| default_telemetry_level(cfg!(debug_assertions)).to_string()); log::info!("privacy welcome modal state: show={} telemetry_level={:?}", privacy_welcome, telemetry_level); let wizard_format = session.settings.global_format().0; + let wizard_level = session.settings.get("telemetry_level").unwrap_or_else(|| "debug".to_string()); NoteCraftApp { session, nav: NavHistory::default(), @@ -696,7 +697,7 @@ impl NoteCraftApp { frameless: false, editor: None, dialog: if privacy_welcome { - Some(Dialog::FirstUseWizard { step: 0, level: telemetry_level, format: wizard_format, add_demo: true, error: None }) + Some(Dialog::FirstUseWizard { step: 0, level: wizard_level, format: wizard_format, add_demo: true, error: None }) } else { None }, @@ -767,7 +768,7 @@ impl NoteCraftApp { fn first_use_wizard(&self) -> Dialog { Dialog::FirstUseWizard { step: 0, - level: self.session.settings.get("telemetry_level").unwrap_or_else(|| default_telemetry_level(cfg!(debug_assertions)).to_string()), + level: self.session.settings.get("telemetry_level").unwrap_or_else(|| "debug".to_string()), format: self.session.settings.global_format().0, add_demo: true, error: None, From 67429b9e5a532ceb9d6162df13acf396069fc588 Mon Sep 17 00:00:00 2001 From: AlienTech Software Date: Sat, 7 Nov 2026 19:39:23 -0800 Subject: [PATCH 7/8] fix(installer): the first launch after installing shows the wizard The MSI leaves a first-use.pending marker beside the app. The first launch clears the first-use flag, shows the wizard once, and removes the marker. The marker stays if the setting cannot be saved, so the next launch retries. Co-Authored-By: Claude Haiku 5.5 --- apps/notecraft/src/main.rs | 34 +++++++++++++++++++++++++++++++++ packaging/windows/notecraft.wxs | 3 +++ packaging/windows/package.ps1 | 2 ++ 3 files changed, 39 insertions(+) diff --git a/apps/notecraft/src/main.rs b/apps/notecraft/src/main.rs index c39e2912..ad606239 100644 --- a/apps/notecraft/src/main.rs +++ b/apps/notecraft/src/main.rs @@ -91,6 +91,23 @@ fn demo_payload(_executable: &std::path::Path) -> Option { if installed.is_dir() { Some(installed) } else { Some(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../docs/demo/DemoNotebook")) } } +/// The file the MSI leaves beside the app to ask for the first-use wizard once. +const INSTALL_MARKER: &str = "first-use.pending"; + +/// Clears the first-use state when the installer left its marker, then removes the marker. The +/// marker stays if the setting cannot be saved, so the next launch tries again. +fn take_install_marker(install_dir: &std::path::Path, settings: &Settings) -> bool { + let marker = install_dir.join(INSTALL_MARKER); + if !marker.is_file() { + return false; + } + if settings.set("privacy_welcome_seen", "").is_err() { + return false; + } + let _ = std::fs::remove_file(&marker); + true +} + fn flag_value(args: &[String], name: &str) -> Option { args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned() } @@ -185,6 +202,10 @@ fn main() -> eframe::Result { let _ = session.settings.set("privacy_welcome_seen", ""); applog::info("First-use flag set: the first-use wizard will show"); } + // The installer leaves a marker beside the app. The first launch after installing shows the wizard again. + if let Some(dir) = executable.parent() { + take_install_marker(dir, &session.settings); + } let mut startup_alerts: Vec<(&str, String)> = Vec::new(); // NoteCraft draws its own title bar unless the settings say the system's is wanted. @@ -271,6 +292,19 @@ fn main() -> eframe::Result { mod tests { use super::*; + #[test] + fn an_installer_marker_asks_for_the_first_use_wizard_once() { + let t = notecraft_store::testing::TempDir::new("install-marker"); + let settings = Settings::at(t.path().join("settings.toml")); + settings.set("privacy_welcome_seen", "true").expect("seen before install"); + std::fs::write(t.path().join(INSTALL_MARKER), "").expect("installer marker"); + + assert!(take_install_marker(t.path(), &settings)); + assert_eq!(settings.get("privacy_welcome_seen").as_deref(), Some(""), "the wizard shows again"); + assert!(!t.path().join(INSTALL_MARKER).exists(), "the marker is used up"); + assert!(!take_install_marker(t.path(), &settings), "a second launch does not ask again"); + } + #[test] fn the_notebooks_flag_wins() { let args = vec!["--notebooks".to_string(), "somewhere".to_string()]; diff --git a/packaging/windows/notecraft.wxs b/packaging/windows/notecraft.wxs index b4f4270a..eb598903 100644 --- a/packaging/windows/notecraft.wxs +++ b/packaging/windows/notecraft.wxs @@ -80,6 +80,9 @@ + + + diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index 55165ae1..a0cb3d75 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -111,6 +111,8 @@ $Stage = Join-Path $TargetDir "windows-package\$Arch" Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Stage | Out-Null Copy-Item (Join-Path $Bin 'notecraft.exe'), (Join-Path $Bin 'notecraft-cli.exe') $Stage +# The installer leaves this marker beside the app. The first launch after installing shows the first-use wizard again. +[IO.File]::WriteAllText((Join-Path $Stage 'first-use.pending'), '') # The app copies both generated formats into the user's notebooks folder at startup. $DemoSource = Join-Path $Root 'docs\demo\DemoNotebook' From 4a7c92b874cf032fac992ce99ff914b96d530212 Mon Sep 17 00:00:00 2001 From: AlienTech Software Date: Sat, 7 Nov 2026 19:49:50 -0800 Subject: [PATCH 8/8] fix(web): skip the first-use wizard and always install the demo The web build registers the Welcome install hook used by the wizard's Finish, so the chosen edition installs. It also marks the wizard as seen at startup, since the web demo has no first-use wizard. Co-Authored-By: Claude Haiku 5.5 --- .github/web-build/test_bundle_demo.py | 8 ++++++++ .github/web-build/web.diff | 24 +++++++++++++++++++++--- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/.github/web-build/test_bundle_demo.py b/.github/web-build/test_bundle_demo.py index 63e52b26..7be45ab7 100644 --- a/.github/web-build/test_bundle_demo.py +++ b/.github/web-build/test_bundle_demo.py @@ -45,5 +45,13 @@ def test_rejects_a_demo_generated_for_a_different_release(self) -> None: bundle_demo(self.root / "docs" / "demo" / "DemoNotebook", Path(temporary) / "demo.zip", wrong_version) + def test_first_run_installs_only_the_html_edition_at_the_notebook_root(self) -> None: + patch = (self.root / ".github" / "web-build" / "web.diff").read_text(encoding="utf-8") + self.assertIn("with_welcome_notebook_setup(|_root, format| install_edition(format))", patch) + self.assertIn('session.settings.set("privacy_welcome_seen", "true")', patch) + self.assertIn('relative.strip_prefix(format)', patch) + self.assertIn("Ok(Some(notebook.to_string_lossy().into_owned()))", patch) + self.assertNotIn('Ok(Some(notebook.join("00-start/welcome/index.html")', patch) + if __name__ == "__main__": unittest.main() diff --git a/.github/web-build/web.diff b/.github/web-build/web.diff index 989d9dc7..fc656fef 100644 --- a/.github/web-build/web.diff +++ b/.github/web-build/web.diff @@ -117,6 +117,8 @@ index 0000000..f4394fb + static CTX: std::cell::OnceCell = const { std::cell::OnceCell::new() }; + static CJK: RefCell = const { RefCell::new(Face::Wanted) }; + static PEN: RefCell> = const { RefCell::new(Vec::new()) }; ++ /// The release Welcome archive's files (html/… and cmgfm/…), kept so Finish can install the chosen edition. ++ static WELCOME: RefCell)>> = const { RefCell::new(Vec::new()) }; + } + + /// A pen's reading from the canvas's pointer events: phase, pointer, where (CSS pixels), pressure. @@ -197,13 +199,27 @@ index 0000000..f4394fb + return Err(format!("The {format} Welcome notebook has {} language folders; expected 13", languages.len())); + } + } ++ WELCOME.with_borrow_mut(|w| *w = files); ++ install_edition("html")?; ++ Ok(Some(notebook.to_string_lossy().into_owned())) ++ } ++ ++ /// Installs one edition ("html" or "cmgfm") of the Welcome notebook at the notebook root, replacing the managed ++ /// copy. Finish calls this through the same hook the desktop app uses, so the chosen format is what gets installed. ++ fn install_edition(format: &str) -> Result { ++ let notebook = Path::new(ROOT).join("welcome-to-notecraft"); ++ let files = WELCOME.with_borrow(|w| w.clone()); ++ if files.is_empty() { ++ return Err("the Welcome notebook has not been loaded yet".into()); ++ } + if fs::metadata(¬ebook).is_ok() { + fs::remove_dir_all(¬ebook).map_err(|e| format!("Could not replace the existing Welcome notebook: {e}"))?; + } + for (relative, content) in files { -+ fs::write(notebook.join(relative), content).map_err(|e| format!("Could not install the Welcome notebook: {e}"))?; ++ let Ok(edition) = relative.strip_prefix(format) else { continue }; ++ fs::write(notebook.join(edition), content).map_err(|e| format!("Could not install the Welcome notebook: {e}"))?; + } -+ Ok(Some(notebook.join("00-start/welcome/index.html").to_string_lossy().into_owned())) ++ Ok(notebook) + } + /// Follows the canvas's pen pointers: eframe turns them into mouse events and drops their pressure. + fn listen_to_the_pen(canvas: &web_sys::HtmlCanvasElement) { @@ -484,7 +500,9 @@ index 0000000..f4394fb + CTX.with(|c| c.set(cc.egui_ctx.clone()).ok()); + cc.egui_ctx.add_bytes_loader(std::sync::Arc::new(Files)); + let session = Session::new(Path::new(ROOT), Settings::at(SETTINGS)).map_err(|e| e.to_string())?; -+ let mut app = NoteCraftApp::new(session); ++ // The web demo has no first-use wizard: mark it seen, so it never opens here. ++ session.settings.set("privacy_welcome_seen", "true").map_err(|e| e.to_string())?; ++ let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|_root, format| install_edition(format)); + if let Some(page) = welcome_page { + if let Some(page) = page.map_err(|e| e.to_string())? { + app.open_path(&page);