From 69e6aaeb0f3e70737df9a7e57db4e4d7c3d1cb52 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Mon, 16 Nov 2026 19:45:45 +0200 Subject: [PATCH] Release KSwitcher v0.6.106 with responsive Files operations --- CMakeLists.txt | 3 +- FILES-UI.md | 20 +- README.md | 9 +- Release/README.md | 16 + resources/app.rc | 6 +- resources/files.rc | 13 + src/app.cpp | 72 +- src/app.h | 1 + src/core.h | 2 +- src/files_lock_processes.inl | 245 +++++++ src/files_main.cpp | 1064 ++++++++++++++++++---------- src/files_text_window.cpp | 2 +- src/lan.cpp | 38 +- src/lan_clipboard.h | 66 +- src/ocr.cpp | 65 +- src/platform.cpp | 11 +- src/screenshot.cpp | 199 +++++- src/screenshot_main.cpp | 16 + src/storage.cpp | 245 +++++-- src/storage.h | 5 + src/update.h | 2 +- tests/files_activation.ps1 | 215 ++++++ tests/files_activation_fixture.cpp | 13 + tests/lan_clipboard.cpp | 31 + tests/ocr.cpp | 47 ++ tests/screenshot_ui.cpp | 86 ++- tests/tests.cpp | 4 +- 27 files changed, 1954 insertions(+), 542 deletions(-) create mode 100644 src/files_lock_processes.inl diff --git a/CMakeLists.txt b/CMakeLists.txt index 4ae5b4b..4be08f5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.24) -project(KSwitcher VERSION 0.6.105 LANGUAGES CXX RC) +project(KSwitcher VERSION 0.6.106 LANGUAGES CXX RC) if(NOT WIN32) message(FATAL_ERROR "KSwitcher uses native Windows APIs") endif() @@ -56,6 +56,7 @@ set_target_properties(KSwitcherConfig PROPERTIES OUTPUT_NAME "KSwitcher.Config") target_compile_definitions(KSwitcherConfig PRIVATE KS_CONFIG_APP) target_link_libraries(KSwitcherConfig PRIVATE kscore) add_executable(KSwitcherTests tests/tests.cpp) +target_include_directories(KSwitcherTests PRIVATE vendor) add_executable(KSwitcherSyncTests tests/sync.cpp) target_include_directories(KSwitcherSyncTests PRIVATE vendor) target_link_libraries(KSwitcherSyncTests PRIVATE kscore) diff --git a/FILES-UI.md b/FILES-UI.md index bc27e5a..afdffd2 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -83,6 +83,11 @@ Warning і початковий фокус на No. лише до шляхів із пробілами. Для `..` вставляється шлях батьківської папки. - Ctrl+Enter вставляє лише назву файла або папки під курсором активної панелі за тими ж правилами вставлення й лапок. Рядок `..` пропускається. +- Локальні й LAN-каталоги скануються у фоновому потоці. Під час переходу + активна панель показує «Loading folder…» і зберігає попередній список до + завершення сканування. Якщо надійшов новіший запит, результат попереднього + сканування пропускається. Після підтвердження UAC очікування списку + від підвищеного процесу теж відбувається у фоні. - Ctrl+R перечитує поточну папку активної панелі. Позиція курсора й позначки зберігаються для наявних елементів, а підраховані через F3 розміри папок скидаються. F2 також виконує цю дію. @@ -313,7 +318,9 @@ Warning і початковий фокус на No. - Власні діалоги Files блокують дії панелей і командного рядка, залишаючи системний заголовок і рамку головного вікна доступними. Клік у Files поза діалогом діє як Cancel. Для прогресу копіювання, переміщення й видалення це відкриває - підтвердження скасування. + підтвердження скасування. Перелік і обробка файлів виконуються у фоновому + потоці. Діалог залишається доступним під час очікування файлового вводу-виводу. + Скасування перевіряється між кроками операції та під час передачі блоків. - Enter активує кнопку у фокусі. Для кнопок із власним малюванням використовуй спільний обробник `dialogButtonEnter`. У підтвердженні скасування початковий фокус стоїть на No. @@ -326,7 +333,16 @@ Warning і початковий фокус на No. - Search і спільні нижні секції Far використовують компактні проміжки між рядками й кнопками, прив’язані до метрик моноширинного шрифту. У Search висота кнопки дорівнює висоті одного рядка. - Нижні кнопки Far групуються по центру. Їхня ширина залежить від напису й дужок, а проміжок між ними становить приблизно половину символу. - Прапорці Far у Search, Copy і попередженнях використовують спільний компонент. У фокусі короткий системний курсор блимає між дужками, а тло рядка зберігає колір діалогу. -- У Copy і Rename/Move помилки шляху показує окремий червоний модальний діалог Far. Після його закриття фокус повертається до поля шляху. +- У Copy і Rename/Move шлях перевіряється у фоновому потоці, і в цей час + діалог можна скасувати. Помилки шляху показує окремий червоний модальний діалог Far. Після його закриття фокус повертається до поля шляху. +- Помилки копіювання, переміщення й видалення показуються в червоному + модальному діалозі Far із причиною помилки та кнопкою OK. +- Якщо локальне перейменування або видалення заблоковане, кнопка Processes… відкриває + список процесів із назвою та PID. Перевірка папки включає вкладені елементи. + End process завершує вибраний процес після окремого підтвердження, після + чого список оновлюється. Якщо Windows обмежила доступ або перевірку + великої папки завершено частково, про це повідомляється в діалозі. + Операцію можна повторити після звільнення файла чи папки. - Короткі червоні повідомлення використовують звичайний текст без смуги прокрутки. Висота діалогу залежить від кількості рядків повідомлення. - Для однорядкових полів Far використовуй спільний компонент `FAR_EDIT` і спільну підготовку та палітру діалогів. Компонент використовує нативний Win32 Edit без рамки й центрує текст вертикально. Його використовують Search, Copy/Rename, Title/Path і пошук в історії. Кольори Text і Popup background діють на всі ці поля, зокрема на поле Copy лише для читання. У відповідних розділах Options → Colors зміни видно на зразку поля. Existing files у Copy є списком без редагування. Поля та редагований список Windows Options мають системне оформлення. - Для позиціонування роздільника використовуй невидимий маркер, якщо межу не задає інший елемент секції. Спільний обробник малює лінію. diff --git a/README.md b/README.md index 20bb65b..fc191e5 100644 --- a/README.md +++ b/README.md @@ -600,8 +600,9 @@ Pressing the history shortcut a second time pastes the second-most-recent item. Data is in `data/` beside the executable, falling back to `%LOCALAPPDATA%/KSwitcher` when the executable's directory is not writable. Each clipboard payload is an encrypted disk file; only bounded previews/metadata stay in memory. Image data is loaded on demand and released when -the history popup is hidden. Settings **Write log** (`writeLog`, enabled by default) controls all -log writes. Disabling it also clears diagnostic context from memory; existing log files remain. +the history popup is hidden. Settings **Write log** (`writeLog`, off by default) controls all +log writes. Enable it when collecting diagnostics that may include typed or copied text. +Disabling it also clears diagnostic context from memory. Existing log files remain. Diagnostic stages stay in a memory buffer of at most 128 events for 30 seconds. Selection diagnostics include the expected text, each copied candidate before and after suffix recovery, paced Shift+Left progress or batch delivery counts, and clipboard sequence changes, @@ -1019,7 +1020,9 @@ Check **★ Pinned only** beside the history search box to show only pinned entr History opens in a separate, short-lived instance of **KSwitcher.exe**. **Esc** closes it even when focus is on the window or an action button, releasing Windows UI allocations with the process. The resident keeps keyboard hooks, clipboard capture and history storage. Search and the pinned-only filter are preserved in encrypted view state. Each fresh opening selects and reveals the newest matching entry; background refreshes preserve the selected record while browsing. If a full-text item viewer is still open, the helper stays alive until the last viewer closes. Pin/delete, formatted/plain paste and OCR remain available; settings and default shortcuts are unchanged. -Image thumbnails are decoded in **KSwitcher.Screenshot.exe**, returning only bounded preview pixels. Image clipboard backup/restore also uses that helper and encrypted temporary files, with clipboard-sequence checks before restoring. Selection reads avoid loading image formats. Keep all three executables together; no fourth executable is required. Paste allows a brief foreground handoff after history closes while preserving cancellation checks. UI Automation remains in the resident. +Image thumbnails are decoded in **KSwitcher.Screenshot.exe**, returning only bounded preview pixels. +History reuses separate helper processes for OCR and thumbnails so recognition can run alongside previews. +Idle helpers exit after 30 seconds, and closing the history host stops its helpers. Image clipboard backup/restore also uses that helper and encrypted temporary files, with clipboard-sequence checks before restoring. Selection reads avoid loading image formats. Keep all three executables together; no fourth executable is required. Paste allows a brief foreground handoff after history closes while preserving cancellation checks. UI Automation remains in the resident. A live development-build test measured **4.37 MiB before history and 4.35 MiB after two open/Esc cycles**, compared with an earlier roughly 8–9 MiB plateau. A same-image clipboard-backup benchmark retained **12.78 MiB before versus 0.05 MiB after**. These measure private working set, not a guaranteed total footprint. Include all helpers when measuring active use: combined memory can be higher while history is open. No forced working-set trimming is used. Existing screenshots and shortcuts remain applicable. The v0.6.38 approach of retaining a hidden history window/RichEdit control is superseded by process termination. diff --git a/Release/README.md b/Release/README.md index 6e1d5a7..1cb4080 100644 --- a/Release/README.md +++ b/Release/README.md @@ -1,5 +1,21 @@ # Latest Windows release +## v0.6.106 — 2026-11-16 + +Files scans local and LAN folders and runs copy, move, rename and delete in the background. Copy and Rename/Move validate destinations in the background. A failed operation opens a red Far-style dialog. For local sharing violations, **Processes…** shows possible blockers and **End process** ends the selected process after confirmation. Retry **F6**, **F8**, or **Shift+Delete** after releasing the item. + +The screenshot editor repaints the affected area while dragging. History reuses separate OCR and thumbnail helpers, and Windows OCR scales images to the engine’s size limit. Shortcut and snippet processing does less work on keystrokes, and LAN transfers wait for a timeout before retrying unacknowledged chunks. + +**Write log** defaults to off for new settings. Existing explicit choices still apply. When enabled, diagnostic logs can contain typed or copied text. + +**Українською.** + +Files сканує локальні й LAN-каталоги та виконує копіювання, переміщення, перейменування й видалення у фоні. Copy і Rename/Move перевіряють шлях у фоні. Помилки операцій відкривають червоний діалог у стилі Far. При локальному блокуванні **Processes…** показує можливі процеси, а **End process** завершує вибраний процес після підтвердження. Після звільнення повторіть **F6**, **F8** або **Shift+Delete**. + +Редактор скриншотів перемальовує змінену область під час перетягування. Історія повторно використовує окремі процеси OCR і мініатюр, а Windows OCR масштабує зображення до ліміту рушія. Обробка хоткеїв і сніпетів виконує менше роботи під час набору. LAN-передача повторно надсилає непідтверджені блоки після тайм-ауту. + +**Write log** вимкнено за замовчуванням для нових налаштувань. Явно збережений вибір продовжує діяти. Увімкнений журнал може містити введений або скопійований текст. + ## v0.6.105 — 2026-11-16 KSwitcher Files gives the Editor a pencil icon and the Viewer an eye icon. The two modes have separate taskbar groups, and **F6** switches the icon and group in the same window. On a PC running KSwitcher as administrator, LAN PowerShell commands such as `dir` now start with standard user rights. This fixes the `0xC0000142` startup failure on that path. This release replaces v0.6.104. diff --git a/resources/app.rc b/resources/app.rc index 68e232b..04394f4 100644 --- a/resources/app.rc +++ b/resources/app.rc @@ -9,8 +9,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur" 1 RT_MANIFEST "app.manifest" 201 RCDATA "update.ps1" 1 VERSIONINFO - FILEVERSION 0,6,105,0 - PRODUCTVERSION 0,6,105,0 + FILEVERSION 0,6,106,0 + PRODUCTVERSION 0,6,106,0 FILEOS VOS_NT_WINDOWS32 FILETYPE VFT_APP BEGIN @@ -20,7 +20,7 @@ BEGIN BEGIN VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility" VALUE "ProductName", "KSwitcher" - VALUE "FileVersion", "0.6.105" + VALUE "FileVersion", "0.6.106" END END BLOCK "VarFileInfo" diff --git a/resources/files.rc b/resources/files.rc index 6c71546..6ab50a3 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -60,6 +60,19 @@ BEGIN CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 67, 38, 51, 15 CONTROL "&Yes", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 36, 38, 51, 15 CONTROL "&No", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 98, 38, 51, 15 + CONTROL "&Processes…", 103, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 14, 38, 75, 15 +END + +609 DIALOGEX 0, 0, 350, 135 +STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN +FONT 10, "Consolas" +BEGIN + LTEXT "", 430, 14, 17, 322, 20 + LISTBOX 431, 14, 41, 322, 61, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP + CONTROL "", 432, "Static", NOT WS_VISIBLE, 14, 108, 1, 1 + CONTROL "&End process", 433, "Button", BS_OWNERDRAW | WS_TABSTOP, 56, 110, 80, 16 + CONTROL "&Refresh", 434, "Button", BS_OWNERDRAW | WS_TABSTOP, 140, 110, 74, 16 + CONTROL "&Close", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 218, 110, 65, 16 END 608 DIALOGEX 0, 0, 220, 67 diff --git a/src/app.cpp b/src/app.cpp index e1b7b2c..5aed7d9 100644 --- a/src/app.cpp +++ b/src/app.cpp @@ -178,6 +178,28 @@ std::vector> shortcuts(const Settings &s) out.emplace_back(Direct + (int)i, s.direct[i]); return out; } +std::vector buildSnippetVariants(const std::wstring &trigger, const std::vector &layouts) +{ + std::vector variants{lower(trigger)}; + for (auto &l : layouts) + { + bool valid = true; + std::wstring normalized; + for (wchar_t c : trigger) + { + auto p = physicalLayout().at(l.code(c)); + if (!p) + { + valid = false; + break; + } + normalized += p; + } + if (valid) + variants.push_back(lower(normalized)); + } + return variants; +} size_t caretSteps(std::wstring text) { size_t n = 0; @@ -976,6 +998,10 @@ void App::applySettings(const Settings &requested, bool validateOcrInstallation) if (validateOcrInstallation && ocrProfile(s) != ocrProfile(settings)) validateTesseract(s); if (s.autoCorrect) { + { + std::lock_guard lock(stateMutex); + predictor.shareDictionaries(autoPredictor); + } predictor.configure(std::filesystem::path(executable()).parent_path() / L"dictionaries", s.autoLanguages); } if (!registerHotkeys(s)) @@ -1008,6 +1034,7 @@ void App::applySettings(const Settings &requested, bool validateOcrInstallation) { std::lock_guard lock(stateMutex); settings = s; + snippetTriggers.clear(); autoPredictor = std::move(predictor); setLoggingEnabled(s.writeLog); run.reset(); @@ -1038,6 +1065,7 @@ void App::reloadLayouts() { std::lock_guard lock(stateMutex); layouts = std::move(latest); + snippetTriggers.clear(); settings = s; run.reset(); last.reset(); @@ -1062,13 +1090,9 @@ void App::setHotkeyCapture(HWND field) bool App::isHotkey(DWORD key, UINT mods) { if (registeredFilesHotkey.key && registeredFilesHotkey.key == key && registeredFilesHotkey.modifiers == mods) return true; - for (auto &[id, text] : shortcuts(settings)) - { - auto h = Hotkey::parse(text); - if (h && h->key == key && h->modifiers == mods) - return true; - } - return false; + return std::any_of(hookBindings.begin(), hookBindings.end(), [&](const auto &binding) { + return binding.second == Hotkey{mods, key}; + }); } void App::resetLanInput() { @@ -1187,30 +1211,24 @@ void App::matchSnippets(HWND fg, bool expandExact) const std::wstring_view prefix = std::wstring_view(keys).substr(start == keys.npos ? 0 : start + 1); const bool suggest = prefix.size() >= 3 || prefix.starts_with(L';'); std::vector matches; - std::set seen; - auto snippetProcess = processName(fg); + std::set seen; + snippetTriggers.resize(settings.snippets.size()); + std::optional snippetProcess; for (int priority : {2, 1}) for (size_t i = 0; i < settings.snippets.size(); ++i) { auto &sn = settings.snippets[i]; - if (snippetAppPriority(sn, snippetProcess) != priority) continue; - std::vector variants{lower(sn.trigger)}; - for (auto &l : layouts) + if (sn.apps.empty() != (priority == 1)) continue; + if (!sn.apps.empty()) { - bool valid = true; - std::wstring normalized; - for (wchar_t c : sn.trigger) - { - auto p = physicalLayout().at(l.code(c)); - if (!p) - { - valid = false; - break; - } - normalized += p; - } - if (valid) - variants.push_back(lower(normalized)); + if (!snippetProcess) snippetProcess = processName(fg); + if (snippetAppPriority(sn, *snippetProcess) != priority) continue; + } + auto &[trigger, variants] = snippetTriggers[i]; + if (variants.empty() || trigger != sn.trigger) + { + variants = buildSnippetVariants(sn.trigger, layouts); + trigger = sn.trigger; } if (expandExact && std::any_of(variants.begin(), variants.end(), [&](const auto &trigger) { return keys.ends_with(trigger); @@ -1221,7 +1239,7 @@ void App::matchSnippets(HWND fg, bool expandExact) } if (suggest && std::any_of(variants.begin(), variants.end(), [&](const auto &trigger) { return trigger.size() > prefix.size() && trigger.starts_with(prefix); - }) && seen.insert(lower(sn.trigger)).second) + }) && seen.insert(variants.front()).second) matches.push_back(i); } if (matches.empty()) return; diff --git a/src/app.h b/src/app.h index 0a6878e..da1f38f 100644 --- a/src/app.h +++ b/src/app.h @@ -192,6 +192,7 @@ class App RECT snippetPopupAnchor{}; bool snippetCaretPending{}; std::optional snippetCaret; + std::vector>> snippetTriggers; std::vector snippetMatches; std::array snippetKeys{}; void matchSnippets(HWND, bool expandExact); diff --git a/src/core.h b/src/core.h index 5230336..5813598 100644 --- a/src/core.h +++ b/src/core.h @@ -78,7 +78,7 @@ struct Settings bool autoCorrect = false; bool autoReplace = false, autoTypos = false; std::map autoReplacements; - bool writeLog = true; + bool writeLog = false; bool screenshotAutoOpenEditor = false; bool useTesseract = false; std::wstring tesseractPath; diff --git a/src/files_lock_processes.inl b/src/files_lock_processes.inl new file mode 100644 index 0000000..3263152 --- /dev/null +++ b/src/files_lock_processes.inl @@ -0,0 +1,245 @@ +bool isSharingError(int error) +{ + return error==ERROR_SHARING_VIOLATION || error==ERROR_LOCK_VIOLATION; +} + +constexpr DWORD lockProbeShare=FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE; +constexpr DWORD lockProbeFlags=FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT; + +DWORD probeDeleteAccess(const fs::path &path) +{ + Handle probe{CreateFileW(path.c_str(),DELETE,lockProbeShare,nullptr,OPEN_EXISTING,lockProbeFlags,nullptr)}; + return probe.value==INVALID_HANDLE_VALUE?GetLastError():ERROR_SUCCESS; +} + +struct LockProcess +{ + DWORD pid; + FILETIME started{}; + std::wstring name; +}; +struct LockScan +{ + std::vector processes; + bool incomplete{}; +}; + +LockScan scanLockProcesses(const std::vector &paths,std::stop_token stop) +{ + LockScan result; + const auto query=reinterpret_cast( + GetProcAddress(GetModuleHandleW(L"ntdll.dll"),"NtQueryInformationFile")); + if(!query) { result.incomplete=true; return result; } + std::set pids; + std::vector buffer(128); + const auto inspect=[&](const fs::path &path) { + const auto error=probeDeleteAccess(path); + if(error==ERROR_SUCCESS) return; + if(!isSharingError(error)) + { + if(error!=ERROR_FILE_NOT_FOUND && error!=ERROR_PATH_NOT_FOUND) result.incomplete=true; + return; + } + Handle file{CreateFileW(path.c_str(),0,lockProbeShare,nullptr,OPEN_EXISTING,lockProbeFlags,nullptr)}; + if(file.value==INVALID_HANDLE_VALUE) {result.incomplete=true;return;} + IO_STATUS_BLOCK status{}; + // FileProcessIdsUsingFileInformation (47) returns an ULONG count followed by aligned ULONG_PTR PIDs. + auto code=query(file.value,&status,buffer.data(),static_cast(buffer.size()*sizeof(ULONG_PTR)), + static_cast(47)); + while((static_cast(code)==0xC0000023 || static_cast(code)==0x80000005 || + static_cast(code)==0xC0000004) && buffer.size()<8192) + { + buffer.resize(buffer.size()*2); + code=query(file.value,&status,buffer.data(),static_cast(buffer.size()*sizeof(ULONG_PTR)), + static_cast(47)); + } + if(code<0 || status.Informationbuffer.size()-1 || size_t(count)+1>status.Information/sizeof(ULONG_PTR)) + { + result.incomplete=true; + return; + } + for(ULONG i=0;i(pid)); + }; + auto remaining=8192u; + const auto deadline=GetTickCount64()+4000; + for(const auto &path:paths) + { + if(stop.stop_requested()) return {}; + inspect(path); + const auto attributes=GetFileAttributesW(path.c_str()); + if(attributes==INVALID_FILE_ATTRIBUTES || !(attributes&FILE_ATTRIBUTE_DIRECTORY) || + (attributes&FILE_ATTRIBUTE_REPARSE_POINT)) continue; + std::error_code error; + fs::recursive_directory_iterator it(path,error),end; + while(!error && it!=end) + { + if(stop.stop_requested()) return {}; + if(!remaining || GetTickCount64()>=deadline) {result.incomplete=true;break;} + --remaining; + const auto item=it->path(); + const auto flags=GetFileAttributesW(item.c_str()); + if(flags==INVALID_FILE_ATTRIBUTES || flags&FILE_ATTRIBUTE_REPARSE_POINT) + it.disable_recursion_pending(); + inspect(item); + it.increment(error); + } + if(error) result.incomplete=true; + } + for(const auto pid:pids) + { + Handle process{OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,pid)}; + LockProcess entry{pid}; + if(process.value) + { + FILETIME exit{},kernel{},user{}; + GetProcessTimes(process.value,&entry.started,&exit,&kernel,&user); + wchar_t path[32768]; + DWORD count=std::size(path); + if(QueryFullProcessImageNameW(process.value,0,path,&count)) + entry.name=fs::path(std::wstring_view(path,count)).filename().wstring(); + } + if(entry.name.empty()) entry.name=L"Unknown process"; + result.processes.push_back(std::move(entry)); + } + return result; +} + +struct LockDialog +{ + std::vector paths; + std::vector processes; + std::future scan; + std::stop_source stop; +}; + +constexpr UINT_PTR lockScanTimer=1; + +void refreshLockProcesses(HWND window,LockDialog &state,std::shared_ptr terminated={}) +{ + if(state.scan.valid()) return; + state.processes.clear(); + SendDlgItemMessageW(window,431,LB_RESETCONTENT,0,0); + EnableWindow(GetDlgItem(window,433),FALSE); + EnableWindow(GetDlgItem(window,434),FALSE); + SetDlgItemTextW(window,430,L"Checking which processes are using the file or folder…"); + try + { + std::packaged_task task([paths=state.paths,stop=state.stop.get_token(),terminated=std::move(terminated)] { + if(terminated) WaitForSingleObject(terminated->value,2500); + return scanLockProcesses(paths,stop); + }); + auto future=task.get_future(); + if(!SetTimer(window,lockScanTimer,50,nullptr)) + throw std::runtime_error("Could not start the process scan."); + std::thread(std::move(task)).detach(); + state.scan=std::move(future); + } + catch(const std::exception &) + { + KillTimer(window,lockScanTimer); + EnableWindow(GetDlgItem(window,434),TRUE); + SetDlgItemTextW(window,430,L"Could not start the process scan."); + } +} + +void endLockProcess(HWND window,LockDialog &state) +{ + const auto index=SendDlgItemMessageW(window,431,LB_GETCURSEL,0,0); + if(index<0 || size_t(index)>=state.processes.size()) return; + const auto &entry=state.processes[index]; + auto error=[&](const wchar_t *message) { + showFilesNotice(window,message,L"End process",{.tone=FilesNoticeTone::warning}); + }; + auto process=std::make_shared(); + process->value=OpenProcess(PROCESS_TERMINATE|PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE,FALSE,entry.pid); + FILETIME started{},exited{},kernel{},user{}; + BOOL critical{}; + if(!process->value || !(entry.started.dwHighDateTime || entry.started.dwLowDateTime) || + !GetProcessTimes(process->value,&started,&exited,&kernel,&user) || + CompareFileTime(&started,&entry.started)!=0 || !IsProcessCritical(process->value,&critical) || critical) + { + error(L"This process has exited, is protected, or cannot be identified."); + return; + } + const auto question=L"End "+entry.name+L" (PID "+std::to_wstring(entry.pid)+ + L")?\r\nUnsaved work in the process may be lost."; + if(showFilesNotice(window,question.c_str(),L"End process",{.confirm=true,.tone=FilesNoticeTone::warning})!=IDYES) + return; + if(WaitForSingleObject(process->value,0)==WAIT_TIMEOUT && !TerminateProcess(process->value,1)) + { + const auto message=ks::lastError(L"Could not end the process"); + error(message.c_str()); + return; + } + refreshLockProcesses(window,state,std::move(process)); +} + +INT_PTR CALLBACK lockProcessesDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) +{ + if(message==WM_INITDIALOG) + { + SetWindowLongPtrW(window,DWLP_USER,lp); + prepareCopyDialog(window); + for(const auto id:{430,431}) SendDlgItemMessageW(window,id,WM_SETFONT,reinterpret_cast(mono),FALSE); + layoutDialogButtons(window,432,{433,434,IDOK}); + SendMessageW(window,DM_SETDEFID,IDOK,0); + SetFocus(GetDlgItem(window,IDOK)); + refreshLockProcesses(window,*reinterpret_cast(lp)); + return FALSE; + } + auto *data=reinterpret_cast(GetWindowLongPtrW(window,DWLP_USER)); + if(!data) return FALSE; + auto &state=*data; + if(message==WM_TIMER && wp==lockScanTimer) + { + if(!state.scan.valid() || state.scan.wait_for(std::chrono::seconds(0))!=std::future_status::ready) + return TRUE; + KillTimer(window,lockScanTimer); + EnableWindow(GetDlgItem(window,434),TRUE); + try + { + auto result=state.scan.get(); + for(auto &entry:result.processes) + { + const auto label=entry.name+L" (PID "+std::to_wstring(entry.pid)+L")"; + if(SendDlgItemMessageW(window,431,LB_ADDSTRING,0,reinterpret_cast(label.c_str()))>=0) + state.processes.push_back(std::move(entry)); + } + SetDlgItemTextW(window,430,state.processes.empty()? + (result.incomplete?L"No processes found. Some items could not be checked.":L"No locking processes found."): + (result.incomplete?L"Possible locking processes. The scan was incomplete.":L"Processes using locked files or folders.")); + if(!state.processes.empty()) + { + SendDlgItemMessageW(window,431,LB_SETCURSEL,0,0); + EnableWindow(GetDlgItem(window,433),TRUE); + } + } + catch(const std::exception &) {SetDlgItemTextW(window,430,L"Could not check for locking processes.");} + return TRUE; + } + if(message==WM_COMMAND) + { + switch(LOWORD(wp)) + { + case 433: endLockProcess(window,state); return TRUE; + case 434: refreshLockProcesses(window,state); return TRUE; + case IDOK: + case IDCANCEL: FilesModalDialog::finish(window,IDCANCEL); return TRUE; + } + } + if(message==WM_CLOSE) {FilesModalDialog::finish(window,IDCANCEL);return TRUE;} + return paintCopyDialog(window,message,wp,lp,L" Locking processes ",false,{432}); +} + +void showLockProcesses(HWND owner,std::vector paths) +{ + LockDialog state{std::move(paths)}; + FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(609),owner,lockProcessesDialog, + reinterpret_cast(&state)); + state.stop.request_stop(); +} diff --git a/src/files_main.cpp b/src/files_main.cpp index 6fc9414..3d60629 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include "files_terminal.h" #include "files_text_window.h" #include "files_menu_navigation.h" @@ -176,9 +177,12 @@ DWORD listElevatedFolder(const fs::path &directory, const std::wstring &pipeName 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) +struct ElevatedFolderListing +{ + Handle pipe{}, process{}; +}; + +DWORD launchElevatedFolder(HWND owner,const fs::path &directory,ElevatedFolderListing &session) { GUID id{}; wchar_t token[40]{}, executable[32768]{}; @@ -186,9 +190,9 @@ DWORD requestElevatedFolder(HWND owner,const fs::path &directory, 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(); + session.pipe.value=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(session.pipe.value==INVALID_HANDLE_VALUE) return GetLastError(); auto parameters=L"--list-folder \""+(directory/L".").wstring()+L"\" \""+name+L"\""; SHELLEXECUTEINFOW launch{}; launch.cbSize=sizeof(launch); @@ -199,23 +203,31 @@ DWORD requestElevatedFolder(HWND owner,const fs::path &directory, launch.lpParameters=parameters.c_str(); launch.nShow=SW_HIDE; if(!ShellExecuteExW(&launch)) return GetLastError(); - Handle process{launch.hProcess}; + session.process.value=launch.hProcess; + return ERROR_SUCCESS; +} + + +DWORD readElevatedFolder(const ElevatedFolderListing &session,const fs::path &directory, + std::vector &folders,std::vector &files, + std::map &metadata,std::stop_token stop) +{ bool connected=false; bool finished=false; auto deadline=GetTickCount64()+10000; - while(GetTickCount64() peer; + bool offerElevation{}; + uint64_t statusRevision{}; + std::shared_ptr elevated; + }; + struct ScanResult + { + DirectoryWatch watch; + std::vector folders, files; + std::map metadata; + std::map timestamps; + DWORD error{}; + bool opened{}; + std::wstring failure; + }; + std::optional scanRequest; + std::future> scan; + std::stop_source scanStop; + bool scanSuperseded{}; std::map timestamps; std::vector rows; std::vector sizes; @@ -447,6 +481,7 @@ struct FilesNoticeOptions bool confirm{}; bool *remember{}; FilesNoticeTone tone{FilesNoticeTone::dialog}; + bool processes{}; }; INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,FilesNoticeOptions options={}); void openMenu(HWND window, int index); @@ -922,7 +957,12 @@ void layout(HWND window,bool activeOnly) RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN); } -void setStatus(const std::wstring &message) { SetWindowTextW(status, message.c_str()); } +uint64_t statusRevision{}; +void setStatus(const std::wstring &message) +{ + ++statusRevision; + SetWindowTextW(status, message.c_str()); +} void showTerminal(HWND owner,bool show) { @@ -1360,15 +1400,12 @@ void showFileDetails(const Panel &panel) SYSTEMTIME modified{}; wchar_t date[64]{}; bool haveTime=false; - if(panel.peer) + if(const auto found=panel.timestamps.find(path); found!=panel.timestamps.end()) { - if(const auto found=panel.timestamps.find(path); found!=panel.timestamps.end()) - { - data.ftLastWriteTime={static_cast(found->second),static_cast(found->second>>32)}; - haveTime=true; - } + data.ftLastWriteTime={static_cast(found->second),static_cast(found->second>>32)}; + haveTime=true; } - else haveTime=GetFileAttributesExW(path.c_str(),GetFileExInfoStandard,&data)!=FALSE; + else if(!panel.peer) haveTime=GetFileAttributesExW(path.c_str(),GetFileExInfoStandard,&data)!=FALSE; if(haveTime && FileTimeToSystemTime(&data.ftLastWriteTime,&modified)) { SYSTEMTIME local{}; @@ -1393,21 +1430,37 @@ void showFileDetails(const Panel &panel) setStatus(details); } -void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::optional peer) +std::unique_ptr scanDirectory(const Panel::ScanRequest &request,std::stop_token stop) { - const auto previousDirectory=(panel.peer?panel.peer->id:std::string{})== - (peer?peer->id:std::string{})?panel.directory:fs::path{}; - const bool sameDirectory=previousDirectory==directory; - // Start watching before enumeration so changes during a scan trigger another refresh. - Panel::DirectoryWatch nextWatch; - if(!peer && (!sameDirectory || panel.watch.handle==INVALID_HANDLE_VALUE)) - nextWatch.start(directory); + auto result=std::make_unique(); + auto &[watch,folders,files,metadata,timestamps,error,opened,failure]=*result; + const auto &directory=request.directory; + const auto &peer=request.peer; + if(stop.stop_requested()) return result; + if(request.elevated) + { + error=readElevatedFolder(*request.elevated,directory,folders,files,metadata,stop); + opened=error==ERROR_SUCCESS; + if(opened) + { + watch.start(directory); + std::sort(folders.begin(),folders.end()); + std::sort(files.begin(),files.end()); + } + else failure=error==ERROR_ACCESS_DENIED?L"Windows denied access after elevation: "+directory.wstring(): + L"Could not read folder as administrator ("+std::to_wstring(error)+L"): "+directory.wstring(); + return result; + } + if(!peer) watch.start(directory); WIN32_FIND_DATAW data{}; const auto search=peer?INVALID_HANDLE_VALUE:FindFirstFileW((directory/L"*").c_str(),&data); - auto error=search==INVALID_HANDLE_VALUE ? GetLastError() : ERROR_SUCCESS; - std::vector folders, files; - std::map metadata; - std::map timestamps; + struct SearchHandle + { + HANDLE handle; + ~SearchHandle(){if(handle!=INVALID_HANDLE_VALUE) FindClose(handle);} + } searchHandle{search}; + error=search==INVALID_HANDLE_VALUE && !peer ? GetLastError() : ERROR_SUCCESS; + opened=search!=INVALID_HANDLE_VALUE; if(peer) { try @@ -1415,22 +1468,58 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti FilesConnection host(&*peer); listFiles(host,directory,[&](const fs::path &path,const FileInfo &info) { + if(stop.stop_requested()) return false; (info.attributes&FILE_ATTRIBUTE_DIRECTORY?folders:files).push_back(path); metadata.emplace(path,FolderEntryMetadata{info.attributes,info.size}); timestamps.emplace(path,info.modified); return true; }); - error=ERROR_SUCCESS; + opened=true; } - catch(const std::system_error &e){setStatus(peer->name+L" — "+fileError(e));return;} - catch(const std::exception &){setStatus(L"Cannot open folder on "+peer->name);return;} + catch(const std::system_error &e){result->failure=peer->name+L" — "+fileError(e);} + catch(const std::exception &){result->failure=L"Cannot open folder on "+peer->name;} } - if (error!=ERROR_SUCCESS && error!=ERROR_FILE_NOT_FOUND) + if(search!=INVALID_HANDLE_VALUE) + { + do + { + if(stop.stop_requested()) return result; + 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}); + timestamps.emplace(path,(uint64_t(data.ftLastWriteTime.dwHighDateTime)<<32)|data.ftLastWriteTime.dwLowDateTime); + } while(FindNextFileW(search,&data)); + error=GetLastError(); + } + std::sort(folders.begin(), folders.end()); + std::sort(files.begin(), files.end()); + return result; +} + +void startDirectoryScan(Panel &panel); + +bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResult &scan) +{ + const auto &directory=request.directory; + auto &peer=request.peer; + const auto previousDirectory=(panel.peer?panel.peer->id:std::string{})== + (peer?peer->id:std::string{})?panel.directory:fs::path{}; + const bool sameDirectory=previousDirectory==directory; + auto &[nextWatch,folders,files,metadata,timestamps,error,opened,failure]=scan; + if(!failure.empty()) + { + setStatus(failure); + return false; + } + if (!scan.opened && 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()) + if(request.offerElevation && denied && !IsUserAnAdmin()) { auto owner=GetParent(panel.list); auto path=directory.wstring(); @@ -1440,37 +1529,28 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti if(rememberElevationApproval || showFilesNotice(owner,question.c_str(), L"KSwitcher Files",{.confirm=true,.remember=&remember})==IDYES) { - const auto result=requestElevatedFolder(owner,directory,folders,files,metadata); + auto elevated=std::make_shared(); + const auto result=launchElevatedFolder(owner,directory,*elevated); 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; + return false; } rememberElevationApproval=rememberElevationApproval || remember; - error=ERROR_SUCCESS; + setStatus(L"Loading folder…"); + request.statusRevision=statusRevision; + request.elevated=std::move(elevated); + panel.scanRequest=std::move(request); + startDirectoryScan(panel); + return true; } } - if(error) return; + if(error) return false; } - 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()); + const bool updateDetails=statusRevision==request.statusRevision; std::set markedPaths; fs::path previousSelection; LRESULT previousRow=0, previousTop=0; @@ -1491,7 +1571,7 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti panel.folderSizeQuery={}; panel.folderSizes.clear(); } - if(!sameDirectory || nextWatch.handle!=INVALID_HANDLE_VALUE) + if(!sameDirectory || panel.watch.handle==INVALID_HANDLE_VALUE) { panel.watch.reset(); std::swap(panel.watch.handle,nextWatch.handle); @@ -1503,6 +1583,8 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti panel.marked.clear(); panel.fileExtensionLength=panel.folderExtensionLength=0; SendMessageW(panel.list, LB_RESETCONTENT, 0, 0); + const auto rowCount = folders.size() + files.size() + directory.has_relative_path(); + SendMessageW(panel.list, LB_INITSTORAGE, rowCount, 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) @@ -1536,6 +1618,11 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti const auto child=std::find(panel.rows.begin(),panel.rows.end(),previousDirectory); if(child!=panel.rows.end()) selected=child; } + if(!request.selection.empty()) + { + const auto requested=std::find(panel.rows.begin(),panel.rows.end(),request.selection); + if(requested!=panel.rows.end()) selected=requested; + } if(selected!=panel.rows.end()) { if(sameDirectory) SendMessageW(panel.list,LB_SETTOPINDEX,previousTop,0); @@ -1544,7 +1631,68 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti InvalidateRect(panel.list,nullptr,FALSE); if(error!=ERROR_SUCCESS && error!=ERROR_NO_MORE_FILES && error!=ERROR_FILE_NOT_FOUND) setStatus(L"Some entries could not be read."); - else if(&panel==&panels[active]) showFileDetails(panel); + else if(updateDetails && &panel==&panels[active]) showFileDetails(panel); + return true; +} + +void startDirectoryScan(Panel &panel) +{ + panel.scanStop=std::stop_source{}; + std::packaged_task()> task( + [request=*panel.scanRequest,stop=panel.scanStop.get_token()] {return scanDirectory(request,stop);}); + auto future=task.get_future(); + std::thread(std::move(task)).detach(); + panel.scan=std::move(future); + panel.scanSuperseded=false; +} + +void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::optional peer, + fs::path selection={},fs::path fallback={}) +{ + if(directory.empty()) return; + if(&panel==&panels[active] && (directory!=panel.directory || + (peer?peer->id:std::string{})!=(panel.peer?panel.peer->id:std::string{}))) + setStatus(L"Loading folder…"); + panel.scanRequest=Panel::ScanRequest{directory,std::move(selection),std::move(fallback), + std::move(peer),offerElevation,statusRevision}; + if(panel.scan.valid()) + { + panel.scanSuperseded=true; + panel.scanStop.request_stop(); + } + else startDirectoryScan(panel); +} + +void collectDirectoryScans() +{ + for(auto &panel:panels) + { + if(!panel.scan.valid() || panel.scan.wait_for(std::chrono::seconds(0))!=std::future_status::ready) + continue; + if(panel.scanSuperseded) + { + panel.scan={}; + startDirectoryScan(panel); + continue; + } + auto request=std::move(*panel.scanRequest); + panel.scanRequest.reset(); + bool applied=false; + const auto fallback=request.fallback; + try + { + auto result=panel.scan.get(); + applied=applyDirectoryScan(panel,std::move(request),*result); + } + catch(const std::exception &) {setStatus(L"Could not read the folder.");} + if(!applied && !fallback.empty()) openOn(panel,fallback,false,{}); + else if(applied && !panel.scan.valid() && !panel.peer && panel.watch.handle!=INVALID_HANDLE_VALUE && + WaitForSingleObject(panel.watch.handle,0)==WAIT_OBJECT_0) + { + if(!FindNextChangeNotification(panel.watch.handle)) panel.watch.reset(); + openOn(panel,panel.directory,false,{}); + } + } } void open(Panel &panel,const fs::path &directory,bool offerElevation=false) @@ -1554,6 +1702,8 @@ void open(Panel &panel,const fs::path &directory,bool offerElevation=false) void selectPanelPath(Panel &panel,const fs::path &path) { + if(panel.scanRequest && path.parent_path()==panel.scanRequest->directory) + panel.scanRequest->selection=path; const auto row=std::find(panel.rows.begin(),panel.rows.end(),path); if(row==panel.rows.end()) return; SendMessageW(panel.list,LB_SETCURSEL,row-panel.rows.begin(),0); @@ -1565,6 +1715,7 @@ void refreshChangedPanels() { for(auto &panel:panels) { + if(panel.scan.valid()) continue; const auto watch=panel.watch.handle; if(watch==INVALID_HANDLE_VALUE || WaitForSingleObject(watch,0)!=WAIT_OBJECT_0) continue; if(!FindNextChangeNotification(watch)) panel.watch.reset(); @@ -2183,6 +2334,12 @@ void enter(Panel &panel) enum class ConflictMode { ask, overwrite, skip, rename, append, newer }; +struct CopyDestination +{ + fs::path directory, newName; + bool useSourcePeer{}; +}; + struct CopyRequest { std::vector sources; @@ -2193,6 +2350,7 @@ struct CopyRequest bool askReadOnly=true; bool move{}; const FilesPeer *sourcePeer{}, *destinationPeer{}, *otherPeer{}; + std::future validation; }; bool directoryExists(const FilesPeer *peer,const fs::path &path) @@ -2724,6 +2882,67 @@ void drawFarComboRow(const DRAWITEMSTRUCT &item) paintText(item.hDC,item.rcItem,label,palette.text,selected?palette.selection:palette.surface); } +CopyDestination validateCopyDestination(CopyRequest request,const std::wstring &value, + const std::optional &source,const std::optional &other) +{ + request.sourcePeer=source?&*source:nullptr; + request.otherPeer=request.destinationPeer=other?&*other:nullptr; + bool useSourcePeer=false; + if(request.move) + { + const fs::path entered(value); + const bool bareName=request.sources.size()==1 && entered==entered.filename() && + entered!=L"." && entered!=L".."; + const auto initial=request.otherDirectory; + const bool usesOtherPanel=entered==initial || entered==initial/L"" || + (request.otherPeer && entered.is_absolute()); + const auto target=usesOtherPanel?entered:request.sources.front().parent_path()/entered; + const auto peer=usesOtherPanel?request.otherPeer:request.sourcePeer; + const bool targetIsDirectory=!value.empty() && value.find_first_of(L"<>|?*")==value.npos && + !bareName && directoryExists(peer,target); + if(value.empty() || value.find_first_of(L"<>|?*")!=value.npos || + (!targetIsDirectory && (request.sources.size()!=1 || !target.has_filename()))) + throw std::runtime_error(ks::utf8(L"Enter an existing destination folder, or a new name for one item.")); + request.destinationPeer=peer; + useSourcePeer=!usesOtherPanel; + request.newName.clear(); + if(targetIsDirectory) + { + request.destination=target.lexically_normal(); + if(!request.destination.has_filename() && request.destination.has_relative_path()) + request.destination=request.destination.parent_path(); + } + else + { + request.destination=target.parent_path(); + request.newName=target.filename(); + } + } + else if(request.sources.size()==1) + { + const auto &name=value; + if(!validFileName(name)) + throw std::runtime_error(ks::utf8(L"Enter a valid name for the copy.")); + 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.move || request.newName.empty()?request.destination:sourceDirectory; + std::error_code error; + const auto peer=request.move || request.newName.empty()?request.destinationPeer:request.sourcePeer; + if(!directoryExists(peer,destination)) + throw std::runtime_error(ks::utf8(L"The destination folder is unavailable.")); + const bool sameHost=(!peer && !request.sourcePeer) || + (peer && request.sourcePeer && peer->id==request.sourcePeer->id); + const bool sameFolder=sameHost && (peer? + CompareStringOrdinal(destination.c_str(),-1,sourceDirectory.c_str(),-1,TRUE)==CSTR_EQUAL: + fs::equivalent(destination,sourceDirectory,error)); + if(request.newName.empty() && sameFolder) + throw std::runtime_error(ks::utf8(L"Open a different folder in the other panel, or enter a new name for a single item.")); + return {std::move(request.destination),std::move(request.newName),useSourcePeer}; +} + INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp) { constexpr int summary=210, pathField=211, conflicts=212; @@ -2789,109 +3008,142 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp) FilesModalDialog::finish(dialog,IDCANCEL); return TRUE; } - if(message!=WM_COMMAND) return FALSE; + constexpr UINT_PTR validationTimer=1; + if(message!=WM_COMMAND && !(message==WM_TIMER && wp==validationTimer)) return FALSE; auto &request=*reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + const auto showError=[&](const wchar_t *message) + { + showFilesNotice(dialog,message,L"Error",{.tone=FilesNoticeTone::warning}); + SetFocus(GetDlgItem(dialog,pathField)); + }; + if(message==WM_TIMER) + { + if(!request.validation.valid() || + request.validation.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return TRUE; + KillTimer(dialog,validationTimer); + for(const auto control:{pathField,213,214,IDOK}) EnableWindow(GetDlgItem(dialog,control),TRUE); + try + { + auto result=request.validation.get(); + request.destination=std::move(result.directory); + request.newName=std::move(result.newName); + request.destinationPeer=result.useSourcePeer?request.sourcePeer:request.otherPeer; + FilesModalDialog::finish(dialog,IDOK); + } + catch(const std::system_error &e) {showError(fileError(e).c_str());} + catch(const std::exception &e) {showError(ks::wide(e.what()).c_str());} + return TRUE; + } if(LOWORD(wp)==213) { InvalidateRect(GetDlgItem(dialog,213),nullptr,FALSE); return FALSE; } if(LOWORD(wp)!=IDOK) return FALSE; - const auto showError=[&](const wchar_t *message) - { - showFilesNotice(dialog,message,L"Error",{.tone=FilesNoticeTone::warning}); - SetFocus(GetDlgItem(dialog,pathField)); - }; + if(request.validation.valid()) return TRUE; try { - if(request.move) - { - const auto field=GetDlgItem(dialog,pathField); - std::wstring value(GetWindowTextLengthW(field)+1,L'\0'); - value.resize(GetWindowTextW(field,value.data(),static_cast(value.size()))); - const fs::path entered(value); - const bool bareName=request.sources.size()==1 && entered==entered.filename() && - entered!=L"." && entered!=L".."; - const auto initial=request.otherDirectory; - const bool usesOtherPanel=entered==initial || entered==initial/L"" || - (request.otherPeer && entered.is_absolute()); - const auto target=usesOtherPanel?entered:request.sources.front().parent_path()/entered; - const auto peer=usesOtherPanel?request.otherPeer:request.sourcePeer; - if(value.empty() || value.find_first_of(L"<>|?*")!=value.npos || - (!directoryExists(peer,target) && - (request.sources.size()!=1 || !target.has_filename() || !directoryExists(peer,target.parent_path())))) - { - showError(L"Enter an existing destination folder, or a new name for one item."); - return TRUE; - } - request.destinationPeer=peer; - request.newName.clear(); - if(!bareName && directoryExists(peer,target)) - { - request.destination=target.lexically_normal(); - if(!request.destination.has_filename() && request.destination.has_relative_path()) - request.destination=request.destination.parent_path(); - } - else - { - request.destination=target.parent_path(); - request.newName=target.filename(); - } - } - else 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(!validFileName(name)) - { - showError(L"Enter a valid name for the copy."); - 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.move || request.newName.empty()?request.destination:sourceDirectory; - std::error_code error; - const auto peer=request.move || request.newName.empty()?request.destinationPeer:request.sourcePeer; - if(!directoryExists(peer,destination)) - { - showError(L"The destination folder is unavailable."); - return TRUE; - } - const bool sameHost=(!peer && !request.sourcePeer) || - (peer && request.sourcePeer && peer->id==request.sourcePeer->id); - const bool sameFolder=sameHost && (peer? - CompareStringOrdinal(destination.c_str(),-1,sourceDirectory.c_str(),-1,TRUE)==CSTR_EQUAL: - fs::equivalent(destination,sourceDirectory,error)); - if(request.newName.empty() && sameFolder) - { - showError(L"Open a different folder in the other panel, or enter a new name for a single item."); - return TRUE; - } + const auto field=GetDlgItem(dialog,pathField); + std::wstring value(GetWindowTextLengthW(field)+1,L'\0'); + value.resize(GetWindowTextW(field,value.data(),static_cast(value.size()))); request.askReadOnly=IsDlgButtonChecked(dialog,214)==BST_CHECKED; const auto mode=SendDlgItemMessageW(dialog,213,CB_GETCURSEL,0,0); if(mode!=CB_ERR) request.conflictMode=static_cast( request.move && mode==static_cast(ConflictMode::append)?static_cast(ConflictMode::newer):mode); - FilesModalDialog::finish(dialog,IDOK); + const auto peer=[](const FilesPeer *value) { + return value?std::optional(*value):std::nullopt; + }; + CopyRequest snapshot{request.sources,request.destination,{},request.otherDirectory}; + snapshot.move=request.move; + std::packaged_task validation( + [snapshot=std::move(snapshot),value=std::move(value), + source=peer(request.sourcePeer),other=peer(request.otherPeer)]() mutable { + return validateCopyDestination(std::move(snapshot),value,source,other); + }); + auto ready=validation.get_future(); + if(!SetTimer(dialog,validationTimer,50,nullptr)) + throw std::runtime_error("Could not start destination validation."); + std::thread(std::move(validation)).detach(); + request.validation=std::move(ready); + SetFocus(GetDlgItem(dialog,IDCANCEL)); + for(const auto control:{pathField,213,214,IDOK}) EnableWindow(GetDlgItem(dialog,control),FALSE); } - catch(const std::system_error &e) + catch(const std::exception &e) { - showError(fileError(e).c_str()); - } - catch(const std::exception &) - { - showError(L"The remote destination is unavailable."); + KillTimer(dialog,validationTimer); + showError(ks::wide(e.what()).c_str()); } return TRUE; } +// Run blocking file work on one worker while the existing modal dialog owns input. +class FileOperationUi +{ + Handle wake_{CreateEventW(nullptr,FALSE,FALSE,nullptr)}; + std::mutex mutex_; + std::function request_; + + public: + template auto invoke(F &&action) + { + std::packaged_task()> task(std::forward(action)); + auto result=task.get_future(); + { + std::lock_guard lock(mutex_); + request_=[&task] {task();}; + } + SetEvent(wake_.value); + return result.get(); + } + + template void run(HWND window,std::atomic_bool &canceled,F &&work) + { + if(!wake_.value) throw std::system_error(GetLastError(),std::system_category()); + std::packaged_task task(std::forward(work)); + auto result=task.get_future(); + std::thread worker([&] {task();SetEvent(wake_.value);}); + std::optional quit; + const auto owner=GetWindow(window,GW_OWNER); + while(result.wait_for(std::chrono::seconds(0))!=std::future_status::ready) + { + MsgWaitForMultipleObjectsEx(1,&wake_.value,INFINITE,QS_ALLINPUT,MWMO_INPUTAVAILABLE); + MSG message{}; + while(PeekMessageW(&message,nullptr,0,0,PM_REMOVE)) + { + if(message.message==WM_QUIT) + { + quit=static_cast(message.wParam); + canceled=true; + continue; + } + if(message.message==WM_SYSKEYDOWN && message.wParam==VK_F4 && + (message.hwnd==owner || IsChild(owner,message.hwnd))) + { + SendMessageW(owner,WM_CLOSE,0,0); + continue; + } + if(FilesModalDialog::handleMessage(window,message)) continue; + TranslateMessage(&message); + DispatchMessageW(&message); + } + std::function request; + { + std::lock_guard lock(mutex_); + request=std::exchange(request_,{}); + } + if(request) request(); + } + worker.join(); + if(quit) PostQuitMessage(*quit); + result.get(); + } +}; + struct CopyProgress { + FileOperationUi ui; HWND window{}; - bool canceled{}; + std::atomic_bool canceled{}; bool closeOwner{}; bool move{}; int conflictChoice{}; @@ -2902,6 +3154,7 @@ struct CopyProgress const wchar_t *lastSkipReason=L""; ULONGLONG lastPaint{}; fs::path from,to,renamedTarget; + fs::path localLockSource,localLockTarget; }; bool copyInProgress{}; CopyProgress *activeCopy{}; @@ -2938,12 +3191,9 @@ LRESULT CALLBACK paintCopyProgressBar(HWND bar,UINT message,WPARAM wp,LPARAM lp, return 0; } -void updateCopyProgress(CopyProgress &progress,uint64_t current,uint64_t fileSize,bool force=false) +void updateCopyProgress(CopyProgress &progress,uint64_t current,uint64_t fileSize) { - constexpr ULONGLONG refreshIntervalMs=200; - const auto now=GetTickCount64(); - if(!force && now-progress.lastPaint=200) + progress.ui.invoke([&] {updateCopyProgress(progress,current,fileSize);}); +} + LRESULT CALLBACK dialogButtonEnter(HWND button,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) { if(message==WM_GETDLGCODE) @@ -3192,6 +3448,8 @@ struct FilesNotice FilesNoticeOptions options; }; +constexpr int showProcessesButton=103; + void layoutFilesNotice(HWND dialog) { const auto ¬ice=*reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); @@ -3235,6 +3493,7 @@ void layoutFilesNotice(HWND dialog) } place(102,bottom+dialogRowGap()+4,1); if(notice.options.confirm) layoutDialogButtons(dialog,102,{IDYES,IDNO}); + else if(notice.options.processes) layoutDialogButtons(dialog,102,{showProcessesButton,IDOK}); else layoutDialogButtons(dialog,102,{IDOK}); } @@ -3261,6 +3520,7 @@ INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) ShowWindow(GetDlgItem(window,IDYES),SW_SHOW); ShowWindow(GetDlgItem(window,IDNO),SW_SHOW); } + if(notice.options.processes) ShowWindow(GetDlgItem(window,showProcessesButton),SW_SHOW); RECT caption{},text{}; if(const auto dc=GetDC(window)) { @@ -3272,7 +3532,7 @@ INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) } const auto inset=dialogFrameMetrics(GetDpiForWindow(window)).content(); const auto minimum=std::max({24L*cellWidth,caption.right+6*cellWidth, - notice.options.remember?30L*cellWidth:0L})+2*inset; + notice.options.remember || notice.options.processes?34L*cellWidth:0L})+2*inset; const auto width=std::clamp(text.right+cellWidth+2*inset,minimum,std::max(minimum,60L*cellWidth+2*inset)); SetWindowPos(window,nullptr,0,0,width,1,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE); layoutFilesNotice(window); @@ -3296,7 +3556,8 @@ INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) if(const auto painted=paintCopyDialog(window,message,wp,lp,notice->title.c_str(),warning,{102},palette)) return painted; const auto command=LOWORD(wp); - if(message==WM_COMMAND && (command==IDOK || command==IDCANCEL || command==IDYES || command==IDNO)) + if(message==WM_COMMAND && (command==IDOK || command==IDCANCEL || command==IDYES || command==IDNO || + (command==showProcessesButton && notice->options.processes))) { if(command==IDYES && notice->options.remember) *notice->options.remember=IsDlgButtonChecked(window,101)==BST_CHECKED; @@ -3321,6 +3582,17 @@ INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,File return result; } +#include "files_lock_processes.inl" + +void showFileOperationError(HWND owner,const wchar_t *title,const std::wstring &message, + std::vector lockPaths={}) +{ + setStatus(L""); + const auto choice=showFilesNotice(owner,message.c_str(),title, + {.tone=FilesNoticeTone::warning,.processes=!lockPaths.empty()}); + if(choice==showProcessesButton) showLockProcesses(owner,std::move(lockPaths)); +} + void showTextMessage(HWND owner,const wchar_t *text) { showFilesNotice(owner,text,L"KSwitcher Files"); @@ -3554,31 +3826,6 @@ INT_PTR CALLBACK warningDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) 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); - if(message.message==WM_SYSKEYDOWN && message.wParam==VK_F4 && - (message.hwnd==owner || IsChild(owner,message.hwnd))) - { - SendMessageW(owner,WM_CLOSE,0,0); - continue; - } - if(FilesModalDialog::handleMessage(progress.window,message)) continue; - TranslateMessage(&message); - DispatchMessageW(&message); - } - return !progress.canceled; -} - using FileEntries=std::vector>; FileEntries childrenOf(FilesConnection &host,const fs::path &path) @@ -3594,7 +3841,7 @@ FileEntries childrenOf(FilesConnection &host,const fs::path &path) bool countCopy(FilesConnection &host,const fs::path &path,CopyProgress &progress) { - if(!pumpCopy(progress)) return false; + if(progress.canceled) return false; const auto info=statFile(host,path); if(!info || (info->attributes&FILE_ATTRIBUTE_REPARSE_POINT)) throw std::system_error(info?ERROR_NOT_SUPPORTED:ERROR_FILE_NOT_FOUND,std::system_category()); @@ -3616,6 +3863,7 @@ struct CopyEndpoints FilesConnection &source, ⌖ bool sameHost; std::string sourceId; + bool sourceLocal, targetLocal; }; void transferFile(const CopyEndpoints &hosts,const fs::path &from,const fs::path &to, @@ -3623,8 +3871,8 @@ void transferFile(const CopyEndpoints &hosts,const fs::path &from,const fs::path { const auto update=[&](uint64_t done,uint64_t total) { - updateCopyProgress(progress,done,total); - return pumpCopy(progress); + reportCopyProgress(progress,done,total); + return !progress.canceled; }; if(hosts.sameHost) { @@ -3644,7 +3892,9 @@ void transferFile(const CopyEndpoints &hosts,const fs::path &from,const fs::path CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::path &to,CopyProgress &progress, bool topLevel=false,bool singleItem=false) { - if(!pumpCopy(progress)) return CopyResult::failed; + if(progress.canceled) return CopyResult::failed; + progress.localLockSource=hosts.sourceLocal?from:fs::path{}; + progress.localLockTarget=hosts.targetLocal?to:fs::path{}; const auto incoming=statFile(hosts.source,from); if(!incoming || (incoming->attributes&FILE_ATTRIBUTE_REPARSE_POINT)) throw std::system_error(incoming?ERROR_NOT_SUPPORTED:ERROR_FILE_NOT_FOUND,std::system_category()); @@ -3681,7 +3931,11 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa if(outcome==CopyResult::skipped) result=outcome; } if(progress.move && result==CopyResult::complete) + { + progress.localLockSource=hosts.sourceLocal?from:fs::path{}; + progress.localLockTarget.clear(); checkFileReply(hosts.source.call(fileRequest("rmdir",from))); + } return result; } @@ -3690,6 +3944,7 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa const auto fileSize=incoming->size; const auto transfer=[&](const fs::path &target,bool replace=false,bool append=false) { + if(hosts.targetLocal) progress.localLockTarget=target; if(!moveOnHost(target,replace)) { transferFile(hosts,from,target,*incoming,replace,append,progress); @@ -3703,7 +3958,7 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa } progress.bytes+=fileSize; ++progress.files; - updateCopyProgress(progress,0,0); + reportCopyProgress(progress,0,0); return CopyResult::complete; }; const auto skip=[&](const wchar_t *reason) @@ -3711,10 +3966,10 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa progress.skippedBytes+=fileSize; ++progress.skippedFiles; progress.lastSkipReason=reason; - updateCopyProgress(progress,0,0); + reportCopyProgress(progress,0,0); return CopyResult::skipped; }; - updateCopyProgress(progress,0,fileSize); + reportCopyProgress(progress,0,fileSize); if(!existing) return transfer(to); if(existing->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)) throw std::system_error(ERROR_ALREADY_EXISTS,std::system_category()); @@ -3729,7 +3984,7 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa { for(unsigned index=2;index<=10000;++index) { - if(!pumpCopy(progress)) return CopyResult::failed; + if(progress.canceled) return CopyResult::failed; const auto name=to.stem().wstring()+L" ("+std::to_wstring(index)+L")"+to.extension().wstring(); const auto candidate=to.parent_path()/name; if(statFile(hosts.target,candidate)) continue; @@ -3745,13 +4000,17 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa { WarningPrompt warning{readOnly?L"Existing file is read-only":L"File already exists", to.c_str(),L"&Overwrite",L"&Skip",*incoming,*existing}; - warningBrush=CreateSolidBrush(RGB(128,0,0)); - answer=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(104),progress.window, - warningDialog,reinterpret_cast(&warning)); + answer=progress.ui.invoke([&] { + if(progress.canceled) return static_cast(IDCANCEL); + warningBrush=CreateSolidBrush(RGB(128,0,0)); + const auto choice=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(104),progress.window, + warningDialog,reinterpret_cast(&warning)); + DeleteObject(warningBrush); + warningBrush=nullptr; + return choice; + }); 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) @@ -3778,7 +4037,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move) if(request.sources.empty()) return; const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(102),owner,copyDialog, reinterpret_cast(&request)); - if(result==-1) setStatus(L"Could not open the Copy dialog."); + if(result==-1) showFileOperationError(owner,move?L"Move failed":L"Copy failed",L"Could not open the operation dialog."); if(result!=IDOK) return; const bool renamed=!request.newName.empty(); @@ -3795,7 +4054,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move) progress.window=progressDialog.window(); if(!progress.window) { - setStatus(L"Could not open copy progress."); + showFileOperationError(owner,move?L"Move failed":L"Copy failed",L"Could not open the progress dialog."); return; } copyInProgress=true; @@ -3807,57 +4066,71 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move) size_t copied=0; std::set results; std::wstring failure; + std::vector lockPaths; try { - FilesConnection sourceHost(request.sourcePeer); - std::unique_ptr otherHost; - if(!sameHost) otherHost=std::make_unique(targetPeer); - const CopyEndpoints hosts{sourceHost,otherHost?*otherHost:sourceHost,sameHost, - request.sourcePeer?request.sourcePeer->id:"local"}; - for(const auto &path:request.sources) - if(!countCopy(sourceHost,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()); - if(sameHost) + progress.ui.run(progress.window,progress.canceled,[&] { + FilesConnection sourceHost(request.sourcePeer); + std::unique_ptr otherHost; + if(!sameHost) otherHost=std::make_unique(targetPeer); + const CopyEndpoints hosts{sourceHost,otherHost?*otherHost:sourceHost,sameHost, + request.sourcePeer?request.sourcePeer->id:"local",!request.sourcePeer,!targetPeer}; + for(const auto &path:request.sources) + if(!countCopy(sourceHost,path,progress)) { failed=true; break; } + reportCopyProgress(progress,0,0,true); + for(const auto &path:request.sources) { - const auto canonical=[&](const fs::path &name) + if(failed) break; + const auto to=targetDirectory/(renamed?request.newName:path.filename()); + if(sameHost) { - const auto reply=sourceHost.call(fileRequest("canonical",name)); - checkFileReply(reply); - return filePath(reply.at("path")); - }; - const auto canonicalSource=canonical(path); - const auto canonicalTarget=canonical(to); - for(auto ancestor=canonicalTarget;;ancestor=ancestor.parent_path()) - { - if(CompareStringOrdinal(ancestor.c_str(),-1,canonicalSource.c_str(),-1,TRUE)==CSTR_EQUAL) + const auto canonical=[&](const fs::path &name) { - throw std::system_error(ERROR_INVALID_PARAMETER,std::system_category()); + const auto reply=sourceHost.call(fileRequest("canonical",name)); + checkFileReply(reply); + return filePath(reply.at("path")); + }; + const auto canonicalSource=canonical(path); + const auto canonicalTarget=canonical(to); + for(auto ancestor=canonicalTarget;;ancestor=ancestor.parent_path()) + { + if(CompareStringOrdinal(ancestor.c_str(),-1,canonicalSource.c_str(),-1,TRUE)==CSTR_EQUAL) + { + throw std::system_error(ERROR_INVALID_PARAMETER,std::system_category()); + } + if(!ancestor.has_relative_path()) break; } - if(!ancestor.has_relative_path()) break; } + if(failed) break; + progress.renamedTarget.clear(); + const auto outcome=copyItem(hosts,path,to,progress,true,request.sources.size()==1); + if(outcome==CopyResult::failed) { failed=true; break; } + if(outcome==CopyResult::skipped) { skipped=true; continue; } + ++copied; + results.insert(progress.renamedTarget.empty()?to:progress.renamedTarget); + progress.ui.invoke([&] { + 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); + }); } - if(failed) break; - progress.renamedTarget.clear(); - const auto outcome=copyItem(hosts,path,to,progress,true,request.sources.size()==1); - if(outcome==CopyResult::failed) { failed=true; break; } - if(outcome==CopyResult::skipped) { skipped=true; continue; } - ++copied; - results.insert(progress.renamedTarget.empty()?to:progress.renamedTarget); - 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); + }); + } + catch(const std::system_error &e) + { + failed=true; + failure=fileError(e); + if(move && isSharingError(e.code().value())) + { + if(!progress.localLockSource.empty()) lockPaths.push_back(progress.localLockSource); + if(!progress.localLockTarget.empty() && progress.localLockTarget!=progress.localLockSource) + lockPaths.push_back(progress.localLockTarget); } } - catch(const std::system_error &e){failed=true;failure=fileError(e);} catch(const std::exception &){failed=true;failure=L"File connection interrupted.";} const auto targetId=peerId(targetPeer); const bool restoreFocus=GetForegroundWindow()==progress.window; - updateCopyProgress(progress,0,0,true); + updateCopyProgress(progress,0,0); RedrawWindow(progress.window,nullptr,nullptr,RDW_UPDATENOW|RDW_ALLCHILDREN); progressDialog.close(); activeCopy=nullptr; @@ -3907,17 +4180,16 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move) SetForegroundWindow(owner); SetFocus(panels[active].list); } - if(failed && !progress.canceled && !failure.empty()) - setStatus((move?L"Move failed — ":L"Copy failed — ")+failure); + if(failed && !progress.canceled) + showFileOperationError(owner,move?L"Move failed":L"Copy failed", + failure.empty()?L"Could not complete the operation.":failure,std::move(lockPaths)); else if(move) { if(progress.canceled) setStatus(L"Move canceled."); - else if(failed) setStatus(L"Could not complete the move."); else if(skipped) setStatus(L"Move complete with skipped items."); else setStatus(L"Move complete."); } else 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."); } @@ -4048,7 +4320,7 @@ INT_PTR CALLBACK deleteProgressDialog(HWND window,UINT message,WPARAM wp,LPARAM } if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL)) { - auto &canceled=*reinterpret_cast(GetWindowLongPtrW(window,DWLP_USER)); + auto &canceled=*reinterpret_cast(GetWindowLongPtrW(window,DWLP_USER)); if(!canceled) canceled=confirmOperationCancellation(window,L"Do you really want to cancel deletion?"); return TRUE; @@ -4056,26 +4328,6 @@ INT_PTR CALLBACK deleteProgressDialog(HWND window,UINT message,WPARAM wp,LPARAM return FALSE; } -bool pumpDeletion(HWND window,bool &canceled) -{ - MSG message{}; - while(!canceled && PeekMessageW(&message,nullptr,0,0,PM_REMOVE)) - { - if(message.message==WM_QUIT) - { - PostQuitMessage(static_cast(message.wParam)); - canceled=true; - break; - } - if(!FilesModalDialog::handleMessage(window,message)) - { - TranslateMessage(&message); - DispatchMessageW(&message); - } - } - return !canceled; -} - void deleteSelection(HWND owner,Panel &panel,bool permanent) { if(copyInProgress) return; @@ -4095,16 +4347,9 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) L"Move the selected items to the Recycle Bin?"; if(paths.size()==1) { - DWORD attributes=INVALID_FILE_ATTRIBUTES; - try - { - FilesConnection host(panel.peer?&*panel.peer:nullptr); - if(const auto info=statFile(host,paths.front())) attributes=info->attributes; - } - catch(const std::system_error &e){setStatus(fileError(e));DeleteObject(warningBrush);warningBrush=nullptr;return;} - catch(const std::exception &){setStatus(L"File connection interrupted.");DeleteObject(warningBrush);warningBrush=nullptr;return;} - if(attributes!=INVALID_FILE_ATTRIBUTES) - message=attributes&FILE_ATTRIBUTE_DIRECTORY + const auto row=std::find(panel.rows.begin(),panel.rows.end(),paths.front()); + if(row!=panel.rows.end()) + message=panel.sizes[row-panel.rows.begin()]==L"Folder" ? (permanent?L"Delete this folder permanently?":L"Move this folder to the Recycle Bin?") : (permanent?L"Delete this file permanently?":L"Move this file to the Recycle Bin?"); } @@ -4119,7 +4364,8 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) SetFocus(panel.list); return; } - bool canceled=false; + std::atomic_bool canceled{}; + FileOperationUi ui; FilesModalDialog progressDialog(instance,MAKEINTRESOURCEW(107),owner,deleteProgressDialog, reinterpret_cast(&canceled)); const auto window=progressDialog.window(); @@ -4130,131 +4376,156 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) bool all=false; int readOnlyChoice=0; std::vector> groups; - std::wstring failure; + std::wstring failure, sharingFailure; + std::set lockPaths; + const auto recordFailure=[&](const std::system_error &error,const fs::path &path) + { + ++failed; + failure=fileError(error); + if(!panel.peer && isSharingError(error.code().value())) + { + lockPaths.insert(path); + if(sharingFailure.empty()) sharingFailure=failure; + } + }; try { - FilesConnection host(panel.peer?&*panel.peer:nullptr); - const auto collect=[&](auto &&self,const fs::path &path,std::vector &group)->void - { - for(const auto &[child,info]:childrenOf(host,path)) + ui.run(window,canceled,[&] { + FilesConnection host(panel.peer?&*panel.peer:nullptr); + const auto collect=[&](auto &&self,const fs::path &path,std::vector &group)->void { - if(!pumpDeletion(window,canceled)) return; - group.push_back(child); - if((info.attributes&FILE_ATTRIBUTE_DIRECTORY) && !(info.attributes&FILE_ATTRIBUTE_REPARSE_POINT)) - self(self,child,group); - } - }; - for(const auto &path:paths) - { - if(!pumpDeletion(window,canceled)) break; - auto &group=groups.emplace_back(1,path); - if(permanent) - { - try + for(const auto &[child,info]:childrenOf(host,path)) { - const auto info=statFile(host,path); - if(info && (info->attributes&FILE_ATTRIBUTE_DIRECTORY) && - !(info->attributes&FILE_ATTRIBUTE_REPARSE_POINT)) collect(collect,path,group); + if(canceled) return; + group.push_back(child); + if((info.attributes&FILE_ATTRIBUTE_DIRECTORY) && !(info.attributes&FILE_ATTRIBUTE_REPARSE_POINT)) + self(self,child,group); } - catch(const std::system_error &e) - { - failure=fileError(e); - ++failed; - ++total; - group.clear(); - } - } - total+=group.size(); - } - ULONGLONG lastPaint=0; - fs::path current; - const auto update=[&](const fs::path &path,bool force) - { - const auto now=GetTickCount64(); - if(!force && now-lastPaint<200) return; - lastPaint=now; - SetDlgItemTextW(window,245,path.c_str()); - const auto status=(permanent?L"Deleted: ":L"Moved: ")+std::to_wstring(done)+L" / "+std::to_wstring(total)+ - L" Skipped: "+std::to_wstring(skipped)+L" Failed: "+std::to_wstring(failed); - SetDlgItemTextW(window,246,status.c_str()); - const auto bar=GetDlgItem(window,247); - SendMessageW(bar,PBM_SETPOS,total?static_cast(100.0*(done+skipped+failed)/total):0,0); - InvalidateRect(bar,nullptr,FALSE); - }; - for(const auto &group:groups) - { - if(!pumpDeletion(window,canceled)) break; - if(group.empty()) continue; - if(group.size()>1 && !all) + }; + for(const auto &path:paths) { - DeleteConfirmation folder{L"The following folder will be deleted:",group.front().wstring(),1,true,true}; - const auto answer=FilesModalDialog::run(instance,MAKEINTRESOURCEW(106),window,deleteConfirmationDialog, - reinterpret_cast(&folder)); - if(answer==244) all=true; - else if(answer==IDNO) + if(canceled) break; + auto &group=groups.emplace_back(1,path); + if(permanent) { - skipped+=group.size(); - update(group.front(),false); - continue; - } - else if(answer!=IDYES) { canceled=true; break; } - } - for(auto it=group.rbegin();it!=group.rend() && pumpDeletion(window,canceled);++it) - { - current=*it; - update(current,false); - bool readOnly=false; - try - { - const auto info=permanent?statFile(host,current):std::optional{}; - const auto attributes=info?info->attributes:INVALID_FILE_ATTRIBUTES; - if(attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_READONLY) && - !(attributes&FILE_ATTRIBUTE_DIRECTORY)) + try { - auto answer=static_cast(readOnlyChoice); - if(!answer) - { - DeleteConfirmation warning{L"Delete this read-only file?",current.wstring(),1,true,false,true}; - answer=FilesModalDialog::run(instance,MAKEINTRESOURCEW(106),window,deleteConfirmationDialog, - reinterpret_cast(&warning)); - if(answer==244 || answer==249) readOnlyChoice=static_cast(answer); - } - if(answer==IDNO || answer==249) - { - ++skipped; - continue; - } - if(answer!=IDYES && answer!=244) - { - canceled=true; - break; - } - if(attributes&FILE_ATTRIBUTE_REPARSE_POINT) - throw std::system_error(ERROR_ACCESS_DENIED,std::system_category()); - readOnly=true; + const auto info=statFile(host,path); + if(info && (info->attributes&FILE_ATTRIBUTE_DIRECTORY) && + !(info->attributes&FILE_ATTRIBUTE_REPARSE_POINT)) collect(collect,path,group); } - if(!permanent && !panel.peer) + catch(const std::system_error &e) { - if(!ks::lan::recycleFile(window,current)) - throw std::system_error(ERROR_ACCESS_DENIED,std::system_category()); + recordFailure(e,path); + ++total; + group.clear(); } - else - { - auto request=fileRequest(permanent?"remove":"recycle",current); - request["readOnly"]=readOnly; - checkFileReply(host.call(request)); - } - ++done; } - catch(const std::system_error &e) + total+=group.size(); + } + ULONGLONG lastPaint=0; + fs::path current; + const auto update=[&](const fs::path &path,bool force) + { + const auto now=GetTickCount64(); + if(!force && now-lastPaint<200) return; + lastPaint=now; + ui.invoke([&] { + SetDlgItemTextW(window,245,path.c_str()); + const auto status=(permanent?L"Deleted: ":L"Moved: ")+std::to_wstring(done)+L" / "+std::to_wstring(total)+ + L" Skipped: "+std::to_wstring(skipped)+L" Failed: "+std::to_wstring(failed); + SetDlgItemTextW(window,246,status.c_str()); + const auto bar=GetDlgItem(window,247); + SendMessageW(bar,PBM_SETPOS,total?static_cast(100.0*(done+skipped+failed)/total):0,0); + InvalidateRect(bar,nullptr,FALSE); + }); + }; + for(const auto &group:groups) + { + if(canceled) break; + if(group.empty()) continue; + if(group.size()>1 && !all) { - ++failed; - failure=fileError(e); - if(e.code().value()>=10000) break; + DeleteConfirmation folder{L"The following folder will be deleted:",group.front().wstring(),1,true,true}; + const auto answer=ui.invoke([&] { + return canceled?static_cast(IDCANCEL): + FilesModalDialog::run(instance,MAKEINTRESOURCEW(106),window,deleteConfirmationDialog, + reinterpret_cast(&folder)); + }); + if(answer==244) all=true; + else if(answer==IDNO) + { + skipped+=group.size(); + update(group.front(),false); + continue; + } + else if(answer!=IDYES) { canceled=true; break; } + } + for(auto it=group.rbegin();it!=group.rend() && !canceled;++it) + { + current=*it; + update(current,false); + bool readOnly=false; + try + { + const auto info=permanent?statFile(host,current):std::optional{}; + const auto attributes=info?info->attributes:INVALID_FILE_ATTRIBUTES; + if(attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_READONLY) && + !(attributes&FILE_ATTRIBUTE_DIRECTORY)) + { + auto answer=static_cast(readOnlyChoice); + if(!answer) + { + DeleteConfirmation warning{L"Delete this read-only file?",current.wstring(),1,true,false,true}; + answer=ui.invoke([&] { + return canceled?static_cast(IDCANCEL): + FilesModalDialog::run(instance,MAKEINTRESOURCEW(106),window,deleteConfirmationDialog, + reinterpret_cast(&warning)); + }); + if(answer==244 || answer==249) readOnlyChoice=static_cast(answer); + } + if(answer==IDNO || answer==249) + { + ++skipped; + continue; + } + if(answer!=IDYES && answer!=244) + { + canceled=true; + break; + } + if(attributes&FILE_ATTRIBUTE_REPARSE_POINT) + throw std::system_error(ERROR_ACCESS_DENIED,std::system_category()); + readOnly=true; + } + if(!permanent && !panel.peer) + { + const auto error=probeDeleteAccess(current); + if(isSharingError(error)) throw std::system_error(error,std::system_category()); + if(!ks::lan::recycleFile(window,current)) + { + // The Shell can hide the error from an individual item in a folder. + lockPaths.insert(current); + throw std::system_error(ERROR_ACCESS_DENIED,std::system_category()); + } + } + else + { + auto request=fileRequest(permanent?"remove":"recycle",current); + request["readOnly"]=readOnly; + checkFileReply(host.call(request)); + } + ++done; + } + catch(const std::system_error &e) + { + recordFailure(e,current); + if(e.code().value()>=10000) break; + } } } - } - update(current,true); + update(current,true); + }); } catch(const std::system_error &e){++failed;failure=fileError(e);} catch(const std::exception &){++failed;failure=L"File connection interrupted.";} @@ -4264,11 +4535,18 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) for(auto &visible:panels) if(!visible.directory.empty()) open(visible,visible.directory); SetFocus(panel.list); - setStatus((canceled?L"Deletion canceled. ":L"Deletion finished. ")+ + const auto summary=(canceled?L"Deletion canceled. ":L"Deletion finished. ")+ std::to_wstring(done)+(permanent?L" deleted, ":L" moved to Recycle Bin, ")+ - std::to_wstring(skipped)+L" skipped, "+std::to_wstring(failed)+L" failed."+(failure.empty()?L"":L" "+failure)); + std::to_wstring(skipped)+L" skipped, "+std::to_wstring(failed)+L" failed."; + if(failed) + { + const auto &reason=sharingFailure.empty()?failure:sharingFailure; + showFileOperationError(owner,L"Delete failed",summary+(reason.empty()?L"":L"\r\n"+reason), + {lockPaths.begin(),lockPaths.end()}); + } + else setStatus(summary); } - else setStatus(L"Could not open deletion progress."); + else showFileOperationError(owner,L"Delete failed",L"Could not open the progress dialog."); DeleteObject(warningBrush); warningBrush=nullptr; } @@ -4916,7 +5194,16 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) updateTerminalOutput(); return 0; } - if(wp==directoryWatchTimer) { refreshChangedPanels(); collectFolderSizes(); return 0; } + if(wp==directoryWatchTimer) + { + if(!FilesModalDialog::activeFor(window)) + { + collectDirectoryScans(); + refreshChangedPanels(); + } + collectFolderSizes(); + return 0; + } if(wp!=transferHighlightTimer) break; ++transferHighlightPhase; for(auto &panel:panels) @@ -4988,14 +5275,9 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) 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()); + const auto root=fs::path(system).root_path(); + openOn(panel,saved.is_absolute()?saved:root,false,{},savedPanelPath(panelCursorKeys[i]), + saved.is_absolute() && saved!=root?root:fs::path{}); SetWindowSubclass(panel.list, panelKeys, 1, i); } SetFocus(panels[0].list); @@ -5485,7 +5767,11 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) for(auto &panel:panels) panel.folderSizeStop.request_stop(); KillTimer(window,terminalTimer); KillTimer(window,directoryWatchTimer); - for(auto &panel:panels) panel.watch.reset(); + for(auto &panel:panels) + { + panel.scanStop.request_stop(); + panel.watch.reset(); + } terminalView.close(); terminal.close(); if(remoteCommandThread.joinable()) @@ -5502,12 +5788,12 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) { - bool writeLog=true; + bool writeLog=ks::Settings{}.writeLog; try { const auto settings=ks::dataDirectory()/L"settings.json"; if(std::filesystem::exists(settings)) - writeLog=Json::parse(ks::readFile(settings,1024*1024)).value("writeLog",true); + writeLog=Json::parse(ks::readFile(settings,1024*1024)).value("writeLog",writeLog); } catch(const std::exception &) {} ks::setLogFilename(L"kswitcher-files.log"); diff --git a/src/files_text_window.cpp b/src/files_text_window.cpp index 7516a6a..db37ca9 100644 --- a/src/files_text_window.cpp +++ b/src/files_text_window.cpp @@ -1418,7 +1418,7 @@ bool TextWindow::needsSave() const void TextWindow::toggleMode() { - if(navigation.valid()) return; + if (busy() || navigation.valid()) return; if (edit && needsSave()) { const auto answer = search.style.confirmSave(window); diff --git a/src/lan.cpp b/src/lan.cpp index 2e96abc..2df39a0 100644 --- a/src/lan.cpp +++ b/src/lan.cpp @@ -392,8 +392,10 @@ struct LanService::Impl if(socket!=INVALID_SOCKET) closesocket(socket); if(winsock) WSACleanup(); } + std::mutex commandGate; Bytes command(const Bytes &input) { + std::lock_guard commandLock(commandGate); auto j=Json::parse(input); auto action=j.value("action","status"); if(action=="enable") { @@ -403,7 +405,7 @@ struct LanService::Impl configureRouter(); if(enabled) start(); else status="Disabled. No discovery sockets or worker thread."; } - std::lock_guard lock(mutex); + std::unique_lock lock(mutex); auto now=GetTickCount64(); if(action=="filesPeers") refreshFiles=true; if(action=="shareLogs") @@ -417,12 +419,17 @@ struct LanService::Impl if(action=="sendFile" || action=="requestLog") { auto peer=j.at("peer").get(); - if(!enabled||!trusted.contains(peer)||!peers.contains(peer)||!peers.at(peer).verified|| - now-peers.at(peer).verified>=lan::PeerLifetime) - throw std::runtime_error("Select an online paired computer."); - if(!transfers->hasSession(peer))throw std::runtime_error("Update KSwitcher on the selected computer to use file transfers."); + const auto checkPeer = [&] { + if(!enabled||!trusted.contains(peer)||!peers.contains(peer)||!peers.at(peer).verified|| + now-peers.at(peer).verified>=lan::PeerLifetime) + throw std::runtime_error("Select an online paired computer."); + if(!transfers->hasSession(peer)) + throw std::runtime_error("Update KSwitcher on the selected computer to use file transfers."); + }; + checkPeer(); if(action=="sendFile") { + lock.unlock(); auto file=std::filesystem::path(wide(j.at("path").get())); auto name=utf8(file.filename().wstring()); if(name.empty()||name.size()>1024)throw std::runtime_error("Invalid file name."); @@ -432,6 +439,9 @@ struct LanService::Impl if(std::filesystem::file_size(file)>fileLimit)throw std::runtime_error("File size limit is 16 MiB."); auto bytes=readFile(file,fileLimit); payload.insert(payload.end(),bytes.begin(),bytes.end()); + lock.lock(); + now=GetTickCount64(); + checkPeer(); transfers->queue({peer},std::move(payload),"file",now); return encoded({{"queued",true}}); } @@ -463,16 +473,24 @@ struct LanService::Impl } if(action=="saveFile"||action=="discardFile") { - auto found=std::find_if(incomingFiles.begin(),incomingFiles.end(),[&](const auto &file){ - return file.id==j.at("id").get() && file.peer==j.at("peer").get(); - }); + const auto id=j.at("id").get(), peer=j.at("peer").get(); + const auto findFile = [&] { + return std::find_if(incomingFiles.begin(),incomingFiles.end(),[&](const auto &file){ + return file.id==id && file.peer==peer; + }); + }; + auto found=findFile(); if(found==incomingFiles.end())throw std::runtime_error("This file is no longer available."); if(action=="saveFile") { auto start=std::find(found->bytes.begin(),found->bytes.end(),0)+1; - atomicWrite(wide(j.at("path").get()),Bytes(start,found->bytes.end())); + const Bytes bytes(start,found->bytes.end()); + lock.unlock(); + atomicWrite(wide(j.at("path").get()),bytes); + lock.lock(); + found=findFile(); } - incomingFiles.erase(found); + if(found!=incomingFiles.end()) incomingFiles.erase(found); if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,incomingFiles.size(),FALSE); } if(action=="position") diff --git a/src/lan_clipboard.h b/src/lan_clipboard.h index 529fe96..7038826 100644 --- a/src/lan_clipboard.h +++ b/src/lan_clipboard.h @@ -13,7 +13,20 @@ class ClipboardExchange { static constexpr size_t Limit=32*1024*1024, Chunk=480, Window=32; struct Item {std::string id,app;Bytes bytes;}; - struct Sending {std::deque> queue;size_t ack{};bool begun{};uint64_t last{},progress{};}; + struct Sending + { + std::deque> queue; + size_t ack{}, sentUpTo{}; + bool begun{}; + uint64_t retryAt{}, progress{}; + void reset(uint64_t now) + { + ack=sentUpTo=0; + begun=false; + retryAt=0; + progress=now; + } + }; struct Receiving {std::string id,app;Bytes bytes;size_t size{};uint64_t last{};DWORD sequence{};}; std::string local, type, domain, boot=randomHex(16); std::map sessions; @@ -55,12 +68,12 @@ class ClipboardExchange if(s.queue.empty())return; bool reset=s.queue.front()->app.starts_with(prefix); std::erase_if(s.queue,[&](const auto &item){return item->app.starts_with(prefix);}); - if(reset){s.ack=0;s.begun=false;s.last=0;s.progress=GetTickCount64();} + if(reset)s.reset(GetTickCount64()); } void peerSession(const std::string &peer,const std::string &value){ if(!identifier(value))return; if(sessions.contains(peer)&&sessions.at(peer)!=value){ - auto found=sending.find(peer);if(found!=sending.end()){found->second.ack=0;found->second.begun=false;found->second.last=0;} + auto found=sending.find(peer);if(found!=sending.end())found->second.reset(found->second.progress); if(type!="clipboard"){ auto previous=receiving.find(peer); if(previous!=receiving.end()){incomingBytes-=previous->second.size;receiving.erase(previous);} @@ -76,7 +89,7 @@ class ClipboardExchange for(auto &[peer,s]:sending)for(auto &item:s.queue)if(counted.insert(item.get()).second)total+=item->bytes.size(); if(total>2*Limit)throw std::runtime_error("LAN clipboard queue is full."); auto item=std::make_shared(Item{randomHex(16),app.size()>128?std::string("Application"):app,std::move(bytes)}); - for(auto &peer:peers){auto &s=sending[peer];if(s.queue.size()>=8){if(type!="clipboard")throw std::runtime_error("LAN transfer queue is full.");continue;}if(s.queue.empty()){s.ack=0;s.begun=false;s.last=0;s.progress=now;}s.queue.push_back(item);} + for(auto &peer:peers){auto &s=sending[peer];if(s.queue.size()>=8){if(type!="clipboard")throw std::runtime_error("LAN transfer queue is full.");continue;}if(s.queue.empty())s.reset(now);s.queue.push_back(item);} if(!peers.empty())status=type=="clipboard"?"Sending clipboard to "+std::to_string(peers.size())+" paired computers...":"Sending…"; } templatevoid poll(const Json &trusted,uint64_t now,Send send) @@ -88,14 +101,30 @@ class ClipboardExchange auto &peer=it->first;auto &s=it->second; if(!trusted.contains(peer)||s.queue.empty()){it=sending.erase(it);continue;} if(now-s.progress>30000){status="Transfer timed out.";it=sending.erase(it);continue;} - if(sessions.contains(peer)&&(!s.last||now-s.last>=100)) + auto &item=*s.queue.front(); + const auto limit=std::min(item.bytes.size(),s.ack+Window*Chunk); + const bool retry=s.retryAt && now>=s.retryAt; + const bool sendBegin=!s.begun && (!s.retryAt || retry); + const bool sendChunks=s.begun && (s.sentUpTo(); - if(!s.begun)send(peer,seal(peer,key,{{"op","begin"},{"item",item.id},{"size",item.bytes.size()},{"app",item.app}})); - else for(size_t offset=s.ack,n=0;offset(); + if(sendBegin) + send(peer,seal(peer,key,{{"op","begin"},{"item",item.id},{"size",item.bytes.size()},{"app",item.app}})); + else + { + // ACKs open new slots. Only a timeout retransmits outstanding chunks. + if(retry) s.sentUpTo=s.ack; + while(s.sentUpTosecond.queue.empty())return; auto &s=found->second;auto &item=*s.queue.front();auto offset=body.at("offset").get(); - if(item.id!=id||offset>item.bytes.size()||offsets.ack+Window*Chunk||(offset!=item.bytes.size()&&offset%Chunk))return; + const auto maxAck=s.begun?s.sentUpTo:Window*Chunk; + if(item.id!=id||offset>item.bytes.size()||offsetmaxAck||(offset!=item.bytes.size()&&offset%Chunk))return; if(offset==s.ack&&s.begun)return; - s.begun=true;s.ack=offset;s.progress=now;s.last=0; - if(offset==item.bytes.size()){s.queue.pop_front();s.ack=0;s.begun=false;status=type=="clipboard"?"Clipboard delivered.":"Transfer delivered.";} + s.begun=true; + s.ack=offset; + s.sentUpTo=std::max(s.sentUpTo,offset); + s.progress=now; + s.retryAt=offset +#include #include #include #include @@ -99,6 +100,38 @@ struct OcrOperation : IInspectable virtual HRESULT STDMETHODCALLTYPE GetCompleted(IUnknown **) = 0; virtual HRESULT STDMETHODCALLTYPE Results(OcrResult **) = 0; }; +class OcrCompletion final : public IUnknown +{ + // Windows.Foundation.AsyncOperationCompletedHandler. + static constexpr GUID interfaceId{0x989c1371,0x444a,0x5e7e,{0xb1,0x97,0x9e,0xaa,0xf9,0xd2,0x82,0x9a}}; + static constexpr GUID agileId{0x94ea2b94,0xe9cc,0x49e0,{0xc0,0xff,0xee,0x64,0xca,0x8f,0x5b,0x90}}; + std::atomic references{1}; + + public: + const HANDLE event=CreateEventW(nullptr,TRUE,FALSE,nullptr); + ~OcrCompletion(){if(event) CloseHandle(event);} + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,void **value) override + { + if(!value) return E_POINTER; + *value=nullptr; + if(iid!=IID_IUnknown && iid!=interfaceId && iid!=agileId) return E_NOINTERFACE; + *value=static_cast(this); + AddRef(); + return S_OK; + } + ULONG STDMETHODCALLTYPE AddRef() override {return ++references;} + ULONG STDMETHODCALLTYPE Release() override + { + const auto count=--references; + if(!count) delete this; + return count; + } + virtual HRESULT STDMETHODCALLTYPE Invoke(OcrOperation *,INT32) + { + return SetEvent(event)?S_OK:HRESULT_FROM_WIN32(GetLastError()); + } +}; + struct AsyncInfo : IInspectable { virtual HRESULT STDMETHODCALLTYPE Id(UINT32 *) = 0; @@ -253,13 +286,12 @@ std::wstring recognizeText(const Clip &clip) RoUninitialize(); } } apartment; - auto pixels = decodeImage(clip); Com ocr; factory(L"Windows.Media.Ocr.OcrEngine", L"{5bffa85a-3384-3540-9940-699120d428a8}", ocr); UINT32 max{}; check(ocr->MaxDimension(&max)); - if (pixels.width > max || pixels.height > max) - throw std::runtime_error("Image exceeds Windows OCR's maximum dimensions"); + if (!max) throw std::runtime_error("Windows OCR reported an invalid image size limit"); + auto pixels = decodeImage(clip,max,max); Com engine; check(ocr->FromProfile(engine.out())); if (!engine.p) @@ -282,21 +314,20 @@ std::wstring recognizeText(const Clip &clip) check(engine->Recognize(bitmap.p, operation.out())); Com info; check(operation->QueryInterface(guid(L"{00000036-0000-0000-c000-000000000046}"), (void **)info.out())); - auto deadline = GetTickCount64() + 30000; - INT32 status{}; - do + Com completed; + completed.p=new OcrCompletion; + if(!completed->event) check(HRESULT_FROM_WIN32(GetLastError())); + check(operation->PutCompleted(completed.p)); + const auto wait=WaitForSingleObject(completed->event,30000); + if(wait!=WAIT_OBJECT_0) { - check(info->Status(&status)); - if (status == 0) - { - if (GetTickCount64() > deadline) - { - info->Cancel(); - throw std::runtime_error("Windows OCR timed out"); - } - Sleep(20); - } - } while (status == 0); + const auto error=wait==WAIT_FAILED?GetLastError():ERROR_TIMEOUT; + info->Cancel(); + if(error==ERROR_TIMEOUT) throw std::runtime_error("Windows OCR timed out"); + check(HRESULT_FROM_WIN32(error)); + } + INT32 status{}; + check(info->Status(&status)); if (status != 1) { HRESULT failure{}; diff --git a/src/platform.cpp b/src/platform.cpp index d53fdb2..79a5af5 100644 --- a/src/platform.cpp +++ b/src/platform.cpp @@ -738,6 +738,11 @@ namespace std::recursive_mutex logGate; bool loggingEnabled = false; std::wstring logFilename = L"kswitcher.log"; +const std::filesystem::path &logDirectory() +{ + static const auto directory = dataDirectory(); + return directory; +} DiagnosticBuffer diagnosticBuffer; } size_t DiagnosticBuffer::expire(ULONGLONG now) @@ -778,7 +783,7 @@ void setLoggingEnabled(bool enabled) std::wstring readDiagnosticLog(bool previous) { std::lock_guard lock(logGate); - auto path = dataDirectory() / (previous ? L"kswitcher.log.1" : L"kswitcher.log"); + auto path = logDirectory() / (previous ? L"kswitcher.log.1" : L"kswitcher.log"); if (!std::filesystem::exists(path)) return previous ? L"No previous log is available yet." : L"No log yet. Entries will appear when a problem is detected."; auto bytes = readFile(path, 2 * 1024 * 1024); @@ -796,7 +801,7 @@ void clearDiagnosticLog(bool previous) { // Serialize clearing with writes and rotation. Never delete the other log. std::lock_guard lock(logGate); - auto path = dataDirectory() / (previous ? L"kswitcher.log.1" : L"kswitcher.log"); + auto path = logDirectory() / (previous ? L"kswitcher.log.1" : L"kswitcher.log"); std::filesystem::remove(path); if (!previous) diagnosticBuffer.clear(); @@ -845,7 +850,7 @@ void log(const std::wstring &message) return; try { - auto path = dataDirectory() / logFilename; + auto path = logDirectory() / logFilename; std::error_code ec; auto size = std::filesystem::file_size(path, ec); if (!ec && size > 256 * 1024) diff --git a/src/screenshot.cpp b/src/screenshot.cpp index 3c1dc74..fc54d56 100644 --- a/src/screenshot.cpp +++ b/src/screenshot.cpp @@ -84,6 +84,13 @@ struct Surface Surface(const Surface &) = delete; Surface &operator=(const Surface &) = delete; }; +struct SavedDc +{ + HDC dc; + int level; + explicit SavedDc(HDC value):dc(value),level(SaveDC(value)) {} + ~SavedDc() { if(level) RestoreDC(dc,level); } +}; using Mark = ScreenshotMark; HFONT textFont(const Mark &m) { @@ -169,7 +176,9 @@ struct Capture { ScreenshotHost &app; std::unique_ptr image; - std::unique_ptr dimmed, frame; + std::unique_ptr dimmed, frame, rendered; + bool renderedMarksValid{}; + RECT dragDamage{}; bool editing{}, dragging{}, arrow{}, owned{}, copied{}; bool autoOpenEditor; bool highlight{}; @@ -249,6 +258,7 @@ struct Capture void remember(const std::vector &previous) { copied=false; + renderedMarksValid=false; history.remember(previous); syncHistory(); } @@ -471,6 +481,76 @@ RECT markBounds(const Mark &m) } return r; } +RECT inkBounds(const Mark &m) +{ + auto bounds=markBounds(m); + const auto padding=m.number?std::clamp(m.radius,8,200)+4: + m.isHighlight()?std::clamp(m.thickness,4,100)/2+4: + m.isText()?4:std::clamp(m.thickness,1,30)*5+14; + InflateRect(&bounds,padding,padding); + return bounds; +} +void includeInk(RECT &area,const Mark &m) +{ + const auto bounds=inkBounds(m); + UnionRect(&area,&area,&bounds); + if(m.isLine() && !m.label.empty()) + { + const auto labelBounds=inkBounds(screenshotArrowLabel(m)); + UnionRect(&area,&area,&labelBounds); + } +} + +Mark shapePreview(const Capture &c) +{ + Mark preview{c.start,c.end,0}; + preview.color=c.currentColor; + preview.style=c.lineStyle; + preview.ends=c.straight || c.shape!=ScreenshotShape::None?LineEnds::None:c.arrowEnds; + preview.shape=c.shape; + return preview; +} + +RECT dragInk(const Capture &c) +{ + RECT area{}; + if(c.part!=MarkPart::None) + { + // Moving an attachment can update linked lines and their labels as well. + for(size_t i=0;i(c.selected) || mark.fromLink.target || mark.toLink.target || + mark.fromNumber || mark.toNumber) + includeInk(area,mark); + } + } + else includeInk(area,(c.highlight || c.freehand)?c.stroke:shapePreview(c)); + return area; +} + +void invalidateDrag(HWND w,Capture &c,const RECT &before) +{ + const auto after=dragInk(c); + RECT affected{}; + UnionRect(&affected,&before,&after); + UnionRect(&c.dragDamage,&c.dragDamage,&affected); + const auto x=[&](LONG value) {return c.view.left+MulDiv(value,c.view.right-c.view.left,c.image->width);}; + const auto y=[&](LONG value) {return c.view.top+MulDiv(value,c.view.bottom-c.view.top,c.image->height);}; + RECT windowArea{x(affected.left),y(affected.top),x(affected.right),y(affected.bottom)}; + // Handles and antialiased scaling extend beyond the rasterized ink. + int padding=4; + if(c.part!=MarkPart::None && c.selected>=0 && c.selected thicknessSegment(const Mark &m) { if(m.shape!=ScreenshotShape::None) { @@ -492,7 +572,8 @@ void drawHighlight(HDC dc,const Mark &m) r.left=std::max(0L,r.left-radius-1); r.top=std::max(0L,r.top-radius-1); r.right=std::min(target.dsBm.bmWidth,r.right+radius+2); r.bottom=std::min(target.dsBm.bmHeight,r.bottom+radius+2); - if(r.right<=r.left || r.bottom<=r.top) return; + RECT clip{}; + if(GetClipBox(dc,&clip)==ERROR || !IntersectRect(&r,&r,&clip)) return; Surface mask(r.right-r.left,r.bottom-r.top); PatBlt(mask.dc,0,0,mask.width,mask.height,BLACKNESS); LOGBRUSH white{BS_SOLID,RGB(255,255,255),0}; @@ -519,7 +600,7 @@ void drawHighlight(HDC dc,const Mark &m) for(int channel=0;channel<3;++channel) at[channel]=static_cast(at[channel]*(153+channels[channel]*102/255)/255); } } -void drawMarks(HDC dc, const std::vector &marks, const Mark *preview = nullptr) +void drawMarks(HDC dc,const std::vector &marks,const Mark *preview=nullptr,const RECT *damage=nullptr) { for(const auto &m:marks) if(m.isHighlight()) drawHighlight(dc,m); if(preview && preview->isHighlight()) drawHighlight(dc,*preview); @@ -533,6 +614,12 @@ void drawMarks(HDC dc, const std::vector &marks, const Mark *preview = nul SetTextColor(dc, RGB(255,255,255)); auto draw = [&](const Mark &m) { + if(damage) + { + const auto bounds=inkBounds(m); + RECT overlap{}; + if(!IntersectRect(&overlap,&bounds,damage)) return; + } auto markPen=CreatePen(PS_SOLID,3,m.color); auto markBrush=CreateSolidBrush(m.color); auto previousMarkPen=SelectObject(dc,markPen),previousMarkBrush=SelectObject(dc,markBrush); @@ -1050,6 +1137,8 @@ void edit(HWND w, Capture &c) c.image = std::move(cropped); c.dimmed.reset(); c.frame.reset(); + c.rendered.reset(); + c.renderedMarksValid=false; c.editing = true; if (activeCapture == w) activeCapture = nullptr; MONITORINFO monitor{sizeof(monitor)}; @@ -1184,6 +1273,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) bool pencil=c->selected>=0 && c->marks[c->selected].freehand; if(pencil && c->marks[c->selected].smoothing!=amount) { if(!c->smoothingDrag) c->remember(c->marks); + c->renderedMarksValid=false; setScreenshotSmoothing(c->marks[c->selected],amount); resolveScreenshotLinks(c->marks); c->smoothingDrag=LOWORD(wp)==TB_THUMBTRACK; @@ -1296,7 +1386,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) if (LOWORD(wp)==12 || LOWORD(wp)==18) { bool changed=LOWORD(wp)==12?c->history.undo(c->marks):c->history.redo(c->marks); - if(changed) { c->copied=false; c->selected=-1; c->selectedLabel=false; c->wheelDelta=0; c->wheelTarget=-1; } + if(changed) { c->copied=false; c->renderedMarksValid=false; c->selected=-1; c->selectedLabel=false; c->wheelDelta=0; c->wheelTarget=-1; } c->syncHistory(); } if (LOWORD(wp)==10 || LOWORD(wp)==11 || LOWORD(wp)==19 || LOWORD(wp)==36 || LOWORD(wp)==37 || LOWORD(wp)==38 || (LOWORD(wp)>=21 && LOWORD(wp)<=27)) @@ -1321,6 +1411,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) InvalidateRect(GetDlgItem(w,38),nullptr,FALSE); } + if(c->dragging) c->renderedMarksValid=false; SetFocus(w); captureCursor(w,*c); InvalidateRect(w,nullptr,FALSE); return 0; case WM_KEYDOWN: if(wp==VK_SHIFT && c->editing && c->dragging && c->freehand && c->part==MarkPart::None && !c->strokeConstrained) { @@ -1463,6 +1554,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) c->strokeUsedConstraint=(wp&MK_SHIFT)!=0; } c->dragging=true; SetCapture(w); + if(c->editing) invalidateDrag(w,*c,{}); } InvalidateRect(w,nullptr,FALSE); return 0; } @@ -1522,7 +1614,18 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) if (c->dragging) { POINT p{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)}; + const auto previousSelection=region(c->start,c->end); + const auto previousInk=c->editing && msg==WM_MOUSEMOVE?dragInk(*c):RECT{}; c->end=c->editing?imagePoint(*c,p,c->part!=MarkPart::Thickness && c->part!=MarkPart::Rotation):POINT{std::clamp(p.x,0L,LONG(c->image->width)),std::clamp(p.y,0L,LONG(c->image->height))}; + if(!c->editing && msg==WM_MOUSEMOVE) + { + const auto selection=region(c->start,c->end); + RECT dirty{}; + if(UnionRect(&dirty,&previousSelection,&selection)) + InvalidateRect(w,&dirty,FALSE); + captureCursor(w,*c); + return 0; + } if(c->editing && c->part==MarkPart::None && c->shape!=ScreenshotShape::None) c->end=constrainScreenshotShape(c->shape,c->start,c->end,c->image->width,c->image->height); if(c->editing && (c->highlight || c->freehand) && c->part==MarkPart::None) { @@ -1593,6 +1696,12 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) c->marks[c->selected]=dragScreenshotMark(c->original,c->part,c->start,c->end,c->image->width,c->image->height,(GetKeyState(VK_SHIFT)&0x8000)!=0); resolveScreenshotLinks(c->marks); } + if(c->editing && msg==WM_MOUSEMOVE) + { + invalidateDrag(w,*c,previousInk); + captureCursor(w,*c); + return 0; + } if (msg==WM_LBUTTONUP) { c->dragging=false; ReleaseCapture(); @@ -1675,9 +1784,10 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) c->panning=false; if(c->dragging && c->part!=MarkPart::None) { - c->marks=std::move(c->beforeDrag); c->part=MarkPart::None; + c->marks=std::move(c->beforeDrag); c->renderedMarksValid=false; c->part=MarkPart::None; } - c->dragging=false; InvalidateRect(w,nullptr,FALSE); return 0; + c->dragging=false; c->renderedMarksValid=false; c->dragDamage={}; + InvalidateRect(w,nullptr,FALSE); return 0; case WM_GETMINMAXINFO: if (c->editing) { @@ -1710,14 +1820,16 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) // Compose the entire frame off screen. Never expose a cleared desktop // or a partially drawn selection between mouse moves. auto buffer=c->frame->dc; - BitBlt(buffer,0,0,c->image->width,c->image->height,c->dimmed->dc,0,0,SRCCOPY); + const auto &dirty=ps.rcPaint; + const int width=dirty.right-dirty.left,height=dirty.bottom-dirty.top; + BitBlt(buffer,dirty.left,dirty.top,width,height,c->dimmed->dc,dirty.left,dirty.top,SRCCOPY); if (c->dragging) { auto r=region(c->start,c->end); BitBlt(buffer,r.left,r.top,r.right-r.left,r.bottom-r.top,c->image->dc,r.left,r.top,SRCCOPY); FrameRect(buffer,&r,static_cast(GetStockObject(WHITE_BRUSH))); } - BitBlt(dc,0,0,c->image->width,c->image->height,buffer,0,0,SRCCOPY); + BitBlt(dc,dirty.left,dirty.top,width,height,buffer,dirty.left,dirty.top,SRCCOPY); } else { @@ -1725,6 +1837,9 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) if (!c->frame || c->frame->width!=width || c->frame->height!=height) c->frame=std::make_unique(width,height); auto buffer=c->frame->dc; + const SavedDc savedFrame(buffer); + const auto &dirty=ps.rcPaint; + IntersectClipRect(buffer,dirty.left,dirty.top,dirty.right,dirty.bottom); FillRect(buffer,&client,GetSysColorBrush(COLOR_APPWORKSPACE)); RECT toolbar{0,0,client.right,c->panelHeight}; FillRect(buffer,&toolbar,static_cast(GetStockObject(WHITE_BRUSH))); @@ -1737,26 +1852,58 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) LineTo(buffer,MulDiv(x,dpi,96),MulDiv(31,dpi,96)); } SelectObject(buffer,previous); DeleteObject(divider); - Surface rendered(c->image->width,c->image->height); - BitBlt(rendered.dc,0,0,rendered.width,rendered.height,c->image->dc,0,0,SRCCOPY); - Mark preview{c->start,c->end,0}; - preview.color=c->currentColor; - preview.style=c->lineStyle; preview.ends=c->straight || c->shape!=ScreenshotShape::None?LineEnds::None:c->arrowEnds; - preview.shape=c->shape; - auto visibleMarks=c->marks; - if(c->inlineText && c->textIndex>=0) { - if(c->editingLabel) visibleMarks[c->textIndex].label.clear(); - else visibleMarks.erase(visibleMarks.begin()+c->textIndex); + const auto preview=shapePreview(*c); + const auto *previewMark=c->dragging && c->part==MarkPart::None? + ((c->highlight || c->freehand)?&c->stroke:&preview):nullptr; + const auto *source=c->image.get(); + if(!c->marks.empty() || previewMark) + { + const bool inlineEdit=c->inlineText && c->textIndex>=0; + const bool partial=c->renderedMarksValid && !inlineEdit; + if(!c->rendered) + c->rendered=std::make_unique(source->width,source->height); + auto &rendered=*c->rendered; + RECT imageArea{0,0,rendered.width,rendered.height}, repaint=imageArea; + if(partial) IntersectRect(&repaint,&imageArea,&c->dragDamage); + if(!IsRectEmpty(&repaint)) + { + c->renderedMarksValid=false; + BitBlt(rendered.dc,repaint.left,repaint.top,repaint.right-repaint.left,repaint.bottom-repaint.top, + source->dc,repaint.left,repaint.top,SRCCOPY); + if(inlineEdit) + { + auto visibleMarks=c->marks; + if(c->editingLabel) visibleMarks[c->textIndex].label.clear(); + else visibleMarks.erase(visibleMarks.begin()+c->textIndex); + drawMarks(rendered.dc,visibleMarks,previewMark); + } + else if(partial) + { + const SavedDc previousClip(rendered.dc); + IntersectClipRect(rendered.dc,repaint.left,repaint.top,repaint.right,repaint.bottom); + drawMarks(rendered.dc,c->marks,previewMark,&repaint); + } + else drawMarks(rendered.dc,c->marks,previewMark); + c->renderedMarksValid=!inlineEdit; + } + source=&rendered; } - drawMarks(rendered.dc,visibleMarks,c->dragging && c->part==MarkPart::None?((c->highlight || c->freehand)?&c->stroke:&preview):nullptr); + else + { + c->rendered.reset(); + c->renderedMarksValid=false; + } + c->dragDamage={}; SetStretchBltMode(buffer,HALFTONE); SetBrushOrgEx(buffer,0,0,nullptr); - int savedCanvas=SaveDC(buffer); - IntersectClipRect(buffer,c->canvas.left,c->canvas.top,c->canvas.right,c->canvas.bottom); - StretchBlt(buffer,c->view.left,c->view.top,c->view.right-c->view.left,c->view.bottom-c->view.top, - rendered.dc,0,0,rendered.width,rendered.height,SRCCOPY); - drawHandles(buffer,*c); - RestoreDC(buffer,savedCanvas); - BitBlt(dc,0,0,width,height,buffer,0,0,SRCCOPY); + { + const SavedDc savedCanvas(buffer); + IntersectClipRect(buffer,c->canvas.left,c->canvas.top,c->canvas.right,c->canvas.bottom); + StretchBlt(buffer,c->view.left,c->view.top,c->view.right-c->view.left,c->view.bottom-c->view.top, + source->dc,0,0,source->width,source->height,SRCCOPY); + drawHandles(buffer,*c); + } + BitBlt(dc,dirty.left,dirty.top,dirty.right-dirty.left,dirty.bottom-dirty.top, + buffer,dirty.left,dirty.top,SRCCOPY); } } catch (...) { EndPaint(w,&ps); throw; } diff --git a/src/screenshot_main.cpp b/src/screenshot_main.cpp index 610a322..ed1bd76 100644 --- a/src/screenshot_main.cpp +++ b/src/screenshot_main.cpp @@ -54,6 +54,22 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int) std::filesystem::path request=argv[2]; LocalFree(argv); return ks::runClipboardSnapshot(request); } + if(argc==5 && std::wstring_view(argv[1])==L"--history-image-worker") { + HANDLE handles[3]{}; + for(int i=0;i<3;++i) + { + wchar_t *end{}; + const auto value=std::wcstoull(argv[i+2],&end,10); + if(!value || *end || value>UINTPTR_MAX) { LocalFree(argv); return 1; } + handles[i]=reinterpret_cast(static_cast(value)); + } + LocalFree(argv); + const auto initialized=CoInitializeEx(nullptr,COINIT_MULTITHREADED); + if(FAILED(initialized)) return 1; + const auto result=ks::runHistoryImageWorker(handles[0],handles[1],handles[2]); + CoUninitialize(); + return result; + } if(argc==3 && (std::wstring(argv[1])==L"--capture-history" || std::wstring(argv[1])==L"--history-ocr")) { bool ocr=std::wstring(argv[1])==L"--history-ocr"; std::filesystem::path request=argv[2]; LocalFree(argv); diff --git a/src/storage.cpp b/src/storage.cpp index 611d75f..eea46a9 100644 --- a/src/storage.cpp +++ b/src/storage.cpp @@ -28,9 +28,9 @@ std::wstring newSnippetId() } namespace { -Bytes jsonBytes(const Json &j) +Bytes jsonBytes(const Json &j, int indent = 2) { - auto s = j.dump(2); + auto s = j.dump(indent); return Bytes(s.begin(), s.end()); } Json parse(const Bytes &bytes) @@ -327,7 +327,7 @@ Settings decodeSettings(const Bytes &bytes, const std::vector &layouts) throw std::runtime_error("Not a KSwitcher or Typlo settings file"); s.recent = j.value("convertLastWord", true); s.switchLayout = j.value("switchSystemLayout", true); - s.writeLog = j.value("writeLog", true); + s.writeLog = j.value("writeLog", s.writeLog); s.history = j.value("historyEnabled", true); s.useTesseract = j.value("useTesseract", false); s.tesseractPath = str(j, "tesseractPath"); @@ -685,7 +685,54 @@ Clip decodeClip(const Bytes &b) throw std::runtime_error("Trailing clipboard data"); return clip; } -History::History(const std::filesystem::path &folder) : folder_(folder) +namespace +{ +struct ImageWorkerControl +{ + static constexpr size_t MaxPath=32768; + wchar_t request[MaxPath]; + int result; +}; +struct ImageWorkerHandle +{ + HANDLE value{}; + ~ImageWorkerHandle() { reset(); } + void reset() + { + if(value) CloseHandle(std::exchange(value,nullptr)); + } +}; +struct ImageWorkerView +{ + ImageWorkerControl *control{}; + ~ImageWorkerView() { reset(); } + void reset() + { + if(control) UnmapViewOfFile(std::exchange(control,nullptr)); + } +}; +struct HistoryImageWorker +{ + std::timed_mutex mutex; + ImageWorkerHandle mapping, requestReady, responseReady, process; + ImageWorkerView view; + + ~HistoryImageWorker() { stop(); } + void stop(); + void start(); + int perform(const std::filesystem::path &, const std::function &); +}; +} + +struct HistoryImageWorkers +{ + // A slow recognition must not delay history thumbnails. + HistoryImageWorker recognition, thumbnails; +}; + +History::~History() = default; +History::History(const std::filesystem::path &folder) + : folder_(folder), imageWorkers_(std::make_unique()) { std::filesystem::create_directories(folder_); loadIndex(); @@ -724,7 +771,12 @@ void History::loadIndex() } entries_ = std::move(loaded); } -void History::reload() { std::lock_guard lock(mutex_); loadIndex(); } +void History::reload() +{ + std::lock_guard writer(indexWriter_); + std::lock_guard lock(mutex_); + loadIndex(); +} void ClipboardSnapshot::cleanup() noexcept { if (request_.empty()) return; @@ -809,7 +861,7 @@ bool History::captureImage(DWORD sequence, const std::wstring &app, const Settin { // Serialize helper index changes with all resident history mutations. Only // metadata is reloaded: GetClipboardData's image allocations die with the child. - std::lock_guard lock(mutex_); + std::lock_guard writer(indexWriter_); if (sequence != GetClipboardSequenceNumber()) return false; auto request = std::filesystem::absolute(folder_) / (L"capture-" + newSnippetId() + L".request"); struct Cleanup { @@ -838,7 +890,10 @@ bool History::captureImage(DWORD sequence, const std::wstring &app, const Settin } GetExitCodeProcess(process.hProcess, &result); CloseHandle(process.hProcess); - loadIndex(); // Also reconcile any completed atomic save before a child failure. + { + std::lock_guard lock(mutex_); + loadIndex(); // Also reconcile any completed atomic save before a child failure. + } if (wait != WAIT_OBJECT_0) throw std::runtime_error("Image history helper timed out"); if (result == 2) return false; if (result == 3) throw std::runtime_error("Clipboard exceeds the configured size limit"); @@ -893,7 +948,7 @@ void History::saveIndex() {"files", e.files}, {"ocrState", e.ocrState}, {"ocrProfile", utf8(e.ocrProfile)}, {"fingerprintVersion", 1}, {"contentHash", e.contentHash}, {"imageHash", e.imageHash}, {"pixelHash", e.pixelHash}}); - atomicWrite(folder_ / L"index.dat", protect(jsonBytes(j))); + atomicWrite(folder_ / L"index.dat", protect(jsonBytes(j, -1))); } std::vector History::entries() const { @@ -1007,6 +1062,7 @@ void History::add(const Clip &clip, const std::wstring &app, const Settings &s, image |= f.id == CF_DIB || f.id == CF_DIBV5 || f.name == L"PNG"; files |= f.id == CF_HDROP; } + std::lock_guard writer(indexWriter_); std::lock_guard lock(mutex_); Entry fingerprints; fingerprints.contentHash = clipboardHash(data); @@ -1068,6 +1124,7 @@ void History::add(const Clip &clip, const std::wstring &app, const Settings &s, } void History::remove(const std::wstring &id) { + std::lock_guard writer(indexWriter_); std::lock_guard lock(mutex_); if (!validId(id)) return; @@ -1082,6 +1139,7 @@ void History::remove(const std::wstring &id) } void History::pin(const std::wstring &id) { + std::lock_guard writer(indexWriter_); std::lock_guard lock(mutex_); for (auto &e : entries_) if (e.id == id) @@ -1090,6 +1148,7 @@ void History::pin(const std::wstring &id) } void History::clear() { + std::lock_guard writer(indexWriter_); std::lock_guard lock(mutex_); auto old = entries_; entries_.clear(); @@ -1101,7 +1160,139 @@ void History::clear() std::filesystem::remove(folder_ / (e.id + L".ocr"), ec); } } -static Bytes historyImageJob(const std::filesystem::path &folder, const std::wstring &id, +namespace +{ +void HistoryImageWorker::stop() +{ + if(process.value && WaitForSingleObject(process.value,0)==WAIT_TIMEOUT) + { + TerminateProcess(process.value,ERROR_CANCELLED); + WaitForSingleObject(process.value,INFINITE); + } + process.reset(); + view.reset(); + mapping.reset(); + requestReady.reset(); + responseReady.reset(); +} + +void HistoryImageWorker::start() +{ + SECURITY_ATTRIBUTES security{sizeof(security),nullptr,TRUE}; + mapping.value=CreateFileMappingW(INVALID_HANDLE_VALUE,&security,PAGE_READWRITE,0,sizeof(ImageWorkerControl),nullptr); + requestReady.value=CreateEventW(&security,FALSE,FALSE,nullptr); + responseReady.value=CreateEventW(&security,FALSE,FALSE,nullptr); + if(!mapping.value || !requestReady.value || !responseReady.value) + throw std::runtime_error("Cannot create history OCR worker channel"); + view.control=static_cast(MapViewOfFile(mapping.value,FILE_MAP_WRITE,0,0,sizeof(ImageWorkerControl))); + if(!view.control) throw std::runtime_error("Cannot map history OCR worker channel"); + + SIZE_T bytes{}; + InitializeProcThreadAttributeList(nullptr,1,0,&bytes); + Bytes storage(bytes); + auto attributes=reinterpret_cast(storage.data()); + if(!InitializeProcThreadAttributeList(attributes,1,0,&bytes)) + throw std::runtime_error("Cannot initialize history OCR worker startup"); + struct Attributes + { + LPPROC_THREAD_ATTRIBUTE_LIST value; + ~Attributes() { DeleteProcThreadAttributeList(value); } + } cleanup{attributes}; + HANDLE inherited[]{mapping.value,requestReady.value,responseReady.value}; + if(!UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST,inherited,sizeof(inherited),nullptr,nullptr)) + throw std::runtime_error("Cannot configure history OCR worker startup"); + + const auto helper=std::filesystem::path(executable()).parent_path()/L"KSwitcher.Screenshot.exe"; + auto command=L"\""+helper.wstring()+L"\" --history-image-worker"; + for(auto handle:inherited) command+=L" "+std::to_wstring(reinterpret_cast(handle)); + STARTUPINFOEXW startup{}; + startup.StartupInfo.cb=sizeof(startup); + startup.lpAttributeList=attributes; + PROCESS_INFORMATION child{}; + if(!CreateProcessW(helper.c_str(),command.data(),nullptr,nullptr,TRUE, + CREATE_NO_WINDOW|EXTENDED_STARTUPINFO_PRESENT,nullptr,helper.parent_path().c_str(),&startup.StartupInfo,&child)) + throw std::runtime_error(utf8(lastError(L"Cannot start history OCR helper"))); + process.value=child.hProcess; + CloseHandle(child.hThread); + for(const auto handle:inherited) SetHandleInformation(handle,HANDLE_FLAG_INHERIT,0); +} + +int HistoryImageWorker::perform(const std::filesystem::path &request,const std::function &cancelled) +{ + std::unique_lock lock(mutex,std::defer_lock); + const auto checkCancelled=[&] { + if(cancelled && cancelled()) throw std::runtime_error("History OCR cancelled"); + }; + while(!lock.try_lock_for(std::chrono::milliseconds(100))) checkCancelled(); + checkCancelled(); + const auto &path=request.native(); + if(path.size()>=ImageWorkerControl::MaxPath) + throw std::runtime_error("History OCR request path is too long"); + + try + { + for(int attempt=0;attempt<2;++attempt) + { + if(!process.value || WaitForSingleObject(process.value,0)!=WAIT_TIMEOUT) + { + stop(); + start(); + } + checkCancelled(); + std::copy(path.begin(),path.end(),view.control->request); + view.control->request[path.size()]=L'\0'; + if(!SetEvent(requestReady.value)) throw std::runtime_error("Cannot request history OCR"); + HANDLE signals[]{responseReady.value,process.value}; + const auto deadline=GetTickCount64()+60000; + for(;;) + { + const auto wait=WaitForMultipleObjects(2,signals,FALSE,100); + if(wait==WAIT_OBJECT_0) + { + checkCancelled(); + return view.control->result; + } + if(wait==WAIT_OBJECT_0+1) + { + DWORD code{}; + if(GetExitCodeProcess(process.value,&code) && code==WAIT_TIMEOUT && !attempt) break; + throw std::runtime_error("History OCR helper exited before responding"); + } + if(wait!=WAIT_TIMEOUT) throw std::runtime_error("Cannot wait for history OCR helper"); + checkCancelled(); + if(GetTickCount64()>=deadline) throw std::runtime_error("History OCR helper timed out"); + } + stop(); + } + } + catch(...) + { + // The child must stop writing before the request and response files are cleaned up. + stop(); + throw; + } + throw std::runtime_error("History OCR helper did not accept the request"); +} +} + +int runHistoryImageWorker(HANDLE mapping,HANDLE requestReady,HANDLE responseReady) +{ + ImageWorkerView view{static_cast( + MapViewOfFile(mapping,FILE_MAP_WRITE,0,0,sizeof(ImageWorkerControl)))}; + if(!view.control) return 1; + for(;;) + { + const auto wait=WaitForSingleObject(requestReady,30000); + if(wait==WAIT_TIMEOUT) return WAIT_TIMEOUT; + if(wait!=WAIT_OBJECT_0) return 1; + const auto &request=view.control->request; + const auto end=std::find(std::begin(request),std::end(request),L'\0'); + view.control->result=end==std::end(request)?1:runHistoryOcr(std::wstring(std::begin(request),end)); + if(!SetEvent(responseReady)) return 1; + } +} + +static Bytes historyImageJob(HistoryImageWorker &worker,const std::filesystem::path &folder,const std::wstring &id, const Json &job, const std::function &cancelled) { if (!validId(id)) throw std::runtime_error("Invalid history ID"); @@ -1117,36 +1308,7 @@ static Bytes historyImageJob(const std::filesystem::path &folder, const std::wst } } cleanup{request, response}; atomicWrite(request, protect(jsonBytes(job))); - auto helper = std::filesystem::path(executable()).parent_path() / L"KSwitcher.Screenshot.exe"; - auto command = L"\"" + helper.wstring() + L"\" --history-ocr \"" + request.wstring() + L"\""; - STARTUPINFOW startup{sizeof(startup)}; - startup.dwFlags = STARTF_USESHOWWINDOW; startup.wShowWindow = SW_HIDE; - PROCESS_INFORMATION process{}; - if (!CreateProcessW(helper.c_str(), command.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, - nullptr, helper.parent_path().c_str(), &startup, &process)) - throw std::runtime_error(utf8(lastError(L"Cannot start history OCR helper"))); - CloseHandle(process.hThread); - struct Child { - HANDLE handle; - ~Child() { - if (WaitForSingleObject(handle, 0) != WAIT_OBJECT_0) { - TerminateProcess(handle, ERROR_CANCELLED); - WaitForSingleObject(handle, INFINITE); - } - CloseHandle(handle); - } - } child{process.hProcess}; - auto deadline = GetTickCount64() + 60000; - for (;;) { - auto wait = WaitForSingleObject(child.handle, 100); - if (wait == WAIT_OBJECT_0) break; - if (wait != WAIT_TIMEOUT) throw std::runtime_error("Cannot wait for history OCR helper"); - if (cancelled && cancelled()) throw std::runtime_error("History OCR cancelled"); - if (GetTickCount64() >= deadline) throw std::runtime_error("History OCR helper timed out"); - } - DWORD result{}; - if (!GetExitCodeProcess(child.handle, &result) || result) - throw std::runtime_error("History OCR helper failed: " + std::to_string(result)); + if(worker.perform(request,cancelled)) throw std::runtime_error("History OCR helper failed"); return unprotect(readFile(response, 8 * 1024 * 1024)); } std::wstring History::recognizeImage(const std::wstring &id, const Settings &settings, @@ -1154,14 +1316,14 @@ std::wstring History::recognizeImage(const std::wstring &id, const Settings &set { Json job{{"schema", 1}, {"id", utf8(id)}, {"tesseract", settings.useTesseract}, {"path", utf8(settings.tesseractPath)}, {"languages", utf8(settings.tesseractLanguages)}}; - auto reply = parse(historyImageJob(folder_, id, job, cancelled)); + auto reply = parse(historyImageJob(imageWorkers_->recognition,folder_, id, job, cancelled)); if (reply.at("schema") != 1 || str(reply, "id") != id) throw std::runtime_error("Invalid history OCR response"); return str(reply, "text"); } Pixels History::thumbnail(const std::wstring &id, const std::function &cancelled) const { - auto bytes = historyImageJob(folder_, id, Json{{"schema", 1}, {"id", utf8(id)}, {"thumbnail", true}}, cancelled); + auto bytes = historyImageJob(imageWorkers_->thumbnails,folder_, id, Json{{"schema", 1}, {"id", utf8(id)}, {"thumbnail", true}}, cancelled); size_t at = 0; auto width = get32(bytes, at), height = get32(bytes, at); if (!width || !height || width > 208 || height > 128 || bytes.size() - at != width * height * 4) @@ -1200,6 +1362,7 @@ int runHistoryOcr(const std::filesystem::path &request) } bool History::saveOcr(const std::wstring &id, const std::optional &text, const Settings &settings) { + std::lock_guard writer(indexWriter_); std::lock_guard lock(mutex_); auto it = std::find_if(entries_.begin(), entries_.end(), [&](auto &e) { return e.id == id; }); // A late OCR completion must never recreate a deleted/pruned image. diff --git a/src/storage.h b/src/storage.h index f77ecbe..23045f8 100644 --- a/src/storage.h +++ b/src/storage.h @@ -5,6 +5,7 @@ namespace ks { struct Pixels; +struct HistoryImageWorkers; Settings loadSettings(const std::filesystem::path &, const std::vector &); Settings decodeSettings(const Bytes &, const std::vector &); Bytes encodeSettings(const Settings &); @@ -26,12 +27,15 @@ class History std::filesystem::path folder_; std::vector entries_; mutable std::mutex mutex_; + std::unique_ptr imageWorkers_; + std::mutex indexWriter_; // Serializes resident mutations with the image capture helper. void saveIndex(); void loadIndex(); void prune(const Settings &); public: explicit History(const std::filesystem::path &); + ~History(); void reload(); std::vector entries() const; Clip load(const std::wstring &id) const; @@ -53,6 +57,7 @@ Clip decodeClip(const Bytes &); bool sameClipboardImage(const Clip &, const Clip &); int runImageHistoryCapture(const std::filesystem::path &request); int runHistoryOcr(const std::filesystem::path &request); +int runHistoryImageWorker(HANDLE mapping, HANDLE requestReady, HANDLE responseReady); // Image backups stay encrypted on disk and are read/written only by a short-lived helper. class ClipboardSnapshot { diff --git a/src/update.h b/src/update.h index 1e572f4..5a46788 100644 --- a/src/update.h +++ b/src/update.h @@ -2,7 +2,7 @@ #include "platform.h" namespace ks { -inline constexpr wchar_t AppVersion[] = L"0.6.105"; +inline constexpr wchar_t AppVersion[] = L"0.6.106"; inline constexpr UINT UpdateMessage = WM_APP + 7; inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000; inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000; diff --git a/tests/files_activation.ps1 b/tests/files_activation.ps1 index 6cb6900..465b39a 100644 --- a/tests/files_activation.ps1 +++ b/tests/files_activation.ps1 @@ -23,6 +23,17 @@ public static class FilesActivationUi { [DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id); [DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string type, string title); [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window); + [DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr window, uint relation); + [DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr window); + [DllImport("user32.dll")] static extern int ReleaseDC(IntPtr window, IntPtr dc); + [DllImport("gdi32.dll")] static extern uint GetPixel(IntPtr dc, int x, int y); + + public static bool HasWarningBackground(IntPtr window) { + var dc = GetDC(window); + if (dc == IntPtr.Zero) return false; + try { return GetPixel(dc, 2, 2) == 0x80; } + finally { ReleaseDC(window, dc); } + } [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); @@ -75,6 +86,29 @@ function Wait-Until([string]$Description, [scriptblock]$Condition) { throw "Timed out waiting for $Description" } +function Find-OperationDialog($Owner, [int]$Control) { + $candidate = [IntPtr]::Zero + while ($true) { + $candidate = [FilesActivationUi]::FindWindowEx([IntPtr]::Zero, $candidate, '#32770', [NullString]::Value) + if ($candidate -eq [IntPtr]::Zero) { return [IntPtr]::Zero } + if (![FilesActivationUi]::IsWindowVisible($candidate) -or + [FilesActivationUi]::GetDlgItem($candidate, $Control) -eq [IntPtr]::Zero) { continue } + $parent = [FilesActivationUi]::GetWindow($candidate, 4) + while ($parent -ne [IntPtr]::Zero) { + if ($parent -eq $Owner) { return $candidate } + $parent = [FilesActivationUi]::GetWindow($parent, 4) + } + } +} + +function Answer-OperationDialog([int]$Control, [int]$Answer) { + Wait-Until "operation dialog with control $Control" { + (Find-OperationDialog $window $Control) -ne [IntPtr]::Zero + } + $dialog = Find-OperationDialog $window $Control + [void][FilesActivationUi]::PostMessage($dialog, 0x111, [IntPtr]$Answer, [IntPtr]::Zero) +} + function Read-Text($Control, $Message = 0x0D, $Parameter = 32768) { $buffer = [Text.StringBuilder]::new(32768) [void][FilesActivationUi]::Read($Control, $Message, [IntPtr]$Parameter, $buffer) @@ -514,6 +548,187 @@ try { (Find-Row $right '[Size B]') } Write-Output 'Ctrl+R refreshed the active pane and kept its cursor.' + + $operationName = 'Background operation.txt' + $leftOperation = Join-Path $leftDir 'Operations' + $rightOperation = Join-Path $rightDir 'Operations' + New-Item -ItemType Directory -Path $leftOperation, $rightOperation | Out-Null + $operationSource = Join-Path $leftOperation $operationName + $operationTarget = Join-Path $rightOperation $operationName + Invoke-Row $left '[Operations]' $false + Invoke-Row $right '[Operations]' $false + Wait-Until 'operation folders loaded in both panes' { + (Read-Text ([FilesActivationUi]::GetDlgItem($window, 142))) -eq $leftOperation -and + (Read-Text ([FilesActivationUi]::GetDlgItem($window, 143))) -eq $rightOperation + } + [IO.File]::WriteAllText($operationSource, 'source contents') + [IO.File]::WriteAllText($operationTarget, 'original target') + Select-Row $left $operationName + [void][FilesActivationUi]::PostMessage($left, 0x100, [IntPtr]0x74, [IntPtr]::Zero) + Answer-OperationDialog 211 1 + Answer-OperationDialog 230 6 + Wait-Until 'copy after overwrite confirmation' { + (Read-Text $status) -ceq 'Copy complete.' -and + [FilesActivationUi]::Focus($window) -eq $inputBox + } + if ([IO.File]::ReadAllText($operationTarget) -cne 'source contents') { + throw 'Copy did not replace the target contents.' + } + [IO.File]::Delete($operationTarget) + Select-Row $left $operationName + [void][FilesActivationUi]::PostMessage($left, 0x100, [IntPtr]0x75, [IntPtr]::Zero) + Wait-Until 'move destination field' { (Find-OperationDialog $window 211) -ne [IntPtr]::Zero } + $moveDialog = Find-OperationDialog $window 211 + $destinationField = [FilesActivationUi]::GetDlgItem($moveDialog, 211) + $validDestination = Read-Text $destinationField + $missingDestination = Join-Path $rightOperation 'missing\destination.txt' + [void][FilesActivationUi]::Write($destinationField, 0x0C, [IntPtr]::Zero, $missingDestination) + Answer-OperationDialog 211 1 + Answer-OperationDialog 100 1 + Wait-Until 'focus returns to the move destination after asynchronous validation' { + [FilesActivationUi]::Focus($window) -eq $destinationField + } + if (!(Test-Path -LiteralPath $operationSource)) { throw 'Invalid destination started the move.' } + [void][FilesActivationUi]::Write($destinationField, 0x0C, [IntPtr]::Zero, $validDestination) + $lockReady = Join-Path $root 'lock.ready' + $locker = Start-Process -FilePath $Fixture -ArgumentList ('--hold "{0}" "{1}"' -f $operationSource,$lockReady) -WindowStyle Hidden -PassThru + try { + Wait-Until 'file locked by the fixture process' { Test-Path -LiteralPath $lockReady } + Answer-OperationDialog 211 1 + Wait-Until 'red modal error for a locked file' { + $errorDialog = Find-OperationDialog $window 100 + $errorDialog -ne [IntPtr]::Zero -and [FilesActivationUi]::HasWarningBackground($errorDialog) + } + $errorDialog = Find-OperationDialog $window 100 + $reason = Read-Text ([FilesActivationUi]::GetDlgItem($errorDialog, 100)) + if (!$reason -or (Read-Text $status).Contains($reason)) { + throw 'The move failure reason must appear in the modal dialog.' + } + Answer-OperationDialog 100 103 + Wait-Until 'the locker appears with its PID' { + $dialog = Find-OperationDialog $window 431 + if ($dialog -eq [IntPtr]::Zero) { return $false } + $list = [FilesActivationUi]::GetDlgItem($dialog, 431) + (Find-Row $list ("KSwitcherFilesActivationFixture.exe (PID {0})" -f $locker.Id)) -ge 0 + } + $dialog = Find-OperationDialog $window 431 + $list = [FilesActivationUi]::GetDlgItem($dialog, 431) + $row = Find-Row $list ("KSwitcherFilesActivationFixture.exe (PID {0})" -f $locker.Id) + [void][FilesActivationUi]::Send($list, 0x186, [IntPtr]$row, [IntPtr]::Zero) + Answer-OperationDialog 431 433 + Answer-OperationDialog 100 7 + Wait-Until 'End process confirmation closes after No' { + (Find-OperationDialog $window 100) -eq [IntPtr]::Zero + } + if ($locker.HasExited) { throw 'Declining the confirmation ended the process.' } + Answer-OperationDialog 431 433 + Answer-OperationDialog 100 6 + if (!$locker.WaitForExit(5000)) { throw 'Confirming End process did not terminate the locker.' } + Wait-Until 'the process list refreshes after termination' { + (Read-Text ([FilesActivationUi]::GetDlgItem($dialog, 430))) -like 'No locking processes found*' + } + Answer-OperationDialog 431 1 + } finally { + if (!$locker.HasExited) { $locker.Kill(); $locker.WaitForExit() } + $locker.Dispose() + } + Select-Row $left $operationName + [void][FilesActivationUi]::PostMessage($left, 0x100, [IntPtr]0x75, [IntPtr]::Zero) + Answer-OperationDialog 211 1 + Wait-Until 'move and asynchronous pane refresh' { + !(Test-Path -LiteralPath $operationSource) -and + (Find-Row $left $operationName) -eq -1 -and (Find-Row $right $operationName) -ge 0 + } + Select-Row $right $operationName + Wait-Until 'Files activation for Shift+Delete' { + [FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox + } + $shell.SendKeys('+{DELETE}') + Answer-OperationDialog 240 6 + Wait-Until 'permanent deletion and asynchronous pane refresh' { + !(Test-Path -LiteralPath $operationTarget) -and (Find-Row $right $operationName) -eq -1 -and + [FilesActivationUi]::Focus($window) -eq $inputBox + } + Write-Output 'Copy overwrite, move and permanent deletion completed through their Files dialogs.' + + $lockedFolder = Join-Path $leftOperation 'Locked folder' + [IO.Directory]::CreateDirectory($lockedFolder) | Out-Null + $folderReady = Join-Path $root 'folder-lock.ready' + $folderLocker = Start-Process -FilePath $Fixture -ArgumentList ('--hold "{0}" "{1}"' -f $lockedFolder,$folderReady) -WindowStyle Hidden -PassThru + try { + Wait-Until 'folder locked by the fixture process' { Test-Path -LiteralPath $folderReady } + Select-Row $left '[Locked folder]' + [void][FilesActivationUi]::PostMessage($left, 0x100, [IntPtr]0x75, [IntPtr]::Zero) + Answer-OperationDialog 211 1 + Answer-OperationDialog 100 103 + Wait-Until 'the folder locker appears with its PID' { + $dialog = Find-OperationDialog $window 431 + if ($dialog -eq [IntPtr]::Zero) { return $false } + $list = [FilesActivationUi]::GetDlgItem($dialog, 431) + (Find-Row $list ("KSwitcherFilesActivationFixture.exe (PID {0})" -f $folderLocker.Id)) -ge 0 + } + Answer-OperationDialog 431 1 + } finally { + if (!$folderLocker.HasExited) { $folderLocker.Kill(); $folderLocker.WaitForExit() } + $folderLocker.Dispose() + } + Write-Output 'The blocking-process dialog identified both a file lock and a folder lock by PID.' + + foreach ($useRecycleBin in $false, $true) { + $name = if ($useRecycleBin) { 'Held for Recycle Bin' } else { 'Held for permanent deletion.txt' } + $target = Join-Path $leftOperation $name + if ($useRecycleBin) { [IO.Directory]::CreateDirectory($target) | Out-Null } + else { [IO.File]::WriteAllText($target, 'fixture') } + $label = if ($useRecycleBin) { "[$name]" } else { $name } + $ready = Join-Path $root "delete-lock-$useRecycleBin.ready" + $deleteLocker = Start-Process -FilePath $Fixture -ArgumentList ('--hold "{0}" "{1}"' -f $target,$ready) -WindowStyle Hidden -PassThru + try { + Wait-Until 'deletion target held by the fixture' { Test-Path -LiteralPath $ready } + Select-Row $left $label + if ($useRecycleBin) { + [void][FilesActivationUi]::PostMessage($left, 0x100, [IntPtr]0x77, [IntPtr]::Zero) + } else { + Wait-Until 'Files activation for blocked Shift+Delete' { [FilesActivationUi]::Activate($window) } + $shell.SendKeys('+{DELETE}') + } + Answer-OperationDialog 240 6 + Wait-Until 'red failure dialog for blocked deletion' { + $dialog = Find-OperationDialog $window 100 + $dialog -ne [IntPtr]::Zero -and [FilesActivationUi]::HasWarningBackground($dialog) + } + Answer-OperationDialog 100 103 + $processLabel = 'KSwitcherFilesActivationFixture.exe (PID {0})' -f $deleteLocker.Id + Wait-Until 'deletion blocker appears in the process list' { + $dialog = Find-OperationDialog $window 431 + $dialog -ne [IntPtr]::Zero -and + (Find-Row ([FilesActivationUi]::GetDlgItem($dialog, 431)) $processLabel) -ge 0 + } + $dialog = Find-OperationDialog $window 431 + $list = [FilesActivationUi]::GetDlgItem($dialog, 431) + [void][FilesActivationUi]::Send($list, 0x186, [IntPtr](Find-Row $list $processLabel), [IntPtr]::Zero) + Answer-OperationDialog 431 433 + Answer-OperationDialog 100 6 + if (!$deleteLocker.WaitForExit(5000)) { throw 'End process did not release the deletion target.' } + Wait-Until 'deletion blocker list refreshes' { + (Read-Text ([FilesActivationUi]::GetDlgItem($dialog, 430))) -like 'No locking processes found*' + } + Answer-OperationDialog 431 1 + Wait-Until 'Files regains focus after closing the process list' { + [FilesActivationUi]::Focus($window) -eq $inputBox + } + } finally { + if (!$deleteLocker.HasExited) { $deleteLocker.Kill(); $deleteLocker.WaitForExit() } + $deleteLocker.Dispose() + } + Select-Row $left $label + Wait-Until 'Files activation for deletion retry' { [FilesActivationUi]::Activate($window) } + $shell.SendKeys('+{DELETE}') + Answer-OperationDialog 240 6 + Wait-Until 'deletion succeeds after ending the blocker' { + !(Test-Path -LiteralPath $target) -and (Find-Row $left $label) -eq -1 + } + } + Write-Output 'Blocked permanent file deletion and folder recycling opened the shared process dialog and released their blockers.' } catch { if ($inputBox -and $status) { Write-Output "Command input length: $((Read-Text $inputBox).Length). Status: $(Read-Text $status)" diff --git a/tests/files_activation_fixture.cpp b/tests/files_activation_fixture.cpp index 780bb92..d81c777 100644 --- a/tests/files_activation_fixture.cpp +++ b/tests/files_activation_fixture.cpp @@ -1,9 +1,22 @@ #include #include #include +#include int wmain(int argc,wchar_t **argv) { + if(argc==4 && std::wstring_view(argv[1])==L"--hold") + { + const auto handle=CreateFileW(argv[2],GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,nullptr, + OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS,nullptr); + if(handle==INVALID_HANDLE_VALUE) return 1; + const auto ready=CreateFileW(argv[3],GENERIC_WRITE,FILE_SHARE_READ,nullptr,CREATE_ALWAYS,0,nullptr); + if(ready==INVALID_HANDLE_VALUE){CloseHandle(handle);return 1;} + CloseHandle(ready); + Sleep(INFINITE); + CloseHandle(handle); + return 0; + } // A launch through the embedded terminal would inherit its console. DWORD consoleProcesses[1]{}; if(GetConsoleProcessList(consoleProcesses,1)>1) return 1; diff --git a/tests/lan_clipboard.cpp b/tests/lan_clipboard.cpp index fd84b4d..902c632 100644 --- a/tests/lan_clipboard.cpp +++ b/tests/lan_clipboard.cpp @@ -30,6 +30,37 @@ int main(){try{ check(b.deliveries.size()==1&&c.deliveries.size()==1,"all paired instances receive exactly once despite loss/duplicates"); check(b.deliveries[0].bytes==payload&&c.deliveries[0].bytes==payload,"binary clipboard survives retransmission"); check(b.deliveries[0].sequence==123&&b.deliveries[0].app=="editor.exe","capture sequence and origin retained"); + { + ClipboardExchange sender(aid),receiver(bid); + sender.peerSession(bid,receiver.session()); + receiver.peerSession(aid,sender.session()); + const Bytes large(480*90+7,42); + sender.queue({bid},large,"no loss",1); + size_t emitted=0; + const auto deliver=[&](const std::string &to,const Json &packet) { + ++emitted; + packets.emplace_back(to,packet); + }; + for(uint64_t now=2;now<300 && receiver.deliveries.empty();++now) + { + sender.poll(trusted,now,deliver); + // Interleave ACKs and sender polls while part of the current window is still in flight. + if(!packets.empty()) + { + auto packet=std::move(packets.front().second); + packets.pop_front(); + receiver.receive(aid,key,packet,now,321,ack); + } + while(!acks.empty()) + { + auto packet=std::move(acks.front().second); + acks.pop_front(); + sender.receive(bid,key,packet,now,321,deliver); + } + } + check(receiver.deliveries.size()==1 && receiver.deliveries.front().bytes==large,"sliding window delivers without loss"); + check(emitted==92,"ACK advancement sends each chunk once without retransmitting in-flight slots"); + } b.receive(aid,key,firstPacket,10000,123,ack); check(acks.empty(),"authenticated old packet replay is ignored"); ClipboardExchange restarted(bid);restarted.peerSession(aid,a.session()); diff --git a/tests/ocr.cpp b/tests/ocr.cpp index b285fdc..66f6248 100644 --- a/tests/ocr.cpp +++ b/tests/ocr.cpp @@ -1,11 +1,27 @@ #include "ocr.h" #include "app.h" +#include +#include +#include #include namespace ks { struct InputRegressionAccess { static void scheduleOcr(App &app) { app.scheduleHistoryOcr(app.settings); } }; } +std::set historyImageHelpers() +{ + const auto snapshot=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); + if(snapshot==INVALID_HANDLE_VALUE) throw std::runtime_error("Cannot enumerate OCR fixtures"); + struct Cleanup {HANDLE handle;~Cleanup(){CloseHandle(handle);}} cleanup{snapshot}; + std::set children; + PROCESSENTRY32W entry{sizeof(entry)}; + for(auto ok=Process32FirstW(snapshot,&entry);ok;ok=Process32NextW(snapshot,&entry)) + if(entry.th32ParentProcessID==GetCurrentProcessId() && lstrcmpiW(entry.szExeFile,L"KSwitcher.Screenshot.exe")==0) + children.insert(entry.th32ProcessID); + return children; +} + int main(int argc, char **argv) { const bool tesseract = argc == 2 && std::string(argv[1]) == "--tesseract"; @@ -52,6 +68,16 @@ int main(int argc, char **argv) throw std::runtime_error("OCR fixture was not recognized"); if (tesseract && ks::lower(text).find(L"привіт") == std::wstring::npos) throw std::runtime_error("Ukrainian OCR fixture was not recognized"); + if (!tesseract) + { + constexpr UINT width=20000; + ks::Pixels wideFixture{width,pixels.height,ks::Bytes(size_t(width)*pixels.height*4,255)}; + for(UINT y=0;yentries().front().id; auto isolated = app.history->recognizeImage(id, config); if (isolated != text) throw std::runtime_error("Helper and in-process OCR results differ"); + const auto recognitionWorker=historyImageHelpers(); + if(recognitionWorker.size()!=1 || app.history->recognizeImage(id,config)!=text || + historyImageHelpers()!=recognitionWorker) + throw std::runtime_error("Successive history requests did not reuse the OCR process"); + const auto thumbnail=app.history->thumbnail(id); + const auto previewWorkers=historyImageHelpers(); + const auto repeated=app.history->thumbnail(id); + if(previewWorkers.size()!=2 || historyImageHelpers()!=previewWorkers || + thumbnail.width!=repeated.width || thumbnail.height!=repeated.height || thumbnail.bgra!=repeated.bgra) + throw std::runtime_error("Successive thumbnail requests did not reuse the independent preview worker"); bool cancelled = false; try { app.history->recognizeImage(id, config, [] { return true; }); } catch (const std::exception &) { cancelled = true; } @@ -71,6 +107,16 @@ int main(int argc, char **argv) bool failed = false; try { app.history->recognizeImage(id, invalid); } catch (const std::exception &) { failed = true; } + if(historyImageHelpers()!=previewWorkers || app.history->recognizeImage(id,config)!=text) + throw std::runtime_error("An OCR job error ended the reusable helper"); + const auto child=OpenProcess(PROCESS_TERMINATE|SYNCHRONIZE,FALSE,*recognitionWorker.begin()); + if(!child) throw std::runtime_error("Cannot open OCR crash fixture"); + const auto terminated=TerminateProcess(child,ERROR_PROCESS_ABORTED) && + WaitForSingleObject(child,5000)==WAIT_OBJECT_0; + CloseHandle(child); + if(!terminated || app.history->recognizeImage(id,config)!=text || historyImageHelpers()==previewWorkers) + throw std::runtime_error("History OCR did not restart its exited helper"); + std::cout << "PASS OCR and thumbnail process reuse and restart after worker exit\n"; if (!failed || app.history->entries().front().ocrState != 1) throw std::runtime_error("Failed helper modified history metadata"); for (const auto &file : std::filesystem::directory_iterator(temp / L"history")) @@ -98,6 +144,7 @@ int main(int argc, char **argv) throw std::runtime_error("Background OCR changed the clipboard"); std::cout << "PASS automatic background OCR, persisted search and unchanged clipboard\n"; } + if(!historyImageHelpers().empty()) throw std::runtime_error("Closing history left OCR workers running"); std::filesystem::remove_all(temp); std::cout << (tesseract ? "PASS optional Tesseract, mixed Ukrainian/English and cache migration\n" : "PASS native Windows OCR, DIB decoding and async result retrieval\n"); diff --git a/tests/screenshot_ui.cpp b/tests/screenshot_ui.cpp index c037ab3..1a886b7 100644 --- a/tests/screenshot_ui.cpp +++ b/tests/screenshot_ui.cpp @@ -531,7 +531,7 @@ int main(int argc, char **argv) auto dib=ks::screenshotClip(cursorPreview.dc,784,448,{}).formats[0].data; BITMAPFILEHEADER bmp{}; bmp.bfType=0x4d42; bmp.bfOffBits=sizeof(bmp)+sizeof(BITMAPINFOHEADER); bmp.bfSize=DWORD(sizeof(bmp)+dib.size()); ks::Bytes preview(sizeof(bmp)); memcpy(preview.data(),&bmp,sizeof(bmp)); preview.insert(preview.end(),dib.begin(),dib.end()); - ks::atomicWrite(L"build/cursor-preview.bmp",preview); + ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"cursor-preview.bmp",preview); for(int tool:{27,26,21,10,11,22,23,24,25,19}) { SendMessageW(window,WM_COMMAND,tool,0); HCURSOR expected=nullptr; @@ -806,6 +806,90 @@ int main(int argc, char **argv) require(IsWindow(window),"Escape does not close the screenshot editor"); SendMessageW(window,WM_CLOSE,0,0); require(!IsWindow(window),"copied screenshot closes without confirmation"); + { + ks::Capture cached(app); + constexpr int imageWidth=400,imageHeight=240; + cached.image=std::make_unique(imageWidth,imageHeight); + PatBlt(cached.image->dc,0,0,imageWidth,imageHeight,WHITENESS); + cached.end={imageWidth,imageHeight}; + const auto editor=CreateWindowW(cls.lpszClassName,L"Cached marks test",WS_POPUP,0,0,imageWidth,imageHeight, + app.window,nullptr,app.instance,&cached); + require(editor,"cached marks test window"); + ks::edit(editor,cached); + cached.marks.push_back({{50,50},{50,50},1}); + const auto paint=[&] {InvalidateRect(editor,nullptr,FALSE);UpdateWindow(editor);}; + paint(); + require(cached.rendered && cached.renderedMarksValid,"paint caches committed marks"); + SetPixelV(cached.rendered->dc,0,0,RGB(19,23,27)); + paint(); + require(GetPixel(cached.rendered->dc,0,0)==RGB(19,23,27),"unchanged paint reuses the marked surface"); + cached.remember(cached.marks); + cached.marks.front().color=RGB(0,128,255); + paint(); + require(GetPixel(cached.rendered->dc,0,0)==RGB(255,255,255),"mark edit rebuilds the cached surface"); + SetPixelV(cached.rendered->dc,0,0,RGB(19,23,27)); + SendMessageW(editor,WM_COMMAND,12,0); + paint(); + require(GetPixel(cached.rendered->dc,0,0)==RGB(255,255,255),"undo rebuilds the cached surface"); + ks::Mark highlight{{10,48},{180,52},0}; + highlight.points={{10,48},{54,50},{92,52}}; + highlight.thickness=9; + cached.marks.push_back(std::move(highlight)); + cached.renderedMarksValid=false; + paint(); + cached.selected=0; + cached.dragging=true; + cached.part=ks::MarkPart::Body; + cached.original=cached.marks.front(); + cached.start={50,50}; + SetPixelV(cached.rendered->dc,0,0,RGB(19,23,27)); + const int mouseX=cached.view.left+MulDiv(70,cached.view.right-cached.view.left,imageWidth); + const int mouseY=cached.view.top+MulDiv(50,cached.view.bottom-cached.view.top,imageHeight); + SendMessageW(editor,WM_MOUSEMOVE,MK_LBUTTON,MAKELPARAM(mouseX,mouseY)); + RECT update{}; + require(GetUpdateRect(editor,&update,FALSE) && update.right-update.leftdc,0,0)==RGB(19,23,27),"drag preserves pixels outside the damaged area"); + ks::Surface reference(imageWidth,imageHeight); + PatBlt(reference.dc,0,0,imageWidth,imageHeight,WHITENESS); + ks::drawMarks(reference.dc,cached.marks); + GdiFlush(); + const auto *expected=static_cast(reference.pixels); + const auto *actual=static_cast(cached.rendered->pixels); + for(size_t pixel=1;pixel(100,100); + selection.dimmed=std::make_unique(100,100); + selection.frame=std::make_unique(100,100); + PatBlt(selection.image->dc,0,0,100,100,WHITENESS); + PatBlt(selection.dimmed->dc,0,0,100,100,BLACKNESS); + auto overlay=CreateWindowW(cls.lpszClassName,L"Selection repaint test",WS_POPUP,0,0,100,100, + app.window,nullptr,app.instance,&selection); + require(overlay,"selection repaint window"); + ShowWindow(overlay,SW_SHOWNOACTIVATE); + UpdateWindow(overlay); + selection.dragging=true; + selection.start=selection.end={10,10}; + SendMessageW(overlay,WM_MOUSEMOVE,MK_LBUTTON,MAKELPARAM(70,70)); + UpdateWindow(overlay); + require(GetPixel(selection.frame->dc,55,55)==RGB(255,255,255),"drag reveals undimmed selection"); + SendMessageW(overlay,WM_MOUSEMOVE,MK_LBUTTON,MAKELPARAM(40,40)); + RECT dirty{}; + require(GetUpdateRect(overlay,&dirty,FALSE) && dirty.left==10 && dirty.top==10 && + dirty.right==70 && dirty.bottom==70,"drag invalidates old and new selection bounds"); + UpdateWindow(overlay); + require(GetPixel(selection.frame->dc,55,55)==RGB(0,0,0) && + GetPixel(selection.frame->dc,20,20)==RGB(255,255,255),"shrinking selection restores its old background"); + DestroyWindow(overlay); + } static bool published=false; static bool notificationAccepted=false; static HWND notificationWindow{}; diff --git a/tests/tests.cpp b/tests/tests.cpp index 849b955..3ecb9bc 100644 --- a/tests/tests.cpp +++ b/tests/tests.cpp @@ -770,8 +770,8 @@ int main(int argc, char **argv) rejects([&] { ks::decodeSettings(ks::Bytes{'{', '}'}, {}); }, "configurator rejects missing settings format"); require(!restored.writeLog, "logging setting persists when disabled"); - require(ks::loadSettings(temp / L"defaults.json", {}).writeLog, - "logging defaults on for existing diagnostic installations"); + require(!ks::loadSettings(temp / L"defaults.json", {}).writeLog, + "logging defaults off until explicitly enabled"); require(restored.snippets[0].text == settings.snippets[0].text, "settings snippet roundtrip"); require(restored.cycle == settings.cycle, "layout order roundtrip"); require(restored.elevatedAutostart, "elevated autostart setting roundtrip");