Browse / github.com/storytold/wordcraft / patch
M14: experimental Windows 7 x64 portable build
M14: experimental Windows 7 x64 portable build ## What this changes Ports VectorCraft's experimental, unsupported Windows 7 SP1 x64 build (`docs/windows7.md`): - New default features `wgpu` and `accessibility` on the `wordcraft` app; a `windows7` feature (`eframe/glow`) with compile-time guards requiring the `x86_64-win7-windows-msvc` target. `on_exit` takes the GL context under `windows7`. `Cargo.lock` gains eframe's optional `glow` dependency. - On the win7 target: OpenGL, no AccessKit adapter, no WinRT animation or home-region lookup, Control Panel › Default Programs for the default-app button, and printing through PowerShell's W
- Status
- open
- Score
- 0.00
- Adopters
- 0 other operators
- Author
- fragtion (imported from pull request #4599, open)
- Base
436d444ef0ee35c2e2b9fb44f87aa7d08d72641f- Size
- +1052 −37 in 20 files
- Review
- pending
- Shared
- 2026-10-28
- Id
73dd72d2930a6db355aea4ad
How it went
No other operator has reported using it yet.
Diff
raw · .github/workflows/windows7.yml Cargo.lock NOTICE README.md ROADMAP.md apps/wordcraft/Cargo.toml apps/wordcraft/src/animations.rs apps/wordcraft/src/default_apps.rs apps/wordcraft/src/main.rs apps/wordcraft/src/print.rs apps/wordcraft/src/print/windows7.rs apps/wordcraft/src/region.rs docs/windows7.md packaging/windows/windows7.ps1 vendor/windows-link/Cargo.toml vendor/windows-link/WORDCRAFT-PATCH.md vendor/windows-link/license-apache-2.0 vendor/windows-link/license-mit vendor/windows-link/readme.md vendor/windows-link/src/lib.rs
new file mode 100644@@ -0,0 +1,63 @@+# Experimental, unsupported Windows 7 SP1 x64 portable build (docs/windows7.md), ported from+# VectorCraft's. It runs by hand and weekly and for changes to the compatibility path; the weekly run+# shows when a dependency update starts importing a post-Windows-7 API.+# packaging/windows/windows7.ps1 does the work: it is the only build that uses the patched+# vendor/windows-link. A modern Windows runner proves compilation and host smoke tests only: run the+# checklist in docs/windows7.md on actual Windows 7 before claiming support.+name: Windows 7 x64 compatibility++on:+ pull_request:+ paths:+ - "Cargo.toml"+ - "Cargo.lock"+ - "apps/wordcraft/Cargo.toml"+ - "apps/wordcraft/src/main.rs"+ - "apps/wordcraft/src/animations.rs"+ - "apps/wordcraft/src/default_apps.rs"+ - "apps/wordcraft/src/region.rs"+ - "apps/wordcraft/src/print.rs"+ - "apps/wordcraft/src/print/**"+ - "apps/wordcraft-cli/Cargo.toml"+ - "vendor/windows-link/**"+ - "packaging/windows/windows7.ps1"+ - ".github/workflows/windows7.yml"+ schedule:+ - cron: "37 5 * * 1" # weekly+ workflow_dispatch:++concurrency:+ group: windows7-${{ github.ref }}+ cancel-in-progress: true++permissions:+ contents: read++env:+ CARGO_TERM_COLOR: always+ CARGO_INCREMENTAL: 0++jobs:+ build:+ runs-on: windows-2022+ timeout-minutes: 120+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ - uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 # v1.13.0+ with:+ arch: x64+ - uses: dtolnay/rust-toolchain@e2a55d2ffb04f378e9626c28d38b36d230d1e12f # master+ with:+ toolchain: nightly-2026-10-01+ components: rust-src+ - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3+ with:+ key: windows7-x64+ - name: Build, check and test the portable package+ shell: pwsh+ run: ./packaging/windows/windows7.ps1 -Test+ - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2+ with:+ name: wordcraft-windows7-x64-portable+ path: dist/release/wordcraft-windows7-x64-portable.zip+ if-no-files-found: error@@ -1382,6 +1382,7 @@ dependencies = [ "egui-wgpu", "egui-winit", "egui_glow",+ "glow", "glutin", "glutin-winit", "image",@@ -108,6 +108,11 @@ cleanup. WordCraft enables only writing; PDF import and its image decoders are n No Microsoft, Adobe, Avid or Autodesk icons, images, templates or artwork are included. +The experimental Windows 7 build (packaging/windows/windows7.ps1) compiles a modified copy of the+windows-link crate 0.2.1 (vendor/windows-link; Microsoft, MIT OR Apache-2.0) that binds CoTaskMemFree+through ole32.dll. Its license texts are in vendor/windows-link and ship in that build's ZIP; every+other build uses the unmodified crate from crates.io.+ Bundled egui font icons The canonical egui0.37 dependency includes egui-icons.ttf (a small subset of emoji-icon-font)@@ -232,6 +232,8 @@ just-me installer needs none: it installs into `%LOCALAPPDATA%\Programs\WordCraf account only. Choose one: installing both gives two WordCraft entries in Settings › Apps and two in the Start menu. Installers and executables are code-signed. +For the experimental, unsupported 64-bit Windows 7 build, see [Windows 7 instructions](docs/windows7.md).+ **If the app doesn't open on Windows:** the desktop app initializes only DirectX 12 by default. Letting wgpu also create an OpenGL instance can crash some graphics drivers (AMD's `atio6axx.dll`) before the window appears, so the app would flash in Task Manager and quit.@@ -4,7 +4,7 @@ **Stage: alpha** · next: beta, ~15 points (60% → 75% ready for real work) and ~150–230 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** trivial (progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: progress log: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: progress log: recovery copies and .json files store pictures as base64, #586 follow-up; previously trivial: progress log: legacy menu keys, #1697; previously trivial: progress log: shape gradients and transparency, #1500; previously trivial: progress log: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: progress log: text above a float's anchor wraps around it, #2048; previously trivial: progress log: File › Recover follows the app theme, #3243; previously trivial: progress log: formatting toolbar with the text context menu, #2959; previously trivial: progress log: caret inside ligatures, #1974; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: progress log: a header-cell picture watermark sits behind the text, #1775; previously trivial: symbols keep their font when the text font changes, #2036; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: Add Font imports every selected font file, #1789); previously trivial (RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: Read Aloud speaks each sentence in its own language, #1843; previously trivial: hint-reliant CJK outlines; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: progress log: Turkish case mapping in AutoCorrect, #1923; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: progress log: Hebrew field results and smart quotes, #1670; previously trivial: Backspace removes a selected table, rows or columns, #1844; previously trivial: progress log: mixed Hebrew/Latin text keeps its order in Word, #1543; previously trivial: progress log: web typing in non-Latin text no longer repeats, #1480; previously trivial: progress log: font family caches bounded and math font lookups follow font changes, #1354; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: progress log: Columns on selected text, #2024; previously trivial: progress log: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: progress log: Indonesian proofing, #498; previously trivial: progress log: DOCX glossary documents (building blocks); previously trivial: progress log: Read Mode keeps the keyboard and shows whole, unobscured columns, #1772); previously trivial: progress log: font list entries of tall-ascent fonts no longer cut off, #2570); previously trivial: progress log: Split Cells and Convert Text to Table dialogs follow the Word check, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout fills the window width, #1876; previously trivial: progress log: Different First Page headers reachable from page 1, #2826; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: progress log: web preferences kept between visits, #2132; previously trivial: progress log: undrawable private-use list bullets show the level's default bullet, #1683; previously trivial: progress log: `w:eastAsianLayout` kept on save; previously trivial: table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; restructured to the craftrules progress-docs standard) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** trivial (progress log: experimental, unsupported Windows 7 build, docs/windows7.md; previously trivial: progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: progress log: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: progress log: recovery copies and .json files store pictures as base64, #586 follow-up; previously trivial: progress log: legacy menu keys, #1697; previously trivial: progress log: shape gradients and transparency, #1500; previously trivial: progress log: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: progress log: text above a float's anchor wraps around it, #2048; previously trivial: progress log: File › Recover follows the app theme, #3243; previously trivial: progress log: formatting toolbar with the text context menu, #2959; previously trivial: progress log: caret inside ligatures, #1974; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: progress log: a header-cell picture watermark sits behind the text, #1775; previously trivial: symbols keep their font when the text font changes, #2036; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: Add Font imports every selected font file, #1789); previously trivial (RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: Read Aloud speaks each sentence in its own language, #1843; previously trivial: hint-reliant CJK outlines; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: progress log: Turkish case mapping in AutoCorrect, #1923; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: progress log: Hebrew field results and smart quotes, #1670; previously trivial: Backspace removes a selected table, rows or columns, #1844; previously trivial: progress log: mixed Hebrew/Latin text keeps its order in Word, #1543; previously trivial: progress log: web typing in non-Latin text no longer repeats, #1480; previously trivial: progress log: font family caches bounded and math font lookups follow font changes, #1354; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: progress log: Columns on selected text, #2024; previously trivial: progress log: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: progress log: Indonesian proofing, #498; previously trivial: progress log: DOCX glossary documents (building blocks); previously trivial: progress log: Read Mode keeps the keyboard and shows whole, unobscured columns, #1772); previously trivial: progress log: font list entries of tall-ascent fonts no longer cut off, #2570); previously trivial: progress log: Split Cells and Convert Text to Table dialogs follow the Word check, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout fills the window width, #1876; previously trivial: progress log: Different First Page headers reachable from page 1, #2826; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: progress log: web preferences kept between visits, #2132; previously trivial: progress log: undrawable private-use list bullets show the level's default bullet, #1683; previously trivial: progress log: `w:eastAsianLayout` kept on save; previously trivial: table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; restructured to the craftrules progress-docs standard) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-18 · **Change:** trivial (English dialects in proofing, #1281; previously trivial: triple borders draw three lines, #1740; previously trivial: progress log: double-clicking a later page's footer no longer scrolls up, #2103; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: progress log: pasted blockquotes are indented paragraphs, #1270; previously trivial: progress log: print-area strings translated in every catalog; previously trivial: progress log: comments readable in the dark theme, #2045; previously trivial: progress log: ODT sections, #1379; previously trivial: progress log: table deletes, Change Case and Unlink Fields respect Track Changes and locked content controls, #1329; previously trivial: progress log: rounded rectangle corners, #1476; previously trivial: progress log: Save As type list, #1399; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; restructured to the craftrules progress-docs standard) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 > **Printing update:** 2026-10-12 · direct desktop printing through craft-print; details below. @@ -140,6 +140,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm ## Progress log +- 2026-10-27: An experimental, unsupported Windows 7 SP1 x64 portable build, ported from VectorCraft's ([`docs/windows7.md`](docs/windows7.md)): the win7 Rust target with a rebuilt standard library, OpenGL instead of wgpu, no AccessKit adapter, printing through the PDF viewer's print verb instead of craft-print's Windows Runtime renderer, and the vendored `windows-link` patch that imports `CoTaskMemFree` from `ole32.dll`. `packaging/windows/windows7.ps1` builds it and checks its imports; a weekly workflow builds it. Not yet run on Windows 7. Readiness estimates unchanged. - 2026-10-22: View › Window › New Window opens a second window on the document (desktop). The windows are titled `Name:1` and `Name:2` and each keeps its own caret, scroll position, zoom and view; edits and Undo are the document's and show in both. Closing one of them asks nothing; the last one asks about unsaved changes, and quitting asks once per document. - 2026-10-22: One native window per open document on the desktop. File › New and Open (from the ribbon, File, shortcuts, the file manager, the command line or the control channel) open the document in a window of its own, focused and placed a step below and right of the last one; opening a file replaces a blank document nobody has used in its own window, and a file that is already open brings its window to the front. Each window keeps its own ribbon tab, File page, dialogs, panes, scroll position and composition. View › Window › Switch Windows lists the windows and brings the chosen one forward. File › Close and a window's close button close that window, asking about unsaved changes first; the last window stays open with no document. Quitting asks about each document with unsaved changes in its own window, and Cancel keeps everything open. The control channel's input and screenshots go to the window focused last. The web app keeps one window. - 2026-10-22: Recovery covers every open document. Each dirty document keeps its own copy, written on the same ten-second cadence whether it is shown or not; closing a document without saving deletes its copy, as saving does, and a clean exit deletes the copies of every document saved or closed since its last copy. File › Recover lists only copies no open document keeps, and Restore opens a copy as another document (or in place of an untouched blank one), so it never replaces work. After a crash with several unsaved documents, the next start lists all of them.@@ -10,6 +10,15 @@ description = "WordCraft desktop app" [lints] workspace = true +[features]+default = ["wgpu", "accessibility"]+wgpu = ["eframe/wgpu"]+accessibility = ["eframe/accesskit"]+# The experimental, unsupported Windows 7 build (docs/windows7.md): OpenGL instead of wgpu, no+# AccessKit adapter. Build with --no-default-features --features windows7 and the win7 Rust target+# (packaging/windows/windows7.ps1).+windows7 = ["eframe/glow"]+ [dependencies] wordcraft-doc = { workspace = true } wordcraft-engine = { workspace = true }@@ -19,7 +28,8 @@ wordcraft-fonts = { workspace = true } wordcraft-ui-egui = { workspace = true } # The control key file's location (shared with the MCP bridge). wordcraft-control-key = { workspace = true }-eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "clipboard", "wayland", "x11", "links"] }+# wgpu and the AccessKit adapter come with the default `wgpu` and `accessibility` features.+eframe = { workspace = true, features = ["default_fonts", "clipboard", "wayland", "x11", "links"] } egui = { workspace = true } serde_json = { workspace = true } log = { workspace = true }@@ -60,7 +70,14 @@ zbus = { version = "5", default-features = false, features = ["async-io", "block wl-clipboard-rs = "0.9" [target.'cfg(target_os = "windows")'.dependencies]+# The clipboard's "Rich Text Format" and the names of its formats (#687, #833), which arboard+# doesn't read. Already in the build through arboard, at this version.+clipboard-win = { version = "5.4", features = ["std"] }++# Not on the Windows 7 build (docs/windows7.md), which has no Windows Runtime or Settings app.+[target.'cfg(all(windows, not(target_vendor = "win7")))'.dependencies] # The upstream default-apps button opens Windows Settings; printing uses craft-print instead.+# Windows 7 opens Control Panel's Default Programs instead (src/default_apps.rs). open = "5" # The system's Animation effects setting (Settings › Accessibility › Visual effects), read through # the Windows Runtime's UISettings: a safe API, where the Win32 call needs unsafe, which our@@ -68,12 +85,13 @@ open = "5" # only the `UI_ViewManagement` bindings, and `System_UserProfile` for the home region new # documents take their paper and units from (#838). windows = { version = "0.62", features = ["UI_ViewManagement", "System_UserProfile"] }-# The clipboard's "Rich Text Format" and the names of its formats (#687, #833), which arboard-# doesn't read. Already in the build through arboard, at this version.-clipboard-win = { version = "5.4", features = ["std"] } -[target.'cfg(not(target_arch = "wasm32"))'.dependencies]+# craft-print draws Windows jobs with Windows.Data.Pdf, a Windows Runtime API: the win7 target+# prints through the PDF viewer instead (src/print/windows7.rs).+[target.'cfg(all(not(target_arch = "wasm32"), not(target_vendor = "win7")))'.dependencies] craft-print = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }++[target.'cfg(not(target_arch = "wasm32"))'.dependencies] rfd = { workspace = true } # Waits for an `rfd::AsyncFileDialog` on a background thread (the dialogs don't block the UI, #94); # rfd itself already depends on it.@@ -2,7 +2,8 @@ //! follows when set to "Use system setting" (`Services::animations_enabled`). //! //! - Windows: Settings › Accessibility › Visual effects › Animation effects, read through the-//! Windows Runtime's `UISettings`.+//! Windows Runtime's `UISettings`. Windows 7 has no Windows Runtime: the Windows 7 build+//! (docs/windows7.md) doesn't ask, and the Options setting decides. //! - macOS: System Settings › Accessibility › Display › Reduce motion, read through `NSWorkspace`. //! - Linux and the BSDs: the desktop's setting, read through the settings portal ([`desktop`]). //!@@ -16,7 +17,7 @@ mod desktop; /// The answer to "does the system have animation effects on?" for the UI: `None` when the system /// doesn't say. `ctx` is asked to redraw when an answer that arrives later changes it. pub fn hook(ctx: &egui::Context) -> Box<dyn Fn() -> Option<bool>> {- #[cfg(any(target_os = "windows", target_os = "macos"))]+ #[cfg(any(all(windows, not(target_vendor = "win7")), target_os = "macos"))] { let _ = ctx; Box::new(remembered(system_enabled, REFRESH))@@ -25,7 +26,7 @@ pub fn hook(ctx: &egui::Context) -> Box<dyn Fn() -> Option<bool>> { { Box::new(desktop::watch(ctx.clone())) }- #[cfg(not(any(target_os = "windows", unix)))]+ #[cfg(not(any(all(windows, not(target_vendor = "win7")), unix)))] { let _ = ctx; Box::new(|| None)@@ -33,11 +34,11 @@ pub fn hook(ctx: &egui::Context) -> Box<dyn Fn() -> Option<bool>> { } /// How long an answer from Windows or macOS is kept before the system is asked again.-#[cfg(any(target_os = "windows", target_os = "macos"))]+#[cfg(any(all(windows, not(target_vendor = "win7")), target_os = "macos"))] const REFRESH: std::time::Duration = std::time::Duration::from_secs(1); /// `read`, asked at most once per `every` and answered from memory in between.-#[cfg(any(target_os = "windows", target_os = "macos", test))]+#[cfg(any(all(windows, not(target_vendor = "win7")), target_os = "macos", test))] fn remembered(read: impl Fn() -> Option<bool>, every: std::time::Duration) -> impl Fn() -> Option<bool> { let last = std::cell::Cell::new(None::<(std::time::Instant, Option<bool>)>); move || {@@ -53,7 +54,7 @@ fn remembered(read: impl Fn() -> Option<bool>, every: std::time::Duration) -> im } /// Whether Windows has animation effects on; `None` when it can't be asked.-#[cfg(target_os = "windows")]+#[cfg(all(windows, not(target_vendor = "win7")))] fn system_enabled() -> Option<bool> { windows::UI::ViewManagement::UISettings::new() .and_then(|settings| settings.AnimationsEnabled())@@ -85,12 +85,26 @@ mod windows { /// Settings › Default apps, on the page of the app registered as `WordCraft` under /// `HKLM\Software\RegisteredApplications` (the MSI writes it).+ #[cfg(not(target_vendor = "win7"))] const SETTINGS_URI: &str = "ms-settings:defaultapps?registeredAppMachine=WordCraft"; + #[cfg(not(target_vendor = "win7"))] pub(super) fn open_default_apps() -> Result<DefaultApp, String> { open::that_detached(SETTINGS_URI).map_err(|e| format!("couldn't open Settings: {e}"))?; Ok(DefaultApp::SettingsOpened) }++ /// Windows 7 has no Settings app (docs/windows7.md): Control Panel › Default Programs ›+ /// Set your default programs, where the user picks WordCraft.+ #[cfg(target_vendor = "win7")]+ pub(super) fn open_default_apps() -> Result<DefaultApp, String> {+ let root = std::path::PathBuf::from(std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into()));+ std::process::Command::new(root.join("System32").join("control.exe"))+ .args(["/name", "Microsoft.DefaultPrograms", "/page", "pageDefaultProgram"])+ .spawn()+ .map_err(|e| format!("couldn't open Control Panel: {e}"))?;+ Ok(DefaultApp::SettingsOpened)+ } } #[cfg(all(unix, not(target_os = "macos")))]@@ -9,6 +9,15 @@ #![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +// The experimental Windows 7 build (docs/windows7.md) is OpenGL only, on the win7 Rust target:+// the ordinary Windows target's standard library itself needs Windows 10.+#[cfg(all(feature = "windows7", any(feature = "wgpu", feature = "accessibility")))]+compile_error!("windows7 requires --no-default-features (wgpu and accessibility must be disabled)");+#[cfg(all(windows, feature = "windows7", not(target_vendor = "win7")))]+compile_error!("windows7 requires --target x86_64-win7-windows-msvc; the ordinary Windows target still imports newer APIs");+#[cfg(all(target_vendor = "win7", not(feature = "windows7")))]+compile_error!("the win7 target requires --no-default-features --features windows7");+ mod animations; #[cfg(target_os = "macos")] mod apple_events;@@ -16,7 +25,7 @@ mod clipboard; mod control_server; mod default_apps; mod file_dialogs;-#[cfg(any(target_os = "windows", target_os = "macos", test))]+#[cfg(all(feature = "wgpu", any(target_os = "windows", target_os = "macos", test)))] mod graphics; mod logging; mod print;@@ -116,7 +125,21 @@ impl eframe::App for App { self.0.ui(ui); self.3.show(frame); }+ #[cfg(not(feature = "windows7"))] fn on_exit(&mut self) {+ self.exit();+ }+ // With OpenGL (the Windows 7 build), eframe hands `on_exit` the GL context.+ #[cfg(feature = "windows7")]+ fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {+ self.exit();+ }+}++impl App {+ /// What [`eframe::App::on_exit`] does: waits for print jobs, ends crash recovery, saves the+ /// preferences and removes the control key file.+ fn exit(&mut self) { print::finish_pending_jobs(); self.0.session.finish_recovery(); save_prefs(&self.0);@@ -415,6 +438,9 @@ fn main() -> eframe::Result { .with_fullsize_content_view(true) .with_titlebar_shown(false) .with_title_shown(false),+ // The Windows 7 build draws with OpenGL (docs/windows7.md).+ #[cfg(feature = "windows7")]+ renderer: eframe::Renderer::Glow, ..Default::default() }; if let Some(icon) = app_icon() {@@ -423,10 +449,10 @@ fn main() -> eframe::Result { // Before eframe creates the wgpu instance: default Windows to DirectX 12 only, or OpenGL when // DirectX 12 has no GPU driver or this is a 32-bit build, and compile DirectX 12 shaders with // FXC, which needs no DLL of ours (#603; see graphics.rs).- #[cfg(target_os = "windows")]+ #[cfg(all(target_os = "windows", feature = "wgpu"))] graphics::configure(&mut options, eframe::wgpu::Backends::from_env()); // Intel Macs: Metal's compiler aborts on wgpu's indirect-validation shaders (#2652).- #[cfg(target_os = "macos")]+ #[cfg(all(target_os = "macos", feature = "wgpu"))] graphics::configure_indirect_validation(&mut options, graphics::skips_indirect_validation(true, cfg!(target_arch = "x86_64"))); load_user_fonts(); // Windows opened for further documents start like the first one, before its saved place.@@ -1,5 +1,11 @@ //! Desktop spooler adapter. Discovery and submission never run on the UI thread.-use wordcraft_ui_egui::printing::{Discover, Duplex, Printer, Settings, Submit};+use wordcraft_ui_egui::printing::{Discover, Settings, Submit};+#[cfg(not(target_vendor = "win7"))]+use wordcraft_ui_egui::printing::{Duplex, Printer};++/// The experimental Windows 7 build's spooler: the PDF viewer's print verb (docs/windows7.md).+#[cfg(any(test, target_vendor = "win7"))]+mod windows7; /// Returns a discovery callback that enumerates spooler printers on a named worker thread and /// sends the list through a channel, keeping spooler calls off the UI thread.@@ -7,11 +13,7 @@ pub fn discover() -> Discover { Box::new(|| { let (sender, receiver) = std::sync::mpsc::channel(); let _ = std::thread::Builder::new().name("print-discovery".into()).spawn(move || {- let printers = craft_print::printers()- .into_iter()- .map(|printer| Printer { name: printer.name, label: printer.description, default: printer.default })- .collect();- let _ = sender.send(printers);+ let _ = sender.send(printers()); }); receiver })@@ -30,25 +32,46 @@ pub fn finish_pending_jobs() { } } +/// The spooler's printers.+#[cfg(not(target_vendor = "win7"))]+fn printers() -> Vec<Printer> {+ craft_print::printers().into_iter().map(|printer| Printer { name: printer.name, label: printer.description, default: printer.default }).collect()+}++#[cfg(target_vendor = "win7")]+use windows7::printers;++/// Hands `bytes` to the spooler; the result is its receipt or the error.+#[cfg(not(target_vendor = "win7"))]+fn send(bytes: &[u8], settings: Settings, collate: bool, options: Vec<(String, String)>) -> Result<String, String> {+ let job = craft_print::Job {+ printer: Some(settings.printer),+ copies: settings.copies.clamp(1, 999),+ collate,+ duplex: settings.duplex.map(|value| match value {+ Duplex::LongEdge => craft_print::Duplex::LongEdge,+ Duplex::ShortEdge => craft_print::Duplex::ShortEdge,+ Duplex::Off => craft_print::Duplex::Off,+ }),+ grayscale: settings.grayscale,+ scaling: craft_print::Scaling::ShrinkToFit,+ title: "WordCraft document".into(),+ options,+ };+ craft_print::submit(bytes, &job).map_err(|error| error.to_string())+}++/// Hands `bytes` to the PDF viewer, which prints with its own settings (docs/windows7.md).+#[cfg(target_vendor = "win7")]+fn send(bytes: &[u8], settings: Settings, _collate: bool, _options: Vec<(String, String)>) -> Result<String, String> {+ windows7::submit(bytes, &settings.printer, settings.copies)+}+ pub fn submit() -> Submit { Box::new(|bytes, settings: Settings, collate, options| { let (sender, receiver) = std::sync::mpsc::channel(); let worker = std::thread::Builder::new().name("print-submit".into()).spawn(move || {- let job = craft_print::Job {- printer: Some(settings.printer),- copies: settings.copies.clamp(1, 999),- collate,- duplex: settings.duplex.map(|value| match value {- Duplex::LongEdge => craft_print::Duplex::LongEdge,- Duplex::ShortEdge => craft_print::Duplex::ShortEdge,- Duplex::Off => craft_print::Duplex::Off,- }),- grayscale: settings.grayscale,- scaling: craft_print::Scaling::ShrinkToFit,- title: "WordCraft document".into(),- options,- };- let _ = sender.send(craft_print::submit(&bytes, &job).map_err(|error| error.to_string()));+ let _ = sender.send(send(&bytes, settings, collate, options)); }); if let Ok(worker) = worker { let mut jobs = JOBS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);new file mode 100644@@ -0,0 +1,289 @@+//! The experimental Windows 7 build's spooler (docs/windows7.md), as in VectorCraft's Windows 7+//! build. craft-print draws jobs with `Windows.Data.Pdf`, a Windows Runtime API Windows 7 doesn't+//! have, so this build lists printers through PowerShell's WMI (`Win32_Printer`) and hands the+//! print-ready PDF to the installed PDF viewer's Print / PrintTo verb. The viewer prints with its+//! own settings: copies, two-sided and grayscale chosen in WordCraft don't reach it, and the+//! result says so.++/// Where a job's PDF waits for the viewer: a fresh file in `dir`. The viewer reads it after the+/// verb returns, so it can't be removed then; files of jobs more than an hour old are removed+/// first instead. Never truncates an existing file, and removes one it couldn't finish.+pub(crate) fn job_file(dir: &std::path::Path, pdf: &[u8]) -> Result<std::path::PathBuf, String> {+ use std::io::Write as _;+ std::fs::create_dir_all(dir).map_err(|e| format!("can't make {}: {e}", dir.display()))?;+ sweep(dir);+ let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default();+ let path = dir.join(format!("job-{}-{stamp}.pdf", std::process::id()));+ let mut file =+ std::fs::OpenOptions::new().write(true).create_new(true).open(&path).map_err(|e| format!("can't create {}: {e}", path.display()))?;+ if let Err(e) = file.write_all(pdf).and_then(|()| file.flush()) {+ drop(file);+ let _ = std::fs::remove_file(&path);+ return Err(format!("can't write {}: {e}", path.display()));+ }+ Ok(path)+}++/// Removes the job files in `dir` more than an hour old: their viewer has long read them. Runs+/// before each job and whenever the printers are listed, so a job's file outlives it by about an+/// hour of using WordCraft's printing. A file still in use stays for the next sweep; the folder is+/// the user's own temp folder.+pub(crate) fn sweep(dir: &std::path::Path) {+ // A folder of a few files; the cap only bounds a runaway listing.+ for entry in std::fs::read_dir(dir).into_iter().flatten().flatten().take(4096) {+ let old = entry.metadata().and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age.as_secs() > 3600);+ if old {+ let _ = std::fs::remove_file(entry.path());+ }+ }+}++/// The folder job files wait in for the viewer.+#[cfg(target_vendor = "win7")]+fn job_dir() -> std::path::PathBuf {+ std::env::temp_dir().join("wordcraft-print")+}++/// PowerShell's `<Default>\t<Name>` lines → the printers, the default first.+pub(crate) fn parse_printers(text: &str) -> Vec<wordcraft_ui_egui::printing::Printer> {+ let mut printers: Vec<wordcraft_ui_egui::printing::Printer> = text+ .lines()+ .filter_map(|l| l.trim_end_matches('\r').split_once('\t'))+ .filter(|(_, name)| !name.trim().is_empty())+ .map(|(default, name)| wordcraft_ui_egui::printing::Printer {+ name: name.trim().to_string(),+ label: String::new(),+ default: default.trim().eq_ignore_ascii_case("true"),+ })+ .collect();+ printers.sort_by_key(|p| !p.default);+ printers+}++/// The environment variables that carry the job's file and printer into PowerShell. A value in+/// the environment is data to PowerShell, never parsed as script, whatever quotes it contains+/// (PowerShell also ends a single-quoted string at ‘ ’ ‚ ‛), so neither is ever written into the+/// script's source.+const FILE_VAR: &str = "WORDCRAFT_PRINT_FILE";+const PRINTER_VAR: &str = "WORDCRAFT_PRINT_PRINTER";++/// The fixed scripts: Print on the default printer, PrintTo on a named one. Each writes `ok`+/// once the viewer has been started; `$ErrorActionPreference = 'Stop'` turns a failure into no `ok`.+const PRINT_SCRIPT: &str = "Start-Process -FilePath $env:WORDCRAFT_PRINT_FILE -Verb Print -WindowStyle Hidden; 'ok'";+const PRINT_TO_SCRIPT: &str =+ "Start-Process -FilePath $env:WORDCRAFT_PRINT_FILE -Verb PrintTo -ArgumentList $env:WORDCRAFT_PRINT_PRINTER -WindowStyle Hidden; 'ok'";++/// The printers, as `<Default>\t<Name>` lines (a fixed script: it reads nothing from WordCraft).+#[cfg(target_vendor = "win7")]+const PRINTERS_SCRIPT: &str = "Get-WmiObject Win32_Printer | ForEach-Object { \"$($_.Default)`t$($_.Name)\" }";++/// The script and environment that print `file` on `printer` (the default printer when blank)+/// through the PDF viewer's verb. PrintTo takes the printer name in double quotes, which a+/// Windows printer name can't contain.+pub(crate) fn print_invocation(file: &str, printer: &str) -> (&'static str, Vec<(&'static str, String)>) {+ let mut env = vec![(FILE_VAR, file.to_string())];+ match printer.trim() {+ "" => (PRINT_SCRIPT, env),+ p => {+ env.push((PRINTER_VAR, format!("\"{}\"", p.replace('"', ""))));+ (PRINT_TO_SCRIPT, env)+ }+ }+}++/// How long PowerShell may take to list the printers or start the viewer: a hung WMI query or+/// print handler must not leave discovery or a job pending for ever.+#[cfg(target_vendor = "win7")]+const LIMIT: std::time::Duration = std::time::Duration::from_secs(60);++/// The most of PowerShell's output that is kept (a printer list is a few kilobytes).+#[cfg(any(test, target_vendor = "win7"))]+const OUTPUT_CAP: u64 = 1 << 20;++/// Runs `command` and collects its standard output, giving it `limit`: a command still running+/// then is killed and reaped, and the error is `TimedOut`. The output is read on a thread of its+/// own, so a full pipe never holds the command past the deadline. The exit status isn't checked.+#[cfg(any(test, target_vendor = "win7"))]+pub(crate) fn output_within(command: &mut std::process::Command, limit: std::time::Duration) -> std::io::Result<Vec<u8>> {+ use std::io::Read as _;+ use std::process::Stdio;+ let mut child = command.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn()?;+ let stop = |child: &mut std::process::Child| {+ let _ = child.kill();+ let _ = child.wait();+ };+ let Some(mut stdout) = child.stdout.take() else {+ stop(&mut child);+ return Err(std::io::Error::other("the command's output could not be read"));+ };+ let (tx, rx) = std::sync::mpsc::channel();+ let reader = std::thread::Builder::new().name("powershell output".into()).spawn(move || {+ let mut out = Vec::new();+ let read = (&mut stdout).take(OUTPUT_CAP).read_to_end(&mut out);+ let _ = std::io::copy(&mut stdout, &mut std::io::sink());+ let _ = tx.send(read.map(|_| out));+ });+ if let Err(e) = reader {+ stop(&mut child);+ return Err(e);+ }+ let timed_out = || std::io::Error::new(std::io::ErrorKind::TimedOut, format!("no answer within {limit:?}"));+ let deadline = std::time::Instant::now() + limit;+ loop {+ match child.try_wait() {+ Ok(Some(_)) => {+ // A moment's grace for output written just before the exit. A process the command+ // started may keep the pipe open; the wait for the output ends at the deadline too.+ let left = deadline.saturating_duration_since(std::time::Instant::now()).max(std::time::Duration::from_millis(100));+ return match rx.recv_timeout(left) {+ Ok(read) => read,+ Err(std::sync::mpsc::RecvTimeoutError::Timeout) => Err(timed_out()),+ Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => Err(std::io::Error::other("the command's output was lost")),+ };+ }+ Ok(None) if std::time::Instant::now() >= deadline => {+ stop(&mut child);+ return Err(timed_out());+ }+ Ok(None) => std::thread::sleep(std::time::Duration::from_millis(10)),+ Err(e) => {+ stop(&mut child);+ return Err(e);+ }+ }+ }+}++/// What the status bar is told once the viewer has the job: the settings the viewer decides.+pub(crate) fn handed_over(copies: u32) -> String {+ let mut note = String::from("handed to the PDF viewer's print command, which prints with its own settings");+ if copies > 1 {+ note.push_str(&format!(" (one copy, not {copies})"));+ }+ note+}++/// Windows PowerShell (2.0 on Windows 7 SP1) running `script`, without a console window.+#[cfg(target_vendor = "win7")]+fn powershell(script: &str) -> std::process::Command {+ use std::os::windows::process::CommandExt as _;+ const CREATE_NO_WINDOW: u32 = 0x0800_0000;+ let root = std::path::PathBuf::from(std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into()));+ let mut c = std::process::Command::new(root.join("System32").join("WindowsPowerShell").join("v1.0").join("powershell.exe"));+ c.args([+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ &format!("$ErrorActionPreference = 'Stop'; [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false); {script}"),+ ])+ .creation_flags(CREATE_NO_WINDOW);+ c+}++/// The spooler's printers; empty when they can't be listed.+#[cfg(target_vendor = "win7")]+pub fn printers() -> Vec<wordcraft_ui_egui::printing::Printer> {+ sweep(&job_dir());+ match output_within(&mut powershell(PRINTERS_SCRIPT), LIMIT) {+ Ok(out) => parse_printers(&String::from_utf8_lossy(&out)),+ Err(e) => {+ log::warn!("listing printers: PowerShell: {e}");+ Vec::new()+ }+ }+}++/// Print `pdf` on `printer` through the PDF viewer's verb.+#[cfg(target_vendor = "win7")]+pub fn submit(pdf: &[u8], printer: &str, copies: u32) -> Result<String, String> {+ let file = job_file(&job_dir(), pdf)?;+ let (script, env) = print_invocation(&file.to_string_lossy(), printer);+ let mut command = powershell(script);+ command.envs(env);+ let failed = match output_within(&mut command, LIMIT) {+ Ok(out) if String::from_utf8_lossy(&out).trim() == "ok" => None,+ Ok(_) => Some("PowerShell couldn't start it".to_string()),+ Err(e) => Some(format!("PowerShell: {e}")),+ };+ if let Some(e) = failed {+ // No viewer took the job, so nothing will read the file.+ let _ = std::fs::remove_file(&file);+ return Err(format!("no app prints PDF files here; install a PDF viewer that can print, or export a PDF ({e})"));+ }+ Ok(handed_over(copies))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn powershell_printer_lines_are_read_default_first() {+ let printers = parse_printers("False\tOffice Laser\r\nTrue\tHome Inkjet\r\nFalse\t \r\nno tab\r\n");+ let names: Vec<(&str, bool)> = printers.iter().map(|p| (p.name.as_str(), p.default)).collect();+ assert_eq!(names, [("Home Inkjet", true), ("Office Laser", false)]);+ assert!(parse_printers("").is_empty());+ }++ #[test]+ fn file_and_printer_reach_powershell_as_data_never_as_script() {+ // Quotes PowerShell would end a single-quoted string at, ASCII and typographic.+ let hostile = "Office \"Laser\" 'B' ‘x’ ‚y‛; Remove-Item C:\\ $(calc)";+ let (script, env) = print_invocation(r"C:\Bob's ‘dir’\job.pdf", hostile);+ assert_eq!(script, PRINT_TO_SCRIPT);+ assert!(!script.contains("Bob") && !script.contains("Laser"));+ assert_eq!(+ env,+ [(FILE_VAR, r"C:\Bob's ‘dir’\job.pdf".to_string()), (PRINTER_VAR, "\"Office Laser 'B' ‘x’ ‚y‛; Remove-Item C:\\ $(calc)\"".to_string())]+ );+ assert!(PRINT_TO_SCRIPT.contains(&format!("$env:{FILE_VAR}")) && PRINT_TO_SCRIPT.contains(&format!("$env:{PRINTER_VAR}")));+ assert!(PRINT_SCRIPT.contains(&format!("$env:{FILE_VAR}")));+ for blank in ["", " "] {+ assert_eq!(print_invocation("job.pdf", blank), (PRINT_SCRIPT, vec![(FILE_VAR, "job.pdf".to_string())]));+ }+ }++ #[test]+ fn the_sweep_removes_job_files_older_than_an_hour_only() {+ let dir = std::env::temp_dir().join(format!("wordcraft-print-sweep-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let (old, new) = (dir.join("old.pdf"), dir.join("new.pdf"));+ std::fs::write(&old, b"a").unwrap();+ std::fs::write(&new, b"b").unwrap();+ let two_hours_ago = std::time::SystemTime::now() - std::time::Duration::from_secs(7200);+ std::fs::File::options().write(true).open(&old).unwrap().set_modified(two_hours_ago).unwrap();+ sweep(&dir);+ assert!(!old.exists());+ assert!(new.exists());+ std::fs::remove_dir_all(dir).unwrap();+ }++ /// A command that outlives its limit is stopped, and one that finishes in time is read.+ #[cfg(unix)]+ #[test]+ fn powershell_gets_a_deadline() {+ let started = std::time::Instant::now();+ let slow = output_within(std::process::Command::new("sleep").arg("30"), std::time::Duration::from_millis(200));+ assert_eq!(slow.unwrap_err().kind(), std::io::ErrorKind::TimedOut);+ assert!(started.elapsed() < std::time::Duration::from_secs(10));+ let quick = output_within(std::process::Command::new("echo").arg("ok"), std::time::Duration::from_secs(10)).unwrap();+ assert_eq!(String::from_utf8_lossy(&quick).trim(), "ok");+ }++ #[test]+ fn job_files_hold_the_pdf_for_the_viewer_and_never_overwrite() {+ let dir = std::env::temp_dir().join(format!("wordcraft-print-test-{}", std::process::id()));+ let a = job_file(&dir, b"%PDF-1.7 a").unwrap();+ let b = job_file(&dir, b"%PDF-1.7 b").unwrap();+ assert_ne!(a, b);+ assert_eq!(std::fs::read(&a).unwrap(), b"%PDF-1.7 a");+ assert_eq!(std::fs::read(&b).unwrap(), b"%PDF-1.7 b");+ std::fs::remove_dir_all(dir).unwrap();+ }++ #[test]+ fn the_result_says_the_viewer_decides_and_copies_are_not_applied() {+ assert!(!handed_over(1).contains("copy"));+ assert!(handed_over(3).ends_with("(one copy, not 3)"));+ }+}@@ -14,7 +14,8 @@ pub fn system() -> wordcraft_engine::Region { return wordcraft_engine::Region::default(); } let region = wordcraft_ui_egui::i18n::system_region();- #[cfg(target_os = "windows")]+ // Not on the Windows 7 build (docs/windows7.md): the API is part of the Windows Runtime.+ #[cfg(all(windows, not(target_vendor = "win7")))] { if std::env::var_os("WORDCRAFT_REGION").is_none() { return match windows::System::UserProfile::GlobalizationPreferences::HomeGeographicRegion() {new file mode 100644@@ -0,0 +1,102 @@+# Windows 7 x64 compatibility build (experimental, unsupported)++> **Status:** experimental, not runtime-verified · **Last updated:** 2026-10-27 · **Change:** new (ported from VectorCraft's Windows 7 build)++Windows 7 is not a supported platform. This build is experimental and community-maintained,+and the WordCraft maintainers have not verified it on Windows 7. It follows VectorCraft's Windows 7+build (storytold/vectorcraft `docs/windows7.md`), with the same toolchain, patch and checks.++This separate build targets **64-bit Windows 7 SP1**. Compared with the regular Windows build:++- It draws with **OpenGL** instead of wgpu (Direct3D 12), so `WGPU_BACKEND` and the Direct3D 12+ start-up probe don't apply. A vendor graphics driver providing **OpenGL 3.3 or newer** is+ required; Windows' built-in generic display driver is insufficient.+- The native **AccessKit** accessibility adapter is left out: screen readers don't see the UI.+- **Printing** lists printers through PowerShell's WMI (`Win32_Printer`, PowerShell 2.0 is part+ of Windows 7 SP1) and hands the print-ready PDF to the installed PDF viewer's Print / PrintTo+ verb. The regular build's craft-print draws jobs with `Windows.Data.Pdf`, a Windows Runtime API+ Windows 7 doesn't have, so craft-print isn't in this build. The viewer prints with its own+ settings: copies, two-sided and grayscale chosen in WordCraft don't reach it (the status bar+ says so). A PDF viewer that can print must be installed.+- Windows' **Animation effects** setting and **home region** aren't read (both are Windows Runtime+ APIs): File › Options › Accessibility › Animation effects decides, and new documents follow+ the display language's region (or `WORDCRAFT_REGION`).+- **Make WordCraft the default** opens Control Panel › Default Programs, since Windows 7 has no+ Settings app. The portable build registers no file types, so WordCraft is listed there only+ after it has been chosen once through Open With.++The `windows7` feature and the win7 Rust target must be selected together; compile-time guards+in `apps/wordcraft/src/main.rs` reject mixing this feature with the ordinary Windows target, and+with the `wgpu` and `accessibility` features. The normal desktop and web builds keep their+existing defaults.++## Build or download++In your GitHub fork, open **Actions → Windows 7 x64 compatibility → Run workflow** (it also runs+weekly and on pull requests changing the compatibility path). When it succeeds, download the+`wordcraft-windows7-x64-portable` artifact, extract the contained portable ZIP, then run+`wordcraft.exe` on Windows 7. The CLI is included. No MSI is provided: the existing installers+remain for modern Windows.++To build locally, use a **Windows 10/11 build computer**, with Rust/rustup and Visual Studio 2022+C++ build tools (x64 compiler and Windows SDK). Open an **x64 Native Tools Command Prompt for+VS 2022**, change to your clone's repository root (the directory containing `Cargo.toml`), and run:++```powershell+powershell -ExecutionPolicy Bypass -File packaging/windows/windows7.ps1+```++Add `-Test` to also run the app and CLI tests on the build computer.++Output: `dist/release/wordcraft-windows7-x64-portable.zip`. The script installs the pinned nightly+compiler and `rust-src`, rebuilds the standard library for `x86_64-win7-windows-msvc`, and links+the C runtime statically. It never installs Rust on the Windows 7 machine. The optional+`CRAFT_FONTS_DIR` setting works as in the normal build. Without it, install fonts for the+languages you need on the destination machine.++The Windows 7 target matters: modern Rust's ordinary `x86_64-pc-windows-msvc` target requires+Windows 10, including standard-library and random-number APIs. Selecting OpenGL alone or changing+an installer version check cannot fix that.++References: [Rust's Windows 7 target](https://doc.rust-lang.org/rustc/platform-support/win7-windows-msvc.html)+and [Windows baseline change](https://blog.rust-lang.org/2024/02/26/Windows-7/).++The packaging script checks the dependency tree (no wgpu, AccessKit adapter or craft-print), x64+PE headers, the subsystem version, and known incompatible imports (including+`GetSystemTimePreciseAsFileTime`, `combase.dll` and the Windows Runtime's+`api-ms-win-core-winrt-*`) before creating the ZIP. This is a regression check, not an exhaustive+audit of every Windows API.++The small vendored `windows-link` patch routes `CoTaskMemFree` to its documented `ole32.dll`+export on the Windows 7 target; the newer binding otherwise imports `combase.dll`, which is absent+on Windows 7. Only this script uses it: it passes+`--config "patch.crates-io.windows-link.path='vendor/windows-link'"` to Cargo, so every other+build, including the normal Windows one, keeps the checksum-verified crates.io crate. Cargo+records the patch in `Cargo.lock`, so the script resolves once, fails if anything other than+windows-link's source changed, builds with `--locked`, and then restores `Cargo.lock`.++## Runtime validation++None yet. A successful build on the Windows 2022 CI runner does **not** prove Windows 7 runtime+compatibility.++## Runtime acceptance checklist++Before declaring support, test on a Windows 7 SP1 x64 machine and record its GPU, driver version,+Windows updates and any missing-DLL/entry-point error:++- Start `wordcraft.exe`; verify a visible window and page, resizing, minimize/restore and exit.+- Type, format and spell-check text; save a `.docx`, close and reopen it.+- Start with `--sample`; export it to PDF and inspect the result.+- Exercise native Open/Save dialogs, clipboard text/images/rich text and drag-and-drop.+- Print to a printer (or Microsoft XPS Document Writer) with a PDF viewer installed.+- Change a preference in File › Options, exit and verify it survives restarting.+- Run `wordcraft-cli.exe --version` and `wordcraft-cli.exe convert` on a document from a Command+ Prompt in the extracted application folder.++This build is experimental until that checklist passes. New dependency versions can add newer+Windows imports, so retain Cargo.lock and repeat runtime QA after dependency updates.++## Revision history++- 2026-10-27: First version, ported from VectorCraft's Windows 7 build.new file mode 100644@@ -0,0 +1,103 @@+<# Experimental, unsupported Windows 7 SP1 x64 build (docs/windows7.md), ported from VectorCraft's.+ Build on Windows 10/11 with the VS 2022 x64 C++ tools and Windows SDK.+ From the repository root: powershell -File packaging/windows/windows7.ps1 [-Test]+ The resulting portable ZIP targets Windows 7 SP1 x64 with an OpenGL 3.3 driver.+ The compiler runs on the build host, not on Windows 7. -Test also runs the app and CLI tests+ on the build host. #>+param([string] $Toolchain = 'nightly-2026-10-01', [switch] $Test)+$ErrorActionPreference = 'Stop'+$Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path+$Target = 'x86_64-win7-windows-msvc'+function Invoke-Checked([scriptblock] $Command) {+ & $Command+ if ($LASTEXITCODE -ne 0) { throw "Command failed with exit code $LASTEXITCODE" }+}+# Cargo.lock without windows-link's registry source and checksum lines (and with LF line endings),+# so the lock files with and without the patch below compare equal.+function Get-LockWithoutWindowsLinkSource([string] $Text) {+ ($Text -replace "`r`n", "`n") -replace '(?m)^(name = "windows-link"\nversion = "[^"]*"\n)source = "[^"]*"\nchecksum = "[^"]*"\n', '$1'+}+Push-Location $Root+$FlagName = 'CARGO_TARGET_X86_64_WIN7_WINDOWS_MSVC_RUSTFLAGS'+$OldFlags = [Environment]::GetEnvironmentVariable($FlagName)+$OldWinres = $env:WORDCRAFT_REQUIRE_WINRES+$Lock = Join-Path $Root 'Cargo.lock'+$LockBytes = [IO.File]::ReadAllBytes($Lock)+try {+ Invoke-Checked { rustup toolchain install $Toolchain --profile minimal --component rust-src }+ # windows-sys imports CoTaskMemFree from combase.dll, which Windows 7 lacks. Only this build uses+ # the patched copy in vendor/windows-link (see its WORDCRAFT-PATCH.md); every other build keeps+ # the crates.io crate. Cargo records the patch in Cargo.lock, so resolve once, check that nothing+ # but windows-link's source moved, then build --locked. The finally block restores Cargo.lock.+ $Patch = @('--config', "patch.crates-io.windows-link.path='vendor/windows-link'")+ Invoke-Checked { cargo "+$Toolchain" metadata --format-version 1 @Patch | Out-Null }+ $Before = Get-LockWithoutWindowsLinkSource ([Text.Encoding]::UTF8.GetString($LockBytes))+ $After = Get-LockWithoutWindowsLinkSource ([IO.File]::ReadAllText($Lock))+ if ($Before -cne $After) { throw 'Cargo.lock is out of date: applying the windows-link patch changed other entries' }+ $CargoArgs = @('--locked') + $Patch + @('--target', $Target, '--no-default-features', '--features', 'wordcraft/windows7')+ $Tree = cargo "+$Toolchain" tree @CargoArgs -p wordcraft -p wordcraft-cli -e normal --prefix none+ if ($LASTEXITCODE -ne 0) { throw 'dependency inspection failed' }+ # craft-print draws jobs with Windows.Data.Pdf (Windows Runtime): src/print/windows7.rs replaces it.+ if ($Tree -match '^(wgpu|wgpu-core|wgpu-hal|accesskit_windows|craft-print|winprint) v') { throw 'unsupported Windows backend in compatibility build' }+ if (-not ($Tree -match '^windows-link v[^ ]+ \(.*vendor[\\/]windows-link\)')) { throw 'the patched windows-link is not in use' }+ # The ordinary pc-windows-msvc standard library requires Windows 10. Rebuild std for win7.+ [Environment]::SetEnvironmentVariable($FlagName, '-C target-feature=+crt-static')+ $env:WORDCRAFT_REQUIRE_WINRES = '1'+ if (-not $env:WORDCRAFT_BUILD_SHA) { $env:WORDCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) }+ $CargoArgs += @('-p', 'wordcraft', '-p', 'wordcraft-cli')+ Invoke-Checked { cargo "+$Toolchain" build -Z build-std=std,panic_unwind @CargoArgs --release }+ $TargetDir = if ($env:CARGO_TARGET_DIR) { $env:CARGO_TARGET_DIR } else { 'target' }+ $Bin = Join-Path $TargetDir "$Target\release"+ # PE subsystem: 2 = Windows GUI (the app opens no console), 3 = console (the CLI's output reaches it).+ foreach ($Check in @(@('wordcraft.exe', 2), @('wordcraft-cli.exe', 3))) {+ $Name = $Check[0]+ $Exe = Join-Path $Bin $Name+ $Bytes = [IO.File]::ReadAllBytes($Exe)+ $Pe = [BitConverter]::ToInt32($Bytes, 0x3c)+ if ([BitConverter]::ToUInt16($Bytes, $Pe + 4) -ne 0x8664) { throw "$Name is not x64" }+ $Major = [BitConverter]::ToUInt16($Bytes, $Pe + 0x48)+ $Minor = [BitConverter]::ToUInt16($Bytes, $Pe + 0x4a)+ if ($Major -gt 6 -or ($Major -eq 6 -and $Minor -gt 1)) { throw "$Name requires subsystem $Major.$Minor" }+ $Subsystem = [BitConverter]::ToUInt16($Bytes, $Pe + 0x5c)+ if ($Subsystem -ne $Check[1]) { throw "$Name has PE subsystem $Subsystem, expected $($Check[1])" }+ $Imports = & dumpbin /nologo /imports $Exe+ if ($LASTEXITCODE -ne 0) { throw "Could not inspect $Name imports" }+ # Regression gate for known loader failures; actual Win7 runtime QA remains necessary.+ # combase.dll and api-ms-win-core-winrt-* are the Windows Runtime (Windows 8+), dcomp.dll is+ # DirectComposition (Windows 8+) and d3d12.dll is Direct3D 12 (Windows 10).+ # The DLLs are listed every time, so a run records what the build imports.+ Write-Output "$Name imports:" ($Imports | Where-Object { $_ -match '^\s+\S+\.dll\s*$' } | ForEach-Object { ' ' + $_.Trim() })+ $Bad = @($Imports | Where-Object { $_ -match '(?i)\b(GetSystemTimePreciseAsFileTime|ProcessPrng|WaitOnAddress|WakeByAddressSingle|WakeByAddressAll)\b|combase\.dll|bcryptprimitives\.dll|d3d12\.dll|dcomp\.dll|api-ms-win-core-path-|api-ms-win-core-winrt-' })+ if ($Bad.Count -gt 0) {+ throw "$Name directly imports a known post-Windows-7 API: $(($Bad | ForEach-Object { $_.Trim() }) -join ', ')"+ }+ }+ Invoke-Checked { & (Join-Path $Bin 'wordcraft-cli.exe') --version }+ $Stage = Join-Path $TargetDir ('windows7-portable-' + [Guid]::NewGuid().ToString('N'))+ New-Item -ItemType Directory -Force $Stage | Out-Null+ Copy-Item (Join-Path $Bin 'wordcraft.exe'), (Join-Path $Bin 'wordcraft-cli.exe') $Stage+ # The same notices as the regular portable zip (package.ps1), plus windows-link's licences.+ Copy-Item README.md, LICENSE-MIT, LICENSE-APACHE, NOTICE, ATTRIBUTION.md $Stage+ Copy-Item vendor/windows-link/license-mit (Join-Path $Stage 'LICENSE-windows-link-MIT')+ Copy-Item vendor/windows-link/license-apache-2.0 (Join-Path $Stage 'LICENSE-windows-link-Apache-2.0')+ Copy-Item docs/windows7.md (Join-Path $Stage 'WINDOWS7.md')+ if ($env:CRAFT_FONTS_DIR) {+ foreach ($ofl in Get-ChildItem (Join-Path $env:CRAFT_FONTS_DIR 'fonts\*\OFL.txt')) {+ Copy-Item $ofl.FullName (Join-Path $Stage "OFL-$($ofl.Directory.Name).txt")+ }+ }+ New-Item -ItemType Directory -Force dist/release | Out-Null+ $Zip = Join-Path $Root 'dist/release/wordcraft-windows7-x64-portable.zip'+ Compress-Archive -Path (Join-Path $Stage '*') -DestinationPath $Zip -Force+ Remove-Item -Recurse -Force $Stage+ Get-Item $Zip+ if ($Test) {+ # Exercises the Windows code paths on the build host only; it doesn't prove Windows 7 runtime support.+ Invoke-Checked { cargo "+$Toolchain" test -Z build-std=std,panic_unwind,test @CargoArgs }+ }+} finally {+ [IO.File]::WriteAllBytes($Lock, $LockBytes)+ [Environment]::SetEnvironmentVariable($FlagName, $OldFlags)+ $env:WORDCRAFT_REQUIRE_WINRES = $OldWinres+ Pop-Location+}new file mode 100644@@ -0,0 +1,39 @@+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO+#+# When uploading crates to the registry Cargo will automatically+# "normalize" Cargo.toml files for maximal compatibility+# with all versions of Cargo and also rewrite `path` dependencies+# to registry (e.g., crates.io) dependencies.+#+# If you are reading this file be aware that the original Cargo.toml+# will likely look very different (and much more reasonable).+# See Cargo.toml.orig for the original contents.++[package]+edition = "2021"+rust-version = "1.71"+name = "windows-link"+version = "0.2.1"+build = false+autolib = false+autobins = false+autoexamples = false+autotests = false+autobenches = false+description = "Linking for Windows"+readme = "readme.md"+categories = ["os::windows-apis"]+license = "MIT OR Apache-2.0"+repository = "https://github.com/microsoft/windows-rs"++[lib]+name = "windows_link"+path = "src/lib.rs"++[lints.rust]+missing_unsafe_on_extern = "warn"++[lints.rust.unexpected_cfgs]+level = "warn"+priority = 0+check-cfg = ["cfg(windows_raw_dylib, windows_slim_errors)"]new file mode 100644@@ -0,0 +1,22 @@+# Windows 7 x64 import compatibility++Upstream: Microsoft windows-link 0.2.1, from crates.io, MIT OR Apache-2.0.+Source: https://crates.io/crates/windows-link/0.2.1+The original license texts are retained here. The same patch is carried by VectorCraft's+Windows 7 build (storytold/vectorcraft `vendor/windows-link`).++Only the non-x86 win7-target macro differs: CoTaskMemFree is imported from+ole32.dll rather than combase.dll. windows-sys 0.61.2 otherwise causes native+file dialogs to introduce a DLL absent on Windows 7. Ordinary targets retain+upstream behavior. This is a binding correction, not a replacement allocator.++Microsoft documents Ole32.dll and Windows 2000 as the API's minimum:+https://learn.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-cotaskmemfree++Only the experimental Windows 7 build uses this copy: packaging/windows/windows7.ps1+passes `--config "patch.crates-io.windows-link.path='vendor/windows-link'"`. The+workspace has no windows-link entry in `[patch]`, so every other build uses the crates.io+crate, verified by the checksum in Cargo.lock.++The Windows 7 packaging check rejects combase.dll to guard this fix. Remove this+patch when upstream bindings provide the same compatibility and recheck imports.new file mode 100644@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright (c) Microsoft Corporation.++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.new file mode 100644@@ -0,0 +1,21 @@+ MIT License++ Copyright (c) Microsoft Corporation.++ Permission is hereby granted, free of charge, to any person obtaining a copy+ of this software and associated documentation files (the "Software"), to deal+ in the Software without restriction, including without limitation the rights+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+ copies of the Software, and to permit persons to whom the Software is+ furnished to do so, subject to the following conditions:++ The above copyright notice and this permission notice shall be included in all+ copies or substantial portions of the Software.++ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+ SOFTWAREnew file mode 100644@@ -0,0 +1,26 @@+## Linking for Windows++The [windows-link](https://crates.io/crates/windows-link) crate provides the `link` macro that simplifies linking. The `link` macro is much the same as the one provided by [windows-targets](https://crates.io/crates/windows-targets) but uses `raw-dylib` and thus does not require import lib files.++* [Getting started](https://kennykerr.ca/rust-getting-started/)+* [Samples](https://github.com/microsoft/windows-rs/tree/master/crates/samples)+* [Releases](https://github.com/microsoft/windows-rs/releases)++Start by adding the following to your Cargo.toml file:++```toml+[dependencies.windows-link]+version = "0.2"+```++Use the `link` macro to define the external functions you wish to call:++```rust+windows_link::link!("kernel32.dll" "system" fn SetLastError(code: u32));+windows_link::link!("kernel32.dll" "system" fn GetLastError() -> u32);++unsafe {+ SetLastError(1234);+ assert_eq!(GetLastError(), 1234);+}+```new file mode 100644@@ -0,0 +1,57 @@+#![doc = include_str!("../readme.md")]+#![no_std]++/// Defines an external function to import.+#[cfg(all(windows, target_arch = "x86"))]+#[macro_export]+macro_rules! link {+ ($library:literal $abi:literal $($link_name:literal)? fn $($function:tt)*) => (+ #[link(name = $library, kind = "raw-dylib", modifiers = "+verbatim", import_name_type = "undecorated")]+ extern $abi {+ $(#[link_name=$link_name])?+ pub fn $($function)*;+ }+ )+}++/// Defines an external function to import.+#[cfg(all(windows, not(target_arch = "x86"), not(target_vendor = "win7")))]+#[macro_export]+macro_rules! link {+ ($library:literal $abi:literal $($link_name:literal)? fn $($function:tt)*) => (+ #[link(name = $library, kind = "raw-dylib", modifiers = "+verbatim")]+ extern $abi {+ $(#[link_name=$link_name])?+ pub fn $($function)*;+ }+ )+}++/// Defines an external function to import.+#[cfg(not(windows))]+#[macro_export]+macro_rules! link {+ ($library:literal $abi:literal $($link_name:literal)? fn $($function:tt)*) => (+ extern $abi {+ pub fn $($function)*;+ }+ )+}++// WordCraft patch (Windows 7 build): windows-sys 0.61.2 binds CoTaskMemFree to+// combase.dll (Windows 8+). The same API is exported by ole32.dll on Windows 7.+// Redirect only this known API; leave every other binding unchanged.+#[cfg(all(windows, not(target_arch = "x86"), target_vendor = "win7"))]+#[macro_export]+macro_rules! link {+ ("combase.dll" $abi:literal fn CoTaskMemFree $($signature:tt)*) => (+ $crate::link!("ole32.dll" $abi fn CoTaskMemFree $($signature)*);+ );+ ($library:literal $abi:literal $($link_name:literal)? fn $($function:tt)*) => (+ #[link(name = $library, kind = "raw-dylib", modifiers = "+verbatim")]+ extern $abi {+ $(#[link_name=$link_name])?+ pub fn $($function)*;+ }+ )+}