Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
05a3f7a8f4 | ||
|
|
12b8f5090c | ||
|
|
19d574edcf | ||
|
|
3840744819 | ||
|
|
94e8ba4304 | ||
|
|
edb1440be0 | ||
|
|
8ef13ca9bd | ||
|
|
c0eca89738 | ||
|
|
0b6709495b | ||
|
|
5f0c51b557 | ||
|
|
733b6deefa | ||
|
|
b3a1e762ec | ||
|
|
219bdd4883 | ||
|
|
d018b91397 |
No files matched your search
+5
-1
@@ -1,5 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.24)
|
||||
project(KSwitcher VERSION 0.6.106 LANGUAGES CXX RC)
|
||||
project(KSwitcher VERSION 0.6.110 LANGUAGES CXX RC)
|
||||
if(NOT WIN32)
|
||||
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
|
||||
endif()
|
||||
@@ -7,6 +7,10 @@ set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
add_executable(KSwitcherFiles WIN32 src/files_main.cpp src/files_text_window.cpp
|
||||
src/files_text_document.cpp src/files_text_language.cpp resources/files.rc)
|
||||
set_property(SOURCE resources/files.rc APPEND PROPERTY OBJECT_DEPENDS
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files.ico"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-viewer.ico"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-editor.ico")
|
||||
include(cmake/FilesTextLibraries.cmake)
|
||||
set_target_properties(KSwitcherFiles PROPERTIES OUTPUT_NAME "KSwitcher.Files")
|
||||
target_compile_definitions(KSwitcherFiles PRIVATE UNICODE _UNICODE NOMINMAX _WIN32_WINNT=0x0A00)
|
||||
|
||||
+51
-10
@@ -1,6 +1,7 @@
|
||||
# Оформлення KSwitcher Files
|
||||
|
||||
Far Manager є зразком для оформлення файлового менеджера. Основне вікно використовує системний заголовок Windows. Панелі, меню й діалоги операцій використовують моноширинний шрифт менеджера та оформлення в стилі Far.
|
||||
Іконка головного вікна показує дві сині панелі з бірюзовою рамкою та виділеним рядком.
|
||||
|
||||
Власні модальні діалоги панелей, редактора й переглядача використовують
|
||||
`FilesModalDialog`. Escape і клік поза діалогом у клієнтській області Files
|
||||
@@ -37,19 +38,51 @@ Warning і початковий фокус на No.
|
||||
Папка відкривається у Провіднику, файл виконує свою стандартну дію Windows.
|
||||
|
||||
- У головному вікні клавіатурний фокус залишається в командному рядку.
|
||||
Tab перемикає активну панель, клік вибирає рядок, а стрілки вгору й вниз,
|
||||
Page Up і Page Down пересувають курсор у панелі навіть під час набору команди.
|
||||
Tab перемикає активну панель, а клік вибирає рядок.
|
||||
Page Up і Page Down пересувають курсор у панелі. Стрілки вгору й вниз
|
||||
керують панеллю, коли список підказок закритий.
|
||||
Стрілки вліво й вправо переходять до першого й останнього рядків, коли
|
||||
командний рядок порожній.
|
||||
Клік оновлює підсвічування рядків курсора без перемальовування всієї панелі.
|
||||
Меню й діалоги тимчасово приймають фокус. Ctrl+V і Shift+Insert вставляють
|
||||
текст із буфера обміну в позицію курсора або замінюють виділення.
|
||||
Enter і Shift+Enter спочатку виконують введену команду. Коли рядок
|
||||
Enter виконує введену команду, якщо підказку не вибрано. Shift+Enter
|
||||
виконує команду одразу. Коли рядок
|
||||
порожній, Enter відкриває поточний елемент. Якщо панелі приховано,
|
||||
Enter передає порожній рядок у термінал. Escape очищає рядок.
|
||||
Enter передає порожній рядок у термінал.
|
||||
Якщо фокус у виводі термінала, Enter і Shift+Enter повертають його до
|
||||
командного рядка й виконують відповідну дію за тими самими правилами.
|
||||
Промпт і текст команди вирівняні по спільній базовій лінії.
|
||||
- Під час набору локальної команди над полем з’являються підказки PowerShell.
|
||||
Автодоповнення працює з відкритими й прихованими панелями (Ctrl+O).
|
||||
Список уточнюється після кожної зміни тексту й доповнює команди, параметри
|
||||
та шляхи відносно робочої папки термінала або активної панелі до запуску
|
||||
термінала. Після `cd ` список пропонує папки,
|
||||
а після вибору можна продовжити шлях через `\`, зокрема всередині лапок.
|
||||
Стрілки вгору й вниз вибирають підказку. Tab вставляє вибрану або першу,
|
||||
Enter вставляє виділену, а клік вставляє підказку під вказівником.
|
||||
Щоб виконати команду після вставлення, натисни Enter ще раз.
|
||||
Escape закриває список зі збереженням тексту. Без списку Escape очищає
|
||||
рядок, а Tab перемикає панель, якщо панелі відкриті. Доступні підказки стандартної локальної
|
||||
сесії PowerShell, включно з програмами з PATH. Для команд без аргументів,
|
||||
як-от `cls`, список не пропонує шляхи.
|
||||
Для `dotnet` підкоманди й параметри підказує встановлений .NET SDK.
|
||||
Для `git` підкоманди, параметри й доречні назви гілок бере штатний
|
||||
скрипт Git for Windows. Підказки використовують локальні дані репозиторію.
|
||||
- Довідник Windows Commands надає офлайн підказки ключів і підкоманд для
|
||||
системних утиліт. Наприклад, `ipconfig /re` пропонує `/release` і `/renew`,
|
||||
`reg q` пропонує `query`, а `cmd /c dir /` пропонує ключі `dir` для CMD.
|
||||
Каталог також підказує вкладені підкоманди та значення, перелічені в
|
||||
синтаксисі. Наприклад, `netsh interface ipv4 show co` пропонує `config`,
|
||||
а `schtasks /query /fo ` пропонує `CSV`, `LIST` і `TABLE`. F1 у командному
|
||||
рядку відкриває статтю Microsoft Learn для поточної команди чи підкоманди.
|
||||
Якщо ввести `dir` безпосередньо у Files, PowerShell підказує власні параметри.
|
||||
Після `ipconfig /renew ` або `ipconfig /release ` список підказує назви
|
||||
локальних адаптерів із DHCP для IPv4. Назви з пробілами вставляються в лапках.
|
||||
- Коли курсор у кінці рядка, список спочатку показує до 5 різних
|
||||
останніх команд з історії, які починаються з набраного тексту.
|
||||
Вибір підставляє всю команду. Підказки з історії доступні й у LAN-панелі.
|
||||
|
||||
- **F8 Delete** у нижньому рядку клавіш викликає той самий діалог видалення,
|
||||
що й клавіша F8.
|
||||
- У нижньому рядку, як у FAR, позначення клавіш сірі на чорному тлі,
|
||||
@@ -69,6 +102,15 @@ Warning і початковий фокус на No.
|
||||
**Options → Command line → Command history → Allow paired PCs to hibernate this PC**.
|
||||
Дозвіл за замовчуванням вимкнений і діє лише для спарених ПК. Для цієї дії
|
||||
потрібні оновлення на обох ПК і ввімкнена гібернація Windows.
|
||||
- У **Change drive** (Alt+F1 або Alt+F2) підкреслена дія **Wake** є праворуч
|
||||
від стану офлайн-ПК. Клік по слову або Enter з фокусом на дії надсилає пакет.
|
||||
Статус відображається на тлі списку. Для текстових дій усередині рядків
|
||||
використовуй спільний компонент `InlineListAction` для малювання, фокуса
|
||||
й обробки кліків. KSwitcher
|
||||
має зберегти MAC-адресу мережевого адаптера. Оновіть KSwitcher та дайте
|
||||
обом ПК побачити один одного в локальній мережі. На цільовому ПК потрібна
|
||||
підтримка Wake-on-LAN у прошивці та налаштуваннях адаптера. Рядок стану
|
||||
повідомляє про надсилання пакета або відсутність збереженої MAC-адреси.
|
||||
- **F9 → Commands → Update remote KSwitcher** запускає штатне оновлення для
|
||||
ПК активної LAN-панелі. Підтвердження з іменем ПК показується у Files
|
||||
відправника. На цільовому ПК потрібен дозвіл **Options → Command line →
|
||||
@@ -85,7 +127,9 @@ Warning і початковий фокус на No.
|
||||
за тими ж правилами вставлення й лапок. Рядок `..` пропускається.
|
||||
- Локальні й LAN-каталоги скануються у фоновому потоці. Під час переходу
|
||||
активна панель показує «Loading folder…» і зберігає попередній список до
|
||||
завершення сканування. Якщо надійшов новіший запит, результат попереднього
|
||||
завершення сканування. Після переходу оновлюються шлях і список цієї панелі
|
||||
та командний рядок. Сусідня панель не перемальовується через цей перехід.
|
||||
Якщо надійшов новіший запит, результат попереднього
|
||||
сканування пропускається. Після підтвердження UAC очікування списку
|
||||
від підвищеного процесу теж відбувається у фоні.
|
||||
- Ctrl+R перечитує поточну папку активної панелі. Позиція курсора й позначки
|
||||
@@ -144,7 +188,8 @@ Warning і початковий фокус на No.
|
||||
- Глобальне скорочення повертає до відкритого вікна Files у поточній сесії Windows або запускає Files, якщо такого вікна немає. Пункт **Files** у треї відкриває нове вікно.
|
||||
|
||||
- Ctrl+Shift+0–9 відкриває діалог Title і Path із поточною папкою. OK додає запис без дублювання, Escape скасовує. Title необов’язковий, порожнє значення показує шлях. Записи LAN зберігають ID ПК, а редагування Path залишає запис на тому самому ПК.
|
||||
- Ctrl+0–9 одразу відкриває єдину папку. Для кількох папок відкривається компактний попап Far з одним заголовком Folder shortcuts у подвійній рамці та коротким рядом клавіш у нижній рамці. Ширина залежить від найдовшого запису й обмежується розміром вікна, а висота — кількістю видимих рядків. Нижня рамка показує Ins Del F4 Ctrl+Up Ctrl+Down. Insert додає поточну папку через Title і Path, Delete відв’язує, F4 редагує, Ctrl+Up і Ctrl+Down змінюють і зберігають порядок. Enter відкриває папку. Escape або клік у Files поза попапом закриває його й повертає фокус до панелі. Commands → Folder shortcuts дає вибрати зайняту цифру й відкрити той самий попап навіть для єдиного запису. Brief і Wide доступні в меню Left/Right та Options.
|
||||
- Ctrl+0–9 відкриває лише папки, призначені натиснутій цифрі. Єдина папка відкривається одразу. Для кількох папок відкривається компактний попап Far з одним заголовком Folder shortcuts у подвійній рамці та коротким рядом клавіш у нижній рамці. Ширина залежить від найдовшого запису й обмежується розміром вікна, а висота — кількістю видимих рядків. Нижня рамка показує Ins Del F4 Ctrl+Up Ctrl+Down. Insert додає поточну папку через Title і Path, Delete відв’язує, F4 редагує, Ctrl+Up і Ctrl+Down змінюють і зберігають порядок. Enter відкриває папку. Escape або клік у Files поза попапом закриває його й повертає фокус до панелі. Commands → Folder shortcuts дає вибрати зайняту цифру й відкрити той самий попап навіть для єдиного запису.
|
||||
- Ctrl+F1 вмикає Brief, Ctrl+F2 вмикає Wide для активної панелі. Ctrl+F3–F12 зарезервовані для інших режимів панелей. Brief і Wide також доступні в меню Left/Right та Options.
|
||||
|
||||
## Налаштування Files
|
||||
|
||||
@@ -272,10 +317,6 @@ Warning і початковий фокус на No.
|
||||
у відкритих локальних папках. Фокус залишається там, де був, а курсор
|
||||
лишається на поточному елементі, якщо той ще існує.
|
||||
|
||||
- Ctrl+8 відкриває список усіх ярликів папок. Кожен рядок показує групу
|
||||
й назву або шлях. Enter відкриває папку в активній панелі, F4 редагує
|
||||
ярлик, а Delete прибирає його зі списку.
|
||||
|
||||
- У Change drive повідомлення No paired computers з’являється після
|
||||
успішної відповіді з порожнім списком. Збої локального запиту до
|
||||
KSwitcher відображаються окремо.
|
||||
|
||||
@@ -873,7 +873,8 @@ after Space, not immediately after a punctuation key. Save Settings to apply cha
|
||||
only to words with a rank at or below that number (for example, 10000). All dictionary words still
|
||||
protect already valid input, and ambiguous alternatives remain unchanged regardless of this limit.
|
||||
**My dictionary** provides separate English, Ukrainian and Russian fields for correct words missing
|
||||
from the bundled dictionaries. Enter words separated by commas or new lines, then click OK and Save
|
||||
from the bundled dictionaries. A hyphen is allowed between letters, as in `test-mt` or `dev-mt`.
|
||||
Enter words separated by commas or new lines, then click OK and Save
|
||||
in Settings. Case and duplicates are normalized automatically; no file editing or ranks are needed.
|
||||
The v0.6.23 bundled Ukrainian dictionary includes `поточні`. The updater preserves existing dictionary files;
|
||||
if upgrading from an older dictionary, add this word in My dictionary → Ukrainian and click OK → Save.
|
||||
@@ -897,8 +898,10 @@ language in the configured dictionary order (the UI uses English, Ukrainian, Rus
|
||||
Different valid spellings remain ambiguous and are left unchanged.
|
||||
**Minimum word length** defaults to 3 and can be set from 1 to 32 letters. Surrounding punctuation
|
||||
does not count toward this minimum; the maximum word length is 32 letters.
|
||||
Known words, ambiguous alternatives, ALL CAPS, mixed-case identifiers, numbers, URLs and email
|
||||
addresses are left unchanged. Short trailing punctuation is retained when the editor selects it
|
||||
Known words, ambiguous alternatives, mixed-case identifiers, numbers, URLs and email addresses
|
||||
are left unchanged. Fully uppercase words can be corrected when the target is in **My dictionary**.
|
||||
For example, add `qa` under English and set the minimum word length to 2 or lower to correct
|
||||
`ЙФ` to `QA` after Space. Short trailing punctuation is retained when the editor selects it
|
||||
together with the word. Actual selected text is verified before replacement. Layout switching follows
|
||||
the existing switch-layout setting. The configured Undo shortcut restores the original and suppresses
|
||||
that word for the rest of the session (until restart).
|
||||
@@ -924,8 +927,9 @@ CC BY-SA 4.0; attribution, pinned source revision and license are in `dictionari
|
||||
|
||||
Download the portable Windows x64 ZIP from [Gitea Releases](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/releases).
|
||||
The [Release folder](Release/README.md) tracks the release notes, manifest and SHA-256 checksum.
|
||||
Run `./package.ps1 -PublishRelease` after building and testing, then upload the generated ZIP,
|
||||
manifest and checksum as release assets.
|
||||
Run `./package.ps1 -PublishRelease` after building and testing. Upload `dist/KSwitcher-win-x64.zip`,
|
||||
`dist/KSwitcher/release-files.json` and `Release/SHA256SUMS.txt` as Gitea release assets.
|
||||
Keep the ZIP in `dist/` and attach it to the release without committing it to Git.
|
||||
|
||||
## Verification
|
||||
|
||||
|
||||
@@ -1,5 +1,53 @@
|
||||
# Latest Windows release
|
||||
|
||||
## v0.6.110 — 2026-11-17
|
||||
|
||||
Entering a folder or returning to its parent in KSwitcher Files refreshes the affected panel and the command line without repainting the other panel.
|
||||
|
||||
Auto-correction can preserve all uppercase letters when correcting to a word in **My dictionary**. With `qa` in the English personal dictionary and **Minimum word length** set to 2 or lower, typing `ЙФ` and pressing Space yields `QA`.
|
||||
|
||||
**Українською.**
|
||||
|
||||
Під час входу в папку або повернення до батьківської папки KSwitcher Files оновлює потрібну панель і командний рядок. Сусідня панель більше не перемальовується через цей перехід.
|
||||
|
||||
Автокорекція зберігає верхній регістр для слів з **My dictionary**. Якщо в особистому словнику English є `qa`, а **Minimum word length** дорівнює 2 або менше, після пробілу `ЙФ` виправиться на `QA`.
|
||||
|
||||
## v0.6.109 — 2026-11-17
|
||||
|
||||
**Ctrl+0–9** in KSwitcher Files opens the assigned folder or shows only the folders assigned to that digit. **Ctrl+F1** selects Brief and **Ctrl+F2** selects Wide in the active panel. **Ctrl+F3–F12** are reserved for other panel modes. If command history used a Ctrl+function shortcut, set a new binding under **Options → Command line → Command history**.
|
||||
|
||||
**My dictionary** accepts hyphens between letters, for example `test-mt` and `dev-mt`. Enter the correct spelling in the dictionary for its language, then click **OK → Save**. Update all PCs that share settings before syncing hyphenated entries.
|
||||
|
||||
**Українською.**
|
||||
|
||||
У KSwitcher Files **Ctrl+0–9** відкриває призначену папку або показує лише папки, призначені натиснутій цифрі. **Ctrl+F1** вмикає Brief, а **Ctrl+F2** вмикає Wide в активній панелі. **Ctrl+F3–F12** зарезервовані для інших режимів панелей. Якщо історія команд використовувала Ctrl із функціональною клавішею, задайте нову комбінацію в **Options → Command line → Command history**.
|
||||
|
||||
**My dictionary** приймає дефіси між літерами, наприклад `test-mt` і `dev-mt`. Введіть правильне написання у словник відповідної мови й натисніть **OK → Save**. Перед синхронізацією слів із дефісами оновіть усі ПК, які обмінюються налаштуваннями.
|
||||
|
||||
## v0.6.108 — 2026-11-17
|
||||
|
||||
KSwitcher Files adds **Wake** beside the offline status of a paired PC in **Change drive** (Alt+F1 or Alt+F2). Click **Wake** or focus it with the arrow keys and press **Enter**. The status bar reports whether KSwitcher sent the Wake-on-LAN packet.
|
||||
|
||||
Update both PCs and let them discover each other once while the target is online so KSwitcher can save its network adapter’s MAC address. Enable Wake-on-LAN on the target. Ethernet is the most reliable option. Wi-Fi requires compatible Wake on Wireless LAN hardware and drivers.
|
||||
|
||||
**Українською.**
|
||||
|
||||
У KSwitcher Files біля статусу спареного офлайн-ПК у меню **Change drive** (Alt+F1 або Alt+F2) є дія **Wake**. Клацніть **Wake** або виберіть її стрілками й натисніть **Enter**. Рядок стану повідомить, чи вдалося надіслати пакет Wake-on-LAN.
|
||||
|
||||
Оновіть обидва ПК і дайте їм один раз побачити один одного, поки цільовий ПК увімкнено, щоб KSwitcher зберіг MAC-адресу його мережевого адаптера. Увімкніть Wake-on-LAN на цільовому ПК. Найнадійніше підключення через Ethernet. Для Wi-Fi потрібна підтримка Wake on Wireless LAN з боку обладнання й драйвера.
|
||||
|
||||
## v0.6.107 — 2026-11-16
|
||||
|
||||
KSwitcher Files suggests recent commands, PowerShell commands and parameters, and paths as you type. The list works with the panes visible or hidden. Use **Up** or **Down** to select, **Tab** or **Enter** on a selected suggestion to insert it, and **Escape** to close the list. Press **F1** in the command line to open the Microsoft Learn article for a documented Windows command or subcommand.
|
||||
|
||||
The offline Windows command catalog includes nested syntax and documented choices such as `schtasks /query /fo LIST`. After `ipconfig /renew ` or `ipconfig /release `, Files suggests local IPv4 adapters configured for DHCP. With Git for Windows, Git completion includes options and matching branch names. With the .NET SDK, `dotnet` completion delegates to the CLI. The main Files window has a new blue two-pane icon inspired by FAR.
|
||||
|
||||
**Українською.**
|
||||
|
||||
KSwitcher Files підказує недавні команди з історії, команди й параметри PowerShell та шляхи під час набору. Список працює з відкритими й прихованими панелями. Стрілки **↑** і **↓** вибирають підказку, **Tab** або **Enter** на вибраній підказці вставляє її, а **Escape** закриває список. **F1** у командному рядку відкриває статтю Microsoft Learn для документованої команди чи підкоманди Windows.
|
||||
|
||||
Офлайн-каталог команд Windows містить вкладений синтаксис і документовані значення, наприклад `schtasks /query /fo LIST`. Після `ipconfig /renew ` або `ipconfig /release ` Files підказує локальні адаптери з DHCP для IPv4. За наявності Git for Windows підказки Git включають параметри й відповідні назви гілок. За наявності .NET SDK підказки для `dotnet` надає сама утиліта. Головне вікно Files має нову синю іконку з двома панелями в стилі FAR.
|
||||
|
||||
## v0.6.106 — 2026-11-16
|
||||
|
||||
Files scans local and LAN folders and runs copy, move, rename and delete in the background. Copy and Rename/Move validate destinations in the background. A failed operation opens a red Far-style dialog. For local sharing violations, **Processes…** shows possible blockers and **End process** ends the selected process after confirmation. Retry **F6**, **F8**, or **Shift+Delete** after releasing the item.
|
||||
|
||||
@@ -1 +1 @@
|
||||
1094524ee07ae94bebddd7dcfa6047fb1ca3d5ce86df9072aa1e881e90b95412 KSwitcher-win-x64.zip
|
||||
6b25873e86443d57a6bc669170c64d30c79d1a41849739b685b8d0f94f2f4576 KSwitcher-win-x64.zip
|
||||
+77
-77
@@ -1,166 +1,166 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"version": "0.6.106",
|
||||
"version": "0.6.110",
|
||||
"files": [
|
||||
{
|
||||
"size": 2369024,
|
||||
"sha256": "0b53535ef8f50f9ec504ed82b930dd2afc862105acdc38a9cfc09059123f0ff2",
|
||||
"path": "KSwitcher.exe"
|
||||
"path": "KSwitcher.exe",
|
||||
"sha256": "eab543bf53474e7cd0523a96441b0054dbfad8e4b3119f73b552d311233b30da",
|
||||
"size": 2373632
|
||||
},
|
||||
{
|
||||
"size": 2366464,
|
||||
"sha256": "d4f1338575cb808497bfc3cb334a32129a66f0efd164a26c8cc5d0a8d5eca8bc",
|
||||
"path": "KSwitcher.Config.exe"
|
||||
"path": "KSwitcher.Config.exe",
|
||||
"sha256": "85da336ddec715bfe1660e36969729c83a20f39d5e0cddb4b5091a2c6fa9ce64",
|
||||
"size": 2370560
|
||||
},
|
||||
{
|
||||
"size": 3346432,
|
||||
"sha256": "1416152e756cdbd37ce29d6337806cce5ceea26f3a03680f050ba8282a380de0",
|
||||
"path": "KSwitcher.Screenshot.exe"
|
||||
"path": "KSwitcher.Screenshot.exe",
|
||||
"sha256": "8e4a38e2b058e6442a8fc40ade9434e771389fceadc3a32bb4ef5287d84fd6f0",
|
||||
"size": 3350016
|
||||
},
|
||||
{
|
||||
"size": 3866112,
|
||||
"sha256": "8be3992909882beb7c94280f3b6902b59f19854f67f0a68d4b753682750edb85",
|
||||
"path": "KSwitcher.Files.exe"
|
||||
"path": "KSwitcher.Files.exe",
|
||||
"sha256": "3640e0612d8a54d523b63e2a9f8a6281047679ead9b47058a8d6274cf04b175a",
|
||||
"size": 4208128
|
||||
},
|
||||
{
|
||||
"size": 194912,
|
||||
"path": "WebView2Loader.dll",
|
||||
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
|
||||
"path": "WebView2Loader.dll"
|
||||
"size": 194912
|
||||
},
|
||||
{
|
||||
"size": 1103,
|
||||
"path": "terminal/addon-fit-LICENSE.txt",
|
||||
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
|
||||
"path": "terminal/addon-fit-LICENSE.txt"
|
||||
"size": 1103
|
||||
},
|
||||
{
|
||||
"size": 1521,
|
||||
"path": "terminal/addon-fit.js",
|
||||
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
|
||||
"path": "terminal/addon-fit.js"
|
||||
"size": 1521
|
||||
},
|
||||
{
|
||||
"size": 527,
|
||||
"path": "terminal/index.html",
|
||||
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
|
||||
"path": "terminal/index.html"
|
||||
"size": 527
|
||||
},
|
||||
{
|
||||
"size": 1073,
|
||||
"path": "terminal/markdown-it-LICENSE.txt",
|
||||
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
|
||||
"path": "terminal/markdown-it-LICENSE.txt"
|
||||
"size": 1073
|
||||
},
|
||||
{
|
||||
"size": 100786,
|
||||
"path": "terminal/markdown-it.js",
|
||||
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
|
||||
"path": "terminal/markdown-it.js"
|
||||
"size": 100786
|
||||
},
|
||||
{
|
||||
"size": 3530,
|
||||
"path": "terminal/markdown.html",
|
||||
"sha256": "e5381c35fb254b558c8b869746e2e575c8ed53600611ac90597ed2dd80fa321c",
|
||||
"path": "terminal/markdown.html"
|
||||
"size": 3530
|
||||
},
|
||||
{
|
||||
"size": 14660,
|
||||
"sha256": "fe202fa3d3c362aff2ab9028b40bd2aee61240bf9bd4a44af55e45d1a4081cf0",
|
||||
"path": "terminal/markdown.js"
|
||||
"path": "terminal/markdown.js",
|
||||
"sha256": "5d1e824df1c3570877e985de0cfaae3f2984ceef7fe23bf4c5ade3c890a93223",
|
||||
"size": 14987
|
||||
},
|
||||
{
|
||||
"size": 1089,
|
||||
"path": "terminal/mermaid-LICENSE.txt",
|
||||
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
|
||||
"path": "terminal/mermaid-LICENSE.txt"
|
||||
"size": 1089
|
||||
},
|
||||
{
|
||||
"size": 5537838,
|
||||
"path": "terminal/mermaid.js",
|
||||
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
|
||||
"path": "terminal/mermaid.js"
|
||||
"size": 5537838
|
||||
},
|
||||
{
|
||||
"size": 5033,
|
||||
"path": "terminal/terminal.js",
|
||||
"sha256": "0557d251962301940785690a3fc49475dd166bb7d0bd0417dc3279d1f1b3a98a",
|
||||
"path": "terminal/terminal.js"
|
||||
"size": 5033
|
||||
},
|
||||
{
|
||||
"size": 1261,
|
||||
"path": "terminal/xterm-LICENSE.txt",
|
||||
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
|
||||
"path": "terminal/xterm-LICENSE.txt"
|
||||
"size": 1261
|
||||
},
|
||||
{
|
||||
"size": 7112,
|
||||
"path": "terminal/xterm.css",
|
||||
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
|
||||
"path": "terminal/xterm.css"
|
||||
"size": 7112
|
||||
},
|
||||
{
|
||||
"size": 488663,
|
||||
"path": "terminal/xterm.js",
|
||||
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
|
||||
"path": "terminal/xterm.js"
|
||||
"size": 488663
|
||||
},
|
||||
{
|
||||
"size": 4401,
|
||||
"path": "LICENSE",
|
||||
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
|
||||
"path": "LICENSE"
|
||||
"size": 4401
|
||||
},
|
||||
{
|
||||
"size": 1075,
|
||||
"sha256": "c0d068392ea65358b798b8c165103560f06e9e3b38c4ab4e2d8810a7b931af86",
|
||||
"path": "json-LICENSE.txt"
|
||||
"path": "json-LICENSE.txt",
|
||||
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
|
||||
"size": 1096
|
||||
},
|
||||
{
|
||||
"size": 883,
|
||||
"path": "files-text-license.txt",
|
||||
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
|
||||
"path": "files-text-license.txt"
|
||||
"size": 883
|
||||
},
|
||||
{
|
||||
"size": 94769,
|
||||
"sha256": "adda764fa7ca0cf80958ef44ed446b438ffa18b5f996c7ef19b553132d0f112a",
|
||||
"path": "README.md"
|
||||
"path": "README.md",
|
||||
"sha256": "eb9cc6aa8f764cb0e1bdf2aa073e4e3d2623a7afc51ed9c6a0aba4046fc7f74c",
|
||||
"size": 95168
|
||||
},
|
||||
{
|
||||
"size": 11577,
|
||||
"path": "LAN-PREVIEW.md",
|
||||
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930",
|
||||
"path": "LAN-PREVIEW.md"
|
||||
"size": 11577
|
||||
},
|
||||
{
|
||||
"size": 682867,
|
||||
"sha256": "5f267c141c3d6837870e1c098f86b89a113ba300343119432644ead88f720c21",
|
||||
"path": "dictionaries/en.txt"
|
||||
"path": "dictionaries/en.txt",
|
||||
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
|
||||
"size": 732485
|
||||
},
|
||||
{
|
||||
"size": 20138,
|
||||
"sha256": "28a9529c7d0bb4dc51f4bf5c116a3d16ef247a052f7591466768ddf563fd1cf5",
|
||||
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt"
|
||||
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
|
||||
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
|
||||
"size": 20566
|
||||
},
|
||||
{
|
||||
"size": 2265,
|
||||
"path": "dictionaries/README.md",
|
||||
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
|
||||
"path": "dictionaries/README.md"
|
||||
"size": 2265
|
||||
},
|
||||
{
|
||||
"size": 1060364,
|
||||
"sha256": "9ef922c7699569304a428f6aba0fd13a21341c0d0cb9561f37ef83c41577a28b",
|
||||
"path": "dictionaries/ru.txt"
|
||||
"path": "dictionaries/ru.txt",
|
||||
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
|
||||
"size": 1109134
|
||||
},
|
||||
{
|
||||
"size": 1280,
|
||||
"path": "dictionaries/sources.json",
|
||||
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
|
||||
"path": "dictionaries/sources.json"
|
||||
"size": 1280
|
||||
},
|
||||
{
|
||||
"size": 940799,
|
||||
"path": "dictionaries/uk.txt",
|
||||
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
|
||||
"path": "dictionaries/uk.txt"
|
||||
"size": 940799
|
||||
},
|
||||
{
|
||||
"size": 993,
|
||||
"path": "tools/README.txt",
|
||||
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
|
||||
"path": "tools/README.txt"
|
||||
"size": 993
|
||||
},
|
||||
{
|
||||
"size": 134656,
|
||||
"path": "tools/StayHere.exe",
|
||||
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376",
|
||||
"path": "tools/StayHere.exe"
|
||||
"size": 134656
|
||||
},
|
||||
{
|
||||
"size": 2796,
|
||||
"path": "tools/StayHere-README.md",
|
||||
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
|
||||
"path": "tools/StayHere-README.md"
|
||||
"size": 2796
|
||||
}
|
||||
]
|
||||
],
|
||||
"schema": 1
|
||||
}
|
||||
+3
-4
@@ -41,12 +41,11 @@ try {
|
||||
[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,(Join-Path $destination $name),$name,[IO.Compression.CompressionLevel]::Optimal) | Out-Null
|
||||
}
|
||||
} finally { $zip.Dispose(); $stream.Dispose() }
|
||||
Get-FileHash -LiteralPath $archive -Algorithm SHA256
|
||||
$archiveHash = Get-FileHash -LiteralPath $archive -Algorithm SHA256
|
||||
$archiveHash
|
||||
if ($PublishRelease) {
|
||||
$release = Join-Path $root 'Release'
|
||||
New-Item -ItemType Directory -Force $release | Out-Null
|
||||
$published = Join-Path $release 'KSwitcher-win-x64.zip'
|
||||
Copy-Item -LiteralPath $archive -Destination $published -Force
|
||||
$hash = (Get-FileHash -LiteralPath $published -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||
$hash = $archiveHash.Hash.ToLowerInvariant()
|
||||
"$hash KSwitcher-win-x64.zip" | Set-Content -LiteralPath (Join-Path $release 'SHA256SUMS.txt') -Encoding ascii
|
||||
}
|
||||
+3
-3
@@ -9,8 +9,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
|
||||
1 RT_MANIFEST "app.manifest"
|
||||
201 RCDATA "update.ps1"
|
||||
1 VERSIONINFO
|
||||
FILEVERSION 0,6,106,0
|
||||
PRODUCTVERSION 0,6,106,0
|
||||
FILEVERSION 0,6,110,0
|
||||
PRODUCTVERSION 0,6,110,0
|
||||
FILEOS VOS_NT_WINDOWS32
|
||||
FILETYPE VFT_APP
|
||||
BEGIN
|
||||
@@ -20,7 +20,7 @@ BEGIN
|
||||
BEGIN
|
||||
VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility"
|
||||
VALUE "ProductName", "KSwitcher"
|
||||
VALUE "FileVersion", "0.6.106"
|
||||
VALUE "FileVersion", "0.6.110"
|
||||
END
|
||||
END
|
||||
BLOCK "VarFileInfo"
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 34 KiB After Width: | Height: | Size: 3.5 KiB |
+11
-4
@@ -34,13 +34,14 @@ std::wstring layoutLanguage(const Layout &layout)
|
||||
return {};
|
||||
}
|
||||
}
|
||||
bool safeAutoWord(const std::wstring &word, int minimumLength)
|
||||
bool safeAutoWord(const std::wstring &word, int minimumLength, bool allowUppercase)
|
||||
{
|
||||
if (minimumLength < 1 || minimumLength > 32 || word.size() < (size_t)minimumLength || word.size() > 32 ||
|
||||
!std::all_of(word.begin(), word.end(), letter))
|
||||
return false;
|
||||
auto small = lower(word);
|
||||
return word == small || (word.substr(1) == small.substr(1) && word != upper(word));
|
||||
const bool allUppercase = word == upper(word);
|
||||
return word == small || (allUppercase ? allowUppercase : word.substr(1) == small.substr(1));
|
||||
}
|
||||
namespace {
|
||||
constexpr size_t DictionaryBlockWords = 32;
|
||||
@@ -289,9 +290,15 @@ std::optional<AutoSuggestion> AutoCorrector::suggest(const std::wstring &typed,
|
||||
if (dictionary == dictionaries.end())
|
||||
continue;
|
||||
auto converted = convert(word, layouts[source], layouts[i], true);
|
||||
if (converted == word || !safeAutoWord(converted, settings.autoMinLength))
|
||||
if (converted == word)
|
||||
continue;
|
||||
int rank = personal(dictionary->first, converted) ? 1 : dictionary->second->rank(converted);
|
||||
const bool knownPersonal = personal(dictionary->first, converted);
|
||||
auto letters = converted;
|
||||
if (knownPersonal)
|
||||
std::erase(letters, L'-');
|
||||
if (!safeAutoWord(letters, settings.autoMinLength, knownPersonal))
|
||||
continue;
|
||||
int rank = knownPersonal ? 1 : dictionary->second->rank(converted);
|
||||
if (!rank)
|
||||
continue;
|
||||
if (matchedText && *matchedText != converted)
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ struct AutoSuggestion
|
||||
std::wstring text;
|
||||
};
|
||||
std::wstring layoutLanguage(const Layout &);
|
||||
bool safeAutoWord(const std::wstring &, int minimumLength = 3);
|
||||
bool safeAutoWord(const std::wstring &, int minimumLength = 3, bool allowUppercase = false);
|
||||
bool autoClosingSelection(const std::wstring &, const Settings & = {});
|
||||
int matchAutoInput(const Run &, const std::wstring &, const std::vector<Layout> &, const Layout &,
|
||||
const Settings & = {});
|
||||
|
||||
+12
-2
@@ -3,6 +3,7 @@
|
||||
#include <cwctype>
|
||||
#include <map>
|
||||
#include <stdexcept>
|
||||
#include <string_view>
|
||||
|
||||
namespace ks
|
||||
{
|
||||
@@ -21,20 +22,29 @@ int snippetAppPriority(const Snippet &snippet, const std::wstring &process)
|
||||
for (const auto &app : snippet.apps) if (snippetAppName(app) == name && !name.empty()) return 2;
|
||||
return 0;
|
||||
}
|
||||
bool validAutoCorrection(const std::wstring &text, const std::wstring &alphabet)
|
||||
static bool validSeparatedWord(const std::wstring &text, const std::wstring &alphabet,
|
||||
std::wstring_view separators)
|
||||
{
|
||||
if (text.empty() || text.size() > 32) return false;
|
||||
auto isLetter = [&](wchar_t c) { return alphabet.find(c) != alphabet.npos; };
|
||||
for (size_t i = 0; i < text.size(); ++i)
|
||||
{
|
||||
if (isLetter(text[i])) continue;
|
||||
if (text[i] != L' ' && text[i] != L'\'' && text[i] != L'\u2019' && text[i] != L'\u02bc')
|
||||
if (separators.find(text[i]) == separators.npos)
|
||||
return false;
|
||||
if (i == 0 || i + 1 == text.size() || !isLetter(text[i - 1]) || !isLetter(text[i + 1]))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool validAutoCorrection(const std::wstring &text, const std::wstring &alphabet)
|
||||
{
|
||||
return validSeparatedWord(text, alphabet, L" '\u2019\u02bc");
|
||||
}
|
||||
bool validPersonalWord(const std::wstring &text, const std::wstring &alphabet)
|
||||
{
|
||||
return validSeparatedWord(lower(text), alphabet, L"-");
|
||||
}
|
||||
bool validAutoReplacementSource(const std::wstring &text, const std::wstring &alphabet)
|
||||
{
|
||||
return text.find(L' ') == text.npos && text.find_first_of(alphabet) != text.npos &&
|
||||
|
||||
@@ -22,6 +22,7 @@ struct Layout
|
||||
bool letter(wchar_t ch);
|
||||
bool validAutoCorrection(const std::wstring &text, const std::wstring &alphabet);
|
||||
bool validAutoReplacementSource(const std::wstring &text, const std::wstring &alphabet);
|
||||
bool validPersonalWord(const std::wstring &text, const std::wstring &alphabet);
|
||||
std::wstring lower(std::wstring text);
|
||||
std::wstring upper(std::wstring text);
|
||||
std::wstring convert(const std::wstring &, const Layout &, const Layout &, bool force = false);
|
||||
|
||||
@@ -0,0 +1,321 @@
|
||||
#pragma once
|
||||
|
||||
#include "platform.h"
|
||||
#include "files_powershell.h"
|
||||
#include "files_windows_command_catalog.h"
|
||||
#include "../vendor/json.hpp"
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
class CommandCompletion
|
||||
{
|
||||
public:
|
||||
using Json = nlohmann::json;
|
||||
|
||||
CommandCompletion() = default;
|
||||
CommandCompletion(const CommandCompletion &) = delete;
|
||||
CommandCompletion &operator=(const CommandCompletion &) = delete;
|
||||
~CommandCompletion() { close(); }
|
||||
|
||||
bool request(const std::wstring &line, DWORD caret, const std::wstring &directory)
|
||||
{
|
||||
auto message=Json{{"line",utf8(line)},{"caret",caret},{"directory",utf8(directory)}}.dump(
|
||||
-1,' ',true,Json::error_handler_t::replace)+"\n";
|
||||
if(message.size()>32768 || (!process && !start())) return false;
|
||||
if(!write(message))
|
||||
{
|
||||
close();
|
||||
return false;
|
||||
}
|
||||
deadline=GetTickCount64()+5000;
|
||||
return true;
|
||||
}
|
||||
|
||||
// An empty optional means the request is still running.
|
||||
std::optional<Json> poll()
|
||||
{
|
||||
DWORD available{},count{};
|
||||
char chunk[8192];
|
||||
if(!PeekNamedPipe(output,nullptr,0,nullptr,&available,nullptr) ||
|
||||
GetTickCount64()>=deadline || pending.size()>1024*1024)
|
||||
{
|
||||
close();
|
||||
return Json{};
|
||||
}
|
||||
if(available && ReadFile(output,chunk,std::min<DWORD>(available,sizeof(chunk)),&count,nullptr))
|
||||
pending.append(chunk,count);
|
||||
const auto end=pending.find('\n');
|
||||
if(end==pending.npos) return {};
|
||||
auto result=Json::parse(pending.begin(),pending.begin()+end,nullptr,false);
|
||||
pending.erase(0,end+1);
|
||||
return result;
|
||||
}
|
||||
|
||||
private:
|
||||
HANDLE process{},input{},output{},job{};
|
||||
ULONGLONG deadline{};
|
||||
std::string pending;
|
||||
|
||||
bool write(std::string_view message)
|
||||
{
|
||||
DWORD written{};
|
||||
return WriteFile(input,message.data(),static_cast<DWORD>(message.size()),&written,nullptr) &&
|
||||
written==message.size();
|
||||
}
|
||||
|
||||
bool start()
|
||||
{
|
||||
SECURITY_ATTRIBUTES inheritable{sizeof(inheritable),nullptr,TRUE};
|
||||
HANDLE childInput{},childOutput{};
|
||||
std::string catalog;
|
||||
for(const auto row:windowsCommandCatalog) catalog.append(row).push_back('\n');
|
||||
const auto initial=Json{{"catalog",std::move(catalog)}}.dump()+"\n";
|
||||
const auto inputCapacity=static_cast<DWORD>(initial.size()+32768);
|
||||
const bool pipes=CreatePipe(&childInput,&input,&inheritable,inputCapacity) &&
|
||||
CreatePipe(&output,&childOutput,&inheritable,65536) &&
|
||||
SetHandleInformation(input,HANDLE_FLAG_INHERIT,0) &&
|
||||
SetHandleInformation(output,HANDLE_FLAG_INHERIT,0);
|
||||
const bool started=pipes && launch(childInput,childOutput) && write(initial);
|
||||
if(childInput) CloseHandle(childInput);
|
||||
if(childOutput) CloseHandle(childOutput);
|
||||
if(!started) close();
|
||||
return started;
|
||||
}
|
||||
|
||||
bool launch(HANDLE childInput,HANDLE childOutput)
|
||||
{
|
||||
const auto shell=windowsPowerShell();
|
||||
if(shell.empty()) return false;
|
||||
// The request is data on stdin. PowerShell parses it for completion in this separate session.
|
||||
wchar_t command[]=LR"PS(powershell.exe -NoLogo -NoProfile -NonInteractive -Command "
|
||||
$ProgressPreference = 'SilentlyContinue';
|
||||
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false);
|
||||
function Get-CompletedArguments($command, $position, $includeCurrent) {
|
||||
foreach ($element in ($command.CommandElements | Select-Object -Skip 1)) {
|
||||
if ($element.Extent.EndOffset -gt $position -or
|
||||
(!$includeCurrent -and $element.Extent.EndOffset -eq $position)) { break }
|
||||
if ($element -is [System.Management.Automation.Language.StringConstantExpressionAst]) {
|
||||
$element.Value;
|
||||
} else { $element.Extent.Text }
|
||||
}
|
||||
}
|
||||
|
||||
function New-ArgumentCompletion([string]$value) {
|
||||
$text = $value;
|
||||
if ($value.StartsWith('@') -or $value -notmatch '^[\p{L}\p{M}\p{N}._/@:+,=\-]+$') {
|
||||
$quote = [string][char]39;
|
||||
$text = $quote + [System.Management.Automation.Language.CodeGeneration]::EscapeSingleQuotedStringContent($value) + $quote;
|
||||
}
|
||||
[System.Management.Automation.CompletionResult]::new($text, $value, 'ParameterValue', $value)
|
||||
}
|
||||
|
||||
function Get-DhcpAdapterNames {
|
||||
foreach ($adapter in [Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces()) {
|
||||
if (!$adapter.Supports([Net.NetworkInformation.NetworkInterfaceComponent]::IPv4)) { continue }
|
||||
try {
|
||||
if ($adapter.GetIPProperties().GetIPv4Properties().IsDhcpEnabled) { $adapter.Name }
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
$initial = ConvertFrom-Json -InputObject ([Console]::ReadLine());
|
||||
$windowsCommands = @{};
|
||||
$windowsHelp = @{};
|
||||
foreach ($row in ($initial.catalog -split '\r?\n')) {
|
||||
if (!$row) { continue }
|
||||
$name, $values, $article = $row.Split([char]9, 3);
|
||||
$windowsCommands[$name] = if ($values) { $values.Split(' ') } else { @() };
|
||||
if ($article) { $windowsHelp[$name] = $article }
|
||||
}
|
||||
$windowsRoots = @($windowsCommands.Keys | Where-Object { !($_.Contains(' ')) } | Sort-Object);
|
||||
$windowsPrograms = @(foreach ($name in $windowsRoots) { $name; $name + '.exe'; $name + '.com' });
|
||||
function Get-WindowsCommandContext($command, $position, $includeCurrent) {
|
||||
if (!$command) { return }
|
||||
$invoked = $command.GetCommandName();
|
||||
if (!$invoked -or !$windowsCommands.ContainsKey([IO.Path]::GetFileNameWithoutExtension($invoked))) { return }
|
||||
$resolved = Get-Command -Name ([WildcardPattern]::Escape($invoked)) -ErrorAction SilentlyContinue |
|
||||
Select-Object -First 1;
|
||||
if ($resolved -is [System.Management.Automation.AliasInfo]) { $resolved = $resolved.ResolvedCommand }
|
||||
if ($resolved -isnot [System.Management.Automation.ApplicationInfo]) { return }
|
||||
$name = [IO.Path]::GetFileNameWithoutExtension($resolved.Name);
|
||||
$arguments = @(Get-CompletedArguments $command $position $includeCurrent);
|
||||
$values = $null;
|
||||
if ($name -eq 'cmd') {
|
||||
for ($i = 0; $i -lt $arguments.Count; ++$i) {
|
||||
if ($arguments[$i] -notin '/c', '/k') { continue }
|
||||
if ($i + 1 -lt $arguments.Count) {
|
||||
$name = [IO.Path]::GetFileNameWithoutExtension($arguments[$i + 1]);
|
||||
$arguments = @($arguments | Select-Object -Skip ($i + 2));
|
||||
} else { $values = $windowsRoots }
|
||||
break
|
||||
}
|
||||
}
|
||||
$root = $name;
|
||||
$article = $windowsHelp[$name];
|
||||
if (!$values) {
|
||||
foreach ($argument in $arguments) {
|
||||
$child = $name + ' ' + $argument;
|
||||
if (!$windowsCommands.ContainsKey($child)) { break }
|
||||
$name = $child;
|
||||
if ($windowsHelp[$name]) { $article = $windowsHelp[$name] }
|
||||
}
|
||||
$values = $windowsCommands[$name];
|
||||
}
|
||||
@{ root = $root; values = $values; arguments = $arguments; article = $article }
|
||||
}
|
||||
|
||||
Register-ArgumentCompleter -Native -CommandName $windowsPrograms -ScriptBlock {
|
||||
param($word, $command, $position)
|
||||
$context = Get-WindowsCommandContext $command $position $false;
|
||||
if (!$context) { return }
|
||||
if ($context.root -eq 'ipconfig' -and $context.arguments.Count -and
|
||||
$context.arguments[0] -in '/renew','/release') {
|
||||
$script:adapterArguments = $true;
|
||||
if ($context.arguments.Count -ne 1) { return }
|
||||
$prefix = ([string]$word).Trim([char[]]@([char]39, [char]34));
|
||||
foreach ($adapterName in (Get-DhcpAdapterNames | Sort-Object -Unique)) {
|
||||
if ($adapterName.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) {
|
||||
New-ArgumentCompletion $adapterName
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if ($word -eq '?') { $word = '/?' }
|
||||
foreach ($value in $context.values) {
|
||||
if ($value.StartsWith([string]$word, [StringComparison]::OrdinalIgnoreCase)) {
|
||||
[System.Management.Automation.CompletionResult]::new($value)
|
||||
}
|
||||
}
|
||||
};
|
||||
Register-ArgumentCompleter -Native -CommandName dotnet,dotnet.exe -ScriptBlock {
|
||||
param($word, $command, $position)
|
||||
$offset = $position - $command.Extent.StartOffset;
|
||||
dotnet.exe complete --position $offset $command.ToString() 2>$null | ForEach-Object {
|
||||
[System.Management.Automation.CompletionResult]::new($_)
|
||||
}
|
||||
};
|
||||
function Find-GitCompletionTools {
|
||||
$git = Get-Command git.exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1;
|
||||
if (!$git) { return }
|
||||
$location = [IO.DirectoryInfo]::new([IO.Path]::GetDirectoryName($git.Source));
|
||||
for ($level = 0; $location -and $level -lt 3; ++$level) {
|
||||
$root = $location.FullName;
|
||||
$location = $location.Parent;
|
||||
$bash = Join-Path $root 'usr/bin/bash.exe';
|
||||
if (![IO.File]::Exists($bash)) { continue }
|
||||
foreach ($architecture in 'mingw64', 'mingw32', 'clangarm64') {
|
||||
$script = Join-Path $root ($architecture + '/share/git/completion/git-completion.bash');
|
||||
if ([IO.File]::Exists($script)) { return @{ bash = $bash; script = $script } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Send words as data to Git for Windows. Backslash-quote escapes are for Windows PowerShell's native argv.
|
||||
$gitCompletionRunner = @'
|
||||
export GIT_ALLOW_PROTOCOL= GIT_TERMINAL_PROMPT=0
|
||||
mapfile -t input
|
||||
for i in ~${!input[@]}~; do input[i]=~${input[i]%$'\r'}~; done
|
||||
source ~${input[0]}~ || exit
|
||||
words=(~${input[@]:1}~)
|
||||
cword=$(( ${#words[@]} - 1 ))
|
||||
cur=${words[cword]}
|
||||
prev=${words[cword-1]}
|
||||
__git_main
|
||||
if (( ${#COMPREPLY[@]} )); then printf '%s\n' ~${COMPREPLY[@]}~; fi
|
||||
'@.Replace('~', ('\' + [char]34));
|
||||
$OutputEncoding = [Console]::OutputEncoding;
|
||||
Register-ArgumentCompleter -Native -CommandName git,git.exe -ScriptBlock {
|
||||
param($word, $command, $position)
|
||||
if (!$script:gitCompletionTools) { $script:gitCompletionTools = Find-GitCompletionTools }
|
||||
if (!$script:gitCompletionTools) { return }
|
||||
$arguments = @('git') + @(Get-CompletedArguments $command $position) + @([string]$word);
|
||||
@($script:gitCompletionTools.script) + $arguments |
|
||||
& $script:gitCompletionTools.bash --noprofile --norc -p -c $gitCompletionRunner 2>$null |
|
||||
ForEach-Object {
|
||||
$value = $_.TrimEnd();
|
||||
if ($value) { New-ArgumentCompletion $value }
|
||||
}
|
||||
};
|
||||
function Get-CompletionCommand($request) {
|
||||
$prefix = $request.line.Substring(0, $request.caret).TrimEnd();
|
||||
$ast = [System.Management.Automation.Language.Parser]::ParseInput($prefix, [ref]$null, [ref]$null);
|
||||
$ast.FindAll({
|
||||
param($node)
|
||||
$node -is [System.Management.Automation.Language.CommandAst] -and
|
||||
$node.Extent.EndOffset -eq $prefix.Length
|
||||
}, $true) | Select-Object -Last 1;
|
||||
}
|
||||
function Test-NoCommandArguments($command) {
|
||||
if (!$command) { return $false }
|
||||
$name = $command.GetCommandName();
|
||||
if (!$name) { return $false }
|
||||
$info = Get-Command -Name ([WildcardPattern]::Escape($name)) -ErrorAction SilentlyContinue;
|
||||
if ($info -is [System.Management.Automation.AliasInfo]) { $info = $info.ResolvedCommand }
|
||||
return ($info -is [System.Management.Automation.FunctionInfo] -or
|
||||
$info -is [System.Management.Automation.CmdletInfo]) -and $info.Parameters.Count -eq 0;
|
||||
}
|
||||
while ($null -ne ($line = [Console]::ReadLine())) {
|
||||
try {
|
||||
$request = ConvertFrom-Json -InputObject $line -ErrorAction Stop;
|
||||
Set-Location -LiteralPath $request.directory -ErrorAction Stop;
|
||||
$script:adapterArguments = $false;
|
||||
$command = Get-CompletionCommand $request;
|
||||
$context = Get-WindowsCommandContext $command $request.caret $true;
|
||||
$result = TabExpansion2 -inputScript $request.line -cursorColumn $request.caret;
|
||||
$candidates = $result.CompletionMatches;
|
||||
if ($candidates.Count -and $candidates[0].ResultType -in 'ProviderItem','ProviderContainer' -and
|
||||
($script:adapterArguments -or (Test-NoCommandArguments $command))) {
|
||||
$candidates = $candidates | Where-Object { $_.ResultType -notin 'ProviderItem','ProviderContainer' };
|
||||
}
|
||||
$items = @($candidates | Select-Object -First 100 | ForEach-Object {
|
||||
@{ label = $_.ListItemText; text = $_.CompletionText; directory = ($_.ResultType -eq 'ProviderContainer') }
|
||||
});
|
||||
$reply = @{ index = $result.ReplacementIndex; length = $result.ReplacementLength;
|
||||
matches = $items; article = [string]$context.article };
|
||||
[Console]::WriteLine((ConvertTo-Json -InputObject $reply -Compress -Depth 4));
|
||||
} catch { [Console]::WriteLine('{}') }
|
||||
}")PS";
|
||||
|
||||
job=CreateJobObjectW(nullptr,nullptr);
|
||||
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};
|
||||
limits.BasicLimitInformation.LimitFlags=JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
||||
if(!job || !SetInformationJobObject(job,JobObjectExtendedLimitInformation,&limits,sizeof(limits))) return false;
|
||||
|
||||
SIZE_T bytes{};
|
||||
InitializeProcThreadAttributeList(nullptr,1,0,&bytes);
|
||||
std::vector<unsigned char> storage(bytes);
|
||||
auto attributes=reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
|
||||
if(!InitializeProcThreadAttributeList(attributes,1,0,&bytes)) return false;
|
||||
HANDLE inherited[]{childInput,childOutput};
|
||||
STARTUPINFOEXW startup{};
|
||||
startup.StartupInfo.cb=sizeof(startup);
|
||||
startup.StartupInfo.dwFlags=STARTF_USESTDHANDLES;
|
||||
startup.StartupInfo.hStdInput=childInput;
|
||||
startup.StartupInfo.hStdOutput=startup.StartupInfo.hStdError=childOutput;
|
||||
startup.lpAttributeList=attributes;
|
||||
PROCESS_INFORMATION child{};
|
||||
const bool started=UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
|
||||
inherited,sizeof(inherited),nullptr,nullptr) &&
|
||||
CreateProcessW(shell.c_str(),command,nullptr,nullptr,TRUE,
|
||||
CREATE_SUSPENDED|CREATE_NO_WINDOW|EXTENDED_STARTUPINFO_PRESENT,
|
||||
nullptr,nullptr,&startup.StartupInfo,&child);
|
||||
DeleteProcThreadAttributeList(attributes);
|
||||
if(!started) return false;
|
||||
process=child.hProcess;
|
||||
const bool running=AssignProcessToJobObject(job,process) && ResumeThread(child.hThread)!=DWORD(-1);
|
||||
if(!running) TerminateProcess(process,1);
|
||||
CloseHandle(child.hThread);
|
||||
return running;
|
||||
}
|
||||
|
||||
void close()
|
||||
{
|
||||
for(const auto handle:{job,input,output,process})
|
||||
if(handle) CloseHandle(handle);
|
||||
job=input=output=process=nullptr;
|
||||
pending.clear();
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -12,7 +12,7 @@ bool validHistoryKeys(const std::array<WORD,2> &keys)
|
||||
const bool function=key>=VK_F1 && key<=VK_F12;
|
||||
if(!letter && !function) return false;
|
||||
if(modifiers==HOTKEYF_CONTROL)
|
||||
return (letter && key!='C' && key!='F' && key!='R' && key!='V' && key!='X' && key!='A' && key!='Z' && key!='Y') || function;
|
||||
return letter && key!='C' && key!='F' && key!='R' && key!='V' && key!='X' && key!='A' && key!='Z' && key!='Y';
|
||||
if(modifiers==HOTKEYF_ALT) return function && key!=VK_F1 && key!=VK_F2 && key!=VK_F4 && key!=VK_F10;
|
||||
return false;
|
||||
});
|
||||
|
||||
@@ -187,8 +187,6 @@ struct FolderShortcutView
|
||||
std::vector<int> digits;
|
||||
int rowHeight{};
|
||||
Panel *panel{};
|
||||
bool all{};
|
||||
std::vector<std::pair<int,size_t>> entries;
|
||||
};
|
||||
|
||||
std::wstring shortcutLabel(const FolderShortcut &entry)
|
||||
@@ -201,7 +199,6 @@ void layoutQuickFolders(HWND dialog,FolderShortcutView &view,int selection)
|
||||
const auto list=GetDlgItem(dialog,shortcutList);
|
||||
SendMessageW(list,LB_RESETCONTENT,0,0);
|
||||
view.digits.clear();
|
||||
view.entries.clear();
|
||||
const auto owner=GetWindow(dialog,GW_OWNER);
|
||||
const auto dc=GetDC(dialog);
|
||||
const auto font=SelectObject(dc,mono);
|
||||
@@ -219,23 +216,14 @@ void layoutQuickFolders(HWND dialog,FolderShortcutView &view,int selection)
|
||||
GetTextExtentPoint32W(dc,label.data(),static_cast<int>(label.size()),&size);
|
||||
return static_cast<int>(size.cx);
|
||||
};
|
||||
int width=std::max(measure(L"Folder shortcuts"),measure(view.all?L"Del F4":view.digit<0?L"Enter Esc":quickFolderHints))+3*cellWidth;
|
||||
int width=std::max(measure(L"Folder shortcuts"),measure(view.digit<0?L"Enter Esc":quickFolderHints))+3*cellWidth;
|
||||
const int textInset=dialogRowTextInset(cellWidth);
|
||||
const auto add=[&](const std::wstring &label)
|
||||
{
|
||||
width=std::max(width,measure(label)+2*textInset);
|
||||
SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
|
||||
};
|
||||
if(view.all)
|
||||
{
|
||||
for(int digit=0;digit<static_cast<int>(folderShortcuts.size());++digit)
|
||||
for(size_t index=0;index<folderShortcuts[digit].size();++index)
|
||||
{
|
||||
view.entries.emplace_back(digit,index);
|
||||
add(std::to_wstring(digit)+L" "+shortcutLabel(folderShortcuts[digit][index]));
|
||||
}
|
||||
}
|
||||
else if(view.digit<0)
|
||||
if(view.digit<0)
|
||||
{
|
||||
for(int digit=0;digit<10;++digit)
|
||||
if(!folderShortcuts[digit].empty())
|
||||
@@ -322,7 +310,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
const auto bounds=paintDialogFrame(dc,client,dialogFrameMetrics(GetDpiForWindow(dialog)),teal,frame);
|
||||
DeleteObject(frame);
|
||||
paintDialogFrameCaptions(dc,client,bounds,L"Folder shortcuts",teal,colors[Text],mono,
|
||||
view->all?L"Del F4":view->digit<0?L"Enter Esc":quickFolderHints);
|
||||
view->digit<0?L"Enter Esc":quickFolderHints);
|
||||
EndPaint(dialog,&ps);
|
||||
return TRUE;
|
||||
}
|
||||
@@ -349,7 +337,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
if(action!=quickRemove && action!=quickEdit && action!=quickInsert && action!=quickMoveUp &&
|
||||
action!=quickMoveDown && action!=IDOK && !(action==shortcutList && HIWORD(wp)==LBN_DBLCLK)) return FALSE;
|
||||
const auto row=SendDlgItemMessageW(dialog,shortcutList,LB_GETCURSEL,0,0);
|
||||
if(!view->all && view->digit<0)
|
||||
if(view->digit<0)
|
||||
{
|
||||
if((action==IDOK || action==shortcutList) && row>=0 && static_cast<size_t>(row)<view->digits.size())
|
||||
{
|
||||
@@ -358,16 +346,8 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
int digit=view->digit;
|
||||
size_t index=static_cast<size_t>(row);
|
||||
if(view->all)
|
||||
{
|
||||
if(index>=view->entries.size() || action==quickInsert ||
|
||||
action==quickMoveUp || action==quickMoveDown) return TRUE;
|
||||
const auto &entry=view->entries[index];
|
||||
digit=entry.first;
|
||||
index=entry.second;
|
||||
}
|
||||
const auto digit=view->digit;
|
||||
const auto index=static_cast<size_t>(row);
|
||||
const auto &group=folderShortcuts[digit];
|
||||
if(action==quickInsert)
|
||||
{
|
||||
@@ -414,7 +394,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
folderShortcuts=std::move(updated);
|
||||
notifyFilesPreferences(GetAncestor(dialog,GA_ROOTOWNER));
|
||||
if(view->all?view->entries.size()==1:folderShortcuts[digit].empty()) FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
if(folderShortcuts[digit].empty()) FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
else layoutQuickFolders(dialog,*view,static_cast<int>(row));
|
||||
return TRUE;
|
||||
}
|
||||
@@ -424,7 +404,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
|
||||
|
||||
void showFolderShortcuts(Panel &panel,int digit,bool all)
|
||||
void showFolderShortcuts(Panel &panel,int digit)
|
||||
{
|
||||
if(digit>=0)
|
||||
{
|
||||
@@ -447,7 +427,6 @@ void showFolderShortcuts(Panel &panel,int digit,bool all)
|
||||
}
|
||||
FolderShortcutView view{digit};
|
||||
view.panel=&panel;
|
||||
view.all=all;
|
||||
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(109),GetParent(panel.list),
|
||||
quickFolderDialog,reinterpret_cast<LPARAM>(&view));
|
||||
SetFocus(panel.list);
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <algorithm>
|
||||
#include <string_view>
|
||||
#include <windowsx.h>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
inline COLORREF hoverSurface(COLORREF surface)
|
||||
{
|
||||
return RGB(3*GetRValue(surface)/4,3*GetGValue(surface)/4,3*GetBValue(surface)/4);
|
||||
}
|
||||
|
||||
class InlineListAction
|
||||
{
|
||||
std::wstring_view label;
|
||||
LRESULT pressedRow=LB_ERR;
|
||||
|
||||
public:
|
||||
explicit InlineListAction(std::wstring_view text):label(text){}
|
||||
|
||||
RECT bounds(RECT row,int cellWidth) const
|
||||
{
|
||||
row.right-=2*cellWidth;
|
||||
row.left=std::max(row.left,row.right-static_cast<LONG>(label.size()*cellWidth));
|
||||
return row;
|
||||
}
|
||||
|
||||
bool hit(HWND list,LRESULT row,LPARAM point,int cellWidth) const
|
||||
{
|
||||
RECT item{};
|
||||
if(SendMessageW(list,LB_GETITEMRECT,row,reinterpret_cast<LPARAM>(&item))==LB_ERR) return false;
|
||||
const auto action=bounds(item,cellWidth);
|
||||
return PtInRect(&action,{GET_X_LPARAM(point),GET_Y_LPARAM(point)});
|
||||
}
|
||||
|
||||
void press(HWND list,LRESULT row)
|
||||
{
|
||||
pressedRow=row;
|
||||
SetCapture(list);
|
||||
}
|
||||
|
||||
bool pressed() const { return pressedRow!=LB_ERR; }
|
||||
void cancel() { pressedRow=LB_ERR; }
|
||||
|
||||
bool release(HWND list,LRESULT row,bool overAction)
|
||||
{
|
||||
const bool activate=pressedRow==row && overAction;
|
||||
cancel();
|
||||
if(GetCapture()==list) ReleaseCapture();
|
||||
return activate;
|
||||
}
|
||||
|
||||
void paint(HDC dc,const RECT &action,int textInset,COLORREF ink,COLORREF surface,bool highlighted) const
|
||||
{
|
||||
SetTextColor(dc,ink);
|
||||
SetBkColor(dc,highlighted?hoverSurface(surface):surface);
|
||||
ExtTextOutW(dc,action.left,action.top+textInset,ETO_OPAQUE|ETO_CLIPPED,&action,
|
||||
label.data(),static_cast<UINT>(label.size()),nullptr);
|
||||
TEXTMETRICW metrics{};
|
||||
GetTextMetricsW(dc,&metrics);
|
||||
const LONG underline=std::min(action.bottom-1,action.top+textInset+metrics.tmAscent+1);
|
||||
const RECT line{action.left,underline,action.right,underline+1};
|
||||
SetDCBrushColor(dc,ink);
|
||||
FillRect(dc,&line,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
}
|
||||
};
|
||||
}
|
||||
+418
-47
@@ -21,15 +21,18 @@
|
||||
#include <objbase.h>
|
||||
#include <winternl.h>
|
||||
#include "files_terminal.h"
|
||||
#include "files_command_completion.h"
|
||||
#include "files_text_window.h"
|
||||
#include "files_menu_navigation.h"
|
||||
#include "files_text_preferences.h"
|
||||
#include "files_menu_paint.h"
|
||||
#include "files_dropdown_paint.h"
|
||||
#include "files_inline_action.h"
|
||||
#include "files_history_date.h"
|
||||
#include "files_terminal_view.h"
|
||||
#include "files_lan_ipc.h"
|
||||
#include "lan_files.h"
|
||||
#include "lan_wake.h"
|
||||
#include "platform.h"
|
||||
|
||||
namespace
|
||||
@@ -428,7 +431,9 @@ struct DriveQuery
|
||||
Json drives=Json::array();
|
||||
std::wstring error;
|
||||
};
|
||||
struct DriveChoice { FilesPeer peer; fs::path path; };
|
||||
struct DriveChoice { FilesPeer peer; std::optional<fs::path> path; };
|
||||
constexpr wchar_t driveWakeLabel[]=L"Wake";
|
||||
ks::files::InlineListAction driveWakeAction(driveWakeLabel);
|
||||
std::vector<DriveQuery> driveQueries;
|
||||
std::map<LRESULT,DriveChoice> remoteDriveRows;
|
||||
constexpr UINT_PTR driveQueryTimer=3;
|
||||
@@ -487,7 +492,7 @@ INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,File
|
||||
void openMenu(HWND window, int index);
|
||||
void showFileDetails(const Panel &panel);
|
||||
void editOptions(HWND owner);
|
||||
void showFolderShortcuts(Panel &panel,int digit,bool all=false);
|
||||
void showFolderShortcuts(Panel &panel,int digit);
|
||||
void layout(HWND window,bool activeOnly=false);
|
||||
void clearTerminalSelection();
|
||||
|
||||
@@ -1016,6 +1021,252 @@ std::wstring terminalInputText()
|
||||
return value;
|
||||
}
|
||||
|
||||
bool commandLineAvailable(HWND owner);
|
||||
|
||||
struct CompletionQuery
|
||||
{
|
||||
std::wstring line, directory;
|
||||
DWORD caret{};
|
||||
bool operator==(const CompletionQuery &) const = default;
|
||||
};
|
||||
struct CompletionItem
|
||||
{
|
||||
std::wstring label, text;
|
||||
size_t index{}, length{};
|
||||
bool directory{};
|
||||
};
|
||||
|
||||
HWND completionList{}, completionFrame{};
|
||||
ks::files::CommandCompletion completionWorker;
|
||||
std::optional<CompletionQuery> completionQuery, pendingCompletion;
|
||||
std::vector<CompletionItem> completionItems;
|
||||
ULONGLONG completionDue{};
|
||||
std::string completionHelpArticle;
|
||||
bool completionHelpRequested{};
|
||||
|
||||
void hideCompletion()
|
||||
{
|
||||
ShowWindow(completionList,SW_HIDE);
|
||||
ShowWindow(completionFrame,SW_HIDE);
|
||||
completionItems.clear();
|
||||
completionDue=0;
|
||||
completionHelpArticle.clear();
|
||||
completionHelpRequested=false;
|
||||
}
|
||||
|
||||
void resetCompletion()
|
||||
{
|
||||
hideCompletion();
|
||||
completionQuery.reset();
|
||||
}
|
||||
|
||||
std::optional<CompletionQuery> currentCompletionQuery()
|
||||
{
|
||||
if(GetFocus()!=terminalInput || GetForegroundWindow()!=GetParent(terminalInput) ||
|
||||
!commandLineAvailable(GetParent(terminalInput))) return {};
|
||||
auto line=terminalInputText();
|
||||
if(line.find_first_not_of(L" \t")==line.npos) return {};
|
||||
DWORD first{},last{};
|
||||
SendMessageW(terminalInput,EM_GETSEL,reinterpret_cast<WPARAM>(&first),reinterpret_cast<LPARAM>(&last));
|
||||
if(!first || first!=last) return {};
|
||||
std::wstring directory;
|
||||
if(!panels[active].peer)
|
||||
directory=terminal.alive() && !terminalDirectory.empty()?terminalDirectory:panels[active].directory.native();
|
||||
return CompletionQuery{std::move(line),std::move(directory),first};
|
||||
}
|
||||
|
||||
void showFramedList(HWND list,HWND frame,int x,int y,int width,int height,int inset)
|
||||
{
|
||||
constexpr UINT flags=SWP_NOACTIVATE|SWP_SHOWWINDOW;
|
||||
SetWindowPos(frame,HWND_TOP,x-inset,y-inset,width+2*inset,height+2*inset,flags);
|
||||
SetWindowPos(list,HWND_TOP,x,y,width,height,flags);
|
||||
}
|
||||
|
||||
void appendPowerShellCompletions(const CompletionQuery &query,const Json &reply,
|
||||
std::set<std::wstring> &seen)
|
||||
{
|
||||
if(!reply.is_object() || !reply.contains("matches")) return;
|
||||
try
|
||||
{
|
||||
const auto index=reply.at("index").get<size_t>();
|
||||
const auto length=reply.at("length").get<size_t>();
|
||||
if(index>query.caret || length>query.line.size()-index) return;
|
||||
for(const auto &row:reply.at("matches"))
|
||||
{
|
||||
auto value=ks::wide(row.at("text").get<std::string>());
|
||||
if(value.empty() || query.line.size()-length+value.size()>2048) continue;
|
||||
auto line=query.line;
|
||||
line.replace(index,length,value);
|
||||
if(seen.insert(std::move(line)).second)
|
||||
completionItems.push_back({ks::wide(row.at("label").get<std::string>()),std::move(value),
|
||||
index,length,row.at("directory").get<bool>()});
|
||||
}
|
||||
}
|
||||
catch(const Json::exception &) {}
|
||||
}
|
||||
|
||||
void showCompletion(HWND owner,const CompletionQuery &query,const Json &reply={})
|
||||
{
|
||||
std::set<std::wstring> seen{query.line};
|
||||
if(query.caret==query.line.size())
|
||||
{
|
||||
for(auto entry=terminalHistory.rbegin();entry!=terminalHistory.rend() && completionItems.size()<5;++entry)
|
||||
{
|
||||
const auto &command=entry->command;
|
||||
if(command.size()>2048 || command.size()<=query.line.size() ||
|
||||
CompareStringOrdinal(command.data(),static_cast<int>(query.line.size()),query.line.data(),
|
||||
static_cast<int>(query.line.size()),TRUE)!=CSTR_EQUAL ||
|
||||
!seen.insert(command).second)
|
||||
continue;
|
||||
completionItems.push_back({command,command,0,query.line.size()});
|
||||
}
|
||||
}
|
||||
appendPowerShellCompletions(query,reply,seen);
|
||||
if(completionItems.empty()) return;
|
||||
|
||||
RECT edit{};
|
||||
GetWindowRect(terminalInput,&edit);
|
||||
MapWindowPoints(nullptr,owner,reinterpret_cast<POINT*>(&edit),2);
|
||||
const int inset=dialogFrameMetrics(GetDpiForWindow(owner)).content();
|
||||
const int rows=std::min({8,static_cast<int>(completionItems.size()),
|
||||
(static_cast<int>(edit.top)-2*inset)/textHeight});
|
||||
int desiredWidth=24*cellWidth;
|
||||
if(const auto dc=GetDC(completionList))
|
||||
{
|
||||
const auto previous=SelectObject(dc,mono);
|
||||
for(const auto &item:completionItems)
|
||||
{
|
||||
SIZE extent{};
|
||||
GetTextExtentPoint32W(dc,item.label.c_str(),static_cast<int>(item.label.size()),&extent);
|
||||
desiredWidth=std::max(desiredWidth,static_cast<int>(extent.cx)+2*cellWidth);
|
||||
}
|
||||
SelectObject(dc,previous);
|
||||
ReleaseDC(completionList,dc);
|
||||
}
|
||||
if(static_cast<size_t>(rows)<completionItems.size())
|
||||
desiredWidth+=GetSystemMetricsForDpi(SM_CXVSCROLL,GetDpiForWindow(owner));
|
||||
const int width=std::min(desiredWidth,static_cast<int>(edit.right-edit.left)-2*inset);
|
||||
if(rows<1 || width<1) { hideCompletion(); return; }
|
||||
SendMessageW(completionList,LB_RESETCONTENT,0,0);
|
||||
SendMessageW(completionList,LB_SETITEMHEIGHT,0,textHeight);
|
||||
for(const auto &item:completionItems)
|
||||
SendMessageW(completionList,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(item.label.c_str()));
|
||||
const int height=rows*textHeight;
|
||||
const int y=edit.top-height-inset;
|
||||
showFramedList(completionList,completionFrame,edit.left+inset,y,width,height,inset);
|
||||
}
|
||||
|
||||
bool openCompletionHelp(HWND owner)
|
||||
{
|
||||
if(completionHelpArticle.empty()) return false;
|
||||
constexpr auto base=L"https://learn.microsoft.com/windows-server/administration/windows-commands/";
|
||||
const auto url=base+ks::wide(completionHelpArticle);
|
||||
if(reinterpret_cast<INT_PTR>(ShellExecuteW(owner,L"open",url.c_str(),nullptr,nullptr,SW_SHOWNORMAL))<=32)
|
||||
setStatus(L"Could not open Windows command help.");
|
||||
return true;
|
||||
}
|
||||
|
||||
bool requestCompletionHelp(HWND owner)
|
||||
{
|
||||
auto query=currentCompletionQuery();
|
||||
if(!query || query->directory.empty()) return false;
|
||||
if(query==completionQuery && openCompletionHelp(owner)) return true;
|
||||
if(query!=completionQuery || pendingCompletion!=query)
|
||||
{
|
||||
hideCompletion();
|
||||
completionQuery=std::move(query);
|
||||
}
|
||||
if(pendingCompletion!=completionQuery) completionDue=GetTickCount64();
|
||||
completionHelpRequested=true;
|
||||
return true;
|
||||
}
|
||||
|
||||
void updateCompletion(HWND owner)
|
||||
{
|
||||
auto query=currentCompletionQuery();
|
||||
if(query!=completionQuery)
|
||||
{
|
||||
hideCompletion();
|
||||
completionQuery=std::move(query);
|
||||
if(completionQuery) completionDue=GetTickCount64()+150;
|
||||
}
|
||||
if(pendingCompletion)
|
||||
{
|
||||
auto reply=completionWorker.poll();
|
||||
if(!reply) return;
|
||||
if(pendingCompletion==completionQuery && !completionDue && completionQuery)
|
||||
{
|
||||
if(reply->is_object() && reply->contains("article") && reply->at("article").is_string())
|
||||
{
|
||||
const auto &article=reply->at("article").get_ref<const std::string&>();
|
||||
if(article.size()<128 && std::all_of(article.begin(),article.end(),[](char ch)
|
||||
{ return (ch>='a' && ch<='z') || (ch>='0' && ch<='9') || ch=='-' || ch=='_'; }))
|
||||
completionHelpArticle=article;
|
||||
}
|
||||
if(!std::exchange(completionHelpRequested,false) || !openCompletionHelp(owner))
|
||||
showCompletion(owner,*completionQuery,*reply);
|
||||
}
|
||||
pendingCompletion.reset();
|
||||
}
|
||||
if(completionQuery && completionDue && GetTickCount64()>=completionDue)
|
||||
{
|
||||
completionDue=0;
|
||||
const auto ¤t=*completionQuery;
|
||||
if(!current.directory.empty() && completionWorker.request(current.line,current.caret,current.directory))
|
||||
pendingCompletion=current;
|
||||
else showCompletion(owner,current);
|
||||
}
|
||||
}
|
||||
|
||||
bool acceptCompletion(size_t row)
|
||||
{
|
||||
if(row>=completionItems.size() || currentCompletionQuery()!=completionQuery) return false;
|
||||
const auto item=completionItems[row];
|
||||
SendMessageW(terminalInput,EM_SETSEL,item.index,item.index+item.length);
|
||||
SendMessageW(terminalInput,EM_REPLACESEL,TRUE,reinterpret_cast<LPARAM>(item.text.c_str()));
|
||||
if(item.directory && item.text.size()>1 &&
|
||||
(item.text.front()==L'\'' || item.text.front()==L'"') && item.text.back()==item.text.front())
|
||||
{
|
||||
const auto caret=item.index+item.text.size()-1;
|
||||
SendMessageW(terminalInput,EM_SETSEL,caret,caret);
|
||||
}
|
||||
hideCompletion();
|
||||
completionQuery=currentCompletionQuery();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool handleCompletionKey(WPARAM key,LPARAM flags)
|
||||
{
|
||||
if(key==VK_F1)
|
||||
return !(flags & (1LL<<30)) && requestCompletionHelp(GetParent(terminalInput));
|
||||
if(key!=VK_UP && key!=VK_DOWN && key!=VK_RETURN && key!=VK_TAB && key!=VK_ESCAPE) return false;
|
||||
if(!IsWindowVisible(completionList) || currentCompletionQuery()!=completionQuery) return false;
|
||||
const auto row=SendMessageW(completionList,LB_GETCURSEL,0,0);
|
||||
if(key==VK_ESCAPE) { hideCompletion(); return true; }
|
||||
if(key==VK_TAB || (key==VK_RETURN && row!=LB_ERR))
|
||||
{
|
||||
if(!(flags & (1LL<<30))) acceptCompletion(row==LB_ERR?0:static_cast<size_t>(row));
|
||||
return true;
|
||||
}
|
||||
if(key!=VK_UP && key!=VK_DOWN) return false;
|
||||
const auto count=static_cast<LRESULT>(completionItems.size());
|
||||
const auto next=key==VK_DOWN?(row+1)%count:(row<=0?count-1:row-1);
|
||||
SendMessageW(completionList,LB_SETCURSEL,next,0);
|
||||
return true;
|
||||
}
|
||||
|
||||
LRESULT CALLBACK completionClick(HWND list,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
|
||||
{
|
||||
if(message==WM_LBUTTONDOWN || message==WM_LBUTTONDBLCLK)
|
||||
{
|
||||
const auto hit=SendMessageW(list,LB_ITEMFROMPOINT,0,lp);
|
||||
if(!HIWORD(hit)) acceptCompletion(LOWORD(hit));
|
||||
return 0;
|
||||
}
|
||||
return DefSubclassProc(list,message,wp,lp);
|
||||
}
|
||||
|
||||
|
||||
void clearTerminalSelection()
|
||||
{
|
||||
if(terminalSelection.empty()) return;
|
||||
@@ -1326,7 +1577,12 @@ void runCommandLine()
|
||||
|
||||
LRESULT CALLBACK terminalInputKeys(HWND input,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
|
||||
{
|
||||
if(message==WM_LBUTTONDOWN || message==WM_RBUTTONDOWN) clearTerminalSelection();
|
||||
if(message==WM_KILLFOCUS) resetCompletion();
|
||||
if(message==WM_LBUTTONDOWN || message==WM_RBUTTONDOWN)
|
||||
{
|
||||
clearTerminalSelection();
|
||||
hideCompletion();
|
||||
}
|
||||
if(message==WM_COPY || (message==WM_CHAR && wp==3))
|
||||
{
|
||||
copyTerminalText(GetParent(input));
|
||||
@@ -1608,8 +1864,9 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
|
||||
for (const auto &file : files) add(file, file.filename().wstring(), false);
|
||||
const auto label=(panel.peer?panel.peer->name+L" · ":std::wstring{})+directory.native();
|
||||
SetWindowTextW(panel.path,label.c_str());
|
||||
InvalidateRect(panel.path,nullptr,FALSE);
|
||||
if(&panel==&panels[active] && !sameDirectory)
|
||||
layout(GetParent(panel.list));
|
||||
layout(GetParent(panel.list),true);
|
||||
auto selected=std::find(panel.rows.begin(),panel.rows.end(),previousSelection);
|
||||
if(selected==panel.rows.end() && !panel.rows.empty())
|
||||
selected=panel.rows.begin()+std::clamp<LRESULT>(previousRow,0,panel.rows.size()-1);
|
||||
@@ -1790,6 +2047,45 @@ void prepareTextDialog(HWND dialog);
|
||||
void showTextMessage(HWND owner,const wchar_t *text);
|
||||
void editTextOptions(HWND owner,bool edit);
|
||||
|
||||
void startPeerAction(std::packaged_task<std::wstring()> task,const std::wstring &status)
|
||||
{
|
||||
pendingPeerAction=task.get_future();
|
||||
try {std::thread(std::move(task)).detach();}
|
||||
catch(const std::system_error &error)
|
||||
{
|
||||
pendingPeerAction={};
|
||||
setStatus(fileError(error));
|
||||
return;
|
||||
}
|
||||
setStatus(status);
|
||||
}
|
||||
|
||||
void wakeRemotePeer(const FilesPeer &peer)
|
||||
{
|
||||
if(pendingPeerAction.valid())
|
||||
{
|
||||
setStatus(L"A remote PC request is already in progress.");
|
||||
return;
|
||||
}
|
||||
std::packaged_task<std::wstring()> task([peer]
|
||||
{
|
||||
try
|
||||
{
|
||||
ks::lan::wakeFilesPeer(peer.id);
|
||||
return peer.name+L": Wake-on-LAN packet sent.";
|
||||
}
|
||||
catch(const std::system_error &error)
|
||||
{
|
||||
return peer.name+L": Could not send Wake-on-LAN packet. "+fileError(error);
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
return peer.name+L": "+ks::wide(error.what());
|
||||
}
|
||||
});
|
||||
startPeerAction(std::move(task),L"Sending Wake-on-LAN packet to "+peer.name+L"...");
|
||||
}
|
||||
|
||||
void runActivePeerAction(HWND owner,bool update)
|
||||
{
|
||||
if(!panels[active].peer) return;
|
||||
@@ -1839,15 +2135,8 @@ void runActivePeerAction(HWND owner,bool update)
|
||||
return unconfirmed;
|
||||
}
|
||||
});
|
||||
pendingPeerAction=task.get_future();
|
||||
try {std::thread(std::move(task)).detach();}
|
||||
catch(const std::system_error &error)
|
||||
{
|
||||
pendingPeerAction={};
|
||||
setStatus(fileError(error));
|
||||
return;
|
||||
}
|
||||
setStatus((update?L"Requesting a KSwitcher update on ":L"Requesting hibernation for ")+peer.name+L"...");
|
||||
startPeerAction(std::move(task),
|
||||
(update?L"Requesting a KSwitcher update on ":L"Requesting hibernation for ")+peer.name+L"...");
|
||||
}
|
||||
|
||||
void selectDrive()
|
||||
@@ -1888,7 +2177,11 @@ void selectDrive()
|
||||
if(row>=0 && static_cast<size_t>(row)<drivePaths.size())
|
||||
openOn(panels[pickerPanel],drivePaths[row],false,{});
|
||||
else if(remote!=remoteDriveRows.end())
|
||||
openOn(panels[pickerPanel],remote->second.path,false,remote->second.peer);
|
||||
{
|
||||
const auto &choice=remote->second;
|
||||
if(choice.path) openOn(panels[pickerPanel],*choice.path,false,choice.peer);
|
||||
else wakeRemotePeer(choice.peer);
|
||||
}
|
||||
}
|
||||
|
||||
LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR)
|
||||
@@ -1921,6 +2214,29 @@ LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PT
|
||||
if(!HIWORD(hit) && separator(LOWORD(hit))) return 0;
|
||||
}
|
||||
}
|
||||
if(msg==WM_CAPTURECHANGED) driveWakeAction.cancel();
|
||||
if(!commandPicker && (msg==WM_LBUTTONDOWN || msg==WM_LBUTTONUP || msg==WM_LBUTTONDBLCLK))
|
||||
{
|
||||
const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,lp);
|
||||
const int row=HIWORD(hit)?-1:LOWORD(hit);
|
||||
const auto choice=remoteDriveRows.find(row);
|
||||
const bool wake=choice!=remoteDriveRows.end() && !choice->second.path;
|
||||
if(msg==WM_LBUTTONUP && driveWakeAction.pressed())
|
||||
{
|
||||
if(driveWakeAction.release(window,row,wake && driveWakeAction.hit(window,row,lp,cellWidth)))
|
||||
{
|
||||
SendMessageW(window,LB_SETCURSEL,row,0);
|
||||
selectDrive();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if(wake && msg!=WM_LBUTTONUP)
|
||||
{
|
||||
if(msg==WM_LBUTTONDOWN && driveWakeAction.hit(window,row,lp,cellWidth))
|
||||
driveWakeAction.press(window,row);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
if(!commandPicker && msg==WM_CHAR)
|
||||
{
|
||||
const auto key=towupper(static_cast<wchar_t>(wp));
|
||||
@@ -1946,7 +2262,14 @@ LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PT
|
||||
TRACKMOUSEEVENT tracking{sizeof(tracking),TME_LEAVE,window,0};
|
||||
TrackMouseEvent(&tracking);
|
||||
const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,lp);
|
||||
if(!HIWORD(hit) && LOWORD(hit)<drivePaths.size()) row=LOWORD(hit);
|
||||
if(!HIWORD(hit))
|
||||
{
|
||||
const auto choice=remoteDriveRows.find(LOWORD(hit));
|
||||
if(LOWORD(hit)<drivePaths.size() ||
|
||||
(choice!=remoteDriveRows.end() && !choice->second.path &&
|
||||
driveWakeAction.hit(window,LOWORD(hit),lp,cellWidth)))
|
||||
row=LOWORD(hit);
|
||||
}
|
||||
}
|
||||
if(driveHover!=row)
|
||||
{
|
||||
@@ -2082,19 +2405,27 @@ void showRemoteDrives(bool focus=false,int initialRow=0)
|
||||
for(const auto &query:driveQueries)
|
||||
{
|
||||
add(query.peer.name);
|
||||
if(query.pending.valid()) add(L" Loading drives...");
|
||||
const auto addChoice=[&](const std::wstring &label,std::optional<fs::path> path)
|
||||
{
|
||||
const auto row=add(label);
|
||||
if(row<0) return;
|
||||
if(previous && previous->peer.id==query.peer.id && previous->path==path) selection=row;
|
||||
remoteDriveRows.emplace(row,DriveChoice{query.peer,std::move(path)});
|
||||
};
|
||||
if(query.peer.address.empty())
|
||||
{
|
||||
const std::wstring status=nextDriveRefresh?L" Looking for PC...":L" Offline";
|
||||
addChoice(status+L" \t"+driveWakeLabel,std::nullopt);
|
||||
}
|
||||
else if(query.pending.valid()) add(L" Loading drives...");
|
||||
else if(!query.error.empty()) add(L" "+query.error);
|
||||
else if(query.peer.address.empty()) add(nextDriveRefresh?L" Looking for PC...":L" Offline");
|
||||
else if(query.drives.empty()) add(L" No drives");
|
||||
for(const auto &entry:query.drives)
|
||||
{
|
||||
const auto root=filePath(entry.at("path"));
|
||||
if(root.native().size()!=3 || root.native().front()<L'A' || root.native().front()>L'Z') continue;
|
||||
const auto labels=driveLabels(root.native().front(),entry.at("type"),entry.at("total"),entry.at("free"));
|
||||
const auto row=add(L" "+labels[0]+L" "+labels[1]+L" "+labels[2]);
|
||||
if(row<0) continue;
|
||||
remoteDriveRows.emplace(row,DriveChoice{query.peer,root});
|
||||
if(previous && previous->peer.id==query.peer.id && previous->path==root) selection=row;
|
||||
addChoice(L" "+labels[0]+L" "+labels[1]+L" "+labels[2],root);
|
||||
}
|
||||
}
|
||||
layoutDrivePicker(static_cast<int>(selection),focus);
|
||||
@@ -4926,8 +5257,8 @@ void openMenu(HWND window, int index)
|
||||
if(index==0 || index==4)
|
||||
{
|
||||
const bool wide=panels[index==4].wide;
|
||||
rows={wide?L" Brief":L"✓ Brief",
|
||||
wide?L"✓ Wide":L" Wide",
|
||||
rows={wide?L" Brief\tCtrl+F1":L"✓ Brief\tCtrl+F1",
|
||||
wide?L"✓ Wide\tCtrl+F2":L" Wide\tCtrl+F2",
|
||||
index==0?L" Change drive\tAlt+F1":L" Change drive\tAlt+F2"};
|
||||
}
|
||||
else if(index==1) rows={L"Copy\tF5",L"Move\tF6",L"Make folder\tF7",L"Exit\tF10"};
|
||||
@@ -4992,8 +5323,7 @@ void openMenu(HWND window, int index)
|
||||
std::max(inset,static_cast<int>(client.right)-width-inset));
|
||||
const int y=anchor.bottom+5;
|
||||
const int height=static_cast<int>(commandActions.size())*static_cast<int>(SendMessageW(picker,LB_GETITEMHEIGHT,0,0));
|
||||
SetWindowPos(pickerFrame,HWND_TOP,x-inset,y-inset,width+2*inset,height+2*inset,SWP_SHOWWINDOW);
|
||||
SetWindowPos(picker,HWND_TOP,x,y,width,height,SWP_SHOWWINDOW);
|
||||
showFramedList(picker,pickerFrame,x,y,width,height,inset);
|
||||
SendMessageW(picker,LB_SETCURSEL,0,0);
|
||||
SetFocus(picker);
|
||||
showMenu(true);
|
||||
@@ -5164,7 +5494,11 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
restoreCommandFocus();
|
||||
return 0;
|
||||
case WM_ACTIVATEAPP:
|
||||
if(!wp) closePanelSearch();
|
||||
if(!wp)
|
||||
{
|
||||
closePanelSearch();
|
||||
resetCompletion();
|
||||
}
|
||||
break;
|
||||
case WM_COPYDATA:
|
||||
{
|
||||
@@ -5178,7 +5512,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
const auto rows=Json::parse(begin,begin+reply->cbData);
|
||||
if(!rows.is_array()) return FALSE;
|
||||
for(const auto &row:rows)
|
||||
drivePeers.push_back({row.at("id"),row.at("address"),ks::wide(row.at("name")),ks::lan::FilesPort,row.value("filesBrowse",false)});
|
||||
drivePeers.push_back({row.at("id"),row.at("address"),ks::wide(row.at("name")),ks::lan::FilesPort,
|
||||
row.value("filesBrowse",false)});
|
||||
}
|
||||
catch(const std::exception &){drivePeers.clear();return FALSE;}
|
||||
drivePeerReplyReceived=true;
|
||||
@@ -5192,6 +5527,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
pendingPeerAction.wait_for(std::chrono::seconds(0))==std::future_status::ready)
|
||||
setStatus(pendingPeerAction.get());
|
||||
updateTerminalOutput();
|
||||
updateCompletion(window);
|
||||
return 0;
|
||||
}
|
||||
if(wp==directoryWatchTimer)
|
||||
@@ -5234,7 +5570,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
0,0,0,0,window,reinterpret_cast<HMENU>(122),instance,nullptr);
|
||||
SetWindowSubclass(picker,pickerKeys,1,0);
|
||||
SendMessageW(picker,LB_SETITEMHEIGHT,0,textHeight);
|
||||
status = CreateWindowW(L"STATIC", L"", WS_CHILD | WS_VISIBLE | SS_PATHELLIPSIS,
|
||||
status = CreateWindowW(L"STATIC", L"", WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | SS_PATHELLIPSIS,
|
||||
0, 0, 0, 0, window, reinterpret_cast<HMENU>(144), instance, nullptr);
|
||||
panelSearchPopup=CreateWindowW(L"STATIC",L"Search",WS_CHILD|WS_CLIPSIBLINGS|SS_OWNERDRAW|SS_NOTIFY,
|
||||
0,0,0,0,window,reinterpret_cast<HMENU>(148),instance,nullptr);
|
||||
@@ -5242,8 +5578,15 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
0,0,0,0,window,nullptr,instance,nullptr);
|
||||
terminalPrompt=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_VISIBLE|SS_PATHELLIPSIS,
|
||||
0,0,0,0,window,nullptr,instance,nullptr);
|
||||
terminalOutput=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_CLIPCHILDREN,
|
||||
terminalOutput=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS,
|
||||
0,0,0,0,window,reinterpret_cast<HMENU>(145),instance,nullptr);
|
||||
completionList=CreateWindowW(L"LISTBOX",L"Command suggestions",
|
||||
WS_CHILD|WS_CLIPSIBLINGS|WS_VSCROLL|LBS_OWNERDRAWFIXED|LBS_HASSTRINGS|LBS_NOINTEGRALHEIGHT,
|
||||
0,0,0,0,window,reinterpret_cast<HMENU>(149),instance,nullptr);
|
||||
completionFrame=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_CLIPSIBLINGS|SS_OWNERDRAW,
|
||||
0,0,0,0,window,nullptr,instance,nullptr);
|
||||
if(!completionList || !completionFrame) return -1;
|
||||
SetWindowSubclass(completionList,completionClick,1,0);
|
||||
terminalBackground=CreateSolidBrush(RGB(24,24,24));
|
||||
if(!terminalInput || !terminalOutput || !terminalPrompt || !terminalBackground) return -1;
|
||||
for(const auto control:{terminalInput,terminalOutput,terminalPrompt})
|
||||
@@ -5296,6 +5639,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
return 0;
|
||||
}
|
||||
case WM_SIZE:
|
||||
hideCompletion();
|
||||
hidePicker();
|
||||
layout(window);
|
||||
return 0;
|
||||
@@ -5401,7 +5745,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
return reinterpret_cast<LRESULT>(blue);
|
||||
}
|
||||
case WM_CTLCOLORLISTBOX:
|
||||
return reinterpret_cast<LRESULT>(reinterpret_cast<HWND>(lp)==picker?teal:blue);
|
||||
return reinterpret_cast<LRESULT>(reinterpret_cast<HWND>(lp)==picker ||
|
||||
reinterpret_cast<HWND>(lp)==completionList?teal:blue);
|
||||
case WM_DRAWITEM:
|
||||
{
|
||||
const auto &item=*reinterpret_cast<const DRAWITEMSTRUCT *>(lp);
|
||||
@@ -5474,12 +5819,13 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
FillRect(item.hDC,&line,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
return TRUE;
|
||||
}
|
||||
if(item.hwndItem==pickerFrame)
|
||||
if(item.hwndItem==pickerFrame || item.hwndItem==completionFrame)
|
||||
{
|
||||
auto border=CreateSolidBrush(commandPicker?colors[Frame]:RGB(255,255,255));
|
||||
const bool driveFrame=item.hwndItem==pickerFrame && !commandPicker;
|
||||
auto border=CreateSolidBrush(driveFrame?RGB(255,255,255):colors[Frame]);
|
||||
const auto box=paintDialogFrame(item.hDC,item.rcItem,
|
||||
dialogFrameMetrics(GetDpiForWindow(window)),teal,border);
|
||||
if(!commandPicker)
|
||||
if(driveFrame)
|
||||
{
|
||||
if(!drivePaths.empty())
|
||||
{
|
||||
@@ -5530,7 +5876,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
paintText(item.hDC,action,text.c_str()+separator+1,colors[Selection],colors[Footer]);
|
||||
return TRUE;
|
||||
}
|
||||
auto background=item.CtlType==ODT_BUTTON?Footer:item.hwndItem==picker?Dialog:PanelBlue;
|
||||
const bool popupRow=item.hwndItem==picker || item.hwndItem==completionList;
|
||||
auto background=item.CtlType==ODT_BUTTON?Footer:popupRow?Dialog:PanelBlue;
|
||||
auto foreground=colors[Text];
|
||||
if(item.hwndItem==picker && commandPicker && item.itemID<commandActions.size() && commandActions[item.itemID]<0)
|
||||
{
|
||||
@@ -5609,8 +5956,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
SelectObject(item.hDC,mono);
|
||||
SetTextColor(item.hDC,foreground);
|
||||
const auto normal=colors[Dialog];
|
||||
const auto hover=RGB(3*GetRValue(normal)/4,3*GetGValue(normal)/4,
|
||||
3*GetBValue(normal)/4);
|
||||
const auto hover=ks::files::hoverSurface(normal);
|
||||
SetBkColor(item.hDC,background==Dialog && static_cast<int>(item.itemID)==driveHover?
|
||||
hover:colors[background]);
|
||||
ExtTextOutW(item.hDC,0,0,ETO_OPAQUE,&item.rcItem,L"",0,nullptr);
|
||||
@@ -5648,12 +5994,27 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
else if(item.hwndItem==picker && !commandPicker && item.itemID>drivePaths.size())
|
||||
{
|
||||
auto bounds=item.rcItem;
|
||||
RECT button{};
|
||||
const auto choice=remoteDriveRows.find(item.itemID);
|
||||
const bool wake=choice!=remoteDriveRows.end() && !choice->second.path;
|
||||
SelectObject(item.hDC,mono);
|
||||
SetTextColor(item.hDC,foreground);
|
||||
SetBkColor(item.hDC,colors[background]);
|
||||
SetBkColor(item.hDC,colors[wake?Dialog:background]);
|
||||
if(wake)
|
||||
{
|
||||
button=driveWakeAction.bounds(bounds,cellWidth);
|
||||
if(shortcut!=std::wstring::npos) text.resize(shortcut);
|
||||
ExtTextOutW(item.hDC,0,0,ETO_OPAQUE,&bounds,L"",0,nullptr);
|
||||
bounds.right=button.left;
|
||||
}
|
||||
ExtTextOutW(item.hDC,bounds.left+driveColumnStarts[0],bounds.top+3,
|
||||
ETO_OPAQUE|ETO_CLIPPED,&bounds,text.c_str(),lstrlenW(text.c_str()),nullptr);
|
||||
|
||||
ETO_OPAQUE|ETO_CLIPPED,&bounds,text.c_str(),static_cast<UINT>(text.size()),nullptr);
|
||||
if(wake)
|
||||
{
|
||||
const bool focused=(item.itemState&ODS_SELECTED) && GetFocus()==picker;
|
||||
driveWakeAction.paint(item.hDC,button,3,foreground,colors[Dialog],
|
||||
focused || static_cast<int>(item.itemID)==driveHover);
|
||||
}
|
||||
}
|
||||
else if(item.CtlID>=130 && item.CtlID<=134)
|
||||
paintMenuLabel(item.hDC,item.rcItem,text,0,foreground,colors[background]);
|
||||
@@ -5702,7 +6063,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
FillRect(item.hDC,&line,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
}
|
||||
}
|
||||
if (item.CtlType==ODT_LISTBOX && item.hwndItem!=picker)
|
||||
if (item.CtlType==ODT_LISTBOX && !popupRow)
|
||||
{
|
||||
RECT track{};
|
||||
GetWindowRect(item.hwndItem,&track);
|
||||
@@ -5714,7 +6075,11 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
return TRUE;
|
||||
}
|
||||
case WM_COMMAND:
|
||||
if(reinterpret_cast<HWND>(lp)==terminalInput && HIWORD(wp)==EN_CHANGE) clearTerminalSelection();
|
||||
if(reinterpret_cast<HWND>(lp)==terminalInput && HIWORD(wp)==EN_CHANGE)
|
||||
{
|
||||
clearTerminalSelection();
|
||||
resetCompletion();
|
||||
}
|
||||
if(copyInProgress || commandHistoryWindow || FilesModalDialog::activeFor(window)) return 0;
|
||||
if(LOWORD(wp)==121 && HIWORD(wp)==LBN_DBLCLK) selectDrive();
|
||||
if(LOWORD(wp)>=130 && LOWORD(wp)<=134 && HIWORD(wp)==BN_CLICKED)
|
||||
@@ -5856,6 +6221,12 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
if(message.hwnd==window && message.message>=WM_KEYFIRST && message.message<=WM_KEYLAST &&
|
||||
GetFocus()==terminalInput)
|
||||
message.hwnd=terminalInput;
|
||||
if(message.hwnd==terminalInput && message.message==WM_KEYDOWN &&
|
||||
!(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_SHIFT)&0x8000) &&
|
||||
!(GetKeyState(VK_MENU)&0x8000) && !(GetKeyState(VK_LWIN)&0x8000) &&
|
||||
!(GetKeyState(VK_RWIN)&0x8000) && commandLineAvailable(window) &&
|
||||
handleCompletionKey(message.wParam,message.lParam))
|
||||
continue;
|
||||
if(message.message==WM_KEYDOWN && message.wParam==VK_RETURN &&
|
||||
!(GetKeyState(VK_CONTROL)&0x8000) &&
|
||||
!(GetKeyState(VK_MENU)&0x8000) && !(GetKeyState(VK_LWIN)&0x8000) &&
|
||||
@@ -5907,8 +6278,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
if(message.message==WM_KEYDOWN && mainInput && !terminalVisible &&
|
||||
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) &&
|
||||
!(GetKeyState(VK_LWIN)&0x8000) && !(GetKeyState(VK_RWIN)&0x8000) &&
|
||||
message.wParam>='0' && message.wParam<='9' && !copyInProgress &&
|
||||
(message.wParam!='8' || (GetKeyState(VK_SHIFT)&0x8000)))
|
||||
message.wParam>='0' && message.wParam<='9' && !copyInProgress)
|
||||
{
|
||||
if(!(message.lParam & (1LL<<30)))
|
||||
{
|
||||
@@ -5922,17 +6292,17 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
continue;
|
||||
}
|
||||
const bool filesMessage=message.hwnd==window || IsChild(window,message.hwnd);
|
||||
if(filesMessage && !terminalVisible && !copyInProgress && !commandHistoryWindow &&
|
||||
message.message==WM_KEYDOWN && message.wParam=='8' &&
|
||||
if(mainInput && !terminalVisible && !copyInProgress &&
|
||||
message.message==WM_KEYDOWN && message.wParam>=VK_F1 && message.wParam<=VK_F12 &&
|
||||
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) &&
|
||||
!(GetKeyState(VK_SHIFT)&0x8000) && !(GetKeyState(VK_LWIN)&0x8000) &&
|
||||
!(GetKeyState(VK_RWIN)&0x8000))
|
||||
{
|
||||
if(!(message.lParam & (1LL<<30)))
|
||||
if(!(message.lParam & (1LL<<30)) && (message.wParam==VK_F1 || message.wParam==VK_F2))
|
||||
{
|
||||
hidePicker();
|
||||
showMenu(false);
|
||||
showFolderShortcuts(panels[active],-1,true);
|
||||
setMode(active,message.wParam==VK_F2);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -5975,6 +6345,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
message.message==WM_NCLBUTTONDOWN) && message.hwnd!=menuBar && message.hwnd!=picker &&
|
||||
std::find(std::begin(menuItems),std::end(menuItems),message.hwnd)==std::end(menuItems))
|
||||
{
|
||||
if(message.hwnd!=completionList) hideCompletion();
|
||||
showMenu(false);
|
||||
if(message.hwnd!=picker) hidePicker();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <string>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
inline std::wstring windowsPowerShell()
|
||||
{
|
||||
wchar_t system[MAX_PATH]{};
|
||||
const auto length=GetSystemDirectoryW(system,MAX_PATH);
|
||||
return length && length<MAX_PATH
|
||||
? std::wstring(system)+L"\\WindowsPowerShell\\v1.0\\powershell.exe" : std::wstring{};
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include "files_powershell.h"
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
@@ -50,10 +51,8 @@ public:
|
||||
startup.lpAttributeList=attributes;
|
||||
PROCESS_INFORMATION info{};
|
||||
wchar_t command[]=L"powershell.exe -NoLogo -NoProfile -NoExit -Command \"Remove-Module PSReadLine -ErrorAction SilentlyContinue; function global:prompt { $location = Get-Location; $path = if ($location.Provider.Name -eq 'FileSystem') { [Uri]::EscapeDataString($location.ProviderPath) }; ([string][char]27) + ']633;ks-directory:' + $path + [char]7 + [char]27 + '[?25l' }; Clear-Host\"";
|
||||
wchar_t system[MAX_PATH]{};
|
||||
const auto length=GetSystemDirectoryW(system,MAX_PATH);
|
||||
const auto shell=std::wstring(system)+L"\\WindowsPowerShell\\v1.0\\powershell.exe";
|
||||
const bool started=length && length<MAX_PATH &&
|
||||
const auto shell=ks::files::windowsPowerShell();
|
||||
const bool started=!shell.empty() &&
|
||||
UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
|
||||
console,sizeof(console),nullptr,nullptr) &&
|
||||
CreateProcessW(shell.c_str(),command,nullptr,nullptr,FALSE,EXTENDED_STARTUPINFO_PRESENT,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+87
-4
@@ -7,6 +7,8 @@
|
||||
#include "lan_mesh.h"
|
||||
#include "lan_clipboard.h"
|
||||
#include "lan_layout.h"
|
||||
#include "lan_network.h"
|
||||
#include "lan_wake.h"
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
@@ -28,14 +30,41 @@ std::string hostName()
|
||||
wchar_t name[256]{}; DWORD size=256;
|
||||
return GetComputerNameW(name,&size) ? utf8(std::wstring(name,size)) : "KSwitcher";
|
||||
}
|
||||
std::vector<ULONG> broadcasts()
|
||||
Bytes ipv4Adapters()
|
||||
{
|
||||
ULONG size=16384; Bytes data(size);
|
||||
auto flags=GAA_FLAG_SKIP_ANYCAST|GAA_FLAG_SKIP_MULTICAST|GAA_FLAG_SKIP_DNS_SERVER;
|
||||
auto result=GetAdaptersAddresses(AF_INET,flags,nullptr,(IP_ADAPTER_ADDRESSES*)data.data(),&size);
|
||||
if(result==ERROR_BUFFER_OVERFLOW) { data.resize(size); result=GetAdaptersAddresses(AF_INET,flags,nullptr,(IP_ADAPTER_ADDRESSES*)data.data(),&size); }
|
||||
if(result!=NO_ERROR) return {};
|
||||
return data;
|
||||
}
|
||||
std::string wakeMacFor(ULONG remote)
|
||||
{
|
||||
DWORD interfaceIndex{};
|
||||
if(GetBestInterface(remote,&interfaceIndex)!=NO_ERROR) return {};
|
||||
auto data=ipv4Adapters();
|
||||
if(data.empty()) return {};
|
||||
for(auto a=reinterpret_cast<const IP_ADAPTER_ADDRESSES*>(data.data());a;a=a->Next)
|
||||
{
|
||||
if(a->IfIndex!=interfaceIndex || a->OperStatus!=IfOperStatusUp || a->PhysicalAddressLength!=6 ||
|
||||
(a->IfType!=IF_TYPE_ETHERNET_CSMACD && a->IfType!=IF_TYPE_IEEE80211)) continue;
|
||||
std::string result;
|
||||
for(size_t i=0;i<a->PhysicalAddressLength;++i)
|
||||
{
|
||||
const auto byte=a->PhysicalAddress[i];
|
||||
result+="0123456789abcdef"[byte>>4];
|
||||
result+="0123456789abcdef"[byte&15];
|
||||
}
|
||||
return lan::wakePacket(result)?result:std::string{};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
std::vector<ULONG> broadcasts()
|
||||
{
|
||||
auto data=ipv4Adapters();
|
||||
std::vector<ULONG> out;
|
||||
if(result!=NO_ERROR) return out;
|
||||
if(data.empty()) return out;
|
||||
for(auto a=(IP_ADAPTER_ADDRESSES*)data.data();a;a=a->Next)
|
||||
if(a->OperStatus==IfOperStatusUp)
|
||||
for(auto u=a->FirstUnicastAddress;u;u=u->Next)
|
||||
@@ -47,6 +76,38 @@ std::vector<ULONG> broadcasts()
|
||||
return out;
|
||||
}
|
||||
}
|
||||
void lan::wakeFilesPeer(const std::string &id)
|
||||
{
|
||||
const auto settings=Json::parse(unprotect(readFile(dataDirectory()/L"lan-pairing.bin",256*1024)));
|
||||
const auto &trusted=settings.at("trusted");
|
||||
if(!settings.value("enabled",false) || !trusted.contains(id))
|
||||
throw std::runtime_error("Enable KSwitcher LAN and select a paired PC.");
|
||||
const auto packet=wakePacket(trusted.at(id).value("wakeMac",""));
|
||||
if(!packet) throw std::runtime_error("No saved MAC address. Run updated KSwitcher on this PC while it is online once.");
|
||||
const auto destinations=broadcasts();
|
||||
if(destinations.empty()) throw std::runtime_error("No local IPv4 network is available.");
|
||||
Network network;
|
||||
WinSocket socket{::socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP)};
|
||||
if(socket.value==INVALID_SOCKET) socketError();
|
||||
const BOOL broadcast=TRUE;
|
||||
if(setsockopt(socket.value,SOL_SOCKET,SO_BROADCAST,reinterpret_cast<const char*>(&broadcast),sizeof(broadcast)))
|
||||
socketError();
|
||||
bool sent=false;
|
||||
int error=WSAEHOSTUNREACH;
|
||||
for(const auto ip:destinations)
|
||||
{
|
||||
sockaddr_in destination{};
|
||||
destination.sin_family=AF_INET;
|
||||
destination.sin_port=htons(9);
|
||||
destination.sin_addr.s_addr=ip;
|
||||
if(sendto(socket.value,reinterpret_cast<const char*>(packet->data()),static_cast<int>(packet->size()),0,
|
||||
reinterpret_cast<const sockaddr*>(&destination),sizeof(destination))==SOCKET_ERROR)
|
||||
error=WSAGetLastError();
|
||||
else sent=true;
|
||||
}
|
||||
if(!sent) throw std::system_error(error,std::system_category());
|
||||
}
|
||||
|
||||
struct LanService::Impl
|
||||
{
|
||||
struct Peer { std::string name,epoch; sockaddr_in address{}; uint64_t seen{},verified{}; bool files{}; };
|
||||
@@ -231,7 +292,15 @@ struct LanService::Impl
|
||||
if(trusted.contains(other))
|
||||
{
|
||||
auto response=lan::envelope("presence",id); response["to"]=other; response["epoch"]=epoch;
|
||||
response["proof"]=lan::mac(trusted[other].at("key"),heartbeat(id,other,epoch,session));
|
||||
const auto &key=trusted[other].at("key");
|
||||
const auto challenge=heartbeat(id,other,epoch,session);
|
||||
response["proof"]=lan::mac(key,challenge);
|
||||
const auto wakeMac=wakeMacFor(address.sin_addr.s_addr);
|
||||
if(!wakeMac.empty())
|
||||
{
|
||||
response["wakeMac"]=wakeMac;
|
||||
response["wakeProof"]=lan::mac(key,challenge+"|wake|"+wakeMac);
|
||||
}
|
||||
send(socket,address,response);
|
||||
}
|
||||
return;
|
||||
@@ -260,7 +329,21 @@ struct LanService::Impl
|
||||
}
|
||||
if(type=="presence" && trusted.contains(other) && j.value("epoch","")==peer.epoch &&
|
||||
lan::equal(j.value("proof",""),lan::mac(trusted[other].at("key"),heartbeat(other,id,peer.epoch,epoch))))
|
||||
{ peer.verified=now; return; }
|
||||
{
|
||||
peer.verified=now;
|
||||
auto &entry=trusted.at(other);
|
||||
const auto wakeMac=j.value("wakeMac","");
|
||||
if(lan::wakePacket(wakeMac) && wakeMac!=entry.value("wakeMac","") &&
|
||||
lan::equal(j.value("wakeProof",""),
|
||||
lan::mac(entry.at("key"),heartbeat(other,id,peer.epoch,epoch)+"|wake|"+wakeMac)))
|
||||
{
|
||||
auto previous=entry;
|
||||
entry["wakeMac"]=wakeMac;
|
||||
try {save();}
|
||||
catch(const std::exception &){entry=std::move(previous);}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(pending && pending->peer==other)
|
||||
{
|
||||
for(const auto &response:pending->receive(j,now)) send(socket,address,response);
|
||||
|
||||
+4
-25
@@ -1,3 +1,4 @@
|
||||
#include "files_powershell.h"
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#include <shellapi.h>
|
||||
@@ -13,6 +14,7 @@
|
||||
#include <thread>
|
||||
#include "lan_files.h"
|
||||
#include "lan_channel.h"
|
||||
#include "lan_network.h"
|
||||
|
||||
namespace ks::lan
|
||||
{
|
||||
@@ -110,28 +112,6 @@ DWORD createJunction(const fs::path &name,const fs::path &target)
|
||||
constexpr size_t FrameLimit=256*1024;
|
||||
constexpr DWORD SocketTimeout=5000;
|
||||
|
||||
struct WinSocket
|
||||
{
|
||||
SOCKET value=INVALID_SOCKET;
|
||||
~WinSocket(){if(value!=INVALID_SOCKET) closesocket(value);}
|
||||
};
|
||||
|
||||
void socketError()
|
||||
{
|
||||
throw std::system_error(WSAGetLastError(),std::system_category());
|
||||
}
|
||||
|
||||
struct Network
|
||||
{
|
||||
Network()
|
||||
{
|
||||
WSADATA data{};
|
||||
if(const auto error=WSAStartup(MAKEWORD(2,2),&data))
|
||||
throw std::system_error(error,std::system_category());
|
||||
}
|
||||
~Network(){WSACleanup();}
|
||||
};
|
||||
|
||||
class Wire
|
||||
{
|
||||
SOCKET socket;
|
||||
@@ -323,9 +303,8 @@ struct RemoteCommand
|
||||
auto arguments=L"powershell.exe -NoLogo -NoProfile -NonInteractive -OutputFormat Text -Command "
|
||||
L"\"& ([ScriptBlock]::Create([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('"+
|
||||
encoded+L"'))))\"";
|
||||
wchar_t system[MAX_PATH]{};
|
||||
if(!GetSystemDirectoryW(system,MAX_PATH)) return GetLastError();
|
||||
const auto shell=std::wstring(system)+L"\\WindowsPowerShell\\v1.0\\powershell.exe";
|
||||
const auto shell=ks::files::windowsPowerShell();
|
||||
if(shell.empty()) return ERROR_PATH_NOT_FOUND;
|
||||
|
||||
FileHandle token,restricted,read,write,input,processJob;
|
||||
if(!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY|TOKEN_DUPLICATE|TOKEN_ASSIGN_PRIMARY|
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
#include <winsock2.h>
|
||||
#include <system_error>
|
||||
|
||||
namespace ks::lan
|
||||
{
|
||||
inline void socketError()
|
||||
{
|
||||
throw std::system_error(WSAGetLastError(),std::system_category());
|
||||
}
|
||||
|
||||
struct WinSocket
|
||||
{
|
||||
SOCKET value=INVALID_SOCKET;
|
||||
~WinSocket(){if(value!=INVALID_SOCKET) closesocket(value);}
|
||||
};
|
||||
|
||||
struct Network
|
||||
{
|
||||
Network()
|
||||
{
|
||||
WSADATA data{};
|
||||
if(const auto error=WSAStartup(MAKEWORD(2,2),&data))
|
||||
throw std::system_error(error,std::system_category());
|
||||
}
|
||||
~Network(){WSACleanup();}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
#pragma once
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace ks::lan
|
||||
{
|
||||
inline std::optional<std::array<unsigned char,102>> wakePacket(std::string_view mac)
|
||||
{
|
||||
constexpr std::string_view digits="0123456789abcdef";
|
||||
std::array<unsigned char,6> address{};
|
||||
if(mac.size()!=2*address.size()) return {};
|
||||
for(size_t i=0;i<address.size();++i)
|
||||
{
|
||||
const auto high=digits.find(mac[2*i]),low=digits.find(mac[2*i+1]);
|
||||
if(high==digits.npos || low==digits.npos) return {};
|
||||
address[i]=static_cast<unsigned char>(16*high+low);
|
||||
}
|
||||
if((address.front()&1) || std::all_of(address.begin(),address.end(),[](auto byte){return byte==0;}))
|
||||
return {};
|
||||
std::array<unsigned char,102> packet{};
|
||||
std::fill_n(packet.begin(),6,0xff);
|
||||
for(auto next=packet.begin()+6;next!=packet.end();next+=address.size())
|
||||
std::copy(address.begin(),address.end(),next);
|
||||
return packet;
|
||||
}
|
||||
|
||||
void wakeFilesPeer(const std::string &id);
|
||||
}
|
||||
+3
-2
@@ -269,8 +269,9 @@ void validateSettings(const Settings &s)
|
||||
if (alphabet.empty() || words.size() > 10000)
|
||||
throw std::runtime_error("Invalid personal dictionary language or too many words");
|
||||
for (const auto &word : words)
|
||||
if (word.empty() || word.size() > 32 || lower(word).find_first_not_of(alphabet) != word.npos)
|
||||
throw std::runtime_error("Personal words must contain 1-32 letters of their selected language");
|
||||
if (!validPersonalWord(word, alphabet))
|
||||
throw std::runtime_error("Personal words must be 1-32 characters, with letters of the selected language. "
|
||||
"A hyphen (-) is allowed between letters.");
|
||||
}
|
||||
if (s.maxItems < 10 || s.maxItems > 10000 || s.maxMiB < 1 || s.maxMiB > 2048 || s.maxImageMiB < 1 ||
|
||||
s.maxImageMiB > 64)
|
||||
|
||||
+1
-1
@@ -1705,7 +1705,7 @@ void showAutoOptions(HWND parent, SettingsView *v)
|
||||
label(w, L"Never correct these words (comma-separated)", 18, 184, 525);
|
||||
edit(w, 405, 18, 212, 524, 52, ES_MULTILINE | WS_VSCROLL | ES_AUTOVSCROLL);
|
||||
value(w, 405, commaList(v->draft.autoNever));
|
||||
label(w, L"My dictionary: correct words, separated by commas or new lines", 18, 276, 525);
|
||||
label(w, L"My dictionary: separate words by commas or new lines. Internal hyphens allowed.", 18, 276, 525);
|
||||
for (auto [id, language] : {std::pair{411, L"en"}, {412, L"uk"}, {413, L"ru"}})
|
||||
{
|
||||
int x = 18 + (id - 411) * 178;
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
#include "platform.h"
|
||||
namespace ks
|
||||
{
|
||||
inline constexpr wchar_t AppVersion[] = L"0.6.106";
|
||||
inline constexpr wchar_t AppVersion[] = L"0.6.110";
|
||||
inline constexpr UINT UpdateMessage = WM_APP + 7;
|
||||
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
|
||||
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
|
||||
|
||||
@@ -0,0 +1,446 @@
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$Executable,
|
||||
[string]$Screenshot
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
Add-Type @"
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class CompletionTest {
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Rect { public int Left, Top, Right, Bottom; }
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string name, string title);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr window, IntPtr process);
|
||||
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] static extern bool AttachThreadInput(uint first, uint second, bool attach);
|
||||
[DllImport("kernel32.dll")] static extern uint GetCurrentThreadId();
|
||||
public static void Activate(IntPtr window) {
|
||||
var own = GetCurrentThreadId();
|
||||
var foreground = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
|
||||
bool attached = foreground != 0 && own != foreground && AttachThreadInput(own, foreground, true);
|
||||
try { SetForegroundWindow(window); }
|
||||
finally { if (attached) AttachThreadInput(own, foreground, false); }
|
||||
}
|
||||
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr window, out Rect bounds);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr window, uint relation);
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Point { public int X, Y; }
|
||||
[DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(Point point);
|
||||
[DllImport("user32.dll")] public static extern bool RedrawWindow(IntPtr window, IntPtr rect, IntPtr region, uint flags);
|
||||
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
|
||||
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr window, int message, IntPtr w, IntPtr l);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, int message, IntPtr w, IntPtr l);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr SetText(IntPtr window, int message, IntPtr w, string text);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr GetText(IntPtr window, int message, IntPtr w, StringBuilder text);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr ItemRect(IntPtr window, int message, IntPtr w, out Rect bounds);
|
||||
}
|
||||
"@
|
||||
|
||||
function Wait-Until([string]$Description, [scriptblock]$Condition) {
|
||||
for ($attempt = 0; $attempt -lt 120; ++$attempt) {
|
||||
if (& $Condition) { return }
|
||||
Start-Sleep -Milliseconds 50
|
||||
}
|
||||
throw "Timed out waiting for $Description"
|
||||
}
|
||||
|
||||
function Set-Line([string]$Line) {
|
||||
[void][CompletionTest]::SetText($edit, 0x000C, 0, $Line)
|
||||
[void][CompletionTest]::Send($edit, 0x00B1, $Line.Length, $Line.Length)
|
||||
}
|
||||
|
||||
function Read-Line {
|
||||
$text = [Text.StringBuilder]::new(2049)
|
||||
[void][CompletionTest]::GetText($edit, 0x000D, $text.Capacity, $text)
|
||||
$text.ToString()
|
||||
}
|
||||
|
||||
function Suggestions([string]$Expected, [int]$Count = -1) {
|
||||
Wait-Until "suggestion '$Expected' (count $Count)" {
|
||||
if (![CompletionTest]::IsWindowVisible($list)) { return $false }
|
||||
$found = [CompletionTest]::SetText($list, 0x01A2, -1, $Expected).ToInt64()
|
||||
$size = [CompletionTest]::Send($list, 0x018B, 0, 0).ToInt64()
|
||||
$found -ge 0 -and ($Count -lt 0 -or $size -eq $Count)
|
||||
}
|
||||
}
|
||||
|
||||
function Press-Key([int]$Key) {
|
||||
if (![CompletionTest]::PostMessage($edit, 0x0100, $Key, 1)) { throw 'Could not post key' }
|
||||
}
|
||||
|
||||
function Toggle-Panels {
|
||||
Wait-Until 'foreground Files window before toggling panes' {
|
||||
if ([CompletionTest]::GetForegroundWindow() -eq $window) { return $true }
|
||||
[void]$keyboard.AppActivate($process.Id)
|
||||
[CompletionTest]::Activate($window)
|
||||
[CompletionTest]::GetForegroundWindow() -eq $window
|
||||
}
|
||||
$keyboard.SendKeys('^o')
|
||||
}
|
||||
|
||||
function Read-SuggestionFrameColor {
|
||||
$frame = [CompletionTest]::GetWindow($list, 2)
|
||||
$bounds = [CompletionTest+Rect]::new()
|
||||
[void][CompletionTest]::GetWindowRect($frame, [ref]$bounds)
|
||||
$pixel = [Drawing.Bitmap]::new(1, 1)
|
||||
$graphics = [Drawing.Graphics]::FromImage($pixel)
|
||||
try {
|
||||
$graphics.CopyFromScreen($bounds.Left + 2, $bounds.Top + 2, 0, 0, $pixel.Size)
|
||||
$pixel.GetPixel(0, 0).ToArgb()
|
||||
} finally {
|
||||
$graphics.Dispose()
|
||||
$pixel.Dispose()
|
||||
}
|
||||
}
|
||||
|
||||
function Test-DotnetCompletion {
|
||||
if (!$hasDotnetSdk) { return }
|
||||
Set-Line 'dotnet '
|
||||
Suggestions 'build'
|
||||
Set-Line 'dotnet bu'
|
||||
Suggestions 'build'
|
||||
Set-Line 'dotnet build --no-res'
|
||||
Suggestions '--no-restore'
|
||||
$row = [CompletionTest]::SetText($list, 0x01A2, -1, '--no-restore')
|
||||
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
|
||||
Press-Key 0x0D
|
||||
Wait-Until 'dotnet option insertion' { (Read-Line) -ceq 'dotnet build --no-restore' }
|
||||
}
|
||||
|
||||
function Test-GitCompletion {
|
||||
if (!$gitFixture) { return }
|
||||
Set-Line 'git ch'
|
||||
Suggestions 'checkout'
|
||||
Set-Line 'git --ver'
|
||||
Suggestions '--version'
|
||||
$switch = 'git -C "' + $gitFixture + '" switch '
|
||||
Set-Line ($switch + '--de')
|
||||
Suggestions '--detach'
|
||||
$prefix = $switch + 'comp'
|
||||
Set-Line $prefix
|
||||
Suggestions 'completion-one'
|
||||
Suggestions 'completion-two'
|
||||
$row = [CompletionTest]::SetText($list, 0x01A2, -1, 'completion-one')
|
||||
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
|
||||
Press-Key 0x0D
|
||||
Wait-Until 'Git branch insertion' { (Read-Line) -ceq ($prefix + 'letion-one') }
|
||||
}
|
||||
|
||||
function Test-WindowsCommandCompletion {
|
||||
Set-Line 'ipconfig '
|
||||
Suggestions '/all'
|
||||
Set-Line 'ipconfig /re'
|
||||
Suggestions '/renew'
|
||||
Suggestions '/release'
|
||||
Set-Line 'ipconfig ?'
|
||||
Suggestions '/?'
|
||||
$row = [CompletionTest]::SetText($list, 0x01A2, -1, '/?')
|
||||
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
|
||||
Press-Key 0x0D
|
||||
Wait-Until 'ipconfig help switch insertion' { (Read-Line) -ceq 'ipconfig /?' }
|
||||
|
||||
Set-Line 'tasklist.exe /f'
|
||||
Suggestions '/fo'
|
||||
Set-Line 'robocopy /mi'
|
||||
Suggestions '/mir'
|
||||
Set-Line 'reg q'
|
||||
Suggestions 'query'
|
||||
Set-Line 'reg query /r'
|
||||
Suggestions '/reg:64'
|
||||
Set-Line 'cmd /c dir /'
|
||||
Suggestions '/w'
|
||||
Set-Line 'dir -Fi'
|
||||
Suggestions 'File'
|
||||
}
|
||||
|
||||
function Test-NestedWindowsCommandCompletion {
|
||||
Set-Line 'netsh interface ip'
|
||||
Suggestions 'ipv4'
|
||||
Set-Line 'netsh interface ipv4 sh'
|
||||
Suggestions 'show'
|
||||
Set-Line 'netsh interface ipv4 show co'
|
||||
Suggestions 'config'
|
||||
Set-Line 'netsh interface ipv4 show config na'
|
||||
Suggestions 'name='
|
||||
Set-Line 'fsutil file queryallocranges of'
|
||||
Suggestions 'offset='
|
||||
Set-Line 'wevtutil query-events /sb'
|
||||
Suggestions '/sbm:'
|
||||
Set-Line 'schtasks /query /fo L'
|
||||
Suggestions 'LIST'
|
||||
$row = [CompletionTest]::SetText($list, 0x01A2, -1, 'LIST')
|
||||
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
|
||||
Press-Key 0x0D
|
||||
Wait-Until 'nested Windows option insertion' { (Read-Line) -ceq 'schtasks /query /fo LIST' }
|
||||
}
|
||||
|
||||
function Test-IpconfigAdapterCompletion {
|
||||
$adapters = foreach ($adapter in [Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces()) {
|
||||
if (!$adapter.Supports([Net.NetworkInformation.NetworkInterfaceComponent]::IPv4)) { continue }
|
||||
try {
|
||||
if ($adapter.GetIPProperties().GetIPv4Properties().IsDhcpEnabled) { $adapter.Name }
|
||||
} catch {}
|
||||
}
|
||||
if (!$adapters) { return }
|
||||
$name = $adapters | Where-Object { $_ -match '^[\p{L}\p{N}-]+ [\p{L}\p{N} ]+$' } | Select-Object -First 1
|
||||
if ($name) {
|
||||
$prefix = '"' + $name.Substring(0, $name.IndexOf(' ') + 1)
|
||||
$expected = "'" + $name + "'"
|
||||
} else {
|
||||
$name = $adapters | Where-Object { $_ -match '^[\p{L}\p{N}-]+$' } | Select-Object -First 1
|
||||
if (!$name) { return }
|
||||
$prefix = $name.Substring(0, 1).ToUpperInvariant()
|
||||
$expected = $name
|
||||
}
|
||||
Set-Line 'ipconfig /renew '
|
||||
Suggestions $name
|
||||
Set-Line ('ipconfig.exe /release ' + $prefix)
|
||||
Suggestions $name
|
||||
$row = [CompletionTest]::SetText($list, 0x01A2, -1, $name)
|
||||
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
|
||||
Press-Key 0x0D
|
||||
Wait-Until 'ipconfig adapter insertion' { (Read-Line) -ceq ('ipconfig.exe /release ' + $expected) }
|
||||
}
|
||||
|
||||
function Test-PathCompletion {
|
||||
$prefix = 'cd "' + $root + '\Al'
|
||||
Set-Line $prefix
|
||||
Suggestions 'Alpine' 2
|
||||
[void][CompletionTest]::Send($edit, 0x0102, [int][char]'p', 1)
|
||||
Suggestions 'Alpha Space' 2
|
||||
[void][CompletionTest]::Send($edit, 0x0102, [int][char]'h', 1)
|
||||
Suggestions 'Alpha Space' 1
|
||||
|
||||
$row = [CompletionTest+Rect]::new()
|
||||
[void][CompletionTest]::ItemRect($list, 0x0198, 0, [ref]$row)
|
||||
$listBounds = [CompletionTest+Rect]::new()
|
||||
[void][CompletionTest]::GetWindowRect($list, [ref]$listBounds)
|
||||
$mouse = [CompletionTest+Point]::new()
|
||||
$mouse.X = $listBounds.Left + 5
|
||||
$mouse.Y = $listBounds.Top + (($row.Top + $row.Bottom) -shr 1)
|
||||
if ([CompletionTest]::WindowFromPoint($mouse) -ne $list) { throw 'The suggestions list is covered' }
|
||||
$point = ((($row.Top + $row.Bottom) -shr 1) -shl 16) -bor 5
|
||||
[void][CompletionTest]::PostMessage($list, 0x0201, 1, $point)
|
||||
Wait-Until 'click insertion with quotes' { (Read-Line) -ceq ('cd "' + $root + '\Alpha Space"') }
|
||||
[void][CompletionTest]::Send($edit, 0x0102, [int][char]'\', 1)
|
||||
Suggestions 'Nested' 1
|
||||
|
||||
Press-Key 0x1B
|
||||
Wait-Until 'Escape dismissal' { ![CompletionTest]::IsWindowVisible($list) }
|
||||
if ((Read-Line) -cne ('cd "' + $root + '\Alpha Space\"')) { throw 'Escape changed the command line' }
|
||||
}
|
||||
|
||||
$root = Join-Path ([IO.Path]::GetTempPath()) ("KSwitcherCompletion-" + [guid]::NewGuid().ToString('N'))
|
||||
$process = $null
|
||||
$dotnet = Get-Command dotnet.exe -CommandType Application -ErrorAction SilentlyContinue
|
||||
$hasDotnetSdk = $dotnet -and [bool](& $dotnet.Source --list-sdks)
|
||||
$historyKey = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
|
||||
$historyPrefix = "Write-Output 'completion-$([guid]::NewGuid().ToString('N'))"
|
||||
$latest = "$historyPrefix-alpha-recent'"
|
||||
$earlier = "$historyPrefix-alpha-earlier'"
|
||||
$other = "$historyPrefix-beta'"
|
||||
$combined = "Get-ChildItem -Name # $([guid]::NewGuid().ToString('N'))"
|
||||
$clearPrefix = ' cls '
|
||||
$clearHistory = "$clearPrefix# $([guid]::NewGuid().ToString('N'))"
|
||||
$fixture = "2026-01-01`0$earlier`02026-01-01`0$other`02026-01-01`0$earlier`02026-01-01`0$latest`02026-01-01`0$combined`02026-01-01`0$clearHistory`0"
|
||||
|
||||
function Remove-HistoryFixture {
|
||||
$bytes = $historyKey.GetValue('CommandHistory')
|
||||
if ($bytes -isnot [byte[]]) { return }
|
||||
$current = [Text.Encoding]::Unicode.GetString($bytes)
|
||||
$clean = $current.Replace($fixture, '')
|
||||
if ($clean -ceq $current) { return }
|
||||
if ($clean.Length -eq 0 -and $null -eq $originalHistory) {
|
||||
$historyKey.DeleteValue('CommandHistory', $false)
|
||||
} else {
|
||||
$historyKey.SetValue('CommandHistory', [Text.Encoding]::Unicode.GetBytes($clean), 'Binary')
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
$originalHistory = $historyKey.GetValue('CommandHistory')
|
||||
$history = if ($null -ne $originalHistory) { [Text.Encoding]::Unicode.GetString($originalHistory) } else { '' }
|
||||
$historyKey.SetValue('CommandHistory', [Text.Encoding]::Unicode.GetBytes($history + $fixture), 'Binary')
|
||||
[void](New-Item -ItemType Directory -Path "$root\Alpha Space\Nested", "$root\Alpine")
|
||||
$gitFixture = $null
|
||||
$git = Get-Command git.exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
if ($git) {
|
||||
$location = [IO.DirectoryInfo]::new([IO.Path]::GetDirectoryName($git.Source))
|
||||
for ($level = 0; $location -and $level -lt 3; ++$level) {
|
||||
$installation = $location.FullName
|
||||
$location = $location.Parent
|
||||
if (!(Test-Path -LiteralPath (Join-Path $installation 'usr/bin/bash.exe'))) { continue }
|
||||
$gitFixture = Join-Path $root 'Git Repo'
|
||||
[void](New-Item -ItemType Directory -Path $gitFixture)
|
||||
& $git.Source -C $gitFixture init --quiet --template= --initial-branch=main
|
||||
if ($LASTEXITCODE) { throw 'Could not initialize the Git fixture' }
|
||||
& $git.Source -C $gitFixture -c user.name=Test -c user.email=test@example.invalid -c commit.gpgSign=false -c core.hooksPath=NUL commit --quiet --allow-empty -m fixture
|
||||
if ($LASTEXITCODE) { throw 'Could not create the Git fixture commit' }
|
||||
& $git.Source -C $gitFixture branch completion-one
|
||||
if ($LASTEXITCODE) { throw 'Could not create Git fixture branch completion-one' }
|
||||
& $git.Source -C $gitFixture branch completion-two
|
||||
if ($LASTEXITCODE) { throw 'Could not create Git fixture branch completion-two' }
|
||||
break
|
||||
}
|
||||
}
|
||||
$process = Start-Process -FilePath (Resolve-Path $Executable) -PassThru -WindowStyle Normal
|
||||
Wait-Until 'Files window' {
|
||||
$process.Refresh()
|
||||
$process.MainWindowHandle -ne [IntPtr]::Zero
|
||||
}
|
||||
Remove-HistoryFixture
|
||||
$window = $process.MainWindowHandle
|
||||
$keyboard = New-Object -ComObject WScript.Shell
|
||||
Wait-Until 'foreground Files window' {
|
||||
[void]$keyboard.AppActivate($process.Id)
|
||||
[CompletionTest]::Activate($window)
|
||||
[CompletionTest]::GetForegroundWindow() -eq $window
|
||||
}
|
||||
$edit = [CompletionTest]::FindWindowEx($window, 0, 'Edit', [System.Management.Automation.Language.NullString]::Value)
|
||||
$list = [CompletionTest]::GetDlgItem($window, 149)
|
||||
if (!$edit -or !$list) { throw 'Missing command line or suggestions list' }
|
||||
|
||||
[void][CompletionTest]::SetThreadDpiAwarenessContext(-4)
|
||||
$status = [CompletionTest]::GetDlgItem($window, 144)
|
||||
$panel = [CompletionTest]::GetDlgItem($window, 102)
|
||||
$statusBounds = [CompletionTest+Rect]::new()
|
||||
$panelBounds = [CompletionTest+Rect]::new()
|
||||
[void][CompletionTest]::GetWindowRect($panel, [ref]$panelBounds)
|
||||
[void][CompletionTest]::GetWindowRect($status, [ref]$statusBounds)
|
||||
if ($statusBounds.Left -ge $panelBounds.Right) {
|
||||
Press-Key 0x09
|
||||
Wait-Until 'left panel active' {
|
||||
$bounds = [CompletionTest+Rect]::new()
|
||||
[void][CompletionTest]::GetWindowRect($status, [ref]$bounds)
|
||||
$bounds.Left -lt $panelBounds.Right
|
||||
}
|
||||
[void][CompletionTest]::GetWindowRect($status, [ref]$statusBounds)
|
||||
}
|
||||
|
||||
Set-Line $clearPrefix
|
||||
Suggestions $clearHistory 1
|
||||
|
||||
Set-Line 'Get-Chi'
|
||||
Suggestions 'Get-ChildItem'
|
||||
Suggestions $combined
|
||||
|
||||
$frame = [CompletionTest]::GetWindow($list, 2)
|
||||
$frameBounds = [CompletionTest+Rect]::new()
|
||||
[void][CompletionTest]::GetWindowRect($frame, [ref]$frameBounds)
|
||||
$x = [Math]::Max($statusBounds.Left, $frameBounds.Left)
|
||||
$y = [Math]::Max($statusBounds.Top, $frameBounds.Top)
|
||||
$w = [Math]::Min($statusBounds.Right, $frameBounds.Right) - $x
|
||||
$h = [Math]::Min($statusBounds.Bottom, $frameBounds.Bottom) - $y
|
||||
if ($w -le 0 -or $h -le 0) { throw 'Suggestions and status must overlap for the repaint check' }
|
||||
$before = [Drawing.Bitmap]::new($w, $h)
|
||||
$after = [Drawing.Bitmap]::new($w, $h)
|
||||
try {
|
||||
$graphics = [Drawing.Graphics]::FromImage($before)
|
||||
try { $graphics.CopyFromScreen($x, $y, 0, 0, $before.Size) } finally { $graphics.Dispose() }
|
||||
[void][CompletionTest]::SetText($status, 0x000C, 0, ('Status repaint test ' * 48))
|
||||
[void][CompletionTest]::RedrawWindow($status, 0, 0, 0x0105)
|
||||
$graphics = [Drawing.Graphics]::FromImage($after)
|
||||
try { $graphics.CopyFromScreen($x, $y, 0, 0, $after.Size) } finally { $graphics.Dispose() }
|
||||
for ($rowPixel = 0; $rowPixel -lt $h; ++$rowPixel) {
|
||||
for ($columnPixel = 0; $columnPixel -lt $w; ++$columnPixel) {
|
||||
if ($before.GetPixel($columnPixel, $rowPixel) -ne $after.GetPixel($columnPixel, $rowPixel)) {
|
||||
throw 'Status repaint drew over command suggestions'
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
$before.Dispose()
|
||||
$after.Dispose()
|
||||
}
|
||||
|
||||
$row = [CompletionTest]::SetText($list, 0x01A2, -1, 'Get-ChildItem')
|
||||
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
|
||||
Press-Key 0x09
|
||||
Wait-Until 'Tab insertion' { (Read-Line) -ceq 'Get-ChildItem' }
|
||||
|
||||
Set-Line ($historyPrefix.ToUpperInvariant())
|
||||
Suggestions $latest 3
|
||||
Set-Line "$historyPrefix-alpha"
|
||||
Suggestions $earlier 2
|
||||
Press-Key 0x09
|
||||
Wait-Until 'most recent history insertion' { (Read-Line) -ceq $latest }
|
||||
|
||||
Set-Line 'Get-ChildItem -Pa'
|
||||
Suggestions 'Path'
|
||||
$row = [CompletionTest]::SetText($list, 0x01A2, -1, 'Path')
|
||||
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
|
||||
Press-Key 0x0D
|
||||
Wait-Until 'Enter insertion' { (Read-Line) -ceq 'Get-ChildItem -Path' }
|
||||
|
||||
Test-PathCompletion
|
||||
Test-DotnetCompletion
|
||||
Test-GitCompletion
|
||||
Test-WindowsCommandCompletion
|
||||
Test-NestedWindowsCommandCompletion
|
||||
Test-IpconfigAdapterCompletion
|
||||
|
||||
# Toggle with a populated list and verify the same draft and suggestions remain accessible.
|
||||
Set-Line "$historyPrefix-alpha"
|
||||
Suggestions $latest 2
|
||||
$frameColor = Read-SuggestionFrameColor
|
||||
$output = [CompletionTest]::GetDlgItem($window, 145)
|
||||
Toggle-Panels
|
||||
Wait-Until 'terminal-only view' {
|
||||
[CompletionTest]::IsWindowVisible($output) -and ![CompletionTest]::IsWindowVisible($panel) -and
|
||||
[CompletionTest]::GetWindow($output, 5) -ne [IntPtr]::Zero
|
||||
}
|
||||
Suggestions $latest 2
|
||||
# Let WebView2 finish its first compositor update after showing the terminal.
|
||||
Start-Sleep -Milliseconds 350
|
||||
if ((Read-SuggestionFrameColor) -ne $frameColor) {
|
||||
throw 'Terminal output drew over command suggestions with panels hidden'
|
||||
}
|
||||
if ($Screenshot) {
|
||||
[void][CompletionTest]::SetThreadDpiAwarenessContext(-4)
|
||||
$bounds = [CompletionTest+Rect]::new()
|
||||
[void][CompletionTest]::GetWindowRect($window, [ref]$bounds)
|
||||
$bitmap = [Drawing.Bitmap]::new($bounds.Right - $bounds.Left, $bounds.Bottom - $bounds.Top)
|
||||
$graphics = [Drawing.Graphics]::FromImage($bitmap)
|
||||
try {
|
||||
$graphics.CopyFromScreen($bounds.Left, $bounds.Top, 0, 0, $bitmap.Size)
|
||||
$bitmap.Save($Screenshot, [Drawing.Imaging.ImageFormat]::Png)
|
||||
} finally {
|
||||
$graphics.Dispose()
|
||||
$bitmap.Dispose()
|
||||
}
|
||||
}
|
||||
|
||||
Press-Key 0x28
|
||||
Press-Key 0x0D
|
||||
Wait-Until 'history insertion with panels hidden' { (Read-Line) -ceq $latest }
|
||||
Test-PathCompletion
|
||||
Test-DotnetCompletion
|
||||
Test-GitCompletion
|
||||
Test-WindowsCommandCompletion
|
||||
Test-NestedWindowsCommandCompletion
|
||||
Test-IpconfigAdapterCompletion
|
||||
|
||||
Toggle-Panels
|
||||
Wait-Until 'panels restored' { [CompletionTest]::IsWindowVisible($panel) }
|
||||
Set-Line "$historyPrefix-alpha"
|
||||
Suggestions $latest 2
|
||||
'Command completion passed with panels visible and hidden'
|
||||
} finally {
|
||||
if ($process -and !$process.HasExited) { Stop-Process -Id $process.Id }
|
||||
Remove-HistoryFixture
|
||||
$historyKey.Dispose()
|
||||
if ($gitFixture -and (Test-Path -LiteralPath $gitFixture)) {
|
||||
$resolved = (Resolve-Path -LiteralPath $gitFixture).ProviderPath
|
||||
if ($resolved -eq [IO.Path]::GetFullPath((Join-Path $root 'Git Repo'))) {
|
||||
Remove-Item -LiteralPath $resolved -Recurse -Force
|
||||
}
|
||||
}
|
||||
foreach ($path in "$root\Alpha Space\Nested", "$root\Alpha Space", "$root\Alpine", $root) {
|
||||
if (Test-Path -LiteralPath $path) { [IO.Directory]::Delete($path) }
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,26 @@
|
||||
param([string]$Executable = "$PSScriptRoot/../build/files-dev/KSwitcher.Files.exe")
|
||||
param(
|
||||
[string]$Executable = "$PSScriptRoot/../build/files-dev/KSwitcher.Files.exe",
|
||||
[switch]$OfflineWake,
|
||||
[string]$Screenshot
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
Add-Type @'
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class FilesDriveShortcutTest {
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Rect { public int Left, Top, Right, Bottom; }
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr window, uint msg, IntPtr w, IntPtr l);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)]
|
||||
public static extern IntPtr SendMessage(IntPtr window, uint msg, IntPtr w, StringBuilder text);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW")]
|
||||
public static extern IntPtr SendRect(IntPtr window, uint msg, IntPtr w, out Rect rect);
|
||||
[DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr window, out Rect rect);
|
||||
[DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr window, IntPtr dc, uint flags);
|
||||
}
|
||||
'@
|
||||
function Wait-Until([scriptblock]$Condition) {
|
||||
@@ -38,6 +49,68 @@ try {
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 258, [IntPtr][int]$Key, [IntPtr]::Zero)
|
||||
Wait-Until { ![FilesDriveShortcutTest]::IsWindowVisible($picker) }
|
||||
}
|
||||
if ($OfflineWake) {
|
||||
function Read-Picker {
|
||||
$count = [FilesDriveShortcutTest]::SendMessage($picker, 395, [IntPtr]::Zero, $null).ToInt32()
|
||||
for ($i = 0; $i -lt $count; $i++) { Read-Text $picker 393 $i }
|
||||
}
|
||||
function Render-Picker {
|
||||
$client = [FilesDriveShortcutTest+Rect]::new()
|
||||
[void][FilesDriveShortcutTest]::GetClientRect($picker, [ref]$client)
|
||||
$bitmap = [Drawing.Bitmap]::new($client.Right, $client.Bottom)
|
||||
$graphics = [Drawing.Graphics]::FromImage($bitmap)
|
||||
try {
|
||||
$dc = $graphics.GetHdc()
|
||||
try {
|
||||
if (![FilesDriveShortcutTest]::PrintWindow($picker, $dc, 2)) { throw 'Could not render drive picker.' }
|
||||
} finally { $graphics.ReleaseHdc($dc) }
|
||||
return $bitmap
|
||||
} finally { $graphics.Dispose() }
|
||||
}
|
||||
function Click-Picker([int]$X, [int]$Y) {
|
||||
$point = [IntPtr](($Y -shl 16) -bor $X)
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 513, [IntPtr]1, $point)
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 514, [IntPtr]::Zero, $point)
|
||||
}
|
||||
Open-Picker
|
||||
$rows = @(Read-Picker)
|
||||
$wake = -1
|
||||
for ($i = 0; $i -lt $rows.Count; $i++) {
|
||||
if ($rows[$i] -match '^ (Offline|Looking for PC\.\.\.) \tWake$') { $wake = $i; break }
|
||||
}
|
||||
if ($wake -lt 0) { throw 'This check requires an offline paired PC with a Wake action.' }
|
||||
$rect = [FilesDriveShortcutTest+Rect]::new()
|
||||
[void][FilesDriveShortcutTest]::SendRect($picker, 408, [IntPtr]$wake, [ref]$rect)
|
||||
$original = [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null)
|
||||
Click-Picker ($rect.Left + 16) ([int](($rect.Top + $rect.Bottom) / 2))
|
||||
Start-Sleep -Milliseconds 100
|
||||
if (![FilesDriveShortcutTest]::IsWindowVisible($picker) -or
|
||||
[FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null) -ne $original) {
|
||||
throw 'Clicking outside the Wake label selected or activated the status row.'
|
||||
}
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 675, [IntPtr]::Zero, [IntPtr]::Zero)
|
||||
$normal = Render-Picker
|
||||
[void][FilesDriveShortcutTest]::SendMessage($picker, 390, [IntPtr]$wake, $null)
|
||||
$focused = Render-Picker
|
||||
try {
|
||||
$changed = @(for ($x = $rect.Left; $x -lt [Math]::Min($rect.Right, $normal.Width); $x++) {
|
||||
if ($normal.GetPixel($x,$rect.Top) -ne $focused.GetPixel($x,$rect.Top)) { $x }
|
||||
})
|
||||
$width = $rect.Right - $rect.Left
|
||||
if (!$changed.Count -or $changed[0] -lt ($rect.Left + $width / 2) -or $changed[-1] -ge $rect.Right - 2) {
|
||||
throw 'Wake focus must highlight only the inline action and leave the status and trailing space unchanged.'
|
||||
}
|
||||
if ($Screenshot) { $focused.Save($Screenshot, [Drawing.Imaging.ImageFormat]::Png) }
|
||||
Click-Picker ([int](($changed[0]+$changed[-1])/2)) ([int](($rect.Top+$rect.Bottom)/2))
|
||||
Wait-Until { ![FilesDriveShortcutTest]::IsWindowVisible($picker) }
|
||||
} finally { $normal.Dispose(); $focused.Dispose() }
|
||||
Open-Picker
|
||||
[void][FilesDriveShortcutTest]::SendMessage($picker, 390, [IntPtr]$wake, $null)
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]13, [IntPtr]::Zero)
|
||||
Wait-Until { ![FilesDriveShortcutTest]::IsWindowVisible($picker) }
|
||||
Write-Output 'Wake focus and mouse activation are limited to the inline action. Enter activates the focused action.'
|
||||
return
|
||||
}
|
||||
Open-Picker
|
||||
$count = [FilesDriveShortcutTest]::SendMessage($picker, 395, [IntPtr]::Zero, $null).ToInt32()
|
||||
$rows = @(for ($i = 0; $i -lt $count; $i++) { Read-Text $picker 393 $i })
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
param(
|
||||
[string]$Executable = "$PSScriptRoot/../build/files-cmake/KSwitcher.Files.exe",
|
||||
[string]$Screenshot
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type @'
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class FilesShortcutWindow {
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Rect { public int Left, Top, Right, Bottom; }
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr window, uint command);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr window, out Rect rect);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)]
|
||||
public static extern IntPtr SendMessage(IntPtr window, uint msg, IntPtr w, StringBuilder text);
|
||||
public static bool Activate(IntPtr window) {
|
||||
if (GetForegroundWindow() == window) return true;
|
||||
keybd_event(0x12, 0, 0, UIntPtr.Zero);
|
||||
keybd_event(0x12, 0, 2, UIntPtr.Zero);
|
||||
SetForegroundWindow(window);
|
||||
return GetForegroundWindow() == window;
|
||||
}
|
||||
}
|
||||
'@
|
||||
function Wait-Until([scriptblock]$Condition) {
|
||||
for ($attempt = 0; $attempt -lt 100; $attempt++) {
|
||||
if (& $Condition) { return }
|
||||
Start-Sleep -Milliseconds 50
|
||||
}
|
||||
throw "Timed out waiting for: $Condition"
|
||||
}
|
||||
function Read-Text($Control, $Message = 13, $Parameter = 2048) {
|
||||
$buffer = [Text.StringBuilder]::new(2048)
|
||||
[void][FilesShortcutWindow]::SendMessage($Control, $Message, [IntPtr]$Parameter, $buffer)
|
||||
$buffer.ToString()
|
||||
}
|
||||
function Read-ShortcutDialog {
|
||||
$foreground = [FilesShortcutWindow]::GetForegroundWindow()
|
||||
if ([FilesShortcutWindow]::GetWindow($foreground, 4) -eq $window -and
|
||||
[FilesShortcutWindow]::GetDlgItem($foreground, 310) -ne [IntPtr]::Zero) { return $foreground }
|
||||
return [IntPtr]::Zero
|
||||
}
|
||||
|
||||
$exe = (Resolve-Path $Executable).Path
|
||||
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
|
||||
$saved = @{}
|
||||
$names = 'FolderShortcuts', 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement'
|
||||
foreach ($name in $names) {
|
||||
if ($name -in $key.GetValueNames()) { $saved[$name] = @($key.GetValue($name), $key.GetValueKind($name)) }
|
||||
}
|
||||
$folder = [IO.Directory]::CreateTempSubdirectory('ks-files-shortcuts-').FullName
|
||||
try {
|
||||
$groups = [object[]]::new(10)
|
||||
for ($digit = 0; $digit -lt 10; $digit++) { $groups[$digit] = @() }
|
||||
foreach ($entry in @(@(3, 'Three'), @(4, 'Four'), @(8, 'Eight A'), @(8, 'Eight B'))) {
|
||||
$path = [IO.Directory]::CreateDirectory((Join-Path $folder $entry[1])).FullName
|
||||
$groups[$entry[0]] += @{ path = $path; peer = ''; name = ''; title = $entry[1] }
|
||||
}
|
||||
$key.SetValue('FolderShortcuts', [Text.Encoding]::UTF8.GetBytes((ConvertTo-Json -InputObject $groups -Depth 4)), 'Binary')
|
||||
foreach ($name in 'LeftWide', 'RightWide') { $key.SetValue($name, 1, 'DWord') }
|
||||
foreach ($name in 'LeftPath', 'RightPath') { $key.SetValue($name, $folder, 'String') }
|
||||
$key.DeleteValue('WindowPlacement', $false)
|
||||
|
||||
$process = Start-Process -FilePath $exe -PassThru
|
||||
$keyboard = New-Object -ComObject WScript.Shell
|
||||
Wait-Until { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
|
||||
$window = $process.MainWindowHandle
|
||||
Wait-Until { [FilesShortcutWindow]::Activate($window) }
|
||||
$heading = [FilesShortcutWindow]::GetDlgItem($window, 140)
|
||||
$rightHeading = [FilesShortcutWindow]::GetDlgItem($window, 141)
|
||||
$leftPath = [FilesShortcutWindow]::GetDlgItem($window, 142)
|
||||
Wait-Until { (Read-Text $leftPath) -eq $folder }
|
||||
|
||||
$keyboard.SendKeys('^8')
|
||||
Wait-Until { (Read-ShortcutDialog) -ne [IntPtr]::Zero }
|
||||
$dialog = Read-ShortcutDialog
|
||||
$list = [FilesShortcutWindow]::GetDlgItem($dialog, 310)
|
||||
$count = [FilesShortcutWindow]::SendMessage($list, 395, [IntPtr]::Zero, $null).ToInt32()
|
||||
$rows = for ($row = 0; $row -lt $count; $row++) { Read-Text $list 393 $row }
|
||||
if (($rows -join '|') -cne 'Eight A|Eight B') {
|
||||
throw "Ctrl+8 should display only its two assigned folders. Actual rows: $($rows -join ' | ')"
|
||||
}
|
||||
if ($Screenshot) {
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
$bounds = [FilesShortcutWindow+Rect]::new()
|
||||
if (![FilesShortcutWindow]::GetWindowRect($dialog, [ref]$bounds)) { throw 'Cannot locate the rendered popup.' }
|
||||
$bitmap = [Drawing.Bitmap]::new(($bounds.Right - $bounds.Left), ($bounds.Bottom - $bounds.Top))
|
||||
try {
|
||||
$graphics = [Drawing.Graphics]::FromImage($bitmap)
|
||||
try { $graphics.CopyFromScreen($bounds.Left, $bounds.Top, 0, 0, $bitmap.Size) }
|
||||
finally { $graphics.Dispose() }
|
||||
$bitmap.Save($Screenshot, [Drawing.Imaging.ImageFormat]::Png)
|
||||
} finally { $bitmap.Dispose() }
|
||||
}
|
||||
$keyboard.SendKeys('{ESC}')
|
||||
Wait-Until { [FilesShortcutWindow]::GetForegroundWindow() -eq $window }
|
||||
$keyboard.SendKeys('^4')
|
||||
Wait-Until { (Read-Text $leftPath) -eq (Join-Path $folder 'Four') }
|
||||
if (![FilesShortcutWindow]::IsWindowVisible($heading)) { throw 'Ctrl+4 changed panel mode.' }
|
||||
$keyboard.SendKeys('^{F1}')
|
||||
Wait-Until { ![FilesShortcutWindow]::IsWindowVisible($heading) }
|
||||
if (![FilesShortcutWindow]::IsWindowVisible($rightHeading)) { throw 'Ctrl+F1 changed the inactive panel.' }
|
||||
$keyboard.SendKeys('^{F2}')
|
||||
Wait-Until { [FilesShortcutWindow]::IsWindowVisible($heading) }
|
||||
Write-Output 'Verified Ctrl+8 popup rows, Ctrl+4 navigation and Ctrl+F1/F2 panel modes.'
|
||||
} finally {
|
||||
if ($process -and !$process.HasExited) {
|
||||
$keyboard.SendKeys('{ESC}')
|
||||
if (!$process.CloseMainWindow() -or !$process.WaitForExit(2500)) { $process.Kill(); $process.WaitForExit() }
|
||||
}
|
||||
foreach ($name in $names) {
|
||||
if ($saved.ContainsKey($name)) { $key.SetValue($name, $saved[$name][0], $saved[$name][1]) }
|
||||
else { $key.DeleteValue($name, $false) }
|
||||
}
|
||||
$key.Dispose()
|
||||
[IO.Directory]::Delete($folder, $true)
|
||||
}
|
||||
@@ -262,6 +262,33 @@ try {
|
||||
$main = Wait-Until { Find-Window 'KSwitcher.Files' $process.Id }
|
||||
$leftPanel=[SearchArrowTest]::GetDlgItem($main,102)
|
||||
$rightPanel=[SearchArrowTest]::GetDlgItem($main,103)
|
||||
# Initial directory scans repaint both panels when their results arrive.
|
||||
[void](Wait-Until {
|
||||
[SearchArrowTest]::SendText($leftPanel,0x1A2,-1,'A.txt').ToInt64() -ge 0 -and
|
||||
[SearchArrowTest]::SendText($rightPanel,0x1A2,-1,'A.txt').ToInt64() -ge 0
|
||||
})
|
||||
if (!$KeyboardCursorOnly) {
|
||||
$leftPath = [SearchArrowTest]::GetDlgItem($main,142)
|
||||
foreach ($step in @(@{ Row='[Right fixture]'; Path=$rightFixture }, @{ Row='..'; Path=$scratch })) {
|
||||
Select-Row $leftPanel $step.Row
|
||||
Start-Sleep -Milliseconds 150
|
||||
$lineCount = @(Get-Content -LiteralPath $paintTrace).Count
|
||||
Post $leftPanel 0x100 13
|
||||
[void](Wait-Until {
|
||||
$path = [Text.StringBuilder]::new(1024)
|
||||
[void][SearchArrowTest]::GetText($leftPath,0xD,$path.Capacity,$path)
|
||||
$path.ToString() -eq $step.Path
|
||||
})
|
||||
[void](Wait-Until {
|
||||
$highlight = Read-PanelHighlights $paintTrace $lineCount
|
||||
@($highlight.Keys -like '0/*').Count -gt 0
|
||||
})
|
||||
Start-Sleep -Milliseconds 150
|
||||
$draws = (Read-PanelHighlights $paintTrace $lineCount).Keys
|
||||
if ($draws -like '1/*') { throw "Opening $($step.Row) repainted rows in the other panel." }
|
||||
}
|
||||
Write-Output 'Verified folder navigation repaints only the panel that changes directories.'
|
||||
}
|
||||
$clicks=if(!$KeyboardCursorOnly){
|
||||
@(@{Panel=$leftPanel; Index=0},@{Panel=$rightPanel; Index=1},@{Panel=$rightPanel; Index=1})
|
||||
}
|
||||
@@ -319,22 +346,7 @@ try {
|
||||
Post $commandMenu 0x100 27
|
||||
[void](Wait-Until { ![SearchArrowTest]::IsWindowVisible($commandMenu) })
|
||||
Write-Output 'Verified Commands grouping, arrow navigation, and inert separators.'
|
||||
$panel = Wait-Until { $handle = [SearchArrowTest]::GetDlgItem($main,102); if ($handle -ne [IntPtr]::Zero) { $handle } }
|
||||
$pathControl = [SearchArrowTest]::GetDlgItem($main,142)
|
||||
$pathText = [Text.StringBuilder]::new(1024)
|
||||
[void][SearchArrowTest]::GetText($pathControl,0xD,$pathText.Capacity,$pathText)
|
||||
$path=$pathText.ToString()
|
||||
if ([IO.Path]::GetPathRoot($path) -ne [IO.Path]::GetPathRoot($scratch)) {
|
||||
throw 'Select a local left-panel folder on the test executable drive before running this interactive test.'
|
||||
}
|
||||
foreach ($component in $path.Substring(3).Split('\',[System.StringSplitOptions]::RemoveEmptyEntries)) {
|
||||
Select-Row $panel '..'
|
||||
[void][SearchArrowTest]::Send($panel,0x100,13,0)
|
||||
}
|
||||
foreach ($component in $scratch.Substring(3).Split('\')) {
|
||||
Select-Row $panel "[$component]"
|
||||
[void][SearchArrowTest]::Send($panel,0x100,13,0)
|
||||
}
|
||||
$panel = $leftPanel
|
||||
$fixtureRow=[SearchArrowTest]::SendText($panel,0x1A2,-1,([IO.Path]::GetFileName($fixture))).ToInt32()
|
||||
Click-PanelRow $panel $fixtureRow
|
||||
[void](Wait-Until { [SearchArrowTest]::Send($panel,0x188,0,0).ToInt32() -eq $fixtureRow })
|
||||
@@ -421,10 +433,10 @@ try {
|
||||
if (!(Test-Path -LiteralPath (Join-Path $scratch $newFolder) -PathType Container)) {
|
||||
throw 'F7 did not create the folder in the active panel.'
|
||||
}
|
||||
$newRow=[SearchArrowTest]::SendText($panel,0x1A2,-1,"[$newFolder]")
|
||||
if ($newRow.ToInt64() -lt 0 -or [SearchArrowTest]::Send($panel,0x188,0,0) -ne $newRow) {
|
||||
throw 'F7 did not select the new folder.'
|
||||
}
|
||||
[void](Wait-Until {
|
||||
$newRow=[SearchArrowTest]::SendText($panel,0x1A2,-1,"[$newFolder]")
|
||||
$newRow.ToInt64() -ge 0 -and [SearchArrowTest]::Send($panel,0x188,0,0) -eq $newRow
|
||||
})
|
||||
Post $main 0x111 115
|
||||
$makeDialog=Wait-Until { Find-Window '#32770' $process.Id 361 }
|
||||
$nameField=[SearchArrowTest]::GetDlgItem($makeDialog,361)
|
||||
@@ -526,6 +538,10 @@ try {
|
||||
!(Test-Path -LiteralPath (Join-Path $linkPath 'link-target.txt') -PathType Leaf)) {
|
||||
throw "F7 did not create a $expected pointing to Alpha."
|
||||
}
|
||||
[void](Wait-Until {
|
||||
$linkRow = [SearchArrowTest]::SendText($panel,0x1A2,-1,"[$linkName]")
|
||||
$linkRow.ToInt64() -ge 0 -and [SearchArrowTest]::Send($panel,0x188,0,0) -eq $linkRow
|
||||
})
|
||||
}
|
||||
Write-Output 'Verified F7 history, quoted batch names, and directory link handling.'
|
||||
Select-Row $panel ([IO.Path]::GetFileName($fixture))
|
||||
@@ -649,6 +665,7 @@ try {
|
||||
} finally { $bitmap.Dispose() }
|
||||
}
|
||||
|
||||
Select-Row $panel ([IO.Path]::GetFileName($fixture))
|
||||
Post $panel 0x100 0x73
|
||||
$editor=Wait-Until { Find-Window 'KSwitcher.Files.Text' $process.Id }
|
||||
$firstControl=[SearchArrowTest]::FindWindowEx($editor,0,'Scintilla',[System.Management.Automation.Language.NullString]::Value)
|
||||
@@ -684,8 +701,8 @@ try {
|
||||
if ([SearchArrowTest]::GetWindow($otherEditor,4) -ne [IntPtr]::Zero) { throw 'The second editor is owned.' }
|
||||
$editorIdentity=[SearchArrowTest]::TaskbarIdentity($editor)
|
||||
$otherIdentity=[SearchArrowTest]::TaskbarIdentity($otherEditor)
|
||||
if (!$editorIdentity -or !$otherIdentity -or $editorIdentity -eq $otherIdentity) {
|
||||
throw 'Editor windows do not have distinct Windows taskbar identities.'
|
||||
if ($editorIdentity -cne 'HrynCo.KSwitcher.Files.Editor' -or $otherIdentity -cne $editorIdentity) {
|
||||
throw 'Both editor windows must use the Editor group on the Windows taskbar.'
|
||||
}
|
||||
Post $otherEditor 0x10 0
|
||||
[void](Wait-Until { ![SearchArrowTest]::IsWindow($otherEditor) })
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "lan.h"
|
||||
#include "lan_pairing.h"
|
||||
#include "lan_wake.h"
|
||||
#include <iostream>
|
||||
#include <tlhelp32.h>
|
||||
|
||||
@@ -29,6 +30,15 @@ int main(int argc,char **argv)
|
||||
check(identifier(randomHex(16)),"cryptographic instance ID");
|
||||
check(mac("key","The quick brown fox jumps over the lazy dog")=="f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8", "HMAC SHA256 known vector");
|
||||
check(equal("abc","abc")&&!equal("abc","abd")&&!equal("abc","ab"),"proof comparison");
|
||||
const auto magic=wakePacket("02468ace1357");
|
||||
const std::array<unsigned char,6> hardwareAddress{0x02,0x46,0x8a,0xce,0x13,0x57};
|
||||
check(magic && std::all_of(magic->begin(),magic->begin()+6,[](auto byte){return byte==0xff;}),
|
||||
"Wake-on-LAN synchronization bytes");
|
||||
for(size_t repeat=0;repeat<16;++repeat)
|
||||
check(std::equal(hardwareAddress.begin(),hardwareAddress.end(),magic->begin()+6*(repeat+1)),
|
||||
"Wake-on-LAN repeats the target MAC address");
|
||||
check(!wakePacket("ffffffffffff") && !wakePacket("000000000000") &&
|
||||
!wakePacket("023456789abx") && !wakePacket("023456789ab"),"invalid Wake-on-LAN addresses rejected");
|
||||
Pairing left(a,b,code,100),right(b,a,code,100),wrong(b,a,std::string(32,'f'),100);
|
||||
check(wrong.receive(left.offer(),101).empty(),"different code cannot acknowledge");
|
||||
auto forged=left.offer();forged["id"]=c;
|
||||
@@ -118,6 +128,19 @@ int main(int argc,char **argv)
|
||||
check(request(restored,{{"action","status"}})["peers"].empty(),"forget removes offline pair");
|
||||
check(!request(restored,{{"action","status"}}).at("shareInput").get<bool>(),"forgetting the input peer revokes persisted input permission");
|
||||
}
|
||||
{
|
||||
const auto folder=root/L"wake";
|
||||
std::filesystem::create_directory(folder);
|
||||
const auto saved=Json{{"version",1},{"id",a},{"enabled",true},{"trusted",{
|
||||
{b,{{"name","Wake peer"},{"key",left.derived},{"wakeMac","02468ace1357"}}},
|
||||
{c,{{"name","Legacy peer"},{"key",left.derived}}}}}}.dump();
|
||||
atomicWrite(folder/L"lan-pairing.bin",protect(Bytes(saved.begin(),saved.end())));
|
||||
LanService restored(folder);
|
||||
const auto peers=request(restored,{{"action","filesPeers"}}).at("peers");
|
||||
check(peers.size()==2 && peers[0].at("id")==b && peers[0].at("address")=="" &&
|
||||
peers[1].at("id")==c,"offline PCs remain selectable in Files with or without a saved MAC address");
|
||||
check(peers.dump().find("02468ace1357")==std::string::npos,"Files snapshot omits the stored MAC address");
|
||||
}
|
||||
if(argc>1&&std::string(argv[1])=="--network")
|
||||
{
|
||||
auto saved=Json::parse(unprotect(readFile(root/L"lan-pairing.bin",256*1024)));
|
||||
|
||||
+26
-1
@@ -399,6 +399,25 @@ int main(int argc, char **argv)
|
||||
require(!supplemental.suggest(L"релызик ", 1, layouts, options),
|
||||
"never-correct list takes precedence over personal word");
|
||||
options.autoNever.clear();
|
||||
options.autoWords[L"en"] = {L"test-mt", L"dev-mt"};
|
||||
auto hyphenated = supplemental.suggest(L"Еуые-ье ", 1, layouts, options);
|
||||
require(hyphenated && hyphenated->text == L"Test-mt " && hyphenated->target == 0,
|
||||
"hyphenated personal word corrects from the wrong layout");
|
||||
options.autoMinLength = 2;
|
||||
require(!supplemental.suggest(L"ЙФ ", 2, layouts, options),
|
||||
"uppercase layout correction requires a personal dictionary entry");
|
||||
options.autoWords[L"en"].push_back(L"qa");
|
||||
auto acronym = supplemental.suggest(L"(ЙФ)! ", 2, layouts, options);
|
||||
require(acronym && acronym->text == L"(QA)! " && acronym->target == 0,
|
||||
"uppercase personal acronym corrects without changing case or punctuation");
|
||||
require(!supplemental.suggest(L"йФ ", 2, layouts, options),
|
||||
"mixed-case personal words remain protected");
|
||||
auto uppercaseHyphenated = supplemental.suggest(L"ЕУЫЕ-ЬЕ ", 1, layouts, options);
|
||||
require(uppercaseHyphenated && uppercaseHyphenated->text == L"TEST-MT ",
|
||||
"uppercase hyphenated personal words correct without changing case");
|
||||
options.autoMinLength = 3;
|
||||
require(!supplemental.suggest(L"ЙФ ", 2, layouts, options),
|
||||
"uppercase personal words respect minimum length");
|
||||
options.autoWords[L"uk"].push_back(L"робить");
|
||||
auto commaWord = supplemental.suggest(L"hj,bnm ", 0, layouts, options);
|
||||
require(commaWord && commaWord->text == L"робить " && commaWord->target == 2,
|
||||
@@ -739,7 +758,7 @@ int main(int argc, char **argv)
|
||||
settings.autoPrefixChars = L"(#";
|
||||
settings.autoSuffixChars = L");%";
|
||||
settings.autoNever = {L"myWord"};
|
||||
settings.autoWords = {{L"uk", {L"релізик"}}, {L"en", {L"kswitcher"}}};
|
||||
settings.autoWords = {{L"uk", {L"релізик"}}, {L"en", {L"kswitcher", L"test-mt", L"dev-mt"}}};
|
||||
settings.autoExcluded = {L"Code.exe"};
|
||||
settings.cycle = {L"en", L"uk"};
|
||||
settings.snippets = {{L";address", L"Line 1\r\n{cursor}Line 2"}};
|
||||
@@ -765,6 +784,12 @@ int main(int argc, char **argv)
|
||||
auto invalidWords = settings;
|
||||
invalidWords.autoWords[L"uk"] = {L"hello"};
|
||||
rejects([&] { ks::validateSettings(invalidWords); }, "personal dictionary rejects wrong language letters");
|
||||
for (const auto *word : {L"-test", L"test-", L"test--mt", L"test-і"})
|
||||
{
|
||||
invalidWords = settings;
|
||||
invalidWords.autoWords[L"en"] = {word};
|
||||
rejects([&] { ks::validateSettings(invalidWords); }, "personal dictionary rejects malformed hyphenated words");
|
||||
}
|
||||
require(ks::encodeSettings(ks::decodeSettings(ks::encodeSettings(settings), {})) == ks::encodeSettings(settings),
|
||||
"configurator snapshot survives serialization without changing the concurrency token");
|
||||
rejects([&] { ks::decodeSettings(ks::Bytes{'{', '}'}, {}); },
|
||||
|
||||
+45
-4
@@ -1,8 +1,50 @@
|
||||
"""Regenerate the native multi-resolution icon (development only; requires Pillow)."""
|
||||
"""Regenerate the native multi-resolution icons (development only; requires Pillow)."""
|
||||
from argparse import ArgumentParser
|
||||
from pathlib import Path
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
root = Path(__file__).resolve().parents[1] / 'resources'
|
||||
icon_sizes = [(size, size) for size in (16, 20, 24, 32, 40, 48, 64, 128, 256)]
|
||||
|
||||
|
||||
def draw_files_icon(size):
|
||||
image = Image.new('RGBA', (size, size))
|
||||
draw = ImageDraw.Draw(image)
|
||||
|
||||
def block(left, top, right, bottom, color):
|
||||
scale = size / 32
|
||||
draw.rectangle((round(left * scale), round(top * scale),
|
||||
round(right * scale) - 1, round(bottom * scale) - 1), fill=color)
|
||||
|
||||
# Draw each size on its own pixel grid so the pane divider stays sharp.
|
||||
frame = '#3DDDEB'
|
||||
panel = '#101E89'
|
||||
block(2, 2, 30, 30, '#10163D')
|
||||
block(2, 2, 30, 26, frame)
|
||||
block(4, 4, 28, 24, panel)
|
||||
divider = max(1, round(size / 16))
|
||||
center = size // 2 - divider // 2
|
||||
draw.rectangle((center, round(size / 8), center + divider - 1, round(size * 3 / 4) - 1), fill=frame)
|
||||
block(6, 6, 12, 8, '#FFE368')
|
||||
block(19, 6, 25, 8, '#FFE368')
|
||||
for y in (10, 18, 22):
|
||||
block(6, y, 12, y + 2, frame)
|
||||
for y, end in ((10, 26), (14, 24), (18, 26)):
|
||||
block(19, y, end, y + 2, frame)
|
||||
block(4, 14, 15, 16, '#5EEAD4')
|
||||
for left in (4, 10, 16, 22):
|
||||
block(left, 28, left + 4, 30, '#1AA3AD')
|
||||
return image
|
||||
|
||||
|
||||
parser = ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--files-only', action='store_true', help='Regenerate only the main Files icon.')
|
||||
args = parser.parse_args()
|
||||
frames = [draw_files_icon(size) for size, _ in icon_sizes]
|
||||
frames[-1].save(root / 'kswitcher-files.ico', sizes=icon_sizes, append_images=frames[:-1])
|
||||
if args.files_only:
|
||||
raise SystemExit
|
||||
|
||||
# Geometric K: white stem/upper arm, mint lower arm on an indigo keycap.
|
||||
polygons = [('#FFFFFF', [(8, 7), (12, 7), (12, 25), (8, 25)]),
|
||||
('#FFFFFF', [(11, 15), (22, 6), (25, 9), (14, 18)]),
|
||||
@@ -20,7 +62,7 @@ for color, points in polygons:
|
||||
draw.polygon([(x*scale,y*scale) for x,y in points], fill=color)
|
||||
im = im.resize((256,256),Image.Resampling.LANCZOS)
|
||||
im.save(root / 'kswitcher.png')
|
||||
im.save(root / 'kswitcher.ico', sizes=[(s,s) for s in (16,20,24,32,40,48,64,128,256)])
|
||||
im.save(root / 'kswitcher.ico', sizes=icon_sizes)
|
||||
|
||||
for mode, color in [('editor', '#4F46E5'), ('viewer', '#087C73')]:
|
||||
image = Image.new('RGBA', (32*scale, 32*scale))
|
||||
@@ -35,5 +77,4 @@ for mode, color in [('editor', '#4F46E5'), ('viewer', '#087C73')]:
|
||||
[(5, 16), (8, 12), (12, 9), (16, 8), (20, 9), (24, 12),
|
||||
(27, 16), (24, 20), (20, 23), (16, 24), (12, 23), (8, 20)]], fill='white')
|
||||
draw.ellipse((12*scale, 12*scale, 20*scale, 20*scale), fill=color)
|
||||
image.resize((256, 256), Image.Resampling.LANCZOS).save(root / f'kswitcher-files-{mode}.ico',
|
||||
sizes=[(s, s) for s in (16, 20, 24, 32, 40, 48, 64, 128, 256)])
|
||||
image.resize((256, 256), Image.Resampling.LANCZOS).save(root / f'kswitcher-files-{mode}.ico', sizes=icon_sizes)
|
||||
@@ -0,0 +1,159 @@
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$DocumentationCheckout,
|
||||
[string]$Output = "$PSScriptRoot/../src/files_windows_command_catalog.h"
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$docs = Join-Path $DocumentationCheckout 'WindowsServerDocs/administration/windows-commands'
|
||||
$revision = git -C $DocumentationCheckout rev-parse HEAD
|
||||
if ($LASTEXITCODE) { throw 'Could not determine the documentation revision.' }
|
||||
$index = Get-Content -LiteralPath (Join-Path $docs 'windows-commands.md') -Raw
|
||||
$entries = @{}
|
||||
$articles = @{}
|
||||
|
||||
function Add-Entry([string]$Name) {
|
||||
if (!$entries.ContainsKey($Name)) {
|
||||
$entries[$Name] = [Collections.Generic.SortedSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
|
||||
}
|
||||
}
|
||||
|
||||
function Add-CommandPath([string]$Name, [string]$Article) {
|
||||
Add-Entry $Name
|
||||
if (!$articles.ContainsKey($Name)) { $articles[$Name] = $Article }
|
||||
$words = $Name.Split(' ')
|
||||
for ($i = 1; $i -lt $words.Count; ++$i) {
|
||||
$parent = $words[0..($i - 1)] -join ' '
|
||||
Add-Entry $parent
|
||||
[void]$entries[$parent].Add($words[$i])
|
||||
}
|
||||
}
|
||||
|
||||
function Add-Options([string]$Name, [string]$Field) {
|
||||
$field = $Field -replace '<[^<>\r\n]*>', ''
|
||||
foreach ($option in [regex]::Matches($field, $switch)) {
|
||||
[void]$entries[$Name].Add($option.Groups['flag'].Value)
|
||||
}
|
||||
}
|
||||
|
||||
# Only extract literal command names and options. Ignore prose, examples and placeholders.
|
||||
$links = [regex]::Matches($index, '(?m)^\s*- \[`(?<name>[\w.-]+(?: [\w.-]+)*)`\]\((?:\./)?(?<file>[\w.-]+\.md)\)')
|
||||
$switch = '(?i)(?:^|[\s\[\{|,`*])(?<flag>[-/+][a-z0-9?][a-z0-9?-]*(?::[a-z0-9]+|[:=])?|[a-z][a-z0-9-]*=)(?=$|[\s\[\]{}|,<>=)`*])'
|
||||
$documents = @{}
|
||||
foreach ($link in $links) {
|
||||
$name = ($link.Groups['name'].Value.ToLowerInvariant() -replace '\.exe(?= |$)', '')
|
||||
$documents[$name] = $link.Groups['file'].Value
|
||||
}
|
||||
foreach ($name in @($documents.Keys)) {
|
||||
if ($name.Contains(' ')) { continue }
|
||||
$file = Join-Path $docs $documents[$name]
|
||||
if (!(Test-Path -LiteralPath $file)) { continue }
|
||||
$text = Get-Content -LiteralPath $file -Raw
|
||||
foreach ($link in [regex]::Matches($text, '\[(?<label>[\w./ -]+)\]\((?:\./)?(?<file>[\w.-]+\.md)\)')) {
|
||||
$childFile = $link.Groups['file'].Value
|
||||
$label = $link.Groups['label'].Value.ToLowerInvariant()
|
||||
if (!$childFile.StartsWith($name + '-') -or !$label.StartsWith($name + ' ')) { continue }
|
||||
$childPath = Join-Path $docs $childFile
|
||||
if (!(Test-Path -LiteralPath $childPath)) { continue }
|
||||
$firstArgument = [regex]::Match((Get-Content -LiteralPath $childPath -Raw),
|
||||
'(?m)^' + [regex]::Escape($name) + '(?:\.exe)?\s+\[?(?<operation>/[\w-]+)(?=[\]\s]|$)')
|
||||
if ($firstArgument.Success -and $label -eq ($name + ' ' + $firstArgument.Groups['operation'].Value.TrimStart('/'))) {
|
||||
$label = $name + ' ' + $firstArgument.Groups['operation'].Value
|
||||
}
|
||||
if (!$documents.ContainsKey($label)) { $documents[$label] = $childFile }
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($name in $documents.Keys) {
|
||||
$article = Join-Path $docs $documents[$name]
|
||||
if (!(Test-Path -LiteralPath $article)) { continue }
|
||||
$text = Get-Content -LiteralPath $article -Raw
|
||||
$slug = [IO.Path]::GetFileNameWithoutExtension($article)
|
||||
Add-CommandPath $name $slug
|
||||
$articles[$name] = $slug
|
||||
$syntax = [regex]::Matches($text, '(?ims)^(?:#{2,6}[^\r\n]*\b)?syntax[ \t]*\r?\n(?<body>.*?)(?=^#{1,6} |\z)')
|
||||
$hasChildren = $false
|
||||
$root = $name.Split(' ')[0]
|
||||
$rootPattern = '^\s*' + [regex]::Escape($root) + '(?:\.exe)?(?=\s|$)\s*'
|
||||
$blocks = @(
|
||||
foreach ($section in $syntax) {
|
||||
[regex]::Matches($section.Groups['body'].Value, '(?ms)^```[^\r\n]*\r?\n(?<code>.*?)^```') |
|
||||
ForEach-Object { $_.Groups['code'].Value }
|
||||
}
|
||||
)
|
||||
foreach ($block in $blocks) {
|
||||
if ($block -match ($rootPattern + '\[\{')) {
|
||||
$operations = [regex]::Matches($block,
|
||||
'(?is)\[\{\s*(?<names>[a-z0-9-]+(?:\s*\|\s*[a-z0-9-]+)+)\s*\}(?<options>.*?)(?=\[\{|\z)')
|
||||
foreach ($operation in $operations) {
|
||||
foreach ($operationName in ($operation.Groups['names'].Value -split '\s*\|\s*')) {
|
||||
$context = $name + ' ' + $operationName.ToLowerInvariant()
|
||||
Add-CommandPath $context $slug
|
||||
Add-Options $context $operation.Groups['options'].Value
|
||||
$hasChildren = $true
|
||||
}
|
||||
}
|
||||
if ($operations.Count) { continue }
|
||||
}
|
||||
$command = $name
|
||||
foreach ($line in ($block -split '\r?\n')) {
|
||||
if ($line -match $rootPattern) {
|
||||
$tail = $line -replace $rootPattern, ''
|
||||
$command = $root
|
||||
while ($tail -match '^\[?(?<word>[a-z0-9][a-z0-9-]*)\]?(?=\s|$)(?!\s*\|)\s*') {
|
||||
$command += ' ' + $Matches.word.ToLowerInvariant()
|
||||
$tail = $tail.Substring($Matches[0].Length)
|
||||
}
|
||||
if ($command.Length -lt $name.Length) {
|
||||
$command = $name
|
||||
$operation = $name.Substring($root.Length).Trim()
|
||||
if ($operation.StartsWith('/')) {
|
||||
$tail = $tail -replace ('^\[?' + [regex]::Escape($operation) + '\]?(?=\s|$)\s*'), ''
|
||||
}
|
||||
}
|
||||
Add-CommandPath $command $slug
|
||||
if ($command.StartsWith($name + ' ')) { $hasChildren = $true }
|
||||
if ($tail -match '^[\[{]+\s*(?<choices>[a-z0-9?-]+(?:\s*\|\s*[a-z0-9?-]+)+)\s*[\]}]') {
|
||||
foreach ($choice in ($Matches.choices -split '\s*\|\s*')) {
|
||||
[void]$entries[$command].Add($choice)
|
||||
}
|
||||
$hasChildren = $true
|
||||
}
|
||||
Add-Options $command $tail
|
||||
} else {
|
||||
Add-Options $command $line
|
||||
}
|
||||
foreach ($choice in [regex]::Matches($line, '(?<flag>[/\-][a-z][a-z0-9-]*)\s+\{(?<values>[a-z0-9_-]+(?:\s*\|\s*[a-z0-9_-]+)+)\}', 'IgnoreCase')) {
|
||||
$context = $command + ' ' + $choice.Groups['flag'].Value.ToLowerInvariant()
|
||||
Add-CommandPath $context $slug
|
||||
foreach ($value in ($choice.Groups['values'].Value -split '\s*\|\s*')) {
|
||||
[void]$entries[$context].Add($value)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!$hasChildren) {
|
||||
foreach ($parameter in [regex]::Matches($text, '(?m)^\|\s*(?<value>[^|\r\n]+)\|')) {
|
||||
$field = $parameter.Groups['value'].Value
|
||||
if ($name.Contains(' /') -and $field.Trim() -eq $name.Split(' ')[-1]) { continue }
|
||||
Add-Options $name $field
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[string[]]$names = $entries.Keys
|
||||
[Array]::Sort($names, [StringComparer]::Ordinal)
|
||||
$lines = @(
|
||||
'#pragma once'
|
||||
'#include <string_view>'
|
||||
''
|
||||
'namespace ks::files'
|
||||
'{'
|
||||
'// Generated by tools/generate-windows-command-completion.ps1 from Microsoft Learn Windows Commands.'
|
||||
"// https://github.com/MicrosoftDocs/windowsserverdocs/tree/$revision/WindowsServerDocs/administration/windows-commands"
|
||||
'inline constexpr std::string_view windowsCommandCatalog[] = {'
|
||||
foreach ($name in $names) {
|
||||
' R"catalog(' + $name + "`t" + ($entries[$name] -join ' ') + "`t" + $articles[$name] + ')catalog",'
|
||||
}
|
||||
'};'
|
||||
'}'
|
||||
)
|
||||
$lines | Set-Content -LiteralPath $Output -Encoding ascii
|
||||
Reference in new issue
Block a user