Feature: Implement the Linux screen preview response

The Linux client now answers COMMAND_SCREEN_PREVIEW_REQ, so a host with
an X11 desktop gets a thumbnail when it is double-clicked in the online
list, a frame in the list's Preview column, and an image from the MCP
get_screenshot tool. Previously only Windows clients advertised the
capability and Linux hosts showed "预览不可用" after a four second wait.

The client does not encode JPEG. Stock desktops ship libjpeg.so.8 whose
struct layout is the distribution's ABI (JPEG_LIB_VERSION 80), while the
in-tree jpeglib.h is libjpeg-turbo 3.1.1 (62), and libturbojpeg is not
installed by default; dlopening the system library against that header
fails with "Wrong JPEG library version: library is 80, caller expects
62". Instead the client sends raw pixels in a new screen preview format,
SCREEN_PREVIEW_FMT_BGRX: top-down rows of B,G,R,X with no row padding,
already scaled to the requested width. The server re-encodes to JPEG at
the single ingress point, so the preview popup, the list thumbnail cache
and the MCP tool keep consuming JPEG only.

Capture follows the path ScreenHandler already uses: root window copied
into an offscreen pixmap with an IncludeInferiors GC, then XGetImage,
which avoids BadMatch under compositing window managers. The X11 type
declarations and the dlopen loader moved out of ScreenHandler.h into
linux/X11Loader.h so both users share one dlsym table. The full-size
image is never materialized: a box filter reads straight from the
XImage rows (honouring bytes_per_line) into the output buffer, scales to
maxWidth without upscaling, and clamps the height to 1080 so a portrait
4K desktop cannot produce a 26 MB packet. Rows and columns come out
even, which they are for JPEG anyway.

The capability bit is now honest about the runtime. LOGIN_INFOR grows
DefaultCaps()/SetCaps(), and the client recomputes the bits before every
login and re-login: CLIENT_CAP_SCREEN_PREVIEW is set only when DISPLAY is
present and the X server actually opens. A headless host therefore gets
-32005 "Host does not support screen preview" from MCP instead of a
timeout, and a host whose session appears after boot picks it up on the
next reconnect. Requests are handled on a detached worker thread behind
a single-flight guard (matching the Windows client), so a slow XGetImage
never stalls the receive thread and a burst of requests degrades to "no
preview" rather than queueing. If the worker thread cannot be created,
the guard is released again, so one failure cannot leave every later
request rejected as busy until the client restarts.

The MCP design note claimed the capability was declared by Windows only,
and the get_screenshot tool description said the same; both now say what
the code does (Windows always, Linux when a display is reachable).

Server side, NormalizeScreenPreviewPacket runs in MessageHandle before
the MCP handoff and the PostMessage to the UI thread. It validates that
width/height are within the values the server itself can ask for and
that bytes equals width*height*4, converts with a stack Gdiplus::Bitmap
over the packet's own pixels (no copy, and no DEBUG_NEW trouble), and
rewrites the header to JPEG. The encoder output is read back by seeking
the stream rather than GlobalSize, so the packet carries no heap-block
padding after the EOI marker. Malformed packets are dropped; failure
statuses pass through untouched so the existing code can report them.

Tested against a Debug server with the WSL Ubuntu 24.04 build as the
client. get_screenshot returned valid JPEGs at max_width 480 (480x142,
1.7 KB) and 1920 (1920x570, 17.9 KB), repeatably; the list showed a
thumbnail for the GUI client and N/A for a second copy started without
DISPLAY, which also answered -32005. The box filter and the BGRX to JPEG
conversion were checked separately with quadrant fixtures: the browser
over the synthetic B,G,R,X buffer recovers red/green/blue/white in the
right channels and the downscale averages, handles non-integer ratios
and row padding, and rejects 24bpp and upscaling. The captured frames
come out black under WSLg because Xwayland keeps no root pixmap there;
that is the compositor, not this code, and Xorg sessions capture
normally.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-10-29 18:12:15 +01:00
1 parent 5bff9df3fc
commit dc4fd792f6
12 files changed
+704 -276

No files matched your search

+99 -3
View File
@@ -6852,15 +6852,19 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
// (IO 线程不接触 UI;clientId 用于循环快照路由到对应窗口)。
// 不用 WPARAM 携带 ID:32 位 Windows 上 WPARAM 是 32 位,会截 64 位 clientID。
if (len < sizeof(ScreenPreviewRspHeader)) break;
// Linux 客户端回的是原始 BGRA,统一在这里转成 JPEG;畸形包直接丢弃
std::vector<BYTE> previewPkt(szBuffer, szBuffer + len);
if (!NormalizeScreenPreviewPacket(previewPkt))
break;
// P2c:MCP 挂起时接管(屏幕预览 = 主连接 RPC,不能 CancelIO)。
// reqId 关联:命中 MCP 的 expectedReqId 才取走,避免误吞 MFC 预览在途响应。
uint64_t previewDevId = ContextObject->GetClientID();
const ScreenPreviewRspHeader* previewHdr = reinterpret_cast<const ScreenPreviewRspHeader*>(szBuffer);
if (McpServer().TakePreviewResponse(previewDevId, previewHdr->reqId, szBuffer, len))
const ScreenPreviewRspHeader* previewHdr = reinterpret_cast<const ScreenPreviewRspHeader*>(previewPkt.data());
if (McpServer().TakePreviewResponse(previewDevId, previewHdr->reqId, previewPkt.data(), (ULONG)previewPkt.size()))
break;
auto* msg = new CMy2015RemoteDlg::PreviewRspMsg{
ContextObject->GetClientID(),
std::vector<BYTE>(szBuffer, szBuffer + len)
std::move(previewPkt)
};
if (!g_2015RemoteDlg->PostMessageA(WM_PREVIEW_RESPONSE, 0, (LPARAM)msg)) {
delete msg;
@@ -9531,6 +9535,98 @@ void CMy2015RemoteDlg::ChooseScreenPreviewParams(context* ctx, WORD& maxWidth, B
jpegQuality = q;
}
namespace {
// GDI+ 的 JPEG 编码器 CLSID(Windows 自带,进程内即可用;与 Bmp2Video 的同名逻辑互不影响)
bool FindJpegEncoderClsid(CLSID& clsid)
{
UINT num = 0, size = 0;
if (Gdiplus::GetImageEncodersSize(&num, &size) != Gdiplus::Ok || size == 0) return false;
std::vector<BYTE> buf(size);
Gdiplus::ImageCodecInfo* info = reinterpret_cast<Gdiplus::ImageCodecInfo*>(buf.data());
if (Gdiplus::GetImageEncoders(num, size, info) != Gdiplus::Ok) return false;
for (UINT i = 0; i < num; ++i) {
if (wcscmp(info[i].MimeType, L"image/jpeg") == 0) {
clsid = info[i].Clsid;
return true;
}
}
return false;
}
} // namespace
// 预览响应规范化:Windows 客户端直接回 JPEG,Linux 客户端没有可靠的 JPEG 编码库,
// 回的是原始 BGRA(SCREEN_PREVIEW_FMT_BGRX)。统一在 IO 线程入口转成 JPEG,下游
// (浮窗 / 列表缩略图 / MCP get_screenshot)就只需要认识 JPEG 一种格式。
// 返回 false 表示这个包畸形、不可用,调用方应直接丢弃。
bool CMy2015RemoteDlg::NormalizeScreenPreviewPacket(std::vector<BYTE>& pkt)
{
if (pkt.size() < sizeof(ScreenPreviewRspHeader)) return false;
ScreenPreviewRspHeader* hdr = reinterpret_cast<ScreenPreviewRspHeader*>(pkt.data());
if (hdr->token != TOKEN_SCREEN_PREVIEW_RSP) return false;
if (hdr->format != SCREEN_PREVIEW_FMT_BGRX) return true; // JPEG / 预留格式:原样放行
// 抓屏失败的响应没有像素可转,原样放行,让下游按 status 报"预览不可用"
if (hdr->status != SCREEN_PREVIEW_OK) return true;
// 尺寸与长度校验:请求侧 maxWidth 已限制在 [64,1920],高度按 16:10 上限放宽到 2160
const int w = hdr->width, h = hdr->height;
if (w < 2 || h < 2 || w > 1920 || h > 2160) return false;
const size_t pixels = (size_t)w * h * 4;
if (hdr->bytes != pixels || pkt.size() < sizeof(*hdr) + pixels) return false;
std::vector<BYTE> jpeg;
{
// Bitmap 直接引用包内像素(不复制),所以编码必须在 pkt 被 resize 之前、且
// 在本作用域内完成析构。用栈对象:本 TU 的 `new` 被 MFC 重定义成 DEBUG_NEW,
// Gdiplus 的 operator new 不接受那种三参形式。
Gdiplus::Bitmap bmp(w, h, w * 4, PixelFormat32bppRGB, pkt.data() + sizeof(*hdr));
if (bmp.GetLastStatus() != Gdiplus::Ok) return false;
CLSID clsid;
if (!FindJpegEncoderClsid(clsid)) return false;
// Linux 端不上报质量(它不编码),这里跟随缩略图默认档 70
Gdiplus::EncoderParameters params;
params.Count = 1;
params.Parameter[0].Guid = Gdiplus::EncoderQuality;
params.Parameter[0].Type = Gdiplus::EncoderParameterValueTypeLong;
params.Parameter[0].NumberOfValues = 1;
ULONG quality = 70;
params.Parameter[0].Value = &quality;
IStream* stream = nullptr;
if (FAILED(::CreateStreamOnHGlobal(NULL, TRUE, &stream))) return false;
if (bmp.Save(stream, &clsid, &params) == Gdiplus::Ok) {
// 取实际写入长度:GlobalSize 按堆块对齐,尾部填充字节不能算进 JPEG
LARGE_INTEGER zero = {};
ULARGE_INTEGER end = {}, start = {};
if (SUCCEEDED(stream->Seek(zero, STREAM_SEEK_END, &end)) &&
end.QuadPart > 0 && end.QuadPart <= 16 * 1024 * 1024 &&
SUCCEEDED(stream->Seek(zero, STREAM_SEEK_SET, &start))) {
jpeg.resize((size_t)end.QuadPart);
ULONG read = 0;
if (FAILED(stream->Read(jpeg.data(), (ULONG)jpeg.size(), &read)) ||
read != jpeg.size()) {
jpeg.clear();
}
}
}
stream->Release();
}
if (jpeg.empty()) return false;
// 用 JPEG 覆盖原像素区;宽高沿用客户端上报值(客户端就是按这两个尺寸缩放的)
pkt.resize(sizeof(*hdr) + jpeg.size());
hdr = reinterpret_cast<ScreenPreviewRspHeader*>(pkt.data()); // resize 后重新取
memcpy(pkt.data() + sizeof(*hdr), jpeg.data(), jpeg.size());
hdr->format = SCREEN_PREVIEW_FMT_JPEG;
hdr->bytes = (uint32_t)jpeg.size();
return true;
}
void CMy2015RemoteDlg::SendScreenPreviewRequest(context* ctx, WORD reqId, WORD maxWidth, BYTE jpegQuality)
{
if (!ctx) return;
+3
View File
@@ -621,6 +621,9 @@ public:
void ChooseScreenPreviewParams(context* ctx, WORD& maxWidth, BYTE& jpegQuality) const;
// 发起预览请求;reqId 应与 m_PreviewReqId 同步
void SendScreenPreviewRequest(context* ctx, WORD reqId, WORD maxWidth, BYTE jpegQuality);
// 预览响应规范化:Linux 客户端回原始 BGRA(SCREEN_PREVIEW_FMT_BGRX),在 IO 线程入口
// 统一转成 JPEG,下游(浮窗/列表缩略图/MCP)只处理 JPEG。返回 false 表示畸形包,应丢弃。
static bool NormalizeScreenPreviewPacket(std::vector<BYTE>& pkt);
// 收到 TOKEN_SCREEN_PREVIEW_RSP(在主线程处理)
afx_msg LRESULT OnPreviewResponse(WPARAM wParam, LPARAM lParam);
afx_msg void OnOnlineUnauthorize();
+3 -2
View File
@@ -1951,7 +1951,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
{
Json::Value tool(Json::objectValue);
tool["name"] = "get_screenshot";
tool["description"] = u8"截取指定在线主机的一帧屏幕,返回 base64 编码的 JPEG 图片(image 对象含 mimeType/data/width/height)。仅 Windows 客户端支持(能力位 CLIENT_CAP_SCREEN_PREVIEW),主连接 RPC、一次性返回。";
tool["description"] = u8"截取指定在线主机的一帧屏幕,返回 base64 编码的 JPEG 图片(image 对象含 mimeType/data/width/height)。支持 Windows 与带 X11 桌面的 Linux 客户端(能力位 CLIENT_CAP_SCREEN_PREVIEW),主连接 RPC、一次性返回。";
tool["inputSchema"] = BuildGetScreenshotInputSchema(); // { id } 必填 + max_width 可选
tool["outputSchema"] = BuildScreenshotOutputSchema();
@@ -2951,7 +2951,8 @@ std::string BuildGetScreenshot(const Json::Value& id, const Json::Value& args, C
if (!ctx)
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
// 能力位门槛:仅 Windows 客户端声明 CLIENT_CAP_SCREEN_PREVIEW(非 Windows 返回明确错误)
// 能力位门槛:只有能抓屏的客户端才声明 CLIENT_CAP_SCREEN_PREVIEW
// (Windows 恒声明;Linux 仅在登录时探测到可用 X11 桌面才声明),否则返回明确错误
if (!ctx->SupportsScreenPreview())
return BuildError(id, -32005, "Host does not support screen preview");