Compare commits

...
Author SHA1 Message Date
agrynco d8c329c265 Prepare KSwitcher v0.6.120
Keep image clipboard backups in a short-lived helper to reduce layout conversion latency while preserving newer copies.
2026-11-20 00:40:46 +02:00
agrynco debd2b9cd9 Release KSwitcher v0.6.119 (#65) 2026-11-18 13:08:23 +02:00
11 changed files with 253 additions and 225 deletions

No files matched your search

+1 -1
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.6.119 LANGUAGES CXX RC)
project(KSwitcher VERSION 0.6.120 LANGUAGES CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
+1 -1
View File
@@ -1027,7 +1027,7 @@ History opens in a separate, short-lived instance of **KSwitcher.exe**. **Esc**
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.
Idle history helpers exit after 30 seconds, and closing the history host stops its helpers. During text conversion, a short-lived instance of **KSwitcher.Screenshot.exe** holds the image clipboard backup in memory and restores it only if the clipboard sequence still matches. Selection reads avoid loading image formats. Keep the executables from the same ZIP together. 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.
+8
View File
@@ -1,5 +1,13 @@
# Latest Windows release
## v0.6.120 — 2026-11-20
Layout conversion starts faster when the Windows clipboard contains an image. KSwitcher keeps the image and accompanying formats in memory for the duration of the operation. It restores them after conversion if the clipboard still belongs to the operation. A newer copy takes precedence.
**Українською.**
Перетворення розкладки починається швидше, коли в буфері обміну Windows є зображення. KSwitcher тримає зображення й супровідні формати в пам’яті до завершення операції. Копія відновлюється, якщо буфер усе ще належить операції. Новіше копіювання має пріоритет.
## v0.6.119 — 2026-11-18
KSwitcher Files runs local commands in the folder shown at the command prompt. After switching panes or opening a different folder, commands such as `git clone` and relative path suggestions use that folder in the same PowerShell session.
+1 -1
View File
@@ -1 +1 @@
566cda1b26bbc5980e3e19f804ae500bf029fe6f5a503cfd609be6f6ad4409ea KSwitcher-win-x64.zip
53334ba83a44c69c3acd2aad297db177366fe553fae8813b88b81e0a215c860f KSwitcher-win-x64.zip
+67 -67
View File
@@ -1,166 +1,166 @@
{
"version": "0.6.119",
"schema": 1,
"files": [
{
"size": 2479104,
"path": "KSwitcher.exe",
"sha256": "e6b98679ac0a460e42ec9f593e88cc802cedaaaf887bce79c3f8577419143aa1"
"sha256": "152b41278761439ce5ebe87bca3a4d8a96d89db82264ec0fbb2299e7c207dfb5",
"size": 2372096
},
{
"size": 2458112,
"path": "KSwitcher.Config.exe",
"sha256": "43e4ea0d087d70658fd2cca47b2f06b919eb86acc65dce1afa7db1e02cbdcded"
"sha256": "3d44721ba688a6916e393d2b9d9291e38ee063795b54cdae8e78cfd621835619",
"size": 2369536
},
{
"size": 3060224,
"path": "KSwitcher.Screenshot.exe",
"sha256": "9b791b2dbf623f50ab92cde4017b07c9f8df4bbb7ac3526d0d18e0d770061f43"
"sha256": "81d9fbb770e876937310a0b483e11bd96cdb9e20b0f6baf0fa9927f24965aeeb",
"size": 3348992
},
{
"size": 4370944,
"path": "KSwitcher.Files.exe",
"sha256": "e44a923d3e686e0e273e6dd167f6bd66dafd66e2870b4950fcbd8824d286a61d"
"sha256": "04c9af5324144a46a5f3cc0d8f2c6912745f8bbad7fbef0576bd52c88b5c5e03",
"size": 4370944
},
{
"size": 194912,
"path": "WebView2Loader.dll",
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
"size": 194912
},
{
"size": 1103,
"path": "terminal/addon-fit-LICENSE.txt",
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
"size": 1103
},
{
"size": 1521,
"path": "terminal/addon-fit.js",
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
"size": 1521
},
{
"size": 527,
"path": "terminal/index.html",
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
"size": 527
},
{
"size": 1073,
"path": "terminal/markdown-it-LICENSE.txt",
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473"
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
"size": 1073
},
{
"size": 100786,
"path": "terminal/markdown-it.js",
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
"size": 100786
},
{
"size": 3635,
"path": "terminal/markdown.html",
"sha256": "8268f55e8642034efa5a762cbd65d02a1d416aea9e777e0fe30a7e916ae3ee79"
"sha256": "8268f55e8642034efa5a762cbd65d02a1d416aea9e777e0fe30a7e916ae3ee79",
"size": 3635
},
{
"size": 16944,
"path": "terminal/markdown.js",
"sha256": "4c68dff619cf248f6bd32b09a45458675c22341892dc377204e46c2f4fd562f8"
"sha256": "4c68dff619cf248f6bd32b09a45458675c22341892dc377204e46c2f4fd562f8",
"size": 16944
},
{
"size": 1089,
"path": "terminal/mermaid-LICENSE.txt",
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80"
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
"size": 1089
},
{
"size": 5537838,
"path": "terminal/mermaid.js",
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3"
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
"size": 5537838
},
{
"size": 5065,
"path": "terminal/terminal.js",
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b"
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b",
"size": 5065
},
{
"size": 1261,
"path": "terminal/xterm-LICENSE.txt",
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
"size": 1261
},
{
"size": 7112,
"path": "terminal/xterm.css",
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
"size": 7112
},
{
"size": 488663,
"path": "terminal/xterm.js",
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
"size": 488663
},
{
"size": 4401,
"path": "LICENSE",
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
"size": 4401
},
{
"size": 1096,
"path": "json-LICENSE.txt",
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831"
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
"size": 1096
},
{
"size": 883,
"path": "files-text-license.txt",
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
"size": 883
},
{
"size": 95317,
"path": "README.md",
"sha256": "ea5016c6fa29a98bf9ebf103fcf27f1be091842ad3228b167d18b053fda767d8"
"sha256": "afc7e78c4c3600888f642692423cd993b4aa431dfa54f752c7ac394de18186c6",
"size": 95354
},
{
"size": 11577,
"path": "LAN-PREVIEW.md",
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930"
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930",
"size": 11577
},
{
"size": 732485,
"path": "dictionaries/en.txt",
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9"
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
"size": 732485
},
{
"size": 20566,
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5"
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
"size": 20566
},
{
"size": 2265,
"path": "dictionaries/README.md",
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
"size": 2265
},
{
"size": 1109134,
"path": "dictionaries/ru.txt",
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849"
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
"size": 1109134
},
{
"size": 1280,
"path": "dictionaries/sources.json",
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
"size": 1280
},
{
"size": 940799,
"path": "dictionaries/uk.txt",
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
"size": 940799
},
{
"size": 993,
"path": "tools/README.txt",
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
"size": 993
},
{
"size": 133120,
"path": "tools/StayHere.exe",
"sha256": "d689b74a0c5ba018d3f26eb32c4fab88a8404627ee69be1e326d60b1167b5667"
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376",
"size": 134656
},
{
"size": 2796,
"path": "tools/StayHere-README.md",
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
"size": 2796
}
]
],
"schema": 1,
"version": "0.6.120"
}
+3 -3
View File
@@ -9,8 +9,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
1 RT_MANIFEST "app.manifest"
201 RCDATA "update.ps1"
1 VERSIONINFO
FILEVERSION 0,6,119,0
PRODUCTVERSION 0,6,119,0
FILEVERSION 0,6,120,0
PRODUCTVERSION 0,6,120,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.119"
VALUE "FileVersion", "0.6.120"
END
END
BLOCK "VarFileInfo"
+7 -7
View File
@@ -50,13 +50,12 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int)
std::wstring token;
bool autoOpenEditor=false, writeLog=false;
int argc{}; auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);
if(argc==3 && std::wstring(argv[1])==L"--clipboard-snapshot") {
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)
const bool clipboardSnapshot = argc == 6 && std::wstring_view(argv[1]) == L"--clipboard-snapshot";
const bool historyImageWorker = argc == 5 && std::wstring_view(argv[1]) == L"--history-image-worker";
if (clipboardSnapshot || historyImageWorker)
{
HANDLE handles[4]{};
for (int i = 0; i < argc - 2; ++i)
{
wchar_t *end{};
const auto value=std::wcstoull(argv[i+2],&end,10);
@@ -64,6 +63,7 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int)
handles[i]=reinterpret_cast<HANDLE>(static_cast<uintptr_t>(value));
}
LocalFree(argv);
if (clipboardSnapshot) return ks::runClipboardSnapshot(handles[0], handles[1], handles[2], handles[3]);
const auto initialized=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
if(FAILED(initialized)) return 1;
const auto result=ks::runHistoryImageWorker(handles[0],handles[1],handles[2]);
+138 -134
View File
@@ -703,26 +703,98 @@ struct ImageWorkerHandle
if(value) CloseHandle(std::exchange(value,nullptr));
}
};
template <typename Control>
struct ImageWorkerView
{
ImageWorkerControl *control{};
Control *control{};
~ImageWorkerView() { reset(); }
void reset()
{
if(control) UnmapViewOfFile(std::exchange(control,nullptr));
}
};
template <typename Control>
struct ImageWorkerChannel
{
ImageWorkerHandle mapping, requestReady, responseReady, process;
ImageWorkerView<Control> view;
~ImageWorkerChannel() { stop(); }
void stop() noexcept
{
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 open()
{
SECURITY_ATTRIBUTES security{sizeof(security), nullptr, TRUE};
mapping.value = CreateFileMappingW(INVALID_HANDLE_VALUE, &security, PAGE_READWRITE, 0, sizeof(Control), 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 image helper channel");
view.control = static_cast<Control *>(MapViewOfFile(mapping.value, FILE_MAP_WRITE, 0, 0, sizeof(Control)));
if (!view.control) throw std::runtime_error("Cannot map image helper channel");
}
void start(std::wstring_view mode, HANDLE parent = nullptr)
{
std::vector<HANDLE> inherited{mapping.value, requestReady.value, responseReady.value};
if (parent) inherited.push_back(parent);
SIZE_T bytes{};
InitializeProcThreadAttributeList(nullptr, 1, 0, &bytes);
Bytes storage(bytes);
auto attributes = reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
if (!InitializeProcThreadAttributeList(attributes, 1, 0, &bytes))
throw std::runtime_error("Cannot initialize image helper startup");
struct Attributes
{
LPPROC_THREAD_ATTRIBUTE_LIST value;
~Attributes() { DeleteProcThreadAttributeList(value); }
} cleanup{attributes};
if (!UpdateProcThreadAttribute(attributes, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
inherited.data(), inherited.size() * sizeof(HANDLE), nullptr, nullptr))
throw std::runtime_error("Cannot configure image helper startup");
const auto helper = std::filesystem::path(executable()).parent_path() / L"KSwitcher.Screenshot.exe";
auto command = L"\"" + helper.wstring() + L"\" ";
command += mode;
for (auto handle : inherited) command += L" " + std::to_wstring(reinterpret_cast<uintptr_t>(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 image helper")));
process.value = child.hProcess;
CloseHandle(child.hThread);
for (auto handle : inherited) SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0);
}
DWORD waitForResponse(DWORD timeout) const
{
HANDLE signals[]{responseReady.value, process.value};
return WaitForMultipleObjects(2, signals, FALSE, timeout);
}
};
struct HistoryImageWorker
{
std::timed_mutex mutex;
ImageWorkerHandle mapping, requestReady, responseReady, process;
ImageWorkerView view;
~HistoryImageWorker() { stop(); }
void stop();
void start();
ImageWorkerChannel<ImageWorkerControl> channel;
int perform(const std::filesystem::path &, const std::function<bool()> &);
};
struct ClipboardSnapshotControl
{
DWORD sequence;
};
}
struct HistoryImageWorkers
@@ -778,42 +850,15 @@ void History::reload()
std::lock_guard lock(mutex_);
loadIndex();
}
void ClipboardSnapshot::cleanup() noexcept
struct ClipboardSnapshot::Helper
{
if (request_.empty()) return;
std::error_code ignored;
for (const auto *suffix : {L"", L".snapshot", L".result"})
std::filesystem::remove(std::filesystem::path(request_.wstring() + suffix), ignored);
request_.clear();
}
ClipboardSnapshot::~ClipboardSnapshot() { cleanup(); }
DWORD ClipboardSnapshot::run(bool restore, DWORD sequence)
{
atomicWrite(request_, protect(jsonBytes(Json{{"schema", 1}, {"restore", restore}, {"sequence", sequence}})));
auto helper = std::filesystem::path(executable()).parent_path() / L"KSwitcher.Screenshot.exe";
auto command = L"\"" + helper.wstring() + L"\" --clipboard-snapshot \"" + 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("Cannot start clipboard snapshot helper");
CloseHandle(process.hThread);
auto wait = WaitForSingleObject(process.hProcess, 10000);
DWORD result = ERROR_GEN_FAILURE;
if (wait != WAIT_OBJECT_0)
{
TerminateProcess(process.hProcess, ERROR_TIMEOUT);
WaitForSingleObject(process.hProcess, INFINITE);
}
GetExitCodeProcess(process.hProcess, &result);
CloseHandle(process.hProcess);
if (wait != WAIT_OBJECT_0 || result) throw std::runtime_error("Clipboard snapshot helper failed");
return parse(unprotect(readFile(request_.wstring() + L".result", 4096))).at("sequence").get<DWORD>();
}
ImageWorkerChannel<ClipboardSnapshotControl> channel;
};
ClipboardSnapshot::ClipboardSnapshot() = default;
ClipboardSnapshot::~ClipboardSnapshot() = default;
void ClipboardSnapshot::capture(HWND window, DWORD sequence)
{
cleanup();
helper_.reset();
clip_ = {};
if (!IsClipboardFormatAvailable(CF_DIB) && !IsClipboardFormatAvailable(CF_DIBV5) &&
!IsClipboardFormatAvailable(CF_BITMAP) && !IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG")))
@@ -821,39 +866,53 @@ void ClipboardSnapshot::capture(HWND window, DWORD sequence)
clip_ = readClipboard(window, 64 * 1024 * 1024, ClipboardRead::WithoutImages, sequence);
return;
}
request_ = std::filesystem::temp_directory_path() / (L"ks-clipboard-" + newSnippetId() + L".request");
try { run(false, sequence); }
catch (...) { cleanup(); throw; }
auto helper = std::make_unique<Helper>();
auto &channel = helper->channel;
channel.open();
channel.view.control->sequence = sequence;
// Let the helper discard its private copy if the resident exits unexpectedly.
ImageWorkerHandle parent;
const auto self = GetCurrentProcess();
if (!DuplicateHandle(self, self, self, &parent.value, SYNCHRONIZE, TRUE, 0))
throw std::runtime_error("Cannot pass resident lifetime to clipboard helper");
channel.start(L"--clipboard-snapshot", parent.value);
if (channel.waitForResponse(10000) != WAIT_OBJECT_0)
throw std::runtime_error("Clipboard snapshot helper failed to capture");
helper_ = std::move(helper);
}
DWORD ClipboardSnapshot::restore(HWND window, DWORD sequence)
{
return request_.empty() ? writeClipboardGuarded(window, clip_, sequence) : run(true, sequence);
if (!helper_) return writeClipboardGuarded(window, clip_, sequence);
auto &channel = helper_->channel;
if (!channel.process.value)
throw std::runtime_error("Clipboard snapshot helper is unavailable");
channel.view.control->sequence = sequence;
DWORD result{};
if (!SetEvent(channel.requestReady.value) || WaitForSingleObject(channel.process.value, 10000) != WAIT_OBJECT_0 ||
!GetExitCodeProcess(channel.process.value, &result) || result != 0)
{
channel.stop();
throw std::runtime_error("Clipboard snapshot helper failed to restore");
}
return channel.view.control->sequence;
}
int runClipboardSnapshot(const std::filesystem::path &request)
int runClipboardSnapshot(HANDLE mapping, HANDLE requestReady, HANDLE responseReady, HANDLE parent)
{
try
{
if (!request.is_absolute() || !request.filename().wstring().starts_with(L"ks-clipboard-") ||
request.extension() != L".request") return 1;
auto job = parse(unprotect(readFile(request, 4096)));
if (job.at("schema") != 1) return 1;
auto sequence = job.at("sequence").get<DWORD>();
const auto snapshot = request.wstring() + L".snapshot";
if (job.at("restore").get<bool>())
{
auto clip = decodeClip(unprotect(readFile(snapshot, 70 * 1024 * 1024)));
HWND window = CreateWindowExW(0, L"STATIC", L"", 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, nullptr, nullptr);
if (!window) return 1;
struct WindowCleanup { HWND window; ~WindowCleanup() { DestroyWindow(window); } } cleanup{window};
sequence = writeClipboardGuarded(window, clip, sequence);
}
else
{
auto clip = readClipboard(nullptr, 64 * 1024 * 1024, ClipboardRead::All, sequence);
if (sequence != GetClipboardSequenceNumber()) return 2;
atomicWrite(snapshot, protect(encodeClip(clip)));
}
atomicWrite(request.wstring() + L".result", protect(jsonBytes(Json{{"sequence", sequence}})));
ImageWorkerView<ClipboardSnapshotControl> view{static_cast<ClipboardSnapshotControl *>(
MapViewOfFile(mapping, FILE_MAP_WRITE, 0, 0, sizeof(ClipboardSnapshotControl)))};
if (!view.control) return 1;
const auto sequence = view.control->sequence;
const auto clip = readClipboard(nullptr, 64 * 1024 * 1024, ClipboardRead::All, sequence);
if (sequence != GetClipboardSequenceNumber() || !SetEvent(responseReady)) return 1;
// Only the clipboard sequence crosses the channel. The captured formats stay in this process.
HANDLE signals[]{parent, requestReady};
if (WaitForMultipleObjects(2, signals, FALSE, INFINITE) != WAIT_OBJECT_0 + 1) return 1;
HWND window = CreateWindowExW(0, L"STATIC", L"", 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, nullptr, nullptr);
if (!window) return 1;
struct WindowCleanup { HWND window; ~WindowCleanup() { DestroyWindow(window); } } cleanup{window};
view.control->sequence = writeClipboardGuarded(window, clip, view.control->sequence);
return 0;
}
catch (...) { return 1; }
@@ -1163,61 +1222,6 @@ void History::clear()
}
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<ImageWorkerControl *>(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<LPPROC_THREAD_ATTRIBUTE_LIST>(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<uintptr_t>(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<bool()> &cancelled)
{
std::unique_lock lock(mutex,std::defer_lock);
@@ -1234,42 +1238,42 @@ int HistoryImageWorker::perform(const std::filesystem::path &request,const std::
{
for(int attempt=0;attempt<2;++attempt)
{
if(!process.value || WaitForSingleObject(process.value,0)!=WAIT_TIMEOUT)
if(!channel.process.value || WaitForSingleObject(channel.process.value,0)!=WAIT_TIMEOUT)
{
stop();
start();
channel.stop();
channel.open();
channel.start(L"--history-image-worker");
}
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};
std::copy(path.begin(),path.end(),channel.view.control->request);
channel.view.control->request[path.size()]=L'\0';
if(!SetEvent(channel.requestReady.value)) throw std::runtime_error("Cannot request history OCR");
const auto deadline=GetTickCount64()+60000;
for(;;)
{
const auto wait=WaitForMultipleObjects(2,signals,FALSE,100);
const auto wait=channel.waitForResponse(100);
if(wait==WAIT_OBJECT_0)
{
checkCancelled();
return view.control->result;
return channel.view.control->result;
}
if(wait==WAIT_OBJECT_0+1)
{
DWORD code{};
if(GetExitCodeProcess(process.value,&code) && code==WAIT_TIMEOUT && !attempt) break;
if(GetExitCodeProcess(channel.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();
channel.stop();
}
}
catch(...)
{
// The child must stop writing before the request and response files are cleaned up.
stop();
channel.stop();
throw;
}
throw std::runtime_error("History OCR helper did not accept the request");
@@ -1278,7 +1282,7 @@ int HistoryImageWorker::perform(const std::filesystem::path &request,const std::
int runHistoryImageWorker(HANDLE mapping,HANDLE requestReady,HANDLE responseReady)
{
ImageWorkerView view{static_cast<ImageWorkerControl *>(
ImageWorkerView<ImageWorkerControl> view{static_cast<ImageWorkerControl *>(
MapViewOfFile(mapping,FILE_MAP_WRITE,0,0,sizeof(ImageWorkerControl)))};
if(!view.control) return 1;
for(;;)
+5 -6
View File
@@ -58,20 +58,19 @@ 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.
// Image backups are held in memory by a helper for the lifetime of the transaction.
class ClipboardSnapshot
{
struct Helper;
Clip clip_;
std::filesystem::path request_;
void cleanup() noexcept;
DWORD run(bool restore, DWORD sequence);
std::unique_ptr<Helper> helper_;
public:
ClipboardSnapshot() = default;
ClipboardSnapshot();
ClipboardSnapshot(const ClipboardSnapshot &) = delete;
ClipboardSnapshot &operator=(const ClipboardSnapshot &) = delete;
~ClipboardSnapshot();
void capture(HWND, DWORD sequence);
DWORD restore(HWND, DWORD sequence);
};
int runClipboardSnapshot(const std::filesystem::path &request);
int runClipboardSnapshot(HANDLE mapping, HANDLE requestReady, HANDLE responseReady, HANDLE parent);
} // namespace ks
+1 -1
View File
@@ -2,7 +2,7 @@
#include "platform.h"
namespace ks
{
inline constexpr wchar_t AppVersion[] = L"0.6.119";
inline constexpr wchar_t AppVersion[] = L"0.6.120";
inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+21 -4
View File
@@ -44,7 +44,9 @@ int main(int argc,char**argv) {
HWND w=owner(); int result=0; ks::Clip original; bool saved=false;
try {
std::string mode=argc>1?argv[1]:"suite";
if(mode=="publish") {
if(mode=="temporary") {
ks::writeClipboard(w,ks::textClip(L"temporary"));
} else if(mode=="publish") {
ks::Pixels p{1566,1068,ks::Bytes(1566*1068*4,255)}; p.bgra[0]=77;
auto dib=ks::imageDib(p); auto v5=dib;
BITMAPV5HEADER h{}; h.bV5Size=sizeof(h); h.bV5Width=p.width; h.bV5Height=-p.height;
@@ -60,9 +62,17 @@ int main(int argc,char**argv) {
auto clip=ks::readClipboard(w,64*1024*1024);
ks::writeClipboard(w,ks::textClip(L"temporary")); ks::writeClipboard(w,clip);
} else {
ks::ClipboardSnapshot snapshot; snapshot.capture(w,GetClipboardSequenceNumber());
auto seq=ks::writeClipboard(w,ks::textClip(L"temporary"));
require(snapshot.restore(w,seq)==GetClipboardSequenceNumber(),"helper returns current sequence");
ks::ClipboardSnapshot snapshot;
auto started=GetTickCount64();
snapshot.capture(w,GetClipboardSequenceNumber());
std::cout<<"Image snapshot capture: "<<GetTickCount64()-started<<" ms\n";
// A separate publisher avoids blocking clipboard notifications on this waiting test thread.
child(L"temporary");
const auto seq=GetClipboardSequenceNumber();
started=GetTickCount64();
const auto restored=snapshot.restore(w,seq);
std::cout<<"Image snapshot restore: "<<GetTickCount64()-started<<" ms\n";
require(restored==GetClipboardSequenceNumber(),"helper returns current sequence");
}
auto after=resident();
auto report="baseline="+std::to_string(baseline)+" after="+std::to_string(after)+" delta="+std::to_string(int64_t(after)-int64_t(baseline))+"\n";
@@ -78,6 +88,13 @@ int main(int argc,char**argv) {
bool rejected=false;
try {ks::readClipboard(w,32*1024*1024,ks::ClipboardRead::WithoutImages,seq);} catch(...) {rejected=true;}
require(rejected,"resident rejects images before reading their data");
{
ks::ClipboardSnapshot snapshot;
try {snapshot.capture(w,seq-1); rejected=false;} catch(...) {rejected=true;}
require(rejected,"stale image snapshot is rejected");
snapshot.capture(w,seq);
}
require(GetClipboardSequenceNumber()==seq,"discarding an image snapshot leaves the clipboard untouched");
{
ks::ClipboardSnapshot snapshot; snapshot.capture(w,seq);
auto stale=ks::writeClipboard(w,ks::textClip(L"temporary"));