跳到主要内容

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

浏览文件

display-governor.test.py

189 行 · 8.8 KB历史下载
1import importlib.util
2import os
3from pathlib import Path
4import shutil
5import struct
6import subprocess
7import sys
8import tempfile
9import time
10import unittest
11
12spec = importlib.util.spec_from_file_location('display_governor', Path(__file__).with_name('display-governor.py'))
13governor = importlib.util.module_from_spec(spec)
14spec.loader.exec_module(governor)
15
16try:
17 from Xlib import X, display
18 from Xlib.ext import xtest
19except ImportError:
20 display = None
21
22
23class PolicyTests(unittest.TestCase):
24 def test_rate_follows_time_since_input(self):
25 self.assertEqual(governor.target_rate(0), 60)
26 self.assertEqual(governor.target_rate(2.9), 60)
27 self.assertEqual(governor.target_rate(3), 30)
28 self.assertEqual(governor.target_rate(179), 30)
29 self.assertEqual(governor.target_rate(180), 20)
30
31 def test_wakes_exactly_at_the_next_change(self):
32 self.assertAlmostEqual(governor.next_change(1), 2)
33 self.assertAlmostEqual(governor.next_change(10), 170)
34 self.assertIsNone(governor.next_change(500))
35
36 def test_only_its_own_modes_are_governed(self):
37 self.assertTrue(governor.governed('fps30-2339x1368'))
38 # Size owners keep, match and delete these names themselves.
39 for name in ('cage-2339x1368', 'cage-phone-800x600', '1600x1000', 'fps-1x2', 'fps30-1x', 'fps30', 'fpsx-1x2'):
40 self.assertFalse(governor.governed(name), name)
41
42 def test_mode_has_the_requested_refresh_rate(self):
43 for rate in (20, 30, 60):
44 mode = governor.mode_timing(rate, 2339, 1368)
45 self.assertAlmostEqual(mode['dot_clock'] / (mode['h_total'] * mode['v_total']), rate)
46 self.assertEqual((mode['width'], mode['height']), (2339, 1368))
47 self.assertEqual(mode['name_length'], len(governor.mode_name(rate, 2339, 1368)))
48
49 def test_full_rate_returns_to_the_size_owners_mode(self):
50 base = ('cage-800x600', 800, 600)
51 passive = ('fps30-800x600', 800, 600)
52 self.assertEqual(governor.choose_mode(30, base, None, {base}), ('fps30-800x600', base))
53 self.assertEqual(governor.choose_mode(60, passive, base, {base, passive}), ('cage-800x600', base))
54 self.assertEqual(governor.choose_mode(60, base, base, {base}), ('cage-800x600', base))
55
56 def test_full_rate_never_restores_another_size(self):
57 stale = ('cage-800x600', 800, 600)
58 current = ('fps30-1024x768', 1024, 768)
59 self.assertEqual(governor.choose_mode(60, current, stale, {stale, current})[0], 'fps60-1024x768')
60 # The owner removed its mode while the display was passive.
61 self.assertEqual(governor.choose_mode(60, ('fps30-800x600', 800, 600), stale, set())[0], 'fps60-800x600')
62
63 def test_raw_key_reads_the_keycode(self):
64 self.assertEqual(governor.raw_key(struct.pack('=HIIHHII', 3, 1234, 250, 3, 0, 0, 0)), 250)
65 self.assertIsNone(governor.raw_key(b'short'))
66 self.assertIsNone(governor.raw_key(None))
67
68
69@unittest.skipUnless(display and shutil.which('Xtigervnc') and shutil.which('xrandr'), 'needs Xtigervnc, xrandr and python3-xlib')
70class DisplayTests(unittest.TestCase):
71 """The governor against a private virtual display."""
72
73 def setUp(self):
74 self.temp = tempfile.TemporaryDirectory(dir='/tmp')
75 self.addCleanup(self.temp.cleanup)
76 number = next(n for n in range(120, 200) if not os.path.exists(f'/tmp/.X11-unix/X{n}'))
77 self.env = dict(os.environ, DISPLAY=f':{number}')
78 self.env.pop('XAUTHORITY', None)
79 server = subprocess.Popen(['Xtigervnc', f':{number}', '-geometry', '800x600', '-depth', '24', '-rfbport', '-1',
80 '-rfbunixpath', self.temp.name + '/d.sock', '-nolisten', 'tcp', '-SecurityTypes', 'None'],
81 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
82 self.addCleanup(server.wait)
83 self.addCleanup(server.terminate)
84 for attempt in range(100):
85 if os.path.exists(f'/tmp/.X11-unix/X{number}'):
86 break
87 time.sleep(.05)
88 else:
89 self.fail('virtual display did not start')
90 self.conn = display.Display(f':{number}')
91 self.addCleanup(self.conn.close)
92 self.root = self.conn.screen().root
93 script = (f'import importlib.util, sys\n'
94 f'spec = importlib.util.spec_from_file_location("g", {str(Path(__file__).with_name("display-governor.py"))!r})\n'
95 f'g = importlib.util.module_from_spec(spec); spec.loader.exec_module(g)\n'
96 f'g.ACTIVE_HOLD, g.IDLE_AFTER = .5, 1.5\nsys.exit(g.main())\n')
97 process = subprocess.Popen([sys.executable, '-c', script], env=self.env)
98 self.addCleanup(process.wait)
99 self.addCleanup(process.terminate)
100 self.process = process
101
102 def current(self):
103 resources = self.root.xrandr_get_screen_resources()
104 output = self.conn.xrandr_get_output_info(resources.outputs[0], resources.config_timestamp)
105 crtc = self.conn.xrandr_get_crtc_info(output.crtc, resources.config_timestamp)
106 position = 0
107 for mode in resources.modes:
108 name = resources.mode_names[position:position + mode.name_length]
109 position += mode.name_length
110 if mode.id == crtc.mode:
111 return name, round(mode.dot_clock / (mode.h_total * mode.v_total)), (mode.width, mode.height)
112
113 def modes(self):
114 return subprocess.check_output(['xrandr', '--query'], env=self.env, text=True)
115
116 def wait(self, rate, size=(800, 600), timeout=4):
117 deadline = time.monotonic() + timeout
118 while time.monotonic() < deadline:
119 current = self.current()
120 if current[1:] == (rate, size):
121 return current[0]
122 time.sleep(.01)
123 self.fail(f'expected {rate} Hz at {size}, display shows {self.current()}')
124
125 def resize(self, width, height):
126 # The sequence of the browser and Desktop resize paths.
127 name = f'cage-{width}x{height}'
128 if f' {name} ' not in self.modes():
129 subprocess.check_call(['xrandr', '--newmode', name, f'{(width + 32) * (height + 8) * 60 / 1000000:.3f}',
130 *map(str, (width, width + 8, width + 16, width + 32, height, height + 1, height + 2, height + 8)),
131 '+HSync', '-VSync'], env=self.env)
132 subprocess.check_call(['xrandr', '--addmode', 'VNC-0', name], env=self.env)
133 subprocess.check_call(['xrandr', '--output', 'VNC-0', '--mode', name], env=self.env)
134
135 def test_unattended_display_slows_and_input_restores_it(self):
136 original = self.current()[0]
137 self.assertEqual(self.wait(30), 'fps30-800x600')
138 self.assertEqual(self.wait(20), 'fps20-800x600')
139 started = time.monotonic()
140 xtest.fake_input(self.conn, X.MotionNotify, x=40, y=40)
141 self.conn.sync()
142 self.assertEqual(self.wait(60), original)
143 self.assertLess(time.monotonic() - started, .5)
144 self.wait(30)
145 code = self.conn.keysym_to_keycode(0x61)
146 xtest.fake_input(self.conn, X.KeyPress, code)
147 xtest.fake_input(self.conn, X.KeyRelease, code)
148 self.conn.sync()
149 self.assertEqual(self.wait(60), original)
150
151 def test_caret_probe_key_is_not_viewer_input(self):
152 subprocess.check_call(['xmodmap', '-e', 'keycode 250 = F24'], env=self.env)
153 self.wait(20)
154 for _ in range(3):
155 xtest.fake_input(self.conn, X.KeyPress, 250)
156 xtest.fake_input(self.conn, X.KeyRelease, 250)
157 self.conn.sync()
158 time.sleep(.2)
159 self.assertEqual(self.current()[1], 20)
160
161 def test_resize_keeps_its_size_and_removes_earlier_modes(self):
162 self.wait(30)
163 self.resize(1024, 700)
164 self.assertEqual(self.wait(60, (1024, 700)), 'cage-1024x700')
165 self.assertEqual(self.wait(30, (1024, 700)), 'fps30-1024x700')
166 self.assertNotIn('fps30-800x600', self.modes())
167 self.assertNotIn('fps20-800x600', self.modes())
168 # A viewer attaching at the same size restores the full rate as well.
169 self.resize(1024, 700)
170 self.assertEqual(self.wait(60, (1024, 700)), 'cage-1024x700')
171 # Each step of a drag stays at the size its owner selected.
172 self.wait(30, (1024, 700))
173 for width in range(1030, 1100, 10):
174 self.resize(width, 700)
175 time.sleep(.05)
176 self.assertEqual(self.current()[1:], (60, (width, 700)))
177 self.assertEqual(self.wait(30, (1090, 700)), 'fps30-1090x700')
178 self.assertIsNone(self.process.poll())
179
180 def test_stopping_restores_the_full_rate(self):
181 original = self.current()[0]
182 self.wait(30)
183 self.process.terminate()
184 self.assertEqual(self.process.wait(timeout=3), 0)
185 self.assertEqual(self.current()[:2], (original, 60))
186
187
188if __name__ == '__main__':
189 unittest.main()