diff --git a/AGENTS.md b/AGENTS.md index 7f9b8f1..43b4530 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -54,6 +54,9 @@ command output. 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. +Verify visible changes in a rendered window. For rendering regressions, +add an automated check that fails on the reported appearance and run it +before handing off a new build. ## Link changes to Gitea issues diff --git a/CMakeLists.txt b/CMakeLists.txt index 707b73a..f853c4f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,11 +1,13 @@ cmake_minimum_required(VERSION 3.24) -project(KSwitcher VERSION 0.6.83 LANGUAGES CXX RC) +project(KSwitcher VERSION 0.6.84 LANGUAGES CXX RC) if(NOT WIN32) message(FATAL_ERROR "KSwitcher uses native Windows APIs") endif() set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) -add_executable(KSwitcherFiles WIN32 src/files_main.cpp resources/files.rc) +add_executable(KSwitcherFiles WIN32 src/files_main.cpp src/files_text_window.cpp + src/files_text_document.cpp src/files_text_language.cpp resources/files.rc) +include(cmake/FilesTextLibraries.cmake) set_target_properties(KSwitcherFiles PROPERTIES OUTPUT_NAME "KSwitcher.Files") target_compile_definitions(KSwitcherFiles PRIVATE UNICODE _UNICODE NOMINMAX _WIN32_WINNT=0x0A00) find_program(KSWITCHER_POWERSHELL NAMES pwsh powershell REQUIRED) @@ -14,6 +16,11 @@ add_custom_target(KSwitcherTerminalAssets -Destination "$" VERBATIM) add_dependencies(KSwitcherFiles KSwitcherTerminalAssets) +add_custom_target(check-files-search-arrow + COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_search_arrow.ps1" + -Executable "$" + DEPENDS KSwitcherFiles + VERBATIM) target_include_directories(KSwitcherFiles PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include") target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid) if(MSVC) @@ -106,6 +113,21 @@ else() target_link_options(KSwitcherOcrTests PRIVATE -static -static-libgcc -static-libstdc++) endif() enable_testing() +add_executable(KSwitcherFilesTextTests tests/files_text_document.cpp src/files_text_document.cpp) +target_include_directories(KSwitcherFilesTextTests PRIVATE src) +target_compile_definitions(KSwitcherFilesTextTests PRIVATE UNICODE _UNICODE NOMINMAX WIN32_LEAN_AND_MEAN) +target_link_libraries(KSwitcherFilesTextTests PRIVATE ole32) +if(NOT MSVC) + target_link_options(KSwitcherFilesTextTests PRIVATE -static) +endif() +add_test(NAME files-text-document COMMAND KSwitcherFilesTextTests) +add_executable(KSwitcherFilesModalTests tests/files_modal_dialog.cpp) +target_include_directories(KSwitcherFilesModalTests PRIVATE src) +target_link_libraries(KSwitcherFilesModalTests PRIVATE user32 comctl32) +if(NOT MSVC) + target_link_options(KSwitcherFilesModalTests PRIVATE -static) +endif() +add_test(NAME files-modal-dialog COMMAND KSwitcherFilesModalTests) add_executable(KSwitcherLanTests tests/lan.cpp) target_link_libraries(KSwitcherLanTests PRIVATE kscore) if(MSVC) diff --git a/FILES-UI.md b/FILES-UI.md index 492f67d..094b662 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -2,6 +2,17 @@ Far Manager є зразком для оформлення файлового менеджера. Основне вікно використовує системний заголовок Windows. Панелі, меню й діалоги операцій використовують моноширинний шрифт менеджера та оформлення в стилі Far. +Власні модальні діалоги панелей, редактора й переглядача використовують +`FilesModalDialog`. Escape і клік поза діалогом у клієнтській області Files +виконують Cancel, а фокус повертається до елемента, з якого відкрили діалог. +Кліки на робочому столі та в інших застосунках залишають діалог відкритим. +Заголовок і рамка вікна-власника доступні, а діалог рухається разом із +власником. Діалог центрується відносно власника та звужується разом із ним +до власної мінімальної ширини. Поки діалог відкритий, ширина власника +обмежена цією мінімальною шириною з відступами. +Це діє і для вкладених діалогів. Під час файлової операції Cancel спершу +просить підтвердити переривання. + ## Скорочення - Enter і подвійний клік відкривають папку в поточній панелі, а локальний @@ -47,7 +58,7 @@ Far Manager є зразком для оформлення файлового м Вікно історії бірюзове, поле пошуку сіро-бірюзове. Поки історія відкрита, дії в панелях, меню й командному рядку заблоковано. Заголовок і рамка головного вікна доступні для переміщення, зміни розміру та керування вікном. - Escape або клік поза діалогом закриває історію. Заголовок і рамка головного + Escape або клік у Files поза діалогом закриває історію. Заголовок і рамка головного вікна залишають історію відкритою під час керування вікном. Історія центрується відносно головного вікна й рухається разом із ним. Tab циклічно переводить фокус між пошуком і списком. @@ -66,11 +77,70 @@ Far Manager є зразком для оформлення файлового м - Глобальне скорочення повертає до відкритого вікна 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. +- Ctrl+0–9 одразу відкриває єдину папку. Для кількох папок відкривається компактний попап Far з одним заголовком Folder shortcuts у подвійній рамці та коротким рядом клавіш у нижній рамці. Ширина залежить від найдовшого запису й обмежується розміром вікна, а висота — кількістю видимих рядків. Нижня рамка показує Ins Del F4 Ctrl+Up Ctrl+Down. Insert додає поточну папку через Title і Path, Delete відв’язує, F4 редагує, Ctrl+Up і Ctrl+Down змінюють і зберігають порядок. Enter відкриває папку. Escape або клік у Files поза попапом закриває його й повертає фокус до панелі. Commands → Folder shortcuts дає вибрати зайняту цифру й відкрити той самий попап навіть для єдиного запису. Brief і Wide доступні в меню Left/Right та Options. ## Налаштування Files -- Options у головному меню одразу відкриває стандартний діалог Windows. Ліворуч є пошук за назвою категорії чи параметра й дерево результатів. Вибір дочірнього вузла відкриває лише його редактор праворуч. Пошук за назвою окремої властивості відкриває вузол, що її містить. Перемикання вузлів зберігає незастосовані зміни. +### Переглядач і редактор + +- F3 відкриває поточний локальний файл у вбудованому переглядачі лише + для читання. F4 відкриває спільне вікно в режимі редагування. Alt+F3 + відкриває файл у програмі, призначеній Windows для цього типу, а Alt+F4 + викликає зареєстровану дію Edit. Ці команди також є в меню Commands. + F10 або × закривають головне вікно Files. Файл із панелі LAN треба + спочатку скопіювати локально. +- Вікно використовує той самий шрифт і розмір, що й файлові панелі, + синю палітру Far за замовчуванням, + рядок стану згори й підказки клавіш унизу. Інформація про файл + вирівняна праворуч. Режим (Edit або View) стоїть у дужках після імені, + далі йдуть кодування, синтаксис, позиція курсора й сторінка великого файла. + Номери рядків показані приглушеним кольором з невеликим відступом від тексту. + Меню редактора й переглядача використовують моноширинний шрифт і кольори + обраної схеми. У FAR (blue) написи верхнього меню чорні, поточний пункт + має чорне тло, а літери доступу жовті. F9 відкриває меню, Alt з літерою + доступу відкриває потрібний розділ. Редактор позначає незбережені зміни зірочкою. + Esc і F10 закривають незмінений файл одразу. Якщо вміст змінився, + діалог Far пропонує Save, Discard або Cancel. +- Syntax → Automatic визначає синтаксис за іменем, розширенням або + shebang. Відомі типи включають C#, C/C++, JavaScript/TypeScript, + HTML, XML, CSS, SQL, Python, PowerShell, Bash, JSON, YAML, TOML і Markdown. + У меню Syntax можна вибрати будь-який вбудований лексер Lexilla або Plain text. + Стан багаторядкової конструкції починається заново на межі сторінки. +- Ctrl+PgUp/PgDn перемикають сторінки, F5 переходить до заданої сторінки, + Ctrl+Shift+Home/End відкривають першу й останню. Ctrl+F шукає в поточній + сторінці, F3 повторює пошук. Ctrl+A виділяє поточну сторінку. + Історія Undo/Redo діє в межах відкритої сторінки. +- Початкова сторінка займає близько 1 МіБ файла. Для вставок і редагування + сторінка може вирости до 8 МіБ у UTF-8. Зміни інших сторінок тимчасово + зберігаються на диску. F2 або Ctrl+S потоково записують нову копію в + папку файла, тож збереження потребує вільного місця для цієї копії. + UTF-8 із BOM або без нього та UTF-16 LE/BE із BOM зберігають своє + кодування. Нередаговані байти копіюються без перетворення. +- Команда Options у панелях, редакторі й переглядачі відкриває один діалог + KSwitcher Files Options. Розділи Viewer та Editor зберігають окремі профілі. + З редактора або переглядача діалог відкриває відповідний розділ. Apply + застосовує зміни до відкритих вікон, Cancel відкидає незастосовану чернетку. + Доступні перенесення рядків, номери рядків, показ пробілів і + кінців рядків, підсвічування поточного рядка, ширина табуляції від 1 до 16, + схеми FAR (blue), Dark і Light та власні кольори. Save scheme у розділі + Viewer або Editor додає поточну палітру до спільного списку схем. Apply + зберігає її та робить доступною в обох розділах. У редакторі також можна + ввімкнути вставлення пробілів замість табуляцій і автоматичні відступи, + а також вибрати символи кінця для нових рядків. +- Діалоги пошуку й переходу до сторінки використовують подвійні рамки та + кнопки Files. Search має компактний розмір, сіре тло, бірюзове поле та окремі кнопки + Find previous і Find next. Word і Selection підставляють у поле слово + під курсором або однорядкове виділення. Поле має висоту одного рядка + й вертикально центрований текст. Стрілка біля поля або Alt+Down + відкриває історію з групуванням за датами. Вибір запису підставляє + запит у поле. Editor і Viewer спільно зберігають до 100 останніх + різних запитів між запусками. Спільний шрифт панелей, меню й тексту змінюється в + Options → Appearance → Font. Редактор і переглядач отримують новий + шрифт після Apply. + +### Параметри файлових панелей + +- Options у головному меню спочатку прибирає смугу меню й одразу відкриває стандартний діалог Windows. Ліворуч є пошук за назвою категорії чи параметра й дерево результатів. Вибір дочірнього вузла відкриває лише його редактор праворуч. Пошук за назвою окремої властивості відкриває вузол, що її містить. Перемикання вузлів зберігає незастосовані зміни. - File panel modes має вузли Panel layout, Wide panel columns і Status line columns. У Colors кожен колір має власний вузол. В Appearance шрифт редагується у вузлі Font. Діалог змінює розмір від розміру, який вміщує всі параметри. Ширина лівої навігації стала, дерево росте по висоті, а права область використовує додатковий простір. OK, Cancel та Apply лишаються внизу праворуч. - Reset selected to defaults скидає вибраний рівень дерева. Корінь All settings скидає всі параметри, навіть коли пошук приховує частину дерева. У редакторах із кількома параметрами Reset property скидає лише вибрану властивість. Скидання змінює чернетку до Apply або OK. Стандартний Panel background — `#000080`. - Apply доступна, коли чернетка відрізняється від застосованих налаштувань. Після Apply або повернення всіх значень до застосованих вона вимикається. Apply одразу зберігає зміни й перемальовує панелі за відкритим діалогом. OK робить те саме й закриває діалог. Cancel і Escape відкидають зміни після останнього Apply та повертають фокус до командного рядка. @@ -119,6 +189,8 @@ Far Manager є зразком для оформлення файлового м - F5, F6, F8 і Shift+Delete у віддалених панелях використовують спільні підтвердження, попередження й прогрес. F5/F6 працюють із файлами та деревами папок між локальними й віддаленими панелями, зокрема між двома різними ПК. Між шляхами одного віддаленого ПК вміст копіюється на ньому. F8 використовує кошик того ПК, на якому лежить файл. - Після розриву з’єднання повтори F5 або F6 до того самого призначення. Віддалене копіювання відновлюється з підтвердженої позиції, якщо збережені байти відповідають початку вихідного файла. Підтверджене скасування видаляє частковий запис поточного файла. Завершені файли лишаються на місці. Наявний файл призначення замінюється після повного запису, а при переміщенні джерело видаляється після підтвердження запису призначення. +- F7, пункт Files → Make folder і кнопка F7 Mkdir відкривають модальний діалог Far. Стрілка біля імені та Alt+Down відкривають історію успішних введень. Link type має варіанти none, directory junction і symbolic link. Поле Target активне для посилань і приймає абсолютний шлях або шлях від поточної папки. У віддаленій панелі посилання створюється на віддаленому ПК, а symbolic link залежить від дозволів Windows на цьому ПК. +- Process multiple names дозволяє розділити імена комами або крапками з комою. Якщо такий символ є частиною імені, візьми ім’я в подвійні лапки. Діалог створює елементи у поточному каталозі, оновлює панель і ставить курсор на останній створений елемент. При помилці в середині списку вже створені елементи зберігаються. - Після F5 або F6 успішно оброблені елементи коротко підсвічуються в панелі, що показує папку призначення. Підсвітка тексту відрізняється від курсора й не переносить фокус. - У широкому режимі ширина під вирівняні розширення залежить від найдовшого розширення в поточній панелі. За вузької панелі залишай місце для імені та колонки Size. @@ -131,7 +203,7 @@ Far Manager є зразком для оформлення файлового м ## Спільні елементи діалогів - Власні діалоги Files блокують дії панелей і командного рядка, залишаючи - системний заголовок і рамку головного вікна доступними. Клік поза діалогом + системний заголовок і рамку головного вікна доступними. Клік у Files поза діалогом діє як Cancel. Для прогресу копіювання, переміщення й видалення це відкриває підтвердження скасування. @@ -141,10 +213,17 @@ Far Manager є зразком для оформлення файлового м - Для власних діалогів і списків 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` центрує текст, підсвічує фокус і додає фігурні дужки для дії за замовчуванням та квадратні для решти кнопок. +- Модальні діалоги редактора й переглядача використовують той самий шрифт, що й діалоги операцій Files. Розміри полів і кнопок враховують метрики цього шрифту. - Нижні секції з кнопками у Copy, Warning і вікні прогресу мають однакову висоту, прив’язану до висоти рядка шрифту. Використовуй `layoutDialogButtons` для такої секції та `centerDialogRow` для інших рядків між роздільниками. Межі секції визначають положення рядка. -- Для текстових полів Far використовуй ресурс `FAR_EDIT` і спільну підготовку та палітру діалогів. Поля призначення Copy/Rename і Title/Path використовують нативний Win32 Edit без рамки, моноширинний шрифт і вертикальне центрування. Кольори Text і Popup background діють на всі ці поля, зокрема на поле Copy лише для читання. У відповідних розділах Options → Colors зміни видно на зразку поля. Existing files у Copy є списком без редагування. Поля та редагований список Windows Options мають системне оформлення. +- Search і спільні нижні секції Far використовують компактні проміжки між рядками й кнопками, прив’язані до метрик моноширинного шрифту. У Search висота кнопки дорівнює висоті одного рядка. +- Нижні кнопки Far групуються по центру. Їхня ширина залежить від напису й дужок, а проміжок між ними становить приблизно половину символу. +- Прапорці Far у Search, Copy і попередженнях використовують спільний компонент. У фокусі короткий системний курсор блимає між дужками, а тло рядка зберігає колір діалогу. +- У Copy і Rename/Move помилки шляху показує окремий червоний модальний діалог Far. Після його закриття фокус повертається до поля шляху. +- Короткі червоні повідомлення використовують звичайний текст без смуги прокрутки. Висота діалогу залежить від кількості рядків повідомлення. +- Для однорядкових полів Far використовуй спільний компонент `FAR_EDIT` і спільну підготовку та палітру діалогів. Компонент використовує нативний Win32 Edit без рамки й центрує текст вертикально. Його використовують Search, Copy/Rename, Title/Path і пошук в історії. Кольори Text і Popup background діють на всі ці поля, зокрема на поле Copy лише для читання. У відповідних розділах Options → Colors зміни видно на зразку поля. Existing files у Copy є списком без редагування. Поля та редагований список Windows Options мають системне оформлення. - Для позиціонування роздільника використовуй невидимий маркер, якщо межу не задає інший елемент секції. Спільний обробник малює лінію. -- Випадаючі списки Far використовують бірюзове тло палітри менеджера. Текст і стрілку вирівнюй вертикально по центру. Прапорці в діалогах операцій використовують позначки `[ ]` та `[x]` і видимий клавіатурний фокус. +- Випадаючі списки й поля Far мають висоту одного рядка шрифту. Бірюзове поле прилягає до сірої ділянки завширшки один символ із темною, вертикально центрованою стрілкою. Make folder, Search і Copy використовують спільне малювання стрілки. Прапорці в діалогах операцій використовують позначки `[ ]` та `[x]` і видимий клавіатурний фокус. +- Розкриті списки й історія Far використовують спільний попап із бірюзовим тлом, світлою рамкою та чорним вибраним рядком. Попап прилягає до обох країв бірюзового поля, стрілка лишається праворуч за межами списку. Історія групується за датами. Довгі списки прокручуються, Enter вибирає рядок, Escape закриває список і повертає фокус до поля. - Повторно використовуй спільне оформлення. Текст, дії та стан операції передавай із коду конкретної операції. Наприклад, Warning повертає відповідь і стан прапорця, а копіювання вирішує, чи застосувати відповідь до наступних конфліктів. ## Діалог Copy diff --git a/README.md b/README.md index 662bdc2..c2b450d 100644 --- a/README.md +++ b/README.md @@ -925,6 +925,12 @@ Run `./package.ps1 -PublishRelease` after building and testing to refresh the tr ## Verification +The Files build uses CMake 3.24 or later and Ninja, both included in the local +w64devkit toolchain. CMake downloads pinned Scintilla and Lexilla source +archives for the built-in viewer and editor on the first configure. The +[Scintilla and Lexilla license](resources/files-text-license.txt) is also +embedded in KSwitcher.Files.exe. + ```powershell .\build.ps1 -Test # Pure/native regression checks; does not touch the user's clipboard .\build.ps1 -Ocr # Render a synthetic image, decode it with WIC and recognize it with Windows OCR diff --git a/Release/README.md b/Release/README.md index 9e19ddc..ac4faa5 100644 --- a/Release/README.md +++ b/Release/README.md @@ -1,5 +1,11 @@ # Latest Windows release +## v0.6.84 — 2026-11-15 + +KSwitcher Files adds an internal viewer on F3 and editor on F4 with syntax highlighting, paged access to large text files, and shared search history. Alt+F3 and Alt+F4 open external applications. Files Options now includes viewer and editor settings, including tab width and the FAR (blue) color scheme. F7 creates folders and directory links, supports multiple names, and remembers successful inputs. Far-style dialogs share focus, resizing and keyboard behavior. + +**Українською.** У KSwitcher Files з’явилися вбудований переглядач по F3 і редактор по F4 з підсвічуванням синтаксису, посторінковою роботою з великими текстовими файлами та спільною історією пошуку. Alt+F3 і Alt+F4 відкривають зовнішні програми. Спільні Options містять параметри переглядача й редактора, зокрема ширину табуляції та схему FAR (blue). F7 створює папки й посилання на каталоги, підтримує кілька імен і запам’ятовує успішні введення. Модальні діалоги Far мають спільну поведінку фокуса, зміни розміру й клавіатурної навігації. + ## v0.6.83 — 2026-11-15 In KSwitcher Files, the command line keeps keyboard focus while Tab switches panes and Up, Down, Page Up, and Page Down move the active pane's cursor. Ctrl+F inserts the full path under the cursor, using double quotes only for paths with spaces. Ctrl+C copies the entire command line. Alt plus a character starts a filename or folder search. After the first match, type without Alt in the Search popup at the bottom of the active pane. F9 opens the menu. diff --git a/build.ps1 b/build.ps1 index 59c65e0..ba3f235 100644 --- a/build.ps1 +++ b/build.ps1 @@ -47,14 +47,22 @@ try { if ($LASTEXITCODE) { throw 'Screenshot link failed' } Copy-Item -LiteralPath $screenshotPath -Destination build/release/KSwitcher.Screenshot.exe -Force $filesPath = Join-Path (Split-Path $executablePath) 'KSwitcher.Files.exe' - $terminalIncludes = & "$root/tools/stage-files-terminal.ps1" -Destination (Split-Path $filesPath) - & "$root/tools/stage-files-terminal.ps1" -Destination build/release | Out-Null - & windres resources/files.rc -O coff -o build/files-res.o - if ($LASTEXITCODE) { throw 'File manager resource compilation failed' } - & $compiler @common "-I$terminalIncludes" -mwindows -municode -static -s src/files_main.cpp build/files-res.o build/lan_files.o build/lan_channel.o build/lan_pairing.o build/platform.o build/core.o '-Wl,--gc-sections' @libs -o $filesPath + $filesBuild = Join-Path $outDir 'files-cmake' + & cmake -S $root -B $filesBuild -G Ninja "-DCMAKE_CXX_COMPILER=$compiler" -DCMAKE_BUILD_TYPE=MinSizeRel + if ($LASTEXITCODE) { throw 'File manager configuration failed' } + & cmake --build $filesBuild --target KSwitcherFiles --parallel 8 if ($LASTEXITCODE) { throw 'File manager build failed' } + Copy-Item -LiteralPath (Join-Path $filesBuild 'KSwitcher.Files.exe') -Destination $filesPath -Force + & strip $filesPath + if ($LASTEXITCODE) { throw 'File manager stripping failed' } + & "$root/tools/stage-files-terminal.ps1" -Destination (Split-Path $filesPath) | Out-Null + & "$root/tools/stage-files-terminal.ps1" -Destination build/release | Out-Null Copy-Item -LiteralPath $filesPath -Destination build/release/KSwitcher.Files.exe -Force if ($Test) { + & cmake --build $filesBuild --target KSwitcherFilesTextTests + if ($LASTEXITCODE) { throw 'Files text test build failed' } + & (Join-Path $filesBuild 'KSwitcherFilesTextTests.exe') + if ($LASTEXITCODE) { throw 'Files text tests failed' } & $compiler @common -Werror tests/settings_merge.cpp build/sync.o build/storage.o build/core.o build/platform.o build/ocr.o @libs -static -s -o build/KSwitcherSettingsMergeTests.exe if ($LASTEXITCODE) { throw 'Settings merge test build failed' } & .\build\KSwitcherSettingsMergeTests.exe diff --git a/cmake/FilesTextLibraries.cmake b/cmake/FilesTextLibraries.cmake new file mode 100644 index 0000000..9b80449 --- /dev/null +++ b/cmake/FilesTextLibraries.cmake @@ -0,0 +1,26 @@ +include(FetchContent) +FetchContent_Declare(scintilla + URL https://www.scintilla.org/scintilla569.zip + URL_HASH SHA256=fddc637afa6e3a9205a5ad67c777d711a921ed2797d792f3034010c1be1539d6 + DOWNLOAD_EXTRACT_TIMESTAMP FALSE) +FetchContent_Declare(lexilla + URL https://www.scintilla.org/lexilla555.zip + URL_HASH SHA256=713ada097b7da0594638e2c5723d8dea486653c23ec2e0c12631df7e5b7f0991 + DOWNLOAD_EXTRACT_TIMESTAMP FALSE) +FetchContent_MakeAvailable(scintilla lexilla) + +file(GLOB scintilla_sources "${scintilla_SOURCE_DIR}/src/*.cxx" "${scintilla_SOURCE_DIR}/win32/*.cxx") +list(FILTER scintilla_sources EXCLUDE REGEX "/ScintillaDLL\\.cxx$") +file(GLOB lexilla_sources "${lexilla_SOURCE_DIR}/lexlib/*.cxx" "${lexilla_SOURCE_DIR}/lexers/*.cxx") +add_library(KSwitcherFilesText STATIC ${scintilla_sources} ${lexilla_sources} + "${lexilla_SOURCE_DIR}/src/Lexilla.cxx") +target_include_directories(KSwitcherFilesText + PUBLIC "${scintilla_SOURCE_DIR}/include" "${lexilla_SOURCE_DIR}/include" + PRIVATE "${scintilla_SOURCE_DIR}/src" "${lexilla_SOURCE_DIR}/lexlib") +target_compile_definitions(KSwitcherFilesText PRIVATE UNICODE _UNICODE NOMINMAX LEXILLA_NO_EXPORT) +target_link_libraries(KSwitcherFilesText PRIVATE imm32 ole32 oleaut32 msimg32) +target_link_libraries(KSwitcherFiles PRIVATE KSwitcherFilesText) +if(MSVC) + set_property(TARGET KSwitcherFilesText KSwitcherFiles PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + target_compile_options(KSwitcherFilesText PRIVATE /utf-8) +endif() diff --git a/package.ps1 b/package.ps1 index 2ce2e25..419328e 100644 --- a/package.ps1 +++ b/package.ps1 @@ -11,6 +11,7 @@ Copy-Item -LiteralPath (Join-Path $root 'build\release\WebView2Loader.dll') -Des Copy-Item -LiteralPath (Join-Path $root 'build\release\terminal') -Destination $destination -Recurse -Force Copy-Item -LiteralPath (Join-Path $root 'LICENSE') -Destination $destination Copy-Item -LiteralPath (Join-Path $root 'vendor\json-LICENSE.txt') -Destination $destination +Copy-Item -LiteralPath (Join-Path $root 'resources\files-text-license.txt') -Destination $destination Copy-Item -LiteralPath (Join-Path $root 'README.md') -Destination $destination Copy-Item -LiteralPath (Join-Path $root 'LAN-PREVIEW.md') -Destination $destination Copy-Item -LiteralPath (Join-Path $root 'dictionaries') -Destination $destination -Recurse -Force @@ -19,7 +20,7 @@ Copy-Item -LiteralPath (Join-Path $root 'resources\portable-tools-README.txt') - Copy-Item -LiteralPath (Join-Path $root 'build\release\tools\StayHere.exe') -Destination (Join-Path $destination 'tools\StayHere.exe') -Force Copy-Item -LiteralPath (Join-Path $root 'utilities\StayHere\README.md') -Destination (Join-Path $destination 'tools\StayHere-README.md') -Force # Enumerate the distributable files explicitly; do not include a user's data directory. -$files = @('KSwitcher.exe','KSwitcher.Config.exe','KSwitcher.Screenshot.exe','KSwitcher.Files.exe','WebView2Loader.dll','terminal','LICENSE','json-LICENSE.txt','README.md','LAN-PREVIEW.md','dictionaries','tools\README.txt','tools\StayHere.exe','tools\StayHere-README.md') | ForEach-Object { Join-Path $destination $_ } +$files = @('KSwitcher.exe','KSwitcher.Config.exe','KSwitcher.Screenshot.exe','KSwitcher.Files.exe','WebView2Loader.dll','terminal','LICENSE','json-LICENSE.txt','files-text-license.txt','README.md','LAN-PREVIEW.md','dictionaries','tools\README.txt','tools\StayHere.exe','tools\StayHere-README.md') | ForEach-Object { Join-Path $destination $_ } $entries = foreach ($path in $files) { foreach ($file in @(Get-ChildItem -LiteralPath $path -File -Recurse)) { @{path=$file.FullName.Substring($destination.Length+1).Replace('\','/'); size=$file.Length; sha256=(Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash.ToLowerInvariant()} diff --git a/resources/app.rc b/resources/app.rc index c7eedb4..ee943d1 100644 --- a/resources/app.rc +++ b/resources/app.rc @@ -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,83,0 - PRODUCTVERSION 0,6,83,0 + FILEVERSION 0,6,84,0 + PRODUCTVERSION 0,6,84,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.83" + VALUE "FileVersion", "0.6.84" END END BLOCK "VarFileInfo" diff --git a/resources/files-text-license.txt b/resources/files-text-license.txt new file mode 100644 index 0000000..e93ac62 --- /dev/null +++ b/resources/files-text-license.txt @@ -0,0 +1,20 @@ +License for Lexilla, Scintilla, and SciTE + +Copyright 1998-2021 by Neil Hodgson + +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation. + +NEIL HODGSON DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS +SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS, IN NO EVENT SHALL NEIL HODGSON BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE +OR PERFORMANCE OF THIS SOFTWARE. \ No newline at end of file diff --git a/resources/files.rc b/resources/files.rc index 750d5e1..8a9d1c4 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -1,11 +1,82 @@ +#pragma code_page(65001) #include #include #define FAR_EDIT(id, mode, x, y, width, height) \ - CONTROL "", id, "Edit", ES_AUTOHSCROLL | WS_TABSTOP | mode, x, y, width, height + CONTROL "", id, "KSwitcher.Files.FarEdit", ES_MULTILINE | ES_AUTOHSCROLL | WS_TABSTOP | mode, x, y, width, height 1 ICON "kswitcher-files.ico" 1 RT_MANIFEST "app.manifest" +601 RCDATA "files-text-license.txt" + +602 DIALOGEX 0, 0, 230, 85 +STYLE DS_SETFONT | DS_CENTER | WS_POPUP +FONT 10, "Consolas" +BEGIN + LTEXT "&Page number", 101, 18, 21, 194, 12 + FAR_EDIT(100, ES_NUMBER, 18, 38, 194, 16) + CONTROL "&Go", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 53, 59, 60, 17 + CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 117, 59, 60, 17 +END + +604 DIALOGEX 0, 0, 268, 101 +STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN +FONT 10, "Consolas" +BEGIN + CONTROL "&Search for", 109, "Static", SS_OWNERDRAW, 18, 17, 130, 12 + FAR_EDIT(100, 0, 18, 30, 241, 14) + CONTROL "↓", 108, "Button", BS_OWNERDRAW | WS_TABSTOP, 259, 30, 11, 14 + CONTROL "W&ord", 106, "Button", BS_OWNERDRAW | WS_TABSTOP, 160, 14, 49, 15 + CONTROL "Se&lection", 107, "Button", BS_OWNERDRAW | WS_TABSTOP, 212, 14, 58, 15 + CONTROL "", 104, "Static", NOT WS_VISIBLE, 18, 51, 1, 1 + AUTOCHECKBOX "&Case sensitive", 101, 18, 52, 110, 12 + AUTOCHECKBOX "&Whole words", 102, 18, 64, 110, 12 + CONTROL "", 105, "Static", NOT WS_VISIBLE, 18, 81, 1, 1 + CONTROL "Find pre&vious", 103, "Button", BS_OWNERDRAW | WS_TABSTOP, 33, 80, 83, 15 + CONTROL "Find &next", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 121, 80, 76, 15 + CONTROL "Canc&el", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 202, 80, 53, 15 +END + +603 DIALOGEX 0, 0, 230, 72 +STYLE DS_SETFONT | DS_CENTER | WS_POPUP +FONT 10, "Consolas" +BEGIN + LTEXT "Save changes to this file?", -1, 18, 23, 194, 12, SS_CENTER + CONTROL "&Save", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP, 17, 42, 60, 17 + CONTROL "&Discard", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP, 82, 42, 66, 17 + CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 153, 42, 60, 17 +END + +607 DIALOGEX 0, 0, 300, 106 +STYLE DS_SETFONT | DS_CENTER | WS_POPUP +FONT 10, "Consolas" +BEGIN + CONTROL "", 100, "Edit", ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | WS_VSCROLL | WS_TABSTOP, 18, 22, 264, 52 + CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 120, 80, 60, 17 + CONTROL "&Yes", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 85, 80, 60, 17 + CONTROL "&No", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 155, 80, 60, 17 + AUTOCHECKBOX "&Remember for this session", 101, 18, 63, 264, 13, NOT WS_VISIBLE +END + +609 DIALOGEX 0, 0, 185, 57 +STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN +FONT 10, "Consolas" +BEGIN + LTEXT "", 100, 14, 16, 157, 13, SS_NOPREFIX + CONTROL "", 102, "Static", NOT WS_VISIBLE, 14, 35, 1, 1 + CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 67, 38, 51, 15 +END + +608 DIALOGEX 0, 0, 220, 67 +STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Save color scheme" +FONT 9, "Segoe UI" +BEGIN + LTEXT "Scheme &name", -1, 8, 8, 204, 10 + EDITTEXT 100, 8, 21, 204, 14, ES_AUTOHSCROLL + DEFPUSHBUTTON "Save", IDOK, 105, 44, 50, 14 + PUSHBUTTON "Cancel", IDCANCEL, 162, 44, 50, 14 +END 101 DIALOGEX 0, 0, 397, 310 STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_CLIPCHILDREN @@ -61,24 +132,40 @@ BEGIN AUTOCHECKBOX "&Underline", 297, 131, 166, 80, 12 AUTOCHECKBOX "Stri&kethrough", 298, 218, 166, 100, 12 CONTROL "Settings preview", 299, "Static", SS_OWNERDRAW | WS_BORDER, 131, 202, 253, 81 + AUTOCHECKBOX "&Wrap lines", 350, 131, 28, 118, 12 + AUTOCHECKBOX "&Line numbers", 351, 257, 28, 125, 12 + AUTOCHECKBOX "Show &whitespace and line endings", 352, 131, 45, 118, 12 + AUTOCHECKBOX "&Highlight current line", 353, 257, 45, 125, 12 + AUTOCHECKBOX "Insert &spaces for tabs", 354, 131, 62, 118, 12 + AUTOCHECKBOX "Auto &indent", 355, 257, 62, 125, 12 + LTEXT "&Tab width", 356, 131, 84, 118, 10 + COMBOBOX 357, 257, 81, 125, 100, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL + LTEXT "Line &endings for new lines", 358, 131, 104, 118, 10 + COMBOBOX 359, 257, 101, 125, 77, CBS_DROPDOWNLIST | WS_TABSTOP + LTEXT "Color sc&heme", 362, 131, 125, 118, 10 + COMBOBOX 363, 257, 122, 125, 67, CBS_DROPDOWNLIST | WS_TABSTOP + LTEXT "Customize &color", 364, 131, 145, 118, 10 + COMBOBOX 365, 257, 142, 125, 116, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL + PUSHBUTTON "Change color…", 366, 257, 181, 82, 15 + LTEXT "", 367, 345, 184, 45, 12 + PUSHBUTTON "&Save scheme…", 368, 131, 163, 118, 15 DEFPUSHBUTTON "OK", IDOK, 222, 289, 50, 14 PUSHBUTTON "Cancel", IDCANCEL, 280, 289, 50, 14 PUSHBUTTON "&Apply", 283, 338, 289, 50, 14 END -102 DIALOGEX 0, 0, 350, 145 +102 DIALOGEX 0, 0, 350, 110 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 "", 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 + FAR_EDIT(211, 0, 14, 29, 322, 18) + LTEXT "Existing files:", 212, 14, 57, 122, 14, SS_CENTERIMAGE + COMBOBOX 213, 140, 57, 196, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_VSCROLL | WS_TABSTOP + AUTOCHECKBOX "Also ask on read-only files", 214, 14, 77, 322, 14 + CONTROL "&Copy", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 87, 92, 86, 18 + CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 177, 92, 86, 18 END 103 DIALOGEX 0, 0, 460, 126 @@ -111,7 +198,7 @@ BEGIN 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 + AUTOCHECKBOX "Remember choice", 232, 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 @@ -154,6 +241,24 @@ BEGIN LTEXT "", 248, 14, 73, 1, 1 CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 157, 74, 86, 18 END +108 DIALOGEX 0, 0, 264, 110 +STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN +FONT 10, "Consolas" +BEGIN + CONTROL "Create the &folder:", 360, "Static", SS_OWNERDRAW, 14, 15, 236, 12 + FAR_EDIT(361, 0, 14, 27, 225, 16) + CONTROL "↓", 363, "Button", BS_OWNERDRAW | WS_TABSTOP, 239, 27, 11, 16 + CONTROL "", 362, "Static", NOT WS_VISIBLE, 14, 48, 1, 1 + CONTROL "&Link type:", 364, "Static", SS_OWNERDRAW, 14, 51, 73, 12 + COMBOBOX 365, 90, 48, 160, 64, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP + CONTROL "&Target:", 366, "Static", SS_OWNERDRAW, 14, 65, 73, 12 + FAR_EDIT(367, 0, 90, 63, 160, 16) + AUTOCHECKBOX "Process &multiple names", 368, 14, 79, 236, 13 + CONTROL "", 369, "Static", NOT WS_VISIBLE, 14, 96, 1, 1 + CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 72, 97, 54, 15 + CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 132, 97, 60, 15 +END + 109 DIALOGEX 0, 0, 250, 85 STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN CAPTION "Folder shortcuts" @@ -181,6 +286,6 @@ 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) + FAR_EDIT(325, 0, 12, 28, 361, 16) LISTBOX 324, 12, 49, 361, 155, LBS_NOTIFY | LBS_OWNERDRAWFIXED | LBS_HASSTRINGS | LBS_NOINTEGRALHEIGHT | WS_TABSTOP END diff --git a/src/files_command_history.inl b/src/files_command_history.inl index 3800159..45ac1ae 100644 --- a/src/files_command_history.inl +++ b/src/files_command_history.inl @@ -61,11 +61,7 @@ void loadCommandHistory() 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}); + terminalHistory.push_back({ks::files::historyDate(),command}); if(terminalHistory.size()>commandHistoryLimit) terminalHistory.erase(terminalHistory.begin()); std::wstring data; for(const auto &entry:terminalHistory) diff --git a/src/files_command_history_dialog.inl b/src/files_command_history_dialog.inl index 0652eed..ca62e97 100644 --- a/src/files_command_history_dialog.inl +++ b/src/files_command_history_dialog.inl @@ -4,36 +4,6 @@ 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(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(ownerClient?focusPanel:nullptr),0) - && ownerClient) return 1; - } - } - } - return CallNextHookEx(nullptr,code,message,data); -} std::wstring historyLower(std::wstring value) { @@ -136,9 +106,15 @@ LRESULT CALLBACK historySearchKeys(HWND search,UINT message,WPARAM key,LPARAM fl 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; + if(key==VK_TAB || key==VK_ESCAPE) return code&~DLGC_WANTALLKEYS; + if(key==VK_RETURN) return code|DLGC_WANTMESSAGE; return code|DLGC_WANTARROWS; } + if(message==WM_KEYDOWN && key==VK_RETURN) + { + SendMessageW(GetParent(search),WM_COMMAND,IDOK,0); + return 0; + } if(message==WM_KEYDOWN && (key==VK_UP || key==VK_DOWN)) { const auto list=GetDlgItem(GetParent(search),historyList); @@ -157,6 +133,13 @@ int historyRowInset(UINT dpi) LRESULT CALLBACK historyListScroll(HWND list,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) { + if(message==WM_GETDLGCODE && wp==VK_RETURN) + return DefSubclassProc(list,message,wp,lp)|DLGC_WANTMESSAGE; + if(message==WM_KEYDOWN && wp==VK_RETURN) + { + SendMessageW(GetParent(list),WM_COMMAND,IDOK,0); + return 0; + } if(message==LB_GETTOPINDEX || message==WM_NCDESTROY) return DefSubclassProc(list,message,wp,lp); const auto top=SendMessageW(list,LB_GETTOPINDEX,0,0); @@ -166,7 +149,7 @@ LRESULT CALLBACK historyListScroll(HWND list,UINT message,WPARAM wp,LPARAM lp,UI return result; } -void sizeCommandHistory(HWND dialog,HWND list,bool movingOwner=false) +void sizeCommandHistory(HWND dialog,HWND list) { const auto owner=GetWindow(dialog,GW_OWNER); RECT ownerBounds{}; @@ -207,14 +190,6 @@ void sizeCommandHistory(HWND dialog,HWND list,bool movingOwner=false) 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) { @@ -228,18 +203,21 @@ void sizeCommandHistory(HWND dialog,HWND list,bool movingOwner=false) GetClientRect(list,&listClient); if(rows*textHeight<=listClient.bottom) SendMessageW(list,LB_SETTOPINDEX,0,0); InvalidateRect(dialog,nullptr,FALSE); + FilesModalDialog::refreshLayout(dialog); } -void layoutOpenCommandHistory(bool movingOwner=false) +void layoutOpenCommandHistory() { if(commandHistoryWindow) - sizeCommandHistory(commandHistoryWindow,GetDlgItem(commandHistoryWindow,historyList),movingOwner); + sizeCommandHistory(commandHistoryWindow,GetDlgItem(commandHistoryWindow,historyList)); } INT_PTR CALLBACK commandHistoryDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) { if(message==WM_INITDIALOG) { + commandHistoryWindow=dialog; + SetWindowLongPtrW(dialog,DWLP_USER,lp); prepareCopyDialog(dialog); const auto list=GetDlgItem(dialog,historyList); SetWindowSubclass(list,historyListScroll,1,0); @@ -260,11 +238,7 @@ INT_PTR CALLBACK commandHistoryDialog(HWND dialog,UINT message,WPARAM wp,LPARAM 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(wp); @@ -320,14 +294,7 @@ INT_PTR CALLBACK commandHistoryDialog(HWND dialog,UINT message,WPARAM wp,LPARAM } 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(wp):panels[active].list; - DestroyWindow(dialog); - if(focusPanel && IsWindow(owner) && !IsIconic(owner)) - { - SetActiveWindow(owner); - SetFocus(focusPanel); - } + FilesModalDialog::finish(dialog,IDCANCEL); return TRUE; } if(message==WM_COMMAND && (LOWORD(wp)==IDOK || (LOWORD(wp)==historyList && HIWORD(wp)==LBN_DBLCLK))) @@ -336,10 +303,9 @@ INT_PTR CALLBACK commandHistoryDialog(HWND dialog,UINT message,WPARAM wp,LPARAM const auto index=SendDlgItemMessageW(dialog,historyList,LB_GETITEMDATA,row,0); if(index>=0 && static_cast(index)(index)); + auto &choice=*reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + choice=static_cast(index); + FilesModalDialog::finish(dialog,IDOK); } return TRUE; } @@ -354,12 +320,9 @@ void refreshCommandHistory() 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)); + if(commandHistoryWindow) return; + size_t choice{}; + if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(111),owner,commandHistoryDialog, + reinterpret_cast(&choice))==IDOK) + recallCommand(choice); } diff --git a/src/files_dialog_input.inl b/src/files_dialog_input.inl index 5dce923..aa22e72 100644 --- a/src/files_dialog_input.inl +++ b/src/files_dialog_input.inl @@ -7,122 +7,311 @@ bool filesMouseDown(UINT message) message==WM_MBUTTONDOWN || message==WM_XBUTTONDOWN; } +bool handleFilesDialogClick(HWND dialog,HWND clicked,POINT point) +{ + if(!clicked || clicked==dialog || IsChild(dialog,clicked) || + GetAncestor(clicked,GA_ROOTOWNER)!=GetAncestor(dialog,GA_ROOTOWNER)) + return false; + + wchar_t windowClass[16]{}; + if(GetClassNameW(clicked,windowClass,16) && std::wstring_view(windowClass)==L"#32768") + { + GUITHREADINFO thread{sizeof(thread)}; + if(GetGUIThreadInfo(GetWindowThreadProcessId(dialog,nullptr),&thread) && + (thread.hwndMenuOwner==dialog || IsChild(dialog,thread.hwndMenuOwner))) + return false; + } + // System pickers and dropdowns owned by this dialog handle their own input. + for(auto popup=GetAncestor(clicked,GA_ROOT);popup;popup=GetWindow(popup,GW_OWNER)) + if(popup==dialog || IsChild(dialog,popup)) return false; + for(auto owner=GetWindow(dialog,GW_OWNER);owner;owner=GetWindow(owner,GW_OWNER)) + { + if(clicked!=owner) continue; + RECT client{}; + GetClientRect(owner,&client); + ScreenToClient(owner,&point); + if(!PtInRect(&client,point)) return false; + break; + } + if(const auto dropdown=static_cast(GetPropW(dialog,ks::files::farDropDownProperty))) + return PostMessageW(dropdown,WM_CLOSE,0,0)!=FALSE; + return PostMessageW(dialog,WM_COMMAND,IDCANCEL,0)!=FALSE; +} + LRESULT CALLBACK filesDialogMouse(int code,WPARAM message,LPARAM data) { const auto dialog=activeFilesDialog; if(code==HC_ACTION && dialog && IsWindowVisible(dialog) && filesMouseDown(static_cast(message))) { const auto point=reinterpret_cast(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; - } - } + if(handleFilesDialogClick(dialog,WindowFromPoint(point),point)) return 1; } return CallNextHookEx(nullptr,code,message,data); } -struct FilesDialogInput +class FilesModalDialog { - HWND previous=activeFilesDialog; - explicit FilesDialogInput(HWND dialog) +public: + FilesModalDialog(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument) + : owner_(owner),focus_(GetFocus()),procedure_(procedure),argument_(argument) { - activeFilesDialog=dialog; - if(!filesDialogMouseHook) - filesDialogMouseHook=SetWindowsHookExW(WH_MOUSE_LL,filesDialogMouse,GetModuleHandleW(nullptr),0); + window_=CreateDialogParamW(instance,resource,owner,dispatchDialog,reinterpret_cast(this)); } - ~FilesDialogInput() + ~FilesModalDialog() { close(); } + FilesModalDialog(const FilesModalDialog &)=delete; + FilesModalDialog &operator=(const FilesModalDialog &)=delete; + + HWND window() const { return window_; } + + static void fitWidthToOwner(HWND dialog,int minimum,void (*layout)(HWND)) { - activeFilesDialog=previous; - if(!previous && filesDialogMouseHook) + auto *state=reinterpret_cast(GetPropW(dialog,stateProperty_)); + RECT bounds{}; + if(!state || !GetWindowRect(dialog,&bounds)) return; + state->preferredWidth_=bounds.right-bounds.left; + state->minimumWidth_=minimum; + state->layout_=layout; + } + + static void refreshLayout(HWND dialog) + { + auto *state=reinterpret_cast(GetPropW(dialog,stateProperty_)); + if(!state || !state->entered_ || state->layout_) return; + state->captureLayout(); + state->fitWidth(dialog,state->ownerBounds_); + } + + static bool dismissOwned(HWND owner) + { + for(auto parent=GetWindow(activeFilesDialog,GW_OWNER);parent;parent=GetWindow(parent,GW_OWNER)) + if(parent==owner) return PostMessageW(activeFilesDialog,WM_CLOSE,0,0)!=FALSE; + return false; + } + + void show() + { + if(!window_ || entered_) return; + previous_=activeFilesDialog; + activeFilesDialog=window_; + entered_=true; + if(!filesDialogMouseHook) + filesDialogMouseHook=SetWindowsHookExW(WH_MOUSE_LL,filesDialogMouse,GetModuleHandleW(nullptr),0); + if(GetWindowRect(owner_,&ownerBounds_)) + { + if(!layout_) captureLayout(); + SetWindowSubclass(owner_,trackOwner,reinterpret_cast(this),reinterpret_cast(this)); + if(ownerBounds_.right-ownerBounds_.left(this)); + if(window_ && IsWindow(window_)) DestroyWindow(window_); + window_=nullptr; + if(!entered_) return; + entered_=false; + 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(GetPropW(dialog,filesDialogResultProperty)); - if(message==WM_INITDIALOG) - { - result=reinterpret_cast(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(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(&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(IsWindow(owner_) && !IsIconic(GetAncestor(owner_,GA_ROOTOWNER))) { - if(status==0) PostQuitMessage(static_cast(message.wParam)); - break; + SetActiveWindow(owner_); + if(IsWindow(focus_) && IsWindowEnabled(focus_) && (focus_==owner_ || IsChild(owner_,focus_))) + SetFocus(focus_); } - 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; -} + + static bool handleMessage(HWND dialog,MSG &message) + { + if(message.hwnd==dialog || IsChild(dialog,message.hwnd)) + { + if(message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE) + { + SendMessageW(dialog,WM_COMMAND,IDCANCEL,0); + return true; + } + return IsDialogMessageW(dialog,&message)!=FALSE; + } + 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 && (filesMouseDown(message.message) || + (message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE))) + PostMessageW(dialog,WM_COMMAND,IDCANCEL,0); + return input; + } + + static void finish(HWND dialog,INT_PTR answer) + { + auto *state=reinterpret_cast(GetPropW(dialog,stateProperty_)); + if(!state) return; + state->result_=answer; + state->finished_=true; + ShowWindow(dialog,SW_HIDE); + } + + static INT_PTR run(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument) + { + FilesModalDialog dialog(instance,resource,owner,procedure,argument); + if(!dialog.window()) return -1; + dialog.show(); + MSG message{}; + while(!dialog.finished_ && IsWindow(dialog.window())) + { + const auto status=GetMessageW(&message,nullptr,0,0); + if(status<=0) + { + if(status==0) PostQuitMessage(static_cast(message.wParam)); + break; + } + if(handleMessage(dialog.window(),message)) continue; + TranslateMessage(&message); + DispatchMessageW(&message); + } + return dialog.result_; + } + +private: + static constexpr wchar_t stateProperty_[]=L"KSwitcher.Files.ModalDialog"; + HWND window_{},owner_{},focus_{},previous_{}; + RECT ownerBounds_{}; + int preferredWidth_{},minimumWidth_{}; + std::vector> controls_; + void (*layout_)(HWND){}; + DLGPROC procedure_; + LPARAM argument_; + INT_PTR result_=IDCANCEL; + bool entered_{},finished_{}; + + void captureLayout() + { + RECT bounds{}; + GetWindowRect(window_,&bounds); + preferredWidth_=bounds.right-bounds.left; + minimumWidth_=MulDiv(preferredWidth_,3,4); + controls_.clear(); + if(GetWindowLongPtrW(window_,GWL_STYLE)&WS_THICKFRAME) + { + MINMAXINFO limits{}; + SendMessageW(window_,WM_GETMINMAXINFO,0,reinterpret_cast(&limits)); + minimumWidth_=std::max(minimumWidth_,limits.ptMinTrackSize.x); + return; + } + const auto dc=GetDC(window_); + if(!dc) return; + for(auto field=GetWindow(window_,GW_CHILD);field;field=GetWindow(field,GW_HWNDNEXT)) + { + RECT rect{}; + GetWindowRect(field,&rect); + MapWindowPoints(nullptr,window_,reinterpret_cast(&rect),2); + wchar_t type[16]{},label[128]{}; + GetClassNameW(field,type,16); + RECT dropdown{}; + if(lstrcmpiW(type,L"ComboBox")==0 && + SendMessageW(field,CB_GETDROPPEDCONTROLRECT,0,reinterpret_cast(&dropdown))) + rect.bottom=rect.top+dropdown.bottom-dropdown.top; + controls_.emplace_back(field,rect); + const auto fieldWidth=rect.right-rect.left; + if(!(GetWindowLongPtrW(field,GWL_STYLE)&WS_VISIBLE) || fieldWidth<=0) continue; + if(lstrcmpiW(type,L"Button")!=0 || !GetWindowTextW(field,label,128)) continue; + const auto font=reinterpret_cast(SendMessageW(field,WM_GETFONT,0,0)); + const auto previous=font?SelectObject(dc,font):nullptr; + RECT text{}; + DrawTextW(dc,label,-1,&text,DT_SINGLELINE|DT_CALCRECT); + TEXTMETRICW metrics{}; + GetTextMetricsW(dc,&metrics); + if(previous) SelectObject(dc,previous); + const auto needed=std::min(fieldWidth,text.right+4*metrics.tmAveCharWidth); + minimumWidth_=std::max(minimumWidth_,static_cast( + (preferredWidth_*needed+fieldWidth-1)/fieldWidth)); + } + ReleaseDC(window_,dc); + } + + int ownerMargin() const { return MulDiv(12,GetDpiForWindow(owner_),96); } + int minimumOwnerWidth() const { return minimumWidth_+2*ownerMargin(); } + + void fitWidth(HWND window,const RECT &owner,bool initial=false) + { + RECT bounds{}; + if(!GetWindowRect(window,&bounds)) return; + const int width=std::clamp(static_cast(owner.right-owner.left)-2*ownerMargin(), + minimumWidth_,std::max(minimumWidth_,preferredWidth_)); + const int height=bounds.bottom-bounds.top; + const int x=(owner.left+owner.right-width)/2; + const int y=(owner.top+owner.bottom-height)/2; + const bool resized=width!=bounds.right-bounds.left; + if(x!=bounds.left || y!=bounds.top || resized) + SetWindowPos(window,nullptr,x,y,width,height,SWP_NOZORDER|SWP_NOACTIVATE| + (resized?SWP_NOCOPYBITS:0)); + if(layout_ && (initial || resized)) layout_(window); + else if(resized && preferredWidth_>0) + for(const auto &[field,rect]:controls_) + { + const auto left=MulDiv(rect.left,width,preferredWidth_); + const auto right=MulDiv(rect.right,width,preferredWidth_); + SetWindowPos(field,nullptr,left,rect.top,right-left,rect.bottom-rect.top, + SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS); + } + if(initial || resized) RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN); + } + + static LRESULT CALLBACK trackOwner(HWND owner,UINT message,WPARAM wp,LPARAM lp,UINT_PTR id,DWORD_PTR data) + { + auto &dialog=*reinterpret_cast(data); + if(message==WM_WINDOWPOSCHANGING && !IsIconic(owner)) + { + auto &position=*reinterpret_cast(lp); + if(!(position.flags&SWP_NOSIZE) && position.cx>0) + position.cx=std::max(position.cx,dialog.minimumOwnerWidth()); + } + if(message==WM_NCDESTROY) RemoveWindowSubclass(owner,trackOwner,id); + const auto result=DefSubclassProc(owner,message,wp,lp); + if(message==WM_GETMINMAXINFO) + { + auto &limits=*reinterpret_cast(lp); + limits.ptMinTrackSize.x=std::max(limits.ptMinTrackSize.x,dialog.minimumOwnerWidth()); + return result; + } + if((message!=WM_MOVE && message!=WM_SIZE) || IsIconic(owner)) return result; + RECT ownerBounds{}; + if(!GetWindowRect(owner,&ownerBounds)) return result; + if(EqualRect(&ownerBounds,&dialog.ownerBounds_)) return result; + dialog.ownerBounds_=ownerBounds; + dialog.fitWidth(dialog.window_,ownerBounds); + return result; + } + + static INT_PTR CALLBACK dispatchDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) + { + auto *state=reinterpret_cast(GetPropW(dialog,stateProperty_)); + if(message==WM_INITDIALOG) + { + state=reinterpret_cast(lp); + if(!SetPropW(dialog,stateProperty_,state)) return FALSE; + lp=state->argument_; + } + if(!state) return FALSE; + const auto handled=state->procedure_(dialog,message,wp,lp); + if(message==WM_NCDESTROY) RemovePropW(dialog,stateProperty_); + if(!handled && message==WM_CLOSE) + { + SendMessageW(dialog,WM_COMMAND,IDCANCEL,0); + return TRUE; + } + return handled; + } +}; diff --git a/src/files_dropdown_paint.h b/src/files_dropdown_paint.h new file mode 100644 index 0000000..0377d44 --- /dev/null +++ b/src/files_dropdown_paint.h @@ -0,0 +1,35 @@ +#pragma once + +#include +#include + +namespace ks::files +{ +inline void paintFarDropDownArrow(HDC dc, const RECT &bounds, HBRUSH surface, COLORREF ink, UINT dpi) +{ + FillRect(dc, &bounds, surface); + // Center the drawn pixels. A font's arrow glyph can sit below the center of its line box. + const auto halfWidth = std::min((bounds.right - bounds.left - 1) / 2, + static_cast(MulDiv(3, dpi, 96))); + const auto halfHeight = std::min((bounds.bottom - bounds.top - 1) / 2, + static_cast(MulDiv(5, dpi, 96))); + if (halfWidth < 1 || halfHeight < 1) return; + const auto x = (bounds.left + bounds.right - 1) / 2; + const auto y = (bounds.top + bounds.bottom - 1) / 2; + const auto tip = y + halfHeight; + const auto head = std::min(halfWidth, halfHeight); + for (LONG row = y - halfHeight; row <= tip; ++row) + SetPixelV(dc, x, row, ink); + for (LONG offset = 1; offset <= head; ++offset) + { + SetPixelV(dc, x - offset, tip - offset, ink); + SetPixelV(dc, x + offset, tip - offset, ink); + } +} + +inline void paintFarFieldArrow(HDC dc, const RECT &bounds, bool enabled, UINT dpi) +{ + paintFarDropDownArrow(dc, bounds, static_cast(GetStockObject(LTGRAY_BRUSH)), + enabled ? RGB(0,0,0) : RGB(48,48,48), dpi); +} +} diff --git a/src/files_folder_shortcuts.inl b/src/files_folder_shortcuts.inl index 2f8718b..4d970ad 100644 --- a/src/files_folder_shortcuts.inl +++ b/src/files_folder_shortcuts.inl @@ -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)) { - finishFilesDialog(dialog,IDCANCEL); + FilesModalDialog::finish(dialog,IDCANCEL); return TRUE; } if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE; @@ -116,7 +116,7 @@ INT_PTR CALLBACK folderShortcutEditDialog(HWND dialog,UINT message,WPARAM wp,LPA ((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); + showFilesNotice(dialog,L"Enter an absolute folder path on the original computer.",L"Folder shortcuts"); SetFocus(GetDlgItem(dialog,shortcutPath)); return TRUE; } @@ -127,7 +127,7 @@ INT_PTR CALLBACK folderShortcutEditDialog(HWND dialog,UINT message,WPARAM wp,LPA for(size_t i=0;i(&edit))==IDOK; } @@ -270,6 +270,7 @@ void layoutQuickFolders(HWND dialog,FolderShortcutView &view,int selection) 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); + FilesModalDialog::refreshLayout(dialog); } LRESULT CALLBACK quickFolderKeys(HWND list,UINT message,WPARAM key,LPARAM flags,UINT_PTR,DWORD_PTR) @@ -340,7 +341,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) } if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL)) { - finishFilesDialog(dialog,IDCANCEL); + FilesModalDialog::finish(dialog,IDCANCEL); return TRUE; } if(message!=WM_COMMAND) return FALSE; @@ -386,7 +387,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) 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); + showFilesNotice(dialog,L"Could not save folder shortcuts.",L"Folder shortcuts"); else { folderShortcuts=std::move(updated); @@ -408,17 +409,17 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) 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); + showFilesNotice(dialog,L"Could not save folder shortcuts.",L"Folder shortcuts"); return TRUE; } folderShortcuts=std::move(updated); notifyFilesPreferences(GetAncestor(dialog,GA_ROOTOWNER)); - if(view->all?view->entries.size()==1:folderShortcuts[digit].empty()) finishFilesDialog(dialog,IDCANCEL); + if(view->all?view->entries.size()==1:folderShortcuts[digit].empty()) FilesModalDialog::finish(dialog,IDCANCEL); else layoutQuickFolders(dialog,*view,static_cast(row)); return TRUE; } view->chosen=group[index]; - finishFilesDialog(dialog,IDOK); + FilesModalDialog::finish(dialog,IDOK); return TRUE; } @@ -447,7 +448,7 @@ void showFolderShortcuts(Panel &panel,int digit,bool all) FolderShortcutView view{digit}; view.panel=&panel; view.all=all; - const auto result=runFilesDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(109),GetParent(panel.list), + const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(109),GetParent(panel.list), quickFolderDialog,reinterpret_cast(&view)); SetFocus(panel.list); if(result==IDOK && view.chosen) openFolderShortcut(panel,*view.chosen); diff --git a/src/files_history_date.h b/src/files_history_date.h new file mode 100644 index 0000000..3c6d55d --- /dev/null +++ b/src/files_history_date.h @@ -0,0 +1,16 @@ +#pragma once + +#include +#include + +namespace ks::files +{ +inline std::wstring historyDate() +{ + SYSTEMTIME now{}; + GetLocalTime(&now); + wchar_t date[24]{}; + GetDateFormatEx(LOCALE_NAME_USER_DEFAULT,0,&now,L"dd.MM.yyyy",date,24,nullptr); + return date; +} +} diff --git a/src/files_main.cpp b/src/files_main.cpp index 787119b..427cce6 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -19,6 +19,11 @@ #include #include #include "files_terminal.h" +#include "files_text_window.h" +#include "files_text_preferences.h" +#include "files_menu_paint.h" +#include "files_dropdown_paint.h" +#include "files_history_date.h" #include "files_terminal_view.h" #include "files_lan_ipc.h" #include "lan_files.h" @@ -298,7 +303,7 @@ std::vector terminalHistory; size_t terminalHistoryIndex{}; constexpr UINT_PTR transferHighlightTimer=1; unsigned transferHighlightPhase{}; -HWND status{}, commands[6]{}; +HWND status{}, commands[7]{}; int active{}, split{}; bool dragging{}; bool rememberElevationApproval{}; @@ -377,6 +382,8 @@ void savePlacement(HWND window) &placement,sizeof(placement)); } void chooseDrive(int index, bool fromMenu = false); +INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,bool confirm=false, + bool *remember=nullptr,bool warning=false); void openMenu(HWND window, int index); void showFileDetails(const Panel &panel); void editOptions(HWND owner); @@ -457,6 +464,17 @@ LOGFONTW defaultFilesFont() return font; } +ks::files::TextWindowFont readFilesFont() +{ + LOGFONTW font{}; + DWORD bytes=sizeof(font); + if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,L"DisplayFont",RRF_RT_REG_BINARY,nullptr,&font,&bytes) + !=ERROR_SUCCESS || bytes!=sizeof(font)) + font=defaultFilesFont(); + font.lfFaceName[LF_FACESIZE-1]=0; + return {font,static_cast(std::clamp(preference(L"FontPoints",defaultFontPoints),80UL,240UL))}; +} + std::array fileStyleFonts{}; bool applyFont(HWND owner, LOGFONTW font, int points) @@ -571,13 +589,7 @@ void paintText(HDC dc, RECT rect, const wchar_t *text, COLORREF foreground, COLO void paintMenuLabel(HDC dc,RECT rect,const std::wstring &text,size_t access,COLORREF foreground,COLORREF background) { paintText(dc,rect,text.c_str(),foreground,background); - if(access>=text.size()) return; - SIZE prefix{}; - GetTextExtentPoint32W(dc,text.c_str(),static_cast(access),&prefix); - const auto mode=SetBkMode(dc,TRANSPARENT); - SetTextColor(dc,RGB(255,255,0)); - ExtTextOutW(dc,rect.left+5+prefix.cx,rect.top+3,ETO_CLIPPED,&rect,text.c_str()+access,1,nullptr); - SetBkMode(dc,mode); + ks::files::paintMenuAccessKey(dc,rect,{rect.left+5,rect.top+3},text,access,RGB(255,255,0)); } struct DialogFramePadding @@ -1174,24 +1186,11 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti { auto owner=GetParent(panel.list); auto path=directory.wstring(); - const TASKDIALOG_BUTTON buttons[]{{IDYES,L"Continue as administrator"},{IDCANCEL,L"Skip"}}; - TASKDIALOGCONFIG dialog{}; - dialog.cbSize=sizeof(dialog); - dialog.hwndParent=owner; - dialog.dwFlags=TDF_ALLOW_DIALOG_CANCELLATION|TDF_POSITION_RELATIVE_TO_WINDOW; - dialog.pszWindowTitle=L"KSwitcher Files"; - dialog.pszMainInstruction=L"Windows denied access to this folder"; - dialog.pszContent=path.c_str(); - dialog.pszVerificationText=L"Remember Continue for this session (Windows may still ask for UAC)"; - dialog.cButtons=static_cast(std::size(buttons)); - dialog.pButtons=buttons; - dialog.nDefaultButton=IDCANCEL; - BOOL skip{}; - int choice=IDYES; - if(!rememberElevationApproval && FAILED(TaskDialogIndirect(&dialog,&choice,nullptr,&skip))) - choice=MessageBoxW(owner,(path+L"\n\nTry opening as administrator?").c_str(), - L"KSwitcher Files",MB_YESNO|MB_DEFBUTTON2|MB_ICONQUESTION); - if(choice==IDYES) + bool remember=false; + const auto question=L"Windows denied access to this folder.\r\n"+path+ + L"\r\n\r\nTry opening as administrator? Windows may still ask for UAC."; + if(rememberElevationApproval || showFilesNotice(owner,question.c_str(), + L"KSwitcher Files",true,&remember)==IDYES) { const auto result=requestElevatedFolder(owner,directory,folders,files,metadata); SetForegroundWindow(owner); @@ -1202,7 +1201,7 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti L"Could not read folder as administrator ("+std::to_wstring(result)+L"): "+path); return; } - rememberElevationApproval=rememberElevationApproval || skip!=FALSE; + rememberElevationApproval=rememberElevationApproval || remember; error=ERROR_SUCCESS; } } @@ -1299,6 +1298,15 @@ void open(Panel &panel,const fs::path &directory,bool offerElevation=false) openOn(panel,directory,offerElevation,panel.peer); } +void selectPanelPath(Panel &panel,const fs::path &path) +{ + const auto row=std::find(panel.rows.begin(),panel.rows.end(),path); + if(row==panel.rows.end()) return; + SendMessageW(panel.list,LB_SETCURSEL,row-panel.rows.begin(),0); + InvalidateRect(panel.list,nullptr,FALSE); + showFileDetails(panel); +} + void refreshChangedPanels() { for(auto &panel:panels) @@ -1312,6 +1320,16 @@ void refreshChangedPanels() } } +void openSelectedText(const Panel &panel, bool edit, bool external); +INT_PTR confirmTextSave(HWND owner); +INT_PTR paintTextDialog(HWND window, UINT message, WPARAM wp, LPARAM lp, const wchar_t *caption); +INT_PTR paintSearchDialog(HWND window,UINT message,WPARAM wp,LPARAM lp); +ks::files::FarDropDownPalette farDropDownPalette(); +void prepareCopyDialog(HWND dialog); +void prepareTextDialog(HWND dialog); +void showTextMessage(HWND owner,const wchar_t *text); +void editTextOptions(HWND owner,bool edit); + void selectDrive() { auto row=SendMessageW(picker,LB_GETCURSEL,0,0); @@ -1333,6 +1351,7 @@ void selectDrive() else setMode(index,row==1); } else if(menuIndex==2 && row==3) showFolderShortcuts(panels[active],-1); + else if(menuIndex==2 && (row==4 || row==5)) openSelectedText(panels[active],row==5,true); else { const int command=menuIndex==1?113+static_cast(row):110+static_cast(row); @@ -1693,6 +1712,26 @@ void openPanelFile(const Panel &panel, const fs::path &file, const wchar_t *verb setStatus(failureMessage); } +#include "files_dialog_input.inl" + +void openSelectedText(const Panel &panel, bool edit, bool external) +{ + const auto row=currentPanelRow(panel); + if(row==LB_ERR || panel.sizes[row]==L"Folder" || panel.sizes[row]==L"Up") return; + if(panel.peer) + { + setStatus(L"Copy the remote file to a local panel before opening it."); + return; + } + const auto &path=panel.rows[row]; + if(external) + openPanelFile(panel,path,edit?L"edit":L"open", + edit?L"No editor is registered for this file.":L"Cannot open the selected file."); + else ks::files::openTextWindow(GetParent(panel.list),path,edit, + {confirmTextSave,paintTextDialog,paintSearchDialog,prepareTextDialog,editTextOptions,showTextMessage,readFilesFont, + farDropDownPalette,FilesModalDialog::run,FilesModalDialog::finish,FilesModalDialog::dismissOwned}); +} + void enter(Panel &panel) { const auto row=currentPanelRow(panel); @@ -1731,9 +1770,6 @@ bool directoryExists(const FilesPeer *peer,const fs::path &path) } HBRUSH warningBrush{}; -RECT previousOwnerBounds{}; - -#include "files_dialog_input.inl" LRESULT CALLBACK dialogButtonEnter(HWND button,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR); @@ -1749,11 +1785,14 @@ void installDialogButtonKeys(HWND dialog) },0); } +constexpr wchar_t farEditClass[]=L"KSwitcher.Files.FarEdit"; +WNDPROC nativeEditProcedure{}; + bool isDialogEdit(HWND control) { - wchar_t name[16]{}; + wchar_t name[32]{}; GetClassNameW(control,name,static_cast(std::size(name))); - return lstrcmpiW(name,L"Edit")==0; + return lstrcmpiW(name,L"Edit")==0 || lstrcmpiW(name,farEditClass)==0; } void centerDialogEditText(HWND field) @@ -1762,7 +1801,7 @@ void centerDialogEditText(HWND field) GetClientRect(field,&edit); if(const auto dc=GetDC(field)) { - const auto oldFont=SelectObject(dc,mono); + const auto oldFont=SelectObject(dc,reinterpret_cast(SendMessageW(field,WM_GETFONT,0,0))); TEXTMETRICW metrics{}; if(GetTextMetricsW(dc,&metrics)) edit.top=std::max(0L,(edit.bottom-metrics.tmHeight)/2); @@ -1772,23 +1811,76 @@ void centerDialogEditText(HWND field) SendMessageW(field,EM_SETRECTNP,0,reinterpret_cast(&edit)); } -LRESULT CALLBACK dialogEditLayout(HWND field,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) +LRESULT CALLBACK farEditProcedure(HWND field,UINT message,WPARAM wp,LPARAM lp) { - const auto result=DefSubclassProc(field,message,wp,lp); + if(message==WM_CHAR && (wp==L'\r' || wp==L'\n')) return 0; + if(message==WM_PASTE && !(GetWindowLongPtrW(field,GWL_STYLE)&ES_READONLY) && OpenClipboard(field)) + { + std::wstring line; + bool multiline=false; + if(const auto handle=GetClipboardData(CF_UNICODETEXT)) + if(const auto data=static_cast(GlobalLock(handle))) + { + const auto end=data+GlobalSize(handle)/sizeof(wchar_t); + const auto stop=std::find_if(data,end,[](wchar_t c){return c==0 || c==L'\r' || c==L'\n';}); + multiline=stop!=end && *stop!=0; + if(multiline) line.assign(data,stop); + GlobalUnlock(handle); + } + CloseClipboard(); + if(multiline) + { + if(!line.empty()) SendMessageW(field,EM_REPLACESEL,TRUE,reinterpret_cast(line.c_str())); + return 0; + } + } + const auto result=CallWindowProcW(nativeEditProcedure,field,message,wp,lp); if(message==WM_SIZE || message==WM_SETFONT) centerDialogEditText(field); + if(message==WM_GETDLGCODE && lp) + { + const auto key=reinterpret_cast(lp)->wParam; + if(key==VK_RETURN || key==VK_TAB || key==VK_ESCAPE) return result&~DLGC_WANTALLKEYS; + } return result; } +bool registerFarEdit(HINSTANCE instance) +{ + WNDCLASSEXW type{sizeof(type)}; + if(!GetClassInfoExW(nullptr,L"Edit",&type)) return false; + nativeEditProcedure=type.lpfnWndProc; + type.hInstance=instance; + type.lpszClassName=farEditClass; + type.lpfnWndProc=farEditProcedure; + return RegisterClassExW(&type)!=0; +} + void prepareDialogEdit(HWND field) { SendMessageW(field,WM_SETFONT,reinterpret_cast(mono),FALSE); const auto margin=MulDiv(2,GetDpiForWindow(field),96); SendMessageW(field,EM_SETMARGINS,EC_LEFTMARGIN|EC_RIGHTMARGIN,MAKELPARAM(margin,margin)); - if(GetWindowLongPtrW(field,GWL_STYLE)&ES_MULTILINE) - { - SetWindowSubclass(field,dialogEditLayout,1,0); - centerDialogEditText(field); - } +} + +void fitFarEditToLine(HWND field) +{ + TEXTMETRICW metrics{}; + const auto dc=GetDC(field); + if(!dc) return; + const auto font=reinterpret_cast(SendMessageW(field,WM_GETFONT,0,0)); + const auto previous=SelectObject(dc,font); + const bool measured=GetTextMetricsW(dc,&metrics)!=FALSE; + SelectObject(dc,previous); + ReleaseDC(field,dc); + if(!measured) return; + + const auto parent=GetParent(field); + RECT cell{}; + GetWindowRect(field,&cell); + MapWindowPoints(nullptr,parent,reinterpret_cast(&cell),2); + const auto height=std::max(metrics.tmHeight,1L); + SetWindowPos(field,nullptr,cell.left,cell.top+(cell.bottom-cell.top-height)/2, + cell.right-cell.left,height,SWP_NOZORDER|SWP_NOACTIVATE); } void prepareCopyDialog(HWND dialog) @@ -1846,13 +1938,15 @@ int dialogFooterInset(HWND dialog) LONG dialogDividerY(HWND dialog,int id) { const auto bounds=dialogControlBounds(dialog,id); + if(id==ks::files::searchOptionsDivider || id==ks::files::searchButtonsDivider) + return bounds.top; if(id==214) { const auto combo=dialogControlBounds(dialog,213); - const auto validation=dialogControlBounds(dialog,328); - return bounds.bottom+std::max(0L,(combo.top-validation.bottom-1)/2); + const auto path=dialogControlBounds(dialog,211); + return bounds.bottom+std::max(0L,(combo.top-path.bottom-1)/2); } - if(id==213) return (dialogControlBounds(dialog,328).bottom+bounds.top-1)/2; + if(id==213) return (dialogControlBounds(dialog,211).bottom+bounds.top-1)/2; return bounds.top-4; } @@ -1870,6 +1964,43 @@ void centerDialogRow(HWND dialog,int upperDivider,int lowerDivider,std::initiali } } +int dialogColumnGap() { return std::max(2,cellWidth/2); } +int dialogRowGap() { return std::max(2,textHeight/5); } + +LONG farDialogButtonWidth(HWND button) +{ + wchar_t label[32]{}; + const auto length=GetWindowTextW(button,label,static_cast(std::size(label))); + const auto characters=length-(wcschr(label,L'&')!=nullptr?1:0); + return (characters+5)*cellWidth; +} + +void groupDialogButtons(HWND dialog,std::initializer_list controls,bool native=false) +{ + RECT client{}; + GetClientRect(dialog,&client); + const auto gap=dialogColumnGap(); + const auto width=[&](int id) + { + if(!native) return farDialogButtonWidth(GetDlgItem(dialog,id)); + const auto bounds=dialogControlBounds(dialog,id); + return bounds.right-bounds.left; + }; + LONG rowWidth=-gap; + for(const auto id:controls) rowWidth+=width(id)+gap; + if(rowWidth>client.right) return; + auto x=native?dialogControlBounds(dialog,*(controls.end()-1)).right-rowWidth: + (client.right-rowWidth)/2; + for(const auto id:controls) + { + const auto bounds=dialogControlBounds(dialog,id); + const auto buttonWidth=width(id); + SetWindowPos(GetDlgItem(dialog,id),nullptr,x,bounds.top,buttonWidth,bounds.bottom-bounds.top, + SWP_NOZORDER|SWP_NOACTIVATE); + x+=buttonWidth+gap; + } +} + void layoutDialogButtons(HWND dialog,int divider,std::initializer_list controls) { RECT client{},window{}; @@ -1884,7 +2015,8 @@ void layoutDialogButtons(HWND dialog,int divider,std::initializer_list cont const auto bounds=dialogControlBounds(dialog,id); tallest=std::max(tallest,bounds.bottom-bounds.top); } - const auto footerHeight=std::max(tallest+2,2*static_cast(textHeight)+2*extra); + const auto footerHeight=std::max(tallest,static_cast(textHeight))+ + 2*std::max(dialogRowGap(),dialogRowGap()+extra); const auto height=dialogDividerY(dialog,divider)+1+footerHeight+dialogFooterInset(dialog); const auto width=window.right-window.left; const auto outerHeight=window.bottom-window.top+height-client.bottom; @@ -1893,24 +2025,43 @@ void layoutDialogButtons(HWND dialog,int divider,std::initializer_list cont SetWindowPos(dialog,nullptr,(owner.left+owner.right-width)/2, (owner.top+owner.bottom-outerHeight)/2,width,outerHeight, (centered?0:SWP_NOMOVE)|SWP_NOZORDER|SWP_NOACTIVATE); + groupDialogButtons(dialog,controls); centerDialogRow(dialog,divider,0,controls); } -void paintDialogButton(const DRAWITEMSTRUCT &item,COLORREF surface,COLORREF foreground) +void drawFarDialogLabel(HDC dc,RECT bounds,std::wstring caption,bool centered) +{ + const auto access=caption.find(L'&'); + if(access!=caption.npos) caption.erase(access,1); + SIZE extent{}; + GetTextExtentPoint32W(dc,caption.c_str(),static_cast(caption.size()),&extent); + RECT label=bounds; + if(centered) label.left+=std::max(0L,(bounds.right-bounds.left-extent.cx)/2); + DrawTextW(dc,caption.c_str(),-1,&label,DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX|DT_END_ELLIPSIS); + TEXTMETRICW metrics{}; + GetTextMetricsW(dc,&metrics); + ks::files::paintMenuAccessKey(dc,bounds,{label.left,bounds.top+(bounds.bottom-bounds.top-metrics.tmHeight)/2}, + caption,access,RGB(255,255,0)); +} + +void paintDialogButton(const DRAWITEMSTRUCT &item,COLORREF surface,COLORREF foreground,bool farAccessKeys=false) { wchar_t label[32]{}; GetWindowTextW(item.hwndItem,label,static_cast(std::size(label))); const bool focused=(item.itemState&(ODS_FOCUS|ODS_SELECTED))!=0; - SetDCBrushColor(item.hDC,focused?colors[Dialog]:surface); + const auto focusSurface=surface==RGB(128,0,0)?RGB(0,0,0): + surface==colors[Dialog]?colors[Selection]:colors[Dialog]; + SetDCBrushColor(item.hDC,focused?focusSurface:surface); FillRect(item.hDC,&item.rcItem,static_cast(GetStockObject(DC_BRUSH))); SelectObject(item.hDC,mono); SetBkMode(item.hDC,TRANSPARENT); - SetTextColor(item.hDC,focused?colors[Text]:foreground); + SetTextColor(item.hDC,(item.itemState&ODS_DISABLED)?RGB(128,128,128):focused?colors[Text]:foreground); auto rect=item.rcItem; const auto defaultButton=SendMessageW(GetParent(item.hwndItem),DM_GETDEFID,0,0); const bool isDefault=HIWORD(defaultButton)==DC_HASDEFID && LOWORD(defaultButton)==item.CtlID; const auto caption=(isDefault?L"{ ":L"[ ")+std::wstring(label)+(isDefault?L" }":L" ]"); - DrawTextW(item.hDC,caption.c_str(),-1,&rect,DT_CENTER|DT_VCENTER|DT_SINGLELINE); + if(farAccessKeys && !(item.itemState&ODS_DISABLED)) drawFarDialogLabel(item.hDC,rect,caption,true); + else DrawTextW(item.hDC,caption.c_str(),-1,&rect,DT_CENTER|DT_VCENTER|DT_SINGLELINE); } INT_PTR paintCopyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp, @@ -1921,7 +2072,8 @@ INT_PTR paintCopyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp, const auto surface=useDialogPalette?colors[Dialog]:warning?RGB(128,0,0):RGB(192,192,192); const auto brush=useDialogPalette?teal:warning?warningBrush:static_cast(GetStockObject(LTGRAY_BRUSH)); if(message==WM_CTLCOLORDLG) return reinterpret_cast(brush); - if(message==WM_CTLCOLORSTATIC || message==WM_CTLCOLOREDIT || message==WM_CTLCOLORBTN) + if(message==WM_CTLCOLORSTATIC || message==WM_CTLCOLOREDIT || message==WM_CTLCOLORBTN || + (useDialogPalette && message==WM_CTLCOLORLISTBOX)) { const auto dc=reinterpret_cast(wp); const bool edit=message==WM_CTLCOLOREDIT || @@ -1960,54 +2112,186 @@ INT_PTR paintCopyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp, return FALSE; } -LRESULT CALLBACK paintConflictCombo(HWND control,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) +struct FarDropDownBounds { - if(message!=WM_PAINT) return DefSubclassProc(control,message,wp,lp); + RECT field,arrow; +}; + +ks::files::FarDropDownPalette farDropDownPalette() +{ + return {colors[Dialog],colors[Text],colors[Selection]}; +} + +FarDropDownBounds farDropDownBounds(RECT bounds) +{ + const auto split=std::max(bounds.left,bounds.right-static_cast(cellWidth)); + return {{bounds.left,bounds.top,split,bounds.bottom},{split,bounds.top,bounds.right,bounds.bottom}}; +} + +void paintFarDropDownText(HDC dc,RECT bounds,const wchar_t *text,bool enabled) +{ + FillRect(dc,&bounds,teal); + SelectObject(dc,mono); + SetBkMode(dc,TRANSPARENT); + SetTextColor(dc,enabled?farDropDownPalette().text:RGB(128,128,128)); + bounds.left+=5; + DrawTextW(dc,text,-1,&bounds,DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX|DT_END_ELLIPSIS); +} + +LRESULT CALLBACK paintFarCombo(HWND control,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) +{ + if(message==WM_LBUTTONDOWN || (message==WM_KEYDOWN && wp==VK_F4) || + (message==WM_SYSKEYDOWN && wp==VK_DOWN) || (message==CB_SHOWDROPDOWN && wp)) + { + if(!IsWindowEnabled(control)) return 0; + SetFocus(control); + std::vector entries; + const auto count=SendMessageW(control,CB_GETCOUNT,0,0); + for(LRESULT index=0;index(length)+1,L'\0'); + const auto copied=SendMessageW(control,CB_GETLBTEXT,index,reinterpret_cast(label.data())); + if(copied==CB_ERR) return 0; + label.resize(copied); + entries.push_back({{},std::move(label)}); + } + const auto previous=SendMessageW(control,CB_GETCURSEL,0,0); + const auto selected=ks::files::chooseFarDropDown(control,entries,static_cast(previous), + farDropDownPalette(),cellWidth); + if(selected>=0 && selected!=previous) + { + SendMessageW(control,CB_SETCURSEL,selected,0); + SendMessageW(GetParent(control),WM_COMMAND,MAKEWPARAM(GetDlgCtrlID(control),CBN_SELCHANGE), + reinterpret_cast(control)); + } + InvalidateRect(control,nullptr,FALSE); + return message==CB_SHOWDROPDOWN?TRUE:0; + } + if(message!=WM_PAINT && message!=WM_PRINTCLIENT && message!=WM_PRINT) + return DefSubclassProc(control,message,wp,lp); PAINTSTRUCT paint{}; - const auto dc=BeginPaint(control,&paint); + const auto dc=message==WM_PAINT?BeginPaint(control,&paint):reinterpret_cast(wp); RECT bounds{}; GetClientRect(control,&bounds); wchar_t label[64]{}; const auto selected=SendMessageW(control,CB_GETCURSEL,0,0); if(selected!=CB_ERR) SendMessageW(control,CB_GETLBTEXT,selected,reinterpret_cast(label)); - auto arrow=bounds; - arrow.left=std::max(bounds.left,bounds.right-2*static_cast(cellWidth)); - bounds.right=arrow.left; - SetDCBrushColor(dc,colors[Dialog]); - FillRect(dc,&bounds,static_cast(GetStockObject(DC_BRUSH))); - FillRect(dc,&arrow,static_cast(GetStockObject(DC_BRUSH))); - SelectObject(dc,mono); - SetBkMode(dc,TRANSPARENT); - SetTextColor(dc,colors[Text]); - bounds.left+=5; - DrawTextW(dc,label,-1,&bounds,DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS|DT_NOPREFIX); - DrawTextW(dc,L"↓",-1,&arrow,DT_SINGLELINE|DT_VCENTER|DT_CENTER); - if(GetFocus()==control) DrawFocusRect(dc,&bounds); - EndPaint(control,&paint); + const auto parts=farDropDownBounds(bounds); + const bool enabled=IsWindowEnabled(control)!=FALSE; + paintFarDropDownText(dc,parts.field,label,enabled); + ks::files::paintFarFieldArrow(dc,parts.arrow,enabled,GetDpiForWindow(control)); + if(GetFocus()==control) DrawFocusRect(dc,&parts.field); + if(message==WM_PAINT) EndPaint(control,&paint); return 0; } +void installFarCombo(HWND combo,HWND lineField) +{ + RECT field{},bounds{}; + GetWindowRect(lineField,&field); + GetWindowRect(combo,&bounds); + const LONG line=field.bottom-field.top; + const auto selection=SendMessageW(combo,CB_GETITEMHEIGHT,static_cast(-1),0); + const auto frame=selection==CB_ERR?0L:std::max(0L,bounds.bottom-bounds.top-static_cast(selection)); + SendMessageW(combo,CB_SETITEMHEIGHT,0,line); + SendMessageW(combo,CB_SETITEMHEIGHT,static_cast(-1),std::max(1L,line-frame)); + SetWindowSubclass(combo,paintFarCombo,1,0); +} + +enum class FarCheckboxSurface : DWORD_PTR { gray, dialog, warning }; + +void showFarCheckboxCaret(HWND field) +{ + const auto dc=GetDC(field); + if(!dc) return; + const auto font=reinterpret_cast(SendMessageW(field,WM_GETFONT,0,0)); + const auto previous=SelectObject(dc,font); + TEXTMETRICW metrics{}; + GetTextMetricsW(dc,&metrics); + SIZE bracket{},space{}; + GetTextExtentPoint32W(dc,L"[",1,&bracket); + GetTextExtentPoint32W(dc,L" ",1,&space); + SelectObject(dc,previous); + ReleaseDC(field,dc); + + RECT bounds{}; + GetClientRect(field,&bounds); + const auto width=std::max(1L,space.cx-2); + const auto height=std::max(2L,metrics.tmHeight/6); + const auto y=(bounds.bottom-metrics.tmHeight)/2+metrics.tmAscent+metrics.tmDescent-height; + if(CreateCaret(field,nullptr,width,height)) + { + SetCaretPos(bracket.cx+1,std::max(0L,y)); + ShowCaret(field); + } +} + +LRESULT CALLBACK paintFarCheckbox(HWND field,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR palette) +{ + if(message==WM_ERASEBKGND) return TRUE; + if(message!=WM_PAINT) + { + if(message==WM_KILLFOCUS) DestroyCaret(); + const auto result=DefSubclassProc(field,message,wp,lp); + if(message==WM_SETFOCUS || ((message==WM_SIZE || message==WM_SETFONT) && GetFocus()==field)) + showFarCheckboxCaret(field); + if(message==BM_SETCHECK || message==WM_SETTEXT || message==WM_ENABLE) + InvalidateRect(field,nullptr,FALSE); + return result; + } + PAINTSTRUCT paint{}; + const auto dc=BeginPaint(field,&paint); + RECT bounds{}; + GetClientRect(field,&bounds); + const auto surface=static_cast(palette); + const auto background=surface==FarCheckboxSurface::gray?RGB(192,192,192): + surface==FarCheckboxSurface::warning?RGB(128,0,0):colors[Dialog]; + const auto ink=surface==FarCheckboxSurface::gray?RGB(0,0,0): + surface==FarCheckboxSurface::warning?RGB(255,255,255):colors[Text]; + SetDCBrushColor(dc,background); + FillRect(dc,&bounds,static_cast(GetStockObject(DC_BRUSH))); + SelectObject(dc,reinterpret_cast(SendMessageW(field,WM_GETFONT,0,0))); + SetBkMode(dc,TRANSPARENT); + SetTextColor(dc,IsWindowEnabled(field)?ink:RGB(128,128,128)); + wchar_t label[80]{}; + GetWindowTextW(field,label,static_cast(std::size(label))); + const auto text=(SendMessageW(field,BM_GETCHECK,0,0)==BST_CHECKED?L"[x] ":L"[ ] ")+std::wstring(label); + if(IsWindowEnabled(field)) drawFarDialogLabel(dc,bounds,text,false); + else DrawTextW(dc,text.c_str(),-1,&bounds,DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS); + EndPaint(field,&paint); + return 0; +} + +void installFarCheckbox(HWND field,FarCheckboxSurface surface) +{ + SetWindowSubclass(field,paintFarCheckbox,1,static_cast(surface)); +} + +bool validFileName(std::wstring_view name) +{ + return !name.empty() && name.back()!=L'.' && name.back()!=L' ' && + name.find_first_of(L"<>:\"/\\|?*")==name.npos && + std::none_of(name.begin(),name.end(),[](wchar_t ch){return ch<32;}); +} + +void drawFarComboRow(const DRAWITEMSTRUCT &item) +{ + wchar_t label[64]{}; + if(item.itemID!=UINT(-1)) + SendMessageW(item.hwndItem,CB_GETLBTEXT,item.itemID,reinterpret_cast(label)); + const bool selected=(item.itemState&ODS_SELECTED)!=0 && (item.itemState&ODS_COMBOBOXEDIT)==0; + const auto palette=farDropDownPalette(); + paintText(item.hDC,item.rcItem,label,palette.text,selected?palette.selection:palette.surface); +} + INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp) { constexpr int summary=210, pathField=211, conflicts=212; - if(message==WM_DRAWITEM && wp==214) - { - const auto &item=*reinterpret_cast(lp); - const auto request=reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); - const bool checked=request && request->askReadOnly; - paintText(item.hDC,item.rcItem,checked?L"[x] Also ask on read-only files": - L"[ ] Also ask on read-only files",RGB(0,0,0),RGB(192,192,192)); - if(item.itemState&ODS_FOCUS) DrawFocusRect(item.hDC,&item.rcItem); - return TRUE; - } if(message==WM_DRAWITEM && wp==213) { - const auto &item=*reinterpret_cast(lp); - wchar_t label[64]{}; - if(item.itemID!=UINT(-1)) - SendMessageW(item.hwndItem,CB_GETLBTEXT,item.itemID,reinterpret_cast(label)); - const bool selected=(item.itemState&ODS_SELECTED)!=0 && (item.itemState&ODS_COMBOBOXEDIT)==0; - paintText(item.hDC,item.rcItem,label,colors[Text],colors[selected?Selection:Dialog]); + drawFarComboRow(*reinterpret_cast(lp)); return TRUE; } if(message==WM_CTLCOLORLISTBOX) @@ -2041,14 +2325,15 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp) SetDlgItemTextW(dialog,pathField,fieldText.c_str()); SendDlgItemMessageW(dialog,pathField,EM_SETREADONLY,!single && !request.move,0); if(request.move) SetDlgItemTextW(dialog,IDOK,L"&Rename"); + fitFarEditToLine(GetDlgItem(dialog,pathField)); layoutDialogButtons(dialog,214,{IDOK,IDCANCEL}); - SendDlgItemMessageW(dialog,328,WM_SETFONT,reinterpret_cast(mono),FALSE); + installFarCheckbox(GetDlgItem(dialog,214),FarCheckboxSurface::gray); + CheckDlgButton(dialog,214,request.askReadOnly?BST_CHECKED:BST_UNCHECKED); SendDlgItemMessageW(dialog,summary,WM_SETFONT,reinterpret_cast(mono),FALSE); SendDlgItemMessageW(dialog,conflicts,WM_SETFONT,reinterpret_cast(mono),FALSE); for(const auto control:{213,214}) SendDlgItemMessageW(dialog,control,WM_SETFONT,reinterpret_cast(mono),FALSE); - SendDlgItemMessageW(dialog,213,CB_SETITEMHEIGHT,0,textHeight); - SendDlgItemMessageW(dialog,213,CB_SETITEMHEIGHT,static_cast(-1),textHeight+2); + installFarCombo(GetDlgItem(dialog,213),GetDlgItem(dialog,pathField)); RECT combo{}, caption{}; const auto captionControl=GetDlgItem(dialog,conflicts); GetWindowRect(GetDlgItem(dialog,213),&combo); @@ -2057,38 +2342,26 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp) MapWindowPoints(nullptr,dialog,reinterpret_cast(&caption),2); SetWindowPos(captionControl,nullptr,caption.left,combo.top, caption.right-caption.left,combo.bottom-combo.top,SWP_NOZORDER|SWP_NOACTIVATE); - SetWindowSubclass(GetDlgItem(dialog,213),paintConflictCombo,1,0); SendMessageW(dialog,DM_SETDEFID,IDOK,0); SendDlgItemMessageW(dialog,pathField,EM_SETSEL,0,-1); return TRUE; } if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL)) { - finishFilesDialog(dialog,IDCANCEL); + FilesModalDialog::finish(dialog,IDCANCEL); return TRUE; } if(message!=WM_COMMAND) return FALSE; auto &request=*reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); - if(LOWORD(wp)==214 && HIWORD(wp)==BN_CLICKED) - { - request.askReadOnly=!request.askReadOnly; - InvalidateRect(GetDlgItem(dialog,214),nullptr,FALSE); - return TRUE; - } if(LOWORD(wp)==213) { InvalidateRect(GetDlgItem(dialog,213),nullptr,FALSE); return FALSE; } - if(LOWORD(wp)==pathField && HIWORD(wp)==EN_CHANGE) - { - SetDlgItemTextW(dialog,328,L""); - return TRUE; - } if(LOWORD(wp)!=IDOK) return FALSE; const auto showError=[&](const wchar_t *message) { - SetDlgItemTextW(dialog,328,message); + showFilesNotice(dialog,message,L"Error",false,nullptr,true); SetFocus(GetDlgItem(dialog,pathField)); }; try @@ -2132,9 +2405,7 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp) const auto field=GetDlgItem(dialog,pathField); std::wstring name(GetWindowTextLengthW(field)+1,L'\0'); name.resize(GetWindowTextW(field,name.data(),static_cast(name.size()))); - if(name.empty() || name.back()==L'.' || name.back()==L' ' || - name.find_first_of(L"<>:\"/\\|?*")!=name.npos || - std::any_of(name.begin(),name.end(),[](wchar_t ch){return ch<32;})) + if(!validFileName(name)) { showError(L"Enter a valid name for the copy."); return TRUE; @@ -2162,10 +2433,11 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp) showError(L"Open a different folder in the other panel, or enter a new name for a single item."); return TRUE; } + request.askReadOnly=IsDlgButtonChecked(dialog,214)==BST_CHECKED; const auto mode=SendDlgItemMessageW(dialog,213,CB_GETCURSEL,0,0); if(mode!=CB_ERR) request.conflictMode=static_cast( request.move && mode==static_cast(ConflictMode::append)?static_cast(ConflictMode::newer):mode); - finishFilesDialog(dialog,IDOK); + FilesModalDialog::finish(dialog,IDOK); } catch(const std::system_error &e) { @@ -2196,24 +2468,6 @@ struct CopyProgress bool copyInProgress{}; CopyProgress *activeCopy{}; -struct OwnedWindowMove -{ - HWND owner; - LONG dx,dy; -}; - -BOOL CALLBACK moveOwnedDialog(HWND window,LPARAM parameter) -{ - const auto &move=*reinterpret_cast(parameter); - if(window==move.owner || !IsWindowVisible(window) || - GetAncestor(window,GA_ROOTOWNER)!=move.owner) return TRUE; - RECT bounds{}; - if(GetWindowRect(window,&bounds)) - SetWindowPos(window,nullptr,bounds.left+move.dx,bounds.top+move.dy,0,0, - SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE); - return TRUE; -} - LRESULT CALLBACK paintCopyProgressBar(HWND bar,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) { if(message!=WM_PAINT) return DefSubclassProc(bar,message,wp,lp); @@ -2296,6 +2550,297 @@ LRESULT CALLBACK dialogButtonEnter(HWND button,UINT message,WPARAM wp,LPARAM lp, return DefSubclassProc(button,message,wp,lp); } +INT_PTR paintTextDialog(HWND window,UINT message,WPARAM wp,LPARAM lp,const wchar_t *caption) +{ + return paintCopyDialog(window,message,wp,lp,caption,false,{},true); +} + +INT_PTR paintSearchDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) +{ + if(message==WM_DRAWITEM) + { + const auto &item=*reinterpret_cast(lp); + if(item.CtlID==ks::files::searchHistoryButton) + { + ks::files::paintFarFieldArrow(item.hDC,item.rcItem, + !(item.itemState&ODS_DISABLED),GetDpiForWindow(item.hwndItem)); + if(item.itemState&ODS_FOCUS) DrawFocusRect(item.hDC,&item.rcItem); + return TRUE; + } + if(item.CtlType==ODT_STATIC) + { + FillRect(item.hDC,&item.rcItem,static_cast(GetStockObject(LTGRAY_BRUSH))); + SelectObject(item.hDC,mono); + SetBkMode(item.hDC,TRANSPARENT); + SetTextColor(item.hDC,RGB(0,0,0)); + wchar_t label[40]{}; + GetWindowTextW(item.hwndItem,label,static_cast(std::size(label))); + drawFarDialogLabel(item.hDC,item.rcItem,label,false); + return TRUE; + } + paintDialogButton(item,RGB(192,192,192),RGB(0,0,0),true); + return TRUE; + } + return paintCopyDialog(window,message,wp,lp,L" Search ",false, + {ks::files::searchOptionsDivider,ks::files::searchButtonsDivider}); +} + +LONG searchDialogInset(HWND dialog) +{ + return std::max(dialogFrameMetrics(GetDpiForWindow(dialog)).content(),2*cellWidth); +} + +void layoutSearchDialog(HWND dialog) +{ + RECT client{}; + GetClientRect(dialog,&client); + const LONG inset=searchDialogInset(dialog); + const LONG gap=dialogColumnGap(); + const LONG available=client.right-2*inset; + const auto size=[&](int id) + { + const auto bounds=dialogControlBounds(dialog,id); + return SIZE{bounds.right-bounds.left,bounds.bottom-bounds.top}; + }; + const auto place=[&](int id,LONG x,LONG y,LONG width,LONG height) + { + SetWindowPos(GetDlgItem(dialog,id),nullptr,x,y,width,height, + SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS); + }; + const auto options=std::array{106,107}; + const auto actions=std::array{103,IDOK,IDCANCEL}; + const auto rowWidth=[&](const auto &ids) + { + LONG width=-gap; + for(const auto id:ids) width+=size(id).cx+gap; + return width; + }; + const LONG row=textHeight; + const LONG spacing=dialogRowGap(); + LONG y=dialogFrameMetrics(GetDpiForWindow(dialog)).content()+spacing; + const auto field=size(100); + const auto optionWidth=rowWidth(options); + const auto optionRowFits=optionWidth<=available; + const auto optionsBesideLabel=optionWidth+gap+11*cellWidth<=available; + + const auto buttons=[&](const auto &ids,LONG left,bool singleRow) + { + for(const auto id:ids) + { + const auto bounds=size(id); + place(id,singleRow?left:(client.right-bounds.cx)/2,y,bounds.cx,row); + left+=bounds.cx+gap; + if(!singleRow) y+=row; + } + if(singleRow) y+=row; + }; + + place(109,inset,y,optionsBesideLabel?available-optionWidth-gap:available,row); + if(optionsBesideLabel) buttons(options,client.right-inset-optionWidth,true); + else y+=row; + const auto parts=farDropDownBounds({inset,y,client.right-inset,y+field.cy}); + place(100,parts.field.left,y,parts.field.right-parts.field.left,field.cy); + place(ks::files::searchHistoryButton,parts.arrow.left,y,parts.arrow.right-parts.arrow.left,field.cy); + y+=field.cy+spacing; + if(!optionsBesideLabel) buttons(options,(client.right-optionWidth)/2,optionRowFits); + + place(ks::files::searchOptionsDivider,inset,y,1,1); + y+=spacing; + for(const auto id:{101,102}) + { + place(id,inset,y,available,row); + y+=row; + } + y+=std::max(1L,spacing/2); + place(ks::files::searchButtonsDivider,inset,y,1,1); + y+=spacing; + const auto actionsWidth=rowWidth(actions); + buttons(actions,(client.right-actionsWidth)/2,actionsWidth<=available); + + RECT bounds{},owner{}; + GetWindowRect(dialog,&bounds); + GetWindowRect(GetWindow(dialog,GW_OWNER),&owner); + const auto height=y+dialogFrameMetrics(GetDpiForWindow(dialog)).content()+spacing; + if(height!=bounds.bottom-bounds.top) + SetWindowPos(dialog,nullptr,bounds.left,(owner.top+owner.bottom-height)/2,client.right,height, + SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS); +} + +void prepareTextDialog(HWND dialog) +{ + prepareCopyDialog(dialog); + TEXTMETRICW templateMetrics{}, filesMetrics{}; + const auto dc=GetDC(dialog); + if(dc) + { + const auto templateFont=reinterpret_cast(SendMessageW(dialog,WM_GETFONT,0,0)); + const auto previous=SelectObject(dc,templateFont); + GetTextMetricsW(dc,&templateMetrics); + SelectObject(dc,mono); + GetTextMetricsW(dc,&filesMetrics); + SelectObject(dc,previous); + ReleaseDC(dialog,dc); + } + const auto scale=[&](LONG value,LONG original,LONG actual) + { + return original>0?MulDiv(value,std::max(original,actual),original):value; + }; + const auto x=[&](LONG value){return scale(value,templateMetrics.tmAveCharWidth,filesMetrics.tmAveCharWidth);}; + const auto y=[&](LONG value){return scale(value,templateMetrics.tmHeight,filesMetrics.tmHeight);}; + RECT bounds{}; + GetWindowRect(dialog,&bounds); + const auto width=x(bounds.right-bounds.left),height=y(bounds.bottom-bounds.top); + SetWindowPos(dialog,nullptr,(bounds.left+bounds.right-width)/2,(bounds.top+bounds.bottom-height)/2, + width,height,SWP_NOZORDER|SWP_NOACTIVATE); + SendMessageW(dialog,WM_SETFONT,reinterpret_cast(mono),FALSE); + const bool search=GetDlgItem(dialog,ks::files::searchOptionsDivider)!=nullptr; + for(auto field=GetWindow(dialog,GW_CHILD);field;field=GetWindow(field,GW_HWNDNEXT)) + { + RECT rect{}; + GetWindowRect(field,&rect); + MapWindowPoints(nullptr,dialog,reinterpret_cast(&rect),2); + SetWindowPos(field,nullptr,x(rect.left),y(rect.top),x(rect.right)-x(rect.left),y(rect.bottom)-y(rect.top), + SWP_NOZORDER|SWP_NOACTIVATE); + SendMessageW(field,WM_SETFONT,reinterpret_cast(mono),FALSE); + wchar_t type[16]{}; + GetClassNameW(field,type,static_cast(std::size(type))); + if(lstrcmpiW(type,L"Button")==0 && (GetWindowLongPtrW(field,GWL_STYLE)&BS_TYPEMASK)==BS_AUTOCHECKBOX) + installFarCheckbox(field,search?FarCheckboxSurface::gray:FarCheckboxSurface::dialog); + } + if(search) + { + fitFarEditToLine(GetDlgItem(dialog,100)); + LONG widest{}; + for(const auto id:{103,IDOK,IDCANCEL,106,107}) + { + const auto button=GetDlgItem(dialog,id); + const auto width=farDialogButtonWidth(button); + SetWindowPos(button,nullptr,0,0,width,textHeight,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE); + widest=std::max(widest,width); + } + FilesModalDialog::fitWidthToOwner(dialog,2*searchDialogInset(dialog)+std::max(widest,22*cellWidth),layoutSearchDialog); + } +} + +INT_PTR CALLBACK textSaveDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) +{ + if(const auto painted=paintTextDialog(window,message,wp,lp,L" Editor ")) + return painted; + if(message==WM_INITDIALOG) + { + prepareTextDialog(window); + groupDialogButtons(window,{IDYES,IDNO,IDCANCEL}); + SendMessageW(window,DM_SETDEFID,IDCANCEL,0); + SetFocus(GetDlgItem(window,IDCANCEL)); + return FALSE; + } + if(message==WM_COMMAND && (LOWORD(wp)==IDYES || LOWORD(wp)==IDNO || LOWORD(wp)==IDCANCEL)) + { + FilesModalDialog::finish(window,LOWORD(wp)); + return TRUE; + } + return FALSE; +} + +INT_PTR confirmTextSave(HWND owner) +{ + return FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(603),owner,textSaveDialog,0); +} + +struct FilesNotice +{ + const wchar_t *text; + std::wstring title; + bool confirm; + bool *remember; + bool warning; +}; + +INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) +{ + if(message==WM_INITDIALOG) + { + SetWindowLongPtrW(window,DWLP_USER,lp); + const auto ¬ice=*reinterpret_cast(lp); + prepareTextDialog(window); + SetDlgItemTextW(window,100,notice.text); + if(notice.warning) + { + const auto bounds=dialogControlBounds(window,100); + const auto divider=dialogControlBounds(window,102); + RECT text{0,0,bounds.right-bounds.left,0}; + if(const auto dc=GetDC(window)) + { + const auto previous=SelectObject(dc,mono); + DrawTextW(dc,notice.text,-1,&text,DT_CALCRECT|DT_WORDBREAK|DT_NOPREFIX); + SelectObject(dc,previous); + ReleaseDC(window,dc); + } + const auto height=std::max(text.bottom,textHeight); + SetWindowPos(GetDlgItem(window,100),nullptr,bounds.left,bounds.top,bounds.right-bounds.left,height, + SWP_NOZORDER|SWP_NOACTIVATE); + SetWindowPos(GetDlgItem(window,102),nullptr,divider.left,bounds.top+height+dialogRowGap()+4,0,0, + SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE); + layoutDialogButtons(window,102,{IDOK}); + } + if(notice.remember) + { + const auto field=GetDlgItem(window,100); + RECT bounds{}; + GetWindowRect(field,&bounds); + SetWindowPos(field,nullptr,0,0,bounds.right-bounds.left, + (bounds.bottom-bounds.top)*3/4,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE); + ShowWindow(GetDlgItem(window,101),SW_SHOW); + } + if(notice.confirm) + { + ShowWindow(GetDlgItem(window,IDOK),SW_HIDE); + ShowWindow(GetDlgItem(window,IDYES),SW_SHOW); + ShowWindow(GetDlgItem(window,IDNO),SW_SHOW); + groupDialogButtons(window,{IDYES,IDNO}); + } + else if(!notice.warning) groupDialogButtons(window,{IDOK}); + const auto defaultButton=notice.confirm?IDNO:IDOK; + SendMessageW(window,DM_SETDEFID,defaultButton,0); + SetFocus(GetDlgItem(window,defaultButton)); + return FALSE; + } + const auto *notice=reinterpret_cast(GetWindowLongPtrW(window,DWLP_USER)); + if(!notice) return FALSE; + if(const auto painted=paintCopyDialog(window,message,wp,lp,notice->title.c_str(), + notice->warning,notice->warning?std::initializer_list{102}:std::initializer_list{}, + !notice->warning)) return painted; + const auto command=LOWORD(wp); + if(message==WM_COMMAND && (command==IDOK || command==IDCANCEL || command==IDYES || command==IDNO)) + { + if(command==IDYES && notice->remember) + *notice->remember=IsDlgButtonChecked(window,101)==BST_CHECKED; + FilesModalDialog::finish(window,command); + return TRUE; + } + return FALSE; +} + +INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,bool confirm,bool *remember,bool warning) +{ + const bool createBrush=warning && !warningBrush; + if(createBrush) warningBrush=CreateSolidBrush(RGB(128,0,0)); + FilesNotice notice{text,std::wstring(L" ")+title+L" ",confirm,remember,warning}; + const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(warning?609:607),owner,filesNoticeDialog, + reinterpret_cast(¬ice)); + if(createBrush) + { + DeleteObject(warningBrush); + warningBrush=nullptr; + } + return result; +} + +void showTextMessage(HWND owner,const wchar_t *text) +{ + showFilesNotice(owner,text,L"KSwitcher Files"); +} + INT_PTR CALLBACK cancelOperationDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) { if(const auto painted=paintCopyDialog(window,message,wp,lp,L" Operation interrupted ",true,{236})) @@ -2314,7 +2859,7 @@ INT_PTR CALLBACK cancelOperationDialog(HWND window,UINT message,WPARAM wp,LPARAM if(message==WM_CLOSE || (message==WM_COMMAND && (LOWORD(wp)==IDYES || LOWORD(wp)==IDNO || LOWORD(wp)==IDCANCEL))) { - finishFilesDialog(window,message==WM_COMMAND && LOWORD(wp)==IDYES?IDYES:IDNO); + FilesModalDialog::finish(window,message==WM_COMMAND && LOWORD(wp)==IDYES?IDYES:IDNO); return TRUE; } return FALSE; @@ -2324,7 +2869,7 @@ bool confirmOperationCancellation(HWND owner,const wchar_t *question) { const auto previous=warningBrush; if(!previous) warningBrush=CreateSolidBrush(RGB(128,0,0)); - const auto answer=runFilesDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(105),owner, + const auto answer=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(105),owner, cancelOperationDialog,reinterpret_cast(question)); if(!previous) { @@ -2481,21 +3026,6 @@ LRESULT CALLBACK warningButtonKeys(HWND button,UINT message,WPARAM wp,LPARAM lp, INT_PTR CALLBACK warningDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) { - if(message==WM_DRAWITEM && wp==232) - { - const auto &item=*reinterpret_cast(lp); - const auto warning=reinterpret_cast(GetWindowLongPtrW(window,DWLP_USER)); - auto bounds=item.rcItem; - FillRect(item.hDC,&bounds,warningBrush); - SelectObject(item.hDC,mono); - SetBkMode(item.hDC,TRANSPARENT); - SetTextColor(item.hDC,RGB(255,255,255)); - bounds.left+=5; - DrawTextW(item.hDC,warning && warning->remember?L"[x] Remember choice":L"[ ] Remember choice", - -1,&bounds,DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX); - if(item.itemState&ODS_FOCUS) DrawFocusRect(item.hDC,&item.rcItem); - return TRUE; - } if(const auto painted=paintCopyDialog(window,message,wp,lp,L" Warning ",true,{233,333,234})) return painted; if(message==WM_INITDIALOG) @@ -2512,6 +3042,7 @@ INT_PTR CALLBACK warningDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) SetDlgItemTextW(window,IDNO,warning.decline); for(const auto control:{230,231,232,329,330,331,332}) SendDlgItemMessageW(window,control,WM_SETFONT,reinterpret_cast(mono),FALSE); + installFarCheckbox(GetDlgItem(window,232),FarCheckboxSurface::warning); centerDialogRow(window,333,234,{232}); layoutDialogButtons(window,234,{IDYES,IDNO,IDCANCEL}); SendMessageW(window,DM_SETDEFID,IDNO,0); @@ -2524,20 +3055,15 @@ INT_PTR CALLBACK warningDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) } if(message==WM_CLOSE) { - finishFilesDialog(window,IDCANCEL); - return TRUE; - } - if(message==WM_COMMAND && LOWORD(wp)==232 && HIWORD(wp)==BN_CLICKED) - { - auto &warning=*reinterpret_cast(GetWindowLongPtrW(window,DWLP_USER)); - warning.remember=!warning.remember; - InvalidateRect(GetDlgItem(window,232),nullptr,FALSE); + FilesModalDialog::finish(window,IDCANCEL); return TRUE; } if(message==WM_COMMAND && (LOWORD(wp)==IDYES || LOWORD(wp)==IDNO || LOWORD(wp)==IDCANCEL)) { + auto &warning=*reinterpret_cast(GetWindowLongPtrW(window,DWLP_USER)); + warning.remember=IsDlgButtonChecked(window,232)==BST_CHECKED; const auto choice=LOWORD(wp); - finishFilesDialog(window,choice); + FilesModalDialog::finish(window,choice); return TRUE; } return FALSE; @@ -2555,23 +3081,15 @@ bool pumpCopy(CopyProgress &progress) break; } const auto owner=GetWindow(progress.window,GW_OWNER); - const bool inMainWindow=message.hwnd==owner || IsChild(owner,message.hwnd); - if(inMainWindow && - ((message.message>=WM_KEYFIRST && message.message<=WM_KEYLAST) || - (message.message>=WM_MOUSEFIRST && message.message<=WM_MOUSELAST))) + if(message.message==WM_SYSKEYDOWN && message.wParam==VK_F4 && + (message.hwnd==owner || IsChild(owner,message.hwnd))) { - if(filesMouseDown(message.message) || (message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE)) - SendMessageW(progress.window,WM_COMMAND,IDCANCEL,0); - else if(message.message==WM_SYSKEYDOWN && message.wParam==VK_F4) - SendMessageW(owner,WM_CLOSE,0,0); + SendMessageW(owner,WM_CLOSE,0,0); continue; } - const bool inProgressWindow=message.hwnd==progress.window || IsChild(progress.window,message.hwnd); - if(!inProgressWindow || !IsDialogMessageW(progress.window,&message)) - { - TranslateMessage(&message); - DispatchMessageW(&message); - } + if(FilesModalDialog::handleMessage(progress.window,message)) continue; + TranslateMessage(&message); + DispatchMessageW(&message); } return !progress.canceled; } @@ -2743,7 +3261,7 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa WarningPrompt warning{readOnly?L"Existing file is read-only":L"File already exists", to.c_str(),L"&Overwrite",L"&Skip",*incoming,*existing}; warningBrush=CreateSolidBrush(RGB(128,0,0)); - answer=runFilesDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(104),progress.window, + answer=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(104),progress.window, warningDialog,reinterpret_cast(&warning)); if(warning.remember && (answer==IDYES || answer==IDNO)) progress.conflictChoice=static_cast(answer); @@ -2779,7 +3297,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move) if(row<0 || static_cast(row)>=source.rows.size() || source.sizes[row]==L"Up") return; request.sources.push_back(source.rows[row]); } - const auto result=runFilesDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(102),owner,copyDialog, + const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(102),owner,copyDialog, reinterpret_cast(&request)); if(result==-1) setStatus(L"Could not open the Copy dialog."); if(result!=IDOK) return; @@ -2793,20 +3311,19 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move) progress.move=move; progress.conflictMode=request.conflictMode; progress.askReadOnly=request.askReadOnly; - progress.window=CreateDialogParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(103),owner, + FilesModalDialog progressDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(103),owner, copyProgressDialog,reinterpret_cast(&progress)); + progress.window=progressDialog.window(); if(!progress.window) { setStatus(L"Could not open copy progress."); return; } - FilesDialogInput progressInput(progress.window); copyInProgress=true; activeCopy=&progress; for(auto &panel:panels) EnableWindow(panel.list,FALSE); for(const auto command:commands) EnableWindow(command,FALSE); - GetWindowRect(owner,&previousOwnerBounds); - ShowWindow(progress.window,SW_SHOW); + progressDialog.show(); bool failed=false, skipped=false; size_t copied=0; std::set results; @@ -2863,7 +3380,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move) const bool restoreFocus=GetForegroundWindow()==progress.window; updateCopyProgress(progress,0,0,true); RedrawWindow(progress.window,nullptr,nullptr,RDW_UPDATENOW|RDW_ALLCHILDREN); - DestroyWindow(progress.window); + progressDialog.close(); activeCopy=nullptr; copyInProgress=false; for(auto &panel:panels) EnableWindow(panel.list,TRUE); @@ -2881,13 +3398,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move) { const auto renamedPath=progress.renamedTarget.empty()? targetDirectory/request.newName:progress.renamedTarget; - const auto row=std::find(source.rows.begin(),source.rows.end(),renamedPath); - if(row!=source.rows.end()) - { - SendMessageW(source.list,LB_SETCURSEL,row-source.rows.begin(),0); - InvalidateRect(source.list,nullptr,FALSE); - showFileDetails(source); - } + selectPanelPath(source,renamedPath); } } else @@ -3028,14 +3539,14 @@ INT_PTR CALLBACK deleteConfirmationDialog(HWND window,UINT message,WPARAM wp,LPA } if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL)) { - finishFilesDialog(window,IDCANCEL); + FilesModalDialog::finish(window,IDCANCEL); return TRUE; } if(message==WM_COMMAND && (LOWORD(wp)==IDYES || ((data->folderPrompt || data->readOnlyPrompt) && (LOWORD(wp)==244 || LOWORD(wp)==IDNO)) || (data->readOnlyPrompt && LOWORD(wp)==249))) { - finishFilesDialog(window,LOWORD(wp)); + FilesModalDialog::finish(window,LOWORD(wp)); return TRUE; } return FALSE; @@ -3077,7 +3588,7 @@ bool pumpDeletion(HWND window,bool &canceled) canceled=true; break; } - if(!filesDialogHandlesMessage(window,message)) + if(!FilesModalDialog::handleMessage(window,message)) { TranslateMessage(&message); DispatchMessageW(&message); @@ -3127,23 +3638,22 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) } DeleteConfirmation confirmation{message,entries,static_cast(shown+(shown(&confirmation))!=IDYES) { DeleteObject(warningBrush); warningBrush=nullptr; - // The dialog owns focus until DialogBoxParamW returns. Restore the invoking list. + // Restore the invoking list after the modal dialog closes. SetFocus(panel.list); return; } bool canceled=false; - const auto window=CreateDialogParamW(instance,MAKEINTRESOURCEW(107),owner,deleteProgressDialog, + FilesModalDialog progressDialog(instance,MAKEINTRESOURCEW(107),owner,deleteProgressDialog, reinterpret_cast(&canceled)); + const auto window=progressDialog.window(); if(window) { - GetWindowRect(owner,&previousOwnerBounds); - FilesDialogInput progressInput(window); - ShowWindow(window,SW_SHOW); + progressDialog.show(); size_t done=0, skipped=0, failed=0, total=0; bool all=false; int readOnlyChoice=0; @@ -3206,7 +3716,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) if(group.size()>1 && !all) { DeleteConfirmation folder{L"The following folder will be deleted:",group.front().wstring(),1,true,true}; - const auto answer=runFilesDialog(instance,MAKEINTRESOURCEW(106),window,deleteConfirmationDialog, + const auto answer=FilesModalDialog::run(instance,MAKEINTRESOURCEW(106),window,deleteConfirmationDialog, reinterpret_cast(&folder)); if(answer==244) all=true; else if(answer==IDNO) @@ -3233,7 +3743,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) if(!answer) { DeleteConfirmation warning{L"Delete this read-only file?",current.wstring(),1,true,false,true}; - answer=runFilesDialog(instance,MAKEINTRESOURCEW(106),window,deleteConfirmationDialog, + answer=FilesModalDialog::run(instance,MAKEINTRESOURCEW(106),window,deleteConfirmationDialog, reinterpret_cast(&warning)); if(answer==244 || answer==249) readOnlyChoice=static_cast(answer); } @@ -3278,7 +3788,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) catch(const std::exception &){++failed;failure=L"File connection interrupted.";} RedrawWindow(window,nullptr,nullptr,RDW_UPDATENOW|RDW_ALLCHILDREN); - DestroyWindow(window); + progressDialog.close(); for(auto &visible:panels) if(!visible.directory.empty()) open(visible,visible.directory); SetFocus(panel.list); @@ -3301,6 +3811,198 @@ void selectPanelEdge(Panel &panel,bool first) showFileDetails(panel); } +struct MakeFolderRequest +{ + const fs::path &directory; + const FilesPeer *peer; + fs::path created; + std::vector history; +}; + +std::vector folderNames(std::wstring_view input,bool multiple) +{ + if(!multiple) return {std::wstring(input)}; + std::vector names; + std::wstring token; + bool quoted=false; + const auto append=[&] + { + const auto first=token.find_first_not_of(L" \t"); + if(first!=token.npos) + names.push_back(token.substr(first,token.find_last_not_of(L" \t")-first+1)); + token.clear(); + }; + for(const auto character:input) + { + if(character==L'"') quoted=!quoted; + else if(!quoted && (character==L',' || character==L';')) append(); + else token+=character; + } + if(quoted) return {}; + append(); + return names; +} + +std::wstring dialogFieldText(HWND field) +{ + std::wstring value(GetWindowTextLengthW(field)+1,L'\0'); + value.resize(GetWindowTextW(field,value.data(),static_cast(value.size()))); + return value; +} + +INT_PTR CALLBACK makeFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) +{ + constexpr int label=360,field=361,divider=362,history=363,linkLabel=364,linkType=365, + targetLabel=366,target=367,multiple=368,footer=369; + const auto input=GetDlgItem(dialog,field); + const auto combo=GetDlgItem(dialog,linkType); + const auto targetInput=GetDlgItem(dialog,target); + if(message==WM_INITDIALOG) + { + SetWindowLongPtrW(dialog,DWLP_USER,lp); + const auto &request=*reinterpret_cast(lp); + prepareTextDialog(dialog); + installFarCheckbox(GetDlgItem(dialog,multiple),FarCheckboxSurface::gray); + for(const auto control:{input,targetInput}) fitFarEditToLine(control); + const auto edit=dialogControlBounds(dialog,field); + const auto arrow=GetDlgItem(dialog,history); + const auto parts=farDropDownBounds({edit.left,edit.top,dialogControlBounds(dialog,history).right,edit.bottom}); + SetWindowPos(input,nullptr,edit.left,edit.top,parts.field.right-edit.left,edit.bottom-edit.top, + SWP_NOZORDER|SWP_NOACTIVATE); + SetWindowPos(arrow,nullptr,parts.arrow.left,edit.top,parts.arrow.right-parts.arrow.left, + edit.bottom-edit.top,SWP_NOZORDER|SWP_NOACTIVATE); + EnableWindow(arrow,!request.history.empty()); + SendMessageW(input,EM_SETLIMITTEXT,511,0); + ks::files::installFarHistoryKey(input,history); + for(const auto text:{L"none",L"directory junction",L"symbolic link"}) + SendMessageW(combo,CB_ADDSTRING,0,reinterpret_cast(text)); + installFarCombo(combo,input); + SendMessageW(combo,CB_SETCURSEL,0,0); + EnableWindow(targetInput,FALSE); + EnableWindow(GetDlgItem(dialog,targetLabel),FALSE); + layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL}); + SendMessageW(dialog,DM_SETDEFID,IDOK,0); + SetFocus(input); + return FALSE; + } + if(message==WM_DRAWITEM) + { + const auto &item=*reinterpret_cast(lp); + if(wp==linkType) { drawFarComboRow(item); return TRUE; } + if(wp==history) + { + ks::files::paintFarFieldArrow(item.hDC,item.rcItem,IsWindowEnabled(item.hwndItem), + GetDpiForWindow(item.hwndItem)); + return TRUE; + } + if(wp==label || wp==linkLabel || wp==targetLabel) + { + FillRect(item.hDC,&item.rcItem,static_cast(GetStockObject(LTGRAY_BRUSH))); + SelectObject(item.hDC,mono); + SetBkMode(item.hDC,TRANSPARENT); + SetTextColor(item.hDC,IsWindowEnabled(item.hwndItem)?RGB(0,0,0):RGB(128,128,128)); + drawFarDialogLabel(item.hDC,item.rcItem,dialogFieldText(item.hwndItem),false); + return TRUE; + } + } + if(message==WM_CTLCOLORLISTBOX) + { + const auto dc=reinterpret_cast(wp); + SetTextColor(dc,colors[Text]); + SetBkColor(dc,colors[Dialog]); + return reinterpret_cast(teal); + } + if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" Make folder ",false,{divider,footer})) + return painted; + if(message!=WM_COMMAND) return FALSE; + const auto command=LOWORD(wp); + if(command==IDCANCEL) + { + FilesModalDialog::finish(dialog,IDCANCEL); + return TRUE; + } + auto *request=reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + if(!request) return FALSE; + if(command==history) + { + ks::files::showFarHistory(dialog,field,request->history,farDropDownPalette()); + return TRUE; + } + const auto kind=SendMessageW(combo,CB_GETCURSEL,0,0); + if(command==linkType && HIWORD(wp)==CBN_SELCHANGE) + { + EnableWindow(targetInput,kind>0); + EnableWindow(GetDlgItem(dialog,targetLabel),kind>0); + InvalidateRect(combo,nullptr,FALSE); + return TRUE; + } + if(command!=IDOK) return FALSE; + const auto error=[&](const wchar_t *text,HWND focus) + { + showFilesNotice(dialog,text,L"Error",false,nullptr,true); + SetFocus(focus); + }; + const auto entered=dialogFieldText(input); + const auto names=folderNames(entered,IsDlgButtonChecked(dialog,multiple)==BST_CHECKED); + if(names.empty() || !std::all_of(names.begin(),names.end(),validFileName)) + { + error(L"Enter a valid folder name.",input); + return TRUE; + } + const fs::path linkTarget=dialogFieldText(targetInput); + if(kind>0 && (linkTarget.empty() || (linkTarget.has_root_name() && !linkTarget.is_absolute()))) + { + error(L"Enter a target directory path.",targetInput); + return TRUE; + } + fs::path current; + try + { + FilesConnection host(request->peer); + for(const auto &name:names) + { + current=request->directory/name; + auto operation=fileRequest(kind>0?"mkdir-link":"mkdir",current); + if(kind>0) + { + const auto resolved=linkTarget.is_absolute()?linkTarget:request->directory/linkTarget; + operation["target"]=ks::utf8(resolved.lexically_normal().native()); + operation["kind"]=kind==1?"junction":"symlink"; + } + checkFileReply(host.call(operation)); + request->created=current; + } + } + catch(const std::system_error &failure) + { + const auto details=current.filename().wstring()+L": "+fileError(failure); + error(details.c_str(),input); + if(!request->created.empty()) FilesModalDialog::finish(dialog,IDOK); + return TRUE; + } + catch(const std::exception &) + { + error(L"Could not create the folder.",input); + if(!request->created.empty()) FilesModalDialog::finish(dialog,IDOK); + return TRUE; + } + ks::files::rememberFarHistory(ks::files::FarHistoryKind::folder,entered); + FilesModalDialog::finish(dialog,IDOK); + return TRUE; +} + +void makeFolder(HWND owner,Panel &panel) +{ + if(panel.directory.empty()) return; + const auto directory=panel.directory; + MakeFolderRequest request{directory,panel.peer?&*panel.peer:nullptr,{}, + ks::files::loadFarHistory(ks::files::FarHistoryKind::folder)}; + if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(108),owner,makeFolderDialog, + reinterpret_cast(&request))!=IDOK) return; + open(panel,directory); + selectPanelPath(panel,request.created); +} + LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR index) { if(message==WM_LBUTTONDOWN) @@ -3356,12 +4058,7 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT if (wp == VK_F10) { SendMessageW(GetParent(window), WM_CLOSE, 0, 0); return 0; } if (wp == VK_F3 || wp == VK_F4) { - const auto &panel = panels[index]; - const auto row=currentPanelRow(panel); - if(row==LB_ERR) return 0; - const bool edit = wp == VK_F4; - openPanelFile(panel, panel.rows[row], edit ? L"edit" : L"open", - edit ? L"No editor is registered for this file." : L"Cannot open the selected file."); + openSelectedText(panels[index],wp==VK_F4,false); return 0; } if (wp == VK_F5 || wp == VK_F6) @@ -3369,6 +4066,11 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT copySelection(GetParent(window),panels[index],panels[1-index],wp==VK_F6); return 0; } + if(wp==VK_F7) + { + makeFolder(GetParent(window),panels[index]); + return 0; + } if(wp==VK_F8 || (wp==VK_DELETE && (GetKeyState(VK_SHIFT)&0x8000))) { deleteSelection(GetParent(window),panels[index],wp==VK_DELETE); @@ -3398,15 +4100,8 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT #include "files_command_history_dialog.inl" bool loadFilesPreferences(HWND window) { - LOGFONTW font{}; - DWORD bytes=sizeof(font); - if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,L"DisplayFont",RRF_RT_REG_BINARY,nullptr,&font,&bytes) - !=ERROR_SUCCESS || bytes!=sizeof(font)) - { - font=defaultFilesFont(); - } - font.lfFaceName[LF_FACESIZE-1]=0; - if(!applyFont(window,font,static_cast(std::clamp(preference(L"FontPoints",defaultFontPoints),80UL,240UL)))) return false; + const auto [font,points]=readFilesFont(); + if(!applyFont(window,font,points)) return false; loadColors(); dialogFramePadding={ std::min(preference(dialogFrameOuterKey,defaultDialogFramePadding.outer),maxDialogFramePadding), @@ -3433,6 +4128,7 @@ void openMenu(HWND window, int index) { hidePicker(); showMenu(false); + RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN|RDW_UPDATENOW|RDW_NOERASE); editOptions(window); return; } @@ -3447,8 +4143,9 @@ void openMenu(HWND window, int index) wide?L"✓ Wide":L" Wide", index==0?L" Change drive\tAlt+F1":L" Change drive\tAlt+F2"}; } - else if(index==1) rows={L"Copy\tF5",L"Move\tF6",L"Exit\tF10"}; - else if(index==2) rows={L"Refresh\tF2",L"View\tF3",L"Edit\tF4",L"Folder shortcuts"}; + else if(index==1) rows={L"Copy\tF5",L"Move\tF6",L"Make folder\tF7",L"Exit\tF10"}; + else if(index==2) rows={L"Refresh\tF2",L"View\tF3",L"Edit\tF4",L"Folder shortcuts", + L"View externally\tAlt+F3",L"Edit externally\tAlt+F4"}; std::set used; commandAccessPositions.assign(rows.size(),std::wstring::npos); const auto reserve=[&](size_t row,wchar_t key) @@ -3463,7 +4160,7 @@ void openMenu(HWND window, int index) return false; }; if(index==0 || index==4) {reserve(0,L'B');reserve(1,L'W');reserve(2,L'C');} - if(index==1) {reserve(0,L'C');reserve(2,L'X');} + if(index==1) {reserve(0,L'C');reserve(2,L'F');reserve(3,L'X');} if(index==2) {reserve(1,L'V');reserve(2,L'E');} for(size_t i=0;i(mono), FALSE); - const wchar_t *labels[]{L"F2 Refresh", L"F3 View", L"F4 Edit", L"F5 Copy", L"F6 Move", L"F10 Exit"}; + const wchar_t *labels[]{L"F2 Refresh", L"F3 View", L"F4 Edit", L"F5 Copy", L"F6 Move", L"F7 Mkdir", L"F10 Exit"}; for (int i = 0; i < static_cast(std::size(commands)); ++i) commands[i] = CreateWindowW(L"BUTTON", labels[i], WS_CHILD | WS_VISIBLE | BS_OWNERDRAW, 0, 0, 0, 0, window, reinterpret_cast(110 + static_cast(i)), instance, nullptr); @@ -3760,25 +4457,9 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN); return 0; } - case WM_MOVE: - layoutOpenCommandHistory(true); - if((copyInProgress || activeFilesDialog) && !IsIconic(window)) - { - RECT bounds{}; - if(GetWindowRect(window,&bounds)) - { - const OwnedWindowMove move{window,bounds.left-previousOwnerBounds.left, - bounds.top-previousOwnerBounds.top}; - previousOwnerBounds=bounds; - if(move.dx || move.dy) - EnumThreadWindows(GetCurrentThreadId(),moveOwnedDialog,reinterpret_cast(&move)); - } - } - return 0; case WM_SIZE: hidePicker(); layout(window); - layoutOpenCommandHistory(); return 0; case WM_GETMINMAXINFO: reinterpret_cast(lp)->ptMinTrackSize = {540, 220}; @@ -4172,9 +4853,9 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) openMenu(window,LOWORD(wp)-130); return 0; } - if (LOWORD(wp) >= 110 && LOWORD(wp) <= 115 && HIWORD(wp) == BN_CLICKED) + if (LOWORD(wp) >= 110 && LOWORD(wp) < 110+std::size(commands) && HIWORD(wp) == BN_CLICKED) { - const WPARAM keys[]{VK_F2, VK_F3, VK_F4, VK_F5, VK_F6, VK_F10}; + const WPARAM keys[]{VK_F2, VK_F3, VK_F4, VK_F5, VK_F6, VK_F7, VK_F10}; SendMessageW(panels[active].list, WM_KEYDOWN, keys[LOWORD(wp) - 110], 0); } if (LOWORD(wp) >= 102 && LOWORD(wp) <= 103 && HIWORD(wp) == LBN_DBLCLK) @@ -4187,11 +4868,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) } return 0; case WM_CLOSE: - if(activeFilesDialog && !activeCopy) - { - PostMessageW(activeFilesDialog,WM_CLOSE,0,0); - return 0; - } + if(!activeCopy && FilesModalDialog::dismissOwned(window)) return 0; if(activeCopy) { if(activeFilesDialog!=activeCopy->window) @@ -4276,7 +4953,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) type.hCursor = LoadCursorW(nullptr, IDC_ARROW); type.lpszClassName = L"KSwitcher.Files"; - if (!RegisterClassW(&type)) return 1; + if (!registerFarEdit(instance) || !RegisterClassW(&type)) return 1; auto window = CreateWindowW(type.lpszClassName, L"KSwitcher Files — local prototype", WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, 900, 540, nullptr, nullptr, instance, nullptr); if (!window) return 1; @@ -4291,22 +4968,21 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) if(message.hwnd==window && message.message>=WM_KEYFIRST && message.message<=WM_KEYLAST && GetFocus()==terminalInput) message.hwnd=terminalInput; - if(commandHistoryWindow) - { - if(message.message==WM_KEYDOWN && (message.wParam==VK_RETURN || message.wParam==VK_ESCAPE) && - (message.hwnd==commandHistoryWindow || IsChild(commandHistoryWindow,message.hwnd))) - { - SendMessageW(commandHistoryWindow,WM_COMMAND,message.wParam==VK_RETURN?IDOK:IDCANCEL,0); - continue; - } - if(IsDialogMessageW(commandHistoryWindow,&message)) continue; - const bool ownerClient=message.hwnd==window || IsChild(window,message.hwnd); - const bool clientInput=(message.message>=WM_KEYFIRST && message.message<=WM_KEYLAST) || - (message.message>=WM_MOUSEFIRST && message.message<=WM_MOUSELAST) || - message.message==WM_CONTEXTMENU; - if(ownerClient && clientInput) continue; - } if(!copyInProgress && handlePanelSearchKey(window,message)) continue; + if(!copyInProgress && !commandHistoryWindow && !activeFilesDialog && !terminalVisible && + message.message==WM_SYSKEYDOWN && (message.wParam==VK_F3 || message.wParam==VK_F4) && + (message.lParam & (1LL<<29)) && + !(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_SHIFT)&0x8000) && + (message.hwnd==window || IsChild(window,message.hwnd))) + { + if(!(message.lParam & (1LL<<30))) + { + hidePicker(); + showMenu(false); + openSelectedText(panels[active],message.wParam==VK_F4,true); + } + continue; + } if(message.message==WM_KEYDOWN && (message.wParam==VK_UP || message.wParam==VK_DOWN) && (GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) && (message.hwnd==window || IsChild(window,message.hwnd)) && !terminalVisible && !copyInProgress) diff --git a/src/files_menu_paint.h b/src/files_menu_paint.h new file mode 100644 index 0000000..d5be540 --- /dev/null +++ b/src/files_menu_paint.h @@ -0,0 +1,22 @@ +#pragma once + +#include +#include + +namespace ks::files +{ +inline void paintMenuAccessKey(HDC dc, const RECT &clip, POINT origin, std::wstring_view title, + size_t access, COLORREF ink) +{ + if (access >= title.size()) return; + SIZE prefix{}; + GetTextExtentPoint32W(dc, title.data(), static_cast(access), &prefix); + const auto background = SetBkMode(dc, TRANSPARENT); + const auto text = SetTextColor(dc, ink); + const auto alignment = SetTextAlign(dc, TA_LEFT | TA_TOP); + ExtTextOutW(dc, origin.x + prefix.cx, origin.y, ETO_CLIPPED, &clip, title.data() + access, 1, nullptr); + SetTextAlign(dc, alignment); + SetTextColor(dc, text); + SetBkMode(dc, background); +} +} diff --git a/src/files_options.inl b/src/files_options.inl index 52d3580..f3c3b27 100644 --- a/src/files_options.inl +++ b/src/files_options.inl @@ -1,7 +1,6 @@ constexpr int optionsSearch=270,optionsTree=271,optionsTitle=272,optionsApply=283,optionsReset=284,optionsProperty=285,optionsResetProperty=286; -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"}; +enum OptionsPage { PanelModes, PanelColors, Appearance, CommandLine, TextViewer, TextEditor, allOptions }; +constexpr const wchar_t *optionsTitles[]{L"File panel modes",L"Colors",L"Appearance",L"Command line",L"Viewer",L"Editor"}; 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 }; @@ -14,6 +13,25 @@ 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 int textTabWidth=357,textLineEnding=359, + textTheme=363,textColor=365,textChangeColor=366,textColorValue=367,textSaveScheme=368; +constexpr int textControls[]{350,351,352,353,356,textTabWidth, + 362,textTheme,364,textColor,textChangeColor,textColorValue,textSaveScheme}; +constexpr int editingControls[]{354,355,358,textLineEnding}; +constexpr struct +{ + int id; + bool ks::files::TextPreferences::*value; + const wchar_t *name; +} textChecks[]{ + {350,&ks::files::TextPreferences::wrap,L"Wrap lines"}, + {351,&ks::files::TextPreferences::numbers,L"Line numbers"}, + {352,&ks::files::TextPreferences::whitespace,L"Show whitespace and line endings"}, + {353,&ks::files::TextPreferences::caretLine,L"Highlight current line"}, + {354,&ks::files::TextPreferences::tabsAsSpaces,L"Insert spaces for tabs"}, + {355,&ks::files::TextPreferences::autoIndent,L"Auto indent"}}; + +bool textOptionsPage(int page) { return page==TextViewer || page==TextEditor; } constexpr struct { int id; @@ -63,11 +81,14 @@ struct OptionsBaseline DWORD width=static_cast(sizeWidth), fields=statusFields; bool extensions=alignExtensions, folders=alignFolders, details=showDetails; std::array wide{panels[0].wide,panels[1].wide}; + ks::files::TextSettings text=ks::files::loadTextPreferences(); }; struct OptionsDraft { OptionsBaseline baseline; + ks::files::TextSettings text=baseline.text; + HWND filesWindow{}; LOGFONTW font=displayFont; int points=fontPoints; DialogFramePadding framePadding=dialogFramePadding; @@ -130,7 +151,7 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft) 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; + optionHistoryKeys(dialog)!=base.keys || draft.text!=base.text; EnableWindow(GetDlgItem(dialog,optionsApply),dirty); InvalidateRect(GetDlgItem(dialog,fileStylePreview),nullptr,FALSE); } @@ -192,12 +213,167 @@ void layoutOptions(HWND dialog,const OptionsDraft &draft) SetWindowPos(GetDlgItem(dialog,control.id),nullptr,x,y,width,height, SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOREDRAW); } + groupDialogButtons(dialog,{IDOK,IDCANCEL,optionsApply},true); if(draft.page==PanelColors && draft.section==fileStyleSection) layoutFileStyleFields(dialog,false); layoutOptionsPreview(dialog); // Paint the final layout together, including the areas vacated by moved controls. RedrawWindow(dialog,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN|RDW_UPDATENOW); } +void refreshTextColor(HWND dialog,const ks::files::TextPreferences &profile) +{ + const auto index=SendDlgItemMessageW(dialog,textColor,CB_GETCURSEL,0,0); + if(index<0 || static_cast(index)>=profile.colors.size()) return; + const auto color=profile.colors[index]; + wchar_t hex[8]{}; + swprintf_s(hex,L"#%02X%02X%02X",unsigned(GetRValue(color)),unsigned(GetGValue(color)),unsigned(GetBValue(color))); + SetDlgItemTextW(dialog,textColorValue,hex); +} + +bool sameSchemeName(const std::wstring &left,const wchar_t *right) +{ + return CompareStringOrdinal(left.c_str(),-1,right,-1,TRUE)==CSTR_EQUAL; +} + +void populateTextSchemes(HWND dialog,const ks::files::TextSettings &settings) +{ + SendDlgItemMessageW(dialog,textTheme,CB_RESETCONTENT,0,0); + const auto add=[&](const wchar_t *name) + { + SendDlgItemMessageW(dialog,textTheme,CB_ADDSTRING,0,reinterpret_cast(name)); + }; + add(L"Custom"); + for(const auto name:ks::files::textPaletteNames) add(name); + for(const auto &scheme:settings.schemes) add(scheme.name.c_str()); +} + +size_t currentTextScheme(const ks::files::TextSettings &settings,const ks::files::TextPreferences &profile) +{ + for(size_t index=0;index(std::size(text))); + std::wstring name=text; + const auto first=name.find_first_not_of(L" \t"); + if(first==name.npos) { MessageBeep(MB_ICONWARNING); return TRUE; } + *reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER))= + name.substr(first,name.find_last_not_of(L" \t")-first+1); + FilesModalDialog::finish(dialog,IDOK); + return TRUE; +} + +void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,ks::files::TextPreferences &profile) +{ + std::wstring name; + if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(608),dialog,schemeNameDialog, + reinterpret_cast(&name))!=IDOK) return; + if(sameSchemeName(name,L"Custom") || std::any_of(std::begin(ks::files::textPaletteNames), + std::end(ks::files::textPaletteNames),[&](const wchar_t *preset){return sameSchemeName(name,preset);})) + { + showFilesNotice(dialog,L"Choose a different name for your color scheme.",L"Save color scheme"); + return; + } + const auto existing=std::find_if(settings.schemes.begin(),settings.schemes.end(), + [&](const auto &scheme){return sameSchemeName(name,scheme.name.c_str());}); + if(existing!=settings.schemes.end()) + { + if(showFilesNotice(dialog,L"Replace the saved scheme with the current colors?",L"Save color scheme",true)!=IDYES) return; + existing->colors=profile.colors; + profile.scheme=existing->name; + } + else + { + if(settings.schemes.size()>=ks::files::maxTextPalettes) + { + showFilesNotice(dialog,L"The color scheme list is full.",L"Save color scheme"); + return; + } + settings.schemes.push_back({name,profile.colors}); + profile.scheme=std::move(name); + } + populateTextSchemes(dialog,settings); +} + +void showTextOptions(HWND dialog,const ks::files::TextSettings &settings,const ks::files::TextPreferences &profile) +{ + for(const auto &check:textChecks) CheckDlgButton(dialog,check.id,profile.*check.value?BST_CHECKED:BST_UNCHECKED); + SendDlgItemMessageW(dialog,textTabWidth,CB_SETCURSEL,profile.tabWidth-1,0); + SendDlgItemMessageW(dialog,textLineEnding,CB_SETCURSEL,profile.lineEnding,0); + SendDlgItemMessageW(dialog,textTheme,CB_SETCURSEL,currentTextScheme(settings,profile),0); + refreshTextColor(dialog,profile); +} + +bool changeTextOption(HWND dialog,OptionsDraft &draft,WPARAM command) +{ + if(!textOptionsPage(draft.page)) return false; + auto &profile=draft.text.profiles[draft.page==TextEditor]; + const auto id=LOWORD(command); + const auto row=[&](int control){return SendDlgItemMessageW(dialog,control,CB_GETCURSEL,0,0);}; + if(const auto check=std::find_if(std::begin(textChecks),std::end(textChecks), + [id](const auto &entry){return entry.id==id;});check!=std::end(textChecks)) + profile.*check->value=IsDlgButtonChecked(dialog,id)==BST_CHECKED; + else if(id==textSaveScheme) saveTextSchemeDraft(dialog,draft.text,profile); + else if(id==textChangeColor) + { + const auto index=row(textColor); + if(index>=0 && static_cast(index)(selected)+1; break; + case textLineEnding: profile.lineEnding=static_cast(selected); break; + case textTheme: + if(selected==0) profile.scheme.clear(); + else if(const auto scheme=static_cast(selected-1);scheme=draft.text.schemes.size()) return false; + profile.scheme=draft.text.schemes[index].name; + profile.colors=draft.text.schemes[index].colors; + } + break; + default: return false; + } + } + else return false; + showTextOptions(dialog,draft.text,profile); + updateOptionsApply(dialog,draft); + return true; +} + void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section) { draft.page=page; @@ -207,7 +383,7 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section) else if(page>=0) { title=optionsTitles[page]; - if(section>=0) + if(section>=0 && !textOptionsPage(page)) 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"; @@ -246,6 +422,9 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section) } constexpr int commandLineControls[]{320,321,322,323}; show(commandLineControls,page==CommandLine && section==0); + show(textControls,textOptionsPage(page)); + show(editingControls,page==TextEditor); + if(textOptionsPage(page)) showTextOptions(dialog,draft.text,draft.text.profiles[page==TextEditor]); const bool fileTypes=page==PanelColors && section==fileStyleSection; constexpr int fileStyleControls[]{287,288,289,290,291,292,293,294,295,296,297,298,300,fileStyleState}; show(fileStyleControls,fileTypes); @@ -306,7 +485,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<=CommandLine;++page) + for(int page=PanelModes;page(std::to_wstring(value).c_str())); + for(int width=1;width<=16;++width) + SendDlgItemMessageW(dialog,textTabWidth,CB_ADDSTRING,0,reinterpret_cast(std::to_wstring(width).c_str())); + for(const auto label:{L"Automatic",L"Windows (CRLF)",L"Unix (LF)",L"Classic Mac (CR)"}) + SendDlgItemMessageW(dialog,textLineEnding,CB_ADDSTRING,0,reinterpret_cast(label)); + populateTextSchemes(dialog,draft.text); + for(const auto label:ks::files::textColorNames) + SendDlgItemMessageW(dialog,textColor,CB_ADDSTRING,0,reinterpret_cast(label)); + SendDlgItemMessageW(dialog,textColor,CB_SETCURSEL,0,0); CheckDlgButton(dialog,202,alignExtensions); CheckDlgButton(dialog,203,showDetails); CheckDlgButton(dialog,204,alignFolders); @@ -421,10 +618,11 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) } if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL)) { - finishFilesDialog(dialog,IDCANCEL); + FilesModalDialog::finish(dialog,IDCANCEL); return TRUE; } if(message!=WM_COMMAND) return FALSE; + if(changeTextOption(dialog,*draft,wp)) return TRUE; switch(LOWORD(wp)) { case optionsSearch: @@ -512,6 +710,10 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) } if(draft->page==allOptions || (draft->page==Appearance && draft->section!=Font)) draft->framePadding=defaultDialogFramePadding; + if(draft->page==allOptions || textOptionsPage(draft->page)) + for(int page=TextViewer;page<=TextEditor;++page) + if(draft->page==allOptions || draft->page==page) + draft->text.profiles[page==TextEditor]=ks::files::TextPreferences{}; showOptionsPage(dialog,*draft,draft->page,draft->section); updateOptionsApply(dialog,*draft); return TRUE; @@ -544,12 +746,12 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) { SetDlgItemTextW(dialog,optionsSearch,L""); TreeView_SelectItem(GetDlgItem(dialog,optionsTree),draft->wideColumnsNode); - MessageBoxW(dialog,L"Enter a width from 6 to 16 characters.",optionsTitles[PanelModes],MB_OK|MB_ICONWARNING); + showFilesNotice(dialog,L"Enter a width from 6 to 16 characters.",optionsTitles[PanelModes]); SetFocus(GetDlgItem(dialog,201)); SendDlgItemMessageW(dialog,201,EM_SETSEL,0,-1); return TRUE; } - const auto owner=GetWindow(dialog,GW_OWNER); + const auto owner=draft->filesWindow; const OptionsWriteLock writeLock; if(!writeLock.acquired()) { @@ -557,35 +759,70 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) return TRUE; } const auto &base=draft->baseline; + const bool textChanged=draft->text!=base.text; + auto textSettings=ks::files::loadTextPreferences(); + for(size_t i=0;itext.profiles[i]==base.text.profiles[i]) continue; + if(textSettings.profiles[i]!=base.text.profiles[i] && textSettings.profiles[i]!=draft->text.profiles[i]) + { + showFilesNotice(dialog,L"Text settings changed in another window. Reopen Options before editing them again.", + L"KSwitcher Files Options"); + return TRUE; + } + textSettings.profiles[i]=draft->text.profiles[i]; + } + if(draft->text.schemes!=base.text.schemes) + { + if(textSettings.schemes!=base.text.schemes && textSettings.schemes!=draft->text.schemes) + { + showFilesNotice(dialog,L"Color schemes changed in another window. Reopen Options before editing them again.", + L"KSwitcher Files Options"); + return TRUE; + } + textSettings.schemes=draft->text.schemes; + } auto keys=optionHistoryKeys(dialog); loadCommandHistoryKeys(); for(size_t i=0;istyles!=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); + showFilesNotice(dialog,L"File type styles changed in another window. Reopen Options before editing them again.", + L"KSwitcher Files Options"); 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); + showFilesNotice(dialog,L"Could not save the file type styles.",L"KSwitcher Files Options"); return TRUE; } const bool fontChanged=optionsFontChanged(*draft); if(fontChanged && !applyFont(owner,draft->font,draft->points)) { if(stylesChanged) saveFileStyles(fileStyles); - MessageBoxW(dialog,L"Could not apply the selected font.",optionsTitles[Appearance],MB_OK|MB_ICONWARNING); + showFilesNotice(dialog,L"Could not apply the selected font.",optionsTitles[Appearance]); return TRUE; } + if(textChanged) + { + try { ks::files::saveTextPreferences(textSettings); } + catch(const std::exception &error) + { + if(fontChanged) applyFont(owner,base.font,base.points); + if(stylesChanged) saveFileStyles(fileStyles); + const auto message=L"Could not save text settings. "+ks::wide(error.what()); + showFilesNotice(dialog,message.c_str(),L"KSwitcher Files Options"); + return TRUE; + } + } const auto saveChanged=[](const wchar_t *name,DWORD value,DWORD initial) { if(value!=initial) savePreference(name,value); @@ -620,7 +857,12 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) saveChanged(L"RightWide",checked(274),base.wide[1]); loadFilesPreferences(owner); notifyFilesPreferences(owner); + const auto dialogOwner=GetWindow(dialog,GW_OWNER); + if(dialogOwner!=owner) + SendMessageW(dialogOwner,filesPreferencesChanged,reinterpret_cast(owner),0); draft->baseline=OptionsBaseline{}; + draft->text=draft->baseline.text; + populateTextSchemes(dialog,draft->text); draft->font=displayFont; draft->points=fontPoints; draft->styles=fileStyles; @@ -640,7 +882,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) layout(owner); showFileDetails(panels[active]); RedrawWindow(owner,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN|RDW_UPDATENOW); - if(LOWORD(wp)==IDOK) finishFilesDialog(dialog,IDOK); + if(LOWORD(wp)==IDOK) FilesModalDialog::finish(dialog,IDOK); else updateOptionsApply(dialog,*draft); return TRUE; } @@ -648,13 +890,25 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) return FALSE; } -void editOptions(HWND owner) +void runOptions(HWND owner,int page) { - const auto panel=panels[active].list; OptionsDraft draft; + draft.filesWindow=GetAncestor(owner,GA_ROOTOWNER); + draft.page=page; + draft.section=textOptionsPage(page)?0:PanelLayout; std::copy(std::begin(colors),std::end(colors),draft.palette.begin()); - const auto result=runFilesDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(101),owner,optionsDialog, + const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(101),owner,optionsDialog, reinterpret_cast(&draft)); - SetFocus(panel); if(result==-1) setStatus(L"Could not open Files Options."); } + +void editOptions(HWND owner) +{ + runOptions(owner,PanelModes); + SetFocus(panels[active].list); +} + +void editTextOptions(HWND owner,bool edit) +{ + runOptions(owner,edit?TextEditor:TextViewer); +} diff --git a/src/files_style_options.inl b/src/files_style_options.inl index 356ee37..7f41fcb 100644 --- a/src/files_style_options.inl +++ b/src/files_style_options.inl @@ -127,7 +127,7 @@ bool addFileStyle(HWND dialog,OptionsDraft &draft) const auto extension=fileStyleExtension(input); if(extension.empty()) { - MessageBoxW(dialog,L"Enter a file extension such as .txt.",L"File type styles",MB_OK|MB_ICONWARNING); + showFilesNotice(dialog,L"Enter a file extension such as .txt.",L"File type styles"); SetFocus(GetDlgItem(dialog,fileStyleSuggestion)); return false; } @@ -138,7 +138,7 @@ bool addFileStyle(HWND dialog,OptionsDraft &draft) { if(draft.styles.size()>=64) { - MessageBoxW(dialog,L"The profile can contain up to 64 file type rules.",L"File type styles",MB_OK|MB_ICONWARNING); + showFilesNotice(dialog,L"The profile can contain up to 64 file type rules.",L"File type styles"); return false; } draft.styles.push_back({extension}); diff --git a/src/files_text_document.cpp b/src/files_text_document.cpp new file mode 100644 index 0000000..b69cfc7 --- /dev/null +++ b/src/files_text_document.cpp @@ -0,0 +1,323 @@ +#include "files_text_document.h" + +#include +#include +#include +#include +#include +#include + +namespace ks::files +{ +namespace +{ +[[noreturn]] void fail(const char *operation) +{ + throw std::system_error(static_cast(GetLastError()), std::system_category(), operation); +} + +struct File +{ + HANDLE handle = INVALID_HANDLE_VALUE; + ~File() { if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle); } + HANDLE release() { return std::exchange(handle, INVALID_HANDLE_VALUE); } +}; + +struct PendingSave +{ + std::filesystem::path path; + ~PendingSave() { if (!path.empty()) DeleteFileW(path.c_str()); } +}; + +HANDLE openSource(const std::filesystem::path &path, bool editable) +{ + const auto sharing = FILE_SHARE_READ | FILE_SHARE_DELETE | (editable ? 0 : FILE_SHARE_WRITE); + const auto result = CreateFileW(path.c_str(), GENERIC_READ, sharing, + nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (result == INVALID_HANDLE_VALUE) fail("Open file"); + return result; +} + +uint64_t fileSize(HANDLE file) +{ + LARGE_INTEGER size{}; + if (!GetFileSizeEx(file, &size)) fail("Read file size"); + return size.QuadPart; +} + +void seek(HANDLE file, uint64_t offset) +{ + LARGE_INTEGER position{}; + position.QuadPart = static_cast(offset); + if (!SetFilePointerEx(file, position, nullptr, FILE_BEGIN)) fail("Seek"); +} + +std::string read(HANDLE file, uint64_t offset, size_t length) +{ + if (!length) return {}; + seek(file, offset); + std::string result(length, '\0'); + DWORD count{}; + if (!ReadFile(file, result.data(), static_cast(length), &count, nullptr)) fail("Read file"); + if (count != length) throw std::runtime_error("The file ended unexpectedly."); + return result; +} + +void write(HANDLE file, std::string_view bytes) +{ + if (bytes.empty()) return; + DWORD written{}; + if (!WriteFile(file, bytes.data(), static_cast(bytes.size()), &written, nullptr)) + fail("Write file"); + if (written != bytes.size()) throw std::runtime_error("The complete block could not be written."); +} + +bool sameFile(HANDLE a, HANDLE b) +{ + BY_HANDLE_FILE_INFORMATION first{}, second{}; + if (!GetFileInformationByHandle(a, &first) || !GetFileInformationByHandle(b, &second)) + fail("Check file identity"); + return first.dwVolumeSerialNumber == second.dwVolumeSerialNumber && + first.nFileIndexHigh == second.nFileIndexHigh && first.nFileIndexLow == second.nFileIndexLow; +} + +std::filesystem::path temporaryPath(const std::filesystem::path &directory) +{ + GUID id{}; + wchar_t name[40]{}; + if (FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id, name, 40)) + throw std::runtime_error("Cannot create a temporary file name."); + return directory / (std::wstring(L".kswitcher-") + name + L".tmp"); +} + +std::filesystem::path createTemporary(const std::filesystem::path &directory, File &file, DWORD flags) +{ + auto path = temporaryPath(directory); + file.handle = CreateFileW(path.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, CREATE_NEW, flags, nullptr); + if (file.handle == INVALID_HANDLE_VALUE) fail("Create temporary file"); + return path; +} +} + +TextDocument::TextDocument(std::filesystem::path path, bool editable) : path_(std::move(path)), editable_(editable) +{ + File source{openSource(path_, editable)}; + if (editable) + { + std::wstring resolved(32768, L'\0'); + const auto length = GetFinalPathNameByHandleW(source.handle, resolved.data(), + static_cast(resolved.size()), FILE_NAME_NORMALIZED | VOLUME_NAME_DOS); + if (length && length < resolved.size()) + { + resolved.resize(length); + path_ = resolved; + } + } + size_ = fileSize(source.handle); + const auto prefix = read(source.handle, 0, static_cast(std::min(3, size_))); + if (prefix.starts_with("\xef\xbb\xbf")) bom_ = 3; + else if (prefix.starts_with("\xff\xfe") || prefix.starts_with("\xfe\xff")) + { + encoding_ = prefix.starts_with("\xff") ? Encoding::utf16le : Encoding::utf16be; + bom_ = 2; + if (size_ % 2) throw std::runtime_error("The UTF-16 file has an incomplete code unit."); + } + source_ = source.release(); +} + +TextDocument::~TextDocument() +{ + if (source_ != INVALID_HANDLE_VALUE) CloseHandle(source_); + if (spool_ != INVALID_HANDLE_VALUE) CloseHandle(spool_); +} + +const wchar_t *TextDocument::encodingName() const +{ + switch (encoding_) + { + case Encoding::utf16le: return L"UTF-16 LE"; + case Encoding::utf16be: return L"UTF-16 BE"; + default: return bom_ ? L"UTF-8 BOM" : L"UTF-8"; + } +} + +uint64_t TextDocument::pages() const +{ + return std::max(1, (size_ - bom_ + pageBytes - 1) / pageBytes); +} + +uint64_t TextDocument::boundary(uint64_t page) const +{ + if (!page) return bom_; + if (page >= pages()) return size_; + + const auto offset = bom_ + page * pageBytes; + const auto unit = encoding_ == Encoding::utf8 ? 1u : 2u; + const auto sample = read(source_, offset - unit, + static_cast(std::min(4096 + unit, size_ - offset + unit))); + const auto getUnit = [&](size_t i) -> unsigned { + const auto first = static_cast(sample[i]); + if (unit == 1) return first; + const auto second = static_cast(sample[i + 1]); + return encoding_ == Encoding::utf16le ? first | (second << 8) : (first << 8) | second; + }; + if (getUnit(0) == '\n') return offset; + for (size_t i = unit; i + unit < sample.size(); i += unit) + if (getUnit(i) == '\n') return offset + i; + + size_t i = unit; + if (unit == 1) + { + // Advance past at most one UTF-8 code point, even on malformed input. + while (i < sample.size() && i <= 3 && (getUnit(i) & 0xc0) == 0x80) ++i; + } + else if (const auto value = getUnit(i); value >= 0xdc00 && value <= 0xdfff) i += unit; + if (i == unit && getUnit(0) == '\r' && getUnit(i) == '\n') i += unit; + return offset + i - unit; +} + +std::string TextDocument::decode(std::string bytes) const +{ + if (encoding_ == Encoding::utf8 || bytes.empty()) return bytes; + std::wstring units; + units.resize(bytes.size() / 2); + for (size_t i = 0; i < units.size(); ++i) + { + const auto a = static_cast(bytes[2 * i]); + const auto b = static_cast(bytes[2 * i + 1]); + units[i] = static_cast(encoding_ == Encoding::utf16le ? a | (b << 8) : (a << 8) | b); + } + const auto length = static_cast(units.size()); + const int required = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, units.data(), length, nullptr, 0, nullptr, nullptr); + if (!required) fail("Decode UTF-16"); + std::string result(required, '\0'); + if (!WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, units.data(), length, result.data(), required, nullptr, nullptr)) + fail("Decode UTF-16"); + return result; +} + +std::string TextDocument::encode(std::string_view utf8) const +{ + if (encoding_ == Encoding::utf8 || utf8.empty()) return std::string(utf8); + const auto length = static_cast(utf8.size()); + const int required = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.data(), length, nullptr, 0); + if (!required) fail("Encode UTF-16"); + std::wstring units(required, L'\0'); + if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.data(), length, units.data(), required)) + fail("Encode UTF-16"); + std::string bytes(units.size() * 2, '\0'); + const int low = encoding_ == Encoding::utf16le ? 0 : 1; + for (size_t i = 0; i < units.size(); ++i) + { + bytes[2 * i + low] = static_cast(units[i] & 0xff); + bytes[2 * i + 1 - low] = static_cast(units[i] >> 8); + } + return bytes; +} + +std::string TextDocument::readPage(uint64_t page) const +{ + if (const auto it = changes_.find(page); it != changes_.end()) + return read(spool_, it->second.offset, it->second.size); + return readOriginal(page); +} + +std::string TextDocument::readOriginal(uint64_t page) const +{ + const auto start = boundary(page); + return decode(read(source_, start, static_cast(boundary(page + 1) - start))); +} + +bool TextDocument::modifiedWith(uint64_t page, std::string_view current) const +{ + const size_t changesOnPage = changes_.contains(page) ? 1 : 0; + return changes_.size() > changesOnPage || current != readOriginal(page); +} + +void TextDocument::stage(uint64_t page, std::string_view utf8) +{ + if (!editable_) throw std::logic_error("The file is open for viewing."); + if (utf8.size() > editLimit) throw std::runtime_error("The edit exceeds 8 MiB on this page."); + if (utf8 == readOriginal(page)) + { + changes_.erase(page); + return; + } + if (spool_ == INVALID_HANDLE_VALUE) + { + wchar_t directory[32768]{}; + const auto length = GetTempPathW(static_cast(std::size(directory)), directory); + if (!length || length >= std::size(directory)) fail("Locate temporary directory"); + File file; + createTemporary(directory, file, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE); + spool_ = file.release(); + } + seek(spool_, spoolSize_); + write(spool_, utf8); + changes_.insert_or_assign(page, Change{spoolSize_, utf8.size()}); + spoolSize_ += utf8.size(); +} + +bool TextDocument::save() +{ + if (!modified()) return true; + PendingSave pending; + File output; + pending.path = createTemporary(path_.parent_path(), output, FILE_ATTRIBUTE_NORMAL); + + uint64_t written{}; + const auto append = [&](std::string_view bytes) { + write(output.handle, bytes); + written += bytes.size(); + }; + const auto copyUntil = [&](uint64_t &offset, uint64_t end) { + while (offset < end) + { + const auto block = read(source_, offset, static_cast(std::min(pageBytes, end - offset))); + append(block); + offset += block.size(); + } + }; + uint64_t offset{}; + for (const auto &[page, change] : changes_) + { + copyUntil(offset, boundary(page)); + append(encode(read(spool_, change.offset, change.size))); + offset = boundary(page + 1); + } + copyUntil(offset, size_); + if (!FlushFileBuffers(output.handle)) fail("Flush saved file"); + CloseHandle(output.release()); + + // A metadata-only handle survives the rename without blocking ReplaceFile's exclusive open. + File replacement{CreateFileW(pending.path.c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)}; + if (replacement.handle == INVALID_HANDLE_VALUE) fail("Track replacement file"); + File current{openSource(path_, true)}; + if (!sameFile(source_, current.handle)) throw std::runtime_error("The file was replaced outside KSwitcher."); + const auto backup = temporaryPath(path_.parent_path()); + if (!ReplaceFileW(path_.c_str(), pending.path.c_str(), backup.c_str(), 0, nullptr, nullptr)) + { + const auto error = GetLastError(); + if (GetFileAttributesW(backup.c_str()) != INVALID_FILE_ATTRIBUTES && + !MoveFileExW(backup.c_str(), path_.c_str(), MOVEFILE_WRITE_THROUGH)) + { + const auto location = backup.u8string(); + throw std::runtime_error("Could not restore the original name after a save error. The original is at " + + std::string(location.begin(), location.end())); + } + SetLastError(error); + fail("Replace original file"); + } + pending.path.clear(); + const auto newSource = ReOpenFile(replacement.handle, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, 0); + DeleteFileW(backup.c_str()); + CloseHandle(source_); + source_ = newSource; + size_ = written; + changes_.clear(); + if (spool_ != INVALID_HANDLE_VALUE) CloseHandle(std::exchange(spool_, INVALID_HANDLE_VALUE)); + spoolSize_ = 0; + return source_ != INVALID_HANDLE_VALUE; +} +} diff --git a/src/files_text_document.h b/src/files_text_document.h new file mode 100644 index 0000000..9a7bedb --- /dev/null +++ b/src/files_text_document.h @@ -0,0 +1,50 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace ks::files +{ +class TextDocument +{ +public: + static constexpr uint64_t pageBytes = 1024 * 1024; + static constexpr size_t editLimit = 8 * pageBytes; + + explicit TextDocument(std::filesystem::path path, bool editable = true); + ~TextDocument(); + TextDocument(const TextDocument &) = delete; + TextDocument &operator=(const TextDocument &) = delete; + + uint64_t pages() const; + uint64_t size() const { return size_; } + uint64_t boundary(uint64_t page) const; + std::string readPage(uint64_t page) const; + void stage(uint64_t page, std::string_view utf8); + bool modified() const { return !changes_.empty(); } + bool modifiedWith(uint64_t page, std::string_view current) const; + bool save(); + const wchar_t *encodingName() const; + +private: + enum class Encoding { utf8, utf16le, utf16be }; + struct Change { uint64_t offset; size_t size; }; + + std::filesystem::path path_; + HANDLE source_ = INVALID_HANDLE_VALUE; + HANDLE spool_ = INVALID_HANDLE_VALUE; + uint64_t size_{}, spoolSize_{}; + size_t bom_{}; + Encoding encoding_ = Encoding::utf8; + bool editable_; + std::map changes_; + + std::string decode(std::string bytes) const; + std::string readOriginal(uint64_t page) const; + std::string encode(std::string_view utf8) const; +}; +} diff --git a/src/files_text_language.cpp b/src/files_text_language.cpp new file mode 100644 index 0000000..25e5958 --- /dev/null +++ b/src/files_text_language.cpp @@ -0,0 +1,270 @@ +#include "files_text_language.h" +#include "core.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace ks::files +{ +namespace +{ +constexpr char cpp[] = "alignas alignof asm auto bool break case catch char char8_t char16_t char32_t class concept const " + "consteval constexpr constinit const_cast continue co_await co_return co_yield decltype default delete do double " + "dynamic_cast else enum explicit export extern false float for friend goto if inline int long mutable namespace " + "new noexcept nullptr operator private protected public register reinterpret_cast requires return short signed " + "sizeof static static_assert static_cast struct switch template this thread_local throw true try typedef typeid " + "typename union unsigned using virtual void volatile wchar_t while import module"; +constexpr char csharp[] = "abstract as async await base bool break byte case catch char checked class const continue " + "decimal default delegate do double else enum event explicit extern false file finally fixed float for foreach from " + "get global goto if implicit in init int interface internal is let lock long namespace new not null object operator " + "or out override partial private protected public readonly record ref required return sbyte sealed select set short " + "sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unmanaged unsafe " + "ushort using value var virtual void volatile when where while with yield"; +constexpr char javascript[] = "abstract any as async await boolean break case catch class const continue debugger declare " + "default delete do else enum export extends false finally for from function get if implements import in infer " + "instanceof interface keyof let module namespace never new null number object of override private protected public " + "readonly return satisfies set static string super switch symbol this throw true try type typeof undefined unknown " + "using var void while with yield"; +constexpr char java[] = "abstract assert boolean break byte case catch char class const continue default do double else " + "enum exports extends final finally float for if implements import instanceof int interface long module native new " + "non-sealed null open opens package permits private protected public record requires return sealed short static super " + "switch synchronized this throw throws transient true try var void volatile while yield false"; +constexpr char sql[] = "add alter and any as asc begin between by case check column commit constraint create cross " + "database declare default delete desc distinct drop else end except exists fetch foreign from full function grant " + "group having in index inner insert intersect into is join left like limit merge not null offset on or order outer " + "over partition primary procedure references returning right rollback row select set table then top transaction " + "truncate union unique update using values view when where window with"; +constexpr char python[] = "and as assert async await break class continue def del elif else except False finally for from " + "global if import in is lambda match case None nonlocal not or pass raise return True try while with yield"; +constexpr char ps[] = "begin break catch class continue data define do dynamicparam else elseif end enum exit filter finally " + "for foreach from function if in param process return switch throw trap try until using var while workflow"; +constexpr char shell[] = "alias bg break case cd continue declare do done echo elif else esac eval exec exit export " + "false fi for function if in local read readonly return select set shift source test then time trap true type " + "typeset ulimit umask unalias unset until wait while"; +constexpr char rust[] = "as async await break const continue crate dyn else enum extern false fn for if impl in let loop " + "match mod move mut pub ref return self Self static struct super trait true type unsafe use where while"; +constexpr char go[] = "break case chan const continue default defer else fallthrough for func go goto if import interface " + "map package range return select struct switch type var nil false true"; +constexpr char lua[] = "and break do else elseif end false for function goto if in local nil not or repeat return then true until while"; +constexpr char ruby[] = "BEGIN END alias and begin break case class def defined do else elsif end ensure false for if in " + "module next nil not or redo rescue retry return self super then true undef unless until when while yield"; +constexpr char html[] = "a abbr address area article aside audio b base bdi bdo blockquote body br button canvas caption " + "cite code col colgroup data datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer " + "form h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe img input ins kbd label legend li link main map mark " + "menu meta meter nav noscript object ol optgroup option output p picture pre progress q rp rt ruby s samp script " + "search section select slot small source span strong style sub summary sup table tbody td template textarea tfoot " + "th thead time title tr track u ul var video wbr accept action alt aria-label async cellpadding charset checked cite " + "class content controls defer disabled for height href http-equiv id lang maxlength method multiple name placeholder " + "readonly rel required role rows scope selected src srcset style tabindex target type value width"; + +struct Mapping +{ + std::wstring_view names; + const char *lexer; + const char *keywords = ""; +}; +constexpr Mapping languages[] = { + {L".c .h .cc .cpp .cxx .hh .hpp .hxx .inl .ipp .ixx .cppm .cu .cuh .m .mm .rc .idl .ino", "cpp", cpp}, + {L".cs .csx .razor.cs", "cpp", csharp}, + {L".js .jsx .mjs .cjs .ts .tsx .mts .cts .es", "cpp", javascript}, + {L".java .pde", "cpp", java}, + {L".kt .kts", "cpp", "abstract actual as break by catch class companion const constructor continue data do else enum " + "expect false finally for fun if import in init interface internal is lateinit null object open operator out " + "override package private protected public return sealed super suspend this throw true try typealias val var when while"}, + {L".glsl .vert .frag .geom .hlsl .fx .metal", "cpp", cpp}, + {L".html .htm .xhtml .shtml .vue .svelte .astro .cshtml .razor .aspx .jsp .php .phtml", "hypertext", html}, + {L".xml .xsl .xslt .xsd .svg .resx .xaml .csproj .fsproj .vbproj .vcxproj .props .targets .config .nuspec " + L".wixproj .wxs .plist .rss .atom .gpx .kml .ui .iml .wsdl .manifest .slnx .axaml", "xml"}, + {L".css .scss .sass .less", "css", "color background display position width height margin padding border font " + "grid flex content gap box-shadow transform animation opacity overflow text-align align-items justify-content"}, + {L".sql .psql .ddl .dml .mysql", "sql", sql}, + {L".py .pyw .pyi .rpy sconstruct sconscript", "python", python}, + {L".json .jsonc .json5 .ipynb .webmanifest .geojson .topojson .code-workspace .sublime-settings .sublime-project", + "json", "false null true Infinity NaN"}, + {L".yaml .yml .eyaml .clang-format .clang-tidy", "yaml", "true false null yes no on off"}, + {L".toml pipfile uv.lock cargo.lock poetry.lock", "toml", "true false"}, + {L".md .markdown .mdown .mkd .mdx readme", "markdown"}, + {L".adoc .asciidoc", "asciidoc"}, + {L".ini .cfg .conf .properties .url .inf .reg .editorconfig .gitconfig .gitattributes .gitmodules .npmrc .env", "props"}, + {L".sh .bash .zsh .ksh .bats .bashrc .bash_profile .zshrc .profile configure gradlew mvnw", "bash", shell}, + {L".ps1 .psm1 .psd1", "powershell", ps}, + {L".bat .cmd", "batch", "call cd chdir cls copy del dir echo endlocal exit for goto if md mkdir move path pause popd " + "pushd rd rem ren rename set setlocal shift start title type"}, + {L".cmake cmakelists.txt", "cmake", "add_executable add_library add_subdirectory cmake_minimum_required " + "configure_file else elseif endforeach endfunction endif endwhile file find_package foreach function if include " + "install list message option project set string target_compile_definitions target_include_directories " + "target_link_libraries unset while"}, + {L".mk .mak makefile gnumakefile", "makefile"}, + {L".rs", "rust", rust}, {L".go", "cpp", go}, {L".lua", "lua", lua}, {L".rb .rake .gemspec gemfile rakefile", "ruby", ruby}, + {L".dart", "dart", "abstract as assert async await break case class const continue default do else enum extends " + "false final finally for if implements import in interface late mixin new null on override return sealed static " + "super switch this throw true try typedef var void while with yield"}, + {L".swift", "cpp", "actor as associatedtype await break case catch class continue default defer deinit do else " + "enum extension false for func guard if import in init let nil private protocol public return self some " + "static struct super switch throw throws true try typealias var where while"}, + {L".zig", "zig"}, {L".d .di", "d"}, {L".nim .nims .nimble", "nim"}, + {L".fs .fsi .fsx", "fsharp"}, {L".ml .mli", "caml"}, {L".sml .sig", "SML"}, + {L".vb .bas .frm .cls", "vb", "as byref byval class const dim each else elseif end enum for function if implements " + "imports inherits interface module new next nothing private property public return select shared sub then try while"}, + {L".vbs", "vbscript"}, {L".pl .pm .t", "perl"}, {L".r .rprofile", "r"}, + {L".jl", "julia"}, {L".matlab", "matlab"}, {L".oct", "octave"}, + {L".tex .sty .ltx", "latex"}, {L".bib", "bib"}, {L".hs", "haskell"}, {L".lhs", "literatehaskell"}, + {L".lisp .lsp .cl .el .scm .ss .rkt", "lisp"}, + {L".s .asm .nasm .inc", "asm"}, {L".a68k", "a68k"}, + {L".v .vh .sv .svh", "verilog"}, {L".vhd .vhdl", "vhdl"}, + {L".f .for .f77", "f77"}, {L".f90 .f95 .f03 .f08", "fortran"}, + {L".ada .adb .ads", "ada"}, {L".pas .pp .dpr", "pascal"}, {L".cob .cbl .cpy", "COBOL"}, + {L".tcl .tk", "tcl"}, {L".coffee .litcoffee", "coffeescript"}, {L".au3", "au3"}, + {L".st", "smalltalk"}, {L".erl .hrl", "erlang"}, + {L".purs", "haskell"}, {L".diff .patch", "diff"}, {L".po .pot", "po"}, + {L".iss", "inno"}, {L".nsi .nsh", "nsis"}, {L".idl3 .odl", "cpp", cpp}, + {L".dmap", "DMAP"}, {L".dns .zone", "props"}, {L".ihex .hex", "ihex"}, {L".srec .s19 .s28 .s37", "srec"}, + {L".edifact .edi", "edifact"}, {L".x12", "x12"}, {L".g4", "cpp", java}, + {L".nix", "nix"}, {L".gd", "gdscript", python}, {L".il", "cil"}, {L".as", "cpp", javascript}, + {L".frt .fth", "forth"}, {L".e .eif", "eiffel"}, {L".pov .povray", "pov"}, + {L".rebol .reb", "rebol"}, {L".asn .asn1", "asn1"}, {L".asy", "asy"}, + {L".raku .rakumod .rakutest .p6 .pm6", "raku"}, {L".bb", "blitzbasic"}, {L".bi", "freebasic"}, + {L".t2t", "txt2tags"}, {L".troff .roff .man", "troff"}, + {L".clw", "clarion"}, {L".spice .cir", "spice"}, +}; + +bool containsWord(std::wstring_view words, std::wstring_view key) +{ + if (key.empty()) return false; + for (size_t start = 0; start < words.size();) + { + const auto end = words.find(L' ', start); + if (words.substr(start, end == words.npos ? end : end - start) == key) return true; + if (end == words.npos) break; + start = end + 1; + } + return false; +} +} + +TextLanguage detectLanguage(const std::filesystem::path &path, std::string_view firstPage) +{ + auto filename = path.filename().wstring(); + auto extension = path.extension().wstring(); + for (auto *value : {&filename, &extension}) + std::transform(value->begin(), value->end(), value->begin(), [](wchar_t ch) { return std::towlower(ch); }); + for (const auto &language : languages) + if (containsWord(language.names, filename) || containsWord(language.names, extension)) + return {language.lexer, language.keywords}; + if (filename.starts_with(L".env.") || extension == L".env") return {"props"}; + if (firstPage.starts_with("WordListSet(0, keywords); + if (language.lexer == "hypertext") lexer->WordListSet(1, javascript); + if (language.lexer == "json") lexer->PropertySet("lexer.json.allow.comments", "1"); + if (language.lexer == "cpp" && (language.keywords == javascript || language.keywords == go)) + { + lexer->PropertySet("lexer.cpp.backquoted.strings", language.keywords == javascript ? "2" : "1"); + if (language.keywords == javascript) lexer->PropertySet("lexer.cpp.regex", "1"); + } + if (language.lexer == "cpp" && language.keywords == csharp) + lexer->PropertySet("lexer.cpp.triplequoted.strings", "1"); + return lexer; +} + +TextColor syntaxColor(Scintilla::ILexer5 &lexer, std::string_view name, int style) +{ + if (!style || (style >= STYLE_DEFAULT && style <= STYLE_LASTPREDEFINED)) return TextColor::text; + const auto *styleTags = lexer.TagsOfStyle(style); + const auto *styleName = lexer.NameOfStyle(style); + const std::string_view tags = styleTags ? styleTags : ""; + const std::string_view token = styleName ? styleName : ""; + const auto has = [&](std::string_view word) { + return tags.find(word) != tags.npos || token.find(word) != token.npos; + }; + if (has("comment")) return TextColor::comment; + if (has("string") || has("character") || has("quoted") || has("regex")) return TextColor::string; + if (has("number") || has("numeric")) return TextColor::number; + if (has("keyword") || has("command") || has("tag") || has("heading") || has("header") || + has("preprocessor") || has("keywordclass")) return TextColor::keyword; + if (has("operator") || has("attribute") || has("property") || has("variable") || has("label")) + return TextColor::symbol; + if (name == "markdown") + { + if (style >= SCE_MARKDOWN_HEADER1 && style <= SCE_MARKDOWN_HEADER6) return TextColor::keyword; + if (style >= SCE_MARKDOWN_CODE && style <= SCE_MARKDOWN_CODEBK) return TextColor::string; + return TextColor::symbol; + } + if (name == "diff") + { + if (style == SCE_DIFF_ADDED) return TextColor::string; + if (style == SCE_DIFF_DELETED) return TextColor::number; + if (style == SCE_DIFF_COMMENT) return TextColor::comment; + return TextColor::keyword; + } + if (name == "sql") + { + if (style >= SCE_SQL_COMMENT && style <= SCE_SQL_COMMENTDOC) return TextColor::comment; + if (style == SCE_SQL_NUMBER) return TextColor::number; + if (style == SCE_SQL_WORD || style == SCE_SQL_WORD2) return TextColor::keyword; + if (style == SCE_SQL_STRING || style == SCE_SQL_CHARACTER) return TextColor::string; + } + if (name == "json") + { + if (style == SCE_JSON_LINECOMMENT || style == SCE_JSON_BLOCKCOMMENT) return TextColor::comment; + if (style == SCE_JSON_STRING || style == SCE_JSON_STRINGEOL) return TextColor::string; + if (style == SCE_JSON_NUMBER) return TextColor::number; + if (style == SCE_JSON_KEYWORD || style == SCE_JSON_LDKEYWORD) return TextColor::keyword; + } + if (name == "css") + { + if (style == SCE_CSS_COMMENT) return TextColor::comment; + if (style == SCE_CSS_DOUBLESTRING || style == SCE_CSS_SINGLESTRING || style == SCE_CSS_VALUE) + return TextColor::string; + if (style == SCE_CSS_TAG || style == SCE_CSS_DIRECTIVE) return TextColor::keyword; + } + if (name == "yaml" || name == "toml") + { + // The two lexers assign the same IDs to these categories. + if (style == SCE_YAML_COMMENT) return TextColor::comment; + if (style == SCE_YAML_KEYWORD) return TextColor::keyword; + if (style == SCE_YAML_NUMBER) return TextColor::number; + } + if (token.empty()) return TextColor::symbol; + return TextColor::text; +} +} diff --git a/src/files_text_language.h b/src/files_text_language.h new file mode 100644 index 0000000..c733058 --- /dev/null +++ b/src/files_text_language.h @@ -0,0 +1,24 @@ +#pragma once + +#include +#include +#include + +namespace Scintilla { class ILexer5; } + +namespace ks::files +{ +enum class TextColor { background, text, chromebg, chrome, selection, comment, keyword, string, number, symbol, + menuText, menuHighlight, menuHighlightText, menuAccessKey, count }; + +struct TextLanguage +{ + std::string lexer; + const char *keywords = ""; +}; + +TextLanguage detectLanguage(const std::filesystem::path &path, std::string_view firstPage); +std::wstring textLanguageLabel(const TextLanguage &language); +Scintilla::ILexer5 *createTextLexer(const TextLanguage &language); +TextColor syntaxColor(Scintilla::ILexer5 &lexer, std::string_view name, int style); +} diff --git a/src/files_text_preferences.h b/src/files_text_preferences.h new file mode 100644 index 0000000..34e1c02 --- /dev/null +++ b/src/files_text_preferences.h @@ -0,0 +1,55 @@ +#pragma once + +#include +#include +#include +#include + +namespace ks::files +{ +inline constexpr size_t documentColorCount = 10; +using TextPalette = std::array; +inline constexpr const wchar_t *textPaletteNames[] = {L"FAR (blue)", L"Dark", L"Light"}; +inline constexpr TextPalette textPalettes[] = { + {RGB(0,0,128), RGB(215,230,255), RGB(0,128,128), RGB(255,255,255), RGB(0,115,115), + RGB(143,195,157), RGB(255,235,118), RGB(165,235,255), RGB(255,181,228), RGB(155,214,255), + RGB(0,0,0), RGB(0,0,0), RGB(255,255,255), RGB(255,255,0)}, + {RGB(29,33,38), RGB(234,237,241), RGB(45,60,70), RGB(255,255,255), RGB(42,86,127), + RGB(155,185,150), RGB(145,201,255), RGB(241,186,143), RGB(208,170,255), RGB(152,226,218), + RGB(255,255,255), RGB(42,86,127), RGB(255,255,255), RGB(255,255,0)}, + {RGB(255,255,255), RGB(28,35,46), RGB(221,231,237), RGB(25,38,54), RGB(74,104,146), + RGB(45,111,70), RGB(103,40,154), RGB(152,52,30), RGB(35,82,156), RGB(0,99,109), + RGB(0,0,0), RGB(189,207,223), RGB(0,0,0), RGB(111,77,0)}, +}; +inline constexpr const wchar_t *textColorNames[] = {L"Background", L"Text", L"Status background", L"Status text", + L"Selection", L"Comment", L"Keyword", L"String", L"Number", L"Symbol", + L"Top menu text", L"Selected menu background", L"Selected menu text", L"Menu access key"}; + +struct TextPreferences +{ + bool wrap{}, numbers{true}, whitespace{}, tabsAsSpaces{}, autoIndent{true}, caretLine{true}; + int tabWidth{4}, lineEnding{}; + std::wstring scheme = textPaletteNames[0]; + TextPalette colors = textPalettes[0]; + bool operator==(const TextPreferences &) const = default; +}; + +// Index 0 is Viewer and index 1 is Editor. +using TextPreferencesSet = std::array; +struct NamedTextPalette +{ + std::wstring name; + TextPalette colors; + bool operator==(const NamedTextPalette &) const = default; +}; +inline constexpr size_t maxTextPalettes = 48; +inline constexpr size_t maxTextPaletteName = 48; +struct TextSettings +{ + TextPreferencesSet profiles; + std::vector schemes; + bool operator==(const TextSettings &) const = default; +}; +TextSettings loadTextPreferences(); +void saveTextPreferences(const TextSettings &settings); +} diff --git a/src/files_text_window.cpp b/src/files_text_window.cpp new file mode 100644 index 0000000..f9df4a1 --- /dev/null +++ b/src/files_text_window.cpp @@ -0,0 +1,1579 @@ +#include "files_text_window.h" +#include "files_text_preferences.h" +#include "files_menu_paint.h" +#include "files_history_date.h" +#include "files_text_document.h" +#include "files_text_language.h" +#include "platform.h" + +#include +#include +#include +#include +#include +#include +#include "../vendor/json.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ks::files +{ +namespace +{ +constexpr const char *profileNames[]{"viewer", "editor"}; + +void readTextProfile(TextPreferences &prefs, const nlohmann::json &data) +{ + prefs.wrap = data.value("wrap", prefs.wrap); + prefs.numbers = data.value("lineNumbers", prefs.numbers); + prefs.whitespace = data.value("whitespace", prefs.whitespace); + prefs.tabsAsSpaces = data.value("tabsAsSpaces", prefs.tabsAsSpaces); + prefs.autoIndent = data.value("autoIndent", prefs.autoIndent); + prefs.caretLine = data.value("caretLine", prefs.caretLine); + prefs.tabWidth = std::clamp(data.value("tabWidth", prefs.tabWidth), 1, 16); + prefs.lineEnding = std::clamp(data.value("lineEnding", prefs.lineEnding), 0, 3); + const auto theme = std::clamp(data.value("theme", 0), 0, static_cast(std::size(textPalettes)) - 1); + prefs.scheme = wide(data.value("scheme", utf8(textPaletteNames[theme]))).substr(0, maxTextPaletteName); + prefs.colors = textPalettes[theme]; + if (data.contains("colors")) + { + const auto documentColors = data.at("colors").get>(); + std::copy(documentColors.begin(), documentColors.end(), prefs.colors.begin()); + } + if (data.contains("menuColors")) + { + const auto menuColors = data.at("menuColors").get>(); + std::copy(menuColors.begin(), menuColors.end(), prefs.colors.begin() + documentColorCount); + } + for (auto &color : prefs.colors) color &= 0xffffff; +} +} + +TextSettings loadTextPreferences() +{ + TextSettings settings{}; + auto &profiles = settings.profiles; + try + { + const auto folder = dataDirectory(); + const auto combined = folder / L"files-text.json"; + if (std::filesystem::exists(combined)) + { + const auto data = nlohmann::json::parse(readFile(combined, 64 * 1024)); + for (size_t i = 0; i < profiles.size(); ++i) + if (data.contains(profileNames[i])) readTextProfile(profiles[i], data.at(profileNames[i])); + if (data.contains("schemes") && data.at("schemes").is_array()) + for (const auto &entry : data.at("schemes")) + { + if (settings.schemes.size() >= maxTextPalettes) break; + try + { + auto name = wide(entry.at("name").get()); + if (name.empty() || name.size() > maxTextPaletteName) continue; + auto colors = entry.at("colors").get(); + for (auto &color : colors) color &= 0xffffff; + settings.schemes.push_back({std::move(name), colors}); + } + catch (const std::exception &) {} + } + return settings; + } + const wchar_t *legacy[]{L"files-viewer.json", L"files-editor.json"}; + for (size_t i = 0; i < profiles.size(); ++i) + { + try { readTextProfile(profiles[i], nlohmann::json::parse(readFile(folder / legacy[i], 16 * 1024))); } + catch (const std::exception &) {} + } + } + catch (const std::exception &) {} + return settings; +} + +void saveTextPreferences(const TextSettings &settings) +{ + nlohmann::json data; + for (size_t i = 0; i < settings.profiles.size(); ++i) + { + const auto &p = settings.profiles[i]; + data[profileNames[i]] = {{"wrap", p.wrap}, {"lineNumbers", p.numbers}, {"whitespace", p.whitespace}, + {"tabsAsSpaces", p.tabsAsSpaces}, {"autoIndent", p.autoIndent}, {"caretLine", p.caretLine}, + {"tabWidth", p.tabWidth}, {"lineEnding", p.lineEnding}, {"scheme", utf8(p.scheme)}, + {"theme", p.scheme == textPaletteNames[1] ? 1 : p.scheme == textPaletteNames[2] ? 2 : 0}, + {"colors", std::vector(p.colors.begin(), p.colors.begin() + documentColorCount)}, + {"menuColors", std::vector(p.colors.begin() + documentColorCount, p.colors.end())}}; + } + auto &schemes = data["schemes"] = nlohmann::json::array(); + for (const auto &scheme : settings.schemes) + schemes.push_back({{"name", utf8(scheme.name)}, {"colors", scheme.colors}}); + const auto json = data.dump(2); + atomicWrite(dataDirectory() / L"files-text.json", Bytes(json.begin(), json.end())); +} + +namespace +{ +constexpr wchar_t windowClass[] = L"KSwitcher.Files.Text"; +const UINT preferencesChanged = RegisterWindowMessageW(L"KSwitcher.Files.PreferencesChanged"); +static_assert(std::size(textColorNames) == static_cast(TextColor::count)); +static_assert(TextPalette{}.size() == std::size(textColorNames)); + +struct MenuLabel +{ + std::wstring title, shortcut; + size_t access = std::wstring::npos; + + explicit MenuLabel(std::wstring_view source) + { + const auto tab = source.find(L'\t'); + if (tab != source.npos) shortcut = source.substr(tab + 1); + source = source.substr(0, tab); + for (size_t i = 0; i < source.size(); ++i) + { + if (source[i] == L'&' && i + 1 < source.size()) + { + if (source[i + 1] == L'&') ++i; + else { access = title.size(); continue; } + } + title += source[i]; + } + } + + bool matches(wchar_t key) const + { + return access < title.size() && std::towupper(title[access]) == std::towupper(key); + } +}; + +COLORREF tintText(COLORREF ink, COLORREF background, int opacity) +{ + const auto blend = [opacity](int foreground, int behind) { + return (foreground * opacity + behind * (100 - opacity)) / 100; + }; + return RGB(blend(GetRValue(ink), GetRValue(background)), + blend(GetGValue(ink), GetGValue(background)), blend(GetBValue(ink), GetBValue(background))); +} + +void drawMenuTitle(HDC dc, RECT bounds, const MenuLabel &label, COLORREF accessInk, bool enabled) +{ + DrawTextW(dc, label.title.c_str(), -1, &bounds, DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX); + if (!enabled || label.access >= label.title.size()) return; + TEXTMETRICW metrics{}; + GetTextMetricsW(dc, &metrics); + const POINT origin{bounds.left, bounds.top + (bounds.bottom - bounds.top - metrics.tmHeight) / 2}; + paintMenuAccessKey(dc, bounds, origin, label.title, label.access, accessInk); +} + +enum Command : UINT +{ + save = 1, close, findText, findNext, previousPage, nextPage, firstPage, lastPage, goToPage, + undo, redo, cut, copy, paste, selectAll, lexerAuto, lexerPlain, options, + lexerStart = 1000, +}; + +struct PagePrompt +{ + TextDialogs style; + uint64_t page{}, pages{}; +}; + +void initializePrompt(TextDialogs style, HWND dialog) +{ + style.prepare(dialog); + SendMessageW(dialog, DM_SETDEFID, IDOK, 0); + SetFocus(GetDlgItem(dialog, 100)); + SendDlgItemMessageW(dialog, 100, EM_SETSEL, 0, -1); +} + +INT_PTR CALLBACK pageDialog(HWND dialog, UINT message, WPARAM wparam, LPARAM lparam) +{ + if (message == WM_INITDIALOG) + { + auto *prompt = reinterpret_cast(lparam); + SetWindowLongPtrW(dialog, DWLP_USER, lparam); + const auto title = L"&Page number (1–" + std::to_wstring(prompt->pages) + L")"; + SetDlgItemTextW(dialog, 101, title.c_str()); + SetDlgItemTextW(dialog, 100, std::to_wstring(prompt->page + 1).c_str()); + initializePrompt(prompt->style, dialog); + return FALSE; + } + auto *prompt = reinterpret_cast(GetWindowLongPtrW(dialog, DWLP_USER)); + if (!prompt) return FALSE; + if (const auto painted = prompt->style.paint(dialog, message, wparam, lparam, L" Go to page ")) + return painted; + if (message != WM_COMMAND) return FALSE; + if (LOWORD(wparam) == IDCANCEL) { prompt->style.finish(dialog, IDCANCEL); return TRUE; } + if (LOWORD(wparam) != IDOK) return FALSE; + wchar_t buffer[32]{}; + const int length = GetDlgItemTextW(dialog, 100, buffer, static_cast(std::size(buffer))); + wchar_t *end{}; + const auto page = std::wcstoull(buffer, &end, 10); + if (!length || *end || !page || page > prompt->pages) + { + MessageBeep(MB_ICONWARNING); + return TRUE; + } + prompt->page = page - 1; + prompt->style.finish(dialog, IDOK); + return TRUE; +} + + +constexpr size_t searchHistoryLimit = 100; +constexpr int searchQueryLimit = 511; + +std::vector readFarHistory(FarHistoryKind kind) +{ + std::vector entries; + try + { + const auto json = nlohmann::json::parse(readFile(dataDirectory() / (kind==FarHistoryKind::search?L"files-search-history.json":L"files-folder-history.json"), 512 * 1024)); + if (!json.is_array()) return entries; + for (const auto &item : json) + { + if (entries.size() == searchHistoryLimit) break; + if (!item.is_object() || !item.contains("date") || !item["date"].is_string() || + !item.contains("text") || !item["text"].is_string()) continue; + auto date = wide(item["date"].get()); + auto text = wide(item["text"].get()); + if (date.size() == 10 && !text.empty() && text.size() <= searchQueryLimit) + entries.push_back({std::move(date), std::move(text)}); + } + } + catch (const std::exception &) {} + return entries; +} + +void writeFarHistory(FarHistoryKind kind,std::wstring_view text) +{ + const auto mutex = CreateMutexW(nullptr, FALSE, kind==FarHistoryKind::search?L"Local\\KSwitcher.Files.SearchHistoryWrite":L"Local\\KSwitcher.Files.FolderHistoryWrite"); + if (!mutex) return; + const auto lock = WaitForSingleObject(mutex, 100); + if (lock == WAIT_OBJECT_0 || lock == WAIT_ABANDONED) + { + try + { + auto entries = readFarHistory(kind); + std::erase_if(entries, [text](const auto &entry) { return entry.text == text; }); + auto json = nlohmann::json::array(); + json.push_back({{"date", utf8(historyDate())}, {"text", utf8(std::wstring(text))}}); + for (size_t index = 0; index < entries.size() && index + 1 < searchHistoryLimit; ++index) + json.push_back({{"date", utf8(entries[index].date)}, {"text", utf8(entries[index].text)}}); + const auto contents = json.dump(); + atomicWrite(dataDirectory() / (kind==FarHistoryKind::search?L"files-search-history.json":L"files-folder-history.json"), Bytes(contents.begin(), contents.end())); + } + catch (const std::exception &) {} + ReleaseMutex(mutex); + } + CloseHandle(mutex); +} + +struct FindPrompt +{ + TextDialogs style; + std::wstring text; + std::wstring word, selection; + DWORD flags = FR_DOWN; + std::vector history; + FarDropDownPalette historyPalette{}; +}; + +struct FarPopup +{ + struct Row { std::wstring_view text; int index; }; + std::vector rows; + FarDropDownPalette palette; + HFONT font{}; + int rowHeight{},inset{},visible{},top{},current{},result=-1; + bool done{}; + + int rowTop() const { return inset+1+rowHeight/2; } + int bottomMargin() const { return inset+1+rowHeight/4; } + + void select(int row) + { + if(row<0 || row>=static_cast(rows.size()) || rows[row].index<0) return; + current=row; + top=std::clamp(top,current-visible+1,current); + } + + void step(int direction,int count=1) + { + auto row=current; + while(count>0) + { + row+=direction; + if(row<0 || row>=static_cast(rows.size())) break; + if(rows[row].index<0) continue; + select(row); + --count; + } + } + + void accept() + { + result=rows[current].index; + done=true; + } + + void paint(HWND window,HDC dc) const + { + RECT bounds{}; + GetClientRect(window,&bounds); + const auto brush=static_cast(GetStockObject(DC_BRUSH)); + SetDCBrushColor(dc,palette.surface); + FillRect(dc,&bounds,brush); + RECT frame=bounds; + InflateRect(&frame,-inset,-inset); + frame.bottom-=rowHeight/4; + SetDCBrushColor(dc,palette.text); + FrameRect(dc,&frame,brush); + SetBkMode(dc,TRANSPARENT); + SetTextColor(dc,palette.text); + SelectObject(dc,font); + const LONG rowLeft=frame.left+inset; + const LONG scrollWidth=static_cast(rows.size())>visible?rowHeight/2:0; + const LONG rowRight=scrollWidth?bounds.right-scrollWidth:frame.right-1; + LONG y=rowTop(); + for(int offset=0;offset(entry.text.size()),&text); + const auto mid=(box.left+box.right)/2; + const auto center=y+rowHeight/2; + const auto gap=text.cx/2+inset*2; + RECT left{frame.left+1,center,mid-gap,center+1}; + RECT right{mid+gap,center,rowRight,center+1}; + SetDCBrushColor(dc,palette.text); + if(left.right>left.left) FillRect(dc,&left,brush); + if(right.right>right.left) FillRect(dc,&right,brush); + } + else box.left+=rowHeight; + DrawTextW(dc,entry.text.data(),static_cast(entry.text.size()),&box, + DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX|DT_END_ELLIPSIS|(entry.index<0?DT_CENTER:DT_LEFT)); + } + if(scrollWidth) + { + RECT up{rowRight,rowTop(),bounds.right,rowTop()+rowHeight}; + RECT down{rowRight,y-rowHeight,bounds.right,y}; + DrawTextW(dc,L"▲",1,&up,DT_SINGLELINE|DT_CENTER|DT_VCENTER); + DrawTextW(dc,L"▼",1,&down,DT_SINGLELINE|DT_CENTER|DT_VCENTER); + RECT track{up.left,up.bottom,up.right,down.top}; + for(LONG line=track.top;line(rows.size())-visible); + RECT thumb{track.left,thumbY,track.right,std::min(track.bottom,thumbY+rowHeight)}; + SetDCBrushColor(dc,palette.text); + FillRect(dc,&thumb,brush); + } + } +}; + +LRESULT CALLBACK farPopupWindow(HWND window,UINT message,WPARAM wp,LPARAM lp) +{ + if(message==WM_NCCREATE) + SetWindowLongPtrW(window,GWLP_USERDATA, + reinterpret_cast(reinterpret_cast(lp)->lpCreateParams)); + auto *state=reinterpret_cast(GetWindowLongPtrW(window,GWLP_USERDATA)); + if(!state) return DefWindowProcW(window,message,wp,lp); + switch(message) + { + case WM_ERASEBKGND: return 1; + case WM_PAINT: + { + PAINTSTRUCT paint{}; + const auto dc=BeginPaint(window,&paint); + const auto saved=SaveDC(dc); + state->paint(window,dc); + RestoreDC(dc,saved); + EndPaint(window,&paint); + return 0; + } + case WM_PRINT: + case WM_PRINTCLIENT: + { + const auto dc=reinterpret_cast(wp); + const auto saved=SaveDC(dc); + state->paint(window,dc); + RestoreDC(dc,saved); + return 0; + } + case WM_CLOSE: state->done=true; return 0; + case WM_CAPTURECHANGED: state->done=true; return 0; + case WM_NCDESTROY: + state->done=true; + SetWindowLongPtrW(window,GWLP_USERDATA,0); + break; + case WM_KEYDOWN: + switch(wp) + { + case VK_ESCAPE: state->done=true; break; + case VK_RETURN: state->accept(); break; + case VK_UP: state->step(-1); break; + case VK_DOWN: state->step(1); break; + case VK_PRIOR: state->step(-1,state->visible); break; + case VK_NEXT: state->step(1,state->visible); break; + case VK_HOME: state->step(-1,static_cast(state->rows.size())); break; + case VK_END: state->step(1,static_cast(state->rows.size())); break; + } + InvalidateRect(window,nullptr,FALSE); + return 0; + case WM_MOUSEWHEEL: + { + const int direction=GET_WHEEL_DELTA_WPARAM(wp)>0?-1:1; + state->top=std::clamp(state->top+3*direction,0,static_cast(state->rows.size())-state->visible); + InvalidateRect(window,nullptr,FALSE); + return 0; + } + case WM_LBUTTONDOWN: + case WM_LBUTTONUP: + case WM_MOUSEMOVE: + { + RECT bounds{}; + GetClientRect(window,&bounds); + const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)}; + if(!PtInRect(&bounds,point)) + { + if(message==WM_LBUTTONDOWN) state->done=true; + return 0; + } + const auto offset=(point.y-state->rowTop())/state->rowHeight; + const bool scroll=static_cast(state->rows.size())>state->visible && + point.x>=bounds.right-state->rowHeight/2; + if(scroll && message==WM_LBUTTONDOWN) + state->top=std::clamp(state->top+(offsetvisible/2?-1:1),0, + static_cast(state->rows.size())-state->visible); + if(!scroll && point.y>=state->rowTop() && offsetvisible) + { + const auto row=state->top+offset; + if(state->rows[row].index>=0) + { + state->select(row); + if(message==WM_LBUTTONUP) state->accept(); + } + } + InvalidateRect(window,nullptr,FALSE); + return 0; + } + } + return DefWindowProcW(window,message,wp,lp); +} + +void showHistoryPopup(HWND dialog,int fieldId,const std::vector &history, + FarDropDownPalette palette) +{ + const auto field=GetDlgItem(dialog,fieldId); + const auto selected=chooseFarDropDown(field,history,0,palette); + if(selected>=0) + { + SetWindowTextW(field,history[selected].text.c_str()); + SendMessageW(field,EM_SETSEL,0,-1); + } +} + +LRESULT CALLBACK searchFieldKeys(HWND field,UINT message,WPARAM key,LPARAM flags,UINT_PTR,DWORD_PTR arrow) +{ + if(message==WM_SYSKEYDOWN && key==VK_DOWN && (flags&(1LL<<29))) + { + PostMessageW(GetParent(field),WM_COMMAND,arrow,0); + return 0; + } + return DefSubclassProc(field,message,key,flags); +} + +INT_PTR CALLBACK searchDialog(HWND dialog, UINT message, WPARAM wparam, LPARAM lparam) +{ + if (message == WM_INITDIALOG) + { + auto *prompt = reinterpret_cast(lparam); + SetWindowLongPtrW(dialog, DWLP_USER, lparam); + SetDlgItemTextW(dialog, 100, prompt->text.c_str()); + SendDlgItemMessageW(dialog, 100, EM_SETLIMITTEXT, searchQueryLimit, 0); + installFarHistoryKey(GetDlgItem(dialog,100),searchHistoryButton); + EnableWindow(GetDlgItem(dialog, searchHistoryButton), !prompt->history.empty()); + CheckDlgButton(dialog, 101, prompt->flags & FR_MATCHCASE ? BST_CHECKED : BST_UNCHECKED); + CheckDlgButton(dialog, 102, prompt->flags & FR_WHOLEWORD ? BST_CHECKED : BST_UNCHECKED); + EnableWindow(GetDlgItem(dialog, 106), !prompt->word.empty()); + EnableWindow(GetDlgItem(dialog, 107), !prompt->selection.empty()); + initializePrompt(prompt->style, dialog); + return FALSE; + } + auto *prompt = reinterpret_cast(GetWindowLongPtrW(dialog, DWLP_USER)); + if (!prompt) return FALSE; + if (const auto painted = prompt->style.paintSearch(dialog, message, wparam, lparam)) + return painted; + if (message != WM_COMMAND) return FALSE; + const auto command = LOWORD(wparam); + if (command == searchHistoryButton) { showHistoryPopup(dialog,100,prompt->history,prompt->historyPalette); return TRUE; } + if (command == IDCANCEL) { prompt->style.finish(dialog, IDCANCEL); return TRUE; } + if (command == 106 || command == 107) + { + const auto &value = command == 106 ? prompt->word : prompt->selection; + if (value.empty()) return TRUE; + SetDlgItemTextW(dialog, 100, value.c_str()); + SetFocus(GetDlgItem(dialog, 100)); + SendDlgItemMessageW(dialog, 100, EM_SETSEL, 0, -1); + return TRUE; + } + if (command != IDOK && command != 103) return FALSE; + wchar_t buffer[searchQueryLimit + 1]{}; + if (!GetDlgItemTextW(dialog, 100, buffer, static_cast(std::size(buffer)))) return TRUE; + prompt->text = buffer; + writeFarHistory(FarHistoryKind::search,prompt->text); + prompt->flags = (IsDlgButtonChecked(dialog, 101) == BST_CHECKED ? FR_MATCHCASE : 0) | + (IsDlgButtonChecked(dialog, 102) == BST_CHECKED ? FR_WHOLEWORD : 0) | + (command == IDOK ? FR_DOWN : 0); + prompt->style.finish(dialog, IDOK); + return TRUE; +} + +class TextWindow +{ +public: + TextWindow(const std::filesystem::path &path, bool editable, TextDialogs dialogs) + : document(path, editable), filename(path.filename().wstring()), edit(editable), + prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()), + automatic(detectLanguage(path, document.readPage(0))), language(automatic), search{dialogs} + { + for (int index = 0; index < GetLexerCount(); ++index) + { + char name[128]{}; + GetLexerName(index, name, sizeof(name)); + if (*name && std::string_view(name) != "null") lexers.emplace_back(name); + } + std::sort(lexers.begin(), lexers.end(), [](const auto &a, const auto &b) { + return _stricmp(a.c_str(), b.c_str()) < 0; + }); + } + + static LRESULT CALLBACK procedure(HWND window, UINT message, WPARAM wparam, LPARAM lparam); + HWND window{}, editor{}; + bool handleKey(const MSG &message); + +private: + TextDocument document; + std::wstring filename; + bool edit{}, loading{}, stagedDirty{}, closeAfterSave{}, insertRejected{}; + TextPreferences prefs; + TextWindowFont filesFont; + TextLanguage automatic, language; + std::vector lexers; + FindPrompt search; + std::string cleanPage; + std::deque menuLabels; + std::vector menuBarLabels; + HBRUSH menuSurface{}; + HMENU menuRoot{}; + std::array menuBounds{}; + int menuSelection = -1; + bool pendingPreferences{}; + Scintilla::ILexer5 *lexer{}; // Scintilla owns the installed lexer. + uint64_t page{}, pageOffset{}, pageTotal{}, fileSize{}; + intptr_t pendingCaret{}; + int pageEol = SC_EOL_CRLF; + size_t undoBytes{}; + std::future saving; + static constexpr UINT_PTR saveTimer = 1; + static constexpr UINT trimUndo = WM_APP + 1; + + LRESULT send(UINT message, WPARAM wparam = 0, LPARAM lparam = 0) const + { + return SendMessageW(editor, message, wparam, lparam); + } + + COLORREF color(TextColor role) const { return prefs.colors[static_cast(role)]; } + int scale(int value) const { return MulDiv(value, GetDpiForWindow(window), 96); } + int chromeHeight() const { return scale(std::max(21, (filesFont.tenthsOfPoint + 9) / 10 + 12)); } + std::string_view pageText() const + { + const auto length = static_cast(send(SCI_GETLENGTH)); + return {reinterpret_cast(send(SCI_GETCHARACTERPOINTER)), length}; + } + bool currentChanged() const { return edit && !loading && send(SCI_GETMODIFY) && pageText() != cleanPage; } + bool dirty() const { return stagedDirty || currentChanged(); } + bool busy() const { return saving.valid(); } + void invalidate() const { InvalidateRect(window, nullptr, FALSE); } + + void createMenu(); + void releaseMenu(); + void reloadPreferences(); + void styleMenu(HMENU menu); + void openMenu(int index); + bool measureMenu(MEASUREITEMSTRUCT &item); + bool drawMenu(const DRAWITEMSTRUCT &item); + LRESULT menuKey(HMENU menu, wchar_t key) const; + HFONT createChromeFont() const; + void updateMenus(); + void applyPreferences(); + void updateLineNumberMargin(); + void applyLineEnding(); + void installLexer(); + void loadPage(uint64_t index); + void stagePage(); + void go(uint64_t index); + void saveFile(bool closeWhenDone); + void finishSave(); + void requestClose(); + void layout(); + void paint(); + void command(UINT id); + void openFind(); + void find(bool down, DWORD flags); + void notify(const SCNotification ¬ice); +}; + +void addItem(HMENU menu, UINT command, const wchar_t *text) +{ + AppendMenuW(menu, MF_STRING, command, text); +} + +HMENU addGroup(HMENU parent, const wchar_t *title) +{ + const auto menu = CreatePopupMenu(); + AppendMenuW(parent, MF_POPUP, reinterpret_cast(menu), title); + return menu; +} + +void TextWindow::createMenu() +{ + const auto menu = CreateMenu(); + const auto file = addGroup(menu, L"&File"); + if (edit) addItem(file, save, L"&Save\tF2"); + addItem(file, close, L"&Close\tF10"); + const auto actions = addGroup(menu, edit ? L"&Edit" : L"&Selection"); + if (edit) + { + addItem(actions, undo, L"&Undo\tCtrl+Z"); + addItem(actions, redo, L"&Redo\tCtrl+Y"); + AppendMenuW(actions, MF_SEPARATOR, 0, nullptr); + addItem(actions, cut, L"Cu&t\tCtrl+X"); + addItem(actions, paste, L"&Paste\tCtrl+V"); + } + addItem(actions, copy, L"&Copy\tCtrl+C"); + addItem(actions, selectAll, L"Select &page\tCtrl+A"); + const auto navigation = addGroup(menu, L"&Navigate"); + addItem(navigation, findText, L"&Find on page…\tCtrl+F"); + addItem(navigation, findNext, L"Find &next\tF3"); + AppendMenuW(navigation, MF_SEPARATOR, 0, nullptr); + addItem(navigation, previousPage, L"&Previous page\tCtrl+PgUp"); + addItem(navigation, nextPage, L"N&ext page\tCtrl+PgDn"); + addItem(navigation, firstPage, L"F&irst page\tCtrl+Shift+Home"); + addItem(navigation, lastPage, L"&Last page\tCtrl+Shift+End"); + addItem(navigation, goToPage, L"&Go to page…\tF5"); + + const auto syntax = addGroup(menu, L"S&yntax"); + addItem(syntax, lexerAuto, L"&Automatic"); + addItem(syntax, lexerPlain, L"&Plain text"); + constexpr std::wstring_view groups[] = {L"A–&F", L"G–&L", L"M–&R", L"S–&Z"}; + const wchar_t lastLetters[] = {L'f', L'l', L'r', L'z'}; + HMENU group{}; + size_t groupIndex{}; + std::wstring assignedKeys; + for (size_t i = 0; i < lexers.size(); ++i) + { + auto name = wide(lexers[i]); + const auto letter = std::towlower(name.front()); + while (groupIndex + 1 < std::size(groups) && letter > lastLetters[groupIndex]) + { + ++groupIndex; + group = nullptr; + assignedKeys.clear(); + } + if (!group) group = addGroup(syntax, groups[groupIndex].data()); + for (size_t position = 0; position < name.size(); ++position) + { + const auto key = static_cast(std::towlower(name[position])); + if (((key >= L'a' && key <= L'z') || (key >= L'0' && key <= L'9')) && + assignedKeys.find(key) == assignedKeys.npos) + { + assignedKeys += key; + name.insert(position, 1, L'&'); + break; + } + } + addItem(group, static_cast(lexerStart + i), name.c_str()); + } + addItem(menu, options, L"&Options…"); + menuRoot = menu; + menuSurface = CreateSolidBrush(color(TextColor::chromebg)); + MENUINFO background{sizeof(background), MIM_BACKGROUND | MIM_APPLYTOSUBMENUS}; + background.hbrBack = menuSurface; + SetMenuInfo(menu, &background); + for (int index = 0; index < GetMenuItemCount(menu); ++index) + { + wchar_t label[64]{}; + GetMenuStringW(menu, index, label, static_cast(std::size(label)), MF_BYPOSITION); + menuBarLabels.emplace_back(label); + if (const auto group = GetSubMenu(menu, index)) styleMenu(group); + } +} + +void TextWindow::openMenu(int index) +{ + if (GetMenuItemID(menuRoot, index) == options) { command(options); return; } + updateMenus(); + menuSelection = index; + invalidate(); + UpdateWindow(window); + POINT anchor{menuBounds[index].left, menuBounds[index].bottom}; + ClientToScreen(window, &anchor); + const auto selected = TrackPopupMenu(GetSubMenu(menuRoot, index), TPM_RETURNCMD | TPM_RIGHTBUTTON, + anchor.x, anchor.y, 0, window, nullptr); + menuSelection = -1; + if (pendingPreferences) reloadPreferences(); + invalidate(); + if (selected) command(selected); +} + +void TextWindow::styleMenu(HMENU menu) +{ + for (int index = 0; index < GetMenuItemCount(menu); ++index) + { + wchar_t label[256]{}; + MENUITEMINFOW entry{sizeof(entry), MIIM_FTYPE | MIIM_STRING | MIIM_SUBMENU}; + entry.dwTypeData = label; + entry.cch = static_cast(std::size(label)); + if (!GetMenuItemInfoW(menu, index, TRUE, &entry)) continue; + auto &stored = menuLabels.emplace_back(label); + entry.fMask = MIIM_FTYPE | MIIM_DATA; + entry.fType |= MFT_OWNERDRAW; + entry.dwItemData = reinterpret_cast(&stored); + SetMenuItemInfoW(menu, index, TRUE, &entry); + if (entry.hSubMenu) styleMenu(entry.hSubMenu); + } +} + +HFONT TextWindow::createChromeFont() const +{ + auto font = filesFont.font; + font.lfHeight = -MulDiv(filesFont.tenthsOfPoint, GetDpiForWindow(window), 720); + font.lfWidth = 0; + return CreateFontIndirectW(&font); +} + +bool TextWindow::measureMenu(MEASUREITEMSTRUCT &item) +{ + if (item.CtlType != ODT_MENU || !item.itemData) return false; + const auto &label = *reinterpret_cast(item.itemData); + const auto dc = GetDC(window); + const auto font = createChromeFont(); + const auto previous = SelectObject(dc, font); + SIZE title{}, shortcut{}; + GetTextExtentPoint32W(dc, label.title.c_str(), static_cast(label.title.size()), &title); + if (!label.shortcut.empty()) + GetTextExtentPoint32W(dc, label.shortcut.c_str(), static_cast(label.shortcut.size()), &shortcut); + SelectObject(dc, previous); + DeleteObject(font); + ReleaseDC(window, dc); + item.itemWidth = static_cast(title.cx + shortcut.cx + scale(label.shortcut.empty() ? 32 : 56)); + item.itemHeight = label.title.empty() ? scale(7) : chromeHeight(); + return true; +} + +bool TextWindow::drawMenu(const DRAWITEMSTRUCT &item) +{ + if (item.CtlType != ODT_MENU || !item.itemData) return false; + const auto &label = *reinterpret_cast(item.itemData); + const bool selected = (item.itemState & (ODS_SELECTED | ODS_HOTLIGHT)) != 0; + const auto dc = item.hDC; + const auto saved = SaveDC(dc); + const auto font = createChromeFont(); + SelectObject(dc, font); + SetBkMode(dc, TRANSPARENT); + const auto surface = static_cast(GetStockObject(DC_BRUSH)); + SetDCBrushColor(dc, color(selected ? TextColor::menuHighlight : TextColor::chromebg)); + FillRect(dc, &item.rcItem, surface); + const auto ink = color(selected ? TextColor::menuHighlightText : TextColor::chrome); + const bool enabled = !(item.itemState & (ODS_DISABLED | ODS_GRAYED)); + SetTextColor(dc, enabled ? ink : tintText(ink, color(TextColor::chromebg), 50)); + auto rect = item.rcItem; + if (label.title.empty()) + { + const auto y = (rect.top + rect.bottom) / 2; + RECT line{rect.left + scale(4), y, rect.right - scale(4), y + 1}; + SetDCBrushColor(dc, ink); + FillRect(dc, &line, surface); + } + else + { + rect.left += scale(18); + rect.right -= scale(14); + if (item.itemState & ODS_CHECKED) + { + auto mark = item.rcItem; + mark.left += scale(4); + DrawTextW(dc, L"✓", 1, &mark, DT_SINGLELINE | DT_VCENTER); + } + drawMenuTitle(dc, rect, label, color(TextColor::menuAccessKey), enabled); + if (!label.shortcut.empty()) + DrawTextW(dc, label.shortcut.c_str(), -1, &rect, DT_SINGLELINE | DT_VCENTER | DT_RIGHT | DT_NOPREFIX); + } + RestoreDC(dc, saved); + DeleteObject(font); + return true; +} + +LRESULT TextWindow::menuKey(HMENU menu, wchar_t key) const +{ + for (int index = 0; index < GetMenuItemCount(menu); ++index) + { + MENUITEMINFOW entry{sizeof(entry), MIIM_DATA | MIIM_STATE}; + if (!GetMenuItemInfoW(menu, index, TRUE, &entry) || !entry.dwItemData || + (entry.fState & (MFS_DISABLED | MFS_GRAYED))) continue; + const auto &label = *reinterpret_cast(entry.dwItemData); + if (label.matches(key)) + return MAKELRESULT(index, MNC_EXECUTE); + } + return MAKELRESULT(0, MNC_IGNORE); +} + +void TextWindow::updateMenus() +{ + const auto menu = menuRoot; + const auto enable = [&](UINT command, bool enabled) { + EnableMenuItem(menu, command, MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_GRAYED)); + }; + enable(save, edit && !busy() && dirty()); + enable(undo, edit && !busy() && send(SCI_CANUNDO)); + enable(redo, edit && !busy() && send(SCI_CANREDO)); + for (const auto command : {previousPage, firstPage}) enable(command, !busy() && page > 0); + for (const auto command : {nextPage, lastPage}) enable(command, !busy() && page + 1 < pageTotal); + enable(goToPage, !busy() && pageTotal > 1); +} + +void TextWindow::installLexer() +{ + lexer = createTextLexer(language); + send(SCI_SETILEXER, 0, reinterpret_cast(lexer)); + applyPreferences(); + send(SCI_COLOURISE, 0, -1); +} + +void TextWindow::releaseMenu() +{ + if (menuRoot) DestroyMenu(std::exchange(menuRoot, nullptr)); + if (menuSurface) DeleteObject(std::exchange(menuSurface, nullptr)); + menuLabels.clear(); + menuBarLabels.clear(); +} + +void TextWindow::reloadPreferences() +{ + if (menuSelection >= 0) + { + pendingPreferences = true; + return; + } + pendingPreferences = false; + auto profile = loadTextPreferences().profiles[edit]; + const auto font = search.style.readFont(); + const bool fontChanged = font.tenthsOfPoint != filesFont.tenthsOfPoint || + std::memcmp(&font.font, &filesFont.font, sizeof(LOGFONTW)) != 0; + if (!fontChanged && profile == prefs) return; + prefs = std::move(profile); + filesFont = font; + if (fontChanged) + { + releaseMenu(); + createMenu(); + } + applyPreferences(); +} + +void TextWindow::applyPreferences() +{ + if (menuSurface) + { + const auto previous = menuSurface; + menuSurface = CreateSolidBrush(color(TextColor::chromebg)); + MENUINFO info{sizeof(info), MIM_BACKGROUND | MIM_APPLYTOSUBMENUS}; + info.hbrBack = menuSurface; + SetMenuInfo(menuRoot, &info); + DeleteObject(previous); + } + const auto &font = filesFont.font; + const auto face = utf8(font.lfFaceName); + send(SCI_STYLESETFONT, STYLE_DEFAULT, reinterpret_cast(face.c_str())); + send(SCI_STYLESETSIZEFRACTIONAL, STYLE_DEFAULT, filesFont.tenthsOfPoint * (SC_FONT_SIZE_MULTIPLIER / 10)); + send(SCI_STYLESETWEIGHT, STYLE_DEFAULT, font.lfWeight ? font.lfWeight : FW_NORMAL); + send(SCI_STYLESETITALIC, STYLE_DEFAULT, font.lfItalic != 0); + send(SCI_STYLESETUNDERLINE, STYLE_DEFAULT, font.lfUnderline != 0); + send(SCI_STYLESETCHARACTERSET, STYLE_DEFAULT, font.lfCharSet); + const auto quality = font.lfQuality == CLEARTYPE_QUALITY || font.lfQuality == CLEARTYPE_NATURAL_QUALITY + ? SC_EFF_QUALITY_LCD_OPTIMIZED : font.lfQuality == ANTIALIASED_QUALITY ? SC_EFF_QUALITY_ANTIALIASED + : font.lfQuality == NONANTIALIASED_QUALITY ? SC_EFF_QUALITY_NON_ANTIALIASED : SC_EFF_QUALITY_DEFAULT; + send(SCI_SETFONTQUALITY, quality); + send(SCI_STYLESETFORE, STYLE_DEFAULT, color(TextColor::text)); + send(SCI_STYLESETBACK, STYLE_DEFAULT, color(TextColor::background)); + send(SCI_STYLECLEARALL); + if (lexer) + { + for (int style = 0; style < 256; ++style) + { + const auto role = syntaxColor(*lexer, language.lexer, style); + send(SCI_STYLESETFORE, style, color(role)); + if (role == TextColor::keyword) send(SCI_STYLESETBOLD, style, TRUE); + } + } + const auto gutter = color(TextColor::chromebg); + send(SCI_STYLESETFORE, STYLE_LINENUMBER, tintText(color(TextColor::chrome), gutter, 70)); + send(SCI_STYLESETBACK, STYLE_LINENUMBER, gutter); + send(SCI_SETELEMENTCOLOUR, SC_ELEMENT_SELECTION_TEXT, RGB(255,255,255) | 0xff000000); + send(SCI_SETELEMENTCOLOUR, SC_ELEMENT_SELECTION_BACK, color(TextColor::selection) | 0xff000000); + send(SCI_SETCARETFORE, color(TextColor::text)); + send(SCI_SETCARETLINEVISIBLE, prefs.caretLine); + send(SCI_SETCARETLINEBACK, color(TextColor::chrome)); + send(SCI_SETCARETLINEBACKALPHA, 24); + send(SCI_SETTABWIDTH, prefs.tabWidth); + send(SCI_SETINDENT, prefs.tabWidth); + send(SCI_SETUSETABS, !prefs.tabsAsSpaces); + send(SCI_SETTABINDENTS, TRUE); + send(SCI_SETBACKSPACEUNINDENTS, TRUE); + send(SCI_SETWRAPMODE, prefs.wrap ? SC_WRAP_WORD : SC_WRAP_NONE); + send(SCI_SETVIEWWS, prefs.whitespace ? SCWS_VISIBLEALWAYS : SCWS_INVISIBLE); + send(SCI_SETVIEWEOL, prefs.whitespace); + applyLineEnding(); + updateLineNumberMargin(); + layout(); + invalidate(); +} + +void TextWindow::updateLineNumberMargin() +{ + LRESULT width{}; + if (prefs.numbers) + { + const auto digits = std::to_string(send(SCI_GETLINECOUNT)).size(); + const std::string sample(digits, '9'); + width = send(SCI_TEXTWIDTH, STYLE_LINENUMBER, reinterpret_cast(sample.c_str())) + scale(7); + } + if (send(SCI_GETMARGINWIDTHN, 0) != width) + send(SCI_SETMARGINWIDTHN, 0, width); + const auto textInset = prefs.numbers ? scale(8) : 1; + if (send(SCI_GETMARGINLEFT) != textInset) + send(SCI_SETMARGINLEFT, 0, textInset); +} + +void TextWindow::applyLineEnding() +{ + const int choices[] = {pageEol, SC_EOL_CRLF, SC_EOL_LF, SC_EOL_CR}; + send(SCI_SETEOLMODE, choices[prefs.lineEnding]); +} + +void TextWindow::loadPage(uint64_t index) +{ + auto data = document.readPage(index); + const auto offset = document.boundary(index); + page = index; + pageOffset = offset; + pageTotal = document.pages(); + fileSize = document.size(); + stagedDirty = document.modified(); + const auto eol = data.find_first_of("\r\n"); + pageEol = eol == data.npos ? SC_EOL_CRLF : data[eol] == '\n' ? SC_EOL_LF : + eol + 1 < data.size() && data[eol + 1] == '\n' ? SC_EOL_CRLF : SC_EOL_CR; + loading = true; + send(SCI_SETREADONLY, FALSE); + send(SCI_SETUNDOCOLLECTION, FALSE); + send(SCI_CLEARALL); + send(SCI_ADDTEXT, data.size(), reinterpret_cast(data.data())); + send(SCI_EMPTYUNDOBUFFER); + send(SCI_SETUNDOCOLLECTION, edit); + applyLineEnding(); + send(SCI_SETSAVEPOINT); + send(SCI_SETREADONLY, !edit); + send(SCI_GOTOPOS, 0); + send(SCI_SETXOFFSET, 0); + send(SCI_SETFIRSTVISIBLELINE, 0); + cleanPage = std::move(data); + loading = false; + updateLineNumberMargin(); + undoBytes = 0; + insertRejected = false; + invalidate(); +} + +void TextWindow::stagePage() +{ + if (!currentChanged()) return; + auto text = std::string(pageText()); + document.stage(page, text); + cleanPage = std::move(text); + stagedDirty = document.modified(); + send(SCI_SETSAVEPOINT); +} + +void TextWindow::go(uint64_t index) +{ + if (index >= pageTotal || index == page) return; + stagePage(); + loadPage(index); +} + +void TextWindow::saveFile(bool closeWhenDone) +{ + if (busy() || !edit) return; + stagePage(); + if (!stagedDirty) + { + if (closeWhenDone) DestroyWindow(window); + return; + } + pendingCaret = send(SCI_GETCURRENTPOS); + closeAfterSave = closeWhenDone; + if (!SetTimer(window, saveTimer, 75, nullptr)) throw std::runtime_error("Cannot start the save timer."); + send(SCI_SETREADONLY, TRUE); + try { saving = std::async(std::launch::async, [this] { return document.save(); }); } + catch (...) + { + KillTimer(window, saveTimer); + send(SCI_SETREADONLY, !edit); + throw; + } + invalidate(); +} + +void TextWindow::finishSave() +{ + if (!busy() || saving.wait_for(std::chrono::milliseconds(0)) != std::future_status::ready) return; + KillTimer(window, saveTimer); + send(SCI_SETREADONLY, !edit); + const auto reopened = saving.get(); + stagedDirty = false; + if (!reopened) + { + search.style.message(window, L"The file was saved. Reopen it to continue editing."); + DestroyWindow(window); + return; + } + if (closeAfterSave) { DestroyWindow(window); return; } + if (pageTotal == 1 && document.pages() == 1) + { + fileSize = document.size(); + invalidate(); + return; + } + loadPage(std::min(page, document.pages() - 1)); + send(SCI_GOTOPOS, std::min(pendingCaret, send(SCI_GETLENGTH))); +} + +void TextWindow::requestClose() +{ + if (busy()) return; + if (currentChanged() ? document.modifiedWith(page, pageText()) : stagedDirty) + { + const auto answer = search.style.confirmSave(window); + if (answer == IDCANCEL) return; + if (answer == IDYES) { saveFile(true); return; } + if (answer != IDNO) return; + } + DestroyWindow(window); +} + +void TextWindow::layout() +{ + if (!editor) return; + RECT area{}; + GetClientRect(window, &area); + const auto row = chromeHeight(); + MoveWindow(editor, 0, 2 * row, area.right, std::max(0L, area.bottom - 3 * row), TRUE); + invalidate(); +} + +void TextWindow::paint() +{ + PAINTSTRUCT paint{}; + const auto dc = BeginPaint(window, &paint); + RECT client{}; + GetClientRect(window, &client); + const auto row = chromeHeight(); + SetDCBrushColor(dc, color(TextColor::chromebg)); + const auto brush = static_cast(GetStockObject(DC_BRUSH)); + RECT menuBar{0, 0, client.right, row}; + RECT top{0, row, client.right, 2 * row}; + RECT bottom{0, client.bottom - row, client.right, client.bottom}; + FillRect(dc, &top, brush); + FillRect(dc, &bottom, brush); + FillRect(dc, &menuBar, brush); + const auto chromeFont = createChromeFont(); + const auto previous = SelectObject(dc, chromeFont); + SetTextColor(dc, color(TextColor::chrome)); + SetBkMode(dc, TRANSPARENT); + LONG left{}; + for (size_t index = 0; index < menuBarLabels.size(); ++index) + { + const auto &label = menuBarLabels[index]; + SIZE extent{}; + GetTextExtentPoint32W(dc, label.title.c_str(), static_cast(label.title.size()), &extent); + const auto inset = scale(9); + menuBounds[index] = {left, 0, left + extent.cx + 2 * inset, row}; + const bool active = menuSelection == static_cast(index); + if (active) + { + SetDCBrushColor(dc, color(TextColor::menuHighlight)); + FillRect(dc, &menuBounds[index], brush); + } + auto bounds = menuBounds[index]; + bounds.left += inset; + SetTextColor(dc, color(active ? TextColor::menuHighlightText : TextColor::menuText)); + drawMenuTitle(dc, bounds, label, color(TextColor::menuAccessKey), true); + left = bounds.right; + } + SetTextColor(dc, color(TextColor::chrome)); + bottom.left += scale(7); + const auto position = send(SCI_GETCURRENTPOS); + const auto line = send(SCI_LINEFROMPOSITION, position) + 1; + const auto column = send(SCI_GETCOLUMN, position) + 1; + const auto displayLanguage = textLanguageLabel(language); + auto status = filename + (edit ? L" (Edit)" : L" (View)") + (dirty() ? L" *" : L"") + + L" │ " + document.encodingName() + L" │ " + displayLanguage + + L" │ Ln " + std::to_wstring(line) + L":" + std::to_wstring(column); + if (pageTotal > 1) + status += L" │ Page " + std::to_wstring(page + 1) + L"/" + std::to_wstring(pageTotal) + + L" @ " + std::to_wstring(pageOffset); + status += L" │ " + std::to_wstring(fileSize) + L" B"; + const auto hints = busy() ? L"Saving…" : insertRejected ? L"Page edit limit: 8 MiB" : + edit ? L"F2 Save F3 Find next F5 Go to page Ctrl+PgUp/PgDn Pages F10 Close" : + L"F3 Find next F5 Go to page Ctrl+PgUp/PgDn Pages F10 Close"; + constexpr UINT format = DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS | DT_NOPREFIX; + top.left += scale(12); + top.right -= scale(12); + if (top.left < top.right) + DrawTextW(dc, status.c_str(), -1, &top, format | DT_RIGHT); + DrawTextW(dc, hints, -1, &bottom, format); + SelectObject(dc, previous); + DeleteObject(chromeFont); + EndPaint(window, &paint); +} + +void TextWindow::openFind() +{ + const auto searchText = [this](LRESULT start, LRESULT end) -> std::wstring { + if (start < 0 || end <= start || end - start > 4 * searchQueryLimit) return {}; + const auto value = pageText().substr(start, end - start); + if (value.find_first_of("\r\n\0", 0, 3) != value.npos) return {}; + auto text = wide(std::string(value)); + return text.size() <= searchQueryLimit ? std::move(text) : std::wstring{}; + }; + const auto caret = send(SCI_GETCURRENTPOS); + search.word = searchText(send(SCI_WORDSTARTPOSITION, caret, TRUE), send(SCI_WORDENDPOSITION, caret, TRUE)); + search.selection = searchText(send(SCI_GETSELECTIONSTART), send(SCI_GETSELECTIONEND)); + search.history = readFarHistory(FarHistoryKind::search); + search.historyPalette = search.style.dropDownPalette(); + if (search.style.run(GetModuleHandleW(nullptr), MAKEINTRESOURCEW(604), window, searchDialog, + reinterpret_cast(&search)) == IDOK) + find((search.flags & FR_DOWN) != 0, search.flags); +} + +void TextWindow::find(bool down, DWORD flags) +{ + const auto needle = utf8(this->search.text); + if (needle.empty()) { openFind(); return; } + const auto length = send(SCI_GETLENGTH); + const auto start = send(down ? SCI_GETSELECTIONEND : SCI_GETSELECTIONSTART); + send(SCI_SETSEARCHFLAGS, ((flags & FR_MATCHCASE) ? SCFIND_MATCHCASE : 0) | + ((flags & FR_WHOLEWORD) ? SCFIND_WHOLEWORD : 0)); + const auto search = [&](LRESULT from, LRESULT to) { + send(SCI_SETTARGETRANGE, from, to); + return send(SCI_SEARCHINTARGET, needle.size(), reinterpret_cast(needle.data())) >= 0; + }; + if (search(start, down ? length : 0) || search(down ? 0 : length, start)) + { + send(SCI_SETSEL, send(SCI_GETTARGETSTART), send(SCI_GETTARGETEND)); + send(SCI_SCROLLCARET); + } + else MessageBeep(MB_ICONINFORMATION); +} + +void TextWindow::command(UINT id) +{ + if (busy()) return; + switch (id) + { + case save: saveFile(false); return; + case close: requestClose(); return; + case previousPage: if (page) go(page - 1); return; + case nextPage: go(page + 1); return; + case firstPage: go(0); return; + case lastPage: go(pageTotal - 1); return; + case goToPage: + { + if (pageTotal <= 1) return; + PagePrompt prompt{search.style, page, pageTotal}; + if (prompt.style.run(GetModuleHandleW(nullptr), MAKEINTRESOURCEW(602), window, pageDialog, + reinterpret_cast(&prompt)) == IDOK) go(prompt.page); + return; + } + case findText: openFind(); return; + case findNext: find((search.flags & FR_DOWN) != 0, search.flags); return; + case undo: if (edit) send(SCI_UNDO); return; + case redo: if (edit) send(SCI_REDO); return; + case cut: if (edit) send(SCI_CUT); return; + case copy: send(SCI_COPY); return; + case paste: if (edit) send(SCI_PASTE); return; + case selectAll: send(SCI_SELECTALL); return; + case lexerAuto: language = automatic; installLexer(); return; + case lexerPlain: language = {}; installLexer(); return; + case options: + search.style.options(window, edit); + SetFocus(editor); + return; + default: + if (id >= lexerStart && id - lexerStart < lexers.size()) + { + const auto &name = lexers[id - lexerStart]; + language = name == automatic.lexer ? automatic : TextLanguage{name}; + installLexer(); + return; + } + return; + } +} + +void TextWindow::notify(const SCNotification ¬ice) +{ + if (loading) return; + switch (notice.nmhdr.code) + { + case SCN_MODIFIED: + if (notice.modificationType & SC_MOD_INSERTCHECK) + { + if (send(SCI_GETLENGTH) + notice.length > static_cast(TextDocument::editLimit)) + { + send(SCI_CHANGEINSERTION, 0, reinterpret_cast("")); + insertRejected = true; + MessageBeep(MB_ICONWARNING); + } + else insertRejected = false; + } + if (notice.modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT)) + { + if (notice.linesAdded) updateLineNumberMargin(); + undoBytes += static_cast(notice.length) + 64; + if (undoBytes >= 32 * TextDocument::pageBytes) + PostMessageW(window, trimUndo, 0, 0); + } + invalidate(); + break; + case SCN_CHARADDED: + if (edit && prefs.autoIndent && (notice.ch == '\n' || (notice.ch == '\r' && send(SCI_GETEOLMODE) == SC_EOL_CR))) + { + const auto position = send(SCI_GETCURRENTPOS); + const auto line = send(SCI_LINEFROMPOSITION, position); + if (line) + { + send(SCI_SETLINEINDENTATION, line, send(SCI_GETLINEINDENTATION, line - 1)); + send(SCI_GOTOPOS, send(SCI_GETLINEINDENTPOSITION, line)); + } + } + break; + case SCN_ZOOM: + updateLineNumberMargin(); + break; + case SCN_UPDATEUI: + case SCN_SAVEPOINTREACHED: + case SCN_SAVEPOINTLEFT: + invalidate(); + break; + } +} + +bool TextWindow::handleKey(const MSG &message) +{ + const auto key = message.wParam; + if (message.hwnd != editor) return false; + if (message.message == WM_SYSKEYDOWN && (message.lParam & (1LL << 29))) + { + for (size_t index = 0; index < menuBarLabels.size(); ++index) + if (menuBarLabels[index].matches(static_cast(key))) + { + SendMessageW(window, WM_COMMAND, 600 + index, 0); + return true; + } + } + if (message.message == WM_KEYDOWN || + (message.message == WM_SYSKEYDOWN && key == VK_F10 && !(message.lParam & (1LL << 29)))) + { + const bool ctrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0; + const bool shift = (GetKeyState(VK_SHIFT) & 0x8000) != 0; + UINT id{}; + if (key == VK_F2 || (ctrl && key == 'S')) id = save; + if (key == VK_F3) id = findNext; + if (key == VK_F5 || (ctrl && key == 'G')) id = goToPage; + if (key == VK_F9) id = 600; + if (key == VK_ESCAPE || key == VK_F10) id = close; + if (ctrl && key == 'F') id = findText; + if (ctrl && key == VK_PRIOR) id = previousPage; + if (ctrl && key == VK_NEXT) id = nextPage; + if (ctrl && shift && key == VK_HOME) id = firstPage; + if (ctrl && shift && key == VK_END) id = lastPage; + if (id) { SendMessageW(window, WM_COMMAND, id, 0); return true; } + } + return false; +} + +LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam, LPARAM lparam) +{ + if (message == WM_NCCREATE) + { + const auto create = reinterpret_cast(lparam); + const auto self = static_cast(create->lpCreateParams); + self->window = window; + SetWindowLongPtrW(window, GWLP_USERDATA, reinterpret_cast(self)); + } + const auto self = reinterpret_cast(GetWindowLongPtrW(window, GWLP_USERDATA)); + if (!self) return DefWindowProcW(window, message, wparam, lparam); + try + { + if (message == preferencesChanged) + { + self->reloadPreferences(); + return 0; + } + switch (message) + { + case WM_CREATE: + self->editor = CreateWindowExW(0, L"Scintilla", L"", WS_CHILD | WS_VISIBLE | WS_TABSTOP | + WS_VSCROLL | WS_HSCROLL, 0, 0, 0, 0, window, nullptr, GetModuleHandleW(nullptr), nullptr); + if (!self->editor) throw std::runtime_error("Cannot create the text control."); + self->send(SCI_SETCODEPAGE, SC_CP_UTF8); + self->send(SCI_SETMARGINS, 1); + self->send(SCI_SETMODEVENTMASK, SC_MOD_INSERTCHECK | SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT); + self->createMenu(); + self->installLexer(); + self->loadPage(0); + self->layout(); + return 0; + case WM_ERASEBKGND: return 1; + case WM_PAINT: self->paint(); return 0; + case WM_SIZE: self->layout(); return 0; + case WM_DPICHANGED: + { + const auto area = reinterpret_cast(lparam); + SetWindowPos(window, nullptr, area->left, area->top, area->right - area->left, + area->bottom - area->top, SWP_NOZORDER | SWP_NOACTIVATE); + self->updateLineNumberMargin(); + self->layout(); + return 0; + } + case WM_SETFOCUS: SetFocus(self->editor); return 0; + case WM_INITMENU: self->updateMenus(); return 0; + case WM_MENUCHAR: return self->menuKey(reinterpret_cast(lparam), LOWORD(wparam)); + case WM_MEASUREITEM: + if (self->measureMenu(*reinterpret_cast(lparam))) return TRUE; + break; + case WM_DRAWITEM: + if (self->drawMenu(*reinterpret_cast(lparam))) return TRUE; + break; + case WM_LBUTTONDOWN: + { + const POINT point{static_cast(LOWORD(lparam)), static_cast(HIWORD(lparam))}; + for (size_t index = 0; index < self->menuBounds.size(); ++index) + if (PtInRect(&self->menuBounds[index], point)) self->openMenu(static_cast(index)); + return 0; + } + case WM_COMMAND: + if (LOWORD(wparam) >= 600 && LOWORD(wparam) < 605) self->openMenu(LOWORD(wparam) - 600); + else self->command(LOWORD(wparam)); + return 0; + case WM_CLOSE: + if (!self->search.style.dismissOwned(window)) self->requestClose(); + return 0; + case WM_NOTIFY: + if (reinterpret_cast(lparam)->hwndFrom == self->editor) + self->notify(*reinterpret_cast(lparam)); + return 0; + case WM_TIMER: + if (wparam == saveTimer) self->finishSave(); + return 0; + case trimUndo: + if (self->undoBytes >= 32 * TextDocument::pageBytes) + { + const bool changed = self->send(SCI_GETMODIFY); + self->send(SCI_EMPTYUNDOBUFFER); + if (changed) self->send(SCI_SETUNDOSAVEPOINT, static_cast(-1)); + self->undoBytes = 0; + } + return 0; + case WM_DESTROY: + self->releaseMenu(); + self->window = nullptr; + return 0; + } + } + catch (const std::exception &error) + { + self->search.style.message(window, wide(error.what()).c_str()); + self->invalidate(); + return message == WM_CREATE ? -1 : 0; + } + return DefWindowProcW(window, message, wparam, lparam); +} +} + +std::vector loadFarHistory(FarHistoryKind kind) +{ + return readFarHistory(kind); +} + +void installFarHistoryKey(HWND field,int arrowId) +{ + SetWindowSubclass(field,searchFieldKeys,1,arrowId); +} + +void rememberFarHistory(FarHistoryKind kind,std::wstring_view text) +{ + writeFarHistory(kind,text); +} + +int chooseFarDropDown(HWND anchor,const std::vector &entries,int selected, + FarDropDownPalette palette,int rightInset) +{ + const auto owner=GetAncestor(anchor,GA_ROOT); + if(entries.empty() || !owner || GetPropW(owner,farDropDownProperty)) return -1; + selected=std::clamp(selected,0,static_cast(entries.size())-1); + FarPopup state{}; + state.palette=palette; + state.font=reinterpret_cast(SendMessageW(anchor,WM_GETFONT,0,0)); + const auto dpi=GetDpiForWindow(anchor); + state.inset=std::max(2,MulDiv(5,dpi,96)); + RECT field{}; + GetWindowRect(anchor,&field); + state.rowHeight=std::max(1L,field.bottom-field.top); + if(const auto dc=GetDC(anchor)) + { + const auto old=SelectObject(dc,state.font); + TEXTMETRICW metrics{}; + if(GetTextMetricsW(dc,&metrics)) state.rowHeight=metrics.tmHeight; + SelectObject(dc,old); + ReleaseDC(anchor,dc); + } + std::wstring_view previous; + for(size_t index=0;index(index)==selected) state.current=static_cast(state.rows.size()); + state.rows.push_back({entry.text,static_cast(index)}); + } + MONITORINFO monitor{sizeof(monitor)}; + if(!GetMonitorInfoW(MonitorFromWindow(anchor,MONITOR_DEFAULTTONEAREST),&monitor)) return -1; + const auto &work=monitor.rcWork; + const bool above=work.bottom-field.bottom<4*state.rowHeight+2*state.inset && + field.top-work.top>work.bottom-field.bottom; + const auto space=above?field.top-work.top:work.bottom-field.bottom; + state.visible=std::clamp((space-state.rowTop()-state.bottomMargin())/state.rowHeight,1, + std::min(9,static_cast(state.rows.size()))); + state.select(state.current); + const auto height=state.visible*state.rowHeight+state.rowTop()+state.bottomMargin(); + const auto width=std::clamp(field.right-field.left-rightInset,1L,work.right-work.left); + const auto left=std::clamp(field.left,work.left,work.right-width); + const auto instance=GetModuleHandleW(nullptr); + WNDCLASSW type{}; + type.lpfnWndProc=farPopupWindow; + type.hInstance=instance; + type.hCursor=LoadCursorW(nullptr,IDC_ARROW); + type.lpszClassName=L"KSwitcher.Files.DropDown"; + RegisterClassW(&type); + const auto window=CreateWindowExW(WS_EX_TOOLWINDOW,type.lpszClassName,L"",WS_POPUP, + left,above?field.top-height:field.bottom,width,height,owner,nullptr,instance,&state); + if(!window) return -1; + SetPropW(owner,farDropDownProperty,window); + ShowWindow(window,SW_SHOW); + SetFocus(window); + SetCapture(window); + MSG message{}; + while(!state.done) + { + const auto status=GetMessageW(&message,nullptr,0,0); + if(status<=0) + { + if(status==0) PostQuitMessage(static_cast(message.wParam)); + break; + } + if(message.hwnd!=window && message.message==WM_KEYDOWN) + message.hwnd=window; + TranslateMessage(&message); + DispatchMessageW(&message); + } + if(GetCapture()==window) ReleaseCapture(); + RemovePropW(owner,farDropDownProperty); + if(IsWindow(window)) DestroyWindow(window); + if(IsWindow(anchor)) SetFocus(anchor); + return state.result; +} + +void showFarHistory(HWND dialog,int fieldId,const std::vector &history, + FarDropDownPalette palette) +{ + showHistoryPopup(dialog,fieldId,history,palette); +} + +void openTextWindow(HWND owner, const std::filesystem::path &path, bool edit, TextDialogs dialogs) +{ + try + { + const auto instance = GetModuleHandleW(nullptr); + static const bool registered = [instance] { + WNDCLASSW type{}; + type.hInstance = instance; + type.hCursor = LoadCursorW(nullptr, IDC_ARROW); + type.hIcon = LoadIconW(instance, MAKEINTRESOURCEW(1)); + type.lpfnWndProc = TextWindow::procedure; + type.lpszClassName = windowClass; + return Scintilla_RegisterClasses(instance) && RegisterClassW(&type); + }(); + if (!registered) throw std::runtime_error("Cannot register the text window."); + TextWindow state(path, edit, dialogs); + const auto title = std::wstring(edit ? L"Editor — " : L"Viewer — ") + path.wstring(); + RECT bounds{}; + GetWindowRect(owner, &bounds); + const auto window = CreateWindowExW(0, windowClass, title.c_str(), WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, + bounds.left, bounds.top, bounds.right - bounds.left, bounds.bottom - bounds.top, owner, nullptr, instance, &state); + if (!window) return; + const auto focus = GetFocus(); + EnableWindow(owner, FALSE); + ShowWindow(window, IsZoomed(owner) ? SW_MAXIMIZE : SW_SHOW); + SetFocus(state.editor); + MSG message{}; + while (state.window) + { + const auto result = GetMessageW(&message, nullptr, 0, 0); + if (result <= 0) + { + if (result == 0) PostQuitMessage(static_cast(message.wParam)); + DestroyWindow(window); + break; + } + if (state.handleKey(message)) continue; + TranslateMessage(&message); + DispatchMessageW(&message); + } + EnableWindow(owner, TRUE); + SetActiveWindow(owner); + if (IsWindow(focus)) SetFocus(focus); + } + catch (const std::exception &error) { dialogs.message(owner, wide(error.what()).c_str()); } +} +} diff --git a/src/files_text_window.h b/src/files_text_window.h new file mode 100644 index 0000000..4a68bf6 --- /dev/null +++ b/src/files_text_window.h @@ -0,0 +1,51 @@ +#pragma once + +#include +#include +#include + +namespace ks::files +{ +inline constexpr int searchOptionsDivider = 104; +inline constexpr int searchButtonsDivider = 105; +inline constexpr int searchHistoryButton = 108; +inline constexpr wchar_t farDropDownProperty[]=L"KSwitcher.Files.ActiveDropDown"; + +struct TextWindowFont +{ + LOGFONTW font; + int tenthsOfPoint; +}; + +struct FarDropDownPalette +{ + COLORREF surface, text, selection; +}; + +enum class FarHistoryKind { search, folder }; +struct FarHistoryEntry { std::wstring date,text; }; +std::vector loadFarHistory(FarHistoryKind kind); +void rememberFarHistory(FarHistoryKind kind,std::wstring_view text); +int chooseFarDropDown(HWND anchor,const std::vector &entries,int selected, + FarDropDownPalette palette,int rightInset=0); +void showFarHistory(HWND dialog,int fieldId,const std::vector &history, + FarDropDownPalette palette); +void installFarHistoryKey(HWND field,int arrowId); + +struct TextDialogs +{ + INT_PTR (*confirmSave)(HWND); + INT_PTR (*paint)(HWND, UINT, WPARAM, LPARAM, const wchar_t *); + INT_PTR (*paintSearch)(HWND, UINT, WPARAM, LPARAM); + void (*prepare)(HWND); + void (*options)(HWND, bool); + void (*message)(HWND, const wchar_t *); + TextWindowFont (*readFont)(); + FarDropDownPalette (*dropDownPalette)(); + INT_PTR (*run)(HINSTANCE,LPCWSTR,HWND,DLGPROC,LPARAM); + void (*finish)(HWND,INT_PTR); + bool (*dismissOwned)(HWND); +}; + +void openTextWindow(HWND owner, const std::filesystem::path &path, bool edit, TextDialogs dialogs); +} diff --git a/src/lan_files.cpp b/src/lan_files.cpp index 52efc31..9b7c36b 100644 --- a/src/lan_files.cpp +++ b/src/lan_files.cpp @@ -2,8 +2,10 @@ #include #include #include +#include #include #include +#include #include #include "lan_files.h" #include "lan_channel.h" @@ -52,6 +54,44 @@ bool recycleFile(HWND owner,const fs::path &path) namespace { +DWORD createJunction(const fs::path &name,const fs::path &target) +{ + if(!target.is_absolute() || target.root_name().native().size()!=2) return ERROR_INVALID_NAME; + const auto print=target.lexically_normal().native(); + const auto substitute=L"\\??\\"+print; + struct MountPointHeader + { + DWORD tag; + WORD dataLength,reserved,substituteOffset,substituteLength,printOffset,printLength; + }; + const auto substituteBytes=substitute.size()*sizeof(wchar_t); + const auto printBytes=print.size()*sizeof(wchar_t); + const auto pathBytes=substituteBytes+printBytes+2*sizeof(wchar_t); + if(sizeof(MountPointHeader)+pathBytes>MAXIMUM_REPARSE_DATA_BUFFER_SIZE) return ERROR_FILENAME_EXCED_RANGE; + const MountPointHeader header{IO_REPARSE_TAG_MOUNT_POINT,static_cast(8+pathBytes),0,0, + static_cast(substituteBytes),static_cast(substituteBytes+sizeof(wchar_t)), + static_cast(printBytes)}; + std::vector buffer(sizeof(header)+pathBytes); + std::memcpy(buffer.data(),&header,sizeof(header)); + std::memcpy(buffer.data()+sizeof(header),substitute.c_str(),substituteBytes); + std::memcpy(buffer.data()+sizeof(header)+header.printOffset,print.c_str(),printBytes); + + if(!CreateDirectoryW(name.c_str(),nullptr)) return GetLastError(); + const auto handle=CreateFileW(name.c_str(),GENERIC_WRITE,0,nullptr,OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr); + DWORD error=ERROR_SUCCESS; + if(handle==INVALID_HANDLE_VALUE) error=GetLastError(); + else + { + DWORD returned{}; + if(!DeviceIoControl(handle,FSCTL_SET_REPARSE_POINT,buffer.data(),static_cast(buffer.size()), + nullptr,0,&returned,nullptr)) error=GetLastError(); + CloseHandle(handle); + } + if(error) RemoveDirectoryW(name.c_str()); + return error; +} + constexpr size_t FrameLimit=256*1024; constexpr DWORD SocketTimeout=5000; @@ -487,6 +527,20 @@ public: return error?failure(error.value()):Json{{"error",0},{"path",utf8(canonical.native())}}; } if(action=="mkdir") return CreateDirectoryW(name.c_str(),nullptr)?ok():failure(); + if(action=="mkdir-link") + { + const auto target=path(request.at("target")); + if(target.empty()) return failure(ERROR_INVALID_NAME); + const auto kind=request.at("kind").get(); + if(kind=="junction") + { + const auto error=createJunction(name,target); + return error?failure(error):ok(); + } + if(kind!="symlink") return failure(ERROR_INVALID_PARAMETER); + return CreateSymbolicLinkW(name.c_str(),target.c_str(), + SYMBOLIC_LINK_FLAG_DIRECTORY|SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)?ok():failure(); + } if(action=="rmdir") return RemoveDirectoryW(name.c_str())?ok():failure(); if(action=="recycle") return recycleFile(nullptr,name)?ok():failure(ERROR_ACCESS_DENIED); if(action=="remove") diff --git a/src/update.h b/src/update.h index 70def40..22b1862 100644 --- a/src/update.h +++ b/src/update.h @@ -2,7 +2,7 @@ #include "platform.h" namespace ks { -inline constexpr wchar_t AppVersion[] = L"0.6.83"; +inline constexpr wchar_t AppVersion[] = L"0.6.84"; inline constexpr UINT UpdateMessage = WM_APP + 7; inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000; inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000; diff --git a/tests/files_modal_dialog.cpp b/tests/files_modal_dialog.cpp new file mode 100644 index 0000000..15b1bed --- /dev/null +++ b/tests/files_modal_dialog.cpp @@ -0,0 +1,60 @@ +#include +#include +#include +#include +#include +#include +#include +#include "files_text_window.h" + +namespace +{ +#include "files_dialog_input.inl" + +bool cancelled(HWND dialog) +{ + MSG message{}; + return PeekMessageW(&message,dialog,WM_COMMAND,WM_COMMAND,PM_REMOVE) && + LOWORD(message.wParam)==IDCANCEL; +} +} + +int main() +{ + const auto instance=GetModuleHandleW(nullptr); + const auto owner=CreateWindowW(L"STATIC",L"Files",WS_OVERLAPPEDWINDOW, + 0,0,300,200,nullptr,nullptr,instance,nullptr); + const auto dialog=CreateWindowW(L"STATIC",L"Search",WS_POPUP, + 0,0,200,100,owner,nullptr,instance,nullptr); + const auto external=CreateWindowW(L"STATIC",L"Other",WS_OVERLAPPEDWINDOW, + 0,0,300,200,nullptr,nullptr,instance,nullptr); + if(!owner || !dialog || !external) + { + std::cerr << "Could not create modal test windows.\n"; + return 1; + } + + POINT client{10,10},frame{10,-1}; + ClientToScreen(owner,&client); + ClientToScreen(owner,&frame); + if(handleFilesDialogClick(dialog,external,client) || + handleFilesDialogClick(dialog,GetDesktopWindow(),client) || + handleFilesDialogClick(dialog,nullptr,client) || cancelled(dialog)) + { + std::cerr << "A click outside Files cancelled the dialog.\n"; + return 1; + } + if(handleFilesDialogClick(dialog,owner,frame) || cancelled(dialog)) + { + std::cerr << "A click on the owner's frame cancelled the dialog.\n"; + return 1; + } + if(!handleFilesDialogClick(dialog,owner,client) || !cancelled(dialog)) + { + std::cerr << "A click in the Files client area did not cancel the dialog.\n"; + return 1; + } + DestroyWindow(owner); + DestroyWindow(external); + std::cout << "Verified Files modal handling of external, frame, and client-area clicks.\n"; +} diff --git a/tests/files_search_arrow.ps1 b/tests/files_search_arrow.ps1 new file mode 100644 index 0000000..d65ac0d --- /dev/null +++ b/tests/files_search_arrow.ps1 @@ -0,0 +1,565 @@ +param([Parameter(Mandatory)][string]$Executable) +$ErrorActionPreference='Stop' +Add-Type -AssemblyName System.Drawing +Add-Type @" +using System; +using System.Runtime.InteropServices; +using System.Text; +public static class SearchArrowTest { + [DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string name, string title); + [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window, out uint pid); + [DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr hwnd, int id); + [DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr hwnd, uint message, IntPtr w, IntPtr l); + [DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr SendText(IntPtr hwnd, uint message, IntPtr w, string l); + [DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr GetText(IntPtr hwnd, uint message, IntPtr w, StringBuilder l); + [DllImport("user32.dll")] public static extern bool PostMessage(IntPtr hwnd, uint message, IntPtr w, IntPtr l); + [StructLayout(LayoutKind.Sequential)] + public struct Rect { public int Left, Top, Right, Bottom; } + [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hwnd, IntPtr after, int x, int y, int w, int h, uint flags); + [DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context); + [DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr hwnd, IntPtr dc, uint flags); + [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hwnd, out Rect rect); + [DllImport("user32.dll")] public static extern bool IsWindow(IntPtr hwnd); + [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hwnd); + [DllImport("user32.dll")] public static extern bool IsWindowEnabled(IntPtr hwnd); + [StructLayout(LayoutKind.Sequential)] + struct GuiThreadInfo { + public int Size, Flags; + public IntPtr Active, Focus, Capture, MenuOwner, MoveSize, Caret; + public Rect CaretBounds; + } + [DllImport("user32.dll")] static extern bool GetGUIThreadInfo(uint thread, ref GuiThreadInfo info); + public static IntPtr FocusedControl(IntPtr window) { + var info = new GuiThreadInfo { Size = Marshal.SizeOf() }; + return GetGUIThreadInfo(GetWindowThreadProcessId(window, out _), ref info) ? info.Focus : IntPtr.Zero; + } + public static bool HasCheckboxCaret(IntPtr checkbox) { + var info = new GuiThreadInfo { Size = Marshal.SizeOf() }; + return GetGUIThreadInfo(GetWindowThreadProcessId(checkbox, out _), ref info) && + info.Caret == checkbox && info.CaretBounds.Left > 0 && + info.CaretBounds.Right > info.CaretBounds.Left && + info.CaretBounds.Bottom - info.CaretBounds.Top < info.CaretBounds.Right - info.CaretBounds.Left; + } +} +"@ +function Wait-Until($Block) { + for ($i=0; $i -lt 120; $i++) { + $value = & $Block + if ($value) { return $value } + Start-Sleep -Milliseconds 100 + } + throw "Timeout: $Block" +} +function Find-Window($Name, $ProcessId, [int]$ControlId=0) { + $wnd = [IntPtr]::Zero + while (($wnd = [SearchArrowTest]::FindWindowEx(0, $wnd, $Name, [System.Management.Automation.Language.NullString]::Value)) -ne [IntPtr]::Zero) { + [uint32]$ownerProcess = 0 + [void][SearchArrowTest]::GetWindowThreadProcessId($wnd, [ref]$ownerProcess) + if ($ownerProcess -eq $ProcessId -and [SearchArrowTest]::IsWindowVisible($wnd) -and + (!$ControlId -or [SearchArrowTest]::GetDlgItem($wnd,$ControlId) -ne [IntPtr]::Zero)) { return $wnd } + } +} +function Select-Row($Panel, $Name) { + $row = [SearchArrowTest]::SendText($Panel, 0x1A2, -1, $Name) + if ($row.ToInt64() -lt 0) { throw "Missing row $Name" } + [void][SearchArrowTest]::Send($Panel, 0x186, $row, 0) +} +function Post($Window, $Message, $W, $L = 0) { + if (![SearchArrowTest]::PostMessage($Window, $Message, $W, $L)) { throw "Post failed" } +} +function Assert-FarCheckbox($Dialog, [int]$Id, $NextControl) { + $checkbox=[SearchArrowTest]::GetDlgItem($Dialog,$Id) + Post $Dialog 0x28 $checkbox 1 + [void](Wait-Until { [SearchArrowTest]::HasCheckboxCaret($checkbox) }) + $checked=[SearchArrowTest]::Send($checkbox,0xF0,0,0) + [void][SearchArrowTest]::Send($checkbox,0xF5,0,0) + if ([SearchArrowTest]::Send($checkbox,0xF0,0,0) -eq $checked) { throw 'The Far checkbox did not toggle.' } + [void][SearchArrowTest]::Send($checkbox,0xF5,0,0) + Post $Dialog 0x28 $NextControl 1 + [void](Wait-Until { + [SearchArrowTest]::FocusedControl($Dialog) -eq $NextControl -and + ![SearchArrowTest]::HasCheckboxCaret($checkbox) + }) +} +function Read-Bounds($Window) { + $bounds=[SearchArrowTest+Rect]::new() + if (![SearchArrowTest]::GetWindowRect($Window,[ref]$bounds)) { throw 'Missing window bounds' } + $bounds +} +function Assert-FarFieldHeight($Dialog, [int[]]$Ids) { + $heights=@(foreach ($id in $Ids) { + $bounds=Read-Bounds ([SearchArrowTest]::GetDlgItem($Dialog,$id)) + $bounds.Bottom-$bounds.Top + }) + if (@($heights | Select-Object -Unique).Count -ne 1) { + throw "Far field heights differ: $heights." + } +} +function Assert-FarDropDown($Popup, $Anchor, [int]$ArrowWidth=0) { + $bounds=Read-Bounds $Popup + $anchorBounds=Read-Bounds $Anchor + if ($bounds.Left -ne $anchorBounds.Left -or $bounds.Top -ne $anchorBounds.Bottom -or + $bounds.Right -ne $anchorBounds.Right-$ArrowWidth) { + throw 'The Far list is not aligned with the field edges.' + } + $bitmap=[Drawing.Bitmap]::new($bounds.Right-$bounds.Left,$bounds.Bottom-$bounds.Top) + try { + $graphics=[Drawing.Graphics]::FromImage($bitmap) + try { + $dc=$graphics.GetHdc() + try { + if (![SearchArrowTest]::PrintWindow($Popup,$dc,0)) { throw 'Could not render Far list.' } + } finally { $graphics.ReleaseHdc($dc) } + } finally { $graphics.Dispose() } + $background=$bitmap.GetPixel(2,2) + if ($background.G -lt 85 -or $background.B -lt 85 -or $background.R -ge $background.G) { + throw "The Far list background is not teal: $background." + } + $frame=$false + $selection=$false + for ($y=3; $y -lt $bitmap.Height-3; $y++) { + $pixel=$bitmap.GetPixel([int]($bitmap.Width/3),$y) + if ($y -lt 16 -and $pixel.R -gt 220 -and $pixel.G -gt 220 -and $pixel.B -gt 220) { $frame=$true } + if ($pixel.R -lt 16 -and $pixel.G -lt 16 -and $pixel.B -lt 16) { $selection=$true } + } + if (!$frame -or !$selection) { throw 'The Far list is missing its light frame or black selected row.' } + } finally { $bitmap.Dispose() } +} +function Resize-Window($Window, $Bounds, [int]$Width, [switch]$Clamped) { + if (![SearchArrowTest]::SetWindowPos($Window,0,$Bounds.Left,$Bounds.Top,$Width, + ($Bounds.Bottom-$Bounds.Top),0x14)) { throw 'Could not resize the owner window.' } + if (!$Clamped) { + [void](Wait-Until { + $current=Read-Bounds $Window + $current.Right-$current.Left -eq $Width + }) + } +} +function Assert-MovesWithOwner($Owner, $Dialog) { + $ownerBefore=Read-Bounds $Owner + $dialogBefore=Read-Bounds $Dialog + $dx=17 + $dy=23 + if (![SearchArrowTest]::SetWindowPos($Owner,0,($ownerBefore.Left+$dx),($ownerBefore.Top+$dy),0,0,0x15)) { + throw 'Could not move the dialog owner.' + } + try { + for ($i=0; $i -lt 20; $i++) { + $ownerAfter=Read-Bounds $Owner + $dialogAfter=Read-Bounds $Dialog + $ownerDeltaX=$ownerAfter.Left-$ownerBefore.Left + $ownerDeltaY=$ownerAfter.Top-$ownerBefore.Top + $dialogDeltaX=$dialogAfter.Left-$dialogBefore.Left + $dialogDeltaY=$dialogAfter.Top-$dialogBefore.Top + if ($ownerDeltaX -eq $dx -and $ownerDeltaY -eq $dy -and + $dialogDeltaX -eq $dx -and $dialogDeltaY -eq $dy) { return } + Start-Sleep -Milliseconds 100 + } + throw "Expected movement ($dx, $dy). Owner moved ($ownerDeltaX, $ownerDeltaY), dialog moved ($dialogDeltaX, $dialogDeltaY)." + } finally { + [void][SearchArrowTest]::SetWindowPos($Owner,0,$ownerBefore.Left,$ownerBefore.Top,0,0,0x15) + } +} +$scratch=Join-Path ([IO.Path]::GetDirectoryName((Resolve-Path -LiteralPath $Executable).Path)) ('search-arrow-test-' + [Guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $scratch | Out-Null +$fixture = Join-Path $scratch ('files-editor-ui-' + [Guid]::NewGuid().ToString('N') + '.cs') +[IO.File]::WriteAllText($fixture, "public class Test {`r`n}`r`n") +$copy=Join-Path $scratch 'KSwitcher.Files.search-arrow-test.exe' +Copy-Item -LiteralPath $Executable -Destination $copy +$process = Start-Process -FilePath $copy -PassThru -WindowStyle Hidden +try { + $previousDpi=[SearchArrowTest]::SetThreadDpiAwarenessContext([IntPtr](-4)) + $main = Wait-Until { Find-Window 'KSwitcher.Files' $process.Id } + $panel = Wait-Until { $handle = [SearchArrowTest]::GetDlgItem($main,102); if ($handle -ne [IntPtr]::Zero) { $handle } } + $pathControl = [SearchArrowTest]::GetDlgItem($main,142) + $pathText = [Text.StringBuilder]::new(1024) + [void][SearchArrowTest]::GetText($pathControl,0xD,$pathText.Capacity,$pathText) + $path=$pathText.ToString() + if ([IO.Path]::GetPathRoot($path) -ne [IO.Path]::GetPathRoot($scratch)) { + throw 'Select a local left-panel folder on the test executable drive before running this interactive test.' + } + foreach ($component in $path.Substring(3).Split('\',[System.StringSplitOptions]::RemoveEmptyEntries)) { + Select-Row $panel '..' + [void][SearchArrowTest]::Send($panel,0x100,13,0) + } + foreach ($component in $scratch.Substring(3).Split('\')) { + Select-Row $panel "[$component]" + [void][SearchArrowTest]::Send($panel,0x100,13,0) + } + $newFolder='F7 тестова папка' + Post $panel 0x100 0x76 + $makeDialog=Wait-Until { Find-Window '#32770' $process.Id 361 } + $nameField=[SearchArrowTest]::GetDlgItem($makeDialog,361) + Assert-FarFieldHeight $makeDialog @(361,363,365,367) + $nameBounds=Read-Bounds $nameField + $arrowBounds=Read-Bounds ([SearchArrowTest]::GetDlgItem($makeDialog,363)) + if ($nameBounds.Right -ne $arrowBounds.Left) { throw 'F7 history arrow does not touch the field.' } + $okButton=Read-Bounds ([SearchArrowTest]::GetDlgItem($makeDialog,1)) + $cancelButton=Read-Bounds ([SearchArrowTest]::GetDlgItem($makeDialog,2)) + $okWidth=$okButton.Right-$okButton.Left + $gap=$cancelButton.Left-$okButton.Right + if ($gap -lt 0 -or $gap -gt $okWidth/7 -or $cancelButton.Right-$cancelButton.Left -le $okWidth) { + throw 'Make folder buttons are not grouped at their caption widths.' + } + [void][SearchArrowTest]::SendText($nameField,0xC,0,$newFolder) + Post $makeDialog 0x111 1 + [void](Wait-Until { ![SearchArrowTest]::IsWindow($makeDialog) }) + if (!(Test-Path -LiteralPath (Join-Path $scratch $newFolder) -PathType Container)) { + throw 'F7 did not create the folder in the active panel.' + } + $newRow=[SearchArrowTest]::SendText($panel,0x1A2,-1,"[$newFolder]") + if ($newRow.ToInt64() -lt 0 -or [SearchArrowTest]::Send($panel,0x188,0,0) -ne $newRow) { + throw 'F7 did not select the new folder.' + } + Post $main 0x111 115 + $makeDialog=Wait-Until { Find-Window '#32770' $process.Id 361 } + $nameField=[SearchArrowTest]::GetDlgItem($makeDialog,361) + [void][SearchArrowTest]::SendText($nameField,0xC,0,$newFolder) + Post $makeDialog 0x111 1 + $folderError=Wait-Until { Find-Window '#32770' $process.Id 100 } + Post $folderError 0x111 1 + [void](Wait-Until { + ![SearchArrowTest]::IsWindow($folderError) -and + [SearchArrowTest]::FocusedControl($makeDialog) -eq $nameField + }) + [void][SearchArrowTest]::SendText($nameField,0xC,0,'Canceled folder') + Post $nameField 0x100 27 + [void](Wait-Until { ![SearchArrowTest]::IsWindow($makeDialog) }) + if (Test-Path -LiteralPath (Join-Path $scratch 'Canceled folder')) { throw 'Canceled F7 created a folder.' } + Write-Output 'Verified F7 folder creation, selection, duplicate error, and cancellation.' + Post $panel 0x100 0x76 + $makeDialog=Wait-Until { Find-Window '#32770' $process.Id 361 } + $nameField=[SearchArrowTest]::GetDlgItem($makeDialog,361) + if (![SearchArrowTest]::IsWindowEnabled([SearchArrowTest]::GetDlgItem($makeDialog,363))) { + throw 'F7 did not persist the folder name in history.' + } + Post $makeDialog 0x111 363 + $popup=Wait-Until { Find-Window 'KSwitcher.Files.DropDown' $process.Id } + Assert-FarDropDown $popup $nameField + Post $popup 0x100 13 + [void](Wait-Until { ![SearchArrowTest]::IsWindow($popup) }) + $chosen=[Text.StringBuilder]::new(256) + [void][SearchArrowTest]::GetText($nameField,0xD,$chosen.Capacity,$chosen) + if ($chosen.ToString() -ne $newFolder) { throw 'The history list did not fill in the selected name.' } + Post $makeDialog 0x111 363 + $popup=Wait-Until { Find-Window 'KSwitcher.Files.DropDown' $process.Id } + Post $popup 0x100 27 + [void](Wait-Until { + ![SearchArrowTest]::IsWindow($popup) -and [SearchArrowTest]::FocusedControl($makeDialog) -eq $nameField + }) + $targetField=[SearchArrowTest]::GetDlgItem($makeDialog,367) + if ([SearchArrowTest]::IsWindowEnabled($targetField)) { throw 'Target is enabled with link type none.' } + $multiple=[SearchArrowTest]::GetDlgItem($makeDialog,368) + [void][SearchArrowTest]::Send($multiple,0xF1,1,0) + [void][SearchArrowTest]::SendText($nameField,0xC,0,'Alpha;"Beta, Gamma", Delta') + Post $makeDialog 0x111 1 + [void](Wait-Until { ![SearchArrowTest]::IsWindow($makeDialog) }) + foreach ($name in 'Alpha','Beta, Gamma','Delta') { + if (!(Test-Path -LiteralPath (Join-Path $scratch $name) -PathType Container)) { + throw "F7 did not create '$name' in the batch." + } + } + [IO.File]::WriteAllText((Join-Path $scratch 'Alpha\link-target.txt'),'F7 link target') + foreach ($kind in 1,2) { + Post $panel 0x100 0x76 + $makeDialog=Wait-Until { Find-Window '#32770' $process.Id 361 } + $nameField=[SearchArrowTest]::GetDlgItem($makeDialog,361) + $selector=[SearchArrowTest]::GetDlgItem($makeDialog,365) + $targetField=[SearchArrowTest]::GetDlgItem($makeDialog,367) + Post $selector 0x100 0x73 + $popup=Wait-Until { Find-Window 'KSwitcher.Files.DropDown' $process.Id } + Assert-FarDropDown $popup $selector ($arrowBounds.Right-$arrowBounds.Left) + for ($row=0; $row -lt $kind; $row++) { Post $popup 0x100 0x28 } + Post $popup 0x100 13 + [void](Wait-Until { ![SearchArrowTest]::IsWindow($popup) }) + [void](Wait-Until { [SearchArrowTest]::IsWindowEnabled($targetField) }) + $linkName="Folder link $kind" + [void][SearchArrowTest]::SendText($nameField,0xC,0,$linkName) + [void][SearchArrowTest]::SendText($targetField,0xC,0,'Alpha') + Post $makeDialog 0x111 1 + $linkPath=Join-Path $scratch $linkName + $outcome=Wait-Until { + if (![SearchArrowTest]::IsWindow($makeDialog)) { 'created' } + elseif (Find-Window '#32770' $process.Id 100) { 'error' } + } + if ($outcome -eq 'error' -and $kind -eq 2) { + # The test host can deny symlink creation by policy. Confirm the same result with Windows. + $probe=Join-Path $scratch 'Symbolic link privilege probe' + try { + [void][IO.Directory]::CreateSymbolicLink($probe,(Join-Path $scratch 'Alpha')) + throw 'Windows can create symbolic links, but F7 reported an error.' + } catch { + if ($_.Exception.InnerException -isnot [IO.IOException] -and + $_.Exception.InnerException -isnot [UnauthorizedAccessException]) { throw } + } + $alert=Find-Window '#32770' $process.Id 100 + Post $alert 0x111 1 + [void](Wait-Until { ![SearchArrowTest]::IsWindow($alert) }) + Post $makeDialog 0x111 2 + [void](Wait-Until { ![SearchArrowTest]::IsWindow($makeDialog) }) + Write-Output 'Windows denied directory symbolic link creation and F7 reported the error.' + continue + } + if ($outcome -ne 'created') { throw "F7 failed to create link type $kind." } + $link=Get-Item -LiteralPath $linkPath + $expected=if ($kind -eq 1) { 'Junction' } else { 'SymbolicLink' } + if ($link.LinkType -ne $expected -or + !(Test-Path -LiteralPath (Join-Path $linkPath 'link-target.txt') -PathType Leaf)) { + throw "F7 did not create a $expected pointing to Alpha." + } + } + Write-Output 'Verified F7 history, quoted batch names, and directory link handling.' + Select-Row $panel ([IO.Path]::GetFileName($fixture)) + Post $panel 0x100 0x74 + $copyDialog=Wait-Until { + $dialog=Find-Window '#32770' $process.Id + if ($dialog -and [SearchArrowTest]::GetDlgItem($dialog,211) -ne [IntPtr]::Zero) { $dialog } + } + if (![SearchArrowTest]::IsWindowEnabled($main)) { throw 'Copy disabled the Files frame.' } + Assert-FarFieldHeight $copyDialog @(211,213) + Assert-MovesWithOwner $main $copyDialog + $mainBounds=Read-Bounds $main + $copyBounds=Read-Bounds $copyDialog + $copyPreferred=$copyBounds.Right-$copyBounds.Left + try { + Resize-Window $main $mainBounds ([Math]::Max(540,[int]($copyPreferred*0.65))) -Clamped + [void](Wait-Until { + $current=Read-Bounds $copyDialog + $current.Right-$current.Left -lt $copyPreferred + }) + } finally { + Resize-Window $main $mainBounds ($mainBounds.Right-$mainBounds.Left) + } + [void](Wait-Until { + $current=Read-Bounds $copyDialog + $current.Right-$current.Left -eq $copyPreferred + }) + $destination=[SearchArrowTest]::GetDlgItem($copyDialog,211) + Assert-FarCheckbox $copyDialog 214 $destination + if ([SearchArrowTest]::GetDlgItem($copyDialog,328) -ne [IntPtr]::Zero) { throw 'Copy has an inline error row.' } + $compact=Read-Bounds $copyDialog + [void][SearchArrowTest]::SendText($destination,0xC,0,'') + Post $copyDialog 0x111 1 + $alert=Wait-Until { Find-Window '#32770' $process.Id 100 } + $alertBounds=Read-Bounds $alert + $alertText=Read-Bounds ([SearchArrowTest]::GetDlgItem($alert,100)) + $alertButton=Read-Bounds ([SearchArrowTest]::GetDlgItem($alert,1)) + if ($alertText.Bottom-$alertText.Top -gt 2*($alertButton.Bottom-$alertButton.Top) -or + $alertButton.Top-$alertText.Bottom -gt $alertButton.Bottom-$alertButton.Top) { + throw 'The short error alert has excess space around the message.' + } + $bitmap=[Drawing.Bitmap]::new($alertBounds.Right-$alertBounds.Left,$alertBounds.Bottom-$alertBounds.Top) + try { + $graphics=[Drawing.Graphics]::FromImage($bitmap) + try { + $dc=$graphics.GetHdc() + try { + if (![SearchArrowTest]::PrintWindow($alert,$dc,0)) { throw 'Could not render the path alert.' } + } finally { $graphics.ReleaseHdc($dc) } + } finally { $graphics.Dispose() } + $background=$bitmap.GetPixel(4,4) + if ($background.R -lt 100 -or $background.G -gt 20 -or $background.B -gt 20) { + throw "Path alert did not use the red warning surface. Got $background." + } + } finally { $bitmap.Dispose() } + Post $alert 0x111 1 + [void](Wait-Until { + ![SearchArrowTest]::IsWindow($alert) -and [SearchArrowTest]::FocusedControl($copyDialog) -eq $destination + }) + $current=Read-Bounds $copyDialog + if ($current.Bottom-$current.Top -ne $compact.Bottom-$compact.Top) { throw 'The error resized Copy vertically.' } + Write-Output 'Verified the red path alert and focus restoration to Copy.' + Post $panel 0x201 1 + [void](Wait-Until { ![SearchArrowTest]::IsWindow($copyDialog) }) + + function Open-Search { + Post $editor 0x111 3 + Wait-Until { + $dialog=Find-Window '#32770' $process.Id + if ($dialog -and [SearchArrowTest]::GetDlgItem($dialog,108) -ne [IntPtr]::Zero) { $dialog } + } + } + + function Assert-Arrow($Dialog, [bool]$Enabled) { + $arrow=[SearchArrowTest]::GetDlgItem($Dialog,108) + $arrowBounds=[SearchArrowTest+Rect]::new() + $dialogBounds=[SearchArrowTest+Rect]::new() + if (![SearchArrowTest]::GetWindowRect($arrow,[ref]$arrowBounds) -or + ![SearchArrowTest]::GetWindowRect($Dialog,[ref]$dialogBounds)) { throw 'Missing Search bounds' } + if ([SearchArrowTest]::IsWindowEnabled($arrow) -ne $Enabled) { throw 'Unexpected history button state' } + $bitmap=[Drawing.Bitmap]::new($dialogBounds.Right-$dialogBounds.Left,$dialogBounds.Bottom-$dialogBounds.Top) + try { + $graphics=[Drawing.Graphics]::FromImage($bitmap) + try { + $dc=$graphics.GetHdc() + try { + if (![SearchArrowTest]::PrintWindow($Dialog,$dc,0)) { throw 'Could not render the Search dialog' } + } finally { $graphics.ReleaseHdc($dc) } + } finally { $graphics.Dispose() } + $x=$arrowBounds.Left-$dialogBounds.Left + $y=$arrowBounds.Top-$dialogBounds.Top + $width=$arrowBounds.Right-$arrowBounds.Left + $height=$arrowBounds.Bottom-$arrowBounds.Top + $field=Read-Bounds ([SearchArrowTest]::GetDlgItem($Dialog,100)) + $inset=$field.Left-$dialogBounds.Left + foreach ($dividerId in 104,105) { + $divider=Read-Bounds ([SearchArrowTest]::GetDlgItem($Dialog,$dividerId)) + $line=$divider.Top-$dialogBounds.Top + for ($column=$inset; $column -lt $bitmap.Width-$inset; $column++) { + $pixel=$bitmap.GetPixel($column,$line) + if ($pixel.R -ne 0 -or $pixel.G -ne 0 -or $pixel.B -ne 0) { + throw "Search divider $dividerId is broken at pixel $column." + } + } + } + $background=$bitmap.GetPixel($x+2,$y+2) + if ([Math]::Abs($background.R-$background.G) -gt 1 -or + [Math]::Abs($background.G-$background.B) -gt 1 -or $background.R -lt 175) { + throw "Expected a light gray arrow slot, got $background." + } + $ink=@(for ($row=1; $row -lt $height-1; $row++) { + for ($column=1; $column -lt $width-1; $column++) { + $pixel=$bitmap.GetPixel($x+$column,$y+$row) + if ($background.R-[Math]::Max($pixel.R,[Math]::Max($pixel.G,$pixel.B)) -ge 100) { $row; break } + } + }) + if ($ink.Count -lt [Math]::Max(5,$height/3)) { throw 'The arrow is missing or has insufficient contrast.' } + if ([Math]::Abs($ink[0]+$ink[-1]-($height-1)) -gt 2) { + throw "The arrow is vertically off center. Ink spans rows $($ink[0])–$($ink[-1]) in a $height-pixel slot." + } + } finally { $bitmap.Dispose() } + } + + Post $panel 0x100 0x73 + $editor=Wait-Until { Find-Window 'KSwitcher.Files.Text' $process.Id } + $originalFocus=Wait-Until { + $focus=[SearchArrowTest]::FocusedControl($editor) + if ($focus -ne [IntPtr]::Zero) { $focus } + } + foreach ($action in 'Escape','outside click','owner close') { + $dialog=Open-Search + $field=[SearchArrowTest]::GetDlgItem($dialog,100) + [void](Wait-Until { [SearchArrowTest]::FocusedControl($dialog) -eq $field }) + if (![SearchArrowTest]::IsWindowEnabled($editor)) { throw 'Search disabled the editor frame.' } + switch ($action) { + 'Escape' { + Assert-MovesWithOwner $editor $dialog + $ownerBounds=Read-Bounds $editor + $dialogBounds=Read-Bounds $dialog + $originalWidth=$ownerBounds.Right-$ownerBounds.Left + $preferred=$dialogBounds.Right-$dialogBounds.Left + try { + Resize-Window $editor $ownerBounds ([int]($preferred*0.92)) + $reduced=Wait-Until { + $current=Read-Bounds $dialog + $width=$current.Right-$current.Left + if ($width -lt $preferred) { $width } + } + Assert-Arrow $dialog $false + Resize-Window $editor $ownerBounds ([int]($preferred*0.30)) -Clamped + $minimum=Wait-Until { + $current=Read-Bounds $dialog + if ($current.Right-$current.Left -lt $reduced) { $current } + } + $floor=$minimum.Right-$minimum.Left + Resize-Window $editor $ownerBounds ([int]($preferred*0.25)) -Clamped + $stillMinimum=Read-Bounds $dialog + $narrowOwner=Read-Bounds $editor + if ($floor -ne ($stillMinimum.Right-$stillMinimum.Left) -or + $stillMinimum.Left -lt $narrowOwner.Left -or $stillMinimum.Right -gt $narrowOwner.Right) { + throw 'The editor shrank below the minimum width needed to contain Search.' + } + $previous=Read-Bounds ([SearchArrowTest]::GetDlgItem($dialog,103)) + $next=Read-Bounds ([SearchArrowTest]::GetDlgItem($dialog,1)) + if ($previous.Bottom -gt $next.Top) { throw 'The narrow Search actions are not on separate rows.' } + Assert-Arrow $dialog $false + } finally { + Resize-Window $editor $ownerBounds $originalWidth + } + [void](Wait-Until { + $restored=Read-Bounds $dialog + $restored.Right-$restored.Left -eq $preferred + }) + Post $field 0x100 27 + } + 'outside click' { Post $editor 0x201 1 } + 'owner close' { Post $editor 0x10 0 } + } + [void](Wait-Until { ![SearchArrowTest]::IsWindow($dialog) }) + if (![SearchArrowTest]::IsWindow($editor)) { throw "$action closed the editor." } + [void](Wait-Until { [SearchArrowTest]::FocusedControl($editor) -eq $originalFocus }) + } + Write-Output 'Verified Search focus and dismissal by Escape, outside click, and editor close.' + Write-Output 'Verified that Search narrows to its own minimum and regains its width as the editor grows.' + $dialog=Open-Search + Assert-FarCheckbox $dialog 101 ([SearchArrowTest]::GetDlgItem($dialog,100)) + $previousButton=Read-Bounds ([SearchArrowTest]::GetDlgItem($dialog,103)) + $nextButton=Read-Bounds ([SearchArrowTest]::GetDlgItem($dialog,1)) + if ($nextButton.Left-$previousButton.Right -ne $gap) { throw 'Search and F7 use different button gaps.' } + Assert-Arrow $dialog $false + [void][SearchArrowTest]::SendText([SearchArrowTest]::GetDlgItem($dialog,100),0xC,0,'public') + Post $dialog 0x111 1 + [void](Wait-Until { ![SearchArrowTest]::IsWindow($dialog) }) + $dialog=Open-Search + Assert-Arrow $dialog $true + Write-Output 'Verified continuous Search dividers and history arrow contrast and centering.' + Post ([SearchArrowTest]::GetDlgItem($dialog,100)) 0x100 27 + [void](Wait-Until { ![SearchArrowTest]::IsWindow($dialog) }) + Post $editor 0x10 0 + [void](Wait-Until { ![SearchArrowTest]::IsWindow($editor) }) + Post $panel 0x100 0x73 + $editor=Wait-Until { Find-Window 'KSwitcher.Files.Text' $process.Id } + $editControl=Wait-Until { + $control=[SearchArrowTest]::FindWindowEx($editor,0,'Scintilla',[System.Management.Automation.Language.NullString]::Value) + if ($control -ne [IntPtr]::Zero) { $control } + } + $initialText=[IO.File]::ReadAllText($fixture) + Post $editControl 0x102 88 + [void](Wait-Until { [SearchArrowTest]::Send($editControl,2159,0,0) -ne [IntPtr]::Zero }) + function Open-SavePrompt { + Post $editor 0x10 0 + Wait-Until { + $dialog=Find-Window '#32770' $process.Id + if ($dialog -and [SearchArrowTest]::GetDlgItem($dialog,7) -ne [IntPtr]::Zero) { $dialog } + } + } + $dialog=Open-SavePrompt + $saveButton=Read-Bounds ([SearchArrowTest]::GetDlgItem($dialog,6)) + $discardButton=Read-Bounds ([SearchArrowTest]::GetDlgItem($dialog,7)) + if ($discardButton.Left-$saveButton.Right -ne $gap) { throw 'Save and F7 use different button gaps.' } + Post $editor 0x201 1 + [void](Wait-Until { ![SearchArrowTest]::IsWindow($dialog) }) + if (![SearchArrowTest]::IsWindow($editor) -or + [SearchArrowTest]::Send($editControl,2159,0,0) -eq [IntPtr]::Zero) { + throw 'Dismissing the save prompt did not preserve the edited document.' + } + $dialog=Open-SavePrompt + Post $dialog 0x111 7 + [void](Wait-Until { ![SearchArrowTest]::IsWindow($editor) }) + if ([IO.File]::ReadAllText($fixture) -ne $initialText) { throw 'Discard wrote to the file.' } + Write-Output 'Verified that dismissing the save prompt preserves edits, and Discard leaves the file untouched.' + + Post $panel 0x100 0x72 + $editor=Wait-Until { Find-Window 'KSwitcher.Files.Text' $process.Id } + $dialog=Open-Search + Assert-Arrow $dialog $true + Assert-MovesWithOwner $editor $dialog + Post $editor 0x201 1 + [void](Wait-Until { ![SearchArrowTest]::IsWindow($dialog) }) + if (![SearchArrowTest]::IsWindow($editor)) { throw 'Outside click closed the viewer.' } + Write-Output 'Verified outside-click cancellation in Copy and Viewer Search.' + + Write-Output 'Verified that Copy and Search move and resize with their owners.' +} +finally { + if (!$process.HasExited) { + Stop-Process -Id $process.Id + [void]$process.WaitForExit(5000) + } + if ($previousDpi) { [void][SearchArrowTest]::SetThreadDpiAwarenessContext($previousDpi) } + $resolved=(Resolve-Path -LiteralPath $scratch).Path + $root=(Resolve-Path -LiteralPath (Split-Path -Parent $scratch)).Path + if ([IO.Path]::GetDirectoryName($resolved) -eq $root -and (Split-Path -Leaf $resolved) -like 'search-arrow-test-*') { + Remove-Item -LiteralPath $resolved -Recurse -Force + } +} diff --git a/tests/files_text_document.cpp b/tests/files_text_document.cpp new file mode 100644 index 0000000..71e2aaa --- /dev/null +++ b/tests/files_text_document.cpp @@ -0,0 +1,162 @@ +#include "files_text_document.h" + +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; +using ks::files::TextDocument; + +namespace +{ +void check(bool condition, const char *message) +{ + if (!condition) throw std::runtime_error(message); +} + +struct Fixture +{ + fs::path directory; + Fixture() + { + GUID id{}; + wchar_t name[40]{}; + check(SUCCEEDED(CoCreateGuid(&id)) && StringFromGUID2(id, name, 40), "Create fixture ID"); + directory = fs::temp_directory_path() / (std::wstring(L"ks-files-text-") + name); + fs::create_directory(directory); + } + ~Fixture() + { + std::error_code error; + fs::remove_all(directory, error); + } +}; + +void writeFile(const fs::path &path, const std::string &bytes) +{ + std::ofstream output(path, std::ios::binary); + output.write(bytes.data(), bytes.size()); + check(static_cast(output), "Write fixture"); +} + +std::string readFile(const fs::path &path) +{ + std::ifstream input(path, std::ios::binary); + check(static_cast(input), "Read fixture"); + return {std::istreambuf_iterator(input), std::istreambuf_iterator()}; +} + +void editsAcrossPages(const fs::path &file) +{ + const std::string first = std::string(TextDocument::pageBytes - 2, 'a') + "\r\n"; + const std::string middle = std::string(TextDocument::pageBytes - 2, 'b') + "\r\n"; + const std::string last = "last\r\n"; + const std::string bom = "\xef\xbb\xbf"; + writeFile(file, bom + first + middle + last); + TextDocument document(file); + check(document.pages() == 3, "Expected three pages"); + check(document.readPage(1) == middle, "Read middle page"); + document.stage(2, "last changed\r\n"); + check(!document.modifiedWith(2, last), "Restoring the only modified page leaves no changes"); + check(document.modifiedWith(0, first), "An original page must not hide changes to other pages"); + document.stage(0, "first changed\n"); + check(document.readPage(2) == "last changed\r\n", "Read staged page"); + check(document.save(), "Replace and reopen"); + check(!document.modified(), "Save clears staged page edits"); + check(readFile(file) == bom + "first changed\n" + middle + "last changed\r\n", + "Save must preserve untouched bytes and the BOM"); + document.stage(0, "saved again\n"); + check(document.save(), "Save again through the same document"); +} + +void unicodeBoundaries(const fs::path &file) +{ + const auto chunk = TextDocument::pageBytes; + const std::string emoji = "\xf0\x9f\x98\x80"; + writeFile(file, std::string(chunk - 1, 'a') + emoji + "tail"); + { + TextDocument document(file, false); + check(document.boundary(1) == chunk + 3, "UTF-8 split within a code point"); + check(document.readPage(0).ends_with(emoji) && document.readPage(1) == "tail", "Read split UTF-8"); + } + for (const bool little : {true, false}) + { + const std::string bom = little ? "\xff\xfe" : "\xfe\xff"; + const std::string letter(little ? "a\0" : "\0a", 2); + const std::string pair(little ? "\x3d\xd8\x00\xde" : "\xd8\x3d\xde\x00", 4); + std::string first; + for (size_t n = 0; n < chunk / 2 - 1; ++n) first += letter; + first += pair; + writeFile(file, bom + first + letter); + TextDocument document(file); + check(document.readPage(0).ends_with(emoji) && document.readPage(1) == "a", "Read split UTF-16"); + document.stage(1, emoji); + check(document.save() && readFile(file) == bom + first + pair, "Preserve UTF-16 byte order"); + } +} + +void rejectExternalReplacement(const fs::path &file) +{ + writeFile(file, "original"); + TextDocument document(file); + document.stage(0, "editor changes"); + auto later = file; + later += L".later"; + auto original = file; + original += L".original"; + writeFile(later, "external changes"); + check(MoveFileExW(file.c_str(), original.c_str(), 0) && MoveFileExW(later.c_str(), file.c_str(), 0), + "Replace file externally"); + bool rejected{}; + try { document.save(); } + catch (const std::exception &) { rejected = true; } + check(rejected && document.modified() && readFile(file) == "external changes", + "Preserve external file and staged changes after conflict"); +} + +void sparseFile(const fs::path &file) +{ + constexpr uint64_t offset = 5ULL << 30; + const auto handle = CreateFileW(file.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + check(handle != INVALID_HANDLE_VALUE, "Create sparse fixture"); + DWORD count{}; + if (!DeviceIoControl(handle, FSCTL_SET_SPARSE, nullptr, 0, nullptr, 0, &count, nullptr)) + { + CloseHandle(handle); + std::cout << "Sparse fixture skipped on this file system.\n"; + return; + } + LARGE_INTEGER position{}; + position.QuadPart = offset; + const bool written = SetFilePointerEx(handle, position, nullptr, FILE_BEGIN) && + WriteFile(handle, "last", 4, &count, nullptr) && count == 4; + CloseHandle(handle); + check(written, "Write beyond the 32-bit range"); + TextDocument document(file); + const auto index = document.pages() - 1; + check(document.size() == offset + 4 && document.boundary(index) == offset, "Use 64-bit offsets"); + check(document.readPage(index) == "last", "Read past 4 GiB"); + document.stage(index, "edited"); + check(document.readPage(index) == "edited", "Stage an edit past 4 GiB"); +} +} + +int main() +{ + try + { + const Fixture fixture; + editsAcrossPages(fixture.directory / L"pages.txt"); + unicodeBoundaries(fixture.directory / L"unicode.txt"); + rejectExternalReplacement(fixture.directory / L"external.txt"); + sparseFile(fixture.directory / L"5gib.log"); + std::cout << "Files text document regressions passed.\n"; + } + catch (const std::exception &error) + { + std::cerr << error.what() << '\n'; + return 1; + } +}