From 10d5a42f2a7a2d83b241326924ff35ed9da88bff Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Fri, 13 Nov 2026 23:59:44 +0200 Subject: [PATCH] Add KSwitcher Files local manager and copy workflow --- AGENTS.md | 6 + CMakeLists.txt | 11 +- FILES-UI.md | 35 + build.ps1 | 6 + package.ps1 | 3 +- resources/files.rc | 80 ++ resources/kswitcher-files.ico | Bin 0 -> 34494 bytes src/app.cpp | 15 + src/files_main.cpp | 2348 +++++++++++++++++++++++++++++++++ 9 files changed, 2502 insertions(+), 2 deletions(-) create mode 100644 FILES-UI.md create mode 100644 resources/files.rc create mode 100644 resources/kswitcher-files.ico create mode 100644 src/files_main.cpp diff --git a/AGENTS.md b/AGENTS.md index 3708a07..86bbfd0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,3 +33,9 @@ Wiki: https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki Updating only the release notes or changing only the Wiki version number does not satisfy this rule; the current functionality must also be reviewed. + +## KSwitcher Files UI + +Before changing the file manager UI, read [FILES-UI.md](FILES-UI.md). +Reuse the shared dialog rendering and layout helpers. Update the document +when an agreed UI requirement changes. diff --git a/CMakeLists.txt b/CMakeLists.txt index 459b6db..d023aca 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5,6 +5,15 @@ if(NOT WIN32) endif() set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) +add_executable(KSwitcherFiles WIN32 src/files_main.cpp resources/files.rc) +set_target_properties(KSwitcherFiles PROPERTIES OUTPUT_NAME "KSwitcher.Files") +target_compile_definitions(KSwitcherFiles PRIVATE UNICODE _UNICODE NOMINMAX _WIN32_WINNT=0x0A00) +target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32) +if(MSVC) + target_compile_options(KSwitcherFiles PRIVATE /utf-8) +else() + target_link_options(KSwitcherFiles PRIVATE -municode -static) +endif() add_executable(StayHere WIN32 utilities/StayHere/main.cpp) add_executable(StayHereTest WIN32 utilities/StayHere/main.cpp) target_compile_definitions(StayHereTest PRIVATE STAYHERE_TEST_INSTANCE) @@ -173,7 +182,7 @@ add_test(NAME screenshot-ui-regressions COMMAND KSwitcherScreenshotUITests) add_test(NAME screenshot-save-regressions COMMAND KSwitcherScreenshotUITests --save-only) add_test(NAME updater-regressions COMMAND powershell.exe -NoProfile -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/update.ps1" -Executable "$") set_tests_properties(native-regressions PROPERTIES WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}") -install(TARGETS KSwitcher KSwitcherConfig KSwitcherScreenshot RUNTIME DESTINATION .) +install(TARGETS KSwitcher KSwitcherConfig KSwitcherScreenshot KSwitcherFiles RUNTIME DESTINATION .) install(FILES LICENSE vendor/json-LICENSE.txt DESTINATION .) add_custom_command(TARGET KSwitcher POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_CURRENT_SOURCE_DIR}/dictionaries" "$/dictionaries") diff --git a/FILES-UI.md b/FILES-UI.md new file mode 100644 index 0000000..7e185f1 --- /dev/null +++ b/FILES-UI.md @@ -0,0 +1,35 @@ +# Оформлення KSwitcher Files + +Far Manager є зразком для оформлення файлового менеджера. Основне вікно використовує системний заголовок Windows. Панелі, меню й діалоги операцій використовують моноширинний шрифт менеджера та оформлення в стилі Far. + +## Спільні елементи діалогів + +- При перенесенні вікна між моніторами з різним DPI оновлюй шрифт, висоту рядків панелей і компонування відкритого прогресу копіювання. Перевір перенесення під час активного копіювання. +- Для власних діалогів використовуй подвійну рамку з одним заголовком у верхній лінії. Звичайний діалог має сіре тло, попередження — темно-червоне тло та білий текст. +- У ресурсі чи виклику задавай назву кнопки й клавішу доступу. Спільна функція `paintDialogButton` додає квадратні дужки, центрує текст і підсвічує фокус. +- Нижні секції з кнопками у Copy, Warning і вікні прогресу мають однакову висоту, прив’язану до висоти рядка шрифту. Використовуй `layoutDialogButtons` для такої секції та `centerDialogRow` для інших рядків між роздільниками. Межі секції визначають положення рядка. +- Поля вводу й випадаючі списки використовують бірюзове тло палітри менеджера. Текст і стрілку вирівнюй вертикально по центру. Прапорці в діалогах операцій використовують позначки `[ ]` та `[x]` і видимий клавіатурний фокус. +- Повторно використовуй спільне оформлення. Текст, дії та стан операції передавай із коду конкретної операції. Наприклад, Warning повертає відповідь і стан прапорця, а копіювання вирішує, чи застосувати відповідь до наступних конфліктів. + +## Діалог Copy + +- Вирівнюй підпис Existing files по вертикальному центру списку. Ширше поле списку починається ближче до підпису, а його правий край збігається з правим краєм поля імені. +- Зберігай однакові проміжки від верхнього роздільника до поля імені й до списку. Підпис, поля та прапорець мають читатися повністю. +- Відступ після прапорця до нижнього роздільника дорівнює відступу від верхнього роздільника до списку. +- Кнопки Copy та Cancel стоять по центру компактної нижньої секції. Висота кнопок має вміщати весь текст поточного шрифту. + +## Вікно прогресу копіювання + +- Секції поточного файла й загального прогресу мають однаковий вертикальний відступ від вмісту до верхньої та нижньої ліній. Cancel стоїть по центру спільної нижньої секції. +- Обидві шкали займають усю ширину вмісту. Відсотки показуються по центру шкали, а її висота враховує поточний шрифт. + +## Попередження про конфлікт + +- Після розрахунку остаточної висоти центр Warning збігається з центром вікна прогресу. +- Remember choice стоїть по вертикальному центру власної секції. Кнопки Overwrite, Skip і Cancel стоять по центру нижньої секції. +- Tab проходить Remember choice, Overwrite, Skip і Cancel. Стрілки вліво та вправо циклічно перемикають три кнопки в порядку їх розташування. +- Стрілки вгору й вниз переходять між сусідніми секціями з інтерактивними елементами. У Warning стрілка вгору з ряду кнопок переводить фокус на Remember choice, а вниз із прапорця — на Overwrite. + +## Перевірка змін + +Відкрий Copy і Warning в одній збірці та порівняй висоту нижніх секцій, центрування, повноту підписів і видимість фокуса. Перевір Tab, стрілки й Esc. Після узгодження нового правила онови відповідний розділ цього документа. diff --git a/build.ps1 b/build.ps1 index 49d8719..eec2ecf 100644 --- a/build.ps1 +++ b/build.ps1 @@ -46,6 +46,12 @@ try { & $compiler -mwindows -municode -static -s '-Wl,--gc-sections' build/lan_channel.o build/lan_input.o build/lan.o build/lan_pairing.o build/core.o build/platform.o build/storage.o build/ocr.o build/screenshot.o build/screenshot_notifications.o build/screenshot_activation.o build/screenshot_main.o build/screenshot-res.o @libs -o $screenshotPath if ($LASTEXITCODE) { throw 'Screenshot link failed' } Copy-Item -LiteralPath $screenshotPath -Destination build/release/KSwitcher.Screenshot.exe -Force + $filesPath = Join-Path (Split-Path $executablePath) 'KSwitcher.Files.exe' + & windres resources/files.rc -O coff -o build/files-res.o + if ($LASTEXITCODE) { throw 'File manager resource compilation failed' } + & $compiler @common -mwindows -municode -static -s src/files_main.cpp build/files-res.o -luser32 -lgdi32 -lcomctl32 -lshell32 -lcomdlg32 -ladvapi32 -lole32 -o $filesPath + if ($LASTEXITCODE) { throw 'File manager build failed' } + Copy-Item -LiteralPath $filesPath -Destination build/release/KSwitcher.Files.exe -Force if ($Test) { & $compiler @common -Werror tests/settings_merge.cpp build/sync.o build/storage.o build/core.o build/platform.o build/ocr.o @libs -static -s -o build/KSwitcherSettingsMergeTests.exe if ($LASTEXITCODE) { throw 'Settings merge test build failed' } diff --git a/package.ps1 b/package.ps1 index 1cd6517..200da6c 100644 --- a/package.ps1 +++ b/package.ps1 @@ -6,6 +6,7 @@ New-Item -ItemType Directory -Force $destination | Out-Null Copy-Item -LiteralPath (Join-Path $root 'build\release\KSwitcher.exe') -Destination $destination Copy-Item -LiteralPath (Join-Path $root 'build\release\KSwitcher.Config.exe') -Destination $destination Copy-Item -LiteralPath (Join-Path $root 'build\release\KSwitcher.Screenshot.exe') -Destination $destination +Copy-Item -LiteralPath (Join-Path $root 'build\release\KSwitcher.Files.exe') -Destination $destination Copy-Item -LiteralPath (Join-Path $root 'LICENSE') -Destination $destination Copy-Item -LiteralPath (Join-Path $root 'vendor\json-LICENSE.txt') -Destination $destination Copy-Item -LiteralPath (Join-Path $root 'README.md') -Destination $destination @@ -16,7 +17,7 @@ Copy-Item -LiteralPath (Join-Path $root 'resources\portable-tools-README.txt') - Copy-Item -LiteralPath (Join-Path $root 'build\release\tools\StayHere.exe') -Destination (Join-Path $destination 'tools\StayHere.exe') -Force Copy-Item -LiteralPath (Join-Path $root 'utilities\StayHere\README.md') -Destination (Join-Path $destination 'tools\StayHere-README.md') -Force # Enumerate the distributable files explicitly; do not include a user's data directory. -$files = @('KSwitcher.exe','KSwitcher.Config.exe','KSwitcher.Screenshot.exe','LICENSE','json-LICENSE.txt','README.md','LAN-PREVIEW.md','dictionaries','tools\README.txt','tools\StayHere.exe','tools\StayHere-README.md') | ForEach-Object { Join-Path $destination $_ } +$files = @('KSwitcher.exe','KSwitcher.Config.exe','KSwitcher.Screenshot.exe','KSwitcher.Files.exe','LICENSE','json-LICENSE.txt','README.md','LAN-PREVIEW.md','dictionaries','tools\README.txt','tools\StayHere.exe','tools\StayHere-README.md') | ForEach-Object { Join-Path $destination $_ } $entries = foreach ($path in $files) { foreach ($file in @(Get-ChildItem -LiteralPath $path -File -Recurse)) { @{path=$file.FullName.Substring($destination.Length+1).Replace('\','/'); size=$file.Length; sha256=(Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash.ToLowerInvariant()} diff --git a/resources/files.rc b/resources/files.rc new file mode 100644 index 0000000..ebf88f1 --- /dev/null +++ b/resources/files.rc @@ -0,0 +1,80 @@ +#include + +1 ICON "kswitcher-files.ico" +1 RT_MANIFEST "app.manifest" + +101 DIALOGEX 0, 0, 256, 141 +STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Wide panel mode" +FONT 9, "Segoe UI" +BEGIN + GROUPBOX "Panel columns — Name, Size", -1, 8, 6, 240, 59 + LTEXT "Size column &width (6-16 characters)", -1, 17, 22, 166, 10 + EDITTEXT 201, 196, 18, 41, 14, ES_NUMBER | ES_AUTOHSCROLL + AUTOCHECKBOX "&Align file extensions", 202, 17, 42, 104, 12 + AUTOCHECKBOX "Align &folder extensions", 204, 130, 42, 108, 12 + GROUPBOX "Status line columns", -1, 8, 72, 240, 39 + AUTOCHECKBOX "Show &details", 203, 17, 83, 94, 11 + AUTOCHECKBOX "Name", 205, 17, 96, 47, 11 + AUTOCHECKBOX "Size", 206, 72, 96, 42, 11 + AUTOCHECKBOX "Date", 207, 128, 96, 45, 11 + AUTOCHECKBOX "Time", 208, 185, 96, 45, 11 + DEFPUSHBUTTON "OK", IDOK, 139, 119, 50, 14 + PUSHBUTTON "Cancel", IDCANCEL, 196, 119, 50, 14 +END + +102 DIALOGEX 0, 0, 350, 114 +STYLE DS_SETFONT | DS_CENTER | WS_POPUP +CAPTION "Copy" +FONT 10, "Consolas" +BEGIN + LTEXT "Copy to", 210, 14, 15, 322, 12, SS_PATHELLIPSIS + CONTROL "", 211, "Edit", ES_MULTILINE | ES_AUTOHSCROLL | WS_TABSTOP, 14, 29, 322, 18 + LTEXT "Existing files:", 212, 14, 61, 122, 14, SS_CENTERIMAGE + COMBOBOX 213, 140, 61, 196, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_VSCROLL | WS_TABSTOP + CONTROL "Also ask on read-only files", 214, "Button", BS_OWNERDRAW | WS_TABSTOP, 14, 81, 322, 14 + CONTROL "&Copy", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 87, 96, 86, 18 + CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 177, 96, 86, 18 +END + +103 DIALOGEX 0, 0, 460, 126 +STYLE DS_SETFONT | DS_CENTER | WS_POPUP +CAPTION "Copying" +FONT 10, "Consolas" +BEGIN + LTEXT "Counting files...", 220, 12, 16, 436, 12, SS_OWNERDRAW + LTEXT "", 221, 12, 31, 436, 12, SS_OWNERDRAW + CONTROL "", 222, "msctls_progress32", PBS_SMOOTH, 12, 46, 436, 14 + LTEXT "Files:", 224, 12, 63, 436, 12 + LTEXT "Bytes:", 225, 12, 77, 436, 12 + CONTROL "", 226, "msctls_progress32", PBS_SMOOTH, 12, 91, 436, 14 + LTEXT "", 228, 12, 60, 1, 1 + LTEXT "", 229, 12, 104, 1, 1 + CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 187, 106, 86, 18 +END + +104 DIALOGEX 0, 0, 360, 106 +STYLE DS_SETFONT | DS_CENTER | WS_POPUP +CAPTION "Warning" +FONT 10, "Consolas" +BEGIN + LTEXT "", 230, 12, 16, 336, 12 + LTEXT "", 231, 12, 33, 336, 12, SS_PATHELLIPSIS + LTEXT "", 233, 12, 55, 1, 1 + LTEXT "", 234, 12, 81, 1, 1 + CONTROL "Remember choice", 232, "Button", BS_OWNERDRAW | WS_TABSTOP, 12, 57, 336, 18 + CONTROL "&Overwrite", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP, 42, 89, 110, 18 + CONTROL "&Skip", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP, 158, 89, 68, 18 + CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 232, 89, 86, 18 +END + +105 DIALOGEX 0, 0, 310, 65 +STYLE DS_SETFONT | DS_CENTER | WS_POPUP +CAPTION "Cancel copy" +FONT 10, "Consolas" +BEGIN + CTEXT "Do you really want to cancel copying?", 235, 12, 17, 286, 16, SS_CENTERIMAGE + LTEXT "", 236, 12, 38, 1, 1 + CONTROL "&Yes", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP, 83, 42, 68, 18 + CONTROL "&No", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP, 159, 42, 68, 18 +END diff --git a/resources/kswitcher-files.ico b/resources/kswitcher-files.ico new file mode 100644 index 0000000000000000000000000000000000000000..9d2951fb1babe1e9dc3eecf3a3b8dc641b1f0a18 GIT binary patch literal 34494 zcmeI4O^zHz5QWnkkj2LK4zJKi$dZ@70RsZBS+Qoxjw=j1P5@W%DUgpcEZHD#&}2^e zlb&Ous;eqHv&uEmQaU0dU;MmRH8oAUaY|3p=jp|Zls%v4bHyQ^&0$}EfBVB}>H78S zS0@Bnnp^N*{y%p=p8kCM<^3vt!D+0V5#MWmnUBT%?6G6~OMLF~_|MI?{Y$Mii|ap@ z%lSE5n}4o;%kxwIDPY|`N$K4BE#u1~r#xr!qblXcQ7X@`cnQ&TI_q()-`m(LFUaHs*t!+h6gQ_UByx zOZU`zd+lH5>a{-p?UPckzVxZ>Z}V&S%r)26_OtnO`+~FiwR`H$wYB{sKNQ%50{OFo z2e0=jU0q~dolfs%J!q5z<#USicSS$v6`xaN5#kjJgaV;JC@`wP-1lf(D8OP9Qcq5n3za}C$(Kla(vRGgm0PT{7`v_|nSF+ZPQdsb)B-WvDvG^SXs z5%Uk!!%OZSRX?KG}<&sVJ0i2Fb8|8j45_l(Bk{(1Nw zK{c7{>(AcY9E;N$m-_j&J;wIhdkk|ft~DO>{8opp_G{n2Z8fj$8}mPWHd&2Y?jM8x zaNM(<`ut?ib2D4aKmC1#F@0LcxjwbF^_*k%Yv(3^tbXe_{cCOOImhbP&Q1PU{nl~% z*V@)|M*UDA6bJ=EfqDgo?+%s!&%C^r+q*Kt)0B>9pWf?nm*&}f`BvyxzNdAQ*KJ<$ zJ*_N4yh4FcAQT7%LV-{q6bJ=e1!_N|*?YcAT7r9@zji*M>blf#`S)F0)P|Q!T7uxV zn6YI~cnMY41=n(xEo#HdB`ra4Tg=$9C%lBJ>w;@J%NDia<&u^lxGiRE*%Mwu)pfy* z&2sL$NpsI_{keJPaJDXcc)6q{2#!2!&-I^s-m5Ns;3ZUD7aV!kT7LQ+$0^_D^{PuB zc)6q{2#!2!EsrVAdS>%_)uj)-gsSU;BhOmPLpe_QHm_G*`oPO2EkSVPS!;Pran>`N z*Q+jl;3ZUD7aV!kS{}-A%C~vF>e2^ZE@=sZBhOmPV~Vq$*}PtL=>spJ>bl^_v)1xZ zj#IwP>s6ON@N!8@5FB~dS{_rJ^~~n=s!Jbu302nxN1nBohjN_qZC*9AwOwU)=)eXqLoftO2Kg5b!r zb}e6<*Q+jl;3ZUD7aVyqc*6r;Le+J_k#`geFPF3g!5xJ+Jm4i%T^AgA zN3rm7NlOsiQFy}xUP9G%!5!7Qq$PM%-tZEtt_$v{)+H^$qw4R+tlM-)!B)JfyCbUZD9qW)x=nW!Y{i?pJE9t+ xgaV;JC=d#S0--=C5DGj(1%`iL;BtTdH)!}g?7a}44$q6)S)Wz*a#w1o^gq)Ffh7O{ literal 0 HcmV?d00001 diff --git a/src/app.cpp b/src/app.cpp index 9cc3fcb..8265c5d 100644 --- a/src/app.cpp +++ b/src/app.cpp @@ -2769,6 +2769,7 @@ void App::trayMenu() AppendMenuW(menu, MF_STRING, 10, L"Clipboard &history"); AppendMenuW(menu, MF_STRING, 24, L"&Capture screen region…"); AppendMenuW(menu, MF_STRING, 11, L"&Settings…"); + AppendMenuW(menu, MF_STRING, 25, L"&Files…"); SetMenuDefaultItem(menu, 11, FALSE); AppendMenuW(menu, MF_STRING, 12, L"S&nippets…"); AppendMenuW(menu, MF_STRING, 13, L"&Keyboard shortcuts…"); @@ -2821,6 +2822,20 @@ void App::trayMenu() } switch (cmd) { + case 25: + { + auto path = std::filesystem::path(executable()).parent_path() / L"KSwitcher.Files.exe"; + auto command = L"\"" + path.wstring() + L"\""; + STARTUPINFOW startup{sizeof(startup)}; + PROCESS_INFORMATION process{}; + if (!CreateProcessW(path.c_str(), command.data(), nullptr, nullptr, FALSE, 0, nullptr, + path.parent_path().c_str(), &startup, &process)) + throw std::runtime_error(utf8(lastError(L"Cannot start KSwitcher Files"))); + AllowSetForegroundWindow(process.dwProcessId); + CloseHandle(process.hThread); + CloseHandle(process.hProcess); + break; + } case 24: dispatch(Screenshot); break; diff --git a/src/files_main.cpp b/src/files_main.cpp new file mode 100644 index 0000000..c3a19b2 --- /dev/null +++ b/src/files_main.cpp @@ -0,0 +1,2348 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +namespace fs = std::filesystem; + +std::wstring formatSize(uint64_t bytes,size_t columns=0) +{ + constexpr const wchar_t *units[]{L"B",L"KiB",L"MiB",L"GiB",L"TiB",L"PiB",L"EiB"}; + constexpr const wchar_t *compact[]{L"",L"K",L"M",L"G",L"T",L"P",L"E"}; + if(columns) + { + for(size_t unit=0;;++unit,bytes/=1024) + { + auto label=std::to_wstring(bytes)+compact[unit]; + if(label.size()<=columns || unit==std::size(compact)-1) return label; + } + } + size_t unit=0; + double value=static_cast(bytes); + while(value>=1024 && unit+1(buffer); + for(;;) + { + std::wstring_view name(entry->FileName,entry->FileNameLength/sizeof(wchar_t)); + if(name!=L"." && name!=L"..") + { + const FolderEntryMetadata metadata{entry->FileAttributes, + static_cast(entry->EndOfFile.QuadPart)}; + std::wstring row(sizeof(metadata)/sizeof(wchar_t),L'\0'); + memcpy(row.data(),&metadata,sizeof(metadata)); + row.append(name); + DWORD written{}; + if(!WriteFile(pipe.value,row.data(),static_cast(row.size()*sizeof(wchar_t)),&written,nullptr)) + return GetLastError(); + } + if(!entry->NextEntryOffset) break; + entry=reinterpret_cast( + reinterpret_cast(entry)+entry->NextEntryOffset); + } + } + const auto error=GetLastError(); + return error==ERROR_NO_MORE_FILES?ERROR_SUCCESS:error; +} + +DWORD requestElevatedFolder(HWND owner,const fs::path &directory, + std::vector &folders,std::vector &files, + std::map &metadata) +{ + GUID id{}; + wchar_t token[40]{}, executable[32768]{}; + auto length=GetModuleFileNameW(nullptr,executable,static_cast(std::size(executable))); + if(!length || length>=std::size(executable) || FAILED(CoCreateGuid(&id)) || + !StringFromGUID2(id,token,static_cast(std::size(token)))) return ERROR_GEN_FAILURE; + auto name=std::wstring(folderPipePrefix)+token; + Handle pipe{CreateNamedPipeW(name.c_str(),PIPE_ACCESS_DUPLEX|FILE_FLAG_FIRST_PIPE_INSTANCE, + PIPE_TYPE_MESSAGE|PIPE_READMODE_MESSAGE|PIPE_NOWAIT|PIPE_REJECT_REMOTE_CLIENTS,1,0,4096,0,nullptr)}; + if(pipe.value==INVALID_HANDLE_VALUE) return GetLastError(); + auto parameters=L"--list-folder \""+(directory/L".").wstring()+L"\" \""+name+L"\""; + SHELLEXECUTEINFOW launch{}; + launch.cbSize=sizeof(launch); + launch.fMask=SEE_MASK_NOCLOSEPROCESS|SEE_MASK_NOASYNC; + launch.hwnd=owner; + launch.lpVerb=L"runas"; + launch.lpFile=executable; + launch.lpParameters=parameters.c_str(); + launch.nShow=SW_HIDE; + if(!ShellExecuteExW(&launch)) return GetLastError(); + Handle process{launch.hProcess}; + bool connected=false; + bool finished=false; + auto deadline=GetTickCount64()+10000; + while(GetTickCount64() rows; + std::vector sizes; + std::vector dimmed; + std::vector marked; + bool wide{}; +}; +Panel panels[2]; +HWND status{}, commands[5]{}; +int active{}, split{}; +bool dragging{}; +bool rememberElevationApproval{}; +HWND picker{}, pickerFrame{}, menuBar{}; +HWND menuItems[5]{}; +int menuIndex{}; +bool commandPicker{}; +int optionsPage{}; +int sizeWidth=6; +bool alignExtensions=true, showDetails=true; +bool alignFolders=false; +DWORD statusFields=15; +std::vector drivePaths; +int pickerPanel{}; +bool altAlone{}; +enum Color { PanelBlue, Text, Frame, Dialog, Selection, Footer, PanelCursor, ColorCount }; +COLORREF colors[]{RGB(0,0,128), RGB(230,255,255), RGB(0,255,255), + RGB(0,128,128), RGB(0,0,0), RGB(0,128,128), RGB(0,128,128)}; +constexpr auto schemeKey = L"Software\\KSwitcher\\Files"; +constexpr auto placementPreference = L"WindowPlacement"; + +bool restorePlacement(HWND window) +{ + WINDOWPLACEMENT placement{}; + DWORD size=sizeof(placement); + if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,placementPreference,RRF_RT_REG_BINARY, + nullptr,&placement,&size)!=ERROR_SUCCESS || size!=sizeof(placement) || + placement.length!=sizeof(placement)) return false; + const auto &rect=placement.rcNormalPosition; + if(static_cast(rect.right)-rect.left<540 || + static_cast(rect.bottom)-rect.top<220) return false; + if(!MonitorFromRect(&rect,MONITOR_DEFAULTTONULL)) return false; + placement.flags=0; + placement.showCmd=placement.showCmd==SW_SHOWMAXIMIZED?SW_SHOWMAXIMIZED:SW_SHOWNORMAL; + if(!SetWindowPlacement(window,&placement)) return false; + ShowWindow(window,static_cast(placement.showCmd)); + return true; +} + +void savePlacement(HWND window) +{ + WINDOWPLACEMENT placement{}; + placement.length=sizeof(placement); + if(!GetWindowPlacement(window,&placement)) return; + const bool maximized=IsZoomed(window) || + (IsIconic(window) && (placement.flags&WPF_RESTORETOMAXIMIZED)); + placement.showCmd=maximized?SW_SHOWMAXIMIZED:SW_SHOWNORMAL; + placement.flags=0; + RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,placementPreference,REG_BINARY, + &placement,sizeof(placement)); +} +void chooseDrive(int index, bool fromMenu = false); +void openMenu(HWND window, int index, int page = 0); +void showFileDetails(const Panel &panel); +void editWideMode(HWND owner); +void layout(HWND window); + +DWORD preference(const wchar_t *name, DWORD fallback) +{ + DWORD value{}, size=sizeof(value); + return RegGetValueW(HKEY_CURRENT_USER,schemeKey,name,RRF_RT_REG_DWORD,nullptr,&value,&size) + == ERROR_SUCCESS ? value : fallback; +} + +void savePreference(const wchar_t *name, DWORD value) +{ + RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,name,REG_DWORD,&value,sizeof(value)); +} + +constexpr const wchar_t *panelPathKeys[]{L"LeftPath",L"RightPath"}; +constexpr const wchar_t *panelCursorKeys[]{L"LeftCursor",L"RightCursor"}; + +fs::path savedPanelPath(const wchar_t *key) +{ + DWORD size{}; + if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,key,RRF_RT_REG_SZ, + nullptr,nullptr,&size)!=ERROR_SUCCESS || size(parameter); + if(reinterpret_cast(SendMessageW(window,WM_GETFONT,0,0))==old) + SendMessageW(window,WM_SETFONT,reinterpret_cast(mono),FALSE); + return TRUE; +} +HBRUSH blue{}, teal{}; +void layout(HWND window); + +bool applyFont(HWND owner, LOGFONTW font, int points) +{ + const auto dpi=GetDpiForWindow(owner); + font.lfHeight=-MulDiv(points,dpi,720); + font.lfWidth=0; + auto next=CreateFontIndirectW(&font); + if(!next) return false; + auto dc=GetDC(owner); + if(!dc){DeleteObject(next);return false;} + auto previous=SelectObject(dc,next); + TEXTMETRICW metrics{}; + GetTextMetricsW(dc,&metrics); + SelectObject(dc,previous); + ReleaseDC(owner,dc); + textHeight=std::max(static_cast(MulDiv(16,dpi,96)),metrics.tmHeight+MulDiv(6,dpi,96)); + cellWidth=std::max(1L,metrics.tmAveCharWidth); + auto old=mono; + mono=next; + displayFont=font; + fontPoints=points; + for(auto &panel:panels) + { + if(panel.path) SendMessageW(panel.path,WM_SETFONT,reinterpret_cast(mono),FALSE); + if(panel.list) SendMessageW(panel.list,LB_SETITEMHEIGHT,0,textHeight); + } + if(picker) SendMessageW(picker,LB_SETITEMHEIGHT,0,textHeight); + if(status) SendMessageW(status,WM_SETFONT,reinterpret_cast(mono),FALSE); + if(old) + { + EnumThreadWindows(GetCurrentThreadId(),[](HWND window,LPARAM parameter)->BOOL + { + EnumChildWindows(window,updateDialogFont,parameter); + return TRUE; + },reinterpret_cast(old)); + DeleteObject(old); + } + return true; +} + +void chooseDisplayFont(HWND owner) +{ + auto font=displayFont; + CHOOSEFONTW dialog{}; + dialog.lStructSize=sizeof(dialog); + dialog.hwndOwner=owner; + dialog.lpLogFont=&font; + dialog.Flags=CF_SCREENFONTS|CF_INITTOLOGFONTSTRUCT|CF_LIMITSIZE; + dialog.nSizeMin=8; + dialog.nSizeMax=24; + if(!ChooseFontW(&dialog)) return; + if(!applyFont(owner,font,dialog.iPointSize)) return; + savePreference(L"FontPoints",fontPoints); + RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,L"DisplayFont",REG_BINARY,&displayFont,sizeof(displayFont)); + layout(owner); + RedrawWindow(owner,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN); +} + +void refreshColors() +{ + if (blue) DeleteObject(blue); + if (teal) DeleteObject(teal); + blue = CreateSolidBrush(colors[PanelBlue]); + teal = CreateSolidBrush(colors[Dialog]); +} + +void loadColors() +{ + for (DWORD i=0; i(SendMessageW(list, LB_GETTOPINDEX, 0, 0)); + int count = static_cast(SendMessageW(list, LB_GETCOUNT, 0, 0)); + RECT rect{}; + GetClientRect(list, &rect); + int rowHeight = static_cast(SendMessageW(list, LB_GETITEMHEIGHT, 0, 0)); + int visible = std::max(1, static_cast(rect.bottom) / std::max(1, rowHeight)); + SendMessageW(list, LB_SETTOPINDEX, + std::clamp(top - (delta / WHEEL_DELTA) * 3, 0, std::max(0, count - visible)), 0); + return 0; + } + return DefSubclassProc(list, message, wp, lp); +} + +void paintScrollPosition(HWND parent, HDC dc, HWND list, COLORREF background) +{ + RECT track{}; + GetWindowRect(list, &track); + MapWindowPoints(nullptr, parent, reinterpret_cast(&track), 2); + track.left = track.right; + track.right += 5; + SetDCBrushColor(dc, background); + FillRect(dc, &track, static_cast(GetStockObject(DC_BRUSH))); + int count = static_cast(SendMessageW(list, LB_GETCOUNT, 0, 0)); + int rowHeight = static_cast(SendMessageW(list, LB_GETITEMHEIGHT, 0, 0)); + int height = track.bottom - track.top; + int visible = std::max(1, height / std::max(1, rowHeight)); + if (height <= 0 || count <= visible) return; + int thumb = std::min(height, std::max(5, MulDiv(height, visible, count))); + int top = static_cast(SendMessageW(list, LB_GETTOPINDEX, 0, 0)); + track.top += MulDiv(std::clamp(top, 0, count - visible), height - thumb, count - visible); + track.bottom = track.top + thumb; + SetDCBrushColor(dc, colors[Frame]); + FillRect(dc, &track, static_cast(GetStockObject(DC_BRUSH))); +} + +void layout(HWND window) +{ + RECT rect{}; + GetClientRect(window, &rect); + int width = rect.right, height = rect.bottom; + int middle = std::clamp(split ? split : width / 2, 120, std::max(120, width - 120)); + auto place=[](HWND control, int x, int y, int width, int height) + { + if(control) SetWindowPos(control,nullptr,x,y,width,height, + SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOREDRAW); + }; + for (int i = 0; i < 2; ++i) + { + int x = i ? middle + 2 : 0; + int end = i ? width : middle - 2; + place(panels[i].path, x + 5, 4, std::max(0, end - x - 10), textHeight); + int headingHeight=panels[i].wide?textHeight:0; + place(panels[i].heading,x+3,textHeight+10,std::max(0,end-x-11),headingHeight); + ShowWindow(panels[i].heading,panels[i].wide?SW_SHOWNA:SW_HIDE); + place(panels[i].list, x + 3, textHeight+10+headingHeight, std::max(0, end - x - 11), + std::max(0, height-3*textHeight-24-headingHeight)); + } + place(menuBar,0,0,width,textHeight+4); + const int menuEdges[]{0,7,15,27,38,46}; + for(int i=0;i<5;++i) + place(menuItems[i],4+menuEdges[i]*cellWidth,0,(menuEdges[i+1]-menuEdges[i])*cellWidth,textHeight+4); + place(status, 8, height-2*textHeight-8, std::max(0, width - 16), textHeight); + for (int i = 0; i < 5; ++i) + place(commands[i], i * width / 5, height-textHeight, (i+1)*width/5-i*width/5, textHeight); + RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN); +} + +void setStatus(const std::wstring &message) { SetWindowTextW(status, message.c_str()); } + +void showFileDetails(const Panel &panel) +{ + auto row=SendMessageW(panel.list,LB_GETCURSEL,0,0); + if(!panel.wide || !showDetails || row<0 || static_cast(row)>=panel.rows.size()) + { + setStatus(L""); + return; + } + const auto &path=panel.rows[row]; + WIN32_FILE_ATTRIBUTE_DATA data{}; + SYSTEMTIME modified{}; + wchar_t date[64]{}; + if(GetFileAttributesExW(path.c_str(),GetFileExInfoStandard,&data) && + FileTimeToSystemTime(&data.ftLastWriteTime,&modified)) + { + SYSTEMTIME local{}; + if(SystemTimeToTzSpecificLocalTime(nullptr,&modified,&local)) + swprintf_s(date,L" %04u-%02u-%02u %02u:%02u",unsigned(local.wYear), + unsigned(local.wMonth),unsigned(local.wDay),unsigned(local.wHour),unsigned(local.wMinute)); + } + std::wstring details; + if(statusFields&1) details=path.filename().wstring(); + if(statusFields&2) + { + const auto &size=panel.sizes[row]; + details+=L" "+(size==L"Folder" || size==L"Up"?size:formatSize(std::stoull(size))); + } + std::wstring timestamp=date; + if((statusFields&4) && timestamp.size()>=12) details+=timestamp.substr(0,12); + if((statusFields&8) && timestamp.size()>=18) details+=timestamp.substr(12); + setStatus(details); +} + +void open(Panel &panel, const fs::path &directory, bool offerElevation=false) +{ + const auto previousDirectory=panel.directory; + WIN32_FIND_DATAW data{}; + const auto search=FindFirstFileW((directory/L"*").c_str(),&data); + auto error=search==INVALID_HANDLE_VALUE ? GetLastError() : ERROR_SUCCESS; + std::vector folders, files; + std::map metadata; + if (error!=ERROR_SUCCESS && error!=ERROR_FILE_NOT_FOUND) + { + const bool denied=error==ERROR_ACCESS_DENIED; + setStatus(denied ? L"Access denied: " + directory.wstring() : + L"Cannot open folder: " + directory.wstring()); + if(offerElevation && denied && !IsUserAnAdmin()) + { + auto owner=GetParent(panel.list); + auto path=directory.wstring(); + const TASKDIALOG_BUTTON buttons[]{{IDYES,L"Continue as administrator"},{IDCANCEL,L"Skip"}}; + TASKDIALOGCONFIG dialog{}; + dialog.cbSize=sizeof(dialog); + dialog.hwndParent=owner; + dialog.dwFlags=TDF_ALLOW_DIALOG_CANCELLATION|TDF_POSITION_RELATIVE_TO_WINDOW; + dialog.pszWindowTitle=L"KSwitcher Files"; + dialog.pszMainInstruction=L"Windows denied access to this folder"; + dialog.pszContent=path.c_str(); + dialog.pszVerificationText=L"Remember Continue for this session (Windows may still ask for UAC)"; + dialog.cButtons=static_cast(std::size(buttons)); + dialog.pButtons=buttons; + dialog.nDefaultButton=IDCANCEL; + BOOL skip{}; + int choice=IDYES; + if(!rememberElevationApproval && FAILED(TaskDialogIndirect(&dialog,&choice,nullptr,&skip))) + choice=MessageBoxW(owner,(path+L"\n\nTry opening as administrator?").c_str(), + L"KSwitcher Files",MB_YESNO|MB_DEFBUTTON2|MB_ICONQUESTION); + if(choice==IDYES) + { + const auto result=requestElevatedFolder(owner,directory,folders,files,metadata); + SetForegroundWindow(owner); + SetFocus(panel.list); + if(result!=ERROR_SUCCESS) + { + setStatus(result==ERROR_ACCESS_DENIED ? L"Windows denied access after elevation: "+path : + L"Could not read folder as administrator ("+std::to_wstring(result)+L"): "+path); + return; + } + rememberElevationApproval=rememberElevationApproval || skip!=FALSE; + error=ERROR_SUCCESS; + } + } + if(error) return; + } + if(search!=INVALID_HANDLE_VALUE) + { + do + { + const std::wstring_view name(data.cFileName); + if(name==L"." || name==L"..") continue; + const auto path=directory/name; + const auto size=(static_cast(data.nFileSizeHigh)<<32)|data.nFileSizeLow; + (data.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY?folders:files).push_back(path); + metadata.emplace(path,FolderEntryMetadata{data.dwFileAttributes,size}); + } while(FindNextFileW(search,&data)); + error=GetLastError(); + FindClose(search); + } + std::sort(folders.begin(), folders.end()); + std::sort(files.begin(), files.end()); + panel.directory = directory; + panel.rows.clear(); + panel.sizes.clear(); + panel.dimmed.clear(); + panel.marked.clear(); + SendMessageW(panel.list, LB_RESETCONTENT, 0, 0); + auto add = [&](const fs::path &path, const std::wstring &label, bool folder) + { + if (SendMessageW(panel.list, LB_ADDSTRING, 0, reinterpret_cast(label.c_str())) >= 0) + { + panel.rows.push_back(path); + panel.marked.push_back(false); + const auto entry=label==L".." ? FolderEntryMetadata{} : metadata.at(path); + panel.dimmed.push_back((entry.attributes&(FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_HIDDEN))!=0); + panel.sizes.push_back(folder ? (label==L".." ? L"Up" : L"Folder") : + std::to_wstring(entry.size)); + } + }; + if (directory.has_relative_path()) add(directory.parent_path(), L"..", true); + for (const auto &folder : folders) add(folder, L"[" + folder.filename().wstring() + L"]", true); + for (const auto &file : files) add(file, file.filename().wstring(), false); + SetWindowTextW(panel.path, directory.c_str()); + auto selected=panel.rows.begin(); + if(!previousDirectory.empty() && previousDirectory.parent_path()==directory) + { + const auto child=std::find(panel.rows.begin(),panel.rows.end(),previousDirectory); + if(child!=panel.rows.end()) selected=child; + } + SendMessageW(panel.list,LB_SETCURSEL,selected-panel.rows.begin(),0); + if(error!=ERROR_SUCCESS && error!=ERROR_NO_MORE_FILES && error!=ERROR_FILE_NOT_FOUND) + setStatus(L"Some entries could not be read."); + else showFileDetails(panel); +} + +void selectDrive() +{ + auto row=SendMessageW(picker,LB_GETCURSEL,0,0); + hidePicker(); + showMenu(false); + if(commandPicker) + { + if(row<0) return; + auto owner=GetParent(picker); + if(menuIndex==0 || menuIndex==4) + { + int index=menuIndex==4; + if(row==2) chooseDrive(index); + else setMode(index,row==1); + } + else if(menuIndex==3) + { + if(optionsPage==0) + { + if(row==2) chooseDisplayFont(owner); + else openMenu(owner,3,row==0?1:2); + } + else if(optionsPage==1) editWideMode(owner); + else if(optionsPage==2) changeColor(owner,static_cast(row)); + } + else + { + const int command=menuIndex==1?113+static_cast(row):110+static_cast(row); + SendMessageW(owner,WM_COMMAND,MAKEWPARAM(command,BN_CLICKED),0); + } + return; + } + if(row>=0 && static_cast(row)(L'A'+letter),L':',L'\\',0}; + wchar_t volume[MAX_PATH]{}; + const auto type=GetDriveTypeW(drive); + ULARGE_INTEGER total{}, free{}; + if(type==DRIVE_FIXED || type==DRIVE_RAMDISK) + { + GetVolumeInformationW(drive,volume,MAX_PATH,nullptr,nullptr,nullptr,nullptr,0); + GetDiskFreeSpaceExW(drive,&free,&total,nullptr); + } + std::wostringstream columns; + columns << drive << L" " << std::left << std::setw(8) << std::wstring(volume).substr(0, 8); + if(total.QuadPart) + columns << L" " << std::right << std::setw(12) << formatSize(total.QuadPart) + << L" | " << std::setw(12) << formatSize(free.QuadPart) << L" free"; + auto label=columns.str(); + SIZE extent{}; + if(dc && GetTextExtentPoint32W(dc,label.c_str(),static_cast(label.size()),&extent)) + textWidth=std::max(textWidth,static_cast(extent.cx)); + if(fs::path(drive)==panels[index].directory.root_path()) selected=static_cast(drivePaths.size()); + SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast(label.c_str())); + drivePaths.emplace_back(drive); + } + if(dc) + { + if(oldFont) SelectObject(dc,oldFont); + ReleaseDC(picker,dc); + } + if(drivePaths.empty()) return; + HWND owner=GetParent(picker); + RECT panel{}; + GetWindowRect(panels[index].list,&panel); + MapWindowPoints(nullptr,owner,reinterpret_cast(&panel),2); + const int panelWidth=panel.right-panel.left; + const int width=std::clamp(textWidth+24,90,std::max(90,panelWidth*4/5-12)); + const int height=std::min(7,static_cast(drivePaths.size()))*textHeight; + const int x=panel.left+(panel.right-panel.left-width)/2; + const int y=panel.top+(panel.bottom-panel.top-height)/2; + SetWindowPos(pickerFrame,HWND_TOP,x-6,y-textHeight-4,width+12,height+textHeight+11,SWP_SHOWWINDOW); + SetWindowPos(picker,HWND_TOP,x,y,width-5,height,SWP_SHOWWINDOW); + SendMessageW(picker,LB_SETCURSEL,selected,0); + SetFocus(picker); + if (fromMenu) showMenu(true); + RedrawWindow(owner,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN|RDW_UPDATENOW); +} + +void enter(Panel &panel) +{ + auto row = SendMessageW(panel.list, LB_GETCURSEL, 0, 0); + if (row >= 0 && static_cast(row) < panel.rows.size()) + { + auto target = panel.rows[row]; + if(panel.sizes[row]==L"Folder" || panel.sizes[row]==L"Up") open(panel,target,true); + } +} + +enum class ConflictMode { ask, overwrite, skip, rename, append, newer }; + +struct CopyRequest +{ + std::vector sources; + fs::path destination; + fs::path newName; + ConflictMode conflictMode{}; + bool askReadOnly=true; +}; + +HBRUSH warningBrush{}; + +void prepareCopyDialog(HWND dialog) +{ + const auto style=GetWindowLongPtrW(dialog,GWL_STYLE); + SetWindowLongPtrW(dialog,GWL_STYLE,style&~(WS_CAPTION|WS_SYSMENU|WS_THICKFRAME)); + const auto extended=GetWindowLongPtrW(dialog,GWL_EXSTYLE); + SetWindowLongPtrW(dialog,GWL_EXSTYLE,extended&~WS_EX_DLGMODALFRAME); + SetWindowPos(dialog,nullptr,0,0,0,0, + SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE|SWP_FRAMECHANGED); +} + +constexpr LONG dialogFrameInset=10; + +RECT dialogControlBounds(HWND dialog,int id) +{ + RECT bounds{}; + GetWindowRect(GetDlgItem(dialog,id),&bounds); + MapWindowPoints(nullptr,dialog,reinterpret_cast(&bounds),2); + return bounds; +} + +LONG dialogDividerY(HWND dialog,int id) +{ + const auto bounds=dialogControlBounds(dialog,id); + if(id==214) + { + const auto combo=dialogControlBounds(dialog,213); + const auto name=dialogControlBounds(dialog,211); + return bounds.bottom+std::max(0L,(combo.top-name.bottom-1)/2); + } + if(id==213) return (dialogControlBounds(dialog,211).bottom+bounds.top-1)/2; + return bounds.top-4; +} + +void centerDialogRow(HWND dialog,int upperDivider,int lowerDivider,std::initializer_list controls) +{ + RECT client{}; + GetClientRect(dialog,&client); + const auto top=dialogDividerY(dialog,upperDivider)+1; + const auto bottom=lowerDivider?dialogDividerY(dialog,lowerDivider):client.bottom-dialogFrameInset; + for(const auto id:controls) + { + const auto bounds=dialogControlBounds(dialog,id); + SetWindowPos(GetDlgItem(dialog,id),nullptr,bounds.left,(top+bottom-(bounds.bottom-bounds.top))/2, + 0,0,SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE); + } +} + +void layoutDialogButtons(HWND dialog,int divider,std::initializer_list controls) +{ + RECT client{},window{}; + GetClientRect(dialog,&client); + GetWindowRect(dialog,&window); + const auto footerHeight=2*static_cast(textHeight); + const auto height=dialogDividerY(dialog,divider)+1+footerHeight+dialogFrameInset; + const auto width=window.right-window.left; + const auto outerHeight=window.bottom-window.top+height-client.bottom; + RECT owner{}; + const bool centered=GetWindowRect(GetWindow(dialog,GW_OWNER),&owner)!=FALSE; + SetWindowPos(dialog,nullptr,(owner.left+owner.right-width)/2, + (owner.top+owner.bottom-outerHeight)/2,width,outerHeight, + (centered?0:SWP_NOMOVE)|SWP_NOZORDER|SWP_NOACTIVATE); + centerDialogRow(dialog,divider,0,controls); +} + +void paintDialogButton(const DRAWITEMSTRUCT &item,COLORREF surface,COLORREF foreground) +{ + wchar_t label[32]{}; + GetWindowTextW(item.hwndItem,label,static_cast(std::size(label))); + const bool focused=(item.itemState&(ODS_FOCUS|ODS_SELECTED))!=0; + SetDCBrushColor(item.hDC,focused?colors[Dialog]:surface); + FillRect(item.hDC,&item.rcItem,static_cast(GetStockObject(DC_BRUSH))); + SelectObject(item.hDC,mono); + SetBkMode(item.hDC,TRANSPARENT); + SetTextColor(item.hDC,focused?colors[Text]:foreground); + auto rect=item.rcItem; + const auto caption=L"[ "+std::wstring(label)+L" ]"; + DrawTextW(item.hDC,caption.c_str(),-1,&rect,DT_CENTER|DT_VCENTER|DT_SINGLELINE); +} + +INT_PTR paintCopyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp, + const wchar_t *caption, bool warning, std::initializer_list dividers) +{ + const auto foreground=warning?RGB(255,255,255):RGB(0,0,0); + const auto surface=warning?RGB(128,0,0):RGB(192,192,192); + const auto brush=warning?warningBrush:static_cast(GetStockObject(LTGRAY_BRUSH)); + if(message==WM_CTLCOLORDLG) return reinterpret_cast(brush); + if(message==WM_CTLCOLORSTATIC || message==WM_CTLCOLOREDIT || message==WM_CTLCOLORBTN) + { + const auto dc=reinterpret_cast(wp); + const bool edit=reinterpret_cast(lp)==GetDlgItem(dialog,211); + SetTextColor(dc,edit?colors[Text]:foreground); + SetBkColor(dc,edit?colors[Dialog]:surface); + return reinterpret_cast(edit?teal:brush); + } + if(message==WM_PAINT) + { + PAINTSTRUCT paint{}; + const auto dc=BeginPaint(dialog,&paint); + RECT bounds{}; + GetClientRect(dialog,&bounds); + FillRect(dc,&bounds,brush); + InflateRect(&bounds,-8,-8); + const auto black=static_cast(GetStockObject(warning?WHITE_BRUSH:BLACK_BRUSH)); + FrameRect(dc,&bounds,black); + InflateRect(&bounds,-2,-2); + FrameRect(dc,&bounds,black); + for(const auto control:dividers) + { + const auto y=dialogDividerY(dialog,control); + RECT divider{bounds.left+1,y,bounds.right-1,y+1}; + FillRect(dc,÷r,black); + } + SelectObject(dc,mono); + RECT title{}; + DrawTextW(dc,caption,-1,&title,DT_CALCRECT|DT_SINGLELINE|DT_NOPREFIX); + const auto titleHeight=title.bottom; + const auto top=std::max(0L,bounds.top-titleHeight/2); + title={bounds.left,top,bounds.right,top+titleHeight}; + SetTextColor(dc,foreground); + SetBkColor(dc,surface); + DrawTextW(dc,caption,-1,&title,DT_CENTER|DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX); + EndPaint(dialog,&paint); + return TRUE; + } + if(message==WM_DRAWITEM) + { + const auto &item=*reinterpret_cast(lp); + paintDialogButton(item,surface,foreground); + return TRUE; + } + return FALSE; +} + +LRESULT CALLBACK paintConflictCombo(HWND control,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) +{ + if(message!=WM_PAINT) return DefSubclassProc(control,message,wp,lp); + PAINTSTRUCT paint{}; + const auto dc=BeginPaint(control,&paint); + RECT bounds{}; + GetClientRect(control,&bounds); + wchar_t label[64]{}; + const auto selected=SendMessageW(control,CB_GETCURSEL,0,0); + if(selected!=CB_ERR) SendMessageW(control,CB_GETLBTEXT,selected,reinterpret_cast(label)); + auto arrow=bounds; + arrow.left=std::max(bounds.left,bounds.right-2*static_cast(cellWidth)); + bounds.right=arrow.left; + SetDCBrushColor(dc,colors[Dialog]); + FillRect(dc,&bounds,static_cast(GetStockObject(DC_BRUSH))); + FillRect(dc,&arrow,static_cast(GetStockObject(DC_BRUSH))); + SelectObject(dc,mono); + SetBkMode(dc,TRANSPARENT); + SetTextColor(dc,colors[Text]); + bounds.left+=5; + DrawTextW(dc,label,-1,&bounds,DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS|DT_NOPREFIX); + DrawTextW(dc,L"↓",-1,&arrow,DT_SINGLELINE|DT_VCENTER|DT_CENTER); + if(GetFocus()==control) DrawFocusRect(dc,&bounds); + EndPaint(control,&paint); + return 0; +} + +INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp) +{ + constexpr int summary=210, pathField=211, conflicts=212; + if(message==WM_DRAWITEM && wp==214) + { + const auto &item=*reinterpret_cast(lp); + const auto request=reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + const bool checked=request && request->askReadOnly; + paintText(item.hDC,item.rcItem,checked?L"[x] Also ask on read-only files": + L"[ ] Also ask on read-only files",RGB(0,0,0),RGB(192,192,192)); + if(item.itemState&ODS_FOCUS) DrawFocusRect(item.hDC,&item.rcItem); + return TRUE; + } + if(message==WM_DRAWITEM && wp==213) + { + const auto &item=*reinterpret_cast(lp); + wchar_t label[64]{}; + if(item.itemID!=UINT(-1)) + SendMessageW(item.hwndItem,CB_GETLBTEXT,item.itemID,reinterpret_cast(label)); + const bool selected=(item.itemState&ODS_SELECTED)!=0 && (item.itemState&ODS_COMBOBOXEDIT)==0; + paintText(item.hDC,item.rcItem,label,colors[Text],colors[selected?Selection:Dialog]); + return TRUE; + } + if(message==WM_CTLCOLORLISTBOX) + { + const auto dc=reinterpret_cast(wp); + SetTextColor(dc,colors[Text]); + SetBkColor(dc,colors[Dialog]); + return reinterpret_cast(teal); + } + if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" Copy ",false,{213,214})) + return painted; + if(message==WM_INITDIALOG) + { + auto &request=*reinterpret_cast(lp); + prepareCopyDialog(dialog); + SetWindowLongPtrW(dialog,DWLP_USER,lp); + for(const auto label:{L"Ask",L"Overwrite",L"Skip",L"Rename",L"Append",L"Only newer file(s)"}) + SendDlgItemMessageW(dialog,213,CB_ADDSTRING,0,reinterpret_cast(label)); + SendDlgItemMessageW(dialog,213,CB_SETCURSEL,0,0); + const auto label=request.sources.size()==1 ? + L"Copy "+request.sources.front().filename().wstring()+L" to:" : + L"Copy "+std::to_wstring(request.sources.size())+L" items to:"; + SetDlgItemTextW(dialog,summary,label.c_str()); + const bool single=request.sources.size()==1; + const auto fieldText=single?request.sources.front().filename():request.destination; + SetDlgItemTextW(dialog,pathField,fieldText.c_str()); + SendDlgItemMessageW(dialog,pathField,EM_SETREADONLY,!single,0); + SendDlgItemMessageW(dialog,pathField,WM_SETFONT,reinterpret_cast(mono),FALSE); + RECT edit{}; + GetClientRect(GetDlgItem(dialog,pathField),&edit); + const auto field=GetDlgItem(dialog,pathField); + if(const auto dc=GetDC(field)) + { + const auto oldFont=SelectObject(dc,mono); + TEXTMETRICW metrics{}; + if(GetTextMetricsW(dc,&metrics)) + edit.top=std::max(0L,(edit.bottom-metrics.tmHeight)/2); + SelectObject(dc,oldFont); + ReleaseDC(field,dc); + } + edit.left+=2; + edit.right-=2; + SendDlgItemMessageW(dialog,pathField,EM_SETRECT,0,reinterpret_cast(&edit)); + layoutDialogButtons(dialog,214,{IDOK,IDCANCEL}); + SendDlgItemMessageW(dialog,summary,WM_SETFONT,reinterpret_cast(mono),FALSE); + SendDlgItemMessageW(dialog,conflicts,WM_SETFONT,reinterpret_cast(mono),FALSE); + for(const auto control:{213,214}) + SendDlgItemMessageW(dialog,control,WM_SETFONT,reinterpret_cast(mono),FALSE); + SendDlgItemMessageW(dialog,213,CB_SETITEMHEIGHT,0,textHeight); + SendDlgItemMessageW(dialog,213,CB_SETITEMHEIGHT,static_cast(-1),textHeight+2); + RECT combo{}, caption{}; + const auto captionControl=GetDlgItem(dialog,conflicts); + GetWindowRect(GetDlgItem(dialog,213),&combo); + GetWindowRect(captionControl,&caption); + MapWindowPoints(nullptr,dialog,reinterpret_cast(&combo),2); + MapWindowPoints(nullptr,dialog,reinterpret_cast(&caption),2); + SetWindowPos(captionControl,nullptr,caption.left,combo.top, + caption.right-caption.left,combo.bottom-combo.top,SWP_NOZORDER|SWP_NOACTIVATE); + SetWindowSubclass(GetDlgItem(dialog,213),paintConflictCombo,1,0); + SendMessageW(dialog,DM_SETDEFID,IDOK,0); + SendDlgItemMessageW(dialog,pathField,EM_SETSEL,0,-1); + return TRUE; + } + if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL)) + { + EndDialog(dialog,IDCANCEL); + return TRUE; + } + if(message!=WM_COMMAND) return FALSE; + auto &request=*reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + if(LOWORD(wp)==214 && HIWORD(wp)==BN_CLICKED) + { + request.askReadOnly=!request.askReadOnly; + InvalidateRect(GetDlgItem(dialog,214),nullptr,FALSE); + return TRUE; + } + if(LOWORD(wp)==213) + { + InvalidateRect(GetDlgItem(dialog,213),nullptr,FALSE); + return FALSE; + } + if(LOWORD(wp)!=IDOK) return FALSE; + if(request.sources.size()==1) + { + const auto field=GetDlgItem(dialog,pathField); + std::wstring name(GetWindowTextLengthW(field)+1,L'\0'); + name.resize(GetWindowTextW(field,name.data(),static_cast(name.size()))); + if(name.empty() || name.back()==L'.' || name.back()==L' ' || + name.find_first_of(L"<>:\"/\\|?*")!=name.npos || + std::any_of(name.begin(),name.end(),[](wchar_t ch){return ch<32;})) + { + MessageBoxW(dialog,L"Enter a valid name for the copy.",L"Copy",MB_OK|MB_ICONWARNING); + SetFocus(field); + return TRUE; + } + if(CompareStringOrdinal(name.c_str(),-1,request.sources.front().filename().c_str(),-1,TRUE)!=CSTR_EQUAL) + request.newName=name; + else request.newName.clear(); + } + const auto sourceDirectory=request.sources.front().parent_path(); + const auto destination=request.newName.empty()?request.destination:sourceDirectory; + std::error_code error; + if(!fs::is_directory(destination,error)) + { + MessageBoxW(dialog,L"The destination folder is unavailable.",L"Copy",MB_OK|MB_ICONWARNING); + return TRUE; + } + if(request.newName.empty() && fs::equivalent(destination,sourceDirectory,error)) + { + MessageBoxW(dialog,L"Open a different folder in the other panel, or enter a new name for a single item.", + L"Copy",MB_OK|MB_ICONWARNING); + return TRUE; + } + const auto mode=SendDlgItemMessageW(dialog,213,CB_GETCURSEL,0,0); + if(mode!=CB_ERR) request.conflictMode=static_cast(mode); + EndDialog(dialog,IDOK); + return TRUE; +} + +struct CopyProgress +{ + HWND window{}; + bool canceled{}; + bool closeOwner{}; + int conflictChoice{}; + ConflictMode conflictMode{}; + bool askReadOnly=true; + uint64_t files{}, totalFiles{}, bytes{}, totalBytes{}; + uint64_t skippedFiles{}, skippedBytes{}; + const wchar_t *lastSkipReason=L""; + ULONGLONG lastPaint{}; + fs::path from,to; +}; +bool copyInProgress{}; +CopyProgress *activeCopy{}; +RECT previousOwnerBounds{}; + +struct OwnedWindowMove +{ + HWND owner; + LONG dx,dy; +}; + +BOOL CALLBACK moveOwnedDialog(HWND window,LPARAM parameter) +{ + const auto &move=*reinterpret_cast(parameter); + if(window==move.owner || !IsWindowVisible(window) || + GetAncestor(window,GA_ROOTOWNER)!=move.owner) return TRUE; + RECT bounds{}; + if(GetWindowRect(window,&bounds)) + SetWindowPos(window,nullptr,bounds.left+move.dx,bounds.top+move.dy,0,0, + SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE); + return TRUE; +} + +LRESULT CALLBACK paintCopyProgressBar(HWND bar,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) +{ + if(message!=WM_PAINT) return DefSubclassProc(bar,message,wp,lp); + PAINTSTRUCT paint{}; + const auto dc=BeginPaint(bar,&paint); + RECT bounds{}; + GetClientRect(bar,&bounds); + const auto percent=std::clamp(SendMessageW(bar,PBM_GETPOS,0,0),LRESULT{0},LRESULT{100}); + auto filled=bounds; + filled.right=static_cast(bounds.right*percent/100); + FillRect(dc,&bounds,static_cast(GetStockObject(WHITE_BRUSH))); + FillRect(dc,&filled,static_cast(GetStockObject(BLACK_BRUSH))); + const auto label=std::to_wstring(percent)+L"%"; + SelectObject(dc,mono); + SetBkMode(dc,TRANSPARENT); + constexpr auto flags=DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX; + SetTextColor(dc,RGB(0,0,0)); + auto labelBounds=bounds; + DrawTextW(dc,label.c_str(),-1,&labelBounds,flags); + const auto saved=SaveDC(dc); + if(saved) + { + IntersectClipRect(dc,filled.left,filled.top,filled.right,filled.bottom); + SetTextColor(dc,RGB(255,255,255)); + labelBounds=bounds; + DrawTextW(dc,label.c_str(),-1,&labelBounds,flags); + RestoreDC(dc,saved); + } + EndPaint(bar,&paint); + return 0; +} + +void updateCopyProgress(CopyProgress &progress,uint64_t current,uint64_t fileSize,bool force=false) +{ + constexpr ULONGLONG refreshIntervalMs=200; + const auto now=GetTickCount64(); + if(!force && now-progress.lastPaint(100.0*std::min(done,total)/total):0; + }; + const auto updateBar=[&](int bar,int value) + { + const auto control=GetDlgItem(progress.window,bar); + SendMessageW(control,PBM_SETPOS,value,0); + InvalidateRect(control,nullptr,FALSE); + }; + const auto bytes=progress.bytes+current; + updateBar(222,fileSize?percent(current,fileSize):0); + updateBar(226,progress.totalBytes? + percent(bytes+progress.skippedBytes,progress.totalBytes): + percent(progress.files+progress.skippedFiles,progress.totalFiles)); + SetDlgItemTextW(progress.window,224,(L"Files: "+std::to_wstring(progress.files)+L" / "+ + std::to_wstring(progress.totalFiles)+(progress.skippedFiles? + L" Skipped: "+std::to_wstring(progress.skippedFiles)+L" ("+progress.lastSkipReason+L")":L"")).c_str()); + SetDlgItemTextW(progress.window,225,(L"Size: "+formatSize(bytes)+L" / "+ + formatSize(progress.totalBytes)).c_str()); +} + +INT_PTR CALLBACK cancelCopyDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) +{ + if(const auto painted=paintCopyDialog(window,message,wp,lp,L" Operation interrupted ",true,{236})) + return painted; + if(message==WM_INITDIALOG) + { + prepareCopyDialog(window); + SendDlgItemMessageW(window,235,WM_SETFONT,reinterpret_cast(mono),FALSE); + layoutDialogButtons(window,236,{IDYES,IDNO}); + SendMessageW(window,DM_SETDEFID,IDNO,0); + SetFocus(GetDlgItem(window,IDNO)); + return FALSE; + } + if(message==WM_CLOSE || (message==WM_COMMAND && + (LOWORD(wp)==IDYES || LOWORD(wp)==IDNO || LOWORD(wp)==IDCANCEL))) + { + EndDialog(window,message==WM_COMMAND && LOWORD(wp)==IDYES?IDYES:IDNO); + return TRUE; + } + return FALSE; +} + +INT_PTR CALLBACK copyProgressDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) +{ + if(message==WM_DRAWITEM && (wp==220 || wp==221)) + { + const auto &item=*reinterpret_cast(lp); + std::wstring path(GetWindowTextLengthW(item.hwndItem)+1,L'\0'); + GetWindowTextW(item.hwndItem,path.data(),static_cast(path.size())); + auto bounds=item.rcItem; + FillRect(item.hDC,&bounds,static_cast(GetStockObject(LTGRAY_BRUSH))); + SelectObject(item.hDC,mono); + SetBkMode(item.hDC,TRANSPARENT); + SetTextColor(item.hDC,RGB(0,0,0)); + constexpr auto flags=DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX; + const int prefix=wp==220?6:4; + if(GetWindowTextLengthW(item.hwndItem)>prefix && path[prefix-2]==L':') + { + SIZE width{}; + GetTextExtentPoint32W(item.hDC,path.data(),prefix,&width); + DrawTextW(item.hDC,path.data(),prefix,&bounds,flags); + bounds.left+=width.cx; + DrawTextW(item.hDC,path.data()+prefix,-1,&bounds,flags|DT_PATH_ELLIPSIS|DT_END_ELLIPSIS); + } + else DrawTextW(item.hDC,path.data(),-1,&bounds,flags|DT_END_ELLIPSIS); + return TRUE; + } + if(const auto painted=paintCopyDialog(window,message,wp,lp,L" Copy ",false,{228,229})) + return painted; + if(message==WM_DPICHANGED) + { + PostMessageW(window,refreshProgressLayout,0,0); + return FALSE; + } + if(message==WM_INITDIALOG || message==refreshProgressLayout) + { + if(message==WM_INITDIALOG) + { + prepareCopyDialog(window); + SetWindowLongPtrW(window,DWLP_USER,lp); + } + for(const auto control:{220,221,224,225}) + { + SendDlgItemMessageW(window,control,WM_SETFONT,reinterpret_cast(mono),FALSE); + const auto bounds=dialogControlBounds(window,control); + SetWindowPos(GetDlgItem(window,control),nullptr,0,0,bounds.right-bounds.left,textHeight, + SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE); + } + for(const auto id:{222,226}) + { + const auto bar=GetDlgItem(window,id); + const auto bounds=dialogControlBounds(window,id); + SetWindowPos(bar,nullptr,0,0,bounds.right-bounds.left,textHeight+8, + SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE); + SetWindowSubclass(bar,paintCopyProgressBar,1,0); + } + const auto moveRow=[&](int id,LONG top) + { + const auto bounds=dialogControlBounds(window,id); + SetWindowPos(GetDlgItem(window,id),nullptr,bounds.left,top,0,0, + SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE); + }; + const auto padding=dialogControlBounds(window,220).top-dialogFrameInset-1; + moveRow(221,std::max(dialogControlBounds(window,221).top,dialogControlBounds(window,220).bottom)); + moveRow(222,std::max(dialogControlBounds(window,222).top,dialogControlBounds(window,221).bottom+4)); + const auto firstBottom=dialogControlBounds(window,222).bottom; + moveRow(228,firstBottom+padding+4); + const auto offset=dialogDividerY(window,228)+1+padding-dialogControlBounds(window,224).top; + for(const auto id:{224,225,226}) + moveRow(id,dialogControlBounds(window,id).top+offset); + moveRow(225,std::max(dialogControlBounds(window,225).top,dialogControlBounds(window,224).bottom)); + moveRow(226,std::max(dialogControlBounds(window,226).top,dialogControlBounds(window,225).bottom+4)); + const auto secondBottom=dialogControlBounds(window,226).bottom; + moveRow(229,secondBottom+padding+4); + layoutDialogButtons(window,229,{IDCANCEL}); + RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN); + return TRUE; + } + if(message==WM_NCHITTEST) + { + RECT bounds{}; + GetWindowRect(window,&bounds); + if(GET_Y_LPARAM(lp)(GetWindowLongPtrW(window,DWLP_USER)); + if(!progress.canceled) + { + warningBrush=CreateSolidBrush(RGB(128,0,0)); + const auto answer=DialogBoxParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(105),window,cancelCopyDialog,0); + DeleteObject(warningBrush); + warningBrush=nullptr; + progress.canceled=answer==IDYES; + } + return TRUE; +} + +struct WarningPrompt +{ + const wchar_t *message; + const wchar_t *details; + const wchar_t *accept; + const wchar_t *decline; + bool remember{}; +}; + +LRESULT CALLBACK warningButtonKeys(HWND button,UINT message,WPARAM wp,LPARAM lp, + UINT_PTR,DWORD_PTR index) +{ + if(message==WM_GETDLGCODE) + { + const auto key=reinterpret_cast(lp); + return DefSubclassProc(button,message,wp,lp)|DLGC_WANTARROWS| + (key && key->message==WM_KEYDOWN && key->wParam==VK_RETURN?DLGC_WANTMESSAGE:0); + } + if(message==WM_KEYDOWN && wp==VK_RETURN) + { + SendMessageW(button,BM_CLICK,0,0); + return 0; + } + if(message==WM_KEYDOWN && (wp==VK_UP || wp==VK_DOWN)) + { + if(index<3 && wp==VK_UP) SetFocus(GetDlgItem(GetParent(button),232)); + if(index==3 && wp==VK_DOWN) SetFocus(GetDlgItem(GetParent(button),IDYES)); + return 0; + } + if(message==WM_KEYDOWN && index<3 && (wp==VK_LEFT || wp==VK_RIGHT)) + { + constexpr int buttons[]{IDYES,IDNO,IDCANCEL}; + SetFocus(GetDlgItem(GetParent(button),buttons[(index+(wp==VK_LEFT?2:1))%3])); + return 0; + } + return DefSubclassProc(button,message,wp,lp); +} + +INT_PTR CALLBACK warningDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) +{ + if(message==WM_DRAWITEM && wp==232) + { + const auto &item=*reinterpret_cast(lp); + const auto warning=reinterpret_cast(GetWindowLongPtrW(window,DWLP_USER)); + auto bounds=item.rcItem; + FillRect(item.hDC,&bounds,warningBrush); + SelectObject(item.hDC,mono); + SetBkMode(item.hDC,TRANSPARENT); + SetTextColor(item.hDC,RGB(255,255,255)); + bounds.left+=5; + DrawTextW(item.hDC,warning && warning->remember?L"[x] Remember choice":L"[ ] Remember choice", + -1,&bounds,DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX); + if(item.itemState&ODS_FOCUS) DrawFocusRect(item.hDC,&item.rcItem); + return TRUE; + } + if(const auto painted=paintCopyDialog(window,message,wp,lp,L" Warning ",true,{233,234})) + return painted; + if(message==WM_INITDIALOG) + { + prepareCopyDialog(window); + SetWindowLongPtrW(window,DWLP_USER,lp); + const auto &warning=*reinterpret_cast(lp); + SetDlgItemTextW(window,230,warning.message); + SetDlgItemTextW(window,231,warning.details); + SetDlgItemTextW(window,IDYES,warning.accept); + SetDlgItemTextW(window,IDNO,warning.decline); + for(const auto control:{230,231,232}) + SendDlgItemMessageW(window,control,WM_SETFONT,reinterpret_cast(mono),FALSE); + centerDialogRow(window,233,234,{232}); + layoutDialogButtons(window,234,{IDYES,IDNO,IDCANCEL}); + SendMessageW(window,DM_SETDEFID,IDNO,0); + constexpr int buttons[]{IDYES,IDNO,IDCANCEL}; + for(size_t i=0;i(GetWindowLongPtrW(window,DWLP_USER)); + warning.remember=!warning.remember; + InvalidateRect(GetDlgItem(window,232),nullptr,FALSE); + return TRUE; + } + if(message==WM_COMMAND && (LOWORD(wp)==IDYES || LOWORD(wp)==IDNO || LOWORD(wp)==IDCANCEL)) + { + const auto choice=LOWORD(wp); + EndDialog(window,choice); + return TRUE; + } + return FALSE; +} + +bool pumpCopy(CopyProgress &progress) +{ + MSG message{}; + while(!progress.canceled && PeekMessageW(&message,nullptr,0,0,PM_REMOVE)) + { + if(message.message==WM_QUIT) + { + PostQuitMessage(static_cast(message.wParam)); + progress.canceled=true; + break; + } + const auto owner=GetWindow(progress.window,GW_OWNER); + const bool inMainWindow=message.hwnd==owner || IsChild(owner,message.hwnd); + if(inMainWindow && + ((message.message>=WM_KEYFIRST && message.message<=WM_KEYLAST) || + (message.message>=WM_MOUSEFIRST && message.message<=WM_MOUSELAST))) + { + if(message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE) + SendMessageW(progress.window,WM_COMMAND,IDCANCEL,0); + else if(message.message==WM_SYSKEYDOWN && message.wParam==VK_F4) + SendMessageW(owner,WM_CLOSE,0,0); + continue; + } + const bool inProgressWindow=message.hwnd==progress.window || IsChild(progress.window,message.hwnd); + if(!inProgressWindow || !IsDialogMessageW(progress.window,&message)) + { + TranslateMessage(&message); + DispatchMessageW(&message); + } + } + return !progress.canceled; +} + +DWORD CALLBACK copyProgressCallback(LARGE_INTEGER total,LARGE_INTEGER transferred,LARGE_INTEGER,LARGE_INTEGER, + DWORD,DWORD,HANDLE,HANDLE,LPVOID context) +{ + auto &progress=*static_cast(context); + updateCopyProgress(progress,transferred.QuadPart,total.QuadPart); + return pumpCopy(progress)?PROGRESS_CONTINUE:PROGRESS_CANCEL; +} + +bool countCopy(const fs::path &path,CopyProgress &progress) +{ + if(!pumpCopy(progress)) return false; + WIN32_FILE_ATTRIBUTE_DATA data{}; + if(!GetFileAttributesExW(path.c_str(),GetFileExInfoStandard,&data) || + (data.dwFileAttributes&FILE_ATTRIBUTE_REPARSE_POINT)) return false; + if(!(data.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)) + { + ++progress.totalFiles; + progress.totalBytes+=(static_cast(data.nFileSizeHigh)<<32)|data.nFileSizeLow; + return true; + } + std::error_code error; + for(fs::directory_iterator it(path,error),end;!error && it!=end;it.increment(error)) + if(!countCopy(it->path(),progress)) return false; + return !error; +} + +enum class CopyResult { complete, skipped, failed }; + +CopyResult copyItem(const fs::path &from,const fs::path &to,CopyProgress &progress) +{ + if(!pumpCopy(progress)) return CopyResult::failed; + const auto attributes=GetFileAttributesW(from.c_str()); + if(attributes==INVALID_FILE_ATTRIBUTES || (attributes&FILE_ATTRIBUTE_REPARSE_POINT)) + return CopyResult::failed; + std::error_code error; + if(attributes&FILE_ATTRIBUTE_DIRECTORY) + { + const auto target=GetFileAttributesW(to.c_str()); + if(target!=INVALID_FILE_ATTRIBUTES && + (!(target&FILE_ATTRIBUTE_DIRECTORY) || (target&FILE_ATTRIBUTE_REPARSE_POINT))) + return CopyResult::failed; + fs::create_directory(to,error); + if(error) return CopyResult::failed; + auto result=CopyResult::complete; + for(fs::directory_iterator it(from,error),end;!error && it!=end;it.increment(error)) + { + const auto child=copyItem(it->path(),to/it->path().filename(),progress); + if(child==CopyResult::failed) return child; + if(child==CopyResult::skipped) result=child; + } + return error?CopyResult::failed:result; + } + + progress.from=from; + progress.to=to; + const auto fileSize=fs::file_size(from,error); + if(error) return CopyResult::failed; + const auto complete=[&]() + { + progress.bytes+=fileSize; + ++progress.files; + updateCopyProgress(progress,0,0); + return CopyResult::complete; + }; + const auto skip=[&](const wchar_t *reason) + { + progress.skippedBytes+=fileSize; + ++progress.skippedFiles; + progress.lastSkipReason=reason; + updateCopyProgress(progress,0,0); + return CopyResult::skipped; + }; + updateCopyProgress(progress,0,fileSize); + if(CopyFileExW(from.c_str(),to.c_str(),copyProgressCallback,&progress,nullptr,COPY_FILE_FAIL_IF_EXISTS)) + return complete(); + const auto code=GetLastError(); + if(progress.canceled || (code!=ERROR_FILE_EXISTS && code!=ERROR_ALREADY_EXISTS && code!=ERROR_ACCESS_DENIED) || + fs::equivalent(from,to,error)) return CopyResult::failed; + WIN32_FILE_ATTRIBUTE_DATA existing{}; + if(!GetFileAttributesExW(to.c_str(),GetFileExInfoStandard,&existing) || + (existing.dwFileAttributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT))) + return CopyResult::failed; + const bool readOnly=(existing.dwFileAttributes&FILE_ATTRIBUTE_READONLY)!=0; + auto mode=progress.conflictMode; + if(readOnly && progress.askReadOnly) mode=ConflictMode::ask; + if(mode==ConflictMode::skip) return skip(L"existing file"); + if(mode==ConflictMode::newer) + { + WIN32_FILE_ATTRIBUTE_DATA incoming{}; + if(!GetFileAttributesExW(from.c_str(),GetFileExInfoStandard,&incoming)) return CopyResult::failed; + if(CompareFileTime(&incoming.ftLastWriteTime,&existing.ftLastWriteTime)<=0) + return skip(L"source is not newer"); + } + if(mode==ConflictMode::rename) + { + for(unsigned index=2;index<=10000;++index) + { + const auto name=to.stem().wstring()+L" ("+std::to_wstring(index)+L")"+to.extension().wstring(); + const auto candidate=to.parent_path()/name; + if(CopyFileExW(from.c_str(),candidate.c_str(),copyProgressCallback,&progress,nullptr,COPY_FILE_FAIL_IF_EXISTS)) + return complete(); + const auto renameError=GetLastError(); + if(progress.canceled || (renameError!=ERROR_FILE_EXISTS && renameError!=ERROR_ALREADY_EXISTS)) + break; + } + return CopyResult::failed; + } + const bool forceAsk=readOnly && progress.askReadOnly && progress.conflictMode!=ConflictMode::ask; + auto answer=mode==ConflictMode::ask?(forceAsk?0:static_cast(progress.conflictChoice)):IDYES; + if(!answer) + { + WarningPrompt warning{readOnly?L"Existing file is read-only":L"File already exists", + to.c_str(),L"&Overwrite",L"&Skip"}; + warningBrush=CreateSolidBrush(RGB(128,0,0)); + answer=DialogBoxParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(104),progress.window, + warningDialog,reinterpret_cast(&warning)); + if(warning.remember && (answer==IDYES || answer==IDNO)) + progress.conflictChoice=static_cast(answer); + DeleteObject(warningBrush); + warningBrush=nullptr; + } + if(answer==IDNO) return skip(readOnly?L"read-only conflict":L"conflict choice"); + if(answer!=IDYES) + { + progress.canceled=answer==IDCANCEL; + return CopyResult::failed; + } + + GUID id{}; + wchar_t name[40]{}; + if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,static_cast(std::size(name)))) + return CopyResult::failed; + const auto temporary=to.parent_path()/(std::wstring(name)+L".tmp"); + if(mode==ConflictMode::append) + { + Handle input{CreateFileW(from.c_str(),GENERIC_READ,FILE_SHARE_READ,nullptr,OPEN_EXISTING,0,nullptr)}; + if(input.value==INVALID_HANDLE_VALUE || + !CopyFileExW(to.c_str(),temporary.c_str(),nullptr,nullptr,nullptr,COPY_FILE_FAIL_IF_EXISTS)) + return CopyResult::failed; + if(readOnly && !SetFileAttributesW(temporary.c_str(), + (existing.dwFileAttributes&~FILE_ATTRIBUTE_READONLY)|FILE_ATTRIBUTE_ARCHIVE)) + { + SetFileAttributesW(temporary.c_str(),FILE_ATTRIBUTE_NORMAL); + DeleteFileW(temporary.c_str()); + return CopyResult::failed; + } + bool appended=false; + { + Handle output{CreateFileW(temporary.c_str(),FILE_APPEND_DATA,0,nullptr,OPEN_EXISTING,0,nullptr)}; + char buffer[65536]; + uint64_t transferred=0; + while(output.value!=INVALID_HANDLE_VALUE && pumpCopy(progress)) + { + DWORD read{},written{}; + if(!ReadFile(input.value,buffer,sizeof(buffer),&read,nullptr)) break; + if(!read) { appended=true; break; } + if(!WriteFile(output.value,buffer,read,&written,nullptr) || written!=read) break; + transferred+=written; + LARGE_INTEGER total{},done{},unused{}; + total.QuadPart=fileSize; + done.QuadPart=transferred; + if(copyProgressCallback(total,done,unused,unused,0,0,nullptr,nullptr,&progress)==PROGRESS_CANCEL) break; + } + } + if(!appended) + { + DeleteFileW(temporary.c_str()); + return CopyResult::failed; + } + } + else if(!CopyFileExW(from.c_str(),temporary.c_str(),copyProgressCallback,&progress,nullptr,COPY_FILE_FAIL_IF_EXISTS)) + return CopyResult::failed; + if(readOnly && !SetFileAttributesW(to.c_str(),existing.dwFileAttributes&~FILE_ATTRIBUTE_READONLY)) + { + DeleteFileW(temporary.c_str()); + return CopyResult::failed; + } + if(MoveFileExW(temporary.c_str(),to.c_str(),MOVEFILE_REPLACE_EXISTING)) return complete(); + if(readOnly) SetFileAttributesW(to.c_str(),existing.dwFileAttributes); + DeleteFileW(temporary.c_str()); + return CopyResult::failed; +} + +void copySelection(HWND owner,Panel &source,Panel &destination) +{ + if(copyInProgress) + { + setStatus(L"A copy is already in progress."); + return; + } + CopyRequest request{{},destination.directory}; + for(size_t i=0;i(row)>=source.rows.size() || source.sizes[row]==L"Up") return; + request.sources.push_back(source.rows[row]); + } + const auto result=DialogBoxParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(102),owner,copyDialog, + reinterpret_cast(&request)); + if(result==-1) setStatus(L"Could not open the Copy dialog."); + if(result!=IDOK) return; + + const bool renamed=!request.newName.empty(); + const auto targetDirectory=renamed?request.sources.front().parent_path():request.destination; + CopyProgress progress; + progress.conflictMode=request.conflictMode; + progress.askReadOnly=request.askReadOnly; + progress.window=CreateDialogParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(103),owner, + copyProgressDialog,reinterpret_cast(&progress)); + if(!progress.window) + { + setStatus(L"Could not open copy progress."); + return; + } + copyInProgress=true; + activeCopy=&progress; + for(auto &panel:panels) EnableWindow(panel.list,FALSE); + for(const auto command:commands) EnableWindow(command,FALSE); + GetWindowRect(owner,&previousOwnerBounds); + ShowWindow(progress.window,SW_SHOW); + bool failed=false, skipped=false; + size_t copied=0; + for(const auto &path:request.sources) + if(!countCopy(path,progress)) { failed=true; break; } + updateCopyProgress(progress,0,0,true); + for(const auto &path:request.sources) + { + if(failed) break; + const auto to=targetDirectory/(renamed?request.newName:path.filename()); + std::error_code error; + const auto canonicalSource=fs::weakly_canonical(path,error); + if(error) { failed=true; break; } + const auto canonicalTarget=fs::weakly_canonical(to,error); + if(error) { failed=true; break; } + for(auto ancestor=canonicalTarget;;ancestor=ancestor.parent_path()) + { + if(CompareStringOrdinal(ancestor.c_str(),-1,canonicalSource.c_str(),-1,TRUE)==CSTR_EQUAL) + { + failed=true; + break; + } + if(!ancestor.has_relative_path()) break; + } + if(failed) break; + const auto outcome=copyItem(path,to,progress); + if(outcome==CopyResult::failed) { failed=true; break; } + if(outcome==CopyResult::skipped) { skipped=true; continue; } + ++copied; + const auto row=std::find(source.rows.begin(),source.rows.end(),path); + if(row!=source.rows.end()) source.marked[row-source.rows.begin()]=false; + InvalidateRect(source.list,nullptr,FALSE); + UpdateWindow(source.list); + } + const bool restoreFocus=GetForegroundWindow()==progress.window; + updateCopyProgress(progress,0,0,true); + RedrawWindow(progress.window,nullptr,nullptr,RDW_UPDATENOW|RDW_ALLCHILDREN); + DestroyWindow(progress.window); + activeCopy=nullptr; + copyInProgress=false; + for(auto &panel:panels) EnableWindow(panel.list,TRUE); + for(const auto command:commands) EnableWindow(command,TRUE); + if(progress.closeOwner) + { + PostMessageW(owner,WM_CLOSE,0,0); + return; + } + auto &updated=renamed?source:destination; + if(updated.directory==targetDirectory && (!renamed || copied)) + open(updated,updated.directory); + if(restoreFocus) + { + SetForegroundWindow(owner); + SetFocus(panels[active].list); + } + if(progress.canceled) setStatus(L"Copy canceled."); + else if(failed) setStatus(L"Could not complete the copy."); + else if(skipped) setStatus(L"Copy complete with skipped items."); + else setStatus(L"Copy complete."); +} + +LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR index) +{ + const bool rangeKey=wp==VK_UP || wp==VK_DOWN || wp==VK_LEFT || wp==VK_RIGHT; + if(message==WM_KEYDOWN && (wp==VK_INSERT || (rangeKey && (GetKeyState(VK_SHIFT)&0x8000)))) + { + auto &panel=panels[index]; + const auto row=SendMessageW(window,LB_GETCURSEL,0,0); + if(row<0 || static_cast(row)>=panel.marked.size()) return 0; + const auto last=static_cast(panel.marked.size()-1); + auto target=row; + switch(wp) + { + case VK_UP: target=std::max(0,row-1); break; + case VK_LEFT: target=0; break; + case VK_RIGHT: target=last; break; + default: target=std::min(last,row+1); break; + } + const bool mark=!panel.marked[row]; + const bool toBoundary=wp==VK_LEFT || wp==VK_RIGHT; + const auto first=toBoundary ? std::min(row,target) : row; + const auto end=toBoundary ? std::max(row,target) : row; + for(auto i=first;i<=end;++i) + if(panel.sizes[i]!=L"Up") panel.marked[i]=mark; + SendMessageW(window,LB_SETCURSEL,target,0); + InvalidateRect(window,nullptr,FALSE); + showFileDetails(panel); + return 0; + } + if (message == WM_KEYDOWN && (wp == VK_LEFT || wp == VK_RIGHT)) + return scrollList(window, message, wp == VK_LEFT ? VK_HOME : VK_END, lp); + if (message == WM_SETFOCUS) + { + active = static_cast(index); + for (int i = 0; i < 2; ++i) InvalidateRect(panels[i].path, nullptr, TRUE); + showFileDetails(panels[index]); + } + if (message == WM_KEYDOWN) + { + if ((GetKeyState(VK_CONTROL)&0x8000) && (wp==L'1' || wp==L'4')) + { + setMode(static_cast(index),wp==L'4'); + return 0; + } + if (wp == VK_TAB) { SetFocus(panels[1 - index].list); return 0; } + if (wp == VK_RETURN) { enter(panels[index]); return 0; } + if (wp == VK_F2) { open(panels[index], panels[index].directory); return 0; } + if (wp == VK_F10) { SendMessageW(GetParent(window), WM_CLOSE, 0, 0); return 0; } + if (wp == VK_F3 || wp == VK_F4) + { + const auto &panel = panels[index]; + auto row = SendMessageW(window, LB_GETCURSEL, 0, 0); + if (row < 0 || static_cast(row) >= panel.rows.size()) return 0; + const auto &file = panel.rows[row]; + std::error_code error; + if (!fs::is_regular_file(file, error)) return 0; + auto verb = wp == VK_F4 ? L"edit" : L"open"; + if (reinterpret_cast(ShellExecuteW(GetParent(window), verb, file.c_str(), nullptr, + panel.directory.c_str(), SW_SHOWNORMAL)) <= 32) + setStatus(wp == VK_F4 ? L"No editor is registered for this file." : L"Cannot open the selected file."); + return 0; + } + if (wp == VK_F5) + { + copySelection(GetParent(window),panels[index],panels[1-index]); + return 0; + } + } + auto result=scrollList(window, message, wp, lp); + if(message==WM_PAINT && panels[index].wide) + { + auto dc=GetDC(window); + if(dc) + { + RECT line{}; + GetClientRect(window,&line); + line.left=std::max(0L,line.right-(sizeWidth+2)*static_cast(cellWidth)); + line.right=line.left+1; + SetDCBrushColor(dc,colors[Frame]); + FillRect(dc,&line,static_cast(GetStockObject(DC_BRUSH))); + ReleaseDC(window,dc); + } + } + return result; +} + +INT_PTR CALLBACK wideModeDialog(HWND dialog, UINT message, WPARAM wp, LPARAM) +{ + constexpr int widthField=201, extensionsField=202, detailsField=203; + if(message==WM_INITDIALOG) + { + SetDlgItemInt(dialog,widthField,sizeWidth,FALSE); + SendDlgItemMessageW(dialog,widthField,EM_SETLIMITTEXT,2,0); + CheckDlgButton(dialog,extensionsField,alignExtensions?BST_CHECKED:BST_UNCHECKED); + CheckDlgButton(dialog,detailsField,showDetails?BST_CHECKED:BST_UNCHECKED); + CheckDlgButton(dialog,204,alignFolders?BST_CHECKED:BST_UNCHECKED); + for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields&(1u<16) + { + MessageBoxW(dialog,L"Enter a width from 6 to 16 characters.",L"Wide panel mode",MB_OK|MB_ICONWARNING); + SetFocus(GetDlgItem(dialog,widthField)); + SendDlgItemMessageW(dialog,widthField,EM_SETSEL,0,-1); + return TRUE; + } + sizeWidth=static_cast(width); + alignExtensions=IsDlgButtonChecked(dialog,extensionsField)==BST_CHECKED; + showDetails=IsDlgButtonChecked(dialog,detailsField)==BST_CHECKED; + alignFolders=IsDlgButtonChecked(dialog,204)==BST_CHECKED; + statusFields=0; + for(int i=0;i<4;++i) if(IsDlgButtonChecked(dialog,205+i)==BST_CHECKED) statusFields|=1u< rows; + if(index==0 || index==4) + { + const bool wide=panels[index==4].wide; + rows={wide?L" Brief\tCtrl+1":L"✓ Brief\tCtrl+1", + wide?L"✓ Wide\tCtrl+4":L" Wide\tCtrl+4", + index==0?L" Change drive\tAlt+F1":L" Change drive\tAlt+F2"}; + } + else if(index==1) rows={L"Copy\tF5",L"Exit\tF10"}; + else if(index==2) rows={L"Refresh\tF2",L"View\tF3",L"Edit\tF4"}; + else if(page==0) rows={L"File panel modes",L"Colors",L"Appearance…"}; + else if(page==1) rows={L"Wide"}; + else if(page==2) rows={L"Panel background",L"Text",L"Frame",L"Popup background", + L"Menu selection",L"Command bar",L"File cursor"}; + for(const auto &row:rows) + SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast(row.c_str())); + RECT anchor{}, client{}; + GetWindowRect(menuItems[index],&anchor); + MapWindowPoints(nullptr,window,reinterpret_cast(&anchor),2); + GetClientRect(window,&client); + const int width=std::min(static_cast(client.right)-16,26*cellWidth+16); + const int x=std::clamp(static_cast(anchor.left)+4,4,std::max(4,static_cast(client.right)-width-12)); + const int y=anchor.bottom+5; + const int height=static_cast(rows.size())*static_cast(SendMessageW(picker,LB_GETITEMHEIGHT,0,0)); + SetWindowPos(pickerFrame,HWND_TOP,x-4,y-4,width+13,height+8,SWP_SHOWWINDOW); + SetWindowPos(picker,HWND_TOP,x,y,width,height,SWP_SHOWWINDOW); + SendMessageW(picker,LB_SETCURSEL,0,0); + SetFocus(picker); + showMenu(true); +} + +LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) +{ + switch (message) + { + case WM_CREATE: + { + auto instance = GetModuleHandleW(nullptr); + LOGFONTW font{}; + DWORD bytes=sizeof(font); + if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,L"DisplayFont",RRF_RT_REG_BINARY,nullptr,&font,&bytes) + !=ERROR_SUCCESS || bytes!=sizeof(font)) + { + font={}; + font.lfWeight=FW_NORMAL; + font.lfCharSet=DEFAULT_CHARSET; + font.lfQuality=CLEARTYPE_QUALITY; + wcscpy_s(font.lfFaceName,L"Consolas"); + } + font.lfFaceName[LF_FACESIZE-1]=0; + if(!applyFont(window,font,static_cast(std::clamp(preference(L"FontPoints",110),80UL,240UL)))) return -1; + loadColors(); + panels[0].wide=preference(L"LeftWide",0)!=0; + panels[1].wide=preference(L"RightWide",0)!=0; + sizeWidth=static_cast(std::clamp(preference(L"SizeWidth",6),6UL,16UL)); + alignExtensions=preference(L"AlignExtensions",1)!=0; + showDetails=preference(L"ShowDetails",1)!=0; + alignFolders=preference(L"AlignFolders",0)!=0; + statusFields=preference(L"StatusFields",15)&15; + menuBar=CreateWindowW(L"BUTTON",L"",WS_CHILD|WS_CLIPSIBLINGS|BS_OWNERDRAW, + 0,0,0,0,window,reinterpret_cast(120),instance,nullptr); + const wchar_t *menus[]{L"Left",L"Files",L"Commands",L"Options",L"Right"}; + for(int i=0;i<5;++i) + { + menuItems[i]=CreateWindowW(L"BUTTON",menus[i],WS_CHILD|WS_CLIPSIBLINGS|BS_OWNERDRAW, + 0,0,0,0,window,reinterpret_cast(130+static_cast(i)),instance,nullptr); + if(!menuItems[i]) return -1; + } + picker=CreateWindowExW(0,L"LISTBOX",L"Change drive", + WS_CHILD|WS_CLIPSIBLINGS|LBS_NOTIFY|LBS_OWNERDRAWFIXED|LBS_HASSTRINGS|LBS_NOINTEGRALHEIGHT, + 0,0,0,0,window,reinterpret_cast(121),instance,nullptr); + pickerFrame=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_CLIPSIBLINGS|SS_OWNERDRAW, + 0,0,0,0,window,reinterpret_cast(122),instance,nullptr); + SetWindowSubclass(picker,pickerKeys,1,0); + SendMessageW(picker,LB_SETITEMHEIGHT,0,textHeight); + status = CreateWindowW(L"STATIC", L"", WS_CHILD | WS_VISIBLE | SS_PATHELLIPSIS, + 0, 0, 0, 0, window, nullptr, instance, nullptr); + if (!mono || !blue || !teal || !menuBar || !picker || !pickerFrame || !status) return -1; + SendMessageW(status, WM_SETFONT, reinterpret_cast(mono), FALSE); + const wchar_t *labels[]{L"F2 Refresh", L"F3 View", L"F4 Edit", L"F5 Copy", L"F10 Exit"}; + for (int i = 0; i < 5; ++i) + commands[i] = CreateWindowW(L"BUTTON", labels[i], WS_CHILD | WS_VISIBLE | BS_OWNERDRAW, + 0, 0, 0, 0, window, reinterpret_cast(110 + static_cast(i)), instance, nullptr); + for (int i = 0; i < 2; ++i) + { + auto &panel = panels[i]; + panel.path = CreateWindowW(L"STATIC", L"", WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | SS_PATHELLIPSIS, + 0, 0, 0, 0, window, nullptr, instance, nullptr); + panel.list = CreateWindowExW(0, L"LISTBOX", L"", + WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | LBS_OWNERDRAWFIXED | LBS_HASSTRINGS, + 0, 0, 0, 0, window, reinterpret_cast(102 + static_cast(i)), instance, nullptr); + panel.heading=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_CLIPSIBLINGS|SS_OWNERDRAW, + 0,0,0,0,window,reinterpret_cast(140+static_cast(i)),instance,nullptr); + if (!panel.path || !panel.list || !panel.heading) return -1; + for (auto child : {panel.path, panel.list}) + SendMessageW(child, WM_SETFONT, reinterpret_cast(mono), FALSE); + SendMessageW(panel.list,LB_SETITEMHEIGHT,0,textHeight); + wchar_t system[MAX_PATH]{}; + GetWindowsDirectoryW(system, MAX_PATH); + const auto saved=savedPanelPath(panelPathKeys[i]); + if(saved.is_absolute()) open(panel,saved); + if(!panel.directory.empty()) + { + const auto cursor=savedPanelPath(panelCursorKeys[i]); + const auto row=std::find(panel.rows.begin(),panel.rows.end(),cursor); + if(row!=panel.rows.end()) SendMessageW(panel.list,LB_SETCURSEL,row-panel.rows.begin(),0); + } + if(panel.directory.empty()) open(panel,fs::path(system).root_path()); + SetWindowSubclass(panel.list, panelKeys, 1, i); + } + SetFocus(panels[0].list); + return 0; + } + case WM_DPICHANGED: + { + hidePicker(); + const auto &bounds=*reinterpret_cast(lp); + applyFont(window,displayFont,fontPoints); + SetWindowPos(window,nullptr,bounds.left,bounds.top,bounds.right-bounds.left, + bounds.bottom-bounds.top,SWP_NOZORDER|SWP_NOACTIVATE); + layout(window); + if(activeCopy) PostMessageW(activeCopy->window,refreshProgressLayout,0,0); + RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN); + return 0; + } + case WM_MOVE: + if(copyInProgress && !IsIconic(window)) + { + RECT bounds{}; + if(GetWindowRect(window,&bounds)) + { + const OwnedWindowMove move{window,bounds.left-previousOwnerBounds.left, + bounds.top-previousOwnerBounds.top}; + previousOwnerBounds=bounds; + if(move.dx || move.dy) + EnumThreadWindows(GetCurrentThreadId(),moveOwnedDialog,reinterpret_cast(&move)); + } + } + return 0; + case WM_SIZE: + hidePicker(); + layout(window); + return 0; + case WM_GETMINMAXINFO: + reinterpret_cast(lp)->ptMinTrackSize = {540, 220}; + return 0; + case WM_SETCURSOR: + case WM_LBUTTONDOWN: + { + POINT point{}; + GetCursorPos(&point); + ScreenToClient(window, &point); + RECT rect{}; + GetClientRect(window, &rect); + const int width = rect.right; + int middle = std::clamp(split ? split : width / 2, 120, std::max(120, width - 120)); + if (point.y >= 0 && point.y < rect.bottom-2*textHeight-14 && abs(point.x - middle) <= 4) + { + SetCursor(LoadCursorW(nullptr, IDC_SIZEWE)); + if (message == WM_LBUTTONDOWN) { dragging = true; SetCapture(window); } + return TRUE; + } + break; + } + case WM_MOUSEMOVE: + if (dragging) { split = std::max(1, GET_X_LPARAM(lp)); layout(window); } + return 0; + case WM_LBUTTONUP: + if (dragging) ReleaseCapture(); + return 0; + case WM_CAPTURECHANGED: + dragging = false; + return 0; + case WM_ERASEBKGND: + return 1; + case WM_PAINT: + { + PAINTSTRUCT paint{}; + auto dc=BeginPaint(window,&paint); + FillRect(dc,&paint.rcPaint,blue); + auto border=CreateSolidBrush(colors[Frame]); + for(const auto &panel:panels) + { + RECT box{}; + GetWindowRect(panel.list,&box); + MapWindowPoints(nullptr,window,reinterpret_cast(&box),2); + box.right+=5; + InflateRect(&box,2,2); + FrameRect(dc,&box,border); + paintScrollPosition(window,dc,panel.list,colors[PanelBlue]); + InflateRect(&box,-1,-1); + FrameRect(dc,&box,border); + } + DeleteObject(border); + EndPaint(window,&paint); + return 0; + } + case WM_CTLCOLORSTATIC: + { + auto dc=reinterpret_cast(wp); + bool highlighted=reinterpret_cast(lp)==panels[active].path; + SetTextColor(dc,colors[highlighted?Text:Frame]); + SetBkColor(dc,colors[highlighted?Dialog:PanelBlue]); + return reinterpret_cast(highlighted?teal:blue); + } + case WM_CTLCOLORLISTBOX: + return reinterpret_cast(reinterpret_cast(lp)==picker?teal:blue); + case WM_DRAWITEM: + { + const auto &item=*reinterpret_cast(lp); + if(item.CtlID==140 || item.CtlID==141) + { + auto name=item.rcItem, size=item.rcItem; + size.left=std::max(size.left,size.right-(sizeWidth+2)*static_cast(cellWidth)); + name.right=size.left; + paintText(item.hDC,name,L"Name",RGB(255,255,0),colors[PanelBlue]); + paintText(item.hDC,size,L"Size",RGB(255,255,0),colors[PanelBlue],true); + RECT line{size.left,size.top,size.left+1,size.bottom}; + SetDCBrushColor(item.hDC,colors[Frame]); + FillRect(item.hDC,&line,static_cast(GetStockObject(DC_BRUSH))); + return TRUE; + } + if(item.hwndItem==pickerFrame) + { + auto box=item.rcItem; + FillRect(item.hDC,&box,teal); + auto border=CreateSolidBrush(colors[Frame]); + InflateRect(&box,-2,-2); + FrameRect(item.hDC,&box,border); + InflateRect(&box,-2,-2); + FrameRect(item.hDC,&box,border); + DeleteObject(border); + if(commandPicker) return TRUE; + box.left+=9; + box.right=std::min(box.right,box.left+13*cellWidth); + box.bottom=box.top+textHeight; + paintText(item.hDC,box,L"Change drive",colors[Text],colors[Dialog]); + paintScrollPosition(pickerFrame,item.hDC,picker,colors[Dialog]); + return TRUE; + } + std::wstring text; + if(item.CtlType==ODT_LISTBOX && item.itemID!=UINT(-1)) + { + auto length=SendMessageW(item.hwndItem,LB_GETTEXTLEN,item.itemID,0); + if(length>=0) + { + text.resize(length+1); + SendMessageW(item.hwndItem,LB_GETTEXT,item.itemID,reinterpret_cast(text.data())); + } + } + if(item.CtlType==ODT_BUTTON) + { + wchar_t label[64]{}; + GetWindowTextW(item.hwndItem,label,64); + text=label; + } + auto background=item.CtlType==ODT_BUTTON?Footer:item.hwndItem==picker?Dialog:PanelBlue; + auto foreground=colors[Text]; + if(item.CtlID>=130 && item.CtlID<=134 && static_cast(item.CtlID)-130==menuIndex) + background=Selection; + if(item.itemState&(ODS_SELECTED|ODS_FOCUS)) + background=item.CtlType==ODT_LISTBOX && item.hwndItem!=picker?PanelCursor:Selection; + if(item.CtlID==102 || item.CtlID==103) + { + const auto &panel=panels[item.CtlID-102]; + if(item.itemID(cellWidth)); + name.right=size.left; + bool folder=panel.sizes[item.itemID]==L"Folder"; + if(folder) text=panel.rows[item.itemID].filename().wstring(); + if(panel.sizes[item.itemID]!=L"Up" && (folder?alignFolders:alignExtensions)) + { + auto extension=panel.rows[item.itemID].extension().wstring(); + if(!extension.empty()) + { + auto end=name; + end.left=std::max(end.left,end.right-8*static_cast(cellWidth)); + name.right=end.left; + paintText(item.hDC,end,extension.c_str()+1,foreground,colors[background],true); + text=panel.rows[item.itemID].stem().wstring(); + } + } + paintText(item.hDC,name,text.c_str(),foreground,colors[background]); + const auto &amount=panel.sizes[item.itemID]; + auto visible=amount; + if(amount!=L"Folder" && amount!=L"Up") + visible=formatSize(std::stoull(amount),static_cast(sizeWidth)); + paintText(item.hDC,size,visible.c_str(),foreground,colors[background],true); + RECT line{size.left,size.top,size.left+1,size.bottom}; + SetDCBrushColor(item.hDC,colors[Frame]); + FillRect(item.hDC,&line,static_cast(GetStockObject(DC_BRUSH))); + } + } + if (item.CtlType==ODT_LISTBOX) + { + RECT track{}; + GetWindowRect(item.hwndItem,&track); + auto owner=item.hwndItem==picker?pickerFrame:window; + MapWindowPoints(nullptr,owner,reinterpret_cast(&track),2); + track.left=track.right; + track.right+=5; + InvalidateRect(owner,&track,FALSE); + } + return TRUE; + } + case WM_COMMAND: + if(LOWORD(wp)==121 && HIWORD(wp)==LBN_DBLCLK) selectDrive(); + if(LOWORD(wp)>=130 && LOWORD(wp)<=134 && HIWORD(wp)==BN_CLICKED) + { + openMenu(window,LOWORD(wp)-130); + return 0; + } + if (LOWORD(wp) >= 110 && LOWORD(wp) <= 114 && HIWORD(wp) == BN_CLICKED) + { + const WPARAM keys[]{VK_F2, VK_F3, VK_F4, VK_F5, VK_F10}; + SetFocus(panels[active].list); + SendMessageW(panels[active].list, WM_KEYDOWN, keys[LOWORD(wp) - 110], 0); + } + if (LOWORD(wp) >= 102 && LOWORD(wp) <= 103 && HIWORD(wp) == LBN_DBLCLK) + enter(panels[LOWORD(wp) - 102]); + if (LOWORD(wp) >= 102 && LOWORD(wp) <= 103 && HIWORD(wp) == LBN_SELCHANGE) + showFileDetails(panels[LOWORD(wp) - 102]); + return 0; + case WM_CLOSE: + if(activeCopy) + { + if(!IsWindowEnabled(activeCopy->window)) + { + setStatus(L"Resolve the copy prompt before closing."); + return 0; + } + SendMessageW(activeCopy->window,WM_COMMAND,IDCANCEL,0); + activeCopy->closeOwner=activeCopy->canceled; + return 0; + } + savePlacement(window); + for(int i=0;i<2;++i) + { + const auto &path=panels[i].directory.native(); + if(!path.empty()) + RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,panelPathKeys[i],REG_SZ,path.c_str(), + static_cast((path.size()+1)*sizeof(wchar_t))); + const auto row=SendMessageW(panels[i].list,LB_GETCURSEL,0,0); + const auto cursor=row>=0 && static_cast(row)((cursor.size()+1)*sizeof(wchar_t))); + } + DestroyWindow(window); + return 0; + case WM_DESTROY: + PostQuitMessage(0); + return 0; + } + return DefWindowProcW(window, message, wp, lp); +} +} + +int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) +{ + int count{}; + if(auto args=CommandLineToArgvW(GetCommandLineW(),&count)) + { + if(count==4 && std::wstring_view(args[1])==L"--list-folder") + { + auto result=listElevatedFolder(fs::path(args[2]).parent_path(),args[3]); + LocalFree(args); + return static_cast(result); + } + LocalFree(args); + } + INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_STANDARD_CLASSES|ICC_PROGRESS_CLASS}; + InitCommonControlsEx(&controls); + WNDCLASSW type{}; + type.hInstance = instance; + type.lpfnWndProc = filesWindow; + type.hIcon = LoadIconW(instance, MAKEINTRESOURCEW(1)); + type.hCursor = LoadCursorW(nullptr, IDC_ARROW); + + type.lpszClassName = L"KSwitcher.Files"; + if (!RegisterClassW(&type)) return 1; + auto window = CreateWindowW(type.lpszClassName, L"KSwitcher Files — local prototype", + WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, 900, 540, nullptr, nullptr, instance, nullptr); + if (!window) return 1; + if(!restorePlacement(window)) ShowWindow(window, show); + MSG message{}; + while (GetMessageW(&message, nullptr, 0, 0) > 0) + { + if (message.message == WM_SYSKEYDOWN && message.wParam == VK_MENU) + { + altAlone=true; + continue; + } + if ((message.message == WM_SYSKEYUP || message.message == WM_KEYUP) && message.wParam == VK_MENU) + { + if(altAlone) + { + hidePicker(); + menuIndex=active==0?0:4; + showMenu(true); + } + altAlone=false; + continue; + } + if(message.message==WM_SYSKEYDOWN || message.message==WM_KEYDOWN) altAlone=false; + if((message.message==WM_LBUTTONDOWN || message.message==WM_RBUTTONDOWN || + message.message==WM_NCLBUTTONDOWN) && message.hwnd!=menuBar && message.hwnd!=picker && + std::find(std::begin(menuItems),std::end(menuItems),message.hwnd)==std::end(menuItems)) + { + showMenu(false); + if(message.hwnd!=picker) hidePicker(); + } + if(message.message==WM_KEYDOWN && IsWindowVisible(menuBar) && !IsWindowVisible(picker)) + { + if(message.wParam==VK_ESCAPE){showMenu(false);SetFocus(panels[active].list);continue;} + if(message.wParam==VK_LEFT || message.wParam==VK_RIGHT) + { + menuIndex=(menuIndex+(message.wParam==VK_LEFT?4:1))%5; + showMenu(true); + continue; + } + if(message.wParam==VK_RETURN || message.wParam==VK_DOWN) + { + SendMessageW(window,WM_COMMAND,MAKEWPARAM(130+menuIndex,BN_CLICKED),0); + continue; + } + } + if (message.message == WM_SYSKEYDOWN && message.wParam == VK_F10 && + !(GetKeyState(VK_MENU) & 0x8000) && !(GetKeyState(VK_SHIFT) & 0x8000)) + { + SendMessageW(window, WM_CLOSE, 0, 0); + continue; + } + if (message.message == WM_SYSKEYDOWN && (message.wParam == VK_F1 || message.wParam == VK_F2)) + { + chooseDrive(static_cast(message.wParam - VK_F1)); + continue; + } + TranslateMessage(&message); + DispatchMessageW(&message); + } + DeleteObject(mono); + DeleteObject(blue); + DeleteObject(teal); + return 0; +} -- 2.54.1