Windows shell replacement in Rust: taskbar, file manager, NTFS search, task manager, disk cleaner. One installer exe.
Rust
WinRust v0.1.0: first public version
Lemxyc46e3d24d8d2
diff --git a/.cargo/config.toml b/.cargo/config.tomlnew file mode 100644index 0000000..fac678a--- /dev/null+++ b/.cargo/config.toml@@ -0,0 +1,2 @@+[build]+rustflags = ["-C", "target-feature=+crt-static"]diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..60c3f94--- /dev/null+++ b/.gitignore@@ -0,0 +1,5 @@+target/+/share+/ripgrep+/payload/*.exe+*.logdiff --git a/CLAUDE.md b/CLAUDE.mdnew file mode 100644index 0000000..3bb0d6f--- /dev/null+++ b/CLAUDE.md@@ -0,0 +1,28 @@+# plugin-launcher++Windows-лаунчер (`src/main.rs`), который ставит плагины из `plugins/` (отдельные cargo-проекты) и `ReShell/`. Описание: `README.md`, планы: `ROADMAP.md`.++## Как обновить плагин после правки его кода (без пересборки лаунчера)++Лаунчер берёт exe из `payload\` на диске раньше вшитых копий, поэтому после правки плагина:++```powershell+powershell -ExecutionPolicy Bypass -File scripts\update-plugin.ps1 <rust-search|rtaskmgr-win32|topbar>+```++Скрипт сам собирает плагин и то, что ставится вместе с ним (topbar → ещё `ReShell` и `rs-du`; rtaskmgr-win32 → ещё `rs-du`), кладёт exe в `payload\` и запускает `plugin-launcher update <плагин>`. Установка требует админа: из обычной оболочки появится окно UAC, **нажать «Да» должен пользователь**. Не пытайся обойти UAC и не меняй настройки UAC.++Лаунчер скрипт запускает **через explorer.exe** (ярлык), а не своим дочерним процессом. Приложение Claude упаковано в MSIX: всё, что запущено из его оболочки (даже через UAC), пишет HKCU в личную копию реестра пакета, которую настоящий сеанс не видит (так терялись Run-ключи, `ReplaceExplorer`, привязка папок). HKLM пишется по-настоящему. Поэтому `install` тоже запускай через explorer.exe, а `reg query HKCU\...` из своей оболочки показывает копию пакета, а не правду. Настоящие значения смотри батником, запущенным через `explorer.exe <bat>`.++После запуска:+1. Скрипт печатает последние строки `%ProgramData%\plugin-launcher\install.log`. Успех: строка `<плагин>: обновлён`. Предупреждения идут после `|`. Ошибка: `ОШИБКА ...`. Файл в UTF-8, читай с `-Encoding UTF8`.+2. Проверь, что процесс плагина запущен (`Get-Process topbar,reshell` и т. п.).+3. Не нашёл `обновлён` или есть ошибка: покажи пользователю текст ошибки, сам ничего не удаляй и не чини реестр.++## Правила++- `update` только для уже установленного плагина. Новый плагин: `install <имя> --yes`, **только с разрешения пользователя** (rust-search отключает поиск Windows, topbar прячет панель задач).+- Не запускай `uninstall`, `rollback` и `install` без прямой просьбы пользователя.+- Правки в `src/main.rs` (сам лаунчер) требуют `cargo build --release` в корне. Для релиза со свежими вшитыми exe: `scripts\build-all.ps1`.+- Правки `src/main.rs` и код установки на живой системе ни разу не прогонялись целиком: тестируй осторожно, по одному плагину.+- `plugins/rust-search` и `plugins/rtaskmgr-win32` синхронизируются с оригиналами на рабочем столе (`scripts\sync.ps1`: оригиналы главнее). Правь оригиналы, а не копии в `plugins\`.diff --git a/Cargo.lock b/Cargo.locknew file mode 100644index 0000000..356b53b--- /dev/null+++ b/Cargo.lock@@ -0,0 +1,256 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "cc"+version = "1.11.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45"+dependencies = [+ "find-msvc-tools",+ "shlex",+]++[[package]]+name = "cfg-if"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"++[[package]]+name = "embed-resource"+version = "3.0.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6168487b5e7eb2673e6efe1200b1848016e436a6ca0b8031bf04bd9d493a249f"+dependencies = [+ "cc",+ "memchr",+ "rustc_version",+ "toml",+ "vswhom",+ "winreg",+]++[[package]]+name = "equivalent"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"++[[package]]+name = "find-msvc-tools"+version = "0.1.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"++[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"++[[package]]+name = "indexmap"+version = "2.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"+dependencies = [+ "equivalent",+ "hashbrown",+]++[[package]]+name = "libc"+version = "0.2.191"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "plugin-launcher"+version = "0.1.0"+dependencies = [+ "embed-resource",+ "windows-sys",+]++[[package]]+name = "proc-macro2"+version = "1.0.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "rustc_version"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"+dependencies = [+ "semver",+]++[[package]]+name = "semver"+version = "1.0.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"++[[package]]+name = "serde_core"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "serde_spanned"+version = "1.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"+dependencies = [+ "serde_core",+]++[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"++[[package]]+name = "syn"+version = "3.0.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "toml"+version = "1.2.1+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7"+dependencies = [+ "indexmap",+ "serde_core",+ "serde_spanned",+ "toml_datetime",+ "toml_parser",+ "toml_writer",+ "winnow",+]++[[package]]+name = "toml_datetime"+version = "1.1.3+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"+dependencies = [+ "serde_core",+]++[[package]]+name = "toml_parser"+version = "1.1.5+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"+dependencies = [+ "winnow",+]++[[package]]+name = "toml_writer"+version = "1.2.0+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"++[[package]]+name = "unicode-ident"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"++[[package]]+name = "vswhom"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b"+dependencies = [+ "libc",+ "vswhom-sys",+]++[[package]]+name = "vswhom-sys"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150"+dependencies = [+ "cc",+ "libc",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "winnow"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"++[[package]]+name = "winreg"+version = "0.56.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10"+dependencies = [+ "cfg-if",+ "windows-sys",+]diff --git a/Cargo.toml b/Cargo.tomlnew file mode 100644index 0000000..e52e7fa--- /dev/null+++ b/Cargo.toml@@ -0,0 +1,20 @@+[package]+name = "plugin-launcher"+version = "0.1.0"+edition = "2024"++[dependencies]+windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Graphics_Dwm", "Win32_Graphics_Gdi", "Win32_Graphics_GdiPlus", "Win32_System_Console", "Win32_System_LibraryLoader", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] }++[build-dependencies]+embed-resource = "3"++[profile.release]+opt-level = "s"+lto = true+codegen-units = 1+panic = "abort"+strip = true++[workspace]+exclude = ["plugins"] # each plugin stays its own independent cargo projectdiff --git a/README.md b/README.mdnew file mode 100644index 0000000..9abc972--- /dev/null+++ b/README.md@@ -0,0 +1,66 @@+<p align="center"><img src="assets/logo.svg" alt="WinRust" width="160"></p>++# WinRust++**Windows-оболочка на Rust: быстрее и легче стандартной.** Набор небольших нативных программ (без .NET, без Electron), которые заменяют части Windows: панель задач, Проводник, поиск файлов, диспетчер задач и чистильщик диска. Всё ставится и удаляется одним лаунчером, всё откатывается обратно.++<p align="center"><img src="assets/th.jpg" alt="WinRust" width="480"></p>++## Бенчмарк++Одноразовые замеры на одной машине (Windows 11 IoT Enterprise 10.0.26300, RTX 4060 Laptop, NTFS). Это порядок величин, а не лабораторные цифры.++| Что | Windows | WinRust | Разница |+|---|---|---|---|+| Поиск файла (rust-search по всему C: против `dir /s` по одной папке) | 8 340 мс | 45 мс | быстрее на **99,5%** |+| То же против `Get-ChildItem -Recurse` | 16 200 – 28 600 мс | 45 мс | быстрее на **99,7–99,8%** |+| Открыть окно с папкой (rust-explorer, медиана 5 запусков) | 420 мс | 60 мс | быстрее на **86%** |+| Память оболочки (topbar + rust-explorer + rs-shell + reshell против explorer.exe) | 366 МБ | 46 МБ | меньше на **87%** |+| То же вместе с индексом поиска (53 МБ) | 366 МБ | 99 МБ | меньше на **73%** |+| Размер файлового менеджера | 3 280 КБ | 498 КБ | меньше на **85%** |+| Размер диспетчера задач | 5 791 КБ | 869 КБ | меньше на **85%** |+| CPU панели в простое (topbar после оптимизации, % одного ядра) | 0,00–0,10% (explorer) | 0,05–0,10% | на уровне Проводника |++В сумме: **в 85–99% случаев быстрее или меньше, по CPU в простое равны.** Оговорки: rs ищет по готовому индексу MFT (за это платит 53 МБ памяти), а `dir` и PowerShell обходят диск заново; explorer.exe при замере всё ещё работал и держал окна, поэтому выигрыш по памяти немного завышен; поиск Windows и диспетчер задач не сравнивались.++Один exe (`plugin-launcher.exe`), который ставит и удаляет наши плагины на Windows. Нужны права администратора. В окне все плагины собраны в один набор WinRust: кнопка «Установить WinRust» ставит недостающие по порядку (topbar раньше rust-explorer), когда всё стоит, она же обновляет; «Удалить всё» откатывает. По одному плагину: командная строка ниже.++| Плагин | Что делает |+|---|---|+| rust-search | поиск файлов по NTFS (Alt+Space); отключает поиск Windows |+| rtaskmgr-win32 | заменяет диспетчер задач |+| topbar | нижняя панель в стиле Windows 11 вместо панели задач (сглаженные скругления, подсказки над кнопками, громкость колесом с показом уровня). Вместе с ним ставятся хоткеи рабочих столов (reshell: Win+1/2/3, Win+`) и блок в PowerShell-профиль (`src/profile.ps1`: zoxide, grep=rg, ll=eza, cat=bat; пишется в Windows PowerShell 5.1 и в pwsh 7, если он есть; без rg/eza/bat/zoxide блок молчит). При удалении topbar блок убирается. |+| rs-du | чистильщик диска (анализ MFT, кеши, `target`/`node_modules`, корзина). Отдельной карточки нет: ставится в папку диспетчера задач вместе с rtaskmgr-win32 или topbar и запускается из меню топбара (ПКМ по пустому месту → «Чистильщик диска»). Исходники: `plugins/rs-du` |+| chrome-rs | заглушка |+| rs-shell | своя оболочка вместо explorer.exe на один вход пользователя: обои, автозагрузка (Run и Startup), запуск и перезапуск topbar, при частых падениях topbar отдаёт сеанс explorer.exe. Кладётся рядом с `topbar.exe`; `rs-shell --dry-run` показывает, что запустит; `--enable` / `--disable` включают и выключают (только HKCU, остальные пользователи не затронуты). Лаунчером пока не ставится. Исходники: `plugins/rs-shell` |+| rust-explorer | **Плагин в лаунчере.** Файловый менеджер на Rust вместо Проводника в стиле Windows: панель слева (быстрый доступ, диски), колонки «Имя / Дата / Тип / Размер», вкладки, тёмная тема. Установка открывает в нём папки и диски (HKCU), запускает `rs-shell --overlay` при входе и **отключает обычный explorer.exe** как оболочку (AutoRestartShell=0, Explorer завершается, когда поднялись topbar и рабочий стол; если topbar не держится, Explorer возвращается сам). Нужен topbar. Удаление всё возвращает. Раньше было: замена окон Проводника на Rust (этап 1 плана: файловый менеджер). Пока не ставится лаунчером: запускается вручную `plugins/rust-explorer/target/release/rust-explorer.exe [папка]`. Есть: виртуальный список, иконки, вкладки (Ctrl+T/W/Tab), копирование/вставка/удаление через IFileOperation, контекстное меню оболочки, перетаскивание. Не сделано: миниатюры, адресная строка, регистрация обработчиком папок, этапы 2-5 (индекс, оболочка, трей, Shell Launcher). |++## Структура+```+src/ лаунчер (окно + логика установки)+payload/ готовые exe плагинов, вшиваются в лаунчер при сборке+plugins/ исходники: rust-search, rtaskmgr-win32, chrome-rs (каждый отдельный cargo-проект)+scripts/ build-all.ps1: синхронизирует plugins/ с оригиналами, пересобирает, обновляет payload/ и STAMPS.txt; sync.ps1 -Check: проверка на рассинхрон (запускать с -ExecutionPolicy Bypass)+ROADMAP.md планы+```++## Сборка+```powershell+.\scripts\build-all.ps1+```+Результат: `target\release\plugin-launcher.exe`. Закройте запущенный лаунчер перед сборкой.+++## Командная строка+Из терминала **с правами администратора**:+```+plugin-launcher list+plugin-launcher install <плагин> --yes (без --yes только покажет предупреждение, ничего не меняет)+plugin-launcher update <плагин> (переустановить из payload\ рядом с exe: без пересборки лаунчера; см. scripts\update-plugin.ps1)+plugin-launcher uninstall <плагин>+plugin-launcher rollback --yes+```+Код выхода: 0 успех, 1 ошибка, 2 неверные аргументы или нет `--yes`. Без аргументов открывается окно.++## Новый плагин+Одна запись в `PLUGINS` (`src/main.rs`): имя, описание, предупреждение, `installed`, пара функций install/uninstall и значок `glyph`. Окно, высота списка и CLI подхватят её сами.diff --git a/ROADMAP.md b/ROADMAP.mdnew file mode 100644index 0000000..2ef1d7e--- /dev/null+++ b/ROADMAP.md@@ -0,0 +1,37 @@+# Plugin Launcher: Roadmap++## Сделано+- Окно на Win32/GDI в стиле rtaskmgr-win32 (тёмная тема, карточки плагинов).+- Плагины вшиты в один `plugin-launcher.exe` (распаковка в Program Files, не в %TEMP%), статический CRT.+- **rust-search**: служба поиска по NTFS + Alt+Space; отключает WSearch и строку поиска на панели задач.+- **rust-search, правый клик по результату**: переименовать (прямо в строке ввода), в корзину, «удалить навсегда + почистить реестр». Удаление идёт в три шага в самой карточке: сканирование (файлы, размер, список записей реестра) → подтверждение (по умолчанию «Cancel») → удаление файлов (снимает read-only, junction/symlink не проходит насквозь); реестр трогается только если все файлы ушли, и сначала сохраняется в `%LOCALAPPDATA%\rs-search\registry-backups\*.reg`. Запись Uninstall/App Paths удаляется целиком, только если сама программа лежала внутри удалённого. Исходники: `rust-search/src/bin/rs-launcher.rs`, `src/regsweep.rs`; проверено тестами и сквозным прогоном в GUI.+- **rtaskmgr-win32**: заменяет диспетчер задач через IFEO-Debugger (`taskmgr.exe` не трогается). При панике пишет `%APPDATA%\rtaskmgr\crash.log` и открывает настоящий Taskmgr в обход IFEO (запуск под отладкой с мгновенным отсоединением; без прав админа через UAC). Понимает `taskmgr /startup`, есть «Перезапустить от имени администратора». Без предупреждений clippy.+- **topbar**: нижняя панель (AppBar) в стиле Windows 11 вместо панели задач: логотип (открывает Пуск), кнопки окон с иконками (ЛКМ — свернуть/активировать, ПКМ/СКМ — закрыть), дата и часы. Родную панель скрывает и ставит в автоскрытие; удаление возвращает её (`topbar.exe --restore`). Не запускалась на живой системе, только собрана.+- **topbar + профиль PowerShell**: при установке topbar в профиль пишется блок между маркерами `# >>> topbar >>>` / `# <<< topbar <<<` (`src/profile.ps1`: zoxide, `grep`=rg, `ll`=eza, `cat`=bat). Пишется в Windows PowerShell 5.1 и в pwsh 7, если он есть; повторная установка не дублирует блок, чужие строки профиля не трогаются, удаление topbar убирает блок (и файл, если в нём больше ничего не было). Проверено на временном профиле; в pwsh и сквозной установкой не проверялось.+- **Командная строка**: `plugin-launcher list | install <плагин> --yes | uninstall <плагин> | rollback --yes`. Без `--yes` install только печатает предупреждение. Коды выхода 0/1/2. Нужен терминал с правами администратора. Окно и CLI вызывают одни и те же функции. Проверены только команды без изменений системы.+- **Плагины как данные**: запись в `PLUGINS` включает значок (`glyph`); новый плагин добавляется одной записью, окно и CLI подхватывают её сами.+- **Страховка topbar**: `reshell` (всегда запущен вместе с панелью) раз в 5 с проверяет, что topbar не работает, а родная панель задач скрыта; два раза подряд (~10 с) — запускает `topbar.exe --restore`. Панель не перезапускает (чтобы не крутиться в цикле при падении на старте). Покрыто unit-тестом условия; сквозной сценарий (убить topbar) не проверялся.+- **Установщик надёжнее**: сбой установки откатывает изменения (при обновлении уже стоящей копии не откатывает); прежние значения WSearch и строки поиска сохраняются в `HKLM\SOFTWARE\plugin-launcher\rust-search` и возвращаются при удалении; несмертельные ошибки (ярлык, задача планировщика, точка восстановления, профиль) считаются и пишутся в `%ProgramData%\plugin-launcher\install.log`; распаковывается только нужное плагину. Только собрано, не запускалось.+- **Обновление без пересборки лаунчера**: exe из `payload\` рядом с лаунчером (или `..\..\payload` в cargo-раскладке) берутся с диска вместо вшитых. `plugin-launcher update <плагин>` и `scripts\update-plugin.ps1 <плагин>` (собрать плагин, положить в payload, обновить). Вшитые копии остаются запасными; для релиза по-прежнему `build-all.ps1`.+- Точка восстановления перед установкой, кнопка «Откатить всё».+- Исходники всех проектов собраны в `plugins/`.++## Дальше (по порядку)+1. **Проверка на чистой Windows 11** (виртуалка): установка, удаление, откат, перезагрузка. Сейчас на другой машине ничего не проверялось.+3. **chrome-rs**: реальная установка вместо заглушки (после готовности браузера; см. `plugins/chrome-rs/ROADMAP.md`).+4. **Профиль PowerShell**: по желанию ставить rg/fd/bat/eza/zoxide через winget отдельной галочкой в настройках topbar (сейчас блок молчит, если их нет); проверить запись в pwsh 7 на машине, где он стоит.+5. **Релизы**: GitHub Releases, SHA-256 рядом, версия в окне, проверка обновлений.+6. **Подпись кода** (убирает SmartScreen и часть ложных срабатываний антивирусов).+7. **Win+S / кнопка «Пуск»**: открывать rust-search вместо поиска Windows (рискованно, отдельное решение).+8. **Не-NTFS диски** в rust-search (сейчас они пропускаются).+9. Тесты на установочную логику (запуск в песочнице/VM), CI-сборка. Сначала проверить `install`/`uninstall`/`rollback` из CLI на VM: в этой сессии они не запускались.++## Известные ограничения+- Системные компоненты не удаляются, а отключаются или обходятся (обратимо). Полное удаление `taskmgr.exe` и поиска Windows невозможно без взлома защиты системы.+- Нужны права администратора.+- Win+S и «Пуск» по-прежнему открывают поиск Windows.++- **wiztree / photoview / debloat** (новые, отдельные cargo-проекты; в окне лаунчера wiztree и photoview, debloat только из командной строки: `install debloat --yes`, `uninstall debloat`).+ - **wiztree**: карта занятого места (treemap) по MFT, окно на GDI; читает MFT тем же кодом, что rs-du (`plugins/rs-du/src/mft.rs`, wiztree подключает его через `#[path]`). Клик по папке: войти, ПКМ/Backspace: вверх, клик по файлу: показать в Проводнике, Tab: следующий диск, F5: заново. Сам перезапускается с UAC. Тест только на раскладку treemap; на живом диске не запускался.+ - **photoview**: просмотр фото на WIC (jpg/png/bmp/gif/tiff/webp/heic/avif при наличии кодека), поворот по EXIF, листание папки, зум колесом, Del в корзину. Установка добавляет «Открыть с помощью» и запись в «Приложения по умолчанию», значением по умолчанию не становится. Проверено запуском на системной картинке; EXIF-ориентации 5 и 7 не проверялись.+ - **debloat**: службы (DiagTrack, карты, отчёты об ошибках и т. п.) и политики реестра (Copilot, Recall, реклама, фон Edge). Старое значение каждой правки пишется в `%ProgramData%\winrust-debloat\undo.txt` до изменения, `--undo` возвращает. Сухой прогон (без `--apply`) проверен на живой системе, `--apply`/`--undo` нет.diff --git a/ReShell/Cargo.lock b/ReShell/Cargo.locknew file mode 100644index 0000000..87e2bcb--- /dev/null+++ b/ReShell/Cargo.lock@@ -0,0 +1,25 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "reshell"+version = "0.1.0"+dependencies = [+ "windows-sys",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]diff --git a/ReShell/Cargo.toml b/ReShell/Cargo.tomlnew file mode 100644index 0000000..8c9749f--- /dev/null+++ b/ReShell/Cargo.toml@@ -0,0 +1,16 @@+[package]+name = "reshell"+version = "0.1.0"+edition = "2024"++[dependencies]+windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_System_Console", "Win32_Graphics_Gdi", "Win32_System_Registry", "Win32_System_Threading", "Win32_Security", "Win32_System_LibraryLoader", "Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse"] }++[profile.release]+opt-level = "s"+lto = true+codegen-units = 1+panic = "abort"+strip = true++[workspace]diff --git a/ReShell/ROADMAP.md b/ReShell/ROADMAP.mdnew file mode 100644index 0000000..3bf9032--- /dev/null+++ b/ReShell/ROADMAP.md@@ -0,0 +1,57 @@+# ReShell: Roadmap++## Суть+Постепенно ускоряем Windows: заменяем свои скрипты на PowerShell/Python (парсинг, обход файлов, логи, системные твики) маленькими бинарниками на Rust.++- **Почему**: запуск `powershell.exe` занимает 300+ мс (и ещё дольше, если `Add-Type` компилирует C# при каждом старте); Rust-exe стартует за миллисекунды и работает в 10–100 раз быстрее на обходе файлов и парсинге.+- **Как**: один скрипт → один exe (или подкоманда общего `reshell.exe`). Поведение и аргументы остаются те же, чтобы замену можно было сделать без переучивания. Старый скрипт лежит рядом до тех пор, пока замена не прошла проверку.+- **Где живёт**: плагин для `plugin-launcher` (вшивается в `payload/`, ставится и откатывается его кнопками), как rust-search и rtaskmgr-win32.+- **Правило**: каждую замену меряем. Нет замера «до/после» — нет галочки.++## Фаза 0. Основа+1. Cargo-проект `ReShell/` (статический CRT, `opt-level=3`, `lto`, `panic=abort`, как у остальных плагинов). Один бинарник `reshell.exe` с подкомандами: `reshell <команда> [аргументы]`.+2. Общий модуль: Win32 через крейт `windows` (без `Add-Type`), логирование в `%LOCALAPPDATA%\reshell\log.txt`, сохранение прежнего состояния перед любым изменением системы (для отката).+3. Замер: `scripts/bench.ps1` гоняет `hyperfine` (или 20 прогонов `Measure-Command`) по старому скрипту и новому exe, пишет таблицу в `BENCH.md`.+4. Запись в `plugin-launcher`: карточка «ReShell», install/uninstall, добавление в `build-all.ps1` и `sync.ps1`.++## Фаза 1. Первые замены (уже есть готовые скрипты)+1. **`SuperSaver.ps1` → `reshell saver on|off`**: план питания, частота экрана (`EnumDisplaySettings`/`ChangeDisplaySettings`), яркость (WMI). Прежняя частота сохраняется в `%LOCALAPPDATA%\reshell\`, а не в `%TEMP%`. Сейчас скрипт при каждом запуске компилирует C# через `Add-Type`, это самый явный выигрыш.+2. **`desktop-hotkeys.ps1` → `reshell hotkeys`** (фоновый процесс): Win+1/2/3 → рабочий стол, Win+` → предыдущий. Хук клавиатуры (`SetWindowsHookEx`) на Rust вместо PowerShell, который висит в памяти (~60–100 МБ) ради одного хука. Модуль `VirtualDesktop` заменить на прямой COM `IVirtualDesktopManagerInternal` (недокументирован, меняется между сборками Windows: держать таблицу GUID по номеру сборки и падать в понятную ошибку, а не крашить explorer).+3. Замер обоих, запись в `BENCH.md`, старые `.ps1` удаляются только после недели ежедневного использования без проблем.++## Фаза 2. Частые утилиты (обход файлов, парсинг, логи)+Каждый пункт — отдельная подкоманда, по мере надобности, не всё сразу:+1. **`reshell clean`**: чистка `%TEMP%`, кэшей браузеров, `SoftwareDistribution\Download`, дампов; сначала показывает, что и сколько удалит (как удаление в rust-search: скан → подтверждение → действие), в корзину по умолчанию.+2. **`reshell du <путь>`**: размер папок через чтение MFT (код уже есть в rust-search, переиспользовать, а не писать заново).+3. **`reshell log <файл|канал>`**: фильтр и хвост логов, включая журнал событий Windows (`EvtQuery`) вместо медленного `Get-WinEvent`.+4. **`reshell startup`**: список и отключение автозагрузки (Run-ключи, папка Startup, планировщик, службы) с сохранением прежнего состояния.+5. Источник новых пунктов: любой свой `.ps1`/`.py`, который запускается чаще раза в день или работает дольше секунды.++## Фаза 3. Ускорение самой системы (обратимые твики)+Только то, что можно откатить; каждое изменение записывается в журнал отката до применения:+1. **`reshell tweak`**: набор проверенных настроек (отключить телеметрию-службы, фоновые приложения, анимации, Game DVR и т.п.) с режимами `list` / `apply <имя>` / `revert <имя>` / `status`.+2. Каждый твик — запись в таблице: что меняет (ключ реестра/служба), прежнее значение, как проверить эффект. Без «магических» твиков, эффект которых нельзя измерить.+3. Замер эффекта: время загрузки (`Microsoft-Windows-Diagnostics-Performance`), RAM после загрузки, число процессов. До/после в `BENCH.md`.+4. Интеграция с кнопкой «Откатить всё» в `plugin-launcher`.++## Фаза 4. Заменить фоновые процессы Windows+Как rtaskmgr и rust-search, но для других тяжёлых штук, каждая отдельным решением:+- кандидаты: Widgets, фоновый OneDrive, ненужные службы Xbox/Edge update; замена — отключение + лёгкий Rust-аналог, если функция нужна.+- критерий входа: процесс заметен в RAM/CPU на чистой системе, и его отключение обратимо.++## Дальше+- `reshell` как замена `powershell -c` в ярлыках и планировщике (запуск без окна консоли, subsystem windows для фоновых команд).+- Тихий режим и вызов из `plugin-launcher install reshell --yes`.+- Проверка на чистой Windows 11 в виртуалке (общий пункт 1 роадмапа лаунчера).++## Ограничения+- Системные твики требуют прав администратора; хоткеи и `saver` — нет (кроме смены плана питания у некоторых политик).+- COM виртуальных рабочих столов недокументирован и ломается при обновлениях Windows.+- Скрипты, которые в основном ждут сеть или внешнюю программу, переписывать бессмысленно: выигрыш только на старте.++## Статус+- **Фаза 0** (частично): Cargo-проект `ReShell/` собирается (330 КБ), подкоманды в `src/`. Не сделано: общий модуль логов, `bench.ps1`, карточка в plugin-launcher, `build-all.ps1`/`sync.ps1`.+- **Фаза 1.1** `reshell saver on|off`: написано, юнит-тест на разбор GUID проходит. **На живой системе не запускалось** (kill лаунчеров, смена плана питания и частоты экрана). Замер старта: `reshell` ~19 мс против ~340 мс у `powershell -NoProfile` + `Add-Type` (15 прогонов, 2026-11-15); это старт, не вся работа скрипта (`powercfg` вызывается как внешний процесс).+- Отличия от `SuperSaver.ps1`: яркость задаётся в плане питания (powercfg), а не через WMI; `off` больше не выставляет яркость 70, а просто возвращает план «Сбалансированная»; прежняя частота хранится в `%LOCALAPPDATA%\reshell\saver_hz.txt`, а не в `%TEMP%`.+- **Фаза 1.2** `reshell hotkeys`: написано, собирается, тест разбора реестра проходит; **на живой системе не запускалось**. Отличие от плана: без COM `IVirtualDesktopManagerInternal`. Текущий стол и их число берутся из реестра (`...\Explorer\VirtualDesktops`), переключение шлёт Ctrl+Win+←/→ нужное число раз (Win пользователь уже держит). Плюс: не ломается между сборками Windows. Минус: идёт через анимацию переключения, нужны включённые системные сочетания. Перед проверкой остановить старый `desktop-hotkeys.ps1`, иначе два хука сработают дважды.+- **Вшит в plugin-launcher** (2026-11-15): payload\reshell.exe; установка topbar кладёт eshell.exe в Program Files\topbar, пишет HKCU\...\Run\reshell и запускает его; удаление topbar убирает всё. Без аргументов eshell = hotkeys. Установка из лаунчера не проверялась.diff --git a/ReShell/src/hotkeys.rs b/ReShell/src/hotkeys.rsnew file mode 100644index 0000000..2f6d42f--- /dev/null+++ b/ReShell/src/hotkeys.rs@@ -0,0 +1,101 @@+//! Replacement for desktop-hotkeys.ps1: Win+1/2/3 -> desktop 1/2/3, Win+` -> previous desktop, Win+E -> our file manager.+//! No undocumented COM: the current desktop comes from the registry, switching sends Ctrl+Win+Left/Right+//! (Win is already held by the user). shortcut: relies on the system shortcuts being enabled.+use std::sync::atomic::{AtomicIsize, AtomicUsize, Ordering::Relaxed};+use windows_sys::Win32::{Foundation::*, System::{LibraryLoader::GetModuleHandleW, Registry::*}, UI::{Input::KeyboardAndMouse::*, WindowsAndMessaging::*}};++static PREV: AtomicUsize = AtomicUsize::new(usize::MAX);+static HOOK: AtomicIsize = AtomicIsize::new(0);++/// (current index, desktop count) from the registry.+fn desktops() -> Option<(usize, usize)> {+ let key: Vec<u16> = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\VirtualDesktops\0".encode_utf16().collect();+ let get = |name: &str| -> Option<Vec<u8>> {+ let n: Vec<u16> = format!("{name}\0").encode_utf16().collect();+ let mut buf = vec![0u8; 1024];+ let mut len = buf.len() as u32;+ let r = unsafe { RegGetValueW(HKEY_CURRENT_USER, key.as_ptr(), n.as_ptr(), RRF_RT_REG_BINARY, std::ptr::null_mut(), buf.as_mut_ptr().cast(), &mut len) };+ (r == 0).then(|| { buf.truncate(len as usize); buf })+ };+ index_in(&get("VirtualDesktopIDs")?, &get("CurrentVirtualDesktop")?)+}++fn index_in(ids: &[u8], cur: &[u8]) -> Option<(usize, usize)> {+ let i = ids.chunks_exact(16).position(|c| c == cur)?;+ Some((i, ids.len() / 16))+}++fn tap(vk: u16, up: bool) -> INPUT {+ let mut i: INPUT = unsafe { std::mem::zeroed() };+ i.r#type = INPUT_KEYBOARD;+ i.Anonymous.ki = KEYBDINPUT { wVk: vk, wScan: 0, dwFlags: if up { KEYEVENTF_KEYUP } else { 0 }, time: 0, dwExtraInfo: 0 };+ i+}++fn send(keys: &[INPUT]) {+ unsafe { SendInput(keys.len() as u32, keys.as_ptr(), size_of::<INPUT>() as i32) };+}++/// Win+E: rust-explorer from the user's own folder (where updates land without admin), else next to us, else Explorer.+/// Null std handles: this process has no console (FreeConsole) and a child that inherits the invalid ones fails to start.+fn open_files() {+ use std::{path::PathBuf, process::{Command, Stdio}};+ let mine = std::env::var_os("LOCALAPPDATA").map(|b| PathBuf::from(b).join(r"plugin-launcher\bin\rust-explorer.exe"));+ let beside = std::env::current_exe().ok().map(|e| e.with_file_name("rust-explorer.exe"));+ let exe = [mine, beside].into_iter().flatten().find(|p| p.exists()).unwrap_or_else(|| "explorer.exe".into());+ let _ = Command::new(exe).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn();+}++fn go(target: usize) {+ let Some((cur, count)) = desktops() else { return };+ if target == cur || target >= count { return }+ PREV.store(cur, Relaxed);+ let key = if target > cur { VK_RIGHT } else { VK_LEFT };+ for _ in 0..cur.abs_diff(target) {+ send(&[tap(VK_CONTROL, false), tap(key, false), tap(key, true), tap(VK_CONTROL, true)]);+ }+}++unsafe extern "system" fn hook(n: i32, w: WPARAM, l: LPARAM) -> LRESULT {+ if n >= 0 {+ let k = unsafe { &*(l as *const KBDLLHOOKSTRUCT) };+ let win = unsafe { (GetAsyncKeyState(VK_LWIN as i32) | GetAsyncKeyState(VK_RWIN as i32)) as u16 & 0x8000 != 0 };+ if k.vkCode == 0x45 && win && k.flags & LLKHF_INJECTED == 0 {+ // Win+E: swallow it so Explorer's own handler does not open a window as well+ if w == WM_KEYDOWN as usize {+ send(&[tap(0xE8, false), tap(0xE8, true)]); // Win release must not open Start+ std::thread::spawn(open_files);+ }+ return 1;+ }+ let id = match k.vkCode { 0x31..=0x33 => Some(k.vkCode as usize - 0x31), 0xC0 => Some(usize::MAX), _ => None };+ if let (Some(id), true, false) = (id, win, k.flags & LLKHF_INJECTED != 0) {+ if w == WM_KEYDOWN as usize {+ // unassigned key tap stops Win release from opening Start; switching runs off the hook thread+ send(&[tap(0xE8, false), tap(0xE8, true)]);+ std::thread::spawn(move || go(if id == usize::MAX { PREV.load(Relaxed) } else { id }));+ }+ return 1;+ }+ }+ unsafe { CallNextHookEx(HOOK.load(Relaxed) as _, n, w, l) }+}++pub fn run() -> i32 {+ let h = unsafe { SetWindowsHookExW(WH_KEYBOARD_LL, Some(hook), GetModuleHandleW(std::ptr::null()), 0) };+ if h.is_null() { eprintln!("hook failed"); return 1 }+ HOOK.store(h as isize, Relaxed);+ let mut m: MSG = unsafe { std::mem::zeroed() };+ while unsafe { GetMessageW(&mut m, std::ptr::null_mut(), 0, 0) } > 0 {}+ 0+}++#[cfg(test)]+mod tests {+ #[test]+ fn finds_index() {+ let ids = [[1u8; 16], [2; 16], [3; 16]].concat();+ assert_eq!(super::index_in(&ids, &[2; 16]), Some((1, 3)));+ assert_eq!(super::index_in(&ids, &[9; 16]), None);+ }+}diff --git a/ReShell/src/main.rs b/ReShell/src/main.rsnew file mode 100644index 0000000..50331dd--- /dev/null+++ b/ReShell/src/main.rs@@ -0,0 +1,27 @@+mod hotkeys;+mod saver;+mod watchdog;++fn main() {+ let a: Vec<String> = std::env::args().skip(1).collect();+ let code = match a.iter().map(String::as_str).collect::<Vec<_>>().as_slice() {+ ["saver", m @ ("on" | "off")] => saver::run(*m == "on"),+ ["hotkeys"] | [] => {+ // one hook per session: the copy in Program Files and the one in the user folder must not both run (keys would fire twice)+ unsafe {+ use windows_sys::Win32::{Foundation::{ERROR_ALREADY_EXISTS, GetLastError}, System::Threading::CreateMutexW};+ let name: Vec<u16> = "Local\\reshell-hotkeys\0".encode_utf16().collect();+ CreateMutexW(std::ptr::null(), 0, name.as_ptr());+ if GetLastError() == ERROR_ALREADY_EXISTS { std::process::exit(0); }+ }+ unsafe { windows_sys::Win32::System::Console::FreeConsole() }; // console exe, but the hook needs no window+ std::thread::spawn(watchdog::run); // brings the taskbar back if topbar dies+ hotkeys::run() // no args: started by the launcher/Run key+ }+ _ => {+ eprintln!("usage: reshell saver on|off | hotkeys (default)");+ 2+ }+ };+ std::process::exit(code);+}diff --git a/ReShell/src/saver.rs b/ReShell/src/saver.rsnew file mode 100644index 0000000..f9eca49--- /dev/null+++ b/ReShell/src/saver.rs@@ -0,0 +1,92 @@+//! Replacement for SuperSaver.ps1: 60 Hz, Power Saver-based scheme, launchers closed.+use std::{fs, path::PathBuf, process::Command};+use windows_sys::Win32::Graphics::Gdi::*;++const NAME: &str = "SuperSaver";+const SAVER: &str = "a1841308-3541-4fab-bc81-f71556f20b4a"; // built-in Power Saver+const BALANCED: &str = "381b4222-f694-41f0-9685-ff5bb260df2e";+const BRIGHTNESS: &str = "aded5e82-b909-4619-9949-f5d71dac0bcb"; // SUB_VIDEO / VIDEO BRIGHTNESS+const SUB_VIDEO: &str = "7516b95f-f776-4464-8c53-06167f40cc99";+const LAUNCHERS: &[&str] = &["steam", "steamwebhelper", "Discord", "EpicGamesLauncher", "Battle.net", "RiotClientServices", "GalaxyClient", "EADesktop", "Origin"];++fn hz_file() -> PathBuf {+ let dir = PathBuf::from(std::env::var("LOCALAPPDATA").unwrap_or_default()).join("reshell");+ let _ = fs::create_dir_all(&dir);+ dir.join("saver_hz.txt")+}++fn devmode() -> DEVMODEA {+ let mut dm: DEVMODEA = unsafe { std::mem::zeroed() };+ dm.dmSize = size_of::<DEVMODEA>() as u16;+ unsafe { EnumDisplaySettingsA(std::ptr::null(), ENUM_CURRENT_SETTINGS, &mut dm) };+ dm+}++fn get_hz() -> u32 { devmode().dmDisplayFrequency }++fn set_hz(hz: u32) -> bool {+ let mut dm = devmode();+ dm.dmDisplayFrequency = hz;+ dm.dmFields = DM_DISPLAYFREQUENCY;+ // CDS_TEST first so an unsupported rate never touches the display; flags 0 = this session only+ unsafe { ChangeDisplaySettingsA(&dm, CDS_TEST) == DISP_CHANGE_SUCCESSFUL && ChangeDisplaySettingsA(&dm, 0) == DISP_CHANGE_SUCCESSFUL }+}++fn powercfg(args: &[&str]) -> String {+ Command::new("powercfg").args(args).output().map(|o| String::from_utf8_lossy(&o.stdout).into_owned()).unwrap_or_default()+}++/// GUID of our scheme from `powercfg /l`, if it exists.+fn find_scheme() -> Option<String> {+ powercfg(&["/l"]).lines().find(|l| l.contains(NAME)).and_then(guid_in)+}++fn guid_in(s: &str) -> Option<String> {+ let i = s.find("GUID:")? + 5;+ s[i..].split_whitespace().next().map(str::to_owned)+}++pub fn run(on: bool) -> i32 {+ let existing = find_scheme();+ if !on {+ powercfg(&["/setactive", BALANCED]);+ if let Some(g) = existing { powercfg(&["/d", &g]); }+ if let Some(hz) = fs::read_to_string(hz_file()).ok().and_then(|s| s.trim().parse().ok()) {+ if set_hz(hz) { let _ = fs::remove_file(hz_file()); }+ }+ return 0;+ }+ let cur = get_hz();+ if cur != 60 {+ if !hz_file().exists() { let _ = fs::write(hz_file(), cur.to_string()); } // remember for 'off'+ if !set_hz(60) { eprintln!("60 Hz not supported on this display"); }+ }+ let mut kill = Command::new("taskkill");+ kill.arg("/F");+ for n in LAUNCHERS { kill.args(["/IM", &format!("{n}.exe")]); }+ let _ = kill.output(); // not running -> error exit, ignored on purpose++ let g = match existing.or_else(|| guid_in(&powercfg(&["/duplicatescheme", SAVER]))) {+ Some(g) => g,+ None => { eprintln!("could not create power scheme"); return 1; }+ };+ powercfg(&["/changename", &g, NAME, "Max battery life"]);+ // DC = on battery: CPU 40%, no turbo, passive cooling, screen off 1 min, sleep 10 min, brightness 20%+ for (sub, set, v) in [+ ("SUB_PROCESSOR", "PROCTHROTTLEMAX", "40"), ("SUB_PROCESSOR", "PERFBOOSTMODE", "0"), ("SUB_PROCESSOR", "SYSCOOLPOL", "0"),+ ("SUB_VIDEO", "VIDEOIDLE", "60"), ("SUB_SLEEP", "STANDBYIDLE", "600"), (SUB_VIDEO, BRIGHTNESS, "20"),+ ] {+ powercfg(&["/setdcvalueindex", &g, sub, set, v]);+ }+ powercfg(&["/setactive", &g]);+ 0+}++#[cfg(test)]+mod tests {+ #[test]+ fn parses_guid() {+ assert_eq!(super::guid_in("Power Scheme GUID: abc-123 (SuperSaver)").as_deref(), Some("abc-123"));+ assert_eq!(super::guid_in("nothing"), None);+ }+}diff --git a/ReShell/src/watchdog.rs b/ReShell/src/watchdog.rsnew file mode 100644index 0000000..61a4c0a--- /dev/null+++ b/ReShell/src/watchdog.rs@@ -0,0 +1,43 @@+//! Safety net for topbar: if the bar process is gone while the real taskbar is still hidden (crash, kill, bad boot),+//! the user would have no taskbar at all. reshell is already running from the Run key, so it watches and calls+//! `topbar.exe --restore`. shortcut: it restores the taskbar but does not restart the bar (a bar that crashes on+//! start would loop forever); upgrade if auto-restart is wanted.+use std::{os::windows::process::CommandExt, process::Command, thread, time::Duration};+use windows_sys::Win32::UI::WindowsAndMessaging::{FindWindowW, IsWindowVisible};++fn wide(s: &str) -> Vec<u16> {+ s.encode_utf16().chain([0]).collect()+}++/// Broken = no bar, and a taskbar that exists but is hidden.+fn broken(bar_up: bool, tray_present: bool, tray_visible: bool) -> bool {+ !bar_up && tray_present && !tray_visible+}++pub fn run() {+ let mut strikes = 0;+ loop {+ thread::sleep(Duration::from_secs(5));+ let (bar, tray) = unsafe { (FindWindowW(wide("topbar").as_ptr(), std::ptr::null()), FindWindowW(wide("Shell_TrayWnd").as_ptr(), std::ptr::null())) };+ let b = broken(!bar.is_null(), !tray.is_null(), !tray.is_null() && unsafe { IsWindowVisible(tray) } != 0);+ strikes = if b { strikes + 1 } else { 0 };+ if strikes == 2 {+ // two checks in a row (~10 s): a bar that is only just starting must not be "restored" under its feet+ if let Ok(exe) = std::env::current_exe() {+ let _ = Command::new(exe.with_file_name("topbar.exe")).arg("--restore").creation_flags(0x0800_0000).status();+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::broken;+ #[test]+ fn only_bar_gone_and_taskbar_hidden_is_broken() {+ assert!(broken(false, true, false));+ assert!(!broken(true, true, false)); // bar running: taskbar is meant to be hidden+ assert!(!broken(false, true, true)); // taskbar already back+ assert!(!broken(false, false, false)); // explorer restarting+ }+}diff --git a/app.manifest b/app.manifestnew file mode 100644index 0000000..f617f47--- /dev/null+++ b/app.manifest@@ -0,0 +1,14 @@+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">+ <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">+ <security><requestedPrivileges>+ <!-- installing services and disabling WSearch needs admin -->+ <requestedExecutionLevel level="requireAdministrator" uiAccess="false"/>+ </requestedPrivileges></security>+ </trustInfo>+ <application xmlns="urn:schemas-microsoft-com:asm.v3">+ <windowsSettings>+ <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>+ </windowsSettings>+ </application>+</assembly>diff --git a/app.rc b/app.rcnew file mode 100644index 0000000..8142754--- /dev/null+++ b/app.rc@@ -0,0 +1 @@+1 24 "app.manifest"diff --git a/assets/logo.svg b/assets/logo.svgnew file mode 100644index 0000000..cfb7521--- /dev/null+++ b/assets/logo.svg@@ -0,0 +1,50 @@+<svg version="1.1" viewBox="0 0 106 106" width="530" height="530" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">+<defs><clipPath id="right"><rect x="1" y="-60" width="59" height="120"/></clipPath></defs>+<rect width="106" height="106" fill="#fff"/>++<!-- Windows 11: left half (two left squares) -->+<rect x="3" y="3" width="48" height="48" fill="#0078D4"/>+<rect x="3" y="55" width="48" height="48" fill="#0078D4"/>++<!-- Rust (official artwork): right half only -->+<g transform="translate(53, 53)" clip-path="url(#right)">+ <path id="r" transform="translate(0.5, 0.5)" stroke="black" stroke-width="1" stroke-linejoin="round" d="+ M -9,-15 H 4 C 12,-15 12,-7 4,-7 H -9 Z+ M -40,22 H 0 V 11 H -9 V 3 H 1 C 12,3 6,22 15,22 H 40+ V 3 H 34 V 5 C 34,13 25,12 24,7 C 23,2 19,-2 18,-2 C 33,-10 24,-26 12,-26 H -35+ V -15 H -25 V 11 H -40 Z" />+ <g id="gear" mask="url(#holes)">+ <circle r="43" fill="none" stroke="black" stroke-width="9" />+ <g id="cogs">+ <polygon id="cog" stroke="black" stroke-width="3" stroke-linejoin="round" points="46,3 51,0 46,-3" />+ <use xlink:href="#cog" transform="rotate(11.25)" /><use xlink:href="#cog" transform="rotate(22.50)" />+ <use xlink:href="#cog" transform="rotate(33.75)" /><use xlink:href="#cog" transform="rotate(45.00)" />+ <use xlink:href="#cog" transform="rotate(56.25)" /><use xlink:href="#cog" transform="rotate(67.50)" />+ <use xlink:href="#cog" transform="rotate(78.75)" /><use xlink:href="#cog" transform="rotate(90.00)" />+ <use xlink:href="#cog" transform="rotate(101.25)" /><use xlink:href="#cog" transform="rotate(112.50)" />+ <use xlink:href="#cog" transform="rotate(123.75)" /><use xlink:href="#cog" transform="rotate(135.00)" />+ <use xlink:href="#cog" transform="rotate(146.25)" /><use xlink:href="#cog" transform="rotate(157.50)" />+ <use xlink:href="#cog" transform="rotate(168.75)" /><use xlink:href="#cog" transform="rotate(180.00)" />+ <use xlink:href="#cog" transform="rotate(191.25)" /><use xlink:href="#cog" transform="rotate(202.50)" />+ <use xlink:href="#cog" transform="rotate(213.75)" /><use xlink:href="#cog" transform="rotate(225.00)" />+ <use xlink:href="#cog" transform="rotate(236.25)" /><use xlink:href="#cog" transform="rotate(247.50)" />+ <use xlink:href="#cog" transform="rotate(258.75)" /><use xlink:href="#cog" transform="rotate(270.00)" />+ <use xlink:href="#cog" transform="rotate(281.25)" /><use xlink:href="#cog" transform="rotate(292.50)" />+ <use xlink:href="#cog" transform="rotate(303.75)" /><use xlink:href="#cog" transform="rotate(315.00)" />+ <use xlink:href="#cog" transform="rotate(326.25)" /><use xlink:href="#cog" transform="rotate(337.50)" />+ <use xlink:href="#cog" transform="rotate(348.75)" />+ </g>+ <g id="mounts">+ <polygon id="mount" stroke="black" stroke-width="6" stroke-linejoin="round" points="-7,-42 0,-35 7,-42" />+ <use xlink:href="#mount" transform="rotate(72)" /><use xlink:href="#mount" transform="rotate(144)" />+ <use xlink:href="#mount" transform="rotate(216)" /><use xlink:href="#mount" transform="rotate(288)" />+ </g>+ </g>+ <mask id="holes">+ <rect x="-60" y="-60" width="120" height="120" fill="white"/>+ <circle id="hole" cy="-40" r="3" />+ <use xlink:href="#hole" transform="rotate(72)" /><use xlink:href="#hole" transform="rotate(144)" />+ <use xlink:href="#hole" transform="rotate(216)" /><use xlink:href="#hole" transform="rotate(288)" />+ </mask>+</g>+</svg>diff --git a/assets/th.jpg b/assets/th.jpgnew file mode 100644index 0000000..bebfc99Binary files /dev/null and b/assets/th.jpg differdiff --git a/build.rs b/build.rsnew file mode 100644index 0000000..bc185be--- /dev/null+++ b/build.rs@@ -0,0 +1,6 @@+fn main() {+ println!("cargo:rerun-if-changed=app.rc");+ println!("cargo:rerun-if-changed=app.manifest");+ println!("cargo:rerun-if-changed=payload");+ embed_resource::compile("app.rc", embed_resource::NONE).manifest_required().unwrap();+}diff --git a/payload/STAMPS.txt b/payload/STAMPS.txtnew file mode 100644index 0000000..4a37a9c--- /dev/null+++ b/payload/STAMPS.txt@@ -0,0 +1,2 @@+rtaskmgr-win32 cc84f0f946ad+rust-search 32bcf0187ec9diff --git a/plugins/chrome-rs/.gitignore b/plugins/chrome-rs/.gitignorenew file mode 100644index 0000000..3383aee--- /dev/null+++ b/plugins/chrome-rs/.gitignore@@ -0,0 +1,5 @@+target/+corpus/out/+corpus/real/+corpus-m4/+corpus/real-old/diff --git a/plugins/chrome-rs/ARCHITECTURE.md b/plugins/chrome-rs/ARCHITECTURE.mdnew file mode 100644index 0000000..b9d8736--- /dev/null+++ b/plugins/chrome-rs/ARCHITECTURE.md@@ -0,0 +1,56 @@+# chrome-rs architecture++One process, one worker thread per page load, CPU rendering. Data flows one way:++```+load.rs fetch main HTML (manual redirects, cookies) -> dom.rs parse+ -> CSS/JS/images fetched in parallel (same-site cookies only)+ -> js.rs QuickJS runs scripts + timers (virtual time, 4 s CPU budget), DOM read back+ -> render.rs + css.rs cascade -> flat Item stream (words, boxes, tables, floats, flex, abs, inline-blocks)+ live pages: js.rs session thread (QuickJS stays alive) <-> UI events; DOM changes -> builder thread -> new Page+main.rs UI thread: layout.rs (Item stream -> Placed text/pictures/controls + background Rects) -> paint (gfx.rs)+snap.rs headless paint of the same pipeline for regression tests and timing+```++## Modules+| File | Role |+|------|------|+| `dom.rs` | HTML parser, arena DOM (`Dom`, `Node`), JSON round trip with JS |+| `css.rs` | Selector parser, `Sheet` (indexed rules), `compute()` cascade into `Style` (`Ext` holds non-inherited layout props) |+| `render.rs` | Styled DOM -> `Item` stream; forms/fields; tables; flex children; float/inline-block/absolute wrapping |+| `layout.rs` | Flow layout: lines, blocks, floats, tables, inline-block atoms, row/column flex, grid, relative/absolute/fixed positioning, paint layers (`z`), UAX #9 line reordering |+| `gfx.rs` | Fonts (fontdue for the main faces, ttf-parser outlines for coverage fallbacks), glyph cache, fill/blend/gradient/image/text/field painting |+| `js.rs` + `prelude.js` | QuickJS runtime and the JS-side DOM/BOM; natives for fetch, cookies, localStorage |+| `store.rs` | Cookie jar (RFC 6265 subset) and per-origin localStorage, persisted under the data dir |+| `load.rs` | Network pipeline, redirects, charset decoding, image decode |+| `snap.rs` | `--snap`, `--pdf`, `--corpus`, `--bench` command-line modes; PDF writer |+| `browse.rs` | Find-in-page, text selection, hit-testing, node boxes for JS (window-independent, unit-tested) |++## Decisions+- **Item stream, not a box tree.** Layout walks a flat list with Box/BoxEnd markers; floats, inline-blocks, absolutes and flex items are nested item lists laid out by recursive `block()` calls. Cheap and fast, but vertical padding/margins are folded into `Break` gaps, so `height`, vertical padding backgrounds and margin collapsing are approximate. Re-evaluate at the M3 checkpoint (Taffy/Stylo vs. own engine).+- **Live JS** (`js::start`): a dedicated thread owns the QuickJS runtime. Load phase = scripts + DOMContentLoaded/load + the first virtual second of timers; then real-time timers. The UI sends `Cmd`s (events, field values, scroll, resize, layout boxes); after each burst the whole DOM is serialized (throttled to ~16/s) and, if changed, sent to a builder thread that fetches new images (URL cache) and builds a `Page` (latest wins, ~12/s). Node ids are the pre-order positions of the last serialization, so UI hits map straight to JS elements. The UI merges the new page with the user's field edits (`merge_fields`: user text wins unless a script changed the value). `run` (offline/tests) keeps the old virtual-time-only behaviour.+- **Fonts**: `Fonts` holds regular/bold/italic sets for sans and mono, lazily loaded coverage fallbacks (kept as bytes, outlined per glyph through `ttf-parser`; their cmap coverage is cached so a font that lacks a character is not read again) and per-page web fonts keyed by a global family id (TTF, OTF, WOFF, WOFF2); complex scripts are shaped per word with rustybuzz; bidi follows UAX #9 at word granularity.+- **Cookies**: sent/stored for the main navigation and for subresources of the same site only (a cheap third-party block). `Expires` is ignored; only `Max-Age` cookies persist.+- **Data dir**: `CHROME_RS_DATA`, else `%APPDATA%\chrome-rs`, else `~/.chrome-rs` (`cookies.tsv`, `localstorage.json`).+- **CSS values**: custom properties resolve at cascade time (`Style.vars`, inherited); `calc()` is a (percent, px) linear form (`Len::Mix`), so `calc(100% - 20px)` works in widths but not in places that only take px.+- **Pseudo-elements** are matched by the same rules (`Compound.pseudo`) and rendered as inline words; only text `content` is supported.+- **Security**: file: URLs are readable only from top-level navigation and file: pages; cross-origin script requests need CORS approval (no preflight, so non-simple requests are blocked); cookies are same-site only for subresources.+- **Paint keys and stacking contexts**: every `Rect` and `Placed` has `z: i64`, up to four base-32768 digits with the outermost stacking context most significant (`zwrap` shifts an inner context's digits down one place and puts the outer digit on top). In-flow content is 0, a positioned box digit `4*z+2`, `fixed` adds digit 16383. `layout_vh` sorts both lists by `z` (stable), `layers` returns each key with its ranges, and the painters draw a layer's rectangles first, then its text. The viewport height that `bottom` of a fixed box refers to is passed to `layout_vh` (relayout when it changes). `fixed` and `sticky` items carry `st` (scroll offset from which they pin, 0 for fixed) and `lim` (how far a sticky box may travel before its container ends; open values are negative while laying out and closed by `close_lims`); before painting, `main.rs` moves them by `min(max(0, scroll - st), lim)` in page coordinates, so hit-testing needs no special case.+- **Boxes**: `BoxSpec` carries vertical padding (`pt/pb`), alpha, gradient, shadow and `clip`. The margin gap before a boxed element excludes its padding, which the box paints itself. `overflow` clipping only applies with an exact `height`; it drops content below the box at layout time.+- **Scroll containers and box markers**: a region with `overflow: auto|scroll` and a fixed height keeps its height, tags everything inside it with a group id (`grp`) and emits an invisible marker `Rect` (`a = 0`, `scroll` = content height); any other box without a background emits a marker with the node only. `layout::groups` lists the containers; `main.rs` keeps a scroll offset per container node, moves the group's items by it and paints them with `gfx::set_clip` set to the box (the clip is honoured by every low-level painter), then draws the thumb. Nested containers: an item moves with its innermost container only.+- **Column flex and grid** are separate `Item`s laid out by recursive `block()` calls like row flex; grid supports column tracks and spans only.+- **Interaction state**: `css::set_state(hover, active, focus)` (process-wide atomics) feeds `:hover/:active/:focus`; a `Page` whose CSS uses them keeps `Restyle { dom, imgs, base }` and `main.rs` calls `render::restyled` when the state changes (items, images and page background are replaced; fields keep the user's edits).+- **Background images** are downloaded by `collect_images` under the key `usize::MAX - element id` (`render::background_urls` finds them with a cheap cascade pass), become a `BgPaint` on the `BoxSpec`, are resolved to a tile size and offset in `layout::resolve_pic` and painted by `gfx::draw_pic`.+- **Percentage heights** resolve in `render.rs` against `Ctx::cb_h`, the nearest ancestor's definite height (root: 720 px); heights from a percentage never clip.+- **Counters** live in the render context (`counters` stack plus `glob` for implicit ones); `content` values carry `\u{1}name\u{2}sep\u{3}` markers that `render.rs` resolves.+- **Text**: UAX #14 splits words into pieces (`render::split_cjk`); a piece that ends in a soft hyphen gets a visible hyphen only when the line breaks after it. `layout::bidi_reorder` runs UAX #9 on the words of a line and reorders them; fallback fonts are read once as bytes and outlined per glyph.+- **Windows build tip**: use a short `CARGO_TARGET_DIR` (long paths break the linker).++## Testing+- `cargo test` — unit tests next to the code (cascade, layout, cookies, JS, forms).+- `chrome-rs --corpus corpus [--bless] [--budget PCT]` — renders `corpus/*.html` offline to `corpus/out/*.png` and compares with `corpus/golden/*.png` (default budget 0.5 % differing pixels). Goldens depend on system fonts: bless once per machine.+- `chrome-rs --snap page.html out.png [width]` — one page to PNG.+- `chrome-rs --bench corpus [runs]` — median build / layout / paint milliseconds per page.+- `chrome-rs --save corpus/real corpus/urls.txt [--force]` — loads each URL once over the network (cookies go to a scratch directory) and archives every GET response under `corpus/real/NNN-name/` (`load::set_archive`: `index.tsv` plus one `.bin` per response). `--corpus` replays these archives through the normal loader, never touching the network, and compares with `corpus/real/golden/`. While replaying, `Math.random` is a fixed generator. The archives are git-ignored.+- `corpus/urls.txt` — the URLs of the real-page corpus.+- `CHROME_RS_TIMING=1` prints load-phase timings; `CHROME_RS_DEBUG=1` prints the first laid-out items.diff --git a/plugins/chrome-rs/Cargo.lock b/plugins/chrome-rs/Cargo.locknew file mode 100644index 0000000..e03a487--- /dev/null+++ b/plugins/chrome-rs/Cargo.lock@@ -0,0 +1,2918 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "ab_glyph"+version = "0.2.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2"+dependencies = [+ "ab_glyph_rasterizer",+ "owned_ttf_parser",+]++[[package]]+name = "ab_glyph_rasterizer"+version = "0.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618"++[[package]]+name = "adler2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"++[[package]]+name = "ahash"+version = "0.8.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"+dependencies = [+ "cfg-if",+ "getrandom 0.3.4",+ "once_cell",+ "version_check",+ "zerocopy",+]++[[package]]+name = "alloc-no-stdlib"+version = "2.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"++[[package]]+name = "alloc-stdlib"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"+dependencies = [+ "alloc-no-stdlib",+]++[[package]]+name = "allocator-api2"+version = "0.2.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"++[[package]]+name = "android-activity"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd"+dependencies = [+ "android-properties",+ "bitflags 2.13.2",+ "cc",+ "jni",+ "libc",+ "log",+ "ndk",+ "ndk-context",+ "ndk-sys",+ "num_enum",+ "thiserror 2.0.21",+]++[[package]]+name = "android-properties"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04"++[[package]]+name = "arboard"+version = "3.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917"+dependencies = [+ "clipboard-win",+ "image",+ "log",+ "objc2 0.6.5",+ "objc2-app-kit 0.3.2",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-foundation 0.3.2",+ "parking_lot",+ "percent-encoding",+ "windows-sys 0.61.2",+ "x11rb",+]++[[package]]+name = "arrayref"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"++[[package]]+name = "arrayvec"+version = "0.7.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"++[[package]]+name = "as-raw-xcb-connection"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b"++[[package]]+name = "atomic-waker"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"++[[package]]+name = "autocfg"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"++[[package]]+name = "base64"+version = "0.23.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"++[[package]]+name = "bitflags"+version = "1.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"++[[package]]+name = "bitflags"+version = "2.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"++[[package]]+name = "bitvec"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837"+dependencies = [+ "funty",+ "radium",+ "tap",+ "wyz",+]++[[package]]+name = "block2"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f"+dependencies = [+ "objc2 0.5.3",+]++[[package]]+name = "brotli"+version = "7.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc97b8f16f944bba54f0433f07e30be199b6dc2bd25937444bbad560bcea29bd"+dependencies = [+ "alloc-no-stdlib",+ "alloc-stdlib",+ "brotli-decompressor 4.0.3",+]++[[package]]+name = "brotli-decompressor"+version = "4.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a334ef7c9e23abf0ce748e8cd309037da93e606ad52eb372e4ce327a0dcfbdfd"+dependencies = [+ "alloc-no-stdlib",+ "alloc-stdlib",+]++[[package]]+name = "brotli-decompressor"+version = "5.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"+dependencies = [+ "alloc-no-stdlib",+ "alloc-stdlib",+]++[[package]]+name = "bumpalo"+version = "3.20.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"++[[package]]+name = "bytemuck"+version = "1.25.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"+dependencies = [+ "bytemuck_derive",+]++[[package]]+name = "bytemuck_derive"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "byteorder-lite"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"++[[package]]+name = "bytes"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"++[[package]]+name = "calloop"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec"+dependencies = [+ "bitflags 2.13.2",+ "log",+ "polling",+ "rustix 0.38.44",+ "slab",+ "thiserror 1.0.69",+]++[[package]]+name = "calloop-wayland-source"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20"+dependencies = [+ "calloop",+ "rustix 0.38.44",+ "wayland-backend",+ "wayland-client",+]++[[package]]+name = "cc"+version = "1.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155"+dependencies = [+ "find-msvc-tools",+ "jobserver",+ "libc",+ "shlex",+]++[[package]]+name = "cfg-if"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"++[[package]]+name = "cfg_aliases"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"++[[package]]+name = "chrome-rs"+version = "0.1.0"+dependencies = [+ "ab_glyph_rasterizer",+ "arboard",+ "encoding_rs",+ "fontdue",+ "image",+ "miniz_oxide 0.8.9",+ "resvg",+ "rquickjs",+ "rustybuzz",+ "serde_json",+ "softbuffer",+ "ttf-parser",+ "unicode-bidi",+ "unicode-linebreak",+ "ureq",+ "winit",+ "woff2-patched",+]++[[package]]+name = "clipboard-win"+version = "5.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a"+dependencies = [+ "error-code",+]++[[package]]+name = "color_quant"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"++[[package]]+name = "combine"+version = "4.6.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92"+dependencies = [+ "bytes",+ "memchr",+]++[[package]]+name = "concurrent-queue"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "core-foundation"+version = "0.9.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "core-foundation-sys"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"++[[package]]+name = "core-graphics"+version = "0.23.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081"+dependencies = [+ "bitflags 1.3.2",+ "core-foundation",+ "core-graphics-types",+ "foreign-types",+ "libc",+]++[[package]]+name = "core-graphics-types"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf"+dependencies = [+ "bitflags 1.3.2",+ "core-foundation",+ "libc",+]++[[package]]+name = "core_detect"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"++[[package]]+name = "core_maths"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30"+dependencies = [+ "libm",+]++[[package]]+name = "crc32fast"+version = "1.5.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"+dependencies = [+ "cfg-if",+]++[[package]]+name = "crossbeam-utils"+version = "0.8.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"++[[package]]+name = "crunchy"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"++[[package]]+name = "ctor"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "83cf0d42651b16c6dfe68685716d18480d18a9c39c62d76e8cf3eb6ed5d8bcbf"+dependencies = [+ "dtor",+]++[[package]]+name = "cursor-icon"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"++[[package]]+name = "data-url"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"++[[package]]+name = "dispatch"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b"++[[package]]+name = "dispatch2"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"+dependencies = [+ "bitflags 2.13.2",+ "objc2 0.6.5",+]++[[package]]+name = "dlib"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a"+dependencies = [+ "libloading",+]++[[package]]+name = "downcast-rs"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"++[[package]]+name = "dpi"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"++[[package]]+name = "drm"+version = "0.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "80bc8c5c6c2941f70a55c15f8d9f00f9710ebda3ffda98075f996a0e6c92756f"+dependencies = [+ "bitflags 2.13.2",+ "bytemuck",+ "drm-ffi",+ "drm-fourcc",+ "libc",+ "rustix 0.38.44",+]++[[package]]+name = "drm-ffi"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "51a91c9b32ac4e8105dec255e849e0d66e27d7c34d184364fb93e469db08f690"+dependencies = [+ "drm-sys",+ "rustix 1.1.6",+]++[[package]]+name = "drm-fourcc"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0aafbcdb8afc29c1a7ee5fbe53b5d62f4565b35a042a662ca9fecd0b54dae6f4"++[[package]]+name = "drm-sys"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ecc8e1361066d91f5ffccff060a3c3be9c3ecde15be2959c1937595f7a82a9f8"+dependencies = [+ "libc",+ "linux-raw-sys 0.9.4",+]++[[package]]+name = "dtor"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "edf234dd1594d6dd434a8fb8cada51ddbbc593e40e4a01556a0b31c62da2775b"++[[package]]+name = "encoding_rs"+version = "0.8.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5"+dependencies = [+ "cfg-if",+ "core_detect",+ "multiversion_no_op",+ "rustversion",+ "scopeguard",+ "simdutf8",+]++[[package]]+name = "equivalent"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"++[[package]]+name = "errno"+version = "0.3.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]++[[package]]+name = "error-code"+version = "3.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7"++[[package]]+name = "euclid"+version = "0.22.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06"+dependencies = [+ "num-traits",+]++[[package]]+name = "fastrand"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"++[[package]]+name = "fax"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a"++[[package]]+name = "fdeflate"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"+dependencies = [+ "simd-adler32",+]++[[package]]+name = "find-msvc-tools"+version = "0.1.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"++[[package]]+name = "flate2"+version = "1.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"+dependencies = [+ "crc32fast",+ "miniz_oxide 0.9.1",+ "zlib-rs",+]++[[package]]+name = "float-cmp"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"++[[package]]+name = "foldhash"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"++[[package]]+name = "foldhash"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"++[[package]]+name = "fontdue"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e796cb6894e6418daacea84b28dd4f98d3b32c74d5bb452ba1ecfbf5ad8e84ca"+dependencies = [+ "hashbrown 0.15.5",+ "ttf-parser",+]++[[package]]+name = "foreign-types"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"+dependencies = [+ "foreign-types-macros",+ "foreign-types-shared",+]++[[package]]+name = "foreign-types-macros"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "foreign-types-shared"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"++[[package]]+name = "four-cc"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "795cbfc56d419a7ce47ccbb7504dd9a5b7c484c083c356e797de08bd988d9629"++[[package]]+name = "funty"+version = "2.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"++[[package]]+name = "futures-core"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"++[[package]]+name = "futures-task"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"++[[package]]+name = "futures-util"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"+dependencies = [+ "futures-core",+ "futures-task",+ "pin-project-lite",+ "slab",+]++[[package]]+name = "gethostname"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"+dependencies = [+ "rustix 1.1.6",+ "windows-link",+]++[[package]]+name = "getrandom"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"+dependencies = [+ "cfg-if",+ "libc",+ "wasi",+]++[[package]]+name = "getrandom"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi 5.3.0",+ "wasip2",+]++[[package]]+name = "getrandom"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi 6.0.0",+]++[[package]]+name = "gif"+version = "0.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"+dependencies = [+ "color_quant",+ "weezl",+]++[[package]]+name = "half"+version = "2.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"+dependencies = [+ "cfg-if",+ "crunchy",+ "zerocopy",+]++[[package]]+name = "hashbrown"+version = "0.15.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"+dependencies = [+ "allocator-api2",+ "equivalent",+ "foldhash 0.1.5",+]++[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"+dependencies = [+ "allocator-api2",+ "equivalent",+ "foldhash 0.2.0",+]++[[package]]+name = "hermit-abi"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"++[[package]]+name = "http"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"+dependencies = [+ "bytes",+ "itoa",+]++[[package]]+name = "httparse"+version = "1.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"++[[package]]+name = "image"+version = "0.25.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"+dependencies = [+ "bytemuck",+ "byteorder-lite",+ "color_quant",+ "gif",+ "image-webp",+ "moxcms",+ "num-traits",+ "png",+ "tiff",+ "zune-core",+ "zune-jpeg",+]++[[package]]+name = "image-webp"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"+dependencies = [+ "byteorder-lite",+ "quick-error",+]++[[package]]+name = "imagesize"+version = "0.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65b27460c2c92b037f3f94c538ed9a3342f3fdf923606781629ccb35f82d042a"++[[package]]+name = "indexmap"+version = "2.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"+dependencies = [+ "equivalent",+ "hashbrown 0.17.1",+]++[[package]]+name = "itoa"+version = "1.0.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"++[[package]]+name = "jni"+version = "0.22.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"+dependencies = [+ "cfg-if",+ "combine",+ "jni-macros",+ "jni-sys 0.4.1",+ "log",+ "simd_cesu8",+ "thiserror 2.0.21",+ "walkdir",+ "windows-link",+]++[[package]]+name = "jni-macros"+version = "0.22.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"+dependencies = [+ "proc-macro2",+ "quote",+ "rustc_version",+ "simd_cesu8",+ "syn 2.0.119",+]++[[package]]+name = "jni-sys"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"+dependencies = [+ "jni-sys 0.4.1",+]++[[package]]+name = "jni-sys"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"+dependencies = [+ "jni-sys-macros",+]++[[package]]+name = "jni-sys-macros"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"+dependencies = [+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "jobserver"+version = "0.1.35"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"+dependencies = [+ "getrandom 0.4.3",+ "libc",+]++[[package]]+name = "js-sys"+version = "0.3.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a"+dependencies = [+ "cfg-if",+ "futures-util",+ "wasm-bindgen",+]++[[package]]+name = "kurbo"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2"+dependencies = [+ "arrayvec",+ "euclid",+ "polycool",+ "smallvec",+]++[[package]]+name = "libc"+version = "0.2.191"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"++[[package]]+name = "libloading"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"+dependencies = [+ "cfg-if",+ "windows-link",+]++[[package]]+name = "libm"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"++[[package]]+name = "libredox"+version = "0.1.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d"+dependencies = [+ "bitflags 2.13.2",+ "libc",+ "plain",+ "redox_syscall 0.9.5",+]++[[package]]+name = "linux-raw-sys"+version = "0.4.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"++[[package]]+name = "linux-raw-sys"+version = "0.9.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12"++[[package]]+name = "linux-raw-sys"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"++[[package]]+name = "lock_api"+version = "0.4.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"+dependencies = [+ "scopeguard",+]++[[package]]+name = "log"+version = "0.4.35"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "memmap2"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157"+dependencies = [+ "libc",+]++[[package]]+name = "miniz_oxide"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"+dependencies = [+ "adler2",+ "simd-adler32",+]++[[package]]+name = "miniz_oxide"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"+dependencies = [+ "adler2",+ "simd-adler32",+]++[[package]]+name = "moxcms"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"+dependencies = [+ "num-traits",+ "pxfm",+]++[[package]]+name = "multiversion_no_op"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d"++[[package]]+name = "ndk"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"+dependencies = [+ "bitflags 2.13.2",+ "jni-sys 0.3.1",+ "log",+ "ndk-sys",+ "num_enum",+ "raw-window-handle",+ "thiserror 1.0.69",+]++[[package]]+name = "ndk-context"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"++[[package]]+name = "ndk-sys"+version = "0.6.0+11769913"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873"+dependencies = [+ "jni-sys 0.3.1",+]++[[package]]+name = "num-traits"+version = "0.2.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"+dependencies = [+ "autocfg",+]++[[package]]+name = "num_enum"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26"+dependencies = [+ "num_enum_derive",+ "rustversion",+]++[[package]]+name = "num_enum_derive"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"+dependencies = [+ "proc-macro-crate",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "objc-sys"+version = "0.3.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310"++[[package]]+name = "objc2"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "19d5490aaf8f1d7cf7688dfa9b0ce07900e168852c45cd2c03f534dfd27cfd0b"+dependencies = [+ "objc-sys",+ "objc2-encode",+]++[[package]]+name = "objc2"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"+dependencies = [+ "objc2-encode",+]++[[package]]+name = "objc2-app-kit"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "libc",+ "objc2 0.5.3",+ "objc2-core-data",+ "objc2-core-image",+ "objc2-foundation 0.2.2",+ "objc2-quartz-core 0.2.2",+]++[[package]]+name = "objc2-app-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"+dependencies = [+ "bitflags 2.13.2",+ "objc2 0.6.5",+ "objc2-core-graphics",+ "objc2-foundation 0.3.2",+]++[[package]]+name = "objc2-cloud-kit"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "objc2 0.5.3",+ "objc2-core-location",+ "objc2-foundation 0.2.2",+]++[[package]]+name = "objc2-contacts"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889"+dependencies = [+ "block2",+ "objc2 0.5.3",+ "objc2-foundation 0.2.2",+]++[[package]]+name = "objc2-core-data"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "objc2 0.5.3",+ "objc2-foundation 0.2.2",+]++[[package]]+name = "objc2-core-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"+dependencies = [+ "bitflags 2.13.2",+ "dispatch2",+ "objc2 0.6.5",+]++[[package]]+name = "objc2-core-graphics"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"+dependencies = [+ "bitflags 2.13.2",+ "dispatch2",+ "objc2 0.6.5",+ "objc2-core-foundation",+ "objc2-io-surface",+]++[[package]]+name = "objc2-core-image"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80"+dependencies = [+ "block2",+ "objc2 0.5.3",+ "objc2-foundation 0.2.2",+ "objc2-metal",+]++[[package]]+name = "objc2-core-location"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781"+dependencies = [+ "block2",+ "objc2 0.5.3",+ "objc2-contacts",+ "objc2-foundation 0.2.2",+]++[[package]]+name = "objc2-encode"+version = "4.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"++[[package]]+name = "objc2-foundation"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "dispatch",+ "libc",+ "objc2 0.5.3",+]++[[package]]+name = "objc2-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"+dependencies = [+ "bitflags 2.13.2",+ "objc2 0.6.5",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-io-surface"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"+dependencies = [+ "bitflags 2.13.2",+ "objc2 0.6.5",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-link-presentation"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398"+dependencies = [+ "block2",+ "objc2 0.5.3",+ "objc2-app-kit 0.2.2",+ "objc2-foundation 0.2.2",+]++[[package]]+name = "objc2-metal"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "objc2 0.5.3",+ "objc2-foundation 0.2.2",+]++[[package]]+name = "objc2-quartz-core"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "objc2 0.5.3",+ "objc2-foundation 0.2.2",+ "objc2-metal",+]++[[package]]+name = "objc2-quartz-core"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"+dependencies = [+ "bitflags 2.13.2",+ "objc2 0.6.5",+ "objc2-core-foundation",+ "objc2-foundation 0.3.2",+]++[[package]]+name = "objc2-symbols"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc"+dependencies = [+ "objc2 0.5.3",+ "objc2-foundation 0.2.2",+]++[[package]]+name = "objc2-ui-kit"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "objc2 0.5.3",+ "objc2-cloud-kit",+ "objc2-core-data",+ "objc2-core-image",+ "objc2-core-location",+ "objc2-foundation 0.2.2",+ "objc2-link-presentation",+ "objc2-quartz-core 0.2.2",+ "objc2-symbols",+ "objc2-uniform-type-identifiers",+ "objc2-user-notifications",+]++[[package]]+name = "objc2-uniform-type-identifiers"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe"+dependencies = [+ "block2",+ "objc2 0.5.3",+ "objc2-foundation 0.2.2",+]++[[package]]+name = "objc2-user-notifications"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "objc2 0.5.3",+ "objc2-core-location",+ "objc2-foundation 0.2.2",+]++[[package]]+name = "once_cell"+version = "1.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"++[[package]]+name = "orbclient"+version = "0.3.55"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5df339f526ea9a60e371768d50efc2f2508c7203290731565d1f7a6f71d21747"+dependencies = [+ "libc",+ "libredox",+]++[[package]]+name = "owned_ttf_parser"+version = "0.25.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b"+dependencies = [+ "ttf-parser",+]++[[package]]+name = "parking_lot"+version = "0.12.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"+dependencies = [+ "lock_api",+ "parking_lot_core",+]++[[package]]+name = "parking_lot_core"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"+dependencies = [+ "cfg-if",+ "libc",+ "redox_syscall 0.5.18",+ "smallvec",+ "windows-link",+]++[[package]]+name = "paste"+version = "1.0.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"++[[package]]+name = "percent-encoding"+version = "2.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"++[[package]]+name = "pico-args"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315"++[[package]]+name = "pin-project"+version = "1.1.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924"+dependencies = [+ "pin-project-internal",+]++[[package]]+name = "pin-project-internal"+version = "1.1.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "pin-project-lite"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"++[[package]]+name = "pkg-config"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"++[[package]]+name = "plain"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"++[[package]]+name = "png"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"+dependencies = [+ "bitflags 2.13.2",+ "crc32fast",+ "fdeflate",+ "flate2",+ "miniz_oxide 0.8.9",+]++[[package]]+name = "polling"+version = "3.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"+dependencies = [+ "cfg-if",+ "concurrent-queue",+ "hermit-abi",+ "pin-project-lite",+ "rustix 1.1.6",+ "windows-sys 0.61.2",+]++[[package]]+name = "polycool"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6"+dependencies = [+ "arrayvec",+]++[[package]]+name = "proc-macro-crate"+version = "3.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"+dependencies = [+ "toml_edit",+]++[[package]]+name = "proc-macro2"+version = "1.0.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "pxfm"+version = "0.1.30"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"++[[package]]+name = "quick-error"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"++[[package]]+name = "quick-xml"+version = "0.41.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1"+dependencies = [+ "memchr",+]++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "r-efi"+version = "5.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"++[[package]]+name = "r-efi"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"++[[package]]+name = "radium"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09"++[[package]]+name = "raw-window-handle"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"++[[package]]+name = "redox_syscall"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa"+dependencies = [+ "bitflags 1.3.2",+]++[[package]]+name = "redox_syscall"+version = "0.5.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "redox_syscall"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "relative-path"+version = "2.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38540a682c6e9bca04a8bca9e5ec5a6ba168dfbb04c9998fe517a9befb92eb68"+dependencies = [+ "serde_core",+]++[[package]]+name = "resvg"+version = "0.50.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77bb4b284cf8a5c8ae721594af53387fb755d2196fddb32b2acfb4fa9251fa0c"+dependencies = [+ "bytemuck",+ "log",+ "pico-args",+ "rgb",+ "svgtypes",+ "tiny-skia 0.12.0",+ "usvg",+]++[[package]]+name = "rgb"+version = "0.8.53"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4"+dependencies = [+ "bytemuck",+]++[[package]]+name = "ring"+version = "0.17.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"+dependencies = [+ "cc",+ "cfg-if",+ "getrandom 0.2.17",+ "libc",+ "untrusted",+ "windows-sys 0.52.0",+]++[[package]]+name = "roxmltree"+version = "0.21.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907"+dependencies = [+ "memchr",+]++[[package]]+name = "rquickjs"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a0a22bf72f515cc4189dd7c63d016f6de92a11eee98ddf7dd64794198f6eb34e"+dependencies = [+ "rquickjs-core",+]++[[package]]+name = "rquickjs-core"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6657979a24d543e5fc66f32cef2f47ca82ce8eb55cec5f7d59a12b7b570bbf24"+dependencies = [+ "hashbrown 0.17.1",+ "relative-path",+ "rquickjs-sys",+]++[[package]]+name = "rquickjs-sys"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cee271d0eeba64f0915b846cb7ae02e16faf3dfdffdca91731101d9d30fe3423"+dependencies = [+ "cc",+]++[[package]]+name = "rustc_version"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"+dependencies = [+ "semver",+]++[[package]]+name = "rustix"+version = "0.38.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"+dependencies = [+ "bitflags 2.13.2",+ "errno",+ "libc",+ "linux-raw-sys 0.4.15",+ "windows-sys 0.52.0",+]++[[package]]+name = "rustix"+version = "1.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"+dependencies = [+ "bitflags 2.13.2",+ "errno",+ "libc",+ "linux-raw-sys 0.12.1",+ "windows-sys 0.61.2",+]++[[package]]+name = "rustls"+version = "0.23.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"+dependencies = [+ "log",+ "once_cell",+ "ring",+ "rustls-pki-types",+ "rustls-webpki",+ "subtle",+ "zeroize",+]++[[package]]+name = "rustls-pki-types"+version = "1.16.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb"+dependencies = [+ "zeroize",+]++[[package]]+name = "rustls-webpki"+version = "0.103.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5"+dependencies = [+ "ring",+ "rustls-pki-types",+ "untrusted",+]++[[package]]+name = "rustversion"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"++[[package]]+name = "rustybuzz"+version = "0.20.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702"+dependencies = [+ "bitflags 2.13.2",+ "bytemuck",+ "core_maths",+ "log",+ "smallvec",+ "ttf-parser",+ "unicode-bidi-mirroring",+ "unicode-ccc",+ "unicode-properties",+ "unicode-script",+]++[[package]]+name = "safer-bytes"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9814c78d534f27a438fcb57091d6deed0634b60e4e500fee28fe5990adf5ea54"+dependencies = [+ "bytes",+ "paste",+ "thiserror 1.0.69",+]++[[package]]+name = "same-file"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"+dependencies = [+ "winapi-util",+]++[[package]]+name = "scoped-tls"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294"++[[package]]+name = "scopeguard"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"++[[package]]+name = "sctk-adwaita"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec"+dependencies = [+ "ab_glyph",+ "log",+ "memmap2",+ "smithay-client-toolkit",+ "tiny-skia 0.11.4",+]++[[package]]+name = "semver"+version = "1.0.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"++[[package]]+name = "serde"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"+dependencies = [+ "serde_core",+]++[[package]]+name = "serde_core"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "serde_json"+version = "1.0.154"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"+dependencies = [+ "itoa",+ "memchr",+ "serde",+ "serde_core",+ "zmij",+]++[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"++[[package]]+name = "simd-adler32"+version = "0.3.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"++[[package]]+name = "simd_cesu8"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"+dependencies = [+ "rustc_version",+ "simdutf8",+]++[[package]]+name = "simdutf8"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"++[[package]]+name = "simplecss"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c"+dependencies = [+ "log",+]++[[package]]+name = "siphasher"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"++[[package]]+name = "slab"+version = "0.4.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"++[[package]]+name = "smallvec"+version = "1.16.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46"++[[package]]+name = "smithay-client-toolkit"+version = "0.19.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016"+dependencies = [+ "bitflags 2.13.2",+ "calloop",+ "calloop-wayland-source",+ "cursor-icon",+ "libc",+ "log",+ "memmap2",+ "rustix 0.38.44",+ "thiserror 1.0.69",+ "wayland-backend",+ "wayland-client",+ "wayland-csd-frame",+ "wayland-cursor",+ "wayland-protocols",+ "wayland-protocols-wlr",+ "wayland-scanner",+ "xkeysym",+]++[[package]]+name = "smol_str"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead"+dependencies = [+ "serde",+]++[[package]]+name = "softbuffer"+version = "0.4.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aac18da81ebbf05109ab275b157c22a653bb3c12cf884450179942f81bcbf6c3"+dependencies = [+ "as-raw-xcb-connection",+ "bytemuck",+ "drm",+ "fastrand",+ "js-sys",+ "memmap2",+ "ndk",+ "objc2 0.6.5",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-foundation 0.3.2",+ "objc2-quartz-core 0.3.2",+ "raw-window-handle",+ "redox_syscall 0.5.18",+ "rustix 1.1.6",+ "tiny-xlib",+ "tracing",+ "wasm-bindgen",+ "wayland-backend",+ "wayland-client",+ "wayland-sys",+ "web-sys",+ "windows-sys 0.61.2",+ "x11rb",+]++[[package]]+name = "strict-num"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"+dependencies = [+ "float-cmp",+]++[[package]]+name = "subtle"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"++[[package]]+name = "svgtypes"+version = "0.16.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f12b12995e3638c70618c1facb1ce65302f6a6f706b675f07c58a5d7391120e"+dependencies = [+ "kurbo",+ "siphasher",+]++[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "syn"+version = "3.0.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "tap"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"++[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl 1.0.69",+]++[[package]]+name = "thiserror"+version = "2.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"+dependencies = [+ "thiserror-impl 2.0.21",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "thiserror-impl"+version = "2.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "tiff"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52"+dependencies = [+ "fax",+ "flate2",+ "half",+ "quick-error",+ "weezl",+ "zune-jpeg",+]++[[package]]+name = "tiny-skia"+version = "0.11.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab"+dependencies = [+ "arrayref",+ "arrayvec",+ "bytemuck",+ "cfg-if",+ "log",+ "tiny-skia-path 0.11.4",+]++[[package]]+name = "tiny-skia"+version = "0.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47ffee5eaaf5527f630fb0e356b90ebdec84d5d18d937c5e440350f88c5a91ea"+dependencies = [+ "arrayref",+ "arrayvec",+ "bytemuck",+ "cfg-if",+ "log",+ "png",+ "tiny-skia-path 0.12.0",+]++[[package]]+name = "tiny-skia-path"+version = "0.11.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93"+dependencies = [+ "arrayref",+ "bytemuck",+ "strict-num",+]++[[package]]+name = "tiny-skia-path"+version = "0.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "edca365c3faccca67d06593c5980fa6c57687de727a03131735bb85f01fdeeb9"+dependencies = [+ "arrayref",+ "bytemuck",+ "strict-num",+]++[[package]]+name = "tiny-xlib"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a90a0ca3ee6a69f2ad28fd11621a4c3f03b371f366be500b64df260c4ffbafb4"+dependencies = [+ "as-raw-xcb-connection",+ "ctor",+ "libloading",+ "pkg-config",+ "tracing",+]++[[package]]+name = "tokio"+version = "1.54.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"+dependencies = [+ "pin-project-lite",+]++[[package]]+name = "toml_datetime"+version = "1.1.3+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"+dependencies = [+ "serde_core",+]++[[package]]+name = "toml_edit"+version = "0.25.19+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218"+dependencies = [+ "indexmap",+ "toml_datetime",+ "toml_parser",+ "winnow",+]++[[package]]+name = "toml_parser"+version = "1.1.5+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"+dependencies = [+ "winnow",+]++[[package]]+name = "tracing"+version = "0.1.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"+dependencies = [+ "pin-project-lite",+ "tracing-core",+]++[[package]]+name = "tracing-core"+version = "0.1.36"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"++[[package]]+name = "ttf-parser"+version = "0.25.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"+dependencies = [+ "core_maths",+]++[[package]]+name = "unicode-bidi"+version = "0.3.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"++[[package]]+name = "unicode-bidi-mirroring"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5dfa6e8c60bb66d49db113e0125ee8711b7647b5579dc7f5f19c42357ed039fe"++[[package]]+name = "unicode-ccc"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ce61d488bcdc9bc8b5d1772c404828b17fc481c0a582b5581e95fb233aef503e"++[[package]]+name = "unicode-ident"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"++[[package]]+name = "unicode-linebreak"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f"++[[package]]+name = "unicode-properties"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833"++[[package]]+name = "unicode-script"+version = "0.5.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa04c955db05429d464c74d495c1ee677e1866e783a4c3747f9c0cef7756cabf"++[[package]]+name = "unicode-segmentation"+version = "1.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"++[[package]]+name = "untrusted"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"++[[package]]+name = "ureq"+version = "3.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d"+dependencies = [+ "base64",+ "brotli-decompressor 5.0.3",+ "flate2",+ "log",+ "percent-encoding",+ "rustls",+ "rustls-pki-types",+ "ureq-proto",+ "utf8-zero",+ "webpki-roots",+]++[[package]]+name = "ureq-proto"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3"+dependencies = [+ "base64",+ "http",+ "httparse",+ "log",+]++[[package]]+name = "usvg"+version = "0.50.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bdb896f04730b97805bbc3191fc57e4bf03face0f14577dd42e783c4d8c98802"+dependencies = [+ "data-url",+ "imagesize",+ "kurbo",+ "log",+ "pico-args",+ "roxmltree",+ "simplecss",+ "siphasher",+ "strict-num",+ "svgtypes",+ "tiny-skia-path 0.12.0",+]++[[package]]+name = "utf8-zero"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"++[[package]]+name = "version_check"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"++[[package]]+name = "walkdir"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"+dependencies = [+ "same-file",+ "winapi-util",+]++[[package]]+name = "wasi"+version = "0.11.1+wasi-snapshot-preview1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"++[[package]]+name = "wasip2"+version = "1.0.4+wasi-0.2.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"+dependencies = [+ "wit-bindgen",+]++[[package]]+name = "wasm-bindgen"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c"+dependencies = [+ "cfg-if",+ "rustversion",+ "wasm-bindgen-macro",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-futures"+version = "0.4.80"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501"+dependencies = [+ "js-sys",+ "tokio",+ "wasm-bindgen",+]++[[package]]+name = "wasm-bindgen-macro"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9"+dependencies = [+ "quote",+ "wasm-bindgen-macro-support",+]++[[package]]+name = "wasm-bindgen-macro-support"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a"+dependencies = [+ "bumpalo",+ "proc-macro2",+ "quote",+ "syn 3.0.10",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-shared"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "wayland-backend"+version = "0.3.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078"+dependencies = [+ "cc",+ "downcast-rs",+ "rustix 1.1.6",+ "scoped-tls",+ "smallvec",+ "wayland-sys",+]++[[package]]+name = "wayland-client"+version = "0.31.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073"+dependencies = [+ "bitflags 2.13.2",+ "rustix 1.1.6",+ "wayland-backend",+ "wayland-scanner",+]++[[package]]+name = "wayland-csd-frame"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e"+dependencies = [+ "bitflags 2.13.2",+ "cursor-icon",+ "wayland-backend",+]++[[package]]+name = "wayland-cursor"+version = "0.31.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d"+dependencies = [+ "rustix 1.1.6",+ "wayland-client",+ "xcursor",+]++[[package]]+name = "wayland-protocols"+version = "0.32.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6"+dependencies = [+ "bitflags 2.13.2",+ "wayland-backend",+ "wayland-client",+ "wayland-scanner",+]++[[package]]+name = "wayland-protocols-plasma"+version = "0.3.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91"+dependencies = [+ "bitflags 2.13.2",+ "wayland-backend",+ "wayland-client",+ "wayland-protocols",+ "wayland-scanner",+]++[[package]]+name = "wayland-protocols-wlr"+version = "0.3.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234"+dependencies = [+ "bitflags 2.13.2",+ "wayland-backend",+ "wayland-client",+ "wayland-protocols",+ "wayland-scanner",+]++[[package]]+name = "wayland-scanner"+version = "0.31.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"+dependencies = [+ "proc-macro2",+ "quick-xml",+ "quote",+]++[[package]]+name = "wayland-sys"+version = "0.31.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be"+dependencies = [+ "dlib",+ "log",+ "once_cell",+ "pkg-config",+]++[[package]]+name = "web-sys"+version = "0.3.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "web-time"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "webpki-roots"+version = "1.0.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297"+dependencies = [+ "rustls-pki-types",+]++[[package]]+name = "weezl"+version = "0.1.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"++[[package]]+name = "winapi-util"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-sys"+version = "0.52.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"+dependencies = [+ "windows-targets",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-targets"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"+dependencies = [+ "windows_aarch64_gnullvm",+ "windows_aarch64_msvc",+ "windows_i686_gnu",+ "windows_i686_gnullvm",+ "windows_i686_msvc",+ "windows_x86_64_gnu",+ "windows_x86_64_gnullvm",+ "windows_x86_64_msvc",+]++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"++[[package]]+name = "windows_aarch64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"++[[package]]+name = "windows_i686_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"++[[package]]+name = "windows_i686_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"++[[package]]+name = "windows_i686_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"++[[package]]+name = "windows_x86_64_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"++[[package]]+name = "windows_x86_64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"++[[package]]+name = "winit"+version = "0.30.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d"+dependencies = [+ "ahash",+ "android-activity",+ "atomic-waker",+ "bitflags 2.13.2",+ "block2",+ "bytemuck",+ "calloop",+ "cfg_aliases",+ "concurrent-queue",+ "core-foundation",+ "core-graphics",+ "cursor-icon",+ "dpi",+ "js-sys",+ "libc",+ "memmap2",+ "ndk",+ "objc2 0.5.3",+ "objc2-app-kit 0.2.2",+ "objc2-foundation 0.2.2",+ "objc2-ui-kit",+ "orbclient",+ "percent-encoding",+ "pin-project",+ "raw-window-handle",+ "redox_syscall 0.4.1",+ "rustix 0.38.44",+ "sctk-adwaita",+ "smithay-client-toolkit",+ "smol_str",+ "tracing",+ "unicode-segmentation",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "wayland-backend",+ "wayland-client",+ "wayland-protocols",+ "wayland-protocols-plasma",+ "web-sys",+ "web-time",+ "windows-sys 0.52.0",+ "x11-dl",+ "x11rb",+ "xkbcommon-dl",+]++[[package]]+name = "winnow"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"+dependencies = [+ "memchr",+]++[[package]]+name = "wit-bindgen"+version = "0.57.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"++[[package]]+name = "woff2-patched"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb9e0d17aedee2afac15749407e107edce8485f57b7ad9fb929f0bbdf2c28f24"+dependencies = [+ "bitvec",+ "brotli",+ "bytes",+ "four-cc",+ "safer-bytes",+ "thiserror 1.0.69",+]++[[package]]+name = "wyz"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed"+dependencies = [+ "tap",+]++[[package]]+name = "x11-dl"+version = "2.21.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f"+dependencies = [+ "libc",+ "once_cell",+ "pkg-config",+]++[[package]]+name = "x11rb"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414"+dependencies = [+ "as-raw-xcb-connection",+ "gethostname",+ "libc",+ "libloading",+ "once_cell",+ "rustix 1.1.6",+ "x11rb-protocol",+]++[[package]]+name = "x11rb-protocol"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"++[[package]]+name = "xcursor"+version = "0.3.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23"++[[package]]+name = "xkbcommon-dl"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5"+dependencies = [+ "bitflags 2.13.2",+ "dlib",+ "log",+ "once_cell",+ "xkeysym",+]++[[package]]+name = "xkeysym"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"++[[package]]+name = "zerocopy"+version = "0.8.63"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8"+dependencies = [+ "zerocopy-derive",+]++[[package]]+name = "zerocopy-derive"+version = "0.8.63"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "zeroize"+version = "1.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"++[[package]]+name = "zlib-rs"+version = "0.6.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"++[[package]]+name = "zmij"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"++[[package]]+name = "zune-core"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"++[[package]]+name = "zune-jpeg"+version = "0.5.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"+dependencies = [+ "zune-core",+]diff --git a/plugins/chrome-rs/Cargo.toml b/plugins/chrome-rs/Cargo.tomlnew file mode 100644index 0000000..6f3e475--- /dev/null+++ b/plugins/chrome-rs/Cargo.toml@@ -0,0 +1,29 @@+[package]+name = "chrome-rs"+version = "0.1.0"+edition = "2024"++[profile.release]+lto = true+codegen-units = 1+strip = true++[dependencies]+arboard = "3.7.0"+encoding_rs = "0.8.44"+fontdue = "0.9.5"+miniz_oxide = "0.8"+image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "gif", "webp"] }+resvg = { version = "0.50.0", default-features = false }+rquickjs = { version = "0.14.0", features = ["loader"] }+serde_json = "1.0.154"+softbuffer = "0.4.8"+ureq = { version = "3.5.2", features = ["brotli"] }+winit = "0.30.13"+rustybuzz = "0.20.1"+unicode-linebreak = "0.1"+unicode-bidi = "0.3"+ttf-parser = "0.25"+ab_glyph_rasterizer = "0.1"+woff2-patched = "0.4"+diff --git a/plugins/chrome-rs/README.md b/plugins/chrome-rs/README.mdnew file mode 100644index 0000000..70d5004--- /dev/null+++ b/plugins/chrome-rs/README.md@@ -0,0 +1,68 @@+# chrome-rs++Small from-scratch browser in Rust. Own HTML parser, own CSS engine, JavaScript via embedded QuickJS, CPU rendering (no GPU).+~3 MB binary, ~30-40 MB RAM on typical pages.++```+cargo run --release -- [url or search words]+```++If the build fails with "path too long" on Windows, set `CARGO_TARGET_DIR` to a short path (e.g. `C:\t`).++## Browser features+- Tabs, **Ctrl+F** find in page (Enter / Shift+Enter / F3 next, Esc closes), mouse **text selection** with Ctrl+C / Ctrl+A / double-click word,+ **zoom** (Ctrl +/-/0, Ctrl+wheel), smooth scrolling and a draggable scrollbar, **Ctrl+D** bookmark (star in the address bar),+ `about:history` / `about:bookmarks` / `about:settings` (Ctrl+H / Ctrl+B), address-bar suggestions from bookmarks and history,+ **Ctrl+Shift+T** reopen a closed tab, **Ctrl+1..9** switch tab, previous session restored on start, **Ctrl+P** saves the page as a PDF+ (`prints` folder in the data dir), IME input. Settings (`home`, `search`) live in `settings.tsv` in the data dir.+- Fonts: real bold/italic faces, fallback fonts for symbols/CJK/Indic loaded on demand, `@font-face` (TTF/OTF/WOFF; not WOFF2),+ text shaping and word-level bidi for Arabic/Hebrew/Indic/Thai, CJK text wraps between characters.+- Live pages: scripts keep running after load (real-time timers, `requestAnimationFrame`), clicks/typing/focus/keys/scroll/resize reach+ page handlers (`addEventListener`, `onclick=`), the page is re-rendered when scripts change the DOM, `getBoundingClientRect`/`offset*`+ report real layout boxes, `location` assignments navigate, `<script type=module>` with imports, dynamic `import()` and top-level await.++## Keys / mouse+- Address bar: type a URL, a host (`rust-lang.org`) or search words (DuckDuckGo), Enter to go. Esc reverts, Ctrl+L selects.+- Click links. Wheel / arrows / PageUp / PageDown / Home / End scroll. Alt+Left/Right history. F5 / Ctrl+R reload.++## Pipeline+`load.rs` fetch (HTTPS, redirects) + external CSS/JS in parallel -> `dom.rs` parse -> `js.rs` run scripts/timers (4 s budget) ->+`render.rs` + `css.rs` cascade into styled words -> `main.rs` layout and paint.++## Works+- CSS: selectors (tag, class, id, attribute, descendant/child/sibling, first/last-child), specificity, `!important`, inline styles,+ `@media` (fixed 1000px viewport), `display`, `color`, `font-size`, `font-weight`, `text-align`, `text-decoration`, margins/padding+ (vertical gaps and left indent), page background, `list-style:none`, `visibility`/`opacity:0` hiding, `line-height`, `position: relative/absolute`, row flexbox (`flex`, grow/shrink/basis, wrap, gap, justify-content, align-items).+- JS: DOM (create/append/remove, innerHTML, attributes, classList, style, querySelector, events, DOMContentLoaded/load),+ timers in virtual time, promises, localStorage stub.++- Images (PNG, JPEG, GIF, WebP) fetched in parallel, downscaled on decode; block background colors (CSS and `bgcolor`).+- Pages in other encodings (windows-1251, etc.), JS `fetch`/XHR (GET only), Ctrl+C / Ctrl+V in the address bar.+- Layout: tables with real columns (colspan, widths, cellpadding/cellspacing, border, bgcolor, valign, nested tables), block boxes+ with margins, padding, `width`/`max-width`, `margin: 0 auto` centering, nested indentation and box backgrounds.+- Floats (`float` / `clear`: text wraps around them), CSS borders on blocks, `<hr>`, monospace fonts and preformatted blocks+ (`<pre>`, `<code>`, `white-space: pre`), `:not()` selectors, empty icon-only buttons are skipped.+- SVG: `<img src=*.svg>` and inline `<svg>` are rasterized once (resvg; shapes, paths, gradients, no `<text>`).+ Fixed-position overlays and "visually hidden" utility elements are not shown. `CHROME_RS_DEBUG=1` prints the first laid-out items.+- Tabs: Ctrl+T new, Ctrl+W close, Ctrl+Tab / Ctrl+Shift+Tab (or Ctrl+PageUp/Down) switch, click the strip, Ctrl+click a link opens it in a new tab.+- Forms: text/password fields with placeholders, textareas (wrapping, multi-line), dropdown selects, radio groups, checkboxes,+ buttons, hidden fields. Click to focus (caret goes where you click), Left/Right/Home/End/Delete/Backspace, Tab / Shift+Tab to move+ between fields, Ctrl+C / Ctrl+V, Enter or the button submits (GET and POST).+- `display:inline-block`, cookies (jar with domain/path/Secure/HttpOnly/Max-Age, persisted), persistent `localStorage`, `document.cookie`.+- Headless tools: `--snap in.html out.png`, `--pdf in.html out.pdf`, `--corpus DIR`, `--bench DIR`; `CHROME_RS_SELFTEST=1` exercises the UI paint paths and exits.+- CSS: `var()` custom properties, `calc()/min()/max()/clamp()`, `vw/vh/ch`, `:nth-child/-of-type/-last-child`, `:is()/:where()`, `:checked`, `:empty`,+ `::before/::after` with text `content`, `min-height`/`height` (as a minimum), `box-sizing`, `border-radius` (rounded fills and borders),+ `text-transform`, `white-space: nowrap`, `text-indent`, gradients as their first color, table `rowspan`.+- Clicking a `<label>` focuses its field or toggles its checkbox/radio.+- Schemes: `file://` (local pages and their CSS/JS/images), `data:`, `about:blank`, `view-source:`; `text/plain` shown preformatted.+- JS: `URL`, `URLSearchParams`, `FormData` (multipart), `Headers`/`Response`, `fetch`/XHR with POST/PUT/DELETE, `history.pushState`,+ `atob/btoa`, `TextEncoder/Decoder`, `Blob`, `performance.now`, `queueMicrotask`, `structuredClone`, `crypto`, `AbortController`, mouse/keyboard event classes.+ Cross-origin `fetch`/XHR follow a simplified CORS (simple requests only, response must allow the origin).+- Regression tooling: `--corpus`, `--snap`, `--bench` (see ARCHITECTURE.md).+- A panic while loading a page shows an error page instead of killing the browser.+- `CHROME_RS_TIMING=1` prints per-phase load timings to stderr.++## Not yet+SVG, file/date/range inputs, form validation, rowspan,+fixed positioning, flex column/stretch, grid, rounded corners, borders on inline elements, long `<pre>` lines are clipped (no horizontal scroll), pseudo-classes beyond the common ones, `box-shadow`, `opacity` below 1, background images,+WebSocket (always fails), Web Workers, MutationObserver, capture-phase events, hover/mouse-move events, WOFF2 fonts, text-selectable PDFs, JS-rendered SPAs, tabs, text selection in pages.diff --git a/plugins/chrome-rs/ROADMAP.md b/plugins/chrome-rs/ROADMAP.mdnew file mode 100644index 0000000..018071f--- /dev/null+++ b/plugins/chrome-rs/ROADMAP.md@@ -0,0 +1,177 @@+# chrome-rs: roadmap and status++Status as of 2026-11-15 (M1, M2, M3 and M4 done). Legend: **[x]** done and covered by a test or a corpus page, **[~]** partly done (the limit is stated), **[ ]** not done.+Sizes are rough solo-developer estimates in weeks of focused work (with AI assistance), not promises.++## 0. What "finished" means++| Tier | Goal | Realistic? |+|------|------|------------|+| A. Reader/docs browser | Articles, docs, forums, search, wikis, simple forms | **Reached** for Latin/Cyrillic/CJK/RTL text pages |+| B. Mainstream web | Logins, shops, news with JS menus, no video | Partly: cookies, forms, live JS, flex, grid, fixed/sticky boxes, scroll containers, stacking contexts and modern CSS work on the real-page corpus; missing JS-rendered sites (frameworks), cache, HTTP/2, media, iframes, canvas |+| C. Modern web apps | Gmail/Docs/Maps/YouTube-class | No for a from-scratch engine |+| D. Chrome parity | Everything + extensions, sync, DRM | No |++**Target: tier B.** The engine decision is made (M3): keep the own engine; revisit only when a concrete feature (iframes, canvas, transitions, contenteditable) cannot be built on the current layout.++## 1. Snapshot++| | |+|---|---|+| Code | about 8,000 lines of Rust + 912 lines of JS prelude (`wc -l`), 12 Rust files |+| Tests | 113 unit tests (+1 ignored: TodoMVC apps) (cascade, layout, fonts, bidi, cookies, CORS and redirects against a local HTTP server, live-JS sessions, ES modules, PDF structure, UI logic) |+| Regression | `--corpus`: 15 hand-written offline pages and 164 archived real pages (of 168 URLs; `corpus/urls.txt`, re-saved 2026-11-15) rendered to PNG and compared with golden images (per-machine goldens; scripts use a fixed `Math.random` while replaying so shuffles do not flap) |+| Release binary | 8.3 MB; whole corpus (174 pages, replayed offline, release build) renders in about 87 s of CPU (was 72 s before the event, shadow DOM and `getComputedStyle` work; the machine was busy, not bisected) |+| Memory (release, Windows, 15 s after load, remeasured 2026-11-15) | example.com 78 MB working set (60 MB private); Hacker News 81 MB (63); MDN JavaScript guide 116 MB (99); Wikipedia Rust article 169 MB (153). Earlier numbers (static 54, HN 91, MDN 103) came from other builds and a 12 s wait: not comparable, the baseline grew with the larger prelude and the event system. A page with CJK text adds about 35 MB |+| Chrome comparison (2026-11-15, one run, Hacker News, 20 s after load, Windows, release build, clean Chrome profile) | chrome-rs: 1 process, 81 MB working set, 63 MB private. Chrome: 11 processes, 560 MB working set (sums shared pages more than once), 323 MB private. About 7x less working set and 5x less private memory on this one page, for a much smaller feature set. One page, one run: an indication, not a benchmark |+| Not measured | Chrome render time and reference screenshots; CPU load; Linux/macOS builds; memory over the whole real-page corpus (only four pages sampled) |+| Never done by hand | the GUI was not clicked through; UI behaviour is covered by pure-logic tests and the `CHROME_RS_SELFTEST` paint run |++## 2. Milestones++### M1. Fidelity of everyday pages: done+- [x] Inline formatting: `inline-block` (shrink-to-fit, baseline), `line-height`, `text-transform`, `white-space: nowrap`, `text-indent`, `<br>`, `letter-spacing`, `vertical-align: super/sub/<length>` on text+- [x] Positioning: `relative`, `absolute` (against the nearest positioned ancestor or the page; `top/right/bottom/left`, `inset`), **`fixed`** (own paint layer drawn at screen coordinates, `bottom`/`top` against the viewport height)+- [x] `sticky` pins to its `top` offset once the page scrolls past it and stops at the bottom of its container; `fixed` and `sticky` boxes are moved in page coordinates on every scroll, so hit-testing and clicks agree with what is painted+- [x] `z-index` and nested stacking contexts: every positioned box (and a relative one with a z-index) is a context, its content is ordered as a unit (a z-index:100 child of a z-index:5 box stays below a z-index:6 sibling); negative z-index paints below in-flow text, `fixed` boxes on top of everything. Contexts nest four deep, deeper levels share the fourth; z-index is clamped to +-4000. A positioned box with `z-index: auto` is treated as a context too+- [x] Flexbox: row (grow/shrink/basis, wrap, gap, justify-content, align-items/self, auto margins) and **column** (stacking with gap and margins, `align-items` across); column has no main-axis sizing (grow/justify need a container height)+- [x] Grid, columns only: `grid-template-columns` with `px`, `%`, `fr`, `repeat(n, ...)`, `repeat(auto-fill|auto-fit, minmax(N, 1fr))`, `gap`/`row-gap`/`column-gap`, `grid-column: span N`; rows are as tall as their tallest item. No explicit rows, areas, named lines, dense packing+- [x] Box model: `box-sizing`, `min-height`/`height`, `border-radius`, `rowspan`, `calc()/min()/max()/clamp()`, `var()`, `em/rem/vw/vh/ch`; **vertical padding is now painted inside the box background** (it used to be only a flow gap)+- [x] Selectors: `:nth-child/-last-child/-of-type`, `:first/last-of-type`, `:only-child`, `:empty`, `:is()/:where()`, `:checked`, `:disabled`, `::before/::after` with text `content`+- [x] Generated content and counters: `counter-reset/-increment`, `counter()` and `counters()` and `attr()` in `content`, `<ol>` numbering (`start`, `value`)+- [x] `box-shadow` (first layer: offset, blur, spread, color; drawn as stacked translucent rectangles; no `inset`)+- [x] `rgba()`/`#rrggbbaa` backgrounds are translucent; `linear-gradient()` is painted (angles, `to <side>`, stops with positions)+- [~] `opacity` below 1: text, box colors and images are blended with what is behind them; no group compositing (overlapping children of one faded box show through each other)+- [x] Scroll containers: `overflow: auto|scroll` with an explicit `height` keeps its size, its content is clipped to the box pixel-exactly and scrolls with the mouse wheel (the innermost container that can move takes the wheel, else the page), with a thumb drawn at the right edge. `overflow: hidden` with a height cuts the content. Not done: dragging the thumb, keyboard scrolling, horizontal scrolling, nested containers move only with their innermost offset, an `auto` container without a fixed height never scrolls, clicks on parts hidden by the clip still hit+- [x] Every box leaves an invisible geometry marker, so `:hover`, hit-testing and `getBoundingClientRect` see the box and its padding, not only its text+- [x] Backgrounds: `background-image: url()` (downloaded with the page's other images; `data:` URLs too) with `background-size` (auto, cover, contain, lengths, percentages), `background-position` (keywords, lengths, percentages), `background-repeat`, and the `background` shorthand; `radial-gradient()` (circle or ellipse, `at x y`, farthest-corner). Conic gradients fall back to the first color stop; only the first layer of a comma list is used; image corners are not rounded by `border-radius`+- [x] `:hover`, `:active`, `:focus`, `:focus-visible`, `:focus-within`: pages whose CSS uses them keep their DOM, and the page is restyled when the pointer moves to another element, the button is pressed or released, or focus moves. No transitions, no `cursor` styles; JS `mouseover` handlers are M4+- [x] Percentage `height` and `min-height` against a containing block that has a definite height (`html, body { height: 100% }` is the 720 px reference height); an auto-height parent ignores them. `html` and `body` are never clipped by `overflow`+- [~] `vertical-align: middle` on images; `top`/`bottom` keep the baseline, and inline boxes other than text and images ignore it+- [x] Exit criterion: a corpus of more than 100 pages. 15 hand-written offline pages plus 159 real pages (of the 168 URLs in `corpus/urls.txt`, the rest did not load: DNS, TLS handshake, timeouts), archived with `chrome-rs --save corpus/real corpus/urls.txt` and rendered offline through the full pipeline by `chrome-rs --corpus corpus`. The archives (261 MB) are not committed because they are third-party content, so the corpus can be rebuilt but not reproduced exactly (the sites change); goldens are per machine. A golden records what chrome-rs draws today, not what is correct: it catches regressions, it does not say a page looks right+- [x] Images and inline SVG take their size from CSS (`width`, `height`, `max-width`, `width: N%`) before the attributes; an unsized `<svg>` is at most 300 px wide. Found through the corpus, 61 of 159 pages changed+- [~] Images: `<picture><source>` (type and px media queries) and `srcset` pick the candidate a 1000 px screen at 1x would use (width descriptors: the smallest of at least 800 w), lazy `data-src`/`data-srcset` are used, `<svg><use href="#id">` copies its target from elsewhere in the page into the svg. Effect on the corpus is small (1904 image responses over 164 pages against 1774 over 159). Known gaps: pictures wider than 800 px are decoded downscaled, so a picture without any CSS or attribute size shows at that smaller size; `object-fit` and icon fonts are not handled++### M2. Text and fonts: done except weights, variable fonts, hyphenation and subpixel rendering+- [x] Real bold, italic and bold-italic faces (sans and mono families), lazily read from disk+- [x] Fallback fonts for symbols, CJK, Indic, Thai, loaded on demand and only when they cover the character; **outlines are read per glyph (`ttf-parser` + `ab_glyph_rasterizer`) instead of parsing the whole font**: a CJK page costs about 35 MB over a Latin page (debug build, Windows; it was 150-250 MB)+- [x] `@font-face` with TTF, OTF, WOFF 1 and **WOFF 2** (`woff2-patched`: brotli and the glyf/loca transform); relative `url()` in external stylesheets is made absolute; `font-display` needs no support because fonts are fetched before the first paint+- [x] Text shaping with rustybuzz for Hebrew, Arabic, Indic, Thai (ligatures, joining, mark placement)+- [x] Bidi by UAX #9 (`unicode-bidi`): paragraph direction from the first strong character, embedding levels per word, visual reordering of the words of each line, numbers inside RTL text keep their order, lone brackets are mirrored in RTL runs. Granularity is the word (mixed-script words are only reordered by the shaper)+- [x] Line breaking by UAX #14 (`unicode-linebreak`): after hyphens and slashes (long URLs wrap), between CJK characters with the kinsoku rules (no line starts with a closing mark or ends with an opening one), after soft hyphens (a hyphen is drawn only where the line breaks)+- [ ] Variable fonts (a variable WOFF2/TTF loads at its default instance, bold is faked) and `font-weight` values 100-900 (only regular/bold exist)+- [ ] Automatic hyphenation (`hyphens: auto` needs dictionaries); only soft hyphens work+- [ ] Sub-pixel antialiasing, hinting at fractional scales++### M3. Architecture checkpoint: decided, keep the own engine+Decision (2026-11-14): no switch to Servo or Blitz. Keep the item-stream layout with the box markers, scroll groups and paint keys added in M1; do not rewrite it into a box tree now.++Data behind it:+- M1 and M2 were done on the existing layout. What looked like architecture limits (stacking contexts, scroll containers, sticky limits, hover, percentage heights, background images) turned out to need markers and tags on the output, not a new tree. The one rewrite I proposed (a box tree) was not needed to deliver them.+- The 159-page real corpus renders, with no crashes after the stack fix, and a contact-sheet review of 80 of the pages shows text, tables, floats, flex and grid, and Latin/Cyrillic/CJK/Arabic/Hebrew/Indic/Thai pages all laid out recognisably. The visible defects fall in three classes:+ 1. images and inline SVG drawn at their natural size because CSS `width`/`height`/`max-width` on `<img>` and `<svg>` was ignored (rust-lang book icons, Flask, Deno, PHP, Python, IETF, sqlite sponsors, GitHub): a bug in `render.rs`, not in the layout model. Fixed afterwards: CSS sizes beat the attributes, one given dimension fixes the other by the picture's proportions, `max-width` and `width: N%` work, an unsized inline `<svg>` is at most 300 px wide; 61 of the 159 real pages changed and were re-blessed;+ 2. pages that need JavaScript to show anything (crates.io, Stack Overflow, Medium, Reddit, IMDb, NYTimes, OpenStreetMap): the M4 scope (DOM and Web API coverage);+ 3. fine details (icon fonts, `<svg>` `<use>`, form control looks).+- Cost of the alternatives is unchanged: Blitz would cost the binary size (7.8 MB) and memory (54 MB static page) that are this project's selling point and a rewrite of the QuickJS bridge; Servo is a different project. Neither was prototyped, so those costs are estimates.++Revisit when something needs a real box tree: iframes with their own documents, canvas, CSS transitions and animations, text editing in `contenteditable`, or when the corpus shows layout (not sizing) defects the item stream cannot express. The trigger is a concrete feature that cannot be built on the markers, not an estimate overrun.++### M4. Live JavaScript and DOM: done (one page at a time)+- [x] A session thread keeps QuickJS alive after load; first virtual second of timers at load, then real-time timers and `requestAnimationFrame`+- [x] UI events reach page handlers (`click`, `mousedown/up`, `keydown/up`, `input`, `change`, `focus`, `blur`, `submit`, `scroll`, `resize`); `addEventListener`, `onclick=` attributes and `el.onx = fn`; `preventDefault` / `return false` cancel link following and form submission+- [x] Typed text, checkbox, radio and select state is mirrored into the page DOM; the UI merges edits with script changes when the page re-renders+- [x] DOM changes re-render the page (throttled; images cached by URL); `location` assignment and `location.href` navigate; `history.pushState`, `popstate`+- [x] Layout APIs from real boxes: `getBoundingClientRect`, `offset*`, `client*`, `scrollTop`; `IntersectionObserver`/`ResizeObserver` report everything visible+- [x] Web APIs: `fetch`/XHR (all methods, FormData multipart, Headers, Response), `URL`, `URLSearchParams`, `Blob`, `TextEncoder/Decoder`, `atob/btoa`, `AbortController`, `performance`, `crypto`, `structuredClone`, `queueMicrotask`, persistent `localStorage`, `document.cookie`+- [x] ES modules: `<script type=module>`, static and dynamic `import()`, top-level await+- [x] `document.implementation` (`createHTMLDocument`, which jQuery needs at load) and the `HTML*Element` globals: `jQuery is not defined` fell from 26 to 7 corpus pages, usa.gov and gov.uk now run their banner and menu scripts+- [x] **Page scripts run in sloppy mode** (rquickjs evals in strict mode by default, so `OSM = {}` without `var` threw `OSM is not defined`): this one switch removed the `RLQ`/`RLCONF` (Wikipedia), `sinaads`, `jsLoader`, `_N_E` and OpenStreetMap errors, and python.org and wikipedia.org now run their menus and portal scripts instead of showing the no-script fallback+- [x] `document.currentScript` (the running script's `src`): Turbopack/Next.js bundles (nodejs.org, tailwindcss.com) no longer throw `chunk path empty but not in a worker`+- [x] `<script type="importmap">` (exact and `prefix/` entries, no `scopes`), so bare module specifiers like `react` resolve; `el.attributes` answers `attributes.name` and `getNamedItem` (jQuery 1.x read `attributes[n].expando` and died, taking `$`/`jQuery` down on about 16 pages); globals `File`, `NodeList`, `HTMLCollection`, `ShadowRoot`, `SVGElement`, `Storage`, `screen`; a small English-only `Intl` (DateTimeFormat, NumberFormat, Collator, PluralRules, RelativeTimeFormat, ListFormat, Segmenter), `Comment`, `Range`, `TreeWalker`, `MessageChannel`, `FileReader`, `Request`, `document.styleSheets/scripts/forms/links/images/fonts`, `performance.timing`, `navigator.*`, `HTML*Element` that test the tag, and about 25 `Element` methods (`insertAdjacentElement`, `replaceWith`, `getAttributeNames`...)+- [x] **Custom Elements**: `customElements.define/get/whenDefined/upgrade`, `class X extends HTMLElement`, upgrade of elements already in the page, `connectedCallback`/`disconnectedCallback`/`attributeChangedCallback`. Not done: customized built-ins+- [x] `import.meta.url` (webpack/Vite derive their public path from it), up to 400 imported modules per page (was 60), `HTMLScriptElement.noModule` (GOV.UK Frontend), `document.adoptedStyleSheets`, `<template>.content`, `form.elements`, `control.form`, `a.pathname/search/hash/host/...`, absolute `a.href` and `script/img.src`, `Text.nodeValue` setter, `meta.content`. A prelude that fails to load now says so under `CHROME_RS_JSERR=1` (it used to switch all JS off silently)+- [x] **Comment nodes** are kept in the DOM for scripts (`<!--[-->` anchors are what Vue and React hydration walk; Font Awesome SVGs carry one too) and stripped before layout and before an inline `<svg>` is written out; root-level comments of a document are dropped. `<select>`: `options`, `selectedIndex`, `selectedOptions`, option `index/text/defaultSelected`: react.dev and vuejs.org now hydrate and render in full+- [x] `CHROME_RS_JSERR=1` also prints `console.error`/`warn` and exceptions thrown inside timers (`JSLOG`), which pages such as Vue and Next.js use to report their own failures; both were swallowed before prints the script exceptions that were swallowed before; use it with `--corpus` to find what breaks+- [ ] Capture phase, hover/mouse-move/pointer events, `MutationObserver` (stub), Web Workers, WebSocket (always fails), `IndexedDB`, `sessionStorage` persistence, `matchMedia` (always false)+- [ ] Incremental restyle/relayout: every update rebuilds the whole page and re-serializes the whole DOM (fine for ordinary pages, slow for 10k+ nodes)+- [x] `getComputedStyle` runs a small cascade over the page's `<style>` elements and the inline style (UA display defaults, specificity, `!important`, inheritance of color/font/visibility...). Declared values come back as written (no unit conversion, no `var()`/`calc()`, `@media` blocks skipped, no pseudo-elements); width/height come from the last layout box. jQuery 2 `show()`/`toggle()` depend on it. It costs CPU: the rule scan is redone every 32 calls and rules are pre-filtered by class/id/tag. `innerText` is still `textContent`+- [~] Blank corpus pages, investigated: crates.io (404), Stack Overflow, NYTimes, Medium, blender.org (403) and IMDb (202) were archived as server errors or bot checks, so they are **not** JS defects; a re-save with a browser User-Agent or from another network may fix them. Left after the fixes below (`CHROME_RS_JSERR=1 --corpus`: 47 error lines over 159 pages, was 300+): `Error loading module .../react-*.js` on GitHub (the import map resolves, but the archive has no copy of the file: re-save with `--save` to check), `not a function` (3, mixed causes), `charAt`/`type`/`replace` of undefined, `ReadableStream` and friends are inert stubs, tailwindcss.com and asahi.com hit the JS CPU budget (`interrupted`; the budget is wall-clock, so on a loaded machine their corpus result flips: a golden mismatch there is not necessarily a regression), Swagger UI on httpbin.org renders its list but not `SchemesContainer`; tools.ietf.org/html/rfc2616 hydrates into an `Error 500` page (a Nuxt route chunk is missing from its archive even after a re-save, cause not found: its golden records that). **Traps found while adding APIs** (an API that exists but is half-done is worse than a missing one, because pages feature-detect it): `DOMParser` present breaks DOMPurify (Swagger UI), so it stays out until it is complete. `PromiseRejectionEvent` and `namespaceURI` looked harmful too, but the blank react.dev and vuejs.org they produced came from two other causes, now fixed: a stale archive (the corpus copy lacked a chunk that hydration now asks for; re-saved) and `select.options` missing (React's `<select>` code). `instanceof HTMLIFrameElement` must test the tag. Open: archive.org, naver.com, Reddit not looked at+- [x] **Events follow the DOM model**: capture, target and bubble phases (`addEventListener(t, f, {capture, once})`, `eventPhase`, `composedPath`, `stopImmediatePropagation`); keyboard events carry `keyCode`/`which`/`code` derived from `key`; `keypress` is sent for Enter and characters; Enter or blur in a changed field fires one `change` (the field's baseline is updated so a script that clears it is not overwritten); `onclick`, `oninput`... exist as null properties (React tests `'oninput' in document`; touch handlers are deliberately absent, python.org's carousel switches to a touch layout if `ontouchstart` exists)+- [x] Parser fixes found through the apps: whitespace-only text at the root of a fragment is kept (Svelte templates `<!> <main>` walk siblings); a stray quote after a value (`data-id="x"">`, produced by Handlebars) no longer swallows the following tags (apache.org and schneier.com now render fully); `innerHTML` of `<script>`/`<style>` is raw text (Backbone templates); `iframe.contentWindow/contentDocument` give an empty document, `onhashchange` exists (jQuery 2 and Backbone 1 write into an iframe)+- [x] **Shadow DOM, flattened**: `attachShadow` roots are real trees (`innerHTML`, `append`, `mode`, `host`, events bubble through the host); when the page is serialized a host shows its shadow tree instead of its light children, a `<slot>` shows the nodes assigned to it (by `slot=` name, fallback content otherwise; `assignedNodes()`), and constructable stylesheets adopted by a root (`adoptedStyleSheets` with `replaceSync`) become `<style>` elements. Shortcuts: shadow styles apply to the whole page (no scoping), `:host` and `::slotted` do not match, events are not retargeted, `cloneNode`/`importNode` construct defined custom elements at once (template content stays inert). Also: `<?x>` parses as a comment (Lit's part markers), `TreeWalker` walks the live tree from `currentNode`, `hasAttributes()`+- [x] **Exit criterion met**: ten TodoMVC apps were archived (`corpus-m4/`, not committed) and driven through the live session (type, Enter, read the list back; `cargo test --release archived_todomvc -- --ignored`): React, Vue, Preact, Svelte 5, Angular, ES6, Backbone, jQuery, Lit and web-components all accept a todo and render it. The test drives events directly, not through the GUI. Svelte needed plain elements to sit one prototype below `Element.prototype` (it collects setters such as `hidden` from that part of the chain; without it `hidden=false` became `setAttribute('hidden', false)` and the list stayed hidden)++### M5. Networking and web platform: partly done+- [x] Cookie jar (domain, path, Secure, HttpOnly, Max-Age; persisted), redirects handled hop by hop, same-site cookies only for subresources+- [x] Schemes: `file://` (readable only by top-level navigation and file pages), `data:`, `about:blank`, `view-source:`, `text/plain` shown preformatted+- [x] Charset decoding, gzip via the HTTP client+- [ ] `Expires` is ignored (only `Max-Age` persists), no `SameSite`, no public-suffix check+- [ ] HTTP cache (ETag, Cache-Control), HTTP/2 and HTTP/3, brotli/zstd, proxy settings, retry policy+- [ ] HSTS, certificate error page, mixed-content blocking, HTTPS-only mode+- [ ] `multipart/form-data` file uploads, file/date/range/color inputs, form validation, autocomplete, password manager+- [ ] Downloads manager, content-type sniffing, in-browser PDF viewing+- [ ] `<video>`/`<audio>`, `<canvas>`, `<iframe>`, `blob:` URLs++### M6. Browser product features: mostly done+- [x] Find in page (Ctrl+F, Enter/Shift+Enter/F3, highlights, centered scroll)+- [x] Text selection with the mouse, double click for a word, Ctrl+A, Ctrl+C+- [x] Zoom (Ctrl +/-/0, Ctrl+wheel), smooth scrolling, draggable scrollbar+- [x] Bookmarks (Ctrl+D, star indicator), history, `about:history`, `about:bookmarks`, `about:settings`, address-bar suggestions+- [x] Reopen closed tab (Ctrl+Shift+T), Ctrl+1..9, session restore on start, home page and search engine in `settings.tsv`+- [x] IME commit text, `<label>` click focuses or toggles its control+- [x] Print to PDF (Ctrl+P): the page is rendered and cut into A4 sheets as images (not selectable text)+- [ ] Context menu, favicons, tab reorder/pin/duplicate, multiple windows, light/dark theme and `prefers-color-scheme`+- [ ] Developer tools (DOM tree, computed style, console, network)+- [ ] Drag and drop, touch/trackpad gestures, kinetic scrolling, caret browsing+- [ ] A real settings UI (settings are a text file), real print dialog and text PDFs+- [ ] Exit criterion not met: not used as a daily browser++### M7. Performance and memory: not started+- [ ] Incremental layout and paint (damage rectangles), layer caching, GPU backend (wgpu/Vello) with the CPU path as fallback+- [ ] Lazy image decode, viewport-only painting, per-tab memory budgets, tab discarding+- [ ] Startup budget, selector matching profiling, JS snapshots+- [~] Tooling exists: `--bench` prints median build/layout/paint milliseconds per corpus page (about 3 ms build, under 1 ms layout on the corpus in release); `CHROME_RS_TIMING=1` prints load phases+- Known costs: CJK fonts (see M2), whole-DOM re-serialization on live pages, every live update rebuilds the page and clones cached images++### M8. Security and isolation: first steps only+- [x] `file:` isolation, cookies scoped to the site for subresources, simplified CORS for script requests (simple requests only, no preflight, response must allow the origin)+- [x] Parser and runtime limits: depth cap, response size limits, JS CPU budget per burst, memory limit+- [ ] Same-origin policy for the DOM (there is only one document, no iframes yet), CSP, `Referrer-Policy`, sandboxed iframes, `X-Frame-Options`+- [ ] Process isolation and OS sandbox (renderer, network and UI share one process)+- [ ] Fuzzing (HTML, CSS, URL, image, SVG, fonts, WOFF), `cargo-deny`/`cargo-audit`+- [ ] Permission prompts, blocklist, signed auto-update+- [ ] Exit criterion not met: no external review of the renderer boundary++### M9. Accessibility and internationalisation: not started+- [ ] Accessibility tree and platform bridges (`accesskit`), keyboard-only navigation and focus ring, `aria-*`, high contrast, reduced motion+- [ ] UI translation (Russian first), locale-aware `Intl`, spell-check, right-to-left UI chrome++### M10. Compatibility, QA and release: not started+- [~] Unit tests and the corpus exist (174 pages); no web-platform-tests subset, no reference screenshots from another browser to compare with, no fuzzers+- [ ] CI on Windows/Linux/macOS, reproducible builds, crash reporter+- [ ] Installers (MSI/MSIX, AppImage/deb, dmg), code signing, update channels+- [ ] User manual and contributor guide (README and ARCHITECTURE exist and are current)+- [ ] Linux and macOS were never built or run: font paths for them are written but untested++## 3. Order of work from here (tier B, one developer)++| Order | Work | Why first |+|-------|------|-----------|+| 1 | The blank JS pages (crates.io, Stack Overflow, Medium, Reddit, IMDb, NYTimes, OpenStreetMap; some are server errors, see M4) | Last open defects of the JS class |+| 2 | Memory over the whole corpus and render time against Chrome on a sample (HN memory re-measured 2026-11-15) | Only four pages were sampled |+| 3 | Corpus follow-ups: icon fonts, form control looks, `object-fit`, decode large images at full size; reference screenshots from another browser for the worst pages | The remaining visible gaps; goldens alone cannot say what is wrong |+| 4 | HTTP cache, HTTP/2, brotli, file uploads, form validation, `<iframe>`, `<canvas>` (iframes and canvas are the M3 revisit triggers) | Logins, shops and embedded content |+| 5 | CI that runs `cargo test` and `--corpus` on every change (needs the archives somewhere: a release asset or a cache) | The corpus only helps if it runs |+| 6 | Security: CSP, DOM same-origin with iframes, fuzzing, renderer process split | Must land before any public release |+| 7 | Accessibility, Linux/macOS builds, installers | Release work |++## 4. Biggest risks++1. **Scope explosion.** Every CSS property is endless. Mitigation: the corpus drives the backlog; build only what blocks listed pages.+2. **Own engine vs. reuse.** Decided at M3 (keep). The risk that remains is a feature that really needs a box tree (iframes, canvas, transitions); it is revisited then, with the corpus as evidence.+3. **Memory.** Eager font parsing and whole-page rebuilds on live pages are the current hot spots; process isolation (M8) will add to it.+4. **JavaScript compatibility.** QuickJS is complete for the language but slow; live pages re-serialize the DOM, so large SPAs will lag.+5. **Security is not optional.** One process, no sandbox, no CSP yet: do not browse untrusted sites with it as a daily browser.+6. **Unverified GUI.** Interactive behaviour (drags, shortcuts, focus flows) was tested through logic and a headless paint run, not by hand; expect bugs in the first manual sessions.+7. **Bus factor.** `ARCHITECTURE.md` documents the data flow and decisions; keep tests green on every change.+8. **Corpus is a regression net, not a correctness check.** Goldens record chrome-rs's own output; the archives are not committed, so a fresh `--save` gives different pages. Mitigation: reference screenshots from another browser for the worst pages, and archives kept as a release asset.diff --git a/plugins/chrome-rs/src/browse.rs b/plugins/chrome-rs/src/browse.rsnew file mode 100644index 0000000..18a42fa--- /dev/null+++ b/plugins/chrome-rs/src/browse.rs@@ -0,0 +1,203 @@+// Window-independent page interaction: find-in-page and text selection over laid-out words (all coordinates are layout px).+// shortcut: selection follows layout order of words (not columns/floats), RTL words map x to characters mirrored but+// selection across mixed-direction runs is approximate.+use crate::{gfx::{is_rtl, Fonts}, layout::Placed};++/// Highlight pieces of one match: (index into `placed`, x offset inside the word, width).+pub struct Match { pub parts: Vec<(usize, f32, f32)> }++fn lower(c: char) -> char { c.to_lowercase().next().unwrap_or(c) }++fn is_text(p: &Placed) -> bool { !p.text.is_empty() && p.img.is_none() && p.field.is_none() }++/// Width of characters `from..to` of `p`'s text.+fn span_w(p: &Placed, from: usize, to: usize, f: &mut Fonts) -> f32 {+ if from >= to { return 0.0; }+ f.width_f(&p.text.chars().skip(from).take(to - from).collect::<String>(), p.size, p.face)+}++/// All case-insensitive occurrences of `q` in the page text (words are joined by single spaces, so phrases match across words).+pub fn find_matches(placed: &[Placed], q: &str, f: &mut Fonts) -> Vec<Match> {+ let qc: Vec<char> = q.split_whitespace().collect::<Vec<_>>().join(" ").chars().map(lower).collect();+ if qc.is_empty() { return vec![]; }+ let (mut hay, mut src): (Vec<char>, Vec<Option<(usize, usize)>>) = (vec![], vec![]);+ for (i, p) in placed.iter().enumerate().filter(|(_, p)| is_text(p)) {+ if !hay.is_empty() { hay.push(' '); src.push(None); }+ for (k, c) in p.text.chars().enumerate() { hay.push(lower(c)); src.push(Some((i, k))); }+ }+ let mut out = vec![];+ let mut s = 0;+ while s + qc.len() <= hay.len() && out.len() < 1000 {+ if hay[s..s + qc.len()] == qc[..] {+ let mut parts: Vec<(usize, usize, usize)> = vec![]; // (placed, first char, last char + 1)+ for &(i, k) in src[s..s + qc.len()].iter().flatten() {+ match parts.last_mut() { Some(l) if l.0 == i => l.2 = k + 1, _ => parts.push((i, k, k + 1)) }+ }+ out.push(Match { parts: parts.into_iter().map(|(i, a, b)| (i, span_w(&placed[i], 0, a, f), span_w(&placed[i], a, b, f))).collect() });+ s += qc.len();+ } else { s += 1; }+ }+ out+}++/// A caret position inside the page text: word index and character offset.+#[derive(Clone, Copy, PartialEq, Debug)]+pub struct SelPoint { pub idx: usize, pub ch: usize }++/// Nearest text position to the layout point (x, y); None when the page has no text.+pub fn hit_point(placed: &[Placed], x: f32, y: f32, f: &mut Fonts) -> Option<SelPoint> {+ let dist = |p: &Placed| {+ let (top, bot) = (p.base - p.size, p.base + p.size * 0.3);+ let dy = if y < top { top - y } else if y > bot { y - bot } else { 0.0 };+ let dx = if x < p.x { p.x - x } else if x > p.x + p.w { x - p.x - p.w } else { 0.0 };+ dy * 4.0 + dx+ };+ let (idx, p) = placed.iter().enumerate().filter(|(_, p)| is_text(p)).min_by(|a, b| dist(a.1).total_cmp(&dist(b.1)))?;+ let rel = if is_rtl(&p.text) { p.w - (x - p.x) } else { x - p.x };+ let (mut acc, mut ch) = (0.0, 0);+ for (k, c) in p.text.chars().enumerate() {+ let cw = f.width_f(&c.to_string(), p.size, p.face);+ if rel < acc + cw / 2.0 { return Some(SelPoint { idx, ch: k }); }+ acc += cw;+ ch = k + 1;+ }+ Some(SelPoint { idx, ch })+}++fn ordered(a: SelPoint, b: SelPoint) -> (SelPoint, SelPoint) { if (a.idx, a.ch) <= (b.idx, b.ch) { (a, b) } else { (b, a) } }++/// (word index, first char, last char + 1) of every selected piece in reading order.+fn pieces(placed: &[Placed], a: SelPoint, b: SelPoint) -> Vec<(usize, usize, usize)> {+ let (a, b) = ordered(a, b);+ (a.idx..=b.idx.min(placed.len().saturating_sub(1))).filter(|&i| is_text(&placed[i])).filter_map(|i| {+ let len = placed[i].text.chars().count();+ let (s, e) = (if i == a.idx { a.ch } else { 0 }, if i == b.idx { b.ch.min(len) } else { len });+ (s < e).then_some((i, s, e))+ }).collect()+}++/// Plain text of the selection: words separated by spaces, new lines where the baseline changes.+pub fn selected_text(placed: &[Placed], a: SelPoint, b: SelPoint) -> String {+ let mut out = String::new();+ let mut prev: Option<&Placed> = None;+ for (i, s, e) in pieces(placed, a, b) {+ let p = &placed[i];+ if let Some(q) = prev { out.push(if p.base - q.base > q.size.min(p.size) * 0.6 { '\n' } else { ' ' }); }+ out.extend(p.text.chars().skip(s).take(e - s));+ prev = Some(p);+ }+ out+}++/// Highlight rectangles (x, top, w, h) for the selection.+pub fn selection_rects(placed: &[Placed], a: SelPoint, b: SelPoint, f: &mut Fonts) -> Vec<(f32, f32, f32, f32)> {+ pieces(placed, a, b).into_iter().map(|(i, s, e)| {+ let p = &placed[i];+ let len = p.text.chars().count();+ let (off, w) = if s == 0 && e == len { (0.0, p.w) } else { (span_w(p, 0, s, f), span_w(p, s, e, f)) };+ (p.x + off, p.base - p.size, w, p.size * 1.25)+ }).collect()+}++/// Whole-word selection around a point (double click).+pub fn word_at(placed: &[Placed], pt: SelPoint) -> (SelPoint, SelPoint) {+ let len = placed.get(pt.idx).map_or(0, |p| p.text.chars().count());+ (SelPoint { idx: pt.idx, ch: 0 }, SelPoint { idx: pt.idx, ch: len })+}++/// First and last text position of the page (select all).+pub fn all(placed: &[Placed]) -> Option<(SelPoint, SelPoint)> {+ let first = placed.iter().position(is_text)?;+ let last = placed.iter().rposition(is_text)?;+ Some((SelPoint { idx: first, ch: 0 }, SelPoint { idx: last, ch: placed[last].text.chars().count() }))+}++/// Element under a layout point: the word/picture there, else the topmost box rectangle (0 = nothing).+pub fn hit_node(placed: &[Placed], rects: &[crate::layout::Rect], x: f32, y: f32) -> usize {+ placed.iter().rev().find(|p| p.node != 0 && x >= p.x && x <= p.x + p.w && y >= p.base - p.size && y <= p.base + p.size * 0.3).map(|p| p.node)+ .or_else(|| rects.iter().rev().find(|r| r.node != 0 && x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h).map(|r| r.node))+ .unwrap_or(0)+}++/// Bounding boxes `(node, x, y, w, h)` in CSS px (layout px / `scale`) of every node that has painted content, including+/// ancestors (the union of what they contain). `parents[i]` is the DOM parent of node `i`.+pub fn node_boxes(placed: &[Placed], rects: &[crate::layout::Rect], parents: &[usize], scale: f32) -> Vec<(usize, f32, f32, f32, f32)> {+ let mut map: std::collections::HashMap<usize, (f32, f32, f32, f32)> = std::collections::HashMap::new(); // x0, y0, x1, y1+ let mut add = |node: usize, b: (f32, f32, f32, f32)| {+ let mut n = node;+ while n != 0 {+ let e = map.entry(n).or_insert(b);+ *e = (e.0.min(b.0), e.1.min(b.1), e.2.max(b.2), e.3.max(b.3));+ n = parents.get(n).copied().unwrap_or(0);+ }+ };+ for p in placed.iter().filter(|p| p.node != 0) { add(p.node, (p.x, p.base - p.size, p.x + p.w, p.base + p.size * 0.25)); }+ for r in rects.iter().filter(|r| r.node != 0 && r.ring == 0.0) { add(r.node, (r.x, r.y, r.x + r.w, r.y + r.h)); }+ map.into_iter().map(|(n, b)| (n, b.0 / scale, b.1 / scale, (b.2 - b.0) / scale, (b.3 - b.1) / scale)).collect()+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::{dom::parse, layout::layout, render};+ use std::collections::HashMap;++ fn lay(html: &str) -> Option<(Vec<Placed>, Fonts)> {+ let mut f = Fonts::system()?;+ let pg = render::build(&parse(html, true), "https://a.com", HashMap::new());+ let (p, _, _) = layout(&pg.items, 800.0, 1.0, &mut f);+ Some((p, f))+ }++ #[test]+ fn find_is_case_insensitive_and_matches_phrases_across_words() {+ let Some((p, mut f)) = lay("<p>Alpha beta<br>gamma BETA delta</p>") else { return };+ let m = find_matches(&p, "beta", &mut f);+ assert_eq!(m.len(), 2);+ assert_eq!(m[0].parts.len(), 1);+ let ph = find_matches(&p, "alpha beta", &mut f);+ assert_eq!((ph.len(), ph[0].parts.len()), (1, 2), "a phrase spans two words");+ let part = find_matches(&p, "amm", &mut f);+ assert!(part[0].parts[0].1 > 0.0 && part[0].parts[0].2 > 0.0, "inside-word match has an offset and a width");+ assert!(find_matches(&p, "nothing", &mut f).is_empty() && find_matches(&p, " ", &mut f).is_empty());+ }++ #[test]+ fn selection_points_text_and_rects() {+ let Some((p, mut f)) = lay("<p>alpha beta<br>gamma delta</p>") else { return };+ let beta = p.iter().find(|q| q.text == "beta").unwrap();+ let a = hit_point(&p, beta.x + 1.0, beta.base - 5.0, &mut f).unwrap();+ assert_eq!((p[a.idx].text.as_str(), a.ch), ("beta", 0));+ let gamma = p.iter().find(|q| q.text == "gamma").unwrap();+ let b = hit_point(&p, gamma.x + gamma.w - 1.0, gamma.base - 5.0, &mut f).unwrap();+ assert_eq!((p[b.idx].text.as_str(), b.ch), ("gamma", 5));+ assert_eq!(selected_text(&p, a, b), "beta\ngamma");+ assert_eq!(selected_text(&p, b, a), "beta\ngamma", "order does not matter");+ let rects = selection_rects(&p, a, b, &mut f);+ assert_eq!(rects.len(), 2);+ let (s, e) = all(&p).unwrap();+ assert_eq!(selected_text(&p, s, e), "alpha beta\ngamma delta");+ let (w0, w1) = word_at(&p, a);+ assert_eq!(selected_text(&p, w0, w1), "beta");+ let far = hit_point(&p, 5000.0, 5000.0, &mut f).unwrap();+ assert_eq!(p[far.idx].text, "delta", "points outside the text snap to the nearest word");+ }++ #[test]+ fn hit_nodes_and_boxes_follow_the_dom() {+ let mut f = match Fonts::system() { Some(f) => f, None => return };+ let d = parse("<div id=a style='background:#eee;padding:0 8px'><span id=b>hello</span> world</div>", true);+ let pg = render::build(&d, "https://a.com", HashMap::new());+ let (placed, rects, _) = layout(&pg.items, 800.0, 1.0, &mut f);+ let id_of = |name: &str| d.descendants().into_iter().find(|&i| d.attr(i, "id") == Some(name)).unwrap();+ let hello = placed.iter().find(|p| p.text == "hello").unwrap();+ let text_node = hit_node(&placed, &rects, hello.x + 2.0, hello.base - 4.0);+ assert_eq!(d.nodes[text_node].parent, id_of("b"), "a word belongs to its text node, whose parent is the span");+ assert_eq!(hit_node(&placed, &rects, 790.0, 5000.0), 0);+ let boxes = node_boxes(&placed, &rects, &pg.parents, 1.0);+ let b = |n: usize| boxes.iter().find(|x| x.0 == n).copied().unwrap();+ let (span, div) = (b(id_of("b")), b(id_of("a")));+ assert!(span.4 > 5.0 && span.3 > 20.0 && span.2 >= div.2 - 0.5, "span {span:?} div {div:?}");+ assert!(div.1 + div.3 >= span.1 + span.3 + 20.0, "the div contains the span plus ' world': {div:?} {span:?}");+ }+}diff --git a/plugins/chrome-rs/src/css.rs b/plugins/chrome-rs/src/css.rsnew file mode 100644index 0000000..d2127d7--- /dev/null+++ b/plugins/chrome-rs/src/css.rs@@ -0,0 +1,1311 @@+// CSS: parser, selector matching, cascade for the properties a text-flow renderer can use.+// Supported: display, color, font-size, font-weight, text-align, text-decoration, margin/padding (vertical gaps ++// left indent), background (page only), visibility/opacity:0 (hide), list-style:none, flex-direction.+// shortcut: sticky acts as relative, grid has columns only, no :hover/:focus/:active; @media evaluated against a fixed 1000px viewport.+use crate::dom::Dom;+use std::{borrow::Cow, collections::HashMap, rc::Rc, sync::{atomic::{AtomicUsize, Ordering}, Arc}};++const VIEWPORT_W: f32 = 1000.0;++#[derive(Clone, Copy, PartialEq)]+enum Comb { Desc, Child, Adj, Sib }++struct AttrSel { name: String, op: char, val: String } // op ' ' = exists++#[derive(Default)]+struct Compound { tag: Option<String>, id: Option<String>, classes: Vec<String>, attrs: Vec<AttrSel>, first: bool, last: bool, never: bool, nots: Vec<Compound>,+ nths: Vec<(bool, bool, i32, i32)>, // (of-type, from-last, a, b) for :nth-*(an+b)+ is: Vec<(bool, Vec<Compound>)>, // :is()/:where() any-of lists (bool = counts toward specificity)+ empty: bool, pseudo: u8,+ state: u8, // :hover 1, :active 2, :focus 4, :focus-within 8+}++struct Complex { parts: Vec<(Comb, Compound)> }++pub struct Decl { prop: String, val: String, imp: bool }++struct Rule { sel: Complex, spec: u32, order: usize, decls: Rc<Vec<Decl>> }++#[derive(Default)]+pub struct Sheet {+ rules: Vec<Rule>,+ by_id: HashMap<String, Vec<usize>>,+ by_class: HashMap<String, Vec<usize>>,+ by_tag: HashMap<String, Vec<usize>>,+ other: Vec<usize>,+ has_pseudo: bool,+ /// some rule depends on :hover/:active/:focus, so the page must be restyled when that state changes+ pub has_state: bool,+ pub faces: Vec<FontFaceRule>,+}++/// One `@font-face` declaration: family (lowercase), weight/style flags and candidate sources in page order.+#[derive(Clone, Debug, PartialEq)]+pub struct FontFaceRule { pub family: String, pub bold: bool, pub italic: bool, pub srcs: Vec<(String, String)> }++fn is_ident(c: char) -> bool { c.is_alphanumeric() || c == '-' || c == '_' || !c.is_ascii() }++fn parse_complex(s: &str) -> Option<Complex> {+ let cs: Vec<char> = s.trim().chars().collect();+ let (mut parts, mut comb, mut cur, mut have, mut i) = (vec![], Comb::Desc, Compound::default(), false, 0);+ let ident = |i: &mut usize| -> String {+ let s0 = *i;+ while *i < cs.len() && is_ident(cs[*i]) { *i += 1; }+ cs[s0..*i].iter().collect()+ };+ while i < cs.len() {+ match cs[i] {+ c if c.is_whitespace() || matches!(c, '>' | '+' | '~') => {+ let mut nc = None;+ while i < cs.len() && (cs[i].is_whitespace() || matches!(cs[i], '>' | '+' | '~')) {+ match cs[i] { '>' => nc = Some(Comb::Child), '+' => nc = Some(Comb::Adj), '~' => nc = Some(Comb::Sib), _ => {} }+ i += 1;+ }+ if have { parts.push((comb, std::mem::take(&mut cur))); have = false; }+ comb = nc.unwrap_or(Comb::Desc);+ }+ '#' => { i += 1; cur.id = Some(ident(&mut i)); have = true; }+ '.' => { i += 1; cur.classes.push(ident(&mut i)); have = true; }+ '*' => { i += 1; have = true; }+ '[' => {+ let close = cs[i..].iter().position(|&c| c == ']')? + i;+ let body: String = cs[i + 1..close].iter().collect();+ i = close + 1;+ have = true;+ let (name, op, val) = match body.find('=') {+ Some(p) => {+ let (n, op) = match body[..p].chars().last() { Some(o @ ('~' | '|' | '^' | '$' | '*')) => (&body[..p - 1], o), _ => (&body[..p], '=') };+ (n.trim().to_string(), op, body[p + 1..].trim().trim_matches(['"', '\'']).to_string())+ }+ None => (body.trim().to_string(), ' ', String::new()),+ };+ cur.attrs.push(AttrSel { name: name.to_ascii_lowercase(), op, val });+ }+ ':' => {+ let double = cs.get(i + 1) == Some(&':');+ i += 1 + double as usize;+ let name = ident(&mut i);+ let mut arg = String::new();+ if cs.get(i) == Some(&'(') {+ let (mut depth, start) = (0, i + 1);+ while i < cs.len() {+ if cs[i] == '(' { depth += 1 } else if cs[i] == ')' { depth -= 1; if depth == 0 { arg = cs[start..i].iter().collect(); i += 1; break; } }+ i += 1;+ }+ }+ have = true;+ match (double, name.as_str()) {+ (false, "not") => match parse_complex(&arg) {+ Some(c) if c.parts.len() == 1 => cur.nots.push(c.parts.into_iter().next().unwrap().1),+ _ => cur.never = true,+ },+ (false, "nth-child" | "nth-last-child" | "nth-of-type" | "nth-last-of-type") => match parse_nth(&arg) {+ Some((a, b)) => cur.nths.push((name.contains("of-type"), name.contains("last"), a, b)),+ None => cur.never = true,+ },+ (false, "first-of-type") => cur.nths.push((true, false, 0, 1)),+ (false, "last-of-type") => cur.nths.push((true, true, 0, 1)),+ (false, "only-child") => { cur.first = true; cur.last = true; }+ (false, "empty") => cur.empty = true,+ (false, "checked" | "disabled") => cur.attrs.push(AttrSel { name: name.clone(), op: ' ', val: String::new() }),+ (false, "is" | "where" | "matches" | "any" | "-webkit-any" | "-moz-any") => {+ let list: Vec<Compound> = split_top(&arg, ',').into_iter().filter_map(parse_complex).filter(|c| c.parts.len() == 1).filter_map(|c| c.parts.into_iter().next().map(|p| p.1)).collect();+ if list.is_empty() { cur.never = true } else { cur.is.push((name != "where", list)); }+ }+ (_, "before" | "after") => cur.pseudo = if name == "before" { 1 } else { 2 },+ (false, "first-child") => cur.first = true,+ (false, "last-child") => cur.last = true,+ (false, "hover") => cur.state |= 1,+ (false, "active") => cur.state |= 2,+ (false, "focus" | "focus-visible") => cur.state |= 4,+ (false, "focus-within") => cur.state |= 8,+ (false, "link" | "visited" | "any-link") => {}+ (false, "root") => cur.tag = Some("html".into()),+ _ => cur.never = true,+ }+ }+ c if is_ident(c) => { cur.tag = Some(ident(&mut i).to_ascii_lowercase()); have = true; }+ _ => return None,+ }+ }+ if have { parts.push((comb, cur)); }+ if parts.is_empty() { None } else { Some(Complex { parts }) }+}++fn parse_nth(s: &str) -> Option<(i32, i32)> {+ let t: String = s.split(" of ").next().unwrap_or("").chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase();+ match t.as_str() { "odd" => return Some((2, 1)), "even" => return Some((2, 0)), _ => {} }+ match t.split_once('n') {+ None => t.parse().ok().map(|b| (0, b)),+ Some((a, b)) => Some((match a { "" | "+" => 1, "-" => -1, x => x.parse().ok()? }, if b.is_empty() { 0 } else { b.parse().ok()? })),+ }+}++fn compound_spec(p: &Compound) -> u32 {+ p.id.is_some() as u32 * 10_000 + (p.classes.len() + p.attrs.len() + p.first as usize + p.last as usize + p.nths.len() + p.state.count_ones() as usize) as u32 * 100 + p.tag.is_some() as u32+ + p.is.iter().filter(|l| l.0).map(|l| l.1.iter().map(compound_spec).max().unwrap_or(0)).sum::<u32>()+ + p.nots.iter().map(compound_spec).sum::<u32>() // :not(x) counts as its argument+}++fn specificity(c: &Complex) -> u32 { c.parts.iter().map(|(_, p)| compound_spec(p)).sum() }++fn elem_siblings(dom: &Dom, id: usize) -> Vec<usize> {+ dom.nodes[dom.nodes[id].parent].kids.iter().copied().filter(|&k| !dom.nodes[k].tag.is_empty()).collect()+}++fn match_compound(dom: &Dom, id: usize, c: &Compound) -> bool {+ if c.never { return false; }+ if c.nots.iter().any(|n| match_compound(dom, id, n)) { return false; }+ let n = &dom.nodes[id];+ if n.tag.is_empty() || c.tag.as_ref().is_some_and(|t| *t != n.tag) { return false; }+ if c.id.as_deref().is_some_and(|i| dom.attr(id, "id") != Some(i)) { return false; }+ if !c.classes.is_empty() {+ let cl = dom.attr(id, "class").unwrap_or("");+ if !c.classes.iter().all(|k| cl.split_whitespace().any(|x| x == k)) { return false; }+ }+ for a in &c.attrs {+ let Some(v) = dom.attr(id, &a.name) else { return false };+ let ok = match a.op {+ ' ' => true,+ '=' => v == a.val,+ '~' => v.split_whitespace().any(|x| x == a.val),+ '|' => v == a.val || v.starts_with(&format!("{}-", a.val)),+ '^' => v.starts_with(&a.val),+ '$' => v.ends_with(&a.val),+ _ => v.contains(&a.val),+ };+ if !ok { return false; }+ }+ for &(of_type, from_last, a, b) in &c.nths {+ let sib: Vec<usize> = elem_siblings(dom, id).into_iter().filter(|&k| !of_type || dom.nodes[k].tag == n.tag).collect();+ let Some(pos) = sib.iter().position(|&k| k == id) else { return false };+ let d = (if from_last { sib.len() - pos } else { pos + 1 }) as i32 - b;+ if !(if a == 0 { d == 0 } else { d % a == 0 && d / a >= 0 }) { return false; }+ }+ if c.empty && !n.kids.iter().all(|&k| dom.nodes[k].tag.is_empty() && dom.nodes[k].text.is_empty()) { return false; }+ if c.is.iter().any(|(_, list)| !list.iter().any(|x| match_compound(dom, id, x))) { return false; }+ if c.first || c.last {+ let sib = elem_siblings(dom, id);+ if c.first && sib.first() != Some(&id) || c.last && sib.last() != Some(&id) { return false; }+ }+ if c.state != 0 {+ let (hover, active, focus) = state();+ if c.state & 1 != 0 && !within(dom, id, hover) || c.state & 2 != 0 && !within(dom, id, active) || c.state & 4 != 0 && (focus != id || id == 0) || c.state & 8 != 0 && !within(dom, id, focus) { return false; }+ }+ true+}++// Interaction state for :hover / :active / :focus: DOM node ids of the pointer target, the pressed element and the focused control (0 = none).+// A process-wide value because page builders run on other threads than the UI.+static STATE: [AtomicUsize; 3] = [AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)];++pub fn set_state(hover: usize, active: usize, focus: usize) { for (s, v) in STATE.iter().zip([hover, active, focus]) { s.store(v, Ordering::Relaxed); } }++fn state() -> (usize, usize, usize) { (STATE[0].load(Ordering::Relaxed), STATE[1].load(Ordering::Relaxed), STATE[2].load(Ordering::Relaxed)) }++/// `id` is `target` or one of its ancestors (the pointer is over a descendant of a hovered element's box).+fn within(dom: &Dom, id: usize, target: usize) -> bool {+ let mut n = target;+ while n != 0 { if n == id { return true; } n = dom.nodes.get(n).map_or(0, |x| x.parent); }+ false+}++fn match_at(dom: &Dom, id: usize, parts: &[(Comb, Compound)], i: usize) -> bool {+ if !match_compound(dom, id, &parts[i].1) { return false; }+ if i == 0 { return true; }+ let parent = dom.nodes[id].parent;+ match parts[i].0 {+ Comb::Desc => { let mut p = parent; while p != 0 { if match_at(dom, p, parts, i - 1) { return true; } p = dom.nodes[p].parent; } false }+ Comb::Child => parent != 0 && match_at(dom, parent, parts, i - 1),+ Comb::Adj | Comb::Sib => {+ let sib = elem_siblings(dom, id);+ let pos = sib.iter().position(|&s| s == id).unwrap_or(0);+ if parts[i].0 == Comb::Adj { pos > 0 && match_at(dom, sib[pos - 1], parts, i - 1) } else { sib[..pos].iter().any(|&s| match_at(dom, s, parts, i - 1)) }+ }+ }+}++fn strip_comments(css: &str) -> String {+ let mut out = String::with_capacity(css.len());+ let mut rest = css;+ while let Some(p) = rest.find("/*") {+ out.push_str(&rest[..p]);+ rest = rest[p + 2..].find("*/").map_or("", |e| &rest[p + 2 + e + 2..]);+ }+ out + rest+}++fn matching_brace(css: &str, open: usize) -> usize {+ let (mut depth, b) = (0i32, css.as_bytes());+ for (k, &c) in b.iter().enumerate().skip(open) {+ if c == b'{' { depth += 1 } else if c == b'}' { depth -= 1; if depth == 0 { return k; } }+ }+ b.len()+}++fn media_ok(q: &str) -> bool {+ let q = q.to_ascii_lowercase();+ if ["print", "speech", "prefers-color-scheme: dark", "pointer: coarse", "hover: none", "prefers-reduced-motion: reduce"].iter().any(|k| q.contains(k)) { return false; }+ let num = |key: &str| -> Vec<f32> {+ q.match_indices(key).filter_map(|(p, _)| {+ let r = q[p + key.len()..].trim_start();+ let end = r.find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap_or(r.len());+ let n: f32 = r[..end].parse().ok()?;+ Some(if r[end..].starts_with("em") { n * 16.0 } else { n })+ }).collect()+ };+ num("max-width:").iter().all(|&n| n >= VIEWPORT_W) && num("min-width:").iter().all(|&n| n <= VIEWPORT_W)+}++/// Whitespace split that keeps `calc(1px + 2px)` together.+fn split_ws(s: &str) -> Vec<&str> {+ let (mut out, mut depth, mut start) = (vec![], 0i32, None::<usize>);+ for (i, c) in s.char_indices() {+ match c {+ '(' => depth += 1,+ ')' => depth -= 1,+ c if c.is_whitespace() && depth <= 0 => { if let Some(st) = start.take() { out.push(&s[st..i]); } continue; }+ _ => {}+ }+ start.get_or_insert(i);+ }+ if let Some(st) = start { out.push(&s[st..]); }+ out+}++fn split_top(s: &str, sep: char) -> Vec<&str> {+ let (mut out, mut depth, mut quote, mut last) = (vec![], 0i32, None::<char>, 0);+ for (i, c) in s.char_indices() {+ match (quote, c) {+ (Some(q), c) if c == q => quote = None,+ (Some(_), _) => {}+ (None, '"' | '\'') => quote = Some(c),+ (None, '(') => depth += 1,+ (None, ')') => depth -= 1,+ (None, c) if c == sep && depth == 0 => { out.push(&s[last..i]); last = i + 1; }+ _ => {}+ }+ }+ out.push(&s[last..]);+ out+}++pub fn parse_decls(body: &str) -> Vec<Decl> {+ split_top(body, ';').into_iter().filter_map(|d| {+ let (p, v) = d.split_once(':')?;+ let (prop, mut val) = (if p.trim().starts_with("--") { p.trim().to_string() } else { p.trim().to_ascii_lowercase() }, v.trim());+ let imp = val.to_ascii_lowercase().ends_with("!important");+ if imp { val = val[..val.len() - 10].trim(); }+ (!prop.is_empty()).then(|| Decl { prop, val: val.to_string(), imp })+ }).collect()+}++fn parse_rules(css: &str, out: &mut Vec<Rule>, order: &mut usize, faces: &mut Vec<FontFaceRule>) {+ let (mut i, len) = (0, css.len());+ while i < len {+ let rest = &css[i..];+ let skipped = rest.len() - rest.trim_start().len();+ i += skipped;+ if i >= len { break; }+ let rest = &css[i..];+ if rest.starts_with('@') {+ let (semi, brace) = (rest.find(';'), rest.find('{'));+ match (semi, brace) {+ (Some(s), b) if b.is_none_or(|b| s < b) => i += s + 1,+ (_, Some(b)) => {+ let end = matching_brace(css, i + b);+ if rest.starts_with("@media") && media_ok(&rest[6..b]) { parse_rules(&css[i + b + 1..end.min(len)], out, order, faces); }+ if rest[..b].trim() == "@font-face" { faces.extend(parse_face(&css[i + b + 1..end.min(len)])); }+ i = end + 1;+ }+ _ => break,+ }+ continue;+ }+ let Some(b) = rest.find('{') else { break };+ let end = matching_brace(css, i + b);+ let (sel, body) = (&rest[..b], &css[i + b + 1..end.min(len)]);+ i = end + 1;+ let decls = Rc::new(parse_decls(body));+ if decls.is_empty() { continue; }+ for s in split_top(sel, ',') {+ if let Some(c) = parse_complex(s) {+ out.push(Rule { spec: specificity(&c), order: *order, sel: c, decls: decls.clone() });+ *order += 1;+ }+ }+ }+}++fn parse_face(body: &str) -> Option<FontFaceRule> {+ let d = parse_decls(body);+ let get = |p: &str| d.iter().rev().find(|x| x.prop == p).map(|x| x.val.as_str());+ let family = get("font-family")?.trim().trim_matches(['"', '\'']).trim().to_ascii_lowercase();+ let srcs: Vec<(String, String)> = split_top(get("src")?, ',').into_iter().filter_map(|part| {+ let p = part.find("url(")?;+ let rest = &part[p + 4..];+ let url = rest[..rest.find(')')?].trim().trim_matches(['"', '\'']).to_string();+ let fmt = part.find("format(").and_then(|f| part[f + 7..].find(')').map(|e| part[f + 7..f + 7 + e].trim().trim_matches(['"', '\'']).to_ascii_lowercase())).unwrap_or_default();+ Some((url, fmt))+ }).collect();+ let weight = get("font-weight").unwrap_or("400");+ let bold = matches!(weight, "bold" | "bolder") || weight.split_whitespace().next().and_then(|w| w.parse::<u32>().ok()).is_some_and(|w| w >= 600);+ (!family.is_empty() && !srcs.is_empty()).then(|| FontFaceRule { family, bold, italic: get("font-style").is_some_and(|v| v.starts_with("italic") || v.starts_with("oblique")), srcs })+}++impl Sheet {+ pub fn has_face(&self, family: &str) -> bool { !self.faces.is_empty() && self.faces.iter().any(|f| f.family == family) }++ /// Sheets are concatenated in cascade order (earlier = lower precedence on ties).+ pub fn new(sheets: &[String]) -> Sheet {+ let (mut rules, mut order) = (vec![], 0);+ let mut faces = vec![];+ for s in sheets { parse_rules(&strip_comments(s), &mut rules, &mut order, &mut faces); }+ let mut sh = Sheet { faces, ..Sheet::default() };+ for (k, r) in rules.iter().enumerate() {+ let key = &r.sel.parts.last().unwrap().1;+ if key.pseudo != 0 { sh.has_pseudo = true; }+ if r.sel.parts.iter().any(|p| p.1.state != 0) { sh.has_state = true; }+ if let Some(i) = &key.id { sh.by_id.entry(i.clone()).or_default().push(k); }+ else if let Some(c) = key.classes.first() { sh.by_class.entry(c.clone()).or_default().push(k); }+ else if let Some(t) = &key.tag { sh.by_tag.entry(t.clone()).or_default().push(k); }+ else { sh.other.push(k); }+ }+ sh.rules = rules;+ sh+ }++ /// Rules matching `id`; `which` 0 = the element itself, 1/2 = its ::before/::after.+ fn matching(&self, dom: &Dom, id: usize, which: u8) -> Vec<&Rule> {+ let mut out = Vec::new();+ let mut check = |ks: &[usize]| for &k in ks {+ let r = &self.rules[k];+ if r.sel.parts.last().is_some_and(|p| p.1.pseudo == which) && match_at(dom, id, &r.sel.parts, r.sel.parts.len() - 1) { out.push(r); }+ };+ check(&self.other);+ if let Some(v) = dom.attr(id, "id").and_then(|i| self.by_id.get(i)) { check(v); }+ for c in dom.attr(id, "class").unwrap_or("").split_whitespace() { if let Some(v) = self.by_class.get(c) { check(v); } }+ if let Some(v) = self.by_tag.get(&dom.nodes[id].tag) { check(v); }+ out+ }+}++#[derive(Clone)]+pub struct Style {+ pub none: bool,+ pub block: bool,+ pub list_item: bool,+ pub flex_row: bool,+ pub color: u32,+ pub size: f32,+ pub bold: bool,+ pub align: u8, // 0 left, 1 center, 2 right+ pub underline: bool,+ pub bullets: bool,+ pub collapse: bool, // border-collapse: collapse (inherited)+ /// Vertical margins (+ vertical padding) as flow gaps; horizontal margins/padding stay separate for box layout.+ pub mt: f32,+ pub mb: f32,+ pub ml: f32,+ pub mr: f32,+ pub pl: f32,+ pub pr: f32,+ pub auto_l: bool,+ pub auto_r: bool,+ pub width: Option<Len>,+ pub max_width: Option<Len>,+ pub pad: [f32; 4], // raw padding (top, right, bottom, left), used by table cells+ pub pad_set: bool,+ pub valign: u8, // 0 top, 1 middle, 2 bottom+ pub float: u8, // 0 none, 1 left, 2 right+ pub clear: u8, // bit 0 = left, bit 1 = right+ pub borders: [Option<(f32, u32)>; 4], // top, right, bottom, left: (width px, color)+ pub mono: bool, // monospace font (inherited)+ pub pre: bool, // white-space: pre / pre-wrap (inherited)+ pub bg: Option<u32>,+ pub vars: Rc<HashMap<String, String>>, // custom properties (inherited)+ pub nowrap: bool, // white-space: nowrap (inherited)+ pub italic: bool, // font-style (inherited)+ pub fam: u16, // web-font family id from font-family (inherited)+ pub tt: u8, // text-transform: 0 none, 1 upper, 2 lower, 3 capitalize (inherited)+ pub lh: f32, // line-height as a multiple of the font size (inherited)+ pub pt: f32, // vertical padding (already part of mt/mb as flow gaps); boxes with a background paint it+ pub pb: f32,+ pub bg_a: f32, // alpha of `bg` (rgba background)+ pub alpha: f32, // opacity of this element and its subtree, multiplied down (approximated by blending colors)+ pub ls: f32, // letter-spacing in px (inherited)+ pub bg_grad: Option<Arc<Grad>>,+ pub bg_img: Option<BgImage>,+ pub x: Ext,+}++/// `linear-gradient`: CSS angle in degrees (0 = up, 90 = right, 180 = down) and color stops at 0..1.+#[derive(Debug)]+pub struct Grad { pub angle: f32, pub stops: Vec<(f32, u32)>, pub radial: bool, pub circle: bool, pub at: (f32, f32) }++/// `background-image: url(...)` with its size, position (x, y) and repeat (x, y).+#[derive(Clone, Debug, PartialEq)]+pub struct BgImage { pub url: String, pub size: BgSize, pub pos: [Len; 2], pub repeat: (bool, bool) }++#[derive(Clone, Copy, Debug, PartialEq)]+pub enum BgSize { Auto, Cover, Contain, Fixed(Option<Len>, Option<Len>) }++/// First `box-shadow` layer; `color` is u32::MAX until resolved to the element's color.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Shadow { pub dx: f32, pub dy: f32, pub blur: f32, pub spread: f32, pub color: u32, pub a: f32 }++#[derive(Clone, Copy, Debug, PartialEq)]+pub enum Track { Px(f32), Pct(f32), Fr(f32) }++/// Non-inherited layout properties added after the first box model: positioning, inline-block and flex container/item settings.+#[derive(Clone, Default)]+pub struct Ext {+ pub pos: u8, // 0 static, 1 relative/sticky, 2 absolute+ pub off: [Option<Len>; 4], // top, right, bottom, left+ pub inline_block: bool,+ pub wrap: bool, pub gap: f32,+ pub justify: u8, // flex: 0 start, 1 center, 2 end, 3 between, 4 around, 5 evenly+ pub align: u8, // align-items / align-self: 0 stretch(=start), 1 start, 2 center, 3 end+ pub grow: f32, pub shrink: f32, pub basis: Option<Len>,+ pub min_h: f32, // height / min-height in px (treated as a minimum)+ pub bb: bool, // box-sizing: border-box+ pub radius: f32, // border-radius in px (9999 for >= 50 %)+ pub indent: f32, // text-indent in px (first line of this block)+ pub z: i32, // z-index (positioned boxes only)+ pub fix_h: bool, // `height` (not just min-height) was given: with overflow clipping the box is exactly that tall+ pub clip: bool, // overflow other than visible+ pub scroll: bool, // overflow: auto | scroll+ pub shadow: Option<Shadow>,+ pub flex_col: bool, pub grid: bool,+ pub tracks: Vec<Track>, pub auto_min: Option<f32>, // grid-template-columns (auto_min: repeat(auto-fill, minmax(N, 1fr)))+ pub row_gap: Option<f32>, pub span: usize, // grid: row-gap, grid-column span (0 = 1)+ pub va: f32, // vertical-align shift of inline text in em (super/sub), positive = up+ pub counter_reset: Vec<(String, i32)>, pub counter_inc: Vec<(String, i32)>,+ pub h_pct: Option<(f32, bool)>, // percentage height/min-height (value, exact), resolved by the renderer against a definite parent height+ pub sticky: bool, // position: sticky (pos = 1)+ pub va_kind: u8, // vertical-align keyword for images: 1 middle, 2 top, 3 bottom+}++/// A CSS length that may depend on the containing block.+#[derive(Clone, Copy, Debug, PartialEq)]+pub enum Len { Px(f32), Pct(f32), /** percent + px, from calc() */ Mix(f32, f32) }++impl Style {+ pub fn root() -> Style {+ Style {+ none: false, block: true, list_item: false, flex_row: false, color: 0x111111, size: 16.0, bold: false, align: 0, underline: false, bullets: true,+ collapse: false, mt: 0.0, mb: 0.0, ml: 0.0, mr: 0.0, pl: 0.0, pr: 0.0, auto_l: false, auto_r: false, width: None, max_width: None,+ pad: [0.0; 4], pad_set: false, valign: 0, float: 0, clear: 0, borders: [None; 4], mono: false, pre: false, bg: None, lh: 1.35, vars: Rc::default(), nowrap: false, italic: false, fam: 0, tt: 0, pt: 0.0, pb: 0.0, bg_a: 1.0, alpha: 1.0, ls: 0.0, bg_grad: None, bg_img: None, x: Ext { shrink: 1.0, ..Ext::default() },+ }+ }+ fn inherit(&self) -> Style {+ Style {+ none: false, block: false, list_item: false, flex_row: false, mt: 0.0, mb: 0.0, ml: 0.0, mr: 0.0, pl: 0.0, pr: 0.0, auto_l: false, auto_r: false,+ width: None, max_width: None, pad: [0.0; 4], pad_set: false, valign: 0, float: 0, clear: 0, borders: [None; 4], bg: None, pt: 0.0, pb: 0.0, bg_a: 1.0, bg_grad: None, bg_img: None, x: Ext { shrink: 1.0, ..Ext::default() }, ..self.clone()+ }+ }+}++/// `1px solid #ccc` -> (width, color); None when the border is off. A missing color means "currentcolor" (u32::MAX).+fn border_value(v: &str, em: f32) -> Option<(f32, u32)> {+ let toks: Vec<&str> = v.split_whitespace().collect();+ if toks.iter().any(|t| matches!(*t, "none" | "hidden")) || toks.is_empty() { return None; }+ let mut w = 3.0;+ for t in &toks {+ match *t { "thin" => w = 1.0, "medium" => w = 3.0, "thick" => w = 5.0, _ => if let Some(px) = length(t, em) { w = px } }+ }+ let color = if let Some(p) = v.find("rgb") { parse_color(&v[p..=v[p..].find(')').map_or(v.len() - 1, |e| p + e)]) } else { toks.iter().find_map(|t| parse_color(t)) };+ (w > 0.0).then_some((w.min(20.0), color.unwrap_or(u32::MAX)))+}++#[derive(Clone, Copy)]+struct V { pct: f32, px: f32, num: bool }++impl V {+ fn scale(self, k: f32) -> V { V { pct: self.pct * k, px: self.px * k, num: self.num } }+}++/// Recursive-descent evaluator for calc()/min()/max()/clamp() bodies into a linear (percent, px) value.+struct Calc<'a> { c: &'a [u8], i: usize, em: f32 }++impl Calc<'_> {+ fn ws(&mut self) { while self.c.get(self.i).is_some_and(|c| c.is_ascii_whitespace()) { self.i += 1; } }+ fn expr(&mut self) -> Option<V> {+ let mut a = self.term()?;+ loop {+ self.ws();+ let op = match self.c.get(self.i) { Some(&o @ (b'+' | b'-')) => o, _ => return Some(a) };+ self.i += 1;+ let b = self.term()?;+ if a.num != b.num { return None; }+ let k = if op == b'+' { 1.0 } else { -1.0 };+ a = V { pct: a.pct + k * b.pct, px: a.px + k * b.px, num: a.num };+ }+ }+ fn term(&mut self) -> Option<V> {+ let mut a = self.factor()?;+ loop {+ self.ws();+ let op = match self.c.get(self.i) { Some(&o @ (b'*' | b'/')) => o, _ => return Some(a) };+ self.i += 1;+ let b = self.factor()?;+ a = match (op, a.num, b.num) {+ (b'*', true, _) => b.scale(a.px),+ (b'*', _, true) => a.scale(b.px),+ (b'/', _, true) if b.px != 0.0 => a.scale(1.0 / b.px),+ _ => return None,+ };+ }+ }+ fn factor(&mut self) -> Option<V> {+ self.ws();+ let c = *self.c.get(self.i)?;+ match c {+ b'(' => { self.i += 1; let v = self.expr()?; self.ws(); if self.c.get(self.i) == Some(&b')') { self.i += 1; Some(v) } else { None } }+ b'-' => { self.i += 1; Some(self.factor()?.scale(-1.0)) }+ b'+' => { self.i += 1; self.factor() }+ c if c.is_ascii_digit() || c == b'.' => {+ let s0 = self.i;+ while self.c.get(self.i).is_some_and(|c| c.is_ascii_digit() || *c == b'.') { self.i += 1; }+ let n: f32 = std::str::from_utf8(&self.c[s0..self.i]).ok()?.parse().ok()?;+ let u0 = self.i;+ while self.c.get(self.i).is_some_and(|c| c.is_ascii_alphabetic() || *c == b'%') { self.i += 1; }+ let em = self.em;+ Some(match std::str::from_utf8(&self.c[u0..self.i]).ok()? {+ "" => V { pct: 0.0, px: n, num: true },+ "px" => V { pct: 0.0, px: n, num: false },+ "%" => V { pct: n, px: 0.0, num: false },+ "em" => V { pct: 0.0, px: n * em, num: false },+ "rem" => V { pct: 0.0, px: n * 16.0, num: false },+ "pt" => V { pct: 0.0, px: n * 4.0 / 3.0, num: false },+ "vw" | "vmax" => V { pct: 0.0, px: n * VIEWPORT_W / 100.0, num: false },+ "vh" | "vmin" => V { pct: 0.0, px: n * 7.2, num: false },+ "ch" | "ex" => V { pct: 0.0, px: n * em * 0.5, num: false },+ _ => return None,+ })+ }+ c if c.is_ascii_alphabetic() => {+ let s0 = self.i;+ while self.c.get(self.i).is_some_and(|c| c.is_ascii_alphabetic()) { self.i += 1; }+ let name = std::str::from_utf8(&self.c[s0..self.i]).ok()?.to_ascii_lowercase();+ if self.c.get(self.i) != Some(&b'(') { return None; }+ let open = self.i;+ let (mut depth, mut end) = (0, None);+ for (k, &ch) in self.c.iter().enumerate().skip(open) {+ if ch == b'(' { depth += 1 } else if ch == b')' { depth -= 1; if depth == 0 { end = Some(k); break; } }+ }+ let end = end?;+ let inner = std::str::from_utf8(&self.c[open + 1..end]).ok()?;+ self.i = end + 1;+ let args: Vec<V> = split_top(inner, ',').into_iter().map(|a| { let mut p = Calc { c: a.as_bytes(), i: 0, em: self.em }; let v = p.expr()?; p.ws(); (p.i == a.len()).then_some(v) }).collect::<Option<_>>()?;+ let plain = args.iter().all(|a| a.pct == 0.0);+ match (name.as_str(), args.len()) {+ ("calc" | "", 1) => Some(args[0]),+ ("min", n) if n >= 1 && plain => args.iter().copied().reduce(|a, b| if b.px < a.px { b } else { a }),+ ("max", n) if n >= 1 && plain => args.iter().copied().reduce(|a, b| if b.px > a.px { b } else { a }),+ ("clamp", 3) if plain => Some(V { px: args[1].px.max(args[0].px).min(args[2].px), ..args[1] }),+ _ => None,+ }+ }+ _ => None,+ }+ }+}++/// (percent, px) of `calc(...)`/`min(...)`/`max(...)`/`clamp(...)`; None for anything else or on a syntax error.+fn calc_eval(v: &str, em: f32) -> Option<(f32, f32)> {+ let v = v.trim();+ if !["calc(", "min(", "max(", "clamp("].iter().any(|p| v.to_ascii_lowercase().starts_with(p)) { return None; }+ let mut p = Calc { c: v.as_bytes(), i: 0, em };+ let r = p.expr()?;+ p.ws();+ (p.i == v.len()).then_some((r.pct, r.px))+}++/// Replaces every `var(--name, fallback)` using `vars`; None when a variable is undefined and has no fallback.+fn subst_vars(v: &str, vars: &HashMap<String, String>, depth: u8) -> Option<String> {+ let (mut out, mut rest) = (String::new(), v);+ while let Some(p) = rest.find("var(") {+ out.push_str(&rest[..p]);+ let (mut d, mut end) = (0, None);+ for (k, c) in rest[p + 3..].char_indices() {+ if c == '(' { d += 1 } else if c == ')' { d -= 1; if d == 0 { end = Some(p + 3 + k); break; } }+ }+ let end = end?;+ let inner = &rest[p + 4..end];+ let (name, fallback) = match inner.split_once(',') { Some((n, f)) => (n.trim(), Some(f.trim())), None => (inner.trim(), None) };+ let val = vars.get(name).cloned().or_else(|| fallback.map(String::from))?;+ out.push_str(&if depth < 8 && val.contains("var(") { subst_vars(&val, vars, depth + 1)? } else { val });+ rest = &rest[end + 1..];+ }+ out.push_str(rest);+ Some(out)+}++fn len_value(v: &str, em: f32) -> Option<Len> {+ let v = v.trim();+ if let Some((pct, px)) = calc_eval(v, em) { return Some(if pct == 0.0 { Len::Px(px) } else if px == 0.0 { Len::Pct(pct) } else { Len::Mix(pct, px) }); }+ if let Some(p) = v.strip_suffix('%') { return p.trim().parse().ok().map(Len::Pct); }+ length(v, em).map(Len::Px)+}++/// Token index for (top, right, bottom, left) given 1-4 shorthand values.+fn expand4(n: usize) -> Option<[usize; 4]> {+ Some(match n { 1 => [0, 0, 0, 0], 2 => [0, 1, 0, 1], 3 => [0, 1, 2, 1], 4 => [0, 1, 2, 3], _ => return None })+}++fn length(v: &str, em: f32) -> Option<f32> {+ let v = v.trim();+ if let Some((pct, px)) = calc_eval(v, em) { return (pct == 0.0).then_some(px); }+ let end = v.find(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-' || c == '+')).unwrap_or(v.len());+ let n: f32 = v[..end].parse().ok()?;+ Some(match &v[end..] { "px" | "" if end > 0 => n, "em" => n * em, "rem" => n * 16.0, "%" => n / 100.0 * em, "pt" => n * 4.0 / 3.0, "vw" | "vmax" => n * VIEWPORT_W / 100.0, "vh" | "vmin" => n * 7.2, "ch" | "ex" => n * em * 0.5, _ => return None })+}++/// Box shorthand -> (values, auto flags) as (top, right, bottom, left).+fn sides(v: &str, em: f32) -> Option<([f32; 4], [bool; 4])> {+ let t: Vec<&str> = split_ws(v);+ let ix = expand4(t.len())?;+ let (mut vals, mut auto) = ([0f32; 4], [false; 4]);+ for k in 0..4 {+ auto[k] = t[ix[k]] == "auto";+ vals[k] = if auto[k] { 0.0 } else { length(t[ix[k]], em)? };+ }+ Some((vals, auto))+}++pub fn parse_color(v: &str) -> Option<u32> { parse_color_a(v).map(|c| c.0) }++/// Color and alpha (0..1); fully transparent colors are None.+pub fn parse_color_a(v: &str) -> Option<(u32, f32)> {+ let v = v.trim().to_ascii_lowercase();+ if let Some(h) = v.strip_prefix('#') {+ let a = if h.len() == 8 { u8::from_str_radix(&h[6..], 16).ok()? as f32 / 255.0 } else if h.len() == 4 { h[3..].chars().next()?.to_digit(16)? as f32 / 15.0 } else { 1.0 };+ if a == 0.0 { return None; }+ return match h.len() {+ 3 | 4 => { let d: Vec<u32> = h.chars().take(3).map(|c| c.to_digit(16)).collect::<Option<_>>()?; Some((d[0] * 17 << 16 | d[1] * 17 << 8 | d[2] * 17, a)) }+ 6 | 8 => u32::from_str_radix(&h[..6], 16).ok().map(|c| (c, a)),+ _ => None,+ };+ }+ if v.starts_with("rgb") {+ let inner = &v[v.find('(')? + 1..v.rfind(')')?];+ let toks: Vec<&str> = inner.split([',', ' ', '/']).filter(|x| !x.is_empty()).collect();+ if toks.len() < 3 { return None; }+ let ch = |x: &str| x.strip_suffix('%').map_or_else(|| x.parse::<f32>().ok(), |p| p.parse::<f32>().ok().map(|n| n * 2.55));+ let (r, g, b) = (ch(toks[0])?, ch(toks[1])?, ch(toks[2])?);+ let a = match toks.get(3) { Some(x) => x.strip_suffix('%').map_or_else(|| x.parse::<f32>().ok(), |p| p.parse::<f32>().ok().map(|n| n / 100.0))?, None => 1.0 }.clamp(0.0, 1.0);+ if a == 0.0 { return None; }+ return Some(((r.clamp(0.0, 255.0) as u32) << 16 | (g.clamp(0.0, 255.0) as u32) << 8 | b.clamp(0.0, 255.0) as u32, a));+ }+ Some((match v.as_str() {+ "black" => 0, "white" => 0xFFFFFF, "red" => 0xFF0000, "green" => 0x008000, "blue" => 0x0000FF, "gray" | "grey" => 0x808080,+ "silver" => 0xC0C0C0, "yellow" => 0xFFFF00, "orange" => 0xFFA500, "purple" => 0x800080, "navy" => 0x000080, "teal" => 0x008080,+ "maroon" => 0x800000, "lime" => 0x00FF00, "aqua" | "cyan" => 0x00FFFF, "fuchsia" | "magenta" => 0xFF00FF, "olive" => 0x808000,+ "darkgray" | "darkgrey" => 0xA9A9A9, "lightgray" | "lightgrey" => 0xD3D3D3, "brown" => 0xA52A2A, "pink" => 0xFFC0CB,+ _ => return None,+ }, 1.0))+}++/// First color of a `background` value and its alpha; gradients give their first stop (a flat fallback under the real gradient).+fn background_color(v: &str) -> Option<(u32, f32)> {+ if let Some(p) = v.find("gradient(") {+ let inner = &v[p + 9..];+ if let Some(r) = inner.find("rgb") { return parse_color_a(&inner[r..=inner[r..].find(')').map_or(inner.len() - 1, |e| r + e)]).map(|c| (c.0, 1.0)); }+ return inner.split([',', '(', ')', ' ']).find_map(parse_color).map(|c| (c, 1.0));+ }+ if let Some(r) = v.find("rgb") { return parse_color_a(&v[r..=v[r..].find(')').map_or(v.len() - 1, |e| r + e)]); }+ split_ws(v).into_iter().find_map(parse_color_a)+}++/// `linear-gradient(angle|to side, stop, stop...)`; None for anything else (radial and conic fall back to the first stop).+fn parse_gradient(v: &str) -> Option<Grad> {+ let (radial, p) = match v.find("radial-gradient(") { Some(p) => (true, p), None => (false, v.find("linear-gradient(")?) };+ let body = &v[p + 16..];+ let (mut depth, mut end) = (1, None);+ for (i, c) in body.char_indices() { if c == '(' { depth += 1 } else if c == ')' { depth -= 1; if depth == 0 { end = Some(i); break; } } }+ let args = split_top(&body[..end?], ',');+ let first = args.first()?.trim();+ let (mut angle, mut from) = (180.0f32, 0);+ let (mut circle, mut at) = (false, (0.5f32, 0.5f32));+ if radial {+ if !split_ws(first).iter().any(|t| parse_color(t).is_some()) {+ circle = first.contains("circle");+ if let Some(i) = first.find("at ") {+ let pct = |l: Len| if let Len::Pct(p) = l { p / 100.0 } else { 0.5 };+ let [x, y] = parse_bg_pos(&split_ws(&first[i + 3..]), 16.0);+ at = (pct(x), pct(y));+ }+ from = 1;+ }+ } else if let Some(dir) = first.strip_prefix("to ") {+ let (t, r, b, l) = (dir.contains("top"), dir.contains("right"), dir.contains("bottom"), dir.contains("left"));+ angle = match (t, r, b, l) { (true, false, false, false) => 0.0, (false, true, false, false) => 90.0, (false, false, true, false) => 180.0, (false, false, false, true) => 270.0, (true, true, _, _) => 45.0, (_, true, true, _) => 135.0, (_, _, true, true) => 225.0, _ => 315.0 };+ from = 1;+ } else if let Some((n, u)) = ["deg", "turn", "rad", "grad"].iter().find_map(|u| first.strip_suffix(u).map(|n| (n, *u))) {+ let x: f32 = n.trim().parse().ok()?;+ angle = match u { "turn" => x * 360.0, "rad" => x.to_degrees(), "grad" => x * 0.9, _ => x };+ from = 1;+ }+ let mut stops: Vec<(Option<f32>, u32)> = vec![];+ for a in &args[from..] {+ let toks = split_ws(a.trim());+ let Some(c) = toks.iter().find_map(|t| parse_color(t)) else { continue };+ let pos = toks.iter().find_map(|t| t.strip_suffix('%').and_then(|n| n.parse::<f32>().ok())).map(|p| p / 100.0);+ stops.push((pos, c));+ }+ if stops.len() < 2 { return None; }+ let n = stops.len();+ let mut out: Vec<(f32, u32)> = stops.iter().enumerate().map(|(i, (pos, c))| (pos.unwrap_or(i as f32 / (n - 1) as f32), *c)).collect();+ for i in 1..n { if out[i].0 < out[i - 1].0 { out[i].0 = out[i - 1].0; } }+ Some(Grad { angle: angle.rem_euclid(360.0), stops: out, radial, circle, at })+}++fn css_url(v: &str) -> Option<String> {+ let rest = &v[v.find("url(")? + 4..];+ Some(rest[..rest.find(')')?].trim().trim_matches(['"', '\'']).to_string())+}++/// `background-position` tokens (keywords, lengths, percentages) as (x, y); a single value centers the other axis.+fn parse_bg_pos(toks: &[&str], em: f32) -> [Len; 2] {+ let kw = |t: &str| match t { "left" | "top" => Some(0.0), "center" => Some(50.0), "right" | "bottom" => Some(100.0), _ => None };+ let one = |t: &str| kw(t).map(Len::Pct).or_else(|| len_value(t, em));+ let (mut x, mut y) = (Len::Pct(0.0), Len::Pct(0.0));+ match toks {+ [a] => match *a {+ "top" | "bottom" => { x = Len::Pct(50.0); y = one(a).unwrap_or(y); }+ "center" => { x = Len::Pct(50.0); y = Len::Pct(50.0); }+ _ => { x = one(a).unwrap_or(x); y = Len::Pct(50.0); }+ },+ [a, b, ..] => {+ let (hx, hy) = if matches!(*a, "top" | "bottom") || matches!(*b, "left" | "right") { (*b, *a) } else { (*a, *b) };+ x = one(hx).unwrap_or(x);+ y = one(hy).unwrap_or(y);+ }+ _ => {}+ }+ [x, y]+}++fn parse_bg_size(toks: &[&str], em: f32) -> BgSize {+ match toks {+ ["cover"] => BgSize::Cover,+ ["contain"] => BgSize::Contain,+ [a] => BgSize::Fixed(len_value(a, em), None),+ [a, b, ..] => BgSize::Fixed(len_value(a, em), len_value(b, em)),+ _ => BgSize::Auto,+ }+}++fn parse_bg_repeat(toks: &[&str]) -> (bool, bool) {+ match toks {+ ["no-repeat"] => (false, false),+ ["repeat-x"] => (true, false),+ ["repeat-y"] => (false, true),+ [a, b] => (*a != "no-repeat", *b != "no-repeat"),+ _ => (true, true),+ }+}++/// Image layer state while a rule's background properties are applied in order.+#[derive(Clone)]+struct BgParts { url: Option<String>, size: BgSize, pos: [Len; 2], repeat: (bool, bool) }++impl BgParts {+ fn new() -> BgParts { BgParts { url: None, size: BgSize::Auto, pos: [Len::Pct(0.0); 2], repeat: (true, true) } }++ /// The first layer of a `background` shorthand: `url(..) 50% 0 / cover no-repeat #fff`.+ fn shorthand(v: &str, em: f32) -> BgParts {+ let mut b = BgParts::new();+ let (mut layer, mut depth) = (String::new(), 0);+ for c in split_top(v, ',').into_iter().next().unwrap_or("").chars() { // a `/` outside parentheses separates position from size+ match c { '(' => { depth += 1; layer.push(c); } ')' => { depth -= 1; layer.push(c); } '/' if depth == 0 => layer.push_str(" / "), _ => layer.push(c) }+ }+ b.url = css_url(&layer);+ let (mut pos, mut size, mut rep, mut after_slash) = (vec![], vec![], vec![], false);+ for t in split_ws(&layer) {+ if t == "/" { after_slash = true; continue; }+ if t.starts_with("url(") || t.contains("gradient(") { continue; }+ if matches!(t, "no-repeat" | "repeat" | "repeat-x" | "repeat-y" | "space" | "round") { rep.push(t); }+ else if after_slash && size.len() < 2 && (matches!(t, "cover" | "contain" | "auto") || len_value(t, em).is_some()) { size.push(t); }+ else if matches!(t, "left" | "right" | "top" | "bottom" | "center") || (parse_color(t).is_none() && len_value(t, em).is_some()) { if !after_slash { pos.push(t); } }+ }+ if !pos.is_empty() { b.pos = parse_bg_pos(&pos, em); }+ if !size.is_empty() { b.size = parse_bg_size(&size, em); }+ if !rep.is_empty() { b.repeat = parse_bg_repeat(&rep); }+ b+ }+}++/// `0 2px 4px 1px rgba(0,0,0,.2)` (first of a comma list); inset shadows are skipped.+fn parse_shadow(v: &str, em: f32) -> Option<Shadow> {+ let first = split_top(v, ',').into_iter().next()?.trim().to_string();+ if first.contains("inset") || first == "none" { return None; }+ let toks = split_ws(&first);+ let nums: Vec<f32> = toks.iter().filter_map(|t| length(t, em)).collect();+ if nums.len() < 2 { return None; }+ let (color, a) = toks.iter().find_map(|t| parse_color_a(t)).unwrap_or((u32::MAX, 0.35));+ Some(Shadow { dx: nums[0], dy: nums[1], blur: nums.get(2).copied().unwrap_or(0.0).clamp(0.0, 60.0), spread: nums.get(3).copied().unwrap_or(0.0).clamp(-30.0, 60.0), color, a })+}++/// `grid-template-columns`: tracks plus the minimum width of a `repeat(auto-fill, minmax(N, 1fr))` pattern.+fn parse_tracks(v: &str, em: f32) -> (Vec<Track>, Option<f32>) {+ let (mut out, mut auto) = (vec![], None);+ for t in split_ws(v) {+ if let Some(inner) = t.strip_prefix("repeat(").and_then(|r| r.strip_suffix(')')) {+ let (n, body) = inner.split_once(',').unwrap_or((inner, ""));+ let (n, body) = (n.trim(), body.trim());+ let (sub, _) = parse_tracks(body, em);+ if n == "auto-fill" || n == "auto-fit" {+ let min = body.strip_prefix("minmax(").and_then(|m| m.split(',').next()).and_then(|m| length(m, em)).or_else(|| length(body, em));+ auto = min.filter(|m| *m > 0.0);+ if auto.is_none() { out.extend(sub); }+ } else if let Ok(k) = n.parse::<usize>() { for _ in 0..k.min(24) { out.extend(sub.iter().copied()); } }+ } else if let Some(n) = t.strip_suffix("fr") { out.push(Track::Fr(n.parse().unwrap_or(1.0))); }+ else if let Some(m) = t.strip_prefix("minmax(").and_then(|m| m.strip_suffix(')')) {+ let hi = m.split(',').nth(1).unwrap_or("").trim();+ out.push(if let Some(n) = hi.strip_suffix("fr") { Track::Fr(n.parse().unwrap_or(1.0)) } else { length(hi, em).map_or(Track::Fr(1.0), Track::Px) });+ }+ else if let Some(p) = t.strip_suffix('%') { out.push(Track::Pct(p.parse().unwrap_or(0.0))); }+ else if let Some(px) = length(t, em) { out.push(Track::Px(px)); }+ else if matches!(t, "auto" | "min-content" | "max-content") || t.starts_with("fit-content") { out.push(Track::Fr(1.0)); }+ }+ (out, auto)+}++fn parse_counters(v: &str, default: i32) -> Vec<(String, i32)> {+ let mut out: Vec<(String, i32)> = vec![];+ for t in split_ws(v) {+ if let Ok(n) = t.parse::<i32>() { if let Some(l) = out.last_mut() { l.1 = n; } }+ else if t != "none" { out.push((t.to_string(), default)); }+ }+ out+}++fn font_size(v: &str, parent: f32) -> Option<f32> {+ Some(match v.trim() {+ "xx-small" => 9.0, "x-small" => 10.0, "small" => 13.0, "medium" => 16.0, "large" => 18.0, "x-large" => 24.0, "xx-large" => 32.0,+ "smaller" => parent * 0.83, "larger" => parent * 1.2,+ x => length(x, parent)?,+ })+}++pub fn compute(dom: &Dom, sheet: &Sheet, id: usize, parent: &Style) -> Style { cascade(dom, id, parent, sheet.matching(dom, id, 0), true, sheet) }++/// Style and text of the `::before` (1) / `::after` (2) pseudo-element of `id`; None without text `content`.+pub fn pseudo(dom: &Dom, sheet: &Sheet, id: usize, which: u8, parent: &Style) -> Option<(Style, String)> {+ if !sheet.has_pseudo { return None; }+ let mut rules = sheet.matching(dom, id, which);+ rules.sort_by_key(|r| (r.spec, r.order));+ let text = rules.iter().flat_map(|r| r.decls.iter()).filter(|d| d.prop == "content").next_back().and_then(|d| content_text(&d.val, dom, id))?;+ (!text.is_empty()).then(|| (cascade(dom, id, parent, rules, false, sheet), text))+}++/// `content` value: concatenated strings and `attr(x)` resolved; `counter(name)` / `counters(name, sep)` become+/// `\u{1}name\u{2}sep\u{3}` markers that the renderer (which owns the counters) replaces.+fn content_text(v: &str, dom: &Dom, id: usize) -> Option<String> {+ let mut out = String::new();+ let mut any = false;+ for tok in content_tokens(v) {+ let t = tok.trim();+ if let Some(inner) = t.strip_prefix("attr(").and_then(|r| r.strip_suffix(')')) { out.push_str(dom.attr(id, inner.trim()).unwrap_or("")); any = true; }+ else if let Some(inner) = t.strip_prefix("counter(").and_then(|r| r.strip_suffix(')')) { out.push_str(&format!("\u{1}{}\u{2}\u{3}", inner.split(',').next().unwrap_or("").trim())); any = true; }+ else if let Some(inner) = t.strip_prefix("counters(").and_then(|r| r.strip_suffix(')')) {+ let mut it = inner.splitn(2, ',');+ let name = it.next().unwrap_or("").trim();+ let sep = it.next().map_or(String::new(), |s| content_string(s.trim()).unwrap_or_default());+ out.push_str(&format!("\u{1}{name}\u{2}{sep}\u{3}")); any = true;+ }+ else if let Some(sv) = content_string(t) { out.push_str(&sv); any = true; }+ }+ // a string with spaces is split by split_ws above only outside quotes; whole quoted strings keep their spaces+ any.then_some(out)+}++/// Whitespace split that keeps quoted strings and `func(...)` calls whole.+fn content_tokens(v: &str) -> Vec<&str> {+ let (mut out, mut depth, mut quote, mut start) = (vec![], 0i32, None::<char>, None::<usize>);+ for (i, c) in v.char_indices() {+ match (quote, c) {+ (Some(q), c) if c == q => quote = None,+ (Some(_), _) => {}+ (None, '"' | '\'') => { quote = Some(c); start.get_or_insert(i); }+ (None, '(') => { depth += 1; start.get_or_insert(i); }+ (None, ')') => depth -= 1,+ (None, c) if c.is_whitespace() && depth <= 0 => { if let Some(st) = start.take() { out.push(&v[st..i]); } }+ _ => { start.get_or_insert(i); }+ }+ }+ if let Some(st) = start { out.push(&v[st..]); }+ out+}++fn content_string(v: &str) -> Option<String> {+ let v = v.trim();+ let q = v.chars().next().filter(|c| *c == '"' || *c == '\'')?;+ let inner = &v[1..];+ let end = inner.rfind(q)?;+ let (mut out, mut it) = (String::new(), inner[..end].chars().peekable());+ while let Some(c) = it.next() {+ if c != '\\' { out.push(c); continue; }+ let mut hex = String::new();+ while hex.len() < 6 && it.peek().is_some_and(|d| d.is_ascii_hexdigit()) { hex.extend(it.next()); }+ if hex.is_empty() { out.extend(it.next()); } else {+ if it.peek() == Some(&' ') { it.next(); }+ out.extend(u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32));+ }+ }+ Some(out)+}++fn cascade(dom: &Dom, id: usize, parent: &Style, rules: Vec<&Rule>, element: bool, sheet: &Sheet) -> Style {+ let mut s = parent.inherit();+ // Presentational attributes (lowest precedence, CSS overrides below).+ if element {+ if let Some(c) = dom.attr(id, "bgcolor").and_then(parse_color) { s.bg = Some(c); }+ if dom.nodes[id].tag == "font" { if let Some(c) = dom.attr(id, "color").and_then(parse_color) { s.color = c; } }+ if matches!(dom.nodes[id].tag.as_str(), "td" | "th" | "tr" | "p" | "div" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "caption") {+ match dom.attr(id, "align").map(str::to_ascii_lowercase).as_deref() { Some("center") => s.align = 1, Some("right") => s.align = 2, Some("left") => s.align = 0, _ => {} }+ }+ }+ let mut matched: Vec<(bool, u32, usize, &Decl)> = rules.into_iter().flat_map(|r| r.decls.iter().map(move |d| (d.imp, r.spec, r.order, d))).collect();+ let inline = if element { dom.attr(id, "style").map(parse_decls).unwrap_or_default() } else { vec![] };+ matched.extend(inline.iter().map(|d| (d.imp, u32::MAX, usize::MAX, d)));+ matched.sort_by_key(|&(imp, spec, ord, _)| (imp, spec, ord));+ // custom properties first (they inherit), then every value with var() substituted+ for (_, _, _, d) in matched.iter().filter(|m| m.3.prop.starts_with("--")) {+ if let Some(v) = if d.val.contains("var(") { subst_vars(&d.val, &s.vars, 0) } else { Some(d.val.clone()) } { Rc::make_mut(&mut s.vars).insert(d.prop.clone(), v); }+ }+ let vals: Vec<Option<Cow<str>>> = matched.iter().map(|m| if m.3.val.contains("var(") { subst_vars(&m.3.val, &s.vars, 0).map(Cow::Owned) } else { Some(Cow::Borrowed(m.3.val.as_str())) }).collect();+ for (k, (_, _, _, d)) in matched.iter().enumerate() {+ let Some(val) = vals[k].as_deref() else { continue };+ if d.prop == "font-size" {+ if let Some(px) = font_size(val, parent.size) { s.size = px.clamp(0.0, 100.0); if px < 1.0 { s.none = true; } }+ }+ }+ let (mut disp, mut col) = (None::<&str>, false);+ let (mut m, mut p, mut auto, mut pad_set, mut overflow_hidden) = ([0f32; 4], [0f32; 4], [false; 4], false, false);+ let mut opacity = None::<f32>;+ let mut bgp = BgParts::new();+ let em = s.size;+ for (k, (_, _, _, d)) in matched.iter().enumerate() {+ let Some(v) = vals[k].as_deref() else { continue };+ match d.prop.as_str() {+ "height" | "min-height" => match len_value(v, em) {+ Some(Len::Px(p)) => { s.x.min_h = s.x.min_h.max(p.clamp(0.0, 20000.0)); if d.prop == "height" { s.x.fix_h = true; } }+ Some(Len::Pct(p)) => s.x.h_pct = Some((p, d.prop == "height")),+ _ => {}+ },+ "border-radius" => s.x.radius = match v.split_whitespace().next() { Some(t) if t.ends_with('%') => if t.trim_end_matches('%').parse::<f32>().is_ok_and(|p| p >= 50.0) { 9999.0 } else { 0.0 }, Some(t) => length(t, em).unwrap_or(0.0).clamp(0.0, 9999.0), None => 0.0 },+ "box-sizing" => s.x.bb = v == "border-box",+ "text-transform" => s.tt = match v { "uppercase" => 1, "lowercase" => 2, "capitalize" => 3, _ => 0 },+ "display" => disp = Some(v),+ "flex-direction" => col = v.starts_with("column"),+ "color" => if let Some(c) = parse_color(v) { s.color = c },+ "font-weight" => s.bold = matches!(v, "bold" | "bolder") || v.parse::<u32>().is_ok_and(|n| n >= 600),+ "text-align" => s.align = match v { "center" => 1, "right" | "end" => 2, _ => 0 },+ "text-decoration" | "text-decoration-line" => s.underline = v.contains("underline"),+ "list-style" | "list-style-type" => s.bullets = !v.starts_with("none"),+ "visibility" => if v == "hidden" || v == "collapse" { s.none = true },+ "opacity" => opacity = v.strip_suffix('%').map_or_else(|| v.parse::<f32>().ok(), |p| p.parse::<f32>().ok().map(|n| n / 100.0)).map(|o| o.clamp(0.0, 1.0)),+ "background" | "background-color" => {+ if let Some((c, a)) = background_color(v) { (s.bg, s.bg_a) = (Some(c), a); }+ if d.prop == "background" || v.contains("gradient(") { s.bg_grad = parse_gradient(v).map(Arc::new); }+ if d.prop == "background" { bgp = BgParts::shorthand(v, em); }+ }+ "background-image" => if v.contains("gradient(") {+ if s.bg.is_none() { if let Some((c, _)) = background_color(v) { (s.bg, s.bg_a) = (Some(c), 1.0); } }+ s.bg_grad = parse_gradient(v).map(Arc::new);+ bgp.url = None;+ } else { bgp.url = css_url(v); if bgp.url.is_some() { s.bg_grad = None; } },+ "background-size" => bgp.size = parse_bg_size(&split_ws(v), em),+ "background-position" => bgp.pos = parse_bg_pos(&split_ws(v), em),+ "background-repeat" => bgp.repeat = parse_bg_repeat(&split_ws(v)),+ "margin" => if let Some((vals, a)) = sides(v, em) { (m, auto) = (vals, a) },+ "margin-top" => { m[0] = length(v, em).unwrap_or(0.0); auto[0] = v == "auto"; }+ "margin-right" => { m[1] = length(v, em).unwrap_or(0.0); auto[1] = v == "auto"; }+ "margin-bottom" => { m[2] = length(v, em).unwrap_or(0.0); auto[2] = v == "auto"; }+ "margin-left" => { m[3] = length(v, em).unwrap_or(0.0); auto[3] = v == "auto"; }+ "padding" => if let Some((vals, _)) = sides(v, em) { p = vals; pad_set = true; },+ "padding-top" => { p[0] = length(v, em).unwrap_or(0.0); pad_set = true; }+ "padding-right" => { p[1] = length(v, em).unwrap_or(0.0); pad_set = true; }+ "padding-bottom" => { p[2] = length(v, em).unwrap_or(0.0); pad_set = true; }+ "padding-left" => { p[3] = length(v, em).unwrap_or(0.0); pad_set = true; }+ "width" => s.width = len_value(v, em),+ "max-width" => s.max_width = len_value(v, em),+ "vertical-align" => {+ s.valign = match v { "middle" => 1, "bottom" => 2, _ => 0 };+ s.x.va_kind = match v { "middle" => 1, "top" | "text-top" => 2, "bottom" | "text-bottom" => 3, _ => 0 };+ s.x.va = match v { "super" => 0.33, "sub" => -0.2, "text-top" | "top" => 0.15, "text-bottom" | "bottom" => -0.15, x => length(x, em).map_or(0.0, |p| p / em.max(1.0)).clamp(-2.0, 2.0) };+ }+ "z-index" => s.x.z = v.parse::<i32>().unwrap_or(0).clamp(-1000, 100000),+ "box-shadow" => s.x.shadow = parse_shadow(v, em),+ "letter-spacing" => s.ls = if v == "normal" { 0.0 } else { length(v, em).unwrap_or(0.0).clamp(-5.0, 50.0) },+ "grid-template-columns" => (s.x.tracks, s.x.auto_min) = parse_tracks(v, em),+ "grid-column" | "grid-column-start" | "grid-column-end" => if let Some(n) = v.split("span").nth(1).and_then(|n| n.split_whitespace().next()).and_then(|n| n.parse::<usize>().ok()) { s.x.span = n.clamp(1, 24); },+ "row-gap" | "grid-row-gap" => s.x.row_gap = length(v, em).map(|g| g.clamp(0.0, 200.0)),+ "counter-reset" | "counter-set" => s.x.counter_reset = parse_counters(v, 0),+ "counter-increment" => s.x.counter_inc = parse_counters(v, 1),+ "border-collapse" => s.collapse = v == "collapse",+ // shortcut: sticky acts as relative (right while the page is not scrolled); fixed boxes stay in the viewport at paint time+ "position" => { s.x.sticky = v == "sticky"; match v { "fixed" => s.x.pos = 3, "absolute" => s.x.pos = 2, "relative" | "sticky" => s.x.pos = 1, _ => s.x.pos = 0 } }+ "top" => s.x.off[0] = len_value(v, em),+ "right" => s.x.off[1] = len_value(v, em),+ "bottom" => s.x.off[2] = len_value(v, em),+ "left" => s.x.off[3] = len_value(v, em),+ "inset" => if let Some((vals, _)) = sides(v, em) { s.x.off = vals.map(|p| Some(Len::Px(p))) },+ "line-height" => s.lh = match v { "normal" => 1.35, x => x.parse::<f32>().ok().or_else(|| len_value(x, em).map(|l| match l { Len::Px(p) => p / em.max(1.0), Len::Pct(p) => p / 100.0, Len::Mix(..) => 1.35 })).unwrap_or(1.35).clamp(0.8, 4.0) },+ "flex-wrap" => s.x.wrap = v.starts_with("wrap"),+ "flex-flow" => { col = v.starts_with("column"); s.x.wrap = v.contains("wrap") && !v.contains("nowrap"); }+ "gap" | "column-gap" | "grid-gap" => {+ let t = split_ws(v);+ s.x.gap = length(t.last().copied().unwrap_or(""), em).unwrap_or(0.0).clamp(0.0, 200.0);+ if d.prop != "column-gap" { s.x.row_gap = t.first().and_then(|r| length(r, em)).map(|g| g.clamp(0.0, 200.0)); }+ }+ "justify-content" => s.x.justify = match v { "center" => 1, "flex-end" | "end" | "right" => 2, "space-between" => 3, "space-around" => 4, "space-evenly" => 5, _ => 0 },+ "align-items" | "align-self" => s.x.align = match v { "flex-start" | "start" | "baseline" => 1, "center" => 2, "flex-end" | "end" => 3, _ => 0 },+ "flex-grow" => s.x.grow = v.parse().unwrap_or(0.0),+ "flex-shrink" => s.x.shrink = v.parse().unwrap_or(1.0),+ "flex-basis" => s.x.basis = if v == "auto" { None } else { len_value(v, em) },+ "flex" => {+ let t: Vec<&str> = v.split_whitespace().collect();+ (s.x.grow, s.x.shrink, s.x.basis) = match t.as_slice() {+ ["none"] => (0.0, 0.0, None),+ ["auto"] => (1.0, 1.0, None),+ [g] if g.parse::<f32>().is_ok() => (g.parse().unwrap_or(0.0), 1.0, Some(Len::Px(0.0))),+ [g, sh] if sh.parse::<f32>().is_ok() => (g.parse().unwrap_or(0.0), sh.parse().unwrap_or(1.0), Some(Len::Px(0.0))),+ [g, sh, b] => (g.parse().unwrap_or(0.0), sh.parse().unwrap_or(1.0), len_value(b, em)),+ [g, b] => (g.parse().unwrap_or(0.0), 1.0, len_value(b, em)),+ _ => (0.0, 1.0, None),+ };+ }+ // "visually hidden" utility hack (skip links, sr-only): clipped away or a 1px box with overflow hidden+ "clip" => if v.replace(' ', "").starts_with("rect(0") { s.none = true },+ "overflow" | "overflow-y" => {+ if d.prop == "overflow" { overflow_hidden = v == "hidden"; }+ let y = v.split_whitespace().last().unwrap_or(v); // `overflow: hidden auto` scrolls vertically+ s.x.clip = y != "visible";+ s.x.scroll = matches!(y, "auto" | "scroll");+ }+ "float" => s.float = match v { "left" => 1, "right" => 2, _ => 0 },+ "clear" => s.clear = match v { "left" => 1, "right" => 2, "both" => 3, _ => 0 },+ "border" => s.borders = [border_value(v, em); 4],+ "border-top" => s.borders[0] = border_value(v, em),+ "border-right" => s.borders[1] = border_value(v, em),+ "border-bottom" => s.borders[2] = border_value(v, em),+ "border-left" => s.borders[3] = border_value(v, em),+ "font-family" => {+ let l = v.to_ascii_lowercase();+ s.mono = ["monospace", "consolas", "courier", "menlo", "mono"].iter().any(|k| l.contains(k));+ // the first listed family that the page defines with @font-face+ s.fam = split_top(&l, ',').into_iter().map(|n| n.trim().trim_matches(['"', '\'']).trim()).find(|n| sheet.has_face(n)).map_or(0, crate::gfx::family_id);+ }+ "font-style" => s.italic = v.starts_with("italic") || v.starts_with("oblique"),+ "white-space" => { s.pre = matches!(v, "pre" | "pre-wrap" | "break-spaces"); s.nowrap = v == "nowrap"; }+ // large negative indents are the image-replacement trick for hiding text+ "text-indent" => if let Some(Len::Px(p)) = len_value(v, em) { if p <= -500.0 { s.none = true } else { s.x.indent = p.clamp(-200.0, 400.0) } },+ _ => {}+ }+ }+ match disp {+ Some("none") => s.none = true,+ Some(d) => {+ s.block = !matches!(d, "inline" | "inline-block" | "inline-flex" | "inline-grid" | "inline-table" | "contents" | "table-cell");+ s.list_item = d == "list-item";+ s.flex_row = matches!(d, "flex" | "inline-flex") && !col;+ s.x.flex_col = matches!(d, "flex" | "inline-flex") && col;+ s.x.grid = matches!(d, "grid" | "inline-grid");+ s.x.inline_block = matches!(d, "inline-block" | "inline-table");+ }+ None => {}+ }+ s.bg_img = bgp.url.map(|url| BgImage { url, size: bgp.size, pos: bgp.pos, repeat: bgp.repeat });+ if let Some(o) = opacity { s.alpha = parent.alpha * o; if o == 0.0 { s.none = true; } }+ if let Some(sh) = s.x.shadow.as_mut() { if sh.color == u32::MAX { sh.color = s.color; } }+ s.mt = (m[0] + p[0]).clamp(0.0, 100.0);+ s.mb = (m[2] + p[2]).clamp(0.0, 100.0);+ (s.pt, s.pb) = (p[0].clamp(0.0, 100.0).min(s.mt), p[2].clamp(0.0, 100.0).min(s.mb));+ s.ml = m[3].clamp(0.0, 400.0);+ s.mr = m[1].clamp(0.0, 400.0);+ s.pl = p[3].clamp(0.0, 400.0);+ s.pr = p[1].clamp(0.0, 400.0);+ (s.auto_l, s.auto_r) = (auto[3], auto[1]);+ if overflow_hidden && matches!(s.width, Some(Len::Px(w)) if w <= 1.0) { s.none = true; }+ for b in s.borders.iter_mut().flatten() { if b.1 == u32::MAX { b.1 = s.color; } }+ (s.pad, s.pad_set) = (p.map(|v| v.clamp(0.0, 100.0)), pad_set);+ s+}++/// Built-in browser defaults, lowest precedence.+pub const UA: &str = "+head,script,style,title,meta,link,template,noscript,option,datalist,object,iframe,canvas,audio,video,[hidden]{display:none}+html,body,div,p,h1,h2,h3,h4,h5,h6,ul,ol,dl,dt,dd,table,tr,section,article,header,footer,nav,main,aside,form,hr,blockquote,figure,figcaption,details,summary,address,pre,fieldset,legend,center,tbody,thead,tfoot,caption{display:block}+li{display:list-item}+td,th{display:inline}+table{text-align:left}+a{color:#0000cc;text-decoration:underline}+h1{font-size:2em;margin:.67em 0;font-weight:bold}+h2{font-size:1.5em;margin:.83em 0;font-weight:bold}+h3{font-size:1.17em;margin:1em 0;font-weight:bold}+h4{font-size:1em;margin:1.33em 0;font-weight:bold}+h5{font-size:.83em;margin:1.67em 0;font-weight:bold}+h6{font-size:.67em;margin:2.33em 0;font-weight:bold}+p,dl,pre,blockquote,figure,fieldset{margin:1em 0}+ul,ol{margin:1em 0;padding-left:40px}+ul ul,ol ol,ul ol,ol ul{margin:0}+blockquote,dd{margin-left:40px}+b,strong,th,dt,summary{font-weight:bold}+i,em,cite,var,dfn,address{font-style:italic}+th,center,caption{text-align:center}+small,sub,sup{font-size:.83em}+sup{vertical-align:super}+sub{vertical-align:sub}+u,ins{text-decoration:underline}+pre,code,kbd,samp,tt{font-family:monospace}+pre{white-space:pre}+hr{border-top:1px solid #999}+";++#[cfg(test)]+mod tests {+ use super::*;+ use crate::dom::parse;++ fn style_of(html: &str, css: &str, tag: &str) -> Style {+ let dom = parse(html, true);+ let sheet = Sheet::new(&[UA.into(), css.into()]);+ let id = dom.find(tag).unwrap();+ // walk ancestors so inheritance applies+ let mut chain = vec![];+ let mut p = id;+ while p != 0 { chain.push(p); p = dom.nodes[p].parent; }+ chain.iter().rev().fold(Style::root(), |ps, &i| compute(&dom, &sheet, i, &ps))+ }++ #[test]+ fn cascade_specificity_and_inheritance() {+ let s = style_of("<div id=a class=b><p>x</p></div>", "div{color:red} .b{color:#00ff00} #a{color:blue} p{font-weight:700}", "p");+ assert_eq!(s.color, 0x0000FF);+ assert!(s.bold && s.block);+ }++ #[test]+ fn important_and_inline_and_none() {+ let s = style_of("<p style='color:red'>x</p>", "p{color:blue!important}", "p");+ assert_eq!(s.color, 0x0000FF);+ assert!(style_of("<p hidden>x</p>", "", "p").none);+ assert!(style_of("<p style='display:none'>x</p>", "", "p").none);+ let s = style_of("<p style='position:fixed;top:0'>x</p>", "", "p");+ assert!(!s.none && s.x.pos == 3, "fixed boxes are kept and flagged");+ assert!(!style_of("<p style='position:absolute'>x</p>", "", "p").none);+ assert!(style_of("<a style='position:absolute;width:1px;height:1px;overflow:hidden'>x</a>", "", "a").none);+ assert!(style_of("<a style='clip: rect(0, 0, 0, 0)'>x</a>", "", "a").none);+ }++ #[test]+ fn combinators_and_attrs() {+ let css = "ul > li{color:red} div p{color:blue} a[href^=http]{color:green} li:first-child{font-weight:bold} :not(pre) > code{color:#123456} pre code{color:#654321}";+ assert_eq!(style_of("<p><code>x</code></p>", css, "code").color, 0x123456);+ assert_eq!(style_of("<pre><code>x</code></pre>", css, "code").color, 0x654321);+ assert_eq!(style_of("<ul><li>x</li></ul>", css, "li").color, 0xFF0000);+ assert!(style_of("<ul><li>x</li></ul>", css, "li").bold);+ assert_eq!(style_of("<div><section><p>x</p></section></div>", css, "p").color, 0x0000FF);+ assert_eq!(style_of("<a href='http://x'>x</a>", css, "a").color, 0x008000);+ }++ #[test]+ fn units_media_and_margins() {+ let s = style_of("<p>x</p>", "p{font-size:20px;margin:0 auto 1em 2em}", "p");+ assert_eq!((s.size, s.mt, s.mb, s.ml), (20.0, 0.0, 20.0, 40.0));+ let s = style_of("<div>x</div>", "div{margin:0 auto;max-width:600px;width:50%;padding:4px 8px}", "div");+ assert_eq!((s.auto_l, s.auto_r, s.max_width, s.width, s.pl, s.pr, s.mt), (true, true, Some(Len::Px(600.0)), Some(Len::Pct(50.0)), 8.0, 8.0, 4.0));+ let s = style_of("<p>x</p>", "@media (max-width:600px){p{color:red}} @media print{p{color:red}} @media (min-width:600px){p{color:#010203}}", "p");+ assert_eq!(s.color, 0x010203);+ assert_eq!(parse_color("rgb(1, 2, 3)"), Some(0x010203));+ assert_eq!(parse_color("#abc"), Some(0xAABBCC));+ }++ fn style_at(html: &str, css: &str, tag: &str, n: usize) -> Style {+ let dom = parse(html, true);+ let sheet = Sheet::new(&[UA.into(), css.into()]);+ let id = dom.descendants().into_iter().filter(|&i| dom.nodes[i].tag == tag).nth(n).unwrap();+ let mut chain = vec![];+ let mut p = id;+ while p != 0 { chain.push(p); p = dom.nodes[p].parent; }+ chain.iter().rev().fold(Style::root(), |ps, &i| compute(&dom, &sheet, i, &ps))+ }++ #[test]+ fn custom_properties_and_calc() {+ let css = ":root{--c:#ff0000;--w:200px} p{color:var(--c);width:calc(100% - var(--w)/2);margin-left:var(--m,10px)}";+ let s = style_of("<p>x</p>", css, "p");+ assert_eq!((s.color, s.width, s.ml), (0xFF0000, Some(Len::Mix(100.0, -100.0)), 10.0));+ assert_eq!(style_of("<p>x</p>", "p{width:min(300px,50vw)}", "p").width, Some(Len::Px(300.0)));+ assert_eq!(style_of("<p>x</p>", "p{width:clamp(10px,2em,18px)}", "p").width, Some(Len::Px(18.0)));+ assert_eq!(style_of("<p>x</p>", "p{color:var(--nope)}", "p").color, 0x111111); // undefined without fallback: ignored+ assert_eq!(style_of("<div style='--k:#00ff00'><p>x</p></div>", "p{color:var(--k)}", "p").color, 0x00FF00); // inherited+ }++ #[test]+ fn gradients_fall_back_to_the_first_stop() {+ assert_eq!(style_of("<p>x</p>", "p{background:linear-gradient(to right, #ff0000 0%, #0000ff 100%)}", "p").bg, Some(0xFF0000));+ assert_eq!(style_of("<p>x</p>", "p{background-image:radial-gradient(circle, rgb(1, 2, 3), white)}", "p").bg, Some(0x010203));+ assert_eq!(style_of("<p>x</p>", "p{background:url(a.png)}", "p").bg, None);+ }++ #[test]+ fn alpha_opacity_gradients_shadows_and_grid_values() {+ let s = style_of("<p>x</p>", "p{background:rgba(0,0,0,.5);opacity:.5;z-index:3;letter-spacing:2px;vertical-align:super}", "p");+ assert_eq!((s.bg, s.bg_a, s.alpha, s.x.z, s.ls), (Some(0), 0.5, 0.5, 3, 2.0));+ assert!(s.x.va > 0.2);+ assert_eq!(style_of("<p>x</p>", "p{background:#ff000080}", "p").bg_a, 128.0 / 255.0);+ let g = style_of("<p>x</p>", "p{background:linear-gradient(to right, #ff0000, #0000ff 50%, #00ff00)}", "p").bg_grad.unwrap();+ assert_eq!((g.angle, g.stops.len(), g.stops[1].0), (90.0, 3, 0.5));+ let g = style_of("<p>x</p>", "p{background-image:linear-gradient(45deg, red 0%, blue 100%)}", "p").bg_grad.unwrap();+ assert_eq!(g.angle, 45.0);+ let sh = style_of("<p>x</p>", "p{color:#112233;box-shadow:2px 4px 8px 1px rgba(0,0,0,.25), 0 0 1px red}", "p").x.shadow.unwrap();+ assert_eq!((sh.dx, sh.dy, sh.blur, sh.spread, sh.a), (2.0, 4.0, 8.0, 1.0, 0.25));+ assert_eq!(style_of("<p>x</p>", "p{color:#112233;box-shadow:0 1px 2px}", "p").x.shadow.unwrap().color, 0x112233);+ let x = style_of("<div>x</div>", "div{display:grid;grid-template-columns:100px 1fr repeat(2, 20%);gap:5px 9px}", "div").x;+ assert!(x.grid);+ assert_eq!(x.tracks, vec![Track::Px(100.0), Track::Fr(1.0), Track::Pct(20.0), Track::Pct(20.0)]);+ assert_eq!((x.gap, x.row_gap), (9.0, Some(5.0)));+ let x = style_of("<div>x</div>", "div{display:grid;grid-template-columns:repeat(auto-fill, minmax(120px, 1fr))}", "div").x;+ assert_eq!(x.auto_min, Some(120.0));+ assert!(style_of("<div>x</div>", "div{display:flex;flex-direction:column}", "div").x.flex_col);+ assert_eq!(style_of("<p>x</p>", "p{counter-reset:a 2 b;counter-increment:a}", "p").x.counter_reset, vec![("a".to_string(), 2), ("b".to_string(), 0)]);+ }++ #[test]+ fn radial_gradients_background_layers_and_percent_heights_parse() {+ let g = style_of("<p>x</p>", "p{background:radial-gradient(circle at 20% 80%, #ff0000, #0000ff)}", "p").bg_grad.unwrap();+ assert!(g.radial && g.circle && g.at == (0.2, 0.8) && g.stops.len() == 2);+ let g = style_of("<p>x</p>", "p{background:radial-gradient(#fff, #000)}", "p").bg_grad.unwrap();+ assert!(g.radial && !g.circle && g.at == (0.5, 0.5));+ let b = style_of("<p>x</p>", "p{background:#eee url(a.png) no-repeat right 10px / cover}", "p");+ let i = b.bg_img.unwrap();+ assert_eq!((i.url.as_str(), i.size, i.repeat, i.pos), ("a.png", BgSize::Cover, (false, false), [Len::Pct(100.0), Len::Px(10.0)]));+ assert_eq!(b.bg, Some(0xEEEEEE));+ let i = style_of("<p>x</p>", "p{background-image:url(\"b.png\");background-size:20px auto;background-position:center;background-repeat:repeat-x}", "p").bg_img.unwrap();+ assert_eq!((i.url.as_str(), i.size, i.repeat, i.pos), ("b.png", BgSize::Fixed(Some(Len::Px(20.0)), None), (true, false), [Len::Pct(50.0), Len::Pct(50.0)]));+ assert!(style_of("<p>x</p>", "p{background:url(a.png);background:#fff}", "p").bg_img.is_none(), "a later shorthand resets the image");+ assert_eq!(style_of("<p>x</p>", "p{height:50%}", "p").x.h_pct, Some((50.0, true)));+ assert_eq!(style_of("<p>x</p>", "p{min-height:25%}", "p").x.h_pct, Some((25.0, false)));+ let x = style_of("<p>x</p>", "p{position:sticky;top:5px;vertical-align:middle}", "p").x;+ assert!(x.sticky && x.pos == 1 && x.va_kind == 1);+ assert!(has_state_rules("a:hover{color:red}") && !has_state_rules("a{color:red}"));+ }++ fn has_state_rules(css: &str) -> bool { Sheet::new(&[css.into()]).has_state }++ #[test]+ fn structural_selectors() {+ let css = "li:nth-child(2n+1){color:#010101} li:nth-child(2){color:#020202} li:last-of-type{font-weight:700} :is(h1,h2){color:#030303}";+ let html = "<ul><li>a</li><li>b</li><li>c</li></ul><h2>t</h2>";+ let c: Vec<u32> = (0..3).map(|n| style_at(html, css, "li", n).color).collect();+ assert_eq!(c, vec![0x010101, 0x020202, 0x010101]);+ assert!(!style_at(html, css, "li", 1).bold && style_at(html, css, "li", 2).bold);+ assert_eq!(style_at(html, css, "h2", 0).color, 0x030303);+ assert_eq!(style_at("<input checked>", "input:checked{color:red}", "input", 0).color, 0xFF0000);+ }+}diff --git a/plugins/chrome-rs/src/dom.rs b/plugins/chrome-rs/src/dom.rsnew file mode 100644index 0000000..a72430a--- /dev/null+++ b/plugins/chrome-rs/src/dom.rs@@ -0,0 +1,384 @@+// HTML -> DOM tree (arena). Forgiving, not spec-complete: simple implied end tags, depth cap, no foreign content rules.+use serde_json::{Map, Value};++/// Tag of a comment node (not a valid element name, so it cannot clash with a real tag).+pub const COMMENT: &str = "#comment";++#[derive(Default, Clone, Debug)]+pub struct Node {+ /// Empty tag = text node (content in `text`).+ pub tag: String,+ pub text: String,+ pub attrs: Vec<(String, String)>,+ pub kids: Vec<usize>,+ pub parent: usize,+}++#[derive(Clone, Debug)]+pub struct Dom { pub nodes: Vec<Node> }++const VOID: &[&str] = &["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr", "param"];+const MAX_DEPTH: usize = 120; // bounds recursion everywhere downstream (JSON, styling)++impl Dom {+ fn new() -> Dom { Dom { nodes: vec![Node { tag: "#root".into(), ..Default::default() }] } }++ pub fn add(&mut self, parent: usize, mut n: Node) -> usize {+ n.parent = parent;+ self.nodes.push(n);+ let id = self.nodes.len() - 1;+ self.nodes[parent].kids.push(id);+ id+ }++ pub fn attr(&self, id: usize, name: &str) -> Option<&str> {+ self.nodes[id].attrs.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str())+ }++ /// All node ids in document order.+ pub fn descendants(&self) -> Vec<usize> {+ let (mut out, mut st) = (vec![], vec![0usize]);+ while let Some(id) = st.pop() {+ out.push(id);+ st.extend(self.nodes[id].kids.iter().rev());+ }+ out+ }++ pub fn text_content(&self, id: usize) -> String {+ let n = &self.nodes[id];+ if n.tag.is_empty() { return n.text.clone(); }+ n.kids.iter().map(|&k| self.text_content(k)).collect()+ }++ pub fn find(&self, tag: &str) -> Option<usize> { self.descendants().into_iter().find(|&i| self.nodes[i].tag == tag) }++ fn detached(&mut self, tag: &str) -> usize {+ self.nodes.push(Node { tag: tag.into(), ..Default::default() });+ self.nodes.len() - 1+ }++ fn move_to(&mut self, kid: usize, parent: usize) {+ self.nodes[kid].parent = parent;+ self.nodes[parent].kids.push(kid);+ }++ /// Guarantee root > html > [head, body].+ fn normalize(&mut self) {+ let root_kids = std::mem::take(&mut self.nodes[0].kids);+ let html = root_kids.iter().copied().find(|&k| self.nodes[k].tag == "html").unwrap_or_else(|| self.detached("html"));+ self.nodes[html].parent = 0;+ self.nodes[0].kids = vec![html];+ for k in root_kids { if k != html { self.move_to(k, html); } }+ let kids = std::mem::take(&mut self.nodes[html].kids);+ let head = kids.iter().copied().find(|&k| self.nodes[k].tag == "head").unwrap_or_else(|| self.detached("head"));+ let body = kids.iter().copied().find(|&k| self.nodes[k].tag == "body").unwrap_or_else(|| self.detached("body"));+ self.nodes[html].kids = vec![head, body];+ self.nodes[head].parent = html;+ self.nodes[body].parent = html;+ for k in kids { if k != head && k != body { self.move_to(k, body); } }+ }++ /// Removes comment nodes from the tree the page is laid out from (they stay in the arena, so node numbers do not move) and joins the text around them.+ pub fn strip_comments(&mut self) {+ for id in 0..self.nodes.len() {+ if !self.nodes[id].kids.iter().any(|&k| self.nodes[k].tag == COMMENT) { continue; }+ let mut out: Vec<usize> = vec![];+ for k in std::mem::take(&mut self.nodes[id].kids) {+ if self.nodes[k].tag == COMMENT { continue; }+ match out.last() {+ Some(&l) if self.nodes[l].tag.is_empty() && self.nodes[k].tag.is_empty() => { let t = std::mem::take(&mut self.nodes[k].text); self.nodes[l].text.push_str(&t); }+ _ => out.push(k),+ }+ }+ self.nodes[id].kids = out;+ }+ }++ pub fn has_comments(&self) -> bool { self.nodes.iter().any(|n| n.tag == COMMENT) }++ pub fn to_json(&self, id: usize) -> Value {+ let n = &self.nodes[id];+ if n.tag.is_empty() { return Value::String(n.text.clone()); }+ if n.tag == COMMENT { return serde_json::json!({ "m": n.text }); }+ let a: Map<String, Value> = n.attrs.iter().map(|(k, v)| (k.clone(), Value::String(v.clone()))).collect();+ let mut m = Map::new();+ m.insert("t".into(), Value::String(n.tag.clone()));+ m.insert("a".into(), Value::Object(a));+ m.insert("c".into(), Value::Array(n.kids.iter().map(|&k| self.to_json(k)).collect()));+ Value::Object(m)+ }++ /// Build a DOM whose single child of the root is `v` (what `document.documentElement` serializes to).+ pub fn from_json(v: &Value) -> Option<Dom> {+ let mut dom = Dom::new();+ add_json(&mut dom, 0, v)?;+ Some(dom)+ }+}++fn add_json(dom: &mut Dom, parent: usize, v: &Value) -> Option<()> {+ match v {+ Value::String(s) => { dom.add(parent, Node { text: s.clone(), ..Default::default() }); }+ Value::Object(m) if m.contains_key("m") => { dom.add(parent, Node { tag: COMMENT.into(), text: m["m"].as_str().unwrap_or("").to_string(), ..Default::default() }); }+ Value::Object(m) => {+ let attrs = m.get("a")?.as_object()?.iter().map(|(k, v)| (k.clone(), v.as_str().unwrap_or("").to_string())).collect();+ let id = dom.add(parent, Node { tag: m.get("t")?.as_str()?.to_string(), attrs, ..Default::default() });+ for c in m.get("c")?.as_array()? { add_json(dom, id, c)?; }+ }+ _ => return None,+ }+ Some(())+}++/// JSON array of the nodes `html` parses to, for innerHTML.+pub fn fragment_json(html: &str) -> String {+ let dom = parse(html, false);+ Value::Array(dom.nodes[0].kids.iter().map(|&k| dom.to_json(k)).collect()).to_string()+}++fn tag_end(s: &str, from: usize) -> usize {+ let b = s.as_bytes();+ let (mut i, mut q, mut prev) = (from + 1, 0u8, 0u8);+ while i < b.len() {+ match (q, b[i]) {+ // a quote only opens a value right after `=`; a stray one (`data-id="x"">`) is part of an attribute name, as in browsers+ (0, b'"' | b'\'') if prev == b'=' => q = b[i],+ (0, b'>') => return i,+ (x, y) if x != 0 && x == y => q = 0,+ _ => {}+ }+ if !b[i].is_ascii_whitespace() { prev = b[i]; }+ i += 1;+ }+ b.len()+}++fn find_ci(hay: &str, needle: &str) -> Option<usize> {+ hay.as_bytes().windows(needle.len()).position(|w| w.eq_ignore_ascii_case(needle.as_bytes()))+}++fn parse_attrs(s: &str) -> Vec<(String, String)> {+ let (b, mut i, mut out): (&[u8], usize, Vec<(String, String)>) = (s.as_bytes(), 0, vec![]);+ loop {+ while i < b.len() && (b[i].is_ascii_whitespace() || b[i] == b'/') { i += 1; }+ if i >= b.len() { break; }+ let s0 = i;+ while i < b.len() && !b[i].is_ascii_whitespace() && b[i] != b'=' && b[i] != b'/' { i += 1; }+ let name = s[s0..i].to_ascii_lowercase();+ while i < b.len() && b[i].is_ascii_whitespace() { i += 1; }+ let mut val = String::new();+ if i < b.len() && b[i] == b'=' {+ i += 1;+ while i < b.len() && b[i].is_ascii_whitespace() { i += 1; }+ if i < b.len() && (b[i] == b'"' || b[i] == b'\'') {+ let q = b[i];+ i += 1;+ let v0 = i;+ while i < b.len() && b[i] != q { i += 1; }+ val = decode(&s[v0..i]);+ i = (i + 1).min(b.len());+ } else {+ let v0 = i;+ while i < b.len() && !b[i].is_ascii_whitespace() { i += 1; }+ val = decode(&s[v0..i]);+ }+ }+ if i == s0 { i += 1; }+ if !name.is_empty() && !out.iter().any(|(k, _)| *k == name) { out.push((name, val)); }+ }+ out+}++pub fn decode(s: &str) -> String {+ if !s.contains('&') { return s.into(); }+ let mut out = String::with_capacity(s.len());+ let mut rest = s;+ while let Some(p) = rest.find('&') {+ out.push_str(&rest[..p]);+ rest = &rest[p..];+ let ent = rest.find(';').filter(|&e| e <= 10).map(|e| &rest[1..e]);+ let ch = ent.and_then(|e| Some(match e {+ "amp" => '&', "lt" => '<', "gt" => '>', "quot" => '"', "apos" => '\'', "nbsp" => ' ', "mdash" => '—', "ndash" => '–',+ "hellip" => '…', "copy" => '©', "reg" => '®', "laquo" => '«', "raquo" => '»', "rsaquo" => '›', "lsaquo" => '‹',+ "middot" => '·', "bull" => '•', "times" => '×', "larr" => '←', "rarr" => '→', "euro" => '€',+ _ => {+ let n = e.strip_prefix('#')?;+ char::from_u32(match n.strip_prefix(['x', 'X']) { Some(h) => u32::from_str_radix(h, 16).ok()?, None => n.parse().ok()? })?+ }+ }));+ match (ch, ent) {+ (Some(c), Some(e)) => { out.push(c); rest = &rest[e.len() + 2..]; }+ _ => { out.push('&'); rest = &rest[1..]; }+ }+ }+ out + rest+}++fn implied_close(dom: &Dom, stack: &mut Vec<usize>, name: &str) {+ let (targets, stops): (&[&str], &[&str]) = match name {+ "li" => (&["li"], &["ul", "ol"]),+ "dt" | "dd" => (&["dt", "dd"], &["dl"]),+ "td" | "th" => (&["td", "th"], &["tr", "table"]),+ "tr" => (&["tr"], &["table"]),+ "option" => (&["option"], &["select"]),+ "p" | "div" | "ul" | "ol" | "dl" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "table" | "form" | "pre" | "blockquote" | "section"+ | "article" | "header" | "footer" | "nav" | "main" | "aside" | "hr" | "fieldset" => {+ if stack.len() > 1 && dom.nodes[*stack.last().unwrap()].tag == "p" { stack.pop(); }+ return;+ }+ _ => return,+ };+ for k in (1..stack.len()).rev() {+ let tag = dom.nodes[stack[k]].tag.as_str();+ if targets.contains(&tag) { stack.truncate(k); return; }+ if stops.contains(&tag) { return; }+ }+}++fn push_text(dom: &mut Dom, stack: &[usize], text: &str, doc: bool) {+ let p = *stack.last().unwrap();+ if doc && p == 0 && text.trim().is_empty() { return; }+ if let Some(&l) = dom.nodes[p].kids.last() {+ if dom.nodes[l].tag.is_empty() { dom.nodes[l].text.push_str(text); return; }+ }+ dom.add(p, Node { text: text.into(), ..Default::default() });+}++/// `doc`: wrap into html/head/body (documents); false for fragments.+pub fn parse(html: &str, doc: bool) -> Dom {+ let mut dom = Dom::new();+ let mut stack = vec![0usize];+ let mut i = 0;+ while i < html.len() {+ if html.as_bytes()[i] == b'<' {+ let rest = &html[i..];+ if rest.starts_with("<!--") {+ let end = rest[4..].find("-->").map(|e| 4 + e);+ // kept for scripts (hydration looks for <!--[--> anchors); a document's root-level comments are dropped so node numbering stays that of <html>+ if !(doc && stack.len() == 1) { dom.add(*stack.last().unwrap(), Node { tag: COMMENT.into(), text: rest[4..end.unwrap_or(rest.len())].into(), ..Default::default() }); }+ i = end.map_or(html.len(), |e| i + e + 3);+ continue;+ }+ if rest.starts_with("<?") {+ // `<?x>` is a bogus comment whose data is `?x` (Lit marks its child parts this way)+ let end = rest.find('>').unwrap_or(rest.len());+ if !(doc && stack.len() == 1) { dom.add(*stack.last().unwrap(), Node { tag: COMMENT.into(), text: rest[1..end].into(), ..Default::default() }); }+ i = (i + end + 1).min(html.len());+ continue;+ }+ if rest.starts_with("<!") || rest.starts_with("<?") { i = rest.find('>').map_or(html.len(), |e| i + e + 1); continue; }+ let closing = rest.starts_with("</");+ let first = rest.as_bytes().get(if closing { 2 } else { 1 }).copied().unwrap_or(0);+ if !first.is_ascii_alphabetic() { push_text(&mut dom, &stack, "<", doc); i += 1; continue; }+ let end = tag_end(html, i);+ let inner = &html[i + 1 + closing as usize..end];+ i = (end + 1).min(html.len());+ let nlen = inner.find(|c: char| c.is_whitespace() || c == '/').unwrap_or(inner.len());+ let name = inner[..nlen].to_ascii_lowercase();+ if closing {+ if let Some(k) = (1..stack.len()).rev().find(|&k| dom.nodes[stack[k]].tag == name) { stack.truncate(k); }+ continue;+ }+ implied_close(&dom, &mut stack, &name);+ let void = VOID.contains(&name.as_str());+ let id = dom.add(*stack.last().unwrap(), Node { tag: name.clone(), attrs: parse_attrs(&inner[nlen..]), ..Default::default() });+ if void || stack.len() >= MAX_DEPTH { continue; }+ stack.push(id);+ if matches!(name.as_str(), "script" | "style" | "title" | "textarea") {+ let j = find_ci(&html[i..], &format!("</{name}")).map_or(html.len(), |e| i + e);+ if j > i {+ let raw = &html[i..j];+ let text = if name == "script" || name == "style" { raw.to_string() } else { decode(raw) };+ dom.add(id, Node { text, ..Default::default() });+ }+ i = j;+ }+ } else {+ let end = html[i..].find('<').map_or(html.len(), |e| i + e);+ push_text(&mut dom, &stack, &decode(&html[i..end]), doc);+ i = end;+ }+ }+ if doc { dom.normalize(); }+ dom+}++#[cfg(test)]+mod tests {+ use super::*;++ fn tags(d: &Dom) -> Vec<String> { d.descendants().into_iter().skip(1).map(|i| if d.nodes[i].tag.is_empty() { format!("'{}'", d.nodes[i].text) } else { d.nodes[i].tag.clone() }).collect() }++ #[test]+ fn stray_quote_after_a_value_does_not_swallow_the_next_tags() {+ let d = parse("<ul><li class=\"\" data-id=\"x\"\"><b>hi</b></li></ul>", true);+ let li = d.find("li").unwrap();+ assert_eq!(d.attr(li, "data-id").as_deref(), Some("x"));+ assert_eq!(d.text_content(d.find("b").unwrap()), "hi");+ }++ #[test]+ fn processing_instruction_is_a_comment() {+ let d = parse("<p>a<?lit$1$>b</p>", true);+ let kids = &d.nodes[d.find("p").unwrap()].kids;+ assert_eq!((d.nodes[kids[1]].tag.as_str(), d.nodes[kids[1]].text.as_str()), (COMMENT, "?lit$1$"));+ }++ #[test]+ fn fragments_keep_root_whitespace() {+ // Svelte templates are `<!> <main>..</main> <!>`: sibling walks count the spaces+ assert_eq!(parse("<!----> <main></main> <b></b>", false).nodes[0].kids.len(), 5);+ assert_eq!(parse(" <p></p> ", true).nodes[0].kids.len(), 1, "documents still drop it");+ }++ #[test]+ fn comments_reach_scripts_but_not_layout() {+ let d = parse("<!-- root --><p>a<!--[-->b<!--]--></p>", true);+ let p = d.find("p").unwrap();+ assert_eq!(d.nodes[p].kids.iter().filter(|&&k| d.nodes[k].tag == COMMENT).count(), 2, "kept inside elements");+ assert!(d.nodes[0].kids.iter().all(|&k| d.nodes[k].tag != COMMENT), "root-level comments are dropped");+ let d2 = Dom::from_json(&d.to_json(d.nodes[0].kids[0])).unwrap();+ assert!(d2.has_comments(), "survives the JSON bridge");+ let mut d3 = d2.clone();+ d3.strip_comments();+ let p3 = d3.find("p").unwrap();+ assert_eq!(d3.nodes[p3].kids.len(), 1, "text around the comments is joined");+ assert_eq!(d3.text_content(p3), "ab");+ }++ #[test]+ fn structure_and_implied_ends() {+ let d = parse("<ul><li>a<li>b</ul><p>x<p>y<b>z</b>", true);+ assert_eq!(tags(&d).join(" "), "html head body ul li 'a' li 'b' p 'x' p 'y' b 'z'");+ }++ #[test]+ fn raw_text_and_attrs() {+ let d = parse("<a href=/x class='c d' data-q=\"a>b\">t</a><script>if(a<b){}</script>", true);+ let a = d.find("a").unwrap();+ assert_eq!(d.attr(a, "href"), Some("/x"));+ assert_eq!(d.attr(a, "data-q"), Some("a>b"));+ assert_eq!(d.text_content(d.find("script").unwrap()), "if(a<b){}");+ }++ #[test]+ fn json_roundtrip() {+ let d = parse("<p id=x>hi <b>there</b></p>", true);+ let v = d.to_json(d.nodes[0].kids[0]);+ let d2 = Dom::from_json(&v).unwrap();+ assert_eq!(tags(&d), tags(&d2));+ assert_eq!(d2.attr(d2.find("p").unwrap(), "id"), Some("x"));+ }++ #[test]+ fn entities() {+ assert_eq!(decode("a b AB — &bogus; & x"), "a b AB — &bogus; & x");+ }++ #[test]+ fn deep_nesting_is_capped() {+ let d = parse(&"<div>".repeat(5000), true);+ assert!(d.nodes.len() < 6000);+ }+}diff --git a/plugins/chrome-rs/src/gfx.rs b/plugins/chrome-rs/src/gfx.rsnew file mode 100644index 0000000..7394915--- /dev/null+++ b/plugins/chrome-rs/src/gfx.rs@@ -0,0 +1,694 @@+// Fonts, line layout and software drawing (pixels are 0x00RRGGBB in a softbuffer slice).+use crate::{load::Img, render::{Field, FieldKind}};+use fontdue::{Font, FontSettings, Metrics};+use std::{cell::Cell, collections::HashMap, sync::Mutex};++thread_local! { static CLIP: Cell<Option<(i32, i32, i32, i32)>> = const { Cell::new(None) }; }++/// Restricts all painting to the screen rectangle (x0, y0, x1, y1), used for the content of a scroll container; None = the whole buffer.+pub fn set_clip(c: Option<(i32, i32, i32, i32)>) { CLIP.with(|k| k.set(c)); }++fn clip_box(bw: usize, bh: usize) -> (i32, i32, i32, i32) {+ let (a, b, c, d) = CLIP.with(Cell::get).unwrap_or((0, 0, i32::MAX, i32::MAX));+ (a.max(0), b.max(0), c.min(bw as i32), d.min(bh as i32))+}++/// A text face packs weight/style/family: bit 0 bold, bit 1 italic, bit 2 monospace, bits 4.. web-font family id (0 = none).+pub const BOLD: u16 = 1;+pub const MONO: u16 = 4;++pub fn face(bold: bool, italic: bool, mono: bool, fam: u16) -> u16 { bold as u16 | (italic as u16) << 1 | (mono as u16) << 2 | fam << 4 }++/// Stable id (1-based) of a lowercase font-family name; shared by the page-loading thread and the UI thread.+pub fn family_id(name: &str) -> u16 {+ static NAMES: Mutex<Vec<String>> = Mutex::new(Vec::new());+ let Ok(mut n) = NAMES.lock() else { return 0 };+ let lower = name.trim().to_ascii_lowercase();+ match n.iter().position(|x| *x == lower) { Some(i) => i as u16 + 1, None => { n.push(lower); n.len().min(4095) as u16 } }+}++/// Rasterizer behind a font slot. Fontdue parses every outline of a font when it is loaded (a 20 MB CJK font costs 150-250 MB),+/// so coverage fallbacks use ttf-parser instead: the file bytes stay as they are and each glyph is outlined only when it is drawn.+enum Rast { Fd(Font), Tp(ttf_parser::Face<'static>) }++#[derive(Clone)]+enum Bytes { Own(std::sync::Arc<Vec<u8>>), Leaked(&'static [u8]) }++impl Bytes { fn as_slice(&self) -> &[u8] { match self { Bytes::Own(a) => a, Bytes::Leaked(s) => s } } }++struct Slot { font: Rast, bold: bool, data: Bytes }++impl Slot {+ fn has(&self, c: char) -> bool {+ match &self.font { Rast::Fd(f) => f.lookup_glyph_index(c) != 0, Rast::Tp(f) => f.glyph_index(c).is_some_and(|g| g.0 != 0) }+ }+ fn raster(&self, c: char, size: f32) -> (Metrics, Vec<u8>) {+ match &self.font { Rast::Fd(f) => f.rasterize(c, size), Rast::Tp(f) => tp_raster(f, f.glyph_index(c).map_or(0, |g| g.0), size) }+ }+ fn raster_id(&self, id: u16, size: f32) -> (Metrics, Vec<u8>) {+ match &self.font { Rast::Fd(f) => f.rasterize_indexed(id, size), Rast::Tp(f) => tp_raster(f, id, size) }+ }+}++/// Collects a glyph outline into an `ab_glyph_rasterizer` canvas (font units, y up -> pixels, y down).+struct Outline { r: ab_glyph_rasterizer::Rasterizer, k: f32, ox: f32, top: f32, start: (f32, f32), last: (f32, f32) }++impl Outline {+ fn pt(&self, x: f32, y: f32) -> (f32, f32) { (x * self.k - self.ox, self.top - y * self.k) }+}++impl ttf_parser::OutlineBuilder for Outline {+ fn move_to(&mut self, x: f32, y: f32) { self.start = self.pt(x, y); self.last = self.start; }+ fn line_to(&mut self, x: f32, y: f32) { let p = self.pt(x, y); self.r.draw_line(ab_glyph_rasterizer::point(self.last.0, self.last.1), ab_glyph_rasterizer::point(p.0, p.1)); self.last = p; }+ fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {+ let (c, p) = (self.pt(x1, y1), self.pt(x, y));+ self.r.draw_quad(ab_glyph_rasterizer::point(self.last.0, self.last.1), ab_glyph_rasterizer::point(c.0, c.1), ab_glyph_rasterizer::point(p.0, p.1));+ self.last = p;+ }+ fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {+ let (c1, c2, p) = (self.pt(x1, y1), self.pt(x2, y2), self.pt(x, y));+ self.r.draw_cubic(ab_glyph_rasterizer::point(self.last.0, self.last.1), ab_glyph_rasterizer::point(c1.0, c1.1), ab_glyph_rasterizer::point(c2.0, c2.1), ab_glyph_rasterizer::point(p.0, p.1));+ self.last = p;+ }+ fn close(&mut self) {+ if self.last != self.start { self.r.draw_line(ab_glyph_rasterizer::point(self.last.0, self.last.1), ab_glyph_rasterizer::point(self.start.0, self.start.1)); }+ self.last = self.start;+ }+}++/// One glyph as fontdue-style metrics and an 8-bit coverage bitmap, outlined on demand.+fn tp_raster(face: &ttf_parser::Face<'static>, id: u16, size: f32) -> (Metrics, Vec<u8>) {+ let gid = ttf_parser::GlyphId(id);+ let k = size / face.units_per_em().max(1) as f32;+ let mut m = Metrics { advance_width: face.glyph_hor_advance(gid).unwrap_or(0) as f32 * k, ..Metrics::default() };+ let Some(bb) = face.glyph_bounding_box(gid) else { return (m, vec![]) };+ let (x0, x1, y0, y1) = ((bb.x_min as f32 * k).floor(), (bb.x_max as f32 * k).ceil(), (bb.y_min as f32 * k).floor(), (bb.y_max as f32 * k).ceil());+ let (w, h) = ((x1 - x0) as usize, (y1 - y0) as usize);+ if w == 0 || h == 0 || w * h > 4_000_000 { return (m, vec![]); }+ let mut ob = Outline { r: ab_glyph_rasterizer::Rasterizer::new(w, h), k, ox: x0, top: y1, start: (0.0, 0.0), last: (0.0, 0.0) };+ if face.outline_glyph(gid, &mut ob).is_none() { return (m, vec![]); }+ let mut bm = vec![0u8; w * h];+ ob.r.for_each_pixel_2d(|x, y, a| bm[y as usize * w + x as usize] = (a * 255.0).round().clamp(0.0, 255.0) as u8);+ (m.xmin, m.ymin, m.width, m.height) = (x0 as i32, y0 as i32, w, h);+ (m, bm)+}++/// A fallback font file: path, whether it is loaded as a slot, and (once scanned) the code point ranges its cmap covers,+/// so that fonts known not to cover a character are not read again.+struct Fb { path: std::path::PathBuf, loaded: bool, cov: Option<Vec<(u32, u32)>> }++fn covers(ranges: &[(u32, u32)], c: u32) -> bool { ranges.binary_search_by(|&(a, b)| if c < a { std::cmp::Ordering::Greater } else if c > b { std::cmp::Ordering::Less } else { std::cmp::Ordering::Equal }).is_ok() }++fn coverage(face: &ttf_parser::Face) -> Vec<(u32, u32)> {+ let mut cps: Vec<u32> = vec![];+ if let Some(cmap) = face.tables().cmap { for st in cmap.subtables { if st.is_unicode() { st.codepoints(|c| cps.push(c)); } } }+ cps.sort_unstable();+ cps.dedup();+ let mut out: Vec<(u32, u32)> = vec![];+ for c in cps { match out.last_mut() { Some(l) if l.1 + 1 == c => l.1 = c, _ => out.push((c, c)) } }+ out+}++/// Four faces (regular, bold, italic, bold-italic) of one family; a face is read from disk the first time text needs it.+struct LazySet { paths: [String; 4], slots: [Option<usize>; 4] }++impl LazySet { fn none() -> LazySet { LazySet { paths: Default::default(), slots: [None; 4] } } }++/// Shaped text run: glyph ids with pixel advances/offsets in visual (left-to-right) order.+struct Shaped { glyphs: Vec<(u16, f32, f32, f32)>, width: f32, slot: usize }++/// Scripts that need shaping (joining, reordering, marks): Hebrew, Arabic, Indic, Thai, presentation forms.+pub fn complex(s: &str) -> bool { s.chars().any(|c| matches!(c as u32, 0x0590..=0x08FF | 0x0900..=0x0EFF | 0xFB1D..=0xFDFF | 0xFE70..=0xFEFF)) }++/// Right-to-left text: the first strong character is Hebrew or Arabic.+pub fn is_rtl(s: &str) -> bool { s.chars().find(|c| c.is_alphabetic()).is_some_and(|c| matches!(c as u32, 0x0590..=0x08FF | 0xFB1D..=0xFDFF | 0xFE70..=0xFEFF)) }++/// Loaded fonts: regular/bold/italic/bold-italic sets for sans and mono, lazily loaded coverage fallbacks (symbols, CJK, ...)+/// and per-page web fonts. Glyphs are looked up per character, so a missing glyph falls through to the next font.+pub struct Fonts {+ slots: Vec<Slot>,+ sans: LazySet,+ mono: LazySet,+ fallback: Vec<Fb>,+ fb_slots: Vec<usize>, // slots of loaded fallbacks+ missing: std::collections::HashSet<char>, // characters no font covers (not searched again)+ web: HashMap<u16, [Option<usize>; 4]>,+ cache: HashMap<(char, u32, u16), (Metrics, Vec<u8>, bool)>,+ shaped: HashMap<(String, u32, u16), std::rc::Rc<Shaped>>,+ glyphs: HashMap<(usize, u16, u32), (Metrics, Vec<u8>)>,+}++const SANS: &[[&str; 4]] = &[+ ["C:\\Windows\\Fonts\\segoeui.ttf", "C:\\Windows\\Fonts\\segoeuib.ttf", "C:\\Windows\\Fonts\\segoeuii.ttf", "C:\\Windows\\Fonts\\segoeuiz.ttf"],+ ["C:\\Windows\\Fonts\\arial.ttf", "C:\\Windows\\Fonts\\arialbd.ttf", "C:\\Windows\\Fonts\\ariali.ttf", "C:\\Windows\\Fonts\\arialbi.ttf"],+ ["/System/Library/Fonts/Supplemental/Arial.ttf", "/System/Library/Fonts/Supplemental/Arial Bold.ttf", "/System/Library/Fonts/Supplemental/Arial Italic.ttf", "/System/Library/Fonts/Supplemental/Arial Bold Italic.ttf"],+ ["/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans-Oblique.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans-BoldOblique.ttf"],+ ["/usr/share/fonts/TTF/DejaVuSans.ttf", "/usr/share/fonts/TTF/DejaVuSans-Bold.ttf", "/usr/share/fonts/TTF/DejaVuSans-Oblique.ttf", "/usr/share/fonts/TTF/DejaVuSans-BoldOblique.ttf"],+];+const MONOS: &[[&str; 4]] = &[+ ["C:\\Windows\\Fonts\\consola.ttf", "C:\\Windows\\Fonts\\consolab.ttf", "C:\\Windows\\Fonts\\consolai.ttf", "C:\\Windows\\Fonts\\consolaz.ttf"],+ ["C:\\Windows\\Fonts\\cour.ttf", "C:\\Windows\\Fonts\\courbd.ttf", "C:\\Windows\\Fonts\\couri.ttf", "C:\\Windows\\Fonts\\courbi.ttf"],+ ["/System/Library/Fonts/Menlo.ttc", "", "", ""],+ ["/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Oblique.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSansMono-BoldOblique.ttf"],+ ["/usr/share/fonts/TTF/DejaVuSansMono.ttf", "/usr/share/fonts/TTF/DejaVuSansMono-Bold.ttf", "/usr/share/fonts/TTF/DejaVuSansMono-Oblique.ttf", "/usr/share/fonts/TTF/DejaVuSansMono-BoldOblique.ttf"],+];+/// Tried in order, only when a character is missing from the main fonts (large CJK fonts are therefore loaded on demand).+const FALLBACKS: &[&str] = &[+ "C:\\Windows\\Fonts\\seguisym.ttf", "C:\\Windows\\Fonts\\tahoma.ttf", "C:\\Windows\\Fonts\\Nirmala.ttf", "C:\\Windows\\Fonts\\Nirmala.ttc", "C:\\Windows\\Fonts\\msyh.ttc", "C:\\Windows\\Fonts\\YuGothM.ttc",+ "C:\\Windows\\Fonts\\malgun.ttf", "C:\\Windows\\Fonts\\simsun.ttc", "C:\\Windows\\Fonts\\seguiemj.ttf", "C:\\Windows\\Fonts\\mingliub.ttc",+ "/System/Library/Fonts/PingFang.ttc", "/System/Library/Fonts/Apple Symbols.ttf", "/System/Library/Fonts/Supplemental/Arial Unicode.ttf",+ "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", "/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc", "/usr/share/fonts/truetype/noto/NotoSans-Regular.ttf",+ "/usr/share/fonts/truetype/noto/NotoSansDevanagari-Regular.ttf", "/usr/share/fonts/truetype/lohit-devanagari/Lohit-Devanagari.ttf",+ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", "/usr/share/fonts/truetype/freefont/FreeSans.ttf",+];++fn variant(set: &[Option<usize>; 4], ix: usize) -> Option<usize> { set[ix].or(set[ix & 1]).or(set[0]).or_else(|| set.iter().flatten().next().copied()) }++fn read_font(path: &str) -> Option<(Font, Vec<u8>)> {+ if path.is_empty() { return None; }+ let data = std::fs::read(path).ok()?;+ Some((Font::from_bytes(data.as_slice(), FontSettings::default()).ok()?, data))+}++impl Fonts {+ /// A single regular font (tests, tools).+ #[cfg(test)]+ pub fn new(font: Font, mono: Option<Font>) -> Fonts {+ let mut f = Fonts { slots: vec![], sans: LazySet::none(), mono: LazySet::none(), fallback: vec![], web: HashMap::new(), cache: HashMap::new(), shaped: HashMap::new(), glyphs: HashMap::new(), fb_slots: vec![], missing: Default::default() };+ f.sans.slots[0] = Some(f.add(font, false, vec![]));+ if let Some(m) = mono { f.mono.slots[0] = Some(f.add(m, false, vec![])); }+ f+ }++ /// The first installed sans and mono families we know (regular faces now, the rest on demand) plus lazy fallbacks.+ pub fn system() -> Option<Fonts> {+ let mut f = Fonts { slots: vec![], sans: LazySet::none(), mono: LazySet::none(), fallback: FALLBACKS.iter().map(|p| Fb { path: p.into(), loaded: false, cov: None }).collect(), web: HashMap::new(), cache: HashMap::new(), shaped: HashMap::new(), glyphs: HashMap::new(), fb_slots: vec![], missing: Default::default() };+ for (set, lists) in [(0, SANS), (1, MONOS)] {+ for paths in lists {+ let Some((font, data)) = read_font(paths[0]) else { continue };+ let reg = f.add(font, false, data);+ let ls = LazySet { paths: [String::new(), paths[1].into(), paths[2].into(), paths[3].into()], slots: [Some(reg), None, None, None] };+ if set == 0 { f.sans = ls } else { f.mono = ls }+ break;+ }+ }+ f.sans.slots[0]?;+ Some(f)+ }++ /// Loads face `ix` of a set when it exists on disk and was not read yet.+ fn ensure(&mut self, mono: bool, ix: usize) -> Option<usize> {+ let set = if mono { &mut self.mono } else { &mut self.sans };+ if set.slots[ix].is_some() { return set.slots[ix]; }+ let path = std::mem::take(&mut set.paths[ix]); // taken: a missing or broken file is not retried+ if path.is_empty() { return None; }+ let (font, data) = read_font(&path)?;+ let i = self.add(font, ix & 1 != 0, data);+ if mono { self.mono.slots[ix] = Some(i) } else { self.sans.slots[ix] = Some(i) }+ Some(i)+ }++ /// Best available face for (bold, italic): exact, then same weight upright, then regular, then anything loaded.+ fn pick_face(&mut self, mono: bool, ix: usize) -> Option<usize> {+ for want in [ix, ix & 1, 0] { if let Some(i) = self.ensure(mono, want) { return Some(i); } }+ let set = if mono { &self.mono } else { &self.sans };+ set.slots.iter().flatten().next().copied()+ }++ fn add(&mut self, font: Font, bold: bool, data: Vec<u8>) -> usize { self.slots.push(Slot { font: Rast::Fd(font), bold, data: Bytes::Own(std::sync::Arc::new(data)) }); self.slots.len() - 1 }++ /// Registers a web font (already decoded to TTF/OTF bytes) for family id `fam`; false when it does not parse.+ pub fn add_web(&mut self, fam: u16, bold: bool, italic: bool, data: &[u8]) -> bool {+ if self.slots.len() > 64 { return false; }+ let Ok(font) = Font::from_bytes(data, FontSettings::default()) else { return false };+ let i = self.add(font, bold, data.to_vec());+ self.web.entry(fam).or_default()[bold as usize | (italic as usize) << 1] = Some(i);+ self.cache.retain(|k, _| k.2 >> 4 != fam);+ true+ }++ /// Font slot and "needs fake bold" for character `c` in `face`.+ fn pick(&mut self, c: char, face: u16) -> (usize, bool) {+ let ix = (face & 3) as usize;+ let web = (face >> 4 != 0).then(|| self.web.get(&(face >> 4)).and_then(|s| variant(s, ix))).flatten();+ let main = if face & MONO != 0 { self.pick_face(true, ix).or_else(|| self.pick_face(false, ix)) } else { self.pick_face(false, ix) }.unwrap_or(0);+ let has = |s: &Vec<Slot>, i: usize| s[i].has(c);+ let mut idx = web.filter(|&i| has(&self.slots, i)).or_else(|| has(&self.slots, main).then_some(main));+ if idx.is_none() && !c.is_control() && !self.missing.contains(&c) {+ if self.fallback.is_empty() { idx = (0..self.slots.len()).find(|&i| has(&self.slots, i)); } // plain test fonts+ // fonts loaded earlier as fallbacks first, then unloaded candidates: only one that covers `c` is kept in memory+ idx = idx.or_else(|| self.fb_slots.iter().copied().find(|&i| has(&self.slots, i)));+ for k in 0..self.fallback.len() {+ if idx.is_some() { break; }+ if self.fallback[k].loaded || self.fallback[k].cov.as_ref().is_some_and(|r| !covers(r, c as u32)) { continue; }+ let Ok(data) = std::fs::read(&self.fallback[k].path) else { self.fallback[k].loaded = true; continue }; // unreadable: never retried+ let cov = match ttf_parser::Face::parse(&data, 0) { Ok(face) => coverage(&face), Err(_) => { self.fallback[k].loaded = true; continue } };+ if covers(&cov, c as u32) {+ let leaked: &'static [u8] = Box::leak(data.into_boxed_slice()); // font files live as long as the process+ let Ok(face) = ttf_parser::Face::parse(leaked, 0) else { self.fallback[k].loaded = true; continue };+ if std::env::var_os("CHROME_RS_DEBUG").is_some() { eprintln!("fallback font {} loaded for {c:?} (U+{:04X}), {} bytes", self.fallback[k].path.display(), c as u32, leaked.len()); }+ self.slots.push(Slot { font: Rast::Tp(face), bold: false, data: Bytes::Leaked(leaked) });+ self.fallback[k].loaded = true;+ self.fb_slots.push(self.slots.len() - 1);+ idx = Some(self.slots.len() - 1);+ } else { self.fallback[k].cov = Some(cov); }+ }+ if idx.is_none() { self.missing.insert(c); }+ }+ let i = idx.unwrap_or(main);+ (i, face & BOLD != 0 && !self.slots[i].bold)+ }++ fn get(&mut self, c: char, size: f32, face: u16) -> &(Metrics, Vec<u8>, bool) {+ let key = (c, size as u32, face);+ if !self.cache.contains_key(&key) {+ if self.cache.len() > 40_000 { self.cache.clear(); }+ let (i, synth) = self.pick(c, face);+ let (m, b) = self.slots[i].raster(c, size);+ self.cache.insert(key, (m, b, synth));+ }+ &self.cache[&key]+ }++ pub fn width(&mut self, s: &str, size: f32) -> f32 { self.width_f(s, size, 0) }+ pub fn width_f(&mut self, s: &str, size: f32, face: u16) -> f32 {+ if complex(s) { if let Some(sh) = self.shape(s, size, face) { return sh.width; } }+ s.chars().map(|c| self.get(c, size, face).0.advance_width).sum()+ }++ /// Shapes `s` with the font that covers its first complex character (cached); None when the font data cannot be shaped.+ fn shape(&mut self, s: &str, size: f32, face: u16) -> Option<std::rc::Rc<Shaped>> {+ let key = (s.to_string(), size as u32, face);+ if let Some(r) = self.shaped.get(&key) { return Some(r.clone()); }+ let first = s.chars().find(|&c| complex(&c.to_string())).unwrap_or('a');+ let (slot, _) = self.pick(first, face);+ let data = self.slots[slot].data.clone();+ let rb = rustybuzz::Face::from_slice(data.as_slice(), 0)?;+ let k = size / rb.units_per_em() as f32;+ let mut buf = rustybuzz::UnicodeBuffer::new();+ buf.push_str(s);+ buf.guess_segment_properties();+ let out = rustybuzz::shape(&rb, &[], buf);+ let glyphs: Vec<(u16, f32, f32, f32)> = out.glyph_infos().iter().zip(out.glyph_positions()).map(|(i, p)| (i.glyph_id as u16, p.x_offset as f32 * k, p.y_offset as f32 * k, p.x_advance as f32 * k)).collect();+ let width = glyphs.iter().map(|g| g.3).sum();+ if self.shaped.len() > 5000 { self.shaped.clear(); }+ let r = std::rc::Rc::new(Shaped { glyphs, width, slot });+ self.shaped.insert(key, r.clone());+ Some(r)+ }++ fn glyph(&mut self, slot: usize, id: u16, size: f32) -> &(Metrics, Vec<u8>) {+ if self.glyphs.len() > 20_000 { self.glyphs.clear(); }+ let sl = &self.slots[slot];+ self.glyphs.entry((slot, id, size as u32)).or_insert_with(|| sl.raster_id(id, size))+ }+ pub fn cw(&mut self, c: char, size: f32) -> f32 { self.get(c, size, 0).0.advance_width }+}++pub fn blend(d: u32, s: u32, a: u32) -> u32 {+ let ch = |sh: u32| (((s >> sh) & 255) * a + ((d >> sh) & 255) * (255 - a)) / 255 << sh;+ ch(16) | ch(8) | ch(0)+}++pub fn fill(buf: &mut [u32], bw: usize, x: i32, y: i32, w: i32, h: i32, color: u32) {+ let (cx0, cy0, cx1, cy1) = clip_box(bw, buf.len() / bw.max(1));+ for py in y.max(cy0)..(y + h).min(cy1) {+ for px in x.max(cx0)..(x + w).min(cx1) {+ if let Some(d) = buf.get_mut(py as usize * bw + px as usize) { *d = color; }+ }+ }+}++/// Like `fill`, blended with `a` (0..=255).+pub fn fill_a(buf: &mut [u32], bw: usize, x: i32, y: i32, w: i32, h: i32, color: u32, a: u32) {+ if a >= 255 { return fill(buf, bw, x, y, w, h, color); }+ let (cx0, cy0, cx1, cy1) = clip_box(bw, buf.len() / bw.max(1));+ for py in y.max(cy0)..(y + h).min(cy1) {+ for px in x.max(cx0)..(x + w).min(cx1) {+ if let Some(d) = buf.get_mut(py as usize * bw + px as usize) { *d = blend(*d, color, a); }+ }+ }+}++/// Rounded rectangle, filled or (ring > 0) an outline `ring` px thick; anti-aliased with a signed distance field.+pub fn draw_rrect(buf: &mut [u32], bw: usize, bh: usize, x: f32, y: f32, w: f32, h: f32, r: f32, ring: f32, color: u32) {+ draw_rrect_a(buf, bw, bh, x, y, w, h, r, ring, &|_, _| color, 255);+}++/// `draw_rrect` with a per-pixel color (gradients; arguments are the pixel's position inside the rectangle, 0..1) and an overall alpha.+pub fn draw_rrect_a(buf: &mut [u32], bw: usize, bh: usize, x: f32, y: f32, w: f32, h: f32, r: f32, ring: f32, color: &dyn Fn(f32, f32) -> u32, alpha: u32) {+ let r = r.min(w.min(h) / 2.0).max(0.0);+ let (cx, cy, hx, hy) = (x + w / 2.0, y + h / 2.0, w / 2.0 - r, h / 2.0 - r);+ let (cx0, cy0, cx1, cy1) = clip_box(bw, bh);+ for py in (y.floor() as i32).max(cy0)..((y + h).ceil() as i32).min(cy1) {+ for px in (x.floor() as i32).max(cx0)..((x + w).ceil() as i32).min(cx1) {+ let (qx, qy) = ((px as f32 + 0.5 - cx).abs() - hx, (py as f32 + 0.5 - cy).abs() - hy);+ let d = qx.max(0.0).hypot(qy.max(0.0)) + qx.max(qy).min(0.0) - r;+ let mut cov = (0.5 - d).clamp(0.0, 1.0);+ if ring > 0.0 { cov -= (0.5 - (d + ring)).clamp(0.0, 1.0); }+ if cov > 0.0 { let i = py as usize * bw + px as usize; let c = color((px as f32 + 0.5 - x) / w.max(1.0), (py as f32 + 0.5 - y) / h.max(1.0)); buf[i] = blend(buf[i], c, (cov * alpha as f32) as u32); }+ }+ }+}++/// Paints a layout rectangle (`dy` = vertical offset of the viewport).+pub fn draw_rect(buf: &mut [u32], bw: usize, bh: usize, r: &crate::layout::Rect, dy: f32) {+ let y = r.y + dy;+ if r.a == 0 || r.pic.is_some() { return; } // markers are invisible // background images are drawn by `draw_pic`, which needs the page's pictures+ if let Some(g) = &r.grad {+ let (sin, cos) = g.angle.to_radians().sin_cos();+ let half = (w_h_len(r.w, r.h, sin, cos)) / 2.0;+ let at = |px: f32, py: f32| {+ if g.radial { // farthest-corner sizing: a circle reaches the far corner, an ellipse keeps the box's proportions+ let (cx, cy) = g.at;+ let (dx, dy) = ((px - cx) * r.w, (py - cy) * r.h);+ let (fx, fy) = (cx.max(1.0 - cx) * r.w, cy.max(1.0 - cy) * r.h);+ let t = if g.circle { dx.hypot(dy) / fx.hypot(fy).max(1.0) } else { (dx / (fx * std::f32::consts::SQRT_2).max(1.0)).hypot(dy / (fy * std::f32::consts::SQRT_2).max(1.0)) };+ return grad_color(&g.stops, t.clamp(0.0, 1.0));+ }+ let (dx, dy) = ((px - 0.5) * r.w, (py - 0.5) * r.h);+ let t = if half > 0.0 { 0.5 + (dx * sin - dy * cos) / (2.0 * half) } else { 0.0 };+ grad_color(&g.stops, t.clamp(0.0, 1.0))+ };+ draw_rrect_a(buf, bw, bh, r.x, y, r.w, r.h, r.r, r.ring, &at, r.a as u32);+ } else if r.r > 0.0 || r.ring > 0.0 { draw_rrect_a(buf, bw, bh, r.x, y, r.w, r.h, r.r, r.ring, &|_, _| r.color, r.a as u32); }+ else { fill_a(buf, bw, r.x as i32, y as i32, r.w as i32, r.h as i32, r.color, r.a as u32); }+}++/// A background image: scaled to the tile size, offset inside the rectangle, repeated per axis, clipped to the rectangle.+pub fn draw_pic(buf: &mut [u32], bw: usize, bh: usize, im: &Img, r: &crate::layout::Rect, dy: f32) {+ let Some(pic) = &r.pic else { return };+ if im.w == 0 || im.h == 0 { return; }+ let y = r.y + dy;+ let (cx0, cy0, cx1, cy1) = clip_box(bw, bh);+ let (x0, x1) = ((r.x.floor() as i32).max(cx0), ((r.x + r.w).ceil() as i32).min(cx1));+ let (y0, y1) = ((y.floor() as i32).max(cy0), ((y + r.h).ceil() as i32).min(cy1));+ for py in y0..y1 {+ let mut ly = py as f32 + 0.5 - (y + pic.oy);+ if pic.ry { ly = ly.rem_euclid(pic.h); } else if ly < 0.0 || ly >= pic.h { continue; }+ let sy = ((ly / pic.h * im.h as f32) as usize).min(im.h as usize - 1);+ for px in x0..x1 {+ let mut lx = px as f32 + 0.5 - (r.x + pic.ox);+ if pic.rx { lx = lx.rem_euclid(pic.w); } else if lx < 0.0 || lx >= pic.w { continue; }+ let sx = ((lx / pic.w * im.w as f32) as usize).min(im.w as usize - 1);+ let p = &im.px[(sy * im.w as usize + sx) * 4..][..4];+ if p[3] == 0 { continue; }+ let d = &mut buf[py as usize * bw + px as usize];+ *d = blend(*d, (p[0] as u32) << 16 | (p[1] as u32) << 8 | p[2] as u32, p[3] as u32);+ }+ }+}++/// Thin scrollbar on the right edge of a scroll container's box at screen (x, y, w, h).+pub fn draw_box_scrollbar(buf: &mut [u32], bw: usize, bh: usize, x: f32, y: f32, w: f32, h: f32, content_h: f32, offset: f32, sc: f32) {+ let max = (content_h - h).max(0.0);+ if max < 1.0 || h < 24.0 * sc { return; }+ let th = (h * h / content_h).max(20.0 * sc).min(h);+ draw_rrect(buf, bw, bh, x + w - 7.0 * sc, y + offset.clamp(0.0, max) / max * (h - th), 5.0 * sc, th, 2.5 * sc, 0.0, 0x9A9A9A);+}++/// Length of the gradient line of a w x h box for a CSS angle (direction `sin, -cos` in screen space).+fn w_h_len(w: f32, h: f32, sin: f32, cos: f32) -> f32 { (w * sin).abs() + (h * cos).abs() }++fn grad_color(stops: &[(f32, u32)], t: f32) -> u32 {+ let Some(first) = stops.first() else { return 0 };+ if t <= first.0 { return first.1; }+ for w in stops.windows(2) {+ let ((p0, c0), (p1, c1)) = (w[0], w[1]);+ if t <= p1 { return if p1 > p0 { blend(c0, c1, (((t - p0) / (p1 - p0)) * 255.0) as u32) } else { c1 }; }+ }+ stops[stops.len() - 1].1+}++/// Nearest-neighbour blit of an RGBA image scaled to w x h at (x, y); alpha-blended, clipped to the buffer.+pub fn draw_image(buf: &mut [u32], bw: usize, bh: usize, im: &Img, x: f32, y: f32, w: f32, h: f32, alpha: u32) {+ let (cx0, cy0, cx1, cy1) = clip_box(bw, bh);+ let (x0, y0, wi, hi) = (x as i32, y as i32, w.max(1.0) as i32, h.max(1.0) as i32);+ for dy in 0..hi {+ let py = y0 + dy;+ if py < cy0 || py >= cy1 { continue; }+ let sy = (dy as u64 * im.h as u64 / hi as u64) as usize;+ for dx in 0..wi {+ let px = x0 + dx;+ if px < cx0 || px >= cx1 { continue; }+ let sx = (dx as u64 * im.w as u64 / wi as u64) as usize;+ let p = &im.px[(sy * im.w as usize + sx) * 4..][..4];+ if p[3] == 0 { continue; }+ let d = &mut buf[py as usize * bw + px as usize];+ *d = blend(*d, (p[0] as u32) << 16 | (p[1] as u32) << 8 | p[2] as u32, p[3] as u32 * alpha / 255);+ }+ }+}++pub fn draw_text(buf: &mut [u32], bw: usize, bh: usize, f: &mut Fonts, s: &str, x: f32, base: f32, size: f32, color: u32) {+ draw_text_m(buf, bw, bh, f, s, x, base, size, color, false);+}++pub fn draw_text_m(buf: &mut [u32], bw: usize, bh: usize, f: &mut Fonts, s: &str, x: f32, base: f32, size: f32, color: u32, mono: bool) {+ draw_text_f(buf, bw, bh, f, s, x, base, size, color, face(false, false, mono, 0));+}++/// Draws `s` in `face`; bold is faked by double-striking when the chosen font has no bold variant.+pub fn draw_text_f(buf: &mut [u32], bw: usize, bh: usize, f: &mut Fonts, s: &str, x: f32, base: f32, size: f32, color: u32, face: u16) {+ draw_text_ls(buf, bw, bh, f, s, x, base, size, color, face, 0.0);+}++/// `draw_text_f` with `ls` extra pixels after every character (letter-spacing).+pub fn draw_text_ls(buf: &mut [u32], bw: usize, bh: usize, f: &mut Fonts, s: &str, mut x: f32, base: f32, size: f32, color: u32, face: u16, ls: f32) {+ let (cx0, cy0, cx1, cy1) = clip_box(bw, bh);+ if complex(s) {+ if let Some(sh) = f.shape(s, size, face) {+ for &(id, ox, oy, adv) in &sh.glyphs {+ let (m, bm) = f.glyph(sh.slot, id, size);+ let gx = (x + ox + m.xmin as f32) as i32;+ let gy = (base - oy - m.height as f32 - m.ymin as f32) as i32;+ for row in 0..m.height {+ let py = gy + row as i32;+ if py < cy0 || py >= cy1 { continue; }+ for col in 0..m.width {+ let px = gx + col as i32;+ let a = bm[row * m.width + col] as u32;+ if a == 0 || px < cx0 || px >= cx1 { continue; }+ let d = &mut buf[py as usize * bw + px as usize];+ *d = blend(*d, color, a);+ }+ }+ x += adv + ls;+ }+ return;+ }+ }+ for c in s.chars() {+ let (m, bm, synth) = f.get(c, size, face);+ for pass in 0..1 + *synth as i32 {+ let gx = (x + m.xmin as f32) as i32 + pass;+ let gy = (base - m.height as f32 - m.ymin as f32) as i32;+ for row in 0..m.height {+ let py = gy + row as i32;+ if py < cy0 || py >= cy1 { continue; }+ for col in 0..m.width {+ let px = gx + col as i32;+ let a = bm[row * m.width + col] as u32;+ if a == 0 || px < cx0 || px >= cx1 { continue; }+ let d = &mut buf[py as usize * bw + px as usize];+ *d = blend(*d, color, a);+ }+ }+ }+ x += m.advance_width + ls;+ }+}++/// Visual lines of `chars` as [start, end) ranges: hard breaks at '\n', soft breaks when a line would exceed `max`.+pub fn wrap_lines(f: &mut Fonts, chars: &[char], fs: f32, max: f32) -> Vec<(usize, usize)> {+ let (mut out, mut start, mut wsum) = (vec![], 0, 0.0);+ for (i, &c) in chars.iter().enumerate() {+ if c == '\n' { out.push((start, i)); start = i + 1; wsum = 0.0; continue; }+ let cw = f.cw(c, fs);+ if wsum + cw > max && i > start { out.push((start, i)); start = i; wsum = 0.0; }+ wsum += cw;+ }+ out.push((start, chars.len()));+ out+}++/// Window [start, end) of a single-line value that fits `max` px and keeps the caret in view.+fn visible(f: &mut Fonts, chars: &[char], caret: usize, fs: f32, max: f32) -> (usize, usize) {+ let (mut start, mut w) = (0, 0.0);+ // widen from the caret backwards while it fits, then fill forwards+ let mut s = caret.min(chars.len());+ while s > 0 { let cw = f.cw(chars[s - 1], fs); if w + cw > max { break; } w += cw; s -= 1; }+ start = start.max(s);+ let mut end = start;+ let mut ew = 0.0;+ while end < chars.len() { let cw = f.cw(chars[end], fs); if ew + cw > max { break; } ew += cw; end += 1; }+ (start, end)+}++/// Draws a form control. `caret` is Some(char index) when the control has keyboard focus.+pub fn draw_field(buf: &mut [u32], bw: usize, bh: usize, f: &mut Fonts, fl: &Field, caret: Option<usize>, sc: f32, x: f32, y: f32, w: f32, h: f32) {+ let focused = caret.is_some();+ let (xi, yi, wi, hi) = (x as i32, y as i32, w as i32, h as i32);+ let (border, bg) = match fl.kind {+ FieldKind::Submit => (0x767676, 0xEFEFEF),+ _ => (if focused { 0x1A73E8 } else { 0x767676 }, 0xFFFFFF),+ };+ fill(buf, bw, xi, yi, wi, hi, border);+ fill(buf, bw, xi + 1, yi + 1, wi - 2, hi - 2, bg);+ let fs = (fl.fs * sc).round().max(8.0);+ let base = y + h * 0.5 + fs * 0.35;+ let ink = 0x111111;+ match fl.kind {+ FieldKind::Check => if fl.checked { let tw = f.cw('x', fs); draw_text(buf, bw, bh, f, "x", x + (w - tw) / 2.0, base, fs, ink); },+ FieldKind::Radio => if fl.checked { let tw = f.cw('\u{2022}', fs); draw_text(buf, bw, bh, f, "\u{2022}", x + (w - tw) / 2.0, base, fs, ink); },+ FieldKind::Submit => { let tw = f.width(&fl.label, fs); draw_text(buf, bw, bh, f, &fl.label, x + (w - tw).max(0.0) / 2.0, base, fs, ink); }+ FieldKind::Select => {+ let label = fl.options.get(fl.sel).map_or("", |o| o.1.as_str());+ let chars: Vec<char> = label.chars().collect();+ let (s, e) = visible(f, &chars, 0, fs, w - 30.0);+ draw_text(buf, bw, bh, f, &chars[s..e].iter().collect::<String>(), x + 6.0, base, fs, ink);+ let (cx, cy) = ((x + w - 14.0) as i32, (y + h / 2.0) as i32 - 2);+ for r in 0..4 { fill(buf, bw, cx - (3 - r), cy + r, 2 * (3 - r) + 1, 1, 0x444444); }+ }+ FieldKind::Text | FieldKind::Password => {+ let chars: Vec<char> = if fl.kind == FieldKind::Password { vec!['\u{2022}'; fl.value.chars().count()] } else { fl.value.chars().collect() };+ if chars.is_empty() && !fl.placeholder.is_empty() {+ let ph: Vec<char> = fl.placeholder.chars().collect();+ let (s, e) = visible(f, &ph, 0, fs, w - 12.0);+ draw_text(buf, bw, bh, f, &ph[s..e].iter().collect::<String>(), x + 6.0, base, fs, 0x8A8A8A);+ }+ let c = caret.unwrap_or(chars.len()).min(chars.len());+ let (s, e) = visible(f, &chars, c, fs, w - 12.0);+ draw_text(buf, bw, bh, f, &chars[s..e].iter().collect::<String>(), x + 6.0, base, fs, ink);+ if focused {+ let cx = x + 6.0 + f.width(&chars[s..c].iter().collect::<String>(), fs);+ fill(buf, bw, cx as i32, (y + h * 0.2) as i32, 1, (h * 0.6) as i32, ink);+ }+ }+ FieldKind::TextArea => {+ let chars: Vec<char> = fl.value.chars().collect();+ let line_h = fs * 1.35;+ let rows = (((h - 8.0) / line_h) as usize).max(1);+ let lines = wrap_lines(f, &chars, fs, w - 14.0);+ let c = caret.unwrap_or(chars.len()).min(chars.len());+ let cl = lines.iter().rposition(|&(s, _)| s <= c).unwrap_or(0);+ let first = (cl + 1).saturating_sub(rows);+ if chars.is_empty() && !fl.placeholder.is_empty() { draw_text(buf, bw, bh, f, &fl.placeholder, x + 6.0, y + 4.0 + fs, fs, 0x8A8A8A); }+ for (k, &(s, e)) in lines.iter().enumerate().skip(first).take(rows) {+ let by = y + 4.0 + fs + (k - first) as f32 * line_h;+ draw_text(buf, bw, bh, f, &chars[s..e].iter().collect::<String>(), x + 6.0, by, fs, ink);+ if focused && k == cl {+ let cx = x + 6.0 + f.width(&chars[s..c.min(e).max(s)].iter().collect::<String>(), fs);+ fill(buf, bw, cx as i32, (by - fs * 0.85) as i32, 1, (fs * 1.1) as i32, ink);+ }+ }+ }+ FieldKind::Hidden => {}+ }+}++/// Dropdown list under a select box at (x, y) with rows of height `h`; returns the index of the first row drawn.+pub fn draw_popup(buf: &mut [u32], bw: usize, bh: usize, f: &mut Fonts, fl: &Field, x: f32, y: f32, w: f32, h: f32) -> usize {+ let first = fl.sel.saturating_sub(POPUP_ROWS - 1).min(fl.options.len().saturating_sub(POPUP_ROWS));+ let n = fl.options.len().min(POPUP_ROWS);+ fill(buf, bw, x as i32, y as i32, w as i32, (h * n as f32) as i32 + 2, 0x767676);+ let fs = (h / 1.5).round().max(8.0);+ for (k, o) in fl.options.iter().enumerate().skip(first).take(POPUP_ROWS) {+ let ry = y + 1.0 + (k - first) as f32 * h;+ fill(buf, bw, x as i32 + 1, ry as i32, w as i32 - 2, h as i32, if k == fl.sel { 0xCFE3FC } else { 0xFFFFFF });+ let chars: Vec<char> = o.1.chars().collect();+ let (s, e) = visible(f, &chars, 0, fs, w - 12.0);+ draw_text(buf, bw, bh, f, &chars[s..e].iter().collect::<String>(), x + 6.0, ry + h * 0.5 + fs * 0.35, fs, 0x111111);+ }+ first+}++pub const POPUP_ROWS: usize = 10;++#[cfg(test)]+mod tests {+ use super::*;++ fn fonts() -> Option<Fonts> {+ let data = ["C:\\Windows\\Fonts\\segoeui.ttf", "C:\\Windows\\Fonts\\arial.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"].iter().find_map(|p| std::fs::read(p).ok())?;+ Some(Fonts::new(Font::from_bytes(data, fontdue::FontSettings::default()).ok()?, None))+ }++ #[test]+ fn background_pictures_tile_scale_and_offset_and_gradients_go_radial() {+ let rect = |pic| crate::layout::Rect { x: 2.0, y: 2.0, w: 8.0, h: 4.0, color: 0, r: 0.0, ring: 0.0, node: 0, z: 0, a: 255, grad: None, pic: Some(pic), st: f32::NAN, lim: f32::NAN, grp: 0, scroll: f32::NAN };+ // a 2x1 picture: red left pixel, blue right pixel+ let im = Img { w: 2, h: 1, px: vec![255, 0, 0, 255, 0, 0, 255, 255] };+ let mut buf = vec![0xFFFFFFu32; 12 * 8];+ let tile = crate::layout::Pic { img: 0, w: 4.0, h: 4.0, ox: 0.0, oy: 0.0, rx: true, ry: false };+ draw_pic(&mut buf, 12, 8, &im, &rect(tile), 0.0);+ let px = |x: usize, y: usize| buf[y * 12 + x];+ assert_eq!((px(2, 2), px(4, 2), px(6, 2), px(8, 2)), (0xFF0000, 0x0000FF, 0xFF0000, 0x0000FF), "two tiles side by side, each a scaled 2x1 picture");+ assert_eq!((px(1, 2), px(10, 2), px(2, 7)), (0xFFFFFF, 0xFFFFFF, 0xFFFFFF), "clipped to the rectangle");+ let mut buf = vec![0xFFFFFFu32; 12 * 8];+ let once = crate::layout::Pic { img: 0, w: 4.0, h: 4.0, ox: 4.0, oy: 0.0, rx: false, ry: false };+ draw_pic(&mut buf, 12, 8, &im, &rect(once), 0.0);+ assert_eq!((buf[2 * 12 + 2], buf[2 * 12 + 6], buf[2 * 12 + 8]), (0xFFFFFF, 0xFF0000, 0x0000FF), "no-repeat at an offset draws one tile");+ // radial: the center takes the first stop, the corner the last+ let g = std::sync::Arc::new(crate::css::Grad { angle: 0.0, stops: vec![(0.0, 0xFF0000), (1.0, 0x0000FF)], radial: true, circle: true, at: (0.5, 0.5) });+ let r = crate::layout::Rect { x: 0.0, y: 0.0, w: 20.0, h: 20.0, color: 0, r: 0.0, ring: 0.0, node: 0, z: 0, a: 255, grad: Some(g), pic: None, st: f32::NAN, lim: f32::NAN, grp: 0, scroll: f32::NAN };+ let mut buf = vec![0xFFFFFFu32; 20 * 20];+ draw_rect(&mut buf, 20, 20, &r, 0.0);+ let (c, k) = (buf[10 * 20 + 10], buf[0]);+ assert!((c >> 16 & 255) > 230 && (k & 255) > 200, "center red {c:06x}, corner blue {k:06x}");+ }++ #[test]+ fn clip_restricts_every_painter_to_the_given_rectangle() {+ let mut buf = vec![0xFFFFFFu32; 20 * 10];+ set_clip(Some((5, 2, 10, 6)));+ fill(&mut buf, 20, 0, 0, 20, 10, 0xFF0000);+ draw_rrect(&mut buf, 20, 10, 0.0, 0.0, 20.0, 10.0, 0.0, 0.0, 0x0000FF);+ set_clip(None);+ let inside = |x: usize, y: usize| (5..10).contains(&x) && (2..6).contains(&y);+ for y in 0..10 { for x in 0..20 { assert_eq!(buf[y * 20 + x] != 0xFFFFFF, inside(x, y), "({x},{y})"); } }+ let mut buf = vec![0xFFFFFFu32; 60 * 20];+ let Some(mut f) = Fonts::system() else { return };+ set_clip(Some((0, 0, 20, 20)));+ draw_text(&mut buf, 60, 20, &mut f, "MMMMMMMM", 0.0, 16.0, 16.0, 0);+ set_clip(None);+ assert!((0..20).any(|y| (0..20).any(|x| buf[y * 60 + x] != 0xFFFFFF)) && (0..20).all(|y| (20..60).all(|x| buf[y * 60 + x] == 0xFFFFFF)), "text is cut at the clip edge");+ }++ #[test]+ fn wrapping_and_caret_window() {+ let Some(mut f) = fonts() else { return };+ let chars: Vec<char> = "ab\ncd".chars().collect();+ assert_eq!(wrap_lines(&mut f, &chars, 16.0, 1000.0), vec![(0, 2), (3, 5)]);+ let long: Vec<char> = "x".repeat(200).chars().collect();+ let lines = wrap_lines(&mut f, &long, 16.0, 100.0);+ assert!(lines.len() > 5 && lines.last().unwrap().1 == 200);+ let (s, e) = visible(&mut f, &long, 200, 16.0, 100.0);+ assert!(s > 0 && e == 200);+ }++ #[test]+ fn real_bold_and_italic_faces_have_their_own_metrics() {+ let Some(mut f) = Fonts::system() else { return };+ let (r, b) = (f.width_f("Hello world", 16.0, 0), f.width_f("Hello world", 16.0, BOLD));+ assert!(b > r + 0.5, "bold face is wider: {b} vs {r}");+ let m = f.width_f("Hello", 16.0, MONO);+ assert!((m - f.width_f("HHHHH", 16.0, MONO)).abs() < 0.01, "mono font has equal advances");+ assert!(f.width_f("\u{4e2d}", 16.0, 0) > 8.0, "CJK resolves through a coverage fallback");+ }++ #[test]+ fn complex_scripts_are_shaped_and_rtl_is_detected() {+ let Some(mut f) = Fonts::system() else { return };+ assert!(complex("\u{05e9}\u{05dc}\u{05d5}\u{05dd}") && complex("\u{0633}\u{0644}\u{0627}\u{0645}") && !complex("hello"));+ assert!(is_rtl("\u{05e9}\u{05dc}\u{05d5}\u{05dd}") && !is_rtl("abc \u{05e9}"));+ let arabic = "\u{0627}\u{0644}\u{0639}\u{0631}\u{0628}\u{064a}\u{0629}";+ let w = f.width_f(arabic, 16.0, 0);+ assert!(w > 10.0, "shaped width {w}");+ let sh = f.shape(arabic, 16.0, 0).expect("shaping works with a system font that has Arabic");+ assert!(!sh.glyphs.is_empty() && (sh.width - w).abs() < 0.01);+ let mut buf = vec![0xFFFFFFu32; 200 * 40];+ draw_text_f(&mut buf, 200, 40, &mut f, arabic, 10.0, 28.0, 20.0, 0, 0);+ assert!(buf.iter().any(|&p| p != 0xFFFFFF), "shaped glyphs are drawn");+ }+}diff --git a/plugins/chrome-rs/src/js.rs b/plugins/chrome-rs/src/js.rsnew file mode 100644index 0000000..f1ee1d3--- /dev/null+++ b/plugins/chrome-rs/src/js.rs@@ -0,0 +1,446 @@+// JavaScript via QuickJS. The DOM lives in prelude.js; we ship it the parsed tree as JSON and run the page's scripts.+// Two modes: `run` (offline/tests: scripts and virtual-time timers, then read the DOM back) and `start`, a live session on+// its own thread that keeps the runtime alive after load: real-time timers, UI events, form values, layout boxes, and+// every DOM change is serialized back (throttled) so the page can be re-rendered.+// shortcut: no capture phase, no hover/mouse-move events, MutationObserver is a stub, no workers/modules; the whole DOM is+// re-serialized after each burst of activity (fine for typical pages, costly for 10k+ nodes).+use crate::{dom::{self, Dom}, load::fetch_req, render::resolve, store};+use rquickjs::{context::EvalOptions, loader::{Loader, Resolver}, module::Declared, Context, Ctx, Function, Module, Runtime, Value};+use std::{+ sync::{atomic::{AtomicU64, AtomicUsize, Ordering}, mpsc, Arc, Mutex},+ time::{Duration, Instant},+};++const PRELUDE: &str = include_str!("prelude.js");+const IDLE: u64 = u64::MAX;++/// A page script: classic, or an ES module whose `name` (its URL) anchors relative imports.+#[derive(Clone)]+pub struct Script { pub module: bool, pub name: String, pub code: String }++impl Script {+ pub fn classic(code: impl Into<String>) -> Script { Script { module: false, name: String::new(), code: code.into() } }+ /// A `<script type="importmap">`: it is not run, it rewrites module specifiers (bare names like `react`).+ pub fn importmap(code: impl Into<String>) -> Script { Script { module: false, name: IMPORTMAP.into(), code: code.into() } }+}++/// Modules one page may import (an app bundle of a framework such as Nuxt splits into a few hundred chunks).+const MAX_MODULES: usize = 400;+const IMPORTMAP: &str = "#importmap";+type ImportMap = Arc<Mutex<Vec<(String, String)>>>;++/// Module specifiers are URLs resolved against the importing module.+struct WebResolver { map: ImportMap, page_url: String }++impl Resolver for WebResolver {+ fn resolve<'js>(&mut self, _: &Ctx<'js>, base: &str, name: &str, _: Option<rquickjs::loader::ImportAttributes<'js>>) -> rquickjs::Result<String> {+ let map = self.map.lock().map(|m| m.clone()).unwrap_or_default();+ Ok(map_specifier(&map, &self.page_url, base, name))+ }+}++/// An import map entry wins: exact name, or a `prefix/` entry (shortcut: no `scopes`, first match wins).+fn map_specifier(map: &[(String, String)], page_url: &str, base: &str, name: &str) -> String {+ for (k, v) in map {+ if k == name { return resolve(page_url, v); }+ if k.ends_with('/') && name.starts_with(k.as_str()) { return resolve(page_url, &format!("{v}{}", &name[k.len()..])); }+ }+ resolve(base, name)+}++/// Imports are fetched synchronously (same rules as fetch(): CORS for other origins, file: only from file: pages).+struct WebLoader { page_url: String, fetched: usize }++impl Loader for WebLoader {+ fn load<'js>(&mut self, ctx: &Ctx<'js>, name: &str, _: Option<rquickjs::loader::ImportAttributes<'js>>) -> rquickjs::Result<Module<'js, Declared>> {+ self.fetched += 1;+ let fail = || rquickjs::Error::new_loading(name);+ if self.fetched > MAX_MODULES { return Err(fail()); }+ let (status, body, _) = fetch_req(name, &self.page_url, "GET", "", "").filter(|_| name.starts_with("http") || name.starts_with("file:") && self.page_url.starts_with("file:")).ok_or_else(fail)?;+ if status >= 400 { return Err(fail()); }+ let m = Module::declare(ctx.clone(), name, body)?;+ m.meta()?.set("url", name)?; // import.meta.url (bundlers derive their public path from it)+ Ok(m)+ }+}++/// Takes the pending exception; `CHROME_RS_JSERR=1` prints it, so a page that renders blank can be diagnosed.+fn report(c: &rquickjs::Ctx) {+ let e = c.catch();+ if std::env::var_os("CHROME_RS_JSERR").is_some() {+ let m = e.as_object().map(|o| format!("{} | {}", o.get::<_, String>("message").unwrap_or_default(), o.get::<_, String>("stack").unwrap_or_default())).unwrap_or_else(|| format!("{e:?}"));+ eprintln!("JSERR {}", m.lines().take(12).collect::<Vec<_>>().join(" / "));+ }+}++fn drain(rt: &Runtime) { while rt.is_job_pending() { if rt.execute_pending_job().is_err() { break; } } }++/// A QuickJS runtime with the prelude loaded. `deadline` is the CPU-time (ms, network waits excluded) at which scripts are interrupted.+struct Vm { rt: Runtime, ctx: Context, deadline: Arc<AtomicU64>, t0: Instant, net_ms: Arc<AtomicU64>, origin: String, ls0: String, imports: ImportMap }++impl Vm {+ fn new(json: String, url: &str, max_fetches: usize, nav: Arc<dyn Fn(String) + Send + Sync>) -> Option<Vm> {+ let rt = Runtime::new().ok()?;+ rt.set_memory_limit(256 << 20);+ rt.set_max_stack_size(1 << 20);+ let deadline = Arc::new(AtomicU64::new(IDLE));+ let net_ms = Arc::new(AtomicU64::new(0)); // time spent waiting on the network does not count against the CPU budget+ let t0 = Instant::now();+ let (dl, net) = (deadline.clone(), net_ms.clone());+ rt.set_interrupt_handler(Some(Box::new(move || (t0.elapsed().as_millis() as u64).saturating_sub(net.load(Ordering::Relaxed)) > dl.load(Ordering::Relaxed))));+ let imports: ImportMap = Arc::default();+ rt.set_loader(WebResolver { map: imports.clone(), page_url: url.to_string() }, WebLoader { page_url: url.to_string(), fetched: 0 });+ let ctx = Context::full(&rt).ok()?;+ let (base, fetches) = (url.to_string(), Arc::new(AtomicUsize::new(0)));+ let origin = store::origin_of(url);+ let ls0 = store::ls_load(&origin);+ let (cookie_url, page_url, net2) = (url.to_string(), url.to_string(), net_ms.clone());+ ctx.with(|c| -> rquickjs::Result<()> {+ let g = c.globals();+ g.set("__dom_json", json)?;+ g.set("__url", url)?;+ // console.error/warn and exceptions swallowed by timers: only visible with CHROME_RS_JSERR=1+ let verbose = std::env::var_os("CHROME_RS_JSERR").is_some();+ g.set("__log", Function::new(c.clone(), move |m: String| { if verbose { eprintln!("JSLOG {}", m.chars().take(400).collect::<String>()); } })?)?;+ g.set("__ls", ls0.clone())?;+ let cu = cookie_url.clone();+ g.set("__cookie_get", Function::new(c.clone(), move || store::cookie_header(&cu, false))?)?;+ g.set("__cookie_set", Function::new(c.clone(), move |h: String| store::set_cookie(&cookie_url, &h, true))?)?;+ g.set("__parse", Function::new(c.clone(), |h: String| dom::fragment_json(&h))?)?;+ g.set("__resolve", Function::new(c.clone(), |b: String, r: String| resolve(&b, &r))?)?;+ g.set("__navigate", Function::new(c.clone(), move |u: String| nav(u))?)?;+ g.set("__fetch", Function::new(c.clone(), move |u: String, method: String, body: String, ctype: String| -> String {+ let full = resolve(&base, &u);+ if !(full.starts_with("http") || full.starts_with("file:") && page_url.starts_with("file:")) || fetches.fetch_add(1, Ordering::Relaxed) >= max_fetches { return r#"{"status":0,"body":""}"#.into(); }+ let t = Instant::now();+ let r = fetch_req(&full, &page_url, &method, &body, &ctype);+ net2.fetch_add(t.elapsed().as_millis() as u64, Ordering::Relaxed);+ let (status, body, ctype) = r.unwrap_or((0, String::new(), String::new()));+ serde_json::json!({ "status": status, "body": body, "ctype": ctype }).to_string()+ })?)?;+ // a prelude that fails to load switches all page JavaScript off: say why when CHROME_RS_JSERR is set+ if let Err(e) = c.eval::<Value, _>(PRELUDE) { report(&c); return Err(e); }+ c.eval::<Value, _>("var __cs = null;")?;+ // corpus replays must be repeatable: shuffled sponsor lists, random ids and the like come out the same every time+ if crate::load::replaying() { c.eval::<Value, _>("Math.random = (() => { let s = 12345; return () => (s = (s * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff; })();")?; }+ Ok(())+ }).ok()?;+ Some(Vm { rt, ctx, deadline, t0, net_ms, origin, ls0, imports })+ }++ fn cpu(&self) -> u64 { (self.t0.elapsed().as_millis() as u64).saturating_sub(self.net_ms.load(Ordering::Relaxed)) }+ fn arm(&self, ms: u64) { self.deadline.store(self.cpu() + ms, Ordering::Relaxed); }+ fn disarm(&self) { self.deadline.store(IDLE, Ordering::Relaxed); }+ fn eval(&self, src: &str) { self.ctx.with(|c| if c.eval::<Value, _>(src).is_err() { report(&c); }); drain(&self.rt); }+ fn run_script(&self, s: &Script) {+ if s.name == IMPORTMAP {+ if let (Ok(v), Ok(mut m)) = (serde_json::from_str::<serde_json::Value>(&s.code), self.imports.lock()) {+ m.extend(v["imports"].as_object().into_iter().flatten().filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string()))));+ }+ return;+ }+ if !s.module {+ // document.currentScript: a <script> element carrying the src, which bundlers (Turbopack, webpack) read to find their chunks+ let name = serde_json::to_string(&s.name).unwrap_or_default();+ self.eval(&format!("__cs = {name};"));+ // page scripts are sloppy-mode JavaScript: rquickjs evals in strict mode by default, where `OSM = {}` without `var` throws+ self.ctx.with(|c| { let mut o = EvalOptions::default(); o.strict = false; if c.eval_with_options::<Value, _>(s.code.as_str(), o).is_err() { report(&c); } });+ drain(&self.rt);+ return self.eval("__cs = null;");+ }+ self.ctx.with(|c| {+ let run = || -> rquickjs::Result<()> {+ let m = Module::declare(c.clone(), s.name.as_str(), s.code.as_str())?;+ m.meta()?.set("url", s.name.as_str())?;+ let (_, p) = m.eval()?;+ p.finish::<Value>().map(|_| ())+ };+ if run().is_err() { report(&c); }+ });+ drain(&self.rt);+ }+ fn eval_bool(&self, src: &str) -> bool { let r = self.ctx.with(|c| c.eval::<bool, _>(src).unwrap_or_else(|_| { let _ = c.catch(); false })); drain(&self.rt); r }+ fn eval_num(&self, src: &str) -> f64 { let r = self.ctx.with(|c| c.eval::<f64, _>(src).unwrap_or_else(|_| { let _ = c.catch(); -1.0 })); drain(&self.rt); r }+ fn serialize(&self) -> Option<String> { self.ctx.with(|c| c.eval::<String, _>("__serialize()").ok()) }++ /// Persists localStorage when the page changed it.+ fn save_ls(&mut self) {+ let ls1 = self.ctx.with(|c| c.eval::<String, _>("__ls_dump()").ok());+ if let Some(ls1) = ls1.filter(|l| *l != self.ls0 && self.origin.starts_with("http")) { store::ls_save(&self.origin, &ls1); self.ls0 = ls1; }+ }++ /// Page scripts, DOMContentLoaded, load, then timers in virtual time (`live`: only the first second, the rest stays queued).+ fn initial_phase(&self, scripts: &[Script], live: bool) {+ self.arm(4000);+ for s in scripts { self.run_script(s); }+ self.eval("__fire('DOMContentLoaded')");+ self.eval("__fire('load')");+ let tick = if live { "__tick(true)" } else { "__tick()" };+ for _ in 0..300 { if !self.eval_bool(tick) { break; } }+ }+}++fn exec(json: String, scripts: &[Script], url: &str) -> Option<String> {+ let mut vm = Vm::new(json, url, 12, Arc::new(|_| {}))?;+ vm.initial_phase(scripts, false);+ vm.disarm();+ vm.save_ls();+ vm.serialize()+}++/// Runs `scripts` (document order) against `dom`; on any failure the DOM is left untouched.+pub fn run(dom: &mut Dom, scripts: &[Script], url: &str) {+ let Some(&html) = dom.nodes[0].kids.first() else { return };+ let Some(out) = exec(dom.to_json(html).to_string(), scripts, url) else { return };+ if let Some(d) = serde_json::from_str(&out).ok().and_then(|v| Dom::from_json(&v)) { *dom = d; }+}++/// What the UI can ask the live page to do. `node` is a Dom node id of the last serialization the UI saw.+enum Cmd {+ Event { node: usize, kind: String, init: String, reply: Option<mpsc::Sender<bool>> },+ Value { node: usize, value: String, checked: Option<bool> },+ Resize { w: u32, h: u32 },+ Scroll(f32),+ Boxes(String),+}++/// Sender side of a live session; cloning is cheap, dropping the last clone ends the session thread.+#[derive(Clone)]+pub struct Handle { tx: mpsc::Sender<Cmd> }++impl Handle {+ /// Dispatches a bubbling event and waits (at most 400 ms) to learn whether a handler called preventDefault().+ pub fn event(&self, node: usize, kind: &str, init: &str) -> bool {+ let (rtx, rrx) = mpsc::channel();+ self.tx.send(Cmd::Event { node, kind: kind.into(), init: init.into(), reply: Some(rtx) }).is_ok() && rrx.recv_timeout(Duration::from_millis(400)).unwrap_or(false)+ }+ /// Fire-and-forget event.+ pub fn post(&self, node: usize, kind: &str, init: &str) { let _ = self.tx.send(Cmd::Event { node, kind: kind.into(), init: init.into(), reply: None }); }+ /// Mirrors what the user typed/checked into the page's DOM (no event is fired).+ pub fn value(&self, node: usize, value: &str, checked: Option<bool>) { let _ = self.tx.send(Cmd::Value { node, value: value.into(), checked }); }+ pub fn resize(&self, w: u32, h: u32) { let _ = self.tx.send(Cmd::Resize { w, h }); }+ /// The user scrolled the page to `y` CSS px: updates scrollY and fires `scroll`.+ pub fn scroll(&self, y: f32) { let _ = self.tx.send(Cmd::Scroll(y)); }+ /// Layout boxes `[[node, x, y, w, h], ...]` for getBoundingClientRect() and friends.+ pub fn boxes(&self, json: String) { let _ = self.tx.send(Cmd::Boxes(json)); }+}++/// Starts a live session. `on_update` receives every changed DOM serialization (JSON, same shape as `Dom::to_json`).+/// Returns the handle and the serialization after the load phase; None when the runtime could not start.+pub fn start(dom_json: String, scripts: Vec<Script>, url: String, on_update: Box<dyn Fn(String) + Send>, nav: Arc<dyn Fn(String) + Send + Sync>) -> Option<(Handle, String)> {+ let (tx, rx) = mpsc::channel::<Cmd>();+ let (itx, irx) = mpsc::channel::<Option<String>>();+ std::thread::Builder::new().stack_size(16 << 20).spawn(move || live_main(dom_json, scripts, url, rx, itx, on_update, nav)).ok()?;+ let first = irx.recv_timeout(Duration::from_secs(40)).ok()??;+ Some((Handle { tx }, first))+}++fn live_main(dom_json: String, scripts: Vec<Script>, url: String, rx: mpsc::Receiver<Cmd>, itx: mpsc::Sender<Option<String>>, on_update: Box<dyn Fn(String) + Send>, nav: Arc<dyn Fn(String) + Send + Sync>) {+ let Some(mut vm) = Vm::new(dom_json, &url, 400, nav) else { let _ = itx.send(None); return };+ vm.initial_phase(&scripts, true);+ vm.disarm();+ vm.save_ls();+ let Some(first) = vm.serialize() else { let _ = itx.send(None); return };+ let _ = itx.send(Some(first.clone()));+ let (base, live_start) = (vm.eval_num("__now()"), Instant::now());+ let clock = || base + live_start.elapsed().as_millis() as f64;+ let (mut last, mut last_sent, mut dirty) = (first, Instant::now(), false);+ let mut next = vm.eval_num("__next_delay()");+ const THROTTLE: Duration = Duration::from_millis(60);+ loop {+ let mut wait: Option<Duration> = if next >= 0.0 { Some(Duration::from_millis(next.max(1.0) as u64)) } else { None };+ if dirty { let left = THROTTLE.saturating_sub(last_sent.elapsed()).max(Duration::from_millis(1)); wait = Some(wait.map_or(left, |w| w.min(left))); }+ let cmd = match wait {+ None => match rx.recv() { Ok(c) => Some(c), Err(_) => break },+ Some(w) => match rx.recv_timeout(w) { Ok(c) => Some(c), Err(mpsc::RecvTimeoutError::Timeout) => None, Err(_) => break },+ };+ vm.arm(2000); // one burst of script work may use two seconds of CPU+ vm.eval(&format!("__setnow({})", clock()));+ if let Some(c) = cmd {+ dirty = true;+ match c {+ Cmd::Event { node, kind, init, reply } => {+ let prevented = vm.eval_bool(&format!("__dispatch({node},{},{})", serde_json::json!(kind), serde_json::json!(init)));+ if let Some(r) = reply { let _ = r.send(prevented); }+ }+ Cmd::Value { node, value, checked } => vm.eval(&format!("__setvalue({node},{},{})", serde_json::json!(value), checked.map_or("null".to_string(), |c| c.to_string()))),+ Cmd::Resize { w, h } => vm.eval(&format!("__resize({w},{h})")),+ Cmd::Scroll(y) => vm.eval(&format!("__scrolled({y})")),+ Cmd::Boxes(json) => vm.eval(&format!("__boxes({json})")),+ }+ }+ next = vm.eval_num(&format!("__run_due({})", clock()));+ if vm.eval_num("__ran()") > 0.0 { dirty = true; }+ vm.disarm();+ if dirty && last_sent.elapsed() >= THROTTLE {+ dirty = false;+ last_sent = Instant::now();+ vm.save_ls();+ if let Some(s) = vm.serialize() { if s != last { on_update(s.clone()); last = s; } }+ }+ }+}++#[cfg(test)]+mod tests {+ #[test]+ fn import_map_rewrites_bare_specifiers() {+ let map = vec![("react".to_string(), "https://cdn.test/react-1.js".to_string()), ("lib/".to_string(), "/vendor/lib/".to_string())];+ assert_eq!(map_specifier(&map, "https://a.com/p", "https://a.com/x/m.js", "react"), "https://cdn.test/react-1.js");+ assert_eq!(map_specifier(&map, "https://a.com/p", "https://a.com/x/m.js", "lib/dom.js"), "https://a.com/vendor/lib/dom.js");+ assert_eq!(map_specifier(&map, "https://a.com/p", "https://a.com/x/m.js", "./other.js"), "https://a.com/x/other.js");+ }++ use super::*;++ fn run_html(html: &str, js: &[&str]) -> Dom {+ let mut d = dom::parse(html, true);+ run(&mut d, &js.iter().map(|s| Script::classic(*s)).collect::<Vec<_>>(), "https://a.com/p?q=1");+ d+ }++ #[test]+ fn custom_elements_links_and_forms() {+ let d = run_html("<my-box id=pre label=L1>x</my-box><a id=l href='/d/x.html?q=1#top'>l</a><form id=f><input name=a><select name=s><option>o</option></select></form><p id=o></p>", &["+ var log = [];+ class MyBox extends HTMLElement {+ static get observedAttributes() { return ['label']; }+ constructor() { super(); log.push('ctor'); }+ connectedCallback() { log.push('conn ' + this.id); }+ attributeChangedCallback(n, o, v) { log.push(n + ':' + o + '>' + v); }+ }+ customElements.define('my-box', MyBox);+ var e = document.createElement('my-box'); e.id = 'new'; document.body.appendChild(e);+ var a = document.getElementById('l'), f = document.getElementById('f');+ log.push(a.href, a.pathname, a.search, a.hash, f.elements.length, f.elements.s.options.length, document.getElementById('pre') instanceof MyBox);+ document.getElementById('o').textContent = log.join('|');+ "]);+ assert_eq!(d.text_content(d.find("p").unwrap()), "ctor|label:null>L1|conn pre|ctor|conn new|https://a.com/d/x.html?q=1#top|/d/x.html|?q=1|#top|2|1|true");+ }++ #[test]+ fn get_computed_style_runs_a_small_cascade() {+ let d = run_html("<style>.hid{display:none} #m{display:block !important} div p{color:blue} .box{width:50%}</style><div class=wrap style='visibility:hidden'><p id=p class=hid>x</p><span id=s>y</span></div><main id=m class=hid></main><section id=sec></section><output id=o></output>", &[+ "var c = id => getComputedStyle(document.getElementById(id)); var r = [c('p').display, c('m').display, c('sec').display, c('s').display, c('p').color, c('s').visibility, c('p').getPropertyValue('display'), c('o').opacity, document.createElement('i') && getComputedStyle(document.body).display];+ document.getElementById('o').textContent = r.join('|');",+ ]);+ assert_eq!(d.text_content(d.find("output").unwrap()), "none|block|block|inline|blue|hidden|none|1|block");+ }++ #[test]+ fn scripts_mutate_dom() {+ let d = run_html("<p id=a>old</p><ul id=l></ul>", &[+ "document.getElementById('a').textContent = 'new ' + location.hostname;",+ "var l = document.querySelector('#l'); for (var i=0;i<2;i++){ var li=document.createElement('li'); li.className='i'+i; li.textContent=i; l.appendChild(li); }",+ "document.title='T'; document.body.insertAdjacentHTML('beforeend','<b class=x>bold</b>');",+ "document.querySelector('.i1').style.color='red';",+ ]);+ assert_eq!(d.text_content(d.find("p").unwrap()), "new a.com");+ assert_eq!(d.nodes.iter().filter(|n| n.tag == "li").count(), 2);+ assert_eq!(d.text_content(d.find("title").unwrap()), "T");+ assert_eq!(d.text_content(d.find("b").unwrap()), "bold");+ let li = d.descendants().into_iter().filter(|&i| d.nodes[i].tag == "li").nth(1).unwrap();+ assert_eq!(d.attr(li, "style"), Some("color:red"));+ }++ #[test]+ fn events_timers_promises_and_errors() {+ let d = run_html("<div id=o></div>", &[+ "throw new Error('boom');",+ "var log=[]; document.addEventListener('DOMContentLoaded',()=>log.push('dcl')); window.addEventListener('load',()=>log.push('load'));",+ "setTimeout(()=>log.push('t2'),20); setTimeout(()=>log.push('t1'),10); Promise.resolve().then(()=>log.push('p'));",+ "window.addEventListener('load',()=>setTimeout(()=>{document.getElementById('o').textContent=log.join(',')},100));",+ ]);+ assert_eq!(d.text_content(d.find("div").unwrap()), "p,dcl,load,t1,t2");+ }++ #[test]+ fn document_cookie_reads_and_writes_the_jar() {+ let d = run_html("<p id=o></p>", &["document.cookie='zz=1; path=/'; document.getElementById('o').textContent = document.cookie;"]);+ assert_eq!(d.text_content(d.find("p").unwrap()), "zz=1");+ assert!(store::cookie_header("https://a.com/p", false).contains("zz=1"));+ }++ #[test]+ fn web_apis_url_encoding_forms_history() {+ let d = run_html("<form id=f><input name=a value='x y'><input type=checkbox name=c checked value=on><input type=checkbox name=n><select name=s><option value=1>One<option value=2 selected>Two</select><textarea name=t>hi</textarea><input type=submit name=go value=Go></form><div id=o></div>", &[r#"+ const out = [];+ const u = new URL('../b/c?x=1&y=a%20b#h', 'https://u:[email protected]:8080/a/d/e');+ out.push(u.href, u.origin, u.searchParams.get('y'));+ u.searchParams.append('z', 'q r'); out.push(u.search);+ out.push(new URLSearchParams({ k: 'v w', e: '' }).toString(), URL.canParse('nope'));+ out.push(btoa('hello'), atob('aGVsbG8='), new TextDecoder().decode(new TextEncoder().encode('héllo €')));+ out.push(new URLSearchParams(new FormData(document.getElementById('f'))).toString());+ history.pushState({ n: 1 }, '', '/next?q=2'); out.push(location.pathname + location.search, JSON.stringify(history.state), history.length);+ out.push(typeof performance.now(), typeof queueMicrotask, crypto.randomUUID().length, structuredClone({ a: [1] }).a[0]);+ queueMicrotask(() => out.push('micro'));+ fetch('ftp://nope').then(() => out.push('ok'), () => out.push('rejected')).then(() => { document.getElementById('o').textContent = out.join('|'); });+ "#]);+ assert_eq!(d.text_content(d.find("div").unwrap()),+ "https://u:[email protected]:8080/a/b/c?x=1&y=a%20b#h|https://example.com:8080|a b|?x=1&y=a+b&z=q+r|k=v+w&e=|false|aGVsbG8=|hello|héllo €|a=x+y&c=on&s=2&t=hi|/next?q=2|{\"n\":1}|2|number|function|36|1|micro|rejected");+ }++ #[test]+ fn infinite_loop_is_cut_off_and_dom_survives() {+ let t = Instant::now();+ let d = run_html("<p>keep</p>", &["while(true){}"]);+ assert!(t.elapsed() < Duration::from_secs(8));+ assert_eq!(d.text_content(d.find("p").unwrap()), "keep");+ }++ fn wait_for(rx: &mpsc::Receiver<String>, pred: impl Fn(&Dom) -> bool, ms: u64) -> Option<Dom> {+ let end = Instant::now() + Duration::from_millis(ms);+ while Instant::now() < end {+ if let Ok(s) = rx.recv_timeout(Duration::from_millis(50)) {+ if let Some(d) = serde_json::from_str(&s).ok().and_then(|v| Dom::from_json(&v)) { if pred(&d) { return Some(d); } }+ }+ }+ None+ }++ #[test]+ fn live_session_runs_real_time_timers_events_and_values() {+ let d = dom::parse("<p id=c>0</p><button id=b>go</button><input id=i name=q value=a><p id=o></p>", true);+ let html = d.nodes[0].kids[0];+ let script = r#"+ var n = 0, el = id => document.getElementById(id);+ setInterval(() => { n++; el('c').textContent = String(n); }, 40);+ setTimeout(() => { el('o').textContent = 'late'; }, 1500);+ el('b').addEventListener('click', e => { e.preventDefault(); el('b').textContent = 'clicked:' + e.type; });+ el('i').addEventListener('input', e => { el('o').textContent = 'typed:' + e.target.value; });+ window.addEventListener('resize', () => { el('o').textContent = 'resized:' + innerWidth; });+ "#;+ let (utx, urx) = mpsc::channel();+ let (h, first) = start(d.to_json(html).to_string(), vec![Script::classic(script)], "https://a.com/".into(), Box::new(move |s| { let _ = utx.send(s); }), Arc::new(|_| {})).unwrap();+ let d0 = Dom::from_json(&serde_json::from_str(&first).unwrap()).unwrap();+ let n0: u32 = d0.text_content(d0.find("p").unwrap()).parse().unwrap();+ assert!((20..=26).contains(&n0), "first second of the interval ran in virtual time: {n0}");+ // the interval keeps running in real time after load+ let d1 = wait_for(&urx, |d| d.text_content(d.find("p").unwrap()).parse::<u32>().is_ok_and(|n| n > n0 + 3), 3000).expect("interval kept ticking");+ let button = d1.find("button").unwrap();+ assert!(h.event(button, "click", "{}"), "preventDefault is reported back");+ wait_for(&urx, |d| d.text_content(d.find("button").unwrap()) == "clicked:click", 3000).expect("click handler ran");+ // typed text is mirrored into the DOM, then the input event sees it+ let input = d1.find("input").unwrap();+ h.value(input, "hello", None);+ h.post(input, "input", "{}");+ wait_for(&urx, |d| d.text_content(d.nodes[d.find("p").unwrap()].kids.len().checked_sub(0).map_or(0, |_| d.descendants().into_iter().filter(|&i| d.nodes[i].tag == "p").nth(1).unwrap())) == "typed:hello", 3000).expect("input event saw the value");+ h.resize(640, 480);+ wait_for(&urx, |d| d.text_content(d.descendants().into_iter().filter(|&i| d.nodes[i].tag == "p").nth(1).unwrap()) == "resized:640", 3000).expect("resize event");+ }++ #[test]+ fn layout_boxes_feed_getboundingclientrect() {+ let d = dom::parse("<div id=a>x</div><p id=o></p>", true);+ let html = d.nodes[0].kids[0];+ let (utx, urx) = mpsc::channel();+ let (h, first) = start(d.to_json(html).to_string(), vec![Script::classic("window.addEventListener('click', () => { var r = document.getElementById('a').getBoundingClientRect(); document.getElementById('o').textContent = [r.left, r.top, r.width, r.height, document.getElementById('a').offsetHeight].join(','); });")], "https://a.com/".into(), Box::new(move |s| { let _ = utx.send(s); }), Arc::new(|_| {})).unwrap();+ // node ids are those of the serialization the UI saw (pre-order), not of the parsed DOM+ let d0 = Dom::from_json(&serde_json::from_str(&first).unwrap()).unwrap();+ let a = d0.descendants().into_iter().find(|&i| d0.attr(i, "id") == Some("a")).unwrap();+ h.boxes(format!("[[{a}, 10, 20, 300.5, 40]]"));+ h.post(a, "click", "{}");+ wait_for(&urx, |d| d.text_content(d.find("p").unwrap()) == "10,20,300.5,40,40", 3000).expect("boxes visible to scripts");+ }+}+diff --git a/plugins/chrome-rs/src/layout.rs b/plugins/chrome-rs/src/layout.rsnew file mode 100644index 0000000..6c2238d--- /dev/null+++ b/plugins/chrome-rs/src/layout.rs@@ -0,0 +1,1258 @@+// Flow layout: items -> positioned text/pictures/controls plus background rectangles.+// Blocks narrow the line box (margins, padding, borders, width/max-width, auto-centering); tables get real columns;+// floats sit at the left/right edge while following lines wrap around them.+// Also: inline-block atoms, row flexbox (grow/shrink/basis/wrap/gap/justify/align), relative/absolute positioning.+// shortcut: `bottom` of the page-level containing block is+// ignored, z-index is a paint layer per positioned box (no full stacking contexts), flex stretch = start; box insets are not counted in column min/max widths;+// a float that does not fit beside earlier floats drops below them instead of splitting lines.+use crate::{css::{BgSize, Grad, Len, Shadow, Track}, gfx::Fonts, render::{AbsSpec, BgPaint, FlexSpec, FloatSpec, GridSpec, Item, Table}};+use std::{cell::Cell, sync::Arc};++pub const MARGIN: f32 = 16.0;++/// Layer of boxes that stay in the viewport while the page scrolls (`position: fixed`); painted last, at screen coordinates.+pub const FIXED_Z: i64 = 16383 * ZK * ZK * ZK;++// A paint key is up to four base-32768 digits, outermost stacking context first, so an element inside a context with z-index 5+// can never paint above a sibling context with z-index 6 however large its own z-index is. In-flow content has digit 0,+// a positioned box 4*z+2 (auto sits above in-flow text, negative below it), `fixed` adds the digit 16383 on top.+const ZK: i64 = 32768;++fn zdigit(z: i32) -> i64 { 4 * z.clamp(-4000, 4000) as i64 + 2 }++/// Puts an item with key `q` inside a stacking context whose own digit is `d`: its digits move one place down, `d` becomes the top one.+fn zwrap(q: i64, d: i64) -> i64 { d * ZK * ZK * ZK + (q + ZK / 2).div_euclid(ZK) }++// shortcut: the viewport height for `position: fixed` offsets is a thread-local set by `layout_vh`; pass it down if layout ever runs on several threads at once+thread_local! { static VH: Cell<f32> = const { Cell::new(720.0) }; static GRP: Cell<u32> = const { Cell::new(0) }; }++fn next_grp() -> u32 { GRP.with(|g| { g.set(g.get() + 1); g.get() }) }++/// Text run, picture or form control placed on a line. For pictures and controls `size` is the height.+pub struct Placed {+ pub x: f32, pub base: f32, pub size: f32, pub w: f32, pub text: String, pub link: Option<usize>,+ pub color: u32, pub face: u16, pub ul: bool, pub img: Option<usize>, pub field: Option<usize>,+ pub lh: f32,+ pub z: i64, // paint key (see `zwrap`)+ pub lim: f32, // sticky: how far the box may travel below its pin point (NAN = unlimited; negative = still open while laying out)+ pub grp: u32, // scroll container this item scrolls with (0 = none)+ pub ls: f32, // letter-spacing in device px+ pub dy: f32, // baseline shift up in device px (vertical-align: super/sub)+ pub st: f32, // scroll offset (device px) from which this item is pinned to the viewport (position: fixed = 0, sticky); NAN = never+ pub node: usize, // DOM node the item belongs to (0 = none)+ /// inline-block content (placed text/rects relative to the atom's top-left), flattened into the output when the line is flushed+ pub blk: Option<Box<(Vec<Placed>, Vec<Rect>)>>,+}++/// Filled rectangle; `r` > 0 rounds the corners, `ring` > 0 draws only an outline of that thickness.+pub struct Rect { pub x: f32, pub y: f32, pub w: f32, pub h: f32, pub color: u32, pub r: f32, pub ring: f32, pub node: usize, pub z: i64, pub a: u8, pub grad: Option<Arc<Grad>>, pub pic: Option<Pic>, pub st: f32,+ pub lim: f32, pub grp: u32,+ /// a scroll container's box (invisible): `grp` is its id and this the height of its content; NAN for every other rectangle+ pub scroll: f32 }++/// A background image placed inside its rectangle: tile size and offset in device px, repeat per axis.+#[derive(Clone, Copy)]+pub struct Pic { pub img: usize, pub w: f32, pub h: f32, pub ox: f32, pub oy: f32, pub rx: bool, pub ry: bool }++struct Out { placed: Vec<Placed>, rects: Vec<Rect>, pw: f32 }+impl Out { fn new(pw: f32) -> Out { Out { placed: vec![], rects: vec![], pw } } }++struct Region { node: usize, radius: f32, min_h: f32, pt: f32, pb: f32, bb: bool, scroll: bool, bgimg: Option<Arc<BgPaint>>, r0: usize, p0: usize, a: f32, clip: bool, shadow: Option<Shadow>, grad: Option<Arc<Grad>>, bg: Option<u32>, top: Option<f32>, x0: f32, x1: f32, saved: (f32, f32), borders: [Option<(f32, u32)>; 4], bw: [f32; 4] }++/// An active float: text must stay clear of `edge` until `bottom`.+struct Fl { right_side: bool, edge: f32, bottom: f32 }++fn px(size: f32, sc: f32) -> f32 { (size * sc).round().max(1.0) }++fn resolve(l: Len, avail: f32, sc: f32) -> f32 {+ match l { Len::Px(p) => p * sc, Len::Pct(p) => p / 100.0 * avail, Len::Mix(pc, p) => pc / 100.0 * avail + p * sc }+}++pub fn layout(items: &[Item], width: f32, sc: f32, f: &mut Fonts) -> (Vec<Placed>, Vec<Rect>, f32) { layout_vh(items, width, sc, 720.0 * sc, f) }++/// Like `layout`, with the viewport height (device px) that `position: fixed` offsets from the bottom refer to.+/// Output is sorted by paint layer (z, stable), so within one layer document order is kept.+pub fn layout_vh(items: &[Item], width: f32, sc: f32, vh: f32, f: &mut Fonts) -> (Vec<Placed>, Vec<Rect>, f32) {+ VH.with(|v| v.set(vh));+ GRP.with(|g| g.set(0));+ let m = MARGIN * sc;+ let mut out = Out::new(width);+ let end = block(items, m, width - m, m, sc, f, &mut out);+ out.placed.sort_by_key(|p| p.z);+ out.rects.sort_by_key(|r| r.z);+ (out.placed, out.rects, end + m)+}++/// Distinct paint keys in ascending order (always includes 0) with the ranges of `rects` and `placed` that carry each+/// (both are sorted by key): paint each layer's rectangles, then its text.+pub fn layers(placed: &[Placed], rects: &[Rect]) -> Vec<(i64, std::ops::Range<usize>, std::ops::Range<usize>)> {+ let mut z: Vec<i64> = placed.iter().map(|p| p.z).chain(rects.iter().map(|r| r.z)).chain([0]).collect();+ z.sort_unstable();+ z.dedup();+ z.into_iter().map(|k| (k, rects.partition_point(|r| r.z < k)..rects.partition_point(|r| r.z <= k), placed.partition_point(|p| p.z < k)..placed.partition_point(|p| p.z <= k))).collect()+}++/// A scroll container found in a layout: where its box is, and how tall its content is (device px).+#[derive(Clone, Copy)]+pub struct Group { pub node: usize, pub x: f32, pub y: f32, pub w: f32, pub h: f32, pub content_h: f32 }++pub fn groups(rects: &[Rect]) -> std::collections::HashMap<u32, Group> {+ rects.iter().filter(|r| r.scroll.is_finite()).map(|r| (r.grp, Group { node: r.node, x: r.x, y: r.y, w: r.w, h: r.h, content_h: r.scroll })).collect()+}++/// Tags the content of a scroll container (everything laid out since `p0`/`r0` that is not already in an inner one).+fn mark_group(out: &mut Out, p0: usize, r0: usize, id: u32) {+ let (p0, r0) = (p0.min(out.placed.len()), r0.min(out.rects.len()));+ for p in &mut out.placed[p0..] { if p.grp == 0 { p.grp = id; } }+ for r in &mut out.rects[r0..] { if r.grp == 0 && r.scroll.is_nan() { r.grp = id; } }+}++/// Sticky boxes inside a container that ends at `bottom` may travel only that far: converts their open `lim` (minus the box's bottom edge).+fn close_lims(out: &mut Out, p0: usize, r0: usize, bottom: f32) {+ let (p0, r0) = (p0.min(out.placed.len()), r0.min(out.rects.len()));+ for p in &mut out.placed[p0..] { if p.lim < 0.0 { p.lim = (bottom + p.lim).max(0.0); } }+ for r in &mut out.rects[r0..] { if r.lim < 0.0 { r.lim = (bottom + r.lim).max(0.0); } }+}++/// Translucent layers that fake a blurred `box-shadow`: the outermost is the largest and the faintest.+fn shadow_rects(sh: &Shadow, x: f32, y: f32, w: f32, h: f32, radius: f32) -> Vec<Rect> {+ let n = ((sh.blur / 2.0).ceil() as i32).clamp(1, 8);+ (0..n).map(|i| {+ let grow = sh.spread + sh.blur / 2.0 - sh.blur * i as f32 / n as f32;+ Rect { x: x + sh.dx - grow, y: y + sh.dy - grow, w: (w + 2.0 * grow).max(0.0), h: (h + 2.0 * grow).max(0.0), color: sh.color, r: if radius > 0.0 { radius + grow.max(0.0) } else { 0.0 }, ring: 0.0, node: 0, z: 0, a: (sh.a / n as f32 * 255.0).round().clamp(1.0, 255.0) as u8, grad: None, pic: None, st: f32::NAN, lim: f32::NAN, grp: 0, scroll: f32::NAN }+ }).collect()+}++/// `overflow: hidden` with a fixed height: drops text that starts below `bottom` and trims rectangles to it.+fn clip_to(out: &mut Out, p0: usize, r0: usize, bottom: f32) {+ let p0 = p0.min(out.placed.len());+ let tail: Vec<Placed> = out.placed.drain(p0..).filter(|p| p.base <= bottom + 0.5).collect();+ out.placed.extend(tail);+ let r0 = r0.min(out.rects.len());+ let tail: Vec<Rect> = out.rects.drain(r0..).filter(|q| q.y < bottom).map(|mut q| { q.h = q.h.min(bottom - q.y); q }).collect();+ out.rects.extend(tail);+}++/// Leading and trailing vertical margins (device px) of a flex or grid item's list.+fn edge_gaps(items: &[Item], sc: f32) -> (f32, f32) {+ let g = |i: Option<&Item>| if let Some(Item::Break(g)) = i { g * sc } else { 0.0 };+ (g(items.first()), g(items.last()))+}++/// Tile size and offset of a background image inside a `w` x `h` box (device px).+fn resolve_pic(bp: &BgPaint, w: f32, h: f32, sc: f32) -> Pic {+ let (nw, nh) = ((bp.nw * sc).max(1.0), (bp.nh * sc).max(1.0));+ let (tw, th) = match bp.size {+ BgSize::Auto => (nw, nh),+ BgSize::Cover => { let k = (w / nw).max(h / nh); (nw * k, nh * k) }+ BgSize::Contain => { let k = (w / nw).min(h / nh); (nw * k, nh * k) }+ BgSize::Fixed(a, b) => match (a.map(|l| resolve(l, w, sc)), b.map(|l| resolve(l, h, sc))) {+ (Some(x), Some(y)) => (x, y),+ (Some(x), None) => (x, x * nh / nw),+ (None, Some(y)) => (y * nw / nh, y),+ _ => (nw, nh),+ },+ };+ let (tw, th) = (tw.max(1.0), th.max(1.0));+ let at = |l: Len, room: f32, whole: f32| if let Len::Pct(p) = l { (whole - room) * p / 100.0 } else { resolve(l, whole, sc) };+ Pic { img: bp.img, w: tw, h: th, ox: at(bp.pos[0], tw, w), oy: at(bp.pos[1], th, h), rx: bp.repeat.0, ry: bp.repeat.1 }+}++fn rtl_char(c: char) -> bool { matches!(c as u32, 0x0590..=0x08FF | 0xFB1D..=0xFDFF | 0xFE70..=0xFEFF | 0x200F | 0x202B | 0x202E | 0x2067 | 0x10800..=0x10FFF | 0x1E800..=0x1EFFF) }++fn mirrored(c: char) -> char { match c { '(' => ')', ')' => '(', '[' => ']', ']' => '[', '{' => '}', '}' => '{', '<' => '>', '>' => '<', '\u{ab}' => '\u{bb}', '\u{bb}' => '\u{ab}', c => c } }++/// UAX #9 on one line of words (a picture or control is one neutral object). Words are reordered visually (rule L2 on word levels),+/// words at an odd level get mirrored brackets (shaped scripts are mirrored by the shaper already); returns true for an RTL paragraph.+fn bidi_reorder(line: &mut Vec<Placed>) -> bool {+ use unicode_bidi::{BidiInfo, Level};+ let (mut text, mut spans) = (String::new(), Vec::with_capacity(line.len()));+ for (i, p) in line.iter().enumerate() {+ if i > 0 { text.push(' '); }+ let a = text.len();+ if p.text.is_empty() { text.push('\u{FFFC}'); } else { text.push_str(&p.text); }+ spans.push(a..text.len());+ }+ let info = BidiInfo::new(&text, None);+ let Some(para) = info.paragraphs.first() else { return false };+ let base = para.level.is_rtl();+ let levels: Vec<Level> = spans.iter().map(|s| info.levels[s.clone()].iter().copied().max().unwrap_or(para.level)).collect();+ if levels.iter().all(|l| *l == Level::ltr()) { return false; }+ let n = line.len();+ let x0 = line.iter().fold(f32::MAX, |m, p| m.min(p.x));+ let gaps: Vec<f32> = (0..n).map(|i| if i == 0 { 0.0 } else { (line[i].x - (line[i - 1].x + line[i - 1].w)).max(0.0) }).collect();+ let space = gaps.iter().copied().find(|g| *g > 0.0).unwrap_or(0.0);+ let order = BidiInfo::reorder_visual(&levels);+ let (mut x, mut new_x) = (x0, vec![0f32; n]);+ for (k, &i) in order.iter().enumerate() {+ if k > 0 { let prev = order[k - 1]; x += if i == prev + 1 { gaps[i] } else if prev == i + 1 { gaps[prev] } else { space }; }+ new_x[i] = x;+ x += line[i].w;+ }+ for (i, p) in line.iter_mut().enumerate() {+ p.x = new_x[i];+ if levels[i].is_rtl() && !crate::gfx::complex(&p.text) && p.text.chars().any(|c| mirrored(c) != c) { p.text = p.text.chars().map(mirrored).collect(); }+ }+ base+}++/// Moves the finished line down to the baseline `y + tallest` and applies text-align inside the line box.+fn flush_line(line: &mut Vec<Placed>, out: &mut Out, y: &mut f32, right: f32, align: u8) {+ if line.is_empty() { return; }+ let h = line.iter().fold(0f32, |m, p| m.max(p.size));+ let adv = line.iter().fold(0f32, |m, p| m.max(p.size * p.lh));+ let lead = (adv - h * 1.35) / 2.0; // half-leading when line-height differs from the 1.35 default+ // Bidi: UAX #9 over the words of the line decides the paragraph direction and each word's embedding level.+ let rtl = if line.iter().any(|p| p.text.chars().any(rtl_char)) { bidi_reorder(line) } else { false };+ let last = line.iter().max_by(|a, b| (a.x + a.w).total_cmp(&(b.x + b.w))).map_or(0.0, |p| p.x + p.w);+ let free = (right - last).max(0.0);+ let shift = match align { 1 => free / 2.0, 2 => free, _ if rtl => free, _ => 0.0 };+ for mut p in line.drain(..) {+ p.base = *y + h + lead - p.dy;+ p.x += shift;+ if let Some(b) = p.blk.take() {+ let (dx, dy) = (p.x, p.base - p.size);+ out.placed.extend(b.0.into_iter().map(|mut q| { q.x += dx; q.base += dy; q }));+ out.rects.extend(b.1.into_iter().map(|mut r| { r.x += dx; r.y += dy; r }));+ } else { out.placed.push(p); }+ }+ *y += adv;+}++/// Line box [l, r] at height `y` after subtracting active floats.+fn eff(floats: &[Fl], y: f32, left: f32, right: f32) -> (f32, f32) {+ let (mut l, mut r) = (left, right);+ for f in floats.iter().filter(|f| f.bottom > y) {+ if f.right_side { r = r.min(f.edge); } else { l = l.max(f.edge); }+ }+ (l, r.max(l + 20.0))+}++fn border_rects(rects: &mut Vec<Rect>, r: &Region, y_end: f32) -> f32 {+ let Some(top) = r.top else { return 0.0 };+ let [bt, br, bb, bl] = r.bw;+ let (w, h) = (r.x1 - r.x0, y_end - top);+ if let (true, [Some(a), Some(b), Some(c), Some(d)]) = (r.radius > 0.0, r.borders) {+ if a == b && b == c && c == d { // one rounded ring instead of four straight sides+ rects.push(Rect { x: r.x0, y: top - bt, w, h: h + bt + bb, color: a.1, r: r.radius, ring: bt, node: r.node, z: 0, a: 255, grad: None, pic: None, st: f32::NAN, lim: f32::NAN, grp: 0, scroll: f32::NAN });+ return bb;+ }+ }+ let side = |rects: &mut Vec<Rect>, b: Option<(f32, u32)>, x: f32, y: f32, w: f32, h: f32| if let Some((_, c)) = b { rects.push(Rect { x, y, w, h, color: c, r: 0.0, ring: 0.0, node: 0, z: 0, a: 255, grad: None, pic: None, st: f32::NAN, lim: f32::NAN, grp: 0, scroll: f32::NAN }); };+ side(rects, r.borders[0], r.x0, top - bt, w, bt);+ side(rects, r.borders[2], r.x0, y_end, w, bb);+ side(rects, r.borders[3], r.x0, top - bt, bl, h + bt + bb);+ side(rects, r.borders[1], r.x1 - br, top - bt, br, h + bt + bb);+ bb+}++/// Lays `items` out between `left0` and `right0` starting at `y0`; returns the y after the last line.+fn block<'a>(items: &'a [Item], left0: f32, right0: f32, y0: f32, sc: f32, f: &mut Fonts, out: &mut Out) -> f32 {+ let (mut left, mut right) = (left0, right0);+ let mut line: Vec<Placed> = vec![];+ let (mut x, mut y, mut gap, mut align) = (left, y0, 0f32, 0u8);+ let (mut cur_l, mut cur_r) = (left, right);+ let (sp0, sr0) = (out.placed.len(), out.rects.len());+ let mut soft_last = false; // the last word on the line ended with a soft hyphen (shown only when the line breaks there)+ let mut regions: Vec<Region> = vec![];+ let mut floats: Vec<Fl> = vec![];+ let mut pos: Vec<Pos<'a>> = vec![];+ macro_rules! flush { () => { flush_line(&mut line, out, &mut y, cur_r, align) }; }+ macro_rules! mark_tops { ($y:expr) => { for r in regions.iter_mut().filter(|r| r.top.is_none()) { r.top = Some($y); } for p in pos.iter_mut().filter(|p| p.top.is_none()) { p.top = Some($y); } }; }+ for it in items {+ match it {+ Item::Break(g) => { flush!(); gap = gap.max(g * sc); }+ Item::Box(b) => {+ flush!();+ let avail = right - left;+ let bw = b.borders.map(|o| o.map_or(0.0, |(w, _)| (w * sc).round().max(1.0)));+ let (inl, inr, pl, pr) = (b.ml * sc, b.mr * sc, b.pl * sc + bw[3], b.pr * sc + bw[1]);+ let inner = (avail - inl - inr - pl - pr).max(20.0);+ let mut w = inner;+ let trim = if b.bb { pl + pr } else { 0.0 }; // border-box: width includes padding and borders+ if let Some(wd) = b.width { w = (resolve(wd, avail, sc) - trim).max(0.0); }+ if let Some(mw) = b.max_width { w = w.min((resolve(mw, avail, sc) - trim).max(0.0)); }+ w = w.clamp(20.0, inner);+ let extra = (inner - w).max(0.0);+ let off = if b.auto_l && b.auto_r { extra / 2.0 } else if b.auto_l { extra } else { 0.0 };+ let bx0 = left + inl + off;+ let starts_now = b.min_h > 0.0 || b.pt > 0.0 || b.pb > 0.0 || b.shadow.is_some() || b.bgimg.is_some();+ if starts_now { // a fixed-height or padded box starts here even when it holds no flow content+ if gap > 0.0 && y > y0 + 0.5 { y += gap; }+ gap = 0.0;+ }+ regions.push(Region { node: b.node, radius: b.radius * sc, min_h: b.min_h * sc, pt: b.pt * sc, pb: b.pb * sc, bb: b.bb, scroll: b.scroll, bgimg: b.bgimg.clone(), r0: out.rects.len(), p0: out.placed.len(), a: b.bg_a, clip: b.clip, shadow: b.shadow, grad: b.grad.clone(), bg: b.bg, top: starts_now.then_some(y), x0: bx0, x1: bx0 + pl + w + pr, saved: (left, right), borders: b.borders, bw });+ left = bx0 + pl;+ right = left + w;+ (cur_l, cur_r) = (left, right);+ y += b.pt * sc;+ }+ Item::BoxEnd => {+ flush!();+ if let Some(mut r) = regions.pop() {+ y += r.pb;+ let mut content_h = f32::NAN; // overflow: auto|scroll with a fixed height: the box keeps its height, the content scrolls inside+ if r.min_h > 0.0 {+ let top = *r.top.get_or_insert(y);+ let need = top + if r.bb { r.min_h } else { r.pt + r.min_h + r.pb };+ if r.scroll { content_h = (y - top).max(0.0); }+ y = if r.clip || r.scroll { need } else { y.max(need) };+ }+ if let (true, Some(top)) = (r.clip, r.top) { clip_to(out, r.p0, r.r0, y.max(top)); }+ close_lims(out, r.p0, r.r0, y);+ if let Some(top) = r.top {+ let at = r.r0.min(out.rects.len());+ let mut under: Vec<Rect> = vec![];+ if let Some(sh) = &r.shadow { under.extend(shadow_rects(sh, r.x0, top, r.x1 - r.x0, y - top, r.radius)); }+ if let Some(color) = r.bg { under.push(Rect { x: r.x0, y: top, w: r.x1 - r.x0, h: y - top, color, r: r.radius, ring: 0.0, node: r.node, z: 0, a: (r.a * 255.0).round().clamp(0.0, 255.0) as u8, grad: r.grad.clone(), pic: None, st: f32::NAN, lim: f32::NAN, grp: 0, scroll: f32::NAN }); }+ if let Some(bp) = &r.bgimg { under.push(Rect { x: r.x0, y: top, w: r.x1 - r.x0, h: y - top, color: 0, r: 0.0, ring: 0.0, node: 0, z: 0, a: 255, grad: None, pic: Some(resolve_pic(bp, r.x1 - r.x0, y - top, sc)), st: f32::NAN, lim: f32::NAN, grp: 0, scroll: f32::NAN }); }+ let marker = |grp: u32, scroll: f32| Rect { x: r.x0, y: top, w: r.x1 - r.x0, h: y - top, color: 0, r: 0.0, ring: 0.0, node: r.node, z: 0, a: 0, grad: None, pic: None, st: f32::NAN, lim: f32::NAN, grp, scroll };+ if content_h.is_finite() {+ let id = next_grp();+ mark_group(out, r.p0, r.r0, id);+ under.push(marker(id, content_h));+ } else if r.bg.is_none() && r.node != 0 { under.push(marker(0, f32::NAN)); } // box geometry for hit-testing and getBoundingClientRect+ out.rects.splice(at..at, under);+ }+ y += border_rects(&mut out.rects, &r, y);+ (left, right) = r.saved;+ (cur_l, cur_r) = (left, right);+ }+ }+ Item::Table(t) => {+ flush!();+ if gap > 0.0 && y > y0 + 0.5 { y += gap; }+ gap = 0.0;+ mark_tops!(y);+ let (l, r) = eff(&floats, y, left, right);+ y = table(t, l, r, y, sc, f, out);+ }+ Item::Float(fl) => {+ flush!();+ if gap > 0.0 && y > y0 + 0.5 { y += gap; }+ gap = 0.0;+ mark_tops!(y);+ let avail = right - left;+ let w = spec_width(fl, avail, sc, f);+ let mut fy = y;+ loop {+ let (l2, r2) = eff(&floats, fy, left, right);+ let active_bottom = floats.iter().filter(|f| f.bottom > fy).map(|f| f.bottom).fold(f32::MAX, f32::min);+ if w <= r2 - l2 + 0.5 || active_bottom == f32::MAX { break; }+ fy = active_bottom;+ }+ let (l2, r2) = eff(&floats, fy, left, right);+ let fx = if fl.right { r2 - w } else { l2 };+ let end = block(&fl.items, fx, fx + w, fy, sc, f, out);+ let spacing = 8.0 * sc;+ floats.push(Fl { right_side: fl.right, edge: if fl.right { fx - spacing } else { fx + w + spacing }, bottom: end });+ }+ Item::Clear(bits) => {+ flush!();+ for fl in floats.iter().filter(|fl| (bits & 1 != 0 && !fl.right_side) || (bits & 2 != 0 && fl.right_side)) { y = y.max(fl.bottom); }+ }+ Item::Rule(color) => {+ flush!();+ if gap > 0.0 && y > y0 + 0.5 { y += gap; }+ gap = 0.0;+ mark_tops!(y);+ let (l, r) = eff(&floats, y, left, right);+ let h = sc.round().max(1.0);+ out.rects.push(Rect { x: l, y, w: r - l, h, color: *color, r: 0.0, ring: 0.0, node: 0, z: 0, a: 255, grad: None, pic: None, st: f32::NAN, lim: f32::NAN, grp: 0, scroll: f32::NAN });+ y += h + 2.0 * sc;+ }+ Item::Flex(sp) => {+ flush!();+ if gap > 0.0 && y > y0 + 0.5 { y += gap; }+ gap = 0.0;+ mark_tops!(y);+ let (l, r) = eff(&floats, y, left, right);+ y = flex(sp, l, r, y, sc, f, out);+ }+ Item::RelStart(off, z, sticky) => {+ let off = (*off, *z, *sticky);+ flush!();+ if gap > 0.0 && y > y0 + 0.5 { y += gap; }+ gap = 0.0;+ pos.push(Pos { x0: left, x1: right, top: Some(y), p0: out.placed.len(), r0: out.rects.len(), off: off.0, z: off.1, sticky: off.2, pending: vec![] });+ }+ Item::RelEnd => {+ flush!();+ if let Some(p) = pos.pop() { close_pos(p, y, sc, f, out); }+ }+ Item::Abs(a) => if a.fixed {+ let (pw, vh) = (out.pw, VH.with(Cell::get));+ place_abs(a, (0.0, 0.0, pw, Some(vh)), (left, y), sc, f, out);+ } else {+ match pos.last_mut() {+ Some(p) => p.pending.push((a, left, y)),+ None => { let pw = out.pw; place_abs(a, (0.0, 0.0, pw, None), (left, y), sc, f, out); }+ }+ },+ Item::Grid(sp) => {+ flush!();+ if gap > 0.0 && y > y0 + 0.5 { y += gap; }+ gap = 0.0;+ mark_tops!(y);+ let (l, r) = eff(&floats, y, left, right);+ y = grid_layout(sp, l, r, y, sc, f, out);+ }+ Item::Word { .. } | Item::Image { .. } | Item::Field { .. } | Item::InlineBlock(_) => {+ let soft = matches!(it, Item::Word { text, .. } if text.ends_with('\u{ad}'));+ let (size, w, space, indent, a, text, color, face, ul, link, img, field, lh, node, blk, ls, dy) = match it {+ Item::Word { text, size, color, bold, italic, fam, ul, mono, link, space, indent, align, lh, node, ls, dy } => {+ let size = px(*size, sc);+ let face = crate::gfx::face(*bold, *italic, *mono, *fam);+ let ls = ls * sc;+ let text = text.trim_end_matches('\u{ad}');+ (size, f.width_f(text, size, face) + ls * text.chars().count() as f32, *space, *indent, *align, text.to_string(), *color, face, *ul, *link, None, None, *lh, *node, None, ls, dy * size)+ }+ Item::Image { img, w, h, link, indent, align, node, va, alpha, pct } => {+ let (mut w, mut h) = (w * sc, h * sc);+ let avail = cur_r - cur_l - indent * sc;+ if let (Some(p), true) = (pct, w > 0.0) { let nw = avail * p / 100.0; h *= nw / w; w = nw; }+ if w > avail && avail > 0.0 { h *= avail / w; w = avail; }+ // vertical-align: middle centers the picture on the baseline plus half the x-height; top/bottom keep the baseline+ let dy = if *va == 1 { 4.0 * sc - h / 2.0 } else { 0.0 };+ (h.max(1.0), w, false, *indent, *align, String::new(), ((alpha * 255.0).round() as u32).clamp(1, 255), 0, false, *link, Some(*img), None, 1.35, *node, None, 0.0, dy)+ }+ Item::Field { idx, w, h, indent, align, node } => {+ let (w, h) = ((w * sc).min(cur_r - cur_l - indent * sc).max(20.0), h * sc);+ (h, w, true, *indent, *align, String::new(), 0, 0, false, None, None, Some(*idx), 1.35, *node, None, 0.0, 0.0)+ }+ Item::InlineBlock(fl) => {+ let w = spec_width(fl, (right - left).max(20.0), sc, f);+ let mut tmp = Out::new(out.pw);+ let h = block(&fl.items, 0.0, w, 0.0, sc, f, &mut tmp).max(1.0);+ (h, w, true, 0.0, align, String::new(), 0, 0, false, None, None, None, 1.35, 0, Some(Box::new((tmp.placed, tmp.rects))), 0.0, 0.0)+ }+ _ => unreachable!(),+ };+ let mut sp = if space && !line.is_empty() { f.width(" ", size) } else { 0.0 };+ if !line.is_empty() && x + sp + w > cur_r {+ if soft_last { if let Some(l) = line.last_mut() { let hw = f.width("-", l.size); l.text.push('-'); l.w += hw; } }+ flush!();+ sp = 0.0;+ }+ if line.is_empty() {+ if gap > 0.0 && y > y0 + 0.5 { y += gap; }+ gap = 0.0;+ (cur_l, cur_r) = eff(&floats, y, left, right);+ x = cur_l + indent * sc;+ align = a;+ mark_tops!(y);+ } else { x += sp; }+ line.push(Placed { x, base: 0.0, size, w, text, link, color, face, ul, img, field, lh, node, blk, z: 0, ls, dy, st: f32::NAN, lim: f32::NAN, grp: 0 });+ soft_last = soft;+ x += w;+ }+ }+ }+ flush!();+ // a box left open by malformed item streams still closes cleanly+ for r in regions.drain(..) {+ if let (Some(color), Some(top)) = (r.bg, r.top) { out.rects.push(Rect { x: r.x0, y: top, w: r.x1 - r.x0, h: y - top, color, r: 0.0, ring: 0.0, node: 0, z: 0, a: 255, grad: None, pic: None, st: f32::NAN, lim: f32::NAN, grp: 0, scroll: f32::NAN }); }+ }+ for p in pos.drain(..) { close_pos(p, y, sc, f, out); }+ close_lims(out, sp0, sr0, y);+ // content that is shorter than a float it contains still ends below it, like a cleared container would+ floats.iter().map(|f| f.bottom).fold(y, f32::max)+}++/// (min-content, max-content) width of an item list: longest word / longest unwrapped line.+fn measure(items: &[Item], sc: f32, f: &mut Fonts) -> (f32, f32) {+ let (mut min, mut maxw, mut line, mut first) = (0f32, 0f32, 0f32, true);+ for it in items {+ match it {+ Item::Word { text, size, space, bold, italic, fam, mono, ls, .. } => {+ let s = px(*size, sc);+ let text = text.trim_end_matches('\u{ad}');+ let w = f.width_f(text, s, crate::gfx::face(*bold, *italic, *mono, *fam)) + ls * sc * text.chars().count() as f32;+ line += if *space && !first { f.width(" ", s) } else { 0.0 } + w;+ min = min.max(w);+ first = false;+ }+ Item::Image { w, .. } | Item::Field { w, .. } => { line += w * sc; min = min.max(w * sc); first = false; }+ Item::Break(_) | Item::Rule(_) | Item::Clear(_) => { maxw = maxw.max(line); line = 0.0; first = true; }+ Item::Table(t) => {+ let (cmin, cmax) = col_metrics(t, sc, f);+ let sp = t.spacing * sc * (cmin.len() as f32 + 1.0);+ min = min.max(cmin.iter().sum::<f32>() + sp);+ maxw = maxw.max(line).max(cmax.iter().sum::<f32>() + sp);+ line = 0.0;+ first = true;+ }+ Item::InlineBlock(fl) => {+ let (mn, mx) = measure(&fl.items, sc, f);+ let inset = box_inset(&fl.items, sc);+ line += if first { 0.0 } else { f.width(" ", 16.0 * sc) } + mx + inset;+ min = min.max(mn + inset);+ first = false;+ }+ Item::Flex(sp) => {+ let ms: Vec<(f32, f32)> = sp.items.iter().map(|i| { let (a, b) = measure(&i.items, sc, f); let n = box_inset(&i.items, sc); (a + n, b + n) }).collect();+ let g = sp.gap * sc * ms.len().saturating_sub(1) as f32;+ if sp.col {+ min = min.max(ms.iter().fold(0f32, |m, x| m.max(x.0)));+ maxw = maxw.max(line).max(ms.iter().fold(0f32, |m, x| m.max(x.1)));+ line = 0.0;+ first = true;+ continue;+ }+ min = min.max(if sp.wrap { ms.iter().fold(0f32, |m, x| m.max(x.0)) } else { ms.iter().map(|x| x.0).sum::<f32>() + g });+ maxw = maxw.max(line).max(ms.iter().map(|x| x.1).sum::<f32>() + g);+ line = 0.0;+ first = true;+ }+ Item::Grid(sp) => {+ let ms: Vec<(f32, f32)> = sp.items.iter().map(|i| { let (a, b) = measure(&i.items, sc, f); let n = box_inset(&i.items, sc); (a + n, b + n) }).collect();+ min = min.max(ms.iter().fold(0f32, |m, x| m.max(x.0)));+ maxw = maxw.max(line).max(ms.iter().map(|x| x.1).sum::<f32>() + sp.col_gap * sc * ms.len().saturating_sub(1) as f32);+ line = 0.0;+ first = true;+ }+ Item::Box(_) | Item::BoxEnd | Item::Float(_) | Item::Abs(_) | Item::RelStart(..) | Item::RelEnd => {}+ }+ }+ (min, maxw.max(line))+}++/// Horizontal margin + padding of a leading Box item.+fn box_inset(items: &[Item], sc: f32) -> f32 {+ // the Box follows the element's top-margin Break+ items.iter().take_while(|i| matches!(i, Item::Break(_) | Item::Box(_))).find_map(|i| if let Item::Box(b) = i { Some((b.ml + b.mr + b.pl + b.pr) * sc) } else { None }).unwrap_or(0.0)+}++/// Outer width of a float / inline-block: explicit width or shrink-to-fit within `avail`.+fn spec_width(fl: &FloatSpec, avail: f32, sc: f32, f: &mut Fonts) -> f32 {+ let (mn, mx) = measure(&fl.items, sc, f);+ let inset = box_inset(&fl.items, sc);+ let mut w = match fl.width { Some(wd) => resolve(wd, avail, sc), None => (mx + inset).min(avail).max((mn + inset).min(avail)) };+ if let Some(m) = fl.max_width { w = w.min(resolve(m, avail, sc)); }+ w.clamp(20.0, avail.max(20.0))+}++/// Open `position:relative` box: its content range in the output and the absolutes waiting for its final height.+struct Pos<'a> { x0: f32, x1: f32, top: Option<f32>, p0: usize, r0: usize, off: [Option<Len>; 4], z: i32, sticky: bool, pending: Vec<(&'a AbsSpec, f32, f32)> }++fn close_pos(p: Pos, y: f32, sc: f32, f: &mut Fonts, out: &mut Out) {+ let top = p.top.unwrap_or(y);+ for (a, sx, sy) in &p.pending { place_abs(a, (p.x0, top, p.x1, Some(y)), (*sx, *sy), sc, f, out); }+ let w = p.x1 - p.x0;+ let off = |i: usize| p.off[i].map(|l| resolve(l, w, sc));+ let (dx, dy) = if p.sticky { (0.0, 0.0) } else { (off(3).or(off(1).map(|v| -v)).unwrap_or(0.0), off(0).or(off(2).map(|v| -v)).unwrap_or(0.0)) };+ let (p0, r0) = (p.p0.min(out.placed.len()), p.r0.min(out.rects.len()));+ if dx != 0.0 || dy != 0.0 {+ for q in &mut out.placed[p0..] { q.x += dx; q.base += dy; }+ for r in &mut out.rects[r0..] { r.x += dx; r.y += dy; }+ }+ if p.sticky { // pinned by the painter once the page scrolls past where the box would leave the top offset+ let st = top - off(0).unwrap_or(0.0);+ for q in &mut out.placed[p0..] { if q.st.is_nan() { q.st = st; q.lim = -y; } }+ for r in &mut out.rects[r0..] { if r.st.is_nan() { r.st = st; r.lim = -y; } }+ }+ if p.z != 0 { // a stacking context: its whole content moves to the layer of its z-index+ let d = zdigit(p.z);+ for q in &mut out.placed[p0..] { q.z = zwrap(q.z, d); }+ for r in &mut out.rects[r0..] { r.z = zwrap(r.z, d); }+ }+}++/// Places a `position:absolute` box in the containing block (x0, top, x1, bottom); `st` is its static position.+fn place_abs(a: &AbsSpec, cb: (f32, f32, f32, Option<f32>), st: (f32, f32), sc: f32, f: &mut Fonts, out: &mut Out) {+ let (cx0, ct, cx1, cbot) = cb;+ let cw = (cx1 - cx0).max(20.0);+ let off = |i: usize| a.off[i].map(|l| resolve(l, cw, sc));+ let (t, r, b, l) = (off(0), off(1), off(2), off(3));+ let (mn, mx) = measure(&a.items, sc, f);+ let inset = box_inset(&a.items, sc);+ let room = (cw - l.unwrap_or(0.0) - r.unwrap_or(0.0)).max(20.0);+ let mut w = match (a.width, l, r) {+ (Some(wd), _, _) => resolve(wd, cw, sc),+ (None, Some(l), Some(r)) => cw - l - r,+ _ => (mx + inset).max(mn + inset).min(room),+ };+ if let Some(m) = a.max_width { w = w.min(resolve(m, cw, sc)); }+ let w = w.clamp(20.0, cw.max(20.0));+ let x = match (l, r) { (Some(l), _) => cx0 + l, (None, Some(r)) => cx1 - r - w, _ => st.0 };+ let mut tmp = Out::new(out.pw);+ let h = block(&a.items, x, x + w, 0.0, sc, f, &mut tmp);+ let y = match (t, b, cbot) { (Some(t), _, _) => ct + t, (None, Some(b), Some(bot)) => bot - b - h, _ => st.1 };+ // positioned boxes paint above in-flow content, by z-index, as a stacking context of their own; fixed ones also stay in the viewport+ let (d, pin) = (zdigit(a.z), if a.fixed { 0.0 } else { f32::NAN });+ let wrap = |z: i64| { let z = zwrap(z, d); if a.fixed { zwrap(z, 16383) } else { z } };+ out.placed.extend(tmp.placed.into_iter().map(|mut p| { p.base += y; p.z = wrap(p.z); if p.st.is_nan() { p.st = pin; } else if !a.fixed { p.st += y; } p }));+ out.rects.extend(tmp.rects.into_iter().map(|mut r| { r.y += y; r.z = wrap(r.z); if r.st.is_nan() { r.st = pin; } else if !a.fixed { r.st += y; } r }));+}++/// Row flex container: sizes items (basis/width/content, grow, shrink), wraps into lines, then justifies and aligns.+/// Column flex container: items stack with `gap` and their own margins; `align-items` places them across.+/// shortcut: no main-axis sizing (grow/shrink/justify need a container height, which is only a minimum here)+fn flex_col(sp: &FlexSpec, left: f32, right: f32, y0: f32, sc: f32, f: &mut Fonts, out: &mut Out) -> f32 {+ let avail = (right - left).max(1.0);+ let gap = sp.gap * sc;+ let mut y = y0;+ for (k, it) in sp.items.iter().enumerate() {+ let (_, mx) = measure(&it.items, sc, f);+ let inset = box_inset(&it.items, sc);+ let al = if it.align != 0 { it.align } else { sp.align };+ let w = match it.width { Some(wd) => resolve(wd, avail, sc) + inset, None if al == 0 => avail, None => mx + inset }.clamp(1.0, avail);+ let off = if it.auto_l && it.auto_r { (avail - w) / 2.0 } else if it.auto_l { avail - w } else { match al { 2 => (avail - w) / 2.0, 3 => avail - w, _ => 0.0 } };+ let (lead, trail) = edge_gaps(&it.items, sc);+ let end = block(&it.items, left + off, left + off + w, y + lead, sc, f, out);+ y = end + trail + if k + 1 < sp.items.len() { gap } else { 0.0 };+ }+ y+}++/// Grid container: columns from `grid-template-columns` (fr, px, %, repeat, auto-fill), items flow row by row and may span columns.+/// shortcut: rows are as tall as their tallest item; no explicit rows, areas, named lines or dense packing+fn grid_layout(sp: &GridSpec, left: f32, right: f32, y0: f32, sc: f32, f: &mut Fonts, out: &mut Out) -> f32 {+ let avail = (right - left).max(1.0);+ let (cg, rg) = (sp.col_gap * sc, sp.row_gap * sc);+ let mut tracks = sp.tracks.clone();+ if let Some(minw) = sp.auto_min { tracks = vec![Track::Fr(1.0); (((avail + cg) / (minw * sc + cg)).floor() as usize).clamp(1, 24)]; }+ if tracks.is_empty() { tracks.push(Track::Fr(1.0)); }+ let n = tracks.len();+ let fixed: f32 = tracks.iter().map(|t| match t { Track::Px(p) => p * sc, Track::Pct(p) => p / 100.0 * avail, Track::Fr(_) => 0.0 }).sum();+ let frs: f32 = tracks.iter().map(|t| if let Track::Fr(k) = t { *k } else { 0.0 }).sum();+ let free = (avail - fixed - cg * (n as f32 - 1.0)).max(0.0);+ let widths: Vec<f32> = tracks.iter().map(|t| match t { Track::Px(p) => p * sc, Track::Pct(p) => p / 100.0 * avail, Track::Fr(k) => if frs > 0.0 { free * k / frs } else { 0.0 } }).collect();+ let mut rows: Vec<Vec<(usize, usize, usize)>> = vec![vec![]];+ let mut col = 0;+ for (i, it) in sp.items.iter().enumerate() {+ let span = it.span.clamp(1, n);+ if col + span > n { rows.push(vec![]); col = 0; }+ rows.last_mut().unwrap().push((i, col, span));+ col += span;+ if col >= n { rows.push(vec![]); col = 0; }+ }+ rows.retain(|r| !r.is_empty());+ let mut y = y0;+ for (ri, row) in rows.iter().enumerate() {+ let (mut cells, mut rh) = (vec![], 0f32);+ for &(i, col, span) in row {+ let it = &sp.items[i];+ let x = left + widths[..col].iter().sum::<f32>() + cg * col as f32;+ let w = widths[col..col + span].iter().sum::<f32>() + cg * (span as f32 - 1.0);+ let (lead, trail) = edge_gaps(&it.items, sc);+ let mut tmp = Out::new(out.pw);+ let end = block(&it.items, x, x + w, y + lead, sc, f, &mut tmp);+ rh = rh.max(end - y + trail);+ cells.push(tmp);+ }+ for tmp in cells { out.placed.extend(tmp.placed); out.rects.extend(tmp.rects); }+ y += rh + if ri + 1 < rows.len() { rg } else { 0.0 };+ }+ y+}++fn flex(sp: &FlexSpec, left: f32, right: f32, y0: f32, sc: f32, f: &mut Fonts, out: &mut Out) -> f32 {+ if sp.col { return flex_col(sp, left, right, y0, sc, f, out); }+ let avail = (right - left).max(1.0);+ let gap = sp.gap * sc;+ let m: Vec<(f32, f32)> = sp.items.iter().map(|it| {+ let (mn, mx) = measure(&it.items, sc, f);+ let inset = box_inset(&it.items, sc);+ let mut base = match (it.basis, it.width) { (Some(b), _) => resolve(b, avail, sc) + inset, (None, Some(w)) => resolve(w, avail, sc) + inset, _ => mx + inset };+ if let Some(mw) = it.max_width { base = base.min(resolve(mw, avail, sc) + inset); }+ let min = (mn + inset).min(base);+ (base, min)+ }).collect();+ let mut lines: Vec<Vec<usize>> = vec![];+ let (mut cur, mut sum) = (vec![], 0f32);+ for (i, (base, _)) in m.iter().enumerate() {+ if sp.wrap && !cur.is_empty() && sum + gap + base > avail { lines.push(std::mem::take(&mut cur)); sum = 0.0; }+ sum += if cur.is_empty() { 0.0 } else { gap } + base;+ cur.push(i);+ }+ if !cur.is_empty() { lines.push(cur); }+ let mut y = y0;+ for (li, line) in lines.iter().enumerate() {+ let n = line.len() as f32;+ let mut w: Vec<f32> = line.iter().map(|&i| m[i].0).collect();+ let free = avail - w.iter().sum::<f32>() - gap * (n - 1.0);+ if free > 0.0 {+ let tg: f32 = line.iter().map(|&i| sp.items[i].grow).sum();+ if tg > 0.0 { for (k, &i) in line.iter().enumerate() { w[k] += free * sp.items[i].grow / tg; } }+ } else if free < 0.0 {+ let sw: f32 = line.iter().map(|&i| sp.items[i].shrink * m[i].0).sum();+ if sw > 0.0 { for (k, &i) in line.iter().enumerate() { w[k] = (m[i].0 + free * sp.items[i].shrink * m[i].0 / sw).max(m[i].1); } }+ }+ let free = (avail - w.iter().sum::<f32>() - gap * (n - 1.0)).max(0.0);+ let autos: f32 = line.iter().map(|&i| sp.items[i].auto_l as u8 as f32 + sp.items[i].auto_r as u8 as f32).sum();+ let (mut start, mut between) = (0.0, 0.0);+ if autos == 0.0 {+ match sp.justify {+ 1 => start = free / 2.0,+ 2 => start = free,+ 3 if n > 1.0 => between = free / (n - 1.0),+ 4 => { between = free / n; start = between / 2.0; }+ 5 => { between = free / (n + 1.0); start = between; }+ _ => {}+ }+ }+ let mut x = left + start;+ let mut cells = vec![];+ let mut line_h = 0f32;+ for (k, &i) in line.iter().enumerate() {+ let it = &sp.items[i];+ if autos > 0.0 && it.auto_l { x += free / autos; }+ let mut tmp = Out::new(out.pw);+ let h = block(&it.items, x, x + w[k], y, sc, f, &mut tmp) - y;+ line_h = line_h.max(h);+ cells.push((tmp, h, if it.align != 0 { it.align } else { sp.align }));+ x += w[k] + gap + between + if autos > 0.0 && it.auto_r { free / autos } else { 0.0 };+ }+ for (mut tmp, h, al) in cells {+ let dy = match al { 2 => (line_h - h) / 2.0, 3 => line_h - h, _ => 0.0 };+ for p in &mut tmp.placed { p.base += dy; }+ for r in &mut tmp.rects { r.y += dy; }+ out.placed.extend(tmp.placed);+ out.rects.extend(tmp.rects);+ }+ y += line_h + if li + 1 < lines.len() { gap } else { 0.0 };+ }+ y+}++/// Start column of every cell (cells covered by a rowspan from an earlier row are skipped) and the column count.+fn grid(t: &Table) -> (usize, Vec<Vec<usize>>) {+ let (mut busy, mut n, mut starts) = (Vec::<usize>::new(), 0, vec![]);+ for row in &t.rows {+ let (mut col, mut rs) = (0, vec![]);+ for cell in &row.cells {+ while busy.get(col).is_some_and(|&b| b > 0) { col += 1; }+ let span = if cell.colspan >= 1000 { 1 } else { cell.colspan.max(1) };+ if busy.len() < col + span { busy.resize(col + span, 0); }+ for b in &mut busy[col..col + span] { *b = cell.rowspan.max(1); }+ rs.push(col);+ col += span;+ n = n.max(col);+ }+ for b in &mut busy { *b = b.saturating_sub(1); }+ starts.push(rs);+ }+ (n, starts)+}++/// Per-column (min, max) widths including cell padding.+fn col_metrics(t: &Table, sc: f32, f: &mut Fonts) -> (Vec<f32>, Vec<f32>) {+ let (n, starts) = grid(t);+ let (mut cmin, mut cmax) = (vec![0f32; n], vec![0f32; n]);+ let mut spans = vec![];+ for (r, row) in t.rows.iter().enumerate() {+ for (k, cell) in row.cells.iter().enumerate() {+ let col = starts[r][k];+ if col >= n { continue; }+ let span = cell.colspan.min(n - col).max(1);+ let (mn, mx) = measure(&cell.items, sc, f);+ let padw = (cell.pad[1] + cell.pad[3]) * sc;+ let (mut mn, mut mx) = (mn + padw, mx + padw);+ if cell.nowrap { mn = mx; }+ if let Some(Len::Px(p)) = cell.width { mx = mn.max(p * sc + padw); }+ if span == 1 { cmin[col] = cmin[col].max(mn); cmax[col] = cmax[col].max(mx); } else { spans.push((col, span, mn, mx)); }+ }+ }+ for (col, span, mn, mx) in spans {+ for (v, need) in [(&mut cmin, mn), (&mut cmax, mx)] {+ let cur: f32 = v[col..col + span].iter().sum();+ if need > cur { let add = (need - cur) / span as f32; for c in &mut v[col..col + span] { *c += add; } }+ }+ }+ for i in 0..n { cmax[i] = cmax[i].max(cmin[i]); }+ (cmin, cmax)+}++fn table(t: &Table, left: f32, right: f32, y0: f32, sc: f32, f: &mut Fonts, out: &mut Out) -> f32 {+ let avail = right - left;+ let (cmin, cmax) = col_metrics(t, sc, f);+ let n = cmin.len();+ if n == 0 { return y0; }+ let sp = t.spacing * sc;+ let total_sp = sp * (n as f32 + 1.0);+ let (smin, smax) = (cmin.iter().sum::<f32>(), cmax.iter().sum::<f32>());+ let table_w = match t.width { Some(w) => resolve(w, avail, sc).min(avail), None => (smax + total_sp).min(avail) }.max(1.0);+ let space = (table_w - total_sp).max(0.0);+ let widths: Vec<f32> = if space >= smax {+ let extra = space - smax;+ cmax.iter().map(|m| m + if smax > 0.0 { extra * m / smax } else { extra / n as f32 }).collect()+ } else if space <= smin {+ cmin.clone()+ } else {+ let k = (space - smin) / (smax - smin);+ (0..n).map(|i| cmin[i] + (cmax[i] - cmin[i]) * k).collect()+ };+ let used = widths.iter().sum::<f32>() + total_sp;+ let tx = left + match t.align { 1 => ((avail - used) / 2.0).max(0.0), 2 => (avail - used).max(0.0), _ => 0.0 };+ let bg_pos = out.rects.len();+ let (_, starts) = grid(t);+ // pass 1: lay every cell out at the top of its row (y = 0) and measure; rowspan cells only stretch the last row they cover+ struct C<'a> { cell: &'a crate::render::Cell, tmp: Out, row: usize, cx0: f32, cw: f32, h: f32, rs: usize }+ let (mut cells, mut row_h) = (vec![], vec![0f32; t.rows.len()]);+ for (r, row) in t.rows.iter().enumerate() {+ for (k, cell) in row.cells.iter().enumerate() {+ let col = starts[r][k];+ if col >= n { continue; }+ let span = cell.colspan.min(n - col).max(1);+ let cw = widths[col..col + span].iter().sum::<f32>() + sp * (span as f32 - 1.0);+ let cx0 = tx + sp + widths[..col].iter().sum::<f32>() + sp * col as f32;+ let [pt, pr, pb, pl] = cell.pad.map(|p| p * sc);+ let mut tmp = Out::new(out.pw);+ let h = block(&cell.items, cx0 + pl, cx0 + cw - pr, pt, sc, f, &mut tmp) + pb;+ let rs = cell.rowspan.clamp(1, t.rows.len() - r);+ if rs == 1 { row_h[r] = row_h[r].max(h); }+ cells.push(C { cell, tmp, row: r, cx0, cw, h, rs });+ }+ }+ for c in cells.iter().filter(|c| c.rs > 1) {+ let last = c.row + c.rs - 1;+ let have = row_h[c.row..=last].iter().sum::<f32>() + sp * (c.rs as f32 - 1.0);+ if c.h > have { row_h[last] += c.h - have; }+ }+ let mut tops = vec![];+ let mut y = y0 + sp;+ for h in &row_h { tops.push(y); y += h + sp; }+ for (r, row) in t.rows.iter().enumerate() {+ if let Some(color) = row.bg { out.rects.push(Rect { x: tx + sp, y: tops[r], w: used - 2.0 * sp, h: row_h[r], color, r: 0.0, ring: 0.0, node: 0, z: 0, a: 255, grad: None, pic: None, st: f32::NAN, lim: f32::NAN, grp: 0, scroll: f32::NAN }); }+ }+ for mut c in cells {+ let (top, full) = (tops[c.row], row_h[c.row..c.row + c.rs].iter().sum::<f32>() + sp * (c.rs as f32 - 1.0));+ if let Some(color) = c.cell.bg { out.rects.push(Rect { x: c.cx0, y: top, w: c.cw, h: full, color, r: 0.0, ring: 0.0, node: 0, z: 0, a: 255, grad: None, pic: None, st: f32::NAN, lim: f32::NAN, grp: 0, scroll: f32::NAN }); }+ if t.border > 0.0 { outline(&mut out.rects, c.cx0, top, c.cw, full, (t.border * sc).round().max(1.0)); }+ let dy = top + match c.cell.valign { 1 => (full - c.h) / 2.0, 2 => full - c.h, _ => 0.0 };+ for p in &mut c.tmp.placed { p.base += dy; }+ for r in &mut c.tmp.rects { r.y += dy; }+ out.rects.extend(c.tmp.rects);+ out.placed.extend(c.tmp.placed);+ }+ if let Some(color) = t.bg { out.rects.insert(bg_pos, Rect { x: tx, y: y0, w: used, h: y - y0, color, r: 0.0, ring: 0.0, node: 0, z: 0, a: 255, grad: None, pic: None, st: f32::NAN, lim: f32::NAN, grp: 0, scroll: f32::NAN }); }+ if t.border > 0.0 { outline(&mut out.rects, tx, y0, used, y - y0, (t.border * sc).round().max(1.0)); }+ y+}++fn outline(rects: &mut Vec<Rect>, x: f32, y: f32, w: f32, h: f32, b: f32) {+ let color = 0x888888;+ rects.push(Rect { x, y, w, h: b, color, r: 0.0, ring: 0.0, node: 0, z: 0, a: 255, grad: None, pic: None, st: f32::NAN, lim: f32::NAN, grp: 0, scroll: f32::NAN });+ rects.push(Rect { x, y: y + h - b, w, h: b, color, r: 0.0, ring: 0.0, node: 0, z: 0, a: 255, grad: None, pic: None, st: f32::NAN, lim: f32::NAN, grp: 0, scroll: f32::NAN });+ rects.push(Rect { x, y, w: b, h, color, r: 0.0, ring: 0.0, node: 0, z: 0, a: 255, grad: None, pic: None, st: f32::NAN, lim: f32::NAN, grp: 0, scroll: f32::NAN });+ rects.push(Rect { x: x + w - b, y, w: b, h, color, r: 0.0, ring: 0.0, node: 0, z: 0, a: 255, grad: None, pic: None, st: f32::NAN, lim: f32::NAN, grp: 0, scroll: f32::NAN });+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::{dom::parse, render};+ use std::collections::HashMap;++ fn fonts() -> Option<Fonts> {+ let data = ["C:\\Windows\\Fonts\\segoeui.ttf", "C:\\Windows\\Fonts\\arial.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"].iter().find_map(|p| std::fs::read(p).ok())?;+ Some(Fonts::new(fontdue::Font::from_bytes(data, fontdue::FontSettings::default()).ok()?, None))+ }++ fn lay(html: &str, width: f32) -> Option<(Vec<Placed>, Vec<Rect>, f32)> {+ let mut f = fonts()?;+ let pg = render::build(&parse(html, true), "https://a.com", HashMap::new());+ Some(layout(&pg.items, width, 1.0, &mut f))+ }++ #[test]+ fn table_columns_sit_side_by_side() {+ let Some((p, _, _)) = lay("<table cellspacing=0><tr><td>alpha</td><td>beta</td></tr><tr><td>gamma delta</td><td>x</td></tr></table>", 800.0) else { return };+ let x = |t: &str| p.iter().find(|q| q.text == t).unwrap();+ assert!(x("beta").x > x("alpha").x + 20.0);+ assert_eq!(x("beta").x, x("x").x); // same column+ assert!(x("gamma").base > x("alpha").base); // second row below+ assert_eq!(x("alpha").x, x("gamma").x);+ }++ #[test]+ fn centered_max_width_box_and_background() {+ let Some((p, r, _)) = lay("<div style='max-width:300px;margin:0 auto;background:#eee;padding:0 10px'>hello world</div>", 1000.0) else { return };+ let hello = p.iter().find(|q| q.text == "hello").unwrap();+ assert!(hello.x > 300.0 && hello.x < 400.0, "x={}", hello.x); // (968-320)/2 + 16 + padding+ let bg = r.iter().find(|q| q.color == 0xEEEEEE).unwrap();+ assert!((bg.w - 320.0).abs() < 1.0 && bg.x < hello.x);+ }++ #[test]+ fn table_width_percent_and_center_align() {+ let Some((p, _, _)) = lay("<center><table width=50%><tr><td>a</td></tr></table></center>", 1000.0) else { return };+ let a = p.iter().find(|q| q.text == "a").unwrap();+ assert!(a.x > 200.0, "x={}", a.x); // centered 484px table: starts at ~258+ }++ #[test]+ fn text_wraps_around_a_float_and_clear_ends_it() {+ let words = "word ".repeat(60);+ let Some((p, _, h)) = lay(&format!("<div style='float:right;width:200px'>box</div><p>{words}</p><div style='clear:both'>after</div>"), 600.0) else { return };+ let boxw = p.iter().find(|q| q.text == "box").unwrap();+ assert!(boxw.x > 380.0, "float on the right edge, x={}", boxw.x);+ let first = p.iter().find(|q| q.text == "word").unwrap();+ let right_edge_first_line = p.iter().filter(|q| q.text == "word" && (q.base - first.base).abs() < 1.0).map(|q| q.x + q.w).fold(0.0, f32::max);+ assert!(right_edge_first_line < boxw.x, "first line must stop before the float: {right_edge_first_line} vs {}", boxw.x);+ let last_word = p.iter().rev().find(|q| q.text == "word").unwrap();+ let after = p.iter().find(|q| q.text == "after").unwrap();+ assert!(after.base > last_word.base);+ assert!(h > after.base);+ }++ fn at<'a>(p: &'a [Placed], t: &str) -> &'a Placed { p.iter().find(|q| q.text == t).unwrap_or_else(|| panic!("no {t}")) }++ #[test]+ fn fixed_boxes_live_in_the_viewport_layer_and_z_index_orders_layers() {+ let Some((p, r, _)) = lay("<p>one</p><p>two</p><div style='position:fixed;bottom:0;left:0;width:200px;background:#abcdef'>bar</div><div style='position:absolute;top:0;left:0;z-index:5'>hi</div><div style='position:absolute;top:0;left:0;z-index:-1;background:#123456'>lo</div>", 800.0) else { return };+ let bar = at(&p, "bar");+ assert!(bar.z >= FIXED_Z && bar.base > 650.0 && bar.base <= 720.0, "bottom:0 sits at the bottom of the 720px viewport: {}", bar.base);+ assert!(r.iter().any(|q| q.color == 0xABCDEF && q.z >= FIXED_Z));+ assert!(at(&p, "hi").z > at(&p, "one").z && at(&p, "lo").z < at(&p, "one").z, "layers: {} {} {}", at(&p, "lo").z, at(&p, "one").z, at(&p, "hi").z);+ assert_eq!(layers(&p, &r).first().map(|l| l.0), Some(at(&p, "lo").z), "layers come out ascending");+ let Some((p, _, _)) = lay("<p>x</p><div style='position:absolute;top:0;left:0;background:#fff'>over</div>", 800.0) else { return };+ assert!(at(&p, "over").z > at(&p, "x").z, "positioned boxes paint above in-flow content");+ }++ #[test]+ fn column_flex_stacks_with_gap_and_aligns_across() {+ let Some((p, _, _)) = lay("<div style='display:flex;flex-direction:column;gap:20px'><div>aa</div><div>bb</div></div>", 600.0) else { return };+ assert!((at(&p, "aa").x - at(&p, "bb").x).abs() < 1.0 && at(&p, "bb").base - at(&p, "aa").base > 30.0, "stacked: {} {}", at(&p, "aa").base, at(&p, "bb").base);+ let Some((p, _, _)) = lay("<div style='display:flex;flex-direction:column;align-items:center'><div>mid</div></div>", 600.0) else { return };+ assert!(at(&p, "mid").x > 250.0, "centered across: {}", at(&p, "mid").x);+ let Some((p, _, _)) = lay("<div style='display:flex;flex-direction:column;align-items:flex-end'><div>end</div></div>", 600.0) else { return };+ assert!(at(&p, "end").x > 500.0, "end-aligned: {}", at(&p, "end").x);+ }++ #[test]+ fn grid_columns_rows_gaps_and_spans() {+ let Some((p, _, _)) = lay("<div style='display:grid;grid-template-columns:repeat(3,1fr);gap:10px'><div>a</div><div>b</div><div>c</div><div>d</div></div>", 1016.0) else { return };+ // avail 984: (984 - 20) / 3 = 321.33 per column+ let (a, b, c, d) = (at(&p, "a"), at(&p, "b"), at(&p, "c"), at(&p, "d"));+ assert!((b.x - a.x - 331.33).abs() < 2.0 && (c.x - b.x - 331.33).abs() < 2.0, "{} {} {}", a.x, b.x, c.x);+ assert!((a.base - b.base).abs() < 1.0 && d.base > a.base + 15.0 && (d.x - a.x).abs() < 1.0, "fourth item wraps to row two");+ let Some((p, _, _)) = lay("<div style='display:grid;grid-template-columns:100px 1fr'><div>l</div><div>r</div></div>", 600.0) else { return };+ assert!((at(&p, "r").x - at(&p, "l").x - 100.0).abs() < 1.0, "fixed first track");+ let Some((p, _, _)) = lay("<div style='display:grid;grid-template-columns:1fr 1fr'><div style='grid-column:span 2'>wide</div><div>n1</div><div>n2</div></div>", 600.0) else { return };+ assert!(at(&p, "n1").base > at(&p, "wide").base + 10.0 && at(&p, "n2").x > at(&p, "n1").x + 100.0);+ let Some((p, _, _)) = lay("<div style='display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr))'><div>1</div><div>2</div><div>3</div><div>4</div></div>", 616.0) else { return };+ // 584px fits two 200px columns; the third item starts row two+ assert!((at(&p, "1").base - at(&p, "2").base).abs() < 1.0 && at(&p, "3").base > at(&p, "1").base + 10.0, "auto-fill packs columns");+ }++ #[test]+ fn overflow_hidden_with_height_clips_and_shadow_and_gradient_emit_rects() {+ let Some((p, r, _)) = lay("<div style='height:40px;overflow:hidden;background:#abcdef'>l1<br>l2<br>l3<br>l4<br>l5<br>l6</div><p>after</p>", 600.0) else { return };+ assert!(p.iter().all(|q| q.text != "l6") && p.iter().any(|q| q.text == "l1"), "lines below the box are cut");+ let bg = r.iter().find(|q| q.color == 0xABCDEF).unwrap();+ assert!((bg.h - 40.0).abs() < 1.0 && at(&p, "after").base > bg.y + 40.0, "box is exactly 40px tall");+ let Some((_, r, _)) = lay("<div style='background:#ffffff;box-shadow:0 4px 8px rgba(0,0,0,.4)'>x</div>", 600.0) else { return };+ let shadows: Vec<_> = r.iter().filter(|q| q.color == 0 && q.a < 255).collect();+ assert!(shadows.len() >= 3 && shadows.windows(2).all(|w| w[0].w >= w[1].w), "layers shrink inward: {}", shadows.len());+ assert!(shadows[0].y > r.iter().find(|q| q.color == 0xFFFFFF).unwrap().y - 6.0);+ let Some((_, r, _)) = lay("<div style='background:linear-gradient(90deg,#ff0000,#0000ff)'>x</div><div style='background:rgba(255,0,0,.5)'>y</div>", 600.0) else { return };+ assert!(r.iter().any(|q| q.grad.is_some()) && r.iter().any(|q| q.a == 128 && q.color == 0xFF0000));+ }++ #[test]+ fn letter_spacing_vertical_align_and_opacity_change_text() {+ let Some((p, _, _)) = lay("<span>abcd</span> <span style='letter-spacing:5px'>abcd</span>", 600.0) else { return };+ let w: Vec<f32> = p.iter().map(|q| q.w).collect();+ assert!((w[1] - w[0] - 20.0).abs() < 1.0, "4 letters x 5px: {w:?}");+ let Some((p, _, _)) = lay("x<sup>up</sup>y<sub>dn</sub>", 600.0) else { return };+ let (up, dn) = (at(&p, "up"), at(&p, "dn"));+ assert!(up.base < dn.base - 3.0, "superscript sits above subscript: {} {}", up.base, dn.base);+ let Some((p, _, _)) = lay("<p style='opacity:.5;color:#000000'>faded</p>", 600.0) else { return };+ let c = at(&p, "faded").color;+ assert!(c > 0x606060 && c < 0xA0A0A0, "black at 50% over white is mid gray: {c:06x}");+ }++ fn lay_with(html: &str, width: f32, imgs: impl Fn(&crate::dom::Dom) -> HashMap<usize, crate::load::Img>) -> Option<(Vec<Placed>, Vec<Rect>, f32)> {+ let mut f = fonts()?;+ let dom = parse(html, true);+ let pg = render::build(&dom, "https://a.com", imgs(&dom));+ Some(layout(&pg.items, width, 1.0, &mut f))+ }++ fn pic(w: u32, h: u32) -> crate::load::Img { crate::load::Img { w, h, px: vec![255; (w * h * 4) as usize] } }++ #[test]+ fn percentage_heights_need_a_definite_parent_and_never_clip_the_page() {+ let Some((_, r, _)) = lay("<div style='height:200px'><div style='height:50%;background:#abcdef'>x</div></div>", 600.0) else { return };+ let bg = r.iter().find(|q| q.color == 0xABCDEF).unwrap();+ assert!((bg.h - 100.0).abs() < 1.0, "half of the 200px parent: {}", bg.h);+ let Some((_, r, _)) = lay("<div><div style='height:50%;background:#abcdef'>x</div></div>", 600.0) else { return };+ assert!(r.iter().find(|q| q.color == 0xABCDEF).unwrap().h < 40.0, "auto parent: the percentage is ignored");+ let lines = "line<br>".repeat(80);+ let Some((p, _, h)) = lay(&format!("<html style='height:100%'><body style='height:100%;overflow:hidden'>{lines}"), 600.0) else { return };+ assert!(h > 1000.0 && p.len() >= 80, "html/body are never clipped: {} placed, height {h}", p.len());+ let Some((_, r, _)) = lay("<div style='height:300px;overflow:hidden'><div style='height:50%;overflow:hidden;background:#abcdef'>a<br>b<br>c<br>d<br>e<br>f</div></div>", 600.0) else { return };+ assert!(r.iter().find(|q| q.color == 0xABCDEF).unwrap().h >= 100.0, "a percentage height is a floor here, not a clip");+ }++ #[test]+ fn percentage_width_images_fill_their_share_of_the_line() {+ let run = |css: &str| lay_with(&format!("<img src=a.png style='{css}'>"), 616.0, |d| HashMap::from([(d.find("img").unwrap(), pic(100, 40))])).map(|r| r.0);+ let (Some(a), Some(b)) = (run("width:50%"), run("width:100%")) else { return };+ let im = |p: &[Placed]| { let q = p.iter().find(|q| q.img.is_some()).unwrap(); (q.w, q.size) };+ assert!((im(&a).0 - 292.0).abs() < 1.0 && (im(&a).1 - 116.8).abs() < 1.0, "{:?}", im(&a));+ assert!((im(&b).0 - 584.0).abs() < 1.0 && (im(&b).1 - 233.6).abs() < 1.0, "{:?}", im(&b));+ }++ #[test]+ fn images_follow_vertical_align_middle_and_opacity() {+ let base = |css: &str| lay_with(&format!("x<img src=a.png width=20 height=40 style='{css}'>y"), 600.0, |d| HashMap::from([(d.find("img").unwrap(), pic(20, 40))])).map(|r| r.0);+ let (Some(a), Some(b)) = (base(""), base("vertical-align:middle")) else { return };+ let im = |p: &[Placed]| p.iter().find(|q| q.img.is_some()).unwrap().base;+ assert!(im(&b) > im(&a) + 10.0, "middle lowers a tall picture toward the text: {} vs {}", im(&b), im(&a));+ let Some(c) = base("opacity:.5") else { return };+ assert_eq!(c.iter().find(|q| q.img.is_some()).unwrap().color, 128);+ assert_eq!(a.iter().find(|q| q.img.is_some()).unwrap().color, 255);+ }++ #[test]+ fn background_images_are_sized_positioned_and_repeated() {+ let html = |css: &str| format!("<div id=b style='height:100px;{css}'>x</div>");+ let run = |css: &str| lay_with(&html(css), 616.0, |d| HashMap::from([(usize::MAX - d.find("div").unwrap(), pic(40, 20))])).map(|r| r.1);+ let (Some(r), Some(c), Some(v)) = (run("background:url(a.png) no-repeat right center / 20px 20px"), run("background:url(a.png) center / cover no-repeat"), run("background-image:url(a.png)")) else { return };+ let p = r.iter().find_map(|q| q.pic).expect("image rect");+ assert!((p.w, p.h) == (20.0, 20.0) && !p.rx && !p.ry, "{} {}", p.w, p.h);+ assert!((p.ox - (584.0 - 20.0)).abs() < 1.0 && (p.oy - 40.0).abs() < 1.0, "right center: {} {}", p.ox, p.oy);+ let p = c.iter().find_map(|q| q.pic).unwrap();+ assert!(p.w >= 584.0 - 0.5 && p.h >= 100.0 - 0.5, "cover fills the box: {} {}", p.w, p.h);+ let p = v.iter().find_map(|q| q.pic).unwrap();+ assert!((p.w, p.h, p.rx, p.ry) == (40.0, 20.0, true, true), "natural size, tiled both ways");+ }++ #[test]+ fn fixed_and_sticky_boxes_get_a_pin_offset() {+ let Some((p, r, _)) = lay("<p>a</p><p>b</p><div style='position:sticky;top:10px;background:#abcdef'>stuck</div><div style='position:fixed;top:0;left:0'>bar</div>", 600.0) else { return };+ let stuck = at(&p, "stuck");+ assert!(stuck.st.is_finite() && (stuck.st - (stuck.base - stuck.size - 10.0)).abs() < 25.0, "pins when its top reaches 10px below the viewport top: st {} base {}", stuck.st, stuck.base);+ assert!(r.iter().find(|q| q.color == 0xABCDEF).unwrap().st.is_finite());+ assert_eq!(at(&p, "bar").st, 0.0, "fixed = pinned from the first pixel of scrolling");+ assert!(at(&p, "a").st.is_nan());+ assert!((stuck.base - at(&p, "b").base) > 10.0, "sticky keeps its normal place until the page scrolls");+ }++ #[test]+ fn nested_stacking_contexts_cannot_escape_their_parent() {+ let Some((p, _, _)) = lay("<div style='position:absolute;top:0;left:0;z-index:5'>outer<div style='position:absolute;top:0;left:0;z-index:100'>deep</div></div><div style='position:absolute;top:0;left:0;z-index:6'>sibling</div><p>flow</p>", 800.0) else { return };+ let (outer, deep, sib, flow) = (at(&p, "outer").z, at(&p, "deep").z, at(&p, "sibling").z, at(&p, "flow").z);+ assert!(deep > outer, "a child paints above its own context's content");+ assert!(deep < sib, "but a z-index:100 child of a z-index:5 context stays below a z-index:6 sibling: {deep} vs {sib}");+ assert!(outer > flow && sib > outer);+ // a relative box with a z-index is a context too+ let Some((p, _, _)) = lay("<div style='position:relative;z-index:2'>rel<div style='position:absolute;top:0;z-index:50'>kid</div></div><div style='position:absolute;z-index:3'>top</div>", 800.0) else { return };+ assert!(at(&p, "kid").z < at(&p, "top").z && at(&p, "kid").z > at(&p, "rel").z);+ let Some((p, _, _)) = lay("<div style='position:fixed;top:0;z-index:1'>fix</div><div style='position:absolute;z-index:9999'>abs</div>", 800.0) else { return };+ assert!(at(&p, "fix").z > at(&p, "abs").z, "fixed boxes paint on top of everything");+ }++ #[test]+ fn sticky_boxes_are_held_back_by_their_container() {+ let Some((p, _, _)) = lay("<div style='height:300px'><div style='position:sticky;top:0'>s</div></div><p>after</p>", 600.0) else { return };+ let s = at(&p, "s");+ assert!(s.lim.is_finite() && s.lim > 250.0 && s.lim < 300.0, "may travel about the container's height: {}", s.lim);+ let Some((p, _, _)) = lay("<div style='position:sticky;top:0'>solo</div><p>x</p><p>y</p>", 600.0) else { return };+ assert!(at(&p, "solo").lim > 20.0, "inside the page the container is the page");+ assert!(at(&p, "x").lim.is_nan());+ }++ #[test]+ fn plain_boxes_leave_an_invisible_geometry_marker() {+ let Some((_, r, _)) = lay("<div style='width:200px;padding:6px'>text</div>", 600.0) else { return };+ let m = r.iter().find(|q| q.node != 0 && q.a == 0).expect("marker for a box without background");+ assert!((m.w - 212.0).abs() < 1.5 && m.h > 20.0 && m.scroll.is_nan(), "{} x {}", m.w, m.h);+ let Some((p, r, _)) = lay("<div style='width:200px;padding:6px;background:#abcdef'>text</div>", 600.0) else { return };+ assert!(r.iter().all(|q| q.a != 0) && !p.is_empty(), "a box that has a background needs no marker");+ assert_eq!(crate::browse::hit_node(&[], &r, 20.0, 25.0) != 0, true, "hit-testing finds the box in its empty padding");+ }++ #[test]+ fn overflow_auto_with_a_height_makes_a_scroll_container() {+ let Some((p, r, _)) = lay("<div style='height:60px;overflow:auto;background:#abcdef'>l1<br>l2<br>l3<br>l4<br>l5<br>l6<br>l7<br>l8</div><p>after</p>", 600.0) else { return };+ let g = groups(&r);+ assert_eq!(g.len(), 1);+ let b = g.values().next().unwrap();+ assert!((b.h - 60.0).abs() < 1.0 && b.content_h > 150.0, "box {} content {}", b.h, b.content_h);+ assert!(p.iter().any(|q| q.text == "l8" && q.grp != 0), "content is kept (not cut) and tagged with the container");+ assert!(at(&p, "after").grp == 0 && at(&p, "after").base > b.y + 60.0, "the page continues below the 60px box");+ let bg = r.iter().find(|q| q.color == 0xABCDEF).unwrap();+ assert!((bg.h - 60.0).abs() < 1.0 && bg.grp == 0, "the background stays still while the content scrolls");+ // overflow: hidden keeps cutting instead+ let Some((p, r, _)) = lay("<div style='height:60px;overflow:hidden'>l1<br>l2<br>l3<br>l4<br>l5<br>l6<br>l7<br>l8</div>", 600.0) else { return };+ assert!(groups(&r).is_empty() && p.iter().all(|q| q.text != "l8"));+ // a container without a fixed height does not scroll+ let Some((_, r, _)) = lay("<div style='overflow:auto'>l1<br>l2<br>l3</div>", 600.0) else { return };+ assert!(groups(&r).is_empty());+ }++ #[test]+ fn counters_number_ordered_lists_and_generated_content() {+ let Some((p, _, _)) = lay("<ol><li>a</li><li>b</li></ol><ol start=5><li>c</li></ol>", 600.0) else { return };+ let marks: Vec<&str> = p.iter().filter(|q| q.text.ends_with('.')).map(|q| q.text.as_str()).collect();+ assert_eq!(marks, vec!["1.", "2.", "5."]);+ let Some((p, _, _)) = lay("<style>body{counter-reset:sec} h2{counter-increment:sec} h2::before{content:'Part ' counter(sec) ': '}</style><h2>one</h2><h2>two</h2>", 600.0) else { return };+ assert!(p.iter().any(|q| q.text == "1:") && p.iter().any(|q| q.text == "2:"), "{:?}", p.iter().map(|q| q.text.clone()).collect::<Vec<_>>());+ }++ #[test]+ fn line_height_spaces_lines() {+ let Some((p, _, _)) = lay("<p style='line-height:3'>aaa<br>bbb</p><p>ccc<br>ddd</p>", 600.0) else { return };+ let (a, b, c, d) = (at(&p, "aaa").base, at(&p, "bbb").base, at(&p, "ccc").base, at(&p, "ddd").base);+ assert!(((b - a) - 48.0).abs() < 1.0, "3x16px lines: {}", b - a);+ assert!(((d - c) - 21.6).abs() < 1.0, "default 1.35: {}", d - c);+ }++ #[test]+ fn inline_blocks_sit_side_by_side_and_wrap() {+ let Some((p, r, _)) = lay("<span style='display:inline-block;width:100px;background:#abcdef'>one</span><span style='display:inline-block;width:100px'>two</span><span style='display:inline-block;width:300px'>three</span>", 400.0) else { return };+ let (one, two, three) = (at(&p, "one"), at(&p, "two"), at(&p, "three"));+ assert!(two.x > one.x + 90.0 && (two.base - one.base).abs() < 1.0, "same line: {} {}", one.x, two.x);+ assert!(three.base > two.base + 5.0, "third wraps to the next line");+ assert!(r.iter().any(|q| q.color == 0xABCDEF && (q.w - 100.0).abs() < 1.0));+ }++ #[test]+ fn flex_row_grow_justify_and_gap() {+ let Some((p, _, _)) = lay("<div style='display:flex;gap:10px'><div style='flex:1'>a</div><div style='flex:3'>b</div></div>", 1016.0) else { return };+ // avail 984: flex:1 and flex:3 split (984-10) as 1:3 -> second starts at 16 + 243.5 + 10+ let (a, b) = (at(&p, "a"), at(&p, "b"));+ assert!((b.x - a.x - 253.5).abs() < 2.0, "{}", b.x - a.x);+ let Some((p, _, _)) = lay("<div style='display:flex;justify-content:space-between'><span>l</span><span>r</span></div>", 600.0) else { return };+ assert!(at(&p, "r").x > 500.0 && at(&p, "l").x < 40.0);+ let Some((p, _, _)) = lay("<div style='display:flex'><span>l</span><span style='margin-left:auto'>r</span></div>", 600.0) else { return };+ assert!(at(&p, "r").x > 500.0, "auto margin pushes right: {}", at(&p, "r").x);+ }++ #[test]+ fn flex_wrap_and_align_center() {+ let Some((p, _, _)) = lay("<div style='display:flex;flex-wrap:wrap'><div style='width:300px'>a</div><div style='width:300px'>b</div><div style='width:300px'>c</div></div>", 700.0) else { return };+ assert!(at(&p, "c").base > at(&p, "a").base + 5.0 && (at(&p, "b").base - at(&p, "a").base).abs() < 1.0);+ let Some((p, _, _)) = lay("<div style='display:flex;align-items:center'><div>x<br>y<br>z</div><div>m</div></div>", 600.0) else { return };+ assert!((at(&p, "m").base - at(&p, "y").base).abs() < 1.0, "m centered against 3-line sibling");+ }++ #[test]+ fn absolute_and_relative_positioning() {+ let Some((p, _, _)) = lay("<div style='position:relative;height:200px'>top<span style='position:absolute;right:10px;top:50px;width:60px'>abs</span></div>", 800.0) else { return };+ let (t, a) = (at(&p, "top"), at(&p, "abs"));+ assert!((a.x - (800.0 - 16.0 - 10.0 - 60.0)).abs() < 2.0, "right edge of containing block: {}", a.x);+ assert!(a.base > t.base + 40.0, "top offset applies: {} vs {}", a.base, t.base);+ let Some((p, _, h)) = lay("<p>before</p><div style='position:relative;left:30px;top:5px'>moved</div><p>after</p>", 800.0) else { return };+ let (b, m, af) = (at(&p, "before"), at(&p, "moved"), at(&p, "after"));+ assert!((m.x - b.x - 30.0).abs() < 1.0 && m.base > b.base + 20.0);+ assert!(af.base > m.base && h > af.base);+ let Some((p, _, _)) = lay("<p>one</p><div style='position:absolute;left:100px;top:300px'>free</div><p>two</p>", 800.0) else { return };+ assert!((at(&p, "free").x - 100.0).abs() < 1.0 && (at(&p, "free").base - 300.0).abs() < 30.0);+ assert!(at(&p, "two").base < 120.0, "absolute takes no flow space");+ }++ #[test]+ fn min_height_and_border_box() {+ let Some((p, r, _)) = lay("<div style='min-height:100px;background:#abcdef'>x</div><p>after</p>", 600.0) else { return };+ let bg = r.iter().find(|q| q.color == 0xABCDEF).unwrap();+ assert!(bg.h >= 100.0 && at(&p, "after").base > bg.y + 100.0, "h={}", bg.h);+ let Some((_, r, _)) = lay("<div style='box-sizing:border-box;width:300px;padding:0 20px;background:#abcdef'>x</div>", 600.0) else { return };+ assert!((r.iter().find(|q| q.color == 0xABCDEF).unwrap().w - 300.0).abs() < 1.0);+ let Some((_, r, _)) = lay("<div style='width:300px;padding:0 20px;background:#abcdef'>x</div>", 600.0) else { return };+ assert!((r.iter().find(|q| q.color == 0xABCDEF).unwrap().w - 340.0).abs() < 1.0);+ }++ #[test]+ fn rowspan_skips_covered_columns_and_stretches_rows() {+ let Some((p, _, _)) = lay("<table cellspacing=0><tr><td rowspan=2>tall<br>tall2<br>tall3</td><td>a</td></tr><tr><td>b</td><td>c</td></tr><tr><td>d</td><td>e</td></tr></table>", 800.0) else { return };+ let (a, b, c, d) = (at(&p, "a"), at(&p, "b"), at(&p, "c"), at(&p, "d"));+ assert!(b.x > a.x - 1.0 && (b.x - a.x).abs() < 1.0, "b sits in a's column, right of the tall cell: {} {}", a.x, b.x);+ assert!(c.x > b.x + 5.0, "c is the extra third column");+ assert!(d.base > at(&p, "tall3").base - 1.0, "row 3 starts below the tall cell: {} vs {}", d.base, at(&p, "tall3").base);+ assert!(at(&p, "tall").x < a.x);+ }++ #[test]+ fn inline_block_shrinks_to_fit_with_padding() {+ let Some((p, _, _)) = lay("<span style='display:inline-block;padding:0 14px;background:#abcdef'>pill button</span>", 600.0) else { return };+ assert!((at(&p, "pill").base - at(&p, "button").base).abs() < 1.0, "one line");+ }++ #[test]+ fn nowrap_keeps_a_run_together_and_text_indent_moves_the_first_line() {+ let Some((p, _, _)) = lay("<div style='width:100px;white-space:nowrap'>alpha beta gamma</div>", 600.0) else { return };+ assert_eq!(p.len(), 1, "one unbreakable run");+ let Some((p, _, _)) = lay("<p style='text-indent:40px'>first line text that is long enough to wrap onto a second line in this narrow box of text</p>", 220.0) else { return };+ let first = p.iter().find(|q| q.text == "first").unwrap();+ let second_line = p.iter().find(|q| q.base > first.base + 5.0).unwrap();+ assert!((first.x - 56.0).abs() < 1.0 && (second_line.x - 16.0).abs() < 1.0, "{} {}", first.x, second_line.x);+ let Some((p, _, _)) = lay("<h1 style='text-indent:-9999px'>hidden</h1><p>shown</p>", 600.0) else { return };+ assert!(p.iter().all(|q| q.text != "hidden"));+ }++ #[test]+ fn rounded_boxes_emit_rounded_rects_and_rings() {+ let Some((_, r, _)) = lay("<div style='border-radius:8px;background:#abcdef;border:2px solid #ff0000'>x</div>", 600.0) else { return };+ assert!(r.iter().any(|q| q.color == 0xABCDEF && q.r == 8.0 && q.ring == 0.0));+ assert!(r.iter().any(|q| q.color == 0xFF0000 && q.r == 8.0 && q.ring == 2.0));+ assert_eq!(r.len(), 2);+ }++ #[test]+ fn borders_and_rules_produce_rects() {+ let Some((_, r, _)) = lay("<div style='border:2px solid #ff0000;padding:4px'>x</div><hr>", 600.0) else { return };+ assert!(r.iter().filter(|q| q.color == 0xFF0000).count() == 4);+ assert!(r.iter().any(|q| q.color == 0x999999 && q.w > 500.0));+ }++ #[test]+ fn rtl_lines_run_right_to_left_and_align_right() {+ let Some((p, _, _)) = lay("<p>\u{05e9}\u{05dc}\u{05d5}\u{05dd} \u{05e2}\u{05d5}\u{05dc}\u{05dd}</p>", 600.0) else { return };+ assert_eq!(p.len(), 2);+ assert!(p[0].x > p[1].x, "first word is on the right: {} {}", p[0].x, p[1].x);+ assert!(p[0].x + p[0].w > 560.0, "right aligned");+ let Some((p, _, _)) = lay("<p>one two</p>", 600.0) else { return };+ assert!(p[0].x < p[1].x && p[0].x < 20.0);+ }++ #[test]+ fn uax9_numbers_inside_rtl_keep_their_order_and_brackets_mirror() {+ // RTL paragraph: Hebrew, a number, Hebrew; logical order 1 2 3 shows as 3 2 1 from the left, the number stays one word+ let Some((p, _, _)) = lay("<p>\u{05d0}\u{05d1} 123 \u{05d2}\u{05d3}</p>", 600.0) else { return };+ let (a, n, g) = (&p[0], &p[1], &p[2]);+ assert!(a.x > n.x && n.x > g.x, "visual order right to left: {} {} {}", a.x, n.x, g.x);+ // a run of two numbers separated by a space keeps left-to-right order inside the RTL line (level 2)+ let Some((p, _, _)) = lay("<p>\u{05d0}\u{05d1} 12 34 \u{05d2}\u{05d3}</p>", 600.0) else { return };+ assert!(p[1].x < p[2].x, "12 comes before 34 from the left: {} {}", p[1].x, p[2].x);+ assert!(p[0].x > p[2].x && p[3].x < p[1].x);+ // a lone bracket in an RTL line is mirrored+ let Some((p, _, _)) = lay("<p>\u{05d0}\u{05d1} (</p>", 600.0) else { return };+ assert_eq!(p[1].text, ")");+ // an all-Latin line is untouched+ let Some((p, _, _)) = lay("<p>(a) b</p>", 600.0) else { return };+ assert_eq!(p[0].text, "(a)");+ }++ #[test]+ fn soft_hyphen_shows_a_hyphen_only_where_the_line_breaks() {+ let Some((p, _, _)) = lay("<p style='width:50px'>co\u{ad}operate</p>", 600.0) else { return };+ assert!(p.iter().any(|q| q.text == "co-") && p.iter().any(|q| q.text == "operate"), "{:?}", p.iter().map(|q| q.text.clone()).collect::<Vec<_>>());+ assert!(p.iter().find(|q| q.text == "operate").unwrap().base > p.iter().find(|q| q.text == "co-").unwrap().base + 5.0, "broken onto two lines");+ let Some((p, _, _)) = lay("<p>co\u{ad}operate</p>", 600.0) else { return };+ assert!(p.iter().all(|q| !q.text.contains('-') && !q.text.contains('\u{ad}')), "{:?}", p.iter().map(|q| q.text.clone()).collect::<Vec<_>>());+ assert!((p[0].base - p[1].base).abs() < 1.0 && (p[1].x - (p[0].x + p[0].w)).abs() < 1.0, "pieces sit together when it fits");+ }++ #[test]+ fn long_urls_and_hyphenated_words_wrap_at_uax14_opportunities() {+ let Some((p, _, h)) = lay("<p style='width:120px'>see https://example.com/some/long/path/name today</p>", 600.0) else { return };+ assert!(p.iter().any(|q| q.text == "path/") && h > 100.0, "long URL is broken at slashes instead of overflowing: {:?}", p.iter().map(|q| q.text.clone()).collect::<Vec<_>>());+ assert!(p.iter().all(|q| q.x + q.w < 16.0 + 140.0), "nothing sticks out of the 120px box");+ }++ #[test]+ fn mixed_direction_lines_keep_each_run_readable() {+ // LTR paragraph with a Hebrew run: label stays on the left, the two Hebrew words are swapped+ let Some((p, _, _)) = lay("<p>Label \u{05e9}\u{05dc}\u{05d5}\u{05dd} \u{05e2}\u{05d5}\u{05dc}\u{05dd}</p>", 600.0) else { return };+ assert!(p[0].x < 40.0 && p[1].x > p[2].x, "{:?}", p.iter().map(|q| q.x).collect::<Vec<_>>());+ // RTL paragraph with a Latin run: the Latin words keep left-to-right order+ let Some((p, _, _)) = lay("<p>\u{05e9}\u{05dc}\u{05d5}\u{05dd} one two</p>", 600.0) else { return };+ let (heb, one, two) = (&p[0], &p[1], &p[2]);+ assert!(heb.x > one.x && one.x < two.x, "{} {} {}", heb.x, one.x, two.x);+ }+}diff --git a/plugins/chrome-rs/src/load.rs b/plugins/chrome-rs/src/load.rsnew file mode 100644index 0000000..37c57cb--- /dev/null+++ b/plugins/chrome-rs/src/load.rs@@ -0,0 +1,805 @@+// Network + page pipeline (runs on a worker thread): fetch HTML, inline external CSS, run scripts, decode images,+// style the DOM. Returns a ready-to-layout Page; the UI thread only lays out and paints.+use crate::{dom::{self, Dom, Node}, js, render::{self, resolve, Page}, store};+use std::{collections::HashMap, sync::{mpsc, Arc}, time::{Duration, Instant}};++/// What a live page reports back to the UI: a re-rendered page after script activity, or a script-initiated navigation.+pub enum LiveEvent { Page(Page), Navigate(String) }++/// Callback for [`LiveEvent`]s (runs on a loader thread).+pub type LiveHook = Box<dyn Fn(LiveEvent) + Send + Sync>;++const UA: &str = "Mozilla/5.0 chrome-rs/0.1";+const MAX_IMG_W: u32 = 800;++/// Decoded RGBA8 image, already downscaled to at most MAX_IMG_W wide.+#[derive(Clone)]+pub struct Img { pub w: u32, pub h: u32, pub px: Vec<u8> }++/// Network archive for the real-page corpus: while recording (`true`) every GET answer is stored under the directory+/// (`index.tsv` + one `.bin` per response); while replaying (`false`) answers come from there and the network is never touched.+static ARCHIVE: std::sync::Mutex<Option<(std::path::PathBuf, bool)>> = std::sync::Mutex::new(None);+static ARCHIVE_INDEX: std::sync::Mutex<Option<HashMap<String, Vec<String>>>> = std::sync::Mutex::new(None);++pub fn set_archive(dir: Option<(std::path::PathBuf, bool)>) {+ let index = dir.as_ref().filter(|d| !d.1).map(|d| {+ std::fs::read_to_string(d.0.join("index.tsv")).unwrap_or_default().lines()+ .filter_map(|l| { let f: Vec<String> = l.split('\t').map(String::from).collect(); (f.len() == 7).then(|| (f[0].clone(), f[1..].to_vec())) }).collect()+ });+ if let Ok(mut i) = ARCHIVE_INDEX.lock() { *i = index; }+ if let Ok(mut a) = ARCHIVE.lock() { *a = dir; }+}++/// True while pages are served from a network archive (the corpus), when scripts must be deterministic.+pub fn replaying() -> bool { ARCHIVE.lock().is_ok_and(|a| a.as_ref().is_some_and(|d| !d.1)) }++fn archive_file(key: &str) -> String { format!("{:016x}.bin", key.bytes().fold(0xcbf29ce484222325u64, |h, b| (h ^ b as u64).wrapping_mul(0x100000001b3))) }++fn archived(method: &str, url: &str) -> Option<Result<Resp, String>> {+ let a = ARCHIVE.lock().ok()?;+ let (dir, record) = a.as_ref()?;+ if *record { return None; }+ let key = format!("{} {url}", method.to_ascii_uppercase());+ let idx = ARCHIVE_INDEX.lock().ok()?;+ let Some(f) = idx.as_ref()?.get(&key) else { return Some(Err("not in the archive".into())) };+ let opt = |s: &String| (!s.is_empty()).then(|| s.clone());+ Some(std::fs::read(dir.join(&f[0])).map_err(|e| e.to_string()).map(|bytes| Resp { url: f[1].clone(), status: f[2].parse().unwrap_or(200), mime: f[3].clone(), charset: opt(&f[4]), bytes, acao: opt(&f[5]) }))+}++fn record(method: &str, url: &str, r: &Resp) {+ let Ok(a) = ARCHIVE.lock() else { return };+ let Some((dir, true)) = a.as_ref() else { return };+ let key = format!("{} {url}", method.to_ascii_uppercase());+ let file = archive_file(&key);+ if std::fs::write(dir.join(&file), &r.bytes).is_err() { return; }+ use std::io::Write;+ if let Ok(mut idx) = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("index.tsv")) {+ let _ = writeln!(idx, "{key}\t{file}\t{}\t{}\t{}\t{}\t{}", r.url, r.status, r.mime, r.charset.as_deref().unwrap_or(""), r.acao.as_deref().unwrap_or(""));+ }+}++/// In-memory HTTP cache for GET responses that arrived without redirects: fresh by `max-age`/`Expires`, otherwise revalidated with ETag / Last-Modified.+/// shortcut: memory only (64 MB cap, wiped when full), no `Vary`, no heuristic freshness; persist to disk if cold starts matter.+struct Cached { resp: Resp, fresh_until: std::time::Instant, etag: Option<String>, modified: Option<String>, size: usize }+static CACHE: std::sync::LazyLock<std::sync::Mutex<(HashMap<String, Cached>, usize)>> = std::sync::LazyLock::new(Default::default);+const CACHE_CAP: usize = 64 << 20;++fn max_age(cc: &str) -> Option<u64> {+ cc.split(',').map(str::trim).find_map(|d| d.strip_prefix("max-age=").or(d.strip_prefix("s-maxage=")).and_then(|v| v.trim_matches('"').parse().ok()))+}++fn cache_store(url: &str, r: &Resp, cc: &str, etag: Option<String>, modified: Option<String>) {+ let lc = cc.to_ascii_lowercase();+ if r.status != 200 || lc.contains("no-store") { return; }+ let age = if lc.contains("no-cache") { 0 } else { max_age(&lc).unwrap_or(0) };+ if age == 0 && etag.is_none() && modified.is_none() { return; }+ let size = r.bytes.len();+ if size > CACHE_CAP / 4 { return; }+ let Ok(mut c) = CACHE.lock() else { return };+ if c.1 + size > CACHE_CAP { c.0.clear(); c.1 = 0; }+ c.1 += size;+ c.0.insert(url.to_string(), Cached { resp: r.clone(), fresh_until: std::time::Instant::now() + Duration::from_secs(age), etag, modified, size });+}++fn agent(secs: u64) -> ureq::Agent {+ ureq::Agent::new_with_config(ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(secs))).http_status_as_error(false).max_redirects(0).build())+}++#[derive(Clone)]+struct Resp { url: String, status: u16, mime: String, charset: Option<String>, bytes: Vec<u8>, acao: Option<String> }++/// `page`: host of the page that triggered a subresource request; cookies are only sent/stored for the same site. None = top-level navigation.+fn get(agent: &ureq::Agent, url: &str, limit: u64, page: Option<&str>) -> Result<Resp, String> { request(agent, url, None, limit, page) }++/// GET, or a urlencoded POST when `post` carries the body. Redirects are followed by hand so every hop sees and sets cookies.+fn request(agent: &ureq::Agent, url: &str, post: Option<&str>, limit: u64, page: Option<&str>) -> Result<Resp, String> {+ match post {+ Some(body) => request_with(agent, url, "POST", Some((body, "application/x-www-form-urlencoded")), limit, page),+ None => request_with(agent, url, "GET", None, limit, page),+ }+}++/// Any HTTP method; `body` = (text, content-type). 301-303 redirects turn into GET, 307/308 keep method and body.+fn request_with(agent: &ureq::Agent, url: &str, method: &str, body: Option<(&str, &str)>, limit: u64, page: Option<&str>) -> Result<Resp, String> {+ if let Some(r) = local(url, limit, page) { return r; }+ if let Some(r) = archived(method, url) { return r; }+ let first_url = url.to_string();+ let mut validators: Option<(Option<String>, Option<String>)> = None;+ if method.eq_ignore_ascii_case("GET") {+ if let Ok(c) = CACHE.lock() {+ if let Some(e) = c.0.get(&first_url) {+ if e.fresh_until > std::time::Instant::now() { return Ok(e.resp.clone()); }+ validators = Some((e.etag.clone(), e.modified.clone()));+ }+ }+ }+ let (mut url, mut method, mut body) = (url.to_string(), method.to_ascii_uppercase(), body);+ let asked = method.clone();+ for _ in 0..10 {+ let host = store::split_url(&url).map_or("", |u| u.1).to_string();+ let jar = page.is_none_or(|p| store::same_site(p, &host));+ let ck = if jar { store::cookie_header(&url, true) } else { String::new() };+ let sent = match (method.as_str(), body) {+ ("POST" | "PUT" | "PATCH", b) => {+ let (text, ctype) = b.unwrap_or(("", ""));+ let mut r = match method.as_str() { "POST" => agent.post(&url), "PUT" => agent.put(&url), _ => agent.patch(&url) }.header("User-Agent", UA);+ if !ctype.is_empty() { r = r.header("Content-Type", ctype); }+ if !ck.is_empty() { r = r.header("Cookie", &ck); }+ r.send(text)+ }+ (m, _) => {+ let mut r = match m { "DELETE" => agent.delete(&url), "HEAD" => agent.head(&url), _ => agent.get(&url) }.header("User-Agent", UA);+ if let (true, Some((etag, modified))) = (url == first_url, &validators) {+ if let Some(e) = etag { r = r.header("If-None-Match", e); }+ if let Some(m) = modified { r = r.header("If-Modified-Since", m); }+ }+ if !ck.is_empty() { r = r.header("Cookie", &ck); }+ r.call()+ }+ };+ let mut resp = sent.map_err(|e| e.to_string())?;+ if jar { for h in resp.headers().get_all("set-cookie") { if let Ok(h) = h.to_str() { store::set_cookie(&url, h, false); } } }+ let status = resp.status().as_u16();+ if status == 304 && url == first_url {+ if let Ok(mut c) = CACHE.lock() {+ if let Some(e) = c.0.get_mut(&first_url) {+ let age = resp.headers().get("cache-control").and_then(|v| v.to_str().ok()).and_then(max_age).unwrap_or(0);+ e.fresh_until = std::time::Instant::now() + Duration::from_secs(age);+ return Ok(e.resp.clone());+ }+ }+ }+ let hdr = |n: &str| resp.headers().get(n).and_then(|v| v.to_str().ok()).map(String::from);+ let (cc, etag, modified) = (hdr("cache-control").unwrap_or_default(), hdr("etag"), hdr("last-modified"));+ let loc = resp.headers().get("location").and_then(|l| l.to_str().ok()).map(|l| resolve(&url, l));+ if let (300..400, Some(next)) = (status, loc) {+ if !matches!(status, 307 | 308) { body = None; method = "GET".into(); }+ url = next;+ continue;+ }+ let resp_acao = resp.headers().get("access-control-allow-origin").and_then(|v| v.to_str().ok()).map(String::from);+ let mime = resp.body().mime_type().unwrap_or("text/html").to_string();+ let charset = resp.body().charset().map(String::from);+ let bytes = resp.body_mut().with_config().limit(limit).read_to_vec().map_err(|e| e.to_string())?;+ let acao = resp_acao;+ let r = Resp { url, status, mime, charset, bytes, acao };+ if asked == "GET" {+ record(&asked, &first_url, &r);+ if r.url == first_url { cache_store(&first_url, &r, &cc, etag, modified); }+ }+ return Ok(r);+ }+ Err("too many redirects".into())+}++fn percent_decode(s: &str) -> Vec<u8> {+ let b = s.as_bytes();+ let (mut out, mut i) = (Vec::with_capacity(b.len()), 0);+ while i < b.len() {+ match (b[i], b.get(i + 1..i + 3).and_then(|h| std::str::from_utf8(h).ok()).and_then(|h| u8::from_str_radix(h, 16).ok())) {+ (b'%', Some(v)) => { out.push(v); i += 3; }+ (c, _) => { out.push(c); i += 1; }+ }+ }+ out+}++fn base64_decode(s: &str) -> Vec<u8> {+ let (mut out, mut acc, mut bits) = (vec![], 0u32, 0);+ for c in s.bytes() {+ let v = match c { b'A'..=b'Z' => c - b'A', b'a'..=b'z' => c - b'a' + 26, b'0'..=b'9' => c - b'0' + 52, b'+' | b'-' => 62, b'/' | b'_' => 63, _ => continue };+ acc = acc << 6 | v as u32;+ bits += 6;+ if bits >= 8 { bits -= 8; out.push((acc >> bits) as u8); acc &= (1 << bits) - 1; }+ }+ out+}++fn escape_html(s: &str) -> String { s.replace('&', "&").replace('<', "<").replace('>', ">") }++fn mime_of_ext(path: &str) -> &'static str {+ match path.rsplit('.').next().map(str::to_ascii_lowercase).as_deref() {+ Some("html" | "htm" | "xhtml") => "text/html",+ Some("css") => "text/css",+ Some("js" | "mjs") => "text/javascript",+ Some("svg") => "image/svg+xml",+ Some("png") => "image/png",+ Some("jpg" | "jpeg") => "image/jpeg",+ Some("gif") => "image/gif",+ Some("webp") => "image/webp",+ _ => "text/plain",+ }+}++/// Non-network schemes: `file:`, `data:`, `about:` and `view-source:`. None for everything else.+fn local(url: &str, limit: u64, page: Option<&str>) -> Option<Result<Resp, String>> {+ let resp = |mime: &str, bytes: Vec<u8>| Ok(Resp { url: url.to_string(), status: 200, mime: mime.to_string(), charset: None, bytes, acao: None });+ if let Some(rest) = url.strip_prefix("file://") {+ // a remote page may not read local files; only top-level navigation and file: pages themselves may+ if page.is_some_and(|p| !p.is_empty()) { return Some(Err("blocked: file: from a remote page".into())); } // file pages have an empty host+ let path = String::from_utf8_lossy(&percent_decode(rest.split(['?', '#']).next().unwrap_or(rest))).into_owned();+ let path = if path.len() > 2 && path.as_bytes()[0] == b'/' && path.as_bytes()[2] == b':' { path[1..].to_string() } else { path };+ return Some(std::fs::metadata(&path).map_err(|e| format!("{path}: {e}")).and_then(|m| if m.len() > limit { Err(format!("{path}: file too large")) } else { std::fs::read(&path).map_err(|e| e.to_string()) })+ .and_then(|bytes| resp(mime_of_ext(&path), bytes)));+ }+ if let Some(rest) = url.strip_prefix("data:") {+ let (meta, payload) = rest.split_once(',')?;+ let b64 = meta.ends_with(";base64");+ let mime = meta.split(';').next().filter(|m| !m.is_empty()).unwrap_or("text/plain");+ let bytes = if b64 { base64_decode(&percent_decode(payload).iter().map(|&c| c as char).collect::<String>()) } else { percent_decode(payload) };+ return Some(if bytes.len() as u64 > limit { Err("data: URL too large".into()) } else { resp(mime, bytes) });+ }+ if url.starts_with("about:") { return Some(resp("text/html", store::about_html(url).unwrap_or_else(|| "<title>about:blank</title>".into()).into_bytes())); }+ if let Some(inner) = url.strip_prefix("view-source:") {+ return Some(request(&agent(20), inner, None, limit, None).map(|r| {+ let body = format!("<title>view-source:{}</title><pre>{}</pre>", escape_html(inner), escape_html(&decode_text(&r)));+ Resp { url: url.to_string(), status: r.status, mime: "text/html".into(), charset: None, bytes: body.into_bytes(), acao: None }+ }));+ }+ None+}++/// WOFF 1.0 / WOFF 2.0 -> plain sfnt bytes (WOFF1 tables are inflated, WOFF2 goes through brotli and the glyf/loca transform); sfnt formats pass through.+fn decode_font(b: &[u8]) -> Option<Vec<u8>> {+ match b.get(..4)? {+ b"wOFF" => {+ let be16 = |o: usize| b.get(o..o + 2).map(|x| u16::from_be_bytes([x[0], x[1]]) as usize);+ let be32 = |o: usize| b.get(o..o + 4).map(|x| u32::from_be_bytes([x[0], x[1], x[2], x[3]]) as usize);+ let n = be16(12)?;+ if n == 0 || n > 64 { return None; }+ let mut tables = vec![];+ for i in 0..n {+ let e = 44 + i * 20;+ let (off, comp, orig) = (be32(e + 4)?, be32(e + 8)?, be32(e + 12)?);+ let raw = b.get(off..off.checked_add(comp)?)?;+ let data = if comp < orig { miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(raw, 8 << 20).ok().filter(|d| d.len() == orig)? } else { raw.to_vec() };+ tables.push((b[e..e + 4].to_vec(), b[e + 16..e + 20].to_vec(), data));+ }+ let mut out = Vec::with_capacity(be32(16)?.min(16 << 20));+ out.extend_from_slice(&b[4..8]); // flavor+ out.extend_from_slice(&(n as u16).to_be_bytes());+ let mut sr = 1usize;+ let mut es = 0u16;+ while sr * 2 <= n { sr *= 2; es += 1; }+ out.extend_from_slice(&((sr * 16) as u16).to_be_bytes());+ out.extend_from_slice(&es.to_be_bytes());+ out.extend_from_slice(&((n * 16 - sr * 16) as u16).to_be_bytes());+ let mut off = 12 + n * 16;+ for (tag, sum, data) in &tables {+ out.extend_from_slice(tag);+ out.extend_from_slice(sum);+ out.extend_from_slice(&(off as u32).to_be_bytes());+ out.extend_from_slice(&(data.len() as u32).to_be_bytes());+ off += data.len().div_ceil(4) * 4;+ }+ for (_, _, data) in &tables {+ out.extend_from_slice(data);+ out.resize(out.len().div_ceil(4) * 4, 0);+ }+ Some(out)+ }+ b"wOF2" => woff2_patched::decode::convert_woff2_to_ttf(&mut &b[..]).ok().filter(|d| d.len() <= 16 << 20),+ b"\0\x01\0\0" | b"OTTO" | b"true" | b"ttcf" => Some(b.to_vec()),+ _ => None,+ }+}++/// Rewrites relative `url(...)` references of a stylesheet to absolute ones (the sheet is inlined, so its own address is lost).+fn absolutize_css_urls(css: &str, sheet_url: &str) -> String {+ let (mut out, mut rest) = (String::with_capacity(css.len()), css);+ while let Some(p) = rest.find("url(") {+ out.push_str(&rest[..p + 4]);+ let after = &rest[p + 4..];+ let Some(end) = after.find(')') else { rest = after; break };+ let raw = after[..end].trim();+ let url = raw.trim_matches(['"', '\'']);+ if url.is_empty() || url.starts_with("data:") || url.starts_with('#') { out.push_str(&after[..end]); } else { out.push_str(&format!("\"{}\"", resolve(sheet_url, url))); }+ rest = &after[end..];+ }+ out.push_str(rest);+ out+}++/// Downloads the first usable source of each `@font-face` rule (WOFF2, WOFF, TTF or OTF).+fn fetch_web_fonts(faces: &[crate::css::FontFaceRule], base: &str, page: &str, local_ok: bool) -> Vec<crate::render::WebFont> {+ let pick = |f: &crate::css::FontFaceRule| f.srcs.iter().map(|(u, fmt)| (resolve(base, u), fmt)).find(|(u, fmt)| {+ let u = u.to_ascii_lowercase();+ let path = u.split(['?', '#']).next().unwrap_or("");+ let ok_kind = matches!(fmt.as_str(), "woff2" | "woff" | "truetype" | "opentype" | "ttf" | "otf") || (fmt.is_empty() && [".woff2", ".woff", ".ttf", ".otf"].iter().any(|e| path.ends_with(e)));+ ok_kind && (u.starts_with("http") || local_ok && u.starts_with("file:"))+ }).map(|s| s.0);+ let list: Vec<(usize, String)> = faces.iter().enumerate().filter_map(|(i, f)| pick(f).map(|u| (i, u))).take(8).collect();+ let data = fetch_all(&list, 3_000_000, page, |r| decode_font(&r.bytes));+ list.iter().zip(data).filter_map(|((i, _), d)| Some(crate::render::WebFont { fam: crate::gfx::family_id(&faces[*i].family), bold: faces[*i].bold, italic: faces[*i].italic, data: d? })).collect()+}++fn sniff_meta_charset(b: &[u8]) -> Option<String> {+ let head = String::from_utf8_lossy(&b[..b.len().min(2048)]).to_ascii_lowercase();+ let rest = head[head.find("charset=")? + 8..].trim_start_matches(['"', '\'']);+ Some(rest.chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').collect())+}++fn decode_text(r: &Resp) -> String {+ let enc = r.charset.clone().or_else(|| sniff_meta_charset(&r.bytes)).and_then(|l| encoding_rs::Encoding::for_label(l.as_bytes()));+ match enc {+ Some(e) if e != encoding_rs::UTF_8 => e.decode(&r.bytes).0.into_owned(),+ _ => String::from_utf8_lossy(&r.bytes).into_owned(),+ }+}++/// Synchronous request for page scripts (fetch/XHR): (status, body, content-type); None on network failure, non-text or a CORS block.+/// Cross-origin requests follow a simplified CORS: only GET/HEAD/POST with a simple content type are sent (no preflight support),+/// and the script only sees the response when `Access-Control-Allow-Origin` is `*` or the page's origin.+pub fn fetch_req(url: &str, page_url: &str, method: &str, body: &str, ctype: &str) -> Option<(u16, String, String)> {+ let page_origin = store::origin_of(page_url);+ let cross = store::origin_of(url) != page_origin;+ let simple_type = ctype.is_empty() || ["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"].iter().any(|t| ctype.to_ascii_lowercase().starts_with(t));+ if cross && !(matches!(method, "GET" | "HEAD") || method == "POST" && simple_type) { return None; }+ let host = store::split_url(page_url).map_or("", |u| u.1);+ let r = request_with(&agent(6), url, method, Some((body, ctype)), 1_000_000, Some(host)).ok()?;+ if cross && !r.acao.as_deref().is_some_and(|a| a == "*" || a == page_origin) { return None; }+ Some((r.status, decode_text(&r), r.mime.clone()))+}++fn decode_image(bytes: &[u8]) -> Option<Img> {+ let head = String::from_utf8_lossy(&bytes[..bytes.len().min(1024)]).to_ascii_lowercase();+ if head.contains("<svg") { return crate::svg::render(&String::from_utf8_lossy(bytes)); }+ let im = image::load_from_memory(bytes).ok()?;+ let im = if im.width() > MAX_IMG_W { im.thumbnail(MAX_IMG_W, 4000) } else { im };+ let rgba = im.to_rgba8();+ Some(Img { w: rgba.width(), h: rgba.height(), px: rgba.into_raw() })+}++fn is_module(dom: &Dom, id: usize) -> bool { dom.nodes[id].tag == "script" && dom.attr(id, "type").is_some_and(|t| t.eq_ignore_ascii_case("module")) }++fn is_js(dom: &Dom, id: usize) -> bool {+ dom.nodes[id].tag == "script" && dom.attr(id, "type").is_none_or(|t| { let t = t.to_ascii_lowercase(); t.is_empty() || t.contains("javascript") || t.contains("ecmascript") })+}++/// Fetches all `list` URLs in parallel, mapping each response body with `f`.+fn fetch_all<T: Send>(list: &[(usize, String)], limit: u64, page: &str, f: impl Fn(Resp) -> Option<T> + Sync) -> Vec<Option<T>> {+ let ag = agent(8);+ std::thread::scope(|s| {+ let hs: Vec<_> = list.iter().map(|(_, u)| { let (ag, f) = (&ag, &f); s.spawn(move || get(ag, u, limit, Some(page)).ok().filter(|r| r.status < 400).and_then(f)) }).collect();+ hs.into_iter().map(|h| h.join().ok().flatten()).collect()+ })+}++/// Offline page for regression snapshots: inline CSS and scripts only, no network, no images.+pub fn load_offline(html: &str, url: &str) -> Page {+ let mut dom = dom::parse(html, true);+ let scripts: Vec<js::Script> = dom.descendants().into_iter().filter(|&i| is_js(&dom, i) && dom.attr(i, "src").is_none()).map(|i| js::Script::classic(dom.text_content(i))).collect();+ js::run(&mut dom, &scripts, url);+ render::build(&dom, url, HashMap::new())+}++pub fn load(url: &str, post: Option<&str>, hook: Option<LiveHook>) -> Result<(String, Page), String> {+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| load_inner(url, post, hook))).unwrap_or_else(|_| Err("internal error while loading this page".into()))+}++/// Decoded images by URL (None = failed once, not retried) so re-rendering a live page does not refetch.+type ImgCache = HashMap<String, Option<Img>>;++/// Candidate of a `srcset`: (url, descriptor value, is a width descriptor).+/// Candidate of a `srcset`: (url, descriptor value, is a width descriptor).+fn parse_srcset(s: &str) -> Vec<(String, f32, bool)> {+ let mut out = vec![];+ let mut rest = s.trim_start_matches(|c: char| c.is_whitespace() || c == ',');+ while !rest.is_empty() {+ // the url runs to the first whitespace (it may contain commas); a trailing comma ends a candidate without descriptor+ let end = rest.find(char::is_whitespace).unwrap_or(rest.len());+ let (url, after) = rest.split_at(end);+ let bare = url.ends_with(',');+ let url = url.trim_end_matches(',');+ let (desc, tail) = if bare { ("", after) } else { match after.find(',') { Some(c) => (&after[..c], &after[c + 1..]), None => (after, "") } };+ let desc = desc.trim();+ let (v, is_w) = if let Some(w) = desc.strip_suffix('w') { (w.parse().unwrap_or(0.0), true) } else if let Some(x) = desc.strip_suffix('x') { (x.parse().unwrap_or(1.0), false) } else { (1.0, false) };+ if !url.is_empty() { out.push((url.to_string(), v, is_w)); }+ rest = tail.trim_start_matches(|c: char| c.is_whitespace() || c == ',');+ }+ out+}++/// The candidate a 1000 px wide screen at 1x would use: the smallest width descriptor of at least 800, else the largest; for density descriptors the 1x one.+fn pick_srcset(s: &str) -> Option<String> {+ let c = parse_srcset(s);+ if c.is_empty() { return None; }+ if c.iter().any(|x| x.2) {+ let mut w: Vec<_> = c.iter().filter(|x| x.2).collect();+ w.sort_by(|a, b| a.1.total_cmp(&b.1));+ return w.iter().find(|x| x.1 >= 800.0).or(w.last()).map(|x| x.0.clone());+ }+ c.iter().min_by(|a, b| (a.1 - 1.0).abs().total_cmp(&(b.1 - 1.0).abs())).map(|x| x.0.clone())+}++/// Does a `<source media>` query hold on a 1000 px wide screen? Only min-width/max-width in px are understood; anything else counts as a match.+fn media_matches(m: &str) -> bool {+ let m = m.to_ascii_lowercase();+ let px = |key: &str| m.split(key).nth(1).and_then(|r| r.trim_start_matches([':', ' ']).split(|c: char| !c.is_ascii_digit() && c != '.').next()).and_then(|v| v.parse::<f32>().ok());+ px("min-width").is_none_or(|v| 1000.0 >= v) && px("max-width").is_none_or(|v| 1000.0 <= v)+}++/// URL of the picture an `<img>` shows: a matching `<picture><source>`, then `srcset`, then `src`, then lazy-loading attributes (`data-src`, `data-srcset`).+fn img_url(dom: &Dom, i: usize) -> Option<String> {+ let usable = |t: &str| { let t = t.trim().to_ascii_lowercase(); t.is_empty() || matches!(t.as_str(), "image/png" | "image/jpeg" | "image/jpg" | "image/gif" | "image/webp" | "image/svg+xml") };+ let parent = dom.nodes[i].parent;+ if parent != 0 && dom.nodes[parent].tag == "picture" {+ for &k in &dom.nodes[parent].kids {+ if k == i { break; }+ if dom.nodes[k].tag != "source" || !usable(dom.attr(k, "type").unwrap_or_default()) || !dom.attr(k, "media").is_none_or(|m| media_matches(&m)) { continue; }+ if let Some(u) = dom.attr(k, "srcset").or_else(|| dom.attr(k, "data-srcset")).and_then(pick_srcset) { return Some(u); }+ }+ }+ if let Some(u) = dom.attr(i, "srcset").or_else(|| dom.attr(i, "data-srcset")).and_then(pick_srcset) { return Some(u); }+ dom.attr(i, "src").filter(|s| !s.is_empty() && !s.starts_with("data:")).or_else(|| dom.attr(i, "data-src")).map(String::from)+}++/// Images of `dom` keyed by node id: `<img>` sources (downloaded once per URL) and outermost inline `<svg>` (rasterized once per markup).+fn collect_images(dom: &Dom, base: &str, page: &str, local_ok: bool, cache: &mut ImgCache) -> HashMap<usize, Img> {+ let img_src: Vec<(usize, String)> = dom.descendants().into_iter().filter(|&i| dom.nodes[i].tag == "img").filter_map(|i| {+ let s = img_url(dom, i)?;+ Some((i, resolve(base, &s)))+ }).filter(|(_, u)| u.starts_with("http") || local_ok && u.starts_with("file:")).take(24).collect();+ // CSS background images are keyed `usize::MAX - element id` so they never collide with `<img>` nodes+ let bg: Vec<(usize, String)> = render::background_urls(dom, base).into_iter().filter(|(_, u)| u.starts_with("http") || u.starts_with("data:") || local_ok && u.starts_with("file:")).map(|(i, u)| (usize::MAX - i, u)).collect();+ let img_src: Vec<(usize, String)> = img_src.into_iter().chain(bg).collect();+ let mut missing: Vec<(usize, String)> = vec![];+ for (i, u) in &img_src { if !cache.contains_key(u) && !missing.iter().any(|(_, m)| m == u) { missing.push((*i, u.clone())); } }+ let decoded = fetch_all(&missing, 4_000_000, page, |r| decode_image(&r.bytes));+ for ((_, u), im) in missing.into_iter().zip(decoded) { cache.insert(u, im); }+ let mut imgs: HashMap<usize, Img> = img_src.iter().filter_map(|(i, u)| Some((*i, cache.get(u)?.clone()?))).collect();+ let inline: Vec<usize> = dom.descendants().into_iter().filter(|&i| dom.nodes[i].tag == "svg").filter(|&i| {+ let mut p = dom.nodes[i].parent;+ while p != 0 { if dom.nodes[p].tag == "svg" { return false; } p = dom.nodes[p].parent; }+ true+ }).take(40).collect();+ for i in inline {+ let markup = crate::svg::to_markup(dom, i);+ let key = format!("svg:{markup}");+ if !cache.contains_key(&key) { let im = crate::svg::render(&markup); cache.insert(key.clone(), im); }+ if let Some(Some(im)) = cache.get(&key) { imgs.insert(i, im.clone()); }+ }+ imgs+}++/// Thread that turns each serialized DOM from a live script session into a Page (latest wins, at most ~12 per second).+fn spawn_builder(rx: mpsc::Receiver<String>, base: String, host: String, mut cache: ImgCache, hook: Arc<LiveHook>) {+ let local = base.starts_with("file:");+ let _ = std::thread::Builder::new().stack_size(32 << 20).spawn(move || {+ while let Ok(mut json) = rx.recv() {+ while let Ok(j) = rx.try_recv() { json = j; }+ let Some(dom) = serde_json::from_str(&json).ok().and_then(|v| Dom::from_json(&v)) else { continue };+ let page = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let imgs = collect_images(&dom, &base, &host, local, &mut cache); render::build(&dom, &base, imgs) }));+ if let Ok(p) = page { hook(LiveEvent::Page(p)); }+ std::thread::sleep(Duration::from_millis(80));+ }+ });+}++fn load_inner(url: &str, post: Option<&str>, hook: Option<LiveHook>) -> Result<(String, Page), String> {+ let timing = std::env::var_os("CHROME_RS_TIMING").is_some();+ let t0 = Instant::now();+ let lap = |what: &str| if timing { eprintln!("{:>6} ms {what}", t0.elapsed().as_millis()); };++ let main = request(&agent(20), url, post, 12_000_000, None)?;+ if !(main.mime.starts_with("text/") || main.mime.contains("xml")) { return Err(format!("unsupported content type: {}", main.mime)); }+ let final_url = main.url.clone();+ let local_ok = final_url.starts_with("file:");+ let fetchable = |u: &str| u.starts_with("http") || local_ok && u.starts_with("file:");+ let page_host = store::split_url(&final_url).map_or(String::new(), |u| u.1.to_string());+ let text = decode_text(&main);+ let mut dom = dom::parse(&if main.mime == "text/plain" { format!("<pre>{}</pre>", escape_html(&text)) } else { text }, true);+ lap("html fetched + parsed");+ let ids = dom.descendants();++ let css: Vec<(usize, String)> = ids.iter().filter(|&&i| {+ dom.nodes[i].tag == "link" && dom.attr(i, "rel").is_some_and(|r| r.to_ascii_lowercase().contains("stylesheet")) && !dom.attr(i, "media").is_some_and(|m| m.contains("print"))+ }).filter_map(|&i| dom.attr(i, "href").map(|h| (i, resolve(&final_url, h)))).filter(|(_, u)| fetchable(u)).take(12).collect();+ let js_src: Vec<(usize, String)> = ids.iter().filter(|&&i| is_js(&dom, i) || is_module(&dom, i)).filter_map(|&i| dom.attr(i, "src").map(|s| (i, resolve(&final_url, s)))).filter(|(_, u)| fetchable(u)).take(16).collect();++ // CSS and JS downloads overlap with each other.+ let (css_text, js_text) = std::thread::scope(|s| {+ let c = s.spawn(|| fetch_all(&css, 2_000_000, &page_host, |r| Some(decode_text(&r))));+ let j = fetch_all(&js_src, 2_000_000, &page_host, |r| Some(decode_text(&r)));+ (c.join().unwrap_or_default(), j)+ });+ lap("css + js downloaded");++ for ((id, _), text) in css.iter().zip(css_text) {+ if let Some(t) = text {+ dom.nodes[*id].tag = "style".into();+ dom.nodes[*id].attrs.clear();+ dom.add(*id, Node { text: absolutize_css_urls(&t, &css[css.iter().position(|(i, _)| i == id).unwrap_or(0)].1), ..Default::default() });+ }+ }+ // classic scripts in document order, then modules (they are deferred), each with the URL that anchors its imports+ let (mut scripts, mut modules, mut inline) = (vec![], vec![], 0);+ for &i in &ids {+ if dom.nodes[i].tag == "script" && dom.attr(i, "type").is_some_and(|t| t.eq_ignore_ascii_case("importmap")) { scripts.push(js::Script::importmap(dom.text_content(i))); continue; }+ let module = is_module(&dom, i);+ if !(module || is_js(&dom, i)) { continue; }+ let (code, name) = if dom.attr(i, "src").is_some() {+ let Some(p) = js_src.iter().position(|(j, _)| *j == i) else { continue };+ let Some(t) = js_text[p].clone() else { continue };+ (t, js_src[p].1.clone())+ } else { inline += 1; (dom.text_content(i), format!("{final_url}#inline-{inline}")) };+ (if module { &mut modules } else { &mut scripts }).push(js::Script { module, name, code });+ }+ scripts.extend(modules);+ // With a hook the scripts stay alive after load (timers, events, DOM updates); otherwise they run once.+ // A page with no scripts and no inline `on...=` handlers needs no JavaScript runtime at all (saves a thread and ~25 MB).+ let needs_js = !scripts.is_empty() || dom.nodes.iter().any(|n| n.attrs.iter().any(|(k, _)| k.starts_with("on")));+ let hook = hook.map(Arc::new);+ let (utx, urx) = mpsc::channel::<String>();+ let mut live = None;+ if let (true, Some(h), Some(&html)) = (needs_js, &hook, dom.nodes[0].kids.first()) {+ let hn = h.clone();+ let nav: Arc<dyn Fn(String) + Send + Sync> = Arc::new(move |u| hn(LiveEvent::Navigate(u)));+ if let Some((handle, first)) = js::start(dom.to_json(html).to_string(), scripts.clone(), final_url.clone(), Box::new(move |s| { let _ = utx.send(s); }), nav) {+ if let Some(d) = serde_json::from_str(&first).ok().and_then(|v| Dom::from_json(&v)) { dom = d; live = Some(handle); }+ }+ }+ if live.is_none() && needs_js { js::run(&mut dom, &scripts, &final_url); }+ lap("scripts executed");++ let mut cache = ImgCache::new();+ let imgs = collect_images(&dom, &final_url, &page_host, local_ok, &mut cache);+ lap("images decoded");++ let mut page = render::build(&dom, &final_url, imgs);+ lap("styled");+ page.webfonts = fetch_web_fonts(&page.faces, &final_url, &page_host, final_url.starts_with("file:"));+ lap("web fonts");+ if let (Some(handle), Some(h)) = (live, hook) {+ page.live = Some(handle);+ spawn_builder(urx, final_url.clone(), page_host, cache, h);+ }+ Ok((final_url, page))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn body(r: Option<Result<Resp, String>>) -> (String, String) { let r = r.unwrap().unwrap(); (r.mime, String::from_utf8(r.bytes).unwrap()) }++ #[test]+ fn data_and_about_urls() {+ assert_eq!(body(local("data:text/html,%3Cb%3Ehi%3C/b%3E", 1000, None)), ("text/html".into(), "<b>hi</b>".into()));+ assert_eq!(body(local("data:text/plain;base64,aGVsbG8gd29ybGQ=", 1000, None)), ("text/plain".into(), "hello world".into()));+ assert!(body(local("about:blank", 10, None)).1.contains("about:blank"));+ assert!(local("https://a.com", 10, None).is_none());+ assert!(local("data:text/plain,toolongpayload", 4, None).unwrap().is_err());+ }++ #[test]+ fn file_urls_open_locally_but_never_from_remote_pages() {+ let path = std::env::temp_dir().join(format!("chrome-rs-file-{}.html", std::process::id()));+ std::fs::write(&path, "<p>local</p>").unwrap();+ let url = format!("file:///{}", path.to_string_lossy().replace('\\', "/").replace(' ', "%20"));+ assert_eq!(body(local(&url, 1000, None)), ("text/html".into(), "<p>local</p>".into()));+ assert_eq!(body(local(&url, 1000, Some(""))).1, "<p>local</p>"); // a file: page may load siblings+ assert!(local(&url, 1000, Some("evil.com")).unwrap().is_err());+ let _ = std::fs::remove_file(path);+ }++ #[test]+ fn plain_text_helpers() {+ assert_eq!(escape_html("<a&b>"), "<a&b>");+ assert_eq!(mime_of_ext("C:/x/readme.MD"), "text/plain");+ assert_eq!(mime_of_ext("a.HTM"), "text/html");+ }++ #[test]+ fn cookies_redirects_and_methods_over_http() {+ use std::io::{Read, Write};+ let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let port = l.local_addr().unwrap().port();+ std::thread::spawn(move || {+ for _ in 0..4 { // login, home (after redirect), echo, home+ let Ok((mut c, _)) = l.accept() else { break };+ let mut buf = vec![];+ let mut chunk = [0u8; 1024];+ let (head_end, clen) = loop {+ let n = c.read(&mut chunk).unwrap_or(0);+ buf.extend_from_slice(&chunk[..n]);+ let text = String::from_utf8_lossy(&buf).to_string();+ if let Some(p) = text.find("\r\n\r\n") {+ let cl = text.to_ascii_lowercase().lines().find_map(|l| l.strip_prefix("content-length: ").and_then(|v| v.trim().parse::<usize>().ok())).unwrap_or(0);+ if buf.len() >= p + 4 + cl || n == 0 { break (p + 4, cl); }+ } else if n == 0 { break (buf.len(), 0); }+ };+ let text = String::from_utf8_lossy(&buf).to_string();+ let (head, body) = (text[..head_end.min(text.len())].to_string(), text[head_end.min(text.len())..].chars().take(clen).collect::<String>());+ let first = head.lines().next().unwrap_or("").to_string();+ let (resp_head, resp_body) = if first.contains("/login") {+ ("HTTP/1.1 302 Found\r\nLocation: /home\r\nSet-Cookie: sid=abc; Path=/; HttpOnly".to_string(), String::new())+ } else if first.contains("/home") {+ ("HTTP/1.1 200 OK\r\nContent-Type: text/html".to_string(), if head.to_ascii_lowercase().contains("cookie: sid=abc") { "welcome".into() } else { "anon".into() })+ } else {+ let ct = head.to_ascii_lowercase().lines().find_map(|l| l.strip_prefix("content-type: ").map(String::from)).unwrap_or_default();+ ("HTTP/1.1 200 OK\r\nContent-Type: text/plain".to_string(), format!("{} {} {}", first.split(' ').next().unwrap_or(""), ct, body))+ };+ let _ = c.write_all(format!("{resp_head}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{resp_body}", resp_body.len()).as_bytes());+ }+ });+ let base = format!("http://127.0.0.1:{port}");+ let ag = agent(5);+ let r = request_with(&ag, &format!("{base}/login"), "GET", None, 10_000, None).unwrap();+ assert_eq!((r.status, r.url.as_str(), String::from_utf8_lossy(&r.bytes).as_ref()), (200, format!("{base}/home").as_str(), "welcome")); // cookie set on the 302 hop, sent on the next+ let r = request_with(&ag, &format!("{base}/echo"), "PUT", Some(("x=1", "application/json")), 10_000, None).unwrap();+ assert_eq!(String::from_utf8_lossy(&r.bytes), "PUT application/json x=1");+ let r = request_with(&ag, &format!("{base}/home"), "GET", None, 10_000, Some("other.com")).unwrap();+ assert_eq!(String::from_utf8_lossy(&r.bytes), "anon"); // third-party request gets no cookies+ }++ #[test]+ fn cross_origin_requests_need_cors_approval() {+ use std::io::{Read, Write};+ let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let base = format!("http://127.0.0.1:{}", l.local_addr().unwrap().port());+ std::thread::spawn(move || {+ while let Ok((mut c, _)) = l.accept() {+ let mut b = [0u8; 2048];+ let n = c.read(&mut b).unwrap_or(0);+ let req = String::from_utf8_lossy(&b[..n]).to_string();+ let acao = if req.contains("/open") { "Access-Control-Allow-Origin: *\r\n" } else if req.contains("/exact") { "Access-Control-Allow-Origin: http://evil.test\r\n" } else { "" };+ let _ = c.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n{acao}Content-Length: 2\r\nConnection: close\r\n\r\nok").as_bytes());+ }+ });+ let other = "http://evil.test/page";+ assert!(fetch_req(&format!("{base}/open"), other, "GET", "", "").is_some());+ assert!(fetch_req(&format!("{base}/exact"), other, "GET", "", "").is_some());+ assert!(fetch_req(&format!("{base}/closed"), other, "GET", "", "").is_none(), "no ACAO header: response hidden from the page");+ assert!(fetch_req(&format!("{base}/open"), other, "PUT", "x", "application/json").is_none(), "needs a preflight we cannot do");+ assert!(fetch_req(&format!("{base}/open"), other, "POST", "{}", "application/json").is_none());+ assert!(fetch_req(&format!("{base}/closed"), &format!("{base}/p"), "GET", "", "").is_some(), "same origin needs no CORS header");+ }++ #[test]+ fn woff2_is_decoded_to_a_font_fontdue_can_read() {+ let packed = include_bytes!("testdata/lato.woff2");+ let ttf = decode_font(packed).expect("brotli + glyf transform");+ assert_eq!(&ttf[..4], b"\0\x01\0\0");+ assert!(ttf.len() > packed.len(), "unpacked is larger: {} vs {}", ttf.len(), packed.len());+ let font = fontdue::Font::from_bytes(ttf.as_slice(), fontdue::FontSettings::default()).expect("parses");+ let (m, bm) = font.rasterize('a', 20.0);+ assert!(m.width > 5 && bm.iter().any(|&p| p > 128), "glyph 'a' has ink");+ assert!(decode_font(b"wOF2garbage").is_none());+ }++ #[test]+ fn woff1_is_unpacked_to_sfnt_and_css_urls_become_absolute() {+ // build a one-table WOFF by hand: header (44) + 1 directory entry (20) + stored table "abcd"+ let mut w = b"wOFF\0\x01\0\0".to_vec();+ w.extend_from_slice(&[0, 0, 0, 0, 0, 1, 0, 0]); // length (ignored), numTables = 1, reserved+ w.extend_from_slice(&[0, 0, 0, 4]); // totalSfntSize+ w.extend_from_slice(&[0; 12]); // version + meta/priv+ w.extend_from_slice(&[0; 12]);+ w.truncate(44);+ w.extend_from_slice(b"head");+ w.extend_from_slice(&64u32.to_be_bytes()); // offset+ w.extend_from_slice(&4u32.to_be_bytes()); // compLength+ w.extend_from_slice(&4u32.to_be_bytes()); // origLength+ w.extend_from_slice(&7u32.to_be_bytes()); // checksum+ w.extend_from_slice(b"abcd");+ let sfnt = decode_font(&w).unwrap();+ assert_eq!(&sfnt[..4], b"\0\x01\0\0");+ assert_eq!(&sfnt[12..16], b"head");+ assert_eq!(&sfnt[28..32], b"abcd");+ assert!(decode_font(b"wOF2....").is_none());+ let css = "@font-face{src:url(../f/a.woff) format('woff'),url(\"data:font/x;base64,AA==\")} .x{background:url( b.png )}";+ let out = absolutize_css_urls(css, "https://a.com/css/site.css");+ assert!(out.contains("url(\"https://a.com/f/a.woff\")") && out.contains("url(\"https://a.com/css/b.png\")") && out.contains("data:font/x;base64,AA=="), "{out}");+ }++ #[test]+ fn font_face_downloads_and_text_uses_the_family() {+ let Some(font) = ["C:\\Windows\\Fonts\\consola.ttf", "C:\\Windows\\Fonts\\arial.ttf","/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf"].iter().find_map(|p| std::fs::read(p).ok()) else { return };+ let dir = std::env::temp_dir().join(format!("chrome-rs-wf-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(dir.join("my font.ttf"), font).unwrap();+ std::fs::write(dir.join("a.html"), "<style>@font-face{font-family:'Foo Bar';src:url('my font.ttf') format('truetype')} p{font-family:'Foo Bar',sans-serif}</style><p>Hello</p><div>plain</div>").unwrap();+ let url = format!("file:///{}/a.html", dir.to_string_lossy().replace('\\', "/").replace(' ', "%20"));+ let (_, page) = load(&url, None, None).unwrap();+ let _ = std::fs::remove_dir_all(&dir);+ assert_eq!(page.webfonts.len(), 1, "font file was fetched through file: and decoded");+ let fam = crate::gfx::family_id("foo bar");+ assert!(page.items.iter().any(|i| matches!(i, crate::render::Item::Word { text, fam: f, .. } if text == "Hello" && *f == fam)));+ assert!(page.items.iter().any(|i| matches!(i, crate::render::Item::Word { text, fam: 0, .. } if text == "plain")));+ let mut fonts = crate::gfx::Fonts::system().unwrap();+ let before = fonts.width_f("Hello", 16.0, crate::gfx::face(false, false, false, fam));+ assert!(fonts.add_web(fam, false, false, &page.webfonts[0].data));+ let after = fonts.width_f("Hello", 16.0, crate::gfx::face(false, false, false, fam));+ assert!(before > 0.0 && after > 0.0);+ }++ fn page_text(pg: &Page) -> String {+ pg.items.iter().filter_map(|i| if let crate::render::Item::Word { text, space, .. } = i { Some(format!("{}{text}", if *space { " " } else { "" })) } else { None }).collect()+ }+++ #[test]+ fn picture_and_srcset_pick_the_source_a_wide_screen_would_use() {+ assert_eq!(pick_srcset("a.jpg 480w, b.jpg 800w, c.jpg 1600w").as_deref(), Some("b.jpg"));+ assert_eq!(pick_srcset("a.jpg 320w, b.jpg 640w").as_deref(), Some("b.jpg"), "nothing wide enough: the largest");+ assert_eq!(pick_srcset("a.png, b.png 2x").as_deref(), Some("a.png"));+ assert_eq!(pick_srcset("https://c.test/r?w=1,h=2 1x, https://c.test/r?w=2 2x").as_deref(), Some("https://c.test/r?w=1,h=2"), "commas inside a url");+ assert!(media_matches("(min-width: 768px)") && !media_matches("(max-width: 600px)") && media_matches("screen"));+ let d = dom::parse("<picture><source media='(max-width:600px)' srcset='small.jpg'><source type='image/avif' srcset='x.avif'><source type='image/webp' srcset='big.webp 1x'><img src='fallback.jpg'></picture><img src='data:image/gif;base64,R0' data-srcset='lazy.jpg 1x'><img src='plain.png'>", true);+ let imgs: Vec<usize> = d.descendants().into_iter().filter(|&i| d.nodes[i].tag == "img").collect();+ assert_eq!(img_url(&d, imgs[0]).as_deref(), Some("big.webp"));+ assert_eq!(img_url(&d, imgs[1]).as_deref(), Some("lazy.jpg"));+ assert_eq!(img_url(&d, imgs[2]).as_deref(), Some("plain.png"));+ }+ #[test]+ fn live_pages_rerender_on_timers_and_clicks() {+ let dir = std::env::temp_dir().join(format!("chrome-rs-live-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(dir.join("a.html"), "<p id=c>tick0</p><p id=m>idle</p><button id=b onclick=\"document.getElementById('m').textContent='clicked'; return false;\">go</button><script>var n=0; setInterval(function(){ n++; document.getElementById('c').textContent='tick'+n; }, 50); window.onload = function(){ document.getElementById('m').textContent='loaded'; };</script>").unwrap();+ let url = format!("file:///{}/a.html", dir.to_string_lossy().replace('\\', "/").replace(' ', "%20"));+ let (tx, rx) = mpsc::channel();+ let tx = std::sync::Mutex::new(tx);+ let hook: LiveHook = Box::new(move |ev| { if let LiveEvent::Page(p) = ev { let _ = tx.lock().unwrap().send(p); } });+ let (_, page) = load(&url, None, Some(hook)).unwrap();+ let handle = page.live.clone().expect("live session started");+ let first = page_text(&page);+ assert!(first.contains("loaded"), "window.onload ran before the first page: {first}");+ let btn = page.fields.iter().find(|f| f.kind == crate::render::FieldKind::Submit).unwrap().node;+ let wait = |pred: &dyn Fn(&str) -> bool| { let end = Instant::now() + Duration::from_secs(5); while Instant::now() < end { if let Ok(p) = rx.recv_timeout(Duration::from_millis(100)) { if pred(&page_text(&p)) { return true; } } } false };+ assert!(wait(&|t| t.contains("tick") && t.trim_start_matches("tick").chars().next().is_some_and(|c| c.is_ascii_digit()) && !t.contains("tick0") && !t.contains("tick1 ")), "timer updates arrive as new pages");+ assert!(handle.event(btn, "click", "{}"), "inline onclick returned false -> default prevented");+ assert!(wait(&|t| t.contains("clicked")), "click handler result is rendered");+ drop(handle);+ let _ = std::fs::remove_dir_all(&dir);+ }+++ /// Adds a todo to archived TodoMVC apps (React, Vue, Svelte, jQuery...) through the live session: type, Enter, read the list back.+ /// Archives are not committed (see ROADMAP), so the test passes silently where `corpus-m4/real` is missing.+ #[test]+ #[ignore = "swaps the global archive: run alone with --ignored"]+ fn archived_todomvc_apps_accept_a_todo() {+ let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("corpus-m4/real");+ let Ok(rd) = std::fs::read_dir(&root) else { return };+ let mut dirs: Vec<_> = rd.flatten().map(|e| e.path()).filter(|p| p.join("url.txt").exists()).collect();+ dirs.sort();+ let mut report = vec![];+ for d in dirs {+ let url = std::fs::read_to_string(d.join("url.txt")).unwrap();+ set_archive(Some((d.clone(), false)));+ let (tx, rx) = mpsc::channel();+ let tx = std::sync::Mutex::new(tx);+ let hook: LiveHook = Box::new(move |ev| { if let LiveEvent::Page(p) = ev { let _ = tx.lock().unwrap().send(p); } });+ let name = d.file_name().unwrap().to_string_lossy().to_string();+ let Ok((_, page)) = load(&url, None, Some(hook)) else { report.push(format!("{name}: load failed")); continue };+ let (Some(h), Some(input)) = (page.live.clone(), page.fields.iter().find(|f| f.kind == crate::render::FieldKind::Text).map(|f| f.node)) else { report.push(format!("{name}: no live input")); continue };+ h.value(input, "buy milk", None);+ h.post(input, "input", "{}");+ h.post(input, "keydown", "{\"key\":\"Enter\"}");+ h.post(input, "keypress", "{\"key\":\"Enter\"}");+ h.post(input, "change", "{}"); // what the UI sends when Enter commits a changed field+ h.post(input, "keyup", "{\"key\":\"Enter\"}");+ let end = Instant::now() + Duration::from_secs(3);+ let (mut ok, mut last) = (false, String::new());+ while Instant::now() < end && !ok { if let Ok(p) = rx.recv_timeout(Duration::from_millis(100)) { last = page_text(&p); ok = last.contains("buy milk"); } }+ report.push(format!("{name}: {}", if ok { "ok".to_string() } else { format!("todo did not appear; last update: {last}") }));+ }+ set_archive(None);+ println!("{}", report.join("\n"));+ assert!(report.iter().all(|r| r.ends_with(": ok")), "{}", report.join("\n"));+ }+ #[test]+ fn es_modules_import_dynamic_import_and_top_level_await() {+ let dir = std::env::temp_dir().join(format!("chrome-rs-mod-{}", std::process::id()));+ std::fs::create_dir_all(dir.join("lib")).unwrap();+ std::fs::write(dir.join("lib/util.js"), "export const x = 'util'; export default function twice(n) { return n * 2; }").unwrap();+ std::fs::write(dir.join("lib/dyn.js"), "export const y = 'dyn';").unwrap();+ std::fs::write(dir.join("main.js"), "import twice, { x } from './lib/util.js'; window.fromMain = x + ':' + twice(21);").unwrap();+ std::fs::write(dir.join("a.html"), "<p id=o>none</p><script type=module src=main.js></script><script type=module>import { x } from './lib/util.js'; const m = await import('./lib/dyn.js'); await Promise.resolve(); document.getElementById('o').textContent = window.fromMain + '|' + x + '|' + m.y;</script>").unwrap();+ let url = format!("file:///{}/a.html", dir.to_string_lossy().replace('\\', "/").replace(' ', "%20"));+ let (_, page) = load(&url, None, None).unwrap();+ let _ = std::fs::remove_dir_all(&dir);+ assert!(page_text(&page).contains("util:42|util|dyn"), "{}", page_text(&page));+ }+}diff --git a/plugins/chrome-rs/src/main.rs b/plugins/chrome-rs/src/main.rsnew file mode 100644index 0000000..6b1d516--- /dev/null+++ b/plugins/chrome-rs/src/main.rs@@ -0,0 +1,1372 @@+// Browser shell: window, tabs, painting, input. Page loading is in load.rs, layout in layout.rs, live page scripts in js.rs.+// shortcut: one softbuffer surface painted on the CPU every frame; the UI thread lays out the page itself.+mod browse;+mod css;+mod dom;+mod gfx;+mod js;+mod layout;+mod load;+mod render;+mod snap;+mod store;+mod svg;++use gfx::{draw_field, draw_image, draw_popup, draw_text, fill, Fonts, POPUP_ROWS};+use browse::SelPoint;+use layout::{Placed, Rect};+use render::{Field, FieldKind, Page};+use std::{num::NonZeroU32, sync::Arc};+use winit::{+ application::ApplicationHandler,+ dpi::PhysicalPosition,+ event::{ElementState, MouseButton, MouseScrollDelta, WindowEvent},+ event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy},+ keyboard::{Key, ModifiersState, NamedKey},+ window::{CursorIcon, Window, WindowId},+};++const TAB_H: f32 = 32.0;+const BAR: f32 = 40.0;+const HOME: &str = "https://example.com";+enum Msg {+ Loaded { uid: u64, id: u64, url: String, push: bool, res: Result<(String, Page), String> },+ /// A live page re-rendered after script activity (or a script asked to navigate); `id` is the navigation that owns the session.+ Live { uid: u64, id: u64, ev: load::LiveEvent },+}++// ---------- text editing helpers (pure, unit-tested) ----------++fn byte_at(s: &str, ci: usize) -> usize { s.char_indices().nth(ci).map_or(s.len(), |(b, _)| b) }++/// Char range [start, end) of the logical (newline-delimited) line holding `caret`.+fn line_bounds(s: &str, caret: usize) -> (usize, usize) {+ let chars: Vec<char> = s.chars().collect();+ let c = caret.min(chars.len());+ let start = chars[..c].iter().rposition(|&ch| ch == '\n').map_or(0, |p| p + 1);+ let end = chars[c..].iter().position(|&ch| ch == '\n').map_or(chars.len(), |p| c + p);+ (start, end)+}++/// Applies an editing key to a text-like field. Returns true when the key was consumed.+fn edit_field(fl: &mut Field, caret: &mut usize, key: &Key, text: Option<&str>) -> bool {+ let len = fl.value.chars().count();+ *caret = (*caret).min(len);+ match key {+ Key::Named(NamedKey::Backspace) => if *caret > 0 { *caret -= 1; fl.value.remove(byte_at(&fl.value, *caret)); },+ Key::Named(NamedKey::Delete) => if *caret < len { fl.value.remove(byte_at(&fl.value, *caret)); },+ Key::Named(NamedKey::ArrowLeft) => *caret = caret.saturating_sub(1),+ Key::Named(NamedKey::ArrowRight) => *caret = (*caret + 1).min(len),+ Key::Named(NamedKey::Home) => *caret = line_bounds(&fl.value, *caret).0,+ Key::Named(NamedKey::End) => *caret = line_bounds(&fl.value, *caret).1,+ Key::Named(NamedKey::ArrowUp | NamedKey::ArrowDown) if fl.kind == FieldKind::TextArea => {+ let (s, e) = line_bounds(&fl.value, *caret);+ let col = *caret - s;+ let up = matches!(key, Key::Named(NamedKey::ArrowUp));+ if up && s > 0 { let (ps, pe) = line_bounds(&fl.value, s - 1); *caret = (ps + col).min(pe); }+ else if !up && e < len { let (ns, ne) = line_bounds(&fl.value, e + 1); *caret = (ns + col).min(ne); }+ }+ Key::Named(NamedKey::Enter) if fl.kind == FieldKind::TextArea => { fl.value.insert(byte_at(&fl.value, *caret), '\n'); *caret += 1; }+ _ => match text.filter(|t| !t.is_empty() && !t.chars().any(char::is_control)) {+ Some(t) if !matches!(key, Key::Named(NamedKey::Enter | NamedKey::Escape | NamedKey::Tab)) => {+ fl.value.insert_str(byte_at(&fl.value, *caret), t);+ *caret += t.chars().count();+ }+ _ => return false,+ },+ }+ true+}++// ---------- URLs and forms ----------++/// (url, post body) for submitting `form` with the given name/value pairs.+fn form_request(form: &render::Form, pairs: &[(&str, &str)]) -> (String, Option<String>) {+ let query = pairs.iter().map(|(k, v)| format!("{}={}", percent_encode(k), percent_encode(v))).collect::<Vec<_>>().join("&");+ if form.post { (form.action.clone(), Some(query)) }+ else { (format!("{}?{query}", form.action.split(['?', '#']).next().unwrap_or("")), None) }+}++fn percent_encode(s: &str) -> String {+ s.bytes().map(|b| if b.is_ascii_alphanumeric() || b"-._~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }).collect()+}++/// Address-bar text -> URL: full URL as is, bare host gets https://, anything else is a search.+/// Address-bar text -> URL; `engine` is a search URL with `{q}` for the query.+fn to_url_with(input: &str, engine: &str) -> String {+ let s = input.trim();+ if s.contains("://") || ["data:", "about:", "view-source:"].iter().any(|p| s.starts_with(p)) { s.into() }+ else if !s.contains(' ') && (s.contains('.') || s.starts_with("localhost")) { format!("https://{s}") }+ else { engine.replace("{q}", &percent_encode(s)) }+}++const ENGINE: &str = "https://html.duckduckgo.com/html/?q={q}";++fn to_url(input: &str) -> String { to_url_with(input, &store::setting("search").filter(|e| e.contains("{q}")).unwrap_or_else(|| ENGINE.into())) }++const ZOOMS: &[f32] = &[0.3, 0.5, 0.67, 0.8, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0, 5.0];++/// Next preset zoom level above/below `z`.+fn zoom_step(z: f32, up: bool) -> f32 {+ if up { ZOOMS.iter().copied().find(|&v| v > z + 0.001).unwrap_or(5.0) } else { ZOOMS.iter().rev().copied().find(|&v| v < z - 0.001).unwrap_or(0.3) }+}++/// Index of `fields[i]` among the fields with the same kind and name (so fields can be matched across rebuilt pages).+fn occurrence(fields: &[Field], i: usize) -> usize { fields[..i].iter().filter(|f| f.kind == fields[i].kind && f.name == fields[i].name).count() }++fn find_occurrence(fields: &[Field], kind: FieldKind, name: &str, n: usize) -> Option<usize> {+ fields.iter().enumerate().filter(|(_, f)| f.kind == kind && f.name == name).nth(n).map(|(i, _)| i)+}++/// Carries the user's edits over to a freshly built live page: a field keeps what the user typed unless a script changed its value.+fn merge_fields(old: &[Field], new: &mut [Field]) {+ for k in 0..new.len() {+ let n = occurrence(new, k);+ let Some(o) = find_occurrence(old, new[k].kind, &new[k].name, n).map(|i| &old[i]) else { continue };+ let nf = &mut new[k];+ if nf.value == o.initial { nf.value = o.value.clone(); nf.sel = o.sel; }+ if nf.checked == o.initial_checked { nf.checked = o.checked; }+ }+}++/// DOM `key` value for the page's keydown/keyup events.+fn key_name(k: &Key) -> Option<String> {+ Some(match k {+ Key::Character(c) => c.to_string(),+ Key::Named(n) => match n {+ NamedKey::Enter => "Enter", NamedKey::Escape => "Escape", NamedKey::Backspace => "Backspace", NamedKey::Tab => "Tab", NamedKey::Delete => "Delete",+ NamedKey::ArrowUp => "ArrowUp", NamedKey::ArrowDown => "ArrowDown", NamedKey::ArrowLeft => "ArrowLeft", NamedKey::ArrowRight => "ArrowRight",+ NamedKey::Home => "Home", NamedKey::End => "End", NamedKey::PageUp => "PageUp", NamedKey::PageDown => "PageDown", NamedKey::Space => " ",+ _ => return None,+ }.to_string(),+ _ => return None,+ })+}++/// State of the find bar.+struct Find { query: String, matches: Vec<browse::Match>, cur: usize }++enum Drag { None, Select { anchor: SelPoint, moved: bool, down: (f32, f32) }, Scrollbar { grab: f32 } }++// ---------- tabs ----------++struct Tab {+ uid: u64,+ page: Page,+ fields: Vec<Field>, // live copy of page.fields (what the user typed/selected)+ focus: Option<usize>, // focused page field; None = address bar+ caret: usize, // char index inside the focused field+ popup: Option<usize>, // open select list+ placed: Vec<Placed>,+ rects: Vec<Rect>,+ content_h: f32,+ layout_w: u32,+ layout_sc: f32,+ layout_vh: u32, // viewport height the layout was made for (position: fixed offsets depend on it)+ hover: usize, // DOM node under the pointer (0 = none), for :hover+ active: usize, // DOM node of the pressed mouse button, for :active+ applied: (usize, usize, usize), // (hover, active, focus) the item stream was last styled with+ pinned: Vec<(bool, usize, f32, f32, f32)>, // fixed/sticky items: (is rect, index, laid-out y, scroll offset at which it pins, travel limit or NAN)+ groups: std::collections::HashMap<u32, layout::Group>, // scroll containers of the layout+ moved: Vec<(bool, usize, f32, u32)>, // items inside scroll containers: (is rect, index, laid-out y, group)+ box_scroll: std::collections::HashMap<usize, f32>, // scroll offset per container node (device px)+ box_applied: bool, // `moved` items are placed for the current `box_scroll`+ pinned_at: f32, // scroll offset the pinned items are currently placed for (NAN = must be updated)+ dirty: bool,+ scroll: f32,+ url: String,+ title: String,+ input: String,+ fresh: bool, // address bar text is "selected": next key replaces it+ loading: bool,+ nav_id: u64,+ hist: Vec<String>,+ hpos: usize,+ zoom: f32,+ target: Option<f32>, // smooth-scroll destination+ sel: Option<(SelPoint, SelPoint)>,+ sugg: Vec<store::Entry>,+ sugg_sel: Option<usize>,+ bookmarked: bool,+ live: Option<js::Handle>, // running page scripts (events in, DOM updates out)+ scroll_sent: f32,+ scroll_at: std::time::Instant,+}++impl Tab {+ fn new(uid: u64) -> Tab {+ Tab {+ uid, page: Page { bg: 0xFFFFFF, ..Page::default() }, fields: vec![], focus: None, caret: 0, popup: None, placed: vec![], rects: vec![],+ content_h: 0.0, layout_w: 0, layout_sc: 1.0, layout_vh: 0, hover: 0, active: 0, applied: (0, 0, 0), pinned: vec![], pinned_at: f32::NAN, groups: Default::default(), moved: vec![], box_scroll: Default::default(), box_applied: false, dirty: true, scroll: 0.0, url: String::new(), title: String::new(), input: String::new(),+ fresh: false, loading: false, nav_id: 0, hist: vec![], hpos: 0, zoom: 1.0, target: None, sel: None, sugg: vec![], sugg_sel: None, bookmarked: false, live: None, scroll_sent: 0.0, scroll_at: std::time::Instant::now(),+ }+ }++ fn blank(uid: u64) -> Tab {+ let mut t = Tab::new(uid);+ t.page = render::build(&dom::parse("<h2>New tab</h2><p>Type an address or search words above and press Enter.</p>", true), "about:blank", Default::default());+ t.title = "New tab".into();+ t.fresh = true;+ t+ }++ fn navigate(&mut self, proxy: &EventLoopProxy<Msg>, url: String, push: bool, post: Option<String>) {+ self.nav_id += 1;+ self.loading = true;+ let (uid, id, proxy) = (self.uid, self.nav_id, proxy.clone());+ let live_proxy = proxy.clone();+ let hook: load::LiveHook = Box::new(move |ev| { let _ = live_proxy.send_event(Msg::Live { uid, id, ev }); });+ // Big stack: DOM/JSON/style recursion is bounded by dom::MAX_DEPTH but frames are large in debug builds.+ let _ = std::thread::Builder::new().stack_size(32 << 20).spawn(move || {+ let res = load::load(&url, post.as_deref(), Some(hook));+ let _ = proxy.send_event(Msg::Loaded { uid, id, url, push, res });+ });+ }++ fn loaded(&mut self, id: u64, url: String, push: bool, res: Result<(String, Page), String>) {+ if id != self.nav_id { return; } // a newer navigation superseded this one+ self.loading = false;+ let url = match res {+ Ok((final_url, mut page)) => {+ self.live = page.live.take();+ self.page = page;+ if push {+ self.hist.truncate(if self.hist.is_empty() { 0 } else { self.hpos + 1 });+ self.hist.push(final_url.clone());+ self.hpos = self.hist.len() - 1;+ }+ final_url+ }+ Err(e) => {+ self.live = None;+ let esc = |s: &str| s.replace('&', "&").replace('<', "<");+ self.page = render::build(&dom::parse(&format!("<h2>Could not load page</h2><p>{}</p><p>{}</p>", esc(&url), esc(&e)), true), &url, Default::default());+ url+ }+ };+ self.title = if self.page.title.is_empty() { url.clone() } else { self.page.title.clone() };+ self.input = url.clone();+ self.url = url;+ self.fresh = false;+ self.fields = self.page.fields.clone();+ self.focus = None;+ self.popup = None;+ self.scroll = 0.0;+ self.target = None;+ self.sel = None;+ self.sugg.clear();+ self.bookmarked = store::is_bookmarked(&self.url);+ store::add_history(&self.url, &self.title);+ self.dirty = true;+ }++ /// A live page re-rendered itself: swap in the new page, keep scroll, zoom and what the user typed.+ fn live_update(&mut self, id: u64, mut page: Page) {+ if id != self.nav_id || self.loading && self.live.is_none() { return; }+ merge_fields(&self.fields, &mut page.fields);+ self.focus = self.focus.and_then(|f| find_occurrence(&page.fields, self.fields[f].kind, &self.fields[f].name.clone(), occurrence(&self.fields, f)));+ self.popup = self.popup.filter(|&p| Some(p) == self.focus);+ self.fields = page.fields.clone();+ if !page.title.is_empty() { self.title = page.title.clone(); }+ self.page = page;+ self.sel = None;+ self.dirty = true;+ }++ /// Mirrors field `i` (typed text, check state, chosen option) into the page's DOM and fires `input`.+ fn live_value(&self, i: usize, fire: &[&str]) {+ let (Some(h), Some(f)) = (&self.live, self.fields.get(i)) else { return };+ match f.kind {+ FieldKind::Check | FieldKind::Radio => h.value(f.node, "", Some(f.checked)),+ _ => h.value(f.node, &f.value, None),+ }+ for k in fire { h.post(f.node, k, "{}"); }+ }++ /// Focus moves between page fields: blur/change for the old one, focus for the new one.+ fn set_focus(&mut self, new: Option<usize>) {+ if self.focus == new { return; }+ if let Some(i) = self.focus { self.commit_change(i); }+ if let Some(h) = &self.live {+ if let Some(f) = self.focus.and_then(|i| self.fields.get(i)) { h.post(f.node, "blur", "{}"); }+ if let Some(f) = new.and_then(|i| self.fields.get(i)) { h.post(f.node, "focus", "{}"); }+ }+ self.focus = new;+ }++ /// Node that receives key events: the focused field, else the page body.+ fn key_target(&self) -> usize { self.focus.and_then(|i| self.fields.get(i)).map_or(self.page.body, |f| f.node) }++ fn refresh_sugg(&mut self) {+ self.sugg = if self.focus.is_none() && !self.fresh { store::suggest(&self.input, 6) } else { vec![] };+ self.sugg_sel = None;+ }++ fn history(&mut self, proxy: &EventLoopProxy<Msg>, back: bool) {+ let target = if back { self.hpos.checked_sub(1) } else { Some(self.hpos + 1).filter(|&p| p < self.hist.len()) };+ if let Some(p) = target {+ self.hpos = p;+ let u = self.hist[p].clone();+ self.navigate(proxy, u, false, None);+ }+ }++ /// Submits the form that owns `field`; `submitter` (a button) contributes its own name/value.+ /// Enter or blur commits a changed field: `change` fires once per edit (a script that clears the field afterwards must not be overwritten by the old text on re-render).+ fn commit_change(&mut self, i: usize) {+ let Some(f) = self.fields.get_mut(i) else { return };+ if !matches!(f.kind, FieldKind::Text | FieldKind::Password | FieldKind::TextArea) || f.value == f.initial { return; }+ f.initial = f.value.clone();+ let node = f.node;+ if let Some(h) = &self.live { h.post(node, "change", "{}"); }+ }++ fn submit(&mut self, proxy: &EventLoopProxy<Msg>, field: usize, submitter: Option<usize>) {+ self.commit_change(field);+ let Some(f) = self.fields[field].form else { return };+ if let (Some(h), Some(form)) = (&self.live, self.page.forms.get(f)) { if h.event(form.node, "submit", "{}") { return; } } // a handler called preventDefault()+ let area_values: Vec<String> = self.fields.iter().map(|fl| if fl.kind == FieldKind::TextArea { fl.value.replace('\n', "\r\n") } else { String::new() }).collect();+ let mut pairs: Vec<(&str, &str)> = vec![];+ for (i, fl) in self.fields.iter().enumerate().filter(|(_, fl)| fl.form == Some(f) && !fl.name.is_empty()) {+ match fl.kind {+ FieldKind::Text | FieldKind::Password | FieldKind::Hidden | FieldKind::Select => pairs.push((&fl.name, &fl.value)),+ FieldKind::TextArea => pairs.push((&fl.name, &area_values[i])),+ FieldKind::Check | FieldKind::Radio => if fl.checked { pairs.push((&fl.name, if fl.value.is_empty() { "on" } else { &fl.value })) },+ FieldKind::Submit => if Some(i) == submitter { pairs.push((&fl.name, &fl.value)) },+ }+ }+ let (url, body) = form_request(&self.page.forms[f], &pairs);+ self.navigate(proxy, url, true, body);+ }++ fn set_radio(&mut self, i: usize) {+ let (form, name) = (self.fields[i].form, self.fields[i].name.clone());+ for (k, fl) in self.fields.iter_mut().enumerate() {+ if fl.kind == FieldKind::Radio && fl.form == form && fl.name == name && !name.is_empty() { fl.checked = k == i; }+ }+ self.fields[i].checked = true;+ let group: Vec<usize> = (0..self.fields.len()).filter(|&k| self.fields[k].kind == FieldKind::Radio && self.fields[k].form == form && self.fields[k].name == name && !name.is_empty() || k == i).collect();+ for k in group { self.live_value(k, if k == i { &["click", "input", "change"] } else { &[] }); }+ }++ fn select_option(&mut self, i: usize, sel: usize) {+ let fl = &mut self.fields[i];+ if let Some(o) = fl.options.get(sel) { fl.sel = sel; fl.value = o.0.clone(); }+ self.live_value(i, &["input", "change"]);+ }++ /// Next/previous focusable text-like control in document order (wraps around).+ fn tab_target(&self, back: bool) -> Option<usize> {+ let ok: Vec<usize> = self.placed.iter().filter_map(|p| p.field).filter(|&i| matches!(self.fields[i].kind, FieldKind::Text | FieldKind::Password | FieldKind::TextArea | FieldKind::Select)).collect();+ if ok.is_empty() { return None; }+ let pos = self.focus.and_then(|f| ok.iter().position(|&i| i == f));+ Some(match (pos, back) {+ (None, false) => ok[0],+ (None, true) => ok[ok.len() - 1],+ (Some(p), false) => ok[(p + 1) % ok.len()],+ (Some(p), true) => ok[(p + ok.len() - 1) % ok.len()],+ })+ }++ fn placed_field(&self, i: usize) -> Option<&Placed> { self.placed.iter().find(|p| p.field == Some(i)) }+}++struct App {+ proxy: EventLoopProxy<Msg>,+ window: Option<Arc<Window>>,+ surface: Option<softbuffer::Surface<Arc<Window>, Arc<Window>>>,+ fonts: Fonts,+ tabs: Vec<Tab>,+ cur: usize,+ next_uid: u64,+ sc: f32,+ mouse: PhysicalPosition<f64>,+ cursor: CursorIcon,+ mods: ModifiersState,+ exit: bool,+ find: Option<Find>,+ closed: Vec<String>,+ drag: Drag,+ page_focus: bool, // last click was inside the page (Ctrl+A / Ctrl+C act on page text)+ last_click: Option<(std::time::Instant, f32, f32)>,+ pending: (Vec<String>, usize), // tabs of the previous session still to open+ notice: Option<String>, // one-line message at the bottom (cleared by the next key or click)+}++impl App {+ fn redraw(&self) { if let Some(w) = &self.window { w.request_redraw(); } }+ fn t(&mut self) -> &mut Tab { &mut self.tabs[self.cur] }+ fn top(&self) -> f32 { (TAB_H + BAR) * self.sc }++ fn sync_title(&self) {+ if let Some(w) = &self.window {+ let t = &self.tabs[self.cur];+ w.set_title(&if t.title.is_empty() { "chrome-rs".to_string() } else { format!("{} - chrome-rs", t.title) });+ }+ }++ fn new_tab(&mut self, url: Option<String>) {+ self.next_uid += 1;+ let mut t = match &url { Some(_) => Tab::new(self.next_uid), None => Tab::blank(self.next_uid) };+ if let Some(u) = url { t.navigate(&self.proxy, u, true, None); }+ self.tabs.push(t);+ self.cur = self.tabs.len() - 1;+ self.sync_title();+ self.redraw();+ }++ fn close_tab(&mut self, i: usize) {+ if self.tabs.len() == 1 { store::save_session(&[], 0); self.exit = true; return; }+ if store::recordable(&self.tabs[i].url) { self.closed.push(self.tabs[i].url.clone()); }+ self.tabs.remove(i);+ if i < self.cur || self.cur >= self.tabs.len() { self.cur = self.cur.saturating_sub(1); }+ self.sync_title();+ self.redraw();+ }++ fn switch_tab(&mut self, i: usize) {+ self.cur = i % self.tabs.len();+ self.sync_title();+ self.redraw();+ }++ /// Ctrl+P: renders the whole page at A4-ish width into a PDF under the data dir's `prints` folder.+ fn print_pdf(&mut self) {+ let t = &self.tabs[self.cur];+ let (buf_w, name) = (794u32, format!("{}.pdf", t.title.chars().filter(|c| c.is_alphanumeric()).take(40).collect::<String>().trim()));+ let (w, h, buf) = snap::paint(&t.page, buf_w, &mut self.fonts);+ let bytes = snap::pdf(&buf, w, h);+ let dir = store::data_dir().map(|d| d.join("prints"));+ self.notice = Some(match dir.and_then(|d| { std::fs::create_dir_all(&d).ok()?; let p = d.join(if name == ".pdf" { "page.pdf".to_string() } else { name }); std::fs::write(&p, &bytes).ok()?; Some(p) }) {+ Some(p) => format!("Saved PDF: {}", p.display()),+ None => "Could not save the PDF".to_string(),+ });+ self.redraw();+ }++ fn save_session(&self) { store::save_session(&self.tabs.iter().map(|t| t.url.clone()).collect::<Vec<_>>(), self.cur); }++ fn set_zoom(&mut self, z: f32) {+ let t = &mut self.tabs[self.cur];+ let z = z.clamp(0.3, 5.0);+ t.scroll *= z / t.zoom;+ t.target = None;+ t.zoom = z;+ t.dirty = true;+ self.redraw();+ }++ /// (track x, thumb y, thumb h, viewport h, max scroll) of the page scrollbar; None when the page fits.+ fn scrollbar(&self) -> Option<(f32, f32, f32, f32, f32)> {+ let (win, t, top) = (self.window.as_ref()?, &self.tabs[self.cur], self.top());+ let size = win.inner_size();+ let view = size.height as f32 - top - if self.find.is_some() { 32.0 * self.sc } else { 0.0 };+ let max = t.content_h - view;+ if max <= 1.0 || view < 40.0 { return None; }+ let th = (view * view / t.content_h).max(30.0 * self.sc).min(view);+ Some((size.width as f32 - 12.0 * self.sc, top + t.scroll / max * (view - th), th, view, max))+ }++ fn recompute_find(&mut self) {+ let Some(f) = self.find.as_mut() else { return };+ f.matches = browse::find_matches(&self.tabs[self.cur].placed, &f.query, &mut self.fonts);+ f.cur = 0;+ self.find_reveal();+ }++ /// Scrolls the current find match into view (centered).+ fn find_reveal(&mut self) {+ let (top, sc) = (self.top(), self.sc);+ let vh = self.viewport_h();+ let Some(f) = &self.find else { return };+ let t = &mut self.tabs[self.cur];+ if let Some(&(i, _, _)) = f.matches.get(f.cur).and_then(|m| m.parts.first()) {+ let p = &t.placed[i];+ let view = (vh - top - 32.0 * sc).max(40.0);+ if p.base - p.size < t.scroll || p.base > t.scroll + view { t.scroll = (p.base - view / 2.0).max(0.0); t.target = None; }+ }+ }++ /// `CHROME_RS_SELFTEST=1`: drives find, selection, zoom, suggestions, smooth scroll and the scrollbar through real paints, then exits.+ fn selftest(&mut self) {+ self.paint();+ self.find = Some(Find { query: "e".into(), matches: vec![], cur: 0 });+ self.recompute_find();+ let t = &mut self.tabs[self.cur];+ if let Some(r) = browse::all(&t.placed) { t.sel = Some(r); }+ t.sugg = vec![store::Entry { url: "https://x.test/".into(), title: "x".into(), time: 0 }];+ t.sugg_sel = Some(0);+ t.bookmarked = true;+ self.set_zoom(1.5);+ self.paint();+ self.scroll_by(400.0);+ for _ in 0..40 { self.paint(); }+ let sb = self.scrollbar().is_some();+ self.set_zoom(0.5);+ self.paint();+ let (n, h, sel) = (self.find.as_ref().map_or(0, |f| f.matches.len()), self.tabs[self.cur].content_h, self.tabs[self.cur].sel.is_some());+ println!("selftest ok: matches={n} content_h={h:.0} scrollbar={sb} selection={sel} title={:?}", self.tabs[self.cur].title);+ std::process::exit(0);+ }++ fn tab_width(&self, bw: f32) -> f32 { (220.0 * self.sc).min((bw - 40.0 * self.sc) / self.tabs.len() as f32) }++ /// What is under the mouse in the page area.+ fn field_at(&self) -> Option<usize> {+ let (mx, my, top) = (self.mouse.x as f32, self.mouse.y as f32, self.top());+ let t = &self.tabs[self.cur];+ t.placed.iter().find(|p| {+ let y = p.base - t.scroll + top;+ p.field.is_some() && mx >= p.x && mx <= p.x + p.w && my >= y - p.size && my <= y+ }).and_then(|p| p.field)+ }++ fn link_at(&self) -> Option<usize> {+ let (mx, my, top) = (self.mouse.x as f32, self.mouse.y as f32, self.top());+ let t = &self.tabs[self.cur];+ t.placed.iter().find(|p| {+ let y = p.base - t.scroll + top;+ p.link.is_some() && mx >= p.x && mx <= p.x + p.w && my >= y - p.size && my <= y + p.size * 0.3+ }).and_then(|p| p.link)+ }++ /// Wheel over a scroll container that can still move in that direction scrolls it instead of the page; true when it did.+ fn scroll_container(&mut self, dy: f32) -> bool {+ let (mx, my, top, sc) = (self.mouse.x as f32, self.mouse.y as f32, self.top(), self.sc);+ let t = &mut self.tabs[self.cur];+ if my < top { return false; }+ let (px, py, d) = (mx, my - top + t.scroll, dy * sc);+ let best = t.groups.values().filter(|g| px >= g.x && px <= g.x + g.w && py >= g.y && py <= g.y + g.h).filter(|g| {+ let (max, cur) = ((g.content_h - g.h).max(0.0), t.box_scroll.get(&g.node).copied().unwrap_or(0.0));+ max > 0.5 && (d > 0.0 && cur < max - 0.5 || d < 0.0 && cur > 0.5)+ }).min_by(|a, b| (a.w * a.h).total_cmp(&(b.w * b.h))).copied(); // the innermost one+ let Some(g) = best else { return false };+ let cur = t.box_scroll.get(&g.node).copied().unwrap_or(0.0);+ t.box_scroll.insert(g.node, (cur + d).clamp(0.0, (g.content_h - g.h).max(0.0)));+ t.box_applied = false;+ self.redraw();+ true+ }++ fn scroll_by(&mut self, dy: f32) {+ let sc = self.sc;+ let t = self.t();+ t.target = Some(t.target.unwrap_or(t.scroll) + dy * sc);+ self.redraw();+ }++ /// Scrolls so that field `i` is on screen.+ fn reveal(&mut self, i: usize, viewport_h: f32) {+ let top = self.top();+ let t = &mut self.tabs[self.cur];+ if let Some(p) = t.placed_field(i) {+ let (y0, y1) = (p.base - p.size, p.base);+ let view = (viewport_h - top).max(0.0);+ t.target = None;+ if y0 < t.scroll { t.scroll = (y0 - 40.0).max(0.0); }+ else if y1 > t.scroll + view { t.scroll = y1 - view + 40.0; }+ }+ }++ fn viewport_h(&self) -> f32 { self.window.as_ref().map_or(720.0, |w| w.inner_size().height as f32) }++ fn paint(&mut self) {+ let (Some(win), Some(surf)) = (&self.window, &mut self.surface) else { return };+ let size = win.inner_size();+ let (Some(w), Some(h)) = (NonZeroU32::new(size.width), NonZeroU32::new(size.height)) else { return };+ surf.resize(w, h).unwrap();+ let sc = win.scale_factor() as f32;+ self.sc = sc;+ let csc = sc * self.tabs[self.cur].zoom;+ let (bw, bh) = (size.width as usize, size.height as usize);+ let (tab_h, bar_h) = ((TAB_H * sc) as usize, (BAR * sc) as usize);+ let top = tab_h + bar_h;+ let tw = (220.0 * sc).min((bw as f32 - 40.0 * sc) / self.tabs.len() as f32);+ let strip: Vec<(String, bool)> = self.tabs.iter().enumerate().map(|(i, t)| {+ (if t.loading && t.title.is_empty() { "Loading...".to_string() } else { t.title.clone() }, i == self.cur)+ }).collect();+ let find_h = if self.find.is_some() { (32.0 * sc) as usize } else { 0 };+ let t = &mut self.tabs[self.cur];+ // :hover / :active / :focus change what the CSS selects: restyle from the kept DOM when that state moved+ let focus_node = t.focus.and_then(|i| t.fields.get(i)).map_or(0, |f| f.node);+ let want = (t.hover, t.active, focus_node);+ if want != t.applied {+ t.applied = want;+ if let Some(src) = t.page.restyle.clone() {+ css::set_state(want.0, want.1, want.2);+ let np = render::restyled(&src);+ (t.page.items, t.page.images, t.page.bg) = (np.items, np.images, np.bg);+ t.dirty = true;+ }+ }+ let vh = bh.saturating_sub(top + find_h) as u32;+ if t.dirty || t.layout_w != size.width || t.layout_sc != csc || t.layout_vh != vh {+ (t.placed, t.rects, t.content_h) = layout::layout_vh(&t.page.items, size.width as f32, csc, vh as f32, &mut self.fonts);+ t.layout_vh = vh;+ t.pinned = t.placed.iter().enumerate().filter(|(_, p)| !p.st.is_nan()).map(|(i, p)| (false, i, p.base, p.st, p.lim))+ .chain(t.rects.iter().enumerate().filter(|(_, r)| !r.st.is_nan()).map(|(i, r)| (true, i, r.y, r.st, r.lim))).collect();+ t.groups = layout::groups(&t.rects);+ t.moved = t.placed.iter().enumerate().filter(|(_, p)| p.grp != 0).map(|(i, p)| (false, i, p.base, p.grp))+ .chain(t.rects.iter().enumerate().filter(|(_, r)| r.grp != 0 && r.scroll.is_nan()).map(|(i, r)| (true, i, r.y, r.grp))).collect();+ t.box_applied = false;+ t.pinned_at = f32::NAN;+ t.layout_w = size.width;+ t.layout_sc = csc;+ t.dirty = false;+ if let Some(f) = self.find.as_mut() { f.matches = browse::find_matches(&t.placed, &f.query, &mut self.fonts); f.cur = f.cur.min(f.matches.len().saturating_sub(1)); }+ if let Some(h) = &t.live {+ h.resize((size.width as f32 / csc) as u32, (bh.saturating_sub(top) as f32 / csc) as u32);+ if let Ok(j) = serde_json::to_string(&browse::node_boxes(&t.placed, &t.rects, &t.page.parents, csc)) { h.boxes(j); }+ }+ if std::env::var_os("CHROME_RS_DEBUG").is_some() {+ for p in t.placed.iter().take(12) { eprintln!("x={:.0} base={:.0} size={:.0} w={:.0} img={:?} {:?}", p.x, p.base, p.size, p.w, p.img, p.text); }+ }+ }+ let max_scroll = (t.content_h - (bh.saturating_sub(top + find_h)) as f32).max(0.0);+ let mut animating = false;+ if let Some(tg) = t.target {+ let tg = tg.clamp(0.0, max_scroll);+ let d = tg - t.scroll;+ if d.abs() < 1.0 { t.scroll = tg; t.target = None; } else { t.scroll += d * 0.35; animating = true; }+ }+ t.scroll = t.scroll.clamp(0.0, max_scroll);+ // fixed and sticky boxes follow the viewport: move them in page coordinates so painting and hit-testing agree+ if !t.pinned.is_empty() && t.pinned_at != t.scroll {+ for &(is_rect, i, orig, st, lim) in &t.pinned {+ let v = orig + (t.scroll - st).max(0.0).min(if lim.is_nan() { f32::MAX } else { lim });+ if is_rect { t.rects[i].y = v; } else { t.placed[i].base = v; }+ }+ t.pinned_at = t.scroll;+ }+ // scroll containers: content moves by the container's offset; painting clips it to the box+ if !t.box_applied {+ let off = |g: u32| t.groups.get(&g).map_or(0.0, |gb| t.box_scroll.get(&gb.node).copied().unwrap_or(0.0).clamp(0.0, (gb.content_h - gb.h).max(0.0)));+ let offs: Vec<(bool, usize, f32)> = t.moved.iter().map(|&(is_rect, i, orig, g)| (is_rect, i, orig - off(g))).collect();+ for (is_rect, i, v) in offs { if is_rect { t.rects[i].y = v; } else { t.placed[i].base = v; } }+ t.box_applied = true;+ }+ if let Some(h) = &t.live {+ if (t.scroll - t.scroll_sent).abs() > 1.0 && t.scroll_at.elapsed().as_millis() > 100 { h.scroll(t.scroll / csc); t.scroll_sent = t.scroll; t.scroll_at = std::time::Instant::now(); }+ }+ let mut buf = surf.buffer_mut().unwrap();+ buf.fill(t.page.bg);+ let dy = top as f32 - t.scroll;+ // paint layers: negative z behind the page text, positioned boxes above it, `fixed` boxes last and at screen coordinates+ let box_clip = |g: u32| t.groups.get(&g).map(|b| (b.x as i32, (b.y + dy) as i32, (b.x + b.w).ceil() as i32, (b.y + b.h + dy).ceil() as i32));+ for (z, rr, pr) in layout::layers(&t.placed, &t.rects) {+ let dz = dy;+ for r in &t.rects[rr.clone()] {+ let y = r.y + dz;+ if y + r.h >= top as f32 && y < bh as f32 {+ gfx::set_clip(box_clip(r.grp).filter(|_| r.scroll.is_nan()));+ gfx::draw_rect(&mut buf, bw, bh, r, dz);+ if let Some(pic) = &r.pic { gfx::draw_pic(&mut buf, bw, bh, &t.page.images[pic.img], r, dz); }+ }+ }+ gfx::set_clip(None);+ if z == 0 {+ if let Some(f) = &self.find {+ for (k, m) in f.matches.iter().enumerate() {+ for &(i, off, w) in &m.parts {+ let p = &t.placed[i];+ fill(&mut buf, bw, (p.x + off) as i32, (p.base - p.size + dy) as i32, w as i32 + 1, (p.size * 1.25) as i32, if k == f.cur { 0xFFA040 } else { 0xFFE066 });+ }+ }+ }+ if let Some((a, b)) = t.sel {+ for (x, y, w, h) in browse::selection_rects(&t.placed, a, b, &mut self.fonts) { fill(&mut buf, bw, x as i32, (y + dy) as i32, w as i32 + 1, h as i32, 0xB3D4FF); }+ }+ }+ for p in &t.placed[pr] {+ let y = p.base + dz;+ if y < top as f32 || y - p.size > bh as f32 { continue; }+ gfx::set_clip(box_clip(p.grp));+ if let Some(i) = p.img {+ draw_image(&mut buf, bw, bh, &t.page.images[i], p.x, y - p.size, p.w, p.size, if p.color == 0 { 255 } else { p.color });+ continue;+ }+ if let Some(i) = p.field {+ let caret = (t.focus == Some(i)).then_some(t.caret);+ draw_field(&mut buf, bw, bh, &mut self.fonts, &t.fields[i], caret, csc, p.x, y - p.size, p.w, p.size);+ continue;+ }+ gfx::draw_text_ls(&mut buf, bw, bh, &mut self.fonts, &p.text, p.x, y, p.size, p.color, p.face, p.ls);+ if p.ul { fill(&mut buf, bw, p.x as i32, y as i32 + 2, p.w as i32, 1, p.color); }+ }+ gfx::set_clip(None);+ for r in t.rects[rr].iter().filter(|r| r.scroll.is_finite()) {+ gfx::draw_box_scrollbar(&mut buf, bw, bh, r.x, r.y + dz, r.w, r.h, r.scroll, t.box_scroll.get(&r.node).copied().unwrap_or(0.0), csc);+ }+ }+ if let Some(i) = t.popup {+ if let Some(p) = t.placed_field(i) {+ let y = p.base - t.scroll + top as f32;+ draw_popup(&mut buf, bw, bh, &mut self.fonts, &t.fields[i], p.x, y, p.w, p.size);+ }+ }++ // page scrollbar+ let view = (bh.saturating_sub(top + find_h)) as f32;+ if max_scroll > 1.0 && view > 40.0 {+ let th = (view * view / t.content_h).max(30.0 * sc).min(view);+ let ty = top as f32 + t.scroll / max_scroll * (view - th);+ gfx::draw_rrect(&mut buf, bw, bh, bw as f32 - 9.0 * sc, ty, 6.0 * sc, th, 3.0 * sc, 0.0, 0x9A9A9A);+ }++ // find bar+ if let Some(f) = &self.find {+ let y0 = bh - find_h;+ fill(&mut buf, bw, 0, y0 as i32, bw as i32, find_h as i32, 0xE8E8E8);+ fill(&mut buf, bw, 0, y0 as i32, bw as i32, 1, 0xB0B0B0);+ let label = if f.query.is_empty() { String::new() } else if f.matches.is_empty() { "no matches".to_string() } else { format!("{}/{}", f.cur + 1, f.matches.len()) };+ let text = format!("Find: {}|", f.query);+ let fs = 15.0 * sc;+ draw_text(&mut buf, bw, bh, &mut self.fonts, &text, 12.0 * sc, y0 as f32 + 21.0 * sc, fs, 0x111111);+ let lw = self.fonts.width(&label, fs);+ draw_text(&mut buf, bw, bh, &mut self.fonts, &label, bw as f32 - lw - 24.0 * sc, y0 as f32 + 21.0 * sc, fs, 0x555555);+ }++ if let Some(n) = &self.notice {+ let y0 = bh.saturating_sub((30.0 * sc) as usize + find_h);+ fill(&mut buf, bw, 0, y0 as i32, bw as i32, (30.0 * sc) as i32, 0x333333);+ draw_text(&mut buf, bw, bh, &mut self.fonts, n, 12.0 * sc, y0 as f32 + 20.0 * sc, 14.0 * sc, 0xFFFFFF);+ }++ // tab strip+ fill(&mut buf, bw, 0, 0, bw as i32, tab_h as i32, 0xC8C8C8);+ let fs = 13.0 * sc;+ for (i, (title, active)) in strip.iter().enumerate() {+ let x = i as f32 * tw;+ fill(&mut buf, bw, x as i32 + 1, (4.0 * sc) as i32, tw as i32 - 2, tab_h as i32 - (4.0 * sc) as i32, if *active { 0xE8E8E8 } else { 0xB8B8B8 });+ let mut label = title.clone();+ while label.chars().count() > 1 && self.fonts.width(&label, fs) > tw - 34.0 * sc { label.pop(); }+ draw_text(&mut buf, bw, bh, &mut self.fonts, &label, x + 10.0 * sc, 21.0 * sc, fs, 0x111111);+ draw_text(&mut buf, bw, bh, &mut self.fonts, "x", x + tw - 18.0 * sc, 21.0 * sc, fs, 0x444444);+ }+ draw_text(&mut buf, bw, bh, &mut self.fonts, "+", strip.len() as f32 * tw + 11.0 * sc, 23.0 * sc, 18.0 * sc, 0x333333);++ // address bar+ fill(&mut buf, bw, 0, tab_h as i32, bw as i32, bar_h as i32, 0xE8E8E8);+ let (tx, ty, ts) = (10.0 * sc, tab_h as f32 + 26.0 * sc, 16.0 * sc);+ if t.fresh {+ let w = self.fonts.width(&t.input, ts);+ fill(&mut buf, bw, tx as i32, tab_h as i32 + (8.0 * sc) as i32, w as i32 + 1, (24.0 * sc) as i32, 0xB3D4FF);+ }+ draw_text(&mut buf, bw, bh, &mut self.fonts, &t.input, tx, ty, ts, 0x000000);+ if t.loading {+ let msg = "Loading...";+ let w = self.fonts.width(msg, ts);+ draw_text(&mut buf, bw, bh, &mut self.fonts, msg, bw as f32 - w - tx, ty, ts, 0x666666);+ } else if !t.fresh && t.focus.is_none() {+ let w = self.fonts.width(&t.input, ts);+ fill(&mut buf, bw, (tx + w) as i32 + 1, tab_h as i32 + (8.0 * sc) as i32, 1, (24.0 * sc) as i32, 0x000000);+ }+ // right side of the address bar: zoom level and bookmark star+ let mut rx = bw as f32 - 14.0 * sc;+ if t.bookmarked { let w = self.fonts.width("\u{2605}", ts); rx -= w; draw_text(&mut buf, bw, bh, &mut self.fonts, "\u{2605}", rx, ty, ts, 0xE8A400); rx -= 10.0 * sc; }+ if (t.zoom - 1.0).abs() > 0.001 && !t.loading { let z = format!("{}%", (t.zoom * 100.0).round()); let w = self.fonts.width(&z, ts * 0.85); draw_text(&mut buf, bw, bh, &mut self.fonts, &z, rx - w, ty, ts * 0.85, 0x555555); }+ // address suggestions+ if !t.sugg.is_empty() {+ let row = 26.0 * sc;+ let bx = 8.0 * sc;+ let width = (bw as f32 - 2.0 * bx).min(900.0 * sc);+ fill(&mut buf, bw, bx as i32 - 1, top as i32, width as i32 + 2, (row * t.sugg.len() as f32) as i32 + 1, 0x999999);+ for (i, e) in t.sugg.iter().enumerate() {+ let y = top as f32 + i as f32 * row;+ fill(&mut buf, bw, bx as i32, y as i32, width as i32, row as i32 - if i + 1 == t.sugg.len() { 0 } else { 1 }, if t.sugg_sel == Some(i) { 0xD6E6FF } else { 0xFFFFFF });+ let label = if e.title.is_empty() { e.url.clone() } else { format!("{} - {}", e.title, e.url) };+ let mut label = label;+ while label.chars().count() > 1 && self.fonts.width(&label, 14.0 * sc) > width - 16.0 * sc { label.pop(); }+ draw_text(&mut buf, bw, bh, &mut self.fonts, &label, bx + 8.0 * sc, y + 18.0 * sc, 14.0 * sc, 0x111111);+ }+ }+ buf.present().unwrap();+ if animating { win.request_redraw(); }+ }++ fn key(&mut self, key: &Key, text: Option<&str>) {+ self.notice = None;+ let (ctrl, alt, shift) = (self.mods.control_key(), self.mods.alt_key(), self.mods.shift_key());+ let proxy = self.proxy.clone();+ let vh = self.viewport_h();+ let ntabs = self.tabs.len();+ // find bar owns plain typing while it is open+ if self.find.is_some() && !ctrl && !alt {+ match key {+ Key::Named(NamedKey::Escape) => { self.find = None; }+ Key::Named(NamedKey::Enter) => if let Some(f) = self.find.as_mut().filter(|f| !f.matches.is_empty()) {+ f.cur = if shift { (f.cur + f.matches.len() - 1) % f.matches.len() } else { (f.cur + 1) % f.matches.len() };+ self.find_reveal();+ },+ Key::Named(NamedKey::Backspace) => { if let Some(f) = self.find.as_mut() { f.query.pop(); } self.recompute_find(); }+ _ => if let Some(s) = text.filter(|s| !s.is_empty() && !s.chars().any(char::is_control)) {+ if let Some(f) = self.find.as_mut() { f.query.push_str(s); }+ self.recompute_find();+ } else if !matches!(key, Key::Named(NamedKey::PageDown | NamedKey::PageUp | NamedKey::ArrowDown | NamedKey::ArrowUp | NamedKey::Home | NamedKey::End | NamedKey::F5)) { return; },+ }+ if matches!(key, Key::Named(NamedKey::Escape | NamedKey::Enter | NamedKey::Backspace)) || text.is_some_and(|s| !s.chars().any(char::is_control) && !s.is_empty()) { self.redraw(); return; }+ }+ // browser-level shortcuts first+ match key {+ Key::Named(NamedKey::F3) => if let Some(f) = self.find.as_mut().filter(|f| !f.matches.is_empty()) {+ f.cur = if shift { (f.cur + f.matches.len() - 1) % f.matches.len() } else { (f.cur + 1) % f.matches.len() };+ self.find_reveal();+ self.redraw();+ return;+ },+ Key::Character(c) if ctrl => match c.to_lowercase().as_str() {+ "t" if shift => { if let Some(u) = self.closed.pop() { self.new_tab(Some(u)); } return; }+ "t" => { self.new_tab(None); return; }+ "w" => { self.close_tab(self.cur); return; }+ "f" => { if self.find.is_none() { self.find = Some(Find { query: String::new(), matches: vec![], cur: 0 }); } self.redraw(); return; }+ "g" => if let Some(f) = self.find.as_mut().filter(|f| !f.matches.is_empty()) {+ f.cur = if shift { (f.cur + f.matches.len() - 1) % f.matches.len() } else { (f.cur + 1) % f.matches.len() };+ self.find_reveal();+ self.redraw();+ return;+ },+ "p" => { self.print_pdf(); return; }+ "d" => { let t = &mut self.tabs[self.cur]; t.bookmarked = store::toggle_bookmark(&t.url.clone(), &t.title.clone()); self.redraw(); return; }+ "h" => { self.new_tab(Some("about:history".into())); return; }+ "b" => { self.new_tab(Some("about:bookmarks".into())); return; }+ "=" | "+" => { let z = zoom_step(self.tabs[self.cur].zoom, true); self.set_zoom(z); return; }+ "-" | "_" => { let z = zoom_step(self.tabs[self.cur].zoom, false); self.set_zoom(z); return; }+ "0" => { self.set_zoom(1.0); return; }+ d if d.len() == 1 && d.as_bytes()[0].is_ascii_digit() && d != "0" => { let n = (d.as_bytes()[0] - b'1') as usize; if n < ntabs { self.switch_tab(n); } return; }+ _ => {}+ },+ Key::Named(NamedKey::Tab) if ctrl => { self.switch_tab(if shift { self.cur + ntabs - 1 } else { self.cur + 1 }); return; }+ Key::Named(NamedKey::PageDown) if ctrl => { self.switch_tab(self.cur + 1); return; }+ Key::Named(NamedKey::PageUp) if ctrl => { self.switch_tab(self.cur + ntabs - 1); return; }+ _ => {}+ }+ let t = &mut self.tabs[self.cur];+ // the page sees plain key presses (not browser shortcuts); Enter in a field can be vetoed before it submits+ let mut enter_vetoed = false;+ if let (Some(h), false, false) = (&t.live, ctrl, alt) {+ if let Some(k) = key_name(key).filter(|_| t.focus.is_some() || self.page_focus || t.page.body != 0 && matches!(key, Key::Named(NamedKey::Escape))) {+ let init = serde_json::json!({ "key": k, "shiftKey": shift, "ctrlKey": ctrl, "altKey": alt }).to_string();+ if matches!(key, Key::Named(NamedKey::Enter)) { enter_vetoed = h.event(t.key_target(), "keydown", &init); if !enter_vetoed { h.post(t.key_target(), "keypress", &init); } } else { h.post(t.key_target(), "keydown", &init); if matches!(key, Key::Character(_)) { h.post(t.key_target(), "keypress", &init); } }+ }+ }+ if enter_vetoed { self.redraw(); return; }+ // a focused page field gets editing keys first+ if let Some(i) = t.focus {+ let kind = t.fields[i].kind;+ if t.popup.is_some() {+ match key {+ Key::Named(NamedKey::Escape | NamedKey::Enter) => t.popup = None,+ Key::Named(NamedKey::ArrowDown) => { let s = (t.fields[i].sel + 1).min(t.fields[i].options.len().saturating_sub(1)); t.select_option(i, s); }+ Key::Named(NamedKey::ArrowUp) => { let s = t.fields[i].sel.saturating_sub(1); t.select_option(i, s); }+ _ => {}+ }+ self.redraw();+ return;+ }+ if kind == FieldKind::Select {+ match key {+ Key::Named(NamedKey::ArrowDown) => { let s = (t.fields[i].sel + 1).min(t.fields[i].options.len().saturating_sub(1)); t.select_option(i, s); self.redraw(); return; }+ Key::Named(NamedKey::ArrowUp) => { let s = t.fields[i].sel.saturating_sub(1); t.select_option(i, s); self.redraw(); return; }+ Key::Named(NamedKey::Space) => { t.popup = Some(i); self.redraw(); return; }+ Key::Named(NamedKey::Enter) => { t.submit(&proxy, i, None); self.redraw(); return; }+ _ => {}+ }+ } else if !ctrl && !alt {+ let mut caret = t.caret;+ let handled = match key {+ Key::Named(NamedKey::Enter) if kind != FieldKind::TextArea => false,+ _ => edit_field(&mut t.fields[i], &mut caret, key, text),+ };+ t.caret = caret;+ if handled { t.live_value(i, &["input"]); self.redraw(); return; }+ }+ }+ match key {+ Key::Named(NamedKey::Tab) => {+ let t = &mut self.tabs[self.cur];+ if let Some(i) = t.tab_target(shift) {+ t.set_focus(Some(i));+ t.popup = None;+ t.caret = t.fields[i].value.chars().count();+ self.reveal(i, vh);+ }+ }+ Key::Named(NamedKey::Enter) => {+ let t = &mut self.tabs[self.cur];+ match t.focus {+ Some(i) => t.submit(&proxy, i, None),+ None => {+ let u = t.sugg_sel.and_then(|i| t.sugg.get(i)).map_or_else(|| to_url(&t.input), |e| e.url.clone());+ t.sugg.clear();+ t.navigate(&proxy, u, true, None);+ }+ }+ }+ Key::Named(NamedKey::ArrowDown) if !self.tabs[self.cur].sugg.is_empty() && self.tabs[self.cur].focus.is_none() => {+ let t = &mut self.tabs[self.cur];+ t.sugg_sel = Some(t.sugg_sel.map_or(0, |i| (i + 1).min(t.sugg.len() - 1)));+ }+ Key::Named(NamedKey::ArrowUp) if !self.tabs[self.cur].sugg.is_empty() && self.tabs[self.cur].focus.is_none() => {+ let t = &mut self.tabs[self.cur];+ t.sugg_sel = t.sugg_sel.and_then(|i| i.checked_sub(1));+ }+ Key::Named(NamedKey::Escape) => {+ let t = &mut self.tabs[self.cur];+ t.sugg.clear();+ if t.focus.take().is_none() { t.input = t.url.clone(); t.fresh = false; }+ }+ Key::Named(NamedKey::Backspace) => {+ let t = &mut self.tabs[self.cur];+ if t.fresh { t.input.clear(); t.fresh = false } else { t.input.pop(); }+ t.refresh_sugg();+ }+ Key::Named(NamedKey::ArrowLeft) if alt => self.tabs[self.cur].history(&proxy, true),+ Key::Named(NamedKey::ArrowRight) if alt => self.tabs[self.cur].history(&proxy, false),+ Key::Named(NamedKey::F5) => { let t = &mut self.tabs[self.cur]; let u = t.url.clone(); t.navigate(&proxy, u, false, None); }+ Key::Named(NamedKey::ArrowDown) => self.scroll_by(48.0),+ Key::Named(NamedKey::ArrowUp) => self.scroll_by(-48.0),+ Key::Named(NamedKey::PageDown) => self.scroll_by(500.0),+ Key::Named(NamedKey::PageUp) => self.scroll_by(-500.0),+ Key::Named(NamedKey::Home) => { let t = &mut self.tabs[self.cur]; t.scroll = 0.0; t.target = None; }+ Key::Named(NamedKey::End) => { let t = &mut self.tabs[self.cur]; t.scroll = f32::MAX; t.target = None; }+ Key::Character(c) if ctrl => {+ let t = &mut self.tabs[self.cur];+ match c.as_str() {+ "l" => { t.fresh = true; t.focus = None; self.page_focus = false; }+ "a" => if t.focus.is_none() {+ match browse::all(&t.placed).filter(|_| self.page_focus) { Some(r) => t.sel = Some(r), None => t.fresh = true }+ },+ "c" => {+ let s = match (t.focus, t.sel) {+ (Some(i), _) => t.fields[i].value.clone(),+ (None, Some((a, b))) if self.page_focus => browse::selected_text(&t.placed, a, b),+ _ => t.input.clone(),+ };+ let _ = arboard::Clipboard::new().and_then(|mut cb| cb.set_text(s));+ }+ "v" => if let Ok(s) = arboard::Clipboard::new().and_then(|mut cb| cb.get_text()) {+ match t.focus {+ Some(i) if matches!(t.fields[i].kind, FieldKind::Text | FieldKind::Password | FieldKind::TextArea) => {+ let s: String = if t.fields[i].kind == FieldKind::TextArea { s.replace("\r\n", "\n").chars().filter(|c| *c == '\n' || !c.is_control()).collect() } else { s.lines().next().unwrap_or("").chars().filter(|c| !c.is_control()).collect() };+ let mut caret = t.caret;+ let at = byte_at(&t.fields[i].value, caret);+ t.fields[i].value.insert_str(at, &s);+ caret += s.chars().count();+ t.caret = caret;+ t.live_value(i, &["input"]);+ }+ Some(_) => {}+ None => {+ let s: String = s.lines().next().unwrap_or("").chars().filter(|c| !c.is_control()).collect();+ if t.fresh { t.input.clear(); t.fresh = false; }+ t.input.push_str(&s);+ t.refresh_sugg();+ }+ }+ },+ "r" => { let u = t.url.clone(); t.navigate(&proxy, u, false, None); }+ _ => {}+ }+ }+ _ if !ctrl => if let Some(s) = text.filter(|s| !s.chars().any(char::is_control)) {+ let t = &mut self.tabs[self.cur];+ if t.focus.is_none() {+ if t.fresh { t.input.clear(); t.fresh = false; }+ t.input.push_str(s);+ t.refresh_sugg();+ }+ },+ _ => {}+ }+ self.redraw();+ }++ fn click(&mut self) {+ let (mx, my) = (self.mouse.x as f32, self.mouse.y as f32);+ let sc = self.sc;+ let proxy = self.proxy.clone();+ let (tab_h, top) = (TAB_H * sc, self.top());+ let bw = self.window.as_ref().map_or(1000.0, |w| w.inner_size().width as f32);+ if my < tab_h {+ let tw = self.tab_width(bw);+ let n = self.tabs.len();+ let i = (mx / tw) as usize;+ if i < n {+ if mx - i as f32 * tw > tw - 26.0 * sc { self.close_tab(i); } else { self.switch_tab(i); }+ } else if mx < n as f32 * tw + 36.0 * sc { self.new_tab(None); }+ return;+ }+ // address suggestions sit just under the bar+ let n_sugg = self.tabs[self.cur].sugg.len();+ if n_sugg > 0 && my >= top && my < top + 26.0 * sc * n_sugg as f32 {+ let t = &mut self.tabs[self.cur];+ let u = t.sugg[((my - top) / (26.0 * sc)) as usize].url.clone();+ t.sugg.clear();+ t.navigate(&proxy, u, true, None);+ self.redraw();+ return;+ }+ self.tabs[self.cur].sugg.clear();+ if my < top {+ self.page_focus = false;+ let t = self.t();+ t.fresh = true; t.focus = None; t.popup = None;+ self.redraw();+ return;+ }+ // open select list gets the click first+ let popup = self.tabs[self.cur].popup;+ if let Some(i) = popup {+ let t = &mut self.tabs[self.cur];+ t.popup = None;+ if let Some(p) = t.placed_field(i) {+ let y = p.base - t.scroll + top;+ let n = t.fields[i].options.len().min(POPUP_ROWS);+ let first = t.fields[i].sel.saturating_sub(POPUP_ROWS - 1).min(t.fields[i].options.len().saturating_sub(POPUP_ROWS));+ if mx >= p.x && mx <= p.x + p.w && my >= y && my < y + p.size * n as f32 {+ let row = ((my - y) / p.size) as usize;+ t.select_option(i, first + row);+ }+ }+ self.redraw();+ return;+ }+ if let Some(i) = self.field_at() {+ let t = &mut self.tabs[self.cur];+ match t.fields[i].kind {+ FieldKind::Text | FieldKind::Password | FieldKind::TextArea => {+ let (pw, ph, px, py) = t.placed_field(i).map_or((0.0, 0.0, 0.0, 0.0), |p| (p.w, p.size, p.x, p.base - t.scroll + top - p.size));+ t.set_focus(Some(i));+ t.caret = gfx_hit_caret(&mut self.fonts, &t.fields[i], sc * t.zoom, pw, ph, mx - px, my - py, if t.focus == Some(i) { t.caret } else { usize::MAX });+ }+ FieldKind::Select => { t.set_focus(Some(i)); t.popup = Some(i); }+ FieldKind::Submit => {+ let node = t.fields[i].node;+ let vetoed = t.live.as_ref().is_some_and(|h| h.event(node, "click", r#"{"button":0}"#));+ if !vetoed { t.submit(&proxy, i, Some(i)); }+ }+ FieldKind::Check => { t.fields[i].checked ^= true; t.set_focus(None); t.live_value(i, &["click", "input", "change"]); }+ FieldKind::Radio => { t.set_focus(None); t.set_radio(i); }+ FieldKind::Hidden => {}+ }+ } else {+ self.tabs[self.cur].set_focus(None);+ // the page's click handlers run first and may cancel the default action (following a link)+ let (csc, top) = (sc * self.tabs[self.cur].zoom, self.top());+ let t = &self.tabs[self.cur];+ let prevented = t.live.as_ref().is_some_and(|h| {+ let node = Some(browse::hit_node(&t.placed, &t.rects, mx, my - top + t.scroll)).filter(|&n| n != 0).unwrap_or(t.page.body);+ let init = serde_json::json!({ "clientX": mx / csc, "clientY": (my - top) / csc, "button": 0, "ctrlKey": self.mods.control_key(), "shiftKey": self.mods.shift_key() }).to_string();+ h.post(node, "mousedown", &init);+ h.post(node, "mouseup", &init);+ h.event(node, "click", &init)+ });+ if prevented { self.redraw(); return; }+ let link = self.link_at().and_then(|i| self.tabs[self.cur].page.links.get(i)).cloned();+ if let Some(node) = link.as_deref().and_then(|u| u.strip_prefix("label:")).and_then(|n| n.parse::<usize>().ok()) {+ // clicking a <label> acts on its control+ let t = &mut self.tabs[self.cur];+ if let Some(i) = t.fields.iter().position(|f| f.node == node) {+ match t.fields[i].kind {+ FieldKind::Text | FieldKind::Password | FieldKind::TextArea => { t.set_focus(Some(i)); t.caret = t.fields[i].value.chars().count(); }+ FieldKind::Select => { t.set_focus(Some(i)); t.popup = Some(i); }+ FieldKind::Submit => t.submit(&proxy, i, Some(i)),+ FieldKind::Check => { t.fields[i].checked ^= true; t.live_value(i, &["click", "input", "change"]); }+ FieldKind::Radio => t.set_radio(i),+ FieldKind::Hidden => {}+ }+ }+ } else if let Some(u) = link.filter(|u| u.starts_with("http") || u.starts_with("file:") || u.starts_with("data:")) {+ if self.mods.control_key() { self.new_tab(Some(u)); } else { self.tabs[self.cur].navigate(&proxy, u, true, None); }+ }+ }+ self.redraw();+ }++ /// Left button pressed: scrollbar, text selection start (links fire on release), or a normal click.+ fn mouse_down(&mut self) {+ self.notice = None;+ let (mx, my, top, sc) = (self.mouse.x as f32, self.mouse.y as f32, self.top(), self.sc);+ let now = std::time::Instant::now();+ let double = self.last_click.is_some_and(|(t, x, y)| now.duration_since(t).as_millis() < 450 && (x - mx).abs() < 5.0 && (y - my).abs() < 5.0);+ self.last_click = Some((now, mx, my));+ self.drag = Drag::None;+ if my >= top {+ if let Some((tx, ty, th, view, _)) = self.scrollbar() {+ if mx >= tx {+ if my >= ty && my <= ty + th { self.drag = Drag::Scrollbar { grab: my - ty }; } else { self.scroll_by(if my < ty { -view * 0.9 / sc } else { view * 0.9 / sc }); }+ return;+ }+ }+ }+ let t = &mut self.tabs[self.cur];+ if t.page.restyle.is_some() && my >= top { t.active = t.hover; self.redraw(); }+ let t = &mut self.tabs[self.cur];+ let in_page = my >= top && t.popup.is_none();+ let on_field = in_page && self.field_at().is_some();+ let t = &mut self.tabs[self.cur];+ t.sel = None;+ if in_page && !on_field && t.sugg.is_empty() {+ self.page_focus = true;+ t.focus = None;+ let (lx, ly) = (mx, my - top + t.scroll);+ if let Some(pt) = browse::hit_point(&t.placed, lx, ly, &mut self.fonts) {+ if double { t.sel = Some(browse::word_at(&t.placed, pt)); self.redraw(); return; }+ self.drag = Drag::Select { anchor: pt, moved: false, down: (mx, my) };+ self.redraw();+ return;+ }+ }+ self.click();+ }++ fn mouse_move(&mut self) {+ let (mx, my, top) = (self.mouse.x as f32, self.mouse.y as f32, self.top());+ match &mut self.drag {+ Drag::Select { anchor, moved, down } => {+ if !*moved && (mx - down.0).abs() + (my - down.1).abs() < 5.0 { return; }+ *moved = true;+ let anchor = *anchor;+ let t = &mut self.tabs[self.cur];+ if let Some(pt) = browse::hit_point(&t.placed, mx, my - top + t.scroll, &mut self.fonts) { t.sel = Some((anchor, pt)); }+ self.redraw();+ }+ Drag::Scrollbar { grab } => {+ let grab = *grab;+ if let Some((_, _, th, view, max)) = self.scrollbar() {+ let t = &mut self.tabs[self.cur];+ t.scroll = ((my - grab - top) / (view - th).max(1.0) * max).clamp(0.0, max);+ t.target = None;+ self.redraw();+ }+ }+ Drag::None => {+ let t = &mut self.tabs[self.cur];+ if t.page.restyle.is_some() && my >= top {+ let n = browse::hit_node(&t.placed, &t.rects, mx, my - top + t.scroll);+ if n != t.hover { t.hover = n; self.redraw(); }+ }+ }+ }+ }++ fn mouse_up(&mut self) {+ if self.tabs[self.cur].active != 0 { self.tabs[self.cur].active = 0; self.redraw(); }+ if let Drag::Select { moved: false, .. } = self.drag { self.drag = Drag::None; self.click(); return; }+ self.drag = Drag::None;+ }++ fn update_cursor(&mut self) {+ let (mx, my) = (self.mouse.x as f32, self.mouse.y as f32);+ let (tab_h, top) = (TAB_H * self.sc, self.top());+ let icon = if my < tab_h { CursorIcon::Pointer }+ else if my < top { CursorIcon::Text }+ else if let Some(i) = self.field_at() {+ match self.tabs[self.cur].fields[i].kind { FieldKind::Text | FieldKind::Password | FieldKind::TextArea => CursorIcon::Text, _ => CursorIcon::Pointer }+ } else if self.link_at().is_some() { CursorIcon::Pointer }+ else { CursorIcon::Default };+ let _ = mx;+ if icon != self.cursor {+ self.cursor = icon;+ if let Some(w) = &self.window { w.set_cursor(icon); }+ }+ }+}++/// Char index in a text field nearest to a click at (rel_x, rel_y) inside the box; `cur` is the current caret+/// (usize::MAX = unfocused, window anchored at the end) so the click maps through the same scrolled view the user sees.+fn gfx_hit_caret(f: &mut Fonts, fl: &Field, sc: f32, w: f32, h: f32, rel_x: f32, rel_y: f32, cur: usize) -> usize {+ let fs = (fl.fs * sc).round().max(8.0);+ let chars: Vec<char> = if fl.kind == FieldKind::Password { vec!['\u{2022}'; fl.value.chars().count()] } else { fl.value.chars().collect() };+ let cur = cur.min(chars.len());+ let nearest = |f: &mut Fonts, s: usize, e: usize, x: f32| -> usize {+ let mut acc = 0.0;+ for i in s..e {+ let cw = f.width(&chars[i].to_string(), fs);+ if x < acc + cw / 2.0 { return i; }+ acc += cw;+ }+ e+ };+ if fl.kind == FieldKind::TextArea {+ let lines = gfx::wrap_lines(f, &chars, fs, w - 14.0);+ let line_h = fs * 1.35;+ let rows = (((h - 8.0) / line_h) as usize).max(1);+ let cl = lines.iter().rposition(|&(s, _)| s <= cur).unwrap_or(0);+ let first = (cl + 1).saturating_sub(rows);+ let k = (first + ((rel_y - 4.0) / line_h).max(0.0) as usize).min(lines.len() - 1);+ let (s, e) = lines[k];+ return nearest(f, s, e, rel_x - 6.0);+ }+ // same window as draw_field: widen backwards from the caret while it fits+ let max = w - 12.0;+ let (mut s, mut used) = (cur, 0.0);+ while s > 0 { let cw = f.width(&chars[s - 1].to_string(), fs); if used + cw > max { break; } used += cw; s -= 1; }+ nearest(f, s, chars.len(), rel_x - 6.0)+}++impl ApplicationHandler<Msg> for App {+ fn resumed(&mut self, el: &ActiveEventLoop) {+ if self.window.is_some() { return; }+ let win = Arc::new(el.create_window(Window::default_attributes().with_title("chrome-rs").with_inner_size(winit::dpi::LogicalSize::new(1000.0, 720.0))).unwrap());+ let ctx = softbuffer::Context::new(win.clone()).unwrap();+ self.surface = Some(softbuffer::Surface::new(&ctx, win.clone()).unwrap());+ self.sc = win.scale_factor() as f32;+ win.set_ime_allowed(true);+ self.window = Some(win);+ let (proxy, t) = (self.proxy.clone(), &mut self.tabs[0]);+ let u = t.url.clone();+ t.navigate(&proxy, u, true, None);+ let (rest, cur) = std::mem::take(&mut self.pending);+ for u in rest { self.new_tab(Some(u)); }+ if cur > 0 { self.switch_tab(cur); }+ }++ fn user_event(&mut self, _: &ActiveEventLoop, msg: Msg) {+ let proxy = self.proxy.clone();+ let (uid, id, url, push, res) = match msg {+ Msg::Loaded { uid, id, url, push, res } => (uid, id, url, push, res),+ Msg::Live { uid, id, ev } => {+ if let Some(t) = self.tabs.iter_mut().find(|t| t.uid == uid) {+ match ev {+ load::LiveEvent::Page(p) => t.live_update(id, p),+ load::LiveEvent::Navigate(u) => if id == t.nav_id { t.navigate(&proxy, u, true, None); },+ }+ }+ self.sync_title();+ self.redraw();+ return;+ }+ };+ let res = res.map(|(u, mut page)| { for w in std::mem::take(&mut page.webfonts) { self.fonts.add_web(w.fam, w.bold, w.italic, &w.data); } (u, page) });+ if let Some(t) = self.tabs.iter_mut().find(|t| t.uid == uid) { t.loaded(id, url, push, res); }+ self.sync_title();+ self.redraw();+ if std::env::var_os("CHROME_RS_SELFTEST").is_some() { self.selftest(); }+ }++ fn window_event(&mut self, el: &ActiveEventLoop, _: WindowId, ev: WindowEvent) {+ match ev {+ WindowEvent::CloseRequested => { self.save_session(); el.exit() }+ WindowEvent::RedrawRequested => self.paint(),+ WindowEvent::Resized(_) | WindowEvent::ScaleFactorChanged { .. } => self.redraw(),+ WindowEvent::ModifiersChanged(m) => self.mods = m.state(),+ WindowEvent::CursorMoved { position, .. } => { self.mouse = position; self.mouse_move(); self.update_cursor(); }+ WindowEvent::MouseInput { state: ElementState::Pressed, button: MouseButton::Left, .. } => self.mouse_down(),+ WindowEvent::MouseInput { state: ElementState::Released, button: MouseButton::Left, .. } => self.mouse_up(),+ WindowEvent::MouseWheel { delta, .. } => {+ let dy = match delta { MouseScrollDelta::LineDelta(_, y) => -y * 48.0, MouseScrollDelta::PixelDelta(p) => -p.y as f32 / self.sc };+ if self.mods.control_key() { let z = zoom_step(self.tabs[self.cur].zoom, dy < 0.0); self.set_zoom(z); } else if !self.scroll_container(dy) { self.scroll_by(dy); }+ }+ WindowEvent::Ime(winit::event::Ime::Commit(s)) => self.key(&Key::Character(s.as_str().into()), Some(&s)),+ WindowEvent::KeyboardInput { event, .. } if event.state == ElementState::Pressed => self.key(&event.logical_key, event.text.as_deref()),+ WindowEvent::KeyboardInput { event, .. } if event.state == ElementState::Released => {+ let t = &self.tabs[self.cur];+ if let (Some(h), Some(k), false) = (&t.live, key_name(&event.logical_key), self.mods.control_key() || self.mods.alt_key()) {+ if t.focus.is_some() || self.page_focus { h.post(t.key_target(), "keyup", &serde_json::json!({ "key": k, "shiftKey": self.mods.shift_key() }).to_string()); }+ }+ }+ _ => {}+ }+ if self.exit { el.exit(); }+ }+}++fn main() {+ let args: Vec<String> = std::env::args().skip(1).collect();+ if matches!(args.first().map(String::as_str), Some("--snap" | "--corpus" | "--bench" | "--pdf" | "--save")) {+ // the same stack size as the page loader threads of the browser, so the corpus hits the same limits+ let a = args.clone();+ let code = std::thread::Builder::new().stack_size(32 << 20).spawn(move || snap::cli(&a, &mut Fonts::system().expect("no system font found (see SANS in gfx.rs)"))).ok().and_then(|h| h.join().ok()).unwrap_or(2);+ std::process::exit(code);+ }+ let fonts = Fonts::system().expect("no system font found (see SANS in gfx.rs)");+ let el = EventLoop::<Msg>::with_user_event().build().unwrap();+ let mut first = Tab::new(1);+ let mut pending = (vec![], 0);+ first.url = match args.first() {+ Some(a) => to_url(a),+ None => {+ let (mut urls, cur) = store::load_session(); // reopen the previous session+ if urls.is_empty() { store::setting("home").map_or_else(|| HOME.to_string(), |h| to_url(&h)) } else { let first = urls.remove(0); pending = (urls, cur); first }+ }+ };+ let mut app = App {+ proxy: el.create_proxy(), window: None, surface: None, fonts, tabs: vec![first], cur: 0, next_uid: 1, sc: 1.0,+ mouse: PhysicalPosition::new(0.0, 0.0), cursor: CursorIcon::Default, mods: ModifiersState::empty(), exit: false,+ find: None, closed: vec![], drag: Drag::None, page_focus: false, last_click: None, pending, notice: None,+ };+ el.run_app(&mut app).unwrap();+}++#[cfg(test)]+mod tests {+ use super::*;++ fn field(kind: FieldKind, v: &str) -> Field { Field { kind, value: v.into(), fs: 16.0, ..Default::default() } }++ #[test]+ fn form_submission_urls() {+ let get = render::Form { action: "https://a.com/s?old=1#x".into(), post: false, node: 0 };+ assert_eq!(form_request(&get, &[("q", "rust lang"), ("t", "a&b")]), ("https://a.com/s?q=rust%20lang&t=a%26b".into(), None));+ let post = render::Form { action: "https://a.com/login".into(), post: true, node: 0 };+ assert_eq!(form_request(&post, &[("u", "x")]), ("https://a.com/login".into(), Some("u=x".into())));+ }++ #[test]+ fn address_bar() {+ assert_eq!(to_url("example.com"), "https://example.com");+ assert_eq!(to_url("http://a.b/x"), "http://a.b/x");+ assert_eq!(to_url_with("rust lang", ENGINE), "https://html.duckduckgo.com/html/?q=rust%20lang");+ assert_eq!(to_url_with("a b", "https://s.test/?q={q}&x=1"), "https://s.test/?q=a%20b&x=1");+ assert_eq!(to_url("about:history"), "about:history");+ }++ #[test]+ fn caret_editing_with_unicode() {+ let mut f = field(FieldKind::Text, "привет");+ let mut c = 6;+ assert!(edit_field(&mut f, &mut c, &Key::Named(NamedKey::ArrowLeft), None));+ assert!(edit_field(&mut f, &mut c, &Key::Named(NamedKey::Backspace), None));+ assert_eq!((f.value.as_str(), c), ("привт", 4));+ assert!(edit_field(&mut f, &mut c, &Key::Character("x".into()), Some("é")));+ assert_eq!((f.value.as_str(), c), ("привéт", 5));+ assert!(edit_field(&mut f, &mut c, &Key::Named(NamedKey::Home), None));+ assert!(edit_field(&mut f, &mut c, &Key::Named(NamedKey::Delete), None));+ assert_eq!((f.value.as_str(), c), ("ривéт", 0));+ assert!(!edit_field(&mut f, &mut c, &Key::Named(NamedKey::Enter), None)); // Enter submits single-line fields+ }++ #[test]+ fn textarea_lines() {+ let mut f = field(FieldKind::TextArea, "ab\ncde");+ let mut c = 6;+ assert!(edit_field(&mut f, &mut c, &Key::Named(NamedKey::ArrowUp), None));+ assert_eq!(c, 2); // column 3 clamped to the end of "ab"+ assert!(edit_field(&mut f, &mut c, &Key::Named(NamedKey::Enter), None));+ assert_eq!((f.value.as_str(), c), ("ab\n\ncde", 3));+ assert_eq!(line_bounds("ab\n\ncde", 3), (3, 3));+ }++ #[test]+ fn zoom_steps_walk_the_preset_list() {+ assert_eq!(zoom_step(1.0, true), 1.1);+ assert_eq!(zoom_step(1.0, false), 0.9);+ assert_eq!(zoom_step(5.0, true), 5.0);+ assert_eq!(zoom_step(0.3, false), 0.3);+ assert_eq!(zoom_step(1.05, true), 1.1);+ }++ #[test]+ fn live_updates_keep_what_the_user_typed() {+ let mk = |name: &str, value: &str, initial: &str| Field { kind: FieldKind::Text, name: name.into(), value: value.into(), initial: initial.into(), ..Default::default() };+ let old = vec![mk("q", "typed by user", ""), mk("other", "x", "x")];+ let mut new = vec![mk("q", "", ""), mk("other", "set by script", "x")];+ merge_fields(&old, &mut new);+ assert_eq!(new[0].value, "typed by user", "script left the field alone: keep the user's text");+ assert_eq!(new[1].value, "set by script", "script changed the field: the script wins");+ let mut moved = vec![mk("fresh", "", ""), mk("q", "", "")];+ merge_fields(&old, &mut moved);+ assert_eq!(moved[1].value, "typed by user", "a field that moved in the DOM is found by name");+ }+}diff --git a/plugins/chrome-rs/src/prelude.js b/plugins/chrome-rs/src/prelude.jsnew file mode 100644index 0000000..0c945cb--- /dev/null+++ b/plugins/chrome-rs/src/prelude.js@@ -0,0 +1,1001 @@+// Minimal browser environment for QuickJS. The page DOM arrives as JSON (__dom_json), scripts mutate this JS-side+// tree, and __serialize() hands the result back to Rust. Natives: __parse(html) -> JSON array of nodes, __url.+(function (g) {+'use strict';+const VOID = new Set(['area','base','br','col','embed','hr','img','input','link','meta','source','track','wbr','param']);+const camel = s => s.replace(/-([a-z])/g, (_, c) => c.toUpperCase());+const kebab = s => s.replace(/[A-Z]/g, c => '-' + c.toLowerCase());+const esc = s => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');+// registry of custom elements (see the custom element section below); it must exist before the first DOM node is built+const CE = { defs: new Map(), tags: new Map(), up: null, waiters: new Map() };+const escA = s => esc(s).replace(/"/g, '"');++class Event {+ constructor(type, init) { this.type = type; this.bubbles = !!(init && init.bubbles); this.cancelable = !!(init && init.cancelable); this.defaultPrevented = false; this.target = null; this.detail = init && init.detail; this.timeStamp = 0; }+ preventDefault() { this.defaultPrevented = true; }+ stopPropagation() { this._stop = true; }+ stopImmediatePropagation() { this._stop = true; this._stopNow = true; }+}+class CustomEvent extends Event {}++class EventTarget {+ // options: `true` / `{ capture, once }`; the same function twice with the same capture flag is added once+ addEventListener(t, f, o) {+ if (!f) return;+ const cap = o === true || !!(o && o.capture), L = this._l = this._l || {};+ const a = L[t] = L[t] || [];+ if (a.some(x => x.f === f && x.cap === cap)) return;+ a.push({ f, cap, once: !!(o && o.once) });+ }+ removeEventListener(t, f, o) {+ const cap = o === true || !!(o && o.capture);+ if (this._l && this._l[t]) this._l[t] = this._l[t].filter(x => !(x.f === f && x.cap === cap));+ }+ dispatchEvent(e) {+ e.target = e.target || this;+ const path = [];+ for (let n = this; n; n = n.parentNode || (n === document ? g : n.nodeType === 11 ? n.host : null)) path.push(n);+ e.composedPath = () => path.slice();+ const run = (n, phase) => {+ try { e.currentTarget = n; } catch (x) {} // Svelte redefines it as a getter-only property+ e.eventPhase = phase;+ if (phase !== 1) {+ // `el.onclick = fn` and inline `onclick="..."` attributes; returning false cancels the default action+ let oh = n['on' + e.type];+ if (typeof oh !== 'function' && n._a && typeof n._a['on' + e.type] === 'string') {+ n._oh = n._oh || {};+ if (!(e.type in n._oh)) { try { n._oh[e.type] = new Function('event', n._a['on' + e.type]); } catch (x) { n._oh[e.type] = null; } }+ oh = n._oh[e.type];+ }+ if (typeof oh === 'function') { try { if (oh.call(n, e) === false) e.preventDefault(); } catch (x) {} }+ }+ const ls = n._l && n._l[e.type];+ if (ls) for (const l of ls.slice()) {+ if (phase === 1 ? !l.cap : phase === 3 && l.cap) continue;+ if (l.once) n._l[e.type] = n._l[e.type].filter(x => x !== l);+ try { typeof l.f === 'function' ? l.f.call(n, e) : l.f.handleEvent(e); } catch (x) { g.__log('listener ' + e.type + ': ' + (x && (x.message + ' ' + x.stack) || x)); }+ if (e._stopNow) return;+ }+ };+ // capture from the outermost ancestor down, then the target, then (if the event bubbles) back up+ for (let i = path.length - 1; i > 0 && !e._stop; i--) run(path[i], 1);+ if (!e._stop) run(path[0], 2);+ for (let i = 1; i < path.length && e.bubbles && !e._stop; i++) run(path[i], 3);+ e.eventPhase = 0; try { e.currentTarget = null; } catch (x) {}+ return !e.defaultPrevented;+ }+}++function descendants(root) {+ const out = [], st = root.childNodes.slice().reverse();+ while (st.length) { const n = st.pop(); if (n.nodeType === 1) { out.push(n); for (let i = n.childNodes.length - 1; i >= 0; i--) st.push(n.childNodes[i]); } }+ return out;+}++class Node extends EventTarget {+ constructor() { super(); this.childNodes = []; this.parentNode = null; }+ get firstChild() { return this.childNodes[0] || null; }+ get lastChild() { return this.childNodes[this.childNodes.length - 1] || null; }+ get nextSibling() { const p = this.parentNode; return p ? p.childNodes[p.childNodes.indexOf(this) + 1] || null : null; }+ get previousSibling() { const p = this.parentNode; return p ? p.childNodes[p.childNodes.indexOf(this) - 1] || null : null; }+ get parentElement() { const p = this.parentNode; return p && p.nodeType === 1 ? p : null; }+ get children() { return this.childNodes.filter(n => n.nodeType === 1); }+ get childElementCount() { return this.children.length; }+ get firstElementChild() { return this.children[0] || null; }+ get lastElementChild() { const c = this.children; return c[c.length - 1] || null; }+ get nextElementSibling() { for (let n = this.nextSibling; n; n = n.nextSibling) if (n.nodeType === 1) return n; return null; }+ get previousElementSibling() { for (let n = this.previousSibling; n; n = n.previousSibling) if (n.nodeType === 1) return n; return null; }+ get ownerDocument() { return document; }+ get isConnected() { for (let n = this; n; n = n.parentNode || (n.nodeType === 11 ? n.host : null)) if (n === document) return true; return false; }+ hasChildNodes() { return this.childNodes.length > 0; }+ appendChild(n) { return this.insertBefore(n, null); }+ insertBefore(n, ref) {+ if (n.nodeType === 11) { for (const c of n.childNodes.slice()) this.insertBefore(c, ref); return n; }+ if (n.parentNode) n.parentNode.removeChild(n);+ n.parentNode = this;+ const i = ref ? this.childNodes.indexOf(ref) : -1;+ if (i < 0) this.childNodes.push(n); else this.childNodes.splice(i, 0, n);+ if (CE.defs.size) ceConnect(n);+ return n;+ }+ removeChild(n) { const i = this.childNodes.indexOf(n); if (i >= 0) { this.childNodes.splice(i, 1); n.parentNode = null; if (CE.defs.size) ceDisconnect(n); } return n; }+ replaceChild(n, old) { this.insertBefore(n, old); this.removeChild(old); return old; }+ remove() { if (this.parentNode) this.parentNode.removeChild(this); }+ append(...a) { for (const x of a) this.appendChild(typeof x === 'object' ? x : document.createTextNode(String(x))); }+ prepend(...a) { const f = this.firstChild; for (const x of a) this.insertBefore(typeof x === 'object' ? x : document.createTextNode(String(x)), f); }+ before(...a) { const p = this.parentNode; if (p) for (const x of a) p.insertBefore(typeof x === 'object' ? x : document.createTextNode(String(x)), this); }+ after(...a) { const p = this.parentNode, nx = this.nextSibling; if (p) for (const x of a) p.insertBefore(typeof x === 'object' ? x : document.createTextNode(String(x)), nx); }+ contains(n) { for (; n; n = n.parentNode) if (n === this) return true; return false; }+ get textContent() { return this.childNodes.map(c => c.nodeType === 8 ? '' : c.textContent).join(''); }+ set textContent(v) {+ this.childNodes.forEach(c => c.parentNode = null); this.childNodes = [];+ if (v !== '' && v != null) this.appendChild(document.createTextNode(String(v)));+ }+ get innerText() { return this.textContent; }+ set innerText(v) { this.textContent = v; }+ cloneNode(deep, inert) {+ let c;+ if (this.nodeType === 3) c = new Text(this.data);+ else if (this.nodeType === 8) c = new Comment(this.data);+ else if (this.nodeType === 11) c = new DocumentFragment();+ else { const C = !inert && CE.defs.get(this.localName); c = C ? new C() : new Element(this.localName); Object.assign(c._a, this._a); } // a defined custom element is constructed (upgraded) at once, as importNode does; template content stays inert+ if (deep) for (const k of this.childNodes) c.appendChild(k.cloneNode(true, inert));+ return c;+ }+}++class Text extends Node {+ constructor(d) { super(); this.data = String(d); this.nodeType = 3; this.nodeName = '#text'; }+ get textContent() { return this.data; }+ set textContent(v) { this.data = String(v); }+ get nodeValue() { return this.data; }+ set nodeValue(v) { this.data = String(v); }+}+class Comment extends Text { constructor(d) { super(d); this.nodeType = 8; this.nodeName = '#comment'; } }+class DocumentFragment extends Node {+ constructor() { super(); this.nodeType = 11; this.nodeName = '#document-fragment'; }+ querySelector(s) { return qsa(this, s, true)[0] || null; }+ querySelectorAll(s) { return qsa(this, s, false); }+}++function ser(n) {+ if (n.nodeType === 3) return esc(n.data);+ if (n.nodeType === 8) return '<!--' + n.data + '-->';+ if (n.nodeType !== 1) return '';+ const a = Object.keys(n._a).map(k => ' ' + k + '="' + escA(n._a[k]) + '"').join('');+ if (VOID.has(n.localName)) return '<' + n.localName + a + '>';+ const raw = n.localName === 'script' || n.localName === 'style';+ return '<' + n.localName + a + '>' + n.childNodes.map(c => raw && c.nodeType === 3 ? c.data : ser(c)).join('') + '</' + n.localName + '>';+}+function fromJSON(arr) {+ return arr.map(o => {+ if (typeof o === 'string') return new Text(o);+ if (o.m !== undefined) return new Comment(o.m);+ const e = new Element(o.t); e._a = o.a || {};+ for (const c of fromJSON(o.c || [])) { c.parentNode = e; e.childNodes.push(c); }+ if (CE.defs.size && CE.defs.has(e.localName)) ceUpgrade(e, CE.defs.get(e.localName));+ return e;+ });+}++const selCache = new Map();+function parseCompound(t) {+ const c = { tag: null, id: null, cls: [], attrs: [], first: false, last: false, nots: [], bad: false };+ const re = /([#.]?[\w-]+|\*|\[[^\]]+\]|::?[\w-]+(?:\([^)]*\))?)/g;+ let m;+ while ((m = re.exec(t))) {+ const x = m[1];+ if (x[0] === '#') c.id = x.slice(1);+ else if (x[0] === '.') c.cls.push(x.slice(1));+ else if (x[0] === '[') {+ const a = /\[\s*([\w-]+)\s*(?:([~|^$*]?=)\s*["']?([^"'\]]*)["']?)?\s*\]/.exec(x);+ if (a) c.attrs.push([a[1].toLowerCase(), a[2], a[3]]); else c.bad = true;+ } else if (x[0] === ':') {+ if (x === ':first-child') c.first = true; else if (x === ':last-child') c.last = true;+ else if (x.startsWith(':not(')) c.nots.push(x.slice(5, -1));+ else c.bad = true;+ } else if (x !== '*') c.tag = x.toLowerCase();+ }+ return c;+}+function parseSel(s) {+ let r = selCache.get(s);+ if (r) return r;+ r = s.split(',').map(p => {+ const toks = p.trim().replace(/\s*([>+~])\s*/g, ' $1 ').split(/\s+/).filter(Boolean);+ const parts = []; let comb = ' ';+ for (const t of toks) { if (t.length === 1 && '>+~'.includes(t)) { comb = t; continue; } parts.push({ comb, c: parseCompound(t) }); comb = ' '; }+ return parts;+ }).filter(p => p.length);+ selCache.set(s, r);+ return r;+}+function matchC(el, c) {+ if (c.bad) return false;+ if (c.tag && el.localName !== c.tag) return false;+ if (c.id && el._a.id !== c.id) return false;+ if (c.cls.length) { const cl = (el._a['class'] || '').split(/\s+/); for (const k of c.cls) if (!cl.includes(k)) return false; }+ for (const [n, op, v] of c.attrs) {+ const x = el._a[n]; if (x === undefined) return false;+ if (op === '=' && x !== v) return false;+ if (op === '^=' && !x.startsWith(v)) return false;+ if (op === '$=' && !x.endsWith(v)) return false;+ if (op === '*=' && !x.includes(v)) return false;+ if (op === '~=' && !x.split(/\s+/).includes(v)) return false;+ }+ if (c.first && el.previousElementSibling) return false;+ if (c.last && el.nextElementSibling) return false;+ for (const n of c.nots) if (matchesSel(el, n)) return false;+ return true;+}+function matchParts(el, parts, i) {+ if (!matchC(el, parts[i].c)) return false;+ if (i === 0) return true;+ switch (parts[i].comb) {+ case ' ': for (let p = el.parentElement; p; p = p.parentElement) if (matchParts(p, parts, i - 1)) return true; return false;+ case '>': return !!el.parentElement && matchParts(el.parentElement, parts, i - 1);+ case '+': return !!el.previousElementSibling && matchParts(el.previousElementSibling, parts, i - 1);+ default: for (let p = el.previousElementSibling; p; p = p.previousElementSibling) if (matchParts(p, parts, i - 1)) return true; return false;+ }+}+function matchesSel(el, s) { return parseSel(s).some(p => matchParts(el, p, p.length - 1)); }+function qsa(root, s, first) {+ const out = [];+ for (const e of descendants(root)) if (matchesSel(e, s)) { out.push(e); if (first) break; }+ return out;+}++function makeStyle(el) {+ const o = {};+ (el._a.style || '').split(';').forEach(d => { const i = d.indexOf(':'); if (i > 0) o[camel(d.slice(0, i).trim())] = d.slice(i + 1).trim(); });+ const sync = () => { el._a.style = Object.keys(o).filter(k => o[k] !== '').map(k => kebab(k) + ':' + o[k]).join(';'); };+ return new Proxy(o, {+ set(t, k, v) { t[k] = String(v); sync(); return true; },+ get(t, k) {+ if (typeof k === 'symbol') return undefined;+ if (k === 'cssText') return el._a.style || '';+ if (k === 'setProperty') return (p, v) => { t[camel(p)] = String(v); sync(); };+ if (k === 'removeProperty') return p => { delete t[camel(p)]; sync(); };+ if (k === 'getPropertyValue') return p => t[camel(p)] || '';+ return k in t ? t[k] : '';+ },+ });+}++// Plain elements sit one prototype below Element.prototype (like HTMLElement.prototype in browsers): Svelte collects property setters (`hidden`, `value`...) from that part of the chain only+const HTMLProto = Object.create(null);+class Element extends Node {+ constructor(tag) { super(); if (new.target === Element) Object.setPrototypeOf(this, HTMLProto); tag = String(tag); this.nodeType = 1; this.localName = tag.toLowerCase(); this.tagName = tag.toUpperCase(); this.nodeName = this.tagName; this._a = {}; }+ getAttribute(n) { n = n.toLowerCase(); return n in this._a ? this._a[n] : null; }+ setAttribute(n, v) { n = n.toLowerCase(); const o = n in this._a ? this._a[n] : null; this._a[n] = String(v); if (n === 'style') this._style = null; if (this._ce) ceAttr(this, n, o, String(v)); }+ removeAttribute(n) { n = n.toLowerCase(); const o = n in this._a ? this._a[n] : null; delete this._a[n]; if (n === 'style') this._style = null; if (this._ce && o !== null) ceAttr(this, n, o, null); }+ hasAttribute(n) { return n.toLowerCase() in this._a; }+ toggleAttribute(n, f) { const has = this.hasAttribute(n), want = f === undefined ? !has : !!f; if (want && !has) this.setAttribute(n, ''); else if (!want && has) this.removeAttribute(n); return want; }+ get id() { return this._a.id || ''; } set id(v) { this._a.id = String(v); }+ get className() { return this._a['class'] || ''; } set className(v) { this._a['class'] = String(v); }+ get hidden() { return 'hidden' in this._a; } set hidden(v) { if (v) this._a.hidden = ''; else delete this._a.hidden; }+ get classList() {+ const el = this, get = () => (el._a['class'] || '').split(/\s+/).filter(Boolean), set = a => { el._a['class'] = a.join(' '); };+ return {+ add(...c) { const a = get(); for (const x of c) if (!a.includes(x)) a.push(x); set(a); },+ remove(...c) { set(get().filter(x => !c.includes(x))); },+ toggle(c, f) { const has = get().includes(c), want = f === undefined ? !has : !!f; if (want && !has) this.add(c); else if (!want && has) this.remove(c); return want; },+ contains(c) { return get().includes(c); },+ replace(a, b) { set(get().map(x => x === a ? b : x)); return true; },+ get length() { return get().length; }, item(i) { return get()[i] || null; }, toString() { return get().join(' '); },+ };+ }+ // an array that also answers `el.attributes.id` and `getNamedItem` (jQuery 1.x reads `attributes[name].expando`)+ get attributes() {+ const l = Object.keys(this._a).map(k => ({ name: k, nodeName: k, localName: k, value: this._a[k], nodeValue: this._a[k], specified: true }));+ for (const a of l) if (!(a.name in l)) l[a.name] = a;+ l.getNamedItem = n => l[n] || null; l.item = i => l[i] || null;+ return l;+ }+ get dataset() {+ const a = this._a;+ return new Proxy({}, { get: (t, k) => typeof k === 'symbol' ? undefined : a['data-' + kebab(k)], set: (t, k, v) => { a['data-' + kebab(k)] = String(v); return true; } });+ }+ get style() { return this._style || (this._style = makeStyle(this)); }+ set style(v) { this._a.style = String(v); this._style = null; }+ get innerHTML() { const raw = this.localName === 'script' || this.localName === 'style'; return this.childNodes.map(c => raw && c.nodeType === 3 ? c.data : ser(c)).join(''); }+ set innerHTML(h) {+ this.childNodes.forEach(c => c.parentNode = null); this.childNodes = [];+ for (const c of fromJSON(JSON.parse(__parse(String(h))))) this.appendChild(c);+ }+ get outerHTML() { return ser(this); }+ insertAdjacentHTML(pos, h) {+ const nodes = fromJSON(JSON.parse(__parse(String(h))));+ if (pos === 'beforeend') nodes.forEach(n => this.appendChild(n));+ else if (pos === 'afterbegin') { const f = this.firstChild; nodes.forEach(n => this.insertBefore(n, f)); }+ else if (pos === 'beforebegin' && this.parentNode) nodes.forEach(n => this.parentNode.insertBefore(n, this));+ else if (pos === 'afterend' && this.parentNode) { const nx = this.nextSibling; nodes.forEach(n => this.parentNode.insertBefore(n, nx)); }+ }+ querySelector(s) { return qsa(this, s, true)[0] || null; }+ querySelectorAll(s) { return qsa(this, s, false); }+ getElementsByTagName(t) { t = t.toLowerCase(); return descendants(this).filter(e => t === '*' || e.localName === t); }+ getElementsByClassName(c) { const cs = c.split(/\s+/).filter(Boolean); return descendants(this).filter(e => cs.every(x => (e._a['class'] || '').split(/\s+/).includes(x))); }+ matches(s) { return matchesSel(this, s); }+ closest(s) { for (let n = this; n && n.nodeType === 1; n = n.parentNode) if (matchesSel(n, s)) return n; return null; }+ click() { this.dispatchEvent(new Event('click', { bubbles: true, cancelable: true })); }+ focus() {} blur() {} scrollIntoView() {} animate() { return { cancel() {}, finished: Promise.resolve() }; }+ getBoundingClientRect() { const b = this._box || [0, 0, 0, 0]; return { x: b[0], y: b[1], left: b[0], top: b[1], width: b[2], height: b[3], right: b[0] + b[2], bottom: b[1] + b[3] }; }+ getClientRects() { return this._box ? [this.getBoundingClientRect()] : []; }+ get offsetWidth() { return Math.round((this._box || [0, 0, 0, 0])[2]); } get offsetHeight() { return Math.round((this._box || [0, 0, 0, 0])[3]); }+ get clientWidth() { return this.offsetWidth; } get clientHeight() { return this.offsetHeight; }+ get offsetLeft() { return Math.round((this._box || [0, 0, 0, 0])[0]); } get offsetTop() { return Math.round((this._box || [0, 0, 0, 0])[1]); }+ get scrollTop() { return this === document.documentElement || this.localName === 'body' ? g.scrollY : 0; } set scrollTop(v) {} get scrollHeight() { return this.offsetHeight; } get scrollWidth() { return this.offsetWidth; }+}+Object.setPrototypeOf(HTMLProto, Element.prototype);+for (const p of ['href', 'src', 'type', 'name', 'title', 'alt', 'rel', 'placeholder', 'target', 'action', 'method', 'lang', 'role'])+ Object.defineProperty(Element.prototype, p, { get() { return this._a[p] || ''; }, set(v) { this._a[p] = String(v); }, configurable: true });+// `a.href` is the absolute address (the raw text stays in getAttribute('href'))+Object.defineProperty(Element.prototype, 'href', { get() { const v = this._a.href; if (v === undefined) return ''; if (!isLink(this)) return v; if (v[0] === '#') return loc._h.replace(/#.*$/, '') + v; try { return __resolve(loc._h, v); } catch (e) { return v; } }, set(v) { this._a.href = String(v); }, configurable: true });+// `src` of script, img, iframe and the media tags is absolute too (webpack finds its public path from script.src)+Object.defineProperty(Element.prototype, 'src', { get() { const v = this._a.src; if (v === undefined) return ''; if (!/^(script|img|iframe|source|audio|video|embed|track|input)$/.test(this.localName)) return v; if (v[0] === '#') return loc._h.replace(/#.*$/, '') + v; try { return __resolve(loc._h, v); } catch (e) { return v; } }, set(v) { this._a.src = String(v); }, configurable: true });+const optVal = o => o._a.value !== undefined ? o._a.value : o.textContent.trim();+Object.defineProperty(Element.prototype, 'value', {+ get() {+ if (this.localName === 'textarea') return this.textContent;+ if (this.localName === 'select') { const o = descendants(this).filter(x => x.localName === 'option'); const s = o.find(x => 'selected' in x._a) || o[0]; return s ? optVal(s) : ''; }+ return this._a.value || '';+ },+ set(v) {+ v = String(v);+ if (this.localName === 'textarea') this.textContent = v;+ else if (this.localName === 'select') { for (const o of descendants(this).filter(x => x.localName === 'option')) { if (optVal(o) === v) o._a.selected = ''; else delete o._a.selected; } }+ else this._a.value = v;+ }, configurable: true });+for (const p of ['checked', 'disabled', 'selected', 'required'])+ Object.defineProperty(Element.prototype, p, { get() { return p in this._a; }, set(v) { if (v) this._a[p] = ''; else delete this._a[p]; }, configurable: true });++class Document extends Node {+ constructor() { super(); this.nodeType = 9; this.nodeName = '#document'; this.readyState = 'loading'; this.referrer = ''; this.characterSet = 'UTF-8'; }+ get cookie() { return __cookie_get(); } set cookie(v) { __cookie_set(String(v)); }+ createElement(t) { const C = CE.defs.get(String(t).toLowerCase()); return C ? new C() : new Element(t); }+ createElementNS(ns, t) { const e = new Element(t); e._ns = ns; return e; }+ createTextNode(d) { return new Text(d); }+ createComment(d) { return new Comment(d === undefined ? '' : d); }+ createDocumentFragment() { return new DocumentFragment(); }+ createEvent() { return new Event(''); }+ getElementById(id) { return descendants(this).find(e => e._a.id === id) || null; }+ querySelector(s) { return qsa(this, s, true)[0] || null; }+ querySelectorAll(s) { return qsa(this, s, false); }+ getElementsByTagName(t) { t = t.toLowerCase(); return descendants(this).filter(e => t === '*' || e.localName === t); }+ getElementsByClassName(c) { return this.documentElement ? this.documentElement.getElementsByClassName(c) : []; }+ get documentElement() { return this.childNodes.find(c => c.nodeType === 1) || null; }+ get head() { return this.documentElement && this.documentElement.children.find(c => c.localName === 'head') || null; }+ get body() { return this.documentElement && this.documentElement.children.find(c => c.localName === 'body') || null; }+ get title() { const t = this.querySelector('title'); return t ? t.textContent.trim() : ''; }+ set title(v) { let t = this.querySelector('title'); if (!t) { t = this.createElement('title'); this.head.appendChild(t); } t.textContent = v; }+ get defaultView() { return g; } get currentScript() { const n = g.__cs; if (!n) return null; const e = this.createElement('script'); if (!n.includes('#inline-')) e.setAttribute('src', n); return e; } get location() { return loc; } set location(v) { nav(v); }+ get visibilityState() { return 'visible'; } get hidden() { return false; }+ hasFocus() { return true; }+ write(h) { const b = this.body || this.documentElement; for (const c of fromJSON(JSON.parse(__parse(String(h))))) b.appendChild(c); }+ writeln(h) { this.write(h); }+ open() {} close() {}+ get implementation() {+ const mk = t => { const d = new Document(), h = d.createElement('html'), hd = d.createElement('head'), b = d.createElement('body'); d.appendChild(h); h.appendChild(hd); h.appendChild(b); if (t) { const e = d.createElement('title'); e.textContent = String(t); hd.appendChild(e); } return d; };+ return { createHTMLDocument: mk, createDocument: () => new Document(), hasFeature: () => true };+ }+}++const document = new Document();+const dom = JSON.parse(__dom_json);+for (const n of fromJSON([dom])) document.appendChild(n);++const loc = { _h: '', assign(u) { nav(u); }, replace(u) { nav(u); }, reload() {}, toString() { return this._h; } };+// location changes navigate the tab (a bare #fragment only updates the address)+const nav = u => {+ u = String(u);+ if (u[0] === '#') { setLoc(loc._h.replace(/#.*$/, '') + u); g.dispatchEvent(new Event('hashchange')); }+ else __navigate(__resolve(loc._h, u));+};+Object.defineProperty(loc, 'href', { get() { return this._h; }, set(v) { nav(v); }, enumerable: true });+Object.defineProperty(loc, 'hash', { get() { return this._hash; }, set(v) { nav('#' + String(v).replace(/^#/, '')); }, enumerable: true });+Object.defineProperty(g, 'location', { get: () => loc, set: v => nav(v), configurable: true });+function setLoc(h) {+ const m = /^(\w+:)(?:\/\/([^\/?#]*))?([^?#]*)(\?[^#]*)?(#.*)?$/.exec(h) || [];+ Object.assign(loc, { _h: h, _hash: m[5] || '', protocol: m[1] || '', host: m[2] || '', hostname: (m[2] || '').replace(/:\d+$/, ''), port: ((m[2] || '').match(/:(\d+)$/) || [])[1] || '',+ pathname: m[3] || '/', search: m[4] || '', origin: m[2] !== undefined ? (m[1] || '') + '//' + m[2] : 'null' });+}+setLoc(__url);++const lsData = JSON.parse(__ls);+const store = (init) => { const d = init || {}; return { getItem: k => k in d ? d[k] : null, setItem: (k, v) => { d[k] = String(v); }, removeItem: k => { delete d[k]; }, clear() { for (const k in d) delete d[k]; }, key: i => Object.keys(d)[i] || null, get length() { return Object.keys(d).length; } }; };+let timers = [], tid = 0, now = 0, perfT = 0, ran = 0;+const cleared = new Set(); // ids cleared while their own callback was running must not be re-armed+const noop = () => {};+class Observer { constructor() {} observe() {} unobserve() {} disconnect() {} takeRecords() { return []; } }+// everything counts as visible, so lazy-loaded and scroll-revealed content appears+class IntersectionObs extends Observer {+ constructor(cb) { super(); this.cb = cb; this.root = null; }+ observe(el) { g.setTimeout(() => { try { const r = el.getBoundingClientRect(); this.cb([{ target: el, isIntersecting: true, intersectionRatio: 1, boundingClientRect: r, intersectionRect: r, rootBounds: null, time: now }], this); } catch (e) {} }, 0); }+}+class ResizeObs extends Observer {+ constructor(cb) { super(); this.cb = cb; }+ observe(el) { g.setTimeout(() => { try { const r = el.getBoundingClientRect(); this.cb([{ target: el, contentRect: r, borderBoxSize: [{ inlineSize: r.width, blockSize: r.height }] }], this); } catch (e) {} }, 0); }+}+// ---- custom elements: `class X extends HTMLElement`, customElements.define, upgrade of elements already in the page, lifecycle callbacks.+// shortcut: shadow trees are flattened into the host when the page is serialized (see `composed`): their <style> rules apply to the whole page, `:host` and `::slotted` do not match, events are not retargeted+class HTMLElement extends Element {+ constructor() { if (CE.up) { const e = CE.up; CE.up = null; return e; } super(CE.tags.get(new.target) || 'div'); this._ce = true; }+ static [Symbol.hasInstance](o) { return this === HTMLElement ? o instanceof Element : Function.prototype[Symbol.hasInstance].call(this, o); }+}+const ceCall = (el, fn, ...a) => { try { if (typeof el[fn] === 'function') el[fn](...a); } catch (e) { __log('custom element ' + fn + ': ' + (e && (e.message + ' ' + e.stack) || e)); } };+const ceConnect = n => { if (n.nodeType !== 1) return; if (n._ce && !n._conn && n.isConnected) { n._conn = true; ceCall(n, 'connectedCallback'); } for (const c of n.childNodes.slice()) ceConnect(c); };+const ceDisconnect = n => { if (n.nodeType !== 1) return; for (const c of n.childNodes.slice()) ceDisconnect(c); if (n._conn) { n._conn = false; ceCall(n, 'disconnectedCallback'); } };+const ceAttr = (el, n, o, v) => { const obs = el.constructor && el.constructor.observedAttributes; if (obs && obs.includes(n)) ceCall(el, 'attributeChangedCallback', n, o, v); };+const ceUpgrade = (el, C) => {+ if (el._ce) return; el._ce = true;+ Object.setPrototypeOf(el, C.prototype);+ CE.up = el; try { new C(); } catch (e) { __log('custom element constructor: ' + (e && e.stack || e)); } finally { CE.up = null; }+ for (const a of Object.keys(el._a)) ceAttr(el, a, null, el._a[a]);+ ceConnect(el);+};+const customElementsApi = {+ define(name, C) { name = String(name).toLowerCase(); if (CE.defs.has(name)) throw new Error("customElements: '" + name + "' is already defined"); CE.defs.set(name, C); CE.tags.set(C, name); const found = []; const walk = n => { for (const c of n.childNodes) if (c.nodeType === 1) { if (c.localName === name) found.push(c); walk(c); } }; walk(document); for (const el of found) ceUpgrade(el, C); (CE.waiters.get(name) || []).forEach(r => r(C)); },+ get: name => CE.defs.get(String(name).toLowerCase()),+ whenDefined(name) { name = String(name).toLowerCase(); if (CE.defs.has(name)) return Promise.resolve(CE.defs.get(name)); return new Promise(r => { if (!CE.waiters.has(name)) CE.waiters.set(name, []); CE.waiters.get(name).push(r); }); },+ upgrade(root) { for (const el of [root, ...descendants(root)]) if (el.nodeType === 1 && CE.defs.has(el.localName)) ceUpgrade(el, CE.defs.get(el.localName)); },+};+// HTMLIFrameElement and friends: `x instanceof HTMLIFrameElement` must test the tag (style-loader and others branch on it)+const TAGGED = { Script: 'script', Input: 'input', Div: 'div', Span: 'span', Anchor: 'a', Image: 'img', Form: 'form', Button: 'button', Select: 'select', TextArea: 'textarea', Canvas: 'canvas', Style: 'style', Link: 'link', Body: 'body', Head: 'head', Html: 'html', Table: 'table', IFrame: 'iframe', Option: 'option', Label: 'label', Paragraph: 'p', Heading: 'h1 h2 h3 h4 h5 h6', UList: 'ul', OList: 'ol', LI: 'li', Media: 'audio video', Video: 'video', Audio: 'audio', Template: 'template' };+for (const [n, tags] of Object.entries(TAGGED)) { const T = tags.split(' '); g['HTML' + n + 'Element'] = class extends Element { static [Symbol.hasInstance](o) { return o instanceof Element && T.includes(o.localName); } }; }+Object.defineProperty(g.HTMLScriptElement.prototype, 'noModule', { value: false, writable: true, configurable: true }); // `'noModule' in HTMLScriptElement.prototype` is how pages detect module support+g.HTMLScriptElement.supports = t => t === 'classic' || t === 'module' || t === 'importmap';+// ---- getComputedStyle: a small cascade over the page's <style> elements (external sheets are inlined by the loader) and the inline style+// shortcut: declared values are returned as written (no unit conversion, no `var()`/`calc()` evaluation, `@media` blocks are skipped), no pseudo-elements, no transitions; specificity ignores :is()/:not() arguments+const UA_NONE = new Set('head script style title meta link template noscript option datalist object iframe canvas audio video base'.split(' '));+const UA_BLOCK = new Set('html body div p h1 h2 h3 h4 h5 h6 ul ol dl dt dd form hr blockquote figure figcaption details summary address pre fieldset legend center section article header footer nav main aside menu dir'.split(' '));+const UA_DISPLAY = { li: 'list-item', table: 'table', tr: 'table-row', td: 'table-cell', th: 'table-cell', thead: 'table-header-group', tbody: 'table-row-group', tfoot: 'table-footer-group', caption: 'table-caption', img: 'inline', button: 'inline-block', input: 'inline-block', select: 'inline-block', textarea: 'inline-block' };+const INHERITED = new Set('visibility color font-size font-family font-weight font-style line-height text-align white-space cursor direction letter-spacing text-transform list-style-type word-spacing'.split(' '));+const splitTop = (s, ch) => { const out = []; let d = 0, q = '', cur = ''; for (const c of s) { if (q) { if (c === q) q = ''; } else if (c === '"' || c === "'") q = c; else if (c === '(' || c === '[') d++; else if (c === ')' || c === ']') d--; if (c === ch && !d && !q) { out.push(cur); cur = ''; } else cur += c; } out.push(cur); return out; };+const parseDecls = t => { const o = []; for (const d of splitTop(t, ';')) { const i = d.indexOf(':'); if (i < 1) continue; let v = d.slice(i + 1).trim(); const imp = /!\s*important\s*$/i.test(v); if (imp) v = v.replace(/!\s*important\s*$/i, '').trim(); o.push([d.slice(0, i).trim().toLowerCase(), v, imp]); } return o; };+const specificity = s => { s = s.replace(/\[[^\]]*\]/g, ' [a] ').replace(/::?(?:before|after|first-line|first-letter)/g, ''); const ids = (s.match(/#[\w-]+/g) || []).length, cls = (s.match(/\.[\w-]+|\[a\]|:(?!:)[\w-]+/g) || []).length, tags = (s.replace(/[#.:][\w-]+/g, ' ').match(/(?:^|[\s>+~])[a-zA-Z][\w-]*/g) || []).length; return ids * 10000 + cls * 100 + tags; };+let sheetKey = null, sheetRules = [], sheetCalls = 0;+// the rightmost compound of a selector must match the element itself: remember its id, classes and tag to skip most rules cheaply+const need = s => { const last = s.split(/[\s>+~]+/).filter(Boolean).pop() || ''; const m = last.replace(/\[[^\]]*\]|:[\w-]+(\([^)]*\))?/g, ''); return { id: (m.match(/#([\w-]+)/) || [])[1], cls: (m.match(/\.[\w-]+/g) || []).map(c => c.slice(1)), tag: (m.match(/^[a-zA-Z][\w-]*/) || [])[0] }; };+const rulesOfPage = () => {+ // the <style> scan is O(page): redo it only every 32 calls (a style added in between shows up a little late)+ if (sheetKey !== null && ++sheetCalls % 32) return sheetRules;+ const styles = descendants(document).filter(e => e.localName === 'style'), key = styles.map(e => e.textContent.length).join(',') + ':' + styles.length;+ if (key === sheetKey) return sheetRules;+ sheetKey = key; sheetRules = []; let order = 0;+ for (const st of styles) {+ const css = st.textContent.replace(/\/\*[\s\S]*?\*\//g, ''); let i = 0;+ while (i < css.length) {+ const o = css.indexOf('{', i); if (o < 0) break;+ const head = css.slice(i, o).trim(); let d = 1, j = o + 1; while (j < css.length && d) { if (css[j] === '{') d++; else if (css[j] === '}') d--; j++; }+ if (!head.startsWith('@')) for (const sel of splitTop(head, ',')) { const s = sel.trim(); if (s) sheetRules.push({ sel: s, spec: specificity(s), order: order++, decls: parseDecls(css.slice(o + 1, j - 1)), need: need(s) }); }+ i = j;+ }+ }+ return sheetRules;+};+const couldMatch = (el, n) => (!n.tag || n.tag === '*' || n.tag.toLowerCase() === el.localName) && (!n.id || el._a.id === n.id) && n.cls.every(c => (' ' + (el._a.class || '') + ' ').includes(' ' + c + ' '));+const computedOf = (el, memo) => {+ if (memo.has(el)) return memo.get(el);+ const own = new Map(); memo.set(el, own);+ if (el.nodeType === 1) {+ const tag = el.localName;+ own.set('display', el._a.hidden !== undefined ? 'none' : UA_NONE.has(tag) ? 'none' : UA_BLOCK.has(tag) ? 'block' : UA_DISPLAY[tag] || 'inline');+ const hits = [];+ for (const r of rulesOfPage()) { if (!couldMatch(el, r.need)) continue; let ok = false; try { ok = matchesSel(el, r.sel); } catch (e) {} if (ok) hits.push(r); }+ hits.sort((a, b) => a.spec - b.spec || a.order - b.order);+ const imp = [];+ for (const r of hits) for (const [k, v, i] of r.decls) { if (i) imp.push([k, v]); else own.set(k, v); }+ for (const [k, v] of parseDecls(el._a.style || '')) own.set(k, v);+ for (const [k, v] of imp) own.set(k, v);+ }+ const pm = el.parentNode && el.parentNode.nodeType === 1 ? computedOf(el.parentNode, memo) : null;+ if (pm) for (const k of INHERITED) if ((!own.has(k) || own.get(k) === 'inherit') && pm.has(k)) own.set(k, pm.get(k));+ return own;+};+const DEFAULT_STYLE = { visibility: 'visible', opacity: '1', position: 'static', color: 'rgb(0, 0, 0)', 'font-size': '16px', 'font-weight': '400', 'font-style': 'normal', 'text-align': 'start', float: 'none', overflow: 'visible', 'z-index': 'auto', 'box-sizing': 'content-box', 'white-space': 'normal', 'pointer-events': 'auto' };+const computedStyle = (el, pseudo) => {+ const m = pseudo ? new Map() : computedOf(el, new Map());+ const get = name => {+ const n = String(name).replace(/[A-Z]/g, c => '-' + c.toLowerCase());+ if (m.has(n)) return m.get(n);+ if ((n === 'width' || n === 'height') && el._box) return el._box[n === 'width' ? 2 : 3] + 'px';+ return n in DEFAULT_STYLE ? DEFAULT_STYLE[n] : '';+ };+ return new Proxy({}, { get: (t, k) => k === 'getPropertyValue' ? get : k === 'getPropertyPriority' ? () => '' : k === 'length' ? m.size : k === 'cssText' ? [...m].map(([a, b]) => a + ': ' + b + ';').join(' ') : typeof k === 'symbol' || k === 'then' ? undefined : get(k) });+};+Object.assign(g, {+ window: g, self: g, top: g, parent: g, frames: g, globalThis: g, document, Node, Element, HTMLElement, Text, DocumentFragment, Document,+ Event, CustomEvent, EventTarget, MutationObserver: Observer, IntersectionObserver: IntersectionObs, ResizeObserver: ResizeObs,+ navigator: { userAgent: 'Mozilla/5.0 chrome-rs/0.1', language: 'en-US', languages: ['en-US'], platform: 'Win32', cookieEnabled: true, onLine: true, vendor: '' },+ console: { log: noop, warn: m => __log('warn: ' + m), error: (...a) => __log('error: ' + a.map(x => x && (x.message ? x.message + ' @ ' + x.stack : x.stack) || x).join(' ')), info: noop, debug: noop, trace: noop, group: noop, groupEnd: noop, table: noop, time: noop, timeEnd: noop, assert: noop },+ localStorage: store(lsData), sessionStorage: store(),+ innerWidth: 1000, innerHeight: 720, outerWidth: 1000, outerHeight: 720, devicePixelRatio: 1, scrollX: 0, scrollY: 0, pageXOffset: 0, pageYOffset: 0,+ scrollTo: noop, scrollBy: noop, focus: noop, blur: noop, alert: noop, confirm: () => false, prompt: () => null, open: () => null, close: noop, print: noop,+ getComputedStyle: computedStyle,+ matchMedia: q => ({ matches: false, media: String(q), addListener: noop, removeListener: noop, addEventListener: noop, removeEventListener: noop }),+ requestAnimationFrame: f => g.setTimeout(f, 16), cancelAnimationFrame: id => g.clearTimeout(id),+ requestIdleCallback: f => g.setTimeout(f, 1), cancelIdleCallback: id => g.clearTimeout(id),+ setTimeout: (f, d, ...a) => { timers.push({ id: ++tid, f, t: now + (+d || 0), a }); return tid; },+ setInterval: (f, d, ...a) => { const e = Math.max(+d || 0, 1); timers.push({ id: ++tid, f, t: now + e, a, every: e, n: 0 }); return tid; },+ clearTimeout: id => { cleared.add(id); timers = timers.filter(x => x.id !== id); },+ clearInterval: id => { cleared.add(id); timers = timers.filter(x => x.id !== id); },+});++// ---- URL, encoding, forms, networking, history (M4 web APIs on top of the synchronous natives __fetch / __resolve)+const dec = s => { try { return decodeURIComponent(s.replace(/\+/g, ' ')); } catch (e) { return s; } };+const encq = s => encodeURIComponent(s).replace(/%20/g, '+');+class URLSearchParams {+ constructor(init) {+ this._p = [];+ if (init instanceof URLSearchParams) this._p = init._p.map(x => x.slice());+ else if (typeof init === 'string') { for (const kv of init.replace(/^\?/, '').split('&')) if (kv) { const i = kv.indexOf('='); this._p.push([dec(i < 0 ? kv : kv.slice(0, i)), dec(i < 0 ? '' : kv.slice(i + 1))]); } }+ else if (init && typeof init[Symbol.iterator] === 'function') for (const [k, v] of init) this._p.push([String(k), String(v)]);+ else if (init) for (const k of Object.keys(init)) this._p.push([k, String(init[k])]);+ }+ _sync() { if (this._u) { const q = this.toString(); this._u.search = q ? '?' + q : ''; } }+ append(k, v) { this._p.push([String(k), String(v)]); this._sync(); }+ delete(k) { this._p = this._p.filter(x => x[0] !== String(k)); this._sync(); }+ get(k) { const e = this._p.find(x => x[0] === String(k)); return e ? e[1] : null; }+ getAll(k) { return this._p.filter(x => x[0] === String(k)).map(x => x[1]); }+ has(k) { return this._p.some(x => x[0] === String(k)); }+ set(k, v) { k = String(k); const i = this._p.findIndex(x => x[0] === k); if (i < 0) this._p.push([k, String(v)]); else { this._p[i][1] = String(v); this._p = this._p.filter((x, j) => x[0] !== k || j === i); } this._sync(); }+ sort() { this._p.sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0); this._sync(); }+ forEach(f, t) { for (const [k, v] of this._p) f.call(t, v, k, this); }+ keys() { return this._p.map(x => x[0])[Symbol.iterator](); }+ values() { return this._p.map(x => x[1])[Symbol.iterator](); }+ entries() { return this._p.map(x => [x[0], x[1]])[Symbol.iterator](); }+ [Symbol.iterator]() { return this.entries(); }+ get size() { return this._p.length; }+ toString() { return this._p.map(([k, v]) => encq(k) + '=' + encq(v)).join('&'); }+}+class URL {+ constructor(u, base) {+ u = String(u);+ if (!/^[a-z][a-z0-9+.-]*:/i.test(u)) { if (base === undefined) throw new TypeError('Invalid URL: ' + u); u = __resolve(String(base instanceof URL ? base.href : base), u); }+ const m = /^([a-z][a-z0-9+.-]*:)(?:\/\/(?:([^:@\/?#]*)(?::([^@\/?#]*))?@)?([^\/?#:]*)(?::(\d+))?)?([^?#]*)(\?[^#]*)?(#.*)?$/i.exec(u);+ if (!m) throw new TypeError('Invalid URL: ' + u);+ this.protocol = m[1].toLowerCase(); this.username = m[2] || ''; this.password = m[3] || ''; this.hostname = (m[4] || '').toLowerCase(); this.port = m[5] || '';+ this.pathname = m[6] || (m[4] !== undefined ? '/' : ''); this.search = m[7] && m[7] !== '?' ? m[7] : ''; this.hash = m[8] && m[8] !== '#' ? m[8] : '';+ this.searchParams = new URLSearchParams(this.search); this.searchParams._u = this;+ }+ get host() { return this.hostname + (this.port ? ':' + this.port : ''); }+ get origin() { return /^https?:$/.test(this.protocol) ? this.protocol + '//' + this.host : 'null'; }+ get href() { return this.protocol + (this.hostname || this.protocol === 'file:' ? '//' : '') + (this.username ? this.username + (this.password ? ':' + this.password : '') + '@' : '') + this.host + this.pathname + this.search + this.hash; }+ toString() { return this.href; } toJSON() { return this.href; }+ static canParse(u, b) { try { new URL(u, b); return true; } catch (e) { return false; } }+}+const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';+const btoa = s => {+ s = String(s); let o = '';+ for (let i = 0; i < s.length; i += 3) {+ const a = s.charCodeAt(i), b = s.charCodeAt(i + 1), c = s.charCodeAt(i + 2);+ if (a > 255 || b > 255 || c > 255) throw new Error('InvalidCharacterError');+ o += B64[a >> 2] + B64[(a & 3) << 4 | (b || 0) >> 4] + (i + 1 < s.length ? B64[(b & 15) << 2 | (c || 0) >> 6] : '=') + (i + 2 < s.length ? B64[c & 63] : '=');+ }+ return o;+};+const atob = s => {+ s = String(s).replace(/[\s=]+/g, ''); let o = '', acc = 0, bits = 0;+ for (const ch of s) { const v = B64.indexOf(ch); if (v < 0) throw new Error('InvalidCharacterError'); acc = acc << 6 | v; bits += 6; if (bits >= 8) { bits -= 8; o += String.fromCharCode(acc >> bits & 255); } }+ return o;+};+class TextEncoder {+ get encoding() { return 'utf-8'; }+ encode(s) { const e = unescape(encodeURIComponent(String(s === undefined ? '' : s))); const a = new Uint8Array(e.length); for (let i = 0; i < e.length; i++) a[i] = e.charCodeAt(i); return a; }+}+class TextDecoder {+ constructor(l) { this.encoding = String(l || 'utf-8').toLowerCase(); }+ decode(b) {+ if (!b) return '';+ const u = b instanceof ArrayBuffer ? new Uint8Array(b) : new Uint8Array(b.buffer || b, b.byteOffset || 0, b.byteLength === undefined ? b.length : b.byteLength);+ let s = ''; for (let i = 0; i < u.length; i++) s += String.fromCharCode(u[i]);+ try { return decodeURIComponent(escape(s)); } catch (e) { return s; }+ }+}+class Blob {+ constructor(parts, o) { this._t = (parts || []).map(p => typeof p === 'string' ? p : p instanceof Blob ? p._t : p && p.byteLength !== undefined ? new TextDecoder().decode(p) : String(p)).join(''); this.type = (o && o.type) || ''; }+ get size() { return unescape(encodeURIComponent(this._t)).length; }+ text() { return Promise.resolve(this._t); }+ arrayBuffer() { return Promise.resolve(new TextEncoder().encode(this._t).buffer); }+}+class FormData {+ constructor(form) {+ this._e = [];+ if (form && form.nodeType === 1) for (const e of descendants(form)) {+ const n = e._a.name, t = (e._a.type || '').toLowerCase();+ if (!n || 'disabled' in e._a) continue;+ if (e.localName === 'input') { if (['submit', 'button', 'reset', 'image', 'file'].includes(t)) continue; if ((t === 'checkbox' || t === 'radio') && !('checked' in e._a)) continue; this._e.push([n, e._a.value !== undefined ? e._a.value : (t === 'checkbox' || t === 'radio' ? 'on' : '')]); }+ else if (e.localName === 'textarea') this._e.push([n, e.textContent]);+ else if (e.localName === 'select') { const o = descendants(e).filter(x => x.localName === 'option'); const s = o.find(x => 'selected' in x._a) || o[0]; if (s) this._e.push([n, s._a.value !== undefined ? s._a.value : s.textContent.trim()]); }+ }+ }+ append(k, v) { this._e.push([String(k), v instanceof Blob ? v : String(v)]); }+ delete(k) { this._e = this._e.filter(x => x[0] !== String(k)); }+ get(k) { const e = this._e.find(x => x[0] === String(k)); return e ? e[1] : null; }+ getAll(k) { return this._e.filter(x => x[0] === String(k)).map(x => x[1]); }+ has(k) { return this._e.some(x => x[0] === String(k)); }+ set(k, v) { k = String(k); const i = this._e.findIndex(x => x[0] === k); if (i < 0) this._e.push([k, String(v)]); else { this._e[i][1] = String(v); this._e = this._e.filter((x, j) => x[0] !== k || j === i); } }+ forEach(f, t) { for (const [k, v] of this._e) f.call(t, v, k, this); }+ keys() { return this._e.map(x => x[0])[Symbol.iterator](); }+ values() { return this._e.map(x => x[1])[Symbol.iterator](); }+ entries() { return this._e.map(x => [x[0], x[1]])[Symbol.iterator](); }+ [Symbol.iterator]() { return this.entries(); }+}+class Headers {+ constructor(init) { this._h = {}; if (init instanceof Headers) init = init._h; if (Array.isArray(init)) for (const [k, v] of init) this.append(k, v); else if (init) for (const k of Object.keys(init)) this.append(k, init[k]); }+ append(k, v) { k = String(k).toLowerCase(); this._h[k] = k in this._h ? this._h[k] + ', ' + v : String(v); }+ set(k, v) { this._h[String(k).toLowerCase()] = String(v); }+ get(k) { k = String(k).toLowerCase(); return k in this._h ? this._h[k] : null; }+ has(k) { return String(k).toLowerCase() in this._h; }+ delete(k) { delete this._h[String(k).toLowerCase()]; }+ forEach(f, t) { for (const k of Object.keys(this._h)) f.call(t, this._h[k], k, this); }+ entries() { return Object.entries(this._h)[Symbol.iterator](); }+ keys() { return Object.keys(this._h)[Symbol.iterator](); }+ values() { return Object.values(this._h)[Symbol.iterator](); }+ [Symbol.iterator]() { return this.entries(); }+}+// request body -> [content-type, text]; FormData goes out as multipart/form-data (text fields only)+const prep = (body, ctype) => {+ if (body === undefined || body === null) return [ctype || '', ''];+ if (body instanceof URLSearchParams) return ['application/x-www-form-urlencoded;charset=UTF-8', body.toString()];+ if (body instanceof FormData) {+ const b = '----chromers' + Math.floor(Math.random() * 1e9);+ return ['multipart/form-data; boundary=' + b, body._e.map(([k, v]) => '--' + b + '\r\nContent-Disposition: form-data; name="' + k.replace(/"/g, '%22') + '"\r\n\r\n' + (v instanceof Blob ? v._t : v) + '\r\n').join('') + '--' + b + '--\r\n'];+ }+ if (body instanceof Blob) return [ctype || body.type, body._t];+ return [ctype || (typeof body === 'string' ? 'text/plain;charset=UTF-8' : ''), typeof body === 'string' ? body : String(body)];+};+const netFetch = (url, method, body, headers) => {+ const h = new Headers(headers), [ct, text] = prep(body, h.get('content-type'));+ return JSON.parse(__fetch(String(url), method, method === 'GET' || method === 'HEAD' ? '' : text, ct));+};+class Response {+ constructor(r, url) { this.status = r.status; this.ok = r.status >= 200 && r.status < 300; this.statusText = ''; this.url = url || ''; this.type = 'basic'; this.redirected = false; this.headers = new Headers(r.ctype ? { 'content-type': r.ctype } : {}); this._b = r.body || ''; this.bodyUsed = false; }+ text() { this.bodyUsed = true; return Promise.resolve(this._b); }+ json() { this.bodyUsed = true; return Promise.resolve().then(() => JSON.parse(this._b)); }+ blob() { return Promise.resolve(new Blob([this._b], { type: this.headers.get('content-type') || '' })); }+ arrayBuffer() { return Promise.resolve(new TextEncoder().encode(this._b).buffer); }+ clone() { return this; }+}+class AbortSignal extends EventTarget { constructor() { super(); this.aborted = false; this.reason = undefined; } throwIfAborted() { if (this.aborted) throw this.reason; } }+class AbortController { constructor() { this.signal = new AbortSignal(); } abort(r) { if (this.signal.aborted) return; this.signal.aborted = true; this.signal.reason = r || new Error('AbortError'); this.signal.dispatchEvent(new Event('abort')); } }+class Hist {+ constructor() { this.entries = [{ s: null, u: location.href }]; this.i = 0; this.scrollRestoration = 'auto'; }+ get length() { return this.entries.length; } get state() { return this.entries[this.i].s; }+ pushState(s, t, u) { if (u !== undefined && u !== null) setLoc(__resolve(location.href, String(u))); this.entries.length = this.i + 1; this.entries.push({ s, u: location.href }); this.i++; }+ replaceState(s, t, u) { if (u !== undefined && u !== null) setLoc(__resolve(location.href, String(u))); this.entries[this.i] = { s, u: location.href }; }+ go(d) { const j = this.i + (d | 0); if (j < 0 || j >= this.entries.length || !d) return; this.i = j; setLoc(this.entries[j].u); g.setTimeout(() => g.dispatchEvent(new g.PopStateEvent('popstate', { state: this.entries[j].s })), 0); }+ back() { this.go(-1); } forward() { this.go(1); }+}+for (const n of ['MouseEvent', 'FocusEvent', 'InputEvent', 'PointerEvent', 'TouchEvent', 'WheelEvent', 'ErrorEvent', 'MessageEvent', 'PopStateEvent', 'HashChangeEvent', 'StorageEvent', 'ProgressEvent', 'SubmitEvent'])+ g[n] = class extends Event { constructor(t, i) { super(t, i); Object.assign(this, i || {}); } };+// the UI sends `key` only: derive the legacy codes (`e.which === 13` is still how jQuery/Backbone apps spot Enter)+const KEYCODES = { Enter: 13, Escape: 27, Backspace: 8, Tab: 9, ' ': 32, Delete: 46, ArrowLeft: 37, ArrowUp: 38, ArrowRight: 39, ArrowDown: 40, Home: 36, End: 35, PageUp: 33, PageDown: 34 };+g.KeyboardEvent = class KeyboardEvent extends Event {+ constructor(t, i) {+ super(t, i); Object.assign(this, i || {});+ const k = this.key === undefined ? '' : String(this.key);+ if (this.keyCode === undefined) this.keyCode = KEYCODES[k] || (k.length === 1 ? k.toUpperCase().charCodeAt(0) : 0);+ if (this.which === undefined) this.which = this.keyCode;+ if (this.code === undefined) this.code = k === 'Enter' ? 'Enter' : k.length === 1 ? (/[a-z]/i.test(k) ? 'Key' + k.toUpperCase() : /\d/.test(k) ? 'Digit' + k : '') : k;+ }+};+class WS extends EventTarget { // no sockets: connections fail asynchronously so pages fall back instead of throwing+ constructor(u) { super(); this.url = String(u); this.readyState = 0; this.bufferedAmount = 0; g.setTimeout(() => { this.readyState = 3; for (const t of ['error', 'close']) { const e = new Event(t); if (typeof this['on' + t] === 'function') this['on' + t](e); this.dispatchEvent(e); } }, 0); }+ send() {} close() { this.readyState = 3; }+}+Object.assign(g, {+ URL, URLSearchParams, btoa, atob, TextEncoder, TextDecoder, Blob, FormData, Headers, Response, AbortController, AbortSignal, WebSocket: WS, EventSource: WS, history: new Hist(),+ performance: { now: () => now + (perfT += 0.01), timeOrigin: 0, mark: noop, measure: noop, getEntriesByName: () => [], getEntriesByType: () => [], clearMarks: noop, clearMeasures: noop },+ queueMicrotask: f => { Promise.resolve().then(f).catch(noop); },+ structuredClone: v => v === undefined ? v : JSON.parse(JSON.stringify(v)),+ crypto: { getRandomValues: a => { const m = Math.pow(256, a.BYTES_PER_ELEMENT || 1); for (let i = 0; i < a.length; i++) a[i] = Math.floor(Math.random() * m); return a; }, randomUUID: () => 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => { const r = Math.random() * 16 | 0; return (c === 'x' ? r : r & 3 | 8).toString(16); }), subtle: {} },+ customElements: customElementsApi,+ CSS: { supports: () => false, escape: s => String(s).replace(/[^\w-]/g, c => '\\' + c) },+ getSelection: () => ({ rangeCount: 0, toString: () => '', removeAllRanges: noop, addRange: noop }),+ Image: function () { return document.createElement('img'); },+ fetch: (u, o) => new Promise((res, rej) => {+ o = o || {};+ const req = u instanceof Object && u.url ? u : null, url = String(req ? req.url : u), method = String(o.method || (req && req.method) || 'GET').toUpperCase();+ if (o.signal && o.signal.aborted) return rej(o.signal.reason);+ const r = netFetch(url, method, o.body, o.headers);+ if (!r.status) return rej(new TypeError('Failed to fetch'));+ res(new Response(r, url));+ }),+ XMLHttpRequest: class extends EventTarget {+ constructor() { super(); this.readyState = 0; this.status = 0; this.statusText = ''; this.responseText = ''; this.response = ''; this.responseType = ''; this.responseURL = ''; this._h = new Headers(); this.timeout = 0; this.withCredentials = false; this.upload = new EventTarget(); }+ open(m, u) { this._m = String(m).toUpperCase(); this._u = String(u); this.readyState = 1; }+ setRequestHeader(k, v) { this._h.append(k, v); } abort() { this._abort = true; }+ getResponseHeader(k) { return this._rh ? this._rh.get(k) : null; }+ getAllResponseHeaders() { let s = ''; if (this._rh) this._rh.forEach((v, k) => { s += k + ': ' + v + '\r\n'; }); return s; }+ overrideMimeType() {}+ send(body) {+ const r = netFetch(this._u, this._m, body, this._h);+ g.setTimeout(() => {+ if (this._abort) return;+ this.status = r.status; this.responseText = r.body || ''; this.responseURL = this._u; this._rh = new Headers(r.ctype ? { 'content-type': r.ctype } : {}); this.readyState = 4;+ try { this.response = this.responseType === 'json' ? JSON.parse(this.responseText) : this.responseText; } catch (e) { this.response = null; }+ const fire = t => { const e = new Event(t); if (typeof this['on' + t] === 'function') { try { this['on' + t].call(this, e); } catch (x) {} } this.dispatchEvent(e); };+ fire('readystatechange'); fire(r.status ? 'load' : 'error'); fire('loadend');+ }, 0);+ }+ },+});+g.navigator.sendBeacon = () => true;+// interface objects scripts test with instanceof or feature checks; the DOM itself hands out plain arrays and elements+class File extends Blob { constructor(parts, name, o) { super(parts, o); this.name = String(name); this.lastModified = (o && o.lastModified) || Date.now(); } }+Object.assign(g, {+ File, NodeList: class NodeList extends Array {}, HTMLCollection: class HTMLCollection extends Array {}, ShadowRoot: class ShadowRoot extends DocumentFragment {+ constructor() { super(); this.mode = 'open'; this.adoptedStyleSheets = []; this.activeElement = null; }+ get innerHTML() { return this.childNodes.map(ser).join(''); }+ set innerHTML(h) { this.childNodes.forEach(c => c.parentNode = null); this.childNodes = []; for (const c of fromJSON(JSON.parse(__parse(String(h))))) this.appendChild(c); }+ getRootNode() { return this; }+ },+ SVGElement: Element, Storage: class Storage {},+ screen: { width: 1000, height: 720, availWidth: 1000, availHeight: 720, colorDepth: 24, pixelDepth: 24, orientation: { type: 'landscape-primary', angle: 0 } },+});++// ---- more of the platform surface that real scripts probe. Where nothing is rendered behind an API it is a stub that answers like an empty page.+const def = (o, props) => { for (const k of Object.keys(props)) if (!(k in o)) Object.defineProperty(o, k, Object.getOwnPropertyDescriptor(props, k)); };+const isLink = e => e.localName === 'a' || e.localName === 'area';+const linkPart = (e, k) => { if (!isLink(e)) return undefined; try { return new URL(e.href)[k]; } catch (x) { return ''; } };+const toNode = n => typeof n === 'string' ? new Text(n) : n;+const fragmentOf = h => { const f = new DocumentFragment(); for (const c of fromJSON(JSON.parse(__parse(String(h))))) f.appendChild(c); return f; };+def(Element.prototype, {+ insertAdjacentElement(w, n) { w = String(w).toLowerCase(); if (w === 'beforebegin') { if (this.parentNode) this.parentNode.insertBefore(n, this); } else if (w === 'afterbegin') this.insertBefore(n, this.childNodes[0] || null); else if (w === 'beforeend') this.appendChild(n); else if (w === 'afterend' && this.parentNode) this.parentNode.insertBefore(n, this.nextSibling); return n; },+ insertAdjacentText(w, t) { this.insertAdjacentElement(w, new Text(t)); },+ getAttributeNames() { return Object.keys(this._a); }, hasAttributes() { return Object.keys(this._a).length > 0; },+ replaceWith(...ns) { const p = this.parentNode; if (!p) return; for (const n of ns) p.insertBefore(toNode(n), this); p.removeChild(this); },+ replaceChildren(...ns) { for (const c of this.childNodes.slice()) this.removeChild(c); for (const n of ns) this.appendChild(toNode(n)); },+ scrollTo() {}, scroll() {}, normalize() {}, getAnimations() { return []; }, requestFullscreen() { return Promise.resolve(); }, setPointerCapture() {}, releasePointerCapture() {},+ isSameNode(n) { return n === this; }, isEqualNode(n) { return !!n && ser(n) === ser(this); },+ compareDocumentPosition(n) { if (n === this) return 0; if (this.contains(n)) return 20; if (n.contains && n.contains(this)) return 10; const all = descendants(document); return all.indexOf(n) > all.indexOf(this) ? 4 : 2; },+ attachShadow(o) { if (this._sr) throw new Error('NotSupportedError: shadow root already attached'); const s = new ShadowRoot(); s.host = this; s.mode = (o && o.mode) || 'open'; this._sr = s; return s; },+ get shadowRoot() { return this._sr && this._sr.mode === 'open' ? this._sr : null; },+ assignedNodes() { if (this.localName !== 'slot') return []; let r = this; while (r.parentNode) r = r.parentNode; return r.host ? slotted(this, r.host) : []; },+ assignedElements() { return this.assignedNodes().filter(n => n.nodeType === 1); },+ getAttributeNS(ns, n) { return this.getAttribute(n); }, setAttributeNS(ns, n, v) { this.setAttribute(n, v); }, removeAttributeNS(ns, n) { this.removeAttribute(n); },+ get tabIndex() { const v = this._a.tabindex; return v === undefined ? (/^(a|button|input|select|textarea)$/.test(this.localName) ? 0 : -1) : +v; }, set tabIndex(v) { this._a.tabindex = String(v); },+ get offsetParent() { return this.parentNode && this.parentNode.nodeType === 1 ? this.parentNode : null; },+ get namespaceURI() { return this._ns || 'http://www.w3.org/1999/xhtml'; },+ // <template>.content: a fragment holding clones of the template's children (templates are never laid out)+ set content(v) { this._a.content = String(v); },+ get content() { if (this.localName !== 'template') return this._a.content || ''; if (!this._content) { this._content = new DocumentFragment(); for (const c of this.childNodes) this._content.appendChild(c.cloneNode(true, true)); } return this._content; },+ // forms: `form.elements['name']` and `control.form`+ get elements() { if (this.localName !== 'form' && this.localName !== 'fieldset') return undefined; const l = descendants(this).filter(e => /^(input|select|textarea|button|fieldset|output|object)$/.test(e.localName) && e._a.type !== 'image'); for (const e of l) for (const k of [e._a.name, e._a.id]) if (k && !(k in l)) l[k] = e; l.namedItem = n => l[n] || null; l.item = i => l[i] || null; return l; },+ get form() { if (!/^(input|select|textarea|button|fieldset|output|object|label)$/.test(this.localName)) return undefined; for (let p = this.parentNode; p; p = p.parentNode) if (p.localName === 'form') return p; return null; },+ // links: the URL parts of <a href> / <area href>, resolved against the page like a browser does+ get pathname() { return linkPart(this, 'pathname'); }, get search() { return linkPart(this, 'search'); }, get hash() { return linkPart(this, 'hash'); },+ get host() { return linkPart(this, 'host'); }, get hostname() { return linkPart(this, 'hostname'); }, get port() { return linkPart(this, 'port'); }, get protocol() { return linkPart(this, 'protocol'); }, get origin() { return linkPart(this, 'origin'); },+ // <select>/<option>: the one selected state is the `selected` attribute (React's select handling reads `select.options.length`)+ get options() { if (this.localName !== 'select' && this.localName !== 'datalist') return undefined; const o = descendants(this).filter(x => x.localName === 'option'); o.item = i => o[i] || null; return o; },+ get selectedIndex() { if (this.localName !== 'select') return undefined; const o = this.options, i = o.findIndex(x => 'selected' in x._a); return i >= 0 ? i : o.length ? 0 : -1; },+ set selectedIndex(v) { this.options.forEach((x, i) => { if (i === v) x._a.selected = ''; else delete x._a.selected; }); },+ get selectedOptions() { if (this.localName !== 'select') return undefined; const o = this.options, i = this.selectedIndex; return i >= 0 ? [o[i]] : []; },+ get defaultSelected() { return 'selected' in this._a; }, set defaultSelected(v) { if (v) this._a.selected = ''; else delete this._a.selected; },+ get index() { let s = this.parentNode; while (s && s.localName !== 'select') s = s.parentNode; return s ? s.options.indexOf(this) : 0; },+ get text() { return this.textContent; }, set text(v) { this.textContent = v; },+ get clientTop() { return 0; }, get clientLeft() { return 0; }, get scrollLeft() { return 0; }, set scrollLeft(v) {},+ get dir() { return this._a.dir || ''; }, set dir(v) { this._a.dir = String(v); }, get slot() { return this._a.slot || ''; }, set slot(v) { this._a.slot = String(v); },+ get draggable() { return this._a.draggable === 'true'; }, set draggable(v) { this._a.draggable = String(!!v); },+ get contentEditable() { return this._a.contenteditable || 'inherit'; }, set contentEditable(v) { this._a.contenteditable = String(v); },+ get isContentEditable() { return this._a.contenteditable === 'true' || this._a.contenteditable === ''; },+});+const fontSet = { ready: Promise.resolve(), status: 'loaded', size: 0, load: () => Promise.resolve([]), check: () => true, forEach: noop, add: noop, delete: noop, has: () => false, addEventListener: noop, removeEventListener: noop, [Symbol.iterator]: function* () {} };+class CSSStyleSheet { constructor() { this.cssRules = []; this.rules = this.cssRules; this.disabled = false; this.media = { mediaText: '' }; this._text = ''; } insertRule(r) { this._text += ' ' + r; return 0; } deleteRule() {} addRule() { return 0; } replace(t) { this._text = String(t); return Promise.resolve(this); } replaceSync(t) { this._text = String(t); } }+const NodeFilter = { FILTER_ACCEPT: 1, FILTER_REJECT: 2, FILTER_SKIP: 3, SHOW_ALL: 0xFFFFFFFF, SHOW_ELEMENT: 1, SHOW_ATTRIBUTE: 2, SHOW_TEXT: 4, SHOW_CDATA_SECTION: 8, SHOW_PROCESSING_INSTRUCTION: 64, SHOW_COMMENT: 128, SHOW_DOCUMENT: 256, SHOW_DOCUMENT_TYPE: 512, SHOW_DOCUMENT_FRAGMENT: 1024 };+class TreeWalker {+ // walks the live tree in document order from `currentNode` (Lit moves currentNode into a template before walking)+ constructor(root, what, filter) { this.root = root; this.currentNode = root; this.whatToShow = what === undefined ? 0xFFFFFFFF : what >>> 0; this.filter = filter || null; }+ _ok(n) { if (!(this.whatToShow & (1 << (n.nodeType - 1)))) return false; const f = this.filter; if (!f) return true; const r = typeof f === 'function' ? f(n) : f.acceptNode(n); return r === 1 || r === true; }+ _next(n) { if (n.childNodes && n.childNodes.length) return n.childNodes[0]; for (; n && n !== this.root; n = n.parentNode) { const s = n.nextSibling; if (s) return s; } return null; }+ _prev(n) { if (n === this.root) return null; let s = n.previousSibling; if (!s) return n.parentNode === this.root ? null : n.parentNode; while (s.childNodes && s.childNodes.length) s = s.childNodes[s.childNodes.length - 1]; return s; }+ nextNode() { let n = this.currentNode; while ((n = this._next(n))) if (this._ok(n)) return this.currentNode = n; return null; }+ previousNode() { let n = this.currentNode; while ((n = this._prev(n))) if (this._ok(n)) return this.currentNode = n; return null; }+ firstChild() { const n = this.currentNode.childNodes && this.currentNode.childNodes[0]; return n && this._ok(n) ? this.currentNode = n : null; }+ parentNode() { const n = this.currentNode === this.root ? null : this.currentNode.parentNode; return n && this._ok(n) ? this.currentNode = n : null; }+}+class Range {+ constructor() { this.collapsed = true; this.startContainer = this.endContainer = document; this.startOffset = this.endOffset = 0; }+ setStart(n, o) { this.startContainer = n; this.startOffset = o; } setEnd(n, o) { this.endContainer = n; this.endOffset = o; }+ selectNode(n) { this.startContainer = this.endContainer = n.parentNode; } selectNodeContents(n) { this.startContainer = this.endContainer = n; }+ collapse() {} detach() {} cloneRange() { return Object.assign(new Range(), this); } deleteContents() {} toString() { return ''; }+ getBoundingClientRect() { return { x: 0, y: 0, left: 0, top: 0, right: 0, bottom: 0, width: 0, height: 0 }; } getClientRects() { return []; }+ createContextualFragment(h) { return fragmentOf(h); }+}+def(Document.prototype, {+ get styleSheets() { return Object.assign(descendants(this).filter(e => e.localName === 'style' || (e.localName === 'link' && /stylesheet/i.test(e._a.rel || ''))).map(e => Object.assign(new CSSStyleSheet(), { ownerNode: e, href: e._a.href || null })), { item(i) { return this[i] || null; } }); },+ get scripts() { return this.getElementsByTagName('script'); }, get forms() { return this.getElementsByTagName('form'); }, get images() { return this.getElementsByTagName('img'); }, get all() { return this.getElementsByTagName('*'); },+ get links() { return descendants(this).filter(e => (e.localName === 'a' || e.localName === 'area') && 'href' in e._a); },+ get compatMode() { return 'CSS1Compat'; }, get doctype() { return { name: 'html', nodeType: 10, publicId: '', systemId: '' }; }, get fonts() { return fontSet; },+ get activeElement() { return this.body; }, get domain() { return loc.hostname; }, get lastModified() { return ''; }, get URL() { return loc._h; }, get documentURI() { return loc._h; }, get baseURI() { return loc._h; },+ get contentType() { return 'text/html'; }, get dir() { return ''; }, get inputEncoding() { return 'UTF-8'; },+ createRange() { return new Range(); }, createTreeWalker(r, w, f) { return new TreeWalker(r, w, f); }, elementFromPoint() { return this.body; }, elementsFromPoint() { return []; },+ getElementsByName(n) { return descendants(this).filter(e => e._a.name === n); }, adoptNode(n) { return n; }, importNode(n, deep) { return n.cloneNode(deep); },+ execCommand() { return false; }, queryCommandSupported() { return false; },+});+const adopted = { get adoptedStyleSheets() { return this._ass || (this._ass = []); }, set adoptedStyleSheets(v) { this._ass = Array.from(v); } };+def(Document.prototype, adopted); def(DocumentFragment.prototype, adopted);+class DOMParser { parseFromString(s) { const d = document.implementation.createHTMLDocument(''); d.body.innerHTML = String(s); return d; } }+class XMLSerializer { serializeToString(n) { return ser(n); } }+class ReadableStream { constructor() { this.locked = false; } getReader() { return { read: () => new Promise(noop), releaseLock: noop, cancel: () => Promise.resolve(), closed: new Promise(noop) }; } cancel() { return Promise.resolve(); } pipeThrough(t) { return t.readable; } pipeTo() { return Promise.resolve(); } tee() { return [this, this]; } }+class WritableStream { constructor() { this.locked = false; } getWriter() { return { write: () => Promise.resolve(), close: () => Promise.resolve(), abort: () => Promise.resolve(), releaseLock: noop, ready: Promise.resolve(), closed: Promise.resolve() }; } }+class TransformStream { constructor() { this.readable = new ReadableStream(); this.writable = new WritableStream(); } }+// message ports deliver asynchronously to the other end (schedulers such as React's use a MessageChannel)+class MessagePort extends EventTarget {+ constructor() { super(); this.onmessage = null; this._o = null; }+ postMessage(d) { const o = this._o; if (o) g.setTimeout(() => { const e = new Event('message'); e.data = d; e.target = o; if (o.onmessage) o.onmessage(e); o.dispatchEvent(e); }, 0); }+ start() {} close() { this._o = null; }+}+class MessageChannel { constructor() { this.port1 = new MessagePort(); this.port2 = new MessagePort(); this.port1._o = this.port2; this.port2._o = this.port1; } }+class BroadcastChannel extends EventTarget { constructor(n) { super(); this.name = n; } postMessage() {} close() {} }+class FileReader extends EventTarget {+ _done(r) { g.setTimeout(() => { this.result = r; this.readyState = 2; for (const t of ['load', 'loadend']) { const e = new Event(t); e.target = this; if (this['on' + t]) this['on' + t](e); this.dispatchEvent(e); } }, 0); }+ readAsText(b) { this._done(b._t); } readAsDataURL(b) { this._done('data:' + (b.type || 'application/octet-stream') + ';base64,' + btoa(unescape(encodeURIComponent(b._t)))); }+ readAsArrayBuffer(b) { this._done(new TextEncoder().encode(b._t).buffer); } abort() {}+}+class Request {+ constructor(i, o) { o = o || {}; const r = i instanceof Request ? i : null; this.url = String(r ? r.url : i); this.method = String(o.method || (r && r.method) || 'GET').toUpperCase(); this.headers = new Headers(o.headers || (r && r.headers)); this.body = o.body !== undefined ? o.body : r ? r.body : null; this.signal = o.signal || null; this.credentials = o.credentials || 'same-origin'; this.mode = o.mode || 'cors'; }+ clone() { return new Request(this); }+}+class DOMRect { constructor(x = 0, y = 0, w = 0, h = 0) { Object.assign(this, { x, y, width: w, height: h }); } get left() { return Math.min(this.x, this.x + this.width); } get right() { return Math.max(this.x, this.x + this.width); } get top() { return Math.min(this.y, this.y + this.height); } get bottom() { return Math.max(this.y, this.y + this.height); } }+class DOMPoint { constructor(x = 0, y = 0, z = 0, w = 1) { Object.assign(this, { x, y, z, w }); } }+class PerformanceObserver extends Observer { static get supportedEntryTypes() { return []; } }+const pad = n => String(n).padStart(2, '0');+// Intl: English only. Dates use the engine's local time (or UTC with timeZone: 'UTC'); there is no locale data, so other languages format like English.+const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];+class DateTimeFormat {+ constructor(l, o) { this.l = (Array.isArray(l) ? l[0] : l) || 'en-US'; this.o = o || {}; }+ resolvedOptions() { return Object.assign({ locale: this.l, calendar: 'gregory', numberingSystem: 'latn', timeZone: 'UTC' }, this.o); }+ format(d) {+ d = d === undefined ? new Date() : new Date(d); let o = this.o; const u = o.timeZone === 'UTC', G = k => d[(u ? 'getUTC' : 'get') + k]();+ if (o.dateStyle || o.timeStyle) { const D = { full: { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }, long: { year: 'numeric', month: 'long', day: 'numeric' }, medium: { year: 'numeric', month: 'short', day: 'numeric' }, short: { year: '2-digit', month: 'numeric', day: 'numeric' } }, T = { short: { hour: 'numeric', minute: '2-digit' } }; o = Object.assign({}, o.dateStyle ? D[o.dateStyle] : {}, o.timeStyle ? Object.assign({ hour: 'numeric', minute: '2-digit' }, o.timeStyle === 'short' ? {} : { second: '2-digit' }) : {}, { hour12: o.hour12 }); }+ const has = ['weekday', 'year', 'month', 'day', 'hour', 'minute', 'second'].some(k => o[k]);+ if (!has) o = Object.assign({}, o, { year: 'numeric', month: 'numeric', day: 'numeric' });+ const parts = []; let date = '';+ if (o.year || o.month || o.day || o.weekday) {+ const y = o.year ? (o.year === '2-digit' ? pad(G('FullYear') % 100) : String(G('FullYear'))) : '', dd = o.day ? (o.day === '2-digit' ? pad(G('Date')) : String(G('Date'))) : '', wd = o.weekday ? (o.weekday === 'long' ? DAYS[G('Day')] : DAYS[G('Day')].slice(0, 3)) : '';+ if (o.month === 'long' || o.month === 'short' || o.month === 'narrow') { const m = o.month === 'long' ? MONTHS[G('Month')] : MONTHS[G('Month')].slice(0, o.month === 'short' ? 3 : 1); date = (wd ? wd + ', ' : '') + [m, dd].filter(Boolean).join(' ') + (y ? (dd ? ', ' : ' ') + y : ''); }+ else { const m = o.month ? (o.month === '2-digit' ? pad(G('Month') + 1) : String(G('Month') + 1)) : ''; date = (wd ? wd + (m || dd || y ? ', ' : '') : '') + [m, dd, y].filter(Boolean).join('/'); }+ }+ let time = '';+ if (o.hour || o.minute || o.second) {+ const h24 = G('Hours'), h12 = o.hour12 !== false && !(o.hourCycle === 'h23') && !/^(de|fr|ru|es|it|pt|ja|zh|ko)/.test(this.l), h = h12 ? (h24 % 12 || 12) : h24, t = [];+ if (o.hour) t.push(o.hour === '2-digit' || !h12 ? pad(h) : String(h)); if (o.minute) t.push(pad(G('Minutes'))); if (o.second) t.push(pad(G('Seconds')));+ time = t.join(':') + (o.hour && h12 ? (h24 < 12 ? ' AM' : ' PM') : '');+ }+ return [date, time].filter(Boolean).join(', ');+ }+ formatToParts(d) { return [{ type: 'literal', value: this.format(d) }]; }+ formatRange(a, b) { return this.format(a) + ' – ' + this.format(b); }+}+const CUR = { USD: '$', EUR: '€', GBP: '£', JPY: '¥', RUB: '₽', INR: '₹', CNY: '¥', KRW: '₩' };+class NumberFormat {+ constructor(l, o) { this.l = (Array.isArray(l) ? l[0] : l) || 'en-US'; this.o = o || {}; }+ resolvedOptions() { return Object.assign({ locale: this.l, numberingSystem: 'latn', style: 'decimal' }, this.o); }+ format(n) {+ n = Number(n); const o = this.o, cur = o.style === 'currency', pct = o.style === 'percent';+ if (!isFinite(n)) return isNaN(n) ? 'NaN' : (n < 0 ? '-∞' : '∞');+ if (pct) n *= 100;+ let min = o.minimumFractionDigits, max = o.maximumFractionDigits; if (min === undefined) min = cur ? 2 : 0; if (max === undefined) max = Math.max(min, cur ? 2 : pct ? 0 : 3);+ let suffix = ''; if (o.notation === 'compact') { for (const [v, s] of [[1e12, 'T'], [1e9, 'B'], [1e6, 'M'], [1e3, 'K']]) if (Math.abs(n) >= v) { n /= v; suffix = s; break; } max = o.maximumFractionDigits === undefined ? (Math.abs(n) < 100 && suffix ? 1 : 0) : max; min = 0; }+ let [i, f = ''] = Math.abs(n).toFixed(Math.min(max, 20)).split('.'); while (f.length > min && f.endsWith('0')) f = f.slice(0, -1);+ if (o.minimumIntegerDigits) i = i.padStart(o.minimumIntegerDigits, '0');+ if (o.useGrouping !== false && !(o.notation === 'compact')) i = i.replace(/\B(?=(\d{3})+(?!\d))/g, ',');+ return (n < 0 && (i !== '0' || f) ? '-' : '') + (cur ? (CUR[o.currency] || (o.currency || '') + ' ') : '') + i + (f ? '.' + f : '') + suffix + (pct ? '%' : '');+ }+ formatToParts(n) { return [{ type: 'literal', value: this.format(n) }]; }+}+class Collator { constructor(l, o) { this.o = o || {}; } compare = (a, b) => { a = String(a); b = String(b); if (this.o.sensitivity === 'base' || this.o.sensitivity === 'accent') { a = a.toLowerCase(); b = b.toLowerCase(); } if (this.o.numeric) { const na = parseFloat(a), nb = parseFloat(b); if (!isNaN(na) && !isNaN(nb) && na !== nb) return na < nb ? -1 : 1; } return a.localeCompare(b); }; resolvedOptions() { return Object.assign({ locale: 'en-US' }, this.o); } }+class PluralRules { constructor(l, o) { this.o = o || {}; } select(n) { if (this.o.type === 'ordinal') { const a = n % 10, b = n % 100; return a === 1 && b !== 11 ? 'one' : a === 2 && b !== 12 ? 'two' : a === 3 && b !== 13 ? 'few' : 'other'; } return n === 1 ? 'one' : 'other'; } resolvedOptions() { return { locale: 'en-US' }; } }+class RelativeTimeFormat { constructor(l, o) { this.o = o || {}; } format(v, unit) { const a = Math.abs(v), s = a + ' ' + String(unit).replace(/s$/, '') + (a === 1 ? '' : 's'); return v < 0 || Object.is(v, -0) ? s + ' ago' : 'in ' + s; } }+class ListFormat { constructor(l, o) { this.o = o || {}; } format(a) { a = Array.from(a); const w = this.o.type === 'disjunction' ? 'or' : 'and'; return a.length < 3 ? a.join(' ' + w + ' ') : a.slice(0, -1).join(', ') + ', ' + w + ' ' + a[a.length - 1]; } }+class Segmenter { constructor(l, o) { this.o = o || {}; } segment(s) { const w = this.o.granularity === 'word'; const parts = w ? String(s).match(/\s+|[\p{L}\p{N}_']+|[^\s\p{L}\p{N}_']/gu) || [] : Array.from(String(s)); let i = 0; return parts.map(p => { const r = { segment: p, index: i, input: s, isWordLike: w ? /[\p{L}\p{N}]/u.test(p) : undefined }; i += p.length; return r; }); } }+const callable = C => { const F = function (...a) { return new C(...a); }; F.prototype = C.prototype; return F; }; // Intl.NumberFormat() works without `new`+const Intl = { DateTimeFormat: callable(DateTimeFormat), NumberFormat: callable(NumberFormat), Collator: callable(Collator), PluralRules, RelativeTimeFormat, ListFormat, Segmenter, getCanonicalLocales: l => [].concat(l || []), supportedValuesOf: () => [] };+Object.assign(g, {+ // no DOMParser: DOMPurify (Swagger UI) switches itself off when it is missing, but breaks on a partial one+ Comment, CharacterData: Text, XMLSerializer, Range, TreeWalker, NodeFilter, ReadableStream, WritableStream, TransformStream, MessageChannel, MessagePort, BroadcastChannel, FileReader, Request,+ DOMRect, DOMRectReadOnly: DOMRect, DOMPoint, PerformanceObserver, CSSStyleSheet, HTMLDocument: Document, XMLDocument: Document, Intl,+ Audio: function (src) { const a = document.createElement('audio'); if (src) a.setAttribute('src', src); return a; },+ Option: function (text, value) { const o = document.createElement('option'); if (text !== undefined) o.textContent = text; if (value !== undefined) o.setAttribute('value', value); return o; },+ postMessage(d) { g.setTimeout(() => { const e = new Event('message'); e.data = d; e.origin = loc.origin; e.source = g; g.dispatchEvent(e); }, 0); },+ visualViewport: { width: 1000, height: 720, scale: 1, offsetLeft: 0, offsetTop: 0, pageLeft: 0, pageTop: 0, addEventListener: noop, removeEventListener: noop },+ reportError: noop, name: '', closed: false, opener: null, frameElement: null,+});+for (const n of ['DOMTokenList', 'NamedNodeMap', 'CSSStyleDeclaration', 'CSSRule', 'StyleSheet', 'MediaQueryList', 'Attr', 'PerformanceEntry']) if (!(n in g)) g[n] = class {};+for (const n of ['UIEvent', 'CloseEvent', 'AnimationEvent', 'TransitionEvent', 'PromiseRejectionEvent']) if (!(n in g)) g[n] = class extends Event {};+Object.defineProperty(g, 'isSecureContext', { get: () => loc.protocol === 'https:', configurable: true });+Object.defineProperty(g, 'origin', { get: () => loc.origin, configurable: true });+Object.assign(g.navigator, {+ appVersion: '5.0 (Windows NT 10.0; Win64; x64) chrome-rs/0.1', appName: 'Netscape', appCodeName: 'Mozilla', product: 'Gecko', hardwareConcurrency: 4, maxTouchPoints: 0, deviceMemory: 8, webdriver: false, doNotTrack: null,+ plugins: [], mimeTypes: [], vibrate: () => false, javaEnabled: () => false,+ clipboard: { writeText: () => Promise.resolve(), readText: () => Promise.resolve('') },+ connection: { effectiveType: '4g', downlink: 10, rtt: 50, saveData: false, addEventListener: noop, removeEventListener: noop },+ permissions: { query: () => Promise.resolve({ state: 'denied', addEventListener: noop }) },+});+// `'onhashchange' in window` gates Backbone's iframe fallback; an <iframe> gets an empty document of its own (jQuery and Backbone only write into it)+g.onhashchange = null;+// real DOM objects have `onclick`, `oninput`... as null properties; React tests `'oninput' in document` and falls back to an IE polyfill (that crashes) without it+for (const t of 'click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave contextmenu wheel keydown keyup keypress input change beforeinput focus blur focusin focusout submit reset select scroll resize load error abort toggle copy cut paste pointerdown pointerup pointermove pointerover pointerout pointercancel dragstart dragend dragover drop animationend transitionend invalid'.split(' ')) {+ for (const o of [Element.prototype, Document.prototype]) if (!('on' + t in o)) Object.defineProperty(o, 'on' + t, { value: null, writable: true, configurable: true });+ if (!('on' + t in g)) g['on' + t] = null;+}+Object.defineProperties(Element.prototype, {+ contentDocument: { get() { if (this.localName !== 'iframe') return null; return this._cd || (this._cd = document.implementation.createHTMLDocument('')); }, configurable: true },+ contentWindow: { get() { if (this.localName !== 'iframe') return null; return this._cw || (this._cw = { document: this.contentDocument, location: { href: 'about:blank', hash: '', replace() {} }, addEventListener() {}, removeEventListener() {}, postMessage() {}, parent: g, top: g }); }, configurable: true },+});+// all zeros: pages subtract these from each other for load timings+g.performance.timing = Object.fromEntries(['navigationStart', 'fetchStart', 'requestStart', 'responseStart', 'responseEnd', 'domLoading', 'domInteractive', 'domContentLoadedEventStart', 'domContentLoadedEventEnd', 'domComplete', 'loadEventStart', 'loadEventEnd'].map(k => [k, 0]));+g.performance.getEntries = () => [];+g.performance.mark = n => ({ name: String(n), entryType: 'mark', startTime: g.performance.now(), duration: 0 });+g.performance.measure = n => ({ name: String(n), entryType: 'measure', startTime: 0, duration: 0 });++for (const k of ['addEventListener', 'removeEventListener', 'dispatchEvent']) g[k] = EventTarget.prototype[k].bind(g);++// Virtual time: runs the next timer without waiting (Rust drains promise jobs in between). `live` keeps timers beyond the first+// second queued (they run later in real time via __run_due) instead of dropping them.+const runTimer = x => {+ ran++;+ try { if (typeof x.f === 'function') x.f(...x.a); } catch (e) { __log('timer: ' + (e && (e.message + ' ' + e.stack) || e)); }+ const dead = cleared.delete(x.id);+ if (x.every && !dead && (x.live || ++x.n < 3)) { x.t = now + x.every; timers.push(x); }+};+g.__tick = live => {+ if (!timers.length) return false;+ timers.sort((a, b) => a.t - b.t || a.id - b.id);+ const x = timers[0];+ if (x.t > (live ? 1000 : 5000)) { if (!live) timers = []; return false; }+ timers.shift();+ now = Math.max(now, x.t);+ x.live = !!live;+ runTimer(x);+ return timers.length > 0;+};+// Real time: runs every timer due at clock `t` (ms); returns the delay until the next one, or -1.+g.__run_due = t => {+ if (t > now) now = t;+ for (let k = 0; k < 100; k++) {+ timers.sort((a, b) => a.t - b.t || a.id - b.id);+ const x = timers[0];+ if (!x || x.t > now) break;+ timers.shift();+ x.live = true;+ runTimer(x);+ }+ return g.__next_delay();+};+g.__next_delay = () => timers.length ? Math.max(0, Math.min(...timers.map(x => x.t)) - now) : -1;+g.__setnow = t => { if (t > now) now = t; };+g.__now = () => now;+g.__ran = () => { const r = ran; ran = 0; return r; };+g.__fire = type => {+ if (type === 'DOMContentLoaded') document.readyState = 'interactive';+ if (type === 'load') document.readyState = 'complete';+ (type === 'load' ? g : document).dispatchEvent(new Event(type, { bubbles: type !== 'load' }));+};+g.__ls_dump = () => JSON.stringify(lsData);+// composed children of a node: a shadow host shows its shadow tree, a <slot> shows the host's nodes assigned to it (or its own fallback content)+const slotted = (slot, host) => { const nm = slot._a.name || ''; return host.childNodes.filter(c => c.nodeType === 3 ? nm === '' : (c.nodeType === 1 ? (c._a.slot || '') === nm : false)); };+const composed = n => {+ const out = [];+ // constructable stylesheets adopted by a shadow root become <style> elements at its start (applied page-wide, like its own <style> children)+ if (n._sr) for (const sh of n._sr.adoptedStyleSheets || []) if (sh && sh._text) { const st = new Element('style'); st.appendChild(new Text(sh._text)); out.push(st); }+ for (const c of (n._sr || n).childNodes) {+ if (c.nodeType === 1 && c.localName === 'slot') { // a <slot> inside a shadow tree shows the nodes its host assigned to it+ let r = c; while (r.parentNode) r = r.parentNode;+ if (r.nodeType === 11 && r.host) { const a = slotted(c, r.host); out.push(...composed({ childNodes: a.length ? a : c.childNodes })); continue; }+ }+ out.push(c);+ }+ return out;+};+let ids = []; // elements/text nodes in the order of the last serialization: Rust node id N is ids[N - 1]+g.__serialize = () => {+ ids = [];+ const s = n => { ids.push(n); return n.nodeType === 3 ? n.data : n.nodeType === 8 ? { m: n.data } : { t: n.localName, a: n._a, c: composed(n).filter(c => c.nodeType === 1 || c.nodeType === 3 || c.nodeType === 8).map(s) }; };+ return JSON.stringify(s(document.documentElement));+};+const EVT = { click: 'MouseEvent', dblclick: 'MouseEvent', mousedown: 'MouseEvent', mouseup: 'MouseEvent', keydown: 'KeyboardEvent', keyup: 'KeyboardEvent', keypress: 'KeyboardEvent', input: 'InputEvent', focus: 'FocusEvent', blur: 'FocusEvent', submit: 'SubmitEvent', scroll: 'Event' };+// UI -> page: dispatch an event at a node of the last serialization; true when a handler called preventDefault()+g.__dispatch = (node, type, init) => {+ const el = node === 0 ? g : ids[node - 1];+ if (!el) return false;+ ran++;+ const o = Object.assign({ bubbles: type !== 'focus' && type !== 'blur', cancelable: true }, init ? JSON.parse(init) : {});+ const e = new (g[EVT[type]] || Event)(type, o);+ el.dispatchEvent(e);+ return e.defaultPrevented;+};+g.__setvalue = (node, v, checked) => {+ const el = ids[node - 1];+ if (!el || el.nodeType !== 1) return;+ if (checked !== null) el.checked = checked; else el.value = v;+};+g.__scrolled = y => { g.scrollY = y; g.pageYOffset = y; g.dispatchEvent(new Event('scroll')); };+g.__resize = (w, h) => { g.innerWidth = w; g.innerHeight = h; g.outerWidth = w; g.outerHeight = h; g.dispatchEvent(new Event('resize')); };+g.__boxes = list => { for (const [id, x, y, w, h] of list) { const el = ids[id - 1]; if (el && el.nodeType === 1) el._box = [x, y, w, h]; } };+// fill the intermediate prototype with the accessors (not the methods: pages polyfill those on Element.prototype and must still win)+for (const k of Reflect.ownKeys(Element.prototype)) { const d = Object.getOwnPropertyDescriptor(Element.prototype, k); if (k !== 'constructor' && d.set) Object.defineProperty(HTMLProto, k, d); }+Object.setPrototypeOf(HTMLElement.prototype, HTMLProto);+})(globalThis);diff --git a/plugins/chrome-rs/src/render.rs b/plugins/chrome-rs/src/render.rsnew file mode 100644index 0000000..42b8c67--- /dev/null+++ b/plugins/chrome-rs/src/render.rs@@ -0,0 +1,822 @@+// Styled DOM -> flat stream of words and breaks that the layout in main.rs flows into lines.+use crate::css::{self, BgSize, Grad, Len, Shadow, Sheet, Style, Track};+use std::sync::Arc;+use crate::dom::Dom;+use crate::load::Img;+use std::collections::HashMap;++const MAX_IMG_CSS_W: f32 = 900.0;++pub enum Item {+ Word { text: String, size: f32, color: u32, bold: bool, italic: bool, fam: u16, ul: bool, mono: bool, link: Option<usize>, space: bool, indent: f32, align: u8, lh: f32, node: usize, ls: f32, dy: f32 },+ /// Inline picture (index into Page::images) at display size w x h in CSS px.+ Image { img: usize, w: f32, h: f32, link: Option<usize>, indent: f32, align: u8, node: usize, va: u8, alpha: f32,+ /// CSS `width: N%`: the layout makes the picture N% of the line and keeps the proportions of `w` x `h`+ pct: Option<f32> },+ /// Form control (index into Page::fields): box of w x h CSS px, `size` = font size.+ Field { idx: usize, w: f32, h: f32, indent: f32, align: u8, node: usize },+ /// Line break plus a vertical gap in px (gaps between consecutive breaks collapse to the largest).+ Break(f32),+ /// Block box (margins, padding, width limits, background) around everything up to the matching BoxEnd.+ Box(BoxSpec),+ BoxEnd,+ /// Table laid out in columns (see layout.rs).+ Table(Box<Table>),+ /// Content that floats to the left/right edge; following lines wrap around it.+ Float(Box<FloatSpec>),+ /// `clear`: continue below floats (bit 0 = left, bit 1 = right).+ Clear(u8),+ /// Horizontal rule in the given color.+ Rule(u32),+ /// `display:inline-block`: laid out as its own block, then placed on the line as one atom (`right` unused).+ InlineBlock(Box<FloatSpec>),+ /// Row flex container.+ Flex(Box<FlexSpec>),+ /// `position:absolute` content, placed against the nearest positioned ancestor (or the page); takes no space in the flow.+ Abs(Box<AbsSpec>),+ /// `position:relative` block: offsets (top, right, bottom, left) shift everything up to the matching RelEnd.+ RelStart([Option<Len>; 4], i32, bool),+ RelEnd,+ /// `display:grid`: children placed in rows over the template's columns.+ Grid(Box<GridSpec>),+}++/// A `background-image: url()` that was downloaded: index into `Page::images`, natural size (CSS px) and how it is placed.+pub struct BgPaint { pub img: usize, pub nw: f32, pub nh: f32, pub size: BgSize, pub pos: [Len; 2], pub repeat: (bool, bool) }++pub struct GridSpec { pub items: Vec<FlexItem>, pub tracks: Vec<Track>, pub auto_min: Option<f32>, pub col_gap: f32, pub row_gap: f32 }++pub struct FlexItem {+ pub items: Vec<Item>, pub grow: f32, pub shrink: f32, pub basis: Option<Len>, pub width: Option<Len>, pub max_width: Option<Len>,+ pub auto_l: bool, pub auto_r: bool, pub align: u8, pub span: usize,+}+pub struct FlexSpec { pub items: Vec<FlexItem>, pub wrap: bool, pub gap: f32, pub justify: u8, pub align: u8, pub col: bool }+pub struct AbsSpec { pub items: Vec<Item>, pub off: [Option<Len>; 4], pub width: Option<Len>, pub max_width: Option<Len>, pub fixed: bool, pub z: i32 }++pub struct FloatSpec { pub right: bool, pub width: Option<Len>, pub max_width: Option<Len>, pub items: Vec<Item> }++#[derive(Clone)]+pub struct BoxSpec {+ pub ml: f32, pub mr: f32, pub pl: f32, pub pr: f32, pub width: Option<Len>, pub max_width: Option<Len>,+ pub auto_l: bool, pub auto_r: bool, pub bg: Option<u32>,+ pub pt: f32, pub pb: f32, // vertical padding inside the box (CSS px)+ pub scroll: bool, // scroll container: overflow auto|scroll with a fixed height+ pub bgimg: Option<Arc<BgPaint>>,+ pub bg_a: f32, pub clip: bool, pub shadow: Option<Shadow>, pub grad: Option<Arc<Grad>>,+ pub bb: bool, pub min_h: f32, pub radius: f32, pub node: usize,+ pub borders: [Option<(f32, u32)>; 4], // top, right, bottom, left+}++pub struct Table { pub rows: Vec<Row>, pub width: Option<Len>, pub border: f32, pub spacing: f32, pub bg: Option<u32>, pub align: u8 }+pub struct Row { pub cells: Vec<Cell>, pub bg: Option<u32> }+pub struct Cell {+ pub items: Vec<Item>, pub colspan: usize, pub width: Option<Len>, pub bg: Option<u32>,+ pub pad: [f32; 4], // top, right, bottom, left (CSS px)+ pub valign: u8, pub nowrap: bool, pub rowspan: usize,+}++#[derive(Clone, Copy, PartialEq, Debug, Default)]+pub enum FieldKind { #[default] Text, Password, Submit, Hidden, Check, Radio, TextArea, Select }++#[derive(Clone, Default)]+pub struct Field {+ pub form: Option<usize>, pub name: String, pub value: String, pub label: String, pub placeholder: String,+ pub kind: FieldKind, pub checked: bool, pub fs: f32,+ /// value / checked state as parsed (the page's own); used to tell user edits from script changes after a live update+ pub initial: String, pub initial_checked: bool,+ /// DOM node of the control (a `<label>` click is routed here)+ pub node: usize,+ /// Select only: (value, label) per option and the chosen index.+ pub options: Vec<(String, String)>, pub sel: usize,+}++pub struct Form { pub action: String, pub post: bool, pub node: usize }++/// A downloaded web font: decoded TTF/OTF bytes for family id `fam`.+pub struct WebFont { pub fam: u16, pub bold: bool, pub italic: bool, pub data: Vec<u8> }++#[derive(Default)]+pub struct Page {+ pub items: Vec<Item>, pub links: Vec<String>, pub title: String, pub bg: u32, pub images: Vec<Img>,+ pub forms: Vec<Form>, pub fields: Vec<Field>,+ /// `@font-face` rules of the page and the fonts downloaded for them (filled in by the loader)+ pub faces: Vec<css::FontFaceRule>, pub webfonts: Vec<WebFont>,+ /// DOM parent of every node id, the `<body>` node, and the live script session (when scripts may keep running)+ pub parents: Vec<usize>, pub body: usize, pub live: Option<crate::js::Handle>,+ /// What a restyle needs (only for pages whose CSS uses :hover/:active/:focus)+ pub restyle: Option<Arc<Restyle>>,+}++pub struct Restyle { pub dom: Dom, pub imgs: HashMap<usize, Img>, pub base: String }++struct Ctx<'a> {+ dom: &'a Dom,+ sheet: Sheet,+ base: &'a str,+ items: Vec<Item>,+ links: Vec<String>,+ link: Option<usize>,+ pending_space: bool,+ bg: Option<u32>,+ bg_stack: Vec<u32>,+ imgs: HashMap<usize, Img>,+ images: Vec<Img>,+ forms: Vec<Form>,+ fields: Vec<Field>,+ cur_form: Option<usize>,+ indent: f32, // text-indent waiting for the first word of the block+ node: usize, // DOM node being walked (events target it)+ cb_h: Option<f32>, // definite height of the containing block (CSS px), for percentage heights+ counters: Vec<(String, i32)>, // CSS counters in scope (innermost last)+ glob: HashMap<String, i32>, // counters incremented without a counter-reset+}++/// `c` shown at `alpha` over `bg`.+fn mix(c: u32, bg: u32, alpha: f32) -> u32 {+ let ch = |sh: u32| (((c >> sh & 255) as f32 * alpha + (bg >> sh & 255) as f32 * (1.0 - alpha)).round() as u32).min(255) << sh;+ ch(16) | ch(8) | ch(0)+}++fn backdrop(cx: &Ctx) -> u32 { cx.bg_stack.last().copied().or(cx.bg).unwrap_or(0xFFFFFF) }++fn lum(c: u32) -> f32 { 0.299 * (c >> 16 & 255) as f32 + 0.587 * (c >> 8 & 255) as f32 + 0.114 * (c & 255) as f32 }++fn sheets_of(dom: &Dom) -> Vec<String> {+ let mut sheets = vec![css::UA.to_string()];+ for id in dom.descendants() {+ let n = &dom.nodes[id];+ if n.tag == "style" && !dom.attr(id, "media").is_some_and(|m| m.contains("print")) { sheets.push(dom.text_content(id)); }+ }+ sheets+}++/// Elements whose computed `background-image` is a `url()`, with the absolute address (the loader downloads these).+pub fn background_urls(dom: &Dom, base: &str) -> Vec<(usize, String)> {+ let sheets = sheets_of(dom);+ let styled = dom.nodes.iter().any(|n| n.attrs.iter().any(|(k, v)| k == "style" && v.contains("url(")));+ if !styled && !sheets.iter().any(|s| s.contains("url(")) { return vec![]; }+ let sheet = Sheet::new(&sheets);+ let root = Style::root();+ dom.descendants().into_iter().filter(|&i| !dom.nodes[i].tag.is_empty()).filter_map(|i| {+ let u = css::compute(dom, &sheet, i, &root).bg_img?.url;+ Some((i, if u.starts_with("data:") { u } else { resolve(base, &u) }))+ }).take(24).collect()+}++/// Rebuilds the item stream of a page after :hover/:active/:focus state changed (see `css::set_state`).+pub fn restyled(src: &Restyle) -> Page { build(&src.dom, &src.base, src.imgs.clone()) }++pub fn build(dom: &Dom, base: &str, imgs: HashMap<usize, Img>) -> Page {+ // layout never sees comment nodes (they only exist for scripts)+ let stripped;+ let dom = if dom.has_comments() { let mut d = dom.clone(); d.strip_comments(); stripped = d; &stripped } else { dom };+ let sheet = Sheet::new(&sheets_of(dom));+ let keep = sheet.has_state.then(|| Arc::new(Restyle { dom: dom.clone(), imgs: imgs.clone(), base: base.to_string() }));+ let mut cx = Ctx { dom, sheet, base, items: vec![], links: vec![], link: None, pending_space: false, bg: None, bg_stack: vec![], imgs, images: vec![], forms: vec![], fields: vec![], cur_form: None, indent: 0.0, node: 0, cb_h: Some(720.0), counters: vec![], glob: HashMap::new() };+ if let Some(&html) = dom.nodes[0].kids.first() { walk(&mut cx, html, &Style::root(), false); }+ let title = dom.find("title").map(|t| dom.text_content(t).split_whitespace().collect::<Vec<_>>().join(" ")).unwrap_or_default();+ Page { items: cx.items, links: cx.links, title, bg: cx.bg.unwrap_or(0xFFFFFF), images: cx.images, forms: cx.forms, fields: cx.fields, faces: cx.sheet.faces.clone(), webfonts: vec![], parents: dom.nodes.iter().map(|n| n.parent).collect(), body: dom.find("body").unwrap_or(0), live: None, restyle: keep }+}++/// Registers a form control and (unless hidden) places it inline.+fn field(cx: &mut Ctx, id: usize, s: &Style) {+ let dom = cx.dom;+ let a = |n: &str| dom.attr(id, n).unwrap_or("").to_string();+ let ty = a("type").to_ascii_lowercase();+ let tag = dom.nodes[id].tag.as_str();+ let (kind, label) = if tag == "button" {+ (FieldKind::Submit, dom.text_content(id).split_whitespace().collect::<Vec<_>>().join(" "))+ } else if tag == "select" {+ (FieldKind::Select, String::new())+ } else if tag == "textarea" {+ (FieldKind::TextArea, String::new())+ } else {+ match ty.as_str() {+ "hidden" => (FieldKind::Hidden, String::new()),+ "password" => (FieldKind::Password, String::new()),+ "submit" | "button" | "reset" | "image" => (FieldKind::Submit, a("value")),+ "checkbox" => (FieldKind::Check, String::new()),+ "radio" => (FieldKind::Radio, String::new()),+ "file" | "range" | "color" | "date" | "datetime-local" | "time" | "month" | "week" => return,+ _ => (FieldKind::Text, String::new()),+ }+ };+ // Plain buttons and resets do nothing without scripting, so they are not tied to the form.+ let inert = matches!(ty.as_str(), "button" | "reset") && tag != "button" || tag == "button" && ty == "button" || ty == "reset";+ // icon-only buttons (no text) cannot be drawn meaningfully, so they are skipped+ if tag == "button" && label.is_empty() { return; }+ let label = if kind == FieldKind::Submit && label.is_empty() { "Submit".into() } else { label };+ let mut options = vec![];+ let mut sel = 0;+ if kind == FieldKind::Select {+ let mut st = vec![id];+ let mut order = vec![];+ while let Some(i) = st.pop() { order.push(i); st.extend(dom.nodes[i].kids.iter().rev()); }+ for o in order.into_iter().filter(|&o| dom.nodes[o].tag == "option") {+ let text = dom.text_content(o).split_whitespace().collect::<Vec<_>>().join(" ");+ if dom.attr(o, "selected").is_some() { sel = options.len(); }+ options.push((dom.attr(o, "value").map_or_else(|| text.clone(), String::from), text));+ }+ }+ let value = match kind {+ FieldKind::Submit if tag != "button" && ty != "image" => String::new(),+ FieldKind::TextArea => dom.text_content(id).strip_prefix('\n').map_or_else(|| dom.text_content(id), String::from),+ FieldKind::Select => options.get(sel).map(|o| o.0.clone()).unwrap_or_default(),+ _ => a("value"),+ };+ let max_opt = options.iter().map(|o| o.1.chars().count()).max().unwrap_or(4) as f32;+ cx.fields.push(Field {+ form: cx.cur_form.filter(|_| !inert), name: a("name"), initial: value.clone(), value, label: label.clone(), placeholder: a("placeholder"), kind,+ checked: dom.attr(id, "checked").is_some(), fs: s.size, node: id, initial_checked: dom.attr(id, "checked").is_some(), options, sel,+ });+ let idx = cx.fields.len() - 1;+ let size = s.size;+ let (w, h) = match kind {+ FieldKind::Hidden => return,+ FieldKind::Check | FieldKind::Radio => (size * 1.1, size * 1.1),+ FieldKind::Select => ((max_opt * size * 0.55 + 40.0).clamp(80.0, 400.0), size * 1.6),+ FieldKind::TextArea => {+ let n = |k: &str, d: f32| dom.attr(id, k).and_then(|v| v.parse::<f32>().ok()).filter(|&c| c > 0.0).unwrap_or(d);+ ((n("cols", 20.0) * size * 0.55 + 12.0).clamp(100.0, 700.0), n("rows", 3.0).min(20.0) * size * 1.35 + 10.0)+ }+ FieldKind::Submit => (label.chars().count() as f32 * size * 0.58 + 24.0, size * 1.6),+ _ => {+ let chars = dom.attr(id, "size").and_then(|v| v.parse::<f32>().ok()).filter(|&c| c > 0.0).unwrap_or(20.0);+ ((chars * size * 0.55 + 12.0).clamp(60.0, 500.0), size * 1.6)+ }+ };+ cx.items.push(Item::Field { idx, w, h, indent: 0.0, align: s.align, node: id });+ cx.pending_space = true;+}++fn word(cx: &mut Ctx, text: &str, s: &Style, space: bool) {+ let text = &match s.tt {+ 1 => text.to_uppercase(),+ 2 => text.to_lowercase(),+ 3 => { let mut c = text.chars(); c.next().map(|f| f.to_uppercase().chain(c).collect()).unwrap_or_default() }+ _ => text.to_string(),+ };+ // Text must stay readable on whatever box it sits in (our backgrounds and the author's colors may disagree).+ let bg = cx.bg_stack.last().copied().or(cx.bg).unwrap_or(0xFFFFFF);+ let mut color = if (lum(s.color) - lum(bg)).abs() < 60.0 { if lum(bg) > 128.0 { 0x111111 } else { 0xEEEEEE } } else { s.color };+ if s.alpha < 1.0 { color = mix(color, bg, s.alpha); }+ cx.items.push(Item::Word { text: text.into(), size: s.size, color, bold: s.bold, italic: s.italic, fam: s.fam, ul: s.underline, mono: s.mono, link: cx.link, space, indent: std::mem::take(&mut cx.indent), align: s.align, lh: s.lh, node: cx.node, ls: s.ls, dy: s.x.va });+}++/// Splits a space-free run at the break opportunities of UAX #14 (after hyphens and slashes, between CJK characters+/// with the kinsoku rules for closing and opening punctuation, after soft hyphens); each piece is laid out as its own word.+fn split_cjk(w: &str) -> Vec<&str> {+ if w.bytes().all(|b| b.is_ascii_alphanumeric()) { return vec![w]; }+ let (mut out, mut start) = (vec![], 0);+ for (at, op) in unicode_linebreak::linebreaks(w) {+ if at < w.len() && op == unicode_linebreak::BreakOpportunity::Allowed && at > start { out.push(&w[start..at]); start = at; }+ }+ if start < w.len() { out.push(&w[start..]); }+ out+}++fn len_attr(v: Option<&str>) -> Option<Len> {+ let v = v?.trim();+ match v.strip_suffix('%') {+ Some(p) => p.trim().parse().ok().map(Len::Pct),+ None => v.trim_end_matches("px").trim().parse().ok().map(Len::Px),+ }+}++fn collect_rows(dom: &Dom, id: usize, out: &mut Vec<usize>) {+ for &k in &dom.nodes[id].kids {+ match dom.nodes[k].tag.as_str() {+ "tr" | "caption" => out.push(k),+ "thead" | "tbody" | "tfoot" => collect_rows(dom, k, out),+ _ => {}+ }+ }+}++/// Builds a Table item: every cell's content is walked into its own item list.+fn table(cx: &mut Ctx, id: usize, s: &Style, parent: &Style) {+ let dom = cx.dom;+ let num = |n: &str, d: f32| dom.attr(id, n).and_then(|v| v.trim().parse::<f32>().ok()).unwrap_or(d);+ let cellpad = num("cellpadding", 1.0).clamp(0.0, 40.0);+ let spacing = if s.collapse { 0.0 } else { num("cellspacing", 2.0).clamp(0.0, 40.0) };+ let border = dom.attr(id, "border").map_or(0.0, |v| v.trim().parse::<f32>().unwrap_or(1.0));+ let width = s.width.or_else(|| len_attr(dom.attr(id, "width")));+ let align = match dom.attr(id, "align").map(str::to_ascii_lowercase).as_deref() { Some("center") => 1, Some("right") => 2, Some("left") => 0, _ => parent.align };+ if let Some(b) = s.bg { cx.bg_stack.push(b); }+ let mut row_ids = vec![];+ collect_rows(dom, id, &mut row_ids);+ let mut rows = vec![];+ for r in row_ids {+ let rs = css::compute(dom, &cx.sheet, r, s);+ if rs.none { continue; }+ let mut cells = vec![];+ let cell_nodes: Vec<usize> = if dom.nodes[r].tag == "caption" { vec![r] } else { dom.nodes[r].kids.iter().copied().filter(|&c| matches!(dom.nodes[c].tag.as_str(), "td" | "th")).collect() };+ for c in cell_nodes {+ let cs = if c == r { rs.clone() } else { css::compute(dom, &cx.sheet, c, &rs) };+ if cs.none { continue; }+ let eff = cs.bg.or(rs.bg);+ if let Some(b) = eff { cx.bg_stack.push(b); }+ let saved = std::mem::take(&mut cx.items);+ cx.pending_space = false;+ for &k in &dom.nodes[c].kids { walk(cx, k, &cs, false); }+ let items = std::mem::replace(&mut cx.items, saved);+ cx.pending_space = false;+ if eff.is_some() { cx.bg_stack.pop(); }+ let valign = match dom.attr(c, "valign").map(str::to_ascii_lowercase).as_deref() { Some("middle") => 1, Some("bottom") => 2, Some("top") => 0, _ => cs.valign };+ cells.push(Cell {+ items,+ colspan: if c == r { 1000 } else { dom.attr(c, "colspan").and_then(|v| v.trim().parse::<usize>().ok()).unwrap_or(1).clamp(1, 64) },+ width: cs.width.or_else(|| len_attr(dom.attr(c, "width"))),+ bg: cs.bg,+ pad: if cs.pad_set { cs.pad } else { [cellpad; 4] },+ valign,+ nowrap: dom.attr(c, "nowrap").is_some(),+ rowspan: if c == r { 1 } else { dom.attr(c, "rowspan").and_then(|v| v.trim().parse::<usize>().ok()).unwrap_or(1).clamp(1, 64) },+ });+ }+ rows.push(Row { cells, bg: rs.bg });+ }+ if s.bg.is_some() { cx.bg_stack.pop(); }+ cx.items.push(Item::Break(s.mt));+ cx.items.push(Item::Table(Box::new(Table { rows, width, border, spacing, bg: s.bg, align })));+ cx.items.push(Item::Break(s.mb));+ cx.pending_space = false;+}++fn px_attr(dom: &Dom, id: usize, name: &str) -> Option<f32> { dom.attr(id, name)?.trim().trim_end_matches("px").parse().ok().filter(|&v: &f32| v > 0.0) }++fn walk(cx: &mut Ctx, id: usize, parent: &Style, forced_inline: bool) {+ let dom = cx.dom;+ cx.node = id;+ let n = &dom.nodes[id];+ if n.tag.is_empty() {+ if parent.pre {+ // preformatted: every source line is one unwrapped run with its spaces kept+ let text = n.text.replace('\t', " ");+ let lines: Vec<&str> = text.trim_end_matches('\n').split('\n').collect();+ for (i, l) in lines.iter().enumerate() {+ if i > 0 { cx.items.push(Item::Break(0.0)); }+ if !l.is_empty() { word(cx, l, parent, false); }+ }+ return;+ }+ if n.text.trim().is_empty() { cx.pending_space |= !n.text.is_empty(); return; }+ let mut space = cx.pending_space || n.text.starts_with(char::is_whitespace);+ if parent.nowrap {+ // nowrap: the whole text node is one unbreakable word+ word(cx, &n.text.split_whitespace().collect::<Vec<_>>().join(" "), parent, space);+ } else {+ for w in n.text.split_whitespace() {+ for (k, piece) in split_cjk(w).into_iter().enumerate() { word(cx, piece, parent, space && k == 0); }+ space = true;+ }+ }+ cx.pending_space = n.text.ends_with(char::is_whitespace);+ return;+ }+ let s = css::compute(dom, &cx.sheet, id, parent);+ if s.none { return; }+ if s.clear != 0 { cx.items.push(Item::Clear(s.clear)); }+ if (s.float != 0 || s.x.inline_block || s.x.pos >= 2) && !forced_inline {+ // Render the element normally into its own item list, then hand it to the layout as a float / inline-block / absolute box.+ let mut inner = s.clone();+ let (float, inline_block, abs) = (s.float, s.x.inline_block, s.x.pos >= 2);+ inner.float = 0;+ inner.clear = 0;+ inner.block = true;+ inner.x.pos = 0;+ inner.x.inline_block = false;+ let (width, max_width) = (s.width, s.max_width);+ inner.width = width.map(|_| Len::Pct(100.0));+ inner.max_width = None;+ let saved = std::mem::take(&mut cx.items);+ cx.pending_space = false;+ walk_styled(cx, id, &inner, parent, false);+ let items = std::mem::replace(&mut cx.items, saved);+ cx.pending_space = !abs && inline_block && float == 0;+ cx.items.push(if abs { Item::Abs(Box::new(AbsSpec { items, off: s.x.off, width, max_width, fixed: s.x.pos == 3, z: s.x.z })) }+ else if float == 0 { Item::InlineBlock(Box::new(FloatSpec { right: false, width, max_width, items })) }+ else { Item::Float(Box::new(FloatSpec { right: float == 2, width, max_width, items })) });+ return;+ }+ walk_styled(cx, id, &s, parent, forced_inline);+}++/// Control a `<label>` stands for: `for=id`, else the first control inside it.+fn label_target(dom: &Dom, id: usize) -> Option<usize> {+ if let Some(f) = dom.attr(id, "for") { return dom.descendants().into_iter().find(|&i| dom.attr(i, "id") == Some(f)); }+ let mut st: Vec<usize> = dom.nodes[id].kids.iter().rev().copied().collect();+ while let Some(i) = st.pop() {+ if matches!(dom.nodes[i].tag.as_str(), "input" | "select" | "textarea") { return Some(i); }+ st.extend(dom.nodes[i].kids.iter().rev());+ }+ None+}++/// Inline text of a `::before` (1) / `::after` (2) pseudo-element with `content: "..."`.+fn pseudo_text(cx: &mut Ctx, id: usize, s: &Style, which: u8) {+ let Some((ps, text)) = css::pseudo(cx.dom, &cx.sheet, id, which, s) else { return };+ if ps.none { return; }+ cx.node = id;+ let text = resolve_counters(cx, &text);+ let mut space = cx.pending_space || text.starts_with(char::is_whitespace);+ for w in text.split_whitespace() { word(cx, w, &ps, space); space = true; }+ cx.pending_space = text.ends_with(char::is_whitespace);+}++/// Replaces the `\u{1}name\u{2}sep\u{3}` markers of a `content` value with the counters' current values.+fn resolve_counters(cx: &Ctx, text: &str) -> String {+ let mut out = String::new();+ let mut rest = text;+ while let Some(a) = rest.find('\u{1}') {+ out.push_str(&rest[..a]);+ let Some(b) = rest[a..].find('\u{3}').map(|b| a + b) else { break };+ let body = &rest[a + 1..b];+ let (name, sep) = body.split_once('\u{2}').unwrap_or((body, ""));+ let vals: Vec<i32> = cx.counters.iter().filter(|c| c.0 == name).map(|c| c.1).collect();+ let vals = if vals.is_empty() { vec![cx.glob.get(name).copied().unwrap_or(0)] } else { vals };+ if sep.is_empty() { out.push_str(&vals.last().copied().unwrap_or(0).to_string()); } else { out.push_str(&vals.iter().map(i32::to_string).collect::<Vec<_>>().join(sep)); }+ rest = &rest[b + 1..];+ }+ out.push_str(rest);+ out+}++/// Row, column or grid container: every element child (and every run of text) becomes a flex item with its own item list.+fn flex(cx: &mut Ctx, id: usize, s: &Style, mode: u8) {+ let dom = cx.dom;+ let mut items = vec![];+ let mut run: Vec<usize> = vec![]; // consecutive text nodes form one anonymous item+ macro_rules! end_run { () => { if !run.is_empty() {+ let saved = std::mem::take(&mut cx.items);+ cx.pending_space = false;+ for &k in &run { walk(cx, k, s, false); }+ let list = std::mem::replace(&mut cx.items, saved);+ if !list.is_empty() { items.push(FlexItem { items: list, grow: 0.0, shrink: 1.0, basis: None, width: None, max_width: None, auto_l: false, auto_r: false, align: 0, span: 1 }); }+ run.clear();+ } }; }+ for &k in &dom.nodes[id].kids {+ if dom.nodes[k].tag.is_empty() { if !dom.nodes[k].text.trim().is_empty() { run.push(k); } continue; }+ end_run!();+ let cs = css::compute(dom, &cx.sheet, k, s);+ if cs.none { continue; }+ let mut inner = cs.clone();+ (inner.float, inner.clear, inner.block, inner.x.inline_block) = (0, 0, true, false);+ inner.width = cs.width.map(|_| Len::Pct(100.0));+ (inner.max_width, inner.auto_l, inner.auto_r) = (None, false, false);+ if cs.x.pos >= 2 { // absolute and fixed children leave the flex flow+ let saved = std::mem::take(&mut cx.items);+ inner.x.pos = 0;+ walk_styled(cx, k, &inner, s, false);+ let list = std::mem::replace(&mut cx.items, saved);+ cx.items.push(Item::Abs(Box::new(AbsSpec { items: list, off: cs.x.off, width: cs.width, max_width: cs.max_width, fixed: cs.x.pos == 3, z: cs.x.z })));+ continue;+ }+ let saved = std::mem::take(&mut cx.items);+ cx.pending_space = false;+ walk_styled(cx, k, &inner, s, false);+ let list = std::mem::replace(&mut cx.items, saved);+ cx.pending_space = false;+ items.push(FlexItem { items: list, grow: cs.x.grow, shrink: cs.x.shrink, basis: cs.x.basis, width: cs.width, max_width: cs.max_width, auto_l: cs.auto_l, auto_r: cs.auto_r, align: cs.x.align, span: cs.x.span.max(1) });+ }+ end_run!();+ cx.items.push(Item::Break(0.0));+ cx.items.push(if mode == 2 {+ Item::Grid(Box::new(GridSpec { items, tracks: s.x.tracks.clone(), auto_min: s.x.auto_min, col_gap: s.x.gap, row_gap: s.x.row_gap.unwrap_or(s.x.gap) }))+ } else {+ Item::Flex(Box::new(FlexSpec { items, wrap: s.x.wrap, gap: s.x.gap, justify: s.x.justify, align: s.x.align, col: mode == 1 }))+ });+ cx.pending_space = false;+}++fn walk_styled(cx: &mut Ctx, id: usize, s: &Style, parent: &Style, forced_inline: bool) {+ let dom = cx.dom;+ let n = &dom.nodes[id];+ let mut s = s.clone();+ // a percentage height needs a definite containing block; otherwise it is auto+ let mut from_pct = false;+ if let (Some((p, exact)), Some(ph)) = (s.x.h_pct, cx.cb_h) {+ s.x.min_h = s.x.min_h.max((ph * p / 100.0).clamp(0.0, 20000.0));+ s.x.fix_h |= exact;+ from_pct = true;+ }+ match n.tag.as_str() {+ "hr" => {+ cx.items.push(Item::Break(s.mt.max(8.0)));+ cx.items.push(Item::Rule(s.borders[0].map_or(0x999999, |b| b.1)));+ cx.items.push(Item::Break(s.mb.max(8.0)));+ cx.pending_space = false;+ return;+ }+ "br" => { cx.items.push(Item::Break(0.0)); cx.pending_space = false; return; }+ // an <svg> is a picture too; svg content that failed to rasterize (or nested svg parts) is simply skipped+ "img" | "svg" => {+ if let Some(im) = cx.imgs.remove(&id) {+ let (nw, nh) = (im.w as f32, im.h as f32);+ // CSS beats the width/height attributes; one given dimension fixes the other by the picture's proportions+ let css_w = if let Some(Len::Px(p)) = s.width { Some(p) } else { None };+ let pct = if let Some(Len::Pct(p)) = s.width { Some(p) } else { None };+ let css_h = s.x.fix_h.then_some(s.x.min_h).filter(|h| *h > 0.0);+ let (aw, ah) = (css_w.or_else(|| px_attr(dom, id, "width")).filter(|_| css_h.is_none() || css_w.is_some()), css_h.or_else(|| px_attr(dom, id, "height")).filter(|_| css_w.is_none() && pct.is_none() || css_h.is_some()));+ let (mut w, mut h) = match (aw, ah) {+ (Some(w), Some(h)) => (w, h),+ (Some(w), None) => (w, w * nh / nw),+ (None, Some(h)) => (h * nw / nh, h),+ // an inline <svg> without any size is 300 px wide at most (browsers use 300 x 150)+ _ if n.tag == "svg" && pct.is_none() => { let k = (300.0 / nw).min(1.0); (nw * k, nh * k) }+ _ => (nw, nh),+ };+ if let Some(Len::Px(mw)) = s.max_width { if w > mw { h *= mw / w; w = mw; } }+ let k = (MAX_IMG_CSS_W / w).min(1.0);+ cx.images.push(im);+ cx.items.push(Item::Image { img: cx.images.len() - 1, w: w * k, h: h * k, link: cx.link, indent: 0.0, align: s.align, node: id, va: s.x.va_kind, alpha: s.alpha, pct });+ cx.pending_space = true;+ } else if let Some(alt) = dom.attr(id, "alt").filter(|a| !a.trim().is_empty()) {+ word(cx, &format!("[{}]", alt.trim()), &s, true);+ }+ return;+ }+ "input" | "button" | "select" | "textarea" => { field(cx, id, &s); return; }+ "table" => { table(cx, id, &s, parent); return; }+ "html" | "body" => if s.bg.is_some() { cx.bg = s.bg },+ _ => {}+ }+ let saved_form = cx.cur_form;+ if n.tag == "form" {+ let action = resolve(cx.base, dom.attr(id, "action").filter(|a| !a.trim().is_empty()).unwrap_or(cx.base));+ cx.forms.push(Form { action, post: dom.attr(id, "method").is_some_and(|m| m.eq_ignore_ascii_case("post")), node: id });+ cx.cur_form = Some(cx.forms.len() - 1);+ }+ let saved_link = cx.link;+ if n.tag == "label" {+ if let Some(t) = label_target(dom, id) { cx.links.push(format!("label:{t}")); cx.link = Some(cx.links.len() - 1); }+ }+ if n.tag == "a" {+ cx.link = dom.attr(id, "href").map(|h| { cx.links.push(resolve(cx.base, h)); cx.links.len() - 1 });+ }+ let block = s.block && !forced_inline;+ let spaced = forced_inline;+ let bg_box = s.bg.filter(|&b| Some(b) != cx.bg || s.bg_a < 1.0 || s.alpha < 1.0 || s.bg_grad.is_some());+ let bg_a = s.bg_a * s.alpha;+ let counter_mark = cx.counters.len();+ for (name, v) in &s.x.counter_reset { cx.counters.push((name.clone(), *v)); }+ for (name, d) in &s.x.counter_inc {+ match cx.counters.iter_mut().rev().find(|c| c.0 == *name) { Some(c) => c.1 += d, None => *cx.glob.entry(name.clone()).or_insert(0) += d }+ }+ let bgimg = s.bg_img.as_ref().and_then(|b| cx.imgs.remove(&(usize::MAX - id)).map(|im| {+ let (nw, nh) = (im.w as f32, im.h as f32);+ cx.images.push(im);+ Arc::new(BgPaint { img: cx.images.len() - 1, nw, nh, size: b.size, pos: b.pos, repeat: b.repeat })+ }));+ let sized = bgimg.is_some() || s.x.shadow.is_some() || s.ml != 0.0 || s.mr != 0.0 || s.pl != 0.0 || s.pr != 0.0 || s.width.is_some() || s.max_width.is_some() || s.auto_l || s.auto_r+ || s.borders.iter().any(Option::is_some) || s.x.min_h > 0.0;+ let boxed = block && (bg_box.is_some() || sized);+ // a box paints its own vertical padding, so the margin gap before it is only the margin+ if block { cx.items.push(Item::Break(if boxed { s.mt - s.pt } else { s.mt })); cx.pending_space = false; cx.indent = s.x.indent; }+ if boxed {+ cx.items.push(Item::Box(BoxSpec {+ ml: s.ml, mr: s.mr, pl: s.pl, pr: s.pr, width: s.width, max_width: s.max_width, auto_l: s.auto_l, auto_r: s.auto_r, bg: bg_box, bb: s.x.bb, min_h: s.x.min_h, radius: s.x.radius, node: id, borders: s.borders,+ pt: s.pt, pb: s.pb, bgimg: bgimg.clone(), bg_a,+ clip: s.x.clip && !s.x.scroll && s.x.fix_h && !from_pct && !matches!(n.tag.as_str(), "html" | "body"),+ scroll: s.x.scroll && s.x.fix_h && !from_pct && !matches!(n.tag.as_str(), "html" | "body"), shadow: s.x.shadow.map(|sh| Shadow { a: sh.a * s.alpha, ..sh }), grad: s.bg_grad.clone(),+ }));+ if let Some(b) = bg_box { let eff = if bg_a < 1.0 { mix(b, backdrop(cx), bg_a) } else { b }; cx.bg_stack.push(eff); }+ }+ let rel = block && s.x.pos == 1;+ if rel { cx.items.push(Item::RelStart(s.x.off, s.x.z, s.x.sticky)); }+ if spaced { cx.pending_space = true; }+ if s.list_item && block && s.bullets {+ let marker = match dom.nodes.get(n.parent).filter(|p| p.tag == "ol") {+ Some(ol) => {+ let start = dom.attr(n.parent, "start").and_then(|v| v.trim().parse::<i64>().ok()).unwrap_or(1);+ let k = ol.kids.iter().take_while(|&&k| k != id).filter(|&&k| dom.nodes[k].tag == "li").count() as i64;+ format!("{}.", dom.attr(id, "value").and_then(|v| v.trim().parse::<i64>().ok()).unwrap_or(start + k))+ }+ None => "•".to_string(),+ };+ word(cx, &marker, &s, false);+ cx.pending_space = true;+ }+ pseudo_text(cx, id, &s, 1);+ let saved_cb = if block { Some(std::mem::replace(&mut cx.cb_h, s.x.fix_h.then_some(s.x.min_h))) } else { None };+ if block && (s.flex_row || s.x.flex_col || s.x.grid) { flex(cx, id, &s, if s.flex_row { 0 } else if s.x.flex_col { 1 } else { 2 }); } else { for &k in &n.kids { walk(cx, k, &s, s.flex_row); } }+ pseudo_text(cx, id, &s, 2);+ if boxed { cx.items.push(Item::BoxEnd); if bg_box.is_some() { cx.bg_stack.pop(); } }+ if rel { cx.items.push(Item::RelEnd); } // after BoxEnd: the box's own min-height, background and borders move with it+ if block { cx.items.push(Item::Break(if boxed { s.mb - s.pb } else { s.mb })); cx.pending_space = false; }+ if spaced && !block { cx.pending_space = true; }+ if let Some(c) = saved_cb { cx.cb_h = c; }+ cx.counters.truncate(counter_mark);+ cx.link = saved_link;+ cx.cur_form = saved_form;+}++pub fn resolve(base: &str, h: &str) -> String { dedot(resolve_raw(base, h)) }++/// Removes `.` and `..` segments from the path of an absolute URL.+fn dedot(url: String) -> String {+ let Some(s) = url.find("://") else { return url };+ let Some(p) = url[s + 3..].find('/') else { return url };+ let start = s + 3 + p;+ let tail_at = url[start..].find(['?', '#']).map_or(url.len(), |i| start + i);+ let (path, tail) = (&url[start..tail_at], &url[tail_at..]);+ if !path.contains("/.") { return url; }+ let mut out: Vec<&str> = vec![];+ for seg in path.split('/').skip(1) { match seg { "." => {} ".." => { out.pop(); } x => out.push(x) } }+ let dir = path.ends_with("/.") || path.ends_with("/..");+ format!("{}/{}{}{}", &url[..start], out.join("/"), if dir && !out.is_empty() { "/" } else { "" }, tail)+}++fn resolve_raw(base: &str, h: &str) -> String {+ if h.contains("://") || h.starts_with('#') || h.contains(':') && !h.contains('/') { return h.into(); }+ let base = base.split(['?', '#']).next().unwrap_or(base);+ let Some(s) = base.find("://") else { return h.into() };+ let origin_end = base[s + 3..].find('/').map_or(base.len(), |p| p + s + 3);+ if let Some(rest) = h.strip_prefix("//") { return format!("{}://{}", &base[..s], rest); }+ if h.starts_with('/') { return format!("{}{}", &base[..origin_end], h); }+ match base[origin_end..].rfind('/') {+ Some(p) => format!("{}{}", &base[..origin_end + p + 1], h),+ None => format!("{}/{}", base, h),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::dom::parse;++ fn words(items: &[Item]) -> String {+ items.iter().map(|i| match i {+ Item::Word { text, space, .. } => format!("{}{}", if *space { " " } else { "" }, text),+ Item::Break(_) => "|".into(),+ _ => String::new(),+ }).collect()+ }++ fn build(d: &Dom, base: &str) -> Page { super::build(d, base, HashMap::new()) }++ #[test]+ fn flow_links_lists_hidden() {+ let d = parse("<title>t</title><style>.x{display:none}</style><h1>Hi & bye</h1><p>see <a href=\"/x\">this</a>.<span class=x>no</span></p><ul><li>one</li><li>two <img alt=pic></li></ul>", true);+ let pg = build(&d, "https://a.com/d/e");+ assert_eq!(words(&pg.items), "|||Hi & bye||see this.|||• one||• two [pic]||||");+ assert_eq!(pg.links, vec!["https://a.com/x"]);+ assert_eq!(pg.title, "t");+ assert!(matches!(pg.items[3], Item::Word { size, bold: true, .. } if size == 32.0));+ }++ #[test]+ fn tables_become_rows_and_cells() {+ let d = parse("<table width=80% border=1 cellpadding=3><thead><tr><th>H</th></tr></thead><tr><td>1.</td><td colspan=2 align=right><a href=x>Title</a></td></tr></table>", true);+ let pg = build(&d, "https://a.com");+ let Some(Item::Table(t)) = pg.items.iter().find(|i| matches!(i, Item::Table(_))) else { panic!("no table") };+ assert_eq!((t.rows.len(), t.rows[1].cells.len(), t.border, t.width), (2, 2, 1.0, Some(Len::Pct(80.0))));+ assert_eq!((t.rows[1].cells[1].colspan, t.rows[1].cells[0].pad), (2, [3.0; 4]));+ assert!(matches!(t.rows[1].cells[1].items[0], Item::Word { align: 2, link: Some(0), .. }));+ assert!(matches!(t.rows[0].cells[0].items[0], Item::Word { bold: true, align: 1, .. }));+ }++ #[test]+ fn images_and_boxes() {+ let d = parse("<div style='background:#ff0000;color:#fff'>hi</div><a href=/x><img src=a.png width=50></a>", true);+ let id = d.find("img").unwrap();+ let mut imgs = HashMap::new();+ imgs.insert(id, Img { w: 100, h: 40, px: vec![0; 100 * 40 * 4] });+ let pg = super::build(&d, "https://a.com", imgs);+ assert_eq!(pg.images.len(), 1);+ assert!(pg.items.iter().any(|i| matches!(i, Item::Box(b) if b.bg == Some(0xFF0000))));+ assert!(pg.items.iter().any(|i| matches!(i, Item::Image { w, h, link: Some(0), .. } if *w == 50.0 && *h == 20.0)));+ assert!(pg.items.iter().any(|i| matches!(i, Item::Word { color: 0xFFFFFF, .. })));+ }++ #[test]+ fn forms_and_fields() {+ let d = parse("<form action=/s method=get><input type=hidden name=h value=1><input name=q value=hi size=10><button>Go</button><input type=button value=No></form><input name=out>", true);+ let pg = build(&d, "https://a.com/x/y");+ assert_eq!(pg.forms.len(), 1);+ assert_eq!((pg.forms[0].action.as_str(), pg.forms[0].post), ("https://a.com/s", false));+ let f: Vec<_> = pg.fields.iter().map(|f| (f.name.as_str(), f.form, f.kind)).collect();+ assert_eq!(f, vec![("h", Some(0), FieldKind::Hidden), ("q", Some(0), FieldKind::Text), ("", Some(0), FieldKind::Submit), ("", None, FieldKind::Submit), ("out", None, FieldKind::Text)]);+ assert_eq!(pg.fields[2].label, "Go");+ assert_eq!(pg.items.iter().filter(|i| matches!(i, Item::Field { .. })).count(), 4); // hidden is not drawn+ }++ #[test]+ fn select_textarea_radio() {+ let d = parse("<form><select name=c><option value=a>Alpha<option value=b selected>Beta</select><textarea name=m rows=4>\nhello</textarea><input type=radio name=r value=1 checked><input type=radio name=r value=2></form>", true);+ let pg = build(&d, "https://a.com");+ let f = &pg.fields;+ assert_eq!((f[0].kind, f[0].sel, f[0].value.as_str(), f[0].options.len()), (FieldKind::Select, 1, "b", 2));+ assert_eq!((f[1].kind, f[1].value.as_str()), (FieldKind::TextArea, "hello"));+ assert_eq!((f[2].kind, f[2].checked, f[3].checked), (FieldKind::Radio, true, false));+ }++ #[test]+ fn page_background_and_contrast() {+ let d = parse("<body style='background:#000'><p style='color:#111'>x</p>", true);+ let pg = build(&d, "https://a.com");+ assert_eq!(pg.bg, 0);+ assert!(matches!(pg.items.iter().find(|i| matches!(i, Item::Word { .. })), Some(Item::Word { color: 0xEEEEEE, .. })));+ }++ #[test]+ fn resolve_cases() {+ assert_eq!(resolve("https://a.com/d/e?q=1", "f"), "https://a.com/d/f");+ assert_eq!(resolve("https://a.com", "f"), "https://a.com/f");+ assert_eq!(resolve("https://a.com/d/e", "//b.com/x"), "https://b.com/x");+ assert_eq!(resolve("https://a.com/d/e", "https://c.com"), "https://c.com");+ assert_eq!(resolve("https://a.com/a/d/e", "../b/./c?x=../y#f"), "https://a.com/a/b/c?x=../y#f");+ assert_eq!(resolve("https://a.com/a/b/c", "../../../.."), "https://a.com/");+ assert_eq!(resolve("https://a.com/a/b/c", ".."), "https://a.com/a/");+ }++ #[test]+ fn pseudo_content_and_text_transform() {+ let d = parse("<style>a::before{content:'\\2192 '} p:after{content:\"!\"} h1{text-transform:uppercase} b{content:'x'}</style><a href=x>go</a><p>t</p><h1>big</h1>", true);+ let w = words(&build(&d, "https://a.com").items);+ assert!(w.contains("\u{2192} go") && w.contains("t!") && w.contains("BIG") && !w.contains('x'), "{w}");+ }++ #[test]+ fn labels_point_at_their_controls() {+ let d = parse("<label for=q>Name</label><input id=q name=q><label>Agree <input type=checkbox name=c></label>", true);+ let pg = build(&d, "https://a.com");+ let q = pg.fields.iter().find(|f| f.name == "q").unwrap().node;+ let c = pg.fields.iter().find(|f| f.name == "c").unwrap().node;+ assert_eq!(pg.links, vec![format!("label:{q}"), format!("label:{c}")]);+ }++ #[test]+ fn cjk_runs_split_into_breakable_pieces() {+ assert_eq!(split_cjk("abc"), vec!["abc"]);+ assert_eq!(split_cjk("ab\u{4f60}\u{597d}cd"), vec!["ab", "\u{4f60}", "\u{597d}", "cd"]);+ let d = parse("<p>\u{4f60}\u{597d}\u{4e16}\u{754c}</p>", true);+ assert_eq!(pg_words(&build(&d, "https://a.com")), 4);+ }++ #[test]+ fn css_sizes_override_image_attributes_and_keep_proportions() {+ let size = |html: &str| {+ let d = parse(html, true);+ let (tag, id) = (if d.find("img").is_some() { "img" } else { "svg" }, d.find("img").or_else(|| d.find("svg")).unwrap());+ let _ = tag;+ let pg = super::build(&d, "https://a.com", HashMap::from([(id, Img { w: 100, h: 40, px: vec![0; 100 * 40 * 4] })]));+ pg.items.iter().find_map(|i| if let Item::Image { w, h, pct, .. } = i { Some((*w, *h, *pct)) } else { None }).unwrap()+ };+ assert_eq!(size("<img width=300 height=300>"), (300.0, 300.0, None), "attributes alone");+ assert_eq!(size("<img>"), (100.0, 40.0, None), "natural size");+ assert_eq!(size("<img width=300 height=300 style='width:50px'>"), (50.0, 20.0, None), "CSS width wins, height follows the proportions");+ assert_eq!(size("<img width=300 height=300 style='height:20px'>"), (50.0, 20.0, None));+ assert_eq!(size("<img style='width:1em'>"), (16.0, 6.4, None));+ assert_eq!(size("<img style='max-width:60px'>"), (60.0, 24.0, None));+ assert_eq!(size("<img style='width:50%'>"), (100.0, 40.0, Some(50.0)));+ assert_eq!(size("<img style='max-width:200px;width:150px'>"), (150.0, 60.0, None));+ let (w, h, _) = size("<svg viewBox='0 0 100 40'></svg>");+ assert!(w <= 300.0 && (w / h - 2.5).abs() < 0.01, "an unsized svg is capped at 300 wide: {w}");+ }++ #[test]+ fn hover_active_and_focus_restyle_from_the_kept_dom() {+ let d = parse("<style>a{color:#0000ff} a:hover{color:#ff0000} p:active{color:#00aa00} input:focus{background:#ffff00}</style><p><a href=x>go</a> tail</p><input name=q>", true);+ let (a, p, inp) = (d.find("a").unwrap(), d.find("p").unwrap(), d.find("input").unwrap());+ let color_of = |pg: &Page, word: &str| pg.items.iter().find_map(|i| match i { Item::Word { text, color, .. } if text == word => Some(*color), _ => None }).unwrap();+ css::set_state(0, 0, 0);+ let pg = build(&d, "https://a.com");+ assert!(pg.restyle.is_some(), "pages with state selectors keep what a restyle needs");+ assert_eq!((color_of(&pg, "go"), color_of(&pg, "tail")), (0x0000FF, 0x111111));+ css::set_state(d.nodes[a].kids[0], 0, 0); // the pointer is over the link's text: the link and its ancestors are :hover+ let pg = restyled(pg.restyle.as_ref().unwrap());+ assert_eq!(color_of(&pg, "go"), 0xFF0000);+ css::set_state(0, p, 0);+ let pg = restyled(pg.restyle.as_ref().unwrap());+ assert_eq!((color_of(&pg, "tail"), color_of(&pg, "go")), (0x00AA00, 0x0000FF));+ css::set_state(0, 0, inp);+ let pg = restyled(pg.restyle.as_ref().unwrap());+ assert!(pg.items.iter().any(|i| matches!(i, Item::Box(b) if b.bg == Some(0xFFFF00))) || pg.items.iter().any(|i| matches!(i, Item::Field { .. })), "focus state reaches the control");+ css::set_state(0, 0, 0);+ assert!(build(&parse("<p>plain</p>", true), "https://a.com").restyle.is_none(), "no state selectors, nothing kept");+ }++ #[test]+ fn background_urls_are_found_from_stylesheets_and_inline_styles() {+ let d = parse("<style>.hero{background:url(img/h.png) no-repeat} .x{background-image:none}</style><div class=hero>a</div><div style=\"background-image:url('/b.jpg')\">b</div><div class=x>c</div><p>d</p>", true);+ let urls: Vec<String> = background_urls(&d, "https://a.com/p/q.html").into_iter().map(|u| u.1).collect();+ assert_eq!(urls, vec!["https://a.com/p/img/h.png", "https://a.com/b.jpg"]);+ assert!(background_urls(&parse("<p>none</p>", true), "https://a.com").is_empty());+ }++ #[test]+ fn uax14_breaks_after_hyphens_and_slashes_and_obeys_kinsoku() {+ assert_eq!(split_cjk("well-known"), vec!["well-", "known"]);+ assert_eq!(split_cjk("https://a.com/b/c"), vec!["https://", "a.com/", "b/", "c"]);+ assert_eq!(split_cjk("plain"), vec!["plain"]);+ assert_eq!(split_cjk("co\u{ad}operate"), vec!["co\u{ad}", "operate"]);+ // no line may start with a closing mark: the full stop and the closing bracket stay with the character before them+ assert_eq!(split_cjk("\u{4f60}\u{597d}\u{3002}\u{4e16}"), vec!["\u{4f60}", "\u{597d}\u{3002}", "\u{4e16}"]);+ assert_eq!(split_cjk("\u{4f60}\u{300d}\u{597d}"), vec!["\u{4f60}\u{300d}", "\u{597d}"]);+ // no line may end with an opening bracket+ assert_eq!(split_cjk("\u{4f60}\u{300c}\u{597d}"), vec!["\u{4f60}", "\u{300c}\u{597d}"]);+ }++ fn pg_words(pg: &Page) -> usize { pg.items.iter().filter(|i| matches!(i, Item::Word { .. })).count() }+}diff --git a/plugins/chrome-rs/src/snap.rs b/plugins/chrome-rs/src/snap.rsnew file mode 100644index 0000000..f3623bc--- /dev/null+++ b/plugins/chrome-rs/src/snap.rs@@ -0,0 +1,254 @@+// Headless rendering for regression testing: `--snap in.html out.png [width]` renders one offline page to a PNG,+// `--bench DIR [runs]` prints median build/layout/paint milliseconds per page, `--corpus DIR [--bless] [--budget PCT]` renders every DIR/*.html and compares it with DIR/golden/<name>.png.+// shortcut: goldens depend on the system fonts, so they are per-machine (bless again after a font change); pages are+// rendered offline (inline CSS/JS only, no images); pages taller than MAX_H are cut off.+// Real pages: `--save DIR urls.txt [--force]` loads each URL once over the network and archives every response under DIR/NNN-name/;+// `--corpus DIR` then also loads every DIR/real/*/ from its archive (no network, full pipeline: CSS, scripts, images, fonts) and compares it with DIR/real/golden.+use crate::{gfx::{draw_field, draw_image, fill, Fonts}, layout::layout, load, render::Page};+use std::path::Path;++const MAX_H: usize = 8000;+const WIDTH: u32 = 1000;++/// Paints the whole page (no scrolling) into a `w x h` pixel buffer.+pub fn paint(page: &Page, width: u32, fonts: &mut Fonts) -> (usize, usize, Vec<u32>) {+ let (mut placed, mut rects, mut content_h) = crate::layout::layout_vh(&page.items, width as f32, 1.0, 720.0, fonts);+ // a page shorter than the viewport has its fixed boxes at the bottom of the page image instead of 720px down+ if content_h < 720.0 && placed.iter().any(|p| p.z >= crate::layout::FIXED_Z) { (placed, rects, content_h) = crate::layout::layout_vh(&page.items, width as f32, 1.0, content_h, fonts); }+ let (bw, bh) = (width as usize, (content_h.ceil() as usize).clamp(1, MAX_H));+ let mut buf = vec![page.bg; bw * bh];+ let groups = crate::layout::groups(&rects);+ let clip = |grp: u32| groups.get(&grp).map(|g| (g.x as i32, g.y as i32, (g.x + g.w).ceil() as i32, (g.y + g.h).ceil() as i32));+ for (_, rr, pr) in crate::layout::layers(&placed, &rects) {+ for r in &rects[rr.clone()] {+ crate::gfx::set_clip(clip(r.grp).filter(|_| r.scroll.is_nan()));+ crate::gfx::draw_rect(&mut buf, bw, bh, r, 0.0);+ if let Some(pic) = &r.pic { crate::gfx::draw_pic(&mut buf, bw, bh, &page.images[pic.img], r, 0.0); }+ }+ for p in &placed[pr] {+ crate::gfx::set_clip(clip(p.grp));+ if let Some(i) = p.img { draw_image(&mut buf, bw, bh, &page.images[i], p.x, p.base - p.size, p.w, p.size, if p.color == 0 { 255 } else { p.color }); continue; }+ if let Some(i) = p.field { draw_field(&mut buf, bw, bh, fonts, &page.fields[i], None, 1.0, p.x, p.base - p.size, p.w, p.size); continue; }+ crate::gfx::draw_text_ls(&mut buf, bw, bh, fonts, &p.text, p.x, p.base, p.size, p.color, p.face, p.ls);+ if p.ul { fill(&mut buf, bw, p.x as i32, p.base as i32 + 2, p.w as i32, 1, p.color); }+ }+ crate::gfx::set_clip(None);+ for r in rects[rr].iter().filter(|r| r.scroll.is_finite()) { crate::gfx::draw_box_scrollbar(&mut buf, bw, bh, r.x, r.y, r.w, r.h, r.scroll, 0.0, 1.0); }+ }+ (bw, bh, buf)+}++/// Minimal PDF: the page image cut into A4 sheets (one Flate-compressed RGB image per sheet, full width). Not selectable text.+pub fn pdf(buf: &[u32], w: usize, h: usize) -> Vec<u8> {+ const PW: f32 = 595.0; // A4 in points+ const PH: f32 = 842.0;+ let sheet_px = ((PH / PW) * w as f32).floor().max(1.0) as usize; // source rows per sheet+ let sheets = h.div_ceil(sheet_px).max(1);+ let mut out: Vec<u8> = b"%PDF-1.4\n".to_vec();+ let mut offs: Vec<usize> = vec![];+ let mut obj = |out: &mut Vec<u8>, body: &[u8]| { offs.push(out.len()); out.extend_from_slice(format!("{} 0 obj\n", offs.len()).as_bytes()); out.extend_from_slice(body); out.extend_from_slice(b"\nendobj\n"); };+ // objects: 1 catalog, 2 pages, then per sheet: page, contents, image+ obj(&mut out, b"<< /Type /Catalog /Pages 2 0 R >>");+ let kids: String = (0..sheets).map(|i| format!("{} 0 R ", 3 + i * 3)).collect();+ obj(&mut out, format!("<< /Type /Pages /Count {sheets} /Kids [{kids}] >>").as_bytes());+ for i in 0..sheets {+ let (y0, y1) = (i * sheet_px, ((i + 1) * sheet_px).min(h));+ let rows = y1 - y0;+ let ph = PW * rows as f32 / w as f32; // image height on the sheet in points+ let (page, content, image) = (3 + i * 3, 4 + i * 3, 5 + i * 3);+ obj(&mut out, format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {PW} {PH}] /Contents {content} 0 R /Resources << /XObject << /Im0 {image} 0 R >> >> >>").as_bytes());+ let _ = page;+ let c = format!("q {PW} 0 0 {ph} 0 {} cm /Im0 Do Q", PH - ph);+ obj(&mut out, format!("<< /Length {} >>\nstream\n{c}\nendstream", c.len()).as_bytes());+ let raw: Vec<u8> = buf[y0 * w..y1 * w].iter().flat_map(|&p| [(p >> 16) as u8, (p >> 8) as u8, p as u8]).collect();+ let z = miniz_oxide::deflate::compress_to_vec_zlib(&raw, 6);+ let mut body = format!("<< /Type /XObject /Subtype /Image /Width {w} /Height {rows} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n", z.len()).into_bytes();+ body.extend_from_slice(&z);+ body.extend_from_slice(b"\nendstream");+ obj(&mut out, &body);+ }+ let xref = out.len();+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offs.len() + 1).as_bytes());+ for o in &offs { out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); }+ out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", offs.len() + 1).as_bytes());+ out+}++fn save_png(path: &Path, w: usize, h: usize, buf: &[u32]) -> Result<(), String> {+ let rgb: Vec<u8> = buf.iter().flat_map(|&c| [(c >> 16) as u8, (c >> 8) as u8, c as u8]).collect();+ image::save_buffer(path, &rgb, w as u32, h as u32, image::ColorType::Rgb8).map_err(|e| e.to_string())+}++/// Percentage of pixels that differ; the area outside the overlap counts as different.+fn diff_pct(a: (usize, usize, &[u32]), b: (usize, usize, &[u32])) -> f64 {+ let (w, h) = (a.0.max(b.0), a.1.max(b.1));+ let same = (0..a.1.min(b.1)).map(|y| (0..a.0.min(b.0)).filter(|&x| a.2[y * a.0 + x] == b.2[y * b.0 + x]).count()).sum::<usize>();+ 100.0 * (1.0 - same as f64 / (w * h) as f64)+}++fn render_file(path: &Path, fonts: &mut Fonts) -> Result<(usize, usize, Vec<u32>), String> {+ let html = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;+ let page = load::load_offline(&html, "https://corpus.test/");+ Ok(paint(&page, WIDTH, fonts))+}++fn html_files(dir: &Path) -> Result<Vec<std::path::PathBuf>, String> {+ let mut pages: Vec<_> = std::fs::read_dir(dir).map_err(|e| e.to_string())?.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "html")).collect();+ pages.sort();+ Ok(pages)+}++fn load_golden(path: &Path) -> Option<(usize, usize, Vec<u32>)> {+ let im = image::open(path).ok()?.to_rgb8();+ let buf = im.pixels().map(|p| (p[0] as u32) << 16 | (p[1] as u32) << 8 | p[2] as u32).collect();+ Some((im.width() as usize, im.height() as usize, buf))+}++/// Entry for `--snap` / `--corpus`; returns the process exit code.+pub fn cli(args: &[String], fonts: &mut Fonts) -> i32 {+ // cookies and local storage of the pages loaded here go to a scratch directory, never into the user's browser profile+ // SAFETY: the main thread only waits for this one, no other thread reads the environment yet+ unsafe { std::env::set_var("CHROME_RS_DATA", std::env::temp_dir().join("chrome-rs-corpus-data")); }+ let mut run = || -> Result<i32, String> {+ match args.first().map(String::as_str) {+ Some("--pdf") => {+ let (inp, out) = (args.get(1).ok_or("usage: --pdf in.html out.pdf")?, args.get(2).ok_or("usage: --pdf in.html out.pdf")?);+ let html = std::fs::read_to_string(inp).map_err(|e| e.to_string())?;+ let (w, h, buf) = paint(&load::load_offline(&html, "https://corpus.test/"), 794, fonts);+ std::fs::write(out, pdf(&buf, w, h)).map_err(|e| e.to_string())?;+ println!("{out}: {w}x{h} px");+ Ok(0)+ }+ Some("--snap") => {+ let (inp, out) = (args.get(1).ok_or("usage: --snap in.html out.png [width]")?, args.get(2).ok_or("usage: --snap in.html out.png [width]")?);+ let html = std::fs::read_to_string(inp).map_err(|e| e.to_string())?;+ let width = args.get(3).and_then(|w| w.parse().ok()).unwrap_or(WIDTH);+ let (w, h, buf) = paint(&load::load_offline(&html, "https://corpus.test/"), width, fonts);+ save_png(Path::new(out), w, h, &buf)?;+ println!("{out}: {w}x{h}");+ Ok(0)+ }+ Some("--bench") => {+ let dir = Path::new(args.get(1).ok_or("usage: --bench DIR [runs]")?);+ let runs: usize = args.get(2).and_then(|v| v.parse().ok()).unwrap_or(20).max(1);+ println!("{:<16} {:>9} {:>9} {:>9}", "page", "build ms", "layout ms", "paint ms");+ for p in html_files(dir)? {+ let html = std::fs::read_to_string(&p).map_err(|e| e.to_string())?;+ let (mut b, mut l, mut t) = (vec![], vec![], vec![]);+ for _ in 0..runs {+ let t0 = std::time::Instant::now();+ let page = load::load_offline(&html, "https://corpus.test/");+ b.push(t0.elapsed().as_secs_f64() * 1e3);+ let t1 = std::time::Instant::now();+ let _ = layout(&page.items, WIDTH as f32, 1.0, fonts);+ l.push(t1.elapsed().as_secs_f64() * 1e3);+ let t2 = std::time::Instant::now();+ let _ = paint(&page, WIDTH, fonts);+ t.push(t2.elapsed().as_secs_f64() * 1e3 - l.last().copied().unwrap_or(0.0));+ }+ let med = |v: &mut Vec<f64>| { v.sort_by(|a, b| a.total_cmp(b)); v[v.len() / 2] };+ println!("{:<16} {:>9.2} {:>9.2} {:>9.2}", p.file_stem().and_then(|s| s.to_str()).unwrap_or("?"), med(&mut b), med(&mut l), med(&mut t).max(0.0));+ }+ Ok(0)+ }+ Some("--save") => {+ let usage = "usage: --save DIR urls.txt [--force]";+ let (dir, list) = (Path::new(args.get(1).ok_or(usage)?), args.get(2).ok_or(usage)?);+ let force = args.iter().any(|a| a == "--force");+ let urls: Vec<String> = std::fs::read_to_string(list).map_err(|e| e.to_string())?.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')).map(String::from).collect();+ let mut ok = 0;+ for (i, u) in urls.iter().enumerate() {+ let slug: String = u.split("://").nth(1).unwrap_or(u).chars().map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '-' }).take(40).collect();+ let d = dir.join(format!("{:03}-{}", i + 1, slug.trim_matches('-')));+ if d.join("url.txt").exists() && !force { ok += 1; continue; }+ let _ = std::fs::remove_dir_all(&d);+ std::fs::create_dir_all(&d).map_err(|e| e.to_string())?;+ load::set_archive(Some((d.clone(), true)));+ match load::load(u, None, None) {+ Ok((_, page)) if !page.items.is_empty() => { std::fs::write(d.join("url.txt"), u).map_err(|e| e.to_string())?; println!("saved {} ({} items)", d.file_name().and_then(|n| n.to_str()).unwrap_or("?"), page.items.len()); ok += 1; }+ Ok(_) => { println!("EMPTY {u}"); let _ = std::fs::remove_dir_all(&d); }+ Err(e) => { println!("FAIL {u}: {e}"); let _ = std::fs::remove_dir_all(&d); }+ }+ }+ load::set_archive(None);+ println!("{ok} of {} pages saved", urls.len());+ Ok(0)+ }+ _ => {+ let dir = Path::new(args.get(1).ok_or("usage: --corpus DIR [--bless] [--budget PCT]")?);+ let bless = args.iter().any(|a| a == "--bless");+ let budget: f64 = args.iter().position(|a| a == "--budget").and_then(|i| args.get(i + 1)).and_then(|v| v.parse().ok()).unwrap_or(0.5);+ let (out_dir, gold_dir) = (dir.join("out"), dir.join("golden"));+ std::fs::create_dir_all(&out_dir).and_then(|_| std::fs::create_dir_all(&gold_dir)).map_err(|e| e.to_string())?;+ let pages = html_files(dir)?;+ let mut failed = 0;+ // real pages (see --save) come from their archives; a page that fails to load counts as over budget+ let real = dir.join("real");+ let mut archives: Vec<std::path::PathBuf> = std::fs::read_dir(&real).map(|d| d.flatten().map(|e| e.path()).filter(|p| p.join("url.txt").exists()).collect()).unwrap_or_default();+ archives.sort();+ let (real_out, real_gold) = (real.join("out"), real.join("golden"));+ if !archives.is_empty() { std::fs::create_dir_all(&real_out).and_then(|_| std::fs::create_dir_all(&real_gold)).map_err(|e| e.to_string())?; }+ let jobs = pages.iter().map(|p| (p.clone(), false)).chain(archives.iter().map(|p| (p.clone(), true)));+ let total = pages.len() + archives.len();+ for (p, is_real) in jobs {+ let name = p.file_stem().and_then(|s| s.to_str()).or_else(|| p.file_name().and_then(|s| s.to_str())).unwrap_or("page").to_string();+ let rendered = if is_real {+ let url = std::fs::read_to_string(p.join("url.txt")).map_err(|e| e.to_string())?;+ load::set_archive(Some((p.clone(), false)));+ let r = load::load(url.trim(), None, None).map(|(_, page)| paint(&page, WIDTH, fonts));+ load::set_archive(None);+ match r { Ok(r) => r, Err(e) => { failed += 1; println!("ERROR {name}: {e}"); continue; } }+ } else { render_file(&p, fonts)? };+ let (w, h, buf) = rendered;+ let (out_dir, gold_dir) = if is_real { (&real_out, &real_gold) } else { (&out_dir, &gold_dir) };+ let out_png = out_dir.join(format!("{name}.png"));+ save_png(&out_png, w, h, &buf)?;+ let gold = gold_dir.join(format!("{name}.png"));+ if bless { std::fs::copy(&out_png, &gold).map_err(|e| e.to_string())?; println!("BLESS {name} {w}x{h}"); continue; }+ match load_golden(&gold) {+ None => println!("NEW {name} (no golden yet; run with --bless)"),+ Some((gw, gh, gb)) => {+ let d = diff_pct((w, h, &buf), (gw, gh, &gb));+ let ok = d <= budget;+ if !ok { failed += 1; }+ println!("{} {name} {d:.3}% (budget {budget}%)", if ok { "ok " } else { "FAIL " });+ }+ }+ }+ println!("{total} pages ({} real), {failed} over budget", archives.len());+ Ok((failed > 0) as i32)+ }+ }+ };+ run().unwrap_or_else(|e| { eprintln!("error: {e}"); 2 })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn pdf_has_one_sheet_per_a4_slice_and_a_valid_xref() {+ let buf = vec![0x336699u32; 100 * 300]; // 100 x 300 px -> sheet height 100*842/595 = 141 px -> 3 sheets+ let p = pdf(&buf, 100, 300);+ let rfind = |needle: &[u8]| p.windows(needle.len()).rposition(|w| w == needle).unwrap();+ assert!(p.starts_with(b"%PDF-1.4") && p.trim_ascii_end().ends_with(b"%%EOF"));+ assert!(p.windows(8).any(|w| w == b"/Count 3"), "three sheets");+ // every xref offset points at "N 0 obj"+ let sx = rfind(b"startxref\n") + 10;+ let start: usize = std::str::from_utf8(&p[sx..]).unwrap().lines().next().unwrap().parse().unwrap();+ assert_eq!(&p[start..start + 4], b"xref");+ let table = std::str::from_utf8(&p[start..rfind(b"trailer")]).unwrap();+ let entries: Vec<usize> = table.lines().skip(2).filter(|l| l.ends_with(" n ")).map(|l| l[..10].parse().unwrap()).collect();+ assert_eq!(entries.len(), 2 + 3 * 3);+ for (i, o) in entries.iter().enumerate() { assert!(p[*o..].starts_with(format!("{} 0 obj", i + 1).as_bytes()), "object {}", i + 1); }+ }++ #[test]+ fn diff_counts_changed_and_missing_pixels() {+ let a = vec![0u32; 4];+ assert_eq!(diff_pct((2, 2, &a), (2, 2, &a)), 0.0);+ assert_eq!(diff_pct((2, 2, &a), (2, 2, &[0, 0, 0, 1])), 25.0);+ assert_eq!(diff_pct((2, 2, &a), (2, 1, &a[..2])), 50.0); // missing row counts as different+ }+}diff --git a/plugins/chrome-rs/src/store.rs b/plugins/chrome-rs/src/store.rsnew file mode 100644index 0000000..361600d--- /dev/null+++ b/plugins/chrome-rs/src/store.rs@@ -0,0 +1,375 @@+// Persistent state: the cookie jar (RFC 6265 subset) and per-origin localStorage, both kept under the data dir.+// shortcut: `Expires` is ignored (cookies without Max-Age live for the session), no SameSite/public-suffix checks, no size caps per+// cookie; upgrade when third-party isolation (M8) lands.+use std::{path::PathBuf, sync::{Mutex, OnceLock}, time::{SystemTime, UNIX_EPOCH}};++#[derive(Clone, Debug, PartialEq)]+pub struct Cookie { name: String, value: String, domain: String, host_only: bool, path: String, secure: bool, http_only: bool, expires: Option<u64> }++#[derive(Default)]+pub struct Jar { cookies: Vec<Cookie> }++fn now() -> u64 { SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()) }++/// (scheme, host without port, path without query) of an absolute URL.+pub fn split_url(url: &str) -> Option<(&str, &str, &str)> {+ let (scheme, rest) = url.split_once("://")?;+ let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());+ let auth = &rest[..end];+ let host = auth.rsplit('@').next().unwrap_or(auth);+ let host = host.rsplit_once(':').filter(|(_, p)| p.chars().all(|c| c.is_ascii_digit())).map_or(host, |(h, _)| h);+ let path = rest[end..].split(['?', '#']).next().unwrap_or("");+ Some((scheme, host, if path.is_empty() { "/" } else { path }))+}++/// `scheme://host[:port]` of an absolute URL ("" when there is none).+pub fn origin_of(url: &str) -> String {+ let end = url.find("://").map_or(0, |p| url[p + 3..].find(['/', '?', '#']).map_or(url.len(), |e| p + 3 + e));+ url[..end].to_string()+}++/// Same site, loosely: equal hosts or one a subdomain of the other.+pub fn same_site(a: &str, b: &str) -> bool { a == b || a.ends_with(&format!(".{b}")) || b.ends_with(&format!(".{a}")) }++fn domain_match(host: &str, c: &Cookie) -> bool { if c.host_only { host == c.domain } else { host == c.domain || host.ends_with(&format!(".{}", c.domain)) } }++fn path_match(req: &str, cp: &str) -> bool { req == cp || req.starts_with(cp) && (cp.ends_with('/') || req[cp.len()..].starts_with('/')) }++impl Jar {+ /// Stores one `Set-Cookie` header received from `url`. `from_js` rejects HttpOnly (scripts cannot create those).+ pub fn set(&mut self, url: &str, header: &str, from_js: bool) {+ let Some((_, host, rpath)) = split_url(url) else { return };+ let mut parts = header.split(';');+ let Some((name, value)) = parts.next().and_then(|nv| nv.split_once('=')) else { return };+ let name = name.trim();+ if name.is_empty() { return; }+ let default_path = match rpath.rfind('/') { Some(0) | None => "/".to_string(), Some(i) => rpath[..i].to_string() };+ let mut c = Cookie { name: name.into(), value: value.trim().into(), domain: host.to_ascii_lowercase(), host_only: true, path: default_path, secure: false, http_only: false, expires: None };+ let mut delete = false;+ for attr in parts {+ let (k, v) = attr.split_once('=').map_or((attr.trim(), ""), |(k, v)| (k.trim(), v.trim()));+ match k.to_ascii_lowercase().as_str() {+ "domain" => {+ let d = v.trim_start_matches('.').to_ascii_lowercase();+ if !d.is_empty() && (host == d || host.ends_with(&format!(".{d}"))) && d.contains('.') { c.domain = d; c.host_only = false; } else { return; }+ }+ "path" => if v.starts_with('/') { c.path = v.into() },+ "secure" => c.secure = true,+ "httponly" => c.http_only = true,+ "max-age" => if let Ok(n) = v.parse::<i64>() { if n <= 0 { delete = true } else { c.expires = Some(now() + n as u64) } },+ _ => {}+ }+ }+ if from_js && c.http_only { return; }+ self.cookies.retain(|o| !(o.name == c.name && o.domain == c.domain && o.path == c.path));+ if !delete { self.cookies.push(c); }+ }++ /// Value of the `Cookie` request header for `url` ("" when nothing matches).+ pub fn header(&mut self, url: &str, with_http_only: bool) -> String {+ let Some((scheme, host, path)) = split_url(url) else { return String::new() };+ let t = now();+ self.cookies.retain(|c| c.expires.is_none_or(|e| e > t));+ let mut hit: Vec<&Cookie> = self.cookies.iter()+ .filter(|c| domain_match(host, c) && path_match(path, &c.path) && (!c.secure || scheme == "https") && (with_http_only || !c.http_only)).collect();+ hit.sort_by_key(|c| std::cmp::Reverse(c.path.len()));+ hit.iter().map(|c| format!("{}={}", c.name, c.value)).collect::<Vec<_>>().join("; ")+ }++ fn to_tsv(&self) -> String {+ self.cookies.iter().filter_map(|c| Some(format!("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n", c.domain, c.host_only as u8, c.path, c.secure as u8, c.http_only as u8, c.expires?, c.name, c.value))).collect()+ }++ fn from_tsv(s: &str) -> Jar {+ let cookies = s.lines().filter_map(|l| {+ let f: Vec<&str> = l.splitn(8, '\t').collect();+ if f.len() < 8 { return None; }+ Some(Cookie { domain: f[0].into(), host_only: f[1] == "1", path: f[2].into(), secure: f[3] == "1", http_only: f[4] == "1", expires: f[5].parse().ok(), name: f[6].into(), value: f[7].into() })+ }).collect();+ Jar { cookies }+ }+}++pub fn data_dir() -> Option<PathBuf> {+ let base = std::env::var_os("CHROME_RS_DATA").map(PathBuf::from)+ .or_else(|| std::env::var_os("APPDATA").map(|p| PathBuf::from(p).join("chrome-rs")))+ .or_else(|| std::env::var_os("HOME").map(|p| PathBuf::from(p).join(".chrome-rs")))?;+ std::fs::create_dir_all(&base).ok()?;+ Some(base)+}++fn jar() -> &'static Mutex<Jar> {+ static JAR: OnceLock<Mutex<Jar>> = OnceLock::new();+ JAR.get_or_init(|| Mutex::new(data_dir().and_then(|d| std::fs::read_to_string(d.join("cookies.tsv")).ok()).map_or_else(Jar::default, |s| Jar::from_tsv(&s))))+}++/// Cookie request header for `url` from the shared jar.+pub fn cookie_header(url: &str, with_http_only: bool) -> String { jar().lock().map(|mut j| j.header(url, with_http_only)).unwrap_or_default() }++/// Records a `Set-Cookie` header in the shared jar and persists the persistent cookies.+pub fn set_cookie(url: &str, header: &str, from_js: bool) {+ let Ok(mut j) = jar().lock() else { return };+ j.set(url, header, from_js);+ if let Some(d) = data_dir() { let _ = std::fs::write(d.join("cookies.tsv"), j.to_tsv()); }+}++fn ls_file(dir: &std::path::Path) -> PathBuf { dir.join("localstorage.json") }++/// localStorage of `origin` as a JSON object string.+pub fn ls_load_in(dir: &std::path::Path, origin: &str) -> String {+ let all: serde_json::Value = std::fs::read_to_string(ls_file(dir)).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default();+ all.get(origin).filter(|v| v.is_object()).map_or_else(|| "{}".into(), |v| v.to_string())+}++/// Replaces the stored localStorage of `origin` (ignored when not a JSON object or over 5 MB).+pub fn ls_save_in(dir: &std::path::Path, origin: &str, json: &str) {+ let Ok(v) = serde_json::from_str::<serde_json::Value>(json) else { return };+ if !v.is_object() || json.len() > 5_000_000 { return; }+ let mut all: serde_json::Map<String, serde_json::Value> = std::fs::read_to_string(ls_file(dir)).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default();+ if v.as_object().is_some_and(|o| o.is_empty()) { all.remove(origin); } else { all.insert(origin.into(), v); }+ let _ = std::fs::write(ls_file(dir), serde_json::Value::Object(all).to_string());+}++pub fn ls_load(origin: &str) -> String { data_dir().map_or_else(|| "{}".into(), |d| ls_load_in(&d, origin)) }+pub fn ls_save(origin: &str, json: &str) { if let Some(d) = data_dir() { ls_save_in(&d, origin, json); } }++// ---------- history, bookmarks, session, settings (tab-separated text files in the data dir)++fn read_lines(dir: &std::path::Path, file: &str) -> Vec<String> { std::fs::read_to_string(dir.join(file)).map(|s| s.lines().map(String::from).collect()).unwrap_or_default() }++fn clean(s: &str) -> String { s.chars().map(|c| if c.is_control() { ' ' } else { c }).collect::<String>().trim().to_string() }++/// One saved page: address, title and unix time.+#[derive(Clone, Debug, PartialEq)]+pub struct Entry { pub url: String, pub title: String, pub time: u64 }++fn parse_entry(l: &str) -> Option<Entry> {+ let mut f = l.splitn(3, '\t');+ Some(Entry { url: f.next()?.to_string(), title: f.next()?.to_string(), time: f.next()?.parse().ok()? })+}++fn entries_in(dir: &std::path::Path, file: &str) -> Vec<Entry> { read_lines(dir, file).iter().filter_map(|l| parse_entry(l)).collect() }++fn write_entries(dir: &std::path::Path, file: &str, e: &[Entry]) {+ let _ = std::fs::write(dir.join(file), e.iter().map(|x| format!("{}\t{}\t{}\n", x.url, x.title, x.time)).collect::<String>());+}++/// Whether a page belongs in history / bookmarks (not internal, scripted or data pages).+pub fn recordable(url: &str) -> bool { url.starts_with("http://") || url.starts_with("https://") || url.starts_with("file://") }++/// Appends a visit (a repeat of the previous visit only updates it); the file is trimmed to the newest 2000 entries.+pub fn add_history_in(dir: &std::path::Path, url: &str, title: &str) {+ if !recordable(url) { return; }+ let mut h = entries_in(dir, "history.tsv");+ let e = Entry { url: clean(url), title: clean(title), time: now() };+ if h.last().is_some_and(|l| l.url == e.url) { h.pop(); }+ h.push(e);+ if h.len() > 2000 { h.drain(..h.len() - 2000); }+ write_entries(dir, "history.tsv", &h);+}++/// Newest first.+pub fn history_in(dir: &std::path::Path) -> Vec<Entry> { let mut h = entries_in(dir, "history.tsv"); h.reverse(); h }++#[cfg(test)]+pub fn clear_history_in(dir: &std::path::Path) { let _ = std::fs::remove_file(dir.join("history.tsv")); }++pub fn bookmarks_in(dir: &std::path::Path) -> Vec<Entry> { entries_in(dir, "bookmarks.tsv") }++pub fn is_bookmarked_in(dir: &std::path::Path, url: &str) -> bool { bookmarks_in(dir).iter().any(|b| b.url == url) }++/// Adds the page, or removes it when it is already bookmarked; returns true when it is bookmarked afterwards.+pub fn toggle_bookmark_in(dir: &std::path::Path, url: &str, title: &str) -> bool {+ if !recordable(url) { return false; }+ let mut b = bookmarks_in(dir);+ let had = b.len();+ b.retain(|x| x.url != url);+ let added = b.len() == had;+ if added { b.push(Entry { url: clean(url), title: clean(title), time: now() }); }+ write_entries(dir, "bookmarks.tsv", &b);+ added+}++/// Address-bar suggestions: bookmarks first, then history, whose url or title contains every word of `q` (case-insensitive).+pub fn suggest_in(dir: &std::path::Path, q: &str, n: usize) -> Vec<Entry> {+ let words: Vec<String> = q.to_lowercase().split_whitespace().map(String::from).collect();+ if words.is_empty() { return vec![]; }+ let mut out: Vec<Entry> = vec![];+ for e in bookmarks_in(dir).into_iter().chain(history_in(dir)) {+ let hay = format!("{} {}", e.url, e.title).to_lowercase();+ if words.iter().all(|w| hay.contains(w)) && !out.iter().any(|o| o.url == e.url) { out.push(e); }+ if out.len() >= n { break; }+ }+ out+}++pub fn save_session_in(dir: &std::path::Path, urls: &[String], current: usize) {+ let body: String = std::iter::once(format!("{current}\n")).chain(urls.iter().filter(|u| recordable(u)).map(|u| format!("{}\n", clean(u)))).collect();+ let _ = std::fs::write(dir.join("session.txt"), body);+}++/// (tab urls, index of the active tab) of the previous run.+pub fn load_session_in(dir: &std::path::Path) -> (Vec<String>, usize) {+ let l = read_lines(dir, "session.txt");+ let cur = l.first().and_then(|c| c.parse().ok()).unwrap_or(0);+ let urls: Vec<String> = l.into_iter().skip(1).filter(|u| recordable(u)).collect();+ let cur = cur.min(urls.len().saturating_sub(1));+ (urls, cur)+}++/// Value of a `key<TAB>value` line in settings.tsv.+pub fn setting_in(dir: &std::path::Path, key: &str) -> Option<String> {+ read_lines(dir, "settings.tsv").iter().find_map(|l| l.split_once('\t').filter(|(k, _)| *k == key).map(|(_, v)| v.trim().to_string())).filter(|v| !v.is_empty())+}++pub fn add_history(url: &str, title: &str) { if let Some(d) = data_dir() { add_history_in(&d, url, title); } }+pub fn toggle_bookmark(url: &str, title: &str) -> bool { data_dir().is_some_and(|d| toggle_bookmark_in(&d, url, title)) }+pub fn is_bookmarked(url: &str) -> bool { data_dir().is_some_and(|d| is_bookmarked_in(&d, url)) }+pub fn suggest(q: &str, n: usize) -> Vec<Entry> { data_dir().map_or_else(Vec::new, |d| suggest_in(&d, q, n)) }+pub fn save_session(urls: &[String], current: usize) { if let Some(d) = data_dir() { save_session_in(&d, urls, current); } }+pub fn load_session() -> (Vec<String>, usize) { data_dir().map_or_else(|| (vec![], 0), |d| load_session_in(&d)) }+pub fn setting(key: &str) -> Option<String> { data_dir().and_then(|d| setting_in(&d, key)) }++fn esc(s: &str) -> String { s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) }++fn day(t: u64) -> String {+ // civil date from unix days (UTC)+ let z = (t / 86_400) as i64 + 719_468;+ let (era, doe) = (z.div_euclid(146_097), z.rem_euclid(146_097));+ let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;+ let (y, doy) = (yoe + era * 400, doe - (365 * yoe + yoe / 4 - yoe / 100));+ let mp = (5 * doy + 2) / 153;+ let (d, m) = (doy - (153 * mp + 2) / 5 + 1, if mp < 10 { mp + 3 } else { mp - 9 });+ format!("{:04}-{:02}-{:02}", if m <= 2 { y + 1 } else { y }, m, d)+}++/// HTML of the internal `about:` pages that list stored data.+pub fn about_html_in(dir: &std::path::Path, page: &str) -> Option<String> {+ let list = |title: &str, e: &[Entry], empty: &str| {+ let mut h = format!("<title>{title}</title><h2>{title}</h2>");+ if e.is_empty() { h += &format!("<p>{empty}</p>"); }+ let mut last = String::new();+ for x in e {+ let d = day(x.time);+ if d != last { h += &format!("<h4>{d}</h4>"); last = d; }+ h += &format!("<div><a href=\"{}\">{}</a> <small>{}</small></div>", esc(&x.url), esc(if x.title.is_empty() { &x.url } else { &x.title }), esc(&x.url));+ }+ h+ };+ Some(match page {+ "about:history" => list("History", &history_in(dir), "Nothing visited yet."),+ "about:bookmarks" => list("Bookmarks", &bookmarks_in(dir), "No bookmarks yet. Press Ctrl+D on a page to add one."),+ "about:settings" => {+ let rows: String = [("home", "Home page (first tab)", "https://example.com"), ("search", "Search engine, {q} is the query", "https://html.duckduckgo.com/html/?q={q}")].iter()+ .map(|(k, d, def)| format!("<tr><td><b>{k}</b></td><td>{}</td><td>{}</td></tr>", esc(d), esc(&setting_in(dir, k).unwrap_or_else(|| format!("{def} (default)"))))).collect();+ format!("<title>Settings</title><h2>Settings</h2><p>Edit <code>{}</code> (one <code>key<TAB>value</code> per line), then restart.</p><table border=1 cellpadding=4>{rows}</table>", esc(&dir.join("settings.tsv").to_string_lossy()))+ }+ _ => return None,+ })+}++pub fn about_html(page: &str) -> Option<String> { about_html_in(&data_dir()?, page) }++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn cookies_scope_by_domain_path_secure_and_expiry() {+ let mut j = Jar::default();+ j.set("https://www.a.com/x/y", "sid=1; Path=/x; HttpOnly", false);+ j.set("https://www.a.com/", "all=2; Domain=a.com", false);+ j.set("https://www.a.com/", "sec=3; Secure", false);+ assert_eq!(j.header("https://www.a.com/x/z", true), "sid=1; all=2; sec=3");+ assert_eq!(j.header("https://www.a.com/x/z", false), "all=2; sec=3"); // scripts do not see HttpOnly+ assert_eq!(j.header("https://api.a.com/", true), "all=2"); // domain cookie reaches subdomains, host-only ones do not+ assert_eq!(j.header("http://www.a.com/", true), "all=2"); // Secure needs https+ assert_eq!(j.header("https://www.a.com/xy", true), "all=2; sec=3"); // path must match on a segment boundary+ assert_eq!(j.header("https://evil.com/", true), "");+ j.set("https://www.a.com/", "all=; Domain=a.com; Max-Age=0", false);+ assert_eq!(j.header("https://api.a.com/", true), "");+ j.set("https://www.a.com/", "x=1; Domain=b.com", false); // foreign Domain is rejected+ assert_eq!(j.header("https://b.com/", true), "");+ j.set("https://www.a.com/", "h=1; HttpOnly", true); // script cannot set HttpOnly+ assert!(!j.header("https://www.a.com/", true).contains("h=1"));+ }++ #[test]+ fn persistent_cookies_roundtrip_and_session_ones_stay_out() {+ let mut j = Jar::default();+ j.set("https://a.com/", "keep=1; Max-Age=3600", false);+ j.set("https://a.com/", "tmp=2", false);+ let tsv = j.to_tsv();+ assert!(tsv.contains("keep") && !tsv.contains("tmp"));+ assert_eq!(Jar::from_tsv(&tsv).header("https://a.com/", true), "keep=1");+ }++ #[test]+ fn url_split_and_same_site() {+ assert_eq!(split_url("https://u:[email protected]:8080/x/y?q#f"), Some(("https", "a.com", "/x/y")));+ assert_eq!(split_url("https://a.com"), Some(("https", "a.com", "/")));+ assert!(same_site("www.a.com", "a.com") && !same_site("a.com", "b.com"));+ assert_eq!(origin_of("https://a.com:8080/x?y#z"), "https://a.com:8080");+ assert_ne!(origin_of("http://a.com/"), origin_of("https://a.com/"));+ }++ #[test]+ fn local_storage_persists_per_origin() {+ let dir = std::env::temp_dir().join(format!("chrome-rs-ls-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ assert_eq!(ls_load_in(&dir, "https://a.com"), "{}");+ ls_save_in(&dir, "https://a.com", r#"{"k":"v"}"#);+ ls_save_in(&dir, "https://b.com", r#"{"x":"y"}"#);+ assert_eq!(ls_load_in(&dir, "https://a.com"), r#"{"k":"v"}"#);+ ls_save_in(&dir, "https://a.com", "{}");+ assert_eq!(ls_load_in(&dir, "https://a.com"), "{}");+ assert_eq!(ls_load_in(&dir, "https://b.com"), r#"{"x":"y"}"#);+ let _ = std::fs::remove_dir_all(&dir);+ }++ fn tmp(name: &str) -> std::path::PathBuf {+ let d = std::env::temp_dir().join(format!("chrome-rs-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&d);+ std::fs::create_dir_all(&d).unwrap();+ d+ }++ #[test]+ fn history_bookmarks_and_suggestions() {+ let d = tmp("hist");+ add_history_in(&d, "https://a.com/x", "Alpha page");+ add_history_in(&d, "about:blank", "ignored");+ add_history_in(&d, "https://b.com/", "Beta\tpage");+ add_history_in(&d, "https://b.com/", "Beta again"); // repeat of the last visit replaces it+ let h = history_in(&d);+ assert_eq!(h.iter().map(|e| (e.url.as_str(), e.title.as_str())).collect::<Vec<_>>(), vec![("https://b.com/", "Beta again"), ("https://a.com/x", "Alpha page")]);+ assert!(toggle_bookmark_in(&d, "https://a.com/x", "Alpha page") && is_bookmarked_in(&d, "https://a.com/x"));+ assert_eq!(suggest_in(&d, "alp", 5).len(), 1);+ assert_eq!(suggest_in(&d, "b.com beta", 5)[0].url, "https://b.com/");+ assert_eq!(suggest_in(&d, "zzz", 5).len(), 0);+ assert_eq!(suggest_in(&d, "a", 1).len(), 1);+ assert!(!toggle_bookmark_in(&d, "https://a.com/x", "") && !is_bookmarked_in(&d, "https://a.com/x")); // toggles off+ assert!(!toggle_bookmark_in(&d, "javascript:alert(1)", "x"));+ let page = about_html_in(&d, "about:history").unwrap();+ assert!(page.contains("<a href=\"https://b.com/\">Beta again</a>") && page.contains("<h4>20"));+ assert!(about_html_in(&d, "about:bookmarks").unwrap().contains("No bookmarks yet"));+ clear_history_in(&d);+ assert!(history_in(&d).is_empty());+ let _ = std::fs::remove_dir_all(&d);+ }++ #[test]+ fn session_and_settings_files() {+ let d = tmp("sess");+ save_session_in(&d, &["https://a.com/".into(), "about:blank".into(), "https://b.com/".into()], 1);+ assert_eq!(load_session_in(&d), (vec!["https://a.com/".to_string(), "https://b.com/".to_string()], 1));+ assert_eq!(load_session_in(&tmp("none")), (vec![], 0));+ std::fs::write(d.join("settings.tsv"), "home\thttps://start.test/\nsearch\t\n").unwrap();+ assert_eq!(setting_in(&d, "home").as_deref(), Some("https://start.test/"));+ assert_eq!(setting_in(&d, "search"), None);+ assert!(about_html_in(&d, "about:settings").unwrap().contains("https://start.test/"));+ assert_eq!(day(0), "1970-01-01");+ assert_eq!(day(1_800_000_000), "2027-01-15");+ let _ = std::fs::remove_dir_all(&d);+ }+}diff --git a/plugins/chrome-rs/src/svg.rs b/plugins/chrome-rs/src/svg.rsnew file mode 100644index 0000000..630af40--- /dev/null+++ b/plugins/chrome-rs/src/svg.rs@@ -0,0 +1,124 @@+// SVG support: standalone .svg files and inline <svg> elements are rasterized once (resvg) into an RGBA Img.+// shortcut: no <text> (fonts are not loaded into resvg), no page-CSS styling of inline svg; upgrade when icon fonts/labels matter.+use crate::{dom::Dom, load::Img};+use resvg::{tiny_skia, usvg};++const MAX_W: f32 = 800.0;++/// Rasterizes SVG markup at its natural size (scaled down to MAX_W wide). Straight (non-premultiplied) RGBA.+pub fn render(svg: &str) -> Option<Img> {+ let tree = usvg::Tree::from_str(svg, &usvg::Options::default()).ok()?;+ let size = tree.size();+ let k = (MAX_W / size.width()).min(1.0);+ let (w, h) = (((size.width() * k).ceil() as u32).clamp(1, 4000), ((size.height() * k).ceil() as u32).clamp(1, 4000));+ let mut pm = tiny_skia::Pixmap::new(w, h)?;+ resvg::render(&tree, tiny_skia::Transform::from_scale(k, k), &mut pm.as_mut());+ let mut px = pm.take();+ for p in px.chunks_exact_mut(4) {+ let a = p[3] as u32;+ if a > 0 && a < 255 { for c in &mut p[..3] { *c = ((*c as u32 * 255 / a).min(255)) as u8; } }+ }+ Some(Img { w, h, px })+}++const CAMEL_ATTRS: &[&str] = &[+ "viewBox", "preserveAspectRatio", "gradientUnits", "gradientTransform", "patternUnits", "patternContentUnits", "patternTransform",+ "clipPathUnits", "maskUnits", "maskContentUnits", "markerWidth", "markerHeight", "markerUnits", "refX", "refY", "stdDeviation",+ "spreadMethod", "startOffset", "textLength", "baseFrequency", "numOctaves", "filterUnits", "primitiveUnits", "pathLength",+];+const CAMEL_TAGS: &[&str] = &[+ "linearGradient", "radialGradient", "clipPath", "textPath", "foreignObject", "feGaussianBlur", "feOffset", "feMerge", "feMergeNode",+ "feColorMatrix", "feBlend", "feFlood", "feComposite",+];++/// The HTML parser lowercases names; SVG is case-sensitive, so restore the common camelCase ones.+fn restore<'a>(lower: &'a str, table: &'a [&'a str]) -> &'a str {+ table.iter().find(|c| c.eq_ignore_ascii_case(lower)).copied().unwrap_or(lower)+}++fn esc(s: &str) -> String { s.replace('&', "&").replace('<', "<").replace('"', """) }++/// Serializes the element subtree at `id` as standalone SVG markup. `<use href="#x">` that points outside the subtree (an icon sprite+/// elsewhere in the page) gets its target copied into a trailing `<defs>`, since the rasterizer only sees this one element.+pub fn to_markup(dom: &Dom, id: usize) -> String {+ let mut out = String::new();+ write(dom, id, true, &mut out);+ let (mut have, mut pending): (Vec<String>, Vec<usize>) = (vec![], vec![id]);+ let mut defs = String::new();+ let ids_in = |root: usize| { let mut v = vec![]; walk(dom, root, &mut |i| if let Some(x) = dom.attr(i, "id") { v.push(x.to_string()); }); v };+ have.extend(ids_in(id));+ for _round in 0..3 {+ let mut wanted: Vec<String> = vec![];+ for r in pending.drain(..) {+ walk(dom, r, &mut |i| if dom.nodes[i].tag == "use" {+ if let Some(h) = dom.attr(i, "href").or_else(|| dom.attr(i, "xlink:href")).and_then(|h| h.strip_prefix('#')) { if !have.iter().any(|x| x == h) && !wanted.iter().any(|x| x == h) { wanted.push(h.to_string()); } }+ });+ }+ if wanted.is_empty() || have.len() > 60 { break; }+ for w in wanted {+ let Some(t) = (1..dom.nodes.len()).find(|&i| dom.attr(i, "id") == Some(w.as_str()) && !dom.nodes[i].tag.is_empty()) else { continue };+ write(dom, t, false, &mut defs);+ have.push(w);+ pending.push(t);+ }+ }+ if !defs.is_empty() && out.ends_with("</svg>") { out.truncate(out.len() - 6); out.push_str(&format!("<defs>{defs}</defs></svg>")); }+ out+}++fn walk(dom: &Dom, id: usize, f: &mut dyn FnMut(usize)) {+ f(id);+ for &k in &dom.nodes[id].kids { walk(dom, k, f); }+}++fn write(dom: &Dom, id: usize, root: bool, out: &mut String) {+ let n = &dom.nodes[id];+ if n.tag == crate::dom::COMMENT { return; }+ if n.tag.is_empty() { out.push_str(&esc(&n.text).replace('"', "\"")); return; }+ let tag = restore(&n.tag, CAMEL_TAGS);+ out.push('<');+ out.push_str(tag);+ if root {+ if dom.attr(id, "xmlns").is_none() { out.push_str(" xmlns=\"http://www.w3.org/2000/svg\""); }+ if dom.attr(id, "xmlns:xlink").is_none() { out.push_str(" xmlns:xlink=\"http://www.w3.org/1999/xlink\""); }+ }+ for (k, v) in &n.attrs { out.push_str(&format!(" {}=\"{}\"", restore(k, CAMEL_ATTRS), esc(v))); }+ out.push('>');+ for &k in &n.kids { write(dom, k, false, out); }+ out.push_str(&format!("</{tag}>"));+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::dom::parse;++ #[test]+ fn renders_shapes_with_alpha() {+ let im = render("<svg xmlns='http://www.w3.org/2000/svg' width='20' height='10'><rect width='10' height='10' fill='#ff0000'/></svg>").unwrap();+ assert_eq!((im.w, im.h), (20, 10));+ assert_eq!(&im.px[..4], &[255, 0, 0, 255]); // left half red+ assert_eq!(im.px[(19) * 4 + 3], 0); // right half transparent+ }+++ #[test]+ fn use_pulls_in_a_sprite_symbol_from_elsewhere_in_the_page() {+ let d = parse("<svg style='display:none'><symbol id=dot viewBox='0 0 2 2'><rect width=2 height=2 fill=#00f /></symbol></svg><p><svg width=8 height=8><use href='#dot' width=8 height=8 /></svg></p>", true);+ let svgs: Vec<usize> = d.descendants().into_iter().filter(|&i| d.nodes[i].tag == "svg").collect();+ let m = to_markup(&d, svgs[1]);+ assert!(m.contains("<defs><symbol id=\"dot\""), "{m}");+ let im = render(&m).unwrap();+ assert_eq!(&im.px[..4], &[0, 0, 255, 255], "the symbol is drawn");+ }+ #[test]+ fn inline_svg_keeps_case_sensitive_names() {+ let d = parse("<p><svg viewBox='0 0 4 4' width=8 height=8><defs><linearGradient id=g><stop offset=0 stop-color=#00f /></linearGradient></defs><circle cx=2 cy=2 r=2 fill=url(#g) /></svg></p>", true);+ let id = d.find("svg").unwrap();+ let m = to_markup(&d, id);+ assert!(m.contains("viewBox=") && m.contains("<linearGradient"), "{m}");+ let im = render(&m).unwrap();+ assert_eq!((im.w, im.h), (8, 8));+ assert!(im.px.chunks(4).any(|p| p[3] == 255)); // circle drawn+ }+}diff --git a/plugins/chrome-rs/src/testdata/lato.woff2 b/plugins/chrome-rs/src/testdata/lato.woff2new file mode 100644index 0000000..ff60934Binary files /dev/null and b/plugins/chrome-rs/src/testdata/lato.woff2 differdiff --git a/plugins/debloat/Cargo.lock b/plugins/debloat/Cargo.locknew file mode 100644index 0000000..a5e5dbb--- /dev/null+++ b/plugins/debloat/Cargo.lock@@ -0,0 +1,7 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "debloat"+version = "0.1.0"diff --git a/plugins/debloat/Cargo.toml b/plugins/debloat/Cargo.tomlnew file mode 100644index 0000000..e6592c1--- /dev/null+++ b/plugins/debloat/Cargo.toml@@ -0,0 +1,11 @@+[package]+name = "debloat"+version = "0.1.0"+edition = "2024"++[profile.release]+opt-level = "s"+lto = true+codegen-units = 1+panic = "abort"+strip = truediff --git a/plugins/debloat/src/main.rs b/plugins/debloat/src/main.rsnew file mode 100644index 0000000..99f9375--- /dev/null+++ b/plugins/debloat/src/main.rs@@ -0,0 +1,226 @@+// debloat show what would change (nothing is modified)+// debloat --apply apply (admin); the old value of every change is written to the undo file BEFORE the change+// debloat --undo put every value and service back exactly as it was+//+// Only reversible things: a few services and registry policies. Not touched on purpose: Windows Update, Defender, Print Spooler,+// Xbox/Game services, SysMain, and installed apps (removing an AppX package cannot be undone from here).+// Side effect worth knowing: Edge shows "managed by your organization" while its two policies below are set.+use std::{+ env,+ fs::{self, OpenOptions},+ io::Write,+ path::PathBuf,+ process::Command,+};++const SERVICES: &[(&str, &str)] = &[+ ("DiagTrack", "Connected User Experiences and Telemetry"),+ ("dmwappushservice", "WAP push message routing (telemetry helper)"),+ ("MapsBroker", "downloaded maps"),+ ("RetailDemo", "retail demo mode"),+ ("WerSvc", "Windows Error Reporting"),+ ("Fax", "Fax"),+];++// (key, value, DWORD data, what it does)+const REGS: &[(&str, &str, u32, &str)] = &[+ (r"HKLM\SOFTWARE\Policies\Microsoft\Windows\DataCollection", "AllowTelemetry", 0, "telemetry to the minimum"),+ (r"HKLM\SOFTWARE\Policies\Microsoft\Windows\DataCollection", "DoNotShowFeedbackNotifications", 1, "no feedback pop-ups"),+ (r"HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsCopilot", "TurnOffWindowsCopilot", 1, "Copilot off"),+ (r"HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsAI", "DisableAIDataAnalysis", 1, "Recall: no snapshots of your screen"),+ (r"HKLM\SOFTWARE\Policies\Microsoft\Windows\CloudContent", "DisableWindowsConsumerFeatures", 1, "no suggested/promoted apps"),+ (r"HKLM\SOFTWARE\Policies\Microsoft\Windows\CloudContent", "DisableCloudOptimizedContent", 1, "no cloud-driven content"),+ (r"HKLM\SOFTWARE\Policies\Microsoft\Windows\CloudContent", "DisableSoftLanding", 1, "no Windows tips and tricks"),+ (r"HKLM\SOFTWARE\Policies\Microsoft\Windows\AdvertisingInfo", "DisabledByGroupPolicy", 1, "no advertising ID"),+ (r"HKLM\SOFTWARE\Policies\Microsoft\Windows\System", "EnableActivityFeed", 0, "no activity history (Timeline)"),+ (r"HKLM\SOFTWARE\Policies\Microsoft\Windows\System", "PublishUserActivities", 0, "activity history stays local"),+ (r"HKLM\SOFTWARE\Policies\Microsoft\Windows\GameDVR", "AllowGameDVR", 0, "Game Bar background capture off"),+ (r"HKLM\SOFTWARE\Policies\Microsoft\Edge", "StartupBoostEnabled", 0, "Edge does not preload at sign-in"),+ (r"HKLM\SOFTWARE\Policies\Microsoft\Edge", "BackgroundModeEnabled", 0, "Edge does not run after it is closed"),+ (r"HKCU\Software\Policies\Microsoft\Windows\Explorer", "DisableSearchBoxSuggestions", 1, "no web results in search"),+ (r"HKCU\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "SilentInstalledAppsEnabled", 0, "no apps installed behind your back"),+ (r"HKCU\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "PreInstalledAppsEnabled", 0, "no pre-installed promoted apps"),+ (r"HKCU\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "OemPreInstalledAppsEnabled", 0, "no OEM promoted apps"),+ (r"HKCU\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "SystemPaneSuggestionsEnabled", 0, "no ads in Start"),+ (r"HKCU\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "SubscribedContent-338388Value", 0, "no suggestions in Start"),+ (r"HKCU\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "SubscribedContent-338389Value", 0, "no tips and suggestions"),+ (r"HKCU\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "SubscribedContent-353694Value", 0, "no suggestions in Settings"),+ (r"HKCU\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "SubscribedContent-353696Value", 0, "no suggestions in Settings"),+ (r"HKCU\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "RotatingLockScreenOverlayEnabled", 0, "no ads on the lock screen"),+];++fn run(prog: &str, args: &[&str]) -> (bool, String) {+ match Command::new(prog).args(args).output() {+ Ok(o) => (o.status.success(), String::from_utf8_lossy(&o.stdout).into_owned()),+ Err(e) => (false, e.to_string()),+ }+}++/// Current start mode as `sc config` spells it. None = service missing, or boot/system driver (never touched).+fn start_mode(svc: &str) -> Option<&'static str> {+ let (ok, out) = run("sc.exe", &["qc", svc]);+ let line = out.lines().find(|l| ok && l.contains("START_TYPE"))?;+ Some(if line.contains("DISABLED") {+ "disabled"+ } else if line.contains("DEMAND_START") {+ "demand"+ } else if line.contains("AUTO_START") {+ if line.contains("DELAYED") { "delayed-auto" } else { "auto" }+ } else {+ return None;+ })+}++#[derive(Debug, PartialEq)]+enum Val {+ Missing,+ Dword(u32),+ Other, // a value of another type: not ours to overwrite+}++/// Reads `reg query /v` output.+fn parse_val(ok: bool, out: &str) -> Val {+ if !ok {+ return Val::Missing;+ }+ match out.lines().find(|l| l.contains("REG_")) {+ Some(l) if l.contains("REG_DWORD") => l.split_whitespace().last().and_then(|t| u32::from_str_radix(t.trim_start_matches("0x"), 16).ok()).map_or(Val::Other, Val::Dword),+ Some(_) => Val::Other,+ None => Val::Missing,+ }+}++fn reg_val(key: &str, value: &str) -> Val {+ let (ok, out) = run("reg.exe", &["query", key, "/v", value]);+ parse_val(ok, &out)+}++fn undo_path() -> PathBuf {+ PathBuf::from(env::var("ProgramData").unwrap_or_else(|_| r"C:\ProgramData".into())).join("winrust-debloat").join("undo.txt")+}++fn plan() {+ println!("Dry run: nothing is changed. Add --apply (admin) to do it, --undo to revert.\n");+ for (svc, why) in SERVICES {+ match start_mode(svc) {+ None => println!(" service {svc:<18} not present"),+ Some("disabled") => println!(" service {svc:<18} already disabled"),+ Some(m) => println!(" service {svc:<18} {m} -> disabled ({why})"),+ }+ }+ for (key, value, data, why) in REGS {+ let state = match reg_val(key, value) {+ Val::Dword(d) if d == *data => "already set".to_string(),+ Val::Dword(d) => format!("{d} -> {data}"),+ Val::Missing => format!("(none) -> {data}"),+ Val::Other => "not a DWORD, left alone".into(),+ };+ println!(" policy {value:<34} {state} ({why})");+ }+}++fn apply() -> Result<(), String> {+ let path = undo_path();+ let dir = path.parent().unwrap();+ fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e} (run as admin)", dir.display()))?;+ let mut log = OpenOptions::new().create(true).append(true).open(&path).map_err(|e| format!("{}: {e}", path.display()))?;+ let mut failed = 0;+ for (svc, _) in SERVICES {+ match start_mode(svc) {+ None => println!("skip {svc}: not present"),+ Some("disabled") => println!("skip {svc}: already disabled"),+ Some(mode) => {+ writeln!(log, "svc|{svc}|{mode}").map_err(|e| e.to_string())?; // log BEFORE changing+ let ok = run("sc.exe", &["config", svc, "start=", "disabled"]).0;+ let _ = run("sc.exe", &["stop", svc]);+ failed += !ok as u32;+ println!("{} {svc}: {mode} -> disabled", if ok { "done " } else { "FAILED" });+ }+ }+ }+ for (key, value, data, _) in REGS {+ let old = match reg_val(key, value) {+ Val::Dword(d) if d == *data => {+ println!("skip {value}: already {data}");+ continue;+ }+ Val::Other => {+ println!("skip {value}: not a DWORD, left alone");+ continue;+ }+ Val::Dword(d) => d.to_string(),+ Val::Missing => "-".into(),+ };+ writeln!(log, "reg|{key}|{value}|{old}").map_err(|e| e.to_string())?;+ let ok = run("reg.exe", &["add", key, "/v", value, "/t", "REG_DWORD", "/d", &data.to_string(), "/f"]).0;+ failed += !ok as u32;+ println!("{} {value} = {data}", if ok { "done " } else { "FAILED" });+ }+ println!("\nUndo information saved to {}. Some changes need a reboot or sign-out.", path.display());+ if failed > 0 { Err(format!("{failed} change(s) failed (run as administrator)")) } else { Ok(()) }+}++fn undo() -> Result<(), String> {+ let path = undo_path();+ let Ok(text) = fs::read_to_string(&path) else {+ println!("nothing to undo (no undo file)");+ return Ok(());+ };+ let mut failed = 0;+ // the first line per item holds the ORIGINAL value (an earlier --apply may have logged the same item again)+ for line in text.lines().rev() {+ let f: Vec<&str> = line.split('|').collect();+ let ok = match f.as_slice() {+ ["svc", name, mode] => run("sc.exe", &["config", name, "start=", mode]).0,+ ["reg", key, value, "-"] => run("reg.exe", &["delete", key, "/v", value, "/f"]).0 || reg_val(key, value) == Val::Missing, // never written (the change itself failed): nothing to remove+ ["reg", key, value, old] => run("reg.exe", &["add", key, "/v", value, "/t", "REG_DWORD", "/d", old, "/f"]).0,+ _ => continue,+ };+ failed += !ok as u32;+ println!("{} {line}", if ok { "restored" } else { "FAILED " });+ }+ if failed > 0 {+ return Err(format!("{failed} item(s) not restored; the undo file is kept at {}", path.display()));+ }+ fs::remove_file(&path).map_err(|e| e.to_string())?;+ println!("\nServices were restored to their old start mode (start them manually or reboot).");+ Ok(())+}++fn main() {+ let args: Vec<String> = env::args().skip(1).collect();+ let r = if args.iter().any(|a| a == "--apply") {+ apply()+ } else if args.iter().any(|a| a == "--undo") {+ undo()+ } else {+ plan();+ Ok(())+ };+ if let Err(e) = r {+ eprintln!("{e}");+ std::process::exit(1);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn reads_reg_query_output() {+ let dw = "\r\nHKEY_LOCAL_MACHINE\\X\r\n AllowTelemetry REG_DWORD 0x1\r\n\r\n";+ assert_eq!(parse_val(true, dw), Val::Dword(1));+ assert_eq!(parse_val(true, " V REG_SZ hello\r\n"), Val::Other);+ assert_eq!(parse_val(false, "ERROR: The system was unable to find the specified registry key or value."), Val::Missing);+ }++ #[test]+ fn every_registry_item_is_hkcu_or_hklm_and_unique() {+ let mut seen = std::collections::HashSet::new();+ for (k, v, _, _) in REGS {+ assert!(k.starts_with("HKLM\\") || k.starts_with("HKCU\\"), "{k}");+ assert!(seen.insert((k, v)), "duplicate {k} {v}");+ }+ }+}diff --git a/plugins/photoview/Cargo.lock b/plugins/photoview/Cargo.locknew file mode 100644index 0000000..eb12e90--- /dev/null+++ b/plugins/photoview/Cargo.lock@@ -0,0 +1,165 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "photoview"+version = "0.1.0"+dependencies = [+ "windows",+ "windows-sys",+]++[[package]]+name = "proc-macro2"+version = "1.0.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "unicode-ident"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"++[[package]]+name = "windows"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"+dependencies = [+ "windows-collections",+ "windows-core",+ "windows-future",+ "windows-numerics",+]++[[package]]+name = "windows-collections"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"+dependencies = [+ "windows-core",+]++[[package]]+name = "windows-core"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-link",+ "windows-result",+ "windows-strings",+]++[[package]]+name = "windows-future"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"+dependencies = [+ "windows-core",+ "windows-link",+ "windows-threading",+]++[[package]]+name = "windows-implement"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "windows-interface"+version = "0.59.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-numerics"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"+dependencies = [+ "windows-core",+ "windows-link",+]++[[package]]+name = "windows-result"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-strings"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-threading"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"+dependencies = [+ "windows-link",+]diff --git a/plugins/photoview/Cargo.toml b/plugins/photoview/Cargo.tomlnew file mode 100644index 0000000..5868bb4--- /dev/null+++ b/plugins/photoview/Cargo.toml@@ -0,0 +1,16 @@+[package]+name = "photoview"+version = "0.1.0"+edition = "2024"++[dependencies]+windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_System_LibraryLoader", "Win32_UI_HiDpi", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] }+# COM only for the image decoder (WIC): JPEG/PNG/GIF/BMP/TIFF, WebP/HEIC/AVIF when the Windows codec is installed+windows = { version = "0.62", features = ["Win32_Foundation", "Win32_Graphics_Imaging", "Win32_System_Com", "Win32_System_Com_StructuredStorage", "Win32_System_Variant"] }++[profile.release]+opt-level = "s"+lto = true+codegen-units = 1+panic = "abort"+strip = truediff --git a/plugins/photoview/src/decode.rs b/plugins/photoview/src/decode.rsnew file mode 100644index 0000000..c04d6c8--- /dev/null+++ b/plugins/photoview/src/decode.rs@@ -0,0 +1,119 @@+// Decodes any picture Windows has a codec for into top-down opaque BGRA, rotated by its EXIF orientation,+// transparent pixels composited over `bg` (BGR).+use windows::{+ Win32::{Foundation::GENERIC_READ, Graphics::Imaging::*, System::Com::*},+ core::*,+};++pub struct Img {+ pub w: i32,+ pub h: i32,+ pub bgra: Vec<u8>,+}++/// Call once on every thread that decodes.+pub fn com_init() {+ unsafe {+ let _ = CoInitializeEx(None, COINIT_MULTITHREADED);+ }+}++/// EXIF orientation (1..8) -> the WIC transform that makes the picture upright.+fn transform(orientation: u16) -> i32 {+ match orientation {+ 2 => 8, // mirrored+ 3 => 2, // 180+ 4 => 16, // mirrored vertically+ 5 => 1 | 8, // transpose+ 6 => 1, // 90 clockwise+ 7 => 3 | 8, // transverse+ 8 => 3, // 90 counter-clockwise+ _ => 0,+ }+}++pub fn decode(path: &str, bg: [u8; 3]) -> Result<Img> {+ unsafe {+ let f: IWICImagingFactory = CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)?;+ let dec = f.CreateDecoderFromFilename(&HSTRING::from(path), None, GENERIC_READ, WICDecodeMetadataCacheOnDemand)?;+ let frame = dec.GetFrame(0)?;+ let orientation = frame+ .GetMetadataQueryReader()+ .and_then(|q| {+ let mut v = windows::Win32::System::Com::StructuredStorage::PROPVARIANT::default();+ q.GetMetadataByName(w!("/app1/ifd/{ushort=274}"), &mut v)?;+ u16::try_from(&v)+ })+ .unwrap_or(1);+ let conv = f.CreateFormatConverter()?;+ conv.Initialize(&frame, &GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, None, 0.0, WICBitmapPaletteTypeCustom)?;+ let mut src: IWICBitmapSource = conv.cast()?;+ let t = transform(orientation);+ if t != 0 {+ let r = f.CreateBitmapFlipRotator()?;+ r.Initialize(&src, WICBitmapTransformOptions(t))?;+ src = r.cast()?;+ }+ let (mut w, mut h) = (0u32, 0u32);+ src.GetSize(&mut w, &mut h)?;+ let mut bgra = vec![0u8; w as usize * h as usize * 4];+ src.CopyPixels(std::ptr::null(), w * 4, &mut bgra)?;+ for p in bgra.chunks_exact_mut(4) {+ let inv = 255 - p[3] as u32; // premultiplied: result = colour + bg * (1 - alpha)+ for c in 0..3 {+ p[c] = (p[c] as u32 + bg[c] as u32 * inv / 255).min(255) as u8;+ }+ p[3] = 255;+ }+ Ok(Img { w: w as i32, h: h as i32, bgra })+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// 2x1 PNG, left pixel opaque red, right pixel fully transparent: the right one must come out as the background.+ #[test]+ fn decodes_png_and_composites_alpha_over_background() {+ // 8-bit RGBA, no interlace; IDAT built by hand (stored deflate block) so the test needs no image file.+ fn crc(d: &[u8]) -> u32 {+ let mut c = !0u32;+ for &b in d {+ c ^= b as u32;+ for _ in 0..8 {+ c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 };+ }+ }+ !c+ }+ fn chunk(out: &mut Vec<u8>, ty: &[u8], data: &[u8]) {+ out.extend((data.len() as u32).to_be_bytes());+ let mut body = ty.to_vec();+ body.extend(data);+ out.extend(&body);+ out.extend(crc(&body).to_be_bytes());+ }+ let raw = [0u8, 255, 0, 0, 255, 0, 0, 0, 0]; // filter 0, red opaque, transparent+ let (mut a, mut b) = (1u32, 0u32);+ for &x in &raw {+ a = (a + x as u32) % 65521;+ b = (b + a) % 65521;+ }+ let mut z = vec![0x78, 0x01, 0x01, raw.len() as u8, 0, !(raw.len() as u8), 0xFF];+ z.extend(raw);+ z.extend(((b << 16) | a).to_be_bytes());+ let mut png = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];+ chunk(&mut png, b"IHDR", &[0, 0, 0, 2, 0, 0, 0, 1, 8, 6, 0, 0, 0]);+ chunk(&mut png, b"IDAT", &z);+ chunk(&mut png, b"IEND", &[]);+ let p = std::env::temp_dir().join("photoview-test.png");+ std::fs::write(&p, png).unwrap();+ com_init();+ let img = decode(p.to_str().unwrap(), [10, 20, 30]).unwrap();+ let _ = std::fs::remove_file(p);+ assert_eq!((img.w, img.h), (2, 1));+ assert_eq!(img.bgra[..4], [0, 0, 255, 255]); // BGRA of opaque red+ assert_eq!(img.bgra[4..8], [10, 20, 30, 255]); // the background, as given (BGR)+ }+}diff --git a/plugins/photoview/src/main.rs b/plugins/photoview/src/main.rsnew file mode 100644index 0000000..8e11109--- /dev/null+++ b/plugins/photoview/src/main.rs@@ -0,0 +1,301 @@+#![windows_subsystem = "windows"]+// photoview [picture] Fast picture viewer (WIC decoder, GDI window). The other pictures of the folder are one key away.+// Left/Right, Space, Backspace, PgUp/PgDn: previous / next Home/End: first / last wheel: zoom drag: pan+// double click, F: fit <-> 100% 1: 100% Del: to the Recycle Bin Esc: close+// shortcuts: files sorted by plain case-insensitive name (no "2 before 10" ordering), only the shown picture is decoded+// (no preloading of neighbours), downscaling is GDI halftone; upgrade if browsing 40 MP photos feels slow.+mod decode;+use std::{+ cell::RefCell,+ path::{Path, PathBuf},+ ptr::{null, null_mut},+ sync::atomic::{AtomicU32, Ordering::Relaxed},+};+use windows_sys::Win32::{+ Foundation::*,+ Graphics::Gdi::*,+ System::LibraryLoader::GetModuleHandleW,+ UI::{+ HiDpi::GetDpiForSystem,+ Input::KeyboardAndMouse::*,+ Shell::{DragAcceptFiles, DragFinish, DragQueryFileW, FOF_ALLOWUNDO, FO_DELETE, HDROP, SHFileOperationW, SHFILEOPSTRUCTW},+ WindowsAndMessaging::*,+ },+};++pub const EXTS: [&str; 11] = ["jpg", "jpeg", "jfif", "png", "bmp", "gif", "tif", "tiff", "webp", "heic", "avif"];+const WM_IMG: u32 = WM_APP + 1; // lparam = Box<(u32, Result<Img, String>)>+const BG: [u8; 3] = [18, 19, 22]; // BGR of rgb(22, 19, 18)++static GEN: AtomicU32 = AtomicU32::new(0); // newest load; older decodes that finish late are dropped++#[derive(Default)]+struct App {+ files: Vec<PathBuf>,+ idx: usize,+ img: Option<decode::Img>,+ note: String,+ zoom: Option<f64>, // None = fit+ off: (f64, f64),+ drag: Option<(i32, i32)>,+ font: isize,+ dpi: i32,+}+thread_local! { static APP: RefCell<App> = RefCell::new(App::default()) }++fn wide(s: &str) -> Vec<u16> {+ s.encode_utf16().chain([0]).collect()+}++fn is_pic(p: &Path) -> bool {+ p.extension().and_then(|e| e.to_str()).is_some_and(|e| EXTS.contains(&e.to_ascii_lowercase().as_str()))+}++fn open(hwnd: HWND, path: &Path) {+ let Some(dir) = path.parent() else { return };+ let mut files: Vec<PathBuf> = std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| is_pic(p)).collect();+ files.sort_by_key(|p| p.file_name().map(|n| n.to_string_lossy().to_lowercase()));+ let idx = files.iter().position(|p| p.as_os_str().eq_ignore_ascii_case(path.as_os_str())).unwrap_or_else(|| {+ files.insert(0, path.to_path_buf());+ 0+ });+ APP.with_borrow_mut(|a| (a.files, a.idx) = (files, idx));+ load(hwnd);+}++fn load(hwnd: HWND) {+ let Some(path) = APP.with_borrow_mut(|a| {+ (a.zoom, a.off) = (None, (0.0, 0.0));+ a.note = "...".into();+ a.files.get(a.idx).cloned()+ }) else {+ return;+ };+ let g = GEN.fetch_add(1, Relaxed) + 1;+ let h = hwnd as isize;+ std::thread::spawn(move || {+ decode::com_init();+ let r = decode::decode(&path.to_string_lossy(), BG).map_err(|e| e.message());+ unsafe { PostMessageW(h as HWND, WM_IMG, 0, Box::into_raw(Box::new((g, r))) as isize) };+ });+ unsafe { InvalidateRect(hwnd, null(), 0) };+ title(hwnd);+}++fn go(hwnd: HWND, to: impl FnOnce(usize, usize) -> usize) {+ let moved = APP.with_borrow_mut(|a| {+ let n = to(a.idx, a.files.len());+ (!a.files.is_empty() && n != a.idx).then(|| a.idx = n).is_some()+ });+ if moved {+ load(hwnd);+ }+}++/// (scale, x, y) of the picture inside a client area of cw x ch.+fn view(a: &App, cw: f64, ch: f64) -> Option<(f64, f64, f64)> {+ let i = a.img.as_ref()?;+ let z = a.zoom.unwrap_or_else(|| (cw / i.w as f64).min(ch / i.h as f64).min(1.0));+ Some((z, (cw - i.w as f64 * z) / 2.0 + a.off.0, (ch - i.h as f64 * z) / 2.0 + a.off.1))+}++fn title(hwnd: HWND) {+ let t = APP.with_borrow(|a| match (a.files.get(a.idx), &a.img) {+ (Some(p), img) => {+ let name = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();+ let size = img.as_ref().map_or(String::new(), |i| format!(" {}x{}", i.w, i.h));+ format!("{name} ({}/{}){size} - Photo viewer", a.idx + 1, a.files.len())+ }+ _ => "Photo viewer".into(),+ });+ unsafe { SetWindowTextW(hwnd, wide(&t).as_ptr()) };+}++unsafe fn paint(hwnd: HWND) {+ unsafe {+ let mut ps: PAINTSTRUCT = std::mem::zeroed();+ let dc = BeginPaint(hwnd, &mut ps);+ let mut rc: RECT = std::mem::zeroed();+ GetClientRect(hwnd, &mut rc);+ let (cw, ch) = (rc.right, rc.bottom);+ let mem = CreateCompatibleDC(dc);+ let bmp = CreateCompatibleBitmap(dc, cw, ch);+ let old = SelectObject(mem, bmp);+ let b = CreateSolidBrush(BG[2] as u32 | (BG[1] as u32) << 8 | (BG[0] as u32) << 16);+ FillRect(mem, &rc, b);+ DeleteObject(b as _);+ APP.with_borrow(|a| {+ if let (Some(i), Some((z, x, y))) = (&a.img, view(a, cw as f64, ch as f64)) {+ let mut bi: BITMAPINFO = std::mem::zeroed();+ bi.bmiHeader = BITMAPINFOHEADER { biSize: size_of::<BITMAPINFOHEADER>() as u32, biWidth: i.w, biHeight: -i.h, biPlanes: 1, biBitCount: 32, biCompression: BI_RGB, ..std::mem::zeroed() };+ SetStretchBltMode(mem, if z < 1.0 { HALFTONE } else { COLORONCOLOR } as _);+ SetBrushOrgEx(mem, 0, 0, null_mut());+ StretchDIBits(mem, x as i32, y as i32, (i.w as f64 * z).round() as i32, (i.h as f64 * z).round() as i32, 0, 0, i.w, i.h, i.bgra.as_ptr() as _, &bi, DIB_RGB_COLORS, SRCCOPY);+ } else {+ SelectObject(mem, a.font as _);+ SetBkMode(mem, TRANSPARENT as _);+ SetTextColor(mem, 0x91_98_a6);+ let mut r = rc;+ let t = wide(if a.files.is_empty() { "Open a picture with this program, or drop one here" } else { &a.note });+ DrawTextW(mem, t.as_ptr(), -1, &mut r, DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX);+ }+ });+ BitBlt(dc, 0, 0, cw, ch, mem, 0, 0, SRCCOPY);+ SelectObject(mem, old);+ DeleteObject(bmp as _);+ DeleteDC(mem);+ EndPaint(hwnd, &ps);+ }+}++/// Moves the current file to the Recycle Bin (Explorer asks first) and shows the next picture.+fn delete_current(hwnd: HWND) {+ let Some(p) = APP.with_borrow(|a| a.files.get(a.idx).cloned()) else { return };+ let mut from = wide(&p.to_string_lossy());+ from.push(0); // the list ends with a double NUL+ let mut op: SHFILEOPSTRUCTW = unsafe { std::mem::zeroed() };+ (op.hwnd, op.wFunc, op.pFrom, op.fFlags) = (hwnd, FO_DELETE, from.as_ptr(), FOF_ALLOWUNDO as u16);+ if unsafe { SHFileOperationW(&mut op) } == 0 && op.fAnyOperationsAborted == 0 {+ APP.with_borrow_mut(|a| {+ a.files.remove(a.idx);+ a.idx = a.idx.min(a.files.len().saturating_sub(1));+ a.img = None;+ });+ load(hwnd);+ }+}++unsafe extern "system" fn proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {+ unsafe {+ let client = || {+ let mut rc: RECT = std::mem::zeroed();+ GetClientRect(hwnd, &mut rc);+ (rc.right as f64, rc.bottom as f64)+ };+ match msg {+ WM_CREATE => {+ let dpi = GetDpiForSystem() as i32;+ let f = CreateFontW(-(18 * dpi / 96), 0, 0, 0, 400, 0, 0, 0, 1, 0, 0, 5, 0, wide("Segoe UI").as_ptr());+ APP.with_borrow_mut(|a| (a.dpi, a.font) = (dpi, f as isize));+ DragAcceptFiles(hwnd, 1);+ 0+ }+ WM_PAINT => {+ paint(hwnd);+ 0+ }+ WM_ERASEBKGND => 1,+ WM_SIZE => {+ InvalidateRect(hwnd, null(), 0);+ 0+ }+ WM_DROPFILES => {+ let d = wp as HDROP;+ let mut buf = [0u16; 1024];+ let n = DragQueryFileW(d, 0, buf.as_mut_ptr(), buf.len() as u32) as usize;+ DragFinish(d);+ open(hwnd, Path::new(&String::from_utf16_lossy(&buf[..n])));+ 0+ }+ WM_IMG => {+ let (g, r) = *Box::from_raw(lp as *mut (u32, Result<decode::Img, String>));+ if g == GEN.load(Relaxed) {+ APP.with_borrow_mut(|a| match r {+ Ok(i) => (a.img, a.note) = (Some(i), String::new()),+ Err(e) => (a.img, a.note) = (None, format!("Cannot open this picture: {e}")),+ });+ InvalidateRect(hwnd, null(), 0);+ title(hwnd);+ }+ 0+ }+ WM_MOUSEWHEEL => {+ let mut p = POINT { x: (lp & 0xFFFF) as i16 as i32, y: (lp >> 16) as i16 as i32 };+ ScreenToClient(hwnd, &mut p);+ let (cw, ch) = client();+ let k = if (wp >> 16) as i16 > 0 { 1.15 } else { 1.0 / 1.15 };+ APP.with_borrow_mut(|a| {+ if let (Some(i), Some((z, x, y))) = (&a.img, view(a, cw, ch)) {+ let z2 = (z * k).clamp(0.02, 32.0);+ // keep the image point under the cursor where it is+ let (u, v) = ((p.x as f64 - x) / z, (p.y as f64 - y) / z);+ a.off = (p.x as f64 - u * z2 - (cw - i.w as f64 * z2) / 2.0, p.y as f64 - v * z2 - (ch - i.h as f64 * z2) / 2.0);+ a.zoom = Some(z2);+ }+ });+ InvalidateRect(hwnd, null(), 0);+ 0+ }+ WM_LBUTTONDOWN => {+ SetCapture(hwnd);+ APP.with_borrow_mut(|a| a.drag = Some(((lp & 0xFFFF) as i16 as i32, (lp >> 16) as i16 as i32)));+ 0+ }+ WM_MOUSEMOVE => {+ let (x, y) = ((lp & 0xFFFF) as i16 as i32, (lp >> 16) as i16 as i32);+ let moved = APP.with_borrow_mut(|a| {+ let Some((px, py)) = a.drag else { return false };+ a.off = (a.off.0 + (x - px) as f64, a.off.1 + (y - py) as f64);+ a.drag = Some((x, y));+ true+ });+ if moved {+ InvalidateRect(hwnd, null(), 0);+ }+ 0+ }+ WM_LBUTTONUP => {+ ReleaseCapture();+ APP.with_borrow_mut(|a| a.drag = None);+ 0+ }+ WM_LBUTTONDBLCLK => {+ APP.with_borrow_mut(|a| (a.zoom, a.off) = (a.zoom.is_none().then_some(1.0), (0.0, 0.0)));+ InvalidateRect(hwnd, null(), 0);+ 0+ }+ WM_KEYDOWN => {+ match wp as u16 {+ VK_ESCAPE => {+ DestroyWindow(hwnd);+ }+ VK_RIGHT | VK_SPACE | VK_NEXT => go(hwnd, |i, n| (i + 1).min(n.saturating_sub(1))),+ VK_LEFT | VK_BACK | VK_PRIOR => go(hwnd, |i, _| i.saturating_sub(1)),+ VK_HOME => go(hwnd, |_, _| 0),+ VK_END => go(hwnd, |_, n| n.saturating_sub(1)),+ VK_DELETE => delete_current(hwnd),+ k if k == b'1' as u16 || k == b'F' as u16 || k == b'0' as u16 => {+ APP.with_borrow_mut(|a| (a.zoom, a.off) = (if k == b'1' as u16 { Some(1.0) } else { None }, (0.0, 0.0)));+ InvalidateRect(hwnd, null(), 0);+ }+ _ => {}+ }+ 0+ }+ WM_DESTROY => {+ PostQuitMessage(0);+ 0+ }+ _ => DefWindowProcW(hwnd, msg, wp, lp),+ }+ }+}++fn main() {+ unsafe {+ decode::com_init();+ SetProcessDPIAware();+ let (inst, class) = (GetModuleHandleW(null()), wide("WinRustPhoto"));+ let wc = WNDCLASSW { style: CS_DBLCLKS, lpfnWndProc: Some(proc), cbClsExtra: 0, cbWndExtra: 0, hInstance: inst, hIcon: null_mut(), hCursor: LoadCursorW(null_mut(), IDC_ARROW), hbrBackground: null_mut(), lpszMenuName: null(), lpszClassName: class.as_ptr() };+ RegisterClassW(&wc);+ let hwnd = CreateWindowExW(0, class.as_ptr(), wide("Photo viewer").as_ptr(), WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, 1280, 800, null_mut(), null_mut(), inst, null());+ if let Some(p) = std::env::args_os().nth(1) {+ open(hwnd, Path::new(&p));+ }+ let mut m: MSG = std::mem::zeroed();+ while GetMessageW(&mut m, null_mut(), 0, 0) > 0 {+ TranslateMessage(&m);+ DispatchMessageW(&m);+ }+ }+}diff --git a/plugins/rs-du/Cargo.lock b/plugins/rs-du/Cargo.locknew file mode 100644index 0000000..c6f4764--- /dev/null+++ b/plugins/rs-du/Cargo.lock@@ -0,0 +1,25 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "rs-du"+version = "0.1.0"+dependencies = [+ "windows-sys",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]diff --git a/plugins/rs-du/Cargo.toml b/plugins/rs-du/Cargo.tomlnew file mode 100644index 0000000..d9fb4da--- /dev/null+++ b/plugins/rs-du/Cargo.toml@@ -0,0 +1,13 @@+[package]+name = "rs-du"+version = "0.1.0"+edition = "2024"++[dependencies]+windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_Console", "Win32_System_IO", "Win32_System_Ioctl"] }++[profile.release]+opt-level = 3+lto = true+panic = "abort"+codegen-units = 1diff --git a/plugins/rs-du/README.md b/plugins/rs-du/README.mdnew file mode 100644index 0000000..404e1de--- /dev/null+++ b/plugins/rs-du/README.md@@ -0,0 +1,56 @@+# rs-du: анализатор диска + чистильщик кешей++**Статус:** этап 1 работает на живом диске (1,5 млн записей за ~2–3 с). Чистильщик (`--clean`, `--apply`) написан, на живом диске ещё не проверен. Дубликаты не начаты.++Показывает за секунды, что занимает место на NTFS-диске, и помогает освободить его.++## Важное уточнение+Индекс `rust-search` хранит только `parent + name` (см. `Ent` в `rust-search/src/main.rs`), **размеров в нём нет**.+Поэтому rs-du читает MFT сам и берёт размер из атрибута `$DATA` (и `$FILE_NAME`) каждой записи.+Код обхода MFT берём из `rust-search` как образец, индекс не меняем.++## Функционал++### 1. Анализ (этап 1)+- `rs-du [диск]`: проход по MFT, размеры суммируются вверх по дереву `parent`.+- Вывод: топ-N папок и файлов по размеру, глубина дерева настраивается (`--depth`, `--top`).+- Считает реальный размер на диске (allocated), а не только логический. Флаг `--logical` переключает.+- Учитывает hardlink (один файл считается один раз), не заходит в junction и symlink.+- Вывод в консоль; `--json` для скриптов.+- Цель: диск на миллион файлов за секунды, а не минуты.++### 2. Чистильщик кешей (этап 2, `rs-du --clean`)+- Знает типовые места: `target` (Rust), `node_modules`, кеши cargo/npm/pip/nuget, `%TEMP%`, кеши браузеров, `$Recycle.Bin`.+- Режим по умолчанию только показывает, сколько можно освободить. Удаление только с `--apply`.+- Для проектов (`target`, `node_modules`) удаляет только если рядом лежит `Cargo.toml` / `package.json`.+- Перед удалением пишет список в лог для проверки; в корзину не кладёт (кеши пересоздаются).+- Не трогает системные папки и файлы, открытые процессами.++#### Чистка для обычного пользователя (`src/clean.rs`)+Каждый пункт: понятное название, пояснение и цвет риска.+- **Безопасно** (зелёное): Temp, отчёты об ошибках и дампы, кеш обновлений Windows, INetCache.+- **Можно удалить** (жёлтое, пересоздастся): кеш Chrome/Edge/Яндекс/Brave/Firefox (пароли и история не трогаются), Telegram, Discord, Teams, VS Code, шейдеры NVIDIA/AMD/DirectX, Steam, кеши разработчика, `target`/`node_modules`.+- **По выбору** (красное): корзина, `Windows.old`, старые установщики и архивы в «Загрузках» (>90 дней), большие забытые видео/архивы (>1 ГБ, не тронуты >180 дней, только в папках пользователя, не облако и не AppData).+- `target`/`node_modules` берутся только если сама папка и её дочерние (release, debug...) не менялись 30 дней. Пункты меньше 1 МБ не показываются.+- Режимы: `--clean` только список; `--clean --apply` зелёное+жёлтое; `--apply --safe` только зелёное; `--apply --all` всё; `--ask` нумерованный список и выбор (Enter, `a`, `n`, номера красных).+- Красные файлы из «Загрузок» и больших файлов не удаляются, а уходят в карантин `X:\.rs-du-quarantine` на 30 дней. `rs-du --restore` возвращает, `rs-du --purge` освобождает место сразу.+- Не сделано: определение остатков удалённых программ, точка восстановления (вместо неё карантин), карта диска, дубликаты, GUI.++### 3. Дубликаты (этап 3, отдельно)+- Группировка по размеру, затем по хешу начала файла, затем по полному хешу.+- Только отчёт, удаление вручную или `--apply` с выбором, какую копию оставить.++## Чего не делаем+- Не-NTFS диски (как и в rust-search, пропускаются).+- Фоновая служба и расписание (может быть позже).+- GUI: сначала консоль.++## Права+Чтение MFT требует администратора (как rust-search).++## План+1. Читатель MFT с размерами + агрегация + вывод топа.+2. Замер на реальном диске, запись результата здесь.+3. Чистильщик.+4. Дубликаты.+5. Запись в `plugin-launcher` (карточка, `build-all.ps1`, `sync.ps1`).diff --git a/plugins/rs-du/src/clean.rs b/plugins/rs-du/src/clean.rsnew file mode 100644index 0000000..696fcc6--- /dev/null+++ b/plugins/rs-du/src/clean.rs@@ -0,0 +1,312 @@+// Cleaner for ordinary users: every item says what it is, how risky it is and how it goes away.+// Safe/Rebuild items regenerate on their own and are picked by default; Ask items (old files, recycle bin, Windows.old)+// are only removed when chosen. Files go to a per-drive quarantine for 30 days (`--restore`, `--purge`).+// shortcuts: Windows.old/SoftwareDistribution may need ownership rights (reported as "partly kept");+// leftovers of uninstalled programs in AppData are not detected; no restore point is created (quarantine instead).+use super::*;+use std::{cmp::Reverse, time::{Duration, SystemTime, UNIX_EPOCH}};+use windows_sys::Win32::System::Console::{ENABLE_VIRTUAL_TERMINAL_PROCESSING, GetConsoleMode, GetStdHandle, STD_OUTPUT_HANDLE, SetConsoleMode};++const QUAR_DAYS: u64 = 30;++#[derive(Clone, Copy, PartialEq, Eq)]+enum Risk { Safe, Rebuild, Ask }+#[derive(Clone, Copy, PartialEq, Eq)]+enum How { Wipe, Remove, Quarantine }++struct Item { risk: Risk, how: How, label: String, note: &'static str, paths: Vec<PathBuf>, bytes: u64 }++fn size_of(p: &Path) -> u64 { if p.is_dir() { dir_size(p) } else { p.metadata().map_or(0, |m| m.len()) } }++fn now() -> u64 { SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()) }++/// True when nothing touched the file (written, read, created) for `days`.+fn quiet_for(m: &fs::Metadata, days: u64) -> bool {+ [m.modified(), m.accessed(), m.created()].into_iter().flatten().max()+ .is_some_and(|t| t.elapsed().is_ok_and(|e| e > Duration::from_secs(days * 86400)))+}++/// A dir is idle when it and its direct children (release/, debug/, .package-lock.json...) are quiet for `days`.+fn idle(p: &Path, days: u64) -> bool {+ p.metadata().is_ok_and(|m| quiet_for(&m, days)) && fs::read_dir(p).into_iter().flatten().flatten().all(|e| e.metadata().is_ok_and(|m| quiet_for(&m, days)))+}++fn subdirs(base: &Path, pred: impl Fn(&str) -> bool) -> Vec<PathBuf> {+ fs::read_dir(base).into_iter().flatten().flatten()+ .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()) && pred(&e.file_name().to_string_lossy())).map(|e| e.path()).collect()+}++/// The known places. Paths that do not exist are dropped later, so rules for software you do not have cost nothing.+fn rules() -> Vec<Item> {+ let var = |k: &str| env::var_os(k).map(PathBuf::from);+ let (local, roam, home, win, pdata) = (var("LOCALAPPDATA"), var("APPDATA"), var("USERPROFILE"), var("SystemRoot"), var("ProgramData"));+ let at = |b: &Option<PathBuf>, rel: &[&str]| -> Vec<PathBuf> { b.iter().flat_map(|b| rel.iter().map(move |r| b.join(r))).collect() };+ let mut v: Vec<Item> = vec![];+ let mut add = |risk, label: &str, note, paths: Vec<PathBuf>| v.push(Item { risk, how: How::Wipe, label: label.into(), note, paths, bytes: 0 });++ add(Risk::Safe, "Временные файлы", "Мусор от программ и установщиков. Программы создадут нужное заново.",+ [var("TEMP").into_iter().collect::<Vec<_>>(), at(&win, &["Temp"])].concat());+ add(Risk::Safe, "Отчёты об ошибках и дампы падений", "Данные о сбоях программ для разработчиков. Вам они не нужны.",+ [at(&pdata, &["Microsoft/Windows/WER/ReportArchive", "Microsoft/Windows/WER/ReportQueue"]), at(&local, &["CrashDumps"]), at(&win, &["Minidump"])].concat());+ add(Risk::Safe, "Кеш обновлений Windows", "Уже установленные обновления. Что понадобится, Windows скачает заново.",+ at(&win, &["SoftwareDistribution/Download", "ServiceProfiles/NetworkService/AppData/Local/Microsoft/Windows/DeliveryOptimization/Cache"]));+ add(Risk::Safe, "Кеш интернета Windows", "Временные копии страниц и картинок для системных программ.", at(&local, &["Microsoft/Windows/INetCache"]));++ let web = "Копии страниц и картинок. Сайты первый раз откроются чуть медленнее. Пароли, закладки и история не затрагиваются.";+ for (name, rel) in [("Google Chrome", "Google/Chrome/User Data"), ("Microsoft Edge", "Microsoft/Edge/User Data"), ("Яндекс Браузер", "Yandex/YandexBrowser/User Data"), ("Brave", "BraveSoftware/Brave-Browser/User Data")] {+ let base = local.as_ref().map(|l| l.join(rel)).unwrap_or_default();+ let ps = subdirs(&base, |n| n == "Default" || n.starts_with("Profile ")).into_iter()+ .flat_map(|p| ["Cache/Cache_Data", "Code Cache", "GPUCache", "Service Worker/CacheStorage"].map(|c| p.join(c))).collect();+ add(Risk::Rebuild, name, web, if base.as_os_str().is_empty() { vec![] } else { ps });+ }+ let ff = local.as_ref().map(|l| l.join("Mozilla/Firefox/Profiles")).unwrap_or_default();+ add(Risk::Rebuild, "Firefox", web, if ff.as_os_str().is_empty() { vec![] } else { subdirs(&ff, |_| true).into_iter().map(|p| p.join("cache2")).collect() });+ add(Risk::Rebuild, "Telegram: кеш медиа", "Картинки и видео из чатов. Скачаются снова, когда откроете чат.", at(&roam, &["Telegram Desktop/tdata/user_data/media_cache", "Telegram Desktop/tdata/user_data/cache"]));+ add(Risk::Rebuild, "Discord", "Кеш картинок и интерфейса. Создастся заново.", at(&roam, &["discord/Cache", "discord/Code Cache", "discord/GPUCache"]));+ add(Risk::Rebuild, "Microsoft Teams", "Кеш интерфейса и вложений. Создастся заново.", at(&roam, &["Microsoft/Teams/Cache", "Microsoft/Teams/blob_storage", "Microsoft/Teams/GPUCache", "Microsoft/Teams/tmp"]));+ add(Risk::Rebuild, "Visual Studio Code", "Кеш редактора. Создастся заново.", at(&roam, &["Code/Cache", "Code/CachedData", "Code/GPUCache", "Code/Code Cache"]));+ add(Risk::Rebuild, "Кеш шейдеров видеокарты (NVIDIA, AMD, DirectX)", "Игры пересоберут его сами, первый запуск игры может чуть подтормаживать.",+ at(&local, &["NVIDIA/DXCache", "NVIDIA/GLCache", "D3DSCache", "AMD/DxCache", "AMD/DxcCache"]));+ add(Risk::Rebuild, "Steam: кеш браузера", "Кеш встроенного браузера Steam. Игры не затрагиваются.", at(&local, &["Steam/htmlcache"]));+ add(Risk::Rebuild, "Кеши программистов (cargo, npm, pip, NuGet)", "Скачанные пакеты. Загрузятся снова при следующей сборке.",+ [at(&home, &[".cargo/registry/cache", ".cargo/registry/src"]), at(&local, &["npm-cache", "pip/cache", "NuGet/v3-cache"]), at(&roam, &["npm-cache"])].concat());+ if let Some(w) = win.as_ref().and_then(|w| w.parent()) {+ v.push(Item { risk: Risk::Ask, how: How::Remove, label: "Windows.old (прежняя версия Windows)".into(),+ note: "Нужна только для отката на старую Windows.", paths: vec![w.join("Windows.old")], bytes: 0 });+ }+ v+}++/// Project build dirs: target next to Cargo.toml, node_modules next to package.json (outermost only, never inside apps).+fn projects(recs: &HashMap<u32, Rec>, tot: &HashMap<u32, u64>, drive: char) -> (Vec<PathBuf>, u64) {+ let is_cand = |r: &Rec| r.dir && (r.name.eq_ignore_ascii_case("target") || r.name.eq_ignore_ascii_case("node_modules"));+ let parents: HashSet<u32> = recs.values().filter(|r| is_cand(r)).map(|r| r.parent).collect();+ let marks: HashSet<(u32, String)> = recs.values().filter(|r| !r.dir && parents.contains(&r.parent) && (r.name.eq_ignore_ascii_case("Cargo.toml") || r.name.eq_ignore_ascii_case("package.json"))).map(|r| (r.parent, r.name.to_ascii_lowercase())).collect();+ let ok = |r: &Rec| marks.contains(&(r.parent, if r.name.eq_ignore_ascii_case("target") { "cargo.toml" } else { "package.json" }.into()));+ let cands: HashSet<u32> = recs.iter().filter(|(_, r)| is_cand(r) && ok(r)).map(|(&i, _)| i).collect();+ let (mut out, mut bytes) = (vec![], 0);+ for &id in &cands {+ let (mut p, mut nested) = (recs[&id].parent, false);+ for _ in 0..128 { if cands.contains(&p) { nested = true; break; } if p == ROOT { break; } p = match recs.get(&p) { Some(x) => x.parent, None => break }; }+ if nested { continue; }+ let path = path_of(recs, id, drive).0;+ // installed apps ship their own node_modules (VS Code, Discord, Node, Unity...): deleting those breaks them+ let low = path.to_lowercase();+ if low.contains("\\appdata\\") || low[3..].starts_with("program files") || low[3..].starts_with("windows") { continue; }+ let p = PathBuf::from(path);+ if !idle(&p, 30) { continue; } // still being built or installed into: somebody is working here+ bytes += tot.get(&id).copied().unwrap_or(0);+ out.push(p);+ }+ (out, bytes)+}++/// Old installers and archives lying in Downloads (top level only).+fn old_downloads() -> Option<Item> {+ const EXT: [&str; 7] = ["exe", "msi", "msix", "iso", "zip", "rar", "7z"];+ let dl = env::var_os("USERPROFILE").map(|h| PathBuf::from(h).join("Downloads"))?;+ let paths: Vec<PathBuf> = fs::read_dir(&dl).ok()?.flatten().filter(|e| {+ let p = e.path();+ e.metadata().is_ok_and(|m| m.is_file() && quiet_for(&m, 90)) && p.extension().is_some_and(|x| EXT.contains(&x.to_string_lossy().to_lowercase().as_str()))+ }).map(|e| e.path()).collect();+ Some(Item { risk: Risk::Ask, how: How::Quarantine, label: format!("Старые установщики и архивы в «Загрузках» ({} шт., старше 90 дней)", paths.len()),+ note: "Скорее всего, программы уже установлены.", paths, bytes: 0 })+}++/// Biggest forgotten videos/archives/installers in the user's own folders (not cloud folders, not AppData).+fn big_old(recs: &HashMap<u32, Rec>, tot: &HashMap<u32, u64>, drive: char, skip: &[PathBuf]) -> Vec<Item> {+ const EXT: [&str; 10] = ["mp4", "mkv", "avi", "mov", "iso", "zip", "rar", "7z", "exe", "msi"];+ const NO: [&str; 6] = ["\\appdata\\", "\\programdata\\", "onedrive", "google drive", "dropbox", "yandex"];+ let mut c: Vec<(u64, u32)> = recs.iter()+ .filter(|(id, r)| !r.dir && tot.get(*id).is_some_and(|&s| s >= 1 << 30) && r.name.rsplit_once('.').is_some_and(|(_, e)| EXT.contains(&e.to_lowercase().as_str())))+ .map(|(&id, _)| (tot[&id], id)).collect();+ c.sort_by_key(|&(s, _)| Reverse(s));+ let mut out = vec![];+ for (s, id) in c {+ let p = PathBuf::from(path_of(recs, id, drive).0);+ let low = p.to_string_lossy().to_lowercase();+ if !low[3..].starts_with("users\\") || NO.iter().any(|k| low.contains(k)) || skip.contains(&p) || !p.metadata().is_ok_and(|m| quiet_for(&m, 180)) { continue; }+ out.push(Item { risk: Risk::Ask, how: How::Quarantine, label: p.to_string_lossy().into(), note: "Большой файл, который давно не открывали.", paths: vec![p], bytes: s });+ if out.len() == 15 { break; }+ }+ out+}++fn vt() -> bool {+ unsafe {+ let h = GetStdHandle(STD_OUTPUT_HANDLE);+ let mut m = 0;+ GetConsoleMode(h, &mut m) != 0 && SetConsoleMode(h, m | ENABLE_VIRTUAL_TERMINAL_PROCESSING) != 0+ }+}++/// Enter = defaults, "a" = everything, "n" = nothing, numbers (1-based, any separator) = defaults plus those.+fn select(s: &str, sel: &mut [bool]) {+ match s.trim().to_lowercase().as_str() {+ "n" | "q" => sel.fill(false),+ "a" => sel.fill(true),+ t => for n in t.split(|c: char| !c.is_ascii_digit()).filter_map(|x| x.parse::<usize>().ok()) {+ if let Some(x) = sel.get_mut(n.wrapping_sub(1)) { *x = true; }+ },+ }+}++fn qroot(p: &Path) -> PathBuf { PathBuf::from(format!("{}:\\.rs-du-quarantine", p.to_string_lossy().chars().next().unwrap_or('C'))) }++fn quarantine(p: &Path, stamp: u64, n: usize) -> bool {+ let root = qroot(p);+ let dir = root.join(stamp.to_string());+ let to = dir.join(format!("{n}_{}", p.file_name().unwrap_or_default().to_string_lossy()));+ let ok = fs::create_dir_all(&dir).is_ok() && fs::rename(p, &to).is_ok();+ if ok && let Ok(mut f) = fs::OpenOptions::new().append(true).create(true).open(root.join("manifest.tsv")) {+ let _ = writeln!(f, "{stamp}\t{}\t{}", p.display(), to.display());+ }+ ok+}++type Row = (u64, PathBuf, PathBuf); // (when, original path, quarantined path)++fn manifest(drive: char) -> (PathBuf, Vec<Row>) {+ let m = PathBuf::from(format!("{drive}:\\.rs-du-quarantine\\manifest.tsv"));+ let rows = fs::read_to_string(&m).unwrap_or_default().lines().filter_map(|l| {+ let mut s = l.splitn(3, '\t');+ Some((s.next()?.parse().ok()?, s.next()?.into(), s.next()?.into()))+ }).collect();+ (m, rows)+}++fn save(m: &Path, rows: &[Row]) {+ let _ = fs::write(m, rows.iter().map(|(t, a, b)| format!("{t}\t{}\t{}\n", a.display(), b.display())).collect::<String>());+}++fn remove(p: &Path) { let _ = if p.is_dir() { fs::remove_dir_all(p) } else { fs::remove_file(p) }; }++/// Deletes quarantined items older than 30 days (all of them with `all`). This is when the space really comes back.+pub fn purge(drive: char, all: bool) {+ let (m, rows) = manifest(drive);+ let (mut keep, mut freed) = (vec![], 0);+ for r in rows {+ if all || now().saturating_sub(r.0) > QUAR_DAYS * 86400 {+ let before = size_of(&r.2);+ remove(&r.2);+ freed += before.saturating_sub(size_of(&r.2));+ if !r.2.exists() { continue; }+ }+ keep.push(r);+ }+ save(&m, &keep);+ for d in subdirs(m.parent().unwrap_or(Path::new("")), |_| true) { let _ = fs::remove_dir(d); } // only empty ones go+ if freed > 0 { println!("quarantine emptied: {} freed", human(freed)); }+}++/// Puts quarantined items back where they were.+pub fn restore(drive: char) {+ let (m, rows) = manifest(drive);+ let mut keep = vec![];+ for r in rows {+ if !r.2.exists() { continue; }+ if r.1.exists() { println!("not restored (the place is taken): {}", r.1.display()); keep.push(r); continue; }+ let moved = r.1.parent().is_some_and(|d| fs::create_dir_all(d).is_ok()) && fs::rename(&r.2, &r.1).is_ok();+ println!("{} {}", if moved { "restored" } else { "FAILED" }, r.1.display());+ if !moved { keep.push(r); }+ }+ save(&m, &keep);+}++pub fn clean(recs: &HashMap<u32, Rec>, tot: &HashMap<u32, u64>, drive: char, apply: bool, ask: bool, all: bool, safe_only: bool) {+ let mut items = rules();+ let (proj, pb) = projects(recs, tot, drive);+ items.push(Item { risk: Risk::Rebuild, how: How::Remove, label: "Папки сборки проектов (target, node_modules)".into(), note: "Пересоберутся при следующей сборке или npm install.", paths: proj, bytes: pb });+ items.push(Item { risk: Risk::Ask, how: How::Wipe, label: "Корзина".into(), note: "Файлы, которые вы уже удалили.", paths: vec![PathBuf::from(format!("{drive}:\\$Recycle.Bin"))], bytes: 0 }); // per-user subfolders need admin+ let dl = old_downloads();+ let skip = dl.as_ref().map(|d| d.paths.clone()).unwrap_or_default();+ items.extend(dl);+ items.extend(big_old(recs, tot, drive, &skip));+ items.retain_mut(|i| {+ i.paths.retain(|p| p.exists());+ if i.bytes == 0 { i.bytes = i.paths.iter().map(|p| size_of(p)).sum(); }+ i.bytes >= 1 << 20 // crumbs (an "empty" recycle bin is 987 bytes) are noise+ });+ items.sort_by_key(|i| (i.risk as u8, Reverse(i.bytes)));++ let c = vt();+ let (rst, col) = (if c { "\x1b[0m" } else { "" }, |r: Risk| if !c { "" } else { match r { Risk::Safe => "\x1b[32m", Risk::Rebuild => "\x1b[33m", Risk::Ask => "\x1b[31m" } });+ let mut last = None;+ for (n, i) in items.iter().enumerate() {+ if last != Some(i.risk) {+ last = Some(i.risk);+ println!("\n{}{}{rst}", col(i.risk), match i.risk {+ Risk::Safe => "БЕЗОПАСНО: Windows и программы создадут это заново сами",+ Risk::Rebuild => "МОЖНО УДАЛИТЬ: пересоздастся, но первое время может работать чуть медленнее",+ Risk::Ask => "ТОЛЬКО ПО ВАШЕМУ ВЫБОРУ: проверьте, что это вам не нужно",+ });+ }+ let fate = match (i.risk, i.how) { (Risk::Ask, How::Quarantine) => " Уйдёт в карантин на 30 дней, можно вернуть (rs-du --restore).", (Risk::Ask, _) => " Удалится навсегда.", _ => "" };+ println!("{:>3}. {:>9} {}\n{:>16}{}{fate}", n + 1, human(i.bytes), i.label, "", i.note);+ }+ let mut sel: Vec<bool> = items.iter().map(|i| all || if safe_only { i.risk == Risk::Safe } else { i.risk != Risk::Ask }).collect();+ let sum = |sel: &[bool]| -> u64 { items.iter().zip(sel).filter(|(_, s)| **s).map(|(i, _)| i.bytes).sum() };+ println!("\nМожно освободить: {} безопасно, {} всего ({} мест)", human(sum(&sel)), human(items.iter().map(|i| i.bytes).sum()), items.len());+ let line = |p: &str| { print!("{p}"); let _ = std::io::stdout().flush(); let mut l = String::new(); let _ = std::io::stdin().read_line(&mut l); l };+ if !apply && !ask { println!("(только просмотр; --apply удалит безопасное, --apply --all всё, --apply --safe только зелёное)"); return; }+ if !apply {+ select(&line("Enter = очистить безопасное (зелёное и жёлтое), a = всё, 12,13 = безопасное + эти номера, n = отмена: "), &mut sel);+ }+ if !sel.contains(&true) { if ask { line("Ничего не удалено. Нажмите Enter, чтобы закрыть."); } return; }++ purge(drive, false);+ let log = env::var_os("LOCALAPPDATA").map(|l| PathBuf::from(l).join("rs-du")).unwrap_or_default();+ let _ = fs::create_dir_all(&log);+ if let Ok(mut f) = fs::File::create(log.join("clean-log.txt")) {+ for (i, _) in items.iter().zip(&sel).filter(|(_, s)| **s) { for p in &i.paths { let _ = writeln!(f, "{}\t{}", i.bytes, p.display()); } }+ }+ let (stamp, mut seq, mut freed, mut held) = (now(), 0, 0u64, 0u64);+ for (i, _) in items.iter().zip(&sel).filter(|(_, s)| **s) {+ for p in &i.paths {+ match i.how {+ How::Wipe => wipe(p),+ How::Remove => remove(p),+ How::Quarantine => { seq += 1; if !quarantine(p, stamp, seq) { println!("не удалось убрать: {}", p.display()); } }+ }+ }+ let left: u64 = i.paths.iter().map(|p| size_of(p)).sum();+ let gone = i.bytes.saturating_sub(left);+ if i.how == How::Quarantine { held += gone } else { freed += gone }+ if left > 0 && i.how != How::Quarantine { println!("частично осталось {} (занято программой или нет прав): {}", human(left), i.label); }+ }+ println!("\nОсвобождено: {}. В карантине: {} (место вернётся через {QUAR_DAYS} дней или после rs-du --purge).", human(freed), human(held));+ println!("Список: {}", log.join("clean-log.txt").display());+ if ask { line("Нажмите Enter, чтобы закрыть."); }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn select_defaults_all_none_and_numbers() {+ let mut s = [true, true, false, false];+ select("", &mut s); assert_eq!(s, [true, true, false, false]);+ select("4", &mut s); assert_eq!(s, [true, true, false, true]);+ select("3, 99,0", &mut s); assert_eq!(s, [true, true, true, true]);+ select("n", &mut s); assert_eq!(s, [false; 4]);+ select("a", &mut s); assert_eq!(s, [true; 4]);+ }++ #[test]+ fn rule_paths_are_absolute() {+ // a missing env var must never turn into a relative path that wipes something in the current dir+ for i in rules() { for p in &i.paths { assert!(p.is_absolute(), "{}", p.display()); } }+ }++ #[test]+ fn manifest_round_trip() {+ let d = env::temp_dir().join("rs-du-test-manifest");+ let _ = fs::create_dir_all(&d);+ let m = d.join("manifest.tsv");+ save(&m, &[(5, "C:\\a".into(), "C:\\q\\1_a".into())]);+ let rows: Vec<Row> = fs::read_to_string(&m).unwrap().lines().filter_map(|l| { let mut s = l.splitn(3, '\t'); Some((s.next()?.parse().ok()?, s.next()?.into(), s.next()?.into())) }).collect();+ assert_eq!(rows, vec![(5, PathBuf::from("C:\\a"), PathBuf::from("C:\\q\\1_a"))]);+ let _ = fs::remove_dir_all(&d);+ }+}diff --git a/plugins/rs-du/src/main.rs b/plugins/rs-du/src/main.rsnew file mode 100644index 0000000..75eaa4e--- /dev/null+++ b/plugins/rs-du/src/main.rs@@ -0,0 +1,130 @@+// rs-du [X:] [--top N] [--depth D] [--logical] [--json]+// rs-du [X:] --clean --ask numbered list by risk, asks what to clean, waits for Enter at the end (used by the topbar menu)+// rs-du [X:] --clean [--apply [--all|--safe]] list (or delete: default = green+yellow, --all = everything, --safe = green only)+// rs-du [X:] --restore | --purge bring quarantined files back | empty the quarantine now (it also empties itself after 30 days)+mod clean;+mod mft;+use mft::*;+// Reads the NTFS MFT (see mft.rs), sums sizes up the parent chain, prints the biggest folders and files. Needs admin (raw volume handle).+// shortcuts: attribute lists / extension records are ignored (very fragmented files are undercounted),+// folder index sizes are not counted; upgrade if numbers drift from Explorer.+use std::{collections::{HashMap, HashSet}, env, fs, io::Write, path::{Path, PathBuf}};++/// Bytes under `p`, not following symlinks/junctions.+fn dir_size(p: &Path) -> u64 {+ let Ok(rd) = fs::read_dir(p) else { return 0 };+ rd.flatten().map(|e| match e.file_type() { Ok(t) if t.is_dir() => dir_size(&e.path()), Ok(t) if t.is_symlink() => 0, _ => e.metadata().map_or(0, |m| m.len()) }).sum()+}++fn wipe(p: &Path) {+ if let Ok(rd) = fs::read_dir(p) {+ for e in rd.flatten() {+ let q = e.path();+ let _ = if e.file_type().is_ok_and(|t| t.is_dir()) { fs::remove_dir_all(&q) } else { fs::remove_file(&q) }; // locked/in-use: skipped+ }+ }+}++fn main() {+ let a: Vec<String> = env::args().skip(1).collect();+ let flag = |f: &str| a.iter().any(|x| x == f);+ let val = |f: &str, d: usize| a.iter().position(|x| x == f).and_then(|i| a.get(i + 1)?.parse().ok()).unwrap_or(d);+ let drive = a.first().filter(|x| x.len() == 2 && x.ends_with(':')).and_then(|x| x.chars().next()).unwrap_or('C').to_ascii_uppercase();+ let (top, depth, logical, json) = (val("--top", 20), val("--depth", 2), flag("--logical"), flag("--json"));+ if flag("--restore") { return clean::restore(drive); }+ if flag("--purge") { return clean::purge(drive, true); }+ let t = std::time::Instant::now();+ let recs = scan(drive).unwrap_or_else(|e| { eprintln!("{e}"); std::process::exit(1) });+ let tot = totals(&recs, logical);+ if flag("--clean") { clean::clean(&recs, &tot, drive, flag("--apply"), flag("--ask"), flag("--all"), flag("--safe")); return; }+ let mut dirs: Vec<(u32, u64)> = vec![];+ let mut files: Vec<(u32, u64)> = vec![];+ for (&id, &s) in &tot {+ match recs.get(&id) { Some(r) if r.dir && id != ROOT => dirs.push((id, s)), Some(_) if id != ROOT => files.push((id, s)), _ => {} }+ }+ dirs.retain(|&(id, _)| path_of(&recs, id, drive).1 <= depth);+ dirs.sort_by_key(|&(_, s)| std::cmp::Reverse(s));+ files.sort_by_key(|&(_, s)| std::cmp::Reverse(s));+ let rows = |v: &[(u32, u64)]| -> Vec<(String, u64)> { v.iter().take(top).map(|&(id, s)| (path_of(&recs, id, drive).0, s)).collect() };+ let (d, f) = (rows(&dirs), rows(&files));+ if json {+ let j = |v: &[(String, u64)]| v.iter().map(|(p, s)| format!("{{\"path\":\"{}\",\"bytes\":{s}}}", p.replace('\\', "\\\\").replace('"', "\\\""))).collect::<Vec<_>>().join(",");+ println!("{{\"drive\":\"{drive}\",\"folders\":[{}],\"files\":[{}]}}", j(&d), j(&f));+ } else {+ println!("{drive}: {} records, {} total ({}), {:.2}s", recs.len(), human(tot.get(&ROOT).copied().unwrap_or(0)), if logical { "logical" } else { "on disk" }, t.elapsed().as_secs_f32());+ println!("\nFolders (depth <= {depth}):");+ for (p, s) in &d { println!("{:>10} {p}", human(*s)); }+ println!("\nFiles:");+ for (p, s) in &f { println!("{:>10} {p}", human(*s)); }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn record() -> Vec<u8> {+ let mut b = vec![0u8; 1024];+ b[..4].copy_from_slice(b"FILE");+ b[4] = 0x30; b[6] = 3; // usa at 0x30, 3 entries+ b[0x30] = 1; // seq+ b[510] = 1; b[1022] = 1;+ b[0x14] = 0x38; b[0x16] = 1; // first attr, in use+ let mut o = 0x38;+ // $FILE_NAME resident: parent=5, name "ab", Win32+ b[o..o + 4].copy_from_slice(&0x30u32.to_le_bytes());+ b[o + 4] = 0x70; b[o + 0x14] = 0x18;+ let c = o + 0x18;+ b[c] = 5; b[c + 0x40] = 2; b[c + 0x41] = 1;+ b[c + 0x42..c + 0x46].copy_from_slice(&[b'a', 0, b'b', 0]);+ o += 0x70;+ // $DATA non-resident: alloc 8192, real 5000+ b[o..o + 4].copy_from_slice(&0x80u32.to_le_bytes());+ b[o + 4] = 0x48; b[o + 8] = 1;+ b[o + 0x28..o + 0x30].copy_from_slice(&8192u64.to_le_bytes());+ b[o + 0x30..o + 0x38].copy_from_slice(&5000u64.to_le_bytes());+ o += 0x48;+ b[o..o + 4].copy_from_slice(&0xFFFF_FFFFu32.to_le_bytes());+ b[0x18] = (o + 8) as u8; b[0x19] = ((o + 8) >> 8) as u8;+ b+ }++ #[test]+ fn parses_name_parent_sizes() {+ let (_, r) = parse(&mut record()).unwrap();+ assert_eq!((r.name.as_str(), r.parent, r.dir, r.alloc, r.logical), ("ab", 5, false, 8192, 5000));+ }++ #[test]+ fn torn_or_unused_records_are_rejected() {+ let mut b = record();+ b[510] = 9;+ assert!(parse(&mut b).is_none());+ let mut b = record();+ b[0x16] = 0;+ assert!(parse(&mut b).is_none());+ }++ #[test]+ fn wipe_empties_dir_but_keeps_it() {+ let d = env::temp_dir().join("rs-du-test-wipe");+ let _ = fs::remove_dir_all(&d);+ fs::create_dir_all(d.join("a/b")).unwrap();+ fs::write(d.join("a/b/f"), [0u8; 100]).unwrap();+ fs::write(d.join("g"), [0u8; 50]).unwrap();+ assert_eq!(dir_size(&d), 150);+ wipe(&d);+ assert!(d.is_dir() && dir_size(&d) == 0 && fs::read_dir(&d).unwrap().count() == 0);+ fs::remove_dir(&d).unwrap();+ }++ #[test]+ fn decodes_data_runs_with_negative_offsets() {+ let mut b = vec![0u8; 256];+ b[0x14] = 0x38;+ b[0x38..0x3C].copy_from_slice(&0x80u32.to_le_bytes());+ b[0x3C] = 0x48; b[0x40] = 1; b[0x58] = 0x40; // $DATA, non-resident, runlist at +0x40+ b[0x78..0x7F].copy_from_slice(&[0x21, 0x18, 0x34, 0x12, 0x11, 0x08, 0xFE]);+ assert_eq!(data_runs(&b).unwrap(), vec![(0x1234, 24), (0x1232, 8)]);+ }+}diff --git a/plugins/rs-du/src/mft.rs b/plugins/rs-du/src/mft.rsnew file mode 100644index 0000000..5eb1541--- /dev/null+++ b/plugins/rs-du/src/mft.rs@@ -0,0 +1,184 @@+// NTFS MFT reader shared by rs-du (console) and wiztree (GUI, includes this file by #[path]).+use std::{collections::HashMap, mem::size_of, ptr};+use windows_sys::Win32::{Foundation::*, Storage::FileSystem::*, System::{IO::DeviceIoControl, Ioctl::*}};++pub const MASK: u64 = 0xFFFF_FFFF_FFFF;+pub const ROOT: u32 = 5;++pub struct Rec { pub parent: u32, pub name: String, pub dir: bool, pub alloc: u64, pub logical: u64 }++pub fn rd(b: &[u8], o: usize, n: usize) -> Option<u64> {+ let s = b.get(o..o.checked_add(n)?)?;+ Some(s.iter().rev().fold(0u64, |a, &x| (a << 8) | x as u64))+}++/// Checks the "FILE" magic and undoes the update-sequence fixups. None for garbage or torn records.+pub fn fixup(b: &mut [u8]) -> Option<()> {+ if b.get(..4)? != b"FILE" { return None; }+ let (uo, uc) = (rd(b, 4, 2)? as usize, rd(b, 6, 2)? as usize);+ let seq = [*b.get(uo)?, *b.get(uo + 1)?];+ for i in 1..uc {+ let end = i * 512 - 2;+ if end + 2 > b.len() { break; }+ if b[end..end + 2] != seq { return None; } // torn record+ let (x, y) = (*b.get(uo + 2 * i)?, *b.get(uo + 2 * i + 1)?);+ b[end] = x;+ b[end + 1] = y;+ }+ Some(())+}++/// Data runs (lcn, clusters) of the first unnamed non-resident $DATA of a fixed-up record. Sparse runs have lcn 0.+pub fn data_runs(b: &[u8]) -> Option<Vec<(u64, u64)>> {+ let mut o = rd(b, 0x14, 2)? as usize;+ loop {+ let (ty, len) = (rd(b, o, 4)?, rd(b, o + 4, 4)? as usize);+ if ty == 0xFFFF_FFFF || len == 0 { return None; }+ if ty == 0x80 && rd(b, o + 8, 1)? != 0 && rd(b, o + 9, 1)? == 0 { break; }+ o += len;+ }+ let (mut p, mut lcn, mut runs) = (o + rd(b, o + 0x20, 2)? as usize, 0i64, vec![]);+ while let Some(&h) = b.get(p) {+ if h == 0 { break; }+ let (ln, on) = ((h & 15) as usize, (h >> 4) as usize);+ let clusters = rd(b, p + 1, ln)?;+ let off = rd(b, p + 1 + ln, on)?;+ let shift = 64 - 8 * on as u32;+ let delta = if on == 0 { 0 } else { ((off << shift) as i64) >> shift };+ lcn += delta;+ runs.push((if on == 0 { 0 } else { lcn as u64 }, clusters));+ p += 1 + ln + on;+ }+ Some(runs)+}++/// Parses one raw MFT record into (base record ref, what it holds). Extension records (base != 0) carry attributes+/// that did not fit in their base record (often $FILE_NAME or more $DATA); `merge` joins them. None for unused/garbage.+pub fn parse(b: &mut [u8]) -> Option<(u64, Rec)> {+ fixup(b)?;+ let flags = rd(b, 0x16, 2)?;+ let base = rd(b, 0x20, 8)? & MASK;+ if flags & 1 == 0 { return None; }+ let used = (rd(b, 0x18, 4)? as usize).min(b.len());+ let mut o = rd(b, 0x14, 2)? as usize;+ let (mut name, mut parent, mut ns) = (None::<String>, 0u32, 2u64);+ let (mut alloc, mut logical) = (0u64, 0u64);+ while o + 8 <= used {+ let ty = rd(b, o, 4)?;+ let len = rd(b, o + 4, 4)? as usize;+ if ty == 0xFFFF_FFFF || len == 0 || o + len > used { break; }+ let nonres = rd(b, o + 8, 1)? != 0;+ if ty == 0x30 && !nonres {+ let c = o + rd(b, o + 0x14, 2)? as usize;+ let n = rd(b, c + 0x41, 1)?;+ if name.is_none() || (ns == 2 && n != 2) { // prefer a non-DOS name+ let nl = rd(b, c + 0x40, 1)? as usize;+ let u16s: Vec<u16> = (0..nl).map(|i| rd(b, c + 0x42 + 2 * i, 2).unwrap_or(0) as u16).collect();+ name = Some(String::from_utf16_lossy(&u16s));+ parent = (rd(b, c, 8)? & MASK) as u32;+ ns = n;+ }+ } else if ty == 0x80 {+ if !nonres { logical += rd(b, o + 0x10, 4)?; }+ else if rd(b, o + 0x10, 8)? == 0 { alloc += rd(b, o + 0x28, 8)?; logical += rd(b, o + 0x30, 8)?; }+ }+ o += len;+ }+ Some((base, Rec { parent, name: name.unwrap_or_default(), dir: flags & 2 != 0, alloc, logical }))+}++pub fn merge(recs: &mut HashMap<u32, Rec>, id: u32, r: Rec) {+ match recs.entry(id) {+ std::collections::hash_map::Entry::Vacant(v) => { v.insert(r); }+ std::collections::hash_map::Entry::Occupied(o) => {+ let e = o.into_mut();+ if e.name.is_empty() { e.name = r.name; e.parent = r.parent; }+ e.dir |= r.dir;+ e.alloc += r.alloc;+ e.logical += r.logical;+ }+ }+}++pub fn scan(drive: char) -> Result<HashMap<u32, Rec>, String> {+ let path: Vec<u16> = format!("\\\\.\\{drive}:").encode_utf16().chain([0]).collect();+ let h = unsafe { CreateFileW(path.as_ptr(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, ptr::null(), OPEN_EXISTING, 0, ptr::null_mut()) };+ if h == INVALID_HANDLE_VALUE { return Err(format!("cannot open volume {drive}: (run as administrator), error {}", unsafe { GetLastError() })); }+ let mut vd: NTFS_VOLUME_DATA_BUFFER = unsafe { std::mem::zeroed() };+ let mut n = 0u32;+ let ok = unsafe { DeviceIoControl(h, FSCTL_GET_NTFS_VOLUME_DATA, ptr::null(), 0, &mut vd as *mut _ as _, size_of::<NTFS_VOLUME_DATA_BUFFER>() as u32, &mut n, ptr::null_mut()) };+ if ok == 0 { return Err(format!("{drive}: is not NTFS (error {})", unsafe { GetLastError() })); }+ let (rs, cl) = (vd.BytesPerFileRecordSegment as usize, vd.BytesPerCluster as u64);+ // Record 0 is $MFT itself: its data runs say where the whole table lives, then we read it in big chunks.+ let mut out = vec![0u8; 12 + rs];+ let inp = NTFS_FILE_RECORD_INPUT_BUFFER { FileReferenceNumber: 0 };+ let ok = unsafe { DeviceIoControl(h, FSCTL_GET_NTFS_FILE_RECORD, &inp as *const _ as _, size_of::<NTFS_FILE_RECORD_INPUT_BUFFER>() as u32, out.as_mut_ptr() as _, out.len() as u32, &mut n, ptr::null_mut()) };+ if ok == 0 { return Err(format!("cannot read the $MFT record, error {}", unsafe { GetLastError() })); }+ let rec0 = out[12..12 + rs].to_vec();+ // the ioctl already hands back a record with the fixups undone (raw reads below do not)+ let runs = data_runs(&rec0).ok_or("no $DATA runs in the $MFT record")?;+ let mut left = vd.MftValidDataLength as u64; // bytes of the table still to read+ let mut recs = HashMap::with_capacity(left as usize / rs / 2);+ let (mut idx, mut buf) = (0u32, vec![0u8; 4 << 20]);+ let (mut seen, mut magic) = (0u32, 0u32);+ for (lcn, clusters) in runs {+ let mut len = (clusters * cl).min(left);+ left -= len;+ if lcn == 0 { idx += (len / rs as u64) as u32; continue; } // sparse hole+ let mut pos = (lcn * cl) as i64;+ while len > 0 {+ let want = len.min(buf.len() as u64) as usize;+ let mut got = 0u32;+ let ok = unsafe { SetFilePointerEx(h, pos, ptr::null_mut(), FILE_BEGIN) != 0 && ReadFile(h, buf.as_mut_ptr() as _, want as u32, &mut got, ptr::null_mut()) != 0 };+ if !ok || got as usize != want { return Err(format!("reading the MFT failed at byte {pos}, error {}", unsafe { GetLastError() })); }+ for c in buf[..want].chunks_exact_mut(rs) {+ seen += 1;+ magic += (&c[..4] == b"FILE") as u32;+ if let Some((base, r)) = parse(c) { merge(&mut recs, if base == 0 { idx } else { base as u32 }, r); }+ idx += 1;+ }+ pos += want as i64;+ len -= want as u64;+ }+ }+ unsafe { CloseHandle(h) };+ recs.retain(|_, r| !r.name.is_empty()); // no $FILE_NAME anywhere (e.g. attribute list in a record we never saw)+ eprintln!("mft: {seen} slots read, {magic} with FILE magic, {} named", recs.len());+ Ok(recs)+}++pub fn path_of(recs: &HashMap<u32, Rec>, mut id: u32, drive: char) -> (String, usize) {+ let mut parts = vec![];+ for _ in 0..128 {+ if id == ROOT { break; }+ let Some(r) = recs.get(&id) else { parts.push("?".into()); break };+ parts.push(r.name.clone());+ id = r.parent;+ }+ let d = parts.len();+ parts.reverse();+ (format!("{drive}:\\{}", parts.join("\\")), d)+}++pub fn human(b: u64) -> String {+ let (mut v, mut i) = (b as f64, 0);+ while v >= 1024.0 && i < 4 { v /= 1024.0; i += 1; }+ format!("{v:.1} {}", ["B", "KB", "MB", "GB", "TB"][i])+}++/// Bytes under every record (a folder = everything below it), summed up the parent chain. Skips root and $BadClus.+pub fn totals(recs: &HashMap<u32, Rec>, logical: bool) -> HashMap<u32, u64> {+ let mut tot: HashMap<u32, u64> = HashMap::new();+ for (&id, r) in recs {+ let s = if logical { r.logical } else { r.alloc };+ if s == 0 || id == ROOT || id == 8 { continue; } // 8 = $BadClus, a sparse file that claims the whole volume+ *tot.entry(id).or_default() += s;+ let mut p = r.parent;+ for _ in 0..128 { // the cap also breaks parent cycles+ *tot.entry(p).or_default() += s;+ if p == ROOT { break; }+ p = match recs.get(&p) { Some(x) => x.parent, None => break };+ }+ }+ tot+}diff --git a/plugins/rs-shell/Cargo.lock b/plugins/rs-shell/Cargo.locknew file mode 100644index 0000000..9d40e91--- /dev/null+++ b/plugins/rs-shell/Cargo.lock@@ -0,0 +1,25 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "rs-shell"+version = "0.1.0"+dependencies = [+ "windows-sys",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]diff --git a/plugins/rs-shell/Cargo.toml b/plugins/rs-shell/Cargo.tomlnew file mode 100644index 0000000..2d31ec5--- /dev/null+++ b/plugins/rs-shell/Cargo.toml@@ -0,0 +1,16 @@+[package]+name = "rs-shell"+version = "0.1.0"+edition = "2024"++[dependencies]+windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Graphics_Dwm", "Win32_System_Console", "Win32_System_RemoteDesktop", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] }++[profile.release]+opt-level = "s"+lto = true+codegen-units = 1+panic = "abort"+strip = true++[workspace]diff --git a/plugins/rs-shell/src/main.rs b/plugins/rs-shell/src/main.rsnew file mode 100644index 0000000..0f9723f--- /dev/null+++ b/plugins/rs-shell/src/main.rs@@ -0,0 +1,381 @@+// rs-shell run as the user's shell: wallpaper, Run keys + Startup folders, topbar (restarted when it dies),+// explorer.exe as the fallback shell if topbar keeps dying+// rs-shell --enable make it THIS user's shell (HKCU Winlogon\Shell; other users and the system are untouched)+// rs-shell --disable back to the normal shell (deletes that one value)+// rs-shell --dry-run print what it would start, change nothing+// rs-shell --overlay run NEXT TO explorer.exe (it stays the shell): topbar + desktop + keep the bar alive. Started at logon by the "rs-overlay" scheduled task (HKCU Run as the fallback).+// Put it next to topbar.exe. Recovery from a black screen: Ctrl+Alt+Del -> Task Manager -> run explorer.exe,+// then `rs-shell --disable`; or sign in as another admin and run `reg delete` on the key printed by --enable.+// Also: starts `rust-explorer.exe --desktop` (desktop icons), Win+D = show desktop / bring the windows back,+// Win+E = file manager (rust-explorer.exe if next to us). Put rust-explorer.exe next to rs-shell.exe.+// shortcuts: Win+D only minimizes ordinary top-level windows (no per-monitor / virtual-desktop logic),+// Run/Startup entries are started through `cmd /c start` (no RunOnce, no startup-delay rules, no disabled-list in+// StartupApproved), topbar's "open" still shells out to explorer.exe for /select; upgrade when those matter.+use std::{os::windows::process::CommandExt, path::PathBuf, process::Command, ptr, sync::Mutex, thread, time::{Duration, Instant}};+use windows_sys::{core::BOOL, Win32::{Foundation::{HWND, LPARAM, RECT}, Graphics::Dwm::DwmGetWindowAttribute, UI::{Input::KeyboardAndMouse::{MOD_NOREPEAT, MOD_WIN, RegisterHotKey}, WindowsAndMessaging::*}}};++const WINLOGON: &str = r"HKCU\Software\Microsoft\Windows NT\CurrentVersion\Winlogon";+const NO_WINDOW: u32 = 0x0800_0000;++/// A Command with null std handles. After FreeConsole() the shell has no valid ones, and spawn() inheriting+/// them fails with "The handle is invalid" (this broke every start the first time).+fn quiet(program: impl AsRef<std::ffi::OsStr>) -> Command {+ let mut c = Command::new(program);+ c.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());+ c+}++fn reg(args: &[&str]) -> Option<String> {+ let o = Command::new("reg").args(args).creation_flags(NO_WINDOW).output().ok()?;+ o.status.success().then(|| String::from_utf8_lossy(&o.stdout).into_owned())+}++/// Commands from `reg query <Run key>` output: " Name REG_SZ command line".+fn parse_run(out: &str) -> Vec<String> {+ out.lines().filter_map(|l| {+ let (_, v) = l.split_once("REG_EXPAND_SZ").or_else(|| l.split_once("REG_SZ"))?;+ Some(v.trim().to_string()).filter(|v| !v.is_empty())+ }).collect()+}++/// The exe a Run command line points at, %VARS% expanded; None when it is not an .exe we can tell apart (scripts, URIs).+fn exe_path(cmd: &str) -> Option<String> {+ let mut c = cmd.trim().to_string();+ while let Some(a) = c.find('%') {+ let b = c[a + 1..].find('%')?;+ let val = std::env::var(&c[a + 1..a + 1 + b]).ok()?;+ c = format!("{}{}{}", &c[..a], val, &c[a + b + 2..]);+ }+ let path = match c.strip_prefix('"') {+ Some(rest) => rest.split('"').next()?.to_string(),+ None => c[..c.to_lowercase().find(".exe")? + 4].to_string(),+ };+ path.to_lowercase().ends_with(".exe").then_some(path)+}++/// Everything the shell should start at logon (commands for `cmd /c start ""`).+fn autostart() -> Vec<String> {+ let mut v = vec![];+ for key in [r"HKLM\Software\Microsoft\Windows\CurrentVersion\Run", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run"] {+ v.extend(reg(&["query", key]).map(|o| parse_run(&o)).unwrap_or_default());+ }+ let dirs = [std::env::var("APPDATA").map(|a| PathBuf::from(a).join(r"Microsoft\Windows\Start Menu\Programs\Startup")), std::env::var("ProgramData").map(|a| PathBuf::from(a).join(r"Microsoft\Windows\Start Menu\Programs\StartUp"))];+ for d in dirs.into_iter().flatten() {+ for e in std::fs::read_dir(d).into_iter().flatten().flatten() {+ if e.file_name().to_string_lossy().eq_ignore_ascii_case("desktop.ini") { continue; }+ v.push(format!("\"{}\"", e.path().display()));+ }+ }+ v.retain(|c| !c.to_lowercase().contains("rs-shell")); // never start ourselves twice+ // topbar's own helper (reshell) is started from our folder below, not from the Run entry that points into Program Files+ v.retain(|c| !c.to_lowercase().contains(r"\topbar\"));+ // a Run entry whose exe is gone is skipped silently by explorer; `cmd /c start` would pop an error dialog (Rave did)+ v.retain(|c| exe_path(c).is_none_or(|p| std::path::Path::new(&p).exists()));+ v+}++fn wide(s: &str) -> Vec<u16> { s.encode_utf16().chain([0]).collect() }++fn dir() -> PathBuf { std::env::current_exe().ok().and_then(|e| e.parent().map(|p| p.to_path_buf())).unwrap_or_default() }++/// An exe next to us, else the one the topbar plugin installed (the rust-explorer plugin keeps only its own files in its folder).+fn find_exe(name: &str) -> PathBuf {+ let own = dir().join(name);+ if own.exists() { return own; }+ PathBuf::from(std::env::var("ProgramFiles").unwrap_or_else(|_| r"C:\Program Files".into())).join("topbar").join(name)+}++fn bar_up() -> bool { unsafe { !FindWindowW(wide("topbar").as_ptr(), std::ptr::null()).is_null() } }++static HIDDEN: Mutex<Vec<isize>> = Mutex::new(Vec::new());++unsafe extern "system" fn collect(h: HWND, lp: LPARAM) -> BOOL {+ unsafe {+ let mut cloaked = 0u32; // DWMWA_CLOAKED: UWP ghosts that are "visible" but not on screen+ DwmGetWindowAttribute(h, 14, &mut cloaked as *mut _ as _, 4);+ let tool = GetWindowLongW(h, GWL_EXSTYLE) as u32 & WS_EX_TOOLWINDOW != 0; // topbar, desktop, tray hosts+ if IsWindowVisible(h) != 0 && IsIconic(h) == 0 && !tool && cloaked == 0 && GetWindow(h, GW_OWNER).is_null() && GetWindowTextLengthW(h) > 0 {+ (*(lp as *mut Vec<isize>)).push(h as isize);+ }+ 1+ }+}++/// A minimized window left on screen (or minimized before the hide setting was applied) shows as a caption stub on+/// the desktop: park it where Windows itself parks hidden minimized windows.+unsafe extern "system" fn park(h: HWND, _: LPARAM) -> BOOL {+ unsafe {+ if IsWindowVisible(h) != 0 && IsIconic(h) != 0 {+ let mut r: RECT = std::mem::zeroed();+ GetWindowRect(h, &mut r);+ if r.left > -30000 { SetWindowPos(h, ptr::null_mut(), -32000, -32000, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); }+ }+ 1+ }+}++/// Win+D: minimize everything, press again to bring the same windows back. Anything open on screen means "minimize":+/// after a window was brought back by hand the old list must not turn the next press into a silent "restore".+fn toggle_desktop() {+ let mut hid = HIDDEN.lock().unwrap();+ unsafe {+ let mut v: Vec<isize> = vec![];+ EnumWindows(Some(collect), &mut v as *mut _ as LPARAM);+ if !v.is_empty() {+ v.iter().for_each(|&h| { ShowWindow(h as HWND, SW_MINIMIZE); });+ *hid = v;+ } else {+ hid.iter().for_each(|&h| { if IsWindow(h as HWND) != 0 { ShowWindow(h as HWND, SW_RESTORE); } });+ hid.clear();+ }+ }+}++fn set_wallpaper() {+ let Some(src) = reg(&["query", r"HKCU\Control Panel\Desktop", "/v", "WallPaper"]).map(|o| parse_run(&o)).and_then(|v| v.into_iter().next()) else { return };+ let mut path = PathBuf::from(&src);+ // without explorer's image transcoder the desktop paints only BMP: convert once (System.Drawing) and keep the copy+ if !src.to_lowercase().ends_with(".bmp") {+ let Ok(base) = std::env::var("LOCALAPPDATA") else { return };+ let bmp = PathBuf::from(base).join("rs-shell").join("wallpaper.bmp");+ let modified = |p: &std::path::Path| std::fs::metadata(p).and_then(|m| m.modified()).ok();+ if modified(&bmp) < modified(&PathBuf::from(&src)) {+ let _ = std::fs::create_dir_all(bmp.parent().unwrap_or(&bmp));+ let script = format!("Add-Type -AssemblyName System.Drawing; $i=[Drawing.Image]::FromFile('{}'); $i.Save('{}',[Drawing.Imaging.ImageFormat]::Bmp)", src.replace('\'', "''"), bmp.display().to_string().replace('\'', "''"));+ let _ = quiet("powershell").args(["-NoProfile", "-NonInteractive", "-Command", &script]).creation_flags(NO_WINDOW).status();+ }+ path = bmp;+ }+ unsafe { SystemParametersInfoW(0x14, 0, wide(&path.to_string_lossy()).as_ptr() as _, 0) }; // SPI_SETDESKWALLPAPER+}++/// Appends a line to %LOCALAPPDATA%\rs-shell\log.txt: a shell has no console, so this is the only way to see what it did.+fn log(msg: &str) {+ use std::io::Write;+ let Ok(base) = std::env::var("LOCALAPPDATA") else { return };+ let dir = PathBuf::from(base).join("rs-shell");+ let _ = std::fs::create_dir_all(&dir);+ let t = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());+ if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("log.txt")) { let _ = writeln!(f, "[{t}] {msg}"); }+}++fn run_shell() {+ unsafe { windows_sys::Win32::System::Console::FreeConsole() };+ log("start");+ // without explorer a minimized window is drawn as a little caption stub on the desktop (apps started with+ // --minimized left grey rectangles over the icons): hide them, the bar lists the windows anyway+ let mut mm = MINIMIZEDMETRICS { cbSize: size_of::<MINIMIZEDMETRICS>() as u32, iWidth: 0, iHorzGap: 0, iVertGap: 0, iArrange: ARW_HIDE as i32 };+ unsafe { SystemParametersInfoW(SPI_SETMINIMIZEDMETRICS, mm.cbSize, &mut mm as *mut _ as _, 0) };+ // the desktop is blank without explorer: repaint the user's wallpaper (again below, once the session has settled)+ thread::spawn(set_wallpaper); // the first conversion takes a second or two; do not hold up autostart+ let list = autostart();+ log(&format!("autostart: {} entries", list.len()));+ for c in list {+ let r = quiet("cmd").raw_arg(format!("/c start \"\" {c}")).creation_flags(NO_WINDOW).spawn();+ log(&format!("start {c} -> {:?}", r.map(|_| ())));+ }+ thread::sleep(Duration::from_secs(4)); // topbar may already have been started by its own Run entry+ set_wallpaper();+ // no bar yet (its logon task is gone in user mode): start it and its hotkey helper from our folder, with our normal rights+ if !bar_up() { log(&format!("topbar spawn -> {:?}", quiet(find_exe("topbar.exe")).spawn().map(|_| ()))); }+ let hotkeys = dir().join("reshell.exe");+ if hotkeys.exists() { log(&format!("reshell spawn -> {:?}", quiet(&hotkeys).spawn().map(|_| ()))); }+ let desktop = dir().join("rust-explorer.exe");+ // the rust-explorer desktop: class "Progman" (so Wallpaper Engine finds it), title "rs-desktop" (explorer's is "Program Manager")+ let desktop_up = || unsafe { !FindWindowW(wide("Progman").as_ptr(), wide("rs-desktop").as_ptr()).is_null() };+ log(&format!("desktop exe {} exists={} up={}", desktop.display(), desktop.exists(), desktop_up()));+ if desktop.exists() && !desktop_up() { log(&format!("desktop spawn -> {:?}", quiet(&desktop).arg("--desktop").spawn().map(|_| ()))); }+ // the supervisor runs on its own thread; this one owns the hotkeys (RegisterHotKey needs the thread's message loop)+ thread::spawn(supervise);+ hotkey_loop();+}++/// Win+D (show desktop) and Win+E (file manager) for sessions where Explorer is not the shell. Never returns.+fn hotkey_loop() {+ unsafe {+ RegisterHotKey(ptr::null_mut(), 1, MOD_WIN | MOD_NOREPEAT, 'D' as u32);+ RegisterHotKey(ptr::null_mut(), 2, MOD_WIN | MOD_NOREPEAT, 'E' as u32);+ let mut m: MSG = std::mem::zeroed();+ while GetMessageW(&mut m, ptr::null_mut(), 0, 0) > 0 {+ match (m.message == WM_HOTKEY).then_some(m.wParam) {+ Some(1) => toggle_desktop(),+ Some(2) => { let fm = dir().join("rust-explorer.exe"); let _ = quiet(if fm.exists() { fm } else { "explorer.exe".into() }).spawn(); }+ _ => {}+ }+ }+ }+}++/// Keeps topbar alive; if it will not stay up, hands the session to explorer.exe and ends the shell.+fn supervise() {+ let (mut starts, mut since, mut misses) = (0, Instant::now(), 0);+ loop {+ unsafe { EnumWindows(Some(park), 0) };+ if bar_up() { misses = 0; } else { misses += 1; }+ if misses >= 6 { // ~6 s: the loop ticks every second now+ if since.elapsed() > Duration::from_secs(120) { (starts, since) = (0, Instant::now()); }+ starts += 1;+ if starts > 3 || quiet(find_exe("topbar.exe")).spawn().is_err() {+ // topbar will not stay up: hand the session to explorer so the user is never left with nothing+ let _ = quiet(find_exe("topbar.exe")).arg("--restore").creation_flags(NO_WINDOW).status();+ let _ = quiet("explorer.exe").spawn();+ std::process::exit(0);+ }+ misses = 0;+ }+ thread::sleep(Duration::from_secs(1));+ }+}++/// `rs-shell --overlay`: runs next to explorer.exe, which stays the real shell (Win+D / Win+E / wallpaper / Run keys are+/// its job). Starts topbar and the rust-explorer desktop on top of it and keeps the bar alive. Started from the user's+/// Run key, so it can live in a folder the user owns (Windows stopped starting our own shell at logon).+/// The rust-explorer plugin's "replace Explorer" switch (HKCU\Software\rs-shell\ReplaceExplorer = 1).+fn replace_on() -> bool {+ reg(&["query", r"HKCU\Software\rs-shell", "/v", "ReplaceExplorer"]).is_some_and(|o| o.contains("0x1"))+}++/// Ends the Explorer that runs as the shell (started without arguments). Folder windows (started with a path) and the COM+/// host (`/factory ... -Embedding`) are other explorer.exe processes and keep running.+fn kill_shell_explorer() {+ let script = r#"Get-CimInstance Win32_Process -Filter "Name='explorer.exe'" | Where-Object { $_.CommandLine -match '(?i)explorer\.exe"?\s*$' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }"#;+ let r = quiet("powershell").args(["-NoProfile", "-NonInteractive", "-Command", script]).creation_flags(NO_WINDOW).status();+ log(&format!("explorer shell stopped -> {:?}", r.map(|s| s.success())));+}++/// True once Explorer has started this session's Run keys and Startup folder. The overlay starts at logon (a scheduled task),+/// before Explorer gets to them: ending Explorer earlier would lose the user's autostart apps.+fn startup_run() -> bool {+ let mut sid = 0;+ unsafe { windows_sys::Win32::System::RemoteDesktop::ProcessIdToSessionId(std::process::id(), &mut sid) };+ let k = format!(r"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\SessionInfo\{sid}");+ ["RunStuffHasBeenRun", "StartupHasBeenRun"].iter().all(|n| reg(&["query", &format!(r"{k}\{n}")]).is_some())+}++/// Gives the user Explorer back (with a normal, not elevated, token: the shell must never run elevated).+fn start_shell_explorer() {+ let r = quiet("runas").args(["/trustlevel:0x20000", r"C:\Windows\explorer.exe"]).creation_flags(NO_WINDOW).spawn();+ log(&format!("explorer shell started -> {:?}", r.map(|_| ())));+}++fn overlay() {+ unsafe { windows_sys::Win32::System::Console::FreeConsole() };+ let replace = replace_on();+ log(&format!("overlay start (replace explorer: {replace})"));+ let wp = thread::spawn(set_wallpaper); // makes sure the BMP the desktop window paints exists (and refreshes the wallpaper)+ if !bar_up() { log(&format!("topbar spawn -> {:?}", quiet(find_exe("topbar.exe")).spawn().map(|_| ()))); }+ let _ = wp.join(); // the BMP conversion (only on a fresh install or a new wallpaper) finishes before the desktop paints it+ let desktop = dir().join("rust-explorer.exe");+ let up = || unsafe { !FindWindowW(wide("Progman").as_ptr(), wide("rs-desktop").as_ptr()).is_null() };+ if desktop.exists() && !up() { log(&format!("desktop spawn -> {:?}", quiet(&desktop).arg("--desktop").spawn().map(|_| ()))); }+ if replace {+ // Explorer is being replaced: this thread watches, the main one owns Win+D / Win+E+ thread::spawn(move || overlay_watch(replace, desktop, up));+ hotkey_loop();+ } else {+ overlay_watch(replace, desktop, up);+ }+}++/// Keeps topbar and the desktop alive. With `replace` it also ends the shell Explorer once both are up, and gives it back+/// (so the user is never left without a shell) if the bar will not stay up.+fn overlay_watch(replace: bool, desktop: PathBuf, up: impl Fn() -> bool) {+ let (mut starts, mut misses, mut dmiss, mut stable, mut killed) = (0, 0, 0, 0, false);+ loop {+ thread::sleep(Duration::from_secs(3));+ if replace && !killed {+ // both our surfaces must be on screen before the system's one goes away+ stable = if bar_up() && up() { stable + 1 } else { 0 };+ if stable >= 3 && startup_run() { kill_shell_explorer(); killed = true; }+ }+ dmiss = if desktop.exists() && !up() { dmiss + 1 } else { 0 };+ if dmiss >= 2 { log(&format!("desktop respawn -> {:?}", quiet(&desktop).arg("--desktop").spawn().map(|_| ()))); dmiss = 0; }+ if bar_up() { misses = 0; continue; }+ misses += 1;+ if misses < 2 { continue; }+ starts += 1;+ if starts > 3 || quiet(find_exe("topbar.exe")).spawn().is_err() {+ // the bar will not stay up: give the system's taskbar (and, if we ended it, Explorer) back and stop+ let _ = quiet(find_exe("topbar.exe")).arg("--restore").creation_flags(NO_WINDOW).status();+ if replace { start_shell_explorer(); }+ log("overlay: topbar keeps dying, system shell restored");+ return;+ }+ misses = 0;+ }+}++/// Windows will not start a shell from a folder the user can write to (a boot from %LOCALAPPDATA% fell back to explorer),+/// so the copy in Program Files is only a loader: it runs the real rs-shell from %LOCALAPPDATA%\plugin-launcher\bin, which+/// can be updated without admin. true = the user-folder shell took over (the loader must not run the shell logic as well).+/// A missing copy or one that dies within 3 s (it started nothing yet) leaves false: the loader then does the job itself.+fn bootstrap() -> bool {+ let Ok(base) = std::env::var("LOCALAPPDATA") else { return false };+ let real = PathBuf::from(base).join(r"plugin-launcher\bin\rs-shell.exe");+ let me = std::env::current_exe().and_then(|p| p.canonicalize()).ok();+ if !real.exists() || real.canonicalize().ok() == me {+ return false;+ }+ let t = Instant::now();+ match quiet(&real).spawn() {+ Ok(mut child) => {+ log(&format!("loader: started {}", real.display()));+ let _ = child.wait();+ t.elapsed() > Duration::from_secs(3)+ }+ Err(e) => {+ log(&format!("loader: cannot start {}: {e}", real.display()));+ false+ }+ }+}++fn main() {+ let a: Vec<String> = std::env::args().skip(1).collect();+ let code = match a.iter().map(String::as_str).collect::<Vec<_>>().as_slice() {+ [] => { if !bootstrap() { run_shell(); } 0 }+ ["--overlay"] => { overlay(); 0 }+ ["--dry-run"] => {+ println!("wallpaper: {:?}", reg(&["query", r"HKCU\Control Panel\Desktop", "/v", "WallPaper"]).map(|o| parse_run(&o)));+ autostart().iter().for_each(|c| println!("autostart: {c}"));+ println!("topbar: {} ({})", find_exe("topbar.exe").display(), if find_exe("topbar.exe").exists() { "found" } else { "MISSING" });+ println!("explorer ran this session's autostart: {}", startup_run());+ 0+ }+ ["--enable"] => {+ let exe = std::env::current_exe().unwrap_or_default();+ if !find_exe("topbar.exe").exists() {+ eprintln!("refusing: topbar.exe is not next to {} (no bar = no way to launch anything)", exe.display());+ 1+ } else if reg(&["add", WINLOGON, "/v", "Shell", "/t", "REG_SZ", "/d", &exe.to_string_lossy(), "/f"]).is_some() {+ println!("done: you get rs-shell instead of explorer at the next sign-in.\nundo: rs-shell --disable (or: reg delete \"{WINLOGON}\" /v Shell /f)");+ 0+ } else { eprintln!("reg add failed"); 1 }+ }+ ["--disable"] => {+ // deleting a value that is not there is fine too+ let _ = reg(&["delete", WINLOGON, "/v", "Shell", "/f"]);+ println!("done: normal shell at the next sign-in");+ 0+ }+ _ => { eprintln!("usage: rs-shell [--enable | --disable | --dry-run]"); 2 }+ };+ std::process::exit(code);+}++#[cfg(test)]+mod tests {+ use super::{exe_path, parse_run};+ #[test]+ fn finds_the_exe_in_run_commands() {+ assert_eq!(exe_path(r#""C:\a b\x.exe" --hidden"#).as_deref(), Some(r"C:\a b\x.exe"));+ assert_eq!(exe_path(r"C:\d\y.exe /background").as_deref(), Some(r"C:\d\y.exe"));+ assert_eq!(exe_path("script.bat"), None);+ assert!(exe_path(r"%windir%\system32\z.exe").unwrap().to_lowercase().ends_with(r"system32\z.exe"));+ }+ #[test]+ fn parses_reg_query_lines() {+ let out = "\nHKEY_CURRENT_USER\\X\n Foo REG_SZ foo.exe --x\n Bar REG_EXPAND_SZ %APPDATA%\\bar.exe\n Empty REG_SZ \n";+ assert_eq!(parse_run(out), ["foo.exe --x", "%APPDATA%\\bar.exe"]);+ }+}diff --git a/plugins/rtaskmgr-win32/.gitignore b/plugins/rtaskmgr-win32/.gitignorenew file mode 100644index 0000000..ea8c4bf--- /dev/null+++ b/plugins/rtaskmgr-win32/.gitignore@@ -0,0 +1 @@+/targetdiff --git a/plugins/rtaskmgr-win32/Cargo.lock b/plugins/rtaskmgr-win32/Cargo.locknew file mode 100644index 0000000..e9382ad--- /dev/null+++ b/plugins/rtaskmgr-win32/Cargo.lock@@ -0,0 +1,481 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "bitflags"+version = "1.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"++[[package]]+name = "bitflags"+version = "2.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"++[[package]]+name = "cc"+version = "1.11.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45"+dependencies = [+ "find-msvc-tools",+ "shlex",+]++[[package]]+name = "cfg-if"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"++[[package]]+name = "embed-resource"+version = "3.0.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6168487b5e7eb2673e6efe1200b1848016e436a6ca0b8031bf04bd9d493a249f"+dependencies = [+ "cc",+ "memchr",+ "rustc_version",+ "toml",+ "vswhom",+ "winreg",+]++[[package]]+name = "equivalent"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"++[[package]]+name = "find-msvc-tools"+version = "0.1.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"++[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"++[[package]]+name = "indexmap"+version = "2.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"+dependencies = [+ "equivalent",+ "hashbrown",+]++[[package]]+name = "lazy_static"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"++[[package]]+name = "libc"+version = "0.2.191"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "muldiv"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0419348c027fa7be448d2ae7ea0e4e04c2334c31dc4e74ab29f00a2a7ca69204"++[[package]]+name = "native-windows-gui"+version = "1.0.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4f7003a669f68deb6b7c57d74fff4f8e533c44a3f0b297492440ef4ff5a28454"+dependencies = [+ "bitflags 1.3.2",+ "lazy_static",+ "muldiv",+ "winapi",+ "winapi-build",+]++[[package]]+name = "ntapi"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae"+dependencies = [+ "winapi",+]++[[package]]+name = "objc2-core-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "objc2-io-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15"+dependencies = [+ "libc",+ "objc2-core-foundation",+]++[[package]]+name = "proc-macro2"+version = "1.0.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "rtaskmgr-win32"+version = "0.1.0"+dependencies = [+ "embed-resource",+ "native-windows-gui",+ "sysinfo",+ "winapi",+ "windows-sys",+]++[[package]]+name = "rustc_version"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"+dependencies = [+ "semver",+]++[[package]]+name = "semver"+version = "1.0.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"++[[package]]+name = "serde_core"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "serde_spanned"+version = "1.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"+dependencies = [+ "serde_core",+]++[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"++[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "syn"+version = "3.0.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "sysinfo"+version = "0.40.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a86bac2f7d06e6384984118ad727f5694110f0ec44d924d05c8fdec3d030bee6"+dependencies = [+ "libc",+ "memchr",+ "ntapi",+ "objc2-core-foundation",+ "objc2-io-kit",+ "windows",+]++[[package]]+name = "toml"+version = "1.2.1+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7"+dependencies = [+ "indexmap",+ "serde_core",+ "serde_spanned",+ "toml_datetime",+ "toml_parser",+ "toml_writer",+ "winnow",+]++[[package]]+name = "toml_datetime"+version = "1.1.3+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"+dependencies = [+ "serde_core",+]++[[package]]+name = "toml_parser"+version = "1.1.5+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"+dependencies = [+ "winnow",+]++[[package]]+name = "toml_writer"+version = "1.2.0+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"++[[package]]+name = "unicode-ident"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"++[[package]]+name = "vswhom"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b"+dependencies = [+ "libc",+ "vswhom-sys",+]++[[package]]+name = "vswhom-sys"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150"+dependencies = [+ "cc",+ "libc",+]++[[package]]+name = "winapi"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"+dependencies = [+ "winapi-i686-pc-windows-gnu",+ "winapi-x86_64-pc-windows-gnu",+]++[[package]]+name = "winapi-build"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc"++[[package]]+name = "winapi-i686-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"++[[package]]+name = "winapi-x86_64-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"++[[package]]+name = "windows"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"+dependencies = [+ "windows-collections",+ "windows-core",+ "windows-future",+ "windows-numerics",+]++[[package]]+name = "windows-collections"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"+dependencies = [+ "windows-core",+]++[[package]]+name = "windows-core"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-link",+ "windows-result",+ "windows-strings",+]++[[package]]+name = "windows-future"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"+dependencies = [+ "windows-core",+ "windows-link",+ "windows-threading",+]++[[package]]+name = "windows-implement"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-interface"+version = "0.59.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-numerics"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"+dependencies = [+ "windows-core",+ "windows-link",+]++[[package]]+name = "windows-result"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-strings"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-threading"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"+dependencies = [+ "windows-link",+]++[[package]]+name = "winnow"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"++[[package]]+name = "winreg"+version = "0.56.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10"+dependencies = [+ "cfg-if",+ "windows-sys",+]diff --git a/plugins/rtaskmgr-win32/Cargo.toml b/plugins/rtaskmgr-win32/Cargo.tomlnew file mode 100644index 0000000..fc65307--- /dev/null+++ b/plugins/rtaskmgr-win32/Cargo.toml@@ -0,0 +1,20 @@+[package]+name = "rtaskmgr-win32"+version = "0.1.0"+edition = "2024"++[dependencies]+native-windows-gui = { version = "1.0.13", default-features = false, features = ["timer", "clipboard", "cursor", "tray-notification", "high-dpi", "embed-resource"] }+sysinfo = { version = "0.40.3", default-features = false, features = ["system", "network", "disk"] }+winapi = { version = "0.3", features = ["debugapi", "winsvc", "processthreadsapi", "winbase", "winnt", "handleapi", "shellapi", "errhandlingapi", "minwindef", "winuser", "wingdi", "winreg", "winerror", "sysinfoapi", "minwinbase", "windef", "commctrl", "winver", "psapi", "libloaderapi", "fileapi", "ioapiset", "ntdef", "setupapi", "guiddef", "securitybaseapi", "synchapi"] }+windows-sys = { version = "0.61.2", features = ["Win32_System_Diagnostics_Etw", "Win32_Foundation", "Win32_System_Time", "Win32_Security_WinTrust", "Win32_Security_Cryptography", "Win32_System_Performance"] }++[profile.release]+opt-level = "s"+lto = true+codegen-units = 1+panic = "abort"+strip = true++[build-dependencies]+embed-resource = "3"diff --git a/plugins/rtaskmgr-win32/app.ico b/plugins/rtaskmgr-win32/app.iconew file mode 100644index 0000000..1f8ff38Binary files /dev/null and b/plugins/rtaskmgr-win32/app.ico differdiff --git a/plugins/rtaskmgr-win32/app.manifest b/plugins/rtaskmgr-win32/app.manifestnew file mode 100644index 0000000..97ad004--- /dev/null+++ b/plugins/rtaskmgr-win32/app.manifest@@ -0,0 +1,26 @@+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">+ <dependency>+ <dependentAssembly>+ <!-- Без Common Controls v6 загрузчик берёт comctl32 v5, где нет GetWindowSubclass -->+ <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*"/>+ </dependentAssembly>+ </dependency>+ <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">+ <security>+ <requestedPrivileges>+ <requestedExecutionLevel level="asInvoker" uiAccess="false"/>+ </requestedPrivileges>+ </security>+ </trustInfo>+ <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">+ <application>+ <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>+ </application>+ </compatibility>+ <application xmlns="urn:schemas-microsoft-com:asm.v3">+ <windowsSettings>+ <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>+ </windowsSettings>+ </application>+</assembly>diff --git a/plugins/rtaskmgr-win32/app.rc b/plugins/rtaskmgr-win32/app.rcnew file mode 100644index 0000000..eb227a4--- /dev/null+++ b/plugins/rtaskmgr-win32/app.rc@@ -0,0 +1,26 @@+1 ICON "app.ico"+1 24 "app.manifest"++1 VERSIONINFO+FILEVERSION 1,0,0,0+PRODUCTVERSION 1,0,0,0+FILEOS 0x4+FILETYPE 0x1+BEGIN+ BLOCK "StringFileInfo"+ BEGIN+ BLOCK "040904B0"+ BEGIN+ VALUE "FileDescription", "Task Manager (Rust)"+ VALUE "ProductName", "RTaskMgr"+ VALUE "FileVersion", "1.0.0"+ VALUE "ProductVersion", "1.0.0"+ VALUE "InternalName", "rtaskmgr-win32"+ VALUE "OriginalFilename", "rtaskmgr-win32.exe"+ END+ END+ BLOCK "VarFileInfo"+ BEGIN+ VALUE "Translation", 0x0409, 0x04B0+ END+ENDdiff --git a/plugins/rtaskmgr-win32/build.rs b/plugins/rtaskmgr-win32/build.rsnew file mode 100644index 0000000..528a5dd--- /dev/null+++ b/plugins/rtaskmgr-win32/build.rs@@ -0,0 +1,7 @@+fn main() {+ println!("cargo:rerun-if-changed=app.rc");+ println!("cargo:rerun-if-changed=app.ico");+ println!("cargo:rerun-if-changed=app.manifest");+ // иконка + версия + манифест (Common Controls v6) одним ресурсом+ embed_resource::compile("app.rc", embed_resource::NONE).manifest_required().unwrap();+}diff --git a/plugins/rtaskmgr-win32/src/app.rs b/plugins/rtaskmgr-win32/src/app.rsnew file mode 100644index 0000000..d262aca--- /dev/null+++ b/plugins/rtaskmgr-win32/src/app.rs@@ -0,0 +1,1299 @@+//! Окно приложения: состояние интерфейса, раскладка, события, меню и действия.+use crate::{data::*, draw::*, model::*, startup, store, sys, ui::*};+use native_windows_gui as nwg;+use std::{+ cell::{Cell, RefCell},+ collections::{HashMap, HashSet},+ ptr::{null, null_mut},+ time::{Duration, Instant},+};+use winapi::shared::windef::{HMENU, HWND};+use winapi::um::winuser::*;++#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub enum Btn {+ RunTask,+ EndTask,+ Efficiency,+ More,+ SvcStart,+ SvcStop,+ StartEnable,+ StartDisable,+ RuleDelete,+}++#[derive(Clone, Copy, PartialEq, Debug)]+pub enum Hit {+ None,+ NavToggle,+ Nav(usize),+ Button(Btn),+ Header(usize),+ Row(usize),+ Chevron(usize),+ VBar,+ PerfItem(usize),+ Setting(usize),+}++#[derive(Clone)]+pub struct Lay {+ pub client: R,+ pub nav: R,+ pub nav_toggle: R,+ pub nav_items: Vec<R>,+ pub band: R,+ pub title: R,+ pub search: R,+ pub buttons: Vec<(R, Btn, &'static str, char)>,+ pub body: R,+ pub header: R,+ pub rows_area: R,+ pub col_x: Vec<i32>,+ pub vbar: R,+ pub perf_list: R,+ pub perf_items: Vec<R>,+ pub perf_main: R,+ pub setting_cards: Vec<(R, SettingId)>,+}++pub struct Ui {+ pub page: Page,+ pub nav_open: bool,+ pub th: Theme,+ pub rows: Vec<Row>,+ pub sel: Option<String>,+ pub expanded: HashSet<String>,+ pub sorts: HashMap<Page, (usize, bool)>,+ pub search: String,+ pub hit: Hit,+ pub mouse: (i32, i32),+ pub scroll: f64,+ pub drag: Option<(i32, f64)>,+ pub perf_sel: PerfKind,+ pub toast: Option<(String, Instant)>,+ pub tip: Option<(String, (i32, i32))>,+ pub lay: Option<Lay>,+ pub last_click: Option<(Instant, String)>,+}++impl Ui {+ pub fn sort_of(&self, p: Page) -> (usize, bool) {+ self.sorts.get(&p).copied().unwrap_or_else(|| default_sort(p))+ }+ pub fn page_has_search(&self) -> bool {+ matches!(self.page, Page::Processes | Page::Users | Page::Details | Page::Services | Page::Startup | Page::History | Page::Rules)+ }+ pub fn has_table(&self) -> bool {+ self.page_has_search()+ }+}++#[derive(Clone, Copy, PartialEq, Debug)]+pub enum Act {+ RunTask,+ EndTask,+ EndTree,+ Efficiency,+ Suspend(bool),+ Prio(u32),+ Affinity(bool),+ OpenDir,+ CopyCmd,+ RuleLower,+ RuleNotify,+ RuleDelete,+ SvcStart,+ SvcStop,+ StartEnable,+ StartDisable,+ Export,+ SetTheme(u8),+ ToggleTray,+ ToggleAutostart,+ ToggleEtw,+ ToggleGpuTemp,+ ShowWindow,+ RelaunchAdmin,+ Exit,+ Toggle,+ Go(Page),+}++pub enum MI {+ Item(&'static str, Act),+ Check(&'static str, Act, bool),+ Sep,+ Sub(&'static str, Vec<MI>),+}++pub struct App {+ pub win: nwg::Window,+ pub search: nwg::TextInput,+ #[allow(dead_code, deprecated)] // owned only to stay alive: dropping it stops the 1 s refresh+ pub timer: nwg::Timer,+ pub tray: nwg::TrayNotification,+ #[allow(dead_code)] // the tray and the window keep using these handles: they must outlive them+ pub tray_icon: nwg::Icon,+ #[allow(dead_code)]+ pub icon_big: nwg::Icon,+ pub data: RefCell<Data>,+ pub ui: RefCell<Ui>,+ pub fonts: Fonts,+ pub scale: f64,+ pub edit_brush: Cell<isize>,+ pub search_rect: Cell<R>,+ pub last_tick: Cell<Instant>,+}++fn layout_log_path() -> Option<&'static std::ffi::OsString> {+ static P: std::sync::OnceLock<Option<std::ffi::OsString>> = std::sync::OnceLock::new();+ P.get_or_init(|| std::env::var_os("RTASKMGR_LAYOUT_LOG")).as_ref()+}++fn wide(s: &str) -> Vec<u16> {+ s.encode_utf16().chain(Some(0)).collect()+}++fn page_buttons(p: Page) -> Vec<(Btn, &'static str, char)> {+ match p {+ Page::Processes => vec![(Btn::RunTask, "Запустить новую задачу", '\u{E710}'), (Btn::EndTask, "Снять задачу", '\u{E711}'), (Btn::Efficiency, "Режим эффективности", '\u{E945}'), (Btn::More, "", '\u{E712}')],+ Page::Users => vec![(Btn::EndTask, "Снять задачу", '\u{E711}'), (Btn::More, "", '\u{E712}')],+ Page::Details => vec![(Btn::RunTask, "Запустить новую задачу", '\u{E710}'), (Btn::EndTask, "Снять задачу", '\u{E711}'), (Btn::More, "", '\u{E712}')],+ Page::Services => vec![(Btn::SvcStart, "Запустить", '\u{E768}'), (Btn::SvcStop, "Остановить", '\u{E71A}'), (Btn::More, "", '\u{E712}')],+ Page::Startup => vec![(Btn::StartEnable, "Включить", '\u{E73E}'), (Btn::StartDisable, "Отключить", '\u{E711}'), (Btn::More, "", '\u{E712}')],+ Page::Rules => vec![(Btn::RuleDelete, "Удалить правило", '\u{E74D}'), (Btn::More, "", '\u{E712}')],+ Page::History => vec![(Btn::More, "", '\u{E712}')],+ _ => vec![],+ }+}++impl App {+ // ================= раскладка =================+ pub fn compute_layout(&self, g: &G, ui: &Ui, d: &Data, w: i32, h: i32) -> Lay {+ let s = g.s;+ let px = |v: f64| (v * s).round() as i32;+ let nav_w = px(if ui.nav_open { NAV_W_OPEN } else { NAV_W });+ let nav = R::new(0, 0, nav_w, h);+ let nav_toggle = R::new(0, px(6.0), px(NAV_W), px(6.0 + 44.0));+ let nav_items: Vec<R> = (0..NAV.len()).map(|i| R::new(0, px(56.0 + i as f64 * 44.0), nav_w, px(56.0 + i as f64 * 44.0 + 44.0))).collect();+ let band = R::new(nav_w, 0, w, px(BAND_H));+ let title = R::new(band.l + px(20.0), 0, band.l + px(320.0), band.b);+ // кнопки справа налево+ let mut buttons = vec![];+ let mut right = band.r - px(12.0);+ for (btn, label, glyph) in page_buttons(ui.page).into_iter().rev() {+ let bw = if label.is_empty() { px(36.0) } else { g.text_w(label, Font::Ui) + px(48.0) };+ let r = R::new(right - bw, px(10.0), right, px(10.0 + 32.0));+ buttons.push((r, btn, label, glyph));+ right -= bw + px(4.0);+ }+ buttons.reverse();+ let btn_left = buttons.first().map_or(band.r, |b| b.0.l);+ let sw = px(440.0).min((btn_left - title.l - px(220.0)).max(px(160.0)));+ let sx = (band.l + btn_left) / 2 - sw / 2 + px(60.0);+ let search = R::new(sx.max(title.l + px(190.0)), px(10.0), (sx.max(title.l + px(190.0))) + sw, px(10.0 + 32.0));+ let body = R::new(nav_w, band.b, w, h);+ let mut lay = Lay {+ client: R::new(0, 0, w, h),+ nav,+ nav_toggle,+ nav_items,+ band,+ title,+ search,+ buttons,+ body,+ header: R::new(0, 0, 0, 0),+ rows_area: R::new(0, 0, 0, 0),+ col_x: vec![],+ vbar: R::new(0, 0, 0, 0),+ perf_list: R::new(0, 0, 0, 0),+ perf_items: vec![],+ perf_main: R::new(0, 0, 0, 0),+ setting_cards: vec![],+ };+ if ui.has_table() {+ let cols = columns(ui.page);+ let hh = px(if ui.page == Page::Processes { 56.0 } else { 36.0 });+ lay.header = R::new(body.l, body.t, body.r, body.t + hh);+ lay.rows_area = R::new(body.l, body.t + hh, body.r, body.b);+ let fixed: f64 = cols.iter().map(|c| c.w).sum();+ let rest = (body.w() as f64 - fixed * s).max(px(140.0) as f64);+ let mut x = body.l;+ lay.col_x.push(x);+ for c in &cols {+ x += if c.w == 0.0 { rest as i32 } else { px(c.w) };+ lay.col_x.push(x);+ }+ lay.vbar = lay.rows_area;+ }+ match ui.page {+ Page::Performance => {+ lay.perf_list = R::new(body.l, body.t, body.l + px(268.0), body.b);+ let n = perf_kinds(d).len().max(1) as i32;+ let item_h = px(76.0).min((body.h() - px(16.0)) / n); // при множестве устройств пункты сжимаются+ lay.perf_items = (0..n).map(|i| R::new(lay.perf_list.l + px(6.0), body.t + px(8.0) + i * item_h, lay.perf_list.r - px(6.0), body.t + px(8.0) + (i + 1) * item_h)).collect();+ lay.perf_main = R::new(lay.perf_list.r + px(24.0), body.t + px(16.0), body.r - px(24.0), body.b - px(12.0));+ }+ Page::Settings => {+ let ids = [SettingId::Theme, SettingId::Tray, SettingId::Autostart, SettingId::Etw, SettingId::GpuTemp];+ let cw = (body.w() - px(48.0)).min(px(900.0));+ lay.setting_cards = ids.iter().enumerate().map(|(i, id)| (R::new(body.l + px(24.0), body.t + px(16.0) + i as i32 * px(76.0), body.l + px(24.0) + cw, body.t + px(16.0) + i as i32 * px(76.0) + px(66.0)), *id)).collect();+ }+ _ => {}+ }+ let _ = d;+ lay+ }++ fn content_height(&self, g: &G, ui: &Ui, lay: &Lay, d: &Data) -> f64 {+ match ui.page {+ Page::Insights => {+ let w = (lay.body.w() - g.px(48.0)).min(g.px(900.0));+ d.hints().iter().map(|h| (g.wrap_h(h, Font::Ui, w - g.px(32.0)) + g.px(34.0)) as f64).sum::<f64>() + g.px(32.0) as f64+ }+ _ => ui.rows.len() as f64 * g.px(ROW_H) as f64,+ }+ }++ // ================= рисование =================+ pub fn paint(&self, hwnd: HWND) {+ let (Ok(d), Ok(mut ui)) = (self.data.try_borrow(), self.ui.try_borrow_mut()) else {+ unsafe { InvalidateRect(hwnd, null(), 0) };+ return;+ };+ unsafe {+ let mut ps: PAINTSTRUCT = std::mem::zeroed();+ let hdc = BeginPaint(hwnd, &mut ps);+ let mut rc = std::mem::zeroed();+ GetClientRect(hwnd, &mut rc);+ let (w, h) = (rc.right, rc.bottom);+ if w > 0 && h > 0 {+ let mem = winapi::um::wingdi::CreateCompatibleDC(hdc);+ let bmp = winapi::um::wingdi::CreateCompatibleBitmap(hdc, w, h);+ let old = winapi::um::wingdi::SelectObject(mem, bmp as *mut _);+ let g = G { dc: mem, s: self.scale, th: ui.th, fonts: &self.fonts };+ let lay = self.compute_layout(&g, &ui, &d, w, h);+ // прокрутка не должна выходить за содержимое+ let area_h = if ui.has_table() { lay.rows_area.h() } else { lay.body.h() } as f64;+ let max_scroll = (self.content_height(&g, &ui, &lay, &d) - area_h).max(0.0);+ ui.scroll = ui.scroll.clamp(0.0, max_scroll);+ g.fill(lay.client, ui.th.bg);+ match ui.page {+ Page::Performance => self.draw_performance(&g, &ui, &d, &lay),+ Page::Insights => self.draw_insights(&g, &ui, &d, &lay),+ Page::Settings => self.draw_settings(&g, &ui, &d, &lay),+ _ => self.draw_table(&g, &ui, &d, &lay),+ }+ self.draw_band(&g, &ui, &d, &lay);+ self.draw_nav(&g, &ui, &lay);+ self.draw_overlay(&g, &ui, lay.client);+ winapi::um::wingdi::BitBlt(hdc, 0, 0, w, h, mem, 0, 0, winapi::um::wingdi::SRCCOPY);+ winapi::um::wingdi::SelectObject(mem, old);+ winapi::um::wingdi::DeleteObject(bmp as *mut _);+ winapi::um::wingdi::DeleteDC(mem);+ if let Some(path) = layout_log_path() {+ // только для автотестов: где лежат кнопки, шапка и первая строка (физические пиксели клиентской области)+ let mut t = format!("scale={}\nrow0={:?}\nheader={:?}\n", self.scale, (lay.rows_area.l, lay.rows_area.t, lay.rows_area.r, lay.rows_area.b), (lay.header.l, lay.header.t, lay.header.r, lay.header.b));+ for (r, b, _, _) in &lay.buttons {+ t += &format!("{:?}={},{},{},{}\n", b, r.l, r.t, r.r, r.b);+ }+ for (i, r) in lay.nav_items.iter().enumerate() {+ t += &format!("nav{i}={},{},{},{}\n", r.l, r.t, r.r, r.b);+ }+ t += &format!("toggle={},{},{},{}\ncols={:?}\n", lay.nav_toggle.l, lay.nav_toggle.t, lay.nav_toggle.r, lay.nav_toggle.b, lay.col_x);+ let _ = std::fs::write(path, t);+ }+ ui.lay = Some(lay);+ }+ EndPaint(hwnd, &ps);+ }+ drop(ui);+ self.place_search();+ }++ /// Ставит поле поиска в шапку (оно настоящее, а рамка вокруг нарисована).+ pub fn place_search(&self) {+ let ui = self.ui.borrow();+ let Some(lay) = &ui.lay else { return };+ let show = ui.page_has_search();+ let s = self.scale;+ let r = lay.search;+ if self.search_rect.get() != r || self.search.visible() != show {+ self.search_rect.set(r);+ let lg = |v: i32| (v as f64 / s).round() as i32;+ self.search.set_position(lg(r.l) + 10, lg(r.t) + 7);+ self.search.set_size((lg(r.w()) - 44).max(40) as u32, 20);+ self.search.set_visible(show);+ }+ }++ pub fn invalidate(&self) {+ if let Some(h) = self.win.handle.hwnd() {+ unsafe { InvalidateRect(h, null(), 0) };+ }+ }++ // ================= проверка попаданий =================+ fn hit_test(&self, ui: &Ui, x: i32, y: i32) -> Hit {+ let Some(lay) = &ui.lay else { return Hit::None };+ if lay.nav_toggle.contains(x, y) {+ return Hit::NavToggle;+ }+ if let Some(i) = lay.nav_items.iter().position(|r| r.contains(x, y)) {+ return Hit::Nav(i);+ }+ if lay.band.contains(x, y) {+ return lay.buttons.iter().find(|b| b.0.contains(x, y)).map_or(Hit::None, |b| Hit::Button(b.1));+ }+ match ui.page {+ Page::Performance => lay.perf_items.iter().position(|r| r.contains(x, y)).map_or(Hit::None, Hit::PerfItem),+ Page::Settings => lay.setting_cards.iter().position(|c| c.0.contains(x, y)).map_or(Hit::None, Hit::Setting),+ _ if ui.has_table() => {+ if lay.header.contains(x, y) {+ let cols = columns(ui.page);+ return (0..cols.len()).find(|&i| x >= lay.col_x[i] && x < lay.col_x[i + 1]).map_or(Hit::None, Hit::Header);+ }+ if lay.rows_area.contains(x, y) {+ let content = ui.rows.len() as f64 * (ROW_H * self.scale).round();+ if content > lay.rows_area.h() as f64 && x >= lay.rows_area.r - (10.0 * self.scale) as i32 {+ return Hit::VBar;+ }+ let i = ((y - lay.rows_area.t) as f64 + ui.scroll) / (ROW_H * self.scale).round();+ let i = i.floor() as usize;+ if i < ui.rows.len() {+ let r = &ui.rows[i];+ let chev_x = lay.col_x[0] + (12.0 * self.scale) as i32 + r.depth as i32 * (22.0 * self.scale) as i32;+ if matches!(ui.page, Page::Processes | Page::Users) && r.expandable && x >= chev_x - (4.0 * self.scale) as i32 && x < chev_x + (22.0 * self.scale) as i32 {+ return Hit::Chevron(i);+ }+ return Hit::Row(i);+ }+ }+ Hit::None+ }+ _ => Hit::None,+ }+ }++ pub fn btn_enabled(&self, ui: &Ui, d: &Data, b: Btn) -> bool {+ let has_sel = ui.sel.is_some();+ match b {+ Btn::RunTask | Btn::More => true,+ Btn::EndTask | Btn::Efficiency | Btn::SvcStart | Btn::SvcStop | Btn::StartEnable | Btn::StartDisable | Btn::RuleDelete => {+ let _ = d;+ has_sel+ }+ }+ }++ // ================= события мыши/клавиатуры =================+ pub fn on_mouse_move(&self, hwnd: HWND, x: i32, y: i32) {+ let mut ui = self.ui.borrow_mut();+ ui.mouse = (x, y);+ let hit = self.hit_test(&ui, x, y);+ let mut redraw = hit != ui.hit;+ ui.hit = hit;+ if let Some((sy, s0)) = ui.drag+ && let Some(lay) = ui.lay.clone() {+ let content = ui.rows.len() as f64 * (ROW_H * self.scale).round();+ let area = lay.rows_area.h() as f64;+ if content > area {+ let thumb = ((area / content) * area).max(24.0 * self.scale);+ ui.scroll = (s0 + (y - sy) as f64 * (content - area) / (area - thumb)).clamp(0.0, content - area);+ redraw = true;+ }+ }+ // подсказка над ячейкой «Подозрительное»: появляется после короткой паузы+ let mut want_tip: Option<(String, (i32, i32))> = None;+ if let (Hit::Row(i), Some(lay)) = (hit, &ui.lay)+ && ui.page == Page::Processes {+ let last = lay.col_x.len() - 2;+ if x >= lay.col_x[last] && x < lay.col_x[last + 1]+ && let Some(r) = ui.rows.get(i)+ && !r.tip.is_empty() {+ want_tip = Some((r.tip.clone(), (x, y)));+ }+ }+ if want_tip.is_none() && ui.tip.is_some() {+ ui.tip = None;+ redraw = true;+ }+ let pending = want_tip.is_some();+ drop(ui);+ unsafe {+ if pending {+ *self.pending_tip().borrow_mut() = want_tip;+ SetTimer(hwnd, 77, 350, None);+ } else {+ KillTimer(hwnd, 77);+ }+ let mut t = TRACKMOUSEEVENT { cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE, hwndTrack: hwnd, dwHoverTime: 0 };+ TrackMouseEvent(&mut t);+ }+ if redraw {+ self.invalidate();+ }+ }++ fn pending_tip(&self) -> &'static RefCell<Option<(String, (i32, i32))>> {+ thread_local! { static P: &'static RefCell<Option<(String, (i32, i32))>> = Box::leak(Box::new(RefCell::new(None))); }+ P.with(|p| *p)+ }++ pub fn on_tip_timer(&self, hwnd: HWND) {+ unsafe { KillTimer(hwnd, 77) };+ let Some(tip) = self.pending_tip().borrow_mut().take() else { return };+ if let Some(log) = std::env::var_os("RTASKMGR_TIP_LOG") {+ let _ = std::fs::write(log, &tip.0); // только для автотестов: какой текст показала бы подсказка+ }+ self.ui.borrow_mut().tip = Some(tip);+ self.invalidate();+ }++ pub fn on_mouse_leave(&self) {+ let mut ui = self.ui.borrow_mut();+ ui.hit = Hit::None;+ ui.tip = None;+ drop(ui);+ self.invalidate();+ }++ pub fn on_lbutton_down(&self, hwnd: HWND, x: i32, y: i32) {+ unsafe { SetFocus(hwnd) };+ let hit = {+ let mut ui = self.ui.borrow_mut();+ ui.tip = None;+ self.hit_test(&ui, x, y)+ };+ match hit {+ Hit::NavToggle => {+ let mut ui = self.ui.borrow_mut();+ ui.nav_open = !ui.nav_open;+ }+ Hit::Nav(i) => self.go_page(NAV[i].0),+ Hit::Button(b) => self.on_button(hwnd, b),+ Hit::Header(i) => {+ {+ let mut ui = self.ui.borrow_mut();+ let cols = columns(ui.page);+ let cur = ui.sort_of(ui.page);+ let numeric = cols[i].align == Align::Right || cols[i].metric.is_some();+ let ns = if cur.0 == i { (i, !cur.1) } else { (i, numeric) };+ let p = ui.page;+ ui.sorts.insert(p, ns);+ }+ self.rebuild();+ }+ Hit::Chevron(i) => {+ let key = self.ui.borrow().rows.get(i).map(|r| r.key.clone());+ if let Some(k) = key {+ self.toggle_expand(&k);+ }+ }+ Hit::Row(i) => {+ let mut dbl: Option<String> = None;+ {+ let mut ui = self.ui.borrow_mut();+ if let Some(r) = ui.rows.get(i) {+ let key = r.key.clone();+ let now = Instant::now();+ if let Some((t, k)) = &ui.last_click+ && *k == key && now.duration_since(*t) < Duration::from_millis(450) {+ dbl = Some(key.clone());+ }+ ui.last_click = Some((now, key.clone()));+ ui.sel = Some(key);+ }+ }+ if let Some(k) = dbl {+ self.toggle_expand(&k);+ }+ }+ Hit::VBar => {+ let mut ui = self.ui.borrow_mut();+ ui.drag = Some((y, ui.scroll));+ unsafe { SetCapture(hwnd) };+ }+ Hit::PerfItem(i) => {+ let kind = perf_kinds(&self.data.borrow()).get(i).copied();+ if let Some(k) = kind {+ self.ui.borrow_mut().perf_sel = k;+ self.data.borrow_mut().want_gpu_temp = matches!(k, PerfKind::Gpu(_)); // температура сразу, не ждать следующего такта+ }+ }+ Hit::Setting(i) => self.on_setting(i, x),+ Hit::None => {}+ }+ self.invalidate();+ }++ pub fn on_lbutton_up(&self) {+ let mut ui = self.ui.borrow_mut();+ if ui.drag.take().is_some() {+ unsafe { ReleaseCapture() };+ }+ }++ pub fn on_wheel(&self, delta: i16) {+ let mut ui = self.ui.borrow_mut();+ ui.scroll -= delta as f64 / 120.0 * 3.0 * (ROW_H * self.scale).round();+ ui.tip = None;+ drop(ui);+ self.invalidate();+ }++ pub fn on_rbutton_up(&self, hwnd: HWND, x: i32, y: i32) {+ let hit = {+ let ui = self.ui.borrow();+ self.hit_test(&ui, x, y)+ };+ if let Hit::Row(i) | Hit::Chevron(i) = hit {+ {+ let mut ui = self.ui.borrow_mut();+ if let Some(r) = ui.rows.get(i) {+ ui.sel = Some(r.key.clone());+ }+ }+ self.invalidate();+ let items = self.row_menu();+ let (px, py) = self.to_screen(hwnd, x, y);+ if let Some(a) = self.show_menu(hwnd, &items, px, py) {+ self.do_act(a);+ }+ }+ }++ fn to_screen(&self, hwnd: HWND, x: i32, y: i32) -> (i32, i32) {+ let mut p = winapi::shared::windef::POINT { x, y };+ unsafe { ClientToScreen(hwnd, &mut p) };+ (p.x, p.y)+ }++ pub fn on_key(&self, hwnd: HWND, vk: u32) {+ let ctrl = unsafe { GetKeyState(VK_CONTROL) } < 0;+ let (page, n) = {+ let ui = self.ui.borrow();+ (ui.page, ui.rows.len())+ };+ if ctrl && vk == 'F' as u32 && self.ui.borrow().page_has_search() {+ unsafe { SetFocus(self.search.handle.hwnd().unwrap_or(hwnd)) };+ return;+ }+ if !self.ui.borrow().has_table() || n == 0 {+ return;+ }+ let cur = {+ let ui = self.ui.borrow();+ ui.sel.as_ref().and_then(|k| ui.rows.iter().position(|r| &r.key == k))+ };+ let step = ((self.ui.borrow().lay.as_ref().map_or(10, |l| l.rows_area.h()) as f64 / (ROW_H * self.scale).round()) as usize).max(1);+ let target = match vk as i32 {+ VK_DOWN => Some(cur.map_or(0, |c| (c + 1).min(n - 1))),+ VK_UP => Some(cur.map_or(0, |c| c.saturating_sub(1))),+ VK_NEXT => Some(cur.map_or(0, |c| (c + step).min(n - 1))),+ VK_PRIOR => Some(cur.map_or(0, |c| c.saturating_sub(step))),+ VK_HOME => Some(0),+ VK_END => Some(n - 1),+ VK_RIGHT | VK_LEFT => {+ let key = self.ui.borrow().sel.clone();+ if let Some(k) = key {+ let want_open = vk as i32 == VK_RIGHT;+ let open = self.ui.borrow().expanded.contains(&k);+ if want_open != open && matches!(page, Page::Processes | Page::Users) {+ self.toggle_expand(&k);+ }+ }+ None+ }+ VK_DELETE => {+ self.do_act(Act::EndTask);+ None+ }+ VK_F5 => {+ self.tick();+ None+ }+ _ => None,+ };+ if let Some(t) = target {+ let mut ui = self.ui.borrow_mut();+ ui.sel = Some(ui.rows[t].key.clone());+ // держим выбранную строку в видимой области+ if let Some(lay) = ui.lay.clone() {+ let rh = (ROW_H * self.scale).round();+ let (top, bot) = (t as f64 * rh, (t as f64 + 1.0) * rh);+ if top < ui.scroll {+ ui.scroll = top;+ } else if bot > ui.scroll + lay.rows_area.h() as f64 {+ ui.scroll = bot - lay.rows_area.h() as f64;+ }+ }+ }+ self.invalidate();+ }++ // ================= страницы, строки =================+ pub fn go_page(&self, p: Page) {+ {+ let mut ui = self.ui.borrow_mut();+ if ui.page == p {+ return;+ }+ ui.page = p;+ ui.scroll = 0.0;+ ui.sel = None;+ ui.search.clear();+ ui.rows.clear();+ ui.tip = None;+ }+ self.search.set_text("");+ {+ let mut d = self.data.borrow_mut();+ match p {+ Page::Startup => d.load_startup(),+ Page::History => d.load_history(),+ _ => {}+ }+ }+ self.rebuild();+ self.save_settings();+ }++ pub fn rebuild(&self) {+ let d = self.data.borrow();+ let mut ui = self.ui.borrow_mut();+ if !ui.has_table() {+ return;+ }+ let rows = {+ let ctx = BuildCtx { page: ui.page, search: &ui.search, expanded: &ui.expanded, sort: ui.sort_of(ui.page) };+ build_rows(&d, &ctx)+ };+ if let Some(k) = ui.sel.clone()+ && !rows.iter().any(|r| r.key == k) {+ ui.sel = None;+ }+ ui.rows = rows;+ }++ fn toggle_expand(&self, key: &str) {+ {+ let mut ui = self.ui.borrow_mut();+ if !ui.expanded.remove(key) {+ ui.expanded.insert(key.to_string());+ }+ }+ self.rebuild();+ }++ /// Из таймера: Windows-таймер может тикать чаще заданного, поэтому режем частоту.+ pub fn on_timer(&self) {+ if self.last_tick.get().elapsed() >= Duration::from_millis(900) {+ self.last_tick.set(Instant::now());+ self.tick();+ }+ }++ pub fn tick(&self) {+ {+ let ui = self.ui.borrow();+ self.data.borrow_mut().want_gpu_temp = ui.page == Page::Performance && matches!(ui.perf_sel, PerfKind::Gpu(_));+ }+ let notes = self.data.borrow_mut().refresh();+ if !notes.is_empty() {+ let msg = notes.join("; ");+ self.toast(&msg);+ self.tray.show(&msg, Some("Диспетчер задач"), None, None);+ }+ {+ let (page, ticks) = (self.ui.borrow().page, self.data.borrow().ticks);+ let mut d = self.data.borrow_mut();+ if page == Page::Startup && ticks % 10 == 0 {+ d.load_startup();+ }+ if page == Page::History && ticks % 30 == 0 {+ d.load_history();+ }+ }+ self.rebuild();+ {+ let mut ui = self.ui.borrow_mut();+ if ui.toast.as_ref().is_some_and(|t| t.1.elapsed() > Duration::from_secs(4)) {+ ui.toast = None;+ }+ }+ self.invalidate();+ }++ pub fn toast(&self, msg: &str) {+ self.ui.borrow_mut().toast = Some((msg.to_string(), Instant::now()));+ self.invalidate();+ }++ pub fn on_search_changed(&self) {+ let t = self.search.text();+ {+ let mut ui = self.ui.borrow_mut();+ ui.search = t;+ ui.scroll = 0.0;+ }+ self.rebuild();+ self.invalidate();+ }++ // ================= кнопки, настройки =================+ fn on_button(&self, hwnd: HWND, b: Btn) {+ match b {+ Btn::RunTask => self.do_act(Act::RunTask),+ Btn::EndTask => self.do_act(Act::EndTask),+ Btn::Efficiency => self.do_act(Act::Efficiency),+ Btn::SvcStart => self.do_act(Act::SvcStart),+ Btn::SvcStop => self.do_act(Act::SvcStop),+ Btn::StartEnable => self.do_act(Act::StartEnable),+ Btn::StartDisable => self.do_act(Act::StartDisable),+ Btn::RuleDelete => self.do_act(Act::RuleDelete),+ Btn::More => {+ let items = self.more_menu();+ let r = self.ui.borrow().lay.as_ref().and_then(|l| l.buttons.iter().find(|x| x.1 == Btn::More).map(|x| x.0));+ if let Some(r) = r {+ let (x, y) = self.to_screen(hwnd, r.r - 220, r.b + 2);+ if let Some(a) = self.show_menu(hwnd, &items, x, y) {+ self.do_act(a);+ }+ }+ }+ }+ }++ fn on_setting(&self, i: usize, x: i32) {+ let id = self.ui.borrow().lay.as_ref().and_then(|l| l.setting_cards.get(i).map(|c| (c.1, c.0)));+ let Some((id, r)) = id else { return };+ match id {+ SettingId::Theme => {+ let ctl_l = r.r - (200.0 * self.scale) as i32;+ let seg = ((x - ctl_l) / (((200.0 * self.scale) as i32 - (16.0 * self.scale) as i32) / 3).max(1)).clamp(0, 2);+ self.do_act(Act::SetTheme(seg as u8));+ }+ SettingId::Tray => self.do_act(Act::ToggleTray),+ SettingId::Autostart => self.do_act(Act::ToggleAutostart),+ SettingId::Etw => self.do_act(Act::ToggleEtw),+ SettingId::GpuTemp => self.do_act(Act::ToggleGpuTemp),+ }+ }++ // ================= меню =================+ fn selected_row(&self) -> Option<Row> {+ let ui = self.ui.borrow();+ ui.sel.as_ref().and_then(|k| ui.rows.iter().find(|r| &r.key == k).cloned())+ }++ fn row_menu(&self) -> Vec<MI> {+ let page = self.ui.borrow().page;+ match page {+ Page::Processes | Page::Users | Page::Details => {+ let mut v = vec![];+ if let Some(r) = self.selected_row()+ && r.expandable {+ v.push(MI::Item(if r.expanded { "Свернуть" } else { "Развернуть" }, Act::Toggle));+ v.push(MI::Sep);+ }+ v.extend([+ MI::Item("Снять задачу", Act::EndTask),+ MI::Item("Завершить дерево процессов", Act::EndTree),+ MI::Item("Режим эффективности", Act::Efficiency),+ MI::Item("Приостановить", Act::Suspend(true)),+ MI::Item("Возобновить", Act::Suspend(false)),+ MI::Sep,+ MI::Sub("Приоритет", sys::PRIORITIES.iter().map(|p| MI::Item(p.0, Act::Prio(p.1))).collect()),+ MI::Sub("Ядра процессора", vec![MI::Item("Все ядра", Act::Affinity(false)), MI::Item("Только половина ядер", Act::Affinity(true))]),+ MI::Sep,+ MI::Item("Открыть расположение файла", Act::OpenDir),+ MI::Item("Копировать командную строку", Act::CopyCmd),+ MI::Sep,+ MI::Item("Правило: понижать приоритет при ЦП > 25% дольше 60 с", Act::RuleLower),+ MI::Item("Правило: уведомлять при ЦП > 25% дольше 60 с", Act::RuleNotify),+ ]);+ v+ }+ Page::Services => vec![MI::Item("Запустить службу", Act::SvcStart), MI::Item("Остановить службу", Act::SvcStop)],+ Page::Startup => vec![MI::Item("Включить", Act::StartEnable), MI::Item("Отключить", Act::StartDisable), MI::Sep, MI::Item("Открыть расположение файла", Act::OpenDir)],+ Page::Rules => vec![MI::Item("Удалить правило", Act::RuleDelete)],+ _ => vec![],+ }+ }++ fn more_menu(&self) -> Vec<MI> {+ let d = self.data.borrow();+ vec![+ MI::Item("Запустить новую задачу", Act::RunTask),+ MI::Item("Экспорт в CSV", Act::Export),+ MI::Sep,+ MI::Sub("Тема", vec![MI::Check("Светлая", Act::SetTheme(0), d.cfg.theme == 0), MI::Check("Тёмная", Act::SetTheme(1), d.cfg.theme == 1), MI::Check("Системная", Act::SetTheme(2), d.cfg.theme == 2)]),+ MI::Item("Параметры", Act::Go(Page::Settings)),+ ]+ .into_iter()+ .chain((!d.is_admin).then_some([MI::Sep, MI::Item("Перезапустить от имени администратора", Act::RelaunchAdmin)]).into_iter().flatten())+ .collect()+ }++ pub fn tray_menu(&self) -> Vec<MI> {+ let d = self.data.borrow();+ vec![+ MI::Item("Показать окно", Act::ShowWindow),+ MI::Sep,+ MI::Check("Закрытие окна сворачивает в трей", Act::ToggleTray, d.cfg.to_tray),+ MI::Check("Запускать при входе в Windows", Act::ToggleAutostart, startup::self_autostart()),+ MI::Check("Сеть по процессам (ETW, администратор)", Act::ToggleEtw, d.etw.is_some()),+ MI::Sep,+ ]+ .into_iter()+ .chain((!d.is_admin).then_some(MI::Item("Перезапустить от имени администратора", Act::RelaunchAdmin)))+ .chain([MI::Item("Выход", Act::Exit)])+ .collect()+ }++ pub fn show_menu(&self, hwnd: HWND, items: &[MI], x: i32, y: i32) -> Option<Act> {+ if items.is_empty() {+ return None;+ }+ set_menu_theme(self.ui.borrow().th.dark);+ let mut acts: Vec<Act> = vec![];+ let menu = build_menu(items, &mut acts);+ let id = unsafe {+ SetForegroundWindow(hwnd);+ TrackPopupMenuEx(menu, TPM_RETURNCMD | TPM_RIGHTBUTTON | TPM_NONOTIFY, x, y, hwnd, null_mut())+ };+ unsafe { DestroyMenu(menu) };+ (id > 0).then(|| acts[id as usize - 1])+ }++ // ================= действия =================+ pub fn do_act(&self, act: Act) {+ match act {+ Act::ShowWindow => return self.show_window(),+ Act::Exit => return self.quit(),+ Act::RelaunchAdmin => {+ self.save_settings(); // the new instance reads them at start: same page, same columns+ if sys::relaunch_as_admin("") {+ return self.quit();+ }+ return self.toast("Запуск от имени администратора отменён");+ }+ Act::Go(p) => return self.go_page(p),+ Act::RunTask => {+ // стандартное окно «Выполнить»+ let _ = std::process::Command::new("explorer.exe").arg("shell:::{2559a1f3-21d7-11d4-bdaf-00c04f60b9f0}").spawn();+ return;+ }+ Act::SetTheme(t) => {+ self.data.borrow_mut().cfg.theme = t;+ self.apply_theme();+ self.save_settings();+ return;+ }+ Act::ToggleTray => {+ let on = {+ let mut d = self.data.borrow_mut();+ d.cfg.to_tray = !d.cfg.to_tray;+ d.cfg.to_tray+ };+ self.toast(if on { "Закрытие окна будет сворачивать в трей" } else { "Закрытие окна завершит программу" });+ self.save_settings();+ return;+ }+ Act::ToggleAutostart => {+ let want = !startup::self_autostart();+ let exe = std::env::current_exe().map(|p| p.display().to_string()).unwrap_or_default();+ let ok = startup::set_self_autostart(want, &exe);+ self.toast(match (ok, startup::self_autostart()) {+ (true, true) => "Программа будет запускаться при входе в Windows (сразу в трей)",+ (true, false) => "Автозапуск программы отключён",+ _ => "Не удалось изменить автозапуск",+ });+ return;+ }+ Act::ToggleEtw => {+ let msg = {+ let mut d = self.data.borrow_mut();+ if !d.is_admin {+ "Сеть по процессам требует прав администратора — запустите программу от имени администратора".to_string()+ } else if let Some(s) = d.etw.take() {+ crate::net::stop(s);+ d.net.clear();+ d.cfg.etw = false;+ "Сеть по процессам выключена".into()+ } else {+ d.etw = crate::net::start();+ d.cfg.etw = d.etw.is_some();+ if d.etw.is_some() { "Сеть по процессам включена (колонка «Сеть»)".into() } else { "Не удалось запустить ETW".into() }+ }+ };+ self.toast(&msg);+ self.save_settings();+ return;+ }+ Act::ToggleGpuTemp => {+ let on = {+ let mut d = self.data.borrow_mut();+ d.cfg.gpu_temp_always = !d.cfg.gpu_temp_always;+ d.cfg.gpu_temp_always+ };+ self.toast(if on { "Температура GPU читается постоянно" } else { "Температура GPU читается только на странице GPU" });+ self.save_settings();+ return;+ }+ Act::Export => return self.export(),+ _ => {}+ }+ let page = self.ui.borrow().page;+ let Some(row) = self.selected_row() else {+ self.toast("Сначала выберите строку в списке");+ return;+ };+ if act == Act::Toggle {+ return self.toggle_expand(&row.key);+ }+ match page {+ Page::Services => return self.act_service(&row, act),+ Page::Startup => return self.act_startup(&row, act),+ Page::Rules => {+ if act == Act::RuleDelete {+ if let Ok(i) = row.key.parse::<usize>() {+ let mut d = self.data.borrow_mut();+ if i < d.rules.len() {+ d.rules.remove(i);+ }+ }+ self.save_settings();+ self.toast("Правило удалено");+ self.rebuild();+ }+ return;+ }+ _ => {}+ }+ self.act_process(&row, act);+ }++ fn act_process(&self, row: &Row, act: Act) {+ let mut pids: Vec<u32> = row.pids.iter().copied().filter(|&p| p != 0).collect();+ if pids.is_empty() {+ return;+ }+ if matches!(act, Act::EndTask | Act::EndTree | Act::Suspend(true)) {+ let d = self.data.borrow();+ let total = pids.len();+ pids.retain(|&p| d.sys.process(sysinfo::Pid::from_u32(p)).is_none_or(|x| !CRITICAL.contains(&x.name().to_string_lossy().to_lowercase().as_str())));+ if pids.len() < total {+ drop(d);+ self.toast("Критичные системные процессы (csrss, lsass, smss и т.п.) защищены и пропущены");+ if pids.is_empty() {+ return;+ }+ }+ }+ if (act == Act::EndTask && pids.len() > 1 || act == Act::EndTree) && !self.confirm(&format!("Завершить процессов: {} (для дерева — вместе с потомками)?", pids.len())) {+ return;+ }+ let report = |what: &str, ok: usize| {+ self.toast(&if ok == pids.len() { format!("{what}: готово ({ok})") } else { format!("{what}: удалось {ok} из {} — для остальных нужны права администратора{}", pids.len(), if self.data.borrow().is_admin { "" } else { " (меню «…» → «Перезапустить от имени администратора»)" }) });+ };+ match act {+ Act::EndTask => {+ let d = self.data.borrow();+ let ok = pids.iter().filter(|&&p| d.sys.process(sysinfo::Pid::from_u32(p)).is_some_and(|x| x.kill())).count();+ drop(d);+ report("Завершение", ok);+ }+ Act::EndTree => {+ let d = self.data.borrow();+ let parents: HashMap<u32, u32> = d.procs.iter().map(|p| (p.pid, p.ppid)).collect();+ let all = descendants(&parents, &pids);+ let ok = all.iter().filter(|&&p| d.sys.process(sysinfo::Pid::from_u32(p)).is_some_and(|x| x.kill())).count();+ drop(d);+ self.toast(&format!("Завершено {ok} из {} (с потомками)", all.len()));+ }+ Act::Prio(c) => report("Приоритет", pids.iter().filter(|&&p| sys::set_priority(p, c)).count()),+ Act::Suspend(on) => {+ let ok: Vec<u32> = pids.iter().copied().filter(|&p| sys::suspend(p, on)).collect();+ {+ let mut d = self.data.borrow_mut();+ for p in &ok {+ if on { d.suspended.insert(*p) } else { d.suspended.remove(p) };+ }+ }+ report(if on { "Приостановка" } else { "Возобновление" }, ok.len());+ }+ Act::Efficiency => {+ let on = !pids.iter().all(|p| self.data.borrow().efficiency.contains(p));+ let ok: Vec<u32> = pids.iter().copied().filter(|&p| sys::set_efficiency(p, on)).collect();+ {+ let mut d = self.data.borrow_mut();+ for p in &ok {+ if on { d.efficiency.insert(*p) } else { d.efficiency.remove(p) };+ }+ }+ report(if on { "Режим эффективности включён" } else { "Режим эффективности выключен" }, ok.len());+ }+ Act::Affinity(half) => report("Привязка к ядрам", pids.iter().filter(|&&p| sys::set_affinity(p, half)).count()),+ Act::OpenDir => {+ let d = self.data.borrow();+ let path = pids.iter().find_map(|&p| d.procs.iter().find(|x| x.pid == p).and_then(|x| x.exe.clone()));+ drop(d);+ match path {+ Some(p) => {+ use std::os::windows::process::CommandExt;+ let _ = std::process::Command::new("explorer").raw_arg(format!("/select,\"{}\"", p.replace("\\..\\", "\\"))).spawn();+ }+ None => self.toast("Путь к файлу недоступен (системный или защищённый процесс)"),+ }+ }+ Act::CopyCmd => {+ let d = self.data.borrow();+ let cmd = process_cmd(&d, pids[0]);+ drop(d);+ if cmd.is_empty() {+ self.toast("Командная строка недоступна для этого процесса");+ } else {+ nwg::Clipboard::set_data_text(&self.win, &cmd);+ self.toast("Командная строка скопирована");+ }+ }+ Act::RuleLower | Act::RuleNotify => {+ let name = {+ let d = self.data.borrow();+ d.procs.iter().find(|p| p.pid == pids[0]).map(|p| p.name.to_lowercase())+ };+ let Some(name) = name else { return };+ let act = if act == Act::RuleLower { store::RuleAct::Lower } else { store::RuleAct::Notify };+ let msg = {+ let mut d = self.data.borrow_mut();+ if d.rules.iter().any(|r| r.proc == name && r.act == act) {+ "Такое правило уже есть (страница «Правила»)".to_string()+ } else {+ d.rules.push(store::Rule { proc: name.clone(), cpu: 25.0, secs: 60, act, hits: 0 });+ format!("Правило добавлено: «{name}» — ЦП > 25% дольше 60 с")+ }+ };+ self.save_settings();+ self.toast(&msg);+ }+ _ => {}+ }+ }++ fn act_service(&self, row: &Row, act: Act) {+ let start = match act {+ Act::SvcStart => true,+ Act::SvcStop => false,+ _ => return,+ };+ let n = row.aux.clone();+ self.toast(&match sys::service_ctl(&n, start) {+ Ok(()) => format!("Служба {n}: команда отправлена"),+ Err(5) => format!("Служба {n}: отказано в доступе — запустите от администратора"),+ Err(e) => format!("Служба {n}: ошибка Win32 {e}"),+ });+ }++ fn act_startup(&self, row: &Row, act: Act) {+ let on = match act {+ Act::StartEnable => true,+ Act::StartDisable => false,+ Act::OpenDir => {+ if let Some(p) = &row.icon_path {+ use std::os::windows::process::CommandExt;+ let _ = std::process::Command::new("explorer").raw_arg(format!("/select,\"{p}\"")).spawn();+ }+ return;+ }+ _ => return,+ };+ let msg = {+ let d = self.data.borrow();+ match d.startup.iter().find(|s| s.key() == row.key) {+ Some(it) => match startup::set_enabled(it, on) {+ Ok(()) => format!("«{}»: {}", it.name, if on { "включено" } else { "отключено — не будет запускаться при входе в Windows" }),+ Err(5) => format!("«{}»: нужны права администратора", it.name),+ Err(e) => format!("«{}»: ошибка Win32 {e}", it.name),+ },+ None => return,+ }+ };+ self.data.borrow_mut().load_startup();+ self.rebuild();+ self.toast(&msg);+ }++ fn confirm(&self, text: &str) -> bool {+ let p = nwg::MessageParams { title: "Подтверждение", content: text, buttons: nwg::MessageButtons::YesNo, icons: nwg::MessageIcons::Warning };+ nwg::modal_message(&self.win, &p) == nwg::MessageChoice::Yes+ }++ fn export(&self) {+ let ui = self.ui.borrow();+ if !ui.has_table() {+ drop(ui);+ return self.toast("На этой странице нечего экспортировать");+ }+ let esc = |s: &str| format!("\"{}\"", s.replace('"', "\"\""));+ let mut out = String::from("\u{feff}");+ out += &columns(ui.page).iter().map(|c| esc(c.title)).collect::<Vec<_>>().join(";");+ for r in &ui.rows {+ out += "\r\n";+ out += &r.cells.iter().map(|c| esc(c)).collect::<Vec<_>>().join(";");+ }+ let (y, mo, d, h, mi, s) = sys::local_time();+ let dir = std::env::var_os("USERPROFILE").map(std::path::PathBuf::from).unwrap_or_default().join("Desktop");+ let path = dir.join(format!("rtaskmgr-{}-{y:04}{mo:02}{d:02}-{h:02}{mi:02}{s:02}.csv", page_title(ui.page)));+ drop(ui);+ match std::fs::write(&path, out) {+ Ok(()) => self.toast(&format!("Сохранено: {}", path.display())),+ Err(e) => self.toast(&format!("Не удалось сохранить CSV: {e}")),+ }+ }++ // ================= окно, тема, настройки =================+ pub fn apply_theme(&self) {+ let dark = {+ let d = self.data.borrow();+ match d.cfg.theme {+ 0 => false,+ 1 => true,+ _ => sys::system_dark(),+ }+ };+ let th = theme(dark);+ self.ui.borrow_mut().th = th;+ if let Some(h) = self.win.handle.hwnd() {+ sys::set_dark_titlebar(h, dark);+ }+ unsafe {+ let old = self.edit_brush.replace(winapi::um::wingdi::CreateSolidBrush(th.panel.c()) as isize);+ if old != 0 {+ winapi::um::wingdi::DeleteObject(old as _);+ }+ }+ set_menu_theme(dark);+ self.invalidate();+ if let Some(h) = self.search.handle.hwnd() {+ unsafe { InvalidateRect(h, null(), 1) };+ }+ }++ pub fn save_settings(&self) {+ let ui = self.ui.borrow();+ let mut d = self.data.borrow_mut();+ d.cfg.view = NAV.iter().position(|n| n.0 == ui.page).unwrap_or(0);+ let (sc, sd) = ui.sort_of(Page::Processes);+ d.cfg.sort = sc;+ d.cfg.desc = sd;+ d.cfg.rules = d.rules.clone();+ d.cfg.etw = d.etw.is_some();+ let (p, s) = (self.win.position(), self.win.size());+ if p.0 > -10000 && s.0 > 100 {+ d.cfg.pos = p;+ d.cfg.size = s;+ }+ store::save(&d.cfg);+ }++ pub fn show_window(&self) {+ self.win.set_visible(true);+ if let Some(h) = self.win.handle.hwnd() {+ unsafe {+ ShowWindow(h, SW_RESTORE);+ SetForegroundWindow(h);+ }+ }+ }++ pub fn quit(&self) {+ self.save_settings();+ if let Some(s) = self.data.borrow_mut().etw.take() {+ crate::net::stop(s);+ }+ self.tray.set_visibility(false);+ nwg::stop_thread_dispatch();+ }+}++/// pid + все его потомки (по таблице pid -> родитель).+pub fn descendants(parent_of: &HashMap<u32, u32>, roots: &[u32]) -> Vec<u32> {+ let mut out: Vec<u32> = roots.to_vec();+ let mut i = 0;+ while i < out.len() {+ let cur = out[i];+ for (&pid, &par) in parent_of {+ if par == cur && !out.contains(&pid) {+ out.push(pid);+ }+ }+ i += 1;+ }+ out+}++fn build_menu(items: &[MI], acts: &mut Vec<Act>) -> HMENU {+ unsafe {+ let m = CreatePopupMenu();+ for it in items {+ match it {+ MI::Item(t, a) => {+ acts.push(*a);+ AppendMenuW(m, MF_STRING, acts.len(), wide(t).as_ptr());+ }+ MI::Check(t, a, on) => {+ acts.push(*a);+ AppendMenuW(m, MF_STRING | if *on { MF_CHECKED } else { 0 }, acts.len(), wide(t).as_ptr());+ }+ MI::Sep => {+ AppendMenuW(m, MF_SEPARATOR, 0, null());+ }+ MI::Sub(t, sub) => {+ let h = build_menu(sub, acts);+ AppendMenuW(m, MF_POPUP, h as usize, wide(t).as_ptr());+ }+ }+ }+ m+ }+}++/// Тёмные/светлые системные меню (недокументированные функции uxtheme: 135 — SetPreferredAppMode, 136 — FlushMenuThemes).+pub fn set_menu_theme(dark: bool) {+ use winapi::um::libloaderapi::{GetProcAddress, LoadLibraryW};+ unsafe {+ let lib = LoadLibraryW(wide("uxtheme.dll").as_ptr());+ if lib.is_null() {+ return;+ }+ let set = GetProcAddress(lib, 135 as *const i8);+ let flush = GetProcAddress(lib, 136 as *const i8);+ if !set.is_null() {+ let f: extern "system" fn(i32) -> i32 = std::mem::transmute(set);+ f(if dark { 2 } else { 3 }); // ForceDark / ForceLight+ }+ if !flush.is_null() {+ let f: extern "system" fn() = std::mem::transmute(flush);+ f();+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn descendants_collects_all_once() {+ let parents = HashMap::from([(2, 1), (3, 2), (4, 1), (9, 8)]);+ let mut got = descendants(&parents, &[1]);+ got.sort();+ assert_eq!(got, vec![1, 2, 3, 4]);+ assert_eq!(descendants(&parents, &[9]), vec![9]);+ }+}diff --git a/plugins/rtaskmgr-win32/src/data.rs b/plugins/rtaskmgr-win32/src/data.rsnew file mode 100644index 0000000..36fd844--- /dev/null+++ b/plugins/rtaskmgr-win32/src/data.rs@@ -0,0 +1,585 @@+//! Данные системы: процессы, службы, автозагрузка, история, правила, показатели производительности.+//! Не знает ничего об интерфейсе.+use crate::{gpu, hw, perf, net, res::ResCache, startup, store, suspect, sys};+use std::{+ collections::{HashMap, VecDeque},+ time::Instant,+};+use store::{Rule, RuleAct};+use sysinfo::{Networks, Pid, ProcessRefreshKind, ProcessesToUpdate, System, UpdateKind};++pub const CAP: usize = 60; // точек на графиках (≈ минута)+const EMA: f32 = 2.0 / 31.0; // сглаживание ≈ среднее за 30 замеров+pub const CRITICAL: [&str; 8] = ["system", "registry", "smss.exe", "csrss.exe", "wininit.exe", "winlogon.exe", "services.exe", "lsass.exe"];++#[derive(Clone)]+pub struct Proc {+ pub pid: u32,+ pub ppid: u32,+ pub name: String,+ pub exe: Option<String>,+ pub cpu: f32, // % от всех ядер+ pub avg: f32, // среднее за ~30 с+ pub mem: u64,+ pub disk: f64, // байт/с (чтение+запись)+ pub net: f64, // байт/с, только при включённом ETW+ pub gpu: f32, // %+ pub reasons: Vec<suspect::Reason>,+ pub title: Option<String>, // заголовок видимого окна (если есть)+ pub user: String, // учётная запись; для процессов с недоступным токеном — «СИСТЕМА»+}++#[derive(Default)]+pub struct Series {+ pub cpu: VecDeque<f32>,+ pub mem: VecDeque<f32>,+ pub disk: VecDeque<f32>, // активность, %+ pub rd: VecDeque<f32>, // МБ/с+ pub wr: VecDeque<f32>,+ pub rx: VecDeque<f32>, // Кбит/с+ pub tx: VecDeque<f32>,+ pub gpu: VecDeque<f32>, // общая загрузка (максимум по адаптерам)+ pub cores: Vec<VecDeque<f32>>,+}++pub fn push(q: &mut VecDeque<f32>, v: f32) {+ if q.len() == CAP {+ q.pop_front();+ }+ q.push_back(v);+}++/// Ряды одного видеоадаптера.+#[derive(Default)]+pub struct GpuSeries {+ pub total: VecDeque<f32>,+ pub g3d: VecDeque<f32>,+ pub gcopy: VecDeque<f32>,+ pub genc: VecDeque<f32>,+ pub gdec: VecDeque<f32>,+ pub ded: VecDeque<f32>, // МБ+ pub shr: VecDeque<f32>, // МБ+}++pub struct GpuState {+ pub adapter: gpu::Adapter,+ pub reg: hw::GpuReg,+ pub util: f32,+ pub ded_used: u64,+ pub shr_used: u64,+ pub temp: Option<f32>,+ pub series: GpuSeries,+}++/// Один физический диск: сведения и ряды.+pub struct DiskState {+ pub number: u32,+ pub letters: String,+ pub info: hw::DiskInfo,+ pub formatted: u64,+ pub active: f32,+ pub rd: f64,+ pub wr: f64,+ pub ms: f32,+ pub s_active: VecDeque<f32>,+ pub s_rd: VecDeque<f32>, // МБ/с+ pub s_wr: VecDeque<f32>,+}++/// Один сетевой адаптер.+pub struct NicState {+ pub name: String,+ pub rx: f64, // байт/с+ pub tx: f64,+ pub bw: f64, // бит/с+ pub s_rx: VecDeque<f32>, // Кбит/с+ pub s_tx: VecDeque<f32>,+}++#[derive(Default)]+struct HistAcc {+ n: u32,+ cpu: f32,+ mem: f32,+ disk: f32,+ net: f32,+}++pub struct Data {+ pub sys: System,+ nets: Networks,+ pub procs: Vec<Proc>,+ ema: HashMap<u32, f32>,+ pub svcs: Vec<sys::Svc>,+ pub svc_pids: HashMap<u32, Vec<String>>,+ pub startup: Vec<startup::Item>,+ pub hist: Vec<Vec<String>>,+ pub series: Series,+ pub rules: Vec<Rule>,+ rule_cnt: HashMap<(usize, u32), u32>,+ acc: HistAcc,+ pub cfg: store::Settings,+ sig: suspect::SigCache,+ susp_info: HashMap<u32, (u8, u32)>,+ pub net: HashMap<u32, f64>,+ pub etw: Option<net::Session>,+ pub perf: Option<perf::Perf>,+ pub sample: perf::Sample,+ pub sysinfo: perf::SysInfo,+ pub meminfo: perf::MemInfo,+ pub res: ResCache,+ pub cpu_total: f32,+ pub mem_pct: f32,+ pub ticks: u32,+ prev: Instant,+ pub is_admin: bool,+ pub efficiency: std::collections::HashSet<u32>, // процессы, которым мы включили режим эффективности+ pub suspended: std::collections::HashSet<u32>, // процессы, которые мы приостановили+ pub disk_total: u64,+ pub hw_mem: hw::MemHw,+ pub gpus: Vec<GpuState>,+ pub disks: Vec<DiskState>,+ pub nics: Vec<NicState>,+ nvml: Option<hw::Nvml>,+ nvml_tried: bool,+ user_cache: HashMap<u32, String>,+ /// Температуру GPU читаем, пока открыта страница GPU (или всегда, если включено в параметрах):+ /// опрос драйвера может будить дискретную видеокарту ноутбука.+ pub want_gpu_temp: bool,+}++pub fn timestamp() -> String {+ let (y, mo, d, h, mi, _) = sys::local_time();+ format!("{y:04}-{mo:02}-{d:02} {h:02}:{mi:02}")+}++pub fn group_key(name: &str) -> String {+ name.to_lowercase()+}++impl Data {+ pub fn new(cfg: store::Settings) -> Data {+ let is_admin = sys::is_admin();+ let mut d = Data::new_inner(cfg, is_admin);+ d.gpus = gpu::adapters()+ .into_iter()+ .map(|a| GpuState { reg: hw::gpu_registry(&a.name), adapter: a, util: 0.0, ded_used: 0, shr_used: 0, temp: None, series: GpuSeries::default() })+ .collect();+ d+ }++ fn new_inner(cfg: store::Settings, is_admin: bool) -> Data {+ Data {+ sys: System::new().expect("sysinfo"),+ nets: Networks::new_with_refreshed_list().expect("сетевые интерфейсы"),+ procs: vec![],+ ema: HashMap::new(),+ svcs: vec![],+ svc_pids: HashMap::new(),+ startup: vec![],+ hist: vec![],+ series: Series::default(),+ rules: cfg.rules.clone(),+ rule_cnt: HashMap::new(),+ acc: HistAcc::default(),+ etw: if is_admin && cfg.etw { net::start() } else { None },+ cfg,+ sig: suspect::SigCache::new(),+ susp_info: HashMap::new(),+ net: HashMap::new(),+ perf: perf::Perf::new(),+ sample: perf::Sample::default(),+ sysinfo: perf::static_info(),+ meminfo: perf::MemInfo::default(),+ res: ResCache::new(),+ cpu_total: 0.0,+ mem_pct: 0.0,+ ticks: 0,+ prev: Instant::now(),+ is_admin,+ efficiency: Default::default(),+ suspended: Default::default(),+ disk_total: 0,+ hw_mem: hw::memory_hw(),+ gpus: vec![],+ disks: vec![],+ nics: vec![],+ nvml: None,+ nvml_tried: false,+ user_cache: HashMap::new(),+ want_gpu_temp: false,+ }+ }++ pub fn load_startup(&mut self) {+ self.startup = startup::list();+ }++ pub fn load_history(&mut self) {+ self.hist = store::read_history(3000);+ }++ /// Один такт обновления. Возвращает сообщения от правил (их показывает интерфейс).+ pub fn refresh(&mut self) -> Vec<String> {+ let dt = self.prev.elapsed().as_secs_f64().clamp(0.3, 5.0);+ self.prev = Instant::now();+ self.ticks += 1;+ let first = self.ticks == 1; // первый замер у sysinfo неточный — не рисуем его+ self.sys.refresh_cpu_usage();+ self.sys.refresh_memory();+ let kind = ProcessRefreshKind::nothing()+ .with_cpu()+ .with_memory()+ .with_disk_usage()+ .with_exe(UpdateKind::OnlyIfNotSet)+ .with_cmd(UpdateKind::OnlyIfNotSet);+ self.sys.refresh_processes_specifics(ProcessesToUpdate::All, true, kind);+ self.nets.refresh(true);++ self.cpu_total = if first { 0.0 } else { self.sys.global_cpu_usage() };+ let (used, total) = (self.sys.used_memory(), self.sys.total_memory().max(1));+ self.mem_pct = (100.0 * used as f64 / total as f64) as f32;+ let cores = self.sys.cpus().len().max(1) as f32;+ let cur: HashMap<u32, f32> = self.sys.processes().values().map(|p| (p.pid().as_u32(), p.cpu_usage() / cores)).collect();+ self.ema.retain(|k, _| cur.contains_key(k));+ for (k, v) in &cur {+ let e = self.ema.entry(*k).or_insert(*v);+ *e += EMA * (*v - *e);+ }+ if self.etw.is_some() {+ self.net = net::drain().into_iter().map(|(pid, (rx, tx))| (pid, (rx + tx) as f64 / dt)).collect();+ }+ self.sample = self.perf.as_mut().map(|p| p.sample()).unwrap_or_default();+ self.meminfo = perf::mem_info();+ if self.want_gpu_temp || self.cfg.gpu_temp_always {+ for g in self.gpus.iter_mut() {+ g.temp = gpu::temperature(g.adapter.luid).or_else(|| {+ // запасной путь для NVIDIA, если драйвер не отдаёт температуру через D3DKMT+ if g.adapter.vendor == 0x10DE {+ if !self.nvml_tried {+ self.nvml_tried = true;+ self.nvml = hw::Nvml::new();+ }+ self.nvml.as_ref().and_then(|n| n.temp()).map(|t| t as f32)+ } else {+ None+ }+ });+ }+ } else {+ for g in self.gpus.iter_mut() {+ g.temp = None;+ }+ }+ if self.ticks % 30 == 1 {+ self.disk_total = disk_capacity();+ }+ if self.ticks % 5 == 1 {+ self.svcs = sys::services();+ self.svc_pids.clear();+ for s in self.svcs.iter().filter(|s| s.pid != 0) {+ self.svc_pids.entry(s.pid).or_default().push(s.name.clone());+ }+ }+ let titles = if self.ticks % 2 == 1 { Some(sys::window_titles()) } else { None };++ // ---- подозрительность ----+ let windir = std::env::var("WINDIR").unwrap_or_else(|_| r"C:\Windows".into());+ let mut reasons: HashMap<u32, Vec<suspect::Reason>> = HashMap::new();+ for p in self.sys.processes().values() {+ let pid = p.pid().as_u32();+ let exe = p.exe().map(|e| e.display().to_string()).filter(|e| !e.is_empty());+ let parent = p.parent().and_then(|pp| self.sys.process(pp)).map(|x| x.name().to_string_lossy().into_owned());+ let entry = self.susp_info.entry(pid).or_insert((0, 0));+ if self.ticks >= entry.1 {+ // «файла нет» подтверждаем двумя проверками подряд (через 3 такта), иначе проверяем раз в минуту+ let missing = exe.as_deref().is_some_and(suspect::file_missing);+ entry.0 = if missing { entry.0.saturating_add(1) } else { 0 };+ entry.1 = self.ticks + if entry.0 == 1 { 3 } else { 60 };+ }+ let exists = entry.0 < 2;+ let sig = match exe.as_deref() {+ Some(e) if !e.to_lowercase().starts_with(&windir.to_lowercase()) => self.sig.get(e),+ _ => suspect::Sig::Unknown,+ };+ let name = p.name().to_string_lossy().into_owned();+ let r = suspect::assess(&suspect::Facts { name: &name, exe: exe.as_deref(), parent: parent.as_deref(), exists, sig, windir: &windir });+ if !r.is_empty() {+ reasons.insert(pid, r);+ }+ }+ self.susp_info.retain(|k, _| cur.contains_key(k));++ // ---- список процессов ----+ let old_titles: HashMap<u32, String> = self.procs.iter().filter_map(|p| p.title.clone().map(|t| (p.pid, t))).collect();+ let user_cache = &mut self.user_cache;+ let procs: Vec<Proc> = self+ .sys+ .processes()+ .values()+ .map(|p| {+ let pid = p.pid().as_u32();+ let d = p.disk_usage();+ Proc {+ pid,+ ppid: p.parent().map_or(0, |x| x.as_u32()),+ name: p.name().to_string_lossy().into_owned(),+ exe: p.exe().map(|e| e.display().to_string()).filter(|e| !e.is_empty()),+ cpu: cur.get(&pid).copied().unwrap_or(0.0),+ avg: self.ema.get(&pid).copied().unwrap_or(0.0),+ mem: p.memory(),+ disk: if first { 0.0 } else { (d.read_bytes + d.written_bytes) as f64 / dt },+ net: self.net.get(&pid).copied().unwrap_or(0.0),+ gpu: self.sample.gpu_by_pid.get(&pid).copied().unwrap_or(0.0),+ reasons: reasons.get(&pid).cloned().unwrap_or_default(),+ user: user_cache.entry(pid).or_insert_with(|| sys::process_user(pid).unwrap_or_else(|| "СИСТЕМА".into())).clone(),+ title: match &titles {+ Some(t) => t.get(&pid).cloned(),+ None => old_titles.get(&pid).cloned(),+ },+ }+ })+ .collect();+ self.procs = procs;+ self.user_cache.retain(|k, _| cur.contains_key(k));+ self.efficiency.retain(|p| cur.contains_key(p));+ self.suspended.retain(|p| cur.contains_key(p));++ // ---- ряды для графиков ----+ let (rx, tx) = self.sample.net.as_ref().map_or_else(+ || {+ let r = self.nets.iter().fold((0u64, 0u64), |a, (_, n)| (a.0 + n.received(), a.1 + n.transmitted()));+ (r.0 as f64 / dt, r.1 as f64 / dt)+ },+ |n| (n.rx, n.tx),+ );+ let per_core: Vec<f32> = self.sys.cpus().iter().map(|c| c.usage()).collect();+ if !first {+ let s = &mut self.series;+ push(&mut s.cpu, self.cpu_total);+ push(&mut s.mem, self.mem_pct);+ push(&mut s.disk, self.sample.disk_active);+ push(&mut s.rd, (self.sample.disk_read / 1_048_576.0) as f32);+ push(&mut s.wr, (self.sample.disk_write / 1_048_576.0) as f32);+ push(&mut s.rx, (rx * 8.0 / 1000.0) as f32);+ push(&mut s.tx, (tx * 8.0 / 1000.0) as f32);+ push(&mut s.gpu, self.sample.gpu_total);+ let _ = &s;+ s.cores.resize_with(per_core.len(), VecDeque::new);+ for (q, v) in s.cores.iter_mut().zip(per_core) {+ push(q, v);+ }+ }++ // ---- адаптеры, диски, сетевые интерфейсы: состояния и ряды ----+ if !first {+ for g in self.gpus.iter_mut() {+ let smp = self.sample.gpus.get(&g.adapter.luid).cloned().unwrap_or_default();+ let ty = |k: &str| smp.types.get(k).copied().unwrap_or(0.0);+ g.util = smp.total;+ g.ded_used = smp.ded;+ g.shr_used = smp.shr;+ let s = &mut g.series;+ push(&mut s.total, smp.total);+ push(&mut s.g3d, ty("3D"));+ push(&mut s.gcopy, ty("Copy"));+ push(&mut s.genc, ty("VideoEncode"));+ push(&mut s.gdec, ty("VideoDecode"));+ push(&mut s.ded, (smp.ded >> 20) as f32);+ push(&mut s.shr, (smp.shr >> 20) as f32);+ }+ for ds in &self.sample.disks {+ let i = match self.disks.iter().position(|d| d.number == ds.number) {+ Some(i) => i,+ None => {+ self.disks.push(DiskState {+ number: ds.number,+ letters: ds.letters.clone(),+ info: hw::disk_info_for(ds.number),+ formatted: hw::volumes_total(&ds.letters),+ active: 0.0,+ rd: 0.0,+ wr: 0.0,+ ms: 0.0,+ s_active: Default::default(),+ s_rd: Default::default(),+ s_wr: Default::default(),+ });+ self.disks.len() - 1+ }+ };+ let d = &mut self.disks[i];+ (d.letters, d.active, d.rd, d.wr, d.ms) = (ds.letters.clone(), ds.active, ds.rd, ds.wr, ds.ms);+ push(&mut d.s_active, ds.active);+ push(&mut d.s_rd, (ds.rd / 1_048_576.0) as f32);+ push(&mut d.s_wr, (ds.wr / 1_048_576.0) as f32);+ }+ self.disks.sort_by_key(|d| d.number);+ for n in &self.sample.nics {+ let i = match self.nics.iter().position(|x| x.name == n.name) {+ Some(i) => i,+ None => {+ self.nics.push(NicState { name: n.name.clone(), rx: 0.0, tx: 0.0, bw: 0.0, s_rx: Default::default(), s_tx: Default::default() });+ self.nics.len() - 1+ }+ };+ let x = &mut self.nics[i];+ (x.rx, x.tx, x.bw) = (n.rx, n.tx, n.bw);+ push(&mut x.s_rx, (n.rx * 8.0 / 1000.0) as f32);+ push(&mut x.s_tx, (n.tx * 8.0 / 1000.0) as f32);+ }+ // адаптеры, исчезнувшие из счётчиков (отключили кабель, выключили Wi-Fi), убираем+ let alive: std::collections::HashSet<&String> = self.sample.nics.iter().map(|n| &n.name).collect();+ self.nics.retain(|n| alive.contains(&n.name));+ }++ // ---- правила ----+ let mut notes: Vec<String> = vec![];+ for ri in 0..self.rules.len() {+ let rule = self.rules[ri].clone();+ for p in self.procs.iter().filter(|p| rule.proc == "*" || p.name.to_lowercase() == rule.proc) {+ if p.cpu > rule.cpu && !CRITICAL.contains(&p.name.to_lowercase().as_str()) {+ let c = self.rule_cnt.entry((ri, p.pid)).or_insert(0);+ *c += 1;+ if *c >= rule.secs {+ *c = 0;+ match rule.act {+ RuleAct::Lower => {+ if sys::priority_name(p.pid) != sys::PRIORITIES[1].0 && sys::set_priority(p.pid, sys::PRIORITIES[1].1) {+ notes.push(format!("Правило: «{}» (PID {}) грузил ЦП > {:.0}% — приоритет понижен", p.name, p.pid, rule.cpu));+ self.rules[ri].hits += 1;+ }+ }+ RuleAct::Notify => {+ notes.push(format!("«{}» (PID {}) грузит ЦП больше {:.0}% уже {} с", p.name, p.pid, rule.cpu, rule.secs));+ self.rules[ri].hits += 1;+ }+ }+ }+ } else {+ self.rule_cnt.remove(&(ri, p.pid));+ }+ }+ }+ self.rule_cnt.retain(|(_, pid), _| cur.contains_key(pid));++ // ---- история: одна запись в минуту ----+ if !first {+ let io = ((self.sample.disk_read + self.sample.disk_write) / 1024.0) as f32;+ let top = if self.acc.n + 1 >= 60 { self.top_consumer() } else { String::new() };+ let a = &mut self.acc;+ (a.n, a.cpu, a.mem, a.disk, a.net) = (a.n + 1, a.cpu + self.cpu_total, a.mem + self.mem_pct, a.disk + io, a.net + ((rx + tx) / 1024.0) as f32);+ if a.n >= 60 {+ let n = a.n as f32;+ store::append_history(&format!("{};{:.0};{:.0};{:.0};{:.0};{}", timestamp(), a.cpu / n, a.mem / n, a.disk / n, a.net / n, top));+ self.acc = HistAcc::default();+ }+ }+ notes+ }++ /// Главный потребитель ЦП по среднему за 30 с: «имя (N%)».+ fn top_consumer(&self) -> String {+ let mut g: HashMap<String, (String, f32)> = HashMap::new();+ for p in &self.procs {+ let e = g.entry(group_key(&p.name)).or_insert((p.name.clone(), 0.0));+ e.1 += p.avg;+ }+ g.into_values().max_by(|a, b| a.1.total_cmp(&b.1)).map_or(String::new(), |(n, v)| format!("{n} ({v:.0}%)"))+ }++ /// Подсказки «что сейчас тормозит» по текущим данным.+ pub fn hints(&self) -> Vec<String> {+ let mut out = vec![];+ let mut groups: HashMap<String, Vec<&Proc>> = HashMap::new();+ for p in &self.procs {+ groups.entry(group_key(&p.name)).or_default().push(p);+ }+ let disp = |g: &[&Proc]| if g.len() > 1 { format!("{} ({} шт.)", g[0].name, g.len()) } else { g[0].name.clone() };+ let avg = |g: &Vec<&Proc>| g.iter().map(|p| p.avg).sum::<f32>();+ let mut gs: Vec<&Vec<&Proc>> = groups.values().collect();+ gs.sort_by(|a, b| avg(b).total_cmp(&avg(a)));+ for g in gs.iter().take(3) {+ let (a, now): (f32, f32) = (avg(g), g.iter().map(|p| p.cpu).sum());+ if a >= 8.0 {+ let mut t = format!("ЦП: «{}» занимает в среднем {a:.0}% за последние 30 с (сейчас {now:.0}%).", disp(g));+ if g[0].name.eq_ignore_ascii_case("svchost.exe") {+ let top = g.iter().max_by(|x, y| x.avg.total_cmp(&y.avg)).unwrap();+ if let Some(s) = self.svc_pids.get(&top.pid) {+ t += &format!(" Самый занятый svchost (PID {}) держит службы: {}.", top.pid, s.iter().take(5).cloned().collect::<Vec<_>>().join(", "));+ }+ }+ out.push(t);+ }+ }+ if self.mem_pct >= 80.0 {+ gs.sort_by_key(|g| std::cmp::Reverse(g.iter().map(|p| p.mem).sum::<u64>()));+ let top: Vec<String> = gs.iter().take(3).map(|g| format!("{} — {}", disp(g), crate::ui::fmt_mem(g.iter().map(|p| p.mem).sum()))).collect();+ out.push(format!("Память занята на {:.0}%. Больше всего у: {}.", self.mem_pct, top.join("; ")));+ }+ let io = self.sample.disk_read + self.sample.disk_write;+ if io > 150.0 * 1_048_576.0 || self.sample.disk_active > 90.0 {+ out.push(format!("Диск загружен на {:.0}% (чтение+запись {:.0} МБ/с).", self.sample.disk_active, io / 1_048_576.0));+ }+ if self.etw.is_some() {+ gs.sort_by(|a, b| b.iter().map(|p| p.net).sum::<f64>().total_cmp(&a.iter().map(|p| p.net).sum::<f64>()));+ if let Some(g) = gs.first() {+ let n: f64 = g.iter().map(|p| p.net).sum();+ if n > 1_000_000.0 {+ out.push(format!("Сеть: «{}» передаёт {:.1} МБ/с — больше всех остальных.", disp(g), n / 1e6));+ }+ }+ }+ let high: Vec<String> = gs.iter().filter(|g| g.iter().any(|p| p.reasons.iter().any(|r| r.sev == 3))).map(|g| disp(g)).take(5).collect();+ if !high.is_empty() {+ out.push(format!("Подозрительные процессы (высокая степень): {}. Наведите курсор на метку в колонке «Подозрительное» — там причина.", high.join(", ")));+ }+ if self.cpu_total > 90.0 {+ out.push("ЦП почти полностью занят — отсортируйте процессы по ЦП, чтобы увидеть виновника.".into());+ }+ if out.is_empty() {+ out.push("Всё в порядке: ни один процесс не потребляет заметно больше обычного.".into());+ }+ out+ }+}++/// Размер системного диска, байт.+fn disk_capacity() -> u64 {+ use sysinfo::Disks;+ Disks::new_with_refreshed_list()+ .map(|d| (&d).into_iter().find(|x| x.mount_point().to_string_lossy().to_uppercase().starts_with("C:")).map_or(0, |x| x.total_space()))+ .unwrap_or(0)+}++pub fn process_cmd(d: &Data, pid: u32) -> String {+ d.sys.process(Pid::from_u32(pid)).map(|p| p.cmd().iter().map(|a| a.to_string_lossy().into_owned()).collect::<Vec<_>>().join(" ")).unwrap_or_default()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn series_keeps_only_cap_points() {+ let mut q = VecDeque::new();+ for i in 0..(CAP + 30) {+ push(&mut q, i as f32);+ }+ assert_eq!(q.len(), CAP);+ assert_eq!(*q.front().unwrap(), 30.0);+ }++ #[test]+ fn refresh_fills_processes_and_series() {+ let mut d = Data::new(store::Settings::default());+ d.refresh();+ std::thread::sleep(std::time::Duration::from_millis(1200));+ d.refresh();+ assert!(d.procs.len() > 20);+ assert!(d.procs.iter().any(|p| p.pid == std::process::id()));+ assert_eq!(d.series.cpu.len(), 1); // первый замер отбрасывается+ assert!(d.meminfo.processes > 0);+ assert!(!d.hints().is_empty());+ }+}diff --git a/plugins/rtaskmgr-win32/src/draw.rs b/plugins/rtaskmgr-win32/src/draw.rsnew file mode 100644index 0000000..57c2ce5--- /dev/null+++ b/plugins/rtaskmgr-win32/src/draw.rs@@ -0,0 +1,847 @@+//! Отрисовка страниц: боковая панель, шапка, таблицы, «Производительность», «Что тормозит», «Параметры».+use crate::{app::*, data::*, model::*, ui::*};+use std::collections::{HashMap, VecDeque};+use winapi::shared::windef::POINT;++pub const ROW_H: f64 = 28.0;+pub const NAV_W: f64 = 48.0;+pub const NAV_W_OPEN: f64 = 220.0;+pub const BAND_H: f64 = 52.0;++pub fn series_color(i: usize, dark: bool) -> Rgb {+ let c = [Rgb(23, 169, 208), Rgb(86, 124, 214), Rgb(82, 177, 95), Rgb(224, 138, 60), Rgb(176, 92, 216)][i.min(4)];+ if dark { c } else { c.lerp(Rgb(0, 0, 0), 0.18) }+}++/// График: сетка, заливка под линией и сама линия; самое новое значение — справа.+pub fn draw_graph(g: &G, r: R, series: &[(&VecDeque<f32>, Rgb)], ymax: f32, grid: bool) {+ let th = g.th;+ g.fill(r, th.bg.lerp(if th.dark { Rgb(0, 0, 0) } else { Rgb(255, 255, 255) }, 0.12));+ if grid {+ let (cols, rows) = (20, 10);+ let gc = th.border.lerp(th.bg, 0.25);+ for i in 1..cols {+ g.vline(r.l + r.w() * i / cols, r.t, r.b, gc);+ }+ for i in 1..rows {+ g.hline(r.l, r.r, r.t + r.h() * i / rows, gc);+ }+ }+ g.clip(r.inset(1));+ for (data, color) in series {+ let n = data.len();+ if n < 2 {+ continue;+ }+ let pt = |i: usize, v: f32| POINT {+ x: r.r - ((n - 1 - i) as i32) * r.w() / (CAP as i32 - 1),+ y: r.b - 1 - ((v / ymax.max(0.001)).clamp(0.0, 1.0) * (r.h() - 2) as f32) as i32,+ };+ let pts: Vec<POINT> = data.iter().enumerate().map(|(i, &v)| pt(i, v)).collect();+ let mut poly = pts.clone();+ poly.push(POINT { x: pts[n - 1].x, y: r.b });+ poly.push(POINT { x: pts[0].x, y: r.b });+ g.polygon(&poly, th.bg.lerp(*color, 0.28));+ g.polyline(&pts, *color, g.px(1.5).max(1));+ }+ g.unclip();+ let first = series.first().map_or(th.border, |s| s.1);+ g.frame(r, th.bg.lerp(first, 0.75));+}++impl App {+ // ---------------- боковая панель ----------------+ pub fn draw_nav(&self, g: &G, ui: &Ui, lay: &Lay) {+ let th = g.th;+ g.fill(lay.nav, th.nav);+ g.glyph(lay.nav_toggle, '\u{E700}', th.text, false);+ if ui.hit == Hit::NavToggle {+ g.round(lay.nav_toggle.inset(g.px(2.0)), g.px(4.0), Some(th.hover), None);+ g.glyph(lay.nav_toggle, '\u{E700}', th.text, false);+ }+ for (i, r) in lay.nav_items.iter().enumerate() {+ let (page, icon, label) = NAV[i];+ let sel = page == ui.page;+ let hov = ui.hit == Hit::Nav(i);+ if sel || hov {+ g.round(r.inset(g.px(3.0)), g.px(5.0), Some(if sel { th.sel } else { th.hover }), None);+ }+ if sel {+ g.round(R::new(r.l + g.px(3.0), r.t + r.h() / 2 - g.px(8.0), r.l + g.px(6.0), r.t + r.h() / 2 + g.px(8.0)), g.px(2.0), Some(th.accent), None);+ }+ let ir = R::new(r.l, r.t, r.l + g.px(NAV_W), r.b);+ g.glyph(ir, icon, if sel { th.accent } else { th.text }, false);+ if ui.nav_open {+ g.text(R::new(r.l + g.px(NAV_W), r.t, r.r - g.px(8.0), r.b), label, Font::Ui, th.text);+ }+ }+ }++ // ---------------- шапка страницы ----------------+ pub fn draw_band(&self, g: &G, ui: &Ui, d: &Data, lay: &Lay) {+ let th = g.th;+ g.fill(lay.band, th.bg);+ g.text(lay.title, page_title(ui.page), Font::Title, th.text);+ if ui.page_has_search() {+ g.round(lay.search, g.px(5.0), Some(th.panel), Some(th.border));+ g.hline(lay.search.l + g.px(5.0), lay.search.r - g.px(5.0), lay.search.b - 1, th.accent.lerp(th.panel, 0.4));+ g.glyph(R::new(lay.search.r - g.px(32.0), lay.search.t, lay.search.r - g.px(4.0), lay.search.b), '\u{E721}', th.dim, true);+ }+ for (r, btn, label, glyph) in &lay.buttons {+ let enabled = self.btn_enabled(ui, d, *btn);+ let hov = enabled && ui.hit == Hit::Button(*btn);+ if hov {+ g.round(*r, g.px(5.0), Some(th.hover), None);+ }+ let c = if enabled { th.text } else { th.dim.lerp(th.bg, 0.35) };+ let gr = R::new(r.l + g.px(8.0), r.t, r.l + g.px(30.0), r.b);+ g.glyph(gr, *glyph, if enabled && *btn == Btn::Efficiency { Rgb(110, 200, 120) } else { c }, true);+ if !label.is_empty() {+ g.text(R::new(r.l + g.px(32.0), r.t, r.r - g.px(8.0), r.b), label, Font::Ui, c);+ }+ }+ g.hline(lay.band.l, lay.band.r, lay.band.b - 1, th.border);+ }++ // ---------------- таблица ----------------+ pub fn draw_table(&self, g: &G, ui: &Ui, d: &Data, lay: &Lay) {+ let th = g.th;+ let page = ui.page;+ let cols = columns(page);+ let xs = &lay.col_x;+ let area = lay.rows_area;++ // шапка+ let sort = ui.sort_of(page);+ for (i, c) in cols.iter().enumerate() {+ let cell = R::new(xs[i], lay.header.t, xs[i + 1], lay.header.b);+ let mut fill = None;+ if let Some(m) = c.metric {+ let agg = agg_value(d, m);+ fill = Some(heat(&th, agg, 100.0));+ }+ if let Some(f) = fill {+ g.fill(cell, f);+ }+ let hov = ui.hit == Hit::Header(i);+ if hov || sort.0 == i {+ g.fill(cell, if th.dark { th.heat1.lerp(th.bg, 0.45).lerp(fill.unwrap_or(th.bg), 0.5) } else { th.hover });+ if let Some(f) = fill.filter(|_| sort.0 != i) {+ g.fill(cell, f.lerp(th.text, 0.06));+ }+ }+ let inner = cell.inset(g.px(8.0));+ if let Some(m) = c.metric {+ let val = agg_text(d, m);+ if page == Page::Processes {+ let top = R::new(inner.l, cell.t + g.px(8.0), inner.r, cell.t + g.px(32.0));+ g.text_right(top, &val, Font::Big, th.text);+ g.text_right(R::new(inner.l, cell.t + g.px(32.0), inner.r, cell.b - g.px(4.0)), c.title, Font::Small, th.dim);+ } else {+ g.text_right(inner, c.title, Font::Semibold, th.text);+ }+ } else if c.align == Align::Right {+ g.text_right(R::new(inner.l, cell.t, inner.r, cell.b - if page == Page::Processes { g.px(4.0) } else { 0 }), c.title, if page == Page::Processes { Font::Small } else { Font::Semibold }, if page == Page::Processes { th.dim } else { th.text });+ } else {+ let lr = R::new(inner.l + if i == 0 { g.px(12.0) } else { 0 }, if page == Page::Processes { cell.b - g.px(28.0) } else { cell.t }, inner.r, cell.b - if page == Page::Processes { g.px(2.0) } else { 0 });+ g.text(lr, c.title, if page == Page::Processes { Font::Small } else { Font::Semibold }, if page == Page::Processes { th.dim } else { th.text });+ }+ if sort.0 == i {+ let ch = if sort.1 { '\u{E70D}' } else { '\u{E70E}' }; // стрелка вниз/вверх+ let ar = R::new(cell.l + (cell.w() - g.px(16.0)) / 2, cell.t + g.px(0.0), cell.l + (cell.w() + g.px(16.0)) / 2, cell.t + g.px(12.0));+ if c.metric.is_some() {+ g.glyph(ar, ch, th.text, true);+ } else {+ g.glyph(R::new(cell.r - g.px(24.0), cell.t, cell.r - g.px(4.0), cell.t + g.px(14.0)), ch, th.dim, true);+ }+ }+ if i > 0 {+ g.vline(cell.l, lay.header.t, lay.header.b, th.border);+ }+ }+ g.hline(lay.header.l, lay.header.r, lay.header.b - 1, th.border);++ // строки+ let row_h = g.px(ROW_H);+ g.clip(area);+ let first = (ui.scroll / row_h as f64).floor().max(0.0) as usize;+ let last = ((ui.scroll + area.h() as f64) / row_h as f64).ceil() as usize + 1;+ for (i, row) in ui.rows.iter().enumerate().skip(first).take(last.saturating_sub(first)) {+ let y = area.t + i as i32 * row_h - ui.scroll as i32;+ let selected = ui.sel.as_deref() == Some(row.key.as_str());+ let hovered = matches!(ui.hit, Hit::Row(j) | Hit::Chevron(j) if j == i);+ let base = if selected { th.sel } else if hovered { th.hover } else { th.bg };+ g.fill(R::new(area.l, y, xs[cols.len()].min(area.r), y + row_h), base);+ for (ci, c) in cols.iter().enumerate() {+ let cell = R::new(xs[ci], y, xs[ci + 1], y + row_h);+ let mut tc = th.text;+ if let Some(Some((v, scale))) = row.heat.get(ci) {+ let h = heat(&th, *v, *scale);+ g.fill(cell, if selected { h.lerp(th.text, 0.07) } else if hovered { h.lerp(th.text, 0.04) } else { h });+ if *v < 0.05 {+ tc = th.dim;+ }+ }+ let text = row.cells.get(ci).map(String::as_str).unwrap_or("");+ let inner = R::new(cell.l + g.px(8.0), cell.t, cell.r - g.px(8.0), cell.b);+ if ci == 0 {+ let mut x = inner.l + g.px(4.0) + row.depth as i32 * g.px(22.0);+ if matches!(page, Page::Processes | Page::Users) {+ if row.expandable {+ g.glyph(R::new(x - g.px(4.0), y, x + g.px(14.0), y + row_h), if row.expanded { '\u{E70D}' } else { '\u{E76C}' }, th.dim, true);+ }+ x += g.px(18.0);+ }+ if row.icon_path.is_some() || page == Page::Processes || (page == Page::Users && row.depth > 0) {+ let sz = g.px(16.0);+ let ico = row.icon_path.as_deref().and_then(|p| d.res.get(p)).map_or(0, |r| r.icon);+ g.icon(if ico != 0 { ico } else { d.res.generic_icon }, x, y + (row_h - sz) / 2, sz);+ x += sz + g.px(8.0);+ }+ g.text(R::new(x, y, inner.r, y + row_h), text, Font::Ui, th.text);+ } else if page == Page::Processes && ci == cols.len() - 1 && row.sev > 0 {+ let col = match row.sev {+ 3 => th.bad,+ 2 => th.warn,+ _ => th.dim,+ };+ g.text(inner, text, Font::Ui, col);+ } else if c.align == Align::Right {+ g.text_right(inner, text, Font::Ui, tc);+ } else {+ g.text(inner, text, Font::Ui, tc);+ }+ }+ for ci in 1..cols.len() {+ if cols[ci].metric.is_some() || cols[ci - 1].metric.is_some() {+ g.vline(xs[ci], y, y + row_h, th.border);+ }+ }+ }+ g.unclip();++ if ui.rows.is_empty() {+ let msg = if ui.search.is_empty() { "Нет данных" } else { "Ничего не найдено" };+ g.text_center(R::new(area.l, area.t + g.px(30.0), area.r, area.t + g.px(70.0)), msg, Font::Ui, th.dim);+ }++ // полоса прокрутки+ let content = ui.rows.len() as f64 * row_h as f64;+ if content > area.h() as f64 {+ let track = lay.vbar;+ let thumb_h = ((area.h() as f64 / content) * track.h() as f64).max(g.px(24.0) as f64);+ let max_scroll = content - area.h() as f64;+ let ty = track.t as f64 + (ui.scroll / max_scroll) * (track.h() as f64 - thumb_h);+ let active = ui.drag.is_some() || ui.hit == Hit::VBar;+ let w = if active { g.px(6.0) } else { g.px(3.0) };+ g.round(R::new(track.r - w - g.px(2.0), ty as i32, track.r - g.px(2.0), (ty + thumb_h) as i32), g.px(2.0), Some(th.dim.lerp(th.bg, if active { 0.0 } else { 0.35 })), None);+ }+ }++ // ---------------- «Что тормозит» ----------------+ pub fn draw_insights(&self, g: &G, ui: &Ui, d: &Data, lay: &Lay) {+ let th = g.th;+ let mut y = lay.body.t + g.px(16.0) - ui.scroll as i32;+ let w = (lay.body.w() - g.px(48.0)).min(g.px(900.0));+ g.clip(lay.body);+ for h in d.hints() {+ let th_h = g.wrap_h(&h, Font::Ui, w - g.px(32.0)) + g.px(24.0);+ let r = R::new(lay.body.l + g.px(24.0), y, lay.body.l + g.px(24.0) + w, y + th_h);+ g.round(r, g.px(6.0), Some(th.panel), Some(th.border));+ g.text_wrapped(R::new(r.l + g.px(16.0), r.t + g.px(12.0), r.r - g.px(16.0), r.b - g.px(12.0)), &h, Font::Ui, th.text);+ y += th_h + g.px(10.0);+ }+ g.unclip();+ }++ // ---------------- «Параметры» ----------------+ pub fn draw_settings(&self, g: &G, ui: &Ui, d: &Data, lay: &Lay) {+ let th = g.th;+ g.clip(lay.body);+ for (r, id) in &lay.setting_cards {+ g.round(*r, g.px(6.0), Some(th.panel), Some(th.border));+ let (title, desc) = setting_text(*id);+ g.text(R::new(r.l + g.px(16.0), r.t + g.px(8.0), r.r - g.px(220.0), r.t + g.px(30.0)), title, Font::Semibold, th.text);+ g.text(R::new(r.l + g.px(16.0), r.t + g.px(30.0), r.r - g.px(220.0), r.b - g.px(6.0)), desc, Font::Small, th.dim);+ let ctl = R::new(r.r - g.px(200.0), r.t, r.r - g.px(16.0), r.b);+ match id {+ SettingId::Theme => {+ let seg = ["Светлая", "Тёмная", "Системная"];+ let sw = ctl.w() / 3;+ for (i, s) in seg.iter().enumerate() {+ let sr = R::new(ctl.l + i as i32 * sw, r.t + g.px(14.0), ctl.l + (i as i32 + 1) * sw, r.b - g.px(14.0));+ let on = d.cfg.theme as usize == i;+ g.round(sr, g.px(4.0), Some(if on { th.accent } else { th.bg }), Some(th.border));+ g.text_center(sr, s, Font::Small, if on { if th.dark { Rgb(0, 0, 0) } else { Rgb(255, 255, 255) } } else { th.text });+ }+ }+ _ => {+ let on = setting_on(*id, d);+ let enabled = !(*id == SettingId::Etw && !d.is_admin);+ let t = R::new(ctl.r - g.px(44.0), r.t + r.h() / 2 - g.px(10.0), ctl.r, r.t + r.h() / 2 + g.px(10.0));+ g.round(t, g.px(10.0), Some(if on { th.accent } else { th.bg }), Some(if on { th.accent } else { th.dim }));+ let kn = g.px(7.0);+ let cx = if on { t.r - g.px(11.0) } else { t.l + g.px(11.0) };+ g.round(R::new(cx - kn, t.t + g.px(10.0) - kn, cx + kn, t.t + g.px(10.0) + kn), kn, Some(if on { if th.dark { Rgb(0, 0, 0) } else { Rgb(255, 255, 255) } } else { th.dim }), None);+ if !enabled {+ g.text_right(R::new(ctl.l, r.t, t.l - g.px(10.0), r.b), "нужен администратор", Font::Small, th.dim);+ }+ }+ }+ }+ g.unclip();+ let _ = ui;+ }++ // ---------------- «Производительность» ----------------+ pub fn draw_performance(&self, g: &G, ui: &Ui, d: &Data, lay: &Lay) {+ let th = g.th;+ let items = perf_items(d);+ let sel_idx = items.iter().position(|i| i.kind == ui.perf_sel).unwrap_or(0);+ g.fill(lay.perf_list, th.bg);+ for (i, r) in lay.perf_items.iter().enumerate() {+ let it = &items[i];+ let sel = sel_idx == i;+ let hov = ui.hit == Hit::PerfItem(i);+ if sel || hov {+ g.round(r.inset(g.px(2.0)), g.px(6.0), Some(if sel { th.sel } else { th.hover }), None);+ }+ let thumb = R::new(r.l + g.px(10.0), r.t + g.px(10.0), r.l + g.px(10.0) + g.px(72.0), r.b - g.px(10.0));+ draw_graph(g, thumb, &it.graphs[0].series, it.graphs[0].ymax, false);+ let tx = thumb.r + g.px(10.0);+ g.text(R::new(tx, r.t + g.px(10.0), r.r - g.px(6.0), r.t + g.px(30.0)), &it.title, Font::Ui, th.text);+ g.text(R::new(tx, r.t + g.px(30.0), r.r - g.px(6.0), r.t + g.px(48.0)), &it.line1, Font::Small, th.dim);+ g.text(R::new(tx, r.t + g.px(46.0), r.r - g.px(6.0), r.t + g.px(64.0)), &it.line2, Font::Small, th.dim);+ }+ g.vline(lay.perf_list.r, lay.perf_list.t, lay.perf_list.b, th.border);++ let m = lay.perf_main;+ let it = &items[sel_idx];+ g.text(R::new(m.l, m.t, m.r - g.px(420.0), m.t + g.px(48.0)), &it.big_title, Font::Huge, th.text);+ g.text_right(R::new(m.r - g.px(420.0), m.t + g.px(10.0), m.r, m.t + g.px(40.0)), &it.device, Font::Big, th.text);++ let frac = match it.layout {+ GLayout::Single => 0.50,+ GLayout::Stack => 0.50,+ GLayout::Grid => 0.56,+ };+ let block_h = ((m.h() as f64 * frac) as i32).max(g.px(180.0));+ let block = R::new(m.l, m.t + g.px(56.0), m.r, m.t + g.px(56.0) + block_h);+ self.draw_graph_block(g, it, block);+ g.text(R::new(m.l, block.b + g.px(2.0), m.l + g.px(200.0), block.b + g.px(20.0)), "60 секунд", Font::Small, th.dim);+ g.text_right(R::new(m.r - g.px(100.0), block.b + g.px(2.0), m.r, block.b + g.px(20.0)), "0", Font::Small, th.dim);+ let mut y = block.b + g.px(30.0);+ if let Some((cap, segs)) = &it.composition {+ g.text(R::new(m.l, y, m.r, y + g.px(18.0)), cap, Font::Small, th.dim);+ let br = R::new(m.l, y + g.px(22.0), m.r, y + g.px(22.0) + g.px(28.0));+ g.fill(br, th.bg.lerp(th.text, 0.06));+ let mut x = br.l;+ for (frac, color) in segs {+ let w = (br.w() as f32 * frac) as i32;+ g.fill(R::new(x, br.t, (x + w).min(br.r), br.b), *color);+ x += w;+ }+ g.frame(br, th.border);+ y = br.b + g.px(18.0);+ }+ // крупные показатели слева и перечень сведений справа+ let colw = g.px(200.0);+ let cols = it.stat_cols.max(1);+ let (mut bx, mut by) = (m.l, y);+ for (i, (label, value)) in it.stats.iter().enumerate() {+ if i > 0 && i % cols == 0 {+ bx = m.l;+ by += g.px(66.0);+ }+ g.text(R::new(bx, by, bx + colw, by + g.px(18.0)), label, Font::Small, th.dim);+ g.text(R::new(bx, by + g.px(18.0), bx + colw + g.px(10.0), by + g.px(48.0)), value, Font::Big, th.text);+ bx += colw + g.px(20.0);+ }+ let rx = (m.l + cols as i32 * (colw + g.px(20.0)) + g.px(40.0)).max(m.r - g.px(520.0));+ let mut ry = y;+ for (k, v) in &it.facts {+ g.text(R::new(rx, ry, rx + g.px(230.0), ry + g.px(22.0)), k, Font::Small, th.dim);+ g.text(R::new(rx + g.px(230.0), ry, m.r, ry + g.px(22.0)), v, Font::Small, th.text);+ ry += g.px(22.0);+ }+ }++ /// Графики страницы: один большой, два друг под другом или сетка 2×N.+ fn draw_graph_block(&self, g: &G, it: &PerfItem, r: R) {+ let gap = g.px(10.0);+ let one = |gs: &GraphSpec, rr: R| {+ let lab = g.px(18.0);+ g.text(R::new(rr.l, rr.t, rr.r - g.px(120.0), rr.t + lab), &gs.label, Font::Small, g.th.dim);+ g.text_right(R::new(rr.r - g.px(160.0), rr.t, rr.r, rr.t + lab), &gs.right, Font::Small, g.th.dim);+ draw_graph(g, R::new(rr.l, rr.t + lab + g.px(2.0), rr.r, rr.b), &gs.series, gs.ymax, true);+ };+ match it.layout {+ GLayout::Single => one(&it.graphs[0], r),+ GLayout::Stack => {+ let h1 = (r.h() as f32 * 0.62) as i32;+ one(&it.graphs[0], R::new(r.l, r.t, r.r, r.t + h1 - gap / 2));+ if let Some(g2) = it.graphs.get(1) {+ one(g2, R::new(r.l, r.t + h1 + gap / 2, r.r, r.b));+ }+ }+ GLayout::Grid => {+ let n = it.graphs.len() as i32;+ let rows = (n + 1) / 2;+ let (cw, ch) = ((r.w() - gap) / 2, (r.h() - gap * (rows - 1)) / rows);+ for (i, gs) in it.graphs.iter().enumerate() {+ let (cx, cy) = (r.l + (i as i32 % 2) * (cw + gap), r.t + (i as i32 / 2) * (ch + gap));+ one(gs, R::new(cx, cy, cx + cw, cy + ch));+ }+ }+ }+ }++ // ---------------- подсказка и уведомление ----------------+ pub fn draw_overlay(&self, g: &G, ui: &Ui, client: R) {+ let th = g.th;+ if let Some((text, (mx, my))) = &ui.tip {+ let w = g.px(430.0);+ let h = g.wrap_h(text, Font::Small, w - g.px(24.0)) + g.px(20.0);+ let mut x = mx + g.px(14.0);+ let mut y = my + g.px(20.0);+ if x + w > client.r {+ x = client.r - w - g.px(6.0);+ }+ if y + h > client.b {+ y = my - h - g.px(8.0);+ }+ let r = R::new(x, y, x + w, y + h);+ g.round(r, g.px(6.0), Some(th.panel), Some(th.dim.lerp(th.bg, 0.4)));+ g.text_wrapped(R::new(r.l + g.px(12.0), r.t + g.px(8.0), r.r - g.px(12.0), r.b - g.px(8.0)), text, Font::Small, th.text);+ }+ if let Some((msg, _)) = &ui.toast {+ let tw = g.text_w(msg, Font::Ui).min(client.w() - g.px(160.0)) + g.px(40.0);+ let r = R::new(client.l + (client.w() - tw) / 2 + g.px(20.0), client.b - g.px(60.0), client.l + (client.w() + tw) / 2 + g.px(20.0), client.b - g.px(20.0));+ g.round(r, g.px(6.0), Some(th.panel), Some(th.dim.lerp(th.bg, 0.5)));+ g.text_center(r.inset(g.px(8.0)), msg, Font::Ui, th.text);+ }+ }+}++fn agg_value(d: &Data, m: Metric) -> f64 {+ match m {+ Metric::Cpu => d.cpu_total as f64,+ Metric::Mem => d.mem_pct as f64,+ Metric::Disk => d.sample.disk_active as f64,+ Metric::Net => d.sample.net_util as f64,+ Metric::Gpu => d.sample.gpu_total as f64,+ }+}++fn agg_text(d: &Data, m: Metric) -> String {+ format!("{:.0}%", agg_value(d, m))+}++#[derive(Clone, Copy, PartialEq, Debug)]+pub enum SettingId {+ Theme,+ Tray,+ Autostart,+ Etw,+ GpuTemp,+}++pub fn setting_text(id: SettingId) -> (&'static str, &'static str) {+ match id {+ SettingId::Theme => ("Тема оформления", "Светлая, тёмная или как в системе"),+ SettingId::Tray => ("Закрытие окна сворачивает в трей", "Программа продолжит собирать историю и применять правила; вернуть окно можно по Ctrl+Alt+T"),+ SettingId::Autostart => ("Запускать при входе в Windows", "Сразу в трей, без окна"),+ SettingId::Etw => ("Сеть по процессам", "Колонка «Сеть» в процессах (ETW). Требуются права администратора"),+ SettingId::GpuTemp => ("Всегда читать температуру GPU", "Иначе температура читается только на странице GPU. Постоянный опрос может будить дискретную видеокарту ноутбука"),+ }+}++pub fn setting_on(id: SettingId, d: &Data) -> bool {+ match id {+ SettingId::Theme => false,+ SettingId::Tray => d.cfg.to_tray,+ SettingId::Autostart => crate::startup::self_autostart(),+ SettingId::Etw => d.etw.is_some(),+ SettingId::GpuTemp => d.cfg.gpu_temp_always,+ }+}++pub struct GraphSpec<'a> {+ pub label: String,+ pub right: String,+ pub series: Vec<(&'a VecDeque<f32>, Rgb)>,+ pub ymax: f32,+}++#[derive(Clone, Copy, PartialEq)]+pub enum GLayout {+ Single,+ Stack,+ Grid,+}++/// Какой ресурс показывает пункт списка слева.+#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]+pub enum PerfKind {+ Cpu,+ Mem,+ Disk(usize),+ Nic(usize),+ Gpu(usize),+}++/// Пункты списка: ЦП, память, каждый физический диск, каждый сетевой адаптер, каждая видеокарта.+pub fn perf_kinds(d: &Data) -> Vec<PerfKind> {+ let mut v = vec![PerfKind::Cpu, PerfKind::Mem];+ v.extend((0..d.disks.len()).map(PerfKind::Disk));+ v.extend((0..d.nics.len()).map(PerfKind::Nic));+ v.extend((0..d.gpus.len()).map(PerfKind::Gpu));+ v+}++/// Элемент списка ресурсов слева на странице «Производительность» и данные для правой части.+pub struct PerfItem<'a> {+ pub kind: PerfKind,+ pub title: String,+ pub line1: String,+ pub line2: String,+ pub graphs: Vec<GraphSpec<'a>>,+ pub layout: GLayout,+ pub big_title: String,+ pub device: String,+ pub stats: Vec<(String, String)>,+ pub stat_cols: usize,+ pub facts: Vec<(String, String)>,+ pub composition: Option<(String, Vec<(f32, Rgb)>)>,+}++fn gb(b: u64) -> String {+ format!("{} ГБ", dec(b as f64 / 1_073_741_824.0, 1))+}++fn mb_cache(b: u64) -> String {+ if b >= 1 << 20 { format!("{} МБ", dec(b as f64 / 1_048_576.0, 1)) } else { format!("{} КБ", b >> 10) }+}++/// Название подключения по имени адаптера: «Wi-Fi», «Ethernet», «Bluetooth» …+pub fn conn_name(adapter: &str) -> &'static str {+ let l = adapter.to_lowercase();+ if l.contains("wi-fi") || l.contains("wireless") || l.contains("wlan") || l.contains("802.11") {+ "Wi-Fi"+ } else if l.contains("bluetooth") {+ "Bluetooth"+ } else if l.contains("vmware") || l.contains("virtual") || l.contains("hyper-v") || l.contains("vethernet") || l.contains("vpn") || l.contains("tap-") {+ "Виртуальный адаптер"+ } else {+ "Ethernet"+ }+}++pub fn perf_items(d: &Data) -> Vec<PerfItem<'_>> {+ let dark = d.cfg.theme != 0 && (d.cfg.theme == 1 || crate::sys::system_dark());+ let col = |i| series_color(i, dark);+ let s = &d.series;+ let last = |q: &VecDeque<f32>| q.back().copied().unwrap_or(0.0);+ let si = &d.sysinfo;+ let speed = si.base_mhz as f32 * d.sample.cpu_perf.max(1.0) / 100.0 / 1000.0;+ let total = d.sys.total_memory();+ let used = d.sys.used_memory();+ let cpu_brand = d.sys.cpus().first().map_or(String::new(), |c| c.brand().to_string());+ let m = &d.meminfo;+ let ms = |x: f64| format!("{} МБ/с", dec(x / 1_048_576.0, 1));+ let gspec = |label: &str, right: &str, q, color, ymax| GraphSpec { label: label.into(), right: right.into(), series: vec![(q, color)], ymax };+ let kinds = perf_kinds(d);+ let mut v = vec![];++ // для одинаковых названий подключений добавляем номер: «Wi-Fi», «Wi-Fi 2»+ let nic_titles: Vec<String> = {+ let mut seen: HashMap<&str, usize> = HashMap::new();+ d.nics+ .iter()+ .map(|n| {+ let c = conn_name(&n.name);+ let k = seen.entry(c).or_insert(0);+ *k += 1;+ if *k > 1 { format!("{c} {k}") } else { c.to_string() }+ })+ .collect()+ };++ for kind in kinds {+ match kind {+ PerfKind::Cpu => v.push(PerfItem {+ kind,+ title: "ЦП".into(),+ line1: format!("{:.0}% {} ГГц", last(&s.cpu), dec(speed as f64, 2)),+ line2: String::new(),+ graphs: vec![gspec("% использования", "100%", &s.cpu, col(0), 100.0)],+ layout: GLayout::Single,+ big_title: "ЦП".into(),+ device: cpu_brand.clone(),+ stats: vec![+ ("Использование".into(), format!("{:.0}%", last(&s.cpu))),+ ("Скорость".into(), format!("{} ГГц", dec(speed as f64, 2))),+ ("Процессы".into(), m.processes.to_string()),+ ("Потоки".into(), m.threads.to_string()),+ ("Дескрипторы".into(), m.handles.to_string()),+ ("Время работы".into(), fmt_uptime(crate::perf::uptime_secs())),+ ],+ stat_cols: 2,+ facts: vec![+ ("Базовая скорость:".into(), format!("{} ГГц", dec(si.base_mhz as f64 / 1000.0, 2))),+ ("Сокетов:".into(), si.sockets.to_string()),+ ("Ядер:".into(), sysinfo::System::physical_core_count().unwrap_or(0).to_string()),+ ("Логических процессоров:".into(), d.sys.cpus().len().to_string()),+ ("Виртуализация:".into(), if si.virt { "Включено" } else { "Отключено" }.into()),+ ("Кэш L1:".into(), mb_cache(si.l1)),+ ("Кэш L2:".into(), mb_cache(si.l2)),+ ("Кэш L3:".into(), mb_cache(si.l3)),+ ],+ composition: None,+ }),++ PerfKind::Mem => {+ let avail = total.saturating_sub(used);+ let mh = &d.hw_mem;+ let kind_txt = mh.kind();+ let reserved = (mh.installed_mb() * 1_048_576).saturating_sub(total);+ let compressed = d.procs.iter().find(|p| p.name.eq_ignore_ascii_case("Memory Compression")).map_or(0, |p| p.mem);+ let cached = if d.sample.mem_modified + d.sample.mem_standby > 0 { d.sample.mem_modified + d.sample.mem_standby } else { m.cache };+ let mut facts: Vec<(String, String)> = vec![];+ if !mh.dimms.is_empty() {+ facts.push(("Скорость:".into(), format!("{} МТ/с", mh.speed())));+ facts.push(("Использовано слотов:".into(), format!("{} из {}", mh.dimms.len(), mh.slots.max(mh.dimms.len() as u32))));+ facts.push(("Форм-фактор:".into(), mh.form().into()));+ facts.push(("Зарезервировано аппаратурой:".into(), format!("{} МБ", dec(reserved as f64 / 1_048_576.0, 0))));+ if !kind_txt.is_empty() {+ facts.push(("Тип:".into(), kind_txt.into()));+ }+ if let Some(d0) = mh.dimms.first().filter(|x| !x.mfr.is_empty()) {+ facts.push(("Производитель:".into(), d0.mfr.clone()));+ }+ }+ let t = total.max(1) as f32;+ let (mut seg, mut parts): (Vec<(f32, Rgb)>, Vec<String>) = (vec![], vec![]);+ seg.push((used as f32 / t, col(1)));+ parts.push(format!("Используется {}", gb(used)));+ if d.sample.mem_modified > 0 {+ seg.push((d.sample.mem_modified as f32 / t, col(1).lerp(Rgb(255, 255, 255), 0.25)));+ parts.push(format!("Изменено {}", gb(d.sample.mem_modified)));+ }+ if d.sample.mem_standby > 0 {+ seg.push(((d.sample.mem_standby.min(avail)) as f32 / t, col(1).lerp(Rgb(128, 128, 128), 0.6)));+ parts.push(format!("В режиме ожидания {}", gb(d.sample.mem_standby)));+ }+ if d.sample.mem_free > 0 {+ parts.push(format!("Свободно {}", gb(d.sample.mem_free)));+ }+ v.push(PerfItem {+ kind,+ title: "Память".into(),+ line1: format!("{}/{} ({:.0}%)", dec(used as f64 / 1_073_741_824.0, 1), gb(total), d.mem_pct),+ line2: String::new(),+ graphs: vec![gspec("Использование памяти", &gb(total), &s.mem, col(1), 100.0)],+ layout: GLayout::Single,+ big_title: "Память".into(),+ device: if kind_txt.is_empty() { gb(total) } else { format!("{} {}", gb(total), kind_txt) },+ stats: vec![+ (if compressed > 0 { "Используется (сжато)" } else { "Используется" }.into(), if compressed > 0 { format!("{} ({})", gb(used), gb(compressed)) } else { gb(used) }),+ ("Доступно".into(), gb(avail)),+ ("Выделено".into(), format!("{}/{}", dec(m.commit_total as f64 / 1_073_741_824.0, 1), gb(m.commit_limit))),+ ("Кэшировано".into(), gb(cached)),+ ("Выгружаемый пул".into(), format!("{} МБ", dec(m.paged as f64 / 1_048_576.0, 0))),+ ("Невыгружаемый пул".into(), format!("{} МБ", dec(m.nonpaged as f64 / 1_048_576.0, 0))),+ ],+ stat_cols: 2,+ facts,+ composition: Some((format!("Состав памяти: {}", parts.join(" · ")), seg)),+ });+ }++ PerfKind::Disk(i) => {+ let dk = &d.disks[i];+ let info = &dk.info;+ let model = info.model.replace('_', " ");+ let kind_txt = match (info.kind.as_str(), info.bus.as_str()) {+ ("", "") => "—".to_string(),+ (k, "") => k.to_string(),+ ("", b) => b.to_string(),+ (k, b) => format!("{k} ({b})"),+ };+ let title = format!("Диск {} ({})", dk.number, dk.letters.trim());+ let xfer_max = dk.s_rd.iter().chain(dk.s_wr.iter()).cloned().fold(1.0f32, f32::max) * 1.15;+ let system = dk.letters.to_uppercase().contains("C:");+ v.push(PerfItem {+ kind,+ title: title.clone(),+ line1: if info.kind.is_empty() { "Локальный диск".into() } else { kind_txt.clone() },+ line2: format!("{:.0}%", dk.active),+ graphs: vec![+ gspec("Время активности", "100%", &dk.s_active, col(2), 100.0),+ GraphSpec { label: "Скорость передачи данных".into(), right: format!("{} МБ/с", dec(xfer_max as f64, 0)), series: vec![(&dk.s_rd, col(2)), (&dk.s_wr, col(2).lerp(Rgb(255, 255, 255), 0.45))], ymax: xfer_max },+ ],+ layout: GLayout::Stack,+ big_title: title,+ device: model,+ stats: vec![+ ("Время активности".into(), format!("{:.0}%", dk.active)),+ ("Средний отклик".into(), format!("{} мс", dec(dk.ms as f64, 1))),+ ("Скорость чтения".into(), ms(dk.rd)),+ ("Скорость записи".into(), ms(dk.wr)),+ ],+ stat_cols: 2,+ facts: vec![+ ("Ёмкость:".into(), gb(info.capacity.max(dk.formatted))),+ ("Форматированный объём:".into(), gb(dk.formatted)),+ ("Системный диск:".into(), if system { "Да" } else { "Нет" }.into()),+ ("Файл подкачки:".into(), if system { "Да" } else { "Нет" }.into()),+ ("Тип:".into(), kind_txt),+ ],+ composition: None,+ });+ }++ PerfKind::Nic(i) => {+ let n = &d.nics[i];+ let title = nic_titles[i].clone();+ let (rx, tx) = (last(&n.s_rx), last(&n.s_tx));+ let ymax = n.s_rx.iter().chain(n.s_tx.iter()).cloned().fold(1000.0f32, f32::max) * 1.15;+ let conn = conn_name(&n.name);+ v.push(PerfItem {+ kind,+ title: title.clone(),+ line1: conn.into(),+ line2: format!("О: {} П: {} Кбит/с", tx as i64, rx as i64),+ graphs: vec![GraphSpec { label: "Пропускная способность".into(), right: format!("{} Кбит/с", ymax as i64), series: vec![(&n.s_rx, col(3)), (&n.s_tx, col(3).lerp(Rgb(255, 255, 255), 0.4))], ymax }],+ layout: GLayout::Single,+ big_title: title,+ device: n.name.clone(),+ stats: vec![("Отправка".into(), format!("{} Кбит/с", tx as i64)), ("Получение".into(), format!("{} Кбит/с", rx as i64))],+ stat_cols: 2,+ facts: vec![("Имя адаптера:".into(), n.name.clone()), ("Тип подключения:".into(), conn.into()), ("Скорость канала:".into(), format!("{:.0} Мбит/с", n.bw / 1e6))],+ composition: None,+ });+ }++ PerfKind::Gpu(i) => {+ let g = &d.gpus[i];+ let a = &g.adapter;+ let vram = a.dedicated.max(g.reg.vram);+ let shared_total = a.shared;+ let temp = g.temp.map(|t| format!("{} °C", dec(t as f64, 0)));+ let name = a.name.clone();+ let title = format!("GPU {i}");+ let vram_mb = (vram >> 20).max(1) as f32;+ v.push(PerfItem {+ kind,+ title: title.clone(),+ line1: name.clone(),+ line2: match &temp {+ Some(t) => format!("{:.0}% ({t})", g.util),+ None => format!("{:.0}%", g.util),+ },+ graphs: vec![+ gspec("3D", "100%", &g.series.g3d, col(4), 100.0),+ gspec("Копирование", "100%", &g.series.gcopy, col(4), 100.0),+ gspec("Видеокодирование", "100%", &g.series.genc, col(4), 100.0),+ gspec("Видеодекодирование", "100%", &g.series.gdec, col(4), 100.0),+ gspec("Использование выделенной памяти GPU", &gb(vram), &g.series.ded, col(4), vram_mb),+ gspec("Использование общей памяти GPU", &gb(shared_total), &g.series.shr, col(4), (shared_total >> 20).max(1) as f32),+ ],+ layout: GLayout::Grid,+ big_title: title,+ device: name.clone(),+ stats: vec![+ ("Использование".into(), format!("{:.0}%", g.util)),+ ("Общая память GPU".into(), format!("{}/{}", dec(g.shr_used as f64 / 1_073_741_824.0, 1), gb(shared_total))),+ ("Память GPU".into(), format!("{}/{}", dec((g.ded_used + g.shr_used) as f64 / 1_073_741_824.0, 1), gb(vram + shared_total))),+ ("Температура GPU".into(), temp.clone().unwrap_or_else(|| "—".into())),+ ],+ stat_cols: 2,+ facts: {+ let dash = |s: &str| if s.is_empty() { "—".to_string() } else { s.to_string() };+ vec![+ ("Выделенная память GPU:".into(), format!("{}/{}", dec(g.ded_used as f64 / 1_073_741_824.0, 1), gb(vram))),+ ("Версия драйвера:".into(), dash(&g.reg.driver_version)),+ ("Дата разработки:".into(), if g.reg.driver_date.is_empty() { "—".into() } else { ru_date(&g.reg.driver_date) }),+ ("Версия DirectX:".into(), dash(&a.dx)),+ ("Физическое расположение:".into(), dash(&a.location)),+ ]+ },+ composition: None,+ });+ }+ }+ }+ v+}++/// «10-19-2026» (месяц-день-год, как хранит драйвер) -> «19.10.2026».+pub fn ru_date(s: &str) -> String {+ let p: Vec<&str> = s.split(['-', '/']).collect();+ if let [m, d, y] = p[..] { format!("{d}.{m}.{y}") } else { s.to_string() }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn nic(name: &str) -> NicState {+ NicState { name: name.into(), rx: 0.0, tx: 0.0, bw: 1e9, s_rx: Default::default(), s_tx: Default::default() }+ }++ fn disk(number: u32, letters: &str) -> DiskState {+ DiskState {+ number,+ letters: letters.into(),+ info: crate::hw::DiskInfo { number, model: "TEST_DISK".into(), kind: "HDD".into(), bus: "SATA".into(), capacity: 2 << 40, formatted: 0 },+ formatted: 1 << 40,+ active: 0.0,+ rd: 0.0,+ wr: 0.0,+ ms: 0.0,+ s_active: Default::default(),+ s_rd: Default::default(),+ s_wr: Default::default(),+ }+ }++ fn gpu(name: &str, vendor: u32) -> GpuState {+ GpuState {+ adapter: crate::gpu::Adapter { name: name.into(), vendor, luid: (vendor, 0), dedicated: 4 << 30, shared: 8 << 30, dx: "DirectX 12 (FL 12_1)".into(), location: "PCI-шина 0, устройство 2, функция 0".into() },+ reg: Default::default(),+ util: 0.0,+ ded_used: 0,+ shr_used: 0,+ temp: Some(55.0),+ series: Default::default(),+ }+ }++ #[test]+ fn several_disks_adapters_and_gpus_get_their_own_items() {+ let mut d = Data::new(crate::store::Settings::default());+ d.disks = vec![disk(0, "C:"), disk(1, "D: E:")];+ d.nics = vec![nic("Intel Wi-Fi 6 AX200"), nic("Realtek PCIe GbE Family Controller"), nic("Qualcomm Wireless 802.11ac")];+ d.gpus = vec![gpu("Intel UHD Graphics", 0x8086), gpu("AMD Radeon RX", 0x1002)];+ let items = perf_items(&d);+ let titles: Vec<&str> = items.iter().map(|i| i.title.as_str()).collect();+ assert_eq!(titles, ["ЦП", "Память", "Диск 0 (C:)", "Диск 1 (D: E:)", "Wi-Fi", "Ethernet", "Wi-Fi 2", "GPU 0", "GPU 1"]);+ assert_eq!(perf_kinds(&d).len(), items.len());+ // у каждого GPU — свои сведения: DirectX, расположение и температура (в том числе не NVIDIA)+ let g1 = items.last().unwrap();+ assert!(g1.facts.iter().any(|f| f.0.contains("DirectX") && f.1.contains("12")));+ assert!(g1.facts.iter().any(|f| f.0.contains("расположение") && f.1.contains("PCI")));+ assert!(g1.line2.contains("55 °C"));+ // второй диск — не системный+ let d1 = &items[3];+ assert!(d1.facts.iter().any(|f| f.0.contains("Системный") && f.1 == "Нет"));+ assert_eq!(conn_name("Bluetooth Device (Personal Area Network)"), "Bluetooth");+ }++ #[test]+ fn driver_date_is_converted_to_russian_order() {+ assert_eq!(ru_date("10-19-2026"), "19.10.2026");+ assert_eq!(ru_date("garbage"), "garbage");+ }+}diff --git a/plugins/rtaskmgr-win32/src/gpu.rs b/plugins/rtaskmgr-win32/src/gpu.rsnew file mode 100644index 0000000..0acb933--- /dev/null+++ b/plugins/rtaskmgr-win32/src/gpu.rs@@ -0,0 +1,212 @@+//! Видеоадаптеры независимо от производителя: список через DXGI, температура через D3DKMT (так же, как у диспетчера Windows),+//! версия DirectX через D3D12 и физическое расположение через SetupAPI.+use std::ffi::c_void;+use std::ptr::{null, null_mut};+use winapi::um::libloaderapi::{GetProcAddress, LoadLibraryW};++fn wide(s: &str) -> Vec<u16> {+ s.encode_utf16().chain(Some(0)).collect()+}++#[derive(Clone, Debug, Default, PartialEq)]+pub struct Adapter {+ pub name: String,+ pub vendor: u32,+ pub luid: (u32, i32), // (младшая часть, старшая часть)+ pub dedicated: u64, // байт+ pub shared: u64,+ pub dx: String, // «DirectX 12 (FL 12.1)»+ pub location: String, // «PCI-шина 1, устройство 0, функция 0»+}++#[repr(C)]+struct Guid(u32, u16, u16, [u8; 8]);++const IID_IDXGIFACTORY1: Guid = Guid(0x770aae78, 0xf26f, 0x4dba, [0xa8, 0x29, 0x25, 0x3c, 0x83, 0xd1, 0xb3, 0x87]);+const IID_ID3D12DEVICE: Guid = Guid(0x189819f1, 0x1db6, 0x4b57, [0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7]);++#[link(name = "dxgi")]+unsafe extern "system" {+ fn CreateDXGIFactory1(riid: *const Guid, out: *mut *mut c_void) -> i32;+}++#[link(name = "gdi32")]+unsafe extern "system" {+ fn D3DKMTOpenAdapterFromLuid(p: *mut OpenFromLuid) -> i32;+ fn D3DKMTQueryAdapterInfo(p: *mut QueryInfo) -> i32;+ fn D3DKMTCloseAdapter(p: *mut u32) -> i32;+}++#[repr(C)]+struct OpenFromLuid {+ low: u32,+ high: i32,+ handle: u32,+}++#[repr(C)]+struct QueryInfo {+ handle: u32,+ ty: u32,+ data: *mut c_void,+ size: u32,+}++/// Вызов метода COM-объекта по номеру в таблице виртуальных методов.+unsafe fn vtbl<T: Copy>(obj: *mut c_void, idx: usize) -> T {+ unsafe {+ let table = *(obj as *const *const usize);+ std::mem::transmute_copy(&*table.add(idx))+ }+}++unsafe fn release(obj: *mut c_void) {+ unsafe {+ let f: unsafe extern "system" fn(*mut c_void) -> u32 = vtbl(obj, 2);+ f(obj);+ }+}++/// Наивысший поддерживаемый уровень возможностей Direct3D для адаптера.+fn directx_level(adapter: *mut c_void) -> String {+ unsafe {+ let lib = LoadLibraryW(wide("d3d12.dll").as_ptr());+ if lib.is_null() {+ return "DirectX 11".into();+ }+ let f = GetProcAddress(lib, c"D3D12CreateDevice".as_ptr());+ if f.is_null() {+ return "DirectX 11".into();+ }+ let create: unsafe extern "system" fn(*mut c_void, i32, *const Guid, *mut *mut c_void) -> i32 = std::mem::transmute(f);+ for (fl, name) in [(0xC200, "12_2"), (0xC100, "12_1"), (0xC000, "12_0"), (0xB100, "11_1"), (0xB000, "11_0")] {+ // ppDevice = NULL: функция только проверяет, можно ли создать устройство (0 или 1 — можно)+ let hr = create(adapter, fl, &IID_ID3D12DEVICE, null_mut());+ if hr == 0 || hr == 1 {+ return format!("DirectX {} (FL {name})", if fl >= 0xC000 { "12" } else { "11" });+ }+ }+ "DirectX 11".into()+ }+}++/// Температура ядра GPU, °C — через D3DKMT_ADAPTER_PERFDATA (работает у NVIDIA, AMD и Intel, если драйвер её отдаёт).+pub fn temperature(luid: (u32, i32)) -> Option<f32> {+ unsafe {+ let mut open = OpenFromLuid { low: luid.0, high: luid.1, handle: 0 };+ if D3DKMTOpenAdapterFromLuid(&mut open) != 0 {+ return None;+ }+ // D3DKMT_ADAPTER_PERFDATA: PhysicalAdapterIndex(4)+выравн.(4), 5×u64, затем FanRPM, Power, Temperature (в 0,1 °C), PowerStateOverride+ let mut perf = [0u8; 64];+ let mut q = QueryInfo { handle: open.handle, ty: 62 /*KMTQAITYPE_ADAPTERPERFDATA*/, data: perf.as_mut_ptr() as *mut c_void, size: perf.len() as u32 };+ let ok = D3DKMTQueryAdapterInfo(&mut q) == 0;+ let mut h = open.handle;+ D3DKMTCloseAdapter(&mut h);+ if !ok {+ return None;+ }+ let t = u32::from_le_bytes([perf[56], perf[57], perf[58], perf[59]]);+ (t > 0 && t < 1500).then_some(t as f32 / 10.0)+ }+}++/// Расположение устройства по описанию: «PCI-шина N, устройство D, функция F».+fn locations() -> Vec<(String, String)> {+ use winapi::shared::guiddef::GUID;+ use winapi::um::setupapi::*;+ let class = GUID { Data1: 0x4d36e968, Data2: 0xe325, Data3: 0x11ce, Data4: [0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18] };+ let mut out = vec![];+ unsafe {+ let set = SetupDiGetClassDevsW(&class, null(), null_mut(), DIGCF_PRESENT);+ if set as isize == -1 {+ return out;+ }+ let mut i = 0;+ loop {+ let mut dev: SP_DEVINFO_DATA = std::mem::zeroed();+ dev.cbSize = std::mem::size_of::<SP_DEVINFO_DATA>() as u32;+ if SetupDiEnumDeviceInfo(set, i, &mut dev) == 0 {+ break;+ }+ i += 1;+ let mut prop = |code: u32, buf: &mut [u8]| -> bool {+ let (mut ty, mut need) = (0u32, 0u32);+ SetupDiGetDeviceRegistryPropertyW(set, &mut dev, code, &mut ty, buf.as_mut_ptr(), buf.len() as u32, &mut need) != 0+ };+ let mut desc = [0u8; 512];+ let (mut bus, mut addr) = ([0u8; 4], [0u8; 4]);+ if prop(0 /*SPDRP_DEVICEDESC*/, &mut desc) && prop(0x10 /*SPDRP_BUSNUMBER*/, &mut bus) && prop(0x1C /*SPDRP_ADDRESS*/, &mut addr) {+ let w: Vec<u16> = desc.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes([c[0], c[1]])).take_while(|&c| c != 0).collect();+ let (b, a) = (u32::from_le_bytes(bus), u32::from_le_bytes(addr));+ out.push((String::from_utf16_lossy(&w), format!("PCI-шина {b}, устройство {}, функция {}", (a >> 16) & 0xFFFF, a & 0xFFFF)));+ }+ }+ SetupDiDestroyDeviceInfoList(set);+ }+ out+}++/// Видеоадаптеры (кроме программного Microsoft Basic Render Driver) в порядке DXGI.+pub fn adapters() -> Vec<Adapter> {+ let mut out = vec![];+ let locs = locations();+ unsafe {+ let mut factory: *mut c_void = null_mut();+ if CreateDXGIFactory1(&IID_IDXGIFACTORY1, &mut factory) != 0 || factory.is_null() {+ return out;+ }+ let enum1: unsafe extern "system" fn(*mut c_void, u32, *mut *mut c_void) -> i32 = vtbl(factory, 12);+ let mut i = 0;+ loop {+ let mut ad: *mut c_void = null_mut();+ if enum1(factory, i, &mut ad) != 0 || ad.is_null() {+ break;+ }+ i += 1;+ // DXGI_ADAPTER_DESC1 (x64): Description[128] u16 @0, VendorId @256, DedicatedVideoMemory @272, SharedSystemMemory @288, LUID @296, Flags @304+ let mut d = [0u8; 312];+ let get_desc1: unsafe extern "system" fn(*mut c_void, *mut u8) -> i32 = vtbl(ad, 10);+ if get_desc1(ad, d.as_mut_ptr()) == 0 {+ let w: Vec<u16> = d[..256].as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes([c[0], c[1]])).take_while(|&c| c != 0).collect();+ let name = String::from_utf16_lossy(&w);+ let u64_at = |o: usize| u64::from_le_bytes(d[o..o + 8].try_into().unwrap());+ let flags = u32::from_le_bytes([d[304], d[305], d[306], d[307]]);+ if flags & 2 == 0 && !name.to_lowercase().contains("basic render") {+ out.push(Adapter {+ location: locs.iter().find(|l| l.0.eq_ignore_ascii_case(&name)).map(|l| l.1.clone()).unwrap_or_default(),+ dx: directx_level(ad),+ vendor: u32::from_le_bytes([d[256], d[257], d[258], d[259]]),+ luid: (u32::from_le_bytes([d[296], d[297], d[298], d[299]]), i32::from_le_bytes([d[300], d[301], d[302], d[303]])),+ dedicated: u64_at(272),+ shared: u64_at(288),+ name,+ });+ }+ }+ release(ad);+ }+ release(factory);+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn real_adapters_have_memory_directx_location_and_temperature() {+ let a = adapters();+ assert!(!a.is_empty(), "DXGI должен вернуть хотя бы один адаптер");+ for g in &a {+ eprintln!("{g:?} temp={:?}", temperature(g.luid));+ assert!(!g.name.is_empty() && g.dx.starts_with("DirectX"), "{g:?}");+ }+ let nv = a.iter().find(|g| g.vendor == 0x10DE).expect("есть NVIDIA");+ assert!(nv.dedicated > 4 << 30, "выделенная память: {}", nv.dedicated);+ assert!(nv.location.contains("PCI"), "расположение: {:?}", nv.location);+ let t = temperature(nv.luid).expect("температура через D3DKMT");+ assert!((15.0..=110.0).contains(&t), "t={t}");+ }+}diff --git a/plugins/rtaskmgr-win32/src/hw.rs b/plugins/rtaskmgr-win32/src/hw.rsnew file mode 100644index 0000000..8b515b4--- /dev/null+++ b/plugins/rtaskmgr-win32/src/hw.rs@@ -0,0 +1,419 @@+//! Сведения об «железе» для страниц «Память», «Диск» и GPU: таблица SMBIOS, запросы к диску, NVML (температура NVIDIA), реестр видеоадаптера.+use std::ptr::null_mut;+use winapi::um::{+ fileapi::{CreateFileW, GetDiskFreeSpaceExW, OPEN_EXISTING},+ handleapi::{CloseHandle, INVALID_HANDLE_VALUE},+ ioapiset::DeviceIoControl,+ libloaderapi::{GetProcAddress, LoadLibraryW},+ winnt::{FILE_SHARE_READ, FILE_SHARE_WRITE},+};++fn wide(s: &str) -> Vec<u16> {+ s.encode_utf16().chain(Some(0)).collect()+}++// ======================= память: SMBIOS =======================+#[derive(Clone, Default, Debug, PartialEq)]+pub struct Dimm {+ pub size_mb: u64,+ pub form: &'static str,+ pub kind: &'static str,+ pub speed: u16, // МТ/с по паспорту модуля+ pub cfg_speed: u16, // МТ/с, на которой модуль реально работает+ pub locator: String,+ pub mfr: String,+}++#[derive(Clone, Default, Debug, PartialEq)]+pub struct MemHw {+ pub dimms: Vec<Dimm>,+ pub slots: u32,+}++impl MemHw {+ pub fn installed_mb(&self) -> u64 {+ self.dimms.iter().map(|d| d.size_mb).sum()+ }+ pub fn kind(&self) -> &'static str {+ self.dimms.first().map_or("", |d| d.kind)+ }+ pub fn speed(&self) -> u16 {+ self.dimms.iter().map(|d| if d.cfg_speed > 0 { d.cfg_speed } else { d.speed }).max().unwrap_or(0)+ }+ pub fn form(&self) -> &'static str {+ self.dimms.first().map_or("", |d| d.form)+ }+}++fn form_name(v: u8) -> &'static str {+ match v {+ 0x09 => "DIMM",+ 0x0C => "RIMM",+ 0x0D => "SODIMM",+ 0x0F => "FB-DIMM",+ 0x03 => "SIMM",+ 0x10 => "Die",+ _ => "—",+ }+}++fn kind_name(v: u8) -> &'static str {+ match v {+ 0x13 => "DDR",+ 0x14 => "DDR2",+ 0x18 => "DDR3",+ 0x1A => "DDR4",+ 0x1B => "LPDDR",+ 0x1C => "LPDDR2",+ 0x1D => "LPDDR3",+ 0x1E => "LPDDR4",+ 0x22 => "DDR5",+ 0x23 => "LPDDR5",+ _ => "",+ }+}++/// Разбор таблицы SMBIOS (без 8-байтового заголовка RawSMBIOSData): типы 16 (массив памяти) и 17 (модуль памяти).+pub fn parse_smbios(data: &[u8]) -> MemHw {+ let mut hw = MemHw::default();+ let mut i = 0;+ while i + 4 <= data.len() {+ let (ty, l) = (data[i], data[i + 1] as usize);+ if l < 4 || i + l > data.len() {+ break;+ }+ let f = &data[i..i + l];+ // строки идут сразу за форматированной частью и заканчиваются двумя нулями+ let start = i + l;+ let mut j = start;+ while j + 1 < data.len() && !(data[j] == 0 && data[j + 1] == 0) {+ j += 1;+ }+ let strings: Vec<&[u8]> = if j > start { data[start..j].split(|&b| b == 0).collect() } else { vec![] };+ let s = |n: u8| -> String { if n == 0 { String::new() } else { strings.get(n as usize - 1).map(|b| String::from_utf8_lossy(b).trim().to_string()).unwrap_or_default() } };+ let u16_at = |o: usize| if l >= o + 2 { u16::from_le_bytes([f[o], f[o + 1]]) } else { 0 };+ match ty {+ 16 => hw.slots += u16_at(0x0D) as u32,+ 17 => {+ let raw = u16_at(0x0C);+ let size_mb = match raw {+ 0 | 0xFFFF => 0, // слот пуст / неизвестно+ 0x7FFF => if l >= 0x20 { u32::from_le_bytes([f[0x1C], f[0x1D], f[0x1E], f[0x1F]]) as u64 } else { 0 },+ r if r & 0x8000 != 0 => (r & 0x7FFF) as u64 / 1024,+ r => r as u64,+ };+ if size_mb > 0 {+ hw.dimms.push(Dimm {+ size_mb,+ form: form_name(f.get(0x0E).copied().unwrap_or(0)),+ kind: kind_name(f.get(0x12).copied().unwrap_or(0)),+ speed: u16_at(0x15),+ cfg_speed: u16_at(0x20),+ locator: s(f.get(0x10).copied().unwrap_or(0)),+ mfr: s(f.get(0x17).copied().unwrap_or(0)),+ });+ }+ }+ 127 => break,+ _ => {}+ }+ i = j + 2;+ }+ hw+}++pub fn memory_hw() -> MemHw {+ #[link(name = "kernel32")]+ unsafe extern "system" {+ fn GetSystemFirmwareTable(sig: u32, id: u32, buf: *mut u8, size: u32) -> u32;+ }+ let sig = u32::from_be_bytes(*b"RSMB");+ let size = unsafe { GetSystemFirmwareTable(sig, 0, null_mut(), 0) };+ if size < 8 {+ return MemHw::default();+ }+ let mut buf = vec![0u8; size as usize];+ if unsafe { GetSystemFirmwareTable(sig, 0, buf.as_mut_ptr(), size) } == 0 {+ return MemHw::default();+ }+ let len = u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]) as usize;+ parse_smbios(&buf[8..(8 + len).min(buf.len())])+}++// ======================= диск =======================+#[derive(Clone, Default, Debug)]+pub struct DiskInfo {+ pub number: u32,+ pub model: String,+ pub kind: String, // SSD / HDD+ pub bus: String, // NVMe / SATA / USB ...+ pub capacity: u64,+ pub formatted: u64,+}++fn open_device(path: &str) -> Option<winapi::um::winnt::HANDLE> {+ let h = unsafe { CreateFileW(wide(path).as_ptr(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE, null_mut(), OPEN_EXISTING, 0, null_mut()) };+ (h != INVALID_HANDLE_VALUE).then_some(h)+}++fn ioctl(h: winapi::um::winnt::HANDLE, code: u32, input: &[u8], out: &mut [u8]) -> bool {+ let mut ret = 0u32;+ unsafe { DeviceIoControl(h, code, input.as_ptr() as *mut _, input.len() as u32, out.as_mut_ptr() as *mut _, out.len() as u32, &mut ret, null_mut()) != 0 }+}++fn cstr_at(buf: &[u8], off: u32) -> String {+ if off == 0 || off as usize >= buf.len() {+ return String::new();+ }+ let s = &buf[off as usize..];+ let n = s.iter().position(|&b| b == 0).unwrap_or(s.len());+ String::from_utf8_lossy(&s[..n]).trim().to_string()+}++/// Размер форматированных томов по буквам вида «C: D:», байт.+pub fn volumes_total(letters: &str) -> u64 {+ use winapi::shared::ntdef::ULARGE_INTEGER;+ let mut sum = 0u64;+ for l in letters.split_whitespace() {+ unsafe {+ let (mut a, mut b, mut c): (ULARGE_INTEGER, ULARGE_INTEGER, ULARGE_INTEGER) = (std::mem::zeroed(), std::mem::zeroed(), std::mem::zeroed());+ if GetDiskFreeSpaceExW(wide(&format!(r"{l}\")).as_ptr(), &mut a, &mut b, &mut c) != 0 {+ sum += *b.QuadPart();+ }+ }+ }+ sum+}+++/// Сведения о системном диске (на котором лежит C:).+#[cfg(test)] // the app asks per disk number (disk_info_for); the hardware test checks C:+pub fn disk_info() -> DiskInfo {+ let mut number = 0;+ if let Some(v) = open_device(r"\\.\C:") {+ let mut out = [0u8; 64];+ if ioctl(v, 0x0056_0000 /*IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS*/, &[], &mut out) {+ number = u32::from_le_bytes([out[8], out[9], out[10], out[11]]);+ }+ unsafe { CloseHandle(v) };+ }+ disk_info_for(number)+}++/// Модель, тип (SSD/HDD), шина и ёмкость физического диска по его номеру.+pub fn disk_info_for(number: u32) -> DiskInfo {+ let mut d = DiskInfo { number, ..Default::default() };+ if let Some(h) = open_device(&format!(r"\\.\PhysicalDrive{}", d.number)) {+ // STORAGE_PROPERTY_QUERY { PropertyId, QueryType(0 = StandardQuery), 1 байт параметров }+ let query = |prop: u32| -> Vec<u8> {+ let mut q = [0u8; 12];+ q[..4].copy_from_slice(&prop.to_le_bytes());+ let mut out = vec![0u8; 1024];+ if ioctl(h, 0x002D_1400 /*IOCTL_STORAGE_QUERY_PROPERTY*/, &q, &mut out) { out } else { vec![] }+ };+ let dev = query(0); // StorageDeviceProperty+ if dev.len() >= 36 {+ let off = |o: usize| u32::from_le_bytes([dev[o], dev[o + 1], dev[o + 2], dev[o + 3]]);+ let (vendor, product) = (cstr_at(&dev, off(12)), cstr_at(&dev, off(16)));+ d.model = if vendor.is_empty() || product.to_lowercase().starts_with(&vendor.to_lowercase()) { product } else { format!("{vendor} {product}") };+ d.bus = match off(28) {+ 17 => "NVMe",+ 11 => "SATA",+ 7 => "USB",+ 8 => "RAID",+ 3 => "ATA",+ 1 => "SCSI",+ _ => "",+ }+ .into();+ }+ let seek = query(7); // StorageDeviceSeekPenaltyProperty+ if seek.len() >= 9 {+ d.kind = if seek[8] == 0 { "SSD" } else { "HDD" }.into();+ }+ // DISK_GEOMETRY_EX: 24 байта геометрии, затем DiskSize (i64) — размер диска без повышенных прав+ let mut geo = [0u8; 128];+ if ioctl(h, 0x0007_00A0 /*IOCTL_DISK_GET_DRIVE_GEOMETRY_EX*/, &[], &mut geo) {+ d.capacity = i64::from_le_bytes([geo[24], geo[25], geo[26], geo[27], geo[28], geo[29], geo[30], geo[31]]).max(0) as u64;+ }+ unsafe { CloseHandle(h) };+ }+ let (mut free, mut total, mut total_free) = (0u64, 0u64, 0u64);+ unsafe {+ use winapi::shared::ntdef::ULARGE_INTEGER;+ let (mut a, mut b, mut c): (ULARGE_INTEGER, ULARGE_INTEGER, ULARGE_INTEGER) = (std::mem::zeroed(), std::mem::zeroed(), std::mem::zeroed());+ if GetDiskFreeSpaceExW(wide(r"C:\").as_ptr(), &mut a, &mut b, &mut c) != 0 {+ free = *a.QuadPart();+ total = *b.QuadPart();+ total_free = *c.QuadPart();+ }+ }+ let _ = (free, total_free);+ d.formatted = total;+ d+}++// ======================= GPU: реестр и NVML =======================+#[derive(Clone, Default, Debug)]+pub struct GpuReg {+ pub driver_version: String,+ pub driver_date: String,+ pub vram: u64, // выделенная память, байт+}++pub fn gpu_registry(name: &str) -> GpuReg {+ use winapi::um::winreg::{RegGetValueW, HKEY_LOCAL_MACHINE};+ let class = r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}";+ let get_str = |sub: &str, val: &str| -> Option<String> {+ let (s, v) = (wide(sub), wide(val));+ let mut buf = vec![0u16; 256];+ let mut size = (buf.len() * 2) as u32;+ let rc = unsafe { RegGetValueW(HKEY_LOCAL_MACHINE, s.as_ptr(), v.as_ptr(), 0x2, null_mut(), buf.as_mut_ptr() as *mut _, &mut size) };+ (rc == 0).then(|| String::from_utf16_lossy(&buf[..(size as usize / 2).saturating_sub(1)]))+ };+ for i in 0..8 {+ let sub = format!(r"{class}\{i:04}");+ if get_str(&sub, "DriverDesc").as_deref() == Some(name) {+ let (s, v) = (wide(&sub), wide("HardwareInformation.qwMemorySize"));+ let (mut q, mut size) = (0u64, 8u32);+ let rc = unsafe { RegGetValueW(HKEY_LOCAL_MACHINE, s.as_ptr(), v.as_ptr(), 0xFFFF /*RRF_RT_ANY: у NVIDIA значение хранится как бинарное, у других — как QWORD*/, null_mut(), &mut q as *mut u64 as *mut _, &mut size) };+ return GpuReg { driver_version: get_str(&sub, "DriverVersion").unwrap_or_default(), driver_date: get_str(&sub, "DriverDate").unwrap_or_default(), vram: if rc == 0 { q } else { 0 } };+ }+ }+ GpuReg::default()+}++/// NVML (драйвер NVIDIA): температура и память видеокарты. Подгружается динамически; без NVIDIA — None.+pub struct Nvml {+ device: usize,+ get_temp: unsafe extern "C" fn(usize, u32, *mut u32) -> i32,+}++#[repr(C)]+struct NvmlMemory {+ total: u64,+ free: u64,+ used: u64,+}++impl Nvml {+ pub fn new() -> Option<Nvml> {+ unsafe {+ let mut lib = LoadLibraryW(wide("nvml.dll").as_ptr());+ if lib.is_null() {+ lib = LoadLibraryW(wide(r"C:\Program Files\NVIDIA Corporation\NVSMI\nvml.dll").as_ptr());+ }+ if lib.is_null() {+ return None;+ }+ let sym = |n: &str| GetProcAddress(lib, format!("{n}\0").as_ptr() as *const i8);+ let (init, by_index, temp) = (sym("nvmlInit_v2"), sym("nvmlDeviceGetHandleByIndex_v2"), sym("nvmlDeviceGetTemperature"));+ if init.is_null() || by_index.is_null() || temp.is_null() {+ return None;+ }+ let init: unsafe extern "C" fn() -> i32 = std::mem::transmute(init);+ let by_index: unsafe extern "C" fn(u32, *mut usize) -> i32 = std::mem::transmute(by_index);+ if init() != 0 {+ return None;+ }+ let mut device = 0usize;+ if by_index(0, &mut device) != 0 {+ return None;+ }+ Some(Nvml { device, get_temp: std::mem::transmute::<winapi::shared::minwindef::FARPROC, unsafe extern "C" fn(usize, u32, *mut u32) -> i32>(temp) })+ }+ }++ /// Температура ядра GPU, °C.+ pub fn temp(&self) -> Option<u32> {+ let mut t = 0u32;+ (unsafe { (self.get_temp)(self.device, 0 /*NVML_TEMPERATURE_GPU*/, &mut t) } == 0).then_some(t)+ }+}++#[allow(dead_code)]+fn _size_check() -> usize {+ std::mem::size_of::<NvmlMemory>()+}++#[cfg(test)]+mod tests {+ use super::*;++ /// Синтетическая таблица: массив памяти на 2 слота + два модуля (один пустой слот не считается).+ fn table() -> Vec<u8> {+ let mut t = vec![];+ // Type 16, длина 0x17+ let mut a = vec![0u8; 0x17];+ a[0] = 16;+ a[1] = 0x17;+ a[0x0D] = 2;+ t.extend(a);+ t.extend([0, 0]);+ // Type 17, DDR5 SODIMM 16 ГБ, 5600/5600, с двумя строками+ let mut m = vec![0u8; 0x22];+ m[0] = 17;+ m[1] = 0x22;+ m[0x0C] = 0x00;+ m[0x0D] = 0x40; // 16384 МБ+ m[0x0E] = 0x0D;+ m[0x10] = 1;+ m[0x12] = 0x22;+ m[0x15] = 0xE0;+ m[0x16] = 0x15; // 5600+ m[0x17] = 2;+ m[0x20] = 0xE0;+ m[0x21] = 0x15;+ t.extend(m);+ t.extend(b"DIMM A\0Samsung\0\0");+ // пустой слот+ let mut e = vec![0u8; 0x22];+ e[0] = 17;+ e[1] = 0x22;+ t.extend(e);+ t.extend([0, 0]);+ // Type 127 — конец таблицы+ t.extend([127, 4, 0, 0, 0, 0]);+ t+ }++ #[test]+ fn smbios_parser_reads_modules_slots_and_strings() {+ let hw = parse_smbios(&table());+ assert_eq!(hw.slots, 2);+ assert_eq!(hw.dimms.len(), 1, "пустой слот не считается модулем");+ let d = &hw.dimms[0];+ assert_eq!((d.size_mb, d.form, d.kind, d.speed, d.cfg_speed), (16384, "SODIMM", "DDR5", 5600, 5600));+ assert_eq!((d.locator.as_str(), d.mfr.as_str()), ("DIMM A", "Samsung"));+ assert_eq!(hw.installed_mb(), 16384);+ }++ #[test]+ fn smbios_parser_survives_garbage() {+ assert_eq!(parse_smbios(&[]), MemHw::default());+ assert_eq!(parse_smbios(&[17, 200, 0, 0, 1, 2, 3]), MemHw::default());+ }++ #[test]+ fn real_hardware_is_readable() {+ let m = memory_hw();+ assert!(m.installed_mb() >= 1024, "память из SMBIOS: {m:?}");+ assert!(m.slots >= m.dimms.len() as u32);+ let d = disk_info();+ assert!(d.capacity > 10_000_000_000 && d.formatted > 10_000_000_000, "{d:?}");+ assert!(!d.model.is_empty(), "{d:?}");+ assert!(d.kind == "SSD" || d.kind == "HDD", "{d:?}");+ eprintln!("RAM: {:?}\nDISK: {:?}", m, d);+ let g = gpu_registry(&crate::perf::static_info().gpu_name);+ eprintln!("GPU reg: {:?}", g);+ assert!(!g.driver_version.is_empty(), "{g:?}");+ if !crate::perf::static_info().gpu_name.is_empty() {+ assert!(g.vram > 512 * 1024 * 1024, "видеопамять не прочиталась: {g:?}");+ }+ if let Some(n) = Nvml::new() {+ let t = n.temp().expect("температура");+ assert!((15..=110).contains(&t), "t={t}");+ eprintln!("GPU temp: {t} °C");+ }+ }+}diff --git a/plugins/rtaskmgr-win32/src/main.rs b/plugins/rtaskmgr-win32/src/main.rsnew file mode 100644index 0000000..9588d8e--- /dev/null+++ b/plugins/rtaskmgr-win32/src/main.rs@@ -0,0 +1,301 @@+#![windows_subsystem = "windows"]+mod app;+mod data;+mod draw;+mod gpu;+mod hw;+mod model;+mod net;+mod perf;+mod res;+mod startup;+mod store;+mod suspect;+mod sys;+mod ui;++use app::*;+use data::*;+use model::*;+use native_windows_gui as nwg;+use std::{+ cell::{Cell, RefCell},+ collections::{HashMap, HashSet},+ rc::Rc,+ time::{Duration, Instant},+};+use ui::*;+use winapi::um::winuser::*;++/// Самопроверка ETW: сессия + трафик через localhost + чтение счётчиков своего процесса. Результат — в файл.+fn net_selftest(out: &str) {+ use std::io::{Read, Write};+ let report = (|| -> Result<String, String> {+ let ses = net::start().ok_or("не удалось запустить ETW-сессию (нужны права администратора)")?;+ std::thread::sleep(Duration::from_millis(500));+ let l = std::net::TcpListener::bind("127.0.0.1:0").map_err(|e| e.to_string())?;+ let addr = l.local_addr().map_err(|e| e.to_string())?;+ let srv = std::thread::spawn(move || {+ let (mut c, _) = l.accept().unwrap();+ let mut buf = vec![0u8; 100_000];+ let mut got = 0;+ while got < 200_000 {+ match c.read(&mut buf) {+ Ok(0) | Err(_) => break,+ Ok(n) => got += n,+ }+ }+ });+ let mut c = std::net::TcpStream::connect(addr).map_err(|e| e.to_string())?;+ c.write_all(&vec![7u8; 200_000]).map_err(|e| e.to_string())?;+ drop(c);+ let _ = srv.join();+ std::thread::sleep(Duration::from_secs(2));+ let me = std::process::id();+ let all = net::drain();+ net::stop(ses);+ let (rx, tx) = all.get(&me).copied().unwrap_or((0, 0));+ Ok(format!("pid={me} принято={rx} отправлено={tx} процессов_в_данных={}", all.len()))+ })();+ let _ = std::fs::write(out, report.unwrap_or_else(|e| format!("ОШИБКА: {e}")));+}++fn xy(l: isize) -> (i32, i32) {+ ((l & 0xFFFF) as i16 as i32, ((l >> 16) & 0xFFFF) as i16 as i32)+}++fn main() {+ if let Some(i) = std::env::args().position(|a| a == "--net-selftest")+ && let Some(out) = std::env::args().nth(i + 1) {+ return net_selftest(&out);+ }+ let args: Vec<String> = std::env::args().skip(1).collect();+ // повторный вызов с правами администратора из start_real_taskmgr: только открыть системный диспетчер+ if args.first().is_some_and(|a| a == "--real-taskmgr") {+ sys::start_real_taskmgr(&args[1..].join(" "), false);+ return;+ }+ // Без прав администратора диспетчер не закроет защищённые процессы (Malwarebytes и т.п.): перезапускаемся через+ // задачу планировщика — с правами и без UAC. "--tray" передаём файлом: у задачи нет аргументов.+ let tray_flag = store::dir().join("tray.flag");+ if !sys::is_admin() {+ if args.iter().any(|a| a == "--tray") {+ let _ = std::fs::create_dir_all(store::dir());+ let _ = std::fs::write(&tray_flag, "");+ }+ if sys::run_elevated_task() {+ return;+ }+ let _ = std::fs::remove_file(&tray_flag);+ }+ let ifeo = sys::taskmgr_args(&args); // Some = нас запустили вместо taskmgr.exe+ // Мы подменяем системный диспетчер: если упадём, Ctrl+Shift+Esc не должен остаться без ответа.+ // (panic = "abort" всё равно сначала вызывает этот хук.)+ let fallback_args = ifeo.clone().unwrap_or_default();+ std::panic::set_hook(Box::new(move |info| {+ let dir = store::dir();+ let _ = std::fs::create_dir_all(&dir);+ let _ = std::fs::write(dir.join("crash.log"), format!("{info}\n{}", std::backtrace::Backtrace::force_capture()));+ sys::start_real_taskmgr(&fallback_args, true);+ }));+ let hidden = args.iter().any(|a| a == "--tray") || (sys::is_admin() && std::fs::remove_file(&tray_flag).is_ok()); // запуск из автозагрузки: сразу в трей+ nwg::enable_visual_styles();+ nwg::init().expect("не удалось инициализировать Win32");+ let scale = nwg::scale_factor();+ let mut font = nwg::Font::default();+ nwg::Font::builder().family("Segoe UI").size(17).build(&mut font).unwrap();+ nwg::Font::set_global_default(Some(font));++ store::trim_history(10_080);+ let cfg = store::load();+ // `taskmgr /0 /startup` (так «Параметры» открывают автозагрузку) — сразу на эту страницу+ let startup_asked = ifeo.as_deref().is_some_and(|a| a.to_lowercase().contains("/startup"));+ let page = if startup_asked { Page::Startup } else { NAV.get(cfg.view).map_or(Page::Processes, |n| n.0) };++ // иконки из ресурса exe (id 1); если ресурса нет — системная+ let embed = nwg::EmbedResource::load(None).ok();+ let load_icon = |out: &mut nwg::Icon, size: (u32, u32)| {+ let ok = embed.as_ref().is_some_and(|e| nwg::Icon::builder().source_embed(Some(e)).source_embed_id(1).size(Some(size)).build(out).is_ok());+ if !ok {+ nwg::Icon::builder().source_system(Some(nwg::OemIcon::Information)).build(out).unwrap();+ }+ };+ let (mut icon_big, mut tray_icon) = (nwg::Icon::default(), nwg::Icon::default());+ load_icon(&mut icon_big, (32, 32));+ load_icon(&mut tray_icon, (16, 16));++ let mut win = nwg::Window::default();+ nwg::Window::builder()+ .flags(if hidden { nwg::WindowFlags::MAIN_WINDOW } else { nwg::WindowFlags::MAIN_WINDOW | nwg::WindowFlags::VISIBLE })+ .icon(Some(&icon_big))+ .size((cfg.size.0 as i32, cfg.size.1 as i32))+ .position(cfg.pos)+ .title("Диспетчер задач")+ .build(&mut win)+ .unwrap();+ let mut search = nwg::TextInput::default();+ nwg::TextInput::builder()+ .parent(&win)+ .placeholder_text(Some("Введите имя, издателя или PID для поиска"))+ .flags(nwg::TextInputFlags::VISIBLE | nwg::TextInputFlags::TAB_STOP)+ .position((0, 0))+ .size((300, 20))+ .build(&mut search)+ .unwrap();+ #[allow(deprecated)] // the plain WM_TIMER is all a 1-second refresh needs; AnimationTimer runs its own thread+ let mut timer = nwg::Timer::default();+ #[allow(deprecated)]+ nwg::Timer::builder().parent(&win).interval(1000).stopped(false).build(&mut timer).unwrap();+ let mut tray = nwg::TrayNotification::default();+ nwg::TrayNotification::builder().parent(&win).icon(Some(&tray_icon)).tip(Some("Диспетчер задач (Rust)")).build(&mut tray).unwrap();++ let ui = Ui {+ page,+ nav_open: false,+ th: theme(true),+ rows: vec![],+ sel: None,+ expanded: HashSet::new(),+ sorts: HashMap::from([(Page::Processes, (cfg.sort.min(7), cfg.desc))]),+ search: String::new(),+ hit: Hit::None,+ mouse: (0, 0),+ scroll: 0.0,+ drag: None,+ perf_sel: draw::PerfKind::Cpu,+ toast: None,+ tip: None,+ lay: None,+ last_click: None,+ };+ let app = Rc::new(App {+ win,+ search,+ timer,+ tray,+ tray_icon,+ icon_big,+ data: RefCell::new(Data::new(cfg.clone())),+ ui: RefCell::new(ui),+ fonts: Fonts::new(scale),+ scale,+ edit_brush: Cell::new(0),+ search_rect: Cell::new(R::new(0, 0, 0, 0)),+ last_tick: Cell::new(Instant::now()),+ });+ app.apply_theme();+ {+ let mut d = app.data.borrow_mut();+ match page {+ Page::Startup => d.load_startup(),+ Page::History => d.load_history(),+ _ => {}+ }+ }+ app.tick();++ // горячая клавиша Ctrl+Alt+T+ let hwnd = app.win.handle.hwnd().unwrap();+ unsafe { RegisterHotKey(hwnd, 1, (MOD_CONTROL | MOD_ALT) as u32, b'T' as u32) };++ let a = app.clone();+ let _raw = nwg::bind_raw_event_handler(&app.win.handle, 0x10000, move |hwnd, msg, w, l| -> Option<isize> {+ match msg {+ WM_PAINT => {+ a.paint(hwnd);+ Some(0)+ }+ WM_ERASEBKGND => Some(1),+ WM_GETMINMAXINFO => unsafe {+ let mmi = &mut *(l as *mut MINMAXINFO);+ mmi.ptMinTrackSize = winapi::shared::windef::POINT { x: (860.0 * a.scale) as i32, y: (560.0 * a.scale) as i32 };+ Some(0)+ },+ WM_SIZE => {+ a.invalidate();+ None+ }+ WM_MOUSEMOVE => {+ let (x, y) = xy(l);+ a.on_mouse_move(hwnd, x, y);+ None+ }+ WM_MOUSELEAVE => {+ a.on_mouse_leave();+ None+ }+ WM_LBUTTONDOWN => {+ let (x, y) = xy(l);+ a.on_lbutton_down(hwnd, x, y);+ Some(0)+ }+ WM_LBUTTONUP => {+ a.on_lbutton_up();+ None+ }+ WM_RBUTTONUP => {+ let (x, y) = xy(l);+ a.on_rbutton_up(hwnd, x, y);+ Some(0)+ }+ WM_MOUSEWHEEL => {+ a.on_wheel(((w >> 16) & 0xFFFF) as i16);+ Some(0)+ }+ WM_KEYDOWN => {+ a.on_key(hwnd, w as u32);+ None+ }+ WM_TIMER if w == 77 => {+ a.on_tip_timer(hwnd);+ Some(0)+ }+ WM_CTLCOLOREDIT => unsafe {+ // поле поиска: цвета как у плашки в шапке+ let th = a.ui.borrow().th;+ winapi::um::wingdi::SetTextColor(w as _, th.text.c());+ winapi::um::wingdi::SetBkColor(w as _, th.panel.c());+ Some(a.edit_brush.get())+ },+ WM_HOTKEY if w == 1 => {+ a.show_window();+ Some(0)+ }+ _ => None,+ }+ })+ .unwrap();++ let a = app.clone();+ let _h = nwg::full_bind_event_handler(&app.win.handle, move |evt, data, handle| {+ use nwg::Event as E;+ match evt {+ E::OnWindowClose => {+ if let nwg::EventData::OnWindowClose(d) = data {+ let to_tray = a.data.borrow().cfg.to_tray;+ if to_tray {+ d.close(false);+ a.save_settings();+ a.win.set_visible(false);+ } else {+ a.quit();+ }+ }+ }+ E::OnTimerTick => a.on_timer(),+ E::OnTextInput if handle == a.search.handle => a.on_search_changed(),+ E::OnMousePress(nwg::MousePressEvent::MousePressLeftUp) if handle == a.tray.handle => a.show_window(),+ E::OnContextMenu if handle == a.tray.handle => {+ let (x, y) = nwg::GlobalCursor::position();+ let items = a.tray_menu();+ if let Some(h) = a.win.handle.hwnd()+ && let Some(act) = a.show_menu(h, &items, x, y)+ {+ a.do_act(act);+ }+ }+ _ => {}+ }+ });+ nwg::dispatch_thread_events();+}diff --git a/plugins/rtaskmgr-win32/src/model.rs b/plugins/rtaskmgr-win32/src/model.rsnew file mode 100644index 0000000..d8255bf--- /dev/null+++ b/plugins/rtaskmgr-win32/src/model.rs@@ -0,0 +1,487 @@+//! Модель интерфейса: страницы, колонки, строки таблиц и их построение из данных.+use crate::{data::*, suspect, ui::*};+use std::collections::{HashMap, HashSet};++#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]+pub enum Page {+ Processes,+ Performance,+ History,+ Startup,+ Users,+ Details,+ Services,+ Insights,+ Rules,+ Settings,+}++/// Пункты боковой панели: страница, символ значка, подпись.+pub const NAV: [(Page, char, &str); 10] = [+ (Page::Processes, '\u{E9D9}', "Процессы"),+ (Page::Performance, '\u{E9D2}', "Производительность"),+ (Page::History, '\u{E81C}', "Журнал приложений"),+ (Page::Startup, '\u{EC4A}', "Автозагрузка"),+ (Page::Users, '\u{E77B}', "Пользователи"),+ (Page::Details, '\u{EA37}', "Подробности"),+ (Page::Services, '\u{E9F5}', "Службы"),+ (Page::Insights, '\u{E946}', "Что тормозит"),+ (Page::Rules, '\u{E7BA}', "Правила"),+ (Page::Settings, '\u{E713}', "Параметры"),+];++pub fn page_title(p: Page) -> &'static str {+ NAV.iter().find(|n| n.0 == p).map_or("", |n| n.2)+}++#[derive(Clone, Copy, PartialEq, Debug)]+pub enum Align {+ Left,+ Right,+}++#[derive(Clone, Copy)]+pub struct Col {+ pub title: &'static str,+ pub w: f64, // логические px; 0 — всё оставшееся место+ pub align: Align,+ pub metric: Option<Metric>, // колонка с агрегатом в шапке и тепловой подсветкой+}++#[derive(Clone, Copy, PartialEq, Debug)]+pub enum Metric {+ Cpu,+ Mem,+ Disk,+ Net,+ Gpu,+}++const fn col(title: &'static str, w: f64, align: Align) -> Col {+ Col { title, w, align, metric: None }+}+const fn mcol(title: &'static str, m: Metric) -> Col {+ Col { title, w: 84.0, align: Align::Right, metric: Some(m) }+}++pub fn columns(p: Page) -> Vec<Col> {+ use Align::*;+ use Metric::*;+ match p {+ Page::Processes => vec![+ col("Имя", 270.0, Left),+ col("Состояние", 112.0, Left),+ mcol("ЦП", Cpu),+ mcol("Память", Mem),+ mcol("Диск", Disk),+ mcol("Сеть", Net),+ mcol("GPU", Gpu),+ col("Подозрительное", 140.0, Left),+ ],+ Page::Users => vec![+ col("Пользователь", 270.0, Left),+ col("Процессов", 112.0, Right),+ mcol("ЦП", Cpu),+ mcol("Память", Mem),+ mcol("Диск", Disk),+ mcol("Сеть", Net),+ mcol("GPU", Gpu),+ ],+ Page::Details => vec![col("Имя", 220.0, Left), col("PID", 70.0, Right), col("Состояние", 100.0, Left), col("ЦП", 70.0, Right), col("Память", 110.0, Right), col("Диск", 100.0, Right), col("Командная строка", 0.0, Left)],+ Page::Services => vec![col("Имя", 200.0, Left), col("PID", 70.0, Right), col("Описание", 360.0, Left), col("Состояние", 110.0, Left)],+ Page::Startup => vec![col("Имя", 240.0, Left), col("Издатель", 200.0, Left), col("Состояние", 110.0, Left), col("Команда", 0.0, Left)],+ Page::History => vec![col("Время", 150.0, Left), col("ЦП %", 80.0, Right), col("Память %", 90.0, Right), col("Ввод-вывод КБ/с", 130.0, Right), col("Сеть КБ/с", 110.0, Right), col("Основной потребитель", 0.0, Left)],+ Page::Rules => vec![col("Процесс", 220.0, Left), col("Условие", 280.0, Left), col("Действие", 200.0, Left), col("Сработало, раз", 130.0, Right)],+ _ => vec![],+ }+}++/// Сортировка по умолчанию: (индекс колонки, по убыванию).+pub fn default_sort(p: Page) -> (usize, bool) {+ match p {+ Page::Processes | Page::Users => (2, true), // ЦП+ Page::Details => (3, true),+ Page::History => (0, true),+ _ => (0, false),+ }+}++#[derive(Clone, Default)]+pub struct Row {+ pub key: String,+ pub depth: u8,+ pub expandable: bool,+ pub expanded: bool,+ pub icon_path: Option<String>,+ pub cells: Vec<String>,+ pub heat: Vec<Option<(f64, f64)>>, // (значение, шкала) для колонок-метрик+ pub sortv: Vec<f64>, // числовые ключи сортировки; NaN — сортировать как текст+ pub sev: u8,+ pub tip: String,+ pub pids: Vec<u32>,+ pub aux: String, // служебное: имя службы, ключ автозагрузки и т.п.+}++pub fn dec(v: f64, digits: usize) -> String {+ format!("{:.*}", digits, v).replace('.', ",")+}++pub fn fmt_cpu(v: f32) -> String {+ if v < 0.05 { "0%".into() } else { format!("{}%", dec(v as f64, 1)) }+}++pub fn fmt_mem_ru(b: u64) -> String {+ let mb = b as f64 / 1_048_576.0;+ if mb >= 1000.0 { format!("{} МБ", group_thousands(mb as u64).replace(',', " ")) } else if mb >= 100.0 { format!("{} МБ", dec(mb, 0)) } else { format!("{} МБ", dec(mb, 1)) }+}++pub fn fmt_disk_ru(bps: f64) -> String {+ let mb = bps / 1_048_576.0;+ if mb < 0.05 { "0 МБ/с".into() } else { format!("{} МБ/с", dec(mb, 1)) }+}++pub fn fmt_net_ru(bps: f64, known: bool) -> String {+ if !known {+ return "—".into();+ }+ let mbit = bps * 8.0 / 1e6;+ if mbit < 0.05 { "0 Мбит/с".into() } else { format!("{} Мбит/с", dec(mbit, 1)) }+}++/// Описание/имя для отображения: описание файла, если известно, иначе имя без «.exe».+fn friendly(d: &Data, p: &Proc) -> String {+ if let Some(r) = p.exe.as_deref().and_then(|e| d.res.get(e))+ && !r.desc.is_empty() {+ return r.desc;+ }+ p.name.strip_suffix(".exe").or_else(|| p.name.strip_suffix(".EXE")).unwrap_or(&p.name).to_string()+}++fn svc_display(d: &Data, pid: u32) -> Option<String> {+ let name = d.svc_pids.get(&pid)?.first()?.clone();+ Some(d.svcs.iter().find(|s| s.name == name).map_or(name, |s| s.display.clone()))+}++fn child_name(d: &Data, p: &Proc) -> String {+ if p.name.eq_ignore_ascii_case("svchost.exe")+ && let Some(s) = svc_display(d, p.pid) {+ return format!("Узел службы: {s}");+ }+ if let Some(t) = &p.title {+ return t.clone();+ }+ friendly(d, p)+}++fn tip_for(procs: &[&Proc], group: bool) -> String {+ let mut by_text: Vec<(u8, String, Vec<u32>)> = vec![];+ for p in procs {+ for r in &p.reasons {+ match by_text.iter_mut().find(|e| e.1 == r.text) {+ Some(e) => e.2.push(p.pid),+ None => by_text.push((r.sev, r.text.clone(), vec![p.pid])),+ }+ }+ }+ if by_text.is_empty() {+ return String::new();+ }+ by_text.sort_by_key(|e| std::cmp::Reverse(e.0));+ let total = by_text.len();+ let mut s = String::from("Почему помечено:");+ for (sev, t, pids) in by_text.into_iter().take(6) {+ let who = if pids.len() > 1 { format!(" (процессов: {})", pids.len()) } else if group && procs.len() > 1 { format!(" [PID {}]", pids[0]) } else { String::new() };+ s += &format!("\n{} — {t}{who}", suspect::sev_word(sev));+ }+ if total > 6 {+ s += &format!("\n… и ещё причин: {}", total - 6);+ }+ s+}++fn proc_row(d: &Data, key: String, depth: u8, name: String, members: &[&Proc], expandable: bool, expanded: bool) -> Row {+ let cpu: f32 = members.iter().map(|p| p.cpu).sum();+ let mem: u64 = members.iter().map(|p| p.mem).sum();+ let disk: f64 = members.iter().map(|p| p.disk).sum();+ let net: f64 = members.iter().map(|p| p.net).sum();+ let gpu: f32 = members.iter().map(|p| p.gpu).fold(0.0, f32::max);+ let sev = members.iter().flat_map(|p| p.reasons.iter()).map(|r| r.sev).max().unwrap_or(0);+ let status = if members.iter().all(|p| d.suspended.contains(&p.pid)) {+ "Приостановлен"+ } else if members.iter().all(|p| d.efficiency.contains(&p.pid)) {+ "Эффективность"+ } else {+ ""+ };+ let etw = d.etw.is_some();+ Row {+ key,+ depth,+ expandable,+ expanded,+ icon_path: members.iter().find_map(|p| p.exe.clone()),+ cells: vec![name, status.into(), fmt_cpu(cpu), fmt_mem_ru(mem), fmt_disk_ru(disk), fmt_net_ru(net, etw), if gpu >= 0.05 { format!("{}%", dec(gpu as f64, 0)) } else { "0%".into() }, suspect::label(sev).to_string()],+ heat: vec![None, None, Some((cpu as f64, 40.0)), Some((mem as f64, 1.5e9)), Some((disk, 5e6)), Some((net, 5e6)), Some((gpu as f64, 40.0)), None],+ sortv: vec![f64::NAN, f64::NAN, cpu as f64, mem as f64, disk, net, gpu as f64, sev as f64],+ sev,+ tip: tip_for(members, members.len() > 1),+ pids: members.iter().map(|p| p.pid).collect(),+ aux: String::new(),+ }+}++pub struct BuildCtx<'a> {+ pub page: Page,+ pub search: &'a str,+ pub expanded: &'a HashSet<String>,+ pub sort: (usize, bool),+}++fn matches(d: &Data, p: &Proc, q: &str) -> bool {+ p.name.to_lowercase().contains(q)+ || p.pid.to_string() == q+ || friendly(d, p).to_lowercase().contains(q)+ || p.exe.as_deref().and_then(|e| d.res.get(e)).is_some_and(|r| r.company.to_lowercase().contains(q))+ || p.title.as_deref().is_some_and(|t| t.to_lowercase().contains(q))+}++pub fn build_rows(d: &Data, c: &BuildCtx) -> Vec<Row> {+ let q = c.search.trim().to_lowercase();+ let mut rows: Vec<Row> = match c.page {+ Page::Processes => {+ let mut groups: HashMap<String, Vec<&Proc>> = HashMap::new();+ for p in &d.procs {+ groups.entry(group_key(&p.name)).or_default().push(p);+ }+ let mut out: Vec<(Row, Vec<Row>)> = vec![];+ for (key, mut members) in groups {+ if !q.is_empty() && !members.iter().any(|p| matches(d, p, &q) || suspect::label(p.reasons.iter().map(|r| r.sev).max().unwrap_or(0)).to_lowercase().contains(&q)) {+ continue;+ }+ members.sort_by(|a, b| b.cpu.total_cmp(&a.cpu));+ let multi = members.len() > 1;+ let base = if members[0].name.eq_ignore_ascii_case("svchost.exe") { "Узел службы".to_string() } else { friendly(d, members[0]) };+ let name = if multi { format!("{base} ({})", members.len()) } else if members[0].name.eq_ignore_ascii_case("svchost.exe") { child_name(d, members[0]) } else { members[0].title.clone().filter(|_| false).unwrap_or(base) };+ let expanded = multi && c.expanded.contains(&key);+ let head = proc_row(d, key.clone(), 0, name, &members, multi, expanded);+ let kids: Vec<Row> = if expanded {+ members.iter().map(|p| proc_row(d, format!("{key}#{}", p.pid), 1, child_name(d, p), &[p], false, false)).collect()+ } else {+ vec![]+ };+ out.push((head, kids));+ }+ sort_pairs(&mut out, c.sort);+ out.into_iter().flat_map(|(h, k)| std::iter::once(h).chain(k)).collect()+ }+ Page::Users => {+ let mut groups: HashMap<String, Vec<&Proc>> = HashMap::new();+ for p in &d.procs {+ groups.entry(p.user.clone()).or_default().push(p);+ }+ let mut out: Vec<(Row, Vec<Row>)> = vec![];+ for (user, mut members) in groups {+ if !q.is_empty() && !user.to_lowercase().contains(&q) && !members.iter().any(|p| matches(d, p, &q)) {+ continue;+ }+ members.sort_by(|a, b| b.cpu.total_cmp(&a.cpu));+ let key = format!("user:{user}");+ let expanded = c.expanded.contains(&key);+ let mut head = proc_row(d, key.clone(), 0, user.clone(), &members, true, expanded);+ head.cells[1] = members.len().to_string();+ head.sortv[1] = members.len() as f64;+ head.icon_path = None;+ head.tip = String::new();+ let kids: Vec<Row> = if expanded { members.iter().map(|p| proc_row(d, format!("{key}#{}", p.pid), 1, child_name(d, p), &[p], false, false)).collect() } else { vec![] };+ out.push((head, kids));+ }+ sort_pairs(&mut out, c.sort);+ out.into_iter().flat_map(|(h, k)| std::iter::once(h).chain(k)).collect()+ }+ Page::Details => d+ .procs+ .iter()+ .filter(|p| q.is_empty() || matches(d, p, &q))+ .map(|p| Row {+ key: p.pid.to_string(),+ icon_path: p.exe.clone(),+ cells: vec![p.name.clone(), p.pid.to_string(), (if d.suspended.contains(&p.pid) { "Приостановлен" } else { "Выполняется" }).into(), fmt_cpu(p.cpu), fmt_mem_ru(p.mem), fmt_disk_ru(p.disk), process_cmd(d, p.pid)],+ sortv: vec![f64::NAN, p.pid as f64, f64::NAN, p.cpu as f64, p.mem as f64, p.disk, f64::NAN],+ pids: vec![p.pid],+ heat: vec![None; 7],+ ..Default::default()+ })+ .collect(),+ Page::Services => d+ .svcs+ .iter()+ .filter(|s| q.is_empty() || s.name.to_lowercase().contains(&q) || s.display.to_lowercase().contains(&q))+ .map(|s| Row {+ key: s.name.clone(),+ cells: vec![s.name.clone(), if s.pid != 0 { s.pid.to_string() } else { String::new() }, s.display.clone(), (if s.running { "Выполняется" } else { "Остановлена" }).into()],+ sortv: vec![f64::NAN, s.pid as f64, f64::NAN, f64::NAN],+ pids: vec![s.pid],+ heat: vec![None; 4],+ aux: s.name.clone(),+ ..Default::default()+ })+ .collect(),+ Page::Startup => d+ .startup+ .iter()+ .filter(|s| q.is_empty() || s.name.to_lowercase().contains(&q) || s.command.to_lowercase().contains(&q))+ .map(|s| {+ let exe = exe_from_command(&s.command);+ let company = exe.as_deref().and_then(|e| d.res.get(e)).map(|r| r.company).unwrap_or_default();+ Row {+ key: s.key(),+ icon_path: exe,+ cells: vec![s.name.clone(), company, (if s.enabled { "Включено" } else { "Отключено" }).into(), s.command.clone()],+ sortv: vec![f64::NAN; 4],+ heat: vec![None; 4],+ tip: format!("Источник: {}.{}", s.source_label(), if s.needs_admin() && !d.is_admin { " Для изменения нужны права администратора." } else { "" }),+ ..Default::default()+ }+ })+ .collect(),+ Page::History => d+ .hist+ .iter()+ .filter(|h| q.is_empty() || h.iter().any(|c| c.to_lowercase().contains(&q)))+ .map(|h| Row {+ key: h[0].clone(),+ cells: h.clone(),+ sortv: vec![f64::NAN, h[1].parse().unwrap_or(0.0), h[2].parse().unwrap_or(0.0), h[3].parse().unwrap_or(0.0), h[4].parse().unwrap_or(0.0), f64::NAN],+ heat: vec![None; 6],+ ..Default::default()+ })+ .collect(),+ Page::Rules => d+ .rules+ .iter()+ .enumerate()+ .map(|(i, r)| Row {+ key: i.to_string(),+ cells: vec![+ if r.proc == "*" { "любой".into() } else { r.proc.clone() },+ format!("ЦП > {:.0}% дольше {} с", r.cpu, r.secs),+ (if r.act == crate::store::RuleAct::Lower { "Понизить приоритет" } else { "Уведомить" }).into(),+ r.hits.to_string(),+ ],+ sortv: vec![f64::NAN, f64::NAN, f64::NAN, r.hits as f64],+ heat: vec![None; 4],+ ..Default::default()+ })+ .collect(),+ _ => vec![],+ };+ if !matches!(c.page, Page::Processes | Page::Users) {+ let (ci, desc) = c.sort;+ rows.sort_by(|a, b| {+ let o = cmp_cells(a, b, ci);+ if desc { o.reverse() } else { o }+ });+ }+ rows+}++fn cmp_cells(a: &Row, b: &Row, ci: usize) -> std::cmp::Ordering {+ let (x, y) = (a.sortv.get(ci).copied().unwrap_or(f64::NAN), b.sortv.get(ci).copied().unwrap_or(f64::NAN));+ if x.is_nan() || y.is_nan() {+ a.cells.get(ci).map(|s| s.to_lowercase()).cmp(&b.cells.get(ci).map(|s| s.to_lowercase()))+ } else {+ x.total_cmp(&y)+ }+}++fn sort_pairs(v: &mut [(Row, Vec<Row>)], sort: (usize, bool)) {+ let (ci, desc) = sort;+ let ord = |a: &Row, b: &Row| {+ let o = cmp_cells(a, b, ci);+ if desc { o.reverse() } else { o }+ };+ v.sort_by(|a, b| ord(&a.0, &b.0));+ for (_, kids) in v.iter_mut() {+ kids.sort_by(|a, b| ord(a, b));+ }+}++/// Путь к исполняемому файлу из команды автозагрузки (в кавычках или до первого пробела после «.exe»).+pub fn exe_from_command(cmd: &str) -> Option<String> {+ let c = cmd.trim();+ let path = if let Some(rest) = c.strip_prefix('"') {+ rest.split('"').next()?.to_string()+ } else {+ let l = c.to_lowercase();+ let end = l.find(".exe").map(|i| i + 4).unwrap_or(c.len());+ c[..end].to_string()+ };+ let path = path.replace("%windir%", &std::env::var("WINDIR").unwrap_or_default());+ (!path.is_empty() && path.contains('\\')).then_some(path)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn exe_extraction() {+ assert_eq!(exe_from_command(r#""C:\Program Files\X\x.exe" --silent"#).as_deref(), Some(r"C:\Program Files\X\x.exe"));+ assert_eq!(exe_from_command(r"C:\Tools\a.exe -k b").as_deref(), Some(r"C:\Tools\a.exe"));+ assert_eq!(exe_from_command("cmd /c foo"), None);+ }++ #[test]+ fn number_formats_use_comma() {+ assert_eq!(fmt_cpu(2.04), "2,0%");+ assert_eq!(fmt_cpu(0.01), "0%");+ assert_eq!(fmt_mem_ru(3_746_000_000), "3 572 МБ");+ assert_eq!(fmt_mem_ru(73 * 1_048_576 + 100_000), "73,1 МБ");+ assert_eq!(fmt_disk_ru(0.0), "0 МБ/с");+ assert_eq!(fmt_net_ru(1.0, false), "—");+ }++ #[test]+ fn every_page_with_table_has_valid_default_sort() {+ for p in [Page::Processes, Page::Users, Page::Details, Page::Services, Page::Startup, Page::History, Page::Rules] {+ assert!(default_sort(p).0 < columns(p).len(), "{p:?}");+ }+ }++ #[test]+ fn users_page_groups_processes_by_account() {+ let mut d = Data::new(crate::store::Settings::default());+ d.refresh();+ let me = d.procs.iter().find(|p| p.pid == std::process::id()).expect("свой процесс").user.clone();+ assert!(!me.is_empty() && me != "СИСТЕМА", "свой токен должен читаться: {me}");+ let mut exp = HashSet::new();+ let rows = build_rows(&d, &BuildCtx { page: Page::Users, search: "", expanded: &exp, sort: default_sort(Page::Users) });+ assert!(rows.iter().all(|r| r.depth == 0 && r.expandable));+ let mine = rows.iter().find(|r| r.cells[0] == me).expect("строка текущего пользователя");+ assert!(mine.pids.contains(&std::process::id()));+ exp.insert(mine.key.clone());+ let rows2 = build_rows(&d, &BuildCtx { page: Page::Users, search: "", expanded: &exp, sort: default_sort(Page::Users) });+ assert!(rows2.iter().filter(|r| r.depth == 1).count() == mine.pids.len());+ }++ #[test]+ fn processes_rows_group_and_expand() {+ let mut d = Data::new(crate::store::Settings::default());+ d.refresh();+ let exp: HashSet<String> = HashSet::new();+ let ctx = BuildCtx { page: Page::Processes, search: "", expanded: &exp, sort: default_sort(Page::Processes) };+ let rows = build_rows(&d, &ctx);+ assert!(!rows.is_empty() && rows.iter().all(|r| r.depth == 0));+ let multi = rows.iter().find(|r| r.expandable).expect("есть группа из нескольких процессов");+ let mut exp2 = HashSet::new();+ exp2.insert(multi.key.clone());+ let ctx2 = BuildCtx { page: Page::Processes, search: "", expanded: &exp2, sort: default_sort(Page::Processes) };+ let rows2 = build_rows(&d, &ctx2);+ assert!(rows2.len() > rows.len());+ assert!(rows2.iter().any(|r| r.depth == 1));+ // поиск по PID находит нужную группу+ let pid = std::process::id().to_string();+ let ctx3 = BuildCtx { page: Page::Processes, search: &pid, expanded: &exp, sort: default_sort(Page::Processes) };+ assert!(build_rows(&d, &ctx3).iter().any(|r| r.pids.contains(&std::process::id())));+ }+}diff --git a/plugins/rtaskmgr-win32/src/net.rs b/plugins/rtaskmgr-win32/src/net.rsnew file mode 100644index 0000000..9e360ed--- /dev/null+++ b/plugins/rtaskmgr-win32/src/net.rs@@ -0,0 +1,114 @@+//! Сеть по процессам: ETW-сессия провайдера Microsoft-Windows-Kernel-Network.+//! Запускать сессию можно только с правами администратора; без них модуль не используется.+use std::{collections::HashMap, ptr::null, ptr::null_mut, sync::Mutex};+use windows_sys::{core::GUID, Win32::System::Diagnostics::Etw::*};++const KERNEL_NETWORK: GUID = GUID { data1: 0x7DD42A49, data2: 0x5329, data3: 0x4832, data4: [0x8D, 0xFD, 0x43, 0xD9, 0x79, 0x15, 0x3A, 0x88] };+const SESSION: &str = "RTaskMgrNet";++/// pid -> (принято, отправлено) байт с прошлого `drain`.+static TOTALS: Mutex<Option<HashMap<u32, (u64, u64)>>> = Mutex::new(None);++pub struct Session {+ handle: u64, // CONTROLTRACE_HANDLE.Value+}++fn ctl(v: u64) -> CONTROLTRACE_HANDLE {+ CONTROLTRACE_HANDLE { Value: v }+}++fn is_kernel_network(g: &GUID) -> bool {+ (g.data1, g.data2, g.data3, g.data4) == (KERNEL_NETWORK.data1, KERNEL_NETWORK.data2, KERNEL_NETWORK.data3, KERNEL_NETWORK.data4)+}++fn wide(s: &str) -> Vec<u16> {+ s.encode_utf16().chain(Some(0)).collect()+}++/// Буфер EVENT_TRACE_PROPERTIES + имя сессии сразу за структурой (так требует ETW).+fn props_buffer(name: &[u16]) -> Vec<u64> {+ let head = std::mem::size_of::<EVENT_TRACE_PROPERTIES>();+ let total = head + name.len() * 2;+ let mut buf = vec![0u64; total.div_ceil(8)];+ unsafe {+ let p = buf.as_mut_ptr() as *mut EVENT_TRACE_PROPERTIES;+ (*p).Wnode.BufferSize = total as u32;+ (*p).Wnode.Flags = WNODE_FLAG_TRACED_GUID;+ (*p).Wnode.ClientContext = 1; // QPC-время+ (*p).LogFileMode = EVENT_TRACE_REAL_TIME_MODE;+ (*p).LoggerNameOffset = head as u32;+ std::ptr::copy_nonoverlapping(name.as_ptr(), (buf.as_mut_ptr() as *mut u8).add(head) as *mut u16, name.len());+ }+ buf+}++/// Событие «отправлено/получено»: первые два поля данных — PID и размер.+unsafe extern "system" fn on_event(rec: *mut EVENT_RECORD) {+ let r = unsafe { &*rec };+ if !is_kernel_network(&r.EventHeader.ProviderId) || r.UserDataLength < 8 || r.UserData.is_null() {+ return;+ }+ let received = match r.EventHeader.EventDescriptor.Id {+ 10 | 26 | 42 | 58 => false, // TCP/UDP отправка, IPv4/IPv6+ 11 | 27 | 43 | 59 => true, // получение+ _ => return,+ };+ let d = unsafe { std::slice::from_raw_parts(r.UserData as *const u8, 8) };+ let pid = u32::from_le_bytes([d[0], d[1], d[2], d[3]]);+ let size = u32::from_le_bytes([d[4], d[5], d[6], d[7]]) as u64;+ if let Ok(mut g) = TOTALS.lock() {+ let e = g.get_or_insert_with(HashMap::new).entry(pid).or_insert((0, 0));+ if received { e.0 += size } else { e.1 += size }+ }+}++/// Запускает сессию и поток-потребитель. None — не хватило прав или ETW недоступен.+pub fn start() -> Option<Session> {+ let name = wide(SESSION);+ let session_handle;+ unsafe {+ // сессия могла остаться от упавшего экземпляра — гасим её+ let mut stale = props_buffer(&name);+ ControlTraceW(ctl(0), name.as_ptr(), stale.as_mut_ptr() as *mut EVENT_TRACE_PROPERTIES, EVENT_TRACE_CONTROL_STOP);++ let mut props = props_buffer(&name);+ let mut handle = ctl(0);+ if StartTraceW(&mut handle, name.as_ptr(), props.as_mut_ptr() as *mut EVENT_TRACE_PROPERTIES) != 0 {+ return None;+ }+ if EnableTraceEx2(handle, &KERNEL_NETWORK, EVENT_CONTROL_CODE_ENABLE_PROVIDER, TRACE_LEVEL_INFORMATION as u8, u64::MAX, 0, 0, null()) != 0 {+ ControlTraceW(handle, null(), props.as_mut_ptr() as *mut EVENT_TRACE_PROPERTIES, EVENT_TRACE_CONTROL_STOP);+ return None;+ }+ session_handle = handle.Value;+ }+ std::thread::spawn(move || unsafe {+ let mut logger = wide(SESSION);+ let mut lf: EVENT_TRACE_LOGFILEW = std::mem::zeroed();+ lf.LoggerName = logger.as_mut_ptr();+ lf.Anonymous1.ProcessTraceMode = PROCESS_TRACE_MODE_REAL_TIME | PROCESS_TRACE_MODE_EVENT_RECORD;+ lf.Anonymous2.EventRecordCallback = Some(on_event);+ let h = OpenTraceW(&mut lf);+ if h.Value != u64::MAX {+ ProcessTrace(&h, 1, null(), null()); // блокируется до остановки сессии+ CloseTrace(h);+ }+ });+ Some(Session { handle: session_handle })+}++pub fn stop(s: Session) {+ let name = wide(SESSION);+ let mut props = props_buffer(&name);+ unsafe { ControlTraceW(ctl(s.handle), null(), props.as_mut_ptr() as *mut EVENT_TRACE_PROPERTIES, EVENT_TRACE_CONTROL_STOP) };+}++/// Забирает накопленные байты по процессам (и обнуляет счётчики).+pub fn drain() -> HashMap<u32, (u64, u64)> {+ TOTALS.lock().ok().and_then(|mut g| g.take()).unwrap_or_default()+}++#[allow(dead_code)]+fn _unused(_: *mut u8) -> *mut u8 {+ null_mut()+}diff --git a/plugins/rtaskmgr-win32/src/perf.rs b/plugins/rtaskmgr-win32/src/perf.rsnew file mode 100644index 0000000..ed93723--- /dev/null+++ b/plugins/rtaskmgr-win32/src/perf.rs@@ -0,0 +1,456 @@+//! Системные показатели для страницы «Производительность»: счётчики PDH (диск, сеть, GPU),+//! сведения о процессоре/памяти и т.п.+use std::{collections::HashMap, ptr::null_mut};+use windows_sys::Win32::System::Performance::*;++fn wide(s: &str) -> Vec<u16> {+ s.encode_utf16().chain(Some(0)).collect()+}++struct Counter(PDH_HCOUNTER);++pub struct Perf {+ query: PDH_HQUERY,+ disk_time: Option<Counter>,+ disk_read: Option<Counter>,+ disk_write: Option<Counter>,+ disk_lat: Option<Counter>,+ disk_time_a: Option<Counter>, // то же по каждому физическому диску (PhysicalDisk(*))+ disk_read_a: Option<Counter>,+ disk_write_a: Option<Counter>,+ disk_lat_a: Option<Counter>,+ mem_mod: Option<Counter>,+ mem_sb_res: Option<Counter>,+ mem_sb_norm: Option<Counter>,+ mem_sb_core: Option<Counter>,+ mem_free: Option<Counter>,+ gpu_eng: Option<Counter>,+ gpu_ded: Option<Counter>,+ gpu_shr: Option<Counter>,+ net_rx: Option<Counter>,+ net_tx: Option<Counter>,+ net_bw: Option<Counter>,+ cpu_perf: Option<Counter>,+}++#[derive(Clone, Default, Debug)]+pub struct NetIf {+ pub name: String,+ pub rx: f64, // байт/с+ pub tx: f64,+ pub bw: f64, // бит/с+}++/// Показатели одного видеоадаптера (по LUID).+#[derive(Clone, Default, Debug)]+pub struct GpuSample {+ pub types: HashMap<String, f32>, // загрузка по типам движков: 3D, Copy, VideoEncode, VideoDecode ...+ pub total: f32,+ pub ded: u64, // байт+ pub shr: u64,+}++/// Показатели одного физического диска.+#[derive(Clone, Default, Debug)]+pub struct DiskSample {+ pub number: u32,+ pub letters: String, // «C:» или «D: E:»+ pub active: f32,+ pub rd: f64,+ pub wr: f64,+ pub ms: f32,+}++#[derive(Clone, Default)]+pub struct Sample {+ pub gpus: HashMap<(u32, i32), GpuSample>,+ pub disks: Vec<DiskSample>,+ pub nics: Vec<NetIf>,+ pub mem_modified: u64,+ pub mem_standby: u64,+ pub mem_free: u64,+ pub disk_active: f32, // %+ pub disk_read: f64, // байт/с+ pub disk_write: f64,+ #[cfg_attr(not(test), allow(dead_code))] // only the self-test prints it+ pub disk_ms: f32, // средний отклик, мс+ pub gpu_total: f32,+ pub gpu_types: HashMap<String, f32>, // загрузка по типам движков: 3D, Copy, VideoEncode, VideoDecode ...+ pub gpu_by_pid: HashMap<u32, f32>,+ pub gpu_ded: u64, // байт+ pub gpu_shr: u64,+ pub net: Option<NetIf>,+ pub net_util: f32, // % пропускной способности самого загруженного интерфейса+ pub cpu_perf: f32, // % от базовой частоты+}++/// LUID из имени экземпляра счётчика: `..._luid_0x00000000_0x0000E4F8_...` -> (низкая часть, высокая часть).+pub fn parse_luid(name: &str) -> Option<(u32, i32)> {+ let rest = name.split("luid_0x").nth(1)?;+ let mut it = rest.split('_');+ let high = u32::from_str_radix(it.next()?, 16).ok()?;+ let low = u32::from_str_radix(it.next()?.trim_start_matches("0x"), 16).ok()?;+ Some((low, high as i32))+}++impl Perf {+ pub fn new() -> Option<Perf> {+ unsafe {+ let mut query: PDH_HQUERY = null_mut();+ if PdhOpenQueryW(std::ptr::null(), 0, &mut query) != 0 {+ return None;+ }+ let add = |path: &str| -> Option<Counter> {+ let mut c: PDH_HCOUNTER = null_mut();+ (PdhAddEnglishCounterW(query, wide(path).as_ptr(), 0, &mut c) == 0).then_some(Counter(c))+ };+ let p = Perf {+ query,+ disk_time: add(r"\PhysicalDisk(_Total)\% Disk Time"),+ disk_read: add(r"\PhysicalDisk(_Total)\Disk Read Bytes/sec"),+ disk_write: add(r"\PhysicalDisk(_Total)\Disk Write Bytes/sec"),+ disk_lat: add(r"\PhysicalDisk(_Total)\Avg. Disk sec/Transfer"),+ disk_time_a: add(r"\PhysicalDisk(*)\% Disk Time"),+ disk_read_a: add(r"\PhysicalDisk(*)\Disk Read Bytes/sec"),+ disk_write_a: add(r"\PhysicalDisk(*)\Disk Write Bytes/sec"),+ disk_lat_a: add(r"\PhysicalDisk(*)\Avg. Disk sec/Transfer"),+ mem_mod: add(r"\Memory\Modified Page List Bytes"),+ mem_sb_res: add(r"\Memory\Standby Cache Reserve Bytes"),+ mem_sb_norm: add(r"\Memory\Standby Cache Normal Priority Bytes"),+ mem_sb_core: add(r"\Memory\Standby Cache Core Bytes"),+ mem_free: add(r"\Memory\Free & Zero Page List Bytes"),+ gpu_eng: add(r"\GPU Engine(*)\Utilization Percentage"),+ gpu_ded: add(r"\GPU Adapter Memory(*)\Dedicated Usage"),+ gpu_shr: add(r"\GPU Adapter Memory(*)\Shared Usage"),+ net_rx: add(r"\Network Interface(*)\Bytes Received/sec"),+ net_tx: add(r"\Network Interface(*)\Bytes Sent/sec"),+ net_bw: add(r"\Network Interface(*)\Current Bandwidth"),+ cpu_perf: add(r"\Processor Information(_Total)\% Processor Performance"),+ };+ PdhCollectQueryData(query); // первый сбор нужен как точка отсчёта для скоростей+ Some(p)+ }+ }++ fn value(c: &Option<Counter>) -> f64 {+ let Some(c) = c else { return 0.0 };+ unsafe {+ let mut v: PDH_FMT_COUNTERVALUE = std::mem::zeroed();+ if PdhGetFormattedCounterValue(c.0, PDH_FMT_DOUBLE, null_mut(), &mut v) == 0 && v.CStatus == 0 {+ v.Anonymous.doubleValue+ } else {+ 0.0+ }+ }+ }++ /// Все экземпляры счётчика с подстановкой (*): (имя экземпляра, значение).+ fn array(c: &Option<Counter>) -> Vec<(String, f64)> {+ let Some(c) = c else { return vec![] };+ unsafe {+ let (mut size, mut count) = (0u32, 0u32);+ let rc = PdhGetFormattedCounterArrayW(c.0, PDH_FMT_DOUBLE, &mut size, &mut count, null_mut());+ if rc != PDH_MORE_DATA || size == 0 {+ return vec![];+ }+ let mut buf = vec![0u64; size as usize / 8 + 8]; // u64 — выравнивание под структуры+ let items = buf.as_mut_ptr() as *mut PDH_FMT_COUNTERVALUE_ITEM_W;+ if PdhGetFormattedCounterArrayW(c.0, PDH_FMT_DOUBLE, &mut size, &mut count, items) != 0 {+ return vec![];+ }+ (0..count as usize)+ .filter_map(|i| {+ let it = &*items.add(i);+ if it.szName.is_null() || it.FmtValue.CStatus != 0 {+ return None;+ }+ let mut n = 0;+ while *it.szName.add(n) != 0 {+ n += 1;+ }+ let name = String::from_utf16_lossy(std::slice::from_raw_parts(it.szName, n));+ Some((name, it.FmtValue.Anonymous.doubleValue))+ })+ .collect()+ }+ }++ pub fn sample(&mut self) -> Sample {+ unsafe { PdhCollectQueryData(self.query) };+ let mut s = Sample {+ disk_active: Self::value(&self.disk_time).clamp(0.0, 100.0) as f32,+ disk_read: Self::value(&self.disk_read),+ disk_write: Self::value(&self.disk_write),+ disk_ms: (Self::value(&self.disk_lat) * 1000.0) as f32,+ cpu_perf: Self::value(&self.cpu_perf) as f32,+ ..Default::default()+ };+ let (mut by_type, mut by_pid_type): (HashMap<String, f64>, HashMap<(u32, String), f64>) = Default::default();+ for (name, v) in Self::array(&self.gpu_eng) {+ let pid = name.strip_prefix("pid_").and_then(|r| r.split('_').next()).and_then(|p| p.parse::<u32>().ok());+ let ty = name.rsplit("engtype_").next().unwrap_or("").to_string();+ *by_type.entry(ty.clone()).or_default() += v;+ if let Some(pid) = pid {+ *by_pid_type.entry((pid, ty)).or_default() += v;+ }+ }+ s.gpu_total = by_type.values().cloned().fold(0.0, f64::max).min(100.0) as f32;+ s.gpu_types = by_type.iter().map(|(k, v)| (k.clone(), v.min(100.0) as f32)).collect();+ for ((pid, _), v) in by_pid_type {+ let e = s.gpu_by_pid.entry(pid).or_insert(0.0);+ *e = e.max(v.min(100.0) as f32);+ }+ s.gpu_ded = Self::array(&self.gpu_ded).iter().map(|x| x.1).sum::<f64>() as u64;+ s.gpu_shr = Self::array(&self.gpu_shr).iter().map(|x| x.1).sum::<f64>() as u64;++ // те же данные по каждому адаптеру (LUID)+ let mut per_type: HashMap<((u32, i32), String), f64> = HashMap::new();+ for (name, v) in Self::array(&self.gpu_eng) {+ if let Some(l) = parse_luid(&name) {+ let ty = name.rsplit("engtype_").next().unwrap_or("").to_string();+ *per_type.entry((l, ty)).or_default() += v;+ }+ }+ for ((l, ty), v) in per_type {+ let g = s.gpus.entry(l).or_default();+ g.types.insert(ty, v.min(100.0) as f32);+ g.total = g.total.max(v.min(100.0) as f32);+ }+ for (name, v) in Self::array(&self.gpu_ded) {+ if let Some(l) = parse_luid(&name) {+ s.gpus.entry(l).or_default().ded += v as u64;+ }+ }+ for (name, v) in Self::array(&self.gpu_shr) {+ if let Some(l) = parse_luid(&name) {+ s.gpus.entry(l).or_default().shr += v as u64;+ }+ }++ // физические диски: экземпляры вида «0 C:» или «1 D: E:»+ let (act, rd, wr, lat) = (Self::array(&self.disk_time_a), Self::array(&self.disk_read_a), Self::array(&self.disk_write_a), Self::array(&self.disk_lat_a));+ let (rd, wr, lat): (HashMap<String, f64>, HashMap<String, f64>, HashMap<String, f64>) = (rd.into_iter().collect(), wr.into_iter().collect(), lat.into_iter().collect());+ for (name, a) in act {+ if name == "_Total" {+ continue;+ }+ let (num, letters) = name.split_once(' ').unwrap_or((&name, ""));+ if let Ok(number) = num.parse::<u32>() {+ s.disks.push(DiskSample {+ number,+ letters: letters.to_string(),+ active: a.clamp(0.0, 100.0) as f32,+ rd: rd.get(&name).copied().unwrap_or(0.0),+ wr: wr.get(&name).copied().unwrap_or(0.0),+ ms: (lat.get(&name).copied().unwrap_or(0.0) * 1000.0) as f32,+ });+ }+ }+ s.disks.sort_by_key(|d| d.number);++ // состав памяти+ s.mem_modified = Self::value(&self.mem_mod) as u64;+ s.mem_standby = (Self::value(&self.mem_sb_res) + Self::value(&self.mem_sb_norm) + Self::value(&self.mem_sb_core)) as u64;+ s.mem_free = Self::value(&self.mem_free) as u64;++ let (rx, tx, bw) = (Self::array(&self.net_rx), Self::array(&self.net_tx), Self::array(&self.net_bw));+ let tx: HashMap<String, f64> = tx.into_iter().collect();+ let bw: HashMap<String, f64> = bw.into_iter().collect();+ let bad = |n: &str| {+ let l = n.to_lowercase();+ l.contains("loopback") || l.contains("isatap") || l.contains("teredo") || l.contains("pseudo") || l.contains("6to4")+ };+ let mut best: Option<NetIf> = None;+ for (name, r) in rx.into_iter().filter(|(n, _)| !bad(n)) {+ let cand = NetIf { rx: r, tx: tx.get(&name).copied().unwrap_or(0.0), bw: bw.get(&name).copied().unwrap_or(0.0), name };+ if cand.bw > 0.0 {+ s.nics.push(cand.clone());+ }+ let better = best.as_ref().is_none_or(|b| (cand.rx + cand.tx, cand.bw) > (b.rx + b.tx, b.bw));+ if better && cand.bw > 0.0 {+ best = Some(cand);+ }+ }+ if let Some(b) = &best {+ s.net_util = ((b.rx + b.tx) * 8.0 / b.bw * 100.0).clamp(0.0, 100.0) as f32;+ }+ s.net = best;+ s+ }+}++impl Drop for Perf {+ fn drop(&mut self) {+ unsafe { PdhCloseQuery(self.query) };+ }+}++// ---------- статические сведения о системе ----------+#[derive(Clone, Default)]+pub struct SysInfo {+ pub base_mhz: u32,+ pub sockets: u32,+ pub l1: u64,+ pub l2: u64,+ pub l3: u64,+ pub virt: bool,+ #[cfg_attr(not(test), allow(dead_code))] // only the tests read it+ pub gpu_name: String,+}++fn reg_string(sub: &str, name: &str) -> Option<String> {+ use winapi::um::winreg::{RegGetValueW, HKEY_LOCAL_MACHINE};+ let (s, n) = (wide(sub), wide(name));+ let mut buf = vec![0u16; 512];+ let mut size = (buf.len() * 2) as u32;+ let rc = unsafe { RegGetValueW(HKEY_LOCAL_MACHINE, s.as_ptr(), n.as_ptr(), 0x2 /*RRF_RT_REG_SZ*/, null_mut(), buf.as_mut_ptr() as *mut _, &mut size) };+ (rc == 0).then(|| String::from_utf16_lossy(&buf[..(size as usize / 2).saturating_sub(1)]))+}++fn reg_dword(sub: &str, name: &str) -> Option<u32> {+ use winapi::um::winreg::{RegGetValueW, HKEY_LOCAL_MACHINE};+ let (s, n) = (wide(sub), wide(name));+ let (mut v, mut size) = (0u32, 4u32);+ let rc = unsafe { RegGetValueW(HKEY_LOCAL_MACHINE, s.as_ptr(), n.as_ptr(), 0x10 /*RRF_RT_REG_DWORD*/, null_mut(), &mut v as *mut u32 as *mut _, &mut size) };+ (rc == 0).then_some(v)+}++/// Разбор записей GetLogicalProcessorInformation: (пакетов процессора, суммарный кэш L1/L2/L3 в байтах).+fn processor_info() -> (u32, [u64; 3]) {+ #[link(name = "kernel32")]+ unsafe extern "system" {+ fn GetLogicalProcessorInformation(buf: *mut u8, len: *mut u32) -> i32;+ }+ let mut len = 0u32;+ unsafe { GetLogicalProcessorInformation(null_mut(), &mut len) };+ if len == 0 {+ return (1, [0; 3]);+ }+ let mut buf = vec![0u8; len as usize];+ if unsafe { GetLogicalProcessorInformation(buf.as_mut_ptr(), &mut len) } == 0 {+ return (1, [0; 3]);+ }+ let (mut sockets, mut cache) = (0u32, [0u64; 3]);+ // SYSTEM_LOGICAL_PROCESSOR_INFORMATION на x64 — 32 байта: маска(8), тип(4)+выравнивание(4), union(16)+ for e in buf.as_chunks::<32>().0 {+ match u32::from_le_bytes([e[8], e[9], e[10], e[11]]) {+ 3 => sockets += 1, // RelationProcessorPackage+ 2 => {+ // RelationCache: Level(1) Assoc(1) LineSize(2) Size(4) Type(4)+ let (level, size) = (e[16], u32::from_le_bytes([e[20], e[21], e[22], e[23]]) as u64);+ if (1..=3).contains(&level) {+ cache[level as usize - 1] += size;+ }+ }+ _ => {}+ }+ }+ (sockets.max(1), cache)+}++/// Номинальная (базовая) частота процессора, МГц — как показывает диспетчер задач.+fn base_mhz() -> u32 {+ #[link(name = "powrprof")]+ unsafe extern "system" {+ fn CallNtPowerInformation(level: i32, input: *const u8, in_len: u32, output: *mut u8, out_len: u32) -> i32;+ }+ // PROCESSOR_POWER_INFORMATION: Number, MaxMhz, CurrentMhz, MhzLimit, MaxIdleState, CurrentIdleState (по 4 байта) на каждый логический процессор+ let mut buf = vec![0u8; 24 * 64];+ let rc = unsafe { CallNtPowerInformation(11 /*ProcessorInformation*/, std::ptr::null(), 0, buf.as_mut_ptr(), buf.len() as u32) };+ if rc == 0 {+ let max = u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]);+ if max > 0 {+ return max;+ }+ }+ reg_dword(r"HARDWARE\DESCRIPTION\System\CentralProcessor\0", "~MHz").unwrap_or(0)+}++pub fn static_info() -> SysInfo {+ let (sockets, cache) = processor_info();+ let class = r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}";+ let mut gpus: Vec<String> = (0..8).filter_map(|i| reg_string(&format!(r"{class}\{i:04}"), "DriverDesc")).filter(|n| !n.to_lowercase().contains("basic")).collect();+ gpus.sort_by_key(|n| {+ let l = n.to_lowercase();+ !(l.contains("nvidia") || l.contains("radeon") || l.contains("geforce")) // дискретная видеокарта — первой+ });+ SysInfo {+ base_mhz: base_mhz(),+ sockets,+ l1: cache[0],+ l2: cache[1],+ l3: cache[2],+ // «Виртуализация включена»: прошивка разрешила её либо уже работает гипервизор (CPUID.1:ECX[31])+ virt: unsafe { winapi::um::processthreadsapi::IsProcessorFeaturePresent(21) } != 0 || (std::arch::x86_64::__cpuid(1).ecx >> 31) & 1 == 1,+ gpu_name: gpus.into_iter().next().unwrap_or_default(),+ }+}++#[derive(Clone, Copy, Default)]+pub struct MemInfo {+ pub commit_total: u64,+ pub commit_limit: u64,+ pub cache: u64,+ pub paged: u64,+ pub nonpaged: u64,+ pub processes: u32,+ pub threads: u32,+ pub handles: u32,+}++pub fn mem_info() -> MemInfo {+ use winapi::um::psapi::{GetPerformanceInfo, PERFORMANCE_INFORMATION};+ let mut p: PERFORMANCE_INFORMATION = unsafe { std::mem::zeroed() };+ let ok = unsafe { GetPerformanceInfo(&mut p, std::mem::size_of::<PERFORMANCE_INFORMATION>() as u32) };+ if ok == 0 {+ return MemInfo::default();+ }+ let page = p.PageSize as u64;+ MemInfo {+ commit_total: p.CommitTotal as u64 * page,+ commit_limit: p.CommitLimit as u64 * page,+ cache: p.SystemCache as u64 * page,+ paged: p.KernelPaged as u64 * page,+ nonpaged: p.KernelNonpaged as u64 * page,+ processes: p.ProcessCount,+ threads: p.ThreadCount,+ handles: p.HandleCount,+ }+}++pub fn uptime_secs() -> u64 {+ unsafe { winapi::um::sysinfoapi::GetTickCount64() / 1000 }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn luid_is_parsed_from_counter_instance_names() {+ assert_eq!(parse_luid("pid_4_luid_0x00000000_0x0000E4F8_phys_0_eng_0_engtype_3D"), Some((0xE4F8, 0)));+ assert_eq!(parse_luid("luid_0x00000001_0x0000F4C0_phys_0"), Some((0xF4C0, 1)));+ assert_eq!(parse_luid("no luid here"), None);+ }++ #[test]+ fn pdh_counters_work_and_system_info_is_sane() {+ let mut p = Perf::new().expect("PDH доступен");+ std::thread::sleep(std::time::Duration::from_millis(1100));+ let s = p.sample();+ assert!((0.0..=100.0).contains(&s.disk_active));+ assert!((0.0..=100.0).contains(&s.gpu_total));+ let i = static_info();+ assert!(i.base_mhz > 500 && i.sockets >= 1 && i.l2 > 0, "base={} sockets={} l2={}", i.base_mhz, i.sockets, i.l2);+ let m = mem_info();+ assert!(m.processes > 10 && m.threads > m.processes && m.commit_limit > 0);+ assert!(uptime_secs() > 10);+ assert!(!s.disks.is_empty(), "PhysicalDisk(*) должен вернуть хотя бы один диск");+ assert!(s.disks.iter().any(|d| d.letters.contains("C:")), "{:?}", s.disks);+ assert!(s.mem_free > 0 && s.mem_standby > 0, "состав памяти: free={} standby={}", s.mem_free, s.mem_standby);+ eprintln!("disks={:?}\nnics={:?}\ngpus={:?}\nmem mod={}MB standby={}MB free={}MB", s.disks, s.nics.iter().map(|n| &n.name).collect::<Vec<_>>(), s.gpus, s.mem_modified >> 20, s.mem_standby >> 20, s.mem_free >> 20);+ eprintln!("base={}MHz perf={:.0}% sockets={} L1={}K L2={}K L3={}K virt={} gpu='{}'", i.base_mhz, s.cpu_perf, i.sockets, i.l1 / 1024, i.l2 / 1024, i.l3 / 1024, i.virt, i.gpu_name);+ eprintln!("disk active={:.0}% rd={:.0} wr={:.0} lat={:.2}ms | gpu={:.0}% ded={}MB shr={}MB pids={} | net={:?} util={:.2}%", s.disk_active, s.disk_read, s.disk_write, s.disk_ms, s.gpu_total, s.gpu_ded >> 20, s.gpu_shr >> 20, s.gpu_by_pid.len(), s.net, s.net_util);+ eprintln!("commit={}/{}MB cache={}MB paged={}MB nonpaged={}MB procs={} threads={} handles={}", m.commit_total >> 20, m.commit_limit >> 20, m.cache >> 20, m.paged >> 20, m.nonpaged >> 20, m.processes, m.threads, m.handles);+ }+}diff --git a/plugins/rtaskmgr-win32/src/res.rs b/plugins/rtaskmgr-win32/src/res.rsnew file mode 100644index 0000000..f81a5e6--- /dev/null+++ b/plugins/rtaskmgr-win32/src/res.rs@@ -0,0 +1,144 @@+//! Иконки, описание и издатель исполняемых файлов. Всё читается в фоновом потоке и кэшируется.+use std::{+ collections::HashMap,+ ptr::{null, null_mut},+ sync::{mpsc, Arc, Mutex},+};+use winapi::um::{+ shellapi::ExtractIconExW,+ winver::{GetFileVersionInfoSizeW, GetFileVersionInfoW, VerQueryValueW},+};++#[derive(Clone, Default)]+pub struct Res {+ pub icon: isize, // HICON (0 — нет)+ pub desc: String,+ pub company: String,+}++pub struct ResCache {+ map: Arc<Mutex<HashMap<String, Option<Res>>>>, // None — запрошено, ещё не готово+ tx: mpsc::Sender<String>,+ /// Поднимается, когда в кэше появились новые данные — интерфейсу пора перерисоваться.+ /// Стандартный значок приложения (для процессов без своего значка).+ pub generic_icon: isize,+}++fn wide(s: &str) -> Vec<u16> {+ s.encode_utf16().chain(Some(0)).collect()+}++unsafe fn version_string(buf: &[u8], lang: &str, key: &str) -> Option<String> {+ let q = wide(&format!(r"\StringFileInfo\{lang}\{key}"));+ let (mut p, mut len) = (null_mut(), 0u32);+ let ok = unsafe { VerQueryValueW(buf.as_ptr() as *const _, q.as_ptr(), &mut p, &mut len) };+ if ok == 0 || p.is_null() || len == 0 {+ return None;+ }+ let s = unsafe { std::slice::from_raw_parts(p as *const u16, len as usize) };+ let s = String::from_utf16_lossy(s).trim_end_matches('\0').trim().to_string();+ (!s.is_empty()).then_some(s)+}++fn load(path: &str) -> Res {+ let mut r = Res::default();+ let w = wide(path);+ unsafe {+ let mut small = null_mut();+ if ExtractIconExW(w.as_ptr(), 0, null_mut(), &mut small, 1) > 0 {+ r.icon = small as isize;+ }+ let mut h = 0u32;+ let size = GetFileVersionInfoSizeW(w.as_ptr(), &mut h);+ if size > 0 {+ let mut buf = vec![0u8; size as usize];+ if GetFileVersionInfoW(w.as_ptr(), 0, size, buf.as_mut_ptr() as *mut _) != 0 {+ // языки ресурса: пары (язык, кодовая страница); берём первый, затем английский как запасной+ let (mut p, mut len) = (null_mut(), 0u32);+ let q = wide(r"\VarFileInfo\Translation");+ let mut langs: Vec<String> = vec![];+ if VerQueryValueW(buf.as_ptr() as *const _, q.as_ptr(), &mut p, &mut len) != 0 && len >= 4 {+ let pairs = std::slice::from_raw_parts(p as *const u16, (len / 2) as usize);+ for c in pairs.as_chunks::<2>().0 {+ langs.push(format!("{:04x}{:04x}", c[0], c[1]));+ }+ }+ langs.push("040904b0".into());+ langs.push("040904e4".into());+ for l in &langs {+ if r.desc.is_empty() {+ r.desc = version_string(&buf, l, "FileDescription").unwrap_or_default();+ }+ if r.company.is_empty() {+ r.company = version_string(&buf, l, "CompanyName").unwrap_or_default();+ }+ }+ }+ }+ }+ let _ = null::<u8>();+ // «битые» строки (управляющие символы, U+FFFD) не показываем — берём имя файла+ let bad = |s: &str| s.chars().any(|c| c.is_control() || c == '\u{FFFD}');+ if bad(&r.desc) {+ r.desc.clear();+ }+ if bad(&r.company) {+ r.company.clear();+ }+ r+}++impl ResCache {+ pub fn new() -> Self {+ let map: Arc<Mutex<HashMap<String, Option<Res>>>> = Arc::new(Mutex::new(HashMap::new()));+ let (tx, rx) = mpsc::channel::<String>();+ let m = map.clone();+ std::thread::spawn(move || {+ for path in rx {+ let r = load(&path);+ if let Ok(mut g) = m.lock() {+ g.insert(path.to_lowercase(), Some(r)); // ключ в том же регистре, в котором его ищет get()+ }+ }+ });+ let generic_icon = unsafe {+ let mut small = null_mut();+ let w = wide("shell32.dll");+ if ExtractIconExW(w.as_ptr(), 2, null_mut(), &mut small, 1) > 0 { small as isize } else { 0 } // значок 2 — «приложение»+ };+ Self { map, tx, generic_icon }+ }++ /// Готовые данные или None (и запрос в очередь, если ещё не запрашивали).+ pub fn get(&self, path: &str) -> Option<Res> {+ let key = path.to_lowercase();+ let Ok(mut g) = self.map.lock() else { return None };+ match g.get(&key) {+ Some(v) => v.clone(),+ None => {+ g.insert(key, None);+ let _ = self.tx.send(path.to_string());+ None+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn reads_description_and_icon_of_a_system_file() {+ let r = load(r"C:\Windows\System32\notepad.exe");+ assert!(!r.desc.is_empty(), "описание файла должно читаться");+ assert!(r.company.to_lowercase().contains("microsoft"));+ assert_ne!(r.icon, 0, "иконка должна извлекаться");+ }++ #[test]+ fn missing_file_gives_empty_resources() {+ let r = load(r"C:\no\such\file.exe");+ assert!(r.desc.is_empty() && r.icon == 0);+ }+}diff --git a/plugins/rtaskmgr-win32/src/startup.rs b/plugins/rtaskmgr-win32/src/startup.rsnew file mode 100644index 0000000..f90e3a1--- /dev/null+++ b/plugins/rtaskmgr-win32/src/startup.rs@@ -0,0 +1,221 @@+//! Автозагрузка: ключи Run в реестре и папки Startup; включение/выключение через StartupApproved+//! (так же, как это делает штатный диспетчер задач).+use std::{fs, path::PathBuf, ptr::null_mut};+use winapi::shared::minwindef::HKEY;+use winapi::um::{+ sysinfoapi::GetSystemTimeAsFileTime,+ winnt::{KEY_READ, KEY_SET_VALUE, REG_BINARY, REG_EXPAND_SZ, REG_SZ},+ winreg::*,+};++const RUN: &str = r"Software\Microsoft\Windows\CurrentVersion\Run";+const RUN32: &str = r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Run";+const APPROVED: &str = r"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved";++struct Source {+ label: &'static str,+ hklm: bool,+ run: Option<&'static str>, // None — папка автозагрузки+ approved: &'static str,+}++const SOURCES: [Source; 5] = [+ Source { label: "Реестр, текущий пользователь", hklm: false, run: Some(RUN), approved: "Run" },+ Source { label: "Реестр, все пользователи", hklm: true, run: Some(RUN), approved: "Run" },+ Source { label: "Реестр, все пользователи (32-бит)", hklm: true, run: Some(RUN32), approved: "Run32" },+ Source { label: "Папка автозагрузки (пользователь)", hklm: false, run: None, approved: "StartupFolder" },+ Source { label: "Папка автозагрузки (все)", hklm: true, run: None, approved: "StartupFolder" },+];++pub struct Item {+ pub name: String, // имя значения реестра или имя файла+ pub command: String,+ pub source: usize,+ pub enabled: bool,+}++impl Item {+ pub fn source_label(&self) -> &'static str {+ SOURCES[self.source].label+ }+ /// Для HKLM нужны права администратора.+ pub fn needs_admin(&self) -> bool {+ SOURCES[self.source].hklm+ }+ pub fn key(&self) -> String {+ format!("{}|{}", self.source, self.name)+ }+}++fn w(s: &str) -> Vec<u16> {+ s.encode_utf16().chain(Some(0)).collect()+}++fn root(hklm: bool) -> HKEY {+ if hklm { HKEY_LOCAL_MACHINE } else { HKEY_CURRENT_USER }+}++fn open(r: HKEY, path: &str, access: u32) -> Option<HKEY> {+ let mut k: HKEY = null_mut();+ (unsafe { RegOpenKeyExW(r, w(path).as_ptr(), 0, access, &mut k) } == 0).then_some(k)+}++fn from_utf16_bytes(b: &[u8]) -> String {+ let u: Vec<u16> = b.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes([c[0], c[1]])).collect();+ String::from_utf16_lossy(&u).trim_end_matches('\0').to_string()+}++/// Строковые значения ключа: (имя, данные).+fn string_values(r: HKEY, path: &str) -> Vec<(String, String)> {+ let mut out = vec![];+ let Some(k) = open(r, path, KEY_READ) else { return out };+ for i in 0.. {+ let mut name = vec![0u16; 16384];+ let mut nlen = name.len() as u32;+ let mut data = vec![0u8; 32768];+ let mut dlen = data.len() as u32;+ let mut ty = 0u32;+ let rc = unsafe { RegEnumValueW(k, i, name.as_mut_ptr(), &mut nlen, null_mut(), &mut ty, data.as_mut_ptr(), &mut dlen) };+ if rc != 0 {+ break; // ERROR_NO_MORE_ITEMS или ошибка — дальше читать нечего+ }+ if ty == REG_SZ || ty == REG_EXPAND_SZ {+ out.push((String::from_utf16_lossy(&name[..nlen as usize]), from_utf16_bytes(&data[..dlen as usize])));+ }+ }+ unsafe { RegCloseKey(k) };+ out+}++/// Включён ли элемент: в StartupApproved выключенному соответствует нечётный первый байт (0x03).+fn approved_enabled(hklm: bool, kind: &str, name: &str) -> bool {+ let Some(k) = open(root(hklm), &format!(r"{APPROVED}\{kind}"), KEY_READ) else { return true };+ let mut buf = [0u8; 12];+ let mut len = buf.len() as u32;+ let rc = unsafe { RegQueryValueExW(k, w(name).as_ptr(), null_mut(), null_mut(), buf.as_mut_ptr(), &mut len) };+ unsafe { RegCloseKey(k) };+ rc != 0 || len == 0 || buf[0] & 1 == 0+}++fn startup_dir(hklm: bool) -> Option<PathBuf> {+ let var = if hklm { "ProgramData" } else { "APPDATA" };+ std::env::var_os(var).map(|p| PathBuf::from(p).join(r"Microsoft\Windows\Start Menu\Programs\Startup"))+}++pub fn list() -> Vec<Item> {+ let mut out = vec![];+ for (i, s) in SOURCES.iter().enumerate() {+ match s.run {+ Some(path) => {+ for (name, command) in string_values(root(s.hklm), path) {+ let enabled = approved_enabled(s.hklm, s.approved, &name);+ out.push(Item { name, command, source: i, enabled });+ }+ }+ None => {+ let Some(d) = startup_dir(s.hklm) else { continue };+ for e in fs::read_dir(d).into_iter().flatten().flatten() {+ let name = e.file_name().to_string_lossy().into_owned();+ if name.eq_ignore_ascii_case("desktop.ini") {+ continue;+ }+ let enabled = approved_enabled(s.hklm, s.approved, &name);+ out.push(Item { name, command: e.path().display().to_string(), source: i, enabled });+ }+ }+ }+ }+ out+}++/// Значение StartupApproved: 12 байт — флаг (02 включено / 03 выключено) + FILETIME выключения.+fn approved_value(enabled: bool, filetime: u64) -> [u8; 12] {+ let mut v = [0u8; 12];+ v[0] = if enabled { 2 } else { 3 };+ if !enabled {+ v[4..].copy_from_slice(&filetime.to_le_bytes());+ }+ v+}++/// Err(код Win32) — например 5 (нет прав) для HKLM без администратора.+pub fn set_enabled(it: &Item, on: bool) -> Result<(), u32> {+ let s = &SOURCES[it.source];+ let mut ft = unsafe { std::mem::zeroed() };+ unsafe { GetSystemTimeAsFileTime(&mut ft) };+ let value = approved_value(on, (ft.dwHighDateTime as u64) << 32 | ft.dwLowDateTime as u64);+ let mut k: HKEY = null_mut();+ let path = w(&format!(r"{APPROVED}\{}", s.approved));+ let rc = unsafe {+ RegCreateKeyExW(root(s.hklm), path.as_ptr(), 0, null_mut(), 0, KEY_SET_VALUE, null_mut(), &mut k, null_mut())+ };+ if rc != 0 {+ return Err(rc as u32);+ }+ let rc = unsafe { RegSetValueExW(k, w(&it.name).as_ptr(), 0, REG_BINARY, value.as_ptr(), value.len() as u32) };+ unsafe { RegCloseKey(k) };+ if rc == 0 { Ok(()) } else { Err(rc as u32) }+}++const SELF_NAME: &str = "RTaskMgr";++pub fn self_autostart() -> bool {+ string_values(HKEY_CURRENT_USER, RUN).iter().any(|(n, _)| n == SELF_NAME)+}++/// Добавляет/убирает саму программу в автозагрузке текущего пользователя (запуск сразу в трей).+pub fn set_self_autostart(on: bool, exe: &str) -> bool {+ let Some(k) = open(HKEY_CURRENT_USER, RUN, KEY_SET_VALUE) else { return false };+ let rc = if on {+ let v: Vec<u16> = format!("\"{exe}\" --tray").encode_utf16().chain(Some(0)).collect();+ unsafe { RegSetValueExW(k, w(SELF_NAME).as_ptr(), 0, REG_SZ, v.as_ptr() as *const u8, (v.len() * 2) as u32) }+ } else {+ unsafe { RegDeleteValueW(k, w(SELF_NAME).as_ptr()) }+ };+ unsafe { RegCloseKey(k) };+ rc == 0 || !on // удалить отсутствующее значение — тоже успех+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn approved_flags() {+ assert_eq!(approved_value(true, 123)[..4], [2, 0, 0, 0]);+ let d = approved_value(false, 0x0102_0304_0506_0708);+ assert_eq!(d[0] & 1, 1); // выключено — нечётный байт, как читает approved_enabled+ assert_eq!(d[4..], 0x0102_0304_0506_0708u64.to_le_bytes());+ }++ /// Интеграционный: временное значение в HKCU\Run → отключить → включить → удалить.+ #[test]+ fn toggle_roundtrip_on_temp_registry_value() {+ use winapi::um::winnt::KEY_WRITE;+ let name = "rtaskmgr_test_dummy";+ let value: Vec<u16> = "notepad.exe".encode_utf16().chain(Some(0)).collect();+ let run = open(HKEY_CURRENT_USER, RUN, KEY_WRITE).expect("HKCU Run");+ unsafe { RegSetValueExW(run, w(name).as_ptr(), 0, REG_SZ, value.as_ptr() as *const u8, (value.len() * 2) as u32) };+ let find = |on: bool| list().into_iter().any(|i| i.name == name && i.source == 0 && i.enabled == on);+ let result = std::panic::catch_unwind(|| {+ assert!(find(true), "новое значение должно быть включено");+ let it = list().into_iter().find(|i| i.name == name).unwrap();+ set_enabled(&it, false).unwrap();+ assert!(find(false), "после set_enabled(false) значение отключено");+ set_enabled(&it, true).unwrap();+ assert!(find(true), "после set_enabled(true) значение снова включено");+ });+ unsafe { RegDeleteValueW(run, w(name).as_ptr()) };+ if let Some(k) = open(HKEY_CURRENT_USER, &format!(r"{APPROVED}\Run"), KEY_SET_VALUE) {+ unsafe { RegDeleteValueW(k, w(name).as_ptr()) };+ unsafe { RegCloseKey(k) };+ }+ unsafe { RegCloseKey(run) };+ result.unwrap();+ }++ #[test]+ fn utf16_bytes_decode() {+ assert_eq!(from_utf16_bytes(&[0x41, 0, 0x42, 0, 0, 0]), "AB");+ }+}diff --git a/plugins/rtaskmgr-win32/src/store.rs b/plugins/rtaskmgr-win32/src/store.rsnew file mode 100644index 0000000..03946bb--- /dev/null+++ b/plugins/rtaskmgr-win32/src/store.rs@@ -0,0 +1,154 @@+//! Настройки, правила и история в %APPDATA%\rtaskmgr (обычные текстовые файлы).+use std::{fs, io::Write, path::PathBuf};++#[derive(Clone, Copy, PartialEq, Debug)]+pub enum RuleAct {+ Lower, // понизить приоритет+ Notify, // только уведомить+}++#[derive(Clone, PartialEq, Debug)]+pub struct Rule {+ pub proc: String, // имя процесса в нижнем регистре+ pub cpu: f32, // порог, % от всех ядер+ pub secs: u32, // сколько секунд подряд выше порога+ pub act: RuleAct,+ pub hits: u32,+}++#[derive(Clone, Debug, PartialEq)]+pub struct Settings {+ pub view: usize,+ pub sort: usize,+ pub desc: bool,+ pub pos: (i32, i32),+ pub size: (u32, u32),+ pub to_tray: bool,+ pub theme: u8, // 0 светлая, 1 тёмная, 2 как в системе+ pub etw: bool, // сеть по процессам (нужен администратор), по умолчанию выключено+ pub gpu_temp_always: bool, // читать температуру GPU и вне страницы GPU (может будить видеокарту ноутбука)+ pub rules: Vec<Rule>,+}++impl Default for Settings {+ fn default() -> Self {+ Self { view: 0, sort: 2, desc: true, pos: (150, 60), size: (1000, 740), to_tray: true, theme: 2, etw: false, gpu_temp_always: false, rules: vec![] }+ }+}++pub fn dir() -> PathBuf {+ let base = std::env::var_os("APPDATA").map(PathBuf::from).unwrap_or_else(std::env::temp_dir);+ base.join("rtaskmgr")+}++pub fn render(s: &Settings) -> String {+ let mut t = format!(+ "view={}\npsort={}\ndesc={}\nx={}\ny={}\nw={}\nh={}\nto_tray={}\ntheme={}\netw={}\ngputemp={}\n",+ s.view, s.sort, s.desc as u8, s.pos.0, s.pos.1, s.size.0, s.size.1, s.to_tray as u8, s.theme, s.etw as u8, s.gpu_temp_always as u8+ );+ for r in &s.rules {+ t += &format!("rule={}|{}|{}|{}|{}\n", r.proc, r.cpu, r.secs, if r.act == RuleAct::Lower { "lower" } else { "notify" }, r.hits);+ }+ t+}++pub fn parse(text: &str) -> Settings {+ let mut s = Settings::default();+ for line in text.lines() {+ let Some((k, v)) = line.split_once('=') else { continue };+ match k {+ "view" => s.view = v.parse().unwrap_or(s.view),+ "psort" => s.sort = v.parse().unwrap_or(s.sort), // «sort» из версии v1 имел другой смысл — не читаем+ "desc" => s.desc = v == "1",+ "x" => s.pos.0 = v.parse().unwrap_or(s.pos.0),+ "y" => s.pos.1 = v.parse().unwrap_or(s.pos.1),+ "w" => s.size.0 = v.parse().unwrap_or(s.size.0),+ "h" => s.size.1 = v.parse().unwrap_or(s.size.1),+ "to_tray" => s.to_tray = v == "1",+ "theme" => s.theme = v.parse().unwrap_or(2).min(2),+ "etw" => s.etw = v == "1",+ "gputemp" => s.gpu_temp_always = v == "1",+ "rule" => {+ let p: Vec<&str> = v.split('|').collect();+ if let [name, cpu, secs, act, hits] = p[..]+ && let (Ok(cpu), Ok(secs)) = (cpu.parse(), secs.parse()) {+ s.rules.push(Rule {+ proc: name.to_string(),+ cpu,+ secs,+ act: if act == "lower" { RuleAct::Lower } else { RuleAct::Notify },+ hits: hits.parse().unwrap_or(0),+ });+ }+ }+ _ => {}+ }+ }+ // защита от мусора в файле: окно не должно быть крошечным или улетать за экран+ s.size = (s.size.0.clamp(640, 4000), s.size.1.clamp(480, 3000));+ s.pos = (s.pos.0.clamp(-200, 6000), s.pos.1.clamp(-50, 4000));+ s+}++pub fn load() -> Settings {+ fs::read_to_string(dir().join("settings.ini")).map(|t| parse(&t)).unwrap_or_default()+}++pub fn save(s: &Settings) {+ let _ = fs::create_dir_all(dir());+ let _ = fs::write(dir().join("settings.ini"), render(s));+}++// ---------- история: одна строка в минуту, поля через ';' ----------+fn hist_path() -> PathBuf {+ dir().join("history.csv")+}++pub fn append_history(line: &str) {+ let _ = fs::create_dir_all(dir());+ if let Ok(mut f) = fs::OpenOptions::new().create(true).append(true).open(hist_path()) {+ let _ = writeln!(f, "{line}");+ }+}++/// Оставляет в файле последние `max` строк (≈ 7 суток при max = 10080).+pub fn trim_history(max: usize) {+ let Ok(t) = fs::read_to_string(hist_path()) else { return };+ let lines: Vec<&str> = t.lines().collect();+ if lines.len() > max {+ let _ = fs::write(hist_path(), lines[lines.len() - max..].join("\n") + "\n");+ }+}++/// Последние `limit` записей, новые сверху.+pub fn read_history(limit: usize) -> Vec<Vec<String>> {+ let t = fs::read_to_string(hist_path()).unwrap_or_default();+ t.lines().rev().take(limit).map(|l| l.split(';').map(str::to_string).collect()).filter(|r: &Vec<String>| r.len() >= 6).collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn settings_roundtrip() {+ let mut s = Settings::default();+ s.view = 3;+ s.sort = 5;+ s.theme = 1;+ s.etw = true;+ s.gpu_temp_always = true;+ s.desc = false;+ s.rules.push(Rule { proc: "chrome.exe".into(), cpu: 50.0, secs: 60, act: RuleAct::Lower, hits: 2 });+ assert_eq!(parse(&render(&s)), s);+ }++ #[test]+ fn garbage_is_clamped_and_ignored() {+ let s = parse("w=1\nh=99999\nx=-99999\nrule=bad\nnonsense\nview=abc");+ assert_eq!(s.size, (640, 3000));+ assert_eq!(s.pos.0, -200);+ assert!(s.rules.is_empty());+ assert_eq!(s.view, 0);+ }+}diff --git a/plugins/rtaskmgr-win32/src/suspect.rs b/plugins/rtaskmgr-win32/src/suspect.rsnew file mode 100644index 0000000..33f6e9e--- /dev/null+++ b/plugins/rtaskmgr-win32/src/suspect.rs@@ -0,0 +1,233 @@+//! Эвристики «подозрительных» процессов. Это подсказки для внимания, а не антивирус:+//! совпадение с правилом не значит, что программа вредоносная (и наоборот).+use std::{+ collections::HashMap,+ ptr::{null, null_mut},+ sync::{mpsc, Arc, Mutex},+};++#[derive(Clone, Debug, PartialEq)]+pub struct Reason {+ pub sev: u8, // 1 — низкая, 2 — средняя, 3 — высокая+ pub text: String,+}++#[derive(Clone, Copy, PartialEq, Debug)]+pub enum Sig {+ Unknown, // ещё проверяется или проверить нельзя+ Signed, // действительная цифровая подпись+ Unsigned, // подписи нет+ Invalid, // подпись есть, но недействительна или не вызывает доверия+}++pub fn label(sev: u8) -> &'static str {+ match sev {+ 3 => "⚠ Высокая",+ 2 => "▲ Средняя",+ 1 => "● Низкая",+ _ => "",+ }+}++pub fn sev_word(sev: u8) -> &'static str {+ match sev {+ 3 => "Высокая",+ 2 => "Средняя",+ _ => "Низкая",+ }+}++/// Системные процессы, под которые любят маскироваться вредоносные программы.+const SYSTEM_NAMES: [&str; 12] = [+ "svchost.exe", "lsass.exe", "csrss.exe", "winlogon.exe", "services.exe", "smss.exe", "wininit.exe", "spoolsv.exe", "taskhostw.exe",+ "dwm.exe", "explorer.exe", "conhost.exe",+];++/// Папки, откуда легитимные программы обычно не работают постоянно.+const RISKY_DIRS: [(&str, &str); 4] = [+ (r"\temp\", "временной папки"),+ (r"\downloads\", "папки «Загрузки»"),+ (r"\$recycle.bin\", "корзины"),+ (r"\users\public\", "общей папки Public"),+];++pub struct Facts<'a> {+ pub name: &'a str,+ pub exe: Option<&'a str>,+ pub parent: Option<&'a str>,+ pub exists: bool,+ pub sig: Sig,+ pub windir: &'a str,+}++fn short(p: &str) -> String {+ let n = p.chars().count();+ if n <= 70 { p.to_string() } else { format!("…{}", p.chars().skip(n - 68).collect::<String>()) }+}++pub fn assess(f: &Facts) -> Vec<Reason> {+ let mut out = vec![];+ let mut add = |sev: u8, text: String| out.push(Reason { sev, text });+ let name = f.name.to_lowercase();+ let parent = f.parent.map(str::to_lowercase);++ if let Some(exe) = f.exe {+ let e = exe.to_lowercase().replace('/', "\\");+ let in_windows = e.starts_with(&f.windir.to_lowercase());+ if SYSTEM_NAMES.contains(&name.as_str()) && !in_windows {+ add(3, format!("Имя совпадает с системным процессом «{}», но файл лежит не в папке Windows: {}", f.name, short(exe)));+ }+ if !f.exists {+ add(3, "Файла процесса нет на диске — его удалили после запуска (так ведёт себя вредоносный код, а иногда и установщики)".into());+ }+ let risky = RISKY_DIRS.iter().find(|(d, _)| e.contains(d));+ if let Some((_, what)) = risky {+ add(2, format!("Запущен из {what}: {} — постоянные программы обычно стоят в Program Files или AppData\\Local\\Programs", short(exe)));+ }+ if !in_windows {+ match f.sig {+ Sig::Invalid => add(2, "Цифровая подпись файла недействительна или не вызывает доверия".into()),+ Sig::Unsigned if risky.is_some() => add(2, "Файл не подписан, а запущен из временной или пользовательской папки".into()),+ Sig::Unsigned => add(1, "Файл не имеет цифровой подписи (издатель не подтверждён) — для самописных и портативных программ это нормально".into()),+ _ => {}+ }+ }+ }+ match (name.as_str(), parent.as_deref()) {+ ("svchost.exe", Some(p)) if p != "services.exe" => add(3, format!("svchost.exe запущен не службой services.exe, а процессом «{}»", f.parent.unwrap_or(""))),+ ("lsass.exe", Some(p)) if p != "wininit.exe" => add(3, format!("lsass.exe запущен не wininit.exe, а процессом «{}»", f.parent.unwrap_or(""))),+ _ => {}+ }+ out.sort_by_key(|r| std::cmp::Reverse(r.sev));+ out+}++/// Файл действительно отсутствует? Только ошибка «не найден»: отказ в доступе, занятость и прочие сбои — не повод считать файл удалённым.+pub fn file_missing(path: &str) -> bool {+ !path.is_empty() && matches!(std::fs::metadata(path), Err(e) if e.kind() == std::io::ErrorKind::NotFound)+}++/// Проверка цифровой подписи файла (WinVerifyTrust, без обращения к сети).+pub fn verify(path: &str) -> Sig {+ use windows_sys::Win32::Security::WinTrust::*;+ let wide: Vec<u16> = path.encode_utf16().chain(Some(0)).collect();+ unsafe {+ let mut file = WINTRUST_FILE_INFO { cbStruct: std::mem::size_of::<WINTRUST_FILE_INFO>() as u32, pcwszFilePath: wide.as_ptr(), hFile: null_mut(), pgKnownSubject: null_mut() };+ let mut data: WINTRUST_DATA = std::mem::zeroed();+ data.cbStruct = std::mem::size_of::<WINTRUST_DATA>() as u32;+ data.dwUIChoice = WTD_UI_NONE;+ data.fdwRevocationChecks = WTD_REVOKE_NONE;+ data.dwUnionChoice = WTD_CHOICE_FILE;+ data.Anonymous.pFile = &mut file;+ data.dwStateAction = WTD_STATEACTION_VERIFY;+ data.dwProvFlags = WTD_CACHE_ONLY_URL_RETRIEVAL | WTD_REVOCATION_CHECK_NONE;+ let mut action = WINTRUST_ACTION_GENERIC_VERIFY_V2;+ let no_ui = -1isize as *mut core::ffi::c_void; // INVALID_HANDLE_VALUE: без окон+ let rc = WinVerifyTrust(no_ui, &mut action, &mut data as *mut _ as *mut core::ffi::c_void);+ data.dwStateAction = WTD_STATEACTION_CLOSE;+ WinVerifyTrust(no_ui, &mut action, &mut data as *mut _ as *mut core::ffi::c_void);+ let _ = null::<u8>();+ match rc as u32 {+ 0 => Sig::Signed,+ 0x800B0100 => Sig::Unsigned, // TRUST_E_NOSIGNATURE+ 0x800B0003 | 0x800B0001 => Sig::Unknown, // формат файла не поддерживает подпись / нет провайдера+ _ => Sig::Invalid,+ }+ }+}++/// Кэш проверок подписи: проверка идёт в фоновом потоке, чтобы не тормозить интерфейс.+pub struct SigCache {+ map: Arc<Mutex<HashMap<String, Sig>>>,+ tx: mpsc::Sender<String>,+}++impl SigCache {+ pub fn new() -> Self {+ let map = Arc::new(Mutex::new(HashMap::new()));+ let (tx, rx) = mpsc::channel::<String>();+ let m = map.clone();+ std::thread::spawn(move || {+ for p in rx {+ let s = verify(&p);+ if let Ok(mut g) = m.lock() {+ g.insert(p, s);+ }+ }+ });+ Self { map, tx }+ }++ /// Сразу возвращает известный результат; для нового файла ставит проверку в очередь и отдаёт Unknown.+ pub fn get(&self, path: &str) -> Sig {+ let Ok(mut g) = self.map.lock() else { return Sig::Unknown };+ if let Some(s) = g.get(path) {+ return *s;+ }+ g.insert(path.to_string(), Sig::Unknown);+ let _ = self.tx.send(path.to_string());+ Sig::Unknown+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn facts<'a>(name: &'a str, exe: &'a str, parent: Option<&'a str>, exists: bool, sig: Sig) -> Facts<'a> {+ Facts { name, exe: Some(exe), parent, exists, sig, windir: r"C:\Windows" }+ }+ fn sev(r: &[Reason]) -> u8 {+ r.iter().map(|x| x.sev).max().unwrap_or(0)+ }++ #[test]+ fn normal_programs_are_not_flagged() {+ let r = assess(&facts("chrome.exe", r"C:\Program Files\Google\Chrome\Application\chrome.exe", Some("explorer.exe"), true, Sig::Signed));+ assert!(r.is_empty());+ let r = assess(&facts("svchost.exe", r"C:\Windows\System32\svchost.exe", Some("services.exe"), true, Sig::Unknown));+ assert!(r.is_empty());+ }++ #[test]+ fn fake_system_process_is_high() {+ let r = assess(&facts("svchost.exe", r"C:\Users\me\AppData\Local\Temp\svchost.exe", Some("services.exe"), true, Sig::Unsigned));+ assert_eq!(sev(&r), 3);+ assert!(r.iter().any(|x| x.text.contains("совпадает с системным")));+ assert!(r.iter().any(|x| x.text.contains("временной папки")));+ }++ #[test]+ fn wrong_parent_and_deleted_file_are_high() {+ assert_eq!(sev(&assess(&facts("svchost.exe", r"C:\Windows\System32\svchost.exe", Some("cmd.exe"), true, Sig::Unknown))), 3);+ assert_eq!(sev(&assess(&facts("lsass.exe", r"C:\Windows\System32\lsass.exe", Some("services.exe"), true, Sig::Unknown))), 3);+ assert_eq!(sev(&assess(&facts("a.exe", r"C:\Tools\a.exe", None, false, Sig::Signed))), 3);+ }++ #[test]+ fn downloads_and_signature_levels() {+ assert_eq!(sev(&assess(&facts("x.exe", r"C:\Users\me\Downloads\x.exe", None, true, Sig::Signed))), 2);+ assert_eq!(sev(&assess(&facts("x.exe", r"C:\Users\me\Downloads\x.exe", None, true, Sig::Unsigned))), 2);+ assert_eq!(sev(&assess(&facts("tool.exe", r"C:\Tools\tool.exe", None, true, Sig::Unsigned))), 1);+ assert_eq!(sev(&assess(&facts("tool.exe", r"C:\Tools\tool.exe", None, true, Sig::Invalid))), 2);+ // системные файлы из Windows подпись не проверяем (каталожные подписи) — не флагуем+ assert!(assess(&facts("notepad.exe", r"C:\Windows\notepad.exe", None, true, Sig::Unsigned)).is_empty());+ }++ #[test]+ fn missing_means_not_found_only() {+ assert!(file_missing(r"C:\no\such\file.exe"));+ assert!(!file_missing(r"C:\Windows\System32\cmd.exe"));+ assert!(!file_missing(r"C:\Windows\System32\..\System32\cmd.exe")); // путь с «..» (как у Git bash)+ assert!(!file_missing("")); // пустой путь — «неизвестно», а не «удалён»+ }++ #[test]+ fn real_signature_check_runs() {+ // cmd.exe лежит в каталоге Windows (подпись каталожная) — главное, что вызов не падает и даёт определённый ответ+ let s = verify(r"C:\Windows\System32\cmd.exe");+ assert!(matches!(s, Sig::Signed | Sig::Unsigned | Sig::Invalid | Sig::Unknown));+ // несуществующий файл не должен считаться подписанным+ assert_ne!(verify(r"C:\no\such\file.exe"), Sig::Signed);+ }+}diff --git a/plugins/rtaskmgr-win32/src/sys.rs b/plugins/rtaskmgr-win32/src/sys.rsnew file mode 100644index 0000000..7d483f6--- /dev/null+++ b/plugins/rtaskmgr-win32/src/sys.rs@@ -0,0 +1,386 @@+//! Тонкие обёртки над Win32: службы, приоритет/ядра/suspend, запуск от администратора, системный диспетчер задач.+use std::{collections::HashMap, ptr::null_mut};+use winapi::um::{+ errhandlingapi::GetLastError,+ handleapi::CloseHandle,+ processthreadsapi::{GetPriorityClass, OpenProcess, SetPriorityClass},+ winbase::{+ ABOVE_NORMAL_PRIORITY_CLASS, BELOW_NORMAL_PRIORITY_CLASS, GetProcessAffinityMask, HIGH_PRIORITY_CLASS,+ IDLE_PRIORITY_CLASS, NORMAL_PRIORITY_CLASS, SetProcessAffinityMask,+ },+ winnt::{HANDLE, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SET_INFORMATION, SERVICE_WIN32},+ winsvc::*,+};++fn wide(s: &str) -> Vec<u16> {+ s.encode_utf16().chain(Some(0)).collect()+}++unsafe fn from_wide(p: *const u16) -> String {+ if p.is_null() {+ return String::new();+ }+ let mut n = 0;+ unsafe {+ while *p.add(n) != 0 {+ n += 1;+ }+ String::from_utf16_lossy(std::slice::from_raw_parts(p, n))+ }+}++// ---------- службы ----------+pub struct Svc {+ pub name: String,+ pub display: String,+ pub pid: u32,+ pub running: bool,+}++pub fn services() -> Vec<Svc> {+ let mut out = vec![];+ unsafe {+ let scm = OpenSCManagerW(std::ptr::null(), std::ptr::null(), SC_MANAGER_ENUMERATE_SERVICE);+ if scm.is_null() {+ return out;+ }+ let (mut need, mut cnt, mut resume) = (0u32, 0u32, 0u32);+ let enumerate = |buf: *mut u8, len: u32, need: &mut u32, cnt: &mut u32, resume: &mut u32| {+ EnumServicesStatusExW(+ scm, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, SERVICE_STATE_ALL, buf, len, need, cnt, resume, std::ptr::null(),+ )+ };+ enumerate(null_mut(), 0, &mut need, &mut cnt, &mut resume); // узнаём нужный размер+ let mut buf = vec![0u64; need as usize / 8 + 1024]; // u64 — для выравнивания структур+ resume = 0;+ if enumerate(buf.as_mut_ptr() as *mut u8, (buf.len() * 8) as u32, &mut need, &mut cnt, &mut resume) != 0 {+ let arr = buf.as_ptr() as *const ENUM_SERVICE_STATUS_PROCESSW;+ for i in 0..cnt as usize {+ let e = &*arr.add(i);+ out.push(Svc {+ name: from_wide(e.lpServiceName),+ display: from_wide(e.lpDisplayName),+ pid: e.ServiceStatusProcess.dwProcessId,+ running: e.ServiceStatusProcess.dwCurrentState == SERVICE_RUNNING,+ });+ }+ }+ CloseServiceHandle(scm);+ }+ out+}++/// Запуск/остановка службы. Err — код ошибки Win32 (5 = нет прав).+pub fn service_ctl(name: &str, start: bool) -> Result<(), u32> {+ unsafe {+ let scm = OpenSCManagerW(std::ptr::null(), std::ptr::null(), SC_MANAGER_CONNECT);+ if scm.is_null() {+ return Err(GetLastError());+ }+ let n = wide(name);+ let svc = OpenServiceW(scm, n.as_ptr(), if start { SERVICE_START } else { SERVICE_STOP });+ let res = if svc.is_null() {+ Err(GetLastError())+ } else {+ let ok = if start {+ StartServiceW(svc, 0, null_mut())+ } else {+ let mut st: SERVICE_STATUS = std::mem::zeroed();+ ControlService(svc, SERVICE_CONTROL_STOP, &mut st)+ };+ let r = if ok != 0 { Ok(()) } else { Err(GetLastError()) };+ CloseServiceHandle(svc);+ r+ };+ CloseServiceHandle(scm);+ res+ }+}++// ---------- управление процессом ----------+fn with_proc<T>(pid: u32, access: u32, f: impl FnOnce(HANDLE) -> T) -> Option<T> {+ unsafe {+ let h = OpenProcess(access, 0, pid);+ if h.is_null() {+ return None;+ }+ let r = f(h);+ CloseHandle(h);+ Some(r)+ }+}++pub const PRIORITIES: [(&str, u32); 5] = [+ ("Низкий", IDLE_PRIORITY_CLASS),+ ("Ниже среднего", BELOW_NORMAL_PRIORITY_CLASS),+ ("Обычный", NORMAL_PRIORITY_CLASS),+ ("Выше среднего", ABOVE_NORMAL_PRIORITY_CLASS),+ ("Высокий", HIGH_PRIORITY_CLASS),+];++pub fn set_priority(pid: u32, class: u32) -> bool {+ with_proc(pid, PROCESS_SET_INFORMATION, |h| unsafe { SetPriorityClass(h, class) != 0 }).unwrap_or(false)+}++pub fn priority_name(pid: u32) -> String {+ let c = with_proc(pid, PROCESS_QUERY_LIMITED_INFORMATION, |h| unsafe { GetPriorityClass(h) }).unwrap_or(0);+ PRIORITIES.iter().find(|p| p.1 == c).map_or("—".into(), |p| p.0.into())+}++/// `half = true` — только первая половина логических ядер, иначе все.+pub fn set_affinity(pid: u32, half: bool) -> bool {+ with_proc(pid, PROCESS_SET_INFORMATION | PROCESS_QUERY_LIMITED_INFORMATION, |h| unsafe {+ let (mut pm, mut sm) = (0usize, 0usize);+ if GetProcessAffinityMask(h, &mut pm, &mut sm) == 0 {+ return false;+ }+ let cores = sm.count_ones();+ let mask = if half && cores > 1 { first_n_bits(sm, cores / 2) } else { sm };+ SetProcessAffinityMask(h, mask as u32) != 0 // shortcut: winapi 0.3 принимает 32-битную маску, > 32 ядер не поддержано+ })+ .unwrap_or(false)+}++/// Первые n установленных бит маски.+fn first_n_bits(mask: usize, n: u32) -> usize {+ let (mut out, mut left) = (0usize, n);+ for b in 0..usize::BITS {+ if left == 0 {+ break;+ }+ if mask >> b & 1 == 1 {+ out |= 1 << b;+ left -= 1;+ }+ }+ out+}++#[link(name = "shell32")]+unsafe extern "system" {+ fn IsUserAnAdmin() -> i32;+}++#[link(name = "ntdll")]+unsafe extern "system" {+ fn NtSuspendProcess(h: HANDLE) -> i32;+ fn NtResumeProcess(h: HANDLE) -> i32;+}++pub fn suspend(pid: u32, on: bool) -> bool {+ with_proc(pid, 0x0800 /*PROCESS_SUSPEND_RESUME*/, |h| unsafe {+ (if on { NtSuspendProcess(h) } else { NtResumeProcess(h) }) >= 0+ })+ .unwrap_or(false)+}++// ---------- администратор ----------+pub fn is_admin() -> bool {+ unsafe { IsUserAnAdmin() != 0 }+}++/// Запускает запланированную задачу `rtaskmgr` (её регистрирует установщик, уровень "Highest"): та же программа+/// с правами администратора и без окна UAC. false — задачи нет или она не запустилась.+pub fn run_elevated_task() -> bool {+ use std::os::windows::process::CommandExt;+ std::process::Command::new("schtasks").args(["/run", "/tn", "rtaskmgr"]).creation_flags(0x0800_0000).status().is_ok_and(|s| s.success())+}++/// Запускает себя заново с запросом UAC и аргументами `args`. true — пользователь согласился.+pub fn relaunch_as_admin(args: &str) -> bool {+ let Ok(exe) = std::env::current_exe() else { return false };+ let (verb, path, params) = (wide("runas"), wide(&exe.to_string_lossy()), wide(args));+ unsafe { winapi::um::shellapi::ShellExecuteW(null_mut(), verb.as_ptr(), path.as_ptr(), params.as_ptr(), std::ptr::null(), 1) as usize > 32 }+}++// ---------- системный диспетчер задач ----------++/// Запуск через IFEO: Windows передаёт первым аргументом путь к taskmgr.exe, дальше — его собственные аргументы+/// (например `/0 /startup` из «Параметров»). Возвращает эти аргументы; None — нас запустили напрямую.+pub fn taskmgr_args(args: &[String]) -> Option<String> {+ let first = args.first()?;+ first.to_lowercase().trim_matches('"').ends_with("taskmgr.exe").then(|| args[1..].join(" "))+}++/// Создаёт процесс под отладкой и сразу отпускает: такой запуск проходит мимо IFEO "Debugger".+/// Возвращает (дескриптор процесса, код ошибки CreateProcess).+fn spawn_past_ifeo(exe: &str, cmdline: &str) -> Result<HANDLE, u32> {+ use winapi::um::{debugapi::DebugActiveProcessStop, processthreadsapi::*, winbase::{DEBUG_ONLY_THIS_PROCESS, DebugSetProcessKillOnExit}};+ unsafe {+ let mut si: STARTUPINFOW = std::mem::zeroed();+ si.cb = std::mem::size_of::<STARTUPINFOW>() as u32;+ let mut pi: PROCESS_INFORMATION = std::mem::zeroed();+ let mut cmd = wide(cmdline);+ let ok = CreateProcessW(wide(exe).as_ptr(), cmd.as_mut_ptr(), null_mut(), null_mut(), 0, DEBUG_ONLY_THIS_PROCESS, null_mut(), null_mut(), &mut si, &mut pi);+ if ok == 0 {+ return Err(GetLastError());+ }+ DebugSetProcessKillOnExit(0); // our exit must not take it down+ DebugActiveProcessStop(pi.dwProcessId);+ CloseHandle(pi.hThread);+ Ok(pi.hProcess)+ }+}++/// Открывает настоящий диспетчер задач Windows (обходя наш собственный IFEO-перехват, иначе снова запустились бы мы).+/// Без прав администратора Taskmgr.exe не стартует (ERROR_ELEVATION_REQUIRED): тогда просим UAC для себя+/// с `--real-taskmgr` и делаем это уже оттуда; `elevate` = false не даёт этому зациклиться.+pub fn start_real_taskmgr(args: &str, elevate: bool) -> bool {+ let root = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".into());+ let exe = format!(r"{root}\System32\Taskmgr.exe");+ match spawn_past_ifeo(&exe, &format!("\"{exe}\" {args}")) {+ Ok(h) => {+ unsafe { CloseHandle(h) };+ true+ }+ Err(740) if elevate => relaunch_as_admin(&format!("--real-taskmgr {args}")),+ Err(_) => false,+ }+}++/// Включена ли тёмная тема приложений в Windows.+pub fn system_dark() -> bool {+ let (key, val) = (wide(r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"), wide("AppsUseLightTheme"));+ let (mut data, mut size) = (1u32, 4u32);+ let rc = unsafe {+ winapi::um::winreg::RegGetValueW(+ winapi::um::winreg::HKEY_CURRENT_USER,+ key.as_ptr(),+ val.as_ptr(),+ 0x10, // RRF_RT_REG_DWORD+ null_mut(),+ &mut data as *mut u32 as *mut _,+ &mut size,+ )+ };+ rc == 0 && data == 0+}++#[link(name = "dwmapi")]+unsafe extern "system" {+ fn DwmSetWindowAttribute(h: winapi::shared::windef::HWND, attr: u32, v: *const std::ffi::c_void, size: u32) -> i32;+}+++/// Тёмная/светлая рамка и заголовок окна.+pub fn set_dark_titlebar(h: winapi::shared::windef::HWND, dark: bool) {+ let v = dark as i32;+ unsafe { DwmSetWindowAttribute(h, 20 /*DWMWA_USE_IMMERSIVE_DARK_MODE*/, &v as *const i32 as *const _, 4) };+}++/// Заголовки видимых окон верхнего уровня по PID (без окон-владельцев и без пустых заголовков).+pub fn window_titles() -> HashMap<u32, String> {+ use winapi::shared::{minwindef::{BOOL, LPARAM}, windef::HWND};+ use winapi::um::winuser::{EnumWindows, GetWindow, GetWindowTextW, GetWindowThreadProcessId, IsWindowVisible, GW_OWNER};+ unsafe extern "system" fn cb(h: HWND, l: LPARAM) -> BOOL {+ unsafe {+ let map = &mut *(l as *mut HashMap<u32, String>);+ if IsWindowVisible(h) == 0 || !GetWindow(h, GW_OWNER).is_null() {+ return 1;+ }+ let mut buf = [0u16; 256];+ let n = GetWindowTextW(h, buf.as_mut_ptr(), 256);+ if n > 0 {+ let mut pid = 0u32;+ GetWindowThreadProcessId(h, &mut pid);+ map.entry(pid).or_insert_with(|| String::from_utf16_lossy(&buf[..n as usize]));+ }+ }+ 1+ }+ let mut map: HashMap<u32, String> = HashMap::new();+ unsafe { EnumWindows(Some(cb), &mut map as *mut _ as LPARAM) };+ map+}++/// Режим эффективности: низкий приоритет + энергосбережение (EcoQoS). `on = false` возвращает обычный режим.+pub fn set_efficiency(pid: u32, on: bool) -> bool {+ #[link(name = "kernel32")]+ unsafe extern "system" {+ fn SetProcessInformation(h: HANDLE, class: i32, info: *const std::ffi::c_void, size: u32) -> i32;+ }+ #[repr(C)]+ struct Throttle {+ version: u32,+ control: u32,+ state: u32,+ }+ with_proc(pid, PROCESS_SET_INFORMATION, |h| unsafe {+ let t = Throttle { version: 1, control: 1 /*EXECUTION_SPEED*/, state: on as u32 };+ let a = SetProcessInformation(h, 4 /*ProcessPowerThrottling*/, &t as *const _ as *const _, std::mem::size_of::<Throttle>() as u32) != 0;+ let b = SetPriorityClass(h, if on { IDLE_PRIORITY_CLASS } else { NORMAL_PRIORITY_CLASS }) != 0;+ a || b+ })+ .unwrap_or(false)+}++/// Локальное время: (год, месяц, день, час, минута, секунда).+pub fn local_time() -> (u16, u16, u16, u16, u16, u16) {+ unsafe {+ let mut t: winapi::um::minwinbase::SYSTEMTIME = std::mem::zeroed();+ winapi::um::sysinfoapi::GetLocalTime(&mut t);+ (t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn taskmgr_args_from_ifeo() {+ let a = |v: &[&str]| taskmgr_args(&v.iter().map(|s| s.to_string()).collect::<Vec<_>>());+ assert_eq!(a(&["C:\\WINDOWS\\system32\\taskmgr.exe", "/0", "/startup"]).as_deref(), Some("/0 /startup"));+ assert_eq!(a(&["\"C:\\Windows\\System32\\Taskmgr.exe\""]).as_deref(), Some(""));+ assert_eq!(a(&["--tray"]), None);+ assert_eq!(a(&[]), None);+ }++ #[test]+ fn debug_spawn_is_released_and_runs_to_its_end() {+ use winapi::um::{processthreadsapi::GetExitCodeProcess, synchapi::WaitForSingleObject};+ let cmd = std::env::var("ComSpec").unwrap();+ let h = spawn_past_ifeo(&cmd, &format!("\"{cmd}\" /c exit 7")).expect("spawn");+ let mut code = 0u32;+ unsafe {+ assert_eq!(WaitForSingleObject(h, 10_000), 0, "a process we did not let go would hang here");+ GetExitCodeProcess(h, &mut code);+ CloseHandle(h);+ }+ assert_eq!(code, 7);+ }+ #[test]+ fn first_bits() {+ assert_eq!(first_n_bits(0b1111_0000, 2), 0b0011_0000);+ assert_eq!(first_n_bits(0b1111, 4), 0b1111);+ }+}++/// Учётная запись, от имени которой запущен процесс: «Пользователь» или «ДОМЕН\Пользователь» для чужих.+/// Для защищённых системных процессов токен недоступен — возвращает None (вызывающий считает их системными).+pub fn process_user(pid: u32) -> Option<String> {+ use winapi::um::{processthreadsapi::OpenProcessToken, securitybaseapi::GetTokenInformation, winbase::LookupAccountSidW, winnt::{TOKEN_QUERY, TOKEN_USER}};+ with_proc(pid, PROCESS_QUERY_LIMITED_INFORMATION, |h| unsafe {+ let mut tok: HANDLE = null_mut();+ if OpenProcessToken(h, TOKEN_QUERY, &mut tok) == 0 {+ return None;+ }+ let mut buf = [0u8; 512];+ let mut need = 0u32;+ let ok = GetTokenInformation(tok, 1 /*TokenUser*/, buf.as_mut_ptr() as *mut _, buf.len() as u32, &mut need) != 0;+ CloseHandle(tok);+ if !ok {+ return None;+ }+ let sid = (*(buf.as_ptr() as *const TOKEN_USER)).User.Sid;+ let (mut nl, mut dl, mut ty) = (256u32, 256u32, 0u32);+ let (mut name, mut dom) = ([0u16; 256], [0u16; 256]);+ if LookupAccountSidW(null_mut(), sid, name.as_mut_ptr(), &mut nl, dom.as_mut_ptr(), &mut dl, &mut ty) == 0 {+ return None;+ }+ let (n, dm) = (String::from_utf16_lossy(&name[..nl as usize]), String::from_utf16_lossy(&dom[..dl as usize]));+ let local = std::env::var("COMPUTERNAME").unwrap_or_default();+ Some(if dm.is_empty() || dm.eq_ignore_ascii_case(&local) || dm.eq_ignore_ascii_case("NT AUTHORITY") { n } else { format!("{dm}\\{n}") })+ })+ .flatten()+}diff --git a/plugins/rtaskmgr-win32/src/ui.rs b/plugins/rtaskmgr-win32/src/ui.rsnew file mode 100644index 0000000..70a38f7--- /dev/null+++ b/plugins/rtaskmgr-win32/src/ui.rs@@ -0,0 +1,384 @@+//! Тема, шрифты и примитивы рисования (GDI) в стиле диспетчера задач Windows 11.+use std::ptr::null_mut;+use winapi::shared::windef::{HBRUSH, HDC, HFONT, HGDIOBJ, POINT, RECT};+use winapi::um::{wingdi::*, winuser::*};++#[derive(Clone, Copy, PartialEq, Debug)]+pub struct Rgb(pub u8, pub u8, pub u8);++impl Rgb {+ pub fn c(self) -> u32 {+ self.0 as u32 | (self.1 as u32) << 8 | (self.2 as u32) << 16+ }+ pub fn lerp(self, o: Rgb, t: f32) -> Rgb {+ let t = t.clamp(0.0, 1.0);+ let m = |a: u8, b: u8| (a as f32 + (b as f32 - a as f32) * t).round() as u8;+ Rgb(m(self.0, o.0), m(self.1, o.1), m(self.2, o.2))+ }+}++#[derive(Clone, Copy)]+pub struct Theme {+ pub dark: bool,+ pub bg: Rgb, // фон страницы и таблицы+ pub nav: Rgb, // боковая панель+ pub panel: Rgb, // плашки, поле поиска+ pub text: Rgb,+ pub dim: Rgb, // приглушённый текст+ pub border: Rgb,+ pub sel: Rgb, // выбранная строка+ pub hover: Rgb,+ pub accent: Rgb,+ pub heat0: Rgb, // «тепловая» подсветка ячеек: от малого значения+ pub heat1: Rgb, // … до большого+ pub warn: Rgb,+ pub bad: Rgb,+}++pub fn theme(dark: bool) -> Theme {+ if dark {+ Theme {+ dark,+ bg: Rgb(28, 28, 28),+ nav: Rgb(32, 32, 32),+ panel: Rgb(44, 44, 44),+ text: Rgb(255, 255, 255),+ dim: Rgb(157, 157, 157),+ border: Rgb(45, 45, 45),+ sel: Rgb(47, 47, 47),+ hover: Rgb(38, 38, 38),+ accent: Rgb(96, 205, 255),+ heat0: Rgb(14, 42, 71),+ heat1: Rgb(27, 100, 173),+ warn: Rgb(252, 225, 0),+ bad: Rgb(255, 99, 97),+ }+ } else {+ Theme {+ dark,+ bg: Rgb(249, 249, 249),+ nav: Rgb(243, 243, 243),+ panel: Rgb(255, 255, 255),+ text: Rgb(26, 26, 26),+ dim: Rgb(96, 96, 96),+ border: Rgb(225, 225, 225),+ sel: Rgb(232, 232, 232),+ hover: Rgb(238, 238, 238),+ accent: Rgb(0, 95, 184),+ heat0: Rgb(228, 240, 252),+ heat1: Rgb(104, 174, 235),+ warn: Rgb(157, 93, 0),+ bad: Rgb(196, 43, 28),+ }+ }+}++#[derive(Clone, Copy, PartialEq)]+pub struct R {+ pub l: i32,+ pub t: i32,+ pub r: i32,+ pub b: i32,+}++impl R {+ pub fn new(l: i32, t: i32, r: i32, b: i32) -> R {+ R { l, t, r, b }+ }+ pub fn w(&self) -> i32 {+ self.r - self.l+ }+ pub fn h(&self) -> i32 {+ self.b - self.t+ }+ pub fn contains(&self, x: i32, y: i32) -> bool {+ x >= self.l && x < self.r && y >= self.t && y < self.b+ }+ pub fn inset(&self, d: i32) -> R {+ R::new(self.l + d, self.t + d, self.r - d, self.b - d)+ }+ pub fn rc(&self) -> RECT {+ RECT { left: self.l, top: self.t, right: self.r, bottom: self.b }+ }+}++#[derive(Clone, Copy, PartialEq, Debug)]+pub enum Font {+ Ui, // основной текст+ Small, // мелкий+ Semibold, // заголовки колонок/разделов+ Title, // заголовок страницы+ Big, // крупные числа+ Huge, // заголовок ресурса на странице «Производительность»+ Icons, // значки (Segoe Fluent Icons)+ IconsSm,+}++pub struct Fonts {+ f: [HFONT; 8],+}++fn mk(face: &str, px: i32, weight: i32) -> HFONT {+ let w: Vec<u16> = face.encode_utf16().chain(Some(0)).collect();+ unsafe { CreateFontW(-px, 0, 0, 0, weight, 0, 0, 0, DEFAULT_CHARSET, 0, 0, CLEARTYPE_QUALITY, 0, w.as_ptr()) }+}++/// Есть ли в системе шрифт значков Windows 11.+fn icon_face() -> &'static str {+ // Segoe Fluent Icons есть в Windows 11; в Windows 10 — Segoe MDL2 Assets (те же коды символов)+ "Segoe Fluent Icons"+}++impl Fonts {+ pub fn new(s: f64) -> Fonts {+ let p = |x: f64| (x * s).round() as i32;+ Fonts {+ f: [+ mk("Segoe UI", p(13.0), 400),+ mk("Segoe UI", p(12.0), 400),+ mk("Segoe UI Semibold", p(13.0), 600),+ mk("Segoe UI Semibold", p(22.0), 600),+ mk("Segoe UI", p(20.0), 400),+ mk("Segoe UI", p(30.0), 300),+ mk(icon_face(), p(16.0), 400),+ mk(icon_face(), p(13.0), 400),+ ],+ }+ }+ pub fn get(&self, f: Font) -> HFONT {+ self.f[f as usize]+ }+}++impl Drop for Fonts {+ fn drop(&mut self) {+ for f in self.f {+ unsafe { DeleteObject(f as HGDIOBJ) };+ }+ }+}++/// Контекст рисования: DC + масштаб + тема + шрифты.+pub struct G<'a> {+ pub dc: HDC,+ pub s: f64,+ pub th: Theme,+ pub fonts: &'a Fonts,+}++impl<'a> G<'a> {+ pub fn px(&self, v: f64) -> i32 {+ (v * self.s).round() as i32+ }++ pub fn fill(&self, r: R, c: Rgb) {+ unsafe {+ let b = CreateSolidBrush(c.c());+ FillRect(self.dc, &r.rc(), b);+ DeleteObject(b as HGDIOBJ);+ }+ }++ pub fn frame(&self, r: R, c: Rgb) {+ unsafe {+ let b = CreateSolidBrush(c.c());+ FrameRect(self.dc, &r.rc(), b);+ DeleteObject(b as HGDIOBJ);+ }+ }++ pub fn hline(&self, x0: i32, x1: i32, y: i32, c: Rgb) {+ self.fill(R::new(x0, y, x1, y + 1.max(self.px(1.0) / 2)), c)+ }++ pub fn vline(&self, x: i32, y0: i32, y1: i32, c: Rgb) {+ self.fill(R::new(x, y0, x + 1.max(self.px(1.0) / 2), y1), c)+ }++ pub fn round(&self, r: R, radius: i32, fill: Option<Rgb>, border: Option<Rgb>) {+ unsafe {+ let brush: HBRUSH = match fill {+ Some(c) => CreateSolidBrush(c.c()),+ None => GetStockObject(NULL_BRUSH as i32) as HBRUSH,+ };+ let pen = match border {+ Some(c) => CreatePen(PS_SOLID as i32, 1, c.c()),+ None => GetStockObject(NULL_PEN as i32) as _,+ };+ let (ob, op) = (SelectObject(self.dc, brush as HGDIOBJ), SelectObject(self.dc, pen as HGDIOBJ));+ RoundRect(self.dc, r.l, r.t, r.r + 1, r.b + 1, radius * 2, radius * 2);+ SelectObject(self.dc, ob);+ SelectObject(self.dc, op);+ if fill.is_some() {+ DeleteObject(brush as HGDIOBJ);+ }+ if border.is_some() {+ DeleteObject(pen as HGDIOBJ);+ }+ }+ }++ /// Текст в прямоугольнике. `flags` — DT_*; по умолчанию слева, по центру по вертикали, с многоточием.+ pub fn text_in(&self, r: R, s: &str, f: Font, c: Rgb, flags: u32) {+ if s.is_empty() {+ return;+ }+ let w: Vec<u16> = s.encode_utf16().collect();+ unsafe {+ let old = SelectObject(self.dc, self.fonts.get(f) as HGDIOBJ);+ SetBkMode(self.dc, TRANSPARENT as i32);+ SetTextColor(self.dc, c.c());+ let mut rc = r.rc();+ DrawTextW(self.dc, w.as_ptr(), w.len() as i32, &mut rc, flags | DT_NOPREFIX);+ SelectObject(self.dc, old);+ }+ }++ pub fn text(&self, r: R, s: &str, f: Font, c: Rgb) {+ self.text_in(r, s, f, c, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS)+ }++ pub fn text_right(&self, r: R, s: &str, f: Font, c: Rgb) {+ self.text_in(r, s, f, c, DT_RIGHT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS)+ }++ pub fn text_center(&self, r: R, s: &str, f: Font, c: Rgb) {+ self.text_in(r, s, f, c, DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS)+ }++ /// Высота текста с переносом по словам при заданной ширине.+ pub fn wrap_h(&self, s: &str, f: Font, w: i32) -> i32 {+ let ws: Vec<u16> = s.encode_utf16().collect();+ unsafe {+ let old = SelectObject(self.dc, self.fonts.get(f) as HGDIOBJ);+ let mut rc = RECT { left: 0, top: 0, right: w.max(10), bottom: 0 };+ DrawTextW(self.dc, ws.as_ptr(), ws.len() as i32, &mut rc, DT_CALCRECT | DT_WORDBREAK | DT_NOPREFIX);+ SelectObject(self.dc, old);+ rc.bottom+ }+ }++ pub fn text_wrapped(&self, r: R, s: &str, f: Font, c: Rgb) {+ self.text_in(r, s, f, c, DT_LEFT | DT_TOP | DT_WORDBREAK);+ }++ pub fn text_w(&self, s: &str, f: Font) -> i32 {+ let w: Vec<u16> = s.encode_utf16().collect();+ unsafe {+ let old = SelectObject(self.dc, self.fonts.get(f) as HGDIOBJ);+ let mut sz = std::mem::zeroed();+ GetTextExtentPoint32W(self.dc, w.as_ptr(), w.len() as i32, &mut sz);+ SelectObject(self.dc, old);+ sz.cx+ }+ }++ /// Символ из шрифта значков по центру прямоугольника.+ pub fn glyph(&self, r: R, ch: char, c: Rgb, small: bool) {+ let mut b = [0u8; 4];+ self.text_center(r, ch.encode_utf8(&mut b), if small { Font::IconsSm } else { Font::Icons }, c);+ }++ pub fn polyline(&self, pts: &[POINT], c: Rgb, width: i32) {+ if pts.len() < 2 {+ return;+ }+ unsafe {+ let pen = CreatePen(PS_SOLID as i32, width, c.c());+ let old = SelectObject(self.dc, pen as HGDIOBJ);+ Polyline(self.dc, pts.as_ptr(), pts.len() as i32);+ SelectObject(self.dc, old);+ DeleteObject(pen as HGDIOBJ);+ }+ }++ pub fn polygon(&self, pts: &[POINT], c: Rgb) {+ if pts.len() < 3 {+ return;+ }+ unsafe {+ let brush = CreateSolidBrush(c.c());+ let (ob, op) = (SelectObject(self.dc, brush as HGDIOBJ), SelectObject(self.dc, GetStockObject(NULL_PEN as i32)));+ Polygon(self.dc, pts.as_ptr(), pts.len() as i32);+ SelectObject(self.dc, ob);+ SelectObject(self.dc, op);+ DeleteObject(brush as HGDIOBJ);+ }+ }++ pub fn icon(&self, hicon: isize, x: i32, y: i32, size: i32) {+ if hicon != 0 {+ unsafe { DrawIconEx(self.dc, x, y, hicon as _, size, size, 0, null_mut(), 3 /*DI_NORMAL*/) };+ }+ }++ pub fn clip(&self, r: R) {+ unsafe {+ let rgn = CreateRectRgn(r.l, r.t, r.r, r.b);+ SelectClipRgn(self.dc, rgn);+ DeleteObject(rgn as HGDIOBJ);+ }+ }++ pub fn unclip(&self) {+ unsafe { SelectClipRgn(self.dc, null_mut()) };+ }+}++/// Цвет «тепловой» подсветки ячейки по доле от шкалы (корень — чтобы малые значения были заметны).+pub fn heat(th: &Theme, value: f64, scale: f64) -> Rgb {+ th.heat0.lerp(th.heat1, ((value / scale).max(0.0).sqrt()) as f32)+}++/// Человекочитаемые единицы.+pub fn fmt_mem(bytes: u64) -> String {+ let mb = bytes as f64 / 1_048_576.0;+ if mb >= 1000.0 { format!("{} МБ", group_thousands(mb as u64)) } else if mb >= 100.0 { format!("{:.0} МБ", mb) } else { format!("{:.1} МБ", mb) }+}++pub fn group_thousands(n: u64) -> String {+ let s = n.to_string();+ let mut out = String::new();+ for (i, c) in s.chars().enumerate() {+ if i > 0 && (s.len() - i).is_multiple_of(3) {+ out.push(',');+ }+ out.push(c);+ }+ out+}+++++pub fn fmt_uptime(secs: u64) -> String {+ format!("{}:{:02}:{:02}:{:02}", secs / 86400, secs / 3600 % 24, secs / 60 % 60, secs % 60)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn formats() {+ assert_eq!(group_thousands(3572), "3,572");+ assert_eq!(group_thousands(12), "12");+ assert_eq!(fmt_mem(3_746_000_000), "3,572 МБ");+ assert_eq!(fmt_uptime(2 * 86400 + 18 * 3600 + 27 * 60 + 54), "2:18:27:54");+ }++ #[test]+ fn heat_is_monotonic_and_clamped() {+ let t = theme(true);+ assert_eq!(heat(&t, 0.0, 50.0), t.heat0);+ assert_eq!(heat(&t, 500.0, 50.0), t.heat1);+ let (a, b) = (heat(&t, 5.0, 50.0), heat(&t, 25.0, 50.0));+ assert!(b.2 > a.2);+ }++ #[test]+ fn lerp_endpoints() {+ assert_eq!(Rgb(0, 0, 0).lerp(Rgb(100, 200, 50), 0.0), Rgb(0, 0, 0));+ assert_eq!(Rgb(0, 0, 0).lerp(Rgb(100, 200, 50), 1.0), Rgb(100, 200, 50));+ }+}diff --git a/plugins/rust-explorer/Cargo.lock b/plugins/rust-explorer/Cargo.locknew file mode 100644index 0000000..86aa1e7--- /dev/null+++ b/plugins/rust-explorer/Cargo.lock@@ -0,0 +1,373 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "cc"+version = "1.11.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45"+dependencies = [+ "find-msvc-tools",+ "shlex",+]++[[package]]+name = "cfg-if"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"++[[package]]+name = "embed-resource"+version = "3.0.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6168487b5e7eb2673e6efe1200b1848016e436a6ca0b8031bf04bd9d493a249f"+dependencies = [+ "cc",+ "memchr",+ "rustc_version",+ "toml",+ "vswhom",+ "winreg",+]++[[package]]+name = "equivalent"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"++[[package]]+name = "find-msvc-tools"+version = "0.1.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"++[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"++[[package]]+name = "indexmap"+version = "2.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"+dependencies = [+ "equivalent",+ "hashbrown",+]++[[package]]+name = "libc"+version = "0.2.191"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "proc-macro2"+version = "1.0.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "rust-explorer"+version = "0.1.0"+dependencies = [+ "embed-resource",+ "windows",+ "windows-core",+ "windows-sys",+]++[[package]]+name = "rustc_version"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"+dependencies = [+ "semver",+]++[[package]]+name = "semver"+version = "1.0.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"++[[package]]+name = "serde_core"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "serde_spanned"+version = "1.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"+dependencies = [+ "serde_core",+]++[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"++[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "syn"+version = "3.0.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "toml"+version = "1.2.1+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7"+dependencies = [+ "indexmap",+ "serde_core",+ "serde_spanned",+ "toml_datetime",+ "toml_parser",+ "toml_writer",+ "winnow",+]++[[package]]+name = "toml_datetime"+version = "1.1.3+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"+dependencies = [+ "serde_core",+]++[[package]]+name = "toml_parser"+version = "1.1.5+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"+dependencies = [+ "winnow",+]++[[package]]+name = "toml_writer"+version = "1.2.0+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"++[[package]]+name = "unicode-ident"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"++[[package]]+name = "vswhom"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b"+dependencies = [+ "libc",+ "vswhom-sys",+]++[[package]]+name = "vswhom-sys"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150"+dependencies = [+ "cc",+ "libc",+]++[[package]]+name = "windows"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"+dependencies = [+ "windows-collections",+ "windows-core",+ "windows-future",+ "windows-numerics",+]++[[package]]+name = "windows-collections"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"+dependencies = [+ "windows-core",+]++[[package]]+name = "windows-core"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-link",+ "windows-result",+ "windows-strings",+]++[[package]]+name = "windows-future"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"+dependencies = [+ "windows-core",+ "windows-link",+ "windows-threading",+]++[[package]]+name = "windows-implement"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-interface"+version = "0.59.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-numerics"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"+dependencies = [+ "windows-core",+ "windows-link",+]++[[package]]+name = "windows-result"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-strings"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-threading"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"+dependencies = [+ "windows-link",+]++[[package]]+name = "winnow"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"++[[package]]+name = "winreg"+version = "0.56.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10"+dependencies = [+ "cfg-if",+ "windows-sys",+]diff --git a/plugins/rust-explorer/Cargo.toml b/plugins/rust-explorer/Cargo.tomlnew file mode 100644index 0000000..b4bc99d--- /dev/null+++ b/plugins/rust-explorer/Cargo.toml@@ -0,0 +1,19 @@+[package]+name = "rust-explorer"+version = "0.1.0"+edition = "2024"++[dependencies]+windows = { version = "0.62.2", features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_System_Com_StructuredStorage", "Win32_System_DataExchange", "Win32_System_Memory", "Win32_System_Ole", "Win32_System_SystemServices", "Win32_UI_Shell", "Win32_UI_Shell_Common", "Win32_UI_WindowsAndMessaging", "Win32_System_Com"] }+windows-core = "0.62"+windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_Storage_FileSystem", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_Time", "Win32_System_SystemInformation", "Win32_Graphics_Dwm", "Win32_Graphics_GdiPlus", "Win32_UI_Controls", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] }++[build-dependencies]+embed-resource = "3"++[profile.release]+opt-level = "s"+lto = true+panic = "abort"+codegen-units = 1+strip = truediff --git a/plugins/rust-explorer/app.manifest b/plugins/rust-explorer/app.manifestnew file mode 100644index 0000000..36f87e2--- /dev/null+++ b/plugins/rust-explorer/app.manifest@@ -0,0 +1,16 @@+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">+ <!-- visual styles for the list and header (without this they stay in the flat classic look and cannot be themed dark) -->+ <dependency><dependentAssembly>+ <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*"/>+ </dependentAssembly></dependency>+ <application xmlns="urn:schemas-microsoft-com:asm.v3">+ <windowsSettings>+ <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>+ <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>+ </windowsSettings>+ </application>+ <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">+ <application><supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/></application>+ </compatibility>+</assembly>diff --git a/plugins/rust-explorer/app.rc b/plugins/rust-explorer/app.rcnew file mode 100644index 0000000..8142754--- /dev/null+++ b/plugins/rust-explorer/app.rc@@ -0,0 +1 @@+1 24 "app.manifest"diff --git a/plugins/rust-explorer/build.rs b/plugins/rust-explorer/build.rsnew file mode 100644index 0000000..b0af67a--- /dev/null+++ b/plugins/rust-explorer/build.rs@@ -0,0 +1,5 @@+fn main() {+ println!("cargo:rerun-if-changed=app.rc");+ println!("cargo:rerun-if-changed=app.manifest");+ embed_resource::compile("app.rc", embed_resource::NONE).manifest_required().unwrap();+}diff --git a/plugins/rust-explorer/src/main.rs b/plugins/rust-explorer/src/main.rsnew file mode 100644index 0000000..2e21c3e--- /dev/null+++ b/plugins/rust-explorer/src/main.rs@@ -0,0 +1,1316 @@+// rust-explorer [path] — file manager window (Explorer replacement).+// Virtual list (LVS_OWNERDATA, only visible rows are asked for text/icon), system icons, tabs,+// IFileOperation (recycle bin / undo / elevation prompts), real shell context menu with submenus, OLE drag and drop.+// Keys: Enter open, Backspace up, F2 rename, Del recycle, Ctrl+C/X/V copy/cut/paste, Ctrl+N new folder,+// Ctrl+T/W/Tab tabs, Ctrl+M thumbnails, Ctrl+L/F4 address bar, Ctrl+F or "? terms" in the bar = instant search through the rs service, right click / Menu key = shell context menu.+// Look: topbar's palette, painted tabs / toolbar / address pill and status line (src/ui.rs), dark title bar and list.+// Clipboard is the system one (Ctrl+C/X/V interoperate with Explorer). Also: Alt+Left/Right back/forward, Alt+Up up,+// Alt+Enter properties, F5 refresh, Ctrl+H hidden files, click a column header to sort, right click on empty space = folder menu.+// shortcuts: std::fs listing (not FindFirstFileEx large fetch), icons are extension-based (exe/lnk/ico/url/scr+// per file) and synchronous (thumbnails: one background thread, 96px, no disk cache), internal copy/cut clipboard, silent rename errors,+// search blocks the UI while it waits for the service (no async), the service pipe is admin-only so run as admin,+// drops always land in the current folder (not on a folder row), tabs remember only the folder (no selection/scroll).+// upgrade: each of those one at a time; then register as the folder-open handler.+// rust-explorer --desktop - the desktop for rs-shell: borderless bottom-most color-keyed window with the Desktop folders+// (user + public) as big icons over the wallpaper it paints itself (without explorer nothing else does): reads the BMP+// that rs-shell converts into %LOCALAPPDATA%\rs-shell\wallpaper.bmp, "fill" style, scaled once at start.+// shortcuts: wallpaper is loaded once (changing it needs a restart), icon labels are always white, no background menu /+// drag-to-position / auto-arrange, items from the public desktop can't be renamed.+#![windows_subsystem = "windows"]+use std::{cell::RefCell, env, fs, os::windows::fs::MetadataExt, path::{Path, PathBuf}, ptr, sync::atomic::{AtomicBool, AtomicUsize, Ordering::Relaxed}};+use windows_sys::Win32::{Foundation::*, Graphics::Gdi::{BLACK_BRUSH, GetStockObject, InvalidateRect}, System::LibraryLoader::GetModuleHandleW, UI::{Controls::*, Input::KeyboardAndMouse::{GetKeyState, SetFocus, VK_CONTROL}, Shell::*, WindowsAndMessaging::*}};++mod ui; // the look: palette, painted tabs / toolbar / address pill / status line, dark theme++static DESKTOP: AtomicBool = AtomicBool::new(false);+fn desk() -> bool { DESKTOP.load(Relaxed) }+const CLR_NONE: isize = 0xFFFF_FFFF; // list background / text background: let the parent's wallpaper show through+thread_local! { static WALL: std::cell::Cell<(isize, i32, i32)> = const { std::cell::Cell::new((0, 0, 0)) }; } // (HBITMAP, w, h)+/// Margins of the desktop's icon list: the bar sits at the bottom. shortcut: assumes the bar is at most 44 px (scaled); it may not reserve the work area.+fn desk_top() -> i32 { ui::sc(8) }+fn desk_bottom() -> i32 { ui::sc(44) }+const THUMB: i32 = 96;+const WM_THUMB: u32 = WM_APP + 2; // worker -> UI: wp = Box<(era, row, HBITMAP)>+static GEN: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); // bumped on every new listing; stale thumbnails are dropped+static TX: std::sync::OnceLock<std::sync::mpsc::Sender<(u32, usize, PathBuf)>> = std::sync::OnceLock::new();+const WM_GO: u32 = WM_APP + 1; // address bar: Enter (wp 13) / Esc (wp 27)+static EDIT_OLD: std::sync::atomic::AtomicIsize = std::sync::atomic::AtomicIsize::new(0);++struct Row { name: String, dir: bool, size: u64, time: u64, icon: i32, thumb: i32 } // time: FILETIME ticks; thumb: -2 not asked, -1 asked, >=0 image-list index++/// Back / forward trail of visited folders (one for the whole window, not per tab).+#[derive(Default)]+struct Hist { v: Vec<PathBuf>, pos: usize }+impl Hist {+ fn visit(&mut self, p: PathBuf) {+ if self.v.get(self.pos) == Some(&p) { return; }+ self.v.truncate(self.pos + usize::from(!self.v.is_empty())); // a new visit drops the forward trail+ self.v.push(p);+ self.pos = self.v.len() - 1;+ }+ fn back(&mut self) -> Option<PathBuf> { if self.pos > 0 { self.pos -= 1; Some(self.v[self.pos].clone()) } else { None } }+ fn forward(&mut self) -> Option<PathBuf> { if self.pos + 1 < self.v.len() { self.pos += 1; Some(self.v[self.pos].clone()) } else { None } }+}++struct State { list: HWND, tab: HWND, edit: HWND, dir: PathBuf, rows: Vec<Row>, thumbs: bool, himl: isize, tabs: Vec<PathBuf>, active: usize, hist: Hist }+thread_local! {+ static ST: RefCell<State> = RefCell::new(State { list: 0 as _, tab: 0 as _, edit: 0 as _, dir: PathBuf::new(), rows: vec![], thumbs: false, himl: 0, tabs: vec![], active: 0, hist: Hist { v: vec![], pos: 0 } });+}+static SORT_COL: AtomicUsize = AtomicUsize::new(0); // 0 name, 1 size, 2 modified+static SORT_ASC: AtomicBool = AtomicBool::new(true);+static SHOW_HIDDEN: AtomicBool = AtomicBool::new(false); // Ctrl+H+static NAV: AtomicBool = AtomicBool::new(false); // loading from the back / forward trail: do not record it again+const WM_NAV: u32 = WM_APP + 3; // wp: 1 back, 2 forward, 3 properties, 4 up (sent from the message loop for Alt+key)++fn row(name: String, m: Option<&fs::Metadata>) -> Row {+ Row { name, dir: m.is_some_and(|m| m.is_dir()), size: m.map_or(0, |m| m.len()), time: m.map_or(0, |m| m.last_write_time()), icon: -1, thumb: -2 }+}++/// Folders always first; inside each group by the column (0 name, 1 size, 2 modified), ties by name.+fn sort_rows(rows: &mut [Row], col: usize, asc: bool) {+ let key = |r: &Row| r.name.rsplit('\\').next().unwrap_or("").to_lowercase();+ rows.sort_by(|a, b| {+ let o = match col { 1 => a.time.cmp(&b.time), 2 => type_text(&a.name, a.dir).cmp(&type_text(&b.name, b.dir)), 3 => a.size.cmp(&b.size), _ => key(a).cmp(&key(b)) };+ (!a.dir).cmp(&!b.dir).then(if asc { o } else { o.reverse() }).then_with(|| key(a).cmp(&key(b)))+ });+}++/// Explorer's "Type" column in short form: "File folder", "TXT file", "File".+fn type_text(name: &str, dir: bool) -> String {+ if dir { return "File folder".into(); }+ let file = name.rsplit('\\').next().unwrap_or(name);+ match file.rsplit_once('.') { Some((stem, e)) if !stem.is_empty() && !e.is_empty() => format!("{} file", e.to_uppercase()), _ => "File".into() }+}++/// Explorer shows file sizes in KB; the bigger ones read better in MB / GB.+fn size_text(b: u64) -> String {+ const MB: u64 = 1 << 20;+ if b < MB { format!("{} KB", b.div_ceil(1024)) } else if b < 1 << 30 { format!("{:.1} MB", b as f64 / MB as f64) } else { format!("{:.2} GB", b as f64 / (1u64 << 30) as f64) }+}++fn date_text(ft: u64) -> String {+ use windows_sys::Win32::{Foundation::{FILETIME, SYSTEMTIME}, System::Time::{FileTimeToSystemTime, SystemTimeToTzSpecificLocalTime}};+ if ft == 0 { return String::new(); }+ unsafe {+ let f = FILETIME { dwLowDateTime: ft as u32, dwHighDateTime: (ft >> 32) as u32 };+ let (mut u, mut l): (SYSTEMTIME, SYSTEMTIME) = (std::mem::zeroed(), std::mem::zeroed());+ if FileTimeToSystemTime(&f, &mut u) == 0 || SystemTimeToTzSpecificLocalTime(ptr::null(), &u, &mut l) == 0 { return String::new(); }+ format!("{:04}-{:02}-{:02} {:02}:{:02}", l.wYear, l.wMonth, l.wDay, l.wHour, l.wMinute)+ }+}++/// Our own tools installed by the launcher (photoview, wiztree): the exe in Program Files, None when not installed.+fn tool(name: &str) -> Option<PathBuf> {+ let p = PathBuf::from(env::var_os("ProgramFiles")?).join(name).join(format!("{name}.exe"));+ p.is_file().then_some(p)+}++/// Same list as photoview's EXTS.+fn is_pic(p: &std::path::Path) -> bool {+ p.extension().and_then(|e| e.to_str()).is_some_and(|e| ["jpg", "jpeg", "jfif", "png", "bmp", "gif", "tif", "tiff", "webp", "heic", "avif"].contains(&e.to_ascii_lowercase().as_str()))+}++fn properties(path: &PathBuf) {+ let (f, v) = (w(&path.to_string_lossy()), w("properties"));+ let mut sei: SHELLEXECUTEINFOW = unsafe { std::mem::zeroed() };+ sei.cbSize = size_of::<SHELLEXECUTEINFOW>() as u32;+ sei.fMask = 0x0C; // SEE_MASK_INVOKEIDLIST+ sei.lpVerb = v.as_ptr(); sei.lpFile = f.as_ptr(); sei.nShow = SW_SHOW;+ unsafe { ShellExecuteExW(&mut sei) };+}++/// New folder / new empty file with a free name ("New folder", "New folder (2)", ...).+fn new_entry(dir: &PathBuf, base: &str, folder: bool) {+ let (stem, ext) = match base.rsplit_once('.') { Some((s, e)) if !folder => (s.to_string(), format!(".{e}")), _ => (base.to_string(), String::new()) };+ let path = (1..).map(|n| dir.join(if n == 1 { base.to_string() } else { format!("{stem} ({n}){ext}") })).find(|p| !p.exists());+ if let Some(p) = path { let _ = if folder { fs::create_dir(p) } else { fs::File::create(p).map(drop) }; }+}++/// Pastes what is on the system clipboard (files copied or cut here or in any other file manager).+fn paste(h: HWND, dir: &PathBuf) {+ let Some((paths, cut)) = sh::clip_get() else { return };+ let _ = sh::fileop(h, if cut { sh::Op::Move } else { sh::Op::Copy }, &paths, dir);+ if cut { sh::clip_clear(); }+}++/// Right click on empty space: the folder's own menu.+#[allow(unsafe_op_in_unsafe_fn)]+unsafe fn bg_menu(h: HWND) {+ let m = CreatePopupMenu();+ for (id, t) in [(1usize, "New folder"), (2, "New text file"), (3, "Paste"), (4, "Refresh"), (5, "Properties")] { AppendMenuW(m, MF_STRING, id, w(t).as_ptr()); }+ let disk = tool("wiztree");+ if disk.is_some() { AppendMenuW(m, MF_STRING, 6, w("Disk usage (WinRust Disk)").as_ptr()); }+ let mut pt: POINT = std::mem::zeroed();+ GetCursorPos(&mut pt);+ let id = TrackPopupMenu(m, TPM_RETURNCMD | TPM_RIGHTBUTTON, pt.x, pt.y, 0, h, ptr::null());+ DestroyMenu(m);+ let dir = cur_dir();+ match id {+ 6 => { // wiztree takes the drive letter and asks for admin rights itself+ let drive: String = dir.to_string_lossy().chars().take(2).collect();+ if let Some(exe) = disk { let _ = std::process::Command::new(exe).arg(drive).spawn(); }+ }+ 1 => new_entry(&dir, "New folder", true),+ 2 => new_entry(&dir, "New text document.txt", false),+ 3 => paste(h, &dir),+ 5 => properties(&dir),+ _ => {}+ }+ if id != 0 { reload(h); }+}++/// Back / forward along the visited-folder trail.+fn nav(h: HWND, back: bool) {+ let to = ST.with_borrow_mut(|st| if back { st.hist.back() } else { st.hist.forward() });+ if let Some(p) = to {+ NAV.store(true, Relaxed);+ load(h, p);+ NAV.store(false, Relaxed);+ }+}++fn w(s: &str) -> Vec<u16> { s.encode_utf16().chain([0]).collect() }++fn put(h: HWND, msg: u32, wp: usize, lp: isize) -> isize { unsafe { SendMessageW(h, msg, wp, lp) } }++fn wstr(p: *const u16) -> String {+ let mut n = 0;+ while unsafe { *p.add(n) } != 0 { n += 1; }+ String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(p, n) })+}++pub fn cur_dir() -> PathBuf { ST.with_borrow(|st| st.dir.clone()) }++/// System image-list index. Extension-based (no disk access) except for files that carry their own icon.+fn icon_of(p: &PathBuf, dir: bool) -> i32 {+ let ext = p.extension().map(|e| e.to_string_lossy().to_lowercase()).unwrap_or_default();+ let own = !dir && matches!(ext.as_str(), "exe" | "lnk" | "ico" | "url" | "scr");+ let mut fi: SHFILEINFOW = unsafe { std::mem::zeroed() };+ let attr = if dir { 0x10 } else { 0x80 }; // DIRECTORY / NORMAL+ let flags = SHGFI_SYSICONINDEX | SHGFI_SMALLICON | if own { 0 } else { SHGFI_USEFILEATTRIBUTES };+ unsafe { SHGetFileInfoW(w(&p.to_string_lossy()).as_ptr(), attr, &mut fi, size_of::<SHFILEINFOW>() as u32, flags) };+ fi.iIcon+}++/// The tabs are painted by the chrome window from State.tabs: "setting a tab's text" is just a repaint.+fn tab_text(tab: HWND, _i: usize, _text: &str, _insert: bool) {+ if !tab.is_null() { unsafe { InvalidateRect(tab, ptr::null(), 0) }; }+}++fn label(dir: &PathBuf) -> String {+ dir.file_name().map_or_else(|| dir.to_string_lossy().into_owned(), |n| n.to_string_lossy().into_owned())+}++/// Rows of `dir`, folders first. Desktop mode merges the public desktop (absolute names) and hides hidden files.+/// None = `dir` itself is unreadable.+fn rows_of(dir: &PathBuf) -> Option<Vec<Row>> {+ let mut dirs = vec![dir.clone()];+ if desk() { dirs.extend(sh::desktop_dirs().into_iter().skip(1)); }+ let mut rows = vec![];+ for (n, d) in dirs.iter().enumerate() {+ let Ok(rd) = fs::read_dir(d) else { if n == 0 { return None } else { continue } };+ for e in rd.flatten() {+ let m = e.metadata().ok();+ if (desk() || !SHOW_HIDDEN.load(Relaxed)) && m.as_ref().is_some_and(|m| m.file_attributes() & 2 != 0) { continue; } // FILE_ATTRIBUTE_HIDDEN+ let name = if n == 0 { e.file_name().to_string_lossy().into_owned() } else { e.path().to_string_lossy().into_owned() };+ rows.push(row(name, m.as_ref()));+ }+ }+ sort_rows(&mut rows, SORT_COL.load(Relaxed), SORT_ASC.load(Relaxed));+ Some(rows)+}++/// Loads `dir` into the virtual list and the active tab. Unreadable dir (access denied, gone) leaves the view unchanged.+/// Never call with ST borrowed: the list sends GETDISPINFO back into the window proc.+fn load(h: HWND, dir: PathBuf) {+ let Some(rows) = rows_of(&dir) else { return };+ if !desk() { unsafe { SetWindowTextW(h, w(&dir.to_string_lossy()).as_ptr()) }; }+ let (list, tab, edit, active, n) = ST.with_borrow_mut(|st| {+ if let Some(t) = st.tabs.get_mut(st.active) { *t = dir.clone(); }+ st.dir = dir.clone(); st.rows = rows;+ if !NAV.load(Relaxed) { st.hist.visit(dir.clone()); }+ (st.list, st.tab, st.edit, st.active, st.rows.len())+ });+ unsafe { SetWindowTextW(edit, w(&dir.to_string_lossy()).as_ptr()) };+ ui::set_search(None); // a folder again: the pill shows its path+ tab_text(tab, active, &label(&dir), false);+ ui::nav_dirty(); // the pane highlights where we are+ reset_thumbs();+ put(list, LVM_DELETEALLITEMS, 0, 0);+ if desk() { desk::fill(list, n); } else { put(list, LVM_SETITEMCOUNT, n, 0); }+}++/// Asks the rust-search service of drive `d` (see plugins/rust-search): terms in, one path per line out.+/// None = no service for that drive or no access (its pipe is admin-only unless started with --allow).+fn ask(d: char, q: &str) -> Option<String> {+ use std::{fs::OpenOptions, io::{Read, Write}};+ let mut p = OpenOptions::new().read(true).write(true).open(format!(r"\\.\pipe\rs-search-{d}")).ok()?;+ p.write_all(q.as_bytes()).ok()?;+ let (mut out, mut chunk) = (Vec::new(), [0u8; 1 << 16]);+ // the server ends its reply by hanging up, which surfaces as a read error: treat any error as EOF+ while let Ok(n @ 1..) = p.read(&mut chunk) { out.extend_from_slice(&chunk[..n]); }+ Some(String::from_utf8_lossy(&out).into_owned())+}++/// Fills the list with search hits from every drive's service. Rows hold absolute paths, so joining them+/// onto the current dir still yields the right file. Blocks the UI for the duration of the query (fast).+/// Never call with ST borrowed.+fn search(h: HWND, q: &str) {+ let mut rows = vec![];+ let mut more = String::new();+ let mut indexed = false; // some drive had a rust-search service+ for d in 'A'..='Z' {+ let Some(reply) = ask(d, q) else { continue };+ indexed = true;+ for line in reply.lines() {+ if line.starts_with("... ") { more = format!(", {}", line.trim_start_matches("... ")); continue; }+ let m = fs::metadata(line).ok();+ rows.push(row(line.to_string(), m.as_ref()));+ }+ }+ if !indexed {+ // no rust-search installed: look through the current folder and below instead+ let (local, cut, flipped) = local_search(&cur_dir(), q);+ if flipped { more = format!(" for \u{201C}{}\u{201D}", flip_layout(q)); } // typed in the wrong layout: shown what was meant+ rows = local;+ if cut { more += ", stopped early: narrow the search"; }+ }+ let n = rows.len();+ let where_ = if indexed { "" } else { " in this folder" };+ let title = if n == 0 { format!("search: {q} - nothing{where_}") } else { format!("search: {q} - {n} hits{where_}{more}") };+ ui::set_search(Some(q.to_string()));+ unsafe { SetWindowTextW(h, w(&title).as_ptr()) };+ let list = ST.with_borrow_mut(|st| { st.rows = rows; st.list });+ reset_thumbs();+ put(list, LVM_DELETEALLITEMS, 0, 0);+ put(list, LVM_SETITEMCOUNT, n, 0);+}++/// The same keys typed in the other layout (QWERTY <-> ЙЦУКЕН): "сфкпщ" -> "cargo", "ljrevtyns" -> "документы".+fn flip_layout(q: &str) -> String {+ let en: Vec<char> = "qwertyuiop[]asdfghjkl;'zxcvbnm,.`QWERTYUIOP{}ASDFGHJKL:\"ZXCVBNM<>~".chars().collect();+ let ru: Vec<char> = "йцукенгшщзхъфывапролджэячсмитьбюёЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮЁ".chars().collect();+ q.chars().map(|c| en.iter().position(|&x| x == c).map(|i| ru[i]).or_else(|| ru.iter().position(|&x| x == c).map(|i| en[i])).unwrap_or(c)).collect()+}++/// Files and folders under `dir` whose name contains `q` (any case), as rows with absolute names. Walks breadth-first and+/// stops after LOCAL_MAX hits or LOCAL_MS so a search from C:\ cannot hang the window. The same walk also matches `q` typed+/// in the other keyboard layout; those hits are used only when `q` itself found nothing.+/// Returns (rows, stopped early, rows are for the other layout).+/// shortcut: blocks the UI while it walks (up to LOCAL_MS); move to a thread if deeper searches are wanted.+fn local_search(dir: &Path, q: &str) -> (Vec<Row>, bool, bool) {+ const LOCAL_MAX: usize = 500;+ const LOCAL_MS: u128 = 1500;+ let (q, t0) = (q.to_lowercase(), std::time::Instant::now());+ let alt = flip_layout(&q);+ let (mut out, mut other, mut queue) = (vec![], vec![], std::collections::VecDeque::from([dir.to_path_buf()]));+ let mut cut = false;+ 'walk: while let Some(d) = queue.pop_front() {+ for e in fs::read_dir(&d).into_iter().flatten().flatten() {+ if out.len() >= LOCAL_MAX || t0.elapsed().as_millis() > LOCAL_MS { cut = true; break 'walk; }+ let Ok(ft) = e.file_type() else { continue };+ if ft.is_dir() && !ft.is_symlink() { queue.push_back(e.path()); } // no junction loops+ let name = e.file_name().to_string_lossy().to_lowercase();+ let hit = |v: &mut Vec<Row>| v.push(row(e.path().to_string_lossy().into_owned(), e.metadata().ok().as_ref()));+ if name.contains(&q) { hit(&mut out); } else if alt != q && other.len() < LOCAL_MAX && name.contains(&alt) { hit(&mut other); }+ }+ }+ if out.is_empty() && !other.is_empty() { (other, cut, true) } else { (out, cut, false) }+}++/// Drops all thumbnails and invalidates in-flight ones; call whenever the rows are replaced.+fn reset_thumbs() {+ GEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+ let himl = ST.with_borrow(|st| st.himl);+ unsafe { ImageList_Remove(himl as _, -1) };+}++fn reload(h: HWND) { load(h, cur_dir()); }++/// (list, current dir, full paths of the selected rows)+fn selected() -> (HWND, PathBuf, Vec<PathBuf>) {+ ST.with_borrow(|st| {+ let (mut sel, mut i) = (vec![], -1isize);+ loop {+ i = put(st.list, LVM_GETNEXTITEM, i as usize, LVNI_SELECTED as isize);+ let Some(r) = usize::try_from(i).ok().and_then(|i| st.rows.get(i)) else { break };+ sel.push(st.dir.join(&r.name));+ }+ (st.list, st.dir.clone(), sel)+ })+}++fn col(list: HWND, i: i32, text: &str, width: i32, right: bool) {+ let mut t = w(text);+ let mut c: LVCOLUMNW = unsafe { std::mem::zeroed() };+ c.mask = LVCF_TEXT | LVCF_WIDTH | LVCF_FMT; c.pszText = t.as_mut_ptr(); c.cx = width;+ c.fmt = if right { LVCFMT_RIGHT } else { LVCFMT_LEFT };+ put(list, LVM_INSERTCOLUMNW, i as usize, &c as *const _ as isize);+}++/// Opens a new tab on the current folder.+fn tab_new() {+ let tab = ST.with_borrow_mut(|st| { st.tabs.push(st.dir.clone()); st.active = st.tabs.len() - 1; st.tab });+ tab_text(tab, 0, "", true);+}++fn tab_select(h: HWND, i: usize) {+ let dir = ST.with_borrow_mut(|st| { st.active = i; st.tabs[i].clone() });+ load(h, dir);+}++fn tab_close(h: HWND) { let a = ST.with_borrow(|st| st.active); tab_close_at(h, a); }++/// Closes tab `i` (the last one stays). The listing changes only when the active tab was the one closed.+fn tab_close_at(h: HWND, i: usize) {+ let (tab, was_active) = ST.with_borrow_mut(|st| {+ if st.tabs.len() < 2 || i >= st.tabs.len() { return (st.tab, None); }+ st.tabs.remove(i);+ let before = st.active;+ st.active = if i < before { before - 1 } else { before.min(st.tabs.len() - 1) };+ (st.tab, Some(i == before))+ });+ match was_active {+ Some(true) => { let a = ST.with_borrow(|st| st.active); tab_select(h, a); }+ Some(false) => tab_text(tab, 0, "", false),+ None => {}+ }+}++fn toggle_view(h: HWND) {+ let (list, on) = ST.with_borrow_mut(|st| { st.thumbs = !st.thumbs; (st.list, st.thumbs) });+ ui::row_height(list, !on);+ put(list, LVM_SETVIEW, if on { LV_VIEW_ICON } else { LV_VIEW_DETAILS } as usize, 0);+ reload(h);+}++/// Address box in search mode ("? terms").+fn search_focus() {+ let edit = ST.with_borrow(|st| st.edit);+ unsafe {+ SetWindowTextW(edit, w("? ").as_ptr());+ SetFocus(edit);+ }+ put(edit, EM_SETSEL, 2, 2);+}++/// Wallpaper for the desktop window.+mod wall {+ use windows_sys::Win32::{Graphics::Gdi::*, UI::WindowsAndMessaging::{IMAGE_BITMAP, LR_LOADFROMFILE, LoadImageW}};++ /// The BMP scaled ("fill": cropped to the screen's aspect) to cw x ch. 0 = no wallpaper file.+ pub fn load(cw: i32, ch: i32) -> isize {+ let Ok(base) = std::env::var("LOCALAPPDATA") else { return 0 };+ let path: Vec<u16> = format!(r"{base}\rs-shell\wallpaper.bmp").encode_utf16().chain([0]).collect();+ unsafe {+ let src = LoadImageW(std::ptr::null_mut(), path.as_ptr(), IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);+ if src.is_null() { return 0; }+ let mut bm: BITMAP = std::mem::zeroed();+ GetObjectW(src, size_of::<BITMAP>() as i32, &mut bm as *mut _ as _);+ let screen = GetDC(std::ptr::null_mut());+ let dst = CreateCompatibleBitmap(screen, cw, ch);+ let (sdc, ddc) = (CreateCompatibleDC(screen), CreateCompatibleDC(screen));+ let (o1, o2) = (SelectObject(sdc, src), SelectObject(ddc, dst));+ SetStretchBltMode(ddc, HALFTONE);+ let (sw, sh) = if bm.bmWidth * ch > bm.bmHeight * cw { (bm.bmHeight * cw / ch, bm.bmHeight) } else { (bm.bmWidth, bm.bmWidth * ch / cw) };+ StretchBlt(ddc, 0, 0, cw, ch, sdc, (bm.bmWidth - sw) / 2, (bm.bmHeight - sh) / 2, sw, sh, SRCCOPY);+ SelectObject(sdc, o1); SelectObject(ddc, o2);+ DeleteDC(sdc); DeleteDC(ddc); ReleaseDC(std::ptr::null_mut(), screen); DeleteObject(src);+ dst as isize+ }+ }++ pub fn paint(dc: HDC, bmp: isize, cw: i32, ch: i32) {+ unsafe {+ let m = CreateCompatibleDC(dc);+ let old = SelectObject(m, bmp as _);+ BitBlt(dc, 0, 0, cw, ch, m, 0, 0, SRCCOPY);+ SelectObject(m, old);+ DeleteDC(m);+ }+ }+}++/// Shell integration through COM (windows crate): file operations, context menu, drag and drop.+mod sh {+ use std::{cell::RefCell, ffi::c_void, os::windows::ffi::OsStrExt, path::PathBuf};+ use windows::{core::*, Win32::{Foundation::*, System::{Com::*, DataExchange::RegisterClipboardFormatW, Memory::{GMEM_MOVEABLE, GlobalAlloc, GlobalLock, GlobalUnlock}, Ole::*, SystemServices::MODIFIERKEYS_FLAGS}, UI::{Shell::{Common::ITEMIDLIST, *}, WindowsAndMessaging::*}}};++ #[derive(Clone, Copy)]+ pub enum Op { Copy, Move, Delete }++ /// [user Desktop, public Desktop] (the user one may be redirected, e.g. to OneDrive).+ pub fn desktop_dirs() -> Vec<PathBuf> {+ [&FOLDERID_Desktop, &FOLDERID_PublicDesktop].iter().filter_map(|id| unsafe {+ let p = SHGetKnownFolderPath(*id, KF_FLAG_DEFAULT, None).ok()?;+ let s = p.to_string().ok();+ CoTaskMemFree(Some(p.0 as *const c_void));+ s.map(PathBuf::from)+ }).collect()+ }++ pub fn init() { unsafe { let _ = OleInitialize(None); } }++ fn wide(p: &PathBuf) -> Vec<u16> { p.as_os_str().encode_wide().chain([0]).collect() }++ /// Copy / move into `to`, or recycle. Must not be called while ST is borrowed (the shell pumps messages).+ pub fn fileop(h: *mut c_void, op: Op, from: &[PathBuf], to: &PathBuf) -> Result<()> {+ unsafe {+ let fo: IFileOperation = CoCreateInstance(&FileOperation, None, CLSCTX_ALL)?;+ fo.SetOwnerWindow(HWND(h))?;+ fo.SetOperationFlags(if matches!(op, Op::Delete) { FOF_ALLOWUNDO } else { FOF_RENAMEONCOLLISION })?;+ let item = |p: &PathBuf| SHCreateItemFromParsingName::<_, _, IShellItem>(PCWSTR(wide(p).as_ptr()), None);+ let dest = if matches!(op, Op::Delete) { None } else { Some(item(to)?) };+ for p in from {+ let it = item(p)?;+ match (op, &dest) {+ (Op::Copy, Some(d)) => fo.CopyItem(&it, d, PCWSTR::null(), None)?,+ (Op::Move, Some(d)) => fo.MoveItem(&it, d, PCWSTR::null(), None)?,+ _ => fo.DeleteItem(&it, None)?,+ }+ }+ fo.PerformOperations()+ }+ }++ /// Background thumbnail loader: GetImage for each (era, row, path) asked for, result posted to the main window.+ pub fn start_thumbs(main: isize) -> std::sync::mpsc::Sender<(u32, usize, PathBuf)> {+ let (tx, rx) = std::sync::mpsc::channel::<(u32, usize, PathBuf)>();+ std::thread::spawn(move || unsafe {+ let _ = CoInitializeEx(None, COINIT_MULTITHREADED);+ for (era, row, path) in rx {+ if era != super::GEN.load(std::sync::atomic::Ordering::Relaxed) { continue; }+ let Ok(f) = SHCreateItemFromParsingName::<_, _, IShellItemImageFactory>(PCWSTR(wide(&path).as_ptr()), None) else { continue };+ let Ok(bmp) = f.GetImage(SIZE { cx: super::THUMB, cy: super::THUMB }, SIIGBF_BIGGERSIZEOK) else { continue };+ let padded = pad(bmp.0);+ windows_sys::Win32::Graphics::Gdi::DeleteObject(bmp.0 as _);+ if padded.is_null() { continue; }+ let b = Box::new((era, row, padded as isize));+ let _ = PostMessageW(Some(HWND(main as *mut c_void)), super::WM_THUMB, WPARAM(Box::into_raw(b) as usize), LPARAM(0));+ }+ });+ tx+ }++ /// Centers `src` (any size up to THUMB, 32-bit with alpha) on a transparent THUMB x THUMB bitmap: ImageList_Add needs exact sizes.+ unsafe fn pad(src: *mut c_void) -> *mut c_void {+ use windows_sys::Win32::Graphics::Gdi::*;+ unsafe {+ let t = super::THUMB;+ let mut bm: BITMAP = std::mem::zeroed();+ GetObjectW(src as _, size_of::<BITMAP>() as i32, &mut bm as *mut _ as _);+ let mut bi: BITMAPINFO = std::mem::zeroed();+ bi.bmiHeader = BITMAPINFOHEADER { biSize: size_of::<BITMAPINFOHEADER>() as u32, biWidth: t, biHeight: -t, biPlanes: 1, biBitCount: 32, biCompression: BI_RGB, ..std::mem::zeroed() };+ let mut bits = std::ptr::null_mut();+ let dst = CreateDIBSection(std::ptr::null_mut(), &bi, DIB_RGB_COLORS, &mut bits, std::ptr::null_mut(), 0);+ if dst.is_null() { return std::ptr::null_mut(); }+ let (dc, sdc) = (CreateCompatibleDC(std::ptr::null_mut()), CreateCompatibleDC(std::ptr::null_mut()));+ let (o1, o2) = (SelectObject(dc, dst), SelectObject(sdc, src as _));+ BitBlt(dc, (t - bm.bmWidth) / 2, (t - bm.bmHeight) / 2, bm.bmWidth, bm.bmHeight, sdc, 0, 0, SRCCOPY);+ SelectObject(dc, o1); SelectObject(sdc, o2);+ DeleteDC(dc); DeleteDC(sdc);+ dst+ }+ }++ /// Puts `paths` on the system clipboard like Explorer: the shell's own data object plus the "Preferred DropEffect"+ /// marker (copy or cut), so Ctrl+V works in a real Explorer window and in other file managers.+ pub fn clip_set(h: *mut c_void, paths: &[PathBuf], cut: bool) -> Result<()> {+ unsafe {+ let data: IDataObject = ui(HWND(h), paths)?;+ let fmt = FORMATETC { cfFormat: RegisterClipboardFormatW(w!("Preferred DropEffect")) as u16, ptd: std::ptr::null_mut(), dwAspect: DVASPECT_CONTENT.0 as u32, lindex: -1, tymed: TYMED_HGLOBAL.0 as u32 };+ let hg = GlobalAlloc(GMEM_MOVEABLE, 4)?;+ *(GlobalLock(hg) as *mut u32) = if cut { DROPEFFECT_MOVE.0 } else { DROPEFFECT_COPY.0 };+ let _ = GlobalUnlock(hg);+ let med = STGMEDIUM { tymed: TYMED_HGLOBAL.0 as u32, u: STGMEDIUM_0 { hGlobal: hg }, pUnkForRelease: std::mem::ManuallyDrop::new(None) };+ data.SetData(&fmt, &med, true)?; // the data object owns the memory from here+ OleSetClipboard(&data)+ }+ }++ /// What is on the system clipboard as files: (paths, cut?). None = no files there.+ pub fn clip_get() -> Option<(Vec<PathBuf>, bool)> {+ unsafe {+ let o = OleGetClipboard().ok()?;+ let paths = hdrop_paths(&o).ok().filter(|p| !p.is_empty())?;+ let fmt = FORMATETC { cfFormat: RegisterClipboardFormatW(w!("Preferred DropEffect")) as u16, ptd: std::ptr::null_mut(), dwAspect: DVASPECT_CONTENT.0 as u32, lindex: -1, tymed: TYMED_HGLOBAL.0 as u32 };+ let cut = o.GetData(&fmt).ok().is_some_and(|mut m| {+ let p = GlobalLock(m.u.hGlobal) as *const u32;+ let v = if p.is_null() { 0 } else { *p };+ let _ = GlobalUnlock(m.u.hGlobal);+ ReleaseStgMedium(&mut m);+ v & DROPEFFECT_MOVE.0 != 0+ });+ Some((paths, cut))+ }+ }++ pub fn clip_clear() { unsafe { let _ = OleSetClipboard(None); } }++ struct Pidls(Vec<*mut ITEMIDLIST>);+ impl Drop for Pidls { fn drop(&mut self) { for p in &self.0 { unsafe { CoTaskMemFree(Some(*p as *const c_void)) }; } } }++ /// A shell UI object (IContextMenu, IDataObject...) for items that all live in one folder.+ fn ui<T: Interface>(h: HWND, paths: &[PathBuf]) -> Result<T> {+ unsafe {+ let mut abs = Pidls(vec![]);+ for p in paths {+ let mut pidl = std::ptr::null_mut();+ SHParseDisplayName(PCWSTR(wide(p).as_ptr()), None, &mut pidl, 0, None)?;+ abs.0.push(pidl);+ }+ let parent: IShellFolder = SHBindToParent(abs.0[0], None)?;+ let kids: Vec<*const ITEMIDLIST> = abs.0.iter().map(|&p| ILFindLastID(p) as *const _).collect();+ parent.GetUIObjectOf(h, &kids, None)+ }+ }++ thread_local! { static CM2: RefCell<Option<IContextMenu2>> = const { RefCell::new(None) }; }++ /// Forwards owner-draw / init-popup menu messages so submenus like "Send to" get filled in.+ pub fn menu_msg(m: u32, wp: usize, lp: isize) -> bool {+ CM2.with_borrow(|c| c.as_ref().is_some_and(|c| unsafe { c.HandleMenuMsg(m, WPARAM(wp), LPARAM(lp)).is_ok() }))+ }++ /// The real shell context menu for `paths`, so 7-Zip/Git/etc. entries show up.+ pub fn show(h: *mut c_void, paths: &[PathBuf]) -> Result<()> {+ unsafe {+ let hwnd = HWND(h);+ let cm: IContextMenu = ui(hwnd, paths)?;+ let menu = CreatePopupMenu()?;+ cm.QueryContextMenu(menu, 0, 1, 0x7FFF, CMF_NORMAL).ok()?;+ CM2.set(cm.cast::<IContextMenu2>().ok());+ let mut pt = POINT::default();+ GetCursorPos(&mut pt)?;+ let id = TrackPopupMenuEx(menu, TPM_RETURNCMD.0 | TPM_RIGHTBUTTON.0, pt.x, pt.y, hwnd, None).0;+ CM2.set(None);+ if id > 0 {+ let ci = CMINVOKECOMMANDINFO { cbSize: size_of::<CMINVOKECOMMANDINFO>() as u32, hwnd, lpVerb: PCSTR((id - 1) as usize as *const u8), nShow: SW_SHOWNORMAL.0, ..Default::default() };+ cm.InvokeCommand(&ci)?;+ }+ DestroyMenu(menu)+ }+ }++ /// Starts an OLE drag of `paths` (blocks until dropped).+ pub fn drag(h: *mut c_void, paths: &[PathBuf]) -> Result<()> {+ unsafe {+ let hwnd = HWND(h);+ let data: IDataObject = ui(hwnd, paths)?;+ SHDoDragDrop(Some(hwnd), &data, None, DROPEFFECT_COPY | DROPEFFECT_MOVE | DROPEFFECT_LINK)?;+ Ok(())+ }+ }++ fn hdrop_paths(o: &IDataObject) -> Result<Vec<PathBuf>> {+ unsafe {+ let fmt = FORMATETC { cfFormat: CF_HDROP.0, ptd: std::ptr::null_mut(), dwAspect: DVASPECT_CONTENT.0 as u32, lindex: -1, tymed: TYMED_HGLOBAL.0 as u32 };+ let mut med = o.GetData(&fmt)?;+ let hd = HDROP(med.u.hGlobal.0);+ let mut out = vec![];+ for i in 0..DragQueryFileW(hd, u32::MAX, None) {+ let mut buf = vec![0u16; DragQueryFileW(hd, i, None) as usize + 1];+ let n = DragQueryFileW(hd, i, Some(&mut buf)) as usize;+ out.push(PathBuf::from(String::from_utf16_lossy(&buf[..n])));+ }+ ReleaseStgMedium(&mut med);+ Ok(out)+ }+ }++ #[implement(IDropTarget)]+ struct DropT { main: isize }++ fn effect(k: MODIFIERKEYS_FLAGS) -> DROPEFFECT { if k.0 & 8 != 0 { DROPEFFECT_COPY } else { DROPEFFECT_MOVE } } // 8 = MK_CONTROL++ impl IDropTarget_Impl for DropT_Impl {+ fn DragEnter(&self, _o: Ref<'_, IDataObject>, k: MODIFIERKEYS_FLAGS, _pt: &POINTL, e: *mut DROPEFFECT) -> Result<()> { unsafe { *e = effect(k) }; Ok(()) }+ fn DragOver(&self, k: MODIFIERKEYS_FLAGS, _pt: &POINTL, e: *mut DROPEFFECT) -> Result<()> { unsafe { *e = effect(k) }; Ok(()) }+ fn DragLeave(&self) -> Result<()> { Ok(()) }+ fn Drop(&self, o: Ref<'_, IDataObject>, k: MODIFIERKEYS_FLAGS, pt: &POINTL, e: *mut DROPEFFECT) -> Result<()> {+ if super::desk::dragging() {+ // desktop icons dropped back on the desktop: a move of the icons, not of the files (the dragger finishes it)+ super::desk::dropped_here((pt.x, pt.y));+ unsafe { *e = DROPEFFECT_NONE };+ return Ok(());+ }+ let paths = hdrop_paths(o.ok()?)?;+ let to = super::cur_dir();+ // like Explorer: same drive moves, other drive copies, Ctrl forces copy+ let copy = k.0 & 8 != 0 || paths.first().and_then(|p| p.components().next()) != to.components().next();+ unsafe { *e = if copy { DROPEFFECT_COPY } else { DROPEFFECT_MOVE } };+ let _ = fileop(self.main as *mut c_void, if copy { Op::Copy } else { Op::Move }, &paths, &to);+ unsafe { let _ = PostMessageW(Some(HWND(self.main as *mut c_void)), WM_APP, WPARAM(0), LPARAM(0)); }+ Ok(())+ }+ }++ pub fn register_drop(list: *mut c_void, main: isize) -> Result<()> {+ let t: IDropTarget = DropT { main }.into();+ unsafe { RegisterDragDrop(HWND(list), &t) }+ }+}+++/// The desktop's own logic: icons stay where the user puts them (positions saved per name), dropping one onto a folder+/// icon moves it into the folder, and a host window for Wallpaper Engine (it draws behind the icons).+mod desk {+ #![allow(unsafe_op_in_unsafe_fn)]+ use super::*;+ use std::{cell::Cell, collections::{HashMap, HashSet}};+ use windows_sys::Win32::Graphics::Gdi::{CreateSolidBrush, DeleteObject, FillRect, HDC, ScreenToClient};++ pub const SPAWN_WORKERW: u32 = 0x052C; // what wallpaper apps send to "Progman" to get a window behind the icons+ const KEY: u32 = 0x0001_0001; // rgb(1, 0, 1): the list's background colour, made see-through while a live wallpaper runs++ thread_local! {+ static DRAG_FROM: Cell<Option<(i32, i32)>> = const { Cell::new(None) }; // our own icon drag: where it started (list coords)+ static DROP_AT: Cell<Option<(i32, i32)>> = const { Cell::new(None) }; // ...and where it was dropped (screen coords)+ static WORKERW: Cell<isize> = const { Cell::new(0) };+ static LIVE: Cell<bool> = const { Cell::new(false) }; // a live wallpaper is running in WORKERW+ }++ fn pos_file() -> PathBuf {+ PathBuf::from(env::var_os("APPDATA").unwrap_or_default()).join(r"rust-explorer\desktop-icons.txt")+ }++ /// Saved icon positions: name -> (x, y) in list pixels.+ fn saved() -> HashMap<String, (i32, i32)> {+ fs::read_to_string(pos_file()).unwrap_or_default().lines().filter_map(|l| {+ let mut p = l.splitn(3, '\t');+ Some((p.next()?.parse().ok()?, p.next()?.parse().ok()?, p.next()?.to_string()))+ }).map(|(x, y, n): (i32, i32, String)| (n, (x, y))).collect()+ }++ fn names() -> Vec<String> { ST.with_borrow(|st| st.rows.iter().map(|r| r.name.clone()).collect()) }++ fn pos(list: HWND, i: usize) -> (i32, i32) {+ let mut p = POINT { x: 0, y: 0 };+ put(list, LVM_GETITEMPOSITION, i, &mut p as *mut _ as isize);+ (p.x, p.y)+ }++ fn set_pos(list: HWND, i: usize, (x, y): (i32, i32)) {+ let p = POINT { x, y };+ put(list, LVM_SETITEMPOSITION32, i, &p as *const _ as isize);+ }++ /// Writes every icon's position (after a move or a fresh layout).+ pub fn save(list: HWND) {+ let lines: String = names().iter().enumerate().map(|(i, n)| { let (x, y) = pos(list, i); format!("{x}\t{y}\t{n}\n") }).collect();+ let f = pos_file();+ let _ = fs::create_dir_all(f.parent().unwrap_or(&f));+ let _ = fs::write(f, lines);+ }++ /// The icon grid: cell size, and how many columns / rows fit.+ struct Grid { cx: i32, cy: i32, cols: i32, rows: i32 }++ impl Grid {+ fn of(list: HWND) -> Grid {+ let s = put(list, LVM_GETITEMSPACING, 0, 0) as u32;+ let (cx, cy) = (((s & 0xFFFF) as i32).max(1), ((s >> 16) as i32).max(1));+ let mut r: RECT = unsafe { std::mem::zeroed() };+ unsafe { GetClientRect(list, &mut r) };+ if r.bottom <= 0 {+ // the first fill runs in WM_CREATE, before WM_SIZE gives the list its size: the size it is about to get+ r = unsafe { RECT { left: 0, top: 0, right: GetSystemMetrics(SM_CXSCREEN), bottom: GetSystemMetrics(SM_CYSCREEN) - desk_top() - desk_bottom() } };+ }+ Grid { cx, cy, cols: (r.right / cx).max(1), rows: (r.bottom / cy).max(1) }+ }+ /// Nearest cell to a position; None if it is off the grid (screen got smaller).+ fn cell(&self, (x, y): (i32, i32)) -> Option<(i32, i32)> {+ let c = ((x + self.cx / 2).div_euclid(self.cx), (y + self.cy / 2).div_euclid(self.cy));+ (c.0 >= 0 && c.1 >= 0 && c.0 < self.cols && c.1 < self.rows).then_some(c)+ }+ fn at(&self, (c, r): (i32, i32)) -> (i32, i32) { (c * self.cx, r * self.cy) }+ /// Free cell nearest to `want`; with no wish the first free one going down the columns, like Windows.+ fn free(&self, taken: &HashSet<(i32, i32)>, want: Option<(i32, i32)>) -> (i32, i32) {+ let all = (0..self.cols).flat_map(|c| (0..self.rows).map(move |r| (c, r))).filter(|c| !taken.contains(c));+ match want {+ Some((wc, wr)) => all.min_by_key(|&(c, r)| (c - wc).pow(2) + (r - wr).pow(2)),+ None => all.min(),+ }+ .unwrap_or((0, 0))+ }+ }++ /// Fills the (non-virtual) desktop list with `n` rows and puts every icon on its saved cell, new ones on free cells.+ pub fn fill(list: HWND, n: usize) {+ for i in 0..n {+ let mut it: LVITEMW = unsafe { std::mem::zeroed() };+ it.mask = LVIF_TEXT | LVIF_IMAGE;+ it.iItem = i as i32;+ it.pszText = usize::MAX as *mut u16; // LPSTR_TEXTCALLBACKW: text and icon come from LVN_GETDISPINFO+ it.iImage = -1; // I_IMAGECALLBACK+ put(list, LVM_INSERTITEMW, 0, &it as *const _ as isize);+ }+ let (g, old, names) = (Grid::of(list), saved(), names());+ let mut taken = HashSet::new();+ let mut later = vec![];+ for (i, name) in names.iter().enumerate() {+ match old.get(name).and_then(|&p| g.cell(p)).filter(|c| !taken.contains(c)) {+ Some(c) => { taken.insert(c); set_pos(list, i, g.at(c)); }+ None => later.push(i),+ }+ }+ for i in later {+ let c = g.free(&taken, None);+ taken.insert(c);+ set_pos(list, i, g.at(c));+ }+ save(list);+ }++ // ---------- moving icons ----------++ /// Our own drag of desktop icons starts (`from` in list coordinates).+ pub fn drag_start(from: (i32, i32)) { DRAG_FROM.set(Some(from)); DROP_AT.set(None); }+ pub fn dragging() -> bool { DRAG_FROM.get().is_some() }+ /// Called by the drop target: the drag ended on the desktop itself at screen point `at`.+ pub fn dropped_here(at: (i32, i32)) { DROP_AT.set(Some(at)); }++ /// After the drag: on a folder icon (not one of the dragged) the selection moves into that folder; anywhere else the+ /// icons move by the drag distance, snapped to the grid, each to the nearest free cell. true = handled here.+ pub fn drag_end(h: HWND, list: HWND) -> bool {+ let Some(from) = DRAG_FROM.take() else { return false };+ // normally our drop target recorded where it ended; over a live wallpaper OLE never reaches it (the wallpaper window of+ // another process is under the pointer), so then: the pointer is over our desktop window = the drop was on the desktop+ let at = DROP_AT.take().or_else(|| unsafe {+ let mut c = POINT { x: 0, y: 0 };+ GetCursorPos(&mut c);+ (GetAncestor(WindowFromPoint(c), GA_ROOT) == h).then_some((c.x, c.y))+ });+ let Some(at) = at else { return false };+ let mut pt = POINT { x: at.0, y: at.1 };+ unsafe { ScreenToClient(list, &mut pt) };+ let (_, dir, paths) = selected();+ let mut sel = vec![];+ let mut i = -1isize;+ loop {+ i = put(list, LVM_GETNEXTITEM, i as usize, LVNI_SELECTED as isize);+ if i < 0 { break; }+ sel.push(i as usize);+ }+ // onto a folder icon+ let mut ht: LVHITTESTINFO = unsafe { std::mem::zeroed() };+ ht.pt = pt;+ let tgt = put(list, LVM_HITTEST, 0, &mut ht as *mut _ as isize);+ if tgt >= 0 && !sel.contains(&(tgt as usize)) {+ let target = ST.with_borrow(|st| st.rows.get(tgt as usize).filter(|r| r.dir).map(|r| st.dir.join(&r.name)));+ if let Some(t) = target {+ let _ = sh::fileop(h as _, sh::Op::Move, &paths, &t);+ let _ = dir;+ unsafe { PostMessageW(h, WM_APP, 0, 0) }; // reload: the moved icons are gone from here+ return true;+ }+ }+ let g = Grid::of(list);+ let n = put(list, LVM_GETITEMCOUNT, 0, 0).max(0) as usize;+ let mut taken: HashSet<(i32, i32)> = (0..n).filter(|i| !sel.contains(i)).filter_map(|i| g.cell(pos(list, i))).collect();+ let (dx, dy) = (pt.x - from.0, pt.y - from.1);+ for &i in &sel {+ let (x, y) = pos(list, i);+ let want = g.cell((x + dx, y + dy)).unwrap_or_else(|| {+ // dragged off the grid: the nearest edge cell+ (((x + dx) / g.cx).clamp(0, g.cols - 1), ((y + dy) / g.cy).clamp(0, g.rows - 1))+ });+ let c = if taken.contains(&want) { g.free(&taken, Some(want)) } else { want };+ taken.insert(c);+ set_pos(list, i, g.at(c));+ }+ save(list);+ true+ }++ // ---------- Wallpaper Engine (and other live wallpapers) ----------+ //+ // They look for the "Progman" window (that is our desktop's class), send it 0x052C and put their window into the+ // "WorkerW" that appears: Windows 11 24H2 has it as a child of Progman, under the icons. Ours is the same, and while it+ // holds a wallpaper the icon list turns see-through (colour key) so the wallpaper shows between the icons.++ pub unsafe fn spawn_workerw(h: HWND) {+ if WORKERW.get() != 0 && IsWindow(WORKERW.get() as HWND) != 0 { return; }+ let mut r: RECT = std::mem::zeroed();+ GetClientRect(h, &mut r);+ let ww = CreateWindowExW(0, w("WorkerW").as_ptr(), ptr::null(), WS_CHILD | WS_VISIBLE, 0, 0, r.right, r.bottom, h, 0 as _, GetModuleHandleW(ptr::null()), ptr::null());+ SetWindowPos(ww, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); // under the icon list+ WORKERW.set(ww as isize);+ }++ /// Every couple of seconds: a wallpaper window inside WorkerW = live mode on, none = back to the picture.+ pub unsafe fn check_live(list: HWND) {+ let ww = WORKERW.get() as HWND;+ let live = !ww.is_null() && IsWindow(ww) != 0 && !GetWindow(ww, GW_CHILD).is_null();+ if live == LIVE.replace(live) { return; }+ // the list stays "transparent" (its background is what the desktop paints: the key colour while live, see erase()),+ // so it keeps drawing the label shadows; the colour key then cuts the background out+ let ex = GetWindowLongPtrW(list, GWL_EXSTYLE);+ if live {+ SetWindowLongPtrW(list, GWL_EXSTYLE, ex | WS_EX_LAYERED as isize);+ SetLayeredWindowAttributes(list, KEY, 0, LWA_COLORKEY);+ } else {+ SetWindowLongPtrW(list, GWL_EXSTYLE, ex & !(WS_EX_LAYERED as isize));+ }+ InvalidateRect(list, ptr::null(), 1);+ }++ /// The desktop's background: the key colour while a live wallpaper shows through, else the picture. false = none to paint.+ pub unsafe fn erase(dc: HDC, h: HWND) -> bool {+ let (bmp, cw, ch) = WALL.get();+ if LIVE.get() {+ let mut r: RECT = std::mem::zeroed();+ GetClientRect(h, &mut r);+ let b = CreateSolidBrush(KEY);+ FillRect(dc, &r, b);+ DeleteObject(b);+ } else if bmp != 0 {+ wall::paint(dc, bmp, cw, ch);+ } else {+ return false;+ }+ true+ }++ /// WorkerW without a wallpaper in it shows the picture wallpaper, like the desktop behind it.+ pub unsafe extern "system" fn workerw_proc(h: HWND, m: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {+ if m == WM_ERASEBKGND {+ let (bmp, cw, ch) = WALL.get();+ if bmp != 0 { wall::paint(wp as _, bmp, cw, ch); } else { let mut r: RECT = std::mem::zeroed(); GetClientRect(h, &mut r); FillRect(wp as _, &r, GetStockObject(BLACK_BRUSH) as _); }+ return 1;+ }+ DefWindowProcW(h, m, wp, lp)+ }++ #[cfg(test)]+ mod tests {+ use super::Grid;+ use std::collections::HashSet;++ #[test]+ fn grid_cells() {+ let g = Grid { cx: 100, cy: 90, cols: 5, rows: 4 };+ assert_eq!(g.cell((0, 0)), Some((0, 0)));+ assert_eq!(g.cell((149, 44)), Some((1, 0))); // rounds to the nearest cell+ assert_eq!(g.cell((900, 0)), None); // off the grid+ let mut taken: HashSet<_> = [(0, 0), (0, 1)].into();+ assert_eq!(g.free(&taken, None), (0, 2)); // down the first column first+ taken.insert((2, 2));+ assert_eq!(g.free(&taken, Some((2, 2))), (1, 2)); // nearest free to the wish (ties: lowest)+ }+ }+}++/// Trace of the icon drags (%TEMP%\rx-drag.log), to find out where one stops working. Cheap: a few lines per drag.+fn drag_log(s: &str) {+ use std::io::Write;+ let p = std::env::temp_dir().join("rx-drag.log");+ if let Ok(mut f) = fs::OpenOptions::new().create(true).append(true).open(p) { let _ = writeln!(f, "{s}"); }+}++/// Address bar subclass: Enter / Esc go to the main window, everything else is the normal edit control.+unsafe extern "system" fn edit_proc(h: HWND, m: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {+ unsafe {+ if matches!(wp, 13 | 27) && matches!(m, WM_KEYDOWN | WM_CHAR) {+ if m == WM_KEYDOWN { PostMessageW(GetAncestor(h, GA_ROOT), WM_GO, wp, 0); }+ return 0; // WM_CHAR swallowed so there is no beep+ }+ CallWindowProcW(std::mem::transmute::<isize, WNDPROC>(EDIT_OLD.load(std::sync::atomic::Ordering::Relaxed)), h, m, wp, lp)+ }+}++unsafe extern "system" fn proc(h: HWND, m: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {+ unsafe {+ match m {+ WM_CREATE => {+ let inst = GetModuleHandleW(ptr::null());+ // desktop mode has no tab bar / address bar: the null handles are harmless to every SendMessage below+ let (mut tab, mut edit) = (0 as HWND, 0 as HWND);+ if !desk() {+ ui::dark_title(h);+ // the chrome (tabs, toolbar, address pill) is one painted window; the address box is a real edit inside its pill+ tab = CreateWindowExW(0, w("RxChrome").as_ptr(), ptr::null(), WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN, 0, 0, 0, 0, h, 0 as _, inst, ptr::null());+ ui::nav_init(CreateWindowExW(0, w("RxNav").as_ptr(), ptr::null(), WS_CHILD | WS_VISIBLE, 0, 0, 0, 0, h, 0 as _, inst, ptr::null()));+ edit = CreateWindowExW(0, w("EDIT").as_ptr(), ptr::null(), WS_CHILD | WS_VISIBLE | ES_AUTOHSCROLL as u32, 0, 0, 0, 0, tab, 0 as _, inst, ptr::null());+ put(edit, WM_SETFONT, ui::font(14, 400, "Segoe UI") as usize, 1);+ EDIT_OLD.store(SetWindowLongPtrW(edit, GWLP_WNDPROC, edit_proc as *const () as isize), std::sync::atomic::Ordering::Relaxed);+ }+ let view = if desk() { LVS_ICON } else { LVS_REPORT };+ let list = CreateWindowExW(0, w("SysListView32").as_ptr(), ptr::null(), WS_CHILD | WS_VISIBLE | view | if desk() { 0 } else { LVS_OWNERDATA } | LVS_EDITLABELS | LVS_SHOWSELALWAYS | LVS_SHAREIMAGELISTS, 0, 0, 0, 0, h, 0 as _, inst, ptr::null());+ put(list, LVM_SETEXTENDEDLISTVIEWSTYLE, 0, (LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER) as isize);+ let mut fi: SHFILEINFOW = std::mem::zeroed();+ let il = SHGetFileInfoW(w("C:\\").as_ptr(), 0, &mut fi, size_of::<SHFILEINFOW>() as u32, SHGFI_SYSICONINDEX | SHGFI_SMALLICON);+ put(list, LVM_SETIMAGELIST, LVSIL_SMALL as usize, il as isize);+ if desk() {+ // system large icons; indexes are shared with the small list, so icon_of() works unchanged+ let big = SHGetFileInfoW(w("C:\\").as_ptr(), 0, &mut fi, size_of::<SHFILEINFOW>() as u32, SHGFI_SYSICONINDEX | SHGFI_LARGEICON);+ put(list, LVM_SETIMAGELIST, LVSIL_NORMAL as usize, big as isize);+ put(list, LVM_SETICONSPACING, 0, ((ui::sc(96) as isize) << 16) | ui::sc(88) as isize);+ // transparent background (the desktop paints it) and shadowed labels, readable on light wallpapers too+ let ex = LVS_EX_TRANSPARENTBKGND | 0x0080_0000; // LVS_EX_TRANSPARENTSHADOWTEXT+ put(list, LVM_SETEXTENDEDLISTVIEWSTYLE, ex as usize, ex as isize);+ for msg in [LVM_SETBKCOLOR, LVM_SETTEXTBKCOLOR] { put(list, msg, 0, CLR_NONE); }+ put(list, LVM_SETTEXTCOLOR, 0, 0x00FF_FFFF);+ let (cw, ch) = (GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));+ WALL.set((wall::load(cw, ch), cw, ch));+ // grey (not ClearType) smoothing: on a live wallpaper the labels sit on a colour key, where ClearType leaves coloured fringes+ put(list, WM_SETFONT, windows_sys::Win32::Graphics::Gdi::CreateFontW(-ui::sc(13), 0, 0, 0, 400, 0, 0, 0, 1, 0, 0, 4, 0, w("Segoe UI").as_ptr()) as usize, 1);+ // like explorer's desktop: wallpaper apps look for a SHELLDLL_DefView under Progman+ CreateWindowExW(0, w("SHELLDLL_DefView").as_ptr(), ptr::null(), WS_CHILD, 0, 0, 0, 0, h, 0 as _, inst, ptr::null());+ SetTimer(h, 7, 2000, None); // live wallpaper on / off (desk::check_live)+ } else {+ let himl = ImageList_Create(THUMB, THUMB, ILC_COLOR32, 64, 64);+ put(list, LVM_SETIMAGELIST, LVSIL_NORMAL as usize, himl as isize);+ put(list, LVM_SETICONSPACING, 0, ((THUMB as isize + 34) << 16) | (THUMB as isize + 24));+ let _ = TX.set(sh::start_thumbs(h as isize));+ ST.with_borrow_mut(|st| st.himl = himl as isize);+ // the same columns, in the same order, as Explorer's details view+ col(list, 0, "Name", ui::sc(360), false); col(list, 1, "Date modified", ui::sc(160), false); col(list, 2, "Type", ui::sc(140), false); col(list, 3, "Size", ui::sc(96), true);+ ui::style_list(list);+ }+ ST.with_borrow_mut(|st| { st.list = list; st.tab = tab; st.edit = edit; st.tabs = vec![PathBuf::new()]; });+ if !desk() { ui::place_edit(tab); }+ let _ = sh::register_drop(list as _, h as isize);+ // live wallpaper: the list is see-through (colour key), so over empty desktop OLE finds the wallpaper window under it,+ // and walks up from there to the desktop window: it must accept the drop too+ if desk() { let _ = sh::register_drop(h as _, h as isize); }+ let start = if desk() { sh::desktop_dirs().into_iter().next().unwrap_or_default() } else { env::args().nth(1).map(PathBuf::from).unwrap_or_else(|| PathBuf::from("C:\\")) };+ load(h, start);+ 0+ }+ WM_SIZE => {+ let list = ST.with_borrow(|st| st.list);+ let (cw, ch) = ((lp & 0xFFFF) as i32, ((lp >> 16) & 0xFFFF) as i32);+ if desk() {+ MoveWindow(list, 0, desk_top(), cw, (ch - desk_top() - desk_bottom()).max(0), 1);+ } else {+ ui::layout_children(cw, ch);+ InvalidateRect(h, ptr::null(), 0);+ }+ 0+ }+ WM_PAINT if !desk() => { ui::paint_status(h); 0 }+ ui::WM_UI => {+ match wp {+ 1 => { let n = ST.with_borrow(|st| st.tabs.len()); if (lp as usize) < n { tab_select(h, lp as usize); } }+ 2 => tab_close_at(h, lp as usize),+ 3 => tab_new(),+ 4 => nav(h, true),+ 5 => nav(h, false),+ 6 => { if let Some(p) = cur_dir().parent() { load(h, p.to_path_buf()) } }+ 7 => reload(h),+ 8 => toggle_view(h),+ 9 => search_focus(),+ 20 => { if let Some(p) = ui::nav_path(lp as usize) { load(h, p); } } // a folder in the left pane+ 21 => { if let Some(p) = ui::crumb_path(lp as usize) { load(h, p); } } // a part of the path in the address pill+ _ => {}+ }+ 0+ }+ WM_ERASEBKGND if desk() && desk::erase(wp as _, h) => 1,+ WM_WINDOWPOSCHANGING if desk() => { // the desktop never rises above other windows+ let wp = &mut *(lp as *mut WINDOWPOS);+ wp.hwndInsertAfter = HWND_BOTTOM;+ wp.flags |= SWP_NOACTIVATE;+ 0+ }+ WM_INITMENUPOPUP if sh::menu_msg(m, wp, lp) => 0,+ WM_DRAWITEM | WM_MEASUREITEM if sh::menu_msg(m, wp, lp) => 1,+ WM_NOTIFY => {+ let nm = &*(lp as *const NMHDR);+ let list = ST.with_borrow(|st| st.list);+ match nm.code {+ NM_CUSTOMDRAW if nm.hwndFrom == list && !desk() => return ui::list_draw(lp), // the rows are painted by hand+ LVN_ITEMCHANGED | LVN_ODSTATECHANGED => ui::status_dirty(h), // selection count in the status line+ LVN_GETDISPINFOW => {+ let it = &mut (*(lp as *mut NMLVDISPINFOW)).item;+ // a request that arrives while ST is borrowed is skipped; the list repaints later+ ST.with(|c| {+ let Ok(mut st) = c.try_borrow_mut() else { return };+ let State { dir, rows, thumbs, .. } = &mut *st;+ let Some(i) = usize::try_from(it.iItem).ok() else { return };+ let Some(r) = rows.get_mut(i) else { return };+ if it.mask & LVIF_TEXT != 0 && it.cchTextMax > 0 {+ let s = match it.iSubItem { 0 => r.name.clone(), 1 => date_text(r.time), 2 => type_text(&r.name, r.dir), _ if r.dir => String::new(), _ => size_text(r.size) };+ let u: Vec<u16> = s.encode_utf16().take(it.cchTextMax as usize - 1).collect();+ ptr::copy_nonoverlapping(u.as_ptr(), it.pszText, u.len());+ *it.pszText.add(u.len()) = 0;+ }+ if it.mask & LVIF_IMAGE != 0 && *thumbs {+ if r.thumb == -2 {+ r.thumb = -1;+ if let Some(tx) = TX.get() { let _ = tx.send((GEN.load(std::sync::atomic::Ordering::Relaxed), i, dir.join(&r.name))); }+ }+ it.iImage = if r.thumb >= 0 { r.thumb } else { I_IMAGENONE };+ } else if it.mask & LVIF_IMAGE != 0 {+ if r.icon < 0 { r.icon = icon_of(&dir.join(&r.name), r.dir); }+ it.iImage = r.icon;+ }+ });+ }+ LVN_ITEMACTIVATE => {+ let i = (*(lp as *const NMITEMACTIVATE)).iItem;+ let hit = ST.with_borrow(|st| usize::try_from(i).ok().and_then(|i| st.rows.get(i)).map(|r| (st.dir.join(&r.name), r.dir)));+ if let Some((p, is_dir)) = hit {+ if is_dir && desk() { let _ = std::process::Command::new(env::current_exe().unwrap_or_default()).arg(p).spawn(); }+ else if is_dir { load(h, p) }+ else if let Some(exe) = tool("photoview").filter(|_| is_pic(&p)) { let _ = std::process::Command::new(exe).arg(&p).spawn(); }+ else { ShellExecuteW(0 as _, ptr::null(), w(&p.to_string_lossy()).as_ptr(), ptr::null(), ptr::null(), SW_SHOWNORMAL); }+ }+ }+ NM_RCLICK if nm.hwndFrom == list => {+ let (_, _, paths) = selected();+ if !paths.is_empty() { let _ = sh::show(h, &paths); reload(h); } else { bg_menu(h); }+ }+ LVN_COLUMNCLICK => {+ let c = (*(lp as *const NMLISTVIEW)).iSubItem as usize;+ let asc = if SORT_COL.load(Relaxed) == c { !SORT_ASC.load(Relaxed) } else { true };+ SORT_COL.store(c, Relaxed);+ SORT_ASC.store(asc, Relaxed);+ let n = ST.with_borrow_mut(|st| {+ sort_rows(&mut st.rows, c, asc);+ st.rows.iter_mut().for_each(|r| r.thumb = -2); // rows moved: thumbnails are asked for again+ st.rows.len()+ });+ reset_thumbs();+ put(list, LVM_REDRAWITEMS, 0, n as isize - 1);+ }+ LVN_BEGINDRAG => {+ let (_, _, paths) = selected();+ drag_log(&format!("BEGINDRAG desk={} selected={}", desk(), paths.len()));+ if !paths.is_empty() {+ if desk() { let p = (*(lp as *const NMLISTVIEW)).ptAction; desk::drag_start((p.x, p.y)); }+ let r = sh::drag(h, &paths);+ drag_log(&format!("drag finished: {r:?}"));+ // dropped on the desktop itself: the icons were moved (or went into a folder icon), no reload needed+ let handled = desk() && desk::drag_end(h, list);+ drag_log(&format!("moved on the desktop: {handled}"));+ if !handled { reload(h); }+ }+ }+ LVN_KEYDOWN => {+ let vk = (*(lp as *const NMLVKEYDOWN)).wVKey as u32;+ let ctrl = GetKeyState(VK_CONTROL as i32) < 0;+ if desk() && matches!(vk, 0x08 | 0x46 | 0x4D | 0x54 | 0x57 | 0x09 | 0x4C | 0x73) { return 0; } // browsing keys make no sense on the desktop+ let (list, dir, paths) = selected();+ match vk {+ 0x08 => if let Some(p) = dir.parent() { load(h, p.to_path_buf()) },+ 0x2E if !paths.is_empty() => { let _ = sh::fileop(h, sh::Op::Delete, &paths, &dir); }+ 0x71 => {+ let i = put(list, LVM_GETNEXTITEM, usize::MAX, LVNI_SELECTED as isize);+ if i >= 0 { put(list, LVM_EDITLABELW, i as usize, 0); }+ }+ 0x46 if ctrl => { search_focus(); return 0; } // Ctrl+F: address bar in search mode+ 0x73 | 0x4C if vk == 0x73 || ctrl => { // F4 / Ctrl+L: address bar+ let edit = ST.with_borrow(|st| st.edit);+ SetFocus(edit);+ put(edit, EM_SETSEL, 0, -1);+ return 0;+ }+ 0x5D if !paths.is_empty() => { let _ = sh::show(h, &paths); }+ 0x43 | 0x58 if ctrl && !paths.is_empty() => { let _ = sh::clip_set(h, &paths, vk == 0x58); return 0; }+ 0x56 if ctrl => paste(h, &dir),+ 0x4E if ctrl => new_entry(&dir, "New folder", true),+ 0x48 if ctrl => { SHOW_HIDDEN.fetch_xor(true, Relaxed); } // Ctrl+H: hidden files+ 0x74 => {} // F5: just the reload below+ 0x4D if ctrl => { toggle_view(h); return 0; } // Ctrl+M: details <-> thumbnails+ 0x54 if ctrl => tab_new(),+ 0x57 if ctrl => { tab_close(h); return 0; }+ 0x09 if ctrl => {+ let next = ST.with_borrow(|st| (st.active + 1) % st.tabs.len());+ tab_select(h, next);+ return 0;+ }+ _ => return 0,+ }+ reload(h);+ }+ LVN_ENDLABELEDITW => {+ let it = &(*(lp as *const NMLVDISPINFOW)).item;+ if !it.pszText.is_null() {+ let new = wstr(it.pszText);+ // reject separators so a rename can never move the item+ if !new.is_empty() && !new.contains(['\\', '/', ':']) {+ ST.with_borrow(|st| if let Some(r) = usize::try_from(it.iItem).ok().and_then(|i| st.rows.get(i)) { let _ = fs::rename(st.dir.join(&r.name), st.dir.join(&new)); });+ PostMessageW(h, WM_APP, 0, 0); // reload after the edit control is gone+ }+ }+ }+ _ => {}+ }+ 0+ }+ WM_SETFOCUS => { SetFocus(ST.with_borrow(|st| st.list)); 0 }+ WM_APP => { reload(h); 0 }+ WM_NAV => {+ match wp {+ 1 => nav(h, true),+ 2 => nav(h, false),+ 3 => { let (_, dir, sel) = selected(); properties(&sel.first().cloned().unwrap_or(dir)); }+ _ => if let Some(p) = cur_dir().parent() { load(h, p.to_path_buf()) },+ }+ 0+ }+ WM_THUMB => {+ let (era, row, bmp) = *Box::from_raw(wp as *mut (u32, usize, isize));+ let (list, himl) = ST.with_borrow(|st| (st.list, st.himl));+ if era == GEN.load(std::sync::atomic::Ordering::Relaxed) {+ let idx = ImageList_Add(himl as _, bmp as _, ptr::null_mut());+ let ok = idx >= 0 && ST.with_borrow_mut(|st| st.rows.get_mut(row).map(|r| r.thumb = idx).is_some());+ if ok { put(list, LVM_REDRAWITEMS, row, row as isize); }+ }+ windows_sys::Win32::Graphics::Gdi::DeleteObject(bmp as _);+ 0+ }+ WM_GO => {+ let (edit, list) = ST.with_borrow(|st| (st.edit, st.list));+ if wp == 13 {+ let mut buf = vec![0u16; GetWindowTextLengthW(edit) as usize + 1];+ let n = GetWindowTextW(edit, buf.as_mut_ptr(), buf.len() as i32) as usize;+ let p = PathBuf::from(String::from_utf16_lossy(&buf[..n]).trim().trim_matches('"'));+ let text = String::from_utf16_lossy(&buf[..n]);+ if let Some(q) = text.trim().strip_prefix('?') {+ if !q.trim().is_empty() { search(h, q.trim()); SetFocus(list); return 0; } // keep the query in the bar+ } else if p.is_dir() { load(h, p); }+ }+ SetWindowTextW(edit, w(&cur_dir().to_string_lossy()).as_ptr()); // also undoes a bad path / Esc+ SetFocus(list);+ 0+ }+ desk::SPAWN_WORKERW if desk() => { desk::spawn_workerw(h); 0 }+ WM_TIMER if desk() && wp == 7 => { desk::check_live(ST.with_borrow(|st| st.list)); 0 }+ WM_DESTROY => { PostQuitMessage(0); 0 }+ _ => DefWindowProcW(h, m, wp, lp),+ }+ }+}++fn main() {+ sh::init();+ unsafe {+ SetProcessDPIAware(); // sharp text at any scaling; every size below goes through ui::sc+ ui::init_scale();+ ui::gdiplus_start();+ ui::dark_mode();+ InitCommonControlsEx(&INITCOMMONCONTROLSEX { dwSize: size_of::<INITCOMMONCONTROLSEX>() as u32, dwICC: ICC_LISTVIEW_CLASSES });+ let inst = GetModuleHandleW(ptr::null());+ let cls = w("RustExplorer");+ let desktop = env::args().nth(1).as_deref() == Some("--desktop");+ // desktop without a wallpaper file shows black, not window white+ let bg = if desktop { GetStockObject(BLACK_BRUSH) as _ } else { windows_sys::Win32::Graphics::Gdi::CreateSolidBrush(ui::BG) };+ RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(ui::proc), hInstance: inst, lpszClassName: w("RxChrome").as_ptr(), hCursor: LoadCursorW(0 as _, IDC_ARROW), ..std::mem::zeroed() });+ RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(ui::nav_proc), hInstance: inst, lpszClassName: w("RxNav").as_ptr(), hCursor: LoadCursorW(0 as _, IDC_ARROW), ..std::mem::zeroed() });+ RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(proc), hInstance: inst, lpszClassName: cls.as_ptr(), hCursor: LoadCursorW(0 as _, IDC_ARROW), hbrBackground: bg, ..std::mem::zeroed() });+ if desktop {+ DESKTOP.store(true, Relaxed);+ // the whole screen: it paints the wallpaper too; the icon list sits above the bar (desk_top / desk_bottom)+ // class "Progman" like explorer's desktop, so Wallpaper Engine & co. find it; title "rs-desktop" tells it apart+ // from explorer's ("Program Manager") for rs-shell+ let pm = w("Progman");+ RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(proc), hInstance: inst, lpszClassName: pm.as_ptr(), hCursor: LoadCursorW(0 as _, IDC_ARROW), hbrBackground: bg, ..std::mem::zeroed() });+ RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(desk::workerw_proc), hInstance: inst, lpszClassName: w("WorkerW").as_ptr(), ..std::mem::zeroed() });+ RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(DefWindowProcW), hInstance: inst, lpszClassName: w("SHELLDLL_DefView").as_ptr(), ..std::mem::zeroed() });+ let d = CreateWindowExW(WS_EX_TOOLWINDOW, pm.as_ptr(), w("rs-desktop").as_ptr(), WS_POPUP, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), 0 as _, 0 as _, inst, ptr::null());+ SetWindowPos(d, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_SHOWWINDOW);+ } else {+ CreateWindowExW(0, cls.as_ptr(), ptr::null(), WS_OVERLAPPEDWINDOW | WS_VISIBLE | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, ui::sc(1000), ui::sc(660), 0 as _, 0 as _, inst, ptr::null());+ }+ let mut msg = std::mem::zeroed();+ while GetMessageW(&mut msg, 0 as _, 0, 0) > 0 {+ // Alt+Left / Right / Up / Enter arrive as WM_SYSKEYDOWN at the list, which never reports them: handle them here+ if msg.message == WM_SYSKEYDOWN && !desk() {+ let act = match msg.wParam { 0x25 => 1, 0x27 => 2, 0x0D => 3, 0x26 => 4, _ => 0 };+ if act != 0 { PostMessageW(GetAncestor(msg.hwnd, GA_ROOT), WM_NAV, act, 0); continue; }+ }+ TranslateMessage(&msg);+ DispatchMessageW(&msg);+ }+ }+}+++#[cfg(test)]+mod tests {+ use super::*;++ fn r(name: &str, dir: bool, size: u64, time: u64) -> Row { Row { name: name.into(), dir, size, time, icon: -1, thumb: -2 } }+ fn names(v: &[Row]) -> Vec<&str> { v.iter().map(|r| r.name.as_str()).collect() }++ #[test]+ fn folders_first_then_by_the_chosen_column() {+ let mut v = vec![r("b.txt", false, 5, 1), r("A", true, 0, 2), r("a.txt", false, 9, 3)];+ sort_rows(&mut v, 0, true);+ assert_eq!(names(&v), ["A", "a.txt", "b.txt"]);+ sort_rows(&mut v, 3, false); // biggest first, the folder still on top+ assert_eq!(names(&v), ["A", "a.txt", "b.txt"]);+ sort_rows(&mut v, 1, true); // oldest first+ assert_eq!(names(&v), ["A", "b.txt", "a.txt"]);+ }++ #[test]+ fn search_hit_paths_sort_by_file_name() {+ let mut v = vec![r("C:\\z\\b.txt", false, 1, 1), r("D:\\a\\a.txt", false, 1, 1)];+ sort_rows(&mut v, 0, true);+ assert_eq!(names(&v), ["D:\\a\\a.txt", "C:\\z\\b.txt"]);+ }++ #[test]+ fn history_goes_back_and_forward_and_a_new_visit_drops_the_forward_trail() {+ let mut h = Hist::default();+ for p in ["a", "b", "c"] { h.visit(p.into()); }+ assert_eq!(h.back(), Some("b".into()));+ assert_eq!(h.back(), Some("a".into()));+ assert_eq!(h.back(), None);+ assert_eq!(h.forward(), Some("b".into()));+ h.visit("x".into()); // from b: c is no longer ahead+ assert_eq!(h.forward(), None);+ assert_eq!(h.back(), Some("b".into()));+ h.visit("x".into()); h.visit("x".into()); // same folder twice is one step+ assert_eq!(h.v.len(), 3);+ }++ #[test]+ fn type_and_size_read_like_explorers() {+ assert_eq!(type_text("x", true), "File folder");+ assert_eq!(type_text("a.txt", false), "TXT file");+ assert_eq!(type_text("C:\\d\\b.tar.gz", false), "GZ file");+ assert_eq!(type_text(".gitignore", false), "File"); // a dot file has no extension+ assert_eq!(type_text("Makefile", false), "File");+ assert_eq!(size_text(1), "1 KB");+ assert_eq!(size_text(2048), "2 KB");+ assert_eq!(size_text(5 << 20), "5.0 MB");+ assert_eq!(size_text(3 << 30), "3.00 GB");+ }++ #[test]+ fn dates_are_formatted_and_zero_is_blank() {+ assert_eq!(date_text(0), "");+ let t = date_text(132_000_000_000_000_000); // some day in 2019, local time zone+ assert!(t.len() == 16 && t.starts_with("20"), "{t}");+ }+}++#[cfg(test)]+mod search_tests {+ #[test]+ fn local_search_finds_names_below_the_folder() {+ let d = std::env::temp_dir().join(format!("rx-search-test-{}", std::process::id()));+ std::fs::create_dir_all(d.join(r"sub\deep")).unwrap();+ for f in [r"Report.txt", r"sub\notes.md", r"sub\deep\REPORT-2.pdf"] { std::fs::write(d.join(f), "x").unwrap(); }+ let (rows, cut, flipped) = super::local_search(&d, "report");+ let (wrong, _, was_flipped) = super::local_search(&d, "кузщке"); // "report" typed in the Russian layout+ let mut names: Vec<String> = rows.iter().map(|r| std::path::Path::new(&r.name).file_name().unwrap().to_string_lossy().into_owned()).collect();+ names.sort();+ let _ = std::fs::remove_dir_all(&d);+ assert_eq!(names, ["REPORT-2.pdf", "Report.txt"]); // any case, any depth, absolute paths+ assert!(!cut && !flipped);+ assert!(was_flipped && wrong.len() == 2);+ }++ #[test]+ fn layout_flip_both_ways() {+ assert_eq!(super::flip_layout("сфкпщ"), "cargo");+ assert_eq!(super::flip_layout("ljrevtyns"), "документы");+ assert_eq!(super::flip_layout("Ыфму"), "Save");+ }+}diff --git a/plugins/rust-explorer/src/ui.rs b/plugins/rust-explorer/src/ui.rsnew file mode 100644index 0000000..4cc18bd--- /dev/null+++ b/plugins/rust-explorer/src/ui.rs@@ -0,0 +1,858 @@+//! The look of the file manager window, in the same palette as topbar: the top part (tabs, back / forward / up / reload,+//! address pill) and the status line are painted by hand (double buffered, eased hover, click flash); the file list is the+//! native list themed dark with taller rows. Everything is scaled by the system DPI.+#![allow(unsafe_op_in_unsafe_fn)]+use super::*;+use std::{cell::Cell, collections::HashMap, path::Path};+use windows_sys::Win32::{Graphics::{Dwm::DwmSetWindowAttribute, Gdi::*}, System::{LibraryLoader::{GetProcAddress, LoadLibraryW}, SystemInformation::GetTickCount64}, UI::Input::KeyboardAndMouse::{GetFocus, TRACKMOUSEEVENT, TME_LEAVE, TrackMouseEvent}};++pub const fn rgb(r: u8, g: u8, b: u8) -> u32 { r as u32 | (g as u32) << 8 | (b as u32) << 16 }+pub const BG: u32 = rgb(24, 30, 44);+pub const LISTBG: u32 = rgb(19, 24, 36);+pub const PILL: u32 = rgb(16, 20, 30);+pub const LINE: u32 = rgb(44, 52, 72);+pub const HOVER: u32 = rgb(40, 48, 68);+pub const ACTIVE: u32 = rgb(52, 61, 84);+pub const ACCENT: u32 = rgb(76, 194, 255);+pub const TEXT: u32 = rgb(255, 255, 255);+pub const DIM: u32 = rgb(150, 158, 175);+pub const OFF: u32 = rgb(80, 88, 105);++pub const CHROME_H: i32 = 88;+pub const STATUS_H: i32 = 26;+pub const WM_UI: u32 = WM_APP + 4; // chrome -> window: wp = action (see Hit), lp = tab index+const WM_MOUSELEAVE: u32 = 0x02A3; // not exported under the enabled features++// what the pointer is over / what a click does+const NONE: i32 = -1;+const BACK: i32 = 1;+const FWD: i32 = 2;+const UP: i32 = 3;+const RELOAD: i32 = 4;+const SEARCH: i32 = 5;+const VIEW: i32 = 6;+const PLUS: i32 = 7;+const TAB: i32 = 100; // + index+const CLOSE: i32 = 200; // + index+const CRUMB: i32 = 400; // + index: a part of the path in the address pill++thread_local! {+ static CRUMBS: RefCell<Vec<(RECT, PathBuf)>> = const { RefCell::new(Vec::new()) }; // where each path part was painted+ static SEARCHING: RefCell<Option<String>> = const { RefCell::new(None) }; // the list shows hits for this query+}++/// The list shows search hits for `q` (None: a folder again); the pill says so instead of showing the path.+pub fn set_search(q: Option<String>) { SEARCHING.set(q); }++/// Folder of the path part `i` of the address pill.+pub fn crumb_path(i: usize) -> Option<PathBuf> { CRUMBS.with_borrow(|c| c.get(i).map(|x| x.1.clone())) }++fn crumb_at(x: i32, y: i32) -> Option<usize> { CRUMBS.with_borrow(|c| c.iter().position(|(r, _)| inside(r, x, y))) }++/// Path parts with the folder each one opens: C:\Users\me -> [("C:", C:\), ("Users", C:\Users), ("me", C:\Users\me)].+fn crumbs_of(dir: &Path) -> Vec<(String, PathBuf)> {+ let mut acc = PathBuf::new();+ dir.components().filter_map(|c| {+ acc.push(c.as_os_str());+ match c {+ std::path::Component::RootDir => None, // folded into the drive part+ std::path::Component::Prefix(p) => { acc.push("\\"); Some((p.as_os_str().to_string_lossy().into_owned(), acc.clone())) }+ _ => Some((c.as_os_str().to_string_lossy().into_owned(), acc.clone())),+ }+ }).collect()+}++thread_local! {+ static SCALE: Cell<f32> = const { Cell::new(1.0) };+ static HV: RefCell<HashMap<i32, (f32, u64)>> = RefCell::new(HashMap::new()); // eased hover per element: (0..1, last update)+ static BUSY: Cell<bool> = const { Cell::new(false) }; // something is still easing: paint another frame+ static HOT: Cell<i32> = const { Cell::new(NONE) };+ static PRESS: Cell<(i32, u64)> = const { Cell::new((i32::MIN, 0)) };+ static BRUSH: Cell<isize> = const { Cell::new(0) }; // address box background+}++pub fn init_scale() {+ unsafe {+ let dc = GetDC(ptr::null_mut());+ SCALE.set(GetDeviceCaps(dc, LOGPIXELSX as i32) as f32 / 96.0);+ ReleaseDC(ptr::null_mut(), dc);+ }+}++pub fn sc(v: i32) -> i32 { (v as f32 * SCALE.get()).round() as i32 }++fn now() -> u64 { unsafe { GetTickCount64() } }++fn ease(t: f32) -> f32 { t * t * (3.0 - 2.0 * t) }++fn mix(a: u32, b: u32, t: f32) -> u32 {+ let ch = |s: u32| {+ let (x, y) = (((a >> s) & 255) as f32, ((b >> s) & 255) as f32);+ (x + (y - x) * t) as u32+ };+ ch(0) | ch(8) << 8 | ch(16) << 16+}++/// Eased 0..1 hover value of one element; keeps the painter running while it moves.+fn hv(key: i32, on: bool) -> f32 {+ let t = now();+ let target = if on { 1.0 } else { 0.0 };+ let v = HV.with_borrow_mut(|m| {+ let e = m.entry(key).or_insert((0.0, t));+ let dt = t.saturating_sub(e.1).min(50) as f32;+ e.1 = t;+ e.0 = if e.0 < target { (e.0 + dt / 120.0).min(target) } else { (e.0 - dt / 200.0).max(target) };+ e.0+ });+ if v != target { BUSY.set(true); }+ ease(v)+}++/// 1.0 right after a click, easing to 0 over 320 ms.+fn press_t(key: i32) -> f32 {+ let (k, t0) = PRESS.get();+ let t = now().saturating_sub(t0) as f32 / 320.0;+ if k != key || t >= 1.0 { return 0.0; }+ BUSY.set(true);+ (1.0 - t) * (1.0 - t)+}++pub fn font(px: i32, weight: i32, face: &str) -> isize {+ unsafe { CreateFontW(-sc(px), 0, 0, 0, weight, 0, 0, 0, 1, 0, 0, 5, 0, w(face).as_ptr()) as isize }+}++// ---------- window frame ----------++/// Dark title bar in the bar's colours, rounded corners.+pub fn dark_title(h: HWND) {+ unsafe {+ let set = |attr: u32, v: i32| { DwmSetWindowAttribute(h, attr, &v as *const _ as _, 4); };+ set(20, 1); // immersive dark mode+ set(33, 2); // round corners+ set(35, BG as i32); // caption+ set(36, TEXT as i32); // caption text+ set(34, LINE as i32); // border+ }+}++/// Dark context menus / scrollbars for the whole process (uxtheme's unnamed exports 135 and 136). Missing = stays light.+pub fn dark_mode() {+ unsafe {+ let m = LoadLibraryW(w("uxtheme.dll").as_ptr());+ if m.is_null() { return; }+ if let Some(f) = GetProcAddress(m, 135usize as *const u8) { std::mem::transmute::<_, extern "system" fn(i32) -> i32>(f)(2); } // SetPreferredAppMode(ForceDark)+ if let Some(f) = GetProcAddress(m, 136usize as *const u8) { std::mem::transmute::<_, extern "system" fn()>(f)(); } // FlushMenuThemes+ }+}++/// Dark list: themed scrollbars and header, own colours and font, taller rows.+pub fn style_list(list: HWND) {+ unsafe {+ SetWindowTheme(list, w("DarkMode_Explorer").as_ptr(), ptr::null());+ let hdr = SendMessageW(list, LVM_GETHEADER, 0, 0) as HWND;+ SetWindowTheme(hdr, w("DarkMode_ItemsView").as_ptr(), ptr::null());+ for (m, c) in [(LVM_SETBKCOLOR, LISTBG), (LVM_SETTEXTBKCOLOR, LISTBG), (LVM_SETTEXTCOLOR, TEXT)] { SendMessageW(list, m, 0, c as isize); }+ SendMessageW(list, WM_SETFONT, font(14, 400, "Segoe UI") as usize, 1);+ row_height(list, true);+ SetWindowSubclass(list, Some(list_sub), 1, 0); // paints the column header (the theme alone leaves it dim)+ }+}++pub const ROW_H: i32 = 36;++/// Details rows get ROW_H tall through an empty 1 px wide state image list (a row is as tall as its tallest image).+/// Off for the thumbnail view, where a state image would take room next to every thumbnail.+pub fn row_height(list: HWND, on: bool) {+ unsafe {+ let il = if on { ImageList_Create(1, sc(ROW_H), ILC_COLOR32, 1, 1) as isize } else { 0 };+ let old = SendMessageW(list, LVM_SETIMAGELIST, LVSIL_STATE as usize, il);+ if old != 0 { ImageList_Destroy(old as _); }+ }+}++thread_local! {+ static ROWHOT: Cell<isize> = const { Cell::new(-1) }; // list row under the pointer+ static FONTS: Cell<(isize, isize)> = const { Cell::new((0, 0)) }; // (name, details) fonts of the list rows+}++/// "Today, 09:48" / "Yesterday, 21:50" for recent files, the plain date otherwise.+fn friendly_date(ft: u64) -> String {+ let s = date_text(ft);+ let mut now: windows_sys::Win32::Foundation::FILETIME = unsafe { std::mem::zeroed() };+ unsafe { windows_sys::Win32::System::SystemInformation::GetSystemTimeAsFileTime(&mut now) };+ let now = (now.dwHighDateTime as u64) << 32 | now.dwLowDateTime as u64;+ let (today, yest) = (date_text(now), date_text(now.saturating_sub(864_000_000_000))); // 24 h in 100 ns ticks+ match s.get(..10) {+ Some(d) if s.len() >= 16 && today.get(..10) == Some(d) => format!("Today, {}", &s[11..]),+ Some(d) if s.len() >= 16 && yest.get(..10) == Some(d) => format!("Yesterday, {}", &s[11..]),+ _ => s,+ }+}++/// The details rows, painted by hand (NM_CUSTOMDRAW of the list): a rounded accent pill with a marker for the selection,+/// a soft one under the pointer, the name bright and the rest dimmed. The thumbnail view keeps the list's own drawing.+pub unsafe fn list_draw(lp: LPARAM) -> LRESULT {+ let cd = &*(lp as *const NMLVCUSTOMDRAW);+ let list = cd.nmcd.hdr.hwndFrom;+ if ST.with(|c| c.try_borrow().map_or(true, |s| s.thumbs)) { return CDRF_DODEFAULT as isize; }+ let dc = cd.nmcd.hdc;+ let mut cr: RECT = std::mem::zeroed();+ GetClientRect(list, &mut cr);+ match cd.nmcd.dwDrawStage {+ CDDS_PREPAINT => (CDRF_NOTIFYITEMDRAW | CDRF_NOTIFYPOSTPAINT) as isize,+ CDDS_POSTPAINT => {+ if SendMessageW(list, LVM_GETITEMCOUNT, 0, 0) == 0 {+ // an empty folder says so instead of showing a blank list+ let (f_big, f_txt) = (font(40, 400, "Segoe MDL2 Assets") as HFONT, font(14, 400, "Segoe UI") as HFONT);+ SetBkMode(dc, TRANSPARENT as i32);+ let mid = cr.bottom / 3;+ let of = SelectObject(dc, f_big);+ text(dc, "\u{E8B7}", rc(0, mid - sc(40), cr.right, mid + sc(10)), mix(LISTBG, DIM, 0.5), DT_CENTER);+ SelectObject(dc, f_txt);+ let msg = if SEARCHING.with_borrow(|s| s.is_some()) { "Nothing found" } else { "This folder is empty" };+ text(dc, msg, rc(0, mid + sc(14), cr.right, mid + sc(40)), DIM, DT_CENTER);+ SelectObject(dc, of);+ DeleteObject(f_big);+ DeleteObject(f_txt);+ }+ CDRF_DODEFAULT as isize+ }+ CDDS_ITEMPREPAINT => {+ let i = cd.nmcd.dwItemSpec;+ let row = ST.with(|c| {+ let mut st = c.try_borrow_mut().ok()?;+ let State { dir, rows, .. } = &mut *st;+ let r = rows.get_mut(i)?;+ if r.icon < 0 { r.icon = icon_of(&dir.join(&r.name), r.dir); }+ Some((r.name.clone(), r.dir, r.time, r.size, r.icon))+ });+ let Some((name, is_dir, time, size, icon)) = row else { return CDRF_DODEFAULT as isize };+ let mut r = RECT { left: LVIR_BOUNDS as i32, ..std::mem::zeroed() };+ SendMessageW(list, LVM_GETITEMRECT, i, &mut r as *mut _ as isize);+ let row_r = rc(0, r.top, cr.right, r.bottom);+ let b = CreateSolidBrush(LISTBG);+ FillRect(dc, &row_r, b);+ DeleteObject(b);+ let sel = SendMessageW(list, LVM_GETITEMSTATE, i, LVIS_SELECTED as isize) as u32 & LVIS_SELECTED != 0;+ let hot = ROWHOT.get() == i as isize;+ let focus = GetFocus() == list;+ let pill = rc(sc(6), r.top + sc(2), cr.right - sc(6), r.bottom - sc(2));+ let bg = match (sel, focus) {+ (true, true) => mix(LISTBG, ACCENT, if hot { 0.26 } else { 0.20 }),+ (true, false) => mix(LISTBG, TEXT, 0.10),+ _ if hot => mix(LISTBG, TEXT, 0.055),+ _ => LISTBG,+ };+ if bg != LISTBG { fill(dc, pill, bg, sc(10)); }+ if sel { fill(dc, rc(pill.left, pill.top + sc(8), pill.left + sc(3), pill.bottom - sc(8)), if focus { ACCENT } else { DIM }, sc(3)); }+ // columns from the header widths (left of the row = minus the horizontal scroll)+ let cw: Vec<i32> = (0..4).map(|k| SendMessageW(list, LVM_GETCOLUMNWIDTH, k, 0) as i32).collect();+ let x: Vec<i32> = (0..4).map(|k| r.left + cw[..k].iter().sum::<i32>()).collect();+ let himl = SendMessageW(list, LVM_GETIMAGELIST, LVSIL_SMALL as usize, 0);+ let (mut iw, mut ih) = (0, 0);+ ImageList_GetIconSize(himl as _, &mut iw, &mut ih);+ if icon >= 0 { ImageList_Draw(himl as _, icon, dc, x[0] + sc(16), (r.top + r.bottom - ih) / 2, ILD_TRANSPARENT); }+ if FONTS.get().0 == 0 { FONTS.set((font(14, 400, "Segoe UI"), font(13, 400, "Segoe UI"))); }+ let (f_name, f_det) = FONTS.get();+ SetBkMode(dc, TRANSPARENT as i32);+ let of = SelectObject(dc, f_name as HFONT);+ let p = Path::new(&name);+ let hit_of_search = p.is_absolute(); // search hits are absolute paths: show the name, and where it lies in the type column+ let shown = if hit_of_search { p.file_name().map_or(name.clone(), |n| n.to_string_lossy().into_owned()) } else { name.clone() };+ text(dc, &shown, rc(x[0] + sc(16) + iw + sc(12), r.top, x[1] - sc(8), r.bottom), TEXT, DT_LEFT);+ SelectObject(dc, f_det as HFONT);+ let dim = if sel { mix(DIM, TEXT, 0.45) } else { DIM };+ text(dc, &friendly_date(time), rc(x[1] + sc(10), r.top, x[2] - sc(8), r.bottom), dim, DT_LEFT);+ let kind = if hit_of_search { p.parent().map_or(String::new(), |d| d.to_string_lossy().into_owned()) } else { type_text(&name, is_dir) };+ text(dc, &kind, rc(x[2] + sc(10), r.top, x[3] - sc(8), r.bottom), dim, DT_LEFT | DT_PATH_ELLIPSIS);+ if !is_dir { text(dc, &size_text(size), rc(x[3], r.top, x[3] + cw[3] - sc(14), r.bottom), dim, DT_RIGHT); }+ SelectObject(dc, of);+ CDRF_SKIPDEFAULT as isize+ }+ _ => CDRF_DODEFAULT as isize,+ }+}++/// Name column takes what the other three leave, so the list never needs a horizontal scrollbar.+pub unsafe fn fit_columns(list: HWND) {+ let mut cr: RECT = std::mem::zeroed();+ GetClientRect(list, &mut cr);+ let rest: i32 = (1..4).map(|k| SendMessageW(list, LVM_GETCOLUMNWIDTH, k, 0) as i32).sum();+ SendMessageW(list, LVM_SETCOLUMNWIDTH, 0, (cr.right - rest).max(sc(200)) as isize);+}++/// Repaints one row (hover moved on or off it).+unsafe fn redraw_row(list: HWND, i: isize) {+ if i < 0 { return; }+ let mut r = RECT { left: LVIR_BOUNDS as i32, ..std::mem::zeroed() };+ if SendMessageW(list, LVM_GETITEMRECT, i as usize, &mut r as *mut _ as isize) != 0 {+ let mut cr: RECT = std::mem::zeroed();+ GetClientRect(list, &mut cr);+ InvalidateRect(list, &rc(0, r.top, cr.right, r.bottom), 0);+ }+}++/// Column header, drawn by hand: bar colour, white / dim title, a sort arrow on the sorted column. The header reports its+/// custom draw to its parent, the list, so the hook sits on the list.+unsafe extern "system" fn list_sub(h: HWND, m: u32, wp: WPARAM, lp: LPARAM, _id: usize, _data: usize) -> LRESULT {+ if m == WM_MOUSEMOVE {+ // hover row for list_draw+ let mut ht: LVHITTESTINFO = std::mem::zeroed();+ ht.pt = POINT { x: (lp & 0xFFFF) as i16 as i32, y: ((lp >> 16) & 0xFFFF) as i16 as i32 };+ let i = SendMessageW(h, LVM_HITTEST, 0, &mut ht as *mut _ as isize);+ let old = ROWHOT.replace(i);+ if old != i {+ redraw_row(h, old);+ redraw_row(h, i);+ let mut tme = TRACKMOUSEEVENT { cbSize: size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE, hwndTrack: h, dwHoverTime: 0 };+ TrackMouseEvent(&mut tme);+ }+ } else if m == WM_MOUSELEAVE {+ redraw_row(h, ROWHOT.replace(-1));+ } else if m == WM_SETFOCUS || m == WM_KILLFOCUS {+ InvalidateRect(h, ptr::null(), 0); // the selection is accent-coloured only while the list has the focus+ }+ if m == WM_NOTIFY {+ let nm = &*(lp as *const NMCUSTOMDRAW);+ let hdr = SendMessageW(h, LVM_GETHEADER, 0, 0) as HWND;+ if nm.hdr.hwndFrom == hdr && nm.hdr.code == NM_CUSTOMDRAW {+ return match nm.dwDrawStage {+ CDDS_PREPAINT => {+ let b = CreateSolidBrush(BG); // the bar behind the columns too+ FillRect(nm.hdc, &nm.rc, b);+ DeleteObject(b);+ CDRF_NOTIFYITEMDRAW as isize+ }+ CDDS_ITEMPREPAINT => {+ let (dc, r, i) = (nm.hdc, nm.rc, nm.dwItemSpec);+ let b = CreateSolidBrush(BG);+ FillRect(dc, &r, b);+ DeleteObject(b);+ fill(dc, rc(r.right - 1, r.top + sc(8), r.right, r.bottom - sc(8)), LINE, 0);+ let mut buf = [0u16; 128];+ let mut it: HDITEMW = std::mem::zeroed();+ it.mask = HDI_TEXT;+ it.pszText = buf.as_mut_ptr();+ it.cchTextMax = 128;+ SendMessageW(hdr, HDM_GETITEMW, i, &mut it as *mut _ as isize);+ let sorted = SORT_COL.load(Relaxed) == i;+ let arrow = if !sorted { "" } else if SORT_ASC.load(Relaxed) { " \u{2191}" } else { " \u{2193}" };+ let f = font(13, if sorted { 600 } else { 400 }, "Segoe UI") as HFONT;+ let of = SelectObject(dc, f);+ SetBkMode(dc, TRANSPARENT as i32);+ let align = if i == 3 { DT_RIGHT } else { DT_LEFT }; // the size column is right-aligned like its numbers+ text(dc, &format!("{}{arrow}", wstr(buf.as_ptr())), rc(r.left + sc(10), r.top, r.right - sc(12), r.bottom), if sorted { TEXT } else { DIM }, align);+ SelectObject(dc, of);+ DeleteObject(f);+ CDRF_SKIPDEFAULT as isize+ }+ _ => 0,+ };+ }+ }+ DefSubclassProc(h, m, wp, lp)+}++// ---------- layout and hit testing ----------++struct Layout { tabs: Vec<RECT>, close: Vec<RECT>, plus: RECT, back: RECT, fwd: RECT, up: RECT, reload: RECT, pill: RECT, search: RECT, view: RECT }++fn rc(l: i32, t: i32, r: i32, b: i32) -> RECT { RECT { left: l, top: t, right: r, bottom: b } }++fn layout(cw: i32, n: usize) -> Layout {+ let (ty0, ty1) = (sc(8), sc(36));+ let tw = ((cw - sc(12) * 2 - sc(36)) / n.max(1) as i32 - sc(4)).clamp(sc(90), sc(220));+ let tabs: Vec<RECT> = (0..n as i32).map(|i| { let l = sc(12) + i * (tw + sc(4)); rc(l, ty0, l + tw, ty1) }).collect();+ let close = tabs.iter().map(|t| rc(t.right - sc(26), (t.top + t.bottom) / 2 - sc(10), t.right - sc(6), (t.top + t.bottom) / 2 + sc(10))).collect();+ let px = tabs.last().map_or(sc(12), |t| t.right + sc(4));+ let plus = rc(px, ty0 + sc(2), px + sc(26), ty1 - sc(2));+ let (by0, by1, bs) = (sc(44), sc(80), sc(36));+ let btn = |i: i32| rc(sc(12) + i * (bs + sc(4)), by0, sc(12) + i * (bs + sc(4)) + bs, by1);+ let view = rc(cw - sc(12) - bs, by0, cw - sc(12), by1);+ let search = rc(view.left - sc(4) - bs, by0, view.left - sc(4), by1);+ let reload = btn(3);+ let pill = rc(reload.right + sc(8), by0, search.left - sc(8), by1);+ Layout { tabs, close, plus, back: btn(0), fwd: btn(1), up: btn(2), reload, pill, search, view }+}++fn inside(r: &RECT, x: i32, y: i32) -> bool { x >= r.left && x < r.right && y >= r.top && y < r.bottom }++fn hit(l: &Layout, x: i32, y: i32) -> i32 {+ for (i, c) in l.close.iter().enumerate() { if inside(c, x, y) && l.tabs.len() > 1 { return CLOSE + i as i32; } }+ for (i, t) in l.tabs.iter().enumerate() { if inside(t, x, y) { return TAB + i as i32; } }+ for (k, r) in [(BACK, &l.back), (FWD, &l.fwd), (UP, &l.up), (RELOAD, &l.reload), (SEARCH, &l.search), (VIEW, &l.view), (PLUS, &l.plus)] {+ if inside(r, x, y) { return k; }+ }+ NONE+}++/// Puts the address box inside the pill.+pub fn place_edit(chrome: HWND) {+ unsafe {+ let edit = ST.with(|c| c.try_borrow().map_or(ptr::null_mut(), |s| s.edit));+ if edit.is_null() { return; }+ let mut r: RECT = std::mem::zeroed();+ GetClientRect(chrome, &mut r);+ let p = layout(r.right, 1).pill;+ let eh = sc(20);+ MoveWindow(edit, p.left + sc(40), (p.top + p.bottom - eh) / 2, (p.right - p.left - sc(40) - sc(16)).max(0), eh, 1);+ if GetFocus() != edit { ShowWindow(edit, SW_HIDE); } // the path parts are painted instead until the pill is clicked+ }+}++// ---------- painting ----------++/// GDI+ for anti-aliased rounded shapes (started once in main); fill() falls back to plain GDI without it.+pub fn gdiplus_start() {+ use windows_sys::Win32::Graphics::GdiPlus::{GdiplusStartup, GdiplusStartupInput};+ unsafe {+ let (mut tok, mut inp): (usize, GdiplusStartupInput) = (0, std::mem::zeroed());+ inp.GdiplusVersion = 1;+ GdiplusStartup(&mut tok, &inp, ptr::null_mut());+ }+}++/// Fills `r` (right / bottom exclusive) in `c`; `rad` > 0 rounds the corners (rad = corner diameter), anti-aliased.+unsafe fn fill(dc: HDC, r: RECT, c: u32, rad: i32) {+ use windows_sys::Win32::Graphics::GdiPlus::*;+ let (wd, ht) = ((r.right - r.left) as f32, (r.bottom - r.top) as f32);+ if wd <= 0.0 || ht <= 0.0 { return; }+ let mut g: *mut GpGraphics = ptr::null_mut();+ if rad <= 0 || GdipCreateFromHDC(dc, &mut g) != 0 || g.is_null() {+ let b = CreateSolidBrush(c);+ if rad <= 0 {+ FillRect(dc, &r, b);+ } else {+ let (ob, op) = (SelectObject(dc, b), SelectObject(dc, GetStockObject(NULL_PEN)));+ RoundRect(dc, r.left, r.top, r.right + 1, r.bottom + 1, rad, rad);+ SelectObject(dc, ob);+ SelectObject(dc, op);+ }+ DeleteObject(b);+ return;+ }+ GdipSetSmoothingMode(g, SmoothingModeAntiAlias);+ GdipSetPixelOffsetMode(g, PixelOffsetModeHalf); // pixel i spans [i, i+1): straight edges stay crisp+ let (x, y, d) = (r.left as f32, r.top as f32, (rad as f32).min(wd).min(ht));+ let mut path: *mut GpPath = ptr::null_mut();+ GdipCreatePath(FillModeAlternate, &mut path);+ GdipAddPathArc(path, x, y, d, d, 180.0, 90.0);+ GdipAddPathArc(path, x + wd - d, y, d, d, 270.0, 90.0);+ GdipAddPathArc(path, x + wd - d, y + ht - d, d, d, 0.0, 90.0);+ GdipAddPathArc(path, x, y + ht - d, d, d, 90.0, 90.0);+ GdipClosePathFigure(path);+ let mut br: *mut GpSolidFill = ptr::null_mut();+ GdipCreateSolidFill(0xFF00_0000 | (c & 255) << 16 | (c & 0xFF00) | (c >> 16 & 255), &mut br); // COLORREF -> ARGB+ GdipFillPath(g, br as *mut GpBrush, path);+ GdipDeleteBrush(br as *mut GpBrush);+ GdipDeletePath(path);+ GdipDeleteGraphics(g);+}++unsafe fn text(dc: HDC, s: &str, mut r: RECT, c: u32, flags: u32) {+ SetTextColor(dc, c);+ DrawTextW(dc, w(s).as_ptr(), -1, &mut r, flags | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS);+}++/// A rounded highlight that eases in on hover and flashes in the accent colour on click; `base` is what it sits on.+unsafe fn glow(dc: HDC, key: i32, r: RECT, base: u32, to: u32, rad: i32, on: bool) {+ let (t, p) = (hv(key, on), press_t(key));+ if t > 0.01 || p > 0.0 { fill(dc, r, mix(mix(base, to, t), ACCENT, 0.45 * p), rad); }+}++unsafe fn paint_chrome(hwnd: HWND) {+ let mut ps: PAINTSTRUCT = std::mem::zeroed();+ let wdc = BeginPaint(hwnd, &mut ps);+ let mut cr: RECT = std::mem::zeroed();+ GetClientRect(hwnd, &mut cr);+ // everything painting needs from the window state, copied out so nothing is borrowed while drawing+ let snap = ST.with(|c| c.try_borrow().ok().map(|s| (s.tabs.iter().map(label).collect::<Vec<_>>(), s.active, s.hist.pos > 0, s.hist.pos + 1 < s.hist.v.len(), s.thumbs, s.edit, s.dir.clone())));+ let Some((labels, active, can_back, can_fwd, thumbs, edit, dir)) = snap else { EndPaint(hwnd, &ps); return };+ BUSY.set(false);+ let (dc, bmp) = (CreateCompatibleDC(wdc), CreateCompatibleBitmap(wdc, cr.right, cr.bottom));+ let old = SelectObject(dc, bmp);+ let bg = CreateSolidBrush(BG);+ FillRect(dc, &cr, bg);+ DeleteObject(bg);+ SetBkMode(dc, TRANSPARENT as i32);+ let l = layout(cr.right, labels.len());+ let hot = HOT.get();+ let (f_txt, f_glyph, f_small) = (font(13, 400, "Segoe UI") as HFONT, font(16, 400, "Segoe MDL2 Assets") as HFONT, font(12, 400, "Segoe MDL2 Assets") as HFONT);+ let of = SelectObject(dc, f_txt);++ // tabs+ for (i, t) in l.tabs.iter().enumerate() {+ let on = i == active;+ let (th, ta) = (hv(TAB + i as i32, hot == TAB + i as i32 || hot == CLOSE + i as i32), hv(1000 + i as i32, on));+ let p = press_t(TAB + i as i32);+ fill(dc, *t, mix(mix(mix(BG, HOVER, th), ACTIVE, ta), ACCENT, 0.35 * p), sc(8));+ if ta > 0.01 { fill(dc, rc(t.left + (t.right - t.left) / 2 - sc(12), t.bottom - sc(3), t.left + (t.right - t.left) / 2 + sc(12), t.bottom), mix(ACTIVE, ACCENT, ta), sc(3)); }+ SelectObject(dc, f_txt);+ text(dc, &labels[i], rc(t.left + sc(14), t.top, t.right - sc(if labels.len() > 1 { 30 } else { 10 }), t.bottom), mix(DIM, TEXT, ta.max(th)), DT_LEFT);+ if labels.len() > 1 && (on || th > 0.05) {+ let c = l.close[i];+ glow(dc, CLOSE + i as i32, c, mix(BG, ACTIVE, ta), HOVER, sc(6), hot == CLOSE + i as i32);+ SelectObject(dc, f_small);+ text(dc, "\u{E711}", c, mix(DIM, TEXT, if hot == CLOSE + i as i32 { 1.0 } else { 0.4 }), DT_CENTER);+ }+ }+ glow(dc, PLUS, l.plus, BG, HOVER, sc(6), hot == PLUS);+ SelectObject(dc, f_small);+ text(dc, "\u{E710}", l.plus, DIM, DT_CENTER);++ // toolbar buttons+ SelectObject(dc, f_glyph);+ for (k, r, g, enabled) in [(BACK, l.back, "\u{E72B}", can_back), (FWD, l.fwd, "\u{E72A}", can_fwd), (UP, l.up, "\u{E74A}", true), (RELOAD, l.reload, "\u{E72C}", true), (SEARCH, l.search, "\u{E721}", true), (VIEW, l.view, if thumbs { "\u{E8FD}" } else { "\u{E80A}" }, true)] {+ if enabled { glow(dc, k, r, BG, HOVER, sc(8), hot == k); }+ text(dc, g, r, if enabled { TEXT } else { OFF }, DT_CENTER);+ }++ // address pill: accent outline while it is being edited+ let focused = !edit.is_null() && GetFocus() == edit;+ let f = hv(2000, focused);+ fill(dc, l.pill, mix(LINE, ACCENT, f), sc(18));+ fill(dc, rc(l.pill.left + 1, l.pill.top + 1, l.pill.right - 1, l.pill.bottom - 1), PILL, sc(17));+ SelectObject(dc, f_glyph);+ let searching = SEARCHING.with_borrow(|s| s.clone());+ text(dc, if searching.is_some() { "\u{E721}" } else { "\u{E838}" }, rc(l.pill.left + sc(10), l.pill.top, l.pill.left + sc(38), l.pill.bottom), mix(DIM, ACCENT, f), DT_CENTER);+ // not being edited: the path as clickable parts, like Windows 11 Explorer ("C: > Users > me"); the edit box is hidden+ let mut crumbs = vec![];+ if !focused {+ let (x0, x1) = (l.pill.left + sc(40), l.pill.right - sc(12));+ let (t, b) = (l.pill.top + sc(5), l.pill.bottom - sc(5));+ if let Some(q) = &searching {+ SelectObject(dc, f_txt);+ text(dc, &format!("Results for \u{201C}{q}\u{201D}"), rc(x0 + sc(6), l.pill.top, x1, l.pill.bottom), ACCENT, DT_LEFT);+ } else {+ let parts = crumbs_of(&dir);+ let width = |s: &str| { let mut r = rc(0, 0, 0, 0); DrawTextW(dc, w(s).as_ptr(), -1, &mut r, DT_CALCRECT | DT_SINGLELINE | DT_NOPREFIX); r.right + sc(16) };+ let chev = sc(18);+ SelectObject(dc, f_txt);+ let ws: Vec<i32> = parts.iter().map(|p| width(&p.0)).collect();+ // too long: drop parts from the left; a "..." part then opens the last one dropped+ let mut first = 0;+ while first + 1 < parts.len() && ws[first..].iter().sum::<i32>() + chev * (parts.len() - first) as i32 + width("\u{2026}") > x1 - x0 { first += 1; }+ let mut shown: Vec<(String, PathBuf, i32)> = vec![];+ if first > 0 { shown.push(("\u{2026}".into(), parts[first - 1].1.clone(), width("\u{2026}"))); }+ shown.extend(parts[first..].iter().zip(&ws[first..]).map(|(p, &wd)| (p.0.clone(), p.1.clone(), wd)));+ let mut x = x0;+ let last = shown.len().saturating_sub(1);+ for (i, (label, path, wd)) in shown.into_iter().enumerate() {+ let r = rc(x, t, (x + wd).min(x1), b);+ glow(dc, CRUMB + i as i32, r, PILL, HOVER, sc(8), hot == CRUMB + i as i32);+ SelectObject(dc, f_txt);+ text(dc, &label, r, if i == last { TEXT } else { mix(DIM, TEXT, if hot == CRUMB + i as i32 { 1.0 } else { 0.35 }) }, DT_CENTER);+ crumbs.push((r, path));+ x = r.right;+ if i < last {+ SelectObject(dc, f_small);+ text(dc, "\u{E76C}", rc(x, t, x + chev, b), mix(DIM, PILL, 0.3), DT_CENTER);+ x += chev;+ }+ }+ }+ }+ CRUMBS.set(crumbs);++ fill(dc, rc(0, cr.bottom - 1, cr.right, cr.bottom), LINE, 0); // hairline under the chrome+ BitBlt(wdc, 0, 0, cr.right, cr.bottom, dc, 0, 0, SRCCOPY);+ SelectObject(dc, of);+ for f in [f_txt, f_glyph, f_small] { DeleteObject(f); }+ SelectObject(dc, old);+ DeleteObject(bmp);+ DeleteDC(dc);+ if BUSY.get() { SetTimer(hwnd, 4, 16, None); } else { KillTimer(hwnd, 4); }+ EndPaint(hwnd, &ps);+}++/// Item / selection counts and the sort order, along the bottom edge.+pub unsafe fn paint_status(h: HWND) {+ let mut ps: PAINTSTRUCT = std::mem::zeroed();+ let dc = BeginPaint(h, &mut ps);+ let mut cr: RECT = std::mem::zeroed();+ GetClientRect(h, &mut cr);+ let strip = rc(0, cr.bottom - sc(STATUS_H), cr.right, cr.bottom);+ let bg = CreateSolidBrush(BG);+ FillRect(dc, &strip, bg);+ DeleteObject(bg);+ fill(dc, rc(0, strip.top, cr.right, strip.top + 1), LINE, 0); // hairline above the status line+ let snap = ST.with(|c| {+ c.try_borrow().ok().map(|s| {+ // selected count and the total size of the selected files+ let (mut n, mut bytes, mut i) = (0usize, 0u64, -1isize);+ loop {+ i = SendMessageW(s.list, LVM_GETNEXTITEM, i as usize, LVNI_SELECTED as isize);+ let Some(r) = usize::try_from(i).ok().and_then(|i| s.rows.get(i)) else { break };+ n += 1;+ if !r.dir { bytes += r.size; }+ }+ (s.rows.len(), n, bytes)+ })+ });+ if let Some((n, sel, bytes)) = snap {+ let items = |k: usize| format!("{k} item{}", if k == 1 { "" } else { "s" });+ let left = match (sel, bytes) {+ (0, _) => items(n),+ (s, 0) => format!("{} \u{00B7} {s} selected", items(n)),+ (s, b) => format!("{} \u{00B7} {s} selected \u{00B7} {}", items(n), size_text(b)),+ };+ let by = ["Name", "Date", "Type", "Size"][SORT_COL.load(Relaxed).min(3)];+ let right = format!("{by} {}", if SORT_ASC.load(Relaxed) { "\u{2191}" } else { "\u{2193}" });+ let f = font(12, 400, "Segoe UI") as HFONT;+ let of = SelectObject(dc, f);+ SetBkMode(dc, TRANSPARENT as i32);+ text(dc, &left, rc(strip.left + sc(14), strip.top, strip.right / 2, strip.bottom), DIM, DT_LEFT);+ text(dc, &right, rc(strip.right / 2, strip.top, strip.right - sc(14), strip.bottom), DIM, DT_RIGHT);+ SelectObject(dc, of);+ DeleteObject(f);+ }+ EndPaint(h, &ps);+}++pub unsafe fn status_dirty(h: HWND) {+ let mut cr: RECT = std::mem::zeroed();+ GetClientRect(h, &mut cr);+ let strip = rc(0, cr.bottom - sc(STATUS_H), cr.right, cr.bottom);+ InvalidateRect(h, &strip, 0);+}++// ---------- chrome window ----------++pub unsafe extern "system" fn proc(h: HWND, m: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {+ let (x, y) = ((lp & 0xFFFF) as i16 as i32, ((lp >> 16) & 0xFFFF) as i16 as i32);+ let layout_now = || {+ let mut r: RECT = std::mem::zeroed();+ GetClientRect(h, &mut r);+ layout(r.right, ST.with(|c| c.try_borrow().map_or(1, |s| s.tabs.len())))+ };+ match m {+ WM_PAINT => paint_chrome(h),+ WM_ERASEBKGND => return 1,+ WM_SIZE => { place_edit(h); InvalidateRect(h, ptr::null(), 0); } // the pill and the tabs re-flow: repaint it all+ WM_TIMER if wp == 4 => { InvalidateRect(h, ptr::null(), 0); }+ WM_MOUSEMOVE => {+ let k = match hit(&layout_now(), x, y) { NONE => crumb_at(x, y).map_or(NONE, |i| CRUMB + i as i32), k => k };+ let mut tme = TRACKMOUSEEVENT { cbSize: size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE, hwndTrack: h, dwHoverTime: 0 };+ TrackMouseEvent(&mut tme);+ if HOT.replace(k) != k { InvalidateRect(h, ptr::null(), 0); }+ }+ WM_MOUSELEAVE => {+ HOT.set(NONE);+ InvalidateRect(h, ptr::null(), 0);+ }+ WM_LBUTTONDOWN | WM_MBUTTONDOWN => {+ let l = layout_now();+ let k = hit(&l, x, y);+ if k == NONE {+ if let Some(i) = crumb_at(x, y) {+ PRESS.set((CRUMB + i as i32, now()));+ PostMessageW(GetParent(h), WM_UI, 21, i as isize); // a path part: go there+ } else if inside(&l.pill, x, y) {+ // the rest of the pill: type a path+ let edit = ST.with(|c| c.try_borrow().map_or(ptr::null_mut(), |s| s.edit));+ SetFocus(edit);+ SendMessageW(edit, EM_SETSEL, 0, -1);+ }+ InvalidateRect(h, ptr::null(), 0);+ return 0;+ }+ PRESS.set((k, now()));+ InvalidateRect(h, ptr::null(), 0);+ let (act, idx) = match k {+ BACK => (4, 0), FWD => (5, 0), UP => (6, 0), RELOAD => (7, 0), SEARCH => (9, 0), VIEW => (8, 0), PLUS => (3, 0),+ k if k >= CLOSE => (2, (k - CLOSE) as isize),+ k => (if m == WM_MBUTTONDOWN { 2 } else { 1 }, (k - TAB) as isize), // middle click on a tab closes it+ };+ PostMessageW(GetParent(h), WM_UI, act, idx);+ }+ WM_COMMAND if (wp >> 16) == 0x0100 || (wp >> 16) == 0x0200 => {+ // edit got / lost focus: shown only while typing (the path parts otherwise), outline colour+ ShowWindow(lp as HWND, if (wp >> 16) == 0x0100 { SW_SHOW } else { SW_HIDE });+ InvalidateRect(h, ptr::null(), 0);+ }+ WM_CTLCOLOREDIT => {+ // the address box: white text on the pill's colour+ let dc = wp as HDC;+ SetTextColor(dc, TEXT);+ SetBkColor(dc, PILL);+ if BRUSH.get() == 0 { BRUSH.set(CreateSolidBrush(PILL) as isize); }+ return BRUSH.get();+ }+ _ => return DefWindowProcW(h, m, wp, lp),+ }+ 0+}+++// ---------- navigation pane (left): quick access folders and the drives, like Explorer's ----------++pub const NAV_W: i32 = 232;+const NAV_ROW: i32 = 34;+const NAV_HEAD: i32 = 32;++struct NavItem { title: String, path: PathBuf, glyph: &'static str, cap: Option<(u64, u64)> } // empty path = section heading; cap = (free, total) bytes of a drive++const NAV_DRIVE: i32 = 52; // a drive row also shows how full it is++fn nav_h(it: &NavItem) -> i32 {+ sc(if it.path.as_os_str().is_empty() { NAV_HEAD } else if it.cap.is_some() { NAV_DRIVE } else { NAV_ROW })+}++thread_local! {+ static NAV: RefCell<Vec<NavItem>> = const { RefCell::new(Vec::new()) };+ static NAVWND: Cell<isize> = const { Cell::new(0) };+ static NAVHOT: Cell<i32> = const { Cell::new(-1) };+}++pub fn nav_init(h: HWND) {+ NAVWND.set(h as isize);+ let home = PathBuf::from(env::var_os("USERPROFILE").unwrap_or_default());+ let head = |t: &str| NavItem { title: t.into(), path: PathBuf::new(), glyph: "", cap: None };+ let mut v = vec![head("Quick access"), NavItem { title: "Home".into(), path: home.clone(), glyph: "\u{E80F}", cap: None }];+ for (t, sub, g) in [("Desktop", "Desktop", "\u{E7F4}"), ("Downloads", "Downloads", "\u{E896}"), ("Documents", "Documents", "\u{E8A5}"), ("Pictures", "Pictures", "\u{E91B}"), ("Music", "Music", "\u{E8D6}"), ("Videos", "Videos", "\u{E714}")] {+ let p = home.join(sub);+ if p.is_dir() { v.push(NavItem { title: t.into(), path: p, glyph: g, cap: None }); }+ }+ v.push(head("This PC"));+ unsafe {+ use windows_sys::Win32::Storage::FileSystem::{GetDiskFreeSpaceExW, GetDriveTypeW, GetLogicalDrives, GetVolumeInformationW};+ let mask = GetLogicalDrives();+ for i in 0..26u32 {+ if mask & (1 << i) == 0 { continue; }+ let letter = (b'A' + i as u8) as char;+ let root = format!("{letter}:\\");+ // fixed and removable disks only: asking a dead network share for its label would stall the window+ if !matches!(GetDriveTypeW(w(&root).as_ptr()), 2 | 3) { continue; }+ let mut label = [0u16; 64];+ let ok = GetVolumeInformationW(w(&root).as_ptr(), label.as_mut_ptr(), 64, ptr::null_mut(), ptr::null_mut(), ptr::null_mut(), ptr::null_mut(), 0);+ let name = if ok != 0 { wstr(label.as_ptr()) } else { String::new() };+ let (mut free, mut total) = (0u64, 0u64);+ let cap = (GetDiskFreeSpaceExW(w(&root).as_ptr(), &mut free, &mut total, ptr::null_mut()) != 0 && total > 0).then_some((free, total));+ v.push(NavItem { title: format!("{} ({letter}:)", if name.is_empty() { "Local Disk" } else { &name }), path: PathBuf::from(root), glyph: "\u{EDA2}", cap });+ }+ }+ NAV.with_borrow_mut(|n| *n = v);+}++pub fn nav_path(i: usize) -> Option<PathBuf> {+ NAV.with_borrow(|n| n.get(i).map(|x| x.path.clone()).filter(|p| !p.as_os_str().is_empty()))+}++pub fn nav_dirty() {+ let h = NAVWND.get() as HWND;+ if !h.is_null() { unsafe { InvalidateRect(h, ptr::null(), 0) }; }+}++/// Chrome on top, the pane on the left (hidden when the window is narrow), the list takes the rest.+pub unsafe fn layout_children(cw: i32, ch: i32) {+ let (chrome, list) = ST.with(|c| c.try_borrow().map_or((ptr::null_mut(), ptr::null_mut()), |s| (s.tab, s.list)));+ let nav = NAVWND.get() as HWND;+ let (top, status) = (sc(CHROME_H), sc(STATUS_H));+ let nw = if cw > sc(760) { sc(NAV_W) } else { 0 };+ let h = (ch - top - status).max(0);+ MoveWindow(chrome, 0, 0, cw, top, 1);+ MoveWindow(nav, 0, top, nw, h, 1);+ MoveWindow(list, nw, top, cw - nw, h, 1);+ fit_columns(list);+}++/// Item under y (None over headings or empty space).+fn nav_hit(y: i32) -> Option<usize> {+ let mut top = sc(8);+ NAV.with_borrow(|n| {+ for (i, it) in n.iter().enumerate() {+ let hgt = nav_h(it);+ if y >= top && y < top + hgt { return (!it.path.as_os_str().is_empty()).then_some(i); }+ top += hgt;+ }+ None+ })+}++unsafe fn paint_nav(hwnd: HWND) {+ let mut ps: PAINTSTRUCT = std::mem::zeroed();+ let wdc = BeginPaint(hwnd, &mut ps);+ let mut cr: RECT = std::mem::zeroed();+ GetClientRect(hwnd, &mut cr);+ BUSY.set(false);+ let (dc, bmp) = (CreateCompatibleDC(wdc), CreateCompatibleBitmap(wdc, cr.right.max(1), cr.bottom.max(1)));+ let old = SelectObject(dc, bmp);+ let bg = CreateSolidBrush(BG);+ FillRect(dc, &cr, bg);+ DeleteObject(bg);+ SetBkMode(dc, TRANSPARENT as i32);+ let (f_txt, f_head, f_glyph, f_small) = (font(13, 400, "Segoe UI") as HFONT, font(12, 600, "Segoe UI") as HFONT, font(16, 400, "Segoe MDL2 Assets") as HFONT, font(11, 400, "Segoe UI") as HFONT);+ let of = SelectObject(dc, f_txt);+ // where we are = the deepest item that contains the current folder+ let cur = ST.with(|c| c.try_borrow().ok().map(|s| s.dir.to_string_lossy().to_lowercase())).unwrap_or_default();+ let hot = NAVHOT.get();+ NAV.with_borrow(|n| {+ let here = n.iter().enumerate().filter(|(_, it)| !it.path.as_os_str().is_empty() && cur.starts_with(&it.path.to_string_lossy().to_lowercase())).max_by_key(|(_, it)| it.path.as_os_str().len()).map(|(i, _)| i);+ let mut y = sc(8);+ for (i, it) in n.iter().enumerate() {+ if it.path.as_os_str().is_empty() {+ SelectObject(dc, f_head);+ text(dc, &it.title.to_uppercase(), rc(sc(18), y + sc(6), cr.right - sc(8), y + sc(NAV_HEAD)), DIM, DT_LEFT);+ y += sc(NAV_HEAD);+ continue;+ }+ let hgt = nav_h(it);+ let r = rc(sc(8), y, cr.right - sc(8), y + hgt);+ let (th, ta) = (hv(5000 + i as i32, hot == i as i32), hv(6000 + i as i32, here == Some(i)));+ let p = press_t(5000 + i as i32);+ if th.max(ta) > 0.01 || p > 0.0 { fill(dc, r, mix(mix(mix(BG, HOVER, th), ACTIVE, ta), ACCENT, 0.3 * p), sc(10)); }+ if ta > 0.01 { fill(dc, rc(r.left, y + sc(10), r.left + sc(3), y + hgt - sc(10)), mix(ACTIVE, ACCENT, ta), sc(3)); }+ let line = rc(r.left, y, r.right, y + sc(NAV_ROW)); // the title line (a drive has its usage bar below it)+ SelectObject(dc, f_glyph);+ text(dc, it.glyph, rc(r.left + sc(10), line.top, r.left + sc(40), line.bottom), mix(DIM, ACCENT, ta), DT_CENTER);+ SelectObject(dc, f_txt);+ text(dc, &it.title, rc(r.left + sc(48), line.top, r.right - sc(8), line.bottom), mix(DIM, TEXT, ta.max(th)), DT_LEFT);+ if let Some((free, total)) = it.cap {+ // usage bar like Windows' "This PC": accent, red once the drive is more than 90 % full+ let used = 1.0 - free as f32 / total as f32;+ let bar = rc(r.left + sc(48), y + sc(30), r.right - sc(14), y + sc(34));+ fill(dc, bar, mix(BG, TEXT, 0.12), sc(4));+ let fw = ((bar.right - bar.left) as f32 * used) as i32;+ fill(dc, rc(bar.left, bar.top, bar.left + fw.max(sc(4)), bar.bottom), if used > 0.9 { rgb(255, 99, 97) } else { ACCENT }, sc(4));+ SelectObject(dc, f_small);+ let gb = |b: u64| b as f64 / 1_073_741_824.0;+ text(dc, &format!("{:.0} GB free of {:.0} GB", gb(free), gb(total)), rc(bar.left, bar.bottom + sc(1), r.right - sc(8), y + hgt - sc(2)), DIM, DT_LEFT);+ }+ y += hgt;+ }+ });+ fill(dc, rc(cr.right - 1, 0, cr.right, cr.bottom), LINE, 0); // hairline between the pane and the list+ BitBlt(wdc, 0, 0, cr.right, cr.bottom, dc, 0, 0, SRCCOPY);+ SelectObject(dc, of);+ for f in [f_txt, f_head, f_glyph, f_small] { DeleteObject(f); }+ SelectObject(dc, old);+ DeleteObject(bmp);+ DeleteDC(dc);+ if BUSY.get() { SetTimer(hwnd, 4, 16, None); } else { KillTimer(hwnd, 4); }+ EndPaint(hwnd, &ps);+}++pub unsafe extern "system" fn nav_proc(h: HWND, m: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {+ let y = ((lp >> 16) & 0xFFFF) as i16 as i32;+ match m {+ WM_PAINT => paint_nav(h),+ WM_ERASEBKGND => return 1,+ WM_TIMER if wp == 4 => { InvalidateRect(h, ptr::null(), 0); }+ WM_MOUSEMOVE => {+ let k = nav_hit(y).map_or(-1, |i| i as i32);+ let mut tme = TRACKMOUSEEVENT { cbSize: size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE, hwndTrack: h, dwHoverTime: 0 };+ TrackMouseEvent(&mut tme);+ if NAVHOT.replace(k) != k { InvalidateRect(h, ptr::null(), 0); }+ }+ WM_MOUSELEAVE => { NAVHOT.set(-1); InvalidateRect(h, ptr::null(), 0); }+ WM_LBUTTONDOWN => {+ if let Some(i) = nav_hit(y) {+ PRESS.set((5000 + i as i32, now()));+ InvalidateRect(h, ptr::null(), 0);+ PostMessageW(GetParent(h), WM_UI, 20, i as isize);+ }+ }+ _ => return DefWindowProcW(h, m, wp, lp),+ }+ 0+}diff --git a/plugins/rust-search/.cargo/config.toml b/plugins/rust-search/.cargo/config.tomlnew file mode 100644index 0000000..fac678a--- /dev/null+++ b/plugins/rust-search/.cargo/config.toml@@ -0,0 +1,2 @@+[build]+rustflags = ["-C", "target-feature=+crt-static"]diff --git a/plugins/rust-search/.gitignore b/plugins/rust-search/.gitignorenew file mode 100644index 0000000..ea8c4bf--- /dev/null+++ b/plugins/rust-search/.gitignore@@ -0,0 +1 @@+/targetdiff --git a/plugins/rust-search/Cargo.lock b/plugins/rust-search/Cargo.locknew file mode 100644index 0000000..7aff35f--- /dev/null+++ b/plugins/rust-search/Cargo.lock@@ -0,0 +1,247 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "bitflags"+version = "2.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"++[[package]]+name = "libc"+version = "0.2.191"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "ntapi"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae"+dependencies = [+ "winapi",+]++[[package]]+name = "objc2-core-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"+dependencies = [+ "bitflags",+]++[[package]]+name = "objc2-io-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15"+dependencies = [+ "libc",+ "objc2-core-foundation",+]++[[package]]+name = "proc-macro2"+version = "1.0.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "rs"+version = "0.1.0"+dependencies = [+ "sysinfo",+ "windows-sys",+]++[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "sysinfo"+version = "0.40.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a86bac2f7d06e6384984118ad727f5694110f0ec44d924d05c8fdec3d030bee6"+dependencies = [+ "libc",+ "memchr",+ "ntapi",+ "objc2-core-foundation",+ "objc2-io-kit",+ "windows",+]++[[package]]+name = "unicode-ident"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"++[[package]]+name = "winapi"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"+dependencies = [+ "winapi-i686-pc-windows-gnu",+ "winapi-x86_64-pc-windows-gnu",+]++[[package]]+name = "winapi-i686-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"++[[package]]+name = "winapi-x86_64-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"++[[package]]+name = "windows"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"+dependencies = [+ "windows-collections",+ "windows-core",+ "windows-future",+ "windows-numerics",+]++[[package]]+name = "windows-collections"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"+dependencies = [+ "windows-core",+]++[[package]]+name = "windows-core"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-link",+ "windows-result",+ "windows-strings",+]++[[package]]+name = "windows-future"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"+dependencies = [+ "windows-core",+ "windows-link",+ "windows-threading",+]++[[package]]+name = "windows-implement"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "windows-interface"+version = "0.59.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-numerics"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"+dependencies = [+ "windows-core",+ "windows-link",+]++[[package]]+name = "windows-result"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-strings"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-threading"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"+dependencies = [+ "windows-link",+]diff --git a/plugins/rust-search/Cargo.toml b/plugins/rust-search/Cargo.tomlnew file mode 100644index 0000000..da24d42--- /dev/null+++ b/plugins/rust-search/Cargo.toml@@ -0,0 +1,8 @@+[package]+name = "rs"+version = "0.1.0"+edition = "2024"++[dependencies]+sysinfo = { version = "0.40.3", default-features = false, features = ["system"] }+windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Graphics_Dwm", "Win32_Graphics_Gdi", "Win32_Graphics_GdiPlus", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_Console", "Win32_System_IO", "Win32_System_Ioctl", "Win32_System_LibraryLoader", "Win32_System_Pipes", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] }diff --git a/plugins/rust-search/src/bin/rs-debloat.rs b/plugins/rust-search/src/bin/rs-debloat.rsnew file mode 100644index 0000000..710afab--- /dev/null+++ b/plugins/rust-search/src/bin/rs-debloat.rs@@ -0,0 +1,153 @@+// rs-debloat show what would change (nothing is modified)+// rs-debloat --apply [--with-wsearch] apply (admin); every change is logged to an undo file first+// rs-debloat --undo restore exactly what --apply changed+//+// Deliberately NOT touched: Windows Update, Defender, Print Spooler, Xbox/Game services.+// Registry tweaks only ADD policy values that do not exist yet; existing values are never overwritten.+use std::{+ env,+ fs::{self, OpenOptions},+ io::Write,+ path::PathBuf,+ process::Command,+};++const SERVICES: &[(&str, &str)] = &[+ ("DiagTrack", "Connected User Experiences and Telemetry"),+ ("dmwappushservice", "WAP push message routing (telemetry helper)"),+ ("SysMain", "Superfetch/prefetch (little use on an SSD)"),+ ("MapsBroker", "downloaded maps"),+ ("RetailDemo", "retail demo mode"),+ ("WerSvc", "Windows Error Reporting"),+ ("Fax", "Fax"),+];+/// Only with --with-wsearch: rs replaces it, but Outlook/Explorer indexed search stops working.+const WSEARCH: (&str, &str) = ("WSearch", "Windows Search indexer (replaced by rs)");++// (key, value, DWORD data, what it does)+const REGS: &[(&str, &str, u32, &str)] = &[+ (r"HKLM\SOFTWARE\Policies\Microsoft\Windows\DataCollection", "AllowTelemetry", 0, "telemetry to the minimum"),+ (r"HKLM\SOFTWARE\Policies\Microsoft\Dsh", "AllowNewsAndInterests", 0, "Widgets off"),+ (r"HKLM\SOFTWARE\Policies\Microsoft\Windows\CloudContent", "DisableWindowsConsumerFeatures", 1, "no suggested/promoted apps"),+ (r"HKCU\Software\Policies\Microsoft\Windows\Explorer", "DisableSearchBoxSuggestions", 1, "no web results in Start search"),+ (r"HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsCopilot", "TurnOffWindowsCopilot", 1, "Copilot off"),+];++fn run(prog: &str, args: &[&str]) -> (bool, String) {+ match Command::new(prog).args(args).output() {+ Ok(o) => (o.status.success(), String::from_utf8_lossy(&o.stdout).into_owned()),+ Err(e) => (false, e.to_string()),+ }+}++/// Current start mode as `sc config` spells it. None = service missing, or boot/system driver (never touched).+fn start_mode(svc: &str) -> Option<&'static str> {+ let (ok, out) = run("sc.exe", &["qc", svc]);+ let line = out.lines().find(|l| ok && l.contains("START_TYPE"))?;+ Some(if line.contains("DISABLED") {+ "disabled"+ } else if line.contains("DEMAND_START") {+ "demand"+ } else if line.contains("AUTO_START") {+ if line.contains("DELAYED") { "delayed-auto" } else { "auto" }+ } else {+ return None;+ })+}++fn reg_exists(key: &str, value: &str) -> bool {+ run("reg.exe", &["query", key, "/v", value]).0+}++fn undo_path() -> PathBuf {+ PathBuf::from(env::var("ProgramData").unwrap_or_else(|_| r"C:\ProgramData".into())).join("rs-debloat").join("undo.txt")+}++fn services(with_wsearch: bool) -> Vec<(&'static str, &'static str)> {+ let mut v = SERVICES.to_vec();+ if with_wsearch {+ v.push(WSEARCH);+ }+ v+}++fn plan(with_wsearch: bool) {+ println!("Dry run: nothing is changed. Add --apply (admin) to do it, --undo to revert.\n");+ for (svc, why) in services(with_wsearch) {+ match start_mode(svc) {+ None => println!(" service {svc:<18} not present"),+ Some("disabled") => println!(" service {svc:<18} already disabled"),+ Some(m) => println!(" service {svc:<18} {m} -> disabled ({why})"),+ }+ }+ for (key, value, data, why) in REGS {+ let state = if reg_exists(key, value) { "already set, left alone" } else { "will set" };+ println!(" policy {value:<32} = {data} {state} ({why})");+ }+ if !with_wsearch {+ println!("\nWindows Search is not included; add --with-wsearch once rs has replaced it for you.");+ }+}++fn apply(with_wsearch: bool) -> Result<(), String> {+ let path = undo_path();+ fs::create_dir_all(path.parent().unwrap()).map_err(|e| format!("cannot create {}: {e} (run as admin)", path.parent().unwrap().display()))?;+ let mut log = OpenOptions::new().create(true).append(true).open(&path).map_err(|e| format!("{}: {e}", path.display()))?;+ for (svc, _) in services(with_wsearch) {+ match start_mode(svc) {+ None => println!("skip {svc}: not present"),+ Some("disabled") => println!("skip {svc}: already disabled"),+ Some(mode) => {+ writeln!(log, "svc|{svc}|{mode}").map_err(|e| e.to_string())?; // log BEFORE changing+ let (ok, _) = run("sc.exe", &["config", svc, "start=", "disabled"]);+ let _ = run("sc.exe", &["stop", svc]);+ println!("{} {svc}: {mode} -> disabled", if ok { "done " } else { "FAILED" });+ }+ }+ }+ for (key, value, data, _) in REGS {+ if reg_exists(key, value) {+ println!("skip {value}: already set");+ continue;+ }+ writeln!(log, "reg|{key}|{value}").map_err(|e| e.to_string())?;+ let (ok, _) = run("reg.exe", &["add", key, "/v", value, "/t", "REG_DWORD", "/d", &data.to_string(), "/f"]);+ println!("{} {value} = {data}", if ok { "done " } else { "FAILED" });+ }+ println!("\nUndo information saved to {}. Some changes need a reboot or sign-out.", path.display());+ Ok(())+}++fn undo() -> Result<(), String> {+ let path = undo_path();+ let text = fs::read_to_string(&path).map_err(|_| "nothing to undo (no undo file)".to_string())?;+ for line in text.lines() {+ let f: Vec<&str> = line.split('|').collect();+ let ok = match f.as_slice() {+ ["svc", name, mode] => run("sc.exe", &["config", name, "start=", mode]).0,+ ["reg", key, value] => run("reg.exe", &["delete", key, "/v", value, "/f"]).0,+ _ => continue,+ };+ println!("{} {line}", if ok { "restored" } else { "FAILED " });+ }+ fs::remove_file(&path).map_err(|e| e.to_string())?;+ println!("\nServices were restored to their old start mode (start them manually or reboot).");+ Ok(())+}++fn main() {+ let args: Vec<String> = env::args().skip(1).collect();+ let ws = args.iter().any(|a| a == "--with-wsearch");+ let r = if args.iter().any(|a| a == "--apply") {+ apply(ws)+ } else if args.iter().any(|a| a == "--undo") {+ undo()+ } else {+ plan(ws);+ Ok(())+ };+ if let Err(e) = r {+ eprintln!("{e}");+ std::process::exit(1);+ }+}diff --git a/plugins/rust-search/src/bin/rs-launcher.rs b/plugins/rust-search/src/bin/rs-launcher.rsnew file mode 100644index 0000000..794a420--- /dev/null+++ b/plugins/rust-search/src/bin/rs-launcher.rs@@ -0,0 +1,1350 @@+// Alt+Space opens a search card; results come from the `rs --serve` services (one pipe per drive).+// Type to search, Up/Down (or mouse) to pick, Enter to open, Ctrl+Enter to show in Explorer, Esc to close.+// `rs-launcher --autostart` registers it to start at logon.+//+// Everything is drawn by hand into one back buffer (GDI+ for the anti-aliased shapes, GDI for ClearType+// text), so the window can animate: fade + slide on show, a selection highlight that glides between+// rows, and a height that eases as results come and go.+#![windows_subsystem = "windows"]+#![allow(unsafe_op_in_unsafe_fn)]+#[path = "../common.rs"]+mod common;+#[path = "../regsweep.rs"]+mod regsweep;+use std::{+ cell::RefCell,+ collections::HashMap,+ fs,+ mem::{size_of, zeroed},+ ptr::{null, null_mut},+ time::Instant,+};+use windows_sys::Win32::{+ Foundation::*,+ Graphics::{+ Dwm::DwmSetWindowAttribute,+ Gdi::*,+ GdiPlus::{+ FillModeAlternate, GdipAddPathArc, GdipClosePathFigure, GdipCreateFromHDC, GdipCreatePath, GdipCreateSolidFill, GdipDeleteBrush, GdipDeleteGraphics, GdipDeletePath, GdipFillPath,+ GdipSetSmoothingMode, GdiplusStartup, GdiplusStartupInput, GpBrush, GpGraphics, GpPath, GpSolidFill, SmoothingModeAntiAlias,+ },+ },+ Storage::FileSystem::{FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_REPARSE_POINT},+ System::LibraryLoader::GetModuleHandleW,+ UI::{+ Input::KeyboardAndMouse::*,+ Shell::{+ FO_DELETE, FOF_ALLOWUNDO, FOF_NOERRORUI, FOF_SILENT, SHFILEINFOW, SHFILEOPSTRUCTW, SHFileOperationW, SHGFI_ICON, SHGFI_LARGEICON, SHGFI_USEFILEATTRIBUTES, SHGetFileInfoW,+ ShellExecuteW,+ },+ WindowsAndMessaging::*,+ },+};++type Rgb = (u8, u8, u8);+const BG: Rgb = (30, 31, 36);+const BORDER: Rgb = (62, 63, 72);+const SEL: Rgb = (46, 50, 62);+const ACCENT: Rgb = (96, 165, 250);+const TEXT: Rgb = (240, 240, 244);+const DIM: Rgb = (143, 146, 158);+const FAINT: Rgb = (98, 101, 112);++// logical pixels; multiplied by the screen scale when used+const W: i32 = 680;+const INPUT_H: i32 = 64;+const ROW_H: i32 = 52;+const PAD: i32 = 8;+const FOOT_H: i32 = 34;+const MAX_ROWS: usize = 7;+const RADIUS: i32 = 14;++const T_DEBOUNCE: usize = 1;+const T_ANIM: usize = 2;+const T_CARET: usize = 3;++const F_INPUT: usize = 0;+const F_NAME: usize = 1;+const F_PATH: usize = 2;+const F_ICON: usize = 3;+const F_HINT: usize = 4;++#[derive(Default)]+struct St {+ scale: f32,+ round_with_region: bool, // DWM could not round the corners (Windows 10): clip with a region instead+ fonts: [isize; 5],+ text: Vec<u16>,+ results: Vec<String>,+ top: usize, // first visible result+ sel: usize,+ sel_f: f32, // animated selection row, relative to `top`+ height: f32,+ th: f32, // target height+ alpha: f32,+ ta: f32, // target alpha+ slide: f32,+ x: i32,+ y: i32,+ last: Option<Instant>,+ caret: bool,+ mouse: (i32, i32),+ icons: HashMap<String, isize>,+ rename: Option<String>, // full path being renamed in the input box+ saved: Vec<u16>, // the search text to restore when the rename ends+ busy: bool, // a dialog is up: losing focus must not close the card+ menu: Option<MenuSt>,+ purge: Option<Purge>,+}+thread_local!(static ST: RefCell<St> = RefCell::new(St::default()));++// Keep borrows short: window messages re-enter the proc, so never call Win32 from inside `f`.+fn st<R>(f: impl FnOnce(&mut St) -> R) -> R {+ ST.with(|s| f(&mut s.borrow_mut()))+}++fn wide(s: &str) -> Vec<u16> {+ s.encode_utf16().chain([0]).collect()+}+fn rgb(c: Rgb) -> u32 {+ c.0 as u32 | (c.1 as u32) << 8 | (c.2 as u32) << 16+}+fn argb(c: Rgb) -> u32 {+ 0xff00_0000 | (c.0 as u32) << 16 | (c.1 as u32) << 8 | c.2 as u32+}++/// Asks every drive's service, in drive order; a drive whose service is down or busy is skipped.+fn ask(q: &str) -> Vec<String> {+ common::drive_letters()+ .into_iter()+ .filter_map(|d| common::ask(d, q)?.ok())+ .flat_map(|s| s.lines().filter(|l| !l.is_empty() && !l.starts_with("... ")).map(String::from).collect::<Vec<_>>())+ .collect()+}++fn is_app(path: &str) -> bool {+ let l = path.to_lowercase();+ l.ends_with(".lnk") && l.contains("\\start menu\\programs\\")+}++/// (title, subtitle) for a result row.+fn labels(path: &str) -> (String, String) {+ let (dir, file) = path.rsplit_once('\\').unwrap_or(("", path));+ if is_app(path) {+ (file.trim_end_matches(".lnk").trim_end_matches(".LNK").to_string(), "Application".into())+ } else {+ (file.to_string(), dir.to_string())+ }+}++fn target_height(s: &St) -> f32 {+ let p = |v: i32| v as f32 * s.scale;+ let rows = s.results.len().min(MAX_ROWS).max(1) as i32;+ let base = if s.text.is_empty() { p(INPUT_H) } else { p(INPUT_H + PAD + rows * ROW_H + if s.results.is_empty() { PAD } else { FOOT_H }) };+ if s.purge.is_some() {+ p(INPUT_H + PAD + PANEL_H)+ } else if s.menu.is_some() {+ base.max(p(INPUT_H + PAD + MENU_PAD * 2 + MENU.len() as i32 * MENU_ITEM_H + 6))+ } else {+ base+ }+}++unsafe fn start_anim(h: HWND) {+ SetTimer(h, T_ANIM, 15, None);+}++unsafe fn show(h: HWND) {+ let (x, y) = {+ let mut pt: POINT = zeroed();+ GetCursorPos(&mut pt);+ let mon = MonitorFromPoint(pt, MONITOR_DEFAULTTOPRIMARY);+ let mut mi: MONITORINFO = zeroed();+ mi.cbSize = size_of::<MONITORINFO>() as u32;+ GetMonitorInfoW(mon, &mut mi);+ let w = st(|s| (W as f32 * s.scale) as i32);+ (mi.rcWork.left + (mi.rcWork.right - mi.rcWork.left - w) / 2, mi.rcWork.top + (mi.rcWork.bottom - mi.rcWork.top) / 5)+ };+ st(|s| {+ s.text.clear();+ s.results.clear();+ (s.rename, s.menu) = (None, None);+ if matches!(s.purge, Some(Purge::Confirm { .. })) {+ s.purge = None;+ }+ (s.top, s.sel, s.sel_f, s.caret) = (0, 0, 0.0, true);+ s.th = target_height(s);+ (s.height, s.alpha, s.ta, s.slide, s.x, s.y, s.last) = (s.th, 0.0, 1.0, 16.0 * s.scale, x, y, None);+ });+ let (w, hgt, slide) = st(|s| ((W as f32 * s.scale) as i32, s.height as i32, s.slide as i32));+ SetLayeredWindowAttributes(h, 0, 0, LWA_ALPHA);+ SetWindowPos(h, HWND_TOPMOST, x, y + slide, w, hgt, SWP_SHOWWINDOW);+ SetForegroundWindow(h);+ SetTimer(h, T_CARET, 530, None);+ start_anim(h);+}++unsafe fn hide(h: HWND) {+ st(|s| s.ta = 0.0);+ start_anim(h);+}++fn ease(v: &mut f32, target: f32, k: f32, eps: f32, moving: &mut bool) {+ *v += (target - *v) * k;+ if (*v - target).abs() < eps {+ *v = target;+ } else {+ *moving = true;+ }+}++unsafe fn step(h: HWND) {+ let (alpha, x, y, w, hgt, moving, gone, region) = st(|s| {+ let now = Instant::now();+ let dt = s.last.map_or(0.016, |l| (now - l).as_secs_f32()).min(0.05);+ s.last = Some(now);+ let (k, ks) = (1.0 - (-dt * 20.0).exp(), 1.0 - (-dt * 32.0).exp());+ let mut moving = false;+ let want_row = (s.sel - s.top) as f32;+ ease(&mut s.alpha, s.ta, k, 0.004, &mut moving);+ ease(&mut s.height, s.th, k, 0.6, &mut moving);+ ease(&mut s.slide, 0.0, k, 0.6, &mut moving);+ ease(&mut s.sel_f, want_row, ks, 0.01, &mut moving);+ let gone = s.ta == 0.0 && s.alpha == 0.0;+ (s.alpha, s.x, s.y + s.slide as i32, (W as f32 * s.scale) as i32, s.height.round() as i32, moving, gone, s.round_with_region)+ });+ SetLayeredWindowAttributes(h, 0, (alpha * 255.0).round() as u8, LWA_ALPHA);+ SetWindowPos(h, HWND_TOPMOST, x, y, w, hgt, SWP_NOACTIVATE);+ if region {+ let r = (RADIUS as f32 * st(|s| s.scale)) as i32 * 2;+ SetWindowRgn(h, CreateRoundRectRgn(0, 0, w + 1, hgt + 1, r, r), 1);+ }+ InvalidateRect(h, null(), 0);+ if gone {+ ShowWindow(h, SW_HIDE);+ KillTimer(h, T_ANIM);+ KillTimer(h, T_CARET);+ } else if !moving {+ KillTimer(h, T_ANIM);+ }+}++unsafe fn refresh(h: HWND) {+ let q = st(|s| String::from_utf16_lossy(&s.text));+ let res = if q.trim().is_empty() { vec![] } else { ask(&q) };+ st(|s| {+ s.results = res;+ s.menu = None;+ (s.top, s.sel, s.sel_f) = (0, 0, 0.0);+ s.th = target_height(s);+ });+ start_anim(h);+}++unsafe fn open(h: HWND, reveal: bool) {+ let Some(p) = st(|s| if s.rename.is_some() { None } else { s.results.get(s.sel).cloned() }) else { return };+ hide(h);+ if reveal {+ ShellExecuteW(null_mut(), wide("open").as_ptr(), wide("explorer.exe").as_ptr(), wide(&format!("/select,\"{p}\"")).as_ptr(), null(), SW_SHOWNORMAL);+ } else {+ ShellExecuteW(null_mut(), wide("open").as_ptr(), wide(&p).as_ptr(), null(), null(), SW_SHOWNORMAL);+ }+}++fn move_sel(delta: isize) {+ st(|s| {+ if s.results.is_empty() || s.rename.is_some() {+ return;+ }+ s.sel = (s.sel as isize + delta).clamp(0, s.results.len() as isize - 1) as usize;+ if s.sel >= s.top + MAX_ROWS {+ s.top = s.sel + 1 - MAX_ROWS;+ }+ if s.sel < s.top {+ s.top = s.sel;+ }+ });+}++fn row_at(y: i32) -> Option<usize> {+ st(|s| {+ let rel = y as f32 - (INPUT_H + PAD) as f32 * s.scale;+ let row = (rel / (ROW_H as f32 * s.scale)).floor();+ (s.purge.is_none() && rel >= 0.0 && (row as usize) < MAX_ROWS && s.top + (row as usize) < s.results.len()).then(|| s.top + row as usize)+ })+}++unsafe fn on_char(h: HWND, c: u16) {+ if c >= 0x20 && c != 0x7f && st(|s| s.menu.is_none() && s.purge.is_none()) {+ st(|s| {+ if s.text.len() < 200 {+ s.text.push(c);+ }+ });+ text_changed(h);+ }+}++unsafe fn backspace(h: HWND, word: bool) {+ st(|s| {+ let drop_one = |t: &mut Vec<u16>| {+ if let Some(c) = t.pop() {+ if (0xDC00..0xE000).contains(&c) {+ t.pop(); // second half of a surrogate pair+ }+ }+ };+ drop_one(&mut s.text);+ if word {+ while s.text.last().is_some_and(|c| *c != 0x20) {+ drop_one(&mut s.text);+ }+ }+ s.caret = true;+ });+ text_changed(h);+}++unsafe fn text_changed(h: HWND) {+ if st(|s| s.rename.is_some()) {+ // editing a file name: the results must stay put+ } else if st(|s| s.text.is_empty()) {+ KillTimer(h, T_DEBOUNCE);+ st(|s| {+ s.results.clear();+ (s.top, s.sel, s.sel_f) = (0, 0, 0.0);+ s.th = target_height(s);+ });+ start_anim(h);+ } else {+ SetTimer(h, T_DEBOUNCE, 70, None); // wait for a pause in typing before asking+ }+ InvalidateRect(h, null(), 0);+}++unsafe extern "system" fn wndproc(h: HWND, m: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {+ match m {+ WM_HOTKEY => {+ if IsWindowVisible(h) != 0 && st(|s| s.ta) > 0.0 { hide(h) } else { show(h) }+ 0+ }+ WM_ACTIVATE => {+ if (wp & 0xffff) as u32 == WA_INACTIVE && st(|s| s.ta > 0.0 && !s.busy && !matches!(s.purge, Some(Purge::Scanning(_) | Purge::Working(_)))) {+ hide(h);+ }+ 0+ }+ WM_TIMER => {+ match wp {+ T_DEBOUNCE => {+ KillTimer(h, T_DEBOUNCE);+ refresh(h);+ }+ T_ANIM => step(h),+ T_CARET => {+ st(|s| s.caret = !s.caret);+ InvalidateRect(h, null(), 0);+ }+ _ => {}+ }+ 0+ }+ WM_CHAR => {+ on_char(h, wp as u16);+ 0+ }+ WM_PURGE => {+ let p = *Box::from_raw(lp as *mut Purge);+ set_purge(h, Some(p));+ 0+ }+ WM_KEYDOWN => {+ if st(|s| s.purge.is_some()) {+ let idle = st(|s| matches!(s.purge, Some(Purge::Confirm { .. } | Purge::Done { .. })));+ match wp as u16 {+ VK_ESCAPE if idle => close_purge(h),+ VK_ESCAPE => hide(h), // the work goes on; its result is shown on the next open+ VK_RETURN => purge_press(h, st(|s| match &s.purge {+ Some(Purge::Confirm { hot, .. } | Purge::Done { hot, .. }) => *hot,+ _ => 0,+ })),+ VK_LEFT | VK_RIGHT | VK_TAB => {+ let n = st(|s| purge_buttons(s).len());+ st(|s| {+ if let Some(Purge::Confirm { hot, .. } | Purge::Done { hot, .. }) = s.purge.as_mut() {+ *hot = if n > 1 { 1 - *hot } else { 0 };+ }+ });+ InvalidateRect(h, null(), 0);+ }+ _ => {}+ }+ return 0;+ }+ if st(|s| s.menu.is_some()) {+ match wp as u16 {+ VK_ESCAPE => close_menu(h),+ VK_RETURN => run_menu(h, st(|s| s.menu.as_ref().map_or(0, |m| m.hot))),+ k @ (VK_UP | VK_DOWN) => {+ st(|s| {+ if let Some(m) = s.menu.as_mut() {+ m.hot = if k == VK_DOWN { (m.hot + 1) % MENU.len() } else { (m.hot + MENU.len() - 1) % MENU.len() };+ }+ });+ InvalidateRect(h, null(), 0);+ }+ _ => {}+ }+ return 0;+ }+ let ctrl = GetKeyState(VK_CONTROL as i32) < 0;+ match wp as u16 {+ VK_ESCAPE => {+ if st(|s| s.rename.is_some()) { end_rename(h, None) } else { hide(h) }+ }+ VK_RETURN => {+ if st(|s| s.rename.is_some()) { finish_rename(h) } else { open(h, ctrl) }+ }+ VK_DOWN => move_sel(1),+ VK_UP => move_sel(-1),+ VK_NEXT => move_sel(MAX_ROWS as isize),+ VK_PRIOR => move_sel(-(MAX_ROWS as isize)),+ VK_BACK => backspace(h, ctrl),+ _ => return 0,+ }+ start_anim(h);+ 0+ }+ WM_MOUSEMOVE => {+ // Windows also sends this when the content under a *still* cursor changes (window appears,+ // rows move), and a resting hand jitters: only a real movement (>= 8 px) may take the+ // selection away from the keyboard.+ let pos = ((lp & 0xffff) as i16 as i32, ((lp >> 16) & 0xffff) as i16 as i32);+ if st(|s| s.purge.is_some()) {+ if let Some(i) = purge_hit(pos.0, pos.1) {+ let changed = st(|s| match s.purge.as_mut() {+ Some(Purge::Confirm { hot, .. } | Purge::Done { hot, .. }) => std::mem::replace(hot, i) != i,+ _ => false,+ });+ if changed {+ InvalidateRect(h, null(), 0);+ }+ }+ return 0;+ }+ if let Some(hit) = menu_hit(pos.0, pos.1) {+ if let Some(i) = hit {+ if st(|s| s.menu.as_mut().is_some_and(|m| std::mem::replace(&mut m.hot, i) != i)) {+ InvalidateRect(h, null(), 0);+ }+ }+ return 0;+ }+ let moved = st(|s| {+ let far = (pos.0 - s.mouse.0).abs() + (pos.1 - s.mouse.1).abs() >= 8;+ if far {+ s.mouse = pos;+ }+ far+ });+ if let Some(i) = moved.then(|| row_at(pos.1)).flatten() {+ if st(|s| std::mem::replace(&mut s.sel, i)) != i {+ start_anim(h);+ }+ }+ 0+ }+ WM_MOUSEWHEEL => {+ if st(|s| s.menu.is_some() || s.purge.is_some()) {+ return 0;+ }+ move_sel(if ((wp >> 16) as i16) > 0 { -1 } else { 1 });+ start_anim(h);+ 0+ }+ WM_LBUTTONUP => {+ if st(|s| s.purge.is_some()) {+ if let Some(i) = purge_hit((lp & 0xffff) as i16 as i32, ((lp >> 16) & 0xffff) as i16 as i32) {+ purge_press(h, i);+ }+ return 0;+ }+ match menu_hit((lp & 0xffff) as i16 as i32, ((lp >> 16) & 0xffff) as i16 as i32) {+ Some(Some(i)) => return { run_menu(h, i); 0 },+ Some(None) => return { close_menu(h); 0 },+ None => {}+ }+ if let Some(i) = row_at(((lp >> 16) & 0xffff) as i16 as i32) {+ st(|s| s.sel = i);+ open(h, false);+ }+ 0+ }+ WM_RBUTTONUP => {+ let (x, y) = ((lp & 0xffff) as i16 as i32, ((lp >> 16) & 0xffff) as i16 as i32);+ match row_at(y) {+ Some(i) if st(|s| s.rename.is_none() && s.purge.is_none()) => open_menu(h, i, x, y),+ _ => close_menu(h),+ }+ 0+ }+ WM_ERASEBKGND => 1,+ WM_PAINT => {+ paint(h);+ 0+ }+ WM_DESTROY => {+ PostQuitMessage(0);+ 0+ }+ _ => DefWindowProcW(h, m, wp, lp),+ }+}++// ---------------------------------------------------------------- right-click actions++// item 3 is "Add to Start" / "Remove from Start" (the label is picked when drawing)+const MENU: [&str; 7] = ["Open", "Run as administrator", "Show in folder", "Add to Start", "Rename", "Move to Recycle Bin", "Delete forever + clean registry"];++/// topbar's Start list: one path per line (the same file topbar reads when its Start panel opens).+fn start_file() -> std::path::PathBuf {+ std::path::PathBuf::from(std::env::var_os("APPDATA").unwrap_or_default()).join("topbar-start.txt")+}++fn start_pins() -> Vec<String> {+ fs::read_to_string(start_file()).map(|s| s.lines().filter(|l| !l.is_empty()).map(String::from).collect()).unwrap_or_default()+}++fn start_pinned(p: &str) -> bool {+ start_pins().iter().any(|x| x.eq_ignore_ascii_case(p))+}++fn start_toggle(p: &str) {+ let mut v = start_pins();+ match v.iter().position(|x| x.eq_ignore_ascii_case(p)) {+ Some(i) => drop(v.remove(i)),+ None => v.push(p.to_string()),+ }+ let _ = fs::write(start_file(), v.join("\n"));+}+const MENU_W: i32 = 270;+const MENU_ITEM_H: i32 = 32;+const MENU_PAD: i32 = 6;+const MENU_BG: Rgb = (40, 42, 50);+const MENU_HOT: Rgb = (62, 68, 84);+const DANGER: Rgb = (248, 113, 113);++struct MenuSt {+ x: i32,+ y: i32,+ hot: usize,+ path: String,+}++/// Modal box over the card; `busy` keeps the card from closing when it loses focus to the box.+unsafe fn ask_box(h: HWND, text: &str, flags: u32) -> i32 {+ st(|s| s.busy = true);+ let r = MessageBoxW(h, wide(text).as_ptr(), wide("rs launcher").as_ptr(), flags | MB_TOPMOST | MB_SETFOREGROUND);+ st(|s| s.busy = false);+ r+}++/// Drive roots, system and profile folders are never touched from here.+fn protected(p: &str) -> bool {+ let l = p.trim_end_matches('\\').to_lowercase();+ if !l.contains('\\') {+ return true; // "c:"+ }+ let var = |k: &str| std::env::var(k).ok().map(|v| v.trim_end_matches('\\').to_lowercase());+ let win = var("SystemRoot");+ if win.as_ref().is_some_and(|w| l == *w || l.starts_with(&format!("{w}\\"))) {+ return true;+ }+ let profile = var("USERPROFILE");+ let users = profile.as_ref().and_then(|p| p.rsplit_once('\\').map(|(d, _)| d.to_string()));+ ["ProgramFiles", "ProgramFiles(x86)", "ProgramData"].iter().filter_map(|k| var(k)).chain(profile).chain(users).any(|x| l == x)+}++// The menu is drawn inside the card (no system popup: that one is light-themed and its modal loop+// stalls the animation timers). x/y are client pixels of the click.+fn menu_rect(s: &St, m: &MenuSt) -> (i32, i32, i32, i32) {+ let p = |v: i32| (v as f32 * s.scale).round() as i32;+ let (w, h) = (p(MENU_W), p(MENU_PAD) * 2 + MENU.len() as i32 * p(MENU_ITEM_H));+ let l = m.x.min(p(W) - w - p(6)).max(p(6));+ let t = m.y.min(s.height.round() as i32 - h - p(6)).max(0);+ (l, t, l + w, t + h)+}++/// None = no menu open; Some(None) = click outside it; Some(Some(i)) = on item i.+fn menu_hit(x: i32, y: i32) -> Option<Option<usize>> {+ st(|s| {+ let m = s.menu.as_ref()?;+ let (l, t, r, b) = menu_rect(s, m);+ let p = |v: i32| (v as f32 * s.scale).round() as i32;+ Some((x >= l && x < r && y >= t && y < b).then(|| (((y - t - p(MENU_PAD)) / p(MENU_ITEM_H)).max(0) as usize).min(MENU.len() - 1)))+ })+}++unsafe fn open_menu(h: HWND, row: usize, x: i32, y: i32) {+ st(|s| {+ if let Some(path) = s.results.get(row).cloned() {+ s.sel = row;+ s.menu = Some(MenuSt { x, y, hot: 0, path });+ s.th = target_height(s); // room for the menu even under a single result+ }+ });+ start_anim(h);+}++unsafe fn close_menu(h: HWND) {+ st(|s| {+ if s.menu.take().is_some() {+ s.th = target_height(s);+ }+ });+ start_anim(h);+ InvalidateRect(h, null(), 0);+}++unsafe fn run_menu(h: HWND, i: usize) {+ let Some(p) = st(|s| s.menu.as_ref().map(|m| m.path.clone())) else { return };+ close_menu(h);+ match i {+ 0 => open(h, false),+ 1 => {+ hide(h);+ ShellExecuteW(null_mut(), wide("runas").as_ptr(), wide(&p).as_ptr(), null(), null(), SW_SHOWNORMAL);+ }+ 2 => open(h, true),+ 3 => start_toggle(&p),+ 4 => begin_rename(h, &p),+ _ => remove(h, &p, i == 6),+ }+}++/// Rename happens in the input box itself: it shows the current name, Enter applies, Esc cancels.+unsafe fn begin_rename(h: HWND, p: &str) {+ if protected(p) {+ ask_box(h, "This is a protected system location.", MB_OK | MB_ICONWARNING);+ return;+ }+ KillTimer(h, T_DEBOUNCE);+ st(|s| {+ let name = p.rsplit('\\').next().unwrap_or(p);+ s.saved = std::mem::replace(&mut s.text, name.encode_utf16().collect());+ s.rename = Some(p.to_string());+ s.caret = true;+ });+ InvalidateRect(h, null(), 0);+}++unsafe fn end_rename(h: HWND, renamed_to: Option<String>) {+ st(|s| {+ if let (Some(old), Some(new)) = (s.rename.take(), renamed_to) {+ if let Some(r) = s.results.iter_mut().find(|r| **r == old) {+ *r = new;+ }+ }+ s.text = std::mem::take(&mut s.saved);+ });+ InvalidateRect(h, null(), 0);+}++unsafe fn finish_rename(h: HWND) {+ let Some(old) = st(|s| s.rename.clone()) else { return };+ let new = st(|s| String::from_utf16_lossy(&s.text)).trim().to_string();+ let (dir, cur) = old.rsplit_once('\\').unwrap_or(("", &old));+ if new.is_empty() || new.contains(['\\', '/', ':', '*', '?', '"', '<', '>', '|']) {+ ask_box(h, "A name cannot be empty or contain \\ / : * ? \" < > |", MB_OK | MB_ICONWARNING);+ return; // stay in rename mode so it can be fixed+ }+ let dst = format!("{dir}\\{new}");+ if new != cur {+ if let Err(e) = fs::rename(&old, &dst) {+ ask_box(h, &format!("Cannot rename:\n{e}"), MB_OK | MB_ICONERROR);+ return;+ }+ }+ end_rename(h, Some(dst));+}++fn recycle(p: &str) -> Result<(), String> {+ let from: Vec<u16> = p.encode_utf16().chain([0, 0]).collect(); // double-NUL list+ let mut op: SHFILEOPSTRUCTW = unsafe { zeroed() };+ op.wFunc = FO_DELETE;+ op.pFrom = from.as_ptr();+ // no FOF_NOCONFIRMATION: when an item is too big for the bin Windows asks before deleting it for good+ op.fFlags = (FOF_ALLOWUNDO | FOF_SILENT | FOF_NOERRORUI) as u16;+ let rc = unsafe { SHFileOperationW(&mut op) };+ let aborted = op.fAnyOperationsAborted;+ if rc != 0 || aborted != 0 { Err(format!("Recycle Bin refused it (code {rc})")) } else { Ok(()) }+}++fn note(text: &str, flags: u32) {+ unsafe { MessageBoxW(null_mut(), wide(text).as_ptr(), wide("rs launcher").as_ptr(), flags | MB_TOPMOST | MB_SETFOREGROUND) };+}++/// Recycle Bin: reversible, no question asked. "Delete forever" opens the purge panel instead.+unsafe fn remove(h: HWND, p: &str, purge: bool) {+ if protected(p) {+ ask_box(h, "This is a protected system location.", MB_OK | MB_ICONWARNING);+ return;+ }+ if purge {+ return begin_purge(h, p);+ }+ hide(h);+ let p = p.to_string();+ std::thread::spawn(move || {+ if let Err(e) = recycle(&p) {+ note(&format!("Cannot delete:\n{e}"), MB_OK | MB_ICONERROR);+ }+ });+}++// ---------------------------------------------------------------- delete forever+//+// Drawn inside the card, in three stages, never touching anything before the user has seen the list:+// Scanning count the files, find the registry entries (read-only, on a thread)+// Confirm show all of it; Cancel is the default button+// Working delete the files; only if every one is gone: back up the registry entries to a .reg, then remove them+// Done what happened, with the backup file one click away++const WM_PURGE: u32 = WM_APP + 7; // lParam = Box<Purge> from a worker thread+const PANEL_H: i32 = 300;+const LIST_MAX: usize = 4;++enum Purge {+ Scanning(String),+ Confirm { path: String, files: u64, bytes: u64, hits: Vec<regsweep::Hit>, hot: usize }, // hot: 0 Cancel, 1 Delete+ Working(String),+ Done { path: String, title: String, lines: Vec<String>, ok: bool, backup: Option<String>, hot: usize }, // hot: 0 Close, 1 Show backup+}++fn post(h: isize, p: Purge) {+ unsafe { PostMessageW(h as HWND, WM_PURGE, 0, Box::into_raw(Box::new(p)) as isize) };+}++/// (files, bytes) under `p`; links are counted, never followed.+fn measure(p: &std::path::Path) -> (u64, u64) {+ use std::os::windows::fs::MetadataExt;+ let Ok(m) = fs::symlink_metadata(p) else { return (0, 0) };+ if m.file_attributes() & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT) != FILE_ATTRIBUTE_DIRECTORY {+ return (1, m.len());+ }+ fs::read_dir(p).map_or((0, 0), |rd| rd.flatten().map(|e| measure(&e.path())).fold((0, 0), |a, b| (a.0 + b.0, a.1 + b.1)))+}++/// Deletes `p` bottom-up, carrying on past failures. Read-only files are unlocked first; junctions and+/// symlinks are removed as links (what they point to is never touched). Returns what could not be removed.+fn wipe(p: &std::path::Path, failed: &mut Vec<String>) {+ use std::os::windows::fs::MetadataExt;+ let Ok(m) = fs::symlink_metadata(p) else { return }; // already gone+ let attrs = m.file_attributes();+ let (dir, link) = (attrs & FILE_ATTRIBUTE_DIRECTORY != 0, attrs & FILE_ATTRIBUTE_REPARSE_POINT != 0);+ let before = failed.len();+ if dir && !link {+ if let Ok(rd) = fs::read_dir(p) {+ for e in rd.flatten() {+ wipe(&e.path(), failed);+ }+ }+ if failed.len() > before {+ return; // a child stayed, so the folder cannot go either; the child is already reported+ }+ }+ if !link && m.permissions().readonly() {+ let mut perm = m.permissions();+ perm.set_readonly(false);+ let _ = fs::set_permissions(p, perm);+ }+ if let Err(e) = if dir { fs::remove_dir(p) } else { fs::remove_file(p) } {+ failed.push(format!("{} ({})", p.display(), e.kind()));+ }+}++fn size_text(b: u64) -> String {+ let (v, u) = match b {+ 0..1024 => return format!("{b} B"),+ ..1_048_576 => (b as f64 / 1024.0, "KB"),+ ..1_073_741_824 => (b as f64 / 1_048_576.0, "MB"),+ _ => (b as f64 / 1_073_741_824.0, "GB"),+ };+ format!("{v:.1} {u}")+}++fn plural(n: usize, one: &str) -> String {+ format!("{n} {one}{}", if n == 1 { "" } else { "s" })+}++/// %LOCALAPPDATA%\rs-search\registry-backups\2026-11-15 10-42-07 name.reg+fn backup_path(p: &str) -> std::path::PathBuf {+ let mut t = unsafe { zeroed() };+ unsafe { windows_sys::Win32::System::SystemInformation::GetLocalTime(&mut t) };+ let t: windows_sys::Win32::Foundation::SYSTEMTIME = t;+ let name: String = p.rsplit('\\').next().unwrap_or("item").chars().map(|c| if c.is_alphanumeric() || " .-_".contains(c) { c } else { '_' }).take(60).collect();+ let base = std::env::var("LOCALAPPDATA").unwrap_or_else(|_| std::env::temp_dir().display().to_string());+ std::path::Path::new(&base)+ .join(r"rs-search\registry-backups")+ .join(format!("{:04}-{:02}-{:02} {:02}-{:02}-{:02} {name}.reg", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond))+}++unsafe fn set_purge(h: HWND, p: Option<Purge>) {+ st(|s| {+ s.menu = None;+ s.purge = p;+ s.th = target_height(s);+ });+ start_anim(h);+ InvalidateRect(h, null(), 0);+}++unsafe fn begin_purge(h: HWND, p: &str) {+ set_purge(h, Some(Purge::Scanning(p.into())));+ let (hw, path) = (h as isize, p.to_string());+ std::thread::spawn(move || {+ let (files, bytes) = measure(std::path::Path::new(&path));+ let hits = regsweep::scan(&path);+ post(hw, Purge::Confirm { path, files, bytes, hits, hot: 0 });+ });+}++unsafe fn run_purge(h: HWND) {+ let Some((path, hits)) = st(|s| match s.purge.take() {+ Some(Purge::Confirm { path, hits, .. }) => Some((path, hits)),+ other => {+ s.purge = other;+ None+ }+ }) else {+ return;+ };+ set_purge(h, Some(Purge::Working(path.clone())));+ let hw = h as isize;+ std::thread::spawn(move || {+ let (files, bytes) = measure(std::path::Path::new(&path));+ let mut failed = Vec::new();+ wipe(std::path::Path::new(&path), &mut failed);+ let done = |title: &str, lines: Vec<String>, ok: bool, backup: Option<String>| Purge::Done { path: path.clone(), title: title.into(), lines, ok, backup, hot: 0 };+ if !failed.is_empty() {+ let mut lines = vec![format!("{} could not be removed (in use or access denied):", plural(failed.len(), "item"))];+ lines.extend(failed.iter().take(3).cloned());+ if failed.len() > 3 {+ lines.push(format!("... and {} more", failed.len() - 3));+ }+ lines.push("The registry was not touched. Close the program using them and try again.".into());+ return post(hw, done("Some files are still there", lines, false, None));+ }+ let mut lines = vec![format!("{} removed ({})", plural(files as usize, "file"), size_text(bytes))];+ if hits.is_empty() {+ lines.push("No registry entries pointed to it.".into());+ return post(hw, done("Deleted", lines, true, None));+ }+ let bak = backup_path(&path);+ if let Err(e) = regsweep::backup(&hits, &bak) {+ lines.push(format!("Registry left as is: the backup could not be written ({e})."));+ return post(hw, done("Deleted, registry kept", lines, false, None));+ }+ let r = regsweep::delete(&hits);+ lines.push(format!("{} removed", plural(r.removed, "registry entry").replace("entrys", "entries")));+ if r.denied > 0 {+ lines.push(format!("{} need administrator rights and were left in place", r.denied));+ }+ post(hw, done("Deleted", lines, r.denied == 0, Some(bak.display().to_string())));+ });+}++/// Enter / click on the panel's button `i`.+unsafe fn purge_press(h: HWND, i: usize) {+ let action = st(|s| match &s.purge {+ Some(Purge::Confirm { .. }) => Some(if i == 1 { 1 } else { 0 }),+ Some(Purge::Done { backup, .. }) => Some(if i == 1 && backup.is_some() { 2 } else { 3 }),+ _ => None,+ });+ match action {+ Some(1) => run_purge(h),+ Some(2) => {+ let b = st(|s| match &s.purge {+ Some(Purge::Done { backup, .. }) => backup.clone(),+ _ => None,+ });+ if let Some(b) = b {+ hide(h);+ ShellExecuteW(null_mut(), wide("open").as_ptr(), wide("explorer.exe").as_ptr(), wide(&format!("/select,\"{b}\"")).as_ptr(), null(), SW_SHOWNORMAL);+ }+ }+ Some(_) => close_purge(h),+ None => {}+ }+}++/// Closes the panel; a path that is gone also leaves the result list.+unsafe fn close_purge(h: HWND) {+ st(|s| {+ if let Some(Purge::Done { path, .. }) = &s.purge {+ if fs::symlink_metadata(path).is_err() {+ let p = path.clone();+ s.results.retain(|r| *r != p);+ s.sel = s.sel.min(s.results.len().saturating_sub(1));+ s.top = s.top.min(s.sel);+ }+ }+ });+ set_purge(h, None);+}++/// Button rectangles of the panel (client px): [left one, right one]; the right one may be absent.+fn purge_buttons(s: &St) -> Vec<(i32, i32, i32, i32)> {+ let p = |v: i32| (v as f32 * s.scale).round() as i32;+ let (w, bottom) = (p(W), p(INPUT_H + PAD + PANEL_H));+ let (bw, bh) = (p(150), p(36));+ let (t, b) = (bottom - p(20) - bh, bottom - p(20));+ let right = (w - p(22) - bw, t, w - p(22), b);+ let left = (right.0 - p(10) - p(110), t, right.0 - p(10), b);+ match &s.purge {+ Some(Purge::Confirm { .. }) => vec![left, right],+ Some(Purge::Done { backup: Some(_), .. }) => vec![left, right],+ Some(Purge::Done { .. }) => vec![(w - p(22) - p(110), t, w - p(22), b)],+ _ => vec![],+ }+}++fn purge_hit(x: i32, y: i32) -> Option<usize> {+ st(|s| purge_buttons(s).iter().position(|&(l, t, r, b)| x >= l && x < r && y >= t && y < b))+}++// ---------------------------------------------------------------- drawing++struct View {+ scale: f32,+ fonts: [isize; 5],+ text: Vec<u16>,+ rows: Vec<(String, String, isize)>, // title, subtitle, icon+ total: usize,+ sel_f: f32,+ caret: bool,+ renaming: bool,+ menu: Option<(i32, i32, usize)>, // left, top, hot item+ menu_pinned: bool, // the menu's file is already in Start: item 3 reads "Remove from Start"+ purge: Option<PView>,+}++/// What the purge panel shows, snapshotted for one paint.+struct PView {+ glyph: (&'static str, Rgb),+ title: (String, Rgb),+ path: String,+ lines: Vec<(String, Rgb, bool)>, // text, colour, small+ note: String,+ buttons: Vec<((i32, i32, i32, i32), &'static str, bool, bool)>, // rect, label, danger, hot+}++fn purge_view(s: &St) -> Option<PView> {+ let rects = purge_buttons(s);+ let btn = |labels: &[(&'static str, bool)], hot: usize| rects.iter().zip(labels).enumerate().map(|(i, (r, (l, d)))| (*r, *l, *d, i == hot)).collect::<Vec<_>>();+ Some(match s.purge.as_ref()? {+ Purge::Scanning(path) => PView {+ glyph: ("\u{E721}", DIM),+ title: ("Checking what will be removed\u{2026}".into(), TEXT),+ path: path.clone(),+ lines: vec![("Counting files and searching the registry. Nothing is deleted yet.".into(), DIM, false)],+ note: String::new(),+ buttons: vec![],+ },+ Purge::Working(path) => PView {+ glyph: ("\u{E74D}", DANGER),+ title: ("Deleting\u{2026}".into(), TEXT),+ path: path.clone(),+ lines: vec![("Esc hides this card; the result waits for the next Alt+Space.".into(), DIM, false)],+ note: String::new(),+ buttons: vec![],+ },+ Purge::Confirm { path, files, bytes, hits, hot } => {+ let mut lines = vec![(format!("{} \u{00B7} {}", plural(*files as usize, "file"), size_text(*bytes)), TEXT, false)];+ if hits.is_empty() {+ lines.push(("No registry entries point to it.".into(), DIM, false));+ } else {+ let n = plural(hits.len(), "registry entry").replace("entrys", "entries");+ lines.push((format!("{n} {} to it and will be removed:", if hits.len() == 1 { "points" } else { "point" }), DIM, false));+ lines.extend(hits.iter().take(LIST_MAX).map(|h| (h.describe(), FAINT, true)));+ if hits.len() > LIST_MAX {+ lines.push((format!("+ {} more", hits.len() - LIST_MAX), FAINT, true));+ }+ }+ PView {+ glyph: ("\u{E74D}", DANGER),+ title: ("Delete forever?".into(), DANGER),+ path: path.clone(),+ lines,+ note: if hits.is_empty() { "Files skip the Recycle Bin and cannot be restored.".into() } else { "Files skip the Recycle Bin. Registry entries are saved to a .reg backup first.".into() },+ buttons: btn(&[("Cancel", false), ("Delete forever", true)], *hot),+ }+ }+ Purge::Done { path, title, lines, ok, backup, hot } => PView {+ glyph: if *ok { ("\u{E73E}", ACCENT) } else { ("\u{E7BA}", DANGER) },+ title: (title.clone(), if *ok { TEXT } else { DANGER }),+ path: path.clone(),+ lines: lines.iter().enumerate().map(|(i, l)| (l.clone(), if i == 0 { TEXT } else { DIM }, false)).collect(),+ note: backup.as_ref().map_or(String::new(), |b| format!("Backup (double-click to restore): {b}")),+ buttons: if backup.is_some() { btn(&[("Close", false), ("Show backup", false)], *hot) } else { btn(&[("Close", false)], 0) },+ },+ })+}++unsafe fn draw_purge(dc: HDC, w: i32, v: &View, pv: &PView) {+ let s = v.scale;+ let p = |x: i32| (x as f32 * s).round() as i32;+ let top = p(INPUT_H + PAD);+ let mut g: *mut GpGraphics = null_mut();+ GdipCreateFromHDC(dc, &mut g);+ GdipSetSmoothingMode(g, SmoothingModeAntiAlias);+ for ((l, t, r, b), _, danger, hot) in &pv.buttons {+ let (rad, l, t, bw, bh) = (8.0 * s, *l as f32, *t as f32, (*r - *l) as f32, (*b - *t) as f32);+ if *danger {+ // the destructive button stays an outline until it is the chosen one+ round_rect(g, l, t, bw, bh, rad, DANGER);+ if !*hot {+ round_rect(g, l + 1.5 * s, t + 1.5 * s, bw - 3.0 * s, bh - 3.0 * s, rad - 1.5 * s, BG);+ }+ } else {+ round_rect(g, l, t, bw, bh, rad, if *hot { MENU_HOT } else { MENU_BG });+ }+ }+ GdipDeleteGraphics(g);+ let left = p(58);+ text(dc, v.fonts[F_ICON], pv.glyph.1, RECT { left: p(22), top: top + p(12), right: p(52), bottom: top + p(40) }, pv.glyph.0, DT_SINGLELINE | DT_VCENTER);+ text(dc, v.fonts[F_NAME], pv.title.1, RECT { left, top: top + p(12), right: w - p(22), bottom: top + p(40) }, &pv.title.0, DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS);+ text(dc, v.fonts[F_PATH], DIM, RECT { left, top: top + p(40), right: w - p(22), bottom: top + p(60) }, &pv.path, DT_SINGLELINE | DT_PATH_ELLIPSIS);+ let mut y = top + p(74);+ for (line, c, small) in &pv.lines {+ let hgt = p(if *small { 18 } else { 22 });+ let (font, indent) = if *small { (v.fonts[F_HINT], p(12)) } else { (v.fonts[F_PATH], 0) };+ text(dc, font, *c, RECT { left: left + indent, top: y, right: w - p(22), bottom: y + hgt }, line, DT_SINGLELINE | DT_VCENTER | DT_PATH_ELLIPSIS);+ y += hgt;+ }+ let bottom = top + p(PANEL_H);+ if !pv.note.is_empty() {+ text(dc, v.fonts[F_HINT], FAINT, RECT { left: p(22), top: bottom - p(20 + 36 + 30), right: w - p(22), bottom: bottom - p(20 + 36 + 8) }, &pv.note, DT_SINGLELINE | DT_VCENTER | DT_PATH_ELLIPSIS);+ }+ for ((l, t, r, b), label, danger, hot) in &pv.buttons {+ let c = if *danger && *hot { (20, 20, 24) } else if *danger { DANGER } else { TEXT };+ text(dc, v.fonts[F_PATH], c, RECT { left: *l, top: *t, right: *r, bottom: *b }, label, DT_SINGLELINE | DT_VCENTER | DT_CENTER);+ }+}+++unsafe fn ensure_icons() {+ st(|s| {+ if s.icons.len() > 300 {+ for (_, i) in s.icons.drain() {+ if i != 0 {+ DestroyIcon(i as _);+ }+ }+ }+ });+ let need: Vec<String> = st(|s| s.results.iter().skip(s.top).take(MAX_ROWS).filter(|p| !s.icons.contains_key(*p)).cloned().collect());+ for p in need {+ let mut fi: SHFILEINFOW = zeroed();+ let path = wide(&p);+ SHGetFileInfoW(path.as_ptr(), 0, &mut fi, size_of::<SHFILEINFOW>() as u32, SHGFI_ICON | SHGFI_LARGEICON);+ if fi.hIcon.is_null() {+ // no icon of its own (unregistered type, vanished file): the generic one for that extension+ SHGetFileInfoW(path.as_ptr(), 0x80, &mut fi, size_of::<SHFILEINFOW>() as u32, SHGFI_ICON | SHGFI_LARGEICON | SHGFI_USEFILEATTRIBUTES);+ }+ st(|s| {+ s.icons.insert(p, fi.hIcon as isize);+ });+ }+}++unsafe fn paint(h: HWND) {+ ensure_icons();+ let v = st(|s| View {+ scale: s.scale,+ fonts: s.fonts,+ text: s.text.clone(),+ rows: s.results.iter().skip(s.top).take(MAX_ROWS).map(|p| {+ let (a, b) = labels(p);+ (a, b, s.icons.get(p).copied().unwrap_or(0))+ }).collect(),+ total: s.results.len(),+ sel_f: s.sel_f,+ caret: s.caret,+ renaming: s.rename.is_some(),+ menu: s.menu.as_ref().map(|m| {+ let (l, t, ..) = menu_rect(s, m);+ (l, t, m.hot)+ }),+ menu_pinned: s.menu.as_ref().is_some_and(|m| start_pinned(&m.path)),+ purge: purge_view(s),+ });+ let mut ps: PAINTSTRUCT = zeroed();+ let dc = BeginPaint(h, &mut ps);+ let mut rc: RECT = zeroed();+ GetClientRect(h, &mut rc);+ let (w, hgt) = (rc.right, rc.bottom);+ let mem = CreateCompatibleDC(dc);+ let bmp = CreateCompatibleBitmap(dc, w, hgt);+ let old = SelectObject(mem, bmp);+ draw(mem, w, hgt, &v);+ BitBlt(dc, 0, 0, w, hgt, mem, 0, 0, SRCCOPY);+ SelectObject(mem, old);+ DeleteObject(bmp);+ DeleteDC(mem);+ EndPaint(h, &ps);+}++unsafe fn fill(dc: HDC, l: i32, t: i32, r: i32, b: i32, c: Rgb) {+ let br = CreateSolidBrush(rgb(c));+ FillRect(dc, &RECT { left: l, top: t, right: r, bottom: b }, br);+ DeleteObject(br);+}++unsafe fn round_rect(g: *mut GpGraphics, x: f32, y: f32, w: f32, h: f32, r: f32, c: Rgb) {+ let mut path: *mut GpPath = null_mut();+ GdipCreatePath(FillModeAlternate, &mut path);+ let d = r * 2.0;+ GdipAddPathArc(path, x, y, d, d, 180.0, 90.0);+ GdipAddPathArc(path, x + w - d, y, d, d, 270.0, 90.0);+ GdipAddPathArc(path, x + w - d, y + h - d, d, d, 0.0, 90.0);+ GdipAddPathArc(path, x, y + h - d, d, d, 90.0, 90.0);+ GdipClosePathFigure(path);+ let mut b: *mut GpSolidFill = null_mut();+ GdipCreateSolidFill(argb(c), &mut b);+ GdipFillPath(g, b as *mut GpBrush, path);+ GdipDeleteBrush(b as *mut GpBrush);+ GdipDeletePath(path);+}++unsafe fn text(dc: HDC, font: isize, c: Rgb, mut r: RECT, s: &str, flags: u32) {+ let w: Vec<u16> = s.encode_utf16().collect();+ let old = SelectObject(dc, font as _);+ SetTextColor(dc, rgb(c));+ DrawTextW(dc, w.as_ptr(), w.len() as i32, &mut r, flags | DT_NOPREFIX);+ SelectObject(dc, old);+}++unsafe fn draw(dc: HDC, w: i32, hgt: i32, v: &View) {+ let s = v.scale;+ let p = |x: i32| (x as f32 * s).round() as i32;+ SetBkMode(dc, TRANSPARENT as i32);+ fill(dc, 0, 0, w, hgt, BG);++ let (rows_top, row_h) = (p(INPUT_H + PAD), ROW_H as f32 * s);+ let nrows = v.rows.len();++ // anti-aliased shapes first, then text on top+ let mut g: *mut GpGraphics = null_mut();+ GdipCreateFromHDC(dc, &mut g);+ GdipSetSmoothingMode(g, SmoothingModeAntiAlias);+ if nrows > 0 && v.purge.is_none() {+ let y = rows_top as f32 + v.sel_f * row_h;+ round_rect(g, p(PAD) as f32, y + 2.0 * s, (w - 2 * p(PAD)) as f32, row_h - 4.0 * s, 10.0 * s, SEL);+ round_rect(g, p(PAD + 4) as f32, y + row_h / 2.0 - 10.0 * s, 3.0 * s, 20.0 * s, 1.5 * s, ACCENT);+ }+ GdipDeleteGraphics(g);++ // input row+ let mid = p(INPUT_H) / 2;+ text(dc, v.fonts[F_ICON], DIM, RECT { left: p(22), top: mid - p(14), right: p(52), bottom: mid + p(14) }, "\u{E721}", DT_SINGLELINE | DT_VCENTER);+ let area = RECT { left: p(58), top: mid - p(18), right: w - p(24), bottom: mid + p(18) };+ let shown = String::from_utf16_lossy(&v.text);+ if v.text.is_empty() {+ text(dc, v.fonts[F_INPUT], FAINT, area, "Search files and apps", DT_SINGLELINE | DT_VCENTER);+ } else {+ let mut size: SIZE = zeroed();+ let old = SelectObject(dc, v.fonts[F_INPUT] as _);+ GetTextExtentPoint32W(dc, v.text.as_ptr(), v.text.len() as i32, &mut size);+ SelectObject(dc, old);+ let overflow = (size.cx - (area.right - area.left - p(4))).max(0); // keep the end (caret) in view+ let saved = SaveDC(dc);+ IntersectClipRect(dc, area.left, area.top, area.right, area.bottom);+ text(dc, v.fonts[F_INPUT], TEXT, RECT { left: area.left - overflow, ..area }, &shown, DT_SINGLELINE | DT_VCENTER | DT_NOCLIP);+ if v.caret {+ fill(dc, area.left - overflow + size.cx + p(2), mid - p(13), area.left - overflow + size.cx + p(4), mid + p(13), ACCENT);+ }+ RestoreDC(dc, saved);+ }+ if v.text.is_empty() && v.caret {+ fill(dc, p(58), mid - p(13), p(58) + p(2), mid + p(13), ACCENT);+ }++ if !v.text.is_empty() || v.purge.is_some() {+ fill(dc, p(PAD + 6), p(INPUT_H) - 1, w - p(PAD + 6), p(INPUT_H), BORDER); // separator+ }+ if let Some(pv) = &v.purge {+ return draw_purge(dc, w, v, pv);+ }+ if nrows == 0 {+ if !v.text.is_empty() {+ text(dc, v.fonts[F_NAME], DIM, RECT { left: 0, top: rows_top, right: w, bottom: rows_top + row_h as i32 }, "No results", DT_SINGLELINE | DT_VCENTER | DT_CENTER);+ }+ return;+ }++ for (i, (name, sub, icon)) in v.rows.iter().enumerate() {+ let y0 = rows_top + (i as f32 * row_h) as i32;+ let isz = p(28);+ if *icon != 0 {+ DrawIconEx(dc, p(PAD + 16), y0 + (row_h as i32 - isz) / 2, *icon as _, isz, isz, 0, null_mut(), DI_NORMAL);+ }+ let (left, right) = (p(PAD + 16 + 28 + 14), w - p(PAD + 14));+ text(dc, v.fonts[F_NAME], TEXT, RECT { left, top: y0 + p(7), right, bottom: y0 + p(29) }, name, DT_SINGLELINE | DT_END_ELLIPSIS);+ text(dc, v.fonts[F_PATH], DIM, RECT { left, top: y0 + p(29), right, bottom: y0 + p(47) }, sub, DT_SINGLELINE | DT_END_ELLIPSIS);+ }+ let foot_y = rows_top + (nrows as f32 * row_h) as i32;+ let more = if v.total > nrows { format!(" \u{2022} {} results", v.total) } else { String::new() };+ text(+ dc,+ v.fonts[F_HINT],+ FAINT,+ RECT { left: p(PAD + 16), top: foot_y + p(4), right: w - p(PAD + 14), bottom: foot_y + p(FOOT_H) },+ &if v.renaming {+ "Type the new name \u{21B5} rename Esc cancel".to_string()+ } else {+ format!("\u{2191}\u{2193} select \u{21B5} open Ctrl+\u{21B5} folder Right-click menu Esc close{more}")+ },+ DT_SINGLELINE | DT_VCENTER,+ );++ if let Some((l, t, hot)) = v.menu {+ let (mw, pad, ih) = (p(MENU_W), p(MENU_PAD), p(MENU_ITEM_H));+ let mh = pad * 2 + MENU.len() as i32 * ih;+ let mut g: *mut GpGraphics = null_mut();+ GdipCreateFromHDC(dc, &mut g);+ GdipSetSmoothingMode(g, SmoothingModeAntiAlias);+ round_rect(g, l as f32, t as f32, mw as f32, mh as f32, 10.0 * s, BORDER);+ round_rect(g, (l + 1) as f32, (t + 1) as f32, (mw - 2) as f32, (mh - 2) as f32, 9.0 * s, MENU_BG);+ round_rect(g, (l + pad) as f32, (t + pad + hot as i32 * ih) as f32, (mw - 2 * pad) as f32, ih as f32, 7.0 * s, MENU_HOT);+ GdipDeleteGraphics(g);+ for (i, label) in MENU.iter().enumerate() {+ let label = if i == 3 && v.menu_pinned { "Remove from Start" } else { label };+ let y0 = t + pad + i as i32 * ih;+ let c = if i == MENU.len() - 1 { DANGER } else { TEXT };+ text(dc, v.fonts[F_PATH], c, RECT { left: l + pad + p(12), top: y0, right: l + mw - pad, bottom: y0 + ih }, label, DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS);+ }+ }+}++fn main() {+ use std::os::windows::process::CommandExt;+ if std::env::args().nth(1).as_deref() == Some("--autostart") {+ let exe = std::env::current_exe().unwrap();+ let ok = std::process::Command::new("reg")+ .args(["add", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run", "/v", "rs-launcher", "/t", "REG_SZ", "/d", &format!("\"{}\"", exe.display()), "/f"])+ .status()+ .map(|s| s.success())+ .unwrap_or(false);+ std::process::exit(if ok { 0 } else { 1 });+ }+ unsafe {+ SetProcessDPIAware();+ let dc = GetDC(null_mut());+ let scale = GetDeviceCaps(dc, LOGPIXELSX as i32) as f32 / 96.0;+ ReleaseDC(null_mut(), dc);++ let (mut token, mut input): (usize, GdiplusStartupInput) = (0, zeroed());+ input.GdiplusVersion = 1;+ GdiplusStartup(&mut token, &input, null_mut());++ let hi = GetModuleHandleW(null());+ let cls = wide("rs_launcher");+ RegisterClassW(&WNDCLASSW {+ style: 0,+ lpfnWndProc: Some(wndproc),+ cbClsExtra: 0,+ cbWndExtra: 0,+ hInstance: hi,+ hIcon: null_mut(),+ hCursor: LoadCursorW(null_mut(), IDC_ARROW),+ hbrBackground: null_mut(),+ lpszMenuName: null(),+ lpszClassName: cls.as_ptr(),+ });+ let main = CreateWindowExW(WS_EX_LAYERED | WS_EX_TOOLWINDOW | WS_EX_TOPMOST, cls.as_ptr(), wide("rs launcher").as_ptr(), WS_POPUP, 0, 0, 10, 10, null_mut(), null_mut(), hi, null());+ if main.is_null() {+ let msg = wide(&format!("cannot create window (error {})", GetLastError()));+ MessageBoxW(null_mut(), msg.as_ptr(), wide("rs launcher").as_ptr(), MB_ICONERROR);+ return;+ }++ // Windows 11: rounded corners, dark frame, border colour. Windows 10 rejects the corner attribute.+ let (round, dark, border) = (2i32, 1i32, rgb(BORDER) as i32);+ let hr = DwmSetWindowAttribute(main, 33, &round as *const _ as _, 4);+ DwmSetWindowAttribute(main, 20, &dark as *const _ as _, 4);+ DwmSetWindowAttribute(main, 34, &border as *const _ as _, 4);++ let font = |px: i32, weight: i32, face: &str| {+ CreateFontW(-((px as f32 * scale).round() as i32), 0, 0, 0, weight, 0, 0, 0, DEFAULT_CHARSET as _, 0, 0, CLEARTYPE_QUALITY as _, 0, wide(face).as_ptr()) as isize+ };+ let fonts = [font(22, 400, "Segoe UI"), font(16, 600, "Segoe UI"), font(13, 400, "Segoe UI"), font(20, 400, "Segoe MDL2 Assets"), font(12, 400, "Segoe UI")];+ st(|s| {+ s.scale = scale;+ s.round_with_region = hr != 0;+ s.fonts = fonts;+ });++ if RegisterHotKey(main, 1, MOD_ALT | MOD_NOREPEAT, VK_SPACE as u32) == 0 {+ MessageBoxW(null_mut(), wide("Alt+Space is taken (is the launcher already running?)").as_ptr(), wide("rs launcher").as_ptr(), MB_ICONERROR);+ return;+ }+ // SearchHost is started by svchost as a packaged app, which ignores the IFEO block the installer sets: end it whenever it appears.+ // Only when the installer's block is present (an uninstalled / unblocked setup must get its search back).+ let blocked = std::process::Command::new("reg").args(["query", r"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\SearchHost.exe", "/v", "Debugger"]).creation_flags(0x0800_0000).output().is_ok_and(|o| o.status.success());+ if blocked {+ std::thread::spawn(|| {+ let Ok(mut sys) = sysinfo::System::new() else { return };+ loop {+ sys.refresh_processes(sysinfo::ProcessesToUpdate::All, true);+ sys.processes_by_exact_name("SearchHost.exe".as_ref()).for_each(|p| {+ p.kill();+ });+ std::thread::sleep(std::time::Duration::from_secs(2));+ }+ });+ }+ let mut msg: MSG = zeroed();+ while GetMessageW(&mut msg, null_mut(), 0, 0) > 0 {+ TranslateMessage(&msg);+ DispatchMessageW(&msg);+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn wipe_unlocks_read_only_and_never_follows_junctions() {+ let base = std::env::temp_dir().join("rs-wipe-test-7c1d");+ let _ = fs::remove_dir_all(&base);+ let (doomed, outside) = (base.join("doomed"), base.join("outside"));+ fs::create_dir_all(doomed.join("sub")).unwrap();+ fs::create_dir_all(&outside).unwrap();+ let ro = doomed.join("sub").join("ro.txt");+ fs::write(&ro, "x").unwrap();+ let mut perm = fs::metadata(&ro).unwrap().permissions();+ perm.set_readonly(true);+ fs::set_permissions(&ro, perm).unwrap();+ fs::write(outside.join("keep.txt"), "keep").unwrap();+ let link = doomed.join("link");+ assert!(std::process::Command::new("cmd").args(["/c", "mklink", "/J"]).arg(&link).arg(&outside).output().unwrap().status.success());++ assert_eq!(measure(&doomed), (2, 1), "ro.txt + the junction itself, target not counted");+ let mut failed = Vec::new();+ wipe(&doomed, &mut failed);+ assert!(failed.is_empty(), "{failed:?}");+ assert!(!doomed.exists());+ assert!(outside.join("keep.txt").exists(), "junction target must survive");+ fs::remove_dir_all(&base).unwrap();+ }++ #[test]+ fn sizes() {+ assert_eq!(size_text(512), "512 B");+ assert_eq!(size_text(1536), "1.5 KB");+ assert_eq!(size_text(5 * 1_048_576), "5.0 MB");+ }+}diff --git a/plugins/rust-search/src/bin/rs-top.rs b/plugins/rust-search/src/bin/rs-top.rsnew file mode 100644index 0000000..5a2b6ef--- /dev/null+++ b/plugins/rust-search/src/bin/rs-top.rs@@ -0,0 +1,88 @@+// rs-top [N] [--cpu] top N process groups by memory (or CPU), svchost split out with the services it hosts.+// rs-top --kill <pid|name> kill one process, or every process with that exe name (e.g. --kill chrome.exe).+// To stop a *service* for good, use rs-debloat.+use std::{collections::HashMap, env, process::Command, thread};+use sysinfo::{ProcessesToUpdate, System, MINIMUM_CPU_UPDATE_INTERVAL};++/// pid -> hosted service names, from `tasklist /svc`.+fn services() -> HashMap<u32, String> {+ let out = Command::new("tasklist").args(["/svc", "/fo", "csv", "/nh"]).output().map(|o| String::from_utf8_lossy(&o.stdout).into_owned()).unwrap_or_default();+ out.lines()+ .filter_map(|l| {+ let f: Vec<&str> = l.trim().trim_matches('"').split("\",\"").collect(); // "img","pid","svc1,svc2"+ (f.len() == 3 && f[2] != "N/A").then(|| Some((f[1].parse().ok()?, f[2].to_string()))).flatten()+ })+ .collect()+}++struct Row {+ label: String,+ count: usize,+ pid: u32,+ cpu: f32,+ mem: u64,+}++fn main() {+ let args: Vec<String> = env::args().skip(1).collect();+ let mut sys = System::new().expect("cannot read system information");+ sys.refresh_processes(ProcessesToUpdate::All, true);++ if args.first().map(String::as_str) == Some("--kill") {+ let Some(target) = args.get(1) else { return eprintln!("usage: rs-top --kill <pid|name>") };+ let pid = target.parse::<u32>().ok();+ let victims: Vec<_> = sys+ .processes()+ .values()+ .filter(|p| match pid {+ Some(id) => p.pid().as_u32() == id,+ None => p.name().to_string_lossy().eq_ignore_ascii_case(target),+ })+ .collect();+ if victims.is_empty() {+ return println!("no process matches {target}");+ }+ for p in victims {+ let ok = p.kill();+ println!("{} {} (pid {})", if ok { "killed" } else { "cannot kill (needs admin?)" }, p.name().to_string_lossy(), p.pid());+ }+ return;+ }++ // CPU usage needs two samples a moment apart.+ thread::sleep(MINIMUM_CPU_UPDATE_INTERVAL);+ sys.refresh_processes(ProcessesToUpdate::All, true);+ sys.refresh_memory();+ let cores = thread::available_parallelism().map(|n| n.get()).unwrap_or(1) as f32;+ let svc = services();++ let mut rows: HashMap<String, Row> = HashMap::new();+ for (pid, p) in sys.processes() {+ let name = p.name().to_string_lossy().into_owned();+ // each svchost hosts different services, so it stays one row per process+ let key = if name.eq_ignore_ascii_case("svchost.exe") { format!("{name} {pid}") } else { name.clone() };+ let label = match svc.get(&pid.as_u32()) {+ Some(s) if key != name => format!("{name} [{s}]"),+ _ => name,+ };+ let r = rows.entry(key).or_insert(Row { label, count: 0, pid: pid.as_u32(), cpu: 0.0, mem: 0 });+ r.count += 1;+ r.cpu += p.cpu_usage() / cores;+ r.mem += p.memory();+ }+ let mut rows: Vec<Row> = rows.into_values().collect();+ if args.iter().any(|a| a == "--cpu") {+ rows.sort_by(|a, b| b.cpu.total_cmp(&a.cpu));+ } else {+ rows.sort_by_key(|r| std::cmp::Reverse(r.mem));+ }+ let n = args.iter().find_map(|a| a.parse::<usize>().ok()).unwrap_or(15);++ let gb = |b: u64| b as f64 / (1u64 << 30) as f64;+ println!("RAM {:.1} / {:.1} GB used\n", gb(sys.used_memory()), gb(sys.total_memory()));+ println!("{:>5} {:>8} {}", "CPU%", "MEM MB", "PROCESS");+ for r in rows.iter().take(n) {+ let who = if r.count == 1 { format!("{} (pid {})", r.label, r.pid) } else { format!("{} x{}", r.label, r.count) };+ println!("{:>5.1} {:>8} {}", r.cpu, r.mem >> 20, who);+ }+}diff --git a/plugins/rust-search/src/common.rs b/plugins/rust-search/src/common.rsnew file mode 100644index 0000000..998b00e--- /dev/null+++ b/plugins/rust-search/src/common.rs@@ -0,0 +1,59 @@+// Shared by rs and rs-launcher: drive discovery and the pipe client.+#![allow(dead_code)]+use std::{+ fs::OpenOptions,+ io::{self, Read, Write},+};+use windows_sys::Win32::Storage::FileSystem::{GetDriveTypeW, GetLogicalDrives, GetVolumeInformationW};++const DRIVE_FIXED: u32 = 3;++pub fn pipe_name(d: char) -> String {+ format!("\\\\.\\pipe\\rs-search-{d}")+}++/// Letters of all mounted drives. Cheap: no volume is touched, so sleeping disks stay asleep.+pub fn drive_letters() -> Vec<char> {+ let mask = unsafe { GetLogicalDrives() };+ (0..26).filter(|i| mask & (1 << i) != 0).map(|i| (b'A' + i as u8) as char).collect()+}++/// Fixed (non-removable, non-network) drives formatted as NTFS: the ones the service can index.+pub fn fixed_ntfs_drives() -> Vec<char> {+ drive_letters()+ .into_iter()+ .filter(|d| {+ let root: Vec<u16> = format!("{d}:\\").encode_utf16().chain([0]).collect();+ let mut fs = [0u16; 16];+ let (ty, ok) = unsafe {+ let ty = GetDriveTypeW(root.as_ptr());+ let null = std::ptr::null_mut();+ (ty, GetVolumeInformationW(root.as_ptr(), null, 0, null as _, null as _, null as _, fs.as_mut_ptr(), 16))+ };+ ty == DRIVE_FIXED && ok != 0 && String::from_utf16_lossy(&fs).trim_end_matches('\0') == "NTFS"+ })+ .collect()+}++/// Asks drive `d`'s service. None = no service for that drive (pipe missing).+pub fn ask(d: char, q: &str) -> Option<io::Result<String>> {+ let mut p = match OpenOptions::new().read(true).write(true).open(pipe_name(d)) {+ Ok(p) => p,+ Err(e) if e.kind() == io::ErrorKind::NotFound => return None,+ Err(e) => return Some(Err(e)),+ };+ Some((|| {+ p.write_all(q.as_bytes())?;+ let (mut out, mut chunk) = (Vec::new(), [0u8; 1 << 16]);+ loop {+ match p.read(&mut chunk) {+ Ok(0) => break,+ Ok(n) => out.extend_from_slice(&chunk[..n]),+ // the server ends its reply by hanging up: BROKEN_PIPE (109) / NOT_CONNECTED (233) is EOF+ Err(e) if matches!(e.raw_os_error(), Some(109 | 233)) => break,+ Err(e) => return Err(e),+ }+ }+ Ok(String::from_utf8_lossy(&out).into_owned())+ })())+}diff --git a/plugins/rust-search/src/main.rs b/plugins/rust-search/src/main.rsnew file mode 100644index 0000000..74e7ffc--- /dev/null+++ b/plugins/rust-search/src/main.rs@@ -0,0 +1,856 @@+// rs [-d X] <term>... search file names on an NTFS volume (reads the MFT; needs an admin shell).+// rs [-d X] --serve keep the index in memory, follow the USN journal, answer queries over a named pipe.+// With a server running, `rs <term>` answers in milliseconds; without one it scans the volume itself.+// rs --install / --uninstall (admin) run the server at every boot as a SYSTEM scheduled task.+use std::{+ env,+ fs::{self, File},+ io::{self, BufWriter, Read, Write},+ mem::{size_of, ManuallyDrop},+ os::windows::io::FromRawHandle,+ path::PathBuf,+ ptr,+ sync::{Arc, Mutex},+ thread,+ time::{Duration, Instant},+};+mod common;+use common::*;+use windows_sys::Win32::{+ Foundation::*,+ Security::{Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW, SECURITY_ATTRIBUTES},+ Storage::FileSystem::*,+ System::{IO::DeviceIoControl, Ioctl::*, Pipes::*},+};++/// Compact file index. A file's slot is its MFT record number (the low 48 bits of the FRN; the sequence+/// number is dropped), so lookup is a plain Vec index. Names live in one byte arena instead of one+/// String each. ~12 bytes per slot + the name bytes, about a third of a HashMap<u64, (u64, String)>.+#[derive(Clone, Copy, Default)]+struct Ent {+ parent: u32, // parent's record number+ off: u32, // name offset in the arena+ len: u16, // name length in bytes; 0 = slot unused+}++#[derive(Default)]+struct Index {+ ents: Vec<Ent>,+ arena: Vec<u8>,+ live: usize,+ garbage: usize, // arena bytes owned by deleted/renamed entries+}++const MAGIC: &[u8; 8] = b"RSIDX001";+const REC_MASK: u64 = (1 << 48) - 1;+const MAX_REC: usize = 1 << 28; // ignore absurd record numbers rather than allocating for them++impl Index {+ fn new() -> Self {+ Self::default()+ }++ fn len(&self) -> usize {+ self.live+ }++ fn insert(&mut self, frn: u64, parent: u64, name: &str) {+ let rec = (frn & REC_MASK) as usize;+ if rec >= MAX_REC || name.len() > u16::MAX as usize {+ return;+ }+ if rec >= self.ents.len() {+ // grow in fixed chunks: after shrink() a doubling Vec would double the whole index+ if rec >= self.ents.capacity() {+ self.ents.reserve_exact(rec + 1 - self.ents.len() + (1 << 16));+ }+ self.ents.resize(rec + 1, Ent::default());+ }+ let old = self.ents[rec].len as usize;+ if old > 0 {+ self.garbage += old;+ } else {+ self.live += 1;+ }+ if self.arena.capacity() - self.arena.len() < name.len() {+ self.arena.reserve_exact(1 << 20);+ }+ let off = self.arena.len() as u32;+ self.arena.extend_from_slice(name.as_bytes());+ self.ents[rec] = Ent { parent: (parent & REC_MASK) as u32, off, len: name.len() as u16 };+ if self.garbage > (8 << 20) && self.garbage * 3 > self.arena.len() {+ self.compact();+ }+ }++ fn remove(&mut self, frn: u64) {+ if let Some(e) = self.ents.get_mut((frn & REC_MASK) as usize) {+ if e.len > 0 {+ self.garbage += e.len as usize;+ e.len = 0;+ self.live -= 1;+ }+ }+ }++ fn name(&self, e: &Ent) -> &str {+ // SAFETY: the arena only ever receives bytes of a &str, and (off, len) always span one whole name.+ unsafe { std::str::from_utf8_unchecked(&self.arena[e.off as usize..e.off as usize + e.len as usize]) }+ }++ /// (parent record, name) of a live record.+ fn get(&self, rec: u32) -> Option<(u32, &str)> {+ self.ents.get(rec as usize).filter(|e| e.len > 0).map(|e| (e.parent, self.name(e)))+ }++ /// `f(record number, name)` over every live entry, split across all cores; results keep record order.+ fn par_filter_map<T: Send>(&self, f: impl Fn(u32, &str) -> Option<T> + Sync) -> Vec<T> {+ let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).min(8);+ let chunk = self.ents.len().div_ceil(threads).max(1);+ std::thread::scope(|s| {+ let f = &f;+ let jobs: Vec<_> = self+ .ents+ .chunks(chunk)+ .enumerate()+ .map(|(ci, c)| {+ s.spawn(move || {+ let live = c.iter().enumerate().filter(|(_, e)| e.len > 0);+ live.filter_map(|(i, e)| f((ci * chunk + i) as u32, self.name(e))).collect::<Vec<T>>()+ })+ })+ .collect();+ jobs.into_iter().flat_map(|j| j.join().unwrap()).collect()+ })+ }++ fn compact(&mut self) {+ let mut arena = Vec::with_capacity(self.arena.len() - self.garbage);+ for e in self.ents.iter_mut().filter(|e| e.len > 0) {+ let s = e.off as usize;+ let off = arena.len() as u32;+ arena.extend_from_slice(&self.arena[s..s + e.len as usize]);+ e.off = off;+ }+ self.arena = arena;+ self.garbage = 0;+ }++ /// Snapshot file: header, then the slots, then the name arena. `jid`/`usn` = the journal position the+ /// snapshot is consistent with, so a later run can replay only what changed since.+ fn write_to(&self, w: &mut impl Write, jid: u64, usn: i64) -> io::Result<()> {+ w.write_all(MAGIC)?;+ for v in [jid, usn as u64, self.ents.len() as u64, self.arena.len() as u64, self.live as u64] {+ w.write_all(&v.to_le_bytes())?;+ }+ for e in &self.ents {+ w.write_all(&e.parent.to_le_bytes())?;+ w.write_all(&e.off.to_le_bytes())?;+ w.write_all(&e.len.to_le_bytes())?;+ w.write_all(&[0, 0])?;+ }+ w.write_all(&self.arena)+ }++ /// Inverse of write_to. None for anything that is not a fully consistent snapshot: the arena is read+ /// back through `from_utf8_unchecked`, so every live name is re-validated here.+ fn read_from(b: &[u8]) -> Option<(Index, u64, i64)> {+ const HEADER: usize = 8 + 5 * 8;+ if b.len() < HEADER || &b[..8] != MAGIC {+ return None;+ }+ let num = |i: usize| u64::from_le_bytes(b[8 + i * 8..16 + i * 8].try_into().unwrap());+ let (jid, usn, n_ents, arena_len, live) = (num(0), num(1) as i64, num(2) as usize, num(3) as usize, num(4) as usize);+ if n_ents > MAX_REC || b.len() != HEADER + n_ents * 12 + arena_len {+ return None;+ }+ let arena = b[HEADER + n_ents * 12..].to_vec();+ let (mut ents, mut seen, mut used) = (Vec::with_capacity(n_ents), 0usize, 0usize);+ for c in b[HEADER..HEADER + n_ents * 12].chunks_exact(12) {+ let e = Ent { parent: u32::from_le_bytes(c[0..4].try_into().unwrap()), off: u32::from_le_bytes(c[4..8].try_into().unwrap()), len: u16::from_le_bytes(c[8..10].try_into().unwrap()) };+ if e.len > 0 {+ let name = arena.get(e.off as usize..e.off as usize + e.len as usize)?;+ std::str::from_utf8(name).ok()?;+ seen += 1;+ used += e.len as usize;+ }+ ents.push(e);+ }+ (seen == live).then(|| (Index { ents, arena, live, garbage: arena_len.saturating_sub(used) }, jid, usn))+ }++ /// Drop the slack left by growth; call once after the initial scan.+ fn shrink(&mut self) {+ self.compact();+ self.ents.shrink_to_fit();+ self.arena.shrink_to_fit();+ }+}+const SHOW: usize = 100;++fn open_volume(drive: char) -> Result<HANDLE, String> {+ let path: Vec<u16> = format!("\\\\.\\{drive}:").encode_utf16().chain([0]).collect();+ let h = unsafe {+ CreateFileW(path.as_ptr(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, ptr::null(), OPEN_EXISTING, 0, ptr::null_mut())+ };+ if h == INVALID_HANDLE_VALUE {+ return Err(format!(+ "cannot open {drive}: (error {}). Run from an elevated (admin) shell; volume must be NTFS.",+ unsafe { GetLastError() }+ ));+ }+ Ok(h)+}++/// Calls f(frn, parent frn, reason, name) for each USN_RECORD_V2 in an ioctl reply (first 8 bytes = next cursor).+fn records(b: &[u8], mut f: impl FnMut(u64, u64, u32, String)) {+ let mut off = 8;+ while off + 60 <= b.len() {+ let r = &b[off..];+ let len = u32::from_le_bytes(r[0..4].try_into().unwrap()) as usize;+ if len == 0 || u16::from_le_bytes(r[4..6].try_into().unwrap()) != 2 {+ break; // only V2 (NTFS)+ }+ let frn = u64::from_le_bytes(r[8..16].try_into().unwrap());+ let parent = u64::from_le_bytes(r[16..24].try_into().unwrap());+ let reason = u32::from_le_bytes(r[40..44].try_into().unwrap());+ let nlen = u16::from_le_bytes(r[56..58].try_into().unwrap()) as usize;+ let noff = u16::from_le_bytes(r[58..60].try_into().unwrap()) as usize;+ let name: Vec<u16> = r[noff..noff + nlen].chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect();+ f(frn, parent, reason, String::from_utf16_lossy(&name));+ off += len;+ }+}++fn scan(h: HANDLE) -> Result<Index, String> {+ let mut idx = Index::new();+ let mut med = MFT_ENUM_DATA_V0 { StartFileReferenceNumber: 0, LowUsn: 0, HighUsn: i64::MAX };+ let mut buf = vec![0u8; 1 << 20];+ loop {+ let mut n = 0u32;+ let ok = unsafe {+ DeviceIoControl(+ h,+ FSCTL_ENUM_USN_DATA,+ &med as *const _ as _,+ size_of::<MFT_ENUM_DATA_V0>() as u32,+ buf.as_mut_ptr() as _,+ buf.len() as u32,+ &mut n,+ ptr::null_mut(),+ )+ };+ if ok == 0 {+ let e = unsafe { GetLastError() };+ return if e == ERROR_HANDLE_EOF {+ idx.shrink();+ Ok(idx)+ } else { Err(format!("FSCTL_ENUM_USN_DATA failed (error {e})")) };+ }+ let b = &buf[..n as usize];+ med.StartFileReferenceNumber = u64::from_le_bytes(b[..8].try_into().unwrap());+ records(b, |frn, parent, _, name| {+ idx.insert(frn, parent, &name);+ });+ }+}++fn journal(h: HANDLE) -> Result<USN_JOURNAL_DATA_V0, String> {+ let mut j: USN_JOURNAL_DATA_V0 = unsafe { std::mem::zeroed() };+ let mut n = 0u32;+ let ok = unsafe {+ DeviceIoControl(h, FSCTL_QUERY_USN_JOURNAL, ptr::null(), 0, &mut j as *mut _ as _, size_of::<USN_JOURNAL_DATA_V0>() as u32, &mut n, ptr::null_mut())+ };+ if ok == 0 {+ return Err(format!("USN journal not available (error {})", unsafe { GetLastError() }));+ }+ Ok(j)+}++/// The live index plus the journal position it is consistent with. Index and position change together+/// under one lock, so a snapshot taken under that lock can always be resumed from `usn`.+struct Shared {+ idx: Index,+ jid: u64,+ usn: i64,+ dirty: bool, // changed since the last snapshot+}++/// Applies journal changes to the shared index. Returns only when the journal can no longer be followed.+fn tail(drive: char, sh: &Mutex<Shared>) {+ let h = match open_volume(drive) {+ Ok(h) => h,+ Err(e) => return eprintln!("{e}"),+ };+ let mask = USN_REASON_FILE_CREATE | USN_REASON_FILE_DELETE | USN_REASON_RENAME_NEW_NAME;+ let mut buf = vec![0u8; 1 << 16];+ let (jid, mut usn) = {+ let g = sh.lock().unwrap();+ (g.jid, g.usn)+ };+ loop {+ let rd = READ_USN_JOURNAL_DATA_V0 { StartUsn: usn, ReasonMask: mask, ReturnOnlyOnClose: 0, Timeout: 1, BytesToWaitFor: 1, UsnJournalID: jid };+ let mut n = 0u32;+ let ok = unsafe {+ DeviceIoControl(h, FSCTL_READ_USN_JOURNAL, &rd as *const _ as _, size_of::<READ_USN_JOURNAL_DATA_V0>() as u32, buf.as_mut_ptr() as _, buf.len() as u32, &mut n, ptr::null_mut())+ };+ if ok == 0 {+ eprintln!("journal read failed (error {}); rebuilding the index", unsafe { GetLastError() });+ unsafe { CloseHandle(h) };+ return;+ }+ let b = &buf[..n as usize];+ usn = i64::from_le_bytes(b[..8].try_into().unwrap());+ let mut g = sh.lock().unwrap();+ if b.len() > 8 {+ records(b, |frn, parent, reason, name| {+ if reason & USN_REASON_FILE_DELETE != 0 {+ g.idx.remove(frn);+ } else {+ g.idx.insert(frn, parent, &name);+ }+ });+ g.dirty = true;+ }+ g.usn = usn;+ }+}++/// Keeps the index current for as long as the process lives: follow the journal, and when that is no+/// longer possible (journal wrapped past us, recreated, volume remounted) index from scratch and go on.+fn maintain(drive: char, sh: Arc<Mutex<Shared>>) {+ loop {+ tail(drive, &sh);+ thread::sleep(Duration::from_secs(10)); // never spin if the failure is persistent+ loop {+ match open_volume(drive).and_then(|h| {+ // cursor first, then scan: nothing is missed+ let r = journal(h).and_then(|j| scan(h).map(|idx| (idx, j)));+ unsafe { CloseHandle(h) };+ r+ }) {+ Ok((idx, j)) => {+ *sh.lock().unwrap() = Shared { idx, jid: j.UsnJournalID, usn: j.NextUsn, dirty: true };+ eprintln!("index rebuilt");+ break;+ }+ Err(e) => {+ eprintln!("rebuild failed: {e}; retrying in 30s");+ thread::sleep(Duration::from_secs(30));+ }+ }+ }+ }+}++/// Per-drive snapshot path. Under the account's own LOCALAPPDATA: for the SYSTEM service that is its private+/// profile, so other users cannot read a listing of every file name on the disk.+fn index_path(drive: char) -> Option<PathBuf> {+ Some(PathBuf::from(env::var_os("LOCALAPPDATA")?).join("rs-search").join(format!("index-{drive}.bin")))+}++/// The saved index and the journal position to resume from, if it still fits this volume's journal.+fn load_saved(drive: char, j: &USN_JOURNAL_DATA_V0) -> Option<(Index, i64)> {+ let (idx, jid, usn) = Index::read_from(&fs::read(index_path(drive)?).ok()?)?;+ (jid == j.UsnJournalID && usn >= j.FirstUsn && usn <= j.NextUsn).then_some((idx, usn))+}++/// Writes the snapshot (temp file + rename, so a crash never leaves a torn file) if anything changed.+fn save(drive: char, sh: &Mutex<Shared>) {+ let Some(path) = index_path(drive) else { return };+ let mut g = sh.lock().unwrap();+ if !g.dirty {+ return;+ }+ let tmp = path.with_extension("tmp");+ let r = fs::create_dir_all(path.parent().unwrap()).and_then(|_| {+ let mut w = BufWriter::new(File::create(&tmp)?);+ g.idx.write_to(&mut w, g.jid, g.usn)?;+ w.flush()?;+ fs::rename(&tmp, &path)+ });+ match r {+ Ok(()) => g.dirty = false,+ Err(e) => eprintln!("cannot save index to {}: {e}", path.display()),+ }+}++const SAVE_EVERY: Duration = Duration::from_secs(600);++fn full_path(idx: &Index, drive: char, mut rec: u32) -> String {+ let mut parts = Vec::new();+ // depth cap guards against cycles in a corrupt index+ while let Some((parent, name)) = idx.get(rec) {+ parts.push(name);+ rec = parent;+ if parts.len() > 256 {+ break;+ }+ }+ parts.reverse();+ format!("{drive}:\\{}", parts.join("\\"))+}++/// Case-insensitive `name.contains(t)` for an already-lowercase `t`. Names are scanned millions of times+/// per query, so the ASCII case (nearly all names) must not allocate.+fn contains_ci(name: &str, t: &str) -> bool {+ if name.is_ascii() && t.is_ascii() {+ let (h, n) = (name.as_bytes(), t.as_bytes());+ if n.is_empty() {+ return true;+ }+ if n.len() > h.len() {+ return false;+ }+ // hand-rolled: the first-byte test rejects almost every position without a call+ 'at: for i in 0..=h.len() - n.len() {+ if h[i].to_ascii_lowercase() != n[0] {+ continue;+ }+ for j in 1..n.len() {+ if h[i + j].to_ascii_lowercase() != n[j] {+ continue 'at;+ }+ }+ return true;+ }+ false+ } else {+ name.to_lowercase().contains(t)+ }+}++/// Ranked paths (exact name, then name starts with first term, then the rest; shorter names first) and total hit count.+fn query(idx: &Index, drive: char, terms: &[String]) -> (Vec<String>, usize) {+ // Shortcuts (.lnk) are candidates first: Start Menu entries are how apps get found, and a plain+ // name-length cut could drop "Google Chrome.lnk" behind hundreds of chrome_*.pak files.+ let mut hits: Vec<(u8, u8, usize, u32)> = idx.par_filter_map(|rec, n| {+ if !terms.iter().all(|t| contains_ci(n, t)) {+ return None;+ }+ let n = n.to_lowercase(); // only for the few hits+ let rank = if n == terms[0] { 0 } else if n.starts_with(&terms[0]) { 1 } else { 2 };+ Some((!(n.ends_with(".lnk") || n.ends_with(".exe")) as u8, rank, n.len(), rec))+ });+ let total = hits.len();+ // shortcut: ties beyond the best CAND candidates are cut in arbitrary order; raise CAND if that ever shows.+ const CAND: usize = 1000;+ if hits.len() > CAND {+ hits.select_nth_unstable(CAND - 1);+ hits.truncate(CAND);+ }+ // Order: Start Menu apps, other shortcuts (.lnk), .exe files, everything else; inside a tier by name match rank;+ // ties: OS component stores (WinSxS, WindowsApps) last, then shorter paths first.+ let mut paths: Vec<(u8, u8, u8, usize, String)> = hits+ .into_iter()+ .map(|(_, rank, _, f)| {+ let p = full_path(idx, drive, f);+ let l = p.to_lowercase();+ let tier = if l.ends_with(".lnk") { if l.contains(START_MENU) { 0 } else { 1 } } else if l.ends_with(".exe") { 2 } else { 3 };+ let junk = JUNK.iter().any(|j| l.contains(j)) as u8;+ (tier, rank, junk, p.len(), p)+ })+ .collect();+ paths.sort_unstable();+ (paths.into_iter().take(SHOW).map(|t| t.4).collect(), total)+}++const START_MENU: &str = "\\start menu\\programs\\";++const JUNK: [&str; 2] = ["\\winsxs\\", "\\windowsapps\\"];++fn render(idx: &Index, drive: char, terms: &[String]) -> String {+ let (paths, total) = query(idx, drive, terms);+ let mut out = paths.join("\n");+ if !out.is_empty() {+ out.push('\n');+ }+ if total > SHOW {+ out += &format!("... {} more\n", total - SHOW);+ }+ out+}++/// Pipe security: only SYSTEM, Administrators and `allow` (a user SID) get access. None = default (admins only).+fn pipe_security(allow: Option<&str>) -> Result<Option<SECURITY_ATTRIBUTES>, String> {+ let Some(sid) = allow else { return Ok(None) };+ let sddl: Vec<u16> = format!("D:(A;;GA;;;SY)(A;;GA;;;BA)(A;;GRGW;;;{sid})").encode_utf16().chain([0]).collect();+ let mut sd = ptr::null_mut();+ let ok = unsafe { ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.as_ptr(), 1, &mut sd, ptr::null_mut()) };+ if ok == 0 {+ return Err(format!("bad --allow SID (error {})", unsafe { GetLastError() }));+ }+ // sd is intentionally never freed: it lives as long as the pipe, i.e. the process+ Ok(Some(SECURITY_ATTRIBUTES { nLength: size_of::<SECURITY_ATTRIBUTES>() as u32, lpSecurityDescriptor: sd, bInheritHandle: 0 }))+}++fn serve(drive: char, allow: Option<String>) -> Result<(), String> {+ let sa = pipe_security(allow.as_deref())?;+ let h = open_volume(drive)?;+ let j = journal(h)?; // read the cursor BEFORE scanning so no change is missed+ let t = Instant::now();+ // A saved snapshot is only a head start: the journal replays everything that changed since it was written.+ let (idx, usn, how) = match load_saved(drive, &j) {+ Some((idx, usn)) => (idx, usn, "loaded"),+ None => (scan(h)?, j.NextUsn, "scanned"),+ };+ unsafe { CloseHandle(h) };+ eprintln!("{how} {} entries in {:?}, serving {}", idx.len(), t.elapsed(), pipe_name(drive));+ let idx = Arc::new(Mutex::new(Shared { idx, jid: j.UsnJournalID, usn, dirty: how == "scanned" }));++ let sh = idx.clone();+ thread::spawn(move || maintain(drive, sh));+ let sh = idx.clone();+ thread::spawn(move || loop {+ save(drive, &sh);+ thread::sleep(SAVE_EVERY);+ });++ let name: Vec<u16> = pipe_name(drive).encode_utf16().chain([0]).collect();+ let pipe = unsafe {+ CreateNamedPipeW(name.as_ptr(), PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_TYPE_BYTE | PIPE_WAIT, 1, 1 << 16, 1 << 16, 0, sa.as_ref().map_or(ptr::null(), |s| s as *const _))+ };+ if pipe == INVALID_HANDLE_VALUE {+ return Err(format!("cannot create pipe (error {}); is a server already running?", unsafe { GetLastError() }));+ }+ loop {+ let ok = unsafe { ConnectNamedPipe(pipe, ptr::null_mut()) };+ if ok != 0 || unsafe { GetLastError() } == ERROR_PIPE_CONNECTED {+ // ManuallyDrop: the pipe handle is reused for the next client, so File must not close it+ let mut f = ManuallyDrop::new(unsafe { File::from_raw_handle(pipe as _) });+ let mut buf = [0u8; 4096];+ if let Ok(n) = f.read(&mut buf) {+ let terms = split_terms(&String::from_utf8_lossy(&buf[..n]));+ if !terms.is_empty() {+ let out = render(&idx.lock().unwrap().idx, drive, &terms);+ let _ = f.write_all(out.as_bytes());+ let _ = f.sync_all(); // FlushFileBuffers: wait until the client has read the reply+ }+ }+ }+ unsafe { DisconnectNamedPipe(pipe) };+ }+}++/// rs --bench <term>: scan once, then time the query 5 times (separates query cost from pipe/process overhead).+fn bench(drive: char, args: &[String]) -> Result<(), String> {+ let terms = split_terms(&args.join(" "));+ if terms.is_empty() {+ return Err("usage: rs --bench <term>".into());+ }+ let idx = scan(open_volume(drive)?)?;+ for _ in 0..5 {+ let t = Instant::now();+ let (_, total) = query(&idx, drive, &terms);+ println!("query {:?} -> {total} hits in {:?}", terms, t.elapsed());+ }+ Ok(())+}++const TASK: &str = "rs-search";++fn ps(script: &str) -> Result<String, String> {+ let o = std::process::Command::new("powershell")+ .args(["-NoProfile", "-NonInteractive", "-Command", script])+ .output()+ .map_err(|e| format!("cannot run powershell: {e}"))?;+ if o.status.success() {+ Ok(String::from_utf8_lossy(&o.stdout).into_owned())+ } else {+ Err(String::from_utf8_lossy(&o.stderr).into_owned())+ }+}++fn install_dir() -> std::path::PathBuf {+ std::path::Path::new(&env::var("ProgramFiles").unwrap_or_else(|_| "C:\\Program Files".into())).join("rs-search")+}++/// Runs `rs --serve` for every fixed NTFS drive at boot, as SYSTEM, from Program Files (admin-only writable:+/// a SYSTEM task must never run a binary from a user-writable folder). The installing user gets the pipes.+fn install() -> Result<(), String> {+ let who = ps("whoami /user /fo csv /nh")?;+ let sid = who.trim().rsplit('"').nth(1).unwrap_or("").to_string(); // "DOM\user","S-1-5-..."+ if !sid.starts_with("S-1-") || !sid.chars().all(|c| c.is_ascii_digit() || c == '-' || c == 'S') {+ return Err(format!("cannot determine your SID from: {who}"));+ }+ let drives = fixed_ntfs_drives();+ if drives.is_empty() {+ return Err("no fixed NTFS drives found".into());+ }+ let _ = ps(&format!("Get-ScheduledTask -TaskName '{TASK}*' -ErrorAction SilentlyContinue | Stop-ScheduledTask; Start-Sleep 1"));+ let dir = install_dir();+ let dst = dir.join("rs.exe");+ let me = env::current_exe().map_err(|e| e.to_string())?;+ std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e} (run as admin)", dir.display()))?;+ if me.canonicalize().ok() != dst.canonicalize().ok() {+ std::fs::copy(&me, &dst).map_err(|e| format!("copy to {}: {e}", dst.display()))?;+ }+ let list = drives.iter().map(|d| format!("'{d}'")).collect::<Vec<_>>().join(",");+ ps(&format!(+ "Unregister-ScheduledTask -TaskName {TASK} -Confirm:$false -ErrorAction SilentlyContinue; \+ $t = New-ScheduledTaskTrigger -AtStartup; \+ $s = New-ScheduledTaskSettingsSet -ExecutionTimeLimit ([TimeSpan]::Zero) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -Priority 4 -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1); \+ foreach ($d in {list}) {{ \+ $a = New-ScheduledTaskAction -Execute '{exe}' -Argument \"-d $d --serve --allow {sid}\"; \+ Register-ScheduledTask -TaskName \"{TASK}-$d\" -Action $a -Trigger $t -Settings $s -User SYSTEM -RunLevel Highest -Force | Out-Null; \+ Start-ScheduledTask -TaskName \"{TASK}-$d\" \+ }}",+ exe = dst.display()+ ))?;+ let names: Vec<String> = drives.iter().map(|d| format!("{d}:")).collect();+ println!("installed to {} for {} and started; runs at every boot. Query with: rs <term>", dst.display(), names.join(" "));+ Ok(())+}++fn uninstall() -> Result<(), String> {+ ps(&format!("Get-ScheduledTask -TaskName '{TASK}*' -ErrorAction SilentlyContinue | ForEach-Object {{ Stop-ScheduledTask -InputObject $_; Unregister-ScheduledTask -InputObject $_ -Confirm:$false }}; Start-Sleep 1"))?;+ let _ = std::fs::remove_dir_all(install_dir());+ // the service's saved indexes live in SYSTEM's profile+ let _ = std::fs::remove_dir_all(PathBuf::from(env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".into())).join(r"System32\config\systemprofile\AppData\Local\rs-search"));+ println!("uninstalled");+ Ok(())+}++fn split_terms(s: &str) -> Vec<String> {+ s.split_whitespace().map(|t| t.to_lowercase()).collect()+}++/// The boot task has no console, so stderr would go nowhere: when run from Program Files, send it to serve-<drive>.log there+/// (admin-only writable, unlike ProgramData where a user could plant a link for SYSTEM to follow). Restarted at 1 MB.+fn serve_log(drive: char) {+ use std::os::windows::io::IntoRawHandle;+ use windows_sys::Win32::System::Console::{STD_ERROR_HANDLE, SetStdHandle};+ if !env::current_exe().is_ok_and(|e| e.starts_with(install_dir())) {+ return;+ }+ let p = install_dir().join(format!("serve-{drive}.log"));+ if std::fs::metadata(&p).is_ok_and(|m| m.len() > 1 << 20) {+ let _ = std::fs::remove_file(&p);+ }+ let Ok(f) = std::fs::OpenOptions::new().create(true).append(true).open(&p) else { return };+ unsafe { SetStdHandle(STD_ERROR_HANDLE, f.into_raw_handle() as _) };+ let t = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());+ eprintln!("[{t}] serve {drive}: start"); // unix seconds, like the launcher's install.log+}++fn main() {+ let mut args: Vec<String> = env::args().skip(1).collect();+ let (mut drive, mut explicit) = ('C', None);+ if args.first().map(|a| a == "-d").unwrap_or(false) && args.len() >= 2 {+ drive = args[1].chars().next().unwrap_or('C').to_ascii_uppercase();+ explicit = Some(drive);+ args.drain(..2);+ }+ let cmd = args.first().map(String::as_str);+ if cmd == Some("--serve") {+ serve_log(drive);+ }+ if matches!(cmd, Some("--serve" | "--install" | "--uninstall" | "--bench")) {+ let allow = args.iter().position(|a| a == "--allow").and_then(|i| args.get(i + 1)).cloned();+ let r = match cmd {+ Some("--serve") => serve(drive, allow),+ Some("--install") => install(),+ Some("--bench") => bench(drive, &args[1..]),+ _ => uninstall(),+ };+ if let Err(e) = r {+ eprintln!("{e}");+ std::process::exit(1);+ }+ return;+ }+ let q = args.join(" ");+ let terms = split_terms(&q);+ if terms.is_empty() {+ eprintln!("usage: rs [-d X] <term>... | rs [-d X] --serve");+ std::process::exit(2);+ }++ // Ask every drive's service; a missing pipe only means that drive has none.+ let mut answered = false;+ for d in explicit.map_or_else(drive_letters, |d| vec![d]) {+ match ask(d, &q) {+ Some(Ok(out)) => {+ answered = true;+ print!("{out}");+ }+ Some(Err(e)) => {+ eprintln!("cannot reach the {d}: service: {e}");+ std::process::exit(1);+ }+ None => {}+ }+ }+ if answered {+ return;+ }+ // No service anywhere: scan the volume(s) ourselves (needs an admin shell).+ for d in explicit.map_or_else(fixed_ntfs_drives, |d| vec![d]) {+ let t = Instant::now();+ let idx = open_volume(d).and_then(scan).unwrap_or_else(|e| {+ eprintln!("{e}");+ std::process::exit(1);+ });+ eprintln!("no server running; indexed {} entries on {d}: in {:?}", idx.len(), t.elapsed());+ print!("{}", render(&idx, d, &terms));+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn sample() -> Index {+ let mut idx = Index::new();+ idx.insert(5, 0, "Users"); // parent 0 is not in the index = volume root+ idx.insert(6, 5, "Docs");+ idx.insert(7, 6, "Report Final.TXT");+ idx.insert(8, 6, "report");+ idx.insert(10, 0, "WinSxS");+ idx.insert(11, 10, "hosts");+ idx.insert(12, 6, "hosts"); // longer path than the WinSxS one, but must still win+ idx+ }++ #[test]+ fn frn_sequence_bits_are_ignored_and_delete_rename_work() {+ let mut idx = sample();+ idx.insert((3 << 48) | 13, (9 << 48) | 6, "new.txt"); // real FRNs carry a sequence number up top+ assert_eq!(full_path(&idx, 'C', 13), "C:\\Users\\Docs\\new.txt");+ idx.insert(13, 6, "renamed.txt");+ idx.remove((3 << 48) | 7);+ assert_eq!(full_path(&idx, 'C', 13), "C:\\Users\\Docs\\renamed.txt");+ assert_eq!(query(&idx, 'C', &["report".into()]).1, 1); // "Report Final.TXT" is gone+ assert_eq!(idx.len(), 7);+ }++ fn snapshot(idx: &Index) -> Vec<u8> {+ let mut b = Vec::new();+ idx.write_to(&mut b, 42, 1000).unwrap();+ b+ }++ #[test]+ fn snapshot_roundtrips_including_garbage_and_deletes() {+ let mut idx = sample();+ idx.insert(13, 6, "old name");+ idx.insert(13, 6, "new name"); // leaves garbage in the arena+ idx.remove(7);+ let (back, jid, usn) = Index::read_from(&snapshot(&idx)).unwrap();+ assert_eq!((jid, usn, back.len(), back.garbage), (42, 1000, idx.len(), idx.garbage));+ assert_eq!(full_path(&back, 'C', 13), "C:\\Users\\Docs\\new name");+ assert_eq!(query(&back, 'C', &["report".into()]).1, 1); // record 7 stays deleted+ }++ #[test]+ fn corrupt_snapshots_are_rejected_not_trusted() {+ let good = snapshot(&sample());+ assert!(Index::read_from(&good).is_some());+ assert!(Index::read_from(&good[..good.len() - 1]).is_none(), "truncated");+ assert!(Index::read_from(&[good.clone(), vec![0]].concat()).is_none(), "trailing bytes");+ let mut bad_magic = good.clone();+ bad_magic[0] ^= 0xff;+ assert!(Index::read_from(&bad_magic).is_none(), "magic");+ let mut bad_utf8 = good.clone();+ *bad_utf8.last_mut().unwrap() = 0xff; // last byte of the arena: not valid UTF-8 (read back unchecked otherwise)+ assert!(Index::read_from(&bad_utf8).is_none(), "utf-8");+ let mut bad_count = good.clone();+ bad_count[8 + 4 * 8] ^= 1; // the `live` counter no longer matches the slots+ assert!(Index::read_from(&bad_count).is_none(), "live count");+ assert!(Index::read_from(&[]).is_none());+ }++ #[test]+ fn start_menu_shortcuts_come_first() {+ let mut idx = sample();+ idx.insert(30, 0, "ProgramData");+ idx.insert(31, 30, "Start Menu");+ idx.insert(32, 31, "Programs");+ idx.insert(33, 32, "My Editor.lnk");+ idx.insert(34, 6, "editor"); // exact name match, but not an app shortcut+ idx.insert(35, 6, "My Editor.lnk"); // .lnk outside the Start Menu (e.g. Recent): second tier, after the apps+ let (p, _) = query(&idx, 'C', &["editor".into()]);+ assert_eq!(p[0], "C:\\ProgramData\\Start Menu\\Programs\\My Editor.lnk");+ assert!(p[1].ends_with("My Editor.lnk") && !p[1].contains("Start Menu"), "other shortcuts come right after the apps");+ assert_eq!(p[2], "C:\\Users\\Docs\\editor");+ }++ #[test]+ fn contains_ci_handles_ascii_and_unicode() {+ assert!(contains_ci("Report Final.TXT", "final"));+ assert!(!contains_ci("abc", "abcd"));+ assert!(contains_ci("ÄPFEL.txt", "äpfel")); // non-ASCII falls back to to_lowercase+ assert!(contains_ci("anything", ""));+ }++ // cargo test --release -- --ignored --nocapture+ #[test]+ #[ignore]+ fn bench_query_over_1_5m_names() {+ let mut idx = Index::new();+ for i in 1..1_500_000u64 {+ idx.insert(i, 5, &format!("Some_File_Name_{i}.dat"));+ }+ let t = std::time::Instant::now();+ let (_, total) = query(&idx, 'C', &["name_77".into()]);+ eprintln!("query over {} names: {:?}, {total} hits", idx.len(), t.elapsed());+ }++ #[test]+ #[ignore]+ fn bench_snapshot_of_1_5m_names() {+ let mut idx = Index::new();+ for i in 1..1_500_000u64 {+ idx.insert(i, 5, &format!("Some_File_Name_{i}.dat"));+ }+ let (t, b) = (Instant::now(), snapshot(&idx));+ let w = t.elapsed();+ let t = Instant::now();+ assert!(Index::read_from(&b).is_some());+ eprintln!("snapshot {} MB: write {w:?}, load+validate {:?}", b.len() >> 20, t.elapsed());+ }++ #[test]+ fn compaction_keeps_live_names() {+ let mut idx = sample();+ let big = "x".repeat(1000);+ for _ in 0..9000 {+ idx.insert(20, 6, &big); // each rewrite orphans 1000 bytes -> triggers compact() past 8 MB+ }+ assert!(idx.arena.len() < 4 << 20, "arena was not compacted: {}", idx.arena.len());+ assert_eq!(idx.get(20).unwrap().1, big);+ assert_eq!(full_path(&idx, 'C', 12), "C:\\Users\\Docs\\hosts");+ }++ #[test]+ fn os_component_stores_rank_last_within_a_tie() {+ let (p, total) = query(&sample(), 'C', &["hosts".into()]);+ assert_eq!(total, 2);+ assert_eq!(p, vec!["C:\\Users\\Docs\\hosts", "C:\\WinSxS\\hosts"]);+ }++ #[test]+ fn exe_files_rank_first() {+ let mut idx = sample();+ idx.insert(20, 6, "tool.txt");+ idx.insert(21, 0, "tooling.exe"); // longer name and path than tool.txt, must still be first+ let (p, _) = query(&idx, 'C', &["tool".into()]);+ assert_eq!(p[0], "C:\\tooling.exe");+ }++ #[test]+ fn resolves_paths() {+ assert_eq!(full_path(&sample(), 'C', 7), "C:\\Users\\Docs\\Report Final.TXT");+ }++ #[test]+ fn ranks_exact_then_prefix_and_requires_all_terms() {+ let idx = sample();+ let (p, total) = query(&idx, 'C', &["report".into()]);+ assert_eq!(total, 2);+ assert_eq!(p[0], "C:\\Users\\Docs\\report");+ assert_eq!(p[1], "C:\\Users\\Docs\\Report Final.TXT");+ assert_eq!(query(&idx, 'C', &["report".into(), "txt".into()]).1, 1);+ assert_eq!(query(&idx, 'C', &["nope".into()]).1, 0);+ }+}diff --git a/plugins/rust-search/src/regsweep.rs b/plugins/rust-search/src/regsweep.rsnew file mode 100644index 0000000..adb5301--- /dev/null+++ b/plugins/rust-search/src/regsweep.rs@@ -0,0 +1,310 @@+// Registry traces of a deleted file/folder, in three steps so nothing is removed blind:+// scan() finds every value (name or string data) under HKCU\Software and HKLM\SOFTWARE that points at+// the path, plus whole Uninstall / App Paths entries of a program that lived inside it;+// backup() writes all of them to a .reg file (double-click restores);+// delete() removes them.+// Not covered: services, 8.3 short names, %ENV% forms, ROT13 UserAssist, binary blobs (ShellBags).+use std::{fs, io, path::Path};+use windows_sys::Win32::{Foundation::*, Storage::FileSystem::DELETE, System::Registry::*};++#[derive(Clone, Copy, PartialEq, Debug)]+pub enum Root {+ Hkcu,+ Hklm,+}+impl Root {+ fn h(self) -> HKEY {+ if self == Root::Hkcu { HKEY_CURRENT_USER } else { HKEY_LOCAL_MACHINE }+ }+ fn name(self) -> &'static str {+ if self == Root::Hkcu { "HKEY_CURRENT_USER" } else { "HKEY_LOCAL_MACHINE" }+ }+}++/// One thing to remove: a value (`value: Some(name)`, "" = the default value) or a whole key (`None`).+#[derive(Clone, Debug)]+pub struct Hit {+ pub root: Root,+ pub key: String, // relative to root, e.g. Software\Foo+ pub value: Option<String>,+}+impl Hit {+ /// One line for the UI: HKCU\Software\Foo · Name (or the key alone for a whole entry).+ pub fn describe(&self) -> String {+ let r = if self.root == Root::Hkcu { "HKCU" } else { "HKLM" };+ match &self.value {+ Some(v) => format!("{r}\\{} \u{00B7} {}", self.key, if v.is_empty() { "(Default)" } else { v }),+ None => format!("{r}\\{} (whole entry)", self.key),+ }+ }+}++#[derive(Default)]+pub struct Report {+ pub removed: usize,+ pub denied: usize, // could not be deleted (HKLM without admin rights)+}++fn wide(s: &str) -> Vec<u16> {+ s.encode_utf16().chain([0]).collect()+}++fn boundary_after(c: Option<char>) -> bool {+ c.is_none_or(|c| matches!(c, '\\' | '"' | '\'' | ',' | ';' | ' ' | '\n' | '/'))+}++/// True if `hay` contains `needle` (lowercase) as a whole path: not glued to a longer name on either side,+/// so C:\Foo does not match C:\Foobar\x.+fn refs(hay: &str, needle: &str) -> bool {+ let h = hay.to_lowercase();+ let mut from = 0;+ while let Some(i) = h[from..].find(needle) {+ let (s, e) = (from + i, from + i + needle.len());+ let before_ok = h[..s].chars().next_back().is_none_or(|c| !c.is_alphanumeric());+ if before_ok && boundary_after(h[e..].chars().next()) {+ return true;+ }+ from = e;+ }+ false+}++/// True if the path `hay` starts with (quotes stripped) lies at or inside `needle`.+fn under(hay: &str, needle: &str) -> bool {+ let h = hay.trim_start_matches([' ', '"']).to_lowercase();+ h.starts_with(needle) && boundary_after(h[needle.len()..].chars().next())+}++struct Val {+ name: String,+ ty: u32,+ data: Vec<u8>,+}+impl Val {+ fn text(&self) -> Option<String> {+ matches!(self.ty, REG_SZ | REG_EXPAND_SZ | REG_MULTI_SZ).then(|| {+ let u: Vec<u16> = self.data.chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect();+ String::from_utf16_lossy(&u).trim_end_matches('\0').replace('\0', "\n")+ })+ }+}++unsafe fn open(parent: HKEY, sub: &str, write: bool) -> Option<HKEY> {+ let mut k: HKEY = std::ptr::null_mut();+ let acc = if write { KEY_READ | KEY_SET_VALUE | DELETE } else { KEY_READ };+ (RegOpenKeyExW(parent, wide(sub).as_ptr(), 0, acc, &mut k) == ERROR_SUCCESS).then_some(k)+}++unsafe fn read_values(key: HKEY) -> Vec<Val> {+ let (mut out, mut i, mut data) = (Vec::new(), 0u32, vec![0u8; 1024]);+ let mut name = vec![0u16; 16384];+ loop {+ let (mut nlen, mut dlen, mut ty) = (name.len() as u32, data.len() as u32, 0u32);+ match RegEnumValueW(key, i, name.as_mut_ptr(), &mut nlen, std::ptr::null(), &mut ty, data.as_mut_ptr(), &mut dlen) {+ ERROR_SUCCESS => {+ out.push(Val { name: String::from_utf16_lossy(&name[..nlen as usize]), ty, data: data[..dlen as usize].to_vec() });+ i += 1;+ }+ ERROR_MORE_DATA => data.resize((dlen as usize).max(data.len() * 2), 0), // retry the same index+ _ => break, // ERROR_NO_MORE_ITEMS or unreadable+ }+ }+ out+}++unsafe fn subkeys(key: HKEY) -> Vec<String> {+ let (mut out, mut i) = (Vec::new(), 0u32);+ let mut buf = vec![0u16; 256];+ loop {+ let mut len = buf.len() as u32;+ if RegEnumKeyExW(key, i, buf.as_mut_ptr(), &mut len, std::ptr::null(), std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut()) != ERROR_SUCCESS {+ break;+ }+ out.push(String::from_utf16_lossy(&buf[..len as usize]));+ i += 1;+ }+ out+}++/// An Uninstall / App Paths entry belongs to the deleted thing only if the program's own location is inside it.+/// (Deleting just C:\App\icon.ico must not wipe App's uninstall entry: then only its DisplayIcon value goes.)+const OWNER_VALUES: [&str; 5] = ["installlocation", "uninstallstring", "quietuninstallstring", "", "path"];+fn owns(vals: &[Val], needle: &str) -> bool {+ vals.iter().any(|v| OWNER_VALUES.contains(&v.name.to_lowercase().as_str()) && v.text().is_some_and(|t| !t.is_empty() && under(&t, needle)))+}++unsafe fn walk(root: Root, key: HKEY, path: &str, needle: &str, depth: u32, hits: &mut Vec<Hit>) {+ for v in read_values(key) {+ if refs(&v.name, needle) || v.text().is_some_and(|t| refs(&t, needle)) {+ hits.push(Hit { root, key: path.into(), value: Some(v.name) });+ }+ }+ let leaf = path.rsplit('\\').next().unwrap_or("").to_lowercase();+ let container = matches!(leaf.as_str(), "uninstall" | "app paths");+ for s in subkeys(key) {+ let Some(child) = open(key, &s, false) else { continue };+ let child_path = format!("{path}\\{s}");+ if container && owns(&read_values(child), needle) {+ hits.push(Hit { root, key: child_path, value: None }); // a program that lived there: the whole entry+ } else if depth < 40 {+ walk(root, child, &child_path, needle, depth + 1, hits);+ }+ RegCloseKey(child);+ }+}++/// Everything in the registry that points at `path`. Reads only.+pub fn scan(path: &str) -> Vec<Hit> {+ let needle = path.trim_end_matches('\\').to_lowercase();+ let mut hits = Vec::new();+ for (root, sub) in [(Root::Hkcu, "Software"), (Root::Hklm, "SOFTWARE")] {+ unsafe {+ if let Some(k) = open(root.h(), sub, false) {+ walk(root, k, sub, &needle, 0, &mut hits);+ RegCloseKey(k);+ }+ }+ }+ hits+}++fn reg_line(v: &Val) -> String {+ let name = if v.name.is_empty() { "@".into() } else { format!("\"{}\"", v.name.replace('\\', "\\\\").replace('"', "\\\"")) };+ let hex = || v.data.iter().map(|b| format!("{b:02x}")).collect::<Vec<_>>().join(",");+ let data = match v.ty {+ REG_DWORD if v.data.len() == 4 => format!("dword:{:08x}", u32::from_le_bytes(v.data[..4].try_into().unwrap())),+ REG_BINARY => format!("hex:{}", hex()),+ t => format!("hex({t:x}):{}", hex()), // exact bytes for every other type, strings included+ };+ // the decoded text as a comment, so a human can read the backup+ let note = v.text().map(|t| format!("; {}\r\n", t.replace('\n', " | "))).unwrap_or_default();+ format!("{note}{name}={data}\r\n")+}++unsafe fn dump_tree(root: Root, key: HKEY, path: &str, out: &mut String, depth: u32) {+ out.push_str(&format!("\r\n[{}\\{path}]\r\n", root.name()));+ for v in read_values(key) {+ out.push_str(®_line(&v));+ }+ for s in subkeys(key) {+ if let Some(c) = open(key, &s, false) {+ if depth < 40 {+ dump_tree(root, c, &format!("{path}\\{s}"), out, depth + 1);+ }+ RegCloseKey(c);+ }+ }+}++/// Writes every hit, exactly as it is now, to a .reg file (UTF-16, what regedit writes and imports).+pub fn backup(hits: &[Hit], file: &Path) -> io::Result<()> {+ let mut out = String::from("Windows Registry Editor Version 5.00\r\n");+ let mut last_header = String::new();+ for h in hits {+ unsafe {+ let Some(k) = open(h.root.h(), &h.key, false) else { continue };+ match &h.value {+ None => {+ dump_tree(h.root, k, &h.key, &mut out, 0);+ last_header.clear();+ }+ Some(name) => {+ if let Some(v) = read_values(k).into_iter().find(|v| v.name == *name) {+ let header = format!("[{}\\{}]", h.root.name(), h.key);+ if header != last_header {+ out.push_str(&format!("\r\n{header}\r\n"));+ last_header = header;+ }+ out.push_str(®_line(&v));+ }+ }+ }+ RegCloseKey(k);+ }+ }+ if let Some(d) = file.parent() {+ fs::create_dir_all(d)?;+ }+ let mut b = vec![0xFF, 0xFE];+ b.extend(out.encode_utf16().flat_map(u16::to_le_bytes));+ fs::write(file, b)+}++/// Removes the hits. Values of one key that is also removed whole are covered by the key.+pub fn delete(hits: &[Hit]) -> Report {+ let mut r = Report::default();+ for h in hits {+ let ok = unsafe {+ match &h.value {+ None => RegDeleteTreeW(h.root.h(), wide(&h.key).as_ptr()) == ERROR_SUCCESS,+ Some(v) => match open(h.root.h(), &h.key, true) {+ Some(k) => {+ let ok = RegDeleteValueW(k, wide(v).as_ptr()) == ERROR_SUCCESS;+ RegCloseKey(k);+ ok+ }+ None => false,+ },+ }+ };+ if ok { r.removed += 1 } else { r.denied += 1 }+ }+ r+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn scan_backup_delete_restore_in_the_real_registry() {+ let p = "C:\\rs-sweep-test-9f3a\\App";+ let reg = |args: &[&str]| std::process::Command::new("reg").args(args).output().unwrap().status.success();+ let base = "HKCU\\Software\\rs-sweep-test-9f3a";+ let _ = reg(&["delete", base, "/f"]);+ assert!(reg(&["add", &format!("{base}\\Run"), "/v", "x", "/d", &format!("\"{p}\\a.exe\" /s"), "/f"]));+ assert!(reg(&["add", &format!("{base}\\Run"), "/v", "keep", "/d", "C:\\rs-sweep-test-9f3aXYZ\\a.exe", "/f"]));+ assert!(reg(&["add", &format!("{base}\\Run"), "/v", "n", "/t", "REG_DWORD", "/d", "7", "/f"]));+ assert!(reg(&["add", &format!("{base}\\Uninstall\\Prod"), "/v", "InstallLocation", "/d", p, "/f"]));+ assert!(reg(&["add", &format!("{base}\\Uninstall\\Prod\\Sub"), "/v", "Size", "/t", "REG_DWORD", "/d", "5", "/f"]));+ // a program elsewhere whose icon was the deleted thing: only that value may go, not the entry+ assert!(reg(&["add", &format!("{base}\\Uninstall\\Other"), "/v", "DisplayIcon", "/d", &format!("{p}\\icon.ico"), "/f"]));+ assert!(reg(&["add", &format!("{base}\\Uninstall\\Other"), "/v", "InstallLocation", "/d", "C:\\Elsewhere", "/f"]));++ let hits: Vec<Hit> = scan(p).into_iter().filter(|h| h.key.contains("rs-sweep-test-9f3a")).collect();+ assert_eq!(hits.len(), 3, "{hits:?}");+ assert!(hits.iter().any(|h| h.key.ends_with("Uninstall\\Prod") && h.value.is_none()));+ assert!(hits.iter().any(|h| h.key.ends_with("Uninstall\\Other") && h.value.as_deref() == Some("DisplayIcon")));++ let bak = std::env::temp_dir().join("rs-sweep-test-9f3a.reg");+ backup(&hits, &bak).unwrap();+ let r = delete(&hits);+ assert_eq!((r.removed, r.denied), (3, 0));+ assert!(!reg(&["query", &format!("{base}\\Run"), "/v", "x"]), "value must be gone");+ assert!(reg(&["query", &format!("{base}\\Run"), "/v", "keep"]), "look-alike path must stay");+ assert!(!reg(&["query", &format!("{base}\\Uninstall\\Prod")]), "uninstall key must be gone");+ assert!(reg(&["query", &format!("{base}\\Uninstall\\Other"), "/v", "InstallLocation"]), "other program's entry must stay");++ assert!(reg(&["import", bak.to_str().unwrap()]), "backup must import");+ assert!(reg(&["query", &format!("{base}\\Run"), "/v", "x"]), "value restored");+ assert!(reg(&["query", &format!("{base}\\Uninstall\\Prod\\Sub"), "/v", "Size"]), "whole tree restored");+ assert!(reg(&["query", &format!("{base}\\Uninstall\\Other"), "/v", "DisplayIcon"]), "icon value restored");+ assert_eq!(scan(p).into_iter().filter(|h| h.key.contains("rs-sweep-test-9f3a")).count(), 3, "restored exactly");+ let _ = fs::remove_file(bak);+ assert!(reg(&["delete", base, "/f"]));+ }++ #[test]+ fn matches_whole_paths_only() {+ let n = "c:\\tools\\foo";+ assert!(refs("C:\\Tools\\Foo", n));+ assert!(refs("\"C:\\Tools\\Foo\\bar.exe\" /x", n));+ assert!(refs("C:\\Tools\\Foo,0", n));+ assert!(!refs("C:\\Tools\\Foobar\\x.exe", n));+ assert!(!refs("xc:\\tools\\foo", n));+ assert!(under("\"C:\\Tools\\Foo\\u.exe\" /S", n));+ assert!(under("C:\\Tools\\Foo", n));+ assert!(!under("C:\\Tools\\Foobar", n));+ assert!(!under("C:\\Tools", n));+ }+}diff --git a/plugins/topbar/.cargo/config.toml b/plugins/topbar/.cargo/config.tomlnew file mode 100644index 0000000..fac678a--- /dev/null+++ b/plugins/topbar/.cargo/config.toml@@ -0,0 +1,2 @@+[build]+rustflags = ["-C", "target-feature=+crt-static"]diff --git a/plugins/topbar/.gitignore b/plugins/topbar/.gitignorenew file mode 100644index 0000000..ea8c4bf--- /dev/null+++ b/plugins/topbar/.gitignore@@ -0,0 +1 @@+/targetdiff --git a/plugins/topbar/Cargo.lock b/plugins/topbar/Cargo.locknew file mode 100644index 0000000..1963b08--- /dev/null+++ b/plugins/topbar/Cargo.lock@@ -0,0 +1,165 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "proc-macro2"+version = "1.0.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "topbar"+version = "0.1.0"+dependencies = [+ "windows",+ "windows-sys",+]++[[package]]+name = "unicode-ident"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"++[[package]]+name = "windows"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"+dependencies = [+ "windows-collections",+ "windows-core",+ "windows-future",+ "windows-numerics",+]++[[package]]+name = "windows-collections"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"+dependencies = [+ "windows-core",+]++[[package]]+name = "windows-core"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-link",+ "windows-result",+ "windows-strings",+]++[[package]]+name = "windows-future"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"+dependencies = [+ "windows-core",+ "windows-link",+ "windows-threading",+]++[[package]]+name = "windows-implement"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "windows-interface"+version = "0.59.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-numerics"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"+dependencies = [+ "windows-core",+ "windows-link",+]++[[package]]+name = "windows-result"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-strings"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-threading"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"+dependencies = [+ "windows-link",+]diff --git a/plugins/topbar/Cargo.toml b/plugins/topbar/Cargo.tomlnew file mode 100644index 0000000..70c156a--- /dev/null+++ b/plugins/topbar/Cargo.toml@@ -0,0 +1,16 @@+[package]+name = "topbar"+version = "0.1.0"+edition = "2024"++[dependencies]+windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Globalization", "Win32_Graphics_Dwm", "Win32_Graphics_Gdi", "Win32_Graphics_GdiPlus", "Win32_NetworkManagement_WiFi", "Win32_NetworkManagement_Ndis", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_DataExchange", "Win32_System_Diagnostics_ToolHelp", "Win32_System_LibraryLoader", "Win32_System_Power", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] }+# COM only where raw vtables would be long: master volume and .lnk targets+windows = { version = "0.62", features = ["Win32_Media_Audio", "Win32_Media_Audio_Endpoints", "Win32_System_Com", "Win32_System_Com_StructuredStorage", "Win32_System_Variant", "Win32_Graphics_Gdi", "Win32_UI_Shell", "Win32_UI_Shell_Common", "Win32_Storage_FileSystem"] }++[profile.release]+opt-level = "s"+lto = true+codegen-units = 1+panic = "abort"+strip = truediff --git a/plugins/topbar/src/fly.rs b/plugins/topbar/src/fly.rsnew file mode 100644index 0000000..c50215e--- /dev/null+++ b/plugins/topbar/src/fly.rs@@ -0,0 +1,1418 @@+// Own flyouts instead of the stock Windows ones: Start (search + all apps + power), Wi-Fi, volume, battery+// (+ brightness), calendar. One popup window; what it shows depends on `Kind`.+use super::*;+use std::sync::Mutex;+use std::{+ collections::HashMap,+ sync::atomic::{AtomicI32, Ordering::Relaxed},+};++#[derive(Clone, Copy, PartialEq)]+pub enum Kind {+ Quick,+ Wifi,+ Cal,+ Start,+ Menu, // right-click menu of the bar+}++#[derive(Clone, Copy, PartialEq)]+enum Act {+ VolSlide,+ BrightSlide,+ Mute,+ WifiSwitch,+ Tile(u8),+ WifiMore,+ Net(usize),+ Settings(&'static str),+ Menu(u8),+ CalPrev,+ CalNext,+ CalToday,+ App(usize), // index into the filtered list+ Power(u8), // 0 lock, 1 sleep, 2 restart, 3 shut down+}++struct Net {+ ssid: String,+ q: i32,+ secure: bool,+ profile: Option<String>,+ connected: bool,+ auth: i32,+}++struct Conn {+ ssid: String,+ auth: i32,+ q: i32,+ rx: u32, // Mbps+ tx: u32,+ phy: &'static str,+}++fn auth_name(a: i32) -> &'static str {+ match a {+ 1 => "Open",+ 2 => "WEP",+ 3 => "WPA",+ 4 => "WPA‑Personal",+ 6 => "WPA2",+ 7 => "WPA2‑Personal",+ 8 => "WPA3",+ 9 => "WPA3‑Personal",+ _ => "Secured",+ }+}++fn phy_name(t: i32) -> &'static str {+ match t {+ 7 => "Wi‑Fi 4",+ 8 => "Wi‑Fi 5",+ 10 => "Wi‑Fi 6",+ 11 => "Wi‑Fi 7",+ 4..=6 => "802.11a/b/g",+ _ => "Wi‑Fi",+ }+}++static APPS: Mutex<Vec<(String, Vec<u16>)>> = Mutex::new(Vec::new()); // Start menu shortcuts: (name, .lnk path)+static BRIGHT: AtomicI32 = AtomicI32::new(-1); // -1 = no controllable display (desktop PC)+const ROWS: usize = 11;++thread_local! {+ static FLY: Cell<Option<Kind>> = const { Cell::new(None) };+ static FH: Cell<HWND> = const { Cell::new(null_mut()) };+ static CAL: Cell<(i32, i32)> = const { Cell::new((2026, 1)) };+ static NETS: RefCell<Vec<Net>> = const { RefCell::new(Vec::new()) };+ static CONN: RefCell<Option<Conn>> = const { RefCell::new(None) };+ static PASS: RefCell<Option<(usize, String)>> = const { RefCell::new(None) };+ static NOTE: RefCell<String> = const { RefCell::new(String::new()) };+ static QUERY: RefCell<String> = const { RefCell::new(String::new()) };+ static SCROLL: Cell<usize> = const { Cell::new(0) };+ static ICONS: RefCell<HashMap<Vec<u16>, HICON>> = RefCell::new(HashMap::new()); // by path: the app list is reloaded and reordered+ static SEL: Cell<usize> = const { Cell::new(0) }; // Start: the row Enter opens (arrow keys move it)+ static OVER: Cell<Option<Act>> = const { Cell::new(None) };+ static DRAG: Cell<u8> = const { Cell::new(0) }; // 0 none, 1 volume slider, 2 brightness slider+ static MENU_X: Cell<i32> = const { Cell::new(0) };+ static CONFIRM: Cell<i32> = const { Cell::new(-1) };+ static LAST: Cell<(Option<Kind>, u64)> = const { Cell::new((None, 0)) }; // which flyout closed when+ static FIN: Cell<(i32, i32)> = const { Cell::new((0, 0)) }; // where the open flyout rests+ static T0: Cell<u64> = const { Cell::new(0) }; // when it started opening+ static JUST: RefCell<(String, u64)> = const { RefCell::new((String::new(), 0)) }; // the app pinned last and when: its row pulses+ static GHOST: Cell<(HWND, u64, (i32, i32))> = const { Cell::new((null_mut(), 0, (0, 0))) }; // the closing flyout: window, start, position+}++const MONTHS: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];++// ---------- data ----------++/// Background: collects the Start menu shortcuts once.+pub fn load_apps() {+ fn walk(dir: &std::path::Path, depth: u8, out: &mut Vec<(String, Vec<u16>)>) {+ for e in std::fs::read_dir(dir).into_iter().flatten().flatten() {+ let p = e.path();+ if p.is_dir() && depth < 4 {+ walk(&p, depth + 1, out);+ } else if p.extension().is_some_and(|x| x.eq_ignore_ascii_case("lnk")) {+ let name = p.file_stem().unwrap_or_default().to_string_lossy().to_string();+ if !name.to_lowercase().contains("uninstall") {+ out.push((name, wide(&p.to_string_lossy())));+ }+ }+ }+ }+ let mut v = Vec::new();+ for (var, sub) in [("ProgramData", r"Microsoft\Windows\Start Menu\Programs"), ("APPDATA", r"Microsoft\Windows\Start Menu\Programs")] {+ if let Some(b) = std::env::var_os(var) {+ walk(&PathBuf::from(b).join(sub), 0, &mut v);+ }+ }+ // Store apps (Settings, Calculator, Terminal, Photos...) have no .lnk: the shell's Apps folder lists them+ let have: std::collections::HashSet<String> = v.iter().map(|a| a.0.to_lowercase()).collect();+ for (name, id) in apps_folder() {+ let ok = id.contains('!') || id.to_lowercase().ends_with(".exe") || id.starts_with("Microsoft.Windows."); // apps, not docs / web links+ if ok && !have.contains(&name.to_lowercase()) && !name.to_lowercase().contains("uninstall") {+ v.push((name, wide(&format!(r"shell:AppsFolder\{id}"))));+ }+ }+ v.sort_by_key(|a| a.0.to_lowercase());+ v.dedup_by(|a, b| a.0.eq_ignore_ascii_case(&b.0));+ *APPS.lock().unwrap() = v;+}++/// (display name, app id) of everything in the shell's Apps folder (what the Windows Start menu lists).+fn apps_folder() -> Vec<(String, String)> {+ use windows::Win32::{+ System::Com::CoTaskMemFree,+ UI::Shell::{BHID_EnumItems, FOLDERID_AppsFolder, IEnumShellItems, IShellItem, KF_FLAG_DEFAULT, SHGetKnownFolderItem, SIGDN, SIGDN_NORMALDISPLAY, SIGDN_PARENTRELATIVEPARSING},+ };+ let mut out = vec![];+ unsafe {+ let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED); // this runs on its own thread+ let Ok(folder) = SHGetKnownFolderItem::<IShellItem>(&FOLDERID_AppsFolder, KF_FLAG_DEFAULT, None) else { return out };+ let Ok(en) = folder.BindToHandler::<_, IEnumShellItems>(None, &BHID_EnumItems) else { return out };+ loop {+ let mut items = [None];+ let mut got = 0u32;+ if en.Next(&mut items, Some(&mut got)).is_err() || got == 0 {+ break;+ }+ let Some(it) = items[0].take() else { break };+ let name = |k: SIGDN| {+ it.GetDisplayName(k).ok().map(|p| {+ let s = p.to_string().unwrap_or_default();+ CoTaskMemFree(Some(p.0 as *const _));+ s+ })+ };+ if let (Some(n), Some(id)) = (name(SIGDN_NORMALDISPLAY), name(SIGDN_PARENTRELATIVEPARSING)) {+ out.push((n, id));+ }+ }+ }+ out+}++const EN_KEYS: &str = "qwertyuiop[]asdfghjkl;'zxcvbnm,.`";+const RU_KEYS: &str = "йцукенгшщзхъфывапролджэячсмитьбюё";++/// The same keys typed in the other layout: "сркщьу" -> "chrome", "ntktuhfv" -> "телеграм".+fn flip_layout(q: &str) -> String {+ let (en, ru): (Vec<char>, Vec<char>) = (EN_KEYS.chars().collect(), RU_KEYS.chars().collect());+ q.chars().map(|c| en.iter().position(|&x| x == c).map(|i| ru[i]).or_else(|| ru.iter().position(|&x| x == c).map(|i| en[i])).unwrap_or(c)).collect()+}++/// How well an app name matches the query (both lower-case): 0 the name starts with it, 1 a word does, 2 the word+/// initials do ("vsc" = Visual Studio Code), 3 it is somewhere inside; None = no match.+fn score(name: &str, q: &str) -> Option<u8> {+ if q.is_empty() {+ return None;+ }+ let words: Vec<&str> = name.split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()).collect();+ let initials: String = words.iter().filter_map(|w| w.chars().next()).collect();+ if name.starts_with(q) {+ Some(0)+ } else if words.iter().any(|w| w.starts_with(q)) {+ Some(1)+ } else if q.chars().count() >= 2 && initials.starts_with(q) {+ Some(2)+ } else if name.contains(q) {+ Some(3)+ } else {+ None+ }+}++// ---------- apps pinned to the Start panel (empty at first; added from right-click menus) ----------++static PINNED: Mutex<Vec<String>> = Mutex::new(Vec::new()); // paths of .lnk / .exe files, in the order they were added++fn pin_file() -> PathBuf {+ appdata_file("topbar-start.txt")+}++fn pinned_load() {+ *PINNED.lock().unwrap() = std::fs::read_to_string(pin_file()).map(|s| s.lines().filter(|l| !l.is_empty()).map(str::to_string).collect()).unwrap_or_default();+}++fn wstr(w: &[u16]) -> String {+ String::from_utf16_lossy(&w[..w.iter().position(|&c| c == 0).unwrap_or(w.len())])+}++pub fn start_pinned(path: &str) -> bool {+ PINNED.lock().unwrap().iter().any(|p| p.eq_ignore_ascii_case(path))+}++/// Files dropped on the open Start panel are added to it; the panel stays open and the new row pulses.+unsafe fn on_files(hw: HWND, hd: HDROP) {+ let n = DragQueryFileW(hd, u32::MAX, null_mut(), 0);+ let mut added = vec![];+ for i in 0..n {+ let len = DragQueryFileW(hd, i, null_mut(), 0) as usize;+ let mut b = vec![0u16; len + 1];+ DragQueryFileW(hd, i, b.as_mut_ptr(), b.len() as u32);+ let path = String::from_utf16_lossy(&b[..len]);+ if start_pin(&path) {+ added.push(std::path::Path::new(&path).file_stem().unwrap_or_default().to_string_lossy().to_string());+ }+ }+ DragFinish(hd);+ note(&match added.len() {+ 0 => "Already in Start".to_string(),+ 1 => format!("Added to Start: {}", added[0]),+ n => format!("Added {n} items to Start"),+ });+ KillTimer(hw, 6);+ InvalidateRect(hw, null(), 0);+ force_fg(hw); // active again, so a later click elsewhere closes it as usual+}++/// Adds the app to the Start panel unless it is already there (a drop on the Start button). true = it was added.+pub fn start_pin(path: &str) -> bool {+ if start_pinned(path) {+ return false;+ }+ start_toggle(path);+ JUST.set((path.to_string(), unsafe { now_ms() }));+ true+}++pub fn is_open(k: Kind) -> bool {+ FLY.get() == Some(k)+}++pub fn any_open() -> bool {+ FLY.get().is_some()+}++/// Short status line shown at the bottom of the open panel (Start: "Added to Start: ...").+pub fn note(s: &str) {+ NOTE.set(s.to_string());+}++/// Adds the app to the Start panel, or removes it when it is already there.+pub fn start_toggle(path: &str) {+ let mut p = PINNED.lock().unwrap();+ match p.iter().position(|x| x.eq_ignore_ascii_case(path)) {+ Some(i) => drop(p.remove(i)),+ None => p.push(path.to_string()),+ }+ let _ = std::fs::write(pin_file(), p.join("\n"));+}++fn filtered() -> Vec<usize> {+ let q = QUERY.with_borrow(|q| q.to_lowercase());+ let mut apps = APPS.lock().unwrap();+ if q.is_empty() {+ // nothing typed: only what the user pinned (an app that is not a Start menu shortcut joins the list on demand)+ return PINNED+ .lock()+ .unwrap()+ .iter()+ .map(|p| {+ let w = wide(p);+ apps.iter().position(|a| a.1 == w).unwrap_or_else(|| {+ let stem = std::path::Path::new(p).file_stem().unwrap_or_default().to_string_lossy().to_string();+ let name: String = stem.chars().take(1).flat_map(char::to_uppercase).chain(stem.chars().skip(1)).collect();+ apps.push((name, w));+ apps.len() - 1+ })+ })+ .collect();+ }+ // typed in the wrong layout: those matches come after the direct ones+ let fq = flip_layout(&q);+ let mut v: Vec<(u8, u32, usize)> = apps+ .iter()+ .enumerate()+ .filter_map(|(i, a)| {+ let n = a.0.to_lowercase();+ let s = score(&n, &q).or_else(|| score(&n, &fq).map(|s| s + 4))?;+ Some((s, u32::MAX - uses(&n), i))+ })+ .collect();+ v.sort_unstable(); // best match, then most launched, then alphabetical (the list is sorted by name)+ v.into_iter().map(|x| x.2).collect()+}++fn read_brightness() {+ std::thread::spawn(|| {+ let o = Command::new("powershell").args(["-NoProfile", "-Command", "(Get-CimInstance -Namespace root/WMI -ClassName WmiMonitorBrightness -ErrorAction SilentlyContinue).CurrentBrightness"]).creation_flags(NO_WINDOW).output();+ BRIGHT.store(o.ok().and_then(|o| String::from_utf8_lossy(&o.stdout).trim().parse().ok()).unwrap_or(-1), Relaxed);+ });+}++fn set_brightness(v: i32) {+ std::thread::spawn(move || {+ let c = format!("Get-CimInstance -Namespace root/WMI -ClassName WmiMonitorBrightnessMethods | Invoke-CimMethod -MethodName WmiSetBrightness -Arguments @{{Timeout=1;Brightness={v}}}");+ let _ = Command::new("powershell").args(["-NoProfile", "-Command", &c]).creation_flags(NO_WINDOW).output();+ });+}++/// Runs `f` with an open WLAN handle and the first wifi adapter. None when there is no wifi.+unsafe fn with_wlan<T>(f: impl FnOnce(HANDLE, &windows_sys::core::GUID) -> T) -> Option<T> {+ let (mut h, mut ver) = (null_mut(), 0u32);+ if WlanOpenHandle(2, null(), &mut ver, &mut h) != 0 {+ return None;+ }+ let mut list: *mut WLAN_INTERFACE_INFO_LIST = null_mut();+ let r = if WlanEnumInterfaces(h, null(), &mut list) == 0 {+ let l = &*list;+ let r = if l.dwNumberOfItems > 0 { Some(f(h, &(*l.InterfaceInfo.as_ptr()).InterfaceGuid)) } else { None };+ WlanFreeMemory(list as *const _);+ r+ } else {+ None+ };+ WlanCloseHandle(h, null());+ r+}++unsafe fn read_nets() {+ let v = with_wlan(|h, g| {+ let mut out: Vec<Net> = Vec::new();+ let mut list: *mut WLAN_AVAILABLE_NETWORK_LIST = null_mut();+ if WlanGetAvailableNetworkList(h, g, 0, null(), &mut list) == 0 {+ let l = &*list;+ for i in 0..l.dwNumberOfItems as usize {+ let n = &*l.Network.as_ptr().add(i);+ let ssid = String::from_utf8_lossy(&n.dot11Ssid.ucSSID[..n.dot11Ssid.uSSIDLength as usize]).to_string();+ if ssid.is_empty() {+ continue;+ }+ let pn = String::from_utf16_lossy(&n.strProfileName[..n.strProfileName.iter().position(|&c| c == 0).unwrap_or(0)]);+ let net = Net { ssid, q: n.wlanSignalQuality as i32, secure: n.bSecurityEnabled != 0, profile: (n.dwFlags & 2 != 0 && !pn.is_empty()).then_some(pn), connected: n.dwFlags & 1 != 0, auth: n.dot11DefaultAuthAlgorithm as i32 };+ match out.iter_mut().find(|o| o.ssid == net.ssid) {+ Some(o) if o.q < net.q => *o = net,+ Some(_) => {}+ None => out.push(net),+ }+ }+ WlanFreeMemory(list as *const _);+ }+ out.sort_by_key(|n| (!n.connected, -n.q));+ out.truncate(7);+ let (mut size, mut data) = (0u32, null_mut());+ let conn = (WlanQueryInterface(h, g, wlan_intf_opcode_current_connection, null(), &mut size, &mut data, null_mut()) == 0).then(|| {+ let at = &*(data as *const WLAN_CONNECTION_ATTRIBUTES);+ let a = &at.wlanAssociationAttributes;+ let ssid = String::from_utf8_lossy(&a.dot11Ssid.ucSSID[..a.dot11Ssid.uSSIDLength as usize]).to_string();+ let c = Conn { ssid, auth: at.wlanSecurityAttributes.dot11AuthAlgorithm as i32, q: a.wlanSignalQuality as i32, rx: a.ulRxRate / 1000, tx: a.ulTxRate / 1000, phy: phy_name(a.dot11PhyType as i32) };+ WlanFreeMemory(data);+ c+ });+ // the network we are on can be missing from the scan list (hidden / not rescanned yet): show it anyway+ if let Some(c) = &conn {+ match out.iter().position(|n| n.ssid == c.ssid) {+ Some(i) => {+ out[i].connected = true;+ out.swap(0, i);+ }+ None => out.insert(0, Net { ssid: c.ssid.clone(), q: c.q, secure: c.auth != 1, profile: Some(c.ssid.clone()), connected: true, auth: c.auth }),+ }+ }+ (out, conn)+ });+ let (nets, conn) = v.unzip();+ NETS.set(nets.unwrap_or_default());+ CONN.set(conn.flatten());+}++unsafe fn wifi_connect(profile: &str) {+ let p = wide(profile);+ with_wlan(|h, g| {+ let params = WLAN_CONNECTION_PARAMETERS { wlanConnectionMode: wlan_connection_mode_profile, strProfile: p.as_ptr(), pDot11Ssid: null_mut(), pDesiredBssidList: null_mut(), dot11BssType: dot11_BSS_type_any, dwFlags: 0 };+ WlanConnect(h, g, ¶ms, null());+ });+}++fn esc(s: &str) -> String {+ s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """)+}++/// Saves a profile for a new network and connects. shortcut: only open and WPA/WPA2/WPA3 personal (password) networks; enterprise ones go to Windows settings.+unsafe fn wifi_join(n: &Net, pass: &str) {+ let (auth, key) = match n.auth {+ 1 => ("open", String::new()),+ 4 => ("WPAPSK", pass.into()),+ 7 => ("WPA2PSK", pass.into()),+ _ => ("WPA3SAE", pass.into()),+ };+ let sec = if auth == "open" {+ "<authEncryption><authentication>open</authentication><encryption>none</encryption><useOneX>false</useOneX></authEncryption>".to_string()+ } else {+ format!("<authEncryption><authentication>{auth}</authentication><encryption>AES</encryption><useOneX>false</useOneX></authEncryption><sharedKey><keyType>passphrase</keyType><protected>false</protected><keyMaterial>{}</keyMaterial></sharedKey>", esc(&key))+ };+ let name = esc(&n.ssid);+ let xml = format!("<?xml version=\"1.0\"?><WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\"><name>{name}</name><SSIDConfig><SSID><name>{name}</name></SSID></SSIDConfig><connectionType>ESS</connectionType><connectionMode>auto</connectionMode><MSM><security>{sec}</security></MSM></WLANProfile>");+ let x = wide(&xml);+ let mut reason = 0u32;+ let ok = with_wlan(|h, g| WlanSetProfile(h, g, 0, x.as_ptr(), null(), 1, null_mut(), &mut reason) == 0).unwrap_or(false);+ if ok {+ wifi_connect(&n.ssid);+ NOTE.set(format!("Connecting to {}…", n.ssid));+ } else {+ NOTE.set("Could not save the network (wrong password format?)".into());+ }+}++// ---------- geometry ----------++fn size(k: Kind) -> (i32, i32) {+ match k {+ Kind::Quick => (360, 196 + if BRIGHT.load(Relaxed) >= 0 { 96 } else { 48 } + 64),+ Kind::Cal => (330, 340),+ Kind::Wifi => (360, wifi_rows().2),+ Kind::Start => (560, 640),+ Kind::Menu => (MW, menu_rows().1),+ }+}++/// Wi-Fi panel rows in logical px: (top, bottom) per network (the connected one is a taller card),+/// y of the "Available networks" label, and the panel height.+fn wifi_rows() -> (Vec<(i32, i32)>, Option<i32>, i32) {+ NETS.with_borrow(|n| {+ let (mut y, mut rows, mut label) = (60, vec![], None);+ for net in n.iter() {+ if net.connected {+ rows.push((y, y + 96));+ y += 104;+ } else {+ if label.is_none() {+ label = Some(y);+ y += 28;+ }+ rows.push((y, y + 54));+ y += 54;+ }+ }+ (rows, label, y + if n.is_empty() { 72 } else { 0 } + 56)+ })+}++fn r(l: i32, t: i32, rr: i32, b: i32) -> RECT {+ RECT { left: sc(l), top: sc(t), right: sc(rr), bottom: sc(b) }+}++fn rects(k: Kind) -> Vec<(RECT, Act)> {+ let (w, h) = size(k);+ match k {+ Kind::Quick => {+ let mut v = vec![(r(16, 16, 16 + 104 - 36, 72), Act::Tile(0)), (r(16 + 104 - 36, 16, 16 + 104, 72), Act::WifiMore)];+ v.extend((1..6u8).map(|i| {+ let (c, rw) = (i as i32 % 3, i as i32 / 3);+ (r(16 + 112 * c, 16 + 96 * rw, 16 + 112 * c + 104, 72 + 96 * rw), Act::Tile(i))+ }));+ let mut y = 196;+ if BRIGHT.load(Relaxed) >= 0 {+ v.push((r(60, y, w - 16, y + 40), Act::BrightSlide));+ y += 48;+ }+ v.push((r(16, y, 52, y + 40), Act::Mute));+ v.push((r(60, y, w - 16, y + 40), Act::VolSlide));+ v.push((r(w - 52, h - 48, w - 12, h - 8), Act::Settings("ms-settings:")));+ v+ }+ Kind::Cal => vec![(r(w - 84, 10, w - 52, 42), Act::CalPrev), (r(w - 48, 10, w - 16, 42), Act::CalNext), (r(16, 10, w - 100, 42), Act::CalToday)],+ Kind::Wifi => {+ let mut v: Vec<_> = wifi_rows().0.iter().enumerate().map(|(i, &(t, b))| (r(8, t, w - 8, b), Act::Net(i))).collect();+ v.push((r(w - 64, 14, w - 16, 38), Act::WifiSwitch));+ v.push((r(16, h - 40, w - 16, h - 8), Act::Settings("ms-settings:network-wifi")));+ v+ }+ Kind::Menu => menu_rows().0.into_iter().enumerate().map(|(i, (t, b))| (r(6, t, w - 6, b), Act::Menu(i as u8))).collect(),+ Kind::Start => {+ let f = filtered();+ let s = SCROLL.get();+ let mut v: Vec<_> = (0..ROWS).filter(|i| s + i < f.len()).map(|i| (r(12, 76 + 40 * i as i32, w - 12, 76 + 40 * (i as i32 + 1)), Act::App(s + i))).collect();+ v.extend((0..4u8).map(|i| (r(w - 16 - 4 * 44 + 44 * i as i32, h - 52, w - 16 - 4 * 44 + 44 * (i as i32 + 1) - 4, h - 12), Act::Power(i))));+ v+ }+ }+}++fn act_at(k: Kind, x: i32, y: i32) -> Option<(RECT, Act)> {+ rects(k).into_iter().rev().find(|(r, _)| x >= r.left && x < r.right && y >= r.top && y < r.bottom)+}++// ---------- open / close ----------++pub fn init(hi: HINSTANCE) {+ pinned_load();+ unsafe {+ let class = wide("topbar_fly");+ let wc = WNDCLASSW { lpfnWndProc: Some(proc), hInstance: hi, hCursor: LoadCursorW(null_mut(), IDC_ARROW), lpszClassName: class.as_ptr(), ..zeroed() };+ RegisterClassW(&wc);+ }+}++/// One row of a menu flyout: a glyph (or an icon, e.g. of a window), a label, red when it destroys something,+/// a separator line above it when `sep`.+pub struct MItem {+ pub glyph: &'static str,+ pub icon: HICON,+ pub label: String,+ pub danger: bool,+ pub sep: bool,+}++impl MItem {+ pub fn new(glyph: &'static str, label: impl Into<String>) -> Self {+ MItem { glyph, icon: null_mut(), label: label.into(), danger: false, sep: false }+ }+ pub fn danger(mut self) -> Self {+ self.danger = true;+ self+ }+ pub fn sep(mut self) -> Self {+ self.sep = true;+ self+ }+}++type Pick = Box<dyn FnOnce(usize)>;+thread_local! {+ static MITEMS: RefCell<Vec<MItem>> = const { RefCell::new(Vec::new()) };+ static MHEAD: RefCell<Option<(HICON, String, String)>> = const { RefCell::new(None) }; // icon, title, subtitle+ static MPICK: RefCell<Option<Pick>> = const { RefCell::new(None) };+}+const MW: i32 = 272; // menu width+const MROW: i32 = 38;+const MHEAD_H: i32 = 58;++/// Menu flyout above the bar, centered on screen x `cx`. `pick` gets the index of the chosen item (not called on cancel).+/// A right click while a menu is open replaces it.+pub fn menu(cx: i32, head: Option<(HICON, String, String)>, items: Vec<MItem>, pick: impl FnOnce(usize) + 'static) {+ if is_open(Kind::Menu) {+ close_now();+ }+ LAST.set((None, 0)); // always opens, even right after another menu closed+ MITEMS.set(items);+ MHEAD.set(head);+ MPICK.set(Some(Box::new(pick)));+ MENU_X.set(cx - sc(MW) / 2);+ toggle(Kind::Menu);+}++/// (top, bottom) of each menu item in logical px, and the panel height.+fn menu_rows() -> (Vec<(i32, i32)>, i32) {+ let mut y = if MHEAD.with_borrow(|h| h.is_some()) { MHEAD_H + 9 } else { 6 };+ let rows = MITEMS.with_borrow(|m| {+ m.iter()+ .map(|it| {+ if it.sep {+ y += 9;+ }+ y += MROW;+ (y - MROW, y)+ })+ .collect()+ });+ (rows, y + 6)+}++/// Right-click menu of an empty spot of the bar.+pub fn context_menu(x: i32) {+ let items = vec![+ MItem::new("\u{E713}", "Параметры Windows"),+ MItem::new("\u{E771}", "Персонализация"),+ MItem::new("\u{E9D9}", "Диспетчер задач").sep(),+ MItem::new("\u{E74D}", "Чистильщик диска"),+ MItem::new("\u{E711}", "Закрыть топбар").danger().sep(),+ ];+ menu(x, None, items, |i| unsafe {+ match i {+ 0 => open(&wide("ms-settings:")),+ 1 => open(&wide("ms-settings:personalization")),+ // with rtaskmgr-win32 installed this is our task manager; a full path because explorer.exe does not search PATH+ 2 => open(&wide(&format!(r"{}\System32\taskmgr.exe", std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".into())))),+ 3 => open_cleaner(),+ _ => _ = PostMessageW(FindWindowW(wide("topbar").as_ptr(), null()), WM_CLOSE, 0, 0), // quits the bar, brings the Windows taskbar back+ }+ });+}++/// Starts the fade-out of the open flyout (it stays as a ghost window until the fade ends).+pub fn close() {+ if FLY.get().is_some() {+ LAST.set((FLY.get(), unsafe { now_ms() }));+ }+ let h = FH.replace(null_mut());+ FLY.set(None);+ if h.is_null() {+ return;+ }+ unsafe {+ kill_ghost();+ GHOST.set((h, now_ms(), FIN.get()));+ KillTimer(h, 1);+ KillTimer(h, 2);+ SetTimer(h, 3, 15, None);+ }+}++/// Closes without the fade (another flyout replaces it, or a fullscreen app needs the screen).+pub fn close_now() {+ close();+ unsafe { kill_ghost() };+}++unsafe fn kill_ghost() {+ let (g, _, _) = GHOST.replace((null_mut(), 0, (0, 0)));+ if !g.is_null() {+ DestroyWindow(g);+ }+}++/// One frame of a flyout fade: opening rises up from the bar while fading in, closing fades out while sinking back down.+unsafe fn anim_step(hw: HWND) {+ let now = now_ms();+ let (g, gt0, gpos) = GHOST.get();+ if hw == g {+ let t = (now.saturating_sub(gt0) as f32 / 150.0).min(1.0);+ let q = t * t;+ SetLayeredWindowAttributes(hw, 0, ((1.0 - q) * 255.0) as u8, LWA_ALPHA);+ SetWindowPos(hw, null_mut(), gpos.0, gpos.1 + (q * sc(10) as f32) as i32, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);+ if t >= 1.0 {+ kill_ghost();+ }+ } else if hw == FH.get() {+ let t = (now.saturating_sub(T0.get()) as f32 / 220.0).min(1.0);+ let p = 1.0 - (1.0 - t).powi(3);+ SetLayeredWindowAttributes(hw, 0, (p * 255.0) as u8, LWA_ALPHA);+ let (x, y) = FIN.get();+ SetWindowPos(hw, null_mut(), x, y + ((1.0 - p) * sc(14) as f32) as i32, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);+ if t >= 1.0 {+ KillTimer(hw, 3);+ }+ } else {+ KillTimer(hw, 3);+ }+}++pub fn toggle(k: Kind) {+ if FLY.get() == Some(k) {+ return close();+ }+ let (was, at) = LAST.get();+ if was == Some(k) && unsafe { now_ms() }.saturating_sub(at) < 400 {+ return; // it closed an instant ago (focus moved to the key / click that is toggling it): this press means "close", not "reopen"+ }+ close();+ unsafe {+ HV.with_borrow_mut(|m| m.retain(|k, _| *k < 1_000_000)); // flyout keys are >= 1_000_000: no stale glow from the last panel+ QUERY.set(String::new());+ SCROLL.set(0);+ SEL.set(0);+ PASS.set(None);+ NOTE.set(String::new());+ CONFIRM.set(-1);+ OVER.set(None);+ let mut t: SYSTEMTIME = zeroed();+ GetLocalTime(&mut t);+ CAL.set((t.wYear as i32, t.wMonth as i32));+ match k {+ Kind::Wifi => {+ with_wlan(|h, g| WlanScan(h, g, null(), null(), null()));+ read_nets();+ }+ Kind::Quick => {+ read_brightness();+ read_nets();+ }+ Kind::Start => {+ pinned_load(); // the search card (rs-launcher) can add to this list from another process+ std::thread::spawn(load_apps); // apps installed since the last open show up (the panel repaints every second)+ }+ _ => {}+ }+ let (w, h) = (sc(size(k).0), sc(size(k).1));+ let sw = GetSystemMetrics(SM_CXSCREEN);+ let x = match k {+ Kind::Start => (sw - w) / 2,+ Kind::Menu => MENU_X.get().min(sw - w - sc(8)).max(sc(8)),+ _ => sw - w - sc(8),+ };+ let class = wide("topbar_fly");+ let fy = bar_top() - sc(8) - h; // above the bar+ let hw = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_LAYERED, class.as_ptr(), null(), WS_POPUP, x, fy + sc(14), w, h, null_mut(), null_mut(), GetModuleHandleW(null()), null());+ SetLayeredWindowAttributes(hw, 0, 0, LWA_ALPHA); // starts invisible, anim_step fades it in+ if k == Kind::Start {+ // accept file drops (an app dragged onto the panel is added to Start); the bar may be elevated, so lift UIPI for them+ DragAcceptFiles(hw, 1);+ for m in [WM_DROPFILES, 0x49 /* WM_COPYGLOBALDATA */, WM_COPYDATA] {+ ChangeWindowMessageFilterEx(hw, m, MSGFLT_ALLOW, null_mut());+ }+ }+ FIN.set((x, fy));+ T0.set(now_ms());+ SetWindowRgn(hw, CreateRoundRectRgn(0, 0, w + 1, h + 1, sc(16), sc(16)), 1);+ FH.set(hw);+ FLY.set(Some(k));+ ShowWindow(hw, SW_SHOW);+ force_fg(hw);+ SetTimer(hw, 1, 1000, None);+ SetTimer(hw, 3, 15, None);+ }+}++// ---------- actions ----------++unsafe fn slide(a: Act, x: i32, rect: RECT) {+ let f = ((x - rect.left - sc(8)) as f32 / (rect.right - rect.left - sc(16)) as f32).clamp(0.0, 1.0);+ if a == Act::VolSlide {+ set_volume((f * 100.0).round() as i32);+ } else {+ BRIGHT.store(((f * 100.0) as i32).max(1), Relaxed);+ }+}++/// Wi-Fi radio on/off (the Wi-Fi tile). shortcut: software radio of the first adapter / first PHY only.+unsafe fn wifi_radio(on: bool) {+ with_wlan(|h, g| {+ let s = WLAN_PHY_RADIO_STATE { dwPhyIndex: 0, dot11SoftwareRadioState: if on { dot11_radio_state_on } else { dot11_radio_state_off }, dot11HardwareRadioState: dot11_radio_state_on };+ WlanSetInterface(h, g, wlan_intf_opcode_radio_state, size_of::<WLAN_PHY_RADIO_STATE>() as u32, &s as *const _ as *const _, null());+ });+}++/// Starts the i-th app of the filtered Start list and counts the launch (search ranks by it). false = no such row.+unsafe fn launch(i: usize) -> bool {+ let Some(app) = filtered().get(i).and_then(|&ai| APPS.lock().unwrap().get(ai).cloned()) else { return false };+ if wstr(&app.1).starts_with("shell:") {+ bump_name(&app.0); // open() counts only .lnk files+ }+ open(&app.1);+ true+}++/// Right-click menu of a Start app: open, open as administrator, show the shortcut's folder.+unsafe fn app_menu(hw: HWND, i: usize, x: i32, y: i32) {+ let Some(lnk) = filtered().get(i).and_then(|&ai| APPS.lock().unwrap().get(ai).map(|a| a.1.clone())) else { return };+ let m = CreatePopupMenu();+ let path = wstr(&lnk);+ let file = !path.starts_with("shell:"); // Store apps have no file to run elevated or to show in a folder+ for (id, label) in [(1, "Open"), (2, "Run as administrator"), (3, "Open file location"), (4, if start_pinned(&path) { "Remove from Start" } else { "Add to Start" })] {+ if file || id == 1 || id == 4 {+ AppendMenuW(m, MF_STRING, id, wide(label).as_ptr());+ }+ }+ let mut pt = POINT { x, y };+ ClientToScreen(hw, &mut pt);+ let cmd = TrackPopupMenu(m, TPM_RETURNCMD | TPM_RIGHTBUTTON, pt.x, pt.y, 0, hw, null());+ DestroyMenu(m);+ match cmd {+ 1 => _ = launch(i),+ 2 => {+ ShellExecuteW(null_mut(), wide("runas").as_ptr(), lnk.as_ptr(), null(), null(), SW_SHOWNORMAL);+ }+ 3 => {+ let p = String::from_utf16_lossy(&lnk[..lnk.len().saturating_sub(1)]);+ ShellExecuteW(null_mut(), wide("open").as_ptr(), wide("explorer.exe").as_ptr(), wide(&format!("/select,\"{p}\"")).as_ptr(), null(), SW_SHOWNORMAL);+ }+ 4 => {+ start_toggle(&path);+ return; // stay open, the list just changed+ }+ _ => return,+ }+ close();+}++unsafe fn run_act(a: Act, rect: RECT, x: i32) {+ match a {+ Act::VolSlide | Act::BrightSlide => {+ DRAG.set(if a == Act::VolSlide { 1 } else { 2 });+ SetCapture(FH.get());+ slide(a, x, rect);+ }+ Act::WifiMore => toggle(Kind::Wifi),+ Act::WifiSwitch => wifi_radio(WIFI.get() < 0 && NETS.with_borrow(|n| n.is_empty())),+ Act::Tile(i) => match i {+ 0 => wifi_radio(WIFI.get() < 0),+ 5 => {+ close();+ keys(&[VK_LWIN, VK_CONTROL, b'L' as u16]); // live captions+ }+ _ => {+ open(&wide(["", "ms-settings:bluetooth", "ms-settings:network-airplanemode", "ms-settings:easeofaccess", "ms-settings:batterysaver"][i as usize]));+ close();+ }+ },+ Act::Mute => toggle_mute(),+ Act::Menu(i) => {+ close();+ if let Some(pick) = MPICK.take() {+ pick(i as usize);+ }+ }+ Act::Settings(u) => {+ open(&wide(u));+ close();+ }+ Act::CalPrev | Act::CalNext => {+ let (mut y, mut m) = CAL.get();+ m += if a == Act::CalNext { 1 } else { -1 };+ (y, m) = if m < 1 { (y - 1, 12) } else if m > 12 { (y + 1, 1) } else { (y, m) };+ CAL.set((y, m));+ }+ Act::CalToday => {+ let mut t: SYSTEMTIME = zeroed();+ GetLocalTime(&mut t);+ CAL.set((t.wYear as i32, t.wMonth as i32));+ }+ Act::Net(i) => {+ let n = NETS.with_borrow(|n| n.get(i).map(|n| (n.connected, n.profile.clone(), n.auth, n.secure, n.ssid.clone())));+ let Some((connected, profile, auth, secure, ssid)) = n else { return };+ if connected {+ with_wlan(|h, g| WlanDisconnect(h, g, null()));+ NOTE.set("Disconnected".into());+ } else if let Some(p) = profile {+ wifi_connect(&p);+ NOTE.set(format!("Connecting to {ssid}…"));+ } else if !secure {+ NETS.with_borrow(|l| wifi_join(&l[i], ""));+ } else if matches!(auth, 4 | 7 | 8 | 9) {+ PASS.set(Some((i, String::new())));+ } else {+ open(&wide("ms-settings:network-wifi"));+ close();+ }+ }+ Act::App(i) => {+ if launch(i) {+ close();+ }+ }+ Act::Power(p) => {+ if p >= 2 && CONFIRM.get() != p as i32 {+ CONFIRM.set(p as i32); // first click only arms it+ return;+ }+ close();+ match p {+ 0 => {+ let _ = Command::new("rundll32.exe").args(["user32.dll,LockWorkStation"]).creation_flags(NO_WINDOW).spawn();+ }+ 1 => {+ // not `rundll32 powrprof.dll,SetSuspendState`: rundll32 passes garbage arguments and the PC hibernates+ // instead of sleeping whenever hibernation is on. On its own thread: the call returns only after wake-up.+ std::thread::spawn(|| sleep_now());+ }+ 2 => {+ let _ = Command::new("shutdown").args(["/r", "/t", "0"]).creation_flags(NO_WINDOW).spawn();+ }+ _ => {+ let _ = Command::new("shutdown").args(["/s", "/t", "0"]).creation_flags(NO_WINDOW).spawn();+ }+ }+ }+ }+}++/// Sleep (S3 / modern standby), never hibernate. SetSuspendState needs the shutdown privilege switched on in our token.+fn sleep_now() {+ use windows_sys::Win32::{+ Security::{AdjustTokenPrivileges, LookupPrivilegeValueW, SE_PRIVILEGE_ENABLED, TOKEN_ADJUST_PRIVILEGES, TOKEN_PRIVILEGES},+ System::{Power::SetSuspendState, Threading::{GetCurrentProcess, OpenProcessToken}},+ };+ unsafe {+ let mut tok = null_mut();+ if OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &mut tok) != 0 {+ let mut tp: TOKEN_PRIVILEGES = zeroed();+ tp.PrivilegeCount = 1;+ tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;+ if LookupPrivilegeValueW(null(), wide("SeShutdownPrivilege").as_ptr(), &mut tp.Privileges[0].Luid) != 0 {+ AdjustTokenPrivileges(tok, 0, &tp, 0, null_mut(), null_mut());+ }+ CloseHandle(tok);+ }+ SetSuspendState(false, false, false);+ }+}++// ---------- painting ----------++unsafe fn track(dc: HDC, rc: RECT, frac: f32) {+ let (l, rr, m) = (rc.left + sc(8), rc.right - sc(8), (rc.top + rc.bottom) / 2);+ fill(dc, RECT { left: l, top: m - sc(2), right: rr, bottom: m + sc(2) }, rgb(70, 78, 98), sc(4));+ let x = l + ((rr - l) as f32 * frac.clamp(0.0, 1.0)) as i32;+ fill(dc, RECT { left: l, top: m - sc(2), right: x, bottom: m + sc(2) }, ACCENT, sc(4));+ fill(dc, RECT { left: x - sc(8), top: m - sc(8), right: x + sc(8), bottom: m + sc(8) }, TEXT, sc(16));+}++unsafe fn paint(hw: HWND, k: Kind) {+ let mut ps: PAINTSTRUCT = zeroed();+ let wdc = BeginPaint(hw, &mut ps);+ let mut cr: RECT = zeroed();+ GetClientRect(hw, &mut cr);+ BUSY.set(false);+ let (dc, bmp) = (CreateCompatibleDC(wdc), CreateCompatibleBitmap(wdc, cr.right, cr.bottom));+ let old = SelectObject(dc, bmp);+ fill(dc, cr, LINE, sc(16));+ fill(dc, RECT { left: 1, top: 1, right: cr.right - 1, bottom: cr.bottom - 1 }, BG, sc(16));+ SetBkMode(dc, TRANSPARENT as i32);+ let (face, gface) = (wide("Segoe UI"), wide("Segoe MDL2 Assets"));+ let font = |f: &[u16], px: i32, wt: i32| CreateFontW(-sc(px), 0, 0, 0, wt, 0, 0, 0, 1, 0, 0, 5, 0, f.as_ptr());+ let (f_txt, f_small, f_glyph, f_title, f_big) = (font(&face, 13, 400), font(&face, 12, 400), font(&gface, 16, 400), font(&face, 15, 600), font(&face, 34, 600));+ let of = SelectObject(dc, f_txt);+ let (w, h) = size(k);+ let over = OVER.get();+ let hot = |a: Act| over == Some(a);+ // hover highlight that fades; the key is the element's position (flyout keys start at 1_000_000)+ let g = |a: Act, rc: RECT, from: u32, to: u32, rad: i32| glow(dc, rc.top * 4096 + rc.left + 1_000_000, hot(a), rc, from, to, rad);+ let (vol, muted) = VOL.get();++ match k {+ Kind::Quick => {+ let rs = rects(k);+ let ssid = NETS.with_borrow(|n| n.iter().find(|n| n.connected).map(|n| n.ssid.clone()));+ let tiles = [("\u{E701}", ssid.unwrap_or("Wi‑Fi".into())), ("\u{E702}", "Bluetooth".into()), ("\u{E709}", "Airplane mode".into()), ("\u{E776}", "Accessibility".into()), ("\u{E945}", "Energy saver".into()), ("\u{E7F0}", "Live captions".into())];+ for (i, (glyph, label)) in tiles.iter().enumerate() {+ let c = (i % 3) as i32;+ let (tl, tt) = (16 + 112 * c, 16 + 96 * (i as i32 / 3));+ let on = i == 0 && WIFI.get() >= 0;+ let full = r(tl, tt, tl + 104, tt + 56);+ fill(dc, full, if on { ACCENT } else { LINE }, sc(8));+ fill(dc, RECT { left: full.left + 1, top: full.top + 1, right: full.right - 1, bottom: full.bottom - 1 }, if on { ACCENT } else { rgb(32, 40, 58) }, sc(8));+ for (rc, a) in rs.iter().filter(|(_, a)| matches!(a, Act::Tile(j) if *j as usize == i) || (i == 0 && *a == Act::WifiMore)) {+ g(*a, *rc, if on { ACCENT } else { rgb(32, 40, 58) }, if on { rgb(110, 210, 255) } else { HOVER }, sc(8));+ }+ SelectObject(dc, f_glyph);+ let gr = if i == 0 { r(tl, tt, tl + 68, tt + 56) } else { full };+ text(dc, glyph, gr, if on { BG } else { TEXT }, DT_CENTER);+ if i == 0 {+ fill(dc, r(tl + 68, tt + 12, tl + 69, tt + 44), if on { BG } else { LINE }, 0);+ text(dc, "\u{E76C}", r(tl + 68, tt, tl + 104, tt + 56), if on { BG } else { TEXT }, DT_CENTER);+ }+ SelectObject(dc, f_small);+ text(dc, label, r(tl, tt + 60, tl + 104, tt + 82), TEXT, DT_CENTER);+ }+ let mut y = 196;+ let b = BRIGHT.load(Relaxed);+ if b >= 0 {+ SelectObject(dc, f_glyph);+ text(dc, "\u{E706}", r(16, y, 52, y + 40), TEXT, DT_CENTER);+ track(dc, rs.iter().find(|(_, a)| *a == Act::BrightSlide).unwrap().0, b as f32 / 100.0);+ y += 48;+ }+ g(Act::Mute, r(16, y, 52, y + 40), BG, HOVER, sc(8));+ SelectObject(dc, f_glyph);+ text(dc, if muted || vol == 0 { "\u{E74F}" } else { "\u{E767}" }, r(16, y, 52, y + 40), TEXT, DT_CENTER);+ track(dc, rs.iter().find(|(_, a)| *a == Act::VolSlide).unwrap().0, if muted { 0.0 } else { vol.max(0) as f32 / 100.0 });+ fill(dc, r(0, h - 56, w, h - 55), LINE, 0);+ let (pct, ac) = BAT.get();+ SelectObject(dc, f_glyph);+ if pct >= 0 {+ text(dc, if ac { "\u{E83E}" } else { "\u{E83F}" }, r(16, h - 48, 44, h - 8), if ac { GOOD } else { TEXT }, DT_CENTER);+ SelectObject(dc, f_txt);+ text(dc, &format!("{pct}%"), r(48, h - 48, 140, h - 8), TEXT, DT_LEFT);+ }+ g(Act::Settings("ms-settings:"), r(w - 52, h - 48, w - 12, h - 8), BG, HOVER, sc(8));+ SelectObject(dc, f_glyph);+ text(dc, "\u{E713}", r(w - 52, h - 48, w - 12, h - 8), TEXT, DT_CENTER);+ }+ Kind::Cal => {+ let (y, m) = CAL.get();+ SelectObject(dc, f_title);+ text(dc, &format!("{} {y}", MONTHS[m as usize - 1]), r(16, 10, w - 100, 42), TEXT, DT_LEFT);+ SelectObject(dc, f_glyph);+ text(dc, "\u{E70E}", r(w - 84, 10, w - 52, 42), TEXT, DT_CENTER);+ text(dc, "\u{E70D}", r(w - 48, 10, w - 16, 42), TEXT, DT_CENTER);+ SelectObject(dc, f_small);+ for (i, d) in ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"].iter().enumerate() {+ text(dc, d, r(18 + 42 * i as i32, 54, 60 + 42 * i as i32, 78), DIM, DT_CENTER);+ }+ let t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];+ let yy = if m < 3 { y - 1 } else { y };+ let first = ((yy + yy / 4 - yy / 100 + yy / 400 + t[m as usize - 1] + 1) % 7 + 6) % 7; // Monday = 0+ let dim = match m {+ 2 => if (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 { 29 } else { 28 },+ 4 | 6 | 9 | 11 => 30,+ _ => 31,+ };+ let mut now: SYSTEMTIME = zeroed();+ GetLocalTime(&mut now);+ SelectObject(dc, f_txt);+ for d in 1..=dim {+ let (col, row) = ((first + d - 1) % 7, (first + d - 1) / 7);+ let cell = r(18 + 42 * col, 84 + 40 * row, 60 + 42 * col, 120 + 40 * row);+ let today = now.wYear as i32 == y && now.wMonth as i32 == m && now.wDay as i32 == d;+ if today {+ fill(dc, cell, ACCENT, sc(18));+ }+ text(dc, &d.to_string(), cell, if today { BG } else { TEXT }, DT_CENTER);+ }+ }+ Kind::Wifi => {+ let on = NETS.with_borrow(|n| !n.is_empty()) || WIFI.get() >= 0;+ SelectObject(dc, f_title);+ text(dc, "Wi‑Fi", r(16, 10, w - 90, 34), TEXT, DT_LEFT);+ SelectObject(dc, f_small);+ let note = NOTE.with_borrow(|n| n.clone());+ let count = NETS.with_borrow(|n| n.len());+ let sub = if !note.is_empty() { note } else if on { format!("On · {count} network{} in range", if count == 1 { "" } else { "s" }) } else { "Off — turn on the switch to see networks".into() };+ text(dc, &sub, r(16, 34, w - 90, 54), DIM, DT_LEFT);+ // on/off switch+ let sw = r(w - 64, 14, w - 16, 38);+ fill(dc, sw, if on { ACCENT } else { rgb(70, 78, 98) }, sc(24));+ let kx = if on { sw.right - sc(13) } else { sw.left + sc(13) };+ fill(dc, RECT { left: kx - sc(8), top: sw.top + sc(4), right: kx + sc(8), bottom: sw.bottom - sc(4) }, if on { BG } else { TEXT }, sc(16));+ let rs = rects(k);+ let pass = PASS.with_borrow(|p| p.clone());+ if let Some((i, p)) = pass {+ let name = NETS.with_borrow(|n| n.get(i).map(|n| n.ssid.clone()).unwrap_or_default());+ SelectObject(dc, f_txt);+ text(dc, &format!("Password for “{name}”"), r(16, 70, w - 16, 96), TEXT, DT_LEFT);+ fill(dc, r(16, 104, w - 16, 142), LINE, sc(6));+ fill(dc, r(17, 105, w - 17, 141), rgb(16, 20, 30), sc(6));+ text(dc, &"•".repeat(p.chars().count()), r(28, 104, w - 28, 142), TEXT, DT_LEFT);+ SelectObject(dc, f_small);+ text(dc, "Enter — connect · Esc — cancel", r(16, 150, w - 16, 174), DIM, DT_LEFT);+ } else {+ let (_, label, _) = wifi_rows();+ let conn = CONN.with_borrow(|c| c.as_ref().map(|c| (c.q, c.rx, c.tx, c.phy)));+ NETS.with_borrow(|nets| {+ if nets.is_empty() {+ SelectObject(dc, f_txt);+ text(dc, if on { "No networks found nearby" } else { "Wi‑Fi is turned off" }, r(16, 70, w - 16, 120), DIM, DT_LEFT);+ }+ if let Some(ly) = label {+ SelectObject(dc, f_small);+ text(dc, "AVAILABLE NETWORKS", r(16, ly + 2, w - 16, ly + 26), DIM, DT_LEFT);+ }+ for (i, n) in nets.iter().enumerate() {+ let rc = rs[i].0;+ let bars = |x: i32, base: i32, q: i32, scale: i32| {+ let lit = ((q + 24) / 25).clamp(1, 4);+ for b in 0..4 {+ let bh = sc((4 + 3 * b) * scale);+ let bx = x + sc(5 * scale) * b;+ fill(dc, RECT { left: bx, top: base - bh, right: bx + sc(3 * scale), bottom: base }, if b < lit { TEXT } else { rgb(90, 98, 115) }, sc(1));+ }+ };+ if n.connected {+ fill(dc, rc, ACTIVE, sc(10));+ g(Act::Net(i), rc, ACTIVE, rgb(60, 70, 96), sc(10));+ bars(rc.left + sc(18), rc.top + sc(54), n.q, 2);+ SelectObject(dc, f_title);+ text(dc, &n.ssid, RECT { left: rc.left + sc(64), top: rc.top + sc(8), right: rc.right - sc(110), bottom: rc.top + sc(34) }, TEXT, DT_LEFT);+ SelectObject(dc, f_small);+ let q = conn.map(|c| c.0).unwrap_or(n.q);+ text(dc, &format!("Connected · signal {q}%"), RECT { left: rc.left + sc(64), top: rc.top + sc(34), right: rc.right - sc(110), bottom: rc.top + sc(56) }, ACCENT, DT_LEFT);+ let det = match conn {+ Some((_, rx, tx, phy)) => format!("{phy} · ↓ {rx} / ↑ {tx} Mbps · {}", auth_name(n.auth)),+ None => auth_name(n.auth).to_string(),+ };+ text(dc, &det, RECT { left: rc.left + sc(64), top: rc.top + sc(58), right: rc.right - sc(12), bottom: rc.top + sc(82) }, DIM, DT_LEFT);+ let cb = RECT { left: rc.right - sc(104), top: rc.top + sc(12), right: rc.right - sc(12), bottom: rc.top + sc(36) };+ fill(dc, cb, BAD, sc(8));+ fill(dc, RECT { left: cb.left + 1, top: cb.top + 1, right: cb.right - 1, bottom: cb.bottom - 1 }, ACTIVE, sc(8));+ text(dc, "Disconnect", cb, BAD, DT_CENTER);+ } else {+ g(Act::Net(i), rc, BG, HOVER, sc(10));+ bars(rc.left + sc(18), rc.top + sc(34), n.q, 1);+ SelectObject(dc, f_txt);+ text(dc, &n.ssid, RECT { left: rc.left + sc(52), top: rc.top + sc(6), right: rc.right - sc(110), bottom: rc.top + sc(30) }, TEXT, DT_LEFT);+ SelectObject(dc, f_small);+ let sub = if !n.secure { "Open network — not secured".to_string() } else if n.profile.is_some() { format!("Saved · {}", auth_name(n.auth)) } else { format!("Not saved · {}", auth_name(n.auth)) };+ text(dc, &format!("{sub} · {}%", n.q), RECT { left: rc.left + sc(52), top: rc.top + sc(28), right: rc.right - sc(110), bottom: rc.bottom - sc(4) }, DIM, DT_LEFT);+ let action = if n.profile.is_some() || !n.secure { "Connect" } else { "Enter password" };+ text(dc, action, RECT { left: rc.right - sc(110), top: rc.top, right: rc.right - sc(14), bottom: rc.bottom }, ACCENT, DT_RIGHT);+ }+ }+ });+ }+ let last = rs.last().unwrap();+ g(last.1, last.0, BG, HOVER, sc(6));+ SelectObject(dc, f_txt);+ text(dc, "More Wi‑Fi settings", last.0, ACCENT, DT_CENTER);+ }+ Kind::Menu => {+ // header: the app's icon on an accent-tinted tile, its name, and what is open+ MHEAD.with_borrow(|hd| {+ if let Some((ic, title, sub)) = hd {+ let tile = r(14, 12, 48, 46);+ fill(dc, tile, mix(BG, ACCENT, 0.16), sc(10));+ if !ic.is_null() {+ DrawIconEx(dc, tile.left + sc(5), tile.top + sc(5), *ic, sc(24), sc(24), 0, null_mut(), DI_NORMAL);+ }+ SelectObject(dc, f_title);+ text(dc, title, r(60, 10, w - 14, 32), TEXT, DT_LEFT);+ SelectObject(dc, f_small);+ text(dc, sub, r(60, 30, w - 14, 48), DIM, DT_LEFT);+ fill(dc, r(12, MHEAD_H + 4, w - 12, MHEAD_H + 5), LINE, 0);+ }+ });+ let rs = rects(k);+ MITEMS.with_borrow(|items| {+ for ((rc, a), it) in rs.iter().zip(items) {+ if it.sep {+ fill(dc, RECT { left: rc.left + sc(6), top: rc.top - sc(5), right: rc.right - sc(6), bottom: rc.top - sc(5) + 1 }, LINE, 0);+ }+ let col = if it.danger { BAD } else { TEXT };+ g(*a, *rc, BG, if it.danger { mix(BG, BAD, 0.22) } else { HOVER }, sc(8));+ let ib = RECT { right: rc.left + sc(40), ..*rc };+ if !it.icon.is_null() {+ DrawIconEx(dc, ib.left + sc(12), (rc.top + rc.bottom) / 2 - sc(8), it.icon, sc(16), sc(16), 0, null_mut(), DI_NORMAL);+ } else {+ SelectObject(dc, f_glyph);+ text(dc, it.glyph, ib, if it.danger { BAD } else { mix(DIM, TEXT, 0.4) }, DT_CENTER);+ }+ SelectObject(dc, f_txt);+ text(dc, &it.label, RECT { left: rc.left + sc(42), right: rc.right - sc(10), ..*rc }, col, DT_LEFT);+ }+ });+ }+ Kind::Start => {+ fill(dc, r(20, 20, w - 20, 56), rgb(16, 20, 30), sc(18));+ SelectObject(dc, f_glyph);+ text(dc, "\u{E721}", r(28, 20, 56, 56), DIM, DT_CENTER);+ SelectObject(dc, f_txt);+ let q = QUERY.with_borrow(|q| q.clone());+ if q.is_empty() {+ text(dc, "Type to search apps", r(64, 20, w - 28, 56), DIM, DT_LEFT);+ } else {+ text(dc, &q, r(64, 20, w - 28, 56), TEXT, DT_LEFT);+ }+ let f = filtered();+ if f.is_empty() {+ if q.is_empty() {+ text(dc, "Nothing here yet", r(24, 76, w - 24, 106), TEXT, DT_LEFT);+ text(dc, "Drag an app or file onto the Start button to add it", r(24, 106, w - 24, 134), DIM, DT_LEFT);+ text(dc, "Or search an app and right-click it → Add to Start", r(24, 134, w - 24, 162), DIM, DT_LEFT);+ } else {+ text(dc, "No apps found", r(24, 76, w - 24, 116), DIM, DT_LEFT);+ }+ }+ let rs = rects(k);+ let apps = APPS.lock().unwrap();+ for (rc, a) in &rs {+ match *a {+ Act::App(i) => {+ // the list is reloaded on a background thread: an index from a moment ago may be gone+ let Some(app) = f.get(i).and_then(|&ai| apps.get(ai)) else { continue };+ // the row that was just pinned pulses in the accent colour for a moment+ let pulse = JUST.with_borrow(|j| {+ let age = now_ms().saturating_sub(j.1) as f32 / 1200.0;+ if age < 1.0 && !j.0.is_empty() && app.1 == wide(&j.0) { (1.0 - age) * (1.0 - age) } else { 0.0 }+ });+ let sel = i == SEL.get(); // what Enter opens+ if pulse > 0.0 || sel {+ BUSY.set(BUSY.get() || pulse > 0.0);+ fill(dc, *rc, mix(if sel { mix(BG, ACCENT, 0.14) } else { BG }, ACCENT, 0.45 * pulse), sc(8));+ }+ g(*a, *rc, if sel { mix(BG, ACCENT, 0.14) } else { BG }, if sel { mix(HOVER, ACCENT, 0.18) } else { HOVER }, sc(8));+ if sel {+ fill(dc, RECT { left: rc.left, top: rc.top + sc(10), right: rc.left + sc(3), bottom: rc.bottom - sc(10) }, ACCENT, sc(3));+ }+ let ic = ICONS.with_borrow_mut(|m| {+ *m.entry(app.1.clone()).or_insert_with(|| {+ let t = lnk_target(&app.1);+ lnk_icon(&app.1, &t)+ })+ });+ if !ic.is_null() {+ DrawIconEx(dc, rc.left + sc(13), (rc.top + rc.bottom - icon_px()) / 2, ic, icon_px(), icon_px(), 0, null_mut(), DI_NORMAL); // at its loaded size: no stretching+ }+ let store = wstr(&app.1).starts_with("shell:");+ text(dc, &app.0, RECT { left: rc.left + sc(52), top: rc.top, right: rc.right - sc(110), bottom: rc.bottom }, TEXT, DT_LEFT);+ SelectObject(dc, f_small);+ let kind = if sel && !q.is_empty() { "Enter ↵" } else if store { "Приложение" } else { "" };+ text(dc, kind, RECT { left: rc.right - sc(110), top: rc.top, right: rc.right - sc(14), bottom: rc.bottom }, DIM, DT_RIGHT);+ SelectObject(dc, f_txt);+ }+ Act::Power(p) => {+ let armed = CONFIRM.get() == p as i32;+ glow(dc, rc.top * 4096 + rc.left + 1_000_000, armed || hot(*a), *rc, BG, if armed { BAD } else { HOVER }, sc(8));+ SelectObject(dc, f_glyph);+ text(dc, ["\u{E72E}", "\u{E708}", "\u{E777}", "\u{E7E8}"][p as usize], *rc, TEXT, DT_CENTER);+ }+ _ => {}+ }+ }+ SelectObject(dc, f_small);+ let note = NOTE.with_borrow(|n| n.clone());+ let hint = match CONFIRM.get() {+ 2 => "Click again to restart".to_string(),+ 3 => "Click again to shut down".to_string(),+ _ if !note.is_empty() => note,+ _ => std::env::var("USERNAME").unwrap_or_default(),+ };+ text(dc, &hint, r(24, h - 52, w - 200, h - 12), DIM, DT_LEFT);+ }+ }++ BitBlt(wdc, 0, 0, cr.right, cr.bottom, dc, 0, 0, SRCCOPY);+ SelectObject(dc, of);+ for f in [f_txt, f_small, f_glyph, f_title, f_big] {+ DeleteObject(f);+ }+ SelectObject(dc, old);+ DeleteObject(bmp);+ DeleteDC(dc);+ if BUSY.get() {+ SetTimer(hw, 2, 16, None); // next animation frame+ } else {+ KillTimer(hw, 2);+ }+ EndPaint(hw, &ps);+}++// ---------- window proc ----------++unsafe extern "system" fn proc(hw: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {+ if msg == WM_TIMER && wp == 3 {+ anim_step(hw); // also for the fading-out ghost window+ return 0;+ }+ if hw != FH.get() {+ return DefWindowProcW(hw, msg, wp, lp); // ghost or a window still being created+ }+ let Some(k) = FLY.get() else { return DefWindowProcW(hw, msg, wp, lp) };+ let (x, y) = ((lp & 0xffff) as i16 as i32, (lp >> 16 & 0xffff) as i16 as i32);+ match msg {+ WM_PAINT => paint(hw, k),+ WM_ERASEBKGND => return 1,+ WM_ACTIVATE if wp & 0xffff == 0 => {+ // A file drag that began elsewhere (desktop icon, folder window) deactivates this panel with the button still+ // down: keep Start open so the drop can land on it, and close once the button is up (timer 6).+ if k == Kind::Start && GetAsyncKeyState(VK_LBUTTON as i32) < 0 {+ SetTimer(hw, 6, 150, None);+ } else {+ close();+ }+ }+ WM_TIMER if wp == 6 => {+ if GetAsyncKeyState(VK_LBUTTON as i32) >= 0 {+ KillTimer(hw, 6);+ if GetForegroundWindow() != hw {+ close();+ }+ }+ }+ WM_DROPFILES => on_files(hw, wp as HDROP),+ WM_TIMER if wp == 2 => {+ InvalidateRect(hw, null(), 0);+ }+ WM_TIMER => {+ if k == Kind::Wifi && PASS.with_borrow(|p| p.is_none()) {+ read_nets();+ let (w, h) = (sc(size(k).0), sc(size(k).1));+ // the panel hangs above the bar: keep its bottom edge where it is and grow / shrink upward+ let (x, _) = FIN.get();+ let y = bar_top() - sc(8) - h;+ FIN.set((x, y));+ SetWindowPos(hw, null_mut(), x, y, w, h, SWP_NOZORDER | SWP_NOACTIVATE);+ SetWindowRgn(hw, CreateRoundRectRgn(0, 0, w + 1, h + 1, sc(16), sc(16)), 1);+ }+ InvalidateRect(hw, null(), 0);+ }+ WM_MOUSEMOVE => {+ if DRAG.get() != 0 {+ let want = if DRAG.get() == 1 { Act::VolSlide } else { Act::BrightSlide };+ if let Some((rc, a)) = rects(k).into_iter().find(|(_, a)| *a == want) {+ slide(a, x, rc);+ }+ }+ let o = act_at(k, x, y).map(|a| a.1);+ if OVER.replace(o) != o || DRAG.get() != 0 {+ InvalidateRect(hw, null(), 0);+ }+ }+ WM_LBUTTONDOWN => {+ if let Some((rc, a)) = act_at(k, x, y) {+ run_act(a, rc, x);+ }+ if FLY.get().is_some() {+ InvalidateRect(hw, null(), 0);+ }+ }+ WM_RBUTTONUP => {+ if let (Kind::Start, Some((_, Act::App(i)))) = (k, act_at(k, x, y)) {+ app_menu(hw, i, x, y);+ InvalidateRect(hw, null(), 0);+ }+ }+ WM_LBUTTONUP => {+ let d = DRAG.replace(0);+ if d != 0 {+ ReleaseCapture();+ if d == 2 {+ set_brightness(BRIGHT.load(Relaxed));+ }+ }+ }+ WM_MOUSEWHEEL => {+ let up = (wp >> 16) as i16 > 0;+ match k {+ Kind::Quick => add_volume(if up { 2 } else { -2 }),+ Kind::Start => SCROLL.set(if up { SCROLL.get().saturating_sub(2) } else { (SCROLL.get() + 2).min(filtered().len().saturating_sub(ROWS)) }),+ _ => {}+ }+ InvalidateRect(hw, null(), 0);+ }+ WM_KEYDOWN if k == Kind::Start && (wp == VK_DOWN as usize || wp == VK_UP as usize) => {+ // arrows move the row Enter opens; the list scrolls to keep it in view+ let n = filtered().len();+ if n > 0 {+ let s = if wp == VK_DOWN as usize { (SEL.get() + 1).min(n - 1) } else { SEL.get().saturating_sub(1) };+ SEL.set(s);+ SCROLL.set(SCROLL.get().min(s).max((s + 1).saturating_sub(ROWS)));+ InvalidateRect(hw, null(), 0);+ }+ }+ WM_CHAR => {+ let c = wp as u32;+ if c == 27 {+ if PASS.with_borrow(|p| p.is_some()) {+ PASS.set(None);+ } else if k == Kind::Start && QUERY.with_borrow(|q| !q.is_empty()) {+ QUERY.set(String::new()); // Esc clears the search first, the next one closes+ SCROLL.set(0);+ SEL.set(0);+ } else {+ close();+ return 0;+ }+ } else if k == Kind::Wifi && PASS.with_borrow(|p| p.is_some()) {+ if c == 13 {+ if let Some((i, p)) = PASS.take() {+ NETS.with_borrow(|n| wifi_join(&n[i], &p));+ }+ } else if let Some(p) = PASS.with_borrow_mut(|p| p.as_mut().map(|p| &mut p.1 as *mut String)) {+ let p = &mut *p;+ if c == 8 {+ p.pop();+ } else if let Some(ch) = char::from_u32(c).filter(|_| c >= 32) {+ p.push(ch);+ }+ }+ } else if k == Kind::Start {+ if c == 13 {+ if launch(SEL.get()) {+ close();+ return 0;+ }+ } else {+ QUERY.with_borrow_mut(|q| {+ if c == 8 {+ q.pop();+ } else if let Some(ch) = char::from_u32(c).filter(|_| c >= 32) {+ q.push(ch);+ }+ });+ SCROLL.set(0);+ SEL.set(0);+ }+ }+ InvalidateRect(hw, null(), 0);+ }+ _ => return DefWindowProcW(hw, msg, wp, lp),+ }+ 0+}++#[cfg(test)]+mod tests {+ use super::{flip_layout, score};++ #[test]+ fn layout_flip_both_ways() {+ assert_eq!(flip_layout("сркщьу"), "chrome");+ assert_eq!(flip_layout("ntktuhfv"), "телеграм");+ assert_eq!(flip_layout("vs code"), "мы сщву");+ }++ #[test]+ fn ranking() {+ assert_eq!(score("visual studio code", "vis"), Some(0));+ assert_eq!(score("visual studio code", "cod"), Some(1));+ assert_eq!(score("visual studio code", "vsc"), Some(2));+ assert_eq!(score("calculator", "cul"), Some(3));+ assert_eq!(score("calculator", "xyz"), None);+ assert_eq!(score("calculator", ""), None);+ assert_eq!(score("v", "v"), Some(0)); // one-letter initials do not count, the prefix does+ }+}diff --git a/plugins/topbar/src/main.rs b/plugins/topbar/src/main.rsnew file mode 100644index 0000000..111b47b--- /dev/null+++ b/plugins/topbar/src/main.rs@@ -0,0 +1,2262 @@+// topbar: replaces the Windows taskbar with a panel at the bottom of the screen (the name stayed from when it sat on top),+// drawn in the Windows 11 taskbar palette: Start, pinned apps and open windows in the center; tray apps, language, wifi,+// volume, battery and date/time on the right. `--restore` brings the normal taskbar back (used by uninstall).+#![windows_subsystem = "windows"]+#![allow(unsafe_op_in_unsafe_fn)]+use std::{+ cell::{Cell, RefCell},+ mem::{size_of, zeroed},+ os::windows::process::CommandExt,+ path::PathBuf,+ process::Command,+ ptr::{null, null_mut},+ thread,+ sync::Mutex,+ collections::HashMap,+ sync::atomic::{AtomicBool, AtomicIsize, Ordering::Relaxed},+};+mod fly;+use windows::{+ Win32::{+ Media::Audio::{Endpoints::IAudioEndpointVolume, IMMDeviceEnumerator, MMDeviceEnumerator, eConsole, eRender},+ System::Com::{CLSCTX_ALL, CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, CoCreateInstance, CoInitializeEx, IPersistFile, STGM},+ UI::Shell::{IShellLinkW, ShellLink},+ },+ core::{Interface, PCWSTR},+};+use windows_sys::Win32::{+ Foundation::*,+ Globalization::{GetDateFormatW, GetLocaleInfoW, GetTimeFormatW},+ Graphics::{+ Dwm::DwmGetWindowAttribute,+ Gdi::*,+ GdiPlus::{+ FillModeAlternate, GdipAddPathArc, GdipClosePathFigure, GdipCreateFromHDC, GdipCreatePath, GdipCreateSolidFill, GdipDeleteBrush, GdipDeleteGraphics, GdipDeletePath, GdipFillPath, GdipSetPixelOffsetMode,+ GdipSetSmoothingMode, GdiplusStartup, GdiplusStartupInput, GpBrush, GpGraphics, GpPath, GpSolidFill, PixelOffsetModeHalf, SmoothingModeAntiAlias,+ },+ },+ NetworkManagement::WiFi::*,+ System::{+ LibraryLoader::{GetModuleHandleW, GetProcAddress},+ Power::{GetSystemPowerStatus, SYSTEM_POWER_STATUS},+ SystemInformation::{GetLocalTime, GetTickCount64},+ Threading::{AttachThreadInput, GetCurrentThreadId, OpenProcess, QueryFullProcessImageNameW, TerminateProcess},+ },+ UI::{Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*},+};++const fn rgb(r: u8, g: u8, b: u8) -> u32 {+ r as u32 | (g as u32) << 8 | (b as u32) << 16+}+const BG: u32 = rgb(24, 30, 44);+const LINE: u32 = rgb(44, 52, 72);+const HOVER: u32 = rgb(40, 48, 68);+const ACTIVE: u32 = rgb(52, 61, 84);+const ACCENT: u32 = rgb(76, 194, 255); // Windows 11 blue+const GOOD: u32 = rgb(108, 203, 95);+const BAD: u32 = rgb(255, 99, 97);+const TEXT: u32 = rgb(255, 255, 255);+const DIM: u32 = rgb(150, 158, 175);+const CALLBACK: u32 = WM_APP + 1;+const WM_MOUSELEAVE: u32 = 0x02A3; // not exported under the enabled features+const NO_WINDOW: u32 = 0x0800_0000;+const BAR_H: i32 = 40;+// hit-test results. Buttons (Start, pins, windows) are >= 0 in left-to-right order; tray apps are TAPP + index.+const NONE: i32 = -1;+const SEARCH: i32 = -10;+const CLOCK: i32 = -4;+const LANG: i32 = -6;+const WIFI_I: i32 = -7;+const VOL_I: i32 = -8;+const BAT_I: i32 = -9;+const TAPP: i32 = -1000;+const SYS_GRP: i32 = -11; // hover key of the one pill around wifi + volume + battery (they open the same panel)+const WIN_START: u32 = WM_APP + 10; // posted by the keyboard hook: Win key pressed alone+const ALT_TAB: u32 = WM_APP + 11; // posted by the keyboard hook: Alt+Tab (wp 1 = Shift held: backwards)+const ALT_UP: u32 = WM_APP + 12; // posted by the keyboard hook: Alt released while switching (wp 1 = Esc: cancel)+static SWITCHING: AtomicBool = AtomicBool::new(false); // Alt+Tab switcher open (the hook thread reads it)+static FULLSCREEN: AtomicBool = AtomicBool::new(false);+static DESK_HIDE: AtomicBool = AtomicBool::new(false); // the desktop in front and the pointer away from the bar for 2 s+static WIN_ALONE: AtomicBool = AtomicBool::new(false);+static BAR: AtomicIsize = AtomicIsize::new(0); // the bar window, for the hook thread+const SNIP: u32 = WM_APP + 13; // posted by the keyboard hook: PrtSc / Win+Shift+S with no explorer to handle them+static EXPLORER_UP: AtomicBool = AtomicBool::new(true); // explorer's taskbar exists (it handles PrtSc itself then); refreshed by the bar++struct Pin {+ lnk: Vec<u16>,+ target: String, // lower-case exe path, "" if unknown+ icon: HICON,+}+struct Btn {+ pin: Option<usize>,+ wins: Vec<HWND>,+ icon: HICON, // the window's icon for unpinned buttons, looked up on refresh, not every animation frame+}++/// One notification-area icon, as an app registered it through Shell_NotifyIcon (we own the "Shell_TrayWnd" they talk to).+struct TIcon {+ hwnd: HWND, // the app's callback window+ uid: u32,+ guid: [u8; 16], // zero unless the app identifies the icon by GUID+ icon: HICON, // our own copy+ cb: u32, // uCallbackMessage+ ver: u32, // NIM_SETVERSION value; >= 4 means the NOTIFYICON_VERSION_4 message format+ hidden: bool,+ tip: String,+ key: String, // owner exe file name, lower-case: what the "keep on the bar" choice is stored under+}+const WM_COPYDATA: u32 = 0x4A;+#[repr(C)]+struct Cds {+ dw: usize,+ cb: u32,+ p: *const u8,+}+static USAGE: Mutex<Option<HashMap<String, u32>>> = Mutex::new(None); // launches per shortcut name, lower-case++fn appdata_file(name: &str) -> PathBuf {+ PathBuf::from(std::env::var_os("APPDATA").unwrap_or_default()).join(name)+}+fn uses(name: &str) -> u32 {+ USAGE+ .lock()+ .unwrap()+ .get_or_insert_with(|| std::fs::read_to_string(appdata_file("topbar-usage.txt")).unwrap_or_default().lines().filter_map(|l| l.rsplit_once('\t')).filter_map(|(k, n)| Some((k.to_string(), n.parse().ok()?))).collect())+ .get(name)+ .copied()+ .unwrap_or(0)+}+/// Counts one launch of the shortcut at `path` (by file name, so the same app pinned and in Start counts together).+fn bump(path: &str) {+ bump_name(&std::path::Path::new(path).file_stem().unwrap_or_default().to_string_lossy());+}+/// Counts one launch of the app called `name` (Start search ranks by it).+fn bump_name(name: &str) {+ let name = name.to_lowercase();+ uses(&name); // loads the file first+ let mut g = USAGE.lock().unwrap();+ let m = g.as_mut().unwrap();+ *m.entry(name).or_insert(0) += 1;+ let _ = std::fs::write(appdata_file("topbar-usage.txt"), m.iter().map(|(k, n)| format!("{k}\t{n}\n")).collect::<String>());+}+fn lnk_uses(lnk: &std::path::Path) -> u32 {+ uses(&lnk.file_stem().unwrap_or_default().to_string_lossy().to_lowercase())+}++thread_local! {+ static HOST: Cell<HWND> = const { Cell::new(null_mut()) };+ static TIPWND: Cell<HWND> = const { Cell::new(null_mut()) };+ static SWWND: Cell<HWND> = const { Cell::new(null_mut()) }; // the Alt+Tab switcher+ static SW: RefCell<(Vec<HWND>, usize)> = const { RefCell::new((Vec::new(), 0)) }; // its windows (z-order) and selection+ static TIP: RefCell<String> = const { RefCell::new(String::new()) };+ static PINS: RefCell<Vec<Pin>> = const { RefCell::new(Vec::new()) };+ static BTNS: RefCell<Vec<Btn>> = const { RefCell::new(Vec::new()) }; // [0] is always Start (pin None, no wins)+ static TAPPS: RefCell<Vec<TIcon>> = const { RefCell::new(Vec::new()) };+ static SHOWN: RefCell<Option<Vec<String>>> = const { RefCell::new(None) }; // tray icons kept on the bar (by exe); None = none: every tray icon lives in the chevron flyout+ static TRAYFLY: Cell<HWND> = const { Cell::new(null_mut()) };+ static FHOT: Cell<i32> = const { Cell::new(-1) };+ static HOT: Cell<i32> = const { Cell::new(NONE) };+ static ORDER: RefCell<Vec<HWND>> = const { RefCell::new(Vec::new()) }; // unpinned windows in the order their buttons were added+ static HV: RefCell<HashMap<i32, (f32, u64)>> = RefCell::new(HashMap::new()); // hover fade per element: (0..1, last update ms)+ static BUSY: Cell<bool> = const { Cell::new(false) }; // a fade is still running: the painter asks for another frame+ static BAR_P: Cell<f32> = const { Cell::new(0.0) }; // bar slide: 0 = off screen, 1 = in place+ static BAR_T: Cell<u64> = const { Cell::new(0) };+ static DESK_T: Cell<u64> = const { Cell::new(0) }; // last moment the bar had a reason to stay on the desktop+ static SCALE: Cell<f32> = const { Cell::new(1.0) };+ static OLD_STATE: Cell<usize> = const { Cell::new(ABS_ALWAYSONTOP as usize) };+ static BAT: Cell<(i32, bool)> = const { Cell::new((-1, false)) }; // (percent or -1 = no battery, on AC)+ static VOL: Cell<(i32, bool)> = const { Cell::new((-1, false)) }; // (percent or -1 = unknown, muted)+ static WIFI: Cell<i32> = const { Cell::new(-1) }; // signal quality 0..100, -1 = not on wifi+ static TICK: Cell<u32> = const { Cell::new(0) };+ static EP: RefCell<Option<IAudioEndpointVolume>> = const { RefCell::new(None) };+ static TB_MSG: Cell<u32> = const { Cell::new(0) }; // "TaskbarCreated"+ static SH_MSG: Cell<u32> = const { Cell::new(0) }; // "SHELLHOOK": window events for the shell (we are the shell hook window without explorer)+ static EXP_TRAY: Cell<HWND> = const { Cell::new(null_mut()) }; // explorer's taskbar we registered with+ static APP_FG: Cell<HWND> = const { Cell::new(null_mut()) }; // last foreground window that is not ours: the language button acts on it+ static LANG_TRY: Cell<(u32, usize)> = const { Cell::new((0, 0)) }; // (thread, layout before) of the last switch, checked by timer 7+}++fn wide(s: &str) -> Vec<u16> {+ s.encode_utf16().chain([0]).collect()+}+fn sc(v: i32) -> i32 {+ (v as f32 * SCALE.get()) as i32+}+fn bar_h() -> i32 {+ sc(BAR_H)+}+/// Screen y of the bar's top edge when it is in place (bottom of the primary monitor).+unsafe fn bar_top() -> i32 {+ GetSystemMetrics(SM_CYSCREEN) - bar_h()+}++// ---------- taskbar / appbar ----------++/// First top-level window of the class that is not our own tray host (explorer's real taskbar).+unsafe fn find_other(class: &str) -> HWND {+ let (c, mut h) = (wide(class), null_mut());+ loop {+ h = FindWindowExW(null_mut(), h, c.as_ptr(), null());+ if h.is_null() || h != HOST.get() {+ return h;+ }+ }+}++unsafe fn tray() -> [HWND; 2] {+ [find_other("Shell_TrayWnd"), find_other("Shell_SecondaryTrayWnd")]+}++/// Tells every app to re-register its tray icon with whichever Shell_TrayWnd is found first.+unsafe fn announce() {+ PostMessageW(HWND_BROADCAST, RegisterWindowMessageW(wide("TaskbarCreated").as_ptr()), 0, 0);+}++fn hide_onedrive() -> bool {+ // topbar.cfg sits next to the exe (the launcher writes it); no file or no line = OneDrive hidden+ std::env::current_exe().ok().and_then(|e| std::fs::read_to_string(e.with_file_name("topbar.cfg")).ok()).is_none_or(|c| !c.contains("hide_onedrive=0"))+}++/// WM_COPYDATA (dwData 1) from Shell_NotifyIcon: u32 magic, u32 NIM_*, then the platform-neutral NOTIFYICONDATA+/// (32-bit handles): hWnd@12 uID@16 uFlags@20 callback@24 hIcon@28 dwState@288 mask@292 version@808 guid@944.+unsafe fn tray_msg(d: &[u8]) {+ let u = |o: usize| u32::from_le_bytes(d[o..o + 4].try_into().unwrap());+ let (op, flags, uid) = (u(4), u(20), u(16));+ let h = u(12) as i32 as isize as HWND;+ let guid: [u8; 16] = if flags & 0x20 != 0 { d[944..960].try_into().unwrap() } else { [0; 16] };+ TAPPS.with_borrow_mut(|t| {+ let pos = t.iter().position(|x| x.hwnd == h && x.uid == uid && x.guid == guid);+ match (op, pos) {+ (2, Some(i)) => {+ DestroyIcon(t.remove(i).icon);+ }+ (4, Some(i)) => t[i].ver = u(808),+ (0 | 1, _) => {+ let i = match pos {+ Some(i) => i,+ None if op == 1 => return, // modify of an icon we never saw+ None => {+ let exe = exe_of(h);+ let n = exe.rsplit('\\').next().unwrap_or("");+ if n == "explorer.exe" || n == "topbar.exe" || (n == "onedrive.exe" && hide_onedrive()) {+ return; // the system's own icons are drawn by the bar itself+ }+ t.push(TIcon { hwnd: h, uid, guid, icon: null_mut(), cb: 0, ver: 0, hidden: false, tip: String::new(), key: n.to_string() });+ t.len() - 1+ }+ };+ let x = &mut t[i];+ if flags & 1 != 0 {+ x.cb = u(24);+ }+ if flags & 2 != 0 {+ let ic = CopyIcon(u(28) as i32 as isize as HICON);+ if !ic.is_null() {+ if !x.icon.is_null() {+ DestroyIcon(x.icon);+ }+ x.icon = ic;+ }+ }+ if flags & 4 != 0 {+ let w: Vec<u16> = d[32..288].chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).take_while(|&c| c != 0).collect();+ x.tip = String::from_utf16_lossy(&w);+ }+ if flags & 8 != 0 && u(292) & 1 != 0 {+ x.hidden = u(288) & 1 != 0; // NIS_HIDDEN+ }+ }+ _ => {}+ }+ });+}++unsafe extern "system" fn tray_proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {+ if msg == WM_COPYDATA {+ let c = &*(lp as *const Cds);+ if c.dw == 1 && c.cb >= 964 {+ tray_msg(std::slice::from_raw_parts(c.p, c.cb as usize));+ return 1;+ }+ // SHAppBarMessage (our own bar's work-area reservation, ABM_SETSTATE...) also goes to "Shell_TrayWnd": hand it to explorer's+ // with a timeout: a hung explorer must not freeze the bar+ let mut r = 0usize;+ SendMessageTimeoutW(find_other("Shell_TrayWnd"), msg, wp, lp, SMTO_ABORTIFHUNG, 2000, &mut r);+ return r as LRESULT;+ }+ DefWindowProcW(hwnd, msg, wp, lp)+}++/// Posts the same messages explorer would for a click on the icon; the app shows its own window or menu.+unsafe fn tray_click(t: (HWND, u32, u32, u32), left: bool) {+ let (hwnd, uid, cb, ver) = t;+ if cb == 0 {+ return;+ }+ let mut pid = 0u32;+ GetWindowThreadProcessId(hwnd, &mut pid);+ AllowSetForegroundWindow(pid); // so the app can bring its popup menu to the front+ let mut pt: POINT = zeroed();+ GetCursorPos(&mut pt);+ let post = |ev: u32| {+ if ver >= 4 {+ PostMessageW(hwnd, cb, ((pt.x as u32 & 0xffff) | (pt.y as u32) << 16) as usize, (ev | (uid & 0xffff) << 16) as isize);+ } else {+ PostMessageW(hwnd, cb, uid as usize, ev as isize);+ }+ };+ match (left, ver >= 4) {+ (true, true) => post(0x400), // NIN_SELECT+ (true, false) => [WM_LBUTTONDOWN, WM_LBUTTONUP].into_iter().for_each(post),+ (false, true) => post(WM_CONTEXTMENU),+ (false, false) => [WM_RBUTTONDOWN, WM_RBUTTONUP].into_iter().for_each(post),+ }+}++/// Indices into TAPPS of the icons kept on the bar; the rest live in the chevron flyout.+fn bar_idx() -> Vec<usize> {+ let shown = SHOWN.with_borrow(|s| s.clone());+ TAPPS.with_borrow(|t| t.iter().enumerate().filter(|(_, x)| !x.hidden && shown.as_ref().is_some_and(|s| s.contains(&x.key))).map(|(i, _)| i).collect())+}+/// Bar slots of the tray: the chevron plus the icons kept on the bar.+fn tray_count() -> usize {+ bar_idx().len() + 1+}++/// Indices into TAPPS of the icons only the flyout shows (everything not kept on the bar).+fn over_idx() -> Vec<usize> {+ let bar = bar_idx();+ TAPPS.with_borrow(|t| (0..t.len()).filter(|i| !t[*i].hidden && !bar.contains(i)).collect())+}++fn toggle_shown(key: &str) {+ let mut cur = SHOWN.with_borrow(|s| s.clone()).unwrap_or_else(|| TAPPS.with_borrow(|t| bar_idx().into_iter().map(|i| t[i].key.clone()).collect()));+ match cur.iter().position(|k| k == key) {+ Some(p) => drop(cur.remove(p)),+ None => cur.push(key.to_string()),+ }+ let _ = std::fs::write(appdata_file("topbar-tray.txt"), cur.join("\n"));+ SHOWN.set(Some(cur));+}++// ---------- tray overflow flyout (the chevron): every icon, click / right click work as in the real tray ----------++const FCELL: i32 = 38;++/// (columns, window width, window height) for the current number of icons.+fn fly_size() -> (usize, i32, i32) {+ let n = over_idx().len().max(1);+ let cols = n.min(6);+ (cols, sc(FCELL) * cols as i32 + sc(16), sc(FCELL) * n.div_ceil(cols) as i32 + sc(16) + sc(26))+}++unsafe fn fly_toggle() {+ let w = TRAYFLY.get();+ if IsWindowVisible(w) != 0 {+ ShowWindow(w, SW_HIDE);+ return;+ }+ let (_, fw, fh) = fly_size();+ FHOT.set(-1);+ let scr = GetSystemMetrics(SM_CXSCREEN);+ let cx = layout(scr).apps.0 + sc(12); // above the chevron+ SetWindowRgn(w, CreateRoundRectRgn(0, 0, fw + 1, fh + 1, sc(12), sc(12)), 1);+ SetWindowPos(w, HWND_TOPMOST, (cx - fw / 2).clamp(sc(8), scr - fw - sc(8)), bar_top() - fh - sc(8), fw, fh, SWP_SHOWWINDOW);+ SetForegroundWindow(w); // so that WM_ACTIVATE tells us when the user clicks elsewhere+}++unsafe extern "system" fn fly_proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {+ let cell_at = |lp: LPARAM| -> i32 {+ let (x, y) = ((lp & 0xffff) as i16 as i32 - sc(8), ((lp >> 16) & 0xffff) as i16 as i32 - sc(8));+ let (cols, _, _) = fly_size();+ let n = over_idx().len() as i32;+ if x < 0 || y < 0 || x >= sc(FCELL) * cols as i32 {+ return -1;+ }+ let i = (y / sc(FCELL)) * cols as i32 + x / sc(FCELL);+ if i < n { i } else { -1 }+ };+ match msg {+ WM_PAINT => {+ let mut ps: PAINTSTRUCT = zeroed();+ let dc = BeginPaint(hwnd, &mut ps);+ let mut r: RECT = zeroed();+ GetClientRect(hwnd, &mut r);+ fill(dc, r, LINE, sc(12));+ fill(dc, RECT { left: 1, top: 1, right: r.right - 1, bottom: r.bottom - 1 }, BG, sc(12));+ let (cols, _, _) = fly_size();+ let f = tip_font();+ let of = SelectObject(dc, f);+ SetBkMode(dc, TRANSPARENT as i32);+ SetTextColor(dc, DIM);+ let mut tip = String::new();+ let over = over_idx();+ TAPPS.with_borrow(|t| {+ for (n, ti) in over.iter().map(|&i| &t[i]).enumerate() {+ let (x, y) = (sc(8) + (n % cols) as i32 * sc(FCELL), sc(8) + (n / cols) as i32 * sc(FCELL));+ if FHOT.get() == n as i32 {+ fill(dc, RECT { left: x, top: y, right: x + sc(FCELL), bottom: y + sc(FCELL) }, HOVER, sc(6));+ tip = ti.tip.clone();+ }+ if !ti.icon.is_null() {+ DrawIconEx(dc, x + sc(9), y + sc(8), ti.icon, sc(20), sc(20), 0, null_mut(), DI_NORMAL);+ }+ }+ });+ if tip.is_empty() {+ tip = if over.is_empty() { "No more icons".into() } else { "Middle click: move to the bar".into() };+ }+ let mut tr = RECT { left: sc(10), top: r.bottom - sc(26), right: r.right - sc(10), bottom: r.bottom - sc(4) };+ DrawTextW(dc, wide(&tip).as_ptr(), -1, &mut tr, DT_LEFT | DT_NOPREFIX | DT_SINGLELINE | DT_END_ELLIPSIS | DT_VCENTER);+ SelectObject(dc, of);+ DeleteObject(f);+ EndPaint(hwnd, &ps);+ 0+ }+ WM_MOUSEMOVE => {+ let mut tme = TRACKMOUSEEVENT { cbSize: size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE, hwndTrack: hwnd, dwHoverTime: 0 };+ TrackMouseEvent(&mut tme);+ if FHOT.replace(cell_at(lp)) != cell_at(lp) {+ InvalidateRect(hwnd, null(), 0);+ }+ 0+ }+ WM_MOUSELEAVE => {+ FHOT.set(-1);+ InvalidateRect(hwnd, null(), 0);+ 0+ }+ WM_LBUTTONDOWN | WM_RBUTTONDOWN | WM_MBUTTONDOWN => {+ let i = cell_at(lp);+ let ti = over_idx().get(i.max(0) as usize).and_then(|&k| TAPPS.with_borrow(|t| t.get(k).map(|x| ((x.hwnd, x.uid, x.cb, x.ver), x.key.clone()))));+ if let (true, Some((t, key))) = (i >= 0, ti) {+ if msg == WM_MBUTTONDOWN {+ toggle_shown(&key);+ InvalidateRect(hwnd, null(), 0);+ } else {+ ShowWindow(hwnd, SW_HIDE);+ tray_click(t, msg == WM_LBUTTONDOWN);+ }+ }+ 0+ }+ WM_ACTIVATE if wp & 0xffff == 0 => {+ ShowWindow(hwnd, SW_HIDE);+ 0+ }+ _ => DefWindowProcW(hwnd, msg, wp, lp),+ }+}++// ---------- tray tooltip: a small popup under the icon after the mouse rests on it ----------++unsafe fn tip_font() -> HFONT {+ CreateFontW(-sc(12), 0, 0, 0, 400, 0, 0, 0, 1, 0, 0, 5, 0, wide("Segoe UI").as_ptr())+}++unsafe extern "system" fn tip_proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {+ if msg != WM_PAINT {+ return DefWindowProcW(hwnd, msg, wp, lp);+ }+ let mut ps: PAINTSTRUCT = zeroed();+ let dc = BeginPaint(hwnd, &mut ps);+ let mut r: RECT = zeroed();+ GetClientRect(hwnd, &mut r);+ fill(dc, r, LINE, sc(8));+ fill(dc, RECT { left: 1, top: 1, right: r.right - 1, bottom: r.bottom - 1 }, BG, sc(8));+ let f = tip_font();+ let of = SelectObject(dc, f);+ SetBkMode(dc, TRANSPARENT as i32);+ SetTextColor(dc, TEXT);+ let mut tr = RECT { left: sc(8), top: sc(5), right: r.right - sc(8), bottom: r.bottom - sc(5) };+ TIP.with_borrow(|s| DrawTextW(dc, wide(s).as_ptr(), -1, &mut tr, DT_LEFT | DT_NOPREFIX | DT_WORDBREAK));+ SelectObject(dc, of);+ DeleteObject(f);+ EndPaint(hwnd, &ps);+ 0+}++/// Tooltip text of a bar element ("" = none).+unsafe fn tip_text(h: i32) -> String {+ match h {+ SEARCH => "Search".into(),+ 0 => "Start".into(),+ TAPP => "Hidden icons".into(),+ CLOCK => {+ let mut t: SYSTEMTIME = zeroed();+ GetLocalTime(&mut t);+ let mut b = [0u16; 80];+ let n = GetDateFormatW(0x0400, 2, &t, null(), b.as_mut_ptr(), 80).max(1) as usize - 1; // DATE_LONGDATE+ String::from_utf16_lossy(&b[..n])+ }+ LANG => format!("{} · click to switch", lang_name()),+ WIFI_I => match WIFI.get() {+ q if q >= 0 => format!("Wi‑Fi · signal {q}%"),+ _ => "Network".into(),+ },+ VOL_I => vol_tip(),+ BAT_I => match BAT.get() {+ (p, ac) if p >= 0 => format!("Battery {p}%{}", if ac { " · plugged in" } else { "" }),+ _ => String::new(),+ },+ t if t > TAPP && t < TAPP + 100 => bar_idx().get((t - TAPP - 1) as usize).and_then(|&i| TAPPS.with_borrow(|t| t.get(i).map(|i| i.tip.clone()))).unwrap_or_default(),+ i if i >= 1 => {+ let (wins, lnk) = BTNS.with_borrow(|b| b.get(i as usize).map(|b| (b.wins.clone(), b.pin.and_then(|p| PINS.with_borrow(|p2| p2.get(p).map(|x| wstr_of(&x.lnk))))))).unwrap_or_default();+ let title = |w: HWND| {+ let mut b = [0u16; 256];+ let n = GetWindowTextW(w, b.as_mut_ptr(), 256).max(0) as usize;+ String::from_utf16_lossy(&b[..n])+ };+ match (wins.first(), lnk) {+ (Some(&w), _) if wins.len() > 1 => format!("{} (+{})", title(w), wins.len() - 1),+ (Some(&w), _) => title(w),+ (None, Some(l)) => std::path::Path::new(&l).file_stem().unwrap_or_default().to_string_lossy().into(),+ _ => String::new(),+ }+ }+ _ => String::new(),+ }+}++fn vol_tip() -> String {+ match VOL.get() {+ (v, false) if v >= 0 => format!("Volume {v}%"),+ (_, true) => "Muted".into(),+ _ => "Volume".into(),+ }+}++/// Shows `s` in a small rounded popup above the bar, centered on screen x `cx`.+unsafe fn show_tip(s: String, cx: i32) {+ let tw = TIPWND.get();+ if s.is_empty() || tw.is_null() {+ return;+ }+ let (dc, f) = (GetDC(tw), tip_font());+ let of = SelectObject(dc, f);+ let mut r = RECT { left: 0, top: 0, right: sc(280), bottom: 0 };+ DrawTextW(dc, wide(&s).as_ptr(), -1, &mut r, DT_CALCRECT | DT_NOPREFIX | DT_WORDBREAK);+ SelectObject(dc, of);+ DeleteObject(f);+ ReleaseDC(tw, dc);+ let (w, h) = (r.right + sc(16), r.bottom + sc(10));+ TIP.set(s);+ SetWindowRgn(tw, CreateRoundRectRgn(0, 0, w + 1, h + 1, sc(8), sc(8)), 1);+ let x = (cx - w / 2).clamp(sc(4), GetSystemMetrics(SM_CXSCREEN) - w - sc(4));+ SetWindowPos(tw, HWND_TOPMOST, x, bar_top() + bar_off() - h - sc(6), w, h, SWP_NOACTIVATE | SWP_SHOWWINDOW);+ InvalidateRect(tw, null(), 1);+}++// ---------- Alt+Tab switcher: the open windows' icons, most recently used first, the selected one's title below ----------++const SW_CELL: i32 = 76;+const SW_PAD: i32 = 14;+const SW_TITLE: i32 = 30;++unsafe fn alt_tab(back: bool) {+ let sw = SWWND.get();+ if IsWindowVisible(sw) == 0 {+ let mut v: Vec<HWND> = Vec::new();+ EnumWindows(Some(collect), &mut v as *mut _ as LPARAM); // z-order: the active window first, then the one before it+ let n = v.len();+ if n == 0 {+ return SWITCHING.store(false, Relaxed);+ }+ SW.set((v, if n == 1 { 0 } else if back { n - 1 } else { 1 }));+ let scr = GetSystemMetrics(SM_CXSCREEN);+ let w = (n as i32 * sc(SW_CELL)).min(scr - sc(80)) + 2 * sc(SW_PAD);+ let h = sc(SW_PAD) + sc(SW_CELL) + sc(SW_TITLE) + sc(SW_PAD) / 2;+ SetWindowRgn(sw, CreateRoundRectRgn(0, 0, w + 1, h + 1, sc(18), sc(18)), 1);+ SetWindowPos(sw, HWND_TOPMOST, (scr - w) / 2, (GetSystemMetrics(SM_CYSCREEN) - h) / 2, w, h, SWP_NOACTIVATE | SWP_SHOWWINDOW);+ } else {+ SW.with_borrow_mut(|(v, i)| *i = if back { (*i + v.len() - 1) % v.len() } else { (*i + 1) % v.len() });+ }+ InvalidateRect(sw, null(), 0);+}++/// Alt released: switch to the selected window (restored if minimized). Esc: just close.+unsafe fn alt_done(cancel: bool) {+ ShowWindow(SWWND.get(), SW_HIDE);+ let (v, i) = SW.take();+ if let Some(&w) = v.get(i).filter(|_| !cancel) {+ if IsIconic(w) != 0 {+ ShowWindow(w, SW_RESTORE);+ }+ force_fg(w);+ }+}++unsafe extern "system" fn sw_proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {+ if msg != WM_PAINT {+ return DefWindowProcW(hwnd, msg, wp, lp);+ }+ let mut ps: PAINTSTRUCT = zeroed();+ let dc = BeginPaint(hwnd, &mut ps);+ let mut r: RECT = zeroed();+ GetClientRect(hwnd, &mut r);+ let (mem, bmp) = (CreateCompatibleDC(dc), CreateCompatibleBitmap(dc, r.right, r.bottom));+ let ob = SelectObject(mem, bmp);+ fill(mem, r, LINE, sc(18));+ fill(mem, RECT { left: 1, top: 1, right: r.right - 1, bottom: r.bottom - 1 }, BG, sc(18));+ let pad = sc(SW_PAD);+ SW.with_borrow(|(v, sel)| {+ let cell = (r.right - 2 * pad) / v.len().max(1) as i32;+ let isz = sc(36).min(cell - sc(14)).max(sc(12));+ for (k, &w) in v.iter().enumerate() {+ let x = pad + k as i32 * cell;+ if k == *sel {+ let c = RECT { left: x + sc(3), top: pad, right: x + cell - sc(3), bottom: pad + sc(SW_CELL) - sc(6) };+ fill(mem, c, ACCENT, sc(12)); // accent ring around the selected window+ fill(mem, RECT { left: c.left + sc(2), top: c.top + sc(2), right: c.right - sc(2), bottom: c.bottom - sc(2) }, ACTIVE, sc(10));+ }+ let ic = icon_of(w);+ if !ic.is_null() {+ DrawIconEx(mem, x + (cell - isz) / 2, pad + (sc(SW_CELL) - sc(6) - isz) / 2, ic, isz, isz, 0, null_mut(), DI_NORMAL);+ }+ }+ if let Some(&w) = v.get(*sel) {+ let mut b = [0u16; 256];+ let n = GetWindowTextW(w, b.as_mut_ptr(), 256).max(0) as usize;+ let f = CreateFontW(-sc(14), 0, 0, 0, 600, 0, 0, 0, 1, 0, 0, 5, 0, wide("Segoe UI").as_ptr());+ let of = SelectObject(mem, f);+ SetBkMode(mem, TRANSPARENT as i32);+ text(mem, &String::from_utf16_lossy(&b[..n]), RECT { left: pad, top: pad + sc(SW_CELL) - sc(4), right: r.right - pad, bottom: pad + sc(SW_CELL) + sc(SW_TITLE) - sc(4) }, TEXT, DT_CENTER);+ SelectObject(mem, of);+ DeleteObject(f);+ }+ });+ BitBlt(dc, 0, 0, r.right, r.bottom, mem, 0, 0, SRCCOPY);+ SelectObject(mem, ob);+ DeleteObject(bmp);+ DeleteDC(mem);+ EndPaint(hwnd, &ps);+ 0+}++unsafe fn hide_tip(bar: HWND) {+ KillTimer(bar, 2);+ ShowWindow(TIPWND.get(), SW_HIDE);+}++unsafe fn set_state(hwnd: HWND, state: usize) {+ let mut ab: APPBARDATA = zeroed();+ ab.cbSize = size_of::<APPBARDATA>() as u32;+ ab.hWnd = hwnd;+ ab.lParam = state as isize;+ SHAppBarMessage(ABM_SETSTATE, &mut ab);+}++/// Hides the real taskbar and sets it to auto-hide so Windows gives its work-area strip back.+unsafe fn hide_taskbar() {+ set_state(tray()[0], ABS_AUTOHIDE as usize);+ for t in tray().into_iter().filter(|t| !t.is_null()) {+ ShowWindow(t, SW_HIDE);+ }+}++unsafe fn show_taskbar(state: usize) {+ set_state(tray()[0], state);+ for t in tray().into_iter().filter(|t| !t.is_null()) {+ ShowWindow(t, SW_SHOWNA);+ }+}++// explorer re-shows its taskbar on hover / restart; hide it again+unsafe fn hide_taskbar_if_shown() {+ if tray().into_iter().any(|t| !t.is_null() && IsWindowVisible(t) != 0) {+ hide_taskbar();+ }+}++/// Reserves the bottom strip of the primary monitor (maximized windows stay above it).+unsafe fn place(hwnd: HWND) {+ let (cx, cy) = (GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));+ let mut ab: APPBARDATA = zeroed();+ ab.cbSize = size_of::<APPBARDATA>() as u32;+ ab.hWnd = hwnd;+ ab.uEdge = ABE_BOTTOM;+ ab.rc = RECT { left: 0, top: cy - bar_h(), right: cx, bottom: cy };+ SHAppBarMessage(ABM_QUERYPOS, &mut ab);+ ab.rc.top = ab.rc.bottom - bar_h();+ SHAppBarMessage(ABM_SETPOS, &mut ab);+ // No explorer (rs-shell / rust-explorer): nobody handles appbars, so set the work area ourselves. Without it maximized+ // windows slide under the bar and, covering the whole monitor, count as "fullscreen" and hide the bar.+ if find_other("Shell_TrayWnd").is_null() {+ set_work_area(RECT { left: 0, top: 0, right: cx, bottom: ab.rc.top });+ }+ SetWindowPos(hwnd, HWND_TOPMOST, ab.rc.left, ab.rc.top + bar_off(), ab.rc.right - ab.rc.left, bar_h(), SWP_NOACTIVATE);+}++unsafe fn set_work_area(mut want: RECT) {+ let mut cur: RECT = zeroed();+ SystemParametersInfoW(SPI_GETWORKAREA, 0, &mut cur as *mut _ as *mut _, 0);+ if (cur.left, cur.top, cur.right, cur.bottom) != (want.left, want.top, want.right, want.bottom) {+ SystemParametersInfoW(SPI_SETWORKAREA, 0, &mut want as *mut _ as *mut _, SPIF_SENDCHANGE);+ }+}++// ---------- data: windows, pins, tray apps, volume, wifi, battery ----------++thread_local! {+ static EXE_CACHE: RefCell<HashMap<usize, (u32, String)>> = RefCell::new(HashMap::new()); // hwnd -> (pid, exe): refresh runs twice a second+}++unsafe fn exe_of(h: HWND) -> String {+ let mut pid = 0u32;+ GetWindowThreadProcessId(h, &mut pid);+ if let Some(e) = EXE_CACHE.with_borrow(|c| c.get(&(h as usize)).filter(|(p, e)| *p == pid && !e.is_empty()).map(|(_, e)| e.clone())) {+ return e;+ }+ let p = OpenProcess(0x1000, 0, pid); // PROCESS_QUERY_LIMITED_INFORMATION+ if p.is_null() {+ return String::new();+ }+ let (mut b, mut n) = ([0u16; 520], 520u32);+ let ok = QueryFullProcessImageNameW(p, 0, b.as_mut_ptr(), &mut n);+ CloseHandle(p);+ let exe = if ok == 0 { String::new() } else { String::from_utf16_lossy(&b[..n as usize]).to_lowercase() };+ EXE_CACHE.with_borrow_mut(|c| {+ if c.len() > 512 {+ c.clear(); // closed windows never leave on their own+ }+ c.insert(h as usize, (pid, exe.clone()));+ });+ exe+}++unsafe extern "system" fn collect(h: HWND, lp: LPARAM) -> i32 {+ let ex = GetWindowLongW(h, GWL_EXSTYLE) as u32;+ let mut cloaked = 0u32; // UWP windows that are suspended / on another desktop are visible but cloaked+ DwmGetWindowAttribute(h, 14, &mut cloaked as *mut _ as *mut _, 4);+ let mut cls = [0u16; 32];+ let n = GetClassNameW(h, cls.as_mut_ptr(), 32) as usize;+ let ours = String::from_utf16_lossy(&cls[..n]) == "topbar";+ if IsWindowVisible(h) != 0 && GetWindow(h, GW_OWNER).is_null() && cloaked == 0 && !ours && GetWindowTextLengthW(h) > 0 && (ex & WS_EX_TOOLWINDOW == 0 || ex & WS_EX_APPWINDOW != 0) {+ (*(lp as *mut Vec<HWND>)).push(h);+ }+ 1+}++/// "%windir%\explorer.exe" -> "C:\Windows\explorer.exe" (unknown variables stay as they are).+fn expand_env(s: &str) -> String {+ let parts: Vec<&str> = s.split('%').collect();+ let mut out = String::new();+ for (i, p) in parts.iter().enumerate() {+ match std::env::var(p) {+ // odd pieces sit between two '%': a variable name+ Ok(v) if i % 2 == 1 && i + 1 < parts.len() => out.push_str(&v),+ _ if i % 2 == 1 && i + 1 < parts.len() => out.push_str(&format!("%{p}%")),+ _ if i % 2 == 1 => out.push_str(&format!("%{p}")), // a lone '%' with nothing to close it+ _ => out.push_str(p),+ }+ }+ out+}++/// Target exe of a shortcut (lower-case), "" if it has none (e.g. Store apps).+unsafe fn lnk_target(lnk: &[u16]) -> String {+ (|| -> Option<String> {+ let sl: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER).ok()?;+ sl.cast::<IPersistFile>().ok()?.Load(PCWSTR(lnk.as_ptr()), STGM(0)).ok()?;+ let mut b = [0u16; 520];+ sl.GetPath(&mut b, null_mut(), 0).ok()?;+ let path = String::from_utf16_lossy(&b[..b.iter().position(|&c| c == 0)?]);+ if !path.is_empty() {+ return Some(path.to_lowercase());+ }+ // shell links without a file target (the File Explorer pin) usually take their icon from the app's exe:+ // "%windir%\explorer.exe,0" -> match the app's windows by that exe+ let mut idx = 0;+ sl.GetIconLocation(&mut b, &mut idx).ok()?;+ let icon = String::from_utf16_lossy(&b[..b.iter().position(|&c| c == 0)?]);+ let icon = expand_env(&icon).to_lowercase();+ icon.ends_with(".exe").then_some(icon)+ })()+ .unwrap_or_default()+}++/// The target's own icon: SHGetFileInfo on the .lnk adds the shortcut arrow, so that is only the fallback.+unsafe fn lnk_icon(lnk: &[u16], target: &str) -> HICON {+ let ic = item_icon(&wstr_of(lnk), icon_px());+ if !ic.is_null() {+ return ic;+ }+ let mut icon: HICON = null_mut();+ if !target.is_empty() {+ ExtractIconExW(wide(target).as_ptr(), 0, null_mut(), &mut icon, 1);+ }+ if icon.is_null() {+ let mut sfi: SHFILEINFOW = zeroed();+ SHGetFileInfoW(lnk.as_ptr(), 0, &mut sfi, size_of::<SHFILEINFOW>() as u32, SHGFI_ICON | SHGFI_SMALLICON);+ icon = sfi.hIcon;+ }+ icon+}++/// Size app icons are drawn at (24 logical px, like the Windows 11 taskbar). Icons are loaded at exactly this size:+/// a 32 px icon stretched by DrawIconEx comes out jagged.+fn icon_px() -> i32 {+ sc(24)+}++/// Icon of a file, shortcut (its target's icon, no arrow) or shell item ("shell:AppsFolder\<app id>") rendered by the+/// shell at exactly `px` pixels, the way Explorer gets its icons. Null if the shell has none.+unsafe fn item_icon(path: &str, px: i32) -> HICON {+ use windows::Win32::{+ Foundation::SIZE,+ UI::Shell::{IShellItem, IShellItemImageFactory, SHCreateItemFromParsingName, SIIGBF_ICONONLY},+ };+ let Ok(item) = SHCreateItemFromParsingName::<_, _, IShellItem>(PCWSTR(wide(path).as_ptr()), None) else { return null_mut() };+ let Ok(f) = item.cast::<IShellItemImageFactory>() else { return null_mut() };+ let Ok(bmp) = f.GetImage(SIZE { cx: px, cy: px }, SIIGBF_ICONONLY) else { return null_mut() };+ let color = bmp.0 as HBITMAP;+ let mask = CreateBitmap(px, px, 1, 1, null()); // ignored: the 32-bit colour bitmap carries the alpha+ let mut ii = ICONINFO { fIcon: 1, xHotspot: 0, yHotspot: 0, hbmMask: mask, hbmColor: color };+ let ic = CreateIconIndirect(&mut ii);+ DeleteObject(mask);+ DeleteObject(color);+ ic+}++thread_local! {+ static EXE_ICONS: RefCell<HashMap<String, HICON>> = RefCell::new(HashMap::new()); // crisp icons of running apps, by exe+}++/// Icon of a running window for its bar button: its exe's icon at the exact size (cached), else what the window reports.+/// Apps run by a generic host (Store apps in ApplicationFrameHost, Java games in javaw, scripts in python...) would all+/// get the host's icon: those keep the window's own icon.+unsafe fn win_icon(w: HWND) -> HICON {+ let exe = exe_of(w);+ const HOSTS: [&str; 8] = ["applicationframehost.exe", "javaw.exe", "java.exe", "pythonw.exe", "python.exe", "mmc.exe", "rundll32.exe", "dllhost.exe"];+ if exe.is_empty() || HOSTS.iter().any(|h| exe.rsplit('\\').next() == Some(*h)) {+ return icon_of(w);+ }+ let ic = EXE_ICONS.with_borrow_mut(|m| *m.entry(exe.clone()).or_insert_with(|| item_icon(&exe, icon_px())));+ if ic.is_null() { icon_of(w) } else { ic }+}++/// Pinned apps (the .lnk files Windows keeps for the taskbar) with their icons and target exe.+unsafe fn load_pins() {+ let Some(appdata) = std::env::var_os("APPDATA") else { return };+ let dir = PathBuf::from(appdata).join(r"Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar");+ let mut files: Vec<_> = std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case("lnk"))).collect();+ files.sort();+ files.sort_by_key(|f| std::cmp::Reverse(lnk_uses(f))); // most used first (stable: ties stay alphabetical)+ for f in files {+ let lnk = wide(&f.to_string_lossy());+ let target = lnk_target(&lnk);+ let icon = lnk_icon(&lnk, &target);+ PINS.with_borrow_mut(|p| p.push(Pin { lnk, target, icon }));+ }+}++fn refresh_buttons() {+ let mut wins: Vec<HWND> = Vec::new();+ unsafe { EnumWindows(Some(collect), &mut wins as *mut _ as LPARAM) };+ let mut btns = vec![Btn { pin: None, wins: vec![], icon: null_mut() }];+ PINS.with_borrow(|pins| btns.extend((0..pins.len()).map(|i| Btn { pin: Some(i), wins: vec![], icon: null_mut() })));+ let mut loose: Vec<HWND> = Vec::new();+ for w in wins {+ let exe = unsafe { exe_of(w) };+ let pin = PINS.with_borrow(|p| p.iter().position(|p| !p.target.is_empty() && p.target == exe));+ match pin {+ Some(i) => btns[1 + i].wins.push(w),+ None => loose.push(w),+ }+ }+ // EnumWindows lists by z-order, so clicking a window would jump its button to the front: keep the order they first appeared in+ ORDER.with_borrow_mut(|o| {+ o.retain(|w| loose.contains(w));+ o.extend(loose.iter().filter(|w| !o.contains(w)).copied().collect::<Vec<_>>());+ btns.extend(o.iter().map(|&w| Btn { pin: None, wins: vec![w], icon: unsafe { win_icon(w) } }));+ });+ BTNS.set(btns);+}++unsafe fn endpoint() -> Option<IAudioEndpointVolume> {+ EP.with_borrow_mut(|e| {+ if e.is_none() {+ *e = (|| -> windows::core::Result<IAudioEndpointVolume> {+ let en: IMMDeviceEnumerator = CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL)?;+ en.GetDefaultAudioEndpoint(eRender, eConsole)?.Activate(CLSCTX_ALL, None)+ })()+ .ok();+ }+ e.clone()+ })+}++unsafe fn read_volume() {+ let v = endpoint().and_then(|e| Some(((e.GetMasterVolumeLevelScalar().ok()? * 100.0).round() as i32, e.GetMute().ok()?.as_bool())));+ if v.is_none() {+ EP.set(None); // device changed: look the endpoint up again next time+ }+ VOL.set(v.unwrap_or((-1, false)));+}++unsafe fn set_volume(v: i32) {+ if let Some(e) = endpoint() {+ let _ = e.SetMasterVolumeLevelScalar(v.clamp(0, 100) as f32 / 100.0, null());+ let _ = e.SetMute(false, null());+ read_volume();+ }+}++unsafe fn add_volume(delta: i32) {+ if let Some(e) = endpoint() {+ let v = (VOL.get().0.max(0) + delta).clamp(0, 100);+ let _ = e.SetMasterVolumeLevelScalar(v as f32 / 100.0, null());+ let _ = e.SetMute(false, null());+ read_volume();+ }+}++unsafe fn toggle_mute() {+ if let Some(e) = endpoint() {+ let _ = e.SetMute(!VOL.get().1, null());+ read_volume();+ }+}++thread_local! {+ static WLAN: Cell<usize> = const { Cell::new(0) }; // WLAN client handle, opened once (opening it talks to wlansvc every time)+}++unsafe fn read_wifi() {+ let mut h: HANDLE = WLAN.get() as HANDLE;+ let mut q = -1;+ if h.is_null() {+ let mut ver = 0u32;+ if WlanOpenHandle(2, null(), &mut ver, &mut h) != 0 {+ h = null_mut();+ }+ WLAN.set(h as usize);+ }+ if !h.is_null() {+ let mut list: *mut WLAN_INTERFACE_INFO_LIST = null_mut();+ if WlanEnumInterfaces(h, null(), &mut list) != 0 {+ WlanCloseHandle(h, null()); // stale handle (service restarted): reopen next time+ WLAN.set(0);+ } else {+ let l = &*list;+ for i in 0..l.dwNumberOfItems as usize {+ let ifc = &*l.InterfaceInfo.as_ptr().add(i);+ let (mut size, mut data) = (0u32, null_mut());+ if ifc.isState == wlan_interface_state_connected && WlanQueryInterface(h, &ifc.InterfaceGuid, wlan_intf_opcode_current_connection, null(), &mut size, &mut data, null_mut()) == 0 {+ q = (*(data as *const WLAN_CONNECTION_ATTRIBUTES)).wlanAssociationAttributes.wlanSignalQuality as i32;+ WlanFreeMemory(data);+ }+ }+ WlanFreeMemory(list as *const _);+ }+ }+ WIFI.set(q);+}++/// A minimized window that Windows left as a caption stub on the desktop (it sits at the bottom left with its restore /+/// maximize / close buttons) goes off screen, as explorer's taskbar would have done. Restoring it is unaffected.+unsafe fn hide_stub(w: HWND) {+ let mut r: RECT = zeroed();+ if IsIconic(w) != 0 && GetWindowRect(w, &mut r) != 0 && r.left > -30000 {+ SetWindowPos(w, null_mut(), -32000, -32000, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);+ }+}++fn refresh() {+ refresh_buttons();+ BTNS.with_borrow(|b| b.iter().flat_map(|b| &b.wins).for_each(|&w| unsafe { hide_stub(w) }));+ let n = TICK.get();+ TICK.set(n + 1);+ unsafe {+ let mut p: SYSTEM_POWER_STATUS = zeroed();+ let ok = GetSystemPowerStatus(&mut p) != 0 && p.BatteryFlag & 128 == 0 && p.BatteryLifePercent <= 100;+ BAT.set(if ok { (p.BatteryLifePercent as i32, p.ACLineStatus == 1) } else { (-1, false) });+ read_volume();+ EXPLORER_UP.store(!find_other("Shell_TrayWnd").is_null(), Relaxed);+ if TAPPS.with_borrow(|t| t.is_empty()) && n % 8 == 4 {+ announce(); // no icons yet (apps started before us, or explorer restarted): ask them to register again+ }+ if n % 6 == 0 {+ read_wifi();+ }+ }+ unsafe {+ // icons of apps that died without NIM_DELETE+ TAPPS.with_borrow_mut(|t| {+ t.retain(|x| {+ let alive = IsWindow(x.hwnd) != 0;+ if !alive {+ DestroyIcon(x.icon);+ }+ alive+ })+ });+ // explorer re-raises its own Shell_TrayWnd now and then; ours must stay in front so apps keep finding it first+ SetWindowPos(HOST.get(), HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);+ }+}++// ---------- layout / hit-testing ----------++struct Layout {+ x0: i32, // first slot: the search button; Start and the rest follow+ bw: i32,+ gap: i32,+ apps: (i32, i32),+ sys: (i32, i32),+ clock: (i32, i32),+}++fn layout(w: i32) -> Layout {+ let gap = sc(4);+ let clock = (w - sc(96), w - sc(6));+ let sys = (clock.0 - sc(4) - sc(150 + if BAT.get().0 >= 0 { 66 } else { 0 }), clock.0 - sc(4));+ let apps = (sys.0 - sc(24) * tray_count() as i32, sys.0);+ let margin = (w - apps.0) + sc(8); // keep the button group centered and clear of both sides+ let n = BTNS.with_borrow(|b| b.len()) as i32 + 1; // + the search slot+ let bw = (((w - 2 * margin + gap) / n.max(1)) - gap).clamp(sc(16), sc(44));+ // centered on search + Start + pins only: opening an unpinned window adds a button on the right instead of shifting Start left+ let fixed = (PINS.with_borrow(|p| p.len()) as i32 + 2).min(n);+ // ...but never so far right that the windows' buttons run into the tray: then the whole row shifts left+ let right_limit = w - margin - (n * (bw + gap) - gap);+ Layout { x0: ((w - (fixed * (bw + gap) - gap)) / 2).min(right_limit).max(sc(8)), bw, gap, apps, sys, clock }+}++unsafe fn hit(hwnd: HWND, x: i32) -> i32 {+ let mut r: RECT = zeroed();+ GetClientRect(hwnd, &mut r);+ let l = layout(r.right);+ if x >= l.clock.0 {+ return CLOCK;+ }+ if x >= l.sys.0 {+ let d = x - l.sys.0;+ return if d < sc(42) { LANG } else if d < sc(74) { WIFI_I } else if d < sc(106) { VOL_I } else { BAT_I };+ }+ if x >= l.apps.0 {+ return TAPP + (x - l.apps.0) / sc(24);+ }+ let n = BTNS.with_borrow(|b| b.len()) as i32 + 1;+ let (d, i) = (x - l.x0, (x - l.x0) / (l.bw + l.gap));+ if d < 0 || d % (l.bw + l.gap) >= l.bw || i >= n { NONE } else if i == 0 { SEARCH } else { i - 1 }+}++// ---------- animation ----------++fn mix(a: u32, b: u32, t: f32) -> u32 {+ let ch = |s: u32| {+ let (x, y) = (((a >> s) & 255) as f32, ((b >> s) & 255) as f32);+ (x + (y - x) * t) as u32+ };+ ch(0) | ch(8) << 8 | ch(16) << 16+}++fn ease(t: f32) -> f32 {+ t * t * (3.0 - 2.0 * t)+}++unsafe fn now_ms() -> u64 {+ GetTickCount64()+}++/// Eased 0..1 hover value of one element: glides toward `on` (1) / off (0) instead of jumping. Sets BUSY while it moves,+/// the painter then schedules another frame.+unsafe fn hv(key: i32, on: bool) -> f32 {+ let now = now_ms();+ let target = if on { 1.0 } else { 0.0 };+ let v = HV.with_borrow_mut(|m| {+ let e = m.entry(key).or_insert((0.0, now));+ let dt = now.saturating_sub(e.1).min(50) as f32; // a long pause must not make the first frame jump+ e.1 = now;+ e.0 = if e.0 < target { (e.0 + dt / 130.0).min(target) } else { (e.0 - dt / 180.0).max(target) };+ e.0+ });+ if v != target {+ BUSY.set(true);+ }+ ease(v)+}++/// Rounded highlight that fades in and out; `from` is the colour it sits on. A click also flashes it in the accent colour.+unsafe fn glow(dc: HDC, key: i32, on: bool, r: RECT, from: u32, to: u32, rad: i32) {+ let t = hv(key, on);+ let p = press_t(key);+ if t > 0.01 || p > 0.0 {+ fill(dc, r, mix(mix(from, to, t), ACCENT, 0.5 * p), rad);+ }+}++thread_local! {+ static PRESS: Cell<(i32, u64)> = const { Cell::new((i32::MIN, 0)) }; // last clicked element and when+ static SEEN: RefCell<HashMap<isize, u64>> = RefCell::new(HashMap::new()); // when each taskbar button first showed+}++/// Marks `key` as just clicked / dropped on: its highlight flashes and its icon squeezes for a moment.+unsafe fn press(key: i32) {+ PRESS.set((key, now_ms()));+}++/// 1.0 right after the click, easing to 0 over 320 ms (keeps the painter running meanwhile).+unsafe fn press_t(key: i32) -> f32 {+ let (k, t0) = PRESS.get();+ let t = now_ms().saturating_sub(t0) as f32 / 320.0;+ if k != key || t >= 1.0 {+ return 0.0;+ }+ BUSY.set(true);+ (1.0 - t) * (1.0 - t)+}++/// 0..1 over 260 ms after a taskbar button first appears: new windows pop in instead of snapping into place.+unsafe fn appear(key: isize) -> f32 {+ let now = now_ms();+ let t0 = SEEN.with_borrow_mut(|m| {+ if m.len() > 512 {+ m.clear(); // shortcut: closed windows are never pruned one by one; a clear only replays the pop-in+ }+ *m.entry(key).or_insert(now)+ });+ let t = now.saturating_sub(t0) as f32 / 260.0;+ if t >= 1.0 {+ return 1.0;+ }+ BUSY.set(true);+ ease(t)+}++/// How far the bar sits below its place: it rises in at start and drops out of the way (and back) when a fullscreen+/// window takes the screen.+fn bar_off() -> i32 {+ ((1.0 - ease(BAR_P.get())) * bar_h() as f32) as i32+}++unsafe fn bar_anim(hwnd: HWND) {+ BAR_T.set(now_ms());+ SetTimer(hwnd, 5, 15, None);+}++unsafe fn bar_step(hwnd: HWND) {+ let target = if FULLSCREEN.load(Relaxed) || DESK_HIDE.load(Relaxed) { 0.0 } else { 1.0 };+ let now = now_ms();+ let dt = now.saturating_sub(BAR_T.replace(now)).min(50) as f32;+ let p = BAR_P.get();+ let p = if p < target { (p + dt / 380.0).min(target) } else { (p - dt / 240.0).max(target) };+ BAR_P.set(p);+ if p > 0.0 && IsWindowVisible(hwnd) == 0 {+ ShowWindow(hwnd, SW_SHOWNOACTIVATE);+ }+ SetWindowPos(hwnd, HWND_TOPMOST, 0, bar_top() + bar_off(), 0, 0, SWP_NOSIZE | SWP_NOACTIVATE);+ if p == target {+ KillTimer(hwnd, 5);+ if p == 0.0 {+ ShowWindow(hwnd, SW_HIDE); // not just moved away: a hidden bar cannot cover a game+ }+ }+}++/// True when the foreground window covers the whole primary monitor (game, F11 video, presentation).+/// A maximized window does not: the bar's reserved strip keeps it below the bar.+unsafe fn fullscreen_now(bar: HWND) -> bool {+ let fg = GetForegroundWindow();+ if fg.is_null() || fg == bar || IsWindowVisible(fg) == 0 || IsIconic(fg) != 0 {+ return false;+ }+ let mut cls = [0u16; 64];+ let n = GetClassNameW(fg, cls.as_mut_ptr(), 64).max(0) as usize;+ if matches!(String::from_utf16_lossy(&cls[..n]).as_str(), "Progman" | "WorkerW" | "Shell_TrayWnd" | "Shell_SecondaryTrayWnd" | "RustExplorer") {+ return false; // the desktop itself is full size (rs-shell's desktop is a rust-explorer window; a file manager is never "fullscreen")+ }+ let mut r: RECT = zeroed();+ GetWindowRect(fg, &mut r);+ let mut mi: MONITORINFO = zeroed();+ mi.cbSize = size_of::<MONITORINFO>() as u32;+ GetMonitorInfoW(MonitorFromWindow(fg, MONITOR_DEFAULTTONEAREST), &mut mi);+ let m = mi.rcMonitor;+ (m.left, m.top) == (0, 0) && r.left <= m.left && r.top <= m.top && r.right >= m.right && r.bottom >= m.bottom+}++/// True when no app window is on screen (none open, or all minimized: Win+D): the user is looking at the desktop.+unsafe fn desktop_now() -> bool {+ BTNS.with_borrow(|b| b.iter().flat_map(|b| &b.wins).all(|&w| IsIconic(w) != 0))+}++unsafe fn fs_update(hwnd: HWND) {+ let fs = fullscreen_now(hwnd);+ // a fullscreen game keeps the screen: the pointer at the bottom edge does not bring the bar (games park it at the+ // edges all the time); Win opens Start, which brings the bar with it+ let mut pt = POINT { x: 0, y: 0 };+ GetCursorPos(&mut pt);+ // desktop in front: the bar leaves 2 s after the pointer does and comes back at the bottom edge (an open flyout keeps it)+ let now = now_ms();+ let sh = GetSystemMetrics(SM_CYSCREEN);+ let over = pt.y >= sh - 1 || (pt.y >= sh - bar_h() && BAR_P.get() > 0.0);+ if fs || !desktop_now() || fly::any_open() || over {+ DESK_T.set(now);+ }+ let desk = !fs && now.saturating_sub(DESK_T.get()) >= 2000;+ if DESK_HIDE.swap(desk, Relaxed) != desk {+ bar_anim(hwnd);+ }+ if FULLSCREEN.swap(fs, Relaxed) != fs {+ if fs {+ fly::close_now();+ hide_tip(hwnd);+ }+ bar_anim(hwnd);+ }+}++/// SetForegroundWindow that also works when the request comes from a keyboard hook (we have not "received input" then):+/// attaching to the foreground thread's input queue lifts the restriction for the moment.+unsafe fn force_fg(hw: HWND) {+ // a mouse click on the bar gives us the right to take the foreground: attaching to another thread's input queue while its+ // button is still down hands the activation back to that window on button-up, and the just-opened flyout closed at once+ if SetForegroundWindow(hw) != 0 && GetForegroundWindow() == hw {+ SetFocus(hw);+ return;+ }+ let me = GetCurrentThreadId();+ let ft = GetWindowThreadProcessId(GetForegroundWindow(), null_mut());+ let attach = ft != 0 && ft != me && AttachThreadInput(me, ft, 1) != 0;+ SetForegroundWindow(hw);+ if attach {+ AttachThreadInput(me, ft, 0);+ }+ SetFocus(hw); // detaching drops our thread's keyboard focus; without it the Start search box gets no typing+}++/// Win key on its own opens our Start. Runs on its own thread so a busy bar can never stall the system keyboard.+unsafe extern "system" fn kb_hook(n: i32, w: WPARAM, l: LPARAM) -> LRESULT {+ if n >= 0 {+ let k = &*(l as *const KBDLLHOOKSTRUCT);+ if k.flags & LLKHF_INJECTED == 0 {+ // without explorer nobody opens the screen capture: PrtSc (when Windows is set to snip with it; otherwise it+ // copies the screen by itself) and Win+Shift+S do it here+ if !EXPLORER_UP.load(Relaxed) {+ let held = |vk: u16| GetAsyncKeyState(vk as i32) < 0;+ let down = w == WM_KEYDOWN as usize || w == WM_SYSKEYDOWN as usize;+ let snip_key = k.vkCode == VK_SNAPSHOT as u32;+ let win_shift_s = k.vkCode == b'S' as u32 && down && (held(VK_LWIN) || held(VK_RWIN)) && held(VK_SHIFT);+ if snip_key || win_shift_s {+ if down {+ WIN_ALONE.store(false, Relaxed);+ PostMessageW(BAR.load(Relaxed) as HWND, SNIP, snip_key as usize, 0); // wp 1: PrtSc, 0: Win+Shift+S+ }+ return 1;+ }+ }+ let down = w == WM_KEYDOWN as usize || w == WM_SYSKEYDOWN as usize;+ let bar = BAR.load(Relaxed) as HWND;+ // Alt+Tab: our own switcher. Without explorer Windows only flips to the next window blindly, and a fullscreen+ // game often takes the focus straight back.+ if k.vkCode == VK_TAB as u32 && k.flags & LLKHF_ALTDOWN != 0 && GetAsyncKeyState(VK_CONTROL as i32) >= 0 {+ if down {+ SWITCHING.store(true, Relaxed);+ PostMessageW(bar, ALT_TAB, (GetAsyncKeyState(VK_SHIFT as i32) < 0) as usize, 0);+ }+ return 1;+ }+ if SWITCHING.load(Relaxed) {+ if k.vkCode == VK_ESCAPE as u32 && down {+ SWITCHING.store(false, Relaxed);+ PostMessageW(bar, ALT_UP, 1, 0);+ return 1;+ }+ if matches!(k.vkCode as u16, VK_LMENU | VK_RMENU | VK_MENU) && !down {+ SWITCHING.store(false, Relaxed);+ keys(&[0xE8]); // the target app must not take the lone Alt release as "open the menu bar"+ PostMessageW(bar, ALT_UP, 0, 0);+ }+ }+ if k.vkCode == VK_LWIN as u32 || k.vkCode == VK_RWIN as u32 {+ if down {+ WIN_ALONE.store(true, Relaxed);+ } else if WIN_ALONE.swap(false, Relaxed) {+ keys(&[0xE8]); // an unassigned key between press and release: Windows no longer opens its own Start+ PostMessageW(BAR.load(Relaxed) as HWND, WIN_START, 0, 0);+ }+ } else if down {+ WIN_ALONE.store(false, Relaxed); // Win+something else: a shortcut, not a Start press+ }+ }+ }+ CallNextHookEx(null_mut(), n, w, l)+}++// ---------- drawing ----------++/// Fills `r` (right / bottom exclusive) in colour `c`; `rad` > 0 rounds the corners (rad = corner diameter), anti-aliased+/// through GDI+. Plain GDI for square boxes and when GDI+ is not available.+unsafe fn fill(dc: HDC, r: RECT, c: u32, rad: i32) {+ let (w, h) = ((r.right - r.left) as f32, (r.bottom - r.top) as f32);+ if w <= 0.0 || h <= 0.0 {+ return;+ }+ let mut g: *mut GpGraphics = null_mut();+ if rad <= 0 || GdipCreateFromHDC(dc, &mut g) != 0 || g.is_null() {+ let b = CreateSolidBrush(c);+ if rad <= 0 {+ FillRect(dc, &r, b);+ } else {+ let (ob, op) = (SelectObject(dc, b), SelectObject(dc, GetStockObject(NULL_PEN)));+ RoundRect(dc, r.left, r.top, r.right + 1, r.bottom + 1, rad, rad);+ SelectObject(dc, ob);+ SelectObject(dc, op);+ }+ DeleteObject(b);+ return;+ }+ GdipSetSmoothingMode(g, SmoothingModeAntiAlias);+ GdipSetPixelOffsetMode(g, PixelOffsetModeHalf); // pixel i spans [i, i+1): straight edges stay crisp+ let (x, y, d) = (r.left as f32, r.top as f32, (rad as f32).min(w).min(h));+ let mut path: *mut GpPath = null_mut();+ GdipCreatePath(FillModeAlternate, &mut path);+ GdipAddPathArc(path, x, y, d, d, 180.0, 90.0);+ GdipAddPathArc(path, x + w - d, y, d, d, 270.0, 90.0);+ GdipAddPathArc(path, x + w - d, y + h - d, d, d, 0.0, 90.0);+ GdipAddPathArc(path, x, y + h - d, d, d, 90.0, 90.0);+ GdipClosePathFigure(path);+ let mut br: *mut GpSolidFill = null_mut();+ GdipCreateSolidFill(0xFF00_0000 | (c & 255) << 16 | (c & 0xFF00) | (c >> 16 & 255), &mut br); // COLORREF -> ARGB+ GdipFillPath(g, br as *mut GpBrush, path);+ GdipDeleteBrush(br as *mut GpBrush);+ GdipDeletePath(path);+ GdipDeleteGraphics(g);+}++unsafe fn text(dc: HDC, s: &str, mut r: RECT, c: u32, flags: u32) {+ SetTextColor(dc, c);+ let w = wide(s);+ DrawTextW(dc, w.as_ptr(), -1, &mut r, flags | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS);+}++unsafe fn icon_of(h: HWND) -> HICON {+ for which in [1usize, 2] {+ // ICON_BIG, ICON_SMALL2+ let mut r = 0usize;+ SendMessageTimeoutW(h, WM_GETICON, which, 0, SMTO_ABORTIFHUNG, 40, &mut r);+ if r != 0 {+ return r as HICON;+ }+ }+ let c = GetClassLongPtrW(h, GCLP_HICON);+ (if c != 0 { c } else { GetClassLongPtrW(h, GCLP_HICONSM) }) as HICON+}++/// The app window the user is typing in: the foreground window, or, while our own bar / panel / menu holds the+/// foreground (after a right click, a closed Start...), the last app window that had it.+unsafe fn app_window() -> HWND {+ let fg = GetForegroundWindow();+ let mut pid = 0u32;+ GetWindowThreadProcessId(fg, &mut pid);+ if !fg.is_null() && pid != std::process::id() {+ APP_FG.set(fg);+ return fg;+ }+ let last = APP_FG.get();+ if IsWindow(last) != 0 { last } else { fg }+}++/// PrtSc without explorer: the whole desktop (all monitors) to the clipboard and to Pictures\Screenshots\<date time>.png.+/// The system's own capture overlay (ms-screenclip:) does not come up without explorer as the shell. Returns the file name.+/// `topbar --shot` does the same from a command line.+unsafe fn screenshot() -> Option<String> {+ use windows_sys::Win32::{+ Graphics::GdiPlus::{GdipCreateBitmapFromHBITMAP, GdipDisposeImage, GdipSaveImageToFile, GpBitmap, GpImage},+ System::DataExchange::{CloseClipboard, EmptyClipboard, OpenClipboard, SetClipboardData},+ };+ let (x, y, w, h) = (GetSystemMetrics(76), GetSystemMetrics(77), GetSystemMetrics(78), GetSystemMetrics(79)); // virtual screen+ if w <= 0 || h <= 0 {+ return None;+ }+ let (scr, mem) = (GetDC(null_mut()), CreateCompatibleDC(GetDC(null_mut())));+ let bmp = CreateCompatibleBitmap(scr, w, h);+ let old = SelectObject(mem, bmp);+ BitBlt(mem, 0, 0, w, h, scr, x, y, SRCCOPY | 0x4000_0000); // CAPTUREBLT: layered windows (the wallpaper, overlays) too+ SelectObject(mem, old);+ DeleteDC(mem);+ ReleaseDC(null_mut(), scr);+ let mut t: SYSTEMTIME = zeroed();+ GetLocalTime(&mut t);+ let name = format!("Screenshot {:04}-{:02}-{:02} {:02}-{:02}-{:02}.png", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond);+ let dir = PathBuf::from(std::env::var_os("USERPROFILE").unwrap_or_default()).join(r"Pictures\Screenshots");+ let _ = std::fs::create_dir_all(&dir);+ let mut gb: *mut GpBitmap = null_mut();+ let mut saved = false;+ if GdipCreateBitmapFromHBITMAP(bmp, null_mut(), &mut gb) == 0 && !gb.is_null() {+ let png = windows_sys::core::GUID { data1: 0x557c_f406, data2: 0x1a04, data3: 0x11d3, data4: [0x9a, 0x73, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e] }; // PNG encoder+ saved = GdipSaveImageToFile(gb as *mut GpImage, wide(&dir.join(&name).to_string_lossy()).as_ptr(), &png, null()) == 0;+ GdipDisposeImage(gb as *mut GpImage);+ }+ let mut clip = false;+ if OpenClipboard(null_mut()) != 0 {+ EmptyClipboard();+ clip = !SetClipboardData(2, bmp as _).is_null(); // CF_BITMAP: the clipboard owns the bitmap from here on+ CloseClipboard();+ }+ if !clip {+ DeleteObject(bmp);+ }+ (saved || clip).then_some(name)+}++/// PrtSc pressed: take the screenshot, then say so above the bar for a moment.+unsafe fn screenshot_notice(bar: HWND) {+ let msg = match screenshot() {+ Some(n) => format!("Скриншот сохранён: {n}\nи скопирован в буфер обмена"),+ None => "Не удалось сделать скриншот".to_string(),+ };+ KillTimer(bar, 2);+ show_tip(msg, GetSystemMetrics(SM_CXSCREEN) / 2);+ SetTimer(bar, 6, 2500, None); // timer 6 hides the tip+}++/// Next keyboard layout for the app window. Posted to its focused control (that is where Chrome, Office... look for it);+/// timer 7 checks it took and otherwise presses Win+Space, the system switcher (games, terminals ignore the message).+unsafe fn next_lang(bar: HWND) {+ let w = app_window();+ let tid = GetWindowThreadProcessId(w, null_mut());+ let mut l: [HKL; 32] = [null_mut(); 32];+ let n = GetKeyboardLayoutList(32, l.as_mut_ptr()).clamp(0, 32) as usize;+ let cur = GetKeyboardLayout(tid);+ if n < 2 {+ return; // one layout: nothing to switch to+ }+ let next = l[(l[..n].iter().position(|&k| k == cur).map_or(0, |i| i + 1)) % n];+ let mut gi: GUITHREADINFO = zeroed();+ gi.cbSize = size_of::<GUITHREADINFO>() as u32;+ let target = if GetGUIThreadInfo(tid, &mut gi) != 0 && !gi.hwndFocus.is_null() { gi.hwndFocus } else { w };+ PostMessageW(target, WM_INPUTLANGCHANGEREQUEST, 0, next as isize);+ LANG_TRY.set((tid, cur as usize));+ SetTimer(bar, 7, 250, None);+}++unsafe fn lang_name() -> String {+ let tid = GetWindowThreadProcessId(app_window(), null_mut());+ let id = GetKeyboardLayout(tid) as usize as u32 & 0xffff;+ let mut b = [0u16; 16];+ let n = GetLocaleInfoW(id, 3, b.as_mut_ptr(), 16).max(1) as usize - 1; // LOCALE_SABBREVLANGNAME+ let s = String::from_utf16_lossy(&b[..n]).to_uppercase();+ if s == "ENU" { "ENG".into() } else { s }+}++thread_local! {+ static SIG: Cell<(u64, u32)> = const { Cell::new((0, 0)) }; // (hash of the last painted state, ticks since the last repaint)+}++/// Hash of everything the bar paints from polled state.+unsafe fn view_sig() -> u64 {+ use std::hash::{Hash, Hasher};+ let mut h = std::collections::hash_map::DefaultHasher::new();+ BTNS.with_borrow(|b| b.iter().for_each(|b| (b.pin, b.icon as usize, b.wins.iter().map(|&w| (w as usize, IsIconic(w))).collect::<Vec<_>>()).hash(&mut h)));+ (GetForegroundWindow() as usize, BAT.get(), VOL.get(), WIFI.get(), EXPLORER_UP.load(Relaxed), clock_texts(), lang_name()).hash(&mut h);+ TAPPS.with_borrow(|t| t.iter().for_each(|x| (x.hwnd as usize, x.uid, x.icon as usize, x.hidden, &x.tip).hash(&mut h)));+ h.finish()+}++unsafe fn clock_texts() -> (String, String) {+ let mut t: SYSTEMTIME = zeroed();+ GetLocalTime(&mut t);+ let (mut a, mut b) = ([0u16; 40], [0u16; 40]);+ let n = GetTimeFormatW(0x0400, 2, &t, null(), a.as_mut_ptr(), 40).max(1) as usize - 1; // LOCALE_USER_DEFAULT, TIME_NOSECONDS+ let m = GetDateFormatW(0x0400, 1, &t, null(), b.as_mut_ptr(), 40).max(1) as usize - 1; // DATE_SHORTDATE+ (String::from_utf16_lossy(&a[..n]), String::from_utf16_lossy(&b[..m]))+}++unsafe fn paint(hwnd: HWND) {+ let mut ps: PAINTSTRUCT = zeroed();+ let wdc = BeginPaint(hwnd, &mut ps);+ let mut cr: RECT = zeroed();+ GetClientRect(hwnd, &mut cr);+ let h = cr.bottom;+ BUSY.set(false);+ let (dc, bmp) = (CreateCompatibleDC(wdc), CreateCompatibleBitmap(wdc, cr.right, h));+ let old = SelectObject(dc, bmp);+ // frosted-glass look: a hairline on top, a faint light catch under it, then the panel colour fading in+ let lit = mix(BG, TEXT, 0.045);+ for y in 0..h {+ fill(dc, RECT { left: 0, top: y, right: cr.right, bottom: y + 1 }, mix(lit, BG, (y as f32 / sc(18) as f32).min(1.0)), 0);+ }+ fill(dc, RECT { left: 0, top: 0, right: cr.right, bottom: 1 }, LINE, 0);+ fill(dc, RECT { left: 0, top: 1, right: cr.right, bottom: 2 }, mix(BG, TEXT, 0.08), 0);+ SetBkMode(dc, TRANSPARENT as i32);+ let (face, gface) = (wide("Segoe UI"), wide("Segoe MDL2 Assets"));+ let font = |f: &[u16], px: i32, wt: i32| CreateFontW(-sc(px), 0, 0, 0, wt, 0, 0, 0, 1, 0, 0, 5, 0, f.as_ptr());+ let (f_txt, f_small, f_glyph, f_bold) = (font(&face, 13, 400), font(&face, 12, 400), font(&gface, 16, 400), font(&face, 13, 600));+ let of = SelectObject(dc, f_txt);++ let l = layout(cr.right);+ let fg = GetForegroundWindow();+ let (top, bot) = (sc(4), h - sc(4));+ let mid = (top + bot) / 2;+ let cell = |x: i32, w: i32| RECT { left: x, top, right: x + w, bottom: bot };+ let hot = HOT.get();+ let active_bg = mix(ACTIVE, ACCENT, 0.12); // the focused app's button: a hint of the accent, not plain grey++ // search button (left of Start)+ let sb = RECT { left: l.x0, top, right: l.x0 + l.bw, bottom: bot };+ glow(dc, SEARCH, hot == SEARCH, sb, BG, HOVER, sc(8));+ SelectObject(dc, f_glyph);+ text(dc, "\u{E721}", sb, if hot == SEARCH { TEXT } else { mix(DIM, TEXT, 0.5) }, DT_CENTER);++ // Start, pinned apps, open windows (center)+ BTNS.with_borrow(|btns| {+ for (i, b) in btns.iter().enumerate() {+ let x = l.x0 + (i as i32 + 1) * (l.bw + l.gap);+ let r = RECT { left: x, top, right: x + l.bw, bottom: bot };+ let act = b.wins.contains(&fg);+ let (th, ta, tp) = (hv(i as i32, hot == i as i32), hv(2000 + i as i32, act), press_t(i as i32));+ if th > 0.01 || ta > 0.01 || tp > 0.0 {+ fill(dc, r, mix(mix(mix(BG, HOVER, th), active_bg, ta), ACCENT, 0.5 * tp), sc(8));+ }+ if i == 0 {+ // Windows logo in four tiles, lit from the top left; grows a little on hover, squeezes on click+ let t = ((sc(8) as f32) * (1.0 + 0.12 * th) * (1.0 - 0.2 * tp)) as i32;+ let (g, cx) = (sc(1).max(1), (r.left + r.right) / 2);+ let tint = [mix(ACCENT, TEXT, 0.35), mix(ACCENT, TEXT, 0.15), mix(ACCENT, TEXT, 0.15), ACCENT];+ for (k, (dx, dy)) in [(-1, -1), (0, -1), (-1, 0), (0, 0)].into_iter().enumerate() {+ let (px, py) = (cx + if dx < 0 { -t - g } else { g }, mid + if dy < 0 { -t - g } else { g });+ fill(dc, RECT { left: px, top: py, right: px + t, bottom: py + t }, tint[k], sc(3));+ }+ continue;+ }+ let ic = match b.pin {+ Some(p) => PINS.with_borrow(|pins| pins.get(p).map_or(null_mut(), |p| p.icon)),+ None => b.icon,+ };+ let key = b.pin.map(|p| -(p as isize) - 1).or_else(|| b.wins.first().map(|&w| w as isize)).unwrap_or(0);+ // squeezes on click, grows in when new, lifts a pixel on hover+ let isz = (icon_px().min(l.bw - sc(6)) as f32 * (1.0 - 0.18 * tp) * (0.55 + 0.45 * appear(key))) as i32;+ if !ic.is_null() {+ DrawIconEx(dc, x + (l.bw - isz) / 2, mid - isz / 2 - sc(2) - (sc(1) as f32 * th) as i32, ic, isz, isz, 0, null_mut(), DI_NORMAL);+ }+ if !b.wins.is_empty() {+ let min = b.wins.iter().all(|&w| IsIconic(w) != 0);+ let pw = sc(6) + (sc(12) as f32 * ta) as i32; // the running-app pill stretches when its window is active+ let py = bot - sc(4);+ let col = if act { ACCENT } else if min { mix(DIM, BG, 0.45) } else { DIM };+ fill(dc, RECT { left: x + (l.bw - pw) / 2, top: py, right: x + (l.bw + pw) / 2, bottom: py + sc(3) }, col, sc(3));+ if b.wins.len() > 1 {+ // a second, shorter pill: more than one window behind this button+ fill(dc, RECT { left: x + (l.bw + pw) / 2 + sc(2), top: py, right: x + (l.bw + pw) / 2 + sc(5), bottom: py + sc(3) }, col, sc(3));+ }+ }+ }+ });++ // a hairline between the app buttons and the tray side+ fill(dc, RECT { left: l.apps.0 - sc(5), top: mid - sc(9), right: l.apps.0 - sc(5) + 1, bottom: mid + sc(9) }, LINE, 0);++ // tray apps+ glow(dc, TAPP, hot == TAPP, cell(l.apps.0, sc(24)), BG, HOVER, sc(8));+ SelectObject(dc, f_glyph);+ text(dc, "\u{E70E}", cell(l.apps.0, sc(24)), if IsWindowVisible(TRAYFLY.get()) != 0 { ACCENT } else { TEXT }, DT_CENTER); // chevron up: the flyout above+ SelectObject(dc, f_txt);+ let bar = bar_idx();+ TAPPS.with_borrow(|t| {+ for (k, &ix) in bar.iter().enumerate() {+ let (i, ti) = (k + 1, &t[ix]);+ let x = l.apps.0 + i as i32 * sc(24);+ glow(dc, TAPP + i as i32, hot == TAPP + i as i32, cell(x, sc(24)), BG, HOVER, sc(8));+ if !ti.icon.is_null() {+ DrawIconEx(dc, x + sc(4), mid - sc(8), ti.icon, sc(16), sc(16), 0, null_mut(), DI_NORMAL);+ }+ }+ });++ // system group: language on its own, then one pill for wifi + volume + battery (like Windows 11: they open one panel)+ let tb = RECT { left: l.sys.0, top, right: l.sys.1, bottom: bot };+ glow(dc, LANG, hot == LANG, RECT { left: tb.left, top, right: tb.left + sc(42), bottom: bot }, BG, HOVER, sc(8));+ let grp = RECT { left: tb.left + sc(44), top, right: tb.right, bottom: bot };+ let (tg, pg) = (hv(SYS_GRP, matches!(hot, WIFI_I | VOL_I | BAT_I) || fly::is_open(fly::Kind::Quick)), press_t(WIFI_I).max(press_t(VOL_I)).max(press_t(BAT_I)));+ if tg > 0.01 || pg > 0.0 {+ fill(dc, grp, mix(mix(BG, HOVER, tg), ACCENT, 0.5 * pg), sc(8));+ }+ let mut x = tb.left + sc(10);+ text(dc, &lang_name(), cell(x, sc(34)), TEXT, DT_LEFT);+ x += sc(42);+ let q = WIFI.get();+ if q >= 0 {+ let lit = ((q + 24) / 25).clamp(1, 4); // 1..4 bars+ for i in 0..4 {+ let bh = sc(4 + 3 * i);+ let bx = x + sc(5) * i;+ fill(dc, RECT { left: bx, top: mid + sc(7) - bh, right: bx + sc(3), bottom: mid + sc(7) }, if i < lit { TEXT } else { mix(DIM, BG, 0.45) }, sc(2));+ }+ } else {+ SelectObject(dc, f_glyph);+ text(dc, "\u{E839}", cell(x - sc(2), sc(22)), TEXT, DT_CENTER); // ethernet+ }+ x += sc(32);+ SelectObject(dc, f_glyph);+ let (vol, muted) = VOL.get();+ let vg = if muted || vol == 0 { "\u{E74F}" } else if vol < 34 { "\u{E993}" } else if vol < 67 { "\u{E994}" } else { "\u{E995}" };+ text(dc, vg, cell(x, sc(22)), if muted { BAD } else { TEXT }, DT_CENTER);+ x += sc(32);+ let (pct, ac) = BAT.get();+ if pct >= 0 {+ let col = if ac { GOOD } else if pct <= 15 { BAD } else { TEXT };+ let (bw, bh, by) = (sc(22), sc(11), mid - sc(5));+ fill(dc, RECT { left: x, top: by, right: x + bw, bottom: by + bh }, col, sc(4)); // outline+ fill(dc, RECT { left: x + sc(1), top: by + sc(1), right: x + bw - sc(1), bottom: by + bh - sc(1) }, mix(BG, HOVER, tg), sc(3));+ let fw = ((bw - sc(4)) * pct / 100).max(sc(1));+ fill(dc, RECT { left: x + sc(2), top: by + sc(2), right: x + sc(2) + fw, bottom: by + bh - sc(2) }, col, sc(2));+ fill(dc, RECT { left: x + bw + sc(1), top: by + sc(3), right: x + bw + sc(3), bottom: by + bh - sc(3) }, col, sc(1)); // terminal nub+ SelectObject(dc, f_txt);+ text(dc, &format!("{pct}%"), cell(x + bw + sc(8), sc(40)), TEXT, DT_LEFT);+ }++ // time (semibold) over the date (dimmed)+ let cb = cell(l.clock.0, l.clock.1 - l.clock.0);+ glow(dc, CLOCK, hot == CLOCK || fly::is_open(fly::Kind::Cal), cb, BG, HOVER, sc(8));+ let (tm, dt) = clock_texts();+ SelectObject(dc, f_bold);+ text(dc, &tm, RECT { left: cb.left, top: cb.top, right: cb.right, bottom: mid + sc(1) }, TEXT, DT_CENTER);+ SelectObject(dc, f_small);+ text(dc, &dt, RECT { left: cb.left, top: mid - sc(1), right: cb.right, bottom: cb.bottom }, mix(DIM, TEXT, 0.35), DT_CENTER);++ BitBlt(wdc, 0, 0, cr.right, h, dc, 0, 0, SRCCOPY);+ SelectObject(dc, of);+ for f in [f_txt, f_small, f_glyph, f_bold] {+ DeleteObject(f);+ }+ SelectObject(dc, old);+ DeleteObject(bmp);+ DeleteDC(dc);+ if BUSY.get() {+ SetTimer(hwnd, 4, 16, None); // next animation frame+ } else {+ KillTimer(hwnd, 4);+ }+ EndPaint(hwnd, &ps);+}++// ---------- input ----------++/// Presses the keys in order, releases them in reverse (e.g. Win+A).+unsafe fn keys(vks: &[u16]) {+ let send = |vk: u16, up: bool| {+ let mut i: INPUT = zeroed();+ i.r#type = INPUT_KEYBOARD;+ i.Anonymous.ki.wVk = vk;+ i.Anonymous.ki.dwFlags = if up { KEYEVENTF_KEYUP } else { 0 };+ SendInput(1, &i, size_of::<INPUT>() as i32);+ };+ vks.iter().for_each(|&v| send(v, false));+ vks.iter().rev().for_each(|&v| send(v, true));+}++/// WM_CLOSE. A window of an elevated app ignores it from our normal-rights process (UIPI), so then+/// ask for admin once (UAC) and let an elevated taskkill send the close request.+unsafe fn close_window(w: HWND) {+ if PostMessageW(w, WM_CLOSE, 0, 0) == 0 {+ let mut pid = 0u32;+ GetWindowThreadProcessId(w, &mut pid);+ ShellExecuteW(null_mut(), wide("runas").as_ptr(), wide("taskkill.exe").as_ptr(), wide(&format!("/PID {pid}")).as_ptr(), null(), SW_HIDE);+ }+}++/// Opens a file, shortcut or URI through explorer, which starts it with the desktop user's normal token: the bar itself+/// may run elevated (see the launcher), and everything started from it must not inherit that.+unsafe fn open(path: &[u16]) {+ let n = path.iter().position(|&c| c == 0).unwrap_or(path.len());+ let p = String::from_utf16_lossy(&path[..n]);+ if p.to_lowercase().ends_with(".lnk") {+ bump(&p);+ }+ // Always through explorer.exe: it starts the target with the desktop user's normal token. ShellExecuteW from here would+ // inherit this bar's admin rights, and an elevated app cannot receive files dragged in from normal windows (UIPI), and+ // PrtSc / Win+Shift+S (ms-screenclip:) do not work when started elevated. With an argument and no explorer shell+ // running, explorer.exe hands the target to its COM host and does not become a shell or raise a taskbar.+ if Command::new("explorer.exe").arg(&p).spawn().is_err() {+ ShellExecuteW(null_mut(), wide("open").as_ptr(), wide(&p).as_ptr(), null(), null(), SW_SHOWNORMAL);+ }+}++/// Starts the disk cleaner (rs-du, installed next to the task manager) elevated: it reads the raw volume.+/// Right-click menu of an app button, like the Windows taskbar's jump list: pin / unpin, close, end process.+fn wstr_of(w: &[u16]) -> String {+ String::from_utf16_lossy(&w[..w.iter().position(|&c| c == 0).unwrap_or(w.len())])+}++/// "1 окно", "3 окна", "5 окон".+fn windows_ru(n: usize) -> String {+ let w = match (n % 10, n % 100) {+ (1, x) if x != 11 => "окно",+ (2..=4, x) if !(12..=14).contains(&x) => "окна",+ _ => "окон",+ };+ format!("{n} {w}")+}++/// Right-click menu of an app button, like the Windows 11 jump list: the app on top, its windows (when there are several),+/// open / pin / Start, then close and end process in red.+unsafe fn app_menu(hwnd: HWND, h: i32) {+ #[derive(Clone, Copy)]+ enum A {+ Win(HWND),+ Open,+ Pin,+ Start,+ Close,+ Kill,+ }+ let (wins, pin, bicon) = BTNS.with_borrow(|b| b.get(h as usize).map(|b| (b.wins.clone(), b.pin, b.icon)).unwrap_or((vec![], None, null_mut())));+ let exe = wins.first().map(|&w| exe_of(w)).unwrap_or_default();+ let (lnk, picon) = pin.and_then(|p| PINS.with_borrow(|p2| p2.get(p).map(|x| (wstr_of(&x.lnk), x.icon)))).unwrap_or_default();+ let launch = if lnk.is_empty() { exe.clone() } else { lnk.clone() };+ let stem = std::path::Path::new(&launch).file_stem().unwrap_or_default().to_string_lossy().to_string();+ let name: String = stem.chars().take(1).flat_map(char::to_uppercase).chain(stem.chars().skip(1)).collect();+ let sub = match (wins.len(), pin.is_some()) {+ (0, _) => "Закреплено · не запущено".to_string(),+ (n, true) => format!("Закреплено · {}", windows_ru(n)),+ (n, false) => format!("Запущено · {}", windows_ru(n)),+ };+ let icon = if picon.is_null() { bicon } else { picon };+ let mut items: Vec<(fly::MItem, A)> = Vec::new();+ if wins.len() > 1 {+ for &w in wins.iter().take(6) {+ let mut b = [0u16; 256];+ let n = GetWindowTextW(w, b.as_mut_ptr(), 256).max(0) as usize;+ items.push((fly::MItem { icon: icon_of(w), ..fly::MItem::new("", String::from_utf16_lossy(&b[..n])) }, A::Win(w)));+ }+ }+ if !launch.is_empty() {+ let it = fly::MItem::new("\u{E8A7}", if wins.is_empty() { "Открыть" } else { "Новое окно" });+ items.push((if items.is_empty() { it } else { it.sep() }, A::Open));+ }+ if pin.is_some() {+ items.push((fly::MItem::new("\u{E77A}", "Открепить от панели"), A::Pin));+ } else if !exe.is_empty() {+ items.push((fly::MItem::new("\u{E718}", "Закрепить на панели"), A::Pin));+ }+ if !launch.is_empty() {+ let s = fly::start_pinned(&launch);+ items.push((fly::MItem::new(if s { "\u{E738}" } else { "\u{E710}" }, if s { "Убрать из Пуска" } else { "Добавить в Пуск" }), A::Start));+ }+ if !wins.is_empty() {+ items.push((fly::MItem::new("\u{E8BB}", if wins.len() > 1 { "Закрыть все окна" } else { "Закрыть окно" }).sep(), A::Close));+ items.push((fly::MItem::new("\u{E7BA}", "Завершить процесс").danger(), A::Kill));+ }+ let acts: Vec<A> = items.iter().map(|x| x.1).collect();+ let items = items.into_iter().map(|x| x.0).collect();+ fly::menu(tip_cx(&bar_layout(hwnd), h), Some((icon, name, sub)), items, move |i| {+ match acts.get(i).copied() {+ Some(A::Win(w)) => {+ if IsIconic(w) != 0 {+ ShowWindow(w, SW_RESTORE);+ }+ force_fg(w);+ }+ Some(A::Open) => open(&wide(&launch)),+ Some(A::Pin) => {+ // by path, not by the index seen when the menu opened: PINS may have changed meanwhile+ match PINS.with_borrow(|p| p.iter().position(|x| !lnk.is_empty() && wstr_of(&x.lnk) == lnk)) {+ Some(p) => unpin(p),+ None if lnk.is_empty() => pin_exe(&exe),+ None => {}+ }+ refresh_buttons(); // the buttons hold indices into PINS: a stale one would index past the end on the next paint+ }+ Some(A::Start) => fly::start_toggle(&launch),+ Some(A::Close) => wins.iter().for_each(|&w| close_window(w)),+ Some(A::Kill) => {+ let mut pids: Vec<u32> = wins+ .iter()+ .map(|&w| {+ let mut pid = 0u32;+ GetWindowThreadProcessId(w, &mut pid);+ pid+ })+ .collect();+ pids.sort_unstable();+ pids.dedup(); // several windows of one app: one kill (and at most one UAC prompt), not one per window+ for pid in pids {+ let p = OpenProcess(1, 0, pid); // PROCESS_TERMINATE; works on elevated apps when the bar itself runs elevated+ if p.is_null() || TerminateProcess(p, 1) == 0 {+ ShellExecuteW(null_mut(), wide("runas").as_ptr(), wide("taskkill.exe").as_ptr(), wide(&format!("/F /T /PID {pid}")).as_ptr(), null(), SW_HIDE);+ }+ if !p.is_null() {+ CloseHandle(p);+ }+ }+ }+ None => {}+ }+ InvalidateRect(BAR.load(Relaxed) as HWND, null(), 0);+ });+}++fn pin_dir() -> PathBuf {+ appdata_file(r"Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar")+}++unsafe fn unpin(i: usize) {+ let Some(p) = PINS.with_borrow_mut(|p| (i < p.len()).then(|| p.remove(i))) else { return };+ let n = p.lnk.iter().position(|&c| c == 0).unwrap_or(p.lnk.len());+ let _ = std::fs::remove_file(String::from_utf16_lossy(&p.lnk[..n]));+ DestroyIcon(p.icon);+}++/// Pins a running app: a shortcut to its exe in the folder where Windows keeps taskbar pins.+/// A dropped .lnk pins its target. Already pinned (same target) = nothing.+unsafe fn pin_exe(path: &str) {+ // targets are compared with exe_of(), which is lower-case+ let exe = if path.to_lowercase().ends_with(".lnk") { lnk_target(&wide(path)) } else { path.to_lowercase() };+ let exe = exe.as_str();+ if exe.is_empty() || PINS.with_borrow(|p| p.iter().any(|p| p.target == exe)) {+ return;+ }+ let stem = std::path::Path::new(exe).file_stem().unwrap_or_default().to_string_lossy().to_string();+ let name: String = stem.chars().enumerate().map(|(i, c)| if i == 0 { c.to_ascii_uppercase() } else { c }).collect();+ let _ = std::fs::create_dir_all(pin_dir());+ let lnk = wide(&pin_dir().join(format!("{name}.lnk")).to_string_lossy());+ let ok = (|| -> Option<()> {+ let sl: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER).ok()?;+ sl.SetPath(PCWSTR(wide(exe).as_ptr())).ok()?;+ sl.cast::<IPersistFile>().ok()?.Save(PCWSTR(lnk.as_ptr()), true).ok()+ })();+ if ok.is_some() {+ let icon = lnk_icon(&lnk, exe);+ PINS.with_borrow_mut(|p| p.push(Pin { lnk, target: exe.to_string(), icon }));+ }+}++/// Files dropped on the bar: on the Start button they are added to Start (the panel opens and the new row pulses),+/// anywhere else they are pinned to the bar.+unsafe fn on_drop(hwnd: HWND, hd: HDROP) {+ let mut pt: POINT = zeroed();+ DragQueryPoint(hd, &mut pt);+ let n = DragQueryFileW(hd, u32::MAX, null_mut(), 0);+ let files: Vec<String> = (0..n)+ .map(|i| {+ let len = DragQueryFileW(hd, i, null_mut(), 0) as usize;+ let mut b = vec![0u16; len + 1];+ DragQueryFileW(hd, i, b.as_mut_ptr(), b.len() as u32);+ String::from_utf16_lossy(&b[..len])+ })+ .collect();+ DragFinish(hd);+ let h = hit(hwnd, pt.x);+ press(if h == NONE { 0 } else { h });+ if h == 0 {+ let added: Vec<&String> = files.iter().filter(|f| fly::start_pin(f)).collect();+ let name = |p: &str| std::path::Path::new(p).file_stem().unwrap_or_default().to_string_lossy().to_string();+ if !fly::is_open(fly::Kind::Start) {+ fly::toggle(fly::Kind::Start);+ }+ fly::note(&match added.len() {+ 0 => "Already in Start".to_string(),+ 1 => format!("Added to Start: {}", name(added[0])),+ n => format!("Added {n} items to Start"),+ });+ } else {+ files.iter().for_each(|f| pin_exe(f));+ refresh_buttons();+ }+ InvalidateRect(hwnd, null(), 0);+}++unsafe fn open_cleaner() {+ let Some(pf) = std::env::var_os("ProgramFiles") else { return };+ let exe = PathBuf::from(pf).join(r"rtaskmgr\rs-du.exe");+ if exe.is_file() {+ ShellExecuteW(null_mut(), wide("runas").as_ptr(), wide(&exe.to_string_lossy()).as_ptr(), wide("C: --clean --ask").as_ptr(), null(), SW_SHOWNORMAL);+ }+}++unsafe extern "system" fn find_launcher(h: HWND, lp: LPARAM) -> i32 {+ let mut cls = [0u16; 32];+ let n = GetClassNameW(h, cls.as_mut_ptr(), 32).max(0) as usize;+ if String::from_utf16_lossy(&cls[..n]) == "rs_launcher" {+ *(lp as *mut HWND) = h;+ return 0;+ }+ 1+}++/// Asks the running rs-launcher to show itself by sending the message its Alt+Space hotkey produces.+/// Faking the key presses did not reliably reach it from this (elevated) process. false = it is not running.+unsafe fn open_launcher() -> bool {+ let mut h: HWND = null_mut();+ EnumWindows(Some(find_launcher), &mut h as *mut _ as LPARAM);+ if h.is_null() {+ return false;+ }+ PostMessageW(h, WM_HOTKEY, 1, (MOD_ALT | MOD_NOREPEAT) as isize | ((VK_SPACE as isize) << 16));+ true+}++unsafe fn click(h: i32, left: bool, mid: bool) {+ match h {+ SEARCH if left => {+ // our search (rs-launcher listens for Alt+Space); without it the Start panel's own search+ if std::env::var_os("ProgramFiles").is_some_and(|p| PathBuf::from(p).join(r"rs-search\rs-launcher.exe").is_file()) {+ if !open_launcher() {+ keys(&[VK_MENU, VK_SPACE]);+ }+ } else {+ fly::toggle(fly::Kind::Start);+ }+ }+ // next input language; Win+Space is handled by explorer's input switcher, which is gone under rs-shell+ LANG if left => next_lang(BAR.load(Relaxed) as HWND),+ WIFI_I => fly::toggle(if left { fly::Kind::Quick } else { fly::Kind::Wifi }), // right click: the network list+ VOL_I | BAT_I => fly::toggle(fly::Kind::Quick),+ CLOCK if left => fly::toggle(fly::Kind::Cal),+ TAPP..=-900 => {+ let slot = (h - TAPP) as usize;+ if slot == 0 {+ if left {+ fly_toggle();+ }+ } else if mid {+ if let Some(k) = bar_idx().get(slot - 1).and_then(|&i| TAPPS.with_borrow(|t| t.get(i).map(|x| x.key.clone()))) {+ toggle_shown(&k); // back into the flyout+ }+ } else {+ let ti = bar_idx().get(slot - 1).and_then(|&i| TAPPS.with_borrow(|t| t.get(i).map(|x| (x.hwnd, x.uid, x.cb, x.ver))));+ ti.into_iter().for_each(|ti| tray_click(ti, left));+ }+ }+ 0 => {+ if left {+ fly::toggle(fly::Kind::Start);+ }+ }+ 1.. => {+ let (wins, lnk) = BTNS.with_borrow(|b| b.get(h as usize).map(|b| (b.wins.clone(), b.pin.and_then(|p| PINS.with_borrow(|p2| p2.get(p).map(|x| x.lnk.clone()))))).unwrap_or_default());+ match (wins.first(), left) {+ (None, true) => lnk.iter().for_each(|l| open(l)), // not running: launch the pinned app+ (Some(&w), false) => close_window(w), // right / middle click+ (Some(&w), true) => {+ // like the Windows taskbar: the active app's button minimizes it, a minimized one restores, any other raises+ let fg = GetForegroundWindow();+ if wins.contains(&fg) && IsIconic(fg) == 0 {+ ShowWindow(fg, SW_MINIMIZE);+ } else {+ if IsIconic(w) != 0 {+ ShowWindow(w, SW_RESTORE);+ }+ SetForegroundWindow(w);+ }+ }+ _ => {}+ }+ }+ _ => {}+ }+}++#[repr(C)]+struct ShellHookInfo {+ hwnd: HWND,+ rc: RECT,+}++/// HSHELL_GETMINRECT: a window is minimizing / restoring and asks where its taskbar button is: the shrink animation+/// flies there instead of to the bottom left corner of the screen.+unsafe fn min_rect(info: *mut ShellHookInfo, bar: HWND) {+ let (w, l) = ((*info).hwnd, bar_layout(bar));+ let exe = exe_of(w);+ let i = BTNS.with_borrow(|b| b.iter().position(|b| b.wins.contains(&w)).or_else(|| b.iter().position(|b| !exe.is_empty() && b.wins.first().is_some_and(|&x| exe_of(x) == exe))));+ let x = match i {+ Some(i) => l.x0 + (i as i32 + 1) * (l.bw + l.gap),+ None => (l.x0 + l.apps.0) / 2, // no button (yet): the middle of the bar+ };+ let top = bar_top() + sc(4);+ (*info).rc = RECT { left: x, top, right: x + l.bw, bottom: top + bar_h() - sc(8) };+}++/// Screen x of the middle of a bar element (the bar spans the screen from x = 0), for its tooltip.+fn tip_cx(l: &Layout, h: i32) -> i32 {+ match h {+ SEARCH => l.x0 + l.bw / 2,+ CLOCK => (l.clock.0 + l.clock.1) / 2,+ LANG => l.sys.0 + sc(21),+ WIFI_I => l.sys.0 + sc(58),+ VOL_I => l.sys.0 + sc(90),+ BAT_I => l.sys.0 + sc(130),+ t if (TAPP..TAPP + 100).contains(&t) => l.apps.0 + (t - TAPP) * sc(24) + sc(12),+ i => l.x0 + (i + 1) * (l.bw + l.gap) + l.bw / 2,+ }+}++unsafe fn bar_layout(hwnd: HWND) -> Layout {+ let mut r: RECT = zeroed();+ GetClientRect(hwnd, &mut r);+ layout(r.right)+}++/// Registers the bar as an appbar with explorer (again after explorer restarts: its list starts empty).+unsafe fn appbar_new(hwnd: HWND) {+ let mut ab: APPBARDATA = zeroed();+ ab.cbSize = size_of::<APPBARDATA>() as u32;+ ab.hWnd = hwnd;+ ab.uCallbackMessage = CALLBACK;+ SHAppBarMessage(ABM_NEW, &mut ab);+ EXP_TRAY.set(tray()[0]);+}++unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {+ if msg != 0 && msg == SH_MSG.get() {+ if wp == 5 && lp != 0 {+ min_rect(lp as *mut ShellHookInfo, hwnd); // HSHELL_GETMINRECT+ return 1;+ }+ return 0;+ }+ if msg != 0 && msg == TB_MSG.get() {+ // also our own announce(): act only when explorer's taskbar is a new window (explorer restarted / came back)+ let t = tray()[0];+ if !t.is_null() && t != EXP_TRAY.get() {+ appbar_new(hwnd);+ hide_taskbar();+ place(hwnd);+ }+ return 0;+ }+ match msg {+ WM_PAINT => paint(hwnd),+ WM_ERASEBKGND => return 1,+ WM_TIMER if wp == 2 => {+ KillTimer(hwnd, 2);+ let h = HOT.get();+ if h != NONE && !fly::any_open() {+ show_tip(tip_text(h), tip_cx(&bar_layout(hwnd), h));+ }+ }+ WM_TIMER if wp == 6 => hide_tip(hwnd), // the volume readout after a wheel turn+ WM_TIMER if wp == 3 => fs_update(hwnd),+ WM_TIMER if wp == 7 => {+ KillTimer(hwnd, 7);+ let (tid, before) = LANG_TRY.get();+ if GetKeyboardLayout(tid) as usize == before {+ let w = app_window();+ if GetForegroundWindow() != w {+ force_fg(w); // Win+Space switches the window in front: put the app back there first+ }+ keys(&[VK_LWIN, VK_SPACE]); // the app ignored the request: the system switcher always works (with explorer)+ }+ InvalidateRect(hwnd, null(), 0); // the label shows the new language right away+ }+ WM_TIMER if wp == 4 => {+ InvalidateRect(hwnd, null(), 0);+ }+ WM_TIMER if wp == 5 => bar_step(hwnd),+ WIN_START => fly::toggle(fly::Kind::Start),+ ALT_TAB => alt_tab(wp == 1),+ ALT_UP => alt_done(wp == 1),+ SNIP if wp == 1 => screenshot_notice(hwnd),+ SNIP => open(&wide("ms-screenclip:")),+ WM_DROPFILES => on_drop(hwnd, wp as HDROP),+ WM_TIMER => {+ hide_taskbar_if_shown();+ refresh();+ // repaint (GDI+, the costly part) only when something shown changed; every 10th tick anyway as a safety net+ let (last, quiet) = SIG.get();+ let s = view_sig();+ if s != last || quiet >= 10 {+ SIG.set((s, 0));+ InvalidateRect(hwnd, null(), 0);+ } else {+ SIG.set((s, quiet + 1));+ }+ }+ WM_MOUSEMOVE => {+ let h = hit(hwnd, (lp & 0xffff) as i16 as i32);+ let mut tme = TRACKMOUSEEVENT { cbSize: size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE, hwndTrack: hwnd, dwHoverTime: 0 };+ TrackMouseEvent(&mut tme);+ if HOT.replace(h) != h {+ hide_tip(hwnd);+ if h != NONE {+ SetTimer(hwnd, 2, 450, None);+ }+ InvalidateRect(hwnd, null(), 0);+ }+ }+ WM_MOUSELEAVE => {+ hide_tip(hwnd);+ HOT.set(-1);+ InvalidateRect(hwnd, null(), 0);+ }+ WM_MOUSEWHEEL => {+ add_volume(if (wp >> 16) as i16 > 0 { 2 } else { -2 }); // wheel anywhere on the bar = volume+ press(VOL_I); // the speaker flashes so it is clear what the wheel changed+ KillTimer(hwnd, 2);+ if !fly::any_open() {+ show_tip(vol_tip(), tip_cx(&bar_layout(hwnd), VOL_I)); // and the level shows above it for a moment+ SetTimer(hwnd, 6, 1200, None);+ }+ InvalidateRect(hwnd, null(), 0);+ }+ WM_LBUTTONDOWN | WM_RBUTTONDOWN | WM_MBUTTONDOWN => {+ let x = (lp & 0xffff) as i16 as i32;+ let h = hit(hwnd, x);+ hide_tip(hwnd);+ if h != NONE {+ press(h);+ }+ if h == NONE && msg == WM_RBUTTONDOWN {+ fly::context_menu(x); // right click on an empty spot+ } else if h >= 1 && msg == WM_RBUTTONDOWN {+ app_menu(hwnd, h);+ } else {+ click(h, msg == WM_LBUTTONDOWN, msg == WM_MBUTTONDOWN);+ }+ InvalidateRect(hwnd, null(), 0);+ }+ CALLBACK => {+ if wp == ABN_FULLSCREENAPP as usize {+ fs_update(hwnd);+ } else if wp == ABN_POSCHANGED as usize {+ place(hwnd);+ }+ }+ WM_DISPLAYCHANGE => place(hwnd),+ WM_DESTROY => {+ let mut ab: APPBARDATA = zeroed();+ ab.cbSize = size_of::<APPBARDATA>() as u32;+ ab.hWnd = hwnd;+ SHAppBarMessage(ABM_REMOVE, &mut ab);+ if find_other("Shell_TrayWnd").is_null() {+ set_work_area(RECT { left: 0, top: 0, right: GetSystemMetrics(SM_CXSCREEN), bottom: GetSystemMetrics(SM_CYSCREEN) }); // ours: give the strip back+ }+ show_taskbar(OLD_STATE.get());+ DestroyWindow(HOST.replace(null_mut()));+ announce(); // icons go back to explorer's tray+ PostQuitMessage(0);+ }+ _ => return DefWindowProcW(hwnd, msg, wp, lp),+ }+ 0+}++fn main() {+ unsafe {+ if std::env::args().any(|a| a == "--restore") {+ show_taskbar(ABS_ALWAYSONTOP as usize); // shortcut: the Windows default, not the user's previous taskbar mode+ if find_other("Shell_TrayWnd").is_null() {+ set_work_area(RECT { left: 0, top: 0, right: GetSystemMetrics(SM_CXSCREEN), bottom: GetSystemMetrics(SM_CYSCREEN) }); // a killed bar's reserved strip+ }+ announce(); // a killed bar took its tray icons with it; apps re-register with explorer+ return;+ }+ if std::env::args().any(|a| a == "--shot") {+ SetProcessDPIAware();+ let (mut tok, mut inp): (usize, GdiplusStartupInput) = (0, zeroed());+ inp.GdiplusVersion = 1;+ GdiplusStartup(&mut tok, &inp, null_mut());+ screenshot();+ return;+ }+ // Atomic single-instance guard (FindWindow alone raced when two launchers started us at once); the handle lives until exit.+ let m = windows_sys::Win32::System::Threading::CreateMutexW(null(), 0, wide("Local\\topbar-single").as_ptr());+ if m.is_null() || GetLastError() == ERROR_ALREADY_EXISTS || !FindWindowW(wide("topbar").as_ptr(), null()).is_null() {+ return; // already running+ }+ let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);+ // Without explorer nobody hides minimized windows: they sit as small caption stubs at the bottom left of the screen.+ // ARW_HIDE moves them off screen (this session only: fWinIni 0 does not touch the saved setting).+ let mut mm: MINIMIZEDMETRICS = zeroed();+ mm.cbSize = size_of::<MINIMIZEDMETRICS>() as u32;+ if SystemParametersInfoW(SPI_GETMINIMIZEDMETRICS, mm.cbSize, &mut mm as *mut _ as *mut _, 0) != 0 {+ mm.iArrange |= ARW_HIDE as i32;+ SystemParametersInfoW(SPI_SETMINIMIZEDMETRICS, mm.cbSize, &mut mm as *mut _ as *mut _, 0);+ }+ let (mut gtok, mut gin): (usize, GdiplusStartupInput) = (0, zeroed());+ gin.GdiplusVersion = 1;+ GdiplusStartup(&mut gtok, &gin, null_mut()); // anti-aliased shapes; fill() falls back to GDI if this failed+ TB_MSG.set(RegisterWindowMessageW(wide("TaskbarCreated").as_ptr()));+ SH_MSG.set(RegisterWindowMessageW(wide("SHELLHOOK").as_ptr()));+ SetProcessDPIAware();+ let dc = GetDC(null_mut());+ SCALE.set(GetDeviceCaps(dc, LOGPIXELSX as i32) as f32 / 96.0);+ ReleaseDC(null_mut(), dc);+ SHOWN.set(std::fs::read_to_string(appdata_file("topbar-tray.txt")).ok().map(|s| s.lines().map(str::to_string).collect()));+ load_pins();+ fly::init(GetModuleHandleW(null()));+ thread::spawn(fly::load_apps);+ let hi = GetModuleHandleW(null());+ let class = wide("topbar");+ let wc = WNDCLASSW { lpfnWndProc: Some(wndproc), hInstance: hi, hCursor: LoadCursorW(null_mut(), IDC_ARROW), lpszClassName: class.as_ptr(), ..zeroed() };+ RegisterClassW(&wc);+ let hwnd = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_NOACTIVATE, class.as_ptr(), class.as_ptr(), WS_POPUP, 0, 0, GetSystemMetrics(SM_CXSCREEN), bar_h(), null_mut(), null_mut(), hi, null());+ // Our own Shell_TrayWnd (hidden, topmost, so apps find it before explorer's): apps register their tray icons here.+ let tc = wide("Shell_TrayWnd");+ RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(tray_proc), hInstance: hi, lpszClassName: tc.as_ptr(), ..zeroed() });+ HOST.set(CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_NOACTIVATE, tc.as_ptr(), null(), WS_POPUP, 0, 0, 0, 0, null_mut(), null_mut(), hi, null()));+ // The bar may run elevated while apps and explorer do not; UIPI would drop their messages to us (icon data, appbar callbacks).+ ChangeWindowMessageFilterEx(HOST.get(), WM_COPYDATA, MSGFLT_ALLOW, null_mut());+ ChangeWindowMessageFilterEx(hwnd, CALLBACK, MSGFLT_ALLOW, null_mut());+ ChangeWindowMessageFilterEx(hwnd, TB_MSG.get(), MSGFLT_ALLOW, null_mut()); // explorer restarted (it runs unelevated)+ // files dragged from a normal-rights app onto the (elevated) bar: Start button = add to Start, elsewhere = pin+ DragAcceptFiles(hwnd, 1);+ for m in [WM_DROPFILES, 0x49 /* WM_COPYGLOBALDATA */, WM_COPYDATA] {+ ChangeWindowMessageFilterEx(hwnd, m, MSGFLT_ALLOW, null_mut());+ }+ let fc = wide("topbar_trayfly");+ RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(fly_proc), hInstance: hi, hCursor: LoadCursorW(null_mut(), IDC_ARROW), lpszClassName: fc.as_ptr(), ..zeroed() });+ TRAYFLY.set(CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_TOPMOST, fc.as_ptr(), null(), WS_POPUP, 0, 0, 1, 1, null_mut(), null_mut(), hi, null()));+ let tipc = wide("topbar_tip");+ RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(tip_proc), hInstance: hi, lpszClassName: tipc.as_ptr(), ..zeroed() });+ TIPWND.set(CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_NOACTIVATE, tipc.as_ptr(), null(), WS_POPUP, 0, 0, 1, 1, null_mut(), null_mut(), hi, null()));+ let swc = wide("topbar_alttab");+ RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(sw_proc), hInstance: hi, lpszClassName: swc.as_ptr(), ..zeroed() });+ SWWND.set(CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_NOACTIVATE, swc.as_ptr(), null(), WS_POPUP, 0, 0, 1, 1, null_mut(), null_mut(), hi, null()));+ let mut ab: APPBARDATA = zeroed();+ ab.cbSize = size_of::<APPBARDATA>() as u32;+ ab.hWnd = tray()[0];+ OLD_STATE.set(SHAppBarMessage(ABM_GETSTATE, &mut ab));+ appbar_new(hwnd);+ // Without explorer nobody is the "taskman" window, so Windows treats minimized windows as loose icons and leaves+ // them as caption stubs on the desktop. Becoming that window (what explorer's taskbar does) makes them hide properly+ // and gets us HSHELL_GETMINRECT. Only when explorer's taskbar is absent: with it running its own registration stays.+ if find_other("Shell_TrayWnd").is_null() {+ if let Some(f) = GetProcAddress(GetModuleHandleW(wide("user32.dll").as_ptr()), b"SetTaskmanWindow\0".as_ptr()) {+ std::mem::transmute::<_, unsafe extern "system" fn(HWND) -> i32>(f)(hwnd);+ }+ RegisterShellHookWindow(hwnd);+ }+ hide_taskbar();+ place(hwnd);+ refresh();+ announce(); // apps already running re-add their icons to us+ SetTimer(hwnd, 1, 500, None);+ BAR.store(hwnd as isize, Relaxed);+ bar_anim(hwnd); // the bar slides in (it starts hidden above the screen)+ SetTimer(hwnd, 3, 250, None); // fullscreen watch+ thread::spawn(|| {+ if !SetWindowsHookExW(WH_KEYBOARD_LL, Some(kb_hook), GetModuleHandleW(null()), 0).is_null() {+ let mut m: MSG = zeroed();+ while GetMessageW(&mut m, null_mut(), 0, 0) > 0 {}+ }+ });+ let mut m: MSG = zeroed();+ while GetMessageW(&mut m, null_mut(), 0, 0) > 0 {+ TranslateMessage(&m);+ DispatchMessageW(&m);+ }+ }+}++#[cfg(test)]+mod tests {+ #[test]+ fn mix_blends() {+ assert_eq!(super::mix(super::rgb(0, 0, 0), super::rgb(200, 100, 50), 0.0), super::rgb(0, 0, 0));+ assert_eq!(super::mix(super::rgb(0, 0, 0), super::rgb(200, 100, 50), 1.0), super::rgb(200, 100, 50));+ assert_eq!(super::mix(super::rgb(0, 0, 0), super::rgb(200, 100, 50), 0.5), super::rgb(100, 50, 25));+ }+}++#[cfg(test)]+mod env_tests {+ #[test]+ fn expands_known_variables_only() {+ let windir = std::env::var("windir").unwrap();+ assert_eq!(super::expand_env(r"%windir%\explorer.exe"), format!(r"{windir}\explorer.exe"));+ assert_eq!(super::expand_env(r"%no_such_var_x%\a.exe"), r"%no_such_var_x%\a.exe");+ assert_eq!(super::expand_env("100% sure"), "100% sure");+ }+}diff --git a/plugins/wiztree/Cargo.lock b/plugins/wiztree/Cargo.locknew file mode 100644index 0000000..635844c--- /dev/null+++ b/plugins/wiztree/Cargo.lock@@ -0,0 +1,25 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "wiztree"+version = "0.1.0"+dependencies = [+ "windows-sys",+]diff --git a/plugins/wiztree/Cargo.toml b/plugins/wiztree/Cargo.tomlnew file mode 100644index 0000000..7922a21--- /dev/null+++ b/plugins/wiztree/Cargo.toml@@ -0,0 +1,14 @@+[package]+name = "wiztree"+version = "0.1.0"+edition = "2024"++[dependencies]+windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Ioctl", "Win32_System_LibraryLoader", "Win32_UI_HiDpi", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] }++[profile.release]+opt-level = "s"+lto = true+codegen-units = 1+panic = "abort"+strip = truediff --git a/plugins/wiztree/src/main.rs b/plugins/wiztree/src/main.rsnew file mode 100644index 0000000..45befad--- /dev/null+++ b/plugins/wiztree/src/main.rs@@ -0,0 +1,349 @@+#![windows_subsystem = "windows"]+// wiztree [X:] Disk usage treemap on the NTFS MFT (the same reader as rs-du, shared through mft.rs).+// Click a folder: go in. Right click / Backspace: up. Click a file: show it in Explorer. Tab: next drive. F5: rescan. Esc: quit.+// Needs admin (raw volume); starts itself elevated (UAC) when it is not.+// shortcuts: one level of the tree at a time, the 300 biggest items; a folder's own index size is not counted (see mft.rs).+#[path = "../../rs-du/src/mft.rs"]+mod mft;+use mft::*;+use std::{cell::RefCell, collections::HashMap, ptr::{null, null_mut}};+use windows_sys::Win32::{+ Foundation::*,+ Graphics::Gdi::*,+ Storage::FileSystem::{GetDriveTypeW, GetLogicalDrives},+ System::LibraryLoader::GetModuleHandleW,+ UI::{HiDpi::GetDpiForSystem, Input::KeyboardAndMouse::*, Shell::{IsUserAnAdmin, ShellExecuteW}, WindowsAndMessaging::*},+};++const WM_DONE: u32 = WM_APP + 1; // lparam = Box<Result<Tree, String>>+const DRIVE_FIXED: u32 = 3;+const MAX_CELLS: usize = 300;+const BG: u32 = rgb(22, 19, 18);+const DIM: u32 = rgb(166, 152, 145);+const ACCENT: u32 = rgb(222, 98, 42);++const fn rgb(r: u8, g: u8, b: u8) -> u32 {+ r as u32 | (g as u32) << 8 | (b as u32) << 16+}++struct Tree {+ recs: HashMap<u32, Rec>,+ tot: HashMap<u32, u64>,+ kids: HashMap<u32, Vec<u32>>,+}++fn build(recs: HashMap<u32, Rec>) -> Tree {+ let tot = totals(&recs, false);+ let mut kids: HashMap<u32, Vec<u32>> = HashMap::new();+ for (&id, r) in &recs {+ if id != ROOT && tot.contains_key(&id) {+ kids.entry(r.parent).or_default().push(id);+ }+ }+ for v in kids.values_mut() {+ v.sort_by_key(|id| std::cmp::Reverse(tot[id]));+ }+ Tree { recs, tot, kids }+}++#[derive(Default)]+struct App {+ tree: Option<Tree>,+ drive: char,+ cur: u32,+ status: String,+ cells: Vec<(RECT, u32)>,+ hot: Option<usize>,+ dpi: i32,+ font: isize,+}+thread_local! { static APP: RefCell<App> = RefCell::new(App { drive: 'C', cur: ROOT, dpi: 96, ..Default::default() }) }++fn wide(s: &str) -> Vec<u16> {+ s.encode_utf16().chain([0]).collect()+}++/// Squarified treemap: `items` (id, size) biggest first, laid out in the rectangle (x, y, w, h).+fn squarify(items: &[(u32, u64)], (mut x, mut y, mut w, mut h): (f64, f64, f64, f64)) -> Vec<(u32, [f64; 4])> {+ let total: f64 = items.iter().map(|i| i.1 as f64).sum();+ let mut out = vec![];+ if total <= 0.0 || w <= 0.0 || h <= 0.0 {+ return out;+ }+ let scale = w * h / total;+ let area = |k: usize| items[k].1 as f64 * scale;+ let mut i = 0;+ while i < items.len() {+ let side = w.min(h);+ let worst = |s: f64, mx: f64, mn: f64| (side * side * mx / (s * s)).max(s * s / (side * side * mn));+ let (mut j, mut s, mut mx, mut mn) = (i + 1, area(i), area(i), area(i));+ let mut cur = worst(s, mx, mn);+ while j < items.len() {+ let a = area(j);+ let next = worst(s + a, mx.max(a), mn.min(a));+ if next > cur {+ break;+ }+ (s, mx, mn, cur, j) = (s + a, mx.max(a), mn.min(a), next, j + 1);+ }+ if w >= h {+ // a column on the left+ let (cw, mut yy) = (s / h, y);+ for k in i..j {+ let ch = area(k) / cw;+ out.push((items[k].0, [x, yy, x + cw, yy + ch]));+ yy += ch;+ }+ x += cw;+ w -= cw;+ } else {+ // a row on top+ let (rh, mut xx) = (s / w, x);+ for k in i..j {+ let cw = area(k) / rh;+ out.push((items[k].0, [xx, y, xx + cw, y + rh]));+ xx += cw;+ }+ y += rh;+ h -= rh;+ }+ i = j;+ }+ out+}++/// Stable colour per extension / folder name (folders darker than files).+fn color(name: &str, dir: bool) -> u32 {+ let key = if dir { name } else { name.rsplit_once('.').map_or("", |e| e.1) };+ let hue = (key.bytes().fold(7u32, |a, b| a.wrapping_mul(31).wrapping_add(b.to_ascii_lowercase() as u32)) % 360) as f64;+ let (s, v) = if dir { (0.35, 0.42) } else { (0.5, 0.72) };+ let f = |n: f64| {+ let k = (n + hue / 60.0) % 6.0;+ ((v - v * s * k.min(4.0 - k).clamp(0.0, 1.0)) * 255.0) as u8+ };+ rgb(f(5.0), f(3.0), f(1.0))+}++fn fixed_drives() -> Vec<char> {+ let mask = unsafe { GetLogicalDrives() };+ ('A'..='Z').filter(|c| mask & (1 << (*c as u8 - b'A')) != 0 && unsafe { GetDriveTypeW(wide(&format!("{c}:\\")).as_ptr()) } == DRIVE_FIXED).collect()+}++fn rescan(hwnd: HWND, drive: char) {+ APP.with_borrow_mut(|a| {+ (a.tree, a.drive, a.cur, a.hot, a.cells) = (None, drive, ROOT, None, vec![]);+ a.status = format!("Reading the MFT of {drive}: ...");+ });+ unsafe { InvalidateRect(hwnd, null(), 0) };+ let h = hwnd as isize;+ std::thread::spawn(move || {+ let r: Result<Tree, String> = scan(drive).map(build);+ unsafe { PostMessageW(h as HWND, WM_DONE, 0, Box::into_raw(Box::new(r)) as isize) };+ });+}++unsafe fn paint(hwnd: HWND) {+ unsafe {+ let mut ps: PAINTSTRUCT = std::mem::zeroed();+ let dc = BeginPaint(hwnd, &mut ps);+ let mut rc: RECT = std::mem::zeroed();+ GetClientRect(hwnd, &mut rc);+ let (w, h) = (rc.right, rc.bottom);+ let mem = CreateCompatibleDC(dc);+ let bmp = CreateCompatibleBitmap(dc, w, h);+ let old = SelectObject(mem, bmp);+ APP.with_borrow_mut(|a| {+ let k = a.dpi as f64 / 96.0;+ let (top, bot) = ((44.0 * k) as i32, (30.0 * k) as i32);+ let fill = |r: &RECT, c: u32| {+ let b = CreateSolidBrush(c);+ FillRect(mem, r, b);+ DeleteObject(b as _);+ };+ fill(&rc, BG);+ SelectObject(mem, a.font as _);+ SetBkMode(mem, TRANSPARENT as _);+ let text = |s: &str, mut r: RECT, c: u32, fmt: u32| {+ SetTextColor(mem, c);+ let t = wide(s);+ DrawTextW(mem, t.as_ptr(), -1, &mut r, fmt);+ };+ let one = DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS | DT_NOPREFIX;+ a.cells.clear();+ let mut head = format!("{}:", a.drive);+ let mut foot = a.status.clone();+ if let Some(t) = &a.tree {+ head = path_of(&t.recs, a.cur, a.drive).0;+ let items: Vec<(u32, u64)> = t.kids.get(&a.cur).map_or(vec![], |v| v.iter().take(MAX_CELLS).map(|&id| (id, t.tot[&id])).collect());+ let pad = 8.0 * k;+ for (id, r) in squarify(&items, (pad, top as f64, w as f64 - 2.0 * pad, (h - top - bot) as f64 - pad)) {+ a.cells.push((RECT { left: r[0] as i32, top: r[1] as i32, right: r[2] as i32, bottom: r[3] as i32 }, id));+ }+ for (n, (c, id)) in a.cells.iter().enumerate() {+ let rec = &t.recs[id];+ let inner = RECT { left: c.left + 1, top: c.top + 1, right: c.right - 1, bottom: c.bottom - 1 };+ fill(&inner, color(&rec.name, rec.dir));+ if a.hot == Some(n) {+ let b = CreateSolidBrush(rgb(255, 255, 255));+ FrameRect(mem, &inner, b);+ DeleteObject(b as _);+ }+ if inner.right - inner.left > (70.0 * k) as i32 && inner.bottom - inner.top > (34.0 * k) as i32 {+ let r = RECT { left: inner.left + 6, top: inner.top + 4, right: inner.right - 4, bottom: inner.bottom - 2 };+ text(&format!("{}\n{}", rec.name, human(t.tot[id])), r, rgb(255, 255, 255), DT_LEFT | DT_TOP | DT_WORDBREAK | DT_END_ELLIPSIS | DT_NOPREFIX);+ }+ }+ let size = if a.cur == ROOT { t.tot.values().max().copied().unwrap_or(0) } else { t.tot.get(&a.cur).copied().unwrap_or(0) };+ head = format!("{head} {}", human(size));+ foot = match a.hot.and_then(|n| a.cells.get(n)) {+ Some((_, id)) => format!("{} {}", path_of(&t.recs, *id, a.drive).0, human(t.tot[id])),+ None => "Click: open folder / show file Right click, Backspace: up Tab: next drive F5: rescan".into(),+ };+ }+ text(&head, RECT { left: (12.0 * k) as i32, top: 0, right: w - 12, bottom: top }, ACCENT, one);+ text(&foot, RECT { left: (12.0 * k) as i32, top: h - bot, right: w - 12, bottom: h }, DIM, one);+ });+ BitBlt(dc, 0, 0, w, h, mem, 0, 0, SRCCOPY);+ SelectObject(mem, old);+ DeleteObject(bmp as _);+ DeleteDC(mem);+ EndPaint(hwnd, &ps);+ }+}++fn up(hwnd: HWND) {+ APP.with_borrow_mut(|a| {+ if let (Some(t), true) = (&a.tree, a.cur != ROOT) {+ a.cur = t.recs.get(&a.cur).map_or(ROOT, |r| r.parent);+ a.hot = None;+ }+ });+ unsafe { InvalidateRect(hwnd, null(), 0) };+}++unsafe extern "system" fn proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {+ unsafe {+ match msg {+ WM_CREATE => {+ let dpi = GetDpiForSystem() as i32;+ let f = CreateFontW(-(15 * dpi / 96), 0, 0, 0, 400, 0, 0, 0, 1, 0, 0, 5, 0, wide("Segoe UI").as_ptr());+ APP.with_borrow_mut(|a| (a.dpi, a.font) = (dpi, f as isize));+ 0+ }+ WM_PAINT => {+ paint(hwnd);+ 0+ }+ WM_ERASEBKGND => 1,+ WM_DONE => {+ match *Box::from_raw(lp as *mut Result<Tree, String>) {+ Ok(t) => APP.with_borrow_mut(|a| {+ a.status = String::new();+ a.tree = Some(t);+ }),+ Err(e) => APP.with_borrow_mut(|a| a.status = e),+ }+ InvalidateRect(hwnd, null(), 0);+ 0+ }+ WM_MOUSEMOVE => {+ let (x, y) = ((lp & 0xFFFF) as i16 as i32, (lp >> 16) as i16 as i32);+ let changed = APP.with_borrow_mut(|a| {+ let n = a.cells.iter().position(|(r, _)| x >= r.left && x < r.right && y >= r.top && y < r.bottom);+ std::mem::replace(&mut a.hot, n) != n+ });+ if changed {+ InvalidateRect(hwnd, null(), 0);+ }+ 0+ }+ WM_LBUTTONDOWN => {+ let act = APP.with_borrow_mut(|a| {+ let id = a.hot.and_then(|n| a.cells.get(n))?.1;+ let t = a.tree.as_ref()?;+ if t.recs[&id].dir {+ let p = None;+ (a.cur, a.hot) = (id, None);+ p+ } else {+ Some(path_of(&t.recs, id, a.drive).0)+ }+ });+ if let Some(p) = act {+ // show the file in Explorer (delete it from there)+ ShellExecuteW(null_mut(), wide("open").as_ptr(), wide("explorer.exe").as_ptr(), wide(&format!("/select,\"{p}\"")).as_ptr(), null(), SW_SHOWNORMAL);+ }+ InvalidateRect(hwnd, null(), 0);+ 0+ }+ WM_RBUTTONDOWN => {+ up(hwnd);+ 0+ }+ WM_KEYDOWN => {+ match wp as u16 {+ VK_ESCAPE => {+ DestroyWindow(hwnd);+ }+ VK_BACK => up(hwnd),+ VK_F5 => rescan(hwnd, APP.with_borrow(|a| a.drive)),+ VK_TAB => {+ let (d, all) = (APP.with_borrow(|a| a.drive), fixed_drives());+ if let Some(n) = all.iter().position(|&c| c == d) {+ rescan(hwnd, all[(n + 1) % all.len()]);+ }+ }+ _ => {}+ }+ 0+ }+ WM_DESTROY => {+ PostQuitMessage(0);+ 0+ }+ _ => DefWindowProcW(hwnd, msg, wp, lp),+ }+ }+}++fn main() {+ unsafe {+ let drive = std::env::args().nth(1).and_then(|a| a.chars().next()).filter(char::is_ascii_alphabetic).map_or('C', |c| c.to_ascii_uppercase());+ if IsUserAnAdmin() == 0 {+ // raw volume access needs it: ask once through UAC and let the elevated copy do the work+ let exe = std::env::current_exe().map(|p| p.display().to_string()).unwrap_or_default();+ ShellExecuteW(null_mut(), wide("runas").as_ptr(), wide(&exe).as_ptr(), wide(&format!("{drive}:")).as_ptr(), null(), SW_SHOWNORMAL);+ return;+ }+ SetProcessDPIAware();+ let (inst, class) = (GetModuleHandleW(null()), wide("WinRustDisk"));+ let wc = WNDCLASSW { style: 0, lpfnWndProc: Some(proc), cbClsExtra: 0, cbWndExtra: 0, hInstance: inst, hIcon: null_mut(), hCursor: LoadCursorW(null_mut(), IDC_ARROW), hbrBackground: null_mut(), lpszMenuName: null(), lpszClassName: class.as_ptr() };+ RegisterClassW(&wc);+ let hwnd = CreateWindowExW(0, class.as_ptr(), wide("WinRust Disk").as_ptr(), WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, 1280, 800, null_mut(), null_mut(), inst, null());+ rescan(hwnd, drive);+ let mut m: MSG = std::mem::zeroed();+ while GetMessageW(&mut m, null_mut(), 0, 0) > 0 {+ TranslateMessage(&m);+ DispatchMessageW(&m);+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn treemap_fills_the_rect_and_keeps_size_ratios() {+ let items = [(1, 600), (2, 300), (3, 200), (4, 100), (5, 100)];+ let cells = squarify(&items, (0.0, 0.0, 400.0, 300.0));+ assert_eq!(cells.len(), 5);+ let a = |id: u32| {+ let r = cells.iter().find(|c| c.0 == id).unwrap().1;+ (r[2] - r[0]) * (r[3] - r[1])+ };+ let total: f64 = (1..=5).map(a).sum();+ assert!((total - 120_000.0).abs() < 1.0, "area {total}");+ assert!((a(1) / a(2) - 2.0).abs() < 1e-6);+ }+}diff --git a/scripts/bench.ps1 b/scripts/bench.ps1new file mode 100644index 0000000..7b1d5fd--- /dev/null+++ b/scripts/bench.ps1@@ -0,0 +1,27 @@+# Run from an ADMIN PowerShell: powershell -ExecutionPolicy Bypass -File scripts\bench.ps1 [term]+# Compares our rs.exe / Task manager.exe with Windows Search / Taskmgr.exe. Changes nothing on the system.+param([string]$term = 'notepad')+$root = Split-Path $PSScriptRoot+$rs = Join-Path $root 'payload\rs.exe'+$tm = Join-Path $root 'payload\Task manager.exe'+function Mem($exe, $name) {+ $p = Start-Process $exe -PassThru; Start-Sleep 5; $p.Refresh()+ $o = "{0}: WS {1} MB, private {2} MB, CPU {3:N1}s" -f $name, [math]::Round($p.WorkingSet64/1MB,1), [math]::Round($p.PrivateMemorySize64/1MB,1), $p.TotalProcessorTime.TotalSeconds+ Stop-Process $p -Force; $o+}+"== Search for '$term' =="+1..3 | ForEach-Object {+ $t = Measure-Command { $n = (& $rs $term | Measure-Object -Line).Lines }+ "rs.exe run $_ : {0:N0} ms, {1} lines" -f $t.TotalMilliseconds, $n+}+try {+ $c = New-Object -ComObject ADODB.Connection+ $c.Open("Provider=Search.CollatorDSO;Extended Properties='Application=Windows';")+ 1..3 | ForEach-Object {+ $t = Measure-Command { $r = $c.Execute("SELECT System.ItemPath FROM SystemIndex WHERE System.FileName LIKE '%$term%'"); $k = 0; while (-not $r.EOF) { $k++; $r.MoveNext() } }+ "Windows Search run $_ : {0:N0} ms, {1} rows" -f $t.TotalMilliseconds, $k+ }+} catch { "Windows Search: unavailable ($($_.Exception.Message))" }+"== Task manager =="+Mem $tm 'ours'+Mem 'C:\Windows\System32\Taskmgr.exe' 'Windows Taskmgr'diff --git a/scripts/build-all.ps1 b/scripts/build-all.ps1new file mode 100644index 0000000..90401dc--- /dev/null+++ b/scripts/build-all.ps1@@ -0,0 +1,27 @@+# Syncs plugins\ from the original project folders, rebuilds every plugin, refreshes payload\ (+ STAMPS.txt),+# then rebuilds the launcher (one self-contained exe). Ends with a stamp check: any mismatch fails the script.+$ErrorActionPreference = 'Stop'+$root = Split-Path $PSScriptRoot+$sync = "$PSScriptRoot\sync.ps1"+& $sync | Out-Null+function Build($dir) { Push-Location "$root\plugins\$dir"; cargo build --release; if ($LASTEXITCODE) { throw "build failed: $dir" }; Pop-Location }+Build 'rust-search'+Build 'rtaskmgr-win32'+Build 'topbar'+Build 'rs-du'+Build 'rust-explorer'+Build 'rs-shell'+foreach ($t in 'wiztree', 'photoview', 'debloat') { Build $t; Copy-Item "$root\plugins\$t\target\release\$t.exe" "$root\payload" -Force }+Push-Location "$root\ReShell"; cargo build --release; if ($LASTEXITCODE) { throw 'build failed: ReShell' }; Pop-Location+Copy-Item "$root\ReShell\target\release\reshell.exe" "$root\payload" -Force+Copy-Item "$root\plugins\topbar\target\release\topbar.exe" "$root\payload" -Force+Copy-Item "$root\plugins\rs-du\target\release\rs-du.exe" "$root\payload" -Force+Copy-Item "$root\plugins\rust-explorer\target\release\rust-explorer.exe", "$root\plugins\rs-shell\target\release\rs-shell.exe" "$root\payload" -Force+$rs = "$root\plugins\rust-search\target\release"+Copy-Item "$rs\rs.exe", "$rs\rs-launcher.exe" "$root\payload" -Force+Copy-Item "$root\plugins\rtaskmgr-win32\target\release\rtaskmgr-win32.exe" "$root\payload\Task manager.exe" -Force+& $sync -Stamp | Out-Null+Push-Location $root; cargo build --release; if ($LASTEXITCODE) { throw 'launcher build failed' }; Pop-Location+& $sync -Check+if ($LASTEXITCODE) { throw 'stamp mismatch' }+Write-Host "done: $root\target\release\plugin-launcher.exe"diff --git a/scripts/dev-update.ps1 b/scripts/dev-update.ps1new file mode 100644index 0000000..b21dd37--- /dev/null+++ b/scripts/dev-update.ps1@@ -0,0 +1,22 @@+# Rebuild one piece and swap it into %LOCALAPPDATA%\plugin-launcher\bin (set up by user-mode.ps1). No admin, no UAC.+# powershell -ExecutionPolicy Bypass -File scripts\dev-update.ps1 <topbar|rs-shell|rust-explorer|reshell>+# topbar / reshell are restarted by rs-shell within ~6 s; rs-shell and rust-explorer take effect at the next sign-in+# (or restart rust-explorer --desktop yourself). Never kills rs-shell: it is the session's shell.+param([Parameter(Mandatory)][ValidateSet('topbar', 'rs-shell', 'rust-explorer', 'reshell')][string]$Name)+$ErrorActionPreference = 'Stop'+$root = Split-Path $PSScriptRoot+$bin = "$env:LOCALAPPDATA\plugin-launcher\bin"+$dir = @{ 'topbar' = "$root\plugins\topbar"; 'rs-shell' = "$root\plugins\rs-shell"; 'rust-explorer' = "$root\plugins\rust-explorer"; 'reshell' = "$root\ReShell" }[$Name]+$exe = "$Name.exe"+if (-not (Test-Path "$bin\rs-shell.exe")) { throw "run scripts\user-mode.ps1 first" }+Push-Location $dir; cargo build --release; $rc = $LASTEXITCODE; Pop-Location+if ($rc -ne 0) { throw "cargo build failed" }+$to = "$bin\$exe"+if (Test-Path $to) { Rename-Item $to ("$exe." + (Get-Date -Format HHmmssfff) + '.old') -Force }+Copy-Item "$dir\target\release\$exe" $to -Force+Get-ChildItem $bin -Filter "$exe.*.old" | ForEach-Object { Remove-Item $_.FullName -Force -ErrorAction SilentlyContinue }+switch ($Name) {+ 'topbar' { Stop-Process -Name topbar -Force -ErrorAction SilentlyContinue; "topbar stopped: rs-shell starts the new one in a few seconds" }+ 'reshell' { Stop-Process -Name reshell -Force -ErrorAction SilentlyContinue; Start-Process $to -WindowStyle Hidden; "reshell restarted" }+ default { "$exe replaced: takes effect at the next sign-in" }+}diff --git a/scripts/sync.ps1 b/scripts/sync.ps1new file mode 100644index 0000000..0233d1f--- /dev/null+++ b/scripts/sync.ps1@@ -0,0 +1,37 @@+# Keeps plugins\<name> identical to the original project folder and stamps what the payload exes were built from.+# sync.ps1 copy originals -> plugins\ (originals win), then report+# sync.ps1 -Check only report; exit 1 on any mismatch+# A stamp = short SHA-256 over every source file (path + content), target\ and .git\ excluded.+# sync.ps1 -Stamp (used by build-all.ps1) record what the payload exes were just built from+param([switch]$Check, [switch]$Stamp)+$ErrorActionPreference = 'Stop'+$root = Split-Path $PSScriptRoot+$desk = Split-Path $root+$orig = @{ 'rust-search' = "$desk\rust-search"; 'rtaskmgr-win32' = "$desk\rtaskmgr-win32" }+$stampFile = "$root\payload\STAMPS.txt"++function Stamp($dir) {+ $parts = Get-ChildItem $dir -Recurse -File | Where-Object { $_.FullName -notmatch '\\(target|dist|backup-v1|\.git)\\' } | Sort-Object FullName |+ ForEach-Object { $_.FullName.Substring($dir.Length) + ':' + (Get-FileHash $_.FullName -Algorithm SHA256).Hash }+ $sha = [Security.Cryptography.SHA256]::Create()+ -join ($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($parts -join "`n")) | Select-Object -First 6 | ForEach-Object { $_.ToString('x2') })+}+function Built($name) {+ if (Test-Path $stampFile) { foreach ($l in Get-Content $stampFile) { $n, $s = $l -split ' '; if ($n -eq $name) { return $s } } }+ '-'+}++if (-not $Check) {+ foreach ($n in $orig.Keys) {+ robocopy $orig[$n] "$root\plugins\$n" /MIR /XD target dist backup-v1 .git /NFL /NDL /NJH /NJS /NP | Out-Null+ if ($LASTEXITCODE -ge 8) { throw "robocopy failed for $n ($LASTEXITCODE)" }+ }+}+if ($Stamp) { ($orig.Keys | ForEach-Object { "$_ $(Stamp "$root\plugins\$_")" }) | Set-Content $stampFile }+$bad = 0+foreach ($n in $orig.Keys) {+ $o = Stamp $orig[$n]; $c = Stamp "$root\plugins\$n"; $b = Built $n+ $state = if ($o -ne $c) { $bad++; 'COPY STALE: run scripts\sync.ps1' } elseif ($c -ne $b) { $bad++; 'PAYLOAD STALE: run scripts\build-all.ps1' } else { 'ok' }+ '{0,-15} original {1} plugins\ {2} payload built from {3} {4}' -f $n, $o, $c, $b, $state+}+if ($Check -and $bad) { exit 1 }diff --git a/scripts/update-plugin.ps1 b/scripts/update-plugin.ps1new file mode 100644index 0000000..d9a95a5--- /dev/null+++ b/scripts/update-plugin.ps1@@ -0,0 +1,54 @@+# Rebuilds ONE plugin (and what ships with it), copies the exes to payload\ and runs `plugin-launcher update`: no launcher rebuild.+# scripts\update-plugin.ps1 rust-search|rtaskmgr-win32|topbar|rust-explorer+# Build + copy need no admin. The update step does: from a normal shell this script asks for it via a UAC prompt (the user clicks Yes),+# then prints the last lines of %ProgramData%\plugin-launcher\install.log (the elevated window's own output is lost).+param([Parameter(Mandatory)][ValidateSet('rust-search', 'rtaskmgr-win32', 'topbar', 'rust-explorer', 'wiztree', 'photoview', 'debloat')][string]$name)+$ErrorActionPreference = 'Stop'+$root = Split-Path $PSScriptRoot+function Build($dir) { Push-Location $dir; cargo build --release; if ($LASTEXITCODE) { throw "build failed: $dir" }; Pop-Location }+$p = "$root\payload"+if ($name -in 'rust-search', 'rtaskmgr-win32') { & "$PSScriptRoot\sync.ps1" | Out-Null } # these two are edited in their original folders on the desktop+switch ($name) {+ 'rust-search' {+ Build "$root\plugins\rust-search"; $r = "$root\plugins\rust-search\target\release"+ Copy-Item "$r\rs.exe", "$r\rs-launcher.exe" $p -Force+ }+ 'rtaskmgr-win32' {+ Build "$root\plugins\rtaskmgr-win32"; Build "$root\plugins\rs-du"+ Copy-Item "$root\plugins\rtaskmgr-win32\target\release\rtaskmgr-win32.exe" "$p\Task manager.exe" -Force+ Copy-Item "$root\plugins\rs-du\target\release\rs-du.exe" $p -Force+ }+ 'topbar' { # reshell and rs-du are installed together with topbar+ Build "$root\plugins\topbar"; Build "$root\plugins\rs-du"; Build "$root\ReShell"+ Copy-Item "$root\plugins\topbar\target\release\topbar.exe" $p -Force+ Copy-Item "$root\plugins\rs-du\target\release\rs-du.exe" $p -Force+ Copy-Item "$root\ReShell\target\release\reshell.exe" $p -Force+ }+ { $_ -in 'wiztree', 'photoview', 'debloat' } { # stand-alone: one exe each (wiztree reads the MFT through rs-du\src\mft.rs)+ Build "$root\plugins\$name"+ Copy-Item "$root\plugins\$name\target\release\$name.exe" $p -Force+ }+ 'rust-explorer' { # rs-shell --overlay starts topbar and the desktop at logon+ Build "$root\plugins\rust-explorer"; Build "$root\plugins\rs-shell"+ Copy-Item "$root\plugins\rust-explorer\target\release\rust-explorer.exe", "$root\plugins\rs-shell\target\release\rs-shell.exe" $p -Force+ }+}+$exe = "$root\target\release\plugin-launcher.exe"+if (-not (Test-Path $exe)) { throw "build the launcher once first: cargo build --release in $root" }+# Started through explorer.exe, never as our child: from a packaged app (the Claude desktop app is MSIX) every child process,+# the elevated launcher included, writes HKCU into the package's private copy of the registry, which the real session+# never sees (Run keys, ReplaceExplorer, folder verbs were silently lost that way). Explorer asks for admin (UAC) itself.+$log = "$env:ProgramData\plugin-launcher\install.log"+$before = if (Test-Path $log) { @(Get-Content $log -Encoding UTF8).Count } else { 0 }+$lnk = "$root\target\update-$name.lnk"+$s = (New-Object -ComObject WScript.Shell).CreateShortcut($lnk); $s.TargetPath = $exe; $s.Arguments = "update $name"; $s.Save()+Start-Process explorer.exe -ArgumentList "`"$lnk`""+# explorer returns at once: wait for the launcher's verdict in the log (the user may take a while to answer UAC)+$deadline = (Get-Date).AddMinutes(5)+do {+ Start-Sleep 2+ $new = if (Test-Path $log) { @(Get-Content $log -Encoding UTF8 | Select-Object -Skip $before) } else { @() }+} until (($new -match "^\[\d+\] ${name}: ") -or (Get-Date) -gt $deadline)+Remove-Item $lnk -ErrorAction SilentlyContinue+if (-not ($new -match "^\[\d+\] ${name}: ")) { Write-Warning "no result in $log after 5 minutes (UAC declined?)" }+$new | Select-Object -Last 4diff --git a/scripts/user-mode.ps1 b/scripts/user-mode.ps1new file mode 100644index 0000000..0391311--- /dev/null+++ b/scripts/user-mode.ps1@@ -0,0 +1,58 @@+# Puts topbar, reshell, rust-explorer and rs-shell into %LOCALAPPDATA%\plugin-launcher\bin (a folder you own: updates never need+# admin) and starts them at sign-in from your Run key as an OVERLAY on top of explorer.exe, which stays the real shell.+# (Replacing the shell itself stopped working: Windows no longer started our rs-shell at logon.) Run from a NORMAL PowerShell:+# powershell -ExecutionPolicy Bypass -File scripts\user-mode.ps1 install / refresh+# powershell -ExecutionPolicy Bypass -File scripts\user-mode.ps1 -Undo remove the Run entry and the shell override+# The old elevated "topbar" logon task would start a second bar: it is deleted once with+# schtasks /delete /tn topbar /f (administrator PowerShell; the script prints this if the task still exists)+param([switch]$Undo)+$ErrorActionPreference = 'Stop'+$root = Split-Path $PSScriptRoot+$bin = "$env:LOCALAPPDATA\plugin-launcher\bin"+$winlogon = 'HKCU\Software\Microsoft\Windows NT\CurrentVersion\Winlogon'+$run = 'HKCU\Software\Microsoft\Windows\CurrentVersion\Run'++# our own Shell override (if any) is never wanted any more+cmd /c "reg delete `"$winlogon`" /v Shell /f >nul 2>&1"++$folderKeys = 'HKCU:\Software\Classes\Directory\shell\open', 'HKCU:\Software\Classes\Folder\shell\open', 'HKCU:\Software\Classes\Drive\shell\open'++if ($Undo) {+ cmd /c "reg delete `"$run`" /v rs-overlay /f >nul 2>&1"+ foreach ($k in $folderKeys) { Remove-Item $k -Recurse -ErrorAction SilentlyContinue } # only our HKCU overrides; the system's verbs stay+ 'overlay: removed from sign-in, folders open in Explorer again (files in ' + $bin + ' left alone)'+ return+}++$src = @{+ 'rs-shell.exe' = "$root\plugins\rs-shell\target\release\rs-shell.exe"+ 'rust-explorer.exe' = "$root\plugins\rust-explorer\target\release\rust-explorer.exe"+ 'topbar.exe' = "$root\plugins\topbar\target\release\topbar.exe"+ 'reshell.exe' = "$root\ReShell\target\release\reshell.exe"+}+foreach ($k in $src.Keys) { if (-not (Test-Path $src[$k])) { throw "missing $($src[$k]): build it first (cargo build --release in that folder)" } }+New-Item -ItemType Directory $bin -Force | Out-Null+foreach ($k in $src.Keys) {+ $to = "$bin\$k"+ # a running exe cannot be overwritten but can be renamed+ if (Test-Path $to) { Rename-Item $to ("$k." + (Get-Date -Format HHmmssfff) + '.old') -Force }+ Copy-Item $src[$k] $to -Force+}+Get-ChildItem $bin -Filter *.old -ErrorAction SilentlyContinue | ForEach-Object { Remove-Item $_.FullName -Force -ErrorAction SilentlyContinue }+reg add $run /v rs-overlay /t REG_SZ /d "`"$bin\rs-shell.exe`" --overlay" /f | Out-Null+"overlay: starts at sign-in from $bin"+# Folders and drives opened from other programs / the desktop / Win+R open in rust-explorer. DelegateExecute is emptied on+# purpose: while it is set, Windows ignores the command and uses Explorer's built-in handler.+foreach ($k in $folderKeys) {+ New-Item "$k\command" -Force | Out-Null+ Set-ItemProperty "$k\command" -Name '(default)' -Value "`"$bin\rust-explorer.exe`" `"%1`""+ Set-ItemProperty "$k\command" -Name 'DelegateExecute' -Value ''+}+'folders: open in rust-explorer (undo: scripts\user-mode.ps1 -Undo)'+cmd /c "schtasks /query /tn topbar >nul 2>&1" # through cmd: schtasks' stderr would be a terminating error under $ErrorActionPreference = Stop+if ($LASTEXITCODE -eq 0) {+ ''+ 'ONE admin step (administrator PowerShell, once): schtasks /delete /tn topbar /f'+}+''+"done. Update later with: scripts\dev-update.ps1 <topbar|rs-shell|rust-explorer|reshell> (no admin)"diff --git a/src/main.rs b/src/main.rsnew file mode 100644index 0000000..5d9aaef--- /dev/null+++ b/src/main.rs@@ -0,0 +1,1353 @@+// Plugin Launcher: a small dark Win32 window that installs / removes plugins (rust-search; chrome-rs is a stub).+// Binaries come from next to this exe, else ..\rust-search\target\release. Needs admin (see app.manifest).+#![windows_subsystem = "windows"]+#![allow(unsafe_op_in_unsafe_fn)]+use std::{+ cell::Cell,+ env, fs,+ io::Write,+ mem::{size_of, zeroed},+ os::windows::process::CommandExt,+ path::{Path, PathBuf},+ process::Command,+ ptr::{null, null_mut},+ sync::{+ Mutex,+ atomic::{AtomicBool, AtomicUsize, Ordering::Relaxed},+ },+ thread,+};+use windows_sys::Win32::{+ Foundation::*,+ Graphics::{+ Dwm::DwmSetWindowAttribute,+ Gdi::*,+ GdiPlus::{+ FillModeAlternate, GdipAddPathArc, GdipClosePathFigure, GdipCreateFromHDC, GdipCreatePath, GdipCreateSolidFill, GdipDeleteBrush, GdipDeleteGraphics, GdipDeletePath, GdipFillPath,+ GdipSetSmoothingMode, GdiplusStartup, GdiplusStartupInput, GpBrush, GpGraphics, GpPath, GpSolidFill, SmoothingModeAntiAlias,+ },+ },+ System::{Console::{ATTACH_PARENT_PROCESS, AttachConsole, GetStdHandle, STD_OUTPUT_HANDLE}, LibraryLoader::GetModuleHandleW},+ UI::{Input::KeyboardAndMouse::*, WindowsAndMessaging::*},+};++const BG: u32 = rgb(22, 19, 18);+const PANEL: u32 = rgb(36, 31, 29);+const BORDER: u32 = rgb(60, 51, 47);+const TEXT: u32 = rgb(255, 255, 255);+const DIM: u32 = rgb(166, 152, 145);+const ACCENT: u32 = rgb(222, 98, 42); // rust orange+const GOOD: u32 = rgb(110, 200, 120);+const BAD: u32 = rgb(255, 99, 97);+const WM_DONE: u32 = WM_APP + 1;+const WM_MOUSELEAVE: u32 = 0x02A3; // not exported by windows-sys under the enabled features++const fn rgb(r: u8, g: u8, b: u8) -> u32 {+ r as u32 | (g as u32) << 8 | (b as u32) << 16+}++struct Plugin {+ name: &'static str,+ desc: &'static str,+ warn: &'static str, // shown in a confirmation box before install+ installed: fn() -> bool,+ actions: Option<(fn() -> Result<(), String>, fn() -> Result<(), String>)>, // (install, uninstall); None = stub+ settings: bool, // shows a gear button that opens the plugin's settings panel+ bulk: bool, // part of the one-click "install everything" (the window lists only these); false = command line only+ glyph: &'static str, // Segoe MDL2 Assets icon+}+const PLUGINS: &[Plugin] = &[+ Plugin {+ name: "rust-search",+ desc: "Быстрый поиск файлов по NTFS (Alt+Space). Заменяет поиск Windows: служба WSearch отключается, SearchHost блокируется.",+ warn: "Служба поиска Windows (WSearch) будет ОТКЛЮЧЕНА, SearchHost.exe заблокирован, строка поиска на панели задач скрыта: поиск в Пуске, Проводнике и Outlook перестанет работать.",+ installed: || prog_dir().join("rs.exe").is_file(),+ actions: Some((install, uninstall)),+ settings: false,+ bulk: true,+ glyph: "\u{E721}", // search+ },+ Plugin {+ name: "rtaskmgr-win32",+ desc: "Диспетчер задач на Rust. Заменяет стандартный: Ctrl+Shift+Esc и запуск taskmgr.exe открывают его.",+ warn: "Стандартный диспетчер задач будет ЗАМЕНЁН: любой запуск taskmgr.exe откроет rtaskmgr-win32.",+ installed: || run("reg", &["query", TM_KEY, "/v", "Debugger"]).is_ok(),+ actions: Some((tm_install, tm_uninstall)),+ settings: false,+ bulk: true,+ glyph: "\u{E9D9}", // diagnostic+ },+ Plugin {+ name: "topbar",+ desc: "Нижняя панель в стиле Windows 11 вместо панели задач: окна, часы, меню. Стандартная панель скрывается. Вместе с ней ставятся хоткеи рабочих столов (Win+1/2/3, Win+`).",+ warn: "Панель задач Windows будет СКРЫТА и заменена панелью внизу экрана. Удаление плагина возвращает её.",+ installed: || bar_dir().join("topbar.exe").is_file(),+ actions: Some((bar_install, bar_uninstall)),+ settings: true,+ bulk: true,+ glyph: "\u{E700}", // menu+ },+ Plugin {+ name: "rust-explorer",+ desc: "Файловый менеджер на Rust вместо Проводника: папки и диски открываются в нём (Win+E тоже), рабочий стол рисует он сам. Обычный explorer.exe как оболочка ОТКЛЮЧАЕТСЯ. Нужен topbar.",+ warn: "ОБЫЧНЫЙ Explorer будет ОТКЛЮЧЁН: после установки панель задач, рабочий стол и окна папок дают topbar и rust-explorer. Сначала установите topbar, без него не будет панели. Ещё для экономии RAM отключаются службы DiagTrack, PcaSvc, InventorySvc, lfsvc (геолокация), cbdhsvc (журнал буфера Win+V), DoSvc ставится вручную, службы svchost объединяются (полностью после перезагрузки); удаление плагина вернёт их. Если что-то пойдёт не так: Ctrl+Alt+Del, Диспетчер задач, Запустить новую задачу, explorer.exe; затем удалите плагин.",+ installed: || rx_dir().join("rust-explorer.exe").is_file(),+ actions: Some((rx_install, rx_uninstall)),+ settings: false,+ bulk: true,+ glyph: "\u{E8B7}", // folder+ },+ Plugin {+ name: "wiztree",+ desc: "Анализ диска: карта занятого места (treemap) по MFT за секунды. Ярлык «WinRust Disk» в меню Пуск, запускается от администратора.",+ warn: "Ничего системного не меняется: файл в Program Files и ярлык в меню Пуск.",+ installed: || wz_dir().join("wiztree.exe").is_file(),+ actions: Some((wz_install, wz_uninstall)),+ settings: false,+ bulk: true,+ glyph: "\u{EDA2}", // hard drive+ },+ Plugin {+ name: "photoview",+ desc: "Просмотр фото: открывается мгновенно, листает папку стрелками, учитывает поворот из EXIF. Появляется в «Открыть с помощью» (по умолчанию не назначается).",+ warn: "Программа добавляется в «Открыть с помощью» для jpg, png, bmp, gif, tiff, webp, heic, avif. Приложением по умолчанию её делаете вы сами в Параметрах.",+ installed: || pv_dir().join("photoview.exe").is_file(),+ actions: Some((pv_install, pv_uninstall)),+ settings: false,+ bulk: true,+ glyph: "\u{E91B}", // picture+ },+ Plugin {+ name: "debloat",+ desc: "Отключает мусор Windows: телеметрию, Copilot, Recall, рекламу в Пуске, фон Edge. Только обратимое, старые значения запоминаются.",+ warn: "Будут ОТКЛЮЧЕНЫ несколько служб (телеметрия, карты, отчёты об ошибках) и выставлены политики реестра (Copilot, Recall, реклама, фон Edge; Edge покажет «управляется организацией»). Старые значения сохраняются, uninstall debloat возвращает всё. Приложения не удаляются.",+ installed: || db_dir().join("debloat.exe").is_file(),+ actions: Some((db_install, db_uninstall)),+ settings: false,+ bulk: false, // changes system behaviour: only on request, never as part of "install everything"+ glyph: "\u{E74D}", // delete+ },+ Plugin { name: "chrome-rs", desc: "Браузер на Rust. Установка пока недоступна (заглушка).", warn: "", installed: || false, actions: None, settings: false, bulk: true, glyph: "\u{E774}" }, // globe+];++static BUSY: AtomicBool = AtomicBool::new(false);+static JOB: AtomicUsize = AtomicUsize::new(usize::MAX); // what BUSY is working on: plugin index, or PLUGINS.len() = rollback+static INSTALLED: [AtomicBool; PLUGINS.len()] = [const { AtomicBool::new(false) }; PLUGINS.len()];+fn refresh() {+ for (p, f) in PLUGINS.iter().zip(&INSTALLED) {+ f.store((p.installed)(), Relaxed);+ }+}+static MSG: Mutex<(String, bool)> = Mutex::new((String::new(), true));+thread_local! { static SETTINGS: Cell<Option<usize>> = const { Cell::new(None) }; } // plugin whose settings panel is open+thread_local! { static HOVER: Cell<Option<usize>> = const { Cell::new(None) }; }++// ---------- install logic ----------++fn out(prog: &str, args: &[&str]) -> Result<String, String> {+ let o = Command::new(prog).args(args).creation_flags(0x0800_0000).output().map_err(|e| format!("{prog}: {e}"))?;+ if o.status.success() {+ Ok(String::from_utf8_lossy(&o.stdout).into_owned())+ } else {+ Err(format!("{prog} {}: {}{}", args.join(" "), String::from_utf8_lossy(&o.stdout).trim(), String::from_utf8_lossy(&o.stderr).trim()))+ }+}++fn run(prog: &str, args: &[&str]) -> Result<(), String> {+ out(prog, args).map(|_| ())+}++// Non-fatal failures of one install: shown as a count in the status line, spelled out in install.log.+static WARN: Mutex<Vec<String>> = Mutex::new(Vec::new());++fn soft(what: &str, r: Result<(), String>) {+ if let Err(e) = r {+ WARN.lock().unwrap().push(format!("{what}: {e}"));+ }+}++fn log(s: &str) {+ let d = PathBuf::from(env::var("ProgramData").unwrap_or_else(|_| r"C:\ProgramData".into())).join("plugin-launcher");+ let _ = fs::create_dir_all(&d);+ if let Ok(mut f) = fs::OpenOptions::new().create(true).append(true).open(d.join("install.log")) {+ let t = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());+ let _ = writeln!(f, "[{t}] {s}"); // shortcut: unix seconds, no date formatting; upgrade if the log gets read by humans a lot+ }+}++/// Copies over an exe that was just killed: taskkill returns before Windows (or an antivirus scan) releases the file, so retry ~6 s.+fn put(src: &Path, dst: &Path) -> Result<(), String> {+ let mut r = fs::copy(src, dst).map(|_| ());+ for _ in 0..30 {+ if !matches!(&r, Err(e) if e.raw_os_error() == Some(32) || e.raw_os_error() == Some(5)) {+ break;+ }+ thread::sleep(std::time::Duration::from_millis(200));+ r = fs::copy(src, dst).map(|_| ());+ }+ r.map_err(|e| format!("{}: {e}", dst.display()))+}++fn reg_dword(key: &str, name: &str) -> Option<u32> {+ let o = out("reg", &["query", key, "/v", name]).ok()?;+ let t = o.lines().find(|l| l.contains("REG_DWORD"))?.split_whitespace().last()?;+ u32::from_str_radix(t.trim_start_matches("0x"), 16).ok()+}++/// What the system looked like before the plugin touched it: HKLM\SOFTWARE\plugin-launcher\<plugin>. Written once+/// (an update must not overwrite the originals with our own values), read and deleted on uninstall.+const STATE: &str = r"HKLM\SOFTWARE\plugin-launcher\rust-search";+const WS_KEY: &str = r"HKLM\SYSTEM\CurrentControlSet\Services\WSearch";+const SB_KEY: &str = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Search";++fn save_dword(name: &str, v: Option<u32>) {+ if let (Some(v), None) = (v, reg_dword(STATE, name)) {+ let _ = run("reg", &["add", STATE, "/v", name, "/t", "REG_DWORD", "/d", &v.to_string(), "/f"]);+ }+}++const SH_KEY: &str = r"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\SearchHost.exe";+const TM_KEY: &str = r"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\taskmgr.exe";++const PAYLOAD: [(&str, &[u8]); 11] = [+ ("wiztree.exe", include_bytes!("../payload/wiztree.exe")),+ ("photoview.exe", include_bytes!("../payload/photoview.exe")),+ ("debloat.exe", include_bytes!("../payload/debloat.exe")),+ ("rust-explorer.exe", include_bytes!("../payload/rust-explorer.exe")),+ ("rs-shell.exe", include_bytes!("../payload/rs-shell.exe")),+ ("reshell.exe", include_bytes!("../payload/reshell.exe")),+ ("topbar.exe", include_bytes!("../payload/topbar.exe")),+ ("rs.exe", include_bytes!("../payload/rs.exe")),+ ("rs-launcher.exe", include_bytes!("../payload/rs-launcher.exe")),+ ("Task manager.exe", include_bytes!("../payload/Task manager.exe")),+ ("rs-du.exe", include_bytes!("../payload/rs-du.exe")),+];++/// Update without rebuilding the launcher: an exe in `payload\` next to this one (or two levels up, the cargo+/// target\release layout) wins over the embedded copy. Trust level = the launcher exe's own folder.+fn disk_payload() -> Option<PathBuf> {+ let exe = env::current_exe().ok()?;+ let d = exe.parent()?;+ [d.join("payload"), d.join(r"..\..\payload")].into_iter().find(|p| p.is_dir())+}++/// Unpacks the `need`ed bundled plugins, runs `f` on them, deletes them. The folder is under Program Files (admin-only writable),+/// not %TEMP%: a user-level process must not be able to swap an exe that is about to be installed as a SYSTEM task.+fn with_payload<T>(need: &[&str], f: impl FnOnce(&Path) -> Result<T, String>) -> Result<T, String> {+ let d = program_files().join(format!("plugin-launcher-tmp-{}", std::process::id()));+ fs::create_dir_all(&d).map_err(|e| format!("{}: {e}", d.display()))?;+ let disk = disk_payload();+ let unpack = |n: &&str| -> Result<(), String> {+ let bytes = PAYLOAD.iter().find(|(m, _)| m == n).ok_or(format!("нет {n} в сборке"))?.1;+ match disk.as_ref().map(|p| p.join(n)).filter(|p| p.is_file()) {+ Some(src) => {+ log(&format!("{n}: из {}", src.display()));+ fs::copy(src, d.join(n)).map(|_| ())+ }+ None => fs::write(d.join(n), bytes),+ }+ .map_err(|e| format!("распаковка {n}: {e}"))+ };+ let r = need.iter().try_for_each(unpack).and_then(|_| f(&d));+ let _ = fs::remove_dir_all(&d);+ r+}++fn program_files() -> PathBuf {+ PathBuf::from(env::var("ProgramFiles").unwrap_or(r"C:\Program Files".into()))+}++fn tm_dir() -> PathBuf {+ program_files().join("rtaskmgr")+}++fn bar_dir() -> PathBuf {+ program_files().join("topbar")+}++fn rx_dir() -> PathBuf {+ program_files().join("rust-explorer")+}++fn prog_dir() -> PathBuf {+ program_files().join("rs-search")+}++// shortcut: Windows makes at most one restore point per 24 h and it needs System Protection on; failures are ignored.+fn checkpoint() -> Result<(), String> {+ run("powershell", &["-NoProfile", "-Command", "Checkpoint-Computer -Description 'Plugin Launcher' -RestorePointType MODIFY_SETTINGS"])+}++// Image File Execution Options "Debugger": Windows starts our exe instead of taskmgr.exe (the system file stays untouched, so this is fully reversible).+fn tm_install() -> Result<(), String> {+ with_payload(&["Task manager.exe", "rs-du.exe"], |d| {+ let dst = tm_dir().join("rtaskmgr-win32.exe");+ let _ = run("taskkill", &["/f", "/im", "rtaskmgr-win32.exe"]); // an update: a running exe cannot be overwritten+ fs::create_dir_all(tm_dir()).map_err(|e| e.to_string())?;+ put(&d.join("Task manager.exe"), &dst)?;+ put(&d.join("rs-du.exe"), &tm_dir().join("rs-du.exe"))?;+ // the search (and the bar's Start panel) lists Start Menu shortcuts only, so without one the task manager is invisible to them+ soft("ярлык в меню Пуск не создан, поиск не увидит диспетчер", run("powershell", &["-NoProfile", "-Command", &format!("$s=(New-Object -ComObject WScript.Shell).CreateShortcut('{}'); $s.TargetPath='{}'; $s.Save()", tm_lnk().display(), dst.display())]));+ // elevated start without a UAC prompt (the exe re-launches itself through this task), so it can end protected processes+ let task = format!("$u=[Security.Principal.WindowsIdentity]::GetCurrent().Name; Register-ScheduledTask -TaskName rtaskmgr -Force -Action (New-ScheduledTaskAction -Execute '{}') -Principal (New-ScheduledTaskPrincipal -UserId $u -LogonType Interactive -RunLevel Highest) -Settings (New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances Parallel) | Out-Null", dst.display());+ soft("задача rtaskmgr не создана, запуск от администратора будет через UAC", run("powershell", &["-NoProfile", "-Command", &task]));+ run("reg", &["add", TM_KEY, "/v", "Debugger", "/t", "REG_SZ", "/d", &format!("\"{}\"", dst.display()), "/f"])+ })+}++fn tm_lnk() -> PathBuf {+ PathBuf::from(std::env::var("ProgramData").unwrap_or_else(|_| r"C:\ProgramData".into())).join(r"Microsoft\Windows\Start Menu\Programs\Task manager.lnk")+}++fn tm_uninstall() -> Result<(), String> {+ let _ = fs::remove_file(tm_lnk());+ let _ = run("schtasks", &["/delete", "/tn", "rtaskmgr", "/f"]);+ // registry first: with the exe gone, taskmgr.exe would not start at all. Only our value: the key may hold+ // other IFEO settings (e.g. mitigation policies) that are not ours to remove.+ run("reg", &["delete", TM_KEY, "/v", "Debugger", "/f"])?;+ let _ = run("taskkill", &["/f", "/im", "rtaskmgr-win32.exe"]);+ let _ = fs::remove_file(tm_dir().join("rtaskmgr-win32.exe"));+ cleaner_release(bar_dir().join("topbar.exe").is_file());+ Ok(())+}++/// rs-du (disk cleaner) lives in the task manager folder and is shared by rtaskmgr-win32 and the topbar menu:+/// it goes away only when the other plugin is gone too.+fn cleaner_release(other_installed: bool) {+ if !other_installed {+ let _ = fs::remove_file(tm_dir().join("rs-du.exe"));+ }+ let _ = fs::remove_dir(tm_dir()); // only succeeds when empty+}++const RUN_KEY: &str = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run";++// topbar.cfg next to topbar.exe (the bar re-reads it every few seconds). Missing file = OneDrive hidden.+fn cfg_path() -> PathBuf {+ bar_dir().join("topbar.cfg")+}++fn od_hidden() -> bool {+ fs::read_to_string(cfg_path()).map_or(true, |c| !c.contains("hide_onedrive=0"))+}++fn set_od_hidden(v: bool) -> Result<(), String> {+ fs::create_dir_all(bar_dir()).and_then(|_| fs::write(cfg_path(), format!("hide_onedrive={}\n", v as u8))).map_err(|e| e.to_string())+}++// PowerShell profile block (src/profile.ps1: zoxide, grep->rg, ll->eza, cat->bat) that lives exactly as long as topbar is installed.+// Written to Windows PowerShell 5.1 and, if installed, pwsh 7 (each has its own $PROFILE).+// shortcut: the elevated user's profile, which is the same account unless UAC asks for a different admin; upgrade if that matters.+const PS_STRIP: &str = r"$p=$PROFILE; $t=[string]$(if(Test-Path $p){Get-Content $p -Raw}); $t=[regex]::Replace($t,'(?s)# >>> topbar >>>.*?# <<< topbar <<<\r?\n?','');";+const PS_BLOCK: &str = include_str!("profile.ps1");+const SHELLS: [&str; 2] = ["powershell", "pwsh"];++fn profile_install() -> Result<(), String> {+ shells_run(&format!("{PS_STRIP}$b=@'\n{PS_BLOCK}'@; New-Item -Force -ItemType Directory (Split-Path $p) | Out-Null; Set-Content $p ($t.TrimEnd() + [Environment]::NewLine + $b) -Encoding utf8"))+}++fn profile_uninstall() -> Result<(), String> {+ // delete the file if nothing but our block was in it+ shells_run(&format!("{PS_STRIP} if($t.Trim()){{Set-Content $p $t -Encoding utf8}}elseif(Test-Path $p){{Remove-Item $p}}"))+}++/// Runs `script` in every shell. Only the first (always present) can fail the call: a missing pwsh is not an error.+fn shells_run(script: &str) -> Result<(), String> {+ let r = run(SHELLS[0], &["-NoProfile", "-Command", script]);+ let _ = run(SHELLS[1], &["-NoProfile", "-Command", script]);+ r+}++fn bar_install() -> Result<(), String> {+ with_payload(&["topbar.exe", "rs-du.exe", "reshell.exe"], |d| {+ let dst = bar_dir().join("topbar.exe");+ let _ = run("taskkill", &["/f", "/im", "topbar.exe"]);+ fs::create_dir_all(bar_dir()).map_err(|e| e.to_string())?;+ put(&d.join("topbar.exe"), &dst)?;+ fs::create_dir_all(tm_dir()).map_err(|e| e.to_string())?;+ put(&d.join("rs-du.exe"), &tm_dir().join("rs-du.exe"))?; // topbar menu "Чистильщик диска"+ let rsh = bar_dir().join("reshell.exe"); // Win+1/2/3 desktop hotkeys, no args = hotkeys+ let _ = run("taskkill", &["/f", "/im", "reshell.exe"]);+ put(&d.join("reshell.exe"), &rsh)?;+ run("reg", &["add", RUN_KEY, "/v", "reshell", "/t", "REG_SZ", "/d", &format!("\"{}\"", rsh.display()), "/f"])?;+ let _ = Command::new("explorer.exe").arg(&rsh).spawn();+ run(dst.to_str().unwrap(), &["--restore"])?; // clean state in case a killed instance left the taskbar hidden+ // The bar runs elevated (a task with the highest run level starts it at logon without a UAC prompt): that lets it close+ // elevated windows and click elevated apps' tray icons. It starts everything else through explorer, i.e. unelevated.+ // Fallback when the task cannot be made: the plain Run key and a normal-rights bar.+ let task = format!("$u=[Security.Principal.WindowsIdentity]::GetCurrent().Name; Register-ScheduledTask -TaskName topbar -Force -Action (New-ScheduledTaskAction -Execute '{}') -Trigger (New-ScheduledTaskTrigger -AtLogOn -User $u) -Principal (New-ScheduledTaskPrincipal -UserId $u -LogonType Interactive -RunLevel Highest) -Settings (New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero)) | Out-Null", dst.display());+ if run("powershell", &["-NoProfile", "-Command", &task]).is_ok() && run("schtasks", &["/run", "/tn", "topbar"]).is_ok() {+ let _ = run("reg", &["delete", RUN_KEY, "/v", "topbar", "/f"]);+ } else {+ WARN.lock().unwrap().push("задача topbar не создана: запуск через Run, без прав администратора".into());+ run("reg", &["add", RUN_KEY, "/v", "topbar", "/t", "REG_SZ", "/d", &format!("\"{}\"", dst.display()), "/f"])?;+ let _ = Command::new("explorer.exe").arg(&dst).spawn(); // normal user token, like rs-launcher+ }+ soft("профиль PowerShell не записан", profile_install()); // a shell nicety, must not fail the bar install+ Ok(())+ })+}++fn bar_uninstall() -> Result<(), String> {+ let _ = run("reg", &["delete", RUN_KEY, "/v", "topbar", "/f"]);+ let _ = run("schtasks", &["/delete", "/tn", "topbar", "/f"]);+ let _ = run("reg", &["delete", RUN_KEY, "/v", "reshell", "/f"]);+ let _ = run("taskkill", &["/f", "/im", "reshell.exe"]);+ let _ = run("taskkill", &["/f", "/im", "topbar.exe"]);+ let _ = profile_uninstall();+ let r = run(bar_dir().join("topbar.exe").to_str().unwrap(), &["--restore"]); // a killed bar cannot restore the taskbar itself+ let _ = fs::remove_dir_all(bar_dir());+ cleaner_release(tm_dir().join("rtaskmgr-win32.exe").is_file());+ r+}++// ---------- rust-explorer: file manager + Explorer replacement ----------+//+// Install: our files in Program Files, folders / drives opened from any program go to rust-explorer (HKCU class verbs of the+// installing user), rs-shell --overlay starts at sign-in and, with the ReplaceExplorer switch, ends the shell Explorer once topbar+// and the rust-explorer desktop are on screen. AutoRestartShell is set to 0 so Windows does not bring Explorer back.+// Uninstall puts everything back and starts Explorer again. rs-shell itself hands the session back to Explorer if topbar dies.+const RX_STATE: &str = r"HKLM\SOFTWARE\plugin-launcher\rust-explorer";+const WINLOGON_KEY: &str = r"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon";+const RX_SWITCH: &str = r"HKCU\Software\rs-shell";+const RX_FOLDERS: [&str; 3] = [r"HKCU\Software\Classes\Directory\shell\open", r"HKCU\Software\Classes\Folder\shell\open", r"HKCU\Software\Classes\Drive\shell\open"];++// svchost RAM trim, done with rust-explorer: (service, Start we set, Windows default). Uninstall puts back the Windows defaults,+// not the values found at install: they may already be our own (the same tweak was first run by hand).+// DoSvc's key is ACL-protected on some builds, so every step is soft: a refused one is only a warning.+const RX_SVCS: [(&str, u32, u32); 6] = [("DiagTrack", 4, 2), ("PcaSvc", 4, 2), ("InventorySvc", 4, 2), ("lfsvc", 4, 3), ("cbdhsvc", 4, 2), ("DoSvc", 3, 2)];+const SPLIT_KEY: &str = r"HKLM\SYSTEM\CurrentControlSet\Control";+const SPLIT_DEFAULT: u32 = 3670016; // 3.5 GB: above it Windows gives every service its own svchost++fn rx_trim(on: bool) {+ for (s, off, def) in RX_SVCS {+ let v = if on { off } else { def };+ soft(&format!("служба {s}"), run("reg", &["add", &format!(r"HKLM\SYSTEM\CurrentControlSet\Services\{s}"), "/v", "Start", "/t", "REG_DWORD", "/d", &v.to_string(), "/f"]));+ if on && off == 4 {+ let _ = run("sc.exe", &["stop", s]); // the per-user cbdhsvc_xxxx instance stops at the next sign-in+ }+ }+ let t = if on { 0x4000000 } else { SPLIT_DEFAULT };+ soft("SvcHostSplitThresholdInKB", run("reg", &["add", SPLIT_KEY, "/v", "SvcHostSplitThresholdInKB", "/t", "REG_DWORD", "/d", &t.to_string(), "/f"]));+}++fn rx_lnk() -> PathBuf {+ PathBuf::from(env::var("ProgramData").unwrap_or_else(|_| r"C:\ProgramData".into())).join(r"plugin-launcher\rs-overlay.lnk")+}++fn rx_install() -> Result<(), String> {+ if !bar_dir().join("topbar.exe").is_file() {+ return Err("сначала установите topbar: без него после отключения Explorer не будет панели".into());+ }+ with_payload(&["rust-explorer.exe", "rs-shell.exe"], |d| {+ for n in ["rs-shell.exe", "rust-explorer.exe"] {+ let _ = run("taskkill", &["/f", "/im", n]); // an update: a running exe cannot be overwritten+ }+ fs::create_dir_all(rx_dir()).map_err(|e| e.to_string())?;+ let (fm, sh) = (rx_dir().join("rust-explorer.exe"), rx_dir().join("rs-shell.exe"));+ put(&d.join("rust-explorer.exe"), &fm)?;+ put(&d.join("rs-shell.exe"), &sh)?;+ // what Windows had, saved once (an update must not overwrite it with our own 0)+ if reg_dword(RX_STATE, "AutoRestartShell").is_none() {+ let v = reg_dword(WINLOGON_KEY, "AutoRestartShell").unwrap_or(1);+ run("reg", &["add", RX_STATE, "/v", "AutoRestartShell", "/t", "REG_DWORD", "/d", &v.to_string(), "/f"])?;+ }+ // folders and drives opened by other programs, the desktop, Win+R: rust-explorer. DelegateExecute is emptied on purpose:+ // while it is set, Windows ignores the command and uses Explorer's built-in handler.+ for k in RX_FOLDERS {+ let c = format!(r"{k}\command");+ run("reg", &["add", &c, "/ve", "/t", "REG_SZ", "/d", &format!("\"{}\" \"%1\"", fm.display()), "/f"])?;+ run("reg", &["add", &c, "/v", "DelegateExecute", "/t", "REG_SZ", "/d", "", "/f"])?;+ }+ // A logon task starts the overlay right at sign-in; Explorer runs the Run key only after its own startup delay (~20 s of+ // plain Windows on screen). Limited run level: the shell side must never run elevated. Fallback: the Run key.+ let task = format!("$u=[Security.Principal.WindowsIdentity]::GetCurrent().Name; Register-ScheduledTask -TaskName rs-overlay -Force -Action (New-ScheduledTaskAction -Execute '{}' -Argument '--overlay') -Trigger (New-ScheduledTaskTrigger -AtLogOn -User $u) -Principal (New-ScheduledTaskPrincipal -UserId $u -LogonType Interactive -RunLevel Limited) -Settings (New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero)) | Out-Null", sh.display());+ if run("powershell", &["-NoProfile", "-Command", &task]).is_ok() {+ let _ = run("reg", &["delete", RUN_KEY, "/v", "rs-overlay", "/f"]);+ } else {+ WARN.lock().unwrap().push("задача rs-overlay не создана: запуск через Run, с задержкой Windows".into());+ run("reg", &["add", RUN_KEY, "/v", "rs-overlay", "/t", "REG_SZ", "/d", &format!("\"{}\" --overlay", sh.display()), "/f"])?;+ }+ run("reg", &["add", RX_SWITCH, "/v", "ReplaceExplorer", "/t", "REG_DWORD", "/d", "1", "/f"])?;+ run("reg", &["add", WINLOGON_KEY, "/v", "AutoRestartShell", "/t", "REG_DWORD", "/d", "0", "/f"])?;+ rx_trim(true);+ // Start it now, with the user's normal token: explorer.exe opens a shortcut unelevated, and the shortcut carries --overlay.+ let lnk = rx_lnk();+ let _ = fs::create_dir_all(lnk.parent().unwrap());+ soft("overlay не запущен сейчас: он стартует при следующем входе", run("powershell", &["-NoProfile", "-Command", &format!("$s=(New-Object -ComObject WScript.Shell).CreateShortcut('{}'); $s.TargetPath='{}'; $s.Arguments='--overlay'; $s.Save()", lnk.display(), sh.display())]));+ let _ = Command::new("explorer.exe").arg(&lnk).spawn();+ Ok(())+ })+}++fn rx_uninstall() -> Result<(), String> {+ // Windows may restart its shell again; our hooks off; then the shell back, unelevated, only if none is running+ let back = reg_dword(RX_STATE, "AutoRestartShell").unwrap_or(1);+ let r = run("reg", &["add", WINLOGON_KEY, "/v", "AutoRestartShell", "/t", "REG_DWORD", "/d", &back.to_string(), "/f"]);+ let _ = run("reg", &["delete", RUN_KEY, "/v", "rs-overlay", "/f"]);+ let _ = run("schtasks", &["/delete", "/tn", "rs-overlay", "/f"]);+ let _ = run("reg", &["delete", RX_SWITCH, "/f"]);+ rx_trim(false);+ for k in RX_FOLDERS {+ let _ = run("reg", &["delete", k, "/f"]); // only our HKCU override; the system's verbs under HKLM stay+ }+ for n in ["rs-shell.exe", "rust-explorer.exe"] {+ let _ = run("taskkill", &["/f", "/im", n]);+ }+ let _ = run("powershell", &["-NoProfile", "-Command", r#"if (-not (Get-CimInstance Win32_Process -Filter "Name='explorer.exe'" | Where-Object { $_.CommandLine -match '(?i)explorer\.exe"?\s*$' })) { runas /trustlevel:0x20000 C:\Windows\explorer.exe }"#]);+ let _ = fs::remove_file(rx_lnk());+ let _ = fs::remove_dir_all(rx_dir());+ if r.is_ok() {+ let _ = run("reg", &["delete", RX_STATE, "/f"]);+ }+ r+}++// ---------- wiztree, photoview, debloat: small stand-alone tools, one exe each in its own Program Files folder ----------++fn wz_dir() -> PathBuf {+ program_files().join("wiztree")+}++fn pv_dir() -> PathBuf {+ program_files().join("photoview")+}++fn db_dir() -> PathBuf {+ program_files().join("debloat")+}++/// Start Menu shortcut: search and the bar's Start panel list Start Menu shortcuts only.+fn start_lnk(name: &str) -> PathBuf {+ PathBuf::from(env::var("ProgramData").unwrap_or_else(|_| r"C:\ProgramData".into())).join(format!(r"Microsoft\Windows\Start Menu\Programs\{name}.lnk"))+}++/// Copies `exe` out of the payload into `dir` (an update: the running copy is killed first) and adds the Start Menu shortcut `lnk`.+fn tool_install(exe: &str, dir: &Path, lnk: Option<&str>) -> Result<(), String> {+ with_payload(&[exe], |d| {+ let _ = run("taskkill", &["/f", "/im", exe]);+ fs::create_dir_all(dir).map_err(|e| e.to_string())?;+ let dst = dir.join(exe);+ put(&d.join(exe), &dst)?;+ if let Some(n) = lnk {+ soft(&format!("ярлык «{n}» в меню Пуск не создан, поиск его не увидит"), run("powershell", &["-NoProfile", "-Command", &format!("$s=(New-Object -ComObject WScript.Shell).CreateShortcut('{}'); $s.TargetPath='{}'; $s.Save()", start_lnk(n).display(), dst.display())]));+ }+ Ok(())+ })+}++fn tool_remove(exe: &str, dir: &Path, lnk: Option<&str>) {+ if let Some(n) = lnk {+ let _ = fs::remove_file(start_lnk(n));+ }+ let _ = run("taskkill", &["/f", "/im", exe]);+ let _ = fs::remove_dir_all(dir);+}++fn wz_install() -> Result<(), String> {+ tool_install("wiztree.exe", &wz_dir(), Some("WinRust Disk"))+}++fn wz_uninstall() -> Result<(), String> {+ tool_remove("wiztree.exe", &wz_dir(), Some("WinRust Disk"));+ Ok(())+}++const PV_EXTS: [&str; 11] = ["jpg", "jpeg", "jfif", "png", "bmp", "gif", "tif", "tiff", "webp", "heic", "avif"]; // keep in step with photoview's EXTS+const PV_PROG: &str = "WinRustPhoto";+const PV_APP: &str = "WinRust Photo Viewer";++/// "Open with" entry and a Default apps entry; the default itself stays the user's choice (Windows does not allow setting it from code).+fn pv_install() -> Result<(), String> {+ tool_install("photoview.exe", &pv_dir(), Some("Photo viewer"))?;+ let exe = pv_dir().join("photoview.exe").display().to_string().replace('\\', r"\\");+ let mut reg = format!(+ "Windows Registry Editor Version 5.00\r\n\r\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\{PV_PROG}]\r\n@=\"Picture\"\r\n\r\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\{PV_PROG}\\shell\\open\\command]\r\n@=\"\\\"{exe}\\\" \\\"%1\\\"\"\r\n\r\n\+ [HKEY_LOCAL_MACHINE\\SOFTWARE\\WinRust\\PhotoView\\Capabilities]\r\n\"ApplicationName\"=\"{PV_APP}\"\r\n\"ApplicationDescription\"=\"Fast picture viewer\"\r\n\r\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\WinRust\\PhotoView\\Capabilities\\FileAssociations]\r\n"+ );+ for e in PV_EXTS {+ reg += &format!("\".{e}\"=\"{PV_PROG}\"\r\n");+ }+ reg += &format!("\r\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\RegisteredApplications]\r\n\"{PV_APP}\"=\"SOFTWARE\\\\WinRust\\\\PhotoView\\\\Capabilities\"\r\n");+ for e in PV_EXTS {+ reg += &format!("\r\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\.{e}\\OpenWithProgids]\r\n\"{PV_PROG}\"=hex(0):\r\n");+ }+ // the .reg lives in Program Files (admin-only), not %TEMP%+ let f = pv_dir().join("register.reg");+ fs::write(&f, reg).map_err(|e| format!("{}: {e}", f.display()))?;+ let r = run("reg", &["import", &f.display().to_string()]);+ let _ = fs::remove_file(&f);+ r+}++fn pv_uninstall() -> Result<(), String> {+ for e in PV_EXTS {+ let _ = run("reg", &["delete", &format!(r"HKLM\SOFTWARE\Classes\.{e}\OpenWithProgids"), "/v", PV_PROG, "/f"]);+ }+ let _ = run("reg", &["delete", r"HKLM\SOFTWARE\RegisteredApplications", "/v", PV_APP, "/f"]);+ let _ = run("reg", &["delete", &format!(r"HKLM\SOFTWARE\Classes\{PV_PROG}"), "/f"]);+ let _ = run("reg", &["delete", r"HKLM\SOFTWARE\WinRust\PhotoView", "/f"]);+ tool_remove("photoview.exe", &pv_dir(), Some("Photo viewer"));+ Ok(())+}++/// Installing = applying: debloat.exe --apply writes an undo file first, uninstalling plays it back.+fn db_install() -> Result<(), String> {+ tool_install("debloat.exe", &db_dir(), None)?;+ out(&db_dir().join("debloat.exe").display().to_string(), &["--apply"]).map(|_| ())+}++fn db_uninstall() -> Result<(), String> {+ let exe = db_dir().join("debloat.exe");+ if exe.is_file() {+ out(&exe.display().to_string(), &["--undo"])?; // on failure the exe and the undo file stay, so it can be repeated+ }+ tool_remove("debloat.exe", &db_dir(), None);+ Ok(())+}++fn taskbar_search(mode: u32) -> Result<(), String> {+ run("reg", &["add", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Search", "/v", "SearchboxTaskbarMode", "/t", "REG_DWORD", "/d", &mode.to_string(), "/f"])+}++fn install() -> Result<(), String> {+ // originals first: if anything below fails, the rollback restores exactly these+ save_dword("WSearchStart", reg_dword(WS_KEY, "Start"));+ save_dword("WSearchDelayed", Some(reg_dword(WS_KEY, "DelayedAutostart").unwrap_or(0)));+ save_dword("SearchboxMode", reg_dword(SB_KEY, "SearchboxTaskbarMode"));+ with_payload(&["rs.exe", "rs-launcher.exe"], |src| {+ run(src.join("rs.exe").to_str().unwrap(), &["--install"])?; // copies itself to Program Files, registers boot tasks+ let dst = prog_dir().join("rs-launcher.exe"); // must live somewhere stable: --autostart registers its own path+ let _ = run("taskkill", &["/f", "/im", "rs-launcher.exe"]);+ put(&src.join("rs-launcher.exe"), &dst)?;+ run(dst.to_str().unwrap(), &["--autostart"])?;+ // via explorer: it starts the launcher with the desktop user's normal token. Started from here it would+ // inherit admin rights, and every file opened from search would run elevated too.+ let _ = Command::new("explorer.exe").arg(&dst).spawn();+ run("sc.exe", &["config", "WSearch", "start=", "disabled"])?;+ let _ = run("sc.exe", &["stop", "WSearch"]);+ // SearchHost.exe (the Start/Win+S search UI) is not a service, so it gets the same IFEO trick as taskmgr: Windows runs `cmd /c exit` instead.+ run("reg", &["add", SH_KEY, "/v", "Debugger", "/t", "REG_SZ", "/d", "cmd.exe /c exit", "/f"])?;+ let _ = run("taskkill", &["/f", "/im", "SearchHost.exe"]);+ taskbar_search(0) // hide the taskbar search box+ })+}++fn uninstall() -> Result<(), String> {+ with_payload(&["rs.exe"], |src| {+ let _ = run("taskkill", &["/f", "/im", "rs-launcher.exe"]);+ let _ = run("reg", &["delete", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run", "/v", "rs-launcher", "/f"]);+ // run the unpacked copy: an exe cannot delete itself, so the installed one would leave its folder behind+ run(src.join("rs.exe").to_str().unwrap(), &["--uninstall"])?;+ let _ = fs::remove_dir_all(prog_dir());+ let _ = run("reg", &["delete", SH_KEY, "/v", "Debugger", "/f"]);+ // no saved values (installed by an older launcher): the Windows defaults+ let mode = match (reg_dword(STATE, "WSearchStart"), reg_dword(STATE, "WSearchDelayed")) {+ (Some(2), Some(0)) => "auto",+ (Some(3), _) => "demand",+ (Some(4), _) => "disabled",+ _ => "delayed-auto",+ };+ run("sc.exe", &["config", "WSearch", "start=", mode])?;+ if mode.ends_with("auto") {+ let _ = run("sc.exe", &["start", "WSearch"]);+ }+ let r = taskbar_search(reg_dword(STATE, "SearchboxMode").unwrap_or(2));+ if r.is_ok() {+ let _ = run("reg", &["delete", STATE, "/f"]);+ }+ r+ })+}++// Shared by the window and the command line, so both do exactly the same thing.+fn install_plugin(i: usize) -> Result<String, String> {+ let p = &PLUGINS[i];+ let (inst, uninst) = p.actions.ok_or("установка недоступна")?;+ let was = (p.installed)(); // already installed = an update: a failure must not remove the working copy+ WARN.lock().unwrap().clear();+ soft("точка восстановления не создана", checkpoint());+ if let Err(e) = inst() {+ log(&format!("{}: ОШИБКА {e}", p.name));+ if was {+ return Err(e);+ }+ let back = uninst().err().map_or(String::new(), |u| format!("; откат: {u}"));+ return Err(format!("{e} (установка отменена, изменения возвращены{back})"));+ }+ let w = WARN.lock().unwrap().clone();+ log(&format!("{}: {} {}", p.name, if was { "обновлён" } else { "установлен" }, w.join(" | ")));+ let note = if w.is_empty() { String::new() } else { format!(r" Предупреждений: {} (см. %ProgramData%\plugin-launcher\install.log).", w.len()) };+ Ok(format!("{} {}.{note}", p.name, if was { "обновлён" } else { "установлен" }))+}++fn uninstall_plugin(i: usize) -> Result<String, String> {+ let p = &PLUGINS[i];+ let (_, uninst) = p.actions.ok_or("удаление недоступно")?;+ uninst().inspect_err(|e| log(&format!("{}: ОШИБКА удаления {e}", p.name)))?;+ log(&format!("{}: удалён", p.name));+ Ok(format!("{} удалён, система восстановлена.", p.name))+}++fn rollback() -> Result<String, String> {+ // reverse install order: rust-explorer (which switched Explorer off) goes before topbar, else the session is left with no panel and no shell+ let errs: Vec<String> = PLUGINS.iter().rev().filter(|p| (p.installed)()).filter_map(|p| p.actions.and_then(|a| a.1().err().map(|e| format!("{}: {e}", p.name)))).collect();+ if errs.is_empty() { Ok("Все плагины удалены, система восстановлена.".into()) } else { Err(errs.join("; ")) }+}++// ---------- command line ----------+//+// plugin-launcher list+// plugin-launcher install <plugin> --yes (without --yes it only prints the warning: nothing is changed)+// plugin-launcher uninstall <plugin>+// plugin-launcher rollback --yes+// Exit code 0 = done, 1 = failed, 2 = bad arguments or --yes missing. Run it from an elevated terminal: the manifest+// demands admin, and from a normal one Windows opens a separate elevated console whose output is lost.++fn cli(args: &[String]) -> i32 {+ // A windows-subsystem exe has no console of its own: use stdout if the caller redirected it (pipe, file),+ // else attach to the parent's console and write to it directly.+ let redirected = unsafe { !GetStdHandle(STD_OUTPUT_HANDLE).is_null() && GetStdHandle(STD_OUTPUT_HANDLE) != INVALID_HANDLE_VALUE };+ let mut out: Box<dyn Write> = if redirected {+ Box::new(std::io::stdout())+ } else {+ unsafe { AttachConsole(ATTACH_PARENT_PROCESS) };+ fs::OpenOptions::new().write(true).open("CONOUT$").map_or_else(|_| Box::new(std::io::sink()) as Box<dyn Write>, |f| Box::new(f))+ };+ let mut say = |s: &str| {+ let _ = writeln!(out, "{s}");+ };+ let yes = args.iter().any(|a| a == "--yes");+ let words: Vec<&str> = args.iter().map(String::as_str).filter(|a| *a != "--yes").collect();+ let find = |n: &str| PLUGINS.iter().position(|p| p.name == n);+ let usage = "usage: plugin-launcher list | install <plugin> --yes | update <plugin> | uninstall <plugin> | rollback --yes";+ let result = match words.as_slice() {+ ["list"] => {+ for p in PLUGINS {+ say(&format!("{:<16}{}", p.name, if p.actions.is_none() { "stub" } else if (p.installed)() { "installed" } else { "not installed" }));+ }+ return 0;+ }+ ["install", n] => match find(n) {+ None => return { say(&format!("unknown plugin: {n}")); 2 },+ Some(i) if !yes => return { say(&format!("{}\nNothing changed. Repeat with --yes to install {n}.", PLUGINS[i].warn)); 2 },+ Some(i) if (PLUGINS[i].installed)() => return { say(&format!("{n} is already installed")); 0 },+ Some(i) => install_plugin(i),+ },+ ["update", n] => match find(n) {+ None => return { say(&format!("unknown plugin: {n}")); 2 },+ Some(i) if !(PLUGINS[i].installed)() => return { say(&format!("{n} is not installed (use install)")); 2 },+ Some(i) => install_plugin(i),+ },+ ["uninstall", n] => match find(n) {+ None => return { say(&format!("unknown plugin: {n}")); 2 },+ Some(i) if !(PLUGINS[i].installed)() => return { say(&format!("{n} is not installed")); 0 },+ Some(i) => uninstall_plugin(i),+ },+ ["rollback"] if yes => rollback(),+ ["rollback"] => return { say("Removes every installed plugin. Repeat with --yes."); 2 },+ _ => return { say(usage); 2 },+ };+ match result {+ Ok(m) => { say(&m); 0 }+ Err(e) => { say(&format!("error: {e}")); 1 }+ }+}++// ---------- drawing ----------+//+// One back buffer per paint: GDI+ for the anti-aliased shapes, then GDI (ClearType) for text on top.++fn wide(s: &str) -> Vec<u16> {+ s.encode_utf16().chain([0]).collect()+}++/// COLORREF (0x00BBGGRR) + alpha -> GDI+ ARGB.+const fn argb(c: u32, a: u8) -> u32 {+ (a as u32) << 24 | (c & 255) << 16 | (c >> 8 & 255) << 8 | (c >> 16 & 255)+}++fn lerp(a: u32, b: u32, t: f32) -> u32 {+ let m = |sh: u32| (((a >> sh & 255) as f32) * (1.0 - t) + ((b >> sh & 255) as f32) * t) as u32;+ m(0) | m(8) << 8 | m(16) << 16+}++type Box4 = [f32; 4]; // left, top, right, bottom in logical px++struct Ui {+ dc: HDC,+ g: *mut GpGraphics,+ s: f32,+}+impl Ui {+ fn px(&self, v: f32) -> i32 {+ (v * self.s).round() as i32+ }+ unsafe fn shape(&self, b: Box4, rad: f32, color: u32) {+ let (s, mut path) = (self.s, null_mut::<GpPath>());+ let (x, y, w, h) = (b[0] * s, b[1] * s, (b[2] - b[0]) * s, (b[3] - b[1]) * s);+ let d = (rad * 2.0 * s).min(h).min(w).max(0.01);+ GdipCreatePath(FillModeAlternate, &mut path);+ GdipAddPathArc(path, x, y, d, d, 180.0, 90.0);+ GdipAddPathArc(path, x + w - d, y, d, d, 270.0, 90.0);+ GdipAddPathArc(path, x + w - d, y + h - d, d, d, 0.0, 90.0);+ GdipAddPathArc(path, x, y + h - d, d, d, 90.0, 90.0);+ GdipClosePathFigure(path);+ let mut br = null_mut::<GpSolidFill>();+ GdipCreateSolidFill(color, &mut br);+ GdipFillPath(self.g, br as *mut GpBrush, path);+ GdipDeleteBrush(br as *mut GpBrush);+ GdipDeletePath(path);+ }+ /// Rounded box with a 1 px outline (`line` == `fill` for none).+ unsafe fn round(&self, b: Box4, rad: f32, fill: u32, line: u32) {+ if line != fill {+ self.shape(b, rad, argb(line, 255));+ let i = 1.0 / self.s;+ self.shape([b[0] + i, b[1] + i, b[2] - i, b[3] - i], rad - i, argb(fill, 255));+ } else {+ self.shape(b, rad, argb(fill, 255));+ }+ }+ unsafe fn font(&self, size: f32, weight: i32, face: &str) -> HFONT {+ CreateFontW(-self.px(size), 0, 0, 0, weight, 0, 0, 0, 1, 0, 0, 5, 0, wide(face).as_ptr())+ }+ unsafe fn text_in(&self, s: &str, b: Box4, size: f32, weight: i32, color: u32, flags: u32, face: &str) {+ let f = self.font(size, weight, face);+ let of = SelectObject(self.dc, f);+ SetTextColor(self.dc, color);+ SetBkMode(self.dc, TRANSPARENT as i32);+ let mut r = RECT { left: self.px(b[0]), top: self.px(b[1]), right: self.px(b[2]), bottom: self.px(b[3]) };+ DrawTextW(self.dc, wide(s).as_ptr(), -1, &mut r, flags | DT_NOPREFIX);+ SelectObject(self.dc, of);+ DeleteObject(f);+ }+ unsafe fn text(&self, s: &str, b: Box4, size: f32, weight: i32, color: u32, flags: u32) {+ self.text_in(s, b, size, weight, color, flags, "Segoe UI");+ }+ /// Width of a single line of text, logical px.+ unsafe fn width(&self, s: &str, size: f32, weight: i32) -> f32 {+ let f = self.font(size, weight, "Segoe UI");+ let of = SelectObject(self.dc, f);+ let mut r: RECT = zeroed();+ DrawTextW(self.dc, wide(s).as_ptr(), -1, &mut r, DT_CALCRECT | DT_SINGLELINE | DT_NOPREFIX);+ SelectObject(self.dc, of);+ DeleteObject(f);+ r.right as f32 / self.s+ }+}++// layout, logical px+const WIN_W: f32 = 600.0;+const M: f32 = 24.0; // outer margin+const N_READY: usize = {+ let (mut n, mut i) = (0, 0);+ while i < PLUGINS.len() {+ if PLUGINS[i].actions.is_some() && PLUGINS[i].bulk {+ n += 1;+ }+ i += 1;+ }+ n+};+const LIST_TOP: f32 = 136.0;+const ROW_H: f32 = 62.0;+const LIST_H: f32 = N_READY as f32 * ROW_H + 12.0;+const MAIN_TOP: f32 = LIST_TOP + LIST_H + 20.0;+const MAIN_H: f32 = 54.0;+const FOOT_H: f32 = 72.0;+const WIN_H: f32 = MAIN_TOP + MAIN_H + 16.0 + FOOT_H;+const BTN_W: f32 = 136.0;+const BTN_H: f32 = 36.0;+// clickable things+const ID_MAIN: usize = 0;+const ID_ROLLBACK: usize = 1;+const ID_OK: usize = 2;+const ID_CANCEL: usize = 3;+const ID_SWITCH: usize = 4;+const ID_GEAR: usize = 5;+const STARTING: usize = usize::MAX - 1; // JOB before install_all picks its first component++/// Installable components, in install order (topbar comes before rust-explorer, which needs it).+fn ready() -> impl Iterator<Item = usize> {+ (0..PLUGINS.len()).filter(|&i| PLUGINS[i].actions.is_some() && PLUGINS[i].bulk)+}++fn row_box(k: usize, w: f32) -> Box4 {+ let t = LIST_TOP + 6.0 + k as f32 * ROW_H;+ [M + 6.0, t, w - M - 6.0, t + ROW_H]+}++/// Settings gear at the right end of the row of the plugin that has settings (topbar): (plugin index, box).+fn gear_box(w: f32) -> Option<(usize, Box4)> {+ let (k, i) = ready().enumerate().find(|&(_, i)| PLUGINS[i].settings)?;+ let r = row_box(k, w);+ let t = r[1] + (ROW_H - 32.0) / 2.0;+ Some((i, [r[2] - 14.0 - 32.0, t, r[2] - 14.0, t + 32.0]))+}++fn main_box(w: f32) -> Box4 {+ [M, MAIN_TOP, w - M, MAIN_TOP + MAIN_H]+}++/// On/off switch inside the settings panel row.+fn switch_box(w: f32) -> Box4 {+ let (d, _, _) = dialog_boxes(w);+ [d[2] - 24.0 - 16.0 - 44.0, d[1] + 78.0 + 23.0, d[2] - 24.0 - 16.0, d[1] + 78.0 + 47.0]+}++fn rollback_box(w: f32) -> Box4 {+ let t = WIN_H - FOOT_H + (FOOT_H - BTN_H) / 2.0;+ [w - M - 150.0, t, w - M, t + BTN_H]+}++/// Dialog panel and its (cancel, ok) buttons.+fn dialog_boxes(w: f32) -> (Box4, Box4, Box4) {+ let (dw, dh) = (528.0, 352.0);+ let (l, t) = ((w - dw) / 2.0, (WIN_H - dh) / 2.0);+ let (bt, r) = (t + dh - 24.0 - BTN_H, l + dw - 24.0);+ ([l, t, l + dw, t + dh], [r - BTN_W - 10.0 - 120.0, bt, r - BTN_W - 10.0, bt + BTN_H], [r - BTN_W, bt, r, bt + BTN_H])+}++/// A button: `kind` 0 = primary (accent), 1 = secondary (outline), 2 = danger (outline, red text), 3 = disabled.+unsafe fn button(ui: &Ui, b: Box4, label: &str, kind: u8, hot: bool) {+ let (fill, line, fg) = match kind {+ 0 => (ACCENT, ACCENT, rgb(255, 255, 255)),+ 1 => (PANEL, BORDER, TEXT),+ 2 => (PANEL, BORDER, BAD),+ _ => (PANEL, lerp(PANEL, BORDER, 0.6), lerp(DIM, PANEL, 0.35)),+ };+ let fill = if hot && kind != 3 { lerp(fill, TEXT, if kind == 0 { 0.14 } else { 0.07 }) } else { fill };+ let line = if hot && kind == 2 { BAD } else if kind == 0 { fill } else { line };+ ui.round(b, 8.0, fill, line);+ ui.text(label, b, 13.5, 600, fg, DT_CENTER | DT_VCENTER | DT_SINGLELINE);+}++unsafe fn paint(hwnd: HWND) {+ let mut ps: PAINTSTRUCT = zeroed();+ let hdc = BeginPaint(hwnd, &mut ps);+ let mut rc: RECT = zeroed();+ GetClientRect(hwnd, &mut rc);+ let (cw, ch) = (rc.right, rc.bottom);+ let mem = CreateCompatibleDC(hdc);+ let bmp = CreateCompatibleBitmap(hdc, cw, ch);+ let ob = SelectObject(mem, bmp);+ let s = GetDeviceCaps(hdc, LOGPIXELSX as i32) as f32 / 96.0;+ let bgb = CreateSolidBrush(BG);+ FillRect(mem, &rc, bgb);+ DeleteObject(bgb);+ let mut g = null_mut::<GpGraphics>();+ GdipCreateFromHDC(mem, &mut g);+ GdipSetSmoothingMode(g, SmoothingModeAntiAlias);+ let ui = Ui { dc: mem, g, s };+ let w = cw as f32 / s;+ let hover = HOVER.get();+ let dialog = DIALOG.with_borrow(|d| d.as_ref().map(|d| (d.title.clone(), d.text.clone(), d.ok.clone(), d.danger)));+ let hot = |id: usize| hover == Some(id);+ let busy = BUSY.load(Relaxed);+ let job = JOB.load(Relaxed);+ let n = PLUGINS.len();+ let n_inst = ready().filter(|&i| INSTALLED[i].load(Relaxed)).count();++ // header: logo + name+ ui.shape([0.0, 0.0, w, 3.0], 0.0, argb(ACCENT, 255));+ let logo = [M, 30.0, M + 60.0, 90.0];+ ui.round(logo, 16.0, ACCENT, ACCENT);+ let inner = lerp(ACCENT, BG, 0.12);+ ui.round([logo[0] + 4.0, logo[1] + 4.0, logo[2] - 4.0, logo[3] - 4.0], 13.0, inner, inner);+ ui.text("W", [logo[0], logo[1] - 2.0, logo[2], logo[3]], 32.0, 900, rgb(255, 255, 255), DT_CENTER | DT_VCENTER | DT_SINGLELINE);+ let tx = logo[2] + 18.0;+ ui.text("WinRust", [tx, 28.0, w - M, 64.0], 30.0, 700, TEXT, DT_LEFT | DT_SINGLELINE | DT_VCENTER);+ ui.text(&format!("Оболочка Windows на Rust \u{00B7} установлено {n_inst} из {N_READY}"), [tx, 64.0, w - M, 88.0], 13.0, 400, DIM, DT_LEFT | DT_SINGLELINE | DT_VCENTER);+ ui.text("ВХОДИТ В СОСТАВ", [M + 4.0, LIST_TOP - 26.0, w - M, LIST_TOP - 6.0], 11.0, 700, DIM, DT_LEFT | DT_SINGLELINE | DT_VCENTER);++ // component list+ ui.round([M, LIST_TOP, w - M, LIST_TOP + LIST_H], 12.0, PANEL, BORDER);+ let pos = ready().position(|i| i == job); // where install_all is now+ let gear = gear_box(w);+ for (k, i) in ready().enumerate() {+ let p = &PLUGINS[i];+ let r = row_box(k, w);+ let installed = INSTALLED[i].load(Relaxed);+ let working = busy && (job == i || (job == n && installed));+ let queued = busy && !installed && (job == STARTING || pos.is_some_and(|q| k > q));+ if k > 0 {+ ui.shape([r[0] + 12.0, r[1], r[2] - 12.0, r[1] + 1.0 / s], 0.0, argb(BORDER, 255));+ }+ if working {+ let t = lerp(PANEL, ACCENT, 0.10);+ ui.round([r[0], r[1] + 3.0, r[2], r[3] - 3.0], 9.0, t, t);+ }+ let tile = [r[0] + 10.0, r[1] + 13.0, r[0] + 46.0, r[1] + 49.0];+ let lit = installed || working;+ let tint = if lit { lerp(PANEL, ACCENT, 0.20) } else { lerp(PANEL, TEXT, 0.06) };+ ui.round(tile, 9.0, tint, tint);+ ui.text_in(p.glyph, tile, 16.0, 400, if lit { ACCENT } else { TEXT }, DT_CENTER | DT_VCENTER | DT_SINGLELINE, "Segoe MDL2 Assets");++ let (pill, pc) = if working {+ (if job == n { "Удаление…" } else { "Установка…" }, ACCENT)+ } else if installed {+ ("Установлен", GOOD)+ } else if queued {+ ("В очереди", DIM)+ } else {+ ("Не установлен", DIM)+ };+ let pr = r[2] - 14.0 - 32.0 - 10.0;+ let pw = ui.width(pill, 11.5, 600) + 18.0;+ let pb = [pr - pw, r[1] + 21.0, pr, r[1] + 41.0];+ let ptint = lerp(PANEL, pc, 0.16);+ ui.round(pb, 10.0, ptint, ptint);+ ui.text(pill, pb, 11.5, 600, pc, DT_CENTER | DT_VCENTER | DT_SINGLELINE);++ let nx = tile[2] + 14.0;+ ui.text(p.name, [nx, r[1] + 11.0, pb[0] - 10.0, r[1] + 32.0], 14.5, 600, TEXT, DT_LEFT | DT_SINGLELINE | DT_VCENTER);+ let short = p.desc.split(". ").next().unwrap_or(p.desc).trim_end_matches('.');+ ui.text(short, [nx, r[1] + 32.0, pb[0] - 10.0, r[3] - 10.0], 12.0, 400, DIM, DT_LEFT | DT_SINGLELINE | DT_END_ELLIPSIS);++ if let Some((_, gb)) = gear.filter(|&(gi, _)| gi == i && installed) {+ let h = hot(ID_GEAR) && !busy;+ ui.round(gb, 8.0, if h { lerp(PANEL, TEXT, 0.08) } else { PANEL }, BORDER);+ ui.text_in("\u{E713}", gb, 14.0, 400, if busy { DIM } else { TEXT }, DT_CENTER | DT_VCENTER | DT_SINGLELINE, "Segoe MDL2 Assets");+ }+ }++ // the one button: installs everything that is missing (or updates all when nothing is)+ let mb = main_box(w);+ if busy {+ let base = lerp(PANEL, ACCENT, 0.22);+ ui.round(mb, 12.0, base, base);+ let done = if job == n { 0.0 } else { pos.map_or(0.0, |q| (q as f32 + 0.5) / N_READY as f32) };+ if done > 0.0 {+ ui.shape([mb[0], mb[1], mb[0] + (mb[2] - mb[0]) * done, mb[3]], 12.0, argb(ACCENT, 255));+ }+ let label = if job == n {+ "Удаление WinRust…".to_string()+ } else {+ pos.map_or("Подготовка…".into(), |q| format!("Устанавливается {} ({} из {N_READY})", PLUGINS[job].name, q + 1))+ };+ ui.text(&label, mb, 15.5, 700, TEXT, DT_CENTER | DT_VCENTER | DT_SINGLELINE);+ } else {+ let all = n_inst == N_READY;+ let label = if all {+ "Обновить WinRust".to_string()+ } else if n_inst == 0 {+ "Установить WinRust".into()+ } else {+ format!("Доустановить WinRust ({} из {N_READY})", N_READY - n_inst)+ };+ let (fill, fg) = if all { (PANEL, TEXT) } else { (ACCENT, rgb(255, 255, 255)) };+ let fill = if hot(ID_MAIN) { lerp(fill, TEXT, if all { 0.07 } else { 0.14 }) } else { fill };+ ui.round(mb, 12.0, fill, if all { BORDER } else { fill });+ let tw = ui.width(&label, 16.0, 700);+ let cx = (mb[0] + mb[2]) / 2.0 + 13.0;+ ui.text_in(if all { "\u{E72C}" } else { "\u{E896}" }, [cx - tw / 2.0 - 30.0, mb[1], cx - tw / 2.0 - 6.0, mb[3]], 15.0, 400, fg, DT_CENTER | DT_VCENTER | DT_SINGLELINE, "Segoe MDL2 Assets");+ ui.text(&label, [cx - tw / 2.0, mb[1], cx + tw / 2.0 + 4.0, mb[3]], 16.0, 700, fg, DT_LEFT | DT_VCENTER | DT_SINGLELINE);+ }++ // footer: status on the left, remove-all on the right+ let ft = WIN_H - FOOT_H;+ ui.shape([M, ft, w - M, ft + 1.0 / s], 0.0, argb(BORDER, 255));+ let (m, ok) = MSG.lock().unwrap().clone();+ let (m, dot, fg) = if busy {+ ("Выполняется, не закрывайте окно…".to_string(), ACCENT, DIM)+ } else if m.is_empty() {+ ("Перед установкой создаётся точка восстановления.".into(), DIM, DIM)+ } else if ok {+ (m, GOOD, TEXT)+ } else {+ (m, BAD, BAD)+ };+ let rb = rollback_box(w);+ ui.shape([M, ft + FOOT_H / 2.0 - 4.0, M + 8.0, ft + FOOT_H / 2.0 + 4.0], 4.0, argb(dot, 255));+ let one_line = ui.width(&m, 12.5, 400) < rb[0] - 16.0 - M - 18.0;+ let tb = [M + 18.0, ft + if one_line { 0.0 } else { 12.0 }, rb[0] - 16.0, WIN_H - if one_line { 0.0 } else { 8.0 }];+ ui.text(&m, tb, 12.5, 400, fg, DT_LEFT | DT_END_ELLIPSIS | if one_line { DT_SINGLELINE | DT_VCENTER } else { DT_WORDBREAK });+ button(&ui, rb, "Удалить всё", if n_inst > 0 && !busy { 2 } else { 3 }, hot(ID_ROLLBACK));++ // confirmation dialog over the dimmed window+ if let Some((title, text, ok_label, danger)) = dialog {+ ui.shape([0.0, 0.0, w, WIN_H + 1.0], 0.0, argb(0, 160));+ let (d, cancel, okb) = dialog_boxes(w);+ ui.round(d, 14.0, lerp(PANEL, BG, 0.25), BORDER);+ let accent = if danger { BAD } else { ACCENT };+ let icon = [d[0] + 24.0, d[1] + 24.0, d[0] + 60.0, d[1] + 60.0];+ let tint = lerp(PANEL, accent, 0.18);+ ui.round(icon, 18.0, tint, tint);+ ui.text_in(if danger { "\u{E7BA}" } else { "\u{E946}" }, icon, 16.0, 400, accent, DT_CENTER | DT_VCENTER | DT_SINGLELINE, "Segoe MDL2 Assets");+ ui.text(&title, [icon[2] + 14.0, d[1] + 24.0, d[2] - 24.0, d[1] + 60.0], 17.0, 600, TEXT, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);+ ui.text(&text, [d[0] + 24.0, d[1] + 76.0, d[2] - 24.0, cancel[1] - 12.0], 12.5, 400, DIM, DT_LEFT | DT_WORDBREAK | DT_END_ELLIPSIS);+ button(&ui, cancel, "Отмена", 1, hot(ID_CANCEL));+ let okfill = if hot(ID_OK) { lerp(accent, TEXT, 0.14) } else { accent };+ ui.round(okb, 8.0, okfill, okfill);+ ui.text(&ok_label, okb, 13.5, 600, rgb(255, 255, 255), DT_CENTER | DT_VCENTER | DT_SINGLELINE);+ }++ // settings panel of a plugin (topbar: OneDrive switch)+ if let Some(i) = SETTINGS.get() {+ ui.shape([0.0, 0.0, w, WIN_H + 1.0], 0.0, argb(0, 160));+ let (d, _, closeb) = dialog_boxes(w);+ ui.round(d, 14.0, lerp(PANEL, BG, 0.25), BORDER);+ let icon = [d[0] + 24.0, d[1] + 24.0, d[0] + 60.0, d[1] + 60.0];+ let tint = lerp(PANEL, ACCENT, 0.18);+ ui.round(icon, 18.0, tint, tint);+ ui.text_in("\u{E713}", icon, 16.0, 400, ACCENT, DT_CENTER | DT_VCENTER | DT_SINGLELINE, "Segoe MDL2 Assets");+ ui.text(&format!("Настройки {}", PLUGINS[i].name), [icon[2] + 14.0, d[1] + 24.0, d[2] - 24.0, d[1] + 60.0], 17.0, 600, TEXT, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);+ let row = [d[0] + 24.0, d[1] + 78.0, d[2] - 24.0, d[1] + 148.0];+ let hid = od_hidden();+ ui.round(row, 10.0, PANEL, BORDER);+ ui.text("Отключение OneDrive", [row[0] + 16.0, row[1] + 10.0, row[2] - 80.0, row[1] + 32.0], 14.0, 600, TEXT, DT_LEFT | DT_SINGLELINE | DT_VCENTER);+ ui.text("Значок OneDrive не показывается в топбаре (по умолчанию). Синхронизация продолжает работать.", [row[0] + 16.0, row[1] + 32.0, row[2] - 80.0, row[3] - 6.0], 12.0, 400, DIM, DT_LEFT | DT_WORDBREAK);+ let sw = switch_box(w);+ let off = lerp(PANEL, TEXT, 0.25);+ let track = if hid { ACCENT } else { off };+ ui.round(sw, 12.0, track, track);+ let kx = if hid { sw[2] - 12.0 } else { sw[0] + 12.0 };+ ui.round([kx - 8.0, sw[1] + 4.0, kx + 8.0, sw[3] - 4.0], 8.0, TEXT, TEXT);+ button(&ui, closeb, "Закрыть", 1, hot(ID_CANCEL));+ }++ GdipDeleteGraphics(g);+ BitBlt(hdc, 0, 0, cw, ch, mem, 0, 0, SRCCOPY);+ SelectObject(mem, ob);+ DeleteObject(bmp);+ DeleteDC(mem);+ EndPaint(hwnd, &ps);+}++// ---------- window ----------++/// What a confirmed dialog runs.+#[derive(Clone, Copy)]+enum Act {+ InstallAll,+ Rollback,+}+struct Dialog {+ title: String,+ text: String,+ ok: String,+ danger: bool,+ act: Act,+}+thread_local! { static DIALOG: std::cell::RefCell<Option<Dialog>> = const { std::cell::RefCell::new(None) }; }++/// Clickable thing under the cursor (ID_*). While a panel is up only its buttons count; while a job runs nothing does.+unsafe fn hit(hwnd: HWND, lp: isize) -> Option<usize> {+ let (x, y) = ((lp & 0xFFFF) as i16 as f32, ((lp >> 16) & 0xFFFF) as i16 as f32);+ let (mut rc, dc): (RECT, _) = (zeroed(), GetDC(hwnd));+ let s = GetDeviceCaps(dc, LOGPIXELSX as i32) as f32 / 96.0;+ ReleaseDC(hwnd, dc);+ GetClientRect(hwnd, &mut rc);+ let w = rc.right as f32 / s;+ let inside = |b: Box4| x >= b[0] * s && x <= b[2] * s && y >= b[1] * s && y <= b[3] * s;+ if SETTINGS.get().is_some() {+ let (_, _, closeb) = dialog_boxes(w);+ return if inside(switch_box(w)) { Some(ID_SWITCH) } else if inside(closeb) { Some(ID_CANCEL) } else { None };+ }+ if DIALOG.with_borrow(|d| d.is_some()) {+ let (_, cancel, ok) = dialog_boxes(w);+ return if inside(ok) { Some(ID_OK) } else if inside(cancel) { Some(ID_CANCEL) } else { None };+ }+ if BUSY.load(Relaxed) {+ return None;+ }+ if gear_box(w).is_some_and(|(i, b)| INSTALLED[i].load(Relaxed) && inside(b)) {+ return Some(ID_GEAR);+ }+ if inside(main_box(w)) {+ return Some(ID_MAIN);+ }+ (INSTALLED.iter().any(|f| f.load(Relaxed)) && inside(rollback_box(w))).then_some(ID_ROLLBACK)+}++/// Runs `job` off the UI thread; its Ok/Err text becomes the status line. `which` = plugin index, n = rollback.+fn start(hwnd: HWND, which: usize, job: impl FnOnce() -> Result<String, String> + Send + 'static) {+ JOB.store(which, Relaxed);+ BUSY.store(true, Relaxed);+ HOVER.set(None);+ unsafe { InvalidateRect(hwnd, null(), 0) };+ let h = hwnd as isize;+ thread::spawn(move || {+ *MSG.lock().unwrap() = match job() {+ Ok(m) => (m, true),+ Err(e) => (format!("Ошибка: {e}"), false),+ };+ refresh();+ BUSY.store(false, Relaxed);+ unsafe { PostMessageW(h as HWND, WM_DONE, 0, 0) };+ });+}++/// One click: every component that is missing, in order (all of them again = update when nothing is missing).+/// Stops at the first failure: rust-explorer must not go on without topbar. `h` = window to repaint between steps.+fn install_all(h: isize) -> Result<String, String> {+ let all = ready().all(|i| (PLUGINS[i].installed)());+ let (mut done, mut warned) = (Vec::new(), false);+ for i in ready() {+ if !all && (PLUGINS[i].installed)() {+ continue;+ }+ JOB.store(i, Relaxed);+ unsafe { InvalidateRect(h as HWND, null(), 0) };+ if let Err(e) = install_plugin(i) {+ let ok = if done.is_empty() { String::new() } else { format!(" Уже готово: {}.", done.join(", ")) };+ return Err(format!("{}: {e}.{ok}", PLUGINS[i].name));+ }+ warned |= !WARN.lock().unwrap().is_empty(); // install_plugin clears the list for each component+ done.push(PLUGINS[i].name);+ refresh();+ }+ let note = if warned { r" Есть предупреждения (см. %ProgramData%\plugin-launcher\install.log)." } else { "" };+ Ok(format!("WinRust {}: {}.{note}", if all { "обновлён" } else { "установлен" }, done.join(", ")))+}++unsafe fn ask(hwnd: HWND, d: Dialog) {+ DIALOG.set(Some(d));+ HOVER.set(None);+ InvalidateRect(hwnd, null(), 0);+}++unsafe fn close_dialog(hwnd: HWND, run: bool) {+ let Some(d) = DIALOG.take() else { return };+ HOVER.set(None);+ InvalidateRect(hwnd, null(), 0);+ if !run {+ return;+ }+ match d.act {+ Act::Rollback => start(hwnd, PLUGINS.len(), rollback),+ Act::InstallAll => {+ let h = hwnd as isize;+ start(hwnd, STARTING, move || install_all(h))+ }+ }+}++unsafe fn click(hwnd: HWND, id: usize) {+ if SETTINGS.get().is_some() {+ if id == ID_SWITCH {+ if let Err(e) = set_od_hidden(!od_hidden()) {+ *MSG.lock().unwrap() = (format!("Ошибка: {e}"), false);+ }+ } else if id == ID_CANCEL {+ SETTINGS.set(None);+ }+ HOVER.set(None);+ InvalidateRect(hwnd, null(), 0);+ return;+ }+ if id == ID_OK || id == ID_CANCEL {+ return close_dialog(hwnd, id == ID_OK);+ }+ if BUSY.load(Relaxed) {+ return;+ }+ match id {+ ID_GEAR => {+ SETTINGS.set(PLUGINS.iter().position(|p| p.settings));+ HOVER.set(None);+ InvalidateRect(hwnd, null(), 0);+ }+ ID_ROLLBACK => ask(hwnd, Dialog {+ title: "Удалить WinRust?".into(),+ text: "Все компоненты будут удалены. Вернутся поиск Windows, стандартный диспетчер задач, панель задач и обычный Проводник.".into(),+ ok: "Удалить всё".into(),+ danger: true,+ act: Act::Rollback,+ }),+ ID_MAIN if ready().all(|i| INSTALLED[i].load(Relaxed)) => ask(hwnd, Dialog {+ title: "Обновить WinRust?".into(),+ text: "Все компоненты будут переустановлены из этой версии установщика. Настройки сохранятся.".into(),+ ok: "Обновить".into(),+ danger: false,+ act: Act::InstallAll,+ }),+ ID_MAIN => ask(hwnd, Dialog {+ title: "Установить WinRust?".into(),+ text: "Компоненты Windows будут заменены:\n\u{2022} поиск Windows отключается, вместо него rust-search (Alt+Space);\n\u{2022} диспетчер задач заменяется на rtaskmgr;\n\u{2022} панель задач заменяется на topbar (внизу экрана);\n\u{2022} Проводник как оболочка отключается: папки и рабочий стол открывает rust-explorer, отключаются службы телеметрии.\n\nСоздаётся точка восстановления, «Удалить всё» вернёт систему. Если экран останется пустым: Ctrl+Alt+Del \u{2192} Диспетчер задач \u{2192} Запустить explorer.exe.".into(),+ ok: "Установить".into(),+ danger: false,+ act: Act::InstallAll,+ }),+ _ => {}+ }+}++unsafe extern "system" fn proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {+ match msg {+ WM_PAINT => paint(hwnd),+ WM_ERASEBKGND => return 1,+ WM_MOUSEMOVE => {+ let h = hit(hwnd, lp);+ if h != HOVER.get() {+ HOVER.set(h);+ InvalidateRect(hwnd, null(), 0);+ }+ let mut t = TRACKMOUSEEVENT { cbSize: size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE, hwndTrack: hwnd, dwHoverTime: 0 };+ TrackMouseEvent(&mut t);+ }+ WM_SETCURSOR if (lp & 0xFFFF) as u32 == HTCLIENT => {+ SetCursor(LoadCursorW(null_mut(), if HOVER.get().is_some() { IDC_HAND } else { IDC_ARROW }));+ return 1;+ }+ WM_MOUSELEAVE => {+ HOVER.set(None);+ InvalidateRect(hwnd, null(), 0);+ }+ WM_LBUTTONUP => {+ if let Some(i) = hit(hwnd, lp) {+ click(hwnd, i);+ }+ }+ WM_KEYDOWN if SETTINGS.get().is_some() && wp as u16 == VK_ESCAPE => {+ SETTINGS.set(None);+ InvalidateRect(hwnd, null(), 0);+ }+ WM_KEYDOWN if DIALOG.with_borrow(|d| d.is_some()) => match wp as u16 {+ VK_ESCAPE => close_dialog(hwnd, false),+ VK_RETURN if DIALOG.with_borrow(|d| d.as_ref().is_some_and(|d| !d.danger)) => close_dialog(hwnd, true), // a dangerous one needs the click++ _ => {}+ },+ WM_DONE => {+ InvalidateRect(hwnd, null(), 0);+ }+ WM_CLOSE if BUSY.load(Relaxed) => {} // closing mid-install would leave the system half-changed+ WM_DESTROY => PostQuitMessage(0),+ _ => return DefWindowProcW(hwnd, msg, wp, lp),+ }+ 0+}++fn main() {+ let args: Vec<String> = env::args().skip(1).collect();+ if !args.is_empty() {+ std::process::exit(cli(&args));+ }+ unsafe {+ refresh();+ let (mut token, mut input): (usize, GdiplusStartupInput) = (0, zeroed());+ input.GdiplusVersion = 1;+ GdiplusStartup(&mut token, &input, null_mut());+ let hi = GetModuleHandleW(null());+ let cls = wide("WinRust");+ let wc = WNDCLASSW { lpfnWndProc: Some(proc), hInstance: hi, hCursor: LoadCursorW(null_mut(), IDC_ARROW), lpszClassName: cls.as_ptr(), ..zeroed() };+ RegisterClassW(&wc);+ let dc = GetDC(null_mut());+ let s = GetDeviceCaps(dc, LOGPIXELSX as i32) as f32 / 96.0;+ ReleaseDC(null_mut(), dc);+ let style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;+ let mut r = RECT { left: 0, top: 0, right: (WIN_W * s) as i32, bottom: (WIN_H * s) as i32 };+ AdjustWindowRect(&mut r, style, 0);+ let title = wide("WinRust");+ let hwnd = CreateWindowExW(0, cls.as_ptr(), title.as_ptr(), style | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, r.right - r.left, r.bottom - r.top, null_mut(), null_mut(), hi, null());+ DwmSetWindowAttribute(hwnd, 20, &1i32 as *const i32 as *const _, 4); // dark title bar+ DwmSetWindowAttribute(hwnd, 35, &BG as *const u32 as *const _, 4); // caption colour = window background (Win11; ignored on Win10)+ let mut m: MSG = zeroed();+ while GetMessageW(&mut m, null_mut(), 0, 0) > 0 {+ TranslateMessage(&m);+ DispatchMessageW(&m);+ }+ }+}diff --git a/src/profile.ps1 b/src/profile.ps1new file mode 100644index 0000000..4cb2df5--- /dev/null+++ b/src/profile.ps1@@ -0,0 +1,7 @@+# >>> topbar >>>+# managed by plugin-launcher: removed together with topbar+if (Get-Command zoxide -ErrorAction SilentlyContinue) { Invoke-Expression (& { (zoxide init powershell | Out-String) }) }+if (Get-Command rg -ErrorAction SilentlyContinue) { Set-Alias grep rg }+if (Get-Command eza -ErrorAction SilentlyContinue) { function ll { eza -la --git @args } }+if (Get-Command bat -ErrorAction SilentlyContinue) { Set-Alias cat bat -Option AllScope -Force; function cats { bat @args } }+# <<< topbar <<<