From 1407b4d260fc2fae42951b17e9536155b5898cd1 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Fri, 13 Nov 2026 12:22:52 +0200 Subject: [PATCH] Release KSwitcher v0.6.74 with LAN file transfer and diagnostics MCP --- CMakeLists.txt | 2 +- LAN-PREVIEW.md | 28 ++++- Release/README.md | 9 ++ Release/SHA256SUMS.txt | 2 +- Release/release-files.json | 44 ++++---- resources/app.rc | 6 +- src/config_main.cpp | 24 ++++- src/lan.cpp | 145 ++++++++++++++++++++++++- src/lan_clipboard.h | 53 ++++++--- src/lan_log.h | 22 ++++ src/mcp_logs.h | 109 +++++++++++++++++++ src/ui.cpp | 216 +++++++++++++++++++++++++++++++++---- src/ui_lan.inl | 95 +++++++++++++++- src/ui_log.inl | 6 +- src/update.h | 2 +- tests/chat_profiles.cpp | 32 ++++-- tests/input.cpp | 2 +- tests/lan_clipboard.cpp | 31 ++++++ 18 files changed, 738 insertions(+), 90 deletions(-) create mode 100644 src/lan_log.h create mode 100644 src/mcp_logs.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 7d45f39..33391ea 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.24) -project(KSwitcher VERSION 0.6.73 LANGUAGES CXX RC) +project(KSwitcher VERSION 0.6.74 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 aa767ed..efdb849 100644 --- a/LAN-PREVIEW.md +++ b/LAN-PREVIEW.md @@ -5,8 +5,32 @@ code on both computers, and shares mouse and keyboard through a screen edge. The module runs inside the resident process. Multiple paired computers can be arranged on a monitor grid. Mouse and keyboard follow neighboring cells, including A → B → C, without relaying input through B. New text and images are also shared -with all online paired computers: history and the active clipboard. File transfer -is not implemented by clipboard synchronization. +with all online paired computers: history and the active clipboard. + +## Files and diagnostic logs + +In **Settings → Computers → Manage computers…**, select an online paired +computer and choose **Send file…**. Both computers need a build with file transfer. +Files up to 16 MiB travel over encrypted LAN. On the destination, open +**Incoming files…** to save or discard each file. Pending files are held in +memory until saved, discarded, or KSwitcher closes. + +To retrieve the current or rotated diagnostic log, enable **Allow paired +computers to download diagnostic logs** on the computer that owns the logs. +This setting defaults to off. On the requesting PC, select that computer and +choose **Download log…** or **Previous log…**. Diagnostic logs may contain +text copied from applications. + +### MCP + +In **Settings → MCP**, choose **Copy configuration** and paste the block into +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 +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. ## Set up multiple computers diff --git a/Release/README.md b/Release/README.md index 0129a7a..a023489 100644 --- a/Release/README.md +++ b/Release/README.md @@ -1,5 +1,14 @@ # Latest Windows release +## 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**. +- Download current and previous diagnostic logs from paired PCs that explicitly allow remote log downloads. +- Copy the Codex configuration from **Settings → MCP**. The MCP server lists paired PCs and reads local or remote diagnostic logs. +- Search contacts in the **Languages for a chat** table. **Copy selected** in Diagnostics now uses normal clipboard synchronization. + +**Українською.** Передавайте файли до 16 МіБ вибраному спареному ПК зашифрованою локальною мережею. У **Incoming files** можна зберегти або відхилити файл. Поточний і попередній журнали доступні для завантаження після ввімкнення відповідного дозволу на віддаленому ПК. У **Settings → MCP** можна скопіювати конфігурацію Codex для читання локальних і віддалених журналів. У таблиці **Languages for a chat** додано пошук контактів, а **Copy selected** у діагностиці тепер проходить через звичайну синхронізацію буфера. + ## v0.6.73 — 2026-11-13 After moving KSwitcher, launch it from its current folder. If Windows autostart diff --git a/Release/SHA256SUMS.txt b/Release/SHA256SUMS.txt index a5a6be5..e467868 100644 --- a/Release/SHA256SUMS.txt +++ b/Release/SHA256SUMS.txt @@ -1 +1 @@ -5e47e81f7e96ef0c32d4f6322d8463f4f30b49e44da20052d8351c81b2451867 KSwitcher-win-x64.zip +d7f2a0667a5dd3e2bc05b2a3c1900eaddd356343f03f53747fdfd4334ca74b3f KSwitcher-win-x64.zip diff --git a/Release/release-files.json b/Release/release-files.json index 191a67c..d76394c 100644 --- a/Release/release-files.json +++ b/Release/release-files.json @@ -1,86 +1,86 @@ { - "version": "0.6.73", + "schema": 1, "files": [ { - "size": 2208256, "path": "KSwitcher.exe", - "sha256": "9c03c121f81221fb2455dd87a13cba27d2870539e323792371d2874ac0ae92a5" + "size": 2243072, + "sha256": "da74c9b6986235d95a66d2f1220d436e83e43ce5e73f5132d7c854c823e559fd" }, { - "size": 2130432, "path": "KSwitcher.Config.exe", - "sha256": "07f18fd579c74b11ebf5cdf8fea27f827cc63de9cccf1402e2f6f87edc9a5269" + "size": 2249216, + "sha256": "0c290ec58befca6ad0b28b9a5d6a5c11b9edbd6c93fb9015dfaefe7a45d82e2e" }, { - "size": 3210240, "path": "KSwitcher.Screenshot.exe", - "sha256": "c426684eb1b081da81adf16f4ccfc3c4a684ce1aae5feb5a75448165ba64b493" + "size": 3244032, + "sha256": "c90aa8bb0c5e37b64b1c1db98cd9618f7bf0ff2941a80a6029f80fe248d2001b" }, { - "size": 4401, "path": "LICENSE", + "size": 4401, "sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c" }, { - "size": 1075, "path": "json-LICENSE.txt", + "size": 1075, "sha256": "c0d068392ea65358b798b8c165103560f06e9e3b38c4ab4e2d8810a7b931af86" }, { - "size": 93756, "path": "README.md", + "size": 93756, "sha256": "1d1307356a3db561cf3a685eb90b5b524e9e62f9d8acb116a412d5f41242128f" }, { - "size": 9908, "path": "LAN-PREVIEW.md", - "sha256": "4a673e44dc42fff45ba8b944413b5b5adddca7100c7eccd1c5010dccc5762e41" + "size": 11201, + "sha256": "26d848df3b106882775ebe8918f2b3ae59ab3be81b713abb90831ed8a2243e8b" }, { - "size": 682867, "path": "dictionaries/en.txt", + "size": 682867, "sha256": "5f267c141c3d6837870e1c098f86b89a113ba300343119432644ead88f720c21" }, { - "size": 20138, "path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt", + "size": 20138, "sha256": "28a9529c7d0bb4dc51f4bf5c116a3d16ef247a052f7591466768ddf563fd1cf5" }, { - "size": 2230, "path": "dictionaries/README.md", + "size": 2230, "sha256": "2df17fe4e17d527c67ab57269b07dce59a49c1fb128c429a1408decbb47109ec" }, { - "size": 1060364, "path": "dictionaries/ru.txt", + "size": 1060364, "sha256": "9ef922c7699569304a428f6aba0fd13a21341c0d0cb9561f37ef83c41577a28b" }, { - "size": 1279, "path": "dictionaries/sources.json", + "size": 1279, "sha256": "d6e11a3aaba22a8a7eaba19f778d8a5bd66653ff306810e85a1b0e7fff3a6b86" }, { - "size": 898248, "path": "dictionaries/uk.txt", + "size": 898248, "sha256": "caeb097749d4afc84b68ad96b3d7dfb6a6569561cd32ccce0bee94a13b43ba86" }, { - "size": 993, "path": "tools/README.txt", + "size": 993, "sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a" }, { - "size": 134656, "path": "tools/StayHere.exe", + "size": 134656, "sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376" }, { - "size": 2796, "path": "tools/StayHere-README.md", + "size": 2796, "sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413" } ], - "schema": 1 + "version": "0.6.74" } diff --git a/resources/app.rc b/resources/app.rc index f190985..97d888a 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,73,0 - PRODUCTVERSION 0,6,73,0 + FILEVERSION 0,6,74,0 + PRODUCTVERSION 0,6,74,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.73" + VALUE "FileVersion", "0.6.74" END END BLOCK "VarFileInfo" diff --git a/src/config_main.cpp b/src/config_main.cpp index 54f7f5c..8f3a3f6 100644 --- a/src/config_main.cpp +++ b/src/config_main.cpp @@ -1,6 +1,7 @@ #include "configuration.h" #include #include +#include "mcp_logs.h" namespace ks { @@ -156,6 +157,26 @@ void App::setHotkeyCapture(HWND field) } void App::clearLog(bool previous) { request(*this, ConfigClearLog, Bytes{static_cast(previous)}); } +int runMcpConfigurator(HINSTANCE instance) +{ + App app(instance); + WNDCLASSW cls{}; + cls.lpfnWndProc = controller; + cls.hInstance = instance; + cls.lpszClassName = L"KSwitcher.Config.MCP"; + RegisterClassW(&cls); + app.window = CreateWindowExW(0, cls.lpszClassName, L"", 0, 0, 0, 0, 0, + HWND_MESSAGE, nullptr, instance, nullptr); + auto result = runLogMcp([&](const Bytes &payload) + { + service = FindWindowW(L"KSwitcher.Main", L"KSwitcher"); + if (!app.window || !service) throw std::runtime_error("Start KSwitcher before reading remote logs."); + return request(app, ConfigLan, payload); + }); + if (app.window) DestroyWindow(app.window); + return result; +} + int runConfigurator(HINSTANCE instance, bool snippets, bool logs) { HANDLE singleton = CreateMutexW(nullptr, TRUE, L"Local\\KSwitcher.Config.Singleton"); @@ -236,8 +257,9 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int) int count{}; auto args = CommandLineToArgvW(GetCommandLineW(), &count); bool snippets = count > 1 && std::wstring(args[1]) == L"--snippets"; bool logs = count > 1 && std::wstring(args[1]) == L"--logs"; + bool mcp = count > 1 && std::wstring(args[1]) == L"--mcp"; LocalFree(args); - result = ks::runConfigurator(instance, snippets, logs); + result = mcp ? ks::runMcpConfigurator(instance) : ks::runConfigurator(instance, snippets, logs); } catch (const std::exception &e) { diff --git a/src/lan.cpp b/src/lan.cpp index 697ddd7..32cd3c4 100644 --- a/src/lan.cpp +++ b/src/lan.cpp @@ -55,6 +55,11 @@ struct LanService::Impl Json trusted=Json::object(),positions=Json::object(); std::unique_ptr pending; std::unique_ptr clipboard; + std::unique_ptr transfers; + std::deque incomingFiles; + struct LogDownload {std::string peer, id; uint64_t deadline; Bytes bytes;}; + std::optional logDownload; + bool shareLogs{}; bool enabled{}; std::atomic stopping{false}; std::mutex mutex; @@ -83,6 +88,7 @@ struct LanService::Impl id=j.at("id"); enabled=j.value("enabled",false); trusted=j.at("trusted"); positions=j.value("positions",Json::object()); shareInput=j.value("shareInput",false);inputPeer=j.value("inputPeer","");inputEdge=j.value("inputEdge",1); + shareLogs=j.value("shareLogs",false); if(inputEdge<0||inputEdge>3||(shareInput&&trusted.empty()))throw std::runtime_error("Invalid input sharing configuration."); if(!trusted.is_object()||trusted.size()>64) throw std::runtime_error("Invalid paired computer list."); for(auto &[key,entry]:trusted.items()) @@ -93,12 +99,13 @@ struct LanService::Impl else id=lan::randomHex(16); lan::fillPositions(positions,trusted,inputPeer,inputEdge); clipboard=std::make_unique(id); + transfers=std::make_unique(id,"file-transfer"); configureRouter(); if(enabled) start(); } ~Impl() { stop(); } void save() { atomicWrite(path,protect(encoded({{"version",1},{"id",id},{"enabled",enabled},{"trusted",trusted}, - {"shareInput",shareInput},{"inputPeer",inputPeer},{"inputEdge",inputEdge},{"positions",positions}}))); } + {"shareInput",shareInput},{"shareLogs",shareLogs},{"inputPeer",inputPeer},{"inputEdge",inputEdge},{"positions",positions}}))); } bool queue(const std::string &peer,lan::InputFrame frame) { std::lock_guard lock(inputMutex); @@ -153,6 +160,7 @@ struct LanService::Impl 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(id); + transfers=std::make_unique(id,"file-transfer");incomingFiles.clear();logDownload.reset(); } void send(SOCKET socket,const sockaddr_in &address,const Json &j) { @@ -161,6 +169,38 @@ struct LanService::Impl } 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) + { + for(auto &item:transfers->deliveries) + { + if(item.app=="file") + { + auto end=std::find(item.bytes.begin(),item.bytes.end(),0); + if(end!=item.bytes.begin() && end!=item.bytes.end() && end-item.bytes.begin()<=1024 && + item.bytes.end()-end-1<=16*1024*1024) + incomingFiles.push_back(std::move(item)); + } + else if(item.app=="log-request" && item.bytes.size()==33) + { + std::string request(item.bytes.begin()+1,item.bytes.end()); + if(!lan::identifier(request)||item.bytes[0]>1)continue; + Bytes response{2}; + if(shareLogs)try + { + auto log=readFile(path.parent_path()/(item.bytes[0]?L"kswitcher.log.1":L"kswitcher.log"),2*1024*1024); + response[0]=0; + response.insert(response.end(),log.begin(),log.end()); + } + catch(const std::exception &){response={1};} + try{transfers->queue({item.peer},std::move(response),"log-reply-"+request,now);} + catch(const std::exception &){} + } + else if(logDownload && nowdeadline && logDownload->peer==item.peer && + item.app=="log-reply-"+logDownload->id && item.bytes.size()<=2*1024*1024+1 && logDownload->bytes.empty()) + logDownload->bytes=std::move(item.bytes); + } + transfers->deliveries.clear(); + } void receive(SOCKET socket,const sockaddr_in &address,const Json &j,uint64_t now) { if(j.value("app","")!="KSwitcher-LAN" || j.value("version",0)!=1) return; @@ -180,6 +220,7 @@ struct LanService::Impl // announcements cannot extend its PeerLifetime expiry. if(peer.address.sin_addr.s_addr!=address.sin_addr.s_addr) peer.verified=0; clipboard->peerSession(other,j.value("clipboardSession","")); + transfers->peerSession(other,j.value("fileSession","")); peer.name=display; peer.epoch=session; peer.address=address; peer.seen=now; if(trusted.contains(other)) { @@ -192,6 +233,17 @@ struct LanService::Impl if(!peers.contains(other)||j.value("to","")!=id) return; auto &peer=peers.at(other); if(peer.address.sin_addr.s_addr!=address.sin_addr.s_addr) return; + if(type=="file-transfer" && trusted.contains(other)) + { + size_t retainedBytes=0; + for(const auto &item:incomingFiles)retainedBytes+=item.bytes.size(); + try {transfers->receive(other,trusted.at(other).at("key"),j,now,0, + [&](const auto &target,const auto &packet){send(socket,peers.at(target).address,packet);}, + incomingFiles.size(),retainedBytes);} + catch(const std::exception &){return;} + receiveTransfers(now); + return; + } if(type=="clipboard" && trusted.contains(other)) { try {clipboard->receive(other,trusted.at(other).at("key"),j,now,GetClipboardSequenceNumber(), @@ -246,13 +298,17 @@ struct LanService::Impl clipboard->poll(trusted,now,[&](const auto &target,const auto &packet){ if(peers.contains(target))send(socket,peers.at(target).address,packet); }); - clipboardActive=clipboard->active(); + transfers->poll(trusted,now,[&](const auto &target,const auto &packet){ + if(peers.contains(target))send(socket,peers.at(target).address,packet); + }); + 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}); if(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(); for(auto ip:broadcasts()) { auto address=bound; address.sin_addr.s_addr=ip; send(socket,address,hello); } nextHello=now+3000; } @@ -324,6 +380,75 @@ struct LanService::Impl if(enabled) start(); else status="Disabled. No discovery sockets or worker thread."; } std::lock_guard lock(mutex); + auto now=GetTickCount64(); + if(action=="shareLogs") + { + bool previous=shareLogs; + shareLogs=j.at("enabled"); + try {save();} catch(...) {shareLogs=previous;throw;} + if(!shareLogs) + for(const auto &[peer,entry]:trusted.items())transfers->cancel(peer,"log-reply-"); + } + if(action=="sendFile" || action=="requestLog") + { + auto peer=j.at("peer").get(); + if(!enabled||!trusted.contains(peer)||!peers.contains(peer)||!peers.at(peer).verified|| + now-peers.at(peer).verified>=lan::PeerLifetime) + 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."); + if(action=="sendFile") + { + auto file=std::filesystem::path(wide(j.at("path").get())); + auto name=utf8(file.filename().wstring()); + if(name.empty()||name.size()>1024)throw std::runtime_error("Invalid file name."); + Bytes payload(name.begin(),name.end()); + payload.push_back(0); + constexpr size_t fileLimit=16*1024*1024; + if(std::filesystem::file_size(file)>fileLimit)throw std::runtime_error("File size limit is 16 MiB."); + auto bytes=readFile(file,fileLimit); + payload.insert(payload.end(),bytes.begin(),bytes.end()); + transfers->queue({peer},std::move(payload),"file",now); + return encoded({{"queued",true}}); + } + if(logDownload && nowdeadline) + throw std::runtime_error("A remote log download is already pending."); + auto request=lan::randomHex(16); + Bytes payload{static_cast(j.value("previous",false))}; + payload.insert(payload.end(),request.begin(),request.end()); + transfers->queue({peer},std::move(payload),"log-request",now); + logDownload=LogDownload{peer,request,now+30000,{}}; + return encoded({{"request",request}}); + } + if(action=="takeLog") + { + if(!logDownload||logDownload->id!=j.at("request").get()||now>=logDownload->deadline) + return encoded({{"state","expired"}}); + if(logDownload->bytes.empty())return encoded({{"state","waiting"}}); + auto bytes=std::move(logDownload->bytes); + logDownload.reset(); + if(bytes.front()!=0)return encoded({{"state",bytes.front()==2?"denied":"unavailable"}}); + std::string hex; + hex.reserve((bytes.size()-1)*2); + for(auto it=bytes.begin()+1;it!=bytes.end();++it) + { + hex+="0123456789abcdef"[*it>>4]; + hex+="0123456789abcdef"[*it&15]; + } + return encoded({{"state","ready"},{"logHex",hex}}); + } + if(action=="saveFile"||action=="discardFile") + { + auto found=std::find_if(incomingFiles.begin(),incomingFiles.end(),[&](const auto &file){ + return file.id==j.at("id").get() && file.peer==j.at("peer").get(); + }); + if(found==incomingFiles.end())throw std::runtime_error("This file is no longer available."); + if(action=="saveFile") + { + auto start=std::find(found->bytes.begin(),found->bytes.end(),0)+1; + atomicWrite(wide(j.at("path").get()),Bytes(start,found->bytes.end())); + } + incomingFiles.erase(found); + } if(action=="position") { auto peer=j.at("peer").get();int x=j.at("x"),y=j.at("y"); @@ -368,6 +493,8 @@ struct LanService::Impl auto peer=j.at("peer").get();auto oldTrusted=trusted;auto oldPositions=positions;bool oldSharing=shareInput; trusted.erase(peer);positions.erase(peer);if(trusted.empty())shareInput=false; try{save();}catch(...){trusted=std::move(oldTrusted);positions=std::move(oldPositions);shareInput=oldSharing;throw;} + std::erase_if(incomingFiles,[&](const auto &file){return file.peer==peer;}); + if(logDownload && logDownload->peer==peer)logDownload.reset(); if(pending&&pending->peer==peer)pending.reset(); configureRouter(); status="Pair removed on this computer."; @@ -376,7 +503,16 @@ struct LanService::Impl {"positions",positions},{"shareInput",shareInput},{"inputPeer",inputPeer},{"controlPeer",router?router->peer():std::string{}},{"inputEdge",inputEdge},{"inputConnected",inputConnected.load()}, {"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;} - auto now=GetTickCount64(); + result["shareLogs"]=shareLogs; + result["files"]=Json::array(); + result["transferStatus"]=transfers->status; + for(const auto &file:incomingFiles) + { + auto end=std::find(file.bytes.begin(),file.bytes.end(),0); + auto filename=utf8(wide(std::string(file.bytes.begin(),end))); + result["files"].push_back({{"id",file.id},{"peer",file.peer},{"sender",trusted.at(file.peer).at("name")}, + {"name",filename},{"size",file.bytes.end()-end-1}}); + } result["pendingPeer"]=pending&&!pending->confirmed ? pending->peer : ""; result["pairSecondsRemaining"]=pending&&!pending->confirmed&&!pending->expired(now) ? (lan::PairLifetime-(now-pending->started)+999)/1000 : 0; @@ -384,7 +520,8 @@ struct LanService::Impl { 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.verifiedhasSession(peer)}}); } for(const auto &[peer,p]:trusted.items()) if(!peers.contains(peer)) result["peers"].push_back({{"id",peer},{"name",p.at("name")},{"address",""},{"paired",true},{"verified",false},{"online",false}}); diff --git a/src/lan_clipboard.h b/src/lan_clipboard.h index 63a4dff..529fe96 100644 --- a/src/lan_clipboard.h +++ b/src/lan_clipboard.h @@ -6,8 +6,8 @@ namespace ks::lan { -// Reliable bounded clipboard messages over the existing discovery socket. -// Every datagram has a fresh directional AES-GCM key; no plaintext clipboard +// Reliable bounded messages over the existing discovery socket. +// Every datagram has a fresh directional AES-GCM key; no plaintext transfer // metadata or contents appear outside the encrypted CBOR body. class ClipboardExchange { @@ -15,7 +15,7 @@ class ClipboardExchange struct Item {std::string id,app;Bytes bytes;}; struct Sending {std::deque> queue;size_t ack{};bool begun{};uint64_t last{},progress{};}; struct Receiving {std::string id,app;Bytes bytes;size_t size{};uint64_t last{};DWORD sequence{};}; - std::string local, boot=randomHex(16); + std::string local, type, domain, boot=randomHex(16); std::map sessions; std::map sending; std::map receiving; @@ -31,33 +31,53 @@ class ClipboardExchange Json seal(const std::string &peer,const std::string &key,const Json &body) { auto nonce=randomHex(16);auto number=++nextPacket; - InputCipher cipher(mac(key,"KSwitcher clipboard v1|"+local+"|"+peer+"|"+boot+"|"+sessions.at(peer)+"|"+std::to_string(number)+"|"+nonce)); - auto packet=envelope("clipboard",local);packet["to"]=peer;packet["nonce"]=nonce;packet["session"]=sessions.at(peer);packet["fromSession"]=boot;packet["number"]=number; + InputCipher cipher(mac(key,domain+local+"|"+peer+"|"+boot+"|"+sessions.at(peer)+"|"+std::to_string(number)+"|"+nonce)); + auto packet=envelope(type,local);packet["to"]=peer;packet["nonce"]=nonce;packet["session"]=sessions.at(peer);packet["fromSession"]=boot;packet["number"]=number; packet["data"]=hex(cipher.encryptPayload(Json::to_cbor(body)));return packet; } public: struct Delivery {std::string peer,id,app;Bytes bytes;DWORD sequence{};}; std::vector deliveries; std::string status="Clipboard sharing ready."; - explicit ClipboardExchange(std::string id):local(std::move(id)){} + explicit ClipboardExchange(std::string id,std::string messageType="clipboard") + :local(std::move(id)),type(std::move(messageType)),domain("KSwitcher "+type+" v1|") + { + if(type!="clipboard")status.clear(); + } const std::string &session()const{return boot;} bool active()const{return !sending.empty();} + bool hasSession(const std::string &peer)const{return sessions.contains(peer);} + void cancel(const std::string &peer,const std::string &prefix) + { + auto found=sending.find(peer); + if(found==sending.end())return; + auto &s=found->second; + if(s.queue.empty())return; + bool reset=s.queue.front()->app.starts_with(prefix); + std::erase_if(s.queue,[&](const auto &item){return item->app.starts_with(prefix);}); + if(reset){s.ack=0;s.begun=false;s.last=0;s.progress=GetTickCount64();} + } void peerSession(const std::string &peer,const std::string &value){ if(!identifier(value))return; if(sessions.contains(peer)&&sessions.at(peer)!=value){ auto found=sending.find(peer);if(found!=sending.end()){found->second.ack=0;found->second.begun=false;found->second.last=0;} + if(type!="clipboard"){ + auto previous=receiving.find(peer); + if(previous!=receiving.end()){incomingBytes-=previous->second.size;receiving.erase(previous);} + receivedPackets.erase(peer); + } } sessions[peer]=value; } void queue(const std::vector &peers,Bytes bytes,std::string app,uint64_t now) { - if(bytes.empty()||bytes.size()>Limit)throw std::runtime_error("LAN clipboard limit is 32 MiB."); + if(bytes.empty()||bytes.size()>Limit)throw std::runtime_error("LAN transfer limit is 32 MiB."); size_t total=bytes.size();std::set counted; for(auto &[peer,s]:sending)for(auto &item:s.queue)if(counted.insert(item.get()).second)total+=item->bytes.size(); if(total>2*Limit)throw std::runtime_error("LAN clipboard queue is full."); auto item=std::make_shared(Item{randomHex(16),app.size()>128?std::string("Application"):app,std::move(bytes)}); - for(auto &peer:peers){auto &s=sending[peer];if(s.queue.size()>=8)continue;if(s.queue.empty()){s.ack=0;s.begun=false;s.last=0;s.progress=now;}s.queue.push_back(item);} - if(!peers.empty())status="Sending clipboard to "+std::to_string(peers.size())+" paired computers..."; + for(auto &peer:peers){auto &s=sending[peer];if(s.queue.size()>=8){if(type!="clipboard")throw std::runtime_error("LAN transfer queue is full.");continue;}if(s.queue.empty()){s.ack=0;s.begun=false;s.last=0;s.progress=now;}s.queue.push_back(item);} + if(!peers.empty())status=type=="clipboard"?"Sending clipboard to "+std::to_string(peers.size())+" paired computers...":"Sending…"; } templatevoid poll(const Json &trusted,uint64_t now,Send send) { @@ -67,7 +87,7 @@ class ClipboardExchange { auto &peer=it->first;auto &s=it->second; if(!trusted.contains(peer)||s.queue.empty()){it=sending.erase(it);continue;} - if(now-s.progress>30000){status="Clipboard transfer timed out.";it=sending.erase(it);continue;} + if(now-s.progress>30000){status="Transfer timed out.";it=sending.erase(it);continue;} if(sessions.contains(peer)&&(!s.last||now-s.last>=100)) { auto &item=*s.queue.front();auto key=trusted.at(peer).at("key").template get(); @@ -80,14 +100,16 @@ class ClipboardExchange ++it; } } - templatevoid receive(const std::string &peer,const std::string &key,const Json &packet,uint64_t now,DWORD sequence,Send send) + templatevoid receive(const std::string &peer,const std::string &key,const Json &packet,uint64_t now,DWORD sequence,Send send, + size_t retained=0,size_t retainedBytes=0) { if(packet.value("session","")!=boot||!sessions.contains(peer)||packet.value("to","")!=local||!identifier(packet.value("nonce","")))return; auto senderBoot=packet.value("fromSession","");auto number=packet.value("number",uint64_t{}); if(!identifier(senderBoot)||!number)return; + if(type!="clipboard"&&senderBoot!=sessions.at(peer))return; auto &seen=receivedPackets[peer]; if((seen.contains(senderBoot)&&number<=seen.at(senderBoot))||(!seen.contains(senderBoot)&&seen.size()>=1024))return; - InputCipher cipher(mac(key,"KSwitcher clipboard v1|"+peer+"|"+local+"|"+senderBoot+"|"+boot+"|"+std::to_string(number)+"|"+packet.at("nonce").get())); + InputCipher cipher(mac(key,domain+peer+"|"+local+"|"+senderBoot+"|"+boot+"|"+std::to_string(number)+"|"+packet.at("nonce").get())); auto body=Json::from_cbor(cipher.decryptPayload(unhex(packet.at("data").get()))); seen[senderBoot]=number; // Retransmissions use new numbers; reordered old packets are retried. auto id=body.value("item","");if(!identifier(id))return; @@ -100,7 +122,7 @@ class ClipboardExchange if(item.id!=id||offset>item.bytes.size()||offsets.ack+Window*Chunk||(offset!=item.bytes.size()&&offset%Chunk))return; if(offset==s.ack&&s.begun)return; s.begun=true;s.ack=offset;s.progress=now;s.last=0; - if(offset==item.bytes.size()){s.queue.pop_front();s.ack=0;s.begun=false;status="Clipboard delivered.";} + if(offset==item.bytes.size()){s.queue.pop_front();s.ack=0;s.begun=false;status=type=="clipboard"?"Clipboard delivered.":"Transfer delivered.";} return; } for(auto &done:completed[peer])if(done.first==id){ack(done.second);return;} @@ -111,7 +133,8 @@ class ClipboardExchange auto found=receiving.find(peer); if(found!=receiving.end()){if(found->second.id==id)ack(found->second.bytes.size());return;} size_t waiting=0;for(auto &d:deliveries)waiting+=d.bytes.size(); - if(incomingBytes+waiting+size>2*Limit||deliveries.size()>=8)return; + if(incomingBytes+waiting+retainedBytes+size>2*Limit||deliveries.size()+retained>=8|| + (type!="clipboard"&&receiving.size()+retained>=8))return; receiving.emplace(peer,Receiving{id,app,{},size,now,sequence});incomingBytes+=size;ack(0);return; } if(op!="chunk")return; @@ -126,7 +149,7 @@ class ClipboardExchange { deliveries.push_back({peer,r.id,r.app,std::move(r.bytes),r.sequence}); auto &done=completed[peer];done.push_back({id,r.size});if(done.size()>64)done.pop_front(); - incomingBytes-=r.size;receiving.erase(found);status="Clipboard received."; + incomingBytes-=r.size;receiving.erase(found);status=type=="clipboard"?"Clipboard received.":"Transfer received."; } } }; diff --git a/src/lan_log.h b/src/lan_log.h new file mode 100644 index 0000000..17e9059 --- /dev/null +++ b/src/lan_log.h @@ -0,0 +1,22 @@ +#pragma once + +#include "core.h" + +namespace ks +{ +inline Bytes decodeLanLog(const std::string &hex) +{ + auto digit = [](char value) -> unsigned + { + if (value >= '0' && value <= '9') return value - '0'; + if (value >= 'a' && value <= 'f') return value - 'a' + 10; + throw std::runtime_error("Invalid diagnostic log response."); + }; + if (hex.size() % 2) throw std::runtime_error("Invalid diagnostic log response."); + Bytes bytes; + bytes.reserve(hex.size() / 2); + for (size_t i = 0; i < hex.size(); i += 2) + bytes.push_back(static_cast(digit(hex[i]) * 16 + digit(hex[i + 1]))); + return bytes; +} +} diff --git a/src/mcp_logs.h b/src/mcp_logs.h new file mode 100644 index 0000000..a5936c6 --- /dev/null +++ b/src/mcp_logs.h @@ -0,0 +1,109 @@ +#pragma once + +#include "../vendor/json.hpp" +#include "lan_log.h" +#include + +namespace ks +{ +inline int runLogMcp(const std::function &lan) +{ + using Json = nlohmann::json; + auto command = [&](const Json &request) + { + auto text = request.dump(); + return Json::parse(lan(Bytes(text.begin(), text.end()))); + }; + 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}} + ]})"); + std::string line; + while (std::getline(std::cin, line)) + { + Json id, reply; + try + { + auto message = Json::parse(line); + if (!message.contains("id")) continue; + id = message.at("id"); + auto method = message.at("method").get(); + if (method == "initialize") + { + auto version = message.at("params").value("protocolVersion", ""); + if (version != "2025-03-26" && version != "2025-06-18" && version != "2025-11-25") + version = "2025-11-25"; + reply["result"] = {{"protocolVersion", version}, {"capabilities", {{"tools", Json::object()}}}, + {"serverInfo", {{"name", "kswitcher-logs"}, {"version", "1.0.0"}}}}; + } + else if (method == "ping") reply["result"] = Json::object(); + else if (method == "tools/list") reply["result"] = tools; + else if (method == "tools/call") + { + std::string output; + bool failed = false; + try + { + auto params = message.at("params"); + auto arguments = params.value("arguments", Json::object()); + auto name = params.at("name").get(); + if (name == "list_log_computers") + { + auto peers = Json::array(); + for (const auto &peer : command({{"action", "status"}}).at("peers").get()) + if (peer.value("paired", false)) + peers.push_back({{"id", peer.at("id")}, {"name", peer.at("name")}, + {"available", peer.value("verified", false) && peer.value("fileTransfer", false)}}); + output = peers.dump(); + } + else if (name == "read_diagnostic_log") + { + auto peer = arguments.value("peer", ""); + 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."); + if (peer.empty()) output = utf8(readDiagnosticLog(previous)); + else + { + auto request = command({{"action", "requestLog"}, {"peer", peer}, {"previous", previous}}).at("request"); + for (;;) + { + auto result = command({{"action", "takeLog"}, {"request", request}}); + auto state = result.at("state").get(); + if (state == "ready") + { + auto bytes = decodeLanLog(result.at("logHex")); + output.assign(bytes.begin(), bytes.end()); + break; + } + if (state == "denied") throw std::runtime_error("Remote log downloads are disabled on that computer."); + if (state == "unavailable") throw std::runtime_error("The remote log is unavailable."); + if (state != "waiting") throw std::runtime_error("The remote log download timed out."); + Sleep(250); + } + } + size_t start = output.size(); + if (start && output.back() == '\n') --start; + while (lines-- && start) + { + auto newline = output.rfind('\n', start - 1); + if (newline == std::string::npos) { start = 0; break; } + start = newline; + } + if (start) output.erase(0, start + 1); + } + else throw std::runtime_error("Unknown tool."); + } + catch (const std::exception &error) { output = error.what(); failed = true; } + reply["result"] = {{"content", Json::array({{{"type", "text"}, {"text", output}}})}, {"isError", failed}}; + } + else reply["error"] = {{"code", -32601}, {"message", "Method not found"}}; + } + catch (const std::exception &) { reply["error"] = {{"code", -32600}, {"message", "Invalid request"}}; } + reply["jsonrpc"] = "2.0"; + reply["id"] = id; + std::cout << reply.dump(-1, ' ', false, Json::error_handler_t::replace) << std::endl; + } + return 0; +} +} diff --git a/src/ui.cpp b/src/ui.cpp index 7c9d0dd..4f74047 100644 --- a/src/ui.cpp +++ b/src/ui.cpp @@ -1,6 +1,7 @@ #include "lan_layout.h" #include "../resources/resource.h" #include "app.h" +#include "lan_log.h" #include "history_preview.h" #include "ui_scroll.h" #include "configuration.h" @@ -270,6 +271,53 @@ LRESULT CALLBACK layoutProc(HWND w, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, DW } return DefSubclassProc(w, msg, wp, lp); } +LRESULT CALLBACK listHeaderDraw(HWND list, UINT message, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR) +{ + if (message != WM_NOTIFY) return DefSubclassProc(list, message, wp, lp); + const auto *notice = reinterpret_cast(lp); + auto header = ListView_GetHeader(list); + if (notice->hwndFrom != header || notice->code != NM_CUSTOMDRAW) + return DefSubclassProc(list, message, wp, lp); + const auto &draw = *reinterpret_cast(lp); + auto background = GetSysColorBrush(COLOR_3DFACE); + auto border = GetSysColorBrush(COLOR_3DSHADOW); + if (draw.dwDrawStage == CDDS_PREPAINT) + { + FillRect(draw.hdc, &draw.rc, background); + return CDRF_NOTIFYITEMDRAW | CDRF_NOTIFYPOSTPAINT; + } + if (draw.dwDrawStage == CDDS_ITEMPREPAINT) + { + RECT cell = draw.rc; + FillRect(draw.hdc, &cell, background); + RECT divider{cell.right - 1, cell.top, cell.right, cell.bottom}; + FillRect(draw.hdc, ÷r, border); + wchar_t title[64]{}; + HDITEMW item{HDI_TEXT | HDI_FORMAT}; + item.pszText = title; + item.cchTextMax = std::size(title); + Header_GetItem(header, static_cast(draw.dwItemSpec), &item); + cell.left += scale(list, 5); + cell.right -= scale(list, 5); + int dc = SaveDC(draw.hdc); + auto font = SendMessageW(header, WM_GETFONT, 0, 0); + if (font) SelectObject(draw.hdc, reinterpret_cast(font)); + SetTextColor(draw.hdc, GetSysColor(COLOR_BTNTEXT)); + SetBkMode(draw.hdc, TRANSPARENT); + UINT alignment = (item.fmt & HDF_RIGHT) ? DT_RIGHT : (item.fmt & HDF_CENTER) ? DT_CENTER : DT_LEFT; + DrawTextW(draw.hdc, title, -1, &cell, alignment | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS | DT_NOPREFIX); + RestoreDC(draw.hdc, dc); + return CDRF_SKIPDEFAULT; + } + if (draw.dwDrawStage == CDDS_POSTPAINT) + { + RECT line{}; + GetClientRect(header, &line); + line.top = line.bottom - 1; + FillRect(draw.hdc, &line, border); + } + return CDRF_DODEFAULT; +} HWND control(HWND parent, const wchar_t *cls, const wchar_t *title, DWORD style, int id, int x, int y, int width, int height) { @@ -278,6 +326,8 @@ HWND control(HWND parent, const wchar_t *cls, const wchar_t *title, DWORD style, scale(parent, width), scale(parent, height), parent, (HMENU)(INT_PTR)id, GetModuleHandleW(nullptr), nullptr); SendMessageW(w, WM_SETFONT, (WPARAM)GetPropW(parent, L"Font"), TRUE); + if (wcscmp(cls, WC_LISTVIEWW) == 0 && (style & LVS_TYPEMASK) == LVS_REPORT && !(style & LVS_NOCOLUMNHEADER)) + SetWindowSubclass(w, listHeaderDraw, 3, 0); if(wcscmp(cls,L"LISTBOX")==0 || wcscmp(cls,WC_LISTVIEWW)==0 || wcscmp(cls,L"COMBOBOX")==0 || (wcscmp(cls,L"EDIT")==0 && (style&ES_MULTILINE))) enableWheelBatching(w,wcscmp(cls,L"LISTBOX")==0); @@ -1127,6 +1177,8 @@ struct ChatLanguagesView Settings draft; int selection = -1; bool dirty{}; + bool updatingList{}; + std::wstring search; }; void collectChatLanguages(HWND w, ChatLanguagesView *v) { @@ -1141,9 +1193,17 @@ void collectChatLanguages(HWND w, ChatLanguagesView *v) } void fillChatLanguages(HWND w, ChatLanguagesView *v) { - int index = (int)SendDlgItemMessageW(w, 710, LB_GETCURSEL, 0, 0); - if (index < 0 || index >= (int)v->keys.size()) return; - v->selection = index; + int index = v->selection; + EnableWindow(GetDlgItem(w, 711), index >= 0); + EnableWindow(GetDlgItem(w, IDOK), index >= 0); + if (index < 0) + { + SendDlgItemMessageW(w, 711, LB_SETSEL, FALSE, -1); + EnableWindow(GetDlgItem(w, 713), FALSE); + value(w, 712, v->keys.empty() ? L"Open a chat, then reopen this dialog to add it." : + L"No contacts match your search."); + return; + } const auto &draft = v->draft; auto saved = draft.chatCycles.find(v->keys[index]); const auto &cycle = saved == draft.chatCycles.end() ? draft.cycle : saved->second; @@ -1157,26 +1217,103 @@ void fillChatLanguages(HWND w, ChatLanguagesView *v) L"Chat profile. Select languages, or remove it to use the defaults."); EnableWindow(GetDlgItem(w, 713), saved != draft.chatCycles.end()); } +void selectChatRow(HWND list, int index) +{ + int row = -1; + if (index >= 0) + { + LVFINDINFOW find{LVFI_PARAM}; + find.lParam = index; + row = ListView_FindItem(list, -1, &find); + } + ListView_SetItemState(list, -1, 0, LVIS_SELECTED | LVIS_FOCUSED); + if (row >= 0) + { + ListView_SetItemState(list, row, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); + ListView_EnsureVisible(list, row, FALSE); + } +} +void filterChatRows(HWND w, ChatLanguagesView *v) +{ + auto list = GetDlgItem(w, 710); + auto search = lower(v->search); + int selection = -1; + v->updatingList = true; + SendMessageW(list, WM_SETREDRAW, FALSE, 0); + ListView_DeleteAllItems(list); + for (size_t i = 0; i < v->keys.size(); ++i) + { + const auto &key = v->keys[i]; + auto contact = key.substr(key.find(L'\n') + 1); + if (lower(contact).find(search) == std::wstring::npos) continue; + auto app = key.starts_with(L"telegram\n") ? L"Telegram" : + key.starts_with(L"telegram-web\n") ? L"Telegram Web" : + key.starts_with(L"viber\n") ? L"Viber (inactive)" : L"Teams"; + LVITEMW item{LVIF_TEXT | LVIF_PARAM}; + item.iItem = ListView_GetItemCount(list); + item.pszText = contact.data(); + item.lParam = static_cast(i); + int row = ListView_InsertItem(list, &item); + if (row < 0) continue; + ListView_SetItemText(list, row, 1, const_cast(app)); + if (selection < 0 || static_cast(i) == v->selection) selection = static_cast(i); + } + selectChatRow(list, selection); + SendMessageW(list, WM_SETREDRAW, TRUE, 0); + InvalidateRect(list, nullptr, TRUE); + v->updatingList = false; + v->selection = selection; + fillChatLanguages(w, v); +} LRESULT CALLBACK chatLanguagesProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) { auto *v = (ChatLanguagesView *)GetWindowLongPtrW(w, GWLP_USERDATA); if (!v) return DefWindowProcW(w, msg, wp, lp); try { + if (msg == WM_NOTIFY && !v->updatingList) + { + auto *change = reinterpret_cast(lp); + if (change->hdr.idFrom == 710 && change->hdr.code == LVN_ITEMCHANGED && + (change->uNewState & LVIS_SELECTED) && !(change->uOldState & LVIS_SELECTED)) + { + int selected = static_cast(change->lParam); + if (selected == v->selection) return 0; + try { collectChatLanguages(w, v); } + catch (...) + { + v->updatingList = true; + selectChatRow(change->hdr.hwndFrom, v->selection); + v->updatingList = false; + throw; + } + v->selection = selected; + fillChatLanguages(w, v); + return 0; + } + } if (msg == WM_COMMAND) { int id = LOWORD(wp); if (id == 711 && HIWORD(wp) == LBN_SELCHANGE) { v->dirty = true; return 0; } - if (id == 710 && HIWORD(wp) == LBN_SELCHANGE) + if (id == 714 && HIWORD(wp) == EN_CHANGE && !v->updatingList) { try { collectChatLanguages(w, v); } - catch (...) { SendDlgItemMessageW(w, 710, LB_SETCURSEL, v->selection, 0); throw; } - fillChatLanguages(w, v); + catch (...) + { + v->updatingList = true; + value(w, 714, v->search); + v->updatingList = false; + throw; + } + v->search = value(w, 714); + filterChatRows(w, v); return 0; } if (id == IDOK || id == 713) { - int selected = (int)SendDlgItemMessageW(w, 710, LB_GETCURSEL, 0, 0); + int selected = v->selection; + if (id == IDOK && selected < 0) return 0; if (selected < 0 || selected >= (int)v->keys.size()) throw std::runtime_error("Open a Telegram or Teams chat, then reopen this dialog."); if (id == 713) @@ -1195,7 +1332,14 @@ LRESULT CALLBACK chatLanguagesProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) if (id == IDCANCEL) { DestroyWindow(w); return 0; } } if (msg == WM_CLOSE) { DestroyWindow(w); return 0; } - if (msg == WM_DPICHANGED) { resizeForDpi(w, wp, lp); return 0; } + if (msg == WM_DPICHANGED) + { + resizeForDpi(w, wp, lp); + auto list = GetDlgItem(w, 710); + ListView_SetColumnWidth(list, 0, scale(w, 442)); + ListView_SetColumnWidth(list, 1, scale(w, 140)); + return 0; + } if (msg == WM_NCDESTROY) { EnableWindow(v->parent, TRUE); @@ -1221,19 +1365,25 @@ void showChatLanguages(HWND parent, SettingsView *settings) if (!key.empty()) data.keys.insert(std::move(key)); return TRUE; }, (LPARAM)&context); + INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_LISTVIEW_CLASSES}; + InitCommonControlsEx(&controls); HWND w = makeWindow(*settings->app, L"KSwitcher.ChatLanguages", L"Languages for a chat", chatLanguagesProc, 640, 524); auto *v = new ChatLanguagesView{parent, settings, {keys.begin(), keys.end()}}; v->draft = settings->draft; + v->updatingList = true; SetWindowLongPtrW(w, GWLP_HWNDPARENT, (LONG_PTR)parent); SetWindowLongPtrW(w, GWLP_USERDATA, (LONG_PTR)v); - label(w, L"Telegram / Telegram Web (Chrome) / Teams; Viber inactive", 18, 16, 604); - control(w, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_BORDER, - 710, 18, 44, 604, 140); - for (const auto &key : v->keys) + label(w, L"&Find contact", 18, 19, 106); + edit(w, 714, 130, 14, 492); + auto list = control(w, WC_LISTVIEWW, L"", WS_TABSTOP | WS_BORDER | LVS_REPORT | LVS_SINGLESEL | + LVS_SHOWSELALWAYS | LVS_NOSORTHEADER, 710, 18, 48, 604, 136); + ListView_SetExtendedListViewStyle(list, LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER | LVS_EX_LABELTIP); + for (const auto &[title, width] : {std::pair{L"Contact", 442}, std::pair{L"App", 140}}) { - auto split = key.find(L'\n'); - auto name = std::wstring(key.starts_with(L"telegram\n") ? L"Telegram: " : key.starts_with(L"telegram-web\n") ? L"Telegram Web: " : key.starts_with(L"viber\n") ? L"Viber (inactive): " : L"Teams: ") + key.substr(split + 1); - SendDlgItemMessageW(w, 710, LB_ADDSTRING, 0, (LPARAM)name.c_str()); + LVCOLUMNW column{LVCF_TEXT | LVCF_WIDTH}; + column.pszText = const_cast(title); + column.cx = scale(w, width); + ListView_InsertColumn(list, Header_GetItemCount(ListView_GetHeader(list)), &column); } control(w, L"STATIC", L"Open a chat, then reopen this dialog to add it.", 0, 712, 18, 194, 604, 26); label(w, L"Click languages to include (saved in the order shown)", 18, 228, 604); @@ -1246,12 +1396,10 @@ void showChatLanguages(HWND parent, SettingsView *settings) button(w, L"&Remove profile", 713, 18, 476, 170); button(w, L"&Use languages", IDOK, 300, 476, 170); button(w, L"&Cancel", IDCANCEL, 486, 476, 136); - EnableWindow(GetDlgItem(w, IDOK), !keys.empty()); - EnableWindow(GetDlgItem(w, 713), FALSE); - if (!keys.empty()) { SendDlgItemMessageW(w, 710, LB_SETCURSEL, 0, 0); fillChatLanguages(w, v); } + filterChatRows(w, v); EnableWindow(parent, FALSE); showRequestedWindow(w); - SetFocus(GetDlgItem(w, 710)); + SetFocus(GetDlgItem(w, 714)); } #include "ui_app_languages.inl" #include "ui_mouse_buttons.inl" @@ -1784,6 +1932,15 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) return TRUE; } break; + case WM_CTLCOLORSTATIC: + if (reinterpret_cast(lp) == GetDlgItem(w, 281)) + { + auto dc = reinterpret_cast(wp); + SetTextColor(dc, GetSysColor(COLOR_WINDOWTEXT)); + SetBkColor(dc, GetSysColor(COLOR_WINDOW)); + return reinterpret_cast(GetSysColorBrush(COLOR_WINDOW)); + } + break; case WM_INPUT: readMouseTestInput(w, *v, reinterpret_cast(lp)); return DefWindowProcW(w, msg, wp, lp); @@ -1827,6 +1984,12 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) { SettingsStateRefresh refresh{w}; int id = LOWORD(wp); + if (id == 282 && HIWORD(wp) == BN_CLICKED) + { + writeClipboard(w, textClip(value(w, 281))); + value(w, 283, L"Copied to clipboard."); + return 0; + } if (id >= 301 && id <= SaveSnippets && snippetCommand(w, &v->snippets, wp, true)) return 0; if (id == 220 && HIWORD(wp) == LBN_SELCHANGE && !v->filling) @@ -2316,8 +2479,9 @@ void showSettings(App &app, bool visible) INITCOMMONCONTROLSEX tabsInit{sizeof(tabsInit), ICC_TAB_CLASSES}; InitCommonControlsEx(&tabsInit); HWND tabs = control(w, WC_TABCONTROLW, L"", WS_TABSTOP, 260, 18, 16, 684, 32); + TabCtrl_SetPadding(tabs, scale(w, 3), scale(w, 3)); const wchar_t *tabNames[] = {L"General", L"Languages", L"Shortcuts", L"Clipboard", L"Snippets", L"Mouse", - L"Sync", L"Computers", L"Diagnostics"}; + L"Sync", L"Computers", L"Diagnostics", L"MCP"}; for (int i = 0; i < (int)std::size(tabNames); ++i) { TCITEMW item{}; item.mask = TCIF_TEXT; item.pszText = const_cast(tabNames[i]); @@ -2400,6 +2564,18 @@ void showSettings(App &app, bool visible) button(w, L"View l&og...", 256, 24, 110, 210); page(); + label(w, L"Codex configuration", 24, 76, 660); + label(w, L"Paste this block into ~/.codex/config.toml to connect Codex to KSwitcher.", 24, 108, 660); + edit(w, 281, 24, 140, 660, 108, ES_MULTILINE | ES_READONLY | ES_AUTOHSCROLL | WS_HSCROLL | WS_BORDER); + const auto server = std::filesystem::path(executable()).parent_path() / L"KSwitcher.Config.exe"; + value(w, 281, L"[mcp_servers.kswitcher]\r\ncommand = " + + wide(nlohmann::json(utf8(server.wstring())).dump()) + L"\r\nargs = [\"--mcp\"]\r\n"); + label(w, L"Select text and press Ctrl+C, or copy the entire block below.", 24, 258, 660); + button(w, L"&Copy configuration", 282, 24, 288, 190); + control(w, L"STATIC", L"", 0, 283, 232, 293, 452, 24); + label(w, L"For remote logs, enable diagnostic log downloads on the paired computer.", 24, 338, 660); + page(); + control(w, L"STATIC", L"No unsaved settings.", 0, 261, 18, 430, 684, 24); button(w, L"Impo&rt...", 250, 18, 466, 125); button(w, L"&Export...", 251, 155, 466, 125); diff --git a/src/ui_lan.inl b/src/ui_lan.inl index 02a5e63..5a05a2e 100644 --- a/src/ui_lan.inl +++ b/src/ui_lan.inl @@ -9,6 +9,9 @@ struct LanView std::string dragPeer;POINT dragStart{},dragPoint{};bool dragMoved{}; std::string gridState; std::vector rows; + std::string logRequest; + std::filesystem::path logDestination; + std::wstring transferMessage; }; nlohmann::json lanRequest(App &app,const nlohmann::json &request) { @@ -20,6 +23,19 @@ std::string selectedLan(HWND w,LanView &v) auto index=SendDlgItemMessageW(w,702,LB_GETCURSEL,0,0); return index>=0 && size_t(index)(); + if(state!="waiting") + { + if(state=="ready") + { + v.logRequest.clear(); + v.transferMessage.clear(); + atomicWrite(v.logDestination,decodeLanLog(reply.at("logHex"))); + v.transferMessage=L"Diagnostic log saved."; + } + else if(state=="denied")v.transferMessage=L"Remote diagnostic downloads are disabled on that PC."; + else if(state=="unavailable")v.transferMessage=L"The selected log is unavailable on that PC."; + else v.transferMessage=L"The remote log download timed out."; + v.logRequest.clear(); + } + } auto selected=selectedLan(w,v); auto next=lanRequest(*v.app,{{"action","status"}}); if(selected.empty()) @@ -104,6 +139,18 @@ void refreshLan(HWND w,LanView &v) EnableWindow(GetDlgItem(w,705),enabled&&online&&!pending&&!paired); EnableWindow(GetDlgItem(w,706),pending); EnableWindow(GetDlgItem(w,707),paired); + bool canTransfer=false; + for(const auto &peer:v.snapshot["peers"]) + if(peer.at("id")==selected)canTransfer=paired&&peer.value("verified",false)&&peer.value("fileTransfer",false); + EnableWindow(GetDlgItem(w,726),canTransfer); + EnableWindow(GetDlgItem(w,727),canTransfer&&v.logRequest.empty()); + EnableWindow(GetDlgItem(w,728),canTransfer&&v.logRequest.empty()); + EnableWindow(GetDlgItem(w,730),!v.snapshot["files"].empty()); + CheckDlgButton(w,729,v.snapshot.value("shareLogs",false)?BST_CHECKED:BST_UNCHECKED); + auto fileCount=v.snapshot["files"].size(); + auto transferStatus=v.transferMessage; + if(transferStatus.empty())transferStatus=wide(v.snapshot.value("transferStatus",std::string{})); + value(w,731,fileCount?L"Incoming files: "+std::to_wstring(fileCount):transferStatus); for(int id:{703,704}) EnableWindow(GetDlgItem(w,id),enabled&&!pending&&!paired); auto positions=v.snapshot.value("positions",nlohmann::json::object()); EnableWindow(GetDlgItem(w,715),enabled&&!positions.empty()&&!v.snapshot.value("shareInput",false)); @@ -154,6 +201,43 @@ LRESULT CALLBACK lanProc(HWND w,UINT msg,WPARAM wp,LPARAM lp) if(id==705) lanRequest(*v->app,{{"action","pair"},{"peer",peer},{"code",utf8(value(w,703))}}); if(id==706) lanRequest(*v->app,{{"action","cancel"}}); if(id==707) lanRequest(*v->app,{{"action","forget"},{"peer",peer}}); + if(id==726) + { + auto file=pickLanFile(w,false); + if(!file.empty()) + { + lanRequest(*v->app,{{"action","sendFile"},{"peer",peer},{"path",utf8(file.wstring())}}); + v->transferMessage.clear(); + } + } + if(id==727||id==728) + { + auto destination=pickLanFile(w,true,id==728?L"kswitcher-previous.log":L"kswitcher-remote.log"); + if(!destination.empty()) + { + auto reply=lanRequest(*v->app,{{"action","requestLog"},{"peer",peer},{"previous",id==728}}); + v->logDestination=std::move(destination); + v->logRequest=reply.at("request").get(); + v->transferMessage=L"Downloading diagnostic log..."; + } + } + if(id==729)lanRequest(*v->app,{{"action","shareLogs"},{"enabled",IsDlgButtonChecked(w,729)==BST_CHECKED}}); + if(id==730 && !v->snapshot["files"].empty()) + { + const auto file=v->snapshot["files"].front(); + auto name=wide(file.at("name").get()); + auto question=wide(file.at("sender").get())+L" sent "+name+L" ("+ + std::to_wstring(file.at("size").get())+L" bytes).\n\nSave this file? Choose No to discard it."; + auto answer=MessageBoxW(w,question.c_str(),L"Incoming file",MB_YESNOCANCEL|MB_ICONQUESTION); + if(answer==IDYES || answer==IDNO) + { + auto destination=answer==IDYES?pickLanFile(w,true,L"received-file"):std::filesystem::path{}; + if(answer==IDNO||!destination.empty()) + lanRequest(*v->app,{{"action",answer==IDYES?"saveFile":"discardFile"},{"id",file.at("id")}, + {"peer",file.at("peer")},{"path",utf8(destination.wstring())}}); + } + v->transferMessage.clear(); + } if(id==715) { lanRequest(*v->app,{{"action","input"},{"enabled",true}}); @@ -167,7 +251,7 @@ LRESULT CALLBACK lanProc(HWND w,UINT msg,WPARAM wp,LPARAM lp) } void showLan(HWND parent,App &app) { - HWND w=makeWindow(app,L"KSwitcher.LAN",L"KSwitcher computers — mouse and keyboard",lanProc,740,908,0,false); + HWND w=makeWindow(app,L"KSwitcher.LAN",L"KSwitcher computers",lanProc,740,908,0,false); SetWindowLongPtrW(w,GWLP_HWNDPARENT,(LONG_PTR)parent); auto v=new LanView{parent,&app};SetWindowLongPtrW(w,GWLP_USERDATA,(LONG_PTR)v); label(w,L"Changes here save automatically. No need to click Save in Settings.",18,16,700); @@ -190,8 +274,13 @@ void showLan(HWND parent,App &app) control(w,L"STATIC",L"",0,719,18,674,700,24); button(w,L"Enable &input sharing",715,18,706,330); button(w,L"&Stop input sharing",716,370,706,240); - control(w,L"STATIC",L"",0,718,18,744,700,64); - control(w,L"STATIC",L"Arrange the same physical layout on every PC. Pair each input source with every destination and enable input on all PCs. Clipboard goes to all paired PCs.",0,720,18,816,580,40); + control(w,L"STATIC",L"",0,718,18,744,700,30); + button(w,L"Send file…",726,18,774,144); + button(w,L"Incoming files…",730,174,774,160); + button(w,L"Download log…",727,346,774,164); + button(w,L"Previous log…",728,522,774,196); + control(w,L"BUTTON",L"Allow paired computers to download diagnostic logs",BS_AUTOCHECKBOX|WS_TABSTOP,729,18,808,700,24); + control(w,L"STATIC",L"",0,731,18,835,700,24); button(w,L"Connection &help",722,18,864,300); button(w,L"&Close",IDCANCEL,618,864,100); EnableWindow(parent,FALSE);showRequestedWindow(w);SetForegroundWindow(w); diff --git a/src/ui_log.inl b/src/ui_log.inl index 4912580..316059d 100644 --- a/src/ui_log.inl +++ b/src/ui_log.inl @@ -177,11 +177,7 @@ void copyLogRows(HWND w, App &app) L" -> " + entry.target + L"\t" + entry.outcome + L"\r\n" + entry.details + L"\r\n\r\n"; } if (!copied.empty()) - { - auto clip = textClip(copied); - clip.formats.push_back({0, L"ExcludeClipboardContentFromMonitorProcessing", {1, 0, 0, 0}}); - app.ownSequence = writeClipboard(app.window, clip); - } + writeClipboard(app.window, textClip(copied)); } LRESULT CALLBACK logProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) { diff --git a/src/update.h b/src/update.h index 235a14d..708dec2 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.73"; +inline constexpr wchar_t AppVersion[] = L"0.6.74"; 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/chat_profiles.cpp b/tests/chat_profiles.cpp index e3d5378..f93769f 100644 --- a/tests/chat_profiles.cpp +++ b/tests/chat_profiles.cpp @@ -179,7 +179,13 @@ int main() SendMessageW(automatic,WM_COMMAND,IDOK,0); require(!saveEnabled(),"reverting auto-correction draft disables Save"); HWND tabs = GetDlgItem(parent, 260); - require(tabs && TabCtrl_GetItemCount(tabs) == 9, "nine settings categories"); + require(tabs && TabCtrl_GetItemCount(tabs) == 10, "ten settings categories"); + wchar_t mcpConfig[4096]{}; + GetDlgItemTextW(parent, 281, mcpConfig, std::size(mcpConfig)); + const std::wstring config(mcpConfig); + require(config.starts_with(L"[mcp_servers.kswitcher]\r\ncommand = \"") && + config.find(L"KSwitcher.Config.exe\"\r\nargs = [\"--mcp\"]") != std::wstring::npos, + "MCP tab shows a Codex stdio configuration"); for (int page = 0; page < TabCtrl_GetItemCount(tabs); ++page) { TabCtrl_SetCurSel(tabs, page); @@ -212,10 +218,18 @@ int main() SendMessageW(parent, WM_COMMAND, 259, 0); HWND dialog = findTestWindow(L"KSwitcher.ChatLanguages", nullptr); require(dialog && !IsWindowEnabled(parent), "chat dialog opens with disabled parent"); - int index = (int)SendDlgItemMessageW(dialog, 710, LB_FINDSTRINGEXACT, -1, (LPARAM)L"Telegram: ! Fixture chat"); - require(index >= 0, "saved chat listed"); - SendDlgItemMessageW(dialog, 710, LB_SETCURSEL, index, 0); - SendMessageW(dialog, WM_COMMAND, MAKEWPARAM(710, LBN_SELCHANGE), 0); + auto findFixtureChat = [&](HWND chatDialog) { + SetDlgItemTextW(chatDialog, 714, L"! fIXTURE CHAT"); + HWND list = GetDlgItem(chatDialog, 710); + require(ListView_GetItemCount(list) == 1, "case-insensitive contact search finds saved chat"); + wchar_t appName[32]{}; + ListView_GetItemText(list, 0, 1, appName, std::size(appName)); + require(std::wstring(appName) == L"Telegram", "chat list shows the source app separately"); + }; + SetDlgItemTextW(dialog, 714, L"No matching fixture 8031"); + require(ListView_GetItemCount(GetDlgItem(dialog, 710)) == 0 && + !IsWindowEnabled(GetDlgItem(dialog, IDOK)), "empty search results disable profile actions"); + findFixtureChat(dialog); require(SendDlgItemMessageW(dialog, 711, LB_GETSELCOUNT, 0, 0) == 1, "saved single language selected"); RedrawWindow(dialog, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN); RECT rect{}; GetClientRect(dialog, &rect); @@ -231,9 +245,7 @@ int main() require(!saveEnabled(),"cancelled chat edits do not enable Save"); SendMessageW(parent, WM_COMMAND, 259, 0); dialog = findTestWindow(L"KSwitcher.ChatLanguages", nullptr); - index = (int)SendDlgItemMessageW(dialog, 710, LB_FINDSTRINGEXACT, -1, (LPARAM)L"Telegram: ! Fixture chat"); - SendDlgItemMessageW(dialog, 710, LB_SETCURSEL, index, 0); - SendMessageW(dialog, WM_COMMAND, MAKEWPARAM(710, LBN_SELCHANGE), 0); + findFixtureChat(dialog); require(SendDlgItemMessageW(dialog, 711, LB_GETSELCOUNT, 0, 0) == 1, "cancel discards language edits"); SendDlgItemMessageW(dialog, 711, LB_SETSEL, TRUE, -1); SendMessageW(dialog, WM_COMMAND, MAKEWPARAM(711, LBN_SELCHANGE), 0); @@ -248,9 +260,7 @@ int main() require(!saveEnabled(),"reopened saved Settings is clean"); SendMessageW(parent, WM_COMMAND, 259, 0); dialog = findTestWindow(L"KSwitcher.ChatLanguages", nullptr); - index = (int)SendDlgItemMessageW(dialog, 710, LB_FINDSTRINGEXACT, -1, (LPARAM)L"Telegram: ! Fixture chat"); - SendDlgItemMessageW(dialog, 710, LB_SETCURSEL, index, 0); - SendMessageW(dialog, WM_COMMAND, MAKEWPARAM(710, LBN_SELCHANGE), 0); + findFixtureChat(dialog); SendMessageW(dialog, WM_COMMAND, 713, 0); require(IsWindow(dialog), "chat reset keeps dialog open"); SendMessageW(dialog, WM_COMMAND, IDOK, 0); diff --git a/tests/input.cpp b/tests/input.cpp index 3897a51..f88ce59 100644 --- a/tests/input.cpp +++ b/tests/input.cpp @@ -818,7 +818,7 @@ int main(int argc, char **argv) { }; RECT lastTab{}, tabClient{}; GetClientRect(tabs, &tabClient); - require(TabCtrl_GetItemCount(tabs) == 9 && TabCtrl_GetItemRect(tabs, 8, &lastTab) && + require(TabCtrl_GetItemCount(tabs) == 10 && TabCtrl_GetItemRect(tabs, 9, &lastTab) && lastTab.right <= tabClient.right, "all Settings tabs fit in one row"); selectPage(3); require(visible(257) && !visible(301), "OCR options are in Clipboard"); diff --git a/tests/lan_clipboard.cpp b/tests/lan_clipboard.cpp index 311e98c..fd84b4d 100644 --- a/tests/lan_clipboard.cpp +++ b/tests/lan_clipboard.cpp @@ -48,6 +48,37 @@ int main(){try{ check(restarted.deliveries.size()==1&&restarted.deliveries[0].bytes==Bytes({1,2,3}),"clipboard works after peer restart"); bool limited=false;try{a.queue({bid},Bytes(32*1024*1024+1),"large",12000);}catch(...){limited=true;} check(limited,"oversized clipboard bounded"); + { + ClipboardExchange sender(aid,"file-transfer"),receiver(bid,"file-transfer"),clipboard(bid); + sender.peerSession(bid,receiver.session());receiver.peerSession(aid,sender.session()); + clipboard.peerSession(aid,sender.session()); + sender.queue({bid},payload,"file",1); + Json first; + for(uint64_t now=10;now<1000&&receiver.deliveries.empty();now+=10) + { + sender.poll(trusted,now,[&](const auto &to,const Json &packet){ + check(to==bid && packet.at("type")=="file-transfer" && packet.dump().size()<=2048, + "file transfer targets a single peer on its own channel"); + if(first.is_null())first=packet; + packets.push_back({to,packet}); + }); + while(!packets.empty()) + { + auto packet=std::move(packets.front().second);packets.pop_front(); + receiver.receive(aid,key,packet,now,0,ack); + } + while(!acks.empty()) + { + auto packet=std::move(acks.front().second);acks.pop_front(); + sender.receive(bid,key,packet,now,0,output); + } + } + check(receiver.deliveries.size()==1&&receiver.deliveries.front().bytes==payload,"file payload arrives intact"); + first["session"]=clipboard.session(); + bool isolated=false; + try{clipboard.receive(aid,key,first,1001,0,ack);}catch(...){isolated=true;} + check(isolated&&acks.empty(),"file ciphertext cannot be injected into the clipboard channel"); + } { WSADATA startup{};check(WSAStartup(MAKEWORD(2,2),&startup)==0,"UDP benchmark starts"); SOCKET sa=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP),sb=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);