Compare commits

..
Author SHA1 Message Date
agrynco 4b252bd111 Add lazy panel trees and background folder sizes
Refs #97
2026-11-25 15:02:32 +02:00
agrynco 7577d19a84 Merge pull request 'KSwitcher.Files: Sunburst and indexed NTFS analysis' (#149) from codex/issue-96-sunburst-ntfs into prerelease
Refs #96
2026-11-25 14:47:49 +02:00
agrynco 24fbf72d60 Add Sunburst and indexed NTFS volume traversal
Refs #96
2026-11-25 14:47:33 +02:00
agrynco 291d7597e3 Merge pull request 'KSwitcher.Files: volume usage and treemap' (#148) from codex/issue-95-volume-treemap into prerelease
Refs #95
2026-11-25 14:34:22 +02:00
agrynco ea6338e9b9 Analyze volume usage and add a Files treemap
Refs #95
2026-11-25 14:34:06 +02:00
agrynco 5ea222ad8a Merge pull request 'KSwitcher.Files: local Space Analyzer' (#147) from codex/issue-94-space-analyzer into prerelease
Refs #94
2026-11-25 14:20:05 +02:00
agrynco efe7937507 Add a local Space Analyzer to Files
Refs #94
2026-11-25 14:19:47 +02:00
agrynco 30a904b386 Merge pull request 'KSwitcher.Files: per-panel sorting and filters' (#146) from codex/issue-93-panel-sort-filter into prerelease
Refs #93
2026-11-25 14:12:27 +02:00
agrynco 2545886092 Add per-panel sorting and file filters
Refs #93
2026-11-25 14:12:11 +02:00
agrynco 3971cb1871 Merge pull request 'KSwitcher.Files: drag and drop' (#145) from codex/issue-92-drag-drop into prerelease
Refs #92
2026-11-25 14:01:57 +02:00
agrynco 31473baa49 Add Windows file drag and drop to Files
Refs #92
2026-11-25 14:01:43 +02:00
agrynco c7b9ee5cb1 Merge pull request 'KSwitcher.Files: Windows file clipboard' (#144) from codex/issue-91-file-clipboard into prerelease
Refs #91
2026-11-25 13:50:48 +02:00
agrynco 07ed4cf724 Support Windows file clipboard in Files
Refs #91
2026-11-25 13:50:30 +02:00
agrynco 4b5bcd2983 Merge pull request 'KSwitcher.Files: Copy the full path of the current item' (#143) from codex/issue-90-copy-full-path into prerelease
Refs #90
2026-11-25 13:37:07 +02:00
agrynco 2a4df70079 Copy the full path of the current file panel item
Refs #90
2026-11-25 13:36:50 +02:00
agrynco e986dd90e5 Merge pull request 'KSwitcher.Files: Add Quick View for text and Markdown' (#142) from codex/issue-89-quick-view into prerelease
Refs #89
2026-11-25 13:33:28 +02:00
agrynco 3dd4edeb2c Add Quick View for local text and Markdown
Refs #89
2026-11-25 13:33:15 +02:00
agrynco edb259e6bb Merge pull request 'KSwitcher.Files: Add persistent recent folders' (#141) from codex/issue-88-recent-folders into prerelease
Refs #88
2026-11-25 13:20:10 +02:00
agrynco 9e287c3a1d Add persistent recent folders to source menus
Refs #88
2026-11-25 13:19:55 +02:00
agrynco 5eda68a7a2 Merge pull request 'KSwitcher.Files: Add local path breadcrumbs and history' (#140) from codex/issue-87-local-path-navigation into prerelease
Refs #87
2026-11-25 13:14:32 +02:00
agrynco 6cbb0639a1 Add local path breadcrumbs and panel history
Refs #87
2026-11-25 13:14:18 +02:00
agrynco 2a6f9c7841 Merge pull request 'KSwitcher.Files: Enable operations in file search results' (#139) from codex/issue-86-search-operations into prerelease
Refs #86
2026-11-25 12:59:21 +02:00
agrynco 94b22fdd52 Enable file operations in search results
Refs #86
2026-11-25 12:59:04 +02:00
agrynco 0d293429df Merge pull request 'KSwitcher.Files: Add recursive local file search' (#138) from codex/issue-85-find-files into prerelease
Refs #85
2026-11-25 11:54:00 +02:00
agrynco 83a099ab25 Add recursive local file search to KSwitcher Files
Refs #85
2026-11-25 11:53:14 +02:00
30 changed files with 4505 additions and 468 deletions

No files matched your search

+10
View File
@@ -26,6 +26,11 @@ add_custom_target(check-files-search-arrow
-Executable "$<TARGET_FILE:KSwitcherFiles>"
DEPENDS KSwitcherFiles
VERBATIM)
add_custom_target(check-files-quick-view
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_quick_view.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>"
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 wininet)
if(MSVC)
@@ -193,6 +198,11 @@ add_test(NAME files-comparison-splitter
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_comparison_splitter.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>")
set_tests_properties(files-comparison-splitter PROPERTIES RUN_SERIAL TRUE TIMEOUT 35)
add_test(NAME files-space-analyzer-layout
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_space_analyzer_layout.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>")
set_tests_properties(files-space-analyzer-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 25)
find_program(KSWITCHER_NODE NAMES node)
if(KSWITCHER_NODE)
add_test(NAME files-terminal-enter
+117 -4
View File
@@ -204,6 +204,17 @@ Warning і початковий фокус на No.
Незбережені зміни у примусово закритих вікнах втрачаються.
Закриття процесів і результат записуються до `kswitcher.log`.
- У файловій панелі Ctrl+C копіює позначені або поточний локальний
елемент у файловий буфер Windows. Ctrl+V вставляє файли й папки в
поточний локальний каталог через звичайний діалог Copy і показує
конфлікти та прогрес. Клік або навігація у файловій панелі вибирають
файловий контекст. Клік у командному рядку або введення тексту
повертають текстовий контекст Ctrl+C / Ctrl+V.
- **Commands → Copy full path** або **Ctrl+Shift+C** копіює повний шлях
файла чи папки під курсором як текст. У LAN- і FTP-панелях текст включає
адресу віддаленого джерела. Для рядка `..` команда не змінює буфер.
- Ctrl+F вставляє повний шлях елемента під курсором активної панелі в позицію
курсора командного рядка або замінює виділення. Подвійні лапки додаються
лише до шляхів із пробілами. На рядку `..` вставляється шлях папки,
@@ -283,7 +294,7 @@ Warning і початковий фокус на No.
- 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 або клік у Files поза попапом закриває його й повертає фокус до панелі. Commands → Folder shortcuts дає вибрати зайняту цифру й відкрити той самий попап навіть для єдиного запису.
- Ctrl+F1 вмикає Brief, Ctrl+F2 вмикає Wide для активної панелі. Ctrl+F3–F12 зарезервовані для інших режимів панелей. Brief і Wide також доступні в меню Left/Right та Options.
- Ctrl+F1 вмикає Brief, Ctrl+F2 вмикає Wide для активної панелі. Ctrl+F3–F9 керують сортуванням і фільтром активної панелі. Ctrl+F10 перемикає List і Tree. Ctrl+F11 перемикає фоновий підрахунок розмірів папок. Brief і Wide також доступні в меню Left/Right та Options.
## Налаштування Files
@@ -429,6 +440,61 @@ Warning і початковий фокус на No.
## Панелі
- **F9 → Commands → Find files** або **Alt+F7** запускає фоновий пошук
файлів у поточній локальній папці та її підпапках. Поле приймає повне
ім’я або маску без урахування регістру. `*` відповідає довільній
послідовності символів, `?` — одному символу. Приховані та системні
елементи можна включити прапорцем. Пошук не обходить junction та інші
посилання на каталоги. Esc під час пошуку зупиняє обхід і показує знайдене.
Результати відкриваються в тій самій панелі з відносними шляхами.
Enter або подвійний клік відкриває папку й ставить курсор на файл.
Esc у результатах повертає вихідну папку, курсор і позначки.
У результатах F3/F4 відкривають файл, а F5/F6 працюють із позначеними
або поточним файлом, використовуючи папку іншої панелі як призначення.
F8 і Shift+Delete використовують звичайні підтвердження. Успішно
переміщені та видалені файли зникають зі списку. Ctrl+R повторює пошук
з тією самою маскою й видимістю прихованих файлів.
- **Left/Right → Tree view** або Ctrl+F10 перемикає вигляд відповідної
панелі незалежно від Brief і Wide. Enter, подвійний клік чи стрілка біля
папки розкриває або згортає гілку. Стрілки вправо й вліво працюють із
гілкою та її батьківською папкою. Вміст гілки читається у фоні під час
розкриття. Позначки згорнутих гілок залишаються доступними для F5, F6 і F8.
Якщо позначено папку та її вміст, команда обробляє їх одним деревом.
Повернення до List відкриває батьківську папку поточного елемента.
- **Background folder sizes** або Ctrl+F11 вмикає вимірювання видимих папок
у фоні для відповідної панелі. Під час оновлення попереднє число лишається
поруч із символом … . Знак + позначає частковий розмір. Error з’являється,
коли вимірювання недоступне. Якщо попереднє число є, позначка ! відрізняє
його від свіжого результату.
- **Commands → Space Analyzer** показує місткість і вільне місце за даними
Windows перед скануванням. Volume вибирає корінь тому, Folder повертає
поточну локальну папку, Start запускає фоновий аналіз тим самим обходом,
що й підрахунок розмірів F3. Посилання на каталоги всередині області
сканування позначаються як link. Stop залишає часткові результати, а
Rescan повторює аналіз із початку.
- Дерево показує логічний розмір, зайняті байти та частку логічного розміру
від батьківської папки. Знак + позначає частковий підрахунок. Зайняті байти
підсумовуються за файловими записами, включно з окремими іменами для
жорстких посилань. Службові дані файлової системи в цей підсумок не входять.
Відсутні дані про зайняті байти позначаються в рядку стану.
- Treemap показує дочірні елементи вибраної папки прямокутниками,
пропорційними до їхнього логічного розміру. Дрібні елементи доступні в
дереві. Клік по плитці відкриває точний елемент у сусідній панелі. Стрілки
переводять фокус між плитками, Enter відкриває плитку у фокусі.
- Sunburst показує до трьох рівнів вкладеності секторами за логічним
розміром. Клік по сектору та Enter у відповідному рядку списку ведуть
до одного елемента. Обраний рядок підсвічує відповідний сектор.
- Під час аналізу всього NTFS-тому Files використовує індекс MFT за
наявності доступу Windows. Звичайний обхід працює без такого доступу.
Обидва режими перераховують доступні записи каталогів, ураховують
жорсткі посилання за їхніми іменами та позначають недоступні гілки.
- View відкриває вибраний файл у спільному переглядачі Files. Show in
other panel відкриває вибрану папку або ставить курсор на файл у сусідній
панелі. Команди роботи з файлами доступні там. Якщо фільтр приховує
вибраний файл, панель показує його до зміни фільтра або переходу в іншу папку.
- Обидві панелі автоматично підхоплюють створення, зміну й видалення файлів
у відкритих локальних папках. Фокус залишається там, де був, а курсор
лишається на поточному елементі, якщо той ще існує.
@@ -463,13 +529,49 @@ Warning і початковий фокус на No.
- Process multiple names дозволяє розділити імена комами або крапками з комою. Якщо такий символ є частиною імені, візьми ім’я в подвійні лапки. Діалог створює елементи у поточному каталозі, оновлює панель і ставить курсор на останній створений елемент. При помилці в середині списку вже створені елементи зберігаються.
- Після F5 або F6 успішно оброблені елементи коротко підсвічуються в панелі, що показує папку призначення. Підсвітка тексту відрізняється від курсора й не переносить фокус.
- У широкому режимі ширина під вирівняні розширення залежить від найдовшого розширення в поточній панелі. За вузької панелі залишай місце для імені та колонки Size.
Розділювач Size проходить по одній вертикалі в заголовку та списку, а праві краї підпису й значень вирівняні.
- **Left/Right → Sort by** та Ctrl+F3, Ctrl+F4, Ctrl+F5 і Ctrl+F6 сортують
відповідну панель за іменем, розширенням, розміром і часом зміни.
Повторний вибір того самого стовпця змінює напрямок. Клік по заголовку
Wide виконує ту саму команду. Стрілка показує поточний напрямок.
Ctrl+F7 перемикає пріоритет папок. За вимкненого пріоритету папки й файли
сортуються разом. Рядок `..` лишається першим. Сортування, напрямок і
пріоритет папок зберігаються окремо для кожної панелі.
- Ctrl+F8 відкриває фільтр імен файлів без урахування регістру. Маска
підтримує `*` і `?` так само, як Find files. Папки залишаються доступними
для навігації. Порожнє поле або `*` вимикає фільтр. Позначки повертаються
для прихованих фільтром елементів, які ще є в поточній папці.
Ctrl+F9 перемикає показ прихованих та системних елементів окремо для
кожної панелі. Типово їх видно. Маска діє до закриття вікна.
- Wide показує Name, Ext, Size і Modified. Modified відображає місцеву
дату, а сортування враховує повний час зміни. За вузької панелі лишаються
Name та Size. Ext враховує параметри вирівнювання розширень.
Межі стовпців збігаються в заголовку та списку.
- Бірюзовий курсор поточного рядка видно в активній панелі. Кожна панель зберігає свою позицію курсора. Коли панелі видимі, F5 і F6 з командного рядка діють на активну панель.
- Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший.
- Поточний шлях відображається по центру верхньої подвійної лінії панелі. Лінію видно з обох боків напису. Бірюзове тло активної панелі охоплює лише напис шляху з невеликими відступами. Довгий шлях скорочується в межах панелі.
- **Commands → Quick View** або **Ctrl+Q** вмикає перегляд локального
тексту й Markdown у сусідній панелі. Перегляд слідує за курсором активної
панелі. Повторна команда повертає сусідній каталог, курсор і позначки.
Під час перегляду файлові операції з призначенням у сусідній панелі
пропонують спершу закрити Quick View.
- **Change drive → Recent folders** у меню Alt+F1 або Alt+F2 показує
останні відвідані локальні папки. Повторний візит підіймає один запис
угору, порядок зберігається після перезапуску. Enter або клік відкриває
шлях у панелі, з якої викликали меню. Delete прибирає вибраний запис.
- У локальному заголовку кнопки ← та → переходять назад і вперед
в історії відповідної панелі. Стрілка ↑, Alt+↑ та рядок `..`
відкривають безпосередню батьківську папку. На корені стрілка вимкнена,
а рядка немає. Alt+← і Alt+→ працюють з історією активної панелі.
- Сегменти шляху відкривають папки. Якщо шлях не вміщується, ліва
трикрапка відкриває прихованих предків, а права — приховані папки
попередньої гілки. Клік по поточній папці або кнопці редагування та Ctrl+L
відкривають поле шляху. Tab доповнює назву папки, Enter відкриває шлях,
а Esc повертає до тих самих панелей і курсора.
- Для LAN і FTP поточний шлях відображається по центру верхньої подвійної лінії панелі. Довгий шлях скорочується в межах панелі.
## Спільні елементи діалогів
@@ -508,6 +610,17 @@ Warning і початковий фокус на No.
- Розкриті списки й історія Far використовують спільний попап із бірюзовим тлом, світлою рамкою та чорним вибраним рядком. Попап прилягає до обох країв бірюзового поля, стрілка лишається праворуч за межами списку. Історія групується за датами. Довгі списки прокручуються, Enter вибирає рядок, Escape закриває список і повертає фокус до поля.
- Повторно використовуй спільне оформлення. Текст, дії та стан операції передавай із коду конкретної операції. Наприклад, Warning повертає відповідь і стан прапорця, а копіювання вирішує, чи застосувати відповідь до наступних конфліктів.
## Перетягування файлів
- Перетягування з Explorer або іншої локальної панелі відкриває діалог
Drop files із повним шляхом призначення та кнопками Copy, Move і Cancel.
Якщо курсор над папкою, призначенням є ця папка. В інших випадках
призначенням є поточна папка панелі. Cancel або Esc скасовує дію.
- Copy і Move відкривають наявний діалог операції з її параметрами,
перевіркою призначення, розв’язанням конфліктів і прогресом. Віддалені
панелі, результати пошуку й віртуальні елементи Explorer без локального
шляху не підтримують перетягування. Files повідомляє причину в рядку стану.
## Діалог Copy
- Вирівнюй підпис Existing files по вертикальному центру списку. Ширше поле списку починається ближче до підпису, а його правий край збігається з правим краєм поля імені.
+48
View File
@@ -407,3 +407,51 @@ BEGIN
LTEXT "Reading and comparing files...", -1, 14, 15, 262, 13
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 101, 31, 88, 17
END
116 DIALOGEX 0, 0, 300, 98
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Find files"
FONT 10, "Consolas"
BEGIN
LTEXT "File &name or mask", 483, 16, 18, 268, 12
FAR_EDIT(480, 0, 16, 32, 268, 15)
AUTOCHECKBOX "Include &hidden and system files", 481, 16, 53, 268, 12
LTEXT "", 482, 10, 69, 1, 1, NOT WS_VISIBLE
CONTROL "&Find", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 68, 73, 80, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 152, 73, 80, 17
END
117 DIALOGEX 0, 0, 290, 83
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Go to folder"
FONT 10, "Consolas"
BEGIN
LTEXT "Folder &path (Tab completes)", 486, 16, 18, 258, 12
FAR_EDIT(485, 0, 16, 32, 258, 15)
LTEXT "", 487, 10, 54, 1, 1, NOT WS_VISIBLE
CONTROL "&Open", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 63, 59, 80, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 59, 80, 17
END
118 DIALOGEX 0, 0, 420, 209
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Space Analyzer"
FONT 10, "Consolas"
BEGIN
LTEXT "", 488, 16, 15, 353, 13, SS_PATHELLIPSIS
LTEXT "", 495, 16, 28, 353, 13, SS_ENDELLIPSIS
CONTROL "Vo&lume", 496, "Button", BS_OWNERDRAW | WS_TABSTOP, 16, 43, 64, 16
CONTROL "Tree&map", 497, "Button", BS_OWNERDRAW | WS_TABSTOP, 84, 43, 64, 16
CONTROL "S&unburst", 499, "Button", BS_OWNERDRAW | WS_TABSTOP, 152, 43, 64, 16
LTEXT "Sunburst items", 501, 171, 43, 201, 16, NOT WS_VISIBLE
LISTBOX 500, 171, 60, 201, 105, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP | WS_VSCROLL | WS_HSCROLL | NOT WS_VISIBLE
CONTROL "", 498, "Static", SS_OWNERDRAW | SS_NOTIFY | WS_TABSTOP | NOT WS_VISIBLE, 16, 60, 353, 105
CONTROL "", 489, "SysTreeView32", WS_TABSTOP | WS_BORDER | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_SHOWSELALWAYS, 16, 32, 353, 131
LTEXT "", 490, 16, 167, 353, 14, SS_ENDELLIPSIS
LTEXT "", 491, 12, 184, 1, 1, NOT WS_VISIBLE
CONTROL "S&top", 492, "Button", BS_OWNERDRAW | WS_TABSTOP, 22, 189, 46, 16
CONTROL "St&art", 493, "Button", BS_OWNERDRAW | WS_TABSTOP, 72, 189, 50, 16
CONTROL "&View", 494, "Button", BS_OWNERDRAW | WS_TABSTOP, 126, 189, 46, 16
CONTROL "&Show in other panel", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 176, 189, 102, 16
CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 282, 189, 50, 16
END
+4
View File
@@ -10,6 +10,10 @@
body { max-width: var(--markdown-width, 960px); margin: auto; padding: 20px 28px; overflow-wrap: anywhere; }
main { font: var(--markdown-font-size, 12pt)/1.55 var(--markdown-font, system-ui, sans-serif); }
nav { position: sticky; top: 0; display: flex; flex-wrap: wrap; gap: .4em; padding-block: .25em; background: Canvas; }
:root.quick-view body { padding: 8px 12px; }
:root.quick-view nav { display: none; }
:root.quick-view main > :first-child { margin-block-start: 0; }
:root.quick-view h1 { font-size: 1.4em; }
nav button { appearance: none; border: 0; background: transparent; color: LinkText;
font: 1.35em/1.25 system-ui, sans-serif; min-width: 1.55em; padding: 0; cursor: pointer; }
nav button:disabled { color: GrayText; opacity: .6; cursor: default; }
+5 -4
View File
@@ -247,12 +247,13 @@ searchPrevious.addEventListener('click', () => stepSearch(-1));
searchNext.addEventListener('click', () => stepSearch(1));
content.addEventListener('toggle', () => { if (!search.hidden) updateSearch(false); }, true);
async function render({ text, fragment, scroll, title, keepPosition, revision, canSave }) {
async function render({ text, fragment, scroll, title, keepPosition, revision, canSave, compact }) {
const current = ++generation;
if (keepPosition) scroll = window.scrollY;
else closeSearch();
document.documentElement.classList.remove('rendered');
document.title = title;
document.documentElement.classList.toggle('quick-view', Boolean(compact));
previewRevision = revision;
renderContent(text, canSave);
const headings = new Set();
@@ -264,7 +265,7 @@ async function render({ text, fragment, scroll, title, keepPosition, revision, c
headings.add(id);
}
images = Array.from(content.querySelectorAll('img[data-path]'));
images.forEach((image, index) => send('image', { path: image.dataset.path, index, generation: current }));
images.forEach((image, index) => send('image', { path: image.dataset.path, index, generation: current, revision }));
const blocks = Array.from(content.querySelectorAll('pre > code.language-mermaid'));
for (const [index, block] of blocks.entries()) {
try {
@@ -289,7 +290,7 @@ async function render({ text, fragment, scroll, title, keepPosition, revision, c
restorePosition({ fragment, scroll });
document.documentElement.classList.add('rendered');
if (!search.hidden) updateSearch(false);
send('rendered');
send('rendered', { revision });
}
content.addEventListener('change', ({ target }) => {
@@ -350,7 +351,7 @@ bridge.addEventListener('message', ({ data }) => {
document.documentElement.classList.remove('rendered');
content.replaceChildren();
}
if (message.action === 'render') void render(message).catch(() => send('failed'));
if (message.action === 'render') void render(message).catch(() => send('failed', { revision: message.revision }));
if (message.action === 'task-result' && message.revision === previewRevision && pendingTask) {
if (!message.saved) pendingTask.target.checked = !pendingTask.checked;
pendingTask = undefined;
+239
View File
@@ -0,0 +1,239 @@
constexpr UINT panelDropReady=WM_APP+33;
struct PanelDrop
{
HWND source{}, target{};
fs::path directory, destination;
std::vector<fs::path> paths;
};
std::optional<PanelDrop> pendingPanelDrop;
HWND draggingPanel{};
std::optional<POINT> panelDragStart;
bool localDropPanel(const Panel &panel)
{
return !panel.peer && !panel.ftp && !panel.findOrigin && panel.directory.is_absolute();
}
LRESULT panelRowAt(HWND window,POINT point,LRESULT top,LRESULT count)
{
const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,MAKELPARAM(point.x,point.y));
// LB_ITEMFROMPOINT only returns the low 16 bits of the row index.
constexpr LRESULT rowRange=1<<16;
auto row=(top&~(rowRange-1))|LOWORD(hit);
if(row<top) row+=rowRange;
RECT bounds{};
return !HIWORD(hit) && row>=0 && row<count &&
SendMessageW(window,LB_GETITEMRECT,row,reinterpret_cast<LPARAM>(&bounds))!=LB_ERR &&
PtInRect(&bounds,point)?row:LB_ERR;
}
FORMATETC fileDropFormat()
{
return {CF_HDROP,nullptr,DVASPECT_CONTENT,-1,TYMED_HGLOBAL};
}
template<class Interface,class Derived>
class DragInterface : public Interface
{
public:
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,void **out) override
{
if(!out) return E_POINTER;
*out=nullptr;
if(iid!=IID_IUnknown && iid!=__uuidof(Interface)) return E_NOINTERFACE;
*out=static_cast<Interface *>(this);
AddRef();
return S_OK;
}
ULONG STDMETHODCALLTYPE AddRef() override {return ++references;}
ULONG STDMETHODCALLTYPE Release() override
{
const auto count=--references;
if(!count) delete static_cast<Derived *>(this);
return count;
}
private:
ULONG references{1};
};
class PanelDropTarget final : public DragInterface<IDropTarget,PanelDropTarget>
{
public:
explicit PanelDropTarget(HWND window) : target(window) {}
HRESULT STDMETHODCALLTYPE DragEnter(IDataObject *data,DWORD,POINTL,DWORD *effect) override
{
auto format=fileDropFormat();
filesystem=data->QueryGetData(&format)==S_OK;
return updateEffect(effect);
}
HRESULT STDMETHODCALLTYPE DragOver(DWORD,POINTL,DWORD *effect) override
{
return updateEffect(effect);
}
HRESULT STDMETHODCALLTYPE DragLeave() override
{
filesystem=false;
return S_OK;
}
HRESULT STDMETHODCALLTYPE Drop(IDataObject *data,DWORD,POINTL location,DWORD *effect) override
{
updateEffect(effect);
filesystem=false;
if(*effect==DROPEFFECT_NONE) return S_OK;
*effect=DROPEFFECT_NONE;
auto format=fileDropFormat();
STGMEDIUM medium{};
if(FAILED(data->GetData(&format,&medium)))
{
setStatus(L"Could not read local paths from the drop.");
return S_OK;
}
std::vector<fs::path> paths;
try
{
if(medium.tymed==TYMED_HGLOBAL) paths=ks::fileDropPaths(medium.hGlobal);
}
catch(const std::exception &) {}
ReleaseStgMedium(&medium);
if(paths.empty())
{
setStatus(L"The drop contains no usable file or folder paths.");
return S_OK;
}
try
{
const auto &panel=panels[GetDlgCtrlID(target)-102];
POINT point{location.x,location.y};
ScreenToClient(target,&point);
const auto row=panelRowAt(target,point,SendMessageW(target,LB_GETTOPINDEX,0,0),
static_cast<LRESULT>(panel.rows.size()));
const auto &destination=row!=LB_ERR && panel.sizes[row]==L"Folder"?panel.rows[row]:panel.directory;
pendingPanelDrop=PanelDrop{draggingPanel,target,panel.directory,destination,std::move(paths)};
if(PostMessageW(GetParent(target),panelDropReady,0,0))
{
// Files performs the requested move after confirmation.
*effect=DROPEFFECT_COPY;
}
else pendingPanelDrop.reset();
}
catch(const std::exception &)
{
setStatus(L"Could not prepare the drop.");
}
return S_OK;
}
private:
HRESULT updateEffect(DWORD *effect)
{
const auto allowed=*effect;
*effect=DROPEFFECT_NONE;
if(!filesystem || !(allowed&DROPEFFECT_COPY))
setStatus(L"Drag files or folders from a Windows filesystem.");
else if(target==draggingPanel)
setStatus(L"Drop files onto the other panel.");
else if(!localDropPanel(panels[GetDlgCtrlID(target)-102]))
setStatus(L"Open a local folder in the destination panel before dropping files.");
else if(!copyInProgress && !pendingPanelDrop && !FilesModalDialog::activeFor(GetParent(target)))
*effect=DROPEFFECT_COPY;
return S_OK;
}
HWND target;
bool filesystem{};
};
class PanelDragSource final : public DragInterface<IDropSource,PanelDragSource>
{
public:
HRESULT STDMETHODCALLTYPE QueryContinueDrag(BOOL escape,DWORD keys) override
{
if(escape) return DRAGDROP_S_CANCEL;
return keys&MK_LBUTTON?S_OK:DRAGDROP_S_DROP;
}
HRESULT STDMETHODCALLTYPE GiveFeedback(DWORD) override {return DRAGDROP_S_USEDEFAULTCURSORS;}
};
void beginPanelDrag(HWND window)
{
auto &panel=panels[GetDlgCtrlID(window)-102];
if(!localDropPanel(panel))
{
setStatus(L"Drag files or folders from an open local folder.");
return;
}
auto paths=selectedPanelPaths(panel);
if(paths.empty()) return;
std::vector<PCIDLIST_ABSOLUTE> items;
items.reserve(paths.size());
const auto clear=[&](void *){for(auto item:items) CoTaskMemFree(const_cast<PIDLIST_ABSOLUTE>(item));};
const std::unique_ptr<void,decltype(clear)> cleanup(&items,clear);
for(const auto &path:paths)
{
PIDLIST_ABSOLUTE item{};
if(FAILED(SHParseDisplayName(path.c_str(),nullptr,&item,0,nullptr)))
{
setStatus(L"Windows could not prepare the selected files or folders for dragging.");
return;
}
items.push_back(item);
}
IShellItemArray *array{};
if(FAILED(SHCreateShellItemArrayFromIDLists(static_cast<UINT>(items.size()),items.data(),&array)))
{
setStatus(L"Windows could not prepare the selected files or folders for dragging.");
return;
}
IDataObject *data{};
const auto result=array->BindToHandler(nullptr,BHID_DataObject,IID_PPV_ARGS(&data));
array->Release();
if(FAILED(result))
{
setStatus(L"Windows could not prepare the selected files or folders for dragging.");
return;
}
const auto source=new(std::nothrow) PanelDragSource;
if(source)
{
draggingPanel=window;
DWORD effect{};
DoDragDrop(data,source,DROPEFFECT_COPY,&effect);
draggingPanel=nullptr;
source->Release();
}
data->Release();
}
void performPanelDrop(HWND owner)
{
if(!pendingPanelDrop) return;
auto drop=std::move(*pendingPanelDrop);
pendingPanelDrop.reset();
auto index=GetDlgCtrlID(drop.target)-102;
if(index<0 || index>=static_cast<int>(std::size(panels))) return;
auto &panel=panels[index];
if(!localDropPanel(panel) || panel.directory!=drop.directory || !IsWindowVisible(drop.target))
{
setStatus(L"The destination panel changed. Drop the files again.");
return;
}
if(copyInProgress || FilesModalDialog::activeFor(owner))
{
setStatus(L"Finish the current operation before dropping files.");
return;
}
const auto text=L"Destination folder:\r\n"+drop.destination.native();
const auto answer=showFilesNotice(owner,text.c_str(),L"Drop files",
{.tone=FilesNoticeTone::neutral,.chooseTransfer=true});
if(answer!=IDYES && answer!=IDNO) return;
auto &source=drop.source?panels[GetDlgCtrlID(drop.source)-102]:panel;
activatePanel(index);
panelClipboardContext=true;
copySelection(owner,source,panel,answer==IDNO,std::move(drop.paths),std::move(drop.destination));
}
+112
View File
@@ -0,0 +1,112 @@
constexpr int findMask=480, findHidden=481, findFooter=482, findLabel=483;
struct FileMaskPrompt
{
Panel::FindOptions options;
bool filter{};
};
INT_PTR CALLBACK fileMaskDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_DRAWITEM)
{
paintDialogButton(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp),RGB(192,192,192),RGB(0,0,0),true);
return TRUE;
}
const auto *prompt=reinterpret_cast<const FileMaskPrompt *>(message==WM_INITDIALOG?lp:GetWindowLongPtrW(dialog,DWLP_USER));
const bool filter=prompt && prompt->filter;
const auto title=filter?L" Panel filter ":L" Find files ";
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,title,false,{findFooter}))
return painted;
if(message==WM_INITDIALOG)
{
const auto &options=prompt->options;
SetWindowLongPtrW(dialog,DWLP_USER,lp);
if(filter)
{
SetWindowTextW(dialog,L"Panel filter");
SetDlgItemTextW(dialog,findLabel,L"File &name or mask (blank clears)");
SetDlgItemTextW(dialog,findHidden,L"Show &hidden and system files");
SetDlgItemTextW(dialog,IDOK,L"&Apply");
}
prepareTextDialog(dialog);
layoutDialogContent(dialog,findLabel);
fitFarEditToLine(GetDlgItem(dialog,findMask));
for(const auto id:{IDOK,IDCANCEL})
{
const auto button=GetDlgItem(dialog,id);
SetWindowPos(button,nullptr,0,0,farDialogButtonWidth(button),textHeight,
SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
}
layoutDialogButtons(dialog,findFooter,{IDOK,IDCANCEL});
installFarCheckbox(GetDlgItem(dialog,findHidden),FarCheckboxSurface::gray);
SendDlgItemMessageW(dialog,findMask,EM_SETLIMITTEXT,255,0);
SetDlgItemTextW(dialog,findMask,options.mask.c_str());
CheckDlgButton(dialog,findHidden,options.includeHidden?BST_CHECKED:BST_UNCHECKED);
SetFocus(GetDlgItem(dialog,findMask));
SendDlgItemMessageW(dialog,findMask,EM_SETSEL,0,-1);
return FALSE;
}
if(message==WM_COMMAND && LOWORD(wp)==IDOK)
{
auto &options=reinterpret_cast<FileMaskPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER))->options;
wchar_t mask[256]{};
GetDlgItemTextW(dialog,findMask,mask,static_cast<int>(std::size(mask)));
if(std::wstring_view(mask).find_first_of(L"/\\:")!=std::wstring_view::npos)
{
showFilesNotice(dialog,L"Enter a file name or mask without a path.",filter?L"Panel filter":L"Find files");
SetFocus(GetDlgItem(dialog,findMask));
return TRUE;
}
options.mask=*mask?mask:L"*";
options.includeHidden=IsDlgButtonChecked(dialog,findHidden)==BST_CHECKED;
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
return FALSE;
}
void startFileSearch(Panel &panel,Panel::FindOptions options)
{
if(panel.scanRequest) return;
cancelFolderSizes(panel);
panel.scanRequest=Panel::ScanRequest{.directory=panel.directory,.statusRevision=statusRevision,.find=std::move(options)};
startDirectoryScan(panel);
}
void findLocalFiles(HWND owner,Panel &panel)
{
if(panel.peer || panel.ftp || panel.directory.empty())
{
setStatus(L"Find files requires a local folder.");
return;
}
if(panel.scanRequest)
{
setStatus(L"Wait for the current scan to finish.");
return;
}
FileMaskPrompt prompt{panel.findOrigin?panel.findOrigin->options:Panel::FindOptions{}};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(116),owner,
fileMaskDialog,reinterpret_cast<LPARAM>(&prompt))!=IDOK) return;
startFileSearch(panel,std::move(prompt.options));
}
void editPanelFilter(HWND owner,Panel &panel)
{
if(!panelViewAvailable(panel)) return;
FileMaskPrompt prompt{{panel.view.mask,panel.view.showHidden},true};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(116),owner,
fileMaskDialog,reinterpret_cast<LPARAM>(&prompt))!=IDOK) return;
auto &options=prompt.options;
if(options.mask==L"*") options.mask.clear();
if(panel.view.mask==options.mask && panel.view.showHidden==options.includeHidden) return;
panel.view.mask=std::move(options.mask);
panel.view.showHidden=options.includeHidden;
updatePanelView(panel);
}
+73
View File
@@ -0,0 +1,73 @@
bool matchesFileMask(std::wstring_view name,std::wstring_view mask)
{
size_t fileIndex=0, maskIndex=0, star=mask.npos, afterStar=0;
while(fileIndex<name.size())
{
if(maskIndex<mask.size() && mask[maskIndex]==L'*')
{
star=maskIndex++;
afterStar=fileIndex;
}
else if(maskIndex<mask.size() &&
(mask[maskIndex]==L'?' || CompareStringOrdinal(name.data()+fileIndex,1,
mask.data()+maskIndex,1,TRUE)==CSTR_EQUAL))
{
++fileIndex;
++maskIndex;
}
else if(star!=mask.npos)
{
maskIndex=star+1;
fileIndex=++afterStar;
}
else return false;
}
return mask.find_first_not_of(L'*',maskIndex)==mask.npos;
}
std::unique_ptr<Panel::ScanResult> scanFileMatches(const Panel::ScanRequest &request,
std::atomic_size_t &entriesRead,std::stop_token stop)
{
auto result=std::make_unique<Panel::ScanResult>();
FilesConnection local(nullptr);
std::vector<fs::path> pending{request.directory};
size_t visited=0;
while(!pending.empty() && !stop.stop_requested())
{
const auto directory=std::move(pending.back());
pending.pop_back();
try
{
listFiles(local,directory,[&](const fs::path &path,const FileInfo &entry)
{
if(stop.stop_requested()) return false;
entriesRead.store(++visited,std::memory_order_relaxed);
if(!request.find->includeHidden && (entry.attributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM)))
return true;
if(entry.attributes&FILE_ATTRIBUTE_DIRECTORY)
{
if(!(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT)) pending.push_back(path);
}
else if(matchesFileMask(path.filename().native(),request.find->mask))
{
result->files.push_back(path);
result->metadata.emplace(path,FolderEntryMetadata{entry.attributes,entry.size,entry.modified});
}
return true;
});
}
catch(const std::system_error &)
{
if(directory==request.directory)
{
result->failure=L"Cannot search folder: "+directory.native();
return result;
}
result->error=ERROR_PARTIAL_COPY;
}
}
if(stop.stop_requested()) result->error=ERROR_CANCELLED;
result->opened=true;
std::sort(result->files.begin(),result->files.end());
return result;
}
+4 -11
View File
@@ -27,25 +27,18 @@ bool saveFolderShortcuts(const FolderShortcuts &shortcuts)
{"name",ks::utf8(entry.peerName)},{"title",ks::utf8(entry.title)}});
groups.push_back(std::move(rows));
}
const auto data=groups.dump();
return data.size()<=1024*1024 &&
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,REG_BINARY,data.data(),
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
return writeFilesJsonPreference(folderShortcutsKey,groups);
}
catch(const std::exception &){return false;}
}
void loadFolderShortcuts()
{
DWORD bytes{};
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS ||
!bytes || bytes>1024*1024) return;
std::string data(bytes,'\0');
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,RRF_RT_REG_BINARY,nullptr,data.data(),&bytes)!=ERROR_SUCCESS)
return;
const auto saved=readFilesJsonPreference(folderShortcutsKey);
if(!saved) return;
try
{
const auto groups=Json::parse(data.begin(),data.begin()+bytes);
const auto &groups=*saved;
if(!groups.is_array() || groups.size()!=folderShortcuts.size()) return;
FolderShortcuts loaded;
for(size_t digit=0;digit<loaded.size();++digit)
+1244 -325
View File
File diff suppressed because it is too large. Load diff
+192
View File
@@ -0,0 +1,192 @@
constexpr DWORD spaceFileShare=FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE;
bool sameVolumeRoot(const fs::path &directory,const fs::path &root)
{
if(root.empty()) return false;
const auto comparable=[](const fs::path &path) {
auto value=std::wstring_view(path.native());
if(!value.empty() && (value.back()==L'\\' || value.back()==L'/')) value.remove_suffix(1);
return value;
};
const auto left=comparable(directory),right=comparable(root);
return !left.empty() && !right.empty() && CompareStringOrdinal(left.data(),static_cast<int>(left.size()),
right.data(),static_cast<int>(right.size()),TRUE)==CSTR_EQUAL;
}
bool isNtfsVolume(const fs::path &root)
{
wchar_t filesystem[16]{};
return GetVolumeInformationW(root.c_str(),nullptr,0,nullptr,nullptr,nullptr,filesystem,
static_cast<DWORD>(std::size(filesystem))) && std::wstring_view(filesystem)==L"NTFS";
}
using NtfsDirectoryIds=std::set<uint64_t>;
bool appendMftDirectories(std::span<const unsigned char> records,NtfsDirectoryIds &directories)
{
struct UsnRow
{
DWORD length;
WORD major,minor;
DWORDLONG id,parent;
USN usn;
LARGE_INTEGER time;
DWORD reason,source,security,attributes;
WORD nameLength,nameOffset;
};
constexpr auto header=offsetof(UsnRow,nameOffset)+sizeof(WORD);
static_assert(header==60);
while(!records.empty())
{
if(records.size()<header) return false;
UsnRow row{};
memcpy(&row,records.data(),header);
if(row.major!=2 || row.length<header || row.length>records.size()) return false;
if((row.attributes&FILE_ATTRIBUTE_DIRECTORY) && !(row.attributes&FILE_ATTRIBUTE_REPARSE_POINT))
directories.insert(row.id);
records=records.subspan(row.length);
}
return true;
}
bool isExpectedNtfsDirectory(HANDLE handle,const fs::path &directory)
{
std::wstring name(MAX_PATH,L'\0');
const auto getName=[&] {
return GetFinalPathNameByHandleW(handle,name.data(),static_cast<DWORD>(name.size()),
FILE_NAME_OPENED|VOLUME_NAME_DOS);
};
auto length=getName();
if(length>=name.size())
{
name.resize(length+1);
length=getName();
}
if(!length || length>=name.size()) return false;
name.resize(length);
constexpr std::wstring_view devicePrefix=LR"(\\?\)";
const auto &expected=directory.native();
std::wstring_view actual(name);
if(actual.starts_with(devicePrefix) && !std::wstring_view(expected).starts_with(devicePrefix))
actual.remove_prefix(devicePrefix.size());
return CompareStringOrdinal(actual.data(),static_cast<int>(actual.size()),expected.data(),
static_cast<int>(expected.size()),TRUE)==CSTR_EQUAL;
}
bool readMftDirectoryIds(const fs::path &root,NtfsDirectoryIds &directories,std::stop_token stop)
{
wchar_t name[64]{};
if(!GetVolumeNameForVolumeMountPointW(root.c_str(),name,static_cast<DWORD>(std::size(name)))) return false;
const auto length=wcslen(name);
if(!length || name[length-1]!=L'\\') return false;
name[length-1]=L'\0';
const Handle volume{CreateFileW(name,GENERIC_READ,spaceFileShare,nullptr,OPEN_EXISTING,0,nullptr)};
if(volume.value==INVALID_HANDLE_VALUE) return false;
struct Enumeration {DWORDLONG first; USN low,high;};
static_assert(sizeof(Enumeration)==24);
Enumeration request{0,0,std::numeric_limits<USN>::max()};
auto buffer=std::vector<unsigned char>(512*1024);
while(!stop.stop_requested())
{
DWORD bytes{};
if(!DeviceIoControl(volume.value,FSCTL_ENUM_USN_DATA,&request,sizeof(request),buffer.data(),
static_cast<DWORD>(buffer.size()),&bytes,nullptr))
return GetLastError()==ERROR_HANDLE_EOF && !directories.empty();
DWORDLONG next{};
if(bytes<sizeof(next) || bytes>buffer.size()) return false;
memcpy(&next,buffer.data(),sizeof(next));
if(next<=request.first) return false;
if(!appendMftDirectories(std::span<const unsigned char>(buffer).subspan(sizeof(next),bytes-sizeof(next)),
directories)) return false;
request.first=next;
}
return false;
}
class NtfsSpaceWalk
{
public:
NtfsSpaceWalk(const fs::path &root,const fs::path &mount,std::stop_token stop) : root(root),
volumeHint{CreateFileW(root.c_str(),FILE_READ_ATTRIBUTES,spaceFileShare,nullptr,OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,nullptr)}
{
if(volumeHint.value!=INVALID_HANDLE_VALUE)
{
try {indexed=readMftDirectoryIds(mount,mft,stop);}
catch(const std::exception &) {}
}
if(!indexed) mft.clear();
}
bool usedMft() const { return usedIndex; }
bool list(const fs::path &directory,const FileVisitor &visit,std::stop_token stop,FilesConnection &fallback)
{
const bool atRoot=directory==root;
const auto known=byPath.extract(directory);
constexpr DWORD openFlags=FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT;
Handle handle{INVALID_HANDLE_VALUE};
if(known && mft.contains(known.mapped()))
{
FILE_ID_DESCRIPTOR id{};
id.dwSize=sizeof(id);
id.Type=FileIdType;
id.FileId.QuadPart=static_cast<LONGLONG>(known.mapped());
handle.value=OpenFileById(volumeHint.value,&id,FILE_LIST_DIRECTORY|FILE_READ_ATTRIBUTES,
spaceFileShare,nullptr,openFlags);
if(handle.value!=INVALID_HANDLE_VALUE)
{
if(isExpectedNtfsDirectory(handle.value,directory)) usedIndex=true;
else
{
CloseHandle(handle.value);
handle.value=INVALID_HANDLE_VALUE;
}
}
}
if(handle.value==INVALID_HANDLE_VALUE)
handle.value=CreateFileW(directory.c_str(),FILE_LIST_DIRECTORY|FILE_READ_ATTRIBUTES,
spaceFileShare,nullptr,OPEN_EXISTING,atRoot?FILE_FLAG_BACKUP_SEMANTICS:openFlags,nullptr);
if(handle.value==INVALID_HANDLE_VALUE) return false;
FILE_ATTRIBUTE_TAG_INFO tag{};
if(!GetFileInformationByHandleEx(handle.value,FileAttributeTagInfo,&tag,sizeof(tag)) ||
!(tag.FileAttributes&FILE_ATTRIBUTE_DIRECTORY) ||
(!atRoot && (tag.FileAttributes&FILE_ATTRIBUTE_REPARSE_POINT))) return false;
bool emitted=false;
const auto status=ks::files::visitDirectoryRecords(handle.value,[&](const FILE_ID_BOTH_DIR_INFO &row,
std::wstring_view name) -> DWORD
{
if(stop.stop_requested()) return ERROR_CANCELLED;
const auto path=directory/name;
const auto attributes=row.FileAttributes;
const auto directoryEntry=(attributes&FILE_ATTRIBUTE_DIRECTORY)!=0;
if(directoryEntry && !(attributes&FILE_ATTRIBUTE_REPARSE_POINT) && indexed)
{
const auto id=static_cast<uint64_t>(row.FileId.QuadPart);
if(mft.contains(id)) byPath.try_emplace(path,id);
}
FileInfo entry{attributes,static_cast<uint64_t>(row.EndOfFile.QuadPart),
static_cast<uint64_t>(row.LastWriteTime.QuadPart)};
if(!(attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT|
FILE_ATTRIBUTE_COMPRESSED|FILE_ATTRIBUTE_SPARSE_FILE)) && row.AllocationSize.QuadPart>=0)
entry.allocated=static_cast<uint64_t>(row.AllocationSize.QuadPart);
emitted=true;
return visit(path,entry)?ERROR_SUCCESS:ERROR_CANCELLED;
});
if(!emitted && (status==ERROR_NOT_SUPPORTED || status==ERROR_INVALID_PARAMETER || status==ERROR_INVALID_FUNCTION))
{
if(atRoot) return !stop.stop_requested() && listFiles(fallback,directory,visit);
return listMeasuredDirectory(fallback,directory,visit,stop);
}
return status==ERROR_SUCCESS;
}
private:
fs::path root;
Handle volumeHint;
NtfsDirectoryIds mft;
std::map<fs::path,uint64_t> byPath;
bool indexed{}, usedIndex{};
};
+49
View File
@@ -0,0 +1,49 @@
std::wstring_view directoryRowName(const fs::path &path)
{
const auto name=std::wstring_view(path.native());
const auto slash=name.find_last_of(L"/\\");
return slash==name.npos?name:name.substr(slash+1);
}
std::wstring_view directoryRowExtension(std::wstring_view name)
{
const auto dot=name.find_last_of(L'.');
return dot==name.npos || dot==0?std::wstring_view{}:name.substr(dot+1);
}
int compareDirectoryText(std::wstring_view left,std::wstring_view right)
{
if(left.empty() || right.empty()) return static_cast<int>(!left.empty())-static_cast<int>(!right.empty());
return CompareStringOrdinal(left.data(),static_cast<int>(left.size()),right.data(),static_cast<int>(right.size()),TRUE)
- CSTR_EQUAL;
}
void orderDirectoryRows(Panel::ScanResult &result,const PanelView &view)
{
auto &rows=result.ordered;
if(view.showHidden && view.mask.empty()) rows.reserve(result.folders.size()+result.files.size());
const auto append=[&](std::vector<fs::path> &paths,bool folder)
{
for(auto &path:paths)
{
const auto &metadata=result.metadata.at(path);
const uint64_t value=view.sort==PanelSort::modified?metadata.modified:
view.sort==PanelSort::size?metadata.size:0;
if(visibleToPanelView(view,path,metadata)) rows.push_back({std::move(path),value,folder});
}
};
append(result.folders,true);
append(result.files,false);
std::sort(rows.begin(),rows.end(),[&](const DirectoryRow &left,const DirectoryRow &right)
{
if(view.foldersFirst && left.folder!=right.folder) return left.folder;
const auto leftName=directoryRowName(left.path), rightName=directoryRowName(right.path);
int order=0;
if(view.sort==PanelSort::extension)
order=compareDirectoryText(directoryRowExtension(leftName),directoryRowExtension(rightName));
else if(left.value!=right.value) order=left.value<right.value?-1:1;
if(!order) order=compareDirectoryText(leftName,rightName);
if(!order) order=leftName.compare(rightName);
return view.descending?order>0:order<0;
});
}
+116
View File
@@ -0,0 +1,116 @@
class PanelRowsUpdate
{
public:
PanelRowsUpdate(Panel &panel,size_t count) : panel(panel),visible(IsWindowVisible(panel.list)),
profiles(ftpProfileList(panel))
{
if(visible) SendMessageW(panel.list,WM_SETREDRAW,FALSE,0);
panel.rows.clear();
panel.sizes.clear();
panel.dimmed.clear();
panel.marked.clear();
panel.fileExtensionLength=panel.folderExtensionLength=0;
panel.rows.reserve(count);
panel.sizes.reserve(count);
panel.dimmed.reserve(count);
panel.marked.reserve(count);
SendMessageW(panel.list,LB_RESETCONTENT,0,0);
SendMessageW(panel.list,LB_INITSTORAGE,count,0);
}
~PanelRowsUpdate() {finish();}
bool add(const fs::path &path,const std::wstring &label,bool folder,bool marked,bool up=false)
{
if(SendMessageW(panel.list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()))<0) return false;
panel.rows.push_back(path);
if(!up)
{
const auto extension=path.extension().native();
auto &longest=folder?panel.folderExtensionLength:panel.fileExtensionLength;
if(extension.size()>1) longest=std::max(longest,extension.size()-1);
}
panel.marked.push_back(!up && marked);
const auto found=panel.metadata.find(path);
const auto entry=up || profiles || found==panel.metadata.end()?FolderEntryMetadata{}:found->second;
panel.dimmed.push_back((entry.attributes&(FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_HIDDEN))!=0);
panel.sizes.push_back(profiles?L"":folder?(up?L"Up":L"Folder"):std::to_wstring(entry.size));
return true;
}
void finish()
{
if(visible)
{
SendMessageW(panel.list,WM_SETREDRAW,TRUE,0);
visible=false;
}
}
private:
Panel &panel;
bool visible,profiles;
};
bool treePanelActive(const Panel &panel)
{
return panel.view.tree && !panel.findOrigin && !panel.tree.root.empty();
}
void markPanelRow(Panel &panel,size_t row,bool mark)
{
if(row>=panel.rows.size() || panel.sizes[row]==L"Up") return;
panel.marked[row]=mark;
if(!treePanelActive(panel)) return;
const auto &path=panel.rows[row];
if(mark) panel.tree.marks.insert(path);
else panel.tree.marks.erase(path);
}
const FolderEntryMetadata *treePanelEntry(const Panel &panel,const fs::path &path)
{
const auto branch=panel.tree.branches.find(path.parent_path());
if(branch==panel.tree.branches.end()) return nullptr;
const auto item=branch->second.metadata.find(path);
return item==branch->second.metadata.end()?nullptr:&item->second;
}
bool matchesFileMask(std::wstring_view name,std::wstring_view mask);
bool visibleToPanelView(const PanelView &view,const fs::path &path,const FolderEntryMetadata &metadata)
{
if(path==view.revealedFile) return true;
return (view.showHidden || !(metadata.attributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM))) &&
((metadata.attributes&FILE_ATTRIBUTE_DIRECTORY) || view.mask.empty() ||
matchesFileMask(path.filename().native(),view.mask));
}
template<class Visitor>
void visitPanelMarks(const Panel &panel,const Visitor &visit)
{
if(treePanelActive(panel))
{
for(const auto &path:panel.tree.marks)
{
const auto entry=treePanelEntry(panel,path);
if(!entry || !visibleToPanelView(panel.view,path,*entry)) continue;
auto directory=path.parent_path();
while(directory!=panel.tree.root)
{
const auto parent=treePanelEntry(panel,directory);
const auto ancestor=directory.parent_path();
if(!parent || ancestor==directory || !visibleToPanelView(panel.view,directory,*parent)) break;
directory=ancestor;
}
if(directory==panel.tree.root) visit(path,*entry);
}
return;
}
if(ftpProfileList(panel)) return;
for(size_t i=0;i<panel.rows.size();++i)
{
if(!panel.marked[i] || panel.sizes[i]==L"Up") continue;
if(const auto item=panel.metadata.find(panel.rows[i]);item!=panel.metadata.end())
visit(item->first,item->second);
}
}
+229
View File
@@ -0,0 +1,229 @@
void stopTreeBranches(Panel &panel)
{
for(auto &[path,branch]:panel.tree.branches) branch.stop.request_stop();
panel.tree={};
}
bool canExpandTreeEntry(const FolderEntryMetadata &entry)
{
return (entry.attributes&FILE_ATTRIBUTE_DIRECTORY) && !(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT);
}
void startPendingTreeScans(Panel &panel)
{
if(!treePanelActive(panel)) return;
auto running=std::count_if(panel.tree.branches.begin(),panel.tree.branches.end(),
[](const auto &item){return item.second.scan.valid();});
for(auto &[path,branch]:panel.tree.branches)
{
if(running>=2) break;
if(!branch.expanded || !branch.needsScan || branch.scan.valid() || path==panel.tree.root) continue;
branch.needsScan=false;
const auto entry=treePanelEntry(panel,path);
if(!entry || !canExpandTreeEntry(*entry)) continue;
branch.stop=std::stop_source{};
Panel::ScanRequest request{.directory=path,.peer=panel.peer,.ftp=panel.ftp};
try
{
branch.scan=scanDirectoryInBackground(GetParent(panel.list),std::move(request),panel.view,
std::make_shared<std::atomic_size_t>(0),branch.stop.get_token());
++running;
}
catch(const std::exception &) {branch.failed=true;}
}
}
void refreshTreeBranches(Panel &panel)
{
if(!treePanelActive(panel)) return;
for(auto &[path,branch]:panel.tree.branches)
if(branch.expanded && path!=panel.tree.root) branch.needsScan=true;
startPendingTreeScans(panel);
}
void replaceTreeRoot(Panel &panel,Panel::ScanResult &scan,bool sameDirectory,const std::set<fs::path> &marks)
{
auto directory=folderPathWithoutSeparator(panel.directory);
if(!sameDirectory || panel.tree.root!=directory) stopTreeBranches(panel);
panel.tree.root=std::move(directory);
auto &root=panel.tree.branches[panel.tree.root];
root.expanded=root.loaded=true;
root.ordered=std::move(scan.ordered);
root.metadata=std::move(scan.metadata);
panel.tree.marks.insert(marks.begin(),marks.end());
if(scan.error!=ERROR_CANCELLED)
std::erase_if(panel.tree.marks,[&](const auto &path) {
return path.parent_path()==panel.tree.root && !root.metadata.contains(path);
});
refreshTreeBranches(panel);
}
void pruneTreeMarks(Panel &panel,const std::set<fs::path> &removed)
{
if(!treePanelActive(panel) || removed.empty()) return;
std::erase_if(panel.tree.marks,[&](auto path) {
for(;path!=panel.tree.root && path!=path.parent_path();path=path.parent_path())
if(removed.contains(path)) return true;
return false;
});
}
std::wstring treeRowPrefix(const Panel &panel,const fs::path &path,bool folder)
{
const auto depth=panel.tree.depths.find(path);
if(depth==panel.tree.depths.end()) return {};
std::wstring prefix(2*std::min<size_t>(depth->second,40),L' ');
if(!folder) return prefix+L" ";
const auto branch=panel.tree.branches.find(path);
if(branch!=panel.tree.branches.end())
{
if(branch->second.scan.valid() || branch->second.needsScan) return prefix+L"… ";
if(branch->second.expanded) return prefix+(branch->second.failed?L"! ":L"▾ ");
}
if(const auto entry=treePanelEntry(panel,path);entry && canExpandTreeEntry(*entry)) return prefix+L"▸ ";
return prefix+L" ";
}
void appendTreeRows(Panel &panel,PanelRowsUpdate &rows)
{
panel.tree.depths.clear();
panel.metadata.clear();
struct BranchRows {const Panel::TreeBranch *branch; size_t next;};
std::vector<BranchRows> stack{{&panel.tree.branches.at(panel.tree.root),0}};
while(!stack.empty())
{
auto &current=stack.back();
if(current.next==current.branch->ordered.size())
{
stack.pop_back();
continue;
}
const auto &entry=current.branch->ordered[current.next++];
const auto &path=entry.path;
panel.tree.depths.emplace(path,stack.size()-1);
const auto metadata=current.branch->metadata.find(path);
if(metadata==current.branch->metadata.end() || !visibleToPanelView(panel.view,path,metadata->second)) continue;
panel.metadata.emplace(path,metadata->second);
const auto label=treeRowPrefix(panel,path,entry.folder)+path.filename().native();
rows.add(path,label,entry.folder,panel.tree.marks.contains(path));
const auto child=panel.tree.branches.find(path);
if(entry.folder && child!=panel.tree.branches.end() && child->second.expanded && child->second.loaded)
stack.push_back({&child->second,0});
}
}
void redrawTreeRows(Panel &panel)
{
if(!treePanelActive(panel)) return;
const auto current=SendMessageW(panel.list,LB_GETCURSEL,0,0);
const auto top=SendMessageW(panel.list,LB_GETTOPINDEX,0,0);
auto selected=current>=0 && static_cast<size_t>(current)<panel.rows.size()?panel.rows[current]:fs::path{};
const auto parent=panelParentPath(panel.directory,!panel.peer && !panel.ftp);
PanelRowsUpdate rows(panel,panel.rows.size());
if(!parent.empty()) rows.add(parent,L"..",true,false,true);
appendTreeRows(panel,rows);
auto position=std::find(panel.rows.begin(),panel.rows.end(),selected);
while(position==panel.rows.end() && !selected.empty() && selected!=panel.tree.root)
{
const auto next=selected.parent_path();
if(next==selected) break;
selected=next;
position=std::find(panel.rows.begin(),panel.rows.end(),selected);
}
if(!panel.rows.empty())
{
SendMessageW(panel.list,LB_SETTOPINDEX,top,0);
SendMessageW(panel.list,LB_SETCURSEL,position==panel.rows.end()?
std::clamp<LRESULT>(current,0,panel.rows.size()-1):position-panel.rows.begin(),0);
}
rows.finish();
InvalidateRect(panel.list,nullptr,FALSE);
InvalidateRect(panel.heading,nullptr,FALSE);
updateSelectionSummary(panel);
refreshQuickView(panel);
}
void collectTreeBranches()
{
for(auto &panel:panels)
{
if(!treePanelActive(panel)) continue;
bool updated=false;
for(auto &[path,branch]:panel.tree.branches)
{
if(!branch.scan.valid() || branch.scan.wait_for(std::chrono::seconds(0))!=std::future_status::ready) continue;
updated=true;
try
{
auto scan=branch.scan.get();
const auto error=scan->error;
branch.failed=!scan->opened || !scan->failure.empty() ||
(error!=ERROR_SUCCESS && error!=ERROR_NO_MORE_FILES && error!=ERROR_FILE_NOT_FOUND);
if(scan->opened && scan->failure.empty())
{
branch.loaded=true;
branch.ordered=std::move(scan->ordered);
branch.metadata=std::move(scan->metadata);
if(!branch.failed) std::erase_if(panel.tree.marks,[&](const auto &marked) {
return marked.parent_path()==path && !branch.metadata.contains(marked);
});
}
}
catch(const std::exception &) {branch.failed=true;}
if(branch.failed && &panel==&panels[active] && branch.expanded)
setStatus(L"Could not read tree folder: "+path.native());
}
if(updated)
{
startPendingTreeScans(panel);
redrawTreeRows(panel);
queueAutomaticPanelSizes(panel);
}
}
}
bool toggleTreeRow(Panel &panel,size_t row,std::optional<bool> expanded={})
{
if(!treePanelActive(panel) || row>=panel.rows.size() || panel.sizes[row]!=L"Folder") return false;
const auto path=panel.rows[row];
const auto entry=treePanelEntry(panel,path);
if(!entry || !canExpandTreeEntry(*entry)) return false;
auto &branch=panel.tree.branches[path];
const auto next=expanded.value_or(!branch.expanded);
if(next==branch.expanded) return false;
branch.expanded=next;
if(next)
{
branch.needsScan=true;
startPendingTreeScans(panel);
}
else branch.needsScan=false;
redrawTreeRows(panel);
if(&panel==&panels[active])
{
if(next && branch.scan.valid()) setStatus(L"Reading tree folder: "+path.native());
else showFileDetails(panel);
}
return true;
}
bool moveTreeCursor(Panel &panel,bool forward)
{
if(!treePanelActive(panel)) return false;
const auto position=SendMessageW(panel.list,LB_GETCURSEL,0,0);
if(position<0 || static_cast<size_t>(position)>=panel.rows.size() || panel.sizes[position]==L"Up") return false;
if(toggleTreeRow(panel,static_cast<size_t>(position),forward)) return true;
const auto &path=panel.rows[position];
if(forward)
{
if(static_cast<size_t>(position+1)<panel.rows.size() && panel.rows[position+1].parent_path()==path)
SendMessageW(panel.list,LB_SETCURSEL,position+1,0);
}
else
{
const auto parent=std::find(panel.rows.begin(),panel.rows.end(),path.parent_path());
if(parent!=panel.rows.end()) SendMessageW(panel.list,LB_SETCURSEL,parent-panel.rows.begin(),0);
}
invalidatePanelCursorChange(panel.list,position);
return true;
}
+384
View File
@@ -0,0 +1,384 @@
bool localNavigationAvailable(const Panel &panel)
{
return !panel.peer && !panel.ftp && !panel.findOrigin && !panel.directory.empty();
}
enum class PathAction { back, forward, up, edit, ancestors, previous, folder };
void navigateLocal(Panel &panel,const fs::path &path,std::optional<size_t> position={})
{
if(path.empty() || sameLocalFolder(path,panel.directory)) return;
closePanelSearch();
openOn(panel,path,true,{},{},{},{},position);
}
void navigateLocalHistory(Panel &panel,int direction)
{
if(const auto next=panel.navigation.neighbor(direction))
navigateLocal(panel,panel.navigation.history[*next],next);
}
struct PathPart
{
PathAction action{};
std::wstring label;
fs::path target;
std::vector<fs::path> hidden;
RECT rect{};
bool current{}, dim{}, enabled=true;
};
std::wstring pathSegmentLabel(const fs::path &path)
{
return panelParentPath(path,true).empty()?path.native():path.filename().native();
}
LONG segmentWidth(const fs::path &path)
{
return static_cast<LONG>(pathSegmentLabel(path).size()+2)*cellWidth;
}
std::vector<PathPart> localPathParts(const Panel &panel,RECT bounds)
{
const LONG total=bounds.right-bounds.left;
if(total<=0) return {};
const LONG width=std::max(1L,std::min(2L*cellWidth,total/7));
std::vector<PathPart> parts;
const auto add=[&](PathPart part,LONG length)
{
if(length<=0 || bounds.left>=bounds.right) return;
part.rect={bounds.left,bounds.top,std::min(bounds.right,bounds.left+length),bounds.bottom};
bounds.left=part.rect.right;
parts.push_back(std::move(part));
};
const auto parent=panelParentPath(panel.directory,true);
add({.action=PathAction::back,.label=L"←",.enabled=panel.navigation.neighbor(-1).has_value()},width);
add({.action=PathAction::forward,.label=L"→",.enabled=panel.navigation.neighbor(1).has_value()},width);
add({.action=PathAction::up,.label=L"↑",.target=parent,.enabled=!parent.empty()},width);
add({.action=PathAction::edit,.label=L"✎"},width);
std::vector<fs::path> ancestors, previous;
for(auto path=parent;!path.empty();path=panelParentPath(path,true)) ancestors.push_back(path);
std::reverse(ancestors.begin(),ancestors.end());
if(inLocalBranch(panel.directory,panel.navigation.previousBranch))
{
for(auto path=panel.navigation.previousBranch;!sameLocalFolder(path,panel.directory);
path=panelParentPath(path,true))
previous.push_back(path);
std::reverse(previous.begin(),previous.end());
}
const LONG room=bounds.right-bounds.left;
LONG required=segmentWidth(panel.directory);
for(const auto &path:ancestors) required+=segmentWidth(path);
for(const auto &path:previous) required+=segmentWidth(path);
size_t firstAncestor=0,visiblePrevious=previous.size();
LONG currentWidth=segmentWidth(panel.directory);
if(required>room)
{
const LONG reserved=(!ancestors.empty()?width:0)+(!previous.empty()?width:0);
currentWidth=std::min(currentWidth,std::max(1L,room-reserved));
LONG remaining=room-currentWidth-reserved;
firstAncestor=ancestors.size();
while(firstAncestor && remaining>=segmentWidth(ancestors[firstAncestor-1]))
remaining-=segmentWidth(ancestors[--firstAncestor]);
visiblePrevious=0;
while(visiblePrevious<previous.size() && remaining>=segmentWidth(previous[visiblePrevious]))
remaining-=segmentWidth(previous[visiblePrevious++]);
}
if(firstAncestor)
add({.action=PathAction::ancestors,.label=L"…",
.hidden={ancestors.begin(),ancestors.begin()+firstAncestor}},width);
for(size_t i=firstAncestor;i<ancestors.size();++i)
add({.action=PathAction::folder,.label=pathSegmentLabel(ancestors[i]),.target=ancestors[i]},
segmentWidth(ancestors[i]));
add({.action=PathAction::edit,.label=pathSegmentLabel(panel.directory),.current=true},currentWidth);
for(size_t i=0;i<visiblePrevious;++i)
add({.action=PathAction::folder,.label=pathSegmentLabel(previous[i]),.target=previous[i],.dim=true},
segmentWidth(previous[i]));
if(visiblePrevious<previous.size())
add({.action=PathAction::previous,.label=L"…",
.hidden={previous.begin()+visiblePrevious,previous.end()},.dim=true},width);
return parts;
}
void paintLocalPath(HDC dc,RECT bounds,const Panel &panel,bool activePanel)
{
const int saved=SaveDC(dc);
SelectObject(dc,mono);
SetBkMode(dc,TRANSPARENT);
for(const auto &part:localPathParts(panel,bounds))
{
const bool current=activePanel && part.current;
FillRect(dc,&part.rect,current?teal:blue);
SetTextColor(dc,!part.enabled || part.dim?RGB(160,170,190):colors[current?Text:Frame]);
auto text=part.rect;
DrawTextW(dc,part.label.c_str(),static_cast<int>(part.label.size()),&text,
DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX);
}
if(saved) RestoreDC(dc,saved);
}
constexpr int addressField=485,addressLabel=486,addressFooter=487;
struct PathPrompt
{
fs::path base, result;
std::wstring completionInput;
std::future<std::wstring> completion;
};
constexpr UINT addressComplete=WM_APP+29;
constexpr UINT_PTR addressCompletionTimer=1;
fs::path enteredPanelPath(const fs::path &base,std::wstring text)
{
if(text.size()>=2 && text.front()==L'"' && text.back()==L'"')
text=text.substr(1,text.size()-2);
return fs::path(text).is_absolute()?fs::path(std::move(text)):base/fs::path(std::move(text));
}
std::wstring panelPathCompletion(const fs::path &base,const std::wstring &text)
{
const auto path=enteredPanelPath(base,text);
const auto directory=path.has_filename()?path.parent_path():path;
const auto prefix=path.filename().native();
fs::path best;
std::error_code error;
for(fs::directory_iterator it(directory,error),end;!error && it!=end;it.increment(error))
{
const auto name=it->path().filename().native();
if(name.size()<prefix.size() || (!prefix.empty() && CompareStringOrdinal(name.data(),
static_cast<int>(prefix.size()),prefix.data(),static_cast<int>(prefix.size()),TRUE)!=CSTR_EQUAL))
continue;
std::error_code typeError;
if(it->is_directory(typeError) && (best.empty() || it->path()<best)) best=it->path();
}
return best.empty()?std::wstring{}:best.native()+L"\\";
}
LRESULT CALLBACK addressFieldKeys(HWND field,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
{
if(message==WM_GETDLGCODE)
{
const auto *key=reinterpret_cast<const MSG *>(lp);
if(key && key->wParam==VK_TAB && !(GetKeyState(VK_SHIFT)&0x8000))
return DefSubclassProc(field,message,wp,lp)|DLGC_WANTTAB;
}
if(message==WM_KEYDOWN && wp==VK_TAB && !(GetKeyState(VK_SHIFT)&0x8000))
{
SendMessageW(GetParent(field),addressComplete,0,0);
return 0;
}
if(message==WM_CHAR && wp==VK_TAB) return 0;
return DefSubclassProc(field,message,wp,lp);
}
INT_PTR CALLBACK editPathDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_DRAWITEM)
{
paintDialogButton(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp),RGB(192,192,192),RGB(0,0,0),true);
return TRUE;
}
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" Go to folder ",false,{addressFooter}))
return painted;
if(message==WM_INITDIALOG)
{
auto &prompt=*reinterpret_cast<PathPrompt *>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
layoutDialogContent(dialog,addressLabel);
layoutDialogButtons(dialog,addressFooter,{IDOK,IDCANCEL});
const auto field=GetDlgItem(dialog,addressField);
SendMessageW(field,EM_SETLIMITTEXT,32767,0);
SetWindowTextW(field,(prompt.base/fs::path{}).c_str());
SetWindowSubclass(field,addressFieldKeys,4,0);
SetFocus(field);
SendMessageW(field,EM_SETSEL,0,-1);
return FALSE;
}
if(message==addressComplete)
{
auto &prompt=*reinterpret_cast<PathPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(prompt.completion.valid()) return TRUE;
prompt.completionInput=shortcutField(dialog,addressField);
std::packaged_task<std::wstring()> task([base=prompt.base,text=prompt.completionInput]
{
return panelPathCompletion(base,text);
});
if(!SetTimer(dialog,addressCompletionTimer,30,nullptr)) return TRUE;
prompt.completion=task.get_future();
std::thread(std::move(task)).detach();
return TRUE;
}
if(message==WM_TIMER && wp==addressCompletionTimer)
{
auto &prompt=*reinterpret_cast<PathPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!prompt.completion.valid() ||
prompt.completion.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return TRUE;
KillTimer(dialog,addressCompletionTimer);
try
{
const auto value=prompt.completion.get();
if(!value.empty() && shortcutField(dialog,addressField)==prompt.completionInput)
{
const auto field=GetDlgItem(dialog,addressField);
SetWindowTextW(field,value.c_str());
SendMessageW(field,EM_SETSEL,value.size(),value.size());
SendMessageW(field,EM_SCROLLCARET,0,0);
}
}
catch(const std::exception &) {}
return TRUE;
}
if(message==WM_COMMAND && LOWORD(wp)==IDOK)
{
auto &prompt=*reinterpret_cast<PathPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
auto path=enteredPanelPath(prompt.base,shortcutField(dialog,addressField)).lexically_normal();
if(!path.is_absolute())
{
showFilesNotice(dialog,L"Enter a folder path.",L"Go to folder");
return TRUE;
}
if(!path.has_filename() && path.has_relative_path()) path=path.parent_path();
prompt.result=std::move(path);
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
return FALSE;
}
void editPanelPath(Panel &panel)
{
PathPrompt prompt{panel.directory};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(117),GetParent(panel.list),
editPathDialog,reinterpret_cast<LPARAM>(&prompt))==IDOK)
navigateLocal(panel,prompt.result);
}
void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector<fs::path> paths,RECT anchor,bool recent=false)
{
hidePicker();
showMenu(false);
commandPicker=false;
pickerPanel=side;
folderPicker=FolderPicker{caption,std::move(paths),recent};
SendMessageW(picker,LB_RESETCONTENT,0,0);
size_t longest=wcslen(caption);
for(const auto &path:folderPicker->paths)
{
longest=std::max(longest,path.native().size());
SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(path.c_str()));
}
RECT client{};
GetClientRect(owner,&client);
const int inset=dialogFrameMetrics(GetDpiForWindow(owner)).content();
const int width=std::max(1,std::min(static_cast<int>(client.right)-2*inset,static_cast<int>(longest+3)*cellWidth));
const int x=std::clamp(static_cast<int>(anchor.left),inset,std::max(inset,static_cast<int>(client.right)-width-inset));
const int y=anchor.bottom+inset;
const int row=std::max(1,static_cast<int>(SendMessageW(picker,LB_GETITEMHEIGHT,0,0)));
RECT input{};
GetWindowRect(terminalInput,&input);
MapWindowPoints(nullptr,owner,reinterpret_cast<POINT *>(&input),2);
const int bottom=std::min(client.bottom,input.top);
const int shown=std::clamp((bottom-y-inset)/row,1,static_cast<int>(folderPicker->paths.size()));
showFramedList(picker,pickerFrame,x,y,width,row*shown,inset);
SendMessageW(picker,LB_SETCURSEL,0,0);
SetFocus(picker);
}
void showRecentFolders(int side)
{
auto paths=readRecentFolders();
if(paths.empty())
{
setStatus(L"No recent local folders.");
return;
}
const auto owner=GetParent(picker);
RECT anchor{};
GetWindowRect(panels[side].path,&anchor);
MapWindowPoints(nullptr,owner,reinterpret_cast<POINT *>(&anchor),2);
showFolderPicker(owner,side,L"Recent folders",std::move(paths),anchor,true);
}
void showHiddenPathParts(HWND window,int side,const PathPart &part)
{
const auto owner=GetParent(window);
auto anchor=part.rect;
MapWindowPoints(window,owner,reinterpret_cast<POINT*>(&anchor),2);
showFolderPicker(owner,side,part.action==PathAction::ancestors?L"Parent folders":L"Previous path",
part.hidden,anchor);
}
LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
{
if(message==WM_LBUTTONDOWN)
{
SetCapture(window);
return 0;
}
if(message==WM_LBUTTONUP && GetCapture()==window)
{
ReleaseCapture();
const int index=GetDlgCtrlID(window)-142;
if(index<0 || index>=2) return 0;
panelClipboardContext=true;
auto &panel=panels[index];
if(!localNavigationAvailable(panel))
{
selectPanelEdge(panel,true);
return 0;
}
activatePanel(index);
RECT bounds{};
GetClientRect(window,&bounds);
const POINT mouse{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
const auto parts=localPathParts(panel,bounds);
for(const auto &part:parts)
{
if(!part.enabled || !PtInRect(&part.rect,mouse)) continue;
switch(part.action)
{
case PathAction::back: navigateLocalHistory(panel,-1); break;
case PathAction::forward: navigateLocalHistory(panel,1); break;
case PathAction::up: case PathAction::folder: navigateLocal(panel,part.target); break;
case PathAction::edit: editPanelPath(panel); break;
case PathAction::ancestors: case PathAction::previous: showHiddenPathParts(window,index,part); break;
}
break;
}
return 0;
}
return DefSubclassProc(window,message,wp,lp);
}
bool handleLocalPathKey(HWND owner,const MSG &message)
{
if(!commandLineAvailable(owner) || terminalVisible || !localNavigationAvailable(panels[active]) ||
(message.hwnd!=terminalInput && message.hwnd!=panels[active].list) ||
((GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000)) return false;
auto &panel=panels[active];
if(message.message==WM_KEYDOWN && message.wParam=='L' &&
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000))
{
if(!(message.lParam&(1LL<<30))) editPanelPath(panel);
return true;
}
if(message.message!=WM_SYSKEYDOWN || !(message.lParam&(1LL<<29)) ||
(GetKeyState(VK_CONTROL)&0x8000)) return false;
if(message.wParam==VK_UP)
navigateLocal(panel,panelParentPath(panel.directory,true));
else if(message.wParam==VK_LEFT || message.wParam==VK_RIGHT)
navigateLocalHistory(panel,message.wParam==VK_LEFT?-1:1);
else return false;
return true;
}
+41
View File
@@ -0,0 +1,41 @@
constexpr wchar_t recentFoldersKey[]=L"RecentFolders";
constexpr size_t recentFoldersLimit=100;
std::vector<fs::path> readRecentFolders()
{
const auto saved=readFilesJsonPreference(recentFoldersKey);
std::vector<fs::path> folders;
if(!saved || !saved->is_array()) return folders;
for(const auto &entry:*saved)
{
if(!entry.is_string()) continue;
const auto path=filePath(entry);
if(!path.is_absolute() || path.native().find(L'\0')!=std::wstring::npos) continue;
if(std::none_of(folders.begin(),folders.end(),[&](const auto &known){return sameLocalFolder(path,known);}))
folders.push_back(path);
if(folders.size()==recentFoldersLimit) break;
}
return folders;
}
bool updateRecentFolders(const fs::path &path,bool remember)
{
const Handle lock{CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.RecentFolders")};
if(!lock.value) return false;
const auto wait=WaitForSingleObject(lock.value,100);
if(wait!=WAIT_OBJECT_0 && wait!=WAIT_ABANDONED) return false;
bool saved=false;
try
{
auto folders=readRecentFolders();
std::erase_if(folders,[&](const auto &known){return sameLocalFolder(path,known);});
if(remember) folders.insert(folders.begin(),path);
if(folders.size()>recentFoldersLimit) folders.resize(recentFoldersLimit);
auto data=Json::array();
for(const auto &folder:folders) data.push_back(ks::utf8(folder.native()));
saved=writeFilesJsonPreference(recentFoldersKey,data);
}
catch(const std::exception &) {}
ReleaseMutex(lock.value);
return saved;
}
+25
View File
@@ -0,0 +1,25 @@
constexpr DWORD maxFilesJsonBytes=1024*1024;
std::optional<Json> readFilesJsonPreference(const wchar_t *key)
{
DWORD bytes{};
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,key,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS ||
!bytes || bytes>maxFilesJsonBytes) return {};
std::string data(bytes,'\0');
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,key,RRF_RT_REG_BINARY,nullptr,data.data(),&bytes)!=ERROR_SUCCESS)
return {};
try {return Json::parse(data.begin(),data.begin()+bytes);}
catch(const std::exception &) {return {};}
}
bool writeFilesJsonPreference(const wchar_t *key,const Json &value)
{
try
{
const auto data=value.dump();
return data.size()<=maxFilesJsonBytes &&
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,key,REG_BINARY,data.data(),
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
}
catch(const std::exception &) {return false;}
}
+655
View File
@@ -0,0 +1,655 @@
constexpr int spacePath=488,spaceTree=489,spaceStatus=490,spaceFooter=491;
constexpr int spaceStop=492,spaceRescan=493,spaceView=494;
constexpr int spaceCapacity=495,spaceScope=496,spaceMapButton=497,spaceMap=498;
constexpr int spaceSunburstButton=499,spaceSunburstList=500,spaceSunburstLabel=501;
constexpr UINT_PTR spaceUpdateTimer=1;
constexpr UINT_PTR spaceVolumeTimer=2;
constexpr size_t spaceBatchSize=256;
constexpr std::initializer_list<int> spaceFooterButtons{spaceStop,spaceRescan,spaceView,IDOK,IDCANCEL};
struct SpaceVolume
{
fs::path root;
std::optional<std::pair<uint64_t,uint64_t>> capacity;
};
std::future<SpaceVolume> readSpaceVolume(const fs::path &folder)
{
std::packaged_task<SpaceVolume()> task([folder] {
SpaceVolume result;
std::wstring root(32768,L'\0');
if(GetVolumePathNameW(folder.c_str(),root.data(),static_cast<DWORD>(root.size())))
{
root.resize(wcslen(root.c_str()));
result.root=fs::path(std::move(root));
}
ULARGE_INTEGER total{},free{};
if(GetDiskFreeSpaceExW(result.root.empty()?folder.c_str():result.root.c_str(),&free,&total,nullptr))
result.capacity=std::pair{total.QuadPart,free.QuadPart};
return result;
});
auto result=task.get_future();
std::thread(std::move(task)).detach();
return result;
}
std::optional<uint64_t> allocatedFileBytes(const fs::path &path,DWORD attributes)
{
const Handle file{CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
nullptr,OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(file.value==INVALID_HANDLE_VALUE) return {};
if(attributes&(FILE_ATTRIBUTE_COMPRESSED|FILE_ATTRIBUTE_SPARSE_FILE))
{
FILE_COMPRESSION_INFO compression{};
if(GetFileInformationByHandleEx(file.value,FileCompressionInfo,&compression,sizeof(compression)) &&
compression.CompressedFileSize.QuadPart>=0)
return static_cast<uint64_t>(compression.CompressedFileSize.QuadPart);
return {};
}
FILE_STANDARD_INFO metadata{};
if(GetFileInformationByHandleEx(file.value,FileStandardInfo,&metadata,sizeof(metadata)) &&
!metadata.Directory && metadata.AllocationSize.QuadPart>=0)
return static_cast<uint64_t>(metadata.AllocationSize.QuadPart);
return {};
}
struct SpaceAllocation
{
FolderSize known;
size_t measured{}, unavailable{};
void add(std::optional<uint64_t> size)
{
if(size)
{
++measured;
known.add(*size);
}
else ++unavailable;
}
};
struct SpaceTile
{
RECT box;
size_t node;
};
#include "files_ntfs_space.inl"
struct SpaceSector
{
size_t node;
unsigned ring;
double start,end;
};
enum class SpaceDisplay { tree, treemap, sunburst };
struct SpaceEvent
{
fs::path path;
std::optional<FileInfo> item;
std::optional<uint64_t> allocated;
};
struct SpaceRun
{
std::stop_source stop;
std::mutex mutex;
std::deque<std::vector<SpaceEvent>> pending;
FolderSize result;
bool finished{}, stopped{}, indexed{};
};
std::shared_ptr<SpaceRun> startSpaceRun(const fs::path &root,const fs::path &mount)
{
auto run=std::make_shared<SpaceRun>();
std::thread([run,root,mount] {
std::vector<SpaceEvent> batch;
auto lastUpdate=GetTickCount64();
const auto publish=[&] {
if(batch.empty()) return;
std::lock_guard lock(run->mutex);
run->pending.push_back(std::move(batch));
batch.clear();
lastUpdate=GetTickCount64();
};
FolderSize total;
const auto stop=run->stop.get_token();
try
{
FilesConnection host(nullptr);
const bool volume=!mount.empty();
std::optional<NtfsSpaceWalk> ntfs;
if(volume && isNtfsVolume(mount)) ntfs.emplace(root,mount,stop);
bool indexReported=false;
total=measureFolder(root,stop,[&](const fs::path &directory,const FileVisitor &visit) {
if(ntfs)
{
const auto result=ntfs->list(directory,visit,stop,host);
if(!indexReported && ntfs->usedMft())
{
std::lock_guard lock(run->mutex);
run->indexed=indexReported=true;
}
return result;
}
if(volume && directory==root) return !stop.stop_requested() && listFiles(host,directory,visit);
return listMeasuredDirectory(host,directory,visit,stop);
},[&](const fs::path &path,const FileInfo *info) {
const auto allocate=info && !(info->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT));
const auto allocation=allocate?(info->allocated?info->allocated:allocatedFileBytes(path,info->attributes)):
std::nullopt;
batch.push_back({path,info?std::optional<FileInfo>(*info):std::nullopt,allocation});
if(batch.size()>=spaceBatchSize || GetTickCount64()-lastUpdate>=80) publish();
});
publish();
}
catch(const std::exception &) {total.partial=true;}
std::lock_guard lock(run->mutex);
run->result=total;
run->stopped=stop.stop_requested();
run->finished=true;
}).detach();
return run;
}
struct SpaceNode
{
fs::path path;
FolderSize size;
SpaceAllocation allocated;
size_t parent{};
std::vector<size_t> children;
HTREEITEM item{};
bool folder{}, link{}, expanded{};
};
struct SpaceAnalyzer
{
fs::path folder, root, selected;
SpaceVolume volume;
std::future<SpaceVolume> pendingVolume;
bool selectedFolder{}, volumeScope{};
SpaceDisplay display{SpaceDisplay::tree};
std::shared_ptr<SpaceRun> run;
std::vector<SpaceNode> nodes;
std::map<fs::path,size_t> directories;
size_t files{}, mapFolder{}, selectedTile{};
std::vector<SpaceTile> tiles;
std::vector<SpaceSector> sectors;
ULONGLONG lastMapUpdate{};
bool scanning{}, hasResults{};
};
void layoutSpaceAnalyzer(HWND dialog)
{
RECT bounds{};
GetClientRect(dialog,&bounds);
const auto frame=dialogFrameMetrics(GetDpiForWindow(dialog));
const auto inset=frame.content();
const auto width=std::max(1L,bounds.right-2*inset);
const auto place=[&](int id,int top,int height) {
SetWindowPos(GetDlgItem(dialog,id),nullptr,inset,top,width,height,SWP_NOZORDER|SWP_NOACTIVATE);
};
auto top=dialogListInset(frame,textHeight);
place(spacePath,top,textHeight);
top+=textHeight;
place(spaceCapacity,top,textHeight);
top+=textHeight+dialogRowGap();
const auto buttonHeight=textHeight;
auto x=inset;
for(const auto id:{spaceScope,spaceMapButton,spaceSunburstButton})
{
const auto button=GetDlgItem(dialog,id);
const auto width=std::max(12L*cellWidth,farDialogButtonWidth(button));
SetWindowPos(button,nullptr,x,top,width,buttonHeight,SWP_NOZORDER|SWP_NOACTIVATE);
x+=width+dialogColumnGap();
}
top+=buttonHeight+dialogRowGap();
place(spaceTree,top,9*textHeight);
const auto state=reinterpret_cast<const SpaceAnalyzer *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(state && state->display==SpaceDisplay::sunburst)
{
const auto graphWidth=width*3/5;
const auto gap=dialogColumnGap();
SetWindowPos(GetDlgItem(dialog,spaceSunburstLabel),nullptr,inset+graphWidth,top-textHeight-dialogRowGap(),
width-graphWidth,textHeight,SWP_NOZORDER|SWP_NOACTIVATE);
SetWindowPos(GetDlgItem(dialog,spaceMap),nullptr,inset,top,graphWidth-gap,9*textHeight,
SWP_NOZORDER|SWP_NOACTIVATE);
SetWindowPos(GetDlgItem(dialog,spaceSunburstList),nullptr,inset+graphWidth,top,width-graphWidth,
9*textHeight,SWP_NOZORDER|SWP_NOACTIVATE);
}
else place(spaceMap,top,9*textHeight);
top+=9*textHeight+dialogRowGap();
place(spaceStatus,top,textHeight);
place(spaceFooter,top+textHeight+dialogRowGap(),1);
layoutDialogButtons(dialog,spaceFooter,spaceFooterButtons);
}
HTREEITEM insertSpaceNode(HWND tree,SpaceAnalyzer &state,size_t index)
{
auto &node=state.nodes[index];
TVINSERTSTRUCTW insert{};
insert.hParent=index?state.nodes[node.parent].item:TVI_ROOT;
insert.hInsertAfter=TVI_LAST;
insert.item.mask=TVIF_TEXT|TVIF_PARAM|TVIF_CHILDREN;
insert.item.pszText=LPSTR_TEXTCALLBACKW;
insert.item.lParam=static_cast<LPARAM>(index);
insert.item.cChildren=node.folder && !node.link?I_CHILDRENCALLBACK:0;
node.item=TreeView_InsertItem(tree,&insert);
return node.item;
}
void expandSpaceNode(HWND tree,SpaceAnalyzer &state,size_t index)
{
auto &node=state.nodes[index];
if(node.expanded) return;
node.expanded=true;
for(auto child:node.children) insertSpaceNode(tree,state,child);
}
void addSpaceEvent(HWND tree,SpaceAnalyzer &state,SpaceEvent event)
{
if(!event.item)
{
const auto directory=state.directories.find(event.path);
if(directory==state.directories.end()) return;
for(auto i=directory->second;;i=state.nodes[i].parent)
{
state.nodes[i].size.partial=true;
if(!i) break;
}
return;
}
const auto parent=state.directories.find(event.path.parent_path());
if(parent==state.directories.end()) return;
const auto index=state.nodes.size();
const bool folder=(event.item->attributes&FILE_ATTRIBUTE_DIRECTORY)!=0;
const bool link=(event.item->attributes&FILE_ATTRIBUTE_REPARSE_POINT)!=0;
const auto bytes=folder || link?0:event.item->size;
if(folder) state.directories.emplace(event.path,index);
else ++state.files;
state.nodes.push_back({.path=std::move(event.path),.size={bytes,false},.parent=parent->second,
.folder=folder,.link=link});
if(!folder && !link) state.nodes[index].allocated.add(event.allocated);
auto &parentNode=state.nodes[parent->second];
parentNode.children.push_back(index);
if(parentNode.item && parentNode.expanded)
{
insertSpaceNode(tree,state,index);
if(parentNode.children.size()==1) TreeView_Expand(tree,parentNode.item,TVE_EXPAND);
}
for(auto i=parent->second;;i=state.nodes[i].parent)
{
state.nodes[i].size.add(bytes);
if(!folder && !link) state.nodes[i].allocated.add(event.allocated);
if(!i) break;
}
}
std::wstring spaceLogicalSize(const SpaceNode &node)
{
return formatSize(node.size.bytes)+(node.size.partial?L"+ logical":L" logical");
}
std::wstring spaceAllocatedSize(const SpaceNode &node)
{
const auto &allocation=node.allocated;
if(!allocation.measured && allocation.unavailable) return L"— on disk";
auto result=formatSize(allocation.known.bytes);
if(allocation.unavailable || allocation.known.partial || node.size.partial) result+=L"+";
return result+L" on disk";
}
std::wstring spaceNodeText(const SpaceAnalyzer &state,size_t index)
{
const auto &node=state.nodes[index];
const auto &parent=state.nodes[node.parent];
auto name=node.path.filename().native();
if(name.empty()) name=node.path.native();
if(name.size()>196)
{
name.resize(196);
if(name.back()>=0xD800 && name.back()<=0xDBFF) name.pop_back();
name+=L"…";
}
if(!state.hasResults) return name;
if(node.link) return name+L" [link]";
auto result=name+L" — "+spaceLogicalSize(node)+L" · "+spaceAllocatedSize(node);
if(parent.size.bytes)
{
wchar_t share[48]{};
swprintf_s(share,L" (%.1f%%)",100.0*static_cast<double>(node.size.bytes)/static_cast<double>(parent.size.bytes));
result+=share;
}
return result;
}
std::optional<size_t> selectedSpaceNode(HWND tree,const SpaceAnalyzer &state)
{
TVITEMW item{};
item.mask=TVIF_PARAM;
item.hItem=TreeView_GetSelection(tree);
if(item.hItem && TreeView_GetItem(tree,&item) && static_cast<size_t>(item.lParam)<state.nodes.size())
return static_cast<size_t>(item.lParam);
return {};
}
#include "files_space_map.inl"
void updateSpaceTree(HWND dialog,SpaceAnalyzer &state)
{
const auto tree=GetDlgItem(dialog,spaceTree);
const auto budget=GetTickCount64()+15;
bool finished=false,stopped=false,changed=false,indexed=false;
do
{
std::vector<SpaceEvent> batch;
{
std::lock_guard lock(state.run->mutex);
indexed=state.run->indexed;
if(!state.run->pending.empty())
{
batch=std::move(state.run->pending.front());
state.run->pending.pop_front();
}
else if(state.run->finished)
{
finished=true;
stopped=state.run->stopped;
state.nodes[0].size.partial|=state.run->result.partial;
}
}
if(batch.empty()) break;
if(!changed) SendMessageW(tree,WM_SETREDRAW,FALSE,0);
changed=true;
for(auto &event:batch) addSpaceEvent(tree,state,std::move(event));
} while(GetTickCount64()<budget);
if(finished) state.scanning=false;
if(changed) SendMessageW(tree,WM_SETREDRAW,TRUE,0);
if(state.display!=SpaceDisplay::tree && (finished || (changed && GetTickCount64()-state.lastMapUpdate>=200)))
refreshSpaceChart(GetDlgItem(dialog,spaceMap),state);
if(changed || finished) InvalidateRect(tree,nullptr,FALSE);
const bool stopping=state.run->stop.stop_requested();
auto status=finished?(stopped?L"Stopped · partial":state.nodes[0].size.partial?L"Partial results":L"Complete"):
stopping?L"Stopping…":L"Scanning…";
const auto &allocation=state.nodes[0].allocated;
auto label=std::wstring(status)+L" · "+std::to_wstring(state.files)+L" files";
if(indexed) label+=L" · NTFS index";
if(allocation.unavailable || allocation.known.partial) label+=L" · on-disk sizes partial";
else label+=state.display==SpaceDisplay::treemap?L" · logical size by area":
state.display==SpaceDisplay::sunburst?L" · logical size by angle":L" · logical shares of parent";
SetDlgItemTextW(dialog,spaceStatus,label.c_str());
if(finished)
{
EnableWindow(GetDlgItem(dialog,spaceStop),FALSE);
EnableWindow(GetDlgItem(dialog,spaceRescan),TRUE);
EnableWindow(GetDlgItem(dialog,spaceScope),!state.volume.root.empty() &&
!sameVolumeRoot(state.folder,state.volume.root));
KillTimer(dialog,spaceUpdateTimer);
}
}
void resetSpaceResults(HWND dialog,SpaceAnalyzer &state,bool scanning)
{
const auto tree=GetDlgItem(dialog,spaceTree);
TreeView_DeleteAllItems(tree);
state.nodes.clear();
state.nodes.push_back({.path=state.root,.folder=true,.expanded=true});
state.directories.clear();
state.directories.emplace(state.root,0);
state.files=0;
state.mapFolder=0;
state.tiles.clear();
state.sectors.clear();
state.selectedTile=0;
state.scanning=scanning;
state.hasResults=scanning;
TreeView_SelectItem(tree,insertSpaceNode(tree,state,0));
if(state.display!=SpaceDisplay::tree) refreshSpaceChart(GetDlgItem(dialog,spaceMap),state);
EnableWindow(GetDlgItem(dialog,spaceView),FALSE);
EnableWindow(GetDlgItem(dialog,IDOK),state.display==SpaceDisplay::tree);
}
void prepareSpaceScope(HWND dialog,SpaceAnalyzer &state)
{
state.run.reset();
const auto scope=state.volumeScope?state.volume.root:state.folder;
state.root=folderPathWithoutSeparator(scope);
SetDlgItemTextW(dialog,spacePath,scope.c_str());
SetDlgItemTextW(dialog,spaceScope,state.volumeScope?L"&Folder":L"Vo&lume");
SetDlgItemTextW(dialog,spaceRescan,L"St&art");
SetDlgItemTextW(dialog,spaceStatus,L"Ready to scan");
EnableWindow(GetDlgItem(dialog,spaceRescan),TRUE);
EnableWindow(GetDlgItem(dialog,spaceStop),FALSE);
resetSpaceResults(dialog,state,false);
layoutSpaceAnalyzer(dialog);
}
void updateSpaceVolume(HWND dialog,SpaceAnalyzer &state)
{
if(!state.pendingVolume.valid() ||
state.pendingVolume.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
try {state.volume=state.pendingVolume.get();}
catch(const std::exception &) {}
KillTimer(dialog,spaceVolumeTimer);
std::wstring caption=L"Volume capacity unavailable";
if(const auto capacity=state.volume.capacity)
{
caption=L"Capacity "+formatSize(capacity->first)+L" · Free "+formatSize(capacity->second);
if(!state.volume.root.empty()) caption+=L" · "+state.volume.root.native();
}
SetDlgItemTextW(dialog,spaceCapacity,caption.c_str());
EnableWindow(GetDlgItem(dialog,spaceScope),
!state.volume.root.empty() && !sameVolumeRoot(state.folder,state.volume.root));
prepareSpaceScope(dialog,state);
}
void rescanSpace(HWND dialog,SpaceAnalyzer &state)
{
resetSpaceResults(dialog,state,true);
SetDlgItemTextW(dialog,spaceRescan,L"&Rescan");
EnableWindow(GetDlgItem(dialog,spaceRescan),FALSE);
EnableWindow(GetDlgItem(dialog,spaceScope),FALSE);
try
{
const bool volume=state.volumeScope || sameVolumeRoot(state.root,state.volume.root);
state.run=startSpaceRun(state.root,volume?state.volume.root:fs::path{});
EnableWindow(GetDlgItem(dialog,spaceStop),TRUE);
SetTimer(dialog,spaceUpdateTimer,60,nullptr);
updateSpaceTree(dialog,state);
}
catch(const std::exception &)
{
EnableWindow(GetDlgItem(dialog,spaceStop),FALSE);
EnableWindow(GetDlgItem(dialog,spaceRescan),TRUE);
state.scanning=false;
EnableWindow(GetDlgItem(dialog,spaceScope),!state.volume.root.empty() &&
!sameVolumeRoot(state.folder,state.volume.root));
SetDlgItemTextW(dialog,spaceStatus,L"Could not start space analysis.");
}
}
INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
auto &state=*reinterpret_cast<SpaceAnalyzer *>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
SetDlgItemTextW(dialog,spacePath,state.folder.c_str());
SetDlgItemTextW(dialog,spaceCapacity,L"Reading volume capacity…");
const auto tree=GetDlgItem(dialog,spaceTree);
SetWindowSubclass(GetDlgItem(dialog,spaceMap),spaceMapInput,1,reinterpret_cast<DWORD_PTR>(&state));
SetWindowSubclass(GetDlgItem(dialog,spaceSunburstList),spaceSunburstListKeys,1,reinterpret_cast<DWORD_PTR>(&state));
TreeView_SetBkColor(tree,RGB(255,255,255));
TreeView_SetTextColor(tree,RGB(0,0,0));
layoutSpaceAnalyzer(dialog);
const auto inset=dialogFrameMetrics(GetDpiForWindow(dialog)).content();
// Rescan is one character wider than the initial Start label.
const auto minimum=dialogButtonGroupWidth(dialog,spaceFooterButtons)+cellWidth+2*inset;
FilesModalDialog::fitWidthToOwner(dialog,minimum,layoutSpaceAnalyzer);
SendMessageW(dialog,DM_SETDEFID,IDCANCEL,0);
resetSpaceResults(dialog,state,false);
EnableWindow(GetDlgItem(dialog,spaceScope),FALSE);
EnableWindow(GetDlgItem(dialog,spaceRescan),FALSE);
EnableWindow(GetDlgItem(dialog,spaceStop),FALSE);
try
{
state.pendingVolume=readSpaceVolume(state.folder);
SetTimer(dialog,spaceVolumeTimer,60,nullptr);
updateSpaceVolume(dialog,state);
}
catch(const std::exception &)
{
SetDlgItemTextW(dialog,spaceCapacity,L"Volume capacity unavailable");
prepareSpaceScope(dialog,state);
}
SetFocus(tree);
return FALSE;
}
const auto state=reinterpret_cast<SpaceAnalyzer *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!state) return FALSE;
const auto tree=GetDlgItem(dialog,spaceTree);
if(message==WM_DRAWITEM && wp==spaceMap)
{
const auto &paint=*reinterpret_cast<const DRAWITEMSTRUCT *>(lp);
if(state->display==SpaceDisplay::sunburst) paintSunburst(paint,*state);
else paintSpaceMap(paint,*state);
return TRUE;
}
if(message==WM_TIMER && wp==spaceVolumeTimer)
{
updateSpaceVolume(dialog,*state);
return TRUE;
}
if(message==WM_TIMER && wp==spaceUpdateTimer)
{
updateSpaceTree(dialog,*state);
return TRUE;
}
if(message==WM_NOTIFY)
{
const auto *notification=reinterpret_cast<const NMHDR *>(lp);
if(notification->hwndFrom==tree)
{
if(notification->code==TVN_GETDISPINFOW)
{
auto &item=reinterpret_cast<NMTVDISPINFOW *>(lp)->item;
const auto index=static_cast<size_t>(item.lParam);
if(index>=state->nodes.size()) return TRUE;
const auto &node=state->nodes[index];
if(item.mask&TVIF_CHILDREN) item.cChildren=node.folder && !node.link &&
(state->scanning || !node.children.empty())?1:0;
if((item.mask&TVIF_TEXT) && item.pszText && item.cchTextMax>0)
{
const auto text=spaceNodeText(*state,index);
lstrcpynW(item.pszText,text.c_str(),item.cchTextMax);
}
return TRUE;
}
if(notification->code==TVN_ITEMEXPANDINGW)
{
const auto &item=*reinterpret_cast<const NMTREEVIEWW *>(lp);
const auto index=static_cast<size_t>(item.itemNew.lParam);
if(item.action==TVE_EXPAND && index<state->nodes.size()) expandSpaceNode(tree,*state,index);
}
if(notification->code==TVN_SELCHANGEDW)
{
const auto selected=selectedSpaceNode(tree,*state);
if(state->display==SpaceDisplay::tree)
{
EnableWindow(GetDlgItem(dialog,spaceView),selected && !state->nodes[*selected].folder);
EnableWindow(GetDlgItem(dialog,IDOK),selected.has_value());
}
}
}
}
if(message==WM_COMMAND)
{
const auto command=LOWORD(wp);
if(command==spaceStop && IsWindowEnabled(GetDlgItem(dialog,spaceStop)))
{
state->run->stop.request_stop();
EnableWindow(GetDlgItem(dialog,spaceStop),FALSE);
updateSpaceTree(dialog,*state);
return TRUE;
}
if(command==spaceScope && IsWindowEnabled(GetDlgItem(dialog,spaceScope)))
{
state->volumeScope=!state->volumeScope;
prepareSpaceScope(dialog,*state);
return TRUE;
}
if(command==spaceMapButton || command==spaceSunburstButton)
{
const auto chart=command==spaceMapButton?SpaceDisplay::treemap:SpaceDisplay::sunburst;
setSpaceDisplay(dialog,*state,state->display==chart?SpaceDisplay::tree:chart);
if(state->run) updateSpaceTree(dialog,*state);
return TRUE;
}
if(command==spaceSunburstList && state->display==SpaceDisplay::sunburst)
{
updateSunburstSelection(dialog,*state);
if(HIWORD(wp)==LBN_DBLCLK)
if(const auto selected=sunburstSelection(dialog,*state))
finishSpaceSelection(dialog,*state,*selected,IDOK);
return TRUE;
}
if(command==spaceRescan && IsWindowEnabled(GetDlgItem(dialog,spaceRescan)))
{
rescanSpace(dialog,*state);
return TRUE;
}
if(command==IDOK || command==spaceView)
{
const auto selected=state->display==SpaceDisplay::sunburst?sunburstSelection(dialog,*state):
state->display==SpaceDisplay::tree?selectedSpaceNode(tree,*state):std::nullopt;
if(selected) finishSpaceSelection(dialog,*state,*selected,command);
return TRUE;
}
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message==WM_DESTROY)
{
if(state->run) state->run->stop.request_stop();
KillTimer(dialog,spaceUpdateTimer);
KillTimer(dialog,spaceVolumeTimer);
}
return paintCopyDialog(dialog,message,wp,lp,L" Space Analyzer ",false,{spaceFooter});
}
void openSpaceAnalyzer(HWND owner,Panel &panel)
{
if(panel.peer || panel.ftp || panel.directory.empty())
{
setStatus(L"Space Analyzer requires an open local folder.");
return;
}
const auto origin=static_cast<int>(&panel-panels);
SpaceAnalyzer state{.folder=folderPathWithoutSeparator(panel.directory),.root=folderPathWithoutSeparator(panel.directory)};
const auto answer=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(118),owner,
spaceAnalyzerDialog,reinterpret_cast<LPARAM>(&state));
if(answer==spaceView)
{
ks::files::openTextWindow(owner,state.selected,false,textWindowDialogs(),nullptr);
return;
}
if(answer!=IDOK) return;
if(quickViewWindow) toggleQuickView(owner);
if(terminalVisible) showTerminal(owner,false);
const auto index=1-origin;
auto &other=panels[index];
activatePanel(index);
panelClipboardContext=true;
if(state.selectedFolder) openOn(other,state.selected,true,{});
else revealLocalFile(other,state.selected);
}
+236
View File
@@ -0,0 +1,236 @@
void finishSpaceSelection(HWND dialog,SpaceAnalyzer &state,size_t selected,int action)
{
if(selected>=state.nodes.size()) return;
const auto &node=state.nodes[selected];
if(action==spaceView && node.folder) return;
state.selected=node.path;
state.selectedFolder=node.folder;
FilesModalDialog::finish(dialog,action);
}
void divideSpaceTiles(std::span<const size_t> nodes,std::span<const long double> prefix,RECT bounds,
LONG margin,std::vector<SpaceTile> &tiles)
{
const auto width=bounds.right-bounds.left, height=bounds.bottom-bounds.top;
if(width<margin || height<margin || nodes.empty()) return;
if(nodes.size()==1)
{
tiles.push_back({bounds,nodes.front()});
return;
}
const auto total=prefix.back()-prefix.front();
if(total<=0) return;
const auto middle=prefix.front()+total/2;
auto pivot=std::lower_bound(prefix.begin()+1,prefix.end()-1,middle);
if(pivot==prefix.end()-1 ||
(pivot>prefix.begin()+1 && middle-pivot[-1]<*pivot-middle)) --pivot;
const auto offset=static_cast<size_t>(pivot-prefix.begin());
const auto share=(*pivot-prefix.front())/total;
auto first=bounds, second=bounds;
if(width>=height)
{
const auto split=bounds.left+std::clamp(static_cast<LONG>(width*share+0.5L),1L,width-1);
first.right=second.left=split;
}
else
{
const auto split=bounds.top+std::clamp(static_cast<LONG>(height*share+0.5L),1L,height-1);
first.bottom=second.top=split;
}
divideSpaceTiles(nodes.first(offset),prefix.first(offset+1),first,margin,tiles);
divideSpaceTiles(nodes.subspan(offset),prefix.subspan(offset),second,margin,tiles);
}
void layoutSpaceMap(HWND map,SpaceAnalyzer &state)
{
state.lastMapUpdate=GetTickCount64();
const auto previous=state.selectedTile<state.tiles.size()?
state.tiles[state.selectedTile].node:std::numeric_limits<size_t>::max();
state.tiles.clear();
state.selectedTile=0;
if(state.mapFolder>=state.nodes.size()) return;
std::vector<size_t> items;
for(auto index:state.nodes[state.mapFolder].children)
if(state.nodes[index].size.bytes) items.push_back(index);
std::sort(items.begin(),items.end(),[&](size_t left,size_t right) {
const auto a=state.nodes[left].size.bytes, b=state.nodes[right].size.bytes;
return a!=b?a>b:left<right;
});
std::vector<long double> prefix{0};
prefix.reserve(items.size()+1);
for(auto index:items) prefix.push_back(prefix.back()+state.nodes[index].size.bytes);
RECT bounds{};
GetClientRect(map,&bounds);
const auto minimum=std::max(4,MulDiv(8,GetDpiForWindow(map),96));
divideSpaceTiles(items,prefix,bounds,minimum,state.tiles);
for(size_t index=0;index<state.tiles.size();++index)
if(state.tiles[index].node==previous)
{
state.selectedTile=index;
break;
}
InvalidateRect(map,nullptr,FALSE);
}
constexpr COLORREF spaceChartColors[]{RGB(158,203,218),RGB(167,205,172),RGB(230,198,142),
RGB(197,179,211),RGB(226,178,173),RGB(177,190,225)};
void paintEmptySpaceChart(const DRAWITEMSTRUCT &paint)
{
auto bounds=paint.rcItem;
SelectObject(paint.hDC,mono);
SetBkMode(paint.hDC,TRANSPARENT);
SetTextColor(paint.hDC,RGB(15,27,35));
DrawTextW(paint.hDC,L"No measured space to display",-1,&bounds,DT_CENTER|DT_VCENTER|DT_SINGLELINE);
}
void paintSpaceMap(const DRAWITEMSTRUCT &paint,const SpaceAnalyzer &state)
{
FillRect(paint.hDC,&paint.rcItem,GetSysColorBrush(COLOR_WINDOW));
SelectObject(paint.hDC,mono);
SetBkMode(paint.hDC,TRANSPARENT);
SetTextColor(paint.hDC,RGB(15,27,35));
if(state.tiles.empty())
{
paintEmptySpaceChart(paint);
return;
}
const auto brush=static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
const auto focused=GetFocus()==paint.hwndItem;
for(size_t index=0;index<state.tiles.size();++index)
{
const auto &tile=state.tiles[index];
if(!RectVisible(paint.hDC,&tile.box)) continue;
const auto &node=state.nodes[tile.node];
auto bounds=tile.box;
SetDCBrushColor(paint.hDC,spaceChartColors[index%std::size(spaceChartColors)]);
FillRect(paint.hDC,&bounds,brush);
FrameRect(paint.hDC,&bounds,GetSysColorBrush(COLOR_WINDOW));
if(focused && index==state.selectedTile)
{
InflateRect(&bounds,-2,-2);
DrawFocusRect(paint.hDC,&bounds);
bounds=tile.box;
}
InflateRect(&bounds,-std::max(3,cellWidth/2),-2);
if(bounds.right-bounds.left>=3*cellWidth && bounds.bottom-bounds.top>=textHeight)
{
const auto name=node.path.filename().native();
DrawTextW(paint.hDC,name.c_str(),-1,&bounds,DT_SINGLELINE|DT_NOPREFIX|DT_END_ELLIPSIS);
bounds.top+=textHeight;
if(bounds.bottom-bounds.top>=textHeight)
{
const auto logical=spaceLogicalSize(node);
DrawTextW(paint.hDC,logical.c_str(),-1,&bounds,DT_SINGLELINE|DT_NOPREFIX|DT_END_ELLIPSIS);
bounds.top+=textHeight;
if(bounds.bottom-bounds.top>=textHeight)
{
const auto allocated=spaceAllocatedSize(node);
DrawTextW(paint.hDC,allocated.c_str(),-1,&bounds,DT_SINGLELINE|DT_NOPREFIX|DT_END_ELLIPSIS);
}
}
}
}
}
#include "files_space_sunburst.inl"
void refreshSpaceChart(HWND map,SpaceAnalyzer &state)
{
if(state.display==SpaceDisplay::sunburst) layoutSunburst(map,state);
else layoutSpaceMap(map,state);
}
LRESULT CALLBACK spaceSunburstListKeys(HWND list,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR payload)
{
auto &state=*reinterpret_cast<SpaceAnalyzer *>(payload);
if(message==WM_GETDLGCODE && lp && wp==VK_RETURN)
return DefSubclassProc(list,message,wp,lp)|DLGC_WANTMESSAGE;
if(message==WM_KEYDOWN && wp==VK_RETURN)
{
const auto dialog=GetParent(list);
if(const auto selected=sunburstSelection(dialog,state)) finishSpaceSelection(dialog,state,*selected,IDOK);
return 0;
}
return DefSubclassProc(list,message,wp,lp);
}
LRESULT CALLBACK spaceMapInput(HWND map,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR payload)
{
auto &state=*reinterpret_cast<SpaceAnalyzer *>(payload);
if(message==WM_SIZE && state.display!=SpaceDisplay::tree) refreshSpaceChart(map,state);
if(message==WM_SETFOCUS || message==WM_KILLFOCUS) InvalidateRect(map,nullptr,FALSE);
if(message==WM_LBUTTONDOWN)
{
SetFocus(map);
return 0;
}
if(message==WM_LBUTTONUP)
{
const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
if(state.display==SpaceDisplay::sunburst)
{
if(const auto hit=hitSunburst(map,state,point))
finishSpaceSelection(GetParent(map),state,state.sectors[*hit].node,IDOK);
return 0;
}
for(const auto &tile:state.tiles)
if(PtInRect(&tile.box,point))
{
finishSpaceSelection(GetParent(map),state,tile.node,IDOK);
break;
}
return 0;
}
if(message==WM_GETDLGCODE)
{
const auto *key=reinterpret_cast<const MSG *>(lp);
return DLGC_WANTARROWS|(key && key->message==WM_KEYDOWN && wp==VK_RETURN?DLGC_WANTMESSAGE:0);
}
if(message==WM_KEYDOWN && state.display==SpaceDisplay::treemap && !state.tiles.empty())
{
if(wp==VK_RETURN)
{
finishSpaceSelection(GetParent(map),state,state.tiles[state.selectedTile].node,IDOK);
return 0;
}
if(wp==VK_DOWN || wp==VK_RIGHT || wp==VK_UP || wp==VK_LEFT)
{
auto &index=state.selectedTile;
if(wp==VK_DOWN || wp==VK_RIGHT) index=(index+1)%state.tiles.size();
else index=index?index-1:state.tiles.size()-1;
InvalidateRect(map,nullptr,FALSE);
return 0;
}
}
return DefSubclassProc(map,message,wp,lp);
}
void setSpaceDisplay(HWND dialog,SpaceAnalyzer &state,SpaceDisplay display)
{
const auto tree=GetDlgItem(dialog,spaceTree), map=GetDlgItem(dialog,spaceMap);
const auto list=GetDlgItem(dialog,spaceSunburstList);
const bool showTree=display==SpaceDisplay::tree, showSunburst=display==SpaceDisplay::sunburst;
const auto selection=selectedSpaceNode(tree,state);
if(state.display==SpaceDisplay::tree && !showTree)
{
const auto index=selection.value_or(0);
const auto &node=state.nodes[index];
state.mapFolder=node.folder && !node.link?index:node.parent;
}
state.display=display;
SetDlgItemTextW(dialog,spaceMapButton,display==SpaceDisplay::treemap?L"Tr&ee":L"Tree&map");
SetDlgItemTextW(dialog,spaceSunburstButton,showSunburst?L"Tr&ee":L"S&unburst");
layoutSpaceAnalyzer(dialog);
ShowWindow(tree,showTree?SW_SHOW:SW_HIDE);
ShowWindow(map,showTree?SW_HIDE:SW_SHOW);
ShowWindow(GetDlgItem(dialog,spaceSunburstLabel),showSunburst?SW_SHOW:SW_HIDE);
ShowWindow(list,showSunburst?SW_SHOW:SW_HIDE);
if(!showSunburst)
{
EnableWindow(GetDlgItem(dialog,spaceView),showTree && selection && !state.nodes[*selection].folder);
EnableWindow(GetDlgItem(dialog,IDOK),showTree && selection.has_value());
}
if(!showTree) refreshSpaceChart(map,state);
SetFocus(showTree?tree:showSunburst?list:map);
}
+149
View File
@@ -0,0 +1,149 @@
constexpr double fullCircle=2*std::numbers::pi_v<double>;
constexpr unsigned sunburstRings=3;
double sunburstRingWidth(const RECT &bounds)
{
return std::max(0L,std::min(bounds.right-bounds.left,bounds.bottom-bounds.top)-4)/
(2.0*(sunburstRings+0.5));
}
void addSunburstRing(SpaceAnalyzer &state,size_t folder,unsigned ring,double start,double end)
{
if(ring>=sunburstRings || end-start<0.02) return;
const auto &parent=state.nodes[folder];
double total=0;
for(auto index:parent.children) total+=static_cast<double>(state.nodes[index].size.bytes);
if(total<=0) return;
const auto span=end-start;
auto cursor=start;
for(auto index:parent.children)
{
const auto &item=state.nodes[index];
if(!item.size.bytes) continue;
const auto next=std::min(end,cursor+span*static_cast<double>(item.size.bytes)/total);
if(next-cursor>=0.02)
{
state.sectors.push_back({index,ring,cursor,next});
if(item.folder) addSunburstRing(state,index,ring+1,cursor,next);
}
cursor=next;
}
}
std::optional<size_t> sunburstSelectedSector(HWND dialog,const SpaceAnalyzer &state)
{
const auto row=SendDlgItemMessageW(dialog,spaceSunburstList,LB_GETCURSEL,0,0);
if(row==LB_ERR) return {};
const auto sector=SendDlgItemMessageW(dialog,spaceSunburstList,LB_GETITEMDATA,row,0);
if(sector==LB_ERR || static_cast<size_t>(sector)>=state.sectors.size()) return {};
return static_cast<size_t>(sector);
}
std::optional<size_t> sunburstSelection(HWND dialog,const SpaceAnalyzer &state)
{
const auto sector=sunburstSelectedSector(dialog,state);
return sector?std::optional<size_t>(state.sectors[*sector].node):std::nullopt;
}
void updateSunburstSelection(HWND dialog,SpaceAnalyzer &state)
{
state.selectedTile=sunburstSelectedSector(dialog,state).value_or(state.sectors.size());
const auto selected=sunburstSelection(dialog,state);
EnableWindow(GetDlgItem(dialog,spaceView),selected && !state.nodes[*selected].folder);
EnableWindow(GetDlgItem(dialog,IDOK),selected.has_value());
InvalidateRect(GetDlgItem(dialog,spaceMap),nullptr,FALSE);
}
void layoutSunburst(HWND map,SpaceAnalyzer &state)
{
const auto dialog=GetParent(map);
const auto list=GetDlgItem(dialog,spaceSunburstList);
const auto selected=sunburstSelection(dialog,state);
state.lastMapUpdate=GetTickCount64();
state.sectors.clear();
state.selectedTile=0;
if(state.mapFolder<state.nodes.size())
addSunburstRing(state,state.mapFolder,0,0,fullCircle);
SendMessageW(list,WM_SETREDRAW,FALSE,0);
SendMessageW(list,LB_RESETCONTENT,0,0);
SendMessageW(list,LB_INITSTORAGE,state.sectors.size(),0);
LRESULT selection=0;
size_t longest=0;
for(size_t i=0;i<state.sectors.size();++i)
{
const auto &sector=state.sectors[i];
const auto &node=state.nodes[sector.node];
const auto &root=state.nodes[state.mapFolder];
const auto name=node.path.lexically_relative(root.path).native();
const auto line=name+L" — "+spaceLogicalSize(node);
const auto row=SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(line.c_str()));
if(row>=0)
{
SendMessageW(list,LB_SETITEMDATA,row,i);
if(selected==sector.node) selection=row;
longest=std::max(longest,line.size());
}
}
SendMessageW(list,LB_SETHORIZONTALEXTENT,(longest+1)*cellWidth,0);
if(!state.sectors.empty()) SendMessageW(list,LB_SETCURSEL,selection,0);
SendMessageW(list,WM_SETREDRAW,TRUE,0);
InvalidateRect(list,nullptr,FALSE);
updateSunburstSelection(dialog,state);
}
std::optional<size_t> hitSunburst(HWND map,const SpaceAnalyzer &state,POINT point)
{
RECT bounds{};
GetClientRect(map,&bounds);
const auto width=sunburstRingWidth(bounds);
if(width<=0) return {};
const auto x=point.x-(bounds.left+bounds.right)/2.0;
const auto y=point.y-(bounds.top+bounds.bottom)/2.0;
const auto radius=std::hypot(x,y)/width-0.5;
if(radius<0 || radius>=sunburstRings) return {};
const auto ring=static_cast<unsigned>(radius);
auto angle=std::atan2(x,-y);
if(angle<0) angle+=fullCircle;
for(size_t i=0;i<state.sectors.size();++i)
{
const auto &sector=state.sectors[i];
if(sector.ring==ring && angle>=sector.start && angle<sector.end) return i;
}
return {};
}
void paintSunburst(const DRAWITEMSTRUCT &paint,const SpaceAnalyzer &state)
{
auto bounds=paint.rcItem;
FillRect(paint.hDC,&bounds,GetSysColorBrush(COLOR_WINDOW));
if(state.sectors.empty())
{
paintEmptySpaceChart(paint);
return;
}
const auto width=sunburstRingWidth(bounds);
const auto x=(bounds.left+bounds.right)/2.0, y=(bounds.top+bounds.bottom)/2.0;
const auto point=[&](double angle,double radius) {
return POINT{std::lround(x+radius*std::sin(angle)),std::lround(y-radius*std::cos(angle))};
};
const auto oldBrush=SelectObject(paint.hDC,GetStockObject(DC_BRUSH));
const auto oldPen=SelectObject(paint.hDC,GetStockObject(DC_PEN));
for(size_t i=0;i<state.sectors.size();++i)
{
const auto &sector=state.sectors[i];
const auto segments=std::clamp(static_cast<int>((sector.end-sector.start)*26),2,164);
const auto inner=(sector.ring+0.5)*width, outer=inner+width;
std::array<POINT,330> points;
for(int segment=0;segment<=segments;++segment)
{
const auto angle=sector.start+(sector.end-sector.start)*segment/segments;
points[segment]=point(angle,outer);
points[2*segments+1-segment]=point(angle,inner);
}
SetDCPenColor(paint.hDC,i==state.selectedTile?RGB(35,48,62):RGB(255,255,255));
SetDCBrushColor(paint.hDC,spaceChartColors[i%std::size(spaceChartColors)]);
Polygon(paint.hDC,points.data(),2*(segments+1));
}
SelectObject(paint.hDC,oldPen);
SelectObject(paint.hDC,oldBrush);
}
+199 -46
View File
@@ -740,13 +740,13 @@ class TextWindow
{
public:
TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const RemoteTextSource *backend,
std::string_view fragment,TextOpenOptions options)
std::string_view fragment,TextOpenOptions options,bool quickView=false)
: original(std::move(path)), peerId(backend?backend->id:""), filename(original.filename().wstring()),
edit(editable), draft(options.draft), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
edit(editable), draft(options.draft), embedded(quickView), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
search{dialogs}, previewFragment(fragment)
{
if (backend) remote=std::make_unique<RemoteTextFile>(*backend,original);
else document=std::make_unique<TextDocument>(draft?std::filesystem::path{}:original,edit,options.encoding);
else if(!embedded) document=std::make_unique<TextDocument>(draft?std::filesystem::path{}:original,edit,options.encoding);
if(options.encoding!=TextEncoding::automatic)
{
newFormat.encoding=options.encoding;
@@ -772,6 +772,7 @@ public:
HWND window{}, editor{};
bool handleKey(const MSG &message);
void goToFragment(std::string_view fragment);
void previewFile(const std::filesystem::path &path);
std::filesystem::path original;
const std::string peerId;
@@ -780,7 +781,7 @@ private:
std::unique_ptr<TextDocument> document;
std::wstring filename;
bool edit{}, loading{}, stagedDirty{}, closeAfterSave{}, insertRejected{};
bool draft{};
bool draft{}, embedded{};
TextSaveFormat newFormat;
std::filesystem::path pendingSavePath;
HICON smallIcon{},largeIcon{};
@@ -862,6 +863,20 @@ private:
static constexpr UINT_PTR openTimer = 2;
static constexpr UINT_PTR previewTimer = 3;
static constexpr UINT_PTR navigationTimer = 4;
static constexpr UINT_PTR quickViewTimer = 5;
struct QuickDocument
{
std::unique_ptr<TextDocument> document;
std::string firstPage;
std::optional<std::string> markdown;
};
std::future<QuickDocument> quickLoading;
std::filesystem::path quickPath;
uint64_t quickRequest{}, quickReading{};
ULONGLONG quickReadyAt{};
std::wstring quickError;
std::optional<std::string> quickMarkdown;
void pollQuickView();
static constexpr UINT trimUndo = WM_APP + 1;
static constexpr UINT previewFailed = WM_APP + 2;
static constexpr UINT openPreviewLink = WM_APP + 3;
@@ -890,7 +905,7 @@ private:
void invalidateStatus() const;
void invalidateHints() const;
void initializeDocument();
void initializeDocument(std::optional<std::string> firstPage={});
void finishOpen();
void createMenu();
void releaseMenu();
@@ -906,7 +921,7 @@ private:
void updateLineNumberMargin();
void applyLineEnding();
void installLexer();
void loadPage(uint64_t index);
void loadPage(uint64_t index,std::optional<std::string> cached={});
void stagePage();
void go(uint64_t index);
void saveFile(bool closeWhenDone);
@@ -1206,7 +1221,7 @@ void TextWindow::reloadPreferences()
if (!fontChanged && profile == prefs) return;
prefs = std::move(profile);
filesFont = font;
if (fontChanged)
if (fontChanged && !embedded)
{
releaseMenu();
createMenu();
@@ -1294,9 +1309,9 @@ void TextWindow::applyLineEnding()
send(SCI_SETEOLMODE, choices[prefs.lineEnding]);
}
void TextWindow::loadPage(uint64_t index)
void TextWindow::loadPage(uint64_t index,std::optional<std::string> cached)
{
auto data = document->readPage(index);
auto data=cached?std::move(*cached):document->readPage(index);
const auto offset = document->boundary(index);
page = index;
pageOffset = offset;
@@ -1344,19 +1359,99 @@ void TextWindow::go(uint64_t index)
loadPage(index);
}
void TextWindow::initializeDocument()
void TextWindow::initializeDocument(std::optional<std::string> firstPage)
{
automatic=detectLanguage(original,document->readPage(0));
if(!firstPage) firstPage=document->readPage(0);
automatic=detectLanguage(original,*firstPage);
language=automatic;
if(canPreview()) ShowWindow(editor,SW_HIDE);
releaseMenu();
createMenu();
if(!embedded)
{
releaseMenu();
createMenu();
if(navigationHistory.empty()) navigationHistory.push_back({original,previewFragment});
}
installLexer();
loadPage(0);
if(navigationHistory.empty()) navigationHistory.push_back({original,previewFragment});
loadPage(0,std::move(firstPage));
updatePreview();
}
std::string readMarkdownDocument(TextDocument &document)
{
std::string text;
for(uint64_t index=0;index<document.pages();++index) text+=document.readPage(index);
return text;
}
void TextWindow::previewFile(const std::filesystem::path &path)
{
if(path==quickPath) return;
quickPath=path;
++quickRequest;
quickReadyAt=GetTickCount64()+80;
stopPreview(false,true);
document.reset();
quickMarkdown.reset();
quickError.clear();
layout();
SetTimer(window,quickViewTimer,30,nullptr);
}
void TextWindow::pollQuickView()
{
if(quickLoading.valid())
{
if(quickLoading.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
const bool current=quickRequest==quickReading;
try
{
auto loaded=quickLoading.get();
if(current)
{
original=quickPath;
filename=original.filename().wstring();
document=std::move(loaded.document);
quickMarkdown=std::move(loaded.markdown);
initializeDocument(std::move(loaded.firstPage));
}
}
catch(const std::exception &error)
{
if(current)
{
quickError=wide(error.what());
document.reset();
layout();
}
}
if(current)
{
KillTimer(window,quickViewTimer);
return;
}
}
if(quickPath.empty())
{
KillTimer(window,quickViewTimer);
return;
}
if(GetTickCount64()<quickReadyAt) return;
quickReading=quickRequest;
std::packaged_task<QuickDocument()> task([path=quickPath] {
auto source=std::make_unique<TextDocument>(path,false);
auto first=source->readPage(0);
if(first.find('\0')!=std::string::npos)
throw std::runtime_error("Binary preview is unavailable.");
std::optional<std::string> markdown;
if(source->size()<=TextDocument::editLimit && detectLanguage(path,first).lexer=="markdown")
markdown=readMarkdownDocument(*source);
source->releaseReadHandle();
return QuickDocument{std::move(source),std::move(first),std::move(markdown)};
});
quickLoading=task.get_future();
std::thread(std::move(task)).detach();
}
void TextWindow::finishOpen()
{
if(!opening.valid() || opening.wait_for(std::chrono::milliseconds(0))!=std::future_status::ready) return;
@@ -1602,6 +1697,12 @@ bool TextWindow::startPreviewBrowser()
{
const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0;
const bool alt=(GetKeyState(VK_MENU)&0x8000)!=0;
if(embedded)
{
if(!ctrl || alt || key!='Q') return false;
PostMessageW(GetParent(window),quickViewToggleMessage,0,0);
return true;
}
if(!alt && ((ctrl && key=='F') || key==VK_F3))
{
const bool shift=(GetKeyState(VK_SHIFT)&0x8000)!=0;
@@ -1684,12 +1785,10 @@ void TextWindow::renderPreview(bool keepPosition)
{
applyMarkdownPreferences(loadTextPreferences().markdown);
previewDeadline=GetTickCount64()+30000;
previewText.clear();
for(uint64_t index=0;index<document->pages();++index)
previewText+=document->readPage(index);
previewText=quickMarkdown?*quickMarkdown:readMarkdownDocument(*document);
if(!remote) document->releaseReadHandle();
nlohmann::json message{{"action","render"},{"text",previewText},{"revision",++previewRevision},
{"canSave",!remote || remote->revision.editable},
{"canSave",!embedded && (!remote || remote->revision.editable)},{"compact",embedded},
{"fragment",std::exchange(previewFragment,{})},{"title",utf8(filename)},
{"keepPosition",keepPosition}};
if(restoreScroll) message["scroll"]=navigationHistory[navigationIndex].scroll;
@@ -1706,7 +1805,7 @@ void TextWindow::applyMarkdownPreferences(const MarkdownPreferences &preferences
void TextWindow::refreshPreview()
{
if(remote || !previewVisible || navigation.valid() || busy() || pendingTask || GetTickCount64()<nextFileCheck) return;
if(embedded || remote || !previewVisible || navigation.valid() || busy() || pendingTask || GetTickCount64()<nextFileCheck) return;
nextFileCheck=GetTickCount64()+350;
const auto stamp=previewFileStamp();
if(!stamp || stamp==previewStamp) return;
@@ -1862,14 +1961,17 @@ void TextWindow::previewMessage(const std::wstring &value)
PostMessageW(window,cycleWindow,message.value("reverse",false),0);
return;
}
if(embedded && action!="image" && action!="rendered" && action!="failed") return;
const auto revision=message.value("revision",previewRevision);
if(embedded && revision!=previewRevision) return;
if(action=="failed")
{
PostMessageW(window,previewFailed,0,0);
PostMessageW(window,previewFailed,static_cast<WPARAM>(revision),0);
return;
}
if(action=="rendered")
{
PostMessageW(window,previewRendered,0,0);
PostMessageW(window,previewRendered,static_cast<WPARAM>(revision),0);
return;
}
if(action=="save-task")
@@ -2054,8 +2156,10 @@ void TextWindow::layout()
RECT area{};
GetClientRect(window, &area);
const auto row = chromeHeight();
MoveWindow(editor, 0, 2 * row, area.right, std::max(0L, area.bottom - 3 * row), TRUE);
preview.layout({0,2*row,area.right,std::max<LONG>(2*row,area.bottom-row)},previewWanted);
const int top=embedded?row:2*row;
const LONG bottom=std::max<LONG>(top,area.bottom-(embedded?0:row));
MoveWindow(editor,0,top,area.right,bottom-top,TRUE);
preview.layout({0,top,area.right,bottom},previewWanted && (!embedded || previewVisible));
ShowWindow(editor,document && !previewWanted?SW_SHOWNA:SW_HIDE);
invalidate();
}
@@ -2121,6 +2225,24 @@ void TextWindow::paint()
const auto row = chromeHeight();
const auto brush = static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
SetDCBrushColor(dc, color(TextColor::background));
if(embedded)
{
FillRect(dc,&client,brush);
auto font=filesFont.font;
font.lfHeight=-MulDiv(filesFont.tenthsOfPoint,GetDpiForWindow(window),720);
const auto chromeFont=CreateFontIndirectW(&font);
std::wstring label=L"Quick View";
if(!quickPath.empty()) label+=L" · "+quickPath.filename().native();
if(!quickError.empty()) label+=L" · "+quickError;
else if(quickPath.empty()) label+=L" · Select a local text file";
else if(!document || (previewWanted && !previewVisible)) label+=L" · Loading…";
else if(!previewVisible && pageTotal>1) label+=L" · First page";
drawEditorStatus(dc,{0,0,client.right,row},chromeFont,color(TextColor::chromebg),
color(TextColor::chrome),scale(6),label);
if(chromeFont) DeleteObject(chromeFont);
EndPaint(window,&paint);
return;
}
const RECT body{0,2*row,client.right,std::max<LONG>(2*row,client.bottom-row)};
FillRect(dc, &body, brush);
SetDCBrushColor(dc, color(TextColor::chromebg));
@@ -2339,6 +2461,7 @@ void TextWindow::notify(const SCNotification &notice)
bool TextWindow::handleKey(const MSG &message)
{
if(embedded) return false;
const auto key = message.wParam;
if (message.hwnd != editor) return false;
if (message.message == WM_SYSKEYDOWN && (message.lParam & (1LL << 29)))
@@ -2387,7 +2510,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
const auto &state=*static_cast<const std::shared_ptr<TextWindow> *>(create->lpCreateParams);
state->window=window;
textWindows.emplace(window,state);
textWindowOrder.push_back(window);
if(!state->embedded) textWindowOrder.push_back(window);
}
const auto found=textWindows.find(window);
if(found==textWindows.end()) return DefWindowProcW(window,message,wparam,lparam);
@@ -2428,7 +2551,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
MSG key{child,msg,wp,lp};
if(state->handleKey(key)) return 0;
}
if(msg==WM_XBUTTONUP && !state->edit)
if(msg==WM_XBUTTONUP && !state->edit && !state->embedded)
{
SendMessageW(state->window,WM_COMMAND,
GET_XBUTTON_WPARAM(wp)==XBUTTON1?historyBack:historyForward,0);
@@ -2447,9 +2570,13 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
state->remote->download(state->edit,[state](uint64_t,uint64_t){return !state->cancelOpen;});
});
}
else if(self->embedded) self->applyPreferences();
else self->initializeDocument();
self->updateIcons(GetDpiForWindow(window));
self->updateTaskbarGroup();
if(!self->embedded)
{
self->updateIcons(GetDpiForWindow(window));
self->updateTaskbarGroup();
}
self->layout();
return 0;
case WM_ERASEBKGND: return 1;
@@ -2465,10 +2592,10 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
self->layout();
return 0;
}
case WM_SETFOCUS: self->focusContent(); return 0;
case WM_SETFOCUS: if(!self->embedded) self->focusContent(); return 0;
case cycleWindow: cycleTextWindows(window,wparam!=0); return 0;
case WM_KEYDOWN:
if(self->previewWanted && !self->previewVisible)
if(!self->embedded && self->previewWanted && !self->previewVisible)
{
if(wparam==VK_F6) self->toggleMode();
if(wparam==VK_ESCAPE || wparam==VK_F10 ||
@@ -2476,13 +2603,15 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
return 0;
}
break;
case previewFailed: self->stopPreview(); return 0;
case previewFailed:
if(!self->embedded || !wparam || wparam==self->previewRevision) self->stopPreview();
return 0;
case savePreviewTask: self->startMarkdownTask(); return 0;
case previewRendered:
if(self->previewWanted)
if(self->previewWanted && (!self->embedded || wparam==self->previewRevision))
{
self->previewVisible=true;
self->syncNavigation();
if(!self->embedded) self->syncNavigation();
self->layout();
if(GetForegroundWindow()==window) self->focusContent();
}
@@ -2511,6 +2640,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
return 0;
}
case WM_COMMAND:
if(self->embedded) return 0;
if (LOWORD(wparam) >= 600 && LOWORD(wparam) < 605) self->openMenu(LOWORD(wparam) - 600);
else self->command(LOWORD(wparam));
return 0;
@@ -2526,6 +2656,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
if (wparam == openTimer) self->finishOpen();
if (wparam == previewTimer) self->pollImages();
if (wparam == navigationTimer) self->finishNavigation();
if (wparam == quickViewTimer) self->pollQuickView();
return 0;
case trimUndo:
if (self->undoBytes >= 32 * TextDocument::pageBytes)
@@ -2538,7 +2669,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
return 0;
case WM_DESTROY:
if(self->cancelNavigation) *self->cancelNavigation=true;
self->updateTaskbarGroup(true);
if(!self->embedded) self->updateTaskbarGroup(true);
self->stopPreview(false);
self->releaseMenu();
return 0;
@@ -2552,7 +2683,8 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
}
catch (const std::exception &error)
{
self->search.style.message(window, wide(error.what()).c_str());
if(self->embedded) self->quickError=wide(error.what());
else self->search.style.message(window, wide(error.what()).c_str());
self->invalidate();
return message == WM_CREATE ? -1 : 0;
}
@@ -2711,6 +2843,37 @@ HWND findOpenDocument(const std::filesystem::path &path,std::string_view id)
return search.match;
}
bool registerTextWindowClass(HINSTANCE instance)
{
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);
}();
return registered;
}
HWND createQuickView(HWND owner,TextDialogs dialogs)
{
const auto instance=GetModuleHandleW(nullptr);
if(!registerTextWindowClass(instance)) return nullptr;
auto state=std::make_shared<TextWindow>(std::filesystem::path{},false,dialogs,nullptr,
std::string_view{},TextOpenOptions{},true);
return CreateWindowExW(0,windowClass,L"Quick View",WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS,
0,0,0,0,owner,reinterpret_cast<HMENU>(158),instance,&state);
}
void previewQuickViewFile(HWND window,const std::filesystem::path &path)
{
if(const auto preview=textWindows.find(window);preview!=textWindows.end())
preview->second->previewFile(path);
}
static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const RemoteTextSource *backend,std::string_view fragment,bool newWindow,TextOpenOptions options)
{
@@ -2733,17 +2896,7 @@ static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool
}
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.");
if(!registerTextWindowClass(instance)) throw std::runtime_error("Cannot register the text window.");
auto state=std::make_shared<TextWindow>(original,edit,dialogs,backend,fragment,options);
const auto title=std::wstring(edit?L"Editor — ":L"Viewer — ")+
(backend?backend->name+L" · ":std::wstring{})+path.wstring();
+4
View File
@@ -80,6 +80,10 @@ struct RemoteTextSource
const RemoteTextRevision &)> upload;
};
inline constexpr UINT quickViewToggleMessage=WM_APP+31;
HWND createQuickView(HWND owner,TextDialogs dialogs);
void previewQuickViewFile(HWND window,const std::filesystem::path &path);
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false,
TextOpenOptions options={});
+42
View File
@@ -0,0 +1,42 @@
#pragma once
#include <windows.h>
#include <array>
#include <cstddef>
#include <string_view>
namespace ks::files
{
template<class Visitor>
DWORD visitDirectoryRecords(HANDLE directory,const Visitor &visit)
{
alignas(FILE_ID_BOTH_DIR_INFO) std::array<unsigned char,64*1024> buffer;
constexpr auto header=offsetof(FILE_ID_BOTH_DIR_INFO,FileName);
while(GetFileInformationByHandleEx(directory,FileIdBothDirectoryInfo,buffer.data(),
static_cast<DWORD>(buffer.size())))
{
for(size_t offset=0;;)
{
const auto remaining=buffer.size()-offset;
if(remaining<header) return ERROR_INVALID_DATA;
const auto &entry=*reinterpret_cast<const FILE_ID_BOTH_DIR_INFO *>(buffer.data()+offset);
const auto size=entry.NextEntryOffset?entry.NextEntryOffset:remaining;
if(size>remaining || size<header || entry.FileNameLength>size-header ||
entry.FileNameLength%sizeof(wchar_t)) return ERROR_INVALID_DATA;
const std::wstring_view name(entry.FileName,entry.FileNameLength/sizeof(wchar_t));
if(name.empty() || name.find_first_of(L"/\\:")!=name.npos || name.find(L'\0')!=name.npos)
return ERROR_INVALID_DATA;
if(name!=L"." && name!=L"..")
{
const auto result=visit(entry,name);
if(result!=ERROR_SUCCESS) return result;
}
if(!entry.NextEntryOffset) break;
if(size%alignof(FILE_ID_BOTH_DIR_INFO)) return ERROR_INVALID_DATA;
offset+=size;
}
}
const auto error=GetLastError();
return error==ERROR_NO_MORE_FILES?ERROR_SUCCESS:error;
}
}
+71
View File
@@ -486,6 +486,77 @@ Clip textClip(const std::wstring &text)
memcpy(f.data.data(), text.c_str(), f.data.size());
return Clip{{std::move(f)}};
}
Clip fileDropClip(std::span<const std::filesystem::path> paths)
{
std::wstring names;
for(const auto &path:paths)
{
if(!path.is_absolute() || path.native().find(L'\0')!=std::wstring::npos)
throw std::invalid_argument("A file clipboard path must be absolute and contain no nulls.");
names+=path.native();
names+=L'\0';
}
if(paths.empty()) names+=L'\0';
names+=L'\0';
DROPFILES header{};
header.pFiles=sizeof(header);
header.fWide=TRUE;
Format files{CF_HDROP,{},Bytes(sizeof(header)+names.size()*sizeof(wchar_t))};
memcpy(files.data.data(),&header,sizeof(header));
memcpy(files.data.data()+sizeof(header),names.data(),names.size()*sizeof(wchar_t));
const DWORD effect=DROPEFFECT_COPY;
Format preferred{0,CFSTR_PREFERREDDROPEFFECT,Bytes(sizeof(effect))};
memcpy(preferred.data.data(),&effect,sizeof(effect));
return Clip{{std::move(files),std::move(preferred)}};
}
std::vector<std::filesystem::path> fileDropPaths(HANDLE medium)
{
const auto size=medium?GlobalSize(medium):0;
if(size<sizeof(DROPFILES)) return {};
const auto bytes=static_cast<const unsigned char *>(GlobalLock(medium));
if(!bytes) return {};
DROPFILES header{};
memcpy(&header,bytes,sizeof(header));
bool terminated=false;
if(header.pFiles>=sizeof(header) && header.pFiles<size)
{
const auto start=bytes+header.pFiles;
if(!header.fWide)
terminated=std::search_n(start,bytes+size,2,static_cast<unsigned char>(0))!=bytes+size;
else if(header.pFiles%alignof(wchar_t)==0)
{
const auto names=reinterpret_cast<const wchar_t *>(start);
const auto end=names+(size-header.pFiles)/sizeof(wchar_t);
terminated=std::search_n(names,end,2,L'\0')!=end;
}
}
GlobalUnlock(medium);
if(!terminated) return {};
const auto drop=reinterpret_cast<HDROP>(medium);
const UINT count=DragQueryFileW(drop,UINT(-1),nullptr,0);
std::vector<std::filesystem::path> paths;
std::set<std::filesystem::path> seen;
for(UINT index=0;index<count;++index)
{
const UINT length=DragQueryFileW(drop,index,nullptr,0);
if(!length || length>32767) continue;
std::wstring name(length+1,L'\0');
if(DragQueryFileW(drop,index,name.data(),length+1)!=length) continue;
name.resize(length);
auto path=std::filesystem::path(std::move(name)).lexically_normal();
if(path.is_absolute() && seen.insert(path).second) paths.push_back(std::move(path));
}
return paths;
}
std::vector<std::filesystem::path> readClipboardFilePaths(HWND window)
{
ClipboardLock lock(window);
return fileDropPaths(GetClipboardData(CF_HDROP));
}
std::wstring Clip::text() const
{
for (const auto &f : formats)
+3
View File
@@ -59,6 +59,9 @@ Clip readClipboard(HWND, size_t limit = 32 * 1024 * 1024,
DWORD writeClipboard(HWND, const Clip &);
DWORD writeClipboardGuarded(HWND, const Clip &, std::optional<DWORD> expected);
Clip textClip(const std::wstring &);
Clip fileDropClip(std::span<const std::filesystem::path> paths);
std::vector<std::filesystem::path> fileDropPaths(HANDLE medium);
std::vector<std::filesystem::path> readClipboardFilePaths(HWND window);
bool chord(WORD key, UINT modifiers = 0);
bool chord(std::span<const WORD> keys);
struct SystemVolume
+65
View File
@@ -0,0 +1,65 @@
Add-Type @'
using System;
using System.Text;
using System.Runtime.InteropServices;
public static class FilesCommandsUi {
[StructLayout(LayoutKind.Sequential)]
public struct Rect { public int Left, Top, Right, Bottom; }
[StructLayout(LayoutKind.Sequential)]
public struct Point { public int X, Y; }
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr window, out Rect rect);
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr window, IntPtr after, int x, int y, int width, int height, uint flags);
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr window, int command);
[DllImport("user32.dll")] public static extern uint GetDpiForWindow(IntPtr window);
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
[DllImport("user32.dll", CharSet=CharSet.Unicode)]
public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string className, string title);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window, out uint pid);
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
[DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr window, out Rect rect);
[DllImport("user32.dll")] public static extern bool ClientToScreen(IntPtr window, ref Point point);
[DllImport("user32.dll")] public static extern bool RedrawWindow(IntPtr window, IntPtr rect, IntPtr region, uint flags);
[DllImport("user32.dll", EntryPoint="PostMessageW")] public static extern bool Post(IntPtr window, uint msg, IntPtr w, IntPtr l);
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, uint msg, IntPtr w, IntPtr l);
[DllImport("user32.dll", CharSet=CharSet.Unicode, EntryPoint="SendMessageW")]
public static extern IntPtr Read(IntPtr window, uint msg, IntPtr w, StringBuilder text);
public static bool Activate(IntPtr window) {
if (GetForegroundWindow() == window) return true;
keybd_event(18, 0, 0, UIntPtr.Zero);
keybd_event(18, 0, 2, UIntPtr.Zero);
SetForegroundWindow(window);
return GetForegroundWindow() == window;
}
}
'@
function Wait-For([string]$Name, [scriptblock]$Condition) {
for ($attempt = 0; $attempt -lt 50; ++$attempt) {
$value = & $Condition
if ($value) { return $value }
Start-Sleep -Milliseconds 100
}
throw "Timed out waiting for $Name."
}
function Invoke-FilesCommand([IntPtr]$Window, [string]$LabelPattern) {
[void][FilesCommandsUi]::Post($Window, 273, [IntPtr]132, [IntPtr]::Zero)
$picker = [FilesCommandsUi]::GetDlgItem($Window, 121)
[void](Wait-For 'the Commands menu' { [FilesCommandsUi]::IsWindowVisible($picker) })
$count = [FilesCommandsUi]::Send($picker, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt64()
for ($row = 0; $row -lt $count; ++$row) {
$label = [Text.StringBuilder]::new(128)
[void][FilesCommandsUi]::Read($picker, 393, [IntPtr]$row, $label)
if ($label.ToString() -like $LabelPattern) {
[void][FilesCommandsUi]::Send($picker, 390, [IntPtr]$row, [IntPtr]::Zero)
[void][FilesCommandsUi]::Post($Window, 273, [IntPtr](0x20000 + 121), $picker)
return
}
}
throw "Missing Files command matching $LabelPattern."
}
+20 -75
View File
@@ -2,50 +2,7 @@ param([Parameter(Mandatory)][string]$Executable)
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Drawing
Add-Type @'
using System;
using System.Text;
using System.Runtime.InteropServices;
public static class ComparisonSplitterUi {
[StructLayout(LayoutKind.Sequential)]
public struct Rect { public int Left, Top, Right, Bottom; }
[StructLayout(LayoutKind.Sequential)]
public struct Point { public int X, Y; }
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
[DllImport("user32.dll", CharSet=CharSet.Unicode)]
public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string className, string title);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window, out uint pid);
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
[DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr window, out Rect rect);
[DllImport("user32.dll")] public static extern bool ClientToScreen(IntPtr window, ref Point point);
[DllImport("user32.dll")] public static extern bool RedrawWindow(IntPtr window, IntPtr rect, IntPtr region, uint flags);
[DllImport("user32.dll", EntryPoint="PostMessageW")] public static extern bool Post(IntPtr window, uint msg, IntPtr w, IntPtr l);
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, uint msg, IntPtr w, IntPtr l);
[DllImport("user32.dll", CharSet=CharSet.Unicode, EntryPoint="SendMessageW")]
public static extern IntPtr Read(IntPtr window, uint msg, IntPtr w, StringBuilder text);
public static bool Activate(IntPtr window) {
if (GetForegroundWindow() == window) return true;
keybd_event(18, 0, 0, UIntPtr.Zero);
keybd_event(18, 0, 2, UIntPtr.Zero);
SetForegroundWindow(window);
return GetForegroundWindow() == window;
}
}
'@
function Wait-For([string]$Name, [scriptblock]$Condition) {
for ($attempt = 0; $attempt -lt 50; ++$attempt) {
$value = & $Condition
if ($value) { return $value }
Start-Sleep -Milliseconds 100
}
throw "Timed out waiting for $Name."
}
. "$PSScriptRoot/files_commands_ui.ps1"
$preferences = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$names = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance'
@@ -57,7 +14,7 @@ foreach ($name in $names) {
}
$temp = (Resolve-Path -LiteralPath ([IO.Path]::GetTempPath())).Path.TrimEnd('\')
$root = Join-Path $temp ('ks-files-splitter-' + [Guid]::NewGuid().ToString('N'))
$dpi = [ComparisonSplitterUi]::SetThreadDpiAwarenessContext([IntPtr](-4))
$dpi = [FilesCommandsUi]::SetThreadDpiAwarenessContext([IntPtr](-4))
$process = $null
try {
$left = Join-Path $root 'left'
@@ -78,52 +35,40 @@ try {
if ($process.MainWindowHandle -ne [IntPtr]::Zero) { $process.MainWindowHandle }
}
foreach ($id in 102, 103) {
$panel = [ComparisonSplitterUi]::GetDlgItem($main, $id)
$panel = [FilesCommandsUi]::GetDlgItem($main, $id)
[void](Wait-For 'the test file in the panel' {
[ComparisonSplitterUi]::Send($panel, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt64() -eq 2
[FilesCommandsUi]::Send($panel, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt64() -eq 2
})
[void][ComparisonSplitterUi]::Send($panel, 390, [IntPtr]1, [IntPtr]::Zero)
[void][FilesCommandsUi]::Send($panel, 390, [IntPtr]1, [IntPtr]::Zero)
}
[void][ComparisonSplitterUi]::Post($main, 273, [IntPtr]132, [IntPtr]::Zero)
$picker = [ComparisonSplitterUi]::GetDlgItem($main, 121)
[void](Wait-For 'the Commands menu' { [ComparisonSplitterUi]::IsWindowVisible($picker) })
$row = -1
$count = [ComparisonSplitterUi]::Send($picker, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt64()
for ($i = 0; $i -lt $count; ++$i) {
$label = [Text.StringBuilder]::new(128)
[void][ComparisonSplitterUi]::Read($picker, 393, [IntPtr]$i, $label)
if ($label.ToString() -like 'Compare files*') { $row = $i; break }
}
if ($row -lt 0) { throw 'Missing Compare files command.' }
[void][ComparisonSplitterUi]::Send($picker, 390, [IntPtr]$row, [IntPtr]::Zero)
[void][ComparisonSplitterUi]::Post($main, 273, [IntPtr](0x20000 + 121), $picker)
Invoke-FilesCommand $main 'Compare files*'
$list = Wait-For 'the foreground comparison list' {
$dialog = [IntPtr]::Zero
while (($dialog = [ComparisonSplitterUi]::FindWindowEx([IntPtr]::Zero,$dialog,'#32770','Compare files')) -ne [IntPtr]::Zero) {
while (($dialog = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero,$dialog,'#32770','Compare files')) -ne [IntPtr]::Zero) {
[uint32]$ownerPid = 0
[void][ComparisonSplitterUi]::GetWindowThreadProcessId($dialog, [ref]$ownerPid)
[void][FilesCommandsUi]::GetWindowThreadProcessId($dialog, [ref]$ownerPid)
if ($ownerPid -ne $process.Id) { continue }
$control = [ComparisonSplitterUi]::GetDlgItem($dialog, 402)
if ([ComparisonSplitterUi]::IsWindowVisible($control) -and [ComparisonSplitterUi]::Activate($dialog)) {
$control = [FilesCommandsUi]::GetDlgItem($dialog, 402)
if ([FilesCommandsUi]::IsWindowVisible($control) -and [FilesCommandsUi]::Activate($dialog)) {
return $control
}
}
}
$bounds = [ComparisonSplitterUi+Rect]::new()
[void][ComparisonSplitterUi]::GetClientRect($list, [ref]$bounds)
$bounds = [FilesCommandsUi+Rect]::new()
[void][FilesCommandsUi]::GetClientRect($list, [ref]$bounds)
$middle = [int]($bounds.Right / 2)
$destination = [int]($bounds.Right * 0.65)
$mouseY = 30 -shl 16
[void][ComparisonSplitterUi]::Send($list, 513, [IntPtr]1, [IntPtr]($mouseY -bor $middle))
[void][FilesCommandsUi]::Send($list, 513, [IntPtr]1, [IntPtr]($mouseY -bor $middle))
for ($x = $middle + 5; $x -lt $destination; $x += 5) {
[void][ComparisonSplitterUi]::Send($list, 512, [IntPtr]1, [IntPtr]($mouseY -bor $x))
[void][ComparisonSplitterUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
[void][FilesCommandsUi]::Send($list, 512, [IntPtr]1, [IntPtr]($mouseY -bor $x))
[void][FilesCommandsUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
}
[void][ComparisonSplitterUi]::Send($list, 514, [IntPtr]::Zero, [IntPtr]($mouseY -bor $destination))
[void][ComparisonSplitterUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
$origin = [ComparisonSplitterUi+Point]::new()
[void][ComparisonSplitterUi]::ClientToScreen($list, [ref]$origin)
[void][FilesCommandsUi]::Send($list, 514, [IntPtr]::Zero, [IntPtr]($mouseY -bor $destination))
[void][FilesCommandsUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
$origin = [FilesCommandsUi+Point]::new()
[void][FilesCommandsUi]::ClientToScreen($list, [ref]$origin)
$bitmap = [Drawing.Bitmap]::new($bounds.Right, 1)
try {
$graphics = [Drawing.Graphics]::FromImage($bitmap)
@@ -146,7 +91,7 @@ try {
else { $preferences.DeleteValue($name, $false) }
}
$preferences.Dispose()
if ($dpi) { [void][ComparisonSplitterUi]::SetThreadDpiAwarenessContext($dpi) }
if ($dpi) { [void][FilesCommandsUi]::SetThreadDpiAwarenessContext($dpi) }
if (Test-Path -LiteralPath $root) {
$resolved = (Resolve-Path -LiteralPath $root).Path
if ((Split-Path -Parent $resolved) -eq $temp -and (Split-Path -Leaf $resolved) -like 'ks-files-splitter-*') {
+6 -3
View File
@@ -89,7 +89,8 @@ try {
Open-Picker $side
$rows = @(Read-Picker)
$row = [Array]::IndexOf($rows, 'FTP')
if ($row -lt 2 -or $rows[$row - 1] -cne '' -or $rows[$row + 1] -cne 'KSwitcher LAN') {
if ($row -lt 2 -or $rows[$row - 1] -cne '' -or $rows[$row + 1] -cne 'Recent folders' -or
$rows[$row + 2] -cne 'KSwitcher LAN') {
throw "Source groups are missing separators in panel $side."
}
[void][FilesDriveShortcutTest]::SendMessage($picker, 390, [IntPtr]$row, $null)
@@ -98,12 +99,14 @@ try {
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero)
Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row }
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero)
Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row + 1 }
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero)
Wait-Until {
$selected = [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32()
$selected -ge 0 -and ($selected -lt $row -or $selected -gt $row + 1)
$selected -ge 0 -and ($selected -lt $row -or $selected -gt $row + 2)
}
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]38, [IntPtr]::Zero)
Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row }
Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row + 1 }
[void][FilesDriveShortcutTest]::SendMessage($picker, 407, [IntPtr]($row - 2), $null)
$bitmap = Render-Picker
try {
+101
View File
@@ -0,0 +1,101 @@
param(
[string]$Executable = "$PSScriptRoot/../build/files-cmake/KSwitcher.Files.exe"
)
$ErrorActionPreference = 'Stop'
Add-Type @'
using System;
using System.Runtime.InteropServices;
public static class FilesQuickViewProbe {
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr parent, int id);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr window);
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
public static bool Activate(IntPtr window) {
if (GetForegroundWindow() == window) return true;
keybd_event(0x12, 0, 0, UIntPtr.Zero);
keybd_event(0x12, 0, 2, UIntPtr.Zero);
SetForegroundWindow(window);
return GetForegroundWindow() == window;
}
}
'@
function Wait-Until([scriptblock]$Condition) {
for ($attempt = 0; $attempt -lt 100; $attempt++) {
if (& $Condition) { return }
Start-Sleep -Milliseconds 50
}
throw "Timed out waiting for: $Condition"
}
$exe = (Resolve-Path $Executable).Path
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$names = 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement'
$saved = @{}
foreach ($name in $names) {
if ($name -in $key.GetValueNames()) { $saved[$name] = @($key.GetValue($name), $key.GetValueKind($name)) }
}
$fixture = [IO.Directory]::CreateTempSubdirectory('ks-files-quick-view-')
try {
$left = $fixture.CreateSubdirectory('left')
$right = $fixture.CreateSubdirectory('right')
$document = Join-Path $left.FullName 'preview.txt'
[IO.File]::WriteAllText($document, 'Quick View fixture')
$key.SetValue('LeftWide', 1, 'DWord')
$key.SetValue('RightWide', 1, 'DWord')
$key.SetValue('LeftPath', $left.FullName, 'String')
$key.SetValue('RightPath', $right.FullName, 'String')
$key.SetValue('LeftCursor', $document, 'String')
$key.DeleteValue('RightCursor', $false)
$key.DeleteValue('WindowPlacement', $false)
$process = Start-Process -FilePath $exe -PassThru
Wait-Until { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
$window = $process.MainWindowHandle
Wait-Until { [FilesQuickViewProbe]::Activate($window) }
$keyboard = New-Object -ComObject WScript.Shell
$leftList = [FilesQuickViewProbe]::GetDlgItem($window, 102)
$rightList = [FilesQuickViewProbe]::GetDlgItem($window, 103)
$rightHeading = [FilesQuickViewProbe]::GetDlgItem($window, 141)
$rightPath = [FilesQuickViewProbe]::GetDlgItem($window, 143)
if (!($leftList -and $rightList -and $rightHeading -and $rightPath)) {
throw 'Expected both file panels in the test window.'
}
Wait-Until { [FilesQuickViewProbe]::IsWindowVisible($rightHeading) }
$keyboard.SendKeys('^q')
Wait-Until {
$hostWindow = [FilesQuickViewProbe]::GetDlgItem($window, 158)
$hostWindow -ne [IntPtr]::Zero -and [FilesQuickViewProbe]::IsWindowVisible($hostWindow)
}
foreach ($control in $rightList, $rightHeading, $rightPath) {
if ([FilesQuickViewProbe]::IsWindowVisible($control)) {
throw 'A file panel control can draw over the Quick View content.'
}
}
if (![FilesQuickViewProbe]::IsWindowVisible($leftList)) { throw 'Quick View hid the source panel.' }
$keyboard.SendKeys('^q')
Wait-Until { [FilesQuickViewProbe]::GetDlgItem($window, 158) -eq [IntPtr]::Zero }
foreach ($control in $rightList, $rightHeading, $rightPath) {
if (![FilesQuickViewProbe]::IsWindowVisible($control)) {
throw 'A file panel control remained hidden after closing Quick View.'
}
}
'Quick View hides the covered list and chrome, then restores the same controls.'
} finally {
if ($process -and !$process.HasExited) {
[void]$process.CloseMainWindow()
if (!$process.WaitForExit(3000)) { $process.Kill(); $process.WaitForExit() }
}
foreach ($name in $names) {
if ($saved.ContainsKey($name)) { $key.SetValue($name, $saved[$name][0], $saved[$name][1]) }
else { $key.DeleteValue($name, $false) }
}
$key.Dispose()
$path = [IO.Path]::GetFullPath($fixture.FullName)
if ([IO.Path]::GetDirectoryName($path) -eq [IO.Path]::TrimEndingDirectorySeparator([IO.Path]::GetTempPath()) -and
[IO.Path]::GetFileName($path).StartsWith('ks-files-quick-view-')) {
[IO.Directory]::Delete($path, $true)
}
}
+62
View File
@@ -0,0 +1,62 @@
param([Parameter(Mandatory)][string]$Executable)
$ErrorActionPreference = 'Stop'
. "$PSScriptRoot/files_commands_ui.ps1"
$dpi = [FilesCommandsUi]::SetThreadDpiAwarenessContext([IntPtr](-4))
$process = $null
try {
$process = Start-Process -FilePath (Resolve-Path -LiteralPath $Executable) -PassThru
$main = Wait-For 'the Files window' {
$process.Refresh()
if ($process.MainWindowHandle -ne [IntPtr]::Zero) { $process.MainWindowHandle }
}
[void][FilesCommandsUi]::ShowWindow($main, 9)
$width = [int](350 * [FilesCommandsUi]::GetDpiForWindow($main) / 96)
if (![FilesCommandsUi]::SetWindowPos($main, [IntPtr]::Zero, 0, 0, $width, 0, 22)) {
throw 'Could not narrow the Files window.'
}
Invoke-FilesCommand $main 'Space Analyzer'
$dialog = Wait-For 'the visible Space Analyzer' {
$candidate = [IntPtr]::Zero
while (($candidate = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero, $candidate, '#32770', 'Space Analyzer')) -ne [IntPtr]::Zero) {
[uint32]$owner = 0
[void][FilesCommandsUi]::GetWindowThreadProcessId($candidate, [ref]$owner)
if ($owner -eq $process.Id -and [FilesCommandsUi]::IsWindowVisible($candidate)) { return $candidate }
}
}
$outer = [FilesCommandsUi+Rect]::new()
if (![FilesCommandsUi]::GetWindowRect($dialog, [ref]$outer)) { throw 'Could not measure the Space Analyzer.' }
$previousRight = $outer.Left
$firstLeft = 0
$midY = 0
foreach ($id in 492, 493, 494, 1, 2) {
$button = [FilesCommandsUi]::GetDlgItem($dialog, $id)
$rect = [FilesCommandsUi+Rect]::new()
if (![FilesCommandsUi]::IsWindowVisible($button) -or ![FilesCommandsUi]::GetWindowRect($button, [ref]$rect)) {
throw "Space Analyzer footer button $id was unavailable."
}
if ($rect.Left -le $previousRight -or $rect.Right -ge $outer.Right -or $rect.Bottom -ge $outer.Bottom) {
throw "Space Analyzer footer button $id was clipped or overlapped at narrow width."
}
if ($id -eq 492) {
$firstLeft = $rect.Left
$midY = $rect.Top + $rect.Bottom
} elseif ([Math]::Abs($midY - $rect.Top - $rect.Bottom) -gt 1) {
throw "Space Analyzer footer button $id was outside the shared button row."
}
$previousRight = $rect.Right
}
if ([Math]::Abs(($firstLeft + $previousRight) - ($outer.Left + $outer.Right)) -gt 2) {
throw 'Space Analyzer footer buttons were off center.'
}
'Verified the full and centered Space Analyzer footer at narrow width.'
} finally {
# End this fixture without saving its temporary window dimensions.
if ($process -and !$process.HasExited) {
$process.Kill()
$process.WaitForExit()
}
if ($dpi) { [void][FilesCommandsUi]::SetThreadDpiAwarenessContext($dpi) }
}