Compare commits

..
Author SHA1 Message Date
agrynco 367a5fd9f7 Release KSwitcher v0.6.121 (#67)
Ship the Files Markdown startup retry and apply word-boundary checks to all snippet triggers.
2026-11-20 16:40:10 +02:00
agrynco 4095c889c1 Release KSwitcher v0.6.120 (#66) 2026-11-20 00:42:13 +02:00
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
23 changed files with 551 additions and 238 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.121 LANGUAGES CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
+11 -4
View File
@@ -129,14 +129,19 @@ Warning і початковий фокус на No.
Enter передає порожній рядок у термінал.
Якщо фокус у виводі термінала, Enter і Shift+Enter повертають його до
командного рядка й виконують відповідну дію за тими самими правилами.
Локальна команда запускається в папці активної панелі, яку показано
перед командним рядком. Після перемикання панелі або переходу до іншої
папки наступна команда використовує нову папку навіть у вже відкритому
PowerShell. Якщо команда змінює папку (наприклад, через `cd`), панель
переходить до неї, якщо користувач за цей час не змінив її розташування.
Під час запуску термінала область виводу має темне тло, поки WebView2
готує сторінку.
Промпт і текст команди вирівняні по спільній базовій лінії.
- Під час набору локальної команди над полем з’являються підказки PowerShell.
Автодоповнення працює з відкритими й прихованими панелями (Ctrl+O).
Список уточнюється після кожної зміни тексту й доповнює команди, параметри
та шляхи відносно робочої папки термінала або активної панелі до запуску
термінала. Після `cd ` список пропонує папки,
та шляхи відносно робочої папки активної панелі.
Після `cd ` список пропонує папки,
а після вибору можна продовжити шлях через `\`, зокрема всередині лапок.
Стрілки вгору й вниз вибирають підказку. Tab вставляє вибрану або першу,
Enter вставляє виділену, а клік вставляє підказку під вказівником.
@@ -326,8 +331,10 @@ Warning і початковий фокус на No.
перерендерюється зі збереженням позиції прокрутки.
Вебпосилання HTTP і HTTPS відкриваються в системному браузері.
Для LAN зображення завантажуються у фоні, а файли за посиланнями — після
кліку. Mermaid працює офлайн. Якщо WebView2 недоступний або файл більший за
8 МіБ, F3 відкриває текстовий перегляд.
кліку. Mermaid працює офлайн і завантажується лише для документів із
діаграмами Mermaid. Якщо WebView2 не завершує запуск, Files один раз
повторює спробу в тому самому вікні. Якщо форматований перегляд недоступний
або файл більший за 8 МіБ, F3 відкриває текстовий перегляд.
- F3 у фоні підраховує сумарний розмір файлів у папці та її підпапках.
На рядку `..` F3 рахує всі папки поточного списку, а за наявності
позначених папок в інших рядках рахує позначені папки. Без позначок
+7 -5
View File
@@ -473,14 +473,16 @@ expand the snippet.
Type `;` at the start of a trigger to open suggestions near the caret, or
type the first three characters of another trigger. The list filters as you
type and fits the widest matching trigger. Use **↑ / ↓** and **Tab** or click
an entry. **Esc** dismisses the list. Full triggers still expand
automatically. See the [snippet guide](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Snippets).
an entry. **Esc** dismisses the list. Full triggers expand automatically at the
start of a word, including when typed in another keyboard layout. See the
[snippet guide](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Snippets).
**Українською.** Введіть `;` на початку тригера або три перші символи іншого
тригера, щоб відкрити підказки біля курсора. Список фільтрується під час набору
й підлаштовує ширину під найдовший збіг. Для вибору натисніть **↑ / ↓** і
**Tab** або клацніть рядок. **Esc** закриває список. Повні тригери й далі
спрацьовують автоматично. Дивіться [посібник зі сніпетів](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Snippets-uk).
**Tab** або клацніть рядок. **Esc** закриває список. Повні тригери спрацьовують
автоматично на межі перед словом, зокрема під час набору в іншій розкладці.
Дивіться [посібник зі сніпетів](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Snippets-uk).
З v0.6.70 підказки відкриваються біля текстового курсора. Якщо редактор не
надає його позицію, введіть повний тригер для розгортання сніпета.
@@ -1027,7 +1029,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.
+29 -1
View File
@@ -1,5 +1,33 @@
# Latest Windows release
## v0.6.121 — 2026-11-20
KSwitcher Files retries WebView2 startup once when a Markdown preview fails to initialize. If the retry succeeds, the same window displays the formatted document. The Markdown viewer loads the bundled Mermaid library only for documents with Mermaid diagrams.
Snippet expansion now requires a word boundary before the trigger, even after a pause. The same rule applies across keyboard layouts and in Far Manager.
**Українською.**
Якщо перегляд Markdown не запускається, KSwitcher Files один раз повторює запуск WebView2. Після успішної спроби форматований документ з’являється в тому самому вікні. Бібліотека Mermaid завантажується лише для документів із діаграмами Mermaid.
KSwitcher розгортає сніпети, коли тригер відокремлено від попереднього слова. Перевірка діє після паузи, у різних розкладках і у Far Manager.
## 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**.
@@ -526,6 +554,6 @@ Use **Test mouse buttons here** to check which events Windows delivers. Mouse pr
Choose **Update** in the tray menu. For v0.3.x–v0.4.1, install the [v0.4.2 bridge](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/releases/tag/v0.4.2) manually first. Close KSwitcher and its editors, extract the bridge ZIP into the installation folder while keeping personal data, dictionaries, and tools, then start v0.4.2 and choose **Update**. v0.2.3 and earlier require manual installation.
For a manual upgrade, exit KSwitcher and its configurator and screenshot editors, then extract the entire **KSwitcher-win-x64.zip** into its installation folder. Verify it with **SHA256SUMS.txt**. Keep personal data, customized dictionaries and tools. Keep the three KSwitcher executables together.
For a manual upgrade, save your work and exit KSwitcher, Settings, Files, screenshot editors and bundled StayHere. Verify **KSwitcher-win-x64.zip** with **SHA256SUMS.txt**, then extract the entire ZIP into the installation folder. Keep personal data, customized dictionaries and tools.
See the [English Wiki](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Home) or [Українська Wiki](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Home-uk).
+1 -1
View File
@@ -1 +1 @@
b7e420509b1ed00bb5c1898fa25c3965fd49ed9d2e9bd85fddcb5149bb7166be KSwitcher-win-x64.zip
c7163b614f4e92e25137a3f89e750878fc9a3e559037e7a8933468b8b83d829d KSwitcher-win-x64.zip
+19 -19
View File
@@ -1,24 +1,26 @@
{
"version": "0.6.121",
"schema": 1,
"files": [
{
"path": "KSwitcher.exe",
"size": 2479104,
"sha256": "d6f931814b40f1e915f4762464195919f282be0bc7d349820509d8504de3e702"
"size": 2479616,
"sha256": "fbdb81083b17c15d784f6772fea286d78a7e7b48ae16ca0216734631ba374fa7"
},
{
"path": "KSwitcher.Config.exe",
"size": 2458112,
"sha256": "0465d7edcd069767292d2395961984973613ae1df484394c967a7d5996855668"
"size": 2457088,
"sha256": "d55ba3ffead5ef585d41e705388eb8f9282e74b8a3c603d0eaf37576e2072b6d"
},
{
"path": "KSwitcher.Screenshot.exe",
"size": 3060224,
"sha256": "bb11400e632aafdc7048737e0b68322f7a37e359452fce87471f70dbd5bde7ed"
"size": 3059200,
"sha256": "207f9cb7bd26c3eb1a2e71719aac0d503514af1754d18659934610a80f02a8da"
},
{
"path": "KSwitcher.Files.exe",
"size": 4368896,
"sha256": "2e59662282a99b5ab42e3cef80ca554470f6d2d9f7e8e7c856d27a6ff9529b9e"
"size": 4370944,
"sha256": "54030d33097766cb9665ec0f5ab0967642d1bcdf3b9e151948ae5d85781dd1fe"
},
{
"path": "WebView2Loader.dll",
@@ -52,13 +54,13 @@
},
{
"path": "terminal/markdown.html",
"size": 3635,
"sha256": "8268f55e8642034efa5a762cbd65d02a1d416aea9e777e0fe30a7e916ae3ee79"
"size": 3599,
"sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094"
},
{
"path": "terminal/markdown.js",
"size": 16944,
"sha256": "4c68dff619cf248f6bd32b09a45458675c22341892dc377204e46c2f4fd562f8"
"size": 17575,
"sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8"
},
{
"path": "terminal/mermaid-LICENSE.txt",
@@ -107,8 +109,8 @@
},
{
"path": "README.md",
"size": 95317,
"sha256": "ea5016c6fa29a98bf9ebf103fcf27f1be091842ad3228b167d18b053fda767d8"
"size": 95524,
"sha256": "23d203a1fe73d1adc5e51d088420848cfabf03929401b78c4dbb249d0b5bdbf6"
},
{
"path": "LAN-PREVIEW.md",
@@ -152,15 +154,13 @@
},
{
"path": "tools/StayHere.exe",
"size": 540583,
"sha256": "bb595202cc4749f3c0fe47adc92d4b02a174abeb5765e493673de9f5e070251c"
"size": 133120,
"sha256": "e23960ff3328f38c050528091ba78b822f0fa74e3396e1a349150e2947598d96"
},
{
"path": "tools/StayHere-README.md",
"size": 2796,
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
}
],
"version": "0.6.118",
"schema": 1
]
}
+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,121,0
PRODUCTVERSION 0,6,121,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.121"
END
END
BLOCK "VarFileInfo"
-1
View File
@@ -52,6 +52,5 @@ figure svg .edgeLabel rect { fill: Canvas !important; opacity: 1 !important; str
</nav>
<main></main>
<script src="markdown-it.js"></script>
<script src="mermaid.js"></script>
<script src="markdown.js"></script>
</html>
+24 -8
View File
@@ -18,14 +18,28 @@ let activeMatch = -1;
let taskMarkers = new WeakMap();
let pendingTask;
let previewRevision = 0;
let mermaidReady;
mermaid.initialize({
startOnLoad: false,
securityLevel: 'strict',
theme: matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default',
suppressErrorRendering: true,
flowchart: { htmlLabels: false }
});
function loadMermaid() {
mermaidReady ??= new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = 'mermaid.js';
script.onload = resolve;
script.onerror = () => reject(new Error('Could not load Mermaid'));
document.head.append(script);
}).then(() => {
const renderer = window.mermaid;
renderer.initialize({
startOnLoad: false,
securityLevel: 'strict',
theme: matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default',
suppressErrorRendering: true,
flowchart: { htmlLabels: false }
});
return renderer;
});
return mermaidReady;
}
markdown.core.ruler.after('inline', 'task_lists', ({ tokens, src, env }) => {
const lines = src.split('\n');
@@ -254,7 +268,9 @@ async function render({ text, fragment, scroll, title, keepPosition, revision, c
const blocks = Array.from(content.querySelectorAll('pre > code.language-mermaid'));
for (const [index, block] of blocks.entries()) {
try {
const { svg } = await mermaid.render('diagram-' + current + '-' + index, block.textContent);
const renderer = await loadMermaid();
if (current !== generation) return;
const { svg } = await renderer.render('diagram-' + current + '-' + index, block.textContent);
if (current !== generation) return;
const figure = document.createElement('figure');
figure.innerHTML = svg;
+57 -5
View File
@@ -200,6 +200,14 @@ std::vector<std::wstring> buildSnippetVariants(const std::wstring &trigger, cons
}
return variants;
}
bool snippetWordCharacter(wchar_t character)
{
WORD type{};
if (character == L'_' ||
(GetStringTypeW(CT_CTYPE1, &character, 1, &type) && (type & (C1_ALPHA | C1_DIGIT))))
return true;
return GetStringTypeW(CT_CTYPE3, &character, 1, &type) && (type & (C3_NONSPACING | C3_VOWELMARK));
}
size_t caretSteps(std::wstring text)
{
size_t n = 0;
@@ -535,12 +543,16 @@ class Transaction
farSelectedSteps = 0;
return valid() && chord(VK_LEFT);
}
while (farSelectedSteps && valid())
return narrowFarSelection(0);
}
bool narrowFarSelection(size_t count)
{
while (farSelectedSteps > count && valid())
{
if (!chord(VK_RIGHT, MOD_ALT | MOD_SHIFT)) return false;
--farSelectedSteps;
}
return !farSelectedSteps && valid();
return farSelectedSteps == count && valid();
}
std::optional<std::wstring> readFarSnippet(size_t count)
{
@@ -549,6 +561,21 @@ class Transaction
if (!finishSelection(false) || observed.empty()) return {};
return observed;
}
std::optional<bool> farSnippetWordBoundary(std::wstring_view trigger)
{
// Select to the beginning of Far's input line in one operation, then
// use the copied prefix to find the preceding character and restore the range.
if (!valid() || !chord(VK_HOME, MOD_ALT | MOD_SHIFT)) return {};
const auto context = copy();
if (!valid() || !context.ends_with(trigger)) return {};
if (context == trigger) return true;
const auto triggerSteps = farSelectedSteps;
farSelectedSteps = caretSteps(context);
if (snippetWordCharacter(context[context.size() - trigger.size() - 1]))
return false;
if (!narrowFarSelection(triggerSteps) || copy() != trigger || !valid()) return {};
return true;
}
std::wstring copyRange(size_t count, const std::wstring &wordCandidate,
const std::function<bool(const std::wstring &)> &matches,
const std::function<bool(const std::wstring &)> &suffixMatches = {})
@@ -1231,7 +1258,16 @@ void App::matchSnippets(HWND fg, bool expandExact)
trigger = sn.trigger;
}
if (expandExact && std::any_of(variants.begin(), variants.end(), [&](const auto &trigger) {
return keys.ends_with(trigger);
if (!keys.ends_with(trigger)) return false;
// A fresh key run can start inside existing text. The editor
// verifies the boundary before expansion even when this check passes.
if (keys.size() == trigger.size()) return true;
const auto layout = std::find_if(layouts.begin(), layouts.end(), [&](const auto &candidate) {
return candidate.handle == run.layout && candidate.convertible;
});
const auto previous = keys[keys.size() - trigger.size() - 1];
return layout == layouts.end() ||
!snippetWordCharacter(layout->at(physicalLayout().code(previous)));
}))
{
queueSnippet(fg, i, sn.trigger.size());
@@ -2207,6 +2243,7 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
{"command", transformCommandName(command)}, {"source", layout(text.empty() ? hint : detect(text, layouts, hint))}, {"target", layout(to)},
{"outcome", utf8(reason)}, {"verification", utf8(verification)},
{"problem", reason != L"Paste verified" && reason != L"layout-only" &&
reason != L"snippet-inside-word" &&
!(command == 0 && reason == L"paste-sent-unverified")},
{"elapsedMs", GetTickCount64() - start}, {"verificationMs", verificationMs},
{"foregroundSame", GetForegroundWindow() == target},
@@ -2489,11 +2526,13 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
}
bool sent = false;
const bool requireReadback = tx.recoveredSelection() || snippet >= 0;
const bool verifySelection = snippet >= 0 || (requireReadback && result != text);
auto probeStarted = GetTickCount64();
PasteProbe probe(!farSnippet && ((config.writeLog && manual) || requireReadback) && result != text, text, target);
PasteProbe probe(!farSnippet && (verifySelection || (config.writeLog && manual && result != text)),
text, target, snippet >= 0);
verificationMs = GetTickCount64() - probeStarted;
diagnosticEvent(L"Paste probe prepared: elapsedMs=" + std::to_wstring(verificationMs) + L" status=" + probe.status);
if (requireReadback && !farSnippet && result != text && probe.status != L"ready")
if (!farSnippet && verifySelection && probe.status != L"ready")
{
verification = probe.status;
reason = snippet >= 0 ? L"snippet-verification-unavailable" : L"recovered-selection-unavailable";
@@ -2502,6 +2541,19 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
run.reset();
return;
}
if (snippet >= 0)
{
std::optional<bool> boundary;
if (farSnippet)
boundary = tx.farSnippetWordBoundary(text);
else if (const auto &preceding = probe.precedingCharacter)
boundary = preceding->empty() || !snippetWordCharacter(preceding->back());
if (!boundary.value_or(false))
{
reason = boundary ? L"snippet-inside-word" : L"snippet-word-boundary-unavailable";
return;
}
}
diagnosticEvent(L"Conversion source=" + std::to_wstring(hint) + L" target=" + std::to_wstring(to) +
L" changed=" + std::to_wstring(result != text));
if (result != text)
+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;
}
+20 -7
View File
@@ -806,7 +806,7 @@ private:
bool uploadPending{};
bool switchAfterSave{};
FilesTerminalView preview;
bool previewWanted{}, previewVisible{};
bool previewWanted{}, previewVisible{}, previewRetried{};
ULONGLONG previewDeadline{};
ULONGLONG nextFileCheck{};
struct FileStamp
@@ -918,6 +918,7 @@ private:
bool needsSave() const;
bool canPreview() const;
void updatePreview();
bool startPreviewBrowser();
void stopPreview(bool refresh=true,bool keepBrowser=false);
void renderPreview(bool keepPosition=false);
void applyMarkdownPreferences(const MarkdownPreferences &preferences);
@@ -1598,14 +1599,21 @@ void TextWindow::updatePreview()
return;
}
previewWanted=true;
previewDeadline=GetTickCount64()+8000;
previewRetried=false;
previewStamp=previewFileStamp();
nextFileCheck=GetTickCount64()+350;
cancelImages=std::make_shared<std::atomic<bool>>(false);
if(!SetTimer(window,previewTimer,50,nullptr)) { stopPreview(); return; }
if(preview.initialized()) renderPreview();
else if(!preview.create(window,[this](const auto &value){previewMessage(value);},
[this]{PostMessageW(window,previewFailed,0,0);},true,[this](UINT key)
else if(!startPreviewBrowser()) { stopPreview(); return; }
layout();
}
bool TextWindow::startPreviewBrowser()
{
previewDeadline=GetTickCount64()+8000;
return preview.create(window,[this](const auto &value){previewMessage(value);},
[this]{previewDeadline=GetTickCount64()+300;},true,[this](UINT key)
{
const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0;
const bool alt=(GetKeyState(VK_MENU)&0x8000)!=0;
@@ -1628,9 +1636,7 @@ void TextWindow::updatePreview()
if(key!=VK_F6 && key!=VK_ESCAPE && key!=VK_F10 && !(ctrl && key=='W')) return false;
PostMessageW(window,WM_COMMAND,key==VK_F6?switchMode:key==VK_ESCAPE?previewEscape:close,0);
return true;
}))
stopPreview();
layout();
});
}
void TextWindow::stopPreview(bool refresh,bool keepBrowser)
@@ -2027,6 +2033,13 @@ void TextWindow::pollImages()
refreshPreview();
if(!previewVisible && GetTickCount64()>=previewDeadline)
{
if(!preview.initialized() && !previewRetried)
{
// The previous window's WebView2 process may still be shutting down.
previewRetried=true;
preview.close();
if(startPreviewBrowser()) return;
}
stopPreview();
return;
}
+29 -11
View File
@@ -11,8 +11,19 @@ class PasteProbe
IUIAutomationElement *element{};
IUIAutomationTextPattern *pattern{};
static std::optional<std::wstring> rangeText(IUIAutomationTextRange *range)
{
BSTR value{};
const HRESULT hr = range->GetText(8193, &value);
std::wstring text(value ? value : L"", SysStringLen(value));
SysFreeString(value);
if (FAILED(hr)) return {};
return text;
}
public:
std::wstring status = L"not-requested";
std::optional<std::wstring> precedingCharacter;
PasteProbe(bool enabled, HWND target)
{
if (!enabled)
@@ -48,11 +59,11 @@ class PasteProbe
!pattern)
return;
}
PasteProbe(bool enabled, const std::wstring &original, HWND target = nullptr)
PasteProbe(bool enabled, const std::wstring &original, HWND target = nullptr, bool readPreceding = false)
: PasteProbe(enabled, target)
{
if (!pattern) return;
auto selected = read(1, false);
auto selected = read(1, false, readPreceding);
auto normalize = [](std::wstring value)
{
for (size_t at = 0; (at = value.find(L"\r\n", at)) != value.npos;)
@@ -80,7 +91,7 @@ class PasteProbe
if (automation)
automation->Release();
}
std::optional<std::wstring> read(int characters, bool allowCaret = true)
std::optional<std::wstring> read(int characters, bool allowCaret = true, bool readPreceding = false)
{
if (!pattern)
return {};
@@ -162,19 +173,26 @@ class PasteProbe
if (SUCCEEDED(hr) && moved != -characters)
hr = E_FAIL;
}
BSTR value{};
if (SUCCEEDED(hr))
hr = range->GetText(8193, &value);
auto text = SUCCEEDED(hr) ? rangeText(range) : std::nullopt;
if (readPreceding && text &&
SUCCEEDED(range->MoveEndpointByRange(TextPatternRangeEndpoint_End, range, TextPatternRangeEndpoint_Start)))
{
int moved{};
if (SUCCEEDED(range->MoveEndpointByUnit(TextPatternRangeEndpoint_Start, TextUnit_Character, -1, &moved)))
{
if (moved == 0)
precedingCharacter.emplace();
else if (auto previous = rangeText(range); previous && !previous->empty())
precedingCharacter = std::move(previous);
}
}
range->Release();
if (FAILED(hr))
if (!text)
{
SysFreeString(value);
status = L"range-read-failed";
return {};
}
std::wstring text(value ? value : L"", SysStringLen(value));
SysFreeString(value);
if (text.size() > 8192)
if (text->size() > 8192)
{
status = L"readback-size-limit";
return {};
+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.121";
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"));
+9 -2
View File
@@ -84,9 +84,11 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int) {
{
ks::App app(instance,false,folder/L"data");app.window=owner;
app.settings.history=false;app.settings.autoCorrect=false;app.settings.writeLog=true;
auto prepare=[&](wchar_t last=L'r') {
auto prepare=[&](wchar_t last=L'r', wchar_t prefix=0) {
if(!ks::activateWindow(target))throw std::runtime_error("isolated Far lost foreground");
key(VK_ESCAPE);key('Y',0,LEFT_CTRL_PRESSED);key(VK_OEM_1,L':',SHIFT_PRESSED);key(WORD(towupper(last)),last);
key(VK_ESCAPE);key('Y',0,LEFT_CTRL_PRESSED);
if(prefix)key(prefix==L' '?VK_SPACE:WORD(towupper(prefix)),prefix);
key(VK_OEM_1,L':',SHIFT_PRESSED);key(WORD(towupper(last)),last);
app.run.reset();app.run.window=target;app.run.layout=ks::windowLayout(target);
app.run.at=GetTickCount64();app.run.keys=L":r";
};
@@ -103,6 +105,11 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int) {
require(ks::readClipboard(owner).text()==sentinel.text(),"snippet restores original clipboard");
prepare(L'x');before=position();original=row();expand(L"rider .{enter}");
require(row()==original && position().X==before.X,"mismatched trigger restores original caret and never executes Enter");
prepare(L'r',L'x');before=position();original=row();expand(L"rider .");
require(row()==original && position().X==before.X,"trigger inside a word restores original caret");
prepare(L'r',L' ');before=position();expand(L"rider .");
require(row().substr(before.X-3,8)==L" rider ." && position().X==before.X+5,
"trigger after a space preserves the separator");
prepare();before=position();original=row();expand(L"left{cursor}right");
require(row().substr(before.X-2,9)==L"leftright" && position().X==before.X+2,"cursor marker uses Far selection semantics");
prepare();before=position();original=row();expand(L"first\nsecond{enter}");
+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) }
+38
View File
@@ -117,6 +117,18 @@ function Scintilla($Window) {
[MarkdownUi]::FindWindowEx($Window,0,'Scintilla',[NullString]::Value)
}
function Assert-ReopenedMarkdown($Window, $File) {
try { Browser 'reopen' '' $File }
finally {
if ([MarkdownUi]::IsWindowVisible((Scintilla $Window))) { throw "$File opened as raw text." }
}
}
function Close-Preview($Window) {
Post $Window 0x10 0
[void](Wait-For 'the Markdown preview to close' { ![MarkdownUi]::IsWindowVisible($Window) })
}
function Assert-TextWindowAppearance($Window, [string]$Mode) {
$identity = "HrynCo.KSwitcher.Files.$Mode"
$resource = if($Mode -eq 'Editor') { ',-104' } else { ',-103' }
@@ -204,6 +216,8 @@ const value = 42;
'@
$original = Join-Path $docs 'Preview.md'
[IO.File]::WriteAllText($original,$fixture)
[IO.File]::WriteAllText("$docs\Reopen.md",'# Reopened Markdown')
[IO.File]::WriteAllText("$docs\Second.md",'# Second Markdown')
$childText = '# Linked Markdown' + "`n`n" + (("Filler paragraph.`n`n") * 60) + '## Target heading'
[IO.File]::WriteAllText("$docs\child\Other.md",$childText)
[IO.File]::WriteAllText("$docs\Plain.txt",'Plain text')
@@ -235,6 +249,30 @@ const value = 42;
[MarkdownUi]::Activate($main)
$panel = [MarkdownUi]::GetDlgItem($main,102)
$previewScript = Join-Path $app 'terminal\markdown.js'
$originalScript = [IO.File]::ReadAllText($previewScript)
try {
# Let the page load without sending the ready message until Files starts a new WebView.
[IO.File]::WriteAllText($previewScript,"document.documentElement.dataset.startup = 'stalled';")
Open-File 'Reopen.md' 0x72
$window = Wait-For 'the stalled Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Reopen.md' }
Browser 'startup-stalled'
} finally { [IO.File]::WriteAllText($previewScript,$originalScript) }
Assert-ReopenedMarkdown $window 'Reopen.md'
Close-Preview $window
Write-Output 'Verified that the same viewer renders Markdown after a stalled WebView2 startup.'
Open-File 'Reopen.md' 0x72
$window = Wait-For 'the Markdown viewer before early close' { Find-Window 'KSwitcher.Files.Text' 'Reopen.md' }
Close-Preview $window
foreach ($file in 'Reopen.md','Second.md','Reopen.md','Second.md','Reopen.md','Second.md') {
Open-File $file 0x72
$window = Wait-For "the reopened $file viewer" { Find-Window 'KSwitcher.Files.Text' $file }
Assert-ReopenedMarkdown $window $file
Close-Preview $window
}
Write-Output 'Verified six immediate Markdown reopens after closing the initial preview during startup.'
Open-File 'Preview.md' 0x72
$window = Wait-For 'the Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Viewer' }
$viewerIcons = Assert-TextWindowAppearance $window 'Viewer'
+11 -2
View File
@@ -139,9 +139,18 @@ try {
clip: { x:0, y:0, width:cssContentSize.width, height:Math.min(cssContentSize.height, 620), scale:1 } });
await writeFile(artifact, Buffer.from(data, 'base64'));
}
} else if (scenario === 'startup-stalled') {
await waitFor(() => evaluate(`document.documentElement?.dataset.startup === 'stalled'`),
'the preview page to load without announcing readiness');
} else if (scenario === 'reopen') {
const heading = title === 'Reopen.md' ? 'Reopened Markdown' : 'Second Markdown';
await waitFor(() => evaluate(`document.documentElement?.classList.contains('rendered') &&
document.querySelector('h1')?.textContent === ${JSON.stringify(heading)}`), heading);
assert.equal(await evaluate(`performance.getEntriesByName(new URL('mermaid.js', location.href).href).length`),
0, 'Reopening a document without diagrams must not load Mermaid');
} else if (scenario === 'external-replacement') {
await waitFor(() => evaluate(`document.documentElement.classList.contains('rendered') &&
document.querySelector('main').textContent.trim() === 'An external replacement'`),
await waitFor(() => evaluate(`document.documentElement?.classList.contains('rendered') &&
document.querySelector('main')?.textContent.trim() === 'An external replacement'`),
'the replacement file rendered after discarding edits');
} else if (scenario === 'diagram-reference') {
await waitFor(() => evaluate("document.documentElement.classList.contains('rendered')"), 'rendered diagram page');
+54
View File
@@ -42,6 +42,10 @@ struct InputRegressionAccess
++*reinterpret_cast<int *>(context);
return DefSubclassProc(window, message, wp, lp);
}, 1, reinterpret_cast<DWORD_PTR>(&hideCount));
expireRun(app);
}
static void expireRun(App &app)
{
std::lock_guard lock(app.stateMutex);
app.run.at = GetTickCount64() - 2500;
}
@@ -867,6 +871,54 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
pasteBehavior = 0;
finish();
break;
case 84:
saved = ks::readClipboard(app->window, 64 * 1024 * 1024);
captured = true;
app->ownSequence = ks::writeClipboard(app->window, ks::textClip(sentinel));
app->settings.snippets = {{L";r", L"rider ."}, {L"[g", L"expanded"}};
app->settings.autoCorrect = false;
ActivateKeyboardLayout(app->layouts[ru].handle, 0);
prepare(L"", false);
typeKeys({'G', 'J', 'L', 'L', 'T', VK_OEM_1, 'R'});
break;
case 85:
require(text() == L"поддежк", "layout variant does not expand at the end of a word");
prepare(L"поддека", false);
SendMessageW(field, EM_SETSEL, 5, 5);
typeKeys({VK_OEM_1, 'R'});
break;
case 86:
require(text() == L"поддежкка", "layout variant does not expand at a caret inside existing text");
require(LOWORD(SendMessageW(field, EM_GETSEL, 0, 0)) == 7,
"skipping expansion restores the caret before the rest of the word");
prepare(L"", false);
typeKeys({'G', 'J', 'L', 'L', 'T'});
break;
case 87:
require(text() == L"подде", "editor received the first part of the word");
ks::InputRegressionAccess::expireRun(*app);
typeKeys({VK_OEM_1, 'R'});
break;
case 88:
require(text() == L"поддежк", "layout variant does not expand after the typing buffer expires");
prepare(L"prefix (", false);
typeKeys({VK_OEM_1, 'R'});
break;
case 89:
require(text() == L"prefix (rider .", "layout variant expands after punctuation");
prepare(L"token_", false);
typeKeys({VK_OEM_4, 'G'});
break;
case 90:
require(text() == L"token_хп", "word boundary also applies to other trigger prefixes");
prepare(L"", false);
typeKeys({VK_OEM_4, 'G'});
break;
case 91:
require(text() == L"expanded", "another layout variant expands at the start of the field");
require(ks::readClipboard(app->window).text() == sentinel, "word boundary check restores the clipboard");
finish();
break;
case 20:
if (!captured)
{
@@ -1182,6 +1234,8 @@ int main(int argc, char **argv)
stage = 64;
if (argc > 1 && std::string(argv[1]) == "--snippet-autocomplete")
stage = 66;
if (argc > 1 && std::string(argv[1]) == "--snippet-word-boundaries")
stage = 84;
SetTimer(host, 1, 100, nullptr);
auto forwarding = SetWindowsHookExW(WH_KEYBOARD_LL,forwardingHook,GetModuleHandleW(nullptr),0);
require(forwarding!=nullptr,"downstream forwarding fixture installed before application hook");