Compare commits

...
22 Commits
Author SHA1 Message Date
agrynco 524a2d4329 Release KSwitcher v0.6.116 (#62)
Show folder reading progress and allow partial results. Improve terminal file-open output and history.
2026-11-17 20:27:27 +02:00
agrynco 5bca97f864 Record the v0.6.116 package manifest and checksum 2026-11-17 20:26:36 +02:00
agrynco 0d714147ea Prepare KSwitcher v0.6.116 with cancellable folder scans 2026-11-17 20:26:09 +02:00
agrynco a0aeb62270 Release KSwitcher v0.6.115 (#61)
Add Shift+F4, prevent editor flicker, and record file launches as short start commands.
2026-11-17 17:30:07 +02:00
agrynco 4be9b24c4b Record the v0.6.115 package manifest and checksum 2026-11-17 17:29:31 +02:00
agrynco 9c30dd91b4 Prepare KSwitcher v0.6.115 with new files and concise open history 2026-11-17 17:27:08 +02:00
agrynco 5ba51ebb00 Release KSwitcher v0.6.114 (#60)
Move the active pane highlight directly to the clicked row.
2026-11-17 16:35:49 +02:00
agrynco 2bc6eb60c9 Record the v0.6.114 package manifest and checksum 2026-11-17 16:35:40 +02:00
agrynco 9c1badcb45 Prepare KSwitcher v0.6.114 with direct panel cursor highlighting 2026-11-17 16:30:18 +02:00
agrynco 9dcc20673a Release KSwitcher v0.6.113 (#59)
Prevent the terminal startup flash and stabilize the clipboard regression test.
2026-11-17 16:14:27 +02:00
agrynco ec4079b346 Record the v0.6.113 package manifest and checksum 2026-11-17 16:13:36 +02:00
agrynco 41cef4d4f3 Prepare KSwitcher v0.6.113 with a dark terminal from startup 2026-11-17 16:11:41 +02:00
agrynco b53b5715ab Release KSwitcher v0.6.112 (#58)
Add backward Ctrl+Shift+Tab cycling in Files, Editor and Viewer.
2026-11-17 15:45:25 +02:00
agrynco 01f44d22b5 Record the v0.6.112 package manifest and checksum 2026-11-17 15:44:36 +02:00
agrynco c78090f7d4 Prepare KSwitcher v0.6.112 with reverse Files window cycling 2026-11-17 15:42:44 +02:00
agrynco 0d797c4f35 Release KSwitcher v0.6.111 (#57)
Ship faster Files folder navigation, panel shortcuts, and Far-style scrollbars.
2026-11-17 15:35:12 +02:00
agrynco b6eaa2c85d Use stripped binaries in the v0.6.111 portable archive 2026-11-17 15:30:50 +02:00
agrynco 72024c3385 Record the v0.6.111 package manifest and legacy upgrade instructions 2026-11-17 15:29:03 +02:00
agrynco d60ef626f0 Prepare KSwitcher v0.6.111 with Files navigation and scrollbars 2026-11-17 15:23:22 +02:00
agrynco e144cd6607 Release KSwitcher v0.6.110 (#56)
Fix unrelated panel repaint and preserve uppercase personal dictionary corrections.
2026-11-17 14:16:03 +02:00
agrynco 05a3f7a8f4 Record the package manifest for KSwitcher v0.6.110 2026-11-17 14:15:41 +02:00
agrynco 12b8f5090c Release KSwitcher v0.6.110 with panel repaint and uppercase correction fixes
Refresh only the affected panel after folder navigation. Preserve uppercase when the target is in the personal dictionary.
2026-11-17 14:10:59 +02:00
33 changed files with 1840 additions and 409 deletions

No files matched your search

+1 -1
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.6.109 LANGUAGES CXX RC)
project(KSwitcher VERSION 0.6.116 LANGUAGES CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
+33 -5
View File
@@ -19,6 +19,10 @@ Far Manager є зразком для оформлення файлового м
не займають місця. Перед завершенням змін перевір коротке повідомлення й
повідомлення з кількома рядками, включно з відступами до рамки та кнопок.
Смуга прокрутки з’являється, лише коли текст не вміщується в доступну висоту.
Панелі, списки попапів і довгі повідомлення використовують вузьку смугу
прокрутки зі стрілками вгорі й унизу та крапковою доріжкою. Відтінки доріжки
й повзунка залежать від фону, на якому вони малюються. Повзунок світліший
за доріжку й показує положення та розмір видимої частини списку.
Оформлення, кнопки й необов’язковий прапорець задаються параметрами шаблону.
Підтвердження гібернації та віддаленого оновлення мають червоне оформлення
Warning і початковий фокус на No.
@@ -33,17 +37,26 @@ Warning і початковий фокус на No.
окремим процесом. BAT і CMD виконуються в поточній сесії вбудованого
термінала, а їхній вивід з’являється під панелями. Щоб відкрити файл із
панелі LAN, спочатку скопіюй його до локальної папки.
Після успішного відкриття локального файла через Windows його шлях
з’являється у виводі термінала й списку історії. Коли термінал неактивний,
його курсор приховано. При виборі
з історії у командний рядок підставляється команда, яка повторює відкриття.
- Коли командний рядок порожній, Shift+Enter відкриває поточний локальний
елемент через Windows.
Папка відкривається у Провіднику, файл виконує свою стандартну дію Windows.
- У головному вікні клавіатурний фокус залишається в командному рядку.
Tab перемикає активну панель, а клік вибирає рядок.
Tab без модифікаторів перемикає активну панель, а клік вибирає рядок.
Ctrl+U міняє видимі панелі місцями разом із їхніми папками, режимами,
курсорами й позначками. Активна панель залишається активною на новому боці.
Page Up і Page Down пересувають курсор у панелі. Стрілки вгору й вниз
керують панеллю, коли список підказок закритий.
Стрілки вліво й вправо переходять до першого й останнього рядків, коли
командний рядок порожній.
Клік оновлює підсвічування рядків курсора без перемальовування всієї панелі.
При кліку в іншу панель курсор відразу з’являється на вибраному рядку.
Попередній рядок цієї панелі оновлюється лише тоді, коли для неактивного
курсора він мав інше оформлення.
Меню й діалоги тимчасово приймають фокус. Ctrl+V і Shift+Insert вставляють
текст із буфера обміну в позицію курсора або замінюють виділення.
Enter виконує введену команду, якщо підказку не вибрано. Shift+Enter
@@ -52,6 +65,8 @@ Warning і початковий фокус на No.
Enter передає порожній рядок у термінал.
Якщо фокус у виводі термінала, Enter і Shift+Enter повертають його до
командного рядка й виконують відповідну дію за тими самими правилами.
Під час запуску термінала область виводу має темне тло, поки WebView2
готує сторінку.
Промпт і текст команди вирівняні по спільній базовій лінії.
- Під час набору локальної команди над полем з’являються підказки PowerShell.
Автодоповнення працює з відкритими й прихованими панелями (Ctrl+O).
@@ -125,9 +140,16 @@ Warning і початковий фокус на No.
лише до шляхів із пробілами. Для `..` вставляється шлях батьківської папки.
- Ctrl+Enter вставляє лише назву файла або папки під курсором активної панелі
за тими ж правилами вставлення й лапок. Рядок `..` пропускається.
- Локальні й LAN-каталоги скануються у фоновому потоці. Під час переходу
активна панель показує «Loading folder…» і зберігає попередній список до
завершення сканування. Якщо надійшов новіший запит, результат попереднього
- Локальні й LAN-каталоги скануються у фоновому потоці. Рядок стану активної
панелі показує «Reading» з лічильником прочитаних файлів і папок та
підказкою [Esc].
До завершення читання панель зберігає попередній список. Escape зупиняє
сканування активної панелі й відкриває прочитану частину папки. Якщо
папку ще не вдалося відкрити, попередній список залишається. Ctrl+R
повторює сканування, щоб отримати повний список. Після переходу
оновлюються шлях і список цієї панелі та командний рядок. Сусідня
панель не перемальовується через цей перехід.
Якщо надійшов новіший запит, результат попереднього
сканування пропускається. Після підтвердження UAC очікування списку
від підвищеного процесу теж відбувається у фоні.
- Ctrl+R перечитує поточну папку активної панелі. Позиція курсора й позначки
@@ -207,7 +229,13 @@ Warning і початковий фокус на No.
За наявності змін перехід у перегляд пропонує Save, Discard або Cancel.
Помилка збереження залишає відкритим редактор зі змінами.
- Ctrl+Tab циклічно перемикає фокус між Files, редакторами й переглядачами
у порядку їх відкриття.
у порядку їх відкриття. Ctrl+Shift+Tab обходить ті самі вікна у зворотному
порядку. Коли відкрито лише Files, активна панель не змінюється.
- Shift+F4 у локальній панелі відкриває Editor для наявного або нового файла.
Порожнє ім’я підставляє `New_File_<дата>_<час>.txt`. Новий файл з’являється
на диску після збереження. Esc після змін пропонує Save, Discard або Cancel.
Save для нового файла відкриває параметри імені, кодування, BOM та кінців
рядків. Скасування параметрів залишає текст у редакторі.
- F3 відкриває Markdown як форматований документ із таблицями, блоками коду,
інтерактивними чекбоксами списків і діаграмами Mermaid. Відмітки в перегляді
діють до повторного рендерингу або виходу з цього режиму. F4 відкриває текст
+13 -10
View File
@@ -148,12 +148,14 @@ updating the application. After verifying a new package, the updater closes File
screenshot editors, Settings, and bundled StayHere for that installation. Save open work before approving an update.
If settings change in the tray while the configurator is open, a conflicting Save is rejected; reopen
the configurator to load the latest settings.
Updates from v0.3.x–v0.4.1 first install the compatible **v0.4.2 bridge** through
Update in the tray menu. Select Update again to install the full current release;
manual extraction is not required. Future full releases use stable `release-vX.Y.Z`
tags, which the bridge and newer clients recognize. Older clients ignore those tags
and continue to find the bridge instead of skipping it. Versions v0.2.3 and earlier
still require the previously documented initial configurator migration.
Updates from v0.3.x–v0.4.1 go through the compatible **v0.4.2 bridge**. If tray
**Update** does not find it, download [v0.4.2](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/releases/tag/v0.4.2),
close KSwitcher and its editors, and extract the bridge ZIP into the installation
directory while keeping personal data, dictionaries, and tools. Start v0.4.2
and select **Update** to install the current full release. Full releases use
stable `release-vX.Y.Z` tags recognized by the bridge and newer clients.
Versions v0.2.3 and earlier still require the previously documented initial
configurator migration.
Modern ZIPs contain `release-files.json` (schema, version, file paths, sizes and SHA-256
hashes). The updater validates that every packaged file is declared, all hashes match,
@@ -898,8 +900,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).
@@ -995,8 +999,7 @@ Keep `v0.4.2` as the last legacy `vX.Y.Z` release. Publish full packages as
`release-vX.Y.Z` (stable, not prerelease), including `release-files.json`,
`KSwitcher-win-x64.zip` and `SHA256SUMS.txt`. Never publish a manifest package under a
legacy version tag: clients that have not installed the bridge would select it.
Keep the compatibility bridge in the first 100 releases returned by Gitea while
supporting old clients; their immutable update code only reads that page.
Legacy clients only read the first 100 releases returned by Gitea. The bridge is now outside that page. For v0.3.x–v0.4.1, follow the manual bridge installation instructions above.
### Editors that omit copied trailing spaces
+73 -1
View File
@@ -1,5 +1,77 @@
# Latest Windows release
## v0.6.116 — 2026-11-17
- Files displays a live count while reading a folder. **Esc** stops the scan and shows the entries already read. **Ctrl+R** reads the folder again. Mouse selection works beyond the first 65,536 rows.
- Files shows the path of files opened through Windows in the terminal and command history. Choosing a history entry still inserts the command that reopens the file. The embedded terminal hides its inactive cursor.
**Українською.**
- Files показує лічильник під час читання папки. **Esc** зупиняє читання й показує вже прочитані записи. **Ctrl+R** перечитує папку. Вибір мишею працює після перших 65 536 рядків.
- Files показує шлях до файла, відкритого через Windows, у терміналі й історії команд. Вибір запису історії підставляє команду для повторного відкриття. Вбудований термінал приховує курсор, коли він неактивний.
## v0.6.115 — 2026-11-17
- **Shift+F4** opens or creates a file in the active local panel. Leave the name blank for a generated `New_File_…txt` name. After editing a draft, **Esc → Save** opens options for the file name, encoding, BOM, and line endings.
- Typing updates the editor status line without repainting the menu or flashing the editor window.
- When **Enter** opens a local file through Windows, Files displays `start 'path'` in the terminal and saves it in command history.
**Українською.**
- **Shift+F4** відкриває або створює файл в активній локальній панелі. Якщо залишити ім’я порожнім, Files підставить `New_File_…txt`. Після редагування чернетки **Esc → Save** відкриває параметри імені, кодування, BOM і кінців рядків.
- Під час набору редактор оновлює рядок стану без перемальовування меню й миготіння вікна.
- Коли **Enter** відкриває локальний файл через Windows, Files показує `start 'шлях'` у терміналі й додає команду до історії.
## v0.6.114 — 2026-11-17
In KSwitcher Files, clicking a row in the inactive pane highlights that row immediately. The previous cursor row in that pane no longer flashes with the active highlight. If it had a custom unfocused cursor color, it returns directly to its normal style.
**Українською.**
У KSwitcher Files клік по рядку неактивної панелі одразу підсвічує вибраний рядок. Попередній рядок курсора цієї панелі більше не блимає активним підсвічуванням. Якщо він мав окремий колір неактивного курсора, рядок одразу повертається до звичайного оформлення.
## v0.6.113 — 2026-11-17
- KSwitcher Files keeps the terminal output area dark while WebView2 initializes. This fixes the white flash during startup.
- The terminal copy regression test checks for a new clipboard write and verifies its contents without first taking clipboard ownership.
**Українською.**
- Під час запуску термінала область виводу KSwitcher Files залишається темною, поки WebView2 готує сторінку. Це усуває білий спалах під час відкриття термінала.
- Тест копіювання з термінала перевіряє новий запис і його вміст без попереднього захоплення буфера обміну.
## v0.6.112 — 2026-11-17
In KSwitcher Files, **Ctrl+Shift+Tab** cycles backward through Files, Editor, and Viewer windows. **Ctrl+Tab** cycles forward. Both shortcuts wrap at the ends of the window list, including in the Markdown preview.
**Українською.**
У KSwitcher Files **Ctrl+Shift+Tab** обходить вікна Files, редактора й переглядача у зворотному порядку. **Ctrl+Tab** обходить їх у прямому порядку. Обидві комбінації працюють циклічно, зокрема в перегляді Markdown.
## v0.6.111 — 2026-11-17
- KSwitcher Files updates a panel as soon as its background folder scan finishes.
- **Ctrl+U** swaps the panels, keeping their folders, view modes, cursors, marked items, and active panel together. Use **Tab** by itself to switch the active panel. **Ctrl+Tab** cycles between Files, Editor, and Viewer windows.
- Panels and scrollable Files popups share a Far-style scrollbar with up and down arrows, a dotted track, and a thumb lighter than its background.
**Українською.**
- KSwitcher Files оновлює панель одразу після завершення фонового читання папки.
- **Ctrl+U** міняє панелі місцями разом із папками, режимами перегляду, курсорами й позначками. Активна панель залишається активною на новому боці. Для перемикання активної панелі натисніть **Tab** без модифікаторів. **Ctrl+Tab** перемикає вікна Files, редактора й переглядача.
- Панелі та попапи з прокруткою у Files мають спільний скролбар у стилі Far зі стрілками вгорі й унизу, крапковою доріжкою та повзунком, світлішим за фон.
## 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**.
@@ -426,7 +498,7 @@ Use **Test mouse buttons here** to check which events Windows delivers. Mouse pr
## Upgrade
Choose **Update** in the tray menu. Legacy v0.3.0–v0.4.1 clients first receive the v0.4.2 compatibility bridge, then the current full release. v0.2.3 and earlier require manual installation.
Choose **Update** in the tray menu. For v0.3.x–v0.4.1, install the [v0.4.2 bridge](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/releases/tag/v0.4.2) manually first. Close KSwitcher and its editors, extract the bridge ZIP into the installation folder while keeping personal data, dictionaries, and tools, then start v0.4.2 and choose **Update**. v0.2.3 and earlier require manual installation.
For a manual upgrade, exit KSwitcher and its configurator and screenshot editors, then extract the entire **KSwitcher-win-x64.zip** into its installation folder. Verify it with **SHA256SUMS.txt**. Keep personal data, customized dictionaries and tools. Keep the three KSwitcher executables together.
+1 -1
View File
@@ -1 +1 @@
2144021cb6ed95cdbd44ef81318136763cd756ff74a41d61586f6588c6b634db KSwitcher-win-x64.zip
5a885ca54c703dd82a5ce82b6fdbe919337f30ca08daeb6c8958f7e36832aef2 KSwitcher-win-x64.zip
+67 -67
View File
@@ -1,166 +1,166 @@
{
"schema": 1,
"version": "0.6.109",
"version": "0.6.116",
"files": [
{
"size": 2373632,
"path": "KSwitcher.exe",
"sha256": "0cf13f2d0212f803223f271ff42cab33f9968d1a6552eec063c8c86567f88883"
"sha256": "b7c7f60c0a1e598359f3bd3775fca67fa2eaf9ebcc41f96da0034b3a92687863",
"size": 2479104
},
{
"size": 2370560,
"path": "KSwitcher.Config.exe",
"sha256": "9387c07d7a4616c2c0f4ea3d38665f2da7e0dfa993228808cfeae0d334019d45"
"sha256": "96a956ab0498269244371355b1549cc89e29d5d9175e36e39d8bef8ab53f6a5f",
"size": 2458112
},
{
"size": 3350016,
"path": "KSwitcher.Screenshot.exe",
"sha256": "501d95eb6fcfe9f4cf498741950f9b8b89991c2ebb5ca986a9ecbfdf2e3dc6bb"
"sha256": "d001683200e1d86caaf96e8c37f004ab2717f8acaad8c172350581792026540d",
"size": 3060224
},
{
"size": 4208128,
"path": "KSwitcher.Files.exe",
"sha256": "05c0204e4854da7ff5b635915ea21b44c1887ff0075d72ca4da8267ef5543616"
"sha256": "cc1bea0d8d7aafe23e7a3be72177123963c7b3d250be93840850953a2aa547a6",
"size": 4232704
},
{
"size": 194912,
"path": "WebView2Loader.dll",
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
"size": 194912
},
{
"size": 1103,
"path": "terminal/addon-fit-LICENSE.txt",
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
"size": 1103
},
{
"size": 1521,
"path": "terminal/addon-fit.js",
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
"size": 1521
},
{
"size": 527,
"path": "terminal/index.html",
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
"size": 527
},
{
"size": 1073,
"path": "terminal/markdown-it-LICENSE.txt",
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473"
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
"size": 1073
},
{
"size": 100786,
"path": "terminal/markdown-it.js",
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
"size": 100786
},
{
"size": 3530,
"path": "terminal/markdown.html",
"sha256": "e5381c35fb254b558c8b869746e2e575c8ed53600611ac90597ed2dd80fa321c"
"sha256": "e5381c35fb254b558c8b869746e2e575c8ed53600611ac90597ed2dd80fa321c",
"size": 3530
},
{
"size": 14987,
"path": "terminal/markdown.js",
"sha256": "5d1e824df1c3570877e985de0cfaae3f2984ceef7fe23bf4c5ade3c890a93223"
"sha256": "55c905afaf074e3253267a7c48a5ebca14edd7f15449fd85c0a884c34da22763",
"size": 15014
},
{
"size": 1089,
"path": "terminal/mermaid-LICENSE.txt",
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80"
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
"size": 1089
},
{
"size": 5537838,
"path": "terminal/mermaid.js",
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3"
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
"size": 5537838
},
{
"size": 5033,
"path": "terminal/terminal.js",
"sha256": "0557d251962301940785690a3fc49475dd166bb7d0bd0417dc3279d1f1b3a98a"
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b",
"size": 5065
},
{
"size": 1261,
"path": "terminal/xterm-LICENSE.txt",
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
"size": 1261
},
{
"size": 7112,
"path": "terminal/xterm.css",
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
"size": 7112
},
{
"size": 488663,
"path": "terminal/xterm.js",
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
"size": 488663
},
{
"size": 4401,
"path": "LICENSE",
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
"size": 4401
},
{
"size": 1096,
"path": "json-LICENSE.txt",
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831"
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
"size": 1096
},
{
"size": 883,
"path": "files-text-license.txt",
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
"size": 883
},
{
"size": 94975,
"path": "README.md",
"sha256": "531bd264f5d145a22051ac93b48986cdee98c0df7a796474d4c90696899cb1b3"
"sha256": "ea5016c6fa29a98bf9ebf103fcf27f1be091842ad3228b167d18b053fda767d8",
"size": 95317
},
{
"size": 11577,
"path": "LAN-PREVIEW.md",
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930"
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930",
"size": 11577
},
{
"size": 732485,
"path": "dictionaries/en.txt",
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9"
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
"size": 732485
},
{
"size": 20566,
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5"
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
"size": 20566
},
{
"size": 2265,
"path": "dictionaries/README.md",
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
"size": 2265
},
{
"size": 1109134,
"path": "dictionaries/ru.txt",
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849"
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
"size": 1109134
},
{
"size": 1280,
"path": "dictionaries/sources.json",
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
"size": 1280
},
{
"size": 940799,
"path": "dictionaries/uk.txt",
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
"size": 940799
},
{
"size": 993,
"path": "tools/README.txt",
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
"size": 993
},
{
"size": 134656,
"path": "tools/StayHere.exe",
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376"
"sha256": "c893d20af87a53cad90306951b80342c553d1cb188291a0377c3f28bd014b2c0",
"size": 133120
},
{
"size": 2796,
"path": "tools/StayHere-README.md",
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
"size": 2796
}
]
],
"schema": 1
}
+3 -3
View File
@@ -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,109,0
PRODUCTVERSION 0,6,109,0
FILEVERSION 0,6,116,0
PRODUCTVERSION 0,6,116,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.109"
VALUE "FileVersion", "0.6.116"
END
END
BLOCK "VarFileInfo"
+38 -2
View File
@@ -50,16 +50,52 @@ BEGIN
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 153, 42, 60, 17
END
611 DIALOGEX 0, 0, 332, 96
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
LTEXT "&Open/create file:", 460, 14, 16, 304, 12
FAR_EDIT(461, 0, 14, 29, 304, 14)
CONTROL "", 466, "Static", NOT WS_VISIBLE, 14, 50, 1, 1
LTEXT "&Code page:", 462, 14, 53, 94, 12
COMBOBOX 463, 112, 51, 206, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
CONTROL "", 467, "Static", NOT WS_VISIBLE, 14, 72, 1, 1
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 76, 60, 16
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 170, 76, 60, 16
END
612 DIALOGEX 0, 0, 332, 184
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
LTEXT "Save file &as:", 460, 14, 16, 304, 12
FAR_EDIT(461, 0, 14, 29, 304, 14)
CONTROL "", 466, "Static", NOT WS_VISIBLE, 14, 50, 1, 1
LTEXT "&Code page:", 462, 14, 53, 94, 12
COMBOBOX 463, 112, 51, 206, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
AUTOCHECKBOX "Add signature (&BOM)", 464, 14, 66, 304, 12
CONTROL "", 468, "Static", NOT WS_VISIBLE, 14, 86, 1, 1
LTEXT "Change line breaks to:", 469, 14, 87, 304, 12
AUTORADIOBUTTON "Do &not change", 470, 14, 100, 304, 12, WS_GROUP | WS_TABSTOP
AUTORADIOBUTTON "&Windows (CR LF)", 471, 14, 112, 304, 12
AUTORADIOBUTTON "&Unix (LF)", 472, 14, 124, 304, 12
AUTORADIOBUTTON "&Mac (CR)", 473, 14, 136, 304, 12
CONTROL "", 467, "Static", NOT WS_VISIBLE | WS_GROUP, 14, 155, 1, 1
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 157, 60, 16
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 170, 157, 60, 16
END
607 DIALOGEX 0, 0, 185, 57
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
CONTROL "", 100, "Edit", ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | WS_VSCROLL, 14, 16, 157, 13
CONTROL "", 100, "Edit", ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL, 14, 16, 157, 13
AUTOCHECKBOX "&Remember for this session", 101, 14, 30, 157, 13, NOT WS_VISIBLE
CONTROL "", 102, "Static", NOT WS_VISIBLE, 14, 35, 1, 1
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 67, 38, 51, 15
CONTROL "&Yes", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 36, 38, 51, 15
CONTROL "&No", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 98, 38, 51, 15
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 129, 38, 51, 15
CONTROL "&Processes…", 103, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 14, 38, 75, 15
END
@@ -68,7 +104,7 @@ STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
LTEXT "", 430, 14, 17, 322, 20
LISTBOX 431, 14, 41, 322, 61, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
LISTBOX 431, 14, 41, 322, 61, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP
CONTROL "", 432, "Static", NOT WS_VISIBLE, 14, 108, 1, 1
CONTROL "&End process", 433, "Button", BS_OWNERDRAW | WS_TABSTOP, 56, 110, 80, 16
CONTROL "&Refresh", 434, "Button", BS_OWNERDRAW | WS_TABSTOP, 140, 110, 74, 16
+1 -1
View File
@@ -282,7 +282,7 @@ document.addEventListener('keydown', event => {
event.preventDefault();
} else if (event.ctrlKey && !event.altKey && event.key === 'Tab') {
event.preventDefault();
send('cycle');
send('cycle', {reverse: event.shiftKey});
} else if ((event.altKey && ['ArrowLeft', 'ArrowRight'].includes(event.key)) ||
['BrowserBack', 'BrowserForward'].includes(event.key)) {
event.preventDefault();
+1
View File
@@ -3,6 +3,7 @@ const terminal = new Terminal({
fontFamily: 'Consolas, monospace',
fontSize: 16,
cursorBlink: false,
cursorInactiveStyle: 'none',
disableStdin: true,
theme: { background: '#181818', foreground: '#e8e8e8' },
});
+4 -3
View File
@@ -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;
@@ -295,7 +296,7 @@ std::optional<AutoSuggestion> AutoCorrector::suggest(const std::wstring &typed,
auto letters = converted;
if (knownPersonal)
std::erase(letters, L'-');
if (!safeAutoWord(letters, settings.autoMinLength))
if (!safeAutoWord(letters, settings.autoMinLength, knownPersonal))
continue;
int rank = knownPersonal ? 1 : dictionary->second->rank(converted);
if (!rank)
+1 -1
View File
@@ -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 & = {});
+17
View File
@@ -2,6 +2,23 @@ constexpr std::array<WORD,2> defaultHistoryKeys{MAKEWORD('E',HOTKEYF_CONTROL),MA
auto commandHistoryKeys=defaultHistoryKeys;
constexpr size_t commandHistoryLimit=1000;
std::wstring commandHistoryLabel(const std::wstring &command)
{
constexpr std::wstring_view prefix=L"start '";
if(!command.starts_with(prefix) || command.size()<=prefix.size() || command.back()!=L'\'')
return command;
const std::wstring_view literal(command.data()+prefix.size(),command.size()-prefix.size()-1);
std::wstring path;
for(size_t i=0;i<literal.size();++i)
{
const auto character=literal[i];
if(character==L'\'' || character==L'\u2018' || character==L'\u2019')
if(++i==literal.size() || literal[i]!=character) return command;
path+=character;
}
return fs::path(path).is_absolute()?path:command;
}
bool validHistoryKeys(const std::array<WORD,2> &keys)
{
if(keys[0]==keys[1]) return false;
+8 -12
View File
@@ -69,7 +69,7 @@ void populateCommandHistory(HWND dialog)
{
return std::all_of(words.begin(),words.end(),[&](const auto &word){return text.find(word)!=text.npos;});
};
if(containsAll(command+L" "+entry.date))
if(containsAll(command+L" "+historyLower(commandHistoryLabel(entry.command))+L" "+entry.date))
{
matches[0].push_back(index);
continue;
@@ -91,7 +91,7 @@ void populateCommandHistory(HWND dialog)
if(first || date!=lastDate) add(date,-1);
first=false;
lastDate=date;
const auto row=add(entry.command,index);
const auto row=add(commandHistoryLabel(entry.command),index);
if(row>=0 && (words.empty() || selected==LB_ERR)) selected=row;
}
}
@@ -140,13 +140,7 @@ LRESULT CALLBACK historyListScroll(HWND list,UINT message,WPARAM wp,LPARAM lp,UI
SendMessageW(GetParent(list),WM_COMMAND,IDOK,0);
return 0;
}
if(message==LB_GETTOPINDEX || message==WM_NCDESTROY)
return DefSubclassProc(list,message,wp,lp);
const auto top=SendMessageW(list,LB_GETTOPINDEX,0,0);
const auto result=scrollList(list,message,wp,lp);
if(top!=SendMessageW(list,LB_GETTOPINDEX,0,0))
InvalidateRect(GetParent(list),nullptr,FALSE);
return result;
return DefSubclassProc(list,message,wp,lp);
}
void sizeCommandHistory(HWND dialog,HWND list)
@@ -165,8 +159,9 @@ void sizeCommandHistory(HWND dialog,HWND list)
LONG longest{};
for(const auto &entry:terminalHistory)
{
const auto label=commandHistoryLabel(entry.command);
SIZE size{};
if(GetTextExtentPoint32W(dc,entry.command.c_str(),static_cast<int>(entry.command.size()),&size))
if(GetTextExtentPoint32W(dc,label.c_str(),static_cast<int>(label.size()),&size))
longest=std::max(longest,size.cx);
}
SelectObject(dc,previous);
@@ -179,7 +174,7 @@ void sizeCommandHistory(HWND dialog,HWND list)
const int gap=MulDiv(4,dpi,96);
const int listTop=top+2*textHeight+2*gap;
const LONG desired=std::max<LONG>(MulDiv(320,dpi,96),
longest+2*cellWidth+2*historyRowInset(dpi)+GetSystemMetricsForDpi(SM_CXVSCROLL,dpi))+2*inset;
longest+2*cellWidth+2*historyRowInset(dpi)+scrollBarWidth(list))+2*inset;
const auto target=std::min(desired,area.right-area.left);
const auto rows=std::max<LRESULT>(1,SendMessageW(list,LB_GETCOUNT,0,0));
RECT listWindow{},listClient{};
@@ -198,7 +193,7 @@ void sizeCommandHistory(HWND dialog,HWND list)
};
place(GetDlgItem(dialog,historySearchLabel),top,textHeight);
place(GetDlgItem(dialog,historySearch),top+textHeight+gap,textHeight);
SetWindowPos(list,nullptr,inset,listTop,std::max(1L,target-2*inset-5),
SetWindowPos(list,nullptr,inset,listTop,std::max(1L,target-2*inset-scrollBarWidth(list)),
std::max(1L,height-listTop-inset),SWP_NOZORDER|SWP_NOACTIVATE);
GetClientRect(list,&listClient);
if(rows*textHeight<=listClient.bottom) SendMessageW(list,LB_SETTOPINDEX,0,0);
@@ -221,6 +216,7 @@ INT_PTR CALLBACK commandHistoryDialog(HWND dialog,UINT message,WPARAM wp,LPARAM
prepareCopyDialog(dialog);
const auto list=GetDlgItem(dialog,historyList);
SetWindowSubclass(list,historyListScroll,1,0);
installScrollBar(list,dialog);
SendMessageW(list,WM_SETFONT,reinterpret_cast<WPARAM>(mono),TRUE);
SendMessageW(list,LB_SETITEMHEIGHT,0,std::max(1,textHeight));
const auto search=GetDlgItem(dialog,historySearch);
+7 -3
View File
@@ -243,7 +243,8 @@ void layoutQuickFolders(HWND dialog,FolderShortcutView &view,int selection)
GetWindowRect(owner,&parent);
const auto windowWidth=std::max(px(260),static_cast<int>(parent.right-parent.left));
const auto windowHeight=std::max(px(140),static_cast<int>(parent.bottom-parent.top));
width=std::min(width,std::max(1,std::min(windowWidth,static_cast<int>(work.right-work.left))-2*inset));
width=std::min(width+scrollBarWidth(list),
std::max(1,std::min(windowWidth,static_cast<int>(work.right-work.left))-2*inset));
const auto maxRows=std::max(1,(std::min(windowHeight,static_cast<int>(work.bottom-work.top))-2*listTop)/view.rowHeight);
const auto count=static_cast<int>(SendMessageW(list,LB_GETCOUNT,0,0));
const int rows=std::min(count,maxRows);
@@ -255,7 +256,8 @@ void layoutQuickFolders(HWND dialog,FolderShortcutView &view,int selection)
const int y=std::clamp(static_cast<int>((parent.top+parent.bottom-h)/2),
static_cast<int>(work.top),std::max(static_cast<int>(work.top),static_cast<int>(work.bottom)-h));
SetWindowPos(dialog,nullptr,x,y,w,h,SWP_NOZORDER|SWP_NOACTIVATE);
SetWindowPos(list,nullptr,inset,listTop,width,listHeight,SWP_NOZORDER|SWP_NOACTIVATE);
SetWindowPos(list,nullptr,inset,listTop,std::max(1,width-scrollBarWidth(list)),listHeight,
SWP_NOZORDER|SWP_NOACTIVATE);
SendMessageW(list,LB_SETCURSEL,std::clamp(selection,0,std::max(0,count-1)),0);
InvalidateRect(dialog,nullptr,TRUE);
FilesModalDialog::refreshLayout(dialog);
@@ -278,7 +280,7 @@ LRESULT CALLBACK quickFolderKeys(HWND list,UINT message,WPARAM key,LPARAM flags,
return 0;
}
}
return scrollList(list,message,key,flags);
return DefSubclassProc(list,message,key,flags);
}
INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
@@ -291,6 +293,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
layoutQuickFolders(dialog,view,0);
const auto list=GetDlgItem(dialog,shortcutList);
SetWindowSubclass(list,quickFolderKeys,1,0);
installScrollBar(list,dialog);
SetFocus(list);
return FALSE;
}
@@ -311,6 +314,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
DeleteObject(frame);
paintDialogFrameCaptions(dc,client,bounds,L"Folder shortcuts",teal,colors[Text],mono,
view->digit<0?L"Enter Esc":quickFolderHints);
paintScrollPosition(dialog,dc,GetDlgItem(dialog,shortcutList),colors[Dialog]);
EndPaint(dialog,&ps);
return TRUE;
}
+7 -1
View File
@@ -186,6 +186,12 @@ INT_PTR CALLBACK lockProcessesDialog(HWND window,UINT message,WPARAM wp,LPARAM l
SetWindowLongPtrW(window,DWLP_USER,lp);
prepareCopyDialog(window);
for(const auto id:{430,431}) SendDlgItemMessageW(window,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
const auto list=GetDlgItem(window,431);
RECT bounds{};
GetWindowRect(list,&bounds);
SetWindowPos(list,nullptr,0,0,std::max(1L,bounds.right-bounds.left-scrollBarWidth(list)),
bounds.bottom-bounds.top,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
installScrollBar(list,window);
layoutDialogButtons(window,432,{433,434,IDOK});
SendMessageW(window,DM_SETDEFID,IDOK,0);
SetFocus(GetDlgItem(window,IDOK));
@@ -233,7 +239,7 @@ INT_PTR CALLBACK lockProcessesDialog(HWND window,UINT message,WPARAM wp,LPARAM l
}
}
if(message==WM_CLOSE) {FilesModalDialog::finish(window,IDCANCEL);return TRUE;}
return paintCopyDialog(window,message,wp,lp,L" Locking processes ",false,{432});
return paintCopyDialog(window,message,wp,lp,L" Locking processes ",false,{432},false,GetDlgItem(window,431));
}
void showLockProcesses(HWND owner,std::vector<fs::path> paths)
+630 -149
View File
File diff suppressed because it is too large. Load diff
+99
View File
@@ -0,0 +1,99 @@
#pragma once
#include <windows.h>
#include <algorithm>
namespace ks::files
{
inline int scrollBarWidth(HWND window) {return std::max(7,MulDiv(12,GetDpiForWindow(window),96));}
inline int scrollArrowHeight(RECT bounds)
{
return std::min(bounds.right-bounds.left,(bounds.bottom-bounds.top)/3);
}
struct ScrollPosition
{
int count, visible, top;
int last() const {return std::max(0,count-visible);}
RECT thumb(RECT track) const
{
const auto arrow=scrollArrowHeight(track);
track.top+=arrow;
track.bottom-=arrow;
const int height=track.bottom-track.top;
if(height<=0 || !last()) return {};
const int size=std::clamp(MulDiv(height,visible,count),std::min(height,arrow),height);
track.top+=MulDiv(std::clamp(top,0,last()),height-size,last());
track.bottom=track.top+size;
return track;
}
int click(RECT track,int y) const
{
const auto arrow=scrollArrowHeight(track);
const auto grip=thumb(track);
const int delta=y<track.top+arrow?-1:y>=track.bottom-arrow?1:
y<grip.top?-visible:y>=grip.bottom?visible:0;
return std::clamp(top+delta,0,last());
}
int drag(RECT track,int y,int offset) const
{
const auto grip=thumb(track);
const auto arrow=scrollArrowHeight(track);
const auto travel=track.bottom-track.top-2*arrow-(grip.bottom-grip.top);
return travel>0?std::clamp(MulDiv(y-track.top-arrow-offset,last(),travel),0,last()):top;
}
};
inline void paintScrollBar(HDC dc,RECT track,ScrollPosition position,COLORREF background)
{
const auto brush=static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
SetDCBrushColor(dc,background);
FillRect(dc,&track,brush);
if(!position.last()) return;
const auto lighter=[&](int divisor){return RGB(GetRValue(background)+(257-GetRValue(background))/divisor,
GetGValue(background)+(257-GetGValue(background))/divisor,
GetBValue(background)+(257-GetBValue(background))/divisor);};
const auto ink=lighter(4),dots=lighter(7);
const int height=scrollArrowHeight(track);
struct
{
BITMAPINFOHEADER header{sizeof(BITMAPINFOHEADER),4,4,1,32,BI_RGB};
DWORD pixels[16]{};
} tile;
for(int y=0;y<4;++y)
for(int x=0;x<4;++x)
{
const auto color=y%2==0 && x%2==y/2?dots:background;
// DIB pixels are stored bottom-up in BGR order.
tile.pixels[(3-y)*4+x]=RGB(GetBValue(color),GetGValue(color),GetRValue(color));
}
if(const auto pattern=CreateDIBPatternBrushPt(&tile,DIB_RGB_COLORS))
{
const RECT channel{track.left,track.top+height,track.right,track.bottom-height};
POINT origin{};
SetBrushOrgEx(dc,channel.left,channel.top,&origin);
FillRect(dc,&channel,pattern);
SetBrushOrgEx(dc,origin.x,origin.y,nullptr);
DeleteObject(pattern);
}
SetDCBrushColor(dc,ink);
const auto thumb=position.thumb(track);
FillRect(dc,&thumb,brush);
const int middle=(track.left+track.right)/2;
const int radius=std::max(0,(height-3)/2);
for(int row=0;row<=radius;++row)
{
const int y=track.top+(height-radius-1)/2+row;
const int mirrored=track.bottom-1-(y-track.top);
const RECT up{middle-row,y,middle+row+1,y+1};
const RECT down{middle-row,mirrored,middle+row+1,mirrored+1};
FillRect(dc,&up,brush);
FillRect(dc,&down,brush);
}
}
}
+1
View File
@@ -128,6 +128,7 @@ struct FileRowStyle
{
COLORREF foreground,background;
unsigned decorations{};
bool operator==(const FileRowStyle &) const = default;
};
FileRowStyle resolveFileStyle(std::wstring_view extension,bool file,bool dimmed,bool protectedRow,
COLORREF foreground,COLORREF background,const std::vector<FileStyle> &styles=fileStyles,
+35 -3
View File
@@ -3,6 +3,9 @@
#ifdef __MINGW32__
__CRT_UUID_DECL(ICoreWebView2_3, 0xA0D6DF20, 0x3B92, 0x416D, 0xAA, 0x0C, 0x43, 0x7A, 0x9C, 0x72, 0x78, 0x57)
__CRT_UUID_DECL(ICoreWebView2Controller2, 0xc979903e, 0xd4ca, 0x4228, 0x92, 0xeb, 0x47, 0xee, 0x3f, 0xa9, 0x6e, 0xab)
__CRT_UUID_DECL(ICoreWebView2ControllerOptions3, 0xb32b191a, 0x8998, 0x57ca, 0xb7, 0xcb, 0xe0, 0x46, 0x17, 0xe4, 0xce, 0x4a)
__CRT_UUID_DECL(ICoreWebView2Environment10, 0xee0eb9df, 0x6f12, 0x46ce, 0xb5, 0x3f, 0x3f, 0x47, 0xb9, 0xc9, 0x28, 0xe0)
__CRT_UUID_DECL(ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler, 0x4e8a3389, 0xc9d8, 0x4bd2, 0xb6, 0xb5, 0x12, 0x4f, 0xee, 0x6c, 0xc1, 0x4d)
__CRT_UUID_DECL(ICoreWebView2CreateCoreWebView2ControllerCompletedHandler, 0x6c4819f3, 0xc9b7, 0x4260, 0x81, 0x27, 0xc9, 0xf5, 0xbd, 0xe7, 0xf6, 0x8c)
__CRT_UUID_DECL(ICoreWebView2WebMessageReceivedEventHandler, 0x57213f19, 0x00e6, 0x49fa, 0x8e, 0x07, 0x89, 0x8e, 0xa0, 0x1e, 0xcb, 0xd2)
@@ -16,6 +19,8 @@ __CRT_UUID_DECL(ICoreWebView2AcceleratorKeyPressedEventHandler, 0xb29c7e28, 0xfa
#include <memory>
#include <utility>
inline constexpr COLORREF terminalSurface=RGB(24,24,24);
template<class Interface, class... Args>
class TerminalCallback final : public Interface
{
@@ -56,6 +61,7 @@ class FilesTerminalView
RECT bounds{};
bool ready{};
bool visible{};
bool waitForReady{};
public:
~FilesTerminalView() { close(); }
void focus()
@@ -94,9 +100,10 @@ public:
RECT current{};
if(FAILED(controller->get_Bounds(&current)) || !EqualRect(&current,&bounds))
controller->put_Bounds(bounds);
const bool showController=show && (!waitForReady || ready);
BOOL currentVisibility{};
if(FAILED(controller->get_IsVisible(&currentVisibility)) || !!currentVisibility!=show)
controller->put_IsVisible(show);
if(FAILED(controller->get_IsVisible(&currentVisibility)) || !!currentVisibility!=showController)
controller->put_IsVisible(showController);
}
void close()
{
@@ -140,6 +147,9 @@ public:
const auto uri=std::wstring(L"https://")+origin+(markdown?L"/markdown.html":L"/index.html");
const auto assets=folder/L"terminal";
if(markdown && !std::filesystem::exists(assets/L"markdown.html")) return false;
waitForReady=!markdown;
constexpr COREWEBVIEW2_COLOR background{
255,GetRValue(terminalSurface),GetGValue(terminalSurface),GetBValue(terminalSurface)};
lifetime=std::make_shared<int>(0);
const std::weak_ptr<int> alive=lifetime;
auto environment=terminalCallback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler,
@@ -153,6 +163,12 @@ public:
if(alive.expired()) return S_OK;
if(FAILED(result) || !view) { failed(); return S_OK; }
controller=view;
if(!markdown)
{
view->put_IsVisible(FALSE);
Microsoft::WRL::ComPtr<ICoreWebView2Controller2> colors;
if(SUCCEEDED(controller.As(&colors))) colors->put_DefaultBackgroundColor(background);
}
view->get_CoreWebView2(&web);
Microsoft::WRL::ComPtr<ICoreWebView2_3> mapped;
if(!web || FAILED(web.As(&mapped)) || FAILED(mapped->SetVirtualHostNameToFolderMapping(
@@ -207,7 +223,11 @@ public:
uri==source &&
SUCCEEDED(args->TryGetWebMessageAsString(&value)))
{
if(wcscmp(value,L"ready")==0) ready=true;
if(!ready && wcscmp(value,L"ready")==0)
{
ready=true;
if(waitForReady) layout(bounds,visible);
}
if(ready) receive(value);
}
CoTaskMemFree(value);
@@ -222,6 +242,18 @@ public:
layout(bounds,visible);
return S_OK;
});
if(!markdown)
{
Microsoft::WRL::ComPtr<ICoreWebView2Environment10> configurable;
Microsoft::WRL::ComPtr<ICoreWebView2ControllerOptions> options;
Microsoft::WRL::ComPtr<ICoreWebView2ControllerOptions3> colors;
if(SUCCEEDED(env->QueryInterface(IID_PPV_ARGS(&configurable))) &&
SUCCEEDED(configurable->CreateCoreWebView2ControllerOptions(&options)) &&
SUCCEEDED(options.As(&colors)) &&
SUCCEEDED(colors->put_DefaultBackgroundColor(background)) &&
SUCCEEDED(configurable->CreateCoreWebView2ControllerWithOptions(host,options.Get(),completed.Get())))
return S_OK;
}
if(FAILED(env->CreateCoreWebView2Controller(host,completed.Get()))) failed();
return S_OK;
});
+142 -42
View File
@@ -38,6 +38,15 @@ HANDLE openSource(const std::filesystem::path &path, bool editable)
return result;
}
HANDLE trackReplacement(const std::filesystem::path &path)
{
// A metadata-only handle survives the rename without blocking ReplaceFile.
const auto handle=CreateFileW(path.c_str(),0,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
if(handle==INVALID_HANDLE_VALUE) fail("Track replacement file");
return handle;
}
uint64_t fileSize(HANDLE file)
{
LARGE_INTEGER size{};
@@ -97,10 +106,87 @@ std::filesystem::path createTemporary(const std::filesystem::path &directory, Fi
if (file.handle == INVALID_HANDLE_VALUE) fail("Create temporary file");
return path;
}
bool isUtf16(TextEncoding encoding)
{
return encoding==TextEncoding::utf16le || encoding==TextEncoding::utf16be;
}
TextDocument::TextDocument(std::filesystem::path path, bool editable) : path_(std::move(path)), editable_(editable)
std::string_view signature(TextEncoding encoding)
{
switch(encoding)
{
case TextEncoding::utf16le: return "\xff\xfe";
case TextEncoding::utf16be: return "\xfe\xff";
case TextEncoding::utf8: return "\xef\xbb\xbf";
default: return {};
}
}
std::wstring decodeMultibyte(std::string_view bytes,UINT codePage,DWORD flags)
{
const int length=static_cast<int>(bytes.size());
const auto required=MultiByteToWideChar(codePage,flags,bytes.data(),length,nullptr,0);
if(!required) fail("Decode text");
std::wstring units(required,L'\0');
if(!MultiByteToWideChar(codePage,flags,bytes.data(),length,units.data(),required)) fail("Decode text");
return units;
}
std::string encode(std::string_view utf8,TextEncoding encoding)
{
if(encoding==TextEncoding::utf8 || utf8.empty()) return std::string(utf8);
const auto units=decodeMultibyte(utf8,CP_UTF8,MB_ERR_INVALID_CHARS);
if(encoding==TextEncoding::windows1252)
{
BOOL substituted{};
const int length=static_cast<int>(units.size());
const auto required=WideCharToMultiByte(1252,WC_NO_BEST_FIT_CHARS,units.data(),length,
nullptr,0,nullptr,&substituted);
if(!required) fail("Encode Windows-1252");
if(substituted) throw std::runtime_error("Some characters cannot be saved as Windows-1252. Choose a Unicode encoding.");
std::string bytes(required,'\0');
if(!WideCharToMultiByte(1252,WC_NO_BEST_FIT_CHARS,units.data(),length,bytes.data(),required,nullptr,&substituted))
fail("Encode Windows-1252");
return bytes;
}
std::string bytes(units.size()*2,'\0');
const size_t low=encoding==TextEncoding::utf16le?0:1;
for(size_t i=0;i<units.size();++i)
{
bytes[2*i+low]=static_cast<char>(units[i]&0xff);
bytes[2*i+1-low]=static_cast<char>(units[i]>>8);
}
return bytes;
}
std::string convertLineEndings(std::string_view text,TextLineEnding ending)
{
if(ending==TextLineEnding::preserve) return std::string(text);
const std::string_view replacement=ending==TextLineEnding::crlf?"\r\n":ending==TextLineEnding::lf?"\n":"\r";
std::string result;
result.reserve(text.size());
for(size_t start=0;start<text.size();)
{
const auto next=text.find_first_of("\r\n",start);
result.append(text.substr(start,next==text.npos?text.npos:next-start));
if(next==text.npos) break;
result.append(replacement);
start=next+1;
if(text[next]=='\r' && start<text.size() && text[start]=='\n') ++start;
}
return result;
}
}
TextDocument::TextDocument(std::filesystem::path path,bool editable,TextEncoding encoding)
: path_(std::move(path)), editable_(editable)
{
if(path_.empty())
{
if(encoding!=TextEncoding::automatic) encoding_=encoding;
return;
}
File source{openSource(path_, editable)};
if (editable)
{
@@ -115,13 +201,15 @@ TextDocument::TextDocument(std::filesystem::path path, bool editable) : path_(st
}
size_ = fileSize(source.handle);
const auto prefix = read(source.handle, 0, static_cast<size_t>(std::min<uint64_t>(3, size_)));
if (prefix.starts_with("\xef\xbb\xbf")) bom_ = 3;
else if (prefix.starts_with("\xff\xfe") || prefix.starts_with("\xfe\xff"))
if(encoding==TextEncoding::automatic)
{
encoding_ = prefix.starts_with("\xff") ? Encoding::utf16le : Encoding::utf16be;
bom_ = 2;
if (size_ % 2) throw std::runtime_error("The UTF-16 file has an incomplete code unit.");
encoding=TextEncoding::utf8;
for(const auto candidate:{TextEncoding::utf16le,TextEncoding::utf16be})
if(prefix.starts_with(signature(candidate))) encoding=candidate;
}
encoding_=encoding;
if(prefix.starts_with(signature(encoding_))) bom_=signature(encoding_).size();
if(isUtf16(encoding_) && size_%2) throw std::runtime_error("The UTF-16 file has an incomplete code unit.");
source_ = source.release();
}
@@ -135,8 +223,9 @@ const wchar_t *TextDocument::encodingName() const
{
switch (encoding_)
{
case Encoding::utf16le: return L"UTF-16 LE";
case Encoding::utf16be: return L"UTF-16 BE";
case TextEncoding::utf16le: return L"UTF-16 LE";
case TextEncoding::utf16be: return L"UTF-16 BE";
case TextEncoding::windows1252: return L"Windows-1252";
default: return bom_ ? L"UTF-8 BOM" : L"UTF-8";
}
}
@@ -160,40 +249,45 @@ uint64_t TextDocument::boundary(uint64_t page,HANDLE source) const
if (page >= pages()) return size_;
const auto offset = bom_ + page * pageBytes;
const auto unit = encoding_ == Encoding::utf8 ? 1u : 2u;
const auto unit = isUtf16(encoding_) ? 2u : 1u;
const auto sample = read(source, offset - unit,
static_cast<size_t>(std::min<uint64_t>(4096 + unit, size_ - offset + unit)));
const auto getUnit = [&](size_t i) -> unsigned {
const auto first = static_cast<unsigned char>(sample[i]);
if (unit == 1) return first;
const auto second = static_cast<unsigned char>(sample[i + 1]);
return encoding_ == Encoding::utf16le ? first | (second << 8) : (first << 8) | second;
return encoding_ == TextEncoding::utf16le ? first | (second << 8) : (first << 8) | second;
};
if (getUnit(0) == '\n') return offset;
for (size_t i = unit; i + unit < sample.size(); i += unit)
if (getUnit(i) == '\n') return offset + i;
size_t i = unit;
if (unit == 1)
if (encoding_ == TextEncoding::utf8)
{
// Advance past at most one UTF-8 code point, even on malformed input.
while (i < sample.size() && i <= 3 && (getUnit(i) & 0xc0) == 0x80) ++i;
}
else if (const auto value = getUnit(i); value >= 0xdc00 && value <= 0xdfff) i += unit;
else if (isUtf16(encoding_))
if (const auto value = getUnit(i); value >= 0xdc00 && value <= 0xdfff) i += unit;
if (i == unit && getUnit(0) == '\r' && getUnit(i) == '\n') i += unit;
return offset + i - unit;
}
std::string TextDocument::decode(std::string bytes) const
{
if (encoding_ == Encoding::utf8 || bytes.empty()) return bytes;
if (encoding_ == TextEncoding::utf8 || bytes.empty()) return bytes;
std::wstring units;
units.resize(bytes.size() / 2);
for (size_t i = 0; i < units.size(); ++i)
if(encoding_==TextEncoding::windows1252) units=decodeMultibyte(bytes,1252,0);
else
{
const auto a = static_cast<unsigned char>(bytes[2 * i]);
const auto b = static_cast<unsigned char>(bytes[2 * i + 1]);
units[i] = static_cast<wchar_t>(encoding_ == Encoding::utf16le ? a | (b << 8) : (a << 8) | b);
units.resize(bytes.size() / 2);
for (size_t i = 0; i < units.size(); ++i)
{
const auto a = static_cast<unsigned char>(bytes[2 * i]);
const auto b = static_cast<unsigned char>(bytes[2 * i + 1]);
units[i] = static_cast<wchar_t>(encoding_ == TextEncoding::utf16le ? a | (b << 8) : (a << 8) | b);
}
}
const auto length = static_cast<int>(units.size());
const int required = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, units.data(), length, nullptr, 0, nullptr, nullptr);
@@ -204,25 +298,6 @@ std::string TextDocument::decode(std::string bytes) const
return result;
}
std::string TextDocument::encode(std::string_view utf8) const
{
if (encoding_ == Encoding::utf8 || utf8.empty()) return std::string(utf8);
const auto length = static_cast<int>(utf8.size());
const int required = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.data(), length, nullptr, 0);
if (!required) fail("Encode UTF-16");
std::wstring units(required, L'\0');
if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.data(), length, units.data(), required))
fail("Encode UTF-16");
std::string bytes(units.size() * 2, '\0');
const int low = encoding_ == Encoding::utf16le ? 0 : 1;
for (size_t i = 0; i < units.size(); ++i)
{
bytes[2 * i + low] = static_cast<char>(units[i] & 0xff);
bytes[2 * i + 1 - low] = static_cast<char>(units[i] >> 8);
}
return bytes;
}
std::string TextDocument::readPage(uint64_t page) const
{
if (const auto it = changes_.find(page); it != changes_.end())
@@ -232,6 +307,7 @@ std::string TextDocument::readPage(uint64_t page) const
std::string TextDocument::readOriginal(uint64_t page) const
{
if(path_.empty()) return {};
File temporary{source_ == INVALID_HANDLE_VALUE ? openSource(path_, false) : INVALID_HANDLE_VALUE};
const auto source=source_ == INVALID_HANDLE_VALUE ? temporary.handle : source_;
const auto start = boundary(page,source);
@@ -298,17 +374,14 @@ bool TextDocument::save()
for (const auto &[page, change] : changes_)
{
copyUntil(offset, boundary(page));
append(encode(read(spool_, change.offset, change.size)));
append(encode(read(spool_, change.offset, change.size),encoding_));
offset = boundary(page + 1);
}
copyUntil(offset, size_);
if (!FlushFileBuffers(output.handle)) fail("Flush saved file");
CloseHandle(output.release());
// A metadata-only handle survives the rename without blocking ReplaceFile's exclusive open.
File replacement{CreateFileW(pending.path.c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)};
if (replacement.handle == INVALID_HANDLE_VALUE) fail("Track replacement file");
File replacement{trackReplacement(pending.path)};
File current{openSource(path_, true)};
if (!sameFile(source_, current.handle)) throw std::runtime_error("The file was replaced outside KSwitcher.");
const auto backup = temporaryPath(path_.parent_path());
@@ -336,4 +409,31 @@ bool TextDocument::save()
spoolSize_ = 0;
return source_ != INVALID_HANDLE_VALUE;
}
bool TextDocument::saveNew(std::filesystem::path path,TextSaveFormat format)
{
if(!path_.empty() || !editable_) throw std::logic_error("The document is not a new editable file.");
if(format.encoding==TextEncoding::automatic) format.encoding=TextEncoding::utf8;
const auto bytes=encode(convertLineEndings(readPage(0),format.lineEnding),format.encoding);
const auto bom=format.bom?signature(format.encoding):std::string_view{};
PendingSave pending;
File output;
pending.path=createTemporary(path.parent_path(),output,FILE_ATTRIBUTE_NORMAL);
write(output.handle,bom);
write(output.handle,bytes);
if(!FlushFileBuffers(output.handle)) fail("Flush saved file");
CloseHandle(output.release());
File replacement{trackReplacement(pending.path)};
if(!MoveFileExW(pending.path.c_str(),path.c_str(),MOVEFILE_WRITE_THROUGH)) fail("Create new file");
pending.path.clear();
path_=std::move(path);
encoding_=format.encoding;
bom_=bom.size();
size_=bom_+bytes.size();
changes_.clear();
if(spool_!=INVALID_HANDLE_VALUE) CloseHandle(std::exchange(spool_,INVALID_HANDLE_VALUE));
spoolSize_=0;
source_=ReOpenFile(replacement.handle,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,0);
return source_!=INVALID_HANDLE_VALUE;
}
}
+14 -4
View File
@@ -9,13 +9,24 @@
namespace ks::files
{
enum class TextEncoding { automatic, utf8, utf16le, utf16be, windows1252 };
enum class TextLineEnding { preserve, crlf, lf, cr };
struct TextSaveFormat
{
TextEncoding encoding=TextEncoding::utf8;
bool bom{};
TextLineEnding lineEnding=TextLineEnding::preserve;
};
class TextDocument
{
public:
static constexpr uint64_t pageBytes = 1024 * 1024;
static constexpr size_t editLimit = 8 * pageBytes;
explicit TextDocument(std::filesystem::path path, bool editable = true);
explicit TextDocument(std::filesystem::path path, bool editable = true,
TextEncoding encoding=TextEncoding::automatic);
~TextDocument();
TextDocument(const TextDocument &) = delete;
TextDocument &operator=(const TextDocument &) = delete;
@@ -29,10 +40,10 @@ public:
bool modified() const { return !changes_.empty(); }
bool modifiedWith(uint64_t page, std::string_view current) const;
bool save();
bool saveNew(std::filesystem::path path, TextSaveFormat format);
const wchar_t *encodingName() const;
private:
enum class Encoding { utf8, utf16le, utf16be };
struct Change { uint64_t offset; size_t size; };
std::filesystem::path path_;
@@ -40,13 +51,12 @@ private:
HANDLE spool_ = INVALID_HANDLE_VALUE;
uint64_t size_{}, spoolSize_{};
size_t bom_{};
Encoding encoding_ = Encoding::utf8;
TextEncoding encoding_ = TextEncoding::utf8;
bool editable_;
std::map<uint64_t, Change> changes_;
std::string decode(std::string bytes) const;
uint64_t boundary(uint64_t page,HANDLE source) const;
std::string readOriginal(uint64_t page) const;
std::string encode(std::string_view utf8) const;
};
}
+150 -61
View File
@@ -2,6 +2,7 @@
#include "files_text_preferences.h"
#include "files_menu_paint.h"
#include "files_menu_navigation.h"
#include "files_scrollbar.h"
#include "files_history_date.h"
#include "files_text_document.h"
#include "files_text_language.h"
@@ -317,10 +318,17 @@ struct FarPopup
FarDropDownPalette palette;
HFONT font{};
int rowHeight{},inset{},visible{},top{},current{},result=-1;
int dragOffset=-1;
bool done{};
int rowTop() const { return inset+1+rowHeight/2; }
int bottomMargin() const { return inset+1+rowHeight/4; }
ScrollPosition scrollPosition() const {return {static_cast<int>(rows.size()),visible,top};}
RECT scrollTrack(HWND window,RECT bounds) const
{
const LONG right=bounds.right-inset-1;
return {std::max(bounds.left,right-scrollBarWidth(window)),rowTop(),right,rowTop()+visible*rowHeight};
}
void select(int row)
{
@@ -370,8 +378,9 @@ struct FarPopup
SetTextColor(dc,palette.text);
SelectObject(dc,font);
const LONG rowLeft=frame.left+inset;
const LONG scrollWidth=static_cast<int>(rows.size())>visible?rowHeight/2:0;
const LONG rowRight=scrollWidth?bounds.right-scrollWidth:frame.right-1;
const auto position=scrollPosition();
const auto track=scrollTrack(window,bounds);
const LONG rowRight=position.last()?track.left:frame.right-1;
LONG y=rowTop();
for(int offset=0;offset<visible;++offset,y+=rowHeight)
{
@@ -400,22 +409,7 @@ struct FarPopup
DrawTextW(dc,entry.text.data(),static_cast<int>(entry.text.size()),&box,
DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX|DT_END_ELLIPSIS|(entry.index<0?DT_CENTER:DT_LEFT));
}
if(scrollWidth)
{
RECT up{rowRight,rowTop(),bounds.right,rowTop()+rowHeight};
RECT down{rowRight,y-rowHeight,bounds.right,y};
DrawTextW(dc,L"▲",1,&up,DT_SINGLELINE|DT_CENTER|DT_VCENTER);
DrawTextW(dc,L"▼",1,&down,DT_SINGLELINE|DT_CENTER|DT_VCENTER);
RECT track{up.left,up.bottom,up.right,down.top};
for(LONG line=track.top;line<track.bottom;line+=2)
for(LONG x=track.left+(line%4==0?0:1);x<track.right;x+=2)
SetPixelV(dc,x,line,palette.text);
const auto travel=std::max(0L,track.bottom-track.top-rowHeight);
const auto thumbY=track.top+MulDiv(top,travel,static_cast<int>(rows.size())-visible);
RECT thumb{track.left,thumbY,track.right,std::min(track.bottom,thumbY+rowHeight)};
SetDCBrushColor(dc,palette.text);
FillRect(dc,&thumb,brush);
}
if(position.last()) paintScrollBar(dc,track,position,palette.surface);
}
};
@@ -482,17 +476,28 @@ LRESULT CALLBACK farPopupWindow(HWND window,UINT message,WPARAM wp,LPARAM lp)
RECT bounds{};
GetClientRect(window,&bounds);
const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
const auto position=state->scrollPosition();
const auto track=state->scrollTrack(window,bounds);
if(state->dragOffset>=0)
{
if(message==WM_MOUSEMOVE) state->top=position.drag(track,point.y,state->dragOffset);
if(message==WM_LBUTTONUP) state->dragOffset=-1;
InvalidateRect(window,nullptr,FALSE);
return 0;
}
if(!PtInRect(&bounds,point))
{
if(message==WM_LBUTTONDOWN) state->done=true;
return 0;
}
const auto offset=(point.y-state->rowTop())/state->rowHeight;
const bool scroll=static_cast<int>(state->rows.size())>state->visible &&
point.x>=bounds.right-state->rowHeight/2;
const bool scroll=position.last() && PtInRect(&track,point);
if(scroll && message==WM_LBUTTONDOWN)
state->top=std::clamp(state->top+(offset<state->visible/2?-1:1),0,
static_cast<int>(state->rows.size())-state->visible);
{
const auto thumb=position.thumb(track);
if(PtInRect(&thumb,point)) state->dragOffset=point.y-thumb.top;
else state->top=position.click(track,point.y);
}
if(!scroll && point.y>=state->rowTop() && offset<state->visible)
{
const auto row=state->top+offset;
@@ -724,13 +729,18 @@ class TextWindow
{
public:
TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const lan::FilesPeer *peer,
std::string_view fragment)
std::string_view fragment,TextOpenOptions options)
: original(std::move(path)), peerId(peer?peer->id:""), filename(original.filename().wstring()),
edit(editable), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
edit(editable), draft(options.draft), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
search{dialogs}, previewFragment(fragment)
{
if (peer) remote=std::make_unique<RemoteTextFile>(RemoteTextFile{*peer,original});
else document=std::make_unique<TextDocument>(original,edit);
else document=std::make_unique<TextDocument>(draft?std::filesystem::path{}:original,edit,options.encoding);
if(options.encoding!=TextEncoding::automatic)
{
newFormat.encoding=options.encoding;
newFormat.bom=options.encoding==TextEncoding::utf16le || options.encoding==TextEncoding::utf16be;
}
for (int index = 0; index < GetLexerCount(); ++index)
{
char name[128]{};
@@ -759,6 +769,9 @@ private:
std::unique_ptr<TextDocument> document;
std::wstring filename;
bool edit{}, loading{}, stagedDirty{}, closeAfterSave{}, insertRejected{};
bool draft{};
TextSaveFormat newFormat;
std::filesystem::path pendingSavePath;
HICON smallIcon{},largeIcon{};
TextPreferences prefs;
TextWindowFont filesFont;
@@ -851,6 +864,9 @@ private:
bool dirty() const { return stagedDirty || (!busy() && uploadPending) || currentChanged(); }
bool busy() const { return saving.valid(); }
void invalidate() const { InvalidateRect(window, nullptr, FALSE); }
RECT statusBounds() const;
void invalidateStatus() const;
void invalidateHints() const;
void initializeDocument();
void finishOpen();
@@ -1337,22 +1353,25 @@ void TextWindow::finishOpen()
void TextWindow::saveFile(bool closeWhenDone)
{
if (busy() || !edit) return;
auto destination=original;
if(draft && !search.style.saveOptions(window,destination,newFormat)) return;
stagePage();
if (!stagedDirty && !uploadPending)
if (!draft && !stagedDirty && !uploadPending)
{
if (closeWhenDone) DestroyWindow(window);
else if (std::exchange(switchAfterSave, false)) changeMode();
return;
}
pendingCaret = send(SCI_GETCURRENTPOS);
if(draft) pendingSavePath=destination;
closeAfterSave = closeWhenDone;
if (!SetTimer(window, saveTimer, 75, nullptr)) throw std::runtime_error("Cannot start the save timer.");
send(SCI_SETREADONLY, TRUE);
try
{
saving=std::async(std::launch::async,[this]
saving=std::async(std::launch::async,[this,destination=std::move(destination)]
{
const auto reopened=document->save();
const auto reopened=draft?document->saveNew(destination,newFormat):document->save();
if(remote)
{
uploadPending=true;
@@ -1379,6 +1398,14 @@ void TextWindow::finishSave()
const auto change = std::exchange(switchAfterSave, false);
const auto reopened = saving.get();
stagedDirty = false;
const bool created=std::exchange(draft,false);
if(created)
{
original=std::move(pendingSavePath);
filename=original.filename().wstring();
navigationHistory.clear();
updateTitle();
}
if (!reopened)
{
search.style.message(window, L"The file was saved. Reopen it to continue editing.");
@@ -1387,6 +1414,12 @@ void TextWindow::finishSave()
}
if (closeAfterSave) { DestroyWindow(window); return; }
if (change) { changeMode(); return; }
if(created)
{
initializeDocument();
send(SCI_GOTOPOS,std::min<LRESULT>(pendingCaret,send(SCI_GETLENGTH)));
return;
}
if (pageTotal == 1 && document->pages() == 1)
{
fileSize = document->size();
@@ -1403,7 +1436,7 @@ void TextWindow::requestClose()
if (busy()) return;
if (needsSave())
{
const auto answer = search.style.confirmSave(window);
const auto answer = search.style.confirmSave(window,draft);
if (answer == IDCANCEL) return;
if (answer == IDYES) { saveFile(true); return; }
if (answer != IDNO) return;
@@ -1419,9 +1452,10 @@ bool TextWindow::needsSave() const
void TextWindow::toggleMode()
{
if (busy() || navigation.valid()) return;
if(draft) return;
if (edit && needsSave())
{
const auto answer = search.style.confirmSave(window);
const auto answer = search.style.confirmSave(window,false);
if (answer == IDYES)
{
switchAfterSave = true;
@@ -1542,7 +1576,7 @@ void TextWindow::updatePreview()
}
if(ctrl && !alt && key==VK_TAB)
{
PostMessageW(window,cycleWindow,0,0);
PostMessageW(window,cycleWindow,(GetKeyState(VK_SHIFT)&0x8000)!=0,0);
return true;
}
if(key==VK_BROWSER_BACK || key==VK_BROWSER_FORWARD || (alt && (key==VK_LEFT || key==VK_RIGHT)))
@@ -1674,7 +1708,7 @@ void TextWindow::previewMessage(const std::wstring &value)
const auto action=message.at("action").get<std::string>();
if(action=="cycle")
{
PostMessageW(window,cycleWindow,0,0);
PostMessageW(window,cycleWindow,message.value("reverse",false),0);
return;
}
if(action=="failed")
@@ -1856,6 +1890,58 @@ void TextWindow::layout()
invalidate();
}
RECT TextWindow::statusBounds() const
{
RECT bounds{};
GetClientRect(window,&bounds);
bounds.top=chromeHeight();
bounds.bottom=2*bounds.top;
return bounds;
}
void TextWindow::invalidateStatus() const
{
const auto bounds=statusBounds();
InvalidateRect(window,&bounds,FALSE);
}
void TextWindow::invalidateHints() const
{
RECT bounds{};
GetClientRect(window,&bounds);
bounds.top=std::max(0L,bounds.bottom-chromeHeight());
InvalidateRect(window,&bounds,FALSE);
}
void drawEditorStatus(HDC dc,RECT bounds,HFONT font,COLORREF background,COLORREF foreground,
int inset,const std::wstring &status)
{
const auto width=bounds.right-bounds.left,height=bounds.bottom-bounds.top;
if(width<=0 || height<=0) return;
const auto memory=CreateCompatibleDC(dc);
const auto bitmap=memory?CreateCompatibleBitmap(dc,width,height):nullptr;
const auto target=bitmap?memory:dc;
const auto oldBitmap=bitmap?SelectObject(memory,bitmap):nullptr;
const auto oldFont=SelectObject(target,font);
auto row=bitmap?RECT{0,0,width,height}:bounds;
SetDCBrushColor(target,background);
FillRect(target,&row,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
SetBkMode(target,TRANSPARENT);
SetTextColor(target,foreground);
row.left+=inset;
row.right-=inset;
if(row.left<row.right)
DrawTextW(target,status.c_str(),-1,&row,DT_RIGHT|DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS|DT_NOPREFIX);
SelectObject(target,oldFont);
if(bitmap)
{
BitBlt(dc,bounds.left,bounds.top,width,height,memory,0,0,SRCCOPY);
SelectObject(memory,oldBitmap);
DeleteObject(bitmap);
}
if(memory) DeleteDC(memory);
}
void TextWindow::paint()
{
PAINTSTRUCT paint{};
@@ -1865,12 +1951,12 @@ void TextWindow::paint()
const auto row = chromeHeight();
const auto brush = static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
SetDCBrushColor(dc, color(TextColor::background));
FillRect(dc, &client, brush);
const RECT body{0,2*row,client.right,std::max<LONG>(2*row,client.bottom-row)};
FillRect(dc, &body, brush);
SetDCBrushColor(dc, color(TextColor::chromebg));
RECT menuBar{0, 0, client.right, row};
RECT top{0, row, client.right, 2 * row};
const RECT top=statusBounds();
RECT bottom{0, client.bottom - row, client.right, client.bottom};
FillRect(dc, &top, brush);
FillRect(dc, &bottom, brush);
FillRect(dc, &menuBar, brush);
const auto chromeFont = createChromeFont();
@@ -1899,27 +1985,27 @@ void TextWindow::paint()
}
SetTextColor(dc, color(TextColor::chrome));
bottom.left += scale(7);
const auto position = send(SCI_GETCURRENTPOS);
const auto line = send(SCI_LINEFROMPOSITION, position) + 1;
const auto column = send(SCI_GETCOLUMN, position) + 1;
const auto displayLanguage = textLanguageLabel(language);
auto status = filename + (edit ? L" (Edit)" : L" (View)") + (dirty() ? L" *" : L"") +
L" │ " + (document?document->encodingName():L"Loading…") + L" │ " + displayLanguage +
L" │ Ln " + std::to_wstring(line) + L":" + std::to_wstring(column);
if (pageTotal > 1)
status += L" │ Page " + std::to_wstring(page + 1) + L"/" + std::to_wstring(pageTotal) +
L" @ " + std::to_wstring(pageOffset);
status += L" │ " + std::to_wstring(fileSize) + L" B";
RECT statusPaint{};
if(IntersectRect(&statusPaint,&top,&paint.rcPaint))
{
const auto position=send(SCI_GETCURRENTPOS);
const auto line=send(SCI_LINEFROMPOSITION,position)+1;
const auto column=send(SCI_GETCOLUMN,position)+1;
auto status=filename+(edit?L" (Edit)":L" (View)")+(dirty()?L" *":L"")+
L" │ "+(document?document->encodingName():L"Loading…")+L" │ "+textLanguageLabel(language)+
L" │ Ln "+std::to_wstring(line)+L":"+std::to_wstring(column);
if(pageTotal>1)
status+=L" │ Page "+std::to_wstring(page+1)+L"/"+std::to_wstring(pageTotal)+
L" @ "+std::to_wstring(pageOffset);
status+=L" │ "+std::to_wstring(fileSize)+L" B";
drawEditorStatus(dc,top,chromeFont,color(TextColor::chromebg),color(TextColor::chrome),scale(12),status);
}
const auto hints = busy() ? L"Saving…" : insertRejected ? L"Page edit limit: 8 MiB" :
edit ? L"F2 Save F3 Find next F5 Go to page F6 View Ctrl+PgUp/PgDn Pages F10 Close" :
previewVisible ? L"F6 Edit Ctrl+W Close" :
previewWanted ? L"Rendering Markdown… Ctrl+W Close" :
L"F3 Find next F5 Go to page F6 Edit Ctrl+PgUp/PgDn Pages F10 Close";
constexpr UINT format = DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS | DT_NOPREFIX;
top.left += scale(12);
top.right -= scale(12);
if (top.left < top.right)
DrawTextW(dc, status.c_str(), -1, &top, format | DT_RIGHT);
DrawTextW(dc, hints, -1, &bottom, format);
SelectObject(dc, previous);
DeleteObject(chromeFont);
@@ -2039,6 +2125,7 @@ void TextWindow::notify(const SCNotification &notice)
case SCN_MODIFIED:
if (notice.modificationType & SC_MOD_INSERTCHECK)
{
const auto hadWarning=insertRejected;
if (send(SCI_GETLENGTH) + notice.length > static_cast<LRESULT>(TextDocument::editLimit))
{
send(SCI_CHANGEINSERTION, 0, reinterpret_cast<LPARAM>(""));
@@ -2046,6 +2133,7 @@ void TextWindow::notify(const SCNotification &notice)
MessageBeep(MB_ICONWARNING);
}
else insertRejected = false;
if(hadWarning!=insertRejected) invalidateHints();
}
if (notice.modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT))
{
@@ -2053,8 +2141,8 @@ void TextWindow::notify(const SCNotification &notice)
undoBytes += static_cast<size_t>(notice.length) + 64;
if (undoBytes >= 32 * TextDocument::pageBytes)
PostMessageW(window, trimUndo, 0, 0);
invalidateStatus();
}
invalidate();
break;
case SCN_CHARADDED:
if (edit && prefs.autoIndent && (notice.ch == '\n' || (notice.ch == '\r' && send(SCI_GETEOLMODE) == SC_EOL_CR)))
@@ -2074,7 +2162,7 @@ void TextWindow::notify(const SCNotification &notice)
case SCN_UPDATEUI:
case SCN_SAVEPOINTREACHED:
case SCN_SAVEPOINTLEFT:
invalidate();
invalidateStatus();
break;
}
}
@@ -2208,7 +2296,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
return 0;
}
case WM_SETFOCUS: self->focusContent(); return 0;
case cycleWindow: cycleTextWindows(window); return 0;
case cycleWindow: cycleTextWindows(window,wparam!=0); return 0;
case WM_KEYDOWN:
if(self->previewWanted && !self->previewVisible)
{
@@ -2407,7 +2495,7 @@ void textWindowOwnerClosed()
if(textWindows.empty()) PostQuitMessage(0);
}
bool cycleTextWindows(HWND current)
bool cycleTextWindows(HWND current,bool reverse)
{
if(!current || (current!=filesOwner && !textWindows.contains(current))) return false;
std::vector<HWND> windows;
@@ -2417,11 +2505,12 @@ bool cycleTextWindows(HWND current)
if(windows.size()<2) return false;
const auto from=std::find(windows.begin(),windows.end(),current);
if(from==windows.end()) return false;
auto to=std::next(from);
if(to==windows.end()) to=windows.begin();
if(IsIconic(*to)) ShowWindow(*to,SW_RESTORE);
SetForegroundWindow(*to);
if(*to!=filesOwner) SendMessageW(*to,WM_SETFOCUS,0,0);
const auto index=static_cast<size_t>(from-windows.begin());
const auto step=reverse?windows.size()-1:1;
const auto target=windows[(index+step)%windows.size()];
if(IsIconic(target)) ShowWindow(target,SW_RESTORE);
SetForegroundWindow(target);
if(target!=filesOwner) SendMessageW(target,WM_SETFOCUS,0,0);
return true;
}
@@ -2452,7 +2541,7 @@ HWND findOpenDocument(const std::filesystem::path &path,const lan::FilesPeer *pe
}
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const lan::FilesPeer *peer,std::string_view fragment,bool newWindow)
const lan::FilesPeer *peer,std::string_view fragment,bool newWindow,TextOpenOptions options)
{
try
{
@@ -2484,7 +2573,7 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD
return Scintilla_RegisterClasses(instance) && RegisterClassW(&type);
}();
if(!registered) throw std::runtime_error("Cannot register the text window.");
auto state=std::make_shared<TextWindow>(original,edit,dialogs,peer,fragment);
auto state=std::make_shared<TextWindow>(original,edit,dialogs,peer,fragment,options);
const auto title=std::wstring(edit?L"Editor — ":L"Viewer — ")+
(peer?peer->name+L" · ":std::wstring{})+path.wstring();
RECT bounds{};
+12 -3
View File
@@ -4,6 +4,7 @@
#include <filesystem>
#include <string_view>
#include <vector>
#include "files_text_document.h"
namespace ks::lan { struct FilesPeer; }
@@ -37,7 +38,7 @@ void installFarHistoryKey(HWND field,int arrowId);
struct TextDialogs
{
INT_PTR (*confirmSave)(HWND);
INT_PTR (*confirmSave)(HWND,bool draft);
INT_PTR (*paint)(HWND, UINT, WPARAM, LPARAM, const wchar_t *);
INT_PTR (*paintSearch)(HWND, UINT, WPARAM, LPARAM);
void (*prepare)(HWND);
@@ -49,10 +50,18 @@ struct TextDialogs
void (*finish)(HWND,INT_PTR);
bool (*dismissOwned)(HWND);
bool (*confirmExisting)(HWND);
bool (*saveOptions)(HWND,std::filesystem::path &,TextSaveFormat &);
};
struct TextOpenOptions
{
TextEncoding encoding=TextEncoding::automatic;
bool draft{};
};
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false);
const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false,
TextOpenOptions options={});
void textWindowOwnerClosed();
bool cycleTextWindows(HWND current);
bool cycleTextWindows(HWND current,bool reverse);
}
+1 -1
View File
@@ -2,7 +2,7 @@
#include "platform.h"
namespace ks
{
inline constexpr wchar_t AppVersion[] = L"0.6.109";
inline constexpr wchar_t AppVersion[] = L"0.6.116";
inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+163 -16
View File
@@ -3,6 +3,7 @@ param(
[Parameter(Mandatory)][string]$Fixture,
[switch]$SystemOpenOnly,
[switch]$TerminalOnly,
[int]$ScanEntries = 0,
[string]$Node='node'
)
$ErrorActionPreference = 'Stop'
@@ -12,6 +13,10 @@ using System.Text;
using System.Runtime.InteropServices;
public static class FilesActivationUi {
public static void CreateScanFiles(string directory, int count) {
for (int i = 0; i < count; i++)
using (System.IO.File.Create(System.IO.Path.Combine(directory, i.ToString("D6") + ".txt"))) {}
}
[StructLayout(LayoutKind.Sequential)]
public struct Rect { public int Left, Top, Right, Bottom; }
[StructLayout(LayoutKind.Sequential)]
@@ -27,6 +32,22 @@ public static class FilesActivationUi {
[DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr window);
[DllImport("user32.dll")] static extern int ReleaseDC(IntPtr window, IntPtr dc);
[DllImport("gdi32.dll")] static extern uint GetPixel(IntPtr dc, int x, int y);
[DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr window, out Rect rect);
[DllImport("user32.dll")] static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
public static uint ReadScreenCenter(IntPtr window) {
var previous = SetThreadDpiAwarenessContext(new IntPtr(-4));
try {
Rect bounds;
if (!GetWindowRect(window, out bounds)) throw new InvalidOperationException("Missing terminal output.");
var dc = GetDC(IntPtr.Zero);
if (dc == IntPtr.Zero) throw new InvalidOperationException("Could not read the screen.");
try { return GetPixel(dc, (bounds.Left + bounds.Right) / 2, (bounds.Top + bounds.Bottom) / 2); }
finally { ReleaseDC(IntPtr.Zero, dc); }
} finally {
if (previous != IntPtr.Zero) SetThreadDpiAwarenessContext(previous);
}
}
public static bool HasWarningBackground(IntPtr window) {
var dc = GetDC(window);
@@ -35,6 +56,7 @@ public static class FilesActivationUi {
finally { ReleaseDC(window, dc); }
}
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] public static extern uint GetClipboardSequenceNumber();
[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 bool PostMessage(IntPtr window, uint msg, IntPtr w, IntPtr l);
@@ -86,6 +108,19 @@ function Wait-Until([string]$Description, [scriptblock]$Condition) {
throw "Timed out waiting for $Description"
}
function Invoke-ClipboardOperation([scriptblock]$Operation) {
for ($attempt = 1; $attempt -le 3; $attempt++) {
try { return (& $Operation) }
catch {
# CLIPBRD_E_CANT_OPEN means another process is using the shared clipboard.
if ($_.Exception.GetBaseException().HResult -ne 0x800401D0 -or
$attempt -eq 3) { throw }
[Windows.Forms.Application]::DoEvents()
Start-Sleep -Milliseconds 25
}
}
}
function Find-OperationDialog($Owner, [int]$Control) {
$candidate = [IntPtr]::Zero
while ($true) {
@@ -172,7 +207,7 @@ $extension = ".ksfiles$unique"
$progId = "KSwitcher.Files.Test.$unique"
$saved = @{}
$profileValues = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'LeftWide', 'RightWide',
'ShowDetails', 'StatusFields', 'CommandHistory', 'WindowPlacement'
'ShowDetails', 'StatusFields', 'CommandHistory', 'CommandHistoryKey', 'PreviousCommandKey', 'WindowPlacement'
$process = $null
$trace = $null
$webviewFlags=$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
@@ -214,6 +249,18 @@ try {
$profile.SetValue('StatusFields', 3)
if($TerminalOnly){
$terminalPage = Join-Path $app 'terminal/index.html'
$page = Get-Content -Raw -LiteralPath $terminalPage
$page = $page.Replace('<style>','<style media="not all">').Replace('src="terminal.js"','src="startup-fixture.js"')
[IO.File]::WriteAllText($terminalPage,$page)
[IO.File]::WriteAllText((Join-Path $app 'terminal/startup-fixture.js'), @'
function startTerminalFixture() {
document.querySelector('style').media = 'all';
const script = document.createElement('script');
script.src = 'terminal.js';
document.body.append(script);
}
'@)
$listener=[Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
$listener.Start()
$port=$listener.LocalEndpoint.Port
@@ -221,6 +268,13 @@ try {
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS="--remote-debugging-port=$port"
$env:WEBVIEW2_USER_DATA_FOLDER=Join-Path $root 'webview'
}
if($SystemOpenOnly) {
$profile.SetValue('PreviousCommandKey',0x0245,'DWord')
$profile.SetValue('CommandHistoryKey',0x0477,'DWord')
}
if ($ScanEntries) {
[FilesActivationUi]::CreateScanFiles("$leftDir\Test folder", $ScanEntries)
}
$process = Start-Process -FilePath $testExe -ArgumentList '--terminal-output-trace' -PassThru
$trace = Join-Path ([IO.Path]::GetTempPath()) "KSwitcher.Files.terminal-trace-$($process.Id).log"
Wait-Until 'Files window' { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
@@ -231,6 +285,49 @@ try {
$output = [FilesActivationUi]::GetDlgItem($window, 145)
$inputBox = [FilesActivationUi]::FindWindowEx($window, [IntPtr]::Zero, 'Edit', $null)
if ($ScanEntries) {
Wait-Until 'visible Files window' { [FilesActivationUi]::Activate($window) }
Wait-Until 'folder fixture row' { (Find-Row $left '[Test folder]') -ge 0 }
$folderRow = Find-Row $left '[Test folder]'
[void][FilesActivationUi]::Send($left, 0x186, [IntPtr]$folderRow, [IntPtr]::Zero)
Press-Enter $inputBox
Wait-Until 'nonzero folder scan progress' {
[FilesActivationUi]::IsWindowVisible($status) -and
(Read-Text $status) -match '^Reading ([1-9][0-9]*) \[Esc\]$'
}
$progress = Read-Text $status
[void][FilesActivationUi]::PostMessage($inputBox, 0x100, [IntPtr]27, [IntPtr]::Zero)
Wait-Until 'partial folder result' { (Read-Text $status) -match '^Partial: \d+$' }
$partial = [FilesActivationUi]::Send($left, 0x18B, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() - 1
$partialStatus = Read-Text $status
if ($partial -le 0 -or $partial -ge $ScanEntries -or
$partialStatus -ne "Partial: $partial" -or
(Read-Text ([FilesActivationUi]::GetDlgItem($window,142))) -ne "$leftDir\Test folder") {
throw "Unexpected partial listing of $partial entries."
}
$keys = New-Object -ComObject WScript.Shell
$fullScan = [Diagnostics.Stopwatch]::StartNew()
$keys.SendKeys('^r')
Wait-Until 'complete folder result after Ctrl+R' {
[FilesActivationUi]::Send($left, 0x18B, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq $ScanEntries + 1
}
$fullScan.Stop()
Write-Output "$progress. $partialStatus. Full scan: $ScanEntries files in $($fullScan.ElapsedMilliseconds) ms."
$target = 65536
[void][FilesActivationUi]::Send($left, 0x197, [IntPtr]$target, [IntPtr]::Zero)
if ([FilesActivationUi]::Send($left, 0x18E, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -ne $target) {
throw "Could not scroll row $target to the top."
}
$point = [IntPtr]((2 -shl 16) -bor 6)
[void][FilesActivationUi]::PostMessage($left, 0x201, [IntPtr]1, $point)
[void][FilesActivationUi]::PostMessage($left, 0x202, [IntPtr]::Zero, $point)
Wait-Until 'mouse selection past the 16-bit row limit' {
[FilesActivationUi]::Send($left, 0x188, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq $target
}
Write-Output "Clicked row $target after scrolling it to the top."
return
}
if($SystemOpenOnly) {
$keys = New-Object -ComObject WScript.Shell
$explorer = New-Object -ComObject Shell.Application
@@ -271,11 +368,55 @@ try {
Wait-Until 'plain Enter invoking the default Windows file association' {
(Test-Path -LiteralPath "$document.opened") -and [IO.File]::ReadAllText("$document.opened") -eq 'opened'
}
$command="start '$($document.Replace("'","''"))'"
Wait-Until 'the system open action in terminal output and command history' {
$history=$profile.GetValue('CommandHistory')
[FilesActivationUi]::IsWindowVisible($output) -and $history -and
([Text.Encoding]::Unicode.GetString($history).Split([char]0) -ccontains $command) -and
(Select-String -LiteralPath $trace -Pattern ('^'+[regex]::Escape($document.Substring(0,24))) -Quiet)
}
Wait-Until 'Files active for command history' { [FilesActivationUi]::Activate($window) }
$keys.SendKeys('%{F8}')
$historyDialog=[IntPtr]::Zero
Wait-Until 'command history showing only the opened file path' {
$script:historyDialog=[FilesActivationUi]::GetForegroundWindow()
$list=[FilesActivationUi]::GetDlgItem($historyDialog,324)
$list -ne [IntPtr]::Zero -and (Find-Row $list $document) -ge 0
}
$historyList=[FilesActivationUi]::GetDlgItem($historyDialog,324)
$historyRow=Find-Row $historyList $document
[void][FilesActivationUi]::Send($historyList,0x186,[IntPtr]$historyRow,[IntPtr]::Zero)
[void][FilesActivationUi]::PostMessage($historyDialog,0x111,[IntPtr]1,[IntPtr]::Zero)
Wait-Until 'selecting the history path restoring a runnable command' { (Read-Text $inputBox) -ceq $command }
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'')
Write-Output 'Verified Shift+Enter opens folders in Explorer. Both Enter and Shift+Enter invoke the default file action.'
Remove-Item -LiteralPath "$document.opened"
}
if($SystemOpenOnly -or $TerminalOnly){
$keys = New-Object -ComObject WScript.Shell
if ($TerminalOnly) {
Wait-Until 'Files active for the terminal startup check' {
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
}
$keys.SendKeys('^o')
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-startup-pause'
if ($LASTEXITCODE) { throw 'Could not pause terminal page initialization.' }
foreach ($frame in 1..10) {
if ([FilesActivationUi]::GetForegroundWindow() -ne $window -or
![FilesActivationUi]::IsWindowVisible($output)) { throw 'The terminal must be visible for the startup check.' }
$pixel = [FilesActivationUi]::ReadScreenCenter($output)
if ($pixel -ne 0x181818) { throw ('Unexpected terminal startup background 0x{0:X6}.' -f $pixel) }
Start-Sleep -Milliseconds 30
}
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-startup-resume'
if ($LASTEXITCODE) { throw 'Could not resume terminal page initialization.' }
Wait-Until 'the terminal rendering after startup' {
Select-String -LiteralPath $trace -SimpleMatch ' web-anchor ' -Quiet -ErrorAction SilentlyContinue
}
$keys.SendKeys('^o')
Wait-Until 'file panes restored after the startup check' { [FilesActivationUi]::IsWindowVisible($left) }
Write-Output 'Verified the dark terminal background before WebView initialization completes.'
}
foreach($case in @(
@{Name='enter-panes'; Keys='{ENTER}'},
@{Name='shift-enter-panes'; Keys='+{ENTER}'},
@@ -334,21 +475,21 @@ try {
Send-InteractiveTerminal "Write-Output '$outputSelection'"
Wait-Until 'output selection fixture command submitted' { !(Read-Text $inputBox) }
Add-Type -AssemblyName System.Windows.Forms
$savedClipboard = [Windows.Forms.Clipboard]::GetDataObject()
$savedClipboard = Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetDataObject() }
try {
$nativeDraft = "Get-Item -LiteralPath '$leftDir'"
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$nativeDraft)
[void][FilesActivationUi]::Send($inputBox,0xB1,[IntPtr]0,[IntPtr]4)
$keys.SendKeys('^{INSERT}')
Wait-Until 'Ctrl+Insert copying the full command line with a partial selection' {
[Windows.Forms.Clipboard]::GetText() -ceq $nativeDraft
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $nativeDraft
}
$webviewDraft = "Get-Item -LiteralPath '$rightDir'"
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$webviewDraft)
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-copy'
if($LASTEXITCODE){throw 'Could not send Ctrl+Insert through the terminal WebView.'}
Wait-Until 'Ctrl+Insert copying the command line with focus in the terminal WebView' {
[Windows.Forms.Clipboard]::GetText() -ceq $webviewDraft
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $webviewDraft
}
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-select-output'
if($LASTEXITCODE){throw 'Could not select the terminal output fixture.'}
@@ -356,22 +497,26 @@ try {
[FilesActivationUi]::Focus($window) -eq $inputBox
}
foreach($key in '^c','^{INSERT}') {
[Windows.Forms.Clipboard]::SetText($webviewDraft)
# Require a new clipboard write without making the test process the clipboard owner.
$beforeCopy = [FilesActivationUi]::GetClipboardSequenceNumber()
$keys.SendKeys($key)
Wait-Until "$key copying only the selected terminal output with a command present" {
[Windows.Forms.Clipboard]::GetText() -ceq $outputSelection
[FilesActivationUi]::GetClipboardSequenceNumber() -ne $beforeCopy -and
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $outputSelection
}
if ((Read-Text $inputBox) -cne $webviewDraft) { throw 'Copying output changed the command line.' }
}
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'')
$keys.SendKeys('^{INSERT}')
Wait-Until 'Ctrl+Insert copying the selected folder name when the command line is empty' {
[Windows.Forms.Clipboard]::GetText() -ceq 'Test folder'
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq 'Test folder'
}
} finally {
if ([Windows.Forms.Clipboard]::GetText() -cin @($nativeDraft,$webviewDraft,$outputSelection,'Test folder')) {
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
else { [Windows.Forms.Clipboard]::Clear() }
Invoke-ClipboardOperation {
if ([Windows.Forms.Clipboard]::GetText() -cin @($nativeDraft,$webviewDraft,$outputSelection,'Test folder')) {
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
else { [Windows.Forms.Clipboard]::Clear() }
}
}
}
Write-Output 'Verified Ctrl+C and Ctrl+Insert copy the selected output, then fall back to the command line or panel.'
@@ -477,7 +622,7 @@ try {
Write-Output 'Both panels refreshed external creation, modification and deletion while preserving focus.'
Add-Type -AssemblyName System.Windows.Forms
$savedClipboard=[Windows.Forms.Clipboard]::GetDataObject()
$savedClipboard=Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetDataObject() }
$programName=[IO.Path]::GetFileName($program)
$expectedNames="Test folder`r`n$programName"
try {
@@ -490,18 +635,20 @@ try {
}
$shell.SendKeys('^{INSERT}')
Wait-Until 'Ctrl+Insert copying marked names in panel order' {
[Windows.Forms.Clipboard]::GetText() -ceq $expectedNames
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $expectedNames
}
Select-Row $right $fileName
$shell.SendKeys('^{INSERT}')
Wait-Until 'Ctrl+Insert copying the current item in the other pane' {
[Windows.Forms.Clipboard]::GetText() -ceq $fileName
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $fileName
}
Write-Output 'Ctrl+Insert copied marked names in order and used the cursor in the other pane.'
} finally {
if ([Windows.Forms.Clipboard]::GetText() -cin @($expectedNames,$fileName)) {
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
else { [Windows.Forms.Clipboard]::Clear() }
Invoke-ClipboardOperation {
if ([Windows.Forms.Clipboard]::GetText() -cin @($expectedNames,$fileName)) {
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
else { [Windows.Forms.Clipboard]::Clear() }
}
}
}
+105 -2
View File
@@ -10,6 +10,8 @@ using System.Runtime.InteropServices;
public static class FilesShortcutWindow {
[StructLayout(LayoutKind.Sequential)]
public struct Rect { public int Left, Top, Right, Bottom; }
[StructLayout(LayoutKind.Sequential)]
public struct Point { public int X, Y; }
[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);
@@ -17,6 +19,11 @@ public static class FilesShortcutWindow {
[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")] public static extern uint GetDpiForWindow(IntPtr window);
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
[DllImport("user32.dll")] public static extern bool ScreenToClient(IntPtr window, ref Point point);
[DllImport("user32.dll", EntryPoint="SendMessageW")]
public static extern IntPtr Send(IntPtr window, uint message, IntPtr w, IntPtr l);
[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) {
@@ -55,6 +62,7 @@ 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
$previousDpi = [FilesShortcutWindow]::SetThreadDpiAwarenessContext([IntPtr](-4))
try {
$groups = [object[]]::new(10)
for ($digit = 0; $digit -lt 10; $digit++) { $groups[$digit] = @() }
@@ -62,6 +70,9 @@ try {
$path = [IO.Directory]::CreateDirectory((Join-Path $folder $entry[1])).FullName
$groups[$entry[0]] += @{ path = $path; peer = ''; name = ''; title = $entry[1] }
}
$groups[9] = @(1..200 | ForEach-Object {
@{ path = (Join-Path $folder "Folder $_"); peer = ''; name = ''; title = "Folder $_" }
})
$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') }
@@ -103,13 +114,105 @@ try {
$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('^{TAB}')
$keyboard.SendKeys('^{F1}')
Wait-Until {
![FilesShortcutWindow]::IsWindowVisible($heading) -or
![FilesShortcutWindow]::IsWindowVisible($rightHeading)
}
if (![FilesShortcutWindow]::IsWindowVisible($rightHeading)) {
throw 'Ctrl+Tab changed the active panel.'
}
$keyboard.SendKeys('{TAB}')
$keyboard.SendKeys('^{F1}')
Wait-Until { ![FilesShortcutWindow]::IsWindowVisible($rightHeading) }
$keyboard.SendKeys('^{F2}')
Wait-Until { [FilesShortcutWindow]::IsWindowVisible($rightHeading) }
$keyboard.SendKeys('{TAB}')
Wait-Until { ![FilesShortcutWindow]::IsWindowVisible($heading) }
if (![FilesShortcutWindow]::IsWindowVisible($rightHeading)) { throw 'Ctrl+F1 changed the inactive panel.' }
$rightPath = [FilesShortcutWindow]::GetDlgItem($window, 143)
$leftList = [FilesShortcutWindow]::GetDlgItem($window, 102)
$rightList = [FilesShortcutWindow]::GetDlgItem($window, 103)
$keyboard.SendKeys('^u')
Wait-Until {
(Read-Text ([FilesShortcutWindow]::GetDlgItem($window, 142))) -eq $folder -and
(Read-Text ([FilesShortcutWindow]::GetDlgItem($window, 143))) -eq (Join-Path $folder 'Four') -and
[FilesShortcutWindow]::IsWindowVisible($rightHeading)
}
$movedLeft = [FilesShortcutWindow+Rect]::new()
$movedRight = [FilesShortcutWindow+Rect]::new()
if (![FilesShortcutWindow]::GetWindowRect($rightList, [ref]$movedLeft) -or
![FilesShortcutWindow]::GetWindowRect($leftList, [ref]$movedRight) -or
$movedLeft.Right -gt $movedRight.Left -or
[FilesShortcutWindow]::IsWindowVisible($heading)) {
throw 'Ctrl+U did not move the visible panel lists with their modes.'
}
$keyboard.SendKeys('^3')
Wait-Until { (Read-Text $leftPath) -eq (Join-Path $folder 'Three') }
if ((Read-Text $rightPath) -ne $folder) { throw 'Ctrl+U did not preserve the active panel.' }
$keyboard.SendKeys('^u')
Wait-Until { [FilesShortcutWindow]::GetDlgItem($window, 142) -eq $leftPath }
$keyboard.SendKeys('^{F2}')
Wait-Until { [FilesShortcutWindow]::IsWindowVisible($heading) }
Write-Output 'Verified Ctrl+8 popup rows, Ctrl+4 navigation and Ctrl+F1/F2 panel modes.'
$keyboard.SendKeys('^9')
Wait-Until { (Read-ShortcutDialog) -ne [IntPtr]::Zero }
$dialog = Read-ShortcutDialog
$list = [FilesShortcutWindow]::GetDlgItem($dialog, 310)
Add-Type -AssemblyName System.Drawing
$bounds = [FilesShortcutWindow+Rect]::new()
if (![FilesShortcutWindow]::GetWindowRect($list, [ref]$bounds)) { throw 'Missing overflow list.' }
Start-Sleep -Milliseconds 150
$barWidth = [int][Math]::Round(12 * [FilesShortcutWindow]::GetDpiForWindow($list) / 96)
$bitmap = [Drawing.Bitmap]::new($barWidth, ($bounds.Bottom - $bounds.Top))
try {
$graphics = [Drawing.Graphics]::FromImage($bitmap)
try { $graphics.CopyFromScreen($bounds.Right, $bounds.Top, 0, 0, $bitmap.Size) }
finally { $graphics.Dispose() }
$background = $bitmap.GetPixel(0, 0)
$thumb = $bitmap.GetPixel(0, $barWidth + 1)
$trackColors = @(0..4 | ForEach-Object {
$x = $_
0..7 | ForEach-Object { $bitmap.GetPixel($x, [int]($bitmap.Height / 2) + $_).ToArgb() }
} | Sort-Object -Unique)
$hasArrow = {
param($y)
$center = [int][Math]::Floor($barWidth / 2)
@(0..($barWidth - 1) | Where-Object {
$bitmap.GetPixel($center, $y + $_).ToArgb() -eq $thumb.ToArgb()
}).Count -gt 0
}
if ($thumb.GetBrightness() -le $background.GetBrightness() -or $trackColors.Count -ne 2 -or
!(& $hasArrow 0) -or !(& $hasArrow ($bitmap.Height - $barWidth))) {
throw "Unexpected scrollbar pixels. Background $background, thumb $thumb, track colors $($trackColors.Count), arrows $(& $hasArrow 0)/$(& $hasArrow ($bitmap.Height - $barWidth))."
}
} finally { $bitmap.Dispose() }
$arrow = [FilesShortcutWindow+Point]::new()
$arrow.X = $bounds.Right + [int]($barWidth / 2)
$arrow.Y = $bounds.Bottom - [int]($barWidth / 2)
if (![FilesShortcutWindow]::ScreenToClient($dialog, [ref]$arrow)) { throw 'Cannot locate the down arrow.' }
$arrowPoint = [IntPtr](($arrow.Y -shl 16) -bor $arrow.X)
[void][FilesShortcutWindow]::Send($dialog, 0x0201, [IntPtr]1, $arrowPoint)
if ([FilesShortcutWindow]::Send($list, 0x018E, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -ne 1) {
throw 'The down arrow should scroll the list by one row.'
}
$grip = [FilesShortcutWindow+Point]::new()
$grip.X = $bounds.Right + [int]($barWidth / 2)
$grip.Y = $bounds.Top + $barWidth + 4
if (![FilesShortcutWindow]::ScreenToClient($dialog, [ref]$grip)) { throw 'Cannot locate the thumb.' }
$gripPoint = [IntPtr](($grip.Y -shl 16) -bor $grip.X)
$dragPoint = [IntPtr]((($grip.Y + 3 * $barWidth) -shl 16) -bor $grip.X)
[void][FilesShortcutWindow]::Send($dialog, 0x0201, [IntPtr]1, $gripPoint)
[void][FilesShortcutWindow]::Send($dialog, 0x0200, [IntPtr]1, $dragPoint)
[void][FilesShortcutWindow]::Send($dialog, 0x0202, [IntPtr]::Zero, $dragPoint)
if ([FilesShortcutWindow]::Send($list, 0x018E, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -le 1) {
throw 'Dragging the scrollbar thumb should advance the list.'
}
$keyboard.SendKeys('{ESC}')
Write-Output 'Verified folder shortcuts, panel swapping, and the rendered overflow scrollbar.'
} finally {
if ($previousDpi) { [void][FilesShortcutWindow]::SetThreadDpiAwarenessContext($previousDpi) }
if ($process -and !$process.HasExited) {
$keyboard.SendKeys('{ESC}')
if (!$process.CloseMainWindow() -or !$process.WaitForExit(2500)) { $process.Kill(); $process.WaitForExit() }
+14 -1
View File
@@ -54,10 +54,12 @@ public static class MarkdownUi {
keybd_event(0x12,0,2,UIntPtr.Zero);
SetForegroundWindow(window);
}
public static void CycleWindow() {
public static void CycleWindow(bool reverse = false) {
keybd_event(0x11,0,0,UIntPtr.Zero);
if (reverse) keybd_event(0x10,0,0,UIntPtr.Zero);
keybd_event(0x09,0,0,UIntPtr.Zero);
keybd_event(0x09,0,2,UIntPtr.Zero);
if (reverse) keybd_event(0x10,0,2,UIntPtr.Zero);
keybd_event(0x11,0,2,UIntPtr.Zero);
}
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
@@ -328,8 +330,19 @@ const value = 42;
Wait-Foreground $window
Browser 'cycle' '' 'Preview.md'
Wait-Foreground $child
Browser 'cycle-reverse' '' 'Other.md'
Wait-Foreground $window
Browser 'edit' '' 'Preview.md'
[void](Wait-For 'the first window to switch to Editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' })
[MarkdownUi]::CycleWindow($true)
Wait-Foreground $main
[MarkdownUi]::CycleWindow($true)
Wait-Foreground $child
Write-Output 'Verified backward Ctrl+Shift+Tab cycling through three windows and wrapping at Files.'
Browser 'close' '' 'Other.md'
[void](Wait-For 'Ctrl+W to close the Shift+click window' { ![MarkdownUi]::IsWindowVisible($child) })
Post (Scintilla $window) 0x100 0x75
Browser 'Перегляд Markdown' '' 'Preview.md'
Browser 'follow'
if ((Wait-For 'the in-place Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Other.md' }) -ne $window) {
throw 'A normal click did not stay in the same window.'
+10 -4
View File
@@ -3,7 +3,7 @@ import { writeFile } from 'node:fs/promises';
import { setTimeout as delay } from 'node:timers/promises';
const [port, scenario, artifact, title] = process.argv.slice(2);
const terminalScenario = ['terminal-enter', 'terminal-copy', 'terminal-select-output'].includes(scenario);
const terminalScenario = scenario.startsWith('terminal-');
let socket;
const pending = new Map();
let sequence = 0;
@@ -69,7 +69,10 @@ await new Promise((resolve, reject) => {
});
try {
if (scenario === 'terminal-select-output') {
if (scenario === 'terminal-startup-pause' || scenario === 'terminal-startup-resume') {
await waitFor(() => evaluate('typeof startTerminalFixture === "function"'), 'the delayed terminal page');
if (scenario === 'terminal-startup-resume') await evaluate('startTerminalFixture()');
} else if (scenario === 'terminal-select-output') {
const selection = await waitFor(() => evaluate(`(() => {
const marker = 'terminal-output-copy-fixture';
const buffer = terminal.buffer.active;
@@ -82,6 +85,8 @@ try {
})()`), 'the terminal output fixture');
assert.equal(selection, 'terminal-output-copy-fixture');
} else if (terminalScenario) {
assert.equal(await evaluate('terminal.options.cursorInactiveStyle'), 'none');
assert.equal(await evaluate('document.querySelectorAll(".xterm-cursor-outline").length'), 0);
await evaluate('document.querySelector(".xterm-helper-textarea").focus()');
const key = scenario === 'terminal-copy'
? { key:'Insert', code:'Insert', modifiers:2, windowsVirtualKeyCode:45 }
@@ -209,8 +214,9 @@ try {
} else if (scenario === 'back' || scenario === 'forward') {
await waitFor(() => evaluate(`!document.getElementById('${scenario}').disabled`), scenario);
await evaluate(`document.getElementById('${scenario}').click()`);
} else if (scenario === 'cycle') {
await command('Input.dispatchKeyEvent', {type:'keyDown', key:'Tab', code:'Tab', modifiers:2, windowsVirtualKeyCode:9});
} else if (scenario === 'cycle' || scenario === 'cycle-reverse') {
const modifiers = scenario === 'cycle-reverse' ? 10 : 2;
await command('Input.dispatchKeyEvent', {type:'keyDown', key:'Tab', code:'Tab', modifiers, windowsVirtualKeyCode:9});
} else if (scenario === 'close') {
await command('Input.dispatchKeyEvent', {type:'keyDown', key:'w', code:'KeyW', modifiers:2, windowsVirtualKeyCode:87});
} else {
+1 -1
View File
@@ -57,7 +57,7 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int)
return font;
};
dialogs.confirmExisting=[](HWND){return true;};
dialogs.confirmSave=[](HWND)->INT_PTR {return IDYES;};
dialogs.confirmSave=[](HWND,bool)->INT_PTR {return IDYES;};
dialogs.message=[](HWND,const wchar_t *message){log(message);};
dialogs.dismissOwned=[](HWND){return false;};
files::openTextWindow(owner,document,false,dialogs,&peer);
+133 -11
View File
@@ -1,4 +1,4 @@
param([Parameter(Mandatory)][string]$Executable,[switch]$KeyboardCursorOnly)
param([Parameter(Mandatory)][string]$Executable,[switch]$KeyboardCursorOnly,[switch]$CreateFileOnly)
$ErrorActionPreference='Stop'
Add-Type -AssemblyName System.Drawing
Add-Type @"
@@ -19,6 +19,21 @@ public static class SearchArrowTest {
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hwnd, IntPtr after, int x, int y, int w, int h, uint flags);
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
[DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr hwnd, IntPtr dc, uint flags);
[DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("user32.dll")] static extern int ReleaseDC(IntPtr hwnd, IntPtr dc);
[DllImport("user32.dll")] public static extern bool InvalidateRect(IntPtr hwnd, IntPtr rect, bool erase);
[DllImport("gdi32.dll")] static extern uint GetPixel(IntPtr dc, int x, int y);
[DllImport("gdi32.dll")] static extern bool SetPixelV(IntPtr dc, int x, int y, uint color);
public static bool EditorMenuProbe(IntPtr window, bool write) {
const uint color = 0x00ff00ff;
var dc = GetDC(window);
if (dc == IntPtr.Zero) throw new InvalidOperationException("Cannot sample the editor.");
try {
if (write && !SetPixelV(dc, 4, 4, color))
throw new InvalidOperationException("Cannot mark the editor menu.");
return GetPixel(dc, 4, 4) == color;
} finally { ReleaseDC(window, dc); }
}
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hwnd, out Rect rect);
[DllImport("user32.dll")] public static extern bool IsWindow(IntPtr hwnd);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hwnd);
@@ -242,7 +257,7 @@ foreach($name in 'A.txt','B.txt','C.txt','D.txt'){
$copy=Join-Path $scratch 'KSwitcher.Files.search-arrow-test.exe'
Copy-Item -LiteralPath $Executable -Destination $copy
$profile=[Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$keysToRestore='LeftPath','RightPath','LeftCursor','RightCursor','WindowPlacement'
$keysToRestore='LeftPath','RightPath','LeftCursor','RightCursor','WindowPlacement','FileStyles'
$saved=@{}
foreach($name in $keysToRestore){
if($name -in $profile.GetValueNames()){
@@ -256,6 +271,8 @@ try {
$profile.SetValue('RightPath',$rightFixture)
$profile.DeleteValue('LeftCursor',$false)
$profile.DeleteValue('RightCursor',$false)
$styles='[{"extension":".txt","background":3158064,"states":[{},{},{"background":3166352}]}]'
$profile.SetValue('FileStyles',[Text.Encoding]::UTF8.GetBytes($styles),'Binary')
$process=Start-Process -FilePath $copy -ArgumentList '--terminal-trace' -PassThru -WindowStyle Normal
$paintTrace=Join-Path ([IO.Path]::GetTempPath()) "KSwitcher.Files.terminal-trace-$($process.Id).log"
$previousDpi=[SearchArrowTest]::SetThreadDpiAwarenessContext([IntPtr](-4))
@@ -267,13 +284,117 @@ try {
[SearchArrowTest]::SendText($leftPanel,0x1A2,-1,'A.txt').ToInt64() -ge 0 -and
[SearchArrowTest]::SendText($rightPanel,0x1A2,-1,'A.txt').ToInt64() -ge 0
})
$clicks=if(!$KeyboardCursorOnly){
@(@{Panel=$leftPanel; Index=0},@{Panel=$rightPanel; Index=1},@{Panel=$rightPanel; Index=1})
if ($CreateFileOnly) {
function Assert-DialogSurface($Dialog, [int]$Red, [int]$Green) {
$bounds=Read-Bounds $Dialog
$bitmap=[Drawing.Bitmap]::new(1,1)
try {
$graphics=[Drawing.Graphics]::FromImage($bitmap)
try {
[void](Wait-Until {
$graphics.CopyFromScreen(($bounds.Left+4),($bounds.Top+4),0,0,$bitmap.Size)
$pixel=$bitmap.GetPixel(0,0)
$pixel.R -eq $Red -and $pixel.G -eq $Green -and $pixel.B -eq $Green
})
} finally { $graphics.Dispose() }
} finally { $bitmap.Dispose() }
}
$keyboard=New-Object -ComObject WScript.Shell
[void](Wait-Until { $keyboard.AppActivate($process.Id) })
$keyboard.SendKeys('+{F4}')
$open=Wait-Until { Find-Window '#32770' $process.Id 461 }
Assert-DialogSurface $open 192 192
Post $open 0x111 1
$editor=Wait-Until { Find-Window 'KSwitcher.Files.Text' $process.Id }
$title=[Text.StringBuilder]::new(1024)
[void][SearchArrowTest]::GetText($editor,0xD,$title.Capacity,$title)
if ($title.ToString() -notmatch '(New_File_[0-9-]+_[0-9.]+\.txt)$') { throw "Missing generated name in $title." }
$generated=$Matches[1]
if (Test-Path -LiteralPath (Join-Path $scratch $generated)) { throw 'Opening a draft created a file.' }
$control=Wait-Until { [SearchArrowTest]::FindWindowEx($editor,0,'Scintilla',[NullString]::Value) }
Start-Sleep -Milliseconds 150
if (![SearchArrowTest]::EditorMenuProbe($editor,$true)) { throw 'Cannot mark the editor menu for the repaint check.' }
foreach($ch in 'First'.ToCharArray()){Post $control 0x102 ([int]$ch)}
Post $control 0x100 13
foreach($ch in 'Second'.ToCharArray()){Post $control 0x102 ([int]$ch)}
[void](Wait-Until { [SearchArrowTest]::Send($control,2159,0,0).ToInt64() })
Start-Sleep -Milliseconds 150
$menuWasPreserved=[SearchArrowTest]::EditorMenuProbe($editor,$false)
[void][SearchArrowTest]::InvalidateRect($editor,0,$false)
if (!$menuWasPreserved) { throw 'Typing in a draft repainted the unchanged editor menu.' }
foreach($cancel in $true,$false) {
Post $control 0x100 27
$confirm=Wait-Until { Find-Window '#32770' $process.Id 6 }
Assert-DialogSurface $confirm 128 0
Post $confirm 0x111 6
$save=Wait-Until { Find-Window '#32770' $process.Id 464 }
Assert-DialogSurface $save 192 192
$name=[SearchArrowTest]::GetDlgItem($save,461)
$current=[Text.StringBuilder]::new(1024)
[void][SearchArrowTest]::GetText($name,0xD,$current.Capacity,$current)
if ($current.ToString() -ne $generated) { throw 'Save options did not carry the generated name.' }
if ($cancel) {
Post $save 0x111 2
[void](Wait-Until { ![SearchArrowTest]::IsWindow($save) -and [SearchArrowTest]::IsWindow($editor) })
continue
}
[void][SearchArrowTest]::SendText($name,0x0C,0,'created.txt')
[void][SearchArrowTest]::Send([SearchArrowTest]::GetDlgItem($save,464),0xF1,1,0)
[void][SearchArrowTest]::Send([SearchArrowTest]::GetDlgItem($save,472),0xF5,0,0)
Post $save 0x111 1
}
$result=Join-Path $scratch 'created.txt'
[void](Wait-Until { (Test-Path -LiteralPath $result) -and ![SearchArrowTest]::IsWindow($editor) })
if ([Convert]::ToHexString([IO.File]::ReadAllBytes($result)) -ne 'EFBBBF46697273740A5365636F6E64') {
throw 'The saved bytes must contain a UTF-8 BOM and LF line endings.'
}
Write-Output 'Verified Shift+F4, the generated name, Escape confirmation, cancellation, and Save options.'
return
}
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; Label='A.txt'},
@{Panel=$leftPanel; Index=0; Label='A.txt'},
@{Panel=$rightPanel; Index=1; Label='..'; UnfocusedStyle=$true},
@{Panel=$rightPanel; Index=1; Label='A.txt'})
}
$activeIndex=0
foreach($check in $clicks) {
$before=[SearchArrowTest]::Send($check.Panel,0x188,0,0).ToInt32()
$top=[SearchArrowTest]::Send($check.Panel,0x18E,0,0).ToInt32()
$row=if($before -eq $top){$top+1}else{$top}
$row=if($check.Label){[SearchArrowTest]::SendText($check.Panel,0x1A2,-1,$check.Label).ToInt32()}
elseif($before -eq $top){$top+1}else{$top}
if($row -lt 0 -or $row -eq $before){throw 'The click fixture must move the cursor.'}
$previousKey="$($check.Index)/$before"
$expected=@{"$($check.Index)/$row"='1'}
if($check.Index -ne $activeIndex){
$source=if($activeIndex -eq 0){$leftPanel}else{$rightPanel}
$sourceRow=[SearchArrowTest]::Send($source,0x188,0,0).ToInt32()
$expected["$activeIndex/$sourceRow"]='0'
}
if($check.Index -eq $activeIndex -or $check.UnfocusedStyle){$expected[$previousKey]='0'}
[void](Wait-Until { Test-Path -LiteralPath $paintTrace })
Start-Sleep -Milliseconds 150
$lineCount=@(Get-Content -LiteralPath $paintTrace).Count
@@ -281,14 +402,15 @@ try {
[void](Wait-Until { [SearchArrowTest]::Send($check.Panel,0x188,0,0).ToInt32() -eq $row })
Start-Sleep -Milliseconds 150
$highlight=Read-PanelHighlights $paintTrace $lineCount
$draws=@($highlight.Keys)
if("$($check.Index)/$row" -notin $draws -or $draws.Count -gt 3){
throw "Clicking a row repainted unrelated file rows. Drawn rows: $draws"
if($highlight.Count -ne $expected.Count -or
@($expected.Keys | Where-Object {$highlight[$_] -ne $expected[$_]}).Count){
throw "Unexpected cursor redraw. Expected rows: $($expected.Keys -join ', '). Drawn rows: $($highlight.Keys -join ', ')."
}
if($highlight["$($check.Index)/$row"] -ne '1' -or
($before -ge $top -and $highlight["$($check.Index)/$before"] -ne '0')){
throw 'The new row must be painted active and the previous visible row must lose its highlight.'
if($check.Index -ne $activeIndex -and (Get-Content -LiteralPath $paintTrace | Select-Object -Skip $lineCount |
Where-Object {$_ -match "^\d+ panel-draw $($check.Index) $before 1 "})){
throw 'The old row in the destination panel flashed as the active cursor.'
}
$activeIndex=$check.Index
}
if($clicks){Write-Output 'Verified file clicks repaint only cursor rows in the active pane and when changing panes.'}
Post $main 0x111 132
+40
View File
@@ -8,6 +8,8 @@
namespace fs = std::filesystem;
using ks::files::TextDocument;
using ks::files::TextEncoding;
using ks::files::TextLineEnding;
namespace
{
@@ -141,6 +143,43 @@ void sparseFile(const fs::path &file)
document.stage(index, "edited");
check(document.readPage(index) == "edited", "Stage an edit past 4 GiB");
}
void saveDraft(const fs::path &file)
{
TextDocument draft({});
check(draft.readPage(0).empty() && draft.pages()==1, "Start with an empty draft");
draft.stage(0,"one\r\ntwo\rthree\n");
writeFile(file,"existing");
bool rejected{};
try {draft.saveNew(file,{});}
catch(const std::exception &) {rejected=true;}
check(rejected && draft.modified() && readFile(file)=="existing", "Preserve a conflicting file and the draft");
fs::remove(file);
check(draft.saveNew(file,{TextEncoding::utf8,true,TextLineEnding::lf}), "Save a draft as a new file");
check(readFile(file)=="\xef\xbb\xbfone\ntwo\nthree\n" && draft.readPage(0)=="one\ntwo\nthree\n",
"Save a UTF-8 signature and normalize mixed line endings");
draft.stage(0,"after");
check(draft.save() && readFile(file)=="\xef\xbb\xbf" "after", "Edit normally after the first save");
const auto ansiFile=file.parent_path()/L"windows1252.txt";
TextDocument ansiDraft({});
ansiDraft.stage(0,"caf\xc3\xa9\n");
check(ansiDraft.saveNew(ansiFile,{TextEncoding::windows1252,false,TextLineEnding::crlf}),
"Save a draft in Windows-1252");
check(readFile(ansiFile)=="caf\xe9\r\n" && ansiDraft.readPage(0)=="caf\xc3\xa9\r\n",
"Round-trip Windows-1252 text and CRLF");
TextDocument ansiReader(ansiFile,false,TextEncoding::windows1252);
check(ansiReader.readPage(0)=="caf\xc3\xa9\r\n", "Open an existing file with an explicit code page");
const auto unicodeFile=file.parent_path()/L"utf16be.txt";
TextDocument unicodeDraft({});
unicodeDraft.stage(0,"a\n");
check(unicodeDraft.saveNew(unicodeFile,{TextEncoding::utf16be,true,TextLineEnding::cr}),
"Save a UTF-16 draft with a signature");
TextDocument unicodeReader(unicodeFile,false);
check(readFile(unicodeFile)==std::string("\xfe\xff\0a\0\r",6) && unicodeReader.readPage(0)=="a\r",
"Detect the UTF-16 signature and read CR line endings");
}
}
int main()
@@ -151,6 +190,7 @@ int main()
editsAcrossPages(fixture.directory / L"pages.txt");
unicodeBoundaries(fixture.directory / L"unicode.txt");
rejectExternalReplacement(fixture.directory / L"external.txt");
saveDraft(fixture.directory / L"created.txt");
sparseFile(fixture.directory / L"5gib.log");
std::cout << "Files text document regressions passed.\n";
}
+15
View File
@@ -403,6 +403,21 @@ int main(int argc, char **argv)
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,