Compare commits

..
14 Commits
Author SHA1 Message Date
agrynco 5cf0ff5140 Release KSwitcher v0.6.117 (#63) 2026-11-18 00:21:06 +02:00
agrynco 9c3de731ec Synchronize updater version and release package 2026-11-18 00:20:38 +02:00
agrynco 3b487d0af4 Record the v0.6.117 package and verify folder sizing shortcuts 2026-11-18 00:16:10 +02:00
agrynco 9c935fe4da Fix the history-host test build include path 2026-11-18 00:13:14 +02:00
agrynco 4f0a1b5f27 Prepare KSwitcher v0.6.117 with FTP support in Files 2026-11-18 00:11:08 +02:00
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
29 changed files with 2639 additions and 514 deletions

No files matched your search

+3 -2
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.6.113 LANGUAGES CXX RC)
project(KSwitcher VERSION 0.6.117 LANGUAGES CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
@@ -26,7 +26,7 @@ add_custom_target(check-files-search-arrow
DEPENDS KSwitcherFiles
VERBATIM)
target_include_directories(KSwitcherFiles PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include")
target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid)
target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet)
if(MSVC)
target_compile_options(KSwitcherFiles PRIVATE /utf-8)
else()
@@ -207,6 +207,7 @@ add_test(NAME chat-profile-regressions COMMAND KSwitcherChatProfileTests)
add_test(NAME lan-window-layout COMMAND KSwitcherChatProfileTests --lan-layout)
set_tests_properties(lan-window-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 30)
add_executable(KSwitcherHistoryHostTests tests/history_host.cpp)
target_include_directories(KSwitcherHistoryHostTests PRIVATE vendor)
target_link_libraries(KSwitcherHistoryHostTests PRIVATE kscore psapi)
set_target_properties(KSwitcherHistoryHostTests PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/history-host-fixture-$<CONFIG>")
add_dependencies(KSwitcherHistoryHostTests KSwitcher KSwitcherScreenshot)
+69 -9
View File
@@ -29,14 +29,51 @@ Warning і початковий фокус на No.
## Скорочення
- **FTP** у меню джерел (Alt+F1 для лівої панелі, Alt+F2 для правої)
відкриває список збережених підключень у вибраній панелі. Shift+F4
додає підключення, F4 редагує виділене, Enter відкриває його.
У формі вкажи назву, сервер, порт (типово 21), ім’я користувача й пароль.
Порожнє ім’я означає анонімний вхід. Паролі зберігаються локально
із захистом Windows DPAPI. Звичайний FTP передає дані без шифрування.
Після підключення панель показує справжній шлях початкового каталогу
сервера. Enter або подвійний клік на `..` відкриває батьківську папку.
У корені рядка `..` немає. Щоб повернутися до списку підключень,
вибери FTP в меню джерел панелі.
Назви файлів і папок передаються в UTF-8. Для старого сервера, який
використовує системну кодову сторінку Windows, увімкни в профілі
**Use Windows encoding for file names** і підключися знову.
- F5 копіює поточний або позначені файли й папки між локальною та
підключеною FTP-панелями в обидва боки. Призначенням є каталог іншої
панелі. Для одного елемента можна вказати ім’я копії в цьому каталозі.
Використовуються спільні діалоги Copy, прогресу та конфлікту імен.
Поточний файл записується під тимчасовим ім’ям до завершення передачі.
Для заміни файла FTP-сервер має приймати перейменування поверх нього.
- У підключеній FTP-панелі F3 та Enter відкривають файл у Viewer, а F4
відкриває Editor. Файл завантажується у тимчасову копію у фоні.
F2 в Editor передає зміни назад на FTP. Якщо сервер повідомляє інший
розмір або час зміни файла, запис скасовується, а правки лишаються в редакторі.
- У підключеній FTP-панелі F6 перейменовує один файл або папку в поточному
каталозі. Якщо нове ім’я зайняте, Files показує помилку. F8 запитує
підтвердження й видаляє вибрані елементи з FTP-сервера без кошика.
Для непорожньої папки Files окремо підтверджує видалення її вмісту.
- У меню Files і його списках, що випадають, стрілки вгору й вниз
переходять між першим і останнім пунктами циклічно та оминають розділювачі.
У меню джерел горизонтальна лінія відділяє FTP від локальних дисків,
а заголовок KSwitcher LAN відділяє LAN-ресурси від FTP.
Літера відкриває локальний диск, цифра 1 відкриває FTP. Для LAN-дисків
і Wake меню показує доступні цифри 2–9 і 0. Призначена цифра зберігається
до закриття меню, навіть коли оновлюється список LAN.
- Enter і подвійний клік відкривають папку в поточній панелі, а локальний
документ — у програмі, призначеній для його типу у Windows. EXE запускається
окремим процесом. BAT і CMD виконуються в поточній сесії вбудованого
термінала, а їхній вивід з’являється під панелями. Щоб відкрити файл із
панелі LAN, спочатку скопіюй його до локальної папки.
Після успішного відкриття локального файла через Windows його шлях
з’являється у виводі термінала й списку історії. Коли термінал неактивний,
його курсор приховано. При виборі
з історії у командний рядок підставляється команда, яка повторює відкриття.
- Коли командний рядок порожній, Shift+Enter відкриває поточний локальний
елемент через Windows.
Папка відкривається у Провіднику, файл виконує свою стандартну дію Windows.
@@ -50,6 +87,9 @@ Warning і початковий фокус на No.
Стрілки вліво й вправо переходять до першого й останнього рядків, коли
командний рядок порожній.
Клік оновлює підсвічування рядків курсора без перемальовування всієї панелі.
При кліку в іншу панель курсор відразу з’являється на вибраному рядку.
Попередній рядок цієї панелі оновлюється лише тоді, коли для неактивного
курсора він мав інше оформлення.
Меню й діалоги тимчасово приймають фокус. Ctrl+V і Shift+Insert вставляють
текст із буфера обміну в позицію курсора або замінюють виділення.
Enter виконує введену команду, якщо підказку не вибрано. Shift+Enter
@@ -130,13 +170,19 @@ Warning і початковий фокус на No.
- Ctrl+F вставляє повний шлях елемента під курсором активної панелі в позицію
курсора командного рядка або замінює виділення. Подвійні лапки додаються
лише до шляхів із пробілами. Для `..` вставляється шлях батьківської папки.
лише до шляхів із пробілами. На рядку `..` вставляється шлях папки,
відкритої в активній панелі.
- Ctrl+Enter вставляє лише назву файла або папки під курсором активної панелі
за тими ж правилами вставлення й лапок. Рядок `..` пропускається.
- Локальні й LAN-каталоги скануються у фоновому потоці. Під час переходу
активна панель показує «Loading folder…» і зберігає попередній список до
завершення сканування. Після переходу оновлюються шлях і список цієї панелі
та командний рядок. Сусідня панель не перемальовується через цей перехід.
- Локальні й LAN-каталоги скануються у фоновому потоці. Рядок стану активної
панелі показує «Reading» з лічильником прочитаних файлів і папок та
підказкою [Esc].
До завершення читання панель зберігає попередній список. Escape зупиняє
сканування активної панелі й відкриває прочитану частину папки. Якщо
папку ще не вдалося відкрити, попередній список залишається. Ctrl+R
повторює сканування, щоб отримати повний список. Після переходу
оновлюються шлях і список цієї панелі та командний рядок. Сусідня
панель не перемальовується через цей перехід.
Якщо надійшов новіший запит, результат попереднього
сканування пропускається. Після підтвердження UAC очікування списку
від підвищеного процесу теж відбувається у фоні.
@@ -219,6 +265,11 @@ Warning і початковий фокус на No.
- Ctrl+Tab циклічно перемикає фокус між Files, редакторами й переглядачами
у порядку їх відкриття. Ctrl+Shift+Tab обходить ті самі вікна у зворотному
порядку. Коли відкрито лише Files, активна панель не змінюється.
- Shift+F4 у локальній панелі відкриває Editor для наявного або нового файла.
Порожнє ім’я підставляє `New_File_<дата>_<час>.txt`. Новий файл з’являється
на диску після збереження. Esc після змін пропонує Save, Discard або Cancel.
Save для нового файла відкриває параметри імені, кодування, BOM та кінців
рядків. Скасування параметрів залишає текст у редакторі.
- F3 відкриває Markdown як форматований документ із таблицями, блоками коду,
інтерактивними чекбоксами списків і діаграмами Mermaid. Відмітки в перегляді
діють до повторного рендерингу або виходу з цього режиму. F4 відкриває текст
@@ -241,11 +292,19 @@ Warning і початковий фокус на No.
Для LAN зображення завантажуються у фоні, а файли за посиланнями — після
кліку. Mermaid працює офлайн. Якщо WebView2 недоступний або файл більший за
8 МіБ, F3 відкриває текстовий перегляд.
- Коли курсор на папці, F3 у фоні підраховує сумарний розмір файлів у ній
та вкладених папках. Якщо позначено папки, розмір рахується для кожної з
них окремо. Результат видно в колонці Size у широкому режимі та в рядку
стану, коли там увімкнено розмір. Це працює і в LAN-панелі. Посилання й
- F3 у фоні підраховує сумарний розмір файлів у папці та її підпапках.
На рядку `..` F3 рахує всі папки поточного списку, а за наявності
позначених папок в інших рядках рахує позначені папки. Без позначок
F3 рахує папку під курсором або відкриває файл. Папки обробляються по черзі,
і результат кожної видно в колонці Size у широкому режимі та в рядку
стану, коли там увімкнено розмір. Це працює і в LAN- та FTP-панелях. Посилання й
junction не обходяться. Недоступний вміст позначається як частковий результат.
Папки, які чекають на підрахунок, мають позначку Queued. Через дві секунди
підрахунку в рядку поточної папки з’являється спінер.
Пересування курсора в списку залишає спінер у рядку папки, яку ще рахують.
Esc скасовує поточний підрахунок і чергу активної панелі, залишаючи
вже обчислені розміри та поточний каталог.
Перехід до іншого каталогу чи джерела панелі скасовує підрахунок.
- F3 і F4 працюють і на панелі LAN. Файл завантажується у тимчасову копію
на диску у фоновому режимі. Збереження передає зміни назад на віддалений ПК.
Якщо розмір або час зміни віддаленого файла відрізняється від відкритої
@@ -357,6 +416,7 @@ Warning і початковий фокус на No.
- Після F5 або F6 успішно оброблені елементи коротко підсвічуються в панелі, що показує папку призначення. Підсвітка тексту відрізняється від курсора й не переносить фокус.
- У широкому режимі ширина під вирівняні розширення залежить від найдовшого розширення в поточній панелі. За вузької панелі залишай місце для імені та колонки Size.
Розділювач Size проходить по одній вертикалі в заголовку та списку, а праві краї підпису й значень вирівняні.
- Бірюзовий курсор поточного рядка видно в активній панелі. Кожна панель зберігає свою позицію курсора. Коли панелі видимі, F5 і F6 з командного рядка діють на активну панель.
- Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший.
+1 -2
View File
@@ -999,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
+43 -1
View File
@@ -1,5 +1,47 @@
# Latest Windows release
## v0.6.117 — 2026-11-18
- KSwitcher Files supports saved FTP connections in both panes. Browse UTF-8 file names, open or edit remote files with **F3/F4**, save with **F2**, copy between a local and FTP pane with **F5**, rename with **F6**, and permanently delete with **F8**.
- **F3** measures folders on local, LAN and FTP panes. On `..` it queues every folder in the current list. Waiting folders show **Queued** and the active folder shows a spinner after two seconds. **Esc** cancels the active pane’s calculation and queue.
- The source menu separates local drives, FTP and KSwitcher LAN. **1** opens FTP and the remaining displayed digits select LAN actions. Wide pane **Size** dividers align, and **Ctrl+F** on `..` inserts the open folder’s path.
**Українською.**
- KSwitcher Files підтримує збережені FTP-підключення в обох панелях. Назви файлів читаються в UTF-8. **F3/F4** відкривають перегляд і редактор, **F2** зберігає зміни, **F5** копіює між локальною та FTP-панелями, **F6** перейменовує, **F8** видаляє без кошика.
- **F3** рахує розмір локальних, LAN- і FTP-папок. На `..` до черги додаються всі папки списку. Папки в черзі мають позначку **Queued**, а біля поточної через дві секунди з’являється спінер. **Esc** скасовує підрахунок і чергу активної панелі.
- Меню джерел розділяє локальні диски, FTP і KSwitcher LAN. **1** відкриває FTP, решта показаних цифр вибирають LAN-дії. Розділювачі колонки **Size** вирівняні, а **Ctrl+F** на `..` вставляє шлях відкритої папки.
## 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.
@@ -468,7 +510,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 @@
99a86abd99b5d886e60eade0c2be6fc9a3a956456479e50799330f7d05393b57 KSwitcher-win-x64.zip
b11409bce6fcc98484107e6c56c13d3830b5c1c6d58515ab7f395ede30dc6d5b KSwitcher-win-x64.zip
+40 -40
View File
@@ -1,166 +1,166 @@
{
"version": "0.6.117",
"files": [
{
"path": "KSwitcher.exe",
"size": 2479104,
"sha256": "0127e3c73c0e5aa5e58c6347b7702439775841723ef28e644eb99e43851073b3"
"path": "KSwitcher.exe",
"sha256": "4ea5e71940d5cd1cbd062c6eead6a57d6c9a7b8a3884f2d8707267872643a55f"
},
{
"path": "KSwitcher.Config.exe",
"size": 2458112,
"sha256": "d65a7e8ff047f8f83674613aa0e0cd29d38beac2c590736d2c53510fded2c9ce"
"path": "KSwitcher.Config.exe",
"sha256": "3576d94c26dbed409dc12a13fb570d3dac5d35f8df1cf79761758a1e308e6b89"
},
{
"path": "KSwitcher.Screenshot.exe",
"size": 3060224,
"sha256": "5e4990d5a6aeca88d20b4cfe8af3f6c050f8a20eb27228f93ce822f73f0a862d"
"path": "KSwitcher.Screenshot.exe",
"sha256": "738a6c42f56bd44d3cd871d53d51aa9580c3a20825c5407d2bb36ce512fe2103"
},
{
"size": 4286976,
"path": "KSwitcher.Files.exe",
"size": 4216832,
"sha256": "2d43503ae5ff296858f5d7dabe39d994859f0dd8f4e0d44af292c8ff053ea50f"
"sha256": "f1231f85448b57771e6ce1f8e416282af8d9112f093bd05cb26881c79ccd5cc5"
},
{
"path": "WebView2Loader.dll",
"size": 194912,
"path": "WebView2Loader.dll",
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
},
{
"path": "terminal/addon-fit-LICENSE.txt",
"size": 1103,
"path": "terminal/addon-fit-LICENSE.txt",
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
},
{
"path": "terminal/addon-fit.js",
"size": 1521,
"path": "terminal/addon-fit.js",
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
},
{
"path": "terminal/index.html",
"size": 527,
"path": "terminal/index.html",
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
},
{
"path": "terminal/markdown-it-LICENSE.txt",
"size": 1073,
"path": "terminal/markdown-it-LICENSE.txt",
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473"
},
{
"path": "terminal/markdown-it.js",
"size": 100786,
"path": "terminal/markdown-it.js",
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
},
{
"path": "terminal/markdown.html",
"size": 3530,
"path": "terminal/markdown.html",
"sha256": "e5381c35fb254b558c8b869746e2e575c8ed53600611ac90597ed2dd80fa321c"
},
{
"path": "terminal/markdown.js",
"size": 15014,
"path": "terminal/markdown.js",
"sha256": "55c905afaf074e3253267a7c48a5ebca14edd7f15449fd85c0a884c34da22763"
},
{
"path": "terminal/mermaid-LICENSE.txt",
"size": 1089,
"path": "terminal/mermaid-LICENSE.txt",
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80"
},
{
"path": "terminal/mermaid.js",
"size": 5537838,
"path": "terminal/mermaid.js",
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3"
},
{
"size": 5065,
"path": "terminal/terminal.js",
"size": 5033,
"sha256": "0557d251962301940785690a3fc49475dd166bb7d0bd0417dc3279d1f1b3a98a"
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b"
},
{
"path": "terminal/xterm-LICENSE.txt",
"size": 1261,
"path": "terminal/xterm-LICENSE.txt",
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
},
{
"path": "terminal/xterm.css",
"size": 7112,
"path": "terminal/xterm.css",
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
},
{
"path": "terminal/xterm.js",
"size": 488663,
"path": "terminal/xterm.js",
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
},
{
"path": "LICENSE",
"size": 4401,
"path": "LICENSE",
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
},
{
"path": "json-LICENSE.txt",
"size": 1096,
"path": "json-LICENSE.txt",
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831"
},
{
"path": "files-text-license.txt",
"size": 883,
"path": "files-text-license.txt",
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
},
{
"size": 95317,
"path": "README.md",
"size": 95289,
"sha256": "fcbd14b6190dc2a3575a4bc4be7229540c647022cb038d33ec4ac22176c67a9e"
"sha256": "ea5016c6fa29a98bf9ebf103fcf27f1be091842ad3228b167d18b053fda767d8"
},
{
"path": "LAN-PREVIEW.md",
"size": 11577,
"path": "LAN-PREVIEW.md",
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930"
},
{
"path": "dictionaries/en.txt",
"size": 732485,
"path": "dictionaries/en.txt",
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9"
},
{
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"size": 20566,
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5"
},
{
"path": "dictionaries/README.md",
"size": 2265,
"path": "dictionaries/README.md",
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
},
{
"path": "dictionaries/ru.txt",
"size": 1109134,
"path": "dictionaries/ru.txt",
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849"
},
{
"path": "dictionaries/sources.json",
"size": 1280,
"path": "dictionaries/sources.json",
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
},
{
"path": "dictionaries/uk.txt",
"size": 940799,
"path": "dictionaries/uk.txt",
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
},
{
"path": "tools/README.txt",
"size": 993,
"path": "tools/README.txt",
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
},
{
"path": "tools/StayHere.exe",
"size": 133120,
"sha256": "4c773c10766de698cbaa4ee1c121e1962d83ec929801f0de13541141b96441f2"
"path": "tools/StayHere.exe",
"sha256": "ebe97d3b7f267632b90463358bcc2518cad12f43c1eb568d2749a08f88a4bd97"
},
{
"path": "tools/StayHere-README.md",
"size": 2796,
"path": "tools/StayHere-README.md",
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
}
],
"version": "0.6.113",
"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,113,0
PRODUCTVERSION 0,6,113,0
FILEVERSION 0,6,117,0
PRODUCTVERSION 0,6,117,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.113"
VALUE "FileVersion", "0.6.117"
END
END
BLOCK "VarFileInfo"
+69
View File
@@ -50,6 +50,41 @@ 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"
@@ -60,6 +95,7 @@ BEGIN
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
@@ -307,3 +343,36 @@ BEGIN
FAR_EDIT(325, 0, 12, 28, 361, 16)
LISTBOX 324, 12, 49, 361, 155, LBS_NOTIFY | LBS_OWNERDRAWFIXED | LBS_HASSTRINGS | LBS_NOINTEGRALHEIGHT | WS_TABSTOP
END
112 DIALOGEX 0, 0, 360, 186
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "FTP connection"
FONT 10, "Consolas"
BEGIN
LTEXT "&Name", 381, 16, 18, 328, 12
FAR_EDIT(382, ES_LEFT, 16, 31, 328, 15)
LTEXT "&Server", 383, 16, 49, 250, 12
LTEXT "Por&t", 384, 278, 49, 66, 12
FAR_EDIT(385, ES_LEFT, 16, 62, 250, 15)
FAR_EDIT(386, ES_LEFT | ES_NUMBER, 278, 62, 66, 15)
LTEXT "&User name (blank for anonymous)", 387, 16, 80, 328, 12
FAR_EDIT(388, ES_LEFT, 16, 93, 328, 15)
LTEXT "&Password", 389, 16, 111, 328, 12
EDITTEXT 390, 16, 124, 328, 15, ES_LEFT | ES_PASSWORD | ES_AUTOHSCROLL
AUTOCHECKBOX "Use &Windows encoding for file names", 392, 16, 144, 328, 14
LTEXT "", 391, 10, 161, 1, 1, NOT WS_VISIBLE
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 92, 164, 86, 18
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 182, 164, 86, 18
END
113 DIALOGEX 0, 0, 350, 73
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Rename"
FONT 10, "Consolas"
BEGIN
LTEXT "New name in the current FTP folder:", 210, 14, 15, 322, 12
FAR_EDIT(211, 0, 14, 29, 322, 18)
LTEXT "", 217, 10, 49, 1, 1, NOT WS_VISIBLE
CONTROL "&Rename", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 87, 51, 86, 18
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 177, 51, 86, 18
END
+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' },
});
+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;
+4 -3
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;
}
}
@@ -159,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);
+1 -1
View File
@@ -152,7 +152,7 @@ bool editFolderShortcut(HWND owner,FolderShortcutEdit &edit)
void addFolderShortcut(const Panel &panel,int digit)
{
if(panel.directory.empty()) return;
if(panel.directory.empty() || panel.ftp) return;
FolderShortcutEdit edit{{panel.directory,panel.peer?panel.peer->id:"",
panel.peer?panel.peer->name:L""},digit,{}};
if(editFolderShortcut(GetParent(panel.list),edit))
+217
View File
@@ -0,0 +1,217 @@
struct FtpProfile
{
std::wstring name, host, user;
INTERNET_PORT port=INTERNET_DEFAULT_FTP_PORT;
ks::Bytes secret;
bool legacyNames{};
};
std::vector<FtpProfile> ftpProfiles;
bool ftpProfilesLoaded{};
constexpr wchar_t ftpProfilesValue[]=L"FtpProfiles";
constexpr DWORD ftpProfilesMaxBytes=1024*1024;
const fs::path ftpRoot=L"\\";
std::wstring ftpPath(const fs::path &path)
{
auto value=path.native();
std::replace(value.begin(),value.end(),L'\\',L'/');
return value;
}
bool saveFtpProfiles(const std::vector<FtpProfile> &profiles)
{
auto rows=Json::array();
for(const auto &profile:profiles)
rows.push_back({{"name",ks::utf8(profile.name)},{"host",ks::utf8(profile.host)},
{"port",profile.port},{"user",ks::utf8(profile.user)},{"secret",profile.secret},
{"legacyNames",profile.legacyNames}});
const auto data=rows.dump();
return data.size()<=ftpProfilesMaxBytes &&
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,REG_BINARY,data.data(),
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
}
bool loadFtpProfiles()
{
if(ftpProfilesLoaded) return true;
DWORD bytes{};
const auto query=RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,
RRF_RT_REG_BINARY,nullptr,nullptr,&bytes);
if(query==ERROR_FILE_NOT_FOUND)
{
ftpProfilesLoaded=true;
return true;
}
if(query!=ERROR_SUCCESS || !bytes || bytes>ftpProfilesMaxBytes) return false;
std::string data(bytes,'\0');
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,RRF_RT_REG_BINARY,
nullptr,data.data(),&bytes)!=ERROR_SUCCESS) return false;
try
{
const auto rows=Json::parse(data.begin(),data.begin()+bytes);
if(!rows.is_array()) return false;
std::vector<FtpProfile> profiles;
for(const auto &row:rows)
{
const auto port=row.at("port").get<unsigned>();
if(!port || port>65535) return false;
FtpProfile profile{ks::wide(row.at("name")),ks::wide(row.at("host")),
ks::wide(row.at("user")),static_cast<INTERNET_PORT>(port),row.at("secret").get<ks::Bytes>(),
row.value("legacyNames",false)};
if(profile.name.empty() || profile.host.empty()) return false;
profiles.push_back(std::move(profile));
}
ftpProfiles=std::move(profiles);
ftpProfilesLoaded=true;
return true;
}
catch(const std::exception &) {return false;}
}
std::wstring ftpPassword(const FtpProfile &profile)
{
if(profile.secret.empty()) return {};
auto bytes=ks::unprotect(profile.secret);
if(bytes.size()%sizeof(wchar_t)) throw std::runtime_error("Invalid FTP password");
std::wstring password(bytes.size()/sizeof(wchar_t),L'\0');
std::copy(bytes.begin(),bytes.end(),reinterpret_cast<unsigned char*>(password.data()));
SecureZeroMemory(bytes.data(),bytes.size());
return password;
}
struct FtpHandle
{
HINTERNET value{};
~FtpHandle() {if(value) InternetCloseHandle(value);}
explicit FtpHandle(HINTERNET handle=nullptr):value(handle) {}
FtpHandle(const FtpHandle &)=delete;
FtpHandle &operator=(const FtpHandle &)=delete;
};
void requireFileOperation(bool success,DWORD error)
{
if(!success) throw std::system_error(error,std::system_category());
}
void checkFileOperation(bool success)
{
if(!success) requireFileOperation(false,GetLastError());
}
class FtpSession
{
FtpHandle internet_{InternetOpenW(L"KSwitcher Files",INTERNET_OPEN_TYPE_DIRECT,nullptr,nullptr,0)};
FtpHandle connection_;
fs::path current_;
UINT nameCodePage_;
public:
explicit FtpSession(const FtpProfile &profile):nameCodePage_(profile.legacyNames?GetACP():CP_UTF8)
{
checkFileOperation(internet_.value!=nullptr);
DWORD timeout=10000, retries=1;
InternetSetOptionW(internet_.value,INTERNET_OPTION_CONNECT_TIMEOUT,&timeout,sizeof(timeout));
InternetSetOptionW(internet_.value,INTERNET_OPTION_CONNECT_RETRIES,&retries,sizeof(retries));
InternetSetOptionW(internet_.value,INTERNET_OPTION_RECEIVE_TIMEOUT,&timeout,sizeof(timeout));
InternetSetOptionW(internet_.value,INTERNET_OPTION_SEND_TIMEOUT,&timeout,sizeof(timeout));
auto password=ftpPassword(profile);
const auto user=profile.user.empty()?(password.empty()?nullptr:L"anonymous"):profile.user.c_str();
connection_.value=InternetConnectW(internet_.value,profile.host.c_str(),profile.port,
user,password.empty()?nullptr:password.c_str(),INTERNET_SERVICE_FTP,INTERNET_FLAG_PASSIVE,0);
const auto error=GetLastError();
SecureZeroMemory(password.data(),password.size()*sizeof(wchar_t));
requireFileOperation(connection_.value!=nullptr,error);
if(!profile.legacyNames)
FtpCommandA(handle(),FALSE,0,"OPTS UTF8 ON",0,nullptr);
}
HINTERNET handle() const {return connection_.value;}
// WinINet's A entry points transfer FTP pathname bytes without a Unicode conversion.
std::wstring decodeName(std::string_view bytes) const
{
if(bytes.empty()) return {};
const auto length=static_cast<int>(bytes.size());
const auto count=MultiByteToWideChar(nameCodePage_,MB_ERR_INVALID_CHARS,bytes.data(),length,nullptr,0);
if(!count)
throw std::runtime_error("The FTP server returned a name in another encoding. Check the FTP connection's file name encoding.");
std::wstring name(count,L'\0');
checkFileOperation(MultiByteToWideChar(nameCodePage_,MB_ERR_INVALID_CHARS,bytes.data(),length,name.data(),count)>0);
return name;
}
std::string encodeName(const fs::path &path) const
{
const auto name=ftpPath(path);
if(name.empty()) return {};
const auto length=static_cast<int>(name.size());
BOOL substituted=FALSE;
const auto legacy=nameCodePage_!=CP_UTF8;
const auto flags=legacy?WC_NO_BEST_FIT_CHARS:WC_ERR_INVALID_CHARS;
const auto replacement=legacy?&substituted:nullptr;
const auto count=WideCharToMultiByte(nameCodePage_,flags,name.data(),length,nullptr,0,nullptr,replacement);
requireFileOperation(count>0 && !substituted,ERROR_NO_UNICODE_TRANSLATION);
std::string bytes(count,'\0');
checkFileOperation(WideCharToMultiByte(nameCodePage_,flags,name.data(),length,bytes.data(),count,nullptr,replacement)>0);
requireFileOperation(!substituted,ERROR_NO_UNICODE_TRANSLATION);
return bytes;
}
const fs::path &initialDirectory()
{
std::string bytes(32768,'\0');
DWORD length=static_cast<DWORD>(bytes.size());
checkFileOperation(FtpGetCurrentDirectoryA(handle(),bytes.data(),&length));
auto initial=decodeName(bytes.c_str());
if(initial.empty() || initial.front()!=L'/' || initial.find_first_of(L"\\\r\n")!=initial.npos)
throw std::system_error(ERROR_BAD_PATHNAME,std::system_category());
const auto first=initial.find_first_not_of(L'/');
if(first==initial.npos) current_=ftpRoot;
else
{
initial.erase(1,first-1);
std::replace(initial.begin(),initial.end(),L'/',L'\\');
current_=fs::path(initial).lexically_normal();
if(current_.has_relative_path() && !current_.has_filename()) current_=current_.parent_path();
}
return current_;
}
void setDirectory(const fs::path &path)
{
if(current_==path) return;
checkFileOperation(FtpSetCurrentDirectoryA(handle(),encodeName(path).c_str()));
current_=path;
}
};
DWORD listFtpDirectory(FtpSession &session,const fs::path &directory,const FileVisitor &visit,
std::stop_token stop={})
{
if(stop.stop_requested()) return ERROR_CANCELLED;
session.setDirectory(directory);
if(stop.stop_requested()) return ERROR_CANCELLED;
WIN32_FIND_DATAA entry{};
const FtpHandle search{FtpFindFirstFileA(session.handle(),nullptr,&entry,
INTERNET_FLAG_RELOAD|INTERNET_FLAG_NO_CACHE_WRITE,0)};
if(!search.value) return GetLastError();
do
{
const auto name=session.decodeName(entry.cFileName);
if(name.empty() || name==L"." || name==L".." || name.find_first_of(L"/\\:\r\n")!=name.npos)
continue;
ULARGE_INTEGER modified{}, size{};
FILETIME utc{};
if(LocalFileTimeToFileTime(&entry.ftLastWriteTime,&utc))
{
modified.HighPart=utc.dwHighDateTime;
modified.LowPart=utc.dwLowDateTime;
}
size.HighPart=entry.nFileSizeHigh;
size.LowPart=entry.nFileSizeLow;
if(!visit(directory/name,{entry.dwFileAttributes,size.QuadPart,modified.QuadPart}))
return ERROR_CANCELLED;
} while(!stop.stop_requested() && InternetFindNextFileA(search.value,&entry));
return stop.stop_requested()?ERROR_CANCELLED:GetLastError();
}
+194
View File
@@ -0,0 +1,194 @@
FileEntries ftpChildren(FtpSession &session,const fs::path &directory,const std::atomic_bool *canceled=nullptr)
{
FileEntries entries;
const auto error=listFtpDirectory(session,directory,[&](const fs::path &path,const FileInfo &info)
{
if(canceled && *canceled) return false;
entries.emplace_back(path,info);
return true;
});
requireFileOperation(error==ERROR_NO_MORE_FILES,error);
return entries;
}
std::optional<FileInfo> ftpEntry(const FileEntries &entries,const fs::path &path)
{
const auto entry=std::find_if(entries.begin(),entries.end(),
[&](const auto &item){return item.first==path;});
return entry==entries.end()?std::nullopt:std::optional<FileInfo>(entry->second);
}
void renameFtpEntry(FtpSession &ftp,const fs::path &source,const fs::path &target)
{
ftp.setDirectory(source.parent_path());
const auto oldName=ftp.encodeName(source.filename());
const auto newName=ftp.encodeName(target.filename());
checkFileOperation(FtpRenameFileA(ftp.handle(),oldName.c_str(),newName.c_str()));
}
struct CopyHost
{
std::optional<FilesConnection> files;
std::optional<FtpSession> ftp;
fs::path listedDirectory;
FileEntries listedEntries;
CopyHost(const FilesPeer *peer,const std::optional<FtpProfile> &profile)
{
if(profile) ftp.emplace(*profile);
else files.emplace(peer);
}
const FileEntries &ftpListing(const fs::path &path,const std::atomic_bool &canceled)
{
if(path!=listedDirectory)
{
listedEntries=ftpChildren(*ftp,path,&canceled);
listedDirectory=path;
}
return listedEntries;
}
std::optional<FileInfo> stat(const fs::path &path,const std::atomic_bool &canceled)
{
return ftp?ftpEntry(ftpListing(path.parent_path(),canceled),path):statFile(*files,path);
}
FileEntries children(const fs::path &path,const std::atomic_bool &canceled)
{
return ftp?ftpListing(path,canceled):childrenOf(*files,path);
}
void makeDirectory(const fs::path &path)
{
if(!ftp)
{
checkFileReply(files->call(fileRequest("mkdir",path)));
return;
}
ftp->setDirectory(path.parent_path());
checkFileOperation(FtpCreateDirectoryA(ftp->handle(),ftp->encodeName(path.filename()).c_str()));
listedDirectory.clear();
}
void remove(const fs::path &path,bool permanent,DWORD attributes,bool readOnly)
{
if(ftp)
{
ftp->setDirectory(path.parent_path());
const auto name=ftp->encodeName(path.filename());
checkFileOperation(attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_DIRECTORY)?
FtpRemoveDirectoryA(ftp->handle(),name.c_str()):FtpDeleteFileA(ftp->handle(),name.c_str()));
return;
}
auto request=fileRequest(permanent?"remove":"recycle",path);
request["readOnly"]=readOnly;
checkFileReply(files->call(request));
}
};
constexpr DWORD ftpCopyFlags=INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_RELOAD|INTERNET_FLAG_NO_CACHE_WRITE;
void downloadFtpFile(FtpSession &ftp,FilesConnection &local,const fs::path &source,const fs::path &target,
const FileInfo &info,bool replace,const ks::lan::FileProgress &progress)
{
ftp.setDirectory(source.parent_path());
const FtpHandle input{FtpOpenFileA(ftp.handle(),ftp.encodeName(source.filename()).c_str(),GENERIC_READ,ftpCopyFlags,0)};
checkFileOperation(input.value!=nullptr);
auto upload=fileRequest("openWrite",target);
upload["transfer"]=ks::lan::randomHex(32);
upload["size"]=info.size;
try
{
const auto output=local.call(upload);
checkFileReply(output);
requireFileOperation(output.value("offset",uint64_t{1})==0,ERROR_FILE_INVALID);
uint64_t done=0;
ks::Bytes bytes(ks::lan::FileChunk);
while(!progress || progress(done,info.size))
{
DWORD read{};
checkFileOperation(InternetReadFile(input.value,bytes.data(),static_cast<DWORD>(bytes.size()),&read));
if(!read)
{
requireFileOperation(done==info.size,ERROR_FILE_INVALID);
requireFileOperation(!progress || progress(done,info.size),ERROR_CANCELLED);
checkFileReply(local.call({{"action","commit"},{"replace",replace},{"modified",info.modified}}));
return;
}
requireFileOperation(read<=info.size-done,ERROR_FILE_INVALID);
checkFileReply(local.call({{"action","write"},
{"data",Json::binary(ks::Bytes(bytes.begin(),bytes.begin()+read))}}));
done+=read;
}
requireFileOperation(false,ERROR_CANCELLED);
}
catch(...)
{
local.call({{"action","abort"}});
throw;
}
}
FileInfo uploadFtpFile(FilesConnection &local,FtpSession &ftp,const fs::path &source,const fs::path &target,
const FileInfo &info,bool replace,const ks::lan::FileProgress &progress,
const ks::files::RemoteTextRevision *expected=nullptr)
{
const auto directory=target.parent_path();
const auto temporary=directory/ks::wide("kswitcher-"+ks::lan::randomHex(16)+".partial");
auto open=fileRequest("openRead",source);
open["size"]=info.size;
open["modified"]=info.modified;
checkFileReply(local.call(open));
ftp.setDirectory(directory);
const auto stage=ftp.encodeName(temporary.filename());
bool staged=false;
try
{
uint64_t done=0;
{
FtpHandle output{FtpOpenFileA(ftp.handle(),stage.c_str(),GENERIC_WRITE,ftpCopyFlags,0)};
checkFileOperation(output.value!=nullptr);
staged=true;
for(;;)
{
requireFileOperation(progress(done,info.size),ERROR_CANCELLED);
const auto packet=local.call({{"action","read"}});
checkFileReply(packet);
const auto &bytes=packet.at("data").get_binary();
if(bytes.empty()) break;
requireFileOperation(bytes.size()<=info.size-done,ERROR_FILE_INVALID);
for(DWORD offset=0;offset<bytes.size();)
{
DWORD written{};
checkFileOperation(InternetWriteFile(output.value,bytes.data()+offset,
static_cast<DWORD>(bytes.size()-offset),&written));
requireFileOperation(written!=0,ERROR_WRITE_FAULT);
offset+=written;
}
done+=bytes.size();
}
requireFileOperation(done==info.size,ERROR_FILE_INVALID);
checkFileOperation(InternetCloseHandle(output.value));
output.value=nullptr;
}
checkFileReply(local.call({{"action","closeRead"}}));
const auto entries=ftpChildren(ftp,directory);
const auto uploaded=ftpEntry(entries,temporary);
requireFileOperation(uploaded && uploaded->size==done,ERROR_WRITE_FAULT);
const auto existing=ftpEntry(entries,target);
if(expected && (!existing || existing->size!=expected->size || existing->modified!=expected->modified))
throw std::runtime_error("The FTP file changed since it was opened. Your edits are still in the editor.");
if(existing)
requireFileOperation(replace && !(existing->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)),
ERROR_ALREADY_EXISTS);
requireFileOperation(progress(done,info.size),ERROR_CANCELLED);
renameFtpEntry(ftp,temporary,target);
return *uploaded;
}
catch(...)
{
if(staged) FtpDeleteFileA(ftp.handle(),stage.c_str());
throw;
}
}
+129
View File
@@ -0,0 +1,129 @@
namespace ftpDialog
{
constexpr int name=382, host=385, port=386, user=388, password=390, footer=391, legacy=392;
std::wstring trim(std::wstring value)
{
const auto first=value.find_first_not_of(L" \t\r\n");
if(first==value.npos) return {};
return value.substr(first,value.find_last_not_of(L" \t\r\n")-first+1);
}
struct Edit
{
FtpProfile profile;
std::optional<size_t> index;
};
INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" FTP connection ",false,{footer}))
return painted;
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
auto &profile=reinterpret_cast<Edit*>(lp)->profile;
prepareCopyDialog(dialog);
layoutDialogContent(dialog,381);
for(const auto id:{381,383,384,387,389,legacy,IDOK,IDCANCEL})
SendDlgItemMessageW(dialog,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
for(const auto id:{name,host,user,password})
SendDlgItemMessageW(dialog,id,EM_SETLIMITTEXT,255,0);
SendDlgItemMessageW(dialog,port,EM_SETLIMITTEXT,5,0);
SetDlgItemTextW(dialog,name,profile.name.c_str());
SetDlgItemTextW(dialog,host,profile.host.c_str());
SetDlgItemTextW(dialog,port,std::to_wstring(profile.port).c_str());
SetDlgItemTextW(dialog,user,profile.user.c_str());
installFarCheckbox(GetDlgItem(dialog,legacy),FarCheckboxSurface::gray);
CheckDlgButton(dialog,legacy,profile.legacyNames?BST_CHECKED:BST_UNCHECKED);
try
{
auto secret=ftpPassword(profile);
SetDlgItemTextW(dialog,password,secret.c_str());
SecureZeroMemory(secret.data(),secret.size()*sizeof(wchar_t));
}
catch(const std::exception &)
{
SetWindowTextW(GetDlgItem(dialog,389),L"&Password (re-enter to replace saved password)");
}
layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL});
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
auto &edit=*reinterpret_cast<Edit*>(GetWindowLongPtrW(dialog,DWLP_USER));
const auto invalid=[&](int field,const wchar_t *message)
{
showFilesNotice(dialog,message,L"FTP connection");
SetFocus(GetDlgItem(dialog,field));
return TRUE;
};
FtpProfile profile;
profile.legacyNames=IsDlgButtonChecked(dialog,legacy)==BST_CHECKED;
profile.name=trim(shortcutField(dialog,name));
if(profile.name.empty() || profile.name==L".." || profile.name.find_first_of(L"\r\n\t")!=profile.name.npos)
return invalid(name,L"Enter a name for this connection.");
for(size_t i=0;i<ftpProfiles.size();++i)
if(edit.index!=i && CompareStringOrdinal(ftpProfiles[i].name.c_str(),-1,profile.name.c_str(),-1,TRUE)==CSTR_EQUAL)
return invalid(name,L"A connection with this name already exists.");
profile.host=trim(shortcutField(dialog,host));
if(profile.host.empty() || profile.host.find_first_of(L" /\\@\t\r\n")!=profile.host.npos)
return invalid(host,L"Enter the server host name or IP address.");
const auto value=shortcutField(dialog,port);
const auto number=value.empty() || value.find_first_not_of(L"0123456789")!=value.npos?0:std::stoul(value);
if(!number || number>65535) return invalid(port,L"Enter a port from 1 to 65535.");
profile.port=static_cast<INTERNET_PORT>(number);
profile.user=shortcutField(dialog,user);
if(profile.user.find_first_of(L"\r\n")!=profile.user.npos)
return invalid(user,L"Enter the user name on one line.");
try
{
auto plain=shortcutField(dialog,password);
if(!plain.empty())
{
const auto start=reinterpret_cast<const unsigned char*>(plain.data());
ks::Bytes bytes(start,start+plain.size()*sizeof(wchar_t));
SecureZeroMemory(plain.data(),plain.size()*sizeof(wchar_t));
profile.secret=ks::protect(bytes);
SecureZeroMemory(bytes.data(),bytes.size());
}
auto updated=ftpProfiles;
if(edit.index) updated[*edit.index]=std::move(profile);
else updated.push_back(std::move(profile));
if(saveFtpProfiles(updated))
{
ftpProfiles=std::move(updated);
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
}
catch(const std::exception &) {}
showFilesNotice(dialog,L"Could not save the FTP connection.",L"FTP connection");
return TRUE;
}
}
void editFtpProfile(Panel &panel,bool create)
{
ftpDialog::Edit edit;
if(!create)
{
const auto row=currentPanelRow(panel);
if(row<0 || static_cast<size_t>(row)>=ftpProfiles.size()) return;
edit.index=static_cast<size_t>(row);
edit.profile=ftpProfiles[*edit.index];
}
const auto owner=GetParent(panel.list);
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(112),owner,
ftpDialog::procedure,reinterpret_cast<LPARAM>(&edit))!=IDOK) return;
for(auto &other:panels)
{
if(!ftpProfileList(other) || other.scan.valid()) continue;
const auto selection=&other==&panel?ftpRoot/std::to_wstring(edit.index.value_or(ftpProfiles.size()-1)):fs::path{};
showFtpProfiles(other,selection);
}
}
+1067 -271
View File
File diff suppressed because it is too large. Load diff
+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,
+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;
};
}
+207 -97
View File
@@ -582,12 +582,59 @@ INT_PTR CALLBACK searchDialog(HWND dialog, UINT message, WPARAM wparam, LPARAM l
return TRUE;
}
RemoteTextSource lanTextSource(const lan::FilesPeer &peer)
{
return {peer.id,peer.name,
[peer](const std::filesystem::path &original,const std::filesystem::path &cache,
bool edit,const RemoteTextSource::Progress &progress,uint64_t sizeLimit)
{
lan::FilesConnection source(&peer),target;
const auto info=source.call(lan::fileRequest("stat",original));
lan::checkFileReply(info);
const bool canCommit=info.value("editCommit",false);
const bool readOnly=info.at("attributes").get<DWORD>()&FILE_ATTRIBUTE_READONLY;
if(edit && !canCommit)
throw std::runtime_error("Update KSwitcher on the remote computer to edit this file.");
if(edit && readOnly) throw std::runtime_error("The remote file is read-only.");
const RemoteTextRevision revision{info.at("size"),info.at("modified"),canCommit && !readOnly};
if(revision.size>sizeLimit) throw std::runtime_error("The image is too large to preview.");
try
{
lan::streamFile(source,target,peer.id,original,cache,revision.size,revision.modified,false,false,progress);
}
catch(...)
{
target.call({{"action","abort"}});
throw;
}
return revision;
},
[peer](const std::filesystem::path &original,const std::filesystem::path &cache,
const RemoteTextRevision &revision)
{
lan::FilesConnection source,target(&peer);
const auto info=source.call(lan::fileRequest("stat",cache));
lan::checkFileReply(info);
const RemoteTextRevision local{info.at("size"),info.at("modified"),revision.editable};
const lan::FileRevision expected{revision.size,revision.modified};
try { lan::streamFile(source,target,"Files editor",cache,original,local.size,local.modified,true,false,{},&expected); }
catch(const std::system_error &error)
{
if(error.code().value()==ERROR_FILE_INVALID)
throw std::runtime_error("The remote file changed since it was opened. Your edits are still in the editor.");
throw;
}
return local;
}};
}
struct RemoteTextFile
{
lan::FilesPeer peer;
RemoteTextSource source;
std::filesystem::path original,cache;
lan::FileRevision revision{};
bool editable{};
RemoteTextRevision revision{};
RemoteTextFile(const RemoteTextSource &backend,const std::filesystem::path &path):source(backend),original(path) {}
~RemoteTextFile()
{
@@ -597,57 +644,22 @@ struct RemoteTextFile
std::filesystem::remove(cache.parent_path(),ignored);
}
static lan::FileRevision stat(lan::FilesConnection &host,const std::filesystem::path &path)
{
const auto reply=host.call(lan::fileRequest("stat",path));
lan::checkFileReply(reply);
return {reply.at("size").get<uint64_t>(),reply.at("modified").get<uint64_t>()};
}
void download(bool edit,const lan::FileProgress &progress,uint64_t sizeLimit=UINT64_MAX)
void download(bool edit,const RemoteTextSource::Progress &progress,uint64_t sizeLimit=UINT64_MAX)
{
GUID id{};
wchar_t name[40]{};
if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,40))
throw std::runtime_error("Cannot create a temporary directory for the LAN file.");
throw std::runtime_error("Cannot create a temporary directory for the remote file.");
const auto directory=std::filesystem::temp_directory_path()/(L"ks-files-edit-"+std::wstring(name));
if(!std::filesystem::create_directory(directory))
throw std::runtime_error("Cannot create a temporary directory for the LAN file.");
cache=directory/original.filename();
lan::FilesConnection source(&peer),target;
const auto info=source.call(lan::fileRequest("stat",original));
lan::checkFileReply(info);
editable=info.value("editCommit",false) &&
!(info.at("attributes").get<DWORD>()&FILE_ATTRIBUTE_READONLY);
if(edit && !info.value("editCommit",false))
throw std::runtime_error("Update KSwitcher on the remote computer to edit this file.");
if(edit && (info.at("attributes").get<DWORD>()&FILE_ATTRIBUTE_READONLY))
throw std::runtime_error("The remote file is read-only.");
revision={info.at("size"),info.at("modified")};
if(revision.size>sizeLimit) throw std::runtime_error("The image is too large to preview.");
try
{
lan::streamFile(source,target,peer.id,original,cache,revision.size,revision.modified,false,false,progress);
}
catch(...)
{
target.call({{"action","abort"}});
throw;
}
throw std::runtime_error("Cannot create a temporary directory for the remote file.");
cache=directory/L"content";
revision=source.download(original,cache,edit,progress,sizeLimit);
}
void upload()
{
lan::FilesConnection source,target(&peer);
const auto local=stat(source,cache);
try { lan::streamFile(source,target,"Files editor",cache,original,local.size,local.modified,true,false,{},&revision); }
catch(const std::system_error &error)
{
if(error.code().value()==ERROR_FILE_INVALID)
throw std::runtime_error("The remote file changed since it was opened. Your edits are still in the editor.");
throw;
}
revision=local;
revision=source.upload(original,cache,revision);
}
};
@@ -688,7 +700,7 @@ std::filesystem::path markdownTarget(const std::filesystem::path &document,std::
return (document.parent_path()/relative).lexically_normal();
}
std::string markdownImage(const std::filesystem::path &path,const lan::FilesPeer *peer,
std::string markdownImage(const std::filesystem::path &path,const RemoteTextSource *backend,
const std::shared_ptr<std::atomic<bool>> &cancel)
{
auto extension=path.extension().wstring();
@@ -702,10 +714,10 @@ std::string markdownImage(const std::filesystem::path &path,const lan::FilesPeer
constexpr uint64_t limit=16*1024*1024;
auto source=path;
std::optional<RemoteTextFile> fetched;
if(peer)
if(backend)
{
if(*cancel) return {};
fetched.emplace(RemoteTextFile{*peer,path});
fetched.emplace(*backend,path);
fetched->download(false,[&](uint64_t,uint64_t){return !*cancel;},limit);
source=fetched->cache;
}
@@ -728,14 +740,19 @@ std::string markdownImage(const std::filesystem::path &path,const lan::FilesPeer
class TextWindow
{
public:
TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const lan::FilesPeer *peer,
std::string_view fragment)
: original(std::move(path)), peerId(peer?peer->id:""), filename(original.filename().wstring()),
edit(editable), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const RemoteTextSource *backend,
std::string_view fragment,TextOpenOptions options)
: original(std::move(path)), peerId(backend?backend->id:""), filename(original.filename().wstring()),
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);
if (backend) remote=std::make_unique<RemoteTextFile>(*backend,original);
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]{};
@@ -764,6 +781,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;
@@ -856,6 +876,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();
@@ -1342,22 +1365,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;
@@ -1384,6 +1410,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.");
@@ -1392,6 +1426,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();
@@ -1408,7 +1448,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;
@@ -1424,9 +1464,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;
@@ -1438,7 +1479,7 @@ void TextWindow::toggleMode()
// The local LAN cache may already contain changes from a failed upload.
if (uploadPending)
{
auto refreshed = std::make_unique<RemoteTextFile>(RemoteTextFile{remote->peer,original});
auto refreshed = std::make_unique<RemoteTextFile>(remote->source,original);
refreshed->download(false,{});
auto replacement = std::make_unique<TextDocument>(refreshed->cache,false);
document.reset();
@@ -1452,7 +1493,7 @@ void TextWindow::toggleMode()
void TextWindow::changeMode()
{
if (!edit && remote && !remote->editable)
if (!edit && remote && !remote->revision.editable)
throw std::runtime_error("The remote file does not support editing.");
auto replacement = std::make_unique<TextDocument>(remote ? remote->cache : original, !edit);
const auto caret = send(SCI_GETCURRENTPOS);
@@ -1476,7 +1517,7 @@ void TextWindow::changeMode()
void TextWindow::updateTitle()
{
const auto title = std::wstring(edit ? L"Editor — " : L"Viewer — ") +
(remote ? remote->peer.name + L" · " : std::wstring{}) + original.wstring();
(remote ? remote->source.name + L" · " : std::wstring{}) + original.wstring();
SetWindowTextW(window,title.c_str());
}
@@ -1745,8 +1786,10 @@ void TextWindow::navigatePreview(PreviewLink request)
if(edit || navigation.valid() || navigationHistory.empty()) return;
if(request.newWindow)
{
openTextWindow(window,request.target.path,false,search.style,remote?&remote->peer:nullptr,
request.target.fragment,true);
if(remote)
openRemoteTextWindow(window,request.target.path,false,search.style,remote->source,request.target.fragment,true);
else
openTextWindow(window,request.target.path,false,search.style,nullptr,request.target.fragment,true);
return;
}
if((request.direction<0 && navigationIndex==0) ||
@@ -1762,13 +1805,13 @@ void TextWindow::navigatePreview(PreviewLink request)
if(destination.path==original || !remote) { showLocation(nullptr); return; }
auto cancel=std::make_shared<std::atomic<bool>>(false);
std::packaged_task<std::unique_ptr<RemoteTextFile>()> task(
[peer=remote->peer,path=destination.path,cancel] {
auto file=std::make_unique<RemoteTextFile>(RemoteTextFile{peer,path});
[backend=remote->source,path=destination.path,cancel] {
auto file=std::make_unique<RemoteTextFile>(backend,path);
file->download(false,[cancel](uint64_t,uint64_t){return !*cancel;});
return file;
});
if(!SetTimer(window,navigationTimer,75,nullptr))
throw std::runtime_error("Cannot start the LAN navigation timer.");
throw std::runtime_error("Cannot start the remote navigation timer.");
try
{
auto result=task.get_future();
@@ -1842,8 +1885,8 @@ void TextWindow::pollImages()
activeImage=std::move(imageQueue.front());
imageQueue.pop_front();
std::packaged_task<std::string()> task(
[path=activeImage.path,peer=remote?std::optional(remote->peer):std::nullopt,cancel=cancelImages] {
return markdownImage(path,peer?&*peer:nullptr,cancel);
[path=activeImage.path,backend=remote?std::optional(remote->source):std::nullopt,cancel=cancelImages] {
return markdownImage(path,backend?&*backend:nullptr,cancel);
});
image=task.get_future();
std::thread(std::move(task)).detach();
@@ -1861,6 +1904,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{};
@@ -1870,12 +1965,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();
@@ -1904,27 +1999,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);
@@ -2044,6 +2139,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>(""));
@@ -2051,6 +2147,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))
{
@@ -2058,8 +2155,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)))
@@ -2079,7 +2176,7 @@ void TextWindow::notify(const SCNotification &notice)
case SCN_UPDATEUI:
case SCN_SAVEPOINTREACHED:
case SCN_SAVEPOINTLEFT:
invalidate();
invalidateStatus();
break;
}
}
@@ -2188,7 +2285,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
self->applyPreferences();
self->send(SCI_SETREADONLY,TRUE);
if(!SetTimer(window,openTimer,75,nullptr))
throw std::runtime_error("Cannot start the LAN file timer.");
throw std::runtime_error("Cannot start the remote file timer.");
self->opening=std::async(std::launch::async,[state=self.get()]
{
state->remote->download(state->edit,[state](uint64_t,uint64_t){return !state->cancelOpen;});
@@ -2431,9 +2528,9 @@ bool cycleTextWindows(HWND current,bool reverse)
return true;
}
HWND findOpenDocument(const std::filesystem::path &path,const lan::FilesPeer *peer)
HWND findOpenDocument(const std::filesystem::path &path,std::string_view id)
{
const auto identity=documentIdentity(path,peer?peer->id:"");
const auto identity=documentIdentity(path,id);
struct Search
{
COPYDATASTRUCT query;
@@ -2457,16 +2554,16 @@ HWND findOpenDocument(const std::filesystem::path &path,const lan::FilesPeer *pe
return search.match;
}
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const lan::FilesPeer *peer,std::string_view fragment,bool newWindow)
static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const RemoteTextSource *backend,std::string_view fragment,bool newWindow,TextOpenOptions options)
{
try
{
if(!textWindows.contains(owner)) filesOwner=owner;
std::error_code error;
const auto identity=peer?path.lexically_normal():std::filesystem::weakly_canonical(path,error);
const auto identity=backend?path.lexically_normal():std::filesystem::weakly_canonical(path,error);
const auto &original=error?path:identity;
if(const auto existing=newWindow?nullptr:findOpenDocument(original,peer))
if(const auto existing=newWindow?nullptr:findOpenDocument(original,backend?backend->id:""))
{
if(dialogs.confirmExisting(owner) && IsWindow(existing))
{
@@ -2490,9 +2587,9 @@ 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,backend,fragment,options);
const auto title=std::wstring(edit?L"Editor — ":L"Viewer — ")+
(peer?peer->name+L" · ":std::wstring{})+path.wstring();
(backend?backend->name+L" · ":std::wstring{})+path.wstring();
RECT bounds{};
GetWindowRect(owner,&bounds);
const auto window=CreateWindowExW(WS_EX_APPWINDOW,windowClass,title.c_str(),
@@ -2504,4 +2601,17 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD
}
catch(const std::exception &error){dialogs.message(owner,wide(error.what()).c_str());}
}
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const lan::FilesPeer *peer,std::string_view fragment,bool newWindow,TextOpenOptions options)
{
const auto backend=peer?std::optional(lanTextSource(*peer)):std::nullopt;
openTextWindowImpl(owner,path,edit,dialogs,backend?&*backend:nullptr,fragment,newWindow,options);
}
void openRemoteTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const RemoteTextSource &source,std::string_view fragment,bool newWindow)
{
openTextWindowImpl(owner,path,edit,dialogs,&source,fragment,newWindow,{});
}
}
+32 -2
View File
@@ -2,8 +2,11 @@
#include <windows.h>
#include <filesystem>
#include <functional>
#include <cstdint>
#include <string_view>
#include <vector>
#include "files_text_document.h"
namespace ks::lan { struct FilesPeer; }
@@ -37,7 +40,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 +52,37 @@ 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{};
};
struct RemoteTextRevision
{
uint64_t size{}, modified{};
bool editable{};
};
struct RemoteTextSource
{
using Progress=std::function<bool(uint64_t,uint64_t)>;
std::string id;
std::wstring name;
std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
bool,const Progress &,uint64_t)> download;
std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
const RemoteTextRevision &)> upload;
};
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 openRemoteTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const RemoteTextSource &source,std::string_view fragment={},bool newWindow=false);
void textWindowOwnerClosed();
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.113";
inline constexpr wchar_t AppVersion[] = L"0.6.117";
inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+102 -5
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)]
@@ -202,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
@@ -263,6 +268,13 @@ function startTerminalFixture() {
$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 }
@@ -273,6 +285,49 @@ function startTerminalFixture() {
$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
@@ -313,6 +368,27 @@ function startTerminalFixture() {
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"
}
@@ -465,6 +541,20 @@ function startTerminalFixture() {
}
if ((Read-Text $inputBox) -cne 'draft command') { throw 'Pane navigation changed the command line.' }
$shell = New-Object -ComObject WScript.Shell
Wait-Until 'Files activation for Ctrl+F' {
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
}
foreach ($case in @(
@{ Row = '..'; Path = $rightDir },
@{ Row = '[Test folder]'; Path = (Join-Path $rightDir 'Test folder') }
)) {
Select-Row $right $case.Row
[void][FilesActivationUi]::Write($inputBox, 0x0C, [IntPtr]::Zero, 'draft command')
[void][FilesActivationUi]::Send($inputBox, 0xB1, [IntPtr]6, [IntPtr]13)
$shell.SendKeys('^f')
$path = if ($case.Path.Contains(' ')) { '"{0}"' -f $case.Path } else { $case.Path }
Wait-Until "Ctrl+F inserting the path for $($case.Row)" { (Read-Text $inputBox) -ceq "draft $path" }
}
$fileName = [IO.Path]::GetFileName($document)
foreach ($name in $fileName, 'Test folder') {
$label = if ($name -eq $fileName) { $name } else { "[$name]" }
@@ -591,17 +681,24 @@ function startTerminalFixture() {
Select-Row $right "[$name]"
[void][FilesActivationUi]::Send($right,0x100,[IntPtr]45,[IntPtr]::Zero)
}
Select-Row $right '[Size C]'
Select-Row $right $fileName
[void][FilesActivationUi]::PostMessage($right,0x100,[IntPtr]0x72,[IntPtr]::Zero)
Wait-Until 'completion of the marked size batch' { (Read-Text $status) -ceq 'Size C Folder' }
Select-Row $right '[Size B]'
Wait-Until 'F3 size for a marked folder' { (Read-Text $status) -ceq 'Size B 23 B' }
Wait-Until 'F3 on a file measuring a marked folder' { (Read-Text $status) -ceq 'Size B 23 B' }
Select-Row $right '[Size C]'
if ((Read-Text $status) -cne 'Size C Folder') { throw 'F3 measured the unmarked cursor folder.' }
Select-Row $right '..'
[void][FilesActivationUi]::Send($right,0x100,[IntPtr]0x72,[IntPtr]::Zero)
Select-Row $right '[Size C]'
Wait-Until 'F3 on the parent row measuring all folders' { (Read-Text $status) -ceq 'Size C 31 B' }
foreach($name in 'Size A','Size B'){
Select-Row $right "[$name]"
[void][FilesActivationUi]::Send($right,0x100,[IntPtr]45,[IntPtr]::Zero)
}
Select-Row $right $fileName
[void][FilesActivationUi]::PostMessage($right,0x100,[IntPtr]0x72,[IntPtr]::Zero)
$viewerTitle='Viewer '+[char]0x2014+" $document"
Wait-Until 'F3 opening a file when folders are marked' {
Wait-Until 'F3 opening a file with no marked folders' {
[FilesActivationUi]::FindWindowEx([IntPtr]::Zero,[IntPtr]::Zero,'KSwitcher.Files.Text',$viewerTitle) -ne [IntPtr]::Zero
}
$viewer=[FilesActivationUi]::FindWindowEx([IntPtr]::Zero,[IntPtr]::Zero,'KSwitcher.Files.Text',$viewerTitle)
+108 -16
View File
@@ -1,6 +1,7 @@
param(
[string]$Executable = "$PSScriptRoot/../build/files-dev/KSwitcher.Files.exe",
[switch]$OfflineWake,
[switch]$FtpProfiles,
[string]$Screenshot
)
$ErrorActionPreference = 'Stop'
@@ -21,6 +22,7 @@ public static class FilesDriveShortcutTest {
public static extern IntPtr SendRect(IntPtr window, uint msg, IntPtr w, out Rect rect);
[DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr window, out Rect rect);
[DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr window, IntPtr dc, uint flags);
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
}
'@
function Wait-Until([scriptblock]$Condition) {
@@ -35,38 +37,116 @@ function Read-Text($Control, $Message = 13, $Parameter = 32768) {
[void][FilesDriveShortcutTest]::SendMessage($Control, $Message, [IntPtr]$Parameter, $buffer)
$buffer.ToString()
}
$process = Start-Process -FilePath (Resolve-Path $Executable) -PassThru
$preferences = $null
$savedPreferences = @{}
$process = $null
$previousDpi = [FilesDriveShortcutTest]::SetThreadDpiAwarenessContext([IntPtr](-4))
try {
if ($FtpProfiles) {
$preferences = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$preferenceNames = 'FtpProfiles', 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement'
foreach ($name in $preferenceNames) {
if ($name -in $preferences.GetValueNames()) {
$savedPreferences[$name] = @($preferences.GetValue($name), $preferences.GetValueKind($name))
}
}
$profile = '[{"name":"Test FTP profile","host":"localhost","user":"","port":21,"secret":[]}]'
$preferences.SetValue('FtpProfiles', [Text.Encoding]::UTF8.GetBytes($profile), 'Binary')
foreach ($name in 'LeftWide', 'RightWide') { $preferences.SetValue($name, 1, 'DWord') }
}
$process = Start-Process -FilePath (Resolve-Path $Executable) -PassThru
Wait-Until { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
$window = $process.MainWindowHandle
$picker = [FilesDriveShortcutTest]::GetDlgItem($window, 121)
$path = [FilesDriveShortcutTest]::GetDlgItem($window, 142)
function Open-Picker {
[void][FilesDriveShortcutTest]::PostMessage($window, 260, [IntPtr]112, [IntPtr]::Zero)
function Open-Picker([int]$Side = 0) {
[void][FilesDriveShortcutTest]::PostMessage($window, 260, [IntPtr](112 + $Side), [IntPtr]::Zero)
Wait-Until { [FilesDriveShortcutTest]::IsWindowVisible($picker) }
}
function Read-Picker {
$count = [FilesDriveShortcutTest]::SendMessage($picker, 395, [IntPtr]::Zero, $null).ToInt32()
for ($i = 0; $i -lt $count; $i++) { Read-Text $picker 393 $i }
}
function Render-Picker {
$client = [FilesDriveShortcutTest+Rect]::new()
[void][FilesDriveShortcutTest]::GetClientRect($picker, [ref]$client)
$bitmap = [Drawing.Bitmap]::new($client.Right, $client.Bottom)
$graphics = [Drawing.Graphics]::FromImage($bitmap)
try {
$dc = $graphics.GetHdc()
try {
if (![FilesDriveShortcutTest]::PrintWindow($picker, $dc, 2)) { throw 'Could not render drive picker.' }
} finally { $graphics.ReleaseHdc($dc) }
return $bitmap
} finally { $graphics.Dispose() }
}
function Press-Shortcut([char]$Key) {
[void][FilesDriveShortcutTest]::PostMessage($picker, 258, [IntPtr][int]$Key, [IntPtr]::Zero)
Wait-Until { ![FilesDriveShortcutTest]::IsWindowVisible($picker) }
}
if ($OfflineWake) {
function Read-Picker {
$count = [FilesDriveShortcutTest]::SendMessage($picker, 395, [IntPtr]::Zero, $null).ToInt32()
for ($i = 0; $i -lt $count; $i++) { Read-Text $picker 393 $i }
}
function Render-Picker {
$client = [FilesDriveShortcutTest+Rect]::new()
[void][FilesDriveShortcutTest]::GetClientRect($picker, [ref]$client)
$bitmap = [Drawing.Bitmap]::new($client.Right, $client.Bottom)
$graphics = [Drawing.Graphics]::FromImage($bitmap)
if ($FtpProfiles) {
foreach ($side in 0, 1) {
Open-Picker $side
$rows = @(Read-Picker)
$row = [Array]::IndexOf($rows, 'FTP')
if ($row -lt 2 -or $rows[$row - 1] -cne '' -or $rows[$row + 1] -cne 'KSwitcher LAN') {
throw "Source groups are missing separators in panel $side."
}
[void][FilesDriveShortcutTest]::SendMessage($picker, 390, [IntPtr]$row, $null)
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]38, [IntPtr]::Zero)
Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row - 2 }
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero)
Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row }
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero)
Wait-Until {
$selected = [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32()
$selected -ge 0 -and ($selected -lt $row -or $selected -gt $row + 1)
}
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]38, [IntPtr]::Zero)
Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row }
[void][FilesDriveShortcutTest]::SendMessage($picker, 407, [IntPtr]($row - 2), $null)
$bitmap = Render-Picker
try {
$divider = [FilesDriveShortcutTest+Rect]::new()
[void][FilesDriveShortcutTest]::SendRect($picker, 408, [IntPtr]($row - 1), [ref]$divider)
$y = $divider.Top + [int][Math]::Floor(($divider.Bottom - $divider.Top) / 2)
if ($y -le 0 -or $y -ge $bitmap.Height) { throw "Group divider is outside the rendered menu in panel $side (row $row, y $y, height $($bitmap.Height), top $([FilesDriveShortcutTest]::SendMessage($picker,398,[IntPtr]::Zero,$null)))." }
$line = $bitmap.GetPixel(4, $y).ToArgb()
if ($line -eq $bitmap.GetPixel(4, $y - 1).ToArgb() -or
$line -ne $bitmap.GetPixel($bitmap.Width - 5, $y).ToArgb()) {
throw "The local disks and FTP divider did not render in panel $side."
}
$ftpBounds = [FilesDriveShortcutTest+Rect]::new()
[void][FilesDriveShortcutTest]::SendRect($picker, 408, [IntPtr]$row, [ref]$ftpBounds)
$yellow = [Drawing.Color]::Yellow.ToArgb()
$hasDigit = $false
for ($lineY = $ftpBounds.Top; $lineY -lt $ftpBounds.Bottom -and $lineY -lt $bitmap.Height -and !$hasDigit; $lineY++) {
for ($x = 0; $x -lt [Math]::Min(128,$bitmap.Width); $x++) {
if ($bitmap.GetPixel($x,$lineY).ToArgb() -eq $yellow) { $hasDigit = $true; break }
}
}
if (!$hasDigit) { throw "The FTP shortcut digit did not render in panel $side." }
if ($Screenshot -and $side -eq 0) { $bitmap.Save($Screenshot, [Drawing.Imaging.ImageFormat]::Png) }
} finally { $bitmap.Dispose() }
[void][FilesDriveShortcutTest]::SendMessage($picker, 390, [IntPtr]($row - 2), $null)
Press-Shortcut '1'
$panelPath = [FilesDriveShortcutTest]::GetDlgItem($window, 142 + $side)
$list = [FilesDriveShortcutTest]::GetDlgItem($window, 102 + $side)
Wait-Until { (Read-Text $panelPath) -ceq 'FTP' }
if ((Read-Text $list 393 0) -cne 'Test FTP profile') { throw "Saved FTP profile missing from panel $side." }
$graphics = [Drawing.Graphics]::FromHwnd($list)
try {
$dc = $graphics.GetHdc()
try {
if (![FilesDriveShortcutTest]::PrintWindow($picker, $dc, 2)) { throw 'Could not render drive picker.' }
if (![FilesDriveShortcutTest]::PrintWindow($list, $dc, 2)) { throw "FTP rows failed to render in panel $side." }
} finally { $graphics.ReleaseHdc($dc) }
return $bitmap
} finally { $graphics.Dispose() }
if ($process.HasExited) { throw "Files exited while rendering the FTP profile in panel $side." }
}
Write-Output 'Both source menus rendered the FTP shortcut, skipped group dividers, and opened FTP with 1.'
return
}
if ($OfflineWake) {
function Click-Picker([int]$X, [int]$Y) {
$point = [IntPtr](($Y -shl 16) -bor $X)
[void][FilesDriveShortcutTest]::PostMessage($picker, 513, [IntPtr]1, $point)
@@ -137,5 +217,17 @@ try {
}
Write-Output 'Remote drives appeared automatically on both opens.'
} finally {
if (!$process.HasExited) { [void]$process.CloseMainWindow() }
if ($previousDpi) { [void][FilesDriveShortcutTest]::SetThreadDpiAwarenessContext($previousDpi) }
if ($process -and !$process.HasExited) {
[void]$process.CloseMainWindow()
if ($preferences -and !$process.WaitForExit(3000)) { Stop-Process -Id $process.Id; $process.WaitForExit() }
}
if ($preferences) {
foreach ($name in $preferenceNames) {
if ($savedPreferences.ContainsKey($name)) {
$preferences.SetValue($name, $savedPreferences[$name][0], $savedPreferences[$name][1])
} else { $preferences.DeleteValue($name, $false) }
}
$preferences.Close()
}
}
+2
View File
@@ -85,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 }
+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);
+20 -3
View File
@@ -11,7 +11,16 @@ public static class PanelFrameWindow {
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
public static bool Activate(IntPtr window) {
if (GetForegroundWindow() == window) return true;
keybd_event(0x12, 0, 0, UIntPtr.Zero);
keybd_event(0x12, 0, 2, UIntPtr.Zero);
SetForegroundWindow(window);
return GetForegroundWindow() == window;
}
}
'@
@@ -38,11 +47,10 @@ function Read-Strip($X, $Y, $Width, $Height) {
$process = Start-Process -FilePath (Resolve-Path $Executable) -PassThru
$previousDpi = [PanelFrameWindow]::SetThreadDpiAwarenessContext([IntPtr](-4))
try {
$keyboard = New-Object -ComObject WScript.Shell
for ($attempt = 0; $attempt -lt 50; $attempt++) {
$process.Refresh()
$window = $process.MainWindowHandle
if ($window -and $keyboard.AppActivate($process.Id)) { break }
if ($window -and [PanelFrameWindow]::Activate($window)) { break }
Start-Sleep -Milliseconds 100
}
Start-Sleep -Milliseconds 300
@@ -67,10 +75,19 @@ try {
$x = $list.Left + 16
$top = @(Read-Strip $x ($path.Top + [Math]::Floor(($path.Bottom - $path.Top) / 2) - 2) 1 4)
if (($top -join ',') -ne ($side -join ',')) { throw "Panel $panel has an inconsistent top frame." }
$start = $list.Left + [int](($list.Right - $list.Left) / 2)
$width = $list.Right - $start
$bodyPixels = @(Read-Strip $start ($list.Top + 2) $width 1)
$headerPixels = @(Read-Strip $start ($header.Top + 2) $width 1)
$bodyDivider = [Array]::IndexOf($bodyPixels, $side[0])
$headerDivider = [Array]::IndexOf($headerPixels, $side[0])
if ($bodyDivider -lt 0 -or $headerDivider -ne $bodyDivider) {
throw "Panel $panel Size column divider is misaligned. Header offset: $headerDivider. Body offset: $bodyDivider."
}
$bottom = @(Read-Strip $x ($list.Bottom + 4) 1 ($header.Bottom - $header.Top + 6))
$bottom = $bottom[($bottom.Count - 4)..($bottom.Count - 1)]
if (($bottom -join ',') -ne ($side -join ',')) { throw "Panel $panel has an inconsistent bottom frame." }
Write-Output "Panel $panel double frame verified on screen."
Write-Output "Panel $panel double frame and Size column divider verified on screen."
}
} finally {
if ($previousDpi) { [void][PanelFrameWindow]::SetThreadDpiAwarenessContext($previousDpi) }
+110 -10
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,6 +284,73 @@ try {
[SearchArrowTest]::SendText($leftPanel,0x1A2,-1,'A.txt').ToInt64() -ge 0 -and
[SearchArrowTest]::SendText($rightPanel,0x1A2,-1,'A.txt').ToInt64() -ge 0
})
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 })) {
@@ -290,12 +374,27 @@ try {
Write-Output 'Verified folder navigation repaints only the panel that changes directories.'
}
$clicks=if(!$KeyboardCursorOnly){
@(@{Panel=$leftPanel; Index=0},@{Panel=$rightPanel; Index=1},@{Panel=$rightPanel; Index=1})
@(@{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
@@ -303,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";
}