Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
68edcc0bfb | ||
|
|
b705c4e4a0 | ||
|
|
31d582d29e | ||
|
|
ad2fa2c92e | ||
|
|
796d03f8a9 | ||
|
|
be68b706f0 | ||
|
|
23a7c73331 | ||
|
|
82fe8ce3a1 | ||
|
|
00cd1262b4 | ||
|
|
7bc734a9a8 | ||
|
|
a19ccaf035 | ||
|
|
60625103f8 | ||
|
|
aa02f2cacb | ||
|
|
6a1e39efa9 | ||
|
|
7242c3f775 | ||
|
|
a43f6441b4 | ||
|
|
2f5ae373a1 | ||
|
|
b978361180 | ||
|
|
93b8055085 | ||
|
|
70ee338fc3 | ||
|
|
46b4b51cea | ||
|
|
721c3f0f38 | ||
|
|
47851d75ef |
No files matched your search
@@ -40,8 +40,31 @@ Wiki: https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki
|
||||
Updating only the release notes or changing only the Wiki version number does
|
||||
not satisfy this rule; the current functionality must also be reviewed.
|
||||
|
||||
## Gitea issue authentication
|
||||
|
||||
For Gitea issue API requests from this checkout, use the project token stored
|
||||
with Windows DPAPI in `kswitcher-gitea-token.dpapi` under the directory returned
|
||||
by `git rev-parse --absolute-git-dir`. Read it with PowerShell
|
||||
`Get-Content -LiteralPath $tokenFile | ConvertTo-SecureString` and use it only
|
||||
for the Gitea authorization header. Keep the token out of tracked files and
|
||||
command output.
|
||||
|
||||
## KSwitcher Files UI
|
||||
|
||||
Before changing the file manager UI, read [FILES-UI.md](FILES-UI.md).
|
||||
Reuse the shared dialog rendering and layout helpers. Update the document
|
||||
when an agreed UI requirement changes.
|
||||
|
||||
## Link changes to Gitea issues
|
||||
|
||||
For commits that implement a Gitea issue, include `Refs #<number>` in the
|
||||
commit message body. In a pull request, use `Fixes #<number>` when merging
|
||||
fully resolves the issue, or `Refs #<number>` when the work is partial.
|
||||
Use the existing issue for follow-up commits on the same change.
|
||||
|
||||
Assign each new issue to the [KSwitcher project board](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/projects/8)
|
||||
using its default column, and verify that the issue appears on the board.
|
||||
|
||||
Use Markdown headings, lists, and bold emphasis to make issue descriptions
|
||||
easy to scan. Embed relevant screenshots as Markdown images using their
|
||||
Gitea attachment URLs, and verify that the images render in the description.
|
||||
+10
-1
@@ -1,5 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.24)
|
||||
project(KSwitcher VERSION 0.6.77 LANGUAGES CXX RC)
|
||||
project(KSwitcher VERSION 0.6.82 LANGUAGES CXX RC)
|
||||
if(NOT WIN32)
|
||||
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
|
||||
endif()
|
||||
@@ -117,6 +117,15 @@ add_test(NAME lan-pairing-regressions COMMAND KSwitcherLanTests)
|
||||
add_executable(KSwitcherLanFilesTests tests/lan_files.cpp)
|
||||
target_link_libraries(KSwitcherLanFilesTests PRIVATE kscore)
|
||||
add_test(NAME lan-files-regressions COMMAND KSwitcherLanFilesTests)
|
||||
add_executable(KSwitcherFilesActivationFixture tests/files_activation_fixture.cpp)
|
||||
if(NOT MSVC)
|
||||
target_link_options(KSwitcherFilesActivationFixture PRIVATE -municode -static)
|
||||
endif()
|
||||
add_test(NAME files-activation-and-refresh
|
||||
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
|
||||
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_activation.ps1"
|
||||
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Fixture "$<TARGET_FILE:KSwitcherFilesActivationFixture>")
|
||||
set_tests_properties(files-activation-and-refresh PROPERTIES RUN_SERIAL TRUE TIMEOUT 120)
|
||||
add_executable(KSwitcherLanInputTests tests/lan_input.cpp)
|
||||
target_link_libraries(KSwitcherLanInputTests PRIVATE kscore)
|
||||
if(MSVC)
|
||||
|
||||
+82
-1
@@ -4,9 +4,53 @@ Far Manager є зразком для оформлення файлового м
|
||||
|
||||
## Скорочення
|
||||
|
||||
- Enter і подвійний клік відкривають папку в поточній панелі, а локальний
|
||||
документ — у програмі, призначеній для його типу у Windows. EXE запускається
|
||||
окремим процесом. BAT і CMD виконуються в поточній сесії вбудованого
|
||||
термінала, а їхній вивід з’являється під панелями. Щоб відкрити файл із
|
||||
панелі LAN, спочатку скопіюй його до локальної папки.
|
||||
|
||||
- У командному рядку Ctrl+V і Shift+Insert вставляють текст із буфера обміну
|
||||
в позицію курсора або замінюють виділення. Якщо фокус на файловій панелі,
|
||||
ці клавіші переводять його до командного рядка й вставляють текст там.
|
||||
Enter запускає команду. Escape очищає поле й залишає фокус у командному рядку.
|
||||
Промпт і текст команди вирівняні по спільній базовій лінії.
|
||||
|
||||
- Ctrl+E підставляє останню команду та переводить фокус із файлової панелі
|
||||
до командного рядка. Повторне натискання
|
||||
підставляє старішу, доки не досягне початку історії. Alt+F8 відкриває історію
|
||||
з групуванням за датами. Enter або подвійний клік у списку підставляє вибрану
|
||||
команду в поле. Для запуску натисни Enter у самому полі.
|
||||
- Історія зберігає 1000 останніх непорожніх команд, надісланих із поля KSwitcher
|
||||
Files, включно з повторами. Вона зберігається локально в профілі Windows між
|
||||
запусками. Options → Command line → Command history змінює обидві комбінації,
|
||||
перевіряє конфлікти та дозволяє відновити типові значення.
|
||||
- Ширина історії підлаштовується під найдовшу команду в межах робочої області
|
||||
монітора. Рядок, який не вміщується, закінчується трьома крапками. Вибір
|
||||
підставляє до командного рядка повний текст.
|
||||
- Пошук в історії фільтрує команди за всіма введеними словами, незалежно від
|
||||
регістру. Збіги за текстом або датою йдуть перед тематичними. Тематичні
|
||||
ключові слова визначаються локально й використовуються лише для пошуку,
|
||||
зокрема в раніше збережених записах. Кожна команда відображається один
|
||||
раз, за датою останнього запуску.
|
||||
- Історія використовує оформлення діалогів Delete і Copy та спільне поле Far.
|
||||
Підпис, поле й список вирівнюються за відступами Dialog frame. Рядки команд
|
||||
і роздільники дат мають власний внутрішній відступ.
|
||||
Вікно історії бірюзове, поле пошуку сіро-бірюзове. Поки історія відкрита,
|
||||
дії в панелях, меню й командному рядку заблоковано. Заголовок і рамка
|
||||
головного вікна доступні для переміщення, зміни розміру та керування вікном.
|
||||
Escape або клік поза діалогом закриває історію. Заголовок і рамка головного
|
||||
вікна залишають історію відкритою під час керування вікном.
|
||||
Історія центрується відносно головного вікна й рухається разом із ним.
|
||||
Tab циклічно переводить фокус між пошуком і списком.
|
||||
Стрілка вгору або вниз із пошуку одразу пересуває вибір у списку.
|
||||
Висота списку залежить від кількості результатів. Коли місця бракує,
|
||||
прокручується список.
|
||||
|
||||
- Короткий Alt перемикає головне меню Files при відпусканні. F9 також перемикає меню. Після закриття фокус повертається до активної панелі. Alt з літерою верхнього рівня спрацьовує одразу при натисканні літери. Alt+O відкриває Options, а відпускання Alt після комбінації не перемикає меню.
|
||||
- Коли головне меню відкрите, L, F, C, O та R відкривають Left, Files, Commands, Options та Right. У підменю підсвічена літера викликає відповідну команду. Літери унікальні в межах поточного рівня. Усталені мнемоніки мають пріоритет, зокрема X для Exit.
|
||||
- Глобальне скорочення **Open KSwitcher Files** можна змінити або очистити в налаштуваннях. Для профілю без цього поля пропонується Ctrl+Alt+F, якщо Windows реєструє комбінацію і вона вільна серед прив’язок KSwitcher.
|
||||
- Глобальне скорочення повертає до відкритого вікна Files у поточній сесії Windows або запускає Files, якщо такого вікна немає. Пункт **Files** у треї відкриває нове вікно.
|
||||
|
||||
- Ctrl+Shift+0–9 відкриває діалог Title і Path із поточною папкою. OK додає запис без дублювання, Escape скасовує. Title необов’язковий, порожнє значення показує шлях. Записи LAN зберігають ID ПК, а редагування Path залишає запис на тому самому ПК.
|
||||
- Ctrl+0–9 одразу відкриває єдину папку. Для кількох папок відкривається компактний попап Far з одним заголовком Folder shortcuts у подвійній рамці та коротким рядом клавіш у нижній рамці. Ширина залежить від найдовшого запису й обмежується розміром вікна, а висота — кількістю видимих рядків. Нижня рамка показує Ins Del F4 Ctrl+Up Ctrl+Down. Insert додає поточну папку через Title і Path, Delete відв’язує, F4 редагує, Ctrl+Up і Ctrl+Down змінюють і зберігають порядок. Enter відкриває папку. Escape або клік поза попапом закриває його й повертає фокус до панелі. Commands → Folder shortcuts дає вибрати зайняту цифру й відкрити той самий попап навіть для єдиного запису. Brief і Wide доступні в меню Left/Right та Options.
|
||||
@@ -28,6 +72,34 @@ Far Manager є зразком для оформлення файлового м
|
||||
|
||||
## Панелі
|
||||
|
||||
- Обидві панелі автоматично підхоплюють створення, зміну й видалення файлів
|
||||
у відкритих локальних папках. Фокус залишається там, де був, а курсор
|
||||
лишається на поточному елементі, якщо той ще існує.
|
||||
|
||||
- Ctrl+8 відкриває список усіх ярликів папок. Кожен рядок показує групу
|
||||
й назву або шлях. Enter відкриває папку в активній панелі, F4 редагує
|
||||
ярлик, а Delete прибирає його зі списку.
|
||||
|
||||
- У Change drive повідомлення No paired computers з’являється після
|
||||
успішної відповіді з порожнім списком. Збої локального запиту до
|
||||
KSwitcher відображаються окремо.
|
||||
|
||||
- Якщо команда у вбудованому PowerShell змінює поточну папку,
|
||||
панель, з якої надіслано команду, переходить до цієї папки.
|
||||
|
||||
- Коли список LAN-дисків змінює розмір меню Change drive, рамка й список
|
||||
змінюють позицію разом. Рамка повністю перемальовується після зміни
|
||||
розміру, а список має однаковий внутрішній відступ зліва і справа.
|
||||
- Тайм-аут запиту дисків відображається як Connection timed out. Якщо
|
||||
ввімкнено Write log, Files записує помилки запитів пар і дисків в окремий
|
||||
журнал `data/kswitcher-files.log`. Системні помилки містять код Windows.
|
||||
|
||||
- Застосовані налаштування Files одразу підхоплюють інші відкриті вікна.
|
||||
Apply зберігає поля, змінені в поточній чернетці. Якщо два вікна одночасно
|
||||
редагували набір стилів файлів, відкрий Options заново, щоб побачити свіжі правила.
|
||||
|
||||
- Типовий колір тексту для ZIP-архівів — світлий коралово-рожевий.
|
||||
|
||||
- Меню Change drive показує літеру, тип, загальний обсяг і вільне місце. Відкриття меню запускає нове LAN-виявлення. Секція KSwitcher LAN показує збережені пари, зокрема офлайн. Після кожного відкриття меню асинхронно запитує диски й показує їх під назвою відповідного ПК. Поки триває запит, видно стан завантаження. Якщо запит не вдався, видно помилку. Повторне відкриття запускає новий запит. Кожна панель має власний диск і шлях, а в заголовку віддаленої панелі перед шляхом показано назву ПК.
|
||||
|
||||
- Список дисків і файлові операції використовують права облікового запису Windows, під яким працює віддалений KSwitcher. Достатньо спарювання й доступного TCP 45885, спільні папки налаштовувати не потрібно.
|
||||
@@ -38,12 +110,18 @@ Far Manager є зразком для оформлення файлового м
|
||||
|
||||
- У широкому режимі ширина під вирівняні розширення залежить від найдовшого розширення в поточній панелі. За вузької панелі залишай місце для імені та колонки Size.
|
||||
|
||||
- Бірюзовий курсор поточного рядка видно лише в активній панелі. Кожна панель зберігає свою позицію курсора.
|
||||
- Бірюзовий курсор поточного рядка видно лише в активній панелі, зокрема коли клавіатурний фокус переходить у командний рядок. Кожна панель зберігає свою позицію курсора. Коли панелі видимі, F5 і F6 з командного рядка діють на активну панель.
|
||||
- Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший.
|
||||
|
||||
- Поточний шлях відображається по центру верхньої подвійної лінії панелі. Лінію видно з обох боків напису. Бірюзове тло активної панелі охоплює лише напис шляху з невеликими відступами. Довгий шлях скорочується в межах панелі.
|
||||
|
||||
## Спільні елементи діалогів
|
||||
|
||||
- Власні діалоги Files блокують дії панелей і командного рядка, залишаючи
|
||||
системний заголовок і рамку головного вікна доступними. Клік поза діалогом
|
||||
діє як Cancel. Для прогресу копіювання, переміщення й видалення це відкриває
|
||||
підтвердження скасування.
|
||||
|
||||
- Enter активує кнопку у фокусі. Для кнопок із власним малюванням використовуй спільний обробник `dialogButtonEnter`. У підтвердженні скасування початковий фокус стоїть на No.
|
||||
|
||||
- При перенесенні вікна між моніторами з різним DPI оновлюй шрифт, висоту рядків панелей і компонування відкритого прогресу копіювання. Перевір перенесення під час активного копіювання.
|
||||
@@ -73,6 +151,9 @@ Far Manager є зразком для оформлення файлового м
|
||||
|
||||
## Попередження про конфлікт
|
||||
|
||||
- Для однойменних файлів Warning показує точний розмір у байтах із розділенням тисяч і місцевий
|
||||
час останньої зміни окремо для вхідного файла та файла в папці призначення.
|
||||
|
||||
- Після розрахунку остаточної висоти центр Warning збігається з центром вікна прогресу.
|
||||
- Remember choice стоїть по вертикальному центру власної секції. Кнопки Overwrite, Skip і Cancel стоять по центру нижньої секції.
|
||||
- Tab проходить Remember choice, Overwrite, Skip і Cancel. Стрілки вліво та вправо циклічно перемикають три кнопки в порядку їх розташування.
|
||||
|
||||
Binary file not shown.
@@ -1,5 +1,47 @@
|
||||
# Latest Windows release
|
||||
|
||||
## v0.6.82 — 2026-11-14
|
||||
|
||||
Enter and double-click open folders in the current pane, open local documents with their Windows default apps, and launch EXE files in separate processes. BAT and CMD files run in the existing embedded PowerShell session, and their output appears below the panes. Both local panes refresh when files are created, modified, or deleted externally and preserve focus.
|
||||
|
||||
**Українською.** Enter і подвійний клік відкривають папки в поточній панелі та локальні документи у стандартних програмах Windows. EXE запускаються окремими процесами, а BAT і CMD виконуються в поточній сесії вбудованого PowerShell із виводом під панелями. Обидві локальні панелі підхоплюють створення, зміну й видалення файлів ззовні та зберігають фокус.
|
||||
|
||||
## v0.6.81 — 2026-11-14
|
||||
|
||||
Ctrl+8 lists all folder shortcuts. Press Enter to open a folder, F4 to edit the shortcut, or Delete to remove it. Ctrl+Alt+F brings an open Files window forward.
|
||||
|
||||
**Українською.** Ctrl+8 показує всі ярлики папок. Enter відкриває папку, F4 редагує ярлик, Delete видаляє його. Ctrl+Alt+F повертає до відкритого вікна Files.
|
||||
|
||||
## v0.6.80 — 2026-11-14
|
||||
|
||||
Includes the Files updates from v0.6.79. Change drive now explains why the local peer lookup failed and shows No paired computers only when the response is empty.
|
||||
|
||||
**Українською.** Випуск включає зміни Files із v0.6.79. Change drive показує конкретну причину збою запиту пар. No paired computers з’являється лише після успішної порожньої відповіді.
|
||||
|
||||
## v0.6.79 — 2026-11-14
|
||||
|
||||
In KSwitcher Files, changing directory in PowerShell updates the panel
|
||||
that sent the command. The global Files shortcut brings an open window to
|
||||
the foreground. Change drive redraws its frame when LAN drives arrive and
|
||||
shows a short timeout message. Files writes LAN lookup errors to its own log.
|
||||
|
||||
**Українською.** Зміна каталогу в PowerShell оновлює панель, з якої
|
||||
надіслано команду. Глобальна клавіша Files повертає до відкритого вікна.
|
||||
Change drive перемальовує рамку після появи LAN-дисків і показує коротке
|
||||
повідомлення про тайм-аут. Files записує помилки LAN у власний журнал.
|
||||
|
||||
## v0.6.78 — 2026-11-14
|
||||
|
||||
The Windows package includes KSwitcher Files, a two-panel file manager with
|
||||
local and paired LAN drives, folder shortcuts, an embedded PowerShell terminal,
|
||||
and searchable command history. Applied Files settings update other open
|
||||
instances immediately.
|
||||
|
||||
**Українською.** До пакета для Windows входить KSwitcher Files, двопанельний
|
||||
файловий менеджер із локальними дисками й дисками спарених ПК, ярликами папок,
|
||||
вбудованим PowerShell та пошуком в історії команд. Застосовані налаштування
|
||||
Files одразу підхоплюють інші відкриті вікна.
|
||||
|
||||
## v0.6.77 — 2026-11-13
|
||||
|
||||
The screenshot editor remembers the local pencil smoothing default across
|
||||
|
||||
@@ -1 +1 @@
|
||||
51d95639527590b36453a5ef485532a7d2135950222fa197eb431a5309f1a45c KSwitcher-win-x64.zip
|
||||
84ba82bdf179419c6cc7a612b12c6adb962a47c55aacee311861e9843be1e683 KSwitcher-win-x64.zip
|
||||
+86
-41
@@ -1,86 +1,131 @@
|
||||
{
|
||||
"version": "0.6.77",
|
||||
"schema": 1,
|
||||
"version": "0.6.82",
|
||||
"files": [
|
||||
{
|
||||
"path": "KSwitcher.exe",
|
||||
"size": 2249216,
|
||||
"sha256": "f1c79d337d746efcda03946cc833b7b5588ef4e739f1dff7d3afa15d0465469f"
|
||||
"size": 2341376,
|
||||
"sha256": "8017fa3d840d4e89871b926ceea6c53d99238ba8145a8158930098c3fd7b8485",
|
||||
"path": "KSwitcher.exe"
|
||||
},
|
||||
{
|
||||
"path": "KSwitcher.Config.exe",
|
||||
"size": 2251776,
|
||||
"sha256": "016edc389007e0d15ee365fff7115fc91a820b46080cb39a3fb362f3b463bae7"
|
||||
"size": 2341888,
|
||||
"sha256": "cbb6624c0382d3a9bd1aa65542f9c2475a171cd11d55372b1c3a3c21fe65d86c",
|
||||
"path": "KSwitcher.Config.exe"
|
||||
},
|
||||
{
|
||||
"path": "KSwitcher.Screenshot.exe",
|
||||
"size": 3247616,
|
||||
"sha256": "c8ef070ad01acc410802c62e0df6a96cb299fe036fe8e99f0cf6a398b7324ec6"
|
||||
"size": 3319808,
|
||||
"sha256": "bc87038c9b090cea36475d3921e6d8a7567d407a447903291f45301fd0e4394d",
|
||||
"path": "KSwitcher.Screenshot.exe"
|
||||
},
|
||||
{
|
||||
"size": 1829888,
|
||||
"sha256": "487e51da766bab3c1e2fbcb88d374ea3a03cda6a5736f1972b861cfff68af82f",
|
||||
"path": "KSwitcher.Files.exe"
|
||||
},
|
||||
{
|
||||
"size": 194912,
|
||||
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
|
||||
"path": "WebView2Loader.dll"
|
||||
},
|
||||
{
|
||||
"size": 1103,
|
||||
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
|
||||
"path": "terminal/addon-fit-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"size": 1521,
|
||||
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
|
||||
"path": "terminal/addon-fit.js"
|
||||
},
|
||||
{
|
||||
"size": 527,
|
||||
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
|
||||
"path": "terminal/index.html"
|
||||
},
|
||||
{
|
||||
"size": 3978,
|
||||
"sha256": "cc6c9cbb3684dbcda1ff587492b5a2047dd62d79b16a037bbc1d9b261afa3f78",
|
||||
"path": "terminal/terminal.js"
|
||||
},
|
||||
{
|
||||
"size": 1261,
|
||||
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
|
||||
"path": "terminal/xterm-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"size": 7112,
|
||||
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
|
||||
"path": "terminal/xterm.css"
|
||||
},
|
||||
{
|
||||
"size": 488663,
|
||||
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
|
||||
"path": "terminal/xterm.js"
|
||||
},
|
||||
{
|
||||
"path": "LICENSE",
|
||||
"size": 4401,
|
||||
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
|
||||
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
|
||||
"path": "LICENSE"
|
||||
},
|
||||
{
|
||||
"path": "json-LICENSE.txt",
|
||||
"size": 1075,
|
||||
"sha256": "c0d068392ea65358b798b8c165103560f06e9e3b38c4ab4e2d8810a7b931af86"
|
||||
"sha256": "c0d068392ea65358b798b8c165103560f06e9e3b38c4ab4e2d8810a7b931af86",
|
||||
"path": "json-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"path": "README.md",
|
||||
"size": 93885,
|
||||
"sha256": "df6d40d0eb66ad7da8db1cffe6bd211de70dfee474cc228e041c821b3940718b"
|
||||
"sha256": "df6d40d0eb66ad7da8db1cffe6bd211de70dfee474cc228e041c821b3940718b",
|
||||
"path": "README.md"
|
||||
},
|
||||
{
|
||||
"path": "LAN-PREVIEW.md",
|
||||
"size": 11418,
|
||||
"sha256": "2c13d3ed4761e679c352fb1ade24a1ec3060ad2862376ede801cdee5fcc3bada"
|
||||
"sha256": "2c13d3ed4761e679c352fb1ade24a1ec3060ad2862376ede801cdee5fcc3bada",
|
||||
"path": "LAN-PREVIEW.md"
|
||||
},
|
||||
{
|
||||
"path": "dictionaries/en.txt",
|
||||
"size": 682867,
|
||||
"sha256": "5f267c141c3d6837870e1c098f86b89a113ba300343119432644ead88f720c21"
|
||||
"sha256": "5f267c141c3d6837870e1c098f86b89a113ba300343119432644ead88f720c21",
|
||||
"path": "dictionaries/en.txt"
|
||||
},
|
||||
{
|
||||
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
|
||||
"size": 20138,
|
||||
"sha256": "28a9529c7d0bb4dc51f4bf5c116a3d16ef247a052f7591466768ddf563fd1cf5"
|
||||
"sha256": "28a9529c7d0bb4dc51f4bf5c116a3d16ef247a052f7591466768ddf563fd1cf5",
|
||||
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt"
|
||||
},
|
||||
{
|
||||
"path": "dictionaries/README.md",
|
||||
"size": 2230,
|
||||
"sha256": "2df17fe4e17d527c67ab57269b07dce59a49c1fb128c429a1408decbb47109ec"
|
||||
"size": 2265,
|
||||
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
|
||||
"path": "dictionaries/README.md"
|
||||
},
|
||||
{
|
||||
"path": "dictionaries/ru.txt",
|
||||
"size": 1060364,
|
||||
"sha256": "9ef922c7699569304a428f6aba0fd13a21341c0d0cb9561f37ef83c41577a28b"
|
||||
"sha256": "9ef922c7699569304a428f6aba0fd13a21341c0d0cb9561f37ef83c41577a28b",
|
||||
"path": "dictionaries/ru.txt"
|
||||
},
|
||||
{
|
||||
"path": "dictionaries/sources.json",
|
||||
"size": 1279,
|
||||
"sha256": "d6e11a3aaba22a8a7eaba19f778d8a5bd66653ff306810e85a1b0e7fff3a6b86"
|
||||
"size": 1280,
|
||||
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
|
||||
"path": "dictionaries/sources.json"
|
||||
},
|
||||
{
|
||||
"path": "dictionaries/uk.txt",
|
||||
"size": 898248,
|
||||
"sha256": "caeb097749d4afc84b68ad96b3d7dfb6a6569561cd32ccce0bee94a13b43ba86"
|
||||
"size": 940799,
|
||||
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
|
||||
"path": "dictionaries/uk.txt"
|
||||
},
|
||||
{
|
||||
"path": "tools/README.txt",
|
||||
"size": 993,
|
||||
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
|
||||
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
|
||||
"path": "tools/README.txt"
|
||||
},
|
||||
{
|
||||
"path": "tools/StayHere.exe",
|
||||
"size": 134656,
|
||||
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376"
|
||||
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376",
|
||||
"path": "tools/StayHere.exe"
|
||||
},
|
||||
{
|
||||
"path": "tools/StayHere-README.md",
|
||||
"size": 2796,
|
||||
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
|
||||
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
|
||||
"path": "tools/StayHere-README.md"
|
||||
}
|
||||
],
|
||||
"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,77,0
|
||||
PRODUCTVERSION 0,6,77,0
|
||||
FILEVERSION 0,6,82,0
|
||||
PRODUCTVERSION 0,6,82,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.77"
|
||||
VALUE "FileVersion", "0.6.82"
|
||||
END
|
||||
END
|
||||
BLOCK "VarFileInfo"
|
||||
|
||||
+31
-12
@@ -39,6 +39,10 @@ BEGIN
|
||||
COMBOBOX 305, 311, 51, 56, 125, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
LTEXT "&Row text padding (characters)", 306, 131, 77, 173, 12
|
||||
COMBOBOX 307, 311, 74, 56, 76, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
LTEXT "Previous command", 320, 131, 30, 120, 12
|
||||
CONTROL "", 321, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 260, 27, 110, 15
|
||||
LTEXT "Open command history", 322, 131, 53, 120, 12
|
||||
CONTROL "", 323, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 260, 50, 110, 15
|
||||
PUSHBUTTON "Reset selected to defaults", 284, 131, 181, 125, 15
|
||||
COMBOBOX 285, 131, 183, 139, 95, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
PUSHBUTTON "Reset property", 286, 278, 183, 108, 15
|
||||
@@ -62,18 +66,19 @@ BEGIN
|
||||
PUSHBUTTON "&Apply", 283, 338, 289, 50, 14
|
||||
END
|
||||
|
||||
102 DIALOGEX 0, 0, 350, 114
|
||||
102 DIALOGEX 0, 0, 350, 145
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Copy"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "Copy to", 210, 14, 15, 322, 12, SS_PATHELLIPSIS
|
||||
FAR_EDIT(211, ES_MULTILINE, 14, 29, 322, 18)
|
||||
LTEXT "Existing files:", 212, 14, 61, 122, 14, SS_CENTERIMAGE
|
||||
COMBOBOX 213, 140, 61, 196, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_VSCROLL | WS_TABSTOP
|
||||
CONTROL "Also ask on read-only files", 214, "Button", BS_OWNERDRAW | WS_TABSTOP, 14, 81, 322, 14
|
||||
CONTROL "&Copy", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 87, 96, 86, 18
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 177, 96, 86, 18
|
||||
LTEXT "", 328, 14, 49, 322, 35, SS_NOPREFIX
|
||||
LTEXT "Existing files:", 212, 14, 92, 122, 14, SS_CENTERIMAGE
|
||||
COMBOBOX 213, 140, 92, 196, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_VSCROLL | WS_TABSTOP
|
||||
CONTROL "Also ask on read-only files", 214, "Button", BS_OWNERDRAW | WS_TABSTOP, 14, 112, 322, 14
|
||||
CONTROL "&Copy", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 87, 127, 86, 18
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 177, 127, 86, 18
|
||||
END
|
||||
|
||||
103 DIALOGEX 0, 0, 460, 126
|
||||
@@ -92,7 +97,7 @@ BEGIN
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 187, 106, 86, 18
|
||||
END
|
||||
|
||||
104 DIALOGEX 0, 0, 360, 106
|
||||
104 DIALOGEX 0, 0, 360, 139
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Warning"
|
||||
FONT 10, "Consolas"
|
||||
@@ -100,11 +105,16 @@ BEGIN
|
||||
LTEXT "", 230, 12, 16, 336, 12
|
||||
LTEXT "", 231, 12, 33, 336, 12, SS_PATHELLIPSIS
|
||||
LTEXT "", 233, 12, 55, 1, 1
|
||||
LTEXT "", 234, 12, 81, 1, 1
|
||||
CONTROL "Remember choice", 232, "Button", BS_OWNERDRAW | WS_TABSTOP, 12, 57, 336, 18
|
||||
CONTROL "&Overwrite", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP, 42, 89, 110, 18
|
||||
CONTROL "&Skip", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP, 158, 89, 68, 18
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 232, 89, 86, 18
|
||||
LTEXT "New", 329, 12, 58, 65, 13
|
||||
RTEXT "", 330, 78, 58, 270, 13
|
||||
LTEXT "Existing", 331, 12, 72, 65, 13
|
||||
RTEXT "", 332, 78, 72, 270, 13
|
||||
LTEXT "", 333, 12, 88, 1, 1
|
||||
LTEXT "", 234, 12, 114, 1, 1
|
||||
CONTROL "Remember choice", 232, "Button", BS_OWNERDRAW | WS_TABSTOP, 12, 90, 336, 18
|
||||
CONTROL "&Overwrite", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP, 42, 122, 110, 18
|
||||
CONTROL "&Skip", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP, 158, 122, 68, 18
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 232, 122, 86, 18
|
||||
END
|
||||
|
||||
105 DIALOGEX 0, 0, 310, 65
|
||||
@@ -165,3 +175,12 @@ BEGIN
|
||||
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 97, 86, 86, 18
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 187, 86, 86, 18
|
||||
END
|
||||
|
||||
111 DIALOGEX 0, 0, 385, 220
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
FONT 9, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "&Search commands or topics", 326, 12, 14, 361, 12
|
||||
FAR_EDIT(325, ES_MULTILINE, 12, 28, 361, 16)
|
||||
LISTBOX 324, 12, 49, 361, 155, LBS_NOTIFY | LBS_OWNERDRAWFIXED | LBS_HASSTRINGS | LBS_NOINTEGRALHEIGHT | WS_TABSTOP
|
||||
END
|
||||
@@ -7,6 +7,16 @@ const terminal = new Terminal({
|
||||
theme: { background: '#181818', foreground: '#e8e8e8' },
|
||||
});
|
||||
const fit = new FitAddon.FitAddon();
|
||||
terminal.parser.registerOscHandler(633, data => {
|
||||
const prefix = 'ks-directory:';
|
||||
if (!data.startsWith(prefix)) return false;
|
||||
try {
|
||||
bridge.postMessage('directory:' + decodeURIComponent(data.slice(prefix.length)));
|
||||
} catch {
|
||||
bridge.postMessage('directory:');
|
||||
}
|
||||
return true;
|
||||
});
|
||||
terminal.loadAddon(fit);
|
||||
const host = document.getElementById('terminal');
|
||||
terminal.open(host);
|
||||
@@ -14,6 +24,8 @@ host.addEventListener('pointerup', () => bridge.postMessage('focus-input'), true
|
||||
const screen = host.querySelector('.xterm-screen');
|
||||
let traceEnabled = false;
|
||||
let traceBudget = 4096;
|
||||
let outputTraceBudget = 256;
|
||||
let traceOutput = false;
|
||||
let currentOffset = 0;
|
||||
function trace(phase) {
|
||||
if (!traceEnabled || traceBudget <= 0) return;
|
||||
@@ -54,8 +66,9 @@ terminal.onScroll(() => {
|
||||
anchorOutput();
|
||||
});
|
||||
bridge.addEventListener('message', ({ data }) => {
|
||||
if (data === 'trace:on') {
|
||||
if (data === 'trace:on' || data === 'trace:output') {
|
||||
traceEnabled = true;
|
||||
traceOutput = data === 'trace:output';
|
||||
trace(2);
|
||||
return;
|
||||
}
|
||||
@@ -73,7 +86,16 @@ bridge.addEventListener('message', ({ data }) => {
|
||||
}
|
||||
const bytes = new Uint8Array(data.length / 2);
|
||||
for (let i = 0; i < bytes.length; i++) bytes[i] = parseInt(data.slice(2*i, 2*i+2), 16);
|
||||
terminal.write(bytes, anchorOutput);
|
||||
terminal.write(bytes, () => {
|
||||
anchorOutput();
|
||||
if (traceOutput && outputTraceBudget > 0) {
|
||||
outputTraceBudget--;
|
||||
const buffer = terminal.buffer.active;
|
||||
const lines = Array.from({ length: terminal.rows }, (_, row) =>
|
||||
buffer.getLine(buffer.viewportY + row)?.translateToString(true) ?? '');
|
||||
bridge.postMessage('output:' + lines.join('\n').trimEnd());
|
||||
}
|
||||
});
|
||||
});
|
||||
new ResizeObserver(() => {
|
||||
const buffer = terminal.buffer.active;
|
||||
|
||||
+23
-1
@@ -143,6 +143,28 @@ ULONG_PTR snippetReplayMarker()
|
||||
}
|
||||
constexpr int OpenFiles = 25, FilesHotkeyFirst = 0x4B10, FilesHotkeySecond = 0x4B11;
|
||||
|
||||
bool activateFilesWindow()
|
||||
{
|
||||
HWND files{};
|
||||
EnumWindows([](HWND candidate, LPARAM context) -> BOOL
|
||||
{
|
||||
wchar_t name[32]{};
|
||||
if(!IsWindowVisible(candidate) || !GetClassNameW(candidate,name,std::size(name)) ||
|
||||
wcscmp(name,L"KSwitcher.Files"))
|
||||
return TRUE;
|
||||
*reinterpret_cast<HWND *>(context)=candidate;
|
||||
return FALSE;
|
||||
},reinterpret_cast<LPARAM>(&files));
|
||||
if(!files) return false;
|
||||
if(IsIconic(files)) ShowWindowAsync(files,SW_RESTORE);
|
||||
if(!SetForegroundWindow(files))
|
||||
{
|
||||
FLASHWINFO flash{sizeof(flash),files,FLASHW_TRAY,3,0};
|
||||
FlashWindowEx(&flash);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<std::pair<int, std::wstring>> shortcuts(const Settings &s)
|
||||
{
|
||||
std::vector<std::pair<int, std::wstring>> out{{Toggle, s.toggle},
|
||||
@@ -3037,7 +3059,7 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
|
||||
case WM_HOTKEY:
|
||||
if (app->filesHotkeyId && wp == static_cast<WPARAM>(app->filesHotkeyId))
|
||||
{
|
||||
app->dispatch(OpenFiles);
|
||||
if(!activateFilesWindow()) app->dispatch(OpenFiles);
|
||||
}
|
||||
else if (wp != FilesHotkeyFirst && wp != FilesHotkeySecond) app->dispatch((int)wp);
|
||||
return 0;
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
constexpr std::array<WORD,2> defaultHistoryKeys{MAKEWORD('E',HOTKEYF_CONTROL),MAKEWORD(VK_F8,HOTKEYF_ALT)};
|
||||
auto commandHistoryKeys=defaultHistoryKeys;
|
||||
constexpr size_t commandHistoryLimit=1000;
|
||||
|
||||
bool validHistoryKeys(const std::array<WORD,2> &keys)
|
||||
{
|
||||
if(keys[0]==keys[1]) return false;
|
||||
return std::all_of(keys.begin(),keys.end(),[](WORD binding)
|
||||
{
|
||||
const auto key=LOBYTE(binding), modifiers=HIBYTE(binding);
|
||||
const bool letter=key>='A' && key<='Z';
|
||||
const bool function=key>=VK_F1 && key<=VK_F12;
|
||||
if(!letter && !function) return false;
|
||||
if(modifiers==HOTKEYF_CONTROL) return (letter && key!='C' && key!='V' && key!='X' && key!='A' && key!='Z' && key!='Y') || function;
|
||||
if(modifiers==HOTKEYF_ALT) return function && key!=VK_F1 && key!=VK_F2 && key!=VK_F4 && key!=VK_F10;
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
std::array<WORD,2> optionHistoryKeys(HWND dialog)
|
||||
{
|
||||
return {static_cast<WORD>(SendDlgItemMessageW(dialog,321,HKM_GETHOTKEY,0,0)),
|
||||
static_cast<WORD>(SendDlgItemMessageW(dialog,323,HKM_GETHOTKEY,0,0))};
|
||||
}
|
||||
|
||||
void setOptionHistoryKeys(HWND dialog,const std::array<WORD,2> &keys)
|
||||
{
|
||||
SendDlgItemMessageW(dialog,321,HKM_SETHOTKEY,keys[0],0);
|
||||
SendDlgItemMessageW(dialog,323,HKM_SETHOTKEY,keys[1],0);
|
||||
}
|
||||
|
||||
void loadCommandHistoryKeys()
|
||||
{
|
||||
const std::array<WORD,2> keys{static_cast<WORD>(preference(L"PreviousCommandKey",defaultHistoryKeys[0])),
|
||||
static_cast<WORD>(preference(L"CommandHistoryKey",defaultHistoryKeys[1]))};
|
||||
commandHistoryKeys=validHistoryKeys(keys)?keys:defaultHistoryKeys;
|
||||
}
|
||||
|
||||
void loadCommandHistory()
|
||||
{
|
||||
|
||||
DWORD bytes{};
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,L"CommandHistory",RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)
|
||||
!=ERROR_SUCCESS || bytes>16*1024*1024 || bytes%sizeof(wchar_t)) return;
|
||||
std::wstring data(bytes/sizeof(wchar_t),L'\0');
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,L"CommandHistory",RRF_RT_REG_BINARY,nullptr,data.data(),&bytes)
|
||||
!=ERROR_SUCCESS) return;
|
||||
size_t start{};
|
||||
while(start<data.size())
|
||||
{
|
||||
const auto dateEnd=data.find(L'\0',start);
|
||||
if(dateEnd==std::wstring::npos) break;
|
||||
const auto commandEnd=data.find(L'\0',dateEnd+1);
|
||||
if(commandEnd==std::wstring::npos) break;
|
||||
terminalHistory.push_back({data.substr(start,dateEnd-start),data.substr(dateEnd+1,commandEnd-dateEnd-1)});
|
||||
start=commandEnd+1;
|
||||
}
|
||||
terminalHistoryIndex=terminalHistory.size();
|
||||
}
|
||||
|
||||
void rememberCommand(const std::wstring &command)
|
||||
{
|
||||
SYSTEMTIME now{};
|
||||
GetLocalTime(&now);
|
||||
wchar_t date[24]{};
|
||||
GetDateFormatEx(LOCALE_NAME_USER_DEFAULT,0,&now,L"dd.MM.yyyy",date,std::size(date),nullptr);
|
||||
terminalHistory.push_back({date,command});
|
||||
if(terminalHistory.size()>commandHistoryLimit) terminalHistory.erase(terminalHistory.begin());
|
||||
std::wstring data;
|
||||
for(const auto &entry:terminalHistory)
|
||||
{
|
||||
data.append(entry.date).push_back(L'\0');
|
||||
data.append(entry.command).push_back(L'\0');
|
||||
}
|
||||
if(RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,L"CommandHistory",REG_BINARY,data.data(),
|
||||
static_cast<DWORD>(data.size()*sizeof(wchar_t)))!=ERROR_SUCCESS)
|
||||
setStatus(L"Could not save command history.");
|
||||
refreshCommandHistory();
|
||||
}
|
||||
|
||||
void recallCommand(size_t index)
|
||||
{
|
||||
terminalHistoryIndex=index;
|
||||
SetWindowTextW(terminalInput,index<terminalHistory.size()?terminalHistory[index].command.c_str():L"");
|
||||
SetFocus(terminalInput);
|
||||
SendMessageW(terminalInput,EM_SETSEL,-2,-1);
|
||||
}
|
||||
|
||||
void showCommandHistory(HWND owner);
|
||||
|
||||
bool handleCommandHistoryKey(HWND window,const MSG &message)
|
||||
{
|
||||
if(message.message!=WM_KEYDOWN && message.message!=WM_SYSKEYDOWN) return false;
|
||||
if((GetKeyState(VK_LWIN)&0x8000) || (GetKeyState(VK_RWIN)&0x8000)) return false;
|
||||
const BYTE modifiers=((GetKeyState(VK_CONTROL)&0x8000)?HOTKEYF_CONTROL:0) |
|
||||
((GetKeyState(VK_MENU)&0x8000)?HOTKEYF_ALT:0) | ((GetKeyState(VK_SHIFT)&0x8000)?HOTKEYF_SHIFT:0);
|
||||
const auto binding=MAKEWORD(message.wParam,modifiers);
|
||||
if(binding==commandHistoryKeys[0] && (message.hwnd==terminalInput ||
|
||||
message.hwnd==panels[0].list || message.hwnd==panels[1].list))
|
||||
{
|
||||
if(terminalHistoryIndex) recallCommand(terminalHistoryIndex-1);
|
||||
return true;
|
||||
}
|
||||
if(binding!=commandHistoryKeys[1]) return false;
|
||||
if(!(message.lParam&(1LL<<30))) showCommandHistory(window);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
constexpr int historyList=324;
|
||||
|
||||
constexpr int historySearch=325;
|
||||
constexpr COLORREF historySearchSurface=RGB(132,177,177);
|
||||
constexpr int historySearchLabel=326;
|
||||
HWND commandHistoryWindow{};
|
||||
HHOOK historyMouseHook{};
|
||||
|
||||
LRESULT CALLBACK dismissHistoryOnOutsideClick(int code,WPARAM message,LPARAM data)
|
||||
{
|
||||
const auto dialog=commandHistoryWindow;
|
||||
if(code==HC_ACTION && dialog && IsWindowVisible(dialog) &&
|
||||
(message==WM_LBUTTONDOWN || message==WM_RBUTTONDOWN ||
|
||||
message==WM_MBUTTONDOWN || message==WM_XBUTTONDOWN))
|
||||
{
|
||||
const auto point=reinterpret_cast<const MSLLHOOKSTRUCT*>(data)->pt;
|
||||
const auto clicked=WindowFromPoint(point);
|
||||
const auto owner=GetWindow(dialog,GW_OWNER);
|
||||
if(clicked!=dialog && !IsChild(dialog,clicked))
|
||||
{
|
||||
POINT local=point;
|
||||
RECT client{};
|
||||
GetClientRect(owner,&client);
|
||||
ScreenToClient(owner,&local);
|
||||
const bool ownerClient=clicked==owner || IsChild(owner,clicked);
|
||||
if(!ownerClient || PtInRect(&client,local))
|
||||
{
|
||||
const auto focusPanel=clicked==panels[0].list?panels[0].list:
|
||||
clicked==panels[1].list?panels[1].list:panels[active].list;
|
||||
if(PostMessageW(dialog,WM_CLOSE,reinterpret_cast<WPARAM>(ownerClient?focusPanel:nullptr),0)
|
||||
&& ownerClient) return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return CallNextHookEx(nullptr,code,message,data);
|
||||
}
|
||||
|
||||
std::wstring historyLower(std::wstring value)
|
||||
{
|
||||
if(!value.empty()) CharLowerBuffW(value.data(),static_cast<DWORD>(value.size()));
|
||||
return value;
|
||||
}
|
||||
|
||||
std::wstring_view commandTopicKeywords(const std::wstring &command)
|
||||
{
|
||||
const auto start=command.find_first_not_of(L" \t");
|
||||
if(start==command.npos) return L"";
|
||||
const auto end=command.find_first_of(L" \t",start);
|
||||
auto tool=command.substr(start,end-start);
|
||||
if(tool.ends_with(L".exe")) tool.resize(tool.size()-4);
|
||||
const auto args=end==command.npos?L"":command.substr(end);
|
||||
if(tool==L"ipconfig" && args.find(L"/flushdns")!=args.npos)
|
||||
return L"network tools мережа dns flush clear cache очистити кеш";
|
||||
if(tool==L"nslookup" || tool==L"resolve-dnsname")
|
||||
return L"network tools мережа dns lookup запит";
|
||||
if(tool==L"ping" || tool==L"tracert" || tool==L"ipconfig" || tool==L"test-netconnection" ||
|
||||
tool==L"netstat" || tool==L"curl" || tool==L"invoke-webrequest")
|
||||
return L"network tools мережа з’єднання connectivity address адреса";
|
||||
if(tool==L"cls" || tool==L"clear" || tool==L"clear-host")
|
||||
return L"terminal clear screen очистити екран консоль";
|
||||
if(tool==L"git")
|
||||
{
|
||||
const auto first=args.find_first_not_of(L" \t");
|
||||
const auto action=first==args.npos?L"":args.substr(first,args.find_first_of(L" \t",first)-first);
|
||||
if(action==L"pull" || action==L"fetch" || action==L"update")
|
||||
return L"git version control repository update fetch pull оновити репозиторій синхронізація";
|
||||
return L"git version control repository репозиторій контроль версій";
|
||||
}
|
||||
return L"";
|
||||
}
|
||||
|
||||
void populateCommandHistory(HWND dialog)
|
||||
{
|
||||
const auto search=GetDlgItem(dialog,historySearch);
|
||||
std::wstring query(GetWindowTextLengthW(search)+1,L'\0');
|
||||
query.resize(GetWindowTextW(search,query.data(),static_cast<int>(query.size())));
|
||||
query=historyLower(std::move(query));
|
||||
std::wistringstream stream(query);
|
||||
std::vector<std::wstring> words;
|
||||
for(std::wstring word;stream>>word;) words.push_back(word);
|
||||
|
||||
const auto list=GetDlgItem(dialog,historyList);
|
||||
SendMessageW(list,WM_SETREDRAW,FALSE,0);
|
||||
SendMessageW(list,LB_RESETCONTENT,0,0);
|
||||
const auto add=[&](const std::wstring &label,LPARAM index)
|
||||
{
|
||||
const auto row=SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
|
||||
if(row>=0) SendMessageW(list,LB_SETITEMDATA,row,index);
|
||||
return row;
|
||||
};
|
||||
std::array<std::vector<size_t>,2> matches;
|
||||
std::set<std::wstring_view> seen;
|
||||
for(size_t index=terminalHistory.size();index-- > 0;)
|
||||
{
|
||||
const auto &entry=terminalHistory[index];
|
||||
if(!seen.insert(entry.command).second) continue;
|
||||
const auto command=historyLower(entry.command);
|
||||
const auto containsAll=[&](const std::wstring &text)
|
||||
{
|
||||
return std::all_of(words.begin(),words.end(),[&](const auto &word){return text.find(word)!=text.npos;});
|
||||
};
|
||||
if(containsAll(command+L" "+entry.date))
|
||||
{
|
||||
matches[0].push_back(index);
|
||||
continue;
|
||||
}
|
||||
const auto keywords=commandTopicKeywords(command);
|
||||
if(!keywords.empty() && containsAll(command+L" "+entry.date+L" "+std::wstring(keywords)))
|
||||
matches[1].push_back(index);
|
||||
}
|
||||
LRESULT selected=LB_ERR;
|
||||
for(const auto &group:matches)
|
||||
{
|
||||
std::wstring lastDate;
|
||||
bool first=true;
|
||||
for(auto match=group.rbegin();match!=group.rend();++match)
|
||||
{
|
||||
const auto index=*match;
|
||||
const auto &entry=terminalHistory[index];
|
||||
const auto &date=entry.date;
|
||||
if(first || date!=lastDate) add(date,-1);
|
||||
first=false;
|
||||
lastDate=date;
|
||||
const auto row=add(entry.command,index);
|
||||
if(row>=0 && (words.empty() || selected==LB_ERR)) selected=row;
|
||||
}
|
||||
}
|
||||
if(selected==LB_ERR) add(words.empty()?L"No commands yet":L"No matching commands",-2);
|
||||
else SendMessageW(list,LB_SETCURSEL,selected,0);
|
||||
SendMessageW(list,WM_SETREDRAW,TRUE,0);
|
||||
InvalidateRect(list,nullptr,TRUE);
|
||||
}
|
||||
|
||||
LRESULT CALLBACK historySearchKeys(HWND search,UINT message,WPARAM key,LPARAM flags,UINT_PTR,DWORD_PTR)
|
||||
{
|
||||
if(message==WM_GETDLGCODE)
|
||||
{
|
||||
const auto code=DefSubclassProc(search,message,key,flags);
|
||||
if(key==VK_RETURN || key==VK_TAB || key==VK_ESCAPE) return code&~DLGC_WANTALLKEYS;
|
||||
return code|DLGC_WANTARROWS;
|
||||
}
|
||||
if(message==WM_KEYDOWN && (key==VK_UP || key==VK_DOWN))
|
||||
{
|
||||
const auto list=GetDlgItem(GetParent(search),historyList);
|
||||
SetFocus(list);
|
||||
SendMessageW(list,message,key,flags);
|
||||
return 0;
|
||||
}
|
||||
return DefSubclassProc(search,message,key,flags);
|
||||
}
|
||||
|
||||
|
||||
int historyRowInset(UINT dpi)
|
||||
{
|
||||
return std::max(MulDiv(4,dpi,96),dialogFrameMetrics(dpi).inner)+dialogRowTextInset(cellWidth);
|
||||
}
|
||||
|
||||
LRESULT CALLBACK historyListScroll(HWND list,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
|
||||
{
|
||||
if(message==LB_GETTOPINDEX || message==WM_NCDESTROY)
|
||||
return DefSubclassProc(list,message,wp,lp);
|
||||
const auto top=SendMessageW(list,LB_GETTOPINDEX,0,0);
|
||||
const auto result=scrollList(list,message,wp,lp);
|
||||
if(top!=SendMessageW(list,LB_GETTOPINDEX,0,0))
|
||||
InvalidateRect(GetParent(list),nullptr,FALSE);
|
||||
return result;
|
||||
}
|
||||
|
||||
void sizeCommandHistory(HWND dialog,HWND list,bool movingOwner=false)
|
||||
{
|
||||
const auto owner=GetWindow(dialog,GW_OWNER);
|
||||
RECT ownerBounds{};
|
||||
if(!GetWindowRect(owner,&ownerBounds) || IsIconic(owner)) return;
|
||||
MONITORINFO monitor{sizeof(monitor)};
|
||||
if(!GetMonitorInfoW(MonitorFromWindow(owner,MONITOR_DEFAULTTONEAREST),&monitor)) return;
|
||||
RECT area{};
|
||||
if(!IntersectRect(&area,&ownerBounds,&monitor.rcWork)) area=monitor.rcWork;
|
||||
|
||||
const auto dc=GetDC(list);
|
||||
if(!dc) return;
|
||||
const auto previous=SelectObject(dc,mono);
|
||||
LONG longest{};
|
||||
for(const auto &entry:terminalHistory)
|
||||
{
|
||||
SIZE size{};
|
||||
if(GetTextExtentPoint32W(dc,entry.command.c_str(),static_cast<int>(entry.command.size()),&size))
|
||||
longest=std::max(longest,size.cx);
|
||||
}
|
||||
SelectObject(dc,previous);
|
||||
ReleaseDC(list,dc);
|
||||
|
||||
const auto dpi=GetDpiForWindow(dialog);
|
||||
const auto frame=dialogFrameMetrics(dpi);
|
||||
const int inset=frame.content();
|
||||
const int top=dialogListInset(frame,textHeight);
|
||||
const int gap=MulDiv(4,dpi,96);
|
||||
const int listTop=top+2*textHeight+2*gap;
|
||||
const LONG desired=std::max<LONG>(MulDiv(320,dpi,96),
|
||||
longest+2*cellWidth+2*historyRowInset(dpi)+GetSystemMetricsForDpi(SM_CXVSCROLL,dpi))+2*inset;
|
||||
const auto target=std::min(desired,area.right-area.left);
|
||||
const auto rows=std::max<LRESULT>(1,SendMessageW(list,LB_GETCOUNT,0,0));
|
||||
RECT listWindow{},listClient{};
|
||||
GetWindowRect(list,&listWindow);
|
||||
GetClientRect(list,&listClient);
|
||||
const auto listBorder=listWindow.bottom-listWindow.top-listClient.bottom;
|
||||
const auto height=std::min<LONG>(listTop+rows*textHeight+listBorder+inset,
|
||||
area.bottom-area.top);
|
||||
const auto left=std::clamp((ownerBounds.left+ownerBounds.right-target)/2,area.left,area.right-target);
|
||||
const auto y=std::clamp((ownerBounds.top+ownerBounds.bottom-height)/2,area.top,area.bottom-height);
|
||||
RECT current{};
|
||||
if(movingOwner && GetWindowRect(dialog,¤t) &&
|
||||
current.right-current.left==target && current.bottom-current.top==height)
|
||||
{
|
||||
if(current.left!=left || current.top!=y)
|
||||
SetWindowPos(dialog,nullptr,left,y,0,0,SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
return;
|
||||
}
|
||||
SetWindowPos(dialog,nullptr,left,y,target,height,SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
const auto place=[&](HWND control,int rowTop,int rowHeight)
|
||||
{
|
||||
SetWindowPos(control,nullptr,inset,rowTop,std::max(1L,target-2*inset),rowHeight,
|
||||
SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
};
|
||||
place(GetDlgItem(dialog,historySearchLabel),top,textHeight);
|
||||
place(GetDlgItem(dialog,historySearch),top+textHeight+gap,textHeight);
|
||||
SetWindowPos(list,nullptr,inset,listTop,std::max(1L,target-2*inset-5),
|
||||
std::max(1L,height-listTop-inset),SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
GetClientRect(list,&listClient);
|
||||
if(rows*textHeight<=listClient.bottom) SendMessageW(list,LB_SETTOPINDEX,0,0);
|
||||
InvalidateRect(dialog,nullptr,FALSE);
|
||||
}
|
||||
|
||||
void layoutOpenCommandHistory(bool movingOwner=false)
|
||||
{
|
||||
if(commandHistoryWindow)
|
||||
sizeCommandHistory(commandHistoryWindow,GetDlgItem(commandHistoryWindow,historyList),movingOwner);
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK commandHistoryDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
prepareCopyDialog(dialog);
|
||||
const auto list=GetDlgItem(dialog,historyList);
|
||||
SetWindowSubclass(list,historyListScroll,1,0);
|
||||
SendMessageW(list,WM_SETFONT,reinterpret_cast<WPARAM>(mono),TRUE);
|
||||
SendMessageW(list,LB_SETITEMHEIGHT,0,std::max(1,textHeight));
|
||||
const auto search=GetDlgItem(dialog,historySearch);
|
||||
SendDlgItemMessageW(dialog,historySearchLabel,WM_SETFONT,reinterpret_cast<WPARAM>(mono),TRUE);
|
||||
SetWindowSubclass(search,historySearchKeys,1,0);
|
||||
populateCommandHistory(dialog);
|
||||
sizeCommandHistory(dialog,list);
|
||||
SetFocus(search);
|
||||
return FALSE;
|
||||
}
|
||||
if(message==WM_COMMAND && LOWORD(wp)==historySearch && HIWORD(wp)==EN_CHANGE)
|
||||
{
|
||||
populateCommandHistory(dialog);
|
||||
sizeCommandHistory(dialog,GetDlgItem(dialog,historyList));
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_NCDESTROY && commandHistoryWindow==dialog)
|
||||
{
|
||||
if(historyMouseHook) UnhookWindowsHookEx(historyMouseHook);
|
||||
historyMouseHook=nullptr;
|
||||
commandHistoryWindow=nullptr;
|
||||
}
|
||||
if(message==WM_CTLCOLORLISTBOX || message==WM_CTLCOLOREDIT)
|
||||
{
|
||||
const auto dc=reinterpret_cast<HDC>(wp);
|
||||
const bool search=message==WM_CTLCOLOREDIT;
|
||||
SetTextColor(dc,search?RGB(0,0,0):colors[Text]);
|
||||
const auto background=search?historySearchSurface:colors[Dialog];
|
||||
SetBkColor(dc,background);
|
||||
if(search) SetDCBrushColor(dc,background);
|
||||
return reinterpret_cast<INT_PTR>(search?GetStockObject(DC_BRUSH):teal);
|
||||
}
|
||||
if(message!=WM_DRAWITEM || wp!=historyList)
|
||||
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" History ",false,{},true,
|
||||
GetDlgItem(dialog,historyList)))
|
||||
return painted;
|
||||
if(message==WM_DRAWITEM && wp==historyList)
|
||||
{
|
||||
const auto &item=*reinterpret_cast<DRAWITEMSTRUCT*>(lp);
|
||||
if(item.itemID==UINT(-1)) return TRUE;
|
||||
const auto count=SendMessageW(item.hwndItem,LB_GETTEXTLEN,item.itemID,0);
|
||||
if(count<0) return TRUE;
|
||||
std::wstring label(static_cast<size_t>(count)+1,L'\0');
|
||||
SendMessageW(item.hwndItem,LB_GETTEXT,item.itemID,reinterpret_cast<LPARAM>(label.data()));
|
||||
label.resize(count);
|
||||
const bool selected=(item.itemState&ODS_SELECTED)!=0 && item.itemData<terminalHistory.size();
|
||||
const auto background=colors[selected?Selection:Dialog];
|
||||
const auto ink=colors[Text];
|
||||
if(item.itemData==static_cast<ULONG_PTR>(-1))
|
||||
{
|
||||
auto bounds=item.rcItem;
|
||||
InflateRect(&bounds,-historyRowInset(GetDpiForWindow(dialog)),0);
|
||||
const auto saved=SaveDC(item.hDC);
|
||||
SelectObject(item.hDC,mono);
|
||||
SetBkColor(item.hDC,background);
|
||||
SetTextColor(item.hDC,ink);
|
||||
ExtTextOutW(item.hDC,0,0,ETO_OPAQUE,&bounds,nullptr,0,nullptr);
|
||||
const auto middle=(bounds.top+bounds.bottom)/2;
|
||||
RECT rule{bounds.left,middle,bounds.right,middle+1};
|
||||
SetBkColor(item.hDC,ink);
|
||||
ExtTextOutW(item.hDC,0,0,ETO_OPAQUE,&rule,nullptr,0,nullptr);
|
||||
SIZE size{};
|
||||
GetTextExtentPoint32W(item.hDC,label.c_str(),static_cast<int>(label.size()),&size);
|
||||
const auto left=(bounds.left+bounds.right-size.cx)/2;
|
||||
RECT caption{left-cellWidth,bounds.top,left+size.cx+cellWidth,bounds.bottom};
|
||||
SetBkColor(item.hDC,background);
|
||||
ExtTextOutW(item.hDC,left,middle-size.cy/2,ETO_OPAQUE,&caption,label.c_str(),
|
||||
static_cast<UINT>(label.size()),nullptr);
|
||||
RestoreDC(item.hDC,saved);
|
||||
}
|
||||
else paintDialogListRow(item.hDC,item.rcItem,label,mono,ink,background,
|
||||
historyRowInset(GetDpiForWindow(dialog)),DT_END_ELLIPSIS);
|
||||
if(selected && (item.itemState&ODS_FOCUS)) DrawFocusRect(item.hDC,&item.rcItem);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
const auto owner=GetWindow(dialog,GW_OWNER);
|
||||
const auto focusPanel=message==WM_CLOSE?reinterpret_cast<HWND>(wp):panels[active].list;
|
||||
DestroyWindow(dialog);
|
||||
if(focusPanel && IsWindow(owner) && !IsIconic(owner))
|
||||
{
|
||||
SetActiveWindow(owner);
|
||||
SetFocus(focusPanel);
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_COMMAND && (LOWORD(wp)==IDOK || (LOWORD(wp)==historyList && HIWORD(wp)==LBN_DBLCLK)))
|
||||
{
|
||||
const auto row=SendDlgItemMessageW(dialog,historyList,LB_GETCURSEL,0,0);
|
||||
const auto index=SendDlgItemMessageW(dialog,historyList,LB_GETITEMDATA,row,0);
|
||||
if(index>=0 && static_cast<size_t>(index)<terminalHistory.size())
|
||||
{
|
||||
const auto owner=GetWindow(dialog,GW_OWNER);
|
||||
DestroyWindow(dialog);
|
||||
SetActiveWindow(owner);
|
||||
recallCommand(static_cast<size_t>(index));
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
void refreshCommandHistory()
|
||||
{
|
||||
if(commandHistoryWindow) populateCommandHistory(commandHistoryWindow);
|
||||
layoutOpenCommandHistory();
|
||||
}
|
||||
|
||||
void showCommandHistory(HWND owner)
|
||||
{
|
||||
if(!commandHistoryWindow)
|
||||
commandHistoryWindow=CreateDialogParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(111),owner,commandHistoryDialog,0);
|
||||
if(!commandHistoryWindow) return;
|
||||
if(!historyMouseHook)
|
||||
historyMouseHook=SetWindowsHookExW(WH_MOUSE_LL,dismissHistoryOnOutsideClick,GetModuleHandleW(nullptr),0);
|
||||
ShowWindow(commandHistoryWindow,SW_SHOW);
|
||||
SetActiveWindow(commandHistoryWindow);
|
||||
SetFocus(GetDlgItem(commandHistoryWindow,historySearch));
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
HWND activeFilesDialog{};
|
||||
HHOOK filesDialogMouseHook{};
|
||||
|
||||
bool filesMouseDown(UINT message)
|
||||
{
|
||||
return message==WM_LBUTTONDOWN || message==WM_RBUTTONDOWN ||
|
||||
message==WM_MBUTTONDOWN || message==WM_XBUTTONDOWN;
|
||||
}
|
||||
|
||||
LRESULT CALLBACK filesDialogMouse(int code,WPARAM message,LPARAM data)
|
||||
{
|
||||
const auto dialog=activeFilesDialog;
|
||||
if(code==HC_ACTION && dialog && IsWindowVisible(dialog) && filesMouseDown(static_cast<UINT>(message)))
|
||||
{
|
||||
const auto point=reinterpret_cast<const MSLLHOOKSTRUCT*>(data)->pt;
|
||||
const auto clicked=WindowFromPoint(point);
|
||||
const auto root=GetAncestor(dialog,GA_ROOTOWNER);
|
||||
if(clicked!=dialog && !IsChild(dialog,clicked))
|
||||
{
|
||||
RECT client{};
|
||||
POINT local=point;
|
||||
GetClientRect(root,&client);
|
||||
ScreenToClient(root,&local);
|
||||
if(clicked!=root || PtInRect(&client,local))
|
||||
{
|
||||
const bool internal=clicked==root || IsChild(root,clicked) ||
|
||||
(clicked && GetAncestor(clicked,GA_ROOTOWNER)==root);
|
||||
if(PostMessageW(dialog,WM_COMMAND,IDCANCEL,0) && internal) return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return CallNextHookEx(nullptr,code,message,data);
|
||||
}
|
||||
|
||||
struct FilesDialogInput
|
||||
{
|
||||
HWND previous=activeFilesDialog;
|
||||
explicit FilesDialogInput(HWND dialog)
|
||||
{
|
||||
activeFilesDialog=dialog;
|
||||
if(!filesDialogMouseHook)
|
||||
filesDialogMouseHook=SetWindowsHookExW(WH_MOUSE_LL,filesDialogMouse,GetModuleHandleW(nullptr),0);
|
||||
}
|
||||
|
||||
~FilesDialogInput()
|
||||
{
|
||||
activeFilesDialog=previous;
|
||||
if(!previous && filesDialogMouseHook)
|
||||
{
|
||||
UnhookWindowsHookEx(filesDialogMouseHook);
|
||||
filesDialogMouseHook=nullptr;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
bool filesDialogHandlesMessage(HWND dialog,MSG &message)
|
||||
{
|
||||
if(message.hwnd==dialog || IsChild(dialog,message.hwnd)) return IsDialogMessageW(dialog,&message);
|
||||
if(!message.hwnd || GetAncestor(message.hwnd,GA_ROOTOWNER)!=GetAncestor(dialog,GA_ROOTOWNER)) return false;
|
||||
const bool input=(message.message>=WM_KEYFIRST && message.message<=WM_KEYLAST) ||
|
||||
(message.message>=WM_MOUSEFIRST && message.message<=WM_MOUSELAST) ||
|
||||
message.message==WM_CONTEXTMENU;
|
||||
if(input && message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE)
|
||||
PostMessageW(dialog,WM_COMMAND,IDCANCEL,0);
|
||||
return input;
|
||||
}
|
||||
|
||||
struct FilesDialogResult
|
||||
{
|
||||
DLGPROC procedure;
|
||||
LPARAM argument;
|
||||
INT_PTR result=IDCANCEL;
|
||||
bool finished=false;
|
||||
};
|
||||
|
||||
constexpr wchar_t filesDialogResultProperty[]=L"KSwitcher.Files.DialogResult";
|
||||
|
||||
INT_PTR CALLBACK filesDialogProcedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
auto *result=reinterpret_cast<FilesDialogResult*>(GetPropW(dialog,filesDialogResultProperty));
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
result=reinterpret_cast<FilesDialogResult*>(lp);
|
||||
if(!SetPropW(dialog,filesDialogResultProperty,result)) return FALSE;
|
||||
lp=result->argument;
|
||||
}
|
||||
if(!result) return FALSE;
|
||||
const auto handled=result->procedure(dialog,message,wp,lp);
|
||||
if(message==WM_NCDESTROY) RemovePropW(dialog,filesDialogResultProperty);
|
||||
return handled;
|
||||
}
|
||||
|
||||
void finishFilesDialog(HWND dialog,INT_PTR answer)
|
||||
{
|
||||
auto *result=reinterpret_cast<FilesDialogResult*>(GetPropW(dialog,filesDialogResultProperty));
|
||||
if(!result) return;
|
||||
result->result=answer;
|
||||
result->finished=true;
|
||||
ShowWindow(dialog,SW_HIDE);
|
||||
}
|
||||
|
||||
INT_PTR runFilesDialog(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument)
|
||||
{
|
||||
FilesDialogResult result{procedure,argument};
|
||||
const auto dialog=CreateDialogParamW(instance,resource,owner,filesDialogProcedure,
|
||||
reinterpret_cast<LPARAM>(&result));
|
||||
if(!dialog) return -1;
|
||||
GetWindowRect(GetAncestor(owner,GA_ROOTOWNER),&previousOwnerBounds);
|
||||
FilesDialogInput input(dialog);
|
||||
ShowWindow(dialog,SW_SHOW);
|
||||
SetActiveWindow(dialog);
|
||||
MSG message{};
|
||||
while(!result.finished && IsWindow(dialog))
|
||||
{
|
||||
const auto status=GetMessageW(&message,nullptr,0,0);
|
||||
if(status<=0)
|
||||
{
|
||||
if(status==0) PostQuitMessage(static_cast<int>(message.wParam));
|
||||
break;
|
||||
}
|
||||
if(filesDialogHandlesMessage(dialog,message)) continue;
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
if(IsWindow(dialog)) DestroyWindow(dialog);
|
||||
if(IsWindow(owner) && !IsIconic(GetAncestor(owner,GA_ROOTOWNER))) SetActiveWindow(owner);
|
||||
return result.result;
|
||||
}
|
||||
@@ -104,7 +104,7 @@ INT_PTR CALLBACK folderShortcutEditDialog(HWND dialog,UINT message,WPARAM wp,LPA
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
EndDialog(dialog,IDCANCEL);
|
||||
finishFilesDialog(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
|
||||
@@ -139,13 +139,14 @@ INT_PTR CALLBACK folderShortcutEditDialog(HWND dialog,UINT message,WPARAM wp,LPA
|
||||
return TRUE;
|
||||
}
|
||||
folderShortcuts=std::move(updated);
|
||||
EndDialog(dialog,IDOK);
|
||||
notifyFilesPreferences(GetAncestor(dialog,GA_ROOTOWNER));
|
||||
finishFilesDialog(dialog,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
bool editFolderShortcut(HWND owner,FolderShortcutEdit &edit)
|
||||
{
|
||||
return DialogBoxParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(110),owner,
|
||||
return runFilesDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(110),owner,
|
||||
folderShortcutEditDialog,reinterpret_cast<LPARAM>(&edit))==IDOK;
|
||||
}
|
||||
|
||||
@@ -186,14 +187,21 @@ struct FolderShortcutView
|
||||
std::vector<int> digits;
|
||||
int rowHeight{};
|
||||
Panel *panel{};
|
||||
HHOOK mouseHook{};
|
||||
bool all{};
|
||||
std::vector<std::pair<int,size_t>> entries;
|
||||
};
|
||||
|
||||
std::wstring shortcutLabel(const FolderShortcut &entry)
|
||||
{
|
||||
return entry.title.empty()?(entry.peerId.empty()?L"":entry.peerName+L" · ")+entry.path.native():entry.title;
|
||||
}
|
||||
|
||||
void layoutQuickFolders(HWND dialog,FolderShortcutView &view,int selection)
|
||||
{
|
||||
const auto list=GetDlgItem(dialog,shortcutList);
|
||||
SendMessageW(list,LB_RESETCONTENT,0,0);
|
||||
view.digits.clear();
|
||||
view.entries.clear();
|
||||
const auto owner=GetWindow(dialog,GW_OWNER);
|
||||
const auto dc=GetDC(dialog);
|
||||
const auto font=SelectObject(dc,mono);
|
||||
@@ -211,14 +219,23 @@ void layoutQuickFolders(HWND dialog,FolderShortcutView &view,int selection)
|
||||
GetTextExtentPoint32W(dc,label.data(),static_cast<int>(label.size()),&size);
|
||||
return static_cast<int>(size.cx);
|
||||
};
|
||||
int width=std::max(measure(L"Folder shortcuts"),measure(view.digit<0?L"Enter Esc":quickFolderHints))+3*cellWidth;
|
||||
int width=std::max(measure(L"Folder shortcuts"),measure(view.all?L"Del F4":view.digit<0?L"Enter Esc":quickFolderHints))+3*cellWidth;
|
||||
const int textInset=dialogRowTextInset(cellWidth);
|
||||
const auto add=[&](const std::wstring &label)
|
||||
{
|
||||
width=std::max(width,measure(label)+2*textInset);
|
||||
SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
|
||||
};
|
||||
if(view.digit<0)
|
||||
if(view.all)
|
||||
{
|
||||
for(int digit=0;digit<static_cast<int>(folderShortcuts.size());++digit)
|
||||
for(size_t index=0;index<folderShortcuts[digit].size();++index)
|
||||
{
|
||||
view.entries.emplace_back(digit,index);
|
||||
add(std::to_wstring(digit)+L" "+shortcutLabel(folderShortcuts[digit][index]));
|
||||
}
|
||||
}
|
||||
else if(view.digit<0)
|
||||
{
|
||||
for(int digit=0;digit<10;++digit)
|
||||
if(!folderShortcuts[digit].empty())
|
||||
@@ -228,7 +245,7 @@ void layoutQuickFolders(HWND dialog,FolderShortcutView &view,int selection)
|
||||
}
|
||||
}
|
||||
else for(const auto &entry:folderShortcuts[view.digit])
|
||||
add(entry.title.empty()?(entry.peerId.empty()?L"":entry.peerName+L" · ")+entry.path.native():entry.title);
|
||||
add(shortcutLabel(entry));
|
||||
SelectObject(dc,font);
|
||||
ReleaseDC(dialog,dc);
|
||||
MONITORINFO monitor{sizeof(monitor)};
|
||||
@@ -275,26 +292,6 @@ LRESULT CALLBACK quickFolderKeys(HWND list,UINT message,WPARAM key,LPARAM flags,
|
||||
return scrollList(list,message,key,flags);
|
||||
}
|
||||
|
||||
HWND quickFolderWindow{};
|
||||
|
||||
bool dismissQuickFoldersAt(HWND dialog,POINT point)
|
||||
{
|
||||
RECT bounds{};
|
||||
if(!dialog || !IsWindowVisible(dialog) || !IsWindowEnabled(dialog) ||
|
||||
GetForegroundWindow()!=dialog || !GetWindowRect(dialog,&bounds) || PtInRect(&bounds,point))
|
||||
return false;
|
||||
return PostMessageW(dialog,WM_COMMAND,IDCANCEL,0)!=FALSE;
|
||||
}
|
||||
|
||||
LRESULT CALLBACK quickFolderMouse(int code,WPARAM message,LPARAM data)
|
||||
{
|
||||
if(code==HC_ACTION && (message==WM_LBUTTONDOWN || message==WM_RBUTTONDOWN ||
|
||||
message==WM_MBUTTONDOWN || message==WM_XBUTTONDOWN) &&
|
||||
dismissQuickFoldersAt(quickFolderWindow,reinterpret_cast<const MSLLHOOKSTRUCT*>(data)->pt))
|
||||
return 1;
|
||||
return CallNextHookEx(nullptr,code,message,data);
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
@@ -305,8 +302,6 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
layoutQuickFolders(dialog,view,0);
|
||||
const auto list=GetDlgItem(dialog,shortcutList);
|
||||
SetWindowSubclass(list,quickFolderKeys,1,0);
|
||||
quickFolderWindow=dialog;
|
||||
view.mouseHook=SetWindowsHookExW(WH_MOUSE_LL,quickFolderMouse,GetModuleHandleW(nullptr),0);
|
||||
SetFocus(list);
|
||||
return FALSE;
|
||||
}
|
||||
@@ -314,8 +309,6 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
if(!view) return FALSE;
|
||||
if(message==WM_DESTROY)
|
||||
{
|
||||
if(view->mouseHook) UnhookWindowsHookEx(view->mouseHook);
|
||||
quickFolderWindow=nullptr;
|
||||
return FALSE;
|
||||
}
|
||||
if(message==WM_PAINT)
|
||||
@@ -328,7 +321,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
const auto bounds=paintDialogFrame(dc,client,dialogFrameMetrics(GetDpiForWindow(dialog)),teal,frame);
|
||||
DeleteObject(frame);
|
||||
paintDialogFrameCaptions(dc,client,bounds,L"Folder shortcuts",teal,colors[Text],mono,
|
||||
view->digit<0?L"Enter Esc":quickFolderHints);
|
||||
view->all?L"Del F4":view->digit<0?L"Enter Esc":quickFolderHints);
|
||||
EndPaint(dialog,&ps);
|
||||
return TRUE;
|
||||
}
|
||||
@@ -347,7 +340,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
EndDialog(dialog,IDCANCEL);
|
||||
finishFilesDialog(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
if(message!=WM_COMMAND) return FALSE;
|
||||
@@ -355,7 +348,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
if(action!=quickRemove && action!=quickEdit && action!=quickInsert && action!=quickMoveUp &&
|
||||
action!=quickMoveDown && action!=IDOK && !(action==shortcutList && HIWORD(wp)==LBN_DBLCLK)) return FALSE;
|
||||
const auto row=SendDlgItemMessageW(dialog,shortcutList,LB_GETCURSEL,0,0);
|
||||
if(view->digit<0)
|
||||
if(!view->all && view->digit<0)
|
||||
{
|
||||
if((action==IDOK || action==shortcutList) && row>=0 && static_cast<size_t>(row)<view->digits.size())
|
||||
{
|
||||
@@ -364,7 +357,17 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
const auto &group=folderShortcuts[view->digit];
|
||||
int digit=view->digit;
|
||||
size_t index=static_cast<size_t>(row);
|
||||
if(view->all)
|
||||
{
|
||||
if(index>=view->entries.size() || action==quickInsert ||
|
||||
action==quickMoveUp || action==quickMoveDown) return TRUE;
|
||||
const auto &entry=view->entries[index];
|
||||
digit=entry.first;
|
||||
index=entry.second;
|
||||
}
|
||||
const auto &group=folderShortcuts[digit];
|
||||
if(action==quickInsert)
|
||||
{
|
||||
const auto &panel=*view->panel;
|
||||
@@ -375,7 +378,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
SetFocus(GetDlgItem(dialog,shortcutList));
|
||||
return TRUE;
|
||||
}
|
||||
if(row<0 || static_cast<size_t>(row)>=group.size()) return TRUE;
|
||||
if(index>=group.size()) return TRUE;
|
||||
if(action==quickMoveUp || action==quickMoveDown)
|
||||
{
|
||||
const auto target=row+(action==quickMoveUp?-1:1);
|
||||
@@ -387,13 +390,14 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
else
|
||||
{
|
||||
folderShortcuts=std::move(updated);
|
||||
notifyFilesPreferences(GetAncestor(dialog,GA_ROOTOWNER));
|
||||
layoutQuickFolders(dialog,*view,static_cast<int>(target));
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
if(action==quickEdit)
|
||||
{
|
||||
FolderShortcutEdit edit{group[row],view->digit,static_cast<size_t>(row)};
|
||||
FolderShortcutEdit edit{group[index],digit,index};
|
||||
if(editFolderShortcut(dialog,edit)) layoutQuickFolders(dialog,*view,static_cast<int>(row));
|
||||
SetFocus(GetDlgItem(dialog,shortcutList));
|
||||
return TRUE;
|
||||
@@ -401,24 +405,25 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
if(action==quickRemove)
|
||||
{
|
||||
auto updated=folderShortcuts;
|
||||
updated[view->digit].erase(updated[view->digit].begin()+row);
|
||||
updated[digit].erase(updated[digit].begin()+index);
|
||||
if(!saveFolderShortcuts(updated))
|
||||
{
|
||||
MessageBoxW(dialog,L"Could not save folder shortcuts.",L"Folder shortcuts",MB_OK|MB_ICONWARNING);
|
||||
return TRUE;
|
||||
}
|
||||
folderShortcuts=std::move(updated);
|
||||
if(folderShortcuts[view->digit].empty()) EndDialog(dialog,IDCANCEL);
|
||||
notifyFilesPreferences(GetAncestor(dialog,GA_ROOTOWNER));
|
||||
if(view->all?view->entries.size()==1:folderShortcuts[digit].empty()) finishFilesDialog(dialog,IDCANCEL);
|
||||
else layoutQuickFolders(dialog,*view,static_cast<int>(row));
|
||||
return TRUE;
|
||||
}
|
||||
view->chosen=group[row];
|
||||
EndDialog(dialog,IDOK);
|
||||
view->chosen=group[index];
|
||||
finishFilesDialog(dialog,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
|
||||
void showFolderShortcuts(Panel &panel,int digit)
|
||||
void showFolderShortcuts(Panel &panel,int digit,bool all)
|
||||
{
|
||||
if(digit>=0)
|
||||
{
|
||||
@@ -441,7 +446,8 @@ void showFolderShortcuts(Panel &panel,int digit)
|
||||
}
|
||||
FolderShortcutView view{digit};
|
||||
view.panel=&panel;
|
||||
const auto result=DialogBoxParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(109),GetParent(panel.list),
|
||||
view.all=all;
|
||||
const auto result=runFilesDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(109),GetParent(panel.list),
|
||||
quickFolderDialog,reinterpret_cast<LPARAM>(&view));
|
||||
SetFocus(panel.list);
|
||||
if(result==IDOK && view.chosen) openFolderShortcut(panel,*view.chosen);
|
||||
|
||||
+493
-133
File diff suppressed because it is too large.
Load diff
+121
-48
@@ -1,7 +1,7 @@
|
||||
constexpr int optionsSearch=270,optionsTree=271,optionsTitle=272,optionsApply=283,optionsReset=284,optionsProperty=285,optionsResetProperty=286;
|
||||
constexpr int allOptions=3;
|
||||
enum OptionsPage { PanelModes, PanelColors, Appearance };
|
||||
constexpr const wchar_t *optionsTitles[]{L"File panel modes",L"Colors",L"Appearance"};
|
||||
constexpr int allOptions=4;
|
||||
enum OptionsPage { PanelModes, PanelColors, Appearance, CommandLine };
|
||||
constexpr const wchar_t *optionsTitles[]{L"File panel modes",L"Colors",L"Appearance",L"Command line"};
|
||||
constexpr const wchar_t *colorNames[]{L"Panel background",L"Text",L"Frame",L"Popup background",
|
||||
L"Menu selection",L"Command bar",L"File cursor"};
|
||||
enum PanelSection { PanelLayout, WideColumns, StatusColumns };
|
||||
@@ -52,8 +52,22 @@ void resetPanelProperty(HWND dialog,const PanelProperty &property)
|
||||
else CheckDlgButton(dialog,property.control,property.defaultValue);
|
||||
}
|
||||
|
||||
struct OptionsBaseline
|
||||
{
|
||||
LOGFONTW font=displayFont;
|
||||
int points=fontPoints;
|
||||
DialogFramePadding padding=dialogFramePadding;
|
||||
std::array<COLORREF,ColorCount> palette=colors;
|
||||
std::vector<FileStyle> styles=fileStyles;
|
||||
std::array<WORD,2> keys=commandHistoryKeys;
|
||||
DWORD width=static_cast<DWORD>(sizeWidth), fields=statusFields;
|
||||
bool extensions=alignExtensions, folders=alignFolders, details=showDetails;
|
||||
std::array<bool,2> wide{panels[0].wide,panels[1].wide};
|
||||
};
|
||||
|
||||
struct OptionsDraft
|
||||
{
|
||||
OptionsBaseline baseline;
|
||||
LOGFONTW font=displayFont;
|
||||
int points=fontPoints;
|
||||
DialogFramePadding framePadding=dialogFramePadding;
|
||||
@@ -81,15 +95,28 @@ struct OptionsDraft
|
||||
|
||||
bool optionsFontChanged(const OptionsDraft &draft)
|
||||
{
|
||||
auto pending=draft.font, applied=displayFont;
|
||||
auto pending=draft.font, applied=draft.baseline.font;
|
||||
// Height follows the selected point size and DPI. applyFont always uses natural width.
|
||||
pending.lfHeight=applied.lfHeight=0;
|
||||
pending.lfWidth=applied.lfWidth=0;
|
||||
return draft.points!=fontPoints ||
|
||||
return draft.points!=draft.baseline.points ||
|
||||
memcmp(&pending,&applied,offsetof(LOGFONTW,lfFaceName))!=0 ||
|
||||
_wcsicmp(pending.lfFaceName,applied.lfFaceName)!=0;
|
||||
}
|
||||
|
||||
struct OptionsWriteLock
|
||||
{
|
||||
HANDLE mutex=CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.OptionsWrite");
|
||||
DWORD result=mutex?WaitForSingleObject(mutex,2000):WAIT_FAILED;
|
||||
|
||||
bool acquired() const { return result==WAIT_OBJECT_0 || result==WAIT_ABANDONED; }
|
||||
~OptionsWriteLock()
|
||||
{
|
||||
if(acquired()) ReleaseMutex(mutex);
|
||||
if(mutex) CloseHandle(mutex);
|
||||
}
|
||||
};
|
||||
|
||||
void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
|
||||
{
|
||||
BOOL valid{};
|
||||
@@ -97,11 +124,13 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
|
||||
const auto checked=[&](int id){return IsDlgButtonChecked(dialog,id)==BST_CHECKED;};
|
||||
DWORD fields=0;
|
||||
for(int i=0;i<4;++i) if(checked(205+i)) fields|=1u<<i;
|
||||
const bool dirty=!valid || width!=static_cast<UINT>(sizeWidth) ||
|
||||
checked(273)!=panels[0].wide || checked(274)!=panels[1].wide ||
|
||||
checked(202)!=alignExtensions || checked(204)!=alignFolders || checked(203)!=showDetails ||
|
||||
fields!=statusFields || draft.palette!=colors || draft.styles!=fileStyles ||
|
||||
draft.framePadding!=dialogFramePadding || optionsFontChanged(draft);
|
||||
const auto &base=draft.baseline;
|
||||
const bool dirty=!valid || width!=base.width ||
|
||||
checked(273)!=base.wide[0] || checked(274)!=base.wide[1] ||
|
||||
checked(202)!=base.extensions || checked(204)!=base.folders || checked(203)!=base.details ||
|
||||
fields!=base.fields || draft.palette!=base.palette || draft.styles!=base.styles ||
|
||||
draft.framePadding!=base.padding || optionsFontChanged(draft) ||
|
||||
optionHistoryKeys(dialog)!=base.keys;
|
||||
EnableWindow(GetDlgItem(dialog,optionsApply),dirty);
|
||||
InvalidateRect(GetDlgItem(dialog,fileStylePreview),nullptr,FALSE);
|
||||
}
|
||||
@@ -181,7 +210,7 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
|
||||
if(section>=0)
|
||||
title=page==PanelModes?panelSectionNames[section]:page==PanelColors?
|
||||
(section==fileStyleSection?L"File type styles":colorNames[section]):
|
||||
section==DialogFrame?L"Dialog frame":L"Font";
|
||||
page==CommandLine?L"Command history":section==DialogFrame?L"Dialog frame":L"Font";
|
||||
}
|
||||
SetDlgItemTextW(dialog,optionsTitle,title);
|
||||
const auto show=[&](auto &controls,bool visible)
|
||||
@@ -215,11 +244,13 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
|
||||
for(const auto &option:frameOptions)
|
||||
SendDlgItemMessageW(dialog,option.id,CB_SETCURSEL,draft.framePadding.*option.value,0);
|
||||
}
|
||||
constexpr int commandLineControls[]{320,321,322,323};
|
||||
show(commandLineControls,page==CommandLine && section==0);
|
||||
const bool fileTypes=page==PanelColors && section==fileStyleSection;
|
||||
constexpr int fileStyleControls[]{287,288,289,290,291,292,293,294,295,296,297,298,300,fileStyleState};
|
||||
show(fileStyleControls,fileTypes);
|
||||
const auto preview=GetDlgItem(dialog,fileStylePreview);
|
||||
ShowWindow(preview,page>=0 && page<allOptions && section>=0?SW_SHOW:SW_HIDE);
|
||||
ShowWindow(preview,page>=0 && page<CommandLine && section>=0?SW_SHOW:SW_HIDE);
|
||||
layoutOptionsPreview(dialog);
|
||||
RedrawWindow(dialog,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN);
|
||||
show(colorOptionControls,page==PanelColors && section>=0 && !fileTypes);
|
||||
@@ -275,7 +306,7 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
|
||||
draft.wideColumnsNode=nullptr;
|
||||
const auto root=add(L"All settings",allOptions,-1,TVI_ROOT);
|
||||
HTREEITEM first{},selected{};
|
||||
for(int page=PanelModes;page<=Appearance;++page)
|
||||
for(int page=PanelModes;page<=CommandLine;++page)
|
||||
{
|
||||
HTREEITEM category{};
|
||||
const bool wholeCategory=matches(optionsTitles[page]) || (!query.empty() && matches(L"All settings"));
|
||||
@@ -305,6 +336,7 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
|
||||
addSection(L"File type styles",fileStyleSection,extensionMatches || matches(L"System and hidden") ||
|
||||
matches(L"Underline") || matches(L"Strikethrough") || matches(L"Foreground"));
|
||||
}
|
||||
else if(page==CommandLine) addSection(L"Command history",0,matches(L"Previous command"));
|
||||
else
|
||||
{
|
||||
addSection(L"Font",Font,matches(L"Display font"));
|
||||
@@ -349,6 +381,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
CheckDlgButton(dialog,273,panels[0].wide);
|
||||
CheckDlgButton(dialog,274,panels[1].wide);
|
||||
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
|
||||
setOptionHistoryKeys(dialog,commandHistoryKeys);
|
||||
filterOptions(dialog,draft);
|
||||
updateOptionsApply(dialog,draft);
|
||||
return TRUE;
|
||||
@@ -388,7 +421,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
EndDialog(dialog,IDCANCEL);
|
||||
finishFilesDialog(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
if(message!=WM_COMMAND) return FALSE;
|
||||
@@ -461,6 +494,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
return TRUE;
|
||||
case optionsReset:
|
||||
if(draft->page==allOptions || draft->page==CommandLine) setOptionHistoryKeys(dialog,defaultHistoryKeys);
|
||||
if(draft->page==allOptions || draft->page==PanelModes)
|
||||
for(const auto &property:panelProperties)
|
||||
if(draft->section<0 || property.section==draft->section) resetPanelProperty(dialog,property);
|
||||
@@ -498,6 +532,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
case 273: case 274:
|
||||
updateOptionsApply(dialog,*draft);
|
||||
return TRUE;
|
||||
case 321: case 323:
|
||||
updateOptionsApply(dialog,*draft);
|
||||
return TRUE;
|
||||
case optionsApply:
|
||||
case IDOK:
|
||||
{
|
||||
@@ -513,7 +550,30 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
return TRUE;
|
||||
}
|
||||
const auto owner=GetWindow(dialog,GW_OWNER);
|
||||
const bool stylesChanged=draft->styles!=fileStyles;
|
||||
const OptionsWriteLock writeLock;
|
||||
if(!writeLock.acquired())
|
||||
{
|
||||
setStatus(L"Another window is saving Files settings. Try Apply again.");
|
||||
return TRUE;
|
||||
}
|
||||
const auto &base=draft->baseline;
|
||||
auto keys=optionHistoryKeys(dialog);
|
||||
loadCommandHistoryKeys();
|
||||
for(size_t i=0;i<keys.size();++i)
|
||||
if(keys[i]==base.keys[i]) keys[i]=commandHistoryKeys[i];
|
||||
if(!validHistoryKeys(keys))
|
||||
{
|
||||
MessageBoxW(dialog,L"Choose distinct shortcuts using Ctrl or Alt that are free in Files.",L"Command history",MB_OK|MB_ICONWARNING);
|
||||
return TRUE;
|
||||
}
|
||||
const bool stylesChanged=draft->styles!=base.styles;
|
||||
loadFileStyles();
|
||||
if(stylesChanged && fileStyles!=base.styles && fileStyles!=draft->styles)
|
||||
{
|
||||
MessageBoxW(dialog,L"File type styles changed in another window. Reopen Options before editing them again.",
|
||||
L"KSwitcher Files Options",MB_OK|MB_ICONWARNING);
|
||||
return TRUE;
|
||||
}
|
||||
if(stylesChanged && !saveFileStyles(draft->styles))
|
||||
{
|
||||
MessageBoxW(dialog,L"Could not save the file type styles.",L"KSwitcher Files Options",MB_OK|MB_ICONWARNING);
|
||||
@@ -526,48 +586,61 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
MessageBoxW(dialog,L"Could not apply the selected font.",optionsTitles[Appearance],MB_OK|MB_ICONWARNING);
|
||||
return TRUE;
|
||||
}
|
||||
if(stylesChanged) fileStyles=draft->styles;
|
||||
sizeWidth=static_cast<int>(width);
|
||||
alignExtensions=IsDlgButtonChecked(dialog,202)==BST_CHECKED;
|
||||
showDetails=IsDlgButtonChecked(dialog,203)==BST_CHECKED;
|
||||
alignFolders=IsDlgButtonChecked(dialog,204)==BST_CHECKED;
|
||||
statusFields=0;
|
||||
for(int i=0;i<4;++i)
|
||||
if(IsDlgButtonChecked(dialog,205+i)==BST_CHECKED) statusFields|=1u<<i;
|
||||
savePreference(L"SizeWidth",sizeWidth);
|
||||
savePreference(L"AlignExtensions",alignExtensions);
|
||||
savePreference(L"ShowDetails",showDetails);
|
||||
savePreference(L"AlignFolders",alignFolders);
|
||||
savePreference(L"StatusFields",statusFields);
|
||||
for(int i=0;i<ColorCount;++i)
|
||||
if(colors[i]!=draft->palette[i])
|
||||
{
|
||||
colors[i]=draft->palette[i];
|
||||
savePreference(std::to_wstring(i).c_str(),colors[i]);
|
||||
}
|
||||
refreshColors();
|
||||
if(draft->framePadding!=dialogFramePadding)
|
||||
const auto saveChanged=[](const wchar_t *name,DWORD value,DWORD initial)
|
||||
{
|
||||
dialogFramePadding=draft->framePadding;
|
||||
savePreference(dialogFrameOuterKey,dialogFramePadding.outer);
|
||||
savePreference(dialogFrameInnerKey,dialogFramePadding.inner);
|
||||
savePreference(dialogRowTextKey,dialogFramePadding.rowText);
|
||||
if(value!=initial) savePreference(name,value);
|
||||
};
|
||||
const auto checked=[&](int id){return IsDlgButtonChecked(dialog,id)==BST_CHECKED;};
|
||||
const auto inputKeys=optionHistoryKeys(dialog);
|
||||
saveChanged(L"PreviousCommandKey",inputKeys[0],base.keys[0]);
|
||||
saveChanged(L"CommandHistoryKey",inputKeys[1],base.keys[1]);
|
||||
saveChanged(L"SizeWidth",width,base.width);
|
||||
saveChanged(L"AlignExtensions",checked(202),base.extensions);
|
||||
saveChanged(L"AlignFolders",checked(204),base.folders);
|
||||
saveChanged(L"ShowDetails",checked(203),base.details);
|
||||
DWORD fields=preference(L"StatusFields",defaultStatusFields)&15;
|
||||
const auto initialFields=fields;
|
||||
for(int i=0;i<4;++i)
|
||||
{
|
||||
const DWORD bit=1u<<i;
|
||||
if(checked(205+i)!=((base.fields&bit)!=0)) fields=checked(205+i)?fields|bit:fields&~bit;
|
||||
}
|
||||
saveChanged(L"StatusFields",fields,initialFields);
|
||||
for(int i=0;i<ColorCount;++i)
|
||||
saveChanged(std::to_wstring(i).c_str(),draft->palette[i],base.palette[i]);
|
||||
saveChanged(dialogFrameOuterKey,draft->framePadding.outer,base.padding.outer);
|
||||
saveChanged(dialogFrameInnerKey,draft->framePadding.inner,base.padding.inner);
|
||||
saveChanged(dialogRowTextKey,draft->framePadding.rowText,base.padding.rowText);
|
||||
if(fontChanged)
|
||||
{
|
||||
savePreference(L"FontPoints",fontPoints);
|
||||
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,L"DisplayFont",REG_BINARY,&displayFont,sizeof(displayFont));
|
||||
draft->font=displayFont;
|
||||
}
|
||||
for(int i=0;i<2;++i)
|
||||
{
|
||||
const bool wide=IsDlgButtonChecked(dialog,273+i)==BST_CHECKED;
|
||||
if(panels[i].wide!=wide) setMode(i,wide);
|
||||
}
|
||||
saveChanged(L"LeftWide",checked(273),base.wide[0]);
|
||||
saveChanged(L"RightWide",checked(274),base.wide[1]);
|
||||
loadFilesPreferences(owner);
|
||||
notifyFilesPreferences(owner);
|
||||
draft->baseline=OptionsBaseline{};
|
||||
draft->font=displayFont;
|
||||
draft->points=fontPoints;
|
||||
draft->styles=fileStyles;
|
||||
draft->palette=colors;
|
||||
draft->framePadding=dialogFramePadding;
|
||||
SetDlgItemInt(dialog,201,sizeWidth,FALSE);
|
||||
CheckDlgButton(dialog,202,alignExtensions);
|
||||
CheckDlgButton(dialog,203,showDetails);
|
||||
CheckDlgButton(dialog,204,alignFolders);
|
||||
CheckDlgButton(dialog,273,panels[0].wide);
|
||||
CheckDlgButton(dialog,274,panels[1].wide);
|
||||
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
|
||||
setOptionHistoryKeys(dialog,commandHistoryKeys);
|
||||
if(draft->page==PanelColors && draft->section==fileStyleSection)
|
||||
updateFileStyleEditor(dialog,*draft,true);
|
||||
showOptionsPage(dialog,*draft,draft->page,draft->section);
|
||||
layout(owner);
|
||||
showFileDetails(panels[active]);
|
||||
RedrawWindow(owner,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN|RDW_UPDATENOW);
|
||||
if(LOWORD(wp)==IDOK) EndDialog(dialog,IDOK);
|
||||
if(LOWORD(wp)==IDOK) finishFilesDialog(dialog,IDOK);
|
||||
else updateOptionsApply(dialog,*draft);
|
||||
return TRUE;
|
||||
}
|
||||
@@ -580,7 +653,7 @@ void editOptions(HWND owner)
|
||||
const auto panel=panels[active].list;
|
||||
OptionsDraft draft;
|
||||
std::copy(std::begin(colors),std::end(colors),draft.palette.begin());
|
||||
const auto result=DialogBoxParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(101),owner,optionsDialog,
|
||||
const auto result=runFilesDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(101),owner,optionsDialog,
|
||||
reinterpret_cast<LPARAM>(&draft));
|
||||
SetFocus(panel);
|
||||
if(result==-1) setStatus(L"Could not open Files Options.");
|
||||
|
||||
@@ -15,7 +15,7 @@ struct FileStyle
|
||||
|
||||
const std::vector<FileStyle> defaultFileStyles{
|
||||
{L"@system-hidden"},{L".exe",RGB(85,255,85)},{L".md",RGB(231,192,247)},
|
||||
{L".7z",RGB(255,210,128)},{L".zip",RGB(255,210,128)},{L".rar",RGB(255,210,128)},
|
||||
{L".7z",RGB(255,210,128)},{L".zip",RGB(255,155,170)},{L".rar",RGB(255,210,128)},
|
||||
{L".tar",RGB(255,210,128)},{L".gz",RGB(255,210,128)},
|
||||
{L".png",RGB(165,230,255)},{L".jpg",RGB(165,230,255)},{L".jpeg",RGB(165,230,255)},
|
||||
{L".gif",RGB(165,230,255)},{L".webp",RGB(165,230,255)},{L".svg",RGB(165,230,255)},
|
||||
|
||||
@@ -49,7 +49,7 @@ public:
|
||||
startup.StartupInfo.cb=sizeof(startup);
|
||||
startup.lpAttributeList=attributes;
|
||||
PROCESS_INFORMATION info{};
|
||||
wchar_t command[]=L"powershell.exe -NoLogo -NoProfile -NoExit -Command \"Remove-Module PSReadLine -ErrorAction SilentlyContinue; function global:prompt { ([string][char]27) + '[?25l' }; Clear-Host\"";
|
||||
wchar_t command[]=L"powershell.exe -NoLogo -NoProfile -NoExit -Command \"Remove-Module PSReadLine -ErrorAction SilentlyContinue; function global:prompt { $location = Get-Location; $path = if ($location.Provider.Name -eq 'FileSystem') { [Uri]::EscapeDataString($location.ProviderPath) }; ([string][char]27) + ']633;ks-directory:' + $path + [char]7 + [char]27 + '[?25l' }; Clear-Host\"";
|
||||
wchar_t system[MAX_PATH]{};
|
||||
const auto length=GetSystemDirectoryW(system,MAX_PATH);
|
||||
const auto shell=std::wstring(system)+L"\\WindowsPowerShell\\v1.0\\powershell.exe";
|
||||
|
||||
@@ -56,7 +56,10 @@ class FilesTerminalView
|
||||
int viewportHeight{};
|
||||
public:
|
||||
bool initialized() const { return ready; }
|
||||
void enableTrace() { if(ready) web->PostWebMessageAsString(L"trace:on"); }
|
||||
void enableTrace(bool output)
|
||||
{
|
||||
if(ready) web->PostWebMessageAsString(output?L"trace:output":L"trace:on");
|
||||
}
|
||||
void setFont(const LOGFONTW &font,int points)
|
||||
{
|
||||
if(!ready) return;
|
||||
|
||||
+7
-1
@@ -737,6 +737,7 @@ namespace
|
||||
{
|
||||
std::recursive_mutex logGate;
|
||||
bool loggingEnabled = false;
|
||||
std::wstring logFilename = L"kswitcher.log";
|
||||
DiagnosticBuffer diagnosticBuffer;
|
||||
}
|
||||
size_t DiagnosticBuffer::expire(ULONGLONG now)
|
||||
@@ -832,6 +833,11 @@ void diagnosticOperation(const std::string &json)
|
||||
record["context"] = utf8(diagnosticBuffer.record(L"Operation complete", true, GetTickCount64()));
|
||||
log(L"Operation " + wide(record.dump(-1, ' ', true, nlohmann::json::error_handler_t::replace)));
|
||||
}
|
||||
void setLogFilename(std::wstring filename)
|
||||
{
|
||||
std::lock_guard lock(logGate);
|
||||
logFilename = std::move(filename);
|
||||
}
|
||||
void log(const std::wstring &message)
|
||||
{
|
||||
std::lock_guard lock(logGate);
|
||||
@@ -839,7 +845,7 @@ void log(const std::wstring &message)
|
||||
return;
|
||||
try
|
||||
{
|
||||
auto path = dataDirectory() / L"kswitcher.log";
|
||||
auto path = dataDirectory() / logFilename;
|
||||
std::error_code ec;
|
||||
auto size = std::filesystem::file_size(path, ec);
|
||||
if (!ec && size > 256 * 1024)
|
||||
|
||||
@@ -94,6 +94,7 @@ class DiagnosticBuffer
|
||||
void clear() { entries.clear(); }
|
||||
};
|
||||
void setLoggingEnabled(bool enabled);
|
||||
void setLogFilename(std::wstring filename);
|
||||
void expireDiagnostics(ULONGLONG now);
|
||||
void diagnosticEvent(const std::wstring &message, bool problem = false);
|
||||
void diagnosticOperation(const std::string &json);
|
||||
|
||||
+3
-1
@@ -1514,7 +1514,9 @@ Settings collectSettings(HWND w, SettingsView *v)
|
||||
s.undo = value(w, 213);
|
||||
s.clipboard = value(w, 214);
|
||||
s.screenshot = value(w, 215);
|
||||
s.filesHotkey = value(w, 216);
|
||||
auto filesHotkey = value(w, 216);
|
||||
if (s.filesHotkey || !filesHotkey.empty())
|
||||
s.filesHotkey = std::move(filesHotkey);
|
||||
s.maxItems = integer(w, 240);
|
||||
s.maxMiB = integer(w, 241);
|
||||
s.maxImageMiB = integer(w, 242);
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
#include "platform.h"
|
||||
namespace ks
|
||||
{
|
||||
inline constexpr wchar_t AppVersion[] = L"0.6.77";
|
||||
inline constexpr wchar_t AppVersion[] = L"0.6.82";
|
||||
inline constexpr UINT UpdateMessage = WM_APP + 7;
|
||||
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
|
||||
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
|
||||
|
||||
@@ -292,11 +292,16 @@ int main()
|
||||
HWND picker = GetDlgItem(dialog, 728);
|
||||
RECT dialogBounds{};
|
||||
GetWindowRect(dialog, &dialogBounds);
|
||||
MONITORINFO monitor{sizeof(monitor)};
|
||||
require(GetMonitorInfoW(MonitorFromWindow(dialog, MONITOR_DEFAULTTONEAREST), &monitor),
|
||||
"monitor work area available");
|
||||
const auto targetX = std::clamp(dialogBounds.left + 32, monitor.rcWork.left, monitor.rcWork.right - 120);
|
||||
const auto targetY = std::clamp(dialogBounds.top + 100, monitor.rcWork.top, monitor.rcWork.bottom - 48);
|
||||
HWND target = CreateWindowExW(WS_EX_TOPMOST | WS_EX_NOACTIVATE, L"EDIT", L"Picker fixture",
|
||||
WS_POPUP | WS_VISIBLE, dialogBounds.left + 32, dialogBounds.top + 100, 120, 48,
|
||||
WS_POPUP | WS_VISIBLE, targetX, targetY, 120, 48,
|
||||
nullptr, nullptr, GetModuleHandleW(nullptr), nullptr);
|
||||
require(picker && target, "window picker and target available");
|
||||
POINT drop{dialogBounds.left + 33, dialogBounds.top + 101};
|
||||
POINT drop{targetX + 1, targetY + 1};
|
||||
require(GetAncestor(WindowFromPoint(drop), GA_ROOT) == target, "fixture window is under the drop point");
|
||||
ScreenToClient(picker, &drop);
|
||||
SendMessageW(picker, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(8, 8));
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$Executable,
|
||||
[Parameter(Mandatory)][string]$Fixture
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type @"
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
public static class FilesActivationUi {
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Rect { public int Left, Top, Right, Bottom; }
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct GuiInfo {
|
||||
public int Size, Flags;
|
||||
public IntPtr Active, Focus, Capture, MenuOwner, MoveSize, Caret;
|
||||
public Rect CaretRect;
|
||||
}
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string type, string title);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr window, uint msg, IntPtr w, IntPtr l);
|
||||
[DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr window, IntPtr process);
|
||||
[DllImport("user32.dll")] static extern bool GetGUIThreadInfo(uint thread, ref GuiInfo info);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, uint msg, IntPtr w, IntPtr l);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW")] static extern IntPtr SendRect(IntPtr window, uint msg, IntPtr w, out Rect rect);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr Read(IntPtr window, uint msg, IntPtr w, StringBuilder text);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr Write(IntPtr window, uint msg, IntPtr w, string text);
|
||||
[DllImport("shell32.dll")] public static extern void SHChangeNotify(int eventId, uint flags, IntPtr first, IntPtr second);
|
||||
|
||||
public static IntPtr Focus(IntPtr window) {
|
||||
var info = new GuiInfo { Size = Marshal.SizeOf(typeof(GuiInfo)) };
|
||||
if (!GetGUIThreadInfo(GetWindowThreadProcessId(window, IntPtr.Zero), ref info))
|
||||
throw new InvalidOperationException("Could not read Files focus.");
|
||||
return info.Focus;
|
||||
}
|
||||
|
||||
public static void ClickRow(IntPtr list, int row, bool doubleClick) {
|
||||
Rect rect;
|
||||
if (SendRect(list, 0x198, new IntPtr(row), out rect).ToInt32() == -1)
|
||||
throw new InvalidOperationException("Missing listbox row.");
|
||||
var point = new IntPtr(((rect.Top + rect.Bottom) / 2 << 16) | (rect.Left + 6));
|
||||
PostMessage(list, 0x201, new IntPtr(1), point);
|
||||
PostMessage(list, 0x202, IntPtr.Zero, point);
|
||||
if (doubleClick) {
|
||||
PostMessage(list, 0x203, new IntPtr(1), point);
|
||||
PostMessage(list, 0x202, IntPtr.Zero, point);
|
||||
}
|
||||
}
|
||||
}
|
||||
"@
|
||||
|
||||
function Wait-Until([string]$Description, [scriptblock]$Condition) {
|
||||
$timer = [Diagnostics.Stopwatch]::StartNew()
|
||||
while ($timer.Elapsed.TotalSeconds -lt 15) {
|
||||
if (& $Condition) { return }
|
||||
if ($process -and $process.HasExited) { throw "Files exited while waiting for $Description" }
|
||||
Start-Sleep -Milliseconds 50
|
||||
}
|
||||
throw "Timed out waiting for $Description"
|
||||
}
|
||||
|
||||
function Read-Text($Control, $Message = 0x0D, $Parameter = 32768) {
|
||||
$buffer = [Text.StringBuilder]::new(32768)
|
||||
[void][FilesActivationUi]::Read($Control, $Message, [IntPtr]$Parameter, $buffer)
|
||||
$buffer.ToString()
|
||||
}
|
||||
|
||||
function Find-Row($List, [string]$Name) {
|
||||
$count = [FilesActivationUi]::Send($List, 0x18B, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32()
|
||||
for ($row = 0; $row -lt $count; $row++) {
|
||||
if ((Read-Text $List 0x189 $row) -ceq $Name) { return $row }
|
||||
}
|
||||
-1
|
||||
}
|
||||
|
||||
function Select-Row($List, [string]$Name, [switch]$DoubleClick) {
|
||||
Wait-Until "row $Name" { (Find-Row $List $Name) -ge 0 }
|
||||
$row = Find-Row $List $Name
|
||||
[void][FilesActivationUi]::Send($List, 0x197, [IntPtr]$row, [IntPtr]::Zero)
|
||||
[FilesActivationUi]::ClickRow($List, $row, $DoubleClick.IsPresent)
|
||||
if (!$DoubleClick) {
|
||||
Wait-Until "selection of $Name" {
|
||||
[FilesActivationUi]::Focus($window) -eq $List -and
|
||||
[FilesActivationUi]::Send($List, 0x188, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq (Find-Row $List $Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Press-Enter($Control) {
|
||||
[void][FilesActivationUi]::PostMessage($Control, 0x100, [IntPtr]13, [IntPtr]::Zero)
|
||||
}
|
||||
|
||||
function Invoke-Row($List, [string]$Name, [bool]$DoubleClick) {
|
||||
Select-Row $List $Name -DoubleClick:$DoubleClick
|
||||
if (!$DoubleClick) { Press-Enter $List }
|
||||
}
|
||||
|
||||
function Send-Terminal([string]$Command) {
|
||||
[void][FilesActivationUi]::Write($inputBox, 0x0C, [IntPtr]::Zero, $Command)
|
||||
Press-Enter $inputBox
|
||||
}
|
||||
|
||||
function Assert-Open($List, $Target, [bool]$DoubleClick) {
|
||||
$report = "$Target.opened"
|
||||
Remove-Item -LiteralPath $report -ErrorAction SilentlyContinue
|
||||
Invoke-Row $List ([IO.Path]::GetFileName($Target)) $DoubleClick
|
||||
Wait-Until "launch of $Target (double click: $DoubleClick)" {
|
||||
(Test-Path -LiteralPath $report) -and [IO.File]::ReadAllText($report) -eq 'opened'
|
||||
}
|
||||
}
|
||||
|
||||
$unique = [Guid]::NewGuid().ToString('N')
|
||||
$root = Join-Path ([IO.Path]::GetTempPath()) "KSwitcher test $unique"
|
||||
$profile = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
|
||||
$classes = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\Classes')
|
||||
$extension = ".ksfiles$unique"
|
||||
$progId = "KSwitcher.Files.Test.$unique"
|
||||
$saved = @{}
|
||||
$profileValues = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'LeftWide', 'RightWide',
|
||||
'ShowDetails', 'StatusFields', 'CommandHistory', 'WindowPlacement'
|
||||
$process = $null
|
||||
$trace = $null
|
||||
try {
|
||||
foreach ($name in $profileValues) {
|
||||
if ($name -in $profile.GetValueNames()) {
|
||||
$saved[$name] = @($profile.GetValue($name), $profile.GetValueKind($name))
|
||||
}
|
||||
}
|
||||
$leftDir = Join-Path $root 'Left panel'
|
||||
$rightDir = Join-Path $root 'Right panel'
|
||||
$app = Join-Path $root 'Application'
|
||||
New-Item -ItemType Directory -Path $leftDir, $rightDir, $app, "$leftDir\Test folder", "$rightDir\Test folder" | Out-Null
|
||||
$source = Split-Path (Resolve-Path -LiteralPath $Executable)
|
||||
$testExe = Join-Path $app 'KSwitcher.Files.exe'
|
||||
Copy-Item -LiteralPath $Executable -Destination $testExe
|
||||
Copy-Item -LiteralPath "$source\WebView2Loader.dll", "$source\terminal" -Destination $app -Recurse
|
||||
$program = Join-Path $leftDir 'Test program.exe'
|
||||
Copy-Item -LiteralPath $Fixture -Destination $program
|
||||
$document = Join-Path $rightDir "Test document$extension"
|
||||
[IO.File]::WriteAllText($document, 'Document fixture')
|
||||
$association = $classes.CreateSubKey($extension)
|
||||
$association.SetValue('', $progId)
|
||||
$association.Dispose()
|
||||
$handler = $classes.CreateSubKey("$progId\shell\open\command")
|
||||
$handler.SetValue('', ('"{0}" "%1"' -f (Resolve-Path -LiteralPath $Fixture).Path))
|
||||
$handler.Dispose()
|
||||
[FilesActivationUi]::SHChangeNotify(0x08000000, 0, [IntPtr]::Zero, [IntPtr]::Zero)
|
||||
|
||||
$batch = Join-Path $leftDir "Test's script.BAT"
|
||||
$cmd = Join-Path $rightDir 'Test script.CMD'
|
||||
[IO.File]::WriteAllLines($batch, @('@echo off', 'echo BAT=%KS_TEST_STATE%'))
|
||||
[IO.File]::WriteAllLines($cmd, @('@echo off', 'echo CMD=%KS_TEST_STATE%'))
|
||||
$profile.SetValue('LeftPath', $leftDir)
|
||||
$profile.SetValue('RightPath', $rightDir)
|
||||
foreach ($name in 'LeftCursor', 'RightCursor') { $profile.DeleteValue($name, $false) }
|
||||
foreach ($name in 'LeftWide', 'RightWide', 'ShowDetails') { $profile.SetValue($name, 1) }
|
||||
$profile.SetValue('StatusFields', 3)
|
||||
|
||||
$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 }
|
||||
$window = $process.MainWindowHandle
|
||||
$left = [FilesActivationUi]::GetDlgItem($window, 102)
|
||||
$right = [FilesActivationUi]::GetDlgItem($window, 103)
|
||||
$status = [FilesActivationUi]::GetDlgItem($window, 144)
|
||||
$output = [FilesActivationUi]::GetDlgItem($window, 145)
|
||||
$inputBox = [FilesActivationUi]::FindWindowEx($window, [IntPtr]::Zero, 'Edit', $null)
|
||||
|
||||
foreach ($double in $false, $true) {
|
||||
Assert-Open $left $program $double
|
||||
Assert-Open $right $document $double
|
||||
}
|
||||
Invoke-Row $left '[Test folder]' $false
|
||||
Wait-Until 'folder navigation by Enter' {
|
||||
(Read-Text ([FilesActivationUi]::GetDlgItem($window, 142))) -eq "$leftDir\Test folder"
|
||||
}
|
||||
Invoke-Row $left '..' $false
|
||||
Invoke-Row $right '[Test folder]' $true
|
||||
Wait-Until 'folder navigation by double click' {
|
||||
(Read-Text ([FilesActivationUi]::GetDlgItem($window, 143))) -eq "$rightDir\Test folder"
|
||||
}
|
||||
Invoke-Row $right '..' $false
|
||||
Write-Output 'Enter and double-click opened folders, the registered document, and the standalone EXE.'
|
||||
|
||||
$sessionValue = $unique.Substring(0, 8)
|
||||
Send-Terminal ('$global:ksSession = "{0}"; $env:KS_TEST_STATE = $ksSession; "READY=" + $ksSession' -f $sessionValue)
|
||||
Wait-Until 'initialized terminal session and rendered test marker' {
|
||||
(Get-Content -LiteralPath $trace -ErrorAction SilentlyContinue) -contains "READY=$sessionValue"
|
||||
}
|
||||
Invoke-Row $left ([IO.Path]::GetFileName($batch)) $false
|
||||
Wait-Until 'visible BAT output with the existing session environment' {
|
||||
[FilesActivationUi]::IsWindowVisible($output) -and
|
||||
(Get-Content -LiteralPath $trace) -contains "BAT=$sessionValue"
|
||||
}
|
||||
Invoke-Row $right ([IO.Path]::GetFileName($cmd)) $true
|
||||
Wait-Until 'visible CMD output with the existing session environment' {
|
||||
[FilesActivationUi]::IsWindowVisible($output) -and
|
||||
(Get-Content -LiteralPath $trace) -contains "CMD=$sessionValue"
|
||||
}
|
||||
Send-Terminal '"AFTER=" + $global:ksSession'
|
||||
Wait-Until 'unchanged PowerShell session state' {
|
||||
(Get-Content -LiteralPath $trace) -contains "AFTER=$sessionValue"
|
||||
}
|
||||
Assert-Open $left $program $false
|
||||
Write-Output 'BAT and CMD ran in the existing terminal and rendered their output.'
|
||||
|
||||
$external = 'External change.txt'
|
||||
Select-Row $left ([IO.Path]::GetFileName($program))
|
||||
foreach ($dir in $leftDir, $rightDir) { [IO.File]::WriteAllText((Join-Path $dir $external), 'one') }
|
||||
Wait-Until 'external creation in both panels' {
|
||||
(Find-Row $left $external) -ge 0 -and (Find-Row $right $external) -ge 0
|
||||
}
|
||||
if ([FilesActivationUi]::Focus($window) -ne $left -or
|
||||
[FilesActivationUi]::Send($left, 0x188, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -ne
|
||||
(Find-Row $left ([IO.Path]::GetFileName($program)))) { throw 'Creation moved focus or selection.' }
|
||||
|
||||
foreach ($panel in @(@{ List = $left; Dir = $leftDir }, @{ List = $right; Dir = $rightDir })) {
|
||||
Select-Row $panel.List $external
|
||||
Wait-Until 'initial file size' { (Read-Text $status) -match ' 3 B$' }
|
||||
[IO.File]::AppendAllText((Join-Path $panel.Dir $external), 'two!')
|
||||
Wait-Until 'updated file size' { (Read-Text $status) -match ' 7 B$' }
|
||||
if ([FilesActivationUi]::Focus($window) -ne $panel.List) { throw 'Modification moved focus.' }
|
||||
}
|
||||
|
||||
foreach ($dir in $leftDir, $rightDir) { [IO.File]::Delete((Join-Path $dir $external)) }
|
||||
Wait-Until 'external deletion in both panels' {
|
||||
(Find-Row $left $external) -eq -1 -and (Find-Row $right $external) -eq -1
|
||||
}
|
||||
if ([FilesActivationUi]::Focus($window) -ne $right) { throw 'Deletion moved focus.' }
|
||||
Write-Output 'Both panels refreshed external creation, modification and deletion while preserving focus.'
|
||||
} finally {
|
||||
if ($process -and !$process.HasExited) {
|
||||
[void]$process.CloseMainWindow()
|
||||
if (!$process.WaitForExit(4000)) { $process.Kill(); $process.WaitForExit() }
|
||||
}
|
||||
foreach ($name in $profileValues) {
|
||||
if ($saved.ContainsKey($name)) { $profile.SetValue($name, $saved[$name][0], $saved[$name][1]) }
|
||||
else { $profile.DeleteValue($name, $false) }
|
||||
}
|
||||
$profile.Dispose()
|
||||
$classes.DeleteSubKeyTree($extension, $false)
|
||||
$classes.DeleteSubKeyTree($progId, $false)
|
||||
$classes.Dispose()
|
||||
[FilesActivationUi]::SHChangeNotify(0x08000000, 0, [IntPtr]::Zero, [IntPtr]::Zero)
|
||||
if ($trace) { Remove-Item -LiteralPath $trace -ErrorAction SilentlyContinue }
|
||||
$resolvedRoot = Resolve-Path -LiteralPath $root -ErrorAction SilentlyContinue
|
||||
$tempPrefix = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd('\') + '\'
|
||||
if ($resolvedRoot -and $resolvedRoot.Path.StartsWith($tempPrefix, [StringComparison]::OrdinalIgnoreCase)) {
|
||||
Remove-Item -LiteralPath $resolvedRoot.Path -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
#include <windows.h>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
|
||||
int wmain(int argc,wchar_t **argv)
|
||||
{
|
||||
// A launch through the embedded terminal would inherit its console.
|
||||
DWORD consoleProcesses[1]{};
|
||||
if(GetConsoleProcessList(consoleProcesses,1)>1) return 1;
|
||||
wchar_t executable[32768]{};
|
||||
const auto length=GetModuleFileNameW(nullptr,executable,static_cast<DWORD>(std::size(executable)));
|
||||
if(!length || length>=std::size(executable)) return 1;
|
||||
const std::filesystem::path target=argc==2?argv[1]:executable;
|
||||
auto report=target;
|
||||
report+=L".opened";
|
||||
std::ofstream result(report,std::ios::binary);
|
||||
result<<"opened";
|
||||
return result?0:1;
|
||||
}
|
||||
Reference in new issue
Block a user