Compare commits

...
Author SHA1 Message Date
copilot-swe-agent[bot]andTyriar 369ca9b525 Add error handling for dynamic imports
Co-authored-by: Tyriar <2193314+Tyriar@users.noreply.github.com>
2026-01-16 01:58:45 +00:00
copilot-swe-agent[bot]andTyriar a5422d1b11 Add dynamic imports for AccessibilityManager and OverviewRulerRenderer
Co-authored-by: Tyriar <2193314+Tyriar@users.noreply.github.com>
2026-01-16 01:56:13 +00:00
copilot-swe-agent[bot]andTyriar c2890d8a4d Add error handling for dynamic import in loadCustomGlyphDefinitions
Co-authored-by: Tyriar <2193314+Tyriar@users.noreply.github.com>
2026-01-16 01:14:01 +00:00
copilot-swe-agent[bot]andTyriar 7a7abddc45 Use dynamic imports for custom glyphs in WebGL addon
Co-authored-by: Tyriar <2193314+Tyriar@users.noreply.github.com>
2026-01-16 01:12:01 +00:00
copilot-swe-agent[bot]andTyriar 8c71bfd65f Revert @xterm/xterm alias to use package.json resolution
Co-authored-by: Tyriar <2193314+Tyriar@users.noreply.github.com>
2026-01-16 00:41:57 +00:00
copilot-swe-agent[bot]andTyriar 3c2b911439 Set up code splitting for ESM build
Co-authored-by: Tyriar <2193314+Tyriar@users.noreply.github.com>
2026-01-16 00:40:40 +00:00
copilot-swe-agent[bot] 5ee8760418 Initial plan 2026-01-16 00:31:02 +00:00
Daniel Imms 777a46445a Merge pull request #5609 from xtermjs/merogge/show-cursor
add `showCursorImmediately` option
2026-01-13 08:47:50 -08:00
meganrogge a20ff565b0 add showCursorImmediately option 2026-01-13 10:36:35 -06:00
Daniel Imms d28046ebed Merge pull request #5607 from Tyriar/5606
Fix blur due to canvas dim mismatch in glyph renderer
2026-01-13 06:35:40 -08:00
Daniel Imms 4ddd982e42 Fix blur due to canvas dim mismatch in glyph renderer
Fixes #5606
2026-01-13 06:23:10 -08:00
Daniel Imms a3228bd1b8 Merge pull request #5604 from Tyriar/2357_2
Fix capital letters and ctrl+letter in win32-input-mode
2026-01-11 09:10:31 -08:00
Daniel Imms a1fca4feb8 Fix ctrl+letter when inside pwsh->WSL 2026-01-11 09:02:44 -08:00
Daniel Imms afc6f0b7eb Fix caps not working in win32InputMode
Part of #2357
2026-01-11 09:00:08 -08:00
Daniel Imms f4c77d37b4 Merge pull request #5603 from Tyriar/2357
Implement win32-input-mode
2026-01-10 06:04:17 -08:00
Daniel Imms 9d0beb7c38 Use 0b over 0x for flags 2026-01-10 05:57:13 -08:00
Daniel Imms f88650ec1c Use win32InputMode in demo on Windows 2026-01-10 05:54:48 -08:00
Daniel Imms 8b35c67dd3 useWin32 -> useWin32InputMode 2026-01-10 05:52:19 -08:00
Daniel Imms 53dc85eca2 Add copyright 2026-01-10 05:48:48 -08:00
Daniel Imms 0946386cc4 Make unit tests more compact 2026-01-10 05:48:30 -08:00
Daniel Imms ebe18b3da5 Add more test cases 2026-01-10 05:42:17 -08:00
Daniel Imms 6c2792a1d5 Fix tests 2026-01-10 05:33:08 -08:00
Daniel Imms ee47054678 Implement win32-input-mode
Fixes #2357
2026-01-10 05:27:03 -08:00
Daniel Imms 91c4761b82 Merge pull request #5600 from Tyriar/4198_kitty
Implement kitty keyboard protocol (CSI =|?|>|< u)
2026-01-10 04:46:38 -08:00
Daniel Imms c9fc6fca8e Lint 2026-01-10 04:39:26 -08:00
Daniel Imms 73cba6dda3 Clean up, add sgr extension to api 2026-01-10 04:38:06 -08:00
Daniel Imms 50b0f3d7ee Add vtExtensions.kittySgrBoldFaintControl 2026-01-10 04:31:36 -08:00
Daniel Imms 686c67a14b Make mandatory browser services readonly 2026-01-10 04:20:29 -08:00
Daniel Imms ec78500f86 Create IKeyboardService 2026-01-10 04:19:23 -08:00
Daniel Imms 98ea14824a Make lint happy 2026-01-09 13:14:30 -08:00
Daniel Imms 4c905dad33 Update API jsdoc 2026-01-09 13:02:18 -08:00
Daniel Imms e3fdcc7869 Fix API lint 2026-01-09 13:01:22 -08:00
Daniel Imms 0674663a5a Remove unused import 2026-01-09 12:56:45 -08:00
Daniel Imms e07832a420 Merge branch 'master' into 4198_kitty 2026-01-09 12:51:48 -08:00
Daniel Imms 934b5dc8fa Merge pull request #5602 from Tyriar/5601
Add SGR 221 and 222
2026-01-09 12:21:43 -08:00
Daniel Imms 7a544d8346 Add SGR 221 and 222
Fixes #5601
2026-01-09 12:13:40 -08:00
Daniel Imms c624a47780 Maintain different buffer flags, stack limit, tests 2026-01-09 11:59:50 -08:00
Daniel Imms 5a29d489c3 Separate out kitty keyboard handlers 2026-01-09 11:46:57 -08:00
Daniel Imms 4a67836a5b Remove support responses
Wrong place for them
2026-01-09 11:42:00 -08:00
Daniel Imms 3adf6be988 Fix some edge cases 2026-01-09 10:36:13 -08:00
Daniel Imms 566589f7c1 More comprehensive tests 2026-01-09 07:23:12 -08:00
Daniel Imms 8dbc91dc24 Add vtExtensions to demo 2026-01-09 07:15:45 -08:00
Daniel Imms 992da3cc4d Hook up vt extensions option 2026-01-09 07:07:10 -08:00
Daniel Imms 3fbaef06ef Align behavior closer with kitty 2026-01-09 06:53:12 -08:00
Daniel Imms 2265fa2ade Implement kitty keyboard protocol (CSI u)
Fixes #4198
2026-01-09 05:59:57 -08:00
Daniel Imms 756c353237 Merge pull request #5593 from kallsyms/improve-lines-cache-perf
improve SearchLineCache performance
2026-01-09 05:59:54 -08:00
Daniel Imms 49a8ac8fc0 Merge pull request #5599 from Tyriar/flush
Flush writes on resize
2026-01-09 05:37:21 -08:00
Daniel Imms bf7c95b6cc Flush writes on resize
Fixes #5597
2026-01-09 05:25:22 -08:00
Daniel Imms 8112fbf210 Merge pull request #5598 from Tyriar/5588
Fix exception on resize during write
2026-01-08 18:10:41 -08:00
Daniel Imms 16a13f8504 Fix exception on resize during write
Fixes #5588
2026-01-08 18:03:42 -08:00
Daniel Imms 9bd128b315 Merge pull request #5594 from Tyriar/onSelectionChangeClear
Fire onSelectionChange on clear
2026-01-08 17:44:16 -08:00
Daniel Imms 729a670043 Merge pull request #5596 from Tyriar/lint_changes
New npm script to lint only changes
2026-01-08 17:39:34 -08:00
Daniel Imms bd8454db55 Another poll case 2026-01-08 17:37:44 -08:00
Daniel Imms d6f6a6af9a Lint instructions 2026-01-08 17:32:50 -08:00
Daniel Imms d65f9312ea Add lint-changes npm scripts 2026-01-08 17:32:15 -08:00
Daniel Imms a437d12004 Poll to avoid a race 2026-01-08 17:25:26 -08:00
Daniel Imms 437490308c Merge pull request #5595 from Tyriar/download_fonts
Remove download fonts
2026-01-08 17:18:36 -08:00
Daniel Imms 3250c31202 Remove download fonts 2026-01-08 17:09:26 -08:00
Daniel Imms 55d12e03d1 Remove unneeded test 2026-01-08 17:04:35 -08:00
Daniel Imms 6efb319ece Add tests more thorough tests for onSelectionChange 2026-01-08 17:01:56 -08:00
Daniel Imms b69afe5765 Merge remote-tracking branch 'upstream/master' into onSelectionChangeClear 2026-01-08 16:51:54 -08:00
Daniel Imms 613aa6ba23 Fire onSelectionChange when starting to drag 2026-01-08 16:51:45 -08:00
Nick Gregory a8c9128841 improve SearchLineCache performance 2026-01-07 16:04:49 -08:00
Daniel Imms 94a264679e Merge pull request #5591 from Tyriar/5586
Ensure mouse listeners are removed on dispose
2026-01-05 12:38:41 -08:00
Daniel Imms cb35d1b487 Ensure mouse listeners are removed on dispose
Also use ? over ! just in case

Fixes #5586
2026-01-05 12:31:54 -08:00
Daniel Imms c97abced76 Merge pull request #5590 from Tyriar/5587
Add undefined checks in erase calls
2026-01-05 11:17:40 -08:00
Daniel Imms 9db31db886 Add undefined checks in erase calls
This is likely a race condition during a resize which is hard to say
what the right behavior is. Instead of hard failing by throwing an
error, silently ignore if this happens.

Fixes #5587
2026-01-05 11:10:56 -08:00
Daniel Imms ccf9727b85 Merge pull request #5583 from Tyriar/root
Clean up root, remove auto approve settings
2026-01-04 06:44:57 -08:00
Daniel Imms 1dfdde9e27 Clean up root, remove auto approve settings
These are automatically auto approved in upcoming vscode
2026-01-04 06:38:53 -08:00
Daniel Imms 2712e88d0a Merge pull request #5582 from Tyriar/readme2
Update readme 2
2026-01-04 06:28:32 -08:00
Daniel Imms b5da8a28f6 Update readme 2 2026-01-04 06:27:22 -08:00
Daniel Imms 66c4f8b116 Merge pull request #5581 from Tyriar/readme
Update readme
2026-01-04 06:20:48 -08:00
Daniel Imms 9148c80d1a Update readme
- Added x2 scale logo
- Revised wording
- Added new addons
2026-01-04 06:18:50 -08:00
Daniel Imms e1bfc7dd1f Merge pull request #5178 from jerch/webfonts-addon
Add webfonts addon
2026-01-04 05:43:01 -08:00
Daniel Imms c6c4a2ffbc Delete unwanted eslintrc 2026-01-03 15:39:24 -08:00
Daniel Imms 2cf2929869 Publish webfonts 2026-01-03 15:36:36 -08:00
Daniel Imms b0145998c5 Fix lint 2026-01-03 15:36:31 -08:00
Daniel Imms 0e57643f16 Move fonts into folder 2026-01-03 15:33:13 -08:00
Daniel Imms a35223a819 Add web fonts window to demo 2026-01-03 15:31:24 -08:00
Daniel Imms 5e95dc1f10 Sync package lock 2026-01-03 15:24:11 -08:00
Daniel Imms b4e9a7f9ea Merge remote-tracking branch 'upstream/master' into pr/jerch/5178 2026-01-03 15:21:50 -08:00
Daniel Imms 73e3357526 Merge pull request #5579 from Tyriar/proposed
Make everything except unicode APIs stable
2026-01-03 15:04:25 -08:00
Daniel Imms 483c7b4a81 Merge pull request #5580 from Tyriar/5572
Update demo dims on font family change
2026-01-03 14:58:57 -08:00
Daniel Imms f4453b3e18 Merge pull request #5566 from xtermjs/dependabot/npm_and_yarn/qs-6.14.1
Bump qs from 6.14.0 to 6.14.1
2026-01-03 14:58:39 -08:00
Daniel Imms 7389a1097d Update tests to use unicode for proposed check 2026-01-03 14:57:55 -08:00
Daniel Imms 0c7b1cb448 Update demo dims on font family change
Fixes #5572
2026-01-03 14:52:32 -08:00
Daniel Imms 7a3b5339e7 Merge pull request #5578 from Tyriar/5576
Lint demo code
2026-01-03 14:41:48 -08:00
Daniel Imms 8193ceae12 Make everything except unicode APIs stable 2026-01-03 14:40:07 -08:00
Daniel Imms 064e299bb0 Merge pull request #5577 from Tyriar/ext_recommendation
Recommend eslint extension in vscode
2026-01-03 14:38:45 -08:00
Daniel Imms 6211bf078c Lint demo code
Fixes #5576
2026-01-03 14:35:39 -08:00
Daniel Imms a639808196 Recommend eslint extension in vscode
Fixes #5575
2026-01-03 14:32:16 -08:00
Daniel Imms b522e255f0 Merge pull request #5571 from Tyriar/5341
Fix isNode detection when process module is used in webpack
2026-01-03 14:25:33 -08:00
Daniel Imms d7850af9a2 Fix lint 2026-01-03 14:19:36 -08:00
Daniel Imms 4182f2226f Merge pull request #5573 from Tyriar/5570_oom
Fix infinite recursion OOM crash in addon-ligatures
2026-01-03 14:15:11 -08:00
Daniel Imms e2f45b5f4e Fix for modern node that includes a navigator.userAgent 2026-01-03 14:10:44 -08:00
Daniel Imms 8712f8067d Fix infinite recursion OOM crash in addon-ligatures
1. processLookahead/BacktrackPosition created separate entry objects
   for each glyph at each position (O(N^M) with N glyphs, M positions).
   Now all glyphs at a position share one entry object.
2. cloneEntry, cloneTree, flattenEntry, and mergeTreeEntry could
   infinitely recurse or duplicate work on shared/cyclic references.
   Added visited/merged tracking maps to cache results.

Note that parsing CommitMono locks up the renderer for some time still
so there is still a performance issue here, this fixes the OOM though.
This was mostly defensive generated code since the codebase is
unfamiliar to me.

Fixes #5570
2026-01-03 14:06:57 -08:00
Daniel Imms 08c49301b7 Fix isNode detection when process module is used in webpack
Fixes #5341
2026-01-03 11:19:23 -08:00
dependabot[bot] 917a8ded92 Bump qs from 6.14.0 to 6.14.1
Bumps [qs](https://github.com/ljharb/qs) from 6.14.0 to 6.14.1.
- [Changelog](https://github.com/ljharb/qs/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ljharb/qs/compare/v6.14.0...v6.14.1)

---
updated-dependencies:
- dependency-name: qs
  dependency-version: 6.14.1
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-03 17:44:20 +00:00
Daniel Imms d06d278f0c Merge pull request #5569 from Tyriar/5568_font_ligatures
Merge font-ligatures package into addon-ligatures
2026-01-03 09:43:07 -08:00
Daniel Imms f84384c83a Fix lint 2026-01-03 09:31:45 -08:00
Daniel Imms ec03109c39 2 space indent 2026-01-03 09:25:39 -08:00
Daniel Imms 21b8f77afb Move unit tests to right folder, push font fixtures 2026-01-03 09:16:58 -08:00
Daniel Imms 363fc84fd2 Merge font-ligatures into addon-ligatures
Fixes #5568
2026-01-03 09:02:06 -08:00
Daniel Imms 8e4de23c11 Merge pull request #5565 from Tyriar/2797
Support ctrl+^ -> RS, move to physical key
2026-01-01 05:25:52 -08:00
Daniel Imms 1caf6dbe50 Fix tests 2026-01-01 05:19:56 -08:00
Daniel Imms 1c97e40a6a Support ctrl+^ -> RS, move to physical key
Fixes #2797
Part of #1862
2026-01-01 04:41:44 -08:00
Daniel Imms cdbafb231d Merge pull request #5564 from Tyriar/3364
Serialize showCursor
2025-12-31 17:14:02 -08:00
Daniel Imms 44a8c7efbc Fix test expectations 2025-12-31 17:08:05 -08:00
Daniel Imms 6277bb363c Serialize showCursor
Fixes #3364
2025-12-31 08:12:39 -08:00
Daniel Imms 40f2eefec7 Merge pull request #5563 from Tyriar/5489
Fix touch scrolling
2025-12-31 06:33:36 -08:00
Daniel Imms 519b1c5ef7 Fix touch scrolling
Fixes #5489
2025-12-31 06:27:45 -08:00
Daniel Imms 97e356fb83 Merge pull request #5562 from Tyriar/2117_3
Add tests for CSI Pm d, e, f, g, m
2025-12-31 05:24:41 -08:00
Daniel Imms 42872a84dd Add tests for CSI Pm d, e, f, g, m
Fixes #2117
2025-12-31 05:18:17 -08:00
Daniel Imms 4700e18833 Merge pull request #5561 from Tyriar/5558
Fix allowTransparency in lib and demo
2025-12-31 05:08:29 -08:00
Daniel Imms d143340b60 Fix allowTransparency in lib and demo
Fixes #5558
Fixes #5560
2025-12-31 05:00:33 -08:00
Daniel Imms a8f26bb758 Merge pull request #5559 from Tyriar/2117_2
Add tests for CSI `Ps K`, `? Ps K`, `Ps S`, `Ps T`, `Ps X`, `Ps Z`, `Ps ^`, `Ps \``
2025-12-30 07:06:37 -08:00
Daniel Imms da4243cf02 Don't skip new tests, implement CSI Ps ^ 2025-12-30 06:59:27 -08:00
Daniel Imms 54e66f3ac4 Add some more CSI tests 2025-12-30 06:48:28 -08:00
Daniel Imms 7d8ef60860 Merge pull request #5557 from Tyriar/playwright_update2
Update playwright test to latest
2025-12-30 06:47:24 -08:00
Daniel Imms 595c119404 Move skip into dom file 2025-12-30 06:05:46 -08:00
Daniel Imms 481431fbc1 Update playwright test to latest 2025-12-30 06:03:17 -08:00
Daniel Imms 5c2cd474ce Merge pull request #5556 from Tyriar/5555
Migrate evaluate calls to use terminal proxy
2025-12-30 05:43:14 -08:00
Daniel Imms 0b9a7cb856 Migrate MouseTracking and Terminal to playwright proxy
Fixes #5555
2025-12-30 05:37:09 -08:00
Daniel Imms a8a4455189 Migrate InputHandler.test.ts to playwright proxy
Part of #5555
2025-12-30 05:27:28 -08:00
Daniel Imms 11fbdb3db7 Merge pull request #5554 from Tyriar/2117
Add unit test for CSI Ps SP @ - SL
2025-12-30 05:10:44 -08:00
Daniel Imms 88ce0d40e7 Add unit test for CSI Ps SP @ - SL
Part of #2117
2025-12-30 05:04:20 -08:00
Daniel Imms 2785f11860 Merge pull request #5553 from Tyriar/1526
Save cursor and restore more modes
2025-12-30 04:55:51 -08:00
Daniel Imms 857c4529cd Save cursor and restore more modes
Fixes #1526
2025-12-30 04:49:54 -08:00
Daniel Imms d30c3e7204 Merge pull request #5552 from Tyriar/contrib
Rework contributing doc
2025-12-30 04:42:18 -08:00
Daniel Imms 982f5e15ff Merge pull request #5551 from Tyriar/702
Add dimensions API
2025-12-30 04:37:31 -08:00
Daniel Imms ec3e4f2af1 Rework contributing doc
Fixes #5550
2025-12-30 04:33:57 -08:00
Daniel Imms 13914ee01e Remove private use in ImageRenderer 2025-12-30 04:09:56 -08:00
Daniel Imms e27cc2c089 Remove private API access from tests/demo 2025-12-30 04:06:26 -08:00
Daniel Imms 214289aaab Add dimensions API
Fixes #702
2025-12-30 03:58:26 -08:00
Daniel Imms a5af434e3e Merge pull request #5549 from Tyriar/5548
Use OffscreenCanvas over DOM for WidthCache
2025-12-30 03:38:15 -08:00
Daniel Imms a513120348 Get dom/width cache tests passing in node 2025-12-30 03:32:34 -08:00
Daniel Imms ef978b370b Use OffscreenCanvas over DOM for WidthCache
Fixes #5548
2025-12-30 02:57:09 -08:00
Daniel Imms 00ad3eac40 Merge pull request #5547 from Tyriar/3433
Serialize scroll region
2025-12-29 07:59:49 -08:00
Daniel Imms 29d3eb2e52 Serialize scroll region
fixes #3433
2025-12-29 07:53:43 -08:00
Daniel Imms 8b594140e9 Merge pull request #5546 from Tyriar/progress
Add progress indicator custom glyphs (EE00-EE0B)
2025-12-29 07:37:53 -08:00
Daniel Imms 7cf48c1eb5 Add progress indicator custom glyphs (EE00-EE0B)
Fixes #5478
2025-12-29 07:31:52 -08:00
Daniel Imms 8e6b6e7464 Merge pull request #5545 from Tyriar/nf
Add nerd fonts test button
2025-12-29 06:39:13 -08:00
Daniel Imms 1b0554714b Add nerd fonts test button
Fixes #5544
2025-12-29 06:33:27 -08:00
Daniel Imms abdfa2628c Merge pull request #5543 from Tyriar/underline_inspect
Report underline attributes in demo cell inspector
2025-12-29 06:23:38 -08:00
Daniel Imms 5b4d794f7a Report underline attributes in demo cell inspector 2025-12-29 06:17:36 -08:00
Daniel Imms 9eb1da79e3 Merge pull request #5542 from Tyriar/4064
Make curly underline more vivid
2025-12-29 06:14:01 -08:00
Daniel Imms d4ba4c109b Make curly underline more vivid
Fixes #4064
2025-12-29 06:04:29 -08:00
Daniel Imms 1ad23d6081 Merge pull request #5539 from Tyriar/ris
Add RIS metadata comment
2025-12-29 05:06:07 -08:00
Daniel Imms 73c01cae89 Merge pull request #5541 from Tyriar/4114
Fix fit using correct dims on demo
2025-12-29 05:03:58 -08:00
Daniel Imms 5174a7310f Add RIS metadata comment
Fixes #5043
2025-12-29 05:00:13 -08:00
Daniel Imms 1d793c9054 Fix fit using correct dims on demo
This doesn't add the debounce suggested in the issue, but it does
comment about it.

Fixes #4114
2025-12-29 04:58:12 -08:00
Daniel Imms 1b7c61a6fc Merge pull request #5540 from Tyriar/4855
Fix decorations with height > 1
2025-12-29 04:20:51 -08:00
Daniel Imms 9780b44115 Fix decorations with height > 1
Fixes #4855
2025-12-29 04:14:56 -08:00
Daniel Imms 8d532a35c4 Merge pull request #5538 from Tyriar/4731_mobile_warn
Update viewport dims when dpr changes
2025-12-28 16:36:30 -08:00
Daniel Imms d6df8d7902 Update viewport dims when dpr changes
Fixes #4731
2025-12-28 16:30:44 -08:00
Daniel Imms 4b9566cef0 Merge pull request #5535 from Tyriar/5408_2
Fix firefox selection when in shadow dom take 2
2025-12-28 16:05:49 -08:00
Daniel Imms b30bb1e3b0 Fix stack overflow 2025-12-28 15:59:29 -08:00
Loïc Mangeonjean d67e73a4da fix(fit-addon): call getComputedStyle on the right window element 2025-12-28 15:55:21 -08:00
Loïc Mangeonjean e7434a932d fix: fix computed style computation on firefox inside a shadow dom 2025-12-28 15:55:21 -08:00
Daniel Imms cdb0497d0d Merge pull request #5534 from Tyriar/5184_sync_reset
Force reset to use sync render
2025-12-28 15:22:13 -08:00
Daniel Imms 2fb42c554e Force reset to use sync render
Fixes #5184
2025-12-28 15:16:23 -08:00
Daniel Imms 3632496c94 Merge pull request #5533 from Tyriar/5532
Fix addon build issue on macOS
2025-12-28 15:08:12 -08:00
Daniel Imms a6407fb3c6 Fix addon build issue on macOS
Fixes #5532
2025-12-28 15:02:16 -08:00
Daniel Imms 65aa28464c Merge pull request #5530 from Tyriar/4339
Fix double annoucne of too much output
2025-12-28 14:57:09 -08:00
Daniel Imms 2baad39ccf Fix double annoucne of too much output
Fixes #4339
2025-12-28 14:51:12 -08:00
Daniel Imms c975956f2a Merge pull request #5529 from Tyriar/worktree1
Force a sync render after resize occurs
2025-12-28 14:44:44 -08:00
Daniel Imms 4619a755b1 Force a sync render after resize occurs
Fixes #4922
Related microsoft/vscode#230120
2025-12-28 14:38:42 -08:00
Daniel Imms bc795d36c0 Merge pull request #5528 from Tyriar/4528
Serialize rich underline styles
2025-12-28 14:26:35 -08:00
Daniel Imms b989c5a568 Fix lint 2025-12-28 14:20:55 -08:00
Daniel Imms d66214b25e Serialize rich underline styles 2025-12-28 14:16:53 -08:00
Daniel Imms 6157f523a8 Merge pull request #5523 from Tyriar/4628
Add idle timeout which pauses cursor blink
2025-12-28 14:04:49 -08:00
Daniel Imms 3ab93ea083 Merge pull request #5526 from Tyriar/lint
Remove eol-last eslint rule
2025-12-28 14:04:18 -08:00
Daniel Imms 7ef4c55ca9 Merge pull request #5525 from Tyriar/demo_hover
Implement cell inspector in demo
2025-12-28 13:57:35 -08:00
Daniel Imms d393154271 Remove eol-last eslint rule
This one's just troublesome when working with generated code. It
doesn't make a difference in the end anyway.
2025-12-28 13:56:22 -08:00
Daniel Imms 2c32ef5963 Fix lint 2025-12-28 13:53:03 -08:00
Daniel Imms a730533790 Implement cell inspector in demo
Fixes #5524
2025-12-28 13:50:37 -08:00
Daniel Imms 8a5ffc1bb1 Tidy comments 2025-12-28 13:42:22 -08:00
Daniel Imms a966f7d591 Explain idle in cursorBlink option 2025-12-28 13:41:21 -08:00
Daniel Imms 4985c9f3f9 Use shared constant for idle timeout 2025-12-28 13:37:25 -08:00
Daniel Imms 2e1651badd Pull dom renderer blink management into class 2025-12-28 13:35:57 -08:00
Daniel Imms 7d1f74fb8b Use const enums for constants 2025-12-28 13:33:51 -08:00
Daniel Imms f8c1f5a32f Add idle timeout which pauses cursor blink
Fixes #4628
2025-12-28 13:30:58 -08:00
Daniel Imms 79944f7524 Merge pull request #5521 from Tyriar/5314
Add quirks setting to control DECSET/DECRST 12
2025-12-28 08:07:47 -08:00
Daniel Imms 52b6710b19 Hide quirks from demo for now 2025-12-28 08:01:56 -08:00
Daniel Imms 2a283a307c Fix lint 2025-12-28 07:56:31 -08:00
Daniel Imms ab4524873b Add test for DECSET quirks 2025-12-28 07:49:12 -08:00
Daniel Imms eb5f0d709a Merge pull request #5522 from Tyriar/5295
Note in API that reflowCursorLine will not move the cursor
2025-12-28 07:43:50 -08:00
Daniel Imms 8a8f262616 Note in API that reflowCursorLine will not move the cursor
Fixes #5295
2025-12-28 07:37:50 -08:00
Daniel Imms ca5a681363 Add quirks setting to control DECSET/DECRST 12
Fixes #5314
2025-12-28 07:34:55 -08:00
Daniel Imms fb10cd62c9 Merge pull request #5520 from Tyriar/4961
Ignore soft hyphen
2025-12-27 14:57:12 -08:00
Daniel Imms 28b62a5e0b Ignore soft hyphen
Fixes #4961
2025-12-27 14:51:07 -08:00
Daniel Imms bedf7e8326 Merge pull request #5519 from Tyriar/5444
Add onBeforeSearch and onAfterSearch APIs
2025-12-27 14:38:30 -08:00
Daniel Imms f50028abce Add onBeforeSearch and onAfterSearch APIs
Fixes #5444
2025-12-27 14:32:39 -08:00
Daniel Imms 7a4c9cadff Merge pull request #5518 from Tyriar/style
Demo: Improve style, remove headers from windows
2025-12-27 09:03:02 -08:00
Daniel Imms 01c1c477c3 Demo: Improve style, remove headers from windows 2025-12-27 08:57:26 -08:00
Daniel Imms 33daadb4ea Merge pull request #5516 from Tyriar/activeMatchBg
Ensure activeMatchBackground decoration is on top
2025-12-27 08:04:50 -08:00
Daniel Imms ef6013aac9 Merge pull request #5517 from Tyriar/demo_addons
Demo: Add addon tabs, shuffle order
2025-12-27 08:04:31 -08:00
Daniel Imms 82f24ad5a5 Demo: Add addon tabs, shuffle order 2025-12-27 06:47:17 -08:00
Daniel Imms 97c435862b Merge pull request #5439 from nya3jp/keydup
Fix key duplication on Android with physical keyboards
2025-12-27 06:38:28 -08:00
Daniel Imms 6488e839a1 Merge branch 'master' into keydup 2025-12-27 06:32:16 -08:00
Daniel Imms 5d3564bb38 Ensure activeMatchBackground decoration is on top
Fixes #5369
2025-12-27 06:30:02 -08:00
Daniel Imms 50985d30f9 Merge pull request #5515 from Tyriar/5457_ctrl+slash
Add ctrl+/ -> ^_ keybinding
2025-12-27 06:05:48 -08:00
Daniel Imms 733e48ec73 Add ctrl+/ -> ^_ keybinding
Fixes #5457
2025-12-27 05:57:43 -08:00
Daniel Imms 057fefd39e Merge pull request #5514 from Tyriar/demo6
Ensure types are checked in demo, fix errors, emit to out-demo
2025-12-27 05:40:41 -08:00
Daniel Imms 4d48f8624b Ensure types are checked in demo, fix errors, emit to out-demo
Part of #5509
2025-12-27 05:31:21 -08:00
Daniel Imms 995b491a7a Merge pull request #5513 from Tyriar/esbuild_warn
Set esbuild log level to warning
2025-12-27 05:23:44 -08:00
Daniel Imms 4fe118a8ff Set esbuild log level to warning
This suppresses a safe to ignore debug log in server task
2025-12-27 05:18:00 -08:00
Daniel Imms 45375c94e2 Merge pull request #5512 from Tyriar/demo_server
Move server.js to TypeScript
2025-12-27 05:12:14 -08:00
Daniel Imms f83760d027 Add esbuild server build task 2025-12-27 04:57:55 -08:00
Daniel Imms 1a1bdefc83 Move server to TS
Fixes #5509
2025-12-27 04:36:18 -08:00
Daniel Imms e28db9e8a9 Merge pull request #5511 from Tyriar/settings
Simplify vscode settings
2025-12-27 04:09:31 -08:00
Daniel Imms be5f510bfb Merge pull request #5510 from Tyriar/dev
Make default build task use a single terminal via concurrently
2025-12-27 04:07:16 -08:00
Daniel Imms ac6b8ebb10 Simplify vscode settings 2025-12-27 04:03:24 -08:00
Daniel Imms 1ada355048 Make default build task use a single terminal via concurrently 2025-12-27 03:41:47 -08:00
Daniel Imms 4ce3e3106b Merge pull request #5508 from Tyriar/demo4
Fix css not being used in demo
2025-12-27 03:15:58 -08:00
Daniel Imms 942aff6af7 Merge pull request #5507 from Tyriar/ts5.9
Upgrade to typescript 5.9.3
2025-12-27 03:14:38 -08:00
Daniel Imms 635b898dc0 Fix css not being used in demo 2025-12-27 03:09:39 -08:00
Daniel Imms e01d1f2f17 Upgrade to typescript 5.9.3 2025-12-27 03:06:14 -08:00
Daniel Imms bd16eeed90 Merge pull request #5506 from Tyriar/shared_compile
Fix type error in SharedRendererTests.ts
2025-12-27 03:01:27 -08:00
Daniel Imms df8f9fc519 Merge pull request #5505 from Tyriar/canvasExceptions
Remove unused skip canvas exceptions from playwright
2025-12-27 02:59:27 -08:00
Daniel Imms 373bf513f1 Fix type error in SharedRendererTests.ts 2025-12-27 02:55:43 -08:00
Daniel Imms 25a5497329 Remove unused skip canvas exceptions from playwright 2025-12-27 02:53:28 -08:00
Daniel Imms 4406043e6b Merge pull request #5504 from Tyriar/onRender_headless
Implement onRender in xterm-headless
2025-12-26 11:33:01 -08:00
Daniel Imms 82f961f76f Move new onRender behavior into headless Terminal impl 2025-12-26 11:27:38 -08:00
Daniel Imms a26471b9f3 Implement onRender in xterm-headless
This effectively enabled implementing an efficient renderer on top
of xterm-headless. See #5392
2025-12-26 11:19:59 -08:00
Daniel Imms ba989a6e6c Merge pull request #5503 from Tyriar/copilot_approve
Add some npm scripts that copilot can approve
2025-12-26 11:16:36 -08:00
Daniel Imms d4f725c649 Merge pull request #5502 from Tyriar/xtversion
Support reporting XTVERSION
2025-12-26 11:13:53 -08:00
Daniel Imms 79f5198b2d Add some npm scripts that copilot can approve 2025-12-26 11:10:53 -08:00
Daniel Imms d8a93b757a Support reporting XTVERSION
Fixes #5342
2025-12-26 11:06:55 -08:00
Daniel Imms 9453634f56 Merge pull request #5501 from Tyriar/demo3
Make clear css file is for index.html
2025-12-26 10:59:43 -08:00
Daniel Imms 10e12cf743 Make clear css file is for index.html
Follow up on #5500
2025-12-26 10:54:07 -08:00
Daniel Imms 79621a4e3f Merge pull request #5500 from Tyriar/demo2
More demo refactors
2025-12-26 10:51:49 -08:00
Daniel Imms 546c5e081d Inline simplified style to test.html 2025-12-26 10:46:27 -08:00
Daniel Imms e6ad59b1b1 Disable grid layout in test.html 2025-12-26 10:38:39 -08:00
Daniel Imms 8eab98b78d Change banner bg color 2025-12-26 04:41:05 -08:00
Daniel Imms 0ed6fd0db6 Fix order of init 2025-12-26 04:40:22 -08:00
Daniel Imms e3f87ab8a1 More move handlers into addons and test window 2025-12-26 04:36:51 -08:00
Daniel Imms 8119bb0a4a Simplify window interaction 2025-12-26 04:31:06 -08:00
Daniel Imms dc0d7c81d9 Add terminal and addon refs to all windows 2025-12-26 04:24:07 -08:00
Daniel Imms fa87ecdc4e Move more handlers into testWindow.ts 2025-12-26 04:15:13 -08:00
Daniel Imms b82e8f345f Move more handlers out, addon types into shared file 2025-12-26 04:09:24 -08:00
Daniel Imms 02e9e56eef Move more handlers into testWindow.ts 2025-12-26 04:04:08 -08:00
Daniel Imms 4fffb96f25 Move addCjk into window, move window interactions out of createTerminal 2025-12-26 03:51:01 -08:00
Daniel Imms 6fe5a124ca Merge pull request #5498 from Tyriar/demo
Improve demo
2025-12-26 03:29:03 -08:00
Daniel Imms f62043de91 Merge pull request #5497 from xtermjs/Tyriar-patch-1
Box Elements -> Block Elements
2025-12-25 04:27:12 -08:00
Daniel Imms 55e5ec6037 Box Elements -> Block Elements 2025-12-25 04:21:47 -08:00
Daniel Imms 7b2a5cb50f Merge pull request #5496 from xtermjs/Tyriar-patch-1
Replace range separator with hyphen
2025-12-25 04:05:17 -08:00
Daniel Imms 8740dcda4d Replace range separator with hyphen 2025-12-25 03:59:54 -08:00
Daniel Imms c046f5b4b1 More refactors 2025-12-25 03:41:47 -08:00
Daniel Imms 6bde923f07 Register the windows 2025-12-24 17:09:20 -08:00
Daniel Imms 40b2bbef34 Improve demo by making full screen, add control bar 2025-12-24 16:43:35 -08:00
Daniel Imms c04806fc92 Merge pull request #5495 from Tyriar/tyriar/git_branch
Support custom glyphs for Git Branch Symbols (PUA U+F5D0-U+F60D)
2025-12-24 16:42:45 -08:00
Daniel Imms 8b1306f46d More polish 2025-12-24 16:13:11 -08:00
Daniel Imms 6612153c44 Add alignment tests 2025-12-24 16:10:36 -08:00
Daniel Imms 2be529ce85 Polish definitions 2025-12-24 16:05:42 -08:00
Daniel Imms 96aa97ce11 Add extended symbols 2025-12-24 15:51:00 -08:00
Daniel Imms 98f4c3128c Stub second batch of glyphs 2025-12-24 15:35:46 -08:00
Daniel Imms ce1ab6fdc4 Correct order or curved glyphs 2025-12-24 15:31:49 -08:00
Daniel Imms e87e0f5443 Add git branch symbol alignment tests 2025-12-24 15:27:30 -08:00
Daniel Imms 4a8d8bd247 Partially implement git branch symbols
Part of #5477
2025-12-24 15:03:28 -08:00
Daniel Imms edf100a24b Merge pull request #5494 from Tyriar/tyriar/scale
Add char-based custom glyph scaling
2025-12-24 13:23:23 -08:00
Daniel Imms ed2d8b8fdc Merge branch 'master' into tyriar/scale 2025-12-24 12:36:32 -08:00
Daniel Imms faeefb53bf Merge pull request #5481 from BattlefieldDuck/fix/incorrect-theme-reference
Fix incorrect ITheme reference in comments
2025-12-24 12:29:40 -08:00
Daniel Imms 32ff1f2115 Merge pull request #5492 from Tyriar/sinon
Remove need for sinon
2025-12-24 12:25:41 -08:00
Daniel Imms acb59daf33 Fix lint 2025-12-24 12:20:12 -08:00
Daniel Imms a3d6bf6710 Merge pull request #5493 from Tyriar/tyriar/node
Upgrade missed parts from node 18 -> 22
2025-12-24 12:10:26 -08:00
Daniel Imms 5e5c623d8b Create test ts project in ligatures addon 2025-12-24 12:09:28 -08:00
Daniel Imms 168520f727 Upgrade missed parts from node 18 -> 22 2025-12-24 11:39:10 -08:00
Daniel Imms 23f61911e2 Remove need for sinon 2025-12-24 11:35:20 -08:00
Daniel Imms 491fa5586a Merge pull request #5491 from Tyriar/jsdom
Upgrade jsdom
2025-12-24 11:33:33 -08:00
Daniel Imms 2f549d74ae Merge pull request #5490 from Tyriar/lint
Update eslint and nyc
2025-12-24 11:26:35 -08:00
Daniel Imms 9df2430433 Upgrade jsdom 2025-12-24 11:26:19 -08:00
Daniel Imms ce9f6275ed Fix lint-api 2025-12-24 11:19:06 -08:00
Daniel Imms 9ca04799fe Merge remote-tracking branch 'origin/master' into lint 2025-12-24 11:16:01 -08:00
Daniel Imms 83757d1bf0 Polish arrow strokes 2025-12-24 11:13:58 -08:00
Daniel Imms 60fa9122a2 Remove old yarn rule and regen package lock 2025-12-24 10:46:59 -08:00
Daniel Imms a8d40a1edf Update eslint and nyc 2025-12-24 10:44:46 -08:00
Daniel Imms 78cc07f88a Split arrow parts into hybrid scaling 2025-12-24 10:30:34 -08:00
Daniel Imms 72d7c69a29 Add char-based custom glyph scaling
Draw calls can now be scaled by the char bounding box instead of the
cell bounding box. This means these character won't be stretched. Both
can also be used at the same like as is the case with 1FBBC RIGHT OPEN
SQUARED DOT.

Fixes #5488
2025-12-24 10:19:11 -08:00
Daniel Imms 0e0b445784 Merge pull request #5487 from Tyriar/tyriar/5480
Move customGlyphs option into webgl addon
2025-12-24 08:46:27 -08:00
Daniel Imms 5d24866042 Move customGlyphs option into webgl addon
Fixes #5480
2025-12-24 08:35:06 -08:00
Daniel Imms cbea462737 Merge pull request #5486 from Tyriar/tyriar/powerline_extra
Implement remaining powerline extra symbols
2025-12-24 08:23:39 -08:00
Daniel Imms a3ae94af1d Correct range 2025-12-24 08:18:19 -08:00
Daniel Imms 0e35521810 Add powerline alignment tests 2025-12-24 08:15:50 -08:00
Daniel Imms 40590fedfa Merge branch 'master' into tyriar/powerline_extra 2025-12-24 08:07:37 -08:00
Daniel Imms 1551d94de4 Implement remaining powerline extra symbols
- Uses fontforge + helper bin/convert_svg_to_custom_glyph.js
- Some of these are very large. They'll be much smaller after gzip but
  if this becomes a problem we can compile the svgs into a binary format

Fixes #5479
2025-12-24 08:06:20 -08:00
Daniel Imms d605803866 Merge pull request #5485 from Tyriar/tyriar/braille
Support custom gylphs for braille patterns (U+2800-U+28FF)
2025-12-24 07:09:40 -08:00
Daniel Imms a797852dfd Support custom gylphs for braille patterns (U+2800-U+28FF)
Fixes #5476
2025-12-24 07:00:53 -08:00
Daniel Imms d42f2b54ff Merge pull request #5484 from Tyriar/tyriar/fix_sextants
Fix sextant rendering
2025-12-24 06:43:57 -08:00
Daniel Imms 79084c3066 Fix sextant rendering
Broke in #5483
2025-12-24 06:38:21 -08:00
Daniel Imms b4f4946cca Merge pull request #5483 from Tyriar/glyph_cleanup
Consolidate custom glyph definition parts
2025-12-24 06:21:11 -08:00
Daniel Imms ed779b9062 Replace PATH_FUNCTION_WITH_WEIGHT with a generic strokeWidth prop 2025-12-24 06:14:41 -08:00
Daniel Imms 20fdfba16f Replace BLOCK_PATTERN_WITH_REGION with new clipPath 2025-12-24 04:33:32 -08:00
Daniel Imms 11dae84ff7 Support clip path on any draw definition 2025-12-24 04:25:59 -08:00
Daniel Imms 579573e77d Merge pull request #5482 from xtermjs/Tyriar-patch-1
Remove line ending editorconfig file
2025-12-24 04:24:04 -08:00
Daniel Imms 2114abe88c Support multiple glyphs with multiple draw calls 2025-12-24 04:19:14 -08:00
Daniel Imms d4fd96639f Remove line ending editorconfig file
This is normalized by git and ends up causing git status to show files that don't actually need to be committed after line ending normalization.
2025-12-24 04:18:31 -08:00
Daniel Imms 269d8c20ae Merge pull request #5475 from Tyriar/depc
Remove remnants of deprecated options
2025-12-24 04:03:49 -08:00
TatLead 49b49627f1 Fix incorrect ITheme reference in comments 2025-12-24 07:10:12 +08:00
Daniel Imms 663b94011a Remove remnants of deprecated options
Following up on #5462
2025-12-23 08:24:35 -08:00
Daniel Imms 54fcb1ea2f Merge pull request #5474 from Tyriar/demo_warn
Fix warnings in demo
2025-12-23 08:17:29 -08:00
Daniel Imms a9da3fbf05 Merge pull request #5473 from Tyriar/tyriar/5466_legacy_computing
Support entire Symbols for Legacy Computing unicode block (0x1FB00-0x1FBFF), add missing powerline symbol
2025-12-23 08:15:05 -08:00
Daniel Imms 091c3967f7 Fix warnings in demo 2025-12-23 08:12:12 -08:00
Daniel Imms 10d6ce3805 Update customGlyphs option 2025-12-23 08:09:46 -08:00
Daniel Imms eb285af11d Add diagonal alignment tests 2025-12-23 08:05:02 -08:00
Daniel Imms 0976935f87 Implement remaining Terminal graphic characters (1FBC0-1FBCA) 2025-12-23 07:42:57 -08:00
Daniel Imms 884b667f4e Implement stick figures 1FBC5-1FBC9 2025-12-23 07:04:19 -08:00
Daniel Imms b8843732bf Implement Terminal graphic characters (1FBCB-1FBCD) 2025-12-23 04:49:46 -08:00
Daniel Imms 44d8d2c873 Finish implementing Terminal graphic characters (1FBB9-1FBBC) 2025-12-23 04:28:45 -08:00
Daniel Imms 3d3abf9cf2 Implement folder 1FBB9-1FBBA 2025-12-23 04:22:19 -08:00
Daniel Imms 268f7af5db Implement running man 1FBB2 and 1FBB3 2025-12-23 04:15:41 -08:00
Daniel Imms 16b72dfd63 Mark powerline symbol range as reserved 2025-12-23 03:50:34 -08:00
Daniel Imms a0e658a18c Add column number powerline symbol 2025-12-23 03:42:41 -08:00
Daniel Imms ea6385f310 Comment alignment 2025-12-23 03:39:37 -08:00
Daniel Imms 02a9d2b047 Indicate reserved codepoints in demo 2025-12-23 03:30:02 -08:00
Daniel Imms 5c0c553936 Implement Arrows (1FBB4-1FBB8) 2025-12-22 19:46:35 -08:00
Daniel Imms eb743e0e19 Implement Terminal graphic character (1FBFA-1FBFA) 2025-12-22 19:15:00 -08:00
Daniel Imms 29d91fe264 Fill in remaining parts of legacy computing 2025-12-22 16:27:41 -08:00
Daniel Imms e8dcf46f39 Add PATH_NEGATIVE, simplify 1FBBD-1FBBF 2025-12-22 16:22:06 -08:00
Daniel Imms 66c1316f87 Implement ARROWHEAD-SHAPED POINTER 2025-12-22 15:43:53 -08:00
Daniel Imms e1803ed5a5 Implement Triangular shade characters (1FB9C-1FB9F) 2025-12-22 15:30:55 -08:00
Daniel Imms 1c3813f3d4 Implement Negative terminal graphic characters (1FBBD-1FBBF) 2025-12-22 15:28:51 -08:00
Daniel Imms e12aef9287 Implement Block elements (1FBCE-1FBCF) 2025-12-22 15:21:10 -08:00
Daniel Imms f5edba0b64 Improve docs on segmentedDigit 2025-12-22 15:18:42 -08:00
Daniel Imms 5a995e5595 Implement Geometric shapes (1FBE0-1FBEF) 2025-12-22 15:14:40 -08:00
Daniel Imms 2bae212f83 Implement Character cell diagonals (1FBD0-1FBDF) 2025-12-22 14:19:02 -08:00
Daniel Imms bde3680cd1 Implement 2 more parts 2025-12-22 14:15:26 -08:00
Daniel Imms 717399ceb6 Implement diagonal fill chars and light solid line with stroke 2025-12-22 14:04:51 -08:00
Daniel Imms 51121f1913 Stub legacy computing custom glyph ranges
Part of #5466
2025-12-22 13:42:38 -08:00
Daniel Imms 483acd3335 Merge pull request #5472 from Tyriar/tyriar/5466_refactor__unified
Custom glyph: Unify rendering function and move all definitions into a single ordered object
2025-12-22 13:31:36 -08:00
Daniel Imms 9dc8cecea3 Fix imports 2025-12-22 13:04:44 -08:00
Daniel Imms 89c2649504 Merge branch 'master' into tyriar/5466_refactor__unified 2025-12-22 12:57:03 -08:00
Daniel Imms 390076fc3f Order box drawing consistently 2025-12-22 12:56:16 -08:00
Daniel Imms a4edeed85d Add box drawing to custom glyph ranges test 2025-12-22 12:48:23 -08:00
Daniel Imms e61697fc86 Start organizing box drawing characters 2025-12-22 12:46:43 -08:00
Daniel Imms 9c019b44c3 unified -> customGlyph 2025-12-22 12:39:31 -08:00
Daniel Imms 5579d83f7d Move box drawing into unified 2025-12-22 12:39:14 -08:00
Daniel Imms 429065487a Move block elements and like into unified 2025-12-22 12:34:12 -08:00
Daniel Imms 219036cb0f Add powerline to glyph ranges test 2025-12-22 12:26:58 -08:00
Daniel Imms 3e80637145 Move powerline to unified 2025-12-22 12:14:50 -08:00
Daniel Imms 0af884d379 Correct shade rectangle rendering 2025-12-22 12:09:41 -08:00
Daniel Imms 5ae9ddf4b8 Add range to headers in ranges test 2025-12-22 12:06:59 -08:00
Daniel Imms 7ac068844c Fix warnings in unicodeTables.ts 2025-12-22 12:06:27 -08:00
Daniel Imms 5bf3d57d16 Move rectangular shade chars into unified 2025-12-22 12:05:47 -08:00
Daniel Imms 6461829411 Clean up symbols for legacy def 2025-12-22 11:48:45 -08:00
Daniel Imms efd6a52033 Support path without function 2025-12-22 11:46:53 -08:00
Daniel Imms 3d9e976cb3 Move main symbols for legacy computing into unified 2025-12-22 11:41:49 -08:00
Daniel Imms 415de67106 Start move to unified draw definition
Part of #5466
2025-12-22 11:35:41 -08:00
Daniel Imms c17c01086f Merge pull request #5471 from Tyriar/tyriar/5466_refactor
Refactor custom glyph to move into folder, split definition from raster
2025-12-22 11:34:43 -08:00
Daniel Imms ce41b175ee Remove cyclic dep 2025-12-22 11:11:50 -08:00
Daniel Imms 32b4547c5a Tweak symbol names 2025-12-22 11:09:02 -08:00
Daniel Imms b64543aa59 Make medium shade consistent, make all shades less heavy 2025-12-22 10:57:59 -08:00
Daniel Imms f049c42acc Add CustomGlyph to exports from rasterizer 2025-12-22 10:48:50 -08:00
Daniel Imms 28760cf482 Move custom glyphs into new folder 2025-12-22 10:47:35 -08:00
Daniel Imms 4982305b51 Split definitions and rasterizer 2025-12-22 10:46:53 -08:00
Daniel Imms 7fee40ddcd Merge pull request #5470 from Tyriar/tyriar/5466_shade
Custom glyph support for rectangular shade/combo chars
2025-12-22 10:41:54 -08:00
Daniel Imms 180183e876 Custom glyph support for rectangular shade/combo chars
Range: U+1FB8C-U+1FB94

Part of #5466
2025-12-22 10:29:22 -08:00
Daniel Imms 8308ede3f5 Merge pull request #5468 from Tyriar/5466_mosaic
Custom glyph support for mosaic terminal graphics chars
2025-12-22 10:27:53 -08:00
Daniel Imms a6db7b41f6 Suppress naming-convention for file as it conflicts with unicode props 2025-12-22 08:34:43 -08:00
Daniel Imms f11241d9de Custom glyph support for mosaic terminal graphics chars
Range: U+1FB3C-U+1FB6F

Part of #5466
2025-12-22 08:29:03 -08:00
Daniel Imms 937deb9f4b Merge pull request #5467 from Tyriar/5464_block_sextants
Custom glyph support for block sextants (U+1FB00-U+1FB3B)
2025-12-22 08:27:29 -08:00
Daniel Imms 6acc861b06 Lint 2025-12-22 07:54:47 -08:00
Daniel Imms 8f05b1854b Lint 2025-12-22 07:41:18 -08:00
Daniel Imms 0f461e7a3e Custom glyph support for block sextants (U+1FB00-U+1FB3B)
Fixes #5464
2025-12-22 07:33:43 -08:00
Daniel Imms 4237d82923 Merge pull request #5465 from Tyriar/5464_demo_helper
Add demo helper to print Symbols for Legacy Computing
2025-12-22 07:26:42 -08:00
Daniel Imms 187156764a Add demo helper to print Symbols for Legacy Computing
Range: 1FB00–1FBFF

Part of #5464
2025-12-22 07:16:22 -08:00
Shuhei Takahashi d03416467d Fix key duplication on Android with physical keyboards
When typing rapidly on Android with physical keyboards, characters often
duplicate on the terminal. This is because physical keyboard events
always go through IME on Android, even for plain English characters, and
rapid typing causes a race condition in the composition helper.

This patch fixes the issue by making sure textarea changes are handled
correctly.
2025-11-07 12:33:59 +09:00
Jörg Breitbart 085a275038 fix promise return, reject on missing family name, doc polish 2024-10-06 23:53:30 +02:00
Jörg Breitbart 104c63d7e0 cleanup files 2024-10-04 17:52:45 +02:00
Jörg Breitbart 70c9861c39 Merge branch 'master' into webfonts-addon 2024-10-04 17:51:18 +02:00
Jörg Breitbart c93623cb3b CI tests 2024-10-04 14:24:36 +02:00
Jörg Breitbart b0389a2ed1 future proof demo 2024-10-04 05:31:47 +02:00
Jörg Breitbart 7907f13774 add license notes for fonts 2024-10-04 04:14:10 +02:00
Jörg Breitbart 956c7cbcba demo tests 2024-10-04 04:00:20 +02:00
Jörg Breitbart 23bef99132 cleanup API 2024-10-04 02:06:02 +02:00
Jörg Breitbart b104bcd144 remove await remnants 2024-10-04 00:42:38 +02:00
Jörg Breitbart 809b9aa1ad fix test runner 2024-10-04 00:15:49 +02:00
Jörg Breitbart 9a536f758d fix integration test runner 2024-10-03 22:23:31 +02:00
Jörg Breitbart 15a63bae22 change to global replacement 2024-10-03 22:10:40 +02:00
Jörg Breitbart 41640d9402 make linter happy 2024-10-03 22:07:10 +02:00
Jörg Breitbart 15664de472 initial 2024-10-03 21:50:34 +02:00
194 changed files with 18026 additions and 9617 deletions
+2 -2
View File
@@ -1,9 +1,9 @@
{
"name": "xterm.js",
"image": "mcr.microsoft.com/devcontainers/typescript-node:18-bookworm",
"image": "mcr.microsoft.com/devcontainers/typescript-node:22-bookworm",
"features": {
"ghcr.io/devcontainers/features/node:1": {
"version": 18
"version": 22
} // yarn
},
"forwardPorts": [
-1
View File
@@ -5,7 +5,6 @@ indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
end_of_line = lf
[*.{j,t}s]
max_line_length = 100
-273
View File
@@ -1,273 +0,0 @@
{
"env": {
"browser": true,
"es2021": true,
"node": true
},
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": [
"demo/tsconfig.json",
"src/browser/tsconfig.json",
"src/common/tsconfig.json",
"src/headless/tsconfig.json",
"src/vs/tsconfig.json",
"test/benchmark/tsconfig.json",
"test/playwright/tsconfig.json",
"addons/addon-attach/src/tsconfig.json",
"addons/addon-attach/test/tsconfig.json",
"addons/addon-clipboard/src/tsconfig.json",
"addons/addon-clipboard/test/tsconfig.json",
"addons/addon-fit/src/tsconfig.json",
"addons/addon-fit/test/tsconfig.json",
"addons/addon-image/src/tsconfig.json",
"addons/addon-image/test/tsconfig.json",
"addons/addon-ligatures/src/tsconfig.json",
"addons/addon-progress/src/tsconfig.json",
"addons/addon-progress/test/tsconfig.json",
"addons/addon-search/src/tsconfig.json",
"addons/addon-search/test/tsconfig.json",
"addons/addon-serialize/src/tsconfig.json",
"addons/addon-serialize/test/tsconfig.json",
"addons/addon-serialize/benchmark/tsconfig.json",
"addons/addon-unicode11/src/tsconfig.json",
"addons/addon-unicode11/test/tsconfig.json",
"addons/addon-unicode-graphemes/src/tsconfig.json",
"addons/addon-unicode-graphemes/test/tsconfig.json",
"addons/addon-unicode-graphemes/benchmark/tsconfig.json",
"addons/addon-web-links/src/tsconfig.json",
"addons/addon-web-links/test/tsconfig.json",
"addons/addon-webgl/src/tsconfig.json",
"addons/addon-webgl/test/tsconfig.json"
],
"sourceType": "module"
},
"ignorePatterns": [
"addons/*/src/third-party/*.ts",
"src/vs/*",
"out/*",
"out-test/*",
"out-esbuild/*",
"out-esbuild-test/*",
"**/inwasm-sdks/*",
"**/typings/*.d.ts",
"**/node_modules",
"**/*.js",
"**/*.mjs"
],
"plugins": [
"@stylistic/ts",
"@typescript-eslint",
"jsdoc"
],
"rules": {
"@stylistic/ts/indent": [
"warn",
2
],
"@stylistic/ts/semi": [
"warn",
"always"
],
"@stylistic/ts/quotes": [
"warn",
"single",
{ "allowTemplateLiterals": true }
],
"@typescript-eslint/array-type": [
"warn",
{
"default": "array",
"readonly": "generic"
}
],
"@typescript-eslint/consistent-type-assertions": "warn",
"@typescript-eslint/consistent-type-definitions": "warn",
"@typescript-eslint/explicit-function-return-type": [
"warn",
{
"allowExpressions": true
}
],
"@typescript-eslint/explicit-member-accessibility": [
"warn",
{
"accessibility": "explicit",
"overrides": {
"constructors": "off"
}
}
],
"@typescript-eslint/member-delimiter-style": [
"warn",
{
"multiline": {
"delimiter": "semi",
"requireLast": true
},
"singleline": {
"delimiter": "comma",
"requireLast": false
}
}
],
"@typescript-eslint/naming-convention": [
"warn",
{ "selector": "default", "format": ["camelCase"],
"filter": {
"regex": "^[a-z]",
"match": true
}
},
// variableLike
{ "selector": "variable", "format": ["camelCase", "UPPER_CASE"] },
{ "selector": "variable", "filter": "^I.+Service$", "format": ["PascalCase"], "prefix": ["I"] },
// memberLike
{ "selector": "memberLike", "modifiers": ["private"], "format": ["camelCase"], "leadingUnderscore": "require" },
{ "selector": "memberLike", "modifiers": ["protected"], "format": ["camelCase"], "leadingUnderscore": "require" },
{ "selector": "enumMember", "format": ["UPPER_CASE"] },
// memberLike - Allow enum-like objects to use UPPER_CASE
{ "selector": "property", "modifiers": ["public"], "format": ["camelCase", "UPPER_CASE"],
"filter": {
"regex": "^[a-z]",
"match": true
}
},
// restrict on* naming for events only
{ "selector": "method", "modifiers": ["public"], "format": ["camelCase", "UPPER_CASE"], "custom": {
"regex": "^on[A-Z].+",
"match": false
} },
{ "selector": "method", "modifiers": ["private"], "format": ["camelCase"], "leadingUnderscore": "require", "custom": {
"regex": "^on[A-Z].+",
"match": false
} },
{ "selector": "method", "modifiers": ["protected"], "format": ["camelCase"], "leadingUnderscore": "require", "custom": {
"regex": "^on[A-Z].+",
"match": false
} },
// typeLike
{ "selector": "typeLike", "format": ["PascalCase"] },
{ "selector": "interface", "format": ["PascalCase"], "prefix": ["I"] }
],
"@typescript-eslint/no-confusing-void-expression": [
"warn",
{ "ignoreArrowShorthand": true }
],
"@typescript-eslint/no-useless-constructor": "warn",
"@typescript-eslint/prefer-namespace-keyword": "warn",
"@typescript-eslint/type-annotation-spacing": "warn",
"comma-dangle": [
"warn",
{
"objects": "never",
"arrays": "never",
"functions": "never"
}
],
"curly": [
"warn",
"multi-line"
],
"eol-last": "warn",
"eqeqeq": [
"warn",
"always"
],
"jsdoc/check-alignment": 1,
"jsdoc/check-param-names": 1,
"jsdoc/no-multi-asterisks": 1,
"keyword-spacing": "warn",
"max-len": [
"warn",
{
"code": 1000, // Don't enforce for code
"comments": 100,
"ignoreTrailingComments": true,
"ignoreUrls": true,
"ignorePattern": "^ *((?<vt_comment>(//|\\*) @vt)|(?<table_comment>\\* \\| )|(?<commented_code>// ))"
}
],
"new-parens": "warn",
"no-duplicate-imports": "warn",
"no-else-return": [
"warn",
{
"allowElseIf": false
}
],
"no-eval": "warn",
"no-extra-semi": "error",
"no-irregular-whitespace": "warn",
"no-restricted-imports": [
"warn",
{
"patterns": [
".*\\/out\\/.*"
]
}
],
"no-restricted-syntax": [
"warn",
{
"selector": "CallExpression[callee.name='requestAnimationFrame']",
"message": "The global requestAnimationFrame() should be avoided, call it on the parent window from ICoreBrowserService."
},
{
"selector": "CallExpression[callee.name='cancelAnimationFrame']",
"message": "The global cancelAnimationFrame() should be avoided, call it on the parent window from ICoreBrowserService."
},
{
"selector": "CallExpression > MemberExpression[object.name='window'][property.name='requestAnimationFrame']",
"message": "window.requestAnimationFrame() should be avoided, call it on the parent window from ICoreBrowserService."
},
{
"selector": "CallExpression > MemberExpression[object.name='window'][property.name='cancelAnimationFrame']",
"message": "window.cancelAnimationFrame() should be avoided, call it on the parent window from ICoreBrowserService."
},
{
"selector": "MemberExpression[object.name='window'][property.name='devicePixelRatio']",
"message": "window.devicePixelRatio should be avoided, get it from ICoreBrowserService."
}
],
"no-trailing-spaces": "warn",
"no-unsafe-finally": "warn",
"no-unused-vars": ["warn", {
"vars": "all",
"args": "none"
}],
"no-var": "warn",
"one-var": [
"warn",
"never"
],
"object-curly-spacing": [
"warn",
"always"
],
"prefer-const": "warn",
"spaced-comment": [
"warn",
"always",
{
"markers": ["/"],
"exceptions": ["-"]
}
]
},
"overrides": [
{
"files": [
"**/*.api.ts",
"**/*.test.ts"
],
"rules": {
"object-curly-spacing": "off",
"max-len": "off",
"no-unused-vars": "off"
}
}
]
}
-107
View File
@@ -1,107 +0,0 @@
{
"env": {
"browser": true,
"es2021": true,
"node": true
},
"parser": "@typescript-eslint/parser",
"plugins": [
"@stylistic/ts",
"@typescript-eslint",
"jsdoc"
],
"rules": {
"@stylistic/ts/indent": [
"warn",
2
],
"@stylistic/ts/semi": [
"warn",
"always"
],
"@stylistic/ts/quotes": [
"warn",
"single",
{ "allowTemplateLiterals": true }
],
"@typescript-eslint/array-type": [
"warn",
{
"default": "array",
"readonly": "generic"
}
],
"@typescript-eslint/explicit-function-return-type": [
"warn",
{
"allowExpressions": true
}
],
"@typescript-eslint/member-delimiter-style": [
"warn",
{
"multiline": {
"delimiter": "semi",
"requireLast": true
},
"singleline": {
"delimiter": "comma",
"requireLast": false
}
}
],
"@typescript-eslint/naming-convention": [
"warn",
{ "selector": "typeLike", "format": ["PascalCase"] },
{ "selector": "interface", "format": ["PascalCase"], "prefix": ["I"] }
],
"@typescript-eslint/prefer-namespace-keyword": "warn",
"@typescript-eslint/type-annotation-spacing": "warn",
"comma-dangle": [
"warn",
{
"objects": "never",
"arrays": "never",
"functions": "never"
}
],
"curly": [
"warn",
"multi-line"
],
"eol-last": "warn",
"eqeqeq": [
"warn",
"always"
],
"jsdoc/check-alignment": 1,
"jsdoc/check-param-names": 1,
"keyword-spacing": "warn",
"max-len": [
"warn",
{
"code": 1000, // Don't enforce for code
"comments": 80,
"ignoreUrls": true,
"ignorePattern": "^ *(?<ps_description>\\* Ps=)"
}
],
"no-extra-semi": "error",
"no-irregular-whitespace": "warn",
"no-trailing-spaces": "warn",
"object-curly-spacing": [
"warn",
"always"
],
"spaced-comment": [
"warn",
"always",
{
"markers": ["/"],
"exceptions": ["-"]
}
]
}
}
+3 -1
View File
@@ -24,7 +24,9 @@ npm run build && npm run esbuild # Build all TypeScript and bundle
- Unit tests filtering to file: `npm run test-unit -- **/fileName.ts
- Per-addon unit tests: `npm run test-unit addons/addon-image/out-esbuild/*.test.js`
- Integration tests: `npm run test-integration` (Playwright across Chrome/Firefox/WebKit)
- Per-addon integration tests: `npm run test-integration --suite=addon-search`
- Integration tests by file: `npm run test-integration -- test/playwright/InputHandler.test.ts`. Never use grep to filter tests, it doesn't work
- Integration tests by addon: `npm run test-integration --suite=addon-search`. Suites always follow the format `addon-<something>`
- Lint changes: `npm run lint-changes` to lint only changed files, `npm run lint-changes-fix` to fix them
## Addon Development Pattern
+9 -2
View File
@@ -62,6 +62,9 @@ jobs:
./addons/addon-web-links/lib/* \
./addons/addon-web-links/out/* \
./addons/addon-web-links/out-*/* \
./addons/addon-web-fonts/lib/* \
./addons/addon-web-fonts/out/* \
./addons/addon-web-fonts/out-*/* \
./addons/addon-webgl/lib/* \
./addons/addon-webgl/out/* \
./addons/addon-webgl/out-*st/*
@@ -199,8 +202,10 @@ jobs:
unzip -o compressed-build.zip
fi
ls -R
- name: Build demo
run: npm run esbuild-demo
- name: Build demo client
run: npm run esbuild-demo-client
- name: Build demo server
run: npm run esbuild-demo-server
- name: Integration tests (core) # Tests use 50% workers to reduce flakiness
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=core
- name: Integration tests (addon-attach)
@@ -221,6 +226,8 @@ jobs:
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-unicode-graphemes
- name: Integration tests (addon-unicode11)
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-unicode11
- name: Integration tests (addon-web-fonts)
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-web-fonts
- name: Integration tests (addon-web-links)
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-web-links
- name: Integration tests (addon-webgl)
+1
View File
@@ -3,6 +3,7 @@ node_modules/
.lock-wscript
lib/
out/
out-demo/
out-test/
out-esbuild/
out-esbuild-test/
-7
View File
@@ -1,7 +0,0 @@
Antonis Kalipetis <akalipetis@sourcelair.com>
Antonis Kalipetis <akalipetis@sourcelair.com> <akalipetis@gmail.com>
Daniel Imms <daimms@microsoft.com> <tyriar@tyriar.com>
Paris Kasidiaris <paris@sourcelair.com>
Paris Kasidiaris <pariskasidiaris@gmail.com>
Thanasis Daglis <thanasis@sourcelair.com>
Thanasis Daglis <thanasis@sourcelair.com> <ath.daglis@gmail.com>
-1
View File
@@ -1 +0,0 @@
NODE_PATH=./out
-5
View File
@@ -1,5 +0,0 @@
require:
- source-map-support/register
reporter: spec
color: true
check-leaks: true
-1
View File
@@ -1 +0,0 @@
package-lock=false
+1 -1
View File
@@ -1 +1 @@
18
22
+5
View File
@@ -0,0 +1,5 @@
{
"recommendations": [
"dbaeumer.vscode-eslint"
]
}
+1 -1
View File
@@ -61,7 +61,7 @@
"runtimeExecutable": "npm",
"runtimeArgs": ["start"],
"stopOnEntry": true,
"runtimeVersion": "18",
"runtimeVersion": "22",
"serverReadyAction": {
"action": "openExternally",
"pattern": "App listening to (http://.*?:[0-9]+)"
+1 -20
View File
@@ -1,23 +1,4 @@
{
"files.associations": {
".eslintrc.json.typings": "jsonc"
},
"files.exclude": {
"**/.nyc_output": true
},
"typescript.preferences.importModuleSpecifier": "non-relative",
"typescript.preferences.quoteStyle": "single",
"mochaExplorer.envPath": ".mocha.env",
"mochaExplorer.files": [
"out/**/*.test.js",
"addons/**/out/*.test.js",
"out-*/**/*.test.js",
"addons/**/out-*/*.test.js"
],
"mochaExplorer.watch": [
"out/**/*.js",
"addons/**/out/*.js",
"out-*/**/*.js",
"addons/**/out-*/*.js"
]
"typescript.preferences.quoteStyle": "single"
}
+25 -4
View File
@@ -10,13 +10,22 @@
"tasks": [
// Compound tasks
{
"label": "Development",
"dependsOn": ["demo-server", "tsc", "esbuild", "esbuild-demo"],
"label": "dev",
"detail": "Runs all tasks required to run the demo in a single terminal using concurrently. This does not support problem matching.",
"type": "npm",
"script": "dev",
"isBackground": true,
"group": {
"kind": "build",
"isDefault": true
}
},
{
"label": "dev (separate terminals)",
"detail": "Runs all tasks required to run the demo in separate terminals. This does support problem matching.",
"dependsOn": ["demo-server", "tsc", "esbuild", "esbuild-demo-client", "esbuild-demo-server"],
"group": "build"
},
// Demo
{
@@ -55,9 +64,21 @@
}
},
{
"label": "esbuild-demo",
"label": "esbuild-demo-client",
"type": "npm",
"script": "esbuild-demo-watch",
"script": "esbuild-demo-client-watch",
"dependsOn": ["esbuild", "tsc"],
"group": "build",
"isBackground": true,
"problemMatcher": "$esbuild-watch",
"presentation": {
"group": "xterm-demo"
}
},
{
"label": "esbuild-demo-server",
"type": "npm",
"script": "esbuild-demo-server-watch",
"dependsOn": ["esbuild", "tsc"],
"group": "build",
"isBackground": true,
+35 -89
View File
@@ -1,104 +1,50 @@
# How to contribute to xterm.js
- [Opening issues for bug reports or feature requests](#opening-issues)
- [Contributing code](#contributing-code)
- [Opening issues](#opening-issues)
- [Answering discussion questions](#answering-discussion-questions)
## Contributing code
You can find issues to work on by looking at issues labeled with [help wanted](https://github.com/xtermjs/xterm.js/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22) or [good first issue](https://github.com/xtermjs/xterm.js/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22). It's a good idea to comment on the issue saying that you're looking into it, just in case someone else comes along and you duplicate work. Once you have your issue, here are the steps to contribute:
- Fork [xterm.js](https://github.com/xtermjs/xterm.js/) ([how to fork a repo](https://help.github.com/articles/fork-a-repo)).
- Get the [xterm.js demo](https://github.com/xtermjs/xterm.js/wiki/Contributing#running-the-demo) running.
- Make the fix and verify it works in the demo. Be sure to follow thew general code style of the rest of the project.
- If your changes are easy to test or likely to regress in the future, add tests. These could be unit or integration (playwright) tests.
- Submit a pull request ([how to create a pull request](https://help.github.com/articles/fork-a-repo)).
> ![TIP]
> Don't put more than one feature or fix in a single pull request. The smaller pull requests are the easier they are to review and merge.
By contributing code to xterm.js you:
- Agree to license the contributed code under xterm.js' [MIT license](LICENSE).
- Confirm that you have the right to contribute and license the code in question. This means that either you hold all rights on the code, or the rights holder has explicitly granted the right to use it like this, through a compatible open source license or through a direct agreement with you.
## Opening issues
The preferred way to report bugs or request features is to use
[GitHub issues](http://github.com/sourcelair/xterm.js/issues). Before
opening an issue, read these pointers.
[GitHub issues](http://github.com/xtermjs/xterm.js/issues).
### Opening issues effectively
### Creating great issues
- Include information about **the browser in which the problem occurred**. Even
if you tested several browsers, and the problem occurred in all of them,
mention this fact in the bug report. Also include browser version numbers and
the operating system that you're on.
- Include information about **the browser in which the problem occurred** or the terminal being used. If you tested several browsers and the problem occurred in all of them, mention this fact in the bug report. Also include browser version numbers and the operating system that you're on.
- Include the version of xterm.js being used, preferably either with the latest `beta` tagged release on npm or reproducing in the demo on the `master` branch.
- Mention precisely what went wrong. What did you expect to happen? What happened instead? Describe the exact steps a maintainer has to take to make the problem occur.
- If the problem can not be reproduced in the [demo of xterm.js](https://github.com/xtermjs/xterm.js/wiki/Contributing#running-the-demo), provide an HTML document that demonstrates the problem.
- Be polite and follow [the code of conduct](https://github.com/xtermjs/xterm.js?tab=coc-ov-file#readme).
- Mention which release of xterm.js you're using. Preferably, try also with
the current HEAD of the master branch, to ensure the problem has not already been
fixed.
### Issue triaging philosophy
- Mention precisely what went wrong. What did you expect to happen? What happened instead? Describe the
exact steps a maintainer has to take to make the problem occur.
It's pretty common for maintainers of large open source projects to suffer from burnout, especially when needing to triage a large number of incoming issues instead of actually building things. Here are some of the steps we take to try mitigate this:
- If the problem can not be reproduced in the [demo of xterm.js](https://github.com/xtermjs/xterm.js/wiki/Contributing#running-the-demo), please provide an HTML document that demonstrates the problem.
- Be polite. Issues with an indignant or belligerent tone tend to be moved to the
bottom of the pile.
- Support questions live in [GH discussions](https://github.com/xtermjs/xterm.js/discussions), issues may be transfered there without further comment and core maintainers may or may not participate in discussions.
- Issues are strictly for well defined features or bugs that are _actionable_.
- Sometimes features are out of scope. A common example of this is a niche feature that the pricipal implementation ([VS Code](https://code.visualstudio.com/)) won't leverage and therefore would be difficult to maintain and likely suffer from bitrot. The reporter may not agree with this, but you could always create an addon if that works or maintain your own fork if it comes to that.
- If a feature does not have a clear way forward or needs more discussion it may be closed ro moved to a discussion.
- If a bug is not easily reproducible it may be closed or moved to a discussion. Generally issues that are labeled are something we want to do or has actionable steps to look into further.
## Answering discussion questions
Issues are only meant to track (likely) feature requests and bugs. We use [GitHub Discussions](https://github.com/xtermjs/xterm.js/discussions) for general Q&A as well as discussing possible features. If you want to help out, many questions get asked over at the [discussions page](https://github.com/xtermjs/xterm.js/discussions) which could use an expert as the core team is often stretched thin.
## Contributing code
You can find issues to work on by looking at the [help wanted](https://github.com/xtermjs/xterm.js/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22) or [good first issue](https://github.com/xtermjs/xterm.js/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) issues. It's a good idea to comment on the issue saying that you're taking it, just in case someone else comes along and you duplicate work. Once you have your issue, here are the steps to contribute:
- Fork [xterm.js](https://github.com/sourcelair/xterm.js/)
([how to fork a repo](https://help.github.com/articles/fork-a-repo)).
- Get the [xterm.js demo](https://github.com/xtermjs/xterm.js/wiki/Contributing#running-the-demo) running.
- Make your changes.
- If your changes are easy to test or likely to regress, add tests. Tests go into `test`, directory.
- Follow the general code style of the rest of the project (see below).
- Submit a pull request
([how to create a pull request](https://help.github.com/articles/fork-a-repo)).
Don't put more than one feature/fix in a single pull request.
By contributing code to xterm.js you:
- Agree to license the contributed code under xterm.js' [MIT
license](LICENSE).
- Confirm that you have the right to contribute and license the code
in question. (Either you hold all rights on the code, or the rights
holder has explicitly granted the right to use it like this,
through a compatible open source license or through a direct
agreement with you.)
### Test coverage
One area that always needs attention is improving out unit test coverage, you can view the code coverage report on [Azure Pipelines](https://dev.azure.com/xtermjs/xterm.js/_build/latest?definitionId=3) by clicking the Code Coverage tab.
## Testing
### Unit tests
Unit tests are run with `npm run test-unit`:
```sh
# All unit tests
npm run test-unit
# Absolute file path
npm run test-unit out-esbuild/browser/Terminal.test.js
# Filter by wildcard
npm run test-unit out-esbuild/**/Terminal.test.js
# Specific addon unit tests tests
npm run test-unit addons/addon-image/out-esbuild/*.test.js
# Multiple files
npm run test-unit out-esbuild/**/Terminal.test.js out-esbuild/**/InputHandler.test.js
```
These use mocha to run all `.test.js` files within the esbuild output (`out-esbuild/`).
### Integration tests
Integration tests are run with `npm run test-integration`:
```sh
# All integration tests
npm run test-integration
# Core integration tests
npm run test-integration --suite=core
# Specific addon integration tests
npm run test-integration --suite=addon-search
```
These use `@playwright/test` to run all tests within the esbuild test output (`out-esbuild-test/`).
Issues are only meant to track (likely) feature requests and bugs. We use [GitHub Discussions](https://github.com/xtermjs/xterm.js/discussions) for general Q&A as well as discussing possible features. If you want to help out, many questions get asked over at the [discussions page](https://github.com/xtermjs/xterm.js/discussions) which could use an expert as the core team is often stretched thin.
+27 -28
View File
@@ -1,27 +1,27 @@
# [![xterm.js logo](images/logo-full.png)](https://xtermjs.org)
# [![xterm.js](images/logo-full.png)](https://xtermjs.org)
Xterm.js is a front-end component written in TypeScript that lets applications bring fully-featured terminals to their users in the browser. It's used by popular projects such as VS Code, Hyper and Theia.
Xterm.js is a frontend component that enables applications to bring fully-featured terminals to their users in the browser. It's used by popular projects such as [VS Code](https://code.visualstudio.com/) (and its forks), [Tabby](https://tabby.sh/) and [Hyper](https://hyper.is/).
## Features
- **Terminal apps just work**: Xterm.js works with most terminal apps such as `bash`, `vim`, and `tmux`, including support for curses-based apps and mouse events.
- **Performant**: Xterm.js is *really* fast, it even includes a GPU-accelerated renderer.
- **Performant**: Xterm.js is *really* fast and includes an optional GPU-accelerated renderer.
- **Rich Unicode support**: Supports CJK, emojis, and IMEs.
- **Self-contained**: Requires zero dependencies to work.
- **Accessible**: Screen reader and minimum contrast ratio support can be turned on.
- **And much more**: Links, theming, addons, well documented API, etc.
- **Self-contained**: The core library has zero dependencies.
- **Accessible**: Screen reader mode and minimum contrast ratio support can be turned on.
- **And much more**: Links, theming, custom glyphs, addons, well documented API, etc.
## What xterm.js is not
- Xterm.js is not a terminal application that you can download and use on your computer.
- Xterm.js is not `bash`. Xterm.js can be connected to processes like `bash` and let you interact with them (provide input, receive output).
- Xterm.js is not `bash`. Xterm.js can be connected to processes like `bash` and let you interact with them (provide input, receive output) through a library like [node-pty](https://github.com/microsoft/node-pty).
## Getting Started
First, you need to install the module, we ship exclusively through [npm](https://www.npmjs.com/), so you need that installed and then add xterm.js as a dependency by running:
First, you need to install the module. We ship exclusively through [npm](https://www.npmjs.com), so you need that installed and then add [@xterm/xterm](https://www.npmjs.com/package/@xterm/xterm) as a dependency by running:
```bash
npm install @xterm/xterm
npm install --save @xterm/xterm
```
To start using xterm.js on your browser, add the `xterm.js` and `xterm.css` to the head of your HTML page. Then create a `<div id="terminal"></div>` onto which xterm can attach itself. Finally, instantiate the `Terminal` object and then call the `open` function with the DOM object of the `div`.
@@ -54,12 +54,10 @@ import { Terminal } from '@xterm/xterm';
### Addons
⚠️ *This section describes the new addon format introduced in v3.14.0, see [here](https://github.com/xtermjs/xterm.js/blob/3.14.2/README.md#addons) for the instructions on the old format*
Addons are separate modules that extend the `Terminal` by building on the [xterm.js API](https://github.com/xtermjs/xterm.js/blob/master/typings/xterm.d.ts). To use an addon, you first need to install it in your project:
```bash
npm i -S @xterm/addon-web-links
npm install --save @xterm/addon-web-links
```
Then import the addon, instantiate it and call `Terminal.loadAddon`:
@@ -80,50 +78,51 @@ The xterm.js team maintains the following addons, but anyone can build them:
- [`@xterm/addon-clipboard`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-clipboard): Access the browser's clipboard
- [`@xterm/addon-fit`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-fit): Fits the terminal to the containing element
- [`@xterm/addon-image`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-image): Adds image support
- [`@xterm/addon-ligatures`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-ligatures): Enables rendering of ligatures
- [`@xterm/addon-progress`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-progress): Adds support for the progress API (`OSC 9;4`)
- [`@xterm/addon-search`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-search): Adds search functionality
- [`@xterm/addon-serialize`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-serialize): Serializes the terminal's buffer to a VT sequences or HTML
- [`@xterm/addon-serialize`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-serialize): Serializes the terminal's buffer to VT sequences or HTML
- [`@xterm/addon-unicode-graphemes`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-unicode-graphemes): Enhanced unicode support including grapheme clustering (experimental)
- [`@xterm/addon-unicode11`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-unicode11): Updates character widths to their unicode11 values
- [`@xterm/addon-web-fonts`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-web-fonts): Easily integrate web fonts
- [`@xterm/addon-web-links`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-web-links): Adds web link detection and interaction
- [`@xterm/addon-webgl`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-webgl): Renders xterm.js using a `canvas` element's webgl2 context
## Browser Support
Since xterm.js is typically implemented as a developer tool, only modern browsers are supported officially. Specifically the latest versions of *Chrome*, *Edge*, *Firefox*, and *Safari*.
Xterm.js works seamlessly in [Electron](https://electronjs.org/) apps and may even work on earlier versions of the browsers. These are the versions we strive to keep working.
Since xterm.js is typically implemented as a developer tool, generally only modern evergreen browsers are supported officially. Specifically the latest versions of *Chrome*, *Edge*, *Firefox*, and *Safari*. Xterm.js also works seamlessly in [Electron](https://electronjs.org/) apps and may even work on earlier versions of the browsers. These are the versions we strive to keep working.
### Node.js Support
We also publish [`xterm-headless`](https://www.npmjs.com/package/xterm-headless) which is a stripped down version of xterm.js that runs in Node.js. An example use case for this is to keep track of a terminal's state where the process is running and using the serialize addon so it can get all state restored upon reconnection.
We also publish [`xterm-headless`](https://www.npmjs.com/package/xterm-headless) which is a stripped down version of xterm.js that runs headless in Node.js. An example use case for this is to keep track of a terminal's state where the process is running and using the [serialize addon](https://www.npmjs.com/package/@xterm/addon-serialize) so it can get all state restored upon reconnection.
## API
The full API for xterm.js is contained within the [TypeScript declaration file](https://github.com/xtermjs/xterm.js/blob/master/typings/xterm.d.ts), use the branch/tag picker in GitHub (`w`) to navigate to the correct version of the API.
Note that some APIs are marked *experimental*, these are added to enable experimentation with new ideas without committing to support it like a normal [semver](https://semver.org/) API. Note that these APIs can change radically between versions, so be sure to read release notes if you plan on using experimental APIs.
Some APIs may be marked with *experimental*, these are added to enable experimentation with new ideas without committing to support it like a normal [semver](https://semver.org/) API. Note that these APIs can change radically between versions, so be sure to read release notes if you plan on using experimental APIs.
## Releases
Xterm.js follows a monthly release cycle roughly.
All current and past releases are available on this repo's [Releases page](https://github.com/sourcelair/xterm.js/releases), you can view the [high-level roadmap on the wiki](https://github.com/xtermjs/xterm.js/wiki/Roadmap) and see what we're working on now by looking through [Milestones](https://github.com/sourcelair/xterm.js/milestones).
Stable releases are done on an as needed basis. All current and past releases are available on this repo's [releases page](https://github.com/sourcelair/xterm.js/releases), you can see what's planned for upcoming releases looking through the repository [milestones](https://github.com/sourcelair/xterm.js/milestones).
### Beta builds
Our CI releases beta builds to npm for every change that goes into master. Install the latest beta build with:
Beta releases are continuously published off the `master` branch. Install the latest beta build with:
```bash
npm install -S @xterm/xterm@beta
npm install --save @xterm/xterm@beta
```
These should generally be stable, but some bugs may slip in. We recommend using the beta build primarily to test out new features and to verify bug fixes.
The principal implementation (VS Code) typically uses the latest or near the latest beta build. Generally they are quite stable but can potentially contain bugs or breaking changes. If stability is very important we recommend using the beta build primarily to test out new features and to verify bug fixes, unless you're tracking what's landing and are comfortable taking that risk.
## Contributing
You can read the [guide on the wiki](https://github.com/xtermjs/xterm.js/wiki/Contributing) to learn how to contribute and set up xterm.js for development.
Read [CONTRIBUTING.md](https://github.com/xtermjs/xterm.js/blob/master/CONTRIBUTING.md) to learn how to contribute to the project.
## Real-world uses
Xterm.js is used in several world-class applications to provide great terminal experiences.
Xterm.js is used in many world-class applications to provide great terminal experiences.
- [**SourceLair**](https://www.sourcelair.com/): In-browser IDE that provides its users with fully-featured Linux terminals based on xterm.js.
- [**Microsoft Visual Studio Code**](http://code.visualstudio.com/): Modern, versatile, and powerful open source code editor that provides an integrated terminal based on xterm.js.
@@ -232,12 +231,12 @@ Xterm.js is used in several world-class applications to provide great terminal e
- [**EmuDevz**](https://afska.github.io/emudevz): A free coding game where players learn how to build an emulator from scratch.
- [And much more...](https://github.com/xtermjs/xterm.js/network/dependents?package_id=UGFja2FnZS0xNjYzMjc4OQ%3D%3D)
Do you use xterm.js in your application as well? Please [open a Pull Request](https://github.com/sourcelair/xterm.js/pulls) to include it here. We would love to have it on our list. Note: Please add any new contributions to the end of the list only.
Do you use xterm.js in your application as well? Please [open a Pull Request](https://github.com/sourcelair/xterm.js/pulls) to include it here. We would love to have it on our list. Please add any new contributions to the end of the list.
## License Agreement
If you contribute code to this project, you implicitly allow your code to be distributed under the MIT license. You are also implicitly verifying that all code is your original work.
Copyright (c) 2017-2022, [The xterm.js authors](https://github.com/xtermjs/xterm.js/graphs/contributors) (MIT License)<br>
Copyright (c) 2017-2026, [The xterm.js authors](https://github.com/xtermjs/xterm.js/graphs/contributors) (MIT License)<br>
Copyright (c) 2014-2017, SourceLair, Private Company ([www.sourcelair.com](https://www.sourcelair.com/home)) (MIT License)<br>
Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
-22
View File
@@ -1,22 +0,0 @@
{
"name": "@xterm/addon-clipboard",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@xterm/addon-clipboard",
"version": "0.1.0",
"license": "MIT",
"dependencies": {
"js-base64": "^3.7.5"
}
},
"node_modules/js-base64": {
"version": "3.7.7",
"resolved": "https://registry.npmjs.org/js-base64/-/js-base64-3.7.7.tgz",
"integrity": "sha512-7rCnleh0z2CkXhH67J8K1Ytz0b2Y+yxTPL+/KOJoa20hfnVQ/3/T6W/KflYI4bRHRagNeXeU2bkNGI3v1oS/lw==",
"license": "BSD-3-Clause"
}
}
}
-8
View File
@@ -1,8 +0,0 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
js-base64@^3.7.5:
version "3.7.7"
resolved "https://registry.npmjs.org/js-base64/-/js-base64-3.7.7.tgz"
integrity sha512-7rCnleh0z2CkXhH67J8K1Ytz0b2Y+yxTPL+/KOJoa20hfnVQ/3/T6W/KflYI4bRHRagNeXeU2bkNGI3v1oS/lw==
+16 -12
View File
@@ -3,9 +3,8 @@
* @license MIT
*/
import type { Terminal, ITerminalAddon } from '@xterm/xterm';
import type { Terminal, ITerminalAddon, IRenderDimensions } from '@xterm/xterm';
import type { FitAddon as IFitApi } from '@xterm/addon-fit';
import { IRenderDimensions } from 'browser/renderer/shared/Types';
import { ViewportConstants } from 'browser/shared/Constants';
interface ITerminalDimensions {
@@ -23,6 +22,17 @@ interface ITerminalDimensions {
const MINIMUM_COLS = 2;
const MINIMUM_ROWS = 1;
function getWindow(e: Node): Window {
if (e?.ownerDocument?.defaultView) {
return e.ownerDocument.defaultView;
}
return window;
}
function _getComputedStyle(el: HTMLElement): CSSStyleDeclaration {
return getWindow(el).getComputedStyle(el, null);
}
export class FitAddon implements ITerminalAddon , IFitApi {
private _terminal: Terminal | undefined;
@@ -38,12 +48,8 @@ export class FitAddon implements ITerminalAddon , IFitApi {
return;
}
// TODO: Remove reliance on private API
const core = (this._terminal as any)._core;
// Force a full render
if (this._terminal.rows !== dims.rows || this._terminal.cols !== dims.cols) {
core._renderService.clear();
this._terminal.resize(dims.cols, dims.rows);
}
}
@@ -57,11 +63,9 @@ export class FitAddon implements ITerminalAddon , IFitApi {
return undefined;
}
// TODO: Remove reliance on private API
const core = (this._terminal as any)._core;
const dims: IRenderDimensions = core._renderService.dimensions;
const dims: IRenderDimensions | undefined = this._terminal.dimensions;
if (dims.css.cell.width === 0 || dims.css.cell.height === 0) {
if (!dims || dims.css.cell.width === 0 || dims.css.cell.height === 0) {
return undefined;
}
@@ -69,10 +73,10 @@ export class FitAddon implements ITerminalAddon , IFitApi {
? 0
: (this._terminal.options.overviewRuler?.width || ViewportConstants.DEFAULT_SCROLL_BAR_WIDTH));
const parentElementStyle = window.getComputedStyle(this._terminal.element.parentElement);
const parentElementStyle = _getComputedStyle(this._terminal.element.parentElement);
const parentElementHeight = parseInt(parentElementStyle.getPropertyValue('height'));
const parentElementWidth = Math.max(0, parseInt(parentElementStyle.getPropertyValue('width')));
const elementStyle = window.getComputedStyle(this._terminal.element);
const elementStyle = _getComputedStyle(this._terminal.element);
const elementPadding = {
top: parseInt(elementStyle.getPropertyValue('padding-top')),
bottom: parseInt(elementStyle.getPropertyValue('padding-bottom')),
-817
View File
@@ -1,817 +0,0 @@
{
"name": "@xterm/addon-image",
"version": "0.8.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@xterm/addon-image",
"version": "0.8.0",
"license": "MIT",
"devDependencies": {
"sixel": "^0.16.0",
"xterm-wasm-parts": "^0.1.0"
}
},
"node_modules/@isaacs/cliui": {
"version": "8.0.2",
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
"integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==",
"dev": true,
"license": "ISC",
"dependencies": {
"string-width": "^5.1.2",
"string-width-cjs": "npm:string-width@^4.2.0",
"strip-ansi": "^7.0.1",
"strip-ansi-cjs": "npm:strip-ansi@^6.0.1",
"wrap-ansi": "^8.1.0",
"wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/@pkgjs/parseargs": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",
"integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==",
"dev": true,
"license": "MIT",
"optional": true,
"engines": {
"node": ">=14"
}
},
"node_modules/acorn": {
"version": "8.15.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"dev": true,
"license": "MIT",
"bin": {
"acorn": "bin/acorn"
},
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/acorn-walk": {
"version": "8.3.4",
"resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.4.tgz",
"integrity": "sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g==",
"dev": true,
"license": "MIT",
"dependencies": {
"acorn": "^8.11.0"
},
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/ansi-regex": {
"version": "6.2.2",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz",
"integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/chalk/ansi-regex?sponsor=1"
}
},
"node_modules/ansi-styles": {
"version": "6.2.3",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",
"integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/anymatch": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz",
"integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==",
"dev": true,
"license": "ISC",
"dependencies": {
"normalize-path": "^3.0.0",
"picomatch": "^2.0.4"
},
"engines": {
"node": ">= 8"
}
},
"node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"dev": true,
"license": "MIT"
},
"node_modules/binary-extensions": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",
"integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/brace-expansion": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
"integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0"
}
},
"node_modules/braces": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",
"integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",
"dev": true,
"license": "MIT",
"dependencies": {
"fill-range": "^7.1.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/chokidar": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
"integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
"dev": true,
"license": "MIT",
"dependencies": {
"anymatch": "~3.1.2",
"braces": "~3.0.2",
"glob-parent": "~5.1.2",
"is-binary-path": "~2.1.0",
"is-glob": "~4.0.1",
"normalize-path": "~3.0.0",
"readdirp": "~3.6.0"
},
"engines": {
"node": ">= 8.10.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
},
"optionalDependencies": {
"fsevents": "~2.3.2"
}
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
},
"engines": {
"node": ">=7.0.0"
}
},
"node_modules/color-name": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"dev": true,
"license": "MIT"
},
"node_modules/colorette": {
"version": "2.0.20",
"resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz",
"integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==",
"dev": true,
"license": "MIT"
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
"dev": true,
"license": "MIT",
"dependencies": {
"path-key": "^3.1.0",
"shebang-command": "^2.0.0",
"which": "^2.0.1"
},
"engines": {
"node": ">= 8"
}
},
"node_modules/eastasianwidth": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz",
"integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==",
"dev": true,
"license": "MIT"
},
"node_modules/emoji-regex": {
"version": "9.2.2",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
"integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==",
"dev": true,
"license": "MIT"
},
"node_modules/fill-range": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
"integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",
"dev": true,
"license": "MIT",
"dependencies": {
"to-regex-range": "^5.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/foreground-child": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz",
"integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==",
"dev": true,
"license": "ISC",
"dependencies": {
"cross-spawn": "^7.0.6",
"signal-exit": "^4.0.1"
},
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/glob": {
"version": "10.5.0",
"resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz",
"integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==",
"dev": true,
"license": "ISC",
"dependencies": {
"foreground-child": "^3.1.0",
"jackspeak": "^3.1.2",
"minimatch": "^9.0.4",
"minipass": "^7.1.2",
"package-json-from-dist": "^1.0.0",
"path-scurry": "^1.11.1"
},
"bin": {
"glob": "dist/esm/bin.mjs"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/glob-parent": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
"integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
"dev": true,
"license": "ISC",
"dependencies": {
"is-glob": "^4.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/inwasm": {
"version": "0.0.13",
"resolved": "https://registry.npmjs.org/inwasm/-/inwasm-0.0.13.tgz",
"integrity": "sha512-gmULhw1wfF3tQ19y0TvcNH6A5jN7IuTD51kbZuy+ittUU59d+ZTQMb53wbGQuciMrledgagL3/ohnjUj5qJikQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"acorn": "^8.8.2",
"acorn-walk": "^8.2.0",
"chokidar": "^3.5.3",
"colorette": "^2.0.20",
"glob": "^10.0.0",
"wabt": "^1.0.32"
},
"bin": {
"inwasm": "lib/cli.js"
}
},
"node_modules/is-binary-path": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz",
"integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==",
"dev": true,
"license": "MIT",
"dependencies": {
"binary-extensions": "^2.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/is-extglob": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
"integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/is-fullwidth-code-point": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/is-glob": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
"integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
"dev": true,
"license": "MIT",
"dependencies": {
"is-extglob": "^2.1.1"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/is-number": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",
"integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.12.0"
}
},
"node_modules/isexe": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
"dev": true,
"license": "ISC"
},
"node_modules/jackspeak": {
"version": "3.4.3",
"resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz",
"integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
"@isaacs/cliui": "^8.0.2"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
},
"optionalDependencies": {
"@pkgjs/parseargs": "^0.11.0"
}
},
"node_modules/lru-cache": {
"version": "10.4.3",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
"integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
"dev": true,
"license": "ISC"
},
"node_modules/minimatch": {
"version": "9.0.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz",
"integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==",
"dev": true,
"license": "ISC",
"dependencies": {
"brace-expansion": "^2.0.1"
},
"engines": {
"node": ">=16 || 14 >=14.17"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/minipass": {
"version": "7.1.2",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz",
"integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==",
"dev": true,
"license": "ISC",
"engines": {
"node": ">=16 || 14 >=14.17"
}
},
"node_modules/normalize-path": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
"integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/package-json-from-dist": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz",
"integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==",
"dev": true,
"license": "BlueOak-1.0.0"
},
"node_modules/path-key": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
"integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/path-scurry": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz",
"integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
"lru-cache": "^10.2.0",
"minipass": "^5.0.0 || ^6.0.2 || ^7.0.0"
},
"engines": {
"node": ">=16 || 14 >=14.18"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/picomatch": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
"integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8.6"
},
"funding": {
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/readdirp": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
"integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==",
"dev": true,
"license": "MIT",
"dependencies": {
"picomatch": "^2.2.1"
},
"engines": {
"node": ">=8.10.0"
}
},
"node_modules/shebang-command": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
"integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
"dev": true,
"license": "MIT",
"dependencies": {
"shebang-regex": "^3.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/shebang-regex": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
"integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/signal-exit": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",
"integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==",
"dev": true,
"license": "ISC",
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/sixel": {
"version": "0.16.0",
"resolved": "https://registry.npmjs.org/sixel/-/sixel-0.16.0.tgz",
"integrity": "sha512-xicu6Y6Cyhmv5rjyHxq2r5RnKerlL/nyZEGjOU5bLCshXkZryc9JFJThTCKPOAtWXCfeWquEKFVFfMPcTD25PA==",
"dev": true,
"license": "MIT"
},
"node_modules/string-width": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz",
"integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==",
"dev": true,
"license": "MIT",
"dependencies": {
"eastasianwidth": "^0.2.0",
"emoji-regex": "^9.2.2",
"strip-ansi": "^7.0.1"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/string-width-cjs": {
"name": "string-width",
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"dev": true,
"license": "MIT",
"dependencies": {
"emoji-regex": "^8.0.0",
"is-fullwidth-code-point": "^3.0.0",
"strip-ansi": "^6.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/string-width-cjs/node_modules/ansi-regex": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/string-width-cjs/node_modules/emoji-regex": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
"dev": true,
"license": "MIT"
},
"node_modules/string-width-cjs/node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/strip-ansi": {
"version": "7.1.2",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz",
"integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^6.0.1"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/chalk/strip-ansi?sponsor=1"
}
},
"node_modules/strip-ansi-cjs": {
"name": "strip-ansi",
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/strip-ansi-cjs/node_modules/ansi-regex": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/to-regex-range": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
"integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"is-number": "^7.0.0"
},
"engines": {
"node": ">=8.0"
}
},
"node_modules/wabt": {
"version": "1.0.39",
"resolved": "https://registry.npmjs.org/wabt/-/wabt-1.0.39.tgz",
"integrity": "sha512-ba+dRL/75VQQY7RkU/CgriGbkoWAfS8TDyUlJfJhJ8KhtXgMl5dhNvoPNUcQ9IWRhW8u41glMSuZeTvsYq2rRg==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"wasm-decompile": "bin/wasm-decompile",
"wasm-interp": "bin/wasm-interp",
"wasm-objdump": "bin/wasm-objdump",
"wasm-stats": "bin/wasm-stats",
"wasm-strip": "bin/wasm-strip",
"wasm-validate": "bin/wasm-validate",
"wasm2c": "bin/wasm2c",
"wasm2wat": "bin/wasm2wat",
"wat2wasm": "bin/wat2wasm"
}
},
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
"integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
"dev": true,
"license": "ISC",
"dependencies": {
"isexe": "^2.0.0"
},
"bin": {
"node-which": "bin/node-which"
},
"engines": {
"node": ">= 8"
}
},
"node_modules/wrap-ansi": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz",
"integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^6.1.0",
"string-width": "^5.0.1",
"strip-ansi": "^7.0.1"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/wrap-ansi-cjs": {
"name": "wrap-ansi",
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
"integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.0.0",
"string-width": "^4.1.0",
"strip-ansi": "^6.0.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/wrap-ansi-cjs/node_modules/ansi-regex": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/wrap-ansi-cjs/node_modules/ansi-styles": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
"dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
},
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/wrap-ansi-cjs/node_modules/emoji-regex": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
"dev": true,
"license": "MIT"
},
"node_modules/wrap-ansi-cjs/node_modules/string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"dev": true,
"license": "MIT",
"dependencies": {
"emoji-regex": "^8.0.0",
"is-fullwidth-code-point": "^3.0.0",
"strip-ansi": "^6.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/wrap-ansi-cjs/node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/xterm-wasm-parts": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/xterm-wasm-parts/-/xterm-wasm-parts-0.1.0.tgz",
"integrity": "sha512-GFE8yNJfdkytGpcsOZhkL3B8XyUqkR/Du3SdxRyFbJg+BBCKm3raaaflgIM4TwNQ2AOLz01BEEuB5FZXx8aNTQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"inwasm": "^0.0.13"
}
}
}
}
+1 -1
View File
@@ -105,7 +105,7 @@ export class IIPHandler implements IOscHandler, IResetHandler {
return true;
}
const blob = new Blob([this._dec.data8], { type: this._metrics.mime });
const blob = new Blob([new Uint8Array(this._dec.data8)], { type: this._metrics.mime });
this._dec.release();
if (!window.createImageBitmap) {
+1 -1
View File
@@ -176,7 +176,7 @@ export class HeaderParser {
try {
const v = this._buffer.slice(0, pos);
this.fields[this._key] = DECODERS[this._key] ? DECODERS[this._key](v) : v;
} catch (e) {
} catch {
return false;
}
return true;
+1 -1
View File
@@ -124,7 +124,7 @@ export class ImageRenderer extends Disposable implements IDisposable {
* Forwarded from internal render service.
*/
public get dimensions(): IRenderDimensions | undefined {
return this._renderService?.dimensions;
return this._terminal.dimensions;
}
/**
+1 -1
View File
@@ -99,7 +99,7 @@ export class SixelHandler implements IDcsHandler, IResetHandler {
}
const canvas = ImageRenderer.createCanvas(undefined, width, height);
canvas.getContext('2d')?.putImageData(new ImageData(this._dec.data8, width, height), 0, 0);
canvas.getContext('2d')?.putImageData(new ImageData(this._dec.data8 as Uint8ClampedArray<ArrayBuffer>, width, height), 0, 0);
if (this._dec.memoryUsage > MEM_PERMA_LIMIT) {
this._dec.release();
}
+1 -1
View File
@@ -300,7 +300,7 @@ test.describe('ImageAddon', () => {
* terminal access helpers.
*/
async function getDimensions(): Promise<IDimensions> {
const dimensions: any = await ctx.page.evaluate(`term._core._renderService.dimensions`);
const dimensions: any = await ctx.page.evaluate(`term.dimensions`);
return {
cellWidth: Math.round(dimensions.css.cell.width),
cellHeight: Math.round(dimensions.css.cell.height),
-1
View File
@@ -3,7 +3,6 @@ node_modules/
coverage/
lib/
fonts/
.env
.vscode/
+27 -3
View File
@@ -1,6 +1,30 @@
MIT License
Copyright (c) 2018
Copyright (c) 2019, The xterm.js authors (https://github.com/xtermjs/xterm.js)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
The code that analyzes font ligatures is forked from https://github.com/princjef/font-ligatures with this license:
MIT License
Copyright (c) 2018 Jeffrey Principe
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -1,78 +0,0 @@
/**
* Copyright (c) 2018 The xterm.js authors. All rights reserved.
* @license MIT
*/
const fs = require('fs');
const path = require('path');
const util = require('util');
const axios = require('axios').default;
const mkdirp = require('mkdirp');
const yauzl = require('yauzl');
const urls = {
fira: 'https://github.com/tonsky/FiraCode/raw/d42e7276fa925e5f82748f3ec9ea429736611b48/distr/otf/FiraCode-Regular.otf',
iosevka: 'https://github.com/be5invis/Iosevka/releases/download/v1.14.3/01-iosevka-1.14.3.zip'
};
const writeFile = util.promisify(fs.writeFile);
const fontsFolder = path.join(__dirname, '../fonts');
async function download() {
await mkdirp(fontsFolder);
try {
await downloadFiraCode();
await downloadIosevka();
console.log('Loaded all fonts for testing')
} catch (e) {
console.warn('Fonts failed to download, ligature tests will not work', e);
}
}
async function downloadFiraCode() {
const file = path.join(fontsFolder, 'firaCode.otf');
if (await util.promisify(fs.exists)(file)) {
console.log('Fira Code already loaded');
} else {
console.log('Downloading Fira Code...');
await writeFile(
file,
(await axios.get(urls.fira, { responseType: 'arraybuffer' })).data
);
}
}
async function downloadIosevka() {
const file = path.join(fontsFolder, 'iosevka.ttf');
if (await util.promisify(fs.exists)(file)) {
console.log('Iosevka already loaded');
} else {
console.log('Downloading Iosevka...');
const iosevkaContents = (await axios.get(urls.iosevka, { responseType: 'arraybuffer' })).data;
const iosevkaZipfile = await util.promisify(yauzl.fromBuffer)(iosevkaContents);
await new Promise((resolve, reject) => {
iosevkaZipfile.on('entry', entry => {
if (entry.fileName === 'ttf/iosevka-regular.ttf') {
iosevkaZipfile.openReadStream(entry, (err, stream) => {
if (err) {
return reject(err);
}
const writeStream = fs.createWriteStream(file);
stream.pipe(writeStream);
writeStream.on('close', () => resolve());
});
}
});
});
}
}
download();
process.on('unhandledRejection', e => {
console.error(e);
process.exit(1);
});
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
-661
View File
@@ -1,661 +0,0 @@
{
"name": "@xterm/addon-ligatures",
"version": "0.9.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@xterm/addon-ligatures",
"version": "0.9.0",
"license": "MIT",
"dependencies": {
"font-finder": "^1.1.0",
"font-ligatures": "^1.4.1"
},
"devDependencies": {
"@types/sinon": "^5.0.1",
"axios": "^1.6.0",
"mkdirp": "0.5.5",
"sinon": "6.3.5",
"yauzl": "^2.10.0"
},
"engines": {
"node": ">8.0.0"
}
},
"node_modules/@sinonjs/commons": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-1.8.0.tgz",
"integrity": "sha512-wEj54PfsZ5jGSwMX68G8ZXFawcSglQSXqCftWX3ec8MDUzQdHgcKvw97awHbY0efQEL5iKUOAmmVtoYgmrSG4Q==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"type-detect": "4.0.8"
}
},
"node_modules/@sinonjs/formatio": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/@sinonjs/formatio/-/formatio-3.2.2.tgz",
"integrity": "sha512-B8SEsgd8gArBLMD6zpRw3juQ2FVSsmdd7qlevyDqzS9WTCtvF55/gAL+h6gue8ZvPYcdiPdvueM/qm//9XzyTQ==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"@sinonjs/commons": "^1",
"@sinonjs/samsam": "^3.1.0"
}
},
"node_modules/@sinonjs/formatio/node_modules/@sinonjs/samsam": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/@sinonjs/samsam/-/samsam-3.3.3.tgz",
"integrity": "sha512-bKCMKZvWIjYD0BLGnNrxVuw4dkWCYsLqFOUWw8VgKF/+5Y+mE7LfHWPIYoDXowH+3a9LsWDMo0uAP8YDosPvHQ==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"@sinonjs/commons": "^1.3.0",
"array-from": "^2.1.1",
"lodash": "^4.17.15"
}
},
"node_modules/@sinonjs/samsam": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/@sinonjs/samsam/-/samsam-2.1.3.tgz",
"integrity": "sha512-8zNeBkSKhU9a5cRNbpCKau2WWPfan+Q2zDlcXvXyhn9EsMqgYs4qzo0XHNVlXC6ABQL8fT6nV+zzo5RTHJzyXw==",
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/@sinonjs/text-encoding": {
"version": "0.7.1",
"resolved": "https://registry.npmjs.org/@sinonjs/text-encoding/-/text-encoding-0.7.1.tgz",
"integrity": "sha512-+iTbntw2IZPb/anVDbypzfQa+ay64MW0Zo8aJ8gZPWMMK6/OubMVb6lUPMagqjOPnmtauXnFCACVl3O7ogjeqQ==",
"dev": true,
"license": "(Unlicense OR Apache-2.0)"
},
"node_modules/@types/sinon": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/@types/sinon/-/sinon-5.0.1.tgz",
"integrity": "sha512-yxzBCIjE3lp9lYjfBbIK/LRCoXgCLLbIIBIje7eNCcUIIR2CZZtyX5uto2hVoMSMqLrsRrT6mwwUEd0yFgOwpA==",
"dev": true,
"license": "MIT"
},
"node_modules/array-from": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/array-from/-/array-from-2.1.1.tgz",
"integrity": "sha1-z+nYwmYoudxa7MYqn12PHzUsEZU= sha512-GQTc6Uupx1FCavi5mPzBvVT7nEOeWMmUA9P95wpfpW1XwMSKs+KaymD5C2Up7KAUKg/mYwbsUYzdZWcoajlNZg==",
"dev": true,
"license": "MIT"
},
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
"dev": true,
"license": "MIT"
},
"node_modules/axios": {
"version": "1.8.2",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.8.2.tgz",
"integrity": "sha512-ls4GYBm5aig9vWx8AWDSGLpnpDQRtWAfrjU+EuytuODrFBkqesN2RkOQCBzrA1RQNHw1SmRMSDDDSwzNAYQ6Rg==",
"dev": true,
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6",
"form-data": "^4.0.0",
"proxy-from-env": "^1.1.0"
}
},
"node_modules/buffer-crc32": {
"version": "0.2.13",
"resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz",
"integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": "*"
}
},
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
"dev": true,
"license": "MIT",
"dependencies": {
"delayed-stream": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/diff": {
"version": "3.5.0",
"resolved": "https://registry.npmjs.org/diff/-/diff-3.5.0.tgz",
"integrity": "sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.3.1"
}
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
"dev": true,
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.1",
"es-errors": "^1.3.0",
"gopd": "^1.2.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-errors": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-object-atoms": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
"dev": true,
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-set-tostringtag": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
"dev": true,
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.6",
"has-tostringtag": "^1.0.2",
"hasown": "^2.0.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/fd-slicer": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz",
"integrity": "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==",
"dev": true,
"license": "MIT",
"dependencies": {
"pend": "~1.2.0"
}
},
"node_modules/follow-redirects": {
"version": "1.15.9",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz",
"integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==",
"dev": true,
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/RubenVerborgh"
}
],
"license": "MIT",
"engines": {
"node": ">=4.0"
},
"peerDependenciesMeta": {
"debug": {
"optional": true
}
}
},
"node_modules/font-finder": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/font-finder/-/font-finder-1.1.0.tgz",
"integrity": "sha512-wpCL2uIbi6GurJbU7ZlQ3nGd61Ho+dSU6U83/xJT5UPFfN35EeCW/rOtS+5k+IuEZu2SYmHzDIPL9eA5tSYRAw==",
"license": "MIT",
"dependencies": {
"get-system-fonts": "^2.0.0",
"promise-stream-reader": "^1.0.1"
},
"engines": {
"node": ">8.0.0"
}
},
"node_modules/font-ligatures": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/font-ligatures/-/font-ligatures-1.4.1.tgz",
"integrity": "sha512-7W6zlfyhvCqShZ5ReUWqmSd9vBaUudW0Hxis+tqUjtHhsPU+L3Grf8mcZAtCiXHTzorhwdRTId2WeH/88gdFkw==",
"license": "MIT",
"dependencies": {
"font-finder": "^1.0.3",
"lru-cache": "^6.0.0",
"opentype.js": "^0.8.0"
},
"engines": {
"node": ">8.0.0"
}
},
"node_modules/form-data": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz",
"integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==",
"dev": true,
"license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"es-set-tostringtag": "^2.1.0",
"hasown": "^2.0.2",
"mime-types": "^2.1.12"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-intrinsic": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"es-define-property": "^1.0.1",
"es-errors": "^1.3.0",
"es-object-atoms": "^1.1.1",
"function-bind": "^1.1.2",
"get-proto": "^1.0.1",
"gopd": "^1.2.0",
"has-symbols": "^1.1.0",
"hasown": "^2.0.2",
"math-intrinsics": "^1.1.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
"dev": true,
"license": "MIT",
"dependencies": {
"dunder-proto": "^1.0.1",
"es-object-atoms": "^1.0.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/get-system-fonts": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/get-system-fonts/-/get-system-fonts-2.0.0.tgz",
"integrity": "sha512-iiM/DavyF2nnLdELzPBSHojzQJVai9WiwrRzn5gp2dutJuerC8qHyBoh4lxfVdKGbnb9eZ4p8Oefbuc3yExB7Q==",
"license": "MIT",
"engines": {
"node": ">8.0.0"
}
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/has-flag": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
"integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/has-symbols": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/has-tostringtag": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
"dev": true,
"license": "MIT",
"dependencies": {
"has-symbols": "^1.0.3"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/hasown": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/isarray": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz",
"integrity": "sha512-D2S+3GLxWH+uhrNEcoh/fnmYeP8E8/zHl644d/jdA0g2uyXvy3sb0qxotE+ne0LtccHknQzWwZEzhak7oJ0COQ==",
"dev": true,
"license": "MIT"
},
"node_modules/just-extend": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/just-extend/-/just-extend-4.1.0.tgz",
"integrity": "sha512-ApcjaOdVTJ7y4r08xI5wIqpvwS48Q0PBG4DJROcEkH1f8MdAiNFyFxz3xoL0LWAVwjrwPYZdVHHxhRHcx/uGLA==",
"dev": true,
"license": "MIT"
},
"node_modules/lodash": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
"dev": true,
"license": "MIT"
},
"node_modules/lodash.get": {
"version": "4.4.2",
"resolved": "https://registry.npmjs.org/lodash.get/-/lodash.get-4.4.2.tgz",
"integrity": "sha512-z+Uw/vLuy6gQe8cfaFWD7p0wVv8fJl3mbzXh33RS+0oW2wvUqiRXiQ69gLWSLpgB5/6sU+r6BlQR0MBILadqTQ==",
"deprecated": "This package is deprecated. Use the optional chaining (?.) operator instead.",
"dev": true,
"license": "MIT"
},
"node_modules/lolex": {
"version": "2.7.5",
"resolved": "https://registry.npmjs.org/lolex/-/lolex-2.7.5.tgz",
"integrity": "sha512-l9x0+1offnKKIzYVjyXU2SiwhXDLekRzKyhnbyldPHvC7BvLPVpdNUNR2KeMAiCN2D/kLNttZgQD5WjSxuBx3Q==",
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/lru-cache": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
"integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
"license": "ISC",
"dependencies": {
"yallist": "^4.0.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"dev": true,
"license": "MIT",
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/minimist": {
"version": "1.2.6",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz",
"integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==",
"dev": true,
"license": "MIT"
},
"node_modules/mkdirp": {
"version": "0.5.5",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz",
"integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"minimist": "^1.2.5"
},
"bin": {
"mkdirp": "bin/cmd.js"
}
},
"node_modules/nise": {
"version": "1.5.3",
"resolved": "https://registry.npmjs.org/nise/-/nise-1.5.3.tgz",
"integrity": "sha512-Ymbac/94xeIrMf59REBPOv0thr+CJVFMhrlAkW/gjCIE58BGQdCj0x7KRCb3yz+Ga2Rz3E9XXSvUyyxqqhjQAQ==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"@sinonjs/formatio": "^3.2.1",
"@sinonjs/text-encoding": "^0.7.1",
"just-extend": "^4.0.2",
"lolex": "^5.0.1",
"path-to-regexp": "^1.7.0"
}
},
"node_modules/nise/node_modules/lolex": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/lolex/-/lolex-5.1.2.tgz",
"integrity": "sha512-h4hmjAvHTmd+25JSwrtTIuwbKdwg5NzZVRMLn9saij4SZaepCrTCxPr35H/3bjwfMJtN+t3CX8672UIkglz28A==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"@sinonjs/commons": "^1.7.0"
}
},
"node_modules/opentype.js": {
"version": "0.8.0",
"resolved": "https://registry.npmjs.org/opentype.js/-/opentype.js-0.8.0.tgz",
"integrity": "sha512-FQHR4oGP+a0m/f6yHoRpBOIbn/5ZWxKd4D/djHVJu8+KpBTYrJda0b7mLcgDEMWXE9xBCJm+qb0yv6FcvPjukg==",
"license": "MIT",
"dependencies": {
"tiny-inflate": "^1.0.2"
},
"bin": {
"ot": "bin/ot"
}
},
"node_modules/path-to-regexp": {
"version": "1.9.0",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-1.9.0.tgz",
"integrity": "sha512-xIp7/apCFJuUHdDLWe8O1HIkb0kQrOMb/0u6FXQjemHn/ii5LrIzU6bdECnsiTF/GjZkMEKg1xdiZwNqDYlZ6g==",
"dev": true,
"license": "MIT",
"dependencies": {
"isarray": "0.0.1"
}
},
"node_modules/pend": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz",
"integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==",
"dev": true,
"license": "MIT"
},
"node_modules/promise-stream-reader": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/promise-stream-reader/-/promise-stream-reader-1.0.1.tgz",
"integrity": "sha512-Tnxit5trUjBAqqZCGWwjyxhmgMN4hGrtpW3Oc/tRI4bpm/O2+ej72BB08l6JBnGQgVDGCLvHFGjGgQS6vzhwXg==",
"license": "MIT",
"engines": {
"node": ">8.0.0"
}
},
"node_modules/proxy-from-env": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
"dev": true,
"license": "MIT"
},
"node_modules/sinon": {
"version": "6.3.5",
"resolved": "https://registry.npmjs.org/sinon/-/sinon-6.3.5.tgz",
"integrity": "sha512-xgoZ2gKjyVRcF08RrIQc+srnSyY1JDJtxu3Nsz07j1ffjgXoY6uPLf/qja6nDBZgzYYEovVkFryw2+KiZz11xQ==",
"deprecated": "16.1.1",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"@sinonjs/commons": "^1.0.2",
"@sinonjs/formatio": "^3.0.0",
"@sinonjs/samsam": "^2.1.2",
"diff": "^3.5.0",
"lodash.get": "^4.4.2",
"lolex": "^2.7.5",
"nise": "^1.4.5",
"supports-color": "^5.5.0",
"type-detect": "^4.0.8"
}
},
"node_modules/supports-color": {
"version": "5.5.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz",
"integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==",
"dev": true,
"license": "MIT",
"dependencies": {
"has-flag": "^3.0.0"
},
"engines": {
"node": ">=4"
}
},
"node_modules/tiny-inflate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.2.tgz",
"integrity": "sha512-fEndoHfuiSlXtvG0EA1gB4uAdy2dbQ3WfOtQw1/Y8NQ9rxtGbGkENwfGmN0wK7OkxDz1lgc5Ei2LQ0oxKDUcVw==",
"license": "MIT"
},
"node_modules/type-detect": {
"version": "4.0.8",
"resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz",
"integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/yallist": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
"license": "ISC"
},
"node_modules/yauzl": {
"version": "2.10.0",
"resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz",
"integrity": "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==",
"dev": true,
"license": "MIT",
"dependencies": {
"buffer-crc32": "~0.2.3",
"fd-slicer": "~1.1.0"
}
}
}
}
+5 -5
View File
@@ -14,7 +14,6 @@
"node": ">8.0.0"
},
"scripts": {
"prepare": "node bin/download-fonts.js",
"build": "tsc -p src",
"watch": "tsc -w -p src",
"prepackage": "npm run build",
@@ -32,14 +31,15 @@
],
"license": "MIT",
"dependencies": {
"font-finder": "^1.1.0",
"font-ligatures": "^1.4.1"
"lru-cache": "^6.0.0",
"opentype.js": "^0.8.0"
},
"devDependencies": {
"@types/sinon": "^5.0.1",
"@types/lru-cache": "^5.1.0",
"@types/opentype.js": "^0.7.0",
"axios": "^1.6.0",
"font-finder": "^1.1.0",
"mkdirp": "0.5.5",
"sinon": "6.3.5",
"yauzl": "^2.10.0"
}
}
+1 -1
View File
@@ -3,7 +3,7 @@
* @license MIT
*/
import { Font, loadBuffer } from 'font-ligatures';
import { Font, loadBuffer } from './fontLigatures/index';
import parse from './parse';
@@ -0,0 +1,40 @@
import { ILookupTree, IFlattenedLookupTree, ILookupTreeEntry, IFlattenedLookupTreeEntry } from './types';
export default function flatten(tree: ILookupTree, visited: Map<ILookupTreeEntry, IFlattenedLookupTreeEntry> = new Map()): IFlattenedLookupTree {
const result: IFlattenedLookupTree = {};
for (const [glyphId, entry] of Object.entries(tree.individual)) {
result[glyphId] = flattenEntry(entry, visited);
}
for (const { range, entry } of tree.range) {
const flattened = flattenEntry(entry, visited);
for (let glyphId = range[0]; glyphId < range[1]; glyphId++) {
result[glyphId] = flattened;
}
}
return result;
}
function flattenEntry(entry: ILookupTreeEntry, visited: Map<ILookupTreeEntry, IFlattenedLookupTreeEntry>): IFlattenedLookupTreeEntry {
if (visited.has(entry)) {
return visited.get(entry)!;
}
const result: IFlattenedLookupTreeEntry = {};
visited.set(entry, result);
if (entry.forward) {
result.forward = flatten(entry.forward, visited);
}
if (entry.reverse) {
result.reverse = flatten(entry.reverse, visited);
}
if (entry.lookup) {
result.lookup = entry.lookup;
}
return result;
}
@@ -0,0 +1,358 @@
/**
* Copyright (c) 2018 The xterm.js authors. All rights reserved.
* @license MIT
*/
import * as path from 'path';
import * as fs from 'fs';
import { assert } from 'chai';
import { loadBuffer } from './index';
interface IFont {
findLigatures(text: string): { outputGlyphs: number[], contextRanges: [number, number][] };
findLigatureRanges(text: string): [number, number][];
}
interface ITestCase {
font: string;
input: string;
glyphs: number[];
ranges: [number, number][];
}
const fira = (input: string, glyphs: number[], ranges: [number, number][]): ITestCase =>
({ font: 'Fira Code', input, glyphs, ranges });
const iosevka = (input: string, glyphs: number[], ranges: [number, number][]): ITestCase =>
({ font: 'Iosevka', input, glyphs, ranges });
const monoid = (input: string, glyphs: number[], ranges: [number, number][]): ITestCase =>
({ font: 'Monoid', input, glyphs, ranges });
const ubuntu = (input: string, glyphs: number[], ranges: [number, number][]): ITestCase =>
({ font: 'Ubuntu Mono', input, glyphs, ranges });
const firaCases: ITestCase[] = [
fira('abc', [133, 145, 146], []),
fira('.=', [1614, 1081], [[0, 2]]),
fira('..=', [1614, 1614, 1083], [[0, 3]]),
fira('.-', [1614, 1080], [[0, 2]]),
fira(':=', [1614, 1055], [[0, 2]]),
fira('=:=', [1614, 1614, 1483], [[0, 3]]),
fira('=!=', [1614, 1614, 1484], [[0, 3]]),
fira('__', [1614, 1099], [[0, 2]]),
fira('==', [1614, 1485], [[0, 2]]),
fira('!=', [1614, 1058], [[0, 2]]),
fira('===', [1614, 1614, 1486], [[0, 3]]),
fira('!==', [1614, 1614, 1059], [[0, 3]]),
fira('=/=', [1614, 1614, 1491], [[0, 3]]),
fira('<-<', [1614, 1614, 1513], [[0, 3]]),
fira('<<-', [1614, 1614, 1522], [[0, 3]]),
fira('<--', [1614, 1614, 1511], [[0, 3]]),
fira('<-', [1614, 1510], [[0, 2]]),
fira('<->', [1614, 1614, 1512], [[0, 3]]),
fira('->', [1614, 1064], [[0, 2]]),
fira('-->', [1614, 1614, 1063], [[0, 3]]),
fira('->>', [1614, 1614, 1065], [[0, 3]]),
fira('>->', [1614, 1614, 1493], [[0, 3]]),
fira('<=<', [1614, 1614, 1519], [[0, 3]]),
fira('<<=', [1614, 1614, 1523], [[0, 3]]),
fira('<==', [1614, 1614, 1517], [[0, 3]]),
fira('<=>', [1614, 1614, 1518], [[0, 3]]),
fira('=>', [1614, 1488], [[0, 2]]),
fira('==>', [1614, 1614, 1487], [[0, 3]]),
fira('=>>', [1614, 1614, 1489], [[0, 3]]),
fira('>=>', [1614, 1614, 1495], [[0, 3]]),
fira('>>=', [1614, 1614, 1498], [[0, 3]]),
fira('>>-', [1614, 1614, 1497], [[0, 3]]),
fira('>-', [1614, 1492], [[0, 2]]),
fira('<~>', [1614, 1614, 1526], [[0, 3]]),
fira('-<', [1614, 1066], [[0, 2]]),
fira('-<<', [1614, 1614, 1067], [[0, 3]]),
fira('=<<', [1614, 1614, 1490], [[0, 3]]),
fira('<~~', [1614, 1614, 1527], [[0, 3]]),
fira('<~', [1614, 1525], [[0, 2]]),
fira('~~', [1614, 1534], [[0, 2]]),
fira('~>', [1614, 1533], [[0, 2]]),
fira('~~>', [1614, 1614, 1535], [[0, 3]]),
fira('<<<', [1614, 1614, 1524], [[0, 3]]),
fira('<<', [1614, 1521], [[0, 2]]),
fira('<=', [1614, 1516], [[0, 2]]),
fira('<>', [1614, 1520], [[0, 2]]),
fira('>=', [1614, 1494], [[0, 2]]),
fira('>>', [1614, 1496], [[0, 2]]),
fira('>>>', [1614, 1614, 1499], [[0, 3]]),
fira('{.', [1001, 977], [[0, 2]]),
fira('{|', [1614, 1049], [[0, 2]]),
fira('[|', [1614, 1050], [[0, 2]]),
fira('<:', [1614, 1506], [[0, 2]]),
fira(':>', [1614, 1056], [[0, 2]]),
fira('|]', [1614, 1474], [[0, 2]]),
fira('|}', [1614, 1473], [[0, 2]]),
fira('.}', [977, 1002], [[0, 2]]),
fira('<|||', [1614, 1614, 1614, 1504], [[0, 4]]),
fira('<||', [1614, 1614, 1503], [[0, 3]]),
fira('<|', [1614, 1502], [[0, 2]]),
fira('<|>', [1614, 1614, 1505], [[0, 3]]),
fira('|>', [1614, 1477], [[0, 2]]),
fira('||>', [1614, 1614, 1472], [[0, 3]]),
fira('|||>', [1614, 1614, 1614, 1470], [[0, 4]]),
fira('<$', [1614, 1507], [[0, 2]]),
fira('<$>', [1614, 1614, 1508], [[0, 3]]),
fira('$>', [1614, 1479], [[0, 2]]),
fira('<+', [1614, 1514], [[0, 2]]),
fira('<+>', [1614, 1614, 1515], [[0, 3]]),
fira('+>', [1614, 1482], [[0, 2]]),
fira('<*', [1614, 1500], [[0, 2]]),
fira('<*>', [1614, 1614, 1501], [[0, 3]]),
fira('*>', [1614, 1047], [[0, 2]]),
fira('/*', [1614, 1092], [[0, 2]]),
fira('*/', [1614, 1048], [[0, 2]]),
fira('///', [1614, 1614, 1097], [[0, 3]]),
fira('//', [1614, 1096], [[0, 2]]),
fira('</', [1614, 1528], [[0, 2]]),
fira('<!--', [1614, 1614, 1614, 1509], [[0, 4]]),
fira('</>', [1614, 1614, 1529], [[0, 3]]),
fira('/>', [1614, 1095], [[0, 2]]),
fira('0xff', [895, 270, 166, 166], [[0, 3]]),
fira('10x10', [896, 895, 270, 896, 895], [[1, 4]]),
fira('9:45', [904, 998, 899, 900], [[0, 2]]),
fira('[:]', [1003, 998, 1004], [[0, 2]]),
fira(';;', [1614, 1091], [[0, 2]]),
fira('::', [1614, 1052], [[0, 2]]),
fira(':::', [1614, 1614, 1053], [[0, 3]]),
fira('..', [1614, 1082], [[0, 2]]),
fira('...', [1614, 1614, 1085], [[0, 3]]),
fira('..<', [1614, 1614, 1084], [[0, 3]]),
fira('!!', [1614, 1057], [[0, 2]]),
fira('??', [1614, 1090], [[0, 2]]),
fira('%%', [1614, 1536], [[0, 2]]),
fira('&&', [1614, 1468], [[0, 2]]),
fira('||', [1614, 1469], [[0, 2]]),
fira('?.', [1614, 1089], [[0, 2]]),
fira('?:', [1614, 1087], [[0, 2]]),
fira('++', [1614, 1480], [[0, 2]]),
fira('+++', [1614, 1614, 1481], [[0, 3]]),
fira('--', [1614, 1061], [[0, 2]]),
fira('---', [1614, 1614, 1062], [[0, 3]]),
fira('**', [1614, 1045], [[0, 2]]),
fira('***', [1614, 1614, 1046], [[0, 3]]),
fira('~=', [1614, 1532], [[0, 2]]),
fira('~-', [1614, 1531], [[0, 2]]),
fira('www', [1614, 1614, 271], [[0, 3]]),
fira('-~', [1614, 1068], [[0, 2]]),
fira('~@', [1614, 1530], [[0, 2]]),
fira('^=', [1614, 1478], [[0, 2]]),
fira('?=', [1614, 1088], [[0, 2]]),
fira('/=', [1614, 1093], [[0, 2]]),
fira('/==', [1614, 1614, 1094], [[0, 3]]),
fira('-|', [1614, 1060], [[0, 2]]),
fira('_|_', [1614, 1614, 1098], [[0, 3]]),
fira('|-', [1614, 1475], [[0, 2]]),
fira('|=', [1614, 1476], [[0, 2]]),
fira('||=', [1614, 1614, 1471], [[0, 3]]),
fira('#!', [1614, 1071], [[0, 2]]),
fira('#=', [1614, 1075], [[0, 2]]),
fira('##', [1614, 1072], [[0, 2]]),
fira('###', [1614, 1614, 1073], [[0, 3]]),
fira('####', [1614, 1614, 1614, 1074], [[0, 4]]),
fira('#{', [1614, 1069], [[0, 2]]),
fira('#[', [1614, 1070], [[0, 2]]),
fira(']#', [1614, 1051], [[0, 2]]),
fira('#(', [1614, 1076], [[0, 2]]),
fira('#?', [1614, 1077], [[0, 2]]),
fira('#_', [1614, 1078], [[0, 2]]),
fira('#_(', [1614, 1614, 1079], [[0, 3]]),
fira('::=', [1614, 1614, 1054], [[0, 3]]),
fira('.?', [1614, 1086], [[0, 2]]),
fira('===>', [1614, 1614, 1486, 1148], [[0, 4]])
];
const iosevkaCases: ITestCase[] = [
iosevka('<-', [31, 3127], [[0, 2]]),
iosevka('<--', [31, 3129, 3139], [[0, 3]]),
iosevka('<---', [31, 3129, 3150, 3139], [[0, 4]]),
iosevka('<-----', [31, 3129, 3150, 3139, 3151, 3151], [[0, 6]]),
iosevka('->', [3126, 33], [[0, 2]]),
iosevka('-->', [3140, 3128, 33], [[0, 3]]),
iosevka('--->', [3140, 3150, 3128, 33], [[0, 4]]),
iosevka('----->', [3153, 3153, 3140, 3150, 3128, 33], [[0, 6]]),
iosevka('<->', [31, 3149, 33], [[0, 3]]),
iosevka('<-->', [31, 3129, 3128, 33], [[0, 4]]),
iosevka('<--->', [31, 3129, 3150, 3128, 33], [[0, 5]]),
iosevka('<----->', [31, 3129, 3150, 3150, 3150, 3128, 33], [[0, 7]]),
iosevka('<=', [3094, 3095], [[0, 2]]),
iosevka('<==', [31, 3158, 3168], [[0, 3]]),
iosevka('<===', [31, 3158, 3179, 3168], [[0, 4]]),
iosevka('<=====', [31, 3158, 3179, 3168, 3180, 3180], [[0, 6]]),
iosevka('=>', [3155, 33], [[0, 2]]),
iosevka('==>', [3169, 3157, 33], [[0, 3]]),
iosevka('===>', [3169, 3179, 3157, 33], [[0, 4]]),
iosevka('=====>', [3182, 3182, 3169, 3179, 3157, 33], [[0, 6]]),
iosevka('<=>', [31, 3178, 33], [[0, 3]]),
iosevka('<==>', [31, 3158, 3157, 33], [[0, 4]]),
iosevka('<===>', [31, 3158, 3179, 3157, 33], [[0, 5]]),
iosevka('<=====>', [31, 3158, 3179, 3179, 3179, 3157, 33], [[0, 7]]),
iosevka('<!--', [31, 3184, 3130, 3139], [[0, 4]]),
iosevka('<!---', [31, 3184, 3130, 3150, 3139], [[0, 5]]),
iosevka('<!-----', [31, 3184, 3130, 3150, 3139, 3151, 3151], [[0, 7]]),
iosevka('a:b', [68, 29, 69], []),
iosevka('a::b', [68, 3012, 3013, 69], [[1, 3]]),
iosevka('a:::b', [68, 3012, 3010, 3013, 69], [[1, 4]]),
iosevka(':=', [3011, 32], [[0, 2]]),
iosevka(':-', [3011, 16], [[0, 2]]),
iosevka(':+', [3011, 14], [[0, 2]]),
iosevka('=:', [32, 3011], [[0, 2]]),
iosevka('-:', [16, 3011], [[0, 2]]),
iosevka('+:', [14, 3011], [[0, 2]]),
iosevka('<*', [31, 3023], [[0, 2]]),
iosevka('*>', [3023, 33], [[0, 2]]),
iosevka('<*>', [31, 3023, 33], [[1, 3]]),
iosevka('<**>', [31, 3023, 3023, 33], [[1, 4]]),
iosevka('<****>', [31, 3023, 3023, 3023, 3023, 33], [[0, 3], [3, 6]]),
iosevka('==', [3083, 3084], [[0, 2]]),
iosevka('!=', [3098, 3084], [[0, 2]]),
iosevka('===', [3083, 3085, 3084], [[0, 3]]),
iosevka('!==', [3099, 3085, 3084], [[0, 3]]),
iosevka('====', [3083, 3085, 3085, 3084], [[0, 4]]),
iosevka('!===', [3100, 3085, 3085, 3084], [[0, 4]])
];
const monoidCases: ITestCase[] = [
monoid('<!--', [775, 775, 775, 643], [[0, 4]]),
monoid('-->', [779, 779, 628], [[0, 3]]),
monoid('<--', [776, 776, 627], [[0, 3]]),
monoid('->>', [780, 780, 626], [[0, 3]]),
monoid('<<-', [777, 777, 625], [[0, 3]]),
monoid('->', [781, 623], [[0, 2]]),
monoid('<-', [778, 624], [[0, 2]]),
monoid('=>', [793, 666], [[0, 2]]),
monoid('<=>', [785, 785, 760], [[0, 3]]),
monoid('<==>', [786, 786, 786, 771], [[0, 4]]),
monoid('==>', [787, 787, 672], [[0, 3]]),
monoid('<==', [788, 788, 671], [[0, 3]]),
monoid('>>=', [791, 791, 758], [[0, 3]]),
monoid('=<<', [792, 792, 759], [[0, 3]]),
monoid('--', [667, 667], [[0, 2]]),
monoid(':=', [29, 761], [[0, 2]]),
monoid('=:=', [789, 789, 665], [[0, 3]]),
monoid('==', [794, 641], [[0, 2]]),
monoid('!==', [782, 782, 646], [[0, 3]]),
monoid('!=', [783, 629], [[0, 2]]),
monoid('<=', [790, 630], [[0, 2]]),
monoid('>=', [792, 631], [[0, 2]]),
monoid('//', [621, 664], [[0, 2]]),
monoid('/**', [18, 753, 753], [[0, 3]]),
monoid('/*', [18, 753], [[0, 2]]),
monoid('*/', [754, 18], [[0, 2]]),
monoid('&&', [633, 775], [[0, 2]]),
monoid('.&', [17, 755], [[0, 2]]),
monoid('||', [634, 635], [[0, 2]]),
monoid('!!', [769, 770], [[0, 2]]),
monoid('::', [772, 773], [[0, 2]]),
monoid('>>', [637, 638], [[0, 2]]),
monoid('<<', [639, 640], [[0, 2]]),
monoid('¯\\_(ツ)_/¯', [113, 765, 66, 767, 613, 768, 66, 766, 113], [[0, 3], [3, 6], [6, 9]]),
monoid('__', [763, 764], [[0, 2]])
];
const ubuntuCases: ITestCase[] = [
ubuntu('==>', [32, 32, 33], [])
];
const fontPaths: Record<string, string> = {
'Fira Code': path.join(__dirname, '../../fonts/FiraCode-Regular.otf'),
'Iosevka': path.join(__dirname, '../../fonts/iosevka-regular.ttf'),
'Monoid': path.join(__dirname, '../../fonts/Monoid-Regular.ttf'),
'Ubuntu Mono': path.join(__dirname, '../../fonts/UbuntuMono-Regular.ttf')
};
const fontCache: Map<string, IFont> = new Map();
function loadFont(fontName: string): IFont {
let font = fontCache.get(fontName);
if (!font) {
const fontPath = fontPaths[fontName];
const buffer = fs.readFileSync(fontPath);
font = loadBuffer(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength));
fontCache.set(fontName, font);
}
return font;
}
describe('addon-ligatures - index', () => {
describe('findLigatures', () => {
for (const { font: fontName, input, glyphs, ranges } of [...firaCases, ...iosevkaCases, ...monoidCases, ...ubuntuCases]) {
it(`${fontName}: '${input}'`, () => {
const font = loadFont(fontName);
const result = font.findLigatures(input);
assert.deepEqual(result.outputGlyphs, glyphs);
assert.deepEqual(result.contextRanges, ranges);
});
}
});
describe('findLigatureRanges', () => {
for (const { font: fontName, input, ranges } of [...firaCases, ...iosevkaCases, ...monoidCases, ...ubuntuCases]) {
it(`${fontName}: '${input}'`, () => {
const font = loadFont(fontName);
const result = font.findLigatureRanges(input);
assert.deepEqual(result, ranges);
});
}
});
describe('caching', () => {
it('findLigatures caches successive calls correctly', () => {
const fontPath = fontPaths['Fira Code'];
const buffer = fs.readFileSync(fontPath);
const font = loadBuffer(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength), { cacheSize: 100 });
const result1 = font.findLigatures('in --> out');
const result2 = font.findLigatures('in --> out');
assert.deepEqual(result1, result2);
});
it('findLigatureRanges caches successive calls correctly', () => {
const fontPath = fontPaths['Fira Code'];
const buffer = fs.readFileSync(fontPath);
const font = loadBuffer(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength), { cacheSize: 100 });
const result1 = font.findLigatureRanges('in --> out');
const result2 = font.findLigatureRanges('in --> out');
assert.deepEqual(result1, result2);
});
it('caches calls to findLigatures after findLigatureRanges correctly', () => {
const fontPath = fontPaths['Fira Code'];
const buffer = fs.readFileSync(fontPath);
const uncached = loadBuffer(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength));
const uncachedResult1 = uncached.findLigatureRanges('in --> out');
const uncachedResult2 = uncached.findLigatures('in --> out');
const font = loadBuffer(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength), { cacheSize: 100 });
const result1 = font.findLigatureRanges('in --> out');
const result2 = font.findLigatures('in --> out');
assert.deepEqual(result1, uncachedResult1);
assert.deepEqual(result2, uncachedResult2);
assert.deepEqual(result1, result2.contextRanges);
});
it('caches calls to findLigatureRanges after findLigatures correctly', () => {
const fontPath = fontPaths['Fira Code'];
const buffer = fs.readFileSync(fontPath);
const uncached = loadBuffer(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength));
const uncachedResult1 = uncached.findLigatures('in --> out');
const uncachedResult2 = uncached.findLigatureRanges('in --> out');
const font = loadBuffer(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength), { cacheSize: 100 });
const result1 = font.findLigatures('in --> out');
const result2 = font.findLigatureRanges('in --> out');
assert.deepEqual(result1, uncachedResult1);
assert.deepEqual(result2, uncachedResult2);
assert.deepEqual(result1.contextRanges, result2);
});
});
});
@@ -0,0 +1,262 @@
import * as opentype from 'opentype.js';
import LRUCache = require('lru-cache');
import { IFont, ILigatureData, IFlattenedLookupTree, ILookupTree, IOptions } from './types';
import mergeTrees from './merge';
import walkTree from './walk';
import mergeRange from './mergeRange';
import buildTreeGsubType6Format1 from './processors/6-1';
import buildTreeGsubType6Format2 from './processors/6-2';
import buildTreeGsubType6Format3 from './processors/6-3';
import buildTreeGsubType8Format1 from './processors/8-1';
import flatten from './flatten';
class FontImpl implements IFont {
private _font: opentype.Font;
private _lookupTrees: { tree: IFlattenedLookupTree, processForward: boolean }[] = [];
private _glyphLookups: { [glyphId: string]: number[] } = {};
private _cache?: LRUCache<string, ILigatureData | [number, number][]>;
constructor(font: opentype.Font, options: Required<IOptions>) {
this._font = font;
if (options.cacheSize > 0) {
this._cache = new LRUCache({
max: options.cacheSize,
length: ((val: ILigatureData | [number, number][], key: string) => key.length) as any
});
}
const caltFeatures = this._font.tables.gsub && this._font.tables.gsub.features.filter((f: { tag: string }) => f.tag === 'calt') || [];
const lookupIndices: number[] = caltFeatures
.reduce((acc: number[], val: { feature: { lookupListIndexes: number[] } }) => [...acc, ...val.feature.lookupListIndexes], []);
const allLookups = this._font.tables.gsub && this._font.tables.gsub.lookups || [];
const lookupGroups = allLookups.filter((l: unknown, i: number) => lookupIndices.some(idx => idx === i));
for (const [index, lookup] of lookupGroups.entries()) {
const trees: ILookupTree[] = [];
switch (lookup.lookupType) {
case 6:
for (const [index, table] of lookup.subtables.entries()) {
switch (table.substFormat) {
case 1:
trees.push(buildTreeGsubType6Format1(table, allLookups, index));
break;
case 2:
trees.push(buildTreeGsubType6Format2(table, allLookups, index));
break;
case 3:
trees.push(buildTreeGsubType6Format3(table, allLookups, index));
break;
}
}
break;
case 8:
for (const [index, table] of lookup.subtables.entries()) {
trees.push(buildTreeGsubType8Format1(table, index));
}
break;
}
const tree = flatten(mergeTrees(trees));
this._lookupTrees.push({
tree,
processForward: lookup.lookupType !== 8
});
for (const glyphId of Object.keys(tree)) {
if (!this._glyphLookups[glyphId]) {
this._glyphLookups[glyphId] = [];
}
this._glyphLookups[glyphId].push(index);
}
}
}
public findLigatures(text: string): ILigatureData {
const cached = this._cache && this._cache.get(text);
if (cached && !Array.isArray(cached)) {
return cached;
}
const glyphIds: number[] = [];
for (const char of text) {
glyphIds.push(this._font.charToGlyphIndex(char));
}
// If there are no lookup groups, there's no point looking for
// replacements. This gives us a minor performance boost for fonts with
// no ligatures
if (this._lookupTrees.length === 0) {
return {
inputGlyphs: glyphIds,
outputGlyphs: glyphIds,
contextRanges: []
};
}
const result = this._findInternal(glyphIds.slice());
const finalResult: ILigatureData = {
inputGlyphs: glyphIds,
outputGlyphs: result.sequence,
contextRanges: result.ranges
};
if (this._cache) {
this._cache.set(text, finalResult);
}
return finalResult;
}
public findLigatureRanges(text: string): [number, number][] {
// Short circuit the process if there are no possible ligatures in the
// font
if (this._lookupTrees.length === 0) {
return [];
}
const cached = this._cache && this._cache.get(text);
if (cached) {
return Array.isArray(cached) ? cached : cached.contextRanges;
}
const glyphIds: number[] = [];
for (const char of text) {
glyphIds.push(this._font.charToGlyphIndex(char));
}
const result = this._findInternal(glyphIds);
if (this._cache) {
this._cache.set(text, result.ranges);
}
return result.ranges;
}
private _findInternal(sequence: number[]): { sequence: number[], ranges: [number, number][] } {
const ranges: [number, number][] = [];
let nextLookup = this._getNextLookup(sequence, 0);
while (nextLookup.index !== null) {
const lookup = this._lookupTrees[nextLookup.index];
if (lookup.processForward) {
let lastGlyphIndex = nextLookup.last;
for (let i = nextLookup.first; i < lastGlyphIndex; i++) {
const result = walkTree(lookup.tree, sequence, i, i);
if (result) {
for (let j = 0; j < result.substitutions.length; j++) {
const sub = result.substitutions[j];
if (sub !== null) {
sequence[i + j] = sub;
}
}
mergeRange(
ranges,
result.contextRange[0] + i,
result.contextRange[1] + i
);
// Substitutions can end up extending the search range
if (i + result.length >= lastGlyphIndex) {
lastGlyphIndex = i + result.length + 1;
}
i += result.length - 1;
}
}
} else {
// We don't need to do the lastGlyphIndex tracking here because
// reverse processing isn't allowed to replace more than one
// character at a time.
for (let i = nextLookup.last - 1; i >= nextLookup.first; i--) {
const result = walkTree(lookup.tree, sequence, i, i);
if (result) {
for (let j = 0; j < result.substitutions.length; j++) {
const sub = result.substitutions[j];
if (sub !== null) {
sequence[i + j] = sub;
}
}
mergeRange(
ranges,
result.contextRange[0] + i,
result.contextRange[1] + i
);
i -= result.length - 1;
}
}
}
nextLookup = this._getNextLookup(sequence, nextLookup.index + 1);
}
return { sequence, ranges };
}
/**
* Returns the lookup and glyph range for the first lookup that might
* contain a match.
*
* @param sequence Input glyph sequence
* @param start The first input to try
*/
private _getNextLookup(sequence: number[], start: number): { index: number | null, first: number, last: number } {
const result: { index: number | null, first: number, last: number } = {
index: null,
first: Infinity,
last: -1
};
// Loop through each glyph and find the first valid lookup for it
for (let i = 0; i < sequence.length; i++) {
const lookups = this._glyphLookups[sequence[i]];
if (!lookups) {
continue;
}
for (let j = 0; j < lookups.length; j++) {
const lookupIndex = lookups[j];
if (lookupIndex >= start) {
// Update the lookup information if it's the one we're
// storing or earlier than it.
if (result.index === null || lookupIndex <= result.index) {
result.index = lookupIndex;
if (result.first > i) {
result.first = i;
}
result.last = i + 1;
}
break;
}
}
}
return result;
}
}
/**
* Load the font from it's binary data. The returned value can be used to find
* ligatures for the font.
*
* @param buffer ArrayBuffer of the font to load
*/
export function loadBuffer(buffer: ArrayBuffer, options?: IOptions): IFont {
const font = opentype.parse(buffer);
return new FontImpl(font, {
cacheSize: 0,
...options
});
}
export { IFont as Font, ILigatureData as LigatureData, IOptions as Options };
@@ -0,0 +1,225 @@
/**
* Copyright (c) 2018 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { assert } from 'chai';
import mergeTrees from './merge';
interface ILookupResult {
contextRange: [number, number];
index: number;
subIndex: number;
length: number;
substitutions: number[];
}
function lookup(substitutionGlyph: number, index?: number, subIndex?: number): ILookupResult {
return {
contextRange: [0, 1],
index: index || 0,
subIndex: subIndex || 0,
length: 1,
substitutions: [substitutionGlyph]
};
}
describe('addon-ligatures - merge', () => {
describe('mergeTrees', () => {
it('combines disjoint trees', () => {
const result = mergeTrees([
{
individual: {
'1': { lookup: lookup(1) }
},
range: []
},
{
individual: {},
range: [{
entry: { lookup: lookup(2) },
range: [2, 4]
}]
},
{
individual: {
'5': { lookup: lookup(3) }
},
range: []
},
{
individual: {},
range: [{
entry: { lookup: lookup(4) },
range: [8, 10]
}]
}
]);
assert.deepEqual(result, {
individual: {
'1': { lookup: lookup(1) },
'5': { lookup: lookup(3) }
},
range: [{
entry: { lookup: lookup(2) },
range: [2, 4]
}, {
entry: { lookup: lookup(4) },
range: [8, 10]
}]
});
});
it('merges matching individual glyphs', () => {
const result = mergeTrees([
{
individual: {
'1': { lookup: lookup(1, 1) }
},
range: []
},
{
individual: {
'1': { lookup: lookup(2, 0) }
},
range: []
},
{
individual: {
'1': { lookup: lookup(3, 2) }
},
range: []
}
]);
assert.deepEqual(result, {
individual: {
'1': { lookup: lookup(2, 0) }
},
range: []
});
});
it('merges range glyphs overlapping individual glyphs', () => {
const result = mergeTrees([
{
individual: {
'1': { lookup: lookup(1, 0) }
},
range: []
},
{
individual: {},
range: [{
entry: { lookup: lookup(2, 1) },
range: [0, 4]
}]
}
]);
assert.deepEqual(result, {
individual: {
'0': { lookup: lookup(2, 1) },
'1': { lookup: lookup(1, 0) }
},
range: [{
entry: { lookup: lookup(2, 1) },
range: [2, 4]
}]
});
});
it('merges individual glyphs overlapping range glyphs', () => {
const result = mergeTrees([
{
individual: {},
range: [{
entry: { lookup: lookup(2, 1) },
range: [0, 4]
}]
},
{
individual: {
'1': { lookup: lookup(1, 0) }
},
range: []
}
]);
assert.deepEqual(result, {
individual: {
'0': { lookup: lookup(2, 1) },
'1': { lookup: lookup(1, 0) }
},
range: [{
entry: { lookup: lookup(2, 1) },
range: [2, 4]
}]
});
});
it('merges multiple overlapping ranges', () => {
const result = mergeTrees([
{
individual: {},
range: [{
entry: { lookup: lookup(1, 2) },
range: [0, 3]
}, {
entry: { lookup: lookup(2, 1) },
range: [6, 12]
}, {
entry: { lookup: lookup(5, 3) },
range: [15, 20]
}, {
entry: { lookup: lookup(7, 4) },
range: [20, 22]
}]
},
{
individual: {},
range: [{
entry: { lookup: lookup(3, 0) },
range: [2, 8]
}, {
entry: { lookup: lookup(4, 0) },
range: [10, 13]
}, {
entry: { lookup: lookup(6, 0) },
range: [16, 21]
}]
}
]);
assert.deepEqual(result, {
individual: {
'2': { lookup: lookup(3, 0) },
'12': { lookup: lookup(4, 0) },
'15': { lookup: lookup(5, 3) },
'20': { lookup: lookup(6, 0) },
'21': { lookup: lookup(7, 4) }
},
range: [{
entry: { lookup: lookup(1, 2) },
range: [0, 2]
}, {
entry: { lookup: lookup(3, 0) },
range: [6, 8]
}, {
entry: { lookup: lookup(3, 0) },
range: [3, 6]
}, {
entry: { lookup: lookup(2, 1) },
range: [8, 10]
}, {
entry: { lookup: lookup(4, 0) },
range: [10, 12]
}, {
entry: { lookup: lookup(6, 0) },
range: [16, 20]
}]
});
});
});
});
@@ -0,0 +1,393 @@
import { ILookupTree, ILookupTreeEntry } from './types';
/**
* Merges the provided trees into a single lookup tree. When conflicting lookups
* are encountered between two trees, the one with the lower index, then the
* lower subindex is chosen.
*
* @param trees Array of trees to merge. Entries in earlier trees are favored
* over those in later trees when there is a choice.
*/
export default function mergeTrees(trees: ILookupTree[]): ILookupTree {
const result: ILookupTree = {
individual: {},
range: []
};
const mergedEntries = new WeakMap<ILookupTreeEntry, Set<ILookupTreeEntry>>();
for (const tree of trees) {
mergeSubtree(result, tree, mergedEntries);
}
return result;
}
/**
* Recursively merges the data for the mergeTree into the mainTree.
*
* @param mainTree The tree where the values should be merged
* @param mergeTree The tree to be merged into the mainTree
* @param mergedEntries WeakMap to track already merged entry pairs
*/
function mergeSubtree(mainTree: ILookupTree, mergeTree: ILookupTree, mergedEntries: WeakMap<ILookupTreeEntry, Set<ILookupTreeEntry>>): void {
// Need to fix this recursively (and handle lookups)
for (const [glyphId, value] of Object.entries(mergeTree.individual)) {
// The main tree is guaranteed to have no overlaps between the
// individual and range values, so if we match an invididual, there
// must not be a range
if (mainTree.individual[glyphId]) {
mergeTreeEntry(mainTree.individual[glyphId], value, mergedEntries);
} else {
let matched = false;
for (const [index, { range, entry }] of mainTree.range.entries()) {
const overlap = getIndividualOverlap(Number(glyphId), range);
// Don't overlap
if (overlap.both === null) {
continue;
}
matched = true;
// If they overlap, we have to split the range and then
// merge the overlap
mainTree.individual[glyphId] = value;
mergeTreeEntry(mainTree.individual[glyphId], cloneEntry(entry), mergedEntries);
// When there's an overlap, we also have to fix up the range
// that we had already processed
mainTree.range.splice(index, 1);
for (const glyph of overlap.second) {
if (Array.isArray(glyph)) {
mainTree.range.push({
range: glyph,
entry: cloneEntry(entry)
});
} else {
mainTree.individual[glyph] = cloneEntry(entry);
}
}
}
if (!matched) {
mainTree.individual[glyphId] = value;
}
}
}
for (const { range, entry } of mergeTree.range) {
// Ranges are more complicated, because they can overlap with
// multiple things, individual and range alike. We start by
// eliminating ranges that are already present in another range
let remainingRanges: (number | [number, number])[] = [range];
for (let index = 0; index < mainTree.range.length; index++) {
const { range, entry: resultEntry } = mainTree.range[index];
for (const [remainingIndex, remainingRange] of remainingRanges.entries()) {
if (Array.isArray(remainingRange)) {
const overlap = getRangeOverlap(remainingRange, range);
if (overlap.both === null) {
continue;
}
mainTree.range.splice(index, 1);
index--;
const entryToMerge: ILookupTreeEntry = cloneEntry(resultEntry);
if (Array.isArray(overlap.both)) {
mainTree.range.push({
range: overlap.both,
entry: entryToMerge
});
} else {
mainTree.individual[overlap.both] = entryToMerge;
}
mergeTreeEntry(entryToMerge, cloneEntry(entry), mergedEntries);
for (const second of overlap.second) {
if (Array.isArray(second)) {
mainTree.range.push({
range: second,
entry: cloneEntry(resultEntry)
});
} else {
mainTree.individual[second] = cloneEntry(resultEntry);
}
}
remainingRanges = overlap.first;
} else {
const overlap = getIndividualOverlap(remainingRange, range);
if (overlap.both === null) {
continue;
}
// If they overlap, we have to split the range and then
// merge the overlap
mainTree.individual[remainingRange] = cloneEntry(entry);
mergeTreeEntry(mainTree.individual[remainingRange], cloneEntry(resultEntry), mergedEntries);
// When there's an overlap, we also have to fix up the range
// that we had already processed
mainTree.range.splice(index, 1);
index--;
for (const glyph of overlap.second) {
if (Array.isArray(glyph)) {
mainTree.range.push({
range: glyph,
entry: cloneEntry(resultEntry)
});
} else {
mainTree.individual[glyph] = cloneEntry(resultEntry);
}
}
remainingRanges.splice(remainingIndex, 1, ...overlap.first);
break;
}
}
}
// Next, we run the same against any individual glyphs
for (const glyphId of Object.keys(mainTree.individual)) {
for (const [remainingIndex, remainingRange] of remainingRanges.entries()) {
if (Array.isArray(remainingRange)) {
const overlap = getIndividualOverlap(Number(glyphId), remainingRange);
if (overlap.both === null) {
continue;
}
// If they overlap, we have to merge the overlap
mergeTreeEntry(mainTree.individual[glyphId], cloneEntry(entry), mergedEntries);
// Update the remaining ranges
remainingRanges.splice(remainingIndex, 1, ...overlap.second);
break;
} else {
if (Number(glyphId) === remainingRange) {
mergeTreeEntry(mainTree.individual[glyphId], cloneEntry(entry), mergedEntries);
break;
}
}
}
}
// Any remaining ranges should just be added directly
for (const remainingRange of remainingRanges) {
if (Array.isArray(remainingRange)) {
mainTree.range.push({
range: remainingRange,
entry: cloneEntry(entry)
});
} else {
mainTree.individual[remainingRange] = cloneEntry(entry);
}
}
}
}
/**
* Recursively merges the entry forr the mergeTree into the mainTree
*
* @param mainTree The entry where the values should be merged
* @param mergeTree The entry to merge into the mainTree
* @param mergedEntries WeakMap to track already merged entry pairs
*/
function mergeTreeEntry(mainTree: ILookupTreeEntry, mergeTree: ILookupTreeEntry, mergedEntries: WeakMap<ILookupTreeEntry, Set<ILookupTreeEntry>>): void {
// Check if we've already merged this pair
let mergedSet = mergedEntries.get(mainTree);
if (mergedSet?.has(mergeTree)) {
return;
}
if (!mergedSet) {
mergedSet = new Set();
mergedEntries.set(mainTree, mergedSet);
}
mergedSet.add(mergeTree);
if (
mergeTree.lookup && (
!mainTree.lookup ||
mainTree.lookup.index > mergeTree.lookup.index ||
(mainTree.lookup.index === mergeTree.lookup.index && mainTree.lookup.subIndex > mergeTree.lookup.subIndex)
)
) {
mainTree.lookup = mergeTree.lookup;
}
if (mergeTree.forward) {
if (!mainTree.forward) {
mainTree.forward = mergeTree.forward;
} else {
mergeSubtree(mainTree.forward, mergeTree.forward, mergedEntries);
}
}
if (mergeTree.reverse) {
if (!mainTree.reverse) {
mainTree.reverse = mergeTree.reverse;
} else {
mergeSubtree(mainTree.reverse, mergeTree.reverse, mergedEntries);
}
}
}
interface IOverlap {
first: (number | [number, number])[];
second: (number | [number, number])[];
both: number | [number, number] | null;
}
/**
* Determines the overlap (if any) between two ranges. Returns the distinct
* ranges for each range and the overlap (if any).
*
* @param first First range
* @param second Second range
*/
function getRangeOverlap(first: [number, number], second: [number, number]): IOverlap {
const result: IOverlap = {
first: [],
second: [],
both: null
};
// Both
if (first[0] < second[1] && second[0] < first[1]) {
const start = Math.max(first[0], second[0]);
const end = Math.min(first[1], second[1]);
result.both = rangeOrIndividual(start, end);
}
// Before
if (first[0] < second[0]) {
const start = first[0];
const end = Math.min(second[0], first[1]);
result.first.push(rangeOrIndividual(start, end));
} else if (second[0] < first[0]) {
const start = second[0];
const end = Math.min(second[1], first[0]);
result.second.push(rangeOrIndividual(start, end));
}
// After
if (first[1] > second[1]) {
const start = Math.max(first[0], second[1]);
const end = first[1];
result.first.push(rangeOrIndividual(start, end));
} else if (second[1] > first[1]) {
const start = Math.max(first[1], second[0]);
const end = second[1];
result.second.push(rangeOrIndividual(start, end));
}
return result;
}
/**
* Determines the overlap (if any) between the individual glyph and the range
* provided. Returns the glyphs and/or ranges that are unique to each provided
* and the overlap (if any).
*
* @param first Individual glyph
* @param second Range
*/
function getIndividualOverlap(first: number, second: [number, number]): IOverlap {
// Disjoint
if (first < second[0] || first > second[1]) {
return {
first: [first],
second: [second],
both: null
};
}
const result: IOverlap = {
first: [],
second: [],
both: first
};
if (second[0] < first) {
result.second.push(rangeOrIndividual(second[0], first));
}
if (second[1] > first) {
result.second.push(rangeOrIndividual(first + 1, second[1]));
}
return result;
}
/**
* Returns an individual glyph if the range is of size one or a range if it is
* larger.
*
* @param start Beginning of the range (inclusive)
* @param end End of the range (exclusive)
*/
function rangeOrIndividual(start: number, end: number): number | [number, number] {
if (end - start === 1) {
return start;
}
return [start, end];
}
/**
* Clones an individual lookup tree entry.
*
* @param entry Lookup tree entry to clone
* @param visited Map to track already cloned entries (prevents infinite loops)
*/
function cloneEntry(entry: ILookupTreeEntry, visited: Map<ILookupTreeEntry, ILookupTreeEntry> = new Map()): ILookupTreeEntry {
if (visited.has(entry)) {
return visited.get(entry)!;
}
const result: ILookupTreeEntry = {};
visited.set(entry, result);
if (entry.forward) {
result.forward = cloneTree(entry.forward, visited);
}
if (entry.reverse) {
result.reverse = cloneTree(entry.reverse, visited);
}
if (entry.lookup) {
result.lookup = {
contextRange: entry.lookup.contextRange.slice() as [number, number],
index: entry.lookup.index,
length: entry.lookup.length,
subIndex: entry.lookup.subIndex,
substitutions: entry.lookup.substitutions.slice()
};
}
return result;
}
/**
* Clones a lookup tree.
*
* @param tree Lookup tree to clone
* @param visited Map to track already cloned entries (prevents infinite loops)
*/
function cloneTree(tree: ILookupTree, visited: Map<ILookupTreeEntry, ILookupTreeEntry> = new Map()): ILookupTree {
const individual: { [glyphId: string]: ILookupTreeEntry } = {};
for (const [glyphId, entry] of Object.entries(tree.individual)) {
individual[glyphId] = cloneEntry(entry, visited);
}
return {
individual,
range: tree.range.map(({ range, entry }) => ({
range: range.slice() as [number, number],
entry: cloneEntry(entry, visited)
}))
};
}
@@ -0,0 +1,49 @@
/**
* Copyright (c) 2018 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { assert } from 'chai';
import mergeRange from './mergeRange';
describe('addon-ligatures - mergeRange', () => {
it('inserts a new range before the existing ones', () => {
const result = mergeRange([[1, 2], [2, 3]], 0, 1);
assert.deepEqual(result, [[0, 1], [1, 2], [2, 3]]);
});
it('inserts in between two ranges', () => {
const result = mergeRange([[0, 2], [4, 6]], 2, 4);
assert.deepEqual(result, [[0, 2], [2, 4], [4, 6]]);
});
it('inserts after the last range', () => {
const result = mergeRange([[0, 2], [4, 6]], 6, 8);
assert.deepEqual(result, [[0, 2], [4, 6], [6, 8]]);
});
it('extends the beginning of a range', () => {
const result = mergeRange([[0, 2], [4, 6]], 3, 5);
assert.deepEqual(result, [[0, 2], [3, 6]]);
});
it('extends the end of a range', () => {
const result = mergeRange([[0, 2], [4, 6]], 1, 4);
assert.deepEqual(result, [[0, 4], [4, 6]]);
});
it('extends the last range', () => {
const result = mergeRange([[0, 2], [4, 6]], 5, 7);
assert.deepEqual(result, [[0, 2], [4, 7]]);
});
it('connects two ranges', () => {
const result = mergeRange([[0, 2], [4, 6]], 1, 5);
assert.deepEqual(result, [[0, 6]]);
});
it('connects more than two ranges', () => {
const result = mergeRange([[0, 2], [4, 6], [8, 10], [12, 14]], 1, 10);
assert.deepEqual(result, [[0, 10], [12, 14]]);
});
});
@@ -0,0 +1,66 @@
/**
* Merges the range defined by the provided start and end into the list of
* existing ranges. The merge is done in place on the existing range for
* performance and is also returned.
*
* @param ranges Existing range list
* @param newRangeStart Start position of the range to merge, inclusive
* @param newRangeEnd End position of range to merge, exclusive
*/
export default function mergeRange(ranges: [number, number][], newRangeStart: number, newRangeEnd: number): [number, number][] {
let inRange = false;
for (let i = 0; i < ranges.length; i++) {
const range = ranges[i];
if (!inRange) {
if (newRangeEnd <= range[0]) {
// Case 1: New range is before the search range
ranges.splice(i, 0, [newRangeStart, newRangeEnd]);
return ranges;
}
if (newRangeEnd <= range[1]) {
// Case 2: New range is either wholly contained within the
// search range or overlaps with the front of it
range[0] = Math.min(newRangeStart, range[0]);
return ranges;
}
if (newRangeStart < range[1]) {
// Case 3: New range either wholly contains the search range
// or overlaps with the end of it
range[0] = Math.min(newRangeStart, range[0]);
inRange = true;
} else {
// Case 4: New range starts after the search range
continue;
}
} else {
if (newRangeEnd <= range[0]) {
// Case 5: New range extends from previous range but doesn't
// reach the current one
ranges[i - 1][1] = newRangeEnd;
return ranges;
}
if (newRangeEnd <= range[1]) {
// Case 6: New range extends from prvious range into the
// current range
ranges[i - 1][1] = Math.max(newRangeEnd, range[1]);
ranges.splice(i, 1);
inRange = false;
return ranges;
}
// Case 7: New range extends from previous range past the
// end of the current range
ranges.splice(i, 1);
i--;
}
}
if (inRange) {
// Case 8: New range extends past the last existing range
ranges[ranges.length - 1][1] = newRangeEnd;
} else {
// Case 9: New range starts after the last existing range
ranges.push([newRangeStart, newRangeEnd]);
}
return ranges;
}
@@ -0,0 +1,82 @@
import { ChainingContextualSubstitutionTable, Lookup } from '../tables';
import { ILookupTree } from '../types';
import { listGlyphsByIndex } from './coverage';
import { processInputPosition, processLookaheadPosition, processBacktrackPosition, getInputTree, IEntryMeta } from './helper';
/**
* Build lookup tree for GSUB lookup table 6, format 1.
* https://docs.microsoft.com/en-us/typography/opentype/spec/gsub#61-chaining-context-substitution-format-1-simple-glyph-contexts
*
* @param table JSON representation of the table
* @param lookups List of lookup tables
* @param tableIndex Index of this table in the overall lookup
*/
export default function buildTree(table: ChainingContextualSubstitutionTable.IFormat1, lookups: Lookup[], tableIndex: number): ILookupTree {
const result: ILookupTree = {
individual: {},
range: []
};
const firstGlyphs = listGlyphsByIndex(table.coverage);
for (const { glyphId, index } of firstGlyphs) {
const chainRuleSet = table.chainRuleSets[index];
// If the chain rule set is null there's nothing to do with this table.
if (!chainRuleSet) {
continue;
}
for (const [subIndex, subTable] of chainRuleSet.entries()) {
let currentEntries: IEntryMeta[] = getInputTree(
result,
subTable.lookupRecords,
lookups,
0,
glyphId
).map(({ entry, substitution }) => ({ entry, substitutions: [substitution] }));
// We walk forward, then backward
for (const [index, glyph] of subTable.input.entries()) {
currentEntries = processInputPosition(
[glyph],
index + 1,
currentEntries,
subTable.lookupRecords,
lookups
);
}
for (const glyph of subTable.lookahead) {
currentEntries = processLookaheadPosition(
[glyph],
currentEntries
);
}
for (const glyph of subTable.backtrack) {
currentEntries = processBacktrackPosition(
[glyph],
currentEntries
);
}
// When we get to the end, insert the lookup information
for (const { entry, substitutions } of currentEntries) {
entry.lookup = {
substitutions,
length: subTable.input.length + 1,
index: tableIndex,
subIndex,
contextRange: [
-1 * subTable.backtrack.length,
1 + subTable.input.length + subTable.lookahead.length
]
};
}
}
}
return result;
}
@@ -0,0 +1,96 @@
import { ChainingContextualSubstitutionTable, Lookup } from '../tables';
import { ILookupTree } from '../types';
import mergeTrees from '../merge';
import { listGlyphsByIndex } from './coverage';
import getGlyphClass, { listClassGlyphs } from './classDef';
import { processInputPosition, processLookaheadPosition, processBacktrackPosition, getInputTree, IEntryMeta } from './helper';
/**
* Build lookup tree for GSUB lookup table 6, format 2.
* https://docs.microsoft.com/en-us/typography/opentype/spec/gsub#62-chaining-context-substitution-format-2-class-based-glyph-contexts
*
* @param table JSON representation of the table
* @param lookups List of lookup tables
* @param tableIndex Index of this table in the overall lookup
*/
export default function buildTree(table: ChainingContextualSubstitutionTable.IFormat2, lookups: Lookup[], tableIndex: number): ILookupTree {
const results: ILookupTree[] = [];
const firstGlyphs = listGlyphsByIndex(table.coverage);
for (const { glyphId } of firstGlyphs) {
const firstInputClass = getGlyphClass(table.inputClassDef, glyphId);
for (const [glyphId, inputClass] of firstInputClass.entries()) {
// istanbul ignore next - invalid font
if (inputClass === null) {
continue;
}
const classSet = table.chainClassSet[inputClass];
// If the class set is null there's nothing to do with this table.
if (!classSet) {
continue;
}
for (const [subIndex, subTable] of classSet.entries()) {
const result: ILookupTree = {
individual: {},
range: []
};
let currentEntries: IEntryMeta[] = getInputTree(
result,
subTable.lookupRecords,
lookups,
0,
glyphId
).map(({ entry, substitution }) => ({ entry, substitutions: [substitution] }));
for (const [index, classNum] of subTable.input.entries()) {
currentEntries = processInputPosition(
listClassGlyphs(table.inputClassDef, classNum),
index + 1,
currentEntries,
subTable.lookupRecords,
lookups
);
}
for (const classNum of subTable.lookahead) {
currentEntries = processLookaheadPosition(
listClassGlyphs(table.lookaheadClassDef, classNum),
currentEntries
);
}
for (const classNum of subTable.backtrack) {
currentEntries = processBacktrackPosition(
listClassGlyphs(table.backtrackClassDef, classNum),
currentEntries
);
}
// When we get to the end, all of the entries we've accumulated
// should have a lookup defined
for (const { entry, substitutions } of currentEntries) {
entry.lookup = {
substitutions,
index: tableIndex,
subIndex,
length: subTable.input.length + 1,
contextRange: [
-1 * subTable.backtrack.length,
1 + subTable.input.length + subTable.lookahead.length
]
};
}
results.push(result);
}
}
}
return mergeTrees(results);
}
@@ -0,0 +1,73 @@
import { ChainingContextualSubstitutionTable, Lookup } from '../tables';
import { ILookupTree } from '../types';
import { listGlyphsByIndex } from './coverage';
import { processInputPosition, processLookaheadPosition, processBacktrackPosition, getInputTree, IEntryMeta } from './helper';
/**
* Build lookup tree for GSUB lookup table 6, format 3.
* https://docs.microsoft.com/en-us/typography/opentype/spec/gsub#63-chaining-context-substitution-format-3-coverage-based-glyph-contexts
*
* @param table JSON representation of the table
* @param lookups List of lookup tables
* @param tableIndex Index of this table in the overall lookup
*/
export default function buildTree(table: ChainingContextualSubstitutionTable.IFormat3, lookups: Lookup[], tableIndex: number): ILookupTree {
const result: ILookupTree = {
individual: {},
range: []
};
const firstGlyphs = listGlyphsByIndex(table.inputCoverage[0]);
for (const { glyphId } of firstGlyphs) {
let currentEntries: IEntryMeta[] = getInputTree(
result,
table.lookupRecords,
lookups,
0,
glyphId
).map(({ entry, substitution }) => ({ entry, substitutions: [substitution] }));
for (const [index, coverage] of table.inputCoverage.slice(1).entries()) {
currentEntries = processInputPosition(
listGlyphsByIndex(coverage).map(glyph => glyph.glyphId),
index + 1,
currentEntries,
table.lookupRecords,
lookups
);
}
for (const coverage of table.lookaheadCoverage) {
currentEntries = processLookaheadPosition(
listGlyphsByIndex(coverage).map(glyph => glyph.glyphId),
currentEntries
);
}
for (const coverage of table.backtrackCoverage) {
currentEntries = processBacktrackPosition(
listGlyphsByIndex(coverage).map(glyph => glyph.glyphId),
currentEntries
);
}
// When we get to the end, all of the entries we've accumulated
// should have a lookup defined
for (const { entry, substitutions } of currentEntries) {
entry.lookup = {
substitutions,
index: tableIndex,
subIndex: 0,
length: table.inputCoverage.length,
contextRange: [
-1 * table.backtrackCoverage.length,
table.inputCoverage.length + table.lookaheadCoverage.length
]
};
}
}
return result;
}
@@ -0,0 +1,69 @@
import { IReverseChainingContextualSingleSubstitutionTable } from '../tables';
import { ILookupTree, ILookupTreeEntry } from '../types';
import { listGlyphsByIndex } from './coverage';
import { processLookaheadPosition, processBacktrackPosition, IEntryMeta } from './helper';
/**
* Build lookup tree for GSUB lookup table 8, format 1.
* https://docs.microsoft.com/en-us/typography/opentype/spec/gsub#81-reverse-chaining-contextual-single-substitution-format-1-coverage-based-glyph-contexts
*
* @param table JSON representation of the table
* @param tableIndex Index of this table in the overall lookup
*/
export default function buildTree(table: IReverseChainingContextualSingleSubstitutionTable, tableIndex: number): ILookupTree {
const result: ILookupTree = {
individual: {},
range: []
};
const glyphs = listGlyphsByIndex(table.coverage);
for (const { glyphId, index } of glyphs) {
const initialEntry: ILookupTreeEntry = {};
if (Array.isArray(glyphId)) {
result.range.push({
entry: initialEntry,
range: glyphId
});
} else {
result.individual[glyphId] = initialEntry;
}
let currentEntries: IEntryMeta[] = [{
entry: initialEntry,
substitutions: [table.substitutes[index]]
}];
// We walk forward, then backward
for (const coverage of table.lookaheadCoverage) {
currentEntries = processLookaheadPosition(
listGlyphsByIndex(coverage).map(glyph => glyph.glyphId),
currentEntries
);
}
for (const coverage of table.backtrackCoverage) {
currentEntries = processBacktrackPosition(
listGlyphsByIndex(coverage).map(glyph => glyph.glyphId),
currentEntries
);
}
// When we get to the end, insert the lookup information
for (const { entry, substitutions } of currentEntries) {
entry.lookup = {
substitutions,
index: tableIndex,
subIndex: 0,
length: 1,
contextRange: [
-1 * table.backtrackCoverage.length,
1 + table.lookaheadCoverage.length
]
};
}
}
return result;
}
@@ -0,0 +1,84 @@
import { ClassDefTable } from '../tables';
/**
* Get the number of the class to which the glyph belongs, or null if it doesn't
* belong to any of them.
*
* @param table JSON representation of the class def table
* @param glyphId Index of the glyph to look for
*/
export default function getGlyphClass(table: ClassDefTable, glyphId: number | [number, number]): Map<number | [number, number], number | null> {
switch (table.format) {
// https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#class-definition-table-format-2
case 2:
if (Array.isArray(glyphId)) {
return getRangeGlyphClass(table, glyphId);
}
return new Map([[
glyphId,
getIndividualGlyphClass(table, glyphId)
]]);
// https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#class-definition-table-format-1
default:
return new Map([[glyphId, null]]);
}
}
function getRangeGlyphClass(table: ClassDefTable.IFormat2, glyphId: [number, number]): Map<number | [number, number], number | null> {
const classStart: number = glyphId[0];
const currentClass: number | null = getIndividualGlyphClass(table, classStart);
let search: number = glyphId[0] + 1;
const result = new Map<[number, number] | number, number | null>();
while (search < glyphId[1]) {
const clazz = getIndividualGlyphClass(table, search);
if (clazz !== currentClass) {
if (search - classStart <= 1) {
result.set(classStart, currentClass);
} else {
result.set([classStart, search], currentClass);
}
}
search++;
}
if (search - classStart <= 1) {
result.set(classStart, currentClass);
} else {
result.set([classStart, search], currentClass);
}
return result;
}
function getIndividualGlyphClass(table: ClassDefTable.IFormat2, glyphId: number): number | null {
for (const range of table.ranges) {
if (range.start <= glyphId && range.end >= glyphId) {
return range.classId;
}
}
return null;
}
export function listClassGlyphs(table: ClassDefTable, index: number): (number | [number, number])[] {
switch (table.format) {
case 2:
const results: (number | [number, number])[] = [];
for (const range of table.ranges) {
if (range.classId !== index) {
continue;
}
if (range.end === range.start) {
results.push(range.start);
} else {
results.push([range.start, range.end + 1]);
}
}
return results;
default:
return [];
}
}
@@ -0,0 +1,43 @@
import { CoverageTable } from '../tables';
/**
* Get the index of the given glyph in the coverage table, or null if it is not
* present in the table.
*
* @param table JSON representation of the coverage table
* @param glyphId Index of the glyph to look for
*/
export default function getCoverageGlyphIndex(table: CoverageTable, glyphId: number): number | null {
switch (table.format) {
// https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#coverage-format-1
case 1:
const index = table.glyphs.indexOf(glyphId);
return index !== -1
? index
: null;
// https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#coverage-format-2
case 2:
const range = table.ranges
.find(range => range.start <= glyphId && range.end >= glyphId);
return range
? range.index
: null;
}
}
export function listGlyphsByIndex(table: CoverageTable): { glyphId: number | [number, number], index: number }[] {
switch (table.format) {
case 1:
return table.glyphs.map((glyphId, index) => ({ glyphId, index }));
case 2:
const results: { glyphId: number | [number, number], index: number }[] = [];
for (const [index, range] of table.ranges.entries()) {
if (range.end === range.start) {
results.push({ glyphId: range.start, index });
} else {
results.push({ glyphId: [range.start, range.end + 1], index });
}
}
return results;
}
}
@@ -0,0 +1,187 @@
import { ILookupTreeEntry, ILookupTree } from '../types';
import { ISubstitutionLookupRecord, Lookup } from '../tables';
import { getIndividualSubstitutionGlyph, getRangeSubstitutionGlyphs } from './substitution';
export interface IEntryMeta {
entry: ILookupTreeEntry;
substitutions: (number | null)[];
}
export function processInputPosition(
glyphs: (number | [number, number])[],
position: number,
currentEntries: IEntryMeta[],
lookupRecords: ISubstitutionLookupRecord[],
lookups: Lookup[]
): IEntryMeta[] {
const nextEntries: IEntryMeta[] = [];
for (const currentEntry of currentEntries) {
currentEntry.entry.forward = {
individual: {},
range: []
};
for (const glyph of glyphs) {
nextEntries.push(...getInputTree(
currentEntry.entry.forward,
lookupRecords,
lookups,
position,
glyph
).map(({ entry, substitution }) => ({
entry,
substitutions: [...currentEntry.substitutions, substitution]
})));
}
}
return nextEntries;
}
export function processLookaheadPosition(
glyphs: (number | [number, number])[],
currentEntries: IEntryMeta[]
): IEntryMeta[] {
const nextEntries: IEntryMeta[] = [];
const processedEntries = new Set<ILookupTreeEntry>();
for (const currentEntry of currentEntries) {
// Skip if we've already processed this entry object
if (processedEntries.has(currentEntry.entry)) {
continue;
}
processedEntries.add(currentEntry.entry);
if (!currentEntry.entry.forward) {
currentEntry.entry.forward = {
individual: {},
range: []
};
}
// All glyphs at this position share ONE entry - lookahead just needs to match,
// all paths lead to the same result
const sharedEntry: ILookupTreeEntry = {};
for (const glyph of glyphs) {
if (Array.isArray(glyph)) {
currentEntry.entry.forward.range.push({
entry: sharedEntry,
range: glyph
});
} else {
currentEntry.entry.forward.individual[glyph] = sharedEntry;
}
}
nextEntries.push({
entry: sharedEntry,
substitutions: currentEntry.substitutions
});
}
return nextEntries;
}
export function processBacktrackPosition(
glyphs: (number | [number, number])[],
currentEntries: IEntryMeta[]
): IEntryMeta[] {
const nextEntries: IEntryMeta[] = [];
const processedEntries = new Set<ILookupTreeEntry>();
for (const currentEntry of currentEntries) {
// Skip if we've already processed this entry object
if (processedEntries.has(currentEntry.entry)) {
continue;
}
processedEntries.add(currentEntry.entry);
if (!currentEntry.entry.reverse) {
currentEntry.entry.reverse = {
individual: {},
range: []
};
}
// All glyphs at this position share ONE entry - backtrack just needs to match,
// all paths lead to the same result
const sharedEntry: ILookupTreeEntry = {};
for (const glyph of glyphs) {
if (Array.isArray(glyph)) {
currentEntry.entry.reverse.range.push({
entry: sharedEntry,
range: glyph
});
} else {
currentEntry.entry.reverse.individual[glyph] = sharedEntry;
}
}
nextEntries.push({
entry: sharedEntry,
substitutions: currentEntry.substitutions
});
}
return nextEntries;
}
export function getInputTree(tree: ILookupTree, substitutions: ISubstitutionLookupRecord[], lookups: Lookup[], inputIndex: number, glyphId: number | [number, number]): { entry: ILookupTreeEntry, substitution: number | null }[] {
const result: { entry: ILookupTreeEntry, substitution: number | null }[] = [];
if (!Array.isArray(glyphId)) {
tree.individual[glyphId] = {};
result.push({
entry: tree.individual[glyphId],
substitution: getSubstitutionAtPosition(substitutions, lookups, inputIndex, glyphId)
});
} else {
const subs = getSubstitutionAtPositionRange(substitutions, lookups, inputIndex, glyphId);
for (const [range, substitution] of subs) {
const entry: ILookupTreeEntry = {};
if (Array.isArray(range)) {
tree.range.push({ range, entry });
} else {
tree.individual[range] = {};
}
result.push({ entry, substitution });
}
}
return result;
}
function getSubstitutionAtPositionRange(substitutions: ISubstitutionLookupRecord[], lookups: Lookup[], index: number, range: [number, number]): Map<number | [number, number], number | null> {
for (const substitution of substitutions.filter(s => s.sequenceIndex === index)) {
for (const substitutionTable of (lookups[substitution.lookupListIndex] as Lookup.IType1).subtables) {
const sub = getRangeSubstitutionGlyphs(
substitutionTable,
range
);
if (!Array.from(sub.values()).every(val => val !== null)) {
return sub;
}
}
}
return new Map([[range, null]]);
}
function getSubstitutionAtPosition(substitutions: ISubstitutionLookupRecord[], lookups: Lookup[], index: number, glyphId: number): number | null {
for (const substitution of substitutions.filter(s => s.sequenceIndex === index)) {
for (const substitutionTable of (lookups[substitution.lookupListIndex] as Lookup.IType1).subtables) {
const sub = getIndividualSubstitutionGlyph(
substitutionTable,
glyphId
);
if (sub !== null) {
return sub;
}
}
}
return null;
}
@@ -0,0 +1,62 @@
import { SubstitutionTable } from '../tables';
import getCoverageGlyphIndex from './coverage';
/**
* Get the substitution glyph for the givne glyph, or null if the glyph was not
* found in the table.
*
* @param table JSON representation of the substitution table
* @param glyphId The index of the glpyh to find substitutions for
*/
export function getRangeSubstitutionGlyphs(table: SubstitutionTable, glyphId: [number, number]): Map<[number, number] | number, number | null> {
const replacementStart: number = glyphId[0];
const currentReplacement: number | null = getIndividualSubstitutionGlyph(table, replacementStart);
let search: number = glyphId[0] + 1;
const result = new Map<[number, number] | number, number | null>();
while (search < glyphId[1]) {
const sub = getIndividualSubstitutionGlyph(table, search);
if (sub !== currentReplacement) {
if (search - replacementStart <= 1) {
result.set(replacementStart, currentReplacement);
} else {
result.set([replacementStart, search], currentReplacement);
}
}
search++;
}
if (search - replacementStart <= 1) {
result.set(replacementStart, currentReplacement);
} else {
result.set([replacementStart, search], currentReplacement);
}
return result;
}
export function getIndividualSubstitutionGlyph(table: SubstitutionTable, glyphId: number): number | null {
const coverageIndex = getCoverageGlyphIndex(table.coverage, glyphId);
// istanbul ignore next - invalid font
if (coverageIndex === null) {
return null;
}
switch (table.substFormat) {
// https://docs.microsoft.com/en-us/typography/opentype/spec/gsub#11-single-substitution-format-1
case 1:
// TODO: determine if there's a rhyme or reason to the 16-bit
// wraparound and if it can ever be a different number
return (glyphId + table.deltaGlyphId) % (2 ** 16);
// https://docs.microsoft.com/en-us/typography/opentype/spec/gsub#12-single-substitution-format-2
case 2:
// eslint-disable-next-line eqeqeq
return table.substitute[coverageIndex] != null
? table.substitute[coverageIndex]
: null;
}
}
@@ -0,0 +1,112 @@
export type SubstitutionTable = SubstitutionTable.IFormat1 | SubstitutionTable.IFormat2;
export namespace SubstitutionTable {
export interface IFormat1 {
substFormat: 1;
coverage: CoverageTable;
deltaGlyphId: number;
}
export interface IFormat2 {
substFormat: 2;
coverage: CoverageTable;
substitute: number[];
}
}
export type CoverageTable = CoverageTable.IFormat1 | CoverageTable.IFormat2;
export namespace CoverageTable {
export interface IFormat1 {
format: 1;
glyphs: number[];
}
export interface IFormat2 {
format: 2;
ranges: {
start: number;
end: number;
index: number;
}[];
}
}
export type ChainingContextualSubstitutionTable = ChainingContextualSubstitutionTable.IFormat1 |
ChainingContextualSubstitutionTable.IFormat2 | ChainingContextualSubstitutionTable.IFormat3;
export namespace ChainingContextualSubstitutionTable {
export interface IFormat1 {
substFormat: 1;
coverage: CoverageTable;
chainRuleSets: ChainSubRuleTable[][];
}
export interface IFormat2 {
substFormat: 2;
coverage: CoverageTable;
backtrackClassDef: ClassDefTable;
inputClassDef: ClassDefTable;
lookaheadClassDef: ClassDefTable;
chainClassSet: (null | IChainSubClassRuleTable[])[];
}
export interface IFormat3 {
substFormat: 3;
backtrackCoverage: CoverageTable[];
inputCoverage: CoverageTable[];
lookaheadCoverage: CoverageTable[];
lookupRecords: ISubstitutionLookupRecord[];
}
}
export interface IReverseChainingContextualSingleSubstitutionTable {
substFormat: 1;
coverage: CoverageTable;
backtrackCoverage: CoverageTable[];
lookaheadCoverage: CoverageTable[];
substitutes: number[];
}
export type ClassDefTable = ClassDefTable.IFormat2;
export namespace ClassDefTable {
export interface IFormat2 {
format: 2;
ranges: {
start: number;
end: number;
classId: number;
}[];
}
}
export interface ISubstitutionLookupRecord {
sequenceIndex: number;
lookupListIndex: number;
}
export type ChainSubRuleTable = IChainSubClassRuleTable;
export interface IChainSubClassRuleTable {
backtrack: number[];
input: number[];
lookahead: number[];
lookupRecords: ISubstitutionLookupRecord[];
}
export type Lookup = Lookup.IType1 | Lookup.IType6 | Lookup.IType8;
export namespace Lookup {
export interface IType1 {
lookupType: 1;
lookupFlag: number;
subtables: SubstitutionTable[];
}
export interface IType6 {
lookupType: 6;
lookupFlag: number;
subtables: ChainingContextualSubstitutionTable[];
}
export interface IType8 {
lookupType: 8;
lookupFlag: number;
subtables: IReverseChainingContextualSingleSubstitutionTable[];
}
}
@@ -0,0 +1,86 @@
export interface ISubstitutionResult {
index: number;
contextRange: [number, number];
}
/**
* Information about ligatures found in a sequence of text
*/
export interface ILigatureData {
/**
* The list of font glyphs in the input text.
*/
inputGlyphs: number[];
/**
* The list of font glyphs after performing replacements for font ligatures.
*/
outputGlyphs: number[];
/**
* Sorted array of ranges that must be rendered together to produce the
* ligatures in the output sequence. The ranges are inclusive on the left and
* exclusive on the right.
*/
contextRanges: [number, number][];
}
export interface IFont {
/**
* Scans the provided text for font ligatures, returning an object with
* metadata about the text and any ligatures found.
*
* @param text String to search for ligatures
*/
findLigatures(text: string): ILigatureData;
/**
* Scans the provided text for font ligatures, returning an array of ranges
* where ligatures are located.
*
* @param text String to search for ligatures
*/
findLigatureRanges(text: string): [number, number][];
}
export interface IOptions {
/**
* Optional size of previous results to store, measured in total number of
* characters from input strings. Defaults to no cache (0)
*/
cacheSize?: number;
}
export interface ILookupTree {
individual: {
[glyphId: string]: ILookupTreeEntry;
};
range: {
range: [number, number];
entry: ILookupTreeEntry;
}[];
}
export interface ILookupTreeEntry {
lookup?: ILookupResult;
forward?: ILookupTree;
reverse?: ILookupTree;
}
export interface ILookupResult {
substitutions: (number | null)[];
length: number;
index: number;
subIndex: number;
contextRange: [number, number];
}
export interface IFlattenedLookupTree {
[glyphId: string]: IFlattenedLookupTreeEntry;
}
export interface IFlattenedLookupTreeEntry {
lookup?: ILookupResult;
forward?: IFlattenedLookupTree;
reverse?: IFlattenedLookupTree;
}
@@ -0,0 +1,67 @@
import { IFlattenedLookupTree, ILookupResult } from './types';
export default function walkTree(tree: IFlattenedLookupTree, sequence: number[], startIndex: number, index: number): ILookupResult | undefined {
const glyphId = sequence[index];
const subtree = tree[glyphId];
if (!subtree) {
return undefined;
}
let lookup = subtree.lookup;
if (subtree.reverse) {
const reverseLookup = walkReverse(subtree.reverse, sequence, startIndex);
if (
(!lookup && reverseLookup) ||
(
reverseLookup && lookup && (
lookup.index > reverseLookup.index ||
(lookup.index === reverseLookup.index && lookup.subIndex > reverseLookup.subIndex)
)
)
) {
lookup = reverseLookup;
}
}
if (++index >= sequence.length || !subtree.forward) {
return lookup;
}
const forwardLookup = walkTree(subtree.forward, sequence, startIndex, index);
if (
(!lookup && forwardLookup) ||
(
forwardLookup && lookup && (
lookup.index > forwardLookup.index ||
(lookup.index === forwardLookup.index && lookup.subIndex > forwardLookup.subIndex)
)
)
) {
lookup = forwardLookup;
}
return lookup;
}
function walkReverse(tree: IFlattenedLookupTree, sequence: number[], index: number): ILookupResult | undefined {
let subtree = tree[sequence[--index]];
let lookup: ILookupResult | undefined = subtree && subtree.lookup;
while (subtree) {
if (
(!lookup && subtree.lookup) ||
(subtree.lookup && lookup && lookup.index > subtree.lookup.index)
) {
lookup = subtree.lookup;
}
if (--index < 0 || !subtree.reverse) {
break;
}
subtree = subtree.reverse[sequence[index]];
}
return lookup;
}
+1 -1
View File
@@ -4,7 +4,7 @@
*/
import type { Terminal } from '@xterm/xterm';
import { Font } from 'font-ligatures';
import { Font } from './fontLigatures/index';
import load from './font';
+1 -2
View File
@@ -4,11 +4,10 @@
*/
import { assert } from 'chai';
import parse from './parse';
// TODO: integrate tests from http://test.csswg.org/suites/css-fonts-4_dev/nightly-unstable/
describe('parse', () => {
describe('addon-ligatures - parse', () => {
it('parses individual families', () => {
assert.deepEqual(parse('monospace'), ['monospace']);
});
+3 -1
View File
@@ -9,7 +9,9 @@
"noUnusedLocals": true,
"preserveWatchOutput": true,
"types": [
"../../../node_modules/@types/mocha"
"../../../node_modules/@types/mocha",
// HACK: src shouldn't use node types but it's needed for index.test.ts
"../../../node_modules/@types/node"
],
"paths": {
"@xterm/addon-ligatures" : [
@@ -4,61 +4,62 @@
*/
import * as path from 'path';
import * as sinon from 'sinon';
import { assert } from 'chai';
import * as fontFinder from 'font-finder';
import * as ligatureSupport from '.';
// Use require to get a mutable module object (ESM imports create read-only bindings)
const fontFinder = require('font-finder');
const ligatureSupport = require('../out-esbuild/index');
const originalList = fontFinder.list;
describe('LigaturesAddon', () => {
let onRefresh: sinon.SinonStub;
let onRefresh: { called: boolean, callCount: number, (...args: any[]): void };
let term: MockTerminal;
// -> forms a ligature in Fira Code and Iosevka, but www only forms a ligature
// in Fira Code
const input = 'a -> b www c';
before(() => {
sinon.stub(fontFinder, 'list').returns(Promise.resolve({
// eslint-disable-next-line @typescript-eslint/naming-convention
fontFinder.list = () => Promise.resolve({
'Fira Code': [{
path: path.join(__dirname, '../fonts/firaCode.otf'),
style: fontFinder.Style.Regular,
type: fontFinder.Type.Monospace,
weight: 400
}],
// eslint-disable-next-line @typescript-eslint/naming-convention
'Iosevka': [{
path: path.join(__dirname, '../fonts/iosevka.ttf'),
style: fontFinder.Style.Regular,
type: fontFinder.Type.Monospace,
weight: 400
}],
// eslint-disable-next-line @typescript-eslint/naming-convention
'Nonexistant Font': [{
path: path.join(__dirname, '../fonts/nonexistant.ttf'),
style: fontFinder.Style.Regular,
type: fontFinder.Type.Monospace,
weight: 400
}]
} as fontFinder.FontList));
});
});
after(() => {
fontFinder.list = originalList;
});
beforeEach(() => {
onRefresh = sinon.stub();
onRefresh = Object.assign((..._args: any[]) => { onRefresh.called = true; onRefresh.callCount++; }, { called: false, callCount: 0 });
term = new MockTerminal(onRefresh);
ligatureSupport.enableLigatures(term as any);
});
it('registers itself correctly', () => {
const term = new MockTerminal(sinon.spy());
const term = new MockTerminal(() => {});
assert.isUndefined(term.joiner);
ligatureSupport.enableLigatures(term as any);
assert.isFunction(term.joiner);
});
it('registers itself correctly when called directly', () => {
const term = new MockTerminal(sinon.spy());
const term = new MockTerminal(() => {});
assert.isUndefined(term.joiner);
ligatureSupport.enableLigatures(term as any);
assert.isFunction(term.joiner);
@@ -72,14 +73,14 @@ describe('LigaturesAddon', () => {
term.options.fontFamily = 'Nonexistant Font, monospace';
assert.deepEqual(term.joiner!(input), []);
await delay(500);
assert.isTrue(onRefresh.notCalled);
assert.strictEqual(onRefresh.callCount, 0);
});
it('returns nothing if the font is not present on the system', async () => {
term.options.fontFamily = 'notinstalled';
assert.deepEqual(term.joiner!(input), []);
await delay(500);
assert.isTrue(onRefresh.notCalled);
assert.strictEqual(onRefresh.callCount, 0);
assert.deepEqual(term.joiner!(input), []);
});
@@ -87,7 +88,7 @@ describe('LigaturesAddon', () => {
term.options.fontFamily = 'monospace';
assert.deepEqual(term.joiner!(input), []);
await delay(500);
assert.isTrue(onRefresh.notCalled);
assert.strictEqual(onRefresh.callCount, 0);
assert.deepEqual(term.joiner!(input), []);
});
@@ -95,7 +96,7 @@ describe('LigaturesAddon', () => {
term.options.fontFamily = '';
assert.deepEqual(term.joiner!(input), []);
await delay(500);
assert.isTrue(onRefresh.notCalled);
assert.strictEqual(onRefresh.callCount, 0);
assert.deepEqual(term.joiner!(input), []);
});
@@ -103,7 +104,7 @@ describe('LigaturesAddon', () => {
term.options.fontFamily = {} as any;
assert.deepEqual(term.joiner!(input), []);
await delay(500);
assert.isTrue(onRefresh.notCalled);
assert.strictEqual(onRefresh.callCount, 0);
});
});
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "ESNext",
"lib": [
"es2021"
],
"rootDir": ".",
"outDir": "../out-esbuild-test",
"sourceMap": true,
"removeComments": true,
"baseUrl": ".",
"strict": true,
"types": [
"../../../node_modules/@types/mocha",
"../../../node_modules/@types/node"
]
},
"include": [
"./**/*",
"../../../typings/xterm.d.ts"
]
}
+2 -1
View File
@@ -2,6 +2,7 @@
"files": [],
"include": [],
"references": [
{ "path": "./src" }
{ "path": "./src" },
{ "path": "./test" }
]
}
-383
View File
@@ -1,383 +0,0 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
"@sinonjs/commons@^1", "@sinonjs/commons@^1.0.2", "@sinonjs/commons@^1.3.0", "@sinonjs/commons@^1.7.0":
version "1.8.0"
resolved "https://registry.npmjs.org/@sinonjs/commons/-/commons-1.8.0.tgz"
integrity sha512-wEj54PfsZ5jGSwMX68G8ZXFawcSglQSXqCftWX3ec8MDUzQdHgcKvw97awHbY0efQEL5iKUOAmmVtoYgmrSG4Q==
dependencies:
type-detect "4.0.8"
"@sinonjs/formatio@^3.0.0", "@sinonjs/formatio@^3.2.1":
version "3.2.2"
resolved "https://registry.npmjs.org/@sinonjs/formatio/-/formatio-3.2.2.tgz"
integrity sha512-B8SEsgd8gArBLMD6zpRw3juQ2FVSsmdd7qlevyDqzS9WTCtvF55/gAL+h6gue8ZvPYcdiPdvueM/qm//9XzyTQ==
dependencies:
"@sinonjs/commons" "^1"
"@sinonjs/samsam" "^3.1.0"
"@sinonjs/samsam@^2.1.2":
version "2.1.3"
resolved "https://registry.npmjs.org/@sinonjs/samsam/-/samsam-2.1.3.tgz"
integrity sha512-8zNeBkSKhU9a5cRNbpCKau2WWPfan+Q2zDlcXvXyhn9EsMqgYs4qzo0XHNVlXC6ABQL8fT6nV+zzo5RTHJzyXw==
"@sinonjs/samsam@^3.1.0":
version "3.3.3"
resolved "https://registry.npmjs.org/@sinonjs/samsam/-/samsam-3.3.3.tgz"
integrity sha512-bKCMKZvWIjYD0BLGnNrxVuw4dkWCYsLqFOUWw8VgKF/+5Y+mE7LfHWPIYoDXowH+3a9LsWDMo0uAP8YDosPvHQ==
dependencies:
"@sinonjs/commons" "^1.3.0"
array-from "^2.1.1"
lodash "^4.17.15"
"@sinonjs/text-encoding@^0.7.1":
version "0.7.1"
resolved "https://registry.npmjs.org/@sinonjs/text-encoding/-/text-encoding-0.7.1.tgz"
integrity sha512-+iTbntw2IZPb/anVDbypzfQa+ay64MW0Zo8aJ8gZPWMMK6/OubMVb6lUPMagqjOPnmtauXnFCACVl3O7ogjeqQ==
"@types/sinon@^5.0.1":
version "5.0.1"
resolved "https://registry.npmjs.org/@types/sinon/-/sinon-5.0.1.tgz"
integrity sha512-yxzBCIjE3lp9lYjfBbIK/LRCoXgCLLbIIBIje7eNCcUIIR2CZZtyX5uto2hVoMSMqLrsRrT6mwwUEd0yFgOwpA==
array-from@^2.1.1:
version "2.1.1"
resolved "https://registry.npmjs.org/array-from/-/array-from-2.1.1.tgz"
integrity sha1-z+nYwmYoudxa7MYqn12PHzUsEZU= sha512-GQTc6Uupx1FCavi5mPzBvVT7nEOeWMmUA9P95wpfpW1XwMSKs+KaymD5C2Up7KAUKg/mYwbsUYzdZWcoajlNZg==
asynckit@^0.4.0:
version "0.4.0"
resolved "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz"
integrity sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==
axios@^1.6.0:
version "1.8.2"
resolved "https://registry.npmjs.org/axios/-/axios-1.8.2.tgz"
integrity sha512-ls4GYBm5aig9vWx8AWDSGLpnpDQRtWAfrjU+EuytuODrFBkqesN2RkOQCBzrA1RQNHw1SmRMSDDDSwzNAYQ6Rg==
dependencies:
follow-redirects "^1.15.6"
form-data "^4.0.0"
proxy-from-env "^1.1.0"
buffer-crc32@~0.2.3:
version "0.2.13"
resolved "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz"
integrity sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==
call-bind-apply-helpers@^1.0.1, call-bind-apply-helpers@^1.0.2:
version "1.0.2"
resolved "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz"
integrity sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==
dependencies:
es-errors "^1.3.0"
function-bind "^1.1.2"
combined-stream@^1.0.8:
version "1.0.8"
resolved "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz"
integrity sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==
dependencies:
delayed-stream "~1.0.0"
delayed-stream@~1.0.0:
version "1.0.0"
resolved "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz"
integrity sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==
diff@^3.5.0:
version "3.5.0"
resolved "https://registry.npmjs.org/diff/-/diff-3.5.0.tgz"
integrity sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==
dunder-proto@^1.0.1:
version "1.0.1"
resolved "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz"
integrity sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==
dependencies:
call-bind-apply-helpers "^1.0.1"
es-errors "^1.3.0"
gopd "^1.2.0"
es-define-property@^1.0.1:
version "1.0.1"
resolved "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz"
integrity sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==
es-errors@^1.3.0:
version "1.3.0"
resolved "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz"
integrity sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==
es-object-atoms@^1.0.0, es-object-atoms@^1.1.1:
version "1.1.1"
resolved "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz"
integrity sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==
dependencies:
es-errors "^1.3.0"
es-set-tostringtag@^2.1.0:
version "2.1.0"
resolved "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz"
integrity sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==
dependencies:
es-errors "^1.3.0"
get-intrinsic "^1.2.6"
has-tostringtag "^1.0.2"
hasown "^2.0.2"
fd-slicer@~1.1.0:
version "1.1.0"
resolved "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz"
integrity sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==
dependencies:
pend "~1.2.0"
follow-redirects@^1.15.6:
version "1.15.9"
resolved "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz"
integrity sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==
font-finder@^1.0.3, font-finder@^1.1.0:
version "1.1.0"
resolved "https://registry.npmjs.org/font-finder/-/font-finder-1.1.0.tgz"
integrity sha512-wpCL2uIbi6GurJbU7ZlQ3nGd61Ho+dSU6U83/xJT5UPFfN35EeCW/rOtS+5k+IuEZu2SYmHzDIPL9eA5tSYRAw==
dependencies:
get-system-fonts "^2.0.0"
promise-stream-reader "^1.0.1"
font-ligatures@^1.4.1:
version "1.4.1"
resolved "https://registry.npmjs.org/font-ligatures/-/font-ligatures-1.4.1.tgz"
integrity sha512-7W6zlfyhvCqShZ5ReUWqmSd9vBaUudW0Hxis+tqUjtHhsPU+L3Grf8mcZAtCiXHTzorhwdRTId2WeH/88gdFkw==
dependencies:
font-finder "^1.0.3"
lru-cache "^6.0.0"
opentype.js "^0.8.0"
form-data@^4.0.0:
version "4.0.4"
resolved "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz"
integrity sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==
dependencies:
asynckit "^0.4.0"
combined-stream "^1.0.8"
es-set-tostringtag "^2.1.0"
hasown "^2.0.2"
mime-types "^2.1.12"
function-bind@^1.1.2:
version "1.1.2"
resolved "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz"
integrity sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==
get-intrinsic@^1.2.6:
version "1.3.0"
resolved "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz"
integrity sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==
dependencies:
call-bind-apply-helpers "^1.0.2"
es-define-property "^1.0.1"
es-errors "^1.3.0"
es-object-atoms "^1.1.1"
function-bind "^1.1.2"
get-proto "^1.0.1"
gopd "^1.2.0"
has-symbols "^1.1.0"
hasown "^2.0.2"
math-intrinsics "^1.1.0"
get-proto@^1.0.1:
version "1.0.1"
resolved "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz"
integrity sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==
dependencies:
dunder-proto "^1.0.1"
es-object-atoms "^1.0.0"
get-system-fonts@^2.0.0:
version "2.0.0"
resolved "https://registry.npmjs.org/get-system-fonts/-/get-system-fonts-2.0.0.tgz"
integrity sha512-iiM/DavyF2nnLdELzPBSHojzQJVai9WiwrRzn5gp2dutJuerC8qHyBoh4lxfVdKGbnb9eZ4p8Oefbuc3yExB7Q==
gopd@^1.2.0:
version "1.2.0"
resolved "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz"
integrity sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==
has-flag@^3.0.0:
version "3.0.0"
resolved "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz"
integrity sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==
has-symbols@^1.0.3, has-symbols@^1.1.0:
version "1.1.0"
resolved "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz"
integrity sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==
has-tostringtag@^1.0.2:
version "1.0.2"
resolved "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz"
integrity sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==
dependencies:
has-symbols "^1.0.3"
hasown@^2.0.2:
version "2.0.2"
resolved "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz"
integrity sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==
dependencies:
function-bind "^1.1.2"
isarray@0.0.1:
version "0.0.1"
resolved "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz"
integrity sha512-D2S+3GLxWH+uhrNEcoh/fnmYeP8E8/zHl644d/jdA0g2uyXvy3sb0qxotE+ne0LtccHknQzWwZEzhak7oJ0COQ==
just-extend@^4.0.2:
version "4.1.0"
resolved "https://registry.npmjs.org/just-extend/-/just-extend-4.1.0.tgz"
integrity sha512-ApcjaOdVTJ7y4r08xI5wIqpvwS48Q0PBG4DJROcEkH1f8MdAiNFyFxz3xoL0LWAVwjrwPYZdVHHxhRHcx/uGLA==
lodash.get@^4.4.2:
version "4.4.2"
resolved "https://registry.npmjs.org/lodash.get/-/lodash.get-4.4.2.tgz"
integrity sha512-z+Uw/vLuy6gQe8cfaFWD7p0wVv8fJl3mbzXh33RS+0oW2wvUqiRXiQ69gLWSLpgB5/6sU+r6BlQR0MBILadqTQ==
lodash@^4.17.15:
version "4.17.21"
resolved "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz"
integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==
lolex@^2.7.5:
version "2.7.5"
resolved "https://registry.npmjs.org/lolex/-/lolex-2.7.5.tgz"
integrity sha512-l9x0+1offnKKIzYVjyXU2SiwhXDLekRzKyhnbyldPHvC7BvLPVpdNUNR2KeMAiCN2D/kLNttZgQD5WjSxuBx3Q==
lolex@^5.0.1:
version "5.1.2"
resolved "https://registry.npmjs.org/lolex/-/lolex-5.1.2.tgz"
integrity sha512-h4hmjAvHTmd+25JSwrtTIuwbKdwg5NzZVRMLn9saij4SZaepCrTCxPr35H/3bjwfMJtN+t3CX8672UIkglz28A==
dependencies:
"@sinonjs/commons" "^1.7.0"
lru-cache@^6.0.0:
version "6.0.0"
resolved "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz"
integrity sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==
dependencies:
yallist "^4.0.0"
math-intrinsics@^1.1.0:
version "1.1.0"
resolved "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz"
integrity sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==
mime-db@1.52.0:
version "1.52.0"
resolved "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz"
integrity sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==
mime-types@^2.1.12:
version "2.1.35"
resolved "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz"
integrity sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==
dependencies:
mime-db "1.52.0"
minimist@^1.2.5:
version "1.2.6"
resolved "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz"
integrity sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==
mkdirp@0.5.5:
version "0.5.5"
resolved "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz"
integrity sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==
dependencies:
minimist "^1.2.5"
nise@^1.4.5:
version "1.5.3"
resolved "https://registry.npmjs.org/nise/-/nise-1.5.3.tgz"
integrity sha512-Ymbac/94xeIrMf59REBPOv0thr+CJVFMhrlAkW/gjCIE58BGQdCj0x7KRCb3yz+Ga2Rz3E9XXSvUyyxqqhjQAQ==
dependencies:
"@sinonjs/formatio" "^3.2.1"
"@sinonjs/text-encoding" "^0.7.1"
just-extend "^4.0.2"
lolex "^5.0.1"
path-to-regexp "^1.7.0"
opentype.js@^0.8.0:
version "0.8.0"
resolved "https://registry.npmjs.org/opentype.js/-/opentype.js-0.8.0.tgz"
integrity sha512-FQHR4oGP+a0m/f6yHoRpBOIbn/5ZWxKd4D/djHVJu8+KpBTYrJda0b7mLcgDEMWXE9xBCJm+qb0yv6FcvPjukg==
dependencies:
tiny-inflate "^1.0.2"
path-to-regexp@^1.7.0:
version "1.9.0"
resolved "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-1.9.0.tgz"
integrity sha512-xIp7/apCFJuUHdDLWe8O1HIkb0kQrOMb/0u6FXQjemHn/ii5LrIzU6bdECnsiTF/GjZkMEKg1xdiZwNqDYlZ6g==
dependencies:
isarray "0.0.1"
pend@~1.2.0:
version "1.2.0"
resolved "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz"
integrity sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==
promise-stream-reader@^1.0.1:
version "1.0.1"
resolved "https://registry.npmjs.org/promise-stream-reader/-/promise-stream-reader-1.0.1.tgz"
integrity sha512-Tnxit5trUjBAqqZCGWwjyxhmgMN4hGrtpW3Oc/tRI4bpm/O2+ej72BB08l6JBnGQgVDGCLvHFGjGgQS6vzhwXg==
proxy-from-env@^1.1.0:
version "1.1.0"
resolved "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz"
integrity sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==
sinon@6.3.5:
version "6.3.5"
resolved "https://registry.npmjs.org/sinon/-/sinon-6.3.5.tgz"
integrity sha512-xgoZ2gKjyVRcF08RrIQc+srnSyY1JDJtxu3Nsz07j1ffjgXoY6uPLf/qja6nDBZgzYYEovVkFryw2+KiZz11xQ==
dependencies:
"@sinonjs/commons" "^1.0.2"
"@sinonjs/formatio" "^3.0.0"
"@sinonjs/samsam" "^2.1.2"
diff "^3.5.0"
lodash.get "^4.4.2"
lolex "^2.7.5"
nise "^1.4.5"
supports-color "^5.5.0"
type-detect "^4.0.8"
supports-color@^5.5.0:
version "5.5.0"
resolved "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz"
integrity sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==
dependencies:
has-flag "^3.0.0"
tiny-inflate@^1.0.2:
version "1.0.2"
resolved "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.2.tgz"
integrity sha512-fEndoHfuiSlXtvG0EA1gB4uAdy2dbQ3WfOtQw1/Y8NQ9rxtGbGkENwfGmN0wK7OkxDz1lgc5Ei2LQ0oxKDUcVw==
type-detect@^4.0.8, type-detect@4.0.8:
version "4.0.8"
resolved "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz"
integrity sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==
yallist@^4.0.0:
version "4.0.0"
resolved "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz"
integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==
yauzl@^2.10.0:
version "2.10.0"
resolved "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz"
integrity sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==
dependencies:
buffer-crc32 "~0.2.3"
fd-slicer "~1.1.0"
@@ -135,6 +135,7 @@ export class DecorationManager extends Disposable {
marker,
x: range[1],
width: range[2],
layer: isActiveResult ? 'top' : 'bottom',
backgroundColor: isActiveResult ? options.activeMatchBackground : options.matchBackground,
overviewRulerOptions: this._highlightedLines.has(marker.line) ? undefined : {
color: isActiveResult ? options.activeMatchColorOverviewRuler : options.matchOverviewRuler,
+14 -1
View File
@@ -5,7 +5,7 @@
import type { Terminal, IDisposable, ITerminalAddon } from '@xterm/xterm';
import type { SearchAddon as ISearchApi, ISearchOptions, ISearchAddonOptions, ISearchResultChangeEvent } from '@xterm/addon-search';
import { Event } from 'vs/base/common/event';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { disposableTimeout } from 'vs/base/common/async';
import { SearchLineCache } from './SearchLineCache';
@@ -42,6 +42,11 @@ export class SearchAddon extends Disposable implements ITerminalAddon, ISearchAp
private _decorationManager: DecorationManager | undefined;
private _resultTracker = this._register(new SearchResultTracker());
private readonly _onAfterSearch = this._register(new Emitter<void>());
public readonly onAfterSearch = this._onAfterSearch.event;
private readonly _onBeforeSearch = this._register(new Emitter<void>());
public readonly onBeforeSearch = this._onBeforeSearch.event;
public get onDidChangeResults(): Event<ISearchResultChangeEvent> {
return this._resultTracker.onDidChangeResults;
}
@@ -98,6 +103,8 @@ export class SearchAddon extends Disposable implements ITerminalAddon, ISearchAp
throw new Error('Cannot use addon until it has been loaded');
}
this._onBeforeSearch.fire();
this._state.lastSearchOptions = searchOptions;
if (this._state.shouldUpdateHighlighting(term, searchOptions)) {
@@ -108,6 +115,8 @@ export class SearchAddon extends Disposable implements ITerminalAddon, ISearchAp
this._fireResults(searchOptions);
this._state.cachedSearchTerm = term;
this._onAfterSearch.fire();
return found;
}
@@ -173,6 +182,8 @@ export class SearchAddon extends Disposable implements ITerminalAddon, ISearchAp
throw new Error('Cannot use addon until it has been loaded');
}
this._onBeforeSearch.fire();
this._state.lastSearchOptions = searchOptions;
if (this._state.shouldUpdateHighlighting(term, searchOptions)) {
@@ -183,6 +194,8 @@ export class SearchAddon extends Disposable implements ITerminalAddon, ISearchAp
this._fireResults(searchOptions);
this._state.cachedSearchTerm = term;
this._onAfterSearch.fire();
return found;
}
+23 -1
View File
@@ -38,6 +38,9 @@ export class SearchLineCache extends Disposable {
private _linesCache: LineCacheEntry[] | undefined;
private _linesCacheTimeout = this._register(new MutableDisposable());
private _linesCacheDisposables = this._register(new MutableDisposable());
// Track access to avoid recreating a timeout on every init call which occurs once per search
// result (findNext/findPrevious -> _highlightAllMatches -> find loop).
private _lastAccessTimestamp = 0;
constructor(private readonly _terminal: Terminal) {
super();
@@ -57,15 +60,34 @@ export class SearchLineCache extends Disposable {
);
}
this._linesCacheTimeout.value = disposableTimeout(() => this._destroyLinesCache(), Constants.LINES_CACHE_TIME_TO_LIVE);
this._lastAccessTimestamp = Date.now();
if (!this._linesCacheTimeout.value) {
this._scheduleLinesCacheTimeout(Constants.LINES_CACHE_TIME_TO_LIVE);
}
}
private _destroyLinesCache(): void {
this._linesCache = undefined;
this._lastAccessTimestamp = 0;
this._linesCacheDisposables.clear();
this._linesCacheTimeout.clear();
}
private _scheduleLinesCacheTimeout(delay: number): void {
this._linesCacheTimeout.value = disposableTimeout(() => {
if (!this._linesCache) {
return;
}
const now = Date.now();
const elapsed = now - this._lastAccessTimestamp;
if (elapsed >= Constants.LINES_CACHE_TIME_TO_LIVE) {
this._destroyLinesCache();
return;
}
this._scheduleLinesCacheTimeout(Constants.LINES_CACHE_TIME_TO_LIVE - elapsed);
}, delay);
}
public getLineFromCache(row: number): LineCacheEntry | undefined {
return this._linesCache?.[row];
}
@@ -385,6 +385,34 @@ test.describe('Search Tests', () => {
});
});
test.describe('onBeforeSearch and onAfterSearch', () => {
test.beforeEach(async () => {
await ctx.page.evaluate(`
window.events = [];
window.search.onBeforeSearch(() => window.events.push('before'));
window.search.onAfterSearch(() => window.events.push('after'));
`);
});
test('should fire before and after findNext', async () => {
await ctx.proxy.write('abc');
await ctx.page.evaluate(`window.search.findNext('a')`);
deepStrictEqual(await ctx.page.evaluate('window.events'), ['before', 'after']);
});
test('should fire before and after findPrevious', async () => {
await ctx.proxy.write('abc');
await ctx.page.evaluate(`window.search.findPrevious('a')`);
deepStrictEqual(await ctx.page.evaluate('window.events'), ['before', 'after']);
});
test('should fire for each search call', async () => {
await ctx.proxy.write('abc abc');
await ctx.page.evaluate(`window.search.findNext('abc')`);
await ctx.page.evaluate(`window.search.findNext('abc')`);
deepStrictEqual(await ctx.page.evaluate('window.events'), ['before', 'after', 'before', 'after']);
});
});
test.describe('Regression tests', () => {
test.describe('#2444 wrapped line content not being found', () => {
let fixture: string;
+11 -2
View File
@@ -152,8 +152,17 @@ declare module '@xterm/addon-search' {
public clearActiveDecoration(): void;
/**
* When decorations are enabled, fires when
* the search results change.
* Fires after a search is performed.
*/
readonly onAfterSearch: IEvent<void>;
/**
* Fires before a search is performed.
*/
readonly onBeforeSearch: IEvent<void>;
/**
* When decorations are enabled, fires when the search results change.
*/
readonly onDidChangeResults: IEvent<ISearchResultChangeEvent>;
}
@@ -112,6 +112,116 @@ describe('SerializeAddon', () => {
}), 'world');
});
});
describe('underline styles', () => {
it('should serialize single underline with style', async () => {
await writeP(terminal, sgr('4:1') + 'test' + sgr('24'));
assert.equal(serializeAddon.serialize(), '\u001b[4:1mtest\u001b[0m');
});
it('should serialize double underline', async () => {
await writeP(terminal, sgr('4:2') + 'test' + sgr('24'));
assert.equal(serializeAddon.serialize(), '\u001b[4:2mtest\u001b[0m');
});
it('should serialize curly underline', async () => {
await writeP(terminal, sgr('4:3') + 'test' + sgr('24'));
assert.equal(serializeAddon.serialize(), '\u001b[4:3mtest\u001b[0m');
});
it('should serialize dotted underline', async () => {
await writeP(terminal, sgr('4:4') + 'test' + sgr('24'));
assert.equal(serializeAddon.serialize(), '\u001b[4:4mtest\u001b[0m');
});
it('should serialize dashed underline', async () => {
await writeP(terminal, sgr('4:5') + 'test' + sgr('24'));
assert.equal(serializeAddon.serialize(), '\u001b[4:5mtest\u001b[0m');
});
it('should serialize underline with RGB color', async () => {
await writeP(terminal, sgr('4', '58;2;255;128;64') + 'test' + sgr('24'));
const result = serializeAddon.serialize();
assert.ok(result.includes('4:1'), result);
assert.ok(result.includes('58:2::255:128:64'), result);
});
it('should serialize underline with palette color', async () => {
await writeP(terminal, sgr('4', '58;5;46') + 'test' + sgr('24'));
const result = serializeAddon.serialize();
assert.ok(result.includes('4:1'), result);
assert.ok(result.includes('58:5:46'), result);
});
});
describe('scroll region', () => {
let scrollTerminal: Terminal;
let scrollAddon: SerializeAddon;
beforeEach(() => {
scrollTerminal = new Terminal({ cols: 10, rows: 5, allowProposedApi: true });
scrollAddon = new SerializeAddon();
scrollTerminal.loadAddon(scrollAddon);
});
it('should serialize scroll region when margins are set', async () => {
await writeP(scrollTerminal, '\x1b[2;4r');
const buffer = (scrollTerminal as any)._core.buffer;
assert.equal(buffer.scrollTop, 1, 'scrollTop should be 1');
assert.equal(buffer.scrollBottom, 3, 'scrollBottom should be 3');
const result = scrollAddon.serialize();
assert.ok(result.includes('\x1b[2;4r'), result);
});
it('should not serialize scroll region when excludeModes is true', async () => {
await writeP(scrollTerminal, '\x1b[2;4r');
const result = scrollAddon.serialize({ excludeModes: true });
assert.ok(!result.includes('\x1b[2;4r'), result);
});
it('should restore scroll region correctly when deserialized', async () => {
await writeP(scrollTerminal, '\x1b[2;4r');
const serialized = scrollAddon.serialize();
const terminal2 = new Terminal({ cols: 10, rows: 5, allowProposedApi: true });
terminal2.loadAddon(new SerializeAddon());
await writeP(terminal2, serialized);
const buffer = (terminal2 as any)._core.buffer;
assert.equal(buffer.scrollTop, 1);
assert.equal(buffer.scrollBottom, 3);
});
});
describe('cursor visibility', () => {
it('should serialize hidden cursor', async () => {
await writeP(terminal, 'hello\x1b[?25l');
assert.equal(terminal.modes.showCursor, false);
const result = serializeAddon.serialize();
assert.ok(result.includes('\x1b[?25l'), result);
});
it('should not serialize visible cursor (default state)', async () => {
await writeP(terminal, 'hello');
assert.equal(terminal.modes.showCursor, true);
const result = serializeAddon.serialize();
assert.ok(!result.includes('\x1b[?25l'), result);
assert.ok(!result.includes('\x1b[?25h'), result);
});
it('should not serialize cursor visibility when excludeModes is true', async () => {
await writeP(terminal, 'hello\x1b[?25l');
const result = serializeAddon.serialize({ excludeModes: true });
assert.ok(!result.includes('\x1b[?25l'), result);
});
it('should restore hidden cursor correctly when deserialized', async () => {
await writeP(terminal, 'hello\x1b[?25l');
const serialized = serializeAddon.serialize();
const terminal2 = new Terminal({ cols: 10, rows: 2, allowProposedApi: true });
terminal2.loadAddon(new SerializeAddon());
await writeP(terminal2, serialized);
assert.equal(terminal2.modes.showCursor, false);
});
});
});
describe('html', () => {
@@ -192,6 +302,50 @@ describe('SerializeAddon', () => {
assert.equal((output.match(/<span style='text-decoration: underline;'>terminal<\/span>/g) || []).length, 1, output);
});
it('cells with double underline styling', async () => {
await writeP(terminal, ' ' + sgr('4:2') + 'terminal' + sgr('24') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.equal((output.match(/<span style='text-decoration: underline double;'>terminal<\/span>/g) || []).length, 1, output);
});
it('cells with curly underline styling', async () => {
await writeP(terminal, ' ' + sgr('4:3') + 'terminal' + sgr('24') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.equal((output.match(/<span style='text-decoration: underline wavy;'>terminal<\/span>/g) || []).length, 1, output);
});
it('cells with dotted underline styling', async () => {
await writeP(terminal, ' ' + sgr('4:4') + 'terminal' + sgr('24') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.equal((output.match(/<span style='text-decoration: underline dotted;'>terminal<\/span>/g) || []).length, 1, output);
});
it('cells with dashed underline styling', async () => {
await writeP(terminal, ' ' + sgr('4:5') + 'terminal' + sgr('24') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.equal((output.match(/<span style='text-decoration: underline dashed;'>terminal<\/span>/g) || []).length, 1, output);
});
it('cells with underline color (palette)', async () => {
await writeP(terminal, ' ' + sgr('4', '58;5;46') + 'terminal' + sgr('24') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.ok(output.includes('text-decoration: underline;'), output);
assert.ok(output.includes('text-decoration-color: #00ff00;'), output);
});
it('cells with underline color (RGB)', async () => {
await writeP(terminal, ' ' + sgr('4', '58;2;255;128;64') + 'terminal' + sgr('24') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.ok(output.includes('text-decoration: underline;'), output);
assert.ok(output.includes('text-decoration-color: #ff8040;'), output);
});
it('cells with invisible styling', async () => {
await writeP(terminal, ' ' + sgr('8') + 'terminal' + sgr('28') + ' ');
+126 -7
View File
@@ -9,6 +9,7 @@ import type { IBuffer, IBufferCell, IBufferRange, ITerminalAddon, Terminal } fro
import type { IHTMLSerializeOptions, SerializeAddon as ISerializeApi, ISerializeOptions, ISerializeRange } from '@xterm/addon-serialize';
import { IAttributeData, IColor } from 'common/Types';
import { DEFAULT_ANSI_COLORS } from 'browser/Types';
import { UnderlineStyle } from 'common/buffer/Constants';
function constrain(value: number, low: number, high: number): number {
return Math.max(low, Math.min(value, high));
@@ -82,10 +83,24 @@ function equalBg(cell1: IBufferCell | IAttributeData, cell2: IBufferCell): boole
&& cell1.getBgColor() === cell2.getBgColor();
}
function equalUnderline(cell1: IBufferCell | IAttributeData, cell2: IBufferCell): boolean {
// If neither cell has underline, consider them equal regardless of internal underline color
// values
if (!cell1.isUnderline() && !cell2.isUnderline()) {
return true;
}
const cell1Data = cell1 as unknown as IAttributeData;
const cell2Data = cell2 as unknown as IAttributeData;
return cell1Data.getUnderlineStyle() === cell2Data.getUnderlineStyle()
&& cell1Data.getUnderlineColor() === cell2Data.getUnderlineColor()
&& cell1Data.getUnderlineColorMode() === cell2Data.getUnderlineColorMode();
}
function equalFlags(cell1: IBufferCell | IAttributeData, cell2: IBufferCell): boolean {
return cell1.isInverse() === cell2.isInverse()
&& cell1.isBold() === cell2.isBold()
&& cell1.isUnderline() === cell2.isUnderline()
&& equalUnderline(cell1, cell2)
&& cell1.isOverline() === cell2.isOverline()
&& cell1.isBlink() === cell2.isBlink()
&& cell1.isInvisible() === cell2.isInvisible()
@@ -274,7 +289,27 @@ class StringSerializeHandler extends BaseSerializeHandler {
if (flagsChanged) {
if (cell.isInverse() !== oldCell.isInverse()) { sgrSeq.push(cell.isInverse() ? 7 : 27); }
if (cell.isBold() !== oldCell.isBold()) { sgrSeq.push(cell.isBold() ? 1 : 22); }
if (cell.isUnderline() !== oldCell.isUnderline()) { sgrSeq.push(cell.isUnderline() ? 4 : 24); }
if (!equalUnderline(cell, oldCell)) {
const cellData = cell as unknown as IAttributeData;
const style = cellData.getUnderlineStyle();
if (style === UnderlineStyle.NONE) {
sgrSeq.push(24);
} else {
// Use SGR 4:X format for underline styles
sgrSeq.push('4:' + style as unknown as number);
// Handle underline color
if (!cellData.isUnderlineColorDefault()) {
const color = cellData.getUnderlineColor();
if (cellData.isUnderlineColorRGB()) {
sgrSeq.push('58:2::' + ((color >>> 16) & 0xFF) + ':' + ((color >>> 8) & 0xFF) + ':' + (color & 0xFF) as unknown as number);
} else {
sgrSeq.push('58:5:' + color as unknown as number);
}
}
}
} else if (cell.isUnderline() !== oldCell.isUnderline()) {
sgrSeq.push(cell.isUnderline() ? 4 : 24);
}
if (cell.isOverline() !== oldCell.isOverline()) { sgrSeq.push(cell.isOverline() ? 53 : 55); }
if (cell.isBlink() !== oldCell.isBlink()) { sgrSeq.push(cell.isBlink() ? 5 : 25); }
if (cell.isInvisible() !== oldCell.isInvisible()) { sgrSeq.push(cell.isInvisible() ? 8 : 28); }
@@ -478,6 +513,25 @@ export class SerializeAddon implements ITerminalAddon , ISerializeApi {
return '';
}
/**
* Serializes the scroll region (DECSTBM) if it's not set to the full terminal size.
* Uses internal API access since scroll region is not exposed in the public API.
*/
private _serializeScrollRegion(terminal: Terminal): string {
// HACK: Internal API access since scroll region is not exposed in the public API
const buffer = (terminal as any)._core.buffer;
const scrollTop: number = buffer.scrollTop;
const scrollBottom: number = buffer.scrollBottom;
// Only serialize if scroll region is not the default (full terminal size)
if (scrollTop !== 0 || scrollBottom !== terminal.rows - 1) {
// DECSTBM uses 1-based indices: CSI Ps ; Ps r
return `\x1b[${scrollTop + 1};${scrollBottom + 1}r`;
}
return '';
}
private _serializeModes(terminal: Terminal): string {
let content = '';
const modes = terminal.modes;
@@ -505,6 +559,12 @@ export class SerializeAddon implements ITerminalAddon , ISerializeApi {
}
}
// Cursor visibility (DECTCEM)
// Default: visible
if (!modes.showCursor) {
content += '\x1b[?25l';
}
return content;
}
@@ -527,9 +587,10 @@ export class SerializeAddon implements ITerminalAddon , ISerializeApi {
}
}
// Modes
// Modes and scroll region
if (!options?.excludeModes) {
content += this._serializeModes(this._terminal);
content += this._serializeScrollRegion(this._terminal);
}
return content;
@@ -627,6 +688,42 @@ export class HTMLSerializeHandler extends BaseSerializeHandler {
return undefined;
}
private _getUnderlineColor(cell: IBufferCell): string | undefined {
const cellData = cell as unknown as IAttributeData;
if (cellData.isUnderlineColorDefault()) {
return undefined;
}
const color = cellData.getUnderlineColor();
if (cellData.isUnderlineColorRGB()) {
const rgb = [
(color >> 16) & 255,
(color >> 8) & 255,
(color ) & 255
];
return '#' + rgb.map(x => this._padStart(x.toString(16), 2, '0')).join('');
}
// Palette color
return this._ansiColors[color].css;
}
private _getUnderlineStyle(cell: IBufferCell): string {
const cellData = cell as unknown as IAttributeData;
switch (cellData.getUnderlineStyle()) {
case UnderlineStyle.SINGLE:
return 'underline';
case UnderlineStyle.DOUBLE:
return 'underline double';
case UnderlineStyle.CURLY:
return 'underline wavy';
case UnderlineStyle.DOTTED:
return 'underline dotted';
case UnderlineStyle.DASHED:
return 'underline dashed';
default:
return 'underline';
}
}
private _diffStyle(cell: IBufferCell, oldCell: IBufferCell): string[] | undefined {
const content: string[] = [];
@@ -647,14 +744,36 @@ export class HTMLSerializeHandler extends BaseSerializeHandler {
if (cell.isInverse()) { content.push('color: #000000; background-color: #BFBFBF;'); }
if (cell.isBold()) { content.push('font-weight: bold;'); }
if (cell.isUnderline() && cell.isOverline()) { content.push('text-decoration: overline underline;'); }
else if (cell.isUnderline()) { content.push('text-decoration: underline;'); }
else if (cell.isOverline()) { content.push('text-decoration: overline;'); }
if (cell.isBlink()) { content.push('text-decoration: blink;'); }
// Handle text-decoration (underline, overline, strikethrough, blink)
const decorations: string[] = [];
if (cell.isUnderline()) {
decorations.push(this._getUnderlineStyle(cell));
}
if (cell.isOverline()) {
decorations.push('overline');
}
if (cell.isStrikethrough()) {
decorations.push('line-through');
}
if (cell.isBlink()) {
decorations.push('blink');
}
if (decorations.length > 0) {
content.push('text-decoration: ' + decorations.join(' ') + ';');
}
// Handle underline color
if (cell.isUnderline()) {
const underlineColor = this._getUnderlineColor(cell);
if (underlineColor) {
content.push('text-decoration-color: ' + underlineColor + ';');
}
}
if (cell.isInvisible()) { content.push('visibility: hidden;'); }
if (cell.isItalic()) { content.push('font-style: italic;'); }
if (cell.isDim()) { content.push('opacity: 0.5;'); }
if (cell.isStrikethrough()) { content.push('text-decoration: line-through;'); }
return content;
}
+19
View File
@@ -0,0 +1,19 @@
Copyright (c) 2024, The xterm.js authors (https://github.com/xtermjs/xterm.js)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+220
View File
@@ -0,0 +1,220 @@
## @xterm/addon-web-fonts
Addon to use webfonts with [xterm.js](https://github.com/xtermjs/xterm.js).
This addon requires xterm.js v5+.
### Install
```bash
npm install --save @xterm/addon-web-fonts
```
### Issue with Webfonts
Webfonts are announced by CSS `font-face` rules (or its Javascript `FontFace` counterparts).
Since font files tend to be quite big assets, browser engines often postpone their loading
to an actual styling request of a codepoint matching a font file's `unicode-range`.
In short - font files will not be loaded until really needed.
xterm.js on the other hand heavily relies on exact measurement of character glyphs
to layout its output. This is done by determining the glyph width (DOM renderer) or
by creating a glyph texture (WebGl renderer) for every output character.
For performance reasons both is done in synchronous code and cached.
This logic only works properly, if a font glyph is available on its first usage,
otherwise the browser will pick a glyph from a fallback font messing up the metrics.
For webfonts and xterm.js this means that we cannot rely on the default loading strategy
of the browser, but have to preload the font files before using that font in xterm.js.
### Static Preloading for the Rescue?
If you dont mind higher initial loading times with a white page shown,
you can tell the browser to preload the needed font files by placing the following
link elements in the document's head above any other CSS/Javascript:
```html
<link rel="preload" as="font" href="/path/to/your/fontfile1.woff" type="font/woff2" crossorigin="anonymous">
<link rel="preload" as="font" href="/path/to/your/fontfile2.woff" type="font/woff2" crossorigin="anonymous">
...
<!-- CSS with font-face rules matching the URLs above -->
```
Browsers also will resort to system fonts, if the preloading takes too long.
So this solution has only a very limited scope.
### Loading with WebFontsAddon
The webfonts addon offers several ways to deal with font assets loading
without leaving the terminal in an unusable state.
Recap - normally boostrapping of a new terminal involves these basic steps (Typescript):
```typescript
import { Terminal } from '@xterm/xterm';
import { XYAddon } from '@xterm/addon-xy';
// create a `Terminal` instance with some options, e.g. a custom font family
const terminal = new Terminal({fontFamily: 'monospace'});
// create and load all addons you want to use, e.g. fit addon
const xyInstance = new XYAddon();
terminal.loadAddon(xyInstance);
// finally: call `open` of the terminal instance
terminal.open(your_terminal_div_element); // <-- critical path for webfonts
// more boostrapping goes here ...
```
This code is guaranteed to work in all browsers synchronously, as the identifier `monospace`
will always be available. It will also work synchronously with any installed system font,
but breaks horribly with webfonts. The actual culprit here is the call to `terminal.open`,
which attaches the terminal to the DOM and starts the renderer with all the glyph caching
mentioned above, while the webfont is not yet fully available.
To fix that, the webfonts addon provides a waiting condition (Typescript):
```typescript
import { Terminal } from '@xterm/xterm';
import { XYAddon } from '@xterm/addon-xy';
import { WebFontsAddon } from '@xterm/addon-web-fonts';
// create a `Terminal` instance, now with webfonts
const terminal = new Terminal({fontFamily: '"Web Mono 1", "Super Powerline", monospace'});
const xyInstance = new XYAddon();
terminal.loadAddon(xyInstance);
const webFontsInstance = new WebFontsAddon();
terminal.loadAddon(webFontsInstance);
// wait for webfonts to be fully loaded
webFontsInstance.loadFonts(['Web Mono 1', 'Super Powerline']).then(() => {
terminal.open(your_terminal_div_element);
// more boostrapping goes here ...
});
```
Here `loadFonts` will look up the font face objects in `document.fonts`
and load them before continuing. For this to work, you have to make sure,
that the CSS `font-face` rules for these webfonts are loaded beforehand,
otherwise `loadFonts` will not find the font family names (promise will be
rejected for missing font family names).
Please note, that this cannot run synchronous anymore, so you will have to split your
bootstrapping code into several stages. If that is too much of a hassle,
you can also move the whole bootstrapping under the waiting condition by using
the static loader instead (Typescript):
```typescript
import { Terminal } from '@xterm/xterm';
import { XYAddon } from '@xterm/addon-xy';
// import static loader
import { loadFonts } from '@xterm/addon-web-fonts';
loadFonts(['Web Mono 1', 'Super Powerline']).then(() => {
// create a `Terminal` instance, now with webfonts
const terminal = new Terminal({fontFamily: '"Web Mono 1", "Super Powerline", monospace'});
const xyInstance = new XYAddon();
terminal.loadAddon(xyInstance);
// optional when using static loader
const webfontsInstance = new WebFontsAddon();
terminal.loadAddon(webfontsInstance);
terminal.open(your_terminal_div_element);
// more boostrapping goes here ...
});
```
With the static loader creating and loading of the actual addon can be omitted,
as fonts are already loaded before any terminal setup happens.
### Webfont Loading at Runtime
Given you have a terminal already running and want to change the font family
to a different not yet loaded webfont:
```typescript
// either create font face objects in javascript
const ff1 = new FontFace('New Web Mono', url1, ...);
const ff2 = new FontFace('New Web Mono', url2, ...);
// and await their loading
loadFonts([ff1, ff2]).then(() => {
// apply new webfont to terminal
terminal.options.fontFamily = 'New Web Mono';
// since the new font might have slighly different metrics,
// also run the fit addon here (or any other custom resize logic)
fitAddon.fit();
});
// or alternatively use CSS to add new font-face rules, e.g.
document.styleSheets[0].insertRule(
"@font-face { font-family: 'New Web Mono'; src: url(newfont.woff); }", 0);
// and await the new font family name
loadFonts(['New Web Mono']).then(() => {
// apply new webfont to terminal
terminal.options.fontFamily = 'New Web Mono';
// since the new font might have slighly different metrics,
// also run the fit addon here (or any other custom resize logic)
fitAddon.fit();
});
```
### Forced Layout Update
If you have the addon loaded into your terminal, you can force the terminal to update
the layout with the method `WebFontsAddon.relayout`. This might come handy,
if the terminal shows webfont related output issue for unknown reasons:
```typescript
...
// given - terminal shows weird font issues, run:
webFontsInstance.relayout().then(() => {
// also run resize logic here, e.g. fit addon
fitAddon.fit();
});
```
Note that this method is only meant as a quickfix on a running terminal to keep it
in a working condition. A production-ready integration should never rely on it,
better fix the real root cause (most likely not properly awaiting the font loader
higher up in the code).
### Webfonts from Fontsource
The addon has been tested to work with webfonts from fontsource.
Javascript example for `vite` with ESM import:
```javascript
import { Terminal } from '@xterm/xterm';
import { FitAddon } from '@xterm/addon-fit';
import { loadFonts } from '@xterm/addon-web-fonts';
import '@xterm/xterm/css/xterm.css';
import '@fontsource/roboto-mono';
import '@fontsource/roboto-mono/400.css';
import '@fontsource/roboto-mono/400-italic.css';
import '@fontsource/roboto-mono/700.css';
import '@fontsource/roboto-mono/700-italic.css';
async function main() {
let fontFamily = '"Roboto Mono", monospace';
try {
await loadFonts(['Roboto Mono']);
} catch (e) {
fontFamily = 'monospace';
}
const terminal = new Terminal({ fontFamily });
const fitAddon = new FitAddon();
terminal.loadAddon(fitAddon);
terminal.open(document.getElementById('your-xterm-container-div'));
fitAddon.fit();
// sync writing shows up in Roboto Mono w'o FOUT
// and a fallback to monospace
terminal.write('put any unicode char here');
}
main();
```
The fontsource packages download the font files to your project folder to be delivered
from there later on. For security sensitive projects this should be the preferred way,
as it brings the font files under your control.
The example furthermore contains proper exception handling with a fallback
(skipped in all other examples for better readability).
---
Also see the full [API](https://github.com/xtermjs/xterm.js/blob/master/addons/addon-web-fonts/typings/addon-web-fonts.d.ts).
+26
View File
@@ -0,0 +1,26 @@
{
"name": "@xterm/addon-web-fonts",
"version": "0.1.0",
"author": {
"name": "The xterm.js authors",
"url": "https://xtermjs.org/"
},
"main": "lib/addon-web-fonts.js",
"module": "lib/addon-web-fonts.mjs",
"types": "typings/addon-web-fonts.d.ts",
"repository": "https://github.com/xtermjs/xterm.js/tree/master/addons/addon-web-fonts",
"license": "MIT",
"keywords": [
"terminal",
"xterm",
"xterm.js"
],
"scripts": {
"build": "../../node_modules/.bin/tsc -p .",
"prepackage": "npm run build",
"package": "../../node_modules/.bin/webpack",
"prepublishOnly": "npm run package",
"start": "node ../../demo/start"
},
"dependencies": {}
}
+152
View File
@@ -0,0 +1,152 @@
/**
* Copyright (c) 2024 The xterm.js authors. All rights reserved.
* @license MIT
*/
import type { Terminal, ITerminalAddon } from '@xterm/xterm';
import type { WebFontsAddon as IWebFontsApi } from '@xterm/addon-web-fonts';
/**
* Unquote a font family name.
*/
function unquote(s: string): string {
if (s[0] === '"' && s[s.length - 1] === '"') return s.slice(1, -1);
if (s[0] === '\'' && s[s.length - 1] === '\'') return s.slice(1, -1);
return s;
}
/**
* Quote a font family name conditionally.
* @see https://mathiasbynens.be/notes/unquoted-font-family
*/
function quote(s: string): string {
const pos = s.match(/([-_a-zA-Z0-9\xA0-\u{10FFFF}]+)/u);
const neg = s.match(/^(-?\d|--)/m);
if (!neg && pos && pos[1] === s) return s;
return `"${s.replace(/"/g, '\\"')}"`;
}
function splitFamily(family: string | undefined): string[] {
if (!family) return [];
return family.split(',').map(e => unquote(e.trim()));
}
function createFamily(families: string[]): string {
return families.map(quote).join(', ');
}
/**
* Hash a font face from it properties.
* Used in `loadFonts` to avoid bloating
* `document.fonts` from multiple calls.
*/
function hashFontFace(ff: FontFace): string {
return JSON.stringify([
unquote(ff.family),
ff.stretch,
ff.style,
ff.unicodeRange,
ff.weight
]);
}
/**
* Wait for webfont resources to be loaded.
*
* Without any argument, all fonts currently listed in
* `document.fonts` will be loaded.
* For a more fine-grained loading strategy you can populate
* the `fonts` argument with:
* - font families : loads all fontfaces in `document.fonts`
* matching the family names
* - fontface objects : loads given fontfaces and adds them to
* `document.fonts`
*
* The returned promise will resolve, when all loading is done.
*/
function _loadFonts(fonts?: (string | FontFace)[]): Promise<FontFace[]> {
const ffs = Array.from(document.fonts);
if (!fonts || !fonts.length) {
return Promise.all(ffs.map(ff => ff.load()));
}
let toLoad: FontFace[] = [];
const ffsHashed = ffs.map(ff => hashFontFace(ff));
for (const font of fonts) {
if (font instanceof FontFace) {
const fontHashed = hashFontFace(font);
const idx = ffsHashed.indexOf(fontHashed);
if (idx === -1) {
document.fonts.add(font);
ffs.push(font);
ffsHashed.push(fontHashed);
toLoad.push(font);
} else {
toLoad.push(ffs[idx]);
}
} else {
// string as font
const familyFiltered = ffs.filter(ff => font === unquote(ff.family));
toLoad = toLoad.concat(familyFiltered);
if (!familyFiltered.length) {
return Promise.reject(`font family "${font}" not registered in document.fonts`);
}
}
}
return Promise.all(toLoad.map(ff => ff.load()));
}
export function loadFonts(fonts?: (string | FontFace)[]): Promise<FontFace[]> {
return document.fonts.ready.then(() => _loadFonts(fonts));
}
export class WebFontsAddon implements ITerminalAddon, IWebFontsApi {
private _term: Terminal | undefined;
constructor(public initialRelayout: boolean = true) { }
public dispose(): void {
this._term = undefined;
}
public activate(term: Terminal): void {
this._term = term;
if (this.initialRelayout) {
document.fonts.ready.then(() => this.relayout());
}
}
public loadFonts(fonts?: (string | FontFace)[]): Promise<FontFace[]> {
return loadFonts(fonts);
}
public async relayout(): Promise<void> {
if (!this._term) {
return;
}
await document.fonts.ready;
const family = this._term.options.fontFamily;
const families = splitFamily(family);
const webFamilies = Array.from(new Set(Array.from(document.fonts).map(e => unquote(e.family))));
const dirty: string[] = [];
const clean: string[] = [];
for (const fam of families) {
(webFamilies.indexOf(fam) !== -1 ? dirty : clean).push(fam);
}
if (!dirty.length) {
return;
}
await _loadFonts(dirty);
if (this._term) {
this._term.options.fontFamily = clean.length ? createFamily(clean) : 'monospace';
this._term.options.fontFamily = family;
}
}
}
+28
View File
@@ -0,0 +1,28 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es2021",
"lib": [
"dom",
"es2015",
"dom.iterable"
],
"rootDir": ".",
"outDir": "../out",
"sourceMap": true,
"removeComments": true,
"strict": true,
"types": [
"../../../node_modules/@types/mocha"
],
"paths": {
"@xterm/addon-web-fonts": [
"../typings/addon-web-fonts.d.ts"
]
}
},
"include": [
"./**/*",
"../../../typings/xterm.d.ts"
]
}
@@ -0,0 +1,120 @@
/**
* Copyright (c) 2024 The xterm.js authors. All rights reserved.
* @license MIT
*/
import test from '@playwright/test';
import { deepStrictEqual, strictEqual } from 'assert';
import { ITestContext, createTestContext, openTerminal, pollFor, timeout } from '../../../test/playwright/TestUtils';
let ctx: ITestContext;
test.beforeAll(async ({ browser }) => {
ctx = await createTestContext(browser);
await openTerminal(ctx, { cols: 40 });
});
test.afterAll(async () => await ctx.page.close());
test.describe('WebFontsAddon', () => {
test.beforeEach(async () => {
// make sure that we start with no webfonts in the document
const empty = await await getDocumentFonts();
deepStrictEqual(empty, []);
});
test.afterEach(async () => {
// for font loading tests to work, we have to remove added rules and fonts
// to work around the quite aggressive font caching done by the browsers
await ctx.page.evaluate(`
document.styleSheets[0].deleteRule(1);
document.styleSheets[0].deleteRule(0);
document.fonts.clear();
`);
});
test.describe('font loading at runtime', () => {
test('loadFonts (JS)', async () => {
await ctx.page.evaluate(`
const ff1 = new FontFace('Kongtext', "url(/kongtext.regular.ttf) format('truetype')");
const ff2 = new FontFace('BPdots', "url(/bpdots.regular.otf) format('opentype')");
loadFonts([ff1, ff2]);
`);
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'loaded' }, { family: 'BPdots', status: 'loaded' }]);
});
test('loadFonts (CSS, unquoted)', async () => {
await ctx.page.evaluate(`
document.styleSheets[0].insertRule("@font-face {font-family: Kongtext; src: url(/kongtext.regular.ttf) format('truetype')}", 0);
document.styleSheets[0].insertRule("@font-face {font-family: BPdots; src: url(/bpdots.regular.otf) format('opentype')}", 1);
loadFonts(['Kongtext', 'BPdots']);
`);
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'loaded' }, { family: 'BPdots', status: 'loaded' }]);
});
test('loadFonts (CSS, quoted)', async ({ browser }) => {
// NOTE: firefox preserves family quotes from CSS rules in fontface, all other browsers unquote them
await ctx.page.evaluate(`
document.styleSheets[0].insertRule("@font-face {font-family: 'Kongtext'; src: url(/kongtext.regular.ttf) format('truetype')}", 0);
document.styleSheets[0].insertRule("@font-face {font-family: 'BPdots'; src: url(/bpdots.regular.otf) format('opentype')}", 1);
loadFonts(['Kongtext', 'BPdots']);
`);
if (browser.browserType().name() === 'firefox') {
deepStrictEqual(await getDocumentFonts(), [{ family: '"Kongtext"', status: 'loaded' }, { family: '"BPdots"', status: 'loaded' }]);
} else {
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'loaded' }, { family: 'BPdots', status: 'loaded' }]);
}
});
test('FontFace hashing', async () => {
// multiple calls of `loadFonts` with the same objects shall not bloat document.fonts
await ctx.page.evaluate(`
const ff1 = new FontFace('Kongtext', "url(/kongtext.regular.ttf) format('truetype')");
const ff2 = new FontFace('BPdots', "url(/bpdots.regular.otf) format('opentype')");
loadFonts([ff1, ff2]);
loadFonts([ff1, ff2]);
loadFonts([ff1, ff2]).then(() => loadFonts([ff1, ff2]));
`);
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'loaded' }, { family: 'BPdots', status: 'loaded' }]);
});
test('autoload & relayout from ctor', async ({ browser }) => {
// to make this test work, we exclude the default measurement char W (x57) by restricting unicode-range
// now the browser will postpone font loading until codepoint is hit --> wrong glyph metrics on first usage
const data = await ctx.page.evaluate(`
document.styleSheets[0].insertRule("@font-face {font-family: Kongtext; src: url(/kongtext.regular.ttf) format('truetype'); unicode-range: U+00A0-00FF}", 0);
`);
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'unloaded' }]);
// broken case: webfont in ctor without addon usage
await ctx.page.evaluate(`
window.helperTerm = new Terminal({fontFamily: '"Kongtext", ' + term.options.fontFamily});
window.helperTerm.open(term.element);
`);
// safari loads the font, firefox & chrome dont
if (browser.browserType().name() === 'webkit') {
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'loaded' }]);
} else {
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'unloaded' }]);
}
// good case: addon fixes layout for webfont in ctor
// the relayout happens async, so wait a bit with a promise
await ctx.page.evaluate(`
window.helperTerm.dispose();
window.helperTerm = new Terminal({fontFamily: '"Kongtext", ' + term.options.fontFamily});
window._webfontsAddon = new WebFontsAddon();
window.helperTerm.loadAddon(window._webfontsAddon);
window.helperTerm.open(term.element);
`);
await timeout(100);
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'loaded' }]);
// cleanup this messy test case
await ctx.page.evaluate(`
window.helperTerm.dispose();
window._webfontsAddon.dispose();
`);
});
});
});
async function getDocumentFonts(): Promise<any> {
return ctx.page.evaluate(`Array.from(document.fonts).map(ff => ({family: ff.family, status: ff.status}))`);
}
@@ -0,0 +1,35 @@
import { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
testDir: '.',
timeout: 10000,
projects: [
{
name: 'ChromeStable',
use: {
browserName: 'chromium',
channel: 'chrome'
}
},
{
name: 'FirefoxStable',
use: {
browserName: 'firefox'
}
},
{
name: 'WebKit',
use: {
browserName: 'webkit'
}
}
],
reporter: 'list',
webServer: {
command: 'npm run start',
port: 3000,
timeout: 120000,
reuseExistingServer: !process.env.CI
}
};
export default config;
+42
View File
@@ -0,0 +1,42 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es2021",
"lib": [
"es2021",
],
// "downlevelIteration": true,
"rootDir": ".",
"outDir": "../out-test",
"sourceMap": true,
"removeComments": true,
"baseUrl": ".",
"paths": {
"common/*": [
"../../../src/common/*"
],
"browser/*": [
"../../../src/browser/*"
]
},
"strict": true,
"types": [
"../../../node_modules/@types/node"
]
},
"include": [
"./**/*",
"../../../typings/xterm.d.ts"
],
"references": [
{
"path": "../../../src/common"
},
{
"path": "../../../src/browser"
},
{
"path": "../../../test/playwright"
}
]
}
+8
View File
@@ -0,0 +1,8 @@
{
"files": [],
"include": [],
"references": [
{ "path": "./src" },
{ "path": "./test" }
]
}
+67
View File
@@ -0,0 +1,67 @@
/**
* Copyright (c) 2024 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { Terminal, ITerminalAddon } from '@xterm/xterm';
declare module '@xterm/addon-web-fonts' {
/**
* Addon to use webfonts in xterm.js
*/
export class WebFontsAddon implements ITerminalAddon {
/**
* @param initialRelayout Force initial relayout, if a webfont was found (default true).
*/
constructor(initialRelayout?: boolean);
public activate(terminal: Terminal): void;
public dispose(): void;
/**
* Wait for webfont resources to be loaded.
*
* Without any argument, all fonts currently listed in
* `document.fonts` will be loaded.
* For a more fine-grained loading strategy you can populate
* the `fonts` argument with:
* - font families : loads all fontfaces in `document.fonts`
* matching the family names
* - fontface objects : loads given fontfaces and adds them to
* `document.fonts`
*
* The returned promise will resolve, when all loading is done.
*/
public loadFonts(fonts?: (string | FontFace)[]): Promise<FontFace[]>;
/**
* Force a terminal relayout by altering `options.FontFamily`.
*
* Found webfonts in `fontFamily` are temporarily removed until the webfont
* resources are fully loaded.
*
* Call this method, if a terminal with webfonts is stuck with broken
* glyph metrics.
*
* The returned promise will resolve, when font loading and layouting are done.
*/
public relayout(): Promise<void>;
}
/**
* Wait for webfont resources to be loaded.
*
* Without any argument, all fonts currently listed in
* `document.fonts` will be loaded.
* For a more fine-grained loading strategy you can populate
* the `fonts` argument with:
* - font families : loads all fontfaces in `document.fonts`
* matching the family names
* - fontface objects : loads given fontfaces and adds them to
* `document.fonts`
*
* The returned promise will resolve, when all loading is done.
*/
function loadFonts(fonts?: (string | FontFace)[]): Promise<FontFace[]>;
}
+33
View File
@@ -0,0 +1,33 @@
/**
* Copyright (c) 2024 The xterm.js authors. All rights reserved.
* @license MIT
*/
const path = require('path');
const addonName = 'WebFontsAddon';
const mainFile = 'addon-web-fonts.js';
module.exports = {
entry: `./out/${addonName}.js`,
devtool: 'source-map',
module: {
rules: [
{
test: /\.js$/,
use: ["source-map-loader"],
enforce: "pre",
exclude: /node_modules/
}
]
},
output: {
filename: mainFile,
path: path.resolve('./lib'),
library: addonName,
libraryTarget: 'umd',
// Force usage of globalThis instead of global / self. (This is cross-env compatible)
globalObject: 'globalThis',
},
mode: 'production'
};
@@ -50,7 +50,7 @@ function isUrl(urlString: string): boolean {
? `${url.protocol}//${url.username}@${url.host}`
: `${url.protocol}//${url.host}`;
return urlString.toLocaleLowerCase().startsWith(parsedBase.toLocaleLowerCase());
} catch (e) {
} catch {
return false;
}
}
@@ -180,7 +180,7 @@ async function cellPos(col: number, row: number): Promise<[number, number]> {
const coords: any = await ctx.page.evaluate(`
(function() {
const rect = window.term.element.getBoundingClientRect();
const dim = term._core._renderService.dimensions;
const dim = window.term.dimensions;
return {left: rect.left, top: rect.top, bottom: rect.bottom, right: rect.right, width: dim.css.cell.width, height: dim.css.cell.height};
})();
`);
+3 -2
View File
@@ -32,9 +32,10 @@ export function acquireTextureAtlas(
deviceCharWidth: number,
deviceCharHeight: number,
devicePixelRatio: number,
deviceMaxTextureSize: number
deviceMaxTextureSize: number,
customGlyphs: boolean = true
): ITextureAtlas {
const newConfig = generateConfig(deviceCellWidth, deviceCellHeight, deviceCharWidth, deviceCharHeight, options, colors, devicePixelRatio, deviceMaxTextureSize);
const newConfig = generateConfig(deviceCellWidth, deviceCellHeight, deviceCharWidth, deviceCharHeight, options, colors, devicePixelRatio, deviceMaxTextureSize, customGlyphs);
// Check to see if the terminal already owns this config
for (let i = 0; i < charAtlasCache.length; i++) {
+2 -2
View File
@@ -9,7 +9,7 @@ import { ITerminalOptions } from '@xterm/xterm';
import { IColorSet, ReadonlyColorSet } from 'browser/Types';
import { NULL_COLOR } from 'common/Color';
export function generateConfig(deviceCellWidth: number, deviceCellHeight: number, deviceCharWidth: number, deviceCharHeight: number, options: Required<ITerminalOptions>, colors: ReadonlyColorSet, devicePixelRatio: number, deviceMaxTextureSize: number): ICharAtlasConfig {
export function generateConfig(deviceCellWidth: number, deviceCellHeight: number, deviceCharWidth: number, deviceCharHeight: number, options: Required<ITerminalOptions>, colors: ReadonlyColorSet, devicePixelRatio: number, deviceMaxTextureSize: number, customGlyphs: boolean = true): ICharAtlasConfig {
// null out some fields that don't matter
const clonedColors: IColorSet = {
foreground: colors.foreground,
@@ -32,7 +32,7 @@ export function generateConfig(deviceCellWidth: number, deviceCellHeight: number
halfContrastCache: colors.halfContrastCache
};
return {
customGlyphs: options.customGlyphs,
customGlyphs,
devicePixelRatio,
deviceMaxTextureSize,
letterSpacing: options.letterSpacing,
@@ -3,12 +3,15 @@
* @license MIT
*/
import { RendererConstants } from 'browser/renderer/shared/Constants';
import { ICoreBrowserService } from 'browser/services/Services';
/**
* The time between cursor blinks.
*/
const BLINK_INTERVAL = 600;
const enum Constants {
/**
* The time between cursor blinks.
*/
BLINK_INTERVAL = 600,
}
export class CursorBlinkStateManager {
public isCursorVisible: boolean;
@@ -16,6 +19,8 @@ export class CursorBlinkStateManager {
private _animationFrame: number | undefined;
private _blinkStartTimeout: number | undefined;
private _blinkInterval: number | undefined;
private _idleTimeout: number | undefined;
private _isIdlePaused: boolean = false;
/**
* The time at which the animation frame was restarted, this is used on the
@@ -31,6 +36,7 @@ export class CursorBlinkStateManager {
this.isCursorVisible = true;
if (this._coreBrowserService.isFocused) {
this._restartInterval();
this._resetIdleTimer();
}
}
@@ -49,9 +55,16 @@ export class CursorBlinkStateManager {
this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame);
this._animationFrame = undefined;
}
if (this._idleTimeout) {
this._coreBrowserService.window.clearTimeout(this._idleTimeout);
this._idleTimeout = undefined;
}
}
public restartBlinkAnimation(): void {
if (this._isIdlePaused) {
this._resetIdleTimer();
}
if (this.isPaused) {
return;
}
@@ -67,7 +80,7 @@ export class CursorBlinkStateManager {
}
}
private _restartInterval(timeToStart: number = BLINK_INTERVAL): void {
private _restartInterval(timeToStart: number = Constants.BLINK_INTERVAL): void {
// Clear any existing interval
if (this._blinkInterval) {
this._coreBrowserService.window.clearInterval(this._blinkInterval);
@@ -82,7 +95,7 @@ export class CursorBlinkStateManager {
// Check if another animation restart was requested while this was being
// started
if (this._animationTimeRestarted) {
const time = BLINK_INTERVAL - (Date.now() - this._animationTimeRestarted);
const time = Constants.BLINK_INTERVAL - (Date.now() - this._animationTimeRestarted);
this._animationTimeRestarted = undefined;
if (time > 0) {
this._restartInterval(time);
@@ -103,7 +116,7 @@ export class CursorBlinkStateManager {
if (this._animationTimeRestarted) {
// calc time diff
// Make restart interval do a setTimeout initially?
const time = BLINK_INTERVAL - (Date.now() - this._animationTimeRestarted);
const time = Constants.BLINK_INTERVAL - (Date.now() - this._animationTimeRestarted);
this._animationTimeRestarted = undefined;
this._restartInterval(time);
return;
@@ -115,12 +128,13 @@ export class CursorBlinkStateManager {
this._renderCallback();
this._animationFrame = undefined;
});
}, BLINK_INTERVAL);
}, Constants.BLINK_INTERVAL);
}, timeToStart);
}
public pause(): void {
this.isCursorVisible = true;
this._isIdlePaused = false;
if (this._blinkInterval) {
this._coreBrowserService.window.clearInterval(this._blinkInterval);
this._blinkInterval = undefined;
@@ -133,6 +147,10 @@ export class CursorBlinkStateManager {
this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame);
this._animationFrame = undefined;
}
if (this._idleTimeout) {
this._coreBrowserService.window.clearTimeout(this._idleTimeout);
this._idleTimeout = undefined;
}
}
public resume(): void {
@@ -141,6 +159,47 @@ export class CursorBlinkStateManager {
this._animationTimeRestarted = undefined;
this._restartInterval();
this._resetIdleTimer();
this.restartBlinkAnimation();
}
/**
* Resets the idle timer. If the terminal is idle for the idle timeout period,
* the cursor blinking will stop.
*/
private _resetIdleTimer(): void {
this._isIdlePaused = false;
if (this._idleTimeout) {
this._coreBrowserService.window.clearTimeout(this._idleTimeout);
}
this._idleTimeout = this._coreBrowserService.window.setTimeout(() => {
this._stopBlinkingDueToIdle();
}, RendererConstants.CURSOR_BLINK_IDLE_TIMEOUT);
}
/**
* Stops cursor blinking due to idle timeout.
*/
private _stopBlinkingDueToIdle(): void {
// Make cursor visible and stop blinking
this.isCursorVisible = true;
this._isIdlePaused = true;
if (this._blinkInterval) {
this._coreBrowserService.window.clearInterval(this._blinkInterval);
this._blinkInterval = undefined;
}
if (this._blinkStartTimeout) {
this._coreBrowserService.window.clearTimeout(this._blinkStartTimeout);
this._blinkStartTimeout = undefined;
}
if (this._animationFrame) {
this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame);
this._animationFrame = undefined;
}
// Clear the idle timeout as we've already acted on it
this._coreBrowserService.window.clearTimeout(this._idleTimeout);
this._idleTimeout = undefined;
// Trigger a render to show the cursor in its final visible state
this._renderCallback();
}
}
-693
View File
@@ -1,693 +0,0 @@
/**
* Copyright (c) 2021 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { throwIfFalsy } from 'browser/renderer/shared/RendererUtils';
interface IBlockVector {
x: number;
y: number;
w: number;
h: number;
}
export const blockElementDefinitions: { [index: string]: IBlockVector[] | undefined } = {
// Block elements (0x2580-0x2590)
'▀': [{ x: 0, y: 0, w: 8, h: 4 }], // UPPER HALF BLOCK
'▁': [{ x: 0, y: 7, w: 8, h: 1 }], // LOWER ONE EIGHTH BLOCK
'▂': [{ x: 0, y: 6, w: 8, h: 2 }], // LOWER ONE QUARTER BLOCK
'▃': [{ x: 0, y: 5, w: 8, h: 3 }], // LOWER THREE EIGHTHS BLOCK
'▄': [{ x: 0, y: 4, w: 8, h: 4 }], // LOWER HALF BLOCK
'▅': [{ x: 0, y: 3, w: 8, h: 5 }], // LOWER FIVE EIGHTHS BLOCK
'▆': [{ x: 0, y: 2, w: 8, h: 6 }], // LOWER THREE QUARTERS BLOCK
'▇': [{ x: 0, y: 1, w: 8, h: 7 }], // LOWER SEVEN EIGHTHS BLOCK
'█': [{ x: 0, y: 0, w: 8, h: 8 }], // FULL BLOCK
'▉': [{ x: 0, y: 0, w: 7, h: 8 }], // LEFT SEVEN EIGHTHS BLOCK
'▊': [{ x: 0, y: 0, w: 6, h: 8 }], // LEFT THREE QUARTERS BLOCK
'▋': [{ x: 0, y: 0, w: 5, h: 8 }], // LEFT FIVE EIGHTHS BLOCK
'▌': [{ x: 0, y: 0, w: 4, h: 8 }], // LEFT HALF BLOCK
'▍': [{ x: 0, y: 0, w: 3, h: 8 }], // LEFT THREE EIGHTHS BLOCK
'▎': [{ x: 0, y: 0, w: 2, h: 8 }], // LEFT ONE QUARTER BLOCK
'▏': [{ x: 0, y: 0, w: 1, h: 8 }], // LEFT ONE EIGHTH BLOCK
'▐': [{ x: 4, y: 0, w: 4, h: 8 }], // RIGHT HALF BLOCK
// Block elements (0x2594-0x2595)
'▔': [{ x: 0, y: 0, w: 8, h: 1 }], // UPPER ONE EIGHTH BLOCK
'▕': [{ x: 7, y: 0, w: 1, h: 8 }], // RIGHT ONE EIGHTH BLOCK
// Terminal graphic characters (0x2596-0x259F)
'▖': [{ x: 0, y: 4, w: 4, h: 4 }], // QUADRANT LOWER LEFT
'▗': [{ x: 4, y: 4, w: 4, h: 4 }], // QUADRANT LOWER RIGHT
'▘': [{ x: 0, y: 0, w: 4, h: 4 }], // QUADRANT UPPER LEFT
'▙': [{ x: 0, y: 0, w: 4, h: 8 }, { x: 0, y: 4, w: 8, h: 4 }], // QUADRANT UPPER LEFT AND LOWER LEFT AND LOWER RIGHT
'▚': [{ x: 0, y: 0, w: 4, h: 4 }, { x: 4, y: 4, w: 4, h: 4 }], // QUADRANT UPPER LEFT AND LOWER RIGHT
'▛': [{ x: 0, y: 0, w: 4, h: 8 }, { x: 4, y: 0, w: 4, h: 4 }], // QUADRANT UPPER LEFT AND UPPER RIGHT AND LOWER LEFT
'▜': [{ x: 0, y: 0, w: 8, h: 4 }, { x: 4, y: 0, w: 4, h: 8 }], // QUADRANT UPPER LEFT AND UPPER RIGHT AND LOWER RIGHT
'▝': [{ x: 4, y: 0, w: 4, h: 4 }], // QUADRANT UPPER RIGHT
'▞': [{ x: 4, y: 0, w: 4, h: 4 }, { x: 0, y: 4, w: 4, h: 4 }], // QUADRANT UPPER RIGHT AND LOWER LEFT
'▟': [{ x: 4, y: 0, w: 4, h: 8 }, { x: 0, y: 4, w: 8, h: 4 }], // QUADRANT UPPER RIGHT AND LOWER LEFT AND LOWER RIGHT
// VERTICAL ONE EIGHTH BLOCK-2 through VERTICAL ONE EIGHTH BLOCK-7
'\u{1FB70}': [{ x: 1, y: 0, w: 1, h: 8 }],
'\u{1FB71}': [{ x: 2, y: 0, w: 1, h: 8 }],
'\u{1FB72}': [{ x: 3, y: 0, w: 1, h: 8 }],
'\u{1FB73}': [{ x: 4, y: 0, w: 1, h: 8 }],
'\u{1FB74}': [{ x: 5, y: 0, w: 1, h: 8 }],
'\u{1FB75}': [{ x: 6, y: 0, w: 1, h: 8 }],
// HORIZONTAL ONE EIGHTH BLOCK-2 through HORIZONTAL ONE EIGHTH BLOCK-7
'\u{1FB76}': [{ x: 0, y: 1, w: 8, h: 1 }],
'\u{1FB77}': [{ x: 0, y: 2, w: 8, h: 1 }],
'\u{1FB78}': [{ x: 0, y: 3, w: 8, h: 1 }],
'\u{1FB79}': [{ x: 0, y: 4, w: 8, h: 1 }],
'\u{1FB7A}': [{ x: 0, y: 5, w: 8, h: 1 }],
'\u{1FB7B}': [{ x: 0, y: 6, w: 8, h: 1 }],
// LEFT AND LOWER ONE EIGHTH BLOCK
'\u{1FB7C}': [{ x: 0, y: 0, w: 1, h: 8 }, { x: 0, y: 7, w: 8, h: 1 }],
// LEFT AND UPPER ONE EIGHTH BLOCK
'\u{1FB7D}': [{ x: 0, y: 0, w: 1, h: 8 }, { x: 0, y: 0, w: 8, h: 1 }],
// RIGHT AND UPPER ONE EIGHTH BLOCK
'\u{1FB7E}': [{ x: 7, y: 0, w: 1, h: 8 }, { x: 0, y: 0, w: 8, h: 1 }],
// RIGHT AND LOWER ONE EIGHTH BLOCK
'\u{1FB7F}': [{ x: 7, y: 0, w: 1, h: 8 }, { x: 0, y: 7, w: 8, h: 1 }],
// UPPER AND LOWER ONE EIGHTH BLOCK
'\u{1FB80}': [{ x: 0, y: 0, w: 8, h: 1 }, { x: 0, y: 7, w: 8, h: 1 }],
// HORIZONTAL ONE EIGHTH BLOCK-1358
'\u{1FB81}': [{ x: 0, y: 0, w: 8, h: 1 }, { x: 0, y: 2, w: 8, h: 1 }, { x: 0, y: 4, w: 8, h: 1 }, { x: 0, y: 7, w: 8, h: 1 }],
// UPPER ONE QUARTER BLOCK
'\u{1FB82}': [{ x: 0, y: 0, w: 8, h: 2 }],
// UPPER THREE EIGHTHS BLOCK
'\u{1FB83}': [{ x: 0, y: 0, w: 8, h: 3 }],
// UPPER FIVE EIGHTHS BLOCK
'\u{1FB84}': [{ x: 0, y: 0, w: 8, h: 5 }],
// UPPER THREE QUARTERS BLOCK
'\u{1FB85}': [{ x: 0, y: 0, w: 8, h: 6 }],
// UPPER SEVEN EIGHTHS BLOCK
'\u{1FB86}': [{ x: 0, y: 0, w: 8, h: 7 }],
// RIGHT ONE QUARTER BLOCK
'\u{1FB87}': [{ x: 6, y: 0, w: 2, h: 8 }],
// RIGHT THREE EIGHTHS B0OCK
'\u{1FB88}': [{ x: 5, y: 0, w: 3, h: 8 }],
// RIGHT FIVE EIGHTHS BL0CK
'\u{1FB89}': [{ x: 3, y: 0, w: 5, h: 8 }],
// RIGHT THREE QUARTERS 0LOCK
'\u{1FB8A}': [{ x: 2, y: 0, w: 6, h: 8 }],
// RIGHT SEVEN EIGHTHS B0OCK
'\u{1FB8B}': [{ x: 1, y: 0, w: 7, h: 8 }],
// CHECKER BOARD FILL
'\u{1FB95}': [
{ x: 0, y: 0, w: 2, h: 2 }, { x: 4, y: 0, w: 2, h: 2 },
{ x: 2, y: 2, w: 2, h: 2 }, { x: 6, y: 2, w: 2, h: 2 },
{ x: 0, y: 4, w: 2, h: 2 }, { x: 4, y: 4, w: 2, h: 2 },
{ x: 2, y: 6, w: 2, h: 2 }, { x: 6, y: 6, w: 2, h: 2 }
],
// INVERSE CHECKER BOARD FILL
'\u{1FB96}': [
{ x: 2, y: 0, w: 2, h: 2 }, { x: 6, y: 0, w: 2, h: 2 },
{ x: 0, y: 2, w: 2, h: 2 }, { x: 4, y: 2, w: 2, h: 2 },
{ x: 2, y: 4, w: 2, h: 2 }, { x: 6, y: 4, w: 2, h: 2 },
{ x: 0, y: 6, w: 2, h: 2 }, { x: 4, y: 6, w: 2, h: 2 }
],
// HEAVY HORIZONTAL FILL (upper middle and lower one quarter block)
'\u{1FB97}': [{ x: 0, y: 2, w: 8, h: 2 }, { x: 0, y: 6, w: 8, h: 2 }]
};
type PatternDefinition = number[][];
/**
* Defines the repeating pattern used by special characters, the pattern is made up of a 2d array of
* pixel values to be filled (1) or not filled (0).
*/
const patternCharacterDefinitions: { [key: string]: PatternDefinition | undefined } = {
// Shade characters (0x2591-0x2593)
'░': [ // LIGHT SHADE (25%)
[1, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 0]
],
'▒': [ // MEDIUM SHADE (50%)
[1, 0],
[0, 0],
[0, 1],
[0, 0]
],
'▓': [ // DARK SHADE (75%)
[0, 1],
[1, 1],
[1, 0],
[1, 1]
]
};
const enum Shapes {
/** │ */ TOP_TO_BOTTOM = 'M.5,0 L.5,1',
/** ─ */ LEFT_TO_RIGHT = 'M0,.5 L1,.5',
/** └ */ TOP_TO_RIGHT = 'M.5,0 L.5,.5 L1,.5',
/** ┘ */ TOP_TO_LEFT = 'M.5,0 L.5,.5 L0,.5',
/** ┐ */ LEFT_TO_BOTTOM = 'M0,.5 L.5,.5 L.5,1',
/** ┌ */ RIGHT_TO_BOTTOM = 'M0.5,1 L.5,.5 L1,.5',
/** ╵ */ MIDDLE_TO_TOP = 'M.5,.5 L.5,0',
/** ╴ */ MIDDLE_TO_LEFT = 'M.5,.5 L0,.5',
/** ╶ */ MIDDLE_TO_RIGHT = 'M.5,.5 L1,.5',
/** ╷ */ MIDDLE_TO_BOTTOM = 'M.5,.5 L.5,1',
/** ┴ */ T_TOP = 'M0,.5 L1,.5 M.5,.5 L.5,0',
/** ┤ */ T_LEFT = 'M.5,0 L.5,1 M.5,.5 L0,.5',
/** ├ */ T_RIGHT = 'M.5,0 L.5,1 M.5,.5 L1,.5',
/** ┬ */ T_BOTTOM = 'M0,.5 L1,.5 M.5,.5 L.5,1',
/** ┼ */ CROSS = 'M0,.5 L1,.5 M.5,0 L.5,1',
/** ╌ */ TWO_DASHES_HORIZONTAL = 'M.1,.5 L.4,.5 M.6,.5 L.9,.5', // .2 empty, .3 filled
/** ┄ */ THREE_DASHES_HORIZONTAL = 'M.0667,.5 L.2667,.5 M.4,.5 L.6,.5 M.7333,.5 L.9333,.5', // .1333 empty, .2 filled
/** ┉ */ FOUR_DASHES_HORIZONTAL = 'M.05,.5 L.2,.5 M.3,.5 L.45,.5 M.55,.5 L.7,.5 M.8,.5 L.95,.5', // .1 empty, .15 filled
/** ╎ */ TWO_DASHES_VERTICAL = 'M.5,.1 L.5,.4 M.5,.6 L.5,.9',
/** ┆ */ THREE_DASHES_VERTICAL = 'M.5,.0667 L.5,.2667 M.5,.4 L.5,.6 M.5,.7333 L.5,.9333',
/** ┊ */ FOUR_DASHES_VERTICAL = 'M.5,.05 L.5,.2 M.5,.3 L.5,.45 L.5,.55 M.5,.7 L.5,.95',
}
const enum Style {
NORMAL = 1,
BOLD = 3
}
/**
* @param xp The percentage of 15% of the x axis.
* @param yp The percentage of 15% of the x axis on the y axis.
*/
type DrawFunctionDefinition = (xp: number, yp: number) => string;
/**
* This contains the definitions of all box drawing characters in the format of SVG paths (ie. the
* svg d attribute).
*/
export const boxDrawingDefinitions: { [character: string]: { [fontWeight: number]: string | DrawFunctionDefinition } | undefined } = {
// Uniform normal and bold
'─': { [Style.NORMAL]: Shapes.LEFT_TO_RIGHT },
'━': { [Style.BOLD]: Shapes.LEFT_TO_RIGHT },
'│': { [Style.NORMAL]: Shapes.TOP_TO_BOTTOM },
'┃': { [Style.BOLD]: Shapes.TOP_TO_BOTTOM },
'┌': { [Style.NORMAL]: Shapes.RIGHT_TO_BOTTOM },
'┏': { [Style.BOLD]: Shapes.RIGHT_TO_BOTTOM },
'┐': { [Style.NORMAL]: Shapes.LEFT_TO_BOTTOM },
'┓': { [Style.BOLD]: Shapes.LEFT_TO_BOTTOM },
'└': { [Style.NORMAL]: Shapes.TOP_TO_RIGHT },
'┗': { [Style.BOLD]: Shapes.TOP_TO_RIGHT },
'┘': { [Style.NORMAL]: Shapes.TOP_TO_LEFT },
'┛': { [Style.BOLD]: Shapes.TOP_TO_LEFT },
'├': { [Style.NORMAL]: Shapes.T_RIGHT },
'┣': { [Style.BOLD]: Shapes.T_RIGHT },
'┤': { [Style.NORMAL]: Shapes.T_LEFT },
'┫': { [Style.BOLD]: Shapes.T_LEFT },
'┬': { [Style.NORMAL]: Shapes.T_BOTTOM },
'┳': { [Style.BOLD]: Shapes.T_BOTTOM },
'┴': { [Style.NORMAL]: Shapes.T_TOP },
'┻': { [Style.BOLD]: Shapes.T_TOP },
'┼': { [Style.NORMAL]: Shapes.CROSS },
'╋': { [Style.BOLD]: Shapes.CROSS },
'╴': { [Style.NORMAL]: Shapes.MIDDLE_TO_LEFT },
'╸': { [Style.BOLD]: Shapes.MIDDLE_TO_LEFT },
'╵': { [Style.NORMAL]: Shapes.MIDDLE_TO_TOP },
'╹': { [Style.BOLD]: Shapes.MIDDLE_TO_TOP },
'╶': { [Style.NORMAL]: Shapes.MIDDLE_TO_RIGHT },
'╺': { [Style.BOLD]: Shapes.MIDDLE_TO_RIGHT },
'╷': { [Style.NORMAL]: Shapes.MIDDLE_TO_BOTTOM },
'╻': { [Style.BOLD]: Shapes.MIDDLE_TO_BOTTOM },
// Double border
'═': { [Style.NORMAL]: (xp, yp) => `M0,${.5 - yp} L1,${.5 - yp} M0,${.5 + yp} L1,${.5 + yp}` },
'║': { [Style.NORMAL]: (xp, yp) => `M${.5 - xp},0 L${.5 - xp},1 M${.5 + xp},0 L${.5 + xp},1` },
'╒': { [Style.NORMAL]: (xp, yp) => `M.5,1 L.5,${.5 - yp} L1,${.5 - yp} M.5,${.5 + yp} L1,${.5 + yp}` },
'╓': { [Style.NORMAL]: (xp, yp) => `M${.5 - xp},1 L${.5 - xp},.5 L1,.5 M${.5 + xp},.5 L${.5 + xp},1` },
'╔': { [Style.NORMAL]: (xp, yp) => `M1,${.5 - yp} L${.5 - xp},${.5 - yp} L${.5 - xp},1 M1,${.5 + yp} L${.5 + xp},${.5 + yp} L${.5 + xp},1` },
'╕': { [Style.NORMAL]: (xp, yp) => `M0,${.5 - yp} L.5,${.5 - yp} L.5,1 M0,${.5 + yp} L.5,${.5 + yp}` },
'╖': { [Style.NORMAL]: (xp, yp) => `M${.5 + xp},1 L${.5 + xp},.5 L0,.5 M${.5 - xp},.5 L${.5 - xp},1` },
'╗': { [Style.NORMAL]: (xp, yp) => `M0,${.5 + yp} L${.5 - xp},${.5 + yp} L${.5 - xp},1 M0,${.5 - yp} L${.5 + xp},${.5 - yp} L${.5 + xp},1` },
'╘': { [Style.NORMAL]: (xp, yp) => `M.5,0 L.5,${.5 + yp} L1,${.5 + yp} M.5,${.5 - yp} L1,${.5 - yp}` },
'╙': { [Style.NORMAL]: (xp, yp) => `M1,.5 L${.5 - xp},.5 L${.5 - xp},0 M${.5 + xp},.5 L${.5 + xp},0` },
'╚': { [Style.NORMAL]: (xp, yp) => `M1,${.5 - yp} L${.5 + xp},${.5 - yp} L${.5 + xp},0 M1,${.5 + yp} L${.5 - xp},${.5 + yp} L${.5 - xp},0` },
'╛': { [Style.NORMAL]: (xp, yp) => `M0,${.5 + yp} L.5,${.5 + yp} L.5,0 M0,${.5 - yp} L.5,${.5 - yp}` },
'╜': { [Style.NORMAL]: (xp, yp) => `M0,.5 L${.5 + xp},.5 L${.5 + xp},0 M${.5 - xp},.5 L${.5 - xp},0` },
'╝': { [Style.NORMAL]: (xp, yp) => `M0,${.5 - yp} L${.5 - xp},${.5 - yp} L${.5 - xp},0 M0,${.5 + yp} L${.5 + xp},${.5 + yp} L${.5 + xp},0` },
'╞': { [Style.NORMAL]: (xp, yp) => `${Shapes.TOP_TO_BOTTOM} M.5,${.5 - yp} L1,${.5 - yp} M.5,${.5 + yp} L1,${.5 + yp}` },
'╟': { [Style.NORMAL]: (xp, yp) => `M${.5 - xp},0 L${.5 - xp},1 M${.5 + xp},0 L${.5 + xp},1 M${.5 + xp},.5 L1,.5` },
'╠': { [Style.NORMAL]: (xp, yp) => `M${.5 - xp},0 L${.5 - xp},1 M1,${.5 + yp} L${.5 + xp},${.5 + yp} L${.5 + xp},1 M1,${.5 - yp} L${.5 + xp},${.5 - yp} L${.5 + xp},0` },
'╡': { [Style.NORMAL]: (xp, yp) => `${Shapes.TOP_TO_BOTTOM} M0,${.5 - yp} L.5,${.5 - yp} M0,${.5 + yp} L.5,${.5 + yp}` },
'╢': { [Style.NORMAL]: (xp, yp) => `M0,.5 L${.5 - xp},.5 M${.5 - xp},0 L${.5 - xp},1 M${.5 + xp},0 L${.5 + xp},1` },
'╣': { [Style.NORMAL]: (xp, yp) => `M${.5 + xp},0 L${.5 + xp},1 M0,${.5 + yp} L${.5 - xp},${.5 + yp} L${.5 - xp},1 M0,${.5 - yp} L${.5 - xp},${.5 - yp} L${.5 - xp},0` },
'╤': { [Style.NORMAL]: (xp, yp) => `M0,${.5 - yp} L1,${.5 - yp} M0,${.5 + yp} L1,${.5 + yp} M.5,${.5 + yp} L.5,1` },
'╥': { [Style.NORMAL]: (xp, yp) => `${Shapes.LEFT_TO_RIGHT} M${.5 - xp},.5 L${.5 - xp},1 M${.5 + xp},.5 L${.5 + xp},1` },
'╦': { [Style.NORMAL]: (xp, yp) => `M0,${.5 - yp} L1,${.5 - yp} M0,${.5 + yp} L${.5 - xp},${.5 + yp} L${.5 - xp},1 M1,${.5 + yp} L${.5 + xp},${.5 + yp} L${.5 + xp},1` },
'╧': { [Style.NORMAL]: (xp, yp) => `M.5,0 L.5,${.5 - yp} M0,${.5 - yp} L1,${.5 - yp} M0,${.5 + yp} L1,${.5 + yp}` },
'╨': { [Style.NORMAL]: (xp, yp) => `${Shapes.LEFT_TO_RIGHT} M${.5 - xp},.5 L${.5 - xp},0 M${.5 + xp},.5 L${.5 + xp},0` },
'╩': { [Style.NORMAL]: (xp, yp) => `M0,${.5 + yp} L1,${.5 + yp} M0,${.5 - yp} L${.5 - xp},${.5 - yp} L${.5 - xp},0 M1,${.5 - yp} L${.5 + xp},${.5 - yp} L${.5 + xp},0` },
'╪': { [Style.NORMAL]: (xp, yp) => `${Shapes.TOP_TO_BOTTOM} M0,${.5 - yp} L1,${.5 - yp} M0,${.5 + yp} L1,${.5 + yp}` },
'╫': { [Style.NORMAL]: (xp, yp) => `${Shapes.LEFT_TO_RIGHT} M${.5 - xp},0 L${.5 - xp},1 M${.5 + xp},0 L${.5 + xp},1` },
'╬': { [Style.NORMAL]: (xp, yp) => `M0,${.5 + yp} L${.5 - xp},${.5 + yp} L${.5 - xp},1 M1,${.5 + yp} L${.5 + xp},${.5 + yp} L${.5 + xp},1 M0,${.5 - yp} L${.5 - xp},${.5 - yp} L${.5 - xp},0 M1,${.5 - yp} L${.5 + xp},${.5 - yp} L${.5 + xp},0` },
// Diagonal
'╱': { [Style.NORMAL]: 'M1,0 L0,1' },
'╲': { [Style.NORMAL]: 'M0,0 L1,1' },
'╳': { [Style.NORMAL]: 'M1,0 L0,1 M0,0 L1,1' },
// Mixed weight
'╼': { [Style.NORMAL]: Shapes.MIDDLE_TO_LEFT, [Style.BOLD]: Shapes.MIDDLE_TO_RIGHT },
'╽': { [Style.NORMAL]: Shapes.MIDDLE_TO_TOP, [Style.BOLD]: Shapes.MIDDLE_TO_BOTTOM },
'╾': { [Style.NORMAL]: Shapes.MIDDLE_TO_RIGHT, [Style.BOLD]: Shapes.MIDDLE_TO_LEFT },
'╿': { [Style.NORMAL]: Shapes.MIDDLE_TO_BOTTOM, [Style.BOLD]: Shapes.MIDDLE_TO_TOP },
'┍': { [Style.NORMAL]: Shapes.MIDDLE_TO_BOTTOM, [Style.BOLD]: Shapes.MIDDLE_TO_RIGHT },
'┎': { [Style.NORMAL]: Shapes.MIDDLE_TO_RIGHT, [Style.BOLD]: Shapes.MIDDLE_TO_BOTTOM },
'┑': { [Style.NORMAL]: Shapes.MIDDLE_TO_BOTTOM, [Style.BOLD]: Shapes.MIDDLE_TO_LEFT },
'┒': { [Style.NORMAL]: Shapes.MIDDLE_TO_LEFT, [Style.BOLD]: Shapes.MIDDLE_TO_BOTTOM },
'┕': { [Style.NORMAL]: Shapes.MIDDLE_TO_TOP, [Style.BOLD]: Shapes.MIDDLE_TO_RIGHT },
'┖': { [Style.NORMAL]: Shapes.MIDDLE_TO_RIGHT, [Style.BOLD]: Shapes.MIDDLE_TO_TOP },
'┙': { [Style.NORMAL]: Shapes.MIDDLE_TO_TOP, [Style.BOLD]: Shapes.MIDDLE_TO_LEFT },
'┚': { [Style.NORMAL]: Shapes.MIDDLE_TO_LEFT, [Style.BOLD]: Shapes.MIDDLE_TO_TOP },
'┝': { [Style.NORMAL]: Shapes.TOP_TO_BOTTOM, [Style.BOLD]: Shapes.MIDDLE_TO_RIGHT },
'┞': { [Style.NORMAL]: Shapes.RIGHT_TO_BOTTOM, [Style.BOLD]: Shapes.MIDDLE_TO_TOP },
'┟': { [Style.NORMAL]: Shapes.TOP_TO_RIGHT, [Style.BOLD]: Shapes.MIDDLE_TO_BOTTOM },
'┠': { [Style.NORMAL]: Shapes.MIDDLE_TO_RIGHT, [Style.BOLD]: Shapes.TOP_TO_BOTTOM },
'┡': { [Style.NORMAL]: Shapes.MIDDLE_TO_BOTTOM, [Style.BOLD]: Shapes.TOP_TO_RIGHT },
'┢': { [Style.NORMAL]: Shapes.MIDDLE_TO_TOP, [Style.BOLD]: Shapes.RIGHT_TO_BOTTOM },
'┥': { [Style.NORMAL]: Shapes.TOP_TO_BOTTOM, [Style.BOLD]: Shapes.MIDDLE_TO_LEFT },
'┦': { [Style.NORMAL]: Shapes.LEFT_TO_BOTTOM, [Style.BOLD]: Shapes.MIDDLE_TO_TOP },
'┧': { [Style.NORMAL]: Shapes.TOP_TO_LEFT, [Style.BOLD]: Shapes.MIDDLE_TO_BOTTOM },
'┨': { [Style.NORMAL]: Shapes.MIDDLE_TO_LEFT, [Style.BOLD]: Shapes.TOP_TO_BOTTOM },
'┩': { [Style.NORMAL]: Shapes.MIDDLE_TO_BOTTOM, [Style.BOLD]: Shapes.TOP_TO_LEFT },
'┪': { [Style.NORMAL]: Shapes.MIDDLE_TO_TOP, [Style.BOLD]: Shapes.LEFT_TO_BOTTOM },
'┭': { [Style.NORMAL]: Shapes.RIGHT_TO_BOTTOM, [Style.BOLD]: Shapes.MIDDLE_TO_LEFT },
'┮': { [Style.NORMAL]: Shapes.LEFT_TO_BOTTOM, [Style.BOLD]: Shapes.MIDDLE_TO_RIGHT },
'┯': { [Style.NORMAL]: Shapes.MIDDLE_TO_BOTTOM, [Style.BOLD]: Shapes.LEFT_TO_RIGHT },
'┰': { [Style.NORMAL]: Shapes.LEFT_TO_RIGHT, [Style.BOLD]: Shapes.MIDDLE_TO_BOTTOM },
'┱': { [Style.NORMAL]: Shapes.MIDDLE_TO_RIGHT, [Style.BOLD]: Shapes.LEFT_TO_BOTTOM },
'┲': { [Style.NORMAL]: Shapes.MIDDLE_TO_LEFT, [Style.BOLD]: Shapes.RIGHT_TO_BOTTOM },
'┵': { [Style.NORMAL]: Shapes.TOP_TO_RIGHT, [Style.BOLD]: Shapes.MIDDLE_TO_LEFT },
'┶': { [Style.NORMAL]: Shapes.TOP_TO_LEFT, [Style.BOLD]: Shapes.MIDDLE_TO_RIGHT },
'┷': { [Style.NORMAL]: Shapes.MIDDLE_TO_TOP, [Style.BOLD]: Shapes.LEFT_TO_RIGHT },
'┸': { [Style.NORMAL]: Shapes.LEFT_TO_RIGHT, [Style.BOLD]: Shapes.MIDDLE_TO_TOP },
'┹': { [Style.NORMAL]: Shapes.MIDDLE_TO_RIGHT, [Style.BOLD]: Shapes.TOP_TO_LEFT },
'┺': { [Style.NORMAL]: Shapes.MIDDLE_TO_LEFT, [Style.BOLD]: Shapes.TOP_TO_RIGHT },
'┽': { [Style.NORMAL]: `${Shapes.TOP_TO_BOTTOM} ${Shapes.MIDDLE_TO_RIGHT}`, [Style.BOLD]: Shapes.MIDDLE_TO_LEFT },
'┾': { [Style.NORMAL]: `${Shapes.TOP_TO_BOTTOM} ${Shapes.MIDDLE_TO_LEFT}`, [Style.BOLD]: Shapes.MIDDLE_TO_RIGHT },
'┿': { [Style.NORMAL]: Shapes.TOP_TO_BOTTOM, [Style.BOLD]: Shapes.LEFT_TO_RIGHT },
'╀': { [Style.NORMAL]: `${Shapes.LEFT_TO_RIGHT} ${Shapes.MIDDLE_TO_BOTTOM}`, [Style.BOLD]: Shapes.MIDDLE_TO_TOP },
'╁': { [Style.NORMAL]: `${Shapes.MIDDLE_TO_TOP} ${Shapes.LEFT_TO_RIGHT}`, [Style.BOLD]: Shapes.MIDDLE_TO_BOTTOM },
'╂': { [Style.NORMAL]: Shapes.LEFT_TO_RIGHT, [Style.BOLD]: Shapes.TOP_TO_BOTTOM },
'╃': { [Style.NORMAL]: Shapes.RIGHT_TO_BOTTOM, [Style.BOLD]: Shapes.TOP_TO_LEFT },
'╄': { [Style.NORMAL]: Shapes.LEFT_TO_BOTTOM, [Style.BOLD]: Shapes.TOP_TO_RIGHT },
'╅': { [Style.NORMAL]: Shapes.TOP_TO_RIGHT, [Style.BOLD]: Shapes.LEFT_TO_BOTTOM },
'╆': { [Style.NORMAL]: Shapes.TOP_TO_LEFT, [Style.BOLD]: Shapes.RIGHT_TO_BOTTOM },
'╇': { [Style.NORMAL]: Shapes.MIDDLE_TO_BOTTOM, [Style.BOLD]: `${Shapes.MIDDLE_TO_TOP} ${Shapes.LEFT_TO_RIGHT}` },
'╈': { [Style.NORMAL]: Shapes.MIDDLE_TO_TOP, [Style.BOLD]: `${Shapes.LEFT_TO_RIGHT} ${Shapes.MIDDLE_TO_BOTTOM}` },
'╉': { [Style.NORMAL]: Shapes.MIDDLE_TO_RIGHT, [Style.BOLD]: `${Shapes.TOP_TO_BOTTOM} ${Shapes.MIDDLE_TO_LEFT}` },
'╊': { [Style.NORMAL]: Shapes.MIDDLE_TO_LEFT, [Style.BOLD]: `${Shapes.TOP_TO_BOTTOM} ${Shapes.MIDDLE_TO_RIGHT}` },
// Dashed
'╌': { [Style.NORMAL]: Shapes.TWO_DASHES_HORIZONTAL },
'╍': { [Style.BOLD]: Shapes.TWO_DASHES_HORIZONTAL },
'┄': { [Style.NORMAL]: Shapes.THREE_DASHES_HORIZONTAL },
'┅': { [Style.BOLD]: Shapes.THREE_DASHES_HORIZONTAL },
'┈': { [Style.NORMAL]: Shapes.FOUR_DASHES_HORIZONTAL },
'┉': { [Style.BOLD]: Shapes.FOUR_DASHES_HORIZONTAL },
'╎': { [Style.NORMAL]: Shapes.TWO_DASHES_VERTICAL },
'╏': { [Style.BOLD]: Shapes.TWO_DASHES_VERTICAL },
'┆': { [Style.NORMAL]: Shapes.THREE_DASHES_VERTICAL },
'┇': { [Style.BOLD]: Shapes.THREE_DASHES_VERTICAL },
'┊': { [Style.NORMAL]: Shapes.FOUR_DASHES_VERTICAL },
'┋': { [Style.BOLD]: Shapes.FOUR_DASHES_VERTICAL },
// Curved
'╭': { [Style.NORMAL]: (xp, yp) => `M.5,1 L.5,${.5 + (yp / .15 * .5)} C.5,${.5 + (yp / .15 * .5)},.5,.5,1,.5` },
'╮': { [Style.NORMAL]: (xp, yp) => `M.5,1 L.5,${.5 + (yp / .15 * .5)} C.5,${.5 + (yp / .15 * .5)},.5,.5,0,.5` },
'╯': { [Style.NORMAL]: (xp, yp) => `M.5,0 L.5,${.5 - (yp / .15 * .5)} C.5,${.5 - (yp / .15 * .5)},.5,.5,0,.5` },
'╰': { [Style.NORMAL]: (xp, yp) => `M.5,0 L.5,${.5 - (yp / .15 * .5)} C.5,${.5 - (yp / .15 * .5)},.5,.5,1,.5` }
};
interface IVectorShape {
d: string;
type: VectorType;
leftPadding?: number;
rightPadding?: number;
}
const enum VectorType {
FILL,
STROKE
}
/**
* This contains the definitions of the primarily used box drawing characters as vector shapes. The
* reason these characters are defined specially is to avoid common problems if a user's font has
* not been patched with powerline characters and also to get pixel perfect rendering as rendering
* issues can occur around AA/SPAA.
*
* The line variants draw beyond the cell and get clipped to ensure the end of the line is not
* visible.
*
* Original symbols defined in https://github.com/powerline/fontpatcher
*/
export const powerlineDefinitions: { [index: string]: IVectorShape } = {
// Git branch
'\u{E0A0}': { d: 'M.3,1 L.03,1 L.03,.88 C.03,.82,.06,.78,.11,.73 C.15,.7,.2,.68,.28,.65 L.43,.6 C.49,.58,.53,.56,.56,.53 C.59,.5,.6,.47,.6,.43 L.6,.27 L.4,.27 L.69,.1 L.98,.27 L.78,.27 L.78,.46 C.78,.52,.76,.56,.72,.61 C.68,.66,.63,.67,.56,.7 L.48,.72 C.42,.74,.38,.76,.35,.78 C.32,.8,.31,.84,.31,.88 L.31,1 M.3,.5 L.03,.59 L.03,.09 L.3,.09 L.3,.655', type: VectorType.FILL },
// L N
'\u{E0A1}': { d: 'M.7,.4 L.7,.47 L.2,.47 L.2,.03 L.355,.03 L.355,.4 L.705,.4 M.7,.5 L.86,.5 L.86,.95 L.69,.95 L.44,.66 L.46,.86 L.46,.95 L.3,.95 L.3,.49 L.46,.49 L.71,.78 L.69,.565 L.69,.5', type: VectorType.FILL },
// Lock
'\u{E0A2}': { d: 'M.25,.94 C.16,.94,.11,.92,.11,.87 L.11,.53 C.11,.48,.15,.455,.23,.45 L.23,.3 C.23,.25,.26,.22,.31,.19 C.36,.16,.43,.15,.51,.15 C.59,.15,.66,.16,.71,.19 C.77,.22,.79,.26,.79,.3 L.79,.45 C.87,.45,.91,.48,.91,.53 L.91,.87 C.91,.92,.86,.94,.77,.94 L.24,.94 M.53,.2 C.49,.2,.45,.21,.42,.23 C.39,.25,.38,.27,.38,.3 L.38,.45 L.68,.45 L.68,.3 C.68,.27,.67,.25,.64,.23 C.61,.21,.58,.2,.53,.2 M.58,.82 L.58,.66 C.63,.65,.65,.63,.65,.6 C.65,.58,.64,.57,.61,.56 C.58,.55,.56,.54,.52,.54 C.48,.54,.46,.55,.43,.56 C.4,.57,.39,.59,.39,.6 C.39,.63,.41,.64,.46,.66 L.46,.82 L.57,.82', type: VectorType.FILL },
// Right triangle solid
'\u{E0B0}': { d: 'M0,0 L1,.5 L0,1', type: VectorType.FILL, rightPadding: 2 },
// Right triangle line
'\u{E0B1}': { d: 'M-1,-.5 L1,.5 L-1,1.5', type: VectorType.STROKE, leftPadding: 1, rightPadding: 1 },
// Left triangle solid
'\u{E0B2}': { d: 'M1,0 L0,.5 L1,1', type: VectorType.FILL, leftPadding: 2 },
// Left triangle line
'\u{E0B3}': { d: 'M2,-.5 L0,.5 L2,1.5', type: VectorType.STROKE, leftPadding: 1, rightPadding: 1 },
// Right semi-circle solid
'\u{E0B4}': { d: 'M0,0 L0,1 C0.552,1,1,0.776,1,.5 C1,0.224,0.552,0,0,0', type: VectorType.FILL, rightPadding: 1 },
// Right semi-circle line
'\u{E0B5}': { d: 'M.2,1 C.422,1,.8,.826,.78,.5 C.8,.174,0.422,0,.2,0', type: VectorType.STROKE, rightPadding: 1 },
// Left semi-circle solid
'\u{E0B6}': { d: 'M1,0 L1,1 C0.448,1,0,0.776,0,.5 C0,0.224,0.448,0,1,0', type: VectorType.FILL, leftPadding: 1 },
// Left semi-circle line
'\u{E0B7}': { d: 'M.8,1 C0.578,1,0.2,.826,.22,.5 C0.2,0.174,0.578,0,0.8,0', type: VectorType.STROKE, leftPadding: 1 },
// Lower left triangle
'\u{E0B8}': { d: 'M-.5,-.5 L1.5,1.5 L-.5,1.5', type: VectorType.FILL },
// Backslash separator
'\u{E0B9}': { d: 'M-.5,-.5 L1.5,1.5', type: VectorType.STROKE, leftPadding: 1, rightPadding: 1 },
// Lower right triangle
'\u{E0BA}': { d: 'M1.5,-.5 L-.5,1.5 L1.5,1.5', type: VectorType.FILL },
// Upper left triangle
'\u{E0BC}': { d: 'M1.5,-.5 L-.5,1.5 L-.5,-.5', type: VectorType.FILL },
// Forward slash separator
'\u{E0BD}': { d: 'M1.5,-.5 L-.5,1.5', type: VectorType.STROKE, leftPadding: 1, rightPadding: 1 },
// Upper right triangle
'\u{E0BE}': { d: 'M-.5,-.5 L1.5,1.5 L1.5,-.5', type: VectorType.FILL }
};
// Forward slash separator redundant
powerlineDefinitions['\u{E0BB}'] = powerlineDefinitions['\u{E0BD}'];
// Backslash separator redundant
powerlineDefinitions['\u{E0BF}'] = powerlineDefinitions['\u{E0B9}'];
/**
* Try drawing a custom block element or box drawing character, returning whether it was
* successfully drawn.
*/
export function tryDrawCustomChar(
ctx: CanvasRenderingContext2D,
c: string,
xOffset: number,
yOffset: number,
deviceCellWidth: number,
deviceCellHeight: number,
fontSize: number,
devicePixelRatio: number
): boolean {
const blockElementDefinition = blockElementDefinitions[c];
if (blockElementDefinition) {
drawBlockElementChar(ctx, blockElementDefinition, xOffset, yOffset, deviceCellWidth, deviceCellHeight);
return true;
}
const patternDefinition = patternCharacterDefinitions[c];
if (patternDefinition) {
drawPatternChar(ctx, patternDefinition, xOffset, yOffset, deviceCellWidth, deviceCellHeight);
return true;
}
const boxDrawingDefinition = boxDrawingDefinitions[c];
if (boxDrawingDefinition) {
drawBoxDrawingChar(ctx, boxDrawingDefinition, xOffset, yOffset, deviceCellWidth, deviceCellHeight, devicePixelRatio);
return true;
}
const powerlineDefinition = powerlineDefinitions[c];
if (powerlineDefinition) {
drawPowerlineChar(ctx, powerlineDefinition, xOffset, yOffset, deviceCellWidth, deviceCellHeight, fontSize, devicePixelRatio);
return true;
}
return false;
}
function drawBlockElementChar(
ctx: CanvasRenderingContext2D,
charDefinition: IBlockVector[],
xOffset: number,
yOffset: number,
deviceCellWidth: number,
deviceCellHeight: number
): void {
for (let i = 0; i < charDefinition.length; i++) {
const box = charDefinition[i];
const xEighth = deviceCellWidth / 8;
const yEighth = deviceCellHeight / 8;
ctx.fillRect(
xOffset + box.x * xEighth,
yOffset + box.y * yEighth,
box.w * xEighth,
box.h * yEighth
);
}
}
const cachedPatterns: Map<PatternDefinition, Map</* fillStyle */string, CanvasPattern>> = new Map();
function drawPatternChar(
ctx: CanvasRenderingContext2D,
charDefinition: number[][],
xOffset: number,
yOffset: number,
deviceCellWidth: number,
deviceCellHeight: number
): void {
let patternSet = cachedPatterns.get(charDefinition);
if (!patternSet) {
patternSet = new Map();
cachedPatterns.set(charDefinition, patternSet);
}
const fillStyle = ctx.fillStyle;
if (typeof fillStyle !== 'string') {
throw new Error(`Unexpected fillStyle type "${fillStyle}"`);
}
let pattern = patternSet.get(fillStyle);
if (!pattern) {
const width = charDefinition[0].length;
const height = charDefinition.length;
const tmpCanvas = ctx.canvas.ownerDocument.createElement('canvas');
tmpCanvas.width = width;
tmpCanvas.height = height;
const tmpCtx = throwIfFalsy(tmpCanvas.getContext('2d'));
const imageData = new ImageData(width, height);
// Extract rgba from fillStyle
let r: number;
let g: number;
let b: number;
let a: number;
if (fillStyle.startsWith('#')) {
r = parseInt(fillStyle.slice(1, 3), 16);
g = parseInt(fillStyle.slice(3, 5), 16);
b = parseInt(fillStyle.slice(5, 7), 16);
a = fillStyle.length > 7 && parseInt(fillStyle.slice(7, 9), 16) || 1;
} else if (fillStyle.startsWith('rgba')) {
([r, g, b, a] = fillStyle.substring(5, fillStyle.length - 1).split(',').map(e => parseFloat(e)));
} else {
throw new Error(`Unexpected fillStyle color format "${fillStyle}" when drawing pattern glyph`);
}
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
imageData.data[(y * width + x) * 4 ] = r;
imageData.data[(y * width + x) * 4 + 1] = g;
imageData.data[(y * width + x) * 4 + 2] = b;
imageData.data[(y * width + x) * 4 + 3] = charDefinition[y][x] * (a * 255);
}
}
tmpCtx.putImageData(imageData, 0, 0);
pattern = throwIfFalsy(ctx.createPattern(tmpCanvas, null));
patternSet.set(fillStyle, pattern);
}
ctx.fillStyle = pattern;
ctx.fillRect(xOffset, yOffset, deviceCellWidth, deviceCellHeight);
}
/**
* Draws the following box drawing characters by mapping a subset of SVG d attribute instructions to
* canvas draw calls.
*
* Box styles: ┎┰┒┍┯┑╓╥╖╒╤╕ ┏┳┓┌┲┓┌┬┐┏┱┐
* ┌─┬─┐ ┏━┳━┓ ╔═╦═╗ ┠╂┨┝┿┥╟╫╢╞╪╡ ┡╇┩├╊┫┢╈┪┣╉┤
* │ │ │ ┃ ┃ ┃ ║ ║ ║ ┖┸┚┕┷┙╙╨╜╘╧╛ └┴┘└┺┛┗┻┛┗┹┘
* ├─┼─┤ ┣━╋━┫ ╠═╬═╣ ┏┱┐┌┲┓┌┬┐┌┬┐ ┏┳┓┌┮┓┌┬┐┏┭┐
* │ │ │ ┃ ┃ ┃ ║ ║ ║ ┡╃┤├╄┩├╆┪┢╅┤ ┞╀┦├┾┫┟╁┧┣┽┤
* └─┴─┘ ┗━┻━┛ ╚═╩═╝ └┴┘└┴┘└┺┛┗┹┘ └┴┘└┶┛┗┻┛┗┵┘
*
* Other:
* ╭─╮ ╲ ╱ ╷╻╎╏┆┇┊┋ ╺╾╴ ╌╌╌ ┄┄┄ ┈┈┈
* │ │ ╳ ╽╿╎╏┆┇┊┋ ╶╼╸ ╍╍╍ ┅┅┅ ┉┉┉
* ╰─╯ ╱ ╲ ╹╵╎╏┆┇┊┋
*
* All box drawing characters:
* ─ ━ │ ┃ ┄ ┅ ┆ ┇ ┈ ┉ ┊ ┋ ┌ ┍ ┎ ┏
* ┐ ┑ ┒ ┓ └ ┕ ┖ ┗ ┘ ┙ ┚ ┛ ├ ┝ ┞ ┟
* ┠ ┡ ┢ ┣ ┤ ┥ ┦ ┧ ┨ ┩ ┪ ┫ ┬ ┭ ┮ ┯
* ┰ ┱ ┲ ┳ ┴ ┵ ┶ ┷ ┸ ┹ ┺ ┻ ┼ ┽ ┾ ┿
* ╀ ╁ ╂ ╃ ╄ ╅ ╆ ╇ ╈ ╉ ╊ ╋ ╌ ╍ ╎ ╏
* ═ ║ ╒ ╓ ╔ ╕ ╖ ╗ ╘ ╙ ╚ ╛ ╜ ╝ ╞ ╟
* ╠ ╡ ╢ ╣ ╤ ╥ ╦ ╧ ╨ ╩ ╪ ╫ ╬ ╭ ╮ ╯
* ╰ ╱ ╲ ╳ ╴ ╵ ╶ ╷ ╸ ╹ ╺ ╻ ╼ ╽ ╾ ╿
*
* ---
*
* Box drawing alignment tests: █
* ▉
* ╔══╦══╗ ┌──┬──┐ ╭──┬──╮ ╭──┬──╮ ┏━━┳━━┓ ┎┒┏┑ ╷ ╻ ┏┯┓ ┌┰┐ ▊ ╱╲╱╲╳╳╳
* ║┌─╨─┐║ │╔═╧═╗│ │╒═╪═╕│ │╓─╁─╖│ ┃┌─╂─┐┃ ┗╃╄┙ ╶┼╴╺╋╸┠┼┨ ┝╋┥ ▋ ╲╱╲╱╳╳╳
* ║│╲ ╱│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╿ │┃ ┍╅╆┓ ╵ ╹ ┗┷┛ └┸┘ ▌ ╱╲╱╲╳╳╳
* ╠╡ ╳ ╞╣ ├╢ ╟┤ ├┼─┼─┼┤ ├╫─╂─╫┤ ┣┿╾┼╼┿┫ ┕┛┖┚ ┌┄┄┐ ╎ ┏┅┅┓ ┋ ▍ ╲╱╲╱╳╳╳
* ║│╱ ╲│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╽ │┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▎
* ║└─╥─┘║ │╚═╤═╝│ │╘═╪═╛│ │╙─╀─╜│ ┃└─╂─┘┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▏
* ╚══╩══╝ └──┴──┘ ╰──┴──╯ ╰──┴──╯ ┗━━┻━━┛ └╌╌┘ ╎ ┗╍╍┛ ┋ ▁▂▃▄▅▆▇█
*
* Source: https://www.w3.org/2001/06/utf-8-test/UTF-8-demo.html
*/
function drawBoxDrawingChar(
ctx: CanvasRenderingContext2D,
charDefinition: { [fontWeight: number]: string | ((xp: number, yp: number) => string) },
xOffset: number,
yOffset: number,
deviceCellWidth: number,
deviceCellHeight: number,
devicePixelRatio: number
): void {
ctx.strokeStyle = ctx.fillStyle;
for (const [fontWeight, instructions] of Object.entries(charDefinition)) {
ctx.beginPath();
ctx.lineWidth = devicePixelRatio * Number.parseInt(fontWeight);
let actualInstructions: string;
if (typeof instructions === 'function') {
const xp = .15;
const yp = .15 / deviceCellHeight * deviceCellWidth;
actualInstructions = instructions(xp, yp);
} else {
actualInstructions = instructions;
}
for (const instruction of actualInstructions.split(' ')) {
const type = instruction[0];
const f = svgToCanvasInstructionMap[type];
if (!f) {
console.error(`Could not find drawing instructions for "${type}"`);
continue;
}
const args: string[] = instruction.substring(1).split(',');
if (!args[0] || !args[1]) {
continue;
}
f(ctx, translateArgs(args, deviceCellWidth, deviceCellHeight, xOffset, yOffset, true, devicePixelRatio));
}
ctx.stroke();
ctx.closePath();
}
}
function drawPowerlineChar(
ctx: CanvasRenderingContext2D,
charDefinition: IVectorShape,
xOffset: number,
yOffset: number,
deviceCellWidth: number,
deviceCellHeight: number,
fontSize: number,
devicePixelRatio: number
): void {
// Clip the cell to make sure drawing doesn't occur beyond bounds
const clipRegion = new Path2D();
clipRegion.rect(xOffset, yOffset, deviceCellWidth, deviceCellHeight);
ctx.clip(clipRegion);
ctx.beginPath();
// Scale the stroke with DPR and font size
const cssLineWidth = fontSize / 12;
ctx.lineWidth = devicePixelRatio * cssLineWidth;
for (const instruction of charDefinition.d.split(' ')) {
const type = instruction[0];
const f = svgToCanvasInstructionMap[type];
if (!f) {
console.error(`Could not find drawing instructions for "${type}"`);
continue;
}
const args: string[] = instruction.substring(1).split(',');
if (!args[0] || !args[1]) {
continue;
}
f(ctx, translateArgs(
args,
deviceCellWidth,
deviceCellHeight,
xOffset,
yOffset,
false,
devicePixelRatio,
(charDefinition.leftPadding ?? 0) * (cssLineWidth / 2),
(charDefinition.rightPadding ?? 0) * (cssLineWidth / 2)
));
}
if (charDefinition.type === VectorType.STROKE) {
ctx.strokeStyle = ctx.fillStyle;
ctx.stroke();
} else {
ctx.fill();
}
ctx.closePath();
}
function clamp(value: number, max: number, min: number = 0): number {
return Math.max(Math.min(value, max), min);
}
const svgToCanvasInstructionMap: { [index: string]: any } = {
'C': (ctx: CanvasRenderingContext2D, args: number[]) => ctx.bezierCurveTo(args[0], args[1], args[2], args[3], args[4], args[5]),
'L': (ctx: CanvasRenderingContext2D, args: number[]) => ctx.lineTo(args[0], args[1]),
'M': (ctx: CanvasRenderingContext2D, args: number[]) => ctx.moveTo(args[0], args[1])
};
function translateArgs(args: string[], cellWidth: number, cellHeight: number, xOffset: number, yOffset: number, doClamp: boolean, devicePixelRatio: number, leftPadding: number = 0, rightPadding: number = 0): number[] {
const result = args.map(e => parseFloat(e) || parseInt(e));
if (result.length < 2) {
throw new Error('Too few arguments for instruction');
}
for (let x = 0; x < result.length; x += 2) {
// Translate from 0-1 to 0-cellWidth
result[x] *= cellWidth - (leftPadding * devicePixelRatio) - (rightPadding * devicePixelRatio);
// Ensure coordinate doesn't escape cell bounds and round to the nearest 0.5 to ensure a crisp
// line at 100% devicePixelRatio
if (doClamp && result[x] !== 0) {
result[x] = clamp(Math.round(result[x] + 0.5) - 0.5, cellWidth, 0);
}
// Apply the cell's offset (ie. x*cellWidth)
result[x] += xOffset + (leftPadding * devicePixelRatio);
}
for (let y = 1; y < result.length; y += 2) {
// Translate from 0-1 to 0-cellHeight
result[y] *= cellHeight;
// Ensure coordinate doesn't escape cell bounds and round to the nearest 0.5 to ensure a crisp
// line at 100% devicePixelRatio
if (doClamp && result[y] !== 0) {
result[y] = clamp(Math.round(result[y] + 0.5) - 0.5, cellHeight, 0);
}
// Apply the cell's offset (ie. x*cellHeight)
result[y] += yOffset;
}
return result;
}
+2 -2
View File
@@ -318,8 +318,8 @@ export class GlyphRenderer extends Disposable {
public handleResize(): void {
const gl = this._gl;
gl.useProgram(this._program);
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
gl.uniform2f(this._resolutionLocation, gl.canvas.width, gl.canvas.height);
gl.viewport(0, 0, this._dimensions.device.canvas.width, this._dimensions.device.canvas.height);
gl.uniform2f(this._resolutionLocation, this._dimensions.device.canvas.width, this._dimensions.device.canvas.height);
this.clear();
}
+63 -51
View File
@@ -5,7 +5,7 @@
import { IColorContrastCache } from 'browser/Types';
import { DIM_OPACITY, TEXT_BASELINE } from './Constants';
import { tryDrawCustomChar } from './CustomGlyphs';
import { loadCustomGlyphDefinitions, tryDrawCustomGlyph } from './customGlyphs/CustomGlyphRasterizer';
import { computeNextVariantOffset, treatGlyphAsBackgroundColor, isPowerlineGlyph, isRestrictedPowerlineGlyph, throwIfFalsy } from 'browser/renderer/shared/RendererUtils';
import { IBoundingBox, ICharAtlasConfig, IRasterizedGlyph, ITextureAtlas } from './Types';
import { NULL_COLOR, channels, color, rgba } from 'common/Color';
@@ -100,6 +100,10 @@ export class TextureAtlas implements ITextureAtlas {
alpha: this._config.allowTransparency,
willReadFrequently: true
}));
// Start loading custom glyph definitions asynchronously if custom glyphs are enabled
if (this._config.customGlyphs !== false) {
loadCustomGlyphDefinitions();
}
}
public dispose(): void {
@@ -514,7 +518,7 @@ export class TextureAtlas implements ITextureAtlas {
// Draw custom characters if applicable
let customGlyph = false;
if (this._config.customGlyphs !== false) {
customGlyph = tryDrawCustomChar(this._tmpCtx, chars, padding, padding, this._config.deviceCellWidth, this._config.deviceCellHeight, this._config.fontSize, this._config.devicePixelRatio);
customGlyph = tryDrawCustomGlyph(this._tmpCtx, chars, padding, padding, this._config.deviceCellWidth, this._config.deviceCellHeight, this._config.deviceCharWidth, this._config.deviceCharHeight, this._config.fontSize, this._config.devicePixelRatio, backgroundColor.css);
}
// Whether to clear pixels based on a threshold difference between the glyph color and the
@@ -551,61 +555,67 @@ export class TextureAtlas implements ITextureAtlas {
}
this._tmpCtx.strokeStyle = this._getColorFromAnsiIndex(fg).css;
}
this._tmpCtx.fillStyle = this._tmpCtx.strokeStyle;
// Underline style/stroke
this._tmpCtx.beginPath();
const xLeft = padding;
const yTop = Math.ceil(padding + this._config.deviceCharHeight) - yOffset - (restrictToCellHeight ? lineWidth * 2 : 0);
const yMid = yTop + lineWidth;
const yBot = yTop + lineWidth * 2;
const yTopDefault = Math.ceil(padding + this._config.deviceCharHeight) - yOffset - (restrictToCellHeight ? lineWidth * 2 : 0);
const yBotDefault = yTopDefault + lineWidth * 2;
let nextOffset = this._workAttributeData.getUnderlineVariantOffset();
let yTop = 0;
let yBot = 0;
for (let i = 0; i < chWidth; i++) {
let wasFilled = false;
this._tmpCtx.save();
yTop = yTopDefault;
yBot = yBotDefault;
const xChLeft = xLeft + i * this._config.deviceCellWidth;
const xChRight = xLeft + (i + 1) * this._config.deviceCellWidth;
const xChMid = xChLeft + this._config.deviceCellWidth / 2;
switch (this._workAttributeData.extended.underlineStyle) {
case UnderlineStyle.DOUBLE:
this._tmpCtx.moveTo(xChLeft, yTop);
this._tmpCtx.lineTo(xChRight, yTop);
this._tmpCtx.moveTo(xChLeft, yBot);
this._tmpCtx.lineTo(xChRight, yBot);
this._tmpCtx.moveTo(xChLeft, yTopDefault);
this._tmpCtx.lineTo(xChRight, yTopDefault);
this._tmpCtx.moveTo(xChLeft, yBotDefault);
this._tmpCtx.lineTo(xChRight, yBotDefault);
break;
case UnderlineStyle.CURLY:
// Choose the bezier top and bottom based on the device pixel ratio, the curly line is
// made taller when the line width is as otherwise it's not very clear otherwise.
const yCurlyBot = lineWidth <= 1 ? yBot : Math.ceil(padding + this._config.deviceCharHeight - lineWidth / 2) - yOffset;
const yCurlyTop = lineWidth <= 1 ? yTop : Math.ceil(padding + this._config.deviceCharHeight + lineWidth / 2) - yOffset;
// Clip the left and right edges of the underline such that it can be drawn just outside
// the edge of the cell to ensure a continuous stroke when there are multiple underlined
// glyphs adjacent to one another.
yTop = this._config.deviceCharHeight + 1;
yBot = yTop + 3 * this._config.devicePixelRatio;
const clipRegion = new Path2D();
clipRegion.rect(xChLeft, yTop, this._config.deviceCellWidth, yBot - yTop);
this._tmpCtx.clip(clipRegion);
// Start 1/2 cell before and end 1/2 cells after to ensure a smooth curve with other
// cells
this._tmpCtx.moveTo(xChLeft - this._config.deviceCellWidth / 2, yMid);
this._tmpCtx.bezierCurveTo(
xChLeft - this._config.deviceCellWidth / 2, yCurlyTop,
xChLeft, yCurlyTop,
xChLeft, yMid
);
this._tmpCtx.bezierCurveTo(
xChLeft, yCurlyBot,
xChMid, yCurlyBot,
xChMid, yMid
);
this._tmpCtx.bezierCurveTo(
xChMid, yCurlyTop,
xChRight, yCurlyTop,
xChRight, yMid
);
this._tmpCtx.bezierCurveTo(
xChRight, yCurlyBot,
xChRight + this._config.deviceCellWidth / 2, yCurlyBot,
xChRight + this._config.deviceCellWidth / 2, yMid
);
// Draw a zigzag pattern, this is derived from the SVG used in monaco for the same
// style. The viewbox is 6x3 so scale it using that.
const cellW = this._config.deviceCellWidth;
const curlyH = (yBot - yTop);
const scaleX = cellW / 6;
const scaleY = curlyH / 3;
const polygons: number[][] = [
[0, 2, 1, 3, 2.4, 3, 0, 0.6],
[5.5, 0, 2.5, 3, 1.1, 3, 4.1, 0],
[4, 0, 6, 2, 6, 0.6, 5.4, 0],
];
for (const polygon of polygons) {
this._tmpCtx.beginPath();
for (let i = 0; i < polygon.length; i += 2) {
const x = xChLeft + polygon[i] * scaleX;
const y = yBot - polygon[i + 1] * scaleY;
if (i === 0) {
this._tmpCtx.moveTo(x, y);
} else {
this._tmpCtx.lineTo(x, y);
}
}
this._tmpCtx.closePath();
this._tmpCtx.fill();
}
wasFilled = true;
break;
case UnderlineStyle.DOTTED:
const offsetWidth = nextOffset === 0 ? 0 :
@@ -614,14 +624,14 @@ export class TextureAtlas implements ITextureAtlas {
const isLineStart = nextOffset >= lineWidth ? false : true;
if (isLineStart === false || offsetWidth === 0) {
this._tmpCtx.setLineDash([Math.round(lineWidth), Math.round(lineWidth)]);
this._tmpCtx.moveTo(xChLeft + offsetWidth, yTop);
this._tmpCtx.lineTo(xChRight, yTop);
this._tmpCtx.moveTo(xChLeft + offsetWidth, yTopDefault);
this._tmpCtx.lineTo(xChRight, yTopDefault);
} else {
this._tmpCtx.setLineDash([Math.round(lineWidth), Math.round(lineWidth)]);
this._tmpCtx.moveTo(xChLeft, yTop);
this._tmpCtx.lineTo(xChLeft + offsetWidth, yTop);
this._tmpCtx.moveTo(xChLeft + offsetWidth + lineWidth, yTop);
this._tmpCtx.lineTo(xChRight, yTop);
this._tmpCtx.moveTo(xChLeft, yTopDefault);
this._tmpCtx.lineTo(xChLeft + offsetWidth, yTopDefault);
this._tmpCtx.moveTo(xChLeft + offsetWidth + lineWidth, yTopDefault);
this._tmpCtx.lineTo(xChRight, yTopDefault);
}
nextOffset = computeNextVariantOffset(xChRight - xChLeft, lineWidth, nextOffset);
break;
@@ -634,16 +644,18 @@ export class TextureAtlas implements ITextureAtlas {
const gap = Math.floor(gapRatio * xChWidth);
const end = xChWidth - line - gap;
this._tmpCtx.setLineDash([line, gap, end]);
this._tmpCtx.moveTo(xChLeft, yTop);
this._tmpCtx.lineTo(xChRight, yTop);
this._tmpCtx.moveTo(xChLeft, yTopDefault);
this._tmpCtx.lineTo(xChRight, yTopDefault);
break;
case UnderlineStyle.SINGLE:
default:
this._tmpCtx.moveTo(xChLeft, yTop);
this._tmpCtx.lineTo(xChRight, yTop);
this._tmpCtx.moveTo(xChLeft, yTopDefault);
this._tmpCtx.lineTo(xChRight, yTopDefault);
break;
}
this._tmpCtx.stroke();
if (!wasFilled) {
this._tmpCtx.stroke();
}
this._tmpCtx.restore();
}
this._tmpCtx.restore();
+8 -4
View File
@@ -4,7 +4,7 @@
*/
import type { ITerminalAddon, Terminal } from '@xterm/xterm';
import type { WebglAddon as IWebglApi } from '@xterm/addon-webgl';
import type { IWebglAddonOptions, WebglAddon as IWebglApi } from '@xterm/addon-webgl';
import { ICharacterJoinerService, ICharSizeService, ICoreBrowserService, IRenderService, IThemeService } from 'browser/services/Services';
import { ITerminal } from 'browser/Types';
import { Disposable, toDisposable } from 'vs/base/common/lifecycle';
@@ -28,9 +28,10 @@ export class WebglAddon extends Disposable implements ITerminalAddon , IWebglApi
private readonly _onContextLoss = this._register(new Emitter<void>());
public readonly onContextLoss = this._onContextLoss.event;
constructor(
private _preserveDrawingBuffer?: boolean
) {
private readonly _customGlyphs: boolean;
private readonly _preserveDrawingBuffer?: boolean;
constructor(options?: IWebglAddonOptions) {
if (isSafari && getSafariVersion() < 16) {
// Perform an extra check to determine if Webgl2 is manually enabled in developer settings
const contextAttributes = {
@@ -44,6 +45,8 @@ export class WebglAddon extends Disposable implements ITerminalAddon , IWebglApi
}
}
super();
this._customGlyphs = options?.customGlyphs ?? true;
this._preserveDrawingBuffer = options?.preserveDrawingBuffer;
}
public activate(terminal: Terminal): void {
@@ -79,6 +82,7 @@ export class WebglAddon extends Disposable implements ITerminalAddon , IWebglApi
decorationService,
optionsService,
themeService,
this._customGlyphs,
this._preserveDrawingBuffer
));
this._register(Event.forward(this._renderer.onContextLoss, this._onContextLoss));
+10 -2
View File
@@ -72,6 +72,7 @@ export class WebglRenderer extends Disposable implements IRenderer {
private readonly _decorationService: IDecorationService,
private readonly _optionsService: IOptionsService,
private readonly _themeService: IThemeService,
private readonly _customGlyphs: boolean = true,
preserveDrawingBuffer?: boolean
) {
super();
@@ -135,6 +136,8 @@ export class WebglRenderer extends Disposable implements IRenderer {
this._observerDisposable.value = observeDevicePixelDimensions(this._canvas, w, (w, h) => this._setCanvasDevicePixelDimensions(w, h));
}));
this._register(addDisposableListener(this._coreBrowserService.mainDocument, 'mousedown', () => this._cursorBlinkStateManager.value?.restartBlinkAnimation()));
this._core.screenElement!.appendChild(this._canvas);
[this._rectangleRenderer.value, this._glyphRenderer.value] = this._initializeWebGLState();
@@ -201,6 +204,9 @@ export class WebglRenderer extends Disposable implements IRenderer {
// Force a full refresh. Resizing `_glyphRenderer` should clear it already,
// so there is no need to clear it again here.
this._clearModel(false);
// Render synchronously to avoid flicker when the canvas is cleared
this._onRequestRedraw.fire({ start: 0, end: this._terminal.rows - 1, sync: true });
}
public handleCharSizeChanged(): void {
@@ -278,7 +284,8 @@ export class WebglRenderer extends Disposable implements IRenderer {
this.dimensions.device.char.width,
this.dimensions.device.char.height,
this._coreBrowserService.dpr,
this._deviceMaxTextureSize
this._deviceMaxTextureSize,
this._customGlyphs
);
if (this._charAtlas !== atlas) {
this._onChangeTextureAtlas.fire(atlas.pages[0].canvas);
@@ -615,7 +622,8 @@ export class WebglRenderer extends Disposable implements IRenderer {
// the change as it's an exact multiple of the cell sizes.
this._canvas.width = width;
this._canvas.height = height;
this._requestRedrawViewport();
// Render synchronously to avoid flicker when the canvas is cleared
this._onRequestRedraw.fire({ start: 0, end: this._terminal.rows - 1, sync: true });
}
private _requestRedrawViewport(): void {
File diff suppressed because one or more lines are too long
@@ -0,0 +1,755 @@
/**
* Copyright (c) 2021 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { throwIfFalsy } from 'browser/renderer/shared/RendererUtils';
import { CustomGlyphDefinitionType, CustomGlyphScaleType, CustomGlyphVectorType, type CustomGlyphCharacterDefinition, type CustomGlyphDefinitionPart, type CustomGlyphPathDrawFunctionDefinition, type CustomGlyphPatternDefinition, type ICustomGlyphSolidOctantBlockVector, type ICustomGlyphVectorShape } from './Types';
/**
* Cached custom glyph definitions. This is loaded dynamically to support code splitting.
*/
let customGlyphDefinitions: { [index: string]: CustomGlyphCharacterDefinition | undefined } | undefined;
/**
* Promise that resolves when custom glyph definitions are loaded.
*/
let loadingPromise: Promise<void> | undefined;
/**
* Begins loading the custom glyph definitions. This should be called as early as possible
* to ensure the definitions are ready when needed.
* @returns A promise that resolves when the definitions are loaded.
*/
export function loadCustomGlyphDefinitions(): Promise<void> {
if (customGlyphDefinitions) {
return Promise.resolve();
}
if (!loadingPromise) {
loadingPromise = import('./CustomGlyphDefinitions').then(module => {
customGlyphDefinitions = module.customGlyphDefinitions;
}).catch(err => {
// Reset the loading promise on failure to allow retry
loadingPromise = undefined;
throw err;
});
}
return loadingPromise;
}
/**
* Try drawing a custom block element or box drawing character, returning whether it was
* successfully drawn.
*/
export function tryDrawCustomGlyph(
ctx: CanvasRenderingContext2D,
c: string,
xOffset: number,
yOffset: number,
deviceCellWidth: number,
deviceCellHeight: number,
deviceCharWidth: number,
deviceCharHeight: number,
fontSize: number,
devicePixelRatio: number,
backgroundColor?: string
): boolean {
// If definitions are not loaded yet, return false to fall back to font rendering
if (!customGlyphDefinitions) {
return false;
}
const unifiedCharDefinition = customGlyphDefinitions[c];
if (unifiedCharDefinition) {
// Normalize to array for uniform handling
const parts = Array.isArray(unifiedCharDefinition) ? unifiedCharDefinition : [unifiedCharDefinition];
for (const part of parts) {
drawDefinitionPart(ctx, part, xOffset, yOffset, deviceCellWidth, deviceCellHeight, deviceCharWidth, deviceCharHeight, fontSize, devicePixelRatio, backgroundColor);
}
return true;
}
return false;
}
function drawDefinitionPart(
ctx: CanvasRenderingContext2D,
part: CustomGlyphDefinitionPart,
xOffset: number,
yOffset: number,
deviceCellWidth: number,
deviceCellHeight: number,
deviceCharWidth: number,
deviceCharHeight: number,
fontSize: number,
devicePixelRatio: number,
backgroundColor?: string
): void {
// Handle scaleType - adjust dimensions and offset when scaling to character area
let drawWidth = deviceCellWidth;
let drawHeight = deviceCellHeight;
let drawXOffset = xOffset;
let drawYOffset = yOffset;
if (part.scaleType === CustomGlyphScaleType.CHAR) {
drawWidth = deviceCharWidth;
drawHeight = deviceCharHeight;
// Center the character within the cell
drawXOffset = xOffset + (deviceCellWidth - deviceCharWidth) / 2;
drawYOffset = yOffset + (deviceCellHeight - deviceCharHeight) / 2;
}
// Handle clipPath generically for any definition type
if (part.clipPath) {
ctx.save();
applyClipPath(ctx, part.clipPath, drawXOffset, drawYOffset, drawWidth, drawHeight);
}
switch (part.type) {
case CustomGlyphDefinitionType.SOLID_OCTANT_BLOCK_VECTOR:
drawBlockVectorChar(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight);
break;
case CustomGlyphDefinitionType.BLOCK_PATTERN:
drawPatternChar(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight);
break;
case CustomGlyphDefinitionType.PATH_FUNCTION:
drawPathFunctionCharacter(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight, devicePixelRatio, part.strokeWidth);
break;
case CustomGlyphDefinitionType.PATH:
drawPathDefinitionCharacter(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight, devicePixelRatio, part.strokeWidth);
break;
case CustomGlyphDefinitionType.PATH_NEGATIVE:
drawPathNegativeDefinitionCharacter(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight, devicePixelRatio, backgroundColor);
break;
case CustomGlyphDefinitionType.VECTOR_SHAPE:
drawVectorShape(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight, fontSize, devicePixelRatio);
break;
case CustomGlyphDefinitionType.BRAILLE:
drawBrailleCharacter(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight);
break;
}
if (part.clipPath) {
ctx.restore();
}
}
function drawBlockVectorChar(
ctx: CanvasRenderingContext2D,
charDefinition: ICustomGlyphSolidOctantBlockVector[],
xOffset: number,
yOffset: number,
deviceCellWidth: number,
deviceCellHeight: number
): void {
for (let i = 0; i < charDefinition.length; i++) {
const box = charDefinition[i];
const xEighth = deviceCellWidth / 8;
const yEighth = deviceCellHeight / 8;
ctx.fillRect(
xOffset + box.x * xEighth,
yOffset + box.y * yEighth,
box.w * xEighth,
box.h * yEighth
);
}
}
/**
* Braille dot positions in octant coordinates (x, y for center of each dot area)
* Columns: left=1-2, right=5-6 (leaving 0 and 7 as margins, 3-4 as gap)
* Rows: 0-1, 2-3, 4-5, 6-7 for the 4 rows
*/
const brailleDotPositions = new Uint8Array([
1, 0, // dot 1 - bit 0
1, 2, // dot 2 - bit 1
1, 4, // dot 3 - bit 2
5, 0, // dot 4 - bit 3
5, 2, // dot 5 - bit 4
5, 4, // dot 6 - bit 5
1, 6, // dot 7 - bit 6
5, 6, // dot 8 - bit 7
]);
/**
* Draws a braille pattern
*/
function drawBrailleCharacter(
ctx: CanvasRenderingContext2D,
pattern: number,
xOffset: number,
yOffset: number,
deviceCellWidth: number,
deviceCellHeight: number
): void {
const xEighth = deviceCellWidth / 8;
const paddingY = deviceCellHeight * 0.1;
const usableHeight = deviceCellHeight * 0.8;
const yEighth = usableHeight / 8;
const radius = Math.min(xEighth, yEighth);
for (let bit = 0; bit < 8; bit++) {
if (pattern & (1 << bit)) {
const x = brailleDotPositions[bit * 2];
const y = brailleDotPositions[bit * 2 + 1];
const cx = xOffset + (x + 1) * xEighth;
const cy = yOffset + paddingY + (y + 1) * yEighth;
ctx.beginPath();
ctx.arc(cx, cy, radius, 0, Math.PI * 2);
ctx.fill();
}
}
}
function drawPathDefinitionCharacter(
ctx: CanvasRenderingContext2D,
charDefinition: CustomGlyphPathDrawFunctionDefinition | string,
xOffset: number,
yOffset: number,
deviceCellWidth: number,
deviceCellHeight: number,
devicePixelRatio: number,
strokeWidth?: number
): void {
const instructions = typeof charDefinition === 'string' ? charDefinition : charDefinition(0, 0);
ctx.beginPath();
let currentX = 0;
let currentY = 0;
let lastControlX = 0;
let lastControlY = 0;
let lastCommand = '';
for (const instruction of instructions.split(' ')) {
const type = instruction[0];
const args: string[] = instruction.substring(1).split(',');
if (type === 'Z') {
ctx.closePath();
lastCommand = type;
continue;
}
if (type === 'V') {
const y = yOffset + parseFloat(args[0]) * deviceCellHeight;
ctx.lineTo(currentX, y);
currentY = y;
lastControlX = currentX;
lastControlY = currentY;
lastCommand = type;
continue;
}
if (type === 'H') {
const x = xOffset + parseFloat(args[0]) * deviceCellWidth;
ctx.lineTo(x, currentY);
currentX = x;
lastControlX = currentX;
lastControlY = currentY;
lastCommand = type;
continue;
}
if (!args[0] || !args[1]) {
continue;
}
if (type === 'A') {
// SVG arc: A rx,ry,xAxisRotation,largeArcFlag,sweepFlag,x,y
const rx = parseFloat(args[0]) * deviceCellWidth;
const ry = parseFloat(args[1]) * deviceCellHeight;
const xAxisRotation = parseFloat(args[2]) * Math.PI / 180;
const largeArcFlag = parseInt(args[3]);
const sweepFlag = parseInt(args[4]);
const x = xOffset + parseFloat(args[5]) * deviceCellWidth;
const y = yOffset + parseFloat(args[6]) * deviceCellHeight;
drawSvgArc(ctx, currentX, currentY, rx, ry, xAxisRotation, largeArcFlag, sweepFlag, x, y);
currentX = x;
currentY = y;
continue;
}
const translatedArgs = args.map((e, i) => {
const val = parseFloat(e);
return i % 2 === 0
? xOffset + val * deviceCellWidth
: yOffset + val * deviceCellHeight;
});
if (type === 'M') {
ctx.moveTo(translatedArgs[0], translatedArgs[1]);
currentX = translatedArgs[0];
currentY = translatedArgs[1];
lastControlX = currentX;
lastControlY = currentY;
} else if (type === 'L') {
ctx.lineTo(translatedArgs[0], translatedArgs[1]);
currentX = translatedArgs[0];
currentY = translatedArgs[1];
lastControlX = currentX;
lastControlY = currentY;
} else if (type === 'Q') {
ctx.quadraticCurveTo(translatedArgs[0], translatedArgs[1], translatedArgs[2], translatedArgs[3]);
lastControlX = translatedArgs[0];
lastControlY = translatedArgs[1];
currentX = translatedArgs[2];
currentY = translatedArgs[3];
} else if (type === 'T') {
// T uses reflection of last control point if previous command was Q or T
let cpX: number;
let cpY: number;
if (lastCommand === 'Q' || lastCommand === 'T') {
cpX = 2 * currentX - lastControlX;
cpY = 2 * currentY - lastControlY;
} else {
cpX = currentX;
cpY = currentY;
}
ctx.quadraticCurveTo(cpX, cpY, translatedArgs[0], translatedArgs[1]);
lastControlX = cpX;
lastControlY = cpY;
currentX = translatedArgs[0];
currentY = translatedArgs[1];
} else if (type === 'C') {
ctx.bezierCurveTo(translatedArgs[0], translatedArgs[1], translatedArgs[2], translatedArgs[3], translatedArgs[4], translatedArgs[5]);
lastControlX = translatedArgs[2];
lastControlY = translatedArgs[3];
currentX = translatedArgs[4];
currentY = translatedArgs[5];
}
lastCommand = type;
}
if (strokeWidth !== undefined) {
ctx.strokeStyle = ctx.fillStyle;
ctx.lineWidth = devicePixelRatio * strokeWidth;
ctx.stroke();
} else {
ctx.fill();
}
}
/**
* Converts SVG arc parameters to canvas arc/ellipse calls.
* Based on the SVG spec's endpoint to center parameterization conversion.
*/
function drawSvgArc(
ctx: CanvasRenderingContext2D,
x1: number, y1: number,
rx: number, ry: number,
phi: number,
largeArcFlag: number,
sweepFlag: number,
x2: number, y2: number
): void {
// Handle degenerate cases
if (rx === 0 || ry === 0) {
ctx.lineTo(x2, y2);
return;
}
rx = Math.abs(rx);
ry = Math.abs(ry);
const cosPhi = Math.cos(phi);
const sinPhi = Math.sin(phi);
// Step 1: Compute (x1', y1')
const dx = (x1 - x2) / 2;
const dy = (y1 - y2) / 2;
const x1p = cosPhi * dx + sinPhi * dy;
const y1p = -sinPhi * dx + cosPhi * dy;
// Step 2: Compute (cx', cy')
let rxSq = rx * rx;
let rySq = ry * ry;
const x1pSq = x1p * x1p;
const y1pSq = y1p * y1p;
// Correct radii if necessary
const lambda = x1pSq / rxSq + y1pSq / rySq;
if (lambda > 1) {
const lambdaSqrt = Math.sqrt(lambda);
rx *= lambdaSqrt;
ry *= lambdaSqrt;
rxSq = rx * rx;
rySq = ry * ry;
}
let sq = (rxSq * rySq - rxSq * y1pSq - rySq * x1pSq) / (rxSq * y1pSq + rySq * x1pSq);
if (sq < 0) sq = 0;
const coef = (largeArcFlag === sweepFlag ? -1 : 1) * Math.sqrt(sq);
const cxp = coef * (rx * y1p / ry);
const cyp = coef * -(ry * x1p / rx);
// Step 3: Compute (cx, cy) from (cx', cy')
const cx = cosPhi * cxp - sinPhi * cyp + (x1 + x2) / 2;
const cy = sinPhi * cxp + cosPhi * cyp + (y1 + y2) / 2;
// Step 4: Compute angles
const ux = (x1p - cxp) / rx;
const uy = (y1p - cyp) / ry;
const vx = (-x1p - cxp) / rx;
const vy = (-y1p - cyp) / ry;
const startAngle = Math.atan2(uy, ux);
let dTheta = Math.atan2(vy, vx) - startAngle;
if (sweepFlag === 0 && dTheta > 0) {
dTheta -= 2 * Math.PI;
} else if (sweepFlag === 1 && dTheta < 0) {
dTheta += 2 * Math.PI;
}
const endAngle = startAngle + dTheta;
ctx.ellipse(cx, cy, rx, ry, phi, startAngle, endAngle, sweepFlag === 0);
}
/**
* Draws a "negative" path where the background color is used to draw the shape on top of a
* foreground-filled cell. This creates the appearance of a cutout without using actual
* transparency, which allows SPAA (subpixel anti-aliasing) to work correctly.
*
* @param ctx The canvas rendering context (fillStyle should be set to foreground color)
* @param charDefinition The vector shape definition for the negative shape
* @param xOffset The x offset to draw at
* @param yOffset The y offset to draw at
* @param deviceCellWidth The width of the cell in device pixels
* @param deviceCellHeight The height of the cell in device pixels
* @param devicePixelRatio The device pixel ratio
* @param backgroundColor The background color to use for the "cutout" portion
*/
function drawPathNegativeDefinitionCharacter(
ctx: CanvasRenderingContext2D,
charDefinition: ICustomGlyphVectorShape,
xOffset: number,
yOffset: number,
deviceCellWidth: number,
deviceCellHeight: number,
devicePixelRatio: number,
backgroundColor?: string
): void {
ctx.save();
// First, fill the entire cell with foreground color
ctx.fillRect(xOffset, yOffset, deviceCellWidth, deviceCellHeight);
// Then draw the "negative" shape with the background color
if (backgroundColor) {
ctx.fillStyle = backgroundColor;
ctx.strokeStyle = backgroundColor;
}
ctx.lineWidth = devicePixelRatio;
ctx.lineCap = 'square';
ctx.beginPath();
for (const instruction of charDefinition.d.split(' ')) {
const type = instruction[0];
const args: string[] = instruction.substring(1).split(',');
if (!args[0] || !args[1]) {
if (type === 'Z') {
ctx.closePath();
}
continue;
}
const translatedArgs = args.map((e, i) => {
const val = parseFloat(e);
return i % 2 === 0
? xOffset + val * deviceCellWidth
: yOffset + val * deviceCellHeight;
});
if (type === 'M') {
ctx.moveTo(translatedArgs[0], translatedArgs[1]);
} else if (type === 'L') {
ctx.lineTo(translatedArgs[0], translatedArgs[1]);
}
}
if (charDefinition.type === CustomGlyphVectorType.STROKE) {
ctx.stroke();
} else {
ctx.fill();
}
ctx.restore();
}
const cachedPatterns: Map<CustomGlyphPatternDefinition, Map</* fillStyle */string, CanvasPattern>> = new Map();
function drawPatternChar(
ctx: CanvasRenderingContext2D,
charDefinition: number[][],
xOffset: number,
yOffset: number,
deviceCellWidth: number,
deviceCellHeight: number
): void {
let patternSet = cachedPatterns.get(charDefinition);
if (!patternSet) {
patternSet = new Map();
cachedPatterns.set(charDefinition, patternSet);
}
const fillStyle = ctx.fillStyle;
if (typeof fillStyle !== 'string') {
throw new Error(`Unexpected fillStyle type "${fillStyle}"`);
}
let pattern = patternSet.get(fillStyle);
if (!pattern) {
const width = charDefinition[0].length;
const height = charDefinition.length;
const tmpCanvas = ctx.canvas.ownerDocument.createElement('canvas');
tmpCanvas.width = width;
tmpCanvas.height = height;
const tmpCtx = throwIfFalsy(tmpCanvas.getContext('2d'));
const imageData = new ImageData(width, height);
// Extract rgba from fillStyle
let r: number;
let g: number;
let b: number;
let a: number;
if (fillStyle.startsWith('#')) {
r = parseInt(fillStyle.slice(1, 3), 16);
g = parseInt(fillStyle.slice(3, 5), 16);
b = parseInt(fillStyle.slice(5, 7), 16);
a = fillStyle.length > 7 && parseInt(fillStyle.slice(7, 9), 16) || 1;
} else if (fillStyle.startsWith('rgba')) {
([r, g, b, a] = fillStyle.substring(5, fillStyle.length - 1).split(',').map(e => parseFloat(e)));
} else {
throw new Error(`Unexpected fillStyle color format "${fillStyle}" when drawing pattern glyph`);
}
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
imageData.data[(y * width + x) * 4 ] = r;
imageData.data[(y * width + x) * 4 + 1] = g;
imageData.data[(y * width + x) * 4 + 2] = b;
imageData.data[(y * width + x) * 4 + 3] = charDefinition[y][x] * (a * 255);
}
}
tmpCtx.putImageData(imageData, 0, 0);
pattern = throwIfFalsy(ctx.createPattern(tmpCanvas, null));
patternSet.set(fillStyle, pattern);
}
ctx.fillStyle = pattern;
ctx.fillRect(xOffset, yOffset, deviceCellWidth, deviceCellHeight);
}
function drawPathFunctionCharacter(
ctx: CanvasRenderingContext2D,
charDefinition: string | ((xp: number, yp: number) => string),
xOffset: number,
yOffset: number,
deviceCellWidth: number,
deviceCellHeight: number,
devicePixelRatio: number,
strokeWidth?: number
): void {
ctx.beginPath();
let actualInstructions: string;
if (typeof charDefinition === 'function') {
const xp = .15;
const yp = .15 / deviceCellHeight * deviceCellWidth;
actualInstructions = charDefinition(xp, yp);
} else {
actualInstructions = charDefinition;
}
const state: ISvgPathState = { currentX: 0, currentY: 0, lastControlX: 0, lastControlY: 0, lastCommand: '' };
for (const instruction of actualInstructions.split(' ')) {
const type = instruction[0];
if (type === 'Z') {
ctx.closePath();
state.lastCommand = type;
continue;
}
const f = svgToCanvasInstructionMap[type];
if (!f) {
console.error(`Could not find drawing instructions for "${type}"`);
continue;
}
const args: string[] = instruction.substring(1).split(',');
if (!args[0] || !args[1]) {
continue;
}
f(ctx, translateArgs(args, deviceCellWidth, deviceCellHeight, xOffset, yOffset, true, devicePixelRatio), state);
state.lastCommand = type;
}
if (strokeWidth !== undefined) {
ctx.strokeStyle = ctx.fillStyle;
ctx.lineWidth = devicePixelRatio * strokeWidth;
ctx.stroke();
} else {
ctx.fill();
}
ctx.closePath();
}
/**
* Applies a clip path to the canvas context from SVG-like path instructions.
*/
function applyClipPath(
ctx: CanvasRenderingContext2D,
clipPath: string,
xOffset: number,
yOffset: number,
deviceCellWidth: number,
deviceCellHeight: number
): void {
ctx.beginPath();
for (const instruction of clipPath.split(' ')) {
const type = instruction[0];
if (type === 'Z') {
ctx.closePath();
continue;
}
const args: string[] = instruction.substring(1).split(',');
if (!args[0] || !args[1]) {
continue;
}
const x = xOffset + parseFloat(args[0]) * deviceCellWidth;
const y = yOffset + parseFloat(args[1]) * deviceCellHeight;
if (type === 'M') {
ctx.moveTo(x, y);
} else if (type === 'L') {
ctx.lineTo(x, y);
}
}
ctx.clip();
}
function drawVectorShape(
ctx: CanvasRenderingContext2D,
charDefinition: ICustomGlyphVectorShape,
xOffset: number,
yOffset: number,
deviceCellWidth: number,
deviceCellHeight: number,
fontSize: number,
devicePixelRatio: number
): void {
// Clip the cell to make sure drawing doesn't occur beyond bounds
const clipRegion = new Path2D();
clipRegion.rect(xOffset, yOffset, deviceCellWidth, deviceCellHeight);
ctx.clip(clipRegion);
ctx.beginPath();
// Scale the stroke with DPR and font size
const cssLineWidth = fontSize / 12;
ctx.lineWidth = devicePixelRatio * cssLineWidth;
const state: ISvgPathState = { currentX: 0, currentY: 0, lastControlX: 0, lastControlY: 0, lastCommand: '' };
for (const instruction of charDefinition.d.split(' ')) {
const type = instruction[0];
if (type === 'Z') {
ctx.closePath();
state.lastCommand = type;
continue;
}
const f = svgToCanvasInstructionMap[type];
if (!f) {
console.error(`Could not find drawing instructions for "${type}"`);
continue;
}
const args: string[] = instruction.substring(1).split(',');
if (!args[0] || !args[1]) {
continue;
}
f(ctx, translateArgs(
args,
deviceCellWidth,
deviceCellHeight,
xOffset,
yOffset,
false,
devicePixelRatio,
(charDefinition.leftPadding ?? 0) * (cssLineWidth / 2),
(charDefinition.rightPadding ?? 0) * (cssLineWidth / 2)
), state);
state.lastCommand = type;
}
if (charDefinition.type === CustomGlyphVectorType.STROKE) {
ctx.strokeStyle = ctx.fillStyle;
ctx.stroke();
} else {
ctx.fill();
}
ctx.closePath();
}
function clamp(value: number, max: number, min: number = 0): number {
return Math.max(Math.min(value, max), min);
}
interface ISvgPathState {
currentX: number;
currentY: number;
lastControlX: number;
lastControlY: number;
lastCommand: string;
}
const svgToCanvasInstructionMap: { [index: string]: (ctx: CanvasRenderingContext2D, args: number[], state: ISvgPathState) => void } = {
'C': (ctx, args, state) => {
ctx.bezierCurveTo(args[0], args[1], args[2], args[3], args[4], args[5]);
state.lastControlX = args[2];
state.lastControlY = args[3];
state.currentX = args[4];
state.currentY = args[5];
},
'L': (ctx, args, state) => {
ctx.lineTo(args[0], args[1]);
state.lastControlX = state.currentX = args[0];
state.lastControlY = state.currentY = args[1];
},
'M': (ctx, args, state) => {
ctx.moveTo(args[0], args[1]);
state.lastControlX = state.currentX = args[0];
state.lastControlY = state.currentY = args[1];
},
'Q': (ctx, args, state) => {
ctx.quadraticCurveTo(args[0], args[1], args[2], args[3]);
state.lastControlX = args[0];
state.lastControlY = args[1];
state.currentX = args[2];
state.currentY = args[3];
},
'T': (ctx, args, state) => {
let cpX: number;
let cpY: number;
if (state.lastCommand === 'Q' || state.lastCommand === 'T') {
cpX = 2 * state.currentX - state.lastControlX;
cpY = 2 * state.currentY - state.lastControlY;
} else {
cpX = state.currentX;
cpY = state.currentY;
}
ctx.quadraticCurveTo(cpX, cpY, args[0], args[1]);
state.lastControlX = cpX;
state.lastControlY = cpY;
state.currentX = args[0];
state.currentY = args[1];
}
};
function translateArgs(args: string[], cellWidth: number, cellHeight: number, xOffset: number, yOffset: number, doClamp: boolean, devicePixelRatio: number, leftPadding: number = 0, rightPadding: number = 0): number[] {
const result = args.map(e => parseFloat(e) || parseInt(e));
if (result.length < 2) {
throw new Error('Too few arguments for instruction');
}
for (let x = 0; x < result.length; x += 2) {
// Translate from 0-1 to 0-cellWidth
result[x] *= cellWidth - (leftPadding * devicePixelRatio) - (rightPadding * devicePixelRatio);
// Ensure coordinate doesn't escape cell bounds and round to the nearest 0.5 to ensure a crisp
// line at 100% devicePixelRatio
if (doClamp && result[x] !== 0) {
result[x] = clamp(Math.round(result[x] + 0.5) - 0.5, cellWidth, 0);
}
// Apply the cell's offset (ie. x*cellWidth)
result[x] += xOffset + (leftPadding * devicePixelRatio);
}
for (let y = 1; y < result.length; y += 2) {
// Translate from 0-1 to 0-cellHeight
result[y] *= cellHeight;
// Ensure coordinate doesn't escape cell bounds and round to the nearest 0.5 to ensure a crisp
// line at 100% devicePixelRatio
if (doClamp && result[y] !== 0) {
result[y] = clamp(Math.round(result[y] + 0.5) - 0.5, cellHeight, 0);
}
// Apply the cell's offset (ie. x*cellHeight)
result[y] += yOffset;
}
return result;
}
@@ -0,0 +1,85 @@
/**
* Copyright (c) 2021 The xterm.js authors. All rights reserved.
* @license MIT
*/
export interface ICustomGlyphSolidOctantBlockVector {
x: number;
y: number;
w: number;
h: number;
}
/**
* @param xp The percentage of 15% of the x axis.
* @param yp The percentage of 15% of the x axis on the y axis.
*/
export type CustomGlyphPathDrawFunctionDefinition = (xp: number, yp: number) => string;
export interface ICustomGlyphVectorShape {
d: string;
type: CustomGlyphVectorType;
leftPadding?: number;
rightPadding?: number;
}
export const enum CustomGlyphVectorType {
FILL,
STROKE
}
export type CustomGlyphPatternDefinition = number[][];
export const enum CustomGlyphDefinitionType {
SOLID_OCTANT_BLOCK_VECTOR,
BLOCK_PATTERN,
PATH_FUNCTION,
PATH,
PATH_NEGATIVE,
VECTOR_SHAPE,
BRAILLE,
}
export type CustomGlyphDefinitionPartRaw = (
{ type: CustomGlyphDefinitionType.SOLID_OCTANT_BLOCK_VECTOR, data: ICustomGlyphSolidOctantBlockVector[] } |
{ type: CustomGlyphDefinitionType.BLOCK_PATTERN, data: CustomGlyphPatternDefinition } |
{ type: CustomGlyphDefinitionType.PATH_FUNCTION, data: CustomGlyphPathDrawFunctionDefinition | string } |
{ type: CustomGlyphDefinitionType.PATH, data: string } |
{ type: CustomGlyphDefinitionType.PATH_NEGATIVE, data: ICustomGlyphVectorShape } |
{ type: CustomGlyphDefinitionType.VECTOR_SHAPE, data: ICustomGlyphVectorShape} |
{ type: CustomGlyphDefinitionType.BRAILLE, data: number }
);
export const enum CustomGlyphScaleType {
/**
* Scale to the entire cell, including letter spacing and line height.
*/
CELL,
/**
* Scale to only the character area, excluding letter spacing and line height.
*/
CHAR,
}
export interface ICustomGlyphDefinitionCommon {
/**
* A custom clip path for the draw definition, restricting the area it can draw to.
*/
clipPath?: string;
/**
* The stroke width to use when drawing the path. Defaults to 1.
*/
strokeWidth?: number;
/**
* Defines how to scale the draw. Defaults to scaling to the full cell including letter spacing
* and line height.
*/
scaleType?: CustomGlyphScaleType;
}
export type CustomGlyphDefinitionPart = CustomGlyphDefinitionPartRaw & ICustomGlyphDefinitionCommon;
/**
* A character definition that can be a single part or an array of parts drawn in sequence.
*/
export type CustomGlyphCharacterDefinition = CustomGlyphDefinitionPart | CustomGlyphDefinitionPart[];
+31 -1
View File
@@ -32,7 +32,7 @@ declare module '@xterm/addon-webgl' {
*/
public readonly onRemoveTextureAtlasCanvas: IEvent<HTMLCanvasElement>;
constructor(preserveDrawingBuffer?: boolean);
constructor(options?: IWebglAddonOptions);
/**
* Activates the addon.
@@ -50,4 +50,34 @@ declare module '@xterm/addon-webgl' {
*/
public clearTextureAtlas(): void;
}
export interface IWebglAddonOptions {
/**
* Whether to draw custom glyphs instead of using the font for the following
* unicode ranges:
*
* - Box Drawing (U+2500-U+257F)
* - Block Elements (U+2580-U+259F)
* - Braille Patterns (U+2800-U+28FF)
* - Powerline Symbols (U+E0A0-U+E0D4, Private Use Area with widespread
* adoption)
* - Progress Indicators (U+EE00-U+EE0B, Private Use Area initially added in
* [Fira Code](https://github.com/tonsky/FiraCode) and later
* [Nerd Fonts](https://github.com/ryanoasis/nerd-fonts/pull/1733)).
* - Git Branch Symbols (U+F5D0-U+F60D, Private Use Area initially adopted
* in [Kitty in 2024](https://github.com/kovidgoyal/kitty/pull/7681) by
* author of [vim-flog](https://github.com/rbong/vim-flog))
* - Symbols for Legacy Computing (U+1FB00-U+1FBFF)
*
* This will typically result in better rendering with continuous lines,
* even when line height and letter spacing is used. The default is true.
*/
customGlyphs?: boolean;
/**
* Whether to enable the preserveDrawingBuffer flag when creating the WebGL
* context. This may be useful in tests. This default is false.
*/
preserveDrawingBuffer?: boolean
}
}
+457
View File
@@ -0,0 +1,457 @@
/**
* Converts an SVG file as exported by fontforge into the SVG-like format as expected by the custom
* glyph rasterizer.
*
* Usage: node convert_svg_to_custom_glyph.js <svg-file-or-folder>
*/
const fs = require('fs');
const path = require('path');
const input = process.argv[2];
if (!input) {
console.error('Usage: node convert_svg_to_custom_glyph.js <svg-file-or-folder>');
process.exit(1);
}
const inputPath = path.resolve(process.cwd(), input);
const stat = fs.statSync(inputPath);
const files = stat.isDirectory()
? fs.readdirSync(inputPath).filter(f => f.endsWith('.svg')).map(f => path.join(inputPath, f))
: [inputPath];
if (files.length === 0) {
console.error('No SVG files found');
process.exit(1);
}
for (const file of files) {
console.log(`\n${'='.repeat(60)}\nProcessing: ${path.basename(file)}\n${'='.repeat(60)}`);
processFile(file);
}
function processFile(filePath) {
// Get file content
const content = fs.readFileSync(filePath, 'utf8');
// Get viewBox
const viewBoxMatch = content.match(/viewBox="([^"]+)"/);
if (!viewBoxMatch) {
console.error('No viewBox found in SVG');
return;
}
const [minX, minY, width, height] = viewBoxMatch[1].split(/\s+/).map(Number);
console.log(`ViewBox: ${minX} ${minY} ${width} ${height}`);
// Get path `d` property
const pathMatch = content.match(/<path[^>]*\sd="([^"]+)"/);
if (!pathMatch) {
console.error('No path d attribute found in SVG');
return;
}
const originalPath = pathMatch[1].replace(/\s+/g, ' ').trim();
console.log(`\nOriginal path length: ${originalPath.length} chars`);
// Parse path into commands
function parsePath(d) {
const commands = [];
const regex = /([MmLlHhVvCcSsQqTtAaZz])([^MmLlHhVvCcSsQqTtAaZz]*)/g;
let match;
while ((match = regex.exec(d)) !== null) {
const cmd = match[1];
const argsStr = match[2].trim();
const args = argsStr ? argsStr.split(/[\s,]+/).map(Number) : [];
commands.push({ cmd, args });
}
return commands;
}
// Convert relative commands to absolute and expand T/S to Q/C
function toAbsolute(commands) {
const result = [];
let x = 0, y = 0; // Current position
let startX = 0, startY = 0; // Start of current subpath
let lastControlX = 0, lastControlY = 0; // Last control point for T/S
let lastCmd = '';
for (const { cmd, args } of commands) {
const isRelative = cmd === cmd.toLowerCase();
const absCmd = cmd.toUpperCase();
switch (absCmd) {
case 'M': {
// MoveTo: M x y (or m dx dy)
const absArgs = [];
for (let i = 0; i < args.length; i += 2) {
const newX = isRelative ? x + args[i] : args[i];
const newY = isRelative ? y + args[i + 1] : args[i + 1];
absArgs.push(newX, newY);
x = newX;
y = newY;
if (i === 0) {
startX = x;
startY = y;
}
}
lastControlX = x;
lastControlY = y;
result.push({ cmd: 'M', args: absArgs });
break;
}
case 'L': {
// LineTo: L x y (or l dx dy)
const absArgs = [];
for (let i = 0; i < args.length; i += 2) {
const newX = isRelative ? x + args[i] : args[i];
const newY = isRelative ? y + args[i + 1] : args[i + 1];
absArgs.push(newX, newY);
x = newX;
y = newY;
}
lastControlX = x;
lastControlY = y;
result.push({ cmd: 'L', args: absArgs });
break;
}
case 'H': {
// Horizontal LineTo - convert to L
for (let i = 0; i < args.length; i++) {
const newX = isRelative ? x + args[i] : args[i];
result.push({ cmd: 'L', args: [newX, y] });
x = newX;
}
lastControlX = x;
lastControlY = y;
break;
}
case 'V': {
// Vertical LineTo - convert to L
for (let i = 0; i < args.length; i++) {
const newY = isRelative ? y + args[i] : args[i];
result.push({ cmd: 'L', args: [x, newY] });
y = newY;
}
lastControlX = x;
lastControlY = y;
break;
}
case 'C': {
// CurveTo: C x1 y1 x2 y2 x y (or c dx1 dy1 dx2 dy2 dx dy)
const absArgs = [];
for (let i = 0; i < args.length; i += 6) {
const x1 = isRelative ? x + args[i] : args[i];
const y1 = isRelative ? y + args[i + 1] : args[i + 1];
const x2 = isRelative ? x + args[i + 2] : args[i + 2];
const y2 = isRelative ? y + args[i + 3] : args[i + 3];
const newX = isRelative ? x + args[i + 4] : args[i + 4];
const newY = isRelative ? y + args[i + 5] : args[i + 5];
absArgs.push(x1, y1, x2, y2, newX, newY);
lastControlX = x2;
lastControlY = y2;
x = newX;
y = newY;
}
result.push({ cmd: 'C', args: absArgs });
break;
}
case 'S': {
// Smooth CurveTo - expand to C
for (let i = 0; i < args.length; i += 4) {
// Reflect last control point
let x1, y1;
if (lastCmd === 'C' || lastCmd === 'S') {
x1 = 2 * x - lastControlX;
y1 = 2 * y - lastControlY;
} else {
x1 = x;
y1 = y;
}
const x2 = isRelative ? x + args[i] : args[i];
const y2 = isRelative ? y + args[i + 1] : args[i + 1];
const newX = isRelative ? x + args[i + 2] : args[i + 2];
const newY = isRelative ? y + args[i + 3] : args[i + 3];
result.push({ cmd: 'C', args: [x1, y1, x2, y2, newX, newY] });
lastControlX = x2;
lastControlY = y2;
x = newX;
y = newY;
}
break;
}
case 'Q': {
// Quadratic CurveTo: Q x1 y1 x y (or q dx1 dy1 dx dy)
const absArgs = [];
for (let i = 0; i < args.length; i += 4) {
const x1 = isRelative ? x + args[i] : args[i];
const y1 = isRelative ? y + args[i + 1] : args[i + 1];
const newX = isRelative ? x + args[i + 2] : args[i + 2];
const newY = isRelative ? y + args[i + 3] : args[i + 3];
absArgs.push(x1, y1, newX, newY);
lastControlX = x1;
lastControlY = y1;
x = newX;
y = newY;
}
result.push({ cmd: 'Q', args: absArgs });
break;
}
case 'T': {
// Smooth Quadratic CurveTo - keep as T
const absArgs = [];
for (let i = 0; i < args.length; i += 2) {
// Reflect last control point for tracking
let cpX, cpY;
if (lastCmd === 'Q' || lastCmd === 'T') {
cpX = 2 * x - lastControlX;
cpY = 2 * y - lastControlY;
} else {
cpX = x;
cpY = y;
}
const newX = isRelative ? x + args[i] : args[i];
const newY = isRelative ? y + args[i + 1] : args[i + 1];
absArgs.push(newX, newY);
lastControlX = cpX;
lastControlY = cpY;
x = newX;
y = newY;
lastCmd = 'T'; // For chained T commands
}
result.push({ cmd: 'T', args: absArgs });
break;
}
case 'A': {
// Arc: A rx ry x-axis-rotation large-arc-flag sweep-flag x y
const absArgs = [];
for (let i = 0; i < args.length; i += 7) {
const rx = args[i];
const ry = args[i + 1];
const rotation = args[i + 2];
const largeArc = args[i + 3];
const sweep = args[i + 4];
const newX = isRelative ? x + args[i + 5] : args[i + 5];
const newY = isRelative ? y + args[i + 6] : args[i + 6];
absArgs.push(rx, ry, rotation, largeArc, sweep, newX, newY);
x = newX;
y = newY;
}
lastControlX = x;
lastControlY = y;
result.push({ cmd: 'A', args: absArgs });
break;
}
case 'Z': {
// ClosePath
x = startX;
y = startY;
lastControlX = x;
lastControlY = y;
result.push({ cmd: 'Z', args: [] });
break;
}
}
if (absCmd !== 'T') {
lastCmd = absCmd;
}
}
return result;
}
// Scale coordinates to 0-1 range
function scaleToNormalized(commands, minX, minY, width, height) {
function scaleX(val) {
return (val - minX) / width;
}
function scaleY(val) {
return (val - minY) / height;
}
function scaleRx(val) {
return val / width;
}
function scaleRy(val) {
return val / height;
}
const result = [];
for (const { cmd, args } of commands) {
const scaledArgs = [];
switch (cmd) {
case 'M':
case 'L':
case 'T': {
for (let i = 0; i < args.length; i += 2) {
scaledArgs.push(scaleX(args[i]), scaleY(args[i + 1]));
}
break;
}
case 'H': {
for (let i = 0; i < args.length; i++) {
scaledArgs.push(scaleX(args[i]));
}
break;
}
case 'V': {
for (let i = 0; i < args.length; i++) {
scaledArgs.push(scaleY(args[i]));
}
break;
}
case 'C': {
for (let i = 0; i < args.length; i += 6) {
scaledArgs.push(
scaleX(args[i]), scaleY(args[i + 1]),
scaleX(args[i + 2]), scaleY(args[i + 3]),
scaleX(args[i + 4]), scaleY(args[i + 5])
);
}
break;
}
case 'S':
case 'Q': {
for (let i = 0; i < args.length; i += 4) {
scaledArgs.push(
scaleX(args[i]), scaleY(args[i + 1]),
scaleX(args[i + 2]), scaleY(args[i + 3])
);
}
break;
}
case 'A': {
for (let i = 0; i < args.length; i += 7) {
// rx, ry need to be scaled; rotation and flags stay the same
scaledArgs.push(
scaleRx(args[i]), // rx
scaleRy(args[i + 1]), // ry
args[i + 2], // rotation
args[i + 3], // large-arc
args[i + 4], // sweep
scaleX(args[i + 5]), // x
scaleY(args[i + 6]) // y
);
}
break;
}
case 'Z': {
// No args
break;
}
}
result.push({ cmd, args: scaledArgs });
}
return result;
}
// Format number to reasonable precision
function formatNum(n, precision = 4) {
const rounded = Number(n.toFixed(precision));
return String(rounded);
}
// Convert commands back to path string
function commandsToPath(commands) {
return commands.map(({ cmd, args }, i) => {
const prefix = i === 0 ? '' : ' ';
if (args.length === 0) return prefix + cmd;
return prefix + cmd + args.map(a => formatNum(a)).join(',');
}).join('');
}
// Main conversion
const parsed = parsePath(originalPath);
const absolute = toAbsolute(parsed);
// Calculate actual bounding box from path data
function getBoundingBox(commands) {
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
for (const { cmd, args } of commands) {
switch (cmd) {
case 'M':
case 'L':
case 'T': {
for (let i = 0; i < args.length; i += 2) {
minX = Math.min(minX, args[i]);
maxX = Math.max(maxX, args[i]);
minY = Math.min(minY, args[i + 1]);
maxY = Math.max(maxY, args[i + 1]);
}
break;
}
case 'H': {
for (let i = 0; i < args.length; i++) {
minX = Math.min(minX, args[i]);
maxX = Math.max(maxX, args[i]);
}
break;
}
case 'V': {
for (let i = 0; i < args.length; i++) {
minY = Math.min(minY, args[i]);
maxY = Math.max(maxY, args[i]);
}
break;
}
case 'C': {
for (let i = 0; i < args.length; i += 6) {
// Include control points and endpoint
minX = Math.min(minX, args[i], args[i + 2], args[i + 4]);
maxX = Math.max(maxX, args[i], args[i + 2], args[i + 4]);
minY = Math.min(minY, args[i + 1], args[i + 3], args[i + 5]);
maxY = Math.max(maxY, args[i + 1], args[i + 3], args[i + 5]);
}
break;
}
case 'S':
case 'Q': {
for (let i = 0; i < args.length; i += 4) {
minX = Math.min(minX, args[i], args[i + 2]);
maxX = Math.max(maxX, args[i], args[i + 2]);
minY = Math.min(minY, args[i + 1], args[i + 3]);
maxY = Math.max(maxY, args[i + 1], args[i + 3]);
}
break;
}
case 'A': {
for (let i = 0; i < args.length; i += 7) {
minX = Math.min(minX, args[i + 5]);
maxX = Math.max(maxX, args[i + 5]);
minY = Math.min(minY, args[i + 6]);
maxY = Math.max(maxY, args[i + 6]);
}
break;
}
}
}
return { minX, minY, width: maxX - minX, height: maxY - minY };
}
const bbox = getBoundingBox(absolute);
console.log(`Path bounding box: x=${bbox.minX}, y=${bbox.minY}, w=${bbox.width}, h=${bbox.height}`);
// Use viewBox for normalization (not path bounding box)
const normalized = scaleToNormalized(absolute, minX, minY, width, height);
const result = commandsToPath(normalized);
console.log(`\nConverted path (${result.length} chars):\n`);
console.log(result);
console.log(`\n\nFor CustomGlyphDefinitions.ts:\n`);
console.log(`'\\u{E0C0}': { type: CustomGlyphDefinitionType.VECTOR_SHAPE, data: { d: '${result}', type: CustomGlyphVectorType.FILL } },`);
// Write output file
const ext = path.extname(filePath);
const outputPath = filePath.replace(ext, `_output${ext}`);
const svgOutput = `<?xml version="1.0" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 1 1">
<path fill="currentColor" d="${result}" />
</svg>
`;
fs.writeFileSync(outputPath, svgOutput, 'utf8');
console.log(`\nOutput written to: ${outputPath}`);
}
+32 -6
View File
@@ -12,6 +12,7 @@ const config = {
isProd: argv.includes('--prod'),
isWatch: argv.includes('--watch'),
isDemoClient: argv.includes('--demo-client'),
isDemoServer: argv.includes('--demo-server'),
isHeadless: argv.includes('--headless'),
addon: argv.find(e => e.startsWith('--addon='))?.replace(/^--addon=/, ''),
};
@@ -25,7 +26,10 @@ const commonOptions = {
target: 'es2021',
sourcemap: true,
treeShaking: true,
logLevel: 'debug',
splitting: true,
chunkNames: 'chunks/[name]-[hash]',
logLevel: 'warning',
outExtension: { '.js': '.mjs' },
};
/** @type {esbuild.BuildOptions} */
@@ -102,7 +106,8 @@ if (config.addon) {
bundleConfig = {
...bundleConfig,
entryPoints: [`addons/addon-${config.addon}/src/${getAddonEntryPoint(config.addon)}.ts`],
outfile: `addons/addon-${config.addon}/lib/addon-${config.addon}.mjs`,
outdir: `addons/addon-${config.addon}/lib`,
entryNames: `addon-${config.addon}`,
};
outConfig = {
...outConfig,
@@ -126,8 +131,9 @@ if (config.addon) {
} else if (config.isDemoClient) {
bundleConfig = {
...bundleConfig,
entryPoints: [`demo/client.ts`],
outfile: 'demo/dist/client-bundle.js',
entryPoints: [`demo/client/client.ts`],
outdir: 'demo/dist',
entryNames: 'client-bundle',
external: ['util', 'os', 'fs', 'path', 'stream', 'Terminal'],
alias: {
// Library ESM imports
@@ -139,6 +145,7 @@ if (config.addon) {
"@xterm/addon-progress": "./addons/addon-progress/lib/addon-progress.mjs",
"@xterm/addon-search": "./addons/addon-search/lib/addon-search.mjs",
"@xterm/addon-serialize": "./addons/addon-serialize/lib/addon-serialize.mjs",
"@xterm/addon-web-fonts": "./addons/addon-web-fonts/lib/addon-web-fonts.mjs",
"@xterm/addon-web-links": "./addons/addon-web-links/lib/addon-web-links.mjs",
"@xterm/addon-webgl": "./addons/addon-webgl/lib/addon-webgl.mjs",
"@xterm/addon-unicode11": "./addons/addon-unicode11/lib/addon-unicode11.mjs",
@@ -152,11 +159,29 @@ if (config.addon) {
"@xterm/addon-ligatures": "./addons/addon-ligatures/out-esbuild/LigaturesAddon",
}
}
skipOut = true;
skipOutTest = true;
} else if (config.isDemoServer) {
bundleConfig = {
...bundleConfig,
entryPoints: [`demo/server/server.ts`],
outfile: 'demo/dist/server-bundle.js',
format: 'cjs',
platform: 'node',
external: ['node-pty'],
// Splitting is not compatible with cjs format
splitting: false,
// Override the .mjs extension from commonOptions
outExtension: {},
}
skipOut = true;
skipOutTest = true;
} else if (config.isHeadless) {
bundleConfig = {
...bundleConfig,
entryPoints: [`src/headless/public/Terminal.ts`],
outfile: `headless/lib-headless/xterm-headless.mjs`
outdir: `headless/lib-headless`,
entryNames: 'xterm-headless',
};
outConfig = {
...outConfig,
@@ -168,7 +193,8 @@ if (config.addon) {
bundleConfig = {
...bundleConfig,
entryPoints: [`src/browser/public/Terminal.ts`],
outfile: `lib/xterm.mjs`
outdir: `lib`,
entryNames: 'xterm',
};
outConfig = {
...outConfig,
+2 -2
View File
@@ -4,14 +4,14 @@ import { spawn } from "child_process";
import { readdir } from "fs/promises";
import { argv } from "process";
/** @type {{cp: import("child_process").ChildProcessByStdio, name: string}[]} */
/** @type {{cp: import("child_process").ChildProcessByStdio<any, any, any>, name: string}[]} */
const jobs = [];
// Core job
jobs.push(createJob('xterm', []));
// Addon jobs
const addons = (await readdir('addons')).map(e => e.replace('addon-', ''));
const addons = (await readdir('addons')).filter(e => e.startsWith('addon-')).map(e => e.replace('addon-', ''));
for (const addon of addons) {
jobs.push(createJob(`xterm-addon-${addon}`, [`--addon=${addon}`]));
}
+49
View File
@@ -0,0 +1,49 @@
/**
* Copyright (c) 2026 The xterm.js authors. All rights reserved.
* @license MIT
*/
// @ts-check
const { execSync, spawn } = require('child_process');
const path = require('path');
const extensions = ['.ts', '.mts'];
const fix = process.argv.includes('--fix');
// Get uncommitted changed files (staged + unstaged)
function getChangedFiles() {
try {
const output = execSync('git diff --name-only --diff-filter=ACMR HEAD', {
encoding: 'utf-8',
cwd: path.join(__dirname, '..')
});
return output.split('\n').filter(f => f && extensions.some(ext => f.endsWith(ext)));
} catch {
return [];
}
}
const files = getChangedFiles();
if (files.length === 0) {
console.log('No changed TypeScript files to lint.');
process.exit(0);
}
console.log(`Linting ${files.length} changed file(s)...`);
const eslintArgs = ['--max-warnings', '0', '--no-warn-ignored'];
if (fix) {
eslintArgs.push('--fix');
}
eslintArgs.push(...files);
const eslint = process.platform === 'win32' ? 'eslint.cmd' : 'eslint';
const child = spawn(eslint, eslintArgs, {
stdio: 'inherit',
cwd: path.join(__dirname, '..'),
shell: process.platform === 'win32'
});
child.on('close', code => process.exit(code ?? 0));
+15 -2
View File
@@ -30,7 +30,7 @@ const changedFiles = getChangedFilesInCommit('HEAD');
// Always publish xterm, technically this isn't needed if
// `changedFiles.some(e => e.search(/^addons\//)`, but it's here for convenience to get the right
// peer dependencies for addons.
const result = checkAndPublishPackage(path.resolve(__dirname, '..'), repoCommit);
const result = checkAndPublishPackage(path.resolve(__dirname, '..'), repoCommit, undefined, true);
const isStableRelease = result.isStableRelease;
const peerDependencies = result.nextVersion.includes('beta') ? {
'@xterm/xterm': `^${result.nextVersion}`,
@@ -51,6 +51,7 @@ const addonPackageDirs = [
path.resolve(__dirname, '../addons/addon-serialize'),
path.resolve(__dirname, '../addons/addon-unicode11'),
path.resolve(__dirname, '../addons/addon-unicode-graphemes'),
path.resolve(__dirname, '../addons/addon-web-fonts'),
path.resolve(__dirname, '../addons/addon-web-links'),
path.resolve(__dirname, '../addons/addon-webgl')
];
@@ -67,7 +68,7 @@ if (isStableRelease) {
updateWebsite();
}
function checkAndPublishPackage(packageDir, repoCommit, peerDependencies) {
function checkAndPublishPackage(packageDir, repoCommit, peerDependencies, updateVersionTs = false) {
const packageJson = require(path.join(packageDir, 'package.json'));
// Determine if this is a stable or beta release
@@ -78,6 +79,18 @@ function checkAndPublishPackage(packageDir, repoCommit, peerDependencies) {
let nextVersion = isStableRelease ? packageJson.version : getNextBetaVersion(packageJson);
log(`Publishing version: ${nextVersion}`, 'green');
// Update Version.ts with the new version
if (updateVersionTs) {
const versionTsPath = path.join(packageDir, 'src/common/Version.ts');
const versionTsContent = fs.readFileSync(versionTsPath, 'utf8');
const updatedVersionTs = versionTsContent.replace(
/export const XTERM_VERSION = '[^']+';/,
`export const XTERM_VERSION = '${nextVersion}';`
);
fs.writeFileSync(versionTsPath, updatedVersionTs);
log(`Updated ${versionTsPath} to version ${nextVersion}`);
}
// Set the version in package.json
const packageJsonFile = path.join(packageDir, 'package.json');
packageJson.version = nextVersion;
+1
View File
@@ -30,6 +30,7 @@ const addons = [
'serialize',
'unicode-graphemes',
'unicode11',
'web-fonts',
'web-links',
'webgl',
];

Some files were not shown because too many files have changed in this diff Show More