Compare commits

..
Author SHA1 Message Date
agrynco 9edb27c765 Merge pull request 'Open Recent folders in the selected file panel' (#194) from codex/recent-folders-in-panel into prerelease
Open Recent folders in the selected file panel
2026-11-26 00:39:09 +02:00
agrynco 5194e2b621 Keep long recent folder names readable and stabilize UI checks
Refs #88
2026-11-26 00:37:46 +02:00
agrynco da914168e8 Open Recent folders in the selected file panel
Refs #88
2026-11-26 00:34:53 +02:00
agrynco 15bf006a19 Merge pull request 'Show SMB connections and shares in the file panel' (#193) from codex/smb-profiles-in-panel into prerelease
Show SMB connections and shares in the file panel
2026-11-26 00:26:50 +02:00
agrynco 9b5cff122d Show SMB connections and shares in the file panel
Refs #109
2026-11-26 00:25:22 +02:00
agrynco 7670616dc4 Merge pull request 'Release KSwitcher v0.8.0' (#192) from codex/release-v0.8.0 into prerelease
Release KSwitcher v0.8.0
2026-11-26 00:02:28 +02:00
agrynco 25acb892d1 Release KSwitcher v0.8.0 2026-11-26 00:01:52 +02:00
agrynco 03a370f445 Merge pull request 'KSwitcher.Files: Add local read-only MCP' (#191) from codex/issue-134-local-files-mcp into prerelease
Refs #134
2026-11-25 23:46:55 +02:00
agrynco e8bef94474 Serve opt-in read-only Files MCP on loopback
Refs #134
2026-11-25 23:46:44 +02:00
agrynco 0f400a58a1 Merge pull request 'KSwitcher.Files: View recent Files diagnostics' (#190) from codex/issue-132-log-view into prerelease
Refs #132
2026-11-25 23:35:29 +02:00
agrynco e852fde4f4 Open recent Files diagnostics in a safe native viewer
Refs #132
2026-11-25 23:35:15 +02:00
agrynco e421c17f2a Merge pull request 'KSwitcher.Files: Add contextual offline help' (#189) from codex/issue-131-context-help into prerelease
Refs #131
2026-11-25 23:29:45 +02:00
28 changed files with 1867 additions and 405 deletions

No files matched your search

+18 -2
View File
@@ -1,12 +1,13 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.7.4 LANGUAGES C CXX RC)
project(KSwitcher VERSION 0.8.0 LANGUAGES C CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_executable(KSwitcherFiles WIN32 src/files_main.cpp src/files_text_window.cpp
src/files_text_document.cpp src/files_text_language.cpp src/files_archive.cpp src/files_git_changes.cpp resources/files.rc)
src/files_text_document.cpp src/files_text_language.cpp src/files_archive.cpp src/files_git_changes.cpp
src/files_mcp.cpp resources/files.rc)
set_property(SOURCE resources/files.rc APPEND PROPERTY OBJECT_DEPENDS
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-viewer.ico"
@@ -185,6 +186,16 @@ if(NOT MSVC)
target_link_options(KSwitcherFilesModalTests PRIVATE -static)
endif()
add_test(NAME files-modal-dialog COMMAND KSwitcherFilesModalTests)
add_executable(KSwitcherFilesMcpTests tests/files_mcp.cpp src/files_mcp.cpp)
target_include_directories(KSwitcherFilesMcpTests PRIVATE src)
target_link_libraries(KSwitcherFilesMcpTests PRIVATE kscore)
if(MSVC)
set_property(TARGET KSwitcherFilesMcpTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
else()
target_link_options(KSwitcherFilesMcpTests PRIVATE -static)
endif()
add_test(NAME files-mcp COMMAND KSwitcherFilesMcpTests)
set_tests_properties(files-mcp PROPERTIES TIMEOUT 30)
add_executable(KSwitcherLanTests tests/lan.cpp)
target_link_libraries(KSwitcherLanTests PRIVATE kscore)
if(MSVC)
@@ -228,6 +239,11 @@ add_test(NAME files-smb-password
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_smb_password.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>")
set_tests_properties(files-smb-password PROPERTIES RUN_SERIAL TRUE TIMEOUT 30)
add_test(NAME files-recent-folders-panel
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_recent_folders_panel.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>")
set_tests_properties(files-recent-folders-panel PROPERTIES RUN_SERIAL TRUE TIMEOUT 35)
add_test(NAME files-space-analyzer-layout
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_space_analyzer_layout.ps1"
+19 -13
View File
@@ -111,12 +111,15 @@ Warning і початковий фокус на No.
підтримувати атомарне перейменування OpenSSH. Якщо сервер відмовляє
в заміні, Files показує причину й зберігає попередній файл.
- **SMB** у меню джерел обох панелей відкриває збережені підключення.
**New** додає назву й сервер або повний UNC-шлях. **Open** для сервера
показує видимі дискові шари. Відомий прихований шар можна додати як
повний UNC-шлях. Вибір шару або відкриття профілю з UNC-папкою переходить
до цієї папки в панелі, з якої викликали меню.
- Для SMB діють дозволи Windows. **Sign in** використовує вказаний
- **SMB** у меню джерел показує збережені підключення у вибраній панелі.
**Shift+F4** додає профіль із сервером або повним UNC-шляхом.
**F4** редагує профіль, **F8** запитує підтвердження видалення.
**Enter** або подвійний клік відкриває профіль. Сервер показує видимі
дискові шари в тій самій панелі, а шар або профіль із повним UNC-шляхом
відкриває папку. Відомий прихований шар можна додати як повний UNC-шлях.
**Esc** або рядок `..` повертає зі списку шарів до профілів.
**Esc** зі списку профілів повертає попередню папку.
- Для SMB діють дозволи Windows. **Sign in** у контекстному меню профілю використовує вказаний
обліковий запис. Прапорець **Remember in Windows Credential Manager**
типово вимкнений. Коли його ввімкнено, після успішного підключення Windows
зберігає облікові дані для цього профілю. **Remove** видаляє профіль і
@@ -635,7 +638,7 @@ Warning і початковий фокус на No.
розміру, а список має однаковий внутрішній відступ зліва і справа.
- Тайм-аут запиту дисків відображається як Connection timed out. Якщо
ввімкнено Write log, Files записує помилки запитів пар і дисків в окремий
журнал `data/kswitcher-files.log`. Системні помилки містять код Windows.
журнал `data/kswitcher-files.log`. Системні помилки містять код Windows. Commands → Files log відкриває до 200 останніх записів поточного або попереднього журналу. Refresh оновлює список. Copy selected або Ctrl+C копіює дату й безпечний опис вибраного запису. Довільні текстові деталі приховано.
- Застосовані налаштування Files одразу підхоплюють інші відкриті вікна.
Apply зберігає поля, змінені в поточній чернетці. Якщо два вікна одночасно
@@ -706,12 +709,13 @@ Warning і початковий фокус на No.
показують перший кадр. Пошкоджені та надто великі файли показують повідомлення.
- **Change drive → Recent folders** у меню Alt+F1 або Alt+F2 показує
останні відвідані локальні, FTP, SFTP та LAN-папки. Повторний візит підіймає
один запис угору, порядок зберігається після перезапуску. Enter або клік
відкриває шлях у панелі, з якої викликали меню. Віддалені записи містять
шлях і ідентифікатор збереженого FTP- чи SFTP-профілю або спареного ПК. Паролі
зберігаються в захищених налаштуваннях профілів. Delete прибирає вибраний
запис із недавніх.
останні відвідані локальні, FTP, SFTP та LAN-папки у вибраній панелі.
**Enter** або подвійний клік відкриває папку в тій самій панелі.
**Delete** прибирає запис із недавніх. **Esc** повертає попередню папку.
Повторний візит підіймає один запис угору, порядок зберігається після
перезапуску. Віддалені записи містять шлях і ідентифікатор збереженого
FTP- чи SFTP-профілю або спареного ПК. Паролі зберігаються в захищених
налаштуваннях профілів.
- Кнопки ← та → переходять назад і вперед в історії відповідної панелі,
зокрема між локальними, FTP, SFTP та LAN-папками. Стрілка ↑, Alt+↑ та рядок `..`
@@ -741,6 +745,8 @@ Warning і початковий фокус на No.
- При перенесенні вікна між моніторами з різним DPI оновлюй шрифт, висоту рядків панелей і компонування відкритого прогресу копіювання. Перевір перенесення під час активного копіювання.
- Для власних діалогів і списків Far використовуй спільні метрики та малювання подвійної рамки. Еталон Delete задає 8 px від краю тла до першої лінії та 14 px від внутрішньої лінії до бічної межі вмісту при 96 DPI. Обидва відступи масштабуються за DPI. Вертикальний відступ враховує висоту заголовка та нижніх підказок. Діалоги й списки зберігають свою палітру та поведінку.
- Commands → Files MCP за замовчуванням зупинений. Start запускає MCP Streamable HTTP на `127.0.0.1` з випадковим портом. Клієнту потрібні Endpoint і `Authorization: Bearer <session token>`. Show token показує токен, Copy token копіює його. Stop і вихід із програми Files відкликають токен. Закриття діалогу залишає сервер активним, і меню показує Files MCP (running). Кожен старт створює новий токен.
- MCP має три інструменти для читання. `get_panels` повертає стан поточних локальних панелей, курсор і сторінку записів. `search_files` фільтрує назви або відносні шляхи поточного списку чи наявних результатів Find. `get_file_metadata` повертає кешовані атрибути, тип, розмір і час зміни для вже показаного елемента. Для продовження списку клієнт передає `nextOffset` як `offset`. Вміст файлів, віддалені панелі, архіви й операції запису не входять до цього API. Запити з браузерним Origin відхиляються.
- F1 відкриває вбудовану офлайн-довідку для панелі, вибраного пункту меню чи поточного діалогу. Пошук фільтрує теми за назвою й текстом. Esc закриває довідку та повертає фокус. У командному рядку з назвою команди F1 зберігає перехід до її довідки Windows. Загальна довідка також доступна через Commands → Help.
- Options → Import JSON / Export JSON переносить вибрані групи збережених параметрів Files. Окремо доступні кольори панелей і порівняння разом зі стилями файлів, режими й компонування панелей та іменовані схеми клавіш. Перед заміною відмінних схем з однаковою назвою Files запитує підтвердження. Імпорт спочатку оновлює чернетку Options. Apply або OK зберігає зміни, Cancel відкидає їх. Формат містить лише ці параметри. Невідомі поля і групи пропускаються.
- Commands → Keyboard shortcuts відкриває іменовані схеми для команд файлових панелей та історії команд. У схемі можна задати кілька клавіш, вибрати основну, вилучити прив’язку, скопіювати схему під новим іменем, перемкнути чи скинути її. OK зберігає активну схему. Меню показує всі прив’язки, нижній ряд і текстові підказки відображають основну. Діалог відхиляє дублікати в контекстах, що перетинаються, і клавіші, зайняті навігацією. Попередні прив’язки історії та порівняння завантажуються як схема Previous settings.
+16
View File
@@ -1,5 +1,21 @@
# Latest Windows release
## v0.8.0 — 2026-11-26
- **Files panels and search.** Find files recursively on local, FTP, SFTP and paired LAN panes. Work with results directly, navigate with breadcrumbs and history, recall recent folders, and configure sorting, filters, columns and panel layout. File clipboard and drag and drop integrate with Windows.
- **Storage and transfers.** Inspect folder sizes and disk usage with the tree, treemap and sunburst. Browse, extract, create and update ZIP and 7z archives. Copy and Move provide masks, multiple destinations and preservation options.
- **Viewing and editing.** Quick View supports text, Markdown, offline HTML, symbolic binary and images. Use Hex Viewer, line bookmarks, unified comparison, change-block application and Undo. Edit PNG/JPEG images with rotate and crop, and opt in to restoring local document windows after a restart.
- **Connections and Windows tools.** Browse saved FTP, SFTP and SMB connections, use the SSH terminal and jump hosts, inspect properties and locking processes, review and stage Git changes, commit the reviewed index, and inspect environment variables.
- **Customize and automate.** Use named keyboard schemes, separate area scales, Windows light and dark palettes, selective JSON settings transfer, offline F1 help, and the Files log. The optional loopback MCP exposes pane state, existing Find results and cached metadata with a per-session token.
**Українською.**
- **Панелі та пошук.** Рекурсивний пошук у локальних, FTP, SFTP і спарених LAN-панелях. Результати підтримують файлові операції. Доступні навігаційний шлях, історія, нещодавні папки, сортування, фільтри, колонки й налаштування панелей. Файловий буфер і перетягування працюють із Windows.
- **Сховище й перенесення.** Дерево, карта та сонячна діаграма показують використання диска. ZIP і 7z можна переглядати, розпаковувати, створювати й оновлювати. Копіювання й переміщення підтримують маски, кілька папок призначення та збереження атрибутів за вибором.
- **Перегляд і редагування.** Quick View підтримує текст, Markdown, офлайн-HTML, символьний перегляд бінарних даних і зображення. Доступні Hex Viewer, закладки рядків, об’єднане порівняння, застосування блоків змін і Undo. PNG/JPEG можна повертати й обрізати. Відновлення локальних вікон після перезапуску вмикається в Options.
- **Підключення та інструменти Windows.** Збережені підключення FTP, SFTP і SMB, SSH-термінал і проміжні вузли, властивості файлів, процеси, що їх блокують, Git Changes із підготовкою та комітом змін, перегляд і редагування змінних середовища.
- **Налаштування й автоматизація.** Іменовані схеми клавіш, окремий масштаб областей, світла й темна палітри Windows, вибіркове перенесення налаштувань через JSON, офлайн-довідка F1 і журнал Files. Опційний локальний MCP читає стан панелей, наявні результати Find і кешовані метадані за токеном сесії.
## v0.7.4 — 2026-11-25
- **Settings → Sync → Google Drive** supports automatic synchronization and a dated list of manual backups. Only one automatic provider is active per PC. Restore a selected backup into the Settings draft and review it before pressing **Apply** or **Save**.
+1 -1
View File
@@ -1 +1 @@
0209951cbe8c5a202dba12a807895ce7146dc6640f96704f6a4aa9afaa4fd3af KSwitcher-win-x64.zip
3d1d0d0a1c9ad671c949e0744987c94642125ccb2f479d3126509250c1fca541 KSwitcher-win-x64.zip
+58 -43
View File
@@ -1,166 +1,181 @@
{
"version": "0.7.4",
"schema": 1,
"files": [
{
"size": 3082752,
"sha256": "31a41c6ecc3387fc9f2b3f228ed64fa916d723654c02dc19bbbb558f94def4b8",
"sha256": "48fb46c472b1a3e689ff7a594f2ba728abee1b0ae2163333901179b624c23fe1",
"size": 3192832,
"path": "KSwitcher.exe"
},
{
"size": 2832384,
"sha256": "b993c050a96215aa63be97e9f05764ead13fcaf4b68fbb99f3d2f9a7d49a629a",
"sha256": "cf6f71169c79bb915c633765a4d56e6048e9a2c84ff877226158e9a27c8183ee",
"size": 2892800,
"path": "KSwitcher.Config.exe"
},
{
"size": 3187712,
"sha256": "eff5921b9067e0f4805c83d3cea10ddaa32b0b4e29f408b71b1004f78754afb9",
"sha256": "79ec0555f9a2668fd284dd73663e2a2aecbc5833dba39e2b02a45b88ad1cae3d",
"size": 3193344,
"path": "KSwitcher.Screenshot.exe"
},
{
"size": 4409344,
"sha256": "569d016d1eff9519cd33aa848723cea0365cbebe9333ed390245d098c4074d8e",
"sha256": "ebe481402fadc09f60afef4dc7ece293d2709c0f3931154d474fbc9a12c7d6a6",
"size": 5967872,
"path": "KSwitcher.Files.exe"
},
{
"size": 194912,
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
"size": 194912,
"path": "WebView2Loader.dll"
},
{
"size": 1103,
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
"size": 1103,
"path": "terminal/addon-fit-LICENSE.txt"
},
{
"size": 1521,
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
"size": 1521,
"path": "terminal/addon-fit.js"
},
{
"size": 527,
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
"size": 527,
"path": "terminal/index.html"
},
{
"size": 1073,
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
"size": 1073,
"path": "terminal/markdown-it-LICENSE.txt"
},
{
"size": 100786,
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
"size": 100786,
"path": "terminal/markdown-it.js"
},
{
"size": 3599,
"sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094",
"sha256": "2576d0c897ffa7e78eb73fc065cd438af164b5dd332cc59083a53ac692fd575f",
"size": 3740,
"path": "terminal/markdown.html"
},
{
"size": 17575,
"sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8",
"sha256": "1eaf9a8a63ec5a62eb4e710cd413bf6893dbc9eaf7dbf4898927fb44afa08bbc",
"size": 18318,
"path": "terminal/markdown.js"
},
{
"size": 1089,
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
"size": 1089,
"path": "terminal/mermaid-LICENSE.txt"
},
{
"size": 5537838,
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
"size": 5537838,
"path": "terminal/mermaid.js"
},
{
"size": 5065,
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b",
"sha256": "838707e2813f7d007f7f60670a78ae4a4a6c97ca9a235d623cb85e16dc50e0c7",
"size": 6627,
"path": "terminal/terminal.js"
},
{
"size": 1261,
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
"size": 1261,
"path": "terminal/xterm-LICENSE.txt"
},
{
"size": 7112,
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
"size": 7112,
"path": "terminal/xterm.css"
},
{
"size": 488663,
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
"size": 488663,
"path": "terminal/xterm.js"
},
{
"size": 4401,
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
"size": 4401,
"path": "LICENSE"
},
{
"size": 1096,
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
"size": 1096,
"path": "json-LICENSE.txt"
},
{
"size": 883,
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
"size": 883,
"path": "files-text-license.txt"
},
{
"size": 105515,
"sha256": "0b1d38528f1da5acccfb02634a91e3aa753547e137ccd1eebd0873fef2a9dd74",
"size": 4880,
"path": "files-archive-license.txt"
},
{
"sha256": "c94d49ba533db63c368a49a7e630ac7e947634cb6dc87cfaab7627272cc3e3e7",
"size": 2994,
"path": "files-image-license.txt"
},
{
"sha256": "05894358228417bb0c524b5c800119b1d47ac0de3477e7cd1abe7a6b41580809",
"size": 2024,
"path": "files-sftp-license.txt"
},
{
"sha256": "be1b3fca2a291284ab550e9e77042fb27ecf927861d2d8fb8ec4907258477f01",
"size": 105515,
"path": "README.md"
},
{
"size": 12804,
"sha256": "f5bfc48e44af14dd6c45f56f689b4034ef1f7bdaca02f9d15ebc32af387366cf",
"sha256": "435ace9c718e14e4c391462ffea3a893c9b6622e9a8b861a7dab0492faf61469",
"size": 16474,
"path": "LAN-PREVIEW.md"
},
{
"size": 732485,
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
"size": 732485,
"path": "dictionaries/en.txt"
},
{
"size": 20566,
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
"size": 20566,
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt"
},
{
"size": 2265,
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
"size": 2265,
"path": "dictionaries/README.md"
},
{
"size": 1109134,
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
"size": 1109134,
"path": "dictionaries/ru.txt"
},
{
"size": 1280,
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
"size": 1280,
"path": "dictionaries/sources.json"
},
{
"size": 940799,
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
"size": 940799,
"path": "dictionaries/uk.txt"
},
{
"size": 993,
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
"size": 993,
"path": "tools/README.txt"
},
{
"sha256": "d4de0a3606267a1c2585412e1288d3be782786720ff1f2ccd9b2217e053bc11b",
"size": 133120,
"sha256": "ba891b6cc5d35d26520fa9ad34e136124e90ed10e0cff2f25dedadd0b48fb88e",
"path": "tools/StayHere.exe"
},
{
"size": 2796,
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
"size": 2796,
"path": "tools/StayHere-README.md"
}
]
],
"schema": 1,
"version": "0.8.0"
}
+3 -3
View File
@@ -14,8 +14,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
1 RT_MANIFEST "app.manifest"
201 RCDATA "update.ps1"
1 VERSIONINFO
FILEVERSION 0,7,4,0
PRODUCTVERSION 0,7,4,0
FILEVERSION 0,8,0,0
PRODUCTVERSION 0,8,0,0
FILEOS VOS_NT_WINDOWS32
FILETYPE VFT_APP
BEGIN
@@ -25,7 +25,7 @@ BEGIN
BEGIN
VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility"
VALUE "ProductName", "KSwitcher"
VALUE "FileVersion", "0.7.4"
VALUE "FileVersion", "0.8.0"
END
END
BLOCK "VarFileInfo"
+31 -17
View File
@@ -214,6 +214,37 @@ BEGIN
DEFPUSHBUTTON "&Close", IDOK, 403, 216, 56, 16
END
619 DIALOGEX 0, 0, 435, 211
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Files log"
FONT 9, "Segoe UI"
BEGIN
LTEXT "&Log", -1, 9, 12, 40, 11
COMBOBOX 680, 51, 9, 115, 70, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
LTEXT "", 681, 9, 31, 415, 28
LISTBOX 682, 9, 62, 417, 117, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_HSCROLL | WS_TABSTOP
PUSHBUTTON "&Copy selected", 683, 9, 187, 90, 15
PUSHBUTTON "&Refresh", 684, 107, 187, 66, 15
DEFPUSHBUTTON "Close", IDOK, 370, 187, 56, 15
END
620 DIALOGEX 0, 0, 395, 152
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Files MCP"
FONT 9, "Segoe UI"
BEGIN
LTEXT "", 690, 9, 9, 376, 12
LTEXT "Read-only access to local panes, Find results and file metadata.", -1, 9, 26, 376, 13
LTEXT "&Endpoint", -1, 9, 49, 72, 12
EDITTEXT 691, 83, 46, 302, 15, ES_READONLY | ES_AUTOHSCROLL
LTEXT "Session &token", -1, 9, 72, 72, 12
EDITTEXT 692, 83, 69, 302, 15, ES_READONLY | ES_AUTOHSCROLL
AUTOCHECKBOX "Sho&w token", 694, 83, 94, 81, 13
PUSHBUTTON "&Copy token", 695, 169, 91, 72, 16
PUSHBUTTON "&Start", 693, 9, 126, 64, 16
DEFPUSHBUTTON "Close", IDOK, 329, 126, 56, 16
END
101 DIALOGEX 0, 0, 397, 310
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_CLIPCHILDREN
CAPTION "KSwitcher Files Options"
@@ -592,23 +623,6 @@ BEGIN
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 59, 80, 17
END
121 DIALOGEX 0, 0, 430, 192
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "SMB connections"
FONT 10, "Consolas"
BEGIN
LTEXT "", 540, 16, 16, 398, 12, SS_ENDELLIPSIS | SS_NOPREFIX
CONTROL "", 541, "ListBox", LBS_OWNERDRAWFIXED | LBS_HASSTRINGS | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP, 16, 31, 398, 103
LTEXT "", 542, 16, 140, 398, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 543, 10, 159, 1, 1, NOT WS_VISIBLE
CONTROL "&Open", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 19, 166, 56, 17
CONTROL "&New", 544, "Button", BS_OWNERDRAW | WS_TABSTOP, 82, 166, 56, 17
CONTROL "&Edit", 545, "Button", BS_OWNERDRAW | WS_TABSTOP, 145, 166, 56, 17
CONTROL "Re&move", 546, "Button", BS_OWNERDRAW | WS_TABSTOP, 208, 166, 56, 17
CONTROL "&Sign in", 547, "Button", BS_OWNERDRAW | WS_TABSTOP, 271, 166, 60, 17
CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 338, 166, 56, 17
END
122 DIALOGEX 0, 0, 355, 113
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "SMB connection"
+1 -1
View File
@@ -1230,7 +1230,7 @@ bool selectedComparisonFiles(CompareFile (&files)[2])
const auto pick=[](const Panel &panel,const fs::path &path,CompareFile &file)
{
const auto row=std::find(panel.rows.begin(),panel.rows.end(),path);
if(panel.archive || transferProfileList(panel) || row==panel.rows.end() || panel.sizes[row-panel.rows.begin()]==L"Folder")
if(panel.archive || panelListsLocations(panel) || row==panel.rows.end() || panel.sizes[row-panel.rows.begin()]==L"Folder")
return false;
const auto directory=path.parent_path();
const auto tail=(directory.filename()/path.filename()).native();
+31 -2
View File
@@ -94,7 +94,32 @@ void showFilesPanelContext(Panel &panel,LRESULT row,POINT screen)
if(!popup.handle) return;
constexpr UINT openItem=1,findItems=2,newProfile=3,properties=4;
const auto add=[&](UINT id,const wchar_t *label){AppendMenuW(popup.handle,MF_STRING,id,label);};
if(transferProfileList(panel))
if(recentFolderList(panel))
{
if(row!=LB_ERR)
{
add(openItem,L"Open folder");
add(117,L"Remove from recent");
}
add(110,L"Refresh panel");
}
else if(panel.listing)
{
if(panel.listing->smb->server.empty())
{
if(row!=LB_ERR)
{
add(openItem,L"Connect");
add(112,L"Edit connection");
add(smbSignInCommand,L"Sign in");
add(117,L"Remove connection");
}
add(newProfile,L"New connection");
}
else if(row!=LB_ERR) add(openItem,L"Open share");
add(110,L"Refresh panel");
}
else if(transferProfileList(panel))
{
if(row!=LB_ERR)
{
@@ -129,7 +154,11 @@ void showFilesPanelContext(Panel &panel,LRESULT row,POINT screen)
screen.x,screen.y,owner,nullptr));
if(command==openItem) enter(panel);
else if(command==findItems) findPanelFiles(owner,panel);
else if(command==newProfile) editTransferProfile(panel,true);
else if(command==newProfile)
{
if(panel.listing) editSmbProfile(panel,true);
else editTransferProfile(panel,true);
}
else if(command==properties) showPanelItemProperties(owner,panel);
else if(command) SendMessageW(owner,WM_COMMAND,MAKEWPARAM(command,BN_CLICKED),0);
}
+1 -1
View File
@@ -8,6 +8,6 @@ inline constexpr UINT filesHelpRequest=WM_APP+273;
enum class FilesHelpTopic
{
panels, menus, navigation, find, transfer, deleteFiles, archive, space, properties, connections,
terminal, viewer, editor, markdown, images, comparison, git, environment, options, keys, appearance, portability, count
terminal, viewer, editor, markdown, images, comparison, git, environment, options, keys, appearance, portability, log, mcp, count
};
}
+13 -3
View File
@@ -11,7 +11,7 @@ constexpr struct
L"Press F9 to show the menu bar. Use the arrow keys to move between categories and entries. Press Enter to run the highlighted command.\r\n\r\n"
L"Press F1 on a menu item for its topic. Commands → Keyboard shortcuts lists the active scheme and lets you assign extra bindings."},
{L"Locations and navigation",L"folder path history breadcrumbs drives recent bookmark directory unc",
L"Use the breadcrumb in a local or remote pane to jump to an ancestor. The folder history keeps earlier locations for that pane. Recent folders are available from the drive picker.\r\n\r\n"
L"Use the breadcrumb in a local or remote pane to jump to an ancestor. The folder history keeps earlier locations for that pane. Choose Recent folders in Change drive to see recent locations in that panel. Enter opens the selected folder, Delete removes it from recent folders, and Esc restores the previous folder.\r\n\r\n"
L"Folder shortcuts open frequently used locations. In the default scheme Ctrl+0–9 recalls a digit and Ctrl+Shift+0–9 adds the current folder."},
{L"Find files",L"search filter mask results alt f7 paths subfolders",
L"Find files searches from the active folder, including subfolders. Supply a filename mask such as *.md. The results show their locations and can be opened or used in file operations.\r\n\r\n"
@@ -32,7 +32,7 @@ constexpr struct
L"Properties shows available file details and Windows attributes. The Windows context menu exposes actions supplied by the file type and the operating system.\r\n\r\n"
L"Use Locking processes for selected local items to see processes with open handles. Save any work in the owning program before closing it."},
{L"Network connections",L"ftp sftp smb lan ssh host authentication credentials password remote",
L"The drive picker opens FTP, SFTP and SMB connection profiles, as well as paired LAN computers. Create a profile with its protocol, host and starting folder.\r\n\r\n"
L"The drive picker opens FTP, SFTP and SMB connection profiles, as well as paired LAN computers. SMB profiles and server shares appear in the selected file panel. Press Shift+F4 to add a profile or Enter to open the selected profile or share. Press Esc to go back. Sign in is in the profile context menu.\r\n\r\n"
L"Check the remote server identity when connecting. If a listing is interrupted, use the Refresh command shown in the pane's status line to retry."},
{L"Command line and terminal",L"powershell ssh console history windows command f1",
L"Type a PowerShell command and press Enter to run it in the active pane's context. Ctrl+O switches between the file panes and terminal output. Previous command and Command history use the active keyboard scheme.\r\n\r\n"
@@ -69,7 +69,13 @@ constexpr struct
L"Viewer and Editor can use System (Windows). Assign either a stock or named palette to each Windows mode under Appearance → System themes."},
{L"Import and export settings",L"json portable backup restore transfer option groups",
L"Select the saved settings groups to include in an export. The supported groups cover colors and file styles, panel layout and keyboard schemes.\r\n\r\n"
L"Import stages chosen groups in Options. Files asks before replacing differing schemes with the same name. Apply saves the new values."}
L"Import stages chosen groups in Options. Files asks before replacing differing schemes with the same name. Apply saves the new values."},
{L"Files log",L"diagnostic journal error logging rotate copy record",
L"Open Files log from Commands to see recent entries. Switch between the current and previous rotated log, or use Refresh to read newer entries.\r\n\r\n"
L"Select an entry to copy its timestamp and summary. The viewer shows only supported diagnostic details."},
{L"Files MCP",L"local loopback bearer authorization model context protocol read only search token",
L"Open Commands → Files MCP and select Start. Configure the client with the displayed loopback endpoint and use the session token as the bearer credential.\r\n\r\n"
L"The client can read current local panes, search their displayed entries and read cached file metadata. Stop revokes the session token."}
};
static_assert(std::size(filesHelpTopics)==static_cast<size_t>(FilesHelpTopic::count));
@@ -185,6 +191,8 @@ FilesHelpTopic filesMenuHelpTopic()
case 19: return FilesHelpTopic::terminal;
case 20: return FilesHelpTopic::keys;
case 21: return FilesHelpTopic::appearance;
case 23: return FilesHelpTopic::log;
case 24: return FilesHelpTopic::mcp;
default: return FilesHelpTopic::menus;
}
}
@@ -229,6 +237,8 @@ std::optional<FilesHelpTopic> filesHelpForWindow(HWND root,HWND target)
case 608: return FilesHelpTopic::appearance;
case 615: case 616: return FilesHelpTopic::keys;
case 617: return FilesHelpTopic::portability;
case 619: return FilesHelpTopic::log;
case 620: return FilesHelpTopic::mcp;
case 604: case 607:
if(const auto owner=GetWindow(root,GW_OWNER);owner && owner!=root)
return filesHelpForWindow(owner,owner);
+177
View File
@@ -0,0 +1,177 @@
constexpr int filesLogSource=680,filesLogStatus=681,filesLogEntries=682,filesLogCopy=683,filesLogRefresh=684;
constexpr size_t filesLogEntryLimit=200,filesLogReadLimit=256*1024;
std::optional<unsigned> filesLogError(std::string_view message,std::string_view marker)
{
const auto last=message.rfind(marker);
if(last==message.npos) return {};
const auto value=message.substr(last+marker.size());
unsigned error{};
const auto parsed=std::from_chars(value.data(),value.data()+value.size(),error);
if(parsed.ec!=std::errc{} || parsed.ptr!=value.data()+value.size()) return {};
return error;
}
std::wstring safeFilesLogEntry(std::string_view line)
{
if(line.ends_with('\r')) line.remove_suffix(1);
std::wstring stamp;
constexpr std::string_view format="0000-00-00 00:00:00 ";
if(line.size()>=format.size())
{
bool valid=true;
for(size_t i=0;i<format.size();++i)
valid&=format[i]=='0'?(line[i]>='0' && line[i]<='9'):line[i]==format[i];
if(valid)
{
stamp=ks::wide(std::string(line.substr(0,format.size()-1)))+L" · ";
line.remove_prefix(format.size());
}
}
// Only fixed descriptions and numeric Windows result codes cross into the UI or clipboard.
std::wstring text;
std::optional<unsigned> error;
if(line=="LAN Files peer lookup failed: local KSwitcher window not found")
text=L"LAN peer lookup failed. KSwitcher is unavailable.";
else if(line.starts_with("LAN Files peer lookup failed: delivered="))
{
text=L"LAN peer lookup failed";
error=filesLogError(line,", Windows error=");
}
else if(line=="LAN Files drive query failed: unexpected error")
text=L"LAN drive query failed. Unexpected error.";
else if(line.starts_with("LAN Files drive query for "))
{
text=L"LAN drive query failed";
error=filesLogError(line,") failed: Windows error ");
if(error==WSAETIMEDOUT) text=L"LAN drive query timed out";
}
else text=L"Diagnostic entry · details hidden";
if(error && *error) text+=L" (Windows error "+std::to_wstring(*error)+L")";
return stamp+text;
}
std::vector<std::wstring> recentFilesLogEntries(const ks::Bytes &bytes)
{
std::vector<std::wstring> entries;
if(bytes.empty()) return entries;
const std::string_view text(reinterpret_cast<const char*>(bytes.data()),bytes.size());
auto end=text.size();
while(end && entries.size()<filesLogEntryLimit)
{
if(text[end-1]=='\n') --end;
const auto split=end?text.rfind('\n',end-1):text.npos;
const auto begin=split==text.npos?0:split+1;
const auto row=text.substr(begin,end-begin);
if(!row.empty() && row!="\r") entries.push_back(safeFilesLogEntry(row));
end=begin;
}
return entries;
}
struct FilesLogDraft
{
std::vector<std::wstring> entries;
};
void refreshFilesLog(HWND dialog,FilesLogDraft &draft)
{
const bool previous=SendDlgItemMessageW(dialog,filesLogSource,CB_GETCURSEL,0,0)==1;
const auto list=GetDlgItem(dialog,filesLogEntries);
SendMessageW(list,LB_RESETCONTENT,0,0);
SendMessageW(list,LB_SETHORIZONTALEXTENT,0,0);
draft.entries.clear();
try
{
if(const auto data=ks::readActiveLogTail(previous,filesLogReadLimit))
{
draft.entries=recentFilesLogEntries(*data);
SetDlgItemTextW(dialog,filesLogStatus,draft.entries.empty()?L"The Files log has no entries.":
L"Most recent first. Select an entry to copy its timestamp and description.");
}
else SetDlgItemTextW(dialog,filesLogStatus,previous?L"No previous Files log is available yet.":
L"No Files log yet. Entries appear when Write log is enabled and Files records a problem.");
}
catch(const std::exception &)
{
SetDlgItemTextW(dialog,filesLogStatus,L"Could not read the Files log. Use Refresh to try again.");
}
int width=0;
const auto dc=GetDC(list);
const auto font=reinterpret_cast<HFONT>(SendMessageW(list,WM_GETFONT,0,0));
const auto oldFont=dc && font?SelectObject(dc,font):nullptr;
for(const auto &entry:draft.entries)
{
SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(entry.c_str()));
if(dc)
{
SIZE extent{};
GetTextExtentPoint32W(dc,entry.c_str(),static_cast<int>(entry.size()),&extent);
width=std::max(width,static_cast<int>(extent.cx)+12);
}
}
if(oldFont) SelectObject(dc,oldFont);
if(dc) ReleaseDC(list,dc);
if(width) SendMessageW(list,LB_SETHORIZONTALEXTENT,width,0);
if(!draft.entries.empty()) SendMessageW(list,LB_SETCURSEL,0,0);
EnableWindow(GetDlgItem(dialog,filesLogCopy),!draft.entries.empty());
}
LRESULT CALLBACK filesLogListKeys(HWND list,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
{
if(message==WM_KEYDOWN && wp=='C' && (GetKeyState(VK_CONTROL)&0x8000) &&
!((GetKeyState(VK_MENU)|GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000))
{
if(!(lp&(1LL<<30))) SendMessageW(GetParent(list),WM_COMMAND,MAKEWPARAM(filesLogCopy,BN_CLICKED),0);
return 0;
}
return DefSubclassProc(list,message,wp,lp);
}
INT_PTR CALLBACK filesLogDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
auto &draft=*reinterpret_cast<FilesLogDraft*>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
for(const auto name:{L"Current",L"Previous"})
SendDlgItemMessageW(dialog,filesLogSource,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name));
SendDlgItemMessageW(dialog,filesLogSource,CB_SETCURSEL,0,0);
SetWindowSubclass(GetDlgItem(dialog,filesLogEntries),filesLogListKeys,1,0);
refreshFilesLog(dialog,draft);
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && (LOWORD(wp)==IDOK || LOWORD(wp)==IDCANCEL)))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND) return FALSE;
auto &draft=*reinterpret_cast<FilesLogDraft*>(GetWindowLongPtrW(dialog,DWLP_USER));
if(LOWORD(wp)==filesLogRefresh || (LOWORD(wp)==filesLogSource && HIWORD(wp)==CBN_SELCHANGE))
{
refreshFilesLog(dialog,draft);
return TRUE;
}
if(LOWORD(wp)==filesLogCopy)
{
const auto row=SendDlgItemMessageW(dialog,filesLogEntries,LB_GETCURSEL,0,0);
if(row>=0 && static_cast<size_t>(row)<draft.entries.size())
{
if(copyFilesText(dialog,draft.entries[row],L"Could not copy the Files log entry."))
SetDlgItemTextW(dialog,filesLogStatus,L"Entry copied.");
else SetDlgItemTextW(dialog,filesLogStatus,L"Could not copy the Files log entry.");
}
return TRUE;
}
return FALSE;
}
void showFilesLog(HWND owner)
{
FilesLogDraft draft;
FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(619),owner,filesLogDialog,
reinterpret_cast<LPARAM>(&draft),false,false);
dialog.runModal();
}
+224 -65
View File
@@ -16,6 +16,7 @@
#include <numbers>
#include <algorithm>
#include <array>
#include <charconv>
#include <atomic>
#include <deque>
#include <filesystem>
@@ -50,6 +51,7 @@
#include "files_text_preferences.h"
#include "files_appearance.h"
#include "files_help.h"
#include "files_mcp.h"
#include "files_menu_paint.h"
#include "files_dropdown_paint.h"
#include "files_scrollbar.h"
@@ -582,6 +584,22 @@ struct RemotePanelLocation
TransferProtocol protocol{};
};
namespace smb { struct PendingConnection; }
struct SmbListing
{
std::string serverId;
std::wstring server;
};
struct PanelListing
{
std::optional<SmbListing> smb;
std::vector<FolderLocation> recent;
std::vector<std::pair<fs::path,std::wstring>> rows;
fs::path returnSelection;
};
struct Panel
{
HWND path{}, list{}, heading{};
@@ -589,6 +607,8 @@ struct Panel
FolderNavigation navigation;
std::optional<FilesPeer> peer;
std::optional<TransferProfile> ftp;
std::optional<PanelListing> listing;
std::shared_ptr<smb::PendingConnection> smbPending;
std::optional<ArchiveLocation> archive;
struct DirectoryWatch
{
@@ -643,6 +663,7 @@ struct Panel
std::optional<ArchiveLocation> archive;
unsigned reconnectAttempt{};
fs::path fallbackSelection;
std::optional<PanelListing> listing;
};
struct RemoteRetry
{
@@ -709,6 +730,36 @@ bool transferProfileList(const Panel &panel)
return panel.ftp && panel.ftp->name.empty();
}
bool recentFolderList(const Panel &panel)
{
return panel.listing && !panel.listing->smb;
}
bool panelListsLocations(const Panel &panel)
{
return panel.listing || transferProfileList(panel);
}
bool samePanelListing(const PanelListing &first,const PanelListing &second)
{
if(first.smb.has_value()!=second.smb.has_value()) return false;
return !first.smb || first.smb->serverId==second.smb->serverId;
}
void showRecentFolders(Panel &panel);
void openRecentFolder(Panel &panel);
void removeRecentFolder(Panel &panel);
void showSmbProfiles(Panel &panel);
void refreshSmbPanel(Panel &panel);
void enterSmbPanel(Panel &panel);
void backSmbPanel(Panel &panel);
void editSmbProfile(Panel &panel,bool create);
void removeSmbProfile(Panel &panel);
void signInSmbProfile(Panel &panel);
void cancelSmbConnection(Panel &panel);
constexpr int smbSignInCommand=547;
FolderLocation folderLocation(const Panel &panel,const fs::path &directory)
{
if(panel.ftp) return {directory,transferFolderProvider(panel.ftp->protocol),panel.ftp->id,panel.ftp->name};
@@ -718,6 +769,12 @@ FolderLocation folderLocation(const Panel &panel,const fs::path &directory)
std::wstring panelLocation(const Panel &panel)
{
if(recentFolderList(panel)) return L"Recent folders";
if(panel.listing)
{
const auto &server=panel.listing->smb->server;
return server.empty()?L"SMB":L"SMB · "+server;
}
if(panel.ftp)
return transferProfileList(panel)?transferProtocolName(panel.ftp->protocol):panel.ftp->name+L" · "+ftpPath(panel.directory);
return (panel.peer?panel.peer->name+L" · ":std::wstring{})+panel.directory.native();
@@ -734,7 +791,7 @@ DWORD effectivePanelColumns(const Panel &panel)
bool hasPanelColumns(const Panel &panel)
{
return detailedPanel(panel) && !panel.findOrigin && !transferProfileList(panel);
return detailedPanel(panel) && !panel.findOrigin && !panelListsLocations(panel);
}
std::wstring panelCaption(const Panel &panel)
@@ -829,7 +886,6 @@ struct FolderPicker
{
const wchar_t *caption;
std::vector<FolderLocation> locations;
bool recent{};
};
std::optional<FolderPicker> folderPicker;
constexpr int defaultSizeWidth=6, defaultFontPoints=110;
@@ -2234,6 +2290,7 @@ LRESULT currentPanelRow(const Panel &panel)
std::vector<fs::path> selectedPanelPaths(const Panel &panel)
{
std::vector<fs::path> paths;
if(panel.listing) return paths;
std::set<fs::path> directories;
visitPanelMarks(panel,[&](const fs::path &path,const FolderEntryMetadata &entry) {
paths.push_back(path);
@@ -2306,7 +2363,7 @@ void copyPanelNames(HWND owner)
void copyPanelFiles(HWND owner,const Panel &panel)
{
if(panel.peer || panel.ftp || panel.archive)
if(panel.peer || panel.ftp || panel.archive || panel.listing)
{
setStatus(L"File clipboard copy requires local files.");
return;
@@ -2324,7 +2381,7 @@ void copyPanelFiles(HWND owner,const Panel &panel)
void copyFullPanelPath(HWND owner,const Panel &panel)
{
const auto row=currentPanelRow(panel);
if(row==LB_ERR || panel.sizes[row]==L"Up" || transferProfileList(panel)) return;
if(row==LB_ERR || panel.sizes[row]==L"Up" || panelListsLocations(panel)) return;
const auto &path=panel.rows[row];
auto value=path.native();
if(panel.ftp)
@@ -2355,6 +2412,12 @@ bool retryRemotePanel(Panel &panel,bool automatic=false,const fs::path &fallback
void refreshPanel(Panel &panel)
{
if(recentFolderList(panel))
{
if(!retryRemotePanel(panel)) showRecentFolders(panel);
return;
}
if(panel.listing) {refreshSmbPanel(panel);return;}
cancelFolderSizes(panel);
if(!panel.view.automaticSizes) panel.folderSizes.clear();
updateSelectionSummary(panel);
@@ -2380,7 +2443,7 @@ std::wstring powerShellPath(const fs::path &path)
void insertCurrentPanelPath(bool nameOnly = false)
{
const auto &panel=panels[active];
if(panel.ftp || panel.archive) return;
if(panel.ftp || panel.listing || panel.archive) return;
const auto row=currentPanelRow(panel);
if(row==LB_ERR) return;
const bool up=panel.sizes[row]==L"Up";
@@ -2568,6 +2631,7 @@ bool showCommandOutput(HWND owner,const Panel &panel)
if(panel.ftp && panel.ftp->protocol==TransferProtocol::sftp && !panel.ftp->id.empty())
return startSshTerminal(owner,panel);
closeSshPrompt(owner);
if(panel.listing) return ensureTerminalView(owner);
if(panel.archive) return startTerminal(owner,panel.archive->file.parent_path());
return panel.peer || panel.ftp?ensureTerminalView(owner):startTerminal(owner,panel.directory);
}
@@ -2607,6 +2671,11 @@ bool submitTerminalCommand(const Panel &panel,const std::wstring &value)
setStatus(L"Shell commands require a local or LAN folder.");
return false;
}
if(panel.listing)
{
setStatus(L"Open a folder before running a shell command.");
return false;
}
if(panel.ftp)
{
if(panel.ftp->protocol==TransferProtocol::sftp && !panel.ftp->id.empty())
@@ -2891,6 +2960,20 @@ void showFileDetails(const Panel &panel)
L" · Enter: Go · Esc: Back");
return;
}
if(recentFolderList(panel))
{
setStatus(panel.rows.empty()?L"No recent folders Esc Back":L"Enter Open folder Delete Remove from recent Esc Back");
return;
}
if(panel.listing)
{
if(panel.smbPending) setStatus(L"Connecting to SMB… Esc Cancel");
else if(!panel.listing->smb->server.empty())
setStatus(panel.rows.size()<=1?L"No visible shares Esc Back":L"Enter Open share Esc Back");
else if(panel.rows.empty()) setStatus(L"Shift+F4 New connection Esc Back");
else setStatus(L"Enter Connect Shift+F4 New Right-click for Edit, Remove or Sign in");
return;
}
if(transferProfileList(panel))
{
setStatus(transferProfiles(panel.ftp->protocol).rows.empty()?L"Shift+F4 New connection":
@@ -3121,7 +3204,9 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
auto &peer=request.peer;
const auto previousDirectory=samePanelSource(panel,peer,request.ftp)?panel.directory:fs::path{};
const auto provider=peer?FolderProvider::lan:request.ftp?transferFolderProvider(request.ftp->protocol):FolderProvider::local;
const bool sameDirectory=sameFolderPath(previousDirectory,directory,provider);
const bool sameDirectory=request.listing || panel.listing?
request.listing && panel.listing && samePanelListing(*panel.listing,*request.listing):
sameFolderPath(previousDirectory,directory,provider);
auto &[nextWatch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered,columnMetadata,archiveEntries]=scan;
const bool partial=error==ERROR_CANCELLED;
if(error==ERROR_CONNECTION_ABORTED && request.find && panel.findOrigin && sameDirectory && files.empty() &&
@@ -3192,7 +3277,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
if(panel.marked[i]) markedPaths.insert(panel.rows[i]);
}
const bool finding=request.find.has_value();
const bool viewChanged=finding!=panel.findOrigin.has_value();
const bool viewChanged=finding!=panel.findOrigin.has_value() || request.listing.has_value()!=panel.listing.has_value();
if(finding)
{
if(!panel.findOrigin)
@@ -3222,31 +3307,34 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
if(mark.parent_path()==folderPathWithoutSeparator(directory)) markedPaths.insert(mark);
panel.listReturnMarks.clear();
}
const bool rememberFolder=!sameDirectory && !partial && (!panel.directory.empty() || peer || request.ftp);
const bool returningFromListing=panel.listing && request.navigationPosition==panel.navigation.current;
const bool rememberFolder=!sameDirectory && !partial && !returningFromListing &&
(!panel.directory.empty() || panel.listing || peer || request.ftp);
panel.directory = directory;
panel.peer=std::move(peer);
panel.ftp=std::move(request.ftp);
panel.archive=std::move(request.archive);
panel.listing=std::move(request.listing);
if(panel.archive) panel.archive->entries=std::move(archiveEntries);
if(!sameDirectory)
{
cancelFolderSizes(panel);
panel.folderSizes.clear();
}
if(partial || finding || panel.archive) panel.watch.reset();
if(partial || finding || panel.archive || panel.listing) panel.watch.reset();
else if(!sameDirectory || panel.watch.handle==INVALID_HANDLE_VALUE)
{
panel.watch.reset();
std::swap(panel.watch.handle,nextWatch.handle);
}
const bool profiles=transferProfileList(panel);
if(!finding && !panel.archive && !profiles)
const bool locationList=panelListsLocations(panel);
if(!finding && !panel.archive && !locationList)
{
auto location=folderLocation(panel,directory);
if(rememberFolder) updateRecentFolders(location,true);
panel.navigation.opened(std::move(location),request.navigationPosition);
}
const bool renderTree=panel.view.tree && !finding && !profiles && !panel.archive;
const bool renderTree=panel.view.tree && !finding && !locationList && !panel.archive;
panel.filteredMarks.clear();
if(renderTree) replaceTreeRoot(panel,scan,sameDirectory,markedPaths);
else
@@ -3263,7 +3351,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
const auto parent=finding?fs::path{}:panel.archive?directory.parent_path():
panelParentPath(directory,!panel.peer && !panel.ftp);
const bool hasParent=!parent.empty();
const auto rowCount=profiles?transferProfiles(panel.ftp->protocol).rows.size():finding?files.size():
const auto rowCount=panel.listing?panel.listing->rows.size():locationList?transferProfiles(panel.ftp->protocol).rows.size():finding?files.size():
renderTree?panel.tree.branches.at(panel.tree.root).ordered.size()+hasParent:ordered.size()+hasParent;
PanelRowsUpdate rows(panel,rowCount);
const auto add=[&](const fs::path &path,const std::wstring &label,bool folder)
@@ -3271,7 +3359,11 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
const bool marked=markedPaths.contains(path);
if(rows.add(path,label,folder,marked) && marked) panel.filteredMarks.erase(path);
};
if(profiles)
if(panel.listing)
{
for(const auto &[path,label]:panel.listing->rows) rows.add(path,label,false,false,path==L"..");
}
else if(locationList)
{
const auto &connections=transferProfiles(panel.ftp->protocol).rows;
for(size_t i=0;i<connections.size();++i)
@@ -3336,7 +3428,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
else if(!partial && error!=ERROR_SUCCESS && error!=ERROR_NO_MORE_FILES && error!=ERROR_FILE_NOT_FOUND)
setStatus(L"Some entries could not be read.");
else if(updateDetails && &panel==&panels[active]) showFileDetails(panel);
if(!finding && !profiles && !panel.archive) queueAutomaticPanelSizes(panel,true);
if(!finding && !locationList && !panel.archive) queueAutomaticPanelSizes(panel,true);
return true;
}
@@ -3348,6 +3440,12 @@ std::future<std::unique_ptr<Panel::ScanResult>> scanDirectoryInBackground(HWND o
std::packaged_task<std::unique_ptr<Panel::ScanResult>()> task(
[request=std::move(request),view=std::move(view),columns,entries=std::move(entries),stop]
{
if(request.listing)
{
auto result=std::make_unique<Panel::ScanResult>();
result->opened=true;
return result;
}
auto result=scanDirectory(request,*entries,stop);
if(result->opened && !request.find)
{
@@ -3378,9 +3476,10 @@ void startDirectoryScan(Panel &panel)
void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::optional<FilesPeer> peer,
fs::path selection={},fs::path fallback={},std::optional<TransferProfile> ftp={},
std::optional<size_t> navigationPosition={},std::optional<ArchiveLocation> archive={},
unsigned reconnectAttempt=0,fs::path fallbackSelection={})
unsigned reconnectAttempt=0,fs::path fallbackSelection={},std::optional<PanelListing> listing={})
{
if(directory.empty() && !ftp) return;
if(directory.empty() && !ftp && !listing) return;
cancelSmbConnection(panel);
panel.remoteRetry.reset();
if(!panel.view.revealedFile.empty() &&
(panel.view.revealedFile.parent_path()!=folderPathWithoutSeparator(directory) ||
@@ -3389,7 +3488,7 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti
cancelFolderSizes(panel);
panel.scanRequest=Panel::ScanRequest{directory,std::move(selection),std::move(fallback),
std::move(peer),offerElevation,statusRevision,{},std::move(ftp),{},navigationPosition,
std::move(archive),reconnectAttempt,std::move(fallbackSelection)};
std::move(archive),reconnectAttempt,std::move(fallbackSelection),std::move(listing)};
if(panel.scan.valid())
{
panel.scanSuperseded=true;
@@ -3401,6 +3500,20 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti
#include "files_panel_recovery.inl"
void openPanelListing(Panel &panel,PanelListing listing,fs::path selection={})
{
if(panel.listing) listing.returnSelection=panel.listing->returnSelection;
else if(const auto row=currentPanelRow(panel);row!=LB_ERR) listing.returnSelection=panel.rows[row];
openOn(panel,{},false,{},std::move(selection),{},{},{},{},0,{},std::move(listing));
}
void closePanelListing(Panel &panel)
{
if(panel.navigation.history.empty()) return;
const auto position=panel.navigation.current;
openFolderLocation(panel,panel.navigation.history[position],position,panel.listing->returnSelection);
}
void collectDirectoryScans()
{
for(auto &panel:panels)
@@ -3922,8 +4035,6 @@ LRESULT sftpDriveRow() {return lanDrivePicker?-1:ftpDriveRow()+1;}
LRESULT smbDriveRow() {return lanDrivePicker?-1:sftpDriveRow()+1;}
LRESULT recentDriveRow() {return lanDrivePicker?-1:smbDriveRow()+1;}
LRESULT lanHeaderRow() {return recentDriveRow()+1;}
void showRecentFolders(int side);
void showSmbProfiles(Panel &panel);
bool driveSourceRow(LRESULT row)
{
@@ -3940,6 +4051,8 @@ bool gitChangesAvailable(const Panel &panel);
void openGitChanges(HWND owner,const Panel &panel);
void showEnvironmentPanel(HWND owner);
void showFilesHelp(HWND owner,ks::files::FilesHelpTopic topic);
void showFilesLog(HWND owner);
void showFilesMcp(HWND owner);
void editFilesKeySchemes(HWND owner,FilesKey initial,FilesKeySettings *pending=nullptr);
void showCommandHistory(HWND owner);
@@ -3997,6 +4110,8 @@ void selectDrive()
else if(menuIndex==2 && row==20) editFilesKeySchemes(owner,FilesKey::Refresh);
else if(menuIndex==2 && row==21) editFilesAppearance(owner,terminalVisible?AppearanceArea::terminal:AppearanceArea::panels);
else if(menuIndex==2 && row==22) showFilesHelp(owner,terminalVisible?ks::files::FilesHelpTopic::terminal:ks::files::FilesHelpTopic::panels);
else if(menuIndex==2 && row==23) showFilesLog(owner);
else if(menuIndex==2 && row==24) showFilesMcp(owner);
else if(menuIndex==1 && row==4) createArchive(owner,panels[active]);
else if(menuIndex==1 && row==5) showPanelItemProperties(owner,panels[active]);
else if(menuIndex==1 && row==6) showPanelLockProcesses(owner,panels[active]);
@@ -4024,7 +4139,11 @@ void selectDrive()
activatePanel(pickerPanel);
showSmbProfiles(panels[pickerPanel]);
}
else if(row==recentDriveRow()) showRecentFolders(pickerPanel);
else if(row==recentDriveRow())
{
activatePanel(pickerPanel);
showRecentFolders(panels[pickerPanel]);
}
else if(remote!=remoteDriveRows.end())
{
const auto &choice=remote->second;
@@ -4035,26 +4154,6 @@ void selectDrive()
LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR)
{
if(folderPicker && folderPicker->recent && msg==WM_KEYDOWN && wp==VK_DELETE)
{
const auto row=SendMessageW(window,LB_GETCURSEL,0,0);
if(!selectablePickerRow(row)) return 0;
auto &paths=folderPicker->locations;
if(!updateRecentFolders(paths[row],false))
{
setStatus(L"Could not remove the recent folder.");
return 0;
}
paths.erase(paths.begin()+row);
SendMessageW(window,LB_DELETESTRING,row,0);
if(paths.empty())
{
hidePicker();
setStatus(L"No recent folders.");
}
else SendMessageW(window,LB_SETCURSEL,std::min(row,static_cast<LRESULT>(paths.size()-1)),0);
return 0;
}
if(folderPicker && msg==WM_LBUTTONUP)
{
const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,lp);
@@ -4549,7 +4648,7 @@ void openPanelFile(const Panel &panel, const fs::path &file, const wchar_t *verb
void openSelectedWithSystem(const Panel &panel)
{
if(panel.ftp || panel.archive) return;
if(panel.ftp || panel.listing || panel.archive) return;
const auto row=currentPanelRow(panel);
if(row==LB_ERR) return;
if(panel.peer)
@@ -4585,7 +4684,7 @@ void refreshQuickView(const Panel &panel)
{
if(!quickViewWindow || &panel!=&panels[quickViewSource]) return;
const auto row=currentPanelRow(panel);
const bool file=!panel.peer && !panel.ftp && !panel.archive && row!=LB_ERR &&
const bool file=!panel.peer && !panel.ftp && !panel.listing && !panel.archive && row!=LB_ERR &&
panel.sizes[row]!=L"Folder" && panel.sizes[row]!=L"Up";
const auto path=file?panel.rows[row]:fs::path{};
if(file && ks::files::isImagePath(path) && !quickImageWindow)
@@ -4671,7 +4770,7 @@ void openArchiveText(const Panel &panel,const fs::path &path,bool hex=false)
void openSelectedText(const Panel &panel, bool edit, bool external,bool hex)
{
if(transferProfileList(panel)) return;
if(panelListsLocations(panel)) return;
const auto row=currentPanelRow(panel);
if(row==LB_ERR || panel.sizes[row]==L"Folder" || panel.sizes[row]==L"Up") return;
if(panel.archive)
@@ -4708,6 +4807,8 @@ void openSelectedText(const Panel &panel, bool edit, bool external,bool hex)
void enter(Panel &panel)
{
if(recentFolderList(panel)) {openRecentFolder(panel);return;}
if(panel.listing) {enterSmbPanel(panel);return;}
const auto row=currentPanelRow(panel);
if(row!=LB_ERR)
{
@@ -6773,6 +6874,11 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
{
const auto sourceFtp=source.ftp;
const bool ftpRename=move && sourceFtp && !transferProfileList(source);
if(source.listing || (destination.listing && !ftpRename && !renameHere))
{
setStatus(L"Open a folder before copying or moving files.");
return;
}
const auto archive=source.archive?source.archive->file:fs::path{};
auto archiveDirectory=archive.empty()?fs::path{}:source.directory.lexically_relative(archive);
if(archiveDirectory==L".") archiveDirectory.clear();
@@ -7284,7 +7390,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent)
setStatus(L"Wait for the search to finish.");
return;
}
if(transferProfileList(panel)) return;
if(panelListsLocations(panel)) return;
if(copyInProgress) return;
const auto ftp=panel.ftp;
permanent=permanent || ftp.has_value();
@@ -7521,7 +7627,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent)
bool pastePanelFiles(HWND owner,Panel &panel)
{
if(!IsClipboardFormatAvailable(CF_HDROP)) return false;
if(panel.peer || panel.ftp || panel.findOrigin)
if(panel.peer || panel.ftp || panel.listing || panel.findOrigin)
{
setStatus(L"Open a local folder before pasting files.");
return true;
@@ -7973,6 +8079,12 @@ void runFilesKeyCommand(HWND owner,int side,FilesKey command)
case FilesKey::Edit:
{
const bool edit=command==FilesKey::Edit;
if(recentFolderList(panel)) break;
if(panel.listing)
{
if(edit) editSmbProfile(panel,false);
break;
}
if(transferProfileList(panel))
{
if(edit) editTransferProfile(panel,false);
@@ -7985,7 +8097,11 @@ void runFilesKeyCommand(HWND owner,int side,FilesKey command)
case FilesKey::Copy:
case FilesKey::Move: copySelection(owner,panel,panels[1-side],command==FilesKey::Move); break;
case FilesKey::Mkdir: makeFolder(owner,panel); break;
case FilesKey::Delete: deleteSelection(owner,panel,false); break;
case FilesKey::Delete:
if(recentFolderList(panel)) removeRecentFolder(panel);
else if(panel.listing) removeSmbProfile(panel);
else deleteSelection(owner,panel,false);
break;
case FilesKey::Exit: SendMessageW(owner,WM_CLOSE,0,0); break;
case FilesKey::Compare: compareSelectedFiles(owner); break;
case FilesKey::Previous: recallPreviousCommand(); break;
@@ -8046,7 +8162,7 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
{
auto &panel=panels[index];
const auto row=panelRowAt(window,screen,SendMessageW(window,LB_GETTOPINDEX,0,0),panel.rows.size());
if(row!=LB_ERR && panel.sizes[row]!=L"Up" && !transferProfileList(panel))
if(row!=LB_ERR && panel.sizes[row]!=L"Up" && !panelListsLocations(panel))
{
closePanelSearch();
SetFocus(window);
@@ -8289,6 +8405,7 @@ struct OptionsWriteLock
#include "files_panel_columns_dialog.inl"
#include "files_space_analyzer.inl"
#include "files_environment.inl"
#include "files_mcp_ui.inl"
void openMenu(HWND window, int index)
{
@@ -8346,7 +8463,8 @@ void openMenu(HWND window, int index)
filesKeyMenuLabel(FilesKey::FullPath),L"Space Analyzer",filesKeyMenuLabel(FilesKey::HexView),
L"Viewer bookmarks…",L"Processes…",L"Git Changes…",L"Environment Variables…",filesKeyMenuLabel(FilesKey::Swap),
filesKeyMenuLabel(FilesKey::History),L"Keyboard shortcuts…",
terminalVisible?L"Terminal appearance…":L"Panel appearance…",L"Help…\tF1"};
terminalVisible?L"Terminal appearance…":L"Panel appearance…",L"Help…\tF1",L"Files log…",
filesMcp.port()?L"Files MCP (running)…":L"Files MCP…"};
}
const auto &panel=panels[active];
const bool remoteResults=remoteSearchResults(panel);
@@ -8393,7 +8511,7 @@ void openMenu(HWND window, int index)
}
if(quickViewWindow || (!panels[active].peer && !panels[active].ftp)) commandActions.push_back(10);
if(panels[active].peer) commandActions.insert(commandActions.end(),{-1,6,7});
commandActions.insert(commandActions.end(),{-1,19,20,21,22});
commandActions.insert(commandActions.end(),{-1,19,20,21,23,24,22});
}
else
for(size_t i=0;i<rows.size();++i) commandActions.push_back(static_cast<int>(i));
@@ -8505,7 +8623,8 @@ void searchPanelByPrefix(HWND window,wchar_t character)
{
if(panel.sizes[row]==L"Up") continue;
const auto *profiles=transferProfileList(panel)?&transferProfiles(panel.ftp->protocol).rows:nullptr;
const auto name=profiles && row<profiles->size()?(*profiles)[row].name:panel.rows[row].filename().native();
const auto name=panel.listing && row<panel.listing->rows.size()?panel.listing->rows[row].second:
profiles && row<profiles->size()?(*profiles)[row].name:panel.rows[row].filename().native();
if(name.size()<panelSearchPrefix.size() ||
CompareStringOrdinal(name.data(),length,panelSearchPrefix.data(),length,TRUE)!=CSTR_EQUAL)
continue;
@@ -8625,6 +8744,9 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
}
switch (message)
{
case ks::files::filesMcpQueryMessage:
filesMcp.answer(readFilesMcpTool);
return 0;
case WM_SETFOCUS:
restoreCommandFocus();
return 0;
@@ -8665,6 +8787,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
if(!FilesModalDialog::activeFor(window))
{
collectDirectoryScans();
collectSmbConnections(window);
collectTreeBranches();
}
return 0;
@@ -8684,6 +8807,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
if(!FilesModalDialog::activeFor(window))
{
collectDirectoryScans();
collectSmbConnections(window);
collectTreeBranches();
pollRemotePanels();
refreshChangedPanels();
@@ -8997,7 +9121,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
if(item.CtlID==140 || item.CtlID==141)
{
const auto &panel=panels[item.CtlID-140];
if(panel.findOrigin || transferProfileList(panel))
if(panel.findOrigin || panelListsLocations(panel))
{
paintText(item.hDC,item.rcItem,panel.findOrigin?L"Relative path":L"Name",RGB(255,255,0),colors[PanelBlue]);
return TRUE;
@@ -9042,8 +9166,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
paintDialogFrameCaptions(item.hDC,item.rcItem,box,L"Change drive",teal,colors[Text],mono);
}
if(item.hwndItem==pickerFrame && folderPicker)
paintDialogFrameCaptions(item.hDC,item.rcItem,box,folderPicker->caption,teal,colors[Text],mono,
folderPicker->recent?L"Del Remove":nullptr);
paintDialogFrameCaptions(item.hDC,item.rcItem,box,folderPicker->caption,teal,colors[Text],mono);
const auto list=item.hwndItem==pickerFrame?picker:completionList;
paintScrollPosition(item.hwndItem,item.hDC,list,colors[Dialog]);
DeleteObject(border);
@@ -9147,9 +9270,9 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
}
}
auto shortcut=text.find(L'\t');
if(item.hwndItem==picker && folderPicker)
paintDialogListRow(item.hDC,item.rcItem,text.c_str(),mono,foreground,rowBackground,
dialogRowTextInset(cellWidth),DT_PATH_ELLIPSIS|DT_END_ELLIPSIS);
if((item.hwndItem==picker && folderPicker) || (panelRow && recentFolderList(panels[item.CtlID-102])))
paintDialogListRow(item.hDC,item.rcItem,text,rowFont?rowFont:mono,foreground,rowBackground,
panelRow?5:dialogRowTextInset(cellWidth),DT_PATH_ELLIPSIS|DT_END_ELLIPSIS);
else if(item.hwndItem==picker && commandPicker && item.itemID<commandAccessPositions.size())
{
auto labelRect=item.rcItem, keyRect=item.rcItem;
@@ -9369,6 +9492,11 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
}
return 0;
}
if(LOWORD(wp)==smbSignInCommand && HIWORD(wp)==BN_CLICKED)
{
signInSmbProfile(panels[active]);
return 0;
}
if(HIWORD(wp)==BN_CLICKED && LOWORD(wp)>=firstDriveButton && LOWORD(wp)<=moreDriveButton)
{
const auto id=LOWORD(wp);
@@ -9419,20 +9547,31 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
ks::files::saveLocalDocumentSession(schemeKey,restoreDocuments);
for(int i=0;i<2;++i)
{
saveFtpPanelLocation(panels[i],i);
const auto path=(panels[i].archive?panels[i].archive->file.parent_path():panels[i].directory).native();
if(!panels[i].peer && !panels[i].ftp && !path.empty())
const auto &panel=panels[i];
saveFtpPanelLocation(panel,i);
if(panel.peer || panel.ftp) continue;
auto path=(panel.archive?panel.archive->file.parent_path():panel.directory).native();
const auto row=currentPanelRow(panel);
auto cursor=panel.archive?panel.archive->file.native():
row==LB_ERR?std::wstring{}:panel.rows[row].native();
if(panel.listing)
{
if(panel.navigation.history.empty()) continue;
const auto &previous=panel.navigation.history[panel.navigation.current];
if(previous.provider!=FolderProvider::local) continue;
path=previous.directory.native();
cursor=panel.listing->returnSelection.native();
}
if(!path.empty())
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,panelPathKeys[i],REG_SZ,path.c_str(),
static_cast<DWORD>((path.size()+1)*sizeof(wchar_t)));
const auto row=SendMessageW(panels[i].list,LB_GETCURSEL,0,0);
const auto cursor=panels[i].archive?panels[i].archive->file.native():
row>=0 && static_cast<size_t>(row)<panels[i].rows.size()?panels[i].rows[row].native():std::wstring{};
if(!panels[i].peer && !panels[i].ftp) RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,panelCursorKeys[i],REG_SZ,cursor.c_str(),
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,panelCursorKeys[i],REG_SZ,cursor.c_str(),
static_cast<DWORD>((cursor.size()+1)*sizeof(wchar_t)));
}
DestroyWindow(window);
return 0;
case WM_DESTROY:
filesMcp.stop();
pendingPanelDrop.reset();
closeGitChanges(window,false);
for(auto &panel:panels)
@@ -9442,6 +9581,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
for(auto &panel:panels)
{
panel.scanStop.request_stop();
cancelSmbConnection(panel);
stopTreeBranches(panel);
panel.watch.reset();
}
@@ -9461,6 +9601,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
return DefWindowProcW(window, message, wp, lp);
}
#include "files_log_view.inl"
#include "files_help.inl"
}
@@ -9583,6 +9724,16 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
continue;
}
if(!copyInProgress && handlePanelSearchKey(window,message)) continue;
if(message.message==WM_KEYDOWN && message.wParam==VK_DELETE && !terminalVisible &&
!(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_SHIFT)&0x8000) &&
!(GetKeyState(VK_MENU)&0x8000) && commandLineAvailable(window) &&
(message.hwnd==panels[active].list ||
(message.hwnd==terminalInput && !GetWindowTextLengthW(terminalInput))) &&
recentFolderList(panels[active]))
{
if(!(message.lParam&(1LL<<30))) removeRecentFolder(panels[active]);
continue;
}
if(message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE && !terminalVisible &&
commandLineAvailable(window) &&
(message.hwnd==terminalInput || message.hwnd==panels[0].list || message.hwnd==panels[1].list))
@@ -9593,6 +9744,12 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
if(!panel.scanSuperseded) stopDirectoryScan();
continue;
}
if(panel.listing && !panel.scanRequest && !GetWindowTextLengthW(terminalInput))
{
if(recentFolderList(panel)) closePanelListing(panel);
else backSmbPanel(panel);
continue;
}
if(panel.archive && !panel.scanRequest)
{
parentArchive(panel);
@@ -9706,7 +9863,9 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
if(!(message.lParam & (1LL<<30)) && commandLineAvailable(window))
{
auto &panel=panels[active];
if(transferProfileList(panel)) editTransferProfile(panel,true);
if(recentFolderList(panel)) continue;
if(panel.listing) editSmbProfile(panel,true);
else if(transferProfileList(panel)) editTransferProfile(panel,true);
else openOrCreateText(window,panel);
}
continue;
+384
View File
@@ -0,0 +1,384 @@
#include "lan_network.h"
#include "files_mcp.h"
#include "lan_pairing.h"
#include <algorithm>
#include <atomic>
#include <charconv>
#include <chrono>
#include <future>
#include <map>
#include <mutex>
#include <optional>
#include <thread>
namespace ks::files
{
namespace
{
using Json=FilesMcpServer::Json;
using Clock=std::chrono::steady_clock;
using namespace std::chrono_literals;
constexpr size_t maxHeaders=8192,maxRequest=16*1024,maxResponse=512*1024;
constexpr std::string_view latestProtocol="2025-11-25";
bool supportedProtocol(std::string_view version)
{
return version==latestProtocol || version=="2025-06-18" || version=="2025-03-26";
}
bool readySocket(SOCKET socket,bool write,std::stop_token stop,Clock::time_point deadline)
{
while(!stop.stop_requested() && Clock::now()<deadline)
{
fd_set ready;
FD_ZERO(&ready);
FD_SET(socket,&ready);
timeval wait{0,50000};
const auto result=select(0,write?nullptr:&ready,write?&ready:nullptr,nullptr,&wait);
if(result) return result>0;
}
return false;
}
bool appendSocket(SOCKET socket,std::string &data,std::stop_token stop,Clock::time_point deadline)
{
char buffer[4096];
if(!readySocket(socket,false,stop,deadline)) return false;
const auto count=recv(socket,buffer,sizeof(buffer),0);
if(count<=0) return false;
data.append(buffer,count);
return true;
}
void sendSocket(SOCKET socket,std::string_view bytes,std::stop_token stop)
{
const auto deadline=Clock::now()+2s;
while(!bytes.empty() && readySocket(socket,true,stop,deadline))
{
const auto count=send(socket,bytes.data(),static_cast<int>(bytes.size()),0);
if(count<=0) return;
bytes.remove_prefix(count);
}
}
std::string lowerAscii(std::string_view text)
{
std::string result(text);
for(auto &ch:result)
if(ch>='A' && ch<='Z') ch=static_cast<char>(ch-'A'+'a');
return result;
}
std::string_view trimHeader(std::string_view text)
{
const auto first=text.find_first_not_of(" \t");
return first==text.npos?std::string_view{}:text.substr(first,text.find_last_not_of(" \t")-first+1);
}
struct HttpRequest
{
std::string_view method,path;
std::map<std::string,std::string_view,std::less<>> headers;
std::string_view header(std::string_view field) const
{
const auto found=headers.find(field);
return found==headers.end()?std::string_view{}:found->second;
}
};
std::optional<HttpRequest> parseHeaders(std::string_view data)
{
HttpRequest request;
auto end=data.find("\r\n");
const auto line=data.substr(0,end);
const auto first=line.find(' '),second=first==line.npos?line.npos:line.find(' ',first+1);
if(end==data.npos || !first || second==line.npos || line.substr(second+1)!="HTTP/1.1") return {};
request.method=line.substr(0,first);
request.path=line.substr(first+1,second-first-1);
data.remove_prefix(end+2);
while(!data.empty())
{
end=data.find("\r\n");
const auto header=data.substr(0,end);
const auto colon=header.find(':');
if(!colon || colon==header.npos) return {};
const auto name=lowerAscii(header.substr(0,colon));
const auto value=trimHeader(header.substr(colon+1));
if(!std::ranges::all_of(name,[](char ch)
{return (ch>='a' && ch<='z') || (ch>='0' && ch<='9') || ch=='-' || ch=='_';}) ||
!std::ranges::all_of(value,[](unsigned char ch){return ch=='\t' || (ch>=32 && ch<127);}) ||
!request.headers.emplace(name,value).second)
return {};
if(end==data.npos) break;
data.remove_prefix(end+2);
}
return request;
}
bool hasSessionToken(std::string_view authorization,std::string_view token)
{
if(authorization.size()!=token.size()+7 || lowerAscii(authorization.substr(0,7))!="bearer ") return false;
unsigned difference=0;
for(size_t i=0;i<token.size();++i)
difference|=static_cast<unsigned char>(authorization[i+7]^token[i]);
return difference==0;
}
struct HttpReply
{
const char *status;
std::string body;
const char *headers="";
};
HttpReply jsonReply(const char *status,Json body)
{
return {status,body.dump(-1,' ',false,Json::error_handler_t::replace)};
}
HttpReply rpcError(const char *status,const Json &id,int code,const char *message)
{
return jsonReply(status,{{"jsonrpc","2.0"},{"id",id},{"error",{{"code",code},{"message",message}}}});
}
const Json &mcpTools()
{
static const auto tools=Json::parse(R"({"tools":[
{"name":"get_panels","description":"Read the two Files panes and their current local listings, selections and Find state.",
"inputSchema":{"type":"object","properties":{"offset":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":1,"maximum":50}},"additionalProperties":false},
"annotations":{"readOnlyHint":true,"destructiveHint":false,"openWorldHint":false}},
{"name":"search_files","description":"Search the current local listing or existing Find results by name or relative path.",
"inputSchema":{"type":"object","properties":{"side":{"type":"string","enum":["active","left","right"]},"query":{"type":"string","minLength":1,"maxLength":128},"offset":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":1,"maximum":50}},"required":["query"],"additionalProperties":false},
"annotations":{"readOnlyHint":true,"destructiveHint":false,"openWorldHint":false}},
{"name":"get_file_metadata","description":"Read cached metadata for a relative path already listed in a current local pane.",
"inputSchema":{"type":"object","properties":{"side":{"type":"string","enum":["active","left","right"]},"path":{"type":"string","minLength":1,"maxLength":2048}},"required":["path"],"additionalProperties":false},
"annotations":{"readOnlyHint":true,"destructiveHint":false,"openWorldHint":false}}
]})");
return tools;
}
Json toolResult(const Json &data,bool error=false)
{
const auto text=error?data.get<std::string>():data.dump(-1,' ',false,Json::error_handler_t::replace);
Json result{{"content",Json::array({{{"type","text"},{"text",text}}})},{"isError",error}};
if(!error) result["structuredContent"]=data;
return result;
}
template<class Read>
HttpReply handleRpc(std::string_view body,const Read &read)
{
Json message,id;
try
{
message=Json::parse(body,[](int depth,Json::parse_event_t,Json &)
{
if(depth>24) throw std::runtime_error("Request nesting limit");
return true;
});
}
catch(const std::exception &) {return rpcError("400 Bad Request",nullptr,-32700,"Invalid JSON");}
if(!message.is_object() || message.value("jsonrpc",Json())!="2.0" ||
!message.contains("method") || !message["method"].is_string())
return rpcError("400 Bad Request",nullptr,-32600,"Invalid request");
const auto &method=message["method"].get_ref<const std::string &>();
if(!message.contains("id"))
{
if(method=="notifications/initialized" || method=="notifications/cancelled") return {"202 Accepted",{}};
return rpcError("400 Bad Request",nullptr,-32600,"Unsupported notification");
}
id=message["id"];
if(!id.is_number_integer() && (!id.is_string() || id.get_ref<const std::string &>().size()>256))
return rpcError("400 Bad Request",nullptr,-32600,"Invalid request id");
auto params=message.value("params",Json::object());
if(!params.is_object()) return rpcError("200 OK",id,-32602,"Invalid parameters");
Json result;
if(method=="initialize")
{
if(!params.contains("protocolVersion") || !params["protocolVersion"].is_string())
return rpcError("200 OK",id,-32602,"Protocol version is required");
const auto version=params["protocolVersion"].get<std::string>();
result={{"protocolVersion",supportedProtocol(version)?version:std::string(latestProtocol)},
{"capabilities",{{"tools",Json::object()}}},
{"serverInfo",{{"name","kswitcher-files"},{"version","1.0.0"}}},
{"instructions","Inspect the current local listings and cached metadata. Search uses the Files panels' current results."}};
}
else if(method=="ping") result=Json::object();
else if(method=="tools/list") result=mcpTools();
else if(method=="tools/call")
{
if(!params.contains("name") || !params["name"].is_string())
return rpcError("200 OK",id,-32602,"Tool name is required");
const auto &name=params["name"].get_ref<const std::string &>();
const auto args=params.value("arguments",Json::object());
if(!args.is_object() || !std::ranges::any_of(mcpTools()["tools"],[&](const auto &tool)
{return tool["name"]==name;}))
return rpcError("200 OK",id,-32602,"Unknown tool or invalid arguments");
auto data=read(name,args);
const auto failed=data.contains("error");
result=failed?toolResult(data.at("error"),true):toolResult(data);
}
else return rpcError("200 OK",id,-32601,"Method not found");
auto answer=jsonReply("200 OK",{{"jsonrpc","2.0"},{"id",id},{"result",std::move(result)}});
return answer.body.size()<=maxResponse?std::move(answer):rpcError("200 OK",id,-32603,"Response is too large");
}
template<class Read>
HttpReply handleHttp(SOCKET socket,unsigned port,std::string_view token,std::stop_token stop,const Read &read)
{
std::string bytes;
const auto deadline=Clock::now()+2s;
size_t end{};
while((end=bytes.find("\r\n\r\n"))==bytes.npos)
{
if(bytes.size()>=maxHeaders) return {"431 Request Header Fields Too Large",{}};
if(!appendSocket(socket,bytes,stop,deadline)) return {"408 Request Timeout",{}};
}
if(end+4>maxHeaders) return {"431 Request Header Fields Too Large",{}};
// Header fields refer into bytes. Parse before appending any further data.
const auto request=parseHeaders(std::string_view(bytes).substr(0,end+2));
if(!request) return {"400 Bad Request",{}};
if(request->headers.contains("origin") || request->header("host")!="127.0.0.1:"+std::to_string(port))
return {"403 Forbidden",{}};
if(!hasSessionToken(request->header("authorization"),token))
return {"401 Unauthorized",{},"WWW-Authenticate: Bearer\r\n"};
if(request->path!="/mcp") return {"404 Not Found",{}};
if(request->method!="POST") return {"405 Method Not Allowed",{},"Allow: POST\r\n"};
if(request->headers.contains("transfer-encoding") ||
(request->headers.contains("mcp-protocol-version") && !supportedProtocol(request->header("mcp-protocol-version"))))
return {"400 Bad Request",{}};
const auto type=request->header("content-type");
if(lowerAscii(trimHeader(type.substr(0,type.find(';'))))!="application/json") return {"415 Unsupported Media Type",{}};
const auto length=request->header("content-length");
size_t count{};
if(length.empty()) return {"411 Length Required",{}};
const auto converted=std::from_chars(length.data(),length.data()+length.size(),count);
if(converted.ec!=std::errc{} || converted.ptr!=length.data()+length.size()) return {"400 Bad Request",{}};
if(count>maxRequest) return {"413 Content Too Large",{}};
const auto start=end+4;
while(bytes.size()-start<count)
if(!appendSocket(socket,bytes,stop,deadline)) return {"408 Request Timeout",{}};
if(bytes.size()-start!=count) return {"400 Bad Request",{}};
return handleRpc(std::string_view(bytes).substr(start,count),read);
}
}
struct FilesMcpServer::Session
{
struct Query
{
std::string name;
Json arguments;
std::promise<Json> result;
std::atomic_bool cancelled{};
};
lan::Network network;
lan::WinSocket listener;
unsigned port{};
std::string token=lan::randomHex(32);
HWND owner{};
std::mutex gate;
std::shared_ptr<Query> pending;
std::jthread worker;
explicit Session(HWND window):owner(window)
{
listener.value=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
BOOL exclusive=TRUE;
u_long nonblocking=1;
sockaddr_in address{};
address.sin_family=AF_INET;
address.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
int size=sizeof(address);
if(listener.value==INVALID_SOCKET || setsockopt(listener.value,SOL_SOCKET,SO_EXCLUSIVEADDRUSE,
reinterpret_cast<const char*>(&exclusive),sizeof(exclusive)) ||
ioctlsocket(listener.value,FIONBIO,&nonblocking) ||
bind(listener.value,reinterpret_cast<const sockaddr *>(&address),sizeof(address)) ||
listen(listener.value,4) || getsockname(listener.value,reinterpret_cast<sockaddr *>(&address),&size))
lan::socketError();
port=ntohs(address.sin_port);
worker=std::jthread([this](std::stop_token stop){run(stop);});
}
~Session()
{
worker.request_stop();
if(worker.joinable()) worker.join();
SecureZeroMemory(token.data(),token.size());
}
Json requestUi(std::string_view name,const Json &arguments,std::stop_token stop)
{
auto query=std::make_shared<Query>();
query->name=name;
query->arguments=arguments;
auto result=query->result.get_future();
{
std::lock_guard lock(gate);
pending=query;
}
const auto deadline=Clock::now()+2s;
if(PostMessageW(owner,filesMcpQueryMessage,0,0))
while(!stop.stop_requested() && Clock::now()<deadline)
if(result.wait_for(25ms)==std::future_status::ready) return result.get();
query->cancelled=true;
std::lock_guard lock(gate);
if(pending==query) pending.reset();
return {{"error","Files did not answer in time."}};
}
void run(std::stop_token stop)
{
while(!stop.stop_requested())
{
if(!readySocket(listener.value,false,stop,Clock::now()+100ms)) continue;
sockaddr_in peer{};
int peerSize=sizeof(peer);
lan::WinSocket client;
client.value=accept(listener.value,reinterpret_cast<sockaddr *>(&peer),&peerSize);
u_long nonblocking=1;
if(client.value==INVALID_SOCKET || peer.sin_family!=AF_INET ||
peer.sin_addr.s_addr!=htonl(INADDR_LOOPBACK) || ioctlsocket(client.value,FIONBIO,&nonblocking))
continue;
HttpReply reply{"500 Internal Server Error",{}};
try
{
reply=handleHttp(client.value,port,token,stop,[&](std::string_view name,const Json &params)
{return requestUi(name,params,stop);});
}
catch(const std::exception &) {}
const auto header=std::string("HTTP/1.1 ")+reply.status+"\r\nConnection: close\r\n"
"Cache-Control: no-store\r\nContent-Type: application/json\r\n"+reply.headers+
"Content-Length: "+std::to_string(reply.body.size())+"\r\n\r\n";
sendSocket(client.value,header+reply.body,stop);
}
}
};
FilesMcpServer::FilesMcpServer()=default;
FilesMcpServer::~FilesMcpServer()=default;
void FilesMcpServer::start(HWND owner)
{
if(!session) session=std::make_unique<Session>(owner);
}
void FilesMcpServer::stop() {session.reset();}
unsigned FilesMcpServer::port() const {return session?session->port:0;}
std::string_view FilesMcpServer::token() const {return session?std::string_view(session->token):std::string_view{};}
void FilesMcpServer::answer(const ReadTool &read)
{
if(!session) return;
std::shared_ptr<Session::Query> query;
{
std::lock_guard lock(session->gate);
query=std::exchange(session->pending,{});
}
if(!query || query->cancelled) return;
try {query->result.set_value(read(query->name,query->arguments));}
catch(const std::exception &) {query->result.set_value({{"error","Files could not read the requested state."}});}
}
}
+33
View File
@@ -0,0 +1,33 @@
#pragma once
#include "../vendor/json.hpp"
#include <windows.h>
#include <functional>
#include <memory>
#include <string_view>
namespace ks::files
{
inline constexpr UINT filesMcpQueryMessage=WM_APP+274;
class FilesMcpServer
{
public:
using Json=nlohmann::json;
using ReadTool=std::function<Json(std::string_view,const Json &)>;
FilesMcpServer();
~FilesMcpServer();
FilesMcpServer(const FilesMcpServer &)=delete;
FilesMcpServer &operator=(const FilesMcpServer &)=delete;
void start(HWND owner);
void stop();
unsigned port() const;
std::string_view token() const;
void answer(const ReadTool &read);
private:
struct Session;
std::unique_ptr<Session> session;
};
}
+223
View File
@@ -0,0 +1,223 @@
ks::files::FilesMcpServer filesMcp;
constexpr int filesMcpStatus=690,filesMcpEndpoint=691,filesMcpToken=692,filesMcpToggle=693,
filesMcpShowToken=694,filesMcpCopyToken=695;
constexpr size_t maxMcpRows=50,maxMcpSearchScan=10000;
std::string mcpSide(int side) {return side==0?"left":"right";}
bool mcpLocalPanel(const Panel &panel)
{
return !panel.peer && !panel.ftp && !panel.archive && ks::files::isLocalDocumentPath(panel.directory);
}
std::optional<std::wstring> mcpRelativePath(const Panel &panel,size_t row)
{
if(row>=panel.rows.size() || row>=panel.sizes.size() || panel.sizes[row]==L"Up") return {};
const auto relative=panel.rows[row].lexically_relative(panel.directory);
if(relative.empty() || relative.has_root_path()) return {};
for(const auto &part:relative)
if(!ks::files::validWindowsFileName(part.native())) return {};
const auto path=relative.generic_wstring();
if(path.size()>2048) return {};
return path;
}
Json mcpFileItem(const Panel &panel,size_t row,const std::wstring &relative)
{
Json item{{"path",ks::utf8(relative)},{"marked",row<panel.marked.size() && panel.marked[row]}};
const auto found=panel.metadata.find(panel.rows[row]);
if(found==panel.metadata.end())
{
item["metadataAvailable"]=false;
return item;
}
const auto &info=found->second;
const bool directory=(info.attributes&FILE_ATTRIBUTE_DIRECTORY)!=0;
item["metadataAvailable"]=true;
item["kind"]=directory?"directory":"file";
item["attributes"]=info.attributes;
item["reparsePoint"]=(info.attributes&FILE_ATTRIBUTE_REPARSE_POINT)!=0;
if(!directory) item["sizeBytes"]=info.size;
if(info.modified)
{
const FILETIME time{static_cast<DWORD>(info.modified),static_cast<DWORD>(info.modified>>32)};
SYSTEMTIME utc{};
if(FileTimeToSystemTime(&time,&utc))
{
wchar_t date[32]{};
swprintf_s(date,L"%04u-%02u-%02uT%02u:%02u:%02uZ",utc.wYear,utc.wMonth,utc.wDay,
utc.wHour,utc.wMinute,utc.wSecond);
item["modifiedUtc"]=ks::utf8(date);
}
}
return item;
}
std::optional<size_t> mcpPageValue(const Json &args,const char *key,size_t fallback,size_t maximum)
{
if(!args.contains(key)) return fallback;
const auto &value=args.at(key);
if(!value.is_number_unsigned() || value>maximum) return {};
return value.get<size_t>();
}
bool mcpArgumentNames(const Json &arguments,std::initializer_list<std::string_view> accepted)
{
for(auto field=arguments.begin();field!=arguments.end();++field)
if(std::ranges::find(accepted,std::string_view(field.key()))==accepted.end()) return false;
return true;
}
std::optional<int> mcpArgumentSide(const Json &arguments)
{
if(!arguments.contains("side") || arguments.at("side")=="active") return active;
if(arguments.at("side")=="left") return 0;
if(arguments.at("side")=="right") return 1;
return {};
}
Json mcpPanelPage(const Panel &panel,size_t offset,size_t limit,std::wstring_view query={})
{
Json entries=Json::array();
size_t row=std::min(offset,panel.rows.size());
const auto scannedEnd=row+std::min(maxMcpSearchScan,panel.rows.size()-row);
for(;row<scannedEnd && entries.size()<limit;++row)
if(const auto relative=mcpRelativePath(panel,row))
if(query.empty() || ks::lower(*relative).find(query)!=std::wstring::npos)
entries.push_back(mcpFileItem(panel,row,*relative));
return {{"entries",std::move(entries)},{"nextOffset",row<panel.rows.size()?Json(row):Json(nullptr)}};
}
Json mcpPanelState(int side,size_t offset,size_t limit)
{
const auto &panel=panels[side];
Json result{{"side",mcpSide(side)},{"available",mcpLocalPanel(panel)},
{"visible",IsWindowVisible(panel.list)!=FALSE}};
if(!result.at("available").get<bool>()) return result;
result["directory"]=ks::utf8(panel.directory.native());
result["mode"]=ks::utf8(panelModeNames[static_cast<size_t>(panel.mode)]);
result["scanning"]=panel.scanRequest.has_value();
const auto selected=currentPanelRow(panel);
if(selected!=LB_ERR)
if(const auto path=mcpRelativePath(panel,static_cast<size_t>(selected))) result["cursor"]=ks::utf8(*path);
const auto *pending=panel.scanRequest && panel.scanRequest->find?&*panel.scanRequest->find:nullptr;
if(pending || panel.findOrigin)
{
const auto &find=pending?*pending:panel.findOrigin->options;
result["find"]={{"mask",ks::utf8(find.mask)},{"includeHidden",find.includeHidden},
{"running",pending!=nullptr},{"error",pending?0:panel.findOrigin->error}};
}
result.update(mcpPanelPage(panel,offset,limit));
return result;
}
Json readFilesMcpTool(std::string_view tool,const Json &arguments)
{
const auto offset=mcpPageValue(arguments,"offset",0,2147483647);
const auto limit=mcpPageValue(arguments,"limit",25,maxMcpRows);
if(!offset || !limit || !*limit) return {{"error","Invalid page offset or limit."}};
if(tool=="get_panels")
{
if(!mcpArgumentNames(arguments,{"offset","limit"})) return {{"error","Unknown pane argument."}};
return {{"active",mcpSide(active)},{"panels",Json::array(
{mcpPanelState(0,*offset,*limit),mcpPanelState(1,*offset,*limit)})}};
}
const auto side=mcpArgumentSide(arguments);
if(!side) return {{"error","Choose an active, left or right pane."}};
const auto &panel=panels[*side];
if(!mcpLocalPanel(panel)) return {{"error","This pane is not a local filesystem listing."}};
if(tool=="search_files")
{
if(!mcpArgumentNames(arguments,{"side","query","offset","limit"}) || !arguments.contains("query") ||
!arguments["query"].is_string() || arguments["query"].get_ref<const std::string &>().size()>512)
return {{"error","Enter a search query of 1 to 128 characters."}};
auto query=ks::wide(arguments["query"].get_ref<const std::string &>());
if(query.empty() || query.size()>128 || query.find_first_of(L"\r\n")!=query.npos ||
query.find(L'\0')!=query.npos) return {{"error","Enter a search query of 1 to 128 characters."}};
auto result=mcpPanelPage(panel,*offset,*limit,ks::lower(std::move(query)));
result["side"]=mcpSide(*side);
result["scope"]=panel.findOrigin?"find-results":"current-listing";
return result;
}
if(tool!="get_file_metadata" || !mcpArgumentNames(arguments,{"side","path"}) ||
!arguments.contains("path") || !arguments["path"].is_string() ||
arguments["path"].get_ref<const std::string &>().size()>8192)
return {{"error","Choose a relative path from the current pane."}};
auto relative=fs::path(ks::wide(arguments["path"].get_ref<const std::string &>()));
if(relative.empty() || relative.has_root_path() || relative.native().size()>2048)
return {{"error","Choose a relative path from the current pane."}};
for(const auto &part:relative)
if(!ks::files::validWindowsFileName(part.native()))
return {{"error","Choose a relative path from the current pane."}};
relative.make_preferred();
const auto path=panel.directory/relative;
const auto found=std::ranges::find(panel.rows,path);
if(found==panel.rows.end()) return {{"error","The file is not in the current pane."}};
const auto row=static_cast<size_t>(found-panel.rows.begin());
const auto listed=mcpRelativePath(panel,row);
if(!listed) return {{"error","The file is not in the current pane."}};
return mcpFileItem(panel,row,*listed);
}
void updateFilesMcpDialog(HWND dialog)
{
const auto port=filesMcp.port();
const auto endpoint=port?L"http://127.0.0.1:"+std::to_wstring(port)+L"/mcp":L"";
SetDlgItemTextW(dialog,filesMcpEndpoint,endpoint.c_str());
SetDlgItemTextW(dialog,filesMcpToggle,port?L"&Stop":L"&Start");
EnableWindow(GetDlgItem(dialog,filesMcpShowToken),port!=0);
EnableWindow(GetDlgItem(dialog,filesMcpCopyToken),port!=0);
if(!port) CheckDlgButton(dialog,filesMcpShowToken,BST_UNCHECKED);
const auto token=port && IsDlgButtonChecked(dialog,filesMcpShowToken)==BST_CHECKED?
ks::wide(std::string(filesMcp.token())):L"";
SetDlgItemTextW(dialog,filesMcpToken,token.c_str());
SetDlgItemTextW(dialog,filesMcpStatus,port?
L"Running on this computer. Stop to revoke the session token.":L"Stopped.");
}
INT_PTR CALLBACK filesMcpDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
updateFilesMcpDialog(dialog);
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && (LOWORD(wp)==IDOK || LOWORD(wp)==IDCANCEL)))
{
SetDlgItemTextW(dialog,filesMcpToken,L"");
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND) return FALSE;
switch(LOWORD(wp))
{
case filesMcpToggle:
try
{
if(filesMcp.port()) filesMcp.stop();
else filesMcp.start(reinterpret_cast<HWND>(GetWindowLongPtrW(dialog,DWLP_USER)));
updateFilesMcpDialog(dialog);
}
catch(const std::exception &)
{
SetDlgItemTextW(dialog,filesMcpStatus,L"Could not start the local MCP listener.");
}
return TRUE;
case filesMcpShowToken:
updateFilesMcpDialog(dialog);
return TRUE;
case filesMcpCopyToken:
if(filesMcp.port() && copyFilesText(dialog,ks::wide(std::string(filesMcp.token())),L"Could not copy the token."))
SetDlgItemTextW(dialog,filesMcpStatus,L"Session token copied.");
return TRUE;
}
return FALSE;
}
void showFilesMcp(HWND owner)
{
FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(620),owner,filesMcpDialog,
reinterpret_cast<LPARAM>(owner),false,false);
dialog.runModal();
}
+10 -4
View File
@@ -58,20 +58,20 @@ bool retryRemotePanel(Panel &panel,bool automatic,const fs::path &fallback)
return true;
}
void openFolderLocation(Panel &panel,const FolderLocation &location,std::optional<size_t> position={})
void openFolderLocation(Panel &panel,const FolderLocation &location,std::optional<size_t> position={},fs::path selection={})
{
if(location.directory.empty()) return;
if(location.provider==FolderProvider::local)
{
openOn(panel,location.directory,true,{},{},{},{},position);
openOn(panel,location.directory,true,{},std::move(selection),{},{},position);
return;
}
if(location.sameSource(folderLocation(panel,panel.directory)))
{
openOn(panel,location.directory,false,panel.peer,{},{},panel.ftp,position);
openOn(panel,location.directory,false,panel.peer,std::move(selection),{},panel.ftp,position);
return;
}
RemotePanelLocation remote{location.directory,{},{},{},position};
RemotePanelLocation remote{location.directory,std::move(selection),{},{},position};
if(isTransferFolder(location.provider))
{
remote.ftpProfile=location.id;
@@ -124,6 +124,12 @@ void saveFtpPanelLocation(const Panel &panel,int index)
location=panel.remoteRetry->location;
else if(panel.scanRequest && panel.scanRequest->ftp && panel.scanRequest->ftp->protocol==TransferProtocol::ftp)
location={panel.scanRequest->directory,panel.scanRequest->selection,panel.scanRequest->ftp->id};
else if(panel.listing && !panel.navigation.history.empty())
{
const auto &previous=panel.navigation.history[panel.navigation.current];
if(previous.provider==FolderProvider::ftp)
location={previous.directory,panel.listing->returnSelection,previous.id};
}
const auto key=ftpPanelLocationKeys[index];
if(location.ftpProfile.empty() || !isFtpFolderPath(location.directory))
+6 -6
View File
@@ -2,7 +2,7 @@ class PanelRowsUpdate
{
public:
PanelRowsUpdate(Panel &panel,size_t count) : panel(panel),visible(IsWindowVisible(panel.list)),
profiles(transferProfileList(panel))
locationList(panelListsLocations(panel))
{
if(visible) SendMessageW(panel.list,WM_SETREDRAW,FALSE,0);
panel.rows.clear();
@@ -33,10 +33,10 @@ public:
}
panel.marked.push_back(!up && marked);
const auto found=panel.metadata.find(path);
const auto entry=up || profiles || found==panel.metadata.end()?FolderEntryMetadata{}:found->second;
const auto entry=up || locationList || found==panel.metadata.end()?FolderEntryMetadata{}:found->second;
panel.dimmed.push_back((entry.attributes&(FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_HIDDEN))!=0);
panel.sizes.push_back(profiles?L"":folder?(up?L"Up":L"Folder"):std::to_wstring(entry.size));
if(!up && !profiles)
panel.sizes.push_back(up?L"Up":locationList?L"":folder?L"Folder":std::to_wstring(entry.size));
if(!up && !locationList)
{
auto &longest=panel.longestColumn;
longest[sizeColumn]=std::max(longest[sizeColumn],panel.sizes.back().size());
@@ -63,7 +63,7 @@ public:
private:
Panel &panel;
bool visible,profiles;
bool visible,locationList;
};
bool treePanelActive(const Panel &panel)
@@ -120,7 +120,7 @@ void visitPanelMarks(const Panel &panel,const Visitor &visit)
}
return;
}
if(transferProfileList(panel)) return;
if(panelListsLocations(panel)) return;
for(size_t i=0;i<panel.rows.size();++i)
{
if(!panel.marked[i] || panel.sizes[i]==L"Up") continue;
+44 -24
View File
@@ -318,24 +318,18 @@ void editPanelPath(Panel &panel)
}
void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector<FolderLocation> locations,
RECT anchor,bool recent=false)
RECT anchor)
{
hidePicker();
showMenu(false);
commandPicker=false;
pickerPanel=side;
folderPicker=FolderPicker{caption,std::move(locations),recent};
folderPicker=FolderPicker{caption,std::move(locations)};
SendMessageW(picker,LB_RESETCONTENT,0,0);
size_t longest=wcslen(caption);
for(const auto &location:folderPicker->locations)
{
auto label=isTransferFolder(location.provider)?ftpPath(location.directory):location.directory.native();
if(recent && location.provider!=FolderProvider::local)
{
const auto &source=location.label;
const auto kind=isTransferFolder(location.provider)?transferProtocolName(folderTransferProtocol(location.provider)):L"LAN";
label=std::wstring(kind)+L" · "+(source.empty()?std::wstring{}:source+L" · ")+label;
}
longest=std::max(longest,label.size());
SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
}
@@ -356,26 +350,52 @@ void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector<Fol
SetFocus(picker);
}
void showRecentFolders(int side)
void showRecentFolders(Panel &panel)
{
auto locations=readRecentFolders();
if(locations.empty())
PanelListing listing;
listing.recent=readRecentFolders();
listing.rows.reserve(listing.recent.size());
for(size_t i=0;i<listing.recent.size();++i)
{
setStatus(L"No recent folders.");
auto &location=listing.recent[i];
auto label=location.directory.native();
if(location.provider!=FolderProvider::local)
{
const wchar_t *kind=L"LAN";
if(isTransferFolder(location.provider))
{
const auto protocol=folderTransferProtocol(location.provider);
kind=transferProtocolName(protocol);
if(loadTransferProfiles(protocol))
if(const auto *profile=findTransferProfile(location.id,protocol)) location.label=profile->name;
label=ftpPath(location.directory);
}
if(!location.label.empty()) label=location.label+L" · "+label;
label=std::wstring(kind)+L" · "+label;
}
listing.rows.emplace_back(std::to_wstring(i),std::move(label));
}
openPanelListing(panel,std::move(listing));
}
void openRecentFolder(Panel &panel)
{
const auto row=currentPanelRow(panel);
if(row!=LB_ERR && !panel.scan.valid())
openFolderLocation(panel,panel.listing->recent[row]);
}
void removeRecentFolder(Panel &panel)
{
const auto row=currentPanelRow(panel);
if(row==LB_ERR || panel.scan.valid()) return;
if(!updateRecentFolders(panel.listing->recent[row],false))
{
setStatus(L"Could not remove the recent folder.");
return;
}
const auto owner=GetParent(picker);
RECT anchor{};
GetWindowRect(panels[side].path,&anchor);
MapWindowPoints(nullptr,owner,reinterpret_cast<POINT *>(&anchor),2);
for(auto &location:locations)
{
if(!isTransferFolder(location.provider)) continue;
const auto protocol=folderTransferProtocol(location.provider);
if(loadTransferProfiles(protocol))
if(const auto *profile=findTransferProfile(location.id,protocol)) location.label=profile->name;
}
showFolderPicker(owner,side,L"Recent folders",std::move(locations),anchor,true);
for(auto &other:panels)
if(recentFolderList(other) && !other.scan.valid()) showRecentFolders(other);
}
void showHiddenPathParts(HWND window,int side,const PathPart &part)
+1 -1
View File
@@ -129,7 +129,7 @@ void showReadOnlyProperties(HWND owner,const ItemProperties &properties,const st
bool panelItemPropertiesAvailable(const Panel &panel)
{
const auto row=currentPanelRow(panel);
return row!=LB_ERR && panel.sizes[row]!=L"Up" && !transferProfileList(panel);
return row!=LB_ERR && panel.sizes[row]!=L"Up" && !panelListsLocations(panel);
}
void showSourceItemProperties(HWND owner,const Panel &panel,const fs::path &path,ItemProperties properties)
+166 -203
View File
@@ -2,7 +2,6 @@ namespace smb
{
constexpr wchar_t profilesKey[]=L"SmbProfiles";
constexpr DWORD shareTypeMask=0xff;
constexpr int summary=540,list=541,status=542,footer=543,newProfile=544,editProfile=545,removeProfile=546,signIn=547;
constexpr int nameLabel=550,nameField=551,addressLabel=552,addressField=553,editFooter=554;
constexpr int loginLabel=555,userLabel=556,userField=557,passwordLabel=558,passwordField=559,rememberField=560,loginFooter=561;
@@ -400,234 +399,198 @@ INT_PTR CALLBACK loginDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
return TRUE;
}
struct Browser
struct PendingConnection
{
std::vector<Profile> profiles;
std::optional<Profile> server;
std::vector<std::wstring> shares;
fs::path chosen;
Profile profile;
std::atomic_bool canceled{};
bool busy{};
std::promise<Connection> result;
std::future<Connection> completion=result.get_future();
};
void browserControls(HWND dialog,const Browser &browser)
std::optional<Profile> findProfile(const fs::path &id)
{
const auto selected=SendDlgItemMessageW(dialog,list,LB_GETCURSEL,0,0)!=LB_ERR;
EnableWindow(GetDlgItem(dialog,list),!browser.busy);
EnableWindow(GetDlgItem(dialog,IDOK),!browser.busy && selected);
EnableWindow(GetDlgItem(dialog,newProfile),!browser.busy);
for(const auto button:{editProfile,removeProfile,signIn})
EnableWindow(GetDlgItem(dialog,button),!browser.busy && selected && !browser.server);
const auto profiles=readProfiles();
const auto match=std::find_if(profiles.begin(),profiles.end(),[&](const auto &profile) {
return ks::wide(profile.id)==id.native();
});
return match==profiles.end()?std::nullopt:std::optional{*match};
}
void showRows(HWND dialog,const Browser &browser,LRESULT selection=0)
std::optional<Profile> selectedProfile(const Panel &panel)
{
const auto rows=GetDlgItem(dialog,list);
SendMessageW(rows,LB_RESETCONTENT,0,0);
const auto add=[&](const std::wstring &label){SendMessageW(rows,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));};
if(browser.server)
{
for(const auto &share:browser.shares) add(share);
SetDlgItemTextW(dialog,summary,(L"Shared folders on "+browser.server->target.server).c_str());
SetDlgItemTextW(dialog,status,browser.shares.empty()?L"No visible disk shares. A known UNC share can be saved as a profile.":L"");
SetDlgItemTextW(dialog,newProfile,L"&Back");
for(const auto button:{editProfile,removeProfile,signIn}) ShowWindow(GetDlgItem(dialog,button),SW_HIDE);
layoutDialogButtons(dialog,footer,{IDOK,newProfile,IDCANCEL});
}
else
{
for(const auto &entry:browser.profiles) add(entry.name+L" · "+profileAddress(entry));
SetDlgItemTextW(dialog,summary,L"Saved SMB connections");
SetDlgItemTextW(dialog,status,browser.profiles.empty()?L"Choose New to add a server or UNC folder.":L"");
SetDlgItemTextW(dialog,newProfile,L"&New");
for(const auto button:{editProfile,removeProfile,signIn}) ShowWindow(GetDlgItem(dialog,button),SW_SHOWNA);
layoutDialogButtons(dialog,footer,{IDOK,newProfile,editProfile,removeProfile,signIn,IDCANCEL});
}
const auto count=SendMessageW(rows,LB_GETCOUNT,0,0);
if(count>0) SendMessageW(rows,LB_SETCURSEL,std::clamp<LRESULT>(selection,0,count-1),0);
browserControls(dialog,browser);
SetFocus(count>0?rows:GetDlgItem(dialog,newProfile));
if(!panel.listing || !panel.listing->smb || !panel.listing->smb->server.empty() || panel.scan.valid() || panel.smbPending) return {};
const auto row=currentPanelRow(panel);
return row==LB_ERR?std::nullopt:findProfile(panel.rows[row]);
}
void openProfile(HWND dialog,Browser &browser,const Profile &profile,bool withLogin)
void showProfiles(Panel &panel,const std::vector<Profile> &profiles,fs::path selection={})
{
Credentials login;
PanelListing listing{SmbListing{}};
listing.rows.reserve(profiles.size());
for(const auto &profile:profiles)
listing.rows.emplace_back(ks::wide(profile.id),profile.name+L" · "+profileAddress(profile));
openPanelListing(panel,std::move(listing),std::move(selection));
}
void refreshProfiles(Panel &panel,const std::vector<Profile> &profiles,fs::path selection={})
{
for(auto &other:panels)
if(other.listing && other.listing->smb && other.listing->smb->server.empty() && !other.smbPending && !other.scan.valid())
showProfiles(other,profiles,&other==&panel?selection:fs::path{});
}
void openProfile(Panel &panel,Profile profile,bool withLogin)
{
if(panel.smbPending || panel.scan.valid()) return;
const auto owner=GetParent(panel.list);
std::shared_ptr<Credentials> login;
if(withLogin)
{
LoginPrompt prompt{profile,login};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(123),dialog,loginDialog,
login=std::make_shared<Credentials>();
LoginPrompt prompt{profile,*login};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(123),owner,loginDialog,
reinterpret_cast<LPARAM>(&prompt))!=IDOK) return;
}
browser.busy=true;
browser.canceled=false;
browserControls(dialog,browser);
SetFocus(GetDlgItem(dialog,IDCANCEL));
SetDlgItemTextW(dialog,status,(L"Connecting to "+profile.target.server+L"…").c_str());
Connection result;
auto pending=std::make_shared<PendingConnection>();
pending->profile=std::move(profile);
try
{
FileOperationUi worker;
worker.run(dialog,browser.canceled,[&]{result=connect(profile,withLogin?&login:nullptr,browser.canceled);});
std::thread([pending,login=std::move(login),owner] {
Connection connection;
try {connection=connect(pending->profile,login.get(),pending->canceled);}
catch(const std::exception &) {connection.error=ERROR_GEN_FAILURE;}
pending->result.set_value(std::move(connection));
PostMessageW(owner,directoryScanReady,0,0);
}).detach();
}
catch(const std::exception &)
catch(const std::system_error &error)
{
result.error=ERROR_GEN_FAILURE;
}
browser.busy=false;
browserControls(dialog,browser);
if(browser.canceled)
{
SetDlgItemTextW(dialog,status,L"Connection canceled.");
SetFocus(GetDlgItem(dialog,list));
setStatus(L"Could not start SMB connection: "+fileError(error));
return;
}
if(result.error)
{
auto detail=profileAddress(profile)+L"\r\n\r\n"+errorText(result.error);
if(result.error==ERROR_ACCESS_DENIED || result.error==ERROR_LOGON_FAILURE ||
result.error==ERROR_INVALID_PASSWORD || result.error==ERROR_BAD_USERNAME)
detail+=L"\r\n\r\nUse Sign in to try a different account.";
showFilesNotice(dialog,detail.c_str(),L"Could not open SMB connection",{.tone=FilesNoticeTone::warning});
SetDlgItemTextW(dialog,status,L"Connection failed. Open to retry or choose Sign in.");
SetFocus(GetDlgItem(dialog,list));
return;
}
if(result.credentialError)
{
const auto detail=L"Connected, but Windows Credential Manager did not save the account.\r\n\r\n"+
errorText(result.credentialError);
showFilesNotice(dialog,detail.c_str(),L"SMB sign in",{.tone=FilesNoticeTone::warning});
}
if(!result.folder.empty())
{
browser.chosen=std::move(result.folder);
FilesModalDialog::finish(dialog,IDOK);
return;
}
browser.server=profile;
browser.shares=std::move(result.shares);
showRows(dialog,browser);
panel.smbPending=std::move(pending);
if(&panel==&panels[active]) showFileDetails(panel);
}
}
INT_PTR CALLBACK browserDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
void cancelSmbConnection(Panel &panel)
{
auto *browser=reinterpret_cast<Browser*>(GetWindowLongPtrW(dialog,DWLP_USER));
if(message==WM_INITDIALOG)
{
browser=reinterpret_cast<Browser*>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareCopyDialog(dialog);
layoutDialogContent(dialog,summary);
for(const auto id:{summary,list,status})
SendDlgItemMessageW(dialog,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
SendDlgItemMessageW(dialog,list,LB_SETITEMHEIGHT,0,textHeight);
installScrollBar(GetDlgItem(dialog,list),dialog);
showRows(dialog,*browser);
return FALSE;
}
if(message==WM_DRAWITEM && wp==list)
{
const auto &item=*reinterpret_cast<const DRAWITEMSTRUCT*>(lp);
if(item.itemID==UINT(-1)) return TRUE;
const auto length=SendMessageW(item.hwndItem,LB_GETTEXTLEN,item.itemID,0);
if(length==LB_ERR) return TRUE;
std::wstring label(static_cast<size_t>(length)+1,L'\0');
SendMessageW(item.hwndItem,LB_GETTEXT,item.itemID,reinterpret_cast<LPARAM>(label.data()));
const bool selected=(item.itemState&ODS_SELECTED)!=0;
paintDialogListRow(item.hDC,item.rcItem,label.c_str(),mono,colors[Text],
selected?colors[Selection]:colors[Dialog],dialogRowTextInset(cellWidth),DT_END_ELLIPSIS);
return TRUE;
}
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" SMB ",false,{footer},true,GetDlgItem(dialog,list)))
return painted;
if(!browser) return FALSE;
if(closeRequest(message,wp))
{
if(browser->busy)
{
browser->canceled=true;
SetDlgItemTextW(dialog,status,L"Stopping when Windows returns…");
}
else FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND) return FALSE;
if(browser->busy) return TRUE;
const auto command=LOWORD(wp);
const auto row=SendDlgItemMessageW(dialog,list,LB_GETCURSEL,0,0);
if(command==list && HIWORD(wp)==LBN_SELCHANGE)
{
browserControls(dialog,*browser);
return TRUE;
}
const bool open=command==IDOK || (command==list && HIWORD(wp)==LBN_DBLCLK);
if(browser->server)
{
if(command==newProfile)
{
browser->server.reset();
browser->shares.clear();
showRows(dialog,*browser);
}
else if(open && row>=0 && static_cast<size_t>(row)<browser->shares.size())
{
browser->chosen=fs::path(browser->server->target.server+L"\\"+browser->shares[row]);
FilesModalDialog::finish(dialog,IDOK);
}
return TRUE;
}
const auto *selected=row>=0 && static_cast<size_t>(row)<browser->profiles.size()?&browser->profiles[row]:nullptr;
if(command==newProfile || (command==editProfile && selected))
{
EditProfile edit{command==newProfile?Profile{}:*selected};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(122),dialog,editDialog,
reinterpret_cast<LPARAM>(&edit))==IDOK)
{
browser->profiles=std::move(*edit.saved);
const auto profile=std::find_if(browser->profiles.begin(),browser->profiles.end(),[&](const auto &entry) {
return entry.id==edit.profile.id;
});
showRows(dialog,*browser,profile-browser->profiles.begin());
}
return TRUE;
}
if(selected && (open || command==signIn))
{
openProfile(dialog,*browser,*selected,command==signIn);
return TRUE;
}
if(selected && command==removeProfile)
{
const auto detail=L"Remove "+selected->name+L" and its saved credentials?";
if(showFilesNotice(dialog,detail.c_str(),L"Remove SMB connection",{.confirm=true})!=IDYES) return TRUE;
DWORD error=ERROR_SUCCESS;
auto updated=updateProfiles([&](auto &profiles) {
const auto row=std::find_if(profiles.begin(),profiles.end(),[&](const auto &entry){return entry.id==selected->id;});
if(row==profiles.end()) return true;
if((error=deleteCredential(*row))) return false;
profiles.erase(row);
return true;
});
if(updated)
{
browser->profiles=std::move(*updated);
showRows(dialog,*browser,row);
}
else
{
const auto failure=error?errorText(error):L"Could not remove the saved connection.";
showFilesNotice(dialog,failure.c_str(),L"Remove SMB connection");
}
return TRUE;
}
return FALSE;
}
if(auto pending=std::exchange(panel.smbPending,{})) pending->canceled=true;
}
void showSmbProfiles(Panel &panel)
{
smb::Browser browser{smb::readProfiles()};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(121),GetParent(panel.list),
smb::browserDialog,reinterpret_cast<LPARAM>(&browser))==IDOK)
openOn(panel,browser.chosen,false,{});
smb::showProfiles(panel,smb::readProfiles());
}
void refreshSmbPanel(Panel &panel)
{
if(panel.scan.valid() || panel.smbPending) return;
if(panel.listing->smb->server.empty()) showSmbProfiles(panel);
else if(auto profile=smb::findProfile(ks::wide(panel.listing->smb->serverId));profile && profile->target.folder.empty())
smb::openProfile(panel,std::move(*profile),false);
else showSmbProfiles(panel);
}
void backSmbPanel(Panel &panel)
{
if(panel.smbPending)
{
cancelSmbConnection(panel);
setStatus(L"SMB connection canceled.");
}
else if(!panel.listing->smb->server.empty())
smb::showProfiles(panel,smb::readProfiles(),ks::wide(panel.listing->smb->serverId));
else closePanelListing(panel);
}
void enterSmbPanel(Panel &panel)
{
if(panel.scan.valid() || panel.smbPending) return;
if(panel.listing->smb->server.empty())
{
if(auto profile=smb::selectedProfile(panel)) smb::openProfile(panel,std::move(*profile),false);
return;
}
const auto row=currentPanelRow(panel);
if(row==LB_ERR) return;
const auto &name=panel.rows[row];
if(name==L"..") backSmbPanel(panel);
else openOn(panel,fs::path(panel.listing->smb->server+L"\\"+name.native()),false,{});
}
void editSmbProfile(Panel &panel,bool create)
{
if(!panel.listing || !panel.listing->smb || !panel.listing->smb->server.empty() || panel.smbPending || panel.scan.valid()) return;
const auto profile=create?std::optional{smb::Profile{}}:smb::selectedProfile(panel);
if(!profile) return;
smb::EditProfile edit{*profile};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(122),GetParent(panel.list),smb::editDialog,
reinterpret_cast<LPARAM>(&edit))==IDOK)
smb::refreshProfiles(panel,*edit.saved,ks::wide(edit.profile.id));
}
void removeSmbProfile(Panel &panel)
{
const auto selected=smb::selectedProfile(panel);
if(!selected) return;
const auto owner=GetParent(panel.list);
const auto detail=L"Remove "+selected->name+L" and its saved credentials?";
if(showFilesNotice(owner,detail.c_str(),L"Remove SMB connection",{.confirm=true})!=IDYES) return;
DWORD error=ERROR_SUCCESS;
const auto updated=smb::updateProfiles([&](auto &profiles) {
const auto entry=std::find_if(profiles.begin(),profiles.end(),[&](const auto &profile){return profile.id==selected->id;});
if(entry==profiles.end()) return true;
if((error=smb::deleteCredential(*entry))) return false;
profiles.erase(entry);
return true;
});
if(updated) smb::refreshProfiles(panel,*updated);
else
{
const auto failure=error?smb::errorText(error):L"Could not remove the saved connection.";
showFilesNotice(owner,failure.c_str(),L"Remove SMB connection");
}
}
void signInSmbProfile(Panel &panel)
{
if(auto profile=smb::selectedProfile(panel)) smb::openProfile(panel,std::move(*profile),true);
}
void collectSmbConnections(HWND owner)
{
for(auto &panel:panels)
{
if(!panel.smbPending || panel.smbPending->completion.wait_for(std::chrono::seconds(0))!=std::future_status::ready)
continue;
auto pending=std::exchange(panel.smbPending,{});
const auto result=pending->completion.get();
const auto &profile=pending->profile;
if(result.error)
{
auto detail=smb::profileAddress(profile)+L"\r\n\r\n"+smb::errorText(result.error);
if(result.error==ERROR_ACCESS_DENIED || result.error==ERROR_LOGON_FAILURE ||
result.error==ERROR_INVALID_PASSWORD || result.error==ERROR_BAD_USERNAME)
detail+=L"\r\n\r\nUse Sign in to try a different account.";
showFilesNotice(owner,detail.c_str(),L"Could not open SMB connection",{.tone=FilesNoticeTone::warning});
if(&panel==&panels[active]) showFileDetails(panel);
continue;
}
if(result.credentialError)
{
const auto detail=L"Connected, but Windows Credential Manager did not save the account.\r\n\r\n"+
smb::errorText(result.credentialError);
showFilesNotice(owner,detail.c_str(),L"SMB sign in",{.tone=FilesNoticeTone::warning});
}
if(!result.folder.empty()) openOn(panel,result.folder,false,{});
else
{
PanelListing listing{SmbListing{profile.id,profile.target.server}};
listing.rows.emplace_back(L"..",L"..");
for(const auto &share:result.shares) listing.rows.emplace_back(share,L"["+share+L"]");
const auto selectFirst=profile.id!=panel.listing->smb->serverId && !result.shares.empty();
openPanelListing(panel,std::move(listing),selectFirst?fs::path(result.shares.front()):fs::path{});
}
}
}
+35
View File
@@ -899,6 +899,41 @@ void setLoggingEnabled(bool enabled)
if (!enabled)
diagnosticBuffer.clear();
}
std::optional<Bytes> readActiveLogTail(bool previous,size_t byteLimit)
{
std::lock_guard lock(logGate);
auto path=logDirectory()/logFilename;
if(previous) path+=L".1";
const auto raw=CreateFileW(path.c_str(),GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
if(raw==INVALID_HANDLE_VALUE)
{
const auto error=GetLastError();
if(error==ERROR_FILE_NOT_FOUND || error==ERROR_PATH_NOT_FOUND) return {};
throw std::runtime_error("Cannot open the diagnostic log");
}
const std::unique_ptr<void,decltype(&CloseHandle)> file(raw,CloseHandle);
LARGE_INTEGER size{};
if(!GetFileSizeEx(raw,&size) || size.QuadPart<0) throw std::runtime_error("Cannot measure the diagnostic log");
const auto limit=std::min<uint64_t>(byteLimit,2*1024*1024);
if(!limit || !size.QuadPart) return Bytes{};
const auto offset=std::max<int64_t>(0,size.QuadPart-static_cast<int64_t>(limit));
LARGE_INTEGER position{};
position.QuadPart=offset?offset-1:0;
if(!SetFilePointerEx(raw,position,nullptr,FILE_BEGIN)) throw std::runtime_error("Cannot seek in the diagnostic log");
Bytes contents(static_cast<size_t>(size.QuadPart-position.QuadPart));
DWORD read{};
if(!ReadFile(raw,contents.data(),static_cast<DWORD>(contents.size()),&read,nullptr))
throw std::runtime_error("Cannot read the diagnostic log");
contents.resize(read);
if(offset && !contents.empty())
{
const auto newline=std::find(contents.begin(),contents.end(),'\n');
contents.erase(contents.begin(),newline==contents.end()?newline:std::next(newline));
}
return contents;
}
std::wstring readDiagnosticLog(bool previous)
{
std::lock_guard lock(logGate);
+1
View File
@@ -107,5 +107,6 @@ void expireDiagnostics(ULONGLONG now);
void diagnosticEvent(const std::wstring &message, bool problem = false);
void diagnosticOperation(const std::string &json);
std::wstring readDiagnosticLog(bool previous);
std::optional<Bytes> readActiveLogTail(bool previous,size_t byteLimit);
void clearDiagnosticLog(bool previous);
} // namespace ks
+1 -1
View File
@@ -2,7 +2,7 @@
#include "platform.h"
namespace ks
{
inline constexpr wchar_t AppVersion[] = L"0.7.4";
inline constexpr wchar_t AppVersion[] = L"0.8.0";
inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+33
View File
@@ -48,6 +48,39 @@ function Wait-For([string]$Name, [scriptblock]$Condition) {
throw "Timed out waiting for $Name."
}
function Read-FilesList([IntPtr]$List) {
$count = [FilesCommandsUi]::Send($List, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32()
for ($row = 0; $row -lt $count; ++$row) {
$label = [Text.StringBuilder]::new(32768)
if ([FilesCommandsUi]::Read($List, 393, [IntPtr]$row, $label).ToInt64() -lt 0) { break }
$label.ToString()
}
}
function Select-FilesListRow([IntPtr]$List, [string]$Label) {
$selection = [array]::IndexOf(@(Read-FilesList $List), $Label)
if ($selection -lt 0) { throw "Missing row '$Label'." }
[void][FilesCommandsUi]::Send($List, 390, [IntPtr]$selection, [IntPtr]::Zero)
}
function Open-FilesSource([IntPtr]$Window, [int]$Side, [string]$Source) {
$menu = if ($Side -eq 0) { 130 } else { 134 }
$picker = [FilesCommandsUi]::GetDlgItem($Window, 121)
[void][FilesCommandsUi]::Post($Window, 0x111, [IntPtr]$menu, [IntPtr]::Zero)
$entry = Wait-For "Change drive in panel ${Side}'s menu" {
if ([FilesCommandsUi]::IsWindowVisible($picker)) {
Read-FilesList $picker | Where-Object { $_ -like '*Change drive*' } | Select-Object -First 1
}
}
Select-FilesListRow $picker $entry
[void][FilesCommandsUi]::Post($Window, 0x111, [IntPtr](0x20000 + 121), $picker)
[void](Wait-For "$Source in panel ${Side}'s source picker" {
[FilesCommandsUi]::IsWindowVisible($picker) -and (Read-FilesList $picker) -contains $Source
})
Select-FilesListRow $picker $Source
[void][FilesCommandsUi]::Post($Window, 0x111, [IntPtr](0x20000 + 121), $picker)
}
function Invoke-FilesCommand([IntPtr]$Window, [string]$LabelPattern) {
[void][FilesCommandsUi]::Post($Window, 273, [IntPtr]132, [IntPtr]::Zero)
$picker = [FilesCommandsUi]::GetDlgItem($Window, 121)
+144
View File
@@ -0,0 +1,144 @@
#include "lan_network.h"
#include "files_mcp.h"
#include <chrono>
#include <future>
#include <iostream>
#include <stdexcept>
namespace
{
using Server=ks::files::FilesMcpServer;
using Json=Server::Json;
using namespace std::chrono_literals;
void expect(bool condition,const char *message)
{
if(!condition) throw std::runtime_error(message);
}
bool connectLoopback(SOCKET socket,unsigned port)
{
sockaddr_in address{};
address.sin_family=AF_INET;
address.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
address.sin_port=htons(static_cast<u_short>(port));
return connect(socket,reinterpret_cast<const sockaddr*>(&address),sizeof(address))==0;
}
std::string post(unsigned port,const std::string &token,const Json &message,
std::string_view extra={},std::string_view host={})
{
ks::lan::WinSocket client;
client.value=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
const DWORD timeout=4000;
expect(client.value!=INVALID_SOCKET &&
!setsockopt(client.value,SOL_SOCKET,SO_RCVTIMEO,reinterpret_cast<const char*>(&timeout),sizeof(timeout)) &&
connectLoopback(client.value,port),"Could not connect to fixture listener");
const auto body=message.dump();
const auto authority=host.empty()?"127.0.0.1:"+std::to_string(port):std::string(host);
const auto bytes="POST /mcp HTTP/1.1\r\nHost: "+authority+"\r\nContent-Type: application/json\r\n"
"Accept: application/json, text/event-stream\r\n"+
(token.empty()?std::string{}:"Authorization: Bearer "+token+"\r\n")+
std::string(extra)+"Content-Length: "+std::to_string(body.size())+"\r\n\r\n"+body;
expect(send(client.value,bytes.data(),static_cast<int>(bytes.size()),0)==static_cast<int>(bytes.size()),
"Could not send fixture request");
std::string response;
char buffer[4096];
for(;;)
{
const int count=recv(client.value,buffer,sizeof(buffer),0);
expect(count>=0,"Fixture request timed out");
if(!count) break;
response.append(buffer,count);
expect(response.size()<1024*1024,"Oversized fixture response");
}
return response;
}
Json content(const std::string &response)
{
const auto end=response.find("\r\n\r\n");
expect(end!=response.npos,"No HTTP headers");
return Json::parse(response.substr(end+4));
}
Json request(std::string_view method,Json params=Json::object())
{
return {{"jsonrpc","2.0"},{"id",4},{"method",method},{"params",std::move(params)}};
}
}
int main()
{
try
{
ks::lan::Network network;
const auto owner=CreateWindowExW(0,L"STATIC",L"Files MCP fixture",0,0,0,0,0,
HWND_MESSAGE,nullptr,GetModuleHandleW(nullptr),nullptr);
expect(owner!=nullptr,"Could not create fixture owner window");
Server server;
expect(!server.port() && server.token().empty(),"The listener is enabled by default");
server.start(owner);
const auto port=server.port();
const auto token=std::string(server.token());
expect(port && token.size()==64,"The session does not have a listener and token");
const auto ping=request("ping");
expect(post(port,{},ping).starts_with("HTTP/1.1 401"),"An unauthenticated request was accepted");
expect(post(port,std::string(64,'0'),ping).starts_with("HTTP/1.1 401"),"A wrong token was accepted");
expect(post(port,token,ping,"Origin: https://example.invalid\r\n").starts_with("HTTP/1.1 403"),
"A browser origin was accepted");
expect(post(port,token,ping,{},"other.invalid").starts_with("HTTP/1.1 403"),
"An unexpected Host was accepted");
expect(post(port,token,ping,"Content-Length: 1\r\n").starts_with("HTTP/1.1 400"),
"An ambiguous message length was accepted");
const auto initialized=content(post(port,token,request("initialize",{{"protocolVersion","2025-11-25"}})));
expect(initialized.at("result").at("protocolVersion")=="2025-11-25","Wrong protocol version");
const Json notification{{"jsonrpc","2.0"},{"method","notifications/initialized"}};
expect(post(port,token,notification).starts_with("HTTP/1.1 202"),"Initialization notification did not succeed");
const auto listed=content(post(port,token,request("tools/list")));
const auto &tools=listed.at("result").at("tools");
expect(tools.size()==3,"The listener advertised unexpected capabilities");
for(const auto &tool:tools) expect(tool.at("annotations").at("readOnlyHint")==true,"A tool is not read-only");
const auto unknown=content(post(port,token,request("tools/call",{{"name","write_file"}})));
expect(unknown.at("error").at("code")==-32602,"An unlisted tool was accepted");
auto pending=std::async(std::launch::async,[&]
{
return content(post(port,token,request("tools/call",
{{"name","get_panels"},{"arguments",{{"limit",3}}}})));
});
const auto deadline=std::chrono::steady_clock::now()+3s;
while(pending.wait_for(1ms)!=std::future_status::ready && std::chrono::steady_clock::now()<deadline)
{
MSG message{};
if(PeekMessageW(&message,owner,ks::files::filesMcpQueryMessage,ks::files::filesMcpQueryMessage,PM_REMOVE))
server.answer([](std::string_view name,const Json &arguments)
{
if(name!="get_panels" || arguments.at("limit")!=3) return Json{{"error","Wrong query"}};
return Json{{"active","left"}};
});
}
expect(pending.get().at("result").at("structuredContent").at("active")=="left",
"The server did not return the UI snapshot");
ks::lan::WinSocket idle;
idle.value=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
expect(idle.value!=INVALID_SOCKET && connectLoopback(idle.value,port),"Could not open idle connection");
const auto start=std::chrono::steady_clock::now();
server.stop();
expect(std::chrono::steady_clock::now()-start<1s && !server.port() && server.token().empty(),
"Stopping did not cancel the listener or detach the token");
server.start(owner);
expect(server.token()!=token,"A restarted listener reused a token");
expect(post(server.port(),token,ping).starts_with("HTTP/1.1 401"),"A revoked token still works");
expect(post(server.port(),std::string(server.token()),ping).starts_with("HTTP/1.1 200"),"The new token failed");
server.stop();
DestroyWindow(owner);
return 0;
}
catch(const std::exception &error)
{
std::cerr<<error.what()<<'\n';
return 1;
}
}
+170
View File
@@ -0,0 +1,170 @@
param(
[Parameter(Mandatory)][string]$Executable,
[string]$PreferenceKey = 'Software\KSwitcher\Files',
[string]$Screenshot,
[int]$FtpPort
)
$ErrorActionPreference = 'Stop'
. "$PSScriptRoot/files_commands_ui.ps1"
function Read-Caption([IntPtr]$Control) {
$label = [Text.StringBuilder]::new(1024)
[void][FilesCommandsUi]::Read($Control, 13, [IntPtr]$label.Capacity, $label)
$label.ToString()
}
function Test-Rows([IntPtr]$List, [string[]]$Expected) {
(@(Read-FilesList $List) -join [char]10) -ceq ($Expected -join [char]10)
}
function Send-PanelKey([IntPtr]$List, [int]$Key) {
[void][FilesCommandsUi]::Post($List, 0x100, [IntPtr]$Key, [IntPtr]::Zero)
}
function Save-FilesWindow([IntPtr]$Window, [string]$Destination) {
Add-Type -AssemblyName System.Drawing
$bounds = [FilesCommandsUi+Rect]::new()
if (![FilesCommandsUi]::GetClientRect($Window, [ref]$bounds)) { throw 'Could not locate the Files window.' }
$bitmap = [Drawing.Bitmap]::new($bounds.Right, $bounds.Bottom)
try {
$graphics = [Drawing.Graphics]::FromImage($bitmap)
try {
$dc = $graphics.GetHdc()
try {
if (![FilesCommandsUi]::PrintWindow($Window, $dc, 3)) { throw 'Could not render the Files window.' }
} finally { $graphics.ReleaseHdc($dc) }
} finally { $graphics.Dispose() }
$bitmap.Save($Destination, [Drawing.Imaging.ImageFormat]::Png)
} finally { $bitmap.Dispose() }
}
$exe = (Resolve-Path -LiteralPath $Executable).Path
$root = [IO.Directory]::CreateTempSubdirectory('ks-recent-folders-').FullName
$preferences = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($PreferenceKey)
$names = 'RecentFolders', 'FtpProfiles', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor',
'LeftFtpLocation', 'RightFtpLocation', 'WindowPlacement', 'LeftViewOrder', 'RightViewOrder'
$saved = @{}
foreach ($name in $names) {
if ($name -in $preferences.GetValueNames()) {
$saved[$name] = @($preferences.GetValue($name), $preferences.GetValueKind($name))
}
}
$process = $null
try {
foreach ($folder in 'left', 'right', 'destination', 'remove') {
[void][IO.Directory]::CreateDirectory((Join-Path $root $folder))
}
$leftFolder = Join-Path $root 'left'
$rightFolder = Join-Path $root 'right'
$destinationFolder = Join-Path $root 'destination'
$removeFolder = Join-Path $root 'remove'
[IO.File]::WriteAllText((Join-Path $leftFolder 'left-marker.txt'), 'left file')
[IO.File]::WriteAllText((Join-Path $rightFolder 'right-marker.txt'), 'right file')
[IO.File]::WriteAllText((Join-Path $destinationFolder 'opened-marker.txt'), 'existing folder')
$ftpId = [guid]::NewGuid().ToString('N')
if ($FtpPort) {
$ftpProfile = @(@{id=$ftpId; name='Local FTP'; host='127.0.0.1'; port=$FtpPort; user=''; secret=@()})
$preferences.SetValue('FtpProfiles', [Text.Encoding]::UTF8.GetBytes((ConvertTo-Json -InputObject $ftpProfile -Compress)), 'Binary')
}
$entries = @($destinationFolder, @{source='ftp'; id=$ftpId; label='Local FTP'; path='\documents'}, $removeFolder)
$ftpLabel = 'FTP · Local FTP · /documents'
$preferences.SetValue('RecentFolders', [Text.Encoding]::UTF8.GetBytes((ConvertTo-Json -InputObject $entries -Compress)), 'Binary')
foreach ($name in 'LeftViewOrder', 'RightViewOrder') { $preferences.SetValue($name, 0, 'DWord') }
$preferences.SetValue('LeftPath', $leftFolder, 'String')
$preferences.SetValue('RightPath', $rightFolder, 'String')
$preferences.SetValue('LeftCursor', (Join-Path $leftFolder 'left-marker.txt'), 'String')
foreach ($name in 'RightCursor', 'LeftFtpLocation', 'RightFtpLocation', 'WindowPlacement') {
$preferences.DeleteValue($name, $false)
}
$process = Start-Process -FilePath $exe -WindowStyle Hidden -PassThru
$window = Wait-For 'the Files window' {
$candidate = [IntPtr]::Zero
while (($candidate = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero, $candidate, 'KSwitcher.Files', [NullString]::Value)) -ne [IntPtr]::Zero) {
[uint32]$owner = 0
[void][FilesCommandsUi]::GetWindowThreadProcessId($candidate, [ref]$owner)
if ($owner -eq $process.Id) { return $candidate }
}
}
if ($Screenshot) { [void][FilesCommandsUi]::SetWindowPos($window, 0, 80, 60, 1380, 720, 20) }
[void][FilesCommandsUi]::ShowWindow($window, 4)
$picker = [FilesCommandsUi]::GetDlgItem($window, 121)
$left = [FilesCommandsUi]::GetDlgItem($window, 102)
$right = [FilesCommandsUi]::GetDlgItem($window, 103)
$leftPath = [FilesCommandsUi]::GetDlgItem($window, 142)
$rightPath = [FilesCommandsUi]::GetDlgItem($window, 143)
[void](Wait-For 'both initial folders' {
(Read-Caption $leftPath) -eq $leftFolder -and (Read-Caption $rightPath) -eq $rightFolder -and
(Read-FilesList $left) -contains 'left-marker.txt' -and (Read-FilesList $right) -contains 'right-marker.txt'
})
$leftBefore = @(Read-FilesList $left)
Select-FilesListRow $left 'left-marker.txt'
$rightBefore = @(Read-FilesList $right)
Open-FilesSource $window 0 'Recent folders'
[void](Wait-For 'recent folders in the left panel' {
(Read-Caption $leftPath) -ceq 'Recent folders' -and
(Test-Rows $left @($destinationFolder, $ftpLabel, $removeFolder))
})
if ([FilesCommandsUi]::IsWindowVisible($picker) -or !(Test-Rows $right $rightBefore)) {
throw 'Recent folders opened a popup or modified the right panel.'
}
if ($Screenshot) { Save-FilesWindow $window $Screenshot }
Select-FilesListRow $left $removeFolder
Send-PanelKey $left 46
[void](Wait-For 'the recent entry to be removed' { Test-Rows $left @($destinationFolder, $ftpLabel) })
if (!(Test-Path -LiteralPath $removeFolder -PathType Container)) { throw 'Delete removed the underlying folder.' }
Send-PanelKey $left 27
[void](Wait-For 'Escape to restore the left panel' {
$row = [FilesCommandsUi]::Send($left, 392, 0, 0).ToInt32()
(Read-Caption $leftPath) -eq $leftFolder -and (Test-Rows $left $leftBefore) -and
$row -ge 0 -and $leftBefore[$row] -eq 'left-marker.txt'
})
Open-FilesSource $window 1 'Recent folders'
[void](Wait-For 'updated recent folders in the right panel' {
(Read-Caption $rightPath) -ceq 'Recent folders' -and (Test-Rows $right @($destinationFolder, $ftpLabel))
})
if ([FilesCommandsUi]::IsWindowVisible($picker) -or !(Test-Rows $left $leftBefore)) {
throw 'Recent folders opened a popup or modified the left panel.'
}
Select-FilesListRow $right $destinationFolder
Send-PanelKey $right 13
[void](Wait-For 'the local folder to open on the right' {
(Read-Caption $rightPath) -eq $destinationFolder -and (Read-FilesList $right) -contains 'opened-marker.txt'
})
if ($FtpPort) {
Open-FilesSource $window 0 'Recent folders'
[void](Wait-For 'the FTP recent entry' { (Read-FilesList $left) -contains $ftpLabel })
Select-FilesListRow $left $ftpLabel
Send-PanelKey $left 13
[void](Wait-For 'the FTP directory to open on the left' {
(Read-Caption $leftPath) -ceq 'Local FTP · /documents' -and
(Read-FilesList $left) -contains 'ftp-marker.txt'
})
if ((Read-Caption $rightPath) -ne $destinationFolder) { throw 'Opening FTP modified the right panel.' }
}
[void][FilesCommandsUi]::Post($window, 16, 0, 0)
if (!$process.WaitForExit(5000)) { throw 'Files did not close.' }
$recorded = [Text.Encoding]::UTF8.GetString($preferences.GetValue('RecentFolders')) | ConvertFrom-Json
if ($recorded -contains $removeFolder) { throw 'The remove action was not persisted.' }
'Verified in-panel Recent folders, deletion, cursor restoration and folder navigation.'
} finally {
if ($process -and !$process.HasExited) { Stop-Process -Id $process.Id; $process.WaitForExit() }
foreach ($name in $names) {
if ($saved.ContainsKey($name)) { $preferences.SetValue($name, $saved[$name][0], $saved[$name][1]) }
else { $preferences.DeleteValue($name, $false) }
}
$preferences.Dispose()
$temp = (Resolve-Path -LiteralPath ([IO.Path]::GetTempPath())).Path.TrimEnd('\')
$resolved = (Resolve-Path -LiteralPath $root).Path
if ((Split-Path -Parent $resolved) -eq $temp -and (Split-Path -Leaf $resolved) -like 'ks-recent-folders-*') {
Remove-Item -LiteralPath $resolved -Recurse -Force
}
}
+23 -15
View File
@@ -61,19 +61,27 @@ try {
}
}
[void][FilesCommandsUi]::ShowWindow($main, 4)
$picker = [FilesCommandsUi]::GetDlgItem($main, 121)
[void][FilesCommandsUi]::Post($main, 0x104, [IntPtr]112, [IntPtr]::Zero)
[void](Wait-For 'Change drive' { [FilesCommandsUi]::IsWindowVisible($picker) })
$count = [FilesCommandsUi]::Send($picker, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32()
$selection = -1
for ($row = 0; $row -lt $count; ++$row) {
$label = [Text.StringBuilder]::new(256)
[void][FilesCommandsUi]::Read($picker, 393, [IntPtr]$row, $label)
if ($label.ToString() -ceq 'SMB') { $selection = $row; break }
function Same-Rows($First, $Second) {
($First -join [char]10) -ceq ($Second -join [char]10)
}
if ($selection -lt 0) { throw 'SMB was missing from Change drive.' }
[void][FilesCommandsUi]::Send($picker, 390, [IntPtr]$selection, [IntPtr]::Zero)
[void][FilesCommandsUi]::Post($picker, 0x100, [IntPtr]13, [IntPtr]::Zero)
$left = [FilesCommandsUi]::GetDlgItem($main, 102)
$right = [FilesCommandsUi]::GetDlgItem($main, 103)
[void](Wait-For 'both local panels' { @(Read-FilesList $left).Count -gt 0 -and @(Read-FilesList $right).Count -gt 0 })
$leftBefore = @(Read-FilesList $left)
$rightBefore = @(Read-FilesList $right)
Open-FilesSource $main 0 'SMB'
[void](Wait-For 'the SMB profile in the left file panel' {
(Read-FilesList $left) -like 'Render fixture*'
})
if (!(Same-Rows $rightBefore @(Read-FilesList $right))) { throw 'Opening SMB on the left changed the right panel.' }
[void][FilesCommandsUi]::Post($left, 0x100, [IntPtr]27, [IntPtr]::Zero)
[void](Wait-For 'Escape to return to the left folder' { Same-Rows $leftBefore @(Read-FilesList $left) })
Open-FilesSource $main 1 'SMB'
[void](Wait-For 'the SMB profile in the right file panel' {
(Read-FilesList $right) -like 'Render fixture*'
})
if (!(Same-Rows $leftBefore @(Read-FilesList $left))) { throw 'Opening SMB on the right changed the left panel.' }
function Find-DialogControl([int]$Id) {
$dialog = [IntPtr]::Zero
while (($dialog = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero, $dialog, '#32770', [NullString]::Value)) -ne [IntPtr]::Zero) {
@@ -85,8 +93,8 @@ try {
}
}
}
$browser, $signIn = Wait-For 'the SMB Sign in command' { Find-DialogControl 547 }
[void][FilesCommandsUi]::Post($browser, 0x111, [IntPtr]547, $signIn)
if (Find-DialogControl 541) { throw 'SMB displayed a separate browser over the file panels.' }
[void][FilesCommandsUi]::Post($main, 0x111, [IntPtr]547, [IntPtr]::Zero)
$dialog, $password = Wait-For 'the SMB password field' { Find-DialogControl 559 }
$empty = Render-Password $password
Set-Password $password 'WWWWWWWW'
@@ -100,7 +108,7 @@ try {
if ([FilesCommandsUi]::Send($remember, 0xf0, [IntPtr]::Zero, [IntPtr]::Zero) -ne [IntPtr]::Zero) {
throw 'Remember in Windows Credential Manager must be unchecked by default.'
}
'Verified password masking and the default credential-saving choice.'
'Verified SMB in both file panels, Escape navigation, password masking and the default credential-saving choice.'
} finally {
if ($process -and !$process.HasExited) { Stop-Process -Id $process.Id; $process.WaitForExit() }
foreach ($name in $names) {