跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

提交记录

macOS、Windows 客机浏览器按滚动距离滚动,操作时提高取帧频率 (#51)

一次滚动原先被拆成多组按下与释放,每组让客机滚动固定的 80 像素,并各占两次 客机往返。工作台的浏览器画面与 Cage 自己的画面服务协商后,改为发送滚动的像素 距离,客机按该距离滚动。 在 #51 的协议基础上调整: - 查看端逐帧合并滚动事件。触控板每秒上报几十到上百个小位移,逐个发送会比原先 的往返更多;首个位移立即发出,其余每帧一条,超出单条上限的距离留给下一帧。 - 只有客机在画面中声明支持时才确认协商。旧的客机组件会忽略距离并按固定步长 滚动,它的查看端继续使用原有的滚轮步进。 - Windows 原生菜单与下拉框同样按距离滚动,不再把每条消息当作一格。 - 协商后的浏览器画面在操作后约一秒内按 60 Hz 取帧,其余时间保持 30 Hz 并在 静止时继续放慢,而非无条件提高到 60 Hz。 - 消息编号改用未分配的 180,不占用 xvp 的 250。 客机侧的距离校验与测试来自 #49 的提交。 Refs #44 Co-authored-by: taobeiv <[email protected]> Co-Authored-By: Claude <[email protected]>

作者
Lee-xeo
时间
2026/11/11 14:14
提交
d6f9378
上一个
00a26f7
这个版本的全部文件
修改docs/guide/browser.md+2 −0看文件
@@ -23,6 +23,8 @@ Linux 环境的浏览器和 Claude Desktop 按显示它的屏幕渲染。2 倍
2323
2424按屏幕渲染随环境组件更新启用,需要环境中的 `xsettingsd`:已安装 Claude Desktop 的环境直接生效,只使用浏览器的旧环境在下次更新环境工具后生效。在此之前以及 Windows 客机上,画面继续使用固定的 1.5 倍或 2 倍渲染。
2525
26新增:macOS 和 Windows 客机的浏览器按滚轮或触控板的实际距离滚动。操作时画面最高 60 Hz,停止操作约 1 秒后回到 30 Hz,静止时进一步放慢取帧。此行为在客机组件更新后生效,旧组件继续按固定步长滚动。
27新增:
2628地址栏右侧的下载按钮在右上角展开文件列表,可查看下载进度、另存为、打开文件或在文件夹中显示;保存失败时可重试。长列表在面板内滚动,点击外部或按 Esc 收起。侧栏“下载”也可打开此面板。
2729
2830浏览器设置的“隐私与网站数据”还提供“网站权限”和“清除浏览数据”,打开 Chromium 对应页面。摄像头、麦克风等权限应结合环境实际设备能力判断。“关于浏览器”中的“搜索引擎”和“下载设置”可以打开更多原生浏览器配置;网页显示这些选项不代表 Cage 已接通所有设备能力。
修改internal/workbench/native_frame_pace_test.go+31 −1看文件
@@ -26,7 +26,7 @@ func TestNativeFramePaceBacksOffUntilChangeOrInput(t *testing.T) {
2626 t.Fatalf("pause %d after unchanged frames is %v", i, waits[i])
2727 }
2828 }
29删除: pace.input()
29新增: pace.input(start)
3030 if pace.next().Sub(start) != nativeFrameInterval {
3131 t.Fatal("input did not restore the full rate")
3232 }
@@ -38,6 +38,36 @@ func TestNativeFramePaceBacksOffUntilChangeOrInput(t *testing.T) {
3838 }
3939}
4040
41新增:func TestNativeFramePaceIsFasterOnlyWhileASmoothDisplayIsOperated(t *testing.T) {
42新增: start := time.Unix(1000, 0)
43新增: pace := nativeFramePace{smooth: true}
44新增: pace.requested(start)
45新增: if pace.next().Sub(start) != nativeFrameInterval {
46新增: t.Fatal("an unattended display was requested at the operating rate")
47新增: }
48新增: pace.input(start)
49新增: if pace.next().Sub(start) != nativeOperatingInterval {
50新增: t.Fatal("an operated display kept the usual rate")
51新增: }
52新增: // Unchanged frames still double the pause.
53新增: pace.answered(false)
54新增: if pace.next().Sub(start) != 2*nativeOperatingInterval {
55新增: t.Fatal("an unchanged operated display was not requested less often")
56新增: }
57新增: pace.answered(true)
58新增: later := start.Add(nativeOperatingHold)
59新增: pace.requested(later)
60新增: if pace.next().Sub(later) != nativeFrameInterval {
61新增: t.Fatal("the operating rate outlived the input")
62新增: }
63新增: desktop := nativeFramePace{}
64新增: desktop.requested(start)
65新增: desktop.input(start)
66新增: if desktop.next().Sub(start) != nativeFrameInterval {
67新增: t.Fatal("a display that is not smooth was requested at the operating rate")
68新增: }
69新增:}
70新增:
4171// An unchanged window is asked for rarely, while input still reaches the
4272// guest at once and is followed by a prompt frame request.
4373func TestNativeRFBUnchangedWindowIsPolledSlowlyAndInputIsNotDelayed(t *testing.T) {
修改internal/workbench/windows_display.go+74 −10看文件
@@ -37,6 +37,7 @@ type windowsWindowFrame struct {
3737 Density float64 `json:"density"`
3838 Panes []windowsWindowPane `json:"panes,omitempty"`
3939 Overlays []windowsWindowPane `json:"overlays,omitempty"`
40新增: Wheel bool `json:"pixelWheel,omitempty"` // the guest scrolls by a pointer event's distance
4041}
4142
4243type windowsWindowPane struct {
@@ -426,6 +427,7 @@ func serveWindowsWindowRFB(stream io.ReadWriter, initial windowsWindowFrame, req
426427 sized := false
427428 supportsResize := false
428429 supportsFence := false
430新增: pixelWheel := false
429431 rgbOrder := false
430432 useZlib := false
431433 useTight := false
@@ -605,9 +607,11 @@ func serveWindowsWindowRFB(stream io.ReadWriter, initial windowsWindowFrame, req
605607 useZlib = false
606608 useTight = false
607609 useTightPNG = false
608删除: fenceRequested := false
610新增: fenceRequested, wheelRequested := false, false
609611 for i := 0; i < len(encodings); i += 4 {
610612 switch int32(binary.BigEndian.Uint32(encodings[i:])) {
613新增: case cageWheelEncoding:
614新增: wheelRequested = true
611615 case -312:
612616 fenceRequested = true
613617 case -223:
@@ -627,6 +631,19 @@ func serveWindowsWindowRFB(stream io.ReadWriter, initial windowsWindowFrame, req
627631 }
628632 }
629633 supportsFence = fenceRequested
634新增: // An older guest would scroll one fixed step for every distance.
635新增: wheelRequested = wheelRequested && initial.Wheel
636新增: if fenceRequested && wheelRequested && !pixelWheel {
637新增: // The viewer sends distances only after this confirmation.
638新增: confirmation := append([]byte{248, 0, 0, 0, 0x80, 0, 0, 0, byte(len(cageWheelCapability))}, cageWheelCapability...)
639新增: if err := write(confirmation); err != nil {
640新增: return err
641新增: }
642新增: }
643新增: pixelWheel = fenceRequested && wheelRequested
644新增: // Only the browser display offers the wheel. Its guest streams
645新增: // frames as it composes them, so scrolling can be shown at 60 Hz.
646新增: pace.smooth = pixelWheel
630647 case 3:
631648 if body[0] == 0 {
632649 incremental = false
@@ -649,6 +666,30 @@ func serveWindowsWindowRFB(stream io.ReadWriter, initial windowsWindowFrame, req
649666 if err := request(map[string]any{"action": "pointer", "target": frame.Target, "mask": body[0], "x": binary.BigEndian.Uint16(body[1:]), "y": binary.BigEndian.Uint16(body[3:])}, nil); err != nil {
650667 return err
651668 }
669新增: case cageWheelMessage:
670新增: dx, dy := int32(binary.BigEndian.Uint32(body[5:])), int32(binary.BigEndian.Uint32(body[9:]))
671新增: if !pixelWheel || body[0] != 0 || dx < -cageWheelLimit || dx > cageWheelLimit || dy < -cageWheelLimit || dy > cageWheelLimit {
672新增: return errors.New("画面滚动消息无效")
673新增: }
674新增: if !sized || dx == 0 && dy == 0 {
675新增: continue
676新增: }
677新增: // The direction bits let a guest without distances scroll one step.
678新增: mask := 0
679新增: if dx < 0 {
680新增: mask |= 32
681新增: } else if dx > 0 {
682新增: mask |= 64
683新增: }
684新增: if dy < 0 {
685新增: mask |= 8
686新增: } else if dy > 0 {
687新增: mask |= 16
688新增: }
689新增: if err := request(map[string]any{"action": "pointer", "target": frame.Target, "mask": mask,
690新增: "x": binary.BigEndian.Uint16(body[1:]), "y": binary.BigEndian.Uint16(body[3:]), "deltaX": dx, "deltaY": dy}, nil); err != nil {
691新增: return err
692新增: }
652693 case 6:
653694 // Native shared clipboard owns clipboard data; committed text takes the
654695 // fixed Unicode input path without changing the OS clipboard.
@@ -670,10 +711,10 @@ func serveWindowsWindowRFB(stream io.ReadWriter, initial windowsWindowFrame, req
670711 }
671712 }
672713 }
673删除: if message[0] == 4 || message[0] == 5 || message[0] == 6 {
714新增: if message[0] == 4 || message[0] == 5 || message[0] == 6 || message[0] == cageWheelMessage {
674715 // The window answers input at once: the next frame is not delayed
675716 // by the pauses of an unchanged screen.
676删除: pace.input()
717新增: pace.input(time.Now())
677718 if pending {
678719 schedule()
679720 }
@@ -681,20 +722,41 @@ func serveWindowsWindowRFB(stream io.ReadWriter, initial windowsWindowFrame, req
681722 }
682723}
683724
684删除:// nativeFrameInterval is the shortest time between two frame requests.
685删除:const nativeFrameInterval = time.Second / 30
725新增:// nativeFrameInterval is the shortest time between two frame requests, and
726新增:// nativeOperatingInterval the one a browser display has while it is operated.
727新增:const (
728新增: nativeFrameInterval = time.Second / 30
729新增: nativeOperatingInterval = time.Second / 60
730新增: nativeOperatingHold = time.Second
731新增:)
732新增:
733新增:// The Cage browser display sends the scrolled distance in one message. It
734新增:// offers the encoding, and uses the message once a fence names the capability.
735新增:const (
736新增: cageWheelEncoding = -57345
737新增: cageWheelMessage = 180
738新增: cageWheelCapability = "cage-wheel-v1"
739新增: cageWheelLimit = 2048
740新增:)
686741
687742// nativeFramePace spaces frame requests to a native guest. Each one is a
688743// round trip into the guest, also when its window has not changed, so the
689744// pause doubles with every unchanged answer, up to about a quarter second.
690删除:// A changed frame or the viewer's input restores the shortest pause.
745新增:// A changed frame or the viewer's input restores the shortest pause. Every
746新增:// frame is a complete image: a smooth display has the shorter pause only for
747新增:// a moment after input, and plays unattended animation at the usual one.
691748type nativeFramePace struct {
692删除: last time.Time
693删除: unchanged int
749新增: last, acted time.Time
750新增: unchanged int
751新增: smooth bool
694752}
695753
696754func (p *nativeFramePace) next() time.Time {
697删除: return p.last.Add(nativeFrameInterval << min(p.unchanged, 3))
755新增: interval := nativeFrameInterval
756新增: if p.smooth && !p.acted.IsZero() && p.last.Sub(p.acted) < nativeOperatingHold {
757新增: interval = nativeOperatingInterval
758新增: }
759新增: return p.last.Add(interval << min(p.unchanged, 3))
698760}
699761
700762func (p *nativeFramePace) requested(now time.Time) { p.last = now }
@@ -707,7 +769,7 @@ func (p *nativeFramePace) answered(changed bool) {
707769 }
708770}
709771
710删除:func (p *nativeFramePace) input() { p.unchanged = 0 }
772新增:func (p *nativeFramePace) input(now time.Time) { p.unchanged, p.acted = 0, now }
711773
712774// readRFBClientMessage reads one complete client message, type byte first.
713775func readRFBClientMessage(stream io.Reader) ([]byte, error) {
@@ -747,6 +809,8 @@ func readRFBClientMessage(stream io.Reader) ([]byte, error) {
747809 }
748810 err = extend(int(size))
749811 }
812新增: case cageWheelMessage:
813新增: err = extend(13)
750814 case 248:
751815 if err = extend(8); err == nil {
752816 if message[8] > 64 {
新增internal/workbench/windows_wheel_test.go+164 −0看文件
@@ -0,0 +1,164 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "encoding/binary"
5新增: "io"
6新增: "net"
7新增: "testing"
8新增: "time"
9新增:)
10新增:
11新增:func TestWindowsWindowRFBPixelWheel(t *testing.T) {
12新增: for _, tc := range []struct {
13新增: name string
14新增: negotiated bool
15新增: delta int32
16新增: accepted bool
17新增: }{
18新增: {"distance", true, 720, true}, {"reverse", true, -360, true},
19新增: {"unnegotiated", false, 100, false}, {"bounded", true, 2049, false},
20新增: } {
21新增: t.Run(tc.name, func(t *testing.T) {
22新增: frame := windowTestFrame(t, 2, 1)
23新增: frame.Target = "verified-frame"
24新增: frame.Wheel = true
25新增: server, client := net.Pipe()
26新增: defer client.Close()
27新增: client.SetDeadline(time.Now().Add(5 * time.Second))
28新增: inputs := make(chan map[string]any, 1)
29新增: done := make(chan error, 1)
30新增: go func() {
31新增: defer server.Close()
32新增: done <- serveWindowsWindowRFB(server, frame, func(input map[string]any, output any) error {
33新增: if input["action"] == "frame" {
34新增: *output.(*windowsWindowFrame) = frame
35新增: } else {
36新增: inputs <- input
37新增: }
38新增: return nil
39新增: })
40新增: }()
41新增: read := func(n int) []byte {
42新增: t.Helper()
43新增: b := make([]byte, n)
44新增: if _, e := io.ReadFull(client, b); e != nil {
45新增: t.Fatal(e)
46新增: }
47新增: return b
48新增: }
49新增: write := func(b []byte) {
50新增: t.Helper()
51新增: if _, e := client.Write(b); e != nil {
52新增: t.Fatal(e)
53新增: }
54新增: }
55新增: read(12)
56新增: write([]byte("RFB 003.008\n"))
57新增: read(2)
58新增: write([]byte{1})
59新增: read(4)
60新增: write([]byte{1})
61新增: init := read(24)
62新增: read(int(binary.BigEndian.Uint32(init[20:])))
63新增: if tc.negotiated {
64新增: packet := []byte{2, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0}
65新增: fence, wheel := int32(-312), int32(cageWheelEncoding)
66新增: binary.BigEndian.PutUint32(packet[4:], uint32(fence))
67新增: binary.BigEndian.PutUint32(packet[8:], uint32(wheel))
68新增: write(packet)
69新增: read(9)
70新增: header := read(9)
71新增: if string(read(int(header[8]))) != cageWheelCapability {
72新增: t.Fatal("missing capability")
73新增: }
74新增: }
75新增: write([]byte{3, 0, 0, 0, 0, 0, 0, 2, 0, 1})
76新增: read(24)
77新增: packet := make([]byte, 14)
78新增: packet[0] = cageWheelMessage
79新增: binary.BigEndian.PutUint16(packet[2:], 1)
80新增: binary.BigEndian.PutUint32(packet[10:], uint32(tc.delta))
81新增: write(packet)
82新增: if tc.accepted {
83新增: select {
84新增: case input := <-inputs:
85新增: if input["deltaY"] != tc.delta || input["target"] != "verified-frame" || input["action"] != "pointer" {
86新增: t.Fatalf("invalid input %v", input)
87新增: }
88新增: case <-time.After(time.Second):
89新增: t.Fatal("wheel missing")
90新增: }
91新增: // The same stream remains ready for subsequent frames.
92新增: write([]byte{3, 0, 0, 0, 0, 0, 0, 2, 0, 1})
93新增: read(24)
94新增: } else {
95新增: select {
96新增: case e := <-done:
97新增: if e == nil {
98新增: t.Fatal("invalid wheel accepted")
99新增: }
100新增: case <-time.After(time.Second):
101新增: t.Fatal("invalid wheel not rejected")
102新增: }
103新增: }
104新增: })
105新增: }
106新增:}
107新增:
108新增:// An older guest ignores distances and scrolls one fixed step per event, so
109新增:// its viewer keeps the wheel steps of RFB.
110新增:func TestWindowsWindowRFBKeepsWheelStepsForAGuestWithoutDistances(t *testing.T) {
111新增: frame := windowTestFrame(t, 2, 1)
112新增: server, client := net.Pipe()
113新增: defer client.Close()
114新增: client.SetDeadline(time.Now().Add(5 * time.Second))
115新增: done := make(chan error, 1)
116新增: go func() {
117新增: defer server.Close()
118新增: done <- serveWindowsWindowRFB(server, frame, func(input map[string]any, output any) error {
119新增: if input["action"] == "frame" {
120新增: *output.(*windowsWindowFrame) = frame
121新增: }
122新增: return nil
123新增: })
124新增: }()
125新增: read := func(n int) []byte {
126新增: t.Helper()
127新增: b := make([]byte, n)
128新增: if _, e := io.ReadFull(client, b); e != nil {
129新增: t.Fatal(e)
130新增: }
131新增: return b
132新增: }
133新增: read(12)
134新增: client.Write([]byte("RFB 003.008\n"))
135新增: read(2)
136新增: client.Write([]byte{1})
137新增: read(4)
138新增: client.Write([]byte{1})
139新增: init := read(24)
140新增: read(int(binary.BigEndian.Uint32(init[20:])))
141新增: packet := []byte{2, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0}
142新增: fence, wheel := int32(-312), int32(cageWheelEncoding)
143新增: binary.BigEndian.PutUint32(packet[4:], uint32(fence))
144新增: binary.BigEndian.PutUint32(packet[8:], uint32(wheel))
145新增: client.Write(packet)
146新增: read(9)
147新增: // The next message is the frame, not a confirmation of the wheel.
148新增: client.Write([]byte{3, 0, 0, 0, 0, 0, 0, 2, 0, 1})
149新增: if update := read(24); update[0] != 0 {
150新增: t.Fatalf("unexpected message %d", update[0])
151新增: }
152新增: distance := make([]byte, 14)
153新增: distance[0] = cageWheelMessage
154新增: binary.BigEndian.PutUint32(distance[10:], 100)
155新增: client.Write(distance)
156新增: select {
157新增: case err := <-done:
158新增: if err == nil {
159新增: t.Fatal("a distance was accepted without confirmation")
160新增: }
161新增: case <-time.After(time.Second):
162新增: t.Fatal("a distance was not rejected")
163新增: }
164新增:}
修改scripts/guest-os/guest-clipboard-windows/BrowserWindowCapture.cs+14 −2看文件
@@ -382,8 +382,20 @@ internal static class BrowserWindowCapture
382382 if(!SetCursorPos(screenX,screenY))throw new InvalidDataException("browser_input_failed");
383383 var mouseMask=NativeGuestInput.PressedButtons(lease);var inputs=new List<InputStroke>();
384384 foreach(var bit in new[]{1,2,4})if((mask&bit)!=(mouseMask&bit))inputs.Add(InputStroke.Button(bit,(mask&bit)==0));
385删除: if((mask&24)!=0)inputs.Add(InputStroke.Wheel((mask&8)!=0?120:-120));
386删除: if((mask&96)!=0)inputs.Add(InputStroke.Wheel((mask&32)!=0?-120:120,true));
385新增: if(input["deltaX"] is not null||input["deltaY"] is not null)
386新增: {
387新增: // A viewer that sends the scrolled distance gets that distance in
388新增: // native menus as well: 100 pixels are one wheel notch.
389新增: var deltaX=input["deltaX"]?.GetValue<int>()??0;var deltaY=input["deltaY"]?.GetValue<int>()??0;
390新增: if(Math.Abs(deltaX)>2048||Math.Abs(deltaY)>2048)throw new InvalidDataException("browser_input_invalid");
391新增: if(deltaY!=0)inputs.Add(InputStroke.Wheel(-deltaY*120/100));
392新增: if(deltaX!=0)inputs.Add(InputStroke.Wheel(deltaX*120/100,true));
393新增: }
394新增: else
395新增: {
396新增: if((mask&24)!=0)inputs.Add(InputStroke.Wheel((mask&8)!=0?120:-120));
397新增: if((mask&96)!=0)inputs.Add(InputStroke.Wheel((mask&32)!=0?-120:120,true));
398新增: }
387399 if(inputs.Count>0)Emit(view,lease,inputs.ToArray());
388400 }
389401 private static void Keyboard(View view,InputLease lease,JsonObject input)
修改scripts/guest-os/tests/windows-browser.test.mjs+16 −0看文件
@@ -466,6 +466,22 @@ integration("a scrolled browser viewport stays visible while a web font is loadi
466466 } finally { clearTimeout(timer); releaseFont(); }
467467});
468468
469新增:integration("pixel wheel preserves distance and still rejects stale targets and invalid bounds", async t => {
470新增: const f = await fixture(t), { page } = await f.open();
471新增: await page.evaluate(() => { document.body.style.height = "6000px"; document.documentElement.style.scrollBehavior = "auto"; });
472新增: const frame = await f.call("frame", {}, "GET");
473新增: const wheel = { kind: "pointer", target: frame.target, x: 600, y: 600, mask: 16, deltaX: 0, deltaY: 720 };
474新增: await f.call("input", wheel);
475新增: await page.waitForFunction(() => scrollY >= 700);
476新增: assert.equal(await page.evaluate(() => scrollY), 720);
477新增: await f.call("input", { ...wheel, mask: 8, deltaY: -360 });
478新增: await page.waitForFunction(() => scrollY === 360);
479新增: await assert.rejects(f.call("input", { ...wheel, target: "stale" }), /target changed/);
480新增: await assert.rejects(f.call("input", { ...wheel, deltaY: 2049 }), /滚动距离/);
481新增: await assert.rejects(f.call("input", { ...wheel, mask: 17 }), /滚动距离/);
482新增: assert.equal(await page.evaluate(() => scrollY), 360);
483新增:});
484新增:
469485integration("audit reads configured browser state separately from expected values and preserves actual HTTP failures", async t => {
470486 const f = await fixture(t, { timezone: "Pacific/Honolulu", language: "ja-JP", diagnostic: true }), one = await f.open();
471487 await f.context().addCookies([{ name: "private_fixture", value: "test-only", domain: "198.18.0.254", path: "/" }]);
修改scripts/guest-os/windows-browser.mjs+8 −4看文件
@@ -952,6 +952,10 @@ export function createNativeBrowserService(options = {}) {
952952 if (input.target !== (split?.generation ?? tab.geometry)) throw failure("target_changed", "Input target changed");
953953 if (input.kind === "pointer") {
954954 if (!Number.isInteger(input.mask) || input.mask < 0 || input.mask > 127 || ![input.x, input.y].every(Number.isFinite) || input.x < 0 || input.y < 0 || input.x >= viewport.width * displayScale || input.y >= viewport.height * displayScale) throw failure("invalid_input", "指针位置无效");
955新增: // Frames announce pixelWheel; a viewer may then send the scrolled
956新增: // distance in pixels in place of one fixed step per event.
957新增: const pixelWheel = input.deltaX !== undefined || input.deltaY !== undefined;
958新增: if (pixelWheel && (![input.deltaX, input.deltaY].every(v => Number.isInteger(v) && Math.abs(v) <= 2048) || (input.mask & 7) || !(input.mask & 120))) throw failure("invalid_input", "滚动距离无效");
955959 const x = Math.max(0, Math.min(tab.page.viewportSize().width - 1, (input.x - xOffset) / displayScale)), y = input.y / displayScale, mask = input.mask & 7;
956960 const modifiers = Number.isInteger(input.modifiers) && input.modifiers >= 0 && input.modifiers <= 15 ? input.modifiers : 0;
957961 const buttons = ((mask & 1) ? 1 : 0) | ((mask & 2) ? 4 : 0) | ((mask & 4) ? 2 : 0);
@@ -965,8 +969,8 @@ export function createNativeBrowserService(options = {}) {
965969 if (down) lastClick = { button, x, y, count, time: now };
966970 }
967971 signal?.throwIfAborted();
968删除: await cdp("Input.dispatchMouseEvent", { type: "mouseMoved", x, y, buttons, modifiers }, tab.session);
969删除: const deltaY = (input.mask & 8 ? -80 : 0) + (input.mask & 16 ? 80 : 0), deltaX = (input.mask & 32 ? -80 : 0) + (input.mask & 64 ? 80 : 0);
972新增: if (!pixelWheel) await cdp("Input.dispatchMouseEvent", { type: "mouseMoved", x, y, buttons, modifiers }, tab.session);
973新增: const deltaY = pixelWheel ? input.deltaY : (input.mask & 8 ? -80 : 0) + (input.mask & 16 ? 80 : 0), deltaX = pixelWheel ? input.deltaX : (input.mask & 32 ? -80 : 0) + (input.mask & 64 ? 80 : 0);
970974 if (deltaX || deltaY) await cdp("Input.dispatchMouseEvent", { type: "mouseWheel", x, y, deltaX, deltaY, buttons, modifiers }, tab.session);
971975 rfbMask = mask; if (!mask) rfbPane = undefined; return { ok: true, active };
972976 }
@@ -1218,7 +1222,7 @@ export function createNativeBrowserService(options = {}) {
12181222 panes.push({ jpeg, x, y: 0, width, height, id, document }); x += width;
12191223 }
12201224 if (bytes > 8 << 20) throw failure("frame_limit", "浏览器画面过大,请缩小窗口后重试");
1221删除: return { sequence, target: generation, width: x, height: Math.round(viewport.height * displayScale), scale: displayScale, panes, active, native: await nativeFrameProof() };
1225新增: return { sequence, target: generation, width: x, height: Math.round(viewport.height * displayScale), scale: displayScale, panes, active, pixelWheel: true, native: await nativeFrameProof() };
12221226 }
12231227 const geometry = tab.geometry, document = tab.document;
12241228 const captured = await captureFrame(tab);
@@ -1226,7 +1230,7 @@ export function createNativeBrowserService(options = {}) {
12261230 if (tab.id !== active || tab.geometry !== geometry || tab.document !== document) throw failure("target_changed", "Input target changed");
12271231 if (input.after === sequence) return { unchanged: true, sequence, ...(input.nativeProof ? { native: await nativeFrameProof() } : {}) };
12281232 if (Buffer.byteLength(captured.jpeg, "base64") > 8 << 20) throw failure("frame_limit", "浏览器画面过大,请缩小窗口后重试");
1229删除: return { ...(mac ? {url: page.url(), title: await page.title()} : {}), sequence, id: tab.id, document, jpeg: captured.jpeg, target: geometry, width: Math.round(viewport.width * displayScale), height: Math.round(viewport.height * displayScale), cssWidth: viewport.width, cssHeight: viewport.height, scale: displayScale, native: await nativeFrameProof() };
1233新增: return { ...(mac ? {url: page.url(), title: await page.title()} : {}), sequence, id: tab.id, document, jpeg: captured.jpeg, target: geometry, width: Math.round(viewport.width * displayScale), height: Math.round(viewport.height * displayScale), cssWidth: viewport.width, cssHeight: viewport.height, scale: displayScale, pixelWheel: true, native: await nativeFrameProof() };
12301234 }
12311235 if (action === "activate") return activate(tab.id);
12321236 if (action === "close") { await page.close(); if (!tabs.size) await addPage(await context.newPage()); if (active) await activate(active); return { ok: true }; }
新增ui/src/cage-wheel.test.mjs+58 −0看文件
@@ -0,0 +1,58 @@
1新增:import assert from "node:assert/strict";
2新增:import test from "node:test";
3新增:import CageWheel, { cageWheelLimit, cageWheelMessage, cageWheelPacket } from "../vendor/novnc/core/cage-wheel.js";
4新增:
5新增:function fixture() {
6新增: const sent = [], frames = [];
7新增: const wheel = new CageWheel((...message) => sent.push(message), callback => frames.push(callback), handle => { frames[handle - 1] = null; });
8新增: // One display frame: run what was scheduled for it.
9新增: const frame = () => { for (const callback of frames.splice(0)) callback?.(); };
10新增: return { wheel, sent, frames, frame };
11新增:}
12新增:
13新增:test("the first distance is sent at once and later ones once per frame", () => {
14新增: const { wheel, sent, frame } = fixture();
15新增: wheel.add(10, 20, 0, 120);
16新增: assert.deepEqual(sent, [[10, 20, 0, 120]]);
17新增: // A trackpad reports many small distances between two frames.
18新增: for (const distance of [3, 4.5, 2.25, 7]) wheel.add(11, 21, 0, distance);
19新增: assert.equal(sent.length, 1);
20新增: frame();
21新增: assert.deepEqual(sent[1], [11, 21, 0, 17]);
22新增: // The fraction of a pixel is kept, and an idle frame ends the series.
23新增: frame();
24新增: assert.equal(sent.length, 2);
25新增: wheel.add(12, 22, 0, 0.75);
26新增: assert.deepEqual(sent[2], [12, 22, 0, 1]);
27新增:});
28新增:
29新增:test("distance beyond one message is carried into the next frames", () => {
30新增: const { wheel, sent, frame } = fixture();
31新增: wheel.add(1, 2, -5000, 3000);
32新增: frame();
33新增: frame();
34新增: frame();
35新增: assert.deepEqual(sent, [[1, 2, -cageWheelLimit, cageWheelLimit], [1, 2, -cageWheelLimit, 952], [1, 2, -904, 0]]);
36新增:});
37新增:
38新增:test("less than a pixel waits, and stopping discards what was not sent", () => {
39新增: const { wheel, sent, frame, frames } = fixture();
40新增: wheel.add(1, 2, 0.2, 0.2);
41新增: assert.equal(sent.length, 0);
42新增: assert.equal(frames.length, 0);
43新增: wheel.add(1, 2, 0.4, 0);
44新增: assert.deepEqual(sent, [[1, 2, 1, 0]]);
45新增: wheel.add(1, 2, 0, 300);
46新增: wheel.stop();
47新增: frame();
48新增: assert.equal(sent.length, 1);
49新增: wheel.add(3, 4, 0, -40);
50新增: assert.deepEqual(sent[1], [3, 4, 0, -40]);
51新增:});
52新增:
53新增:test("a message carries its position and signed distances", () => {
54新增: const packet = cageWheelPacket(513, 1026, -720, 2048), view = new DataView(packet.buffer);
55新增: assert.equal(packet.length, 14);
56新增: assert.deepEqual([packet[0], packet[1]], [cageWheelMessage, 0]);
57新增: assert.deepEqual([view.getUint16(2), view.getUint16(4), view.getInt32(6), view.getInt32(10)], [513, 1026, -720, 2048]);
58新增:});
修改ui/vendor/novnc/NOTICE.cage+2 −1看文件
@@ -1,6 +1,7 @@
11noVNC is distributed under MPL-2.0. See LICENSE.txt and docs/LICENSE.MPL-2.0.
22
33The Cage workbench includes local changes for clipboard transfer, native input
4删除:method composition, frame retention during resize, and decoder cleanup.
4新增:method composition, frame retention during resize, a local cursor fallback,
5新增:pixel wheel distances, and decoder cleanup.
56The modified source is included in the application under licenses/novnc-source.
67Other component licenses are included under docs/ and vendor/pako/LICENSE.
新增ui/vendor/novnc/core/cage-wheel.js+62 −0看文件
@@ -0,0 +1,62 @@
1新增:/*
2新增: * Cage workbench pixel wheel.
3新增: * Licensed under MPL 2.0 (see LICENSE.txt)
4新增: */
5新增:
6新增:// Cage's own display server takes the scrolled distance in one message,
7新增:// where RFB sends a press and a release for each fixed step.
8新增:export const cageWheelEncoding = -57345;
9新增:export const cageWheelCapability = 'cage-wheel-v1';
10新增:export const cageWheelMessage = 180;
11新增:export const cageWheelLimit = 2048;
12新增:
13新增:// type, padding, x, y, then the signed horizontal and vertical distance.
14新增:export function cageWheelPacket(x, y, dx, dy) {
15新增: const packet = new Uint8Array(14), view = new DataView(packet.buffer);
16新增: packet[0] = cageWheelMessage;
17新增: view.setUint16(2, x);
18新增: view.setUint16(4, y);
19新增: view.setInt32(6, dx);
20新增: view.setInt32(10, dy);
21新增: return packet;
22新增:}
23新增:
24新增:// A trackpad reports many small distances, and each message is a round trip
25新增:// to the guest. The first goes out at once; later ones are added up and sent
26新增:// once per frame. Distance beyond the limit of one message stays for the next.
27新增:export default class CageWheel {
28新增: constructor(send, schedule = callback => requestAnimationFrame(callback),
29新增: cancel = handle => cancelAnimationFrame(handle)) {
30新增: this._send = send;
31新增: this._schedule = schedule;
32新增: this._cancel = cancel;
33新增: this._x = this._y = this._dx = this._dy = 0;
34新增: this._frame = null;
35新增: }
36新增:
37新增: add(x, y, dx, dy) {
38新增: this._x = x;
39新增: this._y = y;
40新增: this._dx += dx;
41新增: this._dy += dy;
42新增: if (this._frame === null) this._flush();
43新增: }
44新增:
45新增: _flush() {
46新增: this._frame = null;
47新增: const dx = Math.max(-cageWheelLimit, Math.min(cageWheelLimit, Math.round(this._dx)));
48新增: const dy = Math.max(-cageWheelLimit, Math.min(cageWheelLimit, Math.round(this._dy)));
49新增: // Less than a pixel waits for the next event.
50新增: if (!dx && !dy) return;
51新增: this._dx -= dx;
52新增: this._dy -= dy;
53新增: this._send(this._x, this._y, dx, dy);
54新增: this._frame = this._schedule(() => this._flush());
55新增: }
56新增:
57新增: stop() {
58新增: if (this._frame !== null) this._cancel(this._frame);
59新增: this._frame = null;
60新增: this._dx = this._dy = 0;
61新增: }
62新增:}
修改ui/vendor/novnc/core/rfb.js+32 −0看文件
@@ -16,6 +16,7 @@ import { setCapture } from './util/events.js';
1616import EventTargetMixin from './util/eventtarget.js';
1717import Display from "./display.js";
1818import CageBrowserDisplay from "./cage-browser-display.js";
19新增:import CageWheel, { cageWheelCapability, cageWheelEncoding, cageWheelPacket } from "./cage-wheel.js";
1920import Inflator from "./inflator.js";
2021import Deflator from "./deflator.js";
2122import Keyboard from "./input/keyboard.js";
@@ -195,6 +196,10 @@ export default class RFB extends EventTargetMixin {
195196 this._viewportHasMoved = false;
196197 this._accumulatedWheelDeltaX = 0;
197198 this._accumulatedWheelDeltaY = 0;
199新增: // Offered to Cage's own display server, which confirms it in a fence.
200新增: this._cageBrowserDisplay = !!options.cageBrowserDisplay;
201新增: this._cagePixelWheel = false;
202新增: this._cageWheel = new CageWheel((x, y, dx, dy) => this._cageSendWheel(x, y, dx, dy));
198203
199204 // Gesture state
200205 this._gestureLastTapTime = null;
@@ -641,6 +646,7 @@ export default class RFB extends EventTargetMixin {
641646 }
642647 clearTimeout(this._resizeTimeout);
643648 clearTimeout(this._mouseMoveTimer);
649新增: this._cageWheel.stop();
644650 Log.Debug("<< RFB.disconnect");
645651 }
646652
@@ -1243,6 +1249,15 @@ export default class RFB extends EventTargetMixin {
12431249 let dX = ev.deltaX;
12441250 let dY = ev.deltaY;
12451251
1252新增: // Cage: the guest scrolls by the distance itself. A wheel turned
1253新增: // while a button is held keeps the steps below, which carry the mask.
1254新增: if (this._cagePixelWheel && bmask === 0) {
1255新增: const unit = ev.deltaMode === 1 ? WHEEL_LINE_HEIGHT :
1256新增: ev.deltaMode === 2 ? this._canvas.clientHeight : 1;
1257新增: this._cageWheel.add(pos.x, pos.y, dX * unit, dY * unit);
1258新增: return;
1259新增: }
1260新增:
12461261 // Pixel units unless it's non-zero.
12471262 // Note that if deltamode is line or page won't matter since we aren't
12481263 // sending the mouse wheel delta to the server anyway.
@@ -1286,6 +1301,17 @@ export default class RFB extends EventTargetMixin {
12861301 }
12871302 }
12881303
1304新增: _cageSendWheel(x, y, dx, dy) {
1305新增: const send = () => {
1306新增: if (this._rfbConnectionState !== 'connected' || this._viewOnly) return;
1307新增: this._sock.sQpushBytes(cageWheelPacket(this._display.absX(x), this._display.absY(y), dx, dy));
1308新增: this._sock.flush();
1309新增: };
1310新增: // Stay behind input that is still waiting for its turn.
1311新增: if (this._cageInputChain) this._cageQueueInput(send);
1312新增: else send();
1313新增: }
1314新增:
12891315 _fakeMouseMove(ev, elementX, elementY) {
12901316 this._handleMouseMove(elementX, elementY);
12911317 this._cursor.move(ev.detail.clientX, ev.detail.clientY);
@@ -2272,6 +2298,9 @@ export default class RFB extends EventTargetMixin {
22722298 encs.push(encodings.pseudoEncodingCursor);
22732299 }
22742300
2301新增: // Unknown to other servers, which skip it.
2302新增: if (this._cageBrowserDisplay) encs.push(cageWheelEncoding);
2303新增:
22752304 RFB.messages.clientEncodings(this._sock, encs);
22762305 }
22772306
@@ -2511,6 +2540,9 @@ export default class RFB extends EventTargetMixin {
25112540 }
25122541
25132542 const payload = this._sock.rQshiftStr(length);
2543新增: if ((flags & (1 << 31)) && this._cageBrowserDisplay && payload === cageWheelCapability) {
2544新增: this._cagePixelWheel = true;
2545新增: }
25142546
25152547 this._supportsFence = true;
25162548