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
agrynco 90c93fba8c Prepare KSwitcher v0.6.119
Run local Files commands and resolve completion paths from the active pane.
2026-11-18 13:06:48 +02:00
agrynco a09d5e72d1 Release KSwitcher v0.6.118 (#64) 2026-11-18 02:19:11 +02:00
14 changed files with 333 additions and 242 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.118 LANGUAGES CXX RC)
project(KSwitcher VERSION 0.6.120 LANGUAGES CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
+7 -2
View File
@@ -129,14 +129,19 @@ Warning і початковий фокус на No.
Enter передає порожній рядок у термінал.
Якщо фокус у виводі термінала, Enter і Shift+Enter повертають його до
командного рядка й виконують відповідну дію за тими самими правилами.
Локальна команда запускається в папці активної панелі, яку показано
перед командним рядком. Після перемикання панелі або переходу до іншої
папки наступна команда використовує нову папку навіть у вже відкритому
PowerShell. Якщо команда змінює папку (наприклад, через `cd`), панель
переходить до неї, якщо користувач за цей час не змінив її розташування.
Під час запуску термінала область виводу має темне тло, поки WebView2
готує сторінку.
Промпт і текст команди вирівняні по спільній базовій лінії.
- Під час набору локальної команди над полем з’являються підказки PowerShell.
Автодоповнення працює з відкритими й прихованими панелями (Ctrl+O).
Список уточнюється після кожної зміни тексту й доповнює команди, параметри
та шляхи відносно робочої папки термінала або активної панелі до запуску
термінала. Після `cd ` список пропонує папки,
та шляхи відносно робочої папки активної панелі.
Після `cd ` список пропонує папки,
а після вибору можна продовжити шлях через `\`, зокрема всередині лапок.
Стрілки вгору й вниз вибирають підказку. Tab вставляє вибрану або першу,
Enter вставляє виділену, а клік вставляє підказку під вказівником.
+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.
+16
View File
@@ -1,5 +1,21 @@
# 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.
**Українською.**
KSwitcher Files запускає локальні команди в папці, показаній перед командним рядком. Після перемикання панелі або переходу до іншої папки команди на кшталт `git clone` і підказки відносних шляхів використовують цю папку в тій самій сесії PowerShell.
## v0.6.118 — 2026-11-18
- **Shift+F11** opens a side-by-side comparison of two selected text files from local, LAN or FTP panes. The comparison has its own taskbar button, a movable divider, a native toolbar, **F7/F8** change navigation, and **Ctrl+wheel** text zoom. The shortcut, font and colors are configurable in **Options → File comparison**.
+1 -1
View File
@@ -1 +1 @@
b7e420509b1ed00bb5c1898fa25c3965fd49ed9d2e9bd85fddcb5149bb7166be KSwitcher-win-x64.zip
53334ba83a44c69c3acd2aad297db177366fe553fae8813b88b81e0a215c860f KSwitcher-win-x64.zip
+66 -66
View File
@@ -2,165 +2,165 @@
"files": [
{
"path": "KSwitcher.exe",
"size": 2479104,
"sha256": "d6f931814b40f1e915f4762464195919f282be0bc7d349820509d8504de3e702"
"sha256": "152b41278761439ce5ebe87bca3a4d8a96d89db82264ec0fbb2299e7c207dfb5",
"size": 2372096
},
{
"path": "KSwitcher.Config.exe",
"size": 2458112,
"sha256": "0465d7edcd069767292d2395961984973613ae1df484394c967a7d5996855668"
"sha256": "3d44721ba688a6916e393d2b9d9291e38ee063795b54cdae8e78cfd621835619",
"size": 2369536
},
{
"path": "KSwitcher.Screenshot.exe",
"size": 3060224,
"sha256": "bb11400e632aafdc7048737e0b68322f7a37e359452fce87471f70dbd5bde7ed"
"sha256": "81d9fbb770e876937310a0b483e11bd96cdb9e20b0f6baf0fa9927f24965aeeb",
"size": 3348992
},
{
"path": "KSwitcher.Files.exe",
"size": 4368896,
"sha256": "2e59662282a99b5ab42e3cef80ca554470f6d2d9f7e8e7c856d27a6ff9529b9e"
"sha256": "04c9af5324144a46a5f3cc0d8f2c6912745f8bbad7fbef0576bd52c88b5c5e03",
"size": 4370944
},
{
"path": "WebView2Loader.dll",
"size": 194912,
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
"size": 194912
},
{
"path": "terminal/addon-fit-LICENSE.txt",
"size": 1103,
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
"size": 1103
},
{
"path": "terminal/addon-fit.js",
"size": 1521,
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
"size": 1521
},
{
"path": "terminal/index.html",
"size": 527,
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
"size": 527
},
{
"path": "terminal/markdown-it-LICENSE.txt",
"size": 1073,
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473"
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
"size": 1073
},
{
"path": "terminal/markdown-it.js",
"size": 100786,
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
"size": 100786
},
{
"path": "terminal/markdown.html",
"size": 3635,
"sha256": "8268f55e8642034efa5a762cbd65d02a1d416aea9e777e0fe30a7e916ae3ee79"
"sha256": "8268f55e8642034efa5a762cbd65d02a1d416aea9e777e0fe30a7e916ae3ee79",
"size": 3635
},
{
"path": "terminal/markdown.js",
"size": 16944,
"sha256": "4c68dff619cf248f6bd32b09a45458675c22341892dc377204e46c2f4fd562f8"
"sha256": "4c68dff619cf248f6bd32b09a45458675c22341892dc377204e46c2f4fd562f8",
"size": 16944
},
{
"path": "terminal/mermaid-LICENSE.txt",
"size": 1089,
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80"
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
"size": 1089
},
{
"path": "terminal/mermaid.js",
"size": 5537838,
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3"
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
"size": 5537838
},
{
"path": "terminal/terminal.js",
"size": 5065,
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b"
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b",
"size": 5065
},
{
"path": "terminal/xterm-LICENSE.txt",
"size": 1261,
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
"size": 1261
},
{
"path": "terminal/xterm.css",
"size": 7112,
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
"size": 7112
},
{
"path": "terminal/xterm.js",
"size": 488663,
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
"size": 488663
},
{
"path": "LICENSE",
"size": 4401,
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
"size": 4401
},
{
"path": "json-LICENSE.txt",
"size": 1096,
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831"
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
"size": 1096
},
{
"path": "files-text-license.txt",
"size": 883,
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
"size": 883
},
{
"path": "README.md",
"size": 95317,
"sha256": "ea5016c6fa29a98bf9ebf103fcf27f1be091842ad3228b167d18b053fda767d8"
"sha256": "afc7e78c4c3600888f642692423cd993b4aa431dfa54f752c7ac394de18186c6",
"size": 95354
},
{
"path": "LAN-PREVIEW.md",
"size": 11577,
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930"
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930",
"size": 11577
},
{
"path": "dictionaries/en.txt",
"size": 732485,
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9"
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
"size": 732485
},
{
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"size": 20566,
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5"
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
"size": 20566
},
{
"path": "dictionaries/README.md",
"size": 2265,
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
"size": 2265
},
{
"path": "dictionaries/ru.txt",
"size": 1109134,
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849"
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
"size": 1109134
},
{
"path": "dictionaries/sources.json",
"size": 1280,
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
"size": 1280
},
{
"path": "dictionaries/uk.txt",
"size": 940799,
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
"size": 940799
},
{
"path": "tools/README.txt",
"size": 993,
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
"size": 993
},
{
"path": "tools/StayHere.exe",
"size": 540583,
"sha256": "bb595202cc4749f3c0fe47adc92d4b02a174abeb5765e493673de9f5e070251c"
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376",
"size": 134656
},
{
"path": "tools/StayHere-README.md",
"size": 2796,
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
"size": 2796
}
],
"version": "0.6.118",
"schema": 1
"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,118,0
PRODUCTVERSION 0,6,118,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.118"
VALUE "FileVersion", "0.6.120"
END
END
BLOCK "VarFileInfo"
+34 -15
View File
@@ -441,7 +441,12 @@ HWND terminalInput{},terminalOutput{},terminalPrompt{};
constexpr UINT_PTR terminalTimer=2;
constexpr UINT_PTR directoryWatchTimer=4;
bool terminalVisible{};
std::deque<int> terminalCommandPanels;
struct TerminalCommandContext
{
int panel=-1;
fs::path directory;
};
std::deque<TerminalCommandContext> terminalCommands;
std::wstring terminalDirectory;
int terminalRows{};
struct CommandEntry { std::wstring date, command; };
@@ -1061,8 +1066,8 @@ void swapPanels(HWND window)
// Move the controls with their contents to retain the cursor and scroll position.
std::swap(panels[0],panels[1]);
active=1-active;
for(auto &panel:terminalCommandPanels)
if(panel>=0) panel=1-panel;
for(auto &command:terminalCommands)
if(command.panel>=0) command.panel=1-command.panel;
for(int i=0;i<2;++i)
{
const auto &panel=panels[i];
@@ -1346,7 +1351,7 @@ std::optional<CompletionQuery> currentCompletionQuery()
if(!first || first!=last) return {};
std::wstring directory;
if(!panels[active].peer && !panels[active].ftp)
directory=terminal.alive() && !terminalDirectory.empty()?terminalDirectory:panels[active].directory.native();
directory=panels[active].directory.native();
return CompletionQuery{std::move(line),std::move(directory),first};
}
@@ -1674,14 +1679,19 @@ bool ensureTerminalView(HWND owner)
else if(message.starts_with(L"directory:"))
{
const auto directory=message.substr(10);
if(!terminalCommandPanels.empty())
if(!terminalCommands.empty())
{
const int panel=terminalCommandPanels.front();
terminalCommandPanels.pop_front();
std::error_code error;
if(panel>=0 && !panels[panel].peer && directory!=terminalDirectory &&
!directory.empty() && fs::is_directory(directory,error))
open(panels[panel],directory,false);
const auto command=std::move(terminalCommands.front());
terminalCommands.pop_front();
if(command.panel>=0 && !directory.empty() && directory!=command.directory.native())
{
auto &panel=panels[command.panel];
std::error_code error;
if(!panel.peer && !panel.ftp && panel.directory==command.directory &&
(!panel.scanRequest || panel.scanRequest->directory==command.directory) &&
fs::is_directory(directory,error))
open(panel,directory,false);
}
}
terminalDirectory=directory;
}
@@ -1733,8 +1743,8 @@ bool startTerminal(HWND owner,const fs::path &directory)
if(!ensureTerminalView(owner)) return false;
if(terminal.start(directory.c_str(),terminalSize))
{
terminalCommandPanels={-1};
terminalDirectory.clear();
terminalCommands={{}};
terminalDirectory=directory.native();
return true;
}
setStatus(L"Could not start PowerShell.");
@@ -1835,12 +1845,21 @@ bool submitTerminalCommand(const Panel &panel,const std::wstring &value)
return true;
}
if(!startTerminal(owner,panel.directory)) return false;
if(!terminal.write(value+L"\r"))
// Use the directory displayed by the panel at submission time. A queued
// command may change location before PowerShell gets to this input.
const bool hasCommand=value.find_first_not_of(L" \t\r\n")!=value.npos;
std::wstring input;
if(hasCommand && (terminalDirectory!=panel.directory.native() ||
std::any_of(terminalCommands.begin(),terminalCommands.end(),
[](const auto &command){ return command.panel>=0; })))
input=L"try { Microsoft.PowerShell.Management\\Set-Location -LiteralPath "+
powerShellPath(panel.directory)+L" -ErrorAction Stop } catch { Write-Error $_; return }; ";
if(!terminal.write(input+value+L"\r"))
{
setStatus(L"Could not send PowerShell input.");
return false;
}
terminalCommandPanels.push_back(static_cast<int>(&panel-panels));
terminalCommands.push_back({hasCommand?static_cast<int>(&panel-panels):-1,panel.directory});
return true;
}
+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.118";
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"));
+32 -1
View File
@@ -460,6 +460,34 @@ function startTerminalFixture() {
([IO.File]::ReadAllLines($listing) -ccontains 'zzzz-dir-second')
}
Write-Output 'Verified repeated dir commands in the same terminal with file panes hidden and visible.'
$rightChild = Join-Path $rightDir "Command's [folder]"
[void][IO.Directory]::CreateDirectory($rightChild)
$childRow = "[$([IO.Path]::GetFileName($rightChild))]"
Wait-Until 'new folder in the right panel' { (Find-Row $right $childRow) -ge 0 }
$keys.SendKeys('{TAB}')
Send-InteractiveTerminal 'cmd /d /c "cd > panel-cwd.txt"'
Wait-Until 'native command running in the newly active right panel' {
(Test-Path -LiteralPath (Join-Path $rightDir 'panel-cwd.txt')) -and
(Find-Row $right 'panel-cwd.txt') -ge 0
}
[void][FilesActivationUi]::Send($right, 0x186, [IntPtr](Find-Row $right $childRow), [IntPtr]::Zero)
Press-Enter $inputBox
$rightPath = [FilesActivationUi]::GetDlgItem($window, 143)
Wait-Until 'navigation to the right panel subfolder' { (Read-Text $rightPath) -ceq $rightChild }
Send-InteractiveTerminal 'cmd /d /c "cd > child-cwd.txt"'
Wait-Until 'native command running in the navigated folder' {
(Test-Path -LiteralPath (Join-Path $rightChild 'child-cwd.txt')) -and
(Find-Row $right 'child-cwd.txt') -ge 0
}
Send-InteractiveTerminal 'cd ..'
Wait-Until 'PowerShell cd navigating the right panel' { (Find-Row $right 'panel-cwd.txt') -ge 0 }
$keys.SendKeys('{TAB}')
Send-InteractiveTerminal 'cmd /d /c "cd > left-cwd.txt"'
Wait-Until 'native command running back in the left panel' {
(Test-Path -LiteralPath (Join-Path $leftDir 'left-cwd.txt')) -and
(Find-Row $left 'left-cwd.txt') -ge 0
}
Write-Output 'Verified native commands follow panel switches and folder navigation in the same PowerShell session.'
$marker=Join-Path $root 'webview-enter.txt'
$command="[IO.File]::AppendAllText('$($marker.Replace("'","''"))','executed')"
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$command)
@@ -470,7 +498,10 @@ function startTerminalFixture() {
!(Read-Text $inputBox)
}
Write-Output 'Verified Enter from the terminal WebView runs the command exactly once.'
Select-Row $left '[Test folder]'
# The left panel is already active after the working-directory check.
$folderRow = Find-Row $left '[Test folder]'
if ($folderRow -lt 0) { throw 'Missing folder for the terminal clipboard check.' }
[void][FilesActivationUi]::Send($left, 0x186, [IntPtr]$folderRow, [IntPtr]::Zero)
$outputSelection = 'terminal-output-copy-fixture'
Send-InteractiveTerminal "Write-Output '$outputSelection'"
Wait-Until 'output selection fixture command submitted' { !(Read-Text $inputBox) }