Compare commits

..
Author SHA1 Message Date
agrynco 7242c3f775 test(settings): keep picker fixture within the monitor 2026-11-14 15:17:54 +02:00
agrynco a43f6441b4 chore(release): refresh verified windows package 2026-11-14 15:15:20 +02:00
agrynco 2f5ae373a1 fix(settings): preserve unset files shortcut in options 2026-11-14 15:14:16 +02:00
agrynco b978361180 chore(release): package kswitcher v0.6.78 with files 2026-11-14 15:11:26 +02:00
agrynco 93b8055085 fix(files): synchronize settings across windows
Reload shared preferences in open windows and apply only fields changed in Options.
2026-11-14 15:09:17 +02:00
agrynco 70ee338fc3 Merge pull request 'Add searchable command history to KSwitcher Files' (#19) from codex/files-command-history into main 2026-11-14 14:43:10 +02:00
agrynco 46b4b51cea feat(files): add searchable command history
Persist command recall and align keyboard, mouse, and dialog behavior.

Refs #18
2026-11-14 14:42:48 +02:00
agrynco 721c3f0f38 docs: record KSwitcher issue workflow 2026-11-14 12:56:47 +02:00
agrynco 47851d75ef Merge pull request 'Add folder shortcuts to KSwitcher Files' (#17) from codex/issue-15-folder-shortcuts into main
Fixes #15
2026-11-14 12:20:53 +02:00
agrynco ad01951956 Add folder shortcuts to KSwitcher Files
Share Far dialog fields, palette, frame layout, and configurable padding. Document shortcut behavior and the shared-code rule.

Refs #15
2026-11-14 12:19:13 +02:00
agrynco bf092d2764 Merge pull request 'Customize file type styles and preview Files options' (#16) from codex/files-type-styles into main
Fixes #14
2026-11-14 11:26:01 +02:00
20 changed files with 1935 additions and 257 deletions

No files matched your search

+29
View File
@@ -1,5 +1,11 @@
# Project instructions
## Reuse shared code
Reuse existing shared code wherever possible. When the same behavior,
component, or logic is needed in two or more places, extract it into a
shared component or function and use it at every applicable call site.
## Mandatory Wiki updates for every release
A release is not complete until the published project Wiki reflects that release.
@@ -34,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.
+1 -1
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.6.77 LANGUAGES CXX RC)
project(KSwitcher VERSION 0.6.78 LANGUAGES CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
+61 -3
View File
@@ -4,10 +4,50 @@ Far Manager є зразком для оформлення файлового м
## Скорочення
- У командному рядку 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.
- 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.
## Налаштування Files
- Options у головному меню одразу відкриває стандартний діалог Windows. Ліворуч є пошук за назвою категорії чи параметра й дерево результатів. Вибір дочірнього вузла відкриває лише його редактор праворуч. Пошук за назвою окремої властивості відкриває вузол, що її містить. Перемикання вузлів зберігає незастосовані зміни.
@@ -25,6 +65,12 @@ Far Manager є зразком для оформлення файлового м
## Панелі
- Застосовані налаштування Files одразу підхоплюють інші відкриті вікна.
Apply зберігає поля, змінені в поточній чернетці. Якщо два вікна одночасно
редагували набір стилів файлів, відкрий Options заново, щоб побачити свіжі правила.
- Типовий колір тексту для ZIP-архівів — світлий коралово-рожевий.
- Меню Change drive показує літеру, тип, загальний обсяг і вільне місце. Відкриття меню запускає нове LAN-виявлення. Секція KSwitcher LAN показує збережені пари, зокрема офлайн. Після кожного відкриття меню асинхронно запитує диски й показує їх під назвою відповідного ПК. Поки триває запит, видно стан завантаження. Якщо запит не вдався, видно помилку. Повторне відкриття запускає новий запит. Кожна панель має власний диск і шлях, а в заголовку віддаленої панелі перед шляхом показано назву ПК.
- Список дисків і файлові операції використовують права облікового запису Windows, під яким працює віддалений KSwitcher. Достатньо спарювання й доступного TCP 45885, спільні папки налаштовувати не потрібно.
@@ -35,19 +81,28 @@ Far Manager є зразком для оформлення файлового м
- У широкому режимі ширина під вирівняні розширення залежить від найдовшого розширення в поточній панелі. За вузької панелі залишай місце для імені та колонки Size.
- Бірюзовий курсор поточного рядка видно лише в активній панелі. Кожна панель зберігає свою позицію курсора.
- Бірюзовий курсор поточного рядка видно лише в активній панелі, зокрема коли клавіатурний фокус переходить у командний рядок. Кожна панель зберігає свою позицію курсора. Коли панелі видимі, F5 і F6 з командного рядка діють на активну панель.
- Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший.
- Поточний шлях відображається по центру верхньої подвійної лінії панелі. Лінію видно з обох боків напису. Бірюзове тло активної панелі охоплює лише напис шляху з невеликими відступами. Довгий шлях скорочується в межах панелі.
## Спільні елементи діалогів
- Власні діалоги Files блокують дії панелей і командного рядка, залишаючи
системний заголовок і рамку головного вікна доступними. Клік поза діалогом
діє як Cancel. Для прогресу копіювання, переміщення й видалення це відкриває
підтвердження скасування.
- Enter активує кнопку у фокусі. Для кнопок із власним малюванням використовуй спільний обробник `dialogButtonEnter`. У підтвердженні скасування початковий фокус стоїть на No.
- При перенесенні вікна між моніторами з різним DPI оновлюй шрифт, висоту рядків панелей і компонування відкритого прогресу копіювання. Перевір перенесення під час активного копіювання.
- Для власних діалогів використовуй подвійну рамку з одним заголовком у верхній лінії. Звичайний діалог має сіре тло, попередження — темно-червоне тло та білий текст.
- Для власних діалогів і списків Far використовуй спільні метрики та малювання подвійної рамки. Еталон Delete задає 8 px від краю тла до першої лінії та 14 px від внутрішньої лінії до бічної межі вмісту при 96 DPI. Обидва відступи масштабуються за DPI. Вертикальний відступ враховує висоту заголовка та нижніх підказок. Діалоги й списки зберігають свою палітру та поведінку.
- Appearance → Dialog frame налаштовує зовнішній і внутрішній відступи від 0 до 24 px при 96 DPI. Row text padding додає від 0 до 4 ширин символу з кожного боку тексту в рядках Folder shortcuts. Inner padding задає відстань від рамки до краю списку. Ширина попапа враховує обидва текстові відступи, а довгі шляхи скорочуються в межах доступної ширини. Живий зразок показує чернетку. Apply зберігає значення, Cancel відкидає незастосовані зміни, Reset selected to defaults повертає 8 px, 14 px і 0 символів. Профілі без цих параметрів використовують ті самі значення.
- У ресурсі чи виклику задавай назву кнопки й клавішу доступу. Спільна функція `paintDialogButton` центрує текст, підсвічує фокус і додає фігурні дужки для дії за замовчуванням та квадратні для решти кнопок.
- Нижні секції з кнопками у Copy, Warning і вікні прогресу мають однакову висоту, прив’язану до висоти рядка шрифту. Використовуй `layoutDialogButtons` для такої секції та `centerDialogRow` для інших рядків між роздільниками. Межі секції визначають положення рядка.
- Поля вводу й випадаючі списки використовують бірюзове тло палітри менеджера. Текст і стрілку вирівнюй вертикально по центру. Прапорці в діалогах операцій використовують позначки `[ ]` та `[x]` і видимий клавіатурний фокус.
- Для текстових полів Far використовуй ресурс `FAR_EDIT` і спільну підготовку та палітру діалогів. Поля призначення Copy/Rename і Title/Path використовують нативний Win32 Edit без рамки, моноширинний шрифт і вертикальне центрування. Кольори Text і Popup background діють на всі ці поля, зокрема на поле Copy лише для читання. У відповідних розділах Options → Colors зміни видно на зразку поля. Existing files у Copy є списком без редагування. Поля та редагований список Windows Options мають системне оформлення.
- Для позиціонування роздільника використовуй невидимий маркер, якщо межу не задає інший елемент секції. Спільний обробник малює лінію.
- Випадаючі списки Far використовують бірюзове тло палітри менеджера. Текст і стрілку вирівнюй вертикально по центру. Прапорці в діалогах операцій використовують позначки `[ ]` та `[x]` і видимий клавіатурний фокус.
- Повторно використовуй спільне оформлення. Текст, дії та стан операції передавай із коду конкретної операції. Наприклад, Warning повертає відповідь і стан прапорця, а копіювання вирішує, чи застосувати відповідь до наступних конфліктів.
## Діалог Copy
@@ -67,6 +122,9 @@ Far Manager є зразком для оформлення файлового м
## Попередження про конфлікт
- Для однойменних файлів Warning показує точний розмір у байтах із розділенням тисяч і місцевий
час останньої зміни окремо для вхідного файла та файла в папці призначення.
- Після розрахунку остаточної висоти центр Warning збігається з центром вікна прогресу.
- Remember choice стоїть по вертикальному центру власної секції. Кнопки Overwrite, Skip і Cancel стоять по центру нижньої секції.
- Tab проходить Remember choice, Overwrite, Skip і Cancel. Стрілки вліво та вправо циклічно перемикають три кнопки в порядку їх розташування.
Binary file not shown.
+12
View File
@@ -1,5 +1,17 @@
# Latest Windows release
## 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
View File
@@ -1 +1 @@
51d95639527590b36453a5ef485532a7d2135950222fa197eb431a5309f1a45c KSwitcher-win-x64.zip
d7362104941853bb30646fa44175686ed3d2fd3abcf1fd83daee04dd1d5c6912 KSwitcher-win-x64.zip
+79 -34
View File
@@ -1,86 +1,131 @@
{
"version": "0.6.77",
"schema": 1,
"files": [
{
"path": "KSwitcher.exe",
"size": 2249216,
"sha256": "f1c79d337d746efcda03946cc833b7b5588ef4e739f1dff7d3afa15d0465469f"
"sha256": "1e67e8e15eada80c902764f14a12a0bd370080709a94d454cc3c565dd3de1136",
"size": 2340864
},
{
"path": "KSwitcher.Config.exe",
"size": 2251776,
"sha256": "016edc389007e0d15ee365fff7115fc91a820b46080cb39a3fb362f3b463bae7"
"sha256": "26e9f5db4b6f79408e30fb2650f1a8318b5c17e39ae2bccf614901b815ca6606",
"size": 2341376
},
{
"path": "KSwitcher.Screenshot.exe",
"size": 3247616,
"sha256": "c8ef070ad01acc410802c62e0df6a96cb299fe036fe8e99f0cf6a398b7324ec6"
"sha256": "d9593c6ff103070f1f72b93c0f350ba4782d9df814090565f48bd0aa34125059",
"size": 3319296
},
{
"path": "KSwitcher.Files.exe",
"sha256": "22f897cfdc3207350e3edb63f33747d71a0f9d60c7a8d3771f642ee589ed6ce1",
"size": 1815552
},
{
"path": "WebView2Loader.dll",
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
"size": 194912
},
{
"path": "terminal/addon-fit-LICENSE.txt",
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
"size": 1103
},
{
"path": "terminal/addon-fit.js",
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
"size": 1521
},
{
"path": "terminal/index.html",
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
"size": 527
},
{
"path": "terminal/terminal.js",
"sha256": "142624d166314c4539dd14f922c17dca3d2bc7203f84aff2df03a196602c4b09",
"size": 3174
},
{
"path": "terminal/xterm-LICENSE.txt",
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
"size": 1261
},
{
"path": "terminal/xterm.css",
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
"size": 7112
},
{
"path": "terminal/xterm.js",
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
"size": 488663
},
{
"path": "LICENSE",
"size": 4401,
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
"size": 4401
},
{
"path": "json-LICENSE.txt",
"size": 1075,
"sha256": "c0d068392ea65358b798b8c165103560f06e9e3b38c4ab4e2d8810a7b931af86"
"sha256": "c0d068392ea65358b798b8c165103560f06e9e3b38c4ab4e2d8810a7b931af86",
"size": 1075
},
{
"path": "README.md",
"size": 93885,
"sha256": "df6d40d0eb66ad7da8db1cffe6bd211de70dfee474cc228e041c821b3940718b"
"sha256": "df6d40d0eb66ad7da8db1cffe6bd211de70dfee474cc228e041c821b3940718b",
"size": 93885
},
{
"path": "LAN-PREVIEW.md",
"size": 11418,
"sha256": "2c13d3ed4761e679c352fb1ade24a1ec3060ad2862376ede801cdee5fcc3bada"
"sha256": "2c13d3ed4761e679c352fb1ade24a1ec3060ad2862376ede801cdee5fcc3bada",
"size": 11418
},
{
"path": "dictionaries/en.txt",
"size": 682867,
"sha256": "5f267c141c3d6837870e1c098f86b89a113ba300343119432644ead88f720c21"
"sha256": "5f267c141c3d6837870e1c098f86b89a113ba300343119432644ead88f720c21",
"size": 682867
},
{
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"size": 20138,
"sha256": "28a9529c7d0bb4dc51f4bf5c116a3d16ef247a052f7591466768ddf563fd1cf5"
"sha256": "28a9529c7d0bb4dc51f4bf5c116a3d16ef247a052f7591466768ddf563fd1cf5",
"size": 20138
},
{
"path": "dictionaries/README.md",
"size": 2230,
"sha256": "2df17fe4e17d527c67ab57269b07dce59a49c1fb128c429a1408decbb47109ec"
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
"size": 2265
},
{
"path": "dictionaries/ru.txt",
"size": 1060364,
"sha256": "9ef922c7699569304a428f6aba0fd13a21341c0d0cb9561f37ef83c41577a28b"
"sha256": "9ef922c7699569304a428f6aba0fd13a21341c0d0cb9561f37ef83c41577a28b",
"size": 1060364
},
{
"path": "dictionaries/sources.json",
"size": 1279,
"sha256": "d6e11a3aaba22a8a7eaba19f778d8a5bd66653ff306810e85a1b0e7fff3a6b86"
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
"size": 1280
},
{
"path": "dictionaries/uk.txt",
"size": 898248,
"sha256": "caeb097749d4afc84b68ad96b3d7dfb6a6569561cd32ccce0bee94a13b43ba86"
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
"size": 940799
},
{
"path": "tools/README.txt",
"size": 993,
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
"size": 993
},
{
"path": "tools/StayHere.exe",
"size": 134656,
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376"
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376",
"size": 134656
},
{
"path": "tools/StayHere-README.md",
"size": 2796,
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
"size": 2796
}
],
"schema": 1
"version": "0.6.78"
}
+3 -3
View File
@@ -9,8 +9,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
1 RT_MANIFEST "app.manifest"
201 RCDATA "update.ps1"
1 VERSIONINFO
FILEVERSION 0,6,77,0
PRODUCTVERSION 0,6,77,0
FILEVERSION 0,6,78,0
PRODUCTVERSION 0,6,78,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.78"
END
END
BLOCK "VarFileInfo"
+62 -13
View File
@@ -1,6 +1,9 @@
#include <windows.h>
#include <commctrl.h>
#define FAR_EDIT(id, mode, x, y, width, height) \
CONTROL "", id, "Edit", ES_AUTOHSCROLL | WS_TABSTOP | mode, x, y, width, height
1 ICON "kswitcher-files.ico"
1 RT_MANIFEST "app.manifest"
@@ -30,6 +33,16 @@ BEGIN
LTEXT "", 280, 222, 50, 155, 12
LTEXT "", 281, 131, 30, 254, 14
PUSHBUTTON "Change &font…", 282, 131, 52, 82, 15
LTEXT "&Outer padding (px at 96 DPI)", 302, 131, 31, 173, 12
COMBOBOX 303, 311, 28, 56, 125, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
LTEXT "&Inner padding (px at 96 DPI)", 304, 131, 54, 173, 12
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
@@ -53,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
CONTROL "", 211, "Edit", ES_MULTILINE | ES_AUTOHSCROLL | WS_TABSTOP, 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
FAR_EDIT(211, ES_MULTILINE, 14, 29, 322, 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
@@ -83,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"
@@ -91,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
@@ -135,3 +154,33 @@ BEGIN
LTEXT "", 248, 14, 73, 1, 1
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 157, 74, 86, 18
END
109 DIALOGEX 0, 0, 250, 85
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
CAPTION "Folder shortcuts"
FONT 10, "Consolas"
BEGIN
CONTROL "", 310, "ListBox", LBS_NOTIFY | LBS_OWNERDRAWFIXED | LBS_HASSTRINGS | LBS_NOINTEGRALHEIGHT | WS_TABSTOP, 8, 14, 234, 50
END
110 DIALOGEX 0, 0, 370, 116
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Folder shortcuts"
FONT 10, "Consolas"
BEGIN
LTEXT "&Title", 316, 16, 18, 338, 12
FAR_EDIT(314, ES_LEFT, 16, 31, 338, 15)
LTEXT "&Path", 317, 16, 49, 338, 12
FAR_EDIT(211, ES_LEFT, 16, 62, 338, 15)
LTEXT "", 315, 10, 82, 1, 1, NOT WS_VISIBLE
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
+107
View File
@@ -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;
}
+365
View File
@@ -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,&current) &&
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));
}
+128
View File
@@ -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;
}
+427
View File
@@ -0,0 +1,427 @@
struct FolderShortcut
{
fs::path path;
std::string peerId;
std::wstring peerName,title;
};
using FolderShortcuts=std::array<std::vector<FolderShortcut>,10>;
FolderShortcuts folderShortcuts;
constexpr wchar_t folderShortcutsKey[]=L"FolderShortcuts";
bool sameFolderShortcut(const FolderShortcut &left,const FolderShortcut &right)
{
return left.peerId==right.peerId &&
CompareStringOrdinal(left.path.c_str(),-1,right.path.c_str(),-1,TRUE)==CSTR_EQUAL;
}
bool saveFolderShortcuts(const FolderShortcuts &shortcuts)
{
try
{
auto groups=Json::array();
for(const auto &group:shortcuts)
{
auto rows=Json::array();
for(const auto &entry:group)
rows.push_back({{"path",ks::utf8(entry.path.native())},{"peer",entry.peerId},
{"name",ks::utf8(entry.peerName)},{"title",ks::utf8(entry.title)}});
groups.push_back(std::move(rows));
}
const auto data=groups.dump();
return data.size()<=1024*1024 &&
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,REG_BINARY,data.data(),
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
}
catch(const std::exception &){return false;}
}
void loadFolderShortcuts()
{
DWORD bytes{};
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS ||
!bytes || bytes>1024*1024) return;
std::string data(bytes,'\0');
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,RRF_RT_REG_BINARY,nullptr,data.data(),&bytes)!=ERROR_SUCCESS)
return;
try
{
const auto groups=Json::parse(data.begin(),data.begin()+bytes);
if(!groups.is_array() || groups.size()!=folderShortcuts.size()) return;
FolderShortcuts loaded;
for(size_t digit=0;digit<loaded.size();++digit)
{
if(!groups[digit].is_array()) return;
for(const auto &row:groups[digit])
{
FolderShortcut entry{filePath(row.at("path")),row.at("peer"),ks::wide(row.at("name")),ks::wide(row.value("title",""))};
if(!entry.path.is_absolute() || entry.path.native().find(L'\0')!=std::wstring::npos) continue;
loaded[digit].push_back(std::move(entry));
}
}
folderShortcuts=std::move(loaded);
}
catch(const std::exception &) {}
}
constexpr int shortcutTitle=314,shortcutPath=211;
struct FolderShortcutEdit
{
FolderShortcut entry;
int digit;
std::optional<size_t> index;
};
std::wstring shortcutField(HWND dialog,int id)
{
const auto field=GetDlgItem(dialog,id);
const auto length=GetWindowTextLengthW(field);
std::wstring result(static_cast<size_t>(length)+1,L'\0');
result.resize(GetWindowTextW(field,result.data(),length+1));
return result;
}
INT_PTR CALLBACK folderShortcutEditDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" Folder shortcuts ",false,{315}))
return painted;
if(message==WM_INITDIALOG)
{
auto &edit=*reinterpret_cast<FolderShortcutEdit*>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareCopyDialog(dialog);
layoutDialogContent(dialog,316);
for(const auto id:{316,317,IDOK,IDCANCEL})
SendDlgItemMessageW(dialog,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
SendDlgItemMessageW(dialog,shortcutTitle,EM_SETLIMITTEXT,255,0);
SendDlgItemMessageW(dialog,shortcutPath,EM_SETLIMITTEXT,32767,0);
SetDlgItemTextW(dialog,shortcutTitle,edit.entry.title.c_str());
SetDlgItemTextW(dialog,shortcutPath,edit.entry.path.c_str());
if(!edit.entry.peerId.empty())
SetDlgItemTextW(dialog,317,(L"Path on "+edit.entry.peerName).c_str());
layoutDialogButtons(dialog,315,{IDOK,IDCANCEL});
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
finishFilesDialog(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
auto &edit=*reinterpret_cast<FolderShortcutEdit*>(GetWindowLongPtrW(dialog,DWLP_USER));
auto path=fs::path(shortcutField(dialog,shortcutPath)).lexically_normal();
if(path.has_relative_path() && !path.has_filename()) path=path.parent_path();
const auto root=path.root_name().native();
const bool lanDrive=root.size()==2 && root[1]==L':' &&
((root[0]>=L'A' && root[0]<=L'Z') || (root[0]>=L'a' && root[0]<=L'z'));
if(!path.is_absolute() || (!edit.entry.peerId.empty() && !lanDrive))
{
MessageBoxW(dialog,L"Enter an absolute folder path on the original computer.",L"Folder shortcuts",MB_OK|MB_ICONWARNING);
SetFocus(GetDlgItem(dialog,shortcutPath));
return TRUE;
}
auto entry=edit.entry;
entry.path=std::move(path);
entry.title=shortcutField(dialog,shortcutTitle);
const auto &group=folderShortcuts[edit.digit];
for(size_t i=0;i<group.size();++i)
if((!edit.index || i!=*edit.index) && sameFolderShortcut(group[i],entry))
{
MessageBoxW(dialog,L"This folder is already assigned to this digit.",L"Folder shortcuts",MB_OK|MB_ICONINFORMATION);
return TRUE;
}
auto updated=folderShortcuts;
if(edit.index) updated[edit.digit][*edit.index]=std::move(entry);
else updated[edit.digit].push_back(std::move(entry));
if(!saveFolderShortcuts(updated))
{
MessageBoxW(dialog,L"Could not save folder shortcuts.",L"Folder shortcuts",MB_OK|MB_ICONWARNING);
return TRUE;
}
folderShortcuts=std::move(updated);
notifyFilesPreferences(GetAncestor(dialog,GA_ROOTOWNER));
finishFilesDialog(dialog,IDOK);
return TRUE;
}
bool editFolderShortcut(HWND owner,FolderShortcutEdit &edit)
{
return runFilesDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(110),owner,
folderShortcutEditDialog,reinterpret_cast<LPARAM>(&edit))==IDOK;
}
void addFolderShortcut(const Panel &panel,int digit)
{
if(panel.directory.empty()) return;
FolderShortcutEdit edit{{panel.directory,panel.peer?panel.peer->id:"",
panel.peer?panel.peer->name:L""},digit,{}};
if(editFolderShortcut(GetParent(panel.list),edit))
setStatus(L"Folder added to Ctrl+"+std::to_wstring(digit)+L".");
SetFocus(panel.list);
}
void openFolderShortcut(Panel &panel,const FolderShortcut &entry)
{
if(entry.peerId.empty())
{
openOn(panel,entry.path,true,{});
return;
}
queryDrivePeers();
const auto peer=std::find_if(drivePeers.begin(),drivePeers.end(),
[&](const auto &candidate){return candidate.id==entry.peerId && !candidate.address.empty();});
if(peer==drivePeers.end())
{
setStatus(L"Paired computer unavailable: "+entry.peerName);
return;
}
openOn(panel,entry.path,false,*peer);
}
constexpr int shortcutList=310,quickRemove=313,quickEdit=318,quickInsert=319,quickMoveUp=320,quickMoveDown=321;
constexpr wchar_t quickFolderHints[]=L"Ins Del F4 Ctrl+Up Ctrl+Down";
struct FolderShortcutView
{
int digit;
std::optional<FolderShortcut> chosen;
std::vector<int> digits;
int rowHeight{};
Panel *panel{};
};
void layoutQuickFolders(HWND dialog,FolderShortcutView &view,int selection)
{
const auto list=GetDlgItem(dialog,shortcutList);
SendMessageW(list,LB_RESETCONTENT,0,0);
view.digits.clear();
const auto owner=GetWindow(dialog,GW_OWNER);
const auto dc=GetDC(dialog);
const auto font=SelectObject(dc,mono);
const auto dpi=GetDpiForWindow(dialog);
const auto px=[&](int value){return MulDiv(value,dpi,96);};
TEXTMETRICW metrics{};
GetTextMetricsW(dc,&metrics);
view.rowHeight=std::max(1L,metrics.tmHeight);
const auto frame=dialogFrameMetrics(dpi);
const int inset=frame.content();
const int listTop=dialogListInset(frame,view.rowHeight);
const auto measure=[&](std::wstring_view label)
{
SIZE size{};
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;
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)
{
for(int digit=0;digit<10;++digit)
if(!folderShortcuts[digit].empty())
{
view.digits.push_back(digit);
add(L"Ctrl+"+std::to_wstring(digit));
}
}
else for(const auto &entry:folderShortcuts[view.digit])
add(entry.title.empty()?(entry.peerId.empty()?L"":entry.peerName+L" · ")+entry.path.native():entry.title);
SelectObject(dc,font);
ReleaseDC(dialog,dc);
MONITORINFO monitor{sizeof(monitor)};
GetMonitorInfoW(MonitorFromWindow(owner,MONITOR_DEFAULTTONEAREST),&monitor);
const auto &work=monitor.rcWork;
RECT parent{};
GetWindowRect(owner,&parent);
const auto windowWidth=std::max(px(260),static_cast<int>(parent.right-parent.left));
const auto windowHeight=std::max(px(140),static_cast<int>(parent.bottom-parent.top));
width=std::min(width,std::max(1,std::min(windowWidth,static_cast<int>(work.right-work.left))-2*inset));
const auto maxRows=std::max(1,(std::min(windowHeight,static_cast<int>(work.bottom-work.top))-2*listTop)/view.rowHeight);
const auto count=static_cast<int>(SendMessageW(list,LB_GETCOUNT,0,0));
const int rows=std::min(count,maxRows);
SendMessageW(list,LB_SETITEMHEIGHT,0,view.rowHeight);
const int listHeight=rows*view.rowHeight;
const int w=width+2*inset,h=listHeight+2*listTop;
const int x=std::clamp(static_cast<int>((parent.left+parent.right-w)/2),
static_cast<int>(work.left),std::max(static_cast<int>(work.left),static_cast<int>(work.right)-w));
const int y=std::clamp(static_cast<int>((parent.top+parent.bottom-h)/2),
static_cast<int>(work.top),std::max(static_cast<int>(work.top),static_cast<int>(work.bottom)-h));
SetWindowPos(dialog,nullptr,x,y,w,h,SWP_NOZORDER|SWP_NOACTIVATE);
SetWindowPos(list,nullptr,inset,listTop,width,listHeight,SWP_NOZORDER|SWP_NOACTIVATE);
SendMessageW(list,LB_SETCURSEL,std::clamp(selection,0,std::max(0,count-1)),0);
InvalidateRect(dialog,nullptr,TRUE);
}
LRESULT CALLBACK quickFolderKeys(HWND list,UINT message,WPARAM key,LPARAM flags,UINT_PTR,DWORD_PTR)
{
if(message==WM_KEYDOWN)
{
int command=0;
if(key==VK_RETURN) command=IDOK;
if(key==VK_DELETE) command=quickRemove;
if(key==VK_F4) command=quickEdit;
if(key==VK_INSERT) command=quickInsert;
if((key==VK_UP || key==VK_DOWN) && (GetKeyState(VK_CONTROL)&0x8000))
command=key==VK_UP?quickMoveUp:quickMoveDown;
if(command)
{
if(!(flags & (1LL<<30))) SendMessageW(GetParent(list),WM_COMMAND,command,0);
return 0;
}
}
return scrollList(list,message,key,flags);
}
INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
auto &view=*reinterpret_cast<FolderShortcutView*>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareCopyDialog(dialog);
layoutQuickFolders(dialog,view,0);
const auto list=GetDlgItem(dialog,shortcutList);
SetWindowSubclass(list,quickFolderKeys,1,0);
SetFocus(list);
return FALSE;
}
auto *view=reinterpret_cast<FolderShortcutView*>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!view) return FALSE;
if(message==WM_DESTROY)
{
return FALSE;
}
if(message==WM_PAINT)
{
PAINTSTRUCT ps{};
const auto dc=BeginPaint(dialog,&ps);
RECT client{};
GetClientRect(dialog,&client);
const auto frame=CreateSolidBrush(colors[Text]);
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);
EndPaint(dialog,&ps);
return TRUE;
}
if(message==WM_DRAWITEM && wp==shortcutList)
{
const auto &item=*reinterpret_cast<const DRAWITEMSTRUCT*>(lp);
if(item.itemID==UINT(-1)) return TRUE;
const auto length=SendMessageW(item.hwndItem,LB_GETTEXTLEN,item.itemID,0);
if(length<0) return TRUE;
std::wstring label(static_cast<size_t>(length)+1,L'\0');
SendMessageW(item.hwndItem,LB_GETTEXT,item.itemID,reinterpret_cast<LPARAM>(label.data()));
const auto background=colors[item.itemState&ODS_SELECTED?Selection:Dialog];
paintDialogListRow(item.hDC,item.rcItem,std::wstring_view(label.data(),static_cast<size_t>(length)),
mono,colors[Text],background,dialogRowTextInset(cellWidth));
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
finishFilesDialog(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND) return FALSE;
const auto action=LOWORD(wp);
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((action==IDOK || action==shortcutList) && row>=0 && static_cast<size_t>(row)<view->digits.size())
{
view->digit=view->digits[row];
layoutQuickFolders(dialog,*view,0);
}
return TRUE;
}
const auto &group=folderShortcuts[view->digit];
if(action==quickInsert)
{
const auto &panel=*view->panel;
FolderShortcutEdit edit{{panel.directory,panel.peer?panel.peer->id:"",
panel.peer?panel.peer->name:L""},view->digit,{}};
if(!panel.directory.empty() && editFolderShortcut(dialog,edit))
layoutQuickFolders(dialog,*view,static_cast<int>(group.size())-1);
SetFocus(GetDlgItem(dialog,shortcutList));
return TRUE;
}
if(row<0 || static_cast<size_t>(row)>=group.size()) return TRUE;
if(action==quickMoveUp || action==quickMoveDown)
{
const auto target=row+(action==quickMoveUp?-1:1);
if(target<0 || static_cast<size_t>(target)>=group.size()) return TRUE;
auto updated=folderShortcuts;
std::swap(updated[view->digit][row],updated[view->digit][target]);
if(!saveFolderShortcuts(updated))
MessageBoxW(dialog,L"Could not save folder shortcuts.",L"Folder shortcuts",MB_OK|MB_ICONWARNING);
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)};
if(editFolderShortcut(dialog,edit)) layoutQuickFolders(dialog,*view,static_cast<int>(row));
SetFocus(GetDlgItem(dialog,shortcutList));
return TRUE;
}
if(action==quickRemove)
{
auto updated=folderShortcuts;
updated[view->digit].erase(updated[view->digit].begin()+row);
if(!saveFolderShortcuts(updated))
{
MessageBoxW(dialog,L"Could not save folder shortcuts.",L"Folder shortcuts",MB_OK|MB_ICONWARNING);
return TRUE;
}
folderShortcuts=std::move(updated);
notifyFilesPreferences(GetAncestor(dialog,GA_ROOTOWNER));
if(folderShortcuts[view->digit].empty()) finishFilesDialog(dialog,IDCANCEL);
else layoutQuickFolders(dialog,*view,static_cast<int>(row));
return TRUE;
}
view->chosen=group[row];
finishFilesDialog(dialog,IDOK);
return TRUE;
}
void showFolderShortcuts(Panel &panel,int digit)
{
if(digit>=0)
{
const auto &group=folderShortcuts[digit];
if(group.empty())
{
setStatus(L"No folders assigned to Ctrl+"+std::to_wstring(digit)+L".");
return;
}
if(group.size()==1)
{
openFolderShortcut(panel,group.front());
return;
}
}
if(digit<0 && std::all_of(folderShortcuts.begin(),folderShortcuts.end(),[](const auto &group){return group.empty();}))
{
setStatus(L"No folder shortcuts.");
return;
}
FolderShortcutView view{digit};
view.panel=&panel;
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);
else if(result==-1) setStatus(L"Could not open Folder shortcuts.");
}
+449 -151
View File
File diff suppressed because it is too large. Load diff
+168 -45
View File
@@ -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 };
@@ -11,6 +11,18 @@ constexpr int wideColumnControls[]{275,276,201,202,204};
constexpr int statusColumnControls[]{277,203,205,206,207,208};
constexpr int colorOptionControls[]{279,280};
constexpr int appearanceControls[]{281,282};
enum AppearanceSection { Font, DialogFrame };
constexpr int outerFramePadding=303,innerFramePadding=305,rowTextPadding=307;
constexpr int dialogFrameControls[]{302,outerFramePadding,304,innerFramePadding,306,rowTextPadding};
constexpr struct
{
int id;
DWORD DialogFramePadding::*value;
DWORD maximum;
} frameOptions[]{
{outerFramePadding,&DialogFramePadding::outer,maxDialogFramePadding},
{innerFramePadding,&DialogFramePadding::inner,maxDialogFramePadding},
{rowTextPadding,&DialogFramePadding::rowText,maxDialogRowTextPadding}};
enum class OptionsAnchor { StretchWidth, StretchHeight, BottomRight };
struct OptionsControl
@@ -40,10 +52,25 @@ void resetPanelProperty(HWND dialog,const PanelProperty &property)
else CheckDlgButton(dialog,property.control,property.defaultValue);
}
struct OptionsDraft
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;
std::array<COLORREF,ColorCount> palette{};
std::array<COLORREF,16> custom{};
std::vector<FileStyle> styles=fileStyles;
@@ -68,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{};
@@ -84,10 +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 || 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);
}
@@ -165,7 +208,9 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
{
title=optionsTitles[page];
if(section>=0)
title=page==PanelModes?panelSectionNames[section]:page==PanelColors?(section==fileStyleSection?L"File type styles":colorNames[section]):L"Font";
title=page==PanelModes?panelSectionNames[section]:page==PanelColors?
(section==fileStyleSection?L"File type styles":colorNames[section]):
page==CommandLine?L"Command history":section==DialogFrame?L"Dialog frame":L"Font";
}
SetDlgItemTextW(dialog,optionsTitle,title);
const auto show=[&](auto &controls,bool visible)
@@ -192,11 +237,20 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
show(panelLayoutControls,page==PanelModes && section==PanelLayout);
show(wideColumnControls,page==PanelModes && section==WideColumns);
show(statusColumnControls,page==PanelModes && section==StatusColumns);
show(appearanceControls,page==Appearance && section==Font);
show(dialogFrameControls,page==Appearance && section==DialogFrame);
if(page==Appearance && section==DialogFrame)
{
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);
@@ -209,7 +263,6 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
}
updateFileStyleEditor(dialog,draft,true);
}
show(appearanceControls,page==Appearance && section>=0);
if(page==PanelColors && section>=0 && !fileTypes)
{
const auto color=draft.palette[section];
@@ -253,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"));
@@ -283,7 +336,13 @@ 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 addSection(L"Font",0,matches(L"Display font"));
else if(page==CommandLine) addSection(L"Command history",0,matches(L"Previous command"));
else
{
addSection(L"Font",Font,matches(L"Display font"));
addSection(L"Dialog frame",DialogFrame,
matches(L"Outer padding") || matches(L"Inner padding") || matches(L"Row text padding"));
}
if(category) TreeView_Expand(tree,category,TVE_EXPAND);
}
TreeView_Expand(tree,root,TVE_EXPAND);
@@ -312,12 +371,17 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
SetDlgItemInt(dialog,201,sizeWidth,FALSE);
SendDlgItemMessageW(dialog,201,EM_SETLIMITTEXT,2,0);
SendDlgItemMessageW(dialog,optionsSearch,EM_SETLIMITTEXT,255,0);
for(const auto &option:frameOptions)
for(DWORD value=0;value<=option.maximum;++value)
SendDlgItemMessageW(dialog,option.id,CB_ADDSTRING,0,
reinterpret_cast<LPARAM>(std::to_wstring(value).c_str()));
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);
filterOptions(dialog,draft);
updateOptionsApply(dialog,draft);
return TRUE;
@@ -357,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;
@@ -376,9 +440,19 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
return TRUE;
case 282:
chooseDisplayFont(dialog,draft->font,draft->points);
showOptionsPage(dialog,*draft,Appearance,0);
showOptionsPage(dialog,*draft,Appearance,Font);
updateOptionsApply(dialog,*draft);
return TRUE;
case outerFramePadding: case innerFramePadding: case rowTextPadding:
if(HIWORD(wp)==CBN_SELCHANGE)
{
const auto value=SendMessageW(reinterpret_cast<HWND>(lp),CB_GETCURSEL,0,0);
if(value>=0)
for(const auto &option:frameOptions)
if(option.id==LOWORD(wp)) draft->framePadding.*option.value=static_cast<DWORD>(value);
updateOptionsApply(dialog,*draft);
}
return TRUE;
case fileStyleState:
if(HIWORD(wp)==CBN_SELCHANGE) updateFileStyleEditor(dialog,*draft,false);
return TRUE;
@@ -420,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);
@@ -430,11 +505,13 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
if(draft->page==allOptions || (draft->page==PanelColors &&
(draft->section<0 || draft->section==fileStyleSection)))
draft->styles=defaultFileStyles;
if(draft->page==allOptions || draft->page==Appearance)
if(draft->page==allOptions || (draft->page==Appearance && draft->section!=DialogFrame))
{
draft->font=defaultFilesFont();
draft->points=defaultFontPoints;
}
if(draft->page==allOptions || (draft->page==Appearance && draft->section!=Font))
draft->framePadding=defaultDialogFramePadding;
showOptionsPage(dialog,*draft,draft->page,draft->section);
updateOptionsApply(dialog,*draft);
return TRUE;
@@ -455,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:
{
@@ -470,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);
@@ -483,41 +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;
const auto saveChanged=[](const wchar_t *name,DWORD value,DWORD initial)
{
if(value!=initial) savePreference(name,value);
};
const auto checked=[&](int id){return IsDlgButtonChecked(dialog,id)==BST_CHECKED;};
const auto inputKeys=optionHistoryKeys(dialog);
saveChanged(L"PreviousCommandKey",inputKeys[0],base.keys[0]);
saveChanged(L"CommandHistoryKey",inputKeys[1],base.keys[1]);
saveChanged(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)
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);
{
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)
if(colors[i]!=draft->palette[i])
{
colors[i]=draft->palette[i];
savePreference(std::to_wstring(i).c_str(),colors[i]);
}
refreshColors();
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;
}
@@ -530,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.");
+31 -1
View File
@@ -80,7 +80,25 @@ void paintOptionsPreview(HWND dialog,const DRAWITEMSTRUCT &item,const OptionsDra
entry(L"examples",L"old",true,false);
};
if(draft.page==PanelColors && (draft.section==Dialog || draft.section==Selection))
if(draft.page==Appearance && draft.section==DialogFrame)
{
InflateRect(&bounds,-px(8),-px(8));
const auto framePadding=dialogFrameMetrics(dpi,draft.framePadding);
const auto surface=CreateSolidBrush(palette[Dialog]);
const auto ink=CreateSolidBrush(palette[Text]);
const auto frame=paintDialogFrame(dc,bounds,framePadding,surface,ink);
const auto titleFont=previewFont?previewFont:mono;
paintDialogFrameCaptions(dc,bounds,frame,L"Folder shortcuts",surface,palette[Text],titleFont);
DeleteObject(ink);
DeleteObject(surface);
auto content=bounds;
InflateRect(&content,-framePadding.content(),-dialogListInset(framePadding,metrics.tmHeight));
content.bottom=std::min(content.bottom,content.top+rowHeight);
if(content.bottom>content.top)
paintDialogListRow(dc,content,LR"(C:\Projects\Example\Documents\Archive)",titleFont,
palette[Text],palette[Selection],dialogRowTextInset(metrics.tmAveCharWidth,draft.framePadding));
}
else if(draft.page==PanelColors && (draft.section==Dialog || draft.section==Selection))
{
InflateRect(&bounds,-px(12),-px(10));
const auto maxWidth=px(340);
@@ -134,6 +152,18 @@ void paintOptionsPreview(HWND dialog,const DRAWITEMSTRUCT &item,const OptionsDra
else panel(bounds,draft.page==PanelModes || checked(273),
draft.page==PanelColors && draft.section==PanelCursor,L"C:\\Example");
if(draft.page==PanelColors && (draft.section==Text || draft.section==Dialog))
{
auto field=item.rcItem;
InflateRect(&field,-px(12),-px(10));
field.right=std::min(field.right,field.left+px(340));
field.top+=px(5)+4*rowHeight;
field.bottom=field.top+rowHeight+px(6);
fill(field,RGB(192,192,192));
InflateRect(&field,-px(4),-px(3));
row(field,L"C:\\Example",palette[Text],palette[Dialog]);
}
RestoreDC(dc,saved);
if(previewFont) DeleteObject(previewFont);
}
+1 -1
View File
@@ -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)},
+3 -1
View File
@@ -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
View File
@@ -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.78";
inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+7 -2
View File
@@ -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));