@fairyhunter13/opentui-core 0.1.112 → 0.1.114

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