Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5bca97f864 | ||
|
|
0d714147ea | ||
|
|
a0aeb62270 | ||
|
|
4be9b24c4b | ||
|
|
9c30dd91b4 | ||
|
|
5ba51ebb00 |
No files matched your search
+1
-1
@@ -1,5 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.24)
|
||||
project(KSwitcher VERSION 0.6.114 LANGUAGES CXX RC)
|
||||
project(KSwitcher VERSION 0.6.116 LANGUAGES CXX RC)
|
||||
if(NOT WIN32)
|
||||
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
|
||||
endif()
|
||||
|
||||
+18
-4
@@ -37,6 +37,10 @@ Warning і початковий фокус на No.
|
||||
окремим процесом. BAT і CMD виконуються в поточній сесії вбудованого
|
||||
термінала, а їхній вивід з’являється під панелями. Щоб відкрити файл із
|
||||
панелі LAN, спочатку скопіюй його до локальної папки.
|
||||
Після успішного відкриття локального файла через Windows його шлях
|
||||
з’являється у виводі термінала й списку історії. Коли термінал неактивний,
|
||||
його курсор приховано. При виборі
|
||||
з історії у командний рядок підставляється команда, яка повторює відкриття.
|
||||
- Коли командний рядок порожній, Shift+Enter відкриває поточний локальний
|
||||
елемент через Windows.
|
||||
Папка відкривається у Провіднику, файл виконує свою стандартну дію Windows.
|
||||
@@ -136,10 +140,15 @@ Warning і початковий фокус на No.
|
||||
лише до шляхів із пробілами. Для `..` вставляється шлях батьківської папки.
|
||||
- Ctrl+Enter вставляє лише назву файла або папки під курсором активної панелі
|
||||
за тими ж правилами вставлення й лапок. Рядок `..` пропускається.
|
||||
- Локальні й LAN-каталоги скануються у фоновому потоці. Під час переходу
|
||||
активна панель показує «Loading folder…» і зберігає попередній список до
|
||||
завершення сканування. Після переходу оновлюються шлях і список цієї панелі
|
||||
та командний рядок. Сусідня панель не перемальовується через цей перехід.
|
||||
- Локальні й LAN-каталоги скануються у фоновому потоці. Рядок стану активної
|
||||
панелі показує «Reading» з лічильником прочитаних файлів і папок та
|
||||
підказкою [Esc].
|
||||
До завершення читання панель зберігає попередній список. Escape зупиняє
|
||||
сканування активної панелі й відкриває прочитану частину папки. Якщо
|
||||
папку ще не вдалося відкрити, попередній список залишається. Ctrl+R
|
||||
повторює сканування, щоб отримати повний список. Після переходу
|
||||
оновлюються шлях і список цієї панелі та командний рядок. Сусідня
|
||||
панель не перемальовується через цей перехід.
|
||||
Якщо надійшов новіший запит, результат попереднього
|
||||
сканування пропускається. Після підтвердження UAC очікування списку
|
||||
від підвищеного процесу теж відбувається у фоні.
|
||||
@@ -222,6 +231,11 @@ Warning і початковий фокус на No.
|
||||
- Ctrl+Tab циклічно перемикає фокус між Files, редакторами й переглядачами
|
||||
у порядку їх відкриття. Ctrl+Shift+Tab обходить ті самі вікна у зворотному
|
||||
порядку. Коли відкрито лише Files, активна панель не змінюється.
|
||||
- Shift+F4 у локальній панелі відкриває Editor для наявного або нового файла.
|
||||
Порожнє ім’я підставляє `New_File_<дата>_<час>.txt`. Новий файл з’являється
|
||||
на диску після збереження. Esc після змін пропонує Save, Discard або Cancel.
|
||||
Save для нового файла відкриває параметри імені, кодування, BOM та кінців
|
||||
рядків. Скасування параметрів залишає текст у редакторі.
|
||||
- F3 відкриває Markdown як форматований документ із таблицями, блоками коду,
|
||||
інтерактивними чекбоксами списків і діаграмами Mermaid. Відмітки в перегляді
|
||||
діють до повторного рендерингу або виходу з цього режиму. F4 відкриває текст
|
||||
|
||||
@@ -999,8 +999,7 @@ Keep `v0.4.2` as the last legacy `vX.Y.Z` release. Publish full packages as
|
||||
`release-vX.Y.Z` (stable, not prerelease), including `release-files.json`,
|
||||
`KSwitcher-win-x64.zip` and `SHA256SUMS.txt`. Never publish a manifest package under a
|
||||
legacy version tag: clients that have not installed the bridge would select it.
|
||||
Keep the compatibility bridge in the first 100 releases returned by Gitea while
|
||||
supporting old clients; their immutable update code only reads that page.
|
||||
Legacy clients only read the first 100 releases returned by Gitea. The bridge is now outside that page. For v0.3.x–v0.4.1, follow the manual bridge installation instructions above.
|
||||
|
||||
### Editors that omit copied trailing spaces
|
||||
|
||||
|
||||
+23
-1
@@ -1,5 +1,27 @@
|
||||
# Latest Windows release
|
||||
|
||||
## v0.6.116 — 2026-11-17
|
||||
|
||||
- Files displays a live count while reading a folder. **Esc** stops the scan and shows the entries already read. **Ctrl+R** reads the folder again. Mouse selection works beyond the first 65,536 rows.
|
||||
- Files shows the path of files opened through Windows in the terminal and command history. Choosing a history entry still inserts the command that reopens the file. The embedded terminal hides its inactive cursor.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- Files показує лічильник під час читання папки. **Esc** зупиняє читання й показує вже прочитані записи. **Ctrl+R** перечитує папку. Вибір мишею працює після перших 65 536 рядків.
|
||||
- Files показує шлях до файла, відкритого через Windows, у терміналі й історії команд. Вибір запису історії підставляє команду для повторного відкриття. Вбудований термінал приховує курсор, коли він неактивний.
|
||||
|
||||
## v0.6.115 — 2026-11-17
|
||||
|
||||
- **Shift+F4** opens or creates a file in the active local panel. Leave the name blank for a generated `New_File_…txt` name. After editing a draft, **Esc → Save** opens options for the file name, encoding, BOM, and line endings.
|
||||
- Typing updates the editor status line without repainting the menu or flashing the editor window.
|
||||
- When **Enter** opens a local file through Windows, Files displays `start 'path'` in the terminal and saves it in command history.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- **Shift+F4** відкриває або створює файл в активній локальній панелі. Якщо залишити ім’я порожнім, Files підставить `New_File_…txt`. Після редагування чернетки **Esc → Save** відкриває параметри імені, кодування, BOM і кінців рядків.
|
||||
- Під час набору редактор оновлює рядок стану без перемальовування меню й миготіння вікна.
|
||||
- Коли **Enter** відкриває локальний файл через Windows, Files показує `start 'шлях'` у терміналі й додає команду до історії.
|
||||
|
||||
## v0.6.114 — 2026-11-17
|
||||
|
||||
In KSwitcher Files, clicking a row in the inactive pane highlights that row immediately. The previous cursor row in that pane no longer flashes with the active highlight. If it had a custom unfocused cursor color, it returns directly to its normal style.
|
||||
@@ -476,7 +498,7 @@ Use **Test mouse buttons here** to check which events Windows delivers. Mouse pr
|
||||
|
||||
## Upgrade
|
||||
|
||||
Choose **Update** in the tray menu. Legacy v0.3.0–v0.4.1 clients first receive the v0.4.2 compatibility bridge, then the current full release. v0.2.3 and earlier require manual installation.
|
||||
Choose **Update** in the tray menu. For v0.3.x–v0.4.1, install the [v0.4.2 bridge](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/releases/tag/v0.4.2) manually first. Close KSwitcher and its editors, extract the bridge ZIP into the installation folder while keeping personal data, dictionaries, and tools, then start v0.4.2 and choose **Update**. v0.2.3 and earlier require manual installation.
|
||||
|
||||
For a manual upgrade, exit KSwitcher and its configurator and screenshot editors, then extract the entire **KSwitcher-win-x64.zip** into its installation folder. Verify it with **SHA256SUMS.txt**. Keep personal data, customized dictionaries and tools. Keep the three KSwitcher executables together.
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
aa2c63e1362b22669100eae8bc529fa1f67c41ed822141ad936e8e8661f9c5d1 KSwitcher-win-x64.zip
|
||||
5a885ca54c703dd82a5ce82b6fdbe919337f30ca08daeb6c8958f7e36832aef2 KSwitcher-win-x64.zip
|
||||
+74
-74
@@ -1,166 +1,166 @@
|
||||
{
|
||||
"version": "0.6.114",
|
||||
"schema": 1,
|
||||
"version": "0.6.116",
|
||||
"files": [
|
||||
{
|
||||
"size": 2479104,
|
||||
"sha256": "79b803b43141d62f6a5022fc9dce7fddcbff97e30e71850d309da5cecfa22d26",
|
||||
"path": "KSwitcher.exe"
|
||||
"path": "KSwitcher.exe",
|
||||
"sha256": "b7c7f60c0a1e598359f3bd3775fca67fa2eaf9ebcc41f96da0034b3a92687863",
|
||||
"size": 2479104
|
||||
},
|
||||
{
|
||||
"size": 2458112,
|
||||
"sha256": "67c1a3071a10b49f9ff13c0ada484c3882e97bd955512c471cddec991ae7da3e",
|
||||
"path": "KSwitcher.Config.exe"
|
||||
"path": "KSwitcher.Config.exe",
|
||||
"sha256": "96a956ab0498269244371355b1549cc89e29d5d9175e36e39d8bef8ab53f6a5f",
|
||||
"size": 2458112
|
||||
},
|
||||
{
|
||||
"size": 3060224,
|
||||
"sha256": "b1607b2192b591cd4d7f553a9a69d015f68a1d69882f1cdccf312c93574186aa",
|
||||
"path": "KSwitcher.Screenshot.exe"
|
||||
"path": "KSwitcher.Screenshot.exe",
|
||||
"sha256": "d001683200e1d86caaf96e8c37f004ab2717f8acaad8c172350581792026540d",
|
||||
"size": 3060224
|
||||
},
|
||||
{
|
||||
"size": 4217344,
|
||||
"sha256": "20c4488abc0ae2e21441a5934ae860f83ab66561bbe4066079706046fa1b0fa2",
|
||||
"path": "KSwitcher.Files.exe"
|
||||
"path": "KSwitcher.Files.exe",
|
||||
"sha256": "cc1bea0d8d7aafe23e7a3be72177123963c7b3d250be93840850953a2aa547a6",
|
||||
"size": 4232704
|
||||
},
|
||||
{
|
||||
"size": 194912,
|
||||
"path": "WebView2Loader.dll",
|
||||
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
|
||||
"path": "WebView2Loader.dll"
|
||||
"size": 194912
|
||||
},
|
||||
{
|
||||
"size": 1103,
|
||||
"path": "terminal/addon-fit-LICENSE.txt",
|
||||
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
|
||||
"path": "terminal/addon-fit-LICENSE.txt"
|
||||
"size": 1103
|
||||
},
|
||||
{
|
||||
"size": 1521,
|
||||
"path": "terminal/addon-fit.js",
|
||||
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
|
||||
"path": "terminal/addon-fit.js"
|
||||
"size": 1521
|
||||
},
|
||||
{
|
||||
"size": 527,
|
||||
"path": "terminal/index.html",
|
||||
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
|
||||
"path": "terminal/index.html"
|
||||
"size": 527
|
||||
},
|
||||
{
|
||||
"size": 1073,
|
||||
"path": "terminal/markdown-it-LICENSE.txt",
|
||||
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
|
||||
"path": "terminal/markdown-it-LICENSE.txt"
|
||||
"size": 1073
|
||||
},
|
||||
{
|
||||
"size": 100786,
|
||||
"path": "terminal/markdown-it.js",
|
||||
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
|
||||
"path": "terminal/markdown-it.js"
|
||||
"size": 100786
|
||||
},
|
||||
{
|
||||
"size": 3530,
|
||||
"path": "terminal/markdown.html",
|
||||
"sha256": "e5381c35fb254b558c8b869746e2e575c8ed53600611ac90597ed2dd80fa321c",
|
||||
"path": "terminal/markdown.html"
|
||||
"size": 3530
|
||||
},
|
||||
{
|
||||
"size": 15014,
|
||||
"path": "terminal/markdown.js",
|
||||
"sha256": "55c905afaf074e3253267a7c48a5ebca14edd7f15449fd85c0a884c34da22763",
|
||||
"path": "terminal/markdown.js"
|
||||
"size": 15014
|
||||
},
|
||||
{
|
||||
"size": 1089,
|
||||
"path": "terminal/mermaid-LICENSE.txt",
|
||||
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
|
||||
"path": "terminal/mermaid-LICENSE.txt"
|
||||
"size": 1089
|
||||
},
|
||||
{
|
||||
"size": 5537838,
|
||||
"path": "terminal/mermaid.js",
|
||||
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
|
||||
"path": "terminal/mermaid.js"
|
||||
"size": 5537838
|
||||
},
|
||||
{
|
||||
"size": 5033,
|
||||
"sha256": "0557d251962301940785690a3fc49475dd166bb7d0bd0417dc3279d1f1b3a98a",
|
||||
"path": "terminal/terminal.js"
|
||||
"path": "terminal/terminal.js",
|
||||
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b",
|
||||
"size": 5065
|
||||
},
|
||||
{
|
||||
"size": 1261,
|
||||
"path": "terminal/xterm-LICENSE.txt",
|
||||
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
|
||||
"path": "terminal/xterm-LICENSE.txt"
|
||||
"size": 1261
|
||||
},
|
||||
{
|
||||
"size": 7112,
|
||||
"path": "terminal/xterm.css",
|
||||
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
|
||||
"path": "terminal/xterm.css"
|
||||
"size": 7112
|
||||
},
|
||||
{
|
||||
"size": 488663,
|
||||
"path": "terminal/xterm.js",
|
||||
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
|
||||
"path": "terminal/xterm.js"
|
||||
"size": 488663
|
||||
},
|
||||
{
|
||||
"size": 4401,
|
||||
"path": "LICENSE",
|
||||
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
|
||||
"path": "LICENSE"
|
||||
"size": 4401
|
||||
},
|
||||
{
|
||||
"size": 1096,
|
||||
"path": "json-LICENSE.txt",
|
||||
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
|
||||
"path": "json-LICENSE.txt"
|
||||
"size": 1096
|
||||
},
|
||||
{
|
||||
"size": 883,
|
||||
"path": "files-text-license.txt",
|
||||
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
|
||||
"path": "files-text-license.txt"
|
||||
"size": 883
|
||||
},
|
||||
{
|
||||
"size": 95289,
|
||||
"sha256": "fcbd14b6190dc2a3575a4bc4be7229540c647022cb038d33ec4ac22176c67a9e",
|
||||
"path": "README.md"
|
||||
"path": "README.md",
|
||||
"sha256": "ea5016c6fa29a98bf9ebf103fcf27f1be091842ad3228b167d18b053fda767d8",
|
||||
"size": 95317
|
||||
},
|
||||
{
|
||||
"size": 11577,
|
||||
"path": "LAN-PREVIEW.md",
|
||||
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930",
|
||||
"path": "LAN-PREVIEW.md"
|
||||
"size": 11577
|
||||
},
|
||||
{
|
||||
"size": 732485,
|
||||
"path": "dictionaries/en.txt",
|
||||
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
|
||||
"path": "dictionaries/en.txt"
|
||||
"size": 732485
|
||||
},
|
||||
{
|
||||
"size": 20566,
|
||||
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
|
||||
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
|
||||
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt"
|
||||
"size": 20566
|
||||
},
|
||||
{
|
||||
"size": 2265,
|
||||
"path": "dictionaries/README.md",
|
||||
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
|
||||
"path": "dictionaries/README.md"
|
||||
"size": 2265
|
||||
},
|
||||
{
|
||||
"size": 1109134,
|
||||
"path": "dictionaries/ru.txt",
|
||||
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
|
||||
"path": "dictionaries/ru.txt"
|
||||
"size": 1109134
|
||||
},
|
||||
{
|
||||
"size": 1280,
|
||||
"path": "dictionaries/sources.json",
|
||||
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
|
||||
"path": "dictionaries/sources.json"
|
||||
"size": 1280
|
||||
},
|
||||
{
|
||||
"size": 940799,
|
||||
"path": "dictionaries/uk.txt",
|
||||
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
|
||||
"path": "dictionaries/uk.txt"
|
||||
"size": 940799
|
||||
},
|
||||
{
|
||||
"size": 993,
|
||||
"path": "tools/README.txt",
|
||||
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
|
||||
"path": "tools/README.txt"
|
||||
"size": 993
|
||||
},
|
||||
{
|
||||
"size": 133120,
|
||||
"sha256": "9a66349b7184639013843206c113e16a2d0e9cd88686a1a259e5f8ed9a9e9d89",
|
||||
"path": "tools/StayHere.exe"
|
||||
"path": "tools/StayHere.exe",
|
||||
"sha256": "c893d20af87a53cad90306951b80342c553d1cb188291a0377c3f28bd014b2c0",
|
||||
"size": 133120
|
||||
},
|
||||
{
|
||||
"size": 2796,
|
||||
"path": "tools/StayHere-README.md",
|
||||
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
|
||||
"path": "tools/StayHere-README.md"
|
||||
"size": 2796
|
||||
}
|
||||
]
|
||||
],
|
||||
"schema": 1
|
||||
}
|
||||
+3
-3
@@ -9,8 +9,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
|
||||
1 RT_MANIFEST "app.manifest"
|
||||
201 RCDATA "update.ps1"
|
||||
1 VERSIONINFO
|
||||
FILEVERSION 0,6,114,0
|
||||
PRODUCTVERSION 0,6,114,0
|
||||
FILEVERSION 0,6,116,0
|
||||
PRODUCTVERSION 0,6,116,0
|
||||
FILEOS VOS_NT_WINDOWS32
|
||||
FILETYPE VFT_APP
|
||||
BEGIN
|
||||
@@ -20,7 +20,7 @@ BEGIN
|
||||
BEGIN
|
||||
VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility"
|
||||
VALUE "ProductName", "KSwitcher"
|
||||
VALUE "FileVersion", "0.6.114"
|
||||
VALUE "FileVersion", "0.6.116"
|
||||
END
|
||||
END
|
||||
BLOCK "VarFileInfo"
|
||||
|
||||
@@ -50,6 +50,41 @@ BEGIN
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 153, 42, 60, 17
|
||||
END
|
||||
|
||||
611 DIALOGEX 0, 0, 332, 96
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "&Open/create file:", 460, 14, 16, 304, 12
|
||||
FAR_EDIT(461, 0, 14, 29, 304, 14)
|
||||
CONTROL "", 466, "Static", NOT WS_VISIBLE, 14, 50, 1, 1
|
||||
LTEXT "&Code page:", 462, 14, 53, 94, 12
|
||||
COMBOBOX 463, 112, 51, 206, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
|
||||
CONTROL "", 467, "Static", NOT WS_VISIBLE, 14, 72, 1, 1
|
||||
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 76, 60, 16
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 170, 76, 60, 16
|
||||
END
|
||||
|
||||
612 DIALOGEX 0, 0, 332, 184
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "Save file &as:", 460, 14, 16, 304, 12
|
||||
FAR_EDIT(461, 0, 14, 29, 304, 14)
|
||||
CONTROL "", 466, "Static", NOT WS_VISIBLE, 14, 50, 1, 1
|
||||
LTEXT "&Code page:", 462, 14, 53, 94, 12
|
||||
COMBOBOX 463, 112, 51, 206, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
|
||||
AUTOCHECKBOX "Add signature (&BOM)", 464, 14, 66, 304, 12
|
||||
CONTROL "", 468, "Static", NOT WS_VISIBLE, 14, 86, 1, 1
|
||||
LTEXT "Change line breaks to:", 469, 14, 87, 304, 12
|
||||
AUTORADIOBUTTON "Do ¬ change", 470, 14, 100, 304, 12, WS_GROUP | WS_TABSTOP
|
||||
AUTORADIOBUTTON "&Windows (CR LF)", 471, 14, 112, 304, 12
|
||||
AUTORADIOBUTTON "&Unix (LF)", 472, 14, 124, 304, 12
|
||||
AUTORADIOBUTTON "&Mac (CR)", 473, 14, 136, 304, 12
|
||||
CONTROL "", 467, "Static", NOT WS_VISIBLE | WS_GROUP, 14, 155, 1, 1
|
||||
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 157, 60, 16
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 170, 157, 60, 16
|
||||
END
|
||||
|
||||
607 DIALOGEX 0, 0, 185, 57
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
FONT 10, "Consolas"
|
||||
@@ -60,6 +95,7 @@ BEGIN
|
||||
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 67, 38, 51, 15
|
||||
CONTROL "&Yes", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 36, 38, 51, 15
|
||||
CONTROL "&No", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 98, 38, 51, 15
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 129, 38, 51, 15
|
||||
CONTROL "&Processes…", 103, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 14, 38, 75, 15
|
||||
END
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ const terminal = new Terminal({
|
||||
fontFamily: 'Consolas, monospace',
|
||||
fontSize: 16,
|
||||
cursorBlink: false,
|
||||
cursorInactiveStyle: 'none',
|
||||
disableStdin: true,
|
||||
theme: { background: '#181818', foreground: '#e8e8e8' },
|
||||
});
|
||||
|
||||
@@ -2,6 +2,23 @@ constexpr std::array<WORD,2> defaultHistoryKeys{MAKEWORD('E',HOTKEYF_CONTROL),MA
|
||||
auto commandHistoryKeys=defaultHistoryKeys;
|
||||
constexpr size_t commandHistoryLimit=1000;
|
||||
|
||||
std::wstring commandHistoryLabel(const std::wstring &command)
|
||||
{
|
||||
constexpr std::wstring_view prefix=L"start '";
|
||||
if(!command.starts_with(prefix) || command.size()<=prefix.size() || command.back()!=L'\'')
|
||||
return command;
|
||||
const std::wstring_view literal(command.data()+prefix.size(),command.size()-prefix.size()-1);
|
||||
std::wstring path;
|
||||
for(size_t i=0;i<literal.size();++i)
|
||||
{
|
||||
const auto character=literal[i];
|
||||
if(character==L'\'' || character==L'\u2018' || character==L'\u2019')
|
||||
if(++i==literal.size() || literal[i]!=character) return command;
|
||||
path+=character;
|
||||
}
|
||||
return fs::path(path).is_absolute()?path:command;
|
||||
}
|
||||
|
||||
bool validHistoryKeys(const std::array<WORD,2> &keys)
|
||||
{
|
||||
if(keys[0]==keys[1]) return false;
|
||||
|
||||
@@ -69,7 +69,7 @@ void populateCommandHistory(HWND dialog)
|
||||
{
|
||||
return std::all_of(words.begin(),words.end(),[&](const auto &word){return text.find(word)!=text.npos;});
|
||||
};
|
||||
if(containsAll(command+L" "+entry.date))
|
||||
if(containsAll(command+L" "+historyLower(commandHistoryLabel(entry.command))+L" "+entry.date))
|
||||
{
|
||||
matches[0].push_back(index);
|
||||
continue;
|
||||
@@ -91,7 +91,7 @@ void populateCommandHistory(HWND dialog)
|
||||
if(first || date!=lastDate) add(date,-1);
|
||||
first=false;
|
||||
lastDate=date;
|
||||
const auto row=add(entry.command,index);
|
||||
const auto row=add(commandHistoryLabel(entry.command),index);
|
||||
if(row>=0 && (words.empty() || selected==LB_ERR)) selected=row;
|
||||
}
|
||||
}
|
||||
@@ -159,8 +159,9 @@ void sizeCommandHistory(HWND dialog,HWND list)
|
||||
LONG longest{};
|
||||
for(const auto &entry:terminalHistory)
|
||||
{
|
||||
const auto label=commandHistoryLabel(entry.command);
|
||||
SIZE size{};
|
||||
if(GetTextExtentPoint32W(dc,entry.command.c_str(),static_cast<int>(entry.command.size()),&size))
|
||||
if(GetTextExtentPoint32W(dc,label.c_str(),static_cast<int>(label.size()),&size))
|
||||
longest=std::max(longest,size.cx);
|
||||
}
|
||||
SelectObject(dc,previous);
|
||||
|
||||
+358
-59
@@ -214,7 +214,8 @@ DWORD launchElevatedFolder(HWND owner,const fs::path &directory,ElevatedFolderLi
|
||||
|
||||
DWORD readElevatedFolder(const ElevatedFolderListing &session,const fs::path &directory,
|
||||
std::vector<fs::path> &folders,std::vector<fs::path> &files,
|
||||
std::map<fs::path,FolderEntryMetadata> &metadata,std::stop_token stop)
|
||||
std::map<fs::path,FolderEntryMetadata> &metadata,
|
||||
std::atomic_size_t &entriesRead,std::stop_token stop)
|
||||
{
|
||||
bool connected=false;
|
||||
bool finished=false;
|
||||
@@ -251,6 +252,7 @@ DWORD readElevatedFolder(const ElevatedFolderListing &session,const fs::path &di
|
||||
const auto path=directory/child;
|
||||
(entry.attributes&FILE_ATTRIBUTE_DIRECTORY?folders:files).push_back(path);
|
||||
metadata.emplace(path,entry);
|
||||
entriesRead.store(folders.size()+files.size(),std::memory_order_relaxed);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@@ -361,6 +363,7 @@ struct Panel
|
||||
std::optional<ScanRequest> scanRequest;
|
||||
std::future<std::unique_ptr<ScanResult>> scan;
|
||||
std::stop_source scanStop;
|
||||
std::shared_ptr<std::atomic_size_t> scanEntriesRead;
|
||||
bool scanSuperseded{};
|
||||
std::map<fs::path,uint64_t> timestamps;
|
||||
std::vector<fs::path> rows;
|
||||
@@ -376,8 +379,8 @@ struct Panel
|
||||
};
|
||||
Panel panels[2];
|
||||
FilesTerminal terminal;
|
||||
std::mutex remoteOutputMutex;
|
||||
std::string remoteOutput;
|
||||
std::mutex pendingTerminalOutputMutex;
|
||||
std::string pendingTerminalOutput;
|
||||
std::atomic<bool> remoteCommandRunning{};
|
||||
std::jthread remoteCommandThread;
|
||||
std::ofstream terminalTrace;
|
||||
@@ -499,6 +502,7 @@ struct FilesNoticeOptions
|
||||
bool *remember{};
|
||||
FilesNoticeTone tone{FilesNoticeTone::dialog};
|
||||
bool processes{};
|
||||
bool saveChanges{};
|
||||
};
|
||||
INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,FilesNoticeOptions options={});
|
||||
void openMenu(HWND window, int index);
|
||||
@@ -1115,6 +1119,29 @@ void setStatus(const std::wstring &message)
|
||||
SetWindowTextW(status, message.c_str());
|
||||
}
|
||||
|
||||
bool showDirectoryScanProgress(Panel &panel)
|
||||
{
|
||||
if(!panel.scanRequest) return false;
|
||||
const auto entries=panel.scanEntriesRead ? panel.scanEntriesRead->load(std::memory_order_relaxed) : 0;
|
||||
auto message=panel.scanSuperseded ? std::wstring(L"Waiting to read…") :
|
||||
panel.scanStop.stop_requested() ? L"Stopping… "+std::to_wstring(entries) :
|
||||
L"Reading "+std::to_wstring(entries)+L" [Esc]";
|
||||
wchar_t displayed[96]{};
|
||||
GetWindowTextW(status,displayed,std::size(displayed));
|
||||
if(message!=displayed) setStatus(message);
|
||||
panel.scanRequest->statusRevision=statusRevision;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool stopDirectoryScan()
|
||||
{
|
||||
auto &panel=panels[active];
|
||||
if(terminalVisible || !panel.scanRequest || panel.scanSuperseded || !panel.scan.valid()) return false;
|
||||
panel.scanStop.request_stop();
|
||||
showDirectoryScanProgress(panel);
|
||||
return true;
|
||||
}
|
||||
|
||||
void showTerminal(HWND owner,bool show)
|
||||
{
|
||||
terminalVisible=show;
|
||||
@@ -1270,7 +1297,7 @@ void showCompletion(HWND owner,const CompletionQuery &query,const Json &reply={}
|
||||
static_cast<int>(query.line.size()),TRUE)!=CSTR_EQUAL ||
|
||||
!seen.insert(command).second)
|
||||
continue;
|
||||
completionItems.push_back({command,command,0,query.line.size()});
|
||||
completionItems.push_back({commandHistoryLabel(command),command,0,query.line.size()});
|
||||
}
|
||||
}
|
||||
appendPowerShellCompletions(query,reply,seen);
|
||||
@@ -1623,23 +1650,23 @@ void updateTerminalOutput()
|
||||
if(!bytes.empty()) terminalView.send(bytes);
|
||||
std::string incoming;
|
||||
{
|
||||
const std::lock_guard lock(remoteOutputMutex);
|
||||
incoming.swap(remoteOutput);
|
||||
const std::lock_guard lock(pendingTerminalOutputMutex);
|
||||
incoming.swap(pendingTerminalOutput);
|
||||
}
|
||||
if(!incoming.empty()) terminalView.send(incoming);
|
||||
}
|
||||
|
||||
void appendRemoteOutput(std::string_view output)
|
||||
void appendTerminalOutput(std::string_view output)
|
||||
{
|
||||
const std::lock_guard lock(remoteOutputMutex);
|
||||
const std::lock_guard lock(pendingTerminalOutputMutex);
|
||||
for(const auto character:output)
|
||||
{
|
||||
const auto byte=static_cast<unsigned char>(character);
|
||||
if(byte>=32 || character=='\r' || character=='\n' || character=='\t')
|
||||
remoteOutput+=character;
|
||||
pendingTerminalOutput+=character;
|
||||
}
|
||||
constexpr size_t limit=1024*1024;
|
||||
if(remoteOutput.size()>limit) remoteOutput.erase(0,remoteOutput.size()-limit);
|
||||
if(pendingTerminalOutput.size()>limit) pendingTerminalOutput.erase(0,pendingTerminalOutput.size()-limit);
|
||||
}
|
||||
|
||||
bool submitTerminalCommand(const Panel &panel,const std::wstring &value)
|
||||
@@ -1649,7 +1676,7 @@ bool submitTerminalCommand(const Panel &panel,const std::wstring &value)
|
||||
{
|
||||
constexpr auto busy=L"A remote command is running. Clear the command line and press Escape to cancel it.";
|
||||
setStatus(busy);
|
||||
if(terminalVisible) appendRemoteOutput(ks::utf8(std::wstring(L"\r\n")+busy+L"\r\n"));
|
||||
if(terminalVisible) appendTerminalOutput(ks::utf8(std::wstring(L"\r\n")+busy+L"\r\n"));
|
||||
return false;
|
||||
}
|
||||
if(panel.peer)
|
||||
@@ -1660,7 +1687,7 @@ bool submitTerminalCommand(const Panel &panel,const std::wstring &value)
|
||||
layout(owner);
|
||||
const auto peer=*panel.peer;
|
||||
const auto directory=panel.directory;
|
||||
appendRemoteOutput(ks::utf8(L"\r\n["+peer.name+L" · "+directory.wstring()+L"]> "+value+L"\r\n"));
|
||||
appendTerminalOutput(ks::utf8(L"\r\n["+peer.name+L" · "+directory.wstring()+L"]> "+value+L"\r\n"));
|
||||
remoteCommandRunning=true;
|
||||
try
|
||||
{
|
||||
@@ -1669,11 +1696,11 @@ bool submitTerminalCommand(const Panel &panel,const std::wstring &value)
|
||||
try
|
||||
{
|
||||
FilesConnection host(&peer);
|
||||
const auto code=ks::lan::runRemoteCommand(host,directory,value,appendRemoteOutput,stop);
|
||||
const auto code=ks::lan::runRemoteCommand(host,directory,value,appendTerminalOutput,stop);
|
||||
if(code==STATUS_DLL_INIT_FAILED)
|
||||
appendRemoteOutput("\r\nRemote PowerShell could not start: DLL initialization failed (0xC0000142).\r\n");
|
||||
appendTerminalOutput("\r\nRemote PowerShell could not start: DLL initialization failed (0xC0000142).\r\n");
|
||||
else
|
||||
appendRemoteOutput("\r\n[Remote exit code "+std::to_string(code)+"]\r\n");
|
||||
appendTerminalOutput("\r\n[Remote exit code "+std::to_string(code)+"]\r\n");
|
||||
}
|
||||
catch(const std::system_error &error)
|
||||
{
|
||||
@@ -1682,11 +1709,11 @@ bool submitTerminalCommand(const Panel &panel,const std::wstring &value)
|
||||
? L"The remote PC denied this command. Check its Files command-line settings."
|
||||
: code==ERROR_INVALID_FUNCTION?L"Update KSwitcher on the remote PC."
|
||||
: code==ERROR_CANCELLED?L"Remote command canceled.":fileError(error);
|
||||
appendRemoteOutput(ks::utf8(L"\r\n"+std::wstring(reason)+L"\r\n"));
|
||||
appendTerminalOutput(ks::utf8(L"\r\n"+std::wstring(reason)+L"\r\n"));
|
||||
}
|
||||
catch(const std::exception &)
|
||||
{
|
||||
appendRemoteOutput("\r\nThe remote command connection ended.\r\n");
|
||||
appendTerminalOutput("\r\nThe remote command connection ended.\r\n");
|
||||
}
|
||||
remoteCommandRunning=false;
|
||||
});
|
||||
@@ -1743,6 +1770,7 @@ LRESULT CALLBACK terminalInputKeys(HWND input,UINT message,WPARAM wp,LPARAM lp,U
|
||||
if(message==WM_CHAR && wp==VK_TAB && !terminalVisible) return 0;
|
||||
if(message==WM_CHAR && wp==VK_ESCAPE)
|
||||
{
|
||||
if(stopDirectoryScan()) return 0;
|
||||
if(remoteCommandRunning && !GetWindowTextLengthW(input))
|
||||
{
|
||||
remoteCommandThread.request_stop();
|
||||
@@ -1797,6 +1825,7 @@ LRESULT CALLBACK terminalInputKeys(HWND input,UINT message,WPARAM wp,LPARAM lp,U
|
||||
|
||||
void showFileDetails(const Panel &panel)
|
||||
{
|
||||
if(&panel==&panels[active] && showDirectoryScanProgress(panels[active])) return;
|
||||
auto row=SendMessageW(panel.list,LB_GETCURSEL,0,0);
|
||||
if(!panel.wide || !showDetails || row<0 || static_cast<size_t>(row)>=panel.rows.size())
|
||||
{
|
||||
@@ -1838,24 +1867,29 @@ void showFileDetails(const Panel &panel)
|
||||
setStatus(details);
|
||||
}
|
||||
|
||||
std::unique_ptr<Panel::ScanResult> scanDirectory(const Panel::ScanRequest &request,std::stop_token stop)
|
||||
std::unique_ptr<Panel::ScanResult> scanDirectory(const Panel::ScanRequest &request,
|
||||
std::atomic_size_t &entriesRead,std::stop_token stop)
|
||||
{
|
||||
auto result=std::make_unique<Panel::ScanResult>();
|
||||
auto &[watch,folders,files,metadata,timestamps,error,opened,failure]=*result;
|
||||
const auto &directory=request.directory;
|
||||
const auto &peer=request.peer;
|
||||
if(stop.stop_requested()) return result;
|
||||
if(stop.stop_requested())
|
||||
{
|
||||
error=ERROR_CANCELLED;
|
||||
return result;
|
||||
}
|
||||
if(request.elevated)
|
||||
{
|
||||
error=readElevatedFolder(*request.elevated,directory,folders,files,metadata,stop);
|
||||
opened=error==ERROR_SUCCESS;
|
||||
error=readElevatedFolder(*request.elevated,directory,folders,files,metadata,entriesRead,stop);
|
||||
opened=error==ERROR_SUCCESS || (error==ERROR_CANCELLED && !metadata.empty());
|
||||
if(opened)
|
||||
{
|
||||
watch.start(directory);
|
||||
if(error==ERROR_SUCCESS) watch.start(directory);
|
||||
std::sort(folders.begin(),folders.end());
|
||||
std::sort(files.begin(),files.end());
|
||||
}
|
||||
else failure=error==ERROR_ACCESS_DENIED?L"Windows denied access after elevation: "+directory.wstring():
|
||||
else if(error!=ERROR_CANCELLED) failure=error==ERROR_ACCESS_DENIED?L"Windows denied access after elevation: "+directory.wstring():
|
||||
L"Could not read folder as administrator ("+std::to_wstring(error)+L"): "+directory.wstring();
|
||||
return result;
|
||||
}
|
||||
@@ -1874,24 +1908,36 @@ std::unique_ptr<Panel::ScanResult> scanDirectory(const Panel::ScanRequest &reque
|
||||
try
|
||||
{
|
||||
FilesConnection host(&*peer);
|
||||
listFiles(host,directory,[&](const fs::path &path,const FileInfo &info)
|
||||
const bool complete=listFiles(host,directory,[&](const fs::path &path,const FileInfo &info)
|
||||
{
|
||||
if(stop.stop_requested()) return false;
|
||||
(info.attributes&FILE_ATTRIBUTE_DIRECTORY?folders:files).push_back(path);
|
||||
metadata.emplace(path,FolderEntryMetadata{info.attributes,info.size});
|
||||
timestamps.emplace(path,info.modified);
|
||||
entriesRead.store(folders.size()+files.size(),std::memory_order_relaxed);
|
||||
return true;
|
||||
});
|
||||
opened=true;
|
||||
if(!complete) error=ERROR_CANCELLED;
|
||||
}
|
||||
catch(const std::system_error &e){result->failure=peer->name+L" — "+fileError(e);}
|
||||
catch(const std::exception &){result->failure=L"Cannot open folder on "+peer->name;}
|
||||
if(!opened && stop.stop_requested())
|
||||
{
|
||||
error=ERROR_CANCELLED;
|
||||
opened=!metadata.empty();
|
||||
failure.clear();
|
||||
}
|
||||
}
|
||||
if(search!=INVALID_HANDLE_VALUE)
|
||||
{
|
||||
do
|
||||
{
|
||||
if(stop.stop_requested()) return result;
|
||||
if(stop.stop_requested())
|
||||
{
|
||||
error=ERROR_CANCELLED;
|
||||
break;
|
||||
}
|
||||
const std::wstring_view name(data.cFileName);
|
||||
if(name==L"." || name==L"..") continue;
|
||||
const auto path=directory/name;
|
||||
@@ -1899,9 +1945,11 @@ std::unique_ptr<Panel::ScanResult> scanDirectory(const Panel::ScanRequest &reque
|
||||
(data.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY?folders:files).push_back(path);
|
||||
metadata.emplace(path,FolderEntryMetadata{data.dwFileAttributes,size});
|
||||
timestamps.emplace(path,(uint64_t(data.ftLastWriteTime.dwHighDateTime)<<32)|data.ftLastWriteTime.dwLowDateTime);
|
||||
entriesRead.store(folders.size()+files.size(),std::memory_order_relaxed);
|
||||
} while(FindNextFileW(search,&data));
|
||||
error=GetLastError();
|
||||
if(error!=ERROR_CANCELLED) error=GetLastError();
|
||||
}
|
||||
else if(!peer && stop.stop_requested()) error=ERROR_CANCELLED;
|
||||
std::sort(folders.begin(), folders.end());
|
||||
std::sort(files.begin(), files.end());
|
||||
return result;
|
||||
@@ -1917,12 +1965,18 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
|
||||
(peer?peer->id:std::string{})?panel.directory:fs::path{};
|
||||
const bool sameDirectory=previousDirectory==directory;
|
||||
auto &[nextWatch,folders,files,metadata,timestamps,error,opened,failure]=scan;
|
||||
const bool partial=error==ERROR_CANCELLED;
|
||||
if(!failure.empty())
|
||||
{
|
||||
setStatus(failure);
|
||||
return false;
|
||||
}
|
||||
if (!scan.opened && error!=ERROR_FILE_NOT_FOUND)
|
||||
if(partial && !opened)
|
||||
{
|
||||
if(&panel==&panels[active]) setStatus(L"Reading stopped before the folder opened.");
|
||||
return false;
|
||||
}
|
||||
if (!opened && error!=ERROR_FILE_NOT_FOUND)
|
||||
{
|
||||
const bool denied=error==ERROR_ACCESS_DENIED;
|
||||
setStatus(denied ? L"Access denied: " + directory.wstring() :
|
||||
@@ -1948,7 +2002,6 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
|
||||
return false;
|
||||
}
|
||||
rememberElevationApproval=rememberElevationApproval || remember;
|
||||
setStatus(L"Loading folder…");
|
||||
request.statusRevision=statusRevision;
|
||||
request.elevated=std::move(elevated);
|
||||
panel.scanRequest=std::move(request);
|
||||
@@ -1979,7 +2032,8 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
|
||||
panel.folderSizeQuery={};
|
||||
panel.folderSizes.clear();
|
||||
}
|
||||
if(!sameDirectory || panel.watch.handle==INVALID_HANDLE_VALUE)
|
||||
if(partial) panel.watch.reset();
|
||||
else if(!sameDirectory || panel.watch.handle==INVALID_HANDLE_VALUE)
|
||||
{
|
||||
panel.watch.reset();
|
||||
std::swap(panel.watch.handle,nextWatch.handle);
|
||||
@@ -1990,8 +2044,14 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
|
||||
panel.dimmed.clear();
|
||||
panel.marked.clear();
|
||||
panel.fileExtensionLength=panel.folderExtensionLength=0;
|
||||
SendMessageW(panel.list, LB_RESETCONTENT, 0, 0);
|
||||
const auto rowCount = folders.size() + files.size() + directory.has_relative_path();
|
||||
panel.rows.reserve(rowCount);
|
||||
panel.sizes.reserve(rowCount);
|
||||
panel.dimmed.reserve(rowCount);
|
||||
panel.marked.reserve(rowCount);
|
||||
const bool visible=IsWindowVisible(panel.list);
|
||||
if(visible) SendMessageW(panel.list,WM_SETREDRAW,FALSE,0);
|
||||
SendMessageW(panel.list, LB_RESETCONTENT, 0, 0);
|
||||
SendMessageW(panel.list, LB_INITSTORAGE, rowCount, 0);
|
||||
auto add = [&](const fs::path &path, const std::wstring &label, bool folder)
|
||||
{
|
||||
@@ -2037,8 +2097,11 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
|
||||
if(sameDirectory) SendMessageW(panel.list,LB_SETTOPINDEX,previousTop,0);
|
||||
SendMessageW(panel.list,LB_SETCURSEL,selected-panel.rows.begin(),0);
|
||||
}
|
||||
if(visible) SendMessageW(panel.list,WM_SETREDRAW,TRUE,0);
|
||||
InvalidateRect(panel.list,nullptr,FALSE);
|
||||
if(error!=ERROR_SUCCESS && error!=ERROR_NO_MORE_FILES && error!=ERROR_FILE_NOT_FOUND)
|
||||
if(partial && &panel==&panels[active])
|
||||
setStatus(L"Partial: "+std::to_wstring(folders.size()+files.size()));
|
||||
else if(!partial && error!=ERROR_SUCCESS && error!=ERROR_NO_MORE_FILES && error!=ERROR_FILE_NOT_FOUND)
|
||||
setStatus(L"Some entries could not be read.");
|
||||
else if(updateDetails && &panel==&panels[active]) showFileDetails(panel);
|
||||
return true;
|
||||
@@ -2047,9 +2110,13 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
|
||||
void startDirectoryScan(Panel &panel)
|
||||
{
|
||||
panel.scanStop=std::stop_source{};
|
||||
panel.scanEntriesRead=std::make_shared<std::atomic_size_t>(0);
|
||||
const auto owner=GetParent(panel.list);
|
||||
std::packaged_task<std::unique_ptr<Panel::ScanResult>()> task(
|
||||
[request=*panel.scanRequest,stop=panel.scanStop.get_token()] {return scanDirectory(request,stop);});
|
||||
[request=*panel.scanRequest,entries=panel.scanEntriesRead,stop=panel.scanStop.get_token()]
|
||||
{
|
||||
return scanDirectory(request,*entries,stop);
|
||||
});
|
||||
auto future=task.get_future();
|
||||
std::thread([task=std::move(task),owner]() mutable
|
||||
{
|
||||
@@ -2058,21 +2125,20 @@ void startDirectoryScan(Panel &panel)
|
||||
}).detach();
|
||||
panel.scan=std::move(future);
|
||||
panel.scanSuperseded=false;
|
||||
if(&panel==&panels[active]) showDirectoryScanProgress(panel);
|
||||
}
|
||||
|
||||
void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::optional<FilesPeer> peer,
|
||||
fs::path selection={},fs::path fallback={})
|
||||
{
|
||||
if(directory.empty()) return;
|
||||
if(&panel==&panels[active] && (directory!=panel.directory ||
|
||||
(peer?peer->id:std::string{})!=(panel.peer?panel.peer->id:std::string{})))
|
||||
setStatus(L"Loading folder…");
|
||||
panel.scanRequest=Panel::ScanRequest{directory,std::move(selection),std::move(fallback),
|
||||
std::move(peer),offerElevation,statusRevision};
|
||||
if(panel.scan.valid())
|
||||
{
|
||||
panel.scanSuperseded=true;
|
||||
panel.scanStop.request_stop();
|
||||
if(&panel==&panels[active]) showDirectoryScanProgress(panel);
|
||||
}
|
||||
else startDirectoryScan(panel);
|
||||
}
|
||||
@@ -2091,12 +2157,14 @@ void collectDirectoryScans()
|
||||
}
|
||||
auto request=std::move(*panel.scanRequest);
|
||||
panel.scanRequest.reset();
|
||||
panel.scanEntriesRead.reset();
|
||||
bool applied=false;
|
||||
const auto fallback=request.fallback;
|
||||
try
|
||||
{
|
||||
auto result=panel.scan.get();
|
||||
applied=applyDirectoryScan(panel,std::move(request),*result);
|
||||
if(result->error==ERROR_CANCELLED) continue;
|
||||
}
|
||||
catch(const std::exception &) {setStatus(L"Could not read the folder.");}
|
||||
if(!applied && !fallback.empty()) openOn(panel,fallback,false,{});
|
||||
@@ -2195,7 +2263,8 @@ void collectFolderSizes()
|
||||
}
|
||||
|
||||
void openSelectedText(const Panel &panel, bool edit, bool external);
|
||||
INT_PTR confirmTextSave(HWND owner);
|
||||
INT_PTR confirmTextSave(HWND owner,bool draft);
|
||||
bool chooseTextSaveOptions(HWND owner,fs::path &destination,ks::files::TextSaveFormat &format);
|
||||
INT_PTR paintTextDialog(HWND window, UINT message, WPARAM wp, LPARAM lp, const wchar_t *caption);
|
||||
INT_PTR paintSearchDialog(HWND window,UINT message,WPARAM wp,LPARAM lp);
|
||||
ks::files::FarDropDownPalette farDropDownPalette();
|
||||
@@ -2731,12 +2800,13 @@ void chooseDrive(int index,bool fromMenu)
|
||||
RedrawWindow(owner,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN|RDW_UPDATENOW);
|
||||
}
|
||||
|
||||
void openPanelPathWithSystem(const Panel &panel,const fs::path &path,const wchar_t *verb,
|
||||
bool openPanelPathWithSystem(const Panel &panel,const fs::path &path,const wchar_t *verb,
|
||||
const wchar_t *failureMessage)
|
||||
{
|
||||
if (reinterpret_cast<INT_PTR>(ShellExecuteW(GetParent(panel.list), verb, path.c_str(), nullptr,
|
||||
panel.directory.c_str(), SW_SHOWNORMAL)) <= 32)
|
||||
setStatus(failureMessage);
|
||||
panel.directory.c_str(), SW_SHOWNORMAL)) > 32) return true;
|
||||
setStatus(failureMessage);
|
||||
return false;
|
||||
}
|
||||
|
||||
void openPanelFile(const Panel &panel, const fs::path &file, const wchar_t *verb, const wchar_t *failureMessage)
|
||||
@@ -2767,8 +2837,21 @@ void openPanelFile(const Panel &panel, const fs::path &file, const wchar_t *verb
|
||||
}
|
||||
return;
|
||||
}
|
||||
const bool recordOpen=!verb;
|
||||
if(!verb && isExtension(L".exe")) verb=L"open";
|
||||
openPanelPathWithSystem(panel,file,verb,failureMessage);
|
||||
if(!openPanelPathWithSystem(panel,file,verb,failureMessage) || !recordOpen) return;
|
||||
const auto command=L"start "+powerShellPath(file);
|
||||
rememberCommand(command);
|
||||
terminalHistoryIndex=terminalHistory.size();
|
||||
const auto owner=GetParent(panel.list);
|
||||
if(!ensureTerminalView(owner)) return;
|
||||
appendTerminalOutput(ks::utf8(L"\r\n"+file.native()+L"\r\n"));
|
||||
if(!terminalVisible && terminalRows==0)
|
||||
{
|
||||
terminalRows=5;
|
||||
layout(owner);
|
||||
}
|
||||
terminalView.post(L"scroll-bottom");
|
||||
}
|
||||
|
||||
void openSelectedWithSystem(const Panel &panel)
|
||||
@@ -2787,6 +2870,17 @@ void openSelectedWithSystem(const Panel &panel)
|
||||
|
||||
#include "files_dialog_input.inl"
|
||||
|
||||
ks::files::TextDialogs textWindowDialogs()
|
||||
{
|
||||
return {confirmTextSave,paintTextDialog,paintSearchDialog,prepareTextDialog,editTextOptions,showTextMessage,readFilesFont,
|
||||
farDropDownPalette,FilesModalDialog::run,FilesModalDialog::finish,FilesModalDialog::dismissOwned,
|
||||
[](HWND owner)
|
||||
{
|
||||
return showFilesNotice(owner,L"This file is already open. Switch to its window?",L"Files",
|
||||
{.confirm=true})==IDYES;
|
||||
},chooseTextSaveOptions};
|
||||
}
|
||||
|
||||
void openSelectedText(const Panel &panel, bool edit, bool external)
|
||||
{
|
||||
const auto row=currentPanelRow(panel);
|
||||
@@ -2800,14 +2894,8 @@ void openSelectedText(const Panel &panel, bool edit, bool external)
|
||||
if(external)
|
||||
openPanelFile(panel,path,edit?L"edit":L"open",
|
||||
edit?L"No editor is registered for this file.":L"Cannot open the selected file.");
|
||||
else ks::files::openTextWindow(GetParent(panel.list),path,edit,
|
||||
{confirmTextSave,paintTextDialog,paintSearchDialog,prepareTextDialog,editTextOptions,showTextMessage,readFilesFont,
|
||||
farDropDownPalette,FilesModalDialog::run,FilesModalDialog::finish,FilesModalDialog::dismissOwned,
|
||||
[](HWND owner)
|
||||
{
|
||||
return showFilesNotice(owner,L"This file is already open. Switch to its window?",L"Files",
|
||||
{.confirm=true})==IDYES;
|
||||
}},panel.peer?&*panel.peer:nullptr);
|
||||
else ks::files::openTextWindow(GetParent(panel.list),path,edit,textWindowDialogs(),
|
||||
panel.peer?&*panel.peer:nullptr);
|
||||
}
|
||||
|
||||
void enter(Panel &panel)
|
||||
@@ -3342,7 +3430,9 @@ LRESULT CALLBACK paintFarCheckbox(HWND field,UINT message,WPARAM wp,LPARAM lp,UI
|
||||
SetTextColor(dc,IsWindowEnabled(field)?ink:RGB(128,128,128));
|
||||
wchar_t label[80]{};
|
||||
GetWindowTextW(field,label,static_cast<int>(std::size(label)));
|
||||
const auto text=(SendMessageW(field,BM_GETCHECK,0,0)==BST_CHECKED?L"[x] ":L"[ ] ")+std::wstring(label);
|
||||
const bool radio=(GetWindowLongPtrW(field,GWL_STYLE)&BS_TYPEMASK)==BS_AUTORADIOBUTTON;
|
||||
const bool checked=SendMessageW(field,BM_GETCHECK,0,0)==BST_CHECKED;
|
||||
const auto text=(radio?(checked?L"(•) ":L"( ) "):(checked?L"[x] ":L"[ ] "))+std::wstring(label);
|
||||
if(IsWindowEnabled(field)) drawFarDialogLabel(dc,bounds,text,false);
|
||||
else DrawTextW(dc,text.c_str(),-1,&bounds,DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS);
|
||||
EndPaint(field,&paint);
|
||||
@@ -3907,8 +3997,6 @@ void prepareTextDialog(HWND dialog)
|
||||
|
||||
INT_PTR CALLBACK textSaveDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(const auto painted=paintTextDialog(window,message,wp,lp,L" Editor "))
|
||||
return painted;
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
prepareTextDialog(window);
|
||||
@@ -3917,6 +4005,7 @@ INT_PTR CALLBACK textSaveDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
|
||||
SetFocus(GetDlgItem(window,IDCANCEL));
|
||||
return FALSE;
|
||||
}
|
||||
if(const auto painted=paintTextDialog(window,message,wp,lp,L" Editor ")) return painted;
|
||||
if(message==WM_COMMAND && (LOWORD(wp)==IDYES || LOWORD(wp)==IDNO || LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
FilesModalDialog::finish(window,LOWORD(wp));
|
||||
@@ -3925,8 +4014,11 @@ INT_PTR CALLBACK textSaveDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
INT_PTR confirmTextSave(HWND owner)
|
||||
INT_PTR confirmTextSave(HWND owner,bool draft)
|
||||
{
|
||||
if(draft)
|
||||
return showFilesNotice(owner,L"Save changes to this file?",L"Editor",
|
||||
{.tone=FilesNoticeTone::warning,.saveChanges=true});
|
||||
return FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(603),owner,textSaveDialog,0);
|
||||
}
|
||||
|
||||
@@ -3981,7 +4073,8 @@ void layoutFilesNotice(HWND dialog)
|
||||
bottom+=textHeight;
|
||||
}
|
||||
place(102,bottom+dialogRowGap()+4,1);
|
||||
if(notice.options.confirm) layoutDialogButtons(dialog,102,{IDYES,IDNO});
|
||||
if(notice.options.saveChanges) layoutDialogButtons(dialog,102,{IDYES,IDNO,IDCANCEL});
|
||||
else if(notice.options.confirm) layoutDialogButtons(dialog,102,{IDYES,IDNO});
|
||||
else if(notice.options.processes) layoutDialogButtons(dialog,102,{showProcessesButton,IDOK});
|
||||
else layoutDialogButtons(dialog,102,{IDOK});
|
||||
}
|
||||
@@ -4004,12 +4097,18 @@ INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
|
||||
notice.options.tone==FilesNoticeTone::neutral?FarCheckboxSurface::gray:FarCheckboxSurface::dialog);
|
||||
ShowWindow(checkbox,SW_SHOW);
|
||||
}
|
||||
if(notice.options.confirm)
|
||||
if(notice.options.confirm || notice.options.saveChanges)
|
||||
{
|
||||
ShowWindow(GetDlgItem(window,IDOK),SW_HIDE);
|
||||
ShowWindow(GetDlgItem(window,IDYES),SW_SHOW);
|
||||
ShowWindow(GetDlgItem(window,IDNO),SW_SHOW);
|
||||
}
|
||||
if(notice.options.saveChanges)
|
||||
{
|
||||
SetDlgItemTextW(window,IDYES,L"&Save");
|
||||
SetDlgItemTextW(window,IDNO,L"&Discard");
|
||||
ShowWindow(GetDlgItem(window,IDCANCEL),SW_SHOW);
|
||||
}
|
||||
if(notice.options.processes) ShowWindow(GetDlgItem(window,showProcessesButton),SW_SHOW);
|
||||
RECT caption{},text{};
|
||||
if(const auto dc=GetDC(window))
|
||||
@@ -4022,12 +4121,12 @@ INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
const auto inset=dialogFrameMetrics(GetDpiForWindow(window)).content();
|
||||
const auto minimum=std::max({24L*cellWidth,caption.right+6*cellWidth,
|
||||
notice.options.remember || notice.options.processes?34L*cellWidth:0L})+2*inset;
|
||||
notice.options.remember || notice.options.processes || notice.options.saveChanges?34L*cellWidth:0L})+2*inset;
|
||||
const auto width=std::clamp(text.right+cellWidth+2*inset,minimum,std::max(minimum,60L*cellWidth+2*inset));
|
||||
SetWindowPos(window,nullptr,0,0,width,1,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
layoutFilesNotice(window);
|
||||
FilesModalDialog::fitWidthToOwner(window,minimum,layoutFilesNotice);
|
||||
const auto defaultButton=notice.options.confirm?IDNO:IDOK;
|
||||
const auto defaultButton=notice.options.saveChanges?IDCANCEL:notice.options.confirm?IDNO:IDOK;
|
||||
SendMessageW(window,DM_SETDEFID,defaultButton,0);
|
||||
SetFocus(GetDlgItem(window,defaultButton));
|
||||
return FALSE;
|
||||
@@ -5243,6 +5342,196 @@ void makeFolder(HWND owner,Panel &panel)
|
||||
selectPanelPath(panel,request.created);
|
||||
}
|
||||
|
||||
struct TextFilePrompt
|
||||
{
|
||||
fs::path directory,path;
|
||||
ks::files::TextSaveFormat format;
|
||||
bool saving{};
|
||||
};
|
||||
|
||||
constexpr const wchar_t *textCodePages[]{L"Default",L"65001 | UTF-8",L"1200 | UTF-16 LE",
|
||||
L"1201 | UTF-16 BE",L"1252 | Windows-1252"};
|
||||
constexpr int textPathField=461,textCodePage=463,textBom=464,textFooter=467,textFirstLineEnding=470;
|
||||
|
||||
void layoutTextFilePrompt(HWND dialog)
|
||||
{
|
||||
RECT client{};
|
||||
GetClientRect(dialog,&client);
|
||||
const auto frame=dialogFrameMetrics(GetDpiForWindow(dialog));
|
||||
const auto inset=frame.content(),gap=dialogRowGap();
|
||||
const auto width=client.right-2*inset;
|
||||
const auto place=[&](int id,int x,int y,int w,int h)
|
||||
{
|
||||
SetWindowPos(GetDlgItem(dialog,id),nullptr,x,y,w,h,SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
};
|
||||
auto y=dialogListInset(frame,textHeight);
|
||||
const auto row=[&](int id)
|
||||
{
|
||||
place(id,inset,y,width,textHeight);
|
||||
y+=textHeight;
|
||||
};
|
||||
const auto divider=[&](int id)
|
||||
{
|
||||
y+=gap;
|
||||
place(id,inset,y+4,1,1);
|
||||
y+=gap+1;
|
||||
};
|
||||
row(460);
|
||||
row(textPathField);
|
||||
fitFarEditToLine(GetDlgItem(dialog,textPathField));
|
||||
divider(466);
|
||||
const auto labelWidth=12*cellWidth;
|
||||
place(462,inset,y,labelWidth,textHeight);
|
||||
place(textCodePage,inset+labelWidth,y,width-labelWidth,textHeight);
|
||||
y+=textHeight;
|
||||
if(GetDlgItem(dialog,textBom))
|
||||
{
|
||||
row(textBom);
|
||||
divider(468);
|
||||
row(469);
|
||||
for(int i=0;i<4;++i) row(textFirstLineEnding+i);
|
||||
}
|
||||
divider(textFooter);
|
||||
layoutDialogButtons(dialog,textFooter,{IDOK,IDCANCEL});
|
||||
}
|
||||
|
||||
fs::path unnamedTextFile(const fs::path &directory)
|
||||
{
|
||||
SYSTEMTIME time{};
|
||||
GetLocalTime(&time);
|
||||
wchar_t stem[64]{};
|
||||
swprintf_s(stem,L"New_File_%04u-%02u-%02u_%02u.%02u.%02u.%03u",
|
||||
unsigned(time.wYear),unsigned(time.wMonth),unsigned(time.wDay),unsigned(time.wHour),
|
||||
unsigned(time.wMinute),unsigned(time.wSecond),unsigned(time.wMilliseconds));
|
||||
auto path=directory/(std::wstring(stem)+L".txt");
|
||||
for(unsigned suffix=1;GetFileAttributesW(path.c_str())!=INVALID_FILE_ATTRIBUTES;++suffix)
|
||||
path=directory/(std::wstring(stem)+L"_"+std::to_wstring(suffix)+L".txt");
|
||||
return path;
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK textFilePrompt(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
using namespace ks::files;
|
||||
const auto field=GetDlgItem(dialog,textPathField);
|
||||
const auto combo=GetDlgItem(dialog,textCodePage);
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
const auto &prompt=*reinterpret_cast<const TextFilePrompt *>(lp);
|
||||
prepareTextDialog(dialog);
|
||||
const auto inset=dialogFrameMetrics(GetDpiForWindow(dialog)).content();
|
||||
SetWindowPos(dialog,nullptr,0,0,48*cellWidth+2*inset,1,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
layoutTextFilePrompt(dialog);
|
||||
if(prompt.saving)
|
||||
{
|
||||
SetWindowTextW(field,prompt.path.filename().c_str());
|
||||
installFarCheckbox(GetDlgItem(dialog,textBom),FarCheckboxSurface::gray);
|
||||
for(int i=0;i<4;++i)
|
||||
installFarCheckbox(GetDlgItem(dialog,textFirstLineEnding+i),FarCheckboxSurface::gray);
|
||||
CheckDlgButton(dialog,textBom,prompt.format.bom?BST_CHECKED:BST_UNCHECKED);
|
||||
CheckRadioButton(dialog,textFirstLineEnding,textFirstLineEnding+3,
|
||||
textFirstLineEnding+static_cast<int>(prompt.format.lineEnding));
|
||||
}
|
||||
const int first=prompt.saving?1:0;
|
||||
for(int i=first;i<static_cast<int>(std::size(textCodePages));++i)
|
||||
SendMessageW(combo,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(textCodePages[i]));
|
||||
installFarCombo(combo,field);
|
||||
SendMessageW(combo,CB_SETCURSEL,static_cast<int>(prompt.format.encoding)-first,0);
|
||||
if(prompt.saving) EnableWindow(GetDlgItem(dialog,textBom),prompt.format.encoding!=TextEncoding::windows1252);
|
||||
FilesModalDialog::fitWidthToOwner(dialog,36*cellWidth+2*inset,layoutTextFilePrompt);
|
||||
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
|
||||
SetFocus(field);
|
||||
SendMessageW(field,EM_SETSEL,0,-1);
|
||||
return FALSE;
|
||||
}
|
||||
auto *prompt=reinterpret_cast<TextFilePrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(!prompt) return FALSE;
|
||||
if(message==WM_DRAWITEM && wp==textCodePage)
|
||||
{
|
||||
drawFarComboRow(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CTLCOLORLISTBOX)
|
||||
{
|
||||
const auto dc=reinterpret_cast<HDC>(wp);
|
||||
SetTextColor(dc,colors[Text]);
|
||||
SetBkColor(dc,colors[Dialog]);
|
||||
return reinterpret_cast<INT_PTR>(teal);
|
||||
}
|
||||
const auto painted=prompt->saving?paintCopyDialog(dialog,message,wp,lp,L" Editor ",false,{466,468,textFooter}):
|
||||
paintCopyDialog(dialog,message,wp,lp,L" Editor ",false,{466,textFooter});
|
||||
if(painted) return painted;
|
||||
if(message!=WM_COMMAND) return FALSE;
|
||||
const auto command=LOWORD(wp);
|
||||
if(command==IDCANCEL) {FilesModalDialog::finish(dialog,IDCANCEL); return TRUE;}
|
||||
const auto selected=SendMessageW(combo,CB_GETCURSEL,0,0);
|
||||
const auto encoding=static_cast<TextEncoding>(std::max<LRESULT>(0,selected)+prompt->saving);
|
||||
if(command==textCodePage && HIWORD(wp)==CBN_SELCHANGE && prompt->saving)
|
||||
{
|
||||
EnableWindow(GetDlgItem(dialog,textBom),encoding!=TextEncoding::windows1252);
|
||||
return TRUE;
|
||||
}
|
||||
if(command!=IDOK) return FALSE;
|
||||
const auto entered=dialogFieldText(field);
|
||||
const fs::path name=entered;
|
||||
const auto path=(name.empty()?unnamedTextFile(prompt->directory):prompt->directory/name).lexically_normal();
|
||||
const auto parent=GetFileAttributesW(path.parent_path().c_str());
|
||||
const auto attributes=GetFileAttributesW(path.c_str());
|
||||
if((name.has_root_name() && !name.is_absolute()) || !validFileName(path.filename().native()) ||
|
||||
parent==INVALID_FILE_ATTRIBUTES || !(parent&FILE_ATTRIBUTE_DIRECTORY) ||
|
||||
(attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_DIRECTORY)))
|
||||
{
|
||||
showFilesNotice(dialog,L"Enter a valid file name in an existing folder.",L"Editor");
|
||||
SetFocus(field);
|
||||
return TRUE;
|
||||
}
|
||||
if(prompt->saving && attributes!=INVALID_FILE_ATTRIBUTES)
|
||||
{
|
||||
showFilesNotice(dialog,L"A file with this name already exists. Choose another name.",L"Editor");
|
||||
SetFocus(field);
|
||||
return TRUE;
|
||||
}
|
||||
prompt->path=path;
|
||||
prompt->format.encoding=encoding;
|
||||
if(prompt->saving)
|
||||
{
|
||||
prompt->format.bom=encoding!=TextEncoding::windows1252 &&
|
||||
IsDlgButtonChecked(dialog,textBom)==BST_CHECKED;
|
||||
for(int i=0;i<4;++i)
|
||||
if(IsDlgButtonChecked(dialog,textFirstLineEnding+i)==BST_CHECKED)
|
||||
prompt->format.lineEnding=static_cast<TextLineEnding>(i);
|
||||
}
|
||||
FilesModalDialog::finish(dialog,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
bool chooseTextSaveOptions(HWND owner,fs::path &destination,ks::files::TextSaveFormat &format)
|
||||
{
|
||||
TextFilePrompt prompt{destination.parent_path(),destination,format,true};
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(612),owner,textFilePrompt,
|
||||
reinterpret_cast<LPARAM>(&prompt))!=IDOK) return false;
|
||||
destination=std::move(prompt.path);
|
||||
format=prompt.format;
|
||||
return true;
|
||||
}
|
||||
|
||||
void openOrCreateText(HWND owner,const Panel &panel)
|
||||
{
|
||||
if(panel.peer)
|
||||
{
|
||||
setStatus(L"Open/create file is available in local panels.");
|
||||
return;
|
||||
}
|
||||
if(panel.directory.empty()) return;
|
||||
TextFilePrompt prompt{panel.directory,{}, {.encoding=ks::files::TextEncoding::automatic}};
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(611),owner,textFilePrompt,
|
||||
reinterpret_cast<LPARAM>(&prompt))!=IDOK) return;
|
||||
const auto attributes=GetFileAttributesW(prompt.path.c_str());
|
||||
const bool draft=attributes==INVALID_FILE_ATTRIBUTES && GetLastError()==ERROR_FILE_NOT_FOUND;
|
||||
ks::files::openTextWindow(owner,prompt.path,true,textWindowDialogs(),nullptr,{},false,
|
||||
{prompt.format.encoding,draft});
|
||||
}
|
||||
|
||||
LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR)
|
||||
{
|
||||
const auto index=GetDlgCtrlID(window)-102;
|
||||
@@ -5257,9 +5546,13 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
|
||||
activatePanel(index);
|
||||
return 0;
|
||||
}
|
||||
const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,lp);
|
||||
const auto row=static_cast<LRESULT>(LOWORD(hit));
|
||||
const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||||
// LB_ITEMFROMPOINT only returns the low 16 bits of the row index.
|
||||
const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,lp);
|
||||
const auto top=SendMessageW(window,LB_GETTOPINDEX,0,0);
|
||||
constexpr LRESULT rowRange=1<<16;
|
||||
auto row=(top&~(rowRange-1))|LOWORD(hit);
|
||||
if(row<top) row+=rowRange;
|
||||
RECT bounds{};
|
||||
const bool rowHit=!HIWORD(hit) && row<count &&
|
||||
SendMessageW(window,LB_GETITEMRECT,row,reinterpret_cast<LPARAM>(&bounds))!=LB_ERR &&
|
||||
@@ -5268,7 +5561,6 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
|
||||
const auto target=rowHit?row:point.y>=0 && message==WM_LBUTTONDOWN?count-1:previous;
|
||||
if(target!=previous && index!=active)
|
||||
{
|
||||
const auto top=SendMessageW(window,LB_GETTOPINDEX,0,0);
|
||||
// The native list can repaint during selection. Activate it only after moving the cursor.
|
||||
const bool visible=IsWindowVisible(window);
|
||||
if(visible) SendMessageW(window,WM_SETREDRAW,FALSE,0);
|
||||
@@ -5724,6 +6016,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
collectDirectoryScans();
|
||||
refreshChangedPanels();
|
||||
showDirectoryScanProgress(panels[active]);
|
||||
}
|
||||
collectFolderSizes();
|
||||
return 0;
|
||||
@@ -6491,6 +6784,12 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
{
|
||||
const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0;
|
||||
const bool shift=(GetKeyState(VK_SHIFT)&0x8000)!=0;
|
||||
if(shift && !ctrl && message.wParam==VK_F4 && !terminalVisible)
|
||||
{
|
||||
if(!(message.lParam & (1LL<<30)) && commandLineAvailable(window))
|
||||
openOrCreateText(window,panels[active]);
|
||||
continue;
|
||||
}
|
||||
if(ctrl && !shift &&
|
||||
(message.wParam=='F' || message.wParam=='C' || message.wParam=='R' ||
|
||||
(message.wParam=='U' && !terminalVisible) ||
|
||||
|
||||
+142
-42
@@ -38,6 +38,15 @@ HANDLE openSource(const std::filesystem::path &path, bool editable)
|
||||
return result;
|
||||
}
|
||||
|
||||
HANDLE trackReplacement(const std::filesystem::path &path)
|
||||
{
|
||||
// A metadata-only handle survives the rename without blocking ReplaceFile.
|
||||
const auto handle=CreateFileW(path.c_str(),0,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
|
||||
nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
|
||||
if(handle==INVALID_HANDLE_VALUE) fail("Track replacement file");
|
||||
return handle;
|
||||
}
|
||||
|
||||
uint64_t fileSize(HANDLE file)
|
||||
{
|
||||
LARGE_INTEGER size{};
|
||||
@@ -97,10 +106,87 @@ std::filesystem::path createTemporary(const std::filesystem::path &directory, Fi
|
||||
if (file.handle == INVALID_HANDLE_VALUE) fail("Create temporary file");
|
||||
return path;
|
||||
}
|
||||
|
||||
bool isUtf16(TextEncoding encoding)
|
||||
{
|
||||
return encoding==TextEncoding::utf16le || encoding==TextEncoding::utf16be;
|
||||
}
|
||||
|
||||
TextDocument::TextDocument(std::filesystem::path path, bool editable) : path_(std::move(path)), editable_(editable)
|
||||
std::string_view signature(TextEncoding encoding)
|
||||
{
|
||||
switch(encoding)
|
||||
{
|
||||
case TextEncoding::utf16le: return "\xff\xfe";
|
||||
case TextEncoding::utf16be: return "\xfe\xff";
|
||||
case TextEncoding::utf8: return "\xef\xbb\xbf";
|
||||
default: return {};
|
||||
}
|
||||
}
|
||||
|
||||
std::wstring decodeMultibyte(std::string_view bytes,UINT codePage,DWORD flags)
|
||||
{
|
||||
const int length=static_cast<int>(bytes.size());
|
||||
const auto required=MultiByteToWideChar(codePage,flags,bytes.data(),length,nullptr,0);
|
||||
if(!required) fail("Decode text");
|
||||
std::wstring units(required,L'\0');
|
||||
if(!MultiByteToWideChar(codePage,flags,bytes.data(),length,units.data(),required)) fail("Decode text");
|
||||
return units;
|
||||
}
|
||||
|
||||
std::string encode(std::string_view utf8,TextEncoding encoding)
|
||||
{
|
||||
if(encoding==TextEncoding::utf8 || utf8.empty()) return std::string(utf8);
|
||||
const auto units=decodeMultibyte(utf8,CP_UTF8,MB_ERR_INVALID_CHARS);
|
||||
if(encoding==TextEncoding::windows1252)
|
||||
{
|
||||
BOOL substituted{};
|
||||
const int length=static_cast<int>(units.size());
|
||||
const auto required=WideCharToMultiByte(1252,WC_NO_BEST_FIT_CHARS,units.data(),length,
|
||||
nullptr,0,nullptr,&substituted);
|
||||
if(!required) fail("Encode Windows-1252");
|
||||
if(substituted) throw std::runtime_error("Some characters cannot be saved as Windows-1252. Choose a Unicode encoding.");
|
||||
std::string bytes(required,'\0');
|
||||
if(!WideCharToMultiByte(1252,WC_NO_BEST_FIT_CHARS,units.data(),length,bytes.data(),required,nullptr,&substituted))
|
||||
fail("Encode Windows-1252");
|
||||
return bytes;
|
||||
}
|
||||
std::string bytes(units.size()*2,'\0');
|
||||
const size_t low=encoding==TextEncoding::utf16le?0:1;
|
||||
for(size_t i=0;i<units.size();++i)
|
||||
{
|
||||
bytes[2*i+low]=static_cast<char>(units[i]&0xff);
|
||||
bytes[2*i+1-low]=static_cast<char>(units[i]>>8);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
std::string convertLineEndings(std::string_view text,TextLineEnding ending)
|
||||
{
|
||||
if(ending==TextLineEnding::preserve) return std::string(text);
|
||||
const std::string_view replacement=ending==TextLineEnding::crlf?"\r\n":ending==TextLineEnding::lf?"\n":"\r";
|
||||
std::string result;
|
||||
result.reserve(text.size());
|
||||
for(size_t start=0;start<text.size();)
|
||||
{
|
||||
const auto next=text.find_first_of("\r\n",start);
|
||||
result.append(text.substr(start,next==text.npos?text.npos:next-start));
|
||||
if(next==text.npos) break;
|
||||
result.append(replacement);
|
||||
start=next+1;
|
||||
if(text[next]=='\r' && start<text.size() && text[start]=='\n') ++start;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
TextDocument::TextDocument(std::filesystem::path path,bool editable,TextEncoding encoding)
|
||||
: path_(std::move(path)), editable_(editable)
|
||||
{
|
||||
if(path_.empty())
|
||||
{
|
||||
if(encoding!=TextEncoding::automatic) encoding_=encoding;
|
||||
return;
|
||||
}
|
||||
File source{openSource(path_, editable)};
|
||||
if (editable)
|
||||
{
|
||||
@@ -115,13 +201,15 @@ TextDocument::TextDocument(std::filesystem::path path, bool editable) : path_(st
|
||||
}
|
||||
size_ = fileSize(source.handle);
|
||||
const auto prefix = read(source.handle, 0, static_cast<size_t>(std::min<uint64_t>(3, size_)));
|
||||
if (prefix.starts_with("\xef\xbb\xbf")) bom_ = 3;
|
||||
else if (prefix.starts_with("\xff\xfe") || prefix.starts_with("\xfe\xff"))
|
||||
if(encoding==TextEncoding::automatic)
|
||||
{
|
||||
encoding_ = prefix.starts_with("\xff") ? Encoding::utf16le : Encoding::utf16be;
|
||||
bom_ = 2;
|
||||
if (size_ % 2) throw std::runtime_error("The UTF-16 file has an incomplete code unit.");
|
||||
encoding=TextEncoding::utf8;
|
||||
for(const auto candidate:{TextEncoding::utf16le,TextEncoding::utf16be})
|
||||
if(prefix.starts_with(signature(candidate))) encoding=candidate;
|
||||
}
|
||||
encoding_=encoding;
|
||||
if(prefix.starts_with(signature(encoding_))) bom_=signature(encoding_).size();
|
||||
if(isUtf16(encoding_) && size_%2) throw std::runtime_error("The UTF-16 file has an incomplete code unit.");
|
||||
source_ = source.release();
|
||||
}
|
||||
|
||||
@@ -135,8 +223,9 @@ const wchar_t *TextDocument::encodingName() const
|
||||
{
|
||||
switch (encoding_)
|
||||
{
|
||||
case Encoding::utf16le: return L"UTF-16 LE";
|
||||
case Encoding::utf16be: return L"UTF-16 BE";
|
||||
case TextEncoding::utf16le: return L"UTF-16 LE";
|
||||
case TextEncoding::utf16be: return L"UTF-16 BE";
|
||||
case TextEncoding::windows1252: return L"Windows-1252";
|
||||
default: return bom_ ? L"UTF-8 BOM" : L"UTF-8";
|
||||
}
|
||||
}
|
||||
@@ -160,40 +249,45 @@ uint64_t TextDocument::boundary(uint64_t page,HANDLE source) const
|
||||
if (page >= pages()) return size_;
|
||||
|
||||
const auto offset = bom_ + page * pageBytes;
|
||||
const auto unit = encoding_ == Encoding::utf8 ? 1u : 2u;
|
||||
const auto unit = isUtf16(encoding_) ? 2u : 1u;
|
||||
const auto sample = read(source, offset - unit,
|
||||
static_cast<size_t>(std::min<uint64_t>(4096 + unit, size_ - offset + unit)));
|
||||
const auto getUnit = [&](size_t i) -> unsigned {
|
||||
const auto first = static_cast<unsigned char>(sample[i]);
|
||||
if (unit == 1) return first;
|
||||
const auto second = static_cast<unsigned char>(sample[i + 1]);
|
||||
return encoding_ == Encoding::utf16le ? first | (second << 8) : (first << 8) | second;
|
||||
return encoding_ == TextEncoding::utf16le ? first | (second << 8) : (first << 8) | second;
|
||||
};
|
||||
if (getUnit(0) == '\n') return offset;
|
||||
for (size_t i = unit; i + unit < sample.size(); i += unit)
|
||||
if (getUnit(i) == '\n') return offset + i;
|
||||
|
||||
size_t i = unit;
|
||||
if (unit == 1)
|
||||
if (encoding_ == TextEncoding::utf8)
|
||||
{
|
||||
// Advance past at most one UTF-8 code point, even on malformed input.
|
||||
while (i < sample.size() && i <= 3 && (getUnit(i) & 0xc0) == 0x80) ++i;
|
||||
}
|
||||
else if (const auto value = getUnit(i); value >= 0xdc00 && value <= 0xdfff) i += unit;
|
||||
else if (isUtf16(encoding_))
|
||||
if (const auto value = getUnit(i); value >= 0xdc00 && value <= 0xdfff) i += unit;
|
||||
if (i == unit && getUnit(0) == '\r' && getUnit(i) == '\n') i += unit;
|
||||
return offset + i - unit;
|
||||
}
|
||||
|
||||
std::string TextDocument::decode(std::string bytes) const
|
||||
{
|
||||
if (encoding_ == Encoding::utf8 || bytes.empty()) return bytes;
|
||||
if (encoding_ == TextEncoding::utf8 || bytes.empty()) return bytes;
|
||||
std::wstring units;
|
||||
units.resize(bytes.size() / 2);
|
||||
for (size_t i = 0; i < units.size(); ++i)
|
||||
if(encoding_==TextEncoding::windows1252) units=decodeMultibyte(bytes,1252,0);
|
||||
else
|
||||
{
|
||||
const auto a = static_cast<unsigned char>(bytes[2 * i]);
|
||||
const auto b = static_cast<unsigned char>(bytes[2 * i + 1]);
|
||||
units[i] = static_cast<wchar_t>(encoding_ == Encoding::utf16le ? a | (b << 8) : (a << 8) | b);
|
||||
units.resize(bytes.size() / 2);
|
||||
for (size_t i = 0; i < units.size(); ++i)
|
||||
{
|
||||
const auto a = static_cast<unsigned char>(bytes[2 * i]);
|
||||
const auto b = static_cast<unsigned char>(bytes[2 * i + 1]);
|
||||
units[i] = static_cast<wchar_t>(encoding_ == TextEncoding::utf16le ? a | (b << 8) : (a << 8) | b);
|
||||
}
|
||||
}
|
||||
const auto length = static_cast<int>(units.size());
|
||||
const int required = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, units.data(), length, nullptr, 0, nullptr, nullptr);
|
||||
@@ -204,25 +298,6 @@ std::string TextDocument::decode(std::string bytes) const
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string TextDocument::encode(std::string_view utf8) const
|
||||
{
|
||||
if (encoding_ == Encoding::utf8 || utf8.empty()) return std::string(utf8);
|
||||
const auto length = static_cast<int>(utf8.size());
|
||||
const int required = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.data(), length, nullptr, 0);
|
||||
if (!required) fail("Encode UTF-16");
|
||||
std::wstring units(required, L'\0');
|
||||
if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.data(), length, units.data(), required))
|
||||
fail("Encode UTF-16");
|
||||
std::string bytes(units.size() * 2, '\0');
|
||||
const int low = encoding_ == Encoding::utf16le ? 0 : 1;
|
||||
for (size_t i = 0; i < units.size(); ++i)
|
||||
{
|
||||
bytes[2 * i + low] = static_cast<char>(units[i] & 0xff);
|
||||
bytes[2 * i + 1 - low] = static_cast<char>(units[i] >> 8);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
std::string TextDocument::readPage(uint64_t page) const
|
||||
{
|
||||
if (const auto it = changes_.find(page); it != changes_.end())
|
||||
@@ -232,6 +307,7 @@ std::string TextDocument::readPage(uint64_t page) const
|
||||
|
||||
std::string TextDocument::readOriginal(uint64_t page) const
|
||||
{
|
||||
if(path_.empty()) return {};
|
||||
File temporary{source_ == INVALID_HANDLE_VALUE ? openSource(path_, false) : INVALID_HANDLE_VALUE};
|
||||
const auto source=source_ == INVALID_HANDLE_VALUE ? temporary.handle : source_;
|
||||
const auto start = boundary(page,source);
|
||||
@@ -298,17 +374,14 @@ bool TextDocument::save()
|
||||
for (const auto &[page, change] : changes_)
|
||||
{
|
||||
copyUntil(offset, boundary(page));
|
||||
append(encode(read(spool_, change.offset, change.size)));
|
||||
append(encode(read(spool_, change.offset, change.size),encoding_));
|
||||
offset = boundary(page + 1);
|
||||
}
|
||||
copyUntil(offset, size_);
|
||||
if (!FlushFileBuffers(output.handle)) fail("Flush saved file");
|
||||
CloseHandle(output.release());
|
||||
|
||||
// A metadata-only handle survives the rename without blocking ReplaceFile's exclusive open.
|
||||
File replacement{CreateFileW(pending.path.c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
|
||||
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)};
|
||||
if (replacement.handle == INVALID_HANDLE_VALUE) fail("Track replacement file");
|
||||
File replacement{trackReplacement(pending.path)};
|
||||
File current{openSource(path_, true)};
|
||||
if (!sameFile(source_, current.handle)) throw std::runtime_error("The file was replaced outside KSwitcher.");
|
||||
const auto backup = temporaryPath(path_.parent_path());
|
||||
@@ -336,4 +409,31 @@ bool TextDocument::save()
|
||||
spoolSize_ = 0;
|
||||
return source_ != INVALID_HANDLE_VALUE;
|
||||
}
|
||||
|
||||
bool TextDocument::saveNew(std::filesystem::path path,TextSaveFormat format)
|
||||
{
|
||||
if(!path_.empty() || !editable_) throw std::logic_error("The document is not a new editable file.");
|
||||
if(format.encoding==TextEncoding::automatic) format.encoding=TextEncoding::utf8;
|
||||
const auto bytes=encode(convertLineEndings(readPage(0),format.lineEnding),format.encoding);
|
||||
const auto bom=format.bom?signature(format.encoding):std::string_view{};
|
||||
PendingSave pending;
|
||||
File output;
|
||||
pending.path=createTemporary(path.parent_path(),output,FILE_ATTRIBUTE_NORMAL);
|
||||
write(output.handle,bom);
|
||||
write(output.handle,bytes);
|
||||
if(!FlushFileBuffers(output.handle)) fail("Flush saved file");
|
||||
CloseHandle(output.release());
|
||||
File replacement{trackReplacement(pending.path)};
|
||||
if(!MoveFileExW(pending.path.c_str(),path.c_str(),MOVEFILE_WRITE_THROUGH)) fail("Create new file");
|
||||
pending.path.clear();
|
||||
path_=std::move(path);
|
||||
encoding_=format.encoding;
|
||||
bom_=bom.size();
|
||||
size_=bom_+bytes.size();
|
||||
changes_.clear();
|
||||
if(spool_!=INVALID_HANDLE_VALUE) CloseHandle(std::exchange(spool_,INVALID_HANDLE_VALUE));
|
||||
spoolSize_=0;
|
||||
source_=ReOpenFile(replacement.handle,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,0);
|
||||
return source_!=INVALID_HANDLE_VALUE;
|
||||
}
|
||||
}
|
||||
@@ -9,13 +9,24 @@
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
enum class TextEncoding { automatic, utf8, utf16le, utf16be, windows1252 };
|
||||
enum class TextLineEnding { preserve, crlf, lf, cr };
|
||||
|
||||
struct TextSaveFormat
|
||||
{
|
||||
TextEncoding encoding=TextEncoding::utf8;
|
||||
bool bom{};
|
||||
TextLineEnding lineEnding=TextLineEnding::preserve;
|
||||
};
|
||||
|
||||
class TextDocument
|
||||
{
|
||||
public:
|
||||
static constexpr uint64_t pageBytes = 1024 * 1024;
|
||||
static constexpr size_t editLimit = 8 * pageBytes;
|
||||
|
||||
explicit TextDocument(std::filesystem::path path, bool editable = true);
|
||||
explicit TextDocument(std::filesystem::path path, bool editable = true,
|
||||
TextEncoding encoding=TextEncoding::automatic);
|
||||
~TextDocument();
|
||||
TextDocument(const TextDocument &) = delete;
|
||||
TextDocument &operator=(const TextDocument &) = delete;
|
||||
@@ -29,10 +40,10 @@ public:
|
||||
bool modified() const { return !changes_.empty(); }
|
||||
bool modifiedWith(uint64_t page, std::string_view current) const;
|
||||
bool save();
|
||||
bool saveNew(std::filesystem::path path, TextSaveFormat format);
|
||||
const wchar_t *encodingName() const;
|
||||
|
||||
private:
|
||||
enum class Encoding { utf8, utf16le, utf16be };
|
||||
struct Change { uint64_t offset; size_t size; };
|
||||
|
||||
std::filesystem::path path_;
|
||||
@@ -40,13 +51,12 @@ private:
|
||||
HANDLE spool_ = INVALID_HANDLE_VALUE;
|
||||
uint64_t size_{}, spoolSize_{};
|
||||
size_t bom_{};
|
||||
Encoding encoding_ = Encoding::utf8;
|
||||
TextEncoding encoding_ = TextEncoding::utf8;
|
||||
bool editable_;
|
||||
std::map<uint64_t, Change> changes_;
|
||||
|
||||
std::string decode(std::string bytes) const;
|
||||
uint64_t boundary(uint64_t page,HANDLE source) const;
|
||||
std::string readOriginal(uint64_t page) const;
|
||||
std::string encode(std::string_view utf8) const;
|
||||
};
|
||||
}
|
||||
+113
-30
@@ -729,13 +729,18 @@ class TextWindow
|
||||
{
|
||||
public:
|
||||
TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const lan::FilesPeer *peer,
|
||||
std::string_view fragment)
|
||||
std::string_view fragment,TextOpenOptions options)
|
||||
: original(std::move(path)), peerId(peer?peer->id:""), filename(original.filename().wstring()),
|
||||
edit(editable), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
|
||||
edit(editable), draft(options.draft), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
|
||||
search{dialogs}, previewFragment(fragment)
|
||||
{
|
||||
if (peer) remote=std::make_unique<RemoteTextFile>(RemoteTextFile{*peer,original});
|
||||
else document=std::make_unique<TextDocument>(original,edit);
|
||||
else document=std::make_unique<TextDocument>(draft?std::filesystem::path{}:original,edit,options.encoding);
|
||||
if(options.encoding!=TextEncoding::automatic)
|
||||
{
|
||||
newFormat.encoding=options.encoding;
|
||||
newFormat.bom=options.encoding==TextEncoding::utf16le || options.encoding==TextEncoding::utf16be;
|
||||
}
|
||||
for (int index = 0; index < GetLexerCount(); ++index)
|
||||
{
|
||||
char name[128]{};
|
||||
@@ -764,6 +769,9 @@ private:
|
||||
std::unique_ptr<TextDocument> document;
|
||||
std::wstring filename;
|
||||
bool edit{}, loading{}, stagedDirty{}, closeAfterSave{}, insertRejected{};
|
||||
bool draft{};
|
||||
TextSaveFormat newFormat;
|
||||
std::filesystem::path pendingSavePath;
|
||||
HICON smallIcon{},largeIcon{};
|
||||
TextPreferences prefs;
|
||||
TextWindowFont filesFont;
|
||||
@@ -856,6 +864,9 @@ private:
|
||||
bool dirty() const { return stagedDirty || (!busy() && uploadPending) || currentChanged(); }
|
||||
bool busy() const { return saving.valid(); }
|
||||
void invalidate() const { InvalidateRect(window, nullptr, FALSE); }
|
||||
RECT statusBounds() const;
|
||||
void invalidateStatus() const;
|
||||
void invalidateHints() const;
|
||||
|
||||
void initializeDocument();
|
||||
void finishOpen();
|
||||
@@ -1342,22 +1353,25 @@ void TextWindow::finishOpen()
|
||||
void TextWindow::saveFile(bool closeWhenDone)
|
||||
{
|
||||
if (busy() || !edit) return;
|
||||
auto destination=original;
|
||||
if(draft && !search.style.saveOptions(window,destination,newFormat)) return;
|
||||
stagePage();
|
||||
if (!stagedDirty && !uploadPending)
|
||||
if (!draft && !stagedDirty && !uploadPending)
|
||||
{
|
||||
if (closeWhenDone) DestroyWindow(window);
|
||||
else if (std::exchange(switchAfterSave, false)) changeMode();
|
||||
return;
|
||||
}
|
||||
pendingCaret = send(SCI_GETCURRENTPOS);
|
||||
if(draft) pendingSavePath=destination;
|
||||
closeAfterSave = closeWhenDone;
|
||||
if (!SetTimer(window, saveTimer, 75, nullptr)) throw std::runtime_error("Cannot start the save timer.");
|
||||
send(SCI_SETREADONLY, TRUE);
|
||||
try
|
||||
{
|
||||
saving=std::async(std::launch::async,[this]
|
||||
saving=std::async(std::launch::async,[this,destination=std::move(destination)]
|
||||
{
|
||||
const auto reopened=document->save();
|
||||
const auto reopened=draft?document->saveNew(destination,newFormat):document->save();
|
||||
if(remote)
|
||||
{
|
||||
uploadPending=true;
|
||||
@@ -1384,6 +1398,14 @@ void TextWindow::finishSave()
|
||||
const auto change = std::exchange(switchAfterSave, false);
|
||||
const auto reopened = saving.get();
|
||||
stagedDirty = false;
|
||||
const bool created=std::exchange(draft,false);
|
||||
if(created)
|
||||
{
|
||||
original=std::move(pendingSavePath);
|
||||
filename=original.filename().wstring();
|
||||
navigationHistory.clear();
|
||||
updateTitle();
|
||||
}
|
||||
if (!reopened)
|
||||
{
|
||||
search.style.message(window, L"The file was saved. Reopen it to continue editing.");
|
||||
@@ -1392,6 +1414,12 @@ void TextWindow::finishSave()
|
||||
}
|
||||
if (closeAfterSave) { DestroyWindow(window); return; }
|
||||
if (change) { changeMode(); return; }
|
||||
if(created)
|
||||
{
|
||||
initializeDocument();
|
||||
send(SCI_GOTOPOS,std::min<LRESULT>(pendingCaret,send(SCI_GETLENGTH)));
|
||||
return;
|
||||
}
|
||||
if (pageTotal == 1 && document->pages() == 1)
|
||||
{
|
||||
fileSize = document->size();
|
||||
@@ -1408,7 +1436,7 @@ void TextWindow::requestClose()
|
||||
if (busy()) return;
|
||||
if (needsSave())
|
||||
{
|
||||
const auto answer = search.style.confirmSave(window);
|
||||
const auto answer = search.style.confirmSave(window,draft);
|
||||
if (answer == IDCANCEL) return;
|
||||
if (answer == IDYES) { saveFile(true); return; }
|
||||
if (answer != IDNO) return;
|
||||
@@ -1424,9 +1452,10 @@ bool TextWindow::needsSave() const
|
||||
void TextWindow::toggleMode()
|
||||
{
|
||||
if (busy() || navigation.valid()) return;
|
||||
if(draft) return;
|
||||
if (edit && needsSave())
|
||||
{
|
||||
const auto answer = search.style.confirmSave(window);
|
||||
const auto answer = search.style.confirmSave(window,false);
|
||||
if (answer == IDYES)
|
||||
{
|
||||
switchAfterSave = true;
|
||||
@@ -1861,6 +1890,58 @@ void TextWindow::layout()
|
||||
invalidate();
|
||||
}
|
||||
|
||||
RECT TextWindow::statusBounds() const
|
||||
{
|
||||
RECT bounds{};
|
||||
GetClientRect(window,&bounds);
|
||||
bounds.top=chromeHeight();
|
||||
bounds.bottom=2*bounds.top;
|
||||
return bounds;
|
||||
}
|
||||
|
||||
void TextWindow::invalidateStatus() const
|
||||
{
|
||||
const auto bounds=statusBounds();
|
||||
InvalidateRect(window,&bounds,FALSE);
|
||||
}
|
||||
|
||||
void TextWindow::invalidateHints() const
|
||||
{
|
||||
RECT bounds{};
|
||||
GetClientRect(window,&bounds);
|
||||
bounds.top=std::max(0L,bounds.bottom-chromeHeight());
|
||||
InvalidateRect(window,&bounds,FALSE);
|
||||
}
|
||||
|
||||
void drawEditorStatus(HDC dc,RECT bounds,HFONT font,COLORREF background,COLORREF foreground,
|
||||
int inset,const std::wstring &status)
|
||||
{
|
||||
const auto width=bounds.right-bounds.left,height=bounds.bottom-bounds.top;
|
||||
if(width<=0 || height<=0) return;
|
||||
const auto memory=CreateCompatibleDC(dc);
|
||||
const auto bitmap=memory?CreateCompatibleBitmap(dc,width,height):nullptr;
|
||||
const auto target=bitmap?memory:dc;
|
||||
const auto oldBitmap=bitmap?SelectObject(memory,bitmap):nullptr;
|
||||
const auto oldFont=SelectObject(target,font);
|
||||
auto row=bitmap?RECT{0,0,width,height}:bounds;
|
||||
SetDCBrushColor(target,background);
|
||||
FillRect(target,&row,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
SetBkMode(target,TRANSPARENT);
|
||||
SetTextColor(target,foreground);
|
||||
row.left+=inset;
|
||||
row.right-=inset;
|
||||
if(row.left<row.right)
|
||||
DrawTextW(target,status.c_str(),-1,&row,DT_RIGHT|DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS|DT_NOPREFIX);
|
||||
SelectObject(target,oldFont);
|
||||
if(bitmap)
|
||||
{
|
||||
BitBlt(dc,bounds.left,bounds.top,width,height,memory,0,0,SRCCOPY);
|
||||
SelectObject(memory,oldBitmap);
|
||||
DeleteObject(bitmap);
|
||||
}
|
||||
if(memory) DeleteDC(memory);
|
||||
}
|
||||
|
||||
void TextWindow::paint()
|
||||
{
|
||||
PAINTSTRUCT paint{};
|
||||
@@ -1870,12 +1951,12 @@ void TextWindow::paint()
|
||||
const auto row = chromeHeight();
|
||||
const auto brush = static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
|
||||
SetDCBrushColor(dc, color(TextColor::background));
|
||||
FillRect(dc, &client, brush);
|
||||
const RECT body{0,2*row,client.right,std::max<LONG>(2*row,client.bottom-row)};
|
||||
FillRect(dc, &body, brush);
|
||||
SetDCBrushColor(dc, color(TextColor::chromebg));
|
||||
RECT menuBar{0, 0, client.right, row};
|
||||
RECT top{0, row, client.right, 2 * row};
|
||||
const RECT top=statusBounds();
|
||||
RECT bottom{0, client.bottom - row, client.right, client.bottom};
|
||||
FillRect(dc, &top, brush);
|
||||
FillRect(dc, &bottom, brush);
|
||||
FillRect(dc, &menuBar, brush);
|
||||
const auto chromeFont = createChromeFont();
|
||||
@@ -1904,27 +1985,27 @@ void TextWindow::paint()
|
||||
}
|
||||
SetTextColor(dc, color(TextColor::chrome));
|
||||
bottom.left += scale(7);
|
||||
const auto position = send(SCI_GETCURRENTPOS);
|
||||
const auto line = send(SCI_LINEFROMPOSITION, position) + 1;
|
||||
const auto column = send(SCI_GETCOLUMN, position) + 1;
|
||||
const auto displayLanguage = textLanguageLabel(language);
|
||||
auto status = filename + (edit ? L" (Edit)" : L" (View)") + (dirty() ? L" *" : L"") +
|
||||
L" │ " + (document?document->encodingName():L"Loading…") + L" │ " + displayLanguage +
|
||||
L" │ Ln " + std::to_wstring(line) + L":" + std::to_wstring(column);
|
||||
if (pageTotal > 1)
|
||||
status += L" │ Page " + std::to_wstring(page + 1) + L"/" + std::to_wstring(pageTotal) +
|
||||
L" @ " + std::to_wstring(pageOffset);
|
||||
status += L" │ " + std::to_wstring(fileSize) + L" B";
|
||||
RECT statusPaint{};
|
||||
if(IntersectRect(&statusPaint,&top,&paint.rcPaint))
|
||||
{
|
||||
const auto position=send(SCI_GETCURRENTPOS);
|
||||
const auto line=send(SCI_LINEFROMPOSITION,position)+1;
|
||||
const auto column=send(SCI_GETCOLUMN,position)+1;
|
||||
auto status=filename+(edit?L" (Edit)":L" (View)")+(dirty()?L" *":L"")+
|
||||
L" │ "+(document?document->encodingName():L"Loading…")+L" │ "+textLanguageLabel(language)+
|
||||
L" │ Ln "+std::to_wstring(line)+L":"+std::to_wstring(column);
|
||||
if(pageTotal>1)
|
||||
status+=L" │ Page "+std::to_wstring(page+1)+L"/"+std::to_wstring(pageTotal)+
|
||||
L" @ "+std::to_wstring(pageOffset);
|
||||
status+=L" │ "+std::to_wstring(fileSize)+L" B";
|
||||
drawEditorStatus(dc,top,chromeFont,color(TextColor::chromebg),color(TextColor::chrome),scale(12),status);
|
||||
}
|
||||
const auto hints = busy() ? L"Saving…" : insertRejected ? L"Page edit limit: 8 MiB" :
|
||||
edit ? L"F2 Save F3 Find next F5 Go to page F6 View Ctrl+PgUp/PgDn Pages F10 Close" :
|
||||
previewVisible ? L"F6 Edit Ctrl+W Close" :
|
||||
previewWanted ? L"Rendering Markdown… Ctrl+W Close" :
|
||||
L"F3 Find next F5 Go to page F6 Edit Ctrl+PgUp/PgDn Pages F10 Close";
|
||||
constexpr UINT format = DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS | DT_NOPREFIX;
|
||||
top.left += scale(12);
|
||||
top.right -= scale(12);
|
||||
if (top.left < top.right)
|
||||
DrawTextW(dc, status.c_str(), -1, &top, format | DT_RIGHT);
|
||||
DrawTextW(dc, hints, -1, &bottom, format);
|
||||
SelectObject(dc, previous);
|
||||
DeleteObject(chromeFont);
|
||||
@@ -2044,6 +2125,7 @@ void TextWindow::notify(const SCNotification ¬ice)
|
||||
case SCN_MODIFIED:
|
||||
if (notice.modificationType & SC_MOD_INSERTCHECK)
|
||||
{
|
||||
const auto hadWarning=insertRejected;
|
||||
if (send(SCI_GETLENGTH) + notice.length > static_cast<LRESULT>(TextDocument::editLimit))
|
||||
{
|
||||
send(SCI_CHANGEINSERTION, 0, reinterpret_cast<LPARAM>(""));
|
||||
@@ -2051,6 +2133,7 @@ void TextWindow::notify(const SCNotification ¬ice)
|
||||
MessageBeep(MB_ICONWARNING);
|
||||
}
|
||||
else insertRejected = false;
|
||||
if(hadWarning!=insertRejected) invalidateHints();
|
||||
}
|
||||
if (notice.modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT))
|
||||
{
|
||||
@@ -2058,8 +2141,8 @@ void TextWindow::notify(const SCNotification ¬ice)
|
||||
undoBytes += static_cast<size_t>(notice.length) + 64;
|
||||
if (undoBytes >= 32 * TextDocument::pageBytes)
|
||||
PostMessageW(window, trimUndo, 0, 0);
|
||||
invalidateStatus();
|
||||
}
|
||||
invalidate();
|
||||
break;
|
||||
case SCN_CHARADDED:
|
||||
if (edit && prefs.autoIndent && (notice.ch == '\n' || (notice.ch == '\r' && send(SCI_GETEOLMODE) == SC_EOL_CR)))
|
||||
@@ -2079,7 +2162,7 @@ void TextWindow::notify(const SCNotification ¬ice)
|
||||
case SCN_UPDATEUI:
|
||||
case SCN_SAVEPOINTREACHED:
|
||||
case SCN_SAVEPOINTLEFT:
|
||||
invalidate();
|
||||
invalidateStatus();
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -2458,7 +2541,7 @@ HWND findOpenDocument(const std::filesystem::path &path,const lan::FilesPeer *pe
|
||||
}
|
||||
|
||||
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const lan::FilesPeer *peer,std::string_view fragment,bool newWindow)
|
||||
const lan::FilesPeer *peer,std::string_view fragment,bool newWindow,TextOpenOptions options)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -2490,7 +2573,7 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD
|
||||
return Scintilla_RegisterClasses(instance) && RegisterClassW(&type);
|
||||
}();
|
||||
if(!registered) throw std::runtime_error("Cannot register the text window.");
|
||||
auto state=std::make_shared<TextWindow>(original,edit,dialogs,peer,fragment);
|
||||
auto state=std::make_shared<TextWindow>(original,edit,dialogs,peer,fragment,options);
|
||||
const auto title=std::wstring(edit?L"Editor — ":L"Viewer — ")+
|
||||
(peer?peer->name+L" · ":std::wstring{})+path.wstring();
|
||||
RECT bounds{};
|
||||
|
||||
+11
-2
@@ -4,6 +4,7 @@
|
||||
#include <filesystem>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
#include "files_text_document.h"
|
||||
|
||||
namespace ks::lan { struct FilesPeer; }
|
||||
|
||||
@@ -37,7 +38,7 @@ void installFarHistoryKey(HWND field,int arrowId);
|
||||
|
||||
struct TextDialogs
|
||||
{
|
||||
INT_PTR (*confirmSave)(HWND);
|
||||
INT_PTR (*confirmSave)(HWND,bool draft);
|
||||
INT_PTR (*paint)(HWND, UINT, WPARAM, LPARAM, const wchar_t *);
|
||||
INT_PTR (*paintSearch)(HWND, UINT, WPARAM, LPARAM);
|
||||
void (*prepare)(HWND);
|
||||
@@ -49,10 +50,18 @@ struct TextDialogs
|
||||
void (*finish)(HWND,INT_PTR);
|
||||
bool (*dismissOwned)(HWND);
|
||||
bool (*confirmExisting)(HWND);
|
||||
bool (*saveOptions)(HWND,std::filesystem::path &,TextSaveFormat &);
|
||||
};
|
||||
|
||||
struct TextOpenOptions
|
||||
{
|
||||
TextEncoding encoding=TextEncoding::automatic;
|
||||
bool draft{};
|
||||
};
|
||||
|
||||
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false);
|
||||
const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false,
|
||||
TextOpenOptions options={});
|
||||
void textWindowOwnerClosed();
|
||||
bool cycleTextWindows(HWND current,bool reverse);
|
||||
}
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
#include "platform.h"
|
||||
namespace ks
|
||||
{
|
||||
inline constexpr wchar_t AppVersion[] = L"0.6.114";
|
||||
inline constexpr wchar_t AppVersion[] = L"0.6.116";
|
||||
inline constexpr UINT UpdateMessage = WM_APP + 7;
|
||||
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
|
||||
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
|
||||
|
||||
@@ -3,6 +3,7 @@ param(
|
||||
[Parameter(Mandatory)][string]$Fixture,
|
||||
[switch]$SystemOpenOnly,
|
||||
[switch]$TerminalOnly,
|
||||
[int]$ScanEntries = 0,
|
||||
[string]$Node='node'
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
@@ -12,6 +13,10 @@ using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
public static class FilesActivationUi {
|
||||
public static void CreateScanFiles(string directory, int count) {
|
||||
for (int i = 0; i < count; i++)
|
||||
using (System.IO.File.Create(System.IO.Path.Combine(directory, i.ToString("D6") + ".txt"))) {}
|
||||
}
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Rect { public int Left, Top, Right, Bottom; }
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
@@ -202,7 +207,7 @@ $extension = ".ksfiles$unique"
|
||||
$progId = "KSwitcher.Files.Test.$unique"
|
||||
$saved = @{}
|
||||
$profileValues = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'LeftWide', 'RightWide',
|
||||
'ShowDetails', 'StatusFields', 'CommandHistory', 'WindowPlacement'
|
||||
'ShowDetails', 'StatusFields', 'CommandHistory', 'CommandHistoryKey', 'PreviousCommandKey', 'WindowPlacement'
|
||||
$process = $null
|
||||
$trace = $null
|
||||
$webviewFlags=$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
|
||||
@@ -263,6 +268,13 @@ function startTerminalFixture() {
|
||||
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS="--remote-debugging-port=$port"
|
||||
$env:WEBVIEW2_USER_DATA_FOLDER=Join-Path $root 'webview'
|
||||
}
|
||||
if($SystemOpenOnly) {
|
||||
$profile.SetValue('PreviousCommandKey',0x0245,'DWord')
|
||||
$profile.SetValue('CommandHistoryKey',0x0477,'DWord')
|
||||
}
|
||||
if ($ScanEntries) {
|
||||
[FilesActivationUi]::CreateScanFiles("$leftDir\Test folder", $ScanEntries)
|
||||
}
|
||||
$process = Start-Process -FilePath $testExe -ArgumentList '--terminal-output-trace' -PassThru
|
||||
$trace = Join-Path ([IO.Path]::GetTempPath()) "KSwitcher.Files.terminal-trace-$($process.Id).log"
|
||||
Wait-Until 'Files window' { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
|
||||
@@ -273,6 +285,49 @@ function startTerminalFixture() {
|
||||
$output = [FilesActivationUi]::GetDlgItem($window, 145)
|
||||
$inputBox = [FilesActivationUi]::FindWindowEx($window, [IntPtr]::Zero, 'Edit', $null)
|
||||
|
||||
if ($ScanEntries) {
|
||||
Wait-Until 'visible Files window' { [FilesActivationUi]::Activate($window) }
|
||||
Wait-Until 'folder fixture row' { (Find-Row $left '[Test folder]') -ge 0 }
|
||||
$folderRow = Find-Row $left '[Test folder]'
|
||||
[void][FilesActivationUi]::Send($left, 0x186, [IntPtr]$folderRow, [IntPtr]::Zero)
|
||||
Press-Enter $inputBox
|
||||
Wait-Until 'nonzero folder scan progress' {
|
||||
[FilesActivationUi]::IsWindowVisible($status) -and
|
||||
(Read-Text $status) -match '^Reading ([1-9][0-9]*) \[Esc\]$'
|
||||
}
|
||||
$progress = Read-Text $status
|
||||
[void][FilesActivationUi]::PostMessage($inputBox, 0x100, [IntPtr]27, [IntPtr]::Zero)
|
||||
Wait-Until 'partial folder result' { (Read-Text $status) -match '^Partial: \d+$' }
|
||||
$partial = [FilesActivationUi]::Send($left, 0x18B, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() - 1
|
||||
$partialStatus = Read-Text $status
|
||||
if ($partial -le 0 -or $partial -ge $ScanEntries -or
|
||||
$partialStatus -ne "Partial: $partial" -or
|
||||
(Read-Text ([FilesActivationUi]::GetDlgItem($window,142))) -ne "$leftDir\Test folder") {
|
||||
throw "Unexpected partial listing of $partial entries."
|
||||
}
|
||||
$keys = New-Object -ComObject WScript.Shell
|
||||
$fullScan = [Diagnostics.Stopwatch]::StartNew()
|
||||
$keys.SendKeys('^r')
|
||||
Wait-Until 'complete folder result after Ctrl+R' {
|
||||
[FilesActivationUi]::Send($left, 0x18B, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq $ScanEntries + 1
|
||||
}
|
||||
$fullScan.Stop()
|
||||
Write-Output "$progress. $partialStatus. Full scan: $ScanEntries files in $($fullScan.ElapsedMilliseconds) ms."
|
||||
$target = 65536
|
||||
[void][FilesActivationUi]::Send($left, 0x197, [IntPtr]$target, [IntPtr]::Zero)
|
||||
if ([FilesActivationUi]::Send($left, 0x18E, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -ne $target) {
|
||||
throw "Could not scroll row $target to the top."
|
||||
}
|
||||
$point = [IntPtr]((2 -shl 16) -bor 6)
|
||||
[void][FilesActivationUi]::PostMessage($left, 0x201, [IntPtr]1, $point)
|
||||
[void][FilesActivationUi]::PostMessage($left, 0x202, [IntPtr]::Zero, $point)
|
||||
Wait-Until 'mouse selection past the 16-bit row limit' {
|
||||
[FilesActivationUi]::Send($left, 0x188, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq $target
|
||||
}
|
||||
Write-Output "Clicked row $target after scrolling it to the top."
|
||||
return
|
||||
}
|
||||
|
||||
if($SystemOpenOnly) {
|
||||
$keys = New-Object -ComObject WScript.Shell
|
||||
$explorer = New-Object -ComObject Shell.Application
|
||||
@@ -313,6 +368,27 @@ function startTerminalFixture() {
|
||||
Wait-Until 'plain Enter invoking the default Windows file association' {
|
||||
(Test-Path -LiteralPath "$document.opened") -and [IO.File]::ReadAllText("$document.opened") -eq 'opened'
|
||||
}
|
||||
$command="start '$($document.Replace("'","''"))'"
|
||||
Wait-Until 'the system open action in terminal output and command history' {
|
||||
$history=$profile.GetValue('CommandHistory')
|
||||
[FilesActivationUi]::IsWindowVisible($output) -and $history -and
|
||||
([Text.Encoding]::Unicode.GetString($history).Split([char]0) -ccontains $command) -and
|
||||
(Select-String -LiteralPath $trace -Pattern ('^'+[regex]::Escape($document.Substring(0,24))) -Quiet)
|
||||
}
|
||||
Wait-Until 'Files active for command history' { [FilesActivationUi]::Activate($window) }
|
||||
$keys.SendKeys('%{F8}')
|
||||
$historyDialog=[IntPtr]::Zero
|
||||
Wait-Until 'command history showing only the opened file path' {
|
||||
$script:historyDialog=[FilesActivationUi]::GetForegroundWindow()
|
||||
$list=[FilesActivationUi]::GetDlgItem($historyDialog,324)
|
||||
$list -ne [IntPtr]::Zero -and (Find-Row $list $document) -ge 0
|
||||
}
|
||||
$historyList=[FilesActivationUi]::GetDlgItem($historyDialog,324)
|
||||
$historyRow=Find-Row $historyList $document
|
||||
[void][FilesActivationUi]::Send($historyList,0x186,[IntPtr]$historyRow,[IntPtr]::Zero)
|
||||
[void][FilesActivationUi]::PostMessage($historyDialog,0x111,[IntPtr]1,[IntPtr]::Zero)
|
||||
Wait-Until 'selecting the history path restoring a runnable command' { (Read-Text $inputBox) -ceq $command }
|
||||
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'')
|
||||
Write-Output 'Verified Shift+Enter opens folders in Explorer. Both Enter and Shift+Enter invoke the default file action.'
|
||||
Remove-Item -LiteralPath "$document.opened"
|
||||
}
|
||||
|
||||
@@ -85,6 +85,8 @@ try {
|
||||
})()`), 'the terminal output fixture');
|
||||
assert.equal(selection, 'terminal-output-copy-fixture');
|
||||
} else if (terminalScenario) {
|
||||
assert.equal(await evaluate('terminal.options.cursorInactiveStyle'), 'none');
|
||||
assert.equal(await evaluate('document.querySelectorAll(".xterm-cursor-outline").length'), 0);
|
||||
await evaluate('document.querySelector(".xterm-helper-textarea").focus()');
|
||||
const key = scenario === 'terminal-copy'
|
||||
? { key:'Insert', code:'Insert', modifiers:2, windowsVirtualKeyCode:45 }
|
||||
|
||||
@@ -57,7 +57,7 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int)
|
||||
return font;
|
||||
};
|
||||
dialogs.confirmExisting=[](HWND){return true;};
|
||||
dialogs.confirmSave=[](HWND)->INT_PTR {return IDYES;};
|
||||
dialogs.confirmSave=[](HWND,bool)->INT_PTR {return IDYES;};
|
||||
dialogs.message=[](HWND,const wchar_t *message){log(message);};
|
||||
dialogs.dismissOwned=[](HWND){return false;};
|
||||
files::openTextWindow(owner,document,false,dialogs,&peer);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
param([Parameter(Mandatory)][string]$Executable,[switch]$KeyboardCursorOnly)
|
||||
param([Parameter(Mandatory)][string]$Executable,[switch]$KeyboardCursorOnly,[switch]$CreateFileOnly)
|
||||
$ErrorActionPreference='Stop'
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
Add-Type @"
|
||||
@@ -19,6 +19,21 @@ public static class SearchArrowTest {
|
||||
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hwnd, IntPtr after, int x, int y, int w, int h, uint flags);
|
||||
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
|
||||
[DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr hwnd, IntPtr dc, uint flags);
|
||||
[DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr hwnd);
|
||||
[DllImport("user32.dll")] static extern int ReleaseDC(IntPtr hwnd, IntPtr dc);
|
||||
[DllImport("user32.dll")] public static extern bool InvalidateRect(IntPtr hwnd, IntPtr rect, bool erase);
|
||||
[DllImport("gdi32.dll")] static extern uint GetPixel(IntPtr dc, int x, int y);
|
||||
[DllImport("gdi32.dll")] static extern bool SetPixelV(IntPtr dc, int x, int y, uint color);
|
||||
public static bool EditorMenuProbe(IntPtr window, bool write) {
|
||||
const uint color = 0x00ff00ff;
|
||||
var dc = GetDC(window);
|
||||
if (dc == IntPtr.Zero) throw new InvalidOperationException("Cannot sample the editor.");
|
||||
try {
|
||||
if (write && !SetPixelV(dc, 4, 4, color))
|
||||
throw new InvalidOperationException("Cannot mark the editor menu.");
|
||||
return GetPixel(dc, 4, 4) == color;
|
||||
} finally { ReleaseDC(window, dc); }
|
||||
}
|
||||
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hwnd, out Rect rect);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindow(IntPtr hwnd);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hwnd);
|
||||
@@ -269,6 +284,73 @@ try {
|
||||
[SearchArrowTest]::SendText($leftPanel,0x1A2,-1,'A.txt').ToInt64() -ge 0 -and
|
||||
[SearchArrowTest]::SendText($rightPanel,0x1A2,-1,'A.txt').ToInt64() -ge 0
|
||||
})
|
||||
if ($CreateFileOnly) {
|
||||
function Assert-DialogSurface($Dialog, [int]$Red, [int]$Green) {
|
||||
$bounds=Read-Bounds $Dialog
|
||||
$bitmap=[Drawing.Bitmap]::new(1,1)
|
||||
try {
|
||||
$graphics=[Drawing.Graphics]::FromImage($bitmap)
|
||||
try {
|
||||
[void](Wait-Until {
|
||||
$graphics.CopyFromScreen(($bounds.Left+4),($bounds.Top+4),0,0,$bitmap.Size)
|
||||
$pixel=$bitmap.GetPixel(0,0)
|
||||
$pixel.R -eq $Red -and $pixel.G -eq $Green -and $pixel.B -eq $Green
|
||||
})
|
||||
} finally { $graphics.Dispose() }
|
||||
} finally { $bitmap.Dispose() }
|
||||
}
|
||||
$keyboard=New-Object -ComObject WScript.Shell
|
||||
[void](Wait-Until { $keyboard.AppActivate($process.Id) })
|
||||
$keyboard.SendKeys('+{F4}')
|
||||
$open=Wait-Until { Find-Window '#32770' $process.Id 461 }
|
||||
Assert-DialogSurface $open 192 192
|
||||
Post $open 0x111 1
|
||||
$editor=Wait-Until { Find-Window 'KSwitcher.Files.Text' $process.Id }
|
||||
$title=[Text.StringBuilder]::new(1024)
|
||||
[void][SearchArrowTest]::GetText($editor,0xD,$title.Capacity,$title)
|
||||
if ($title.ToString() -notmatch '(New_File_[0-9-]+_[0-9.]+\.txt)$') { throw "Missing generated name in $title." }
|
||||
$generated=$Matches[1]
|
||||
if (Test-Path -LiteralPath (Join-Path $scratch $generated)) { throw 'Opening a draft created a file.' }
|
||||
$control=Wait-Until { [SearchArrowTest]::FindWindowEx($editor,0,'Scintilla',[NullString]::Value) }
|
||||
Start-Sleep -Milliseconds 150
|
||||
if (![SearchArrowTest]::EditorMenuProbe($editor,$true)) { throw 'Cannot mark the editor menu for the repaint check.' }
|
||||
foreach($ch in 'First'.ToCharArray()){Post $control 0x102 ([int]$ch)}
|
||||
Post $control 0x100 13
|
||||
foreach($ch in 'Second'.ToCharArray()){Post $control 0x102 ([int]$ch)}
|
||||
[void](Wait-Until { [SearchArrowTest]::Send($control,2159,0,0).ToInt64() })
|
||||
Start-Sleep -Milliseconds 150
|
||||
$menuWasPreserved=[SearchArrowTest]::EditorMenuProbe($editor,$false)
|
||||
[void][SearchArrowTest]::InvalidateRect($editor,0,$false)
|
||||
if (!$menuWasPreserved) { throw 'Typing in a draft repainted the unchanged editor menu.' }
|
||||
foreach($cancel in $true,$false) {
|
||||
Post $control 0x100 27
|
||||
$confirm=Wait-Until { Find-Window '#32770' $process.Id 6 }
|
||||
Assert-DialogSurface $confirm 128 0
|
||||
Post $confirm 0x111 6
|
||||
$save=Wait-Until { Find-Window '#32770' $process.Id 464 }
|
||||
Assert-DialogSurface $save 192 192
|
||||
$name=[SearchArrowTest]::GetDlgItem($save,461)
|
||||
$current=[Text.StringBuilder]::new(1024)
|
||||
[void][SearchArrowTest]::GetText($name,0xD,$current.Capacity,$current)
|
||||
if ($current.ToString() -ne $generated) { throw 'Save options did not carry the generated name.' }
|
||||
if ($cancel) {
|
||||
Post $save 0x111 2
|
||||
[void](Wait-Until { ![SearchArrowTest]::IsWindow($save) -and [SearchArrowTest]::IsWindow($editor) })
|
||||
continue
|
||||
}
|
||||
[void][SearchArrowTest]::SendText($name,0x0C,0,'created.txt')
|
||||
[void][SearchArrowTest]::Send([SearchArrowTest]::GetDlgItem($save,464),0xF1,1,0)
|
||||
[void][SearchArrowTest]::Send([SearchArrowTest]::GetDlgItem($save,472),0xF5,0,0)
|
||||
Post $save 0x111 1
|
||||
}
|
||||
$result=Join-Path $scratch 'created.txt'
|
||||
[void](Wait-Until { (Test-Path -LiteralPath $result) -and ![SearchArrowTest]::IsWindow($editor) })
|
||||
if ([Convert]::ToHexString([IO.File]::ReadAllBytes($result)) -ne 'EFBBBF46697273740A5365636F6E64') {
|
||||
throw 'The saved bytes must contain a UTF-8 BOM and LF line endings.'
|
||||
}
|
||||
Write-Output 'Verified Shift+F4, the generated name, Escape confirmation, cancellation, and Save options.'
|
||||
return
|
||||
}
|
||||
if (!$KeyboardCursorOnly) {
|
||||
$leftPath = [SearchArrowTest]::GetDlgItem($main,142)
|
||||
foreach ($step in @(@{ Row='[Right fixture]'; Path=$rightFixture }, @{ Row='..'; Path=$scratch })) {
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
using ks::files::TextDocument;
|
||||
using ks::files::TextEncoding;
|
||||
using ks::files::TextLineEnding;
|
||||
|
||||
namespace
|
||||
{
|
||||
@@ -141,6 +143,43 @@ void sparseFile(const fs::path &file)
|
||||
document.stage(index, "edited");
|
||||
check(document.readPage(index) == "edited", "Stage an edit past 4 GiB");
|
||||
}
|
||||
|
||||
void saveDraft(const fs::path &file)
|
||||
{
|
||||
TextDocument draft({});
|
||||
check(draft.readPage(0).empty() && draft.pages()==1, "Start with an empty draft");
|
||||
draft.stage(0,"one\r\ntwo\rthree\n");
|
||||
writeFile(file,"existing");
|
||||
bool rejected{};
|
||||
try {draft.saveNew(file,{});}
|
||||
catch(const std::exception &) {rejected=true;}
|
||||
check(rejected && draft.modified() && readFile(file)=="existing", "Preserve a conflicting file and the draft");
|
||||
fs::remove(file);
|
||||
check(draft.saveNew(file,{TextEncoding::utf8,true,TextLineEnding::lf}), "Save a draft as a new file");
|
||||
check(readFile(file)=="\xef\xbb\xbfone\ntwo\nthree\n" && draft.readPage(0)=="one\ntwo\nthree\n",
|
||||
"Save a UTF-8 signature and normalize mixed line endings");
|
||||
draft.stage(0,"after");
|
||||
check(draft.save() && readFile(file)=="\xef\xbb\xbf" "after", "Edit normally after the first save");
|
||||
|
||||
const auto ansiFile=file.parent_path()/L"windows1252.txt";
|
||||
TextDocument ansiDraft({});
|
||||
ansiDraft.stage(0,"caf\xc3\xa9\n");
|
||||
check(ansiDraft.saveNew(ansiFile,{TextEncoding::windows1252,false,TextLineEnding::crlf}),
|
||||
"Save a draft in Windows-1252");
|
||||
check(readFile(ansiFile)=="caf\xe9\r\n" && ansiDraft.readPage(0)=="caf\xc3\xa9\r\n",
|
||||
"Round-trip Windows-1252 text and CRLF");
|
||||
TextDocument ansiReader(ansiFile,false,TextEncoding::windows1252);
|
||||
check(ansiReader.readPage(0)=="caf\xc3\xa9\r\n", "Open an existing file with an explicit code page");
|
||||
|
||||
const auto unicodeFile=file.parent_path()/L"utf16be.txt";
|
||||
TextDocument unicodeDraft({});
|
||||
unicodeDraft.stage(0,"a\n");
|
||||
check(unicodeDraft.saveNew(unicodeFile,{TextEncoding::utf16be,true,TextLineEnding::cr}),
|
||||
"Save a UTF-16 draft with a signature");
|
||||
TextDocument unicodeReader(unicodeFile,false);
|
||||
check(readFile(unicodeFile)==std::string("\xfe\xff\0a\0\r",6) && unicodeReader.readPage(0)=="a\r",
|
||||
"Detect the UTF-16 signature and read CR line endings");
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
@@ -151,6 +190,7 @@ int main()
|
||||
editsAcrossPages(fixture.directory / L"pages.txt");
|
||||
unicodeBoundaries(fixture.directory / L"unicode.txt");
|
||||
rejectExternalReplacement(fixture.directory / L"external.txt");
|
||||
saveDraft(fixture.directory / L"created.txt");
|
||||
sparseFile(fixture.directory / L"5gib.log");
|
||||
std::cout << "Files text document regressions passed.\n";
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user