Skip to content

Windows shell replacement in Rust: taskbar, file manager, NTFS search, task manager, disk cleaner. One installer exe.

Rust

topbar: auto-hide option, own Win+Shift+S region clipper, volume keys, keyboard button in Start search; rust-explorer: desktop shortcut names, network drives, Space preview; rs-shell: shell Explorer match

Lemxy8a87d7cbdba2
diff --git a/CLAUDE.md b/CLAUDE.md
index ac9b8d1..f862e42 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -31,7 +31,7 @@
## Обновить установленный плагин после правки (без пересборки установщика)
```powershell
-powershell -ExecutionPolicy Bypass -File scripts\update-plugin.ps1 <rust-search|rtaskmgr-win32|topbar|rust-explorer|wiztree|photoview|debloat>
+powershell -ExecutionPolicy Bypass -File scripts\update-plugin.ps1 <rust-search|rtaskmgr-win32|topbar|rust-explorer|wiztree|photoview|rust-settings|debloat>
```
Скрипт пересобирает плагины, обновляет `payload\` и запускает `plugin-launcher update <плагин>` через explorer.exe. Появится окно UAC: **«Да» нажимает пользователь**. Не обходи UAC и не меняй его настройки.
diff --git a/Cargo.lock b/Cargo.lock
index 5633555..09179d2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -148,8 +148,10 @@ dependencies = [
name = "photoview"
version = "0.1.0"
dependencies = [
+ "embed-resource",
"windows",
"windows-sys",
+ "winrust-common",
]
[[package]]
@@ -230,6 +232,17 @@ dependencies = [
"winrust-common",
]
+[[package]]
+name = "rust-settings"
+version = "0.1.0"
+dependencies = [
+ "embed-resource",
+ "windows",
+ "windows-core",
+ "windows-sys",
+ "winrust-common",
+]
+
[[package]]
name = "rustc_version"
version = "0.4.1"
@@ -359,6 +372,7 @@ checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
name = "topbar"
version = "0.1.0"
dependencies = [
+ "embed-resource",
"windows",
"windows-sys",
"winrust-common",
@@ -564,6 +578,7 @@ dependencies = [
name = "wiztree"
version = "0.1.0"
dependencies = [
+ "embed-resource",
"windows-sys",
"winrust-common",
]
diff --git a/Cargo.toml b/Cargo.toml
index a75d508..989f97d 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -29,6 +29,7 @@ members = [
"plugins/photoview",
"plugins/debloat",
"plugins/purge",
+ "plugins/rust-settings",
]
# Stay separate projects with their own target\ and Cargo.lock, because they need panic = "unwind" (the profile below is
# shared by every member): rust-search's service threads must not take the process down, chrome-rs catches panics per page.
diff --git a/README.md b/README.md
index 6d92b27..97a6659 100644
--- a/README.md
+++ b/README.md
@@ -40,6 +40,7 @@ The installer is in English. The **Русский** button in its corner (or "Wi
| **rust-explorer** | A file manager with tabs, and the desktop | Folders and drives open in it; **Explorer stops being the shell** (comes back by itself if topbar fails). Disables PcaSvc, InventorySvc, lfsvc, cbdhsvc, sets DoSvc to manual, merges svchost processes. Requires topbar |
| **wiztree** | A disk-usage map ("WinRust Disk" in Start) | Nothing, apart from the file and a shortcut |
| **photoview** | A fast photo viewer | Adds it to "Open with" (it does not become the default) |
+| **rust-settings** | Settings in Rust: display (resolution, refresh rate), sound (volume), power plan and drive space, per-app volume and device choice, night light, display arrangement by dragging, network adapters, Wi-Fi on every adapter (password or 802.1X), VPN and proxy, Bluetooth, apps, Windows Update, disk cleanup, theme, about | Nothing, apart from the file and a shortcut. Win+I and the bar menus open this window instead of Windows Settings (only a few rare pages still open the system ones) |
| **debloat** | Off: telemetry, Copilot, Recall, Start ads, Edge in the background | Services and registry policies; old values are saved and restored on uninstall. **Command line only:** `install debloat --yes` |
| **purge** | Removes the bundled junk like Tiny11 does: Clipchamp, News, Weather, Xbox overlays, Teams, Cortana, Widgets, Skype and more, plus telemetry tasks | **IRREVERSIBLE, no undo.** Apps are removed for all users and from the image; the Store, Settings, Start and runtimes stay. Run `purge.exe` first: it only lists. **Command line only:** `install purge --yes` (OneDrive and Edge: `purge.exe --apply --onedrive --edge`) |
| chrome-rs | A browser | Not installable yet |
@@ -55,7 +56,8 @@ The gear at the left end of the bar opens **Style**. The choice applies at once
| **Normal** | Windows 11 blue, the bar at the bottom |
| **Terminal** | Green on black, Consolas, square corners |
| **Floating dock** | A pill-shaped bar in the middle; maximized windows get the whole screen, the dock slides away over them and comes back at the bottom edge |
-| **Tiling** | A thin bar at the top, amber accent, square corners; "Tile the windows" puts the open windows side by side |
+| **Tiling** | A thin bar at the top, amber accent, rounded like Normal; "Tile the windows" puts the open windows side by side |
+| **White road** | Light ivory with gold: faint low-poly triangles, some traced in gold, behind the bar, its panels and rust-settings |
The choice is stored in `%ProgramData%\WinRust\style.txt`.
diff --git a/README.ru.md b/README.ru.md
index 99a7a1d..0c66637 100644
--- a/README.ru.md
+++ b/README.ru.md
@@ -40,6 +40,7 @@
| **rust-explorer** | Файловый менеджер с вкладками и рабочий стол | Папки и диски открываются в нём; **Проводник перестаёт быть оболочкой** (возвращается сам, если topbar не работает). Отключаются PcaSvc, InventorySvc, lfsvc, cbdhsvc, DoSvc ставится вручную, процессы svchost объединяются. Нужен topbar |
| **wiztree** | Карта занятого места на диске («WinRust Disk» в Пуске) | Ничего, кроме файла и ярлыка |
| **photoview** | Быстрый просмотр фото | Добавляется в «Открыть с помощью» (по умолчанию не назначается) |
+| **rust-settings** | Параметры на Rust: экран (разрешение, частота, ночной свет, расположение мониторов перетаскиванием), звук (устройства, громкость по приложениям), схема питания, место на дисках и очистка, сетевые адаптеры, Wi-Fi на всех адаптерах (пароль или 802.1X), VPN и прокси, Bluetooth, приложения, Центр обновления, тема, о системе | Ничего, кроме файла и ярлыка. Win+I и меню панели открывают это окно вместо Параметров Windows (лишь несколько редких разделов по-прежнему системные) |
| **debloat** | Отключает телеметрию, Copilot, Recall, рекламу в Пуске, фоновый Edge | Службы и политики реестра; старые значения сохраняются и возвращаются при удалении. **Только из командной строки:** `install debloat --yes` |
| **purge** | Удаляет предустановленный мусор, как Tiny11: Clipchamp, Новости, Погода, Xbox-оверлеи, Teams, Cortana, виджеты, Skype и др., а также задачи телеметрии | **НЕОБРАТИМО, отката нет.** Приложения удаляются для всех пользователей и из образа; Магазин, Параметры, Пуск и среды выполнения остаются. Сначала запустите `purge.exe`: он только показывает список. **Только из командной строки:** `install purge --yes` (OneDrive и Edge: `purge.exe --apply --onedrive --edge`) |
| chrome-rs | Браузер | Пока не ставится |
@@ -55,7 +56,8 @@
| **Обычный** | Синий, как в Windows 11, панель внизу |
| **Терминал** | Зелёный на чёрном, шрифт Consolas, прямые углы |
| **Плавающий док** | Панель-пилюля по центру; развёрнутые окна занимают весь экран, док уезжает из-под них и возвращается у нижнего края |
-| **Тайлинг** | Тонкая панель сверху, янтарный акцент, прямые углы; «Разложить окна плиткой» ставит открытые окна рядом |
+| **Тайлинг** | Тонкая панель сверху, янтарный акцент, скругления как в Обычном; «Разложить окна плиткой» ставит открытые окна рядом |
+| **Белая дорога** | Цвет слоновой кости с золотом: еле заметные треугольники, часть с золотой обводкой, за панелью, её окошками и rust-settings |
Выбор хранится в `%ProgramData%\WinRust\style.txt`.
diff --git a/ROADMAP.md b/ROADMAP.md
index 7d32d8b..13ca72f 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -34,7 +34,14 @@ Each item says how far it was checked: **tests** (unit tests), **built** (compil
- **wiztree**: disk-usage treemap from the MFT. *tests (layout only); not run on a live disk*
- **photoview**: WIC photo viewer, EXIF rotation, "Open with" entry. *ran; EXIF orientations 5 and 7 not checked*
- **debloat**: services and policies (telemetry, Copilot, Recall, ads, Edge background), old values in `%ProgramData%\winrust-debloat\undo.txt`, `--undo`. *dry run ran; `--apply`/`--undo` not run*
-- **purge**: removes the bundled Store apps (installed and provisioned) and the telemetry scheduled tasks like Tiny11 does; OneDrive and Edge only with `--onedrive` / `--edge`. IRREVERSIBLE, a log in `%ProgramData%\winrust-purge emoved.txt`. `purge.exe` lists, `--ask` asks for YES (the bar's right-click menu), `--apply` removes. Protected names (Store, Settings, Start, runtimes) are tested. *tests, dry run ran; `--apply` not run*
+- **purge**: removes the bundled Store apps (installed and provisioned) and the telemetry scheduled tasks like Tiny11 does; OneDrive and Edge only with `--onedrive` / `--edge`. IRREVERSIBLE, a log in `%ProgramData%\winrust-purge
+emoved.txt`. `purge.exe` lists, `--ask` asks for YES (the bar's right-click menu), `--apply` removes. Protected names (Store, Settings, Start, runtimes) are tested. *tests, dry run ran; `--apply` not run*
+- **White road style and new topbar panels**: a fifth, light style (ivory, gold accent, low-poly triangles, some traced in gold, drawn with GDI+ behind the bar, its panels, rust-settings and Explorer's list in white); Quick settings and Wi-Fi panels redrawn: tiles with round icon badges and labels inside, sliders on one card with a shadowed knob, battery pill and round gear, an iOS-style switch, the connected network on its own card with a check mark (link speed and security on hover, Disconnect appears on hover), other networks on one card split by hairlines; a right click on a network opens a small menu (connect / disconnect, forget, known networks); while joining, the signal arcs sweep and a bar slides under the row until it connects or 25 s pass. rust-settings: values that used to step on each click (resolution, refresh rate, scale, orientation, display, screen mode, power plan, screen-off and sleep timeouts) open an animated drop-down list with the current value checked (arrows, Enter, Esc and the wheel work in it); a display without an EDID name reads "Built-in display" instead of `\\.\DISPLAY1`. `topbar --preview quick|wifi` shows a panel alone. *built, tests; panels screenshotted in White road and Tiling, rust-settings and Explorer in White road*
+- **New look** (all programs): the shared palette is now neutral graphite with Apple's system blue (Normal), midnight ink with indigo (Floating dock), refined Terminal and Tiling; Apple's dark-mode green/yellow/red for status everywhere; Segoe UI Variable and Segoe Fluent Icons on Windows 11 (Segoe UI / MDL2 on Windows 10). rtaskmgr, the installer, wiztree and photoview moved from their own colours to the same graphite. rust-settings is redrawn like macOS System Settings: coloured page icons, grouped rounded cards with hairlines and section headers, iOS-style switches, smooth (GDI+) shapes, a centred content column, a floating bottom bar. `WINRUST_STYLE=<name>` previews a style in one process. *built, tests; rust-settings screenshots checked in all four styles, the other programs not looked at after the change*
+- **rust-settings** (first steps): a small Settings window that needs neither Explorer nor the Store Settings app. Pages: Display (resolution and refresh rate of the primary display: a change is temporary, Enter keeps it, Esc or 15 s goes back; tested with `CDS_TEST` first), Sound (volume slider and mute of the default playback device, Core Audio), Power & storage (battery, power plan switch, free space on fixed drives), Network (Wi-Fi/Ethernet adapters and link speed; Wi-Fi: radio on/off, connect to saved, open and new networks with the password typed in the window (profile through the WLAN API, a failed attempt deletes it), hidden networks, disconnect/forget on right click, the result shown with Windows' reason text; scans about every 30 s, not on every refresh), Personalization (dark theme for apps/system, transparency, accent on title bars: four HKCU values), About (read-only), More (opens the system pages through the existing helper). Only documented Win32 calls, nothing run as a command. Installable like wiztree (a file in Program Files and a Start menu shortcut); once installed, Win+I and the bar menus open it for the exact addresses `ms-settings:` (display), `sound`, `personalization`/`colors`/`themes`, `powersleep`/`storagesense`, `network-status`, `about`, all others still go to Windows' Settings. Installer wiring only built, never run; Ethernet: only real cards (Hyper-V, VPN and Wi-Fi Direct adapters hidden), each with address, link speed and an internet dot from the Network List Manager; a click shows IPv4/IPv6, gateway, DNS, DHCP or manual, MAC. Next: Bluetooth, per-device volume. Wi-Fi password entry not tried on a live network yet. Written from scratch (the code offered in PR #14 was not used). Long pages scroll with the wheel, clickable rows highlight under the pointer. *tests (mode, slider, scroll and page-key logic), built, started; display change and volume not tried on a live system*
+- **No more stubs in the settings** (rust-settings, the bar's quick settings, the task manager): rust-settings now has pages for Bluetooth (radio, airplane mode, paired devices with their connection state, pairing a nearby device, removal on a second click), Apps (installed programs, uninstall with a second click) and Windows Update (check, download and install through the Windows Update Agent; installing needs administrator rights). Sound: choose the playback and recording device (the default-device switch is the one undocumented call, the COM class every switcher uses) and the volume of each app. Display: night light (a colour filter of our own, a gamma ramp kept by a background `rust-settings --nightlight`, autostart through a HKCU Run value that uninstall removes; not Windows' schedule-driven one, which is an undocumented per-build blob) and the arrangement of several displays by dragging (snaps flush against a neighbour, Windows refuses gaps; a click picks the display). Network: VPN profiles (connect with the password Windows saved, disconnect), proxy (on/off, address, PAC script, applications told to re-read), Wi-Fi on every adapter and 802.1X (PEAP-MSCHAPv2: user name and password, the profile and per-user credentials through the WLAN API; EAP-TLS with certificates is not offered). Power & storage: disk cleanup (user temp files older than a day, recycle bin with Windows' own confirmation). The bar's quick-settings tiles Bluetooth, Airplane mode, Accessibility (Narrator, Magnifier, sticky and filter keys) and Energy saver show their state and act, with Russian labels; the Wi-Fi tile and panel use every adapter and send enterprise networks to rust-settings. Task manager: core affinity takes a 64-bit mask (winapi 0.3 declares it as 32-bit), so cores above the 32nd work (a process still lives in one processor group, up to 64 logical processors). *tests (new logic: addresses, colour gains, cleaning, snapping, picture mapping, EAP documents, mask), release builds, every page started for 9 s; not tried on a live system: pairing, VPN dialling, Windows Update install, the 802.1X sign-in (no such network at hand), the arrangement drag (one display here), and the quick-settings tiles*
+- **Shortcuts closed**: reshell's watchdog restores the taskbar and then restarts the bar (up to 3 tries in a row, a bar stable for a minute gives them back); topbar remembers the user's own taskbar mode (auto-hide / always on top) in `%APPDATA% opbar-taskbar-state.txt` and gives it back on exit and `--restore`; the rust-explorer desktop sizes its icon area from the real work area (bar at the top or bottom, any height, dock style) and follows changes; rust-settings gets a Scale step and an HDR switch for the primary display (orientation was already there). Night light stays a link to Windows. *built, tests; scale and HDR only read on a live system, not switched; the watchdog restart and the other changes not run on a live system*
+- **Several displays and icons**: rust-settings picks the display its rows act on (resolution, rate, scale, orientation, HDR), switches extend / duplicate / one screen only (confirmed like a resolution, goes back after 15 s) and makes a display the main one. rust-explorer, rust-settings, topbar, wiztree, photoview and the installer got icons in one style (graphite tile, one coloured glyph, drawn 4x and shrunk: smooth at 16-256 px) from `scripts\make-icons.py`; rtaskmgr keeps its own. *built, tests; the display logic ran only on a one-display PC (reads), the icons were checked in the built exes*
## Next (in order)
0. **Phones and safe removal in rust-explorer** (#2): not started, too big for a quick fix. (a) MTP/PTP phones have no drive letter, so they need the Windows Portable Devices API (`IPortableDeviceManager`, `IPortableDeviceContent`, enumerate objects, read and write through `IPortableDeviceResources` streams) behind a second "file system" in rust-explorer next to the path-based one; copy, paste, delete and drag and drop have to be redone on it. (b) Safe removal: a tray icon in topbar (it already hosts tray icons) that lists removable drives, and `CM_Request_Device_Eject` on the device node of the chosen drive (flush first, report "in use" with the process that holds it). (b) is the smaller half and works for USB sticks and disks; (a) is what the issue is mostly about. Needs a real phone and a USB stick to test: nothing here can be checked by unit tests alone.
diff --git a/ROADMAP.ru.md b/ROADMAP.ru.md
index 943bdfd..8cfbc69 100644
--- a/ROADMAP.ru.md
+++ b/ROADMAP.ru.md
@@ -34,7 +34,14 @@
- **wiztree**: карта занятого места по MFT. *тесты (только раскладка); на живом диске не запускался*
- **photoview**: просмотр фото на WIC, поворот по EXIF, пункт «Открыть с помощью». *запускалось; EXIF-ориентации 5 и 7 не проверялись*
- **debloat**: службы и политики (телеметрия, Copilot, Recall, реклама, фоновый Edge), старые значения в `%ProgramData%\winrust-debloat\undo.txt`, `--undo`. *сухой прогон запускался; `--apply`/`--undo` нет*
-- **purge**: удаляет предустановленные Store-приложения (установленные и из образа) и задачи телеметрии, как Tiny11; OneDrive и Edge только с `--onedrive` / `--edge`. НЕОБРАТИМО, журнал в `%ProgramData%\winrust-purge emoved.txt`. `purge.exe` показывает список, `--ask` просит ввести YES (меню по правому клику на панели), `--apply` удаляет. Защищённые имена (Магазин, Параметры, Пуск, среды выполнения) проверены тестами. *тесты, пробный запуск выполнен; `--apply` не запускался*
+- **purge**: удаляет предустановленные Store-приложения (установленные и из образа) и задачи телеметрии, как Tiny11; OneDrive и Edge только с `--onedrive` / `--edge`. НЕОБРАТИМО, журнал в `%ProgramData%\winrust-purge
+emoved.txt`. `purge.exe` показывает список, `--ask` просит ввести YES (меню по правому клику на панели), `--apply` удаляет. Защищённые имена (Магазин, Параметры, Пуск, среды выполнения) проверены тестами. *тесты, пробный запуск выполнен; `--apply` не запускался*
+- **Стиль «Белая дорога» и новые панели topbar**: пятый, светлый стиль (слоновая кость, золотой акцент, треугольники, часть с золотой обводкой, через GDI+ за панелью, её окошками, rust-settings; список Проводника белый); быстрые настройки и Wi-Fi перерисованы: плитки с круглыми значками и подписями внутри, ползунки на одной карточке с ручкой с тенью, батарея в «пилюле» и круглая шестерёнка, переключатель как в iOS, подключённая сеть на своей карточке с галочкой (скорость и защита при наведении, там же появляется «Отключиться»), остальные сети на одной карточке с тонкими разделителями; правый клик по сети открывает меню (подключиться / отключиться, забыть, известные сети); при подключении дуги сигнала бегут, а под строкой скользит полоска, пока сеть не подключится или не пройдёт 25 с. rust-settings: значения, которые раньше перебирались по клику (разрешение, частота, масштаб, ориентация, дисплей, режим экранов, схема питания, отключение экрана и сон), открывают анимированный выпадающий список с галочкой у текущего (работают стрелки, Enter, Esc и колесо); дисплей без имени в EDID называется «Встроенный экран», а не `\\.\DISPLAY1`. `topbar --preview quick|wifi` показывает панель отдельно. *собрано, тесты; панели сняты в «Белой дороге» и «Тайлинге», rust-settings и Проводник в «Белой дороге»*
+- **Новый вид** (все программы): общая палитра теперь нейтральный графит с системным синим Apple (Обычный), полуночный с индиго (Плавающий док), обновлённые Терминал и Тайлинг; везде зелёный/жёлтый/красный Apple для состояний; Segoe UI Variable и Segoe Fluent Icons на Windows 11 (Segoe UI / MDL2 на Windows 10). rtaskmgr, установщик, wiztree и photoview перешли со своих цветов на тот же графит. rust-settings перерисован в духе Системных настроек macOS: цветные значки разделов, сгруппированные скруглённые карточки с тонкими разделителями и заголовками групп, переключатели как в iOS, сглаженные фигуры (GDI+), колонка по центру, плавающая нижняя панель. `WINRUST_STYLE=<имя>` показывает стиль в одном процессе. *собрано, тесты; скриншоты rust-settings проверены во всех четырёх стилях, остальные программы после изменения не смотрели*
+- **rust-settings** (первые шаги): небольшое окно Параметров, которому не нужны ни Проводник, ни Store-приложение Параметры. Страницы: Экран (разрешение и частота основного дисплея: изменение временное, Enter оставляет, Esc или 15 с возвращают; сначала проверка `CDS_TEST`), Звук (ползунок громкости и выключение звука на устройстве по умолчанию, Core Audio), Питание и диски (батарея, смена схемы питания, свободное место на постоянных дисках), Сеть (адаптеры Wi-Fi/Ethernet и скорость связи; Wi-Fi: включение/выключение, подключение к сохранённым, открытым и новым сетям с паролем, введённым в окне (профиль через WLAN API, неудачная попытка его удаляет), скрытые сети, отключить/забыть по правой кнопке, итог с текстом причины от Windows; сканирование примерно раз в 30 с, а не при каждом обновлении), Персонализация (тёмная тема приложений и системы, прозрачность, акцент на заголовках: четыре значения в HKCU), О системе (только чтение), Другие разделы (открывает системные страницы через существующий помощник). Только документированные вызовы Win32, ничего не запускается как команда. Ставится как wiztree (файл в Program Files и ярлык в меню Пуск); после установки Win+I и меню панели открывают его для точных адресов `ms-settings:` (экран), `sound`, `personalization`/`colors`/`themes`, `powersleep`/`storagesense`, `network-status`, `about`, остальные идут в Параметры Windows. Подключение к установщику только собрано, не запускалось; Ethernet: только настоящие карты (Hyper-V, VPN и Wi-Fi Direct скрыты), у каждой адрес, скорость и точка «интернет» от Network List Manager; по клику IPv4/IPv6, шлюз, DNS, DHCP или вручную, MAC. Дальше: Bluetooth, громкость по приложениям. Ввод пароля Wi-Fi на живой сети ещё не пробовали. Написано с нуля (код из PR #14 не использовался). Длинные страницы прокручиваются колесом, кликабельные строки подсвечиваются под курсором. *тесты (логика режимов, ползунка, прокрутки и выбора страницы), собрано, запущено; смену режима экрана и громкость на живой системе не пробовали*
+- **Заглушек в настройках больше нет** (rust-settings, быстрые настройки панели, диспетчер задач): в rust-settings появились страницы Bluetooth (радио, авиарежим, сопряжённые устройства с состоянием подключения, сопряжение ближайшего устройства, удаление вторым кликом), Приложения (установленные программы, удаление вторым кликом) и Центр обновления (проверка, загрузка и установка через Windows Update Agent; для установки нужны права администратора). Звук: выбор устройств воспроизведения и записи (смена устройства по умолчанию, единственный недокументированный вызов, тот COM-класс, которым пользуются все переключатели) и громкость каждого приложения. Экран: ночной свет (свой цветовой фильтр: гамма-рампа, которую держит фоновый `rust-settings --nightlight`, автозапуск через значение Run в HKCU, его удаляет uninstall; не системный по расписанию, у него недокументированный блок под каждую сборку) и расположение нескольких мониторов перетаскиванием (прилипает вплотную к соседу, Windows не принимает зазоры; клик выбирает монитор). Сеть: профили VPN (подключение с паролем, который сохранила Windows, отключение), прокси (вкл/выкл, адрес, PAC-скрипт, программам сообщается о смене), Wi-Fi на всех адаптерах и 802.1X (PEAP-MSCHAPv2: имя и пароль, профиль и учётные данные пользователя через WLAN API; EAP-TLS с сертификатами не предлагается). Питание и диски: очистка диска (временные файлы пользователя старше суток, корзина с подтверждением самой Windows). Плитки быстрых настроек панели Bluetooth, Авиарежим, Спец. возможности (диктор, лупа, залипание и фильтрация клавиш) и Экономия энергии показывают состояние и работают, подписи по-русски; плитка и панель Wi-Fi используют все адаптеры и отправляют корпоративные сети в rust-settings. Диспетчер задач: привязка к ядрам принимает 64-битную маску (winapi 0.3 объявляет её 32-битной), поэтому ядра выше 32-го работают (процесс по-прежнему живёт в одной группе процессоров, до 64 логических). *тесты (новая логика: адреса, коэффициенты цвета, очистка, прилипание, перевод координат картинки, EAP-документы, маска), релизные сборки, каждая страница запущена на 9 с; на живой системе не пробовали: сопряжение, набор VPN, установку обновлений, вход 802.1X (такой сети нет под рукой), перетаскивание мониторов (здесь один монитор) и плитки быстрых настроек*
+- **Закрыты упрощения**: watchdog reshell возвращает панель задач и затем перезапускает bar (до 3 попыток подряд, bar, проработавший минуту, возвращает попытки); topbar запоминает собственный режим панели задач пользователя (автоскрытие / поверх окон) в `%APPDATA% opbar-taskbar-state.txt` и возвращает его при выходе и `--restore`; рабочий стол rust-explorer считает область значков по настоящей рабочей области (панель сверху или снизу, любой высоты, режим дока) и следит за её изменениями; в rust-settings появились шаг масштаба и переключатель HDR для основного экрана (ориентация уже была). Ночной свет остаётся ссылкой в Windows. *собрано, тесты; масштаб и HDR только прочитаны на живой системе, не переключались; перезапуск watchdog и остальные правки на живой системе не запускались*
+- **Несколько экранов и иконки**: rust-settings выбирает дисплей, к которому относятся строки (разрешение, частота, масштаб, ориентация, HDR), переключает «расширить / повторять / только один экран» (с подтверждением как у разрешения, через 15 с возвращает) и делает дисплей основным. У rust-explorer, rust-settings, topbar, wiztree, photoview и установщика появились иконки в одном стиле (графитовая плитка, один цветной значок, рисуются в 4 раза крупнее и сжимаются: гладкие от 16 до 256 px) из `scripts\make-icons.py`; у rtaskmgr осталась своя. *собрано, тесты; логика дисплеев запускалась только на ПК с одним экраном (чтение), иконки проверены в собранных exe*
## Дальше (по порядку)
0. **Телефоны и безопасное извлечение в rust-explorer** (#2): не начато, для быстрой правки слишком много. (а) У MTP/PTP-телефонов нет буквы диска, поэтому нужен Windows Portable Devices API (`IPortableDeviceManager`, `IPortableDeviceContent`, перечисление объектов, чтение и запись через потоки `IPortableDeviceResources`) как вторая «файловая система» в rust-explorer рядом с путевой; копирование, вставку, удаление и перетаскивание придётся переделать под неё. (б) Безопасное извлечение: значок в трее topbar (трей там уже есть), список съёмных дисков и `CM_Request_Device_Eject` для узла выбранного диска (сначала сброс буферов, при «занято» показать, какой процесс держит). Часть (б) меньше и работает для флешек и дисков; (а) это то, о чём в основном issue. Для проверки нужны настоящий телефон и флешка: одними юнит-тестами не обойтись.
diff --git a/ReShell/src/watchdog.rs b/ReShell/src/watchdog.rs
index 61a4c0a..40f538a 100644
--- a/ReShell/src/watchdog.rs
+++ b/ReShell/src/watchdog.rs
@@ -1,10 +1,13 @@
//! 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.
+//! the user would have no taskbar at all. reshell is already running from the Run key, so it watches: first
+//! `topbar.exe --restore` (the taskbar is back at once), then it starts the bar again. A bar that keeps dying is given up
+//! after `MAX_RESTARTS` tries in a row, so a bar that crashes on start cannot loop forever; the taskbar then stays.
use std::{os::windows::process::CommandExt, process::Command, thread, time::Duration};
use windows_sys::Win32::UI::WindowsAndMessaging::{FindWindowW, IsWindowVisible};
+const MAX_RESTARTS: u32 = 3;
+const STABLE_CHECKS: u32 = 12; // ~60 s of a running bar: it was a one-off crash, the tries start over
+
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain([0]).collect()
}
@@ -14,17 +17,49 @@ fn broken(bar_up: bool, tray_present: bool, tray_visible: bool) -> bool {
!bar_up && tray_present && !tray_visible
}
+#[derive(Debug, PartialEq, Eq)]
+enum Act {
+ Nothing,
+ /// Bring the taskbar back, then start the bar again.
+ Recover,
+}
+
+#[derive(Default)]
+struct Guard {
+ strikes: u32,
+ restarts: u32,
+ stable: u32,
+}
+
+impl Guard {
+ /// One look (every 5 s): what to do now.
+ fn step(&mut self, bar_up: bool, broke: bool) -> Act {
+ self.stable = if bar_up { self.stable + 1 } else { 0 };
+ if self.stable >= STABLE_CHECKS {
+ self.restarts = 0;
+ }
+ self.strikes = if broke { self.strikes + 1 } else { 0 };
+ // two checks in a row (~10 s): a bar that is only just starting must not be "restored" under its feet
+ if self.strikes == 2 && self.restarts < MAX_RESTARTS {
+ self.restarts += 1;
+ self.strikes = 0;
+ return Act::Recover;
+ }
+ Act::Nothing
+ }
+}
+
pub fn run() {
- let mut strikes = 0;
+ let mut g = Guard::default();
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
+ let broke = broken(!bar.is_null(), !tray.is_null(), !tray.is_null() && unsafe { IsWindowVisible(tray) } != 0);
+ if g.step(!bar.is_null(), broke) == Act::Recover {
if let Ok(exe) = std::env::current_exe() {
- let _ = Command::new(exe.with_file_name("topbar.exe")).arg("--restore").creation_flags(0x0800_0000).status();
+ let topbar = exe.with_file_name("topbar.exe");
+ let _ = Command::new(&topbar).arg("--restore").creation_flags(0x0800_0000).status();
+ let _ = Command::new(&topbar).creation_flags(0x0800_0000).spawn(); // detached: the bar outlives this call
}
}
}
@@ -32,7 +67,7 @@ pub fn run() {
#[cfg(test)]
mod tests {
- use super::broken;
+ use super::*;
#[test]
fn only_bar_gone_and_taskbar_hidden_is_broken() {
assert!(broken(false, true, false));
@@ -40,4 +75,37 @@ mod tests {
assert!(!broken(false, true, true)); // taskbar already back
assert!(!broken(false, false, false)); // explorer restarting
}
+
+ #[test]
+ fn recovers_after_two_broken_checks() {
+ let mut g = Guard::default();
+ assert_eq!(g.step(false, true), Act::Nothing);
+ assert_eq!(g.step(false, true), Act::Recover);
+ }
+
+ #[test]
+ fn a_bar_that_keeps_crashing_is_given_up() {
+ let mut g = Guard::default();
+ let mut recovered = 0;
+ for _ in 0..40 {
+ // the bar starts, dies at once: broken again
+ if g.step(false, true) == Act::Recover {
+ recovered += 1;
+ }
+ }
+ assert_eq!(recovered, MAX_RESTARTS);
+ }
+
+ #[test]
+ fn a_stable_bar_gives_the_tries_back() {
+ let mut g = Guard::default();
+ for _ in 0..4 {
+ g.step(false, true);
+ }
+ assert_eq!(g.restarts, 2);
+ for _ in 0..STABLE_CHECKS {
+ g.step(true, false);
+ }
+ assert_eq!(g.restarts, 0);
+ }
}
diff --git a/app.ico b/app.ico
new file mode 100644
index 0000000..8a246a6
Binary files /dev/null and b/app.ico differ
diff --git a/app.rc b/app.rc
index 8142754..49bf0c8 100644
--- a/app.rc
+++ b/app.rc
@@ -1 +1,2 @@
+1 ICON "app.ico"
1 24 "app.manifest"
diff --git a/build.rs b/build.rs
index 5ce3700..3164bf2 100644
--- a/build.rs
+++ b/build.rs
@@ -2,6 +2,7 @@ use std::{env, fs, path::Path};
fn main() {
println!("cargo:rerun-if-changed=app.rc");
+ println!("cargo:rerun-if-changed=app.ico");
println!("cargo:rerun-if-changed=app.manifest");
println!("cargo:rerun-if-changed=payload.txt");
embed_resource::compile("app.rc", embed_resource::NONE).manifest_required().unwrap();
diff --git a/common/Cargo.toml b/common/Cargo.toml
index 34fcca8..9cb1152 100644
--- a/common/Cargo.toml
+++ b/common/Cargo.toml
@@ -4,4 +4,4 @@ version = "0.1.0"
edition = "2024"
[dependencies]
-windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Graphics_Dwm", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Ioctl", "Win32_UI_WindowsAndMessaging"] }
+windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Graphics_Dwm", "Win32_Graphics_Gdi", "Win32_Graphics_GdiPlus", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Ioctl", "Win32_UI_WindowsAndMessaging"] }
diff --git a/common/src/settings.rs b/common/src/settings.rs
index 99be0ba..caab37a 100644
--- a/common/src/settings.rs
+++ b/common/src/settings.rs
@@ -42,14 +42,63 @@ if($started){
$bad=0
while($bad -lt 5 -and (Get-Process SystemSettings -ErrorAction SilentlyContinue)){ Start-Sleep -Seconds 2; if(Get-Process SystemSettings -ErrorAction SilentlyContinue | Where-Object { -not $_.Responding }){ $bad++ } else { $bad=0 } }
KillStale
- Get-CimInstance Win32_Process -Filter "Name='explorer.exe'" | Where-Object { $_.CommandLine -match '(?i)explorer\.exe"?\s*$' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }
+ Get-CimInstance Win32_Process -Filter "Name='explorer.exe'" | Where-Object { $_.CommandLine -match '(?i)explorer\.exe"?(\s+/NoUACCheck)?\s*$' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }
$rx="$env:ProgramFiles\rust-explorer\rust-explorer.exe"
if((Test-Path $rx) -and -not (Get-CimInstance Win32_Process -Filter "Name='rust-explorer.exe'" | Where-Object { $_.CommandLine -match '--desktop' })){ Start-Process $rx -ArgumentList '--desktop' }
}
"#;
+/// The rust-settings page that stands for an exact `ms-settings:` address (a bare `ms-settings:` is Win+I: the first page).
+/// Only these: any other address keeps going to Windows' own Settings.
+fn own_page(uri: &str) -> Option<&'static str> {
+ match uri.trim().to_ascii_lowercase().as_str() {
+ "ms-settings:" | "ms-settings:display" | "ms-settings:nightlight" => Some("display"),
+ "ms-settings:sound" => Some("sound"),
+ "ms-settings:personalization" | "ms-settings:colors" | "ms-settings:personalization-colors" | "ms-settings:themes" => Some("personalization"),
+ "ms-settings:powersleep" | "ms-settings:storagesense" | "ms-settings:batterysaver" => Some("power"),
+ "ms-settings:network-status" | "ms-settings:network-wifi" | "ms-settings:network-wifisettings" | "ms-settings:network-vpn" | "ms-settings:network-proxy" => Some("network"),
+ "ms-settings:bluetooth" | "ms-settings:network-airplanemode" => Some("bluetooth"),
+ "ms-settings:appsfeatures" => Some("apps"),
+ "ms-settings:windowsupdate" => Some("update"),
+ "ms-settings:about" => Some("about"),
+ _ => None,
+ }
+}
+
+/// rust-settings.exe where the installer puts it: Program Files is writable by administrators only (a user-writable
+/// folder would let any program swap the exe that Win+I starts).
+fn own_exe() -> Option<std::path::PathBuf> {
+ let exe = std::path::PathBuf::from(std::env::var_os("ProgramFiles")?).join("rust-settings").join("rust-settings.exe");
+ exe.is_file().then_some(exe)
+}
+
/// `uri` is passed through the environment, never spliced into the script. A second call while the first still waits is harmless.
pub fn open(uri: &str) {
+ if let (Some(page), Some(exe)) = (own_page(uri), own_exe()) {
+ if Command::new(exe).arg(page).stdin(Stdio::null()).creation_flags(0x0800_0000).spawn().is_ok() {
+ return;
+ }
+ }
let _ = Command::new("powershell").args(["-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden", "-Command", PS])
.env("WR_URI", uri).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).creation_flags(0x0800_0000).spawn();
}
+
+#[cfg(test)]
+mod tests {
+ use super::own_page;
+
+ #[test]
+ fn only_exact_addresses_go_to_rust_settings() {
+ assert_eq!(own_page("ms-settings:"), Some("display"));
+ assert_eq!(own_page("MS-Settings:Sound"), Some("sound"));
+ assert_eq!(own_page("ms-settings:themes"), Some("personalization"));
+ assert_eq!(own_page("ms-settings:powersleep"), Some("power"));
+ assert_eq!(own_page("ms-settings:network-status"), Some("network"));
+ assert_eq!(own_page("ms-settings:personalization-background"), None);
+ assert_eq!(own_page("ms-settings:network-wifi"), Some("network"));
+ assert_eq!(own_page("ms-settings:bluetooth"), Some("bluetooth"));
+ assert_eq!(own_page("ms-settings:windowsupdate"), Some("update"));
+ assert_eq!(own_page("ms-settings:easeofaccess"), None);
+ assert_eq!(own_page("ms-settings:sound; calc"), None);
+ }
+}
diff --git a/common/src/style.rs b/common/src/style.rs
index 4c27882..81c4fc4 100644
--- a/common/src/style.rs
+++ b/common/src/style.rs
@@ -11,10 +11,11 @@ pub enum Style {
Normal,
Terminal, // monospace, green on black, square corners
Dock, // the bar is a floating pill in the middle
- Tiling, // a thin status strip at the top, square corners, windows side by side
+ Tiling, // a thin status strip at the top, windows side by side
+ Road, // "White road": light ivory, faint triangles in the background
}
-pub const ALL: [Style; 4] = [Style::Normal, Style::Terminal, Style::Dock, Style::Tiling];
+pub const ALL: [Style; 5] = [Style::Normal, Style::Terminal, Style::Dock, Style::Tiling, Style::Road];
impl Style {
pub fn name(self) -> &'static str {
@@ -23,6 +24,7 @@ impl Style {
Style::Terminal => "terminal",
Style::Dock => "dock",
Style::Tiling => "tiling",
+ Style::Road => "road",
}
}
/// Unknown or empty text (no file yet, a hand edit) is the normal style.
@@ -30,11 +32,16 @@ impl Style {
ALL.into_iter().find(|v| v.name().eq_ignore_ascii_case(s.trim())).unwrap_or(Style::Normal)
}
/// Square corners everywhere.
+ // only the terminal keeps the monospace, square look; tiling uses the same sans and rounded shapes as the rest
pub fn square(self) -> bool {
- matches!(self, Style::Terminal | Style::Tiling)
+ self == Style::Terminal
}
pub fn mono(self) -> bool {
- matches!(self, Style::Terminal | Style::Tiling)
+ self == Style::Terminal
+ }
+ /// Dark text on a light background.
+ pub fn light(self) -> bool {
+ self == Style::Road
}
}
@@ -56,7 +63,9 @@ fn store(s: Style) {
/// Reads the file again now (on the "style changed" broadcast).
pub fn reload() {
- store(Style::parse(&file().and_then(|f| std::fs::read_to_string(f).ok()).unwrap_or_default()));
+ // WINRUST_STYLE overrides the file for this process only (to look at a style without switching every window)
+ let name = std::env::var("WINRUST_STYLE").ok().or_else(|| file().and_then(|f| std::fs::read_to_string(f).ok()));
+ store(Style::parse(&name.unwrap_or_default()));
}
/// The current style. The file is read again at most once a second, so a program that missed the broadcast still follows.
@@ -77,6 +86,31 @@ pub fn set_style(s: Style) {
unsafe { PostMessageW(HWND_BROADCAST, msg(), 0, 0) };
}
+fn autohide_file() -> Option<PathBuf> {
+ std::env::var_os("ProgramData").map(|p| PathBuf::from(p).join("WinRust").join("autohide.txt"))
+}
+
+/// The bar hides when the pointer is away and comes back at the screen edge (off unless the file says 1). Re-read once a second.
+pub fn autohide() -> bool {
+ if now_ms().saturating_sub(HIDE_AT.load(Relaxed)) > 1000 {
+ HIDE.store(autohide_file().and_then(|f| std::fs::read_to_string(f).ok()).is_some_and(|s| s.trim() == "1") as u8, Relaxed);
+ HIDE_AT.store(now_ms(), Relaxed);
+ }
+ HIDE.load(Relaxed) == 1
+}
+
+static HIDE: AtomicU8 = AtomicU8::new(0);
+static HIDE_AT: AtomicU64 = AtomicU64::new(0);
+
+pub fn set_autohide(on: bool) {
+ HIDE.store(on as u8, Relaxed);
+ HIDE_AT.store(now_ms(), Relaxed);
+ if let Some(f) = autohide_file() {
+ let _ = std::fs::create_dir_all(f.parent().unwrap());
+ let _ = std::fs::write(f, if on { "1" } else { "0" });
+ }
+}
+
/// The broadcast message a window gets when the style changed: call `reload()` and repaint.
pub fn msg() -> u32 {
static M: AtomicU32 = AtomicU32::new(0);
@@ -106,25 +140,127 @@ pub const fn rgb(r: u8, g: u8, b: u8) -> u32 {
r as u32 | (g as u32) << 8 | (b as u32) << 16
}
-/// In the order of `ALL`.
-pub const PALS: [Pal; 4] = [
- // normal: Windows 11 blue
- Pal { bg: rgb(24, 30, 44), line: rgb(44, 52, 72), hover: rgb(40, 48, 68), active: rgb(52, 61, 84), accent: rgb(76, 194, 255), text: rgb(255, 255, 255), dim: rgb(150, 158, 175) },
+/// In the order of `ALL`. Neutral, low-contrast surfaces and one restrained accent (the look of macOS / modern fintech apps).
+pub const PALS: [Pal; 5] = [
+ // normal: graphite with the Apple system blue
+ Pal { bg: rgb(22, 22, 24), line: rgb(46, 46, 50), hover: rgb(36, 36, 40), active: rgb(44, 44, 49), accent: rgb(10, 132, 255), text: rgb(245, 245, 247), dim: rgb(142, 142, 147) },
// terminal: green on black
- Pal { bg: rgb(10, 15, 10), line: rgb(40, 72, 40), hover: rgb(20, 40, 20), active: rgb(28, 56, 28), accent: rgb(91, 215, 91), text: rgb(207, 232, 207), dim: rgb(100, 145, 100) },
- // dock: graphite with violet
- Pal { bg: rgb(27, 29, 34), line: rgb(50, 53, 62), hover: rgb(42, 45, 53), active: rgb(52, 55, 66), accent: rgb(167, 139, 250), text: rgb(255, 255, 255), dim: rgb(154, 160, 170) },
+ Pal { bg: rgb(8, 11, 9), line: rgb(30, 48, 35), hover: rgb(16, 28, 20), active: rgb(22, 38, 27), accent: rgb(74, 222, 128), text: rgb(204, 232, 212), dim: rgb(98, 132, 108) },
+ // dock: midnight ink with indigo
+ Pal { bg: rgb(17, 18, 25), line: rgb(40, 42, 56), hover: rgb(29, 31, 42), active: rgb(37, 40, 54), accent: rgb(124, 134, 255), text: rgb(240, 241, 246), dim: rgb(138, 142, 160) },
// tiling: dark with amber
- Pal { bg: rgb(17, 19, 23), line: rgb(40, 44, 52), hover: rgb(30, 34, 41), active: rgb(38, 43, 52), accent: rgb(229, 192, 123), text: rgb(215, 218, 224), dim: rgb(110, 117, 130) },
+ Pal { bg: rgb(16, 17, 20), line: rgb(38, 40, 46), hover: rgb(27, 29, 34), active: rgb(35, 37, 43), accent: rgb(245, 182, 82), text: rgb(224, 226, 231), dim: rgb(120, 125, 138) },
+ // white road: warm ivory with gold
+ Pal { bg: rgb(247, 245, 240), line: rgb(226, 220, 207), hover: rgb(238, 233, 222), active: rgb(232, 225, 210), accent: rgb(176, 134, 52), text: rgb(28, 26, 22), dim: rgb(124, 117, 104) },
];
+/// Status colours shared by every style (Apple's dark-mode system green, yellow, red).
+pub const GOOD: u32 = rgb(48, 209, 88);
+pub const WARN: u32 = rgb(255, 214, 10);
+pub const BAD: u32 = rgb(255, 69, 58);
+
pub fn pal() -> &'static Pal {
&PALS[ALL.iter().position(|&s| s == style()).unwrap_or(0)]
}
+/// A raised surface (a card, a tile): pure white on the light style, a step up from the background on the dark ones.
+pub fn card() -> u32 {
+ if style().light() { rgb(255, 255, 255) } else { mix(pal().bg, pal().text, 0.06) }
+}
+
+/// Text and glyphs drawn on an accent fill.
+pub fn on_accent() -> u32 {
+ if style().light() { rgb(255, 255, 255) } else { pal().bg }
+}
+
+/// `a` moved toward `b` by `t` (0..1), per channel.
+pub 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.clamp(0.0, 1.0)).round() as u32
+ };
+ ch(0) | ch(8) << 8 | ch(16) << 16
+}
+
+/// The White road background over `r`: faceted ivory triangles, a few of them traced in gold.
+/// Does nothing in the other styles. Needs GDI+ started (GdiplusStartup) by the program.
+pub unsafe fn backdrop(dc: windows_sys::Win32::Graphics::Gdi::HDC, r: windows_sys::Win32::Foundation::RECT, scale: f32) {
+ use windows_sys::Win32::Graphics::GdiPlus::*;
+ if !style().light() {
+ return;
+ }
+ let mut g: *mut GpGraphics = std::ptr::null_mut();
+ if unsafe { GdipCreateFromHDC(dc, &mut g) } != 0 || g.is_null() {
+ return;
+ }
+ let argb = |c: u32, a: f32| ((a.clamp(0.0, 1.0) * 255.0) as u32) << 24 | (c & 255) << 16 | (c & 0xFF00) | (c >> 16 & 255);
+ let (x0, y0, w, h) = (r.left as f32, r.top as f32, (r.right - r.left) as f32, (r.bottom - r.top) as f32);
+ let s = 58.0 * scale.max(0.5);
+ let (cols, rows) = ((w / s) as i32 + 2, (h / (s * 0.866)) as i32 + 2);
+ // a lattice of equilateral-ish triangles; each vertex nudged by a hash so the facets look cut by hand
+ let pt = |i: i32, j: i32| {
+ let (hx, hy) = (hash(i, j, 1) - 0.5, hash(i, j, 2) - 0.5);
+ let off = if j & 1 == 1 { s * 0.5 } else { 0.0 };
+ PointF { X: x0 + i as f32 * s - off + hx * s * 0.34, Y: y0 + j as f32 * s * 0.866 + hy * s * 0.3 - s * 0.4 }
+ };
+ let gold = pal().accent;
+ unsafe {
+ GdipSetSmoothingMode(g, SmoothingModeAntiAlias);
+ let mut br: *mut GpSolidFill = std::ptr::null_mut();
+ GdipCreateSolidFill(0, &mut br);
+ let mut pen: *mut GpPen = std::ptr::null_mut();
+ GdipCreatePen1(0, 1.0, UnitPixel, &mut pen);
+ for j in 0..rows {
+ for i in 0..cols {
+ let (a, b, c, d) = if j & 1 == 0 { (pt(i, j), pt(i + 1, j), pt(i, j + 1), pt(i + 1, j + 1)) } else { (pt(i, j), pt(i + 1, j), pt(i + 1, j + 1), pt(i + 2, j + 1)) };
+ for (k, tri) in [[a, b, c], [b, d, c]].iter().enumerate() {
+ let v = hash(i, j, 3 + k as u32);
+ // light from the top left: most facets near white, some a touch warmer or greyer
+ let shade = if v < 0.5 { mix(pal().bg, rgb(255, 255, 255), 0.25 + v) } else { mix(pal().bg, rgb(226, 214, 190), (v - 0.5) * 0.45) };
+ GdipSetSolidFillColor(br, argb(shade, 1.0));
+ GdipFillPolygon(g, br as *mut GpBrush, tri.as_ptr(), 3, FillModeAlternate);
+ // facet edges: a hairline of white; one triangle in nine traced in gold
+ let (edge, wd) = if hash(i, j, 7 + k as u32) > 0.84 { (argb(gold, 0.6), 1.0 * scale) } else { (argb(rgb(255, 255, 255), 0.7), 0.6) };
+ GdipSetPenColor(pen, edge);
+ GdipSetPenWidth(pen, wd);
+ GdipDrawPolygon(g, pen, tri.as_ptr(), 3);
+ }
+ }
+ }
+ GdipDeletePen(pen);
+ GdipDeleteBrush(br as *mut GpBrush);
+ GdipDeleteGraphics(g);
+ }
+}
+
+/// 0..1 from a lattice point (stable between paints).
+fn hash(i: i32, j: i32, salt: u32) -> f32 {
+ let mut x = (i as u32).wrapping_mul(0x9E37_79B1) ^ (j as u32).wrapping_mul(0x85EB_CA77) ^ salt.wrapping_mul(0xC2B2_AE3D);
+ x ^= x >> 15;
+ x = x.wrapping_mul(0x2C1B_3C6D);
+ x ^= x >> 12;
+ (x & 0xFFFF) as f32 / 65535.0
+}
+
+fn font_file(name: &str) -> bool {
+ std::env::var_os("WINDIR").is_some_and(|w| PathBuf::from(w).join("Fonts").join(name).is_file())
+}
+
+/// The proportional UI font: Windows 11's Segoe UI Variable where it is installed, else Segoe UI.
+pub fn sans_face() -> &'static str {
+ static F: std::sync::OnceLock<&str> = std::sync::OnceLock::new();
+ F.get_or_init(|| if font_file("SegUIVar.ttf") { "Segoe UI Variable Text" } else { "Segoe UI" })
+}
+
/// The UI font of the current style.
pub fn ui_face() -> &'static str {
- if style().mono() { "Consolas" } else { "Segoe UI" }
+ if style().mono() { "Consolas" } else { sans_face() }
+}
+
+/// The icon font: Segoe Fluent Icons (Windows 11, same code points) or Segoe MDL2 Assets.
+pub fn icon_face() -> &'static str {
+ static F: std::sync::OnceLock<&str> = std::sync::OnceLock::new();
+ F.get_or_init(|| if font_file("SegoeIcons.ttf") { "Segoe Fluent Icons" } else { "Segoe MDL2 Assets" })
}
#[cfg(test)]
@@ -139,5 +275,13 @@ mod tests {
assert_eq!(Style::parse(" Tiling\r\n"), Style::Tiling);
assert_eq!(Style::parse(""), Style::Normal);
assert_eq!(Style::parse("neon"), Style::Normal);
+ assert_eq!(PALS.len(), ALL.len());
+ }
+
+ #[test]
+ fn hash_is_stable_and_in_range() {
+ assert_eq!(hash(3, 4, 1), hash(3, 4, 1));
+ assert!((0..50).all(|i| (0.0..=1.0).contains(&hash(i, -i, 2))));
+ assert_eq!(mix(rgb(0, 0, 0), rgb(200, 100, 50), 0.5), rgb(100, 50, 25));
}
}
diff --git a/payload.txt b/payload.txt
index 608a40c..9ed3728 100644
--- a/payload.txt
+++ b/payload.txt
@@ -10,5 +10,6 @@ rust-explorer.exe = target/release/rust-explorer.exe
rs-shell.exe = target/release/rs-shell.exe
wiztree.exe = target/release/wiztree.exe
photoview.exe = target/release/photoview.exe
+rust-settings.exe = target/release/rust-settings.exe
debloat.exe = target/release/debloat.exe
purge.exe = target/release/purge.exe
diff --git a/plugins/photoview/Cargo.toml b/plugins/photoview/Cargo.toml
index f5bdb2f..72d6a1b 100644
--- a/plugins/photoview/Cargo.toml
+++ b/plugins/photoview/Cargo.toml
@@ -4,6 +4,10 @@ version = "0.1.0"
edition = "2024"
[dependencies]
+winrust-common = { path = "../../common" }
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"] }
+
+[build-dependencies]
+embed-resource = "3"
diff --git a/plugins/photoview/app.ico b/plugins/photoview/app.ico
new file mode 100644
index 0000000..443403f
Binary files /dev/null and b/plugins/photoview/app.ico differ
diff --git a/plugins/photoview/app.rc b/plugins/photoview/app.rc
new file mode 100644
index 0000000..0a9daf1
--- /dev/null
+++ b/plugins/photoview/app.rc
@@ -0,0 +1 @@
+1 ICON "app.ico"
diff --git a/plugins/photoview/build.rs b/plugins/photoview/build.rs
new file mode 100644
index 0000000..e8d32ea
--- /dev/null
+++ b/plugins/photoview/build.rs
@@ -0,0 +1,5 @@
+fn main() {
+ println!("cargo:rerun-if-changed=app.rc");
+ println!("cargo:rerun-if-changed=app.ico");
+ embed_resource::compile("app.rc", embed_resource::NONE).manifest_optional().unwrap();
+}
diff --git a/plugins/photoview/src/main.rs b/plugins/photoview/src/main.rs
index 8e11109..644dd14 100644
--- a/plugins/photoview/src/main.rs
+++ b/plugins/photoview/src/main.rs
@@ -25,7 +25,7 @@ use windows_sys::Win32::{
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)
+const BG: [u8; 3] = [24, 22, 22]; // BGR of rgb(22, 22, 24), the shared graphite
static GEN: AtomicU32 = AtomicU32::new(0); // newest load; older decodes that finish late are dropped
@@ -134,7 +134,7 @@ unsafe fn paint(hwnd: HWND) {
} else {
SelectObject(mem, a.font as _);
SetBkMode(mem, TRANSPARENT as _);
- SetTextColor(mem, 0x91_98_a6);
+ SetTextColor(mem, 0x93_8e_8e);
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);
@@ -175,7 +175,7 @@ unsafe extern "system" fn proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) ->
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());
+ let f = CreateFontW(-(18 * dpi / 96), 0, 0, 0, 400, 0, 0, 0, 1, 0, 0, 5, 0, wide(winrust_common::style::sans_face()).as_ptr());
APP.with_borrow_mut(|a| (a.dpi, a.font) = (dpi, f as isize));
DragAcceptFiles(hwnd, 1);
0
diff --git a/plugins/rs-shell/src/main.rs b/plugins/rs-shell/src/main.rs
index d49fe81..f992361 100644
--- a/plugins/rs-shell/src/main.rs
+++ b/plugins/rs-shell/src/main.rs
@@ -207,7 +207,7 @@ fn replace_on() -> bool {
/// 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 script = r#"Get-CimInstance Win32_Process -Filter "Name='explorer.exe'" | Where-Object { $_.CommandLine -match '(?i)explorer\.exe"?(\s+/NoUACCheck)?\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())));
}
diff --git a/plugins/rtaskmgr-win32/src/draw.rs b/plugins/rtaskmgr-win32/src/draw.rs
index 4799748..638addf 100644
--- a/plugins/rtaskmgr-win32/src/draw.rs
+++ b/plugins/rtaskmgr-win32/src/draw.rs
@@ -9,7 +9,7 @@ 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)];
+ let c = [Rgb(10, 132, 255), Rgb(94, 92, 230), Rgb(48, 209, 88), Rgb(255, 159, 10), Rgb(191, 90, 242)][i.min(4)]; // Apple system blue, indigo, green, orange, purple
if dark { c } else { c.lerp(Rgb(0, 0, 0), 0.18) }
}
@@ -95,7 +95,7 @@ impl App {
}
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);
+ g.glyph(gr, *glyph, if enabled && *btn == Btn::Efficiency { Rgb(48, 209, 88) } 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);
}
diff --git a/plugins/rtaskmgr-win32/src/sys.rs b/plugins/rtaskmgr-win32/src/sys.rs
index d6f0b8c..4a1a0db 100644
--- a/plugins/rtaskmgr-win32/src/sys.rs
+++ b/plugins/rtaskmgr-win32/src/sys.rs
@@ -6,7 +6,7 @@ use winapi::um::{
processthreadsapi::{GetPriorityClass, OpenProcess, SetPriorityClass},
winbase::{
ABOVE_NORMAL_PRIORITY_CLASS, BELOW_NORMAL_PRIORITY_CLASS, GetProcessAffinityMask, HIGH_PRIORITY_CLASS,
- IDLE_PRIORITY_CLASS, NORMAL_PRIORITY_CLASS, SetProcessAffinityMask,
+ IDLE_PRIORITY_CLASS, NORMAL_PRIORITY_CLASS,
},
winnt::{HANDLE, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SET_INFORMATION, SERVICE_WIN32},
winsvc::*,
@@ -136,7 +136,7 @@ pub fn set_affinity(pid: u32, half: bool) -> bool {
}
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 ядер не поддержано
+ SetProcessAffinityMask64(h, mask) != 0
})
.unwrap_or(false)
}
@@ -156,6 +156,13 @@ fn first_n_bits(mask: usize, n: u32) -> usize {
out
}
+#[link(name = "kernel32")]
+unsafe extern "system" {
+ // winapi 0.3 declares the mask as a 32-bit DWORD; the real parameter is a pointer-sized DWORD_PTR
+ #[link_name = "SetProcessAffinityMask"]
+ fn SetProcessAffinityMask64(h: HANDLE, mask: usize) -> i32;
+}
+
#[link(name = "shell32")]
unsafe extern "system" {
fn IsUserAnAdmin() -> i32;
@@ -353,6 +360,7 @@ mod tests {
fn first_bits() {
assert_eq!(first_n_bits(0b1111_0000, 2), 0b0011_0000);
assert_eq!(first_n_bits(0b1111, 4), 0b1111);
+ assert_eq!(first_n_bits(usize::MAX, 40), (1usize << 40) - 1); // ядра за пределами 32-го бита
}
}
diff --git a/plugins/rtaskmgr-win32/src/ui.rs b/plugins/rtaskmgr-win32/src/ui.rs
index 17c48f5..ad27b27 100644
--- a/plugins/rtaskmgr-win32/src/ui.rs
+++ b/plugins/rtaskmgr-win32/src/ui.rs
@@ -39,36 +39,36 @@ 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),
+ bg: Rgb(22, 22, 24),
+ nav: Rgb(28, 28, 31),
+ panel: Rgb(36, 36, 40),
+ text: Rgb(245, 245, 247),
+ dim: Rgb(142, 142, 147),
+ border: Rgb(46, 46, 50),
+ sel: Rgb(44, 44, 49),
+ hover: Rgb(33, 33, 37),
+ accent: Rgb(10, 132, 255),
+ heat0: Rgb(16, 34, 60),
+ heat1: Rgb(20, 98, 196),
+ warn: Rgb(255, 214, 10),
+ bad: Rgb(255, 69, 58),
}
} else {
Theme {
dark,
- bg: Rgb(249, 249, 249),
- nav: Rgb(243, 243, 243),
+ bg: Rgb(251, 251, 253),
+ nav: Rgb(242, 242, 247),
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),
+ text: Rgb(29, 29, 31),
+ dim: Rgb(110, 110, 115),
+ border: Rgb(229, 229, 234),
+ sel: Rgb(229, 229, 234),
+ hover: Rgb(238, 238, 242),
+ accent: Rgb(0, 113, 227),
+ heat0: Rgb(232, 241, 253),
+ heat1: Rgb(102, 166, 240),
+ warn: Rgb(178, 110, 0),
+ bad: Rgb(215, 0, 21),
}
}
}
@@ -126,7 +126,7 @@ fn mk(face: &str, px: i32, weight: i32) -> HFONT {
/// Есть ли в системе шрифт значков Windows 11.
fn icon_face() -> &'static str {
// Segoe Fluent Icons есть в Windows 11; в Windows 10 — Segoe MDL2 Assets (те же коды символов)
- "Segoe Fluent Icons"
+ winrust_common::style::icon_face()
}
impl Fonts {
@@ -134,12 +134,12 @@ impl 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(winrust_common::style::sans_face(), p(13.0), 400),
+ mk(winrust_common::style::sans_face(), p(12.0), 400),
+ mk(winrust_common::style::sans_face(), p(13.0), 600),
+ mk(winrust_common::style::sans_face(), p(22.0), 600),
+ mk(winrust_common::style::sans_face(), p(20.0), 400),
+ mk(winrust_common::style::sans_face(), p(30.0), 300),
mk(icon_face(), p(16.0), 400),
mk(icon_face(), p(13.0), 400),
],
diff --git a/plugins/rust-explorer/app.ico b/plugins/rust-explorer/app.ico
new file mode 100644
index 0000000..4dd36a2
Binary files /dev/null and b/plugins/rust-explorer/app.ico differ
diff --git a/plugins/rust-explorer/app.rc b/plugins/rust-explorer/app.rc
index 8142754..49bf0c8 100644
--- a/plugins/rust-explorer/app.rc
+++ b/plugins/rust-explorer/app.rc
@@ -1 +1,2 @@
+1 ICON "app.ico"
1 24 "app.manifest"
diff --git a/plugins/rust-explorer/build.rs b/plugins/rust-explorer/build.rs
index b0af67a..1ccba4e 100644
--- a/plugins/rust-explorer/build.rs
+++ b/plugins/rust-explorer/build.rs
@@ -1,5 +1,6 @@
fn main() {
println!("cargo:rerun-if-changed=app.rc");
+ println!("cargo:rerun-if-changed=app.ico");
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.rs
index 87adb1a..da24e87 100644
--- a/plugins/rust-explorer/src/main.rs
+++ b/plugins/rust-explorer/src/main.rs
@@ -26,9 +26,21 @@ 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) }
+/// What the bar reserves at the top and bottom of the screen: the work area topbar sets when there is no explorer.
+fn work_strips() -> (i32, i32) {
+ let mut r: RECT = unsafe { std::mem::zeroed() };
+ if unsafe { SystemParametersInfoW(SPI_GETWORKAREA, 0, &mut r as *mut _ as *mut _, 0) } == 0 { return (0, 0); }
+ (r.top.max(0), (unsafe { GetSystemMetrics(SM_CYSCREEN) } - r.bottom).max(0))
+}
+/// Margins of the desktop's icon list, from the bar's real size: its reserved strip (any height, top or bottom).
+/// The dock style reserves nothing but floats over the bottom edge, so it gets a fixed gap while topbar runs.
+fn desk_top() -> i32 { work_strips().0 + ui::sc(8) }
+fn desk_bottom() -> i32 {
+ let reserved = work_strips().1;
+ if reserved > 0 { return reserved + ui::sc(4); }
+ let bar_up = unsafe { !FindWindowW(w("topbar").as_ptr(), ptr::null()).is_null() };
+ if bar_up && winrust_common::style::style() == winrust_common::style::Style::Dock { ui::sc(52) } else { ui::sc(8) }
+}
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
@@ -197,6 +209,15 @@ fn tab_text(tab: HWND, _i: usize, _text: &str, _insert: bool) {
if !tab.is_null() { unsafe { InvalidateRect(tab, ptr::null(), 0) }; }
}
+/// The text of a desktop row. Rows from the public desktop carry absolute paths: only the file name is shown, and shortcuts
+/// lose their ".lnk" / ".url" like in Explorer. Other windows show the row as it is.
+fn shown_name(name: &str, desktop: bool) -> String {
+ if !desktop { return name.to_string(); }
+ let file = std::path::Path::new(name).file_name().map_or_else(|| name.to_string(), |n| n.to_string_lossy().into_owned());
+ let lower = file.to_lowercase();
+ if lower.ends_with(".lnk") || lower.ends_with(".url") { file[..file.len() - 4].to_string() } else { file }
+}
+
fn label(dir: &PathBuf) -> String {
dir.file_name().map_or_else(|| dir.to_string_lossy().into_owned(), |n| n.to_string_lossy().into_owned())
}
@@ -984,6 +1005,17 @@ unsafe extern "system" fn proc(h: HWND, m: u32, wp: WPARAM, lp: LPARAM) -> LRESU
load(h, start);
0
}
+ // the bar came, went or changed size (it sets the work area), or the screen changed: the icon list follows
+ WM_SETTINGCHANGE | WM_DISPLAYCHANGE if desk() => {
+ if m == WM_DISPLAYCHANGE {
+ SetWindowPos(h, HWND_BOTTOM, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), SWP_NOACTIVATE); // WM_SIZE lays out
+ } else if wp == SPI_SETWORKAREA as usize {
+ let (list, mut r) = (ST.with_borrow(|st| st.list), std::mem::zeroed::<RECT>());
+ GetClientRect(h, &mut r);
+ MoveWindow(list, 0, desk_top(), r.right, (r.bottom - desk_top() - desk_bottom()).max(0), 1);
+ }
+ 0
+ }
WM_SIZE => {
let list = ST.with_borrow(|st| st.list);
let (cw, ch) = ((lp & 0xFFFF) as i32, ((lp >> 16) & 0xFFFF) as i32);
@@ -1037,7 +1069,7 @@ unsafe extern "system" fn proc(h: HWND, m: u32, wp: WPARAM, lp: LPARAM) -> LRESU
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 s = match it.iSubItem { 0 => shown_name(&r.name, desk()), 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;
@@ -1102,6 +1134,8 @@ unsafe extern "system" fn proc(h: HWND, m: u32, wp: WPARAM, lp: LPARAM) -> LRESU
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); }
+ // Space on a picture: a quick look in photoview (pictures only: videos and text are not previewed yet)
+ 0x20 if !desk() => if let (Some(p), Some(exe)) = (paths.first().filter(|p| is_pic(p)), tool("photoview")) { let _ = std::process::Command::new(exe).arg(p).spawn(); },
0x71 => {
let i = put(list, LVM_GETNEXTITEM, usize::MAX, LVNI_SELECTED as isize);
if i >= 0 { put(list, LVM_EDITLABELW, i as usize, 0); }
@@ -1242,6 +1276,14 @@ mod tests {
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 desktop_rows_show_file_names_without_shortcut_extensions() {
+ assert_eq!(shown_name(r"C:\Users\Public\Desktop\Steam.lnk", true), "Steam");
+ assert_eq!(shown_name("Notes.txt", true), "Notes.txt");
+ assert_eq!(shown_name(r"C:\x\Game.URL", true), "Game");
+ assert_eq!(shown_name(r"C:\x\Steam.lnk", false), r"C:\x\Steam.lnk");
+ }
+
#[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)];
diff --git a/plugins/rust-explorer/src/ui.rs b/plugins/rust-explorer/src/ui.rs
index 5f6a284..6ea2ac8 100644
--- a/plugins/rust-explorer/src/ui.rs
+++ b/plugins/rust-explorer/src/ui.rs
@@ -6,11 +6,11 @@ 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 }
// The colours come from the WinRust style the topbar gear picks (normal, terminal, dock, tiling): the same palette as the bar.
pub use winrust_common::style::{pal, ui_face};
-pub fn listbg() -> u32 { mix(pal().bg, 0, 0.22) }
-pub fn pill() -> u32 { mix(pal().bg, 0, 0.35) }
+// sunk surfaces: darker than the window on the dark styles, white on the light one
+pub fn listbg() -> u32 { if winrust_common::style::style().light() { winrust_common::style::card() } else { mix(pal().bg, 0, 0.22) } }
+pub fn pill() -> u32 { if winrust_common::style::style().light() { mix(pal().bg, pal().text, 0.06) } else { mix(pal().bg, 0, 0.35) } }
pub fn off() -> u32 { mix(pal().dim, pal().bg, 0.45) }
pub const CHROME_H: i32 = 88;
@@ -122,7 +122,7 @@ pub fn font(px: i32, weight: i32, face: &str) -> isize {
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(20, !winrust_common::style::style().light() as i32); // immersive dark mode, except on the light style
set(33, if winrust_common::style::style().square() { 1 } else { 2 }); // round corners, square in the terminal and tiling styles
set(35, pal().bg as i32); // caption
set(36, pal().text as i32); // caption text
@@ -221,7 +221,7 @@ pub unsafe fn list_draw(lp: LPARAM) -> LRESULT {
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, ui_face()) as HFONT);
+ let (f_big, f_txt) = (font(40, 400, winrust_common::style::icon_face()) as HFONT, font(14, 400, ui_face()) as HFONT);
SetBkMode(dc, TRANSPARENT as i32);
let mid = cr.bottom / 3;
let of = SelectObject(dc, f_big);
@@ -496,7 +496,7 @@ unsafe fn paint_chrome(hwnd: HWND) {
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, ui_face()) as HFONT, font(16, 400, "Segoe MDL2 Assets") as HFONT, font(12, 400, "Segoe MDL2 Assets") as HFONT);
+ let (f_txt, f_glyph, f_small) = (font(13, 400, ui_face()) as HFONT, font(16, 400, winrust_common::style::icon_face()) as HFONT, font(12, 400, winrust_common::style::icon_face()) as HFONT);
let of = SelectObject(dc, f_txt);
// tabs
@@ -741,7 +741,13 @@ pub fn nav_init(h: HWND) {
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 ty = GetDriveTypeW(w(&root).as_ptr());
+ if ty == 4 {
+ // a mapped network drive: listed without label and size, they would stall the window while a share is down
+ v.push(NavItem { title: format!("Network Drive ({letter}:)"), path: PathBuf::from(root), glyph: "\u{E8CE}", cap: None });
+ continue;
+ }
+ if !matches!(ty, 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() };
@@ -800,7 +806,7 @@ unsafe fn paint_nav(hwnd: HWND) {
FillRect(dc, &cr, bg);
DeleteObject(bg);
SetBkMode(dc, TRANSPARENT as i32);
- let (f_txt, f_head, f_glyph, f_small) = (font(13, 400, ui_face()) as HFONT, font(12, 600, ui_face()) as HFONT, font(16, 400, "Segoe MDL2 Assets") as HFONT, font(11, 400, ui_face()) as HFONT);
+ let (f_txt, f_head, f_glyph, f_small) = (font(13, 400, ui_face()) as HFONT, font(12, 600, ui_face()) as HFONT, font(16, 400, winrust_common::style::icon_face()) as HFONT, font(11, 400, ui_face()) 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();
@@ -832,7 +838,7 @@ unsafe fn paint_nav(hwnd: HWND) {
let bar = rc(r.left + sc(48), y + sc(30), r.right - sc(14), y + sc(34));
fill(dc, bar, mix(pal().bg, pal().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 { pal().accent }, sc(4));
+ fill(dc, rc(bar.left, bar.top, bar.left + fw.max(sc(4)), bar.bottom), if used > 0.9 { winrust_common::style::BAD } else { pal().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)), pal().dim, DT_LEFT);
diff --git a/plugins/rust-search/src/bin/rs-launcher.rs b/plugins/rust-search/src/bin/rs-launcher.rs
index d97e005..e65d184 100644
--- a/plugins/rust-search/src/bin/rs-launcher.rs
+++ b/plugins/rust-search/src/bin/rs-launcher.rs
@@ -380,7 +380,7 @@ unsafe fn apply_style(main: HWND) {
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 face = ui_face();
- let fonts = [font(22, 400, face), font(16, 600, face), font(13, 400, face), font(20, 400, "Segoe MDL2 Assets"), font(12, 400, face)];
+ let fonts = [font(22, 400, face), font(16, 600, face), font(13, 400, face), font(20, 400, winrust_common::style::icon_face()), font(12, 400, face)];
for f in st(|s| std::mem::replace(&mut s.fonts, fonts)) {
if f != 0 {
DeleteObject(f as _);
@@ -388,7 +388,7 @@ unsafe fn apply_style(main: HWND) {
}
// Windows 11: rounded corners (square in the terminal and tiling styles), dark frame, border colour. Windows 10 rejects the corner attribute.
let square = style().square();
- let (round, dark, border) = (if square { 1i32 } else { 2i32 }, 1i32, rgb(c_border()) as i32);
+ let (round, dark, border) = (if square { 1i32 } else { 2i32 }, !style().light() as i32, rgb(c_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);
diff --git a/plugins/rust-settings/Cargo.toml b/plugins/rust-settings/Cargo.toml
new file mode 100644
index 0000000..84a2f88
--- /dev/null
+++ b/plugins/rust-settings/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "rust-settings"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]
+winrust-common = { path = "../../common" }
+windows-sys = { version = "0.61.2", features = ["Win32_Devices_Display", "Win32_Foundation", "Win32_Graphics_Dwm", "Win32_Graphics_Gdi", "Win32_Graphics_GdiPlus", "Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_NetworkManagement_WiFi", "Win32_Networking_WinSock", "Win32_Storage_FileSystem", "Win32_System_LibraryLoader", "Win32_System_Power", "Win32_System_Registry", "Win32_System_Threading", "Win32_NetworkManagement_Rras", "Win32_Networking_WinInet", "Win32_Security_ExtensibleAuthenticationProtocol", "Win32_UI_Shell", "Win32_UI_ColorSystem", "Win32_System_Com", "Win32_System_SystemInformation", "Win32_UI_HiDpi", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] }
+# COM only for the volume (Core Audio), as photoview uses it for WIC
+windows = { version = "0.62", features = ["Win32_Foundation", "Devices_Radios", "Foundation_Collections", "Win32_Networking_NetworkListManager", "Win32_Media_Audio", "Win32_Media_Audio_Endpoints", "Win32_UI_Shell_PropertiesSystem", "Win32_Devices_FunctionDiscovery", "Win32_System_UpdateAgent", "Win32_System_Ole", "Devices_Bluetooth", "Devices_Enumeration", "Foundation", "Win32_System_Com", "Win32_System_Com_StructuredStorage", "Win32_System_Variant"] }
+
+windows-core = "0.62" # the `interface` macro of audio.rs refers to this crate by name
+
+[build-dependencies]
+embed-resource = "3"
diff --git a/plugins/rust-settings/app.ico b/plugins/rust-settings/app.ico
new file mode 100644
index 0000000..1f49e0f
Binary files /dev/null and b/plugins/rust-settings/app.ico differ
diff --git a/plugins/rust-settings/app.rc b/plugins/rust-settings/app.rc
new file mode 100644
index 0000000..0a9daf1
--- /dev/null
+++ b/plugins/rust-settings/app.rc
@@ -0,0 +1 @@
+1 ICON "app.ico"
diff --git a/plugins/rust-settings/build.rs b/plugins/rust-settings/build.rs
new file mode 100644
index 0000000..e8d32ea
--- /dev/null
+++ b/plugins/rust-settings/build.rs
@@ -0,0 +1,5 @@
+fn main() {
+ println!("cargo:rerun-if-changed=app.rc");
+ println!("cargo:rerun-if-changed=app.ico");
+ embed_resource::compile("app.rc", embed_resource::NONE).manifest_optional().unwrap();
+}
diff --git a/plugins/rust-settings/src/audio.rs b/plugins/rust-settings/src/audio.rs
new file mode 100644
index 0000000..39924f4
--- /dev/null
+++ b/plugins/rust-settings/src/audio.rs
@@ -0,0 +1,197 @@
+//! Sound (Core Audio): volume and mute of the default playback device or microphone, the list of devices with choosing the
+//! default one, and the volume of every app that plays sound. Every call asks for the default device again, so a device change
+//! in Windows is followed. All calls come from the UI thread, which initializes COM in `init`.
+#![allow(non_snake_case)] // the method names of the COM interface below
+use std::{ffi::c_void, ptr::null};
+use windows::{
+ Win32::{
+ Devices::FunctionDiscovery::PKEY_Device_FriendlyName,
+ Media::Audio::{
+ DEVICE_STATE_ACTIVE, EDataFlow, Endpoints::IAudioEndpointVolume, IAudioSessionControl2, IAudioSessionManager2, IMMDevice, IMMDeviceEnumerator, ISimpleAudioVolume,
+ MMDeviceEnumerator, eCapture, eCommunications, eConsole, eMultimedia, eRender,
+ },
+ System::Com::{CLSCTX_ALL, COINIT_APARTMENTTHREADED, CoCreateInstance, CoInitializeEx, STGM_READ},
+ },
+ core::{GUID, HRESULT, Interface, PCWSTR},
+};
+
+pub fn init() {
+ unsafe {
+ let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
+ }
+}
+
+/// What a volume slider controls.
+#[derive(Clone, Copy, PartialEq, Debug)]
+pub enum Src {
+ Out,
+ Mic,
+ /// One app's sessions on the default playback device (pid 0: system sounds).
+ App(u32),
+}
+
+fn enumerator() -> Option<IMMDeviceEnumerator> {
+ unsafe { CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).ok() }
+}
+
+fn default_device(mic: bool) -> Option<IMMDevice> {
+ unsafe { enumerator()?.GetDefaultAudioEndpoint(if mic { eCapture } else { eRender }, eConsole).ok() }
+}
+
+fn endpoint(mic: bool) -> Option<IAudioEndpointVolume> {
+ unsafe { default_device(mic)?.Activate::<IAudioEndpointVolume>(CLSCTX_ALL, None).ok() }
+}
+
+// ---- devices ----
+
+pub struct Dev {
+ pub id: String,
+ pub name: String,
+ pub default: bool,
+}
+
+fn dev_id(d: &IMMDevice) -> Option<String> {
+ unsafe { d.GetId().ok().and_then(|p| p.to_string().ok()) }
+}
+
+fn dev_name(d: &IMMDevice) -> String {
+ unsafe {
+ let name = d.OpenPropertyStore(STGM_READ).ok().and_then(|s| s.GetValue(&PKEY_Device_FriendlyName).ok()).map(|v| v.to_string()).filter(|s| !s.is_empty());
+ name.unwrap_or_else(|| dev_id(d).unwrap_or_default())
+ }
+}
+
+/// The active playback (or recording) devices; the one Windows uses by default is flagged.
+pub fn devices(mic: bool) -> Vec<Dev> {
+ let Some(e) = enumerator() else { return vec![] };
+ let flow: EDataFlow = if mic { eCapture } else { eRender };
+ let cur = unsafe { e.GetDefaultAudioEndpoint(flow, eConsole).ok() }.and_then(|d| dev_id(&d));
+ let Ok(col) = (unsafe { e.EnumAudioEndpoints(flow, DEVICE_STATE_ACTIVE) }) else { return vec![] };
+ (0..unsafe { col.GetCount() }.unwrap_or(0)).filter_map(|i| unsafe { col.Item(i).ok() }).filter_map(|d| dev_id(&d).map(|id| Dev { default: Some(&id) == cur.as_ref(), name: dev_name(&d), id })).collect()
+}
+
+/// The default device's name ("—" without one).
+pub fn default_name(mic: bool) -> String {
+ default_device(mic).map_or("—".into(), |d| dev_name(&d))
+}
+
+// The system's own switch of the default device. It has no documented API: this is the COM class Windows' sound panel and every
+// third-party switcher use (PolicyConfigClient); only the one method SetDefaultEndpoint is called, the rest are placeholders
+// that keep the vtable in place.
+#[windows::core::interface("f8679f50-850a-41cf-9c72-430f290290c8")]
+unsafe trait IPolicyConfig: windows::core::IUnknown {
+ fn GetMixFormat(&self, dev: PCWSTR, fmt: *mut *mut c_void) -> HRESULT;
+ fn GetDeviceFormat(&self, dev: PCWSTR, default: i32, fmt: *mut *mut c_void) -> HRESULT;
+ fn ResetDeviceFormat(&self, dev: PCWSTR) -> HRESULT;
+ fn SetDeviceFormat(&self, dev: PCWSTR, a: *mut c_void, b: *mut c_void) -> HRESULT;
+ fn GetProcessingPeriod(&self, dev: PCWSTR, default: i32, a: *mut i64, b: *mut i64) -> HRESULT;
+ fn SetProcessingPeriod(&self, dev: PCWSTR, a: *mut i64) -> HRESULT;
+ fn GetShareMode(&self, dev: PCWSTR, m: *mut c_void) -> HRESULT;
+ fn SetShareMode(&self, dev: PCWSTR, m: *mut c_void) -> HRESULT;
+ fn GetPropertyValue(&self, dev: PCWSTR, fx: i32, key: *const c_void, v: *mut c_void) -> HRESULT;
+ fn SetPropertyValue(&self, dev: PCWSTR, fx: i32, key: *const c_void, v: *mut c_void) -> HRESULT;
+ fn SetDefaultEndpoint(&self, dev: PCWSTR, role: i32) -> HRESULT;
+ fn SetEndpointVisibility(&self, dev: PCWSTR, visible: i32) -> HRESULT;
+}
+
+const POLICY_CONFIG_CLIENT: GUID = GUID::from_u128(0x870af99c_171d_4f9e_af0d_e63df40c2bc9);
+
+/// Makes `id` (from `devices`) the default for every role (apps, media, calls).
+pub fn set_default(id: &str) -> bool {
+ unsafe {
+ let Ok(pc) = CoCreateInstance::<_, IPolicyConfig>(&POLICY_CONFIG_CLIENT, None, CLSCTX_ALL) else { return false };
+ let w: Vec<u16> = id.encode_utf16().chain([0]).collect();
+ [eConsole, eMultimedia, eCommunications].iter().all(|r| pc.SetDefaultEndpoint(PCWSTR(w.as_ptr()), r.0).is_ok())
+ }
+}
+
+// ---- apps ----
+
+fn sessions() -> Vec<IAudioSessionControl2> {
+ unsafe {
+ let Some(m) = default_device(false).and_then(|d| d.Activate::<IAudioSessionManager2>(CLSCTX_ALL, None).ok()) else { return vec![] };
+ let Ok(list) = m.GetSessionEnumerator() else { return vec![] };
+ (0..list.GetCount().unwrap_or(0)).filter_map(|i| list.GetSession(i).ok()).filter_map(|s| s.cast::<IAudioSessionControl2>().ok()).collect()
+ }
+}
+
+/// "chrome.exe" -> "chrome": the name of a process from its image path.
+fn proc_name(pid: u32) -> Option<String> {
+ use windows_sys::Win32::{Foundation::CloseHandle, System::Threading::*};
+ unsafe {
+ let h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
+ if h.is_null() {
+ return None;
+ }
+ let mut buf = [0u16; 520];
+ let mut n = buf.len() as u32;
+ let ok = QueryFullProcessImageNameW(h, 0, buf.as_mut_ptr(), &mut n) != 0;
+ CloseHandle(h);
+ let path = String::from_utf16_lossy(&buf[..n as usize]);
+ ok.then(|| path.rsplit('\\').next().unwrap_or(&path).trim_end_matches(".exe").to_string())
+ }
+}
+
+/// The apps with an audio session on the default playback device: (pid, name), one entry per process, by name.
+pub fn apps() -> Vec<(u32, String)> {
+ let mut out: Vec<(u32, String)> = vec![];
+ for s in sessions() {
+ let pid = unsafe { s.GetProcessId() }.unwrap_or(0);
+ let system = unsafe { s.IsSystemSoundsSession() }.0 == 0; // S_OK: it is the system sounds session
+ let pid = if system { 0 } else { pid };
+ if out.iter().any(|o| o.0 == pid) {
+ continue;
+ }
+ let name = if pid == 0 { t!("Системные звуки", "System sounds").to_string() } else { proc_name(pid).unwrap_or_else(|| format!("PID {pid}")) };
+ out.push((pid, name));
+ }
+ out.sort_by_key(|a| a.1.to_lowercase());
+ out
+}
+
+fn app_volumes(pid: u32) -> Vec<ISimpleAudioVolume> {
+ sessions()
+ .into_iter()
+ .filter(|s| {
+ let sys = unsafe { s.IsSystemSoundsSession() }.0 == 0;
+ if pid == 0 { sys } else { !sys && unsafe { s.GetProcessId() }.ok() == Some(pid) }
+ })
+ .filter_map(|s| s.cast::<ISimpleAudioVolume>().ok())
+ .collect()
+}
+
+// ---- volume and mute ----
+
+/// 0.0..=1.0; None when there is no such device (or app).
+pub fn volume(src: Src) -> Option<f32> {
+ unsafe {
+ match src {
+ Src::Out | Src::Mic => endpoint(src == Src::Mic)?.GetMasterVolumeLevelScalar().ok(),
+ Src::App(pid) => app_volumes(pid).first()?.GetMasterVolume().ok(),
+ }
+ }
+}
+
+pub fn set_volume(src: Src, v: f32) {
+ let v = v.clamp(0.0, 1.0);
+ unsafe {
+ match src {
+ Src::Out | Src::Mic => {
+ if let Some(e) = endpoint(src == Src::Mic) {
+ let _ = e.SetMasterVolumeLevelScalar(v, null());
+ }
+ }
+ Src::App(pid) => app_volumes(pid).iter().for_each(|a| drop(a.SetMasterVolume(v, null()))),
+ }
+ }
+}
+
+pub fn muted(mic: bool) -> Option<bool> {
+ unsafe { Some(endpoint(mic)?.GetMute().ok()?.as_bool()) }
+}
+
+pub fn set_mute(mic: bool, m: bool) {
+ if let Some(e) = endpoint(mic) {
+ let _ = unsafe { e.SetMute(m, null()) };
+ }
+}
diff --git a/plugins/rust-settings/src/bt.rs b/plugins/rust-settings/src/bt.rs
new file mode 100644
index 0000000..3178827
--- /dev/null
+++ b/plugins/rust-settings/src/bt.rs
@@ -0,0 +1,181 @@
+//! Bluetooth and airplane mode through Windows.Devices.Radios / Devices.Enumeration (no admin, no Settings app): the radio switch,
+//! paired devices with their connection state, pairing a nearby device and removing a paired one. The WinRT calls wait, so they
+//! run in a thread and leave their result in `STATE`, which the window reads on its next refresh.
+use std::sync::{
+ Mutex,
+ atomic::{AtomicBool, Ordering::Relaxed},
+};
+use windows::{
+ Devices::{
+ Bluetooth::BluetoothDevice,
+ Enumeration::{DeviceInformation, DevicePairingKinds, DevicePairingResultStatus, DeviceUnpairingResultStatus},
+ Radios::{Radio, RadioKind, RadioState},
+ },
+ Foundation::TypedEventHandler,
+ core::HSTRING,
+};
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Dev {
+ pub id: String,
+ pub name: String,
+ pub connected: bool,
+}
+
+#[derive(Default, Clone)]
+pub struct State {
+ pub bt: Option<bool>, // a Bluetooth radio: on or off; None without one
+ pub air: Option<bool>, // every radio is off
+ pub paired: Vec<Dev>,
+ pub nearby: Vec<Dev>,
+ pub scanning: bool,
+ pub note: String, // the outcome of the last pairing / removal
+}
+
+static STATE: Mutex<State> = Mutex::new(State { bt: None, air: None, paired: vec![], nearby: vec![], scanning: false, note: String::new() });
+static BUSY: AtomicBool = AtomicBool::new(false);
+
+pub fn state() -> State {
+ STATE.lock().map(|s| s.clone()).unwrap_or_default()
+}
+
+fn with<T>(f: impl FnOnce(&mut State) -> T) -> Option<T> {
+ STATE.lock().ok().map(|mut s| f(&mut s))
+}
+
+fn radios() -> Vec<Radio> {
+ let _ = Radio::RequestAccessAsync().and_then(|a| a.join());
+ Radio::GetRadiosAsync().and_then(|a| a.join()).map(|v| v.into_iter().collect()).unwrap_or_default()
+}
+
+/// Radio and device lists, read again in a thread (one at a time); `done` runs afterwards (to repaint).
+pub fn refresh(done: impl FnOnce() + Send + 'static) {
+ if BUSY.swap(true, Relaxed) {
+ return;
+ }
+ std::thread::spawn(move || {
+ let rs = radios();
+ let bt: Vec<_> = rs.iter().filter(|r| r.Kind().is_ok_and(|k| k == RadioKind::Bluetooth)).collect();
+ let bt_on = (!bt.is_empty()).then(|| bt.iter().any(|r| r.State().is_ok_and(|s| s == RadioState::On)));
+ let air = (!rs.is_empty()).then(|| rs.iter().all(|r| r.State().is_ok_and(|s| s != RadioState::On)));
+ let paired = if bt_on == Some(true) { list(true) } else { vec![] };
+ with(|s| (s.bt, s.air, s.paired) = (bt_on, air, paired));
+ BUSY.store(false, Relaxed);
+ done();
+ });
+}
+
+fn list(paired: bool) -> Vec<Dev> {
+ let Ok(sel) = BluetoothDevice::GetDeviceSelectorFromPairingState(paired) else { return vec![] };
+ let Ok(all) = DeviceInformation::FindAllAsyncAqsFilter(&sel).and_then(|a| a.join()) else { return vec![] };
+ let mut out: Vec<Dev> = all
+ .into_iter()
+ .filter_map(|d| {
+ let (id, name) = (d.Id().ok()?.to_string(), d.Name().ok()?.to_string());
+ let connected = paired && BluetoothDevice::FromIdAsync(&HSTRING::from(&id)).and_then(|a| a.join()).and_then(|b| b.ConnectionStatus()).is_ok_and(|c| c.0 == 1);
+ (!name.trim().is_empty()).then_some(Dev { id, name, connected })
+ })
+ .collect();
+ out.sort_by(|a, b| b.connected.cmp(&a.connected).then(a.name.to_lowercase().cmp(&b.name.to_lowercase())));
+ out
+}
+
+/// Switches every radio of that kind (`None`: all radios, which is airplane mode) and re-reads the state.
+pub fn set(kind: Option<RadioKind>, on: bool, done: impl FnOnce() + Send + 'static) {
+ std::thread::spawn(move || {
+ for r in radios().into_iter().filter(|r| kind.is_none_or(|k| r.Kind().is_ok_and(|rk| rk == k))) {
+ let _ = r.SetStateAsync(if on { RadioState::On } else { RadioState::Off }).and_then(|a| a.join());
+ }
+ BUSY.store(false, Relaxed);
+ refresh(done);
+ });
+}
+
+pub fn set_bluetooth(on: bool, done: impl FnOnce() + Send + 'static) {
+ set(Some(RadioKind::Bluetooth), on, done);
+}
+
+pub fn set_airplane(on: bool, done: impl FnOnce() + Send + 'static) {
+ // airplane mode: everything off; back from it: Wi-Fi and Bluetooth on (the radios that have a switch of their own)
+ std::thread::spawn(move || {
+ for r in radios() {
+ let kind = r.Kind().ok();
+ if on || matches!(kind, Some(RadioKind::WiFi | RadioKind::Bluetooth)) {
+ let _ = r.SetStateAsync(if on { RadioState::Off } else { RadioState::On }).and_then(|a| a.join());
+ }
+ }
+ BUSY.store(false, Relaxed);
+ refresh(done);
+ });
+}
+
+/// Looks for devices in range (it takes about ten seconds).
+pub fn scan(done: impl FnOnce() + Send + 'static) {
+ if with(|s| std::mem::replace(&mut s.scanning, true)) != Some(false) {
+ return;
+ }
+ std::thread::spawn(move || {
+ let found = list(false);
+ with(|s| (s.nearby, s.scanning) = (found, false));
+ done();
+ });
+}
+
+fn pairing_text(code: i32) -> String {
+ match DevicePairingResultStatus(code) {
+ DevicePairingResultStatus::Paired => t!("Устройство подключено", "Device paired").into(),
+ DevicePairingResultStatus::AlreadyPaired => t!("Уже сопряжено", "Already paired").into(),
+ DevicePairingResultStatus::AuthenticationFailure | DevicePairingResultStatus::AuthenticationNotAllowed => t!("Сопряжение отклонено устройством", "The device refused to pair").into(),
+ DevicePairingResultStatus::RequiredHandlerNotRegistered | DevicePairingResultStatus::RejectedByHandler => t!("Для этого устройства нужен ввод PIN: сопрягите его в параметрах Windows", "This device needs a PIN: pair it in Windows' own settings").into(),
+ _ => tf!("Не удалось сопрячь (код {})", "Could not pair (code {})", code),
+ }
+}
+
+/// Pairs a device from `nearby`: confirmation and a displayed PIN are accepted here (the PIN is shown in the note so it can be
+/// compared with the device); a device that wants a PIN typed in is reported.
+pub fn pair(id: String, done: impl FnOnce() + Send + 'static) {
+ std::thread::spawn(move || {
+ let msg = (|| -> windows::core::Result<String> {
+ let info = DeviceInformation::CreateFromIdAsync(&HSTRING::from(&id))?.join()?;
+ let custom = info.Pairing()?.Custom()?;
+ custom.PairingRequested(&TypedEventHandler::new(|_, args: windows::core::Ref<windows::Devices::Enumeration::DevicePairingRequestedEventArgs>| {
+ if let Some(a) = args.as_ref() {
+ if a.PairingKind().is_ok_and(|k| k == DevicePairingKinds::ConfirmPinMatch || k == DevicePairingKinds::DisplayPin) {
+ let pin = a.Pin().map(|p| p.to_string()).unwrap_or_default();
+ with(|s| s.note = tf!("PIN: {} (сравните с устройством)", "PIN: {} (compare with the device)", pin));
+ }
+ a.Accept()?;
+ }
+ Ok(())
+ }))?;
+ let kinds = DevicePairingKinds::ConfirmOnly | DevicePairingKinds::DisplayPin | DevicePairingKinds::ConfirmPinMatch;
+ let r = custom.PairAsync(kinds)?.join()?;
+ Ok(pairing_text(r.Status()?.0))
+ })()
+ .unwrap_or_else(|e| tf!("Не удалось сопрячь: {}", "Could not pair: {}", e.message()));
+ with(|s| s.note = msg);
+ BUSY.store(false, Relaxed);
+ refresh(|| {});
+ done();
+ });
+}
+
+/// Removes a paired device.
+pub fn unpair(id: String, done: impl FnOnce() + Send + 'static) {
+ std::thread::spawn(move || {
+ let msg = (|| -> windows::core::Result<String> {
+ let info = DeviceInformation::CreateFromIdAsync(&HSTRING::from(&id))?.join()?;
+ let r = info.Pairing()?.UnpairAsync()?.join()?;
+ Ok(if r.Status()? == DeviceUnpairingResultStatus::Unpaired { t!("Устройство удалено", "Device removed").into() } else { tf!("Не удалось удалить (код {})", "Could not remove (code {})", r.Status()?.0) })
+ })()
+ .unwrap_or_else(|e| tf!("Не удалось удалить: {}", "Could not remove: {}", e.message()));
+ with(|s| s.note = msg);
+ BUSY.store(false, Relaxed);
+ refresh(|| {});
+ done();
+ });
+}
+
+pub fn take_note() -> Option<String> {
+ with(|s| std::mem::take(&mut s.note)).filter(|n| !n.is_empty())
+}
diff --git a/plugins/rust-settings/src/display.rs b/plugins/rust-settings/src/display.rs
new file mode 100644
index 0000000..aeb67fb
--- /dev/null
+++ b/plugins/rust-settings/src/display.rs
@@ -0,0 +1,588 @@
+//! Displays: resolution, refresh rate, orientation through ChangeDisplaySettingsExW, scale and HDR through DisplayConfig, and the
+//! multi-display parts (which display the rows act on, extend/duplicate/one screen only, which display is the main one).
+//! A change is applied as a temporary mode first (CDS_FULLSCREEN: not saved, undone when the process ends); the caller keeps it
+//! with `apply(.., true)` after the user confirms, or goes back with `revert()` (which also undoes a screen-mode change).
+use std::{
+ cell::Cell,
+ ptr::{null, null_mut},
+};
+use windows_sys::Win32::Graphics::Gdi::*;
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub struct Mode {
+ pub w: u32,
+ pub h: u32,
+ pub hz: u32,
+}
+
+thread_local! {
+ static SEL: Cell<usize> = const { Cell::new(0) }; // which attached display the rows act on
+ static PREV_TOPO: Cell<Option<i32>> = const { Cell::new(None) }; // the screen mode before a change that is not confirmed yet
+}
+
+type Name = [u16; 32];
+
+/// Every display attached to the desktop: its GDI name and whether it is the main one.
+fn attached() -> Vec<(Name, bool)> {
+ let mut out = vec![];
+ for i in 0.. {
+ let mut dd: DISPLAY_DEVICEW = unsafe { std::mem::zeroed() };
+ dd.cb = size_of::<DISPLAY_DEVICEW>() as u32;
+ if unsafe { EnumDisplayDevicesW(null(), i, &mut dd, 0) } == 0 {
+ break;
+ }
+ if dd.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP != 0 {
+ out.push((dd.DeviceName, dd.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE != 0));
+ }
+ }
+ out
+}
+
+/// The selected display (the first one when the selection points past the last, e.g. after unplugging).
+fn selected() -> Option<(Name, bool)> {
+ let a = attached();
+ let n = a.len();
+ a.into_iter().nth(SEL.get() % n.max(1))
+}
+
+/// Name for the Win32 calls: None (= the main display) for the main one, so a single-display PC behaves exactly as before.
+fn dev() -> Option<Name> {
+ selected().filter(|s| !s.1).map(|s| s.0)
+}
+
+fn dev_ptr(n: &Option<Name>) -> *const u16 {
+ n.as_ref().map_or(null(), |n| n.as_ptr())
+}
+
+fn name_text(n: &[u16]) -> String {
+ String::from_utf16_lossy(n).trim_end_matches('\0').to_string()
+}
+
+/// (number of the selected display, how many there are, its name, is it the main one)
+pub fn monitor_info() -> Option<(usize, usize, String, bool)> {
+ let total = attached().len();
+ let (name, primary) = selected()?;
+ let label = selected_path().and_then(|p| friendly_name(&p)).unwrap_or_default();
+ // no EDID name (a laptop's own panel often has none): a plain name instead of "\\.\DISPLAY1"
+ let fallback = || if primary && total == 1 { winrust_common::t!("Встроенный экран", "Built-in display").to_string() } else { winrust_common::tf!("Дисплей {}", "Display {}", name_text(&name).trim_start_matches(r"\\.\DISPLAY")) };
+ Some((SEL.get() % total.max(1) + 1, total, if label.is_empty() { fallback() } else { label }, primary))
+}
+
+/// "1 · DELL U2720Q" for each attached display, for a picker.
+pub fn monitor_names() -> Vec<String> {
+ let keep = SEL.get();
+ let v = (0..attached().len()).map(|i| {
+ SEL.set(i);
+ monitor_info().map_or(format!("{}", i + 1), |m| format!("{} · {}", i + 1, m.2))
+ }).collect();
+ SEL.set(keep);
+ v
+}
+
+/// Index of the display the rows act on.
+pub fn selected_index() -> usize {
+ SEL.get() % attached().len().max(1)
+}
+
+pub fn select_monitor(i: usize) {
+ SEL.set(i);
+}
+
+fn blank() -> DEVMODEW {
+ let mut d: DEVMODEW = unsafe { std::mem::zeroed() };
+ d.dmSize = size_of::<DEVMODEW>() as u16;
+ d
+}
+
+fn mode_of(d: &DEVMODEW) -> Mode {
+ Mode { w: d.dmPelsWidth, h: d.dmPelsHeight, hz: d.dmDisplayFrequency }
+}
+
+/// The selected display's current settings, with its position.
+fn current_dm() -> Option<DEVMODEW> {
+ let mut d = blank();
+ (unsafe { EnumDisplaySettingsW(dev_ptr(&dev()), ENUM_CURRENT_SETTINGS, &mut d) } != 0).then_some(d)
+}
+
+pub fn current() -> Option<Mode> {
+ current_dm().map(|d| mode_of(&d))
+}
+
+/// Every 32-bit mode the display reports, once each.
+pub fn modes() -> Vec<Mode> {
+ let (mut out, name) = (vec![], dev());
+ for i in 0.. {
+ let mut d = blank();
+ if unsafe { EnumDisplaySettingsW(dev_ptr(&name), i, &mut d) } == 0 {
+ break;
+ }
+ let m = mode_of(&d);
+ if d.dmBitsPerPel == 32 && m.hz > 1 && !out.contains(&m) {
+ out.push(m);
+ }
+ }
+ out
+}
+
+/// The wanted rate when the resolution has it, else its highest.
+fn pick_hz(avail: &[u32], want: u32) -> u32 {
+ if avail.contains(&want) { want } else { avail.iter().copied().max().unwrap_or(want) }
+}
+
+fn rates(modes: &[Mode], w: u32, h: u32) -> Vec<u32> {
+ let mut v: Vec<u32> = modes.iter().filter(|m| (m.w, m.h) == (w, h)).map(|m| m.hz).collect();
+ v.sort_unstable();
+ v
+}
+
+/// Every resolution the display has, largest first.
+pub fn resolutions(modes: &[Mode]) -> Vec<(u32, u32)> {
+ let mut res: Vec<(u32, u32)> = modes.iter().map(|m| (m.w, m.h)).collect();
+ res.sort_unstable_by_key(|&(w, h)| std::cmp::Reverse((w as u64 * h as u64, w)));
+ res.dedup();
+ res
+}
+
+/// The mode for resolution `w` x `h`, keeping the current refresh rate when it exists there (else its highest).
+pub fn with_res(modes: &[Mode], cur: Mode, w: u32, h: u32) -> Mode {
+ Mode { w, h, hz: pick_hz(&rates(modes, w, h), cur.hz) }
+}
+
+/// The refresh rates of the current resolution, lowest first.
+pub fn rates_at(modes: &[Mode], cur: Mode) -> Vec<u32> {
+ rates(modes, cur.w, cur.h)
+}
+
+/// 0 = landscape, 1 = portrait (90), 2 = landscape flipped, 3 = portrait flipped.
+pub fn orientation() -> Option<u32> {
+ current_dm().map(|d| unsafe { d.Anonymous1.Anonymous2.dmDisplayOrientation })
+}
+
+/// Turns the display to orientation `o` (0..3, see `orientation`); `save` as in `apply`.
+pub fn set_orientation(o: u32, save: bool) -> bool {
+ let Some(mut d) = current_dm() else { return false };
+ if (unsafe { d.Anonymous1.Anonymous2.dmDisplayOrientation } ^ o) & 1 == 1 {
+ (d.dmPelsWidth, d.dmPelsHeight) = (d.dmPelsHeight, d.dmPelsWidth); // landscape <-> portrait swaps width and height
+ }
+ d.Anonymous1.Anonymous2.dmDisplayOrientation = o % 4;
+ d.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYORIENTATION | DM_POSITION;
+ change(&d, save)
+}
+
+/// The test run refuses a mode the driver cannot set before anything on the screen changes.
+fn change(d: &DEVMODEW, save: bool) -> bool {
+ let name = dev_ptr(&dev());
+ unsafe {
+ ChangeDisplaySettingsExW(name, d, null_mut(), CDS_TEST, null()) == DISP_CHANGE_SUCCESSFUL
+ && ChangeDisplaySettingsExW(name, d, null_mut(), if save { CDS_UPDATEREGISTRY } else { CDS_FULLSCREEN }, null()) == DISP_CHANGE_SUCCESSFUL
+ }
+}
+
+/// `save` = false: temporary; true: written to the registry (keeps after a restart; also confirms a screen-mode change).
+/// The orientation and the position stay as they are now.
+pub fn apply(m: Mode, save: bool) -> bool {
+ if save {
+ PREV_TOPO.set(None);
+ }
+ let Some(mut d) = current_dm() else { return false };
+ (d.dmPelsWidth, d.dmPelsHeight, d.dmDisplayFrequency, d.dmFields) = (m.w, m.h, m.hz, DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY | DM_DISPLAYORIENTATION | DM_POSITION);
+ change(&d, save)
+}
+
+/// Back to the saved mode (and the screen mode from before an unconfirmed change).
+pub fn revert() {
+ unsafe { ChangeDisplaySettingsExW(null(), null(), null_mut(), 0, null()) };
+ if let Some(t) = PREV_TOPO.take() {
+ set_topology(t);
+ }
+}
+
+/// Makes the selected display the main one: the others move so that it sits at (0, 0), as Windows' own Settings does.
+pub fn make_primary() -> bool {
+ let Some((name, primary)) = selected() else { return false };
+ if primary {
+ return false;
+ }
+ let get = |n: &Name| {
+ let mut d = blank();
+ (unsafe { EnumDisplaySettingsW(n.as_ptr(), ENUM_CURRENT_SETTINGS, &mut d) } != 0).then_some(d)
+ };
+ let Some(me) = get(&name) else { return false };
+ let (ox, oy) = unsafe { (me.Anonymous1.Anonymous2.dmPosition.x, me.Anonymous1.Anonymous2.dmPosition.y) };
+ // moves that Windows refuses are found out first: queued (CDS_NORESET) changes cannot be taken back
+ let mut moves = vec![];
+ for (n, _) in attached() {
+ let Some(mut d) = get(&n) else { return false };
+ unsafe {
+ d.Anonymous1.Anonymous2.dmPosition.x -= ox;
+ d.Anonymous1.Anonymous2.dmPosition.y -= oy;
+ }
+ d.dmFields = DM_POSITION;
+ let flags = CDS_UPDATEREGISTRY | CDS_NORESET | if n == name { CDS_SET_PRIMARY } else { 0 };
+ if unsafe { ChangeDisplaySettingsExW(n.as_ptr(), &d, null_mut(), CDS_TEST, null()) } != DISP_CHANGE_SUCCESSFUL {
+ return false;
+ }
+ moves.push((n, d, flags));
+ }
+ for (n, d, flags) in &moves {
+ unsafe { ChangeDisplaySettingsExW(n.as_ptr(), d, null_mut(), *flags, null()) };
+ }
+ unsafe { ChangeDisplaySettingsExW(null(), null(), null_mut(), 0, null()) == DISP_CHANGE_SUCCESSFUL }
+}
+
+// ---- scale and HDR of the selected display (DisplayConfig) ----
+// HDR ("advanced color") is documented (Windows 10 1709+). The scale is not: types -3 / -4 of DisplayConfig(Get|Set)DeviceInfo are
+// what Windows' own Settings app uses (stable since Windows 10 1607); the values are steps relative to the recommended scale.
+use windows_sys::Win32::Devices::Display::*;
+
+const SCALES: [u32; 12] = [100, 125, 150, 175, 200, 225, 250, 300, 350, 400, 450, 500];
+
+fn header(ty: i32, size: usize, p: &DISPLAYCONFIG_PATH_INFO, target: bool) -> DISPLAYCONFIG_DEVICE_INFO_HEADER {
+ let (adapter, id) = if target { (p.targetInfo.adapterId, p.targetInfo.id) } else { (p.sourceInfo.adapterId, p.sourceInfo.id) };
+ DISPLAYCONFIG_DEVICE_INFO_HEADER { r#type: ty, size: size as u32, adapterId: adapter, id }
+}
+
+/// The active DisplayConfig paths.
+fn active_paths() -> Vec<DISPLAYCONFIG_PATH_INFO> {
+ paths_of(QDC_ONLY_ACTIVE_PATHS).map_or(vec![], |p| p.0)
+}
+
+/// The paths for `flags` and, for QDC_DATABASE_CURRENT, the current screen mode.
+fn paths_of(flags: u32) -> Option<(Vec<DISPLAYCONFIG_PATH_INFO>, i32)> {
+ unsafe {
+ let (mut np, mut nm) = (0u32, 0u32);
+ if GetDisplayConfigBufferSizes(flags, &mut np, &mut nm) != 0 {
+ return None;
+ }
+ let mut paths = vec![std::mem::zeroed::<DISPLAYCONFIG_PATH_INFO>(); np as usize];
+ let mut modes = vec![std::mem::zeroed::<DISPLAYCONFIG_MODE_INFO>(); nm as usize];
+ let mut topo: DISPLAYCONFIG_TOPOLOGY_ID = 0;
+ let topo_ptr = if flags == QDC_DATABASE_CURRENT { &mut topo as *mut _ } else { null_mut() };
+ if QueryDisplayConfig(flags, &mut np, paths.as_mut_ptr(), &mut nm, modes.as_mut_ptr(), topo_ptr) != 0 {
+ return None;
+ }
+ paths.truncate(np as usize);
+ Some((paths, topo))
+ }
+}
+
+/// The active path whose source is the selected display.
+fn selected_path() -> Option<DISPLAYCONFIG_PATH_INFO> {
+ let want = selected()?.0;
+ active_paths().into_iter().find(|p| unsafe {
+ let mut n: DISPLAYCONFIG_SOURCE_DEVICE_NAME = std::mem::zeroed();
+ n.header = header(DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, size_of::<DISPLAYCONFIG_SOURCE_DEVICE_NAME>(), p, false);
+ DisplayConfigGetDeviceInfo(&mut n.header) == 0 && n.viewGdiDeviceName == want
+ })
+}
+
+#[repr(C)]
+struct TargetName {
+ h: DISPLAYCONFIG_DEVICE_INFO_HEADER,
+ flags: u32,
+ technology: i32,
+ manufacturer: u16,
+ product: u16,
+ connector: u32,
+ friendly: [u16; 64],
+ path: [u16; 128],
+}
+
+/// The monitor's own name from its EDID ("DELL U2720Q"), if it has one.
+fn friendly_name(p: &DISPLAYCONFIG_PATH_INFO) -> Option<String> {
+ let mut t: TargetName = unsafe { std::mem::zeroed() };
+ t.h = header(DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME, size_of::<TargetName>(), p, true);
+ (unsafe { DisplayConfigGetDeviceInfo(&mut t.h) } == 0).then(|| name_text(&t.friendly)).filter(|s| !s.is_empty())
+}
+
+/// How the displays work together: the four modes of Win+P.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Topo {
+ Extend,
+ Duplicate,
+ PcOnly,
+ SecondOnly,
+}
+
+impl Topo {
+ pub const ALL: [Topo; 4] = [Topo::Extend, Topo::Duplicate, Topo::PcOnly, Topo::SecondOnly];
+ /// DISPLAYCONFIG_TOPOLOGY_* (also the SDC_TOPOLOGY_* flag value).
+ fn id(self) -> i32 {
+ match self {
+ Topo::PcOnly => 1,
+ Topo::Duplicate => 2,
+ Topo::Extend => 4,
+ Topo::SecondOnly => 8,
+ }
+ }
+ fn of(id: i32) -> Option<Topo> {
+ Topo::ALL.into_iter().find(|t| t.id() == id)
+ }
+}
+
+pub fn topology() -> Option<Topo> {
+ Topo::of(paths_of(QDC_DATABASE_CURRENT)?.1)
+}
+
+/// How many screens are plugged in and usable, whether or not they are switched on now.
+pub fn connected() -> usize {
+ let Some((paths, _)) = paths_of(QDC_ALL_PATHS) else { return 0 };
+ let mut ids: Vec<(u32, i32, u32)> = paths.iter().filter(|p| p.targetInfo.targetAvailable != 0).map(|p| (p.targetInfo.adapterId.LowPart, p.targetInfo.adapterId.HighPart, p.targetInfo.id)).collect();
+ ids.sort_unstable();
+ ids.dedup();
+ ids.len()
+}
+
+fn set_topology(id: i32) -> bool {
+ unsafe { SetDisplayConfig(0, null(), 0, null(), SDC_APPLY | id as u32) == 0 }
+}
+
+/// Switches to screen mode `t`. The old mode is kept so that `revert()` can go back: the caller asks the user to confirm,
+/// as with a resolution.
+pub fn set_topology_to(t: Topo) -> bool {
+ let (Some(cur), true) = (topology(), connected() > 1) else { return false };
+ if cur == t {
+ return false;
+ }
+ let ok = set_topology(t.id());
+ if ok {
+ PREV_TOPO.set(Some(cur.id()));
+ }
+ ok
+}
+
+#[repr(C)]
+struct DpiGet {
+ h: DISPLAYCONFIG_DEVICE_INFO_HEADER,
+ min: i32,
+ cur: i32,
+ max: i32,
+}
+
+#[repr(C)]
+struct DpiSet {
+ h: DISPLAYCONFIG_DEVICE_INFO_HEADER,
+ rel: i32,
+}
+
+/// (minimum, current, maximum) step relative to the recommended scale.
+fn dpi_steps(p: &DISPLAYCONFIG_PATH_INFO) -> Option<(i32, i32, i32)> {
+ let mut g = DpiGet { h: header(-3, size_of::<DpiGet>(), p, false), min: 0, cur: 0, max: 0 };
+ (unsafe { DisplayConfigGetDeviceInfo(&mut g.h) } == 0).then_some((g.min, g.cur, g.max))
+}
+
+/// The scale in percent for a step `rel` when the smallest step is `min` (the recommended one is step 0).
+fn percent(min: i32, rel: i32) -> Option<u32> {
+ SCALES.get(usize::try_from(rel - min).ok()?).copied()
+}
+
+
+/// Scale of the selected display in percent.
+pub fn scale() -> Option<u32> {
+ let (min, cur, _) = dpi_steps(&selected_path()?)?;
+ percent(min, cur)
+}
+
+/// The scales the selected display offers in percent, and the index of the current one.
+pub fn scales() -> Option<(Vec<u32>, usize)> {
+ let (min, cur, max) = dpi_steps(&selected_path()?)?;
+ Some(((min..=max).filter_map(|r| percent(min, r)).collect(), (cur - min).max(0) as usize))
+}
+
+/// Sets the scale to entry `i` of `scales()`. Windows applies it to open windows by itself.
+pub fn set_scale_index(i: usize) -> bool {
+ let Some(p) = selected_path() else { return false };
+ let Some((min, _, max)) = dpi_steps(&p) else { return false };
+ let mut s = DpiSet { h: header(-4, size_of::<DpiSet>(), &p, false), rel: (min + i as i32).min(max) };
+ unsafe { DisplayConfigSetDeviceInfo(&mut s.h) == 0 }
+}
+
+#[repr(C)]
+struct ColorGet {
+ h: DISPLAYCONFIG_DEVICE_INFO_HEADER,
+ value: u32, // bit 0 supported, bit 1 enabled, bit 2 wide colour enforced, bit 3 force disabled
+ encoding: i32,
+ bits: u32,
+}
+
+#[repr(C)]
+struct ColorSet {
+ h: DISPLAYCONFIG_DEVICE_INFO_HEADER,
+ enable: u32,
+}
+
+/// HDR of the selected display: None = it cannot do HDR (or advanced color is forced off), else on or off.
+pub fn hdr() -> Option<bool> {
+ let p = selected_path()?;
+ let mut g = ColorGet { h: header(DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO, size_of::<ColorGet>(), &p, true), value: 0, encoding: 0, bits: 0 };
+ if unsafe { DisplayConfigGetDeviceInfo(&mut g.h) } != 0 {
+ return None;
+ }
+ hdr_state(g.value)
+}
+
+fn hdr_state(value: u32) -> Option<bool> {
+ (value & 1 != 0 && value & 8 == 0).then_some(value & 2 != 0)
+}
+
+pub fn set_hdr(on: bool) -> bool {
+ let Some(p) = selected_path() else { return false };
+ let mut s = ColorSet { h: header(DISPLAYCONFIG_DEVICE_INFO_SET_ADVANCED_COLOR_STATE, size_of::<ColorSet>(), &p, true), enable: on as u32 };
+ unsafe { DisplayConfigSetDeviceInfo(&mut s.h) == 0 }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn scale_steps_are_relative_to_the_recommended_one() {
+ // a 1080p laptop: smallest step 100% (rel -1), recommended 125% (0), up to 200% (3)
+ assert_eq!(percent(-1, -1), Some(100));
+ assert_eq!(percent(-1, 0), Some(125));
+ assert_eq!(percent(-1, 3), Some(200));
+ assert_eq!(percent(-1, 99), None);
+ }
+
+ #[test]
+ fn screen_modes_map_to_windows_ids() {
+ for t in Topo::ALL {
+ assert_eq!(Topo::of(t.id()), Some(t));
+ }
+ assert_eq!(Topo::of(0), None);
+ }
+
+ #[test]
+ fn hdr_needs_support_and_no_force_disable() {
+ assert_eq!(hdr_state(0), None);
+ assert_eq!(hdr_state(1), Some(false));
+ assert_eq!(hdr_state(3), Some(true));
+ assert_eq!(hdr_state(1 | 8), None);
+ }
+
+ #[test]
+ #[ignore = "reads this machine's display; run with --ignored --nocapture"]
+ fn live_primary_display() {
+ println!("scale {:?}, hdr {:?}, monitor {:?}, topology {:?}, connected {}", scale(), hdr(), monitor_info(), topology(), connected());
+ }
+
+ const fn m(w: u32, h: u32, hz: u32) -> Mode {
+ Mode { w, h, hz }
+ }
+ const ALL: [Mode; 5] = [m(1920, 1080, 60), m(1920, 1080, 144), m(1280, 720, 60), m(2560, 1440, 60), m(2560, 1440, 120)];
+
+ #[test]
+ fn resolutions_largest_first_keeping_the_rate() {
+ assert_eq!(resolutions(&ALL), vec![(2560, 1440), (1920, 1080), (1280, 720)]);
+ assert_eq!(with_res(&ALL, m(2560, 1440, 120), 1920, 1080), m(1920, 1080, 144)); // no 120 Hz at 1080p: its highest
+ assert_eq!(with_res(&ALL, m(1920, 1080, 60), 2560, 1440), m(2560, 1440, 60));
+ assert!(resolutions(&[]).is_empty());
+ }
+
+ #[test]
+ fn refresh_rates_of_the_current_resolution() {
+ assert_eq!(rates_at(&ALL, m(1920, 1080, 60)), vec![60, 144]);
+ assert_eq!(rates_at(&ALL, m(1280, 720, 60)), vec![60]);
+ }
+}
+
+// ---- arrangement: where the displays sit next to each other ----
+
+/// A display on the virtual desktop (desktop pixels).
+#[derive(Clone, Copy, PartialEq, Debug)]
+pub struct Mon {
+ pub x: i32,
+ pub y: i32,
+ pub w: i32,
+ pub h: i32,
+ pub primary: bool,
+}
+
+/// The attached displays in the order of the picker.
+pub fn layout() -> Vec<Mon> {
+ attached()
+ .into_iter()
+ .filter_map(|(n, primary)| {
+ let mut d = blank();
+ (unsafe { EnumDisplaySettingsW(n.as_ptr(), ENUM_CURRENT_SETTINGS, &mut d) } != 0).then(|| {
+ let p = unsafe { d.Anonymous1.Anonymous2.dmPosition };
+ Mon { x: p.x, y: p.y, w: d.dmPelsWidth as i32, h: d.dmPelsHeight as i32, primary }
+ })
+ })
+ .collect()
+}
+
+fn overlaps(a: (i32, i32, i32, i32), b: &Mon) -> bool {
+ a.0 < b.x + b.w && a.0 + a.2 > b.x && a.1 < b.y + b.h && a.1 + a.3 > b.y
+}
+
+/// Where a display of size w x h dropped at (x, y) lands: flush against the nearest edge of another display (Windows refuses
+/// gaps and overlaps), sliding along that edge as far as the drop was.
+pub fn snap(x: i32, y: i32, w: i32, h: i32, others: &[Mon]) -> (i32, i32) {
+ let mut best: Option<((i32, i32), i64)> = None;
+ for o in others {
+ let along_y = y.clamp(o.y - h + 1, o.y + o.h - 1);
+ let along_x = x.clamp(o.x - w + 1, o.x + o.w - 1);
+ for c in [(o.x + o.w, along_y), (o.x - w, along_y), (along_x, o.y + o.h), (along_x, o.y - h)] {
+ if others.iter().any(|m| overlaps((c.0, c.1, w, h), m)) {
+ continue;
+ }
+ let d = (c.0 - x) as i64 * (c.0 - x) as i64 + (c.1 - y) as i64 * (c.1 - y) as i64;
+ if best.is_none_or(|b| d < b.1) {
+ best = Some((c, d));
+ }
+ }
+ }
+ best.map_or((x, y), |b| b.0)
+}
+
+/// Moves display `i` so its corner is at (x, y) (already snapped); everything is shifted so the main display stays at (0, 0).
+/// Tested first, then applied and saved. Returns false when Windows refuses.
+pub fn move_monitor(i: usize, x: i32, y: i32) -> bool {
+ let att = attached();
+ let mut mons = layout();
+ if i >= mons.len() || mons.len() != att.len() {
+ return false;
+ }
+ (mons[i].x, mons[i].y) = (x, y);
+ let Some(p) = mons.iter().find(|m| m.primary).copied() else { return false };
+ let mut moves = vec![];
+ for ((n, _), m) in att.iter().zip(&mons) {
+ let mut d = blank();
+ if unsafe { EnumDisplaySettingsW(n.as_ptr(), ENUM_CURRENT_SETTINGS, &mut d) } == 0 {
+ return false;
+ }
+ d.Anonymous1.Anonymous2.dmPosition.x = m.x - p.x;
+ d.Anonymous1.Anonymous2.dmPosition.y = m.y - p.y;
+ d.dmFields = DM_POSITION;
+ if unsafe { ChangeDisplaySettingsExW(n.as_ptr(), &d, null_mut(), CDS_TEST, null()) } != DISP_CHANGE_SUCCESSFUL {
+ return false;
+ }
+ moves.push((*n, d, m.primary));
+ }
+ for (n, d, primary) in &moves {
+ unsafe { ChangeDisplaySettingsExW(n.as_ptr(), d, null_mut(), CDS_UPDATEREGISTRY | CDS_NORESET | if *primary { CDS_SET_PRIMARY } else { 0 }, null()) };
+ }
+ unsafe { ChangeDisplaySettingsExW(null(), null(), null_mut(), 0, null()) == DISP_CHANGE_SUCCESSFUL }
+}
+
+#[cfg(test)]
+mod arrange_tests {
+ use super::*;
+
+ fn m(x: i32, y: i32, w: i32, h: i32) -> Mon {
+ Mon { x, y, w, h, primary: false }
+ }
+
+ #[test]
+ fn a_dropped_display_lands_flush_against_the_nearest_edge() {
+ let main = [m(0, 0, 1920, 1080)];
+ assert_eq!(snap(1950, 100, 1280, 720, &main), (1920, 100)); // right of it, keeps its height offset
+ assert_eq!(snap(-1300, -50, 1280, 720, &main), (-1280, -50)); // left
+ assert_eq!(snap(300, 1200, 1280, 720, &main), (300, 1080)); // below
+ assert_eq!(snap(100, 5000, 1280, 720, &main), (100, 1080)); // far away still touches it
+ // dropped on top of it: pushed out to some edge
+ let r = snap(1000, 400, 800, 600, &main);
+ assert!(!overlaps((r.0, r.1, 800, 600), &main[0]));
+ }
+}
diff --git a/plugins/rust-settings/src/ext.rs b/plugins/rust-settings/src/ext.rs
new file mode 100644
index 0000000..6f45af7
--- /dev/null
+++ b/plugins/rust-settings/src/ext.rs
@@ -0,0 +1,451 @@
+//! The parts that used to be links to Windows' Settings: proxy, VPN (Remote Access API), disk cleanup (temp files, recycle bin),
+//! night light and the list of installed programs. Only documented Win32 calls; nothing here runs a shell.
+use crate::sys::{self, wide};
+use std::{
+ path::Path,
+ ptr::{null, null_mut},
+ sync::atomic::{AtomicU64, Ordering::Relaxed},
+ time::{Duration, SystemTime},
+};
+use windows_sys::Win32::{
+ Foundation::*,
+ NetworkManagement::Rras::*,
+ Networking::WinInet::{INTERNET_OPTION_REFRESH, INTERNET_OPTION_SETTINGS_CHANGED, InternetSetOptionW},
+ System::Registry::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE},
+};
+
+fn utf16(s: &[u16]) -> String {
+ String::from_utf16_lossy(&s[..s.iter().position(|&c| c == 0).unwrap_or(s.len())])
+}
+
+// ---- proxy (the per-user WinINet settings every browser and the system read) ----
+
+pub const INET: &str = r"Software\Microsoft\Windows\CurrentVersion\Internet Settings";
+
+pub fn proxy_text() -> String {
+ sys::string_long(HKEY_CURRENT_USER, INET, "ProxyServer").filter(|s| !s.is_empty()).unwrap_or_else(|| t!("не задан", "not set").into())
+}
+
+pub fn pac_text() -> String {
+ sys::string_long(HKEY_CURRENT_USER, INET, "AutoConfigURL").filter(|s| !s.is_empty()).unwrap_or_else(|| t!("не задан", "not set").into())
+}
+
+/// A proxy address as WinINet takes it: `host:port` or `http=h:p;https=h:p`. Empty clears it.
+pub fn valid_proxy(s: &str) -> bool {
+ s.len() <= 200 && !s.chars().any(|c| c.is_control() || c == ' ' || c == '"' || c == '<' || c == '>')
+}
+
+/// A script address for automatic configuration: http(s) or file URL.
+pub fn valid_pac(s: &str) -> bool {
+ s.is_empty() || (s.len() <= 400 && ["http://", "https://", "file://"].iter().any(|p| s.to_ascii_lowercase().starts_with(p)) && !s.chars().any(|c| c.is_control() || c == ' '))
+}
+
+/// Saves the proxy address (or the script address) and tells running programs to read the settings again.
+pub fn set_proxy(pac: bool, v: &str) -> bool {
+ let ok = sys::set_hkcu_string(INET, if pac { "AutoConfigURL" } else { "ProxyServer" }, v);
+ if ok && !pac && !v.is_empty() {
+ sys::set_hkcu_dword(INET, "ProxyEnable", 1);
+ }
+ proxy_changed();
+ ok
+}
+
+pub fn proxy_changed() {
+ unsafe {
+ InternetSetOptionW(null(), INTERNET_OPTION_SETTINGS_CHANGED, null(), 0);
+ InternetSetOptionW(null(), INTERNET_OPTION_REFRESH, null(), 0);
+ }
+}
+
+// ---- VPN ----
+
+#[derive(Clone, Debug)]
+pub struct Vpn {
+ pub name: String,
+ pub pbk: Option<String>, // the phone book that holds it (None: the default one)
+ pub on: bool,
+}
+
+fn user_pbk() -> Option<String> {
+ let p = std::path::PathBuf::from(std::env::var_os("APPDATA")?).join(r"Microsoft\Network\Connections\Pbk\rasphone.pbk");
+ p.is_file().then(|| p.to_string_lossy().into_owned())
+}
+
+fn entries(pbk: Option<&str>) -> Vec<String> {
+ let w = pbk.map(wide);
+ let (mut cb, mut n) = (size_of::<RASENTRYNAMEW>() as u32, 0u32);
+ let mut v: Vec<RASENTRYNAMEW> = vec![unsafe { std::mem::zeroed() }; 1];
+ v[0].dwSize = cb;
+ let ptr = |w: &Option<Vec<u16>>| w.as_ref().map_or(null(), |w| w.as_ptr());
+ let mut rc = unsafe { RasEnumEntriesW(null(), ptr(&w), v.as_mut_ptr(), &mut cb, &mut n) };
+ if rc == ERROR_BUFFER_TOO_SMALL {
+ v = vec![unsafe { std::mem::zeroed() }; cb as usize / size_of::<RASENTRYNAMEW>() + 1];
+ v.iter_mut().for_each(|e| e.dwSize = size_of::<RASENTRYNAMEW>() as u32);
+ rc = unsafe { RasEnumEntriesW(null(), ptr(&w), v.as_mut_ptr(), &mut cb, &mut n) };
+ }
+ if rc != 0 {
+ return vec![];
+ }
+ v.iter().take(n as usize).map(|e| utf16(&e.szEntryName)).collect()
+}
+
+fn active() -> Vec<(String, HRASCONN)> {
+ let (mut cb, mut n) = (size_of::<RASCONNW>() as u32, 0u32);
+ let mut v: Vec<RASCONNW> = vec![unsafe { std::mem::zeroed() }; 1];
+ v[0].dwSize = cb;
+ let mut rc = unsafe { RasEnumConnectionsW(v.as_mut_ptr(), &mut cb, &mut n) };
+ if rc == ERROR_BUFFER_TOO_SMALL {
+ v = vec![unsafe { std::mem::zeroed() }; cb as usize / size_of::<RASCONNW>() + 1];
+ v.iter_mut().for_each(|e| e.dwSize = size_of::<RASCONNW>() as u32);
+ rc = unsafe { RasEnumConnectionsW(v.as_mut_ptr(), &mut cb, &mut n) };
+ }
+ if rc != 0 {
+ return vec![];
+ }
+ v.iter().take(n as usize).map(|c| (utf16(&c.szEntryName), c.hrasconn)).collect()
+}
+
+/// The VPN profiles of this PC (Settings' VPN list and the classic ones) and whether each is connected.
+pub fn vpns() -> Vec<Vpn> {
+ let on = active();
+ let mut out: Vec<Vpn> = vec![];
+ for (pbk, names) in [(None, entries(None)), (user_pbk(), user_pbk().map_or(vec![], |p| entries(Some(&p))))] {
+ for name in names {
+ if !out.iter().any(|v| v.name == name) {
+ out.push(Vpn { on: on.iter().any(|c| c.0 == name), name, pbk: pbk.clone() });
+ }
+ }
+ }
+ out
+}
+
+pub fn ras_error(code: u32) -> String {
+ let mut buf = [0u16; 256];
+ if unsafe { RasGetErrorStringW(code, buf.as_mut_ptr(), buf.len() as u32) } == 0 {
+ let s = utf16(&buf);
+ if !s.is_empty() {
+ return s;
+ }
+ }
+ tf!("код {}", "code {}", code)
+}
+
+/// Dials a profile with the credentials Windows saved for it. Blocks until it is up or has failed: call from a thread.
+pub fn dial(name: &str, pbk: Option<&str>) -> Result<(), String> {
+ unsafe {
+ let mut p: RASDIALPARAMSW = std::mem::zeroed();
+ p.dwSize = size_of::<RASDIALPARAMSW>() as u32;
+ for (d, s) in p.szEntryName.iter_mut().zip(name.encode_utf16().take(256)) {
+ *d = s;
+ }
+ let w = pbk.map(wide);
+ let wp = w.as_ref().map_or(null(), |w| w.as_ptr());
+ let mut saved = 0;
+ let rc = RasGetEntryDialParamsW(wp, &mut p, &mut saved);
+ if rc != 0 {
+ return Err(ras_error(rc));
+ }
+ let mut h: HRASCONN = null_mut();
+ let rc = RasDialW(null(), wp, &p, 0, null(), &mut h);
+ p.szPassword.fill(0);
+ if rc != 0 {
+ if !h.is_null() {
+ RasHangUpW(h);
+ }
+ return Err(if rc == ERROR_AUTHENTICATION_FAILURE as u32 || saved == 0 { t!("Нет сохранённого пароля: введите его один раз в параметрах VPN Windows", "No saved password: enter it once in Windows' VPN settings").into() } else { ras_error(rc) });
+ }
+ Ok(())
+ }
+}
+
+/// Hangs up the connection of that profile.
+pub fn hang_up(name: &str) -> bool {
+ let Some((_, h)) = active().into_iter().find(|c| c.0 == name) else { return false };
+ unsafe { RasHangUpW(h) == 0 }
+}
+
+// ---- disk cleanup ----
+
+/// u64::MAX: not measured yet.
+pub static TEMP_BYTES: AtomicU64 = AtomicU64::new(u64::MAX);
+
+fn old_enough(m: &std::fs::Metadata, min_age: Duration) -> bool {
+ m.modified().ok().and_then(|t| SystemTime::now().duration_since(t).ok()).is_some_and(|a| a >= min_age)
+}
+
+fn reparse(m: &std::fs::Metadata) -> bool {
+ use std::os::windows::fs::MetadataExt;
+ m.file_attributes() & 0x400 != 0
+}
+
+/// Deletes the files under `dir` that are at least `min_age` old (empty folders go too); files in use, links and junctions are
+/// left alone. Returns (bytes freed, files deleted).
+pub fn clean_dir(dir: &Path, min_age: Duration) -> (u64, u32) {
+ let (mut bytes, mut files) = (0u64, 0u32);
+ let Ok(rd) = std::fs::read_dir(dir) else { return (0, 0) };
+ for e in rd.flatten() {
+ let Ok(m) = std::fs::symlink_metadata(e.path()) else { continue };
+ if reparse(&m) {
+ continue;
+ }
+ if m.is_dir() {
+ let (b, f) = clean_dir(&e.path(), min_age);
+ (bytes, files) = (bytes + b, files + f);
+ let _ = std::fs::remove_dir(e.path()); // only succeeds when empty
+ } else if old_enough(&m, min_age) && std::fs::remove_file(e.path()).is_ok() {
+ (bytes, files) = (bytes + m.len(), files + 1);
+ }
+ }
+ (bytes, files)
+}
+
+/// Bytes of the files under `dir` that `clean_dir` could delete.
+pub fn dir_bytes(dir: &Path, min_age: Duration) -> u64 {
+ let Ok(rd) = std::fs::read_dir(dir) else { return 0 };
+ rd.flatten()
+ .filter_map(|e| Some((e.path(), std::fs::symlink_metadata(e.path()).ok()?)))
+ .filter(|(_, m)| !reparse(m))
+ .map(|(p, m)| if m.is_dir() { dir_bytes(&p, min_age) } else if old_enough(&m, min_age) { m.len() } else { 0 })
+ .sum()
+}
+
+const TEMP_AGE: Duration = Duration::from_secs(24 * 3600);
+
+fn temp_dir() -> std::path::PathBuf {
+ std::env::temp_dir()
+}
+
+/// Measures the temp folder in a thread (it can be large); `done` runs afterwards.
+pub fn measure_temp(done: impl FnOnce() + Send + 'static) {
+ std::thread::spawn(move || {
+ TEMP_BYTES.store(dir_bytes(&temp_dir(), TEMP_AGE), Relaxed);
+ done();
+ });
+}
+
+/// Deletes the user's temp files older than a day, in a thread; `done` gets the message to show.
+pub fn clean_temp(done: impl FnOnce(String) + Send + 'static) {
+ std::thread::spawn(move || {
+ let (b, n) = clean_dir(&temp_dir(), TEMP_AGE);
+ TEMP_BYTES.store(dir_bytes(&temp_dir(), TEMP_AGE), Relaxed);
+ done(tf!("Удалено файлов: {} ({})", "Files deleted: {} ({})", n, crate::power::size(b)));
+ });
+}
+
+pub fn temp_text() -> String {
+ match TEMP_BYTES.load(Relaxed) {
+ u64::MAX => t!("считаю…", "measuring…").into(),
+ b => crate::power::size(b),
+ }
+}
+
+/// Size of the recycle bin (all drives).
+pub fn bin_bytes() -> u64 {
+ use windows_sys::Win32::UI::Shell::*;
+ let mut i: SHQUERYRBINFO = unsafe { std::mem::zeroed() };
+ i.cbSize = size_of::<SHQUERYRBINFO>() as u32;
+ if unsafe { SHQueryRecycleBinW(null(), &mut i) } == 0 { i.i64Size.max(0) as u64 } else { 0 }
+}
+
+/// Empties the recycle bin; Windows asks for the confirmation itself. Returns false when it was refused or cancelled.
+pub fn empty_bin(hwnd: HWND) -> bool {
+ use windows_sys::Win32::UI::Shell::*;
+ unsafe { SHEmptyRecycleBinW(hwnd, null(), SHERB_NOSOUND) == 0 }
+}
+
+// ---- night light ----
+// Windows' own night light is an undocumented per-build registry blob, so this is a colour-temperature filter of its own:
+// a gamma ramp on every display, kept by a small background process of this exe (`--nightlight`) that follows the setting.
+
+const NIGHT: &str = r"Software\WinRust\NightLight";
+const RUN: &str = r"Software\Microsoft\Windows\CurrentVersion\Run";
+
+/// The strengths on offer: Kelvin (0 = off).
+pub const NIGHT_STEPS: [u32; 5] = [0, 5500, 4800, 4200, 3600];
+
+pub fn night_kelvin() -> u32 {
+ sys::dword(HKEY_CURRENT_USER, NIGHT, "Kelvin").unwrap_or(0)
+}
+
+pub fn night_text() -> String {
+ match night_kelvin() {
+ 0 => t!("Выкл.", "Off").into(),
+ k => format!("{k} K"),
+ }
+}
+
+/// Switches the filter: the helper starts (and starts with Windows) while it is on, and puts the colours back when it is off.
+pub fn set_night(k: u32) {
+ sys::set_hkcu_dword(NIGHT, "Kelvin", k);
+ if k > 0 {
+ if let Ok(exe) = std::env::current_exe() {
+ sys::set_hkcu_string(RUN, "WinRustNightLight", &format!("\"{}\" --nightlight", exe.display()));
+ use std::os::windows::process::CommandExt;
+ let _ = std::process::Command::new(exe).arg("--nightlight").creation_flags(0x0800_0000).spawn();
+ }
+ } else {
+ sys::set_hkcu_string(RUN, "WinRustNightLight", "");
+ }
+}
+
+/// Red, green and blue gains (0..=1) of a colour temperature (Tanner Helland's approximation, relative to a 6500 K screen).
+pub fn gains(kelvin: u32) -> [f32; 3] {
+ let t = kelvin.clamp(1000, 6500) as f32 / 100.0;
+ let r = if t <= 66.0 { 255.0 } else { 329.698_73 * (t - 60.0).powf(-0.133_204_76) };
+ let g = if t <= 66.0 { 99.470_8 * t.ln() - 161.119_57 } else { 288.122_17 * (t - 60.0).powf(-0.075_514_85) };
+ let b = if t >= 66.0 { 255.0 } else if t <= 19.0 { 0.0 } else { 138.517_73 * (t - 10.0).ln() - 305.044_8 };
+ [r, g, b].map(|c| (c / 255.0).clamp(0.0, 1.0))
+}
+
+fn ramp(k: u32) -> [[u16; 256]; 3] {
+ let g = if k == 0 { [1.0; 3] } else { gains(k) };
+ let mut r = [[0u16; 256]; 3];
+ for (c, ch) in r.iter_mut().enumerate() {
+ for (i, v) in ch.iter_mut().enumerate() {
+ *v = (i as f32 * 257.0 * g[c]).round() as u16;
+ }
+ }
+ r
+}
+
+fn apply_ramp(k: u32) {
+ use windows_sys::Win32::{Graphics::Gdi::*, UI::ColorSystem::SetDeviceGammaRamp};
+ let r = ramp(k);
+ for i in 0.. {
+ let mut dd: DISPLAY_DEVICEW = unsafe { std::mem::zeroed() };
+ dd.cb = size_of::<DISPLAY_DEVICEW>() as u32;
+ if unsafe { EnumDisplayDevicesW(null(), i, &mut dd, 0) } == 0 {
+ break;
+ }
+ if dd.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP == 0 {
+ continue;
+ }
+ unsafe {
+ let dc = CreateDCW(wide("DISPLAY").as_ptr(), dd.DeviceName.as_ptr(), null(), null());
+ if !dc.is_null() {
+ SetDeviceGammaRamp(dc, r.as_ptr() as _);
+ DeleteDC(dc);
+ }
+ }
+ }
+}
+
+/// The helper process: re-applies the filter every few seconds (a mode change or sleep resets it) and leaves, with the colours
+/// back, once the setting is off. A second copy exits at once.
+pub fn night_helper() {
+ use windows_sys::Win32::System::Threading::CreateMutexW;
+ unsafe {
+ let m = CreateMutexW(null(), 0, wide("WinRustNightLight").as_ptr());
+ if m.is_null() || GetLastError() == ERROR_ALREADY_EXISTS {
+ return;
+ }
+ }
+ loop {
+ let k = night_kelvin();
+ apply_ramp(k);
+ if k == 0 {
+ return;
+ }
+ std::thread::sleep(Duration::from_secs(3));
+ }
+}
+
+// ---- installed programs ----
+
+#[derive(Clone)]
+pub struct App {
+ pub name: String,
+ pub version: String,
+ pub uninstall: String,
+}
+
+/// The programs of the classic list (HKLM 64/32-bit and HKCU), by name; components and updates are left out.
+pub fn programs() -> Vec<App> {
+ let base = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
+ let wow = r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall";
+ let mut out: Vec<App> = vec![];
+ for (root, path) in [(HKEY_LOCAL_MACHINE, base), (HKEY_LOCAL_MACHINE, wow), (HKEY_CURRENT_USER, base)] {
+ for sub in sys::subkeys(root, path) {
+ let key = format!(r"{path}\{sub}");
+ let Some(name) = sys::string_long(root, &key, "DisplayName").filter(|n| !n.trim().is_empty()) else { continue };
+ let Some(cmd) = sys::string_long(root, &key, "UninstallString").filter(|c| !c.trim().is_empty()) else { continue };
+ if sys::dword(root, &key, "SystemComponent") == Some(1) || sys::string_long(root, &key, "ParentKeyName").is_some() {
+ continue;
+ }
+ if !out.iter().any(|a| a.name == name) {
+ out.push(App { version: sys::string_long(root, &key, "DisplayVersion").unwrap_or_default(), name, uninstall: cmd });
+ }
+ }
+ }
+ out.sort_by_key(|a| a.name.to_lowercase());
+ out
+}
+
+/// Starts a program's own uninstaller (the command line it registered, as Windows' own list does).
+pub fn uninstall(cmd: &str) -> bool {
+ use windows_sys::Win32::System::Threading::*;
+ unsafe {
+ let mut si: STARTUPINFOW = std::mem::zeroed();
+ si.cb = size_of::<STARTUPINFOW>() as u32;
+ let mut pi: PROCESS_INFORMATION = std::mem::zeroed();
+ let mut line = wide(cmd);
+ if CreateProcessW(null(), line.as_mut_ptr(), null(), null(), 0, 0, null(), null(), &si, &mut pi) == 0 {
+ return false;
+ }
+ CloseHandle(pi.hThread);
+ CloseHandle(pi.hProcess);
+ true
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn proxy_and_pac_addresses_are_checked() {
+ assert!(valid_proxy("") && valid_proxy("proxy.corp:8080") && valid_proxy("http=a:1;https=b:2"));
+ assert!(!valid_proxy("a b") && !valid_proxy("a\"b"));
+ assert!(valid_pac("") && valid_pac("http://x/proxy.pac") && valid_pac("FILE://C:/p.pac"));
+ assert!(!valid_pac("ftp://x") && !valid_pac("proxy.pac"));
+ }
+
+ #[test]
+ fn warmer_light_cuts_blue_first() {
+ let (w, n) = (gains(6500), gains(3600));
+ assert!(w.iter().all(|&g| g > 0.95));
+ assert!(n[0] > 0.99 && n[2] < n[1] && n[1] < n[0] && n[2] > 0.4); // never so dark that Windows refuses the ramp
+ let r = ramp(3600);
+ assert_eq!(r[0][0], 0);
+ assert_eq!(r[0][255], 65535);
+ assert!(r[2][255] < r[0][255]);
+ assert_eq!(ramp(0)[2][255], 65535);
+ }
+
+ #[test]
+ fn cleaning_removes_old_files_and_empty_folders_and_counts_them() {
+ let d = std::env::temp_dir().join(format!("rs-clean-test-{}", std::process::id()));
+ std::fs::create_dir_all(d.join("sub/deeper")).unwrap();
+ std::fs::write(d.join("a.tmp"), [0u8; 10]).unwrap();
+ std::fs::write(d.join("sub/deeper/b.tmp"), [0u8; 5]).unwrap();
+ assert_eq!(dir_bytes(&d, Duration::from_secs(3600)), 0); // too new for a real clean
+ assert_eq!(dir_bytes(&d, Duration::ZERO), 15);
+ assert_eq!(clean_dir(&d, Duration::ZERO), (15, 2));
+ assert_eq!(std::fs::read_dir(&d).unwrap().count(), 0);
+ std::fs::remove_dir(&d).unwrap();
+ }
+}
+
+#[cfg(test)]
+mod live {
+ use super::*;
+
+ #[test]
+ #[ignore] // prints this machine's VPNs, programs and proxy: cargo test -p rust-settings live -- --ignored --nocapture
+ fn print_system() {
+ println!("vpns: {:?}", vpns());
+ println!("proxy: {} | pac: {}", proxy_text(), pac_text());
+ println!("programs: {}", programs().len());
+ println!("bin: {} bytes, night: {}", bin_bytes(), night_text());
+ }
+}
diff --git a/plugins/rust-settings/src/main.rs b/plugins/rust-settings/src/main.rs
new file mode 100644
index 0000000..f8f3172
--- /dev/null
+++ b/plugins/rust-settings/src/main.rs
@@ -0,0 +1,2082 @@
+#![windows_subsystem = "windows"]
+// rust-settings [page] A small Settings window that does not need Explorer or the Store Settings app.
+// Pages: Display (resolution, refresh rate, scale, orientation, HDR, night light, arrangement of several displays by dragging), Sound (output/input
+// device, volume, mute, volume per app), Power & storage (battery, power plan, drives, disk cleanup), Network (adapters, Wi-Fi on every adapter:
+// radio, connect with a password or 802.1X user name/password, hidden networks, disconnect/forget on right click; VPN; proxy), Bluetooth (radio,
+// airplane mode, paired and nearby devices), Apps (installed programs, uninstall), Windows Update (check, install), Personalization, About.
+// `page` is a name or an ms-settings: address; anything unknown opens the first page. Esc closes, Up/Down change the page.
+// A new resolution or refresh rate is temporary until confirmed: Enter keeps it, Esc or 15 s without a key goes back.
+// Safety: only documented Win32/WinRT calls (the one undocumented piece is the default-device switch of the sound panel, see audio.rs);
+// written are the HKCU values in `pages()`, the proxy values, the display mode and layout, the audio volume/mute/default device,
+// Wi-Fi profiles through the WLAN API (a password typed here goes only into the profile Windows stores), the night-light setting;
+// started: a program's own uninstaller after a second click, and this exe again for the night-light filter. No shell, no strings run as commands.
+// Display: resolution, refresh rate, scale (undocumented DisplayConfig type -4, the one Windows' Settings uses), orientation, HDR.
+// Several displays: pick the display the rows act on, extend/duplicate/one screen only (confirmed like a resolution), make main.
+// shortcut: night light is a colour filter of our own (a gamma ramp kept by a helper process), not Windows' schedule-driven one (an undocumented per-build blob).
+#[macro_use]
+extern crate winrust_common;
+mod audio;
+mod bt;
+mod display;
+mod ext;
+mod net;
+mod power;
+mod sys;
+mod wifi;
+mod wu;
+use std::{
+ cell::RefCell,
+ ptr::{null, null_mut},
+};
+use sys::wide;
+use windows_sys::Win32::{
+ Foundation::*,
+ Graphics::Gdi::*,
+ NetworkManagement::WiFi::wlan_notification_acm_connection_complete,
+ System::{
+ LibraryLoader::GetModuleHandleW,
+ Registry::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE},
+ SystemInformation::*,
+ },
+ UI::{HiDpi::GetDpiForSystem, Input::KeyboardAndMouse::*, WindowsAndMessaging::*},
+};
+
+const PERSONALIZE: &str = r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize";
+const STORAGE_SENSE: &str = r"Software\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy";
+const NT: &str = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion";
+
+enum Row {
+ /// On when the DWORD equals `on_when`; a missing value counts as `default`.
+ Toggle { label: String, key: &'static str, name: &'static str, on_when: u32, default: u32 },
+ Info(String, String),
+ /// A click does `Op`; the value shown is read live.
+ Cycle(String, fn() -> String, Op),
+ /// The volume of the speakers, the microphone or one app.
+ Slider(String, audio::Src),
+ /// A row that does `Cmd` on a click; the value is shown dim on the right.
+ Item(String, String, Cmd),
+ /// One of the four slots of the display-arrangement picture; every slot draws its own quarter of it.
+ Arrange(u8),
+ /// A network adapter; a click shows or hides its details (the Info rows after it) when `bool` is set.
+ Adapter(net::Adapter, bool),
+ /// A section title above a group of rows (not clickable).
+ Header(String),
+ /// A switch whose state is read live (None: no such device, drawn disabled); a click does `Op`.
+ Switch(String, fn() -> Option<bool>, Op),
+ /// A visible Wi-Fi network and its status text: a click connects (asking for a password when it has no profile),
+ /// a right click disconnects or forgets a saved one.
+ Wifi(wifi::Net, String),
+}
+
+#[derive(Clone, Copy)]
+enum Op {
+ Res,
+ Hz,
+ Mute,
+ MicMute,
+ Orient,
+ Scale,
+ Hdr,
+ Monitor, // which display the rows below act on
+ Topology, // extend / duplicate / one screen only
+ Primary, // make the selected display the main one
+ Screen,
+ Sleep,
+ Plan,
+ Radio, // Wi-Fi on/off
+ Hidden, // asks for the name of a hidden network
+ Nop, // a live value that does nothing when clicked
+ OutDev, // playback device
+ InDev, // recording device
+ Night, // night-light strength
+ Proxy, // asks for the proxy address
+ Pac, // asks for the proxy script address
+ Bt, // Bluetooth radio
+ Air, // airplane mode
+}
+
+#[derive(Clone)]
+enum Cmd {
+ Vpn(ext::Vpn),
+ CleanTemp,
+ EmptyBin,
+ Uninstall(String),
+ BtPair(String),
+ BtUnpair(String),
+ BtScan,
+ Check,
+ Install,
+}
+
+const CONFIRM_SECS: u32 = 15;
+const WM_MOUSELEAVE: u32 = 0x02A3; // not in windows-sys' enabled modules
+
+struct Page {
+ title: String,
+ rows: Vec<Row>,
+}
+
+#[derive(Default)]
+struct App {
+ pages: Vec<Page>,
+ page: usize,
+ dpi: i32,
+ fonts: [isize; 6], // see refresh_fonts
+ mono: bool, // the fonts are the monospace ones of the terminal/tiling styles
+ pending: u32, // seconds left to confirm a display change; 0 = nothing to confirm
+ drag: Option<audio::Src>, // a volume slider is being dragged
+ scroll: i32, // how far the rows are scrolled up, logical px
+ hover: Option<usize>, // the clickable row under the pointer
+ prompt: Option<Prompt>, // the bottom bar asks for a Wi-Fi password or a hidden network's name
+ edit: isize, // its text field (HWND), 0 when no prompt
+ brush: isize, // the field's background brush
+ msg: Option<String>, // a Wi-Fi status shown in the bottom bar
+ connecting: Option<(String, String, bool)>, // (SSID, profile, profile made just now): waiting for the result
+ ticks: u32, // network refreshes since start: every 8th also scans
+ pick: Option<Pick>, // an open drop-down list of values
+ arr: Option<ArrDrag>, // a display of the arrangement picture is being dragged
+ layout: Vec<display::Mon>, // the displays as the picture shows them
+ armed: Option<String>, // the row (by label) whose destructive action waits for a second click
+ apps: Option<Vec<ext::App>>, // the installed programs, read when the page opens
+}
+
+/// A display being dragged in the arrangement picture (desktop pixels).
+struct ArrDrag {
+ idx: usize,
+ grab: (i32, i32), // pointer minus the display's corner
+ cur: (i32, i32), // where the corner is now
+ moved: bool,
+}
+
+/// A drop-down list under a row: the values to choose from, the current one, and its animation.
+struct Pick {
+ op: Op,
+ row: usize,
+ items: Vec<String>,
+ cur: Option<usize>,
+ hover: Option<usize>,
+ top: usize, // first visible item when the list is longer than PICK_MAX
+ t0: std::time::Instant,
+}
+
+const PICK_ROW: i32 = 36;
+const PICK_MAX: usize = 8;
+
+enum Prompt {
+ Ssid,
+ /// The proxy address (false) or the proxy script address (true).
+ Proxy(bool),
+ /// An 802.1X network: first the user name, then the password.
+ EapUser(wifi::Net),
+ EapPass(wifi::Net, String),
+ /// The network and whether it is a hidden one (then an empty password means an open network).
+ Key(wifi::Net, bool),
+}
+thread_local! { static APP: RefCell<App> = RefCell::new(App::default()) }
+
+fn is_on(val: Option<u32>, on_when: u32, default: u32) -> bool {
+ val.unwrap_or(default) == on_when
+}
+
+fn row_at(y: i32, top: i32, h: i32, n: usize) -> Option<usize> {
+ if y < top {
+ return None;
+ }
+ let i = ((y - top) / h) as usize;
+ (i < n).then_some(i)
+}
+
+fn os_name(product: &str, build: u32) -> String {
+ // the registry still says "Windows 10" on Windows 11
+ if build >= 22000 { product.replace("Windows 10", "Windows 11") } else { product.to_string() }
+}
+
+fn gb(bytes: u64) -> String {
+ format!("{:.1} GB", bytes as f64 / (1u64 << 30) as f64)
+}
+
+/// Words that select each page, in the order of `pages()`.
+const PAGE_KEYS: [&[&str]; 9] = [&["display"], &["sound"], &["power", "battery", "storage"], &["network", "wifi", "ethernet"], &["bluetooth", "airplane"], &["apps"], &["update"], &["personal", "color", "theme"], &["about"]];
+
+/// The page a name or an ms-settings: address points at; the first page when nothing matches.
+fn page_for(arg: &str) -> usize {
+ let a = arg.to_ascii_lowercase();
+ PAGE_KEYS.iter().position(|ks| ks.iter().any(|k| a.contains(k))).unwrap_or(0)
+}
+
+fn res_text() -> String {
+ display::current().map_or("?".into(), |m| format!("{} x {}", m.w, m.h))
+}
+
+fn hz_text() -> String {
+ display::current().map_or("?".into(), |m| format!("{} Hz", m.hz))
+}
+
+fn monitor_text() -> String {
+ match display::monitor_info() {
+ Some((n, total, name, _)) if total > 1 => format!("{n}/{total} · {name}"),
+ Some((_, _, name, _)) => name,
+ None => "?".into(),
+ }
+}
+
+fn topo_text() -> String {
+ if display::connected() < 2 {
+ return t!("Один экран", "Single display").into();
+ }
+ display::topology().map_or("?".into(), |t| topo_name(t).into())
+}
+
+fn topo_name(t: display::Topo) -> &'static str {
+ use display::Topo::*;
+ match t {
+ Extend => t!("Расширить", "Extend"),
+ Duplicate => t!("Повторять", "Duplicate"),
+ PcOnly => t!("Только этот ПК", "PC screen only"),
+ SecondOnly => t!("Только второй экран", "Second screen only"),
+ }
+}
+
+fn primary_text() -> String {
+ match display::monitor_info() {
+ Some((_, _, _, true)) => t!("Этот дисплей основной", "This is the main display").into(),
+ Some(_) => t!("Сделать основным", "Make main").into(),
+ None => "?".into(),
+ }
+}
+
+fn scale_text() -> String {
+ display::scale().map_or("?".into(), |p| format!("{p}%"))
+}
+
+/// The HDR switch: None (drawn disabled) when the display cannot do HDR.
+fn hdr_on() -> Option<bool> {
+ display::hdr()
+}
+
+fn orient_text() -> String {
+ display::orientation().and_then(|o| orient_names().get(o as usize).copied()).unwrap_or("?").into()
+}
+
+fn orient_names() -> [&'static str; 4] {
+ [t!("Альбомная", "Landscape"), t!("Книжная", "Portrait"), t!("Альбомная (перевёрнутая)", "Landscape (flipped)"), t!("Книжная (перевёрнутая)", "Portrait (flipped)")]
+}
+
+/// Rows whose value is picked from a list (the others act on a click). Screen modes need a second screen.
+fn listed(op: Op) -> bool {
+ matches!(op, Op::Res | Op::Hz | Op::Orient | Op::Scale | Op::Monitor | Op::Plan | Op::Screen | Op::Sleep | Op::OutDev | Op::InDev | Op::Night) || (matches!(op, Op::Topology) && display::connected() > 1)
+}
+
+/// The values a list offers and the index of the current one. None when there is nothing to choose.
+fn choices(op: Op) -> Option<(Vec<String>, Option<usize>)> {
+ let list = match op {
+ Op::Res => {
+ let (modes, c) = (display::modes(), display::current()?);
+ let r = display::resolutions(&modes);
+ (r.iter().map(|(w, h)| format!("{w} x {h}")).collect(), r.iter().position(|&x| x == (c.w, c.h)))
+ }
+ Op::Hz => {
+ let (modes, c) = (display::modes(), display::current()?);
+ let r = display::rates_at(&modes, c);
+ (r.iter().map(|h| format!("{h} Hz")).collect(), r.iter().position(|&h| h == c.hz))
+ }
+ Op::Orient => (orient_names().iter().map(|s| s.to_string()).collect(), display::orientation().map(|o| o as usize)),
+ Op::Scale => {
+ let (v, i) = display::scales()?;
+ (v.iter().map(|p| format!("{p}%")).collect(), Some(i))
+ }
+ Op::Monitor => (display::monitor_names(), Some(display::selected_index())),
+ Op::Topology if display::connected() > 1 => {
+ let cur = display::topology();
+ (display::Topo::ALL.iter().map(|&t| topo_name(t).to_string()).collect(), display::Topo::ALL.iter().position(|&t| Some(t) == cur))
+ }
+ Op::OutDev | Op::InDev => {
+ let d = audio::devices(matches!(op, Op::InDev));
+ (d.iter().map(|d| d.name.clone()).collect(), d.iter().position(|d| d.default))
+ }
+ Op::Night => (night_labels(), ext::NIGHT_STEPS.iter().position(|&k| k == ext::night_kelvin())),
+ Op::Plan => power::plans(),
+ Op::Screen => power::timeouts(power::Timeout::Screen),
+ Op::Sleep => power::timeouts(power::Timeout::Sleep),
+ _ => return None,
+ };
+ (!list.0.is_empty()).then_some(list)
+}
+
+/// Applies entry `i` of `choices(op)`. Display modes are temporary until confirmed (the 15 s countdown in the bottom bar).
+unsafe fn choose(hwnd: HWND, op: Op, i: usize) {
+ let confirm = || unsafe {
+ APP.with_borrow_mut(|a| a.pending = CONFIRM_SECS);
+ SetTimer(hwnd, 1, 1000, None);
+ };
+ let (modes, cur) = (display::modes(), display::current());
+ match (op, cur) {
+ (Op::Res, Some(c)) => {
+ if let Some(&(w, h)) = display::resolutions(&modes).get(i) {
+ let m = display::with_res(&modes, c, w, h);
+ if m != c && display::apply(m, false) {
+ confirm();
+ }
+ }
+ }
+ (Op::Hz, Some(c)) => {
+ if let Some(&hz) = display::rates_at(&modes, c).get(i) {
+ if hz != c.hz && display::apply(display::Mode { hz, ..c }, false) {
+ confirm();
+ }
+ }
+ }
+ (Op::Orient, _) if display::orientation() != Some(i as u32) && display::set_orientation(i as u32, false) => confirm(),
+ (Op::Scale, _) => drop(display::set_scale_index(i)),
+ (Op::Monitor, _) => display::select_monitor(i),
+ (Op::Topology, _) => {
+ if display::Topo::ALL.get(i).is_some_and(|&t| display::set_topology_to(t)) {
+ confirm();
+ }
+ }
+ (Op::OutDev | Op::InDev, _) => {
+ if let Some(d) = audio::devices(matches!(op, Op::InDev)).get(i) {
+ audio::set_default(&d.id);
+ }
+ }
+ (Op::Night, _) => ext::set_night(ext::NIGHT_STEPS.get(i).copied().unwrap_or(0)),
+ (Op::Plan, _) => power::set_plan(i),
+ (Op::Screen, _) => power::set_timeout(power::Timeout::Screen, i),
+ (Op::Sleep, _) => power::set_timeout(power::Timeout::Sleep, i),
+ _ => {}
+ }
+}
+
+unsafe fn open_pick(hwnd: HWND, op: Op, row: usize) {
+ let Some((items, cur)) = choices(op) else { return };
+ let top = cur.unwrap_or(0).saturating_sub(PICK_MAX / 2).min(items.len().saturating_sub(PICK_MAX));
+ APP.with_borrow_mut(|a| a.pick = Some(Pick { op, row, items, cur, hover: cur, top, t0: std::time::Instant::now() }));
+ unsafe { SetTimer(hwnd, 4, 15, None) }; // animation frames
+}
+
+/// Where the open list sits (device px), how many items show, and whether it opens downward from its row.
+fn pick_geom(a: &App, cw: i32, ch: i32) -> Option<(RECT, usize, bool)> {
+ let pk = a.pick.as_ref()?;
+ let p = |v: i32| (v as f64 * (a.dpi as f64 / 96.0)) as i32;
+ let (cl, cr) = col(cw, a.dpi);
+ let scroll = a.scroll.min(max_scroll(a.pages.get(a.page).map_or(0, |pg| pg.rows.len()), ch * 96 / a.dpi.max(1)));
+ let row_top = p(ROWS_TOP + ROW_H * pk.row as i32 - scroll);
+ let n = pk.items.len().min(PICK_MAX);
+ let (w, h) = (p(280).min(cr - cl), p(12 + PICK_ROW * n as i32));
+ let left = cr - w - p(6);
+ let down = row_top + p(ROW_H) + h + p(12) <= ch || row_top - h < p(12);
+ let top = if down { row_top + p(ROW_H) - p(2) } else { row_top - h + p(2) };
+ Some((RECT { left, top, right: left + w, bottom: top + h }, n, down))
+}
+
+/// The list item under (x, y), as an index into its items.
+fn pick_item(a: &App, cw: i32, ch: i32, x: i32, y: i32) -> Option<usize> {
+ let (r, n, _) = pick_geom(a, cw, ch)?;
+ let row = a.dpi * PICK_ROW / 96;
+ let pad = a.dpi * 6 / 96;
+ (x >= r.left && x < r.right && y >= r.top + pad && y < r.top + pad + row * n as i32).then(|| a.pick.as_ref().unwrap().top + ((y - r.top - pad) / row) as usize)
+}
+
+fn night_labels() -> Vec<String> {
+ ext::NIGHT_STEPS
+ .iter()
+ .map(|&k| match k {
+ 0 => t!("Выкл.", "Off").to_string(),
+ 5500 => tf!("Слабый · {} K", "Low · {} K", k),
+ 4800 => tf!("Средний · {} K", "Medium · {} K", k),
+ 4200 => tf!("Сильный · {} K", "Strong · {} K", k),
+ _ => tf!("Максимальный · {} K", "Maximum · {} K", k),
+ })
+ .collect()
+}
+
+fn out_dev_text() -> String {
+ audio::default_name(false)
+}
+
+fn in_dev_text() -> String {
+ audio::default_name(true)
+}
+
+fn bt_on() -> Option<bool> {
+ bt::state().bt
+}
+
+fn air_on() -> Option<bool> {
+ bt::state().air
+}
+
+fn screen_text() -> String {
+ power::timeout_text(power::Timeout::Screen)
+}
+
+fn sleep_text() -> String {
+ power::timeout_text(power::Timeout::Sleep)
+}
+
+const NET_PAGE: usize = 3;
+const BT_PAGE: usize = 4;
+const APPS_PAGE: usize = 5;
+const WU_PAGE: usize = 6;
+
+thread_local! { static EXPANDED: RefCell<Option<String>> = const { RefCell::new(None) } } // the adapter whose details show
+thread_local! { static RADIO: std::cell::Cell<Option<(bool, bool)>> = const { std::cell::Cell::new(None) } }
+
+/// The Wi-Fi switch: None (drawn disabled) without an adapter or with the hardware switch off.
+fn radio_on() -> Option<bool> {
+ RADIO.get().filter(|r| r.1).map(|r| r.0)
+}
+
+fn sound_muted() -> Option<bool> {
+ audio::muted(false)
+}
+
+fn mic_muted() -> Option<bool> {
+ audio::muted(true)
+}
+
+/// Lit bars (1..=4) for a WLAN signal quality (0..=100).
+fn bars(q: u32) -> u32 {
+ match q {
+ 0..=19 => 1,
+ 20..=44 => 2,
+ 45..=69 => 3,
+ _ => 4,
+ }
+}
+
+fn wifi_note(n: &wifi::Net) -> String {
+ use wifi::Sec::*;
+ match (n.connected, &n.profile, n.sec) {
+ (true, ..) => t!("Подключено · правый клик: отключить, забыть", "Connected · right click: disconnect, forget").into(),
+ (_, Some(_), _) => t!("Сохранена", "Saved").into(),
+ (_, _, None) if n.eap.is_some() => t!("Корпоративная (802.1X) · имя и пароль", "Enterprise (802.1X) · user name and password").into(),
+ (_, _, None) => t!("Корпоративная, сертификатом: не поддерживается", "Enterprise with certificates: not supported").into(),
+ (_, _, Some(Open | Owe)) => t!("Открытая сеть", "Open network").into(),
+ (_, _, Some(s)) => {
+ let kind = match s {
+ Wep { .. } => "WEP",
+ Wpa { .. } => "WPA",
+ Wpa3 => "WPA3",
+ _ => "WPA2",
+ };
+ tf!("Защищена · {}", "Secured · {}", kind)
+ }
+ }
+}
+
+/// Adapters with their addresses, Wi-Fi on/off, the visible networks, then the system pages for VPN and proxy.
+fn network_rows() -> Vec<Row> {
+ let mut rows = vec![];
+ let adapters = net::adapters();
+ if !adapters.is_empty() {
+ rows.push(Row::Header(t!("Подключения", "Connections").into()));
+ }
+ for a in adapters {
+ let open = EXPANDED.with_borrow(|e| e.as_deref() == Some(a.name.as_str()));
+ let details = if open { a.details() } else { vec![] };
+ rows.push(Row::Adapter(a, open));
+ rows.extend(details.into_iter().map(|(l, v)| Row::Info(l, v)));
+ }
+ let radio = wifi::radio();
+ RADIO.set(radio);
+ if let Some((_, hw)) = radio {
+ rows.push(Row::Header("Wi-Fi".into()));
+ let label = if hw { "Wi-Fi".into() } else { t!("Wi-Fi выключен кнопкой на устройстве", "Wi-Fi is off by the hardware switch").into() };
+ rows.push(Row::Switch(label, radio_on, Op::Radio));
+ for n in wifi::list().into_iter().take(12) {
+ let note = wifi_note(&n);
+ rows.push(Row::Wifi(n, note));
+ }
+ if radio.is_some_and(|r| r.0 && r.1) {
+ rows.push(Row::Cycle(t!("Другая сеть…", "Other network…").into(), String::new, Op::Hidden));
+ }
+ }
+ rows.push(Row::Header("VPN".into()));
+ let vpns = ext::vpns();
+ if vpns.is_empty() {
+ rows.push(Row::Info(t!("VPN-подключения", "VPN connections").into(), t!("не настроены", "none set up").into()));
+ }
+ for v in vpns {
+ let state = if v.on { t!("Подключено", "Connected") } else { t!("Отключено", "Disconnected") };
+ rows.push(Row::Item(v.name.clone(), state.into(), Cmd::Vpn(v)));
+ }
+ rows.push(Row::Header(t!("Прокси-сервер", "Proxy").into()));
+ rows.push(toggle_row(t!("Использовать прокси-сервер", "Use a proxy server"), ext::INET, "ProxyEnable", 1, 0));
+ rows.push(Row::Cycle(t!("Адрес прокси-сервера", "Proxy address").into(), ext::proxy_text, Op::Proxy));
+ rows.push(Row::Cycle(t!("Скрипт настройки (PAC)", "Setup script (PAC)").into(), ext::pac_text, Op::Pac));
+ rows
+}
+
+fn toggle_row(label: &str, key: &'static str, name: &'static str, on_when: u32, default: u32) -> Row {
+ Row::Toggle { label: label.into(), key, name, on_when, default }
+}
+
+fn display_rows() -> Vec<Row> {
+ let head = |s: &str| Row::Header(s.into());
+ let mut rows = vec![head(t!("Дисплеи", "Displays"))];
+ if display::layout().len() > 1 {
+ rows.extend((0..4).map(Row::Arrange));
+ }
+ rows.extend([
+ Row::Cycle(t!("Дисплей", "Display").into(), monitor_text, Op::Monitor),
+ Row::Cycle(t!("Несколько экранов", "Multiple displays").into(), topo_text, Op::Topology),
+ Row::Cycle(t!("Основной дисплей", "Main display").into(), primary_text, Op::Primary),
+ head(t!("Выбранный дисплей", "Selected display")),
+ Row::Cycle(t!("Разрешение", "Resolution").into(), res_text, Op::Res),
+ Row::Cycle(t!("Частота обновления", "Refresh rate").into(), hz_text, Op::Hz),
+ Row::Cycle(t!("Масштаб", "Scale").into(), scale_text, Op::Scale),
+ Row::Cycle(t!("Ориентация", "Orientation").into(), orient_text, Op::Orient),
+ Row::Switch(t!("HDR", "HDR").into(), hdr_on, Op::Hdr),
+ head(t!("Цвет", "Colour")),
+ Row::Cycle(t!("Ночной свет", "Night light").into(), ext::night_text, Op::Night),
+ ]);
+ rows
+}
+
+fn sound_rows() -> Vec<Row> {
+ let head = |s: &str| Row::Header(s.into());
+ let mut rows = vec![
+ head(t!("Вывод", "Output")),
+ Row::Cycle(t!("Устройство вывода", "Output device").into(), out_dev_text, Op::OutDev),
+ Row::Slider(t!("Громкость", "Volume").into(), audio::Src::Out),
+ Row::Switch(t!("Без звука", "Mute").into(), sound_muted, Op::Mute),
+ head(t!("Ввод", "Input")),
+ Row::Cycle(t!("Устройство ввода", "Input device").into(), in_dev_text, Op::InDev),
+ Row::Slider(t!("Микрофон", "Microphone").into(), audio::Src::Mic),
+ Row::Switch(t!("Микрофон выключен", "Microphone muted").into(), mic_muted, Op::MicMute),
+ head(t!("Громкость приложений", "Volume per app")),
+ ];
+ let apps = audio::apps();
+ if apps.is_empty() {
+ rows.push(Row::Info(t!("Приложения со звуком", "Apps with sound").into(), t!("сейчас нет", "none right now").into()));
+ }
+ rows.extend(apps.into_iter().map(|(pid, name)| Row::Slider(name, audio::Src::App(pid))));
+ rows
+}
+
+fn power_rows() -> Vec<Row> {
+ let head = |s: &str| Row::Header(s.into());
+ let bin = ext::bin_bytes();
+ [
+ vec![
+ head(t!("Питание", "Power")),
+ Row::Cycle(t!("Батарея", "Battery").into(), power::battery_text, Op::Nop),
+ Row::Cycle(t!("Схема питания", "Power plan").into(), power::plan_text, Op::Plan),
+ Row::Cycle(t!("Отключать экран через", "Turn screen off after").into(), screen_text, Op::Screen),
+ Row::Cycle(t!("Переходить в сон через", "Sleep after").into(), sleep_text, Op::Sleep),
+ head(t!("Хранилище", "Storage")),
+ toggle_row(t!("Контроль памяти (автоочистка)", "Storage Sense (auto cleanup)"), STORAGE_SENSE, "01", 1, 0),
+ ],
+ power::drives().into_iter().map(|(l, free, total)| Row::Info(tf!("Диск {}:", "Drive {}:", l), tf!("{} свободно из {}", "{} free of {}", power::size(free), power::size(total)))).collect(),
+ vec![
+ head(t!("Очистка диска", "Disk cleanup")),
+ Row::Item(t!("Временные файлы (старше суток)", "Temporary files (older than a day)").into(), ext::temp_text(), Cmd::CleanTemp),
+ Row::Item(t!("Корзина", "Recycle Bin").into(), if bin == 0 { t!("пуста", "empty").into() } else { power::size(bin) }, Cmd::EmptyBin),
+ ],
+ ]
+ .into_iter()
+ .flatten()
+ .collect()
+}
+
+fn bt_rows() -> Vec<Row> {
+ let s = bt::state();
+ let head = |x: &str| Row::Header(x.into());
+ let label = if s.bt.is_some() { "Bluetooth".into() } else { t!("Bluetooth: адаптера нет", "Bluetooth: no adapter").into() };
+ let mut rows = vec![head("Bluetooth"), Row::Switch(label, bt_on, Op::Bt), Row::Switch(t!("Режим «в самолёте»", "Airplane mode").into(), air_on, Op::Air)];
+ if s.bt == Some(true) {
+ rows.push(head(t!("Сопряжённые устройства", "Paired devices")));
+ if s.paired.is_empty() {
+ rows.push(Row::Info(t!("Устройства", "Devices").into(), t!("нет", "none").into()));
+ }
+ for d in &s.paired {
+ let st = if d.connected { t!("Подключено", "Connected") } else { t!("Сопряжено", "Paired") };
+ rows.push(Row::Item(d.name.clone(), st.into(), Cmd::BtUnpair(d.id.clone())));
+ }
+ rows.push(head(t!("Устройства поблизости", "Nearby devices")));
+ rows.push(Row::Item(t!("Найти устройства", "Find devices").into(), if s.scanning { t!("поиск…", "searching…").into() } else { String::new() }, Cmd::BtScan));
+ for d in s.nearby.iter().filter(|d| !s.paired.iter().any(|p| p.id == d.id)) {
+ rows.push(Row::Item(d.name.clone(), t!("Сопрячь", "Pair").into(), Cmd::BtPair(d.id.clone())));
+ }
+ }
+ rows
+}
+
+fn apps_rows(list: &[ext::App]) -> Vec<Row> {
+ let mut rows = vec![Row::Header(tf!("Установленные программы: {}", "Installed programs: {}", list.len()))];
+ rows.extend(list.iter().take(400).map(|a| Row::Item(a.name.clone(), a.version.clone(), Cmd::Uninstall(a.uninstall.clone()))));
+ rows
+}
+
+fn wu_rows() -> Vec<Row> {
+ let s = wu::state();
+ let status = match (&s.busy, &s.found) {
+ (Some(b), _) => b.clone(),
+ (_, None) => t!("Ещё не проверялось", "Not checked yet").into(),
+ (_, Some(f)) if f.is_empty() => t!("Всё установлено", "Up to date").into(),
+ (_, Some(f)) => tf!("Доступно обновлений: {}", "Updates available: {}", f.len()),
+ };
+ let mut rows = vec![Row::Header(t!("Центр обновления Windows", "Windows Update").into()), Row::Info(t!("Состояние", "Status").into(), status)];
+ if !s.note.is_empty() {
+ rows.push(Row::Info(t!("Результат", "Result").into(), s.note.clone()));
+ }
+ for title in s.found.iter().flatten().take(30) {
+ rows.push(Row::Info(t!("Обновление", "Update").into(), title.clone()));
+ }
+ if s.busy.is_none() {
+ rows.push(Row::Item(t!("Проверить наличие обновлений", "Check for updates").into(), String::new(), Cmd::Check));
+ if s.found.as_ref().is_some_and(|f| !f.is_empty()) {
+ rows.push(Row::Item(t!("Скачать и установить", "Download and install").into(), t!("нужны права администратора", "needs administrator rights").into(), Cmd::Install));
+ }
+ }
+ rows
+}
+
+/// The rows of the pages that change by themselves; the others are built once.
+fn dynamic(page: usize, apps: &mut Option<Vec<ext::App>>) -> Option<Vec<Row>> {
+ match page {
+ 0 => Some(display_rows()),
+ 1 => Some(sound_rows()),
+ 2 => Some(power_rows()),
+ NET_PAGE => Some(network_rows()),
+ BT_PAGE => Some(bt_rows()),
+ APPS_PAGE => Some(apps_rows(apps.get_or_insert_with(ext::programs))),
+ WU_PAGE => Some(wu_rows()),
+ _ => None,
+ }
+}
+
+fn pages() -> Vec<Page> {
+ let reg = |n| sys::string(HKEY_LOCAL_MACHINE, NT, n).unwrap_or_default();
+ let build: u32 = reg("CurrentBuild").parse().unwrap_or(0);
+ let mut mem: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
+ mem.dwLength = size_of::<MEMORYSTATUSEX>() as u32;
+ let ram = if unsafe { GlobalMemoryStatusEx(&mut mem) } != 0 { gb(mem.ullTotalPhys) } else { "?".into() };
+ let head = |s: &str| Row::Header(s.into());
+ vec![
+ Page { title: t!("Экран", "Display").into(), rows: display_rows() },
+ Page { title: t!("Звук", "Sound").into(), rows: sound_rows() },
+ Page { title: t!("Питание и диски", "Power & storage").into(), rows: power_rows() },
+ Page { title: t!("Сеть", "Network").into(), rows: network_rows() },
+ Page { title: "Bluetooth".into(), rows: bt_rows() },
+ Page { title: t!("Приложения", "Apps").into(), rows: vec![] }, // read when the page opens
+ Page { title: t!("Центр обновления", "Windows Update").into(), rows: wu_rows() },
+ Page {
+ title: t!("Персонализация", "Personalization").into(),
+ rows: vec![
+ head(t!("Оформление", "Appearance")),
+ toggle_row(t!("Тёмная тема для приложений", "Dark theme for apps"), PERSONALIZE, "AppsUseLightTheme", 0, 1),
+ toggle_row(t!("Тёмная тема для системы", "Dark theme for the system"), PERSONALIZE, "SystemUsesLightTheme", 0, 1),
+ toggle_row(t!("Эффекты прозрачности", "Transparency effects"), PERSONALIZE, "EnableTransparency", 1, 1),
+ toggle_row(t!("Акцентный цвет на заголовках окон", "Accent color on title bars"), r"Software\Microsoft\Windows\DWM", "ColorPrevalence", 1, 0),
+ ],
+ },
+ Page {
+ title: t!("О системе", "About").into(),
+ rows: vec![
+ head(t!("Устройство", "Device")),
+ Row::Info(t!("Имя компьютера", "Computer name").into(), std::env::var("COMPUTERNAME").unwrap_or_default()),
+ Row::Info(t!("Оперативная память", "Memory").into(), ram),
+ head("Windows"),
+ Row::Info(t!("Выпуск", "Edition").into(), os_name(&reg("ProductName"), build)),
+ Row::Info(t!("Версия", "Version").into(), reg("DisplayVersion")),
+ Row::Info(t!("Сборка", "Build").into(), reg("CurrentBuild")),
+ ],
+ },
+ ]
+}
+
+/// `a` -> `b` by `t` (0..1), per channel.
+fn mix(a: u32, b: u32, t: f32) -> u32 {
+ let ch = |s: u32| ((a >> s & 255) as f32 * (1.0 - t) + (b >> s & 255) as f32 * t) as u32;
+ ch(0) | ch(8) << 8 | ch(16) << 16
+}
+
+/// The colours of the shared WinRust style (the topbar gear menu picks it), derived once per paint: quiet surfaces a few
+/// percent lighter than the background, hairline separators, one accent.
+struct Theme {
+ bg: u32,
+ side: u32,
+ card: u32,
+ sep: u32,
+ hover: u32,
+ sel: u32,
+ accent: u32,
+ fg: u32,
+ dim: u32,
+ off: u32,
+ square: bool,
+}
+
+fn theme() -> Theme {
+ let p = winrust_common::style::pal();
+ let up = |t: f32| mix(p.bg, p.text, t);
+ let card = winrust_common::style::card();
+ Theme { bg: p.bg, side: up(0.03), card, sep: up(0.1), hover: mix(card, p.text, 0.045), sel: up(0.1), accent: p.accent, fg: p.text, dim: p.dim, off: up(0.2), square: winrust_common::style::style().square() }
+}
+
+use winrust_common::style::rgb;
+
+/// Icon and tile colour of each page, in the order of `pages()` (the coloured squares of macOS' System Settings).
+const ICONS: [(&str, u32); 9] = [
+ ("\u{E7F4}", rgb(10, 132, 255)),
+ ("\u{E767}", rgb(255, 55, 95)),
+ ("\u{E7E8}", rgb(48, 209, 88)),
+ ("\u{E774}", rgb(50, 173, 230)),
+ ("\u{E702}", rgb(0, 122, 255)),
+ ("\u{E71D}", rgb(255, 159, 10)),
+ ("\u{E895}", rgb(52, 199, 89)),
+ ("\u{E771}", rgb(191, 90, 242)),
+ ("\u{E946}", rgb(142, 142, 147)),
+];
+
+/// Fills `r`; `d` is the corner diameter (0 = square corners). Rounded shapes go through GDI+ for smooth edges;
+/// a GDI+ graphics per call keeps the order with the GDI text in between and follows the DC's clip.
+unsafe fn shape(dc: HDC, r: RECT, color: u32, d: i32) {
+ use windows_sys::Win32::Graphics::GdiPlus::*;
+ unsafe {
+ if r.right <= r.left || r.bottom <= r.top {
+ return;
+ }
+ if d <= 0 {
+ let b = CreateSolidBrush(color);
+ FillRect(dc, &r, b);
+ DeleteObject(b as _);
+ return;
+ }
+ let mut g = null_mut();
+ if GdipCreateFromHDC(dc, &mut g) != Ok {
+ return;
+ }
+ GdipSetSmoothingMode(g, SmoothingModeAntiAlias);
+ GdipSetPixelOffsetMode(g, PixelOffsetModeHalf);
+ let (x, y, w, h) = (r.left as f32, r.top as f32, (r.right - r.left) as f32, (r.bottom - r.top) as f32);
+ let d = (d as f32).min(w).min(h);
+ let mut path = 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 = null_mut();
+ GdipCreateSolidFill(0xFF00_0000 | (color & 255) << 16 | (color >> 8 & 255) << 8 | (color >> 16 & 255), &mut br);
+ GdipFillPath(g, br as *mut GpBrush, path);
+ GdipDeleteBrush(br as *mut GpBrush);
+ GdipDeletePath(path);
+ GdipDeleteGraphics(g);
+ }
+}
+
+unsafe fn text(dc: HDC, font: isize, s: &str, mut r: RECT, color: u32, flags: u32) {
+ unsafe {
+ SelectObject(dc, font as _);
+ SetBkMode(dc, TRANSPARENT as _);
+ SetTextColor(dc, color);
+ DrawTextW(dc, wide(s).as_ptr(), -1, &mut r, flags | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS);
+ }
+}
+
+/// Width of one line of `s` in `font` (device px).
+unsafe fn text_width(dc: HDC, font: isize, s: &str) -> i32 {
+ unsafe {
+ SelectObject(dc, font as _);
+ let mut r = RECT { left: 0, top: 0, right: 0, bottom: 0 };
+ DrawTextW(dc, wide(s).as_ptr(), -1, &mut r, DT_CALCRECT | DT_SINGLELINE | DT_NOPREFIX);
+ r.right
+ }
+}
+
+const SIDE: i32 = 248;
+const ROW_H: i32 = 52;
+const ROWS_TOP: i32 = 84;
+const NAV_TOP: i32 = 14;
+const NAV_H: i32 = 40;
+const COL_MAX: i32 = 760;
+
+/// Left and right edge of the content column (device px): at most `COL_MAX` wide, centred in the space beside the sidebar.
+fn col(cw: i32, dpi: i32) -> (i32, i32) {
+ let p = |v: i32| v * dpi / 96;
+ let avail = cw - p(SIDE);
+ let w = (avail - p(64)).min(p(COL_MAX)).max(p(200));
+ let l = p(SIDE) + ((avail - w) / 2).max(p(16));
+ (l, l + w)
+}
+
+/// Left and right end of the volume slider's bar for a client width `cw`.
+fn track(cw: i32, dpi: i32) -> (i32, i32) {
+ let p = |v: i32| v * dpi / 96;
+ let (_, r) = col(cw, dpi);
+ (r - p(18 + 220), r - p(18))
+}
+
+/// The volume (0..=1) a click or drag at `x` means.
+fn slider_value(x: i32, l: i32, r: i32) -> f32 {
+ (((x - l) as f32 / (r - l).max(1) as f32).clamp(0.0, 1.0) * 100.0).round() / 100.0
+}
+
+/// Desktop pixels <-> device pixels of the arrangement picture.
+struct Map {
+ s: f32,
+ cx: f32,
+ cy: f32,
+ ox: f32,
+ oy: f32,
+}
+
+impl Map {
+ fn dev(&self, x: i32, y: i32) -> (i32, i32) {
+ ((self.ox + (x as f32 - self.cx) * self.s) as i32, (self.oy + (y as f32 - self.cy) * self.s) as i32)
+ }
+ fn desk(&self, x: i32, y: i32) -> (i32, i32) {
+ (((x as f32 - self.ox) / self.s + self.cx) as i32, ((y as f32 - self.oy) / self.s + self.cy) as i32)
+ }
+}
+
+/// Fits the displays into `bx`, with room around them to drag a display to the other side.
+fn arr_map(mons: &[display::Mon], bx: RECT) -> Map {
+ let l = mons.iter().map(|m| m.x).min().unwrap_or(0);
+ let t = mons.iter().map(|m| m.y).min().unwrap_or(0);
+ let r = mons.iter().map(|m| m.x + m.w).max().unwrap_or(1);
+ let b = mons.iter().map(|m| m.y + m.h).max().unwrap_or(1);
+ let (w, h) = (((r - l) as f32 * 1.8).max(1.0), ((b - t) as f32 * 1.8).max(1.0));
+ let s = ((bx.right - bx.left) as f32 / w).min((bx.bottom - bx.top) as f32 / h).max(0.0001);
+ Map { s, cx: (l + r) as f32 / 2.0, cy: (t + b) as f32 / 2.0, ox: (bx.left + bx.right) as f32 / 2.0, oy: (bx.top + bx.bottom) as f32 / 2.0 }
+}
+
+/// The picture's rectangle on screen (device px), from the page's first arrangement slot.
+fn arr_box(a: &App, cw: i32) -> Option<RECT> {
+ let p = |v: i32| (v as f64 * (a.dpi as f64 / 96.0)) as i32;
+ let i = a.pages.get(a.page)?.rows.iter().position(|r| matches!(r, Row::Arrange(0)))?;
+ let (cl, cr) = col(cw, a.dpi);
+ let top = p(ROWS_TOP + ROW_H * i as i32 - a.scroll);
+ Some(RECT { left: cl + p(16), top: top + p(10), right: cr - p(16), bottom: top + p(ROW_H * 4) - p(10) })
+}
+
+/// The most the rows of `rows` rows can be scrolled in a client area `ch` px high (logical px).
+fn max_scroll(rows: usize, ch: i32) -> i32 {
+ (ROWS_TOP + ROW_H * rows as i32 + 24 - ch).max(0)
+}
+
+/// Paints the title bar and border in the style's colours (Windows 11; older Windows ignores the calls and keeps its own).
+unsafe fn frame(hwnd: HWND) {
+ let t = theme();
+ let set = |attr: u32, v: u32| unsafe { windows_sys::Win32::Graphics::Dwm::DwmSetWindowAttribute(hwnd, attr, &v as *const u32 as _, 4) };
+ set(20, !winrust_common::style::style().light() as u32); // dark caption buttons, except on the light style
+ set(35, t.side); // caption colour: one surface with the sidebar
+ set(36, t.fg); // caption text
+ set(34, t.sep); // border
+ set(33, if t.square { 1 } else { 2 }); // corners: square / round
+}
+
+/// (Re)creates the fonts when the style's face (Segoe UI Variable / Consolas) differs from the one in use.
+/// 0 body, 1 page title, 2 icons, 3 small text, 4 section headers, 5 small icons.
+fn refresh_fonts() {
+ let mono = winrust_common::style::style().mono();
+ APP.with_borrow_mut(|a| {
+ if a.fonts[0] != 0 && a.mono == mono {
+ return;
+ }
+ let font = |h: f32, w: i32, face: &str| unsafe { CreateFontW(-((h * a.dpi as f32 / 96.0).round() as i32), 0, 0, 0, w, 0, 0, 0, 1, 0, 0, 5, 0, wide(face).as_ptr()) as isize };
+ let (face, icons) = (winrust_common::style::ui_face(), winrust_common::style::icon_face());
+ let new = [font(14.5, 400, face), font(28.0, 600, face), font(16.0, 400, icons), font(12.0, 400, face), font(12.5, 600, face), font(13.0, 400, icons)];
+ for f in a.fonts.into_iter().filter(|&f| f != 0) {
+ unsafe { DeleteObject(f as _) };
+ }
+ (a.fonts, a.mono) = (new, mono);
+ });
+}
+
+unsafe fn paint(hwnd: HWND) {
+ unsafe {
+ refresh_fonts();
+ 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, bmp) = (CreateCompatibleDC(dc), CreateCompatibleBitmap(dc, cw, ch));
+ let old = SelectObject(mem, bmp);
+ let t = theme();
+ APP.with_borrow(|a| {
+ let p = |v: i32| (v as f64 * (a.dpi as f64 / 96.0)) as i32;
+ let rd = |v: i32| if t.square { 0 } else { p(v) };
+ let inset = |r: RECT, n: i32| RECT { left: r.left + n, top: r.top + n, right: r.right - n, bottom: r.bottom - n };
+ let [body, title, icon, small, section, icon_s] = a.fonts;
+ // a switch at the right end of `inner`: None is drawn disabled
+ let switch = |inner: RECT, r: RECT, on: Option<bool>| {
+ let (w, h) = (p(42), p(24));
+ let (l, tp) = (inner.right - w, r.top + (r.bottom - r.top - h) / 2);
+ let lit = on == Some(true);
+ let track = if lit { t.accent } else if on.is_none() { mix(t.card, t.off, 0.5) } else { t.off };
+ shape(mem, RECT { left: l, top: tp, right: l + w, bottom: tp + h }, track, rd(h));
+ let k = h - p(4);
+ let kx = if lit { l + w - k - p(2) } else { l + p(2) };
+ shape(mem, RECT { left: kx, top: tp + p(2), right: kx + k, bottom: tp + p(2) + k }, if on.is_none() { mix(t.fg, t.card, 0.5) } else { rgb(255, 255, 255) }, rd(k));
+ };
+ shape(mem, rc, t.bg, 0);
+ // sidebar: one surface with the title bar, a hairline to the content
+ winrust_common::style::backdrop(mem, RECT { left: p(SIDE), ..rc }, a.dpi as f32 / 96.0);
+ shape(mem, RECT { left: 0, top: 0, right: p(SIDE), bottom: ch }, t.side, 0);
+ shape(mem, RECT { left: p(SIDE), top: 0, right: p(SIDE) + 1, bottom: ch }, t.sep, 0);
+ for (i, pg) in a.pages.iter().enumerate() {
+ let r = RECT { left: p(10), top: p(NAV_TOP + NAV_H * i as i32), right: p(SIDE - 10), bottom: p(NAV_TOP + NAV_H * (i as i32 + 1) - 2) };
+ let sel = i == a.page;
+ if sel {
+ shape(mem, r, t.sel, rd(8));
+ }
+ let (glyph, tile) = ICONS.get(i).copied().unwrap_or(("", t.dim));
+ let s = p(26);
+ let tr = RECT { left: r.left + p(8), top: (r.top + r.bottom - s) / 2, right: r.left + p(8) + s, bottom: (r.top + r.bottom + s) / 2 };
+ if t.square {
+ text(mem, icon_s, glyph, tr, if sel { t.accent } else { t.dim }, DT_CENTER);
+ } else {
+ shape(mem, tr, tile, p(14));
+ text(mem, icon_s, glyph, tr, rgb(255, 255, 255), DT_CENTER);
+ }
+ text(mem, body, &pg.title, RECT { left: tr.right + p(12), ..r }, if sel { t.fg } else { mix(t.dim, t.fg, 0.55) }, DT_LEFT);
+ }
+ let Some(pg) = a.pages.get(a.page) else { return };
+ let (cl, cr) = col(cw, a.dpi);
+ text(mem, title, &pg.title, RECT { left: cl + p(4), top: p(18), right: cr, bottom: p(70) }, t.fg, DT_LEFT);
+ // rows scroll under the title: nothing is drawn above their top edge
+ let saved = SaveDC(mem);
+ IntersectClipRect(mem, p(SIDE) + 1, p(ROWS_TOP - 8), cw, ch);
+ let scroll = a.scroll.min(max_scroll(pg.rows.len(), ch * 96 / a.dpi.max(1)));
+ let n = pg.rows.len();
+ let is_head = |i: usize| matches!(pg.rows.get(i), Some(Row::Header(_)));
+ for (i, row) in pg.rows.iter().enumerate() {
+ let y = p(ROWS_TOP + ROW_H * i as i32 - scroll);
+ let r = RECT { left: cl, top: y, right: cr, bottom: y + p(ROW_H) };
+ if r.bottom < 0 || r.top > ch {
+ continue;
+ }
+ if let Row::Header(s) = row {
+ text(mem, section, s, RECT { left: cl + p(16), top: r.bottom - p(30), right: cr, bottom: r.bottom - p(8) }, t.dim, DT_LEFT);
+ continue;
+ }
+ // grouped card: rounded at the top of a group and at its bottom, hairlines between its rows
+ let (first, last) = (i == 0 || is_head(i - 1), i + 1 == n || is_head(i + 1));
+ // each row paints only its own slot: a rounded half where the group starts or ends, a square half elsewhere
+ let (rad, mid) = (rd(12), (r.top + r.bottom) / 2);
+ shape(mem, RECT { bottom: mid + 1, ..r }, t.card, if first { rad * 2 } else { 0 });
+ shape(mem, RECT { top: mid, ..r }, t.card, if last { rad * 2 } else { 0 });
+ if first {
+ shape(mem, RECT { top: r.top + rad, bottom: mid + 1, ..r }, t.card, 0); // squares the bottom corners of the top half
+ }
+ if last {
+ shape(mem, RECT { top: mid, bottom: r.bottom - rad, ..r }, t.card, 0);
+ }
+ if !first {
+ shape(mem, RECT { left: r.left + p(16), top: r.top, right: r.right - p(16), bottom: r.top + 1 }, t.sep, 0);
+ }
+ if a.hover == Some(i) {
+ shape(mem, inset(r, p(4)), t.hover, rd(9) * 2);
+ }
+ let inner = RECT { left: r.left + p(16), right: r.right - p(16), ..r };
+ match row {
+ Row::Header(_) => {}
+ Row::Toggle { label, key, name, on_when, default } => {
+ text(mem, body, label, inner, t.fg, DT_LEFT);
+ switch(inner, r, Some(is_on(sys::dword(HKEY_CURRENT_USER, key, name), *on_when, *default)));
+ }
+ Row::Switch(label, value, _) => {
+ let v = value();
+ text(mem, body, label, inner, if v.is_some() { t.fg } else { t.dim }, DT_LEFT);
+ switch(inner, r, v);
+ }
+ Row::Info(label, value) => {
+ // the label keeps what it needs (up to half the row), the value gets the rest
+ let lw = text_width(mem, body, label).min((inner.right - inner.left) / 2);
+ text(mem, body, label, RECT { right: inner.left + lw, ..inner }, t.fg, DT_LEFT);
+ text(mem, body, value, RECT { left: inner.left + lw + p(16), ..inner }, t.dim, DT_RIGHT);
+ }
+ Row::Cycle(label, value, op) => {
+ text(mem, body, label, inner, if matches!(op, Op::Hidden) { t.accent } else { t.fg }, DT_LEFT);
+ let chev = !matches!(op, Op::Nop | Op::Hidden) && (listed(*op) || !matches!(op, Op::Topology));
+ let vr = RECT { right: inner.right - if chev { p(22) } else { 0 }, ..inner };
+ let open = a.pick.as_ref().is_some_and(|pk| pk.row == i);
+ text(mem, body, &value(), vr, if open { t.accent } else { t.dim }, DT_RIGHT);
+ if chev {
+ // a list opens (chevron down, up while open); other rows act on a click
+ let g = if !listed(*op) { "\u{E76C}" } else if open { "\u{E70E}" } else { "\u{E70D}" };
+ text(mem, icon_s, g, inner, if open { t.accent } else { t.dim }, DT_RIGHT);
+ }
+ }
+ Row::Adapter(ad, open) => {
+ let lit = ad.up && ad.internet != Some(false);
+ let glyph = if ad.wifi { "\u{E701}" } else { "\u{E839}" };
+ text(mem, icon, glyph, RECT { right: inner.left + p(22), ..inner }, if lit { t.accent } else { t.dim }, DT_CENTER);
+ let tl = inner.left + p(34);
+ let st = ad.status();
+ let sw = text_width(mem, small, &st);
+ let right = inner.right - p(22) - sw - p(18);
+ text(mem, body, &ad.name, RECT { left: tl, top: r.top + p(7), right, bottom: r.top + p(29) }, t.fg, DT_LEFT);
+ text(mem, small, &ad.summary(), RECT { left: tl, top: r.top + p(27), right, bottom: r.bottom - p(7) }, t.dim, DT_LEFT);
+ let sr = RECT { right: inner.right - p(22), ..inner };
+ text(mem, small, &st, sr, t.dim, DT_RIGHT);
+ let dot = p(7);
+ let (dx, cy) = (sr.right - sw - p(8) - dot, (r.top + r.bottom) / 2);
+ let dc = match (ad.up, ad.internet) {
+ (false, _) => t.off,
+ (_, Some(true)) => winrust_common::style::GOOD,
+ (_, Some(false)) => winrust_common::style::WARN,
+ _ => t.accent,
+ };
+ shape(mem, RECT { left: dx, top: cy - dot / 2, right: dx + dot, bottom: cy - dot / 2 + dot }, dc, rd(dot));
+ text(mem, icon_s, if *open { "\u{E70D}" } else { "\u{E76C}" }, inner, t.dim, DT_RIGHT);
+ }
+ Row::Wifi(nw, note) => {
+ let busy = a.connecting.as_ref().is_some_and(|c| c.0 == nw.ssid);
+ // signal: four rising bars, the lit ones in the text colour (accent when connected)
+ let (bw, gap, bh) = (p(3), p(2), p(14));
+ let (bx, by) = (inner.left + p(2), (r.top + r.bottom + bh) / 2);
+ for k in 0..4 {
+ let h = bh * (k + 1) / 4;
+ let lit = (k as u32) < bars(nw.quality);
+ let c = if !lit { t.off } else if nw.connected { t.accent } else { t.fg };
+ let x = bx + k * (bw + gap);
+ shape(mem, RECT { left: x, top: by - h, right: x + bw, bottom: by }, c, rd(2));
+ }
+ let tl = inner.left + p(34);
+ text(mem, body, &nw.ssid, RECT { left: tl, top: r.top + p(7), right: inner.right - p(52), bottom: r.top + p(29) }, t.fg, DT_LEFT);
+ let sub = if busy { t!("Подключение…", "Connecting…").into() } else { note.clone() };
+ text(mem, small, &sub, RECT { left: tl, top: r.top + p(27), right: inner.right - p(52), bottom: r.bottom - p(7) }, if busy || nw.connected { t.accent } else { t.dim }, DT_LEFT);
+ if nw.connected {
+ text(mem, icon_s, "\u{E73E}", inner, t.accent, DT_RIGHT);
+ } else if nw.sec.is_none_or(|s| s.needs_key()) && nw.profile.is_none() {
+ text(mem, icon_s, "\u{E72E}", inner, t.dim, DT_RIGHT);
+ }
+ }
+ Row::Item(label, value, cmd) => {
+ let armed = a.armed.as_deref() == Some(label.as_str());
+ let lw = text_width(mem, body, label).min((inner.right - inner.left) * 3 / 5);
+ text(mem, body, label, RECT { right: inner.left + lw, ..inner }, if armed { winrust_common::style::BAD } else { t.fg }, DT_LEFT);
+ let value = if armed { t!("Нажмите ещё раз", "Click again").to_string() } else { value.clone() };
+ let ink = if armed { winrust_common::style::BAD } else if matches!(cmd, Cmd::Vpn(v) if v.on) || value == t!("Подключено", "Connected") { t.accent } else { t.dim };
+ text(mem, body, &value, RECT { left: inner.left + lw + p(16), right: inner.right - p(22), ..inner }, ink, DT_RIGHT);
+ text(mem, icon_s, "\u{E76C}", inner, t.dim, DT_RIGHT);
+ }
+ Row::Arrange(k) => {
+ // the whole picture is drawn in every slot, clipped to it: scrolling shows the right part of it
+ let top = r.top - p(ROW_H * *k as i32);
+ let bx = RECT { left: r.left + p(16), top: top + p(10), right: r.right - p(16), bottom: top + p(ROW_H * 4) - p(10) };
+ let sv = SaveDC(mem);
+ IntersectClipRect(mem, r.left, r.top, r.right, r.bottom);
+ shape(mem, RECT { left: r.left, top, right: r.right, bottom: top + p(ROW_H * 4) }, t.card, 0);
+ let map = arr_map(&a.layout, bx);
+ let sel = display::selected_index();
+ for (j, m) in a.layout.iter().enumerate() {
+ let (x, y) = match &a.arr {
+ Some(d) if d.idx == j => d.cur,
+ _ => (m.x, m.y),
+ };
+ let (x0, y0) = map.dev(x, y);
+ let (x1, y1) = map.dev(x + m.w, y + m.h);
+ let mr = RECT { left: x0, top: y0, right: x1, bottom: y1 };
+ let dragging = a.arr.as_ref().is_some_and(|d| d.idx == j);
+ shape(mem, mr, if j == sel { t.accent } else { t.off }, rd(6));
+ shape(mem, inset(mr, p(2)), if j == sel { mix(t.accent, t.bg, if dragging { 0.0 } else { 0.25 }) } else { mix(t.card, t.fg, 0.1) }, rd(5));
+ text(mem, title, &(j + 1).to_string(), mr, if j == sel { rgb(255, 255, 255) } else { t.fg }, DT_CENTER);
+ if m.primary {
+ shape(mem, RECT { left: x0 + (x1 - x0) / 2 - p(14), top: y1 - p(10), right: x0 + (x1 - x0) / 2 + p(14), bottom: y1 - p(6) }, if j == sel { rgb(255, 255, 255) } else { t.dim }, rd(4));
+ }
+ }
+ RestoreDC(mem, sv);
+ }
+ Row::Slider(label, src) => {
+ text(mem, body, label, inner, t.fg, DT_LEFT);
+ let (l, rt) = track(cw, a.dpi);
+ let v = audio::volume(*src);
+ let (cy, h) = ((r.top + r.bottom) / 2, p(4));
+ shape(mem, RECT { left: l, top: cy - h / 2, right: rt, bottom: cy + h / 2 }, t.off, rd(h));
+ let x = l + ((rt - l) as f32 * v.unwrap_or(0.0)) as i32;
+ shape(mem, RECT { left: l, top: cy - h / 2, right: x, bottom: cy + h / 2 }, t.accent, rd(h));
+ if v.is_some() {
+ shape(mem, RECT { left: x - p(11), top: cy - p(11), right: x + p(11), bottom: cy + p(11) }, t.sep, rd(22));
+ shape(mem, RECT { left: x - p(10), top: cy - p(10), right: x + p(10), bottom: cy + p(10) }, rgb(255, 255, 255), rd(20));
+ }
+ let pct = v.map_or("—".into(), |v| format!("{}%", (v * 100.0).round() as u32));
+ text(mem, body, &pct, RECT { right: l - p(16), ..inner }, t.dim, DT_RIGHT);
+ }
+ }
+ }
+ RestoreDC(mem, saved);
+ // the floating bar at the bottom: a display change to confirm, a prompt, or a Wi-Fi message
+ let (r, e) = bar(cw, ch, a.dpi);
+ let rad = rd(14) * 2;
+ if a.pending > 0 {
+ shape(mem, r, t.accent, rad);
+ let msg = tf!("Оставить этот режим? Enter: оставить, Esc или {} с: вернуть", "Keep this mode? Enter keeps it, Esc or {} s goes back", a.pending);
+ text(mem, body, &msg, RECT { left: r.left + p(18), right: r.right - p(18), ..r }, rgb(255, 255, 255), DT_LEFT);
+ } else if let Some(pr) = &a.prompt {
+ shape(mem, r, t.sep, rad);
+ shape(mem, inset(r, 1), t.card, rad);
+ shape(mem, inset(e, -p(2)), t.accent, rd(8) * 2);
+ shape(mem, e, t.bg, rd(6) * 2);
+ let ask = match pr {
+ Prompt::Ssid => t!("Имя скрытой сети", "Hidden network name").into(),
+ Prompt::Proxy(false) => t!("Прокси: адрес:порт (пусто: убрать)", "Proxy: host:port (empty: remove)").into(),
+ Prompt::Proxy(true) => t!("Адрес скрипта PAC (пусто: убрать)", "PAC script address (empty: remove)").into(),
+ Prompt::EapUser(n) => tf!("Имя пользователя для «{}» (домен\\имя)", "User name for \"{}\" (domain\\name)", n.ssid),
+ Prompt::EapPass(n, _) => tf!("Пароль «{}»", "Password for \"{}\"", n.ssid),
+ Prompt::Key(n, true) => tf!("Пароль «{}» (пусто: открытая)", "Password for \"{}\" (empty: open)", n.ssid),
+ Prompt::Key(n, false) => tf!("Пароль «{}»", "Password for \"{}\"", n.ssid),
+ };
+ let label = a.msg.clone().unwrap_or(ask);
+ text(mem, body, &label, RECT { left: r.left + p(18), right: e.left - p(14), ..r }, if a.msg.is_some() { winrust_common::style::BAD } else { t.fg }, DT_LEFT);
+ } else if let Some(m) = &a.msg {
+ shape(mem, r, t.sep, rad);
+ shape(mem, inset(r, 1), t.card, rad);
+ let dot = p(8);
+ let cy = (r.top + r.bottom) / 2;
+ shape(mem, RECT { left: r.left + p(18), top: cy - dot / 2, right: r.left + p(18) + dot, bottom: cy + dot / 2 }, if a.connecting.is_some() { t.accent } else { t.dim }, rd(dot));
+ text(mem, body, m, RECT { left: r.left + p(36), right: r.right - p(18), ..r }, t.fg, DT_LEFT);
+ }
+ // the open drop-down list: unfolds away from its row, items fade in, the current value has a check mark
+ if let (Some((pr, n, down)), Some(pk)) = (pick_geom(a, cw, ch), a.pick.as_ref()) {
+ let k = (pk.t0.elapsed().as_secs_f32() / 0.18).min(1.0);
+ let k = k * k * (3.0 - 2.0 * k);
+ let hh = ((pr.bottom - pr.top) as f32 * (0.35 + 0.65 * k)) as i32;
+ let r = if down { RECT { bottom: pr.top + hh, ..pr } } else { RECT { top: pr.bottom - hh, ..pr } };
+ let rad = rd(12) * 2;
+ let light = winrust_common::style::style().light();
+ shape(mem, RECT { left: r.left - p(2), top: r.top + p(4), right: r.right + p(2), bottom: r.bottom + p(10) }, mix(t.bg, 0, if light { 0.08 } else { 0.35 }), rad + p(8));
+ shape(mem, r, t.sep, rad);
+ shape(mem, inset(r, 1), t.card, rad);
+ let saved = SaveDC(mem);
+ IntersectClipRect(mem, r.left, r.top + p(2), r.right, r.bottom - p(2));
+ let off = if down { 0 } else { r.top - pr.top }; // unfolding upward: the items ride with the top edge
+ for j in 0..n {
+ let idx = pk.top + j;
+ let ir = RECT { left: pr.left + p(6), top: pr.top + off + p(6 + PICK_ROW * j as i32), right: pr.right - p(6), bottom: pr.top + off + p(6 + PICK_ROW * (j as i32 + 1)) };
+ let ink = |c: u32| mix(t.card, c, k);
+ if pk.hover == Some(idx) {
+ shape(mem, ir, ink(t.hover), rd(8) * 2);
+ }
+ let sel = pk.cur == Some(idx);
+ text(mem, body, &pk.items[idx], RECT { left: ir.left + p(12), right: ir.right - p(36), ..ir }, ink(if sel { t.accent } else { t.fg }), DT_LEFT);
+ if sel {
+ text(mem, icon_s, "\u{E73E}", RECT { right: ir.right - p(12), ..ir }, ink(t.accent), DT_RIGHT);
+ }
+ }
+ // a thin scroll thumb when not everything fits
+ let total = pk.items.len();
+ if total > n {
+ let (th, tt) = (r.bottom - r.top - p(16), r.top + p(8));
+ let (a0, a1) = (tt + th * pk.top as i32 / total as i32, tt + th * (pk.top + n) as i32 / total as i32);
+ shape(mem, RECT { left: r.right - p(6), top: a0, right: r.right - p(3), bottom: a1 }, mix(t.card, t.dim, 0.6 * k), rd(3) * 2);
+ }
+ RestoreDC(mem, saved);
+ }
+ });
+ BitBlt(dc, 0, 0, cw, ch, mem, 0, 0, SRCCOPY);
+ SelectObject(mem, old);
+ DeleteObject(bmp as _);
+ DeleteDC(mem);
+ EndPaint(hwnd, &ps);
+ }
+}
+
+enum Act {
+ Page(usize),
+ Flip(&'static str, &'static str, u32),
+ Do(Op),
+ Pick(Op, usize), // open the list of values of the row at this index
+ Volume(f32, audio::Src),
+ Cmd(Cmd),
+ Arr(i32, i32),
+ Wifi(wifi::Net),
+ Adapter(String),
+}
+
+/// The row under client y (device px), None above the rows or past the last one.
+fn row_at_scrolled(a: &App, y: i32) -> Option<usize> {
+ let p = |v: i32| (v as f64 * (a.dpi as f64 / 96.0)) as i32;
+ if y < p(ROWS_TOP - 8) {
+ return None;
+ }
+ let rows = &a.pages.get(a.page)?.rows;
+ row_at(y + p(a.scroll), p(ROWS_TOP), p(ROW_H), rows.len())
+}
+
+fn click(x: i32, y: i32, cw: i32) -> Option<Act> {
+ APP.with_borrow(|a| {
+ let p = |v: i32| (v as f64 * (a.dpi as f64 / 96.0)) as i32;
+ if x < p(SIDE) {
+ return row_at(y, p(NAV_TOP), p(NAV_H), a.pages.len()).map(Act::Page);
+ }
+ let rows = &a.pages.get(a.page)?.rows;
+ match rows.get(row_at_scrolled(a, y)?)? {
+ Row::Cycle(_, _, op) if listed(*op) => Some(Act::Pick(*op, row_at_scrolled(a, y)?)),
+ Row::Cycle(_, _, op) => Some(Act::Do(*op)),
+ Row::Slider(_, src) => {
+ let (l, r) = track(cw, a.dpi);
+ (x >= l - p(12) && x <= r + p(12)).then(|| Act::Volume(slider_value(x, l, r), *src))
+ }
+ Row::Item(_, _, cmd) => Some(Act::Cmd(cmd.clone())),
+ Row::Arrange(_) => Some(Act::Arr(x, y)),
+ Row::Toggle { key, name, on_when, default, .. } => {
+ let on = is_on(sys::dword(HKEY_CURRENT_USER, key, name), *on_when, *default);
+ Some(Act::Flip(key, name, if on { 1 - on_when } else { *on_when }))
+ }
+ Row::Wifi(n, _) => Some(Act::Wifi(n.clone())),
+ Row::Adapter(ad, _) => Some(Act::Adapter(ad.name.clone())),
+ Row::Switch(_, _, op) => Some(Act::Do(*op)),
+ Row::Info(..) | Row::Header(_) => None,
+ }
+ })
+}
+
+/// Ends the confirmation of a display change: `keep` saves the mode, otherwise the saved one comes back.
+unsafe fn finish_confirm(hwnd: HWND, keep: bool) {
+ unsafe {
+ KillTimer(hwnd, 1);
+ APP.with_borrow_mut(|a| a.pending = 0);
+ match (keep, display::current()) {
+ (true, Some(m)) => {
+ display::apply(m, true);
+ }
+ _ => display::revert(),
+ }
+ InvalidateRect(hwnd, null(), 0);
+ }
+}
+
+/// The rows that act on a click (the others open a list, see `choose`).
+unsafe fn display_or_mute(_hwnd: HWND, op: Op) {
+ match op {
+ Op::Mute => audio::set_mute(false, !audio::muted(false).unwrap_or(false)),
+ Op::MicMute => audio::set_mute(true, !audio::muted(true).unwrap_or(false)),
+ Op::Primary => drop(display::make_primary()),
+ Op::Hdr => {
+ if let Some(on) = display::hdr() {
+ display::set_hdr(!on);
+ }
+ }
+ Op::Bt => {
+ if let Some(on) = bt::state().bt {
+ bt::set_bluetooth(!on, ping);
+ }
+ }
+ Op::Air => {
+ if let Some(on) = bt::state().air {
+ bt::set_airplane(!on, ping);
+ }
+ }
+ Op::Proxy => unsafe { open_prompt(_hwnd, Prompt::Proxy(false)) },
+ Op::Pac => unsafe { open_prompt(_hwnd, Prompt::Proxy(true)) },
+ _ => {}
+ }
+}
+
+static MAIN: std::sync::atomic::AtomicIsize = std::sync::atomic::AtomicIsize::new(0);
+const WM_NOTE: u32 = 0x8000 + 3; // WM_APP + 3: lParam is a Box<String> for the bottom bar
+const WM_REFRESH: u32 = 0x8000 + 4; // WM_APP + 4: a thread finished, read the page again
+
+/// Asks the window (from any thread) to read the page again.
+fn ping() {
+ unsafe { PostMessageW(MAIN.load(std::sync::atomic::Ordering::Relaxed) as HWND, WM_REFRESH, 0, 0) };
+}
+
+/// Shows `s` in the bottom bar and reads the page again (from any thread).
+fn note(s: String) {
+ let b = Box::into_raw(Box::new(s));
+ if unsafe { PostMessageW(MAIN.load(std::sync::atomic::Ordering::Relaxed) as HWND, WM_NOTE, 0, b as isize) } == 0 {
+ drop(unsafe { Box::from_raw(b) });
+ }
+}
+
+/// Reads the rows of the page on screen again (not while a list is open or something is being dragged). The rows are read
+/// outside the borrow of the state: the Win32/COM calls that read them can run the window procedure (STA message pumping).
+unsafe fn refresh_page(hwnd: HWND) {
+ unsafe {
+ let (page, busy, mut apps) = APP.with_borrow_mut(|a| (a.page, a.pick.is_some() || a.drag.is_some() || a.arr.is_some(), a.apps.take()));
+ let (rows, layout) = if busy { (None, None) } else { (dynamic(page, &mut apps), (page == 0).then(display::layout)) };
+ APP.with_borrow_mut(|a| {
+ a.apps = apps;
+ if let Some(l) = layout {
+ a.layout = l;
+ }
+ if let Some(rows) = rows {
+ if let Some(p) = a.pages.get_mut(page) {
+ p.rows = rows;
+ }
+ a.hover = a.hover.filter(|&i| a.pages.get(a.page).is_some_and(|p| i < p.rows.len()));
+ }
+ });
+ clamp_scroll(hwnd, 0);
+ InvalidateRect(hwnd, null(), 0);
+ }
+}
+
+/// Opens page `i` (the pages that change by themselves are read fresh).
+unsafe fn goto(hwnd: HWND, i: usize) {
+ unsafe {
+ close_prompt(hwnd);
+ APP.with_borrow_mut(|a| {
+ (a.pick, a.armed) = (None, None);
+ (a.page, a.scroll, a.hover) = (i, 0, None);
+ if i == APPS_PAGE {
+ a.apps = None; // read the programs again
+ }
+ });
+ match i {
+ NET_PAGE => wifi::scan(),
+ BT_PAGE => bt::refresh(ping),
+ 2 => {
+ if ext::TEMP_BYTES.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX {
+ ext::measure_temp(ping);
+ }
+ }
+ _ => {}
+ }
+ refresh_page(hwnd);
+ }
+}
+
+fn once_more(label: &str) -> bool {
+ APP.with_borrow_mut(|a| {
+ let again = a.armed.as_deref() == Some(label);
+ a.armed = if again { None } else { Some(label.to_string()) };
+ again
+ })
+}
+
+/// What a click on an `Item` row does.
+unsafe fn run_cmd(hwnd: HWND, label: &str, cmd: Cmd) {
+ unsafe {
+ let say = |m: String| APP.with_borrow_mut(|a| a.msg = Some(m));
+ match cmd {
+ // destructive ones need a second click on the same row
+ Cmd::Uninstall(c) => {
+ if once_more(label) {
+ say(if ext::uninstall(&c) { tf!("Запущено удаление «{}»", "Uninstalling \"{}\"", label) } else { tf!("Не удалось запустить удаление «{}»", "Could not start uninstalling \"{}\"", label) });
+ }
+ }
+ Cmd::BtUnpair(id) => {
+ if once_more(label) {
+ bt::unpair(id, ping);
+ }
+ }
+ c => {
+ APP.with_borrow_mut(|a| a.armed = None);
+ match c {
+ Cmd::Vpn(v) => {
+ let name = v.name.clone();
+ if v.on {
+ std::thread::spawn(move || {
+ ext::hang_up(&name);
+ note(tf!("VPN «{}» отключён", "VPN \"{}\" disconnected", name));
+ });
+ } else {
+ say(tf!("Подключение к «{}»…", "Connecting to \"{}\"…", name));
+ std::thread::spawn(move || note(ext::dial(&name, v.pbk.as_deref()).map_or_else(|e| e, |_| tf!("VPN «{}» подключён", "VPN \"{}\" connected", name))));
+ }
+ }
+ Cmd::CleanTemp => {
+ say(t!("Очистка…", "Cleaning…").into());
+ ext::clean_temp(note);
+ }
+ Cmd::EmptyBin => {
+ if ext::empty_bin(hwnd) {
+ say(t!("Корзина очищена", "Recycle Bin emptied").into());
+ }
+ }
+ Cmd::BtPair(id) => {
+ say(t!("Сопряжение…", "Pairing…").into());
+ bt::pair(id, ping);
+ }
+ Cmd::BtScan => {
+ bt::scan(ping);
+ ping();
+ }
+ Cmd::Check => {
+ wu::check(ping);
+ ping();
+ }
+ Cmd::Install => {
+ wu::install(ping);
+ ping();
+ }
+ Cmd::Uninstall(_) | Cmd::BtUnpair(_) => {}
+ }
+ }
+ }
+ refresh_page(hwnd);
+ }
+}
+
+/// Scrolls the rows by `by` logical px, keeping them inside their range (also after a resize).
+unsafe fn clamp_scroll(hwnd: HWND, by: i32) {
+ unsafe {
+ let mut rc: RECT = std::mem::zeroed();
+ GetClientRect(hwnd, &mut rc);
+ APP.with_borrow_mut(|a| {
+ let n = a.pages.get(a.page).map_or(0, |p| p.rows.len());
+ a.scroll = (a.scroll + by).clamp(0, max_scroll(n, rc.bottom * 96 / a.dpi.max(1)));
+ });
+ }
+}
+
+/// The floating bar at the bottom of the content column and, inside it, the text field of a prompt (device px).
+fn bar(cw: i32, ch: i32, dpi: i32) -> (RECT, RECT) {
+ let p = |v: i32| v * dpi / 96;
+ let (cl, cr) = col(cw, dpi);
+ let w = (cr - cl).min(p(620));
+ let l = cl + (cr - cl - w) / 2;
+ let r = RECT { left: l, top: ch - p(78), right: l + w, bottom: ch - p(24) };
+ let e = RECT { left: r.left + w * 11 / 20, top: r.top + p(12), right: r.right - p(12), bottom: r.bottom - p(12) };
+ (r, e)
+}
+
+const WM_EDIT_KEY: u32 = 0x8000 + 2; // WM_APP + 2: Enter or Esc in the prompt's field (wParam = the key)
+const EM_LIMITTEXT: u32 = 0xC5;
+const EM_SETSEL: u32 = 0xB1;
+const EM_SETMARGINS: u32 = 0xD3;
+static EDIT_PROC: std::sync::atomic::AtomicIsize = std::sync::atomic::AtomicIsize::new(0);
+
+/// The field's own procedure, which keeps Enter and Esc (a single-line edit only beeps at them) for the window.
+unsafe extern "system" fn edit_proc(h: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {
+ unsafe {
+ match msg {
+ WM_KEYDOWN if wp == VK_RETURN as usize || wp == VK_ESCAPE as usize => {
+ PostMessageW(GetParent(h), WM_EDIT_KEY, wp, 0); // posted: the field is destroyed there
+ 0
+ }
+ WM_CHAR if wp == 13 || wp == 27 => 0,
+ _ => CallWindowProcW(std::mem::transmute::<isize, WNDPROC>(EDIT_PROC.load(std::sync::atomic::Ordering::Relaxed)), h, msg, wp, lp),
+ }
+ }
+}
+
+unsafe fn close_prompt(hwnd: HWND) {
+ unsafe {
+ let ed = APP.with_borrow_mut(|a| {
+ a.prompt = None;
+ std::mem::take(&mut a.edit)
+ });
+ if ed != 0 {
+ SetWindowTextW(ed as HWND, wide("").as_ptr());
+ DestroyWindow(ed as HWND);
+ SetFocus(hwnd);
+ }
+ }
+}
+
+/// Shows the prompt with an empty text field (hidden characters for a password).
+unsafe fn open_prompt(hwnd: HWND, pr: Prompt) {
+ unsafe {
+ close_prompt(hwnd);
+ let key = matches!(pr, Prompt::Key(..) | Prompt::EapPass(..));
+ let limit = match pr {
+ Prompt::Ssid => 32,
+ Prompt::Proxy(_) => 300,
+ Prompt::EapUser(_) => 64,
+ _ => 128,
+ };
+ let mut rc: RECT = std::mem::zeroed();
+ GetClientRect(hwnd, &mut rc);
+ let (dpi, font) = APP.with_borrow(|a| (a.dpi, a.fonts[0]));
+ let (_, e) = bar(rc.right, rc.bottom, dpi);
+ let style = WS_CHILD | WS_VISIBLE | ES_AUTOHSCROLL as u32 | if key { ES_PASSWORD as u32 } else { 0 };
+ let ed = CreateWindowExW(0, wide("EDIT").as_ptr(), null(), style, e.left, e.top, e.right - e.left, e.bottom - e.top, hwnd, null_mut(), GetModuleHandleW(null()), null());
+ if ed.is_null() {
+ return;
+ }
+ SendMessageW(ed, WM_SETFONT, font as usize, 0);
+ SendMessageW(ed, EM_LIMITTEXT, limit, 0);
+ SendMessageW(ed, EM_SETMARGINS, 3, (6 * dpi / 96 * 0x10001) as isize); // left and right
+ EDIT_PROC.store(SetWindowLongPtrW(ed, GWLP_WNDPROC, edit_proc as *const () as isize), std::sync::atomic::Ordering::Relaxed);
+ SetFocus(ed);
+ APP.with_borrow_mut(|a| (a.prompt, a.edit, a.msg) = (Some(pr), ed as isize, None));
+ InvalidateRect(hwnd, null(), 0);
+ }
+}
+
+/// The field's text; the buffer it passed through is wiped (it may be a password).
+unsafe fn edit_text(ed: isize) -> String {
+ unsafe {
+ let mut buf = vec![0u16; 320];
+ let n = GetWindowTextW(ed as HWND, buf.as_mut_ptr(), buf.len() as i32).max(0) as usize;
+ let s = String::from_utf16_lossy(&buf[..n]);
+ buf.fill(0);
+ s
+ }
+}
+
+/// A connection was started: the bottom bar says so until its result comes (or 30 s pass).
+unsafe fn start_wait(hwnd: HWND, ssid: String, profile: String, new: bool) {
+ unsafe {
+ APP.with_borrow_mut(|a| {
+ a.msg = Some(tf!("Подключение к «{}»…", "Connecting to \"{}\"…", ssid));
+ a.connecting = Some((ssid, profile, new));
+ });
+ SetTimer(hwnd, 3, 30_000, None);
+ }
+}
+
+/// A new network: saves its profile and connects, or shows why not.
+unsafe fn add_network(hwnd: HWND, n: &wifi::Net, sec: wifi::Sec, key: &str, hidden: bool) -> bool {
+ unsafe {
+ match wifi::add_and_connect(&n.ssid, &n.raw, sec, key, hidden, Some(&n.iface)) {
+ Ok(p) => {
+ close_prompt(hwnd);
+ start_wait(hwnd, n.ssid.clone(), p, true);
+ true
+ }
+ Err(e) => {
+ APP.with_borrow_mut(|a| a.msg = Some(e));
+ false
+ }
+ }
+ }
+}
+
+/// Enter in the prompt: the hidden network's name leads to its password; a password saves the network and connects.
+unsafe fn submit_prompt(hwnd: HWND) {
+ unsafe {
+ let ed = APP.with_borrow(|a| a.edit);
+ let mut s = edit_text(ed);
+ match APP.with_borrow_mut(|a| a.prompt.take()) {
+ Some(Prompt::Ssid) if s.trim().is_empty() || s.len() > 32 => {
+ APP.with_borrow_mut(|a| (a.prompt, a.msg) = (Some(Prompt::Ssid), Some(t!("Имя сети: от 1 до 32 байт", "Network name: 1 to 32 bytes").into())));
+ }
+ Some(Prompt::Ssid) => {
+ let n = wifi::Net { raw: s.as_bytes().to_vec(), ssid: s.clone(), quality: 0, connected: false, profile: None, sec: Some(wifi::Sec::Wpa2 { tkip: false }), eap: None, iface: std::mem::zeroed() };
+ open_prompt(hwnd, Prompt::Key(n, true));
+ }
+ Some(Prompt::Proxy(pac)) => {
+ let v = s.trim().to_string();
+ if if pac { ext::valid_pac(&v) } else { ext::valid_proxy(&v) } {
+ ext::set_proxy(pac, &v);
+ close_prompt(hwnd);
+ refresh_page(hwnd);
+ } else {
+ APP.with_borrow_mut(|a| (a.prompt, a.msg) = (Some(Prompt::Proxy(pac)), Some(t!("Неверный адрес", "Not a valid address").into())));
+ }
+ }
+ Some(Prompt::EapUser(n)) if s.trim().is_empty() => APP.with_borrow_mut(|a| (a.prompt, a.msg) = (Some(Prompt::EapUser(n)), Some(t!("Введите имя пользователя", "Enter the user name").into()))),
+ Some(Prompt::EapUser(n)) => open_prompt(hwnd, Prompt::EapPass(n, s.trim().to_string())),
+ Some(Prompt::EapPass(n, user)) => match wifi::add_eap_and_connect(&n.ssid, &n.raw, n.eap.unwrap_or("WPA2"), &user, &s, false, Some(&n.iface)) {
+ Ok(profile) => {
+ close_prompt(hwnd);
+ start_wait(hwnd, n.ssid.clone(), profile, true);
+ }
+ Err(e) => {
+ APP.with_borrow_mut(|a| (a.prompt, a.msg) = (Some(Prompt::EapPass(n, user)), Some(e)));
+ SendMessageW(ed as HWND, EM_SETSEL, 0, -1);
+ }
+ },
+ Some(Prompt::Key(n, hidden)) => {
+ let sec = if hidden && s.is_empty() { wifi::Sec::Open } else { n.sec.unwrap_or(wifi::Sec::Wpa2 { tkip: false }) };
+ if !add_network(hwnd, &n, sec, &s, hidden) {
+ APP.with_borrow_mut(|a| a.prompt = Some(Prompt::Key(n, hidden)));
+ SendMessageW(ed as HWND, EM_SETSEL, 0, -1);
+ }
+ }
+ None => {}
+ }
+ s.as_bytes_mut().fill(0);
+ InvalidateRect(hwnd, null(), 0);
+ }
+}
+
+/// A click on a Wi-Fi network.
+unsafe fn wifi_click(hwnd: HWND, n: wifi::Net) {
+ unsafe {
+ close_prompt(hwnd);
+ match (&n.profile, n.sec) {
+ _ if n.connected => APP.with_borrow_mut(|a| a.msg = Some(t!("Отключить или забыть: правая кнопка мыши", "Disconnect or forget: right click").into())),
+ (Some(p), _) => {
+ if wifi::connect(p, &n.iface) {
+ start_wait(hwnd, n.ssid.clone(), p.clone(), false);
+ }
+ }
+ (None, Some(s)) if !s.needs_key() => drop(add_network(hwnd, &n, s, "", false)),
+ (None, Some(_)) => open_prompt(hwnd, Prompt::Key(n, false)),
+ (None, None) if n.eap.is_some() => open_prompt(hwnd, Prompt::EapUser(n)),
+ (None, None) => APP.with_borrow_mut(|a| a.msg = Some(t!("Эта сеть входит сертификатом: такие сети не поддерживаются", "This network signs in with a certificate: not supported").into())),
+ }
+ SetTimer(hwnd, 2, 1500, None); // look again soon: the list changes as the connection goes
+ }
+}
+
+/// Right click on a saved network: disconnect / connect, forget.
+unsafe fn wifi_menu(hwnd: HWND, x: i32, y: i32) {
+ unsafe {
+ let hit = APP.with_borrow(|a| {
+ (x >= a.dpi * SIDE / 96).then(|| row_at_scrolled(a, y)).flatten().and_then(|i| match a.pages.get(a.page)?.rows.get(i)? {
+ Row::Wifi(n, _) if n.profile.is_some() => Some(n.clone()),
+ _ => None,
+ })
+ });
+ let Some(n) = hit else { return };
+ let Some(profile) = n.profile.clone() else { return };
+ let (on, off, forget) = (wide(t!("Подключить", "Connect")), wide(t!("Отключить", "Disconnect")), wide(t!("Забыть сеть", "Forget network")));
+ let m = CreatePopupMenu();
+ AppendMenuW(m, MF_STRING, 1, if n.connected { off.as_ptr() } else { on.as_ptr() });
+ AppendMenuW(m, MF_STRING, 2, forget.as_ptr());
+ let mut pt = POINT { x, y };
+ ClientToScreen(hwnd, &mut pt);
+ let cmd = TrackPopupMenu(m, TPM_RETURNCMD | TPM_RIGHTBUTTON, pt.x, pt.y, 0, hwnd, null());
+ DestroyMenu(m);
+ match cmd {
+ 1 if n.connected => drop(wifi::disconnect()),
+ 1 => wifi_click(hwnd, n),
+ 2 => drop(wifi::forget(&profile)),
+ _ => return,
+ }
+ SetTimer(hwnd, 2, 1500, None);
+ InvalidateRect(hwnd, null(), 0);
+ }
+}
+
+unsafe extern "system" fn proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {
+ unsafe {
+ if msg == winrust_common::style::msg() {
+ winrust_common::style::reload(); // the style changed in the topbar menu: repaint in it
+ frame(hwnd);
+ InvalidateRect(hwnd, null(), 0);
+ return 0;
+ }
+ match msg {
+ WM_PAINT => {
+ paint(hwnd);
+ 0
+ }
+ WM_ERASEBKGND => 1,
+ WM_SIZE | WM_SETTINGCHANGE => {
+ clamp_scroll(hwnd, 0);
+ let (ed, dpi) = APP.with_borrow(|a| (a.edit, a.dpi));
+ if ed != 0 {
+ let mut rc: RECT = std::mem::zeroed();
+ GetClientRect(hwnd, &mut rc);
+ let (_, e) = bar(rc.right, rc.bottom, dpi);
+ MoveWindow(ed as HWND, e.left, e.top, e.right - e.left, e.bottom - e.top, 1);
+ }
+ InvalidateRect(hwnd, null(), 0); // a changed theme repaints in it
+ 0
+ }
+ WM_CTLCOLOREDIT => {
+ let t = theme();
+ SetTextColor(wp as HDC, t.fg);
+ SetBkColor(wp as HDC, t.bg);
+ let b = CreateSolidBrush(t.bg);
+ let old = APP.with_borrow_mut(|a| std::mem::replace(&mut a.brush, b as isize));
+ if old != 0 {
+ DeleteObject(old as _);
+ }
+ b as LRESULT
+ }
+ WM_EDIT_KEY => {
+ if wp == VK_RETURN as usize {
+ submit_prompt(hwnd);
+ } else {
+ close_prompt(hwnd);
+ APP.with_borrow_mut(|a| a.msg = None);
+ InvalidateRect(hwnd, null(), 0);
+ }
+ 0
+ }
+ wifi::WM_WIFI => {
+ if wp as i32 == wlan_notification_acm_connection_complete && lp != 0 {
+ let (reason, profile) = *Box::from_raw(lp as *mut (u32, String));
+ // only the connection this window started: Windows also reports its own automatic ones
+ if let Some((ssid, prof, new)) = APP.with_borrow_mut(|a| a.connecting.take_if(|c| c.1 == profile)) {
+ KillTimer(hwnd, 3);
+ let m = (reason != 0).then(|| {
+ if new {
+ wifi::forget(&prof); // a wrong password is not kept: the next click asks again
+ }
+ tf!("Не удалось подключиться к «{}»: {}", "Could not connect to \"{}\": {}", ssid, wifi::reason_text(reason))
+ });
+ APP.with_borrow_mut(|a| a.msg = m);
+ }
+ }
+ if APP.with_borrow(|a| a.page == NET_PAGE) {
+ refresh_page(hwnd);
+ }
+ 0
+ }
+ WM_NOTE => {
+ let m = *Box::from_raw(lp as *mut String);
+ APP.with_borrow_mut(|a| a.msg = Some(m));
+ refresh_page(hwnd);
+ 0
+ }
+ WM_REFRESH => {
+ if let Some(m) = bt::take_note() {
+ APP.with_borrow_mut(|a| a.msg = Some(m));
+ }
+ refresh_page(hwnd);
+ 0
+ }
+ WM_TIMER if wp == 3 => {
+ KillTimer(hwnd, 3);
+ if let Some((ssid, ..)) = APP.with_borrow_mut(|a| a.connecting.take()) {
+ APP.with_borrow_mut(|a| a.msg = Some(tf!("«{}» не ответила за 30 с", "\"{}\" did not answer in 30 s", ssid)));
+ InvalidateRect(hwnd, null(), 0);
+ }
+ 0
+ }
+ WM_TIMER if wp == 4 => {
+ if APP.with_borrow(|a| a.pick.as_ref().is_none_or(|pk| pk.t0.elapsed().as_millis() > 220)) {
+ KillTimer(hwnd, 4);
+ }
+ InvalidateRect(hwnd, null(), 0);
+ 0
+ }
+ WM_MOUSEWHEEL if APP.with_borrow(|a| a.pick.is_some()) => {
+ // the wheel scrolls an open list instead of the page
+ let up = (wp >> 16) as i16 > 0;
+ APP.with_borrow_mut(|a| {
+ if let Some(pk) = a.pick.as_mut() {
+ let max = pk.items.len().saturating_sub(PICK_MAX);
+ pk.top = if up { pk.top.saturating_sub(1) } else { (pk.top + 1).min(max) };
+ }
+ });
+ InvalidateRect(hwnd, null(), 0);
+ 0
+ }
+ WM_MOUSEWHEEL => {
+ clamp_scroll(hwnd, -((wp >> 16) as i16 as i32) / 120 * ROW_H);
+ InvalidateRect(hwnd, null(), 0);
+ 0
+ }
+ WM_TIMER if wp == 2 => {
+ let (page, n) = APP.with_borrow_mut(|a| {
+ a.ticks += 1;
+ (a.page, a.ticks)
+ });
+ if page == NET_PAGE && n % 8 == 0 {
+ wifi::scan(); // about every 30 s; the result arrives as an event
+ }
+ if page == BT_PAGE {
+ bt::refresh(ping);
+ }
+ if page != APPS_PAGE {
+ refresh_page(hwnd); // the pages whose values change by themselves
+ }
+ SetTimer(hwnd, 2, 4000, None);
+ 0
+ }
+ WM_TIMER => {
+ // the countdown of an unconfirmed display change: at 0 it goes back by itself
+ if APP.with_borrow_mut(|a| (a.pending > 0).then(|| a.pending -= 1).is_some_and(|_| a.pending == 0)) {
+ finish_confirm(hwnd, false);
+ } else {
+ InvalidateRect(hwnd, null(), 0);
+ }
+ 0
+ }
+ WM_MOUSEMOVE => {
+ if let Some(src) = APP.with_borrow(|a| a.drag) {
+ let (mut rc, dpi) = (std::mem::zeroed::<RECT>(), APP.with_borrow(|a| a.dpi));
+ GetClientRect(hwnd, &mut rc);
+ let (l, r) = track(rc.right, dpi);
+ audio::set_volume(src, slider_value((lp & 0xFFFF) as i16 as i32, l, r));
+ InvalidateRect(hwnd, null(), 0);
+ }
+ if APP.with_borrow(|a| a.arr.is_some()) {
+ let mut rc = std::mem::zeroed::<RECT>();
+ GetClientRect(hwnd, &mut rc);
+ let (x, y) = ((lp & 0xFFFF) as i16 as i32, (lp >> 16) as i16 as i32);
+ APP.with_borrow_mut(|a| {
+ let Some(bx) = arr_box(a, rc.right) else { return };
+ let (px, py) = arr_map(&a.layout, bx).desk(x, y);
+ if let Some(d) = a.arr.as_mut() {
+ d.cur = (px - d.grab.0, py - d.grab.1);
+ let m = a.layout[d.idx];
+ d.moved |= (d.cur.0 - m.x).abs() + (d.cur.1 - m.y).abs() > 60;
+ }
+ });
+ InvalidateRect(hwnd, null(), 0);
+ }
+ let mut te = TRACKMOUSEEVENT { cbSize: size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE, hwndTrack: hwnd, dwHoverTime: 0 };
+ TrackMouseEvent(&mut te);
+ let (x, y) = ((lp & 0xFFFF) as i16 as i32, (lp >> 16) as i16 as i32);
+ let mut rc: RECT = std::mem::zeroed();
+ GetClientRect(hwnd, &mut rc);
+ let over = APP.with_borrow_mut(|a| {
+ let it = pick_item(a, rc.right, rc.bottom, x, y);
+ let pk = a.pick.as_mut()?;
+ let old = pk.hover;
+ pk.hover = it.or(old);
+ Some(old != pk.hover)
+ });
+ if over.is_some() {
+ if over == Some(true) {
+ InvalidateRect(hwnd, null(), 0);
+ }
+ return 0; // rows under an open list do not light up
+ }
+ let changed = APP.with_borrow_mut(|a| {
+ let side = a.dpi * SIDE / 96;
+ let now = a.pages.get(a.page).and_then(|pg| (x >= side).then(|| row_at_scrolled(a, y)).flatten().filter(|&i| !matches!(pg.rows[i], Row::Info(..) | Row::Header(_) | Row::Arrange(_))));
+ std::mem::replace(&mut a.hover, now) != now
+ });
+ if changed {
+ InvalidateRect(hwnd, null(), 0);
+ }
+ 0
+ }
+ WM_MOUSELEAVE => {
+ if APP.with_borrow_mut(|a| a.hover.take().is_some()) {
+ InvalidateRect(hwnd, null(), 0);
+ }
+ 0
+ }
+ WM_LBUTTONUP => {
+ ReleaseCapture();
+ let dropped = APP.with_borrow_mut(|a| {
+ a.drag = None;
+ a.arr.take().map(|d| (d, a.layout.clone()))
+ });
+ if let Some((d, mons)) = dropped {
+ let m = mons[d.idx];
+ if d.moved {
+ // flush against the nearest edge of another display; Windows refuses gaps and overlaps
+ let others: Vec<_> = mons.iter().enumerate().filter(|(j, _)| *j != d.idx).map(|(_, m)| *m).collect();
+ let (x, y) = display::snap(d.cur.0, d.cur.1, m.w, m.h, &others);
+ if (x, y) != (m.x, m.y) && !display::move_monitor(d.idx, x, y) {
+ APP.with_borrow_mut(|a| a.msg = Some(t!("Windows не приняла такое расположение", "Windows did not accept that arrangement").into()));
+ }
+ } else {
+ display::select_monitor(d.idx); // a click picks the display the rows below act on
+ }
+ refresh_page(hwnd);
+ InvalidateRect(hwnd, null(), 0);
+ }
+ 0
+ }
+ WM_LBUTTONDOWN => {
+ let mut rc: RECT = std::mem::zeroed();
+ GetClientRect(hwnd, &mut rc);
+ // an open list takes the click: an item is chosen, anywhere else only closes it
+ let (x, y) = ((lp & 0xFFFF) as i16 as i32, (lp >> 16) as i16 as i32);
+ if let Some(picked) = APP.with_borrow_mut(|a| {
+ let it = pick_item(a, rc.right, rc.bottom, x, y);
+ a.pick.take().map(|pk| it.map(|i| (pk.op, i)))
+ }) {
+ if let Some((op, i)) = picked {
+ choose(hwnd, op, i);
+ }
+ InvalidateRect(hwnd, null(), 0);
+ return 0;
+ }
+ // a finished Wi-Fi message goes with the next click; a prompt or a running connection keeps its own
+ APP.with_borrow_mut(|a| {
+ if a.prompt.is_none() && a.connecting.is_none() {
+ a.msg = None;
+ }
+ });
+ match click((lp & 0xFFFF) as i16 as i32, (lp >> 16) as i16 as i32, rc.right) {
+ Some(Act::Do(Op::Radio)) => {
+ wifi::set_radio(!RADIO.get().is_some_and(|r| r.0));
+ SetTimer(hwnd, 2, 1500, None);
+ }
+ Some(Act::Do(Op::Hidden)) => open_prompt(hwnd, Prompt::Ssid),
+ Some(Act::Do(op)) => display_or_mute(hwnd, op),
+ Some(Act::Pick(op, row)) => open_pick(hwnd, op, row),
+ Some(Act::Volume(v, src)) => {
+ audio::set_volume(src, v);
+ SetCapture(hwnd);
+ APP.with_borrow_mut(|a| a.drag = Some(src));
+ }
+ Some(Act::Cmd(cmd)) => {
+ let label = APP.with_borrow(|a| row_at_scrolled(a, (lp >> 16) as i16 as i32).and_then(|i| match a.pages.get(a.page)?.rows.get(i)? {
+ Row::Item(l, ..) => Some(l.clone()),
+ _ => None,
+ }));
+ run_cmd(hwnd, &label.unwrap_or_default(), cmd);
+ }
+ Some(Act::Arr(x, y)) => {
+ let started = APP.with_borrow_mut(|a| {
+ let bx = arr_box(a, rc.right)?;
+ let (px, py) = arr_map(&a.layout, bx).desk(x, y);
+ let i = a.layout.iter().position(|m| px >= m.x && px < m.x + m.w && py >= m.y && py < m.y + m.h)?;
+ let m = a.layout[i];
+ a.arr = Some(ArrDrag { idx: i, grab: (px - m.x, py - m.y), cur: (m.x, m.y), moved: false });
+ Some(())
+ });
+ if started.is_some() {
+ SetCapture(hwnd);
+ }
+ }
+ Some(Act::Page(i)) => goto(hwnd, i),
+ Some(Act::Flip(k, n, v)) => {
+ if sys::set_hkcu_dword(k, n, v) {
+ if k == PERSONALIZE {
+ sys::announce_theme();
+ } else if k == ext::INET {
+ ext::proxy_changed();
+ }
+ }
+ }
+ Some(Act::Wifi(n)) => wifi_click(hwnd, n),
+ Some(Act::Adapter(name)) => {
+ EXPANDED.with_borrow_mut(|e| *e = if e.as_deref() == Some(name.as_str()) { None } else { Some(name) });
+ refresh_page(hwnd);
+ }
+ None => {}
+ }
+ InvalidateRect(hwnd, null(), 0);
+ 0
+ }
+ WM_RBUTTONUP => {
+ wifi_menu(hwnd, (lp & 0xFFFF) as i16 as i32, (lp >> 16) as i16 as i32);
+ 0
+ }
+ WM_KEYDOWN => {
+ match wp as u16 {
+ VK_ESCAPE | VK_UP | VK_DOWN | VK_RETURN if APP.with_borrow(|a| a.pick.is_some()) => {
+ // keys in an open list: arrows move, Enter chooses, Esc closes
+ let key = wp as u16;
+ let go = APP.with_borrow_mut(|a| {
+ let pk = a.pick.as_mut()?;
+ let n = pk.items.len();
+ match key {
+ VK_UP | VK_DOWN => {
+ let h = pk.hover.map_or(0, |h| if key == VK_UP { h.saturating_sub(1) } else { (h + 1).min(n - 1) });
+ pk.hover = Some(h);
+ pk.top = pk.top.min(h).max((h + 1).saturating_sub(PICK_MAX));
+ None
+ }
+ VK_RETURN => a.pick.take().and_then(|pk| pk.hover.map(|h| (pk.op, h))),
+ _ => {
+ a.pick = None;
+ None
+ }
+ }
+ });
+ if let Some((op, i)) = go {
+ choose(hwnd, op, i);
+ }
+ InvalidateRect(hwnd, null(), 0);
+ }
+ VK_ESCAPE => {
+ if APP.with_borrow(|a| a.pending > 0) {
+ finish_confirm(hwnd, false);
+ } else if APP.with_borrow(|a| a.prompt.is_some()) {
+ close_prompt(hwnd);
+ InvalidateRect(hwnd, null(), 0);
+ } else {
+ DestroyWindow(hwnd);
+ }
+ }
+ VK_RETURN if APP.with_borrow(|a| a.pending > 0) => finish_confirm(hwnd, true),
+ k @ (VK_UP | VK_DOWN) => {
+ let to = APP.with_borrow(|a| if k == VK_UP { a.page.saturating_sub(1) } else { (a.page + 1).min(a.pages.len() - 1) });
+ goto(hwnd, to);
+ InvalidateRect(hwnd, null(), 0);
+ }
+ _ => {}
+ }
+ 0
+ }
+ WM_DESTROY => {
+ PostQuitMessage(0);
+ 0
+ }
+ _ => DefWindowProcW(hwnd, msg, wp, lp),
+ }
+ }
+}
+
+fn main() {
+ if std::env::args().nth(1).as_deref() == Some("--nightlight") {
+ return ext::night_helper(); // the colour filter's background process, see ext.rs
+ }
+ audio::init();
+ unsafe {
+ let (mut token, mut input): (usize, windows_sys::Win32::Graphics::GdiPlus::GdiplusStartupInput) = (0, std::mem::zeroed());
+ input.GdiplusVersion = 1;
+ windows_sys::Win32::Graphics::GdiPlus::GdiplusStartup(&mut token, &input, null_mut()); // for the smooth rounded shapes
+ SetProcessDPIAware();
+ let dpi = GetDpiForSystem() as i32;
+ let start = std::env::args().nth(1).map_or(0, |a| page_for(&a));
+ let (pg, lay) = (pages(), display::layout()); // read before the borrow: COM calls inside can run the window procedure
+ APP.with_borrow_mut(|a| (a.pages, a.page, a.dpi, a.layout) = (pg, start, dpi, lay));
+ refresh_fonts();
+ let (inst, class) = (GetModuleHandleW(null()), wide("WinRustSettings"));
+ 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(t!("Параметры", "Settings")).as_ptr(), WS_OVERLAPPEDWINDOW | WS_VISIBLE | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, 940 * dpi / 96, 620 * dpi / 96, null_mut(), null_mut(), inst, null());
+ frame(hwnd);
+ MAIN.store(hwnd as isize, std::sync::atomic::Ordering::Relaxed);
+ wifi::watch(hwnd);
+ goto(hwnd, start); // reads the page fresh and starts what it needs (a Wi-Fi scan, the Bluetooth lists)
+ SetTimer(hwnd, 2, 4000, None);
+ 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 toggle_state_follows_value_and_default() {
+ assert!(is_on(Some(0), 0, 1)); // dark theme: value 0 is "on"
+ assert!(!is_on(Some(1), 0, 1));
+ assert!(!is_on(None, 0, 1)); // no value: light theme
+ assert!(!is_on(None, 1, 0)); // accent on title bars is off by default
+ }
+
+ #[test]
+ fn rows_are_hit_by_position() {
+ assert_eq!(row_at(10, 76, 52, 3), None); // above the first row
+ assert_eq!(row_at(76, 76, 52, 3), Some(0));
+ assert_eq!(row_at(76 + 52 * 2 + 51, 76, 52, 3), Some(2));
+ assert_eq!(row_at(76 + 52 * 3, 76, 52, 3), None); // below the last row
+ }
+
+ #[test]
+ fn short_pages_do_not_scroll_and_long_ones_stop_at_the_end() {
+ assert_eq!(max_scroll(3, 620), 0);
+ assert_eq!(max_scroll(20, 620), ROWS_TOP + ROW_H * 20 + 24 - 620);
+ }
+
+ #[test]
+ fn every_page_has_its_keys() {
+ assert_eq!(pages().len(), PAGE_KEYS.len());
+ assert_eq!(page_for("ms-settings:network-status"), 3);
+ }
+
+ #[test]
+ fn the_arrangement_picture_maps_both_ways_and_keeps_displays_inside() {
+ let mons = [display::Mon { x: 0, y: 0, w: 1920, h: 1080, primary: true }, display::Mon { x: 1920, y: 0, w: 1280, h: 1024, primary: false }];
+ let bx = RECT { left: 100, top: 20, right: 500, bottom: 180 };
+ let m = arr_map(&mons, bx);
+ let (x0, y0) = m.dev(0, 0);
+ let (x1, y1) = m.dev(3200, 1080);
+ assert!(x0 >= bx.left && y0 >= bx.top && x1 <= bx.right && y1 <= bx.bottom);
+ let (bx2, by2) = m.dev(1920, 500);
+ assert!((m.desk(bx2, by2).0 - 1920).abs() <= 8 && (m.desk(bx2, by2).1 - 500).abs() <= 8); // round trip within a few pixels
+ }
+
+ #[test]
+ fn slider_maps_position_to_whole_percent() {
+ assert_eq!(slider_value(100, 100, 300), 0.0);
+ assert_eq!(slider_value(200, 100, 300), 0.5);
+ assert_eq!(slider_value(900, 100, 300), 1.0); // dragged past the end
+ assert_eq!(slider_value(-5, 100, 300), 0.0);
+ }
+
+ #[test]
+ fn names_and_pages() {
+ assert_eq!(os_name("Windows 10 Pro", 26100), "Windows 11 Pro");
+ assert_eq!(os_name("Windows 10 Pro", 19045), "Windows 10 Pro");
+ assert_eq!(gb(16 << 30), "16.0 GB");
+ assert_eq!((page_for("ms-settings:about"), page_for("more"), page_for("ms-settings:display"), page_for("")), (8, 0, 0, 0));
+ assert_eq!((page_for("ms-settings:sound"), page_for("ms-settings:personalization-colors")), (1, 7));
+ assert_eq!((page_for("bluetooth"), page_for("apps"), page_for("update"), page_for("network")), (BT_PAGE, APPS_PAGE, WU_PAGE, NET_PAGE));
+ assert_eq!((page_for("ms-settings:powersleep"), page_for("ms-settings:storagesense")), (2, 2));
+ }
+}
diff --git a/plugins/rust-settings/src/net.rs b/plugins/rust-settings/src/net.rs
new file mode 100644
index 0000000..e253067
--- /dev/null
+++ b/plugins/rust-settings/src/net.rs
@@ -0,0 +1,252 @@
+//! Network adapters (Wi-Fi and Ethernet) through GetAdaptersAddresses: addresses, gateway, DNS, MAC, DHCP, link speed, and
+//! whether Windows sees the internet through each (Network List Manager). Read-only: changing IP/DNS needs admin, left to Windows.
+use std::net::{Ipv4Addr, Ipv6Addr};
+use windows_sys::Win32::{
+ Foundation::*,
+ NetworkManagement::IpHelper::*,
+ Networking::WinSock::{SOCKADDR, SOCKADDR_IN6, SOCKET_ADDRESS},
+};
+
+const IF_ETHERNET: u32 = 6;
+const IF_WIFI: u32 = 71;
+const OPER_UP: i32 = 1;
+
+pub struct Adapter {
+ pub name: String,
+ pub desc: String,
+ pub wifi: bool,
+ pub up: bool,
+ pub speed: u64, // bits per second
+ pub ipv4: Vec<(Ipv4Addr, u8)>, // address, prefix length
+ pub ipv6: Vec<Ipv6Addr>, // without the link-local ones
+ pub gateway: Vec<String>,
+ pub dns: Vec<String>,
+ pub mac: String,
+ pub dhcp: bool,
+ pub internet: Option<bool>, // None: Windows does not say
+}
+
+pub fn speed_text(bits_per_sec: u64) -> Option<String> {
+ match bits_per_sec / 1_000_000 {
+ 0 => None,
+ m if m >= 1000 => Some(tf!("{} Гбит/с", "{} Gbps", m as f64 / 1000.0)),
+ m => Some(tf!("{} Мбит/с", "{} Mbps", m)),
+ }
+}
+
+/// A link-local IPv4 address (169.254.x.x): the adapter is up but got no address from DHCP.
+fn apipa(ip: &Ipv4Addr) -> bool {
+ ip.octets()[..2] == [169, 254]
+}
+
+impl Adapter {
+ /// The short status on the right of the adapter's row.
+ pub fn status(&self) -> String {
+ if !self.up {
+ return t!("Не подключено", "Not connected").into();
+ }
+ match (self.internet, self.ipv4.first()) {
+ (Some(true), _) => t!("Интернет", "Internet").into(),
+ (_, Some((ip, _))) if apipa(ip) && self.ipv6.is_empty() => t!("Нет адреса (DHCP)", "No address (DHCP)").into(),
+ (Some(false), _) => t!("Без интернета", "No internet").into(),
+ _ => t!("Подключено", "Connected").into(),
+ }
+ }
+
+ /// The line under the name: address and link speed.
+ pub fn summary(&self) -> String {
+ let ip = self.ipv4.iter().find(|(ip, _)| !apipa(ip)).map(|(ip, _)| ip.to_string()).or_else(|| self.ipv6.first().map(|ip| ip.to_string()));
+ let kind = if self.wifi { "Wi-Fi" } else { "Ethernet" };
+ [Some(kind.to_string()), ip, if self.up { speed_text(self.speed) } else { None }].into_iter().flatten().collect::<Vec<_>>().join(" · ")
+ }
+
+ /// (label, value) rows of the expanded adapter.
+ pub fn details(&self) -> Vec<(String, String)> {
+ let join = |v: Vec<String>| if v.is_empty() { "—".to_string() } else { v.join(", ") };
+ let mut out = vec![(t!("Описание", "Description").to_string(), self.desc.clone())];
+ if self.up {
+ // an unplugged adapter keeps a link-local address and Windows' placeholder DNS: noise, not shown
+ out.push(("IPv4".into(), join(self.ipv4.iter().map(|(ip, p)| format!("{ip}/{p}")).collect())));
+ if !self.ipv6.is_empty() {
+ out.push(("IPv6".into(), join(self.ipv6.iter().map(|ip| ip.to_string()).collect())));
+ }
+ out.push((t!("Шлюз", "Gateway").into(), join(self.gateway.clone())));
+ out.push(("DNS".into(), join(self.dns.clone())));
+ }
+ out.push((t!("Адрес IP", "IP assignment").into(), if self.dhcp { t!("Автоматически (DHCP)", "Automatic (DHCP)").into() } else { t!("Вручную", "Manual").into() }));
+ out.push(("MAC".into(), self.mac.clone()));
+ out
+ }
+}
+
+fn pwstr(p: *const u16) -> String {
+ if p.is_null() {
+ return String::new();
+ }
+ let len = (0..).take_while(|&i| unsafe { *p.add(i) } != 0).count();
+ String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(p, len) })
+}
+
+fn sockaddr(a: &SOCKET_ADDRESS) -> Option<std::net::IpAddr> {
+ let sa = a.lpSockaddr as *const SOCKADDR;
+ if sa.is_null() {
+ return None;
+ }
+ match unsafe { (*sa).sa_family } {
+ 2 => {
+ let d = unsafe { (*sa).sa_data }; // port (2 bytes), then the address
+ Some(Ipv4Addr::new(d[2] as u8, d[3] as u8, d[4] as u8, d[5] as u8).into())
+ }
+ 23 if a.iSockaddrLength as usize >= size_of::<SOCKADDR_IN6>() => Some(Ipv6Addr::from(unsafe { (*(sa as *const SOCKADDR_IN6)).sin6_addr.u.Byte }).into()),
+ _ => None,
+ }
+}
+
+/// Walks one of the adapter's linked address lists (`Next` and `Address` share the layout of every such list).
+macro_rules! walk {
+ ($first:expr) => {{
+ let mut out = vec![];
+ let mut p = $first;
+ while !p.is_null() {
+ let x = unsafe { &*p };
+ out.push(x);
+ p = x.Next;
+ }
+ out
+ }};
+}
+
+/// A real network card: Hyper-V switches, VPN and Wi-Fi Direct adapters say they are not hardware.
+fn hardware(a: &IP_ADAPTER_ADDRESSES_LH) -> bool {
+ let mut row: MIB_IF_ROW2 = unsafe { std::mem::zeroed() };
+ row.InterfaceLuid = a.Luid;
+ unsafe { GetIfEntry2(&mut row) == ERROR_SUCCESS && row.InterfaceAndOperStatusFlags._bitfield & 1 != 0 }
+}
+
+/// Internet per adapter GUID, as the Network List Manager (the source of Windows' own tray icon) reports it.
+fn internet() -> Vec<(windows::core::GUID, bool)> {
+ use windows::Win32::{Networking::NetworkListManager::*, System::Com::*};
+ let mut out = vec![];
+ unsafe {
+ let Ok(nlm) = CoCreateInstance::<_, INetworkListManager>(&NetworkListManager, None, CLSCTX_ALL) else { return out };
+ let Ok(conns) = nlm.GetNetworkConnections() else { return out };
+ loop {
+ let mut one = [None];
+ let mut n = 0u32;
+ if conns.Next(&mut one, Some(&mut n)).is_err() || n == 0 {
+ break;
+ }
+ let Some(c) = one[0].take() else { break };
+ if let (Ok(id), Ok(cn)) = (c.GetAdapterId(), c.GetConnectivity()) {
+ out.push((id, cn.0 & (NLM_CONNECTIVITY_IPV4_INTERNET.0 | NLM_CONNECTIVITY_IPV6_INTERNET.0) != 0));
+ }
+ }
+ }
+ out
+}
+
+/// "{GUID}" as GetAdaptersAddresses names an adapter.
+fn guid_of(name: &str) -> Option<windows::core::GUID> {
+ let h = name.trim_matches(|c| c == '{' || c == '}').replace('-', "");
+ u128::from_str_radix(&h, 16).ok().filter(|_| h.len() == 32).map(windows::core::GUID::from_u128)
+}
+
+/// The Wi-Fi and Ethernet cards (virtual ones left out), connected ones first.
+pub fn adapters() -> Vec<Adapter> {
+ let mut n = 16 * 1024u32;
+ // u64 words: the structures need 8-byte alignment
+ let mut buf: Vec<u64> = vec![0; n as usize / 8 + 1];
+ for _ in 0..3 {
+ let rc = unsafe { GetAdaptersAddresses(0, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_INCLUDE_GATEWAYS, std::ptr::null(), buf.as_mut_ptr() as *mut IP_ADAPTER_ADDRESSES_LH, &mut n) };
+ if rc == ERROR_BUFFER_OVERFLOW {
+ buf = vec![0; n as usize / 8 + 1];
+ continue;
+ }
+ if rc != ERROR_SUCCESS {
+ break;
+ }
+ let net = internet();
+ let mut out: Vec<Adapter> = walk!(buf.as_ptr() as *const IP_ADAPTER_ADDRESSES_LH)
+ .into_iter()
+ .filter(|a| (a.IfType == IF_ETHERNET || a.IfType == IF_WIFI) && hardware(a))
+ .map(|a| {
+ let mut ipv4 = vec![];
+ let mut ipv6 = vec![];
+ for u in walk!(a.FirstUnicastAddress) {
+ match sockaddr(&u.Address) {
+ Some(std::net::IpAddr::V4(ip)) => ipv4.push((ip, u.OnLinkPrefixLength)),
+ Some(std::net::IpAddr::V6(ip)) if ip.segments()[0] & 0xffc0 != 0xfe80 => ipv6.push(ip),
+ _ => {}
+ }
+ }
+ let name = unsafe { std::ffi::CStr::from_ptr(a.AdapterName as _) }.to_string_lossy().into_owned();
+ let id = guid_of(&name);
+ let mac = a.PhysicalAddress[..(a.PhysicalAddressLength as usize).min(8)].iter().map(|b| format!("{b:02X}")).collect::<Vec<_>>().join(":");
+ Adapter {
+ name: pwstr(a.FriendlyName),
+ desc: pwstr(a.Description),
+ wifi: a.IfType == IF_WIFI,
+ up: a.OperStatus == OPER_UP,
+ speed: a.TransmitLinkSpeed,
+ ipv4,
+ ipv6,
+ gateway: walk!(a.FirstGatewayAddress).into_iter().filter_map(|g| sockaddr(&g.Address)).map(|ip| ip.to_string()).collect(),
+ dns: walk!(a.FirstDnsServerAddress).into_iter().filter_map(|d| sockaddr(&d.Address)).map(|ip| ip.to_string()).fold(vec![], |mut v, ip| {
+ if !v.contains(&ip) {
+ v.push(ip); // Windows lists a router's IPv6 DNS once per prefix
+ }
+ v
+ }),
+ mac,
+ dhcp: unsafe { a.Anonymous2.Flags } & IP_ADAPTER_DHCP_ENABLED != 0,
+ internet: id.and_then(|id| net.iter().find(|(g, _)| *g == id).map(|&(_, on)| on)),
+ }
+ })
+ .collect();
+ out.sort_by_key(|a| !a.up);
+ return out;
+ }
+ vec![]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn eth(up: bool, ip: [u8; 4], internet: Option<bool>) -> Adapter {
+ Adapter { name: "Ethernet".into(), desc: String::new(), wifi: false, up, speed: 1_000_000_000, ipv4: vec![(Ipv4Addr::from(ip), 24)], ipv6: vec![], gateway: vec![], dns: vec![], mac: String::new(), dhcp: true, internet }
+ }
+
+ #[test]
+ fn link_speed_reads_in_mbps_or_gbps() {
+ assert_eq!(speed_text(0), None);
+ assert_eq!(speed_text(866_000_000).as_deref(), Some("866 Мбит/с"));
+ assert_eq!(speed_text(2_500_000_000).as_deref(), Some("2.5 Гбит/с"));
+ }
+
+ #[test]
+ fn status_tells_internet_dhcp_failure_and_unplugged_apart() {
+ assert_eq!(eth(false, [192, 168, 1, 5], None).status(), "Не подключено");
+ assert_eq!(eth(true, [192, 168, 1, 5], Some(true)).status(), "Интернет");
+ assert_eq!(eth(true, [169, 254, 3, 4], Some(false)).status(), "Нет адреса (DHCP)");
+ assert_eq!(eth(true, [192, 168, 1, 5], Some(false)).status(), "Без интернета");
+ assert_eq!(eth(true, [192, 168, 1, 5], None).status(), "Подключено");
+ assert_eq!(eth(true, [192, 168, 1, 5], None).summary(), "Ethernet · 192.168.1.5 · 1 Гбит/с");
+ assert_eq!(eth(false, [169, 254, 3, 4], None).summary(), "Ethernet");
+ }
+
+ #[test]
+ fn adapter_guids_parse() {
+ assert_eq!(guid_of("{12345678-9ABC-DEF0-1234-56789ABCDEF0}"), Some(windows::core::GUID::from_u128(0x12345678_9abc_def0_1234_56789abcdef0)));
+ assert_eq!(guid_of("junk"), None);
+ }
+
+ #[test]
+ #[ignore] // prints this machine's adapters: cargo test -p rust-settings -- --ignored --nocapture
+ fn print_adapters() {
+ unsafe { windows::Win32::System::Com::CoInitializeEx(None, windows::Win32::System::Com::COINIT_APARTMENTTHREADED).ok().ok() };
+ for a in adapters() {
+ println!("{} | {} | {} | {:?}", a.name, a.status(), a.summary(), a.details());
+ }
+ }
+}
diff --git a/plugins/rust-settings/src/power.rs b/plugins/rust-settings/src/power.rs
new file mode 100644
index 0000000..1e7bc9d
--- /dev/null
+++ b/plugins/rust-settings/src/power.rs
@@ -0,0 +1,186 @@
+//! Battery, power plan and drive space: documented Win32 calls (GetSystemPowerStatus, powrprof, GetDiskFreeSpaceExW).
+use std::ptr::{null, null_mut};
+use windows_sys::{
+ Win32::{Foundation::*, Storage::FileSystem::*, System::Power::*},
+ core::GUID,
+};
+
+const DRIVE_FIXED: u32 = 3; // GetDriveTypeW
+
+fn same(a: &GUID, b: &GUID) -> bool {
+ (a.data1, a.data2, a.data3, a.data4) == (b.data1, b.data2, b.data3, b.data4)
+}
+
+pub fn size(bytes: u64) -> String {
+ const GB: f64 = (1u64 << 30) as f64;
+ let b = bytes as f64;
+ if b >= 1024.0 * GB { format!("{:.2} TB", b / (1024.0 * GB)) } else { format!("{:.1} GB", b / GB) }
+}
+
+/// "73%, on battery" / "100%, plugged in" / "No battery".
+pub fn battery(on_ac: u8, flag: u8, percent: u8) -> String {
+ if flag == 128 || flag == 255 || percent > 100 {
+ return t!("Нет батареи", "No battery").into();
+ }
+ let src = if on_ac == 1 { t!("от сети", "plugged in") } else { t!("от батареи", "on battery") };
+ format!("{percent}%, {src}")
+}
+
+pub fn battery_text() -> String {
+ let mut s: SYSTEM_POWER_STATUS = unsafe { std::mem::zeroed() };
+ if unsafe { GetSystemPowerStatus(&mut s) } == 0 {
+ return "?".into();
+ }
+ battery(s.ACLineStatus, s.BatteryFlag, s.BatteryLifePercent)
+}
+
+/// Fixed drives as (letter, free, total).
+pub fn drives() -> Vec<(char, u64, u64)> {
+ let mask = unsafe { GetLogicalDrives() };
+ (0..26u8)
+ .filter(|i| mask >> i & 1 == 1)
+ .filter_map(|i| {
+ let root: Vec<u16> = format!("{}:\\", (b'A' + i) as char).encode_utf16().chain([0]).collect();
+ if unsafe { GetDriveTypeW(root.as_ptr()) } != DRIVE_FIXED {
+ return None;
+ }
+ let (mut free, mut total, mut _all) = (0u64, 0u64, 0u64);
+ (unsafe { GetDiskFreeSpaceExW(root.as_ptr(), &mut free, &mut total, &mut _all) } != 0).then_some(((b'A' + i) as char, free, total))
+ })
+ .collect()
+}
+
+fn schemes() -> Vec<GUID> {
+ let mut out = vec![];
+ for i in 0.. {
+ let mut g: GUID = unsafe { std::mem::zeroed() };
+ let mut n = size_of::<GUID>() as u32;
+ if unsafe { PowerEnumerate(null_mut(), null(), null(), ACCESS_SCHEME, i, &mut g as *mut GUID as *mut u8, &mut n) } != ERROR_SUCCESS {
+ break;
+ }
+ out.push(g);
+ }
+ out
+}
+
+fn active() -> Option<GUID> {
+ let mut p: *mut GUID = null_mut();
+ if unsafe { PowerGetActiveScheme(null_mut(), &mut p) } != ERROR_SUCCESS || p.is_null() {
+ return None;
+ }
+ let g = unsafe { *p };
+ unsafe { LocalFree(p as _) };
+ Some(g)
+}
+
+fn name_of(g: &GUID) -> String {
+ let mut n = 0u32;
+ unsafe { PowerReadFriendlyName(null_mut(), g, null(), null(), null_mut(), &mut n) };
+ if n < 2 {
+ return "?".into();
+ }
+ let mut buf = vec![0u8; n as usize];
+ if unsafe { PowerReadFriendlyName(null_mut(), g, null(), null(), buf.as_mut_ptr(), &mut n) } != ERROR_SUCCESS {
+ return "?".into();
+ }
+ let w: Vec<u16> = buf.chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).take_while(|&c| c != 0).collect();
+ String::from_utf16_lossy(&w)
+}
+
+pub fn plan_text() -> String {
+ active().map_or("?".into(), |g| name_of(&g))
+}
+
+/// The power plans' names and the index of the active one.
+pub fn plans() -> (Vec<String>, Option<usize>) {
+ let all = schemes();
+ let cur = active().and_then(|c| all.iter().position(|g| same(g, &c)));
+ (all.iter().map(name_of).collect(), cur)
+}
+
+pub fn set_plan(i: usize) {
+ if let Some(g) = schemes().get(i) {
+ unsafe { PowerSetActiveScheme(null_mut(), g) };
+ }
+}
+
+/// Screen-off and sleep timeouts of the active plan (seconds; 0 = never), written for mains and battery alike.
+#[derive(Clone, Copy)]
+pub enum Timeout {
+ Screen,
+ Sleep,
+}
+
+const VIDEO: GUID = GUID { data1: 0x7516b95f, data2: 0xf776, data3: 0x4464, data4: [0x8c, 0x53, 0x06, 0x16, 0x7f, 0x40, 0xcc, 0x99] };
+const VIDEO_IDLE: GUID = GUID { data1: 0x3c0bc021, data2: 0xc8a8, data3: 0x4e07, data4: [0xa9, 0x73, 0x6b, 0x14, 0xcb, 0xcb, 0x2b, 0x7e] };
+const SLEEP: GUID = GUID { data1: 0x238c9fa8, data2: 0x0aad, data3: 0x41ed, data4: [0x83, 0xf4, 0x97, 0xbe, 0x24, 0x2c, 0x8f, 0x20] };
+const SLEEP_IDLE: GUID = GUID { data1: 0x29f6c1db, data2: 0x86da, data3: 0x48c5, data4: [0x9f, 0xdb, 0xf2, 0xb6, 0x7b, 0x1f, 0x44, 0xda] };
+const STEPS: [u32; 10] = [60, 120, 180, 300, 600, 900, 1200, 1800, 3600, 0];
+
+fn ids(t: Timeout) -> (&'static GUID, &'static GUID) {
+ match t {
+ Timeout::Screen => (&VIDEO, &VIDEO_IDLE),
+ Timeout::Sleep => (&SLEEP, &SLEEP_IDLE),
+ }
+}
+
+pub fn timeout(t: Timeout) -> Option<u32> {
+ let (g, (sub, set)) = (active()?, ids(t));
+ let mut v = 0u32;
+ (unsafe { PowerReadACValueIndex(null_mut(), &g, sub, set, &mut v) } == ERROR_SUCCESS).then_some(v)
+}
+
+pub fn timeout_text(t: Timeout) -> String {
+ timeout(t).map_or("?".into(), secs_text)
+}
+
+fn secs_text(s: u32) -> String {
+ match s {
+ 0 => t!("Никогда", "Never").into(),
+ s if s < 3600 => tf!("{} мин", "{} min", s / 60),
+ s => tf!("{} ч", "{} h", s / 3600),
+ }
+}
+
+/// The timeouts to pick from and the index of the current one (None: an unusual value set elsewhere).
+pub fn timeouts(t: Timeout) -> (Vec<String>, Option<usize>) {
+ let cur = timeout(t);
+ (STEPS.iter().map(|&s| secs_text(s)).collect(), STEPS.iter().position(|&s| Some(s) == cur))
+}
+
+/// Sets the timeout to entry `i` of `timeouts()`, for mains and battery alike.
+pub fn set_timeout(t: Timeout, i: usize) {
+ let (Some(g), Some(&v)) = (active(), STEPS.get(i)) else { return };
+ let (sub, set) = ids(t);
+ unsafe {
+ PowerWriteACValueIndex(null_mut(), &g, sub, set, v);
+ PowerWriteDCValueIndex(null_mut(), &g, sub, set, v);
+ PowerSetActiveScheme(null_mut(), &g); // applies the change
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn sizes_read_in_gb_and_tb() {
+ assert_eq!(size(500 << 30), "500.0 GB");
+ assert_eq!(size(2 << 40), "2.00 TB");
+ }
+
+ #[test]
+ fn battery_text_covers_no_battery_and_both_sources() {
+ assert_eq!(battery(1, 128, 255), "Нет батареи");
+ assert_eq!(battery(0, 0, 73), "73%, от батареи");
+ assert_eq!(battery(1, 8, 100), "100%, от сети");
+ }
+
+ #[test]
+ fn timeout_names() {
+ assert_eq!(secs_text(0), "Никогда");
+ assert_eq!(secs_text(300), "5 мин");
+ assert_eq!(secs_text(3600), "1 ч");
+ assert_eq!(STEPS.len(), 10);
+ }
+}
diff --git a/plugins/rust-settings/src/sys.rs b/plugins/rust-settings/src/sys.rs
new file mode 100644
index 0000000..a1854b0
--- /dev/null
+++ b/plugins/rust-settings/src/sys.rs
@@ -0,0 +1,80 @@
+//! Registry reads/writes through documented Win32 calls only (no reg.exe, no shell, no strings run as commands).
+use std::ptr::null_mut;
+use windows_sys::Win32::{Foundation::*, System::Registry::*, UI::WindowsAndMessaging::*};
+
+pub fn wide(s: &str) -> Vec<u16> {
+ s.encode_utf16().chain([0]).collect()
+}
+
+pub fn dword(root: HKEY, key: &str, name: &str) -> Option<u32> {
+ let (mut v, mut n) = (0u32, 4u32);
+ let rc = unsafe { RegGetValueW(root, wide(key).as_ptr(), wide(name).as_ptr(), RRF_RT_REG_DWORD, null_mut(), &mut v as *mut u32 as _, &mut n) };
+ (rc == ERROR_SUCCESS).then_some(v)
+}
+
+pub fn string(root: HKEY, key: &str, name: &str) -> Option<String> {
+ let mut buf = [0u16; 256];
+ let mut n = size_of_val(&buf) as u32;
+ let rc = unsafe { RegGetValueW(root, wide(key).as_ptr(), wide(name).as_ptr(), RRF_RT_REG_SZ, null_mut(), buf.as_mut_ptr() as _, &mut n) };
+ // n counts bytes including the closing NUL
+ (rc == ERROR_SUCCESS).then(|| String::from_utf16_lossy(&buf[..(n as usize / 2).saturating_sub(1)]))
+}
+
+/// Writes a REG_DWORD under HKCU (the key is created when missing).
+pub fn set_hkcu_dword(key: &str, name: &str, v: u32) -> bool {
+ unsafe { RegSetKeyValueW(HKEY_CURRENT_USER, wide(key).as_ptr(), wide(name).as_ptr(), REG_DWORD, &v as *const u32 as _, 4) == ERROR_SUCCESS }
+}
+
+/// Tells running programs the theme changed. In a thread: a hung window can hold the broadcast for seconds.
+pub fn announce_theme() {
+ std::thread::spawn(|| {
+ let what = wide("ImmersiveColorSet");
+ unsafe { SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0, what.as_ptr() as isize, SMTO_ABORTIFHUNG, 2000, null_mut()) };
+ });
+}
+
+/// A REG_SZ of any length (the 256-character `string` is too short for uninstall commands).
+pub fn string_long(root: HKEY, key: &str, name: &str) -> Option<String> {
+ let mut n = 0u32;
+ let (k, v) = (wide(key), wide(name));
+ if unsafe { RegGetValueW(root, k.as_ptr(), v.as_ptr(), RRF_RT_REG_SZ, null_mut(), null_mut(), &mut n) } != ERROR_SUCCESS || n < 2 {
+ return None;
+ }
+ let mut buf = vec![0u16; n as usize / 2 + 1];
+ let mut n2 = (buf.len() * 2) as u32;
+ let rc = unsafe { RegGetValueW(root, k.as_ptr(), v.as_ptr(), RRF_RT_REG_SZ, null_mut(), buf.as_mut_ptr() as _, &mut n2) };
+ (rc == ERROR_SUCCESS).then(|| String::from_utf16_lossy(&buf[..(n2 as usize / 2).saturating_sub(1)]))
+}
+
+/// Writes a REG_SZ under HKCU (the key is created when missing); an empty text deletes the value.
+pub fn set_hkcu_string(key: &str, name: &str, v: &str) -> bool {
+ unsafe {
+ if v.is_empty() {
+ let rc = RegDeleteKeyValueW(HKEY_CURRENT_USER, wide(key).as_ptr(), wide(name).as_ptr());
+ return rc == ERROR_SUCCESS || rc == ERROR_FILE_NOT_FOUND;
+ }
+ let w = wide(v);
+ RegSetKeyValueW(HKEY_CURRENT_USER, wide(key).as_ptr(), wide(name).as_ptr(), REG_SZ, w.as_ptr() as _, (w.len() * 2) as u32) == ERROR_SUCCESS
+ }
+}
+
+/// The names of the subkeys of `root\key`.
+pub fn subkeys(root: HKEY, key: &str) -> Vec<String> {
+ let mut out = vec![];
+ unsafe {
+ let mut h: HKEY = null_mut();
+ if RegOpenKeyExW(root, wide(key).as_ptr(), 0, KEY_READ, &mut h) != ERROR_SUCCESS {
+ return out;
+ }
+ for i in 0.. {
+ let mut buf = [0u16; 256];
+ let mut n = buf.len() as u32;
+ if RegEnumKeyExW(h, i, buf.as_mut_ptr(), &mut n, null_mut(), null_mut(), null_mut(), null_mut()) != ERROR_SUCCESS {
+ break;
+ }
+ out.push(String::from_utf16_lossy(&buf[..n as usize]));
+ }
+ RegCloseKey(h);
+ }
+ out
+}
diff --git a/plugins/rust-settings/src/wifi.rs b/plugins/rust-settings/src/wifi.rs
new file mode 100644
index 0000000..2863fc1
--- /dev/null
+++ b/plugins/rust-settings/src/wifi.rs
@@ -0,0 +1,445 @@
+//! Wi-Fi through the documented WLAN API (wlanapi.dll): visible networks of the first adapter, connect (a new network gets a
+//! profile built here from the password typed in the window; Windows keeps it, encrypted, like its own page does), disconnect,
+//! forget, radio on/off (Windows.Devices.Radios, which needs no admin). Events (scan done, connection result) come as messages.
+//! Every Wi-Fi adapter is used (a network is listed once, with the adapter that sees it best). 802.1X networks (WPA/WPA2-Enterprise,
+//! PEAP with MSCHAPv2: user name and password) get a profile with the credentials stored for the user.
+// shortcut: PEAP-MSCHAPv2 only; EAP-TLS (certificates) is not offered. The server certificate is checked against the trusted roots.
+use std::ptr::{null, null_mut};
+use windows_sys::{
+ Win32::{Foundation::*, NetworkManagement::WiFi::*, UI::WindowsAndMessaging::PostMessageW},
+ core::GUID,
+};
+
+/// The message a WLAN event posts to the window: wParam = the ACM notification code.
+/// For `wlan_notification_acm_connection_complete` lParam is a `Box<(u32 reason, String profile)>` the window takes back.
+pub const WM_WIFI: u32 = 0x8000 + 1; // WM_APP + 1
+
+/// What a profile for the network needs (from the auth/cipher it announces). None in `Net::sec`: 802.1X, left to Windows.
+#[derive(Clone, Copy, PartialEq, Debug)]
+pub enum Sec {
+ Open,
+ Owe, // "enhanced open": encrypted, no password
+ Wep { shared: bool },
+ Wpa { tkip: bool },
+ Wpa2 { tkip: bool },
+ Wpa3,
+}
+
+impl Sec {
+ fn of(secured: bool, auth: i32, cipher: i32) -> Option<Sec> {
+ let tkip = cipher == DOT11_CIPHER_ALGO_TKIP;
+ let wep = matches!(cipher, DOT11_CIPHER_ALGO_WEP | DOT11_CIPHER_ALGO_WEP40 | DOT11_CIPHER_ALGO_WEP104);
+ Some(match auth {
+ DOT11_AUTH_ALGO_80211_OPEN if !secured => Sec::Open,
+ DOT11_AUTH_ALGO_80211_OPEN if wep => Sec::Wep { shared: false },
+ DOT11_AUTH_ALGO_80211_SHARED_KEY => Sec::Wep { shared: true },
+ DOT11_AUTH_ALGO_OWE => Sec::Owe,
+ DOT11_AUTH_ALGO_WPA_PSK => Sec::Wpa { tkip },
+ DOT11_AUTH_ALGO_RSNA_PSK => Sec::Wpa2 { tkip },
+ DOT11_AUTH_ALGO_WPA3_SAE => Sec::Wpa3,
+ _ => return None,
+ })
+ }
+
+ pub fn needs_key(self) -> bool {
+ !matches!(self, Sec::Open | Sec::Owe)
+ }
+
+ /// (authentication, encryption) as the profile schema names them.
+ fn names(self) -> (&'static str, &'static str) {
+ let enc = |tkip| if tkip { "TKIP" } else { "AES" };
+ match self {
+ Sec::Open => ("open", "none"),
+ Sec::Owe => ("OWE", "AES"),
+ Sec::Wep { shared } => (if shared { "shared" } else { "open" }, "WEP"),
+ Sec::Wpa { tkip } => ("WPAPSK", enc(tkip)),
+ Sec::Wpa2 { tkip } => ("WPA2PSK", enc(tkip)),
+ Sec::Wpa3 => ("WPA3SAE", "AES"),
+ }
+ }
+
+ /// The profile's keyType for `key`, or why the key cannot be right (checked before Windows sees it).
+ fn key_type(self, key: &str) -> Result<&'static str, String> {
+ let hex = |n: usize| key.len() == n && key.bytes().all(|b| b.is_ascii_hexdigit());
+ match self {
+ Sec::Open | Sec::Owe => Ok(""),
+ Sec::Wep { .. } if [5, 13].contains(&key.len()) && key.is_ascii() || hex(10) || hex(26) => Ok("networkKey"),
+ Sec::Wep { .. } => Err(t!("Ключ WEP: 5 или 13 символов (или 10/26 шестнадцатеричных)", "WEP key: 5 or 13 characters (or 10/26 hex digits)").into()),
+ Sec::Wpa { .. } | Sec::Wpa2 { .. } if hex(64) => Ok("networkKey"),
+ _ if (8..=63).contains(&key.len()) => Ok("passPhrase"),
+ _ => Err(t!("Пароль: от 8 до 63 символов", "Password: 8 to 63 characters").into()),
+ }
+ }
+}
+
+#[derive(Clone)]
+pub struct Net {
+ pub ssid: String,
+ pub raw: Vec<u8>, // the SSID's bytes: the name may not be UTF-8
+ pub quality: u32, // 0..=100
+ pub connected: bool,
+ pub profile: Option<String>, // saved profile name: these connect with one click
+ pub sec: Option<Sec>,
+ pub eap: Option<&'static str>, // 802.1X: the authentication the profile names ("WPA2", "WPA")
+ pub iface: GUID, // the adapter that sees it
+}
+
+pub fn same_iface(a: &GUID, b: &GUID) -> bool {
+ (a.data1, a.data2, a.data3, a.data4) == (b.data1, b.data2, b.data3, b.data4)
+}
+
+/// The enterprise authentication a network announces, when this window can sign in to it.
+fn eap_of(secured: bool, auth: i32) -> Option<&'static str> {
+ match auth {
+ DOT11_AUTH_ALGO_RSNA if secured => Some("WPA2"),
+ DOT11_AUTH_ALGO_WPA if secured => Some("WPA"),
+ _ => None,
+ }
+}
+
+struct Client(HANDLE);
+
+impl Drop for Client {
+ fn drop(&mut self) {
+ unsafe { WlanCloseHandle(self.0, null()) };
+ }
+}
+
+/// A WLAN handle and the GUIDs of all Wi-Fi adapters (None without any).
+fn open_all() -> Option<(Client, Vec<GUID>)> {
+ let (mut ver, mut h) = (0u32, null_mut());
+ if unsafe { WlanOpenHandle(WLAN_API_VERSION_2_0, null(), &mut ver, &mut h) } != 0 {
+ return None;
+ }
+ let c = Client(h);
+ let mut list: *mut WLAN_INTERFACE_INFO_LIST = null_mut();
+ if unsafe { WlanEnumInterfaces(h, null(), &mut list) } != 0 || list.is_null() {
+ return None;
+ }
+ let guids: Vec<GUID> = unsafe { std::slice::from_raw_parts((*list).InterfaceInfo.as_ptr(), (*list).dwNumberOfItems as usize).iter().map(|i| i.InterfaceGuid).collect() };
+ unsafe { WlanFreeMemory(list as _) };
+ (!guids.is_empty()).then_some((c, guids))
+}
+
+fn utf16(s: &[u16]) -> String {
+ String::from_utf16_lossy(&s[..s.iter().position(|&c| c == 0).unwrap_or(s.len())])
+}
+
+fn wide(s: &str) -> Vec<u16> {
+ s.encode_utf16().chain([0]).collect()
+}
+
+/// One entry per SSID: Windows lists a saved network twice (with and without its profile), so the entries are merged
+/// (strongest signal, the profile, the connected flag); the connected one first, then by signal.
+fn tidy(v: Vec<Net>) -> Vec<Net> {
+ let mut out: Vec<Net> = vec![];
+ for n in v.into_iter().filter(|n| !n.raw.is_empty()) {
+ match out.iter_mut().find(|o| o.raw == n.raw) {
+ Some(o) => {
+ if n.connected || (!o.connected && n.quality > o.quality) {
+ o.iface = n.iface; // the adapter that is connected, else the one with the better signal
+ }
+ o.quality = o.quality.max(n.quality);
+ o.connected |= n.connected;
+ if o.profile.is_none() {
+ o.profile = n.profile;
+ }
+ }
+ None => out.push(n),
+ }
+ }
+ out.sort_by(|a, b| b.connected.cmp(&a.connected).then(b.quality.cmp(&a.quality)));
+ out
+}
+
+/// Asks the adapter for a fresh scan; the result comes later as `wlan_notification_acm_scan_complete`.
+/// Not on every refresh: a scan makes a connected adapter leave its channel for a moment (ping spikes).
+pub fn scan() {
+ if let Some((c, guids)) = open_all() {
+ for g in guids {
+ unsafe { WlanScan(c.0, &g, null(), null(), null()) };
+ }
+ }
+}
+
+/// Visible networks from the last scan. Empty without a Wi-Fi adapter or with the radio off.
+pub fn list() -> Vec<Net> {
+ let Some((c, guids)) = open_all() else { return vec![] };
+ let mut out = vec![];
+ for guid in guids {
+ let mut nl: *mut WLAN_AVAILABLE_NETWORK_LIST = null_mut();
+ if unsafe { WlanGetAvailableNetworkList(c.0, &guid, 0, null(), &mut nl) } != 0 || nl.is_null() {
+ continue;
+ }
+ let items = unsafe { std::slice::from_raw_parts((*nl).Network.as_ptr(), (*nl).dwNumberOfItems as usize) };
+ out.extend(items.iter().filter(|n| n.dot11BssType == dot11_BSS_type_infrastructure).map(|n| {
+ let raw = n.dot11Ssid.ucSSID[..(n.dot11Ssid.uSSIDLength as usize).min(32)].to_vec();
+ Net {
+ ssid: String::from_utf8_lossy(&raw).into_owned(),
+ raw,
+ quality: n.wlanSignalQuality,
+ connected: n.dwFlags & WLAN_AVAILABLE_NETWORK_CONNECTED != 0,
+ profile: (n.dwFlags & WLAN_AVAILABLE_NETWORK_HAS_PROFILE != 0).then(|| utf16(&n.strProfileName)),
+ sec: Sec::of(n.bSecurityEnabled != 0, n.dot11DefaultAuthAlgorithm, n.dot11DefaultCipherAlgorithm),
+ eap: eap_of(n.bSecurityEnabled != 0, n.dot11DefaultAuthAlgorithm),
+ iface: guid,
+ }
+ }));
+ unsafe { WlanFreeMemory(nl as _) };
+ }
+ tidy(out)
+}
+
+/// (software switch on, hardware switch on) of the adapter's radio; None without a Wi-Fi adapter.
+pub fn radio() -> Option<(bool, bool)> {
+ let (c, guids) = open_all()?;
+ let (mut soft, mut hard, mut any) = (false, true, false);
+ for guid in guids {
+ let (mut n, mut p, mut ty) = (0u32, null_mut(), 0);
+ if unsafe { WlanQueryInterface(c.0, &guid, wlan_intf_opcode_radio_state, null(), &mut n, &mut p, &mut ty) } != 0 || p.is_null() {
+ continue;
+ }
+ let st = unsafe { &*(p as *const WLAN_RADIO_STATE) };
+ let phys = &st.PhyRadioState[..(st.dwNumberOfPhys as usize).min(64)];
+ soft |= phys.iter().any(|x| x.dot11SoftwareRadioState == dot11_radio_state_on);
+ hard &= phys.iter().all(|x| x.dot11HardwareRadioState == dot11_radio_state_on);
+ any = true;
+ unsafe { WlanFreeMemory(p) };
+ }
+ any.then_some((soft, hard))
+}
+
+/// Turns the Wi-Fi radio on or off, in a thread (the WinRT call waits). The window sees the change on its next refresh.
+pub fn set_radio(on: bool) {
+ std::thread::spawn(move || {
+ use windows::Devices::Radios::{Radio, RadioKind, RadioState};
+ let _ = Radio::RequestAccessAsync().and_then(|a| a.join());
+ let Ok(radios) = Radio::GetRadiosAsync().and_then(|a| a.join()) else { return };
+ for r in radios.into_iter().filter(|r| r.Kind().is_ok_and(|k| k == RadioKind::WiFi)) {
+ let _ = r.SetStateAsync(if on { RadioState::On } else { RadioState::Off }).and_then(|a| a.join());
+ }
+ });
+}
+
+/// Starts the connection to a saved profile (the result comes as `wlan_notification_acm_connection_complete`).
+pub fn connect(profile: &str, guid: &GUID) -> bool {
+ let Some((c, _)) = open_all() else { return false };
+ let name = wide(profile);
+ let p = WLAN_CONNECTION_PARAMETERS { wlanConnectionMode: wlan_connection_mode_profile, strProfile: name.as_ptr(), pDot11Ssid: null_mut(), pDesiredBssidList: null_mut(), dot11BssType: dot11_BSS_type_infrastructure, dwFlags: 0 };
+ unsafe { WlanConnect(c.0, guid, &p, null()) == 0 }
+}
+
+pub fn disconnect() -> bool {
+ open_all().is_some_and(|(c, guids)| guids.iter().fold(false, |any, g| unsafe { WlanDisconnect(c.0, g, null()) == 0 } || any))
+}
+
+/// Deletes a saved profile (Windows forgets the password; a connected network drops).
+pub fn forget(profile: &str) -> bool {
+ open_all().is_some_and(|(c, guids)| guids.iter().fold(false, |any, g| unsafe { WlanDeleteProfile(c.0, g, wide(profile).as_ptr(), null()) == 0 } || any))
+}
+
+/// Windows' own (localized) text for a WLAN reason code.
+pub fn reason_text(code: u32) -> String {
+ let mut buf = [0u16; 512];
+ if unsafe { WlanReasonCodeToString(code, buf.len() as u32, buf.as_mut_ptr(), null()) } == 0 {
+ let s = utf16(&buf);
+ if !s.is_empty() {
+ return s;
+ }
+ }
+ tf!("код {}", "code {}", code)
+}
+
+fn xml_escape(s: &str) -> String {
+ s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;").replace('\'', "&apos;")
+}
+
+/// A WLAN profile (schema v1) for one network. The SSID goes in as hex too, so any bytes are matched exactly;
+/// every text is escaped, a password with `<` or `&` cannot change the document.
+fn profile_xml(name: &str, raw: &[u8], sec: Sec, key: &str, key_type: &str, hidden: bool) -> String {
+ let hex: String = raw.iter().map(|b| format!("{b:02X}")).collect();
+ let (auth, enc) = sec.names();
+ let name = xml_escape(name);
+ let hidden = if hidden { "<nonBroadcast>true</nonBroadcast>" } else { "" };
+ let shared = if sec.needs_key() {
+ let idx = if matches!(sec, Sec::Wep { .. }) { "<keyIndex>0</keyIndex>" } else { "" };
+ format!("<sharedKey><keyType>{key_type}</keyType><protected>false</protected><keyMaterial>{}</keyMaterial></sharedKey>{idx}", xml_escape(key))
+ } else {
+ String::new()
+ };
+ format!(
+ r#"<?xml version="1.0"?><WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1"><name>{name}</name><SSIDConfig><SSID><hex>{hex}</hex><name>{name}</name></SSID>{hidden}</SSIDConfig><connectionType>ESS</connectionType><connectionMode>auto</connectionMode><MSM><security><authEncryption><authentication>{auth}</authentication><encryption>{enc}</encryption><useOneX>false</useOneX></authEncryption>{shared}</security></MSM></WLANProfile>"#
+ )
+}
+
+/// Saves a profile for a network that has none and starts connecting. Ok: the profile's name (delete it if the connection
+/// fails, so a wrong password is not kept). Err: a text for the user.
+pub fn add_and_connect(ssid: &str, raw: &[u8], sec: Sec, key: &str, hidden: bool, iface: Option<&GUID>) -> Result<String, String> {
+ let kt = sec.key_type(key)?;
+ let Some((c, guid)) = pick(iface) else { return Err(t!("Нет адаптера Wi-Fi", "No Wi-Fi adapter").into()) };
+ let mut xml = wide(&profile_xml(ssid, raw, sec, key, kt, hidden));
+ let mut reason = 0u32;
+ let rc = unsafe { WlanSetProfile(c.0, &guid, 0, xml.as_ptr(), null(), 1, null(), &mut reason) };
+ xml.iter_mut().for_each(|w| *w = 0); // the password is in there: not left in freed memory
+ if rc != 0 {
+ return Err(if rc == ERROR_ACCESS_DENIED { t!("Windows запретила сохранять сети (политика)", "Windows refused to save networks (policy)").into() } else { tf!("Профиль не принят: {}", "Profile rejected: {}", reason_text(reason)) });
+ }
+ if !connect(ssid, &guid) {
+ forget(ssid);
+ return Err(t!("Не удалось начать подключение", "Could not start connecting").into());
+ }
+ Ok(ssid.to_string())
+}
+
+/// The handle and the adapter to use: `iface` when it is still there, else the first one.
+fn pick(iface: Option<&GUID>) -> Option<(Client, GUID)> {
+ let (c, guids) = open_all()?;
+ let g = iface.and_then(|w| guids.iter().find(|g| same_iface(g, w))).or(guids.first()).copied()?;
+ Some((c, g))
+}
+
+/// The profile of an 802.1X network: WPA/WPA2-Enterprise with PEAP and MSCHAPv2 inside; the credentials come separately (user data).
+/// The server certificate is checked against the system's trusted roots without a prompt (a prompt cannot show in this window).
+fn eap_profile_xml(name: &str, raw: &[u8], auth: &str, hidden: bool) -> String {
+ let hex: String = raw.iter().map(|b| format!("{b:02X}")).collect();
+ let name = xml_escape(name);
+ let enc = if auth == "WPA" { "TKIP" } else { "AES" };
+ let hidden = if hidden { "<nonBroadcast>true</nonBroadcast>" } else { "" };
+ format!(
+ r#"<?xml version="1.0"?><WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1"><name>{name}</name><SSIDConfig><SSID><hex>{hex}</hex><name>{name}</name></SSID>{hidden}</SSIDConfig><connectionType>ESS</connectionType><connectionMode>auto</connectionMode><MSM><security><authEncryption><authentication>{auth}</authentication><encryption>{enc}</encryption><useOneX>true</useOneX></authEncryption><OneX xmlns="http://www.microsoft.com/networking/OneX/v1"><authMode>user</authMode><EAPConfig><EapHostConfig xmlns="http://www.microsoft.com/provisioning/EapHostConfig" xmlns:eapCommon="http://www.microsoft.com/provisioning/EapCommon" xmlns:baseEap="http://www.microsoft.com/provisioning/BaseEapConnectionPropertiesV1"><EapMethod><eapCommon:Type>25</eapCommon:Type><eapCommon:AuthorId>0</eapCommon:AuthorId></EapMethod><Config xmlns:baseEap="http://www.microsoft.com/provisioning/BaseEapConnectionPropertiesV1" xmlns:msPeap="http://www.microsoft.com/provisioning/MsPeapConnectionPropertiesV1" xmlns:msChapV2="http://www.microsoft.com/provisioning/MsChapV2ConnectionPropertiesV1"><baseEap:Eap><baseEap:Type>25</baseEap:Type><msPeap:EapType><msPeap:ServerValidation><msPeap:DisableUserPromptForServerValidation>true</msPeap:DisableUserPromptForServerValidation><msPeap:ServerNames></msPeap:ServerNames></msPeap:ServerValidation><msPeap:FastReconnect>true</msPeap:FastReconnect><msPeap:InnerEapOptional>false</msPeap:InnerEapOptional><baseEap:Eap><baseEap:Type>26</baseEap:Type><msChapV2:EapType><msChapV2:UseWinLogonCredentials>false</msChapV2:UseWinLogonCredentials></msChapV2:EapType></baseEap:Eap><msPeap:EnableQuarantineChecks>false</msPeap:EnableQuarantineChecks><msPeap:RequireCryptoBinding>false</msPeap:RequireCryptoBinding><msPeap:PeapExtensions/></msPeap:EapType></baseEap:Eap></Config></EapHostConfig></EAPConfig></OneX></security></MSM></WLANProfile>"#
+ )
+}
+
+/// The per-user credentials of a PEAP-MSCHAPv2 profile (`domain\user` is split; every text is escaped).
+fn eap_user_xml(user: &str, pass: &str) -> String {
+ let (domain, user) = user.split_once('\\').unwrap_or(("", user));
+ let (d, u, p) = (xml_escape(domain), xml_escape(user), xml_escape(pass));
+ format!(
+ r#"<?xml version="1.0"?><EapHostUserCredentials xmlns="http://www.microsoft.com/provisioning/EapHostUserCredentials" xmlns:eapCommon="http://www.microsoft.com/provisioning/EapCommon" xmlns:baseEap="http://www.microsoft.com/provisioning/BaseEapMethodUserCredentials"><EapMethod><eapCommon:Type>25</eapCommon:Type><eapCommon:AuthorId>0</eapCommon:AuthorId></EapMethod><Credentials xmlns:eapUser="http://www.microsoft.com/provisioning/EapUserPropertiesV1" xmlns:baseEap="http://www.microsoft.com/provisioning/BaseEapUserPropertiesV1" xmlns:MsPeap="http://www.microsoft.com/provisioning/MsPeapUserPropertiesV1" xmlns:MsChapV2="http://www.microsoft.com/provisioning/MsChapV2UserPropertiesV1"><baseEap:Eap><baseEap:Type>25</baseEap:Type><MsPeap:EapType><baseEap:Eap><baseEap:Type>26</baseEap:Type><MsChapV2:EapType><MsChapV2:Username>{u}</MsChapV2:Username><MsChapV2:Password>{p}</MsChapV2:Password><MsChapV2:LogonDomain>{d}</MsChapV2:LogonDomain></MsChapV2:EapType></baseEap:Eap></MsPeap:EapType></baseEap:Eap></Credentials></EapHostUserCredentials>"#
+ )
+}
+
+/// Saves an 802.1X profile with the user's credentials and starts connecting. Ok: the profile's name (deleted again if the
+/// connection fails, so wrong credentials are not kept).
+pub fn add_eap_and_connect(ssid: &str, raw: &[u8], auth: &str, user: &str, pass: &str, hidden: bool, iface: Option<&GUID>) -> Result<String, String> {
+ let Some((c, guid)) = pick(iface) else { return Err(t!("Нет адаптера Wi-Fi", "No Wi-Fi adapter").into()) };
+ let xml = wide(&eap_profile_xml(ssid, raw, auth, hidden));
+ let mut reason = 0u32;
+ let rc = unsafe { WlanSetProfile(c.0, &guid, 0, xml.as_ptr(), null(), 1, null(), &mut reason) };
+ if rc != 0 {
+ return Err(if rc == ERROR_ACCESS_DENIED { t!("Windows запретила сохранять сети (политика)", "Windows refused to save networks (policy)").into() } else { tf!("Профиль не принят: {}", "Profile rejected: {}", reason_text(reason)) });
+ }
+ let mut creds = wide(&eap_user_xml(user, pass));
+ let rc = unsafe { WlanSetProfileEapXmlUserData(c.0, &guid, wide(ssid).as_ptr(), 0, creds.as_ptr(), null()) };
+ creds.fill(0); // the password is in there: not left in freed memory
+ if rc != 0 {
+ forget(ssid);
+ return Err(tf!("Не удалось сохранить учётные данные: {}", "Could not save the credentials: {}", reason_text(rc)));
+ }
+ if !connect(ssid, &guid) {
+ forget(ssid);
+ return Err(t!("Не удалось начать подключение", "Could not start connecting").into());
+ }
+ Ok(ssid.to_string())
+}
+
+unsafe extern "system" fn on_event(d: *mut L2_NOTIFICATION_DATA, ctx: *mut core::ffi::c_void) {
+ let d = unsafe { &*d };
+ if d.NotificationSource != WLAN_NOTIFICATION_SOURCE_ACM {
+ return;
+ }
+ let code = d.NotificationCode as i32;
+ let lp = if code == wlan_notification_acm_connection_complete && !d.pData.is_null() && d.dwDataSize as usize >= size_of::<WLAN_CONNECTION_NOTIFICATION_DATA>() {
+ let c = unsafe { &*(d.pData as *const WLAN_CONNECTION_NOTIFICATION_DATA) };
+ Box::into_raw(Box::new((c.wlanReasonCode, utf16(&c.strProfileName)))) as isize
+ } else if [wlan_notification_acm_scan_complete, wlan_notification_acm_scan_fail, wlan_notification_acm_disconnected, wlan_notification_acm_interface_arrival, wlan_notification_acm_interface_removal].contains(&code) {
+ 0
+ } else {
+ return;
+ };
+ if unsafe { PostMessageW(ctx as HWND, WM_WIFI, code as usize, lp) } == 0 && lp != 0 {
+ drop(unsafe { Box::from_raw(lp as *mut (u32, String)) }); // the window is gone
+ }
+}
+
+/// Sends the window WLAN events for as long as the process lives (the handle is kept open on purpose).
+pub fn watch(hwnd: HWND) {
+ let (mut ver, mut h) = (0u32, null_mut());
+ if unsafe { WlanOpenHandle(WLAN_API_VERSION_2_0, null(), &mut ver, &mut h) } == 0 {
+ unsafe { WlanRegisterNotification(h, WLAN_NOTIFICATION_SOURCE_ACM, 1, Some(on_event), hwnd as _, null(), null_mut()) };
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn n(s: &str, q: u32, c: bool, p: Option<&str>) -> Net {
+ Net { ssid: s.into(), raw: s.as_bytes().to_vec(), quality: q, connected: c, profile: p.map(Into::into), sec: Some(Sec::Wpa2 { tkip: false }), eap: None, iface: unsafe { std::mem::zeroed() } }
+ }
+
+ #[test]
+ fn duplicates_merge_and_the_connected_goes_first() {
+ let v = tidy(vec![n("a", 40, false, Some("a")), n("a", 90, false, None), n("", 99, false, None), n("b", 20, true, Some("b")), n("b", 20, false, None), n("c", 60, false, None)]);
+ let got: Vec<_> = v.iter().map(|x| (x.ssid.as_str(), x.quality, x.connected, x.profile.is_some())).collect();
+ // "a" keeps its saved profile although the stronger entry had none
+ assert_eq!(got, [("b", 20, true, true), ("a", 90, false, true), ("c", 60, false, false)]);
+ }
+
+ #[test]
+ fn the_eap_documents_carry_escaped_credentials_and_split_the_domain() {
+ let u = eap_user_xml("CORP\\ann<", "p&w");
+ assert!(u.contains("<MsChapV2:Username>ann&lt;</MsChapV2:Username>") && u.contains("<MsChapV2:LogonDomain>CORP</MsChapV2:LogonDomain>") && u.contains("<MsChapV2:Password>p&amp;w</MsChapV2:Password>"));
+ assert!(eap_user_xml("bob", "x").contains("<MsChapV2:LogonDomain></MsChapV2:LogonDomain>"));
+ let p = eap_profile_xml("corp", b"corp", "WPA2", false);
+ assert!(p.contains("<useOneX>true</useOneX>") && p.contains("<authentication>WPA2</authentication>") && p.contains("<hex>636F7270</hex>"));
+ assert_eq!(eap_of(true, DOT11_AUTH_ALGO_RSNA), Some("WPA2"));
+ assert_eq!(eap_of(true, DOT11_AUTH_ALGO_RSNA_PSK), None);
+ }
+
+ #[test]
+ fn security_is_read_from_auth_and_cipher() {
+ assert_eq!(Sec::of(false, DOT11_AUTH_ALGO_80211_OPEN, DOT11_CIPHER_ALGO_NONE), Some(Sec::Open));
+ assert_eq!(Sec::of(true, DOT11_AUTH_ALGO_80211_OPEN, DOT11_CIPHER_ALGO_WEP), Some(Sec::Wep { shared: false }));
+ assert_eq!(Sec::of(true, DOT11_AUTH_ALGO_RSNA_PSK, DOT11_CIPHER_ALGO_CCMP), Some(Sec::Wpa2 { tkip: false }));
+ assert_eq!(Sec::of(true, DOT11_AUTH_ALGO_WPA3_SAE, DOT11_CIPHER_ALGO_CCMP), Some(Sec::Wpa3));
+ assert_eq!(Sec::of(true, DOT11_AUTH_ALGO_RSNA, DOT11_CIPHER_ALGO_CCMP), None); // enterprise
+ }
+
+ #[test]
+ fn keys_are_checked_before_windows_sees_them() {
+ let w = Sec::Wpa2 { tkip: false };
+ assert_eq!(w.key_type("1234567"), Err("Пароль: от 8 до 63 символов".into()));
+ assert_eq!(w.key_type("12345678"), Ok("passPhrase"));
+ assert_eq!(w.key_type(&"a".repeat(64)), Ok("networkKey"));
+ assert!(w.key_type(&"z".repeat(64)).is_err());
+ assert!(Sec::Wpa3.key_type(&"a".repeat(64)).is_err());
+ assert_eq!(Sec::Wep { shared: false }.key_type("abcde"), Ok("networkKey"));
+ assert!(Sec::Wep { shared: false }.key_type("abcdef").is_err());
+ assert_eq!(Sec::Open.key_type(""), Ok(""));
+ }
+
+ #[test]
+ fn profile_escapes_text_and_carries_the_ssid_as_hex() {
+ let x = profile_xml("a<b", b"a<b", Sec::Wpa2 { tkip: false }, "p&ss</keyMaterial>", "passPhrase", true);
+ assert!(x.contains("<hex>613C62</hex><name>a&lt;b</name>"));
+ assert!(x.contains("<keyMaterial>p&amp;ss&lt;/keyMaterial&gt;</keyMaterial>"));
+ assert!(x.contains("<nonBroadcast>true</nonBroadcast>") && x.contains("<authentication>WPA2PSK</authentication><encryption>AES</encryption>"));
+ let o = profile_xml("open", b"open", Sec::Open, "", "", false);
+ assert!(!o.contains("sharedKey") && !o.contains("nonBroadcast") && o.contains("<encryption>none</encryption>"));
+ }
+}
+
+#[cfg(test)]
+mod live {
+ use super::*;
+
+ #[test]
+ #[ignore] // prints this machine's Wi-Fi: cargo test -p rust-settings live -- --ignored --nocapture
+ fn print_wifi() {
+ println!("radio: {:?}", radio());
+ for n in list() {
+ println!("{} q={} connected={} profile={:?} sec={:?} eap={:?}", n.ssid, n.quality, n.connected, n.profile, n.sec, n.eap);
+ }
+ }
+}
diff --git a/plugins/rust-settings/src/wu.rs b/plugins/rust-settings/src/wu.rs
new file mode 100644
index 0000000..94cd0fa
--- /dev/null
+++ b/plugins/rust-settings/src/wu.rs
@@ -0,0 +1,119 @@
+//! Windows Update through the Windows Update Agent COM API (documented): look for updates, download and install them.
+//! Searching and installing take minutes, so they run in a thread; the window shows `state()`. Installing needs administrator
+//! rights (Windows says "access denied" otherwise, which is reported as such).
+use std::sync::Mutex;
+use windows::{
+ Win32::System::{
+ Com::{CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx},
+ UpdateAgent::*,
+ },
+ core::BSTR,
+};
+
+#[derive(Clone, Default)]
+pub struct State {
+ pub busy: Option<String>, // what is going on right now
+ pub found: Option<Vec<String>>, // titles of the updates waiting; None: not looked yet
+ pub note: String, // the result of the last action
+}
+
+static STATE: Mutex<State> = Mutex::new(State { busy: None, found: None, note: String::new() });
+
+pub fn state() -> State {
+ STATE.lock().map(|s| s.clone()).unwrap_or_default()
+}
+
+fn with<T>(f: impl FnOnce(&mut State) -> T) {
+ if let Ok(mut s) = STATE.lock() {
+ f(&mut s);
+ }
+}
+
+fn session() -> windows::core::Result<IUpdateSession> {
+ unsafe {
+ let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
+ CoCreateInstance(&UpdateSession, None, CLSCTX_INPROC_SERVER)
+ }
+}
+
+fn search(s: &IUpdateSession) -> windows::core::Result<IUpdateCollection> {
+ unsafe { s.CreateUpdateSearcher()?.Search(&BSTR::from("IsInstalled=0 and IsHidden=0 and Type='Software'"))?.Updates() }
+}
+
+fn titles(c: &IUpdateCollection) -> Vec<String> {
+ unsafe { (0..c.Count().unwrap_or(0)).filter_map(|i| c.get_Item(i).ok()).filter_map(|u| u.Title().ok()).map(|t| t.to_string()).collect() }
+}
+
+fn err_text(e: &windows::core::Error) -> String {
+ if e.code().0 as u32 == 0x8007_0005 {
+ t!("Нужны права администратора", "Administrator rights are needed").into()
+ } else {
+ e.message()
+ }
+}
+
+fn start(what: &str, done: impl FnOnce() + Send + 'static, job: impl FnOnce() -> String + Send + 'static) {
+ let mut busy = true;
+ with(|s| {
+ busy = s.busy.is_some();
+ if !busy {
+ s.busy = Some(what.to_string());
+ }
+ });
+ if busy {
+ return;
+ }
+ std::thread::spawn(move || {
+ let note = job();
+ with(|s| (s.busy, s.note) = (None, note));
+ done();
+ });
+}
+
+/// Looks for updates.
+pub fn check(done: impl FnOnce() + Send + 'static) {
+ start(t!("Поиск обновлений…", "Checking for updates…"), done, || match session().and_then(|s| search(&s)) {
+ Ok(c) => {
+ let t = titles(&c);
+ let note = if t.is_empty() { t!("Обновлений нет: установлены все", "You're up to date").into() } else { tf!("Найдено обновлений: {}", "Updates found: {}", t.len()) };
+ with(|s| s.found = Some(t));
+ note
+ }
+ Err(e) => tf!("Не удалось проверить: {}", "Could not check: {}", err_text(&e)),
+ });
+}
+
+/// Downloads and installs every update found by `check`.
+pub fn install(done: impl FnOnce() + Send + 'static) {
+ start(t!("Загрузка и установка обновлений…", "Downloading and installing updates…"), done, || {
+ let run = || -> windows::core::Result<String> {
+ unsafe {
+ let s = session()?;
+ let found = search(&s)?;
+ if found.Count()? == 0 {
+ return Ok(t!("Обновлений нет: установлены все", "You're up to date").into());
+ }
+ for i in 0..found.Count()? {
+ let u = found.get_Item(i)?;
+ if !u.EulaAccepted()?.as_bool() {
+ u.AcceptEula()?;
+ }
+ }
+ let d = s.CreateUpdateDownloader()?;
+ d.SetUpdates(&found)?;
+ d.Download()?;
+ let inst = s.CreateUpdateInstaller()?;
+ inst.SetUpdates(&found)?;
+ let r = inst.Install()?;
+ Ok(if r.RebootRequired()?.as_bool() { t!("Установлено. Нужна перезагрузка", "Installed. Restart to finish").into() } else { t!("Обновления установлены", "Updates installed").into() })
+ }
+ };
+ match run() {
+ Ok(m) => {
+ with(|s| s.found = Some(vec![]));
+ m
+ }
+ Err(e) => tf!("Не удалось установить: {}", "Could not install: {}", err_text(&e)),
+ }
+ });
+}
diff --git a/plugins/topbar/Cargo.toml b/plugins/topbar/Cargo.toml
index 3631a62..57ebb81 100644
--- a/plugins/topbar/Cargo.toml
+++ b/plugins/topbar/Cargo.toml
@@ -5,6 +5,9 @@ edition = "2024"
[dependencies]
winrust-common = { path = "../../common" }
-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_NetworkManagement_IpHelper", "Win32_Networking_WinSock", "Win32_Security", "Win32_Storage_FileSystem", "Win32_Storage_Packaging_Appx", "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"] }
+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_NetworkManagement_IpHelper", "Win32_Networking_WinSock", "Win32_Security", "Win32_Storage_FileSystem", "Win32_Storage_Packaging_Appx", "Win32_System_DataExchange", "Win32_System_Diagnostics_ToolHelp", "Win32_System_LibraryLoader", "Win32_System_Power", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Accessibility", "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"] }
+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", "Devices_Radios", "Foundation_Collections"] }
+
+[build-dependencies]
+embed-resource = "3"
diff --git a/plugins/topbar/app.ico b/plugins/topbar/app.ico
new file mode 100644
index 0000000..68f8e2e
Binary files /dev/null and b/plugins/topbar/app.ico differ
diff --git a/plugins/topbar/app.rc b/plugins/topbar/app.rc
new file mode 100644
index 0000000..0a9daf1
--- /dev/null
+++ b/plugins/topbar/app.rc
@@ -0,0 +1 @@
+1 ICON "app.ico"
diff --git a/plugins/topbar/build.rs b/plugins/topbar/build.rs
new file mode 100644
index 0000000..e8d32ea
--- /dev/null
+++ b/plugins/topbar/build.rs
@@ -0,0 +1,5 @@
+fn main() {
+ println!("cargo:rerun-if-changed=app.rc");
+ println!("cargo:rerun-if-changed=app.ico");
+ embed_resource::compile("app.rc", embed_resource::NONE).manifest_optional().unwrap();
+}
diff --git a/plugins/topbar/src/clip.rs b/plugins/topbar/src/clip.rs
new file mode 100644
index 0000000..23d81eb
--- /dev/null
+++ b/plugins/topbar/src/clip.rs
@@ -0,0 +1,215 @@
+//! Win+Shift+S: the region clipper. The desktop is copied once, shown dimmed on a full-screen window, and the rectangle the
+//! user drags stays bright. On release that region goes to the clipboard and to Pictures\Screenshots (like PrtSc does);
+//! Esc or the right button cancels. It has its own thread and message loop, so a busy bar cannot stall it.
+use std::{
+ cell::RefCell,
+ ptr::{null, null_mut},
+ sync::{
+ Mutex,
+ atomic::{AtomicBool, Ordering::Relaxed},
+ },
+};
+use windows_sys::Win32::{
+ Foundation::*,
+ Graphics::Gdi::*,
+ System::LibraryLoader::GetModuleHandleW,
+ UI::{Input::KeyboardAndMouse::*, WindowsAndMessaging::*},
+};
+
+/// The file name of the last saved region, for the bar's notice (taken by `clip_notice`).
+pub static DONE: Mutex<Option<String>> = Mutex::new(None);
+static BUSY: AtomicBool = AtomicBool::new(false);
+
+struct St {
+ orig: HBITMAP,
+ dim: HBITMAP,
+ w: i32,
+ h: i32,
+ from: Option<(i32, i32)>,
+ to: (i32, i32),
+}
+
+thread_local! {
+ static ST: RefCell<Option<St>> = const { RefCell::new(None) };
+}
+
+/// The rectangle between two corners, whichever way it was dragged.
+fn rect(a: (i32, i32), b: (i32, i32)) -> RECT {
+ RECT { left: a.0.min(b.0), top: a.1.min(b.1), right: a.0.max(b.0), bottom: a.1.max(b.1) }
+}
+
+fn sel() -> Option<RECT> {
+ ST.with_borrow(|s| s.as_ref().and_then(|s| s.from.map(|f| rect(f, s.to))))
+}
+
+pub fn start() {
+ if BUSY.swap(true, Relaxed) {
+ return;
+ }
+ std::thread::spawn(|| {
+ unsafe { run() };
+ BUSY.store(false, Relaxed);
+ });
+}
+
+unsafe fn run() {
+ let (vx, vy, w, h) = (GetSystemMetrics(SM_XVIRTUALSCREEN), GetSystemMetrics(SM_YVIRTUALSCREEN), GetSystemMetrics(SM_CXVIRTUALSCREEN), GetSystemMetrics(SM_CYVIRTUALSCREEN));
+ if w <= 0 || h <= 0 {
+ return;
+ }
+ let scr = GetDC(null_mut());
+ let (mem, dd, one) = (CreateCompatibleDC(scr), CreateCompatibleDC(scr), CreateCompatibleDC(scr));
+ let (orig, dim, black) = (CreateCompatibleBitmap(scr, w, h), CreateCompatibleBitmap(scr, w, h), CreateCompatibleBitmap(scr, 1, 1));
+ let (o1, o2, o3) = (SelectObject(mem, orig), SelectObject(dd, dim), SelectObject(one, black));
+ BitBlt(mem, 0, 0, w, h, scr, vx, vy, SRCCOPY | 0x4000_0000); // CAPTUREBLT: layered windows too
+ BitBlt(dd, 0, 0, w, h, mem, 0, 0, SRCCOPY);
+ PatBlt(one, 0, 0, 1, 1, BLACKNESS);
+ AlphaBlend(dd, 0, 0, w, h, one, 0, 0, 1, 1, BLENDFUNCTION { BlendOp: 0, BlendFlags: 0, SourceConstantAlpha: 110, AlphaFormat: 0 });
+ SelectObject(mem, o1);
+ SelectObject(dd, o2);
+ SelectObject(one, o3);
+ for d in [mem, dd, one] {
+ DeleteDC(d);
+ }
+ DeleteObject(black);
+ ReleaseDC(null_mut(), scr);
+ ST.set(Some(St { orig, dim, w, h, from: None, to: (0, 0) }));
+
+ let (cls, hi) = (super::wide("WinRustClip"), GetModuleHandleW(null()));
+ let mut wc: WNDCLASSW = std::mem::zeroed();
+ wc.lpfnWndProc = Some(proc);
+ wc.hInstance = hi;
+ wc.hCursor = LoadCursorW(null_mut(), IDC_CROSS);
+ wc.lpszClassName = cls.as_ptr();
+ RegisterClassW(&wc); // 0 when it exists already (a second clip): fine
+ let hw = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW, cls.as_ptr(), null(), WS_POPUP | WS_VISIBLE, vx, vy, w, h, null_mut(), null_mut(), hi, null());
+ if !hw.is_null() {
+ super::force_fg(hw);
+ let mut m: MSG = std::mem::zeroed();
+ while GetMessageW(&mut m, null_mut(), 0, 0) > 0 {
+ TranslateMessage(&m);
+ DispatchMessageW(&m);
+ }
+ }
+ DeleteObject(orig);
+ DeleteObject(dim);
+ ST.set(None);
+}
+
+unsafe fn paint(hw: HWND) {
+ let mut ps: PAINTSTRUCT = std::mem::zeroed();
+ let hdc = BeginPaint(hw, &mut ps);
+ let p = ps.rcPaint;
+ let mem = CreateCompatibleDC(hdc);
+ let (dim, orig) = ST.with_borrow(|s| s.as_ref().map(|s| (s.dim, s.orig))).unwrap_or((null_mut(), null_mut()));
+ let old = SelectObject(mem, dim);
+ BitBlt(hdc, p.left, p.top, p.right - p.left, p.bottom - p.top, mem, p.left, p.top, SRCCOPY);
+ if let Some(r) = sel() {
+ // the bright part: the selection within the dirty area
+ let (l, t, rr, b) = (r.left.max(p.left), r.top.max(p.top), r.right.min(p.right), r.bottom.min(p.bottom));
+ SelectObject(mem, orig);
+ if rr > l && b > t {
+ BitBlt(hdc, l, t, rr - l, b - t, mem, l, t, SRCCOPY);
+ }
+ FrameRect(hdc, &RECT { left: r.left - 1, top: r.top - 1, right: r.right + 1, bottom: r.bottom + 1 }, GetStockObject(WHITE_BRUSH) as HBRUSH);
+ }
+ SelectObject(mem, old);
+ DeleteDC(mem);
+ EndPaint(hw, &ps);
+}
+
+/// Repaint what the selection covered before and covers now.
+unsafe fn dirty(hw: HWND, before: Option<RECT>) {
+ let now = sel();
+ let r = match (before, now) {
+ (Some(a), Some(b)) => RECT { left: a.left.min(b.left), top: a.top.min(b.top), right: a.right.max(b.right), bottom: a.bottom.max(b.bottom) },
+ (Some(a), None) | (None, Some(a)) => a,
+ _ => return,
+ };
+ InvalidateRect(hw, &RECT { left: r.left - 3, top: r.top - 3, right: r.right + 3, bottom: r.bottom + 3 }, 0);
+}
+
+/// Cuts the selected region out of the desktop copy and hands it on.
+unsafe fn finish(hw: HWND) {
+ let (r, orig) = match (sel(), ST.with_borrow(|s| s.as_ref().map(|s| s.orig))) {
+ (Some(r), Some(o)) => (r, o),
+ _ => return DestroyWindow_(hw),
+ };
+ let (rw, rh) = (r.right - r.left, r.bottom - r.top);
+ if rw < 3 || rh < 3 {
+ return DestroyWindow_(hw); // a click, not a drag
+ }
+ let scr = GetDC(null_mut());
+ let (src, dst) = (CreateCompatibleDC(scr), CreateCompatibleDC(scr));
+ let piece = CreateCompatibleBitmap(scr, rw, rh);
+ let (o1, o2) = (SelectObject(src, orig), SelectObject(dst, piece));
+ BitBlt(dst, 0, 0, rw, rh, src, r.left, r.top, SRCCOPY);
+ SelectObject(src, o1);
+ SelectObject(dst, o2);
+ DeleteDC(src);
+ DeleteDC(dst);
+ ReleaseDC(null_mut(), scr);
+ DestroyWindow_(hw); // the dimmed screen goes first; saving takes a moment
+ if let Some(name) = super::save_bitmap(piece) {
+ if let Ok(mut d) = DONE.lock() {
+ *d = Some(name);
+ }
+ PostMessageW(super::BAR.load(Relaxed) as HWND, super::SNIP, 2, 0);
+ }
+}
+
+#[allow(non_snake_case)]
+unsafe fn DestroyWindow_(hw: HWND) {
+ DestroyWindow(hw);
+}
+
+unsafe extern "system" fn proc(hw: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {
+ let pt = ((lp & 0xffff) as i16 as i32, ((lp >> 16) & 0xffff) as i16 as i32);
+ match msg {
+ WM_ERASEBKGND => 1,
+ WM_PAINT => {
+ paint(hw);
+ 0
+ }
+ WM_LBUTTONDOWN => {
+ ST.with_borrow_mut(|s| {
+ if let Some(s) = s {
+ s.from = Some(pt);
+ s.to = pt;
+ }
+ });
+ SetCapture(hw);
+ 0
+ }
+ WM_MOUSEMOVE => {
+ if wp & 1 != 0 && sel().is_some() { // MK_LBUTTON
+ let before = sel();
+ ST.with_borrow_mut(|s| {
+ if let Some(s) = s {
+ s.to = (pt.0.clamp(0, s.w), pt.1.clamp(0, s.h));
+ }
+ });
+ dirty(hw, before);
+ }
+ 0
+ }
+ WM_LBUTTONUP => {
+ ReleaseCapture();
+ finish(hw);
+ 0
+ }
+ WM_RBUTTONDOWN => {
+ DestroyWindow(hw);
+ 0
+ }
+ WM_KEYDOWN if wp == VK_ESCAPE as usize => {
+ DestroyWindow(hw);
+ 0
+ }
+ WM_DESTROY => {
+ PostQuitMessage(0);
+ 0
+ }
+ _ => DefWindowProcW(hw, msg, wp, lp),
+ }
+}
diff --git a/plugins/topbar/src/fly.rs b/plugins/topbar/src/fly.rs
index eff1c1d..d74e77f 100644
--- a/plugins/topbar/src/fly.rs
+++ b/plugins/topbar/src/fly.rs
@@ -25,7 +25,8 @@ enum Act {
Tile(u8),
WifiMore,
Net(usize),
- NetOff, // the connected network's Disconnect button
+ NetOff, // the connected network's Disconnect button (shown on hover)
+ Ctx(u8), // an item of the Wi-Fi panel's right-click menu
Settings(&'static str),
Menu(u8),
CalPrev,
@@ -33,6 +34,14 @@ enum Act {
CalToday,
App(usize), // index into the filtered list
Power(u8), // 0 lock, 1 sleep, 2 restart, 3 shut down
+ Keyboard, // the on-screen keyboard button in the Start search field
+}
+
+/// The touch keyboard (TabTip), else the classic on-screen keyboard. Windows opens it by itself only for the Explorer shell.
+fn touch_keyboard() {
+ let tip = std::env::var_os("CommonProgramFiles").map(|p| std::path::PathBuf::from(p).join(r"microsoft shared\ink\TabTip.exe"));
+ let exe = tip.filter(|p| p.is_file()).unwrap_or_else(|| "osk.exe".into());
+ let _ = std::process::Command::new(exe).spawn();
}
struct Net {
@@ -42,6 +51,7 @@ struct Net {
profile: Option<String>,
connected: bool,
auth: i32,
+ g: windows_sys::core::GUID, // the adapter that sees it
}
struct Conn {
@@ -79,6 +89,7 @@ fn phy_name(t: i32) -> &'static str {
}
static APPS: Mutex<Vec<(String, Vec<u16>)>> = Mutex::new(Vec::new()); // Start menu shortcuts: (name, .lnk path)
+pub static PREVIEW: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); // `--preview`: stays open without focus
static BRIGHT: AtomicI32 = AtomicI32::new(-1); // -1 = no controllable display (desktop PC)
const ROWS: usize = 11;
@@ -90,6 +101,8 @@ thread_local! {
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 CONNECTING: RefCell<Option<(String, u64)>> = const { RefCell::new(None) }; // the network being joined and since when: its row animates
+ static CTX: RefCell<Option<(String, i32, i32, u64)>> = const { RefCell::new(None) }; // Wi-Fi right-click menu: network (by name: the list reorders), x, y (px), opened at
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
@@ -368,27 +381,37 @@ fn set_brightness(v: i32) {
});
}
-/// 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> {
+/// Runs `f` for every Wi-Fi adapter with one open WLAN handle.
+unsafe fn for_each_wlan(mut f: impl FnMut(HANDLE, &windows_sys::core::GUID)) {
let (mut h, mut ver) = (null_mut(), 0u32);
if WlanOpenHandle(2, null(), &mut ver, &mut h) != 0 {
- return None;
+ return;
}
let mut list: *mut WLAN_INTERFACE_INFO_LIST = null_mut();
- let r = if WlanEnumInterfaces(h, null(), &mut list) == 0 {
+ 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 };
+ for i in 0..l.dwNumberOfItems as usize {
+ f(h, &(*l.InterfaceInfo.as_ptr().add(i)).InterfaceGuid);
+ }
WlanFreeMemory(list as *const _);
- r
- } else {
- None
- };
+ }
WlanCloseHandle(h, null());
- r
}
-unsafe fn read_nets() {
- let v = with_wlan(|h, g| {
+/// Runs `f` with an open WLAN handle for the adapter `g`.
+unsafe fn with_iface<T>(g: &windows_sys::core::GUID, 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 r = f(h, g);
+ WlanCloseHandle(h, null());
+ Some(r)
+}
+
+/// The visible networks and the current connection of one adapter.
+unsafe fn read_one(h: HANDLE, g: &windows_sys::core::GUID) -> (Vec<Net>, Option<Conn>) {
+ {
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 {
@@ -400,7 +423,7 @@ unsafe fn read_nets() {
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 };
+ 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, g: *g };
match out.iter_mut().find(|o| o.ssid == net.ssid) {
Some(o) if o.q < net.q => *o = net,
Some(_) => {}
@@ -410,7 +433,6 @@ unsafe fn read_nets() {
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);
@@ -427,19 +449,65 @@ unsafe fn read_nets() {
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 }),
+ 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, g: *g }),
}
}
(out, conn)
+ }
+}
+
+unsafe fn read_nets() {
+ let mut nets: Vec<Net> = vec![];
+ let mut conn: Option<Conn> = None;
+ for_each_wlan(|h, g| {
+ let (o, c) = read_one(h, g);
+ for n in o {
+ // one entry per network: the adapter that is connected to it, else the one with the better signal
+ match nets.iter_mut().find(|x| x.ssid == n.ssid) {
+ Some(x) if (n.connected && !x.connected) || (!x.connected && x.q < n.q) => *x = n,
+ Some(_) => {}
+ None => nets.push(n),
+ }
+ }
+ if conn.is_none() {
+ conn = c;
+ }
});
- let (nets, conn) = v.unzip();
- NETS.set(nets.unwrap_or_default());
- CONN.set(conn.flatten());
+ nets.sort_by_key(|n| (!n.connected, -n.q));
+ nets.truncate(7);
+ NETS.set(nets);
+ CONN.set(conn);
+ // the joining animation ends when the network shows up as connected, or gives up after 25 s
+ let on = NETS.with_borrow(|n| n.iter().find(|n| n.connected).map(|n| n.ssid.clone()));
+ if let Some((ssid, t0)) = CONNECTING.with_borrow(|c| c.clone()) {
+ if on.as_deref() == Some(ssid.as_str()) {
+ CONNECTING.set(None);
+ NOTE.set(String::new());
+ } else if now_ms().saturating_sub(t0) > 25_000 {
+ CONNECTING.set(None);
+ NOTE.set(tf!("Не удалось подключиться к «{ssid}»", "Could not connect to “{ssid}”"));
+ }
+ }
+}
+
+unsafe fn start_connecting(ssid: &str) {
+ CONNECTING.set(Some((ssid.to_string(), now_ms())));
+ NOTE.set(String::new());
}
-unsafe fn wifi_connect(profile: &str) {
+/// Deletes the saved profile of `ssid` (Windows drops the connection if it is the current one).
+unsafe fn forget(ssid: &str) {
+ let Some(p) = NETS.with_borrow(|n| n.iter().find(|n| n.ssid == ssid).and_then(|n| n.profile.clone())) else { return };
+ let w = wide(&p);
+ let mut ok = false;
+ for_each_wlan(|h, g| ok |= WlanDeleteProfile(h, g, w.as_ptr(), null()) == 0);
+ NOTE.set(if ok { tf!("Сеть «{ssid}» забыта", "Forgot “{ssid}”") } else { tf!("Не удалось забыть «{ssid}»", "Could not forget “{ssid}”") });
+ read_nets();
+}
+
+unsafe fn wifi_connect(profile: &str, g: &windows_sys::core::GUID) {
let p = wide(profile);
- with_wlan(|h, g| {
+ with_iface(g, |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, &params, null());
});
@@ -466,12 +534,12 @@ unsafe fn wifi_join(n: &Net, pass: &str) {
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);
+ let ok = with_iface(&n.g, |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));
+ wifi_connect(&n.ssid, &n.g);
+ start_connecting(&n.ssid);
} else {
- NOTE.set("Could not save the network (wrong password format?)".into());
+ NOTE.set(t!("Не удалось сохранить сеть (неверный формат пароля?)", "Could not save the network (wrong password format?)").into());
}
}
@@ -479,7 +547,7 @@ unsafe fn wifi_join(n: &Net, pass: &str) {
fn size(k: Kind) -> (i32, i32) {
match k {
- Kind::Quick => (360, 196 + if BRIGHT.load(Relaxed) >= 0 { 96 } else { 48 } + 64),
+ Kind::Quick => (360, 252 + 44 * sliders()),
Kind::Cal => (330, 340),
Kind::Wifi => (360, wifi_rows().2),
Kind::Start => (560, 640),
@@ -491,21 +559,49 @@ fn size(k: Kind) -> (i32, i32) {
/// y of the "Other 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) = (78, vec![], None);
+ let (mut y, mut rows, mut label) = (64, vec![], None);
for net in n.iter() {
if net.connected {
- rows.push((y, y + 130));
- y += 140;
+ rows.push((y, y + 60));
+ y += 74;
} else {
if label.is_none() {
label = Some(y);
- y += 30;
+ y += 26;
}
- rows.push((y, y + 48));
- y += 48;
+ rows.push((y, y + 46));
+ y += 46;
}
}
- (rows, label, y + if n.is_empty() { 84 } else { 8 } + 50)
+ (rows, label, y + if n.is_empty() { 70 } else { 10 } + 44)
+ })
+}
+
+/// Quick settings: how many slider rows (volume, plus brightness on a laptop).
+fn sliders() -> i32 {
+ if BRIGHT.load(Relaxed) >= 0 { 2 } else { 1 }
+}
+
+const CTX_W: i32 = 196; // right-click menu width, logical px
+const CTX_ROW: i32 = 34;
+
+/// The right-click menu's items for a network: (label, what it does: 0 connect, 1 disconnect, 2 forget, 3 known networks).
+fn ctx_items(ssid: &str) -> Vec<(&'static str, u8)> {
+ NETS.with_borrow(|n| {
+ let Some(n) = n.iter().find(|n| n.ssid == ssid) else { return vec![] };
+ let mut v = vec![if n.connected { (t!("Отключиться", "Disconnect"), 1) } else { (t!("Подключиться", "Connect"), 0) }];
+ if n.profile.is_some() {
+ v.push((t!("Забыть сеть", "Forget network"), 2));
+ }
+ v.push((t!("Известные сети…", "Known networks…"), 3));
+ v
+ })
+}
+
+fn ctx_rects() -> Vec<(RECT, Act)> {
+ CTX.with_borrow(|c| match c {
+ Some((ssid, x, y, _)) => (0..ctx_items(ssid).len() as i32).map(|j| (RECT { left: x + sc(6), top: y + sc(6 + CTX_ROW * j), right: x + sc(CTX_W - 6), bottom: y + sc(6 + CTX_ROW * (j + 1)) }, Act::Ctx(j as u8))).collect(),
+ None => vec![],
})
}
@@ -517,19 +613,23 @@ 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;
+ // a 3x2 grid of tiles; the Wi-Fi tile has a round "more" button in its corner (found first: act_at searches backwards)
+ let mut v = vec![];
+ for i in 0..6u8 {
+ let (tl, tt) = (16 + 112 * (i as i32 % 3), 16 + 84 * (i as i32 / 3));
+ v.push((r(tl, tt, tl + 104, tt + 76), Act::Tile(i)));
+ if i == 0 {
+ v.push((r(tl + 66, tt + 8, tl + 96, tt + 38), Act::WifiMore));
+ }
+ }
+ let mut y = 188;
if BRIGHT.load(Relaxed) >= 0 {
- v.push((r(60, y, w - 16, y + 40), Act::BrightSlide));
- y += 48;
+ v.push((r(64, y, w - 24, y + 40), Act::BrightSlide));
+ y += 44;
}
- 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.push((r(24, y, 60, y + 40), Act::Mute));
+ v.push((r(64, y, w - 24, y + 40), Act::VolSlide));
+ v.push((r(w - 54, h - 50, w - 14, h - 10), 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)],
@@ -537,11 +637,12 @@ fn rects(k: Kind) -> Vec<(RECT, Act)> {
let rows = wifi_rows().0;
let mut v: Vec<_> = rows.iter().enumerate().map(|(i, &(t, b))| (r(12, t, w - 12, b), Act::Net(i))).collect();
if let Some(i) = NETS.with_borrow(|n| n.iter().position(|n| n.connected)) {
- let b = rows[i].1;
- v.push((r(w - 24 - 116, b - 42, w - 24, b - 12), Act::NetOff));
+ let (t, b) = rows[i];
+ v.push((r(w - 12 - 108, t + 14, w - 24, b - 14), Act::NetOff));
}
- v.push((r(w - 66, 24, w - 18, 48), Act::WifiSwitch));
- v.push((r(12, h - 48, w - 12, h - 12), Act::Settings("ms-settings:network-wifi")));
+ v.push((r(w - 58, 18, w - 16, 42), Act::WifiSwitch));
+ v.push((r(12, h - 44, w - 12, h - 8), Act::Settings("ms-settings:network-wifi")));
+ v.extend(ctx_rects()); // last: on top of the rows
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(),
@@ -550,6 +651,7 @@ fn rects(k: Kind) -> Vec<(RECT, Act)> {
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.push((r(w - 58, 24, w - 26, 52), Act::Keyboard)); // inside the search field, at its right end
v
}
}
@@ -742,6 +844,7 @@ pub fn toggle(k: Kind) {
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
+ CTX.set(None);
QUERY.set(String::new());
SCROLL.set(0);
SEL.set(0);
@@ -754,12 +857,13 @@ pub fn toggle(k: Kind) {
CAL.set((t.wYear as i32, t.wMonth as i32));
match k {
Kind::Wifi => {
- with_wlan(|h, g| WlanScan(h, g, null(), null(), null()));
+ for_each_wlan(|h, g| _ = WlanScan(h, g, null(), null(), null()));
read_nets();
}
Kind::Quick => {
read_brightness();
read_nets();
+ crate::quick::refresh();
}
Kind::Start => {
pinned_load(); // the search card (rs-launcher) can add to this list from another process
@@ -808,9 +912,9 @@ unsafe fn slide(a: Act, x: i32, rect: RECT) {
}
}
-/// Wi-Fi radio on/off (the Wi-Fi tile). shortcut: software radio of the first adapter / first PHY only.
+/// Wi-Fi radio on/off (the Wi-Fi tile), software radio of every adapter (first PHY of each).
unsafe fn wifi_radio(on: bool) {
- with_wlan(|h, g| {
+ for_each_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());
});
@@ -874,10 +978,30 @@ unsafe fn run_act(a: Act, rect: RECT, x: i32) {
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();
+ 1 => match crate::quick::bluetooth() {
+ Some(on) => crate::quick::set(false, !on),
+ None => NOTE.set(t!("Нет адаптера Bluetooth", "No Bluetooth adapter").into()),
+ },
+ 2 => crate::quick::set(true, !crate::quick::airplane().unwrap_or(false)),
+ 3 => {
+ let mut pt: POINT = zeroed();
+ GetCursorPos(&mut pt);
+ let (nar, mag) = (crate::quick::running("Narrator.exe"), crate::quick::running("Magnify.exe"));
+ let (sticky, filter) = (crate::quick::sticky_keys(), crate::quick::filter_keys());
+ let items = vec![
+ MItem::new(t!("Экранный диктор", "Narrator")).hint("Win+Ctrl+Enter").on(nar),
+ MItem::new(t!("Экранная лупа", "Magnifier")).hint("Win +/Esc").on(mag),
+ MItem::new(t!("Залипание клавиш", "Sticky keys")).on(sticky).sep(),
+ MItem::new(t!("Фильтрация ввода", "Filter keys")).on(filter),
+ ];
+ menu(pt.x, None, items, move |i| match i {
+ 0 => keys(&[VK_LWIN, VK_CONTROL, VK_RETURN]),
+ 1 => keys(if mag { &[VK_LWIN, VK_ESCAPE] } else { &[VK_LWIN, VK_OEM_PLUS] }),
+ 2 => crate::quick::set_keys(false, !sticky),
+ _ => crate::quick::set_keys(true, !filter),
+ });
}
+ _ => crate::quick::set_energy_saver(!crate::quick::energy_saver()),
},
Act::Mute => toggle_mute(),
Act::Menu(i) => {
@@ -890,6 +1014,7 @@ unsafe fn run_act(a: Act, rect: RECT, x: i32) {
open(&wide(u));
close();
}
+ Act::Keyboard => touch_keyboard(), // the panel stays open: the keys go to its search field
Act::CalPrev | Act::CalNext => {
let (mut y, mut m) = CAL.get();
m += if a == Act::CalNext { 1 } else { -1 };
@@ -902,13 +1027,13 @@ unsafe fn run_act(a: Act, rect: RECT, x: i32) {
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 };
+ let n = NETS.with_borrow(|n| n.get(i).map(|n| (n.connected, n.profile.clone(), n.auth, n.secure, n.ssid.clone(), n.g)));
+ let Some((connected, profile, auth, secure, ssid, iface)) = n else { return };
if connected {
// the card is information; its Disconnect button is the action
} else if let Some(p) = profile {
- wifi_connect(&p);
- NOTE.set(tf!("Подключение к {ssid}…", "Connecting to {ssid}…"));
+ wifi_connect(&p, &iface);
+ start_connecting(&ssid);
} else if !secure {
NETS.with_borrow(|l| wifi_join(&l[i], ""));
} else if matches!(auth, 4 | 7 | 8 | 9) {
@@ -919,9 +1044,26 @@ unsafe fn run_act(a: Act, rect: RECT, x: i32) {
}
}
Act::NetOff => {
- with_wlan(|h, g| WlanDisconnect(h, g, null()));
+ for_each_wlan(|h, g| _ = WlanDisconnect(h, g, null()));
NOTE.set(t!("Отключено", "Disconnected").into());
}
+ Act::Ctx(j) => {
+ let Some((ssid, ..)) = CTX.take() else { return };
+ match ctx_items(&ssid).get(j as usize).map(|i| i.1) {
+ Some(0) => {
+ if let Some(i) = NETS.with_borrow(|n| n.iter().position(|n| n.ssid == ssid)) {
+ run_act(Act::Net(i), rect, x);
+ }
+ }
+ Some(1) => run_act(Act::NetOff, rect, x),
+ Some(2) => forget(&ssid),
+ Some(3) => {
+ open(&wide("ms-settings:network-wifisettings"));
+ close();
+ }
+ _ => {}
+ }
+ }
Act::App(i) => {
if launch(i) {
close();
@@ -976,12 +1118,29 @@ fn sleep_now() {
// ---------- painting ----------
+/// A slider: a thick rounded track filled in the accent up to `frac`, and a white knob with a soft shadow.
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) }, mix(pal().line, pal().dim, 0.3), sc(4));
+ let (l, rr, m, th) = (rc.left + sc(10), rc.right - sc(10), (rc.top + rc.bottom) / 2, sc(3));
+ fill(dc, RECT { left: l, top: m - th, right: rr, bottom: m + th }, mix(card(), pal().text, 0.12), 2 * th);
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) }, pal().accent, sc(4));
- fill(dc, RECT { left: x - sc(8), top: m - sc(8), right: x + sc(8), bottom: m + sc(8) }, pal().text, sc(16));
+ fill(dc, RECT { left: l, top: m - th, right: x.max(l + 2 * th), bottom: m + th }, pal().accent, 2 * th);
+ let kr = sc(10);
+ fill(dc, RECT { left: x - kr - 1, top: m - kr, right: x + kr + 1, bottom: m + kr + sc(2) }, mix(card(), 0, 0.22), 2 * kr + 2);
+ fill(dc, RECT { left: x - kr, top: m - kr, right: x + kr, bottom: m + kr }, if style().light() { rgb(255, 255, 255) } else { mix(pal().text, card(), 0.04) }, 2 * kr);
+}
+
+/// A raised rounded surface: a hairline edge (a soft shadow on the light style) around `base`.
+unsafe fn surface(dc: HDC, rc: RECT, base: u32, rad: i32) {
+ let light = style().light();
+ if light {
+ fill(dc, RECT { top: rc.top + sc(1), bottom: rc.bottom + sc(2), ..rc }, mix(pal().bg, pal().dim, 0.16), rad);
+ }
+ fill(dc, rc, if light { mix(pal().bg, pal().line, 0.9) } else { mix(base, pal().text, 0.07) }, rad);
+ fill(dc, RECT { left: rc.left + 1, top: rc.top + 1, right: rc.right - 1, bottom: rc.bottom - 1 }, base, rad - 2);
+}
+
+fn inset(rc: RECT, d: i32) -> RECT {
+ RECT { left: rc.left + d, top: rc.top + d, right: rc.right - d, bottom: rc.bottom - d }
}
unsafe fn paint(hw: HWND, k: Kind) {
@@ -992,12 +1151,15 @@ unsafe fn paint(hw: HWND, k: Kind) {
BUSY.set(false);
let (dc, bmp) = (CreateCompatibleDC(wdc), CreateCompatibleBitmap(wdc, cr.right, cr.bottom));
let old = SelectObject(dc, bmp);
- fill(dc, cr, pal().line, sc(16));
- fill(dc, RECT { left: 1, top: 1, right: cr.right - 1, bottom: cr.bottom - 1 }, pal().bg, sc(16));
+ fill(dc, cr, if style().light() { mix(pal().bg, pal().dim, 0.3) } else { mix(pal().bg, pal().text, 0.12) }, sc(16));
+ fill(dc, inset(cr, 1), pal().bg, sc(16));
+ winrust_common::style::backdrop(dc, inset(cr, 1), sc(100) as f32 / 100.0);
SetBkMode(dc, TRANSPARENT as i32);
- let (face, gface) = (wide(ui_face()), wide("Segoe MDL2 Assets"));
+ let (face, gface) = (wide(ui_face()), wide(winrust_common::style::icon_face()));
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 (f_semi, f_head, f_gs, f_label) = (font(&face, 13, 600), font(&face, 18, 700), font(&gface, 11, 400), font(&face, 12, 600));
+ let card = card();
let of = SelectObject(dc, f_txt);
let (w, h) = size(k);
let over = OVER.get();
@@ -1009,58 +1171,88 @@ unsafe fn paint(hw: HWND, k: Kind) {
match k {
Kind::Quick => {
let rs = rects(k);
+ let q = WIFI.get();
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 { pal().accent } else { pal().line }, sc(8));
- fill(dc, RECT { left: full.left + 1, top: full.top + 1, right: full.right - 1, bottom: full.bottom - 1 }, if on { pal().accent } else { mix(pal().bg, pal().line, 0.5) }, 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 { pal().accent } else { mix(pal().bg, pal().line, 0.5) }, if on { mix(pal().accent, pal().text, 0.3) } else { pal().hover }, sc(8));
- }
- SelectObject(dc, f_glyph);
- let gr = if i == 0 { r(tl, tt, tl + 68, tt + 56) } else { full };
+ let wsub = match (q >= 0, ssid) {
+ (true, Some(s)) => s,
+ (true, None) => t!("Подключено", "Connected").into(),
+ _ if NETS.with_borrow(|n| n.is_empty()) => t!("Выключен", "Off").into(),
+ _ => t!("Не подключено", "Not connected").into(),
+ };
+ let (bt, air, acc, eco) = (crate::quick::bluetooth(), crate::quick::airplane(), crate::quick::accessibility_on(), crate::quick::energy_saver());
+ let onoff = |b: Option<bool>| match b {
+ Some(true) => t!("Вкл.", "On").to_string(),
+ Some(false) => t!("Выкл.", "Off").to_string(),
+ None => t!("Нет", "None").to_string(),
+ };
+ let states = [q >= 0, bt == Some(true), air == Some(true), acc, eco, false];
+ let tiles = [
+ ("\u{E701}", "Wi‑Fi".to_string(), wsub),
+ ("\u{E702}", "Bluetooth".to_string(), onoff(bt)),
+ ("\u{E709}", t!("Авиарежим", "Airplane mode").to_string(), onoff(air)),
+ ("\u{E776}", t!("Спец. возможности", "Accessibility").to_string(), onoff(Some(acc))),
+ ("\u{E945}", t!("Экономия энергии", "Energy saver").to_string(), onoff(Some(eco))),
+ ("\u{E7F0}", t!("Субтитры", "Live captions").to_string(), String::new()),
+ ];
+ for (i, (glyph, label, sub)) in tiles.iter().enumerate() {
+ let (tl, tt) = (16 + 112 * (i as i32 % 3), 16 + 84 * (i as i32 / 3));
+ let full = r(tl, tt, tl + 104, tt + 76);
+ let on = states[i];
+ let base = if on { mix(card, pal().accent, 0.12) } else { card };
+ surface(dc, full, base, sc(18));
+ g(Act::Tile(i as u8), inset(full, 1), base, mix(base, pal().text, 0.05), sc(16));
+ // the round icon badge: lit in the accent when on
+ let badge = r(tl + 12, tt + 12, tl + 44, tt + 44);
+ fill(dc, badge, if on { pal().accent } else { mix(card, pal().text, 0.08) }, sc(32));
+ let ink = if on { on_accent() } else { pal().text };
if i == 0 {
// the same arcs as the bar: lit by the signal, a cross when not connected
- let c = if on { pal().bg } else { pal().text };
- let q = WIFI.get();
- wifi_glyph(dc, (gr.left + gr.right) / 2, (gr.top + gr.bottom) / 2, sc(20), if q >= 0 { arcs_lit(q) } else { 0 }, c, mix(c, if on { pal().accent } else { pal().bg }, 0.55), if q < 0 { 1 } else { 0 });
+ wifi_glyph(dc, (badge.left + badge.right) / 2, (badge.top + badge.bottom) / 2 - sc(1), sc(15), if q >= 0 { arcs_lit(q) } else { 0 }, ink, mix(ink, if on { pal().accent } else { card }, 0.55), if q < 0 { 1 } else { 0 });
+ let more = rs.iter().find(|(_, a)| *a == Act::WifiMore).unwrap().0;
+ g(Act::WifiMore, more, base, mix(base, pal().text, 0.1), sc(30));
+ SelectObject(dc, f_gs);
+ text(dc, "\u{E76C}", more, pal().dim, DT_CENTER);
} else {
- text(dc, glyph, gr, if on { pal().bg } else { pal().text }, DT_CENTER);
+ SelectObject(dc, f_glyph);
+ text(dc, glyph, badge, ink, DT_CENTER);
}
- if i == 0 {
- fill(dc, r(tl + 68, tt + 12, tl + 69, tt + 44), if on { pal().bg } else { pal().line }, 0);
- text(dc, "\u{E76C}", r(tl + 68, tt, tl + 104, tt + 56), if on { pal().bg } else { pal().text }, DT_CENTER);
+ SelectObject(dc, f_label);
+ text(dc, label.as_str(), r(tl + 12, tt + 46, tl + 102, tt + 62), pal().text, DT_LEFT);
+ if !sub.is_empty() {
+ SelectObject(dc, f_small);
+ text(dc, sub, r(tl + 12, tt + 61, tl + 100, tt + 75), pal().dim, DT_LEFT);
}
- SelectObject(dc, f_small);
- text(dc, label, r(tl, tt + 60, tl + 104, tt + 82), pal().text, DT_CENTER);
}
- let mut y = 196;
+ // sliders sit together on one card
+ let n = sliders();
+ surface(dc, r(16, 184, w - 16, 192 + 44 * n), card, sc(18));
+ let mut y = 188;
let b = BRIGHT.load(Relaxed);
if b >= 0 {
SelectObject(dc, f_glyph);
- text(dc, "\u{E706}", r(16, y, 52, y + 40), pal().text, DT_CENTER);
+ text(dc, "\u{E706}", r(24, y, 60, y + 40), mix(pal().dim, pal().text, 0.5), DT_CENTER);
track(dc, rs.iter().find(|(_, a)| *a == Act::BrightSlide).unwrap().0, b as f32 / 100.0);
- y += 48;
+ y += 44;
}
- g(Act::Mute, r(16, y, 52, y + 40), pal().bg, pal().hover, sc(8));
+ g(Act::Mute, r(24, y + 2, 60, y + 38), card, mix(card, pal().text, 0.08), sc(36));
SelectObject(dc, f_glyph);
- text(dc, if muted || vol == 0 { "\u{E74F}" } else { "\u{E767}" }, r(16, y, 52, y + 40), pal().text, DT_CENTER);
+ text(dc, if muted || vol == 0 { "\u{E74F}" } else { "\u{E767}" }, r(24, y, 60, y + 40), if muted { BAD } else { mix(pal().dim, pal().text, 0.5) }, 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), pal().line, 0);
+ // footer: the battery in a pill, the settings gear in a circle
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 { pal().text }, DT_CENTER);
- SelectObject(dc, f_txt);
- text(dc, &format!("{pct}%"), r(48, h - 48, 140, h - 8), pal().text, DT_LEFT);
+ let pill = r(16, h - 48, 102, h - 12);
+ surface(dc, pill, card, sc(36));
+ SelectObject(dc, f_glyph);
+ text(dc, if ac { "\u{E83E}" } else { "\u{E83F}" }, r(26, h - 48, 50, h - 12), if ac { GOOD } else if pct <= 15 { BAD } else { pal().text }, DT_CENTER);
+ SelectObject(dc, f_semi);
+ text(dc, &format!("{pct}%"), r(54, h - 48, 98, h - 12), pal().text, DT_LEFT);
}
- g(Act::Settings("ms-settings:"), r(w - 52, h - 48, w - 12, h - 8), pal().bg, pal().hover, sc(8));
+ let gear = r(w - 54, h - 50, w - 14, h - 10);
+ surface(dc, gear, card, sc(40));
+ g(Act::Settings("ms-settings:"), inset(gear, 1), card, mix(card, pal().text, 0.08), sc(38));
SelectObject(dc, f_glyph);
- text(dc, "\u{E713}", r(w - 52, h - 48, w - 12, h - 8), pal().text, DT_CENTER);
+ text(dc, "\u{E713}", gear, pal().text, DT_CENTER);
}
Kind::Cal => {
let (y, m) = CAL.get();
@@ -1097,128 +1289,187 @@ unsafe fn paint(hw: HWND, k: Kind) {
Kind::Wifi => {
let on = NETS.with_borrow(|n| !n.is_empty()) || WIFI.get() >= 0;
let state = net();
- // header: the live network icon, the title and one line of plain status
- net_icon(dc, sc(34), sc(40), sc(26), f_glyph);
- SelectObject(dc, f_title);
- text(dc, "Wi‑Fi", r(64, 18, w - 90, 40), pal().text, DT_LEFT);
+ // header: the title, and a status line only when it says something the list does not
let note = NOTE.with_borrow(|n| n.clone());
- let (sub, sub_col) = if !note.is_empty() {
- (note, pal().dim)
+ let sub = if !note.is_empty() {
+ Some((note, pal().dim))
} else {
match state {
- Link::Wifi(_) => (t!("Подключено · интернет есть", "Connected · online").to_string(), GOOD),
- Link::NoInternet(_) => (t!("Подключено, но интернета нет", "Connected, no internet").into(), WARN),
- Link::Cable => (t!("Интернет по кабелю", "Online over a cable").into(), pal().dim),
- Link::Offline if on => (t!("Не подключено", "Not connected").into(), pal().dim),
- Link::Offline => (t!("Выключен", "Turned off").into(), pal().dim),
+ Link::Wifi(_) => None,
+ Link::NoInternet(_) => Some((t!("Подключено, но интернета нет", "Connected, no internet").to_string(), WARN)),
+ Link::Cable => Some((t!("Интернет по кабелю", "Online over a cable").into(), pal().dim)),
+ Link::Offline if on => Some((t!("Не подключено", "Not connected").into(), pal().dim)),
+ Link::Offline => Some((t!("Выключен", "Turned off").into(), pal().dim)),
}
};
- SelectObject(dc, f_small);
- text(dc, &sub, r(64, 40, w - 90, 60), sub_col, DT_LEFT);
- // on/off switch: the knob glides, the track fades to the accent
- let sw = r(w - 66, 24, w - 18, 48);
+ SelectObject(dc, f_title);
+ match &sub {
+ Some((s, c)) => {
+ text(dc, "Wi‑Fi", r(18, 13, w - 76, 33), pal().text, DT_LEFT);
+ SelectObject(dc, f_small);
+ text(dc, s, r(18, 33, w - 76, 51), *c, DT_LEFT);
+ }
+ None => text(dc, "Wi‑Fi", r(18, 18, w - 76, 42), pal().text, DT_LEFT),
+ }
+ // switch: the track fades to the accent, a white knob glides across
+ let sw = r(w - 58, 18, w - 16, 42);
let ts = ease(hv(1_500_000, on));
- fill(dc, sw, mix(mix(pal().line, pal().dim, 0.25), pal().accent, ts), sc(24));
- let kx = sw.left + sc(12) + ((sw.right - sw.left - sc(24)) as f32 * ts) as i32;
- fill(dc, RECT { left: kx - sc(8), top: sw.top + sc(4), right: kx + sc(8), bottom: sw.bottom - sc(4) }, mix(pal().text, pal().bg, ts), sc(16));
- fill(dc, r(16, 68, w - 16, 69), pal().line, 0);
+ let swh = sw.bottom - sw.top;
+ fill(dc, sw, mix(mix(card, pal().text, 0.18), pal().accent, ts), swh);
+ let kr = swh / 2 - sc(2);
+ let kx = sw.left + swh / 2 + ((sw.right - sw.left - swh) as f32 * ts) as i32;
+ let ky = (sw.top + sw.bottom) / 2;
+ fill(dc, RECT { left: kx - kr, top: ky - kr, right: kx + kr, bottom: ky + kr }, rgb(255, 255, 255), 2 * kr);
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, &tf!("Пароль для «{name}»", "Password for “{name}”"), r(18, 82, w - 18, 106), pal().text, DT_LEFT);
- fill(dc, r(16, 112, w - 16, 150), pal().accent, sc(8));
- fill(dc, r(17, 113, w - 17, 149), mix(pal().bg, 0, 0.35), sc(8));
+ text(dc, &tf!("Пароль для «{name}»", "Password for “{name}”"), r(18, 62, w - 18, 84), pal().text, DT_LEFT);
+ fill(dc, r(16, 90, w - 16, 128), pal().accent, sc(10));
+ fill(dc, r(18, 92, w - 18, 126), card, sc(8));
let dots = "•".repeat(p.chars().count());
- text(dc, &dots, r(30, 112, w - 30, 150), pal().text, DT_LEFT);
+ text(dc, &dots, r(30, 90, w - 30, 128), pal().text, DT_LEFT);
// a blinking caret after the dots
if now_ms() / 530 % 2 == 0 {
let mut tr = RECT { left: 0, top: 0, right: 0, bottom: 0 };
let wd = wide(&dots);
DrawTextW(dc, wd.as_ptr(), -1, &mut tr, DT_CALCRECT | DT_SINGLELINE | DT_NOPREFIX);
let cx = sc(30) + tr.right - tr.left + sc(2);
- fill(dc, RECT { left: cx, top: sc(122), right: cx + sc(2), bottom: sc(140) }, pal().accent, 0);
+ fill(dc, RECT { left: cx, top: sc(100), right: cx + sc(2), bottom: sc(118) }, pal().accent, 0);
}
BUSY.set(true);
SelectObject(dc, f_small);
- text(dc, t!("Enter — подключиться · Esc — отмена", "Enter — connect · Esc — cancel"), r(18, 158, w - 18, 180), pal().dim, DT_LEFT);
+ text(dc, t!("Enter — подключиться · Esc — отмена", "Enter — connect · Esc — cancel"), r(18, 136, w - 18, 156), pal().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)));
+ let (rows, label, _) = wifi_rows();
+ let conn = CONN.with_borrow(|c| c.as_ref().map(|c| (c.q, c.phy, c.rx, c.tx)));
+ let joining = CONNECTING.with_borrow(|c| c.as_ref().map(|c| c.0.clone()));
let age = now_ms().saturating_sub(T0.get()) as f32;
+ let now = now_ms();
NETS.with_borrow(|nets| {
if nets.is_empty() {
SelectObject(dc, f_txt);
- text(dc, if on { t!("Рядом нет сетей", "No networks nearby") } else { t!("Включите Wi‑Fi, чтобы увидеть сети", "Turn Wi‑Fi on to see networks") }, r(18, 86, w - 18, 130), pal().dim, DT_LEFT);
+ text(dc, if on { t!("Рядом нет сетей", "No networks nearby") } else { t!("Включите Wi‑Fi, чтобы увидеть сети", "Turn Wi‑Fi on to see networks") }, r(18, 70, w - 18, 110), pal().dim, DT_LEFT);
}
if let Some(ly) = label {
SelectObject(dc, f_small);
- text(dc, t!("Другие сети", "Other networks"), r(20, ly + 6, w - 16, ly + 26), pal().dim, DT_LEFT);
+ text(dc, t!("Другие сети", "Other networks"), r(20, ly + 2, w - 16, ly + 22), pal().dim, DT_LEFT);
+ }
+ // the connected network on its own card, the others together on one, split by hairlines
+ let others: Vec<usize> = (0..nets.len()).filter(|&i| !nets[i].connected).collect();
+ if let (Some(&a), Some(&b)) = (others.first(), others.last()) {
+ surface(dc, r(12, rows[a].0, w - 12, rows[b].1), card, sc(14));
}
for (i, n) in nets.iter().enumerate() {
let rc = rs[i].0;
// rows fade in one after another when the panel opens
- let t = ease(((age - 45.0 * i as f32) / 240.0).clamp(0.0, 1.0));
+ let t = ease(((age - 40.0 * i as f32) / 220.0).clamp(0.0, 1.0));
if t < 1.0 {
BUSY.set(true);
}
- let ink = |c: u32| mix(pal().bg, c, t);
- let lit = arcs_lit(n.q);
+ let ink = |c: u32| mix(card, c, t);
+ let busy = joining.as_deref() == Some(n.ssid.as_str());
if n.connected {
- let card = mix(pal().bg, pal().active, 0.85);
- fill(dc, rc, mix(pal().bg, card, t), sc(12));
- let online = !matches!(state, Link::NoInternet(_));
- wifi_glyph(dc, rc.left + sc(30), rc.top + sc(32), sc(26), lit, ink(pal().accent), ink(mix(pal().dim, card, 0.45)), if online { 0 } else { 2 });
- SelectObject(dc, f_title);
- text(dc, &n.ssid, RECT { left: rc.left + sc(60), top: rc.top + sc(12), right: rc.right - sc(14), bottom: rc.top + sc(36) }, ink(pal().text), DT_LEFT);
- let (dot, words) = if online { (GOOD, t!("Интернет есть", "Online")) } else { (WARN, t!("Нет интернета", "No internet")) };
- let dy = rc.top + sc(46);
- fill(dc, RECT { left: rc.left + sc(60), top: dy - sc(3), right: rc.left + sc(66), bottom: dy + sc(3) }, ink(dot), sc(6));
- SelectObject(dc, f_small);
- text(dc, words, RECT { left: rc.left + sc(72), top: dy - sc(10), right: rc.right - sc(14), bottom: dy + sc(10) }, ink(dot), DT_LEFT);
+ surface(dc, rc, card, sc(14));
+ } else if others.last() != Some(&i) {
+ fill(dc, RECT { left: rc.left + sc(48), top: rc.bottom - 1, right: rc.right - sc(14), bottom: rc.bottom }, mix(card, pal().text, 0.08), 0);
+ }
+ let open = hot(Act::Net(i)) || (n.connected && hot(Act::NetOff));
+ g(Act::Net(i), RECT { left: rc.left + sc(4), top: rc.top + sc(4), right: rc.right - sc(4), bottom: rc.bottom - sc(4) }, card, mix(card, pal().text, 0.045), sc(10));
+ // signal arcs; while joining they sweep up one after another
+ let lit = if busy { BUSY.set(true); (now / 230 % 4) as i32 } else { arcs_lit(n.q) };
+ let online = !matches!(state, Link::NoInternet(_));
+ let cy = (rc.top + rc.bottom) / 2;
+ let arc = if n.connected || busy { pal().accent } else { pal().text };
+ wifi_glyph(dc, rc.left + sc(26), cy - sc(1), sc(16), lit, ink(arc), ink(mix(pal().dim, card, 0.55)), if n.connected && !online { 2 } else { 0 });
+ let saved = n.profile.is_some();
+ let (sub, sub_c) = if busy {
+ (format!("{}{}", t!("Подключение", "Connecting"), &"...."[..(now / 400 % 4) as usize]), pal().accent)
+ } else if n.connected {
let q = conn.map(|c| c.0).unwrap_or(n.q);
- let det = match conn {
- Some((_, rx, tx, phy)) => format!("{phy} · {q}% · ↓{rx} ↑{tx} {} · {}", t!("Мбит/с", "Mbps"), auth_name(n.auth)),
- None => format!("{q}% · {}", auth_name(n.auth)),
- };
- text(dc, &det, RECT { left: rc.left + sc(60), top: rc.top + sc(58), right: rc.right - sc(14), bottom: rc.top + sc(76) }, ink(pal().dim), DT_LEFT);
- // a quiet Disconnect button that turns red under the pointer
- if let Some(&(ob, _)) = rs.iter().find(|(_, a)| *a == Act::NetOff) {
- g(Act::NetOff, ob, mix(card, pal().bg, 0.5), mix(card, BAD, 0.3), sc(8));
- SelectObject(dc, f_small);
- text(dc, t!("Отключиться", "Disconnect"), ob, ink(if hot(Act::NetOff) { pal().text } else { mix(pal().dim, pal().text, 0.5) }), DT_CENTER);
+ match conn {
+ _ if !online => (t!("Подключено, без интернета", "Connected, no internet").into(), WARN),
+ // under the pointer the line shows the link details instead
+ Some((_, _, rx, tx)) if open => (format!("↓{rx} ↑{tx} {} · {}", t!("Мбит/с", "Mbps"), auth_name(n.auth)), pal().dim),
+ Some((_, phy, ..)) => (format!("{} · {phy} · {q}%", t!("Подключено", "Connected")), pal().dim),
+ None => (format!("{} · {q}%", t!("Подключено", "Connected")), pal().dim),
}
+ } else if !n.secure {
+ (t!("Открытая сеть", "Open network").into(), WARN)
+ } else if saved {
+ (t!("Сохранена", "Saved").into(), pal().dim)
} else {
- g(Act::Net(i), rc, pal().bg, pal().hover, sc(10));
- wifi_glyph(dc, rc.left + sc(22), rc.top + sc(24), sc(16), lit, ink(pal().text), ink(mix(pal().dim, pal().bg, 0.5)), 0);
- let saved = n.profile.is_some();
- let sub = if !n.secure { t!("Открытая сеть", "Open network") } else if saved { t!("Сохранена", "Saved") } else { "" };
- SelectObject(dc, f_txt);
- let name_rc = if sub.is_empty() { RECT { left: rc.left + sc(46), right: rc.right - sc(110), ..rc } } else { RECT { left: rc.left + sc(46), top: rc.top + sc(5), right: rc.right - sc(110), bottom: rc.top + sc(27) } };
- text(dc, &n.ssid, name_rc, ink(pal().text), DT_LEFT);
- if !sub.is_empty() {
- SelectObject(dc, f_small);
- text(dc, sub, RECT { left: rc.left + sc(46), top: rc.top + sc(25), right: rc.right - sc(110), bottom: rc.bottom - sc(5) }, ink(if n.secure { pal().dim } else { WARN }), DT_LEFT);
- }
- if hot(Act::Net(i)) {
- SelectObject(dc, f_small);
- let action = if saved || !n.secure { t!("Подключить", "Connect") } else { t!("Ввести пароль", "Enter password") };
- text(dc, action, RECT { left: rc.right - sc(120), right: rc.right - sc(14), ..rc }, pal().accent, DT_RIGHT);
- } else if n.secure {
+ (String::new(), pal().dim)
+ };
+ let right = rc.right - sc(118);
+ SelectObject(dc, if n.connected { f_semi } else { f_txt });
+ if sub.is_empty() {
+ text(dc, &n.ssid, RECT { left: rc.left + sc(48), right, ..rc }, ink(pal().text), DT_LEFT);
+ } else {
+ text(dc, &n.ssid, RECT { left: rc.left + sc(48), top: cy - sc(19), right, bottom: cy + sc(1) }, ink(pal().text), DT_LEFT);
+ SelectObject(dc, f_small);
+ text(dc, &sub, RECT { left: rc.left + sc(48), top: cy, right, bottom: cy + sc(18) }, ink(sub_c), DT_LEFT);
+ }
+ if busy {
+ // an indeterminate bar sliding along the row's bottom edge
+ let (l, rr) = (rc.left + sc(48), rc.right - sc(16));
+ let span = rr - l;
+ let p = (now % 1300) as f32 / 1300.0;
+ let a = l + ((span as f32) * (ease(p) * 1.3 - 0.3)) as i32;
+ let b = a + span * 3 / 10;
+ fill(dc, RECT { left: l, top: rc.bottom - sc(5), right: rr, bottom: rc.bottom - sc(3) }, mix(card, pal().accent, 0.18), sc(2));
+ fill(dc, RECT { left: a.max(l), top: rc.bottom - sc(5), right: b.min(rr), bottom: rc.bottom - sc(3) }, pal().accent, sc(2));
+ }
+ if n.connected {
+ if open {
+ if let Some(&(ob, _)) = rs.iter().find(|(_, a)| *a == Act::NetOff) {
+ g(Act::NetOff, ob, card, mix(card, BAD, 0.14), ob.bottom - ob.top);
+ SelectObject(dc, f_semi);
+ text(dc, t!("Отключиться", "Disconnect"), ob, if hot(Act::NetOff) { BAD } else { pal().dim }, DT_CENTER);
+ }
+ } else {
SelectObject(dc, f_glyph);
- text(dc, "\u{E72E}", RECT { left: rc.right - sc(40), right: rc.right - sc(8), ..rc }, ink(mix(pal().dim, pal().bg, 0.35)), DT_CENTER); // lock
+ text(dc, "\u{E73E}", RECT { left: rc.right - sc(44), right: rc.right - sc(14), ..rc }, ink(pal().accent), DT_CENTER); // check mark
}
+ } else if open && !busy {
+ SelectObject(dc, f_semi);
+ let action = if saved || !n.secure { t!("Подключить", "Connect") } else { t!("Ввести пароль", "Enter password") };
+ text(dc, action, RECT { left: rc.right - sc(130), right: rc.right - sc(16), ..rc }, pal().accent, DT_RIGHT);
+ } else if n.secure && !busy {
+ SelectObject(dc, f_gs);
+ text(dc, "\u{E72E}", RECT { left: rc.right - sc(42), right: rc.right - sc(14), ..rc }, ink(mix(pal().dim, card, 0.35)), DT_CENTER); // lock
}
}
});
}
- let last = rs.last().unwrap();
- g(last.1, last.0, pal().bg, pal().hover, sc(8));
- SelectObject(dc, f_txt);
- text(dc, t!("Параметры сети", "Network settings"), RECT { left: last.0.left + sc(10), ..last.0 }, pal().accent, DT_LEFT);
- SelectObject(dc, f_glyph);
- text(dc, "\u{E76C}", RECT { left: last.0.right - sc(36), ..last.0 }, pal().accent, DT_CENTER); // chevron right
+ if let Some(&(lr, la)) = rs.iter().find(|(_, a)| matches!(a, Act::Settings(_))) {
+ g(la, lr, pal().bg, mix(pal().bg, pal().text, 0.05), sc(10));
+ SelectObject(dc, f_txt);
+ text(dc, t!("Параметры сети", "Network settings"), RECT { left: lr.left + sc(8), ..lr }, pal().accent, DT_LEFT);
+ SelectObject(dc, f_gs);
+ text(dc, "\u{E76C}", RECT { left: lr.right - sc(34), ..lr }, pal().dim, DT_CENTER); // chevron right
+ }
+ // the right-click menu unfolds downward from where it was opened
+ if let Some((ssid, mx, my, t0)) = CTX.with_borrow(|c| c.clone()) {
+ let items = ctx_items(&ssid);
+ let t = ease((now_ms().saturating_sub(t0) as f32 / 150.0).min(1.0));
+ if t < 1.0 {
+ BUSY.set(true);
+ }
+ let full = sc(12 + CTX_ROW * items.len() as i32);
+ let mr = RECT { left: mx, top: my, right: mx + sc(CTX_W), bottom: my + (full as f32 * (0.4 + 0.6 * t)) as i32 };
+ fill(dc, RECT { left: mr.left - 1, top: mr.top + sc(2), right: mr.right + 1, bottom: mr.bottom + sc(4) }, mix(pal().bg, 0, if style().light() { 0.12 } else { 0.5 }), sc(14));
+ surface(dc, mr, card, sc(12));
+ for ((ir, a), (label, what)) in ctx_rects().iter().zip(&items) {
+ if ir.bottom > mr.bottom - sc(4) {
+ break; // still unfolding
+ }
+ g(*a, *ir, card, if *what == 2 { mix(card, BAD, 0.12) } else { mix(card, pal().text, 0.06) }, sc(8));
+ SelectObject(dc, f_txt);
+ text(dc, label, RECT { left: ir.left + sc(12), ..*ir }, if *what == 2 { BAD } else { pal().text }, DT_LEFT);
+ }
+ }
}
Kind::Menu => {
// header: the app's icon on an accent-tinted tile, its name, and what is open
@@ -1269,15 +1520,21 @@ unsafe fn paint(hw: HWND, k: Kind) {
});
}
Kind::Start => {
- fill(dc, r(20, 20, w - 20, 56), mix(pal().bg, 0, 0.35), sc(18));
+ surface(dc, r(20, 20, w - 20, 56), card, sc(36));
SelectObject(dc, f_glyph);
text(dc, "\u{E721}", r(28, 20, 56, 56), pal().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), pal().dim, DT_LEFT);
+ text(dc, "Type to search apps", r(64, 20, w - 64, 56), pal().dim, DT_LEFT);
} else {
- text(dc, &q, r(64, 20, w - 28, 56), pal().text, DT_LEFT);
+ text(dc, &q, r(64, 20, w - 64, 56), pal().text, DT_LEFT);
+ }
+ if let Some((kr, ka)) = rects(k).into_iter().find(|(_, a)| *a == Act::Keyboard) {
+ g(ka, kr, card, mix(card, pal().text, 0.1), sc(14));
+ SelectObject(dc, f_glyph);
+ text(dc, "\u{E765}", kr, if hot(ka) { pal().text } else { pal().dim }, DT_CENTER); // keyboard
+ SelectObject(dc, f_txt);
}
let f = filtered();
if f.is_empty() {
@@ -1349,7 +1606,7 @@ unsafe fn paint(hw: HWND, k: Kind) {
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] {
+ for f in [f_txt, f_small, f_glyph, f_title, f_big, f_semi, f_head, f_gs, f_label] {
DeleteObject(f);
}
SelectObject(dc, old);
@@ -1378,7 +1635,7 @@ unsafe extern "system" fn proc(hw: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LR
match msg {
WM_PAINT => paint(hw, k),
WM_ERASEBKGND => return 1,
- WM_ACTIVATE if wp & 0xffff == 0 => {
+ WM_ACTIVATE if wp & 0xffff == 0 && !PREVIEW.load(Relaxed) => {
// 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 {
@@ -1425,7 +1682,10 @@ unsafe extern "system" fn proc(hw: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LR
}
}
WM_LBUTTONDOWN => {
- if let Some((rc, a)) = act_at(k, x, y) {
+ let hit = act_at(k, x, y);
+ if CTX.with_borrow(|c| c.is_some()) && !matches!(hit, Some((_, Act::Ctx(_)))) {
+ CTX.set(None); // a click beside the open menu only closes it
+ } else if let Some((rc, a)) = hit {
run_act(a, rc, x);
}
if FLY.get().is_some() {
@@ -1433,10 +1693,20 @@ unsafe extern "system" fn proc(hw: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LR
}
}
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);
+ match (k, act_at(k, x, y)) {
+ (Kind::Start, Some((_, Act::App(i)))) => app_menu(hw, i, x, y),
+ (Kind::Wifi, Some((_, Act::Net(_) | Act::NetOff))) if PASS.with_borrow(|p| p.is_none()) => {
+ let i = if let Some((_, Act::Net(i))) = act_at(k, x, y) { i } else { NETS.with_borrow(|n| n.iter().position(|n| n.connected)).unwrap_or(0) };
+ if let Some(ssid) = NETS.with_borrow(|n| n.get(i).map(|n| n.ssid.clone())) {
+ // keep the menu inside the panel
+ let (pw, ph) = (sc(size(k).0), sc(size(k).1));
+ let mh = sc(12 + CTX_ROW * ctx_items(&ssid).len() as i32);
+ CTX.set(Some((ssid, x.min(pw - sc(CTX_W) - sc(8)).max(sc(8)), y.min(ph - mh - sc(8)).max(sc(8)), now_ms())));
+ }
+ }
+ _ => {}
}
+ InvalidateRect(hw, null(), 0);
}
WM_LBUTTONUP => {
let d = DRAG.replace(0);
@@ -1469,7 +1739,9 @@ unsafe extern "system" fn proc(hw: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LR
WM_CHAR => {
let c = wp as u32;
if c == 27 {
- if PASS.with_borrow(|p| p.is_some()) {
+ if CTX.with_borrow(|c| c.is_some()) {
+ CTX.set(None);
+ } else 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
diff --git a/plugins/topbar/src/main.rs b/plugins/topbar/src/main.rs
index 6830e25..370137d 100644
--- a/plugins/topbar/src/main.rs
+++ b/plugins/topbar/src/main.rs
@@ -18,8 +18,10 @@ use std::{
#[macro_use]
extern crate winrust_common;
use winrust_common as i18n;
-use winrust_common::style::{Style, pal, style, ui_face};
+use winrust_common::style::{Style, card, on_accent, pal, rgb, style, ui_face};
+mod clip;
mod fly;
+mod quick;
use windows::{
Win32::{
Media::Audio::{Endpoints::IAudioEndpointVolume, IMMDeviceEnumerator, MMDeviceEnumerator, eConsole, eRender},
@@ -50,7 +52,6 @@ use windows_sys::Win32::{
UI::{Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*},
};
-use winrust_common::style::rgb;
/// A corner radius in logical px, 0 in the square styles.
fn rr(v: i32) -> i32 {
if style().square() { 0 } else { sc(v) }
@@ -81,9 +82,9 @@ unsafe fn bar_y() -> i32 {
unsafe fn pop_y(h: i32) -> i32 {
if at_top() { bar_h() + sc(8) } else { bar_top() - sc(8) - h }
}
-const GOOD: u32 = rgb(108, 203, 95);
-const BAD: u32 = rgb(255, 99, 97);
-const WARN: u32 = rgb(255, 196, 0);
+const GOOD: u32 = winrust_common::style::GOOD;
+const BAD: u32 = winrust_common::style::BAD;
+const WARN: u32 = winrust_common::style::WARN;
const CALLBACK: u32 = WM_APP + 1;
const WM_MOUSELEAVE: u32 = 0x02A3; // not exported under the enabled features
const NO_WINDOW: u32 = 0x0800_0000;
@@ -108,6 +109,7 @@ 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 VOLKEY: u32 = WM_APP + 14; // posted by the keyboard hook: a volume key (wp 0 up, 1 down, 2 mute)
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
@@ -721,6 +723,38 @@ unsafe fn hide_taskbar() {
}
}
+fn taskbar_state_file() -> PathBuf {
+ appdata_file("topbar-taskbar-state.txt")
+}
+
+/// The taskbar mode (always on top / auto-hide bits) the user had before the bar hid it. It lives in a file so that
+/// `--restore` (reshell's watchdog after a crash) puts back the user's own mode, not the Windows default.
+fn saved_taskbar_state() -> Option<usize> {
+ std::fs::read_to_string(taskbar_state_file()).ok()?.trim().parse().ok()
+}
+
+fn forget_taskbar_state() {
+ let _ = std::fs::remove_file(taskbar_state_file());
+}
+
+/// At start: the mode to give back later. A file left by a crashed run wins (explorer's current mode is then our own
+/// auto-hide); otherwise the current mode is the user's and is written down. Without explorer's taskbar: the default.
+unsafe fn remember_taskbar_state() -> usize {
+ if let Some(s) = saved_taskbar_state() {
+ return s;
+ }
+ let tb = tray()[0];
+ if tb.is_null() {
+ return ABS_ALWAYSONTOP as usize;
+ }
+ let mut ab: APPBARDATA = zeroed();
+ ab.cbSize = size_of::<APPBARDATA>() as u32;
+ ab.hWnd = tb;
+ let s = SHAppBarMessage(ABM_GETSTATE, &mut ab);
+ let _ = std::fs::write(taskbar_state_file(), s.to_string());
+ s
+}
+
unsafe fn show_taskbar(state: usize) {
set_state(tray()[0], state);
for t in tray().into_iter().filter(|t| !t.is_null()) {
@@ -743,7 +777,7 @@ unsafe fn place(hwnd: HWND) {
ab.hWnd = hwnd;
// the reserved strip: the bar itself plus the dock's gap under it
// the dock reserves nothing: maximized windows take the whole screen and the dock slides away over them
- let strip = if style() == Style::Dock { 0 } else { bar_h() };
+ let strip = if style() == Style::Dock || i18n::style::autohide() { 0 } else { bar_h() };
if at_top() {
ab.uEdge = ABE_TOP;
ab.rc = RECT { left: 0, top: 0, right: cx, bottom: strip };
@@ -1390,7 +1424,8 @@ unsafe fn bar_anim(hwnd: HWND) {
}
unsafe fn bar_step(hwnd: HWND) {
- let target = if FULLSCREEN.load(Relaxed) { 0.0 } else { 1.0 }; // hides only for a fullscreen game or video: not over the desktop, not in any style
+ // hides for a fullscreen game or video, and with "auto-hide" on while the pointer is away (never otherwise: not over the desktop, not in any style)
+ let target = if FULLSCREEN.load(Relaxed) || (i18n::style::autohide() && 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();
@@ -1444,7 +1479,7 @@ unsafe fn fs_update(hwnd: HWND) {
let now = now_ms();
let sh = GetSystemMetrics(SM_CYSCREEN);
let over = if at_top() { pt.y <= 0 || (pt.y < bar_h() && BAR_P.get() > 0.0) } else { pt.y >= sh - 1 || (pt.y >= sh - bar_h() - dock_gap() && BAR_P.get() > 0.0) };
- if fs || !(desktop_now() || dock_covered()) || fly::any_open() || over {
+ if fs || !(i18n::style::autohide() || desktop_now() || dock_covered()) || fly::any_open() || over {
DESK_T.set(now);
}
let desk = !fs && now.saturating_sub(DESK_T.get()) >= 2000;
@@ -1500,21 +1535,41 @@ unsafe fn force_fg(hw: HWND) {
unsafe extern "system" fn kb_hook(n: i32, w: WPARAM, l: LPARAM) -> LRESULT {
if n >= 0 {
let k = &*(l as *const KBDLLHOOKSTRUCT);
+ let down0 = w == WM_KEYDOWN as usize || w == WM_SYSKEYDOWN as usize;
+ // without explorer nobody handles the volume keys, and Surface's power + volume-up arrives as an injected Win+PrtSc
+ // (the injected events are skipped below, so these two are taken before that check)
+ if !EXPLORER_UP.load(Relaxed) {
+ let vol = [(VK_VOLUME_UP, 0), (VK_VOLUME_DOWN, 1), (VK_VOLUME_MUTE, 2)].into_iter().find(|&(vk, _)| k.vkCode == vk as u32);
+ if let Some((_, v)) = vol {
+ if down0 {
+ PostMessageW(BAR.load(Relaxed) as HWND, VOLKEY, v, 0);
+ }
+ return 1;
+ }
+ if k.vkCode == VK_SNAPSHOT as u32 && k.flags & LLKHF_INJECTED != 0 {
+ if down0 {
+ PostMessageW(BAR.load(Relaxed) as HWND, SNIP, 1, 0);
+ }
+ return 1;
+ }
+ }
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
+ // Win+Shift+S is our own region clipper (also under Explorer); without explorer nobody opens the screen
+ // capture either: PrtSc (when Windows is set to snip with it; otherwise it copies the screen by itself) does it here
+ let held = |vk: u16| GetAsyncKeyState(vk as i32) < 0;
+ let snip_key = !EXPLORER_UP.load(Relaxed) && k.vkCode == VK_SNAPSHOT as u32;
+ let win_shift_s = k.vkCode == b'S' as u32 && down0 && (held(VK_LWIN) || held(VK_RWIN)) && held(VK_SHIFT);
+ if snip_key || win_shift_s {
+ if down0 {
+ WIN_ALONE.store(false, Relaxed);
+ if win_shift_s {
+ // a key between Win down and up, so Windows does not open its Start menu on the release
+ keybd_event(0xE8, 0, 0, 0);
+ keybd_event(0xE8, 0, KEYEVENTF_KEYUP, 0);
}
- return 1;
+ 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;
@@ -1633,10 +1688,6 @@ unsafe fn app_window() -> HWND {
/// 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;
@@ -1648,6 +1699,16 @@ unsafe fn screenshot() -> Option<String> {
SelectObject(mem, old);
DeleteDC(mem);
ReleaseDC(null_mut(), scr);
+ save_bitmap(bmp)
+}
+
+/// Saves a screen bitmap as Pictures\Screenshots\Screenshot <date time>.png and puts it on the clipboard (which then owns it).
+/// Returns the file name when either worked.
+unsafe fn save_bitmap(bmp: HBITMAP) -> Option<String> {
+ use windows_sys::Win32::{
+ Graphics::GdiPlus::{GdipCreateBitmapFromHBITMAP, GdipDisposeImage, GdipSaveImageToFile, GpBitmap, GpImage},
+ System::DataExchange::{CloseClipboard, EmptyClipboard, OpenClipboard, SetClipboardData},
+ };
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);
@@ -1672,6 +1733,14 @@ unsafe fn screenshot() -> Option<String> {
(saved || clip).then_some(name)
}
+/// The clipper saved a region (its file name is left in `clip::DONE`): say so above the bar for a moment.
+unsafe fn clip_notice(bar: HWND) {
+ let name = clip::DONE.lock().ok().and_then(|mut d| d.take()).unwrap_or_default();
+ KillTimer(bar, 2);
+ show_tip(tf!("Фрагмент сохранён: {name}\nи скопирован в буфер обмена", "Snip saved: {name}\nand copied to the clipboard"), GetSystemMetrics(SM_CXSCREEN) / 2);
+ SetTimer(bar, 6, 2500, None);
+}
+
/// PrtSc pressed: take the screenshot, then say so above the bar for a moment.
unsafe fn screenshot_notice(bar: HWND) {
let msg = match screenshot() {
@@ -1786,13 +1855,14 @@ unsafe fn paint(hwnd: HWND) {
for y in 0..h {
fill(dc, RECT { left: 0, top: y, right: cr.right, bottom: y + 1 }, mix(lit, pal().bg, (y as f32 / sc(18) as f32).min(1.0)), 0);
}
+ winrust_common::style::backdrop(dc, cr, sc(100) as f32 / 100.0);
let edge = if at_top() { h - 1 } else { 0 }; // the hairline faces the windows
fill(dc, RECT { left: 0, top: edge, right: cr.right, bottom: edge + 1 }, pal().line, 0);
if !at_top() {
fill(dc, RECT { left: 0, top: 1, right: cr.right, bottom: 2 }, mix(pal().bg, pal().text, 0.08), 0);
}
SetBkMode(dc, TRANSPARENT as i32);
- let (face, gface) = (wide(ui_face()), wide("Segoe MDL2 Assets"));
+ let (face, gface) = (wide(ui_face()), wide(winrust_common::style::icon_face()));
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);
@@ -2218,16 +2288,23 @@ unsafe fn open_launcher() -> bool {
/// The gear's menu: the UI style (saved for the other WinRust programs) and putting the windows side by side.
unsafe fn style_menu() {
let bar = BAR.load(Relaxed) as HWND;
- let names = [t!("Обычный", "Normal"), t!("Терминал", "Terminal"), t!("Плавающий док", "Floating dock"), t!("Тайлинг", "Tiling")];
+ let names = [t!("Обычный", "Normal"), t!("Терминал", "Terminal"), t!("Плавающий док", "Floating dock"), t!("Тайлинг", "Tiling"), t!("Белая дорога", "White road")];
let mut items: Vec<fly::MItem> = i18n::style::ALL.iter().zip(names).map(|(&s, n)| fly::MItem::new(n).on(s == style())).collect();
items.push(fly::MItem::new(t!("Разложить окна плиткой", "Tile the windows")).sep());
+ items.push(fly::MItem::new(t!("Скрывать панель автоматически", "Hide the bar automatically")).on(i18n::style::autohide()));
let head = (null_mut(), "\u{E713}", t!("Стиль", "Style").to_string(), t!("Вид панели и программ WinRust", "Look of the bar and the WinRust programs").to_string());
+ let tile = i18n::style::ALL.len();
fly::menu(tip_cx(&bar_layout(bar), GEAR), Some(head), items, move |i| match i18n::style::ALL.get(i) {
Some(&s) => {
i18n::style::set_style(s);
place(bar);
}
- None => tile_windows(),
+ None if i == tile => tile_windows(),
+ None => {
+ i18n::style::set_autohide(!i18n::style::autohide());
+ place(bar); // the reserved strip comes or goes with it
+ bar_anim(bar);
+ }
});
}
@@ -2413,7 +2490,15 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM)
ALT_TAB => alt_tab(wp == 1),
ALT_UP => alt_done(wp == 1),
SNIP if wp == 1 => screenshot_notice(hwnd),
- SNIP => open(&wide("ms-screenclip:")),
+ SNIP if wp == 2 => clip_notice(hwnd),
+ SNIP => clip::start(),
+ VOLKEY => {
+ if wp == 2 { toggle_mute() } else { add_volume(if wp == 0 { 4 } else { -4 }) }
+ KillTimer(hwnd, 2);
+ show_tip(vol_tip(), tip_cx(&bar_layout(hwnd), VOL_I));
+ SetTimer(hwnd, 6, 1200, None);
+ InvalidateRect(hwnd, null(), 0);
+ }
WM_DROPFILES => on_drop(hwnd, wp as HDROP),
WM_TIMER => {
hide_taskbar_if_shown();
@@ -2488,6 +2573,7 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM)
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());
+ forget_taskbar_state();
DestroyWindow(HOST.replace(null_mut()));
announce(); // icons go back to explorer's tray
PostQuitMessage(0);
@@ -2500,7 +2586,8 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM)
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
+ show_taskbar(saved_taskbar_state().unwrap_or(ABS_ALWAYSONTOP as usize));
+ forget_taskbar_state();
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
}
@@ -2515,6 +2602,22 @@ fn main() {
screenshot();
return;
}
+ // `topbar --preview quick|wifi`: one flyout on its own (no bar, no hooks), to look at a style change; the process is closed by hand
+ if let Some(p) = std::env::args().skip_while(|a| a != "--preview").nth(1) {
+ SetProcessDPIAware();
+ let (mut tok, mut inp): (usize, GdiplusStartupInput) = (0, zeroed());
+ inp.GdiplusVersion = 1;
+ GdiplusStartup(&mut tok, &inp, null_mut());
+ fly::init(GetModuleHandleW(null()));
+ fly::PREVIEW.store(true, Relaxed);
+ fly::toggle(if p == "wifi" { fly::Kind::Wifi } else { fly::Kind::Quick });
+ let mut msg: MSG = zeroed();
+ while GetMessageW(&mut msg, null_mut(), 0, 0) > 0 {
+ TranslateMessage(&msg);
+ DispatchMessageW(&msg);
+ }
+ 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() {
@@ -2569,10 +2672,7 @@ fn main() {
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));
+ OLD_STATE.set(remember_taskbar_state());
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
diff --git a/plugins/topbar/src/quick.rs b/plugins/topbar/src/quick.rs
new file mode 100644
index 0000000..a550298
Binary files /dev/null and b/plugins/topbar/src/quick.rs differ
diff --git a/plugins/wiztree/Cargo.toml b/plugins/wiztree/Cargo.toml
index a1d2948..26f9ac5 100644
--- a/plugins/wiztree/Cargo.toml
+++ b/plugins/wiztree/Cargo.toml
@@ -6,3 +6,6 @@ edition = "2024"
[dependencies]
winrust-common = { path = "../../common" }
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"] }
+
+[build-dependencies]
+embed-resource = "3"
diff --git a/plugins/wiztree/app.ico b/plugins/wiztree/app.ico
new file mode 100644
index 0000000..a5698af
Binary files /dev/null and b/plugins/wiztree/app.ico differ
diff --git a/plugins/wiztree/app.rc b/plugins/wiztree/app.rc
new file mode 100644
index 0000000..0a9daf1
--- /dev/null
+++ b/plugins/wiztree/app.rc
@@ -0,0 +1 @@
+1 ICON "app.ico"
diff --git a/plugins/wiztree/build.rs b/plugins/wiztree/build.rs
new file mode 100644
index 0000000..e8d32ea
--- /dev/null
+++ b/plugins/wiztree/build.rs
@@ -0,0 +1,5 @@
+fn main() {
+ println!("cargo:rerun-if-changed=app.rc");
+ println!("cargo:rerun-if-changed=app.ico");
+ embed_resource::compile("app.rc", embed_resource::NONE).manifest_optional().unwrap();
+}
diff --git a/plugins/wiztree/src/main.rs b/plugins/wiztree/src/main.rs
index ff5682a..3f97f20 100644
--- a/plugins/wiztree/src/main.rs
+++ b/plugins/wiztree/src/main.rs
@@ -16,9 +16,9 @@ use windows_sys::Win32::{
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 BG: u32 = rgb(22, 22, 24);
+const DIM: u32 = rgb(142, 142, 147);
+const ACCENT: u32 = rgb(10, 132, 255);
const fn rgb(r: u8, g: u8, b: u8) -> u32 {
r as u32 | (g as u32) << 8 | (b as u32) << 16
@@ -114,7 +114,7 @@ fn squarify(items: &[(u32, u64)], (mut x, mut y, mut w, mut h): (f64, f64, f64,
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 (s, v) = if dir { (0.28, 0.36) } else { (0.42, 0.66) }; // muted: the map reads calm, the labels stay legible
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
@@ -224,7 +224,7 @@ unsafe extern "system" fn proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) ->
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());
+ let f = CreateFontW(-(15 * dpi / 96), 0, 0, 0, 400, 0, 0, 0, 1, 0, 0, 5, 0, wide(winrust_common::style::sans_face()).as_ptr());
APP.with_borrow_mut(|a| (a.dpi, a.font) = (dpi, f as isize));
0
}
diff --git a/scripts/make-icons.py b/scripts/make-icons.py
new file mode 100644
index 0000000..b49829e
--- /dev/null
+++ b/scripts/make-icons.py
@@ -0,0 +1,178 @@
+"""Draws the app icons (python scripts\\make-icons.py; needs Pillow) and writes `app.ico` next to each app.
+One look for all: a graphite rounded tile with a soft shadow and a faint top light, one glyph in the app's colour
+(the same colours as the page tiles of rust-settings). Everything is drawn 4x too big and shrunk with LANCZOS: smooth edges,
+and every ico frame is made from the master, not stretched from a small one."""
+import io, math, struct, sys
+from pathlib import Path
+from PIL import Image, ImageChops, ImageDraw, ImageFilter
+
+ROOT = Path(__file__).resolve().parent.parent
+M = 1024 # master canvas
+SIZES = [16, 24, 32, 48, 64, 128, 256]
+
+
+def mask(draw_fn):
+ im = Image.new("L", (M, M), 0)
+ draw_fn(ImageDraw.Draw(im))
+ return im
+
+
+def rr(box, r):
+ return lambda d: d.rounded_rectangle(box, r, fill=255)
+
+
+def union(*fns):
+ def f(d):
+ for fn in fns:
+ fn(d)
+ return f
+
+
+def poly_line(points, w):
+ """A polyline with round caps and joins."""
+ def f(d):
+ d.line(points, fill=255, width=w, joint="curve")
+ for x, y in points:
+ d.ellipse((x - w / 2, y - w / 2, x + w / 2, y + w / 2), fill=255)
+ return f
+
+
+def gradient(top, bottom):
+ g = Image.new("RGB", (1, M))
+ for y in range(M):
+ t = y / (M - 1)
+ g.putpixel((0, y), tuple(round(a + (b - a) * t) for a, b in zip(top, bottom)))
+ return g.resize((M, M))
+
+
+def lighter(c, k):
+ return tuple(min(255, round(v + (255 - v) * k)) for v in c)
+
+
+def darker(c, k):
+ return tuple(round(v * (1 - k)) for v in c)
+
+
+def paint(canvas, m, color, spread=0.22):
+ """Fills mask m with a colour that is a little lighter on top and darker below."""
+ canvas.paste(gradient(lighter(color, spread), darker(color, spread * 0.8)), (0, 0), m)
+
+
+def cut(c, m):
+ """Erases mask m from the glyph layer: the tile shows through."""
+ c.putalpha(ImageChops.subtract(c.getchannel("A"), m))
+
+
+def tile():
+ t = Image.new("RGBA", (M, M), (0, 0, 0, 0))
+ box = (56, 40, M - 56, M - 72)
+ shape = mask(rr(box, 224))
+ # soft drop shadow
+ sh = Image.new("RGBA", (M, M), (0, 0, 0, 0))
+ sh.paste((0, 0, 0, 120), (0, 26), shape.filter(ImageFilter.GaussianBlur(26)))
+ t = Image.alpha_composite(t, sh)
+ body = gradient((40, 43, 53), (21, 23, 29)).convert("RGBA")
+ body.putalpha(shape)
+ t = Image.alpha_composite(t, body)
+ # hairline light along the rim, strongest at the top
+ inner = mask(rr((box[0] + 5, box[1] + 5, box[2] - 5, box[3] - 5), 219))
+ rim = ImageChops.subtract(shape, inner)
+ fade = gradient((255, 255, 255), (60, 60, 60)).convert("L").point(lambda v: v * 38 // 255)
+ rim_a = ImageChops.multiply(rim, fade)
+ rim_img = Image.new("RGBA", (M, M), (255, 255, 255, 0))
+ rim_img.putalpha(rim_a)
+ return Image.alpha_composite(t, rim_img), shape
+
+
+# ---- glyphs: each draws onto `c` (RGB master) and returns nothing; the tile colour is `ink` for cut-outs ----
+
+
+def folder(c, col):
+ back = mask(union(rr((250, 300, 500, 470), 56), rr((250, 360, 774, 740), 64)))
+ paint(c, back, darker(col, 0.28))
+ paint(c, mask(rr((250, 438, 774, 740), 64)), col)
+
+
+def gear(c, col):
+ n, ro, ri = 8, 330, 262
+ pts = []
+ for i in range(n):
+ a = 2 * math.pi * i / n
+ for da, r in ((-0.20, ri), (-0.13, ro), (0.13, ro), (0.20, ri)):
+ pts.append((512 + r * math.cos(a + da), 512 + r * math.sin(a + da)))
+ g = mask(lambda d: (d.polygon(pts, fill=255), d.ellipse((512 - ri - 8, 512 - ri - 8, 512 + ri + 8, 512 + ri + 8), fill=255)))
+ hole = mask(lambda d: d.ellipse((512 - 108, 512 - 108, 512 + 108, 512 + 108), fill=255))
+ paint(c, ImageChops.subtract(g, hole), col)
+
+
+def bar(c, col):
+ for i, (x0, x1) in enumerate(((252, 500), (524, 772))): # two ghost windows above the bar
+ paint(c, mask(rr((x0, 270, x1, 560), 44)), darker(col, 0.62), 0.1)
+ paint(c, mask(rr((236, 600, 788, 740), 70)), col)
+ cuts = mask(lambda d: [d.ellipse((x - 26, 670 - 26, x + 26, 670 + 26), fill=255) for x in (352, 432)] + [d.rounded_rectangle((584, 650, 700, 690), 20, fill=255)])
+ cut(c, cuts)
+
+
+def treemap(c, col):
+ rects = [((246, 250, 536, 774), 0.0), ((568, 250, 778, 470), 0.12), ((568, 502, 664, 774), 0.26), ((696, 502, 778, 774), 0.4)]
+ for box, k in rects:
+ paint(c, mask(rr(box, 34)), lighter(col, k) if k else col)
+
+
+def picture(c, col):
+ card = mask(rr((236, 290, 788, 734), 76))
+ paint(c, card, col)
+ sun = mask(lambda d: d.ellipse((600 - 54, 410 - 54, 600 + 54, 410 + 54), fill=255))
+ hills = mask(lambda d: d.polygon([(236, 760), (236, 650), (380, 510), (480, 610), (590, 530), (788, 710), (788, 760)], fill=255))
+ paint(c, ImageChops.multiply(hills, card), darker(col, 0.38), 0.1)
+ paint(c, sun, lighter(col, 0.75), 0.05)
+
+
+def package(c, col):
+ paint(c, mask(poly_line([(268, 590), (268, 736), (756, 736), (756, 590)], 64)), darker(col, 0.25))
+ paint(c, mask(union(poly_line([(512, 262), (512, 590)], 68), poly_line([(372, 462), (512, 602), (652, 462)], 68))), col)
+
+
+APPS = {
+ "plugins/rust-explorer": (folder, (10, 132, 255)),
+ "plugins/rust-settings": (gear, (174, 180, 194)),
+ "plugins/topbar": (bar, (124, 134, 255)),
+ "plugins/wiztree": (treemap, (255, 159, 10)),
+ "plugins/photoview": (picture, (191, 90, 242)),
+ ".": (package, (48, 209, 88)),
+}
+
+
+def render(glyph, col):
+ base, _ = tile()
+ layer = Image.new("RGBA", (M, M), (0, 0, 0, 0))
+ glyph(layer, col)
+ return Image.alpha_composite(base, layer)
+
+
+def frame_bytes(img, s):
+ buf = io.BytesIO()
+ img.resize((s, s), Image.LANCZOS).save(buf, "PNG")
+ return buf.getvalue()
+
+
+def write_ico(path, img):
+ frames = [(s, frame_bytes(img, s)) for s in SIZES]
+ head = struct.pack("<HHH", 0, 1, len(frames))
+ off = 6 + 16 * len(frames)
+ entries, data = b"", b""
+ for s, b in frames:
+ entries += struct.pack("<BBBBHHII", s % 256, s % 256, 0, 0, 1, 32, len(b), off + len(data))
+ data += b
+ path.write_bytes(head + entries + data)
+
+
+if __name__ == "__main__":
+ sheet = Image.new("RGBA", (256 * len(APPS), 256), (255, 255, 255, 0))
+ for i, (rel, (glyph, col)) in enumerate(APPS.items()):
+ img = render(glyph, col)
+ write_ico(ROOT / rel / "app.ico", img)
+ sheet.paste(img.resize((256, 256), Image.LANCZOS), (256 * i, 0))
+ if len(sys.argv) > 1:
+ sheet.save(sys.argv[1])
+ print("wrote", len(APPS), "icons")
diff --git a/scripts/update-plugin.ps1 b/scripts/update-plugin.ps1
index e3be7f8..8b0c0bd 100644
--- a/scripts/update-plugin.ps1
+++ b/scripts/update-plugin.ps1
@@ -1,8 +1,8 @@
# Rebuilds the plugins (cargo only recompiles what changed), refreshes payload\ and runs `plugin-launcher update`: no launcher rebuild.
-# scripts\update-plugin.ps1 rust-search|rtaskmgr-win32|topbar|rust-explorer|wiztree|photoview|debloat
+# scripts\update-plugin.ps1 rust-search|rtaskmgr-win32|topbar|rust-explorer|wiztree|photoview|rust-settings|debloat
# 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)
+param([Parameter(Mandatory)][ValidateSet('rust-search', 'rtaskmgr-win32', 'topbar', 'rust-explorer', 'wiztree', 'photoview', 'rust-settings', 'debloat')][string]$name)
$ErrorActionPreference = 'Stop'
$root = Split-Path $PSScriptRoot
& "$PSScriptRoot\build-plugins.ps1" # rebuilds what changed (and what ships with the plugin), refreshes payload\
diff --git a/src/install/explorer.rs b/src/install/explorer.rs
index ccd693f..87eda0f 100644
--- a/src/install/explorer.rs
+++ b/src/install/explorer.rs
@@ -121,7 +121,7 @@ pub(crate) fn rx_uninstall() -> Result<(), String> {
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 _ = run("powershell", &["-NoProfile", "-Command", r#"if (-not (Get-CimInstance Win32_Process -Filter "Name='explorer.exe'" | Where-Object { $_.CommandLine -match '(?i)explorer\.exe"?(\s+/NoUACCheck)?\s*$' })) { runas /trustlevel:0x20000 C:\Windows\explorer.exe }"#]);
let _ = fs::remove_file(rx_lnk());
let _ = fs::remove_file(start_lnk("Rust Explorer"));
let _ = fs::remove_dir_all(rx_dir());
diff --git a/src/install/tools.rs b/src/install/tools.rs
index 25c9ab8..4258905 100644
--- a/src/install/tools.rs
+++ b/src/install/tools.rs
@@ -1,4 +1,4 @@
-//! wiztree, photoview, debloat, purge: small stand-alone tools, one exe each in its own Program Files folder.
+//! wiztree, photoview, rust-settings, debloat, purge: small stand-alone tools, one exe each in its own Program Files folder.
use crate::*;
// ---------- wiztree, photoview, debloat: small stand-alone tools, one exe each in its own Program Files folder ----------
@@ -11,6 +11,10 @@ pub(crate) fn pv_dir() -> PathBuf {
program_files().join("photoview")
}
+pub(crate) fn st_dir() -> PathBuf {
+ program_files().join("rust-settings")
+}
+
pub(crate) fn pu_dir() -> PathBuf {
program_files().join("purge")
}
@@ -41,6 +45,18 @@ pub(crate) fn tool_remove(exe: &str, dir: &Path, lnk: Option<&str>) {
let _ = fs::remove_dir_all(dir);
}
+pub(crate) fn st_install() -> Result<(), String> {
+ tool_install("rust-settings.exe", &st_dir(), Some("WinRust Settings"))
+}
+
+pub(crate) fn st_uninstall() -> Result<(), String> {
+ tool_remove("rust-settings.exe", &st_dir(), Some("WinRust Settings")); // also ends the night-light helper (same exe)
+ // what the night-light switch left for the user: its autostart value and its setting
+ let _ = run("reg", &["delete", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run", "/v", "WinRustNightLight", "/f"]);
+ let _ = run("reg", &["delete", r"HKCU\Software\WinRust\NightLight", "/f"]);
+ Ok(())
+}
+
pub(crate) fn wz_install() -> Result<(), String> {
tool_install("wiztree.exe", &wz_dir(), Some("WinRust Disk"))
}
diff --git a/src/main.rs b/src/main.rs
index 5842aa7..0c68688 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -41,14 +41,14 @@ use windows_sys::Win32::{
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 BG: u32 = rgb(22, 22, 24); // the shared WinRust graphite (common/src/style.rs, normal style)
+const PANEL: u32 = rgb(34, 34, 38);
+const BORDER: u32 = rgb(50, 50, 55);
+const TEXT: u32 = rgb(245, 245, 247);
+const DIM: u32 = rgb(142, 142, 147);
+const ACCENT: u32 = rgb(10, 132, 255);
+const GOOD: u32 = winrust_common::style::GOOD;
+const BAD: u32 = winrust_common::style::BAD;
const WM_DONE: u32 = WM_APP + 1;
const WM_MOUSELEAVE: u32 = 0x02A3; // not exported by windows-sys under the enabled features
@@ -136,6 +136,16 @@ const PLUGINS: &[Plugin] = &[
bulk: true,
glyph: "\u{E91B}", // picture
},
+ Plugin {
+ name: "rust-settings",
+ desc: Tr("Параметры на Rust: экран (разрешение, частота), звук (громкость), тема, о системе. Win+I и меню панели открывают их, а не Параметры Windows, поэтому Проводник не нужен. Остальные разделы открывают системные.", "Settings in Rust: display (resolution, refresh rate), sound (volume), theme, about. Win+I and the bar menus open it instead of Windows Settings, so Explorer is not needed. Other pages open the system ones."),
+ warn: Tr("Ничего системного не меняется: файл в Program Files и ярлык «WinRust Settings» в меню Пуск. Win+I начинает открывать это окно; удалите плагин, и всё вернётся.", "Nothing in the system is changed: a file in Program Files and a 'WinRust Settings' Start menu shortcut. Win+I starts opening this window; uninstall the plugin and it goes back."),
+ installed: || st_dir().join("rust-settings.exe").is_file(),
+ actions: Some((st_install, st_uninstall)),
+ settings: false,
+ bulk: true,
+ glyph: "\u{E713}", // settings
+ },
Plugin {
name: "debloat",
desc: Tr("Отключает мусор Windows: телеметрию, Copilot, Recall, рекламу в Пуске, фон Edge. Только обратимое, старые значения запоминаются.", "Disables Windows junk: telemetry, Copilot, Recall, Start menu ads, the Edge background. Reversible changes only, old values are remembered."),
diff --git a/src/ui.rs b/src/ui.rs
index 1253faa..c63bec2 100644
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -70,11 +70,11 @@ impl Ui {
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");
+ self.text_in(s, b, size, weight, color, flags, winrust_common::style::sans_face());
}
/// 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 f = self.font(size, weight, winrust_common::style::sans_face());
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);
@@ -249,13 +249,13 @@ pub(crate) unsafe fn paint(hwnd: HWND) {
let sel = SELECTED[i].load(Relaxed);
ui.round(cb, 5.0, if sel { ACCENT } else { PANEL }, if sel { ACCENT } else { lerp(BORDER, TEXT, if hot(ID_CHECK + i) { 0.4 } else { 0.0 }) });
if sel {
- ui.text_in("\u{E73E}", cb, 11.0, 700, rgb(255, 255, 255), DT_CENTER | DT_VCENTER | DT_SINGLELINE, "Segoe MDL2 Assets");
+ ui.text_in("\u{E73E}", cb, 11.0, 700, rgb(255, 255, 255), DT_CENTER | DT_VCENTER | DT_SINGLELINE, winrust_common::style::icon_face());
}
let tile = [r[0] + 42.0, r[1] + 13.0, r[0] + 78.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");
+ ui.text_in(p.glyph, tile, 16.0, 400, if lit { ACCENT } else { TEXT }, DT_CENTER | DT_VCENTER | DT_SINGLELINE, winrust_common::style::icon_face());
let (pill, pc) = if working {
(if job == n { t!("Удаление…", "Removing…") } else { t!("Установка…", "Installing…") }, ACCENT)
@@ -282,7 +282,7 @@ pub(crate) unsafe fn paint(hwnd: HWND) {
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");
+ ui.text_in("\u{E713}", gb, 14.0, 400, if busy { DIM } else { TEXT }, DT_CENTER | DT_VCENTER | DT_SINGLELINE, winrust_common::style::icon_face());
}
}
@@ -319,7 +319,7 @@ pub(crate) unsafe fn paint(hwnd: HWND) {
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_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, winrust_common::style::icon_face());
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);
}
@@ -354,7 +354,7 @@ pub(crate) unsafe fn paint(hwnd: HWND) {
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_in(if danger { "\u{E7BA}" } else { "\u{E946}" }, icon, 16.0, 400, accent, DT_CENTER | DT_VCENTER | DT_SINGLELINE, winrust_common::style::icon_face());
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, t!("Отмена", "Cancel"), 1, hot(ID_CANCEL));
@@ -371,7 +371,7 @@ pub(crate) unsafe fn paint(hwnd: HWND) {
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_in("\u{E713}", icon, 16.0, 400, ACCENT, DT_CENTER | DT_VCENTER | DT_SINGLELINE, winrust_common::style::icon_face());
ui.text(&tf!("Настройки {}", "{} settings", 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();