@xincli/opentui-core 0.4.6

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 (476) hide show
  1. package/README.md +63 -0
  2. package/dev/keypress-debug-renderer.ts +148 -0
  3. package/dev/keypress-debug.ts +43 -0
  4. package/dev/print-env-vars.ts +32 -0
  5. package/dev/test-tmux-graphics-334.sh +68 -0
  6. package/dev/test-tmux-theme-queries.sh +151 -0
  7. package/dev/thai-debug-test.ts +68 -0
  8. package/dev/theme-mode.ts +290 -0
  9. package/docs/development.md +144 -0
  10. package/package.json +102 -0
  11. package/prebuilt/aarch64-android/libopentui.so +0 -0
  12. package/scripts/build-android.ts +226 -0
  13. package/scripts/build-native-termux.sh +525 -0
  14. package/scripts/build.ts +530 -0
  15. package/scripts/dist-test.ts +312 -0
  16. package/scripts/package-prebuilt.ts +110 -0
  17. package/scripts/publish.ts +60 -0
  18. package/scripts/test-node-hook.mjs +16 -0
  19. package/scripts/test-node.ts +241 -0
  20. package/scripts/vendor-deps.sh +73 -0
  21. package/src/NativeSpanFeed.ts +375 -0
  22. package/src/Renderable.ts +1878 -0
  23. package/src/__snapshots__/buffer.test.ts.snap +28 -0
  24. package/src/animation/Timeline.test.ts +2709 -0
  25. package/src/animation/Timeline.ts +598 -0
  26. package/src/ansi.ts +22 -0
  27. package/src/audio.ts +479 -0
  28. package/src/benchmark/attenuation-benchmark.ts +81 -0
  29. package/src/benchmark/audio-playback-benchmark.ts +344 -0
  30. package/src/benchmark/box-draw-benchmark.ts +1042 -0
  31. package/src/benchmark/colormatrix-benchmark.ts +123 -0
  32. package/src/benchmark/gain-benchmark.ts +80 -0
  33. package/src/benchmark/latest-all-bench-run.json +707 -0
  34. package/src/benchmark/latest-async-bench-run.json +336 -0
  35. package/src/benchmark/latest-default-bench-run.json +657 -0
  36. package/src/benchmark/latest-large-bench-run.json +707 -0
  37. package/src/benchmark/latest-quick-bench-run.json +207 -0
  38. package/src/benchmark/layout-benchmark.ts +2547 -0
  39. package/src/benchmark/markdown-benchmark.ts +1796 -0
  40. package/src/benchmark/native-span-feed-async-benchmark.ts +355 -0
  41. package/src/benchmark/native-span-feed-benchmark.md +56 -0
  42. package/src/benchmark/native-span-feed-benchmark.ts +596 -0
  43. package/src/benchmark/native-span-feed-compare.ts +280 -0
  44. package/src/benchmark/render-traversal-benchmark.ts +928 -0
  45. package/src/benchmark/text-buffer-render-benchmark.ts +874 -0
  46. package/src/benchmark/text-table-benchmark.ts +948 -0
  47. package/src/buffer.test.ts +292 -0
  48. package/src/buffer.ts +564 -0
  49. package/src/console.test.ts +629 -0
  50. package/src/console.ts +1253 -0
  51. package/src/edit-buffer.test.ts +1852 -0
  52. package/src/edit-buffer.ts +417 -0
  53. package/src/editor-view.test.ts +1056 -0
  54. package/src/editor-view.ts +290 -0
  55. package/src/index.ts +25 -0
  56. package/src/lib/KeyHandler.integration.test.ts +292 -0
  57. package/src/lib/KeyHandler.stopPropagation.test.ts +289 -0
  58. package/src/lib/KeyHandler.test.ts +662 -0
  59. package/src/lib/KeyHandler.ts +222 -0
  60. package/src/lib/RGBA.test.ts +60 -0
  61. package/src/lib/RGBA.ts +343 -0
  62. package/src/lib/ascii.font.ts +330 -0
  63. package/src/lib/border.test.ts +83 -0
  64. package/src/lib/border.ts +170 -0
  65. package/src/lib/bunfs.test.ts +27 -0
  66. package/src/lib/bunfs.ts +18 -0
  67. package/src/lib/clipboard.test.ts +63 -0
  68. package/src/lib/clipboard.ts +41 -0
  69. package/src/lib/clock.ts +35 -0
  70. package/src/lib/data-paths.test.ts +133 -0
  71. package/src/lib/data-paths.ts +109 -0
  72. package/src/lib/debounce.ts +106 -0
  73. package/src/lib/detect-links.test.ts +98 -0
  74. package/src/lib/detect-links.ts +56 -0
  75. package/src/lib/env.test.ts +228 -0
  76. package/src/lib/env.ts +209 -0
  77. package/src/lib/extmarks-history.ts +51 -0
  78. package/src/lib/extmarks-multiwidth.test.ts +324 -0
  79. package/src/lib/extmarks.test.ts +3547 -0
  80. package/src/lib/extmarks.ts +861 -0
  81. package/src/lib/fonts/block.json +405 -0
  82. package/src/lib/fonts/grid.json +265 -0
  83. package/src/lib/fonts/huge.json +741 -0
  84. package/src/lib/fonts/pallet.json +314 -0
  85. package/src/lib/fonts/shade.json +591 -0
  86. package/src/lib/fonts/slick.json +321 -0
  87. package/src/lib/fonts/tiny.json +69 -0
  88. package/src/lib/hast-styled-text.ts +59 -0
  89. package/src/lib/index.ts +22 -0
  90. package/src/lib/keybinding.internal.test.ts +342 -0
  91. package/src/lib/keybinding.internal.ts +182 -0
  92. package/src/lib/objects-in-viewport.test.ts +789 -0
  93. package/src/lib/objects-in-viewport.ts +153 -0
  94. package/src/lib/output.capture.ts +58 -0
  95. package/src/lib/parse.keypress-kitty.protocol.test.ts +347 -0
  96. package/src/lib/parse.keypress-kitty.test.ts +712 -0
  97. package/src/lib/parse.keypress-kitty.ts +470 -0
  98. package/src/lib/parse.keypress.test.ts +2020 -0
  99. package/src/lib/parse.keypress.ts +480 -0
  100. package/src/lib/parse.mouse.test.ts +552 -0
  101. package/src/lib/parse.mouse.ts +232 -0
  102. package/src/lib/paste.ts +18 -0
  103. package/src/lib/queue.ts +65 -0
  104. package/src/lib/render-geometry.ts +36 -0
  105. package/src/lib/renderable.validations.test.ts +87 -0
  106. package/src/lib/renderable.validations.ts +83 -0
  107. package/src/lib/scroll-acceleration.ts +98 -0
  108. package/src/lib/selection.ts +261 -0
  109. package/src/lib/singleton.ts +34 -0
  110. package/src/lib/stdin-parser.test.ts +2439 -0
  111. package/src/lib/stdin-parser.ts +2007 -0
  112. package/src/lib/styled-text.ts +178 -0
  113. package/src/lib/terminal-capability-detection.test.ts +226 -0
  114. package/src/lib/terminal-capability-detection.ts +98 -0
  115. package/src/lib/terminal-palette.test.ts +954 -0
  116. package/src/lib/terminal-palette.ts +441 -0
  117. package/src/lib/tree-sitter/assets/README.md +119 -0
  118. package/src/lib/tree-sitter/assets/javascript/highlights.scm +205 -0
  119. package/src/lib/tree-sitter/assets/javascript/tree-sitter-javascript.wasm +0 -0
  120. package/src/lib/tree-sitter/assets/markdown/highlights.scm +150 -0
  121. package/src/lib/tree-sitter/assets/markdown/injections.scm +27 -0
  122. package/src/lib/tree-sitter/assets/markdown/tree-sitter-markdown.wasm +0 -0
  123. package/src/lib/tree-sitter/assets/markdown_inline/highlights.scm +115 -0
  124. package/src/lib/tree-sitter/assets/markdown_inline/tree-sitter-markdown_inline.wasm +0 -0
  125. package/src/lib/tree-sitter/assets/typescript/highlights.scm +604 -0
  126. package/src/lib/tree-sitter/assets/typescript/tree-sitter-typescript.wasm +0 -0
  127. package/src/lib/tree-sitter/assets/update.ts +360 -0
  128. package/src/lib/tree-sitter/assets/zig/highlights.scm +284 -0
  129. package/src/lib/tree-sitter/assets/zig/tree-sitter-zig.wasm +0 -0
  130. package/src/lib/tree-sitter/assets.d.ts +9 -0
  131. package/src/lib/tree-sitter/cache.test.ts +291 -0
  132. package/src/lib/tree-sitter/client.test.ts +1434 -0
  133. package/src/lib/tree-sitter/client.ts +847 -0
  134. package/src/lib/tree-sitter/default-parsers.ts +133 -0
  135. package/src/lib/tree-sitter/download-utils.ts +148 -0
  136. package/src/lib/tree-sitter/index.ts +75 -0
  137. package/src/lib/tree-sitter/parser.worker.ts +1098 -0
  138. package/src/lib/tree-sitter/parsers-config.ts +81 -0
  139. package/src/lib/tree-sitter/resolve-ft.test.ts +55 -0
  140. package/src/lib/tree-sitter/resolve-ft.ts +189 -0
  141. package/src/lib/tree-sitter/types.ts +132 -0
  142. package/src/lib/tree-sitter/update-assets.ts +10 -0
  143. package/src/lib/tree-sitter-styled-text.test.ts +1253 -0
  144. package/src/lib/tree-sitter-styled-text.ts +314 -0
  145. package/src/lib/validate-dir-name.ts +55 -0
  146. package/src/lib/yoga.options.test.ts +628 -0
  147. package/src/lib/yoga.options.ts +346 -0
  148. package/src/native-event-worker-repro.test.ts +48 -0
  149. package/src/native-event-worker-repro.worker.ts +9 -0
  150. package/src/native-handle.test.ts +221 -0
  151. package/src/platform/ffi.test.ts +516 -0
  152. package/src/platform/ffi.ts +653 -0
  153. package/src/platform/runtime.test.ts +52 -0
  154. package/src/platform/runtime.ts +121 -0
  155. package/src/platform/test.ts +45 -0
  156. package/src/platform/worker-handler-cleanup.fixture.ts +12 -0
  157. package/src/platform/worker-onmessage-startup.fixture.ts +10 -0
  158. package/src/platform/worker-startup.fixture.ts +9 -0
  159. package/src/platform/worker.node-test.ts +153 -0
  160. package/src/platform/worker.ts +425 -0
  161. package/src/plugins/core-slot.ts +579 -0
  162. package/src/plugins/registry.ts +402 -0
  163. package/src/plugins/types.ts +46 -0
  164. package/src/post/effects.ts +948 -0
  165. package/src/post/filters.ts +512 -0
  166. package/src/post/matrices.ts +288 -0
  167. package/src/renderables/ASCIIFont.ts +219 -0
  168. package/src/renderables/Box.test.ts +474 -0
  169. package/src/renderables/Box.ts +353 -0
  170. package/src/renderables/Code.test.ts +2388 -0
  171. package/src/renderables/Code.ts +555 -0
  172. package/src/renderables/Diff.regression.test.ts +381 -0
  173. package/src/renderables/Diff.test.ts +3212 -0
  174. package/src/renderables/Diff.ts +1278 -0
  175. package/src/renderables/EditBufferRenderable.test.ts +288 -0
  176. package/src/renderables/EditBufferRenderable.ts +1152 -0
  177. package/src/renderables/FrameBuffer.ts +47 -0
  178. package/src/renderables/Input.test.ts +1310 -0
  179. package/src/renderables/Input.ts +273 -0
  180. package/src/renderables/LineNumberRenderable.ts +725 -0
  181. package/src/renderables/Markdown.ts +2144 -0
  182. package/src/renderables/ScrollBar.ts +423 -0
  183. package/src/renderables/ScrollBox.ts +903 -0
  184. package/src/renderables/Select.test.ts +1134 -0
  185. package/src/renderables/Select.ts +535 -0
  186. package/src/renderables/Slider.test.ts +456 -0
  187. package/src/renderables/Slider.ts +342 -0
  188. package/src/renderables/TabSelect.test.ts +238 -0
  189. package/src/renderables/TabSelect.ts +447 -0
  190. package/src/renderables/Text.selection-buffer.test.ts +118 -0
  191. package/src/renderables/Text.test.ts +2662 -0
  192. package/src/renderables/Text.ts +147 -0
  193. package/src/renderables/TextBufferRenderable.ts +504 -0
  194. package/src/renderables/TextNode.test.ts +1137 -0
  195. package/src/renderables/TextNode.ts +379 -0
  196. package/src/renderables/TextTable.test.ts +1411 -0
  197. package/src/renderables/TextTable.ts +1434 -0
  198. package/src/renderables/Textarea.ts +425 -0
  199. package/src/renderables/TimeToFirstDraw.ts +89 -0
  200. package/src/renderables/__snapshots__/Code.test.ts.snap +13 -0
  201. package/src/renderables/__snapshots__/Diff.test.ts.snap +785 -0
  202. package/src/renderables/__snapshots__/Text.test.ts.snap +421 -0
  203. package/src/renderables/__snapshots__/TextTable.test.ts.snap +215 -0
  204. package/src/renderables/__tests__/Code.test.ts +55 -0
  205. package/src/renderables/__tests__/LineNumberRenderable.scrollbox-simple.test.ts +144 -0
  206. package/src/renderables/__tests__/LineNumberRenderable.scrollbox.test.ts +827 -0
  207. package/src/renderables/__tests__/LineNumberRenderable.test.ts +1906 -0
  208. package/src/renderables/__tests__/LineNumberRenderable.wrapping.test.ts +85 -0
  209. package/src/renderables/__tests__/Markdown.code-colors.test.ts +288 -0
  210. package/src/renderables/__tests__/Markdown.test.ts +4175 -0
  211. package/src/renderables/__tests__/MultiRenderable.selection.test.ts +87 -0
  212. package/src/renderables/__tests__/Textarea.buffer.test.ts +683 -0
  213. package/src/renderables/__tests__/Textarea.destroyed-events.test.ts +675 -0
  214. package/src/renderables/__tests__/Textarea.editing.test.ts +2120 -0
  215. package/src/renderables/__tests__/Textarea.error-handling.test.ts +35 -0
  216. package/src/renderables/__tests__/Textarea.events.test.ts +738 -0
  217. package/src/renderables/__tests__/Textarea.highlights.test.ts +590 -0
  218. package/src/renderables/__tests__/Textarea.keybinding.test.ts +3275 -0
  219. package/src/renderables/__tests__/Textarea.paste.test.ts +357 -0
  220. package/src/renderables/__tests__/Textarea.rendering.test.ts +1927 -0
  221. package/src/renderables/__tests__/Textarea.scroll.test.ts +733 -0
  222. package/src/renderables/__tests__/Textarea.selection.test.ts +1589 -0
  223. package/src/renderables/__tests__/Textarea.stress.test.ts +670 -0
  224. package/src/renderables/__tests__/Textarea.undo-redo.test.ts +383 -0
  225. package/src/renderables/__tests__/Textarea.visual-lines.test.ts +310 -0
  226. package/src/renderables/__tests__/__snapshots__/LineNumberRenderable.code.test.ts.snap +221 -0
  227. package/src/renderables/__tests__/__snapshots__/LineNumberRenderable.scrollbox-simple.test.ts.snap +89 -0
  228. package/src/renderables/__tests__/__snapshots__/LineNumberRenderable.scrollbox.test.ts.snap +457 -0
  229. package/src/renderables/__tests__/__snapshots__/LineNumberRenderable.test.ts.snap +158 -0
  230. package/src/renderables/__tests__/__snapshots__/Textarea.rendering.test.ts.snap +387 -0
  231. package/src/renderables/__tests__/markdown-parser.test.ts +241 -0
  232. package/src/renderables/__tests__/renderable-test-utils.ts +60 -0
  233. package/src/renderables/composition/README.md +8 -0
  234. package/src/renderables/composition/VRenderable.ts +32 -0
  235. package/src/renderables/composition/constructs.ts +127 -0
  236. package/src/renderables/composition/vnode.ts +277 -0
  237. package/src/renderables/index.ts +23 -0
  238. package/src/renderables/markdown-parser.ts +79 -0
  239. package/src/renderer-theme-mode.ts +199 -0
  240. package/src/renderer.ts +4975 -0
  241. package/src/runtime-plugin-support-configure.ts +63 -0
  242. package/src/runtime-plugin-support.ts +13 -0
  243. package/src/runtime-plugin.ts +626 -0
  244. package/src/specs/terminal-startup.md +64 -0
  245. package/src/syntax-style.test.ts +841 -0
  246. package/src/syntax-style.ts +274 -0
  247. package/src/testing/README.md +219 -0
  248. package/src/testing/bun-test-node.ts +880 -0
  249. package/src/testing/capture-spans.test.ts +216 -0
  250. package/src/testing/integration.test.ts +276 -0
  251. package/src/testing/manual-clock.ts +117 -0
  252. package/src/testing/mock-keys.test.ts +1378 -0
  253. package/src/testing/mock-keys.ts +457 -0
  254. package/src/testing/mock-mouse.test.ts +218 -0
  255. package/src/testing/mock-mouse.ts +247 -0
  256. package/src/testing/mock-tree-sitter-client.ts +81 -0
  257. package/src/testing/spy.ts +13 -0
  258. package/src/testing/terminal-capabilities.ts +47 -0
  259. package/src/testing/test-recorder.test.ts +410 -0
  260. package/src/testing/test-recorder.ts +133 -0
  261. package/src/testing/test-renderer.ts +375 -0
  262. package/src/testing/test-renderer.wait.test.ts +278 -0
  263. package/src/testing/test-streams.ts +31 -0
  264. package/src/testing.ts +9 -0
  265. package/src/tests/__snapshots__/absolute-positioning.snapshot.test.ts.snap +481 -0
  266. package/src/tests/__snapshots__/renderable.snapshot.test.ts.snap +19 -0
  267. package/src/tests/__snapshots__/scrollbox.test.ts.snap +29 -0
  268. package/src/tests/absolute-positioning.snapshot.test.ts +638 -0
  269. package/src/tests/allocator-stats.test.ts +53 -0
  270. package/src/tests/audio.test.ts +303 -0
  271. package/src/tests/destroy-during-render.test.ts +200 -0
  272. package/src/tests/destroy-on-exit.fixture.ts +36 -0
  273. package/src/tests/destroy-on-exit.test.ts +62 -0
  274. package/src/tests/ffi-borrowed-pointer-callsites.test.ts +153 -0
  275. package/src/tests/hover-cursor.test.ts +98 -0
  276. package/src/tests/native-backed-measurement-lifecycle.test.ts +133 -0
  277. package/src/tests/native-backed-measurement-parity.test.ts +322 -0
  278. package/src/tests/native-span-feed-async.test.ts +173 -0
  279. package/src/tests/native-span-feed-close.test.ts +120 -0
  280. package/src/tests/native-span-feed-coverage.test.ts +227 -0
  281. package/src/tests/native-span-feed-edge-cases.test.ts +384 -0
  282. package/src/tests/native-span-feed-use-after-free.test.ts +45 -0
  283. package/src/tests/opacity.test.ts +123 -0
  284. package/src/tests/renderable.snapshot.test.ts +524 -0
  285. package/src/tests/renderable.test.ts +1851 -0
  286. package/src/tests/renderer.clock.test.ts +270 -0
  287. package/src/tests/renderer.console-startup.test.ts +2151 -0
  288. package/src/tests/renderer.control.test.ts +458 -0
  289. package/src/tests/renderer.core-slot-binding.test.ts +962 -0
  290. package/src/tests/renderer.cursor.test.ts +26 -0
  291. package/src/tests/renderer.custom-stdout.test.ts +1112 -0
  292. package/src/tests/renderer.destroy-during-render.test.ts +147 -0
  293. package/src/tests/renderer.focus-restore.test.ts +257 -0
  294. package/src/tests/renderer.focus.test.ts +329 -0
  295. package/src/tests/renderer.idle.test.ts +219 -0
  296. package/src/tests/renderer.input.test.ts +2615 -0
  297. package/src/tests/renderer.kitty-flags.test.ts +195 -0
  298. package/src/tests/renderer.lifecycle.test.ts +34 -0
  299. package/src/tests/renderer.mouse.test.ts +1315 -0
  300. package/src/tests/renderer.notifications.test.ts +27 -0
  301. package/src/tests/renderer.palette.test.ts +1199 -0
  302. package/src/tests/renderer.remote.test.ts +247 -0
  303. package/src/tests/renderer.render-stats.test.ts +146 -0
  304. package/src/tests/renderer.scrollback-surface.test.ts +474 -0
  305. package/src/tests/renderer.selection.test.ts +138 -0
  306. package/src/tests/renderer.slot-registry.test.ts +684 -0
  307. package/src/tests/renderer.tracker.test.ts +202 -0
  308. package/src/tests/renderer.useMouse.test.ts +83 -0
  309. package/src/tests/runtime-plugin-node-modules-cycle.fixture.ts +76 -0
  310. package/src/tests/runtime-plugin-node-modules-import-like-string.fixture.ts +48 -0
  311. package/src/tests/runtime-plugin-node-modules-mjs.fixture.ts +43 -0
  312. package/src/tests/runtime-plugin-node-modules-no-bare-rewrite.fixture.ts +67 -0
  313. package/src/tests/runtime-plugin-node-modules-package-type-cache.fixture.ts +72 -0
  314. package/src/tests/runtime-plugin-node-modules-runtime-specifier.fixture.ts +44 -0
  315. package/src/tests/runtime-plugin-node-modules-scoped-package-bare-rewrite.fixture.ts +85 -0
  316. package/src/tests/runtime-plugin-path-alias.fixture.ts +43 -0
  317. package/src/tests/runtime-plugin-resolve-roots.fixture.ts +65 -0
  318. package/src/tests/runtime-plugin-support-configure.fixture.ts +31 -0
  319. package/src/tests/runtime-plugin-support-late-addition.fixture.ts +17 -0
  320. package/src/tests/runtime-plugin-support.fixture.ts +11 -0
  321. package/src/tests/runtime-plugin-support.test.ts +54 -0
  322. package/src/tests/runtime-plugin-windows-file-url.fixture.ts +30 -0
  323. package/src/tests/runtime-plugin.fixture.ts +40 -0
  324. package/src/tests/runtime-plugin.test.ts +369 -0
  325. package/src/tests/scrollbox-culling-bug.test.ts +114 -0
  326. package/src/tests/scrollbox-hitgrid-resize.test.ts +136 -0
  327. package/src/tests/scrollbox-hitgrid.test.ts +909 -0
  328. package/src/tests/scrollbox.test.ts +1895 -0
  329. package/src/tests/wrap-resize-perf.test.ts +276 -0
  330. package/src/tests/yoga-api-coverage.test.ts +409 -0
  331. package/src/tests/yoga-callback-stress.test.ts +122 -0
  332. package/src/tests/yoga-ffi.test.ts +117 -0
  333. package/src/tests/yoga-setters.test.ts +921 -0
  334. package/src/tests/yoga-upstream/YGAlignBaselineTest.test.ts +124 -0
  335. package/src/tests/yoga-upstream/YGComputedBorderTest.test.ts +27 -0
  336. package/src/tests/yoga-upstream/YGComputedMarginTest.test.ts +27 -0
  337. package/src/tests/yoga-upstream/YGComputedPaddingTest.test.ts +27 -0
  338. package/src/tests/yoga-upstream/YGDirtiedTest.test.ts +157 -0
  339. package/src/tests/yoga-upstream/YGErrataTest.test.ts +40 -0
  340. package/src/tests/yoga-upstream/YGFlexBasisAuto.test.ts +23 -0
  341. package/src/tests/yoga-upstream/YGHasNewLayout.test.ts +81 -0
  342. package/src/tests/yoga-upstream/YGMeasureCacheTest.test.ts +31 -0
  343. package/src/tests/yoga-upstream/YGMeasureTest.test.ts +70 -0
  344. package/src/tests/yoga-upstream/generated/YGAbsolutePositionTest.test.ts +1864 -0
  345. package/src/tests/yoga-upstream/generated/YGAlignContentTest.test.ts +5829 -0
  346. package/src/tests/yoga-upstream/generated/YGAlignItemsTest.test.ts +2444 -0
  347. package/src/tests/yoga-upstream/generated/YGAlignSelfTest.test.ts +293 -0
  348. package/src/tests/yoga-upstream/generated/YGAndroidNewsFeed.test.ts +315 -0
  349. package/src/tests/yoga-upstream/generated/YGAspectRatioTest.test.ts +231 -0
  350. package/src/tests/yoga-upstream/generated/YGAutoTest.test.ts +347 -0
  351. package/src/tests/yoga-upstream/generated/YGBorderTest.test.ts +256 -0
  352. package/src/tests/yoga-upstream/generated/YGBoxSizingTest.test.ts +2747 -0
  353. package/src/tests/yoga-upstream/generated/YGDimensionTest.test.ts +129 -0
  354. package/src/tests/yoga-upstream/generated/YGDisplayContentsTest.test.ts +109 -0
  355. package/src/tests/yoga-upstream/generated/YGDisplayTest.test.ts +1097 -0
  356. package/src/tests/yoga-upstream/generated/YGFlexDirectionTest.test.ts +4562 -0
  357. package/src/tests/yoga-upstream/generated/YGFlexTest.test.ts +677 -0
  358. package/src/tests/yoga-upstream/generated/YGFlexWrapTest.test.ts +2071 -0
  359. package/src/tests/yoga-upstream/generated/YGGapTest.test.ts +3303 -0
  360. package/src/tests/yoga-upstream/generated/YGIntrinsicSizeTest.test.ts +582 -0
  361. package/src/tests/yoga-upstream/generated/YGJustifyContentTest.test.ts +2150 -0
  362. package/src/tests/yoga-upstream/generated/YGMarginTest.test.ts +1963 -0
  363. package/src/tests/yoga-upstream/generated/YGMinMaxDimensionTest.test.ts +1446 -0
  364. package/src/tests/yoga-upstream/generated/YGPaddingTest.test.ts +354 -0
  365. package/src/tests/yoga-upstream/generated/YGPercentageTest.test.ts +1760 -0
  366. package/src/tests/yoga-upstream/generated/YGRoundingTest.test.ts +1161 -0
  367. package/src/tests/yoga-upstream/generated/YGSizeOverflowTest.test.ts +207 -0
  368. package/src/tests/yoga-upstream/generated/YGStaticPositionTest.test.ts +6338 -0
  369. package/src/tests/yoga-upstream/tools/MeasureCounter.ts +54 -0
  370. package/src/tests/yoga-upstream/tools/utils.ts +81 -0
  371. package/src/text-buffer-view.test.ts +722 -0
  372. package/src/text-buffer-view.ts +193 -0
  373. package/src/text-buffer.test.ts +512 -0
  374. package/src/text-buffer.ts +250 -0
  375. package/src/types.ts +199 -0
  376. package/src/utils.ts +88 -0
  377. package/src/yoga.ts +1146 -0
  378. package/src/zig/ansi.zig +502 -0
  379. package/src/zig/audio.zig +1206 -0
  380. package/src/zig/bench/README.md +50 -0
  381. package/src/zig/bench/buffer-color-blending_bench.zig +350 -0
  382. package/src/zig/bench/buffer-draw-box_bench.zig +786 -0
  383. package/src/zig/bench/buffer-draw-text-buffer_bench.zig +894 -0
  384. package/src/zig/bench/edit-buffer_bench.zig +476 -0
  385. package/src/zig/bench/editor-view_bench.zig +169 -0
  386. package/src/zig/bench/native-span-feed_bench.zig +107 -0
  387. package/src/zig/bench/rope-markers_bench.zig +713 -0
  388. package/src/zig/bench/rope_bench.zig +514 -0
  389. package/src/zig/bench/styled-text_bench.zig +476 -0
  390. package/src/zig/bench/text-buffer-coords_bench.zig +362 -0
  391. package/src/zig/bench/text-buffer-view_bench.zig +459 -0
  392. package/src/zig/bench/text-chunk-graphemes_bench.zig +272 -0
  393. package/src/zig/bench/utf8_bench.zig +799 -0
  394. package/src/zig/bench-utils.zig +431 -0
  395. package/src/zig/bench.zig +223 -0
  396. package/src/zig/buffer-methods.zig +215 -0
  397. package/src/zig/buffer.zig +2515 -0
  398. package/src/zig/build.zig +700 -0
  399. package/src/zig/build.zig.zon +19 -0
  400. package/src/zig/edit-buffer.zig +900 -0
  401. package/src/zig/editor-view.zig +812 -0
  402. package/src/zig/event-bus.zig +28 -0
  403. package/src/zig/event-emitter.zig +65 -0
  404. package/src/zig/file-logger.zig +92 -0
  405. package/src/zig/grapheme.zig +838 -0
  406. package/src/zig/handles.zig +267 -0
  407. package/src/zig/lib.zig +2813 -0
  408. package/src/zig/link.zig +349 -0
  409. package/src/zig/logger.zig +43 -0
  410. package/src/zig/mem-registry.zig +126 -0
  411. package/src/zig/miniaudio_shim.c +21 -0
  412. package/src/zig/native-renderable.zig +112 -0
  413. package/src/zig/native-span-feed-bench-lib.zig +7 -0
  414. package/src/zig/native-span-feed.zig +747 -0
  415. package/src/zig/renderer-output.zig +677 -0
  416. package/src/zig/renderer.zig +2106 -0
  417. package/src/zig/rope.zig +1220 -0
  418. package/src/zig/split-scrollback.zig +88 -0
  419. package/src/zig/syntax-style.zig +174 -0
  420. package/src/zig/terminal.zig +1652 -0
  421. package/src/zig/test.zig +82 -0
  422. package/src/zig/tests/README.md +18 -0
  423. package/src/zig/tests/ansi_test.zig +18 -0
  424. package/src/zig/tests/audio_test.zig +439 -0
  425. package/src/zig/tests/buffer-methods_test.zig +1111 -0
  426. package/src/zig/tests/buffer_test.zig +2926 -0
  427. package/src/zig/tests/edit-buffer-history_test.zig +299 -0
  428. package/src/zig/tests/edit-buffer_test.zig +1688 -0
  429. package/src/zig/tests/editor-view_test.zig +3454 -0
  430. package/src/zig/tests/event-emitter_test.zig +249 -0
  431. package/src/zig/tests/grapheme_test.zig +1329 -0
  432. package/src/zig/tests/handles_test.zig +123 -0
  433. package/src/zig/tests/link_test.zig +220 -0
  434. package/src/zig/tests/mem-registry_test.zig +473 -0
  435. package/src/zig/tests/memory_leak_regression_test.zig +234 -0
  436. package/src/zig/tests/native-renderable_test.zig +16 -0
  437. package/src/zig/tests/native-span-feed_test.zig +1266 -0
  438. package/src/zig/tests/renderer_test.zig +2604 -0
  439. package/src/zig/tests/rope-nested_test.zig +712 -0
  440. package/src/zig/tests/rope_fuzz_test.zig +238 -0
  441. package/src/zig/tests/rope_test.zig +2362 -0
  442. package/src/zig/tests/segment-merge.test.zig +148 -0
  443. package/src/zig/tests/split-scrollback_test.zig +70 -0
  444. package/src/zig/tests/syntax-style_test.zig +558 -0
  445. package/src/zig/tests/terminal_test.zig +1489 -0
  446. package/src/zig/tests/test-renderer.zig +126 -0
  447. package/src/zig/tests/text-buffer-drawing_test.zig +3291 -0
  448. package/src/zig/tests/text-buffer-highlights_test.zig +706 -0
  449. package/src/zig/tests/text-buffer-iterators_test.zig +776 -0
  450. package/src/zig/tests/text-buffer-segment_test.zig +320 -0
  451. package/src/zig/tests/text-buffer-selection_test.zig +1056 -0
  452. package/src/zig/tests/text-buffer-selection_viewport_test.zig +358 -0
  453. package/src/zig/tests/text-buffer-view_test.zig +3672 -0
  454. package/src/zig/tests/text-buffer_test.zig +2191 -0
  455. package/src/zig/tests/unicode-width-map.zon +3909 -0
  456. package/src/zig/tests/utf8_no_zwj_test.zig +260 -0
  457. package/src/zig/tests/utf8_test.zig +4060 -0
  458. package/src/zig/tests/utf8_wcwidth_cursor_test.zig +267 -0
  459. package/src/zig/tests/utf8_wcwidth_test.zig +357 -0
  460. package/src/zig/tests/word-wrap-editing_test.zig +498 -0
  461. package/src/zig/tests/wrap-cache-perf_test.zig +113 -0
  462. package/src/zig/tests/yoga_test.zig +65 -0
  463. package/src/zig/text-buffer-iterators.zig +496 -0
  464. package/src/zig/text-buffer-segment.zig +403 -0
  465. package/src/zig/text-buffer-view.zig +1428 -0
  466. package/src/zig/text-buffer.zig +1272 -0
  467. package/src/zig/utf8.zig +1954 -0
  468. package/src/zig/utils.zig +12 -0
  469. package/src/zig/uucode-stub.zig +76 -0
  470. package/src/zig/vendor/miniaudio/miniaudio.h +93468 -0
  471. package/src/zig/yoga.zig +658 -0
  472. package/src/zig-structs.ts +381 -0
  473. package/src/zig.ts +5260 -0
  474. package/tsconfig.build.json +17 -0
  475. package/tsconfig.json +27 -0
  476. package/tsconfig.node-test.json +138 -0
@@ -0,0 +1,2515 @@
1
+ const std = @import("std");
2
+ const Allocator = std.mem.Allocator;
3
+ const ansi = @import("ansi.zig");
4
+ const tb = @import("text-buffer.zig");
5
+ const tbv = @import("text-buffer-view.zig");
6
+ const edv = @import("editor-view.zig");
7
+ const math = std.math;
8
+ const assert = std.debug.assert;
9
+
10
+ const gp = @import("grapheme.zig");
11
+ const link = @import("link.zig");
12
+
13
+ const logger = @import("logger.zig");
14
+ const utf8 = @import("utf8.zig");
15
+
16
+ pub const RGBA = ansi.RGBA;
17
+ pub const Vec3f = @Vector(3, f32);
18
+ pub const Vec4f = @Vector(4, f32);
19
+
20
+ const TextBuffer = tb.TextBuffer;
21
+ const TextBufferView = tbv.TextBufferView;
22
+ const EditorView = edv.EditorView;
23
+
24
+ pub const DEFAULT_SPACE_CHAR: u32 = 32;
25
+ const MAX_UNICODE_CODEPOINT: u32 = 0x10FFFF;
26
+ const BLOCK_CHAR: u32 = 0x2588; // Full block █
27
+ const QUADRANT_CHARS_COUNT = 16;
28
+
29
+ const GRAYSCALE_CHARS = " .'^\",:;Il!i><~+_-?][}{1)(|\\/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$";
30
+
31
+ pub const BorderSides = packed struct {
32
+ top: bool = false,
33
+ right: bool = false,
34
+ bottom: bool = false,
35
+ left: bool = false,
36
+ };
37
+
38
+ pub const BorderCharIndex = enum(u8) {
39
+ topLeft = 0,
40
+ topRight = 1,
41
+ bottomLeft = 2,
42
+ bottomRight = 3,
43
+ horizontal = 4,
44
+ vertical = 5,
45
+ topT = 6,
46
+ bottomT = 7,
47
+ leftT = 8,
48
+ rightT = 9,
49
+ cross = 10,
50
+ };
51
+
52
+ pub const TextSelection = struct {
53
+ start: u32,
54
+ end: u32,
55
+ bgColor: ?RGBA,
56
+ fgColor: ?RGBA,
57
+ };
58
+
59
+ pub const ClipRect = struct {
60
+ x: i32,
61
+ y: i32,
62
+ width: u32,
63
+ height: u32,
64
+ };
65
+
66
+ pub const BufferError = error{
67
+ OutOfMemory,
68
+ InvalidDimensions,
69
+ InvalidUnicode,
70
+ BufferTooSmall,
71
+ };
72
+
73
+ pub inline fn rgbaEqual(a: RGBA, b: RGBA) bool {
74
+ return a[0] == b[0] and a[1] == b[1] and a[2] == b[2] and a[3] == b[3];
75
+ }
76
+
77
+ pub const Cell = struct {
78
+ char: u32,
79
+ fg: RGBA,
80
+ bg: RGBA,
81
+ attributes: u32,
82
+ };
83
+
84
+ inline fn makeCell(char: u32, fg: RGBA, bg: RGBA, attributes: u32) Cell {
85
+ return .{
86
+ .char = char,
87
+ .fg = fg,
88
+ .bg = bg,
89
+ .attributes = attributes,
90
+ };
91
+ }
92
+
93
+ fn isRGBAWithAlpha(color: RGBA) bool {
94
+ return ansi.alpha(color) < 255;
95
+ }
96
+
97
+ inline fn isFullyOpaque(opacity: f32, fg: RGBA, bg: RGBA) bool {
98
+ return opacity == 1.0 and !isRGBAWithAlpha(fg) and !isRGBAWithAlpha(bg);
99
+ }
100
+
101
+ inline fn isFullyTransparent(opacity: f32, fg: RGBA, bg: RGBA) bool {
102
+ return opacity == 0.0 or (ansi.alpha(fg) == 0 and ansi.alpha(bg) == 0);
103
+ }
104
+
105
+ inline fn mulDiv255(a: u32, b: u32) u32 {
106
+ return (a * b + 127) / 255;
107
+ }
108
+
109
+ inline fn roundDiv(n: u32, d: u32) u8 {
110
+ return @intCast((n + d / 2) / d);
111
+ }
112
+
113
+ fn blendColors(src: RGBA, dst0: RGBA, backdrop: ?RGBA) RGBA {
114
+ const sa = @as(u32, ansi.alpha(src));
115
+
116
+ if (sa == 0) return dst0;
117
+
118
+ const dst = if (ansi.alpha(dst0) == 0) (backdrop orelse dst0) else dst0;
119
+ if (sa == 255) return ansi.rgbColor(ansi.red(src), ansi.green(src), ansi.blue(src), 255);
120
+
121
+ const da = @as(u32, ansi.alpha(dst));
122
+ const inv = 255 - sa;
123
+ const out_a = sa + mulDiv255(da, inv);
124
+
125
+ if (out_a == 0) return ansi.rgbColor(0, 0, 0, 0);
126
+
127
+ if (da == 255) {
128
+ return ansi.rgbColor(
129
+ @intCast((@as(u32, ansi.red(src)) * sa + @as(u32, ansi.red(dst)) * inv + 127) / 255),
130
+ @intCast((@as(u32, ansi.green(src)) * sa + @as(u32, ansi.green(dst)) * inv + 127) / 255),
131
+ @intCast((@as(u32, ansi.blue(src)) * sa + @as(u32, ansi.blue(dst)) * inv + 127) / 255),
132
+ 255,
133
+ );
134
+ }
135
+
136
+ return ansi.rgbColor(
137
+ roundDiv(@as(u32, ansi.red(src)) * sa + mulDiv255(@as(u32, ansi.red(dst)) * da, inv), out_a),
138
+ roundDiv(@as(u32, ansi.green(src)) * sa + mulDiv255(@as(u32, ansi.green(dst)) * da, inv), out_a),
139
+ roundDiv(@as(u32, ansi.blue(src)) * sa + mulDiv255(@as(u32, ansi.blue(dst)) * da, inv), out_a),
140
+ @intCast(out_a),
141
+ );
142
+ }
143
+
144
+ inline fn opacityToU8(opacity: f32) u8 {
145
+ return ansi.rgbaComponentToU8(opacity);
146
+ }
147
+
148
+ fn applyOpacity(color: RGBA, opacity: u8) RGBA {
149
+ return ansi.packRGBA8(
150
+ ansi.red(color),
151
+ ansi.green(color),
152
+ ansi.blue(color),
153
+ @intCast(mulDiv255(@as(u32, ansi.alpha(color)), opacity)),
154
+ ansi.getMeta(color),
155
+ );
156
+ }
157
+
158
+ /// Optimized buffer for terminal rendering
159
+ pub const OptimizedBuffer = struct {
160
+ buffer: struct {
161
+ char: []u32,
162
+ fg: []RGBA,
163
+ bg: []RGBA,
164
+ attributes: []u32,
165
+ },
166
+ width: u32,
167
+ height: u32,
168
+ respectAlpha: bool,
169
+ blendBackdropColor: ?RGBA,
170
+ allocator: Allocator,
171
+ pool: *gp.GraphemePool,
172
+ link_pool: *link.LinkPool,
173
+
174
+ grapheme_tracker: gp.GraphemeTracker,
175
+ link_tracker: link.LinkTracker,
176
+ width_method: utf8.WidthMethod,
177
+ id: []const u8,
178
+ scissor_stack: std.ArrayListUnmanaged(ClipRect),
179
+ opacity_stack: std.ArrayListUnmanaged(f32),
180
+
181
+ const InitOptions = struct {
182
+ respectAlpha: bool = false,
183
+ blendBackdropColor: ?RGBA = null,
184
+ pool: *gp.GraphemePool,
185
+ width_method: utf8.WidthMethod = .unicode,
186
+ id: []const u8 = "unnamed buffer",
187
+ link_pool: ?*link.LinkPool = null,
188
+ };
189
+
190
+ const BoxTitleLayout = struct {
191
+ shouldDraw: bool = false,
192
+ x: i32 = 0,
193
+ startX: i32 = 0,
194
+ endX: i32 = 0,
195
+ };
196
+
197
+ pub fn init(allocator: Allocator, width: u32, height: u32, options: InitOptions) BufferError!*OptimizedBuffer {
198
+ if (width == 0 or height == 0) {
199
+ logger.warn("OptimizedBuffer.init: Invalid dimensions {}x{}", .{ width, height });
200
+ return BufferError.InvalidDimensions;
201
+ }
202
+
203
+ const self = allocator.create(OptimizedBuffer) catch return BufferError.OutOfMemory;
204
+ errdefer allocator.destroy(self);
205
+
206
+ const size = width * height;
207
+
208
+ const owned_id = allocator.dupe(u8, options.id) catch return BufferError.OutOfMemory;
209
+ errdefer allocator.free(owned_id);
210
+
211
+ var scissor_stack: std.ArrayListUnmanaged(ClipRect) = .{};
212
+ errdefer scissor_stack.deinit(allocator);
213
+
214
+ var opacity_stack: std.ArrayListUnmanaged(f32) = .{};
215
+ errdefer opacity_stack.deinit(allocator);
216
+
217
+ const lp = options.link_pool orelse link.initGlobalLinkPool(allocator);
218
+ const char_buffer = allocator.alloc(u32, size) catch return BufferError.OutOfMemory;
219
+ errdefer allocator.free(char_buffer);
220
+
221
+ const fg_buffer = allocator.alloc(RGBA, size) catch return BufferError.OutOfMemory;
222
+ errdefer allocator.free(fg_buffer);
223
+
224
+ const bg_buffer = allocator.alloc(RGBA, size) catch return BufferError.OutOfMemory;
225
+ errdefer allocator.free(bg_buffer);
226
+
227
+ const attributes_buffer = allocator.alloc(u32, size) catch return BufferError.OutOfMemory;
228
+ errdefer allocator.free(attributes_buffer);
229
+
230
+ self.* = .{
231
+ .buffer = .{
232
+ .char = char_buffer,
233
+ .fg = fg_buffer,
234
+ .bg = bg_buffer,
235
+ .attributes = attributes_buffer,
236
+ },
237
+ .width = width,
238
+ .height = height,
239
+ .respectAlpha = options.respectAlpha,
240
+ .blendBackdropColor = options.blendBackdropColor,
241
+ .allocator = allocator,
242
+ .pool = options.pool,
243
+ .link_pool = lp,
244
+ .grapheme_tracker = gp.GraphemeTracker.init(allocator, options.pool),
245
+ .link_tracker = link.LinkTracker.init(allocator, lp),
246
+ .width_method = options.width_method,
247
+ .id = owned_id,
248
+ .scissor_stack = scissor_stack,
249
+ .opacity_stack = opacity_stack,
250
+ };
251
+
252
+ @memset(self.buffer.char, 0);
253
+ @memset(self.buffer.fg, ansi.rgbColor(0, 0, 0, 0));
254
+ @memset(self.buffer.bg, ansi.rgbColor(0, 0, 0, 0));
255
+ @memset(self.buffer.attributes, 0);
256
+
257
+ return self;
258
+ }
259
+
260
+ pub fn getCharPtr(self: *OptimizedBuffer) [*]u32 {
261
+ return self.buffer.char.ptr;
262
+ }
263
+
264
+ pub fn getFgPtr(self: *OptimizedBuffer) [*]RGBA {
265
+ return self.buffer.fg.ptr;
266
+ }
267
+
268
+ pub fn getBgPtr(self: *OptimizedBuffer) [*]RGBA {
269
+ return self.buffer.bg.ptr;
270
+ }
271
+
272
+ pub fn getAttributesPtr(self: *OptimizedBuffer) [*]u32 {
273
+ return self.buffer.attributes.ptr;
274
+ }
275
+
276
+ pub fn deinit(self: *OptimizedBuffer) void {
277
+ const allocator = self.allocator;
278
+ defer allocator.destroy(self);
279
+
280
+ self.opacity_stack.deinit(self.allocator);
281
+ self.scissor_stack.deinit(self.allocator);
282
+ self.link_tracker.deinit();
283
+ self.grapheme_tracker.deinit();
284
+ self.allocator.free(self.buffer.char);
285
+ self.allocator.free(self.buffer.fg);
286
+ self.allocator.free(self.buffer.bg);
287
+ self.allocator.free(self.buffer.attributes);
288
+ self.allocator.free(self.id);
289
+ self.* = undefined;
290
+ }
291
+
292
+ pub fn getCurrentScissorRect(self: *const OptimizedBuffer) ?ClipRect {
293
+ if (self.scissor_stack.items.len == 0) return null;
294
+ return self.scissor_stack.items[self.scissor_stack.items.len - 1];
295
+ }
296
+
297
+ pub fn isPointInScissor(self: *const OptimizedBuffer, x: i32, y: i32) bool {
298
+ const scissor = self.getCurrentScissorRect() orelse return true;
299
+ return x >= scissor.x and x < scissor.x + @as(i32, @intCast(scissor.width)) and
300
+ y >= scissor.y and y < scissor.y + @as(i32, @intCast(scissor.height));
301
+ }
302
+
303
+ pub fn isRectInScissor(self: *const OptimizedBuffer, x: i32, y: i32, width: u32, height: u32) bool {
304
+ const scissor = self.getCurrentScissorRect() orelse return true;
305
+
306
+ const rect_end_x = x + @as(i32, @intCast(width));
307
+ const rect_end_y = y + @as(i32, @intCast(height));
308
+ const scissor_end_x = scissor.x + @as(i32, @intCast(scissor.width));
309
+ const scissor_end_y = scissor.y + @as(i32, @intCast(scissor.height));
310
+
311
+ return !(x >= scissor_end_x or rect_end_x <= scissor.x or
312
+ y >= scissor_end_y or rect_end_y <= scissor.y);
313
+ }
314
+
315
+ pub fn clipRectToScissor(self: *const OptimizedBuffer, x: i32, y: i32, width: u32, height: u32) ?ClipRect {
316
+ const scissor = self.getCurrentScissorRect() orelse return ClipRect{
317
+ .x = x,
318
+ .y = y,
319
+ .width = width,
320
+ .height = height,
321
+ };
322
+
323
+ const rect_end_x = x + @as(i32, @intCast(width));
324
+ const rect_end_y = y + @as(i32, @intCast(height));
325
+ const scissor_end_x = scissor.x + @as(i32, @intCast(scissor.width));
326
+ const scissor_end_y = scissor.y + @as(i32, @intCast(scissor.height));
327
+
328
+ const intersect_x = @max(x, scissor.x);
329
+ const intersect_y = @max(y, scissor.y);
330
+ const intersect_end_x = @min(rect_end_x, scissor_end_x);
331
+ const intersect_end_y = @min(rect_end_y, scissor_end_y);
332
+
333
+ if (intersect_x >= intersect_end_x or intersect_y >= intersect_end_y) {
334
+ return null; // No intersection
335
+ }
336
+
337
+ return .{
338
+ .x = intersect_x,
339
+ .y = intersect_y,
340
+ .width = @intCast(intersect_end_x - intersect_x),
341
+ .height = @intCast(intersect_end_y - intersect_y),
342
+ };
343
+ }
344
+
345
+ pub fn pushScissorRect(self: *OptimizedBuffer, x: i32, y: i32, width: u32, height: u32) !void {
346
+ var rect: ClipRect = .{
347
+ .x = x,
348
+ .y = y,
349
+ .width = width,
350
+ .height = height,
351
+ };
352
+
353
+ // Intersect with current scissor (if any) so nested scissor rects always clip to parents.
354
+ if (self.getCurrentScissorRect() != null) {
355
+ const intersect = self.clipRectToScissor(rect.x, rect.y, rect.width, rect.height);
356
+ if (intersect) |clipped| {
357
+ rect = clipped;
358
+ } else {
359
+ // Completely outside current scissor; push a degenerate rect so nothing renders.
360
+ rect = ClipRect{ .x = 0, .y = 0, .width = 0, .height = 0 };
361
+ }
362
+ }
363
+
364
+ try self.scissor_stack.append(self.allocator, rect);
365
+ }
366
+
367
+ pub fn popScissorRect(self: *OptimizedBuffer) void {
368
+ if (self.scissor_stack.items.len > 0) {
369
+ _ = self.scissor_stack.pop();
370
+ }
371
+ }
372
+
373
+ pub fn clearScissorRects(self: *OptimizedBuffer) void {
374
+ self.scissor_stack.clearRetainingCapacity();
375
+ }
376
+
377
+ /// Get the current effective opacity (product of all stacked opacities)
378
+ pub fn getCurrentOpacity(self: *const OptimizedBuffer) f32 {
379
+ if (self.opacity_stack.items.len == 0) return 1.0;
380
+ return self.opacity_stack.items[self.opacity_stack.items.len - 1];
381
+ }
382
+
383
+ /// Push an opacity value onto the stack. The effective opacity is multiplied with the current.
384
+ pub fn pushOpacity(self: *OptimizedBuffer, opacity: f32) !void {
385
+ const current = self.getCurrentOpacity();
386
+ const effective = current * std.math.clamp(opacity, 0.0, 1.0);
387
+ try self.opacity_stack.append(self.allocator, effective);
388
+ }
389
+
390
+ /// Pop an opacity value from the stack
391
+ pub fn popOpacity(self: *OptimizedBuffer) void {
392
+ if (self.opacity_stack.items.len > 0) {
393
+ _ = self.opacity_stack.pop();
394
+ }
395
+ }
396
+
397
+ /// Clear all opacity values from the stack
398
+ pub fn clearOpacity(self: *OptimizedBuffer) void {
399
+ self.opacity_stack.clearRetainingCapacity();
400
+ }
401
+
402
+ pub fn resize(self: *OptimizedBuffer, width: u32, height: u32) BufferError!void {
403
+ if (self.width == width and self.height == height) return;
404
+ if (width == 0 or height == 0) return BufferError.InvalidDimensions;
405
+
406
+ const size = width * height;
407
+
408
+ self.buffer.char = self.allocator.realloc(self.buffer.char, size) catch return BufferError.OutOfMemory;
409
+ self.buffer.fg = self.allocator.realloc(self.buffer.fg, size) catch return BufferError.OutOfMemory;
410
+ self.buffer.bg = self.allocator.realloc(self.buffer.bg, size) catch return BufferError.OutOfMemory;
411
+ self.buffer.attributes = self.allocator.realloc(self.buffer.attributes, size) catch return BufferError.OutOfMemory;
412
+
413
+ self.width = width;
414
+ self.height = height;
415
+
416
+ // Always clear after resize to initialize cells (realloc doesn't zero memory)
417
+ // This handles both growing (new cells are garbage) and shrinking (grapheme cleanup)
418
+ self.clear(ansi.rgbColor(0, 0, 0, 255), null);
419
+ }
420
+
421
+ fn coordsToIndex(self: *const OptimizedBuffer, x: u32, y: u32) u32 {
422
+ return y * self.width + x;
423
+ }
424
+
425
+ fn indexToCoords(self: *const OptimizedBuffer, index: u32) struct { x: u32, y: u32 } {
426
+ return .{
427
+ .x = index % self.width,
428
+ .y = index / self.width,
429
+ };
430
+ }
431
+
432
+ pub fn clear(self: *OptimizedBuffer, bg: RGBA, char: ?u32) void {
433
+ const cellChar = char orelse DEFAULT_SPACE_CHAR;
434
+ self.link_tracker.clear();
435
+ self.grapheme_tracker.clear();
436
+ @memset(self.buffer.char, @intCast(cellChar));
437
+ @memset(self.buffer.attributes, 0);
438
+ @memset(self.buffer.fg, ansi.rgbColor(255, 255, 255, 255));
439
+ @memset(self.buffer.bg, bg);
440
+ }
441
+
442
+ /// Write a single cell and update link tracker. No grapheme tracking,
443
+ /// span cleanup, or continuation propagation.
444
+ pub fn setRaw(self: *OptimizedBuffer, x: u32, y: u32, cell: Cell) void {
445
+ const index = self.validateAndIndex(x, y) orelse return;
446
+ self.writeCellAndLinks(index, cell);
447
+ }
448
+
449
+ /// Like set(), but without span cleanup. Writes the cell, its continuation
450
+ /// cells (for width-2+ graphemes), and updates grapheme/link trackers.
451
+ ///
452
+ /// Intended for the renderer's diff loop where cells are synced from an
453
+ /// authoritative source buffer. Span cleanup is skipped because it can
454
+ /// destroy continuation cells that were correctly written by an earlier
455
+ /// iteration of the same left-to-right pass (issue #723).
456
+ pub fn syncCell(self: *OptimizedBuffer, x: u32, y: u32, cell: Cell) void {
457
+ self.setInternal(false, x, y, cell);
458
+ }
459
+
460
+ pub fn set(self: *OptimizedBuffer, x: u32, y: u32, cell: Cell) void {
461
+ self.setInternal(true, x, y, cell);
462
+ }
463
+
464
+ fn setInternal(self: *OptimizedBuffer, comptime span_cleanup: bool, x: u32, y: u32, cell: Cell) void {
465
+ const index = self.validateAndIndex(x, y) orelse return;
466
+ const prev_char = self.buffer.char[index];
467
+ const prev_link_id = ansi.TextAttributes.getLinkId(self.buffer.attributes[index]);
468
+ var tracker_replaced = false;
469
+
470
+ if (!span_cleanup) {
471
+ const old_start_id: ?u32 = if (gp.isGraphemeChar(prev_char)) gp.graphemeIdFromChar(prev_char) else null;
472
+ const new_start_id: ?u32 = blk: {
473
+ if (!gp.isGraphemeChar(cell.char)) break :blk null;
474
+ const new_width = gp.charRightExtent(cell.char) + 1;
475
+ if (x + new_width > self.width) break :blk null;
476
+ break :blk gp.graphemeIdFromChar(cell.char);
477
+ };
478
+
479
+ if (old_start_id != null or new_start_id != null) {
480
+ self.grapheme_tracker.replace(old_start_id, new_start_id);
481
+ tracker_replaced = true;
482
+ }
483
+ }
484
+
485
+ // If overwriting a grapheme span (start or continuation) with a different char, clear that span first
486
+ if (span_cleanup) {
487
+ if ((gp.isGraphemeChar(prev_char) or gp.isContinuationChar(prev_char)) and prev_char != cell.char) {
488
+ const row_start: u32 = y * self.width;
489
+ const row_end: u32 = row_start + self.width - 1;
490
+ const left = gp.charLeftExtent(prev_char);
491
+ const right = gp.charRightExtent(prev_char);
492
+ const id = gp.graphemeIdFromChar(prev_char);
493
+
494
+ const new_grapheme_id: ?u32 = blk: {
495
+ if (!gp.isGraphemeChar(cell.char)) break :blk null;
496
+ const new_width = gp.charRightExtent(cell.char) + 1;
497
+ if (x + new_width > self.width) break :blk null;
498
+ break :blk gp.graphemeIdFromChar(cell.char);
499
+ };
500
+ self.grapheme_tracker.replace(id, new_grapheme_id);
501
+ tracker_replaced = true;
502
+
503
+ const span_start = index - @min(left, index - row_start);
504
+ const span_end = index + @min(right, row_end - index);
505
+
506
+ var span_i: u32 = span_start;
507
+ while (span_i <= span_end) : (span_i += 1) {
508
+ const span_char = self.buffer.char[span_i];
509
+ if (!(gp.isGraphemeChar(span_char) or gp.isContinuationChar(span_char))) continue;
510
+ if (gp.graphemeIdFromChar(span_char) != id) continue;
511
+
512
+ const span_link_id = ansi.TextAttributes.getLinkId(self.buffer.attributes[span_i]);
513
+ if (span_link_id != 0) {
514
+ self.link_tracker.removeCellRef(span_link_id);
515
+ }
516
+
517
+ self.buffer.char[span_i] = @intCast(DEFAULT_SPACE_CHAR);
518
+ self.buffer.attributes[span_i] = 0;
519
+ }
520
+ }
521
+ }
522
+
523
+ if (gp.isGraphemeChar(cell.char)) {
524
+ const right = gp.charRightExtent(cell.char);
525
+ const width: u32 = 1 + right;
526
+
527
+ if (x + width > self.width) {
528
+ const end_of_line = (y + 1) * self.width;
529
+ var eol_i = index;
530
+ while (eol_i < end_of_line) : (eol_i += 1) {
531
+ const eol_link_id = ansi.TextAttributes.getLinkId(self.buffer.attributes[eol_i]);
532
+ if (eol_link_id != 0) {
533
+ self.link_tracker.removeCellRef(eol_link_id);
534
+ }
535
+ }
536
+ @memset(self.buffer.char[index..end_of_line], @intCast(DEFAULT_SPACE_CHAR));
537
+ @memset(self.buffer.attributes[index..end_of_line], cell.attributes);
538
+ @memset(self.buffer.fg[index..end_of_line], cell.fg);
539
+ @memset(self.buffer.bg[index..end_of_line], cell.bg);
540
+ const new_link_id = ansi.TextAttributes.getLinkId(cell.attributes);
541
+ if (new_link_id != 0) {
542
+ const cells_written = end_of_line - index;
543
+ var link_i: u32 = 0;
544
+ while (link_i < cells_written) : (link_i += 1) {
545
+ self.link_tracker.addCellRef(new_link_id);
546
+ }
547
+ }
548
+ return;
549
+ }
550
+
551
+ self.buffer.char[index] = cell.char;
552
+ self.buffer.fg[index] = cell.fg;
553
+ self.buffer.bg[index] = cell.bg;
554
+ self.buffer.attributes[index] = cell.attributes;
555
+
556
+ const id: u32 = gp.graphemeIdFromChar(cell.char);
557
+ const is_same_grapheme_start = gp.isGraphemeChar(prev_char) and prev_char == cell.char;
558
+ if (!tracker_replaced and !is_same_grapheme_start) {
559
+ self.grapheme_tracker.add(id);
560
+ }
561
+
562
+ const new_link_id = ansi.TextAttributes.getLinkId(cell.attributes);
563
+ if (prev_link_id != 0 and prev_link_id != new_link_id) {
564
+ self.link_tracker.removeCellRef(prev_link_id);
565
+ }
566
+ if (new_link_id != 0 and new_link_id != prev_link_id) {
567
+ self.link_tracker.addCellRef(new_link_id);
568
+ }
569
+
570
+ if (width > 1) {
571
+ const row_end_index: u32 = (y * self.width) + self.width - 1;
572
+ const max_right = @min(right, row_end_index - index);
573
+ if (max_right > 0) {
574
+ var cont_i: u32 = 1;
575
+ while (cont_i <= max_right) : (cont_i += 1) {
576
+ const cont_link_id = ansi.TextAttributes.getLinkId(self.buffer.attributes[index + cont_i]);
577
+ if (cont_link_id != 0) {
578
+ self.link_tracker.removeCellRef(cont_link_id);
579
+ }
580
+ }
581
+
582
+ @memset(self.buffer.fg[index + 1 .. index + 1 + max_right], cell.fg);
583
+ @memset(self.buffer.bg[index + 1 .. index + 1 + max_right], cell.bg);
584
+ @memset(self.buffer.attributes[index + 1 .. index + 1 + max_right], cell.attributes);
585
+ var k: u32 = 1;
586
+ while (k <= max_right) : (k += 1) {
587
+ const cont = gp.packContinuation(k, max_right - k, id);
588
+ self.buffer.char[index + k] = cont;
589
+ if (new_link_id != 0) {
590
+ self.link_tracker.addCellRef(new_link_id);
591
+ }
592
+ }
593
+ }
594
+ }
595
+ } else {
596
+ self.writeCellAndLinks(index, cell);
597
+ }
598
+ }
599
+
600
+ /// Validate coordinates and return buffer index, or null if out of bounds / scissor.
601
+ fn validateAndIndex(self: *OptimizedBuffer, x: u32, y: u32) ?u32 {
602
+ if (x >= self.width or y >= self.height) return null;
603
+ if (!self.isPointInScissor(@intCast(x), @intCast(y))) return null;
604
+ return self.coordsToIndex(x, y);
605
+ }
606
+
607
+ /// Write cell data at index and update link tracker.
608
+ fn writeCellAndLinks(self: *OptimizedBuffer, index: u32, cell: Cell) void {
609
+ const prev_link_id = ansi.TextAttributes.getLinkId(self.buffer.attributes[index]);
610
+ const new_link_id = ansi.TextAttributes.getLinkId(cell.attributes);
611
+
612
+ self.buffer.char[index] = cell.char;
613
+ self.buffer.fg[index] = cell.fg;
614
+ self.buffer.bg[index] = cell.bg;
615
+ self.buffer.attributes[index] = cell.attributes;
616
+
617
+ if (prev_link_id != 0 and prev_link_id != new_link_id) {
618
+ self.link_tracker.removeCellRef(prev_link_id);
619
+ }
620
+ if (new_link_id != 0 and new_link_id != prev_link_id) {
621
+ self.link_tracker.addCellRef(new_link_id);
622
+ }
623
+ }
624
+
625
+ pub fn get(self: *const OptimizedBuffer, x: u32, y: u32) ?Cell {
626
+ if (x >= self.width or y >= self.height) return null;
627
+
628
+ const index = self.coordsToIndex(x, y);
629
+ return .{
630
+ .char = self.buffer.char[index],
631
+ .fg = self.buffer.fg[index],
632
+ .bg = self.buffer.bg[index],
633
+ .attributes = self.buffer.attributes[index],
634
+ };
635
+ }
636
+
637
+ pub fn getWidth(self: *const OptimizedBuffer) u32 {
638
+ return self.width;
639
+ }
640
+
641
+ pub fn getHeight(self: *const OptimizedBuffer) u32 {
642
+ return self.height;
643
+ }
644
+
645
+ pub fn setRespectAlpha(self: *OptimizedBuffer, respectAlpha: bool) void {
646
+ self.respectAlpha = respectAlpha;
647
+ }
648
+
649
+ pub fn getRespectAlpha(self: *const OptimizedBuffer) bool {
650
+ return self.respectAlpha;
651
+ }
652
+
653
+ pub fn setBlendBackdropColor(self: *OptimizedBuffer, color: ?RGBA) void {
654
+ self.blendBackdropColor = color;
655
+ }
656
+
657
+ pub fn getBlendBackdropColor(self: *const OptimizedBuffer) ?RGBA {
658
+ return self.blendBackdropColor;
659
+ }
660
+
661
+ pub fn getId(self: *const OptimizedBuffer) []const u8 {
662
+ return self.id;
663
+ }
664
+
665
+ /// Calculate the real byte size of the character buffer including grapheme pool data
666
+ pub fn getRealCharSize(self: *const OptimizedBuffer) u32 {
667
+ const total_chars = self.width * self.height;
668
+ const grapheme_count = self.grapheme_tracker.getGraphemeCellCount();
669
+ const total_grapheme_bytes = self.grapheme_tracker.getTotalGraphemeBytes();
670
+
671
+ const regular_char_bytes = (total_chars - grapheme_count) * @sizeOf(u32);
672
+ return regular_char_bytes + total_grapheme_bytes;
673
+ }
674
+
675
+ /// Write all resolved character bytes to the given output buffer
676
+ /// Returns the number of bytes written, or 0 if the output buffer is too small
677
+ pub fn writeResolvedChars(self: *const OptimizedBuffer, output_buffer: []u8, addLineBreaks: bool) BufferError!u32 {
678
+ var bytes_written: u32 = 0;
679
+ const total_cells = self.width * self.height;
680
+
681
+ var i: u32 = 0;
682
+ while (i < total_cells) : (i += 1) {
683
+ const char_code = self.buffer.char[i];
684
+
685
+ if (gp.isGraphemeChar(char_code)) {
686
+ const gid = gp.graphemeIdFromChar(char_code);
687
+ if (self.pool.get(gid)) |grapheme_bytes| {
688
+ if (bytes_written + grapheme_bytes.len > output_buffer.len) {
689
+ return BufferError.BufferTooSmall;
690
+ }
691
+ @memcpy(output_buffer[bytes_written .. bytes_written + grapheme_bytes.len], grapheme_bytes);
692
+ bytes_written += @intCast(grapheme_bytes.len);
693
+ } else |_| {
694
+ if (bytes_written + 1 > output_buffer.len) {
695
+ return BufferError.BufferTooSmall;
696
+ }
697
+ output_buffer[bytes_written] = ' ';
698
+ bytes_written += 1;
699
+ }
700
+ } else if (gp.isContinuationChar(char_code)) {
701
+ continue;
702
+ } else {
703
+ const codepoint = char_code;
704
+
705
+ if (codepoint == 0 or codepoint > 0x10FFFF) {
706
+ if (bytes_written + 1 > output_buffer.len) {
707
+ return BufferError.BufferTooSmall;
708
+ }
709
+ output_buffer[bytes_written] = ' ';
710
+ bytes_written += 1;
711
+ continue;
712
+ }
713
+
714
+ var utf8_bytes: [4]u8 = undefined;
715
+ const utf8_len = std.unicode.utf8Encode(@intCast(codepoint), &utf8_bytes) catch {
716
+ if (bytes_written + 1 > output_buffer.len) {
717
+ return BufferError.BufferTooSmall;
718
+ }
719
+ output_buffer[bytes_written] = ' ';
720
+ bytes_written += 1;
721
+ continue;
722
+ };
723
+
724
+ if (bytes_written + utf8_len > output_buffer.len) {
725
+ return BufferError.BufferTooSmall;
726
+ }
727
+ @memcpy(output_buffer[bytes_written .. bytes_written + utf8_len], utf8_bytes[0..utf8_len]);
728
+ bytes_written += @intCast(utf8_len);
729
+ }
730
+
731
+ if (addLineBreaks and (i + 1) % self.width == 0) {
732
+ if (bytes_written + 1 > output_buffer.len) {
733
+ return BufferError.BufferTooSmall;
734
+ }
735
+ output_buffer[bytes_written] = '\n';
736
+ bytes_written += 1;
737
+ }
738
+ }
739
+
740
+ return bytes_written;
741
+ }
742
+
743
+ pub fn blendCells(self: *const OptimizedBuffer, overlayCell: Cell, destCell: Cell) Cell {
744
+ const hasBgAlpha = isRGBAWithAlpha(overlayCell.bg);
745
+ const hasFgAlpha = isRGBAWithAlpha(overlayCell.fg);
746
+
747
+ if (hasBgAlpha or hasFgAlpha) {
748
+ const blendedBg = if (hasBgAlpha)
749
+ blendColors(overlayCell.bg, destCell.bg, self.blendBackdropColor)
750
+ else
751
+ overlayCell.bg;
752
+ const charIsDefaultSpace = overlayCell.char == DEFAULT_SPACE_CHAR;
753
+ const destNotZero = destCell.char != 0;
754
+ const destNotDefaultSpace = destCell.char != DEFAULT_SPACE_CHAR;
755
+ const destWidthIsOne = gp.encodedCharWidth(destCell.char) == 1;
756
+
757
+ const preserveChar = (charIsDefaultSpace and
758
+ destNotZero and
759
+ destNotDefaultSpace and
760
+ destWidthIsOne);
761
+ const finalChar = if (preserveChar) destCell.char else overlayCell.char;
762
+
763
+ var finalFg: RGBA = undefined;
764
+ if (preserveChar) {
765
+ finalFg = blendColors(overlayCell.bg, destCell.fg, self.blendBackdropColor);
766
+ } else {
767
+ finalFg = if (hasFgAlpha)
768
+ blendColors(overlayCell.fg, blendedBg, self.blendBackdropColor)
769
+ else
770
+ overlayCell.fg;
771
+ }
772
+
773
+ // When preserving char, preserve its base attributes but NOT its link
774
+ // Links ALWAYS come from overlay, never from destination
775
+ // Even if overlay has no link (link_id=0), it clears the destination's link
776
+ const baseAttrs = if (preserveChar)
777
+ ansi.TextAttributes.getBaseAttributes(destCell.attributes)
778
+ else
779
+ ansi.TextAttributes.getBaseAttributes(overlayCell.attributes);
780
+ // Overlay link always wins - whether it's a real link or 0 (no link)
781
+ const overlayLinkId = ansi.TextAttributes.getLinkId(overlayCell.attributes);
782
+ const finalAttributes = ansi.TextAttributes.setLinkId(@as(u32, baseAttrs), overlayLinkId);
783
+
784
+ return .{
785
+ .char = finalChar,
786
+ .fg = finalFg,
787
+ .bg = blendedBg,
788
+ .attributes = finalAttributes,
789
+ };
790
+ }
791
+
792
+ return overlayCell;
793
+ }
794
+
795
+ pub fn setCellWithAlphaBlending(
796
+ self: *OptimizedBuffer,
797
+ x: u32,
798
+ y: u32,
799
+ char: u32,
800
+ fg: RGBA,
801
+ bg: RGBA,
802
+ attributes: u32,
803
+ ) void {
804
+ self.setCellWithAlphaBlendingCell(x, y, makeCell(char, fg, bg, attributes));
805
+ }
806
+
807
+ fn setCellWithAlphaBlendingCell(self: *OptimizedBuffer, x: u32, y: u32, cell: Cell) void {
808
+ if (!self.isPointInScissor(@intCast(x), @intCast(y))) return;
809
+
810
+ const opacity = self.getCurrentOpacity();
811
+ if (isFullyTransparent(opacity, cell.fg, cell.bg)) return;
812
+ if (isFullyOpaque(opacity, cell.fg, cell.bg)) {
813
+ self.set(x, y, cell);
814
+ return;
815
+ }
816
+
817
+ const opacity_u8 = opacityToU8(opacity);
818
+ const effectiveCell = makeCell(
819
+ cell.char,
820
+ applyOpacity(cell.fg, opacity_u8),
821
+ applyOpacity(cell.bg, opacity_u8),
822
+ cell.attributes,
823
+ );
824
+
825
+ if (self.get(x, y)) |destCell| {
826
+ const blendedCell = self.blendCells(effectiveCell, destCell);
827
+ self.set(x, y, blendedCell);
828
+ } else {
829
+ self.set(x, y, effectiveCell);
830
+ }
831
+ }
832
+
833
+ pub fn setCellWithAlphaBlendingRaw(
834
+ self: *OptimizedBuffer,
835
+ x: u32,
836
+ y: u32,
837
+ char: u32,
838
+ fg: RGBA,
839
+ bg: RGBA,
840
+ attributes: u32,
841
+ ) void {
842
+ self.setCellWithAlphaBlendingRawCell(x, y, makeCell(char, fg, bg, attributes));
843
+ }
844
+
845
+ fn setCellWithAlphaBlendingRawCell(self: *OptimizedBuffer, x: u32, y: u32, cell: Cell) void {
846
+ if (!self.isPointInScissor(@intCast(x), @intCast(y))) return;
847
+
848
+ const opacity = self.getCurrentOpacity();
849
+ if (isFullyTransparent(opacity, cell.fg, cell.bg)) return;
850
+ if (isFullyOpaque(opacity, cell.fg, cell.bg)) {
851
+ assert(!gp.isGraphemeChar(cell.char));
852
+ assert(!gp.isContinuationChar(cell.char));
853
+ self.setRaw(x, y, cell);
854
+ return;
855
+ }
856
+
857
+ const opacity_u8 = opacityToU8(opacity);
858
+ const effectiveCell = makeCell(
859
+ cell.char,
860
+ applyOpacity(cell.fg, opacity_u8),
861
+ applyOpacity(cell.bg, opacity_u8),
862
+ cell.attributes,
863
+ );
864
+
865
+ if (self.get(x, y)) |destCell| {
866
+ const blendedCell = self.blendCells(effectiveCell, destCell);
867
+ assert(!gp.isGraphemeChar(blendedCell.char));
868
+ assert(!gp.isContinuationChar(blendedCell.char));
869
+ self.setRaw(x, y, blendedCell);
870
+ } else {
871
+ assert(!gp.isGraphemeChar(effectiveCell.char));
872
+ assert(!gp.isContinuationChar(effectiveCell.char));
873
+ self.setRaw(x, y, effectiveCell);
874
+ }
875
+ }
876
+
877
+ inline fn trySetTransparentTextCellFast(
878
+ self: *OptimizedBuffer,
879
+ index: u32,
880
+ char: u32,
881
+ fg: RGBA,
882
+ attributes: u32,
883
+ ) bool {
884
+ // drawTextBuffer spends a lot of time in generic alpha blending when the
885
+ // common case is really "opaque glyph over transparent bg". In that case
886
+ // the result is just: keep the destination background, write fg/attrs,
887
+ // and preserve an underlying visible glyph when the overlay char is a
888
+ // transparent space. Links and graphemes stay on the slow path because
889
+ // they need tracker maintenance that direct writes would skip.
890
+ if (ansi.alpha(fg) != 255) return false;
891
+ if (ansi.TextAttributes.getLinkId(attributes) != 0) return false;
892
+ if (gp.isGraphemeChar(char) or gp.isContinuationChar(char)) return false;
893
+
894
+ const dest_char = self.buffer.char[index];
895
+ const dest_attributes = self.buffer.attributes[index];
896
+ if (ansi.TextAttributes.getLinkId(dest_attributes) != 0) return false;
897
+ if (gp.isGraphemeChar(dest_char) or gp.isContinuationChar(dest_char)) return false;
898
+
899
+ if (char == DEFAULT_SPACE_CHAR and dest_char != 0 and dest_char != DEFAULT_SPACE_CHAR and gp.encodedCharWidth(dest_char) == 1) {
900
+ return true;
901
+ }
902
+
903
+ self.buffer.char[index] = char;
904
+ self.buffer.fg[index] = fg;
905
+ self.buffer.attributes[index] = attributes;
906
+ return true;
907
+ }
908
+
909
+ pub fn drawChar(
910
+ self: *OptimizedBuffer,
911
+ char: u32,
912
+ x: u32,
913
+ y: u32,
914
+ fg: RGBA,
915
+ bg: RGBA,
916
+ attributes: u32,
917
+ ) void {
918
+ self.setCellWithAlphaBlendingCell(x, y, makeCell(char, fg, bg, attributes));
919
+ }
920
+
921
+ pub fn fillRect(
922
+ self: *OptimizedBuffer,
923
+ x: u32,
924
+ y: u32,
925
+ width: u32,
926
+ height: u32,
927
+ bg: RGBA,
928
+ ) void {
929
+ if (self.width == 0 or self.height == 0 or width == 0 or height == 0) return;
930
+ if (x >= self.width or y >= self.height) return;
931
+
932
+ if (!self.isRectInScissor(@intCast(x), @intCast(y), width, height)) return;
933
+
934
+ const opacity = self.getCurrentOpacity();
935
+ if (isFullyTransparent(opacity, ansi.rgbColor(0, 0, 0, 0), bg)) return;
936
+
937
+ const startX = x;
938
+ const startY = y;
939
+ const maxEndX = if (x < self.width) self.width - 1 else 0;
940
+ const maxEndY = if (y < self.height) self.height - 1 else 0;
941
+ const requestedEndX = x + width - 1;
942
+ const requestedEndY = y + height - 1;
943
+ const endX = @min(maxEndX, requestedEndX);
944
+ const endY = @min(maxEndY, requestedEndY);
945
+
946
+ if (startX > endX or startY > endY) return;
947
+
948
+ const clippedRect = self.clipRectToScissor(@intCast(startX), @intCast(startY), endX - startX + 1, endY - startY + 1) orelse return;
949
+ const clippedStartX = @max(startX, @as(u32, @intCast(clippedRect.x)));
950
+ const clippedStartY = @max(startY, @as(u32, @intCast(clippedRect.y)));
951
+ const clippedEndX = @min(endX, @as(u32, @intCast(clippedRect.x + @as(i32, @intCast(clippedRect.width)) - 1)));
952
+ const clippedEndY = @min(endY, @as(u32, @intCast(clippedRect.y + @as(i32, @intCast(clippedRect.height)) - 1)));
953
+
954
+ const hasAlpha = isRGBAWithAlpha(bg) or opacity < 1.0;
955
+ const graphemeAware = self.grapheme_tracker.hasAny();
956
+ const linkAware = self.link_tracker.hasAny();
957
+
958
+ if (graphemeAware or linkAware) {
959
+ var fillY = clippedStartY;
960
+ while (fillY <= clippedEndY) : (fillY += 1) {
961
+ var fillX = clippedStartX;
962
+ while (fillX <= clippedEndX) : (fillX += 1) {
963
+ self.setCellWithAlphaBlendingCell(
964
+ fillX,
965
+ fillY,
966
+ makeCell(DEFAULT_SPACE_CHAR, ansi.rgbColor(255, 255, 255, 255), bg, 0),
967
+ );
968
+ }
969
+ }
970
+ } else if (hasAlpha) {
971
+ // No grapheme/link bookkeeping is needed here, so the raw blend
972
+ // path avoids the extra tracker work done by the generic setter.
973
+ var fillY = clippedStartY;
974
+ while (fillY <= clippedEndY) : (fillY += 1) {
975
+ var fillX = clippedStartX;
976
+ while (fillX <= clippedEndX) : (fillX += 1) {
977
+ self.setCellWithAlphaBlendingRaw(fillX, fillY, DEFAULT_SPACE_CHAR, ansi.rgbColor(255, 255, 255, 255), bg, 0);
978
+ }
979
+ }
980
+ } else {
981
+ // For non-alpha (fully opaque) backgrounds with no graphemes or links, we can do direct filling
982
+ var fillY = clippedStartY;
983
+ while (fillY <= clippedEndY) : (fillY += 1) {
984
+ const rowStartIndex = self.coordsToIndex(@intCast(clippedStartX), @intCast(fillY));
985
+ const rowWidth = clippedEndX - clippedStartX + 1;
986
+
987
+ const rowSliceChar = self.buffer.char[rowStartIndex .. rowStartIndex + rowWidth];
988
+ const rowSliceFg = self.buffer.fg[rowStartIndex .. rowStartIndex + rowWidth];
989
+ const rowSliceBg = self.buffer.bg[rowStartIndex .. rowStartIndex + rowWidth];
990
+ const rowSliceAttrs = self.buffer.attributes[rowStartIndex .. rowStartIndex + rowWidth];
991
+
992
+ @memset(rowSliceChar, @intCast(DEFAULT_SPACE_CHAR));
993
+ @memset(rowSliceFg, ansi.rgbColor(255, 255, 255, 255));
994
+ @memset(rowSliceBg, bg);
995
+ @memset(rowSliceAttrs, 0);
996
+ }
997
+ }
998
+ }
999
+
1000
+ fn fillRectClipped(
1001
+ self: *OptimizedBuffer,
1002
+ x: i32,
1003
+ y: i32,
1004
+ width: u32,
1005
+ height: u32,
1006
+ bg: RGBA,
1007
+ ) void {
1008
+ if (width == 0 or height == 0) return;
1009
+
1010
+ const startX = @max(0, x);
1011
+ const startY = @max(0, y);
1012
+ const endX = @min(@as(i32, @intCast(self.width)) - 1, x + @as(i32, @intCast(width)) - 1);
1013
+ const endY = @min(@as(i32, @intCast(self.height)) - 1, y + @as(i32, @intCast(height)) - 1);
1014
+
1015
+ if (startX > endX or startY > endY) return;
1016
+
1017
+ self.fillRect(
1018
+ @intCast(startX),
1019
+ @intCast(startY),
1020
+ @intCast(endX - startX + 1),
1021
+ @intCast(endY - startY + 1),
1022
+ bg,
1023
+ );
1024
+ }
1025
+
1026
+ pub fn drawText(
1027
+ self: *OptimizedBuffer,
1028
+ text: []const u8,
1029
+ x: u32,
1030
+ y: u32,
1031
+ fg: RGBA,
1032
+ bg: ?RGBA,
1033
+ attributes: u32,
1034
+ ) BufferError!void {
1035
+ if (x >= self.width or y >= self.height) return;
1036
+ if (text.len == 0) return;
1037
+
1038
+ const opacity = self.getCurrentOpacity();
1039
+ if (isFullyTransparent(opacity, fg, bg orelse ansi.rgbColor(0, 0, 0, 0))) return;
1040
+
1041
+ const is_ascii_only = utf8.isAsciiOnly(text);
1042
+
1043
+ var grapheme_list: std.ArrayListUnmanaged(utf8.GraphemeInfo) = .{};
1044
+ defer grapheme_list.deinit(self.allocator);
1045
+
1046
+ const tab_width: u8 = 2;
1047
+ try utf8.findGraphemeInfo(self.allocator, text, tab_width, is_ascii_only, self.width_method, &grapheme_list);
1048
+ const specials = grapheme_list.items;
1049
+
1050
+ var advance_cells: u32 = 0;
1051
+ var byte_offset: u32 = 0;
1052
+ var col: u32 = 0;
1053
+ var special_idx: usize = 0;
1054
+
1055
+ while (byte_offset < text.len) {
1056
+ const charX = x + advance_cells;
1057
+ if (charX >= self.width) break;
1058
+
1059
+ const at_special = special_idx < specials.len and specials[special_idx].col_offset == col;
1060
+
1061
+ var grapheme_bytes: []const u8 = undefined;
1062
+ var g_width: u8 = undefined;
1063
+
1064
+ if (at_special) {
1065
+ const g = specials[special_idx];
1066
+ grapheme_bytes = text[g.byte_offset .. g.byte_offset + g.byte_len];
1067
+ g_width = g.width;
1068
+ byte_offset = g.byte_offset + g.byte_len;
1069
+ special_idx += 1;
1070
+ } else {
1071
+ if (byte_offset >= text.len) break;
1072
+ grapheme_bytes = text[byte_offset .. byte_offset + 1];
1073
+ g_width = 1;
1074
+ byte_offset += 1;
1075
+ }
1076
+
1077
+ if (!self.isPointInScissor(@intCast(charX), @intCast(y))) {
1078
+ advance_cells += g_width;
1079
+ col += g_width;
1080
+ continue;
1081
+ }
1082
+
1083
+ var bgColor: RGBA = undefined;
1084
+ if (bg) |b| {
1085
+ bgColor = b;
1086
+ } else if (self.get(charX, y)) |existingCell| {
1087
+ bgColor = existingCell.bg;
1088
+ } else {
1089
+ bgColor = ansi.rgbColor(0, 0, 0, 255);
1090
+ }
1091
+
1092
+ const cell_width = utf8.getWidthAt(text, if (at_special) specials[special_idx - 1].byte_offset else byte_offset - 1, tab_width, self.width_method);
1093
+ if (cell_width == 0) {
1094
+ col += g_width;
1095
+ continue;
1096
+ }
1097
+
1098
+ if (grapheme_bytes.len == 1 and grapheme_bytes[0] == '\t') {
1099
+ var tab_col: u32 = 0;
1100
+ while (tab_col < g_width) : (tab_col += 1) {
1101
+ const tab_x = charX + tab_col;
1102
+ if (tab_x >= self.width) break;
1103
+
1104
+ if (isRGBAWithAlpha(bgColor)) {
1105
+ self.setCellWithAlphaBlendingCell(
1106
+ tab_x,
1107
+ y,
1108
+ makeCell(DEFAULT_SPACE_CHAR, fg, bgColor, attributes),
1109
+ );
1110
+ } else {
1111
+ self.set(tab_x, y, makeCell(DEFAULT_SPACE_CHAR, fg, bgColor, attributes));
1112
+ }
1113
+ }
1114
+ advance_cells += g_width;
1115
+ col += g_width;
1116
+ continue;
1117
+ }
1118
+
1119
+ var encoded_char: u32 = 0;
1120
+ if (grapheme_bytes.len == 1 and cell_width == 1 and grapheme_bytes[0] >= 32) {
1121
+ encoded_char = @as(u32, grapheme_bytes[0]);
1122
+ } else {
1123
+ const gid = self.pool.alloc(grapheme_bytes) catch return BufferError.OutOfMemory;
1124
+ encoded_char = gp.packGraphemeStart(gid & gp.GRAPHEME_ID_MASK, cell_width);
1125
+ }
1126
+
1127
+ if (isRGBAWithAlpha(bgColor)) {
1128
+ self.setCellWithAlphaBlendingCell(
1129
+ charX,
1130
+ y,
1131
+ makeCell(encoded_char, fg, bgColor, attributes),
1132
+ );
1133
+ } else {
1134
+ self.set(charX, y, makeCell(encoded_char, fg, bgColor, attributes));
1135
+ }
1136
+
1137
+ advance_cells += cell_width;
1138
+ col += g_width;
1139
+ }
1140
+ }
1141
+
1142
+ pub fn drawFrameBuffer(self: *OptimizedBuffer, destX: i32, destY: i32, frameBuffer: *OptimizedBuffer, sourceX: ?u32, sourceY: ?u32, sourceWidth: ?u32, sourceHeight: ?u32) void {
1143
+ if (self.width == 0 or self.height == 0 or frameBuffer.width == 0 or frameBuffer.height == 0) return;
1144
+
1145
+ const opacity = self.getCurrentOpacity();
1146
+ if (opacity == 0.0) return;
1147
+
1148
+ const srcX = sourceX orelse 0;
1149
+ const srcY = sourceY orelse 0;
1150
+ const srcWidth = sourceWidth orelse frameBuffer.width;
1151
+ const srcHeight = sourceHeight orelse frameBuffer.height;
1152
+
1153
+ if (srcX >= frameBuffer.width or srcY >= frameBuffer.height) return;
1154
+ if (srcWidth == 0 or srcHeight == 0) return;
1155
+
1156
+ const clampedSrcWidth = @min(srcWidth, frameBuffer.width - srcX);
1157
+ const clampedSrcHeight = @min(srcHeight, frameBuffer.height - srcY);
1158
+
1159
+ const startDestX = @max(0, destX);
1160
+ const startDestY = @max(0, destY);
1161
+ const endDestX = @min(@as(i32, @intCast(self.width)) - 1, destX + @as(i32, @intCast(clampedSrcWidth)) - 1);
1162
+ const endDestY = @min(@as(i32, @intCast(self.height)) - 1, destY + @as(i32, @intCast(clampedSrcHeight)) - 1);
1163
+
1164
+ if (startDestX > endDestX or startDestY > endDestY) return;
1165
+
1166
+ // Check if the destination rectangle intersects with the scissor rect
1167
+ const destWidth = @as(u32, @intCast(endDestX - startDestX + 1));
1168
+ const destHeight = @as(u32, @intCast(endDestY - startDestY + 1));
1169
+ if (!self.isRectInScissor(startDestX, startDestY, destWidth, destHeight)) return;
1170
+
1171
+ const graphemeAware = self.grapheme_tracker.hasAny() or frameBuffer.grapheme_tracker.hasAny();
1172
+ const linkAware = self.link_tracker.hasAny() or frameBuffer.link_tracker.hasAny();
1173
+
1174
+ // Calculate clipping once for both paths
1175
+ const clippedRect = self.clipRectToScissor(startDestX, startDestY, destWidth, destHeight) orelse return;
1176
+ const clippedStartX = @max(startDestX, clippedRect.x);
1177
+ const clippedStartY = @max(startDestY, clippedRect.y);
1178
+ const clippedEndX = @min(endDestX, @as(i32, @intCast(clippedRect.x + @as(i32, @intCast(clippedRect.width)) - 1)));
1179
+ const clippedEndY = @min(endDestY, @as(i32, @intCast(clippedRect.y + @as(i32, @intCast(clippedRect.height)) - 1)));
1180
+
1181
+ if (!graphemeAware and !frameBuffer.respectAlpha and !linkAware) {
1182
+ // Fast path: direct memory copy
1183
+ var dY = clippedStartY;
1184
+
1185
+ while (dY <= clippedEndY) : (dY += 1) {
1186
+ const relativeDestY = dY - destY;
1187
+ const sY = srcY + @as(u32, @intCast(relativeDestY));
1188
+
1189
+ if (sY >= frameBuffer.height) continue;
1190
+
1191
+ const relativeDestX = clippedStartX - destX;
1192
+ const sX = srcX + @as(u32, @intCast(relativeDestX));
1193
+
1194
+ if (sX >= frameBuffer.width) continue;
1195
+
1196
+ const destRowStart = self.coordsToIndex(@intCast(clippedStartX), @intCast(dY));
1197
+ const srcRowStart = frameBuffer.coordsToIndex(sX, sY);
1198
+ const actualCopyWidth = @min(@as(u32, @intCast(clippedEndX - clippedStartX + 1)), frameBuffer.width - sX);
1199
+
1200
+ @memcpy(self.buffer.char[destRowStart .. destRowStart + actualCopyWidth], frameBuffer.buffer.char[srcRowStart .. srcRowStart + actualCopyWidth]);
1201
+ @memcpy(self.buffer.fg[destRowStart .. destRowStart + actualCopyWidth], frameBuffer.buffer.fg[srcRowStart .. srcRowStart + actualCopyWidth]);
1202
+ @memcpy(self.buffer.bg[destRowStart .. destRowStart + actualCopyWidth], frameBuffer.buffer.bg[srcRowStart .. srcRowStart + actualCopyWidth]);
1203
+ @memcpy(self.buffer.attributes[destRowStart .. destRowStart + actualCopyWidth], frameBuffer.buffer.attributes[srcRowStart .. srcRowStart + actualCopyWidth]);
1204
+ }
1205
+ return;
1206
+ }
1207
+
1208
+ var dY = clippedStartY;
1209
+ while (dY <= clippedEndY) : (dY += 1) {
1210
+ var lastDrawnGraphemeId: u32 = 0;
1211
+
1212
+ var dX = clippedStartX;
1213
+ while (dX <= clippedEndX) : (dX += 1) {
1214
+ const relativeDestX = dX - destX;
1215
+ const relativeDestY = dY - destY;
1216
+ const sX = srcX + @as(u32, @intCast(relativeDestX));
1217
+ const sY = srcY + @as(u32, @intCast(relativeDestY));
1218
+
1219
+ if (sX >= frameBuffer.width or sY >= frameBuffer.height) continue;
1220
+
1221
+ const srcIndex = frameBuffer.coordsToIndex(sX, sY);
1222
+ if (srcIndex >= frameBuffer.buffer.char.len) continue;
1223
+
1224
+ const srcChar = frameBuffer.buffer.char[srcIndex];
1225
+ const srcFg = frameBuffer.buffer.fg[srcIndex];
1226
+ const srcBg = frameBuffer.buffer.bg[srcIndex];
1227
+ const srcAttr = frameBuffer.buffer.attributes[srcIndex];
1228
+
1229
+ if (ansi.alpha(srcBg) == 0 and ansi.alpha(srcFg) == 0) continue;
1230
+
1231
+ if (graphemeAware) {
1232
+ if (gp.isContinuationChar(srcChar)) {
1233
+ const graphemeId = srcChar & gp.GRAPHEME_ID_MASK;
1234
+ if (graphemeId != lastDrawnGraphemeId) {
1235
+ // We haven't drawn the start character for this grapheme (likely out of bounds to the left)
1236
+ // Draw a space with the same attributes to fill the cell
1237
+ self.setCellWithAlphaBlendingCell(
1238
+ @intCast(dX),
1239
+ @intCast(dY),
1240
+ makeCell(DEFAULT_SPACE_CHAR, srcFg, srcBg, srcAttr),
1241
+ );
1242
+ }
1243
+ continue;
1244
+ }
1245
+
1246
+ if (gp.isGraphemeChar(srcChar)) {
1247
+ lastDrawnGraphemeId = srcChar & gp.GRAPHEME_ID_MASK;
1248
+ }
1249
+
1250
+ self.setCellWithAlphaBlendingCell(
1251
+ @intCast(dX),
1252
+ @intCast(dY),
1253
+ makeCell(srcChar, srcFg, srcBg, srcAttr),
1254
+ );
1255
+ continue;
1256
+ }
1257
+
1258
+ self.setCellWithAlphaBlendingRawCell(
1259
+ @intCast(dX),
1260
+ @intCast(dY),
1261
+ makeCell(srcChar, srcFg, srcBg, srcAttr),
1262
+ );
1263
+ }
1264
+ }
1265
+ }
1266
+
1267
+ /// Draw a TextBufferView to this OptimizedBuffer with selection support and optional syntax highlighting
1268
+ pub fn drawTextBuffer(
1269
+ self: *OptimizedBuffer,
1270
+ text_buffer_view: *TextBufferView,
1271
+ x: i32,
1272
+ y: i32,
1273
+ ) void {
1274
+ self.drawTextBufferInternal(TextBufferView, text_buffer_view, x, y);
1275
+ }
1276
+
1277
+ /// Internal implementation that accepts either TextBufferView or EditorView
1278
+ /// Both types must expose: getVirtualLines(), getViewport(), getCachedLineInfo(), getVirtualLineSpans(), getTextBuffer(), getSelection()
1279
+ fn drawTextBufferInternal(
1280
+ self: *OptimizedBuffer,
1281
+ comptime ViewType: type,
1282
+ view: *ViewType,
1283
+ x: i32,
1284
+ y: i32,
1285
+ ) void {
1286
+ const opacity = self.getCurrentOpacity();
1287
+ if (opacity == 0.0) return;
1288
+
1289
+ const virtual_lines = view.getVirtualLines();
1290
+ const viewport = view.getViewport();
1291
+ const text_buffer = view.getTextBuffer();
1292
+ const text_defaults = text_buffer.defaults();
1293
+ const PrefilledViewportBg = struct {
1294
+ bg: RGBA,
1295
+ };
1296
+
1297
+ const prefilledViewportBg: ?PrefilledViewportBg = blk: {
1298
+ if (comptime ViewType != EditorView) break :blk null;
1299
+ const vp = viewport orelse break :blk null;
1300
+ const base_defaults = view.edit_buffer.getTextBuffer().defaults();
1301
+ const default_bg = base_defaults.bg orelse break :blk null;
1302
+ if (ansi.alpha(default_bg) == 0) break :blk null;
1303
+ self.fillRectClipped(x, y, vp.width, vp.height, default_bg);
1304
+ break :blk .{ .bg = default_bg };
1305
+ };
1306
+
1307
+ if (virtual_lines.len == 0) return;
1308
+
1309
+ const firstVisibleLine: u32 = if (y < 0) @intCast(-y) else 0;
1310
+ const bufferBottomY = self.height;
1311
+ const lastPossibleLine = if (y >= @as(i32, @intCast(bufferBottomY)))
1312
+ 0
1313
+ else if (y < 0)
1314
+ @min(virtual_lines.len, firstVisibleLine + bufferBottomY)
1315
+ else
1316
+ @min(virtual_lines.len, bufferBottomY - @as(u32, @intCast(y)));
1317
+
1318
+ if (firstVisibleLine >= virtual_lines.len or lastPossibleLine == 0) return;
1319
+ if (firstVisibleLine >= lastPossibleLine) return;
1320
+
1321
+ const horizontal_offset: u32 = if (viewport) |vp| vp.x else 0;
1322
+ const viewport_width: u32 = if (viewport) |vp| vp.width else std.math.maxInt(u32);
1323
+
1324
+ var currentX = x;
1325
+ var currentY = y + @as(i32, @intCast(firstVisibleLine));
1326
+ const total_line_count = text_buffer.lineCount();
1327
+
1328
+ const line_info = view.getCachedLineInfo();
1329
+ var globalCharPos: u32 = if (firstVisibleLine < line_info.line_start_cols.len)
1330
+ line_info.line_start_cols[firstVisibleLine]
1331
+ else
1332
+ 0;
1333
+
1334
+ for (virtual_lines[firstVisibleLine..lastPossibleLine], 0..) |vline, slice_idx| {
1335
+ if (currentY >= bufferBottomY) break;
1336
+
1337
+ currentX = x;
1338
+ var column_in_line: u32 = 0;
1339
+ globalCharPos = vline.col_offset;
1340
+
1341
+ // When viewport is set, virtual_lines is a slice starting from viewport.y
1342
+ // But getVirtualLineSpans expects absolute indices, so we need to use the absolute index
1343
+ // slice_idx is relative to the slice (0, 1, 2...), we need to add viewport offset + firstVisibleLine
1344
+ const viewport_offset: u32 = if (viewport) |vp| vp.y else 0;
1345
+ const vline_idx = viewport_offset + firstVisibleLine + slice_idx;
1346
+ const vline_span_info = view.getVirtualLineSpans(vline_idx);
1347
+ const spans = vline_span_info.spans;
1348
+ const col_offset = vline_span_info.col_offset;
1349
+ var span_idx: usize = 0;
1350
+ var lineFg = text_defaults.fg orelse ansi.rgbColor(255, 255, 255, 255);
1351
+ var lineBg = text_defaults.bg orelse ansi.rgbColor(0, 0, 0, 0);
1352
+ var lineAttributes = text_defaults.attributes orelse 0;
1353
+ const defaultFg = lineFg;
1354
+ const defaultBg = lineBg;
1355
+ const defaultAttributes = lineAttributes;
1356
+
1357
+ // Find the span that contains the starting render position (col_offset + horizontal_offset)
1358
+ const start_col = col_offset + horizontal_offset;
1359
+ while (span_idx < spans.len and spans[span_idx].next_col <= start_col) {
1360
+ span_idx += 1;
1361
+ }
1362
+
1363
+ var next_change_col: u32 = if (span_idx < spans.len)
1364
+ spans[span_idx].next_col
1365
+ else
1366
+ std.math.maxInt(u32);
1367
+
1368
+ // Apply the style at the starting position
1369
+ if (span_idx < spans.len and spans[span_idx].col <= start_col and spans[span_idx].style_id != 0) {
1370
+ if (text_buffer.getSyntaxStyle()) |style| {
1371
+ if (style.resolveById(spans[span_idx].style_id)) |resolved_style| {
1372
+ if (resolved_style.fg) |fg| {
1373
+ lineFg = fg;
1374
+ }
1375
+ if (resolved_style.bg) |bg| {
1376
+ lineBg = bg;
1377
+ }
1378
+ lineAttributes |= resolved_style.attributes;
1379
+ }
1380
+ }
1381
+ }
1382
+
1383
+ for (vline.chunks.items) |vchunk| {
1384
+ const chunk = vchunk.chunk;
1385
+ const chunk_bytes = chunk.getBytes(text_buffer.memRegistry());
1386
+ const specials = chunk.getGraphemes(text_buffer.getAllocator(), text_buffer.memRegistry(), text_buffer.tabWidth(), text_buffer.widthMethod()) catch continue;
1387
+ const line_col_offset = vline.col_offset;
1388
+
1389
+ if (currentX >= @as(i32, @intCast(self.width))) {
1390
+ globalCharPos += vchunk.width;
1391
+ currentX += @intCast(vchunk.width);
1392
+ continue;
1393
+ }
1394
+ const col_end = vchunk.grapheme_start + vchunk.width;
1395
+ var col = vchunk.grapheme_start;
1396
+ var special_idx: usize = 0;
1397
+ var byte_offset: u32 = 0;
1398
+
1399
+ if (vchunk.grapheme_start > 0) {
1400
+ // Use UTF-8 aware position finding to skip to the grapheme_start
1401
+ const is_ascii_only = (vchunk.chunk.flags & tb.TextChunk.Flags.ASCII_ONLY) != 0;
1402
+ const pos_result = utf8.findPosByWidth(chunk_bytes, vchunk.grapheme_start, text_buffer.tabWidth(), is_ascii_only, false, text_buffer.widthMethod());
1403
+ byte_offset = pos_result.byte_offset;
1404
+
1405
+ // Advance special_idx to match the skipped columns
1406
+ var init_col: u32 = 0;
1407
+ while (init_col < vchunk.grapheme_start and special_idx < specials.len) {
1408
+ const g = specials[special_idx];
1409
+ if (g.col_offset < vchunk.grapheme_start) {
1410
+ special_idx += 1;
1411
+ init_col = g.col_offset + g.width;
1412
+ } else {
1413
+ break;
1414
+ }
1415
+ }
1416
+ }
1417
+
1418
+ while (col < col_end) {
1419
+ const at_special = special_idx < specials.len and specials[special_idx].col_offset == col;
1420
+
1421
+ var grapheme_bytes: []const u8 = undefined;
1422
+ var g_width: u8 = undefined;
1423
+
1424
+ if (at_special) {
1425
+ const g = specials[special_idx];
1426
+ grapheme_bytes = chunk_bytes[g.byte_offset .. g.byte_offset + g.byte_len];
1427
+ g_width = g.width;
1428
+ byte_offset = g.byte_offset + g.byte_len;
1429
+ special_idx += 1;
1430
+ } else {
1431
+ if (byte_offset >= chunk_bytes.len) break;
1432
+ const cp_len = std.unicode.utf8ByteSequenceLength(chunk_bytes[byte_offset]) catch 1;
1433
+ const next_byte_offset = @min(byte_offset + cp_len, chunk_bytes.len);
1434
+ grapheme_bytes = chunk_bytes[byte_offset..next_byte_offset];
1435
+ g_width = 1;
1436
+ byte_offset = next_byte_offset;
1437
+ }
1438
+
1439
+ if (column_in_line < horizontal_offset) {
1440
+ globalCharPos += g_width;
1441
+ column_in_line += g_width;
1442
+ col += g_width;
1443
+ continue;
1444
+ }
1445
+
1446
+ if (column_in_line >= horizontal_offset + viewport_width) {
1447
+ globalCharPos += (col_end - col);
1448
+ break;
1449
+ }
1450
+
1451
+ if (currentX < -@as(i32, @intCast(g_width))) {
1452
+ globalCharPos += g_width;
1453
+ currentX += @as(i32, @intCast(g_width));
1454
+ column_in_line += g_width;
1455
+ col += g_width;
1456
+ continue;
1457
+ }
1458
+
1459
+ if (currentX >= @as(i32, @intCast(self.width))) {
1460
+ globalCharPos += (col_end - col);
1461
+ break;
1462
+ }
1463
+
1464
+ if (!self.isPointInScissor(currentX, currentY)) {
1465
+ globalCharPos += g_width;
1466
+ currentX += @as(i32, @intCast(g_width));
1467
+ column_in_line += g_width;
1468
+ col += g_width;
1469
+ continue;
1470
+ }
1471
+
1472
+ var selection_offset = globalCharPos;
1473
+ if (vline.is_truncated and globalCharPos >= line_col_offset) {
1474
+ const ellipsis_width: u32 = 3;
1475
+ const column_offset_in_line = globalCharPos - line_col_offset;
1476
+ if (column_offset_in_line >= vline.ellipsis_pos and column_offset_in_line < vline.ellipsis_pos + ellipsis_width) {
1477
+ selection_offset = line_col_offset + vline.ellipsis_pos;
1478
+ } else if (column_offset_in_line >= vline.ellipsis_pos + ellipsis_width) {
1479
+ selection_offset = line_col_offset + vline.truncation_suffix_start +
1480
+ (column_offset_in_line - vline.ellipsis_pos - ellipsis_width);
1481
+ } else {
1482
+ selection_offset = line_col_offset + column_offset_in_line;
1483
+ }
1484
+ }
1485
+
1486
+ // Track the actual column position in the source line (including horizontal offset)
1487
+ var source_col_pos = col_offset + column_in_line;
1488
+ if (vline.is_truncated) {
1489
+ const ellipsis_width: u32 = 3;
1490
+ const column_offset_in_line = globalCharPos - line_col_offset;
1491
+ if (column_offset_in_line >= vline.ellipsis_pos and column_offset_in_line < vline.ellipsis_pos + ellipsis_width) {
1492
+ source_col_pos = std.math.maxInt(u32);
1493
+ } else if (column_offset_in_line >= vline.ellipsis_pos + ellipsis_width) {
1494
+ source_col_pos = vline.truncation_suffix_start + (column_offset_in_line - vline.ellipsis_pos - ellipsis_width);
1495
+ }
1496
+ }
1497
+
1498
+ if (source_col_pos >= next_change_col and span_idx + 1 < spans.len) {
1499
+ span_idx += 1;
1500
+ const new_span = spans[span_idx];
1501
+
1502
+ lineFg = defaultFg;
1503
+ lineBg = defaultBg;
1504
+ lineAttributes = defaultAttributes;
1505
+
1506
+ if (text_buffer.getSyntaxStyle()) |style| {
1507
+ if (new_span.style_id != 0) {
1508
+ if (style.resolveById(new_span.style_id)) |resolved_style| {
1509
+ if (resolved_style.fg) |fg| {
1510
+ lineFg = fg;
1511
+ }
1512
+ if (resolved_style.bg) |bg| {
1513
+ lineBg = bg;
1514
+ }
1515
+ lineAttributes |= resolved_style.attributes;
1516
+ }
1517
+ }
1518
+ }
1519
+
1520
+ next_change_col = new_span.next_col;
1521
+ }
1522
+
1523
+ if (vline.is_truncated) {
1524
+ const column_offset_in_line = globalCharPos - line_col_offset;
1525
+ const ellipsis_width: u32 = 3;
1526
+ if (column_offset_in_line >= vline.ellipsis_pos and column_offset_in_line < vline.ellipsis_pos + ellipsis_width) {
1527
+ lineFg = defaultFg;
1528
+ lineBg = defaultBg;
1529
+ lineAttributes = defaultAttributes;
1530
+ } else if (column_offset_in_line >= vline.ellipsis_pos + ellipsis_width) {
1531
+ const suffix_col_pos = vline.truncation_suffix_start + (column_offset_in_line - vline.ellipsis_pos - ellipsis_width);
1532
+ if (spans.len == 0) {
1533
+ lineFg = defaultFg;
1534
+ lineBg = defaultBg;
1535
+ lineAttributes = defaultAttributes;
1536
+ next_change_col = std.math.maxInt(u32);
1537
+ } else {
1538
+ var suffix_span_idx: usize = 0;
1539
+ while (suffix_span_idx < spans.len and spans[suffix_span_idx].next_col <= suffix_col_pos) {
1540
+ suffix_span_idx += 1;
1541
+ }
1542
+ if (suffix_span_idx < spans.len) {
1543
+ span_idx = suffix_span_idx;
1544
+ }
1545
+ const active_span = spans[span_idx];
1546
+ lineFg = defaultFg;
1547
+ lineBg = defaultBg;
1548
+ lineAttributes = defaultAttributes;
1549
+ if (text_buffer.getSyntaxStyle()) |style| {
1550
+ if (active_span.style_id != 0) {
1551
+ if (style.resolveById(active_span.style_id)) |resolved_style| {
1552
+ if (resolved_style.fg) |fg| {
1553
+ lineFg = fg;
1554
+ }
1555
+ if (resolved_style.bg) |bg| {
1556
+ lineBg = bg;
1557
+ }
1558
+ lineAttributes |= resolved_style.attributes;
1559
+ }
1560
+ }
1561
+ }
1562
+ next_change_col = active_span.next_col;
1563
+ }
1564
+ }
1565
+ }
1566
+
1567
+ var finalFg = lineFg;
1568
+ var finalBg = lineBg;
1569
+ const finalAttributes = lineAttributes;
1570
+
1571
+ var cell_idx: u32 = 0;
1572
+ while (cell_idx < g_width) : (cell_idx += 1) {
1573
+ if (view.getSelection()) |sel| {
1574
+ const isSelected = selection_offset + cell_idx >= sel.start and selection_offset + cell_idx < sel.end;
1575
+ if (isSelected) {
1576
+ if (sel.bgColor) |selBg| {
1577
+ finalBg = selBg;
1578
+ if (sel.fgColor) |selFg| {
1579
+ finalFg = selFg;
1580
+ }
1581
+ } else {
1582
+ const temp = lineFg;
1583
+ finalFg = if (ansi.alpha(lineBg) > 0) lineBg else ansi.rgbColor(0, 0, 0, 255);
1584
+ finalBg = temp;
1585
+ }
1586
+ break;
1587
+ }
1588
+ }
1589
+ }
1590
+
1591
+ // Skip zero-width characters (ZWJ, VS16, etc.) - don't render them
1592
+ // Don't increment col since they take no space
1593
+ if (g_width == 0) {
1594
+ continue;
1595
+ }
1596
+
1597
+ var drawFg = finalFg;
1598
+ var drawBg = finalBg;
1599
+ const drawAttributes = finalAttributes;
1600
+
1601
+ if (drawAttributes & (1 << 5) != 0) {
1602
+ const temp = drawFg;
1603
+ drawFg = drawBg;
1604
+ drawBg = temp;
1605
+ }
1606
+
1607
+ if (prefilledViewportBg) |prefilledBg| {
1608
+ if (rgbaEqual(drawBg, prefilledBg.bg)) {
1609
+ drawBg[3] = drawBg[3] & 0xff00;
1610
+ }
1611
+ }
1612
+
1613
+ // TextBuffer/Textarea typically render opaque glyphs onto a
1614
+ // transparent bg. Reuse the direct transparent-text write
1615
+ // path instead of paying for generic per-cell blending.
1616
+ const useTransparentTextFastPath = self.getCurrentOpacity() == 1.0 and ansi.alpha(drawBg) == 0;
1617
+
1618
+ if (grapheme_bytes.len == 1 and grapheme_bytes[0] == '\t') {
1619
+ const tab_indicator = view.getTabIndicator();
1620
+ const tab_indicator_color = view.getTabIndicatorColor();
1621
+
1622
+ var tab_col: u32 = 0;
1623
+ while (tab_col < g_width) : (tab_col += 1) {
1624
+ if (currentX + @as(i32, @intCast(tab_col)) >= @as(i32, @intCast(self.width))) break;
1625
+
1626
+ const char = if (tab_col == 0 and tab_indicator != null) tab_indicator.? else DEFAULT_SPACE_CHAR;
1627
+ const fg = if (tab_col == 0 and tab_indicator_color != null) tab_indicator_color.? else drawFg;
1628
+
1629
+ if (useTransparentTextFastPath) {
1630
+ const index = self.coordsToIndex(@intCast(currentX + @as(i32, @intCast(tab_col))), @intCast(currentY));
1631
+ if (self.trySetTransparentTextCellFast(index, char, fg, drawAttributes)) {
1632
+ continue;
1633
+ }
1634
+ }
1635
+
1636
+ self.setCellWithAlphaBlendingCell(
1637
+ @intCast(currentX + @as(i32, @intCast(tab_col))),
1638
+ @intCast(currentY),
1639
+ makeCell(char, fg, drawBg, drawAttributes),
1640
+ );
1641
+ }
1642
+ } else {
1643
+ var encoded_char: u32 = 0;
1644
+ if (grapheme_bytes.len == 1 and g_width == 1 and grapheme_bytes[0] >= 32) {
1645
+ encoded_char = @as(u32, grapheme_bytes[0]);
1646
+ } else {
1647
+ const gid = self.pool.alloc(grapheme_bytes) catch |err| {
1648
+ logger.warn("GraphemePool.alloc FAILED for grapheme (len={d}, bytes={any}): {}", .{ grapheme_bytes.len, grapheme_bytes, err });
1649
+ globalCharPos += g_width;
1650
+ currentX += @as(i32, @intCast(g_width));
1651
+ col += g_width;
1652
+ continue;
1653
+ };
1654
+ encoded_char = gp.packGraphemeStart(gid & gp.GRAPHEME_ID_MASK, g_width);
1655
+ }
1656
+
1657
+ if (useTransparentTextFastPath) {
1658
+ const index = self.coordsToIndex(@intCast(currentX), @intCast(currentY));
1659
+ if (self.trySetTransparentTextCellFast(index, encoded_char, drawFg, drawAttributes)) {
1660
+ globalCharPos += g_width;
1661
+ currentX += @as(i32, @intCast(g_width));
1662
+ column_in_line += g_width;
1663
+ col += g_width;
1664
+ continue;
1665
+ }
1666
+ }
1667
+
1668
+ self.setCellWithAlphaBlendingCell(
1669
+ @intCast(currentX),
1670
+ @intCast(currentY),
1671
+ makeCell(encoded_char, drawFg, drawBg, drawAttributes),
1672
+ );
1673
+ }
1674
+
1675
+ globalCharPos += g_width;
1676
+ currentX += @as(i32, @intCast(g_width));
1677
+ column_in_line += g_width;
1678
+ col += g_width;
1679
+ }
1680
+ }
1681
+
1682
+ const is_last_vline_of_logical_line = (slice_idx + 1 >= virtual_lines[firstVisibleLine..lastPossibleLine].len) or
1683
+ (virtual_lines[firstVisibleLine..lastPossibleLine][slice_idx + 1].source_line != vline.source_line);
1684
+
1685
+ if (is_last_vline_of_logical_line) {
1686
+ const is_last_logical_line = vline.source_line + 1 >= total_line_count;
1687
+ if (!is_last_logical_line) {
1688
+ globalCharPos += 1;
1689
+ }
1690
+ }
1691
+
1692
+ currentY += 1;
1693
+ }
1694
+ }
1695
+
1696
+ /// Draw an EditorView to this OptimizedBuffer
1697
+ /// EditorView wraps TextBufferView, so we just delegate to drawTextBufferInternal
1698
+ /// EditorView handles viewport management and returns only the visible lines
1699
+ pub fn drawEditorView(
1700
+ self: *OptimizedBuffer,
1701
+ editor_view: *EditorView,
1702
+ x: i32,
1703
+ y: i32,
1704
+ ) void {
1705
+ self.drawTextBufferInternal(EditorView, editor_view, x, y);
1706
+ }
1707
+
1708
+ /// Draw a complete border grid in a single call.
1709
+ /// columnOffsets and rowOffsets include an extra trailing entry so that
1710
+ /// the range for column `i` is `[columnOffsets[i]+1 .. columnOffsets[i+1]-1]`.
1711
+ pub fn drawGrid(
1712
+ self: *OptimizedBuffer,
1713
+ borderChars: [*]const u32,
1714
+ borderFg: RGBA,
1715
+ borderBg: RGBA,
1716
+ columnOffsets: [*]const i32,
1717
+ columnCount: u32,
1718
+ rowOffsets: [*]const i32,
1719
+ rowCount: u32,
1720
+ drawInner: bool,
1721
+ drawOuter: bool,
1722
+ ) void {
1723
+ if (rowCount == 0 or columnCount == 0) return;
1724
+ if (!drawInner and !drawOuter) return;
1725
+
1726
+ const opacity = self.getCurrentOpacity();
1727
+ if (isFullyTransparent(opacity, borderFg, borderBg)) return;
1728
+
1729
+ const hChar = borderChars[@intFromEnum(BorderCharIndex.horizontal)];
1730
+ const vChar = borderChars[@intFromEnum(BorderCharIndex.vertical)];
1731
+ const bufWidth = self.width;
1732
+ const bufHeight = self.height;
1733
+ const bufWidthI32 = @as(i32, @intCast(bufWidth));
1734
+ const bufHeightI32 = @as(i32, @intCast(bufHeight));
1735
+
1736
+ // Draw row-by-row: horizontal border line, then vertical borders for the row's content area
1737
+ var rowIdx: u32 = 0;
1738
+ while (rowIdx <= rowCount) : (rowIdx += 1) {
1739
+ const is_outer_row = rowIdx == 0 or rowIdx == rowCount;
1740
+ const should_draw_horizontal = if (is_outer_row) drawOuter else drawInner;
1741
+ const borderY = rowOffsets[rowIdx];
1742
+ if (borderY >= bufHeightI32) break;
1743
+
1744
+ // --- horizontal border line: intersections + fills ---
1745
+ if (should_draw_horizontal and borderY >= 0) {
1746
+ var colBorderIdx: u32 = 0;
1747
+ while (colBorderIdx <= columnCount) : (colBorderIdx += 1) {
1748
+ const is_outer_col = colBorderIdx == 0 or colBorderIdx == columnCount;
1749
+ const should_draw_vertical = if (is_outer_col) drawOuter else drawInner;
1750
+ if (!should_draw_vertical) continue;
1751
+
1752
+ const bx = columnOffsets[colBorderIdx];
1753
+ if (bx >= bufWidthI32) break;
1754
+ if (bx < 0) continue;
1755
+
1756
+ const has_up = rowIdx > 0 and should_draw_vertical;
1757
+ const has_down = rowIdx < rowCount and should_draw_vertical;
1758
+ const has_left = colBorderIdx > 0;
1759
+ const has_right = colBorderIdx < columnCount;
1760
+ const intersection = tableBorderIntersectionByConnections(borderChars, has_up, has_down, has_left, has_right);
1761
+
1762
+ self.setRaw(@as(u32, @intCast(bx)), @as(u32, @intCast(borderY)), .{ .char = intersection, .fg = borderFg, .bg = borderBg, .attributes = 0 });
1763
+ }
1764
+
1765
+ var colIdx: u32 = 0;
1766
+ while (colIdx < columnCount) : (colIdx += 1) {
1767
+ const has_boundary_after = if (colIdx < columnCount - 1) drawInner else drawOuter;
1768
+ const boundary_padding: i32 = if (has_boundary_after) 0 else 1;
1769
+ const startX = columnOffsets[colIdx] + 1;
1770
+ const endX = columnOffsets[colIdx + 1] + boundary_padding;
1771
+
1772
+ if (startX >= bufWidthI32) break;
1773
+ if (endX <= 0) continue;
1774
+
1775
+ const clampedStart = @as(u32, @intCast(@max(@as(i32, 0), startX)));
1776
+ const clampedEnd = @as(u32, @intCast(@min(bufWidthI32, endX)));
1777
+
1778
+ if (clampedStart < clampedEnd) {
1779
+ const borderYU32 = @as(u32, @intCast(borderY));
1780
+ @memset(self.buffer.char[borderYU32 * bufWidth + clampedStart .. borderYU32 * bufWidth + clampedEnd], hChar);
1781
+ @memset(self.buffer.fg[borderYU32 * bufWidth + clampedStart .. borderYU32 * bufWidth + clampedEnd], borderFg);
1782
+ @memset(self.buffer.bg[borderYU32 * bufWidth + clampedStart .. borderYU32 * bufWidth + clampedEnd], borderBg);
1783
+ @memset(self.buffer.attributes[borderYU32 * bufWidth + clampedStart .. borderYU32 * bufWidth + clampedEnd], 0);
1784
+ }
1785
+ }
1786
+ }
1787
+
1788
+ if (rowIdx >= rowCount) break;
1789
+
1790
+ // --- vertical borders for each content line in this row ---
1791
+ const has_row_boundary_after = if (rowIdx < rowCount - 1) drawInner else drawOuter;
1792
+ const row_boundary_padding: i32 = if (has_row_boundary_after) 0 else 1;
1793
+ const contentStartY = borderY + 1;
1794
+ const contentEndY = rowOffsets[rowIdx + 1] + row_boundary_padding;
1795
+ var cy = contentStartY;
1796
+ while (cy < contentEndY and cy < bufHeightI32) : (cy += 1) {
1797
+ if (cy < 0) continue;
1798
+
1799
+ const rowBase = @as(u32, @intCast(cy)) * bufWidth;
1800
+ var colBorderIdx: u32 = 0;
1801
+ while (colBorderIdx <= columnCount) : (colBorderIdx += 1) {
1802
+ const is_outer_col = colBorderIdx == 0 or colBorderIdx == columnCount;
1803
+ const should_draw_vertical = if (is_outer_col) drawOuter else drawInner;
1804
+ if (!should_draw_vertical) continue;
1805
+
1806
+ const bx = columnOffsets[colBorderIdx];
1807
+ if (bx >= bufWidthI32) break;
1808
+ if (bx < 0) continue;
1809
+
1810
+ const idx = rowBase + @as(u32, @intCast(bx));
1811
+ self.buffer.char[idx] = vChar;
1812
+ self.buffer.fg[idx] = borderFg;
1813
+ self.buffer.bg[idx] = borderBg;
1814
+ self.buffer.attributes[idx] = 0;
1815
+ }
1816
+ }
1817
+ }
1818
+ }
1819
+
1820
+ fn tableBorderIntersectionByConnections(borderChars: [*]const u32, hasUp: bool, hasDown: bool, hasLeft: bool, hasRight: bool) u32 {
1821
+ if (hasUp and hasDown and hasLeft and hasRight) return borderChars[@intFromEnum(BorderCharIndex.cross)];
1822
+
1823
+ if (!hasUp and hasDown and !hasLeft and hasRight) return borderChars[@intFromEnum(BorderCharIndex.topLeft)];
1824
+ if (!hasUp and hasDown and hasLeft and !hasRight) return borderChars[@intFromEnum(BorderCharIndex.topRight)];
1825
+ if (hasUp and !hasDown and !hasLeft and hasRight) return borderChars[@intFromEnum(BorderCharIndex.bottomLeft)];
1826
+ if (hasUp and !hasDown and hasLeft and !hasRight) return borderChars[@intFromEnum(BorderCharIndex.bottomRight)];
1827
+
1828
+ if (hasUp and hasDown and !hasLeft and hasRight) return borderChars[@intFromEnum(BorderCharIndex.leftT)];
1829
+ if (hasUp and hasDown and hasLeft and !hasRight) return borderChars[@intFromEnum(BorderCharIndex.rightT)];
1830
+ if (!hasUp and hasDown and hasLeft and hasRight) return borderChars[@intFromEnum(BorderCharIndex.topT)];
1831
+ if (hasUp and !hasDown and hasLeft and hasRight) return borderChars[@intFromEnum(BorderCharIndex.bottomT)];
1832
+
1833
+ if ((hasLeft or hasRight) and !hasUp and !hasDown) return borderChars[@intFromEnum(BorderCharIndex.horizontal)];
1834
+ if ((hasUp or hasDown) and !hasLeft and !hasRight) return borderChars[@intFromEnum(BorderCharIndex.vertical)];
1835
+
1836
+ return borderChars[@intFromEnum(BorderCharIndex.cross)];
1837
+ }
1838
+
1839
+ inline fn isSingleWidthBorderChar(char: u32) bool {
1840
+ if (char == 0) return true;
1841
+ if (char > MAX_UNICODE_CODEPOINT) return false;
1842
+ return utf8.eastAsianWidth(@intCast(char)) == 1;
1843
+ }
1844
+
1845
+ inline fn canUseTransparentBorderFastPath(self: *const OptimizedBuffer, borderChars: [*]const u32, borderColor: RGBA, backgroundColor: RGBA) bool {
1846
+ // When border glyphs are width-1, opaque, and tracker-free, drawing them
1847
+ // over a transparent background is just a direct char/fg/attrs write
1848
+ // while keeping the destination background unchanged.
1849
+ return self.getCurrentOpacity() == 1.0 and
1850
+ ansi.alpha(borderColor) == 255 and
1851
+ ansi.alpha(backgroundColor) == 0 and
1852
+ !self.grapheme_tracker.hasAny() and
1853
+ !self.link_tracker.hasAny() and
1854
+ isSingleWidthBorderChar(borderChars[@intFromEnum(BorderCharIndex.topLeft)]) and
1855
+ isSingleWidthBorderChar(borderChars[@intFromEnum(BorderCharIndex.topRight)]) and
1856
+ isSingleWidthBorderChar(borderChars[@intFromEnum(BorderCharIndex.bottomLeft)]) and
1857
+ isSingleWidthBorderChar(borderChars[@intFromEnum(BorderCharIndex.bottomRight)]) and
1858
+ isSingleWidthBorderChar(borderChars[@intFromEnum(BorderCharIndex.horizontal)]) and
1859
+ isSingleWidthBorderChar(borderChars[@intFromEnum(BorderCharIndex.vertical)]);
1860
+ }
1861
+
1862
+ /// Draw a box with borders and optional fill
1863
+ pub fn drawBox(
1864
+ self: *OptimizedBuffer,
1865
+ x: i32,
1866
+ y: i32,
1867
+ width: u32,
1868
+ height: u32,
1869
+ borderChars: [*]const u32,
1870
+ borderSides: BorderSides,
1871
+ borderColor: RGBA,
1872
+ backgroundColor: RGBA,
1873
+ titleColor: RGBA,
1874
+ shouldFill: bool,
1875
+ title: ?[]const u8,
1876
+ titleAlignment: u8, // 0=left, 1=center, 2=right
1877
+ bottomTitle: ?[]const u8,
1878
+ bottomTitleAlignment: u8, // 0=left, 1=center, 2=right
1879
+ ) !void {
1880
+ const opacity = self.getCurrentOpacity();
1881
+
1882
+ const border_bg_transparent = isFullyTransparent(opacity, borderColor, backgroundColor);
1883
+ const has_title = title != null or bottomTitle != null;
1884
+ const title_visible = has_title and !isFullyTransparent(opacity, titleColor, backgroundColor);
1885
+
1886
+ if (border_bg_transparent and !title_visible) return;
1887
+
1888
+ const startX = @max(0, x);
1889
+ const startY = @max(0, y);
1890
+ const endX = @min(@as(i32, @intCast(self.width)) - 1, x + @as(i32, @intCast(width)) - 1);
1891
+ const endY = @min(@as(i32, @intCast(self.height)) - 1, y + @as(i32, @intCast(height)) - 1);
1892
+
1893
+ if (startX > endX or startY > endY) return;
1894
+
1895
+ const boxWidth = @as(u32, @intCast(endX - startX + 1));
1896
+ const boxHeight = @as(u32, @intCast(endY - startY + 1));
1897
+ if (!self.isRectInScissor(startX, startY, boxWidth, boxHeight)) return;
1898
+
1899
+ const isAtActualLeft = startX == x;
1900
+ const isAtActualRight = endX == x + @as(i32, @intCast(width)) - 1;
1901
+ const isAtActualTop = startY == y;
1902
+ const isAtActualBottom = endY == y + @as(i32, @intCast(height)) - 1;
1903
+
1904
+ const titleLayout = self.computeBoxTitleLayout(title, borderSides.top, isAtActualTop, startX, endX, width, titleAlignment);
1905
+ const bottomTitleLayout = self.computeBoxTitleLayout(bottomTitle, borderSides.bottom, isAtActualBottom, startX, endX, width, bottomTitleAlignment);
1906
+
1907
+ if (shouldFill) {
1908
+ if (!borderSides.top and !borderSides.right and !borderSides.bottom and !borderSides.left) {
1909
+ const fillWidth = @as(u32, @intCast(endX - startX + 1));
1910
+ const fillHeight = @as(u32, @intCast(endY - startY + 1));
1911
+ self.fillRect(@intCast(startX), @intCast(startY), fillWidth, fillHeight, backgroundColor);
1912
+ } else {
1913
+ const innerStartX = startX + if (borderSides.left and isAtActualLeft) @as(i32, 1) else @as(i32, 0);
1914
+ const innerStartY = startY + if (borderSides.top and isAtActualTop) @as(i32, 1) else @as(i32, 0);
1915
+ const innerEndX = endX - if (borderSides.right and isAtActualRight) @as(i32, 1) else @as(i32, 0);
1916
+ const innerEndY = endY - if (borderSides.bottom and isAtActualBottom) @as(i32, 1) else @as(i32, 0);
1917
+
1918
+ if (innerEndX >= innerStartX and innerEndY >= innerStartY) {
1919
+ const fillWidth = @as(u32, @intCast(innerEndX - innerStartX + 1));
1920
+ const fillHeight = @as(u32, @intCast(innerEndY - innerStartY + 1));
1921
+ self.fillRect(@intCast(innerStartX), @intCast(innerStartY), fillWidth, fillHeight, backgroundColor);
1922
+ }
1923
+ }
1924
+ }
1925
+
1926
+ // Special cases for extending vertical borders
1927
+ const leftBorderOnly = borderSides.left and isAtActualLeft and !borderSides.top and !borderSides.bottom;
1928
+ const rightBorderOnly = borderSides.right and isAtActualRight and !borderSides.top and !borderSides.bottom;
1929
+ const bottomOnlyWithVerticals = borderSides.bottom and isAtActualBottom and !borderSides.top and (borderSides.left or borderSides.right);
1930
+ const topOnlyWithVerticals = borderSides.top and isAtActualTop and !borderSides.bottom and (borderSides.left or borderSides.right);
1931
+
1932
+ const extendVerticalsToTop = leftBorderOnly or rightBorderOnly or bottomOnlyWithVerticals;
1933
+ const extendVerticalsToBottom = leftBorderOnly or rightBorderOnly or topOnlyWithVerticals;
1934
+ const useTransparentBorderFastPath = canUseTransparentBorderFastPath(self, borderChars, borderColor, backgroundColor);
1935
+
1936
+ // Draw horizontal borders
1937
+ if (borderSides.top or borderSides.bottom) {
1938
+ // Draw top border
1939
+ if (borderSides.top and isAtActualTop) {
1940
+ var drawX = startX;
1941
+ while (drawX <= endX) : (drawX += 1) {
1942
+ if (startY >= 0 and startY < @as(i32, @intCast(self.height))) {
1943
+ if (titleLayout.shouldDraw and drawX >= titleLayout.startX and drawX <= titleLayout.endX) {
1944
+ continue;
1945
+ }
1946
+
1947
+ var char = borderChars[@intFromEnum(BorderCharIndex.horizontal)];
1948
+
1949
+ // Handle corners
1950
+ if (drawX == startX and isAtActualLeft) {
1951
+ char = if (borderSides.left) borderChars[@intFromEnum(BorderCharIndex.topLeft)] else borderChars[@intFromEnum(BorderCharIndex.horizontal)];
1952
+ } else if (drawX == endX and isAtActualRight) {
1953
+ char = if (borderSides.right) borderChars[@intFromEnum(BorderCharIndex.topRight)] else borderChars[@intFromEnum(BorderCharIndex.horizontal)];
1954
+ }
1955
+
1956
+ if (useTransparentBorderFastPath) {
1957
+ const index = self.coordsToIndex(@intCast(drawX), @intCast(startY));
1958
+ self.buffer.char[index] = char;
1959
+ self.buffer.fg[index] = borderColor;
1960
+ self.buffer.attributes[index] = 0;
1961
+ } else {
1962
+ self.setCellWithAlphaBlendingCell(
1963
+ @intCast(drawX),
1964
+ @intCast(startY),
1965
+ makeCell(char, borderColor, backgroundColor, 0),
1966
+ );
1967
+ }
1968
+ }
1969
+ }
1970
+ }
1971
+
1972
+ // Draw bottom border
1973
+ if (borderSides.bottom and isAtActualBottom) {
1974
+ var drawX = startX;
1975
+ while (drawX <= endX) : (drawX += 1) {
1976
+ if (endY >= 0 and endY < @as(i32, @intCast(self.height))) {
1977
+ if (bottomTitleLayout.shouldDraw and drawX >= bottomTitleLayout.startX and drawX <= bottomTitleLayout.endX) {
1978
+ continue;
1979
+ }
1980
+
1981
+ var char = borderChars[@intFromEnum(BorderCharIndex.horizontal)];
1982
+
1983
+ // Handle corners
1984
+ if (drawX == startX and isAtActualLeft) {
1985
+ char = if (borderSides.left) borderChars[@intFromEnum(BorderCharIndex.bottomLeft)] else borderChars[@intFromEnum(BorderCharIndex.horizontal)];
1986
+ } else if (drawX == endX and isAtActualRight) {
1987
+ char = if (borderSides.right) borderChars[@intFromEnum(BorderCharIndex.bottomRight)] else borderChars[@intFromEnum(BorderCharIndex.horizontal)];
1988
+ }
1989
+
1990
+ if (useTransparentBorderFastPath) {
1991
+ const index = self.coordsToIndex(@intCast(drawX), @intCast(endY));
1992
+ self.buffer.char[index] = char;
1993
+ self.buffer.fg[index] = borderColor;
1994
+ self.buffer.attributes[index] = 0;
1995
+ } else {
1996
+ self.setCellWithAlphaBlendingCell(
1997
+ @intCast(drawX),
1998
+ @intCast(endY),
1999
+ makeCell(char, borderColor, backgroundColor, 0),
2000
+ );
2001
+ }
2002
+ }
2003
+ }
2004
+ }
2005
+ }
2006
+
2007
+ // Draw vertical borders
2008
+ const verticalStartY = if (extendVerticalsToTop) startY else startY + if (borderSides.top and isAtActualTop) @as(i32, 1) else @as(i32, 0);
2009
+ const verticalEndY = if (extendVerticalsToBottom) endY else endY - if (borderSides.bottom and isAtActualBottom) @as(i32, 1) else @as(i32, 0);
2010
+
2011
+ if (borderSides.left or borderSides.right) {
2012
+ var drawY = verticalStartY;
2013
+ while (drawY <= verticalEndY) : (drawY += 1) {
2014
+ // Left border
2015
+ if (borderSides.left and isAtActualLeft and startX >= 0 and startX < @as(i32, @intCast(self.width))) {
2016
+ if (useTransparentBorderFastPath) {
2017
+ const index = self.coordsToIndex(@intCast(startX), @intCast(drawY));
2018
+ self.buffer.char[index] = borderChars[@intFromEnum(BorderCharIndex.vertical)];
2019
+ self.buffer.fg[index] = borderColor;
2020
+ self.buffer.attributes[index] = 0;
2021
+ } else {
2022
+ self.setCellWithAlphaBlendingCell(
2023
+ @intCast(startX),
2024
+ @intCast(drawY),
2025
+ makeCell(borderChars[@intFromEnum(BorderCharIndex.vertical)], borderColor, backgroundColor, 0),
2026
+ );
2027
+ }
2028
+ }
2029
+
2030
+ // Right border
2031
+ if (borderSides.right and isAtActualRight and endX >= 0 and endX < @as(i32, @intCast(self.width))) {
2032
+ if (useTransparentBorderFastPath) {
2033
+ const index = self.coordsToIndex(@intCast(endX), @intCast(drawY));
2034
+ self.buffer.char[index] = borderChars[@intFromEnum(BorderCharIndex.vertical)];
2035
+ self.buffer.fg[index] = borderColor;
2036
+ self.buffer.attributes[index] = 0;
2037
+ } else {
2038
+ self.setCellWithAlphaBlendingCell(
2039
+ @intCast(endX),
2040
+ @intCast(drawY),
2041
+ makeCell(borderChars[@intFromEnum(BorderCharIndex.vertical)], borderColor, backgroundColor, 0),
2042
+ );
2043
+ }
2044
+ }
2045
+ }
2046
+ }
2047
+
2048
+ if (titleLayout.shouldDraw) {
2049
+ if (title) |titleText| {
2050
+ try self.drawText(titleText, @intCast(titleLayout.x), @intCast(startY), titleColor, backgroundColor, 0);
2051
+ }
2052
+ }
2053
+
2054
+ if (bottomTitleLayout.shouldDraw) {
2055
+ if (bottomTitle) |titleText| {
2056
+ try self.drawText(titleText, @intCast(bottomTitleLayout.x), @intCast(endY), titleColor, backgroundColor, 0);
2057
+ }
2058
+ }
2059
+ }
2060
+
2061
+ fn computeBoxTitleLayout(
2062
+ self: *OptimizedBuffer,
2063
+ titleText: ?[]const u8,
2064
+ borderSide: bool,
2065
+ isAtActualSide: bool,
2066
+ startX: i32,
2067
+ endX: i32,
2068
+ width: u32,
2069
+ alignment: u8,
2070
+ ) BoxTitleLayout {
2071
+ const text = titleText orelse return .{ .x = startX };
2072
+
2073
+ if (text.len == 0 or !borderSide or !isAtActualSide) {
2074
+ return .{ .x = startX };
2075
+ }
2076
+
2077
+ const is_ascii = utf8.isAsciiOnly(text);
2078
+ const titleLength = @as(i32, @intCast(utf8.calculateTextWidth(text, 2, is_ascii, self.width_method)));
2079
+ const minTitleSpace = 4;
2080
+
2081
+ if (@as(i32, @intCast(width)) < titleLength + minTitleSpace) {
2082
+ return .{ .x = startX };
2083
+ }
2084
+
2085
+ const padding = 2;
2086
+ var titleX = startX + padding;
2087
+
2088
+ if (alignment == 1) {
2089
+ titleX = startX + @max(padding, @divFloor(@as(i32, @intCast(width)) - titleLength, 2));
2090
+ } else if (alignment == 2) {
2091
+ titleX = startX + @as(i32, @intCast(width)) - padding - titleLength;
2092
+ }
2093
+
2094
+ titleX = @max(startX + padding, @min(titleX, endX - titleLength));
2095
+
2096
+ return .{
2097
+ .shouldDraw = true,
2098
+ .x = titleX,
2099
+ .startX = titleX,
2100
+ .endX = titleX + titleLength - 1,
2101
+ };
2102
+ }
2103
+
2104
+ /// Draw a buffer of pixel data using super sampling (2x2 pixels per character cell)
2105
+ /// alignedBytesPerRow: The number of bytes per row in the pixelData buffer, considering alignment/padding.
2106
+ pub fn drawSuperSampleBuffer(
2107
+ self: *OptimizedBuffer,
2108
+ posX: u32,
2109
+ posY: u32,
2110
+ pixelData: [*]const u8,
2111
+ len: usize,
2112
+ format: u8, // 0: bgra8unorm, 1: rgba8unorm
2113
+ alignedBytesPerRow: u32,
2114
+ ) void {
2115
+ const bytesPerPixel = 4;
2116
+ const isBGRA = (format == 0);
2117
+
2118
+ // TODO: A more robust implementation might take source width/height explicitly.
2119
+
2120
+ var y_cell = posY;
2121
+ while (y_cell < self.height) : (y_cell += 1) {
2122
+ var x_cell = posX;
2123
+ while (x_cell < self.width) : (x_cell += 1) {
2124
+ if (!self.isPointInScissor(@intCast(x_cell), @intCast(y_cell))) {
2125
+ continue;
2126
+ }
2127
+
2128
+ const renderX: u32 = (x_cell - posX) * 2;
2129
+ const renderY: u32 = (y_cell - posY) * 2;
2130
+
2131
+ const tlIndex: usize = @intCast(renderY * alignedBytesPerRow + renderX * bytesPerPixel);
2132
+ const trIndex: usize = tlIndex + bytesPerPixel;
2133
+ const blIndex: usize = @intCast((renderY + 1) * alignedBytesPerRow + renderX * bytesPerPixel);
2134
+ const brIndex: usize = blIndex + bytesPerPixel;
2135
+
2136
+ const indices = [_]usize{ tlIndex, trIndex, blIndex, brIndex };
2137
+
2138
+ // Get RGBA colors for TL, TR, BL, BR
2139
+ var pixelsRgba: [4]RGBA = undefined;
2140
+ pixelsRgba[0] = getPixelColor(indices[0], pixelData, len, isBGRA); // TL
2141
+ pixelsRgba[1] = getPixelColor(indices[1], pixelData, len, isBGRA); // TR
2142
+ pixelsRgba[2] = getPixelColor(indices[2], pixelData, len, isBGRA); // BL
2143
+ pixelsRgba[3] = getPixelColor(indices[3], pixelData, len, isBGRA); // BR
2144
+
2145
+ const cellResult = renderQuadrantBlock(pixelsRgba);
2146
+
2147
+ self.setCellWithAlphaBlending(
2148
+ x_cell,
2149
+ y_cell,
2150
+ cellResult.char,
2151
+ cellResult.fg,
2152
+ cellResult.bg,
2153
+ 0,
2154
+ );
2155
+ }
2156
+ }
2157
+ }
2158
+
2159
+ /// Draw a buffer of pixel data using pre-computed super sample results from compute shader
2160
+ /// data contains an array of CellResult structs (48 bytes each)
2161
+ /// Each CellResult: bg(16) + fg(16) + char(4) + padding1(4) + padding2(4) + padding3(4) = 48 bytes
2162
+ pub fn drawPackedBuffer(
2163
+ self: *OptimizedBuffer,
2164
+ data: [*]const u8,
2165
+ dataLen: usize,
2166
+ posX: u32,
2167
+ posY: u32,
2168
+ terminalWidthCells: u32,
2169
+ terminalHeightCells: u32,
2170
+ ) void {
2171
+ const cellResultSize = 48;
2172
+ const numCells = dataLen / cellResultSize;
2173
+ const bufferWidthCells = terminalWidthCells;
2174
+
2175
+ var i: usize = 0;
2176
+ while (i < numCells) : (i += 1) {
2177
+ const cellDataOffset = i * cellResultSize;
2178
+
2179
+ const cellX = posX + @as(u32, @intCast(i % bufferWidthCells));
2180
+ const cellY = posY + @as(u32, @intCast(i / bufferWidthCells));
2181
+
2182
+ if (cellX >= terminalWidthCells or cellY >= terminalHeightCells) continue;
2183
+ if (cellX >= self.width or cellY >= self.height) continue;
2184
+
2185
+ if (!self.isPointInScissor(@intCast(cellX), @intCast(cellY))) continue;
2186
+
2187
+ const bgPtr = @as([*]const f32, @ptrCast(@alignCast(data + cellDataOffset)));
2188
+ const bg: RGBA = ansi.rgbaFromFloats(bgPtr[0], bgPtr[1], bgPtr[2], bgPtr[3]);
2189
+
2190
+ const fgPtr = @as([*]const f32, @ptrCast(@alignCast(data + cellDataOffset + 16)));
2191
+ const fg: RGBA = ansi.rgbaFromFloats(fgPtr[0], fgPtr[1], fgPtr[2], fgPtr[3]);
2192
+
2193
+ const charPtr = @as([*]const u32, @ptrCast(@alignCast(data + cellDataOffset + 32)));
2194
+ var char = charPtr[0];
2195
+
2196
+ if (char == 0 or char > MAX_UNICODE_CODEPOINT) {
2197
+ char = DEFAULT_SPACE_CHAR;
2198
+ }
2199
+
2200
+ if (char < 32 or (char > 126 and char < 0x2580)) {
2201
+ char = BLOCK_CHAR;
2202
+ }
2203
+
2204
+ self.setCellWithAlphaBlending(cellX, cellY, char, fg, bg, 0);
2205
+ }
2206
+ }
2207
+
2208
+ fn getGrayscaleChar(intensity: f32) u32 {
2209
+ if (intensity < 0.01) return ' ';
2210
+ const clamped = @min(@max(intensity, 0.0), 1.0);
2211
+ const index: usize = @intFromFloat(clamped * @as(f32, @floatFromInt(GRAYSCALE_CHARS.len - 1)));
2212
+ return GRAYSCALE_CHARS[index];
2213
+ }
2214
+
2215
+ pub fn drawGrayscaleBuffer(
2216
+ self: *OptimizedBuffer,
2217
+ posX: i32,
2218
+ posY: i32,
2219
+ intensities: [*]const f32,
2220
+ srcWidth: u32,
2221
+ srcHeight: u32,
2222
+ fgColor: ?RGBA,
2223
+ bgColor: ?RGBA,
2224
+ ) void {
2225
+ const bg = bgColor orelse ansi.rgbColor(0, 0, 0, 0);
2226
+ if (srcWidth == 0 or srcHeight == 0) return;
2227
+ if (posX >= @as(i32, @intCast(self.width)) or posY >= @as(i32, @intCast(self.height))) return;
2228
+
2229
+ const startX: u32 = if (posX < 0) @intCast(-posX) else 0;
2230
+ const startY: u32 = if (posY < 0) @intCast(-posY) else 0;
2231
+
2232
+ const destStartX: u32 = if (posX < 0) 0 else @intCast(posX);
2233
+ const destStartY: u32 = if (posY < 0) 0 else @intCast(posY);
2234
+
2235
+ if (startX >= srcWidth or startY >= srcHeight) return;
2236
+
2237
+ const visibleWidth = @min(srcWidth - startX, self.width - destStartX);
2238
+ const visibleHeight = @min(srcHeight - startY, self.height - destStartY);
2239
+
2240
+ if (visibleWidth == 0 or visibleHeight == 0) return;
2241
+
2242
+ const baseFg = fgColor orelse ansi.rgbColor(255, 255, 255, 255);
2243
+
2244
+ const opacity = self.getCurrentOpacity();
2245
+ const graphemeAware = self.grapheme_tracker.hasAny();
2246
+ const linkAware = self.link_tracker.hasAny();
2247
+
2248
+ var srcY: u32 = startY;
2249
+ var destY: u32 = destStartY;
2250
+ while (srcY < startY + visibleHeight) : ({
2251
+ srcY += 1;
2252
+ destY += 1;
2253
+ }) {
2254
+ var srcX: u32 = startX;
2255
+ var destX: u32 = destStartX;
2256
+ while (srcX < startX + visibleWidth) : ({
2257
+ srcX += 1;
2258
+ destX += 1;
2259
+ }) {
2260
+ if (!self.isPointInScissor(@intCast(destX), @intCast(destY))) continue;
2261
+
2262
+ const srcIndex = srcY * srcWidth + srcX;
2263
+ const intensity = intensities[srcIndex];
2264
+
2265
+ if (intensity < 0.01) continue;
2266
+
2267
+ const char = getGrayscaleChar(intensity);
2268
+
2269
+ const gray = @min(@max(intensity, 0.0), 1.0);
2270
+ const fg = applyOpacity(baseFg, opacityToU8(gray * opacity));
2271
+
2272
+ if (graphemeAware or linkAware) {
2273
+ self.setCellWithAlphaBlendingCell(destX, destY, makeCell(char, fg, bg, 0));
2274
+ } else {
2275
+ self.setCellWithAlphaBlendingRawCell(destX, destY, makeCell(char, fg, bg, 0));
2276
+ }
2277
+ }
2278
+ }
2279
+ }
2280
+
2281
+ pub fn drawGrayscaleBufferSupersampled(
2282
+ self: *OptimizedBuffer,
2283
+ posX: i32,
2284
+ posY: i32,
2285
+ intensities: [*]const f32,
2286
+ srcWidth: u32,
2287
+ srcHeight: u32,
2288
+ fgColor: ?RGBA,
2289
+ bgColor: ?RGBA,
2290
+ ) void {
2291
+ const bg = bgColor orelse ansi.rgbColor(0, 0, 0, 0);
2292
+ const termWidth = srcWidth / 2;
2293
+ const termHeight = srcHeight / 2;
2294
+
2295
+ if (termWidth == 0 or termHeight == 0) return;
2296
+ if (posX >= @as(i32, @intCast(self.width)) or posY >= @as(i32, @intCast(self.height))) return;
2297
+
2298
+ const startX: u32 = if (posX < 0) @intCast(-posX) else 0;
2299
+ const startY: u32 = if (posY < 0) @intCast(-posY) else 0;
2300
+
2301
+ const destStartX: u32 = if (posX < 0) 0 else @intCast(posX);
2302
+ const destStartY: u32 = if (posY < 0) 0 else @intCast(posY);
2303
+
2304
+ if (startX >= termWidth or startY >= termHeight) return;
2305
+
2306
+ const visibleWidth = @min(termWidth - startX, self.width - destStartX);
2307
+ const visibleHeight = @min(termHeight - startY, self.height - destStartY);
2308
+
2309
+ if (visibleWidth == 0 or visibleHeight == 0) return;
2310
+
2311
+ const baseFg = fgColor orelse ansi.rgbColor(255, 255, 255, 255);
2312
+
2313
+ const opacity = self.getCurrentOpacity();
2314
+ const graphemeAware = self.grapheme_tracker.hasAny();
2315
+ const linkAware = self.link_tracker.hasAny();
2316
+
2317
+ const maxIdx = srcHeight * srcWidth;
2318
+ var cellY: u32 = startY;
2319
+ var destY: u32 = destStartY;
2320
+ while (cellY < startY + visibleHeight) : ({
2321
+ cellY += 1;
2322
+ destY += 1;
2323
+ }) {
2324
+ var cellX: u32 = startX;
2325
+ var destX: u32 = destStartX;
2326
+ while (cellX < startX + visibleWidth) : ({
2327
+ cellX += 1;
2328
+ destX += 1;
2329
+ }) {
2330
+ if (!self.isPointInScissor(@intCast(destX), @intCast(destY))) continue;
2331
+
2332
+ const qx = cellX * 2;
2333
+ const qy = cellY * 2;
2334
+
2335
+ const tlIdx = qy * srcWidth + qx;
2336
+ const trIdx = qy * srcWidth + qx + 1;
2337
+ const blIdx = (qy + 1) * srcWidth + qx;
2338
+ const brIdx = (qy + 1) * srcWidth + qx + 1;
2339
+
2340
+ const tl: f32 = if (tlIdx < maxIdx) intensities[tlIdx] else 0.0;
2341
+ const tr: f32 = if (trIdx < maxIdx and qx + 1 < srcWidth) intensities[trIdx] else 0.0;
2342
+ const bl: f32 = if (blIdx < maxIdx and qy + 1 < srcHeight) intensities[blIdx] else 0.0;
2343
+ const br: f32 = if (brIdx < maxIdx and qx + 1 < srcWidth and qy + 1 < srcHeight) intensities[brIdx] else 0.0;
2344
+
2345
+ const avgIntensity = (tl + tr + bl + br) / 4.0;
2346
+
2347
+ if (avgIntensity < 0.01) continue;
2348
+
2349
+ const char = getGrayscaleChar(avgIntensity);
2350
+
2351
+ const gray = @min(@max(avgIntensity, 0.0), 1.0);
2352
+ const fg = applyOpacity(baseFg, opacityToU8(gray * opacity));
2353
+
2354
+ if (graphemeAware or linkAware) {
2355
+ self.setCellWithAlphaBlendingCell(destX, destY, makeCell(char, fg, bg, 0));
2356
+ } else {
2357
+ self.setCellWithAlphaBlendingRawCell(destX, destY, makeCell(char, fg, bg, 0));
2358
+ }
2359
+ }
2360
+ }
2361
+ }
2362
+ };
2363
+
2364
+ fn getPixelColor(idx: usize, data: [*]const u8, dataLen: usize, bgra: bool) RGBA {
2365
+ if (idx + 3 >= dataLen) {
2366
+ return ansi.rgbColor(255, 0, 255, 0); // Return Transparent Magenta for out-of-bounds
2367
+ }
2368
+ var rByte: u8 = undefined;
2369
+ var gByte: u8 = undefined;
2370
+ var bByte: u8 = undefined;
2371
+ var aByte: u8 = undefined;
2372
+
2373
+ if (bgra) {
2374
+ bByte = data[idx];
2375
+ gByte = data[idx + 1];
2376
+ rByte = data[idx + 2];
2377
+ aByte = data[idx + 3];
2378
+ } else { // Assume RGBA
2379
+ rByte = data[idx];
2380
+ gByte = data[idx + 1];
2381
+ bByte = data[idx + 2];
2382
+ aByte = data[idx + 3];
2383
+ }
2384
+
2385
+ return ansi.rgbColor(rByte, gByte, bByte, aByte);
2386
+ }
2387
+
2388
+ const quadrantChars = [_]u32{
2389
+ 32, // 0000
2390
+ 0x2597, // 0001 BR ░
2391
+ 0x2596, // 0010 BL ░
2392
+ 0x2584, // 0011 Lower Half Block ▄
2393
+ 0x259D, // 0100 TR ░
2394
+ 0x2590, // 0101 Right Half Block ▐
2395
+ 0x259E, // 0110 TR+BL ░
2396
+ 0x259F, // 0111 TR+BL+BR ░
2397
+ 0x2598, // 1000 TL ░
2398
+ 0x259A, // 1001 TL+BR ░
2399
+ 0x258C, // 1010 Left Half Block ▌
2400
+ 0x2599, // 1011 TL+BL+BR ░
2401
+ 0x2580, // 1100 Upper Half Block ▀
2402
+ 0x259C, // 1101 TL+TR+BR ░
2403
+ 0x259B, // 1110 TL+TR+BL ░
2404
+ 0x2588, // 1111 Full Block █
2405
+ };
2406
+
2407
+ fn colorDistance(a: RGBA, b: RGBA) f32 {
2408
+ const dr = @as(f32, @floatFromInt(ansi.red(a))) - @as(f32, @floatFromInt(ansi.red(b)));
2409
+ const dg = @as(f32, @floatFromInt(ansi.green(a))) - @as(f32, @floatFromInt(ansi.green(b)));
2410
+ const db = @as(f32, @floatFromInt(ansi.blue(a))) - @as(f32, @floatFromInt(ansi.blue(b)));
2411
+ return dr * dr + dg * dg + db * db;
2412
+ }
2413
+
2414
+ fn closestColorIndex(pixel: RGBA, candidates: [2]RGBA) u1 {
2415
+ return if (colorDistance(pixel, candidates[0]) <= colorDistance(pixel, candidates[1])) 0 else 1;
2416
+ }
2417
+
2418
+ fn averageColorRgba(pixels: []const RGBA) RGBA {
2419
+ if (pixels.len == 0) return ansi.rgbColor(0, 0, 0, 0);
2420
+
2421
+ var sumR: u32 = 0;
2422
+ var sumG: u32 = 0;
2423
+ var sumB: u32 = 0;
2424
+ var sumA: u32 = 0;
2425
+
2426
+ for (pixels) |p| {
2427
+ sumR += ansi.red(p);
2428
+ sumG += ansi.green(p);
2429
+ sumB += ansi.blue(p);
2430
+ sumA += ansi.alpha(p);
2431
+ }
2432
+
2433
+ const len: u32 = @intCast(pixels.len);
2434
+ return ansi.rgbColor(
2435
+ @intCast((sumR + len / 2) / len),
2436
+ @intCast((sumG + len / 2) / len),
2437
+ @intCast((sumB + len / 2) / len),
2438
+ @intCast((sumA + len / 2) / len),
2439
+ );
2440
+ }
2441
+
2442
+ fn luminance(color: RGBA) f32 {
2443
+ return 0.2126 * ansi.redF(color) + 0.7152 * ansi.greenF(color) + 0.0722 * ansi.blueF(color);
2444
+ }
2445
+
2446
+ pub const QuadrantResult = struct {
2447
+ char: u32,
2448
+ fg: RGBA,
2449
+ bg: RGBA,
2450
+ };
2451
+
2452
+ // Calculate the quadrant block character and colors from RGBA pixels
2453
+ fn renderQuadrantBlock(pixels: [4]RGBA) QuadrantResult {
2454
+ // 1. Find the most different pair of pixels
2455
+ var p_idxA: u3 = 0;
2456
+ var p_idxB: u3 = 1;
2457
+ var maxDist = colorDistance(pixels[0], pixels[1]);
2458
+
2459
+ inline for (0..4) |i| {
2460
+ inline for ((i + 1)..4) |j| {
2461
+ const dist = colorDistance(pixels[i], pixels[j]);
2462
+ if (dist > maxDist) {
2463
+ p_idxA = @intCast(i);
2464
+ p_idxB = @intCast(j);
2465
+ maxDist = dist;
2466
+ }
2467
+ }
2468
+ }
2469
+ const p_candA = pixels[p_idxA];
2470
+ const p_candB = pixels[p_idxB];
2471
+
2472
+ // 2. Determine chosen_dark_color and chosen_light_color based on luminance
2473
+ var chosen_dark_color: RGBA = undefined;
2474
+ var chosen_light_color: RGBA = undefined;
2475
+
2476
+ if (luminance(p_candA) <= luminance(p_candB)) {
2477
+ chosen_dark_color = p_candA;
2478
+ chosen_light_color = p_candB;
2479
+ } else {
2480
+ chosen_dark_color = p_candB;
2481
+ chosen_light_color = p_candA;
2482
+ }
2483
+
2484
+ // 3. Classify quadrants and build quadrantBits
2485
+ var quadrantBits: u4 = 0;
2486
+ const bitValues = [_]u4{ 8, 4, 2, 1 };
2487
+
2488
+ inline for (0..4) |i| {
2489
+ const pixelRgba = pixels[i];
2490
+ if (closestColorIndex(pixelRgba, .{ chosen_dark_color, chosen_light_color }) == 0) {
2491
+ quadrantBits |= bitValues[i];
2492
+ }
2493
+ }
2494
+
2495
+ // 4. Construct Result
2496
+ if (quadrantBits == 0) { // All light
2497
+ return .{
2498
+ .char = 32,
2499
+ .fg = chosen_dark_color,
2500
+ .bg = averageColorRgba(pixels[0..4]),
2501
+ };
2502
+ } else if (quadrantBits == 15) { // All dark
2503
+ return .{
2504
+ .char = quadrantChars[15],
2505
+ .fg = averageColorRgba(pixels[0..4]),
2506
+ .bg = chosen_light_color,
2507
+ };
2508
+ } else { // Mixed pattern
2509
+ return .{
2510
+ .char = quadrantChars[quadrantBits],
2511
+ .fg = chosen_dark_color,
2512
+ .bg = chosen_light_color,
2513
+ };
2514
+ }
2515
+ }