Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25acb892d1 | ||
|
|
03a370f445 | ||
|
|
e8bef94474 | ||
|
|
0f400a58a1 | ||
|
|
e852fde4f4 | ||
|
|
e421c17f2a | ||
|
|
f4dcd0efd9 | ||
|
|
a5a5724513 | ||
|
|
040658f350 | ||
|
|
0ac6501b21 | ||
|
|
b6b7164742 | ||
|
|
8870d8c3d9 | ||
|
|
eb0f6ead72 | ||
|
|
d26eec3c98 |
No files matched your search
+13
-2
@@ -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)
|
||||
|
||||
+8
-1
@@ -635,7 +635,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 зберігає поля, змінені в поточній чернетці. Якщо два вікна одночасно
|
||||
@@ -741,6 +741,13 @@ 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.
|
||||
- Масштаб панелей, текстового Viewer, Editor, Markdown, термінала й порівняння зберігається окремо. У Commands є Panel appearance або Terminal appearance залежно від видимої області. Options у Viewer, Editor та Markdown і кнопка Appearance у порівнянні відкривають відповідну сторінку. Значення 100% використовує обраний базовий розмір шрифту.
|
||||
- Viewer і Editor підтримують колірну схему System (Windows). У Appearance → System themes можна призначити окремі палітри світлому й темному режимам Windows, включно із власними схемами. Rename scheme змінює назву власної схеми у списку, Viewer, Editor і призначеннях світлого та темного режимів.
|
||||
- Appearance → Dialog frame налаштовує зовнішній і внутрішній відступи від 0 до 24 px при 96 DPI. Row text padding додає від 0 до 4 ширин символу з кожного боку тексту в рядках Folder shortcuts. Inner padding задає відстань від рамки до краю списку. Ширина попапа враховує обидва текстові відступи, а довгі шляхи скорочуються в межах доступної ширини. Живий зразок показує чернетку. Apply зберігає значення, Cancel відкидає незастосовані зміни, Reset selected to defaults повертає 8 px, 14 px і 0 символів. Профілі без цих параметрів використовують ті самі значення.
|
||||
- У ресурсі чи виклику задавай назву кнопки й клавішу доступу. Спільна функція `paintDialogButton` центрує текст, підсвічує фокус і додає фігурні дужки для дії за замовчуванням та квадратні для решти кнопок.
|
||||
- Модальні діалоги редактора й переглядача використовують той самий шрифт, що й діалоги операцій Files. Розміри полів і кнопок враховують метрики цього шрифту.
|
||||
|
||||
@@ -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 @@
|
||||
0209951cbe8c5a202dba12a807895ce7146dc6640f96704f6a4aa9afaa4fd3af KSwitcher-win-x64.zip
|
||||
3d1d0d0a1c9ad671c949e0744987c94642125ccb2f479d3126509250c1fca541 KSwitcher-win-x64.zip
|
||||
+58
-43
@@ -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
@@ -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"
|
||||
|
||||
+101
-6
@@ -156,6 +156,95 @@ BEGIN
|
||||
PUSHBUTTON "Cancel", IDCANCEL, 162, 44, 50, 14
|
||||
END
|
||||
|
||||
615 DIALOGEX 0, 0, 371, 214
|
||||
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
|
||||
CAPTION "Keyboard shortcuts"
|
||||
FONT 9, "Segoe UI"
|
||||
BEGIN
|
||||
LTEXT "Active &scheme", -1, 9, 9, 160, 11
|
||||
COMBOBOX 610, 9, 22, 194, 120, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
PUSHBUTTON "&Copy as…", 611, 211, 22, 69, 15
|
||||
PUSHBUTTON "Rese&t scheme", 612, 288, 22, 74, 15
|
||||
LTEXT "&Command", -1, 9, 49, 166, 11
|
||||
LISTBOX 613, 9, 63, 166, 117, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
|
||||
LTEXT "", 614, 184, 49, 178, 11
|
||||
LISTBOX 615, 184, 63, 178, 80, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
|
||||
CONTROL "", 616, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 184, 152, 74, 15
|
||||
PUSHBUTTON "&Add", 617, 264, 152, 44, 15
|
||||
PUSHBUTTON "&Remove", 618, 314, 152, 48, 15
|
||||
PUSHBUTTON "Make &primary", 619, 184, 172, 75, 15
|
||||
DEFPUSHBUTTON "OK", IDOK, 250, 192, 52, 15
|
||||
PUSHBUTTON "Cancel", IDCANCEL, 310, 192, 52, 15
|
||||
END
|
||||
|
||||
616 DIALOGEX 0, 0, 233, 73
|
||||
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
|
||||
CAPTION "Copy keyboard scheme"
|
||||
FONT 9, "Segoe UI"
|
||||
BEGIN
|
||||
LTEXT "Scheme &name", -1, 9, 9, 214, 11
|
||||
EDITTEXT 620, 9, 23, 215, 15, ES_AUTOHSCROLL
|
||||
DEFPUSHBUTTON "Copy", IDOK, 112, 49, 52, 15
|
||||
PUSHBUTTON "Cancel", IDCANCEL, 172, 49, 52, 15
|
||||
END
|
||||
|
||||
617 DIALOGEX 0, 0, 240, 124
|
||||
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
|
||||
CAPTION "Files settings"
|
||||
FONT 9, "Segoe UI"
|
||||
BEGIN
|
||||
LTEXT "", 624, 9, 9, 222, 24
|
||||
AUTOCHECKBOX "Colors and file styles", 621, 9, 39, 222, 13
|
||||
AUTOCHECKBOX "Panel modes and layout", 622, 9, 55, 222, 13
|
||||
AUTOCHECKBOX "Keyboard schemes", 623, 9, 71, 222, 13
|
||||
DEFPUSHBUTTON "Load", IDOK, 118, 99, 52, 15
|
||||
PUSHBUTTON "Cancel", IDCANCEL, 179, 99, 52, 15
|
||||
END
|
||||
|
||||
618 DIALOGEX 0, 0, 468, 242
|
||||
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
|
||||
CAPTION "KSwitcher Files Help"
|
||||
FONT 9, "Segoe UI"
|
||||
BEGIN
|
||||
LTEXT "&Search help", -1, 9, 9, 112, 11
|
||||
EDITTEXT 670, 9, 23, 145, 15, ES_AUTOHSCROLL
|
||||
LISTBOX 671, 9, 45, 145, 160, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
|
||||
LTEXT "", 672, 165, 23, 294, 15
|
||||
EDITTEXT 673, 165, 45, 294, 160, ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | ES_WANTRETURN | WS_VSCROLL
|
||||
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"
|
||||
@@ -194,10 +283,7 @@ BEGIN
|
||||
COMBOBOX 305, 311, 51, 56, 125, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
LTEXT "&Row text padding (characters)", 306, 131, 77, 173, 12
|
||||
COMBOBOX 307, 311, 74, 56, 76, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
LTEXT "Previous command", 320, 131, 30, 120, 12
|
||||
CONTROL "", 321, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 260, 27, 110, 15
|
||||
LTEXT "Open command history", 322, 131, 53, 120, 12
|
||||
CONTROL "", 323, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 260, 50, 110, 15
|
||||
PUSHBUTTON "&Keyboard shortcuts…", 321, 131, 30, 127, 15
|
||||
AUTOCHECKBOX "Allow &paired PCs to run PowerShell commands here", 370, 131, 79, 250, 14
|
||||
AUTOCHECKBOX "Allow paired PCs to &hibernate this PC", 371, 131, 95, 250, 14
|
||||
AUTOCHECKBOX "Allow paired PCs to &update KSwitcher here", 372, 131, 111, 250, 14
|
||||
@@ -236,6 +322,7 @@ BEGIN
|
||||
PUSHBUTTON "Change color…", 366, 257, 181, 82, 15
|
||||
LTEXT "", 367, 345, 184, 45, 12
|
||||
PUSHBUTTON "&Save scheme…", 368, 131, 163, 118, 15
|
||||
PUSHBUTTON "Re&name scheme…", 534, 257, 163, 125, 15
|
||||
AUTOCHECKBOX "Restore local Viewer and Editor windows after restart", 524, 131, 210, 250, 13
|
||||
LTEXT "Maximum &width (px, 0 = full window)", 373, 131, 31, 184, 12
|
||||
EDITTEXT 374, 318, 28, 64, 14, ES_NUMBER | ES_AUTOHSCROLL
|
||||
@@ -250,8 +337,16 @@ BEGIN
|
||||
COMBOBOX 411, 250, 76, 132, 126, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
PUSHBUTTON "Change color…", 412, 250, 97, 82, 15
|
||||
LTEXT "", 413, 338, 100, 45, 12
|
||||
LTEXT "Compare files &shortcut", 414, 131, 130, 117, 12
|
||||
CONTROL "", 415, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 250, 127, 132, 15
|
||||
PUSHBUTTON "&Keyboard shortcuts…", 415, 131, 127, 127, 15
|
||||
LTEXT "&Scale", 528, 131, 235, 118, 12
|
||||
COMBOBOX 529, 257, 232, 125, 98, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
LTEXT "&Light mode palette", 530, 131, 32, 118, 12
|
||||
COMBOBOX 531, 250, 29, 132, 115, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
LTEXT "&Dark mode palette", 532, 131, 56, 118, 12
|
||||
COMBOBOX 533, 250, 53, 132, 115, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
LTEXT "Viewer and Editor use these palettes when Color scheme is set to System (Windows).", 535, 131, 80, 250, 28
|
||||
PUSHBUTTON "&Import JSON…", 525, 8, 289, 70, 14
|
||||
PUSHBUTTON "&Export JSON…", 526, 84, 289, 70, 14
|
||||
DEFPUSHBUTTON "OK", IDOK, 222, 289, 50, 14
|
||||
PUSHBUTTON "Cancel", IDCANCEL, 280, 289, 50, 14
|
||||
PUSHBUTTON "&Apply", 283, 338, 289, 50, 14
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cwchar>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
enum class AppearanceArea { panels, viewer, editor, markdown, terminal, comparison, count };
|
||||
inline constexpr size_t appearanceIndex(AppearanceArea area) { return static_cast<size_t>(area); }
|
||||
using AppearanceScales=std::array<unsigned,appearanceIndex(AppearanceArea::count)>;
|
||||
inline constexpr AppearanceScales defaultAppearanceScales{100,100,100,100,100,100};
|
||||
inline constexpr unsigned minAppearanceScale=75,maxAppearanceScale=200;
|
||||
|
||||
inline int scaledAppearanceSize(int size,unsigned percent)
|
||||
{
|
||||
return MulDiv(size,static_cast<int>(percent),100);
|
||||
}
|
||||
|
||||
inline bool windowsAppThemeChanged(UINT message,LPARAM parameter)
|
||||
{
|
||||
return message==WM_THEMECHANGED || (message==WM_SETTINGCHANGE && parameter &&
|
||||
std::wcscmp(reinterpret_cast<const wchar_t*>(parameter),L"ImmersiveColorSet")==0);
|
||||
}
|
||||
|
||||
inline bool windowsUsesDarkApps()
|
||||
{
|
||||
DWORD light=1,bytes=sizeof(light);
|
||||
return RegGetValueW(HKEY_CURRENT_USER,L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",
|
||||
L"AppsUseLightTheme",RRF_RT_REG_DWORD,nullptr,&light,&bytes)==ERROR_SUCCESS && !light;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,3 @@
|
||||
constexpr std::array<WORD,2> defaultHistoryKeys{MAKEWORD('E',HOTKEYF_CONTROL),MAKEWORD(VK_F8,HOTKEYF_ALT)};
|
||||
auto commandHistoryKeys=defaultHistoryKeys;
|
||||
constexpr size_t commandHistoryLimit=1000;
|
||||
|
||||
std::wstring commandHistoryLabel(const std::wstring &command)
|
||||
@@ -19,41 +17,6 @@ std::wstring commandHistoryLabel(const std::wstring &command)
|
||||
return fs::path(path).is_absolute()?path:command;
|
||||
}
|
||||
|
||||
bool validHistoryKeys(const std::array<WORD,2> &keys)
|
||||
{
|
||||
if(keys[0]==keys[1]) return false;
|
||||
return std::all_of(keys.begin(),keys.end(),[](WORD binding)
|
||||
{
|
||||
const auto key=LOBYTE(binding), modifiers=HIBYTE(binding);
|
||||
const bool letter=key>='A' && key<='Z';
|
||||
const bool function=key>=VK_F1 && key<=VK_F12;
|
||||
if(!letter && !function) return false;
|
||||
if(modifiers==HOTKEYF_CONTROL)
|
||||
return letter && key!='C' && key!='F' && key!='R' && key!='V' && key!='X' && key!='A' && key!='Z' && key!='Y';
|
||||
if(modifiers==HOTKEYF_ALT) return function && key!=VK_F1 && key!=VK_F2 && key!=VK_F4 && key!=VK_F10;
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
std::array<WORD,2> optionHistoryKeys(HWND dialog)
|
||||
{
|
||||
return {static_cast<WORD>(SendDlgItemMessageW(dialog,321,HKM_GETHOTKEY,0,0)),
|
||||
static_cast<WORD>(SendDlgItemMessageW(dialog,323,HKM_GETHOTKEY,0,0))};
|
||||
}
|
||||
|
||||
void setOptionHistoryKeys(HWND dialog,const std::array<WORD,2> &keys)
|
||||
{
|
||||
SendDlgItemMessageW(dialog,321,HKM_SETHOTKEY,keys[0],0);
|
||||
SendDlgItemMessageW(dialog,323,HKM_SETHOTKEY,keys[1],0);
|
||||
}
|
||||
|
||||
void loadCommandHistoryKeys()
|
||||
{
|
||||
const std::array<WORD,2> keys{static_cast<WORD>(preference(L"PreviousCommandKey",defaultHistoryKeys[0])),
|
||||
static_cast<WORD>(preference(L"CommandHistoryKey",defaultHistoryKeys[1]))};
|
||||
commandHistoryKeys=validHistoryKeys(keys)?keys:defaultHistoryKeys;
|
||||
}
|
||||
|
||||
void loadCommandHistory()
|
||||
{
|
||||
|
||||
@@ -107,23 +70,3 @@ void recallPreviousCommand()
|
||||
if(terminalHistoryIndex==terminalHistory.size()) terminalHistoryDraft=terminalInputText();
|
||||
recallCommand(terminalHistoryIndex-1);
|
||||
}
|
||||
|
||||
void showCommandHistory(HWND owner);
|
||||
|
||||
bool handleCommandHistoryKey(HWND window,const MSG &message)
|
||||
{
|
||||
if(message.message!=WM_KEYDOWN && message.message!=WM_SYSKEYDOWN) return false;
|
||||
if((GetKeyState(VK_LWIN)&0x8000) || (GetKeyState(VK_RWIN)&0x8000)) return false;
|
||||
const BYTE modifiers=((GetKeyState(VK_CONTROL)&0x8000)?HOTKEYF_CONTROL:0) |
|
||||
((GetKeyState(VK_MENU)&0x8000)?HOTKEYF_ALT:0) | ((GetKeyState(VK_SHIFT)&0x8000)?HOTKEYF_SHIFT:0);
|
||||
const auto binding=MAKEWORD(message.wParam,modifiers);
|
||||
if(binding==commandHistoryKeys[0] && (message.hwnd==terminalInput ||
|
||||
message.hwnd==panels[0].list || message.hwnd==panels[1].list))
|
||||
{
|
||||
recallPreviousCommand();
|
||||
return true;
|
||||
}
|
||||
if(binding!=commandHistoryKeys[1]) return false;
|
||||
if(!(message.lParam&(1LL<<30))) showCommandHistory(window);
|
||||
return true;
|
||||
}
|
||||
+8
-28
@@ -4,31 +4,8 @@ enum ComparisonColor { CompareBackground, CompareText, CompareInsert, CompareDel
|
||||
constexpr const wchar_t *comparisonColorNames[]{L"Background",L"Text",L"Insertion",L"Deletion",L"Replacement",
|
||||
L"Changed fragment",L"Alignment padding",L"Divider",L"Text on changed lines"};
|
||||
constexpr wchar_t comparisonAppearanceKey[]=L"ComparisonAppearance";
|
||||
constexpr wchar_t comparisonShortcutKey[]=L"ComparisonShortcut";
|
||||
constexpr WORD defaultComparisonShortcut=MAKEWORD(VK_F11,HOTKEYF_SHIFT);
|
||||
WORD comparisonShortcut=defaultComparisonShortcut;
|
||||
constexpr int comparisonSplitScale=10000;
|
||||
|
||||
bool validComparisonShortcut(WORD shortcut)
|
||||
{
|
||||
const auto key=LOBYTE(shortcut),modifiers=HIBYTE(shortcut);
|
||||
return key>=VK_F1 && key<=VK_F12 &&
|
||||
(modifiers==(HOTKEYF_CONTROL|HOTKEYF_SHIFT) ||
|
||||
(modifiers==HOTKEYF_SHIFT && key!=VK_F4 && key!=VK_F8));
|
||||
}
|
||||
|
||||
void loadComparisonShortcut()
|
||||
{
|
||||
const auto shortcut=static_cast<WORD>(preference(comparisonShortcutKey,defaultComparisonShortcut));
|
||||
comparisonShortcut=validComparisonShortcut(shortcut)?shortcut:defaultComparisonShortcut;
|
||||
}
|
||||
|
||||
std::wstring comparisonShortcutLabel()
|
||||
{
|
||||
return std::wstring(HIBYTE(comparisonShortcut)&HOTKEYF_CONTROL?L"Ctrl+Shift+F":L"Shift+F")+
|
||||
std::to_wstring(LOBYTE(comparisonShortcut)-VK_F1+1);
|
||||
}
|
||||
|
||||
struct ComparisonAppearance
|
||||
{
|
||||
LOGFONTW font=defaultFilesFont();
|
||||
@@ -157,8 +134,9 @@ void applyComparisonFont(HWND dialog,FileComparison &comparison)
|
||||
{
|
||||
auto font=comparison.appearance.font;
|
||||
const auto dpi=GetDpiForWindow(dialog);
|
||||
const auto points=std::clamp(comparison.appearance.points+comparison.zoom,80,240);
|
||||
comparison.zoom=points-comparison.appearance.points;
|
||||
const auto base=areaFontPoints(comparison.appearance.points,AppearanceArea::comparison);
|
||||
const auto points=std::clamp(base+comparison.zoom,60,480);
|
||||
comparison.zoom=points-base;
|
||||
font.lfHeight=-MulDiv(points,dpi,720);
|
||||
font.lfWidth=0;
|
||||
if(const auto next=CreateFontIndirectW(&font))
|
||||
@@ -201,8 +179,8 @@ bool zoomComparison(HWND dialog,FileComparison &comparison,WPARAM wheel)
|
||||
comparison.wheelRemainder+=GET_WHEEL_DELTA_WPARAM(wheel);
|
||||
const auto steps=comparison.wheelRemainder/WHEEL_DELTA;
|
||||
comparison.wheelRemainder%=WHEEL_DELTA;
|
||||
const auto base=comparison.appearance.points;
|
||||
const auto zoom=std::clamp(base+comparison.zoom+10*steps,80,240)-base;
|
||||
const auto base=areaFontPoints(comparison.appearance.points,AppearanceArea::comparison);
|
||||
const auto zoom=std::clamp(base+comparison.zoom+10*steps,60,480)-base;
|
||||
if(zoom!=comparison.zoom)
|
||||
{
|
||||
comparison.zoom=zoom;
|
||||
@@ -1023,7 +1001,8 @@ void initializeComparisonToolbar(HWND toolbar)
|
||||
{icon(HIST_BACK),404,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Previous")},
|
||||
{icon(HIST_FORWARD),405,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Next")},
|
||||
{separator,0,0,BTNS_SEP,{},0,0},
|
||||
{I_IMAGENONE,406,TBSTATE_ENABLED,text|BTNS_CHECK,{},0,reinterpret_cast<INT_PTR>(L"Show whitespace changes")}
|
||||
{I_IMAGENONE,406,TBSTATE_ENABLED,text|BTNS_CHECK,{},0,reinterpret_cast<INT_PTR>(L"Show whitespace changes")},
|
||||
{I_IMAGENONE,527,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Appearance…")}
|
||||
};
|
||||
SendMessageW(toolbar,TB_ADDBUTTONSW,std::size(buttons),reinterpret_cast<LPARAM>(buttons));
|
||||
}
|
||||
@@ -1130,6 +1109,7 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
const auto id=LOWORD(wp);
|
||||
if(comparison->working) return TRUE;
|
||||
if(id==IDCANCEL) {closeComparison(dialog,*comparison);return TRUE;}
|
||||
if(id==527) {editFilesAppearance(dialog,AppearanceArea::comparison);return TRUE;}
|
||||
if(id==applyLeft || id==applyRight)
|
||||
{
|
||||
const auto side=id-applyLeft;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
bool handleFilesHelpMessage(const MSG &message);
|
||||
|
||||
HWND activeFilesDialog{};
|
||||
HHOOK filesDialogMouseHook{};
|
||||
|
||||
@@ -53,9 +55,10 @@ class FilesModalDialog
|
||||
{
|
||||
public:
|
||||
FilesModalDialog(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument,
|
||||
bool watchOutsideClicks=true)
|
||||
bool watchOutsideClicks=true,bool fitToOwner=true)
|
||||
: owner_(owner),focus_(GetFocus()),procedure_(procedure),argument_(argument),
|
||||
watchOutsideClicks_(watchOutsideClicks)
|
||||
resource_(IS_INTRESOURCE(resource)?static_cast<unsigned>(reinterpret_cast<ULONG_PTR>(resource)):0),
|
||||
watchOutsideClicks_(watchOutsideClicks),fitToOwner_(fitToOwner)
|
||||
{
|
||||
window_=CreateDialogParamW(instance,resource,owner,dispatchDialog,reinterpret_cast<LPARAM>(this));
|
||||
}
|
||||
@@ -66,6 +69,12 @@ public:
|
||||
|
||||
HWND window() const { return window_; }
|
||||
|
||||
static unsigned resourceFor(HWND window)
|
||||
{
|
||||
const auto *state=reinterpret_cast<const FilesModalDialog*>(GetPropW(window,stateProperty_));
|
||||
return state?state->resource_:0;
|
||||
}
|
||||
|
||||
static HWND activeFor(HWND owner)
|
||||
{
|
||||
const auto root=GetAncestor(owner,GA_ROOTOWNER);
|
||||
@@ -111,7 +120,7 @@ public:
|
||||
activeFilesDialog=window_;
|
||||
entered_=true;
|
||||
refreshMouseHook();
|
||||
if(GetWindowRect(owner_,&ownerBounds_))
|
||||
if(fitToOwner_ && GetWindowRect(owner_,&ownerBounds_))
|
||||
{
|
||||
if(!layout_) captureLayout();
|
||||
SetWindowSubclass(owner_,trackOwner,reinterpret_cast<UINT_PTR>(this),reinterpret_cast<DWORD_PTR>(this));
|
||||
@@ -146,6 +155,7 @@ public:
|
||||
{
|
||||
if(message.hwnd==dialog || IsChild(dialog,message.hwnd))
|
||||
{
|
||||
if(handleFilesHelpMessage(message)) return true;
|
||||
if(message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE)
|
||||
{
|
||||
SendMessageW(dialog,WM_COMMAND,IDCANCEL,0);
|
||||
@@ -209,7 +219,8 @@ private:
|
||||
DLGPROC procedure_;
|
||||
LPARAM argument_;
|
||||
INT_PTR result_=IDCANCEL;
|
||||
bool entered_{},finished_{},watchOutsideClicks_;
|
||||
unsigned resource_{};
|
||||
bool entered_{},finished_{},watchOutsideClicks_,fitToOwner_;
|
||||
|
||||
static void refreshMouseHook()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
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, log, mcp, count
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
using ks::files::FilesHelpTopic;
|
||||
|
||||
constexpr struct
|
||||
{
|
||||
const wchar_t *title,*keywords,*body;
|
||||
} filesHelpTopics[]{
|
||||
{L"File panels",L"commander left right selection tabs keyboard refresh",
|
||||
L"Use Tab to switch panes. Enter opens the selected folder or file. Insert marks an item and advances to the next row. The selection summary counts marked items.\r\n\r\n"
|
||||
L"The command bar shows the primary keys for common actions. The Left and Right menus switch modes, choose drives, sort items, and filter a pane."},
|
||||
{L"Menus and shortcuts",L"f9 access keys commands actions configuration",
|
||||
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"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"
|
||||
L"Enter visits a result's folder. Esc stops an active search or returns from the results. Use Quick View for a preview of a local result."},
|
||||
{L"Copy, move and rename",L"transfer destination mask overwrite permissions timestamps clipboard queue",
|
||||
L"Copy and Move use the selection in the active pane. The destination starts with the other pane. Check the destination and the conflict policy before starting the operation.\r\n\r\n"
|
||||
L"Copy/Move options can limit the selection by mask, target several folders, and preserve timestamps or supported permissions. The progress dialog shows the active file and an estimate when enough data has transferred."},
|
||||
{L"Delete and Recycle Bin",L"permanent remove recovery confirmation shift delete",
|
||||
L"Delete respects the selected items and shows a confirmation. Local files are sent to the Recycle Bin when supported. Check the notice for remote locations or permanent deletion.\r\n\r\n"
|
||||
L"Shift+Delete requests permanent deletion. Cancel the confirmation to keep the selection without deleting it."},
|
||||
{L"Archives",L"zip 7z pack extract compression update",
|
||||
L"Open a ZIP or 7z archive from a local pane to browse its entries. Copy entries out to extract them. Back out through the parent entry or Esc.\r\n\r\n"
|
||||
L"Use Pack files to create or update a ZIP or 7z archive. Review the destination, compression and conflict choices before saving."},
|
||||
{L"Space Analyzer",L"storage folder size allocation disk tree treemap sunburst",
|
||||
L"Open Space Analyzer from Commands for a local folder. The tree and charts show which folders consume space. Select an item to inspect its contribution and choose the display you need.\r\n\r\n"
|
||||
L"Logical size describes file data. Allocated size describes disk allocation where it can be measured."},
|
||||
{L"Properties and locking processes",L"context menu windows owner attributes filesystem locks handle",
|
||||
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"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"
|
||||
L"With a command name at the caret, F1 can open its Windows command reference. With an empty command line F1 opens the Files guide."},
|
||||
{L"Text Viewer and Quick View",L"preview read file html hex bookmark go to search",
|
||||
L"View opens a separate window. Quick View previews the local selection alongside its pane. View as hex displays binary data. A local Viewer refreshes when its file is changed externally.\r\n\r\n"
|
||||
L"Use the Viewer menus for Find, page navigation and bookmarks. Options opens the Viewer appearance page."},
|
||||
{L"Text Editor",L"edit save encoding f2 f4 f6 external changes buffers",
|
||||
L"Edit opens a text file for changes. The Editor menu provides Save, Find, undo and encoding controls. Switching to Viewer keeps a pending Editor buffer for the open document.\r\n\r\n"
|
||||
L"When the disk version changes, choose Reload or Keep buffer. Saving checks the disk version again and reports a conflict if the file has changed."},
|
||||
{L"Markdown preview",L"markdown rendered source local links images search",
|
||||
L"Open a Markdown file in Viewer to read the rendered document. Use its navigation controls for local links and its search form to find rendered text. Switch back to source for editing.\r\n\r\n"
|
||||
L"Options opens the Markdown page for width, font and scale. Markdown's scale is separate from the text Viewer and Editor."},
|
||||
{L"Image Viewer and Editor",L"png jpeg image zoom rotate crop undo save copy",
|
||||
L"View opens supported images with fit, zoom and navigation controls. Local PNG and JPEG files can be opened with Edit to rotate or crop them.\r\n\r\n"
|
||||
L"Use Undo to reverse edits and Save Copy to create a new file. Replacing the original requires confirmation and checks for external changes."},
|
||||
{L"File comparison",L"diff unified changes left right hunk apply undo whitespace",
|
||||
L"Select the two files and choose Compare files. Previous and Next jump between change blocks. Unified changes the view, and Fold unchanged collapses matching context.\r\n\r\n"
|
||||
L"Apply to left or right changes that side's draft. Use Undo or save the selected side when ready. Appearance opens the comparison font, colors and scale."},
|
||||
{L"Git Changes",L"staged unstaged repository status commit branch diff",
|
||||
L"Open Git Changes in a Git working tree to inspect changes, branches and history. Select an entry to review its diff.\r\n\r\n"
|
||||
L"Stage the changes you want to include. Commit staged changes shows the items currently in the index before writing the commit."},
|
||||
{L"Environment Variables",L"user system process path edit windows variables",
|
||||
L"Environment Variables lists user, system and process scopes. Choose a scope, then review the selected name and value before editing.\r\n\r\n"
|
||||
L"Changes to the system scope require the appropriate Windows permission. Existing applications may need to reopen before using updated values."},
|
||||
{L"Files Options",L"preferences settings search apply reset cancel layout font",
|
||||
L"Search settings by name or choose a section in the tree. Apply saves the draft and refreshes affected windows. Cancel discards the pending changes.\r\n\r\n"
|
||||
L"Reset selected to defaults applies to the displayed section. Import JSON and Export JSON transfer supported settings groups between profiles."},
|
||||
{L"Keyboard schemes",L"keys shortcuts multiple primary named duplicate context conflict",
|
||||
L"Use Commands → Keyboard shortcuts to switch or copy a named scheme. Select a command, enter a key and choose Add. Make primary controls which binding appears in the command bar.\r\n\r\n"
|
||||
L"Keys already assigned in an overlapping context cannot be added to another command in that context. F1 opens this guide."},
|
||||
{L"Appearance and scale",L"theme light dark windows appearance font palette size",
|
||||
L"Panels, Viewer, Editor, Markdown, terminal and comparison each have a saved scale. Use the visible area's Options or Appearance command to open its settings.\r\n\r\n"
|
||||
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"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));
|
||||
|
||||
constexpr int helpSearch=670,helpTopics=671,helpTitle=672,helpBody=673;
|
||||
|
||||
void displayFilesHelpTopic(HWND dialog,int topic)
|
||||
{
|
||||
if(topic<0)
|
||||
{
|
||||
SetDlgItemTextW(dialog,helpTitle,L"No matching help topics");
|
||||
SetDlgItemTextW(dialog,helpBody,L"");
|
||||
return;
|
||||
}
|
||||
const auto &entry=filesHelpTopics[topic];
|
||||
SetDlgItemTextW(dialog,helpTitle,entry.title);
|
||||
SetDlgItemTextW(dialog,helpBody,entry.body);
|
||||
SendDlgItemMessageW(dialog,helpBody,EM_SETSEL,0,0);
|
||||
SendDlgItemMessageW(dialog,helpBody,EM_SCROLLCARET,0,0);
|
||||
}
|
||||
|
||||
void filterFilesHelpTopics(HWND dialog,int previous)
|
||||
{
|
||||
wchar_t buffer[129]{};
|
||||
GetDlgItemTextW(dialog,helpSearch,buffer,std::size(buffer));
|
||||
std::wistringstream query(ks::lower(buffer));
|
||||
std::vector<std::wstring> tokens;
|
||||
for(std::wstring term;query>>term;) tokens.push_back(std::move(term));
|
||||
const auto list=GetDlgItem(dialog,helpTopics);
|
||||
SendMessageW(list,LB_RESETCONTENT,0,0);
|
||||
int displayed=-1;
|
||||
LRESULT selected=LB_ERR;
|
||||
for(size_t i=0;i<std::size(filesHelpTopics);++i)
|
||||
{
|
||||
const auto &topic=filesHelpTopics[i];
|
||||
const auto text=ks::lower(std::wstring(topic.title)+L" "+topic.keywords+L" "+topic.body);
|
||||
if(!std::ranges::all_of(tokens,[&](const auto &word){return text.find(word)!=text.npos;})) continue;
|
||||
const auto row=SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(topic.title));
|
||||
if(row<0) continue;
|
||||
SendMessageW(list,LB_SETITEMDATA,row,i);
|
||||
if(selected==LB_ERR || static_cast<int>(i)==previous)
|
||||
{
|
||||
selected=row;
|
||||
displayed=static_cast<int>(i);
|
||||
}
|
||||
}
|
||||
if(selected!=LB_ERR) SendMessageW(list,LB_SETCURSEL,selected,0);
|
||||
displayFilesHelpTopic(dialog,displayed);
|
||||
}
|
||||
|
||||
int selectedFilesHelpTopic(HWND dialog)
|
||||
{
|
||||
const auto row=SendDlgItemMessageW(dialog,helpTopics,LB_GETCURSEL,0,0);
|
||||
return row==LB_ERR?-1:static_cast<int>(SendDlgItemMessageW(dialog,helpTopics,LB_GETITEMDATA,row,0));
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK filesHelpDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
SendDlgItemMessageW(dialog,helpSearch,EM_SETLIMITTEXT,128,0);
|
||||
filterFilesHelpTopics(dialog,static_cast<int>(lp));
|
||||
SetFocus(GetDlgItem(dialog,helpSearch));
|
||||
return FALSE;
|
||||
}
|
||||
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;
|
||||
if(LOWORD(wp)==helpSearch && HIWORD(wp)==EN_CHANGE)
|
||||
filterFilesHelpTopics(dialog,selectedFilesHelpTopic(dialog));
|
||||
if(LOWORD(wp)==helpTopics && HIWORD(wp)==LBN_SELCHANGE)
|
||||
displayFilesHelpTopic(dialog,selectedFilesHelpTopic(dialog));
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
void showFilesHelp(HWND owner,FilesHelpTopic topic)
|
||||
{
|
||||
if(!owner || !IsWindow(owner) || FilesModalDialog::resourceFor(owner)==618) return;
|
||||
FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(618),owner,filesHelpDialog,
|
||||
static_cast<LPARAM>(topic),false,false);
|
||||
dialog.runModal();
|
||||
}
|
||||
|
||||
FilesHelpTopic filesMenuHelpTopic()
|
||||
{
|
||||
if(folderPicker) return FilesHelpTopic::navigation;
|
||||
if(!commandPicker) return IsWindowVisible(picker)?FilesHelpTopic::connections:FilesHelpTopic::menus;
|
||||
const auto row=SendMessageW(picker,LB_GETCURSEL,0,0);
|
||||
if(!selectablePickerRow(row)) return FilesHelpTopic::menus;
|
||||
const int action=commandActions[row];
|
||||
if(menuIndex==0 || menuIndex==4) return action==4?FilesHelpTopic::navigation:FilesHelpTopic::panels;
|
||||
if(menuIndex==1)
|
||||
{
|
||||
if(action==4) return FilesHelpTopic::archive;
|
||||
if(action==5 || action==6) return FilesHelpTopic::properties;
|
||||
return action<=2?FilesHelpTopic::transfer:FilesHelpTopic::menus;
|
||||
}
|
||||
if(menuIndex!=2) return FilesHelpTopic::menus;
|
||||
switch(action)
|
||||
{
|
||||
case 1: case 4: case 10: case 13: case 14: return FilesHelpTopic::viewer;
|
||||
case 2: case 5: return FilesHelpTopic::editor;
|
||||
case 3: case 11: return FilesHelpTopic::navigation;
|
||||
case 6: case 7: return FilesHelpTopic::connections;
|
||||
case 8: return FilesHelpTopic::comparison;
|
||||
case 9: return FilesHelpTopic::find;
|
||||
case 12: return FilesHelpTopic::space;
|
||||
case 15: return FilesHelpTopic::properties;
|
||||
case 16: return FilesHelpTopic::git;
|
||||
case 17: return FilesHelpTopic::environment;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<FilesHelpTopic> filesHelpForWindow(HWND root,HWND target)
|
||||
{
|
||||
const auto resource=FilesModalDialog::resourceFor(root);
|
||||
switch(resource)
|
||||
{
|
||||
case 618: return {};
|
||||
case 101:
|
||||
{
|
||||
const auto control=GetDlgCtrlID(target);
|
||||
if(control==optionsImport || control==optionsExport) return FilesHelpTopic::portability;
|
||||
if(control==321 || control==comparisonKeySchemesButton) return FilesHelpTopic::keys;
|
||||
if(const auto *option=reinterpret_cast<const OptionsDraft*>(GetWindowLongPtrW(root,DWLP_USER)))
|
||||
{
|
||||
if(option->page==Appearance || control==areaScaleControl) return FilesHelpTopic::appearance;
|
||||
if(option->page==TextViewer && option->section==markdownSection) return FilesHelpTopic::markdown;
|
||||
if(option->page==PanelModes) return FilesHelpTopic::panels;
|
||||
if(option->page==CommandLine) return FilesHelpTopic::terminal;
|
||||
if(option->page==CompareFiles) return FilesHelpTopic::comparison;
|
||||
}
|
||||
return FilesHelpTopic::options;
|
||||
}
|
||||
case 102: case 103: case 104: case 105: case 108: case 113: case 129: return FilesHelpTopic::transfer;
|
||||
case 106: case 107: return FilesHelpTopic::deleteFiles;
|
||||
case 109: case 110: case 117: return FilesHelpTopic::navigation;
|
||||
case 111: return FilesHelpTopic::terminal;
|
||||
case 112: case 121: case 122: case 123: case 124: return FilesHelpTopic::connections;
|
||||
case 114: case 115: return FilesHelpTopic::comparison;
|
||||
case 116: return FilesHelpTopic::find;
|
||||
case 118: return FilesHelpTopic::space;
|
||||
case 119: return FilesHelpTopic::panels;
|
||||
case 120: return FilesHelpTopic::archive;
|
||||
case 125: case 609: return FilesHelpTopic::properties;
|
||||
case 126: return FilesHelpTopic::git;
|
||||
case 127: case 128: return FilesHelpTopic::environment;
|
||||
case 130: return FilesHelpTopic::images;
|
||||
case 602: case 613: case 614: return FilesHelpTopic::viewer;
|
||||
case 603: case 611: case 612: return FilesHelpTopic::editor;
|
||||
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);
|
||||
break;
|
||||
}
|
||||
if(comparisonWindows.contains(root)) return FilesHelpTopic::comparison;
|
||||
if(const auto area=ks::files::textWindowAppearanceArea(root))
|
||||
return *area==AppearanceArea::markdown?FilesHelpTopic::markdown:
|
||||
*area==AppearanceArea::editor?FilesHelpTopic::editor:FilesHelpTopic::viewer;
|
||||
wchar_t type[64]{};
|
||||
GetClassNameW(root,type,std::size(type));
|
||||
if(std::wstring_view(type)==L"KSwitcherFilesImageViewer") return FilesHelpTopic::images;
|
||||
if(root!=GetParent(terminalInput)) return resource?std::optional(FilesHelpTopic::options):std::nullopt;
|
||||
if(gitChangesView && (target==gitChangesView->host || IsChild(gitChangesView->host,target))) return FilesHelpTopic::git;
|
||||
if(quickImageWindow && (target==quickImageWindow || IsChild(quickImageWindow,target))) return FilesHelpTopic::images;
|
||||
if(quickViewWindow && (target==quickViewWindow || IsChild(quickViewWindow,target))) return FilesHelpTopic::viewer;
|
||||
if(IsWindowVisible(menuBar) || IsWindowVisible(picker)) return filesMenuHelpTopic();
|
||||
if(terminalVisible || target==terminalOutput || IsChild(terminalOutput,target)) return FilesHelpTopic::terminal;
|
||||
if(target==panels[0].path || target==panels[1].path) return FilesHelpTopic::navigation;
|
||||
return panels[active].findOrigin?FilesHelpTopic::find:FilesHelpTopic::panels;
|
||||
}
|
||||
|
||||
bool handleFilesHelpMessage(const MSG &message)
|
||||
{
|
||||
const bool posted=message.message==ks::files::filesHelpRequest;
|
||||
if(!message.hwnd || (!posted && (message.message!=WM_KEYDOWN || message.wParam!=VK_F1 ||
|
||||
((GetKeyState(VK_CONTROL)|GetKeyState(VK_MENU)|GetKeyState(VK_SHIFT)|
|
||||
GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000)))) return false;
|
||||
const auto root=GetAncestor(message.hwnd,GA_ROOT);
|
||||
auto target=message.hwnd;
|
||||
if(root==target)
|
||||
if(const auto focus=GetFocus();focus && IsChild(root,focus)) target=focus;
|
||||
if(FilesModalDialog::resourceFor(root)==618) return true;
|
||||
const auto topic=posted && message.hwnd==GetParent(terminalInput)?
|
||||
std::optional(FilesHelpTopic::terminal):filesHelpForWindow(root,target);
|
||||
if(!topic) return false;
|
||||
if(!posted)
|
||||
{
|
||||
if(message.lParam&(1LL<<30)) return true;
|
||||
if(target==terminalInput && commandLineAvailable(root) && handleCompletionKey(VK_F1,message.lParam))
|
||||
return true;
|
||||
}
|
||||
showFilesHelp(root,*topic);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
enum KeyContext : unsigned { panelKeyContext=1, terminalKeyContext=2 };
|
||||
enum class FilesKey
|
||||
{
|
||||
Refresh, View, Edit, Copy, Move, Mkdir, Delete, Exit, Compare, Previous, History,
|
||||
Pack, Find, ExternalView, ExternalEdit, QuickView, FullPath, HexView, Swap, Properties, Next, Count
|
||||
};
|
||||
constexpr size_t keyIndex(FilesKey command) { return static_cast<size_t>(command); }
|
||||
constexpr unsigned bothKeyContexts=panelKeyContext|terminalKeyContext;
|
||||
constexpr WORD chord(BYTE key,BYTE modifiers=0) { return MAKEWORD(key,modifiers); }
|
||||
constexpr BYTE keyCtrl=HOTKEYF_CONTROL,keyShift=HOTKEYF_SHIFT,keyAlt=HOTKEYF_ALT;
|
||||
constexpr struct
|
||||
{
|
||||
const char *id;
|
||||
const wchar_t *label;
|
||||
unsigned contexts;
|
||||
std::array<WORD,2> defaults;
|
||||
} filesKeyCommands[]{
|
||||
{"refresh",L"Refresh panel",bothKeyContexts,{chord('R',keyCtrl),chord(VK_F2)}},
|
||||
{"view",L"View",panelKeyContext,{chord(VK_F3)}},
|
||||
{"edit",L"Edit",panelKeyContext,{chord(VK_F4)}},
|
||||
{"copy",L"Copy",panelKeyContext,{chord(VK_F5)}},
|
||||
{"move",L"Move",panelKeyContext,{chord(VK_F6)}},
|
||||
{"mkdir",L"Make folder",panelKeyContext,{chord(VK_F7)}},
|
||||
{"delete",L"Delete to Recycle Bin",panelKeyContext,{chord(VK_F8)}},
|
||||
{"exit",L"Exit",bothKeyContexts,{chord(VK_F10)}},
|
||||
{"compare",L"Compare files",panelKeyContext,{chord(VK_F11,keyShift)}},
|
||||
{"previous",L"Previous command",bothKeyContexts,{chord('E',keyCtrl)}},
|
||||
{"history",L"Command history",bothKeyContexts,{chord(VK_F8,keyAlt)}},
|
||||
{"pack",L"Pack files",panelKeyContext,{chord(VK_F5,keyAlt)}},
|
||||
{"find",L"Find files",panelKeyContext,{chord(VK_F7,keyAlt)}},
|
||||
{"externalView",L"View externally",panelKeyContext,{chord(VK_F3,keyAlt)}},
|
||||
{"externalEdit",L"Edit externally",panelKeyContext,{chord(VK_F4,keyAlt)}},
|
||||
{"quickView",L"Quick View",panelKeyContext,{chord('Q',keyCtrl)}},
|
||||
{"fullPath",L"Copy full path",panelKeyContext,{chord('C',keyCtrl|keyShift)}},
|
||||
{"hexView",L"View as hex",panelKeyContext,{chord(VK_F3,keyShift)}},
|
||||
{"swap",L"Swap panels",panelKeyContext,{chord('U',keyCtrl)}},
|
||||
{"properties",L"Properties",panelKeyContext,{chord('A',keyCtrl)}},
|
||||
{"next",L"Next command",terminalKeyContext,{chord(VK_DOWN)}},
|
||||
};
|
||||
static_assert(std::size(filesKeyCommands)==keyIndex(FilesKey::Count));
|
||||
constexpr size_t filesKeySchemeLimit=24,filesKeysPerCommand=8;
|
||||
constexpr wchar_t filesKeySchemePreference[]=L"KeySchemesV1";
|
||||
|
||||
struct FilesKeyScheme
|
||||
{
|
||||
std::wstring name;
|
||||
std::array<std::vector<WORD>,keyIndex(FilesKey::Count)> keys;
|
||||
bool operator==(const FilesKeyScheme &) const=default;
|
||||
};
|
||||
|
||||
struct FilesKeySettings
|
||||
{
|
||||
std::vector<FilesKeyScheme> schemes;
|
||||
size_t active{};
|
||||
bool operator==(const FilesKeySettings &) const=default;
|
||||
};
|
||||
|
||||
std::wstring filesKeyLabel(WORD binding)
|
||||
{
|
||||
if(!binding) return {};
|
||||
std::wstring label;
|
||||
if(HIBYTE(binding)&keyCtrl) label+=L"Ctrl+";
|
||||
if(HIBYTE(binding)&keyAlt) label+=L"Alt+";
|
||||
if(HIBYTE(binding)&keyShift) label+=L"Shift+";
|
||||
const auto key=LOBYTE(binding);
|
||||
if(key>=VK_F1 && key<=VK_F24) label+=L"F"+std::to_wstring(key-VK_F1+1);
|
||||
else if(key==VK_DOWN) label+=L"Down";
|
||||
else label+=static_cast<wchar_t>(key);
|
||||
return label;
|
||||
}
|
||||
|
||||
FilesKeyScheme defaultFilesKeyScheme(std::wstring name=L"Default")
|
||||
{
|
||||
FilesKeyScheme scheme{std::move(name),{}};
|
||||
for(size_t command=0;command<scheme.keys.size();++command)
|
||||
for(const auto binding:filesKeyCommands[command].defaults)
|
||||
if(binding) scheme.keys[command].push_back(binding);
|
||||
return scheme;
|
||||
}
|
||||
|
||||
FilesKeySettings filesKeySettings{{defaultFilesKeyScheme()},0};
|
||||
|
||||
bool sameFilesKeySchemeName(std::wstring_view first,std::wstring_view second)
|
||||
{
|
||||
return CompareStringOrdinal(first.data(),static_cast<int>(first.size()),
|
||||
second.data(),static_cast<int>(second.size()),TRUE)==CSTR_EQUAL;
|
||||
}
|
||||
|
||||
bool validFilesKeySchemeName(std::wstring_view name)
|
||||
{
|
||||
return !name.empty() && name.size()<=48 && !iswspace(name.front()) && !iswspace(name.back()) &&
|
||||
std::ranges::none_of(name,[](wchar_t character){return iswcntrl(character);});
|
||||
}
|
||||
|
||||
unsigned reservedFilesKeyContexts(WORD binding)
|
||||
{
|
||||
const auto key=LOBYTE(binding),mods=HIBYTE(binding);
|
||||
if(key>=VK_F1 && key<=VK_F24)
|
||||
{
|
||||
if(mods==keyAlt && key==VK_F4) return terminalKeyContext;
|
||||
if(!mods && key==VK_F1) return bothKeyContexts;
|
||||
if((!mods && key==VK_F9) || (mods==keyAlt && (key==VK_F1 || key==VK_F2 || key==VK_F10)) ||
|
||||
(mods==keyShift && key==VK_F4) || (mods==keyShift && key==VK_F10) ||
|
||||
(mods==keyCtrl && key<=VK_F12))
|
||||
return panelKeyContext;
|
||||
return 0;
|
||||
}
|
||||
if(key==VK_DOWN && !mods) return panelKeyContext;
|
||||
if(key>='A' && key<='Z' && (mods&keyCtrl) && !(mods&keyAlt))
|
||||
{
|
||||
constexpr std::wstring_view editing=L"CFOPVXYZ";
|
||||
if(mods==keyCtrl && editing.find(key)!=editing.npos) return bothKeyContexts;
|
||||
if((mods==keyCtrl && key=='A') || (mods==(keyCtrl|keyShift) && (key=='C' || key=='V')))
|
||||
return terminalKeyContext;
|
||||
return 0;
|
||||
}
|
||||
return bothKeyContexts;
|
||||
}
|
||||
|
||||
std::wstring filesKeyConflict(const FilesKeyScheme &scheme,size_t command,WORD binding)
|
||||
{
|
||||
if(!binding || (HIBYTE(binding)&~(keyCtrl|keyShift|keyAlt)))
|
||||
return L"Use a function key or a letter with Ctrl.";
|
||||
const auto contexts=filesKeyCommands[command].contexts;
|
||||
if(reservedFilesKeyContexts(binding)&contexts)
|
||||
return filesKeyLabel(binding)+L" is reserved or unavailable in this context.";
|
||||
for(size_t i=0;i<scheme.keys.size();++i)
|
||||
if((filesKeyCommands[i].contexts&contexts) && std::ranges::find(scheme.keys[i],binding)!=scheme.keys[i].end())
|
||||
return filesKeyLabel(binding)+L" is already assigned to "+filesKeyCommands[i].label+L".";
|
||||
return {};
|
||||
}
|
||||
|
||||
std::optional<FilesKeySettings> parseFilesKeySettings(const Json &stored)
|
||||
{
|
||||
try
|
||||
{
|
||||
if(stored.at("version")!=1 || !stored.at("schemes").is_array()) return {};
|
||||
const auto &rows=stored.at("schemes");
|
||||
if(rows.empty() || rows.size()>filesKeySchemeLimit) return {};
|
||||
FilesKeySettings settings;
|
||||
const auto active=stored.at("active").get<std::string>();
|
||||
for(const auto &row:rows)
|
||||
{
|
||||
auto name=ks::wide(row.at("name").get<std::string>());
|
||||
if(!validFilesKeySchemeName(name) ||
|
||||
std::ranges::any_of(settings.schemes,[&](const auto &other)
|
||||
{ return sameFilesKeySchemeName(other.name,name); })) return {};
|
||||
FilesKeyScheme scheme{std::move(name),{}};
|
||||
const auto &commands=row.at("commands");
|
||||
if(!commands.is_object()) return {};
|
||||
for(size_t i=0;i<scheme.keys.size();++i)
|
||||
{
|
||||
const auto found=commands.find(filesKeyCommands[i].id);
|
||||
if(found==commands.end()) continue;
|
||||
if(!found->is_array() || found->size()>filesKeysPerCommand) return {};
|
||||
for(const auto &entry:*found)
|
||||
{
|
||||
if(!entry.is_number_unsigned() || entry>0xffff) return {};
|
||||
const auto binding=entry.get<WORD>();
|
||||
if(binding==chord(VK_F1)) continue;
|
||||
if(!filesKeyConflict(scheme,i,binding).empty()) return {};
|
||||
scheme.keys[i].push_back(binding);
|
||||
}
|
||||
}
|
||||
for(size_t i=0;i<scheme.keys.size();++i)
|
||||
if(!commands.contains(filesKeyCommands[i].id))
|
||||
for(const auto binding:filesKeyCommands[i].defaults)
|
||||
if(binding && filesKeyConflict(scheme,i,binding).empty()) scheme.keys[i].push_back(binding);
|
||||
if(active==ks::utf8(scheme.name)) settings.active=settings.schemes.size();
|
||||
settings.schemes.push_back(std::move(scheme));
|
||||
}
|
||||
return settings;
|
||||
}
|
||||
catch(const std::exception &) { return {}; }
|
||||
}
|
||||
|
||||
Json serializeFilesKeySettings(const FilesKeySettings &settings)
|
||||
{
|
||||
Json schemes=Json::array();
|
||||
for(const auto &scheme:settings.schemes)
|
||||
{
|
||||
Json commands=Json::object();
|
||||
for(size_t i=0;i<scheme.keys.size();++i) commands[filesKeyCommands[i].id]=scheme.keys[i];
|
||||
schemes.push_back({{"name",ks::utf8(scheme.name)},{"commands",std::move(commands)}});
|
||||
}
|
||||
return {{"version",1},{"active",ks::utf8(settings.schemes[settings.active].name)},{"schemes",std::move(schemes)}};
|
||||
}
|
||||
|
||||
void loadFilesKeySettings()
|
||||
{
|
||||
if(const auto json=readFilesJsonPreference(filesKeySchemePreference))
|
||||
if(auto settings=parseFilesKeySettings(*json))
|
||||
{
|
||||
filesKeySettings=std::move(*settings);
|
||||
return;
|
||||
}
|
||||
auto migrated=defaultFilesKeyScheme(L"Previous settings");
|
||||
constexpr struct { FilesKey command; const wchar_t *name; } legacy[]{
|
||||
{FilesKey::Previous,L"PreviousCommandKey"},{FilesKey::History,L"CommandHistoryKey"},
|
||||
{FilesKey::Compare,L"ComparisonShortcut"},
|
||||
};
|
||||
for(const auto &item:legacy)
|
||||
{
|
||||
const auto index=keyIndex(item.command);
|
||||
auto &keys=migrated.keys[index];
|
||||
const auto fallback=filesKeyCommands[index].defaults.front();
|
||||
const auto binding=static_cast<WORD>(preference(item.name,fallback));
|
||||
const auto context=filesKeyCommands[index].contexts;
|
||||
if(binding==fallback || (HIBYTE(binding)&~(keyCtrl|keyShift|keyAlt)) ||
|
||||
(reservedFilesKeyContexts(binding)&context)) continue;
|
||||
for(size_t i=0;i<migrated.keys.size();++i)
|
||||
if(filesKeyCommands[i].contexts&context) std::erase(migrated.keys[i],binding);
|
||||
keys={binding};
|
||||
}
|
||||
filesKeySettings={{defaultFilesKeyScheme()},0};
|
||||
if(migrated.keys!=filesKeySettings.schemes.front().keys)
|
||||
{
|
||||
filesKeySettings.schemes.push_back(std::move(migrated));
|
||||
filesKeySettings.active=1;
|
||||
}
|
||||
}
|
||||
|
||||
WORD currentFilesChord(WPARAM key)
|
||||
{
|
||||
if(key>0xff || ((GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000)) return 0;
|
||||
return chord(static_cast<BYTE>(key),((GetKeyState(VK_CONTROL)&0x8000)?keyCtrl:0) |
|
||||
((GetKeyState(VK_SHIFT)&0x8000)?keyShift:0) | ((GetKeyState(VK_MENU)&0x8000)?keyAlt:0));
|
||||
}
|
||||
|
||||
std::optional<FilesKey> boundFilesCommand(WORD binding,unsigned context)
|
||||
{
|
||||
const auto &keys=filesKeySettings.schemes[filesKeySettings.active].keys;
|
||||
for(size_t i=0;i<keys.size();++i)
|
||||
if((filesKeyCommands[i].contexts&context) && std::ranges::find(keys[i],binding)!=keys[i].end())
|
||||
return static_cast<FilesKey>(i);
|
||||
return {};
|
||||
}
|
||||
|
||||
std::wstring filesKeyHint(FilesKey command,bool all=false)
|
||||
{
|
||||
std::wstring text;
|
||||
for(const auto binding:filesKeySettings.schemes[filesKeySettings.active].keys[keyIndex(command)])
|
||||
{
|
||||
if(!text.empty()) text+=L", ";
|
||||
text+=filesKeyLabel(binding);
|
||||
if(!all) break;
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
std::wstring filesKeyMenuLabel(FilesKey command,std::wstring label={})
|
||||
{
|
||||
if(label.empty()) label=filesKeyCommands[keyIndex(command)].label;
|
||||
const auto keys=filesKeyHint(command,true);
|
||||
if(!keys.empty()) label+=L"\t"+keys;
|
||||
return label;
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
constexpr int keySchemeChoice=610,keySchemeCopy=611,keySchemeReset=612,keySchemeCommand=613,
|
||||
keySchemeContext=614,keySchemeBindings=615,keySchemeCapture=616,keySchemeAdd=617,keySchemeRemove=618,
|
||||
keySchemePrimary=619,keySchemeName=620;
|
||||
|
||||
struct FilesKeySchemeDraft
|
||||
{
|
||||
FilesKeySettings base=filesKeySettings,settings=base;
|
||||
FilesKey initial;
|
||||
FilesKeySettings *pending{};
|
||||
};
|
||||
|
||||
INT_PTR CALLBACK copyKeySchemeDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
auto &name=*reinterpret_cast<std::wstring*>(lp);
|
||||
SendDlgItemMessageW(dialog,keySchemeName,EM_SETLIMITTEXT,48,0);
|
||||
SetDlgItemTextW(dialog,keySchemeName,name.c_str());
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
|
||||
auto &name=*reinterpret_cast<std::wstring*>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
wchar_t entry[49]{};
|
||||
GetDlgItemTextW(dialog,keySchemeName,entry,std::size(entry));
|
||||
name=entry;
|
||||
FilesModalDialog::finish(dialog,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
void refreshFilesKeyBindings(HWND dialog,const FilesKeyScheme &scheme,size_t command,size_t selection=0)
|
||||
{
|
||||
const auto &descriptor=filesKeyCommands[command];
|
||||
SetDlgItemTextW(dialog,keySchemeContext,
|
||||
descriptor.contexts==bothKeyContexts?L"Keys · panels and command output":
|
||||
descriptor.contexts==terminalKeyContext?L"Keys · command output":L"Keys · file panels");
|
||||
const auto list=GetDlgItem(dialog,keySchemeBindings);
|
||||
SendMessageW(list,LB_RESETCONTENT,0,0);
|
||||
const auto &keys=scheme.keys[command];
|
||||
for(size_t i=0;i<keys.size();++i)
|
||||
{
|
||||
auto label=filesKeyLabel(keys[i]);
|
||||
if(!i) label+=L" (primary)";
|
||||
SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
|
||||
}
|
||||
if(!keys.empty()) SendMessageW(list,LB_SETCURSEL,std::min(selection,keys.size()-1),0);
|
||||
EnableWindow(GetDlgItem(dialog,keySchemeRemove),!keys.empty());
|
||||
EnableWindow(GetDlgItem(dialog,keySchemePrimary),keys.size()>1 && selection>0 && selection<keys.size());
|
||||
EnableWindow(GetDlgItem(dialog,keySchemeAdd),keys.size()<filesKeysPerCommand);
|
||||
}
|
||||
|
||||
void refreshFilesKeySchemes(HWND dialog,const FilesKeySettings &settings)
|
||||
{
|
||||
const auto choice=GetDlgItem(dialog,keySchemeChoice);
|
||||
SendMessageW(choice,CB_RESETCONTENT,0,0);
|
||||
for(const auto &scheme:settings.schemes)
|
||||
SendMessageW(choice,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(scheme.name.c_str()));
|
||||
SendMessageW(choice,CB_SETCURSEL,settings.active,0);
|
||||
EnableWindow(GetDlgItem(dialog,keySchemeCopy),settings.schemes.size()<filesKeySchemeLimit);
|
||||
}
|
||||
|
||||
std::wstring filesKeyBarLabel(FilesKey command,const wchar_t *action)
|
||||
{
|
||||
return filesKeyHint(command)+L" "+action;
|
||||
}
|
||||
|
||||
void refreshFilesKeyBar()
|
||||
{
|
||||
for(size_t i=0;i<std::size(keyBar);++i)
|
||||
{
|
||||
SetWindowTextW(commands[i],filesKeyBarLabel(keyBar[i].command,keyBar[i].label).c_str());
|
||||
InvalidateRect(commands[i],nullptr,FALSE);
|
||||
}
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK filesKeySchemesDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
auto &draft=*reinterpret_cast<FilesKeySchemeDraft*>(lp);
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
refreshFilesKeySchemes(dialog,draft.settings);
|
||||
for(const auto &item:filesKeyCommands)
|
||||
SendDlgItemMessageW(dialog,keySchemeCommand,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(item.label));
|
||||
const auto index=keyIndex(draft.initial);
|
||||
SendDlgItemMessageW(dialog,keySchemeCommand,LB_SETCURSEL,index,0);
|
||||
refreshFilesKeyBindings(dialog,draft.settings.schemes[draft.settings.active],index);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
if(message!=WM_COMMAND) return FALSE;
|
||||
auto &draft=*reinterpret_cast<FilesKeySchemeDraft*>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
auto &settings=draft.settings;
|
||||
auto &scheme=settings.schemes[settings.active];
|
||||
const auto row=SendDlgItemMessageW(dialog,keySchemeCommand,LB_GETCURSEL,0,0);
|
||||
if(row==LB_ERR) return FALSE;
|
||||
const auto command=static_cast<size_t>(row);
|
||||
const auto position=static_cast<size_t>(SendDlgItemMessageW(dialog,keySchemeBindings,LB_GETCURSEL,0,0));
|
||||
auto &keys=scheme.keys[command];
|
||||
switch(LOWORD(wp))
|
||||
{
|
||||
case keySchemeChoice:
|
||||
if(HIWORD(wp)==CBN_SELCHANGE)
|
||||
{
|
||||
const auto chosen=SendDlgItemMessageW(dialog,keySchemeChoice,CB_GETCURSEL,0,0);
|
||||
if(chosen!=CB_ERR) settings.active=static_cast<size_t>(chosen);
|
||||
refreshFilesKeyBindings(dialog,settings.schemes[settings.active],command);
|
||||
}
|
||||
return TRUE;
|
||||
case keySchemeCommand:
|
||||
if(HIWORD(wp)==LBN_SELCHANGE) refreshFilesKeyBindings(dialog,scheme,command);
|
||||
return TRUE;
|
||||
case keySchemeBindings:
|
||||
if(HIWORD(wp)==LBN_SELCHANGE)
|
||||
EnableWindow(GetDlgItem(dialog,keySchemePrimary),position>0 && position<keys.size());
|
||||
return TRUE;
|
||||
case keySchemeCopy:
|
||||
{
|
||||
if(settings.schemes.size()>=filesKeySchemeLimit) return TRUE;
|
||||
std::wstring name=scheme.name.substr(0,43)+L" copy";
|
||||
FilesModalDialog copyName(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(616),dialog,
|
||||
copyKeySchemeDialog,reinterpret_cast<LPARAM>(&name),false);
|
||||
if(copyName.runModal()!=IDOK) return TRUE;
|
||||
if(!validFilesKeySchemeName(name) || std::ranges::any_of(settings.schemes,[&](const auto &other)
|
||||
{ return sameFilesKeySchemeName(other.name,name); }))
|
||||
{
|
||||
showFilesNotice(dialog,L"Enter a unique name with no leading or trailing spaces.",L"Keyboard shortcuts");
|
||||
return TRUE;
|
||||
}
|
||||
auto copy=scheme;
|
||||
copy.name=std::move(name);
|
||||
settings.schemes.push_back(std::move(copy));
|
||||
settings.active=settings.schemes.size()-1;
|
||||
refreshFilesKeySchemes(dialog,settings);
|
||||
refreshFilesKeyBindings(dialog,settings.schemes.back(),command);
|
||||
return TRUE;
|
||||
}
|
||||
case keySchemeReset:
|
||||
{
|
||||
FilesNoticeOptions notice;
|
||||
notice.confirm=true;
|
||||
notice.accept=L"&Reset";
|
||||
const auto prompt=L"Reset all keys in “"+scheme.name+L"” to defaults?";
|
||||
if(showFilesNotice(dialog,prompt.c_str(),L"Keyboard shortcuts",notice)!=IDYES) return TRUE;
|
||||
scheme=defaultFilesKeyScheme(scheme.name);
|
||||
refreshFilesKeyBindings(dialog,scheme,command);
|
||||
return TRUE;
|
||||
}
|
||||
case keySchemeAdd:
|
||||
{
|
||||
if(keys.size()>=filesKeysPerCommand) return TRUE;
|
||||
const auto binding=static_cast<WORD>(SendDlgItemMessageW(dialog,keySchemeCapture,HKM_GETHOTKEY,0,0));
|
||||
if(const auto conflict=filesKeyConflict(scheme,command,binding);!conflict.empty())
|
||||
{
|
||||
showFilesNotice(dialog,conflict.c_str(),L"Keyboard shortcuts");
|
||||
SetFocus(GetDlgItem(dialog,keySchemeCapture));
|
||||
return TRUE;
|
||||
}
|
||||
keys.push_back(binding);
|
||||
SendDlgItemMessageW(dialog,keySchemeCapture,HKM_SETHOTKEY,0,0);
|
||||
refreshFilesKeyBindings(dialog,scheme,command,keys.size()-1);
|
||||
return TRUE;
|
||||
}
|
||||
case keySchemeRemove:
|
||||
if(position<keys.size())
|
||||
{
|
||||
keys.erase(keys.begin()+position);
|
||||
refreshFilesKeyBindings(dialog,scheme,command,position<keys.size()?position:0);
|
||||
}
|
||||
return TRUE;
|
||||
case keySchemePrimary:
|
||||
if(position>0 && position<keys.size())
|
||||
{
|
||||
std::rotate(keys.begin(),keys.begin()+position,keys.begin()+position+1);
|
||||
refreshFilesKeyBindings(dialog,scheme,command);
|
||||
}
|
||||
return TRUE;
|
||||
case IDOK:
|
||||
if(draft.pending) *draft.pending=settings;
|
||||
else if(settings!=draft.base)
|
||||
{
|
||||
const OptionsWriteLock writeLock;
|
||||
if(!writeLock.acquired())
|
||||
{
|
||||
showFilesNotice(dialog,L"Another window is saving Files settings. Try again.",L"Keyboard shortcuts");
|
||||
return TRUE;
|
||||
}
|
||||
loadFilesKeySettings();
|
||||
if(filesKeySettings!=draft.base && filesKeySettings!=settings)
|
||||
{
|
||||
showFilesNotice(dialog,L"Keyboard schemes were changed in another window. Reopen this dialog.",
|
||||
L"Keyboard shortcuts");
|
||||
return TRUE;
|
||||
}
|
||||
if(!writeFilesJsonPreference(filesKeySchemePreference,serializeFilesKeySettings(settings)))
|
||||
{
|
||||
showFilesNotice(dialog,L"Could not save the keyboard schemes.",L"Keyboard shortcuts");
|
||||
return TRUE;
|
||||
}
|
||||
filesKeySettings=settings;
|
||||
refreshFilesKeyBar();
|
||||
showFileDetails(panels[active]);
|
||||
notifyFilesPreferences(GetAncestor(dialog,GA_ROOTOWNER));
|
||||
}
|
||||
FilesModalDialog::finish(dialog,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
void editFilesKeySchemes(HWND owner,FilesKey initial,FilesKeySettings *pending)
|
||||
{
|
||||
if(!pending) loadFilesKeySettings();
|
||||
const auto &base=pending?*pending:filesKeySettings;
|
||||
FilesKeySchemeDraft draft{base,base,initial,pending};
|
||||
FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(615),owner,
|
||||
filesKeySchemesDialog,reinterpret_cast<LPARAM>(&draft),false);
|
||||
dialog.runModal();
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
+213
-160
@@ -16,6 +16,7 @@
|
||||
#include <numbers>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <charconv>
|
||||
#include <atomic>
|
||||
#include <deque>
|
||||
#include <filesystem>
|
||||
@@ -48,6 +49,9 @@
|
||||
#include "files_text_window.h"
|
||||
#include "files_menu_navigation.h"
|
||||
#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"
|
||||
@@ -805,10 +809,12 @@ size_t terminalHistoryIndex{};
|
||||
std::wstring terminalHistoryDraft;
|
||||
constexpr UINT_PTR transferHighlightTimer=1;
|
||||
unsigned transferHighlightPhase{};
|
||||
constexpr struct KeyBarCommand { int id; WPARAM key; const wchar_t *label; } keyBar[]{
|
||||
{110,VK_F2,L"Ctrl+R Refresh"}, {111,VK_F3,L"F3 View"}, {112,VK_F4,L"F4 Edit"},
|
||||
{113,VK_F5,L"F5 Copy"}, {114,VK_F6,L"F6 Move"}, {115,VK_F7,L"F7 Mkdir"},
|
||||
{117,VK_F8,L"F8 Delete"}, {116,VK_F10,L"F10 Exit"}
|
||||
DWORD preference(const wchar_t *name,DWORD fallback);
|
||||
#include "files_key_schemes.inl"
|
||||
constexpr struct KeyBarCommand { int id; FilesKey command; const wchar_t *label; } keyBar[]{
|
||||
{110,FilesKey::Refresh,L"Refresh"}, {111,FilesKey::View,L"View"}, {112,FilesKey::Edit,L"Edit"},
|
||||
{113,FilesKey::Copy,L"Copy"}, {114,FilesKey::Move,L"Move"}, {115,FilesKey::Mkdir,L"Mkdir"},
|
||||
{117,FilesKey::Delete,L"Delete"}, {116,FilesKey::Exit,L"Exit"}
|
||||
};
|
||||
HWND status{}, commands[std::size(keyBar)]{};
|
||||
int active{}, split{};
|
||||
@@ -1059,10 +1065,33 @@ void setMode(int index,PanelMode mode)
|
||||
if((previous^effectivePanelColumns(panel))&extendedColumnMask) refreshPanelColumnData(panel);
|
||||
showFileDetails(panels[active]);
|
||||
}
|
||||
HFONT mono{};
|
||||
HFONT mono{},terminalFont{};
|
||||
LOGFONTW displayFont{};
|
||||
int fontPoints=110;
|
||||
int textHeight=20, cellWidth=9;
|
||||
int textHeight=20, cellWidth=9,terminalTextHeight=20;
|
||||
|
||||
using ks::files::AppearanceArea;
|
||||
constexpr const wchar_t *areaScaleKeys[]{L"PanelScale",L"ViewerScale",L"EditorScale",L"MarkdownScale",
|
||||
L"TerminalScale",L"ComparisonScale"};
|
||||
static_assert(std::size(areaScaleKeys)==ks::files::appearanceIndex(AppearanceArea::count));
|
||||
|
||||
unsigned readAreaScale(AppearanceArea area)
|
||||
{
|
||||
const auto value=preference(areaScaleKeys[ks::files::appearanceIndex(area)],100);
|
||||
return value>=ks::files::minAppearanceScale && value<=ks::files::maxAppearanceScale?value:100;
|
||||
}
|
||||
|
||||
ks::files::AppearanceScales readAreaScales()
|
||||
{
|
||||
auto result=ks::files::defaultAppearanceScales;
|
||||
for(size_t i=0;i<result.size();++i) result[i]=readAreaScale(static_cast<AppearanceArea>(i));
|
||||
return result;
|
||||
}
|
||||
|
||||
int areaFontPoints(int points,AppearanceArea area)
|
||||
{
|
||||
return ks::files::scaledAppearanceSize(points,readAreaScale(area));
|
||||
}
|
||||
|
||||
using PanelColumnRects=std::array<RECT,panelColumnCount>;
|
||||
|
||||
@@ -1186,21 +1215,33 @@ std::array<HFONT,4> fileStyleFonts{};
|
||||
bool applyFont(HWND owner, LOGFONTW font, int points)
|
||||
{
|
||||
const auto dpi=GetDpiForWindow(owner);
|
||||
font.lfHeight=-MulDiv(points,dpi,720);
|
||||
font.lfWidth=0;
|
||||
auto next=CreateFontIndirectW(&font);
|
||||
if(!next) return false;
|
||||
const int terminalPoints=areaFontPoints(points,AppearanceArea::terminal);
|
||||
font.lfHeight=-MulDiv(terminalPoints,dpi,720);
|
||||
const auto nextTerminal=CreateFontIndirectW(&font);
|
||||
font.lfHeight=-MulDiv(areaFontPoints(points,AppearanceArea::panels),dpi,720);
|
||||
const auto next=CreateFontIndirectW(&font);
|
||||
auto dc=GetDC(owner);
|
||||
if(!dc){DeleteObject(next);return false;}
|
||||
auto previous=SelectObject(dc,next);
|
||||
TEXTMETRICW metrics{};
|
||||
if(!next || !nextTerminal || !dc)
|
||||
{
|
||||
if(next) DeleteObject(next);
|
||||
if(nextTerminal) DeleteObject(nextTerminal);
|
||||
if(dc) ReleaseDC(owner,dc);
|
||||
return false;
|
||||
}
|
||||
const auto previous=SelectObject(dc,next);
|
||||
TEXTMETRICW metrics{},terminalMetrics{};
|
||||
GetTextMetricsW(dc,&metrics);
|
||||
SelectObject(dc,nextTerminal);
|
||||
GetTextMetricsW(dc,&terminalMetrics);
|
||||
SelectObject(dc,previous);
|
||||
ReleaseDC(owner,dc);
|
||||
textHeight=std::max(static_cast<LONG>(MulDiv(16,dpi,96)),metrics.tmHeight+MulDiv(6,dpi,96));
|
||||
cellWidth=std::max(1L,metrics.tmAveCharWidth);
|
||||
auto old=mono;
|
||||
terminalTextHeight=std::max(static_cast<LONG>(MulDiv(16,dpi,96)),terminalMetrics.tmHeight+MulDiv(6,dpi,96));
|
||||
const auto old=mono,oldTerminal=terminalFont;
|
||||
mono=next;
|
||||
terminalFont=nextTerminal;
|
||||
for(unsigned i=1;i<fileStyleFonts.size();++i)
|
||||
{
|
||||
if(fileStyleFonts[i]) DeleteObject(fileStyleFonts[i]);
|
||||
@@ -1210,9 +1251,10 @@ bool applyFont(HWND owner, LOGFONTW font, int points)
|
||||
fileStyleFonts[i]=CreateFontIndirectW(&decorated);
|
||||
}
|
||||
displayFont=font;
|
||||
displayFont.lfHeight=-MulDiv(points,dpi,720);
|
||||
fontPoints=points;
|
||||
terminalView.setFont(displayFont,fontPoints);
|
||||
sshView.setFont(displayFont,fontPoints);
|
||||
terminalView.setFont(displayFont,terminalPoints);
|
||||
sshView.setFont(displayFont,terminalPoints);
|
||||
for(auto &panel:panels)
|
||||
{
|
||||
if(panel.path) SendMessageW(panel.path,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
|
||||
@@ -1222,7 +1264,8 @@ bool applyFont(HWND owner, LOGFONTW font, int points)
|
||||
if(picker) SendMessageW(picker,LB_SETITEMHEIGHT,0,textHeight);
|
||||
if(status) SendMessageW(status,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
|
||||
for(const auto control:{terminalInput,terminalOutput,terminalPrompt})
|
||||
if(control) SendMessageW(control,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
|
||||
if(control) SendMessageW(control,WM_SETFONT,reinterpret_cast<WPARAM>(terminalFont),FALSE);
|
||||
if(oldTerminal) DeleteObject(oldTerminal);
|
||||
if(old)
|
||||
{
|
||||
EnumThreadWindows(GetCurrentThreadId(),[](HWND window,LPARAM parameter)->BOOL
|
||||
@@ -1635,7 +1678,7 @@ void layout(HWND window,bool activeOnly)
|
||||
RECT rect{};
|
||||
GetClientRect(window, &rect);
|
||||
int width = rect.right, height = rect.bottom;
|
||||
const int inputTop=height-2*textHeight;
|
||||
const int inputTop=height-textHeight-terminalTextHeight;
|
||||
const bool gitMode=showingGitChanges();
|
||||
const int terminalBottom=std::max(4,inputTop);
|
||||
const int summaryHeight=!terminalVisible && hasSelectionSummary()?textHeight:0;
|
||||
@@ -1646,7 +1689,7 @@ void layout(HWND window,bool activeOnly)
|
||||
const int panelMargin=compactLayout?4:5;
|
||||
const int pathTop=driveHeight+(compactLayout?1:4);
|
||||
const int terminalTop=terminalVisible?4:std::max(4,terminalBottom-
|
||||
std::min(terminalRows,std::max(0,(terminalBottom-detailsHeight)/textHeight-4))*textHeight);
|
||||
std::min(terminalRows,std::max(0,(terminalBottom-detailsHeight)/terminalTextHeight-4))*terminalTextHeight);
|
||||
const int panelBottom=terminalTop-detailsHeight;
|
||||
const bool showOutput=!gitMode && terminalTop<terminalBottom;
|
||||
traceTerminal("layout",terminalRows,terminalTop,terminalBottom,showOutput,terminalVisible);
|
||||
@@ -1709,14 +1752,14 @@ void layout(HWND window,bool activeOnly)
|
||||
SIZE promptExtent{static_cast<LONG>(prompt.size())*cellWidth,0};
|
||||
if(const auto dc=GetDC(window))
|
||||
{
|
||||
const auto previous=SelectObject(dc,mono);
|
||||
const auto previous=SelectObject(dc,terminalFont);
|
||||
GetTextExtentPoint32W(dc,prompt.c_str(),static_cast<int>(prompt.size()),&promptExtent);
|
||||
SelectObject(dc,previous);
|
||||
ReleaseDC(window,dc);
|
||||
}
|
||||
const int promptWidth=std::min(width/2,static_cast<int>(promptExtent.cx));
|
||||
place(terminalPrompt,4,inputTop,promptWidth,textHeight);
|
||||
place(terminalInput,4+promptWidth,inputTop,std::max(0,width-8-promptWidth),textHeight);
|
||||
place(terminalPrompt,4,inputTop,promptWidth,terminalTextHeight);
|
||||
place(terminalInput,4+promptWidth,inputTop,std::max(0,width-8-promptWidth),terminalTextHeight);
|
||||
if(activeOnly)
|
||||
{
|
||||
const RECT details{0,panelBottom+detailsInset+summaryHeight,width,
|
||||
@@ -2389,6 +2432,11 @@ void handleTerminalPromptInput(HWND owner,std::wstring_view action)
|
||||
const auto key=std::find_if(std::begin(keys),std::end(keys),
|
||||
[action](const auto &binding){ return binding.first==action; });
|
||||
if(key==std::end(keys) || handleCompletionKey(key->second,0)) return;
|
||||
if(key->second==VK_F1)
|
||||
{
|
||||
PostMessageW(owner,ks::files::filesHelpRequest,0,0);
|
||||
return;
|
||||
}
|
||||
const auto character=key->second==VK_BACK || key->second==VK_ESCAPE;
|
||||
SendMessageW(terminalInput,character?WM_CHAR:WM_KEYDOWN,key->second,0);
|
||||
}
|
||||
@@ -2406,7 +2454,7 @@ bool ensureTerminalView(HWND owner,bool ssh=false)
|
||||
auto &source=ssh?sshView:terminalView;
|
||||
if(message==L"ready")
|
||||
{
|
||||
source.setFont(displayFont,fontPoints);
|
||||
source.setFont(displayFont,areaFontPoints(fontPoints,AppearanceArea::terminal));
|
||||
if(ssh) source.post(L"ssh-reset");
|
||||
if(terminalTrace.is_open() && !ssh) source.enableTrace(traceTerminalOutput);
|
||||
}
|
||||
@@ -2724,10 +2772,9 @@ LRESULT CALLBACK terminalInputKeys(HWND input,UINT message,WPARAM wp,LPARAM lp,U
|
||||
SendMessageW(panels[active].list,WM_KEYDOWN,wp,lp);
|
||||
return 0;
|
||||
}
|
||||
if(message==WM_KEYDOWN && (wp==VK_UP || wp==VK_DOWN))
|
||||
if(message==WM_KEYDOWN && wp==VK_UP)
|
||||
{
|
||||
if(wp==VK_UP) recallPreviousCommand();
|
||||
if(wp==VK_DOWN && terminalHistoryIndex<terminalHistory.size()) recallCommand(terminalHistoryIndex+1);
|
||||
recallPreviousCommand();
|
||||
return 0;
|
||||
}
|
||||
return DefSubclassProc(input,message,wp,lp);
|
||||
@@ -2827,9 +2874,11 @@ void showFileDetails(const Panel &panel)
|
||||
if(&panel==&panels[active])
|
||||
for(const auto key:commands) InvalidateRect(key,nullptr,FALSE);
|
||||
if(&panel==&panels[active] && showDirectoryScanProgress(panels[active])) return;
|
||||
const auto refreshKey=filesKeyHint(FilesKey::Refresh);
|
||||
if(panel.remoteRetry)
|
||||
{
|
||||
setStatus(L"Ctrl+R to retry · "+panel.remoteRetry->failure,true);
|
||||
setStatus((refreshKey.empty()?L"Refresh to retry":refreshKey+L" to retry")+
|
||||
L" · "+panel.remoteRetry->failure,true);
|
||||
return;
|
||||
}
|
||||
if(panel.findOrigin)
|
||||
@@ -2838,7 +2887,7 @@ void showFileDetails(const Panel &panel)
|
||||
const auto count=std::to_wstring(panel.rows.size());
|
||||
if(error==ERROR_CONNECTION_ABORTED)
|
||||
setStatus(count+(panel.rows.size()==1?L" match":L" matches")+
|
||||
L" · Connection interrupted · Ctrl+R Retry · Esc Back");
|
||||
L" · Connection interrupted · "+(refreshKey.empty()?L"Refresh to retry":refreshKey+L" Retry")+L" · Esc Back");
|
||||
else setStatus(count+(error==ERROR_CANCELLED?L" matches (stopped)":
|
||||
error?L" matches (some folders could not be read)":L" matches")+
|
||||
L" · Enter: Go · Esc: Back");
|
||||
@@ -2847,7 +2896,8 @@ void showFileDetails(const Panel &panel)
|
||||
if(transferProfileList(panel))
|
||||
{
|
||||
setStatus(transferProfiles(panel.ftp->protocol).rows.empty()?L"Shift+F4 New connection":
|
||||
L"Shift+F4 New F4 Edit Enter Connect");
|
||||
L"Shift+F4 New "+(filesKeyHint(FilesKey::Edit).empty()?L"":filesKeyHint(FilesKey::Edit)+L" Edit ")+
|
||||
L"Enter Connect");
|
||||
return;
|
||||
}
|
||||
auto row=SendMessageW(panel.list,LB_GETCURSEL,0,0);
|
||||
@@ -3775,7 +3825,7 @@ ks::files::FarDropDownPalette farDropDownPalette();
|
||||
void prepareCopyDialog(HWND dialog);
|
||||
void prepareTextDialog(HWND dialog);
|
||||
void showTextMessage(HWND owner,const wchar_t *text);
|
||||
void editTextOptions(HWND owner,bool edit);
|
||||
void editFilesAppearance(HWND owner,AppearanceArea area);
|
||||
|
||||
void startPeerAction(std::packaged_task<std::wstring()> task,const std::wstring &status)
|
||||
{
|
||||
@@ -3891,6 +3941,11 @@ void showProcesses(HWND owner,std::vector<fs::path> paths={});
|
||||
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);
|
||||
|
||||
bool selectablePickerRow(LRESULT row)
|
||||
{
|
||||
@@ -3942,6 +3997,12 @@ void selectDrive()
|
||||
else if(menuIndex==2 && row==16) openGitChanges(owner,panels[active]);
|
||||
else if(menuIndex==2 && row==17) showEnvironmentPanel(owner);
|
||||
else if(menuIndex==2 && row==18) swapPanels(owner);
|
||||
else if(menuIndex==2 && row==19) showCommandHistory(owner);
|
||||
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]);
|
||||
@@ -4511,7 +4572,7 @@ void openSelectedWithSystem(const Panel &panel)
|
||||
|
||||
ks::files::TextDialogs textWindowDialogs()
|
||||
{
|
||||
return {confirmTextSave,paintTextDialog,paintSearchDialog,prepareTextDialog,editTextOptions,showTextMessage,readFilesFont,
|
||||
return {confirmTextSave,paintTextDialog,paintSearchDialog,prepareTextDialog,editFilesAppearance,showTextMessage,readFilesFont,
|
||||
farDropDownPalette,FilesModalDialog::run,FilesModalDialog::finish,FilesModalDialog::dismissOwned,
|
||||
[](HWND owner)
|
||||
{
|
||||
@@ -4523,7 +4584,7 @@ ks::files::TextDialogs textWindowDialogs()
|
||||
return showFilesNotice(owner,L"The file changed outside Files. Reload the disk version?",
|
||||
L"File changed on disk",{.confirm=true,.tone=FilesNoticeTone::warning,
|
||||
.accept=L"&Reload",.decline=L"&Keep buffer"})==IDYES;
|
||||
}};
|
||||
},readAreaScale};
|
||||
}
|
||||
|
||||
void refreshQuickView(const Panel &panel)
|
||||
@@ -4578,17 +4639,6 @@ void toggleQuickView(HWND owner)
|
||||
layout(owner);
|
||||
}
|
||||
|
||||
bool handleQuickViewKey(HWND window,const MSG &message)
|
||||
{
|
||||
if(message.message!=WM_KEYDOWN || message.wParam!='Q' || terminalVisible ||
|
||||
!commandLineAvailable(window) ||
|
||||
!(GetKeyState(VK_CONTROL)&0x8000) ||
|
||||
((GetKeyState(VK_MENU)|GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000))
|
||||
return false;
|
||||
if(!(message.lParam&(1LL<<30))) toggleQuickView(window);
|
||||
return true;
|
||||
}
|
||||
|
||||
ks::files::RemoteTextSource transferTextSource(const TransferProfile &profile);
|
||||
|
||||
void openPanelImage(const Panel &panel,const fs::path &path,const ks::files::RemoteTextSource *source=nullptr)
|
||||
@@ -7919,6 +7969,72 @@ void editTransferProfile(Panel &panel,bool create);
|
||||
#include "files_properties.inl"
|
||||
#include "files_context_menu.inl"
|
||||
|
||||
void runFilesKeyCommand(HWND owner,int side,FilesKey command)
|
||||
{
|
||||
auto &panel=panels[side];
|
||||
switch(command)
|
||||
{
|
||||
case FilesKey::Refresh: refreshPanel(panel); break;
|
||||
case FilesKey::View:
|
||||
case FilesKey::Edit:
|
||||
{
|
||||
const bool edit=command==FilesKey::Edit;
|
||||
if(transferProfileList(panel))
|
||||
{
|
||||
if(edit) editTransferProfile(panel,false);
|
||||
break;
|
||||
}
|
||||
const auto row=currentPanelRow(panel);
|
||||
if(edit || row==LB_ERR || !calculateFolderSizes(panel,row)) openSelectedText(panel,edit,false);
|
||||
break;
|
||||
}
|
||||
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::Exit: SendMessageW(owner,WM_CLOSE,0,0); break;
|
||||
case FilesKey::Compare: compareSelectedFiles(owner); break;
|
||||
case FilesKey::Previous: recallPreviousCommand(); break;
|
||||
case FilesKey::Next:
|
||||
if(terminalHistoryIndex<terminalHistory.size()) recallCommand(terminalHistoryIndex+1);
|
||||
break;
|
||||
case FilesKey::History: showCommandHistory(owner); break;
|
||||
case FilesKey::Pack: createArchive(owner,panel); break;
|
||||
case FilesKey::Find: findPanelFiles(owner,panel); break;
|
||||
case FilesKey::ExternalView:
|
||||
case FilesKey::ExternalEdit: openSelectedText(panel,command==FilesKey::ExternalEdit,true); break;
|
||||
case FilesKey::QuickView: toggleQuickView(owner); break;
|
||||
case FilesKey::FullPath: copyFullPanelPath(owner,panel); break;
|
||||
case FilesKey::HexView: openSelectedText(panel,false,false,true); break;
|
||||
case FilesKey::Swap: swapPanels(owner); break;
|
||||
case FilesKey::Properties: showPanelItemProperties(owner,panel); break;
|
||||
case FilesKey::Count: break;
|
||||
}
|
||||
}
|
||||
|
||||
bool handleFilesKeyChord(HWND owner,const MSG &message)
|
||||
{
|
||||
if(message.message!=WM_KEYDOWN && message.message!=WM_SYSKEYDOWN) return false;
|
||||
if(copyInProgress || FilesModalDialog::activeFor(owner) ||
|
||||
(message.hwnd!=owner && message.hwnd!=terminalInput && message.hwnd!=panels[0].list &&
|
||||
message.hwnd!=panels[1].list && !IsChild(owner,message.hwnd))) return false;
|
||||
const bool input=message.hwnd==terminalInput || message.hwnd==panels[0].list || message.hwnd==panels[1].list;
|
||||
const auto binding=currentFilesChord(message.wParam);
|
||||
if(!binding) return false;
|
||||
const auto command=boundFilesCommand(binding,terminalVisible?terminalKeyContext:panelKeyContext);
|
||||
if(!command || (!input && *command!=FilesKey::History && *command!=FilesKey::Exit)) return false;
|
||||
if(!commandLineAvailable(owner) && *command!=FilesKey::History && *command!=FilesKey::Exit) return false;
|
||||
if(*command==FilesKey::Properties && (!panelItemPropertiesAvailable(panels[active]) ||
|
||||
(message.hwnd==terminalInput && GetWindowTextLengthW(terminalInput)))) return false;
|
||||
if(!(message.lParam&(1LL<<30)) || *command==FilesKey::Previous || *command==FilesKey::Next)
|
||||
{
|
||||
hidePicker();
|
||||
showMenu(false);
|
||||
runFilesKeyCommand(owner,message.hwnd==panels[1].list?1:message.hwnd==panels[0].list?0:active,*command);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR)
|
||||
{
|
||||
const auto index=GetDlgCtrlID(window)-102;
|
||||
@@ -8077,7 +8193,7 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
|
||||
SetFocus(terminalInput);
|
||||
return SendMessageW(terminalInput,message,wp,lp);
|
||||
}
|
||||
if (message == WM_KEYDOWN)
|
||||
if (message == WM_KEYDOWN || message==WM_SYSKEYDOWN)
|
||||
{
|
||||
if(wp==VK_TAB)
|
||||
{
|
||||
@@ -8090,38 +8206,14 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
|
||||
return 0;
|
||||
}
|
||||
if (wp == VK_RETURN) { enter(panels[index]); return 0; }
|
||||
if (wp == VK_F2)
|
||||
if(const auto command=boundFilesCommand(currentFilesChord(wp),panelKeyContext))
|
||||
{
|
||||
refreshPanel(panels[index]);
|
||||
runFilesKeyCommand(GetParent(window),static_cast<int>(index),*command);
|
||||
return 0;
|
||||
}
|
||||
if (wp == VK_F10) { SendMessageW(GetParent(window), WM_CLOSE, 0, 0); return 0; }
|
||||
if (wp == VK_F3 || wp == VK_F4)
|
||||
if(wp==VK_DELETE && (GetKeyState(VK_SHIFT)&0x8000))
|
||||
{
|
||||
auto &panel=panels[index];
|
||||
if(transferProfileList(panel))
|
||||
{
|
||||
if(wp==VK_F4) editTransferProfile(panel,false);
|
||||
return 0;
|
||||
}
|
||||
const auto row=currentPanelRow(panel);
|
||||
if(wp==VK_F3 && row!=LB_ERR && calculateFolderSizes(panel,row)) return 0;
|
||||
openSelectedText(panel,wp==VK_F4,false);
|
||||
return 0;
|
||||
}
|
||||
if (wp == VK_F5 || wp == VK_F6)
|
||||
{
|
||||
copySelection(GetParent(window),panels[index],panels[1-index],wp==VK_F6);
|
||||
return 0;
|
||||
}
|
||||
if(wp==VK_F7)
|
||||
{
|
||||
makeFolder(GetParent(window),panels[index]);
|
||||
return 0;
|
||||
}
|
||||
if(wp==VK_F8 || (wp==VK_DELETE && (GetKeyState(VK_SHIFT)&0x8000)))
|
||||
{
|
||||
deleteSelection(GetParent(window),panels[index],wp==VK_DELETE);
|
||||
deleteSelection(GetParent(window),panels[index],true);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -8180,16 +8272,30 @@ bool loadFilesPreferences(HWND window)
|
||||
compactLayout=preference(compactLayoutKey,0)!=0;
|
||||
restoreDocuments=preference(restoreDocumentsKey,0)!=0;
|
||||
statusFields=preference(L"StatusFields",defaultStatusFields)&15;
|
||||
loadCommandHistoryKeys();
|
||||
loadComparisonShortcut();
|
||||
loadFilesKeySettings();
|
||||
return true;
|
||||
}
|
||||
|
||||
#include "files_find.inl"
|
||||
struct OptionsWriteLock
|
||||
{
|
||||
HANDLE mutex=CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.OptionsWrite");
|
||||
DWORD result=mutex?WaitForSingleObject(mutex,2000):WAIT_FAILED;
|
||||
|
||||
bool acquired() const { return result==WAIT_OBJECT_0 || result==WAIT_ABANDONED; }
|
||||
~OptionsWriteLock()
|
||||
{
|
||||
if(acquired()) ReleaseMutex(mutex);
|
||||
if(mutex) CloseHandle(mutex);
|
||||
}
|
||||
};
|
||||
|
||||
#include "files_key_schemes_dialog.inl"
|
||||
#include "files_options.inl"
|
||||
#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)
|
||||
{
|
||||
@@ -8235,16 +8341,20 @@ void openMenu(HWND window, int index)
|
||||
if(detailedPanel(panel)) rows.push_back(L" Columns…");
|
||||
}
|
||||
}
|
||||
else if(index==1) rows={L"Copy\tF5",L"Move\tF6",L"Make folder\tF7",L"Exit\tF10",L"Pack files…\tAlt+F5",
|
||||
L"Properties…\tCtrl+A",L"Locking processes…"};
|
||||
else if(index==1) rows={filesKeyMenuLabel(FilesKey::Copy),filesKeyMenuLabel(FilesKey::Move),
|
||||
filesKeyMenuLabel(FilesKey::Mkdir),filesKeyMenuLabel(FilesKey::Exit),filesKeyMenuLabel(FilesKey::Pack,L"Pack files…"),
|
||||
filesKeyMenuLabel(FilesKey::Properties,L"Properties…"),L"Locking processes…"};
|
||||
else if(index==2)
|
||||
{
|
||||
rows={L"Refresh panel\tCtrl+R",L"View\tF3",L"Edit\tF4",L"Folder shortcuts",
|
||||
L"View externally\tAlt+F3",L"Edit externally\tAlt+F4",
|
||||
L"Hibernate remote PC",L"Update remote KSwitcher",L"Compare files\t"+comparisonShortcutLabel(),
|
||||
L"Find files\tAlt+F7",quickViewWindow?L"Close Quick View\tCtrl+Q":L"Quick View\tCtrl+Q",
|
||||
L"Copy full path\tCtrl+Shift+C",L"Space Analyzer",L"View as hex\tShift+F3",L"Viewer bookmarks…",L"Processes…",
|
||||
L"Git Changes…",L"Environment Variables…",L"Swap panels\tCtrl+U"};
|
||||
rows={filesKeyMenuLabel(FilesKey::Refresh),filesKeyMenuLabel(FilesKey::View),filesKeyMenuLabel(FilesKey::Edit),
|
||||
L"Folder shortcuts",filesKeyMenuLabel(FilesKey::ExternalView),filesKeyMenuLabel(FilesKey::ExternalEdit),
|
||||
L"Hibernate remote PC",L"Update remote KSwitcher",filesKeyMenuLabel(FilesKey::Compare),
|
||||
filesKeyMenuLabel(FilesKey::Find),filesKeyMenuLabel(FilesKey::QuickView,quickViewWindow?L"Close Quick View":L"Quick View"),
|
||||
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",L"Files log…",
|
||||
filesMcp.port()?L"Files MCP (running)…":L"Files MCP…"};
|
||||
}
|
||||
const auto &panel=panels[active];
|
||||
const bool remoteResults=remoteSearchResults(panel);
|
||||
@@ -8255,7 +8365,7 @@ void openMenu(HWND window, int index)
|
||||
if(remoteSearchActionAvailable(113)) commandActions.push_back(0);
|
||||
if(remoteSearchActionAvailable(114))
|
||||
{
|
||||
if(panel.ftp) rows[1]=L"Rename\tF6";
|
||||
if(panel.ftp) rows[1]=filesKeyMenuLabel(FilesKey::Move,L"Rename");
|
||||
commandActions.push_back(1);
|
||||
}
|
||||
commandActions.push_back(3);
|
||||
@@ -8291,6 +8401,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,23,24,22});
|
||||
}
|
||||
else
|
||||
for(size_t i=0;i<rows.size();++i) commandActions.push_back(static_cast<int>(i));
|
||||
@@ -8503,6 +8614,8 @@ void handleFilesReturn(bool shift)
|
||||
|
||||
LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
if(quickViewWindow && ks::files::windowsAppThemeChanged(message,lp))
|
||||
SendMessageW(quickViewWindow,message,wp,lp);
|
||||
if(message==filesPreferencesChanged)
|
||||
{
|
||||
if(quickViewWindow) SendNotifyMessageW(quickViewWindow,message,wp,lp);
|
||||
@@ -8510,6 +8623,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
if(reinterpret_cast<HWND>(wp)!=window)
|
||||
{
|
||||
loadFilesPreferences(window);
|
||||
refreshFilesKeyBar();
|
||||
layout(window);
|
||||
layoutOpenCommandHistory();
|
||||
showFileDetails(panels[active]);
|
||||
@@ -8519,6 +8633,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;
|
||||
@@ -8638,7 +8755,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
terminalBackground=CreateSolidBrush(terminalSurface);
|
||||
if(!terminalInput || !terminalOutput || !terminalPrompt || !terminalBackground) return -1;
|
||||
for(const auto control:{terminalInput,terminalOutput,terminalPrompt})
|
||||
SendMessageW(control,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
|
||||
SendMessageW(control,WM_SETFONT,reinterpret_cast<WPARAM>(terminalFont),FALSE);
|
||||
SendMessageW(terminalInput,EM_SETLIMITTEXT,2048,0);
|
||||
SendMessageW(terminalInput,EM_SETMARGINS,EC_LEFTMARGIN|EC_RIGHTMARGIN,0);
|
||||
SetWindowSubclass(terminalInput,terminalInputKeys,1,0);
|
||||
@@ -8647,7 +8764,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
if (!mono || !blue || !teal || !menuBar || !picker || !pickerFrame || !status || !panelSearchPopup) return -1;
|
||||
SendMessageW(status, WM_SETFONT, reinterpret_cast<WPARAM>(mono), FALSE);
|
||||
for (int i = 0; i < static_cast<int>(std::size(commands)); ++i)
|
||||
commands[i] = CreateWindowW(L"BUTTON", keyBar[i].label, WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,
|
||||
commands[i] = CreateWindowW(L"BUTTON", filesKeyBarLabel(keyBar[i].command,keyBar[i].label).c_str(),
|
||||
WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,
|
||||
0, 0, 0, 0, window, reinterpret_cast<HMENU>(static_cast<INT_PTR>(keyBar[i].id)), instance, nullptr);
|
||||
for(int i=0;i<static_cast<int>(driveButtons.size());++i)
|
||||
{
|
||||
@@ -8976,7 +9094,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
if(std::find(std::begin(commands),std::end(commands),item.hwndItem)!=std::end(commands))
|
||||
{
|
||||
if(item.CtlID==114 && remoteSearchResults(panels[active]) && panels[active].ftp)
|
||||
text=L"F6 Rename";
|
||||
text=filesKeyBarLabel(FilesKey::Move,L"Rename");
|
||||
const auto separator=text.find(L' ');
|
||||
auto key=text.substr(0,separator);
|
||||
if(key.starts_with(L'F') && key.size()>1) key.erase(0,1);
|
||||
@@ -9284,7 +9402,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
for(const auto &command:keyBar)
|
||||
if(LOWORD(wp)==command.id && remoteSearchActionAvailable(command.id))
|
||||
SendMessageW(panels[active].list,WM_KEYDOWN,command.key,0);
|
||||
runFilesKeyCommand(window,active,command.command);
|
||||
}
|
||||
if (LOWORD(wp) >= 102 && LOWORD(wp) <= 103 && HIWORD(wp) == LBN_DBLCLK)
|
||||
enter(panels[LOWORD(wp) - 102]);
|
||||
@@ -9326,6 +9444,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
DestroyWindow(window);
|
||||
return 0;
|
||||
case WM_DESTROY:
|
||||
filesMcp.stop();
|
||||
pendingPanelDrop.reset();
|
||||
closeGitChanges(window,false);
|
||||
for(auto &panel:panels)
|
||||
@@ -9353,6 +9472,9 @@ 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"
|
||||
}
|
||||
|
||||
int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
@@ -9424,7 +9546,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
{
|
||||
if(GetForegroundWindow()==window || IsChild(window,GetFocus())) restoreCommandFocus();
|
||||
if(GetMessageW(&message,nullptr,0,0)<=0) break;
|
||||
if(handleComparisonMessage(message)) continue;
|
||||
if(handleFilesHelpMessage(message) || handleComparisonMessage(message)) continue;
|
||||
if(message.message==WM_KEYDOWN && message.wParam==VK_TAB &&
|
||||
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) &&
|
||||
ks::files::cycleTextWindows(GetAncestor(message.hwnd,GA_ROOT),(GetKeyState(VK_SHIFT)&0x8000)!=0))
|
||||
@@ -9447,7 +9569,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if(handleQuickViewKey(window,message) || handlePanelPathKey(window,message)) continue;
|
||||
if(handlePanelPathKey(window,message) || handleFilesKeyChord(window,message)) continue;
|
||||
if((message.message==WM_KEYDOWN || message.message==WM_SYSKEYDOWN) &&
|
||||
!terminalVisible && commandLineAvailable(window) &&
|
||||
(message.hwnd==terminalInput || message.hwnd==panels[0].list || message.hwnd==panels[1].list) &&
|
||||
@@ -9505,41 +9627,13 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if(!terminalVisible && !copyInProgress && !commandHistoryWindow && !FilesModalDialog::activeFor(window) &&
|
||||
message.message==WM_SYSKEYDOWN && (message.wParam==VK_F5 || message.wParam==VK_F7) &&
|
||||
(message.lParam & (1LL<<29)) &&
|
||||
!((GetKeyState(VK_CONTROL)|GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000))
|
||||
{
|
||||
if(!(message.lParam & (1LL<<30)))
|
||||
{
|
||||
hidePicker();
|
||||
showMenu(false);
|
||||
if(message.wParam==VK_F5) createArchive(window,panels[active]);
|
||||
else findPanelFiles(window,panels[active]);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if(!copyInProgress && !commandHistoryWindow && !FilesModalDialog::activeFor(window) && !terminalVisible &&
|
||||
message.message==WM_SYSKEYDOWN && (message.wParam==VK_F3 || message.wParam==VK_F4) &&
|
||||
(message.lParam & (1LL<<29)) &&
|
||||
!(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_SHIFT)&0x8000) &&
|
||||
(message.hwnd==window || IsChild(window,message.hwnd)))
|
||||
{
|
||||
if(!(message.lParam & (1LL<<30)))
|
||||
{
|
||||
hidePicker();
|
||||
showMenu(false);
|
||||
openSelectedText(panels[active],message.wParam==VK_F4,true);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if(message.message==WM_KEYDOWN && (message.wParam==VK_UP || message.wParam==VK_DOWN) &&
|
||||
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) &&
|
||||
(message.hwnd==window || IsChild(window,message.hwnd)) && !terminalVisible && !copyInProgress)
|
||||
{
|
||||
RECT bounds{};
|
||||
GetClientRect(window,&bounds);
|
||||
const auto maximum=std::max(0,static_cast<int>(bounds.bottom)/textHeight-8);
|
||||
const auto maximum=std::max(0,static_cast<int>(bounds.bottom)/terminalTextHeight-8);
|
||||
const int rows=std::clamp(terminalRows+(message.wParam==VK_UP?1:-1),0,maximum);
|
||||
traceTerminal(message.wParam==VK_UP?"key-grow":"key-shrink",terminalRows,rows);
|
||||
if(rows && !showCommandOutput(window,panels[active])) continue;
|
||||
@@ -9586,21 +9680,6 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
continue;
|
||||
}
|
||||
const bool filesMessage=message.hwnd==window || IsChild(window,message.hwnd);
|
||||
if(filesMessage && !terminalVisible && !copyInProgress && !commandHistoryWindow &&
|
||||
!FilesModalDialog::activeFor(window) && message.message==WM_KEYDOWN &&
|
||||
!(GetKeyState(VK_MENU)&0x8000) && !(GetKeyState(VK_LWIN)&0x8000) &&
|
||||
!(GetKeyState(VK_RWIN)&0x8000) && (GetKeyState(VK_SHIFT)&0x8000) &&
|
||||
MAKEWORD(message.wParam,HOTKEYF_SHIFT|((GetKeyState(VK_CONTROL)&0x8000)?HOTKEYF_CONTROL:0))==
|
||||
comparisonShortcut)
|
||||
{
|
||||
if(!(message.lParam & (1LL<<30)))
|
||||
{
|
||||
hidePicker();
|
||||
showMenu(false);
|
||||
compareSelectedFiles(window);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if(mainInput && !terminalVisible && !copyInProgress &&
|
||||
(message.message==WM_KEYDOWN || (message.message==WM_SYSKEYDOWN && message.wParam==VK_F10)) &&
|
||||
message.wParam>=VK_F1 && message.wParam<=VK_F12 &&
|
||||
@@ -9635,17 +9714,6 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if(ctrl && shift && message.wParam=='C' && !terminalVisible && commandLineAvailable(window))
|
||||
{
|
||||
if(!(message.lParam & (1LL<<30))) copyFullPanelPath(window,panels[active]);
|
||||
continue;
|
||||
}
|
||||
if(ctrl && !shift && message.wParam=='A' && !terminalVisible && commandLineAvailable(window) &&
|
||||
(!GetWindowTextLengthW(terminalInput) || panelFocused) && panelItemPropertiesAvailable(panels[active]))
|
||||
{
|
||||
if(!(message.lParam&(1LL<<30))) showPanelItemProperties(window,panels[active]);
|
||||
continue;
|
||||
}
|
||||
if(shift && !ctrl && message.wParam==VK_F4 && !terminalVisible)
|
||||
{
|
||||
if(!(message.lParam & (1LL<<30)) && commandLineAvailable(window))
|
||||
@@ -9656,21 +9724,13 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if(shift && !ctrl && message.wParam==VK_F3 && !terminalVisible && commandLineAvailable(window))
|
||||
{
|
||||
if(!(message.lParam&(1LL<<30))) openSelectedText(panels[active],false,false,true);
|
||||
continue;
|
||||
}
|
||||
if(ctrl && !shift &&
|
||||
(message.wParam=='F' || message.wParam=='C' || message.wParam=='R' ||
|
||||
(message.wParam=='U' && !terminalVisible) ||
|
||||
(message.wParam=='F' || message.wParam=='C' ||
|
||||
message.wParam==VK_RETURN || message.wParam==VK_INSERT))
|
||||
{
|
||||
if(!(message.lParam & (1LL<<30)))
|
||||
{
|
||||
if(message.wParam=='F') insertCurrentPanelPath();
|
||||
else if(message.wParam=='R') refreshPanel(panels[active]);
|
||||
else if(message.wParam=='U') swapPanels(window);
|
||||
else if(message.wParam==VK_RETURN) insertCurrentPanelPath(true);
|
||||
else if(message.wParam==VK_INSERT) copyCommandLineOrPanelNames(window);
|
||||
else copyOrInterruptTerminal();
|
||||
@@ -9685,7 +9745,6 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if(filesMessage && !copyInProgress && handleCommandHistoryKey(window,message)) continue;
|
||||
const bool modified=(GetKeyState(VK_CONTROL)&0x8000) || (GetKeyState(VK_SHIFT)&0x8000) ||
|
||||
(GetKeyState(VK_LWIN)&0x8000) || (GetKeyState(VK_RWIN)&0x8000);
|
||||
if(filesMessage && !copyInProgress &&
|
||||
@@ -9751,13 +9810,6 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (message.message == WM_SYSKEYDOWN && message.wParam == VK_F10 &&
|
||||
!(GetKeyState(VK_CONTROL) & 0x8000) && !(GetKeyState(VK_MENU) & 0x8000) &&
|
||||
!(GetKeyState(VK_SHIFT) & 0x8000))
|
||||
{
|
||||
SendMessageW(window, WM_CLOSE, 0, 0);
|
||||
continue;
|
||||
}
|
||||
if (message.message == WM_SYSKEYDOWN && (message.wParam == VK_F1 || message.wParam == VK_F2))
|
||||
{
|
||||
chooseDrive(static_cast<int>(message.wParam - VK_F1));
|
||||
@@ -9768,6 +9820,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
}
|
||||
for(auto font:fileStyleFonts) if(font) DeleteObject(font);
|
||||
DeleteObject(mono);
|
||||
DeleteObject(terminalFont);
|
||||
DeleteObject(blue);
|
||||
DeleteObject(teal);
|
||||
DeleteObject(terminalBackground);
|
||||
|
||||
@@ -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 ¶ms)
|
||||
{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."}});}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
};
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
+254
-90
@@ -1,12 +1,13 @@
|
||||
constexpr int optionsSearch=270,optionsTree=271,optionsTitle=272,optionsApply=283,optionsReset=284,optionsProperty=285,optionsResetProperty=286,
|
||||
optionsImport=525,optionsExport=526,
|
||||
optionsRemoteTerminal=370,optionsRemoteHibernate=371,optionsRemoteUpdate=372;
|
||||
enum OptionsPage { PanelModes, PanelColors, Appearance, CommandLine, TextViewer, TextEditor, allOptions, CompareFiles };
|
||||
constexpr const wchar_t *optionsTitles[]{L"File panel modes",L"Colors",L"Appearance",L"Command line",
|
||||
L"Viewer",L"Editor",L"All settings",L"File comparison"};
|
||||
constexpr int comparisonFontLabel=408,comparisonChooseFont=409,comparisonColorCombo=411,
|
||||
comparisonChooseColor=412,comparisonColorValue=413,comparisonShortcutControl=415;
|
||||
comparisonChooseColor=412,comparisonColorValue=413,comparisonKeySchemesButton=415;
|
||||
constexpr int comparisonControls[]{comparisonFontLabel,comparisonChooseFont,410,comparisonColorCombo,
|
||||
comparisonChooseColor,comparisonColorValue,414,comparisonShortcutControl};
|
||||
comparisonChooseColor,comparisonColorValue,comparisonKeySchemesButton};
|
||||
constexpr const wchar_t *colorNames[]{L"Panel background",L"Text",L"Frame",L"Popup background",
|
||||
L"Menu selection",L"Command bar",L"File cursor"};
|
||||
enum PanelSection { PanelLayout, WideColumns, StatusColumns };
|
||||
@@ -17,14 +18,17 @@ constexpr int wideColumnControls[]{275,276,201,202,204};
|
||||
constexpr int statusColumnControls[]{277,203,205,206,207,208};
|
||||
constexpr int colorOptionControls[]{279,280};
|
||||
constexpr int appearanceControls[]{281,282};
|
||||
enum AppearanceSection { Font, DialogFrame };
|
||||
enum AppearanceSection { Font, DialogFrame, SystemThemes };
|
||||
constexpr int terminalScaleSection=1,areaScaleLabel=528,areaScaleControl=529;
|
||||
constexpr int systemLightChoice=531,systemDarkChoice=533;
|
||||
constexpr int systemThemeControls[]{530,systemLightChoice,532,systemDarkChoice,535};
|
||||
constexpr int outerFramePadding=303,innerFramePadding=305,rowTextPadding=307;
|
||||
constexpr int dialogFrameControls[]{302,outerFramePadding,304,innerFramePadding,306,rowTextPadding};
|
||||
constexpr int restoreDocumentsControl=524;
|
||||
constexpr int textTabWidth=357,textLineEnding=359,
|
||||
textTheme=363,textColor=365,textChangeColor=366,textColorValue=367,textSaveScheme=368;
|
||||
textTheme=363,textColor=365,textChangeColor=366,textColorValue=367,textSaveScheme=368,textRenameScheme=534;
|
||||
constexpr int textControls[]{350,351,352,353,356,textTabWidth,
|
||||
362,textTheme,364,textColor,textChangeColor,textColorValue,textSaveScheme};
|
||||
362,textTheme,364,textColor,textChangeColor,textColorValue,textSaveScheme,textRenameScheme};
|
||||
constexpr int editingControls[]{354,355,358,textLineEnding};
|
||||
constexpr int markdownSection=1,markdownWidth=374,markdownFamily=376,markdownChoose=377,markdownSize=379;
|
||||
constexpr int markdownControls[]{373,markdownWidth,375,markdownFamily,markdownChoose,378,markdownSize};
|
||||
@@ -53,7 +57,7 @@ constexpr struct
|
||||
{innerFramePadding,&DialogFramePadding::inner,maxDialogFramePadding},
|
||||
{rowTextPadding,&DialogFramePadding::rowText,maxDialogRowTextPadding}};
|
||||
|
||||
enum class OptionsAnchor { StretchWidth, StretchHeight, BottomRight };
|
||||
enum class OptionsAnchor { StretchWidth, StretchHeight, BottomRight, BottomLeft };
|
||||
struct OptionsControl
|
||||
{
|
||||
int id;
|
||||
@@ -106,7 +110,6 @@ struct OptionsBaseline
|
||||
DialogFramePadding padding=dialogFramePadding;
|
||||
std::array<COLORREF,ColorCount> palette=colors;
|
||||
std::vector<FileStyle> styles=fileStyles;
|
||||
std::array<WORD,2> keys=commandHistoryKeys;
|
||||
bool remoteTerminal=ks::lan::remoteTerminalAllowed();
|
||||
bool remoteHibernate=ks::lan::remoteHibernateAllowed();
|
||||
bool remoteUpdate=ks::lan::remoteUpdateAllowed();
|
||||
@@ -117,7 +120,8 @@ struct OptionsBaseline
|
||||
std::array<PanelMode,2> modes{panels[0].mode,panels[1].mode};
|
||||
ks::files::TextSettings text=ks::files::loadTextPreferences();
|
||||
ComparisonAppearance comparison=readComparisonAppearance();
|
||||
WORD compareShortcut=comparisonShortcut;
|
||||
FilesKeySettings keySettings=filesKeySettings;
|
||||
ks::files::AppearanceScales scales=readAreaScales();
|
||||
};
|
||||
|
||||
struct OptionsDraft
|
||||
@@ -125,6 +129,8 @@ struct OptionsDraft
|
||||
OptionsBaseline baseline;
|
||||
ks::files::TextSettings text=baseline.text;
|
||||
ComparisonAppearance comparison=baseline.comparison;
|
||||
FilesKeySettings keySettings=baseline.keySettings;
|
||||
ks::files::AppearanceScales scales=baseline.scales;
|
||||
HWND filesWindow{};
|
||||
LOGFONTW font=displayFont;
|
||||
int points=fontPoints;
|
||||
@@ -140,13 +146,14 @@ struct OptionsDraft
|
||||
HTREEITEM wideColumnsNode{},markdownNode{};
|
||||
RECT initialClient{};
|
||||
UINT initialDpi=96;
|
||||
OptionsControl controls[8]{
|
||||
OptionsControl controls[10]{
|
||||
{optionsTree,OptionsAnchor::StretchHeight},
|
||||
{optionsTitle,OptionsAnchor::StretchWidth},
|
||||
{275,OptionsAnchor::StretchWidth},{277,OptionsAnchor::StretchWidth},
|
||||
{281,OptionsAnchor::StretchWidth},
|
||||
{IDOK,OptionsAnchor::BottomRight},{IDCANCEL,OptionsAnchor::BottomRight},
|
||||
{optionsApply,OptionsAnchor::BottomRight}};
|
||||
{optionsApply,OptionsAnchor::BottomRight},
|
||||
{optionsImport,OptionsAnchor::BottomLeft},{optionsExport,OptionsAnchor::BottomLeft}};
|
||||
|
||||
};
|
||||
|
||||
@@ -164,19 +171,6 @@ bool optionsFontChanged(const OptionsDraft &draft)
|
||||
_wcsicmp(pending.lfFaceName,applied.lfFaceName)!=0;
|
||||
}
|
||||
|
||||
struct OptionsWriteLock
|
||||
{
|
||||
HANDLE mutex=CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.OptionsWrite");
|
||||
DWORD result=mutex?WaitForSingleObject(mutex,2000):WAIT_FAILED;
|
||||
|
||||
bool acquired() const { return result==WAIT_OBJECT_0 || result==WAIT_ABANDONED; }
|
||||
~OptionsWriteLock()
|
||||
{
|
||||
if(acquired()) ReleaseMutex(mutex);
|
||||
if(mutex) CloseHandle(mutex);
|
||||
}
|
||||
};
|
||||
|
||||
void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
|
||||
{
|
||||
BOOL valid{};
|
||||
@@ -192,11 +186,11 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
|
||||
checked(compactLayoutControl)!=base.compact || checked(restoreDocumentsControl)!=base.restoreLocal ||
|
||||
fields!=base.fields || draft.palette!=base.palette || draft.styles!=base.styles ||
|
||||
draft.framePadding!=base.padding || optionsFontChanged(draft) ||
|
||||
optionHistoryKeys(dialog)!=base.keys || checked(optionsRemoteTerminal)!=base.remoteTerminal ||
|
||||
checked(optionsRemoteTerminal)!=base.remoteTerminal ||
|
||||
checked(optionsRemoteHibernate)!=base.remoteHibernate ||
|
||||
checked(optionsRemoteUpdate)!=base.remoteUpdate ||
|
||||
draft.text!=base.text || draft.comparison!=base.comparison ||
|
||||
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_GETHOTKEY,0,0)!=base.compareShortcut;
|
||||
draft.text!=base.text || draft.comparison!=base.comparison || draft.keySettings!=base.keySettings ||
|
||||
draft.scales!=base.scales;
|
||||
EnableWindow(GetDlgItem(dialog,optionsApply),dirty);
|
||||
InvalidateRect(GetDlgItem(dialog,fileStylePreview),nullptr,FALSE);
|
||||
}
|
||||
@@ -254,6 +248,7 @@ void layoutOptions(HWND dialog,const OptionsDraft &draft)
|
||||
case OptionsAnchor::StretchWidth: width+=dx;break;
|
||||
case OptionsAnchor::StretchHeight: height+=dy;break;
|
||||
case OptionsAnchor::BottomRight: x+=dx;y+=dy;break;
|
||||
case OptionsAnchor::BottomLeft: y+=dy;break;
|
||||
}
|
||||
SetWindowPos(GetDlgItem(dialog,control.id),nullptr,x,y,width,height,
|
||||
SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOREDRAW);
|
||||
@@ -289,19 +284,22 @@ void populateTextSchemes(HWND dialog,const ks::files::TextSettings &settings)
|
||||
};
|
||||
add(L"Custom");
|
||||
for(const auto name:ks::files::textPaletteNames) add(name);
|
||||
add(L"System (Windows)");
|
||||
for(const auto &scheme:settings.schemes) add(scheme.name.c_str());
|
||||
}
|
||||
|
||||
size_t currentTextScheme(const ks::files::TextSettings &settings,const ks::files::TextPreferences &profile)
|
||||
{
|
||||
for(size_t index=0;index<std::size(ks::files::textPalettes);++index)
|
||||
const auto presets=std::size(ks::files::textPalettes);
|
||||
if(profile.scheme==ks::files::systemTextScheme) return presets+1;
|
||||
for(size_t index=0;index<presets;++index)
|
||||
if(profile.scheme==ks::files::textPaletteNames[index] && profile.colors==ks::files::textPalettes[index])
|
||||
return index+1;
|
||||
for(size_t index=0;index<settings.schemes.size();++index)
|
||||
{
|
||||
const auto &scheme=settings.schemes[index];
|
||||
if(profile.scheme==scheme.name && profile.colors==scheme.colors)
|
||||
return std::size(ks::files::textPalettes)+index+1;
|
||||
return presets+index+2;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -312,6 +310,13 @@ INT_PTR CALLBACK schemeNameDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
SendDlgItemMessageW(dialog,100,EM_SETLIMITTEXT,ks::files::maxTextPaletteName,0);
|
||||
const auto &name=*reinterpret_cast<const std::wstring*>(lp);
|
||||
if(!name.empty())
|
||||
{
|
||||
SetWindowTextW(dialog,L"Rename color scheme");
|
||||
SetDlgItemTextW(dialog,100,name.c_str());
|
||||
SetDlgItemTextW(dialog,IDOK,L"Rename");
|
||||
}
|
||||
groupDialogButtons(dialog,{IDOK,IDCANCEL},true);
|
||||
return TRUE;
|
||||
}
|
||||
@@ -329,13 +334,22 @@ INT_PTR CALLBACK schemeNameDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,ks::files::TextPreferences &profile)
|
||||
bool reservedTextSchemeName(const std::wstring &name)
|
||||
{
|
||||
return sameSchemeName(name,L"Custom") || sameSchemeName(name,L"System (Windows)") ||
|
||||
sameSchemeName(name,ks::files::systemTextScheme) ||
|
||||
std::any_of(std::begin(ks::files::textPaletteNames),std::end(ks::files::textPaletteNames),
|
||||
[&](const wchar_t *preset){return sameSchemeName(name,preset);});
|
||||
}
|
||||
|
||||
void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,bool edit)
|
||||
{
|
||||
auto &profile=settings.profiles[edit];
|
||||
const auto palette=ks::files::resolvedTextProfile(settings,edit).colors;
|
||||
std::wstring name;
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(608),dialog,schemeNameDialog,
|
||||
reinterpret_cast<LPARAM>(&name))!=IDOK) return;
|
||||
if(sameSchemeName(name,L"Custom") || std::any_of(std::begin(ks::files::textPaletteNames),
|
||||
std::end(ks::files::textPaletteNames),[&](const wchar_t *preset){return sameSchemeName(name,preset);}))
|
||||
if(reservedTextSchemeName(name))
|
||||
{
|
||||
showFilesNotice(dialog,L"Choose a different name for your color scheme.",L"Save color scheme");
|
||||
return;
|
||||
@@ -346,7 +360,7 @@ void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,ks::files
|
||||
{
|
||||
if(showFilesNotice(dialog,L"Replace the saved scheme with the current colors?",L"Save color scheme",
|
||||
{.confirm=true,.tone=FilesNoticeTone::neutral})!=IDYES) return;
|
||||
existing->colors=profile.colors;
|
||||
existing->colors=palette;
|
||||
profile.scheme=existing->name;
|
||||
}
|
||||
else
|
||||
@@ -356,18 +370,44 @@ void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,ks::files
|
||||
showFilesNotice(dialog,L"The color scheme list is full.",L"Save color scheme");
|
||||
return;
|
||||
}
|
||||
settings.schemes.push_back({name,profile.colors});
|
||||
settings.schemes.push_back({name,palette});
|
||||
profile.scheme=std::move(name);
|
||||
}
|
||||
profile.colors=palette;
|
||||
populateTextSchemes(dialog,settings);
|
||||
}
|
||||
|
||||
void showTextOptions(HWND dialog,const ks::files::TextSettings &settings,const ks::files::TextPreferences &profile)
|
||||
void renameTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,const ks::files::TextPreferences &profile)
|
||||
{
|
||||
const auto scheme=std::ranges::find_if(settings.schemes,[&](const auto &candidate)
|
||||
{ return sameSchemeName(profile.scheme,candidate.name.c_str()); });
|
||||
if(scheme==settings.schemes.end()) return;
|
||||
auto name=scheme->name;
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(608),dialog,schemeNameDialog,
|
||||
reinterpret_cast<LPARAM>(&name))!=IDOK || name==scheme->name) return;
|
||||
if(reservedTextSchemeName(name) || std::ranges::any_of(settings.schemes,[&](const auto &candidate)
|
||||
{return &candidate!=&*scheme && sameSchemeName(name,candidate.name.c_str());}))
|
||||
{
|
||||
showFilesNotice(dialog,L"Choose a unique name for the color scheme.",L"Rename color scheme");
|
||||
return;
|
||||
}
|
||||
for(auto &document:settings.profiles)
|
||||
if(sameSchemeName(document.scheme,scheme->name.c_str())) document.scheme=name;
|
||||
for(auto &role:settings.systemThemes)
|
||||
if(sameSchemeName(role,scheme->name.c_str())) role=name;
|
||||
scheme->name=std::move(name);
|
||||
populateTextSchemes(dialog,settings);
|
||||
}
|
||||
|
||||
void showTextOptions(HWND dialog,const ks::files::TextSettings &settings,bool edit)
|
||||
{
|
||||
const auto profile=ks::files::resolvedTextProfile(settings,edit);
|
||||
for(const auto &check:textChecks) CheckDlgButton(dialog,check.id,profile.*check.value?BST_CHECKED:BST_UNCHECKED);
|
||||
SendDlgItemMessageW(dialog,textTabWidth,CB_SETCURSEL,profile.tabWidth-1,0);
|
||||
SendDlgItemMessageW(dialog,textLineEnding,CB_SETCURSEL,profile.lineEnding,0);
|
||||
SendDlgItemMessageW(dialog,textTheme,CB_SETCURSEL,currentTextScheme(settings,profile),0);
|
||||
const auto selected=currentTextScheme(settings,profile);
|
||||
SendDlgItemMessageW(dialog,textTheme,CB_SETCURSEL,selected,0);
|
||||
EnableWindow(GetDlgItem(dialog,textRenameScheme),selected>=std::size(ks::files::textPalettes)+2);
|
||||
refreshTextColor(dialog,profile);
|
||||
}
|
||||
|
||||
@@ -402,12 +442,20 @@ bool changeTextOption(HWND dialog,OptionsDraft &draft,WPARAM command)
|
||||
if(const auto check=std::find_if(std::begin(textChecks),std::end(textChecks),
|
||||
[id](const auto &entry){return entry.id==id;});check!=std::end(textChecks))
|
||||
profile.*check->value=IsDlgButtonChecked(dialog,id)==BST_CHECKED;
|
||||
else if(id==textSaveScheme) saveTextSchemeDraft(dialog,draft.text,profile);
|
||||
else if(id==textSaveScheme) saveTextSchemeDraft(dialog,draft.text,draft.page==TextEditor);
|
||||
else if(id==textRenameScheme) renameTextSchemeDraft(dialog,draft.text,profile);
|
||||
else if(id==textChangeColor)
|
||||
{
|
||||
const auto index=row(textColor);
|
||||
if(index>=0 && static_cast<size_t>(index)<profile.colors.size())
|
||||
choosePanelColor(dialog,profile.colors[index],draft.custom.data());
|
||||
{
|
||||
auto palette=ks::files::resolvedTextProfile(draft.text,draft.page==TextEditor).colors;
|
||||
if(choosePanelColor(dialog,palette[index],draft.custom.data()))
|
||||
{
|
||||
profile.colors=palette;
|
||||
profile.scheme.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
else if(HIWORD(command)==CBN_SELCHANGE)
|
||||
{
|
||||
@@ -419,15 +467,20 @@ bool changeTextOption(HWND dialog,OptionsDraft &draft,WPARAM command)
|
||||
case textTabWidth: profile.tabWidth=static_cast<int>(selected)+1; break;
|
||||
case textLineEnding: profile.lineEnding=static_cast<int>(selected); break;
|
||||
case textTheme:
|
||||
if(selected==0) profile.scheme.clear();
|
||||
if(selected==0)
|
||||
{
|
||||
profile.colors=ks::files::resolvedTextProfile(draft.text,draft.page==TextEditor).colors;
|
||||
profile.scheme.clear();
|
||||
}
|
||||
else if(const auto scheme=static_cast<size_t>(selected-1);scheme<std::size(ks::files::textPalettes))
|
||||
{
|
||||
profile.scheme=ks::files::textPaletteNames[scheme];
|
||||
profile.colors=ks::files::textPalettes[scheme];
|
||||
}
|
||||
else if(scheme==std::size(ks::files::textPalettes)) profile.scheme=ks::files::systemTextScheme;
|
||||
else
|
||||
{
|
||||
const auto index=scheme-std::size(ks::files::textPalettes);
|
||||
const auto index=scheme-std::size(ks::files::textPalettes)-1;
|
||||
if(index>=draft.text.schemes.size()) return false;
|
||||
profile.scheme=draft.text.schemes[index].name;
|
||||
profile.colors=draft.text.schemes[index].colors;
|
||||
@@ -437,7 +490,7 @@ bool changeTextOption(HWND dialog,OptionsDraft &draft,WPARAM command)
|
||||
}
|
||||
}
|
||||
else return false;
|
||||
showTextOptions(dialog,draft.text,profile);
|
||||
showTextOptions(dialog,draft.text,draft.page==TextEditor);
|
||||
updateOptionsApply(dialog,draft);
|
||||
return true;
|
||||
}
|
||||
@@ -456,6 +509,65 @@ void showComparisonOptions(HWND dialog,const ComparisonAppearance &appearance)
|
||||
SetDlgItemTextW(dialog,comparisonColorValue,hex);
|
||||
}
|
||||
|
||||
std::optional<AppearanceArea> optionsScaleArea(int page,int section)
|
||||
{
|
||||
if(page==Appearance && section==Font) return AppearanceArea::panels;
|
||||
if(page==CommandLine && section==terminalScaleSection) return AppearanceArea::terminal;
|
||||
if(page==TextViewer) return section==markdownSection?AppearanceArea::markdown:AppearanceArea::viewer;
|
||||
if(page==TextEditor) return AppearanceArea::editor;
|
||||
if(page==CompareFiles) return AppearanceArea::comparison;
|
||||
return {};
|
||||
}
|
||||
|
||||
void showAreaScale(HWND dialog,const OptionsDraft &draft,std::optional<AppearanceArea> area)
|
||||
{
|
||||
const auto label=GetDlgItem(dialog,areaScaleLabel);
|
||||
const auto field=GetDlgItem(dialog,areaScaleControl);
|
||||
ShowWindow(label,area?SW_SHOW:SW_HIDE);
|
||||
ShowWindow(field,area?SW_SHOW:SW_HIDE);
|
||||
if(!area) return;
|
||||
const auto index=ks::files::appearanceIndex(*area);
|
||||
constexpr const wchar_t *labels[]{L"&Panel scale",L"&Viewer scale",L"&Editor scale",L"&Markdown scale",
|
||||
L"&Terminal scale",L"&Comparison scale"};
|
||||
constexpr int top[]{77,232,232,124,29,155};
|
||||
SetWindowTextW(label,labels[index]);
|
||||
RECT labelBox{131,top[index]+3,0,0},fieldBox{257,top[index],0,0};
|
||||
MapDialogRect(dialog,&labelBox);
|
||||
MapDialogRect(dialog,&fieldBox);
|
||||
const auto flags=SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE;
|
||||
SetWindowPos(label,nullptr,labelBox.left,labelBox.top,0,0,flags);
|
||||
SetWindowPos(field,nullptr,fieldBox.left,fieldBox.top,0,0,flags);
|
||||
SendMessageW(field,CB_RESETCONTENT,0,0);
|
||||
const auto selected=draft.scales[index];
|
||||
for(unsigned percent=ks::files::minAppearanceScale;percent<=ks::files::maxAppearanceScale;++percent)
|
||||
{
|
||||
if(percent%5 && percent!=selected) continue;
|
||||
const auto caption=std::to_wstring(percent)+L"%";
|
||||
const auto row=SendMessageW(field,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(caption.c_str()));
|
||||
if(row<0) continue;
|
||||
SendMessageW(field,CB_SETITEMDATA,row,percent);
|
||||
if(percent==selected) SendMessageW(field,CB_SETCURSEL,row,0);
|
||||
}
|
||||
}
|
||||
|
||||
void showSystemThemeRoles(HWND dialog,const ks::files::TextSettings &settings)
|
||||
{
|
||||
constexpr int controls[]{systemLightChoice,systemDarkChoice};
|
||||
for(size_t role=0;role<std::size(controls);++role)
|
||||
{
|
||||
const auto control=GetDlgItem(dialog,controls[role]);
|
||||
SendMessageW(control,CB_RESETCONTENT,0,0);
|
||||
const auto add=[&](const wchar_t *name)
|
||||
{
|
||||
const auto row=SendMessageW(control,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name));
|
||||
if(row>=0 && sameSchemeName(settings.systemThemes[role],name))
|
||||
SendMessageW(control,CB_SETCURSEL,row,0);
|
||||
};
|
||||
for(const auto name:ks::files::textPaletteNames) add(name);
|
||||
for(const auto &scheme:settings.schemes) add(scheme.name.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
|
||||
{
|
||||
draft.page=page;
|
||||
@@ -470,7 +582,8 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
|
||||
else if(section>=0 && !textOptionsPage(page) && page!=CompareFiles)
|
||||
title=page==PanelModes?panelSectionNames[section]:page==PanelColors?
|
||||
(section==fileStyleSection?L"File type styles":colorNames[section]):
|
||||
page==CommandLine?L"Command history":section==DialogFrame?L"Dialog frame":L"Font";
|
||||
page==CommandLine?(section==terminalScaleSection?L"Terminal appearance":L"Command history"):
|
||||
section==SystemThemes?L"System themes":section==DialogFrame?L"Dialog frame":L"Font";
|
||||
}
|
||||
SetDlgItemTextW(dialog,optionsTitle,title);
|
||||
const auto show=[&](auto &controls,bool visible)
|
||||
@@ -498,6 +611,9 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
|
||||
show(wideColumnControls,page==PanelModes && section==WideColumns);
|
||||
show(statusColumnControls,page==PanelModes && section==StatusColumns);
|
||||
show(appearanceControls,page==Appearance && section==Font);
|
||||
show(systemThemeControls,page==Appearance && section==SystemThemes);
|
||||
if(page==Appearance && section==SystemThemes) showSystemThemeRoles(dialog,draft.text);
|
||||
showAreaScale(dialog,draft,optionsScaleArea(page,section));
|
||||
show(comparisonControls,page==CompareFiles);
|
||||
if(page==CompareFiles) showComparisonOptions(dialog,draft.comparison);
|
||||
show(dialogFrameControls,page==Appearance && section==DialogFrame);
|
||||
@@ -506,18 +622,19 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
|
||||
for(const auto &option:frameOptions)
|
||||
SendDlgItemMessageW(dialog,option.id,CB_SETCURSEL,draft.framePadding.*option.value,0);
|
||||
}
|
||||
constexpr int commandLineControls[]{320,321,322,323,optionsRemoteTerminal,optionsRemoteHibernate,optionsRemoteUpdate};
|
||||
constexpr int commandLineControls[]{321,optionsRemoteTerminal,optionsRemoteHibernate,optionsRemoteUpdate};
|
||||
show(commandLineControls,page==CommandLine && section==0);
|
||||
show(markdownControls,markdown);
|
||||
show(textControls,textOptionsPage(page) && !markdown);
|
||||
ShowWindow(GetDlgItem(dialog,restoreDocumentsControl),page==TextViewer && !markdown?SW_SHOW:SW_HIDE);
|
||||
show(editingControls,page==TextEditor);
|
||||
if(textOptionsPage(page) && !markdown) showTextOptions(dialog,draft.text,draft.text.profiles[page==TextEditor]);
|
||||
if(textOptionsPage(page) && !markdown) showTextOptions(dialog,draft.text,page==TextEditor);
|
||||
const bool fileTypes=page==PanelColors && section==fileStyleSection;
|
||||
constexpr int fileStyleControls[]{287,288,289,290,291,292,293,294,295,296,297,298,300,fileStyleState};
|
||||
show(fileStyleControls,fileTypes);
|
||||
const auto preview=GetDlgItem(dialog,fileStylePreview);
|
||||
ShowWindow(preview,page>=0 && page<CommandLine && section>=0?SW_SHOW:SW_HIDE);
|
||||
const bool panelPreview=page>=0 && page<CommandLine && section>=0 && !(page==Appearance && section==SystemThemes);
|
||||
ShowWindow(preview,panelPreview?SW_SHOW:SW_HIDE);
|
||||
layoutOptionsPreview(dialog);
|
||||
RedrawWindow(dialog,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN);
|
||||
show(colorOptionControls,page==PanelColors && section>=0 && !fileTypes);
|
||||
@@ -610,16 +727,21 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
|
||||
addSection(L"File type styles",fileStyleSection,extensionMatches || matches(L"System and hidden") ||
|
||||
matches(L"Underline") || matches(L"Strikethrough") || matches(L"Foreground"));
|
||||
}
|
||||
else if(page==CommandLine) addSection(L"Command history",0,
|
||||
matches(L"Previous command") || matches(L"Allow paired PCs to run PowerShell commands here") ||
|
||||
matches(L"Allow paired PCs to hibernate this PC") || matches(L"Allow paired PCs to update KSwitcher here"));
|
||||
else if(page==CommandLine)
|
||||
{
|
||||
addSection(L"Command history",0,matches(L"Previous command") || matches(L"Keyboard shortcuts") ||
|
||||
matches(L"Allow paired PCs to run PowerShell commands here") || matches(L"Allow paired PCs to hibernate this PC") ||
|
||||
matches(L"Allow paired PCs to update KSwitcher here"));
|
||||
addSection(L"Terminal appearance",terminalScaleSection,matches(L"Terminal scale"));
|
||||
}
|
||||
else if(page==CompareFiles)
|
||||
addSection(L"Font and colors",0,matches(L"Compare files shortcut") || std::any_of(std::begin(comparisonColorNames),
|
||||
addSection(L"Font and colors",0,matches(L"Comparison scale") || matches(L"Compare files shortcut") || matches(L"Keyboard shortcuts") || std::any_of(std::begin(comparisonColorNames),
|
||||
std::end(comparisonColorNames),matches));
|
||||
else if(textOptionsPage(page))
|
||||
{
|
||||
const bool propertyMatches=matches(L"Tab width") ||
|
||||
matches(L"Color scheme") || matches(L"Save scheme") || matches(L"Customize colors") ||
|
||||
matches(L"Color scheme") || matches(L"Save scheme") || matches(L"Rename scheme") || matches(L"Customize colors") ||
|
||||
matches(page==TextEditor?L"Editor scale":L"Viewer scale") ||
|
||||
(page==TextEditor && matches(L"Line endings for new lines")) ||
|
||||
(page==TextViewer && matches(L"Restore local Viewer and Editor windows after restart")) ||
|
||||
std::any_of(std::begin(textChecks),std::end(textChecks),[&](const auto &check)
|
||||
@@ -627,11 +749,13 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
|
||||
std::any_of(std::begin(ks::files::textColorNames),std::end(ks::files::textColorNames),matches);
|
||||
addSection(page==TextEditor?L"Editing and appearance":L"Viewing and appearance",0,propertyMatches);
|
||||
if(page==TextViewer) addSection(L"Markdown",markdownSection,
|
||||
matches(L"Maximum width") || matches(L"Full window") || matches(L"Font family") || matches(L"Font size"));
|
||||
matches(L"Maximum width") || matches(L"Full window") || matches(L"Font family") || matches(L"Font size") ||
|
||||
matches(L"Markdown scale"));
|
||||
}
|
||||
else
|
||||
{
|
||||
addSection(L"Font",Font,matches(L"Display font"));
|
||||
addSection(L"Font",Font,matches(L"Display font") || matches(L"Panel scale"));
|
||||
addSection(L"System themes",SystemThemes,matches(L"Light mode palette") || matches(L"Dark mode palette"));
|
||||
addSection(L"Dialog frame",DialogFrame,
|
||||
matches(L"Outer padding") || matches(L"Inner padding") || matches(L"Row text padding"));
|
||||
}
|
||||
@@ -642,6 +766,8 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
|
||||
if(!first) SetDlgItemTextW(dialog,optionsTitle,L"No matching settings");
|
||||
}
|
||||
|
||||
#include "files_options_transfer.inl"
|
||||
|
||||
INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
@@ -672,8 +798,6 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
for(const auto label:comparisonColorNames)
|
||||
SendDlgItemMessageW(dialog,comparisonColorCombo,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label));
|
||||
SendDlgItemMessageW(dialog,comparisonColorCombo,CB_SETCURSEL,0,0);
|
||||
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETRULES,HKCOMB_NONE,HOTKEYF_SHIFT);
|
||||
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETHOTKEY,comparisonShortcut,0);
|
||||
SendDlgItemMessageW(dialog,optionsSearch,EM_SETLIMITTEXT,255,0);
|
||||
for(const auto &option:frameOptions)
|
||||
for(DWORD value=0;value<=option.maximum;++value)
|
||||
@@ -696,7 +820,6 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
CheckDlgButton(dialog,restoreDocumentsControl,restoreDocuments);
|
||||
showPanelModeOptions(dialog);
|
||||
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
|
||||
setOptionHistoryKeys(dialog,commandHistoryKeys);
|
||||
CheckDlgButton(dialog,optionsRemoteTerminal,ks::lan::remoteTerminalAllowed());
|
||||
CheckDlgButton(dialog,optionsRemoteHibernate,ks::lan::remoteHibernateAllowed());
|
||||
CheckDlgButton(dialog,optionsRemoteUpdate,ks::lan::remoteUpdateAllowed());
|
||||
@@ -754,6 +877,29 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
case optionsSearch:
|
||||
if(HIWORD(wp)==EN_CHANGE) filterOptions(dialog,*draft);
|
||||
return TRUE;
|
||||
case areaScaleControl:
|
||||
if(HIWORD(wp)==CBN_SELCHANGE)
|
||||
if(const auto area=optionsScaleArea(draft->page,draft->section))
|
||||
{
|
||||
const auto row=SendDlgItemMessageW(dialog,areaScaleControl,CB_GETCURSEL,0,0);
|
||||
if(row>=0)
|
||||
{
|
||||
const auto percent=SendDlgItemMessageW(dialog,areaScaleControl,CB_GETITEMDATA,row,0);
|
||||
if(percent>=ks::files::minAppearanceScale && percent<=ks::files::maxAppearanceScale)
|
||||
draft->scales[ks::files::appearanceIndex(*area)]=static_cast<unsigned>(percent);
|
||||
}
|
||||
updateOptionsApply(dialog,*draft);
|
||||
}
|
||||
return TRUE;
|
||||
case systemLightChoice: case systemDarkChoice:
|
||||
if(HIWORD(wp)==CBN_SELCHANGE)
|
||||
{
|
||||
wchar_t name[ks::files::maxTextPaletteName+1]{};
|
||||
GetDlgItemTextW(dialog,LOWORD(wp),name,std::size(name));
|
||||
if(ks::files::namedTextPalette(draft->text,name)) draft->text.systemThemes[LOWORD(wp)==systemDarkChoice]=name;
|
||||
updateOptionsApply(dialog,*draft);
|
||||
}
|
||||
return TRUE;
|
||||
case 279:
|
||||
if(draft->page==PanelColors && draft->section>=0 && draft->section<ColorCount)
|
||||
{
|
||||
@@ -861,14 +1007,15 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
return TRUE;
|
||||
case optionsReset:
|
||||
if(draft->page==allOptions) draft->scales=ks::files::defaultAppearanceScales;
|
||||
else if(const auto area=optionsScaleArea(draft->page,draft->section))
|
||||
draft->scales[ks::files::appearanceIndex(*area)]=100;
|
||||
if(draft->page==allOptions || (draft->page==Appearance && (draft->section<0 || draft->section==SystemThemes)))
|
||||
draft->text.systemThemes=ks::files::TextSettings{}.systemThemes;
|
||||
if(draft->page==allOptions || draft->page==CompareFiles)
|
||||
{
|
||||
draft->comparison=ComparisonAppearance{};
|
||||
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETHOTKEY,defaultComparisonShortcut,0);
|
||||
}
|
||||
if(draft->page==allOptions || draft->page==CommandLine)
|
||||
{
|
||||
setOptionHistoryKeys(dialog,defaultHistoryKeys);
|
||||
CheckDlgButton(dialog,optionsRemoteTerminal,BST_UNCHECKED);
|
||||
CheckDlgButton(dialog,optionsRemoteHibernate,BST_UNCHECKED);
|
||||
CheckDlgButton(dialog,optionsRemoteUpdate,BST_UNCHECKED);
|
||||
@@ -883,12 +1030,12 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
if(draft->page==allOptions || (draft->page==PanelColors &&
|
||||
(draft->section<0 || draft->section==fileStyleSection)))
|
||||
draft->styles=defaultFileStyles;
|
||||
if(draft->page==allOptions || (draft->page==Appearance && draft->section!=DialogFrame))
|
||||
if(draft->page==allOptions || (draft->page==Appearance && (draft->section<0 || draft->section==Font)))
|
||||
{
|
||||
draft->font=defaultFilesFont();
|
||||
draft->points=defaultFontPoints;
|
||||
}
|
||||
if(draft->page==allOptions || (draft->page==Appearance && draft->section!=Font))
|
||||
if(draft->page==allOptions || (draft->page==Appearance && (draft->section<0 || draft->section==DialogFrame)))
|
||||
draft->framePadding=defaultDialogFramePadding;
|
||||
if(draft->page==allOptions || (draft->page==TextViewer && draft->section!=markdownSection))
|
||||
CheckDlgButton(dialog,restoreDocumentsControl,BST_UNCHECKED);
|
||||
@@ -920,22 +1067,16 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
case optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate:
|
||||
updateOptionsApply(dialog,*draft);
|
||||
return TRUE;
|
||||
case 321: case 323: case comparisonShortcutControl:
|
||||
case 321: case comparisonKeySchemesButton:
|
||||
editFilesKeySchemes(dialog,LOWORD(wp)==321?FilesKey::Previous:FilesKey::Compare,&draft->keySettings);
|
||||
updateOptionsApply(dialog,*draft);
|
||||
return TRUE;
|
||||
case optionsImport: case optionsExport:
|
||||
transferFilesOptions(dialog,*draft,LOWORD(wp)==optionsImport);
|
||||
return TRUE;
|
||||
case optionsApply:
|
||||
case IDOK:
|
||||
{
|
||||
const auto compareShortcut=static_cast<WORD>(
|
||||
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_GETHOTKEY,0,0));
|
||||
if(!validComparisonShortcut(compareShortcut))
|
||||
{
|
||||
showFilesNotice(dialog,L"Choose Shift or Ctrl+Shift with a function key. Shift+F4 and Shift+F8 are reserved.",
|
||||
optionsTitles[CompareFiles]);
|
||||
if(IsWindowVisible(GetDlgItem(dialog,comparisonShortcutControl)))
|
||||
SetFocus(GetDlgItem(dialog,comparisonShortcutControl));
|
||||
return TRUE;
|
||||
}
|
||||
if(draft->markdownError)
|
||||
{
|
||||
if(!draft->markdownNode) SetDlgItemTextW(dialog,optionsSearch,L"");
|
||||
@@ -963,6 +1104,14 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
return TRUE;
|
||||
}
|
||||
const auto &base=draft->baseline;
|
||||
const bool keysChanged=draft->keySettings!=base.keySettings;
|
||||
loadFilesKeySettings();
|
||||
if(keysChanged && filesKeySettings!=base.keySettings && filesKeySettings!=draft->keySettings)
|
||||
{
|
||||
showFilesNotice(dialog,L"Keyboard schemes changed in another window. Reopen Options before editing them again.",
|
||||
L"Keyboard shortcuts");
|
||||
return TRUE;
|
||||
}
|
||||
const auto storedComparison=readComparisonAppearance();
|
||||
const bool comparisonChanged=draft->comparison!=base.comparison;
|
||||
if(comparisonChanged && storedComparison!=base.comparison && storedComparison!=draft->comparison)
|
||||
@@ -972,7 +1121,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
return TRUE;
|
||||
}
|
||||
const bool textChanged=draft->text!=base.text;
|
||||
auto textSettings=ks::files::loadTextPreferences();
|
||||
const auto storedText=ks::files::loadTextPreferences();
|
||||
auto textSettings=storedText;
|
||||
if(draft->text.markdown!=base.text.markdown)
|
||||
{
|
||||
if(textSettings.markdown!=base.text.markdown && textSettings.markdown!=draft->text.markdown)
|
||||
@@ -1004,14 +1154,15 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
textSettings.schemes=draft->text.schemes;
|
||||
}
|
||||
auto keys=optionHistoryKeys(dialog);
|
||||
loadCommandHistoryKeys();
|
||||
for(size_t i=0;i<keys.size();++i)
|
||||
if(keys[i]==base.keys[i]) keys[i]=commandHistoryKeys[i];
|
||||
if(!validHistoryKeys(keys))
|
||||
if(draft->text.systemThemes!=base.text.systemThemes)
|
||||
{
|
||||
showFilesNotice(dialog,L"Choose distinct shortcuts using Ctrl or Alt that are free in Files.",L"Command history");
|
||||
return TRUE;
|
||||
if(textSettings.systemThemes!=base.text.systemThemes && textSettings.systemThemes!=draft->text.systemThemes)
|
||||
{
|
||||
showFilesNotice(dialog,L"System theme choices changed in another window. Reopen Options before editing them again.",
|
||||
L"System themes");
|
||||
return TRUE;
|
||||
}
|
||||
textSettings.systemThemes=draft->text.systemThemes;
|
||||
}
|
||||
const bool stylesChanged=draft->styles!=base.styles;
|
||||
loadFileStyles();
|
||||
@@ -1053,15 +1204,22 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
if(keysChanged && !writeFilesJsonPreference(filesKeySchemePreference,serializeFilesKeySettings(draft->keySettings)))
|
||||
{
|
||||
if(textChanged)
|
||||
try {ks::files::saveTextPreferences(storedText);}
|
||||
catch(const std::exception &) {setStatus(L"Could not restore earlier text settings.",true);}
|
||||
if(comparisonChanged) saveComparisonAppearance(storedComparison);
|
||||
if(fontChanged) applyFont(owner,base.font,base.points);
|
||||
if(stylesChanged) saveFileStyles(fileStyles);
|
||||
showFilesNotice(dialog,L"Could not save the keyboard schemes.",L"Keyboard shortcuts");
|
||||
return TRUE;
|
||||
}
|
||||
const auto saveChanged=[](const wchar_t *name,DWORD value,DWORD initial)
|
||||
{
|
||||
if(value!=initial) savePreference(name,value);
|
||||
};
|
||||
const auto checked=[&](int id){return IsDlgButtonChecked(dialog,id)==BST_CHECKED;};
|
||||
const auto inputKeys=optionHistoryKeys(dialog);
|
||||
saveChanged(L"PreviousCommandKey",inputKeys[0],base.keys[0]);
|
||||
saveChanged(L"CommandHistoryKey",inputKeys[1],base.keys[1]);
|
||||
saveChanged(comparisonShortcutKey,compareShortcut,base.compareShortcut);
|
||||
saveChanged(ks::lan::remoteTerminalPreference,checked(optionsRemoteTerminal),base.remoteTerminal);
|
||||
saveChanged(ks::lan::remoteHibernatePreference,checked(optionsRemoteHibernate),base.remoteHibernate);
|
||||
saveChanged(ks::lan::remoteUpdatePreference,checked(optionsRemoteUpdate),base.remoteUpdate);
|
||||
@@ -1086,6 +1244,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
saveChanged(dialogFrameOuterKey,draft->framePadding.outer,base.padding.outer);
|
||||
saveChanged(dialogFrameInnerKey,draft->framePadding.inner,base.padding.inner);
|
||||
saveChanged(dialogRowTextKey,draft->framePadding.rowText,base.padding.rowText);
|
||||
for(size_t i=0;i<draft->scales.size();++i) saveChanged(areaScaleKeys[i],draft->scales[i],base.scales[i]);
|
||||
if(fontChanged)
|
||||
{
|
||||
savePreference(L"FontPoints",fontPoints);
|
||||
@@ -1097,6 +1256,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
if(mode!=base.modes[index]) savePanelMode(index,mode);
|
||||
}
|
||||
loadFilesPreferences(owner);
|
||||
refreshFilesKeyBar();
|
||||
notifyFilesPreferences(owner);
|
||||
const auto dialogOwner=GetWindow(dialog,GW_OWNER);
|
||||
if(dialogOwner!=owner)
|
||||
@@ -1104,6 +1264,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
draft->baseline=OptionsBaseline{};
|
||||
draft->text=draft->baseline.text;
|
||||
draft->comparison=draft->baseline.comparison;
|
||||
draft->keySettings=draft->baseline.keySettings;
|
||||
draft->scales=draft->baseline.scales;
|
||||
showMarkdownOptions(dialog,draft->text.markdown);
|
||||
populateTextSchemes(dialog,draft->text);
|
||||
draft->font=displayFont;
|
||||
@@ -1121,8 +1283,6 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
CheckDlgButton(dialog,restoreDocumentsControl,restoreDocuments);
|
||||
showPanelModeOptions(dialog);
|
||||
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
|
||||
setOptionHistoryKeys(dialog,commandHistoryKeys);
|
||||
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETHOTKEY,comparisonShortcut,0);
|
||||
CheckDlgButton(dialog,optionsRemoteTerminal,ks::lan::remoteTerminalAllowed());
|
||||
CheckDlgButton(dialog,optionsRemoteHibernate,ks::lan::remoteHibernateAllowed());
|
||||
CheckDlgButton(dialog,optionsRemoteUpdate,ks::lan::remoteUpdateAllowed());
|
||||
@@ -1140,12 +1300,13 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
void runOptions(HWND owner,int page)
|
||||
void runOptions(HWND owner,int page,int section=0,bool restoreLocation=true)
|
||||
{
|
||||
loadFilesKeySettings();
|
||||
OptionsDraft draft;
|
||||
draft.filesWindow=GetAncestor(owner,GA_ROOTOWNER);
|
||||
const DWORD initial=static_cast<DWORD>((page<<8)|1);
|
||||
const auto saved=preference(optionsLocationKey,initial);
|
||||
const DWORD initial=static_cast<DWORD>((page<<8)|(section+1));
|
||||
const auto saved=restoreLocation?preference(optionsLocationKey,initial):initial;
|
||||
draft.location=(saved>>8)<=CompareFiles?saved:initial;
|
||||
draft.page=static_cast<int>(draft.location>>8);
|
||||
draft.section=static_cast<int>(draft.location&255)-1;
|
||||
@@ -1162,7 +1323,10 @@ void editOptions(HWND owner)
|
||||
SetFocus(panels[active].list);
|
||||
}
|
||||
|
||||
void editTextOptions(HWND owner,bool edit)
|
||||
void editFilesAppearance(HWND owner,AppearanceArea area)
|
||||
{
|
||||
runOptions(owner,edit?TextEditor:TextViewer);
|
||||
constexpr int pages[]{Appearance,TextViewer,TextEditor,TextViewer,CommandLine,CompareFiles};
|
||||
constexpr int sections[]{Font,0,0,markdownSection,terminalScaleSection,0};
|
||||
const auto index=ks::files::appearanceIndex(area);
|
||||
runOptions(owner,pages[index],sections[index],false);
|
||||
}
|
||||
@@ -7,7 +7,8 @@ void paintOptionsPreview(HWND dialog,const DRAWITEMSTRUCT &item,const OptionsDra
|
||||
const auto dpi=GetDpiForWindow(item.hwndItem);
|
||||
const auto px=[&](int value){return MulDiv(value,dpi,96);};
|
||||
auto font=draft.font;
|
||||
font.lfHeight=-MulDiv(draft.points,dpi,720);
|
||||
const auto panelScale=draft.scales[ks::files::appearanceIndex(AppearanceArea::panels)];
|
||||
font.lfHeight=-MulDiv(ks::files::scaledAppearanceSize(draft.points,panelScale),dpi,720);
|
||||
font.lfWidth=0;
|
||||
const auto previewFont=CreateFontIndirectW(&font);
|
||||
SelectObject(dc,previewFont?previewFont:mono);
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
constexpr struct
|
||||
{
|
||||
const char *id;
|
||||
const wchar_t *label;
|
||||
int control;
|
||||
} filesTransferGroups[]{
|
||||
{"colors",L"&Colors and file styles",621},
|
||||
{"panels",L"&Panel modes and layout",622},
|
||||
{"keys",L"&Keyboard schemes",623},
|
||||
};
|
||||
|
||||
constexpr struct
|
||||
{
|
||||
const char *id;
|
||||
int control;
|
||||
bool OptionsBaseline::*value;
|
||||
} transferablePanelChecks[]{
|
||||
{"alignFileExtensions",202,&OptionsBaseline::extensions},
|
||||
{"alignFolderExtensions",204,&OptionsBaseline::folders},
|
||||
{"showDetails",203,&OptionsBaseline::details},
|
||||
{"rightClickMarks",rightClickMarksControl,&OptionsBaseline::mouseMarks},
|
||||
{"driveButtons",driveButtonsControl,&OptionsBaseline::drives},
|
||||
{"compactLayout",compactLayoutControl,&OptionsBaseline::compact},
|
||||
};
|
||||
|
||||
struct FilesTransferDraft
|
||||
{
|
||||
bool importing{};
|
||||
Json groups=Json::object();
|
||||
std::array<bool,std::size(filesTransferGroups)> chosen{};
|
||||
};
|
||||
|
||||
INT_PTR CALLBACK filesTransferDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
auto &draft=*reinterpret_cast<FilesTransferDraft*>(lp);
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
SetWindowTextW(dialog,draft.importing?L"Import Files settings":L"Export Files settings");
|
||||
SetDlgItemTextW(dialog,624,draft.importing?
|
||||
L"Choose groups to load into Options. Apply saves the changes.":
|
||||
L"Choose groups to export from your saved Files settings.");
|
||||
SetDlgItemTextW(dialog,IDOK,draft.importing?L"&Load":L"&Export");
|
||||
for(const auto &group:filesTransferGroups)
|
||||
{
|
||||
const bool available=draft.groups.contains(group.id);
|
||||
const auto control=GetDlgItem(dialog,group.control);
|
||||
SetWindowTextW(control,group.label);
|
||||
ShowWindow(control,available?SW_SHOW:SW_HIDE);
|
||||
CheckDlgButton(dialog,group.control,available?BST_CHECKED:BST_UNCHECKED);
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
if(message!=WM_COMMAND) return FALSE;
|
||||
auto &draft=*reinterpret_cast<FilesTransferDraft*>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
for(size_t i=0;i<draft.chosen.size();++i)
|
||||
{
|
||||
const auto &group=filesTransferGroups[i];
|
||||
draft.chosen[i]=draft.groups.contains(group.id) && IsDlgButtonChecked(dialog,group.control)==BST_CHECKED;
|
||||
}
|
||||
const bool any=std::ranges::any_of(draft.chosen,[](bool chosen){return chosen;});
|
||||
if(LOWORD(wp)==IDOK && any) FilesModalDialog::finish(dialog,IDOK);
|
||||
else EnableWindow(GetDlgItem(dialog,IDOK),any);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
fs::path chooseFilesTransferPath(HWND owner,bool importing)
|
||||
{
|
||||
std::array<wchar_t,32768> file{};
|
||||
if(!importing) wcscpy_s(file.data(),file.size(),L"KSwitcher.Files.settings.json");
|
||||
OPENFILENAMEW pick{sizeof(pick)};
|
||||
pick.hwndOwner=owner;
|
||||
pick.lpstrTitle=importing?L"Open Files settings JSON":L"Save Files settings JSON";
|
||||
pick.lpstrFilter=L"JSON files (*.json)\0*.json\0All files (*.*)\0*.*\0";
|
||||
pick.lpstrFile=file.data();
|
||||
pick.nMaxFile=static_cast<DWORD>(file.size());
|
||||
pick.lpstrDefExt=L"json";
|
||||
pick.Flags=OFN_EXPLORER|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST|
|
||||
(importing?OFN_FILEMUSTEXIST:OFN_OVERWRITEPROMPT);
|
||||
if(importing?GetOpenFileNameW(&pick):GetSaveFileNameW(&pick)) return file.data();
|
||||
if(CommDlgExtendedError()) throw std::runtime_error("Could not open the file picker.");
|
||||
return {};
|
||||
}
|
||||
|
||||
Json exportFilesOptionGroups(const OptionsBaseline &saved)
|
||||
{
|
||||
Json colors{{"panels",saved.palette},{"comparison",saved.comparison.palette},{"fileStyles",serializeFileStyles(saved.styles)}};
|
||||
Json panels{{"leftMode",static_cast<DWORD>(saved.modes[0])},
|
||||
{"rightMode",static_cast<DWORD>(saved.modes[1])},{"sizeWidth",saved.width},{"statusFields",saved.fields}};
|
||||
for(const auto &check:transferablePanelChecks) panels[check.id]=saved.*check.value;
|
||||
return {{"colors",std::move(colors)},{"panels",std::move(panels)},{"keys",serializeFilesKeySettings(saved.keySettings)}};
|
||||
}
|
||||
|
||||
template<typename Palette>
|
||||
void importFilesColors(const Json &value,Palette &palette)
|
||||
{
|
||||
if(!value.is_array()) throw std::runtime_error("Expected an array of colors.");
|
||||
for(size_t i=0;i<std::min(value.size(),palette.size());++i)
|
||||
{
|
||||
if(!value[i].is_number_unsigned() || value[i]>0xffffff)
|
||||
throw std::runtime_error("A color is outside the RGB range.");
|
||||
palette[i]=value[i].template get<COLORREF>();
|
||||
}
|
||||
}
|
||||
|
||||
DWORD importFilesOptionNumber(const Json &value,DWORD minimum,DWORD maximum)
|
||||
{
|
||||
if(!value.is_number_unsigned() || value<minimum || value>maximum)
|
||||
throw std::runtime_error("A panel setting is outside its supported range.");
|
||||
return value.get<DWORD>();
|
||||
}
|
||||
|
||||
std::optional<FilesKeySettings> mergeImportedFilesKeySchemes(HWND owner,const FilesKeySettings &local,const Json &value)
|
||||
{
|
||||
const auto imported=parseFilesKeySettings(value);
|
||||
if(!imported) throw std::runtime_error("The keyboard schemes contain invalid or conflicting bindings.");
|
||||
auto result=local;
|
||||
size_t replacements{};
|
||||
for(size_t i=0;i<imported->schemes.size();++i)
|
||||
{
|
||||
const auto &scheme=imported->schemes[i];
|
||||
const auto existing=std::ranges::find_if(result.schemes,[&](const auto &candidate)
|
||||
{ return sameFilesKeySchemeName(candidate.name,scheme.name); });
|
||||
const auto position=static_cast<size_t>(existing-result.schemes.begin());
|
||||
if(i==imported->active) result.active=position;
|
||||
if(existing==result.schemes.end()) result.schemes.push_back(scheme);
|
||||
else if(existing->keys!=scheme.keys)
|
||||
{
|
||||
++replacements;
|
||||
auto name=existing->name;
|
||||
*existing=scheme;
|
||||
existing->name=std::move(name);
|
||||
}
|
||||
}
|
||||
if(result.schemes.size()>filesKeySchemeLimit)
|
||||
throw std::runtime_error("The imported keyboard schemes exceed the number Files can store.");
|
||||
if(replacements)
|
||||
{
|
||||
const auto prompt=L"Replace "+std::to_wstring(replacements)+
|
||||
(replacements==1?L" keyboard scheme with the same name?":L" keyboard schemes with the same names?");
|
||||
if(showFilesNotice(owner,prompt.c_str(),L"Import Files settings",
|
||||
{.confirm=true,.accept=L"&Replace"})!=IDYES) return {};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void stageImportedFilesOptions(HWND dialog,OptionsDraft &draft,const Json &groups)
|
||||
{
|
||||
auto palette=draft.palette;
|
||||
auto comparison=draft.comparison.palette;
|
||||
auto styles=draft.styles;
|
||||
auto options=OptionsBaseline{};
|
||||
options.modes={panelModeOption(dialog,0),panelModeOption(dialog,1)};
|
||||
options.width=GetDlgItemInt(dialog,201,nullptr,FALSE);
|
||||
options.fields=0;
|
||||
for(int i=0;i<4;++i)
|
||||
if(IsDlgButtonChecked(dialog,205+i)==BST_CHECKED) options.fields|=1u<<i;
|
||||
for(const auto &check:transferablePanelChecks)
|
||||
options.*check.value=IsDlgButtonChecked(dialog,check.control)==BST_CHECKED;
|
||||
|
||||
const auto colorGroup=groups.find("colors");
|
||||
if(colorGroup!=groups.end())
|
||||
{
|
||||
if(!colorGroup->is_object()) throw std::runtime_error("Invalid colors group.");
|
||||
if(colorGroup->contains("panels")) importFilesColors(colorGroup->at("panels"),palette);
|
||||
if(colorGroup->contains("comparison")) importFilesColors(colorGroup->at("comparison"),comparison);
|
||||
if(colorGroup->contains("fileStyles"))
|
||||
{
|
||||
auto parsed=parseFileStyles(colorGroup->at("fileStyles"));
|
||||
if(!parsed) throw std::runtime_error("Invalid file styles.");
|
||||
styles=std::move(*parsed);
|
||||
}
|
||||
}
|
||||
const auto panelGroup=groups.find("panels");
|
||||
if(panelGroup!=groups.end())
|
||||
{
|
||||
if(!panelGroup->is_object()) throw std::runtime_error("Invalid panel modes and layout group.");
|
||||
for(const auto &check:transferablePanelChecks)
|
||||
if(panelGroup->contains(check.id)) options.*check.value=panelGroup->at(check.id).get<bool>();
|
||||
constexpr const char *modeKeys[]{"leftMode","rightMode"};
|
||||
for(size_t i=0;i<options.modes.size();++i)
|
||||
if(panelGroup->contains(modeKeys[i]))
|
||||
options.modes[i]=static_cast<PanelMode>(importFilesOptionNumber(
|
||||
panelGroup->at(modeKeys[i]),0,std::size(panelModeNames)-1));
|
||||
if(panelGroup->contains("sizeWidth"))
|
||||
options.width=importFilesOptionNumber(panelGroup->at("sizeWidth"),6,16);
|
||||
if(panelGroup->contains("statusFields"))
|
||||
options.fields=importFilesOptionNumber(panelGroup->at("statusFields"),0,15);
|
||||
}
|
||||
if(groups.contains("keys"))
|
||||
{
|
||||
auto keys=mergeImportedFilesKeySchemes(dialog,draft.keySettings,groups.at("keys"));
|
||||
if(!keys) return;
|
||||
draft.keySettings=std::move(*keys);
|
||||
}
|
||||
if(colorGroup!=groups.end())
|
||||
{
|
||||
draft.palette=palette;
|
||||
draft.comparison.palette=comparison;
|
||||
draft.styles=std::move(styles);
|
||||
}
|
||||
if(panelGroup!=groups.end())
|
||||
{
|
||||
if(panelGroup->contains("sizeWidth")) SetDlgItemInt(dialog,201,options.width,FALSE);
|
||||
for(int index=0;index<2;++index)
|
||||
SendDlgItemMessageW(dialog,273+index,CB_SETCURSEL,static_cast<WPARAM>(options.modes[index]),0);
|
||||
for(const auto &check:transferablePanelChecks)
|
||||
CheckDlgButton(dialog,check.control,options.*check.value?BST_CHECKED:BST_UNCHECKED);
|
||||
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,options.fields&(1u<<i)?BST_CHECKED:BST_UNCHECKED);
|
||||
}
|
||||
if(draft.page==PanelColors && draft.section==fileStyleSection) updateFileStyleEditor(dialog,draft,true);
|
||||
showOptionsPage(dialog,draft,draft.page,draft.section);
|
||||
updateOptionsApply(dialog,draft);
|
||||
}
|
||||
|
||||
void transferFilesOptions(HWND dialog,OptionsDraft &options,bool importing)
|
||||
{
|
||||
try
|
||||
{
|
||||
FilesTransferDraft transfer{.importing=importing};
|
||||
if(importing)
|
||||
{
|
||||
const auto path=chooseFilesTransferPath(dialog,true);
|
||||
if(path.empty()) return;
|
||||
const auto data=ks::readFile(path,maxFilesJsonBytes);
|
||||
const auto document=Json::parse(data,[](int depth,Json::parse_event_t,Json &)
|
||||
{
|
||||
if(depth>32) throw std::runtime_error("The JSON contains too many nested levels.");
|
||||
return true;
|
||||
});
|
||||
if(document.value("format",std::string{})!="kswitcher-files-settings" || document.at("version")!=1)
|
||||
throw std::runtime_error("This Files settings format or version is unsupported.");
|
||||
const auto &groups=document.at("groups");
|
||||
if(!groups.is_object()) throw std::runtime_error("The document does not contain settings groups.");
|
||||
for(const auto &group:filesTransferGroups)
|
||||
if(groups.contains(group.id)) transfer.groups[group.id]=groups.at(group.id);
|
||||
if(transfer.groups.empty()) throw std::runtime_error("The file does not contain any supported settings groups.");
|
||||
}
|
||||
else transfer.groups=exportFilesOptionGroups(options.baseline);
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(617),dialog,filesTransferDialog,
|
||||
reinterpret_cast<LPARAM>(&transfer))!=IDOK) return;
|
||||
for(size_t i=0;i<transfer.chosen.size();++i)
|
||||
if(!transfer.chosen[i]) transfer.groups.erase(filesTransferGroups[i].id);
|
||||
if(importing) stageImportedFilesOptions(dialog,options,transfer.groups);
|
||||
else
|
||||
{
|
||||
const auto path=chooseFilesTransferPath(dialog,false);
|
||||
if(path.empty()) return;
|
||||
const auto output=Json{{"format","kswitcher-files-settings"},{"version",1},
|
||||
{"groups",std::move(transfer.groups)}}.dump(2)+"\n";
|
||||
const auto temporary=ks::files::temporaryPath(path.parent_path());
|
||||
const bool replace=GetFileAttributesW(path.c_str())!=INVALID_FILE_ATTRIBUTES;
|
||||
ks::atomicWrite(temporary,ks::Bytes(output.begin(),output.end()));
|
||||
if(!MoveFileExW(temporary.c_str(),path.c_str(),MOVEFILE_WRITE_THROUGH|(replace?MOVEFILE_REPLACE_EXISTING:0)))
|
||||
{
|
||||
DeleteFileW(temporary.c_str());
|
||||
throw std::runtime_error("Could not publish the settings file.");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(const Json::exception &)
|
||||
{
|
||||
showFilesNotice(dialog,L"The JSON is damaged or contains an invalid value.",L"Files settings");
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
const auto message=ks::wide(error.what());
|
||||
showFilesNotice(dialog,message.c_str(),L"Files settings");
|
||||
}
|
||||
}
|
||||
+31
-34
@@ -48,60 +48,54 @@ bool sameFileExtension(std::wstring_view left,std::wstring_view right)
|
||||
right.data(),static_cast<int>(right.size()),TRUE)==CSTR_EQUAL;
|
||||
}
|
||||
|
||||
void loadFileStyles()
|
||||
std::optional<std::vector<FileStyle>> parseFileStyles(const Json &rows)
|
||||
{
|
||||
DWORD bytes{};
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,fileStyleKey,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS ||
|
||||
!bytes || bytes>256*1024) return;
|
||||
std::string data(bytes,'\0');
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,fileStyleKey,RRF_RT_REG_BINARY,nullptr,data.data(),&bytes)!=ERROR_SUCCESS)
|
||||
return;
|
||||
try
|
||||
{
|
||||
const auto rows=Json::parse(data.begin(),data.begin()+bytes);
|
||||
if(!rows.is_array() || rows.size()>64) return;
|
||||
if(!rows.is_array() || rows.size()>64) return {};
|
||||
std::vector<FileStyle> parsed;
|
||||
for(const auto &row:rows)
|
||||
{
|
||||
FileStyle style{ks::wide(row.at("extension").get<std::string>())};
|
||||
if(style.extension!=L"@system-hidden" && fileStyleExtension(style.extension)!=style.extension) return;
|
||||
if(std::any_of(parsed.begin(),parsed.end(),[&](const auto &existing){return existing.extension==style.extension;}))
|
||||
return;
|
||||
const auto color=[&](const char *key)->std::optional<COLORREF>
|
||||
if(style.extension!=L"@system-hidden" && fileStyleExtension(style.extension)!=style.extension) return {};
|
||||
if(std::ranges::any_of(parsed,[&](const auto &existing){return existing.extension==style.extension;}))
|
||||
return {};
|
||||
const auto color=[](const Json &entry,const char *key)->std::optional<COLORREF>
|
||||
{
|
||||
if(!row.contains(key)) return {};
|
||||
const auto value=row.at(key).get<DWORD>();
|
||||
if(value>0xffffff) throw std::runtime_error("Invalid file style color");
|
||||
return value;
|
||||
if(!entry.contains(key)) return {};
|
||||
const auto &value=entry.at(key);
|
||||
if(!value.is_number_unsigned() || value>0xffffff) throw std::runtime_error("Invalid file style color");
|
||||
return value.get<DWORD>();
|
||||
};
|
||||
style.foreground=color("foreground");
|
||||
style.background=color("background");
|
||||
style.foreground=color(row,"foreground");
|
||||
style.background=color(row,"background");
|
||||
style.underline=row.value("underline",false);
|
||||
style.strikeout=row.value("strikeout",false);
|
||||
if(row.contains("states"))
|
||||
{
|
||||
const auto &states=row.at("states");
|
||||
if(!states.is_array() || states.size()!=style.states.size()) return;
|
||||
if(!states.is_array() || states.size()!=style.states.size()) return {};
|
||||
for(size_t i=0;i<style.states.size();++i)
|
||||
{
|
||||
const auto read=[&](const char *key)->std::optional<COLORREF>
|
||||
{
|
||||
if(!states[i].contains(key)) return {};
|
||||
const auto value=states[i].at(key).get<DWORD>();
|
||||
if(value>0xffffff) throw std::runtime_error("Invalid state color");
|
||||
return value;
|
||||
};
|
||||
style.states[i]={read("foreground"),read("background")};
|
||||
if(!states[i].is_object()) return {};
|
||||
style.states[i]={color(states[i],"foreground"),color(states[i],"background")};
|
||||
}
|
||||
}
|
||||
parsed.push_back(std::move(style));
|
||||
}
|
||||
fileStyles=std::move(parsed);
|
||||
return parsed;
|
||||
}
|
||||
catch(const std::exception &) {}
|
||||
catch(const std::exception &) {return {};}
|
||||
}
|
||||
|
||||
bool saveFileStyles(const std::vector<FileStyle> &styles)
|
||||
void loadFileStyles()
|
||||
{
|
||||
fileStyles=defaultFileStyles;
|
||||
if(const auto rows=readFilesJsonPreference(fileStyleKey))
|
||||
if(auto parsed=parseFileStyles(*rows)) fileStyles=std::move(*parsed);
|
||||
}
|
||||
|
||||
Json serializeFileStyles(const std::vector<FileStyle> &styles)
|
||||
{
|
||||
auto rows=Json::array();
|
||||
for(const auto &style:styles)
|
||||
@@ -119,9 +113,12 @@ bool saveFileStyles(const std::vector<FileStyle> &styles)
|
||||
}
|
||||
rows.push_back(std::move(row));
|
||||
}
|
||||
const auto data=rows.dump();
|
||||
return RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,fileStyleKey,REG_BINARY,data.data(),
|
||||
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
|
||||
return rows;
|
||||
}
|
||||
|
||||
bool saveFileStyles(const std::vector<FileStyle> &styles)
|
||||
{
|
||||
return writeFilesJsonPreference(fileStyleKey,serializeFileStyles(styles));
|
||||
}
|
||||
|
||||
struct FileRowStyle
|
||||
|
||||
@@ -2,12 +2,15 @@
|
||||
|
||||
#include <windows.h>
|
||||
#include <array>
|
||||
#include <optional>
|
||||
#include <string_view>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
inline constexpr size_t documentColorCount = 10;
|
||||
inline constexpr wchar_t systemTextScheme[]=L"@system";
|
||||
using TextPalette = std::array<COLORREF, 14>;
|
||||
inline constexpr const wchar_t *textPaletteNames[] = {L"FAR (blue)", L"Dark", L"Light"};
|
||||
inline constexpr TextPalette textPalettes[] = {
|
||||
@@ -56,8 +59,11 @@ struct TextSettings
|
||||
TextPreferencesSet profiles;
|
||||
std::vector<NamedTextPalette> schemes;
|
||||
MarkdownPreferences markdown;
|
||||
std::array<std::wstring,2> systemThemes{textPaletteNames[2],textPaletteNames[1]};
|
||||
bool operator==(const TextSettings &) const = default;
|
||||
};
|
||||
std::optional<TextPalette> namedTextPalette(const TextSettings &settings,std::wstring_view name);
|
||||
TextPreferences resolvedTextProfile(const TextSettings &settings,bool editor);
|
||||
TextSettings loadTextPreferences();
|
||||
void saveTextPreferences(const TextSettings &settings);
|
||||
}
|
||||
+79
-11
@@ -1,4 +1,5 @@
|
||||
#include "files_text_window.h"
|
||||
#include "files_help.h"
|
||||
#include "files_image_view.h"
|
||||
#include "files_text_preferences.h"
|
||||
#include "files_menu_paint.h"
|
||||
@@ -73,6 +74,30 @@ void readTextProfile(TextPreferences &prefs, const nlohmann::json &data)
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<TextPalette> namedTextPalette(const TextSettings &settings,std::wstring_view name)
|
||||
{
|
||||
const auto matches=[&](const wchar_t *other)
|
||||
{
|
||||
return !name.empty() && CompareStringOrdinal(name.data(),static_cast<int>(name.size()),other,-1,TRUE)==CSTR_EQUAL;
|
||||
};
|
||||
for(size_t i=0;i<std::size(textPalettes);++i)
|
||||
if(matches(textPaletteNames[i])) return textPalettes[i];
|
||||
for(const auto &scheme:settings.schemes)
|
||||
if(matches(scheme.name.c_str())) return scheme.colors;
|
||||
return {};
|
||||
}
|
||||
|
||||
TextPreferences resolvedTextProfile(const TextSettings &settings,bool editor)
|
||||
{
|
||||
auto profile=settings.profiles[editor];
|
||||
if(profile.scheme==systemTextScheme)
|
||||
{
|
||||
const bool dark=windowsUsesDarkApps();
|
||||
profile.colors=namedTextPalette(settings,settings.systemThemes[dark]).value_or(textPalettes[dark?1:2]);
|
||||
}
|
||||
return profile;
|
||||
}
|
||||
|
||||
TextSettings loadTextPreferences()
|
||||
{
|
||||
TextSettings settings{};
|
||||
@@ -109,6 +134,17 @@ TextSettings loadTextPreferences()
|
||||
}
|
||||
catch (const std::exception &) {}
|
||||
}
|
||||
if(const auto system=data.find("systemThemes");system!=data.end() && system->is_object())
|
||||
{
|
||||
constexpr const char *roles[]{"light","dark"};
|
||||
for(size_t i=0;i<settings.systemThemes.size();++i)
|
||||
if(const auto name=system->find(roles[i]);name!=system->end() && name->is_string())
|
||||
{
|
||||
auto value=wide(name->get<std::string>());
|
||||
if(value.size()<=maxTextPaletteName && namedTextPalette(settings,value))
|
||||
settings.systemThemes[i]=std::move(value);
|
||||
}
|
||||
}
|
||||
return settings;
|
||||
}
|
||||
const wchar_t *legacy[]{L"files-viewer.json", L"files-editor.json"};
|
||||
@@ -140,6 +176,7 @@ void saveTextPreferences(const TextSettings &settings)
|
||||
schemes.push_back({{"name", utf8(scheme.name)}, {"colors", scheme.colors}});
|
||||
data["markdown"]={{"width",settings.markdown.width},{"fontSize",settings.markdown.fontSize},
|
||||
{"font",utf8(settings.markdown.font)}};
|
||||
data["systemThemes"]={{"light",utf8(settings.systemThemes[0])},{"dark",utf8(settings.systemThemes[1])}};
|
||||
const auto json = data.dump(2);
|
||||
atomicWrite(dataDirectory() / L"files-text.json", Bytes(json.begin(), json.end()));
|
||||
}
|
||||
@@ -683,6 +720,19 @@ std::future<std::unique_ptr<RemoteTextFile>> fetchRemoteText(const RemoteTextSou
|
||||
return result;
|
||||
}
|
||||
|
||||
unsigned textAreaScale(TextDialogs dialogs,AppearanceArea area)
|
||||
{
|
||||
return dialogs.readScale?dialogs.readScale(area):100;
|
||||
}
|
||||
|
||||
TextWindowFont scaledDocumentFont(TextDialogs dialogs,bool editor)
|
||||
{
|
||||
auto font=dialogs.readFont();
|
||||
font.tenthsOfPoint=scaledAppearanceSize(font.tenthsOfPoint,
|
||||
textAreaScale(dialogs,editor?AppearanceArea::editor:AppearanceArea::viewer));
|
||||
return font;
|
||||
}
|
||||
|
||||
class TextWindow;
|
||||
std::map<HWND,std::shared_ptr<TextWindow>> textWindows;
|
||||
std::vector<HWND> textWindowOrder;
|
||||
@@ -771,7 +821,7 @@ public:
|
||||
: original(std::move(path)), peerId(backend?backend->id:""), filename(original.filename().wstring()),
|
||||
edit(editable), draft(options.draft), embedded(quickView), hex(options.hex && !editable),
|
||||
initialBookmark(options.line),
|
||||
prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
|
||||
prefs(resolvedTextProfile(loadTextPreferences(),editable)), filesFont(scaledDocumentFont(dialogs,editable)),
|
||||
search{dialogs}, previewFragment(fragment)
|
||||
{
|
||||
if (backend) remote=std::make_unique<RemoteTextFile>(*backend,original);
|
||||
@@ -808,6 +858,10 @@ public:
|
||||
bool openBookmark(const ViewerBookmark &bookmark);
|
||||
nlohmann::json sessionState() const;
|
||||
void restoreSession(const nlohmann::json &state);
|
||||
AppearanceArea appearanceArea() const
|
||||
{
|
||||
return previewWanted?AppearanceArea::markdown:edit?AppearanceArea::editor:AppearanceArea::viewer;
|
||||
}
|
||||
std::filesystem::path original;
|
||||
const std::string peerId;
|
||||
|
||||
@@ -1318,8 +1372,8 @@ void TextWindow::reloadPreferences()
|
||||
pendingPreferences = false;
|
||||
auto settings = loadTextPreferences();
|
||||
applyMarkdownPreferences(settings.markdown);
|
||||
auto &profile = settings.profiles[edit];
|
||||
const auto font = search.style.readFont();
|
||||
auto profile=resolvedTextProfile(settings,edit);
|
||||
const auto font=scaledDocumentFont(search.style,edit);
|
||||
const bool fontChanged = font.tenthsOfPoint != filesFont.tenthsOfPoint ||
|
||||
std::memcmp(&font.font, &filesFont.font, sizeof(LOGFONTW)) != 0;
|
||||
if (!fontChanged && profile == prefs) return;
|
||||
@@ -2060,7 +2114,8 @@ void TextWindow::showTextMode(const ViewerPosition &position,std::string content
|
||||
{
|
||||
rememberLocalVersion();
|
||||
if(canPreview()) ShowWindow(editor,SW_HIDE);
|
||||
prefs = loadTextPreferences().profiles[edit];
|
||||
prefs=resolvedTextProfile(loadTextPreferences(),edit);
|
||||
filesFont=scaledDocumentFont(search.style,edit);
|
||||
releaseMenu();
|
||||
createMenu();
|
||||
installLexer();
|
||||
@@ -2216,6 +2271,11 @@ bool TextWindow::startPreviewBrowser()
|
||||
{
|
||||
const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0;
|
||||
const bool alt=(GetKeyState(VK_MENU)&0x8000)!=0;
|
||||
if(key==VK_F1 && !ctrl && !alt && !((GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000))
|
||||
{
|
||||
PostMessageW(window,filesHelpRequest,0,0);
|
||||
return true;
|
||||
}
|
||||
if(embedded)
|
||||
{
|
||||
if(!ctrl && !alt && !(GetKeyState(VK_SHIFT)&0x8000) && key==VK_F6 && quickKind==QuickKind::html)
|
||||
@@ -2366,8 +2426,9 @@ void TextWindow::renderPreview(bool keepPosition)
|
||||
void TextWindow::applyMarkdownPreferences(const MarkdownPreferences &preferences)
|
||||
{
|
||||
if(!preview.initialized()) return;
|
||||
const auto scale=textAreaScale(search.style,AppearanceArea::markdown);
|
||||
preview.post(wide(nlohmann::json{{"action","appearance"},{"width",preferences.width},
|
||||
{"fontSize",preferences.fontSize},{"font",utf8(preferences.font)}}.dump()));
|
||||
{"fontSize",preferences.fontSize*scale/100.0},{"font",utf8(preferences.font)}}.dump()));
|
||||
}
|
||||
|
||||
void TextWindow::refreshPreview()
|
||||
@@ -2992,7 +3053,7 @@ void TextWindow::command(UINT id)
|
||||
case lexerAuto: language = automatic; installLexer(); return;
|
||||
case lexerPlain: language = {}; installLexer(); return;
|
||||
case options:
|
||||
search.style.options(window, edit);
|
||||
search.style.options(window,appearanceArea());
|
||||
SetFocus(editor);
|
||||
return;
|
||||
default:
|
||||
@@ -3125,7 +3186,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
const auto self=found->second;
|
||||
try
|
||||
{
|
||||
if (message == preferencesChanged)
|
||||
if(message==preferencesChanged || windowsAppThemeChanged(message,lparam))
|
||||
{
|
||||
self->reloadPreferences();
|
||||
return 0;
|
||||
@@ -3505,16 +3566,23 @@ void previewQuickViewFile(HWND window,const std::filesystem::path &path)
|
||||
preview->second->previewFile(path);
|
||||
}
|
||||
|
||||
std::optional<AppearanceArea> textWindowAppearanceArea(HWND window)
|
||||
{
|
||||
const auto entry=textWindows.find(window);
|
||||
if(entry==textWindows.end()) return {};
|
||||
return entry->second->appearanceArea();
|
||||
}
|
||||
|
||||
void previewQuickViewText(HWND window,const std::wstring &title,std::string_view contents,bool diff)
|
||||
{
|
||||
if(const auto preview=textWindows.find(window);preview!=textWindows.end())
|
||||
preview->second->previewEmbeddedText(title,contents,diff);
|
||||
}
|
||||
|
||||
ImageViewStyle imageViewStyle(TextDialogs dialogs)
|
||||
ImageViewStyle imageViewStyle(TextDialogs dialogs,bool edit=false)
|
||||
{
|
||||
const auto font=dialogs.readFont();
|
||||
const auto colors=loadTextPreferences().profiles[0].colors;
|
||||
const auto font=scaledDocumentFont(dialogs,edit);
|
||||
const auto colors=resolvedTextProfile(loadTextPreferences(),edit).colors;
|
||||
return {font.font,font.tenthsOfPoint,colors[0],colors[1],colors[2],colors[3],colors[4]};
|
||||
}
|
||||
|
||||
@@ -3560,7 +3628,7 @@ void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const
|
||||
}
|
||||
}
|
||||
if(!textWindows.contains(owner)) filesOwner=owner;
|
||||
const auto window=createImageView(owner,false,imageViewStyle(dialogs),std::move(images),path,std::move(load),
|
||||
const auto window=createImageView(owner,false,imageViewStyle(dialogs,editor!=nullptr),std::move(images),path,std::move(load),
|
||||
[](HWND closed) {
|
||||
std::erase(textWindowOrder,closed);
|
||||
quitWhenFilesWindowsClose();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include "files_appearance.h"
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
@@ -48,7 +49,7 @@ struct TextDialogs
|
||||
INT_PTR (*paint)(HWND, UINT, WPARAM, LPARAM, const wchar_t *);
|
||||
INT_PTR (*paintSearch)(HWND, UINT, WPARAM, LPARAM);
|
||||
void (*prepare)(HWND);
|
||||
void (*options)(HWND, bool);
|
||||
void (*options)(HWND, AppearanceArea);
|
||||
void (*message)(HWND, const wchar_t *);
|
||||
TextWindowFont (*readFont)();
|
||||
FarDropDownPalette (*dropDownPalette)();
|
||||
@@ -58,6 +59,7 @@ struct TextDialogs
|
||||
bool (*confirmExisting)(HWND);
|
||||
bool (*saveOptions)(HWND,std::filesystem::path &,TextSaveFormat &);
|
||||
bool (*reloadChanged)(HWND){};
|
||||
unsigned (*readScale)(AppearanceArea){};
|
||||
};
|
||||
|
||||
struct TextOpenOptions
|
||||
@@ -128,4 +130,5 @@ void textWindowOwnerClosed();
|
||||
void standaloneFilesWindowOpened();
|
||||
void standaloneFilesWindowClosed();
|
||||
bool cycleTextWindows(HWND current,bool reverse);
|
||||
std::optional<AppearanceArea> textWindowAppearanceArea(HWND window);
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user