Compare commits

...
Author SHA1 Message Date
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
23 changed files with 1867 additions and 400 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.115 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)
+61 -11
View File
@@ -29,16 +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 дія
`start 'шлях до файла'` з’являється у виводі термінала й історії команд.
Після успішного відкриття локального файла через Windows його шлях
з’являється у виводі термінала й списку історії. Коли термінал неактивний,
його курсор приховано. При виборі
з історії у командний рядок підставляється команда, яка повторює відкриття.
- Коли командний рядок порожній, Shift+Enter відкриває поточний локальний
елемент через Windows.
Папка відкривається у Провіднику, файл виконує свою стандартну дію Windows.
@@ -135,13 +170,19 @@ Warning і початковий фокус на No.
- Ctrl+F вставляє повний шлях елемента під курсором активної панелі в позицію
курсора командного рядка або замінює виділення. Подвійні лапки додаються
лише до шляхів із пробілами. Для `..` вставляється шлях батьківської папки.
лише до шляхів із пробілами. На рядку `..` вставляється шлях папки,
відкритої в активній панелі.
- Ctrl+Enter вставляє лише назву файла або папки під курсором активної панелі
за тими ж правилами вставлення й лапок. Рядок `..` пропускається.
- Локальні й LAN-каталоги скануються у фоновому потоці. Під час переходу
активна панель показує «Loading folder…» і зберігає попередній список до
завершення сканування. Після переходу оновлюються шлях і список цієї панелі
та командний рядок. Сусідня панель не перемальовується через цей перехід.
- Локальні й LAN-каталоги скануються у фоновому потоці. Рядок стану активної
панелі показує «Reading» з лічильником прочитаних файлів і папок та
підказкою [Esc].
До завершення читання панель зберігає попередній список. Escape зупиняє
сканування активної панелі й відкриває прочитану частину папки. Якщо
папку ще не вдалося відкрити, попередній список залишається. Ctrl+R
повторює сканування, щоб отримати повний список. Після переходу
оновлюються шлях і список цієї панелі та командний рядок. Сусідня
панель не перемальовується через цей перехід.
Якщо надійшов новіший запит, результат попереднього
сканування пропускається. Після підтвердження UAC очікування списку
від підвищеного процесу теж відбувається у фоні.
@@ -251,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. Файл завантажується у тимчасову копію
на диску у фоновому режимі. Збереження передає зміни назад на віддалений ПК.
Якщо розмір або час зміни віддаленого файла відрізняється від відкритої
@@ -367,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
+23 -1
View File
@@ -1,5 +1,27 @@
# 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.
@@ -488,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 @@
debcdf6dbb7d7dc959e094d4e39d6c7655efff453f90d13b69b0d7f1c406072c KSwitcher-win-x64.zip
b11409bce6fcc98484107e6c56c13d3830b5c1c6d58515ab7f395ede30dc6d5b KSwitcher-win-x64.zip
+67 -67
View File
@@ -1,166 +1,166 @@
{
"schema": 1,
"version": "0.6.115",
"version": "0.6.117",
"files": [
{
"sha256": "e50dfca08dfc1e4149c43303cf303d1860410b263901dd39ba621d5d175142cd",
"size": 2479104,
"path": "KSwitcher.exe",
"size": 2479104
"sha256": "4ea5e71940d5cd1cbd062c6eead6a57d6c9a7b8a3884f2d8707267872643a55f"
},
{
"sha256": "2ec390faaddad72ee59f819cf54f3f0aafa463b637180e7f877034b7352d474a",
"size": 2458112,
"path": "KSwitcher.Config.exe",
"size": 2458112
"sha256": "3576d94c26dbed409dc12a13fb570d3dac5d35f8df1cf79761758a1e308e6b89"
},
{
"sha256": "149ef86ea46f8c2b01b1d806a4770d7226cffc1b55059fa3ef63233d90b17e96",
"size": 3060224,
"path": "KSwitcher.Screenshot.exe",
"size": 3060224
"sha256": "738a6c42f56bd44d3cd871d53d51aa9580c3a20825c5407d2bb36ce512fe2103"
},
{
"sha256": "85b7aa5e99a4e60d49193de077c6067afb53fbadcc724504167855732d787543",
"size": 4286976,
"path": "KSwitcher.Files.exe",
"size": 4229120
"sha256": "f1231f85448b57771e6ce1f8e416282af8d9112f093bd05cb26881c79ccd5cc5"
},
{
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
"size": 194912,
"path": "WebView2Loader.dll",
"size": 194912
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
},
{
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
"size": 1103,
"path": "terminal/addon-fit-LICENSE.txt",
"size": 1103
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
},
{
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
"size": 1521,
"path": "terminal/addon-fit.js",
"size": 1521
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
},
{
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
"size": 527,
"path": "terminal/index.html",
"size": 527
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
},
{
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
"size": 1073,
"path": "terminal/markdown-it-LICENSE.txt",
"size": 1073
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473"
},
{
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
"size": 100786,
"path": "terminal/markdown-it.js",
"size": 100786
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
},
{
"sha256": "e5381c35fb254b558c8b869746e2e575c8ed53600611ac90597ed2dd80fa321c",
"size": 3530,
"path": "terminal/markdown.html",
"size": 3530
"sha256": "e5381c35fb254b558c8b869746e2e575c8ed53600611ac90597ed2dd80fa321c"
},
{
"sha256": "55c905afaf074e3253267a7c48a5ebca14edd7f15449fd85c0a884c34da22763",
"size": 15014,
"path": "terminal/markdown.js",
"size": 15014
"sha256": "55c905afaf074e3253267a7c48a5ebca14edd7f15449fd85c0a884c34da22763"
},
{
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
"size": 1089,
"path": "terminal/mermaid-LICENSE.txt",
"size": 1089
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80"
},
{
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
"size": 5537838,
"path": "terminal/mermaid.js",
"size": 5537838
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3"
},
{
"sha256": "0557d251962301940785690a3fc49475dd166bb7d0bd0417dc3279d1f1b3a98a",
"size": 5065,
"path": "terminal/terminal.js",
"size": 5033
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b"
},
{
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
"size": 1261,
"path": "terminal/xterm-LICENSE.txt",
"size": 1261
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
},
{
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
"size": 7112,
"path": "terminal/xterm.css",
"size": 7112
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
},
{
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
"size": 488663,
"path": "terminal/xterm.js",
"size": 488663
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
},
{
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
"size": 4401,
"path": "LICENSE",
"size": 4401
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
},
{
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
"size": 1096,
"path": "json-LICENSE.txt",
"size": 1096
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831"
},
{
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
"size": 883,
"path": "files-text-license.txt",
"size": 883
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
},
{
"sha256": "fcbd14b6190dc2a3575a4bc4be7229540c647022cb038d33ec4ac22176c67a9e",
"size": 95317,
"path": "README.md",
"size": 95289
"sha256": "ea5016c6fa29a98bf9ebf103fcf27f1be091842ad3228b167d18b053fda767d8"
},
{
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930",
"size": 11577,
"path": "LAN-PREVIEW.md",
"size": 11577
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930"
},
{
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
"size": 732485,
"path": "dictionaries/en.txt",
"size": 732485
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9"
},
{
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
"size": 20566,
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"size": 20566
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5"
},
{
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
"size": 2265,
"path": "dictionaries/README.md",
"size": 2265
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
},
{
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
"size": 1109134,
"path": "dictionaries/ru.txt",
"size": 1109134
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849"
},
{
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
"size": 1280,
"path": "dictionaries/sources.json",
"size": 1280
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
},
{
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
"size": 940799,
"path": "dictionaries/uk.txt",
"size": 940799
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
},
{
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
"size": 993,
"path": "tools/README.txt",
"size": 993
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
},
{
"sha256": "9aa1710226ee70d49b6a02fed41411f5f70c16422a76ee079e67d2eb3a53c5d2",
"size": 133120,
"path": "tools/StayHere.exe",
"size": 133120
"sha256": "ebe97d3b7f267632b90463358bcc2518cad12f43c1eb568d2749a08f88a4bd97"
},
{
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
"size": 2796,
"path": "tools/StayHere-README.md",
"size": 2796
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
}
]
],
"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,115,0
PRODUCTVERSION 0,6,115,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.115"
VALUE "FileVersion", "0.6.117"
END
END
BLOCK "VarFileInfo"
+33
View File
@@ -343,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);
}
}
+768 -214
View File
File diff suppressed because it is too large. Load diff
+96 -69
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,13 +740,13 @@ 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,
TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const RemoteTextSource *backend,
std::string_view fragment,TextOpenOptions options)
: original(std::move(path)), peerId(peer?peer->id:""), filename(original.filename().wstring()),
: 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});
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)
{
@@ -1467,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();
@@ -1481,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);
@@ -1505,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());
}
@@ -1774,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) ||
@@ -1791,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();
@@ -1871,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();
@@ -2271,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;});
@@ -2514,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;
@@ -2540,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,TextOpenOptions options)
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))
{
@@ -2573,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,options);
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(),
@@ -2587,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,{});
}
}
+21
View File
@@ -2,6 +2,8 @@
#include <windows.h>
#include <filesystem>
#include <functional>
#include <cstdint>
#include <string_view>
#include <vector>
#include "files_text_document.h"
@@ -59,9 +61,28 @@ struct TextOpenOptions
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,
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.115";
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;
+96 -6
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
@@ -318,8 +373,22 @@ function startTerminalFixture() {
$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 -SimpleMatch "start '$($document.Substring(0,12))" -Quiet)
(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"
}
@@ -472,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]" }
@@ -598,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 }
+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) }