diff --git a/Cargo.lock b/Cargo.lock index 2109e39..8f85f76 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -954,6 +954,7 @@ dependencies = [ "hintway_analytics", "memmap2", "mslnk", + "pulldown-cmark", "rayon", "serde", "serde_json", @@ -1276,6 +1277,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "pulldown-cmark" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9f068eba8e7071c5f9511831b44f32c740d5adf574e990f946ddb53db2f314e" +dependencies = [ + "bitflags 2.13.2", + "memchr", + "unicase", +] + [[package]] name = "quote" version = "1.0.47" @@ -1860,6 +1872,12 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + [[package]] name = "unicode-ident" version = "1.0.26" diff --git a/common/src/model/installer_payload.rs b/common/src/model/installer_payload.rs index 0076b68..4ab3031 100644 --- a/common/src/model/installer_payload.rs +++ b/common/src/model/installer_payload.rs @@ -35,12 +35,12 @@ pub struct InstallerPayload { pub payload_blake3: String, pub created_at_unix: i64, pub manifest: Manifest, - /// Optional EULA text shown on the License page of the installer UI. + /// Optional EULA source shown as CommonMark on the License page. /// `None` falls back to a built-in placeholder. #[serde(default, skip_serializing_if = "Option::is_none")] pub license_text: Option, - /// Per-language EULA translations, keyed by 2-letter UI language code - /// (`"fr"`). See [`license_for`](Self::license_for). + /// Per-language CommonMark EULA translations, keyed by 2-letter UI + /// language code (`"fr"`). See [`license_for`](Self::license_for). #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub license_texts: BTreeMap, /// File-type associations to register under `HKCU\Software\Classes`. @@ -106,8 +106,8 @@ pub struct InstallerPayload { } impl InstallerPayload { - /// EULA to show for UI language `lang`: its translation, else the default - /// `license_text`. `None` (or empty) = built-in placeholder. + /// CommonMark EULA source for UI language `lang`: its translation, else + /// the default `license_text`. `None` (or empty) = built-in placeholder. pub fn license_for(&self, lang: &str) -> Option<&str> { self.license_texts .get(lang) diff --git a/docs/src/building/config.md b/docs/src/building/config.md index cbe1a9b..fe6c2d0 100644 --- a/docs/src/building/config.md +++ b/docs/src/building/config.md @@ -75,8 +75,8 @@ one of `pub_key` / `pub_key_literal` is also required. An invalid | Key | Type | Default | Description | |---|---|---|---| -| `license` | path | built-in placeholder | UTF-8 EULA text shown on the License page. | -| `licenses` | table | `{}` | Per-language EULA translations, `{ fr = "EULA-fr.txt" }`. See [Branding](../packaging/branding.md#translations). | +| `license` | path | built-in placeholder | UTF-8 plain-text or CommonMark EULA shown on the License page. | +| `licenses` | table | `{}` | Per-language EULA translations, `{ fr = "EULA-fr.md" }`. See [Branding](../packaging/branding.md#translations). | | `banner` | path | flat gray header | PNG painted across the wizard header. See [Branding](../packaging/branding.md). | | `banner_dark` | path | same as `banner` | Dark-theme variant of `banner` for the WinUI wizard. Needs `banner`. See [Branding](../packaging/branding.md#dark-theme-variant). | | `assoc` | array | `[]` | File associations: `".ext:Description"` strings and/or `[[assoc]]` tables with an icon choice. See [File associations](../packaging/associations.md). | @@ -123,7 +123,7 @@ out = "dist/setup-myapp-1.0.exe" priv_key = "keys/priv.key" pub_key = "keys/pub.key" -license = "legal/EULA-myapp-en.txt" +license = "legal/EULA-myapp-en.md" banner = "branding/header-1400x144.png" banner_dark = "branding/header-dark-1400x144.png" assoc = [".myx:MyApp Document", ".myz:MyApp Archive"] diff --git a/docs/src/packaging/branding.md b/docs/src/packaging/branding.md index 0889afa..08608dc 100644 --- a/docs/src/packaging/branding.md +++ b/docs/src/packaging/branding.md @@ -8,15 +8,21 @@ required. All are driven from `pack`, on the CLI or in the ## License text -Pass `--license ` and the UTF-8 text in that file becomes the EULA shown -on the installer's License page. Without it, the page shows a built-in -placeholder text. +Pass `--license ` and the UTF-8 plain text or CommonMark in that file becomes the +EULA shown on the installer's License page. Both `.txt` and `.md` use the same +CommonMark renderer, so existing plain-text files remain supported without a +configuration change. Paragraphs, headings (levels 1–6), ordered and unordered +lists (including nested lists), block quotes, emphasis, strong text, inline and +fenced code, thematic breaks and links are supported. Clickable links are +limited to `http`, `https` and `mailto`. Images are ignored, table syntax stays +plain text, and raw HTML is displayed rather than interpreted. Without a +license file, the page shows a built-in placeholder text. ```pwsh installer_builder.exe pack ` --product "My App" --product-id myapp --publisher "My Company" --to-version 1.0 ` --input .\build\myapp --exe myapp.exe ` - --license .\legal\EULA-myapp-en.txt ` + --license .\legal\EULA-myapp-en.md ` --priv-key .\keys\priv.key --pub-key .\keys\pub.key ` --out .\dist\setup-myapp-1.0.exe ``` @@ -28,8 +34,8 @@ file per language with `--license-lang =` (repeatable), or a `licenses` table in the config file: ```toml -license = "legal/EULA-en.txt" # fallback for every other language -licenses = { fr = "legal/EULA-fr.txt", de = "legal/EULA-de.txt" } +license = "legal/EULA-en.md" # fallback for every other language +licenses = { fr = "legal/EULA-fr.md", de = "legal/EULA-de.md" } ``` The installer shows the file for its UI language, falling back to `license` @@ -125,6 +131,9 @@ $env:INSTALLWAY_PREVIEW_BANNER_DARK = ".\branding\header-dark-1400x144.png" .\target\debug\installer.exe --preview license ``` +On a machine with WinUI available, append `-win32` to compare the fallback +renderer with the same sample: `--preview license-win32`. + Switch Windows between light and dark mode (Settings > Personalization > Colors) to check both. diff --git a/docs/src/reference/cli.md b/docs/src/reference/cli.md index 7666e58..490f132 100644 --- a/docs/src/reference/cli.md +++ b/docs/src/reference/cli.md @@ -60,7 +60,7 @@ wins. Required fields are checked after merging. See | Option | Default | Description | |---|---|---| -| `--license ` | Built-in placeholder | UTF-8 EULA shown on the License page. | +| `--license ` | Built-in placeholder | UTF-8 plain-text or CommonMark EULA shown on the License page. | | `--license-lang ` | None | EULA translation for one UI language. Repeatable. See [Branding](../packaging/branding.md#translations). | | `--banner ` | Flat gray header | PNG painted across the wizard header. Author at 1400 x 144 px; see [Branding](../packaging/branding.md#header-banner). | | `--banner-dark ` | Same as `--banner` | Dark-theme variant of `--banner`, shown by the WinUI wizard when Windows runs dark (with light title text). Needs `--banner`; see [Branding](../packaging/branding.md#dark-theme-variant). | diff --git a/docs/src/reference/payload.md b/docs/src/reference/payload.md index 81fd9db..ea0ff21 100644 --- a/docs/src/reference/payload.md +++ b/docs/src/reference/payload.md @@ -44,8 +44,8 @@ serializer-determinism trap. | `payload_blake3` | `String` | BLAKE3 of the payload archive, re-verified before extraction. | | `created_at_unix` | `i64` | | | `manifest` | `Manifest` | The per-file table; see below. | -| `license_text` | `Option` | EULA shown on the License page. | -| `license_texts` | `BTreeMap` | EULA translations by UI language code; picked over `license_text` for that language. | +| `license_text` | `Option` | UTF-8 EULA source rendered as CommonMark on the License page. | +| `license_texts` | `BTreeMap` | CommonMark EULA translations by UI language code; picked over `license_text` for that language. | | `associations` | `Vec` | File types to register under `Software\Classes`. Each has `ext`, `description`, and optional `icon` (token template, empty means the main exe) and `icon_index` (`>= 0` an index, `< 0` a negated resource id; default `0`). | | `plugins` | `Vec` | Bundled [plugins](../packaging/plugins.md) and their phases. | | `shortcuts` | `Vec` | [Shortcuts](../packaging/shortcuts.md) to create. `dir`, `name`, `target`, and `args` are token templates. None are created unless declared. | diff --git a/installer/Cargo.toml b/installer/Cargo.toml index bf864c9..748e24c 100644 --- a/installer/Cargo.toml +++ b/installer/Cargo.toml @@ -29,6 +29,7 @@ mslnk = "0.1" fs4 = "1" memmap2 = "0.9" rayon = "1.12" +pulldown-cmark = { version = "0.13", default-features = false } [target.'cfg(windows)'.dependencies] windows = { version = "0.62.2", features = [ @@ -37,6 +38,7 @@ windows = { version = "0.62.2", features = [ "Win32_System_Com", "Win32_UI_WindowsAndMessaging", "Win32_UI_Controls", + "Win32_UI_Controls_RichEdit", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_HiDpi", "Win32_UI_Shell", diff --git a/installer/src/main.rs b/installer/src/main.rs index 24b4aa5..3b80424 100644 --- a/installer/src/main.rs +++ b/installer/src/main.rs @@ -86,7 +86,8 @@ struct Cli { force_show_path_window: bool, /// Dev-only: render one UI view with sample data, no payload needed - /// (`license` | `choose` | `progress` | `done` | `error` | `minimal`). + /// (`license` | `choose` | `progress` | `done` | `error` | `minimal`), + /// optionally suffixed with `-win32` to force the legacy backend. #[cfg(debug_assertions)] #[arg(long)] preview: Option, diff --git a/installer/src/ui/license_markdown.rs b/installer/src/ui/license_markdown.rs new file mode 100644 index 0000000..b882ded --- /dev/null +++ b/installer/src/ui/license_markdown.rs @@ -0,0 +1,464 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Gaëtan Dezeiraud, Louis Pinaud + +//! Markdown parsing shared by the WinUI and Win32 license views. +//! +//! The payload remains a plain UTF-8 string for backward compatibility. Both +//! frontends parse that string through this module, so `.txt` and `.md` files +//! have exactly the same behavior and there is no format flag to keep in sync. + +use pulldown_cmark::{Event, HeadingLevel, Parser, Tag, TagEnd}; +use std::fmt::Write; + +pub(crate) const BUILT_IN_LICENSE: &str = "END USER LICENSE AGREEMENT - SAMPLE\r\n\r\n\ +Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod \ +tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, \ +quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo \ +consequat.\r\n\r\n\ +Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore \ +eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, \ +sunt in culpa qui officia deserunt mollit anim id est laborum.\r\n\r\n\ +Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium \ +doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore \ +veritatis et quasi architecto beatae vitae dicta sunt explicabo.\r\n\r\n\ +Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, \ +sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.\r\n\r\n\ +At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis \ +praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias \ +excepturi sint occaecati cupiditate non provident, similique sunt in culpa \ +qui officia deserunt mollitia animi, id est laborum et dolorum fuga.\r\n\r\n\ +By clicking 'I accept' you agree to be bound by the terms above."; + +#[derive(Debug, Default, Eq, PartialEq)] +pub(crate) struct Document { + pub blocks: Vec, +} + +#[derive(Debug, Eq, PartialEq)] +pub(crate) struct Block { + pub kind: BlockKind, + pub inlines: Vec, + pub quote_depth: usize, + pub list_depth: usize, + pub list_prefix: Option, +} + +impl Block { + pub fn heading_level(&self) -> Option { + match self.kind { + BlockKind::Heading(level) => Some(level), + _ => None, + } + } + + pub fn prefix(&self) -> String { + format!( + "{}{}", + "│ ".repeat(self.quote_depth), + self.list_prefix.as_deref().unwrap_or("") + ) + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum BlockKind { + Paragraph, + Heading(u8), + Code, + Rule, +} + +#[derive(Debug, Eq, PartialEq)] +pub(crate) struct Inline { + pub text: String, + pub bold: bool, + pub italic: bool, + pub code: bool, + pub link: Option, +} + +#[derive(Default)] +struct Style { + bold: usize, + italic: usize, + code: bool, + link: Option, +} + +struct ListState { + next: Option, +} + +#[derive(Default)] +struct Builder { + document: Document, + current: Option, + style: Style, + quote_depth: usize, + lists: Vec, + pending_list_prefix: Option, + image_depth: usize, +} + +impl Builder { + fn start_block(&mut self, kind: BlockKind) { + self.finish_block(); + self.current = Some(Block { + kind, + inlines: Vec::new(), + quote_depth: self.quote_depth, + list_depth: self.lists.len(), + list_prefix: self.pending_list_prefix.take(), + }); + } + + fn ensure_block(&mut self) -> &mut Block { + if self.current.is_none() { + self.start_block(BlockKind::Paragraph); + } + self.current.as_mut().expect("block was just created") + } + + fn finish_block(&mut self) { + let Some(block) = self.current.take() else { + return; + }; + if !block.inlines.is_empty() || matches!(block.kind, BlockKind::Rule) { + self.document.blocks.push(block); + } + } + + fn text(&mut self, text: &str) { + if self.image_depth > 0 || text.is_empty() { + return; + } + let inline = Inline { + text: text.to_string(), + bold: self.style.bold > 0, + italic: self.style.italic > 0, + code: self.style.code, + link: self.style.link.clone(), + }; + let block = self.ensure_block(); + if let Some(previous) = block.inlines.last_mut() + && previous.bold == inline.bold + && previous.italic == inline.italic + && previous.code == inline.code + && previous.link == inline.link + { + previous.text.push_str(&inline.text); + } else { + block.inlines.push(inline); + } + } + + fn line_break(&mut self) { + self.text("\n"); + } + + fn start_item(&mut self) { + self.finish_block(); + self.pending_list_prefix = self.lists.last_mut().map(|list| match &mut list.next { + Some(next) => { + let prefix = format!("{next}. "); + *next += 1; + prefix + } + None => "• ".to_string(), + }); + } + + fn rule(&mut self) { + self.start_block(BlockKind::Rule); + self.text("────────────────────────"); + self.finish_block(); + } +} + +pub(crate) fn parse(source: &str) -> Document { + let mut builder = Builder::default(); + + for event in Parser::new(source) { + match event { + Event::Start(tag) => start_tag(&mut builder, tag), + Event::End(tag) => end_tag(&mut builder, tag), + Event::Text(text) | Event::Html(text) | Event::InlineHtml(text) => builder.text(&text), + Event::Code(text) => { + let was_code = std::mem::replace(&mut builder.style.code, true); + builder.text(&text); + builder.style.code = was_code; + } + Event::SoftBreak | Event::HardBreak => builder.line_break(), + Event::Rule => builder.rule(), + _ => {} + } + } + builder.finish_block(); + builder.document +} + +fn start_tag(builder: &mut Builder, tag: Tag<'_>) { + match tag { + Tag::Paragraph => builder.start_block(BlockKind::Paragraph), + Tag::Heading { level, .. } => builder.start_block(BlockKind::Heading(heading(level))), + Tag::BlockQuote(_) => { + builder.finish_block(); + builder.quote_depth += 1; + } + Tag::CodeBlock(_) => { + builder.start_block(BlockKind::Code); + builder.style.code = true; + } + Tag::List(first) => builder.lists.push(ListState { next: first }), + Tag::Item => builder.start_item(), + Tag::Emphasis => builder.style.italic += 1, + Tag::Strong => builder.style.bold += 1, + Tag::Link { dest_url, .. } => { + builder.style.link = safe_link(&dest_url).map(str::to_owned); + } + Tag::Image { .. } => builder.image_depth += 1, + _ => {} + } +} + +fn end_tag(builder: &mut Builder, tag: TagEnd) { + match tag { + TagEnd::Paragraph | TagEnd::Heading(_) => builder.finish_block(), + TagEnd::BlockQuote(_) => { + builder.finish_block(); + builder.quote_depth = builder.quote_depth.saturating_sub(1); + } + TagEnd::CodeBlock => { + builder.style.code = false; + builder.finish_block(); + } + TagEnd::List(_) => { + builder.finish_block(); + builder.lists.pop(); + } + TagEnd::Item => builder.finish_block(), + TagEnd::Emphasis => builder.style.italic = builder.style.italic.saturating_sub(1), + TagEnd::Strong => builder.style.bold = builder.style.bold.saturating_sub(1), + TagEnd::Link => builder.style.link = None, + TagEnd::Image => builder.image_depth = builder.image_depth.saturating_sub(1), + _ => {} + } +} + +fn heading(level: HeadingLevel) -> u8 { + match level { + HeadingLevel::H1 => 1, + HeadingLevel::H2 => 2, + HeadingLevel::H3 => 3, + HeadingLevel::H4 => 4, + HeadingLevel::H5 => 5, + HeadingLevel::H6 => 6, + } +} + +fn safe_link(uri: &str) -> Option<&str> { + let safe_scheme = ["https://", "http://", "mailto:"].iter().any(|prefix| { + uri.len() > prefix.len() + && uri + .get(..prefix.len()) + .is_some_and(|scheme| scheme.eq_ignore_ascii_case(prefix)) + }); + (safe_scheme && !uri.chars().any(|c| c.is_control() || c == '"')).then_some(uri) +} + +#[derive(Debug, Eq, PartialEq)] +pub(crate) struct LinkRange { + pub start: i32, + pub end: i32, + pub uri: String, +} + +/// Convert the shared document to Rich Text Format for the native Win32 +/// RichEdit control. Formatting is deliberately generated from the parsed +/// model rather than from the source extension. +pub(crate) fn to_rtf(document: &Document) -> (String, Vec) { + let mut out = String::from( + "{\\rtf1\\ansi\\ansicpg1252\\uc1\\deff0{\\fonttbl{\\f0 Segoe UI;}}\ + {\\colortbl;\\red0\\green102\\blue204;}\\viewkind4 ", + ); + let mut links = Vec::new(); + let mut position = 0i32; + + for (block_index, block) in document.blocks.iter().enumerate() { + // Six points after each paragraph mirrors the 8-DIP spacing used by + // the WinUI block stack at the default 96 DPI. + out.push_str("{\\pard\\sa120"); + // RTF indentation is expressed in twips: 18 DIP = 270 twips at 96 DPI. + let indent = block.list_depth.saturating_sub(1) * 270; + if indent > 0 { + let _ = write!(out, "\\li{indent}"); + } + // The Win32 chrome uses the standard 9-point Segoe UI dialog font. + // Keep the Markdown body on that baseline and retain the WinUI heading + // ratios above it. RTF sizes are half-points. + let size = match block.kind { + BlockKind::Heading(1) => 31, + BlockKind::Heading(2) => 27, + BlockKind::Heading(3) => 23, + BlockKind::Heading(4) => 21, + BlockKind::Heading(5 | 6) => 18, + BlockKind::Code => 17, + BlockKind::Rule => 13, + BlockKind::Paragraph => 18, + BlockKind::Heading(_) => 18, + }; + let _ = write!(out, "\\fs{size} "); + if block.heading_level().is_some() { + out.push_str("\\b "); + } + if block.quote_depth > 0 || matches!(block.kind, BlockKind::Code) { + out.push_str("\\i "); + } + + let prefix = block.prefix(); + push_rtf_text(&mut out, &prefix); + position += utf16_len(&prefix); + + for inline in &block.inlines { + out.push('{'); + if inline.bold { + out.push_str("\\b "); + } + if inline.italic || inline.code { + out.push_str("\\i "); + } + let link_start = inline.link.is_some().then_some(position); + if link_start.is_some() { + // Reactor's native WinUI hyperlink surface does not expose + // nested run styling, so links intentionally reset emphasis + // here as well to keep both frontends visually equivalent. + out.push_str("\\b0\\i0\\ul\\cf1 "); + } + push_rtf_text(&mut out, &inline.text); + position += utf16_len(&inline.text); + if let (Some(start), Some(uri)) = (link_start, &inline.link) { + links.push(LinkRange { + start, + end: position, + uri: uri.clone(), + }); + } + out.push('}'); + } + out.push_str("\\par}"); + if block_index + 1 < document.blocks.len() { + position += 1; + } + } + out.push('}'); + (out, links) +} + +fn utf16_len(text: &str) -> i32 { + text.encode_utf16().count() as i32 +} + +fn push_rtf_text(out: &mut String, text: &str) { + for unit in text.encode_utf16() { + match unit { + 0x7b | 0x7d | 0x5c => { + out.push('\\'); + out.push(char::from_u32(unit as u32).expect("ASCII punctuation")); + } + 0x0a => out.push_str("\\line "), + 0x20..=0x7e => out.push(char::from_u32(unit as u32).expect("ASCII character")), + _ => { + let _ = write!(out, "\\u{}?", unit as i16); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plain_text_keeps_line_breaks() { + let document = parse("first line\r\nsecond line"); + assert_eq!(document.blocks.len(), 1); + assert_eq!( + document.blocks[0].inlines[0].text, + "first line\nsecond line" + ); + } + + #[test] + fn parses_inline_formatting_and_safe_links() { + let document = parse("**bold** *italic* [`site`](https://example.com) [bad](file:///c:/x)"); + let inlines = &document.blocks[0].inlines; + assert!(inlines.iter().any(|i| i.text == "bold" && i.bold)); + assert!(inlines.iter().any(|i| i.text == "italic" && i.italic)); + assert!(inlines.iter().any(|i| { + i.text == "site" && i.code && i.link.as_deref() == Some("https://example.com") + })); + assert!( + inlines + .iter() + .any(|i| i.text.contains("bad") && i.link.is_none()) + ); + assert_eq!( + safe_link("HTTPS://example.com"), + Some("HTTPS://example.com") + ); + assert_eq!(safe_link("https://"), None); + assert_eq!(safe_link("javascript:alert(1)"), None); + } + + #[test] + fn parses_headings_quotes_and_nested_lists() { + let document = parse("# Terms\n\n> Quote\n\n1. One\n - Nested\n2. Two"); + assert_eq!(document.blocks[0].kind, BlockKind::Heading(1)); + assert_eq!(document.blocks[1].quote_depth, 1); + assert_eq!(document.blocks[2].list_prefix.as_deref(), Some("1. ")); + assert_eq!(document.blocks[3].list_depth, 2); + assert_eq!(document.blocks[3].list_prefix.as_deref(), Some("• ")); + assert_eq!(document.blocks[4].list_prefix.as_deref(), Some("2. ")); + } + + #[test] + fn ignores_images_but_not_surrounding_text() { + let document = parse("Before ![secret alt](https://example.com/a.png) after"); + let text: String = document.blocks[0] + .inlines + .iter() + .map(|inline| inline.text.as_str()) + .collect(); + assert_eq!(text, "Before after"); + } + + #[test] + fn tables_remain_plain_text() { + let document = parse("A | B\n--|--\n1 | 2"); + let text: String = document.blocks[0] + .inlines + .iter() + .map(|inline| inline.text.as_str()) + .collect(); + assert_eq!(text, "A | B\n--|--\n1 | 2"); + } + + #[test] + fn rtf_contains_block_and_inline_formatting() { + let (rtf, links) = to_rtf(&parse( + "# Terms\n\n> Read **carefully** and visit [site](https://example.com).", + )); + assert!(rtf.starts_with("{\\rtf1")); + assert!(rtf.contains("\\fs31")); + assert!(rtf.contains("\\b carefully")); + assert!(rtf.contains("\\ul\\cf1 site")); + assert_eq!(links.len(), 1); + assert_eq!(links[0].uri, "https://example.com"); + } + + #[test] + fn link_ranges_use_rich_edit_utf16_offsets() { + let (_, links) = to_rtf(&parse("😀 [site](https://example.com)")); + assert_eq!((links[0].start, links[0].end), (3, 7)); + } +} diff --git a/installer/src/ui/mod.rs b/installer/src/ui/mod.rs index 4e7548a..78ffea1 100644 --- a/installer/src/ui/mod.rs +++ b/installer/src/ui/mod.rs @@ -3,6 +3,7 @@ mod dest; mod helpers; +mod license_markdown; pub mod minimal; pub mod win32; pub mod winui; @@ -88,6 +89,15 @@ pub(crate) const SAMPLE_FILE: &str = "resources/app/node_modules/@company/design /// Dev-only: render one view with sample data. #[cfg(debug_assertions)] pub fn preview(view: &str, translator: common::i18n::Translator) -> Result<()> { + // Let developers compare both native renderers on machines where WinUI is + // available without changing the production backend selection. + if let Some(view) = view.strip_suffix("-win32") { + return if view == "minimal" { + minimal::preview(translator) + } else { + win32::preview(view, translator) + }; + } if winui::available() { winui::preview(view, translator)?; return Ok(()); @@ -254,7 +264,28 @@ pub(crate) fn sample_payload(view: &str) -> InstallerPayload { default_features: Vec::new(), feature_mode: Default::default(), }, - license_text: None, + license_text: view.starts_with("license").then(|| { + "# Terms and Conditions\n\n\ + ## Markdown rendering demonstration\n\n\ + This sample agreement contains **bold text**, *italic text* and `inline code`. \ + Visit the [project website](https://example.com) for a clickable link example.\n\n\ + > By continuing, you confirm that you have read this quotation.\n\ + > It can span multiple lines.\n\n\ + ### Your obligations\n\n\ + 1. Read these terms and conditions.\n\ + 2. Follow these rules:\n \ + - use the software responsibly;\n \ + - keep a backup of your data.\n\ + 3. Accept the terms or close this window.\n\n\ + ---\n\n\ + #### Additional information\n\n\ + - `.txt` and `.md` files use exactly the same rendering path.\n\ + - Images are ignored and tables remain plain text.\n\n\ + ##### Small level-five heading\n\n\ + ###### Small level-six heading\n\n\ + End of the sample license." + .to_string() + }), license_texts: Default::default(), associations: Vec::new(), shortcuts: Vec::new(), diff --git a/installer/src/ui/win32/handlers.rs b/installer/src/ui/win32/handlers.rs index f6c275a..7b29517 100644 --- a/installer/src/ui/win32/handlers.rs +++ b/installer/src/ui/win32/handlers.rs @@ -22,11 +22,15 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::thread; use windows::Win32::Foundation::{HWND, LPARAM, WPARAM}; -use windows::Win32::UI::Controls::BST_CHECKED; +use windows::Win32::UI::Controls::RichEdit::{EN_LINK, ENLINK}; +use windows::Win32::UI::Controls::{BST_CHECKED, NMHDR}; use windows::Win32::UI::Input::KeyboardAndMouse::EnableWindow; +use windows::Win32::UI::Shell::ShellExecuteW; use windows::Win32::UI::WindowsAndMessaging::{ - GetDlgItem, MB_ICONWARNING, PostMessageW, SW_HIDE, SW_SHOW, SendMessageW, ShowWindow, WM_CLOSE, + GetDlgItem, MB_ICONWARNING, PostMessageW, SW_HIDE, SW_SHOW, SW_SHOWNORMAL, SendMessageW, + ShowWindow, WM_CLOSE, WM_LBUTTONUP, }; +use windows::core::{PCWSTR, w}; fn current_phase() -> Phase { STATE.with(|s| { @@ -37,6 +41,45 @@ fn current_phase() -> Phase { }) } +/// Open a Markdown link clicked in the read-only RichEdit license control. +pub(super) unsafe fn on_notify(hwnd: HWND, lparam: LPARAM) -> bool { + if lparam.0 == 0 { + return false; + } + let header = unsafe { &*(lparam.0 as *const NMHDR) }; + if header.idFrom != super::ID_LICENSE_EDIT || header.code != EN_LINK { + return false; + } + let event = unsafe { std::ptr::read_unaligned(lparam.0 as *const ENLINK) }; + if event.msg != WM_LBUTTONUP { + return true; + } + let uri = STATE.with(|state| { + state.borrow().as_ref().and_then(|state| { + state + .borrow() + .license_links + .iter() + .find(|link| event.chrg.cpMin >= link.start && event.chrg.cpMax <= link.end) + .map(|link| link.uri.clone()) + }) + }); + if let Some(uri) = uri { + let uri_wide = common::utils::wide(&uri); + unsafe { + ShellExecuteW( + Some(hwnd), + w!("open"), + PCWSTR(uri_wide.as_ptr()), + PCWSTR::null(), + PCWSTR::null(), + SW_SHOWNORMAL, + ); + } + } + true +} + /// Stores the result of a background plugin-step query until the UI thread picks /// it up from `WM_APP_PLUGIN_STEP`. static QUERIED_STEP: Mutex> = Mutex::new(None); diff --git a/installer/src/ui/win32/mod.rs b/installer/src/ui/win32/mod.rs index ddf6f9c..bb8bef4 100644 --- a/installer/src/ui/win32/mod.rs +++ b/installer/src/ui/win32/mod.rs @@ -14,6 +14,7 @@ mod views; use crate::payload::LoadedPayload; use crate::ui::helpers; +use crate::ui::license_markdown::LinkRange; use anyhow::Result; #[cfg(debug_assertions)] use common::model::choice_option::ChoiceOption; @@ -118,6 +119,8 @@ pub(super) struct UiState { pub card_brush: HBRUSH, pub error_brush: HBRUSH, pub license_accepted: bool, + /// Clickable Markdown links and their RichEdit character ranges. + pub license_links: Vec, pub chosen_path: Option, /// Runtime-built controls for plugin-contributed pages (empty with no UI /// plugins). See [`plugin_pages`]. @@ -306,6 +309,9 @@ unsafe fn create_window( ) -> Result { unsafe { helpers::init_progress_class(); + // RICHEDIT50W is provided by Msftedit.dll and is used for the single + // Markdown-rendered license path (for both `.txt` and `.md` sources). + let _ = windows::Win32::System::LibraryLoader::LoadLibraryW(w!("Msftedit.dll")); let font_normal = helpers::create_font("Segoe UI", 16, FW_NORMAL.0 as i32); let font_bold = helpers::create_font("Segoe UI", 16, FW_SEMIBOLD.0 as i32); @@ -338,6 +344,7 @@ unsafe fn create_window( card_brush, error_brush, license_accepted: false, + license_links: Vec::new(), chosen_path: Some(default_path.to_path_buf()), plugin_fields: Vec::new(), header_text: String::new(), @@ -802,6 +809,12 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: } LRESULT(DefWindowProcW(hwnd, msg, wparam, lparam).0) }, + WM_NOTIFY => unsafe { + if handlers::on_notify(hwnd, lparam) { + return LRESULT(0); + } + LRESULT(DefWindowProcW(hwnd, msg, wparam, lparam).0) + }, WM_COMMAND => unsafe { let id = wparam.0 & 0xFFFF; let code = ((wparam.0 >> 16) & 0xFFFF) as u32; diff --git a/installer/src/ui/win32/views.rs b/installer/src/ui/win32/views.rs index f227348..eb647c3 100644 --- a/installer/src/ui/win32/views.rs +++ b/installer/src/ui/win32/views.rs @@ -14,11 +14,17 @@ use crate::ui::helpers::{ self, CHECKBOX, ControlRect, DEFAULT_BUTTON, PUSH_BUTTON, child, child_ex, move_controls, set_static_icon, }; +use crate::ui::license_markdown::{self, BUILT_IN_LICENSE, LinkRange}; use common::model::installer_payload::InstallerPayload; use common::model::payload_kind::PayloadKind; +use std::ffi::CString; use std::path::Path; -use windows::Win32::Foundation::HWND; +use windows::Win32::Foundation::{HWND, LPARAM, WPARAM}; use windows::Win32::UI::Controls::PROGRESS_CLASSW; +use windows::Win32::UI::Controls::RichEdit::{ + CFE_LINK, CFM_LINK, CHARFORMAT2W, CHARRANGE, EM_EXSETSEL, EM_SETCHARFORMAT, EM_SETEVENTMASK, + EM_SETTEXTEX, ENM_LINK, MSFTEDIT_CLASS, SCF_SELECTION, SETTEXTEX, ST_DEFAULT, +}; use windows::Win32::UI::WindowsAndMessaging::*; use windows::core::w; @@ -35,25 +41,6 @@ const WS_VSCROLL: WINDOW_STYLE = WINDOW_STYLE(0x0020_0000); const READ_ONLY_TEXT: WINDOW_STYLE = WINDOW_STYLE(WS_CLIPSIBLINGS.0 | WS_VSCROLL.0 | ES_MULTILINE | ES_READONLY | ES_LEFT); -const LOREM: &str = "END USER LICENSE AGREEMENT - SAMPLE\r\n\r\n\ -Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod \ -tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, \ -quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo \ -consequat.\r\n\r\n\ -Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore \ -eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, \ -sunt in culpa qui officia deserunt mollit anim id est laborum.\r\n\r\n\ -Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium \ -doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore \ -veritatis et quasi architecto beatae vitae dicta sunt explicabo.\r\n\r\n\ -Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, \ -sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.\r\n\r\n\ -At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis \ -praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias \ -excepturi sint occaecati cupiditate non provident, similique sunt in culpa \ -qui officia deserunt mollitia animi, id est laborum et dolorum fuga.\r\n\r\n\ -By clicking 'I accept' you agree to be bound by the terms above."; - pub(super) unsafe fn build_controls(hwnd: HWND, payload: &InstallerPayload, default_path: &Path) { unsafe { build_banner_header(hwnd, payload); @@ -109,17 +96,23 @@ unsafe fn build_banner_header(hwnd: HWND, payload: &InstallerPayload) { /// License view: read-only EULA edit + "I accept" checkbox. unsafe fn build_license(hwnd: HWND, payload: &InstallerPayload) { - let license = payload.license_for(tr().lang()).unwrap_or(LOREM); + let license = payload.license_for(tr().lang()).unwrap_or(BUILT_IN_LICENSE); let accept = tr().get("install.license_accept"); unsafe { - child_ex( + let edit = child_ex( hwnd, WS_EX_CLIENTEDGE, - w!("EDIT"), - license, + MSFTEDIT_CLASS, + "", READ_ONLY_TEXT, ID_LICENSE_EDIT, ); + let links = set_license_markdown(edit, license); + STATE.with(|state| { + if let Some(state) = state.borrow().as_ref() { + state.borrow_mut().license_links = links; + } + }); child( hwnd, w!("BUTTON"), @@ -130,6 +123,63 @@ unsafe fn build_license(hwnd: HWND, payload: &InstallerPayload) { } } +unsafe fn set_license_markdown(edit: HWND, source: &str) -> Vec { + unsafe { + let document = license_markdown::parse(source); + let (rtf, links) = license_markdown::to_rtf(&document); + let rtf = CString::new(rtf).expect("the RTF encoder escapes NUL characters"); + let options = SETTEXTEX { + flags: ST_DEFAULT, + codepage: 65001, + }; + SendMessageW( + edit, + EM_SETTEXTEX, + Some(WPARAM((&options as *const SETTEXTEX) as usize)), + Some(LPARAM(rtf.as_ptr() as isize)), + ); + + // CFE_LINK gives friendly-name links their native cursor and EN_LINK + // notifications. Their target URIs remain in `links`, not in the RTF. + let mut link_format = CHARFORMAT2W::default(); + link_format.Base.cbSize = std::mem::size_of::() as u32; + link_format.Base.dwMask = CFM_LINK; + link_format.Base.dwEffects = CFE_LINK; + for link in &links { + select_rich_text(edit, link.start, link.end); + SendMessageW( + edit, + EM_SETCHARFORMAT, + Some(WPARAM(SCF_SELECTION as usize)), + Some(LPARAM((&link_format as *const CHARFORMAT2W) as isize)), + ); + } + select_rich_text(edit, 0, 0); + SendMessageW( + edit, + EM_SETEVENTMASK, + Some(WPARAM(0)), + Some(LPARAM(ENM_LINK as isize)), + ); + links + } +} + +unsafe fn select_rich_text(edit: HWND, start: i32, end: i32) { + let range = CHARRANGE { + cpMin: start, + cpMax: end, + }; + unsafe { + SendMessageW( + edit, + EM_EXSETSEL, + Some(WPARAM(0)), + Some(LPARAM((&range as *const CHARRANGE) as isize)), + ); + } +} + /// Choose view: destination label + path edit + Browse button, and the /// non-empty-folder warning below them, hidden until the chosen folder is found /// to already contain files. @@ -346,7 +396,6 @@ pub(super) unsafe fn apply_fonts(hwnd: HWND) { ID_STATUS_FILE, ID_ERROR_BOX, ID_CLOSE_BTN, - ID_LICENSE_EDIT, ID_ACCEPT_CHK, ID_NEXT_BTN, ID_BACK_BTN, diff --git a/installer/src/ui/winui/wizard.rs b/installer/src/ui/winui/wizard.rs index 54c8b52..bfd9a0e 100644 --- a/installer/src/ui/winui/wizard.rs +++ b/installer/src/ui/winui/wizard.rs @@ -14,6 +14,7 @@ use super::model::{ }; use super::plugin_page; use super::worker::{self, Feed}; +use crate::ui::license_markdown::{self, BUILT_IN_LICENSE, Block, BlockKind}; use crate::ui::wizard_engine::Step; use common::model::launch_option::LaunchOption; use common::model::payload_kind::PayloadKind; @@ -66,26 +67,6 @@ impl WizardApp { } } -/// Placeholder EULA, matching the Win32 wizard's so both previews agree. -const LOREM: &str = "END USER LICENSE AGREEMENT - SAMPLE\r\n\r\n\ -Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod \ -tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, \ -quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo \ -consequat.\r\n\r\n\ -Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore \ -eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, \ -sunt in culpa qui officia deserunt mollit anim id est laborum.\r\n\r\n\ -Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium \ -doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore \ -veritatis et quasi architecto beatae vitae dicta sunt explicabo.\r\n\r\n\ -Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, \ -sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.\r\n\r\n\ -At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis \ -praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias \ -excepturi sint occaecati cupiditate non provident, similique sunt in culpa \ -qui officia deserunt mollitia animi, id est laborum et dolorum fuga.\r\n\r\n\ -By clicking 'I accept' you agree to be bound by the terms above."; - /// A unit handler that clones the model, mutates it, and commits. fn on( model: &Model, @@ -279,14 +260,13 @@ fn content(model: &Model, set: &SetState) -> Element { /// viewer sizes to its content and pushes the checkbox off-window. fn license_view(model: &Model, set: &SetState) -> Element { let text = with_payload(|p| p.license_for(tr().lang()).map(str::to_owned)) - .unwrap_or_else(|| LOREM.to_string()); + .unwrap_or_else(|| BUILT_IN_LICENSE.to_string()); let accepted = model.license_accepted; grid(vec![ Element::from(card( scroll_viewer( - text_block(text) - .wrap() - .selectable() + vstack(markdown_blocks(&text)) + .spacing(8.0) .padding(Thickness::uniform(16.0)), ) .vertical_scroll_bar_visibility(ScrollBarVisibility::Auto), @@ -304,6 +284,73 @@ fn license_view(model: &Model, set: &SetState) -> Element { .into() } +/// Render the shared Markdown model with native WinUI rich-text controls. +/// Keeping one control per block lets headings use their own size while the +/// surrounding StackPanel keeps paragraphs, lists and quotes in document order. +fn markdown_blocks(source: &str) -> Vec { + license_markdown::parse(source) + .blocks + .into_iter() + .map(markdown_block) + .collect() +} + +fn markdown_block(block: Block) -> Element { + let heading = block.heading_level(); + let mut inlines = Vec::new(); + let prefix = block.prefix(); + if !prefix.is_empty() { + inlines.push(RichTextInline::Run(RichTextRun { + text: prefix, + is_bold: heading.is_some(), + is_italic: block.quote_depth > 0, + })); + } + for inline in block.inlines { + for (index, part) in inline.text.split('\n').enumerate() { + if index > 0 { + inlines.push(RichTextInline::LineBreak); + } + if part.is_empty() { + continue; + } + if let Some(uri) = &inline.link { + inlines.push(RichTextInline::Hyperlink(RichTextHyperlink { + text: part.to_string(), + uri: uri.clone(), + })); + } else { + inlines.push(RichTextInline::Run(RichTextRun { + text: part.to_string(), + is_bold: inline.bold || heading.is_some(), + // Reactor currently exposes bold/italic on rich runs. Code + // uses italic as the shared native fallback in both UIs. + is_italic: inline.italic || inline.code || block.quote_depth > 0, + })); + } + } + } + let font_size = match heading { + Some(1) => 24.0, + Some(2) => 21.0, + Some(3) => 18.0, + Some(4) => 16.0, + Some(5 | 6) => 14.0, + _ if matches!(block.kind, BlockKind::Code) => 13.0, + _ if matches!(block.kind, BlockKind::Rule) => 10.0, + _ => 14.0, + }; + let left = block.list_depth.saturating_sub(1) as f64 * 18.0; + Element::from( + RichTextBlock::new() + .paragraphs(RichText::single_paragraph(inlines)) + .font_size(font_size) + .text_wrapping(TextWrapping::Wrap) + .is_text_selection_enabled(true) + .margin(Thickness::new(left, 0.0, 0.0, 0.0)), + ) +} + fn choose_view(model: &Model, set: &SetState) -> Element { let picker = { let model = model.clone(); diff --git a/installer_builder/src/args.rs b/installer_builder/src/args.rs index c7d5478..f39b918 100644 --- a/installer_builder/src/args.rs +++ b/installer_builder/src/args.rs @@ -86,12 +86,12 @@ pub struct PackCli { #[arg(short, long)] pub exe: Option, - /// Optional path to a license text file shown on the License page. + /// Optional path to a UTF-8 plain-text or CommonMark license file. #[arg(long)] pub license: Option, /// License translation for one UI language, format `LANG=FILE` (e.g. - /// `fr=EULA-fr.txt`). Repeatable. Shown instead of `--license` when the + /// `fr=EULA-fr.md`). Repeatable. Shown instead of `--license` when the /// installer runs in that language. Overrides the same language from the /// config file's `licenses` table. #[arg(long = "license-lang", value_name = "LANG=FILE")]