codecin 7.22.10__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. codecin/__init__.py +27 -0
  2. codecin/aot.py +1057 -0
  3. codecin/assembler.py +619 -0
  4. codecin/cbackend.py +3024 -0
  5. codecin/cin.py +4265 -0
  6. codecin/cli.py +670 -0
  7. codecin/codecin_native.dll +0 -0
  8. codecin/config.py +50 -0
  9. codecin/console.py +183 -0
  10. codecin/cpu.py +312 -0
  11. codecin/crom.py +449 -0
  12. codecin/cvm.py +708 -0
  13. codecin/disasm.py +149 -0
  14. codecin/environment.py +176 -0
  15. codecin/errors.py +54 -0
  16. codecin/isa.py +560 -0
  17. codecin/lib/array/pic.toml +10 -0
  18. codecin/lib/array/src/array.cin +103 -0
  19. codecin/lib/bigint/pic.toml +10 -0
  20. codecin/lib/bigint/src/bigint.cin +589 -0
  21. codecin/lib/bits/pic.toml +10 -0
  22. codecin/lib/bits/src/bits.cin +143 -0
  23. codecin/lib/bitset/pic.toml +10 -0
  24. codecin/lib/bitset/src/bitset.cin +374 -0
  25. codecin/lib/codec/pic.toml +10 -0
  26. codecin/lib/codec/src/codec.cin +563 -0
  27. codecin/lib/combin/pic.toml +10 -0
  28. codecin/lib/combin/src/combin.cin +414 -0
  29. codecin/lib/conv/pic.toml +10 -0
  30. codecin/lib/conv/src/conv.cin +151 -0
  31. codecin/lib/cppstd/pic.toml +10 -0
  32. codecin/lib/cppstd/src/cppstd.cin +418 -0
  33. codecin/lib/cstd/pic.toml +10 -0
  34. codecin/lib/cstd/src/cstd.cin +424 -0
  35. codecin/lib/csv/pic.toml +10 -0
  36. codecin/lib/csv/src/csv.cin +405 -0
  37. codecin/lib/dp/pic.toml +10 -0
  38. codecin/lib/dp/src/dp.cin +325 -0
  39. codecin/lib/ffi/pic.toml +10 -0
  40. codecin/lib/ffi/src/ffi.cin +163 -0
  41. codecin/lib/fmt/pic.toml +10 -0
  42. codecin/lib/fmt/src/fmt.cin +325 -0
  43. codecin/lib/frac/pic.toml +10 -0
  44. codecin/lib/frac/src/frac.cin +252 -0
  45. codecin/lib/gostd/pic.toml +10 -0
  46. codecin/lib/gostd/src/gostd.cin +415 -0
  47. codecin/lib/graph/pic.toml +10 -0
  48. codecin/lib/graph/src/graph.cin +367 -0
  49. codecin/lib/gui/pic.toml +10 -0
  50. codecin/lib/gui/src/gui.cin +218 -0
  51. codecin/lib/hash/pic.toml +10 -0
  52. codecin/lib/hash/src/hash.cin +67 -0
  53. codecin/lib/heap/pic.toml +10 -0
  54. codecin/lib/heap/src/heap.cin +199 -0
  55. codecin/lib/io/pic.toml +10 -0
  56. codecin/lib/io/src/io.cin +141 -0
  57. codecin/lib/json/pic.toml +10 -0
  58. codecin/lib/json/src/json.cin +84 -0
  59. codecin/lib/key/pic.toml +10 -0
  60. codecin/lib/key/src/key.cin +78 -0
  61. codecin/lib/math/pic.toml +10 -0
  62. codecin/lib/math/src/math.cin +50 -0
  63. codecin/lib/matrix/pic.toml +10 -0
  64. codecin/lib/matrix/src/matrix.cin +155 -0
  65. codecin/lib/net/pic.toml +10 -0
  66. codecin/lib/net/src/net.cin +171 -0
  67. codecin/lib/path/pic.toml +10 -0
  68. codecin/lib/path/src/path.cin +372 -0
  69. codecin/lib/queue/pic.toml +10 -0
  70. codecin/lib/queue/src/queue.cin +112 -0
  71. codecin/lib/rand/pic.toml +10 -0
  72. codecin/lib/rand/src/rand.cin +46 -0
  73. codecin/lib/set/pic.toml +10 -0
  74. codecin/lib/set/src/set.cin +269 -0
  75. codecin/lib/sort/pic.toml +10 -0
  76. codecin/lib/sort/src/sort.cin +93 -0
  77. codecin/lib/stat/pic.toml +10 -0
  78. codecin/lib/stat/src/stat.cin +138 -0
  79. codecin/lib/str/pic.toml +10 -0
  80. codecin/lib/str/src/str.cin +54 -0
  81. codecin/lib/termux/pic.toml +10 -0
  82. codecin/lib/termux/src/termux.cin +118 -0
  83. codecin/lib/test/pic.toml +10 -0
  84. codecin/lib/test/src/test.cin +74 -0
  85. codecin/lib/text/pic.toml +10 -0
  86. codecin/lib/text/src/text.cin +323 -0
  87. codecin/lib/time/pic.toml +10 -0
  88. codecin/lib/time/src/time.cin +54 -0
  89. codecin/lib/token/pic.toml +10 -0
  90. codecin/lib/token/src/token.cin +183 -0
  91. codecin/lib/tree/pic.toml +10 -0
  92. codecin/lib/tree/src/tree.cin +256 -0
  93. codecin/lib/unionfind/pic.toml +10 -0
  94. codecin/lib/unionfind/src/unionfind.cin +115 -0
  95. codecin/lib/validate/pic.toml +10 -0
  96. codecin/lib/validate/src/validate.cin +148 -0
  97. codecin/lib/vec/pic.toml +10 -0
  98. codecin/lib/vec/src/vec.cin +88 -0
  99. codecin/logger.py +145 -0
  100. codecin/memory.py +306 -0
  101. codecin/mkn.py +916 -0
  102. codecin/native/aot/aot.go +114 -0
  103. codecin/native/aot/stub_main.go.txt +23 -0
  104. codecin/native/build.ps1 +33 -0
  105. codecin/native/build.sh +48 -0
  106. codecin/native/cmd/cincc/main.go +66 -0
  107. codecin/native/compiler/codegen.go +2238 -0
  108. codecin/native/compiler/compile_test.go +1069 -0
  109. codecin/native/compiler/parser.go +1331 -0
  110. codecin/native/compiler/syscalls.go +166 -0
  111. codecin/native/compiler/tokenizer.go +394 -0
  112. codecin/native/compiler/types.go +217 -0
  113. codecin/native/engine/args.go +37 -0
  114. codecin/native/engine/audio.go +402 -0
  115. codecin/native/engine/audio_other.go +105 -0
  116. codecin/native/engine/audio_test.go +279 -0
  117. codecin/native/engine/audio_windows.go +190 -0
  118. codecin/native/engine/canvas.go +271 -0
  119. codecin/native/engine/console_other.go +9 -0
  120. codecin/native/engine/console_windows.go +43 -0
  121. codecin/native/engine/crom.go +86 -0
  122. codecin/native/engine/encode.go +93 -0
  123. codecin/native/engine/engine_test.go +198 -0
  124. codecin/native/engine/ffi_nocgo.go +20 -0
  125. codecin/native/engine/ffi_registry.go +69 -0
  126. codecin/native/engine/ffi_unix.go +109 -0
  127. codecin/native/engine/ffi_windows.go +117 -0
  128. codecin/native/engine/gui.go +209 -0
  129. codecin/native/engine/gui_stub.go +13 -0
  130. codecin/native/engine/gui_test.go +148 -0
  131. codecin/native/engine/gui_windows.go +604 -0
  132. codecin/native/engine/gui_x11.go +723 -0
  133. codecin/native/engine/host_test.go +139 -0
  134. codecin/native/engine/hostcrypto.go +30 -0
  135. codecin/native/engine/hostdesktop.go +173 -0
  136. codecin/native/engine/hostnet.go +127 -0
  137. codecin/native/engine/isa_gen.go +689 -0
  138. codecin/native/engine/keyboard.go +432 -0
  139. codecin/native/engine/keyboard_other.go +94 -0
  140. codecin/native/engine/keyboard_stub.go +17 -0
  141. codecin/native/engine/keyboard_termios_darwin.go +9 -0
  142. codecin/native/engine/keyboard_termios_linux.go +9 -0
  143. codecin/native/engine/keyboard_test.go +246 -0
  144. codecin/native/engine/keyboard_windows.go +208 -0
  145. codecin/native/engine/keyboard_windows_test.go +123 -0
  146. codecin/native/engine/lineedit.go +262 -0
  147. codecin/native/engine/lineedit_test.go +105 -0
  148. codecin/native/engine/lineint_unix.go +17 -0
  149. codecin/native/engine/lineint_windows.go +19 -0
  150. codecin/native/engine/mem_other.go +37 -0
  151. codecin/native/engine/mem_windows.go +33 -0
  152. codecin/native/engine/native.go +640 -0
  153. codecin/native/engine/netsock.go +321 -0
  154. codecin/native/engine/ops_ext.go +515 -0
  155. codecin/native/engine/stdin.go +72 -0
  156. codecin/native/engine/stdin_other.go +9 -0
  157. codecin/native/engine/stdin_windows.go +60 -0
  158. codecin/native/engine/system.go +313 -0
  159. codecin/native/engine/termux.go +180 -0
  160. codecin/native/engine/version_gen.go +7 -0
  161. codecin/native/engine/vkb_darwin.go +62 -0
  162. codecin/native/engine/vkb_linux.go +95 -0
  163. codecin/native/engine/vkb_stub.go +11 -0
  164. codecin/native/engine/vm.go +1677 -0
  165. codecin/native/go.mod +3 -0
  166. codecin/native/ir/ir.go +48 -0
  167. codecin/native/main.go +448 -0
  168. codecin/native/mc/aarch64.go +165 -0
  169. codecin/native/mc/aarch64_test.go +30 -0
  170. codecin/native/mc/elf.go +88 -0
  171. codecin/native/mc/print_test.go +52 -0
  172. codecin/native/mc/x86_64.go +1262 -0
  173. codecin/native/mc/x86_64_test.go +102 -0
  174. codecin/native.py +432 -0
  175. codecin/native_codegen.py +987 -0
  176. codecin/nativegen.py +786 -0
  177. codecin/object.py +539 -0
  178. codecin/optimizer.py +236 -0
  179. codecin/packaging/__init__.py +46 -0
  180. codecin/packaging/archive.py +177 -0
  181. codecin/packaging/model.py +519 -0
  182. codecin/packaging/spec.py +193 -0
  183. codecin/packaging/store.py +372 -0
  184. codecin/packaging/toml.py +541 -0
  185. codecin/packaging/vcs.py +215 -0
  186. codecin/pic.py +1917 -0
  187. codecin/pic_api.py +374 -0
  188. codecin/pic_login.py +519 -0
  189. codecin/pic_registry.py +515 -0
  190. codecin/registers.py +130 -0
  191. codecin/sdgcc.py +493 -0
  192. codecin/stats.py +230 -0
  193. codecin/stdlib.py +138 -0
  194. codecin/toolchain.py +396 -0
  195. codecin/toolkit.py +26 -0
  196. codecin/version.py +260 -0
  197. codecin-7.22.10.dist-info/METADATA +1077 -0
  198. codecin-7.22.10.dist-info/RECORD +202 -0
  199. codecin-7.22.10.dist-info/WHEEL +5 -0
  200. codecin-7.22.10.dist-info/entry_points.txt +5 -0
  201. codecin-7.22.10.dist-info/licenses/LICENSE +7 -0
  202. codecin-7.22.10.dist-info/top_level.txt +1 -0
@@ -0,0 +1,723 @@
1
+ //go:build linux
2
+
3
+ package engine
4
+
5
+ import (
6
+ "bufio"
7
+ "encoding/binary"
8
+ "image"
9
+ _ "io"
10
+ "net"
11
+ "os"
12
+ "strconv"
13
+ "strings"
14
+ "time"
15
+ )
16
+
17
+ // Linux GUI 后端: 纯 Go X11 客户端 (标准库 net, 零第三方依赖)。
18
+ // 支持 X11 与 XWayland (绝大多数发行版的默认显示路径); 无 DISPLAY 或
19
+ // 认证失败时 gui_new 优雅返回 -1。
20
+ //
21
+ // 事件在同一 goroutine (调用 SYS 的 VM 线程) 内处理: X11 无线程亲和性
22
+ // 限制, 连接/呈现/泵事件全部同步完成 —— 与 VM 单线程确定性模型天然契合。
23
+ // 窗口间的间隙事件缓存在内核 socket 缓冲, gui_update 时统一泵出。
24
+ // 协议编码按 X11 核心协议 (请求 4 字节对齐, 大端字段)。
25
+
26
+ const (
27
+ x11OpcodeCreateWindow = 1
28
+ x11OpcodeDestroyWindow = 4
29
+ x11OpcodeMapWindow = 8
30
+ x11OpcodeInternAtom = 16
31
+ x11OpcodeChangeProp = 18
32
+ x11OpcodeCreateGC = 55
33
+ x11OpcodePutImage = 72
34
+ x11OpcodeKeymap = 101
35
+
36
+ evKeyPress = 2
37
+ evButtonPress = 4
38
+ evButtonRelease = 5
39
+ evMotion = 6
40
+ evClientMessage = 33
41
+ x11ZPixmap = 2
42
+ x11VisualTrueCol = 4
43
+ )
44
+
45
+ type x11Conn struct {
46
+ conn net.Conn
47
+ br *bufio.Reader
48
+ resBase uint32
49
+ root uint32
50
+ visual uint32
51
+ depth uint8
52
+ minKC uint8
53
+ maxKC uint8
54
+ perKC int
55
+ keysyms []uint32
56
+ win uint32
57
+ gc uint32
58
+ w, h int
59
+ maxReqLen int // 单请求最大字节数 (握手值×4)
60
+ nextID uint32
61
+ atomWMPro uint32
62
+ atomWMDel uint32
63
+ }
64
+
65
+ // ---------------- 平台接口 ----------------
66
+
67
+ func guiPlatformOpen(w, h int, title string, buf *image.RGBA) bool {
68
+ _ = buf
69
+ xc, err := guiX11Dial()
70
+ if err != nil {
71
+ return false
72
+ }
73
+ if !xc.openWindow(w, h, title) {
74
+ _ = xc.conn.Close()
75
+ return false
76
+ }
77
+ return true
78
+ }
79
+
80
+ func guiPlatformUpdate(buf *image.RGBA) bool {
81
+ guiMu.Lock()
82
+ xc := guiX11
83
+ guiMu.Unlock()
84
+ if xc == nil {
85
+ return false
86
+ }
87
+ if !xc.pump() { // 连接断开: 视为窗口关闭
88
+ guiMarkClosed()
89
+ return false
90
+ }
91
+ pix := guiSnapshot(buf)
92
+ if pix == nil {
93
+ return true
94
+ }
95
+ return xc.present(pix, buf.Rect.Dx(), buf.Rect.Dy())
96
+ }
97
+
98
+ func guiPlatformClose() {
99
+ guiMu.Lock()
100
+ xc := guiX11
101
+ guiX11 = nil
102
+ guiMu.Unlock()
103
+ if xc != nil {
104
+ xc.destroy()
105
+ }
106
+ }
107
+
108
+ // 虚拟键盘实现见 vkb_linux.go (onboard / matchbox-keyboard / xvkbd)。
109
+
110
+ // guiX11 当前连接 (gui.go 状态之外的平台侧句柄)。
111
+ var guiX11 *x11Conn
112
+
113
+ // ---------------- 连接与握手 ----------------
114
+
115
+ // guiX11Dial 解析 $DISPLAY 建立连接 (unix socket 优先, 其次 TCP)。
116
+ func guiX11Dial() (*x11Conn, error) {
117
+ spec := os.Getenv("DISPLAY")
118
+ if spec == "" {
119
+ return nil, &displayError{"DISPLAY not set"}
120
+ }
121
+ host, disp, err := parseDisplay(spec)
122
+ if err != nil {
123
+ return nil, err
124
+ }
125
+ var conn net.Conn
126
+ if host == "" {
127
+ conn, err = net.DialTimeout("unix",
128
+ "/tmp/.X11-unix/X"+disp, 2*time.Second)
129
+ } else {
130
+ conn, err = net.DialTimeout("tcp",
131
+ host+":"+strconv.Itoa(atoiOr0(disp)+6000), 2*time.Second)
132
+ }
133
+ if err != nil {
134
+ return nil, err
135
+ }
136
+ _ = conn.SetDeadline(time.Now().Add(2 * time.Second))
137
+ xc, err := x11Handshake(conn, host, disp)
138
+ _ = conn.SetDeadline(time.Time{})
139
+ if err != nil {
140
+ _ = conn.Close()
141
+ return nil, err
142
+ }
143
+ return xc, nil
144
+ }
145
+
146
+ type displayError struct{ msg string }
147
+
148
+ func (e *displayError) Error() string { return e.msg }
149
+
150
+ // parseDisplay 解析 "host:dpy[.screen]"。
151
+ func parseDisplay(spec string) (host, disp string, err error) {
152
+ colon := strings.LastIndex(spec, ":")
153
+ if colon < 0 {
154
+ return "", "", &displayError{"bad DISPLAY: " + spec}
155
+ }
156
+ host = spec[:colon]
157
+ dpy := spec[colon+1:]
158
+ if i := strings.Index(dpy, "."); i >= 0 {
159
+ dpy = dpy[:i]
160
+ }
161
+ if _, e := strconv.Atoi(dpy); e != nil {
162
+ return "", "", &displayError{"bad DISPLAY number: " + spec}
163
+ }
164
+ return host, dpy, nil
165
+ }
166
+
167
+ func atoiOr0(s string) int {
168
+ n, _ := strconv.Atoi(s)
169
+ return n
170
+ }
171
+
172
+ // x11Handshake 发送连接握手并解析 setup 回复。
173
+ func x11Handshake(conn net.Conn, host, disp string) (*x11Conn, error) {
174
+ br := bufio.NewReader(conn)
175
+ // 认证: MIT-MAGIC-COOKIE-1 (尽力而为; 本地 socket 通常无需)
176
+ name, cookie := xauthCookie(host, disp)
177
+ hdr := make([]byte, 12)
178
+ hdr[0] = 'l' // LSBFirst
179
+ binary.BigEndian.PutUint16(hdr[2:4], 11) // protocol major
180
+ binary.BigEndian.PutUint16(hdr[4:6], 0) // minor
181
+ binary.BigEndian.PutUint16(hdr[6:8], uint16(len(name)))
182
+ binary.BigEndian.PutUint16(hdr[8:10], uint16(len(cookie)))
183
+ req := append(hdr, name...)
184
+ req = append(req, make([]byte, pad4(len(name))-len(name))...)
185
+ req = append(req, cookie...)
186
+ req = append(req, make([]byte, pad4(len(cookie))-len(cookie))...)
187
+ if _, err := conn.Write(req); err != nil {
188
+ return nil, err
189
+ }
190
+ first, err := br.ReadByte()
191
+ if err != nil {
192
+ return nil, err
193
+ }
194
+ if first != 1 { // 0=failed, 2=further-auth
195
+ return nil, &displayError{"X11 handshake rejected"}
196
+ }
197
+ head := make([]byte, 7)
198
+ if _, err := ioReadFull(br, head); err != nil {
199
+ return nil, err
200
+ }
201
+ extra := int(binary.BigEndian.Uint16(head[5:7])) * 4
202
+ body := make([]byte, extra)
203
+ if _, err := ioReadFull(br, body); err != nil {
204
+ return nil, err
205
+ }
206
+ // additional data: release(4) resBase(4) mask(4) motion(4) vendorLen(2)
207
+ // maxReq(2) screens(1) formats(1) order(1) bitOrder(1) unit(1) pad(1)
208
+ // minKC(1) maxKC(1) unused(4) vendor.. formats.. screens..
209
+ if len(body) < 32 {
210
+ return nil, &displayError{"X11 setup truncated"}
211
+ }
212
+ vendorLen := int(binary.BigEndian.Uint16(body[16:18]))
213
+ maxReqBytes := int(binary.BigEndian.Uint16(body[18:20])) * 4
214
+ numFormats := int(body[21])
215
+ minKC, maxKC := body[26], body[27]
216
+ pos := padTo(32+vendorLen, 4) + numFormats*8
217
+ if len(body) < pos+40 {
218
+ return nil, &displayError{"X11 setup truncated"}
219
+ }
220
+ sc := body[pos:]
221
+ root := binary.BigEndian.Uint32(sc[0:4])
222
+ rootVisual := binary.BigEndian.Uint32(sc[32:36])
223
+ rootDepth := sc[38]
224
+ nDepths := int(sc[39])
225
+ visual, depth := findTrueColor(sc[40:], nDepths, rootVisual, rootDepth)
226
+ if visual == 0 {
227
+ return nil, &displayError{"no TrueColor visual found"}
228
+ }
229
+ xc := &x11Conn{
230
+ conn: conn,
231
+ br: br,
232
+ resBase: binary.BigEndian.Uint32(body[4:8]),
233
+ root: root,
234
+ visual: visual,
235
+ depth: depth,
236
+ minKC: minKC,
237
+ maxKC: maxKC,
238
+ maxReqLen: maxReqBytes,
239
+ }
240
+ if !xc.loadKeymap() {
241
+ return nil, &displayError{"X11 keymap query failed"}
242
+ }
243
+ return xc, nil
244
+ }
245
+
246
+ // findTrueColor 找 depth>=24 的 TrueColor visual (缺省回落根 visual)。
247
+ func findTrueColor(depths []byte, n int, fallbackVisual uint32, fallbackDepth uint8) (uint32, uint8) {
248
+ pos := 0
249
+ for d := 0; d < n && pos+8 <= len(depths); d++ {
250
+ depth := depths[pos]
251
+ nVis := int(binary.BigEndian.Uint16(depths[pos+2 : pos+4]))
252
+ pos += 8
253
+ for v := 0; v < nVis && pos+24 <= len(depths); v++ {
254
+ id := binary.BigEndian.Uint32(depths[pos : pos+4])
255
+ class := depths[pos+4]
256
+ if class == x11VisualTrueCol && depth >= 24 {
257
+ return id, depth
258
+ }
259
+ pos += 24
260
+ }
261
+ }
262
+ return fallbackVisual, fallbackDepth
263
+ }
264
+
265
+ // loadKeymap GetKeyboardMapping: keycode -> keysyms 表。
266
+ func (xc *x11Conn) loadKeymap() bool {
267
+ count := int(xc.maxKC) - int(xc.minKC) + 1
268
+ if count <= 0 {
269
+ return false
270
+ }
271
+ req := make([]byte, 8)
272
+ req[0] = x11OpcodeKeymap
273
+ req[1] = xc.minKC
274
+ binary.BigEndian.PutUint16(req[2:4], 2) // 8 字节请求
275
+ req[4] = uint8(count)
276
+ if _, err := xc.conn.Write(req); err != nil {
277
+ return false
278
+ }
279
+ head := make([]byte, 32)
280
+ if _, err := ioReadFull(xc.br, head); err != nil || head[0] != 1 {
281
+ return false
282
+ }
283
+ xc.perKC = int(head[1])
284
+ n := int(binary.BigEndian.Uint32(head[4:8])) * 4
285
+ if xc.perKC <= 0 || n <= 0 {
286
+ return false
287
+ }
288
+ body := make([]byte, n)
289
+ if _, err := ioReadFull(xc.br, body); err != nil {
290
+ return false
291
+ }
292
+ xc.keysyms = make([]uint32, n/4)
293
+ for i := range xc.keysyms {
294
+ xc.keysyms[i] = binary.BigEndian.Uint32(body[i*4 : i*4+4])
295
+ }
296
+ return true
297
+ }
298
+
299
+ // ---------------- 窗口创建 / 呈现 / 销毁 ----------------
300
+
301
+ func (xc *x11Conn) allocID() uint32 {
302
+ xc.nextID++
303
+ return xc.resBase + xc.nextID
304
+ }
305
+
306
+ func (xc *x11Conn) openWindow(w, h int, title string) bool {
307
+ xc.atomWMPro = xc.internAtom("WM_PROTOCOLS")
308
+ xc.atomWMDel = xc.internAtom("WM_DELETE_WINDOW")
309
+ win := xc.allocID()
310
+ gc := xc.allocID()
311
+
312
+ // CreateWindow (值顺序按 value-mask 位序: back-pixel -> event-mask)
313
+ // CW_BACK_PIXEL(0x2) | CW_EVENT_MASK(0x800)
314
+ const evMask = 0x1 | 0x2 | 0x4 | 0x8 | 0x40 | 0x8000 | 0x20000
315
+ req := make([]byte, 44)
316
+ req[0] = x11OpcodeCreateWindow
317
+ req[1] = xc.depth
318
+ binary.BigEndian.PutUint16(req[2:4], 11) // 44/4
319
+ binary.BigEndian.PutUint32(req[4:8], win)
320
+ binary.BigEndian.PutUint32(req[8:12], xc.root)
321
+ binary.BigEndian.PutUint16(req[12:14], 0) // x
322
+ binary.BigEndian.PutUint16(req[14:16], 0) // y
323
+ binary.BigEndian.PutUint16(req[16:18], uint16(w))
324
+ binary.BigEndian.PutUint16(req[18:20], uint16(h))
325
+ binary.BigEndian.PutUint16(req[20:22], 1) // border
326
+ binary.BigEndian.PutUint16(req[22:24], 1) // InputOutput
327
+ binary.BigEndian.PutUint32(req[26:30], xc.visual)
328
+ binary.BigEndian.PutUint32(req[30:34], 0x2|0x800)
329
+ binary.BigEndian.PutUint32(req[34:38], 0xFFFFFF) // 白背景
330
+ binary.BigEndian.PutUint32(req[38:42], evMask)
331
+ if err := xc.write(req); err != nil {
332
+ return false
333
+ }
334
+
335
+ // CreateGC (graphics-exposures = 0)
336
+ greq := make([]byte, 20)
337
+ greq[0] = x11OpcodeCreateGC
338
+ binary.BigEndian.PutUint16(greq[2:4], 5) // 20/4
339
+ binary.BigEndian.PutUint32(greq[4:8], gc)
340
+ binary.BigEndian.PutUint32(greq[8:12], win)
341
+ binary.BigEndian.PutUint32(greq[12:16], 1<<9) // GC_GRAPHICS_EXPOSURES
342
+ if err := xc.write(greq); err != nil {
343
+ return false
344
+ }
345
+
346
+ // ChangeProperty: WM_PROTOCOLS = [WM_DELETE_WINDOW] (点 X 触发 ClientMessage)
347
+ if xc.atomWMPro != 0 && xc.atomWMDel != 0 {
348
+ preq := make([]byte, 28)
349
+ preq[0] = x11OpcodeChangeProp
350
+ binary.BigEndian.PutUint16(preq[2:4], 7) // 28/4
351
+ binary.BigEndian.PutUint32(preq[4:8], win)
352
+ binary.BigEndian.PutUint32(preq[8:12], xc.atomWMPro)
353
+ binary.BigEndian.PutUint32(preq[12:16], xc.atomWMPro) // type: ATOM
354
+ preq[16] = 32 // format
355
+ binary.BigEndian.PutUint32(preq[20:24], 1) // n items
356
+ binary.BigEndian.PutUint32(preq[24:28], xc.atomWMDel)
357
+ _ = xc.write(preq)
358
+ }
359
+
360
+ // MapWindow
361
+ mreq := make([]byte, 8)
362
+ mreq[0] = x11OpcodeMapWindow
363
+ binary.BigEndian.PutUint16(mreq[2:4], 2)
364
+ binary.BigEndian.PutUint32(mreq[4:8], win)
365
+ if err := xc.write(mreq); err != nil {
366
+ return false
367
+ }
368
+ xc.win = win
369
+ xc.gc = gc
370
+ xc.w, xc.h = w, h
371
+ guiMu.Lock()
372
+ guiX11 = xc
373
+ guiMu.Unlock()
374
+ return true
375
+ }
376
+
377
+ // internAtom 同步查询 atom。
378
+ func (xc *x11Conn) internAtom(name string) uint32 {
379
+ b := []byte(name)
380
+ req := make([]byte, 8+pad4(len(b)))
381
+ req[0] = x11OpcodeInternAtom
382
+ req[1] = 0 // only-if-exists = false
383
+ binary.BigEndian.PutUint16(req[2:4], uint16(len(req)/4))
384
+ binary.BigEndian.PutUint16(req[4:6], uint16(len(b)))
385
+ copy(req[8:], b)
386
+ if err := xc.write(req); err != nil {
387
+ return 0
388
+ }
389
+ rep := make([]byte, 32)
390
+ if err := xc.readReply(rep); err != nil || rep[0] != 1 {
391
+ return 0
392
+ }
393
+ return binary.BigEndian.Uint32(rep[8:12])
394
+ }
395
+
396
+ // present 把 RGBA 像素呈现到窗口 (PutImage 分块)。
397
+ func (xc *x11Conn) present(pix []byte, w, h int) bool {
398
+ bpl := w * 4
399
+ chunkRows := (xc.maxReqLen - 24) / bpl
400
+ if chunkRows < 1 {
401
+ chunkRows = 1
402
+ }
403
+ if chunkRows > h {
404
+ chunkRows = h
405
+ }
406
+ for row := 0; row < h; row += chunkRows {
407
+ rows := chunkRows
408
+ if rows > h-row {
409
+ rows = h - row
410
+ }
411
+ n := rows * bpl
412
+ req := make([]byte, 24+n)
413
+ req[0] = x11OpcodePutImage
414
+ req[1] = x11ZPixmap
415
+ binary.BigEndian.PutUint16(req[2:4], uint16((24+n)/4))
416
+ binary.BigEndian.PutUint32(req[4:8], xc.win)
417
+ binary.BigEndian.PutUint32(req[8:12], xc.gc)
418
+ binary.BigEndian.PutUint16(req[12:14], uint16(w))
419
+ binary.BigEndian.PutUint16(req[14:16], uint16(rows))
420
+ binary.BigEndian.PutUint16(req[16:18], 0) // dst-x
421
+ binary.BigEndian.PutUint16(req[18:20], uint16(row))
422
+ req[21] = xc.depth
423
+ packPixels(pix[row*bpl:(row+rows)*bpl], req[24:])
424
+ if err := xc.write(req); err != nil {
425
+ return false
426
+ }
427
+ }
428
+ return true
429
+ }
430
+
431
+ // packPixels RGBA -> ZPixmap 像素单元 (LSB 服务器: B,G,R,x; MSB: x,R,G,B)。
432
+ // x11Handshake 默认本地服务器为 LSBFirst ('l' 握手序即客户端序),
433
+ // 这里按客户端一律 LSB 编码 (请求 hdr[0]='l' 已声明)。
434
+ func packPixels(src, dst []byte) {
435
+ j := 0
436
+ for i := 0; i+3 < len(src); i += 4 {
437
+ dst[j] = src[i+2] // B
438
+ dst[j+1] = src[i+1] // G
439
+ dst[j+2] = src[i] // R
440
+ j += 4
441
+ }
442
+ }
443
+
444
+ func (xc *x11Conn) destroy() {
445
+ if xc.win != 0 {
446
+ req := make([]byte, 8)
447
+ req[0] = x11OpcodeDestroyWindow
448
+ binary.BigEndian.PutUint16(req[2:4], 2)
449
+ binary.BigEndian.PutUint32(req[4:8], xc.win)
450
+ _ = xc.write(req)
451
+ }
452
+ _ = xc.conn.Close()
453
+ }
454
+
455
+ // ---------------- 事件泵 ----------------
456
+
457
+ // pump 非阻塞泵空全部待处理事件 (按键/鼠标注入状态, 其余消费掉)。
458
+ func (xc *x11Conn) pump() bool {
459
+ _ = xc.conn.SetReadDeadline(time.Now())
460
+ defer func() { _ = xc.conn.SetReadDeadline(time.Time{}) }()
461
+ var ev [32]byte
462
+ for {
463
+ if _, err := ioReadFull(xc.br, ev[:]); err != nil {
464
+ if isTimeout(err) {
465
+ return true // 输入暂尽: 正常
466
+ }
467
+ return false // 连接断开
468
+ }
469
+ xc.handleEvent(ev[:])
470
+ }
471
+ }
472
+
473
+ // handleEvent 解析单个 32 字节事件。
474
+ func (xc *x11Conn) handleEvent(ev []byte) {
475
+ switch ev[0] {
476
+ case 0: // 错误: 消费
477
+ case evKeyPress:
478
+ state := binary.BigEndian.Uint16(ev[28:30])
479
+ if k, ok := xc.keycodeToKey(ev[1], state); ok {
480
+ guiInjectKey(k)
481
+ }
482
+ case evButtonPress:
483
+ guiX11Button(int(ev[1]), true)
484
+ guiX11Mouse(ev)
485
+ case evButtonRelease:
486
+ guiX11Button(int(ev[1]), false)
487
+ guiX11Mouse(ev)
488
+ case evMotion:
489
+ guiX11Mouse(ev)
490
+ case evClientMessage:
491
+ // WM_DELETE_WINDOW: format=32(字节1), type@8, data[0]@12
492
+ if ev[1] == 32 && binary.BigEndian.Uint32(ev[8:12]) == xc.atomWMPro &&
493
+ binary.BigEndian.Uint32(ev[12:16]) == xc.atomWMDel {
494
+ guiMarkClosed()
495
+ }
496
+ default: // Expose / MapNotify / ConfigureNotify 等: 消费
497
+ }
498
+ }
499
+
500
+ func guiX11Mouse(ev []byte) {
501
+ x := int(int16(binary.BigEndian.Uint16(ev[24:26])))
502
+ y := int(int16(binary.BigEndian.Uint16(ev[26:28])))
503
+ guiSetMouse(x, y, -1)
504
+ }
505
+
506
+ // guiX11Button X11 按钮号 -> guiMouseBtn 位 (1 左 / 2 中 / 3 右)。
507
+ func guiX11Button(detail int, down bool) {
508
+ var bit int
509
+ switch detail {
510
+ case 1:
511
+ bit = 1
512
+ case 2:
513
+ bit = 4
514
+ case 3:
515
+ bit = 2
516
+ default:
517
+ return // 滚轮 4/5
518
+ }
519
+ guiMouseButtonBit(bit, down)
520
+ }
521
+
522
+ // keycodeToKey 键码 -> 统一键码值 (与终端 / Windows 三端一致)。
523
+ func (xc *x11Conn) keycodeToKey(kc uint8, state uint16) (uint64, bool) {
524
+ shift := state&0x1 != 0
525
+ ctrl := state&0x4 != 0
526
+ k := xc.lookupKeysym(kc, shift)
527
+ if k == 0 {
528
+ return 0, false
529
+ }
530
+ // Ctrl+字母 -> 控制字节 (与 Windows / 终端一致: Ctrl+C=3)
531
+ if ctrl {
532
+ switch {
533
+ case k >= 'a' && k <= 'z':
534
+ return uint64(k - 96), true
535
+ case k >= 'A' && k <= 'Z':
536
+ return uint64(k - 64), true
537
+ }
538
+ }
539
+ switch k {
540
+ case 0xFF08:
541
+ return 8, true // BackSpace
542
+ case 0xFF09:
543
+ return 9, true // Tab
544
+ case 0xFE20:
545
+ return keyShiftTab, true // ISO_Left_Tab (Shift+Tab)
546
+ case 0xFF0D:
547
+ return 13, true // Return
548
+ case 0xFF1B:
549
+ return 27, true // Escape
550
+ case 0xFF50:
551
+ return keyHome, true
552
+ case 0xFF55:
553
+ return keyPgUp, true
554
+ case 0xFF56:
555
+ return keyPgDn, true
556
+ case 0xFF63:
557
+ return keyIns, true
558
+ case 0xFFFF:
559
+ return keyDel, true
560
+ case 0xFF51:
561
+ return arrowVariant(keyLeft, x11Mod(shift, ctrl)), true
562
+ case 0xFF52:
563
+ return arrowVariant(keyUp, x11Mod(shift, ctrl)), true
564
+ case 0xFF53:
565
+ return arrowVariant(keyRight, x11Mod(shift, ctrl)), true
566
+ case 0xFF54:
567
+ return arrowVariant(keyDown, x11Mod(shift, ctrl)), true
568
+ case 0xFFBE:
569
+ return keyF1, true
570
+ case 0xFFBF:
571
+ return keyF2, true
572
+ case 0xFFC0:
573
+ return keyF3, true
574
+ case 0xFFC1:
575
+ return keyF4, true
576
+ case 0xFFC2:
577
+ return keyF5, true
578
+ case 0xFFC3:
579
+ return keyF6, true
580
+ case 0xFFC4:
581
+ return keyF7, true
582
+ case 0xFFC5:
583
+ return keyF8, true
584
+ case 0xFFC6:
585
+ return keyF9, true
586
+ case 0xFFC7:
587
+ return keyF10, true
588
+ case 0xFFC8:
589
+ return keyF11, true
590
+ case 0xFFC9:
591
+ return keyF12, true
592
+ }
593
+ switch {
594
+ case k >= 0x20 && k <= 0xFF: // Latin-1
595
+ return uint64(k), true
596
+ case k >= 0x1000000: // Unicode keysym
597
+ return uint64(k - 0x1000000), true
598
+ }
599
+ return 0, false
600
+ }
601
+
602
+ // x11Mod X11 state -> XTerm 修饰值 (1+shift|ctrl)。
603
+ func x11Mod(shift, ctrl bool) int {
604
+ m := 1
605
+ if shift {
606
+ m += 1
607
+ }
608
+ if ctrl {
609
+ m += 4
610
+ }
611
+ return m
612
+ }
613
+
614
+ // lookupKeysym 取键盘映射: col0 = 基础层, col1 = Shift 层。
615
+ func (xc *x11Conn) lookupKeysym(kc uint8, shift bool) uint32 {
616
+ if xc.perKC <= 0 {
617
+ return 0
618
+ }
619
+ idx := int(kc) - int(xc.minKC)
620
+ rows := len(xc.keysyms) / xc.perKC
621
+ if idx < 0 || idx >= rows {
622
+ return 0
623
+ }
624
+ row := xc.keysyms[idx*xc.perKC : (idx+1)*xc.perKC]
625
+ if shift && len(row) > 1 && row[1] != 0 {
626
+ return row[1]
627
+ }
628
+ if row[0] != 0 {
629
+ return row[0]
630
+ }
631
+ for _, k := range row {
632
+ if k != 0 {
633
+ return k
634
+ }
635
+ }
636
+ return 0
637
+ }
638
+
639
+ // ---------------- Xauthority ----------------
640
+
641
+ // xauthCookie 读取 $XAUTHORITY / ~/.Xauthority 里匹配 display 的
642
+ // MIT-MAGIC-COOKIE-1 (尽力而为; 失败返回空认证)。
643
+ func xauthCookie(host, disp string) (string, []byte) {
644
+ path := os.Getenv("XAUTHORITY")
645
+ if path == "" {
646
+ home, err := os.UserHomeDir()
647
+ if err != nil {
648
+ return "", nil
649
+ }
650
+ path = home + "/.Xauthority"
651
+ }
652
+ data, err := os.ReadFile(path)
653
+ if err != nil {
654
+ return "", nil
655
+ }
656
+ pos := 0
657
+ for pos+2 <= len(data) {
658
+ family := int(binary.BigEndian.Uint16(data[pos : pos+2]))
659
+ pos += 2
660
+ fields := make([][]byte, 4)
661
+ ok := true
662
+ for fi := range fields {
663
+ if pos+2 > len(data) {
664
+ ok = false
665
+ break
666
+ }
667
+ n := int(binary.BigEndian.Uint16(data[pos : pos+2]))
668
+ pos += 2
669
+ if pos+n > len(data) {
670
+ ok = false
671
+ break
672
+ }
673
+ fields[fi] = data[pos : pos+n]
674
+ pos += n
675
+ }
676
+ if !ok {
677
+ break
678
+ }
679
+ addr, number, aname, adata := fields[0], fields[1], fields[2], fields[3]
680
+ if string(aname) != "MIT-MAGIC-COOKIE-1" || string(number) != disp {
681
+ continue
682
+ }
683
+ // family 256 = LocalHost (unix socket); 其余匹配主机名
684
+ if family == 256 || (host != "" && strings.EqualFold(string(addr), host)) {
685
+ return "MIT-MAGIC-COOKIE-1", append([]byte(nil), adata...)
686
+ }
687
+ }
688
+ return "", nil
689
+ }
690
+
691
+ // ---------------- 小工具 ----------------
692
+
693
+ func pad4(n int) int { return (n + 3) &^ 3 }
694
+
695
+ func padTo(pos, align int) int { return (pos + align - 1) &^ (align - 1) }
696
+
697
+ func ioReadFull(r *bufio.Reader, b []byte) (int, error) {
698
+ total := 0
699
+ for total < len(b) {
700
+ n, err := r.Read(b[total:])
701
+ total += n
702
+ if err != nil {
703
+ return total, err
704
+ }
705
+ }
706
+ return total, nil
707
+ }
708
+
709
+ func isTimeout(err error) bool {
710
+ ne, ok := err.(net.Error)
711
+ return ok && ne.Timeout()
712
+ }
713
+
714
+ func (xc *x11Conn) write(b []byte) error {
715
+ _, err := xc.conn.Write(b)
716
+ return err
717
+ }
718
+
719
+ // readReply 读一个 32 字节回复/事件 (阻塞, 调用方负责超时)。
720
+ func (xc *x11Conn) readReply(b []byte) error {
721
+ _, err := ioReadFull(xc.br, b)
722
+ return err
723
+ }