diff --git a/CMakeLists.txt b/CMakeLists.txt index 33391ea..9b322b6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.24) -project(KSwitcher VERSION 0.6.74 LANGUAGES CXX RC) +project(KSwitcher VERSION 0.6.75 LANGUAGES CXX RC) if(NOT WIN32) message(FATAL_ERROR "KSwitcher uses native Windows APIs") endif() diff --git a/LAN-PREVIEW.md b/LAN-PREVIEW.md index efdb849..a0722d2 100644 --- a/LAN-PREVIEW.md +++ b/LAN-PREVIEW.md @@ -28,7 +28,7 @@ Codex's `~/.codex/config.toml`. It starts the MCP server over stdio with the absolute path to `KSwitcher.Config.exe` and the `--mcp` argument. `list_log_computers` returns paired computer IDs and availability. `read_diagnostic_log` reads the latest 100 lines by default (1–500 with -`lines`). Set `previous` to read the rotated log. Omit `peer` for the +`lines`). Use `offset` to skip newer lines and page backward. Set `previous` to read the rotated log. Omit `peer` for the local log or pass a paired computer ID for a remote log. Remote reads need the local resident process running and log downloads enabled on the remote PC. diff --git a/README.md b/README.md index c1a1cef..662bdc2 100644 --- a/README.md +++ b/README.md @@ -609,9 +609,9 @@ Windows exposes them; selection offsets are available for native EDIT controls a marked unavailable for other editors. Input interruptions identify keyboard, mouse, settings or layout-refresh events during an operation. Failed selection verification includes the expected selection and actual copied text in the operation details, without implying that a paste occurred. -Only problem operations write a structured summary to `kswitcher.log`, with their preceding +Problem operations write a structured summary to `kswitcher.log`, with their preceding context. Successful operations stay in that bounded memory buffer and are included only when -a subsequent problem flushes it; they do not create separate rows. Flushed context is discarded. Ordinary application +a subsequent problem flushes it. Verified pastes that take at least two seconds also write a summary without the copied text. Flushed context is discarded. Ordinary application errors are also logged when logging is enabled. This works in normal Release builds. Incident context contains tracked physical input, the expected word, copied text, conversion result, and layout IDs, correlated by request ID even when verification fails. Text fields use quoted, @@ -833,13 +833,13 @@ default and require the main **Automatic correction (experimental)** checkbox to - **Use custom replacements**: enter one `typo=correction` pair per line, for example `првиіт=привіт` or `helo=hello`. Entries are normalized to lowercase; duplicate source words - are rejected. The typo must contain 1–32 letters. The correction may contain several words + are rejected. The typo must be one word of 1–32 characters with at least one letter. It can contain digits and internal apostrophes. The correction may contain several words separated by single spaces, for example `мамамила=мама мила`, up to 32 characters including spaces. Corrections also allow apostrophes (`'`, `’`, `ʼ`) between letters, for example `ревю=рев'ю`. Both sides must use the same supported language, without other punctuation; leading, trailing and repeated spaces are not allowed. Explicit pairs take priority over dictionary recognition, including already valid words, and do not require dictionary membership or satisfy the frequency limit. - Update every synchronizing PC to v0.6.60 or newer before sharing apostrophe pairs; older clients reject them. + Update every synchronizing PC to v0.6.75 before sharing pairs with digits or apostrophes in the typo. - **Correct spelling typos using dictionaries**: checks unknown words in the current language after no layout correction is found. It accepts exactly one dictionary candidate reachable by inserting, deleting or replacing one letter, or swapping two adjacent letters. Both input diff --git a/Release/README.md b/Release/README.md index a023489..a29bf3a 100644 --- a/Release/README.md +++ b/Release/README.md @@ -1,5 +1,23 @@ # Latest Windows release +## v0.6.75 — 2026-11-13 + +Conversion cancels earlier when input changes and skips restoring an untouched +clipboard. Diagnostic records identify the active conversion behind `busy`, +separate clipboard and paste verification timings, and retain a text-free +summary of verified pastes that take at least two seconds. MCP log reads +support `offset` to page backward. + +**Українською.** Конвертація раніше скасовується після зміни вводу й пропускає +відновлення буфера, якщо його не змінювала. Діагностика показує активну спробу +для `busy`, окремий час роботи з буфером і перевірки вставки, а також зберігає +підсумок перевірених вставок від двох секунд без скопійованого тексту. У MCP +параметр `offset` дає змогу читати старіші рядки. + +Explicit replacements now accept digits and internal apostrophes in the source word, for example нав1язав=навʼязав. Invalid entries identify the offending pair. + +**Українською.** Явні заміни підтримують цифри й внутрішні апострофи у вихідному слові, наприклад нав1язав=навʼязав. Повідомлення про помилку показує проблемну пару. + ## v0.6.74 — 2026-11-13 - Send files up to 16 MiB to a selected paired PC over encrypted LAN. Save or discard them from **Incoming files**. diff --git a/Release/SHA256SUMS.txt b/Release/SHA256SUMS.txt index e467868..555fb7f 100644 --- a/Release/SHA256SUMS.txt +++ b/Release/SHA256SUMS.txt @@ -1 +1 @@ -d7f2a0667a5dd3e2bc05b2a3c1900eaddd356343f03f53747fdfd4334ca74b3f KSwitcher-win-x64.zip +36dc789641f72269f4526bf02934788a4dcc48cbe610e4a99bfe0e754ba8977f KSwitcher-win-x64.zip diff --git a/Release/release-files.json b/Release/release-files.json index d76394c..1de35bb 100644 --- a/Release/release-files.json +++ b/Release/release-files.json @@ -1,86 +1,86 @@ { - "schema": 1, "files": [ { + "sha256": "f34c3cc81f01b5c1a2f5008081235c15abbdd204f18a095bebc6fe84d86b135b", "path": "KSwitcher.exe", - "size": 2243072, - "sha256": "da74c9b6986235d95a66d2f1220d436e83e43ce5e73f5132d7c854c823e559fd" + "size": 2247680 }, { + "sha256": "15df9e958517da640e4b06936bfb724dcdf6c3eec489dfab9ab60c9368b9c425", "path": "KSwitcher.Config.exe", - "size": 2249216, - "sha256": "0c290ec58befca6ad0b28b9a5d6a5c11b9edbd6c93fb9015dfaefe7a45d82e2e" + "size": 2251264 }, { + "sha256": "db3a8db6bed2484aae9ac5fdee2521e5dcb352c5e7eb1b9b1664886fb2745204", "path": "KSwitcher.Screenshot.exe", - "size": 3244032, - "sha256": "c90aa8bb0c5e37b64b1c1db98cd9618f7bf0ff2941a80a6029f80fe248d2001b" + "size": 3246592 }, { + "sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c", "path": "LICENSE", - "size": 4401, - "sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c" + "size": 4401 }, { + "sha256": "c0d068392ea65358b798b8c165103560f06e9e3b38c4ab4e2d8810a7b931af86", "path": "json-LICENSE.txt", - "size": 1075, - "sha256": "c0d068392ea65358b798b8c165103560f06e9e3b38c4ab4e2d8810a7b931af86" + "size": 1075 }, { + "sha256": "df6d40d0eb66ad7da8db1cffe6bd211de70dfee474cc228e041c821b3940718b", "path": "README.md", - "size": 93756, - "sha256": "1d1307356a3db561cf3a685eb90b5b524e9e62f9d8acb116a412d5f41242128f" + "size": 93885 }, { + "sha256": "f23bc26ee40daaf8f356d1d4da7f0bf22303a11b80591cf8c8299d9591e2159e", "path": "LAN-PREVIEW.md", - "size": 11201, - "sha256": "26d848df3b106882775ebe8918f2b3ae59ab3be81b713abb90831ed8a2243e8b" + "size": 11253 }, { + "sha256": "5f267c141c3d6837870e1c098f86b89a113ba300343119432644ead88f720c21", "path": "dictionaries/en.txt", - "size": 682867, - "sha256": "5f267c141c3d6837870e1c098f86b89a113ba300343119432644ead88f720c21" + "size": 682867 }, { + "sha256": "28a9529c7d0bb4dc51f4bf5c116a3d16ef247a052f7591466768ddf563fd1cf5", "path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt", - "size": 20138, - "sha256": "28a9529c7d0bb4dc51f4bf5c116a3d16ef247a052f7591466768ddf563fd1cf5" + "size": 20138 }, { + "sha256": "2df17fe4e17d527c67ab57269b07dce59a49c1fb128c429a1408decbb47109ec", "path": "dictionaries/README.md", - "size": 2230, - "sha256": "2df17fe4e17d527c67ab57269b07dce59a49c1fb128c429a1408decbb47109ec" + "size": 2230 }, { + "sha256": "9ef922c7699569304a428f6aba0fd13a21341c0d0cb9561f37ef83c41577a28b", "path": "dictionaries/ru.txt", - "size": 1060364, - "sha256": "9ef922c7699569304a428f6aba0fd13a21341c0d0cb9561f37ef83c41577a28b" + "size": 1060364 }, { + "sha256": "d6e11a3aaba22a8a7eaba19f778d8a5bd66653ff306810e85a1b0e7fff3a6b86", "path": "dictionaries/sources.json", - "size": 1279, - "sha256": "d6e11a3aaba22a8a7eaba19f778d8a5bd66653ff306810e85a1b0e7fff3a6b86" + "size": 1279 }, { + "sha256": "caeb097749d4afc84b68ad96b3d7dfb6a6569561cd32ccce0bee94a13b43ba86", "path": "dictionaries/uk.txt", - "size": 898248, - "sha256": "caeb097749d4afc84b68ad96b3d7dfb6a6569561cd32ccce0bee94a13b43ba86" + "size": 898248 }, { + "sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a", "path": "tools/README.txt", - "size": 993, - "sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a" + "size": 993 }, { + "sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376", "path": "tools/StayHere.exe", - "size": 134656, - "sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376" + "size": 134656 }, { + "sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413", "path": "tools/StayHere-README.md", - "size": 2796, - "sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413" + "size": 2796 } ], - "version": "0.6.74" + "version": "0.6.75", + "schema": 1 } diff --git a/resources/app.rc b/resources/app.rc index 97d888a..8cf0479 100644 --- a/resources/app.rc +++ b/resources/app.rc @@ -9,8 +9,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur" 1 RT_MANIFEST "app.manifest" 201 RCDATA "update.ps1" 1 VERSIONINFO - FILEVERSION 0,6,74,0 - PRODUCTVERSION 0,6,74,0 + FILEVERSION 0,6,75,0 + PRODUCTVERSION 0,6,75,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.74" + VALUE "FileVersion", "0.6.75" END END BLOCK "VarFileInfo" diff --git a/src/app.cpp b/src/app.cpp index aa52bf4..4cea75f 100644 --- a/src/app.cpp +++ b/src/app.cpp @@ -188,6 +188,7 @@ class Transaction ClipboardSnapshot snapshot; DWORD expected{}; bool captured{}; + bool clipboardModified{}; mutable bool invalidLogged{}; unsigned copyNumber{}; std::wstring adopted; @@ -210,9 +211,14 @@ class Transaction expected = GetClipboardSequenceNumber(); try { + auto started = GetTickCount64(); + const bool image = IsClipboardFormatAvailable(CF_DIB) || IsClipboardFormatAvailable(CF_DIBV5) || + IsClipboardFormatAvailable(CF_BITMAP) || IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG")); snapshot.capture(app.window, expected); if (expected != GetClipboardSequenceNumber()) throw std::runtime_error("Clipboard changed while taking snapshot"); + diagnosticEvent(L"Clipboard snapshot captured: elapsedMs=" + + std::to_wstring(GetTickCount64() - started) + L" image=" + std::to_wstring(image)); break; } catch (...) @@ -236,10 +242,12 @@ class Transaction ~Transaction() { if (farSnippet) finishSelection(false); - if (captured && GetClipboardSequenceNumber() == expected) + if (captured && clipboardModified && GetClipboardSequenceNumber() == expected) try { + auto started = GetTickCount64(); app.ownSequence = snapshot.restore(app.window, expected); + diagnosticEvent(L"Clipboard snapshot restored: elapsedMs=" + std::to_wstring(GetTickCount64() - started)); } catch (...) { @@ -296,6 +304,7 @@ class Transaction auto temporary = c; const std::wstring exclusion = L"ExcludeClipboardContentFromMonitorProcessing"; temporary.formats.push_back({RegisterClipboardFormatW(exclusion.c_str()), exclusion, Bytes{0}}); + clipboardModified = true; app.ownSequence = expected = writeClipboard(app.window, temporary); // A concurrent writer can win immediately after CloseClipboard, before we read its sequence. // Never adopt that writer's sequence as our own and paste its content. @@ -2026,7 +2035,8 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet DiagnosticJson record{{"attempt", std::to_string(attempt)}, {"process", utf8(processName(target))}, {"command", transformCommandName(command)}, {"source", "Unknown"}, {"target", "Unknown"}, {"outcome", "busy"}, {"verification", "not-attempted"}, {"problem", true}, - {"elapsedMs", GetTickCount64() - requestedAt}}; + {"elapsedMs", GetTickCount64() - requestedAt}, + {"activeAttempt", activeTransformAttempt.load()}}; diagnosticOperation(record.dump()); } catch (...) {} @@ -2038,6 +2048,7 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet autoPending = false; snippetPending = -1; } + activeTransformAttempt = attempt; Run recent; std::optional previous; Settings config; @@ -2059,20 +2070,24 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet struct BusyReset { std::atomic &b; + std::atomic &active; HWND window; bool deferred{}; ~BusyReset() { + active = 0; if (deferred) PostMessageW(window, ReplayTypingMessage, 0, 0); else b = false; } - } reset{busy, window, preDeferred}; + } reset{busy, activeTransformAttempt, window, preDeferred}; + const auto workerStarted = GetTickCount64(); auto effectiveChat = requestedChat; if (lower(processName(target)) == L"chrome") effectiveChat = readChromeChat(target); config.cycle = chatCycle(config, languageProfileKey(config, target, effectiveChat), available); auto start = GetTickCount64(); + ULONGLONG verificationMs{}; std::wstring reason = L"cancelled-before-selection"; std::wstring text, result, expected, actual, verification = L"not-attempted"; int hint = -1, to = command >= Direct ? command - Direct : -1; @@ -2087,6 +2102,8 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet expected += key == L' ' ? L' ' : layout.at(physicalLayout().code(key)); } diagnosticEvent(L"Transform context id=" + std::to_wstring(attempt) + + L" queueMs=" + std::to_wstring(workerStarted - requestedAt) + + L" profileMs=" + std::to_wstring(start - workerStarted) + L" layouts=" + layoutIds + L" physicalKeys=" + diagnosticText(recent.keys) + L" trackedExpected=" + diagnosticText(expected)); } @@ -2096,6 +2113,7 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet HWND target; uint64_t version, attempt; ULONGLONG start; + const ULONGLONG &verificationMs; bool enabled; std::wstring &reason; std::wstring &text, &result, &expected; @@ -2116,7 +2134,8 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet {"outcome", utf8(reason)}, {"verification", utf8(verification)}, {"problem", reason != L"Paste verified" && reason != L"layout-only" && !(command == 0 && reason == L"paste-sent-unverified")}, - {"elapsedMs", GetTickCount64() - start}, {"foregroundSame", GetForegroundWindow() == target}, + {"elapsedMs", GetTickCount64() - start}, {"verificationMs", verificationMs}, + {"foregroundSame", GetForegroundWindow() == target}, {"inputSame", app.inputVersion.load() == version}, {"original", bounded(text)}, {"expected", bounded(verification == L"selection-mismatch" ? expected : result)}, {"actual", bounded(actual)}, {"selectionExpected", bounded(expected)}, @@ -2126,7 +2145,7 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet } catch (...) {} // Logging must never abort a completed input transaction. } - } audit{*this, target, version, attempt, requestedAt, manual || snippet >= 0, reason, text, result, expected, + } audit{*this, target, version, attempt, requestedAt, verificationMs, manual || snippet >= 0, reason, text, result, expected, actual, verification, hint, to, command, available}; try { @@ -2191,7 +2210,12 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet bool farEditor; ~SelectionReset() { if (selected && !farEditor && valid()) chord(VK_RIGHT); } } selectionReset{autoSelected, valid, farSnippet}; + reason = L"context-changed-before-snapshot"; + if (!valid()) return; + reason = L"clipboard-snapshot"; Transaction tx(*this, target, version, farSnippet, snippetEditor); + reason = L"context-changed-before-selection"; + if (!tx.valid()) return; reason = L"selection-unavailable"; diagnosticEvent(L"Transform target=" + processName(target) + L" command=" + std::to_wstring(command) + L" recent=" + std::to_wstring(config.recent) + L" keys=" + @@ -2311,6 +2335,11 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet std::to_wstring(recent.keys.size()) + L" match=" + std::to_wstring(hint)); if (hint < 0) { + if (!tx.valid()) + { + reason = L"context-changed-during-selection"; + return; + } actual = text; verification = L"selection-mismatch"; reason = text.empty() ? L"recent-copy-empty" : L"recent-verification-mismatch"; @@ -2386,7 +2415,10 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet } bool sent = false; const bool requireReadback = tx.recoveredSelection() || snippet >= 0; + auto probeStarted = GetTickCount64(); PasteProbe probe(!farSnippet && ((config.writeLog && manual) || requireReadback) && result != text, text, target); + 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") { verification = probe.status; @@ -2424,6 +2456,7 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet verification = probe.status; if (tx.valid()) { + auto readStarted = GetTickCount64(); auto observed = farSnippet ? tx.readFarSnippet(caretSteps(result)) : probe.read((int)caretSteps(result)); // A native Edit may silently ignore Ctrl+V while the clipboard is busy. @@ -2437,6 +2470,7 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet else observed.reset(); } + verificationMs += GetTickCount64() - readStarted; verification = farSnippet ? (observed ? L"read-back-via-far-clipboard" : L"far-readback-unavailable") : probe.status; if (observed && tx.valid()) diff --git a/src/app.h b/src/app.h index be9f725..5c2a41f 100644 --- a/src/app.h +++ b/src/app.h @@ -162,6 +162,7 @@ class App UINT taskbarCreated{}; bool trayRetryPending{}; uint64_t transformAttempt{}, previousAttemptVersion{}; + std::atomic activeTransformAttempt{}; ULONGLONG previousAttemptAt{}; HWND previousAttemptWindow{}; int previousAttemptCommand{}, repeatAttempts{}; diff --git a/src/autocorrect.cpp b/src/autocorrect.cpp index fb14875..a39d26b 100644 --- a/src/autocorrect.cpp +++ b/src/autocorrect.cpp @@ -245,18 +245,20 @@ std::optional AutoCorrector::suggest(const std::wstring &typed, const std::wstring alphabet = sourceLanguage == L"en" ? L"abcdefghijklmnopqrstuvwxyz" : sourceLanguage == L"uk" ? L"абвгґдеєжзиіїйклмнопрстуфхцчшщьюя" : L"абвгдеёжзийклмнопрстуфхцчшщъыьэюя"; auto small = lower(word); + bool inCycle = std::find(settings.cycle.begin(), settings.cycle.end(), layouts[source].id) != settings.cycle.end(); bool sameLanguage = safeAutoWord(word, settings.autoMinLength) && - small.find_first_not_of(alphabet) == small.npos && - std::find(settings.cycle.begin(), settings.cycle.end(), layouts[source].id) != settings.cycle.end(); + small.find_first_not_of(alphabet) == small.npos && inCycle; auto sameLayout = [&](std::wstring text) { if (word != small) text[0] = upper(text.substr(0, 1))[0]; return AutoSuggestion{source, source, prefix + text + suffix}; }; - if (settings.autoReplace && sameLanguage) + if (settings.autoReplace && inCycle) { auto replacement = settings.autoReplacements.find(small); if (replacement != settings.autoReplacements.end() && + (word == small || (word.substr(1) == small.substr(1) && word != upper(word))) && + validAutoReplacementSource(small, alphabet) && validAutoCorrection(replacement->second, alphabet)) return sameLayout(replacement->second); } diff --git a/src/core.cpp b/src/core.cpp index 5a39e64..206859f 100644 --- a/src/core.cpp +++ b/src/core.cpp @@ -35,6 +35,11 @@ bool validAutoCorrection(const std::wstring &text, const std::wstring &alphabet) } return true; } +bool validAutoReplacementSource(const std::wstring &text, const std::wstring &alphabet) +{ + return text.find(L' ') == text.npos && text.find_first_of(alphabet) != text.npos && + validAutoCorrection(text, alphabet + L"0123456789"); +} int HotkeyHook::update(UINT key, bool down, UINT modifiers, const std::vector> &bindings) { diff --git a/src/core.h b/src/core.h index d71d973..83bfcd9 100644 --- a/src/core.h +++ b/src/core.h @@ -21,6 +21,7 @@ struct Layout }; bool letter(wchar_t ch); bool validAutoCorrection(const std::wstring &text, const std::wstring &alphabet); +bool validAutoReplacementSource(const std::wstring &text, const std::wstring &alphabet); std::wstring lower(std::wstring text); std::wstring upper(std::wstring text); std::wstring convert(const std::wstring &, const Layout &, const Layout &, bool force = false); diff --git a/src/mcp_logs.h b/src/mcp_logs.h index a5936c6..2171183 100644 --- a/src/mcp_logs.h +++ b/src/mcp_logs.h @@ -16,7 +16,7 @@ inline int runLogMcp(const std::function &lan) }; const Json tools = Json::parse(R"({"tools":[ {"name":"list_log_computers","description":"List paired computers that support remote log downloads.","inputSchema":{"type":"object","properties":{}},"annotations":{"readOnlyHint":true}}, - {"name":"read_diagnostic_log","description":"Read recent KSwitcher diagnostic log lines. Omit peer for the local computer.","inputSchema":{"type":"object","properties":{"peer":{"type":"string"},"previous":{"type":"boolean"},"lines":{"type":"integer","minimum":1,"maximum":500,"default":100}}},"annotations":{"readOnlyHint":true}} + {"name":"read_diagnostic_log","description":"Read KSwitcher diagnostic log lines. Omit peer for the local computer. Use offset to page backward from the newest line.","inputSchema":{"type":"object","properties":{"peer":{"type":"string"},"previous":{"type":"boolean"},"lines":{"type":"integer","minimum":1,"maximum":500,"default":100},"offset":{"type":"integer","minimum":0,"default":0}}},"annotations":{"readOnlyHint":true}} ]})"); std::string line; while (std::getline(std::cin, line)) @@ -62,6 +62,8 @@ inline int runLogMcp(const std::function &lan) bool previous = arguments.value("previous", false); int lines = arguments.value("lines", 100); if (lines < 1 || lines > 500) throw std::runtime_error("lines must be between 1 and 500."); + int offset = arguments.value("offset", 0); + if (offset < 0) throw std::runtime_error("offset must be nonnegative."); if (peer.empty()) output = utf8(readDiagnosticLog(previous)); else { @@ -82,15 +84,17 @@ inline int runLogMcp(const std::function &lan) Sleep(250); } } - size_t start = output.size(); - if (start && output.back() == '\n') --start; - while (lines-- && start) + auto previousLine = [&](size_t end) { - auto newline = output.rfind('\n', start - 1); - if (newline == std::string::npos) { start = 0; break; } - start = newline; - } - if (start) output.erase(0, start + 1); + if (!end) return size_t{}; + if (output[end - 1] == '\n') --end; + return end ? output.rfind('\n', end - 1) + 1 : size_t{}; + }; + size_t end = output.size(); + while (offset-- > 0 && end) end = previousLine(end); + size_t start = end; + while (lines-- > 0 && start) start = previousLine(start); + output = output.substr(start, end - start); } else throw std::runtime_error("Unknown tool."); } diff --git a/src/paste_probe.h b/src/paste_probe.h index fe6f94f..bdd7926 100644 --- a/src/paste_probe.h +++ b/src/paste_probe.h @@ -90,15 +90,22 @@ class PasteProbe return {}; } IUIAutomationElement *focused{}; - BOOL same = FALSE; - if (SUCCEEDED(automation->GetFocusedElement(&focused)) && focused) + if (FAILED(automation->GetFocusedElement(&focused)) || !focused) { - automation->CompareElements(element, focused, &same); + if (focused) focused->Release(); + status = L"accessibility-focus-unavailable"; + return {}; + } + BOOL same = FALSE; + if (FAILED(automation->CompareElements(element, focused, &same))) + { + focused->Release(); + status = L"accessibility-focus-comparison-failed"; + return {}; } if (!same) { - if (focused) - focused->Release(); + focused->Release(); status = L"focused-control-changed"; return {}; } diff --git a/src/platform.cpp b/src/platform.cpp index 8e50602..7ab7021 100644 --- a/src/platform.cpp +++ b/src/platform.cpp @@ -816,6 +816,13 @@ void diagnosticOperation(const std::string &json) auto record = nlohmann::json::parse(json); if (!record.value("problem", true)) { + if (record.value("elapsedMs", 0ULL) >= 2000 && record.value("outcome", "") == "Paste verified") + { + auto summary = record; + for (auto field : {"original", "expected", "actual", "selectionExpected"}) + summary.erase(field); + log(L"Operation " + wide(summary.dump(-1, ' ', true, nlohmann::json::error_handler_t::replace))); + } // Keep successful operations only in the bounded, short-lived context. // They are persisted with a subsequent failure, never as standalone rows. diagnosticBuffer.record(L"Completed operation " + wide(record.dump(-1, ' ', true, diff --git a/src/storage.cpp b/src/storage.cpp index 34ef6d8..dc7963a 100644 --- a/src/storage.cpp +++ b/src/storage.cpp @@ -253,10 +253,12 @@ void validateSettings(const Settings &s) L"абвгдеёжзийклмнопрстуфхцчшщъыьэюя"}) valid |= !from.empty() && !to.empty() && from.size() <= 32 && to.size() <= 32 && from == lower(from) && to == lower(to) && from != to && - from.find_first_not_of(alphabet) == from.npos && + validAutoReplacementSource(from, alphabet) && validAutoCorrection(to, alphabet); if (!valid) - throw std::runtime_error("Use a lowercase typo of 1-32 letters and a different correction of 1-32 characters in the same language. Single spaces between words and apostrophes between letters are allowed."); + throw std::runtime_error("Invalid replacement: " + utf8(from.substr(0, 32)) + "=" + + utf8(to.substr(0, 32)) + "\n\nUse one lowercase word of 1-32 characters. The typo may include " + "digits and internal apostrophes. Use a different correction of 1-32 characters in the same language."); } for (const auto &[language, words] : s.autoWords) { diff --git a/src/update.h b/src/update.h index 708dec2..bda7b54 100644 --- a/src/update.h +++ b/src/update.h @@ -2,7 +2,7 @@ #include "platform.h" namespace ks { -inline constexpr wchar_t AppVersion[] = L"0.6.74"; +inline constexpr wchar_t AppVersion[] = L"0.6.75"; inline constexpr UINT UpdateMessage = WM_APP + 7; inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000; inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000; diff --git a/tests/tests.cpp b/tests/tests.cpp index 63301f1..849b955 100644 --- a/tests/tests.cpp +++ b/tests/tests.cpp @@ -592,6 +592,10 @@ int main(int argc, char **argv) require(!edited.suggest(L"hlelo ", 0, layouts, options), "never-correct overrides explicit pairs"); options.autoNever.clear(); options.autoReplacements[L"мамамила"] = L"мама мила"; + options.autoReplacements[L"нав1язав"] = L"нав’язав"; + ks::validateSettings(options); + correction = edited.suggest(L"Нав1язав ", 2, layouts, options); + require(correction && correction->text == L"Нав’язав ", "explicit replacements accept digits in the typo"); for (const auto *text : {L"рев'ю", L"рев’ю", L"ревʼю", L"моє рев'ю"}) { options.autoReplacements[L"ревю"] = text;