Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bdd058f493 | ||
|
|
e7624b620e | ||
|
|
367a5fd9f7 |
No files matched your search
+1
-1
@@ -1,5 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.24)
|
||||
project(KSwitcher VERSION 0.6.120 LANGUAGES CXX RC)
|
||||
project(KSwitcher VERSION 0.6.123 LANGUAGES CXX RC)
|
||||
if(NOT WIN32)
|
||||
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
|
||||
endif()
|
||||
|
||||
+4
-2
@@ -331,8 +331,10 @@ Warning і початковий фокус на No.
|
||||
перерендерюється зі збереженням позиції прокрутки.
|
||||
Вебпосилання HTTP і HTTPS відкриваються в системному браузері.
|
||||
Для LAN зображення завантажуються у фоні, а файли за посиланнями — після
|
||||
кліку. Mermaid працює офлайн. Якщо WebView2 недоступний або файл більший за
|
||||
8 МіБ, F3 відкриває текстовий перегляд.
|
||||
кліку. Mermaid працює офлайн і завантажується лише для документів із
|
||||
діаграмами Mermaid. Якщо WebView2 не завершує запуск, Files один раз
|
||||
повторює спробу в тому самому вікні. Якщо форматований перегляд недоступний
|
||||
або файл більший за 8 МіБ, F3 відкриває текстовий перегляд.
|
||||
- F3 у фоні підраховує сумарний розмір файлів у папці та її підпапках.
|
||||
На рядку `..` F3 рахує всі папки поточного списку, а за наявності
|
||||
позначених папок в інших рядках рахує позначені папки. Без позначок
|
||||
|
||||
+14
-2
@@ -59,6 +59,12 @@ the local resident process running and log downloads enabled on the remote PC.
|
||||
into the source computer restores its cursor at the corresponding edge. Empty
|
||||
cells, diagonal-only neighbors and offline PCs do not transfer control.
|
||||
|
||||
When input sharing is enabled, the tray icon shows a steady gray dot if all
|
||||
paired PCs are offline, a pulsing amber dot while a discovered PC is connecting,
|
||||
a green dot when all online paired PCs are connected, and a red dot if the LAN
|
||||
worker stops. Hover over the icon to see the connection status and the connected
|
||||
count when only some paired PCs are connected.
|
||||
|
||||
The source cursor is parked and hidden beneath a tiny no-activation window. A
|
||||
small banner identifies remote control; no full-screen layered bitmap is retained.
|
||||
The destination uses its own keyboard layout and runs its own hotkeys/snippets.
|
||||
@@ -105,8 +111,14 @@ VLANs, public IPv4 and IPv6-only networks are not supported by discovery yet.
|
||||
A second LAN-enabled KSwitcher cannot use the same ports on one computer.
|
||||
|
||||
Input first tries TCP in the usual direction, then reverse TCP after 1.5 seconds.
|
||||
If TCP has not authenticated after 5 seconds, the lower-ID peer negotiates an
|
||||
encrypted UDP input session on the existing discovery socket (UDP 45883).
|
||||
LAN discovery authenticates paired PCs before starting new input connections.
|
||||
Discovery remains active while all paired PCs are offline and wakes input sharing
|
||||
when one reappears. An authenticated input connection survives missed discovery
|
||||
announcements. Once discovery has expired and the channel closes, further input
|
||||
attempts wait for fresh discovery.
|
||||
After at least 5 seconds, the lower-ID peer starts encrypted UDP fallback on the
|
||||
discovery socket (UDP 45883) once its current TCP connection attempt has failed
|
||||
or reached its 10-second deadline.
|
||||
UDP uses fresh session challenges, authenticated encryption, ordered event
|
||||
numbers, acknowledgements and bounded retries; duplicated packets do not repeat
|
||||
key presses. Two seconds without authenticated traffic or acknowledgement
|
||||
|
||||
@@ -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 підказки відкриваються біля текстового курсора. Якщо редактор не
|
||||
надає його позицію, введіть повний тригер для розгортання сніпета.
|
||||
|
||||
+33
-1
@@ -1,5 +1,37 @@
|
||||
# Latest Windows release
|
||||
|
||||
## v0.6.123 — 2026-11-20
|
||||
|
||||
- The tray shows a steady gray dot when all paired PCs are offline. The amber dot pulses while a discovered PC is connecting. Green means every online paired PC is connected.
|
||||
- LAN discovery stays active. Once discovery has expired and the last input channel closes, KSwitcher pauses mouse and keyboard connection attempts until a paired PC reappears.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- Коли всі спаровані ПК офлайн, у треї видно статичну сіру крапку. Жовта крапка пульсує під час підключення до знайденого ПК. Зелена означає, що всі доступні спаровані ПК під’єднані.
|
||||
- Пошук у LAN продовжує працювати. Коли строк дії підтвердження присутності спливає й останній канал вводу закривається, KSwitcher призупиняє спроби підключення миші та клавіатури до появи спарованого ПК.
|
||||
|
||||
## v0.6.122 — 2026-11-20
|
||||
|
||||
- LAN mouse and keyboard sharing lets a TCP attempt finish or time out before starting the encrypted UDP fallback.
|
||||
- The tray icon pulses amber while reconnecting, shows green when all paired PCs are connected, and shows red if the LAN service stops. Hover to see connection status and how many PCs are connected. Diagnostic logs distinguish a declined cursor handoff from returned control.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- Під час передавання миші та клавіатури KSwitcher чекає завершення TCP-спроби або її тайм-ауту, перш ніж запустити резервне з’єднання через зашифрований UDP.
|
||||
- Іконка в треї пульсує жовтим під час перепідключення, показує зелену крапку, коли всі спаровані ПК під’єднані, і червону, якщо LAN-модуль зупинився. Наведіть курсор, щоб побачити стан і кількість підключених ПК. У діагностичному журналі видно, коли другий ПК відхилив перехід курсора або повернув керування.
|
||||
|
||||
## 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.
|
||||
@@ -542,6 +574,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 @@
|
||||
53334ba83a44c69c3acd2aad297db177366fe553fae8813b88b81e0a215c860f KSwitcher-win-x64.zip
|
||||
868941978ca231f3df01917277d8ec5b8de970c81f6b83b5fa9e64b18b71ab9a KSwitcher-win-x64.zip
|
||||
+76
-76
@@ -1,166 +1,166 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"version": "0.6.123",
|
||||
"files": [
|
||||
{
|
||||
"path": "KSwitcher.exe",
|
||||
"sha256": "152b41278761439ce5ebe87bca3a4d8a96d89db82264ec0fbb2299e7c207dfb5",
|
||||
"size": 2372096
|
||||
"size": 5892884,
|
||||
"sha256": "043c10eb6752656fc2aa6c1f8d329d4fe243347a5275088e5dc4385638acd870",
|
||||
"path": "KSwitcher.exe"
|
||||
},
|
||||
{
|
||||
"path": "KSwitcher.Config.exe",
|
||||
"sha256": "3d44721ba688a6916e393d2b9d9291e38ee063795b54cdae8e78cfd621835619",
|
||||
"size": 2369536
|
||||
"size": 5948997,
|
||||
"sha256": "ac6368858b86d4e9a4a2c1cf4cd90c39b58d699909c417f73d9f882c54dd96a0",
|
||||
"path": "KSwitcher.Config.exe"
|
||||
},
|
||||
{
|
||||
"path": "KSwitcher.Screenshot.exe",
|
||||
"sha256": "81d9fbb770e876937310a0b483e11bd96cdb9e20b0f6baf0fa9927f24965aeeb",
|
||||
"size": 3348992
|
||||
"size": 5763947,
|
||||
"sha256": "d2f435c645419a155e6feac7761d9894f7bd2099cd695a93650847c869c50ffb",
|
||||
"path": "KSwitcher.Screenshot.exe"
|
||||
},
|
||||
{
|
||||
"path": "KSwitcher.Files.exe",
|
||||
"sha256": "04c9af5324144a46a5f3cc0d8f2c6912745f8bbad7fbef0576bd52c88b5c5e03",
|
||||
"size": 4370944
|
||||
"size": 9395313,
|
||||
"sha256": "43512aa25c8b9854cb3134b9480e24049eab77a0008af55cede06369dc6a0964",
|
||||
"path": "KSwitcher.Files.exe"
|
||||
},
|
||||
{
|
||||
"path": "WebView2Loader.dll",
|
||||
"size": 194912,
|
||||
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
|
||||
"size": 194912
|
||||
"path": "WebView2Loader.dll"
|
||||
},
|
||||
{
|
||||
"path": "terminal/addon-fit-LICENSE.txt",
|
||||
"size": 1103,
|
||||
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
|
||||
"size": 1103
|
||||
"path": "terminal/addon-fit-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"path": "terminal/addon-fit.js",
|
||||
"size": 1521,
|
||||
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
|
||||
"size": 1521
|
||||
"path": "terminal/addon-fit.js"
|
||||
},
|
||||
{
|
||||
"path": "terminal/index.html",
|
||||
"size": 527,
|
||||
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
|
||||
"size": 527
|
||||
"path": "terminal/index.html"
|
||||
},
|
||||
{
|
||||
"path": "terminal/markdown-it-LICENSE.txt",
|
||||
"size": 1073,
|
||||
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
|
||||
"size": 1073
|
||||
"path": "terminal/markdown-it-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"path": "terminal/markdown-it.js",
|
||||
"size": 100786,
|
||||
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
|
||||
"size": 100786
|
||||
"path": "terminal/markdown-it.js"
|
||||
},
|
||||
{
|
||||
"path": "terminal/markdown.html",
|
||||
"sha256": "8268f55e8642034efa5a762cbd65d02a1d416aea9e777e0fe30a7e916ae3ee79",
|
||||
"size": 3635
|
||||
"size": 3599,
|
||||
"sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094",
|
||||
"path": "terminal/markdown.html"
|
||||
},
|
||||
{
|
||||
"path": "terminal/markdown.js",
|
||||
"sha256": "4c68dff619cf248f6bd32b09a45458675c22341892dc377204e46c2f4fd562f8",
|
||||
"size": 16944
|
||||
"size": 17575,
|
||||
"sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8",
|
||||
"path": "terminal/markdown.js"
|
||||
},
|
||||
{
|
||||
"path": "terminal/mermaid-LICENSE.txt",
|
||||
"size": 1089,
|
||||
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
|
||||
"size": 1089
|
||||
"path": "terminal/mermaid-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"path": "terminal/mermaid.js",
|
||||
"size": 5537838,
|
||||
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
|
||||
"size": 5537838
|
||||
"path": "terminal/mermaid.js"
|
||||
},
|
||||
{
|
||||
"path": "terminal/terminal.js",
|
||||
"size": 5065,
|
||||
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b",
|
||||
"size": 5065
|
||||
"path": "terminal/terminal.js"
|
||||
},
|
||||
{
|
||||
"path": "terminal/xterm-LICENSE.txt",
|
||||
"size": 1261,
|
||||
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
|
||||
"size": 1261
|
||||
"path": "terminal/xterm-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"path": "terminal/xterm.css",
|
||||
"size": 7112,
|
||||
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
|
||||
"size": 7112
|
||||
"path": "terminal/xterm.css"
|
||||
},
|
||||
{
|
||||
"path": "terminal/xterm.js",
|
||||
"size": 488663,
|
||||
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
|
||||
"size": 488663
|
||||
"path": "terminal/xterm.js"
|
||||
},
|
||||
{
|
||||
"path": "LICENSE",
|
||||
"size": 4401,
|
||||
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
|
||||
"size": 4401
|
||||
"path": "LICENSE"
|
||||
},
|
||||
{
|
||||
"path": "json-LICENSE.txt",
|
||||
"size": 1096,
|
||||
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
|
||||
"size": 1096
|
||||
"path": "json-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"path": "files-text-license.txt",
|
||||
"size": 883,
|
||||
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
|
||||
"size": 883
|
||||
"path": "files-text-license.txt"
|
||||
},
|
||||
{
|
||||
"path": "README.md",
|
||||
"sha256": "afc7e78c4c3600888f642692423cd993b4aa431dfa54f752c7ac394de18186c6",
|
||||
"size": 95354
|
||||
"size": 95524,
|
||||
"sha256": "23d203a1fe73d1adc5e51d088420848cfabf03929401b78c4dbb249d0b5bdbf6",
|
||||
"path": "README.md"
|
||||
},
|
||||
{
|
||||
"path": "LAN-PREVIEW.md",
|
||||
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930",
|
||||
"size": 11577
|
||||
"size": 12353,
|
||||
"sha256": "3ab51025826e8aa2f7c07b70b920b556409b002029b4bb92cb34c5b32dac6e54",
|
||||
"path": "LAN-PREVIEW.md"
|
||||
},
|
||||
{
|
||||
"path": "dictionaries/en.txt",
|
||||
"size": 732485,
|
||||
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
|
||||
"size": 732485
|
||||
"path": "dictionaries/en.txt"
|
||||
},
|
||||
{
|
||||
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
|
||||
"size": 20566,
|
||||
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
|
||||
"size": 20566
|
||||
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt"
|
||||
},
|
||||
{
|
||||
"path": "dictionaries/README.md",
|
||||
"size": 2265,
|
||||
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
|
||||
"size": 2265
|
||||
"path": "dictionaries/README.md"
|
||||
},
|
||||
{
|
||||
"path": "dictionaries/ru.txt",
|
||||
"size": 1109134,
|
||||
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
|
||||
"size": 1109134
|
||||
"path": "dictionaries/ru.txt"
|
||||
},
|
||||
{
|
||||
"path": "dictionaries/sources.json",
|
||||
"size": 1280,
|
||||
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
|
||||
"size": 1280
|
||||
"path": "dictionaries/sources.json"
|
||||
},
|
||||
{
|
||||
"path": "dictionaries/uk.txt",
|
||||
"size": 940799,
|
||||
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
|
||||
"size": 940799
|
||||
"path": "dictionaries/uk.txt"
|
||||
},
|
||||
{
|
||||
"path": "tools/README.txt",
|
||||
"size": 993,
|
||||
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
|
||||
"size": 993
|
||||
"path": "tools/README.txt"
|
||||
},
|
||||
{
|
||||
"path": "tools/StayHere.exe",
|
||||
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376",
|
||||
"size": 134656
|
||||
"size": 540583,
|
||||
"sha256": "bb595202cc4749f3c0fe47adc92d4b02a174abeb5765e493673de9f5e070251c",
|
||||
"path": "tools/StayHere.exe"
|
||||
},
|
||||
{
|
||||
"path": "tools/StayHere-README.md",
|
||||
"size": 2796,
|
||||
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
|
||||
"size": 2796
|
||||
"path": "tools/StayHere-README.md"
|
||||
}
|
||||
],
|
||||
"schema": 1,
|
||||
"version": "0.6.120"
|
||||
]
|
||||
}
|
||||
+3
-3
@@ -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,120,0
|
||||
PRODUCTVERSION 0,6,120,0
|
||||
FILEVERSION 0,6,123,0
|
||||
PRODUCTVERSION 0,6,123,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.120"
|
||||
VALUE "FileVersion", "0.6.123"
|
||||
END
|
||||
END
|
||||
BLOCK "VarFileInfo"
|
||||
|
||||
@@ -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>
|
||||
@@ -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;
|
||||
|
||||
+183
-29
@@ -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 = {})
|
||||
@@ -862,30 +889,132 @@ void App::report(const std::wstring &text)
|
||||
}
|
||||
constexpr UINT_PTR TrayRetryTimer = 20;
|
||||
constexpr UINT TrayRetryIntervalMs = 1000;
|
||||
constexpr UINT_PTR TrayInputTimer = 22;
|
||||
constexpr UINT TrayInputPulseMs = 450;
|
||||
|
||||
void App::addTray()
|
||||
namespace
|
||||
{
|
||||
HICON trayInputIcon(HICON base, int width, int height, uint32_t color)
|
||||
{
|
||||
if (!base || width < 8 || height < 8) return nullptr;
|
||||
BITMAPINFO bitmapInfo{};
|
||||
bitmapInfo.bmiHeader = {sizeof(BITMAPINFOHEADER), width, -height, 1, 32, BI_RGB};
|
||||
void *bits{};
|
||||
HBITMAP bitmap = CreateDIBSection(nullptr, &bitmapInfo, DIB_RGB_COLORS, &bits, nullptr, 0);
|
||||
if (!bitmap) return nullptr;
|
||||
HDC dc = CreateCompatibleDC(nullptr);
|
||||
HICON icon{};
|
||||
if (dc)
|
||||
{
|
||||
auto previous = SelectObject(dc, bitmap);
|
||||
auto pixels = static_cast<uint32_t *>(bits);
|
||||
std::fill_n(pixels, size_t(width) * height, 0);
|
||||
if (DrawIconEx(dc, 0, 0, base, width, height, 0, nullptr, DI_NORMAL))
|
||||
{
|
||||
GdiFlush();
|
||||
const int radius = std::max(3, MulDiv(std::min(width, height), 3, 16));
|
||||
const int cx = width - 1 - radius, cy = height - 1 - radius;
|
||||
for (int y = -radius; y <= radius; ++y)
|
||||
for (int x = -radius; x <= radius; ++x)
|
||||
{
|
||||
const int distance = x * x + y * y;
|
||||
if (distance <= radius * radius)
|
||||
pixels[(cy + y) * width + cx + x] = distance <= (radius - 1) * (radius - 1)
|
||||
? color : 0xff242424;
|
||||
}
|
||||
// The 32-bit DIB supplies the transparency. The fallback mask is initialized as well.
|
||||
std::vector<unsigned char> maskBits(size_t((width + 15) / 16) * 2 * height);
|
||||
if (auto mask = CreateBitmap(width, height, 1, 1, maskBits.data()))
|
||||
{
|
||||
ICONINFO info{TRUE, 0, 0, mask, bitmap};
|
||||
icon = CreateIconIndirect(&info);
|
||||
DeleteObject(mask);
|
||||
}
|
||||
}
|
||||
SelectObject(dc, previous);
|
||||
DeleteDC(dc);
|
||||
}
|
||||
DeleteObject(bitmap);
|
||||
return icon;
|
||||
}
|
||||
}
|
||||
|
||||
bool App::updateTray(DWORD action, bool notifyFile)
|
||||
{
|
||||
NOTIFYICONDATAW icon{sizeof(icon)};
|
||||
icon.hWnd = window;
|
||||
icon.uID = 1;
|
||||
icon.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_SHOWTIP;
|
||||
icon.uFlags = NIF_ICON | NIF_TIP | NIF_SHOWTIP;
|
||||
if (action == NIM_ADD) icon.uFlags |= NIF_MESSAGE;
|
||||
icon.uCallbackMessage = TrayMessage;
|
||||
icon.hIcon = (HICON)LoadImageW(instance, MAKEINTRESOURCEW(IDI_KSWITCHER), IMAGE_ICON,
|
||||
GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_SHARED);
|
||||
auto tip = incomingLanFileCount ? L"KSwitcher — files ready to save: " + std::to_wstring(incomingLanFileCount)
|
||||
: localBuildTitle(L"KSwitcher — keyboard layouts & clipboard");
|
||||
const int width = GetSystemMetrics(SM_CXSMICON), height = GetSystemMetrics(SM_CYSMICON);
|
||||
icon.hIcon = (HICON)LoadImageW(instance, MAKEINTRESOURCEW(IDI_KSWITCHER), IMAGE_ICON, width, height, LR_SHARED);
|
||||
HICON badge{};
|
||||
auto tip = localBuildTitle(L"KSwitcher");
|
||||
if (trayInput.paired)
|
||||
{
|
||||
const bool reconnecting = trayInput.reconnecting();
|
||||
const uint32_t color = trayInput.stopped ? 0xfff16b66 : !trayInput.online ? 0xffa0a4ab :
|
||||
!reconnecting ? 0xff45d58c : trayInputPulse ? 0xffffc457 : 0xffac7830;
|
||||
badge = trayInputIcon(icon.hIcon, width, height, color);
|
||||
if (badge) icon.hIcon = badge;
|
||||
tip += L" — Mouse & keyboard: ";
|
||||
if (trayInput.stopped) tip += L"connection stopped";
|
||||
else if (!trayInput.online) tip += L"all paired PCs offline. Waiting for LAN discovery.";
|
||||
else
|
||||
{
|
||||
tip += reconnecting ? L"reconnecting" : L"connected";
|
||||
if (trayInput.connected < trayInput.paired)
|
||||
tip += L" (" + std::to_wstring(trayInput.connected) + L"/" +
|
||||
std::to_wstring(trayInput.paired) + L" PCs connected)";
|
||||
}
|
||||
}
|
||||
else if (!incomingLanFileCount)
|
||||
tip = localBuildTitle(L"KSwitcher — keyboard layouts & clipboard");
|
||||
if (incomingLanFileCount)
|
||||
tip += L"\nFiles ready to save: " + std::to_wstring(incomingLanFileCount);
|
||||
wcsncpy_s(icon.szTip, tip.c_str(), _TRUNCATE);
|
||||
if (Shell_NotifyIconW(NIM_ADD, &icon))
|
||||
if (notifyFile)
|
||||
{
|
||||
icon.uFlags |= NIF_INFO;
|
||||
wcscpy_s(icon.szInfoTitle, L"Incoming file ready to save");
|
||||
wcscpy_s(icon.szInfo, L"Open Settings → Computers → Manage computers → Incoming files.");
|
||||
icon.dwInfoFlags = NIIF_INFO;
|
||||
}
|
||||
const bool updated = Shell_NotifyIconW(action, &icon) != FALSE;
|
||||
if (badge) DestroyIcon(badge);
|
||||
return updated;
|
||||
}
|
||||
|
||||
void App::refreshTrayInput()
|
||||
{
|
||||
const auto state = lanService ? lanService->inputConnections() : LanInputConnections{};
|
||||
if (state == trayInput) return;
|
||||
trayInput = state;
|
||||
trayInputPulse = true;
|
||||
if (state.reconnecting())
|
||||
SetTimer(window, TrayInputTimer, TrayInputPulseMs, nullptr);
|
||||
else
|
||||
KillTimer(window, TrayInputTimer);
|
||||
updateTray(NIM_MODIFY);
|
||||
}
|
||||
|
||||
void App::addTray()
|
||||
{
|
||||
if (updateTray(NIM_ADD))
|
||||
{
|
||||
KillTimer(window, TrayRetryTimer);
|
||||
trayRetryPending = false;
|
||||
NOTIFYICONDATAW icon{sizeof(icon)};
|
||||
icon.hWnd = window;
|
||||
icon.uID = 1;
|
||||
icon.uVersion = NOTIFYICON_VERSION_4;
|
||||
Shell_NotifyIconW(NIM_SETVERSION, &icon);
|
||||
}
|
||||
else if (!trayRetryPending)
|
||||
{
|
||||
trayRetryPending = SetTimer(window, TrayRetryTimer, TrayRetryIntervalMs, nullptr) != 0;
|
||||
}
|
||||
icon.uVersion = NOTIFYICON_VERSION_4;
|
||||
Shell_NotifyIconW(NIM_SETVERSION, &icon);
|
||||
}
|
||||
bool App::registerHotkeys(const Settings &s, bool rollback)
|
||||
{
|
||||
@@ -926,6 +1055,7 @@ Bytes App::lanCommand(const Bytes &command)
|
||||
if (lanService->inputEnabled()) SetTimer(window, 7, 10, nullptr);
|
||||
else KillTimer(window, 7);
|
||||
if (lanService->takeInputChange()) resetLanInput();
|
||||
refreshTrayInput();
|
||||
return reply;
|
||||
}
|
||||
void App::applySettings(const Settings &requested)
|
||||
@@ -1231,7 +1361,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 +2346,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 +2629,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 +2644,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)
|
||||
@@ -3201,23 +3356,12 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
|
||||
case LanFilesChangedMessage:
|
||||
{
|
||||
app->incomingLanFileCount = wp;
|
||||
NOTIFYICONDATAW icon{sizeof(icon)};
|
||||
icon.hWnd = hwnd;
|
||||
icon.uID = 1;
|
||||
icon.uFlags = NIF_TIP | NIF_SHOWTIP;
|
||||
auto tip = wp ? L"KSwitcher — files ready to save: " + std::to_wstring(wp)
|
||||
: localBuildTitle(L"KSwitcher — keyboard layouts & clipboard");
|
||||
wcsncpy_s(icon.szTip, tip.c_str(), _TRUNCATE);
|
||||
if (lp)
|
||||
{
|
||||
icon.uFlags |= NIF_INFO;
|
||||
wcscpy_s(icon.szInfoTitle, L"Incoming file ready to save");
|
||||
wcscpy_s(icon.szInfo, L"Open Settings → Computers → Manage computers → Incoming files.");
|
||||
icon.dwInfoFlags = NIIF_INFO;
|
||||
}
|
||||
if (Shell_NotifyIconW(NIM_MODIFY, &icon) && lp) app->incomingFileBalloon = true;
|
||||
if (app->updateTray(NIM_MODIFY, lp != 0) && lp) app->incomingFileBalloon = true;
|
||||
return 0;
|
||||
}
|
||||
case LanInputStatusMessage:
|
||||
app->refreshTrayInput();
|
||||
return 0;
|
||||
case CheckAutostartMessage:
|
||||
app->checkAutostartPath();
|
||||
return 0;
|
||||
@@ -3260,6 +3404,15 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
|
||||
if (app->trayRetryPending) app->addTray();
|
||||
return 0;
|
||||
}
|
||||
if (wp == TrayInputTimer)
|
||||
{
|
||||
if (app->trayInput.reconnecting())
|
||||
{
|
||||
app->trayInputPulse = !app->trayInputPulse;
|
||||
app->updateTray(NIM_MODIFY);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (wp == MouseClickTimer) { app->flushMouseClicks(); return 0; }
|
||||
if (wp >= FirstMouseVolumeTimer && wp < FirstMouseVolumeTimer + std::size(MouseButtonNames))
|
||||
{
|
||||
@@ -3453,6 +3606,7 @@ int App::execute()
|
||||
try { lanService = std::make_unique<LanService>(data,window); }
|
||||
catch (const std::exception &e) { report(L"LAN module: " + wide(e.what())); }
|
||||
if (lanService && lanService->inputEnabled()) SetTimer(window, 7, 10, nullptr);
|
||||
refreshTrayInput();
|
||||
SetTimer(window, 1, 60000, nullptr);
|
||||
if (!smoke) SetTimer(window, 6, 1000, nullptr);
|
||||
if (!smoke) SetTimer(window, 8, 250, nullptr);
|
||||
|
||||
@@ -161,6 +161,10 @@ class App
|
||||
bool stop{};
|
||||
UINT taskbarCreated{};
|
||||
bool trayRetryPending{};
|
||||
LanInputConnections trayInput;
|
||||
bool trayInputPulse{};
|
||||
bool updateTray(DWORD action, bool notifyFile = false);
|
||||
void refreshTrayInput();
|
||||
uint64_t transformAttempt{}, previousAttemptVersion{};
|
||||
size_t incomingLanFileCount{};
|
||||
bool incomingFileBalloon{};
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
+69
-21
@@ -110,7 +110,14 @@ void lan::wakeFilesPeer(const std::string &id)
|
||||
|
||||
struct LanService::Impl
|
||||
{
|
||||
struct Peer { std::string name,epoch; sockaddr_in address{}; uint64_t seen{},verified{}; bool files{}; };
|
||||
struct Peer
|
||||
{
|
||||
std::string name,epoch;
|
||||
sockaddr_in address{};
|
||||
uint64_t seen{},verified{};
|
||||
bool files{};
|
||||
bool present(uint64_t now)const{return verified && now-verified<lan::PeerLifetime;}
|
||||
};
|
||||
std::filesystem::path path;
|
||||
std::string id,epoch=lan::randomHex(16),name=hostName(),status="Disabled.";
|
||||
std::map<std::string,Peer> peers;
|
||||
@@ -129,7 +136,7 @@ struct LanService::Impl
|
||||
bool shareInput{};
|
||||
std::string inputPeer;
|
||||
int inputEdge=1;
|
||||
std::atomic<bool> inputConnected{false},abortInput{false};
|
||||
std::atomic<bool> abortInput{false};
|
||||
std::atomic<uint64_t> inputEpoch{0};
|
||||
std::atomic<uint64_t> inputConfiguration{0};
|
||||
std::atomic<bool> layoutChanged{false};
|
||||
@@ -139,6 +146,8 @@ struct LanService::Impl
|
||||
std::map<std::string,uint64_t> inputReady;
|
||||
std::unique_ptr<lan::InputMesh> router;
|
||||
std::string inputStatus="Input sharing disabled.";
|
||||
size_t inputConnectedPeers{}, inputOnlinePeers{};
|
||||
bool inputWorkerStopped{};
|
||||
bool inputNeedsHelp{};
|
||||
HWND inputWindow{};std::atomic<bool> inputNotification{false};
|
||||
explicit Impl(const std::filesystem::path &root,HWND window) : path(root/L"lan-pairing.bin"),inputWindow(window)
|
||||
@@ -212,6 +221,7 @@ struct LanService::Impl
|
||||
void start()
|
||||
{
|
||||
stopping=false; epoch=lan::randomHex(16); status="Searching for KSwitcher computers...";
|
||||
updateInputStatus(0,0,"Waiting for paired computers...",false);
|
||||
worker=std::thread([this]{ run(); });
|
||||
}
|
||||
void stop()
|
||||
@@ -219,17 +229,39 @@ struct LanService::Impl
|
||||
if(router)router->cancel(GetTickCount64());
|
||||
stopping=true;
|
||||
if(worker.joinable()) worker.join();
|
||||
inputConnected=false;++inputEpoch;
|
||||
{std::lock_guard lock(inputMutex);inputOut.clear();inputIn.clear();inputReady.clear();}
|
||||
std::lock_guard lock(mutex); pending.reset(); peers.clear();clipboard=std::make_unique<lan::ClipboardExchange>(id);
|
||||
transfers=std::make_unique<lan::ClipboardExchange>(id,"file-transfer");incomingFiles.clear();logDownload.reset();
|
||||
if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,0,FALSE);
|
||||
}
|
||||
void updateInputStatus(size_t connected,size_t online,std::string status,bool needsHelp,bool stopped=false)
|
||||
{
|
||||
bool changed;
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
changed=connected!=inputConnectedPeers||online!=inputOnlinePeers||stopped!=inputWorkerStopped;
|
||||
inputConnectedPeers=connected;
|
||||
inputOnlinePeers=online;
|
||||
inputWorkerStopped=stopped;
|
||||
inputStatus=std::move(status);
|
||||
inputNeedsHelp=needsHelp;
|
||||
}
|
||||
if(changed&&inputWindow)PostMessageW(inputWindow,LanInputStatusMessage,0,0);
|
||||
}
|
||||
void send(SOCKET socket,const sockaddr_in &address,const Json &j)
|
||||
{
|
||||
auto bytes=j.dump(); if(bytes.size()>2048) return;
|
||||
sendto(socket,bytes.data(),int(bytes.size()),0,(const sockaddr*)&address,sizeof(address));
|
||||
}
|
||||
Json discoveryAnnouncement(bool filesListening)const
|
||||
{
|
||||
auto hello=lan::envelope("hello",id);
|
||||
hello["name"]=name;
|
||||
hello["epoch"]=epoch;
|
||||
hello["clipboardSession"]=clipboard->session();
|
||||
hello["fileSession"]=transfers->session();
|
||||
hello["filesBrowse"]=filesListening;
|
||||
return hello;
|
||||
}
|
||||
std::string heartbeat(const std::string &from,const std::string &to,const std::string &a,const std::string &b)
|
||||
{ return "KSwitcher LAN v1|presence|"+from+"|"+to+"|"+a+"|"+b; }
|
||||
void receiveTransfers(uint64_t now)
|
||||
@@ -267,7 +299,7 @@ struct LanService::Impl
|
||||
}
|
||||
transfers->deliveries.clear();
|
||||
}
|
||||
void receive(SOCKET socket,const sockaddr_in &address,const Json &j,uint64_t now)
|
||||
void receive(SOCKET socket,const sockaddr_in &address,const Json &j,uint64_t now,bool filesListening)
|
||||
{
|
||||
if(j.value("app","")!="KSwitcher-LAN" || j.value("version",0)!=1) return;
|
||||
auto other=j.value("id",""); if(!lan::identifier(other)||other==id) return;
|
||||
@@ -278,19 +310,23 @@ struct LanService::Impl
|
||||
if(display.empty()||display.size()>128||!lan::identifier(session)||
|
||||
std::any_of(display.begin(),display.end(),[](unsigned char c){return c<32||c==127;})) return;
|
||||
// Discovery is untrusted and never grants input access.
|
||||
if(!peers.contains(other) && peers.size()>=64) return;
|
||||
const bool firstAnnouncement=!peers.contains(other);
|
||||
if(firstAnnouncement && peers.size()>=64) return;
|
||||
auto &peer=peers[other];
|
||||
// A fresh announcement rotates the challenge every three seconds; it
|
||||
// does not revoke a recent successful proof for the same address.
|
||||
// Only a valid presence response renews verified, so untrusted/replayed
|
||||
// announcements cannot extend its PeerLifetime expiry.
|
||||
if(peer.address.sin_addr.s_addr!=address.sin_addr.s_addr) peer.verified=0;
|
||||
const bool addressChanged=peer.address.sin_addr.s_addr!=address.sin_addr.s_addr;
|
||||
if(addressChanged) peer.verified=0;
|
||||
clipboard->peerSession(other,j.value("clipboardSession",""));
|
||||
transfers->peerSession(other,j.value("fileSession",""));
|
||||
peer.files=j.value("filesBrowse",false);
|
||||
peer.name=display; peer.epoch=session; peer.address=address; peer.seen=now;
|
||||
if(trusted.contains(other))
|
||||
{
|
||||
// A returning peer can prove presence right away using our current challenge.
|
||||
if(firstAnnouncement) send(socket,address,discoveryAnnouncement(filesListening));
|
||||
auto response=lan::envelope("presence",id); response["to"]=other; response["epoch"]=epoch;
|
||||
const auto &key=trusted[other].at("key");
|
||||
const auto challenge=heartbeat(id,other,epoch,session);
|
||||
@@ -409,13 +445,16 @@ struct LanService::Impl
|
||||
});
|
||||
clipboardActive=clipboard->active()||transfers->active();
|
||||
if(shareInput)for(auto &[peer,entry]:trusted.items())
|
||||
endpoints.push_back({peer,entry.at("key"),peers.contains(peer)?peers.at(peer).address.sin_addr.s_addr:0});
|
||||
{
|
||||
const auto found=peers.find(peer);
|
||||
const bool discovered=found!=peers.end()&&found->second.present(now);
|
||||
endpoints.push_back({.id=peer,.key=entry.at("key"),
|
||||
.address=discovered?found->second.address.sin_addr.s_addr:0,.discovered=discovered});
|
||||
}
|
||||
if(refreshFiles.exchange(false) || now>=nextHello)
|
||||
{
|
||||
epoch=lan::randomHex(16); // Fresh challenge prevents replayed presence from staying online.
|
||||
auto hello=lan::envelope("hello",id); hello["name"]=name; hello["epoch"]=epoch;hello["clipboardSession"]=clipboard->session();
|
||||
hello["fileSession"]=transfers->session();
|
||||
hello["filesBrowse"]=filesListening;
|
||||
const auto hello=discoveryAnnouncement(filesListening);
|
||||
for(auto ip:broadcasts()) { auto address=bound; address.sin_addr.s_addr=ip; send(socket,address,hello); }
|
||||
nextHello=now+3000;
|
||||
}
|
||||
@@ -434,7 +473,7 @@ struct LanService::Impl
|
||||
{std::lock_guard lock(inputMutex);out.swap(inputOut);}
|
||||
if(abortInput.exchange(false)){hub.disconnect();out.clear();}
|
||||
hub.poll(endpoints,out,in,now);
|
||||
auto readyPeers=hub.ready();inputConnected=!readyPeers.empty();
|
||||
auto readyPeers=hub.ready();const auto connected=readyPeers.size();
|
||||
{std::lock_guard lock(inputMutex);inputReady=std::move(readyPeers);
|
||||
for(auto &frame:in){
|
||||
if(!inputIn.empty()&&inputIn.back().peer==frame.peer&&inputIn.back().epoch==frame.epoch){
|
||||
@@ -447,8 +486,10 @@ struct LanService::Impl
|
||||
}
|
||||
if(!in.empty()&&inputWindow&&!inputNotification.exchange(true))
|
||||
if(!PostMessageW(inputWindow,LanInputReadyMessage,0,0))inputNotification=false;
|
||||
{std::lock_guard lock(mutex);inputStatus=hub.status();inputNeedsHelp=hub.needsHelp();}
|
||||
fd_set read; FD_ZERO(&read); FD_SET(socket,&read); timeval delay{0,!endpoints.empty()||clipboardActive?5000:100000};
|
||||
const auto online=hub.onlinePeers();
|
||||
updateInputStatus(connected,online,online||endpoints.empty()?hub.status():
|
||||
"All paired PCs are offline. Waiting for LAN discovery.",hub.needsHelp());
|
||||
fd_set read; FD_ZERO(&read); FD_SET(socket,&read); timeval delay{0,online||clipboardActive?5000:100000};
|
||||
int ready=select(0,&read,nullptr,nullptr,&delay);
|
||||
if(ready==SOCKET_ERROR) throw std::runtime_error("LAN discovery socket failed.");
|
||||
if(ready>0) for(int count=0;count<64;++count)
|
||||
@@ -463,15 +504,16 @@ struct LanService::Impl
|
||||
bool allowed=false;auto peer=j.value("id","");
|
||||
{std::lock_guard lock(mutex);allowed=shareInput&&trusted.contains(peer)&&peers.contains(peer)&&peers.at(peer).address.sin_addr.s_addr==sender.sin_addr.s_addr;}
|
||||
if(allowed)hub.receiveDatagram(j,GetTickCount64());
|
||||
}else {std::lock_guard lock(mutex);receive(socket,sender,j,GetTickCount64());}
|
||||
}else {std::lock_guard lock(mutex);receive(socket,sender,j,GetTickCount64(),filesListening);}
|
||||
}
|
||||
catch(const Json::exception &) {} // Malformed network data cannot interrupt discovery.
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(const std::exception &e) { std::lock_guard lock(mutex); status=std::string("LAN stopped: ")+e.what(); }
|
||||
inputConnected=false;++inputEpoch;
|
||||
{std::lock_guard lock(mutex);if(shareInput)inputStatus="Input connection closed.";}
|
||||
{std::lock_guard lock(inputMutex);inputOut.clear();inputIn.clear();inputReady.clear();}
|
||||
++inputEpoch;
|
||||
updateInputStatus(0,0,"Input connection closed.",false,true);
|
||||
if(socket!=INVALID_SOCKET) closesocket(socket);
|
||||
if(winsock) WSACleanup();
|
||||
}
|
||||
@@ -503,8 +545,7 @@ struct LanService::Impl
|
||||
{
|
||||
auto peer=j.at("peer").get<std::string>();
|
||||
const auto checkPeer = [&] {
|
||||
if(!enabled||!trusted.contains(peer)||!peers.contains(peer)||!peers.at(peer).verified||
|
||||
now-peers.at(peer).verified>=lan::PeerLifetime)
|
||||
if(!enabled||!trusted.contains(peer)||!peers.contains(peer)||!peers.at(peer).present(now))
|
||||
throw std::runtime_error("Select an online paired computer.");
|
||||
if(!transfers->hasSession(peer))
|
||||
throw std::runtime_error("Update KSwitcher on the selected computer to use file transfers.");
|
||||
@@ -628,7 +669,7 @@ struct LanService::Impl
|
||||
status="Pair removed on this computer.";
|
||||
}
|
||||
Json result={{"enabled",enabled},{"id",id},{"name",name},{"status",status},{"pending",pending&&!pending->confirmed},{"peers",Json::array()},
|
||||
{"positions",positions},{"shareInput",shareInput},{"inputPeer",inputPeer},{"controlPeer",router?router->peer():std::string{}},{"inputEdge",inputEdge},{"inputConnected",inputConnected.load()},
|
||||
{"positions",positions},{"shareInput",shareInput},{"inputPeer",inputPeer},{"controlPeer",router?router->peer():std::string{}},{"inputEdge",inputEdge},{"inputConnected",inputConnectedPeers!=0},
|
||||
{"inputStatus",enabled&&shareInput?inputStatus:"Input sharing disabled."},{"inputNeedsHelp",enabled&&shareInput&&inputNeedsHelp},{"controlMode",router?int(router->mode()):0}};
|
||||
{std::lock_guard inputLock(inputMutex);result["inputReady"]=inputReady;}
|
||||
result["shareLogs"]=shareLogs;
|
||||
@@ -649,7 +690,7 @@ struct LanService::Impl
|
||||
if(action=="filesPeers" && !trusted.contains(peer)) continue;
|
||||
char ip[INET_ADDRSTRLEN]{}; InetNtopA(AF_INET,(void*)&p.address.sin_addr,ip,sizeof(ip));
|
||||
result["peers"].push_back({{"id",peer},{"name",p.name},{"address",ip},{"paired",trusted.contains(peer)},
|
||||
{"verified",p.verified && now-p.verified<lan::PeerLifetime},{"online",true},
|
||||
{"verified",p.present(now)},{"online",true},
|
||||
{"fileTransfer",transfers->hasSession(peer)},{"filesBrowse",p.files}});
|
||||
}
|
||||
for(const auto &[peer,p]:trusted.items()) if(!peers.contains(peer))
|
||||
@@ -682,6 +723,13 @@ std::vector<LanClipboard> LanService::takeClipboard()
|
||||
impl->clipboard->deliveries.clear();return result;
|
||||
}
|
||||
bool LanService::inputEnabled()const{return impl->enabled&&impl->shareInput;}
|
||||
LanInputConnections LanService::inputConnections()const
|
||||
{
|
||||
std::lock_guard lock(impl->mutex);
|
||||
if(!inputEnabled())return {};
|
||||
const auto paired=impl->trusted.size();
|
||||
return {std::min(impl->inputConnectedPeers,paired),std::min(impl->inputOnlinePeers,paired),paired,impl->inputWorkerStopped};
|
||||
}
|
||||
bool LanService::tickInput(bool allowEnter){return impl->tickInput(allowEnter);}
|
||||
bool LanService::keyboard(const KBDLLHOOKSTRUCT &k,bool down){return impl->router&&impl->router->keyboard(k,down,GetTickCount64());}
|
||||
bool LanService::mouse(UINT message,const MSLLHOOKSTRUCT &m,bool allowEnter){return impl->router&&impl->router->mouse(message,m,GetTickCount64(),allowEnter);}
|
||||
|
||||
@@ -7,7 +7,15 @@ namespace ks
|
||||
inline constexpr UINT LanInputReadyMessage=WM_APP+67, LanClipboardReadyMessage=WM_APP+68, LanClipboardPublishMessage=WM_APP+69;
|
||||
inline constexpr UINT LanFilesChangedMessage=WM_APP+70;
|
||||
inline constexpr UINT LanUpdateRequestedMessage=WM_APP+90;
|
||||
inline constexpr UINT LanInputStatusMessage=WM_APP+91;
|
||||
struct LanClipboard {std::string peer,name,app;Bytes data;DWORD sequence{};};
|
||||
struct LanInputConnections
|
||||
{
|
||||
size_t connected{}, online{}, paired{};
|
||||
bool stopped{};
|
||||
bool reconnecting()const{return !stopped&&connected<online;}
|
||||
bool operator==(const LanInputConnections &) const = default;
|
||||
};
|
||||
// Discovery, pairing and optional encrypted input within the resident process.
|
||||
class LanService
|
||||
{
|
||||
@@ -21,6 +29,7 @@ class LanService
|
||||
void publishClipboard(Bytes, const std::string &);
|
||||
std::vector<LanClipboard> takeClipboard();
|
||||
bool inputEnabled() const;
|
||||
LanInputConnections inputConnections() const;
|
||||
bool tickInput(bool allowEnter = true);
|
||||
bool keyboard(const KBDLLHOOKSTRUCT &, bool down);
|
||||
bool mouse(UINT, const MSLLHOOKSTRUCT &, bool allowEnter);
|
||||
|
||||
+25
-11
@@ -213,6 +213,7 @@ bool InputChannel::adopt(uintptr_t accepted,uint64_t now)
|
||||
impl->connecting=false;impl->begin(now);impl->socket=SOCKET(accepted);return true;
|
||||
}
|
||||
bool InputChannel::ready()const{return impl->authenticated;}
|
||||
bool InputChannel::handshaking()const{return impl->socket!=INVALID_SOCKET&&!impl->authenticated;}
|
||||
uint64_t InputChannel::generation()const{return impl->changed;}
|
||||
std::string InputChannel::status()const{
|
||||
return impl->lastError.empty() ? impl->state : impl->lastError+" Retrying automatically.";
|
||||
@@ -221,7 +222,16 @@ void InputChannel::disconnect(){impl->reset(GetTickCount64(),"Input disconnected
|
||||
std::string InputChannel::transport()const{return impl->reverse?"reverse TCP":"direct TCP";}
|
||||
struct InputHub::Impl
|
||||
{
|
||||
struct Link { InputEndpoint endpoint;std::unique_ptr<InputChannel> channel;std::unique_ptr<InputDatagram> udp;uint64_t generation{},epoch{},since{},failedSince{};bool udpReady{};std::string lastState; };
|
||||
struct Link
|
||||
{
|
||||
InputEndpoint endpoint;
|
||||
std::unique_ptr<InputChannel> channel;
|
||||
std::unique_ptr<InputDatagram> udp;
|
||||
uint64_t generation{},epoch{},since{},failedSince{};
|
||||
bool udpReady{};
|
||||
std::string lastState;
|
||||
bool ready()const{return channel->ready()||udp->ready();}
|
||||
};
|
||||
struct Pending {SOCKET socket;uint32_t address;uint64_t since;};
|
||||
std::string local;uint16_t port;SOCKET listener=INVALID_SOCKET;
|
||||
std::map<std::string,Link> links;std::vector<Pending> pending;uint64_t epoch{},retry{};
|
||||
@@ -235,17 +245,18 @@ struct InputHub::Impl
|
||||
currentTime=now;
|
||||
for(auto it=links.begin();it!=links.end();){
|
||||
auto match=std::find_if(endpoints.begin(),endpoints.end(),[&](auto &e){return e.id==it->first&&e.key==it->second.endpoint.key&&e.port==it->second.endpoint.port;});
|
||||
if(match==endpoints.end())it=links.erase(it);else ++it;
|
||||
// Discovery gates new attempts. An authenticated connection can outlive discovery.
|
||||
if(match==endpoints.end()||(!match->discovered&&!it->second.ready()))it=links.erase(it);else ++it;
|
||||
}
|
||||
for(auto &e:endpoints)if(e.id!=local&&!links.contains(e.id)){
|
||||
for(auto &e:endpoints)if(e.discovered&&e.id!=local&&!links.contains(e.id)){
|
||||
Link link;link.endpoint=e;link.channel=std::make_unique<InputChannel>(local,e.id,e.key,0,e.port,true);
|
||||
link.udp=std::make_unique<InputDatagram>(local,e.id,e.key);link.since=link.failedSince=now;link.epoch=++epoch;links.emplace(e.id,std::move(link));
|
||||
}
|
||||
// Discovery is a hint, not the lifetime of authenticated input sessions.
|
||||
// Keep the last usable address across missed announcements. A new address
|
||||
// is used only once a channel is down, never to tear down working input.
|
||||
for(auto &e:endpoints){if(e.id==local)continue;auto &link=links.at(e.id);
|
||||
if(e.address&&!link.channel->ready()&&e.address!=link.endpoint.address){
|
||||
for(auto &e:endpoints){if(!e.discovered||e.id==local)continue;auto &link=links.at(e.id);
|
||||
if(e.address&&!link.ready()&&e.address!=link.endpoint.address){
|
||||
link.channel->disconnect();link.endpoint.address=e.address;
|
||||
}
|
||||
}
|
||||
@@ -279,14 +290,16 @@ struct InputHub::Impl
|
||||
}
|
||||
for(auto &[id,link]:links){
|
||||
std::vector<InputFrame> frames,received;for(auto &f:out)if(f.peer==id&&(!f.epoch||f.epoch==link.epoch))enqueueInput(frames,f.frame);
|
||||
if(sendDatagram&&!link.channel->ready()&&!link.udp->active()&&local<id&&now-link.since>=5000){link.udp->start(now);link.channel->disconnect();frames.clear();}
|
||||
// Let an in-flight TCP connection finish or hit its own deadline.
|
||||
// Check before poll() so another TCP retry cannot starve UDP fallback.
|
||||
if(sendDatagram&&!link.channel->ready()&&!link.channel->handshaking()&&
|
||||
!link.udp->active()&&local<id&&now-link.since>=5000){link.udp->start(now);frames.clear();}
|
||||
if(link.udp->active()){
|
||||
link.udp->poll(frames,received,now,sendDatagram);
|
||||
if(!link.udp->active()){link.since=now;link.channel->disconnect();received.clear();}
|
||||
}else link.channel->poll(link.endpoint.address,frames,received,now);
|
||||
if(link.udpReady!=link.udp->ready()){link.udpReady=link.udp->ready();link.epoch=++epoch;}
|
||||
bool ready=link.channel->ready()||link.udp->ready();
|
||||
if(ready)link.failedSince=link.since=now;
|
||||
if(link.ready())link.failedSince=link.since=now;
|
||||
auto state=link.udp->ready()?"Input connected via encrypted UDP.":link.udp->active()?"Trying encrypted UDP over discovery...":link.channel->ready()?"Input connected via "+link.channel->transport()+".":link.channel->status();
|
||||
if(state!=link.lastState){link.lastState=state;log(L"LAN input peer "+wide(id.substr(0,8))+L": "+wide(state));}
|
||||
if(link.generation!=link.channel->generation()){link.generation=link.channel->generation();link.epoch=++epoch;}
|
||||
@@ -297,7 +310,8 @@ struct InputHub::Impl
|
||||
InputHub::InputHub(std::string id,uint16_t port):impl(std::make_unique<Impl>(std::move(id),port)){}
|
||||
InputHub::~InputHub()=default;
|
||||
void InputHub::poll(const std::vector<InputEndpoint> &peers,const std::vector<RoutedInput> &out,std::vector<RoutedInput> &in,uint64_t now){impl->poll(peers,out,in,now);}
|
||||
std::map<std::string,uint64_t> InputHub::ready()const{std::map<std::string,uint64_t> result;for(auto &[id,l]:impl->links)if(l.channel->ready()||l.udp->ready())result[id]=l.epoch;return result;}
|
||||
std::map<std::string,uint64_t> InputHub::ready()const{std::map<std::string,uint64_t> result;for(auto &[id,l]:impl->links)if(l.ready())result[id]=l.epoch;return result;}
|
||||
size_t InputHub::onlinePeers()const{return impl->links.size();}
|
||||
std::string InputHub::status()const{
|
||||
auto count=ready().size();if(count==impl->links.size()&&count){
|
||||
std::string routes;for(auto &[id,l]:impl->links){if(!routes.empty())routes+=", ";routes+=id.substr(0,8)+": "+(l.udp->ready()?"encrypted UDP":l.channel->transport());}
|
||||
@@ -305,7 +319,7 @@ std::string InputHub::status()const{
|
||||
}
|
||||
if(needsHelp())return "Automatic connection attempts have not succeeded for every PC. Enable input on both PCs. Open Connection help for firewall commands.";
|
||||
if(!impl->error.empty())return impl->error;
|
||||
for(auto &[id,l]:impl->links)if(!l.channel->ready()&&!l.udp->ready())return l.lastState;
|
||||
for(auto &[id,l]:impl->links)if(!l.ready())return l.lastState;
|
||||
return "Waiting for paired computers...";
|
||||
}
|
||||
void InputHub::disconnect(){for(auto &[id,l]:impl->links){l.channel->disconnect();l.udp->reset();l.since=impl->currentTime;}}
|
||||
@@ -318,7 +332,7 @@ void InputHub::receiveDatagram(const Json &j,uint64_t now){
|
||||
if(!active&&link.udp->active())link.channel->disconnect();
|
||||
}
|
||||
bool InputHub::needsHelp()const{
|
||||
for(auto &[id,l]:impl->links)if(!l.channel->ready()&&!l.udp->ready()&&impl->currentTime-l.failedSince>=15000)return true;
|
||||
for(auto &[id,l]:impl->links)if(!l.ready()&&impl->currentTime-l.failedSince>=15000)return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+9
-1
@@ -55,12 +55,19 @@ class InputChannel
|
||||
void poll(uint32_t peerAddress,const std::vector<InputFrame> &out,std::vector<InputFrame> &in,uint64_t now);
|
||||
bool adopt(uintptr_t socket,uint64_t now);
|
||||
bool ready() const;
|
||||
bool handshaking() const;
|
||||
uint64_t generation() const;
|
||||
std::string status() const;
|
||||
void disconnect();
|
||||
std::string transport()const;
|
||||
};
|
||||
struct InputEndpoint {std::string id,key;uint32_t address{};uint16_t port=45884;};
|
||||
struct InputEndpoint
|
||||
{
|
||||
std::string id,key;
|
||||
uint32_t address{};
|
||||
uint16_t port=45884;
|
||||
bool discovered=true;
|
||||
};
|
||||
struct RoutedInput {std::string peer;InputFrame frame;uint64_t epoch{};};
|
||||
class InputHub
|
||||
{
|
||||
@@ -70,6 +77,7 @@ class InputHub
|
||||
~InputHub();
|
||||
void poll(const std::vector<InputEndpoint> &,const std::vector<RoutedInput> &,std::vector<RoutedInput> &,uint64_t now);
|
||||
std::map<std::string,uint64_t> ready()const;
|
||||
size_t onlinePeers()const;
|
||||
std::string status()const;
|
||||
void disconnect();
|
||||
using SendDatagram=std::function<void(const std::string &,const Json &)>;
|
||||
|
||||
+16
-4
@@ -211,9 +211,18 @@ void InputRouter::receive(const InputFrame &f,uint64_t now)
|
||||
if(!connected||!env.desktop()){cancel(now);return;}
|
||||
if(f.type==InputType::Enter)
|
||||
{
|
||||
if(!f.token||f.a<0||f.a>3||(!multi&&f.a!=(edge^1))||f.b<0||f.b>65535||held()||returning||
|
||||
mode_==ControlMode::Sending||mode_==ControlMode::Receiving||(mode_==ControlMode::Requesting&&preferLocal))
|
||||
{post({InputType::Return,f.token,32768});return;}
|
||||
const wchar_t *declined=nullptr;
|
||||
if(!f.token||f.a<0||f.a>3||(!multi&&f.a!=(edge^1))||f.b<0||f.b>65535)
|
||||
declined=L"invalid edge or position";
|
||||
else if(held())declined=L"a local key or mouse button is held";
|
||||
else if(returning||mode_==ControlMode::Sending||mode_==ControlMode::Receiving||
|
||||
(mode_==ControlMode::Requesting&&preferLocal))
|
||||
declined=L"another handoff is active";
|
||||
if(declined)
|
||||
{
|
||||
log(std::wstring(L"LAN input: declined cursor handoff: ")+declined);
|
||||
post({InputType::Return,f.token,32768});return;
|
||||
}
|
||||
if(mode_==ControlMode::Requesting)cancel(now);
|
||||
if(multi)edge=f.a^1;
|
||||
crossEdge=-1;token=f.token;remainderX=remainderY=0;mode(ControlMode::Receiving);
|
||||
@@ -231,7 +240,10 @@ void InputRouter::receive(const InputFrame &f,uint64_t now)
|
||||
return;
|
||||
}
|
||||
if(f.token!=token||!token)return;
|
||||
if(f.type==InputType::Return){log(L"LAN input: peer returned control");local(now,std::clamp(f.a,0,65535));return;}
|
||||
if(f.type==InputType::Return){
|
||||
log(mode_==ControlMode::Requesting?L"LAN input: peer declined cursor handoff":L"LAN input: peer returned control");
|
||||
local(now,std::clamp(f.a,0,65535));return;
|
||||
}
|
||||
if(mode_!=ControlMode::Receiving)return;
|
||||
bool ok=true;
|
||||
if(f.type==InputType::Move)
|
||||
|
||||
@@ -50,6 +50,7 @@ class InputMesh
|
||||
if(!ready.contains(peer)||!positions.contains(peer))return;
|
||||
if(f.type==InputType::Enter){
|
||||
if(!allowEnter||f.a<0||f.a>3||(router.mode()!=ControlMode::Local&&active!=peer)){
|
||||
if(!allowEnter)log(L"LAN input: declined cursor handoff during a local text operation or shortcut capture");
|
||||
send(peer,{InputType::Return,f.token,32768});return;
|
||||
}
|
||||
if(router.mode()==ControlMode::Local)select(peer,f.a^1,now);
|
||||
|
||||
+29
-11
@@ -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 {};
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
#include "platform.h"
|
||||
namespace ks
|
||||
{
|
||||
inline constexpr wchar_t AppVersion[] = L"0.6.120";
|
||||
inline constexpr wchar_t AppVersion[] = L"0.6.123";
|
||||
inline constexpr UINT UpdateMessage = WM_APP + 7;
|
||||
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
|
||||
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
|
||||
|
||||
@@ -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}");
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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");
|
||||
|
||||
+64
-4
@@ -319,10 +319,10 @@ void hubChecks()
|
||||
while((hubs[0]->ready().size()!=2||hubs[1]->ready().size()!=2||hubs[2]->ready().size()!=2)&&GetTickCount64()<deadline)pump();
|
||||
check(hubs[0]->ready().size()==2&&hubs[1]->ready().size()==2&&hubs[2]->ready().size()==2,"three TCP hubs authenticate all independent pair channels on one listener per PC");
|
||||
auto generation=hubs[0]->ready();
|
||||
for(auto &list:endpoints)for(auto &e:list)e.address=0;
|
||||
for(auto &list:endpoints)for(auto &e:list){e.address=0;e.discovered=false;}
|
||||
for(int n=0;n<20;++n)pump();
|
||||
check(hubs[0]->ready()==generation&&hubs[1]->ready().size()==2&&hubs[2]->ready().size()==2,"expired discovery does not destroy authenticated channels");
|
||||
for(auto &list:endpoints)for(auto &e:list)e.address=htonl(INADDR_LOOPBACK);
|
||||
for(auto &list:endpoints)for(auto &e:list){e.address=htonl(INADDR_LOOPBACK);e.discovered=true;}
|
||||
InputFrame keyFrame{InputType::Key,7,'A',0,1},cross{InputType::Cross,8,2,30000};
|
||||
hubs[0]->poll(endpoints[0],{{ids[1],keyFrame},{ids[2],cross}},incoming[0],GetTickCount64());
|
||||
for(int n=0;n<100&&(incoming[1].empty()||incoming[2].empty());++n)pump();
|
||||
@@ -340,16 +340,76 @@ void hubChecks()
|
||||
for(int n=0;n<300&&(server.ready().empty()||client.ready().empty());++n){
|
||||
server.poll(unknown,{},a,GetTickCount64());client.poll(known,{},b,GetTickCount64());Sleep(1);
|
||||
}
|
||||
check(server.ready().size()==1&&client.ready().size()==1,"saved pair listens and authenticates without receiving a discovery announcement");
|
||||
check(server.ready().size()==1&&client.ready().size()==1,"available peer can accept inbound TCP without dialing");
|
||||
}
|
||||
endpoints[0].erase(endpoints[0].begin());hubs[0]->poll(endpoints[0],{},incoming[0],GetTickCount64()+1800);
|
||||
check(!hubs[0]->ready().contains(ids[1])&&hubs[0]->ready().contains(ids[2]),"forgetting one pair revokes only its channel");
|
||||
}
|
||||
void offlineDiscoveryChecks()
|
||||
{
|
||||
WSADATA data{};if(WSAStartup(MAKEWORD(2,2),&data))throw std::runtime_error("WSAStartup");
|
||||
struct Close{~Close(){WSACleanup();}} close;
|
||||
std::string a(32,'a'),b(32,'b'),key(64,'f');
|
||||
const auto pa=freePort(),pb=freePort();
|
||||
InputHub left(a,pa),right(b,pb);
|
||||
std::vector<InputEndpoint> ea{{b,key,htonl(INADDR_LOOPBACK),pb,false}},eb{{a,key,htonl(INADDR_LOOPBACK),pa,false}};
|
||||
std::vector<RoutedInput> ia,ib;
|
||||
int datagrams=0;
|
||||
left.datagrams([&](const auto &,const auto &){++datagrams;});
|
||||
auto now=GetTickCount64();
|
||||
auto pump=[&](uint64_t step=1){now+=step;right.poll(eb,{},ib,now);left.poll(ea,{},ia,now);};
|
||||
auto checkIdle=[&]{
|
||||
check(left.onlinePeers()==0&&left.ready().empty()&&!left.needsHelp()&&datagrams==0,
|
||||
"offline saved peer does not trigger input retries or connection help");
|
||||
SOCKET probe=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
|
||||
sockaddr_in addr{};addr.sin_family=AF_INET;addr.sin_addr.s_addr=htonl(INADDR_LOOPBACK);addr.sin_port=htons(pa);
|
||||
int result=connect(probe,(sockaddr*)&addr,sizeof(addr));
|
||||
const auto error=WSAGetLastError();closesocket(probe);
|
||||
check(result==SOCKET_ERROR&&error==WSAECONNREFUSED,"input TCP listener is closed while all peers are offline");
|
||||
};
|
||||
pump();pump(20000);checkIdle();
|
||||
auto rediscover=[&]{
|
||||
ea.front().discovered=eb.front().discovered=true;
|
||||
for(int n=0;n<200&&(left.ready().empty()||right.ready().empty());++n){pump(20);Sleep(1);}
|
||||
check(left.onlinePeers()==1&&left.ready().contains(b)&&right.ready().contains(a),
|
||||
"input TCP connects when the saved peer reappears in discovery");
|
||||
};
|
||||
rediscover();
|
||||
const auto oldEpoch=left.ready().at(b);
|
||||
ea.front().discovered=false;
|
||||
eb.clear(); // The other instance stops while discovery is already stale.
|
||||
for(int n=0;n<30;++n){pump(20);Sleep(1);}
|
||||
pump(20000);checkIdle();
|
||||
eb={{a,key,htonl(INADDR_LOOPBACK),pa,false}};
|
||||
rediscover();
|
||||
check(left.ready().at(b)!=oldEpoch,"rediscovery replaces the disconnected input generation");
|
||||
}
|
||||
void fallbackChecks()
|
||||
{
|
||||
WSADATA data{};if(WSAStartup(MAKEWORD(2,2),&data))throw std::runtime_error("WSAStartup");
|
||||
struct Close{~Close(){WSACleanup();}} close;
|
||||
std::string a(32,'a'),b(32,'b'),key(64,'f');
|
||||
{
|
||||
auto pa=freePort(),pb=freePort();InputHub left(a,pa),right(b,pb);
|
||||
std::vector<InputEndpoint> ea{{b,key,htonl(INADDR_LOOPBACK),pb}},eb{{a,key,0}};
|
||||
std::vector<RoutedInput> ia,ib;
|
||||
int datagrams=0;
|
||||
left.datagrams([&](const auto &,const auto &){++datagrams;});
|
||||
auto now=GetTickCount64();
|
||||
right.poll(eb,{},ib,now); // Listen, but delay reading and authenticating the TCP connection.
|
||||
left.poll(ea,{},ia,now);
|
||||
for(int n=0;n<100&&left.status().find("authenticating")==std::string::npos;++n){
|
||||
Sleep(1);left.poll(ea,{},ia,now+1);
|
||||
}
|
||||
check(left.status().find("authenticating")!=std::string::npos,"TCP connection is waiting for the peer handshake");
|
||||
now+=6000;
|
||||
left.poll(ea,{},ia,now);
|
||||
for(int n=0;n<100&&(left.ready().empty()||right.ready().empty());++n){
|
||||
++now;right.poll(eb,{},ib,now);left.poll(ea,{},ia,now);Sleep(1);
|
||||
}
|
||||
check(left.ready().contains(b)&&right.ready().contains(a)&&datagrams==0,
|
||||
"UDP fallback does not cancel a TCP handshake within its deadline");
|
||||
}
|
||||
for(bool udp:{false,true}){
|
||||
auto pa=freePort(),pb=freePort(),blocked=freePort();InputHub left(a,pa),right(b,pb);
|
||||
std::vector<InputEndpoint> ea{{b,key,htonl(INADDR_LOOPBACK),blocked}},eb{{a,key,htonl(INADDR_LOOPBACK),udp?blocked:pa}};
|
||||
@@ -507,6 +567,6 @@ void channelChecks()
|
||||
}
|
||||
int main()
|
||||
{
|
||||
try{channelChecks();hubChecks();fallbackChecks();datagramChecks();routerChecks();meshChecks();std::cout<<"Passed "<<passed<<" LAN input checks\n";}
|
||||
try{channelChecks();hubChecks();offlineDiscoveryChecks();fallbackChecks();datagramChecks();routerChecks();meshChecks();std::cout<<"Passed "<<passed<<" LAN input checks\n";}
|
||||
catch(const std::exception &e){std::cerr<<"FAIL: "<<e.what()<<'\n';return 1;}
|
||||
}
|
||||
Reference in new issue
Block a user