Compare commits

...
Author SHA1 Message Date
Daniel Imms ee2da690d9 Update ghostty submodule 2026-02-09 03:49:36 -08:00
Daniel Imms b4529f317b . 2026-02-08 20:18:30 -08:00
Daniel Imms e14746e6e9 Merge pull request #5682 from Tyriar/3440
Add attributesEqual and underline diff APIs
2026-02-07 06:37:19 -08:00
Daniel Imms 82333b9414 Remove unnecessary cast 2026-02-07 06:29:33 -08:00
Daniel Imms 9eeb2799c1 Remove internal details about underline cell APIs 2026-02-07 06:24:47 -08:00
Daniel Imms 5630471480 Merge pull request #5684 from Tyriar/5681
Make 0x1FB98 and 0x1FB99 perfectly tile
2026-02-07 06:24:05 -08:00
Daniel Imms e0c59e68b2 Make 0x1FB98 and 0x1FB99 perfectly tile
Fixes #5681
2026-02-07 06:12:47 -08:00
Daniel Imms cc8e680790 Add attributesEqual and underline diff APIs
Fixes #3440
2026-02-06 16:21:25 -08:00
Daniel Imms 452ee50c81 Merge pull request #5669 from Tyriar/custom_glyph_alignment
Use offset variants for some custom glyphs
2026-02-06 12:58:20 -08:00
Daniel Imms f41e53a0f0 Use correct non-inverse shade char in testWindow 2026-02-06 12:50:28 -08:00
Daniel Imms b287397c4f Merge pull request #5680 from Tyriar/5678
Move overviewRuler API under scrollbar
2026-02-05 09:29:16 -08:00
Daniel Imms aebbe81252 Add overviewRuler options to demo 2026-02-05 09:19:26 -08:00
Daniel Imms d155bb6767 Move overviewRuler API under scrollbar
Fixes #5678
2026-02-05 09:14:58 -08:00
Daniel Imms 3a147e8e10 Merge pull request #5679 from Tyriar/scrollbar
Add scrollbar.showScrollbar
2026-02-05 07:28:45 -08:00
Daniel Imms c2db7d4c8a Add scrollbar.showScrollbar
Fixes #5676
2026-02-05 07:20:23 -08:00
Daniel Imms 456bc73bae Merge pull request #5677 from Tyriar/log_task
Use ILogService in TaskQueue
2026-02-05 06:49:05 -08:00
Daniel Imms 2e776c0820 Use ILogService in TaskQueue 2026-02-05 06:40:50 -08:00
Daniel Imms 6f163beb97 Merge pull request #5674 from xtermjs/anthonykim1/addScreenElementAPI
Add api to expose screenElement
2026-02-04 04:40:37 -08:00
Daniel Imms b0d0bf8187 Update typings/xterm.d.ts 2026-02-04 04:32:37 -08:00
Anthony Kim 32e77c3b81 Lint 2026-02-03 23:24:57 -08:00
Anthony Kim cba6e3d191 Add api to expose screenElement 2026-02-03 15:49:07 -08:00
Daniel Imms 5741e450e6 Merge pull request #5665 from Tyriar/de_vs
Remove vs/ module
2026-02-03 07:14:08 -08:00
Daniel Imms 6ef653e589 Merge remote-tracking branch 'upstream/master' into de_vs 2026-02-03 07:05:50 -08:00
Daniel Imms a4c0e4690e Make arrows a little less fat 2026-02-03 07:00:33 -08:00
Daniel Imms a31f78bc8b Prefix all scrollbar classes with xterm- 2026-02-03 06:57:50 -08:00
Daniel Imms ca8e8546b5 Remove unused methods on scrollable element 2026-02-03 06:00:24 -08:00
Daniel Imms 3d473b52b6 Further merge and reduce
- Remove unused keyboardEvent module
- Trim unused browserEvent in OnStopCallback
- Inline single-use helpers to reduce module surface
- Remove createFastDomNode wrapper
2026-02-03 05:21:03 -08:00
Daniel Imms a2bec2aeab Merge pull request #5672 from Tyriar/blink_opt
Prevent blink interval from running unless needed
2026-02-03 05:15:45 -08:00
Daniel Imms 205cf6089d Prevent blink interval from running unless needed
Part of #944
2026-02-03 05:07:40 -08:00
Daniel Imms 8b0a6f9785 Enumerate all block pattern codepoints 2026-02-03 05:04:03 -08:00
Daniel Imms db0226be5c Add triangular shade chars fill tests 2026-02-03 04:59:10 -08:00
Daniel Imms ab5c06cf17 Merge abstract and smooth scrollable elements 2026-02-03 04:55:32 -08:00
Daniel Imms 9a778f0c98 Move back to CellColorResolver 2026-02-03 04:53:02 -08:00
Daniel Imms c102b4af50 Merge pull request #5671 from Tyriar/944
Implement blink rendering
2026-02-03 04:03:20 -08:00
Daniel Imms f3a7cac49f Handle options within blink state manager 2026-02-03 03:55:25 -08:00
Daniel Imms 0d2a58c9d0 Clean up lifecycle of blink manager 2026-02-03 03:48:28 -08:00
Daniel Imms 8a00898533 Implement blink rendering
Fixes #944
2026-02-03 03:46:21 -08:00
Daniel Imms edb0e1ceb3 Simplify, reduce
- Merge ScrollableElement into SmoothScrollableElement
- Prune unused helpers FastDomNode, Widget LinkedList
- Make internal exports non-exported
- Remove redundant guards/aliases
2026-02-03 03:42:19 -08:00
Daniel Imms 93c1650446 Move variant handling out of CellColorResolver.ts 2026-02-03 03:37:57 -08:00
Daniel Imms 77695cb405 Make arrows configurable via API 2026-02-02 12:33:33 -08:00
Daniel Imms dc4ebfd6e3 Use offset variants for some custom glyphs
Part of #5668
2026-02-02 08:07:04 -08:00
Daniel Imms fae6f03f90 Consolidate dom and browser helpers, remove unused 2026-02-02 07:09:33 -08:00
Daniel Imms d36af624cf Remove vs/, fix lint and build 2026-02-02 06:10:43 -08:00
Daniel Imms a105d3e457 Lint and remove more parts 2026-02-01 22:36:14 -08:00
Daniel Imms d5900c7eae Remove more parts 2026-02-01 22:22:29 -08:00
Daniel Imms beebe8b5dc Reduce size of scrollable impl 2026-02-01 21:28:18 -08:00
Daniel Imms 8f9045ed88 Merge pull request #5664 from Tyriar/renderer_tests_wsl
Get playwright tests reliably passing in wsl
2026-02-01 08:54:30 -08:00
Daniel Imms b8e5ec7304 Fix lint 2026-02-01 08:41:01 -08:00
Daniel Imms 6a3d2480e0 Get playwright tests reliably passing in wsl 2026-02-01 08:35:49 -08:00
Daniel Imms 735afde77f Merge pull request #5663 from Tyriar/image_demo
Move remaining addon test buttons into their own windows
2026-02-01 08:34:29 -08:00
Daniel Imms 53efc95170 Move remaining addon test buttons into their own windows 2026-02-01 08:26:20 -08:00
Daniel Imms 3512f140de Merge pull request #5658 from Tyriar/outline
Fix demo button outline
2026-02-01 08:23:59 -08:00
Daniel Imms dbe35428cb Merge pull request #5662 from Tyriar/any_fixes
Remove some easy any usages
2026-02-01 08:06:33 -08:00
Daniel Imms 297ac838a3 Fix build 2026-02-01 07:58:36 -08:00
Daniel Imms 5316cb0812 Remove some easy any usages 2026-02-01 07:48:40 -08:00
Daniel Imms c124550971 Merge pull request #5661 from Tyriar/iip
Fix copying array data in IIPHandler
2026-02-01 07:23:39 -08:00
Daniel Imms 6525a7e68e Fix copying array data in IIPHandler
Fixes #5660
2026-02-01 07:15:25 -08:00
Daniel Imms f666135881 Move all impl to scrollable/ 2026-02-01 06:25:12 -08:00
Daniel Imms b2133d93f0 Merge pull request #5659 from Tyriar/dead_code2
Remove unreachable code in SGR handling 100
2026-02-01 06:07:15 -08:00
Daniel Imms a5e4f90139 Remove unreachable code in SGR handling 100
The implementation seems to be wrong. This looks like a remnant left over from
term.js before bright SGR was implemented.
2026-02-01 05:59:00 -08:00
Daniel Imms a27b8feb8f Fix demo button outline 2026-01-31 22:56:48 -08:00
Daniel Imms eea03cf0a9 Use lightweight versions of most vs/ imports 2026-01-31 22:52:19 -08:00
Daniel Imms e96748cc79 Merge pull request #5657 from Tyriar/inst2
Correct test copilot instructions
2026-01-31 22:34:43 -08:00
Daniel Imms 334c8170fe Merge pull request #5654 from Tyriar/5612
win32 input mode: Avoid scrolling to bottom on modifier only
2026-01-31 22:34:02 -08:00
Daniel Imms 2bb9662bea Merge pull request #5656 from Tyriar/cancel
Remove cancelEvent/cancel function
2026-01-31 22:26:50 -08:00
Daniel Imms 7cba3c9fa1 Correct test copilot instructions 2026-01-31 22:26:06 -08:00
Daniel Imms bab7db13db Remove cancelEvent/cancel function 2026-01-31 22:18:32 -08:00
Daniel Imms 1c79c5511c Merge pull request #5653 from Tyriar/input_handler_tests
Add remaining input handler tests, unskip modes that don't change
2026-01-31 22:09:48 -08:00
Daniel Imms 7b417f4585 win32 input mode: Avoid scrolling to bottom on modifier only
Fixes #5612
2026-01-31 22:05:33 -08:00
Daniel Imms dc487dfd6f Assert no mode changes and unskip 2026-01-31 22:01:35 -08:00
Daniel Imms 36baf70bea Unskip supported InputHandler tests 2026-01-31 21:05:36 -08:00
Daniel Imms 87e0b9ab10 Merge pull request #5652 from Tyriar/lint_test
Enable linting on test/ folder
2026-01-31 21:04:36 -08:00
Daniel Imms 5e532c13c6 Enable linting on test/ folder 2026-01-31 20:57:51 -08:00
Daniel Imms db131e0c22 Merge pull request #5651 from Tyriar/ih_tests
Implement more InputHandler tests
2026-01-31 18:28:42 -08:00
Daniel Imms 51b9a713da Implement more InputHandler tests
Part of #2117
2026-01-31 18:21:32 -08:00
Daniel Imms 972c069fa3 Merge pull request #5650 from Tyriar/slow_tests_3
Speed up TextDecoder.test.ts
2026-01-31 16:48:31 -08:00
Daniel Imms 2c0ba3c058 Speed up TextDecoder.test.ts
- Reduce calls to decode and clear
- Consolidate numberic checks
- Increase batch size
2026-01-31 16:42:11 -08:00
Daniel Imms e515647f99 Merge pull request #5649 from Tyriar/promise
Clear dangling timeout that keeps unit tests event loop alive
2026-01-31 16:27:25 -08:00
Daniel Imms 7a2794a552 Clear dangling timeout that keeps unit tests event loop alive
This fixes the issue where test-unit could run for up to 5 seconds after
the tests have already finished.
2026-01-31 16:21:03 -08:00
Daniel Imms da2267a10f Merge pull request #5648 from Tyriar/slow_tests_2
Speed up all remaining unit tests below threshold (40ms?)
2026-01-31 16:09:46 -08:00
Daniel Imms 34e68b1ad4 Speed up all remaining unit tests below threshold (40ms?) 2026-01-31 15:50:51 -08:00
Daniel Imms 1c42957461 Merge pull request #5646 from Tyriar/slow_tests
Speed up slow payload limit parser tests
2026-01-31 15:40:10 -08:00
Daniel Imms 77036d3f12 Merge pull request #5647 from Tyriar/fix_benchmark
Fix benchmark usage, add instructions
2026-01-31 15:37:17 -08:00
Daniel Imms ccbf612ddb Fix lint 2026-01-31 15:33:49 -08:00
Daniel Imms eed8423030 Clarify runtime cases 2026-01-31 15:30:16 -08:00
Daniel Imms 431d511c95 Fix benchmark usage, add instructions 2026-01-31 15:28:11 -08:00
Daniel Imms 0ca1bd48be Inline payload limit 2026-01-31 15:21:48 -08:00
Daniel Imms 7ceb15bb83 Reduce payload size to speed up unit tests
Reduces 11s -> 8s for full run
2026-01-31 15:17:10 -08:00
Daniel Imms 5ecdc7da44 Make payload limit configurable by tests 2026-01-31 15:08:05 -08:00
Daniel Imms 2e2270d01f Merge pull request #5645 from Tyriar/events
Optimize Emitter.fire for 0 and 1 listeners
2026-01-31 14:51:01 -08:00
Daniel Imms 042bb4bed9 Optimize Emitter.fire for 0 and 1 listeners
Before:
      Context "Emitter.fire()"
         Context "0 listeners"
            Case "#1" : 1 runs - average throughput: 97.77 MB/s
         Context "1 listener"
            Case "#1" : 1 runs - average throughput: 49.30 MB/s
         Context "2 listeners"
            Case "#1" : 1 runs - average throughput: 35.37 MB/s
         Context "5 listeners"
            Case "#1" : 1 runs - average throughput: 15.32 MB/s

After:
      Context "Emitter.fire()"
         Context "0 listeners"
            Case "#1" : 1 runs - average throughput: 376.94 MB/s
         Context "1 listener"
            Case "#1" : 1 runs - average throughput: 84.29 MB/s
         Context "2 listeners"
            Case "#1" : 1 runs - average throughput: 32.36 MB/s
         Context "5 listeners"
            Case "#1" : 1 runs - average throughput: 15.93 MB/s
2026-01-31 14:42:23 -08:00
Daniel Imms 7e3c41ba49 Merge pull request #5643 from Tyriar/cacheWorkCell
Cache work cell in hot loops
2026-01-31 10:33:25 -08:00
Daniel Imms 21e4301e38 Merge pull request #5642 from Tyriar/startsWith
Prefer startsWith over indexOf === 0
2026-01-31 10:27:15 -08:00
Daniel Imms 3ef43aedb1 Cache work cell in hot loops 2026-01-31 10:26:15 -08:00
Daniel Imms 9eaf5b45dc Merge pull request #5641 from Tyriar/padStart
Use native padStart over custom impl
2026-01-31 10:25:24 -08:00
Daniel Imms 39037ee806 Prefer startsWith over indexOf === 0
Faster and make code clearer
2026-01-31 10:20:44 -08:00
Daniel Imms e542affaca Use native padStart over custom impl 2026-01-31 10:17:52 -08:00
Daniel Imms 038883c41b Merge pull request #5640 from Tyriar/strict_demo
Make demo use strict TS compiler mode
2026-01-31 09:32:36 -08:00
Daniel Imms 6c3d4e4ea4 Fix lint 2026-01-31 09:26:05 -08:00
Daniel Imms 659cfddd8c Merge branch 'master' into strict_demo 2026-01-31 09:24:47 -08:00
Daniel Imms c375696ee6 Make demo use strict TS compiler mode 2026-01-31 09:22:45 -08:00
Daniel Imms bc3c376e83 Merge pull request #5628 from Tyriar/5626
Support color scheme reporting
2026-01-31 09:18:33 -08:00
Daniel Imms 9fca3d8ecf Merge branch 'master' into 5626 2026-01-31 09:12:15 -08:00
Daniel Imms 8eed7b4163 Merge pull request #5639 from Tyriar/nullish
Add @typescript-eslint/prefer-nullish-coalescing eslint rule
2026-01-31 09:03:35 -08:00
Daniel Imms c29938ee83 Merge pull request #5634 from Tyriar/const_enum
Use const enum in EscapeSequences
2026-01-31 09:00:38 -08:00
Daniel Imms 0e679ea6ae Use nullish coalescing in KeyboardService 2026-01-31 08:56:53 -08:00
Daniel Imms d0e8141f7c Merge branch 'master' into nullish 2026-01-31 08:56:14 -08:00
Daniel Imms 1d322c9e45 Fix name to follow enum rules 2026-01-31 08:54:15 -08:00
Daniel Imms bad7e329df Add @typescript-eslint/prefer-nullish-coalescing eslint rule 2026-01-31 08:43:05 -08:00
Daniel Imms ae5e7e55c8 Merge pull request #5638 from Tyriar/tyriar/comma
Add @stylistic/comma-spacing eslint rule
2026-01-31 08:32:49 -08:00
Daniel Imms 5bb2e46508 Merge pull request #5630 from xtermjs/anthonykim1/updateNodePtyVersion
Update node-pty to ^1.2.0-beta.9
2026-01-31 08:31:09 -08:00
Daniel Imms 5938b8823d Add @stylistic/comma-spacing eslint rule 2026-01-31 07:38:16 -08:00
Daniel Imms 69d87c8a30 Merge pull request #5637 from Tyriar/remove_trace
Remove trace decorator and unused platform consts
2026-01-30 07:34:45 -08:00
Daniel Imms a247154650 Merge pull request #5636 from Tyriar/win32__kitty
Move kitty input mode into a class to avoid init cost
2026-01-30 07:29:42 -08:00
Daniel Imms b30d9c3533 Remove trace decorator and unused platform consts 2026-01-30 07:27:38 -08:00
Daniel Imms 60190c1c48 Merge branch 'master' into win32__kitty 2026-01-30 07:23:07 -08:00
Daniel Imms 99d69d2236 Merge pull request #5635 from Tyriar/win32
Move win32 input mode into a class to avoid init cost
2026-01-30 07:23:01 -08:00
Daniel Imms de01d4608c Move kitty input mode into a class to avoid init cost 2026-01-30 07:09:48 -08:00
Daniel Imms d35481c3f9 Move win32 input mode into a class to avoid init cost 2026-01-30 07:07:55 -08:00
Daniel Imms e2d84928b7 Merge pull request #5633 from Tyriar/dead_code
Remove unused TypedArrayUtils.ts
2026-01-30 07:00:49 -08:00
Daniel Imms 9ffd16aa9b Use const enum in EscapeSequences
They'll be inlined and only the used ones will show in bundle
2026-01-30 06:55:50 -08:00
Daniel Imms 77fa03d11c Remove unused TypedArrayUtils.ts 2026-01-30 06:53:02 -08:00
Daniel Imms 01450f044a Merge pull request #5632 from Tyriar/5631
Remove vs dependency in common
2026-01-30 06:39:28 -08:00
Daniel Imms b04d816d8a Undo changes to headless/package.json 2026-01-30 06:32:49 -08:00
Daniel Imms f80dbf3d03 Fix lint, split up namespace and interface 2026-01-30 06:21:15 -08:00
Daniel Imms b58bd452af Fix lint 2026-01-30 06:07:30 -08:00
Daniel Imms e8d99d50a6 Remove vs dependency in common
Fixes #5631
2026-01-30 06:03:16 -08:00
Anthony Kim b87cba4c2a Update node-pty to ^1.2.0-beta.9 2026-01-28 14:04:46 -08:00
Daniel Imms 6f87ae77a7 Support color scheme reporting
CSI ? 996 n
CSI ? 2031 h
CSI ? 2031 l

Fixes #5626
2026-01-27 10:19:26 -08:00
Daniel Imms 5f25e05cd2 Merge pull request #5625 from Tyriar/kitty_shift_disambiguate
Don't disambiguous kitty keyboard on shift only
2026-01-26 14:51:17 -08:00
Daniel Imms 2af9d10171 Don't disambiguous kitty keyboard on shift only
Part of microsoft/vscode#286809
2026-01-26 14:44:34 -08:00
Daniel Imms f471c0add8 Merge pull request #5624 from xtermjs/Tyriar-patch-1
Don't set windows input mode on demo
2026-01-26 13:19:09 -08:00
Daniel Imms 62dc0d9c51 Don't set windows input mode on demo 2026-01-26 13:12:37 -08:00
Daniel Imms 14525b334f Merge pull request #5618 from xtermjs/anthonykim1/lastState1
Add STATE_LENGTH to equal last state + 1
2026-01-23 04:10:06 -08:00
Anthony Kim 1ace108422 better comments 2026-01-22 10:54:41 -08:00
Anthony Kim 2c1441a52d Add STATE_LENGTH to equal last state + 1 2026-01-22 10:49:21 -08:00
Daniel Imms 8e67c0093c Merge pull request #5617 from xtermjs/anthonykim1/kittyGraphicsProtocol
Add register apc handler
2026-01-22 04:35:38 -08:00
Anthony Kim ee3b3626e8 Again, format 2026-01-21 16:27:19 -08:00
Anthony Kim b286f21f64 Add APC_STRING since DCS_PASSTHROUGH isnt the last in ParserState anymore 2026-01-21 15:50:51 -08:00
Anthony Kim 3d92a7e2ed Dont be silly with original formatting 2026-01-21 15:13:03 -08:00
Anthony Kim b01ba7db28 Add apc tests parser.test.ts 2026-01-21 14:17:01 -08:00
Anthony Kim 1c73006e39 Switch TransitionTable to Uint16Array 2026-01-21 13:41:29 -08:00
Anthony Kim 03b015d5d3 Add registerApcHandler to xterm-headless.d.ts 2026-01-21 11:45:21 -08:00
Anthony Kim 42d408a9a7 Change ordering in escapeSequnceParser.ts 2026-01-21 11:29:04 -08:00
Anthony Kim 5ecd980a83 Comment 2026-01-21 11:01:09 -08:00
Anthony Kim 63ebe2df5b Stop messing with existing formatting 2026-01-21 11:00:10 -08:00
Anthony Kim 1b2d361b59 Remove comment on Constant.ts for ApcState 2026-01-21 10:59:33 -08:00
Anthony Kim 8e29591b9f Add registerApcHandler to public api 2026-01-21 10:42:36 -08:00
Anthony Kim 48df6117ed Add ApcParser 2026-01-21 08:31:07 -08:00
Daniel Imms 14b6a71391 Merge pull request #5615 from Tyriar/5585
Fix stack overflow in webgl page merge logic
2026-01-19 04:07:10 -08:00
Daniel Imms c24eb60bd3 Fix stack overflow in merge logic
Fixes #5585
2026-01-18 15:45:19 -08:00
Daniel Imms 2521bab72f Merge pull request #5613 from Tyriar/tyriar/5611
Fix some control keys not sending correct sequences
2026-01-16 06:14:01 -08:00
Daniel Imms 0f1c9a47db Fix some control keys not sending correct sequences
Fixes #5611
2026-01-16 06:06:55 -08:00
277 changed files with 10793 additions and 22005 deletions
+2 -2
View File
@@ -22,10 +22,10 @@ npm run build && npm run esbuild # Build all TypeScript and bundle
**Testing**:
- Unit tests: `npm run test-unit` (Mocha)
- 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`
- 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)
- 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>`
- 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
@@ -0,0 +1,18 @@
---
applyTo: '**/*.benchmark.ts'
---
# Benchmark run instructions
- Full suite: `npm run benchmark`
- Single benchmark file:
- Tree: `npm run benchmark -- -t out-test/benchmark/Event.benchmark.js`
- Run file: `npm run benchmark -- -s "out-test/benchmark/Event.benchmark.js" out-test/benchmark/Event.benchmark.js`
- Single context/case:
- Use `-t` to get the path, then:
- `npm run benchmark -- -s "<path>" out-test/benchmark/Event.benchmark.js`
When writing instructions, use `RuntimeCase` to measure pure runtime in ms, use `ThroughputRuntimeCase` when measuring throughput in MB/s.
Notes:
- Benchmarks run from built JS in `out-test/benchmark/*.benchmark.js`.
- Keep `NODE_PATH=./out` (handled by the npm script).
+3
View File
@@ -0,0 +1,3 @@
[submodule "vendor/ghostty"]
path = vendor/ghostty
url = https://github.com/ghostty-org/ghostty
+1 -1
View File
@@ -12,7 +12,7 @@ interface IAttachOptions {
bidirectional?: boolean;
}
export class AttachAddon implements ITerminalAddon , IAttachApi {
export class AttachAddon implements ITerminalAddon, IAttachApi {
private _socket: WebSocket;
private _bidirectional: boolean;
private _disposables: IDisposable[] = [];
@@ -5,10 +5,9 @@ const config: PlaywrightTestConfig = {
timeout: 10000,
projects: [
{
name: 'ChromeStable',
name: 'Chromium',
use: {
browserName: 'chromium',
channel: 'chrome'
browserName: 'chromium'
}
},
{
@@ -5,10 +5,9 @@ const config: PlaywrightTestConfig = {
timeout: 10000,
projects: [
{
name: 'ChromeStable',
name: 'Chromium',
use: {
browserName: 'chromium',
channel: 'chrome'
browserName: 'chromium'
}
},
{
+4 -3
View File
@@ -33,7 +33,7 @@ function _getComputedStyle(el: HTMLElement): CSSStyleDeclaration {
return getWindow(el).getComputedStyle(el, null);
}
export class FitAddon implements ITerminalAddon , IFitApi {
export class FitAddon implements ITerminalAddon, IFitApi {
private _terminal: Terminal | undefined;
public activate(terminal: Terminal): void {
@@ -69,9 +69,10 @@ export class FitAddon implements ITerminalAddon , IFitApi {
return undefined;
}
const scrollbarWidth = (this._terminal.options.scrollback === 0
const showScrollbar = this._terminal.options.scrollbar?.showScrollbar ?? true;
const scrollbarWidth = (this._terminal.options.scrollback === 0 || !showScrollbar
? 0
: (this._terminal.options.overviewRuler?.width || ViewportConstants.DEFAULT_SCROLL_BAR_WIDTH));
: (this._terminal.options.scrollbar?.width ?? ViewportConstants.DEFAULT_SCROLL_BAR_WIDTH));
const parentElementStyle = _getComputedStyle(this._terminal.element.parentElement);
const parentElementHeight = parseInt(parentElementStyle.getPropertyValue('height'));
+2 -3
View File
@@ -5,10 +5,9 @@ const config: PlaywrightTestConfig = {
timeout: 10000,
projects: [
{
name: 'ChromeStable',
name: 'Chromium',
use: {
browserName: 'chromium',
channel: 'chrome'
browserName: 'chromium'
}
},
{
+2 -5
View File
@@ -9,10 +9,6 @@ import Base64Decoder from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';
import { HeaderParser, IHeaderFields, HeaderState } from './IIPHeaderParser';
import { imageType, UNSUPPORTED_TYPE } from './IIPMetrics';
// eslint-disable-next-line
declare const Buffer: any;
// limit hold memory in base64 decoder
const KEEP_DATA = 4194304;
@@ -105,7 +101,8 @@ export class IIPHandler implements IOscHandler, IResetHandler {
return true;
}
const blob = new Blob([new Uint8Array(this._dec.data8)], { type: this._metrics.mime });
// HACK: The types on Blob are too restrictive, this is a Uint8Array so the browser accepts it
const blob = new Blob([this._dec.data8 as Uint8Array<ArrayBuffer>], { type: this._metrics.mime });
this._dec.release();
if (!window.createImageBitmap) {
+3 -2
View File
@@ -8,6 +8,7 @@ declare const Buffer: any;
export interface IHeaderFields {
[key: string]: number | string | Uint32Array | null | undefined;
// base-64 encoded filename. Defaults to "Unnamed file".
name: string;
// File size in bytes. The file transfer will be canceled if this size is exceeded.
@@ -81,7 +82,7 @@ function toName(data: Uint32Array): string {
return new TextDecoder().decode(b);
}
const DECODERS: {[key: string]: (v: Uint32Array) => any} = {
const DECODERS: {[key: string]: (v: Uint32Array) => number | string} = {
inline: toInt,
size: toInt,
name: toName,
@@ -100,7 +101,7 @@ export class HeaderParser {
private _buffer = new Uint32Array(MAX_FIELDCHARS);
private _position = 0;
private _key = '';
public fields: {[key: string]: any} = {};
public fields: {[key: string]: number | string | Uint32Array | null | undefined} = {};
public reset(): void {
this._buffer.fill(0);
+2 -2
View File
@@ -48,7 +48,7 @@ const enum GaStatus {
}
export class ImageAddon implements ITerminalAddon , IImageApi {
export class ImageAddon implements ITerminalAddon, IImageApi {
private _opts: IImageAddonOptions;
private _defaultOpts: IImageAddonOptions;
private _storage: ImageStorage | undefined;
@@ -90,7 +90,7 @@ export class ImageAddon implements ITerminalAddon , IImageApi {
// windowOptions.getCellSizePixels = true;
// windowOptions.getWinSizeChars = true;
// terminal.setOption('windowOptions', windowOptions);
const windowOps = terminal.options.windowOptions || {};
const windowOps = terminal.options.windowOptions ?? {};
windowOps.getWinSizePixels = true;
windowOps.getCellSizePixels = true;
windowOps.getWinSizeChars = true;
+3 -3
View File
@@ -6,7 +6,7 @@
import { toRGBA8888 } from 'sixel/lib/Colors';
import { IDisposable } from '@xterm/xterm';
import { ICellSize, ITerminalExt, IImageSpec, IRenderDimensions, IRenderService } from './Types';
import { Disposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { Disposable, MutableDisposable, toDisposable } from 'common/Lifecycle';
const PLACEHOLDER_LENGTH = 4096;
const PLACEHOLDER_HEIGHT = 24;
@@ -38,7 +38,7 @@ export class ImageRenderer extends Disposable implements IDisposable {
* Only the DOM output canvas should be on the terminal's document,
* which gets explicitly checked in `insertLayerToDom`.
*/
const canvas = (localDocument || document).createElement('canvas');
const canvas = (localDocument ?? document).createElement('canvas');
canvas.width = width | 0;
canvas.height = height | 0;
return canvas;
@@ -242,7 +242,7 @@ export class ImageRenderer extends Disposable implements IDisposable {
}
if (!this._placeholder) return;
this._ctx.drawImage(
this._placeholderBitmap || this._placeholder!,
this._placeholderBitmap ?? this._placeholder!,
col * width,
(row * height) % 2 ? 0 : 1, // needs %2 offset correction
width * count,
+9 -7
View File
@@ -132,8 +132,10 @@ export class ImageStorage implements IDisposable {
) {
try {
this.setLimit(this._opts.storageLimit);
} catch (e: any) {
console.error(e.message);
} catch (e: unknown) {
if (e instanceof Error) {
console.error(e.message);
}
console.warn(`storageLimit is set to ${this.getLimit()} MB`);
}
this._viewportMetrics = {
@@ -381,7 +383,7 @@ export class ImageStorage implements IDisposable {
if (!line) return;
for (let col = 0; col < cols; ++col) {
if (line.getBg(col) & BgFlags.HAS_EXTENDED) {
let e: IExtendedAttrsImage = line._extendedAttrs[col] || EMPTY_ATTRS;
let e: IExtendedAttrsImage = line._extendedAttrs[col] ?? EMPTY_ATTRS;
const imageId = e.imageId;
if (imageId === undefined || imageId === -1) {
continue;
@@ -400,7 +402,7 @@ export class ImageStorage implements IDisposable {
while (
++col < cols
&& (line.getBg(col) & BgFlags.HAS_EXTENDED)
&& (e = line._extendedAttrs[col] || EMPTY_ATTRS)
&& (e = line._extendedAttrs[col] ?? EMPTY_ATTRS)
&& (e.imageId === imageId)
&& (e.tileId === startTile + count)
) {
@@ -442,7 +444,7 @@ export class ImageStorage implements IDisposable {
for (let row = 0; row < rows; ++row) {
const line = buffer.lines.get(row) as IBufferLineExt;
if (line.getBg(oldCol) & BgFlags.HAS_EXTENDED) {
const e: IExtendedAttrsImage = line._extendedAttrs[oldCol] || EMPTY_ATTRS;
const e: IExtendedAttrsImage = line._extendedAttrs[oldCol] ?? EMPTY_ATTRS;
const imageId = e.imageId;
if (imageId === undefined || imageId === -1) {
continue;
@@ -487,7 +489,7 @@ export class ImageStorage implements IDisposable {
const buffer = this._terminal._core.buffer;
const line = buffer.lines.get(y) as IBufferLineExt;
if (line && line.getBg(x) & BgFlags.HAS_EXTENDED) {
const e: IExtendedAttrsImage = line._extendedAttrs[x] || EMPTY_ATTRS;
const e: IExtendedAttrsImage = line._extendedAttrs[x] ?? EMPTY_ATTRS;
if (e.imageId && e.imageId !== -1) {
const orig = this._images.get(e.imageId)?.orig;
if (window.ImageBitmap && orig instanceof ImageBitmap) {
@@ -507,7 +509,7 @@ export class ImageStorage implements IDisposable {
const buffer = this._terminal._core.buffer;
const line = buffer.lines.get(y) as IBufferLineExt;
if (line && line.getBg(x) & BgFlags.HAS_EXTENDED) {
const e: IExtendedAttrsImage = line._extendedAttrs[x] || EMPTY_ATTRS;
const e: IExtendedAttrsImage = line._extendedAttrs[x] ?? EMPTY_ATTRS;
if (e.imageId && e.imageId !== -1 && e.tileId !== -1) {
const spec = this._images.get(e.imageId);
if (spec) {
+1 -3
View File
@@ -15,7 +15,6 @@
"paths": {
"browser/*": [ "../../../src/browser/*" ],
"common/*": [ "../../../src/common/*" ],
"vs/*": [ "../../../src/vs/*" ],
"@xterm/addon-image": [ "../typings/addon-image.d.ts" ]
}
},
@@ -25,7 +24,6 @@
],
"references": [
{ "path": "../../../src/browser" },
{ "path": "../../../src/common" },
{ "path": "../../../src/vs" }
{ "path": "../../../src/common" }
]
}
+2 -3
View File
@@ -5,10 +5,9 @@ const config: PlaywrightTestConfig = {
timeout: 10000,
projects: [
{
name: 'ChromeStable',
name: 'Chromium',
use: {
browserName: 'chromium',
channel: 'chrome'
browserName: 'chromium'
}
},
{
+2 -2
View File
@@ -13,7 +13,7 @@ export interface ITerminalAddon {
dispose(): void;
}
export class LigaturesAddon implements ITerminalAddon , ILigaturesApi {
export class LigaturesAddon implements ITerminalAddon, ILigaturesApi {
private readonly _fallbackLigatures: string[];
private readonly _fontFeatureSettings?: string;
@@ -22,7 +22,7 @@ export class LigaturesAddon implements ITerminalAddon , ILigaturesApi {
constructor(options?: Partial<ILigatureOptions>) {
// Source: calt set from https://github.com/be5invis/Iosevka?tab=readme-ov-file#ligations
this._fallbackLigatures = (options?.fallbackLigatures || [
this._fallbackLigatures = (options?.fallbackLigatures ?? [
'<--', '<---', '<<-', '<-', '->', '->>', '-->', '--->',
'<==', '<===', '<<=', '<=', '=>', '=>>', '==>', '===>', '>=', '>>=',
'<->', '<-->', '<--->', '<---->', '<=>', '<==>', '<===>', '<====>', '::', ':::',
+11 -9
View File
@@ -42,11 +42,11 @@ export default async function load(fontFamily: string, cacheSize: number): Promi
if (status && status.state !== 'granted') {
throw new Error('Permission to access local fonts not granted.');
}
} catch (err: any) {
} catch (err: unknown) {
// A `TypeError` indicates the 'local-fonts'
// permission is not yet implemented, so
// only `throw` if this is _not_ the problem.
if (err.name !== 'TypeError') {
if (err instanceof Error && err.name !== 'TypeError') {
throw err;
}
}
@@ -60,8 +60,10 @@ export default async function load(fontFamily: string, cacheSize: number): Promi
fonts[metadata.family].push(metadata);
}
fontsPromise = Promise.resolve(fonts);
} catch (err: any) {
console.error(err.name, err.message);
} catch (err: unknown) {
if (err instanceof Error) {
console.error(err.name, err.message);
}
}
}
// Latest proposal https://bugs.chromium.org/p/chromium/issues/detail?id=1312603
@@ -76,13 +78,13 @@ export default async function load(fontFamily: string, cacheSize: number): Promi
fonts[metadata.family].push(metadata);
}
fontsPromise = Promise.resolve(fonts);
} catch (err: any) {
console.error(err.name, err.message);
} catch (err: unknown) {
if (err instanceof Error) {
console.error(err.name, err.message);
}
}
}
if (!fontsPromise) {
fontsPromise = Promise.resolve({});
}
fontsPromise ??= Promise.resolve({});
}
const fonts = await fontsPromise;
@@ -52,12 +52,10 @@ export function processLookaheadPosition(
}
processedEntries.add(currentEntry.entry);
if (!currentEntry.entry.forward) {
currentEntry.entry.forward = {
individual: {},
range: []
};
}
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
@@ -97,12 +95,10 @@ export function processBacktrackPosition(
}
processedEntries.add(currentEntry.entry);
if (!currentEntry.entry.reverse) {
currentEntry.entry.reverse = {
individual: {},
range: []
};
}
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
@@ -54,9 +54,6 @@ export function getIndividualSubstitutionGlyph(table: SubstitutionTable, glyphId
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;
return table.substitute[coverageIndex] ?? null;
}
}
+1 -1
View File
@@ -30,7 +30,7 @@ export function enableLigatures(term: Terminal, fallbackLigatures: string[] = []
let currentFontName: string | undefined = undefined;
let font: Font | undefined = undefined;
let loadingState: LoadingState = LoadingState.UNLOADED;
let loadError: any | undefined = undefined;
let loadError: unknown = undefined;
return term.registerCharacterJoiner((text: string): [number, number][] => {
// If the font hasn't been loaded yet, load it and return an empty result
+2 -2
View File
@@ -5,7 +5,7 @@
import type { Terminal, ITerminalAddon, IDisposable } from '@xterm/xterm';
import type { ProgressAddon as IProgressApi, IProgressState } from '@xterm/addon-progress';
import type { Emitter, Event } from 'vs/base/common/event';
import type { Emitter, IEvent } from 'common/Event';
const enum ProgressType {
@@ -39,7 +39,7 @@ export class ProgressAddon implements ITerminalAddon, IProgressApi {
private _pr = 0;
// HACK: This uses ! to align with the API, this should be fixed when 5283 is resolved
private _onChange!: Emitter<IProgressState>;
public onChange!: Event<IProgressState>;
public onChange!: IEvent<IProgressState>;
public dispose(): void {
this._seqHandler?.dispose();
+4 -4
View File
@@ -15,12 +15,12 @@
"../../../node_modules/@types/mocha"
],
"paths": {
"common/*": [
"../../../src/common/*"
],
"browser/*": [
"../../../src/browser/*"
],
"vs/*": [
"../../../src/vs/*"
],
"@xterm/addon-progress": [
"../typings/addon-progress.d.ts"
]
@@ -35,7 +35,7 @@
"path": "../../../src/browser"
},
{
"path": "../../../src/vs"
"path": "../../../src/common"
}
]
}
@@ -5,10 +5,9 @@ const config: PlaywrightTestConfig = {
timeout: 10000,
projects: [
{
name: 'ChromeStable',
name: 'Chromium',
use: {
browserName: 'chromium',
channel: 'chrome'
browserName: 'chromium'
}
},
{
+1 -1
View File
@@ -5,7 +5,7 @@
import type { Terminal, IDisposable, IDecoration } from '@xterm/xterm';
import type { ISearchDecorationOptions } from '@xterm/addon-search';
import { dispose, Disposable, toDisposable } from 'vs/base/common/lifecycle';
import { dispose, Disposable, toDisposable } from 'common/Lifecycle';
import type { ISearchResult } from './SearchEngine';
/**
+6 -6
View File
@@ -4,10 +4,10 @@
*/
import type { Terminal, IDisposable, ITerminalAddon } from '@xterm/xterm';
import type { SearchAddon as ISearchApi, ISearchOptions, ISearchAddonOptions, ISearchResultChangeEvent } from '@xterm/addon-search';
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 type { SearchAddon as ISearchApi, ISearchOptions, ISearchAddonOptions, ISearchResultChangeEvent, ISearchDecorationOptions } from '@xterm/addon-search';
import { Emitter, type IEvent } from 'common/Event';
import { Disposable, MutableDisposable, toDisposable } from 'common/Lifecycle';
import { disposableTimeout } from 'common/Async';
import { SearchLineCache } from './SearchLineCache';
import { SearchState } from './SearchState';
import { SearchEngine, type ISearchResult } from './SearchEngine';
@@ -47,7 +47,7 @@ export class SearchAddon extends Disposable implements ITerminalAddon, ISearchAp
private readonly _onBeforeSearch = this._register(new Emitter<void>());
public readonly onBeforeSearch = this._onBeforeSearch.event;
public get onDidChangeResults(): Event<ISearchResultChangeEvent> {
public get onDidChangeResults(): IEvent<ISearchResultChangeEvent> {
return this._resultTracker.onDidChangeResults;
}
@@ -222,7 +222,7 @@ export class SearchAddon extends Disposable implements ITerminalAddon, ISearchAp
* @param result The result to select.
* @returns Whether a result was selected.
*/
private _selectResult(result: ISearchResult | undefined, options?: any, noScroll?: boolean): boolean {
private _selectResult(result: ISearchResult | undefined, options?: ISearchDecorationOptions, noScroll?: boolean): boolean {
if (!this._terminal || !this._decorationManager) {
return false;
}
+1 -1
View File
@@ -7,7 +7,7 @@ import { SearchEngine } from './SearchEngine';
import { SearchLineCache } from './SearchLineCache';
import { Terminal } from 'browser/public/Terminal';
import type { ISearchOptions } from '@xterm/addon-search';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { DisposableStore } from 'common/Lifecycle';
function writeP(terminal: Terminal, data: string): Promise<void> {
return new Promise(r => terminal.write(data, r));
+4 -3
View File
@@ -64,6 +64,9 @@ export class SearchEngine {
throw new Error(`Invalid col: ${startCol} to search in terminal of ${this._terminal.cols} cols`);
}
startRow = Math.max(0, startRow);
startCol = Math.max(0, startCol);
this._lineCache.initLinesCache();
const searchPosition: ISearchPosition = {
@@ -198,9 +201,7 @@ export class SearchEngine {
}
}
if (!result) {
result = this._findInLine(term, searchPosition, searchOptions, isReverseSearch);
}
result ??= this._findInLine(term, searchPosition, searchOptions, isReverseSearch);
// Search from startRow - 1 to top
if (!result) {
@@ -5,7 +5,7 @@
import { assert } from 'chai';
import { SearchLineCache, LineCacheEntry } from './SearchLineCache';
import { Terminal } from 'browser/public/Terminal';
import { timeout } from 'vs/base/common/async';
import { timeout } from 'common/Async';
function writeP(terminal: Terminal, data: string): Promise<void> {
return new Promise(r => terminal.write(data, r));
+2 -2
View File
@@ -4,8 +4,8 @@
*/
import type { Terminal } from '@xterm/xterm';
import { combinedDisposable, Disposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { disposableTimeout } from 'vs/base/common/async';
import { combinedDisposable, Disposable, MutableDisposable, toDisposable } from 'common/Lifecycle';
import { disposableTimeout } from 'common/Async';
export type LineCacheEntry = [
/**
@@ -5,8 +5,8 @@
import type { ISearchResultChangeEvent } from '@xterm/addon-search';
import type { IDisposable } from '@xterm/xterm';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable } from 'vs/base/common/lifecycle';
import { Emitter, type IEvent } from 'common/Event';
import { Disposable } from 'common/Lifecycle';
import type { ISearchResult } from './SearchEngine';
/**
@@ -25,7 +25,7 @@ export class SearchResultTracker extends Disposable {
private _selectedDecoration: ISelectedDecoration | undefined;
private readonly _onDidChangeResults = this._register(new Emitter<ISearchResultChangeEvent>());
public get onDidChangeResults(): Event<ISearchResultChangeEvent> { return this._onDidChangeResults.event; }
public get onDidChangeResults(): IEvent<ISearchResultChangeEvent> { return this._onDidChangeResults.event; }
/**
* Gets the current search results.
-6
View File
@@ -21,9 +21,6 @@
"browser/*": [
"../../../src/browser/*"
],
"vs/*": [
"../../../src/vs/*"
],
"@xterm/addon-search" : [
"../typings/addon-search.d.ts"
]
@@ -39,9 +36,6 @@
},
{
"path": "../../../src/browser"
},
{
"path": "../../../src/vs"
}
]
}
@@ -5,10 +5,9 @@ const config: PlaywrightTestConfig = {
timeout: 10000,
projects: [
{
name: 'ChromeStable',
name: 'Chromium',
use: {
browserName: 'chromium',
channel: 'chrome'
browserName: 'chromium'
}
},
{
@@ -116,7 +116,7 @@ describe('SerializeAddon', () => {
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');
assert.equal(serializeAddon.serialize(), '\u001b[4mtest\u001b[0m');
});
it('should serialize double underline', async () => {
@@ -228,7 +228,7 @@ describe('SerializeAddon', () => {
it('empty terminal with selection turned off', () => {
const output = serializeAddon.serializeAsHTML();
assert.notEqual(output, '');
assert.equal((output.match(/<div><span> {10}<\/span><\/div>/g) || []).length, 2);
assert.equal((output.match(/<div><span> {10}<\/span><\/div>/g) ?? []).length, 2);
});
it('empty terminal with no selection', () => {
@@ -245,7 +245,7 @@ describe('SerializeAddon', () => {
const output = serializeAddon.serializeAsHTML({
onlySelection: true
});
assert.equal((output.match(/<div><span>terminal<\/span><\/div>/g) || []).length, 1, output);
assert.equal((output.match(/<div><span>terminal<\/span><\/div>/g) ?? []).length, 1, output);
});
it('basic terminal with html unsafe chars', async () => {
@@ -255,7 +255,7 @@ describe('SerializeAddon', () => {
const output = serializeAddon.serializeAsHTML({
onlySelection: true
});
assert.equal((output.match(/<div><span>&lt;a>&amp;pi;<\/span><\/div>/g) || []).length, 1, output);
assert.equal((output.match(/<div><span>&lt;a>&amp;pi;<\/span><\/div>/g) ?? []).length, 1, output);
});
it('serializes rows within a provided range', async () => {
@@ -267,7 +267,7 @@ describe('SerializeAddon', () => {
startCol: 4
}
});
const rowMatches = output.match(/<div><span>.*?<\/span><\/div>/g) || [];
const rowMatches = output.match(/<div><span>.*?<\/span><\/div>/g) ?? [];
assert.equal(rowMatches.length, 1, output);
assert.ok(rowMatches[0]?.includes('hello'));
assert.ok(!output.includes('bye'));
@@ -278,56 +278,56 @@ describe('SerializeAddon', () => {
await writeP(terminal, ' ' + sgr('1') + 'terminal' + sgr('22') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.equal((output.match(/<span style='font-weight: bold;'>terminal<\/span>/g) || []).length, 1, output);
assert.equal((output.match(/<span style='font-weight: bold;'>terminal<\/span>/g) ?? []).length, 1, output);
});
it('cells with italic styling', async () => {
await writeP(terminal, ' ' + sgr('3') + 'terminal' + sgr('23') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.equal((output.match(/<span style='font-style: italic;'>terminal<\/span>/g) || []).length, 1, output);
assert.equal((output.match(/<span style='font-style: italic;'>terminal<\/span>/g) ?? []).length, 1, output);
});
it('cells with inverse styling', async () => {
await writeP(terminal, ' ' + sgr('7') + 'terminal' + sgr('27') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.equal((output.match(/<span style='color: #000000; background-color: #BFBFBF;'>terminal<\/span>/g) || []).length, 1, output);
assert.equal((output.match(/<span style='color: #000000; background-color: #BFBFBF;'>terminal<\/span>/g) ?? []).length, 1, output);
});
it('cells with underline styling', async () => {
await writeP(terminal, ' ' + sgr('4') + 'terminal' + sgr('24') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.equal((output.match(/<span style='text-decoration: underline;'>terminal<\/span>/g) || []).length, 1, output);
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);
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);
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);
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);
assert.equal((output.match(/<span style='text-decoration: underline dashed;'>terminal<\/span>/g) ?? []).length, 1, output);
});
it('cells with underline color (palette)', async () => {
@@ -350,49 +350,49 @@ describe('SerializeAddon', () => {
await writeP(terminal, ' ' + sgr('8') + 'terminal' + sgr('28') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.equal((output.match(/<span style='visibility: hidden;'>terminal<\/span>/g) || []).length, 1, output);
assert.equal((output.match(/<span style='visibility: hidden;'>terminal<\/span>/g) ?? []).length, 1, output);
});
it('cells with dim styling', async () => {
await writeP(terminal, ' ' + sgr('2') + 'terminal' + sgr('22') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.equal((output.match(/<span style='opacity: 0.5;'>terminal<\/span>/g) || []).length, 1, output);
assert.equal((output.match(/<span style='opacity: 0.5;'>terminal<\/span>/g) ?? []).length, 1, output);
});
it('cells with strikethrough styling', async () => {
await writeP(terminal, ' ' + sgr('9') + 'terminal' + sgr('29') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.equal((output.match(/<span style='text-decoration: line-through;'>terminal<\/span>/g) || []).length, 1, output);
assert.equal((output.match(/<span style='text-decoration: line-through;'>terminal<\/span>/g) ?? []).length, 1, output);
});
it('cells with combined styling', async () => {
await writeP(terminal, sgr('1') + ' ' + sgr('9') + 'termi' + sgr('22') + 'nal' + sgr('29') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.equal((output.match(/<span style='font-weight: bold;'> <\/span>/g) || []).length, 1, output);
assert.equal((output.match(/<span style='font-weight: bold; text-decoration: line-through;'>termi<\/span>/g) || []).length, 1, output);
assert.equal((output.match(/<span style='text-decoration: line-through;'>nal<\/span>/g) || []).length, 1, output);
assert.equal((output.match(/<span style='font-weight: bold;'> <\/span>/g) ?? []).length, 1, output);
assert.equal((output.match(/<span style='font-weight: bold; text-decoration: line-through;'>termi<\/span>/g) ?? []).length, 1, output);
assert.equal((output.match(/<span style='text-decoration: line-through;'>nal<\/span>/g) ?? []).length, 1, output);
});
it('cells with color styling', async () => {
await writeP(terminal, ' ' + sgr('38;5;46') + 'terminal' + sgr('39') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.equal((output.match(/<span style='color: #00ff00;'>terminal<\/span>/g) || []).length, 1, output);
assert.equal((output.match(/<span style='color: #00ff00;'>terminal<\/span>/g) ?? []).length, 1, output);
});
it('cells with background styling', async () => {
await writeP(terminal, ' ' + sgr('48;5;46') + 'terminal' + sgr('49') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.equal((output.match(/<span style='background-color: #00ff00;'>terminal<\/span>/g) || []).length, 1, output);
assert.equal((output.match(/<span style='background-color: #00ff00;'>terminal<\/span>/g) ?? []).length, 1, output);
});
it('empty terminal with default options', async () => {
const output = serializeAddon.serializeAsHTML();
assert.equal((output.match(/color: #000000; background-color: #ffffff; font-family: monospace; font-size: 15px;/g) || []).length, 1, output);
assert.equal((output.match(/color: #000000; background-color: #ffffff; font-family: monospace; font-size: 15px;/g) ?? []).length, 1, output);
});
it('empty terminal with custom options', async () => {
@@ -405,14 +405,14 @@ describe('SerializeAddon', () => {
const output = serializeAddon.serializeAsHTML({
includeGlobalBackground: true
});
assert.equal((output.match(/color: #ff00ff; background-color: #00ff00; font-family: verdana; font-size: 20px;/g) || []).length, 1, output);
assert.equal((output.match(/color: #ff00ff; background-color: #00ff00; font-family: verdana; font-size: 20px;/g) ?? []).length, 1, output);
});
it('empty terminal with background included', async () => {
const output = serializeAddon.serializeAsHTML({
includeGlobalBackground: true
});
assert.equal((output.match(/color: #ffffff; background-color: #000000; font-family: monospace; font-size: 15px;/g) || []).length, 1, output);
assert.equal((output.match(/color: #ffffff; background-color: #000000; font-family: monospace; font-size: 15px;/g) ?? []).length, 1, output);
});
it('cells with custom color styling', async () => {
@@ -422,7 +422,7 @@ describe('SerializeAddon', () => {
await writeP(terminal, ' ' + sgr('38;5;0') + 'terminal' + sgr('39') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.equal((output.match(/<span style='color: #ffa500;'>terminal<\/span>/g) || []).length, 1, output);
assert.equal((output.match(/<span style='color: #ffa500;'>terminal<\/span>/g) ?? []).length, 1, output);
});
it('cells with color styling - xterm headless', async () => {
@@ -432,7 +432,7 @@ describe('SerializeAddon', () => {
await writeP(terminal, ' ' + sgr('38;5;46') + 'terminal' + sgr('39') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.equal((output.match(/<span style='color: #00ff00;'>terminal<\/span>/g) || []).length, 1, output);
assert.equal((output.match(/<span style='color: #00ff00;'>terminal<\/span>/g) ?? []).length, 1, output);
});
});
});
+44 -34
View File
@@ -89,11 +89,19 @@ function equalUnderline(cell1: IBufferCell | IAttributeData, cell2: IBufferCell)
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();
if (cell1.getUnderlineStyle() !== cell2.getUnderlineStyle()) {
return false;
}
const cell1Default = cell1.isUnderlineColorDefault();
const cell2Default = cell2.isUnderlineColorDefault();
if (cell1Default && cell2Default) {
return true;
}
if (cell1Default !== cell2Default) {
return false;
}
return cell1.getUnderlineColor() === cell2.getUnderlineColor()
&& cell1.getUnderlineColorMode() === cell2.getUnderlineColorMode();
}
function equalFlags(cell1: IBufferCell | IAttributeData, cell2: IBufferCell): boolean {
@@ -109,6 +117,16 @@ function equalFlags(cell1: IBufferCell | IAttributeData, cell2: IBufferCell): bo
&& cell1.isStrikethrough() === cell2.isStrikethrough();
}
function attributesEquals(cell1: IBufferCell | IAttributeData, cell2: IBufferCell): boolean {
const cell1AsBufferCell = cell1 as IBufferCell;
if (typeof cell1AsBufferCell.attributesEquals === 'function') {
return cell1AsBufferCell.attributesEquals(cell2);
}
return equalFg(cell1, cell2)
&& equalBg(cell1, cell2)
&& equalFlags(cell1, cell2);
}
class StringSerializeHandler extends BaseSerializeHandler {
private _rowIndex: number = 0;
private _allRows: string[] = new Array<string>();
@@ -258,6 +276,9 @@ class StringSerializeHandler extends BaseSerializeHandler {
private _diffStyle(cell: IBufferCell | IAttributeData, oldCell: IBufferCell): number[] {
const sgrSeq: number[] = [];
if (attributesEquals(cell, oldCell)) {
return sgrSeq;
}
const fgChanged = !equalFg(cell, oldCell);
const bgChanged = !equalBg(cell, oldCell);
const flagsChanged = !equalFlags(cell, oldCell);
@@ -290,17 +311,18 @@ class StringSerializeHandler extends BaseSerializeHandler {
if (cell.isInverse() !== oldCell.isInverse()) { sgrSeq.push(cell.isInverse() ? 7 : 27); }
if (cell.isBold() !== oldCell.isBold()) { sgrSeq.push(cell.isBold() ? 1 : 22); }
if (!equalUnderline(cell, oldCell)) {
const cellData = cell as unknown as IAttributeData;
const style = cellData.getUnderlineStyle();
const style = cell.getUnderlineStyle();
if (style === UnderlineStyle.NONE) {
sgrSeq.push(24);
} else if (style === UnderlineStyle.SINGLE && cell.isUnderlineColorDefault()) {
sgrSeq.push(4);
} 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()) {
if (!cell.isUnderlineColorDefault()) {
const color = cell.getUnderlineColor();
if (cell.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);
@@ -457,7 +479,7 @@ class StringSerializeHandler extends BaseSerializeHandler {
}
}
export class SerializeAddon implements ITerminalAddon , ISerializeApi {
export class SerializeAddon implements ITerminalAddon, ISerializeApi {
private _terminal: Terminal | undefined;
public activate(terminal: Terminal): void {
@@ -601,7 +623,7 @@ export class SerializeAddon implements ITerminalAddon , ISerializeApi {
throw new Error('Cannot use addon until it has been loaded');
}
return this._serializeBufferAsHTML(this._terminal, options || {});
return this._serializeBufferAsHTML(this._terminal, options ?? {});
}
public dispose(): void { }
@@ -630,20 +652,6 @@ export class HTMLSerializeHandler extends BaseSerializeHandler {
}
}
private _padStart(target: string, targetLength: number, padString: string): string {
targetLength = targetLength >> 0;
padString = padString ?? ' ';
if (target.length > targetLength) {
return target;
}
targetLength -= target.length;
if (targetLength > padString.length) {
padString += padString.repeat(targetLength / padString.length);
}
return padString.slice(0, targetLength) + target;
}
protected _beforeSerialize(rows: number, start: number, end: number): void {
this._htmlContent += '<html><body><!--StartFragment--><pre>';
@@ -680,7 +688,7 @@ export class HTMLSerializeHandler extends BaseSerializeHandler {
(color >> 8) & 255,
(color ) & 255
];
return '#' + rgb.map(x => this._padStart(x.toString(16), 2, '0')).join('');
return '#' + rgb.map(x => x.toString(16).padStart(2, '0')).join('');
}
if (isFg ? cell.isFgPalette() : cell.isBgPalette()) {
return this._ansiColors[color].css;
@@ -689,26 +697,24 @@ export class HTMLSerializeHandler extends BaseSerializeHandler {
}
private _getUnderlineColor(cell: IBufferCell): string | undefined {
const cellData = cell as unknown as IAttributeData;
if (cellData.isUnderlineColorDefault()) {
if (cell.isUnderlineColorDefault()) {
return undefined;
}
const color = cellData.getUnderlineColor();
if (cellData.isUnderlineColorRGB()) {
const color = cell.getUnderlineColor();
if (cell.isUnderlineColorRGB()) {
const rgb = [
(color >> 16) & 255,
(color >> 8) & 255,
(color ) & 255
];
return '#' + rgb.map(x => this._padStart(x.toString(16), 2, '0')).join('');
return '#' + rgb.map(x => x.toString(16).padStart(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()) {
switch (cell.getUnderlineStyle()) {
case UnderlineStyle.SINGLE:
return 'underline';
case UnderlineStyle.DOUBLE:
@@ -727,6 +733,10 @@ export class HTMLSerializeHandler extends BaseSerializeHandler {
private _diffStyle(cell: IBufferCell, oldCell: IBufferCell): string[] | undefined {
const content: string[] = [];
if (attributesEquals(cell, oldCell)) {
return undefined;
}
const fgChanged = !equalFg(cell, oldCell);
const bgChanged = !equalBg(cell, oldCell);
const flagsChanged = !equalFlags(cell, oldCell);
@@ -203,6 +203,46 @@ test.describe('SerializeAddon', () => {
strictEqual(await ctx.page.evaluate(`window.serialize.serialize();`), lines.join('\r\n'));
});
test('buffer cell attributesEquals compares underline style and color', async () => {
await ctx.proxy.write(`${sgr(UNDERLINE_DOUBLE, UNDERLINE_COLOR_RED)}A${sgr(UNDERLINE_DOUBLE, UNDERLINE_COLOR_RED)}B${sgr(NORMAL)}`);
const sameAttributes = await ctx.page.evaluate(`(() => {
const line = window.term.buffer.active.getLine(0);
const cellA = line?.getCell(0);
const cellB = line?.getCell(1);
if (!cellA || !cellB) {
return undefined;
}
return cellA.attributesEquals(cellB);
})()`);
strictEqual(sameAttributes, true);
await ctx.page.evaluate(`window.term.reset()`);
await ctx.proxy.write(`${sgr(UNDERLINE_DOUBLE, UNDERLINE_COLOR_RED)}A${sgr(UNDERLINE_DOUBLE, UNDERLINE_COLOR_GREEN)}B${sgr(NORMAL)}`);
const differentColor = await ctx.page.evaluate(`(() => {
const line = window.term.buffer.active.getLine(0);
const cellA = line?.getCell(0);
const cellB = line?.getCell(1);
if (!cellA || !cellB) {
return undefined;
}
return cellA.attributesEquals(cellB);
})()`);
strictEqual(differentColor, false);
await ctx.page.evaluate(`window.term.reset()`);
await ctx.proxy.write(`${sgr(UNDERLINE_DOUBLE, UNDERLINE_COLOR_RED)}A${sgr(UNDERLINED, UNDERLINE_COLOR_RED)}B${sgr(NORMAL)}`);
const differentStyle = await ctx.page.evaluate(`(() => {
const line = window.term.buffer.active.getLine(0);
const cellA = line?.getCell(0);
const cellB = line?.getCell(1);
if (!cellA || !cellB) {
return undefined;
}
return cellA.attributesEquals(cellB);
})()`);
strictEqual(differentStyle, false);
});
test('serialize all rows of content with color256', async function(): Promise<any> {
const rows = 32;
const cols = 10;
@@ -602,6 +642,9 @@ const BOLD = '1';
const DIM = '2';
const ITALIC = '3';
const UNDERLINED = '4';
const UNDERLINE_DOUBLE = '4:2';
const UNDERLINE_COLOR_RED = '58;5;196';
const UNDERLINE_COLOR_GREEN = '58;5;46';
const BLINK = '5';
const INVERSE = '7';
const INVISIBLE = '8';
@@ -5,10 +5,9 @@ const config: PlaywrightTestConfig = {
timeout: 10000,
projects: [
{
name: 'ChromeStable',
name: 'Chromium',
use: {
browserName: 'chromium',
channel: 'chrome'
browserName: 'chromium'
}
},
{
@@ -9,19 +9,15 @@ import type { Terminal, ITerminalAddon, IUnicodeHandling } from '@xterm/xterm';
import type { UnicodeGraphemesAddon as IUnicodeGraphemesApi } from '@xterm/addon-unicode-graphemes';
import { UnicodeGraphemeProvider } from './UnicodeGraphemeProvider';
export class UnicodeGraphemesAddon implements ITerminalAddon , IUnicodeGraphemesApi {
export class UnicodeGraphemesAddon implements ITerminalAddon, IUnicodeGraphemesApi {
private _provider15Graphemes?: UnicodeGraphemeProvider;
private _provider15?: UnicodeGraphemeProvider;
private _unicode?: IUnicodeHandling;
private _oldVersion: string = '';
public activate(terminal: Terminal): void {
if (! this._provider15) {
this._provider15 = new UnicodeGraphemeProvider(false);
}
if (! this._provider15Graphemes) {
this._provider15Graphemes = new UnicodeGraphemeProvider(true);
}
this._provider15 ??= new UnicodeGraphemeProvider(false);
this._provider15Graphemes ??= new UnicodeGraphemeProvider(true);
const unicode = terminal.unicode;
this._unicode = unicode;
unicode.register(this._provider15);
@@ -1,7 +1,7 @@
import UnicodeTrie from './unicode-trie';
const trieRaw = "AAARAAAAAABwxwAAAb4LQfTtmw+sVmUdx58LL/ffe/kjzNBV80gW1F3yR+6CvbJiypoZa0paWmAWSluErSBbFtYkkuZykq6QamGJ4WRqo2kFGy6dYWtEq6G1MFAJbRbOVTQr+x7f5+x97q/n/3me87wXzm/3s+f/7/d7/p7znnvOlvGMbQM7wIPgEbAPHABPgcPgefAS+BfYwuv/F/Q2OulBxKcK6TMRPxu8FcwFbwcjYCFYDC4Cl4ArwNXgGvBJsA58UdBDwy+jbBO4La8DtoEd4H7wkNBuN+KPgn3gADgIngaHwFHwF/AyeAWMm4C+TGi3LdiJ/EnIex04A2RgFpgD5oKFYDG4CLwHXAo+IKSvAqt4/evA9bz9jWA6+Cq3dyvCP8HWNwX93wF38/ROcD94SCjP2+1B+BiPP4HwgOD/7xD/I08fRniMx48jPAFeBeuF+n29jE0G08FZvaPHYWZvh9mcEfAOjlhXx/qGfd2QvLO3zccmtMnzliC9lPt+GenD1nyMiK/LNf1cycs+gfAzPJ6vtxe4jhuQtx5sBLeA28G3eb3v8/Beif4HkPewxu5G6N/rMP4qfgEdvwZPgj+AZ8Cx3nYfxiE8Dk6AV0FfH/YEOB28AbwJDIPzQAtcAC4Gl/Z19F+J+NVCehWPr0b46b7RvixvdPg8yr7U10l/BfFN4La8DdgGdoAHwU/AI2AfOACeAofB8+AlcAKwfvyBKeCM/o7NrF9PXmdWv9/Ynot2I7ztIg8dF5I2a8i63CjZU+9Fm2Wcy4U4ZQVYyeOrwVoev57UuxHcJKRvFuJXgnU8/nUebtbYrKmpCUOx31P7UVNTU1NTU1NTU1OGLTz8Xr/77+W7+9vP0or0MxPMbXaizY8FW3sQ3wseB/t5/kGEh8DR/vbzwL8i/Af4Dy8fP8BYE0weaKenI/wV/DhrQG97JspngzlgLpgHzgPzwUhdVpfVZXVZXRa87HxwAVgQ4Pn5WEd85l5TUzOasvezFw/E3b/LoP9D4CpwrcTWWsGXNQOj748/G9k3G56d1KYxmbELwQbwKFiJvBM8nDWlHa5E+AOwCzwLzjkNeeB28NvTeB1OYyr0gQ1g99R23nGE50xj7MPgc+A+8K5Bxj4FHgB/G2z/T9XEzCZjd/S0WYX4Pc3/r/Nn5I0f6qQXIP5x8ENwBMyYyNhHJ3b0pOCuLrBvM941NTU1JyNHEp+BrC8dMyalt1/m3uWfhmeULzRGp9d3wf0WZSN8+prCr60Wz09tuNmx35sl9Y825HXvRN39KNveaL8flb9f913kbec67kHeTsR3gYcH2uV7ED4m2HhCYi/X9ZuBzvuXv0f8iKIfx5B/XCg7gTgbVPdvAsomCuWnD45eK28UyvL3Jt+s0fU2TVnOXJQvJHUWIb0ELAWXgCt4+UcMumSsEtpch/g6ouMGpG/ieZsc9N/q4YsLd3D9WyPbsWEbfNgO7hN82TWY/n8xKbmsC3xQsYKf+7sjrx2TH+u4H3vhx+OO6+X9hmtXN7C/4r15EPaeBs9J7L7YBeeED/k7wn8fbIf/Rji+yVizmd4vW6bB19cb/PU9w7MxMA60bzPHgM8+zG623+OnzOf55yNc3Gw/k303wveBy3nZcoTXgNVgLfiCRNcG5N3SbIebwZ08fhe4l8d/BH7K4yI/4+HPwS/BAfBks+PzIaHuc3x+ivSL4GUyZ68I6fwZYRNMG2qnz+Th2QjfMtTx/1zE5w61nyN+Q7C3aKgdin1dgrylYBn4INdhGn/Z2FfFiqH01/SUXMvnPD+jC+j85N/RqRhR/DYaS6T+P09K1mD+vzW+5zVqqeVUl0wTz2lK8odJHRGXfBufdGLSoSo3+ZFJ6sl0qvJVNmhI4z4i06mrZ6uT1le1z5h5HE3tMiHPtQ5javu+ItMXUr/MXpmwmyRL3D6U7UwIMyYfczGu0qdqb2pbhcw4xQkhWQBMerrZ/liXrGTbsQwTwrEu4zSczKLrd7fCSKiKn+zSo8BWXMe8myXWOivrUxWi60OPoQ7VIasbQ0S/Ukk3rZVullNhHEL1rYoxUF0PTfm6elWJzq54ZsU4z11ohOy0oxT2izFqCNj4TesXcWZo6+Jfqr1O+1O1beqDagypj2J9F1u2daucj3Eknmq/6PaHrK7Mb1o35DiW1a/a76LuhlDXZX25SOz11S33ErKxDb2/fc/bFKI6axskn+4/W90u9mOtbRf7smsoTdvOfwoRz0t6DaP9k81v6P7Re5aUQudTd303rX+bZzBl97/KR7E+Xbux9lLI+aNr1PfaYLpPDiW2/vrYTX1drMIeXbMye6HXlw8292Jl7ZXxLxRlxXbcaH9drjFlxfa3Qozx8NWRi834lPVZbD+SmN7EJPzc9TVCSVXXDps9L+513b2J7fMu176V2YOhx1A3JrJ8KrLxUumpcu5j/lYT+2tzLRVDZmhjO442a1Clu0ox9VPVXzE/lcS4V0k1D6LI1pJsz8fct9SGbO5l/rmKzTlvsxdj3IvRtC2uv0t1fotltvd2VaCy5Sp5m0EhnZG4CCNxXZrWp/VUIrOjapfnNw11ZNI0V/GWzKNuxtzGKKTEtJeR0NVmpojbtBuW5On0u0is9ZMxvU8ZM+8vEyadtu10oqtP9Q4rcJEm85+Two/QkpGwjI6YkgkhtUfzZOW6fFVexuRri+qj9TJJHZkdmW5abiu0rs6uj2TMfmx06bISUj9tZ9Lja8dVQtox6WpxTJKfW3M4MSTmvU4sWy1CU6BF4jIfdNeDjHWuO1lCWIm2Jr2ixNZvklD2fP0Q6+vsmO4hqN1hJvfDtV5G8mTlsvau4qPP1a64L1skT6QYEzEtq0PzGZOfCbSdSmcKTP7Qs86Ej/1hEpelaV6IMdT5ayu2+nT9tmnnO746XbLxE8t0qOrYtJWhmk9bvaLfsrotRVw1PnR+bcafSUKZ6Mps7smobybJLH2R6WqRkJa1DHV0UmbfUcksiSF0HExSpp+uY0zbTklMaCm7blzEtg8h1rNMXNaYi05ZXsbC75sQ/4+aUxFV2jL50Q3jE0rK2rVtN09By8OHoo1vH2LPSdE323mr2sdu0pUZiDkWLRKWnfeQY6taKzHF9n/GPv8jd/0/egiRvYMR24fU79iY3s9Qva9RlYR8n8HHtq9fMcT1HRWfdZXiHd9YInt/iI4PTaf+BimXKvdXYU+3hlRpHzs2dVK/cxhDn+xs0I2jzxjL5kpXz1VU72aLtkK/97sALKyQqu25SshvG6h08/cLrlKswRklKXvvXfa+pZt+y8nah5YUv2Oo/ap/X2URdRfico9K69hcp6r6XaCz5Wo/hs/iNTGF6N6tV92/9ZS0Wba9SlT3pKF/e6W674+x9ly+VRL73cPU8ygb31D3eSqfVd+iqET0y3YMYojoO11XqrTt2nPxmeq1HYeqxkmUMt8DiesjpoTSr+qDrD+qPZDiOZxMdH0pRPX8MFUfQtv0Xbs+a1a1NnRryNZ/2+tsaPG5ZoX0RXZei88yZGdo4UMPj/cwv/kMJboxLISuQbE+1VW12Mx7FWOrW3M9Hv7Y+uxyraPSo8B2TGPuLdOeZha+hBKf8Sjsm/oR+7pmsx/oeOraFWdXleeV6oyl41zm+mgSuq9C6ox1TsU8D+m4dwMmf8v2nz7Tm+fYfj7HV1K/x1HWjquvY+2dllxM64ue87Su772zzbXIVC+WxLZTRR9MdkMTypZNH1z6G0tUvoccwxA+hfLNdV+a7MaQqscztMi+7QnxDZXvd1dldWQOyMbApb1Jd2h91Ffx+y9Xfb7tClokboOvrRhrbVpFFO8z+65t2/u4su9MUx028znH01/TGVDmHAj13W1o+1USw+eUfYtpO+b82rRNsb6oPpV+1fdBqddB6n3WDXvdJDZrJ0QfQp6bsc/kqq4BIddHWXGdN1pmWveh58F1zYUW1zmOITHXWOg1XrZvZSWUf77tq1ofqear6muaT1lIQp3bofabSafJVlnfYo9B6LGr8uzz2Xchvzfw+T9PlgiV/A8=";
declare const Buffer: any;
declare const Buffer: { from(s: string, encoding: string): Uint8Array } | undefined;
function _dec(s: string): Uint8Array {
if (typeof Buffer !== 'undefined') return Buffer.from(s, 'base64');
const bs = atob(s);
@@ -5,10 +5,9 @@ const config: PlaywrightTestConfig = {
timeout: 10000,
projects: [
{
name: 'ChromeStable',
name: 'Chromium',
use: {
browserName: 'chromium',
channel: 'chrome'
browserName: 'chromium'
}
},
{
+1 -1
View File
@@ -9,7 +9,7 @@ import type { Terminal, ITerminalAddon } from '@xterm/xterm';
import type { Unicode11Addon as IUnicode11Api } from '@xterm/addon-unicode11';
import { UnicodeV11 } from './UnicodeV11';
export class Unicode11Addon implements ITerminalAddon , IUnicode11Api {
export class Unicode11Addon implements ITerminalAddon, IUnicode11Api {
public activate(terminal: Terminal): void {
terminal.unicode.register(new UnicodeV11());
}
@@ -5,10 +5,9 @@ const config: PlaywrightTestConfig = {
timeout: 10000,
projects: [
{
name: 'ChromeStable',
name: 'Chromium',
use: {
browserName: 'chromium',
channel: 'chrome'
browserName: 'chromium'
}
},
{
@@ -5,10 +5,9 @@ const config: PlaywrightTestConfig = {
timeout: 10000,
projects: [
{
name: 'ChromeStable',
name: 'Chromium',
use: {
browserName: 'chromium',
channel: 'chrome'
browserName: 'chromium'
}
},
{
+2 -2
View File
@@ -35,7 +35,7 @@ function handleLink(event: MouseEvent, uri: string): void {
}
}
export class WebLinksAddon implements ITerminalAddon , IWebLinksApi {
export class WebLinksAddon implements ITerminalAddon, IWebLinksApi {
private _terminal: Terminal | undefined;
private _linkProvider: IDisposable | undefined;
@@ -48,7 +48,7 @@ export class WebLinksAddon implements ITerminalAddon , IWebLinksApi {
public activate(terminal: Terminal): void {
this._terminal = terminal;
const options = this._options as ILinkProviderOptions;
const regex = options.urlRegex || strictUrlRegex;
const regex = options.urlRegex ?? strictUrlRegex;
this._linkProvider = this._terminal.registerLinkProvider(new WebLinkProvider(this._terminal, regex, this._handler, options));
}
@@ -5,10 +5,9 @@ const config: PlaywrightTestConfig = {
timeout: 10000,
projects: [
{
name: 'ChromeStable',
name: 'Chromium',
use: {
browserName: 'chromium',
channel: 'chrome'
browserName: 'chromium'
}
},
{
+5 -2
View File
@@ -7,6 +7,7 @@ import { ICellData } from 'common/Types';
import { Terminal } from '@xterm/xterm';
import { rgba } from 'common/Color';
import { treatGlyphAsBackgroundColor } from 'browser/renderer/shared/RendererUtils';
import { blockPatternCodepoints } from './customGlyphs/CustomGlyphDefinitions';
// Work variables to avoid garbage collection
let $fg = 0;
@@ -42,7 +43,7 @@ export class CellColorResolver {
* Resolves colors for the cell, putting the result into the shared {@link result}. This resolves
* overrides, inverse and selection for the cell which can then be used to feed into the renderer.
*/
public resolve(cell: ICellData, x: number, y: number, deviceCellWidth: number): void {
public resolve(cell: ICellData, x: number, y: number, deviceCellWidth: number, deviceCellHeight: number): void {
this.result.bg = cell.bg;
this.result.fg = cell.fg;
this.result.ext = cell.bg & BgFlags.HAS_EXTENDED ? cell.extended.ext : 0;
@@ -63,7 +64,9 @@ export class CellColorResolver {
const lineWidth = Math.max(1, Math.floor(this._optionService.rawOptions.fontSize * this._coreBrowserService.dpr / 15));
$variantOffset = x * deviceCellWidth % (Math.round(lineWidth) * 2);
}
if ($variantOffset === 0 && blockPatternCodepoints.has(code)) {
$variantOffset = ((x * deviceCellWidth) % 2) * 2 + ((y * deviceCellHeight) % 2);
}
// Apply decorations on the bottom layer
this._decorationService.forEachDecorationAtCell(x, y, 'bottom', d => {
if (d.backgroundColorRGB) {
+3 -1
View File
@@ -8,6 +8,7 @@ import { ITerminalOptions, Terminal } from '@xterm/xterm';
import { ITerminal, ReadonlyColorSet } from 'browser/Types';
import { ICharAtlasConfig, ITextureAtlas } from './Types';
import { generateConfig, configEquals } from './CharAtlasUtils';
import type { ILogService } from 'common/services/Services';
interface ITextureAtlasCacheEntry {
atlas: ITextureAtlas;
@@ -67,8 +68,9 @@ export function acquireTextureAtlas(
}
const core: ITerminal = (terminal as any)._core;
const logService = (core as any)._logService as ILogService;
const newEntry: ITextureAtlasCacheEntry = {
atlas: new TextureAtlas(document, newConfig, core.unicodeService),
atlas: new TextureAtlas(document, newConfig, core.unicodeService, logService),
config: newConfig,
ownedBy: [terminal]
};
@@ -3,7 +3,7 @@
* @license MIT
*/
import { toDisposable, IDisposable } from 'vs/base/common/lifecycle';
import { toDisposable, IDisposable } from 'common/Lifecycle';
export function observeDevicePixelDimensions(element: HTMLElement, parentWindow: Window & typeof globalThis, callback: (deviceWidth: number, deviceHeight: number) => void): IDisposable {
// Observe any resizes to the element and extract the actual pixel size of the element if the
+1 -1
View File
@@ -5,7 +5,7 @@
import { TextureAtlas } from './TextureAtlas';
import { IRenderDimensions } from 'browser/renderer/shared/Types';
import { NULL_CELL_CODE } from 'common/buffer/Constants';
import { Disposable, toDisposable } from 'vs/base/common/lifecycle';
import { Disposable, toDisposable } from 'common/Lifecycle';
import { Terminal } from '@xterm/xterm';
import { IRenderModel, IWebGL2RenderingContext, IWebGLVertexArrayObject, type IRasterizedGlyph, type ITextureAtlas } from './Types';
import { createProgram, GLTexture, PROJECTION_MATRIX } from './WebglUtils';
+1 -1
View File
@@ -7,7 +7,7 @@ import { IRenderDimensions } from 'browser/renderer/shared/Types';
import { IThemeService } from 'browser/services/Services';
import { ReadonlyColorSet } from 'browser/Types';
import { Attributes, FgFlags } from 'common/buffer/Constants';
import { Disposable, toDisposable } from 'vs/base/common/lifecycle';
import { Disposable, toDisposable } from 'common/Lifecycle';
import { IColor } from 'common/Types';
import { Terminal } from '@xterm/xterm';
import { RENDER_MODEL_BG_OFFSET, RENDER_MODEL_FG_OFFSET, RENDER_MODEL_INDICIES_PER_CELL } from './RenderModel';
+19 -6
View File
@@ -14,8 +14,8 @@ import { IdleTaskQueue } from 'common/TaskQueue';
import { IColor } from 'common/Types';
import { AttributeData } from 'common/buffer/AttributeData';
import { Attributes, DEFAULT_COLOR, DEFAULT_EXT, UnderlineStyle } from 'common/buffer/Constants';
import { IUnicodeService } from 'common/services/Services';
import { Emitter } from 'vs/base/common/event';
import { ILogService, IUnicodeService } from 'common/services/Services';
import { Emitter } from 'common/Event';
/**
* A shared object which is used to draw nothing for a particular cell.
@@ -88,7 +88,8 @@ export class TextureAtlas implements ITextureAtlas {
constructor(
private readonly _document: Document,
private readonly _config: ICharAtlasConfig,
private readonly _unicodeService: IUnicodeService
private readonly _unicodeService: IUnicodeService,
private readonly _logService: ILogService
) {
this._createNewPage();
this._tmpCanvas = createCanvas(
@@ -119,7 +120,7 @@ export class TextureAtlas implements ITextureAtlas {
private _doWarmUp(): void {
// Pre-fill with ASCII 33-126, this is not urgent and done in idle callbacks
const queue = new IdleTaskQueue();
const queue = new IdleTaskQueue(this._logService);
for (let i = 33; i < 126; i++) {
queue.enqueue(() => {
if (!this._cacheMap.get(i, DEFAULT_COLOR, DEFAULT_COLOR, DEFAULT_EXT)) {
@@ -176,6 +177,17 @@ export class TextureAtlas implements ITextureAtlas {
// Gather details of the merge
const mergingPages = pagesBySize.slice(sameSizeI, sameSizeI + 4);
// Only proceed with merge if we have exactly 4 same-sized pages. If not, we cannot
// effectively reduce page count and merging would cause issues.
if (mergingPages.length < 4 || mergingPages.some(p => p.canvas.width !== mergingPages[0].canvas.width)) {
const newPage = new AtlasPage(this._document, this._textureSize);
this._pages.push(newPage);
this._activePages.push(newPage);
this._onAddTextureAtlasCanvas.fire(newPage.canvas);
return newPage;
}
const sortedMergingPagesIndexes = mergingPages.map(e => e.glyphs[0].texturePage).sort((a, b) => a > b ? 1 : -1);
const mergedPageIndex = this.pages.length - mergingPages.length;
@@ -399,7 +411,7 @@ export class TextureAtlas implements ITextureAtlas {
const cache = this._getContrastCache(dim);
const adjustedColor = cache.getColor(bg, fg);
if (adjustedColor !== undefined) {
return adjustedColor || undefined;
return adjustedColor ?? undefined;
}
const bgRgba = this._resolveBackgroundRgba(bgColorMode, bgColor, inverse);
@@ -514,7 +526,8 @@ export class TextureAtlas implements ITextureAtlas {
// Draw custom characters if applicable
let customGlyph = false;
if (this._config.customGlyphs !== false) {
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);
const variantOffset = this._workAttributeData.getUnderlineVariantOffset();
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, variantOffset);
}
// Whether to clear pixels based on a threshold difference between the glyph color and the
+3 -3
View File
@@ -7,7 +7,7 @@ import { FontWeight } from '@xterm/xterm';
import { IColorSet } from 'browser/Types';
import { ISelectionRenderModel } from 'browser/renderer/shared/Types';
import { CursorInactiveStyle, CursorStyle, type IDisposable } from 'common/Types';
import type { Event } from 'vs/base/common/event';
import type { IEvent } from 'common/Event';
export interface IRenderModel {
cells: Uint32Array;
@@ -58,8 +58,8 @@ export interface ICharAtlasConfig {
export interface ITextureAtlas extends IDisposable {
readonly pages: { canvas: HTMLCanvasElement, version: number }[];
onAddTextureAtlasCanvas: Event<HTMLCanvasElement>;
onRemoveTextureAtlasCanvas: Event<HTMLCanvasElement>;
onAddTextureAtlasCanvas: IEvent<HTMLCanvasElement>;
onRemoveTextureAtlasCanvas: IEvent<HTMLCanvasElement>;
/**
* Warm up the texture atlas, adding common glyphs to avoid slowing early frame.
+8 -14
View File
@@ -7,15 +7,14 @@ import type { ITerminalAddon, Terminal } from '@xterm/xterm';
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';
import { Disposable, toDisposable } from 'common/Lifecycle';
import { getSafariVersion, isSafari } from 'common/Platform';
import { ICoreService, IDecorationService, ILogService, IOptionsService } from 'common/services/Services';
import { ICoreService, IDecorationService, IOptionsService } from 'common/services/Services';
import { IWebGL2RenderingContext } from './Types';
import { WebglRenderer } from './WebglRenderer';
import { setTraceLogger } from 'common/services/LogService';
import { Emitter, Event } from 'vs/base/common/event';
import { Emitter, EventUtils } from 'common/Event';
export class WebglAddon extends Disposable implements ITerminalAddon , IWebglApi {
export class WebglAddon extends Disposable implements ITerminalAddon, IWebglApi {
private _terminal?: Terminal;
private _renderer?: WebglRenderer;
@@ -66,13 +65,8 @@ export class WebglAddon extends Disposable implements ITerminalAddon , IWebglApi
const charSizeService: ICharSizeService = unsafeCore._charSizeService;
const coreBrowserService: ICoreBrowserService = unsafeCore._coreBrowserService;
const decorationService: IDecorationService = unsafeCore._decorationService;
const logService: ILogService = unsafeCore._logService;
const themeService: IThemeService = unsafeCore._themeService;
// Set trace logger just in case it hasn't been yet which could happen when the addon is
// bundled separately to the core module
setTraceLogger(logService);
this._renderer = this._register(new WebglRenderer(
terminal,
characterJoinerService,
@@ -85,10 +79,10 @@ export class WebglAddon extends Disposable implements ITerminalAddon , IWebglApi
this._customGlyphs,
this._preserveDrawingBuffer
));
this._register(Event.forward(this._renderer.onContextLoss, this._onContextLoss));
this._register(Event.forward(this._renderer.onChangeTextureAtlas, this._onChangeTextureAtlas));
this._register(Event.forward(this._renderer.onAddTextureAtlasCanvas, this._onAddTextureAtlasCanvas));
this._register(Event.forward(this._renderer.onRemoveTextureAtlasCanvas, this._onRemoveTextureAtlasCanvas));
this._register(EventUtils.forward(this._renderer.onContextLoss, this._onContextLoss));
this._register(EventUtils.forward(this._renderer.onChangeTextureAtlas, this._onChangeTextureAtlas));
this._register(EventUtils.forward(this._renderer.onAddTextureAtlasCanvas, this._onAddTextureAtlasCanvas));
this._register(EventUtils.forward(this._renderer.onRemoveTextureAtlasCanvas, this._onRemoveTextureAtlasCanvas));
renderService.setRenderer(this._renderer);
this._register(toDisposable(() => {
+54 -8
View File
@@ -13,7 +13,8 @@ import { ICharSizeService, ICharacterJoinerService, ICoreBrowserService, IThemeS
import { CharData, IBufferLine, ICellData } from 'common/Types';
import { AttributeData } from 'common/buffer/AttributeData';
import { CellData } from 'common/buffer/CellData';
import { Attributes, Content, NULL_CELL_CHAR, NULL_CELL_CODE } from 'common/buffer/Constants';
import { Attributes, Content, FgFlags, NULL_CELL_CHAR, NULL_CELL_CODE } from 'common/buffer/Constants';
import { TextBlinkStateManager } from 'browser/renderer/shared/TextBlinkStateManager';
import { ICoreService, IDecorationService, IOptionsService } from 'common/services/Services';
import { Terminal } from '@xterm/xterm';
import { GlyphRenderer } from './GlyphRenderer';
@@ -22,14 +23,15 @@ import { COMBINED_CHAR_BIT_MASK, RENDER_MODEL_BG_OFFSET, RENDER_MODEL_EXT_OFFSET
import { IWebGL2RenderingContext, type ITextureAtlas } from './Types';
import { LinkRenderLayer } from './renderLayer/LinkRenderLayer';
import { IRenderLayer } from './renderLayer/Types';
import { Emitter, Event } from 'vs/base/common/event';
import { addDisposableListener } from 'vs/base/browser/dom';
import { combinedDisposable, Disposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { Emitter, EventUtils } from 'common/Event';
import { addDisposableListener } from 'browser/Dom';
import { combinedDisposable, Disposable, MutableDisposable, toDisposable } from 'common/Lifecycle';
import { createRenderDimensions } from 'browser/renderer/shared/RendererUtils';
export class WebglRenderer extends Disposable implements IRenderer {
private _renderLayers: IRenderLayer[];
private _cursorBlinkStateManager: MutableDisposable<CursorBlinkStateManager> = new MutableDisposable();
private _textBlinkStateManager: TextBlinkStateManager;
private _charAtlasDisposable = this._register(new MutableDisposable());
private _charAtlas: ITextureAtlas | undefined;
private _devicePixelRatio: number;
@@ -37,8 +39,9 @@ export class WebglRenderer extends Disposable implements IRenderer {
private _observerDisposable = this._register(new MutableDisposable());
private _model: RenderModel = new RenderModel();
private _rowHasBlinkingCells: boolean[] = [];
private _rowHasBlinkingCellsCount: number = 0;
private _workCell: ICellData = new CellData();
private _workCell2: ICellData = new CellData();
private _cellColorResolver: CellColorResolver;
private _canvas: HTMLCanvasElement;
@@ -105,6 +108,12 @@ export class WebglRenderer extends Disposable implements IRenderer {
this._updateDimensions();
this._updateCursorBlink();
this._register(_optionsService.onOptionChange(() => this._handleOptionsChanged()));
this._textBlinkStateManager = this._register(new TextBlinkStateManager(
() => this._requestRedrawViewport(),
this._coreBrowserService,
this._optionsService
));
this._resetBlinkingRowState();
this._deviceMaxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
@@ -178,6 +187,7 @@ export class WebglRenderer extends Disposable implements IRenderer {
this._updateDimensions();
this._model.resize(this._terminal.cols, this._terminal.rows);
this._resetBlinkingRowState();
// Resize all render layers
for (const l of this._renderLayers) {
@@ -231,6 +241,10 @@ export class WebglRenderer extends Disposable implements IRenderer {
this._requestRedrawViewport();
}
public handleViewportVisibilityChange(isVisible: boolean): void {
this._textBlinkStateManager.setViewportVisible(isVisible);
}
public handleSelectionChanged(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void {
for (const l of this._renderLayers) {
l.handleSelectionChanged(this._terminal, start, end, columnSelectMode);
@@ -290,8 +304,8 @@ export class WebglRenderer extends Disposable implements IRenderer {
if (this._charAtlas !== atlas) {
this._onChangeTextureAtlas.fire(atlas.pages[0].canvas);
this._charAtlasDisposable.value = combinedDisposable(
Event.forward(atlas.onAddTextureAtlasCanvas, this._onAddTextureAtlasCanvas),
Event.forward(atlas.onRemoveTextureAtlasCanvas, this._onRemoveTextureAtlasCanvas)
EventUtils.forward(atlas.onAddTextureAtlasCanvas, this._onAddTextureAtlasCanvas),
EventUtils.forward(atlas.onRemoveTextureAtlasCanvas, this._onRemoveTextureAtlasCanvas)
);
}
this._charAtlas = atlas;
@@ -323,6 +337,9 @@ export class WebglRenderer extends Disposable implements IRenderer {
l.reset(this._terminal);
}
this._resetBlinkingRowState();
this._textBlinkStateManager.setNeedsBlinkInViewport(false);
this._cursorBlinkStateManager.value?.restartBlinkAnimation();
this._updateCursorBlink();
}
@@ -420,6 +437,7 @@ export class WebglRenderer extends Disposable implements IRenderer {
for (y = start; y <= end; y++) {
row = y + terminal.buffer.ydisp;
line = terminal.buffer.lines.get(row)!;
let rowHasBlinkingCells = false;
this._model.lineLengths[y] = 0;
isCursorRow = cursorY === row;
skipJoinedCheckUntilX = 0;
@@ -477,8 +495,12 @@ export class WebglRenderer extends Disposable implements IRenderer {
code = cell.getCode();
i = ((y * terminal.cols) + x) * RENDER_MODEL_INDICIES_PER_CELL;
if (!rowHasBlinkingCells && cell.isBlink()) {
rowHasBlinkingCells = true;
}
// Load colors/resolve overrides into work colors
this._cellColorResolver.resolve(cell, x, row, this.dimensions.device.cell.width);
this._cellColorResolver.resolve(cell, x, row, this.dimensions.device.cell.width, this.dimensions.device.cell.height);
// Override colors for cursor cell
if (isCursorVisible && row === cursorY) {
@@ -506,6 +528,10 @@ export class WebglRenderer extends Disposable implements IRenderer {
}
}
if (this._textBlinkStateManager.isEnabled && !this._textBlinkStateManager.isBlinkOn && cell.isBlink()) {
this._cellColorResolver.result.fg |= FgFlags.INVISIBLE;
}
if (code !== NULL_CELL_CODE) {
this._model.lineLengths[y] = x + 1;
}
@@ -552,11 +578,31 @@ export class WebglRenderer extends Disposable implements IRenderer {
x--; // Go back to the previous update cell for next iteration
}
}
this._setRowBlinkState(y, rowHasBlinkingCells);
}
if (modelUpdated) {
this._rectangleRenderer.value!.updateBackgrounds(this._model);
}
this._rectangleRenderer.value!.updateCursor(this._model);
this._updateTextBlinkState();
}
private _resetBlinkingRowState(): void {
this._rowHasBlinkingCells = new Array(this._terminal.rows).fill(false);
this._rowHasBlinkingCellsCount = 0;
}
private _setRowBlinkState(row: number, hasBlinkingCells: boolean): void {
const previous = this._rowHasBlinkingCells[row];
if (previous === hasBlinkingCells) {
return;
}
this._rowHasBlinkingCells[row] = hasBlinkingCells;
this._rowHasBlinkingCellsCount += hasBlinkingCells ? 1 : -1;
}
private _updateTextBlinkState(): void {
this._textBlinkStateManager.setNeedsBlinkInViewport(this._rowHasBlinkingCellsCount > 0);
}
/**
@@ -644,8 +644,8 @@ export const customGlyphDefinitions: { [index: string]: CustomGlyphCharacterDefi
] },
// Diagonal fill characters (1FB98-1FB99)
'\u{1FB98}': { type: CustomGlyphDefinitionType.PATH_FUNCTION, data: 'M0,0 L1,1 M0,.25 L.75,1 M0,.5 L.5,1 M0,.75 L.25,1 M.25,0 L1,.75 M.5,0 L1,.5 M.75,0 L1,.25', strokeWidth: 1 }, // UPPER LEFT TO LOWER RIGHT FILL
'\u{1FB99}': { type: CustomGlyphDefinitionType.PATH_FUNCTION, data: 'M0,.25 L.25,0 M0,.5 L.5,0 M0,.75 L.75,0 M0,1 L1,0 M.25,1 L1,.25 M.5,1 L1,.5 M.75,1 L1,.75', strokeWidth: 1 }, // UPPER RIGHT TO LOWER LEFT FILL
'\u{1FB98}': { type: CustomGlyphDefinitionType.PATH_FUNCTION, data: 'M-0.25,-0.25 L1.25,1.25 M-0.25,0 L1,1.25 M-0.25,0.25 L0.75,1.25 M-0.25,0.5 L0.5,1.25 M0,-0.25 L1.25,1 M0.25,-0.25 L1.25,0.75 M0.5,-0.25 L1.25,0.5 M-0.25,0.75 L0.25,1.25 M0.75,-0.25 L1.25,0.25', strokeWidth: 1 }, // UPPER LEFT TO LOWER RIGHT FILL
'\u{1FB99}': { type: CustomGlyphDefinitionType.PATH_FUNCTION, data: 'M-0.25,0.5 L0.5,-0.25 M-0.25,0.75 L0.75,-0.25 M-0.25,1 L1,-0.25 M-0.25,1.25 L1.25,-0.25 M0,1.25 L1.25,0 M0.25,1.25 L1.25,0.25 M0.5,1.25 L1.25,0.5 M-0.25,0.25 L0.25,-0.25 M0.75,1.25 L1.25,0.75', strokeWidth: 1 }, // UPPER RIGHT TO LOWER LEFT FILL
// Smooth mosaic terminal graphic characters (1FB9A-1FB9B)
'\u{1FB9A}': { type: CustomGlyphDefinitionType.VECTOR_SHAPE, data: { d: 'M0,0 L.5,.5 L0,1 L1,1 L.5,.5 L1,0', type: CustomGlyphVectorType.FILL } }, // UPPER AND LOWER TRIANGULAR HALF BLOCK
@@ -820,6 +820,27 @@ export const customGlyphDefinitions: { [index: string]: CustomGlyphCharacterDefi
// #endregion
};
export const blockPatternCodepoints = new Set<number>([
// Shade characters (2591-2593)
0x2591,
0x2592,
0x2593,
// Rectangular shade characters (1FB8C-1FB94)
0x1FB8C,
0x1FB8D,
0x1FB8E,
0x1FB8F,
0x1FB90,
0x1FB91,
0x1FB92,
0x1FB94,
// Triangular shade characters (1FB9C-1FB9F)
0x1FB9C,
0x1FB9D,
0x1FB9E,
0x1FB9F
]);
/**
* Generates a drawing function for sextant characters. Sextants are a 2x3 grid where each cell
* can be on or off.
@@ -22,14 +22,15 @@ export function tryDrawCustomGlyph(
deviceCharHeight: number,
fontSize: number,
devicePixelRatio: number,
backgroundColor?: string
backgroundColor?: string,
variantOffset: number = 0
): boolean {
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);
drawDefinitionPart(ctx, part, xOffset, yOffset, deviceCellWidth, deviceCellHeight, deviceCharWidth, deviceCharHeight, fontSize, devicePixelRatio, backgroundColor, variantOffset);
}
return true;
}
@@ -48,7 +49,8 @@ function drawDefinitionPart(
deviceCharHeight: number,
fontSize: number,
devicePixelRatio: number,
backgroundColor?: string
backgroundColor?: string,
variantOffset: number = 0
): void {
// Handle scaleType - adjust dimensions and offset when scaling to character area
let drawWidth = deviceCellWidth;
@@ -74,7 +76,7 @@ function drawDefinitionPart(
drawBlockVectorChar(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight);
break;
case CustomGlyphDefinitionType.BLOCK_PATTERN:
drawPatternChar(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight);
drawPatternChar(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight, variantOffset);
break;
case CustomGlyphDefinitionType.PATH_FUNCTION:
drawPathFunctionCharacter(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight, devicePixelRatio, part.strokeWidth);
@@ -437,7 +439,8 @@ function drawPatternChar(
xOffset: number,
yOffset: number,
deviceCellWidth: number,
deviceCellHeight: number
deviceCellHeight: number,
variantOffset: number = 0
): void {
let patternSet = cachedPatterns.get(charDefinition);
if (!patternSet) {
@@ -486,6 +489,15 @@ function drawPatternChar(
pattern = throwIfFalsy(ctx.createPattern(tmpCanvas, null));
patternSet.set(fillStyle, pattern);
}
// Apply pattern offset to ensure seamless tiling across cells when cell dimensions are odd.
// variantOffset encodes: bit 1 = x pixel shift, bit 0 = y pixel shift.
const dx = (variantOffset >> 1) & 1;
const dy = variantOffset & 1;
if (dx !== 0 || dy !== 0) {
pattern.setTransform(new DOMMatrix().translateSelf(-dx, -dy));
} else {
pattern.setTransform(new DOMMatrix());
}
ctx.fillStyle = pattern;
ctx.fillRect(xOffset, yOffset, deviceCellWidth, deviceCellHeight);
}
@@ -500,6 +512,11 @@ function drawPathFunctionCharacter(
devicePixelRatio: number,
strokeWidth?: number
): void {
ctx.save();
ctx.beginPath();
ctx.rect(xOffset, yOffset, deviceCellWidth, deviceCellHeight);
ctx.clip();
ctx.beginPath();
let actualInstructions: string;
if (typeof charDefinition === 'function') {
@@ -526,7 +543,7 @@ function drawPathFunctionCharacter(
if (!args[0] || !args[1]) {
continue;
}
f(ctx, translateArgs(args, deviceCellWidth, deviceCellHeight, xOffset, yOffset, true, devicePixelRatio), state);
f(ctx, translateArgs(args, deviceCellWidth, deviceCellHeight, xOffset, yOffset, true, devicePixelRatio, 0, 0, false), state);
state.lastCommand = type;
}
if (strokeWidth !== undefined) {
@@ -537,6 +554,7 @@ function drawPathFunctionCharacter(
ctx.fill();
}
ctx.closePath();
ctx.restore();
}
/**
@@ -685,7 +703,7 @@ const svgToCanvasInstructionMap: { [index: string]: (ctx: CanvasRenderingContext
}
};
function translateArgs(args: string[], cellWidth: number, cellHeight: number, xOffset: number, yOffset: number, doClamp: boolean, devicePixelRatio: number, leftPadding: number = 0, rightPadding: number = 0): number[] {
function translateArgs(args: string[], cellWidth: number, cellHeight: number, xOffset: number, yOffset: number, doClamp: boolean, devicePixelRatio: number, leftPadding: number = 0, rightPadding: number = 0, clampToCell: boolean = true): number[] {
const result = args.map(e => parseFloat(e) || parseInt(e));
if (result.length < 2) {
@@ -695,10 +713,11 @@ function translateArgs(args: string[], cellWidth: number, cellHeight: number, xO
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
// Round to the nearest 0.5 to ensure a crisp line at 100% devicePixelRatio, and optionally
// clamp to the cell bounds.
if (doClamp && result[x] !== 0) {
result[x] = clamp(Math.round(result[x] + 0.5) - 0.5, cellWidth, 0);
const rounded = Math.round(result[x] + 0.5) - 0.5;
result[x] = clampToCell ? clamp(rounded, cellWidth, 0) : rounded;
}
// Apply the cell's offset (ie. x*cellWidth)
result[x] += xOffset + (leftPadding * devicePixelRatio);
@@ -707,10 +726,11 @@ function translateArgs(args: string[], cellWidth: number, cellHeight: number, xO
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
// Round to the nearest 0.5 to ensure a crisp line at 100% devicePixelRatio, and optionally
// clamp to the cell bounds.
if (doClamp && result[y] !== 0) {
result[y] = clamp(Math.round(result[y] + 0.5) - 0.5, cellHeight, 0);
const rounded = Math.round(result[y] + 0.5) - 0.5;
result[y] = clampToCell ? clamp(rounded, cellHeight, 0) : rounded;
}
// Apply the cell's offset (ie. x*cellHeight)
result[y] += yOffset;
@@ -7,7 +7,7 @@ import { ReadonlyColorSet } from 'browser/Types';
import { acquireTextureAtlas } from '../CharAtlasCache';
import { IRenderDimensions } from 'browser/renderer/shared/Types';
import { ICoreBrowserService, IThemeService } from 'browser/services/Services';
import { Disposable, toDisposable } from 'vs/base/common/lifecycle';
import { Disposable, toDisposable } from 'common/Lifecycle';
import { CellData } from 'common/buffer/CellData';
import { IOptionsService } from 'common/services/Services';
import { Terminal } from '@xterm/xterm';
-6
View File
@@ -18,9 +18,6 @@
"browser/*": [
"../../../src/browser/*"
],
"vs/*": [
"../../../src/vs/*"
],
"@xterm/addon-webgl": [
"../typings/addon-webgl.d.ts"
]
@@ -42,9 +39,6 @@
},
{
"path": "../../../src/browser"
},
{
"path": "../../../src/vs"
}
]
}
+2 -3
View File
@@ -5,10 +5,9 @@ const config: PlaywrightTestConfig = {
timeout: 10000,
projects: [
{
name: 'ChromeStable',
name: 'Chromium',
use: {
browserName: 'chromium',
channel: 'chrome'
browserName: 'chromium'
}
},
{
+42
View File
@@ -0,0 +1,42 @@
/**
* Copyright (c) 2026 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { spawnSync } from 'child_process';
import { copyFileSync, mkdirSync, renameSync } from 'fs';
import path from 'path';
import process from 'process';
import { fileURLToPath } from 'url';
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const ghosttyDir = path.join(repoRoot, 'vendor', 'ghostty');
const wasmOutDir = path.join(repoRoot, 'vendor', 'ghostty-wasm');
const wasmBinDir = path.join(wasmOutDir, 'bin');
const wasmFile = path.join(wasmOutDir, 'ghostty-vt.wasm');
const wasmBinFile = path.join(wasmBinDir, 'ghostty-vt.wasm');
mkdirSync(wasmOutDir, { recursive: true });
const result = spawnSync('zig', [
'build',
'lib-vt',
'-Dtarget=wasm32-freestanding',
'-Doptimize=ReleaseSmall',
'-p',
path.relative(ghosttyDir, wasmOutDir)
], {
cwd: ghosttyDir,
stdio: 'inherit',
shell: true
});
if (result.status !== 0) {
process.exit(result.status ?? 1);
}
try {
renameSync(wasmBinFile, wasmFile);
} catch {
copyFileSync(wasmBinFile, wasmFile);
}
+2 -3
View File
@@ -127,6 +127,7 @@ if (config.addon) {
} else if (config.isDemoClient) {
bundleConfig = {
...bundleConfig,
sourcemap: false,
entryPoints: [`demo/client/client.ts`],
outfile: 'demo/dist/client-bundle.js',
external: ['util', 'os', 'fs', 'path', 'stream', 'Terminal'],
@@ -190,9 +191,7 @@ if (config.addon) {
entryPoints: [
'src/browser/**/*.ts',
'src/common/**/*.ts',
'src/headless/**/*.ts',
'src/vs/base/**/*.ts',
'src/vs/patches/**/*.ts'
'src/headless/**/*.ts'
],
outdir: 'out-esbuild/'
};
+3
View File
@@ -6,6 +6,9 @@
const cp = require('child_process');
const path = require('path');
globalThis.require = require;
globalThis.XTERM_GHOSTTY_WASM_URL = path.resolve(__dirname, '../vendor/ghostty-wasm/ghostty-vt.wasm');
const COVERAGE_LINES_THRESHOLD = 40;
// Add `out` to the NODE_PATH so absolute paths can be resolved.
+24 -11
View File
@@ -218,17 +218,30 @@
/* Derived from vs/base/browser/ui/scrollbar/media/scrollbar.css */
/* xterm.js customization: Override xterm's cursor style */
.xterm .xterm-scrollable-element > .scrollbar {
.xterm .xterm-scrollable-element > .xterm-scrollbar {
cursor: default;
}
/* Arrows */
.xterm .xterm-scrollable-element > .scrollbar > .scra {
.xterm .xterm-scrollable-element > .xterm-scrollbar > .xterm-scra {
cursor: pointer;
font-size: 11px !important;
background-color: var(--vscode-scrollbarSliderBackground, rgba(100, 100, 100, 0.4));
mask-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 11 11'><path d='M2.5 8.5 L5.5 2.5 L8.5 8.5 Z' fill='black'/></svg>");
-webkit-mask-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 11 11'><path d='M2.5 8.5 L5.5 2.5 L8.5 8.5 Z' fill='black'/></svg>");
mask-repeat: no-repeat;
-webkit-mask-repeat: no-repeat;
mask-position: center center;
-webkit-mask-position: center center;
mask-size: 100% 100%;
-webkit-mask-size: 100% 100%;
}
.xterm .xterm-scrollable-element > .visible {
.xterm .xterm-scrollable-element > .xterm-scrollbar > .xterm-scra.xterm-arrow-down {
transform: rotate(180deg);
}
.xterm .xterm-scrollable-element > .xterm-visible {
opacity: 1;
/* Background rule added for IE9 - to allow clicks on dom node */
@@ -238,20 +251,20 @@
/* In front of peek view */
z-index: 11;
}
.xterm .xterm-scrollable-element > .invisible {
.xterm .xterm-scrollable-element > .xterm-invisible {
opacity: 0;
pointer-events: none;
}
.xterm .xterm-scrollable-element > .invisible.fade {
.xterm .xterm-scrollable-element > .xterm-invisible.xterm-fade {
transition: opacity 800ms linear;
}
/* Scrollable Content Inset Shadow */
.xterm .xterm-scrollable-element > .shadow {
.xterm .xterm-scrollable-element > .xterm-shadow {
position: absolute;
display: none;
}
.xterm .xterm-scrollable-element > .shadow.top {
.xterm .xterm-scrollable-element > .xterm-shadow.xterm-shadow-top {
display: block;
top: 0;
left: 3px;
@@ -259,7 +272,7 @@
width: 100%;
box-shadow: var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset;
}
.xterm .xterm-scrollable-element > .shadow.left {
.xterm .xterm-scrollable-element > .xterm-shadow.xterm-shadow-left {
display: block;
top: 3px;
left: 0;
@@ -267,13 +280,13 @@
width: 3px;
box-shadow: var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset;
}
.xterm .xterm-scrollable-element > .shadow.top-left-corner {
.xterm .xterm-scrollable-element > .xterm-shadow.xterm-shadow-top-left-corner {
display: block;
top: 0;
left: 0;
height: 3px;
width: 3px;
}
.xterm .xterm-scrollable-element > .shadow.top.left {
.xterm .xterm-scrollable-element > .xterm-shadow.xterm-shadow-top.xterm-shadow-left {
box-shadow: var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset;
}
+99 -80
View File
@@ -16,9 +16,12 @@ if ('WebAssembly' in window) {
import { Terminal, ITerminalOptions, type ITheme } from '@xterm/xterm';
import { AttachAddon } from '@xterm/addon-attach';
import { AddonImageWindow } from './components/window/addonImageWindow';
import { AddonLigaturesWindow } from './components/window/addonLigaturesWindow';
import { AddonProgressWindow } from './components/window/addonProgressWindow';
import { AddonSearchWindow } from './components/window/addonSearchWindow';
import { AddonSerializeWindow } from './components/window/addonSerializeWindow';
import { AddonWebFontsWindow } from './components/window/addonWebFontsWindow';
import { AddonWebLinksWindow } from './components/window/addonWebLinksWindow';
import { AddonsWindow } from './components/window/addonsWindow';
import { CellInspectorWindow } from './components/window/cellInspectorWindow';
import { ControlBar } from './components/controlBar';
@@ -58,11 +61,11 @@ export interface IWindowWithTerminal extends Window {
}
declare let window: IWindowWithTerminal;
let term;
let protocol;
let socketURL;
let socket;
let pid;
let term: Terminal | null;
let protocol: string;
let socketURL: string;
let socket: WebSocket | null;
let pid: string;
let controlBar: ControlBar;
let addonsWindow: AddonsWindow;
let addonSearchWindow: AddonSearchWindow;
@@ -73,7 +76,7 @@ const addons: AddonCollection = {
attach: { name: 'attach', ctor: AttachAddon, canChange: false },
clipboard: { name: 'clipboard', ctor: ClipboardAddon, canChange: true },
fit: { name: 'fit', ctor: FitAddon, canChange: false },
image: { name: 'image', ctor: ImageAddon, canChange: true },
image: { name: 'image', ctor: ImageAddon!, canChange: true },
progress: { name: 'progress', ctor: ProgressAddon, canChange: true },
search: { name: 'search', ctor: SearchAddon, canChange: true },
serialize: { name: 'serialize', ctor: SerializeAddon, canChange: true },
@@ -116,8 +119,8 @@ const xtermjsTheme = {
brightWhite: '#FFFFFF'
} satisfies ITheme;
function setPadding(): void {
term.element.style.padding = parseInt(paddingElement.value, 10).toString() + 'px';
addons.fit.instance.fit();
term!.element!.style.padding = parseInt(paddingElement.value, 10).toString() + 'px';
addons.fit.instance!.fit();
}
function getSearchOptions(): ISearchOptions {
@@ -141,7 +144,7 @@ const disposeRecreateButtonHandler: () => void = () => {
if (term) {
term.dispose();
term = null;
window.term = null;
(window as any).term = null;
socket = null;
addons.attach.instance = undefined;
addons.clipboard.instance = undefined;
@@ -154,10 +157,10 @@ const disposeRecreateButtonHandler: () => void = () => {
addons.ligatures.instance = undefined;
addons.webLinks.instance = undefined;
addons.webgl.instance = undefined;
document.getElementById('dispose').innerHTML = 'Recreate Terminal';
document.getElementById('dispose')!.innerHTML = 'Recreate Terminal';
} else {
createTerminal();
document.getElementById('dispose').innerHTML = 'Dispose terminal';
document.getElementById('dispose')!.innerHTML = 'Dispose terminal';
}
};
@@ -165,7 +168,7 @@ const createNewWindowButtonHandler: () => void = () => {
if (term) {
disposeRecreateButtonHandler();
}
const win = window.open();
const win = window.open()!;
terminalContainer = win.document.createElement('div');
terminalContainer.id = 'terminal-container';
win.document.body.appendChild(terminalContainer);
@@ -207,17 +210,20 @@ if (document.location.pathname === '/test') {
} else {
const typedTerm = createTerminal();
controlBar = new ControlBar(document.getElementById('sidebar'), document.querySelector('.banner-tabs'), []);
controlBar = new ControlBar(document.getElementById('sidebar')!, document.querySelector('.banner-tabs')!, []);
optionsWindow = controlBar.registerWindow(new OptionsWindow(typedTerm, addons, { updateTerminalSize, updateTerminalContainerBackground }));
const styleWindow = controlBar.registerWindow(new StyleWindow(typedTerm, addons));
controlBar.registerWindow(new CellInspectorWindow(typedTerm, addons));
controlBar.registerWindow(new VtWindow(typedTerm, addons));
addonsWindow = controlBar.registerWindow(new AddonsWindow(typedTerm, addons));
addonSearchWindow = controlBar.registerWindow(new AddonSearchWindow(typedTerm, addons), { afterId: 'addons', hidden: true, italics: true });
controlBar.registerWindow(new AddonImageWindow(typedTerm, addons), { afterId: 'addons', hidden: true, italics: true });
controlBar.registerWindow(new AddonLigaturesWindow(typedTerm, addons), { afterId: 'addon-image', hidden: true, italics: true });
controlBar.registerWindow(new AddonProgressWindow(typedTerm, addons), { afterId: 'addon-ligatures', hidden: true, italics: true });
addonSearchWindow = controlBar.registerWindow(new AddonSearchWindow(typedTerm, addons), { afterId: 'addon-progress', hidden: true, italics: true });
controlBar.registerWindow(new AddonSerializeWindow(typedTerm, addons), { afterId: 'addon-search', hidden: true, italics: true });
controlBar.registerWindow(new AddonImageWindow(typedTerm, addons), { afterId: 'addon-serialize', hidden: true, italics: true });
controlBar.registerWindow(new AddonWebFontsWindow(typedTerm, addons), { afterId: 'addon-image', hidden: true, italics: true });
addonWebglWindow = controlBar.registerWindow(new WebglWindow(typedTerm, addons), { afterId: 'addon-web-fonts', hidden: true, italics: true });
controlBar.registerWindow(new AddonWebFontsWindow(typedTerm, addons), { afterId: 'addon-serialize', hidden: true, italics: true });
controlBar.registerWindow(new AddonWebLinksWindow(typedTerm, addons), { afterId: 'addon-web-fonts', hidden: true, italics: true });
addonWebglWindow = controlBar.registerWindow(new WebglWindow(typedTerm, addons), { afterId: 'addon-web-links', hidden: true, italics: true });
controlBar.registerWindow(new TestWindow(typedTerm, addons, { disposeRecreateButtonHandler, createNewWindowButtonHandler }), { afterId: 'options' });
actionElements = {
findNext: addonSearchWindow.findNextInput,
@@ -229,52 +235,56 @@ if (document.location.pathname === '/test') {
// TODO: Most of below should be encapsulated within windows
paddingElement = styleWindow.paddingElement;
controlBar.setTabVisible('addon-webgl', true);
controlBar.setTabVisible('addon-image', !!addons.image.instance);
controlBar.setTabVisible('addon-ligatures', !!addons.ligatures.instance);
controlBar.setTabVisible('addon-progress', !!addons.progress.instance);
controlBar.setTabVisible('addon-search', true);
controlBar.setTabVisible('addon-serialize', true);
controlBar.setTabVisible('addon-image', true);
controlBar.setTabVisible('addon-web-fonts', true);
addonWebglWindow.setTextureAtlas(addons.webgl.instance.textureAtlas);
addons.webgl.instance.onChangeTextureAtlas(e => addonWebglWindow.setTextureAtlas(e));
addons.webgl.instance.onAddTextureAtlasCanvas(e => addonWebglWindow.appendTextureAtlas(e));
addons.webgl.instance.onRemoveTextureAtlasCanvas(e => addonWebglWindow.removeTextureAtlas(e));
controlBar.setTabVisible('addon-web-links', !!addons.webLinks.instance);
controlBar.setTabVisible('addon-webgl', true);
addonWebglWindow.setTextureAtlas(addons.webgl.instance!.textureAtlas!);
addons.webgl.instance!.onChangeTextureAtlas(e => addonWebglWindow.setTextureAtlas(e));
addons.webgl.instance!.onAddTextureAtlasCanvas(e => addonWebglWindow.appendTextureAtlas(e));
addons.webgl.instance!.onRemoveTextureAtlasCanvas(e => addonWebglWindow.removeTextureAtlas(e));
paddingElement.value = '0';
addDomListener(paddingElement, 'change', setPadding);
addDomListener(actionElements.findNext, 'keydown', (e) => {
if (e.key === 'Enter') {
addons.search.instance.findNext(actionElements.findNext.value, getSearchOptions());
addons.search.instance!.findNext(actionElements.findNext.value, getSearchOptions());
e.preventDefault();
}
});
addDomListener(actionElements.findNext, 'input', (e) => {
addons.search.instance.findNext(actionElements.findNext.value, getSearchOptions());
addons.search.instance!.findNext(actionElements.findNext.value, getSearchOptions());
});
addDomListener(actionElements.findPrevious, 'keydown', (e) => {
if (e.key === 'Enter') {
addons.search.instance.findPrevious(actionElements.findPrevious.value, getSearchOptions());
addons.search.instance!.findPrevious(actionElements.findPrevious.value, getSearchOptions());
e.preventDefault();
}
});
addDomListener(actionElements.findPrevious, 'input', (e) => {
addons.search.instance.findPrevious(actionElements.findPrevious.value, getSearchOptions());
addons.search.instance!.findPrevious(actionElements.findPrevious.value, getSearchOptions());
});
addDomListener(actionElements.findNext, 'blur', (e) => {
addons.search.instance.clearActiveDecoration();
addons.search.instance!.clearActiveDecoration();
});
addDomListener(actionElements.findPrevious, 'blur', (e) => {
addons.search.instance.clearActiveDecoration();
addons.search.instance!.clearActiveDecoration();
});
}
function createTerminal(): Terminal {
// Clean terminal
while (terminalContainer.children.length) {
terminalContainer.removeChild(terminalContainer.children[0]);
while (terminalContainer!.children.length) {
terminalContainer!.removeChild(terminalContainer!.children[0]);
}
const isWindows = ['Windows', 'Win16', 'Win32', 'WinCE'].indexOf(navigator.platform) >= 0;
term = new Terminal({
scrollbar: { showScrollbar: true },
allowProposedApi: true,
windowsPty: isWindows ? {
// In a real scenario, these values should be verified on the backend
@@ -282,10 +292,7 @@ function createTerminal(): Terminal {
buildNumber: 22621
} : undefined,
fontFamily: '"Fira Code", monospace, "Powerline Extra Symbols"',
theme: { ...xtermjsTheme },
vtExtensions: {
win32InputMode: isWindows
}
theme: { ...xtermjsTheme }
} as ITerminalOptions);
// Load addons
@@ -293,7 +300,7 @@ function createTerminal(): Terminal {
addons.search.instance = new SearchAddon();
addons.serialize.instance = new SerializeAddon();
addons.fit.instance = new FitAddon();
addons.image.instance = new ImageAddon();
addons.image.instance = new ImageAddon!();
addons.progress.instance = new ProgressAddon();
addons.unicodeGraphemes.instance = new UnicodeGraphemesAddon();
addons.clipboard.instance = new ClipboardAddon();
@@ -314,7 +321,7 @@ function createTerminal(): Terminal {
typedTerm.loadAddon(addons.webFonts.instance);
typedTerm.loadAddon(addons.clipboard.instance);
window.term = term; // Expose `term` to window for debugging purposes
(window as any).term = term; // Expose `term` to window for debugging purposes
term.onResize((size: { cols: number, rows: number }) => {
if (!pid) {
return;
@@ -333,7 +340,7 @@ function createTerminal(): Terminal {
if (addons.webgl.instance) {
try {
typedTerm.loadAddon(addons.webgl.instance);
term.open(terminalContainer);
term.open(terminalContainer!);
} catch (e) {
console.warn('error during loading webgl addon:', e);
addons.webgl.instance.dispose();
@@ -342,7 +349,7 @@ function createTerminal(): Terminal {
}
if (!typedTerm.element) {
// webgl loading failed for some reason, attach with DOM renderer
term.open(terminalContainer);
term.open(terminalContainer!);
}
term.focus();
@@ -352,13 +359,13 @@ function createTerminal(): Terminal {
if (optionsWindow.autoResize) {
// In general this should be debounced to avoid excessive work on the main
// thread by firing the expensive resize action repeatedly
addons.fit.instance.fit();
addons.fit.instance!.fit();
}
});
resizeObserver.observe(terminalContainer);
resizeObserver.observe(terminalContainer!);
window.addEventListener('resize', () => {
terminalContainer.style.width = document.body.clientWidth + 'px';
terminalContainer!.style.width = document.body.clientWidth + 'px';
});
// fit is called within a setTimeout, cols and rows need this.
@@ -372,7 +379,7 @@ function createTerminal(): Terminal {
if (useRealTerminal instanceof HTMLInputElement && !useRealTerminal.checked) {
runFakeTerminal();
} else {
const res = await fetch('/terminals?cols=' + term.cols + '&rows=' + term.rows, { method: 'POST' });
const res = await fetch('/terminals?cols=' + term!.cols + '&rows=' + term!.rows, { method: 'POST' });
const processId = await res.text();
pid = processId;
socketURL += processId;
@@ -387,52 +394,52 @@ function createTerminal(): Terminal {
}
function runRealTerminal(): void {
addons.attach.instance = new AttachAddon(socket);
term.loadAddon(addons.attach.instance);
term._initialized = true;
initAddons(term);
addons.attach.instance = new AttachAddon(socket!);
term!.loadAddon(addons.attach.instance);
(term as any)._initialized = true;
initAddons(term!);
}
function runFakeTerminal(): void {
if (term._initialized) {
if ((term as any)._initialized) {
return;
}
term._initialized = true;
initAddons(term);
(term as any)._initialized = true;
initAddons(term!);
term.prompt = () => {
term.write('\r\n$ ');
(term as any).prompt = () => {
term!.write('\r\n$ ');
};
term.writeln('Welcome to xterm.js');
term.writeln('This is a local terminal emulation, without a real terminal in the back-end.');
term.writeln('Type some keys and commands to play around.');
term.writeln('');
term.prompt();
term!.writeln('Welcome to xterm.js');
term!.writeln('This is a local terminal emulation, without a real terminal in the back-end.');
term!.writeln('Type some keys and commands to play around.');
term!.writeln('');
(term as any).prompt();
term.onKey((e: { key: string, domEvent: KeyboardEvent }) => {
term!.onKey((e: { key: string, domEvent: KeyboardEvent }) => {
const ev = e.domEvent;
const printable = !ev.altKey && !ev.ctrlKey && !ev.metaKey;
if (ev.keyCode === 13) {
term.prompt();
(term as any).prompt();
} else if (ev.keyCode === 8) {
// Do not delete the prompt
if (term._core.buffer.x > 2) {
term.write('\b \b');
if ((term as any)._core.buffer.x > 2) {
term!.write('\b \b');
}
} else if (printable) {
term.write(e.key);
term!.write(e.key);
}
});
}
function updateTerminalContainerBackground(): void {
if (term.options.allowTransparency) {
terminalContainer.style.background = 'repeating-conic-gradient(#000000 0% 25%, #101010 0% 50%) 50% / 20px 20px';
if (term!.options.allowTransparency) {
terminalContainer!.style.background = 'repeating-conic-gradient(#000000 0% 25%, #101010 0% 50%) 50% / 20px 20px';
} else {
terminalContainer.style.background = term.options.theme?.background ?? '#000000';
terminalContainer!.style.background = term!.options.theme?.background ?? '#000000';
}
}
@@ -442,19 +449,19 @@ function initAddons(term: Terminal): void {
function postInitWebgl(): void {
controlBar.setTabVisible('addon-webgl', true);
setTimeout(() => {
addonWebglWindow.setTextureAtlas(addons.webgl.instance.textureAtlas);
addons.webgl.instance.onChangeTextureAtlas(e => addonWebglWindow.setTextureAtlas(e));
addons.webgl.instance.onAddTextureAtlasCanvas(e => addonWebglWindow.appendTextureAtlas(e));
addonWebglWindow.setTextureAtlas(addons.webgl.instance!.textureAtlas!);
addons.webgl.instance!.onChangeTextureAtlas(e => addonWebglWindow.setTextureAtlas(e));
addons.webgl.instance!.onAddTextureAtlasCanvas(e => addonWebglWindow.appendTextureAtlas(e));
}, 500);
}
function preDisposeWebgl(): void {
controlBar.setTabVisible('addon-webgl', false);
if (addons.webgl.instance.textureAtlas) {
addons.webgl.instance.textureAtlas.remove();
if (addons.webgl.instance!.textureAtlas) {
addons.webgl.instance!.textureAtlas.remove();
}
}
Object.keys(addons).forEach((name: AddonType) => {
(Object.keys(addons) as AddonType[]).forEach(name => {
const addon = addons[name];
const checkbox = document.createElement('input') as HTMLInputElement;
checkbox.type = 'checkbox';
@@ -469,12 +476,12 @@ function initAddons(term: Terminal): void {
term.unicode.activeVersion = '15-graphemes';
}
if (name === 'search' && checkbox.checked) {
addons[name].instance.onDidChangeResults(e => updateFindResults(e));
addons[name].instance!.onDidChangeResults(e => updateFindResults(e));
}
addDomListener(checkbox, 'change', () => {
if (name === 'image') {
if (checkbox.checked) {
const ctorOptionsJson = document.querySelector<HTMLTextAreaElement>('#image-options').value;
const ctorOptionsJson = document.querySelector<HTMLTextAreaElement>('#image-options')!.value;
addon.instance = ctorOptionsJson
? new addons[name].ctor(JSON.parse(ctorOptionsJson))
: new addons[name].ctor();
@@ -500,9 +507,15 @@ function initAddons(term: Terminal): void {
term.unicode.activeVersion = '15-graphemes';
} else if (name === 'search') {
controlBar.setTabVisible('addon-search', true);
addons[name].instance.onDidChangeResults(e => updateFindResults(e));
addons[name].instance!.onDidChangeResults(e => updateFindResults(e));
} else if (name === 'serialize') {
controlBar.setTabVisible('addon-serialize', true);
} else if (name === 'ligatures') {
controlBar.setTabVisible('addon-ligatures', true);
} else if (name === 'progress') {
controlBar.setTabVisible('addon-progress', true);
} else if (name === 'webLinks') {
controlBar.setTabVisible('addon-web-links', true);
}
}
catch {
@@ -519,6 +532,12 @@ function initAddons(term: Terminal): void {
controlBar.setTabVisible('addon-search', false);
} else if (name === 'serialize') {
controlBar.setTabVisible('addon-serialize', false);
} else if (name === 'ligatures') {
controlBar.setTabVisible('addon-ligatures', false);
} else if (name === 'progress') {
controlBar.setTabVisible('addon-progress', false);
} else if (name === 'webLinks') {
controlBar.setTabVisible('addon-web-links', false);
}
addon.instance!.dispose();
addon.instance = undefined;
@@ -590,17 +609,17 @@ function updateFindResults(e: { resultIndex: number, resultCount: number } | und
function addDomListener(element: HTMLElement, type: string, handler: (...args: any[]) => any): void {
element.addEventListener(type, handler);
term._core._register({ dispose: () => element.removeEventListener(type, handler) });
(term as any)._core._register({ dispose: () => element.removeEventListener(type, handler) });
}
function updateTerminalSize(): void {
const width = optionsWindow.autoResize ? '100%'
: (term.dimensions.css.canvas.width + term._core.viewport.scrollBarWidth).toString() + 'px';
: ((term as any).dimensions.css.canvas.width + (term as any)._core.viewport.scrollBarWidth).toString() + 'px';
const height = optionsWindow.autoResize ? '100%'
: (term.dimensions.css.canvas.height).toString() + 'px';
terminalContainer.style.width = width;
terminalContainer.style.height = height;
addons.fit.instance.fit();
: ((term as any).dimensions.css.canvas.height).toString() + 'px';
terminalContainer!.style.width = width;
terminalContainer!.style.height = height;
addons.fit.instance!.fit();
}
(console as any).image = (source: ImageData | HTMLCanvasElement, scale: number = 1) => {
@@ -5,14 +5,15 @@
import { BaseWindow } from './baseWindow';
import type { IControlWindow } from '../controlBar';
import type { IImageAddonOptions } from '@xterm/addon-image';
export class AddonImageWindow extends BaseWindow implements IControlWindow {
public readonly id = 'addon-image';
public readonly label = 'image';
private _imageStorageLimitInput: HTMLInputElement;
private _imageShowPlaceholderCheckbox: HTMLInputElement;
private _imageOptionsTextarea: HTMLTextAreaElement;
private _imageStorageLimitInput!: HTMLInputElement;
private _imageShowPlaceholderCheckbox!: HTMLInputElement;
private _imageOptionsTextarea!: HTMLTextAreaElement;
public build(container: HTMLElement): void {
// Storage limit
@@ -46,6 +47,20 @@ export class AddonImageWindow extends BaseWindow implements IControlWindow {
this._imageOptionsTextarea.rows = 12;
optionsLabel.appendChild(this._imageOptionsTextarea);
container.appendChild(optionsLabel);
container.appendChild(document.createElement('br'));
container.appendChild(document.createElement('br'));
const dl = document.createElement('dl');
const dt = document.createElement('dt');
dt.textContent = 'Image Test';
dl.appendChild(dt);
this._addDdWithButton(dl, 'image-demo1', 'snake (sixel)');
this._addDdWithButton(dl, 'image-demo2', 'oranges (sixel)');
this._addDdWithButton(dl, 'image-demo3', 'palette (iip)');
container.appendChild(dl);
this._initImageAddonExposed();
}
public get imageStorageLimitInput(): HTMLInputElement {
@@ -59,4 +74,93 @@ export class AddonImageWindow extends BaseWindow implements IControlWindow {
public get imageOptionsTextarea(): HTMLTextAreaElement {
return this._imageOptionsTextarea;
}
private _addDdWithButton(dl: HTMLElement, id: string, label: string): void {
const dd = document.createElement('dd');
const button = document.createElement('button');
button.id = id;
button.textContent = label;
dd.appendChild(button);
dl.appendChild(dd);
}
private _initImageAddonExposed(): void {
const imageAddon = this._addons.image.instance!;
const defaultOptions: IImageAddonOptions = (imageAddon as any)._defaultOpts;
const limitStorageElement = document.querySelector<HTMLInputElement>('#image-storagelimit')!;
limitStorageElement.valueAsNumber = imageAddon.storageLimit;
this._addDomListener(limitStorageElement, 'change', () => {
try {
imageAddon.storageLimit = limitStorageElement.valueAsNumber;
limitStorageElement.valueAsNumber = imageAddon.storageLimit;
console.log('changed storageLimit to', imageAddon.storageLimit);
} catch (e) {
limitStorageElement.valueAsNumber = imageAddon.storageLimit;
console.log('storageLimit at', imageAddon.storageLimit);
throw e;
}
});
const showPlaceholderElement = document.querySelector<HTMLInputElement>('#image-showplaceholder')!;
showPlaceholderElement.checked = imageAddon.showPlaceholder;
this._addDomListener(showPlaceholderElement, 'change', () => {
imageAddon.showPlaceholder = showPlaceholderElement.checked;
});
const ctorOptionsElement = document.querySelector<HTMLTextAreaElement>('#image-options')!;
ctorOptionsElement.value = JSON.stringify(defaultOptions, null, 2);
const sixelDemo = (url: string) => () => fetch(url)
.then(resp => resp.arrayBuffer())
.then(buffer => {
this._terminal.write('\r\n');
this._terminal.write(new Uint8Array(buffer));
});
const iipDemo = (url: string) => () => fetch(url)
.then(resp => resp.arrayBuffer())
.then(buffer => {
const data = new Uint8Array(buffer);
let sdata = '';
for (let i = 0; i < data.length; ++i) sdata += String.fromCharCode(data[i]);
this._terminal.write('\r\n');
this._terminal.write(`\x1b]1337;File=inline=1;size=${data.length}:${btoa(sdata)}\x1b\\`);
});
document.getElementById('image-demo1')!.addEventListener('click',
sixelDemo('https://raw.githubusercontent.com/saitoha/libsixel/master/images/snake.six'));
document.getElementById('image-demo2')!.addEventListener('click',
sixelDemo('https://raw.githubusercontent.com/jerch/node-sixel/master/testfiles/test2.sixel'));
document.getElementById('image-demo3')!.addEventListener('click',
iipDemo('https://raw.githubusercontent.com/jerch/node-sixel/master/palette.png'));
// demo for image retrieval API
this._terminal.element!.addEventListener('click', (ev: MouseEvent) => {
if (!ev.ctrlKey || !imageAddon) return;
// TODO...
// if (ev.altKey) {
// const sel = term.getSelectionPosition();
// if (sel) {
// addons.image.instance
// .extractCanvasAtBufferRange(term.getSelectionPosition())
// ?.toBlob(data => window.open(URL.createObjectURL(data), '_blank'));
// return;
// }
// }
const pos = (this._terminal as any)._core._mouseService!.getCoords(ev, (this._terminal as any)._core.screenElement!, this._terminal.cols, this._terminal.rows);
const x = pos[0] - 1;
const y = pos[1] - 1;
const canvas = ev.shiftKey
// ctrl+shift+click: get single tile
? imageAddon.extractTileAtBufferCell(x, this._terminal.buffer.active.viewportY + y)
// ctrl+click: get original image
: imageAddon.getImageAtBufferCell(x, this._terminal.buffer.active.viewportY + y);
canvas?.toBlob(data => data && window.open(URL.createObjectURL(data), '_blank'));
});
}
private _addDomListener(element: HTMLElement, type: string, handler: (...args: any[]) => any): void {
element.addEventListener(type, handler);
(this._terminal as any)._core._register({ dispose: () => element.removeEventListener(type, handler) });
}
}
@@ -0,0 +1,44 @@
/**
* Copyright (c) 2026 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { BaseWindow } from './baseWindow';
import type { IControlWindow } from '../controlBar';
export class AddonLigaturesWindow extends BaseWindow implements IControlWindow {
public readonly id = 'addon-ligatures';
public readonly label = 'ligatures';
public build(container: HTMLElement): void {
const dl = document.createElement('dl');
const dt = document.createElement('dt');
dt.textContent = 'Ligatures Addon';
dl.appendChild(dt);
const dd = document.createElement('dd');
const button = document.createElement('button');
button.id = 'ligatures-test';
button.textContent = 'Common ligatures';
button.title = 'Write common ligatures sequences';
button.addEventListener('click', () => this._ligaturesTest());
dd.appendChild(button);
dl.appendChild(dd);
container.appendChild(dl);
}
private _ligaturesTest(): void {
this._terminal.write([
'',
'-<< -< -<- <-- <--- <<- <- -> ->> --> ---> ->- >- >>-',
'=<< =< =<= <== <=== <<= <= => =>> ==> ===> =>= >= >>=',
'<-> <--> <---> <----> <=> <==> <===> <====> :: ::: __',
'<~~ </ </> /> ~~> == != /= ~= <> === !== !=== =/= =!=',
'<: := *= *+ <* <*> *> <| <|> |> <. <.> .> +* =* =: :>',
'(* *) /* */ [| |] {| |} ++ +++ \/ /\ |- -| <!-- <!---',
'==== ===== ====== ======= ======== =========',
'---- ----- ------ ------- -------- ---------'
].join('\r\n'));
}
}
@@ -0,0 +1,135 @@
/**
* Copyright (c) 2026 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { BaseWindow } from './baseWindow';
import type { IControlWindow } from '../controlBar';
import type { IProgressState } from '@xterm/addon-progress';
export class AddonProgressWindow extends BaseWindow implements IControlWindow {
public readonly id = 'addon-progress';
public readonly label = 'progress';
public build(container: HTMLElement): void {
const dl = document.createElement('dl');
const dt = document.createElement('dt');
dt.textContent = 'Progress Addon';
dl.appendChild(dt);
this._addDdWithButton(dl, 'progress-run', 'full set run', '');
this._addDdWithButton(dl, 'progress-0', 'state 0: remove', '');
this._addDdWithButton(dl, 'progress-1', 'state 1: set 20%', '');
this._addDdWithButton(dl, 'progress-2', 'state 2: error', '');
this._addDdWithButton(dl, 'progress-3', 'state 3: indeterminate', '');
this._addDdWithButton(dl, 'progress-4', 'state 4: pause', '');
const progressDd = document.createElement('dd');
const progressDiv = document.createElement('div');
progressDiv.id = 'progress-progress';
const progressPercent = document.createElement('div');
progressPercent.id = 'progress-percent';
const progressIndeterminate = document.createElement('div');
progressIndeterminate.id = 'progress-indeterminate';
progressDiv.appendChild(progressPercent);
progressDiv.appendChild(progressIndeterminate);
progressDd.appendChild(progressDiv);
dl.appendChild(progressDd);
const stateDd = document.createElement('dd');
const stateDiv = document.createElement('div');
stateDiv.id = 'progress-state';
stateDiv.textContent = 'State:';
stateDd.appendChild(stateDiv);
dl.appendChild(stateDd);
container.appendChild(dl);
this._initProgress();
this._addProgressStyles(container);
}
private _addDdWithButton(dl: HTMLElement, id: string, label: string, title: string): void {
const dd = document.createElement('dd');
const button = document.createElement('button');
button.id = id;
button.textContent = label;
if (title) {
button.title = title;
}
dd.appendChild(button);
dl.appendChild(dd);
}
private _initProgress(): void {
const states = { 0: 'remove', 1: 'set', 2: 'error', 3: 'indeterminate', 4: 'pause' };
const colors = { 0: '', 1: 'green', 2: 'red', 3: '', 4: 'yellow' };
function progressHandler({ state, value }: IProgressState): void {
// Simulate windows taskbar hack by windows terminal:
// Since the taskbar has no means to indicate error/pause state other than by coloring
// the current progress, we move 0 to 10% and distribute higher values in the remaining 90 %
// NOTE: This is most likely not what you want to do for other progress indicators,
// that have a proper visual state for error/paused.
value = Math.min(10 + value * 0.9, 100);
document.getElementById('progress-percent')!.style.width = `${value}%`;
document.getElementById('progress-percent')!.style.backgroundColor = colors[state];
document.getElementById('progress-state')!.innerText = `State: ${states[state]}`;
document.getElementById('progress-percent')!.style.display = state === 3 ? 'none' : 'block';
document.getElementById('progress-indeterminate')!.style.display = state === 3 ? 'block' : 'none';
}
const progressAddon = this._addons.progress.instance!;
progressAddon.onChange(progressHandler);
const initialProgress = progressAddon.progress;
progressHandler(initialProgress);
document.getElementById('progress-run')!.addEventListener('click', async () => {
this._terminal.write('\x1b]9;4;0\x1b\\');
for (let i = 0; i <= 100; i += 5) {
this._terminal.write(`\x1b]9;4;1;${i}\x1b\\`);
await new Promise(res => setTimeout(res, 200));
}
});
document.getElementById('progress-0')!.addEventListener('click', () => this._terminal.write('\x1b]9;4;0\x1b\\'));
document.getElementById('progress-1')!.addEventListener('click', () => this._terminal.write('\x1b]9;4;1;20\x1b\\'));
document.getElementById('progress-2')!.addEventListener('click', () => this._terminal.write('\x1b]9;4;2\x1b\\'));
document.getElementById('progress-3')!.addEventListener('click', () => this._terminal.write('\x1b]9;4;3\x1b\\'));
document.getElementById('progress-4')!.addEventListener('click', () => this._terminal.write('\x1b]9;4;4\x1b\\'));
}
private _addProgressStyles(container: HTMLElement): void {
const style = document.createElement('style');
style.textContent = `
#progress-progress {
border: 1px solid black;
height: 10px;
}
#progress-percent {
height: 100%;
}
#progress-indeterminate {
display: none;
position: relative;
height: 100%;
}
#progress-indeterminate:before {
content: '';
position: absolute;
left: 0;
bottom: 0px;
width: 50px;
height: 10px;
background: blue;
animation: ballbns 1s ease-in-out infinite alternate;
}
@keyframes ballbns {
0% { left: 0; transform: translateX(0%); }
100% { left: 100%; transform: translateX(-100%); }
}
`;
container.appendChild(style);
}
}
@@ -10,13 +10,13 @@ export class AddonSearchWindow extends BaseWindow implements IControlWindow {
public readonly id = 'addon-search';
public readonly label = 'search';
private _findNextInput: HTMLInputElement;
private _findPreviousInput: HTMLInputElement;
private _findResultsSpan: HTMLElement;
private _regexCheckbox: HTMLInputElement;
private _caseSensitiveCheckbox: HTMLInputElement;
private _wholeWordCheckbox: HTMLInputElement;
private _highlightAllMatchesCheckbox: HTMLInputElement;
private _findNextInput!: HTMLInputElement;
private _findPreviousInput!: HTMLInputElement;
private _findResultsSpan!: HTMLElement;
private _regexCheckbox!: HTMLInputElement;
private _caseSensitiveCheckbox!: HTMLInputElement;
private _wholeWordCheckbox!: HTMLInputElement;
private _highlightAllMatchesCheckbox!: HTMLInputElement;
public build(container: HTMLElement): void {
const wrapper = document.createElement('div');
@@ -10,10 +10,10 @@ export class AddonSerializeWindow extends BaseWindow implements IControlWindow {
public readonly id = 'addon-serialize';
public readonly label = 'serialize';
private _serializeOutputPre: HTMLPreElement;
private _htmlSerializeOutputPre: HTMLPreElement;
private _htmlSerializeOutputResult: HTMLElement;
private _writeToTerminalCheckbox: HTMLInputElement;
private _serializeOutputPre!: HTMLPreElement;
private _htmlSerializeOutputPre!: HTMLPreElement;
private _htmlSerializeOutputResult!: HTMLElement;
private _writeToTerminalCheckbox!: HTMLInputElement;
public build(container: HTMLElement): void {
const wrapper = document.createElement('div');
@@ -64,7 +64,7 @@ export class AddonSerializeWindow extends BaseWindow implements IControlWindow {
}
private _serializeButtonHandler(): void {
const output = this._addons.serialize.instance.serialize();
const output = this._addons.serialize.instance!.serialize();
const outputString = JSON.stringify(output);
this._serializeOutputPre.innerText = outputString;
@@ -75,7 +75,7 @@ export class AddonSerializeWindow extends BaseWindow implements IControlWindow {
}
private _htmlSerializeButtonHandler(): void {
const output = this._addons.serialize.instance.serializeAsHTML();
const output = this._addons.serialize.instance!.serializeAsHTML();
this._htmlSerializeOutputPre.innerText = output;
// Deprecated, but the most supported for now.
@@ -0,0 +1,52 @@
/**
* Copyright (c) 2026 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { BaseWindow } from './baseWindow';
import type { IControlWindow } from '../controlBar';
export class AddonWebLinksWindow extends BaseWindow implements IControlWindow {
public readonly id = 'addon-web-links';
public readonly label = 'web-links';
public build(container: HTMLElement): void {
const dl = document.createElement('dl');
const dt = document.createElement('dt');
dt.textContent = 'Weblinks Addon';
dl.appendChild(dt);
const dd = document.createElement('dd');
const button = document.createElement('button');
button.id = 'weblinks-test';
button.textContent = 'Test URLs';
button.title = 'Various url conditions from demo data, hover&click to test';
button.addEventListener('click', () => this._testWeblinks());
dd.appendChild(button);
dl.appendChild(dd);
container.appendChild(dl);
}
private _testWeblinks(): void {
const linkExamples = `
aaa http://example.com aaa http://example.com aaa
\uFFE5\uFFE5\uFFE5 http://example.com aaa http://example.com aaa
aaa http://example.com \uFFE5\uFFE5\uFFE5 http://example.com aaa
\uFFE5\uFFE5\uFFE5 http://example.com \uFFE5\uFFE5\uFFE5 http://example.com aaa
aaa https://ko.wikipedia.org/wiki/\uC704\uD0A4\uBC31\uACFC:\uB300\uBB38 aaa https://ko.wikipedia.org/wiki/\uC704\uD0A4\uBC31\uACFC:\uB300\uBB38 aaa
\uFFE5\uFFE5\uFFE5 https://ko.wikipedia.org/wiki/\uC704\uD0A4\uBC31\uACFC:\uB300\uBB38 aaa https://ko.wikipedia.org/wiki/\uC704\uD0A4\uBC31\uACFC:\uB300\uBB38 \uFFE5\uFFE5\uFFE5
aaa http://test:password@example.com/some_path aaa
brackets enclosed:
aaa [http://example.de] aaa
aaa (http://example.de) aaa
aaa <http://example.de> aaa
aaa {http://example.de} aaa
ipv6 https://[::1]/with/some?vars=and&a#hash aaa
stop at final '.': This is a sentence with an url to http://example.com.
stop at final '?': Is this the right url http://example.com/?
stop at final '?': Maybe this one http://example.com/with?arguments=false?
`;
this._terminal.write(linkExamples.split('\n').join('\r\n'));
}
}
@@ -10,7 +10,7 @@ export class AddonsWindow extends BaseWindow implements IControlWindow {
public readonly id = 'addons';
public readonly label = 'Addons';
private _addonsContainer: HTMLElement;
private _addonsContainer!: HTMLElement;
public build(container: HTMLElement): void {
// Description
@@ -30,14 +30,14 @@ export class CellInspectorWindow extends BaseWindow implements IControlWindow {
public readonly id = 'cell-inspector';
public readonly label = 'Cell Inspector';
private _container: HTMLElement;
private _positionEl: HTMLElement;
private _charEl: HTMLElement;
private _codeEl: HTMLElement;
private _widthEl: HTMLElement;
private _fgEl: HTMLElement;
private _bgEl: HTMLElement;
private _attrsEl: HTMLElement;
private _container!: HTMLElement;
private _positionEl!: HTMLElement;
private _charEl!: HTMLElement;
private _codeEl!: HTMLElement;
private _widthEl!: HTMLElement;
private _fgEl!: HTMLElement;
private _bgEl!: HTMLElement;
private _attrsEl!: HTMLElement;
public build(container: HTMLElement): void {
this._container = container;
+1 -1
View File
@@ -10,7 +10,7 @@ export class GpuWindow extends BaseWindow implements IControlWindow {
public readonly id = 'gpu';
public readonly label = 'WebGL';
private _textureAtlasContainer: HTMLElement;
private _textureAtlasContainer!: HTMLElement;
public build(container: HTMLElement): void {
const zoomCheckbox = document.createElement('input');
+39 -24
View File
@@ -80,8 +80,8 @@ export class OptionsWindow extends BaseWindow implements IControlWindow {
public readonly id = 'options';
public readonly label = 'Options';
private _container: HTMLElement;
private _optionsContainer: HTMLElement;
private _container!: HTMLElement;
private _optionsContainer!: HTMLElement;
private _autoResize: boolean = true;
constructor(
@@ -109,24 +109,26 @@ export class OptionsWindow extends BaseWindow implements IControlWindow {
public initOptions(addDomListener: (el: HTMLElement, type: string, handler: (...args: any[]) => any) => void): void {
const blacklistedOptions = [
'cancelEvents',
'convertEol',
'termName',
'cols', 'rows',
'documentOverride',
'linkHandler',
'logger',
'overviewRuler',
'quirks',
'theme',
'vtExtensions',
'windowOptions',
'windowsPty',
];
const nestedBooleanOptions: { label: string, parent: string, prop: string }[] = [
{ label: 'vtExtensions.kittyKeyboard', parent: 'vtExtensions', prop: 'kittyKeyboard' },
{ label: 'vtExtensions.kittySgrBoldFaintControl', parent: 'vtExtensions', prop: 'kittySgrBoldFaintControl' },
{ label: 'vtExtensions.win32InputMode', parent: 'vtExtensions', prop: 'win32InputMode' }
const nestedBooleanOptions: { label: string, path: string[], prop: string }[] = [
{ label: 'scrollbar.showScrollbar', path: ['scrollbar'], prop: 'showScrollbar' },
{ label: 'scrollbar.showArrows', path: ['scrollbar'], prop: 'showArrows' },
{ label: 'scrollbar.overviewRuler.showTopBorder', path: ['scrollbar', 'overviewRuler'], prop: 'showTopBorder' },
{ label: 'scrollbar.overviewRuler.showBottomBorder', path: ['scrollbar', 'overviewRuler'], prop: 'showBottomBorder' },
{ label: 'vtExtensions.kittyKeyboard', path: ['vtExtensions'], prop: 'kittyKeyboard' },
{ label: 'vtExtensions.kittySgrBoldFaintControl', path: ['vtExtensions'], prop: 'kittySgrBoldFaintControl' },
{ label: 'vtExtensions.win32InputMode', path: ['vtExtensions'], prop: 'win32InputMode' }
];
const stringOptions: { [key: string]: string[] | null } = {
cursorStyle: ['block', 'underline', 'bar'],
@@ -143,7 +145,7 @@ export class OptionsWindow extends BaseWindow implements IControlWindow {
const booleanOptions: string[] = [];
const numberOptions: string[] = [];
options.filter(o => blacklistedOptions.indexOf(o) === -1).forEach(o => {
switch (typeof this._terminal.options[o]) {
switch (typeof (this._terminal.options as Record<string, unknown>)[o]) {
case 'boolean':
booleanOptions.push(o);
break;
@@ -160,25 +162,27 @@ export class OptionsWindow extends BaseWindow implements IControlWindow {
let html = '';
html += '<div class="option-group">';
booleanOptions.forEach(o => {
html += `<div class="option"><label><input id="opt-${o}" type="checkbox" ${this._terminal.options[o] ? 'checked' : ''}/> ${o}</label></div>`;
html += `<div class="option"><label><input id="opt-${o}" type="checkbox" ${(this._terminal.options as Record<string, unknown>)[o] ? 'checked' : ''}/> ${o}</label></div>`;
});
nestedBooleanOptions.forEach(({ label, parent, prop }) => {
const checked = this._terminal.options[parent]?.[prop] ?? false;
nestedBooleanOptions.forEach(({ label, path, prop }) => {
const options = this._terminal.options as Record<string, unknown>;
const parent = path.reduce<Record<string, unknown> | undefined>((acc, key) => (acc as Record<string, unknown> | undefined)?.[key] as Record<string, unknown> | undefined, options);
const checked = (parent as Record<string, unknown> | undefined)?.[prop] ?? false;
html += `<div class="option"><label><input id="opt-${label.replace('.', '-')}" type="checkbox" ${checked ? 'checked' : ''}/> ${label}</label></div>`;
});
html += '</div><div class="option-group">';
numberOptions.forEach(o => {
html += `<div class="option"><label>${o} <input id="opt-${o}" type="number" value="${this._terminal.options[o] ?? ''}" step="${o === 'lineHeight' || o === 'scrollSensitivity' ? '0.1' : '1'}"/></label></div>`;
html += `<div class="option"><label>${o} <input id="opt-${o}" type="number" value="${(this._terminal.options as Record<string, unknown>)[o] ?? ''}" step="${o === 'lineHeight' || o === 'scrollSensitivity' ? '0.1' : '1'}"/></label></div>`;
});
html += '</div><div class="option-group">';
Object.keys(stringOptions).forEach(o => {
if (o === 'colsRows') {
html += `<div class="option"><label>size (<var>cols</var><code>x</code><var>rows</var> or <code>auto</code>) <input id="opt-${o}" type="text" value="auto"/></label></div>`;
} else if (stringOptions[o]) {
const selectedOption = o === 'theme' ? 'xtermjs' : this._terminal.options[o];
const selectedOption = o === 'theme' ? 'xtermjs' : (this._terminal.options as Record<string, unknown>)[o];
html += `<div class="option"><label>${o} <select id="opt-${o}">${stringOptions[o]!.map(v => `<option ${v === selectedOption ? 'selected' : ''}>${v}</option>`).join('')}</select></label></div>`;
} else {
html += `<div class="option"><label>${o} <input id="opt-${o}" type="text" value="${this._terminal.options[o]}"/></label></div>`;
html += `<div class="option"><label>${o} <input id="opt-${o}" type="text" value="${(this._terminal.options as Record<string, unknown>)[o]}"/></label></div>`;
}
});
html += '</div>';
@@ -190,18 +194,29 @@ export class OptionsWindow extends BaseWindow implements IControlWindow {
const input = document.getElementById(`opt-${o}`) as HTMLInputElement;
addDomListener(input, 'change', () => {
console.log('change', o, input.checked);
this._terminal.options[o] = input.checked;
(this._terminal.options as Record<string, unknown>)[o] = input.checked;
if (o ==='allowTransparency') {
this._terminal.options.theme = this._getTheme();
this._handlers.updateTerminalContainerBackground();
}
});
});
nestedBooleanOptions.forEach(({ label, parent, prop }) => {
nestedBooleanOptions.forEach(({ label, path, prop }) => {
const input = document.getElementById(`opt-${label.replace('.', '-')}`) as HTMLInputElement;
addDomListener(input, 'change', () => {
console.log('change', label, input.checked);
this._terminal.options[parent] = { ...this._terminal.options[parent], [prop]: input.checked };
const options = this._terminal.options as Record<string, unknown>;
if (path.length === 1) {
const parentKey = path[0];
options[parentKey] = { ...(options[parentKey] as Record<string, unknown> | undefined), [prop]: input.checked };
return;
}
if (path.length === 2) {
const [parentKey, childKey] = path;
const parent = (options[parentKey] as Record<string, unknown> | undefined) ?? {};
const child = (parent[childKey] as Record<string, unknown> | undefined) ?? {};
options[parentKey] = { ...parent, [childKey]: { ...child, [prop]: input.checked } };
}
});
});
numberOptions.forEach(o => {
@@ -216,7 +231,7 @@ export class OptionsWindow extends BaseWindow implements IControlWindow {
this._terminal.options.scrollback = parseInt(input.value);
setTimeout(() => this._handlers.updateTerminalSize(), 5);
} else {
this._terminal.options[o] = parseInt(input.value);
(this._terminal.options as Record<string, unknown>)[o] = parseInt(input.value);
}
this._handlers.updateTerminalSize();
});
@@ -225,7 +240,7 @@ export class OptionsWindow extends BaseWindow implements IControlWindow {
const input = document.getElementById(`opt-${o}`) as HTMLInputElement;
addDomListener(input, 'change', () => {
console.log('change', o, input.value);
let value: any = input.value;
let value: unknown = input.value;
if (o === 'colsRows') {
const m = input.value.match(/^([0-9]+)x([0-9]+)$/);
if (m) {
@@ -239,7 +254,7 @@ export class OptionsWindow extends BaseWindow implements IControlWindow {
} else if (o === 'theme') {
value = this._getTheme();
}
this._terminal.options[o] = value;
(this._terminal.options as Record<string, unknown>)[o] = value;
if (o === 'theme') {
this._handlers.updateTerminalContainerBackground();
}
@@ -259,11 +274,11 @@ export class OptionsWindow extends BaseWindow implements IControlWindow {
}
private _getTheme(): ITheme {
const input = document.querySelector<HTMLInputElement>('#opt-theme');
let theme: ITheme;
const input = document.querySelector<HTMLInputElement>('#opt-theme')!;
let theme: ITheme = {};
switch (input.value) {
case 'default':
theme = undefined;
theme = {};
break;
case 'xtermjs':
theme = { ...xtermjsTheme };
+1 -1
View File
@@ -10,7 +10,7 @@ export class StyleWindow extends BaseWindow implements IControlWindow {
public readonly id = 'style';
public readonly label = 'Style';
private _paddingElement: HTMLInputElement;
private _paddingElement!: HTMLInputElement;
public build(container: HTMLElement): void {
const wrapper = document.createElement('div');
+19 -244
View File
@@ -8,8 +8,6 @@ import type { IControlWindow } from '../controlBar';
import { BaseWindow } from './baseWindow';
import type { IDisposable, Terminal } from '@xterm/xterm';
import type { AddonCollection } from 'types';
import type { IProgressState } from '@xterm/addon-progress';
import type { IImageAddonOptions } from '@xterm/addon-image';
export class TestWindow extends BaseWindow implements IControlWindow {
public readonly id = 'test';
@@ -66,61 +64,13 @@ export class TestWindow extends BaseWindow implements IControlWindow {
this._addDdWithButton(dl, 'add-overview-ruler', 'Add Overview Ruler', 'Add an overview ruler to the terminal', () => addOverviewRuler(this._terminal));
this._addDdWithButton(dl, 'decoration-stress-test', 'Stress Test', 'Toggle between adding and removing a decoration to each line', () => decorationStressTest(this._terminal));
// Ligatures Addon section
this._addDt(dl, 'Ligatures Addon');
this._addDdWithButton(dl, 'ligatures-test', 'Common ligatures', 'Write common ligatures sequences', () => ligaturesTest(this._terminal));
// Weblinks Addon section
this._addDt(dl, 'Weblinks Addon');
this._addDdWithButton(dl, 'weblinks-test', 'Test URLs', 'Various url conditions from demo data, hover&click to test', () => testWeblinks(this._terminal));
// Image Test section
this._addDt(dl, 'Image Test');
this._addDdWithButton(dl, 'image-demo1', 'snake (sixel)', '');
this._addDdWithButton(dl, 'image-demo2', 'oranges (sixel)', '');
this._addDdWithButton(dl, 'image-demo3', 'palette (iip)', '');
// Events Test section
this._addDt(dl, 'Events Test');
this._addDdWithButton(dl, 'event-focus', 'focus', '', () => this._terminal.focus());
this._addDdWithButton(dl, 'event-blur', 'blur', '', () => this._terminal.blur());
// Progress Addon section
this._addDt(dl, 'Progress Addon');
this._addDdWithButton(dl, 'progress-run', 'full set run', '');
this._addDdWithButton(dl, 'progress-0', 'state 0: remove', '');
this._addDdWithButton(dl, 'progress-1', 'state 1: set 20%', '');
this._addDdWithButton(dl, 'progress-2', 'state 2: error', '');
this._addDdWithButton(dl, 'progress-3', 'state 3: indeterminate', '');
this._addDdWithButton(dl, 'progress-4', 'state 4: pause', '');
// Progress bar
const progressDd = document.createElement('dd');
const progressDiv = document.createElement('div');
progressDiv.id = 'progress-progress';
const progressPercent = document.createElement('div');
progressPercent.id = 'progress-percent';
const progressIndeterminate = document.createElement('div');
progressIndeterminate.id = 'progress-indeterminate';
progressDiv.appendChild(progressPercent);
progressDiv.appendChild(progressIndeterminate);
progressDd.appendChild(progressDiv);
dl.appendChild(progressDd);
// Progress state
const stateDd = document.createElement('dd');
const stateDiv = document.createElement('div');
stateDiv.id = 'progress-state';
stateDiv.textContent = 'State:';
stateDd.appendChild(stateDiv);
dl.appendChild(stateDd);
wrapper.appendChild(dl);
container.appendChild(wrapper);
initProgress(this._terminal, this._addons);
this._addProgressStyles(container);
initImageAddonExposed(this._terminal, this._addons);
}
private _addDt(dl: HTMLElement, text: string): void {
@@ -139,7 +89,9 @@ export class TestWindow extends BaseWindow implements IControlWindow {
}
dd.appendChild(button);
dl.appendChild(dd);
button.addEventListener('click', handler);
if (handler) {
button.addEventListener('click', handler);
}
}
private _addDdWithCheckbox(dl: HTMLElement, id: string, label: string, title: string, checked: boolean): void {
@@ -159,38 +111,6 @@ export class TestWindow extends BaseWindow implements IControlWindow {
dl.appendChild(dd);
}
private _addProgressStyles(container: HTMLElement): void {
const style = document.createElement('style');
style.textContent = `
#progress-progress {
border: 1px solid black;
height: 10px;
}
#progress-percent {
height: 100%;
}
#progress-indeterminate {
display: none;
position: relative;
height: 100%;
}
#progress-indeterminate:before {
content: '';
position: absolute;
left: 0;
bottom: 0px;
width: 50px;
height: 10px;
background: blue;
animation: ballbns 1s ease-in-out infinite alternate;
}
@keyframes ballbns {
0% { left: 0; transform: translateX(0%); }
100% { left: 100%; transform: translateX(-100%); }
}
`;
container.appendChild(style);
}
}
/**
@@ -465,7 +385,7 @@ function customGlyphAlignmentHandler(term: Terminal): void {
while (fillChars.length > 0) {
const batch = fillChars.splice(0, 10);
for (const fillChar of batch) {
term.write(`${fillChar.codePointAt(0).toString(16).toUpperCase().padEnd(5, ' ')} `);
term.write(`${fillChar.codePointAt(0)!.toString(16).toUpperCase().padEnd(5, ' ')} `);
}
term.write('\n\r');
for (let i = 0; i < 3; i++) {
@@ -477,6 +397,13 @@ function customGlyphAlignmentHandler(term: Terminal): void {
}
}
term.write('\x1b[0mTriangular fill tests:\x1b[36m\n\r');
term.write('1FB9C 1FB9D 1FB9E 1FB9F all\n\r');
term.write('\u{02592}\u{02592}\u{02592}\u{1FB9C} \u{1FB9D}\u{02592}\u{02592}\u{02592} \u{00020}\u{00020}\u{00020}\u{1FB9E} \u{1FB9F}\u{00020}\u{00020}\u{00020} \u{00020}\u{1FB9E}\u{1FB9F}\u{00020}\n\r');
term.write('\u{02592}\u{02592}\u{1FB9C}\u{00020} \u{00020}\u{1FB9D}\u{02592}\u{02592} \u{00020}\u{00020}\u{1FB9E}\u{02592} \u{02592}\u{1FB9F}\u{00020}\u{00020} \u{1FB9E}\u{02592}\u{02592}\u{1FB9F}\n\r');
term.write('\u{02592}\u{1FB9C}\u{00020}\u{00020} \u{00020}\u{00020}\u{1FB9D}\u{02592} \u{00020}\u{1FB9E}\u{02592}\u{02592} \u{02592}\u{02592}\u{1FB9F}\u{00020} \u{1FB9D}\u{02592}\u{02592}\u{1FB9C}\n\r');
term.write('\u{1FB9C}\u{00020}\u{00020}\u{00020} \u{00020}\u{00020}\u{00020}\u{1FB9D} \u{1FB9E}\u{02592}\u{02592}\u{02592} \u{02592}\u{02592}\u{02592}\u{1FB9F} \u{00020}\u{1FB9D}\u{1FB9C}\u{00020}\n\r');
term.write('\x1b[0mPowerline alignment tests:\n\r');
const powerlineLeftChars = ['\u{E0B2}', '\u{E0B3}', '\u{E0B6}', '\u{E0B7}', '\u{E0BA}', '\u{E0BB}', '\u{E0BE}', '\u{E0BF}', '\u{E0C2}', '\u{E0C3}', '\u{E0C5}', '\u{E0C7}', '\u{E0CA}', '\u{E0D4}'];
const powerlineRightChars = ['\u{E0B0}', '\u{E0B1}', '\u{E0B4}', '\u{E0B5}', '\u{E0B8}', '\u{E0B9}', '\u{E0BC}', '\u{E0BD}', '\u{E0C0}', '\u{E0C1}', '\u{E0C4}', '\u{E0C6}', '\u{E0C8}', '\u{E0D2}', '\u{E0CC}', '\u{E0CD}', '\u{E0CE}', '\u{E0CF}', '\u{E0D0}', '\u{E0D1}'];
@@ -751,42 +678,6 @@ Test BG-colored Erase (BCE):
term.write(data.split('\n').join('\r\n'));
}
function ligaturesTest(term: Terminal): void {
term.write([
'',
'-<< -< -<- <-- <--- <<- <- -> ->> --> ---> ->- >- >>-',
'=<< =< =<= <== <=== <<= <= => =>> ==> ===> =>= >= >>=',
'<-> <--> <---> <----> <=> <==> <===> <====> :: ::: __',
'<~~ </ </> /> ~~> == != /= ~= <> === !== !=== =/= =!=',
'<: := *= *+ <* <*> *> <| <|> |> <. <.> .> +* =* =: :>',
'(* *) /* */ [| |] {| |} ++ +++ \/ /\ |- -| <!-- <!---',
'==== ===== ====== ======= ======== =========',
'---- ----- ------ ------- -------- ---------'
].join('\r\n'));
}
function testWeblinks(term: Terminal): void {
const linkExamples = `
aaa http://example.com aaa http://example.com aaa
¥¥¥ http://example.com aaa http://example.com aaa
aaa http://example.com ¥¥¥ http://example.com aaa
¥¥¥ http://example.com ¥¥¥ http://example.com aaa
aaa https://ko.wikipedia.org/wiki/위키백과:대문 aaa https://ko.wikipedia.org/wiki/위키백과:대문 aaa
¥¥¥ https://ko.wikipedia.org/wiki/위키백과:대문 aaa https://ko.wikipedia.org/wiki/위키백과:대문 ¥¥¥
aaa http://test:password@example.com/some_path aaa
brackets enclosed:
aaa [http://example.de] aaa
aaa (http://example.de) aaa
aaa <http://example.de> aaa
aaa {http://example.de} aaa
ipv6 https://[::1]/with/some?vars=and&a#hash aaa
stop at final '.': This is a sentence with an url to http://example.com.
stop at final '?': Is this the right url http://example.com/?
stop at final '?': Maybe this one http://example.com/with?arguments=false?
`;
term.write(linkExamples.split('\n').join('\r\n'));
}
function loadTest(term: Terminal, addons: AddonCollection): void {
const rendererName = addons.webgl.instance ? 'webgl' : 'dom';
const testData = [];
@@ -854,7 +745,7 @@ function loadTestLongLines(term: Terminal, addons: AddonCollection): void {
}
function addDecoration(term: Terminal, dim: number = 1): void {
term.options['overviewRuler'] = { width: 14 };
term.options.scrollbar = { ...(term.options.scrollbar ?? {}), width: 14, overviewRuler: term.options.scrollbar?.overviewRuler ?? {} };
const marker = term.registerMarker(1);
const decoration = term.registerDecoration({
marker,
@@ -864,14 +755,14 @@ function addDecoration(term: Terminal, dim: number = 1): void {
foregroundColor: '#00FE00',
overviewRulerOptions: { color: '#ef292980', position: 'left' }
});
decoration.onRender((e: HTMLElement) => {
decoration?.onRender((e: HTMLElement) => {
e.style.right = '100%';
e.style.backgroundColor = '#ef292980';
});
}
function addOverviewRuler(term: Terminal): void {
term.options['overviewRuler'] = { width: 14 };
term.options.scrollbar = { ...(term.options.scrollbar ?? {}), width: 14, overviewRuler: term.options.scrollbar?.overviewRuler ?? {} };
term.registerDecoration({ marker: term.registerMarker(1), overviewRulerOptions: { color: '#ef2929' } });
term.registerDecoration({ marker: term.registerMarker(3), overviewRulerOptions: { color: '#8ae234' } });
term.registerDecoration({ marker: term.registerMarker(5), overviewRulerOptions: { color: '#729fcf' } });
@@ -896,133 +787,17 @@ function decorationStressTest(term: Terminal): void {
for (const x of [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]) {
for (let y = 0; y < term.buffer.active.length; y++) {
const cursorOffsetY = y - cursorY;
decorationStressTestDecorations.push(term.registerDecoration({
const decoration = term.registerDecoration({
marker: term.registerMarker(cursorOffsetY),
x,
width: 4,
backgroundColor: '#FF0000',
overviewRulerOptions: { color: '#FF0000' }
}));
});
if (decoration) {
decorationStressTestDecorations.push(decoration);
}
}
}
}
}
function initProgress(term: Terminal, addons: AddonCollection): void {
const STATES = { 0: 'remove', 1: 'set', 2: 'error', 3: 'indeterminate', 4: 'pause' };
const COLORS = { 0: '', 1: 'green', 2: 'red', 3: '', 4: 'yellow' };
function progressHandler({ state, value }: IProgressState): void {
// Simulate windows taskbar hack by windows terminal:
// Since the taskbar has no means to indicate error/pause state other than by coloring
// the current progress, we move 0 to 10% and distribute higher values in the remaining 90 %
// NOTE: This is most likely not what you want to do for other progress indicators,
// that have a proper visual state for error/paused.
value = Math.min(10 + value * 0.9, 100);
document.getElementById('progress-percent').style.width = `${value}%`;
document.getElementById('progress-percent').style.backgroundColor = COLORS[state];
document.getElementById('progress-state').innerText = `State: ${STATES[state]}`;
document.getElementById('progress-percent').style.display = state === 3 ? 'none' : 'block';
document.getElementById('progress-indeterminate').style.display = state === 3 ? 'block' : 'none';
}
const progressAddon = addons.progress.instance;
progressAddon.onChange(progressHandler);
// apply initial state once to make it visible on page load
const initialProgress = progressAddon.progress;
progressHandler(initialProgress);
document.getElementById('progress-run').addEventListener('click', async () => {
term.write('\x1b]9;4;0\x1b\\');
for (let i = 0; i <= 100; i += 5) {
term.write(`\x1b]9;4;1;${i}\x1b\\`);
await new Promise(res => setTimeout(res, 200));
}
});
document.getElementById('progress-0').addEventListener('click', () => term.write('\x1b]9;4;0\x1b\\'));
document.getElementById('progress-1').addEventListener('click', () => term.write('\x1b]9;4;1;20\x1b\\'));
document.getElementById('progress-2').addEventListener('click', () => term.write('\x1b]9;4;2\x1b\\'));
document.getElementById('progress-3').addEventListener('click', () => term.write('\x1b]9;4;3\x1b\\'));
document.getElementById('progress-4').addEventListener('click', () => term.write('\x1b]9;4;4\x1b\\'));
}
function initImageAddonExposed(term: Terminal, addons: AddonCollection): void {
const DEFAULT_OPTIONS: IImageAddonOptions = (addons.image.instance as any)._defaultOpts;
const limitStorageElement = document.querySelector<HTMLInputElement>('#image-storagelimit');
limitStorageElement.valueAsNumber = addons.image.instance.storageLimit;
addDomListener(term, limitStorageElement, 'change', () => {
try {
addons.image.instance.storageLimit = limitStorageElement.valueAsNumber;
limitStorageElement.valueAsNumber = addons.image.instance.storageLimit;
console.log('changed storageLimit to', addons.image.instance.storageLimit);
} catch (e) {
limitStorageElement.valueAsNumber = addons.image.instance.storageLimit;
console.log('storageLimit at', addons.image.instance.storageLimit);
throw e;
}
});
const showPlaceholderElement = document.querySelector<HTMLInputElement>('#image-showplaceholder');
showPlaceholderElement.checked = addons.image.instance.showPlaceholder;
addDomListener(term, showPlaceholderElement, 'change', () => {
addons.image.instance.showPlaceholder = showPlaceholderElement.checked;
});
const ctorOptionsElement = document.querySelector<HTMLTextAreaElement>('#image-options');
ctorOptionsElement.value = JSON.stringify(DEFAULT_OPTIONS, null, 2);
const sixelDemo = (url: string) => () => fetch(url)
.then(resp => resp.arrayBuffer())
.then(buffer => {
term.write('\r\n');
term.write(new Uint8Array(buffer));
});
const iipDemo = (url: string) => () => fetch(url)
.then(resp => resp.arrayBuffer())
.then(buffer => {
const data = new Uint8Array(buffer);
let sdata = '';
for (let i = 0; i < data.length; ++i) sdata += String.fromCharCode(data[i]);
term.write('\r\n');
term.write(`\x1b]1337;File=inline=1;size=${data.length}:${btoa(sdata)}\x1b\\`);
});
document.getElementById('image-demo1').addEventListener('click',
sixelDemo('https://raw.githubusercontent.com/saitoha/libsixel/master/images/snake.six'));
document.getElementById('image-demo2').addEventListener('click',
sixelDemo('https://raw.githubusercontent.com/jerch/node-sixel/master/testfiles/test2.sixel'));
document.getElementById('image-demo3').addEventListener('click',
iipDemo('https://raw.githubusercontent.com/jerch/node-sixel/master/palette.png'));
// demo for image retrieval API
term.element.addEventListener('click', (ev: MouseEvent) => {
if (!ev.ctrlKey || !addons.image.instance) return;
// TODO...
// if (ev.altKey) {
// const sel = term.getSelectionPosition();
// if (sel) {
// addons.image.instance
// .extractCanvasAtBufferRange(term.getSelectionPosition())
// ?.toBlob(data => window.open(URL.createObjectURL(data), '_blank'));
// return;
// }
// }
const pos = (term as any)._core._mouseService!.getCoords(ev, (term as any)._core.screenElement!, term.cols, term.rows);
const x = pos[0] - 1;
const y = pos[1] - 1;
const canvas = ev.shiftKey
// ctrl+shift+click: get single tile
? addons.image.instance.extractTileAtBufferCell(x, term.buffer.active.viewportY + y)
// ctrl+click: get original image
: addons.image.instance.getImageAtBufferCell(x, term.buffer.active.viewportY + y);
canvas?.toBlob(data => window.open(URL.createObjectURL(data), '_blank'));
});
}
function addDomListener(term: Terminal, element: HTMLElement, type: string, handler: (...args: any[]) => any): void {
element.addEventListener(type, handler);
(term as any)._core._register({ dispose: () => element.removeEventListener(type, handler) });
}
+2 -4
View File
@@ -5,14 +5,12 @@
import { BaseWindow } from './baseWindow';
import type { IControlWindow } from '../controlBar';
import type { Terminal } from '@xterm/xterm';
export class VtWindow extends BaseWindow implements IControlWindow {
public readonly id = 'vt';
public readonly label = 'VT';
private _container: HTMLElement;
private _term: Terminal | undefined;
private _container!: HTMLElement;
public build(container: HTMLElement): void {
this._container = container;
@@ -65,7 +63,7 @@ export class VtWindow extends BaseWindow implements IControlWindow {
const writeCsiSplit = writeCsi.split('|');
const prefix = writeCsiSplit.length === 2 ? writeCsiSplit[0] : '';
const suffix = writeCsiSplit[writeCsiSplit.length - 1];
element.addEventListener('click', () => this._term?.write(this._csi(`${prefix}${inputs.map(e => e.value).join(';')}${suffix}`)));
element.addEventListener('click', () => this._terminal.write(this._csi(`${prefix}${inputs.map(e => e.value).join(';')}${suffix}`)));
const desc = document.createElement('span');
desc.textContent = description;
+1 -1
View File
@@ -10,7 +10,7 @@ export class WebglWindow extends BaseWindow implements IControlWindow {
public readonly id = 'addon-webgl';
public readonly label = 'webgl';
private _textureAtlasContainer: HTMLElement;
private _textureAtlasContainer!: HTMLElement;
public build(container: HTMLElement): void {
const zoomCheckbox = document.createElement('input');
+1
View File
@@ -6,6 +6,7 @@
"rootDir": ".",
"sourceMap": true,
"baseUrl": ".",
"strict": true,
"paths": {
"@xterm/addon-attach": ["../../addons/addon-attach"],
"@xterm/addon-clipboard": ["../../addons/addon-clipboard"],
+1
View File
@@ -33,6 +33,7 @@ body {
padding: 4px 10px;
cursor: pointer;
font-size: 12px;
outline-offset: -1px;
}
.banner-tabs button:hover {
background: rgba(255,255,255,0.1);
+1
View File
@@ -46,6 +46,7 @@ function startServer(): void {
});
app.use('/fonts', express.static(demoRoot + '/fonts'));
app.use('/vendor/ghostty-wasm', express.static(demoRoot + '/../vendor/ghostty-wasm'));
app.use('/dist', express.static(demoRoot + '/dist'));
app.use('/src', express.static(demoRoot + '/src'));
+9 -1
View File
@@ -10,7 +10,6 @@ export default tseslint.config(
{
ignores: [
'addons/*/src/third-party/*.ts',
'src/vs/*',
'**/out/*',
'**/out-test/*',
'**/out-esbuild/*',
@@ -35,6 +34,7 @@ export default tseslint.config(
}
},
rules: {
'@stylistic/comma-spacing': ['warn', { before: false, after: true }],
'@stylistic/indent': ['warn', 2],
'@stylistic/semi': ['warn', 'always'],
'@stylistic/quotes': ['warn', 'single', { allowTemplateLiterals: true }],
@@ -66,6 +66,7 @@ export default tseslint.config(
],
'@typescript-eslint/no-confusing-void-expression': ['warn', { ignoreArrowShorthand: true }],
'@typescript-eslint/no-useless-constructor': 'warn',
'@typescript-eslint/prefer-nullish-coalescing': ['warn', { ignorePrimitives: true }],
'@typescript-eslint/prefer-namespace-keyword': 'warn',
'@typescript-eslint/no-unused-vars': ['warn', { vars: 'all', args: 'none' }],
'@typescript-eslint/no-require-imports': 'off',
@@ -140,5 +141,12 @@ export default tseslint.config(
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-member-accessibility': 'off'
}
},
{
// Disable prefer-nullish-coalescing for files without strictNullChecks
files: ['demo/**/*.ts', '**/*.benchmark.ts'],
rules: {
'@typescript-eslint/prefer-nullish-coalescing': 'off'
}
}
);
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@xterm/headless",
"description": "A headless terminal component that runs in Node.js",
"version": "5.5.0",
"version": "6.0.0",
"main": "lib-headless/xterm-headless.js",
"module": "lib-headless/xterm-headless.mjs",
"types": "typings/xterm-headless.d.ts",
+5 -4
View File
@@ -41,7 +41,7 @@
"jsdom": "^27.3.0",
"mocha": "^10.1.0",
"mustache": "^4.2.0",
"node-pty": "1.1.0-beta19",
"node-pty": "^1.2.0-beta.9",
"nyc": "^17.1.0",
"source-map-loader": "^3.0.0",
"source-map-support": "^0.5.20",
@@ -6016,11 +6016,12 @@
}
},
"node_modules/node-pty": {
"version": "1.1.0-beta19",
"resolved": "https://registry.npmjs.org/node-pty/-/node-pty-1.1.0-beta19.tgz",
"integrity": "sha512-/p4Zu56EYDdXjjaLWzrIlFyrBnND11LQGP0/L6GEVGURfCNkAlHc3Twg/2I4NPxghimHXgvDlwp7Z2GtvDIh8A==",
"version": "1.2.0-beta.9",
"resolved": "https://registry.npmjs.org/node-pty/-/node-pty-1.2.0-beta.9.tgz",
"integrity": "sha512-XR3x/4OQZ7DlceespOQ99kk9jZHwmO78RuEIZtGsSPdsDi11s79VcK04aqcaK3x09Y6ORJM/KBz/oQ/p+WGRLg==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
"node-addon-api": "^7.1.0"
}
+6 -4
View File
@@ -45,18 +45,20 @@
"esbuild-demo-client-watch": "node bin/esbuild.mjs --demo-client --watch",
"esbuild-demo-server": "node bin/esbuild.mjs --demo-server",
"esbuild-demo-server-watch": "node bin/esbuild.mjs --demo-server --watch",
"ghostty-wasm": "node bin/build_ghostty_wasm.mjs",
"test": "npm run test-unit",
"posttest": "npm run lint",
"lint": "eslint --max-warnings 0 src/ addons/ demo/",
"lint": "eslint --max-warnings 0 src/ addons/ demo/ test/",
"lint-changes": "node ./bin/lint_changes.js",
"lint-changes-fix": "node ./bin/lint_changes.js --fix",
"lint-fix": "eslint --fix src/ addons/ demo/",
"lint-fix": "eslint --fix src/ addons/ demo/ test/",
"lint-api": "eslint --config eslint.config.typings.mjs --max-warnings 0 typings/",
"test-unit": "node ./bin/test_unit.js",
"test-unit-slow-tests": "npm run test-unit | grep \"ms)\"",
"test-unit-coverage": "node ./bin/test_unit.js --coverage",
"test-unit-dev": "cross-env NODE_PATH='./out' mocha",
"test-integration": "node ./bin/test_integration.js --workers=75%",
"test-integration-chromium": "node ./bin/test_integration.js --workers=75% \"--project=ChromeStable\"",
"test-integration-chromium": "node ./bin/test_integration.js --workers=75% \"--project=Chromium\"",
"test-integration-firefox": "node ./bin/test_integration.js --workers=75% \"--project=FirefoxStable\"",
"test-integration-webkit": "node ./bin/test_integration.js --workers=75% \"--project=WebKit\"",
"test-integration-debug": "node ./bin/test_integration.js --workers=1 --headed --timeout=30000",
@@ -103,7 +105,7 @@
"jsdom": "^27.3.0",
"mocha": "^10.1.0",
"mustache": "^4.2.0",
"node-pty": "1.1.0-beta19",
"node-pty": "^1.2.0-beta.9",
"nyc": "^17.1.0",
"source-map-loader": "^3.0.0",
"source-map-support": "^0.5.20",
+2 -2
View File
@@ -6,11 +6,11 @@
import * as Strings from 'browser/LocalizableStrings';
import { ITerminal, IRenderDebouncer } from 'browser/Types';
import { TimeBasedDebouncer } from 'browser/TimeBasedDebouncer';
import { Disposable, toDisposable } from 'vs/base/common/lifecycle';
import { Disposable, toDisposable } from 'common/Lifecycle';
import { ICoreBrowserService, IRenderService } from 'browser/services/Services';
import { IBuffer } from 'common/buffer/Types';
import { IInstantiationService } from 'common/services/Services';
import { addDisposableListener } from 'vs/base/browser/dom';
import { addDisposableListener } from 'browser/Dom';
const MAX_ROWS_TO_READ = 20;
+77 -48
View File
@@ -42,22 +42,22 @@ import { SelectionService } from 'browser/services/SelectionService';
import { ICharSizeService, ICharacterJoinerService, ICoreBrowserService, IKeyboardService, ILinkProviderService, IMouseService, IRenderService, ISelectionService, IThemeService } from 'browser/services/Services';
import { ThemeService } from 'browser/services/ThemeService';
import { KeyboardService } from 'browser/services/KeyboardService';
import { channels, color } from 'common/Color';
import { channels, color, rgb } from 'common/Color';
import { CoreTerminal } from 'common/CoreTerminal';
import * as Browser from 'common/Platform';
import { ColorRequestType, CoreMouseAction, CoreMouseButton, CoreMouseEventType, IColorEvent, ITerminalOptions, KeyboardResultType, SpecialColorIndex } from 'common/Types';
import { DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';
import { IBuffer } from 'common/buffer/Types';
import { C0, C1_ESCAPED } from 'common/data/EscapeSequences';
import { C0, C1ESCAPED } from 'common/data/EscapeSequences';
import { toRgbString } from 'common/input/XParseColor';
import { DecorationService } from 'common/services/DecorationService';
import { IDecorationService } from 'common/services/Services';
import { WindowsOptionsReportType } from '../common/InputHandler';
import { AccessibilityManager } from './AccessibilityManager';
import { Linkifier } from './Linkifier';
import { Emitter, Event } from 'vs/base/common/event';
import { addDisposableListener } from 'vs/base/browser/dom';
import { MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { Emitter, EventUtils, type IEvent } from 'common/Event';
import { addDisposableListener } from 'browser/Dom';
import { MutableDisposable, toDisposable } from 'common/Lifecycle';
export class CoreBrowserTerminal extends CoreTerminal implements ITerminal {
public textarea: HTMLTextAreaElement | undefined;
@@ -135,15 +135,15 @@ export class CoreBrowserTerminal extends CoreTerminal implements ITerminal {
public readonly onBell = this._onBell.event;
private _onFocus = this._register(new Emitter<void>());
public get onFocus(): Event<void> { return this._onFocus.event; }
public get onFocus(): IEvent<void> { return this._onFocus.event; }
private _onBlur = this._register(new Emitter<void>());
public get onBlur(): Event<void> { return this._onBlur.event; }
public get onBlur(): IEvent<void> { return this._onBlur.event; }
private _onA11yCharEmitter = this._register(new Emitter<string>());
public get onA11yChar(): Event<string> { return this._onA11yCharEmitter.event; }
public get onA11yChar(): IEvent<string> { return this._onA11yCharEmitter.event; }
private _onA11yTabEmitter = this._register(new Emitter<number>());
public get onA11yTab(): Event<number> { return this._onA11yTabEmitter.event; }
public get onA11yTab(): IEvent<number> { return this._onA11yTabEmitter.event; }
private _onWillOpen = this._register(new Emitter<HTMLElement>());
public get onWillOpen(): Event<HTMLElement> { return this._onWillOpen.event; }
public get onWillOpen(): IEvent<HTMLElement> { return this._onWillOpen.event; }
private readonly _onDimensionsChange = this._register(new Emitter<IRenderDimensionsApi>());
public readonly onDimensionsChange = this._onDimensionsChange.event;
@@ -187,10 +187,10 @@ export class CoreBrowserTerminal extends CoreTerminal implements ITerminal {
this._register(this._inputHandler.onRequestReset(() => this.reset()));
this._register(this._inputHandler.onRequestWindowsOptionsReport(type => this._reportWindowsOptions(type)));
this._register(this._inputHandler.onColor((event) => this._handleColorEvent(event)));
this._register(Event.forward(this._inputHandler.onCursorMove, this._onCursorMove));
this._register(Event.forward(this._inputHandler.onTitleChange, this._onTitleChange));
this._register(Event.forward(this._inputHandler.onA11yChar, this._onA11yCharEmitter));
this._register(Event.forward(this._inputHandler.onA11yTab, this._onA11yTabEmitter));
this._register(EventUtils.forward(this._inputHandler.onCursorMove, this._onCursorMove));
this._register(EventUtils.forward(this._inputHandler.onTitleChange, this._onTitleChange));
this._register(EventUtils.forward(this._inputHandler.onA11yChar, this._onA11yCharEmitter));
this._register(EventUtils.forward(this._inputHandler.onA11yTab, this._onA11yTabEmitter));
// Setup listeners
this._register(this._bufferService.onResize(e => this._afterResize(e.cols, e.rows)));
@@ -235,7 +235,7 @@ export class CoreBrowserTerminal extends CoreTerminal implements ITerminal {
const colorRgb = color.toColorRGB(acc === 'ansi'
? this._themeService.colors.ansi[req.index]
: this._themeService.colors[acc]);
this.coreService.triggerDataEvent(`${C0.ESC}]${ident};${toRgbString(colorRgb)}${C1_ESCAPED.ST}`);
this.coreService.triggerDataEvent(`${C0.ESC}]${ident};${toRgbString(colorRgb)}${C1ESCAPED.ST}`);
break;
case ColorRequestType.SET:
if (acc === 'ansi') {
@@ -252,6 +252,20 @@ export class CoreBrowserTerminal extends CoreTerminal implements ITerminal {
}
}
/**
* Reports the current color scheme (dark or light) based on the relative luminance
* of the background and foreground theme colors.
* Sends CSI ? 997 ; 1 n for dark mode or CSI ? 997 ; 2 n for light mode.
*/
private _reportColorScheme(): void {
if (!this._themeService) return;
const bgLuminance = rgb.relativeLuminance(this._themeService.colors.background.rgba >> 8);
const fgLuminance = rgb.relativeLuminance(this._themeService.colors.foreground.rgba >> 8);
// Dark mode = background is darker than foreground (lower luminance)
const colorSchemeMode = bgLuminance < fgLuminance ? 1 : 2;
this.coreService.triggerDataEvent(`${C0.ESC}[?997;${colorSchemeMode}n`);
}
protected _setup(): void {
super._setup();
@@ -495,6 +509,16 @@ export class CoreBrowserTerminal extends CoreTerminal implements ITerminal {
this._themeService = this._instantiationService.createInstance(ThemeService);
this._instantiationService.setService(IThemeService, this._themeService);
// CSI ? 996 n - color scheme query (https://contour-terminal.org/vt-extensions/color-palette-update-notifications/)
this._register(this._inputHandler.onRequestColorSchemeQuery(() => this._reportColorScheme()));
// Emit unsolicited color scheme notification on theme change when DECSET 2031 is enabled
this._register(this._themeService.onChangeColors(() => {
if (this.coreService.decPrivateModes.colorSchemeUpdates) {
this._reportColorScheme();
}
}));
this._characterJoinerService = this._instantiationService.createInstance(CharacterJoinerService);
this._instantiationService.setService(ICharacterJoinerService, this._characterJoinerService);
@@ -566,7 +590,7 @@ export class CoreBrowserTerminal extends CoreTerminal implements ITerminal {
this.textarea!.focus();
this.textarea!.select();
}));
this._register(Event.any(
this._register(EventUtils.any(
this._onScroll.event,
this._inputHandler.onScroll
)(() => {
@@ -592,11 +616,14 @@ export class CoreBrowserTerminal extends CoreTerminal implements ITerminal {
}
this._register(this.optionsService.onSpecificOptionChange('screenReaderMode', e => this._handleScreenReaderModeOptionChange(e)));
if (this.options.overviewRuler.width) {
const showScrollbar = this.options.scrollbar?.showScrollbar ?? true;
const overviewRulerWidth = this.options.scrollbar?.width;
if (showScrollbar && overviewRulerWidth) {
this._overviewRulerRenderer = this._register(this._instantiationService.createInstance(OverviewRulerRenderer, this._viewportElement, this.screenElement));
}
this.optionsService.onSpecificOptionChange('overviewRuler', value => {
if (!this._overviewRulerRenderer && value && this._viewportElement && this.screenElement) {
this.optionsService.onSpecificOptionChange('scrollbar', value => {
const shouldShow = (value?.showScrollbar ?? true) && !!value?.width;
if (!this._overviewRulerRenderer && shouldShow && this._viewportElement && this.screenElement) {
this._overviewRulerRenderer = this._register(this._instantiationService.createInstance(OverviewRulerRenderer, this._viewportElement, this.screenElement));
}
});
@@ -739,11 +766,12 @@ export class CoreBrowserTerminal extends CoreTerminal implements ITerminal {
this._document!.removeEventListener('mousemove', requestedEvents.mousedrag);
}
}
return this.cancel(ev);
},
wheel: (ev: WheelEvent) => {
sendEvent(ev);
return this.cancel(ev, true);
ev.preventDefault();
ev.stopPropagation();
return false;
},
mousedrag: (ev: MouseEvent) => {
// deal only with move while a button is held
@@ -793,15 +821,15 @@ export class CoreBrowserTerminal extends CoreTerminal implements ITerminal {
if (!(events & CoreMouseEventType.UP)) {
this._document!.removeEventListener('mouseup', requestedEvents.mouseup!);
requestedEvents.mouseup = null;
} else if (!requestedEvents.mouseup) {
requestedEvents.mouseup = eventListeners.mouseup;
} else {
requestedEvents.mouseup ??= eventListeners.mouseup;
}
if (!(events & CoreMouseEventType.DRAG)) {
this._document!.removeEventListener('mousemove', requestedEvents.mousedrag!);
requestedEvents.mousedrag = null;
} else if (!requestedEvents.mousedrag) {
requestedEvents.mousedrag = eventListeners.mousedrag;
} else {
requestedEvents.mousedrag ??= eventListeners.mousedrag;
}
}));
// force initial onProtocolChange so we dont miss early mouse requests
@@ -843,8 +871,6 @@ export class CoreBrowserTerminal extends CoreTerminal implements ITerminal {
if (requestedEvents.mousedrag) {
this._document!.addEventListener('mousemove', requestedEvents.mousedrag);
}
return this.cancel(ev);
}));
this._register(addDisposableListener(el, 'wheel', (ev: WheelEvent) => {
@@ -875,13 +901,17 @@ export class CoreBrowserTerminal extends CoreTerminal implements ITerminal {
self._coreBrowserService?.dpr
);
if (lines === 0) {
return this.cancel(ev, true);
ev.preventDefault();
ev.stopPropagation();
return false;
}
// Construct and send sequences
const sequence = C0.ESC + (this.coreService.decPrivateModes.applicationCursorKeys ? 'O' : '[') + (ev.deltaY < 0 ? 'A' : 'B');
this.coreService.triggerDataEvent(sequence, true);
return this.cancel(ev, true);
ev.preventDefault();
ev.stopPropagation();
return false;
}
}, { passive: false }));
}
@@ -1091,7 +1121,9 @@ export class CoreBrowserTerminal extends CoreTerminal implements ITerminal {
if (result.type === KeyboardResultType.PAGE_DOWN || result.type === KeyboardResultType.PAGE_UP) {
const scrollCount = this.rows - 1;
this.scrollLines(result.type === KeyboardResultType.PAGE_UP ? -scrollCount : scrollCount);
return this.cancel(event, true);
event.preventDefault();
event.stopPropagation();
return false;
}
if (result.type === KeyboardResultType.SELECT_ALL) {
@@ -1104,7 +1136,8 @@ export class CoreBrowserTerminal extends CoreTerminal implements ITerminal {
if (result.cancel) {
// The event is canceled at the end already, is this necessary?
this.cancel(event, true);
event.preventDefault();
event.stopPropagation();
}
if (!result.key) {
@@ -1132,16 +1165,19 @@ export class CoreBrowserTerminal extends CoreTerminal implements ITerminal {
this.textarea!.value = '';
}
const wasModifierOnly = this._keyboardService.useWin32InputMode && wasModifierKeyOnlyEvent(event);
this._onKey.fire({ key: result.key, domEvent: event });
this._showCursor();
this.coreService.triggerDataEvent(result.key, true);
this.coreService.triggerDataEvent(result.key, !wasModifierOnly);
// Cancel events when not in screen reader mode so events don't get bubbled up and handled by
// other listeners. When screen reader mode is enabled, we don't cancel them (unless ctrl or alt
// is also depressed) so that the cursor textarea can be updated, which triggers the screen
// reader to read it.
if (!this.optionsService.rawOptions.screenReaderMode || event.altKey || event.ctrlKey) {
return this.cancel(event, true);
event.preventDefault();
event.stopPropagation();
return false;
}
this._keyDownHandled = true;
@@ -1175,7 +1211,8 @@ export class CoreBrowserTerminal extends CoreTerminal implements ITerminal {
// Handle key release for Kitty keyboard protocol
const result = this._keyboardService.evaluateKeyUp(ev);
if (result?.key) {
this.coreService.triggerDataEvent(result.key, true);
const wasModifierOnly = this._keyboardService.useWin32InputMode && wasModifierKeyOnlyEvent(ev);
this.coreService.triggerDataEvent(result.key, !wasModifierOnly);
}
this.updateCursorStyle(ev);
@@ -1201,8 +1238,6 @@ export class CoreBrowserTerminal extends CoreTerminal implements ITerminal {
return false;
}
this.cancel(ev);
if (ev.charCode) {
key = ev.charCode;
} else if (ev.which === null || ev.which === undefined) {
@@ -1255,8 +1290,6 @@ export class CoreBrowserTerminal extends CoreTerminal implements ITerminal {
const text = ev.data;
this.coreService.triggerDataEvent(text, true);
this.cancel(ev);
return true;
}
@@ -1368,15 +1401,6 @@ export class CoreBrowserTerminal extends CoreTerminal implements ITerminal {
}
}
// TODO: Remove cancel function and cancelEvents option
public cancel(ev: MouseEvent | WheelEvent | KeyboardEvent | InputEvent, force?: boolean): boolean | undefined {
if (!this.options.cancelEvents && !force) {
return;
}
ev.preventDefault();
ev.stopPropagation();
return false;
}
}
/**
@@ -1386,5 +1410,10 @@ export class CoreBrowserTerminal extends CoreTerminal implements ITerminal {
function wasModifierKeyOnlyEvent(ev: KeyboardEvent): boolean {
return ev.keyCode === 16 || // Shift
ev.keyCode === 17 || // Ctrl
ev.keyCode === 18; // Alt
ev.keyCode === 18 || // Alt
ev.keyCode === 91 || // Meta (Left)
ev.keyCode === 92 || // Meta (Right)
ev.keyCode === 93 || // Meta (Menu)
ev.keyCode === 224 || // Meta (Firefox)
ev.key === 'Meta';
}
+178
View File
@@ -0,0 +1,178 @@
/**
* Copyright (c) 2026 The xterm.js authors. All rights reserved.
* @license MIT
*
* Minimal DOM helpers for xterm.js browser code.
*/
import { IntervalTimer } from 'common/Async';
import { IDisposable } from 'common/Lifecycle';
export function getWindow(e: Node | UIEvent | undefined | null): Window {
const candidateNode = e as Node | undefined | null;
if (candidateNode?.ownerDocument?.defaultView) {
return candidateNode.ownerDocument.defaultView;
}
const candidateEvent = e as UIEvent | undefined | null;
if (candidateEvent?.view) {
return candidateEvent.view;
}
return window;
}
class DomListener implements IDisposable {
private _handler: ((e: any) => void) | null;
private _node: EventTarget | null;
private readonly _type: string;
private readonly _options: boolean | AddEventListenerOptions | undefined;
constructor(node: EventTarget, type: string, handler: (e: any) => void, options?: boolean | AddEventListenerOptions) {
this._node = node;
this._type = type;
this._handler = handler;
this._options = options;
node.addEventListener(type, handler, options);
}
public dispose(): void {
if (!this._node || !this._handler) {
return;
}
this._node.removeEventListener(this._type, this._handler, this._options);
this._node = null;
this._handler = null;
}
}
export function addDisposableListener<K extends keyof GlobalEventHandlersEventMap>(node: EventTarget, type: K, handler: (event: GlobalEventHandlersEventMap[K]) => void, useCapture?: boolean): IDisposable;
export function addDisposableListener(node: EventTarget, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable;
export function addDisposableListener(node: EventTarget, type: string, handler: (event: any) => void, options: AddEventListenerOptions): IDisposable;
export function addDisposableListener(node: EventTarget, type: string, handler: (event: any) => void, useCaptureOrOptions?: boolean | AddEventListenerOptions): IDisposable {
return new DomListener(node, type, handler, useCaptureOrOptions);
}
export function addStandardDisposableListener(node: HTMLElement, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable {
return addDisposableListener(node, type, handler, useCapture);
}
export const eventType = {
CLICK: 'click',
MOUSE_DOWN: 'mousedown',
MOUSE_OVER: 'mouseover',
MOUSE_LEAVE: 'mouseleave',
KEY_DOWN: 'keydown',
KEY_UP: 'keyup',
INPUT: 'input',
BLUR: 'blur',
FOCUS: 'focus',
CHANGE: 'change',
POINTER_DOWN: 'pointerdown',
POINTER_MOVE: 'pointermove',
POINTER_UP: 'pointerup',
MOUSE_WHEEL: 'wheel',
WHEEL: 'wheel'
} as const;
export function getDomNodePagePosition(domNode: HTMLElement): { left: number, top: number, width: number, height: number } {
const bb = domNode.getBoundingClientRect();
const win = getWindow(domNode);
return {
left: bb.left + win.scrollX,
top: bb.top + win.scrollY,
width: bb.width,
height: bb.height
};
}
class AnimationFrameQueueItem implements IDisposable {
private _canceled = false;
constructor(private readonly _runner: () => void, public priority: number) {
}
public dispose(): void {
this._canceled = true;
}
public execute(): void {
if (this._canceled) {
return;
}
try {
this._runner();
} catch (e) {
console.error(e);
}
}
public static sort(a: AnimationFrameQueueItem, b: AnimationFrameQueueItem): number {
return b.priority - a.priority;
}
}
interface IWindowAnimationFrameState {
next: AnimationFrameQueueItem[];
current: AnimationFrameQueueItem[];
animFrameRequested: boolean;
inAnimationFrameRunner: boolean;
}
const animationFrameState = new Map<Window, IWindowAnimationFrameState>();
function getAnimationFrameState(targetWindow: Window): IWindowAnimationFrameState {
let state = animationFrameState.get(targetWindow);
if (!state) {
state = {
next: [],
current: [],
animFrameRequested: false,
inAnimationFrameRunner: false
};
animationFrameState.set(targetWindow, state);
}
return state;
}
function animationFrameRunner(targetWindow: Window): void {
const state = getAnimationFrameState(targetWindow);
state.animFrameRequested = false;
state.current = state.next;
state.next = [];
state.inAnimationFrameRunner = true;
while (state.current.length > 0) {
state.current.sort(AnimationFrameQueueItem.sort);
const top = state.current.shift()!;
top.execute();
}
state.inAnimationFrameRunner = false;
}
export function scheduleAtNextAnimationFrame(targetWindow: Window, runner: () => void, priority: number = 0): IDisposable {
const state = getAnimationFrameState(targetWindow);
const item = new AnimationFrameQueueItem(runner, priority);
state.next.push(item);
if (!state.animFrameRequested) {
state.animFrameRequested = true;
targetWindow.requestAnimationFrame(() => animationFrameRunner(targetWindow));
}
return item;
}
export class WindowIntervalTimer extends IntervalTimer {
private readonly _defaultTarget?: Window;
constructor(node?: Node) {
super();
this._defaultTarget = node ? getWindow(node) : undefined;
}
public cancelAndSet(runner: () => void, interval: number, targetWindow?: Window): void {
super.cancelAndSet(runner, interval, targetWindow ?? this._defaultTarget ?? window);
}
}
+3 -3
View File
@@ -4,12 +4,12 @@
*/
import { IBufferCellPosition, ILink, ILinkDecorations, ILinkWithState, ILinkifier2, ILinkifierEvent } from 'browser/Types';
import { Disposable, dispose, toDisposable } from 'vs/base/common/lifecycle';
import { Disposable, dispose, toDisposable } from 'common/Lifecycle';
import { IDisposable } from 'common/Types';
import { IBufferService } from 'common/services/Services';
import { ILinkProviderService, IMouseService, IRenderService } from './services/Services';
import { Emitter } from 'vs/base/common/event';
import { addDisposableListener } from 'vs/base/browser/dom';
import { Emitter } from 'common/Event';
import { addDisposableListener } from 'browser/Dom';
export class Linkifier extends Disposable implements ILinkifier2 {
public get currentLink(): ILinkWithState | undefined { return this._currentLink; }
+3 -1
View File
@@ -9,6 +9,8 @@ import { CellData } from 'common/buffer/CellData';
import { IBufferService, IOptionsService, IOscLinkService } from 'common/services/Services';
export class OscLinkProvider implements ILinkProvider {
private readonly _workCell = new CellData();
constructor(
@IBufferService private readonly _bufferService: IBufferService,
@IOptionsService private readonly _optionsService: IOptionsService,
@@ -25,7 +27,7 @@ export class OscLinkProvider implements ILinkProvider {
const result: ILink[] = [];
const linkHandler = this._optionsService.rawOptions.linkHandler;
const cell = new CellData();
const cell = this._workCell;
const lineLength = line.getTrimmedLength();
let currentLinkId = -1;
let currentStart = -1;
+2 -2
View File
@@ -40,8 +40,8 @@ export class RenderDebouncer implements IRenderDebouncerWithCallback {
public refresh(rowStart: number | undefined, rowEnd: number | undefined, rowCount: number): void {
this._rowCount = rowCount;
// Get the min/max row start/end for the arg values
rowStart = rowStart !== undefined ? rowStart : 0;
rowEnd = rowEnd !== undefined ? rowEnd : this._rowCount - 1;
rowStart = rowStart ?? 0;
rowEnd = rowEnd ?? this._rowCount - 1;
// Set the properties to the updated values
this._rowStart = this._rowStart !== undefined ? Math.min(this._rowStart, rowStart) : rowStart;
this._rowEnd = this._rowEnd !== undefined ? Math.max(this._rowEnd, rowEnd) : rowEnd;
+107 -43
View File
@@ -17,6 +17,21 @@ const INIT_ROWS = 24;
// grab wcwidth from mock unicode service (hardcoded to V6)
const wcwidth = (new MockUnicodeService()).wcwidth;
function assertLineEqual(actual: any, expected: any): void {
assert.isOk(actual);
assert.isOk(expected);
assert.equal(actual.length, expected.length);
assert.equal(actual.isWrapped, expected.isWrapped);
const actualCell = new CellData();
const expectedCell = new CellData();
for (let i = 0; i < actual.length; i++) {
assert.deepEqual(
actual.loadCell(i, actualCell).getAsCharData(),
expected.loadCell(i, expectedCell).getAsCharData()
);
}
}
describe('Terminal', () => {
let term: TestTerminal;
const termOptions = {
@@ -183,16 +198,14 @@ describe('Terminal', () => {
assert.equal(term.buffer.ybase, 0);
assert.equal(term.buffer.ydisp, 0);
assert.equal(term.buffer.lines.length, term.rows);
assert.deepEqual(term.buffer.lines.get(0), promptLine);
assertLineEqual(term.buffer.lines.get(0), promptLine);
for (let i = 1; i < term.rows; i++) {
assert.deepEqual(term.buffer.lines.get(i), term.buffer.getBlankLine(DEFAULT_ATTR_DATA));
assertLineEqual(term.buffer.lines.get(i), term.buffer.getBlankLine(DEFAULT_ATTR_DATA));
}
});
it('should clear a buffer larger than rows', async () => {
// Fill the buffer with dummy rows
for (let i = 0; i < term.rows * 2; i++) {
await term.writeP('test\n');
}
await term.writeP('test\n'.repeat(term.rows * 2));
const promptLine = term.buffer.lines.get(term.buffer.ybase + term.buffer.y);
term.clear();
@@ -200,9 +213,9 @@ describe('Terminal', () => {
assert.equal(term.buffer.ybase, 0);
assert.equal(term.buffer.ydisp, 0);
assert.equal(term.buffer.lines.length, term.rows);
assert.deepEqual(term.buffer.lines.get(0), promptLine);
assertLineEqual(term.buffer.lines.get(0), promptLine);
for (let i = 1; i < term.rows; i++) {
assert.deepEqual(term.buffer.lines.get(i), term.buffer.getBlankLine(DEFAULT_ATTR_DATA));
assertLineEqual(term.buffer.lines.get(i), term.buffer.getBlankLine(DEFAULT_ATTR_DATA));
}
});
it('should not break the prompt when cleared twice', () => {
@@ -213,9 +226,9 @@ describe('Terminal', () => {
assert.equal(term.buffer.ybase, 0);
assert.equal(term.buffer.ydisp, 0);
assert.equal(term.buffer.lines.length, term.rows);
assert.deepEqual(term.buffer.lines.get(0), promptLine);
assertLineEqual(term.buffer.lines.get(0), promptLine);
for (let i = 1; i < term.rows; i++) {
assert.deepEqual(term.buffer.lines.get(i), term.buffer.getBlankLine(DEFAULT_ATTR_DATA));
assertLineEqual(term.buffer.lines.get(i), term.buffer.getBlankLine(DEFAULT_ATTR_DATA));
}
});
});
@@ -389,9 +402,7 @@ describe('Terminal', () => {
it('should not scroll down, when a custom keydown handler prevents the event', async () => {
// Add some output to the terminal
for (let i = 0; i < term.rows * 3; i++) {
await term.writeP('test\r\n');
}
await term.writeP('test\r\n'.repeat(term.rows * 3));
const startYDisp = (term.rows * 2) + 1;
term.attachCustomKeyEventHandler(() => {
return false;
@@ -405,6 +416,42 @@ describe('Terminal', () => {
});
});
describe('keyDown', () => {
it('should not scroll down on modifier-only input in win32 input mode', async () => {
term.options.vtExtensions = { win32InputMode: true };
term.coreService.decPrivateModes.win32InputMode = true;
(term as any).textarea = { value: '' };
await term.writeP('test\r\n'.repeat(term.rows * 3));
const startYDisp = term.buffer.ydisp;
term.scrollLines(-1);
const scrolledYDisp = term.buffer.ydisp;
assert.equal(scrolledYDisp, startYDisp - 1);
const evKeyDown = {
type: 'keydown',
key: 'Control',
keyCode: 17,
ctrlKey: true,
preventDefault: () => { },
stopPropagation: () => { }
} as KeyboardEvent;
const evKeyUp = {
type: 'keyup',
key: 'Control',
keyCode: 17,
preventDefault: () => { },
stopPropagation: () => { }
} as KeyboardEvent;
term.keyDown(evKeyDown);
assert.equal(term.buffer.ydisp, scrolledYDisp);
(term as any)._keyUp(evKeyUp);
assert.equal(term.buffer.ydisp, scrolledYDisp);
});
});
describe('scroll() function', () => {
describe('when scrollback > 0', () => {
it('should create a new line and scroll', () => {
@@ -731,70 +778,87 @@ describe('Terminal', () => {
it(`${range}: 2 characters per cell`, async function (): Promise<void> {
const high = String.fromCharCode(0xD800);
const cell = new CellData();
const values: string[] = [];
for (let j = i; j <= i + 0xF; j++) {
await term.writeP(high + String.fromCharCode(j));
const tchar = term.buffer.lines.get(0)!.loadCell(0, cell);
assert.equal(tchar.getChars(), high + String.fromCharCode(j));
values.push(high + String.fromCharCode(j));
}
await term.writeP(values.join('\r\n'));
for (let idx = 0; idx < values.length; idx++) {
const expected = values[idx];
const tchar = term.buffer.lines.get(idx)!.loadCell(0, cell);
assert.equal(tchar.getChars(), expected);
assert.equal(tchar.getChars().length, 2);
assert.equal(tchar.getWidth(), 1);
assert.equal(term.buffer.lines.get(0)!.loadCell(1, cell).getChars(), '');
term.reset();
assert.equal(term.buffer.lines.get(idx)!.loadCell(1, cell).getChars(), '');
}
});
it(`${range}: 2 characters at last cell`, async () => {
const high = String.fromCharCode(0xD800);
const cell = new CellData();
term.buffer.x = term.cols - 1;
const values: string[] = [];
for (let j = i; j <= i + 0xF; j++) {
await term.writeP(high + String.fromCharCode(j));
assert.equal(term.buffer.lines.get(0)!.loadCell(term.buffer.x - 1, cell).getChars(), high + String.fromCharCode(j));
assert.equal(term.buffer.lines.get(0)!.loadCell(term.buffer.x - 1, cell).getChars().length, 2);
assert.equal(term.buffer.lines.get(1)!.loadCell(0, cell).getChars(), '');
term.reset();
values.push(high + String.fromCharCode(j));
}
await term.writeP(values.map((value, idx) => `\x1b[${idx + 1};${term.cols}H${value}`).join(''));
for (let idx = 0; idx < values.length; idx++) {
const expected = values[idx];
assert.equal(term.buffer.lines.get(idx)!.loadCell(term.cols - 1, cell).getChars(), expected);
assert.equal(term.buffer.lines.get(idx)!.loadCell(term.cols - 1, cell).getChars().length, 2);
assert.equal(term.buffer.lines.get(idx + 1)!.loadCell(0, cell).getChars(), '');
}
});
it(`${range}: 2 characters per cell over line end with autowrap`, async function (): Promise<void> {
const high = String.fromCharCode(0xD800);
const cell = new CellData();
term.resize(term.cols, 40);
const values: string[] = [];
for (let j = i; j <= i + 0xF; j++) {
term.buffer.x = term.cols - 1;
await term.writeP('a' + high + String.fromCharCode(j));
assert.equal(term.buffer.lines.get(0)!.loadCell(term.cols - 1, cell).getChars(), 'a');
assert.equal(term.buffer.lines.get(1)!.loadCell(0, cell).getChars(), high + String.fromCharCode(j));
assert.equal(term.buffer.lines.get(1)!.loadCell(0, cell).getChars().length, 2);
assert.equal(term.buffer.lines.get(1)!.loadCell(1, cell).getChars(), '');
term.reset();
values.push(high + String.fromCharCode(j));
}
await term.writeP(values.map((value, idx) => `\x1b[${idx * 2 + 1};${term.cols}H` + 'a' + value).join(''));
for (let idx = 0; idx < values.length; idx++) {
const expected = values[idx];
const row = idx * 2;
assert.equal(term.buffer.lines.get(row)!.loadCell(term.cols - 1, cell).getChars(), 'a');
assert.equal(term.buffer.lines.get(row + 1)!.loadCell(0, cell).getChars(), expected);
assert.equal(term.buffer.lines.get(row + 1)!.loadCell(0, cell).getChars().length, 2);
assert.equal(term.buffer.lines.get(row + 1)!.loadCell(1, cell).getChars(), '');
}
});
it(`${range}: 2 characters per cell over line end without autowrap`, async function (): Promise<void> {
const high = String.fromCharCode(0xD800);
const cell = new CellData();
const values: string[] = [];
for (let j = i; j <= i + 0xF; j++) {
term.buffer.x = term.cols - 1;
await term.writeP('\x1b[?7l'); // Disable wraparound mode
const width = wcwidth((0xD800 - 0xD800) * 0x400 + j - 0xDC00 + 0x10000);
if (width !== 1) {
continue;
}
await term.writeP('a' + high + String.fromCharCode(j));
// auto wraparound mode should cut off the rest of the line
assert.equal(term.buffer.lines.get(0)!.loadCell(term.cols - 1, cell).getChars(), high + String.fromCharCode(j));
assert.equal(term.buffer.lines.get(0)!.loadCell(term.cols - 1, cell).getChars().length, 2);
assert.equal(term.buffer.lines.get(1)!.loadCell(1, cell).getChars(), '');
term.reset();
values.push(high + String.fromCharCode(j));
}
await term.writeP('\x1b[?7l' + values.map((value, idx) => `\x1b[${idx + 1};${term.cols}H` + 'a' + value).join(''));
for (let idx = 0; idx < values.length; idx++) {
const expected = values[idx];
assert.equal(term.buffer.lines.get(idx)!.loadCell(term.cols - 1, cell).getChars(), expected);
assert.equal(term.buffer.lines.get(idx)!.loadCell(term.cols - 1, cell).getChars().length, 2);
assert.equal(term.buffer.lines.get(idx + 1)!.loadCell(1, cell).getChars(), '');
}
});
it(`${range}: splitted surrogates`, async function (): Promise<void> {
const high = String.fromCharCode(0xD800);
const cell = new CellData();
const values: string[] = [];
for (let j = i; j <= i + 0xF; j++) {
await term.writeP(high + String.fromCharCode(j));
const tchar = term.buffer.lines.get(0)!.loadCell(0, cell);
assert.equal(tchar.getChars(), high + String.fromCharCode(j));
values.push(high + String.fromCharCode(j));
}
await term.writeP(values.join('\r\n'));
for (let idx = 0; idx < values.length; idx++) {
const expected = values[idx];
const tchar = term.buffer.lines.get(idx)!.loadCell(0, cell);
assert.equal(tchar.getChars(), expected);
assert.equal(tchar.getChars().length, 2);
assert.equal(tchar.getWidth(), 1);
assert.equal(term.buffer.lines.get(0)!.loadCell(1, cell).getChars(), '');
term.reset();
assert.equal(term.buffer.lines.get(idx)!.loadCell(1, cell).getChars(), '');
}
});
}
+30 -30
View File
@@ -18,7 +18,7 @@ import { AttributeData } from 'common/buffer/AttributeData';
import { ISelectionRedrawRequestEvent, ISelectionRequestScrollLinesEvent } from 'browser/selection/Types';
import { css } from 'common/Color';
import { createRenderDimensions } from 'browser/renderer/shared/RendererUtils';
import { Emitter, type Event } from 'vs/base/common/event';
import { Emitter, type IEvent } from 'common/Event';
export class TestTerminal extends CoreBrowserTerminal {
public get curAttrData(): IAttributeData { return (this as any)._inputHandler._curAttrData; }
@@ -30,24 +30,24 @@ export class TestTerminal extends CoreBrowserTerminal {
}
export class MockTerminal implements ITerminal {
public onBlur!: Event<void>;
public onFocus!: Event<void>;
public onA11yChar!: Event<string>;
public onWriteParsed!: Event<void>;
public onA11yTab!: Event<number>;
public onCursorMove!: Event<void>;
public onLineFeed!: Event<void>;
public onSelectionChange!: Event<void>;
public onData!: Event<string>;
public onBinary!: Event<string>;
public onTitleChange!: Event<string>;
public onBell!: Event<void>;
public onScroll!: Event<number>;
public onWillOpen!: Event<HTMLElement>;
public onKey!: Event<{ key: string, domEvent: KeyboardEvent }>;
public onRender!: Event<{ start: number, end: number }>;
public onResize!: Event<{ cols: number, rows: number }>;
public onDimensionsChange!: Event<IRenderDimensionsApi>;
public onBlur!: IEvent<void>;
public onFocus!: IEvent<void>;
public onA11yChar!: IEvent<string>;
public onWriteParsed!: IEvent<void>;
public onA11yTab!: IEvent<number>;
public onCursorMove!: IEvent<void>;
public onLineFeed!: IEvent<void>;
public onSelectionChange!: IEvent<void>;
public onData!: IEvent<string>;
public onBinary!: IEvent<string>;
public onTitleChange!: IEvent<string>;
public onBell!: IEvent<void>;
public onScroll!: IEvent<number>;
public onWillOpen!: IEvent<HTMLElement>;
public onKey!: IEvent<{ key: string, domEvent: KeyboardEvent }>;
public onRender!: IEvent<{ start: number, end: number }>;
public onResize!: IEvent<{ cols: number, rows: number }>;
public onDimensionsChange!: IEvent<IRenderDimensionsApi>;
public dimensions: IRenderDimensionsApi | undefined;
public markers!: IMarker[];
public linkifier: ILinkifier2 | undefined;
@@ -107,6 +107,9 @@ export class MockTerminal implements ITerminal {
public registerOscHandler(ident: number, callback: (data: string) => boolean | Promise<boolean>): IDisposable {
throw new Error('Method not implemented.');
}
public registerApcHandler(ident: number, callback: (data: string) => boolean | Promise<boolean>): IDisposable {
throw new Error('Method not implemented.');
}
public registerLinkProvider(linkProvider: ILinkProvider): IDisposable {
throw new Error('Method not implemented.');
}
@@ -195,9 +198,6 @@ export class MockTerminal implements ITerminal {
public scrollToRow(absoluteRow: number): number {
throw new Error('Method not implemented.');
}
public cancel(ev: MouseEvent | WheelEvent | KeyboardEvent | InputEvent, force?: boolean): void {
throw new Error('Method not implemented.');
}
public log(text: string): void {
throw new Error('Method not implemented.');
}
@@ -273,9 +273,9 @@ export class MockBuffer implements IBuffer {
}
export class MockRenderer implements IRenderer {
public onRequestRedraw!: Event<IRequestRedrawEvent>;
public onCanvasResize!: Event<{ width: number, height: number }>;
public onRender!: Event<{ start: number, end: number }>;
public onRequestRedraw!: IEvent<IRequestRedrawEvent>;
public onCanvasResize!: IEvent<{ width: number, height: number }>;
public onRender!: IEvent<{ start: number, end: number }>;
public dispose(): void {
throw new Error('Method not implemented.');
}
@@ -378,7 +378,7 @@ export class MockCoreBrowserService implements ICoreBrowserService {
export class MockCharSizeService implements ICharSizeService {
public serviceBrand: undefined;
public get hasValidSize(): boolean { return this.width > 0 && this.height > 0; }
public onCharSizeChange: Event<void> = new Emitter<void>().event;
public onCharSizeChange: IEvent<void> = new Emitter<void>().event;
constructor(public width: number, public height: number) {}
public measure(): void {}
}
@@ -396,10 +396,10 @@ export class MockMouseService implements IMouseService {
export class MockRenderService implements IRenderService {
public serviceBrand: undefined;
public onDimensionsChange: Event<IRenderDimensions> = new Emitter<IRenderDimensions>().event;
public onRenderedViewportChange: Event<{ start: number, end: number }> = new Emitter<{ start: number, end: number }>().event;
public onRender: Event<{ start: number, end: number }> = new Emitter<{ start: number, end: number }>().event;
public onRefreshRequest: Event<{ start: number, end: number}> = new Emitter<{ start: number, end: number }>().event;
public onDimensionsChange: IEvent<IRenderDimensions> = new Emitter<IRenderDimensions>().event;
public onRenderedViewportChange: IEvent<{ start: number, end: number }> = new Emitter<{ start: number, end: number }>().event;
public onRender: IEvent<{ start: number, end: number }> = new Emitter<{ start: number, end: number }>().event;
public onRefreshRequest: IEvent<{ start: number, end: number}> = new Emitter<{ start: number, end: number }>().event;
public dimensions: IRenderDimensions = createRenderDimensions();
public refreshRows(start: number, end: number): void {
throw new Error('Method not implemented.');
+2 -2
View File
@@ -37,8 +37,8 @@ export class TimeBasedDebouncer implements IRenderDebouncer {
public refresh(rowStart: number | undefined, rowEnd: number | undefined, rowCount: number): void {
this._rowCount = rowCount;
// Get the min/max row start/end for the arg values
rowStart = rowStart !== undefined ? rowStart : 0;
rowEnd = rowEnd !== undefined ? rowEnd : this._rowCount - 1;
rowStart = rowStart ?? 0;
rowEnd = rowEnd ?? this._rowCount - 1;
// Set the properties to the updated values
this._rowStart = this._rowStart !== undefined ? Math.min(this._rowStart, rowStart) : rowStart;
this._rowEnd = this._rowEnd !== undefined ? Math.max(this._rowEnd, rowEnd) : rowEnd;
+10 -12
View File
@@ -7,7 +7,7 @@ import { CharData, IColor, ICoreTerminal, ITerminalOptions } from 'common/Types'
import { IBuffer } from 'common/buffer/Types';
import { IDisposable, IRenderDimensions as IRenderDimensionsApi, Terminal as ITerminalApi } from '@xterm/xterm';
import { channels, css } from 'common/Color';
import type { Event } from 'vs/base/common/event';
import type { IEvent } from 'common/Event';
/**
* A portion of the public API that are implemented identially internally and simply passed through.
@@ -23,14 +23,12 @@ export interface ITerminal extends InternalPassthroughApis, ICoreTerminal {
readonly dimensions: IRenderDimensionsApi | undefined;
onBlur: Event<void>;
onFocus: Event<void>;
onDimensionsChange: Event<IRenderDimensionsApi>;
onA11yChar: Event<string>;
onA11yTab: Event<number>;
onWillOpen: Event<HTMLElement>;
cancel(ev: MouseEvent | WheelEvent | KeyboardEvent | InputEvent, force?: boolean): boolean | void;
onBlur: IEvent<void>;
onFocus: IEvent<void>;
onDimensionsChange: IEvent<IRenderDimensionsApi>;
onA11yChar: IEvent<string>;
onA11yTab: IEvent<number>;
onWillOpen: IEvent<HTMLElement>;
}
export type CustomKeyEventHandler = (event: KeyboardEvent) => boolean;
@@ -101,7 +99,7 @@ export interface IPartialColorSet {
export interface IViewport extends IDisposable {
scrollBarWidth: number;
readonly onRequestScrollLines: Event<{ amount: number, suppressScrollEvent: boolean }>;
readonly onRequestScrollLines: IEvent<{ amount: number, suppressScrollEvent: boolean }>;
syncScrollArea(immediate?: boolean, force?: boolean): void;
getLinesScrolled(ev: WheelEvent): number;
getBufferElements(startLine: number, endLine?: number): { bufferElements: HTMLElement[], cursorElement?: HTMLElement };
@@ -131,8 +129,8 @@ export interface ILinkWithState {
}
export interface ILinkifier2 extends IDisposable {
onShowLinkUnderline: Event<ILinkifierEvent>;
onHideLinkUnderline: Event<ILinkifierEvent>;
onShowLinkUnderline: IEvent<ILinkifierEvent>;
onHideLinkUnderline: IEvent<ILinkifierEvent>;
readonly currentLink: ILinkWithState | undefined;
}
+28 -20
View File
@@ -5,15 +5,15 @@
import { ICoreBrowserService, IRenderService, IThemeService } from 'browser/services/Services';
import { ViewportConstants } from 'browser/shared/Constants';
import { Disposable, toDisposable } from 'vs/base/common/lifecycle';
import { Disposable, toDisposable } from 'common/Lifecycle';
import { IBufferService, ICoreMouseService, IOptionsService } from 'common/services/Services';
import { CoreMouseEventType } from 'common/Types';
import { addDisposableListener, scheduleAtNextAnimationFrame } from 'vs/base/browser/dom';
import { SmoothScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement';
import type { ScrollableElementChangeOptions } from 'vs/base/browser/ui/scrollbar/scrollableElementOptions';
import { Emitter, Event } from 'vs/base/common/event';
import { Scrollable, ScrollbarVisibility, type ScrollEvent } from 'vs/base/common/scrollable';
import { Gesture, EventType as GestureEventType, type GestureEvent } from 'vs/base/browser/touch';
import { addDisposableListener, scheduleAtNextAnimationFrame } from 'browser/Dom';
import { SmoothScrollableElement } from 'browser/scrollable/scrollableElement';
import type { IScrollableElementChangeOptions } from 'browser/scrollable/scrollableElementOptions';
import { Emitter, EventUtils } from 'common/Event';
import { Scrollable, ScrollbarVisibility, type IScrollEvent } from 'browser/scrollable/scrollable';
import { Gesture, EventType as GestureEventType, type IGestureEvent } from 'browser/scrollable/touch';
export class Viewport extends Disposable {
@@ -52,16 +52,17 @@ export class Viewport extends Disposable {
}));
this._scrollableElement = this._register(new SmoothScrollableElement(screenElement, {
vertical: ScrollbarVisibility.Auto,
horizontal: ScrollbarVisibility.Hidden,
vertical: ScrollbarVisibility.AUTO,
horizontal: ScrollbarVisibility.HIDDEN,
useShadows: false,
mouseWheelSmoothScroll: true,
verticalHasArrows: this._optionsService.rawOptions.scrollbar?.showArrows ?? false,
...this._getChangeOptions()
}, scrollable));
this._register(this._optionsService.onMultipleOptionChange([
'scrollSensitivity',
'fastScrollSensitivity',
'overviewRuler'
'scrollbar'
], () => this._scrollableElement.updateOptions(this._getChangeOptions())));
// Don't handle mouse wheel if wheel events are supported by the current mouse prototcol
this._register(coreMouseService.onProtocolChange(type => {
@@ -71,7 +72,7 @@ export class Viewport extends Disposable {
}));
this._scrollableElement.setScrollDimensions({ height: 0, scrollHeight: 0 });
this._register(Event.runAndSubscribe(themeService.onChangeColors, () => {
this._register(EventUtils.runAndSubscribe(themeService.onChangeColors, () => {
element.style.backgroundColor = themeService.colors.background.css;
this._scrollableElement.getDomNode().style.backgroundColor = themeService.colors.background.css;
}));
@@ -81,15 +82,15 @@ export class Viewport extends Disposable {
this._styleElement = coreBrowserService.mainDocument.createElement('style');
screenElement.appendChild(this._styleElement);
this._register(toDisposable(() => this._styleElement.remove()));
this._register(Event.runAndSubscribe(themeService.onChangeColors, () => {
this._register(EventUtils.runAndSubscribe(themeService.onChangeColors, () => {
this._styleElement.textContent = [
`.xterm .xterm-scrollable-element > .scrollbar > .slider {`,
`.xterm .xterm-scrollable-element > .xterm-scrollbar > .xterm-slider {`,
` background: ${themeService.colors.scrollbarSliderBackground.css};`,
`}`,
`.xterm .xterm-scrollable-element > .scrollbar > .slider:hover {`,
`.xterm .xterm-scrollable-element > .xterm-scrollbar > .xterm-slider:hover {`,
` background: ${themeService.colors.scrollbarSliderHoverBackground.css};`,
`}`,
`.xterm .xterm-scrollable-element > .scrollbar > .slider.active {`,
`.xterm .xterm-scrollable-element > .xterm-scrollbar > .xterm-slider.xterm-active {`,
` background: ${themeService.colors.scrollbarSliderActiveBackground.css};`,
`}`
].join('\n');
@@ -108,7 +109,7 @@ export class Viewport extends Disposable {
// Touch/gesture scrolling support
this._register(Gesture.addTarget(screenElement));
this._register(addDisposableListener(screenElement, GestureEventType.Change, (e: GestureEvent) => this._handleGestureChange(e)));
this._register(addDisposableListener(screenElement, GestureEventType.CHANGE, (e: IGestureEvent) => this._handleGestureChange(e)));
}
public scrollLines(disp: number): void {
@@ -129,11 +130,18 @@ export class Viewport extends Disposable {
});
}
private _getChangeOptions(): ScrollableElementChangeOptions {
private _getChangeOptions(): IScrollableElementChangeOptions {
const showScrollbar = this._optionsService.rawOptions.scrollbar?.showScrollbar ?? true;
const showArrows = this._optionsService.rawOptions.scrollbar?.showArrows ?? false;
const verticalScrollbarSize = showScrollbar
? (this._optionsService.rawOptions.scrollbar?.width ?? ViewportConstants.DEFAULT_SCROLL_BAR_WIDTH)
: 0;
return {
mouseWheelScrollSensitivity: this._optionsService.rawOptions.scrollSensitivity,
fastScrollSensitivity: this._optionsService.rawOptions.fastScrollSensitivity,
verticalScrollbarSize: this._optionsService.rawOptions.overviewRuler?.width || ViewportConstants.DEFAULT_SCROLL_BAR_WIDTH
vertical: showScrollbar ? ScrollbarVisibility.AUTO : ScrollbarVisibility.HIDDEN,
verticalScrollbarSize,
verticalHasArrows: showArrows
};
}
@@ -179,7 +187,7 @@ export class Viewport extends Disposable {
this._isSyncing = false;
}
private _handleScroll(e: ScrollEvent): void {
private _handleScroll(e: IScrollEvent): void {
if (!this._renderService) {
return;
}
@@ -196,7 +204,7 @@ export class Viewport extends Disposable {
this._isHandlingScroll = false;
}
private _handleGestureChange(e: GestureEvent): void {
private _handleGestureChange(e: IGestureEvent): void {
e.preventDefault();
e.stopPropagation();
const pos = this._scrollableElement.getScrollPosition();
@@ -4,7 +4,7 @@
*--------------------------------------------------------------------------------------------*/
import { ICoreBrowserService, IRenderService } from 'browser/services/Services';
import { Disposable, toDisposable } from 'vs/base/common/lifecycle';
import { Disposable, toDisposable } from 'common/Lifecycle';
import { IBufferService, IDecorationService, IInternalDecoration } from 'common/services/Services';
export class BufferDecorationRenderer extends Disposable {
@@ -5,7 +5,7 @@
import { ColorZoneStore, IColorZone, IColorZoneStore } from 'browser/decorations/ColorZoneStore';
import { ICoreBrowserService, IRenderService, IThemeService } from 'browser/services/Services';
import { Disposable, toDisposable } from 'vs/base/common/lifecycle';
import { Disposable, toDisposable } from 'common/Lifecycle';
import { IBufferService, IDecorationService, IOptionsService } from 'common/services/Services';
const enum Constants {
@@ -38,7 +38,12 @@ export class OverviewRulerRenderer extends Disposable {
private readonly _ctx: CanvasRenderingContext2D;
private readonly _colorZoneStore: IColorZoneStore = new ColorZoneStore();
private get _width(): number {
return this._optionsService.options.overviewRuler?.width || 0;
const scrollbar = this._optionsService.rawOptions.scrollbar;
const showScrollbar = scrollbar?.showScrollbar ?? true;
if (!showScrollbar) {
return 0;
}
return scrollbar?.width ?? 0;
}
private _animationFrame: number | undefined;
@@ -95,7 +100,7 @@ export class OverviewRulerRenderer extends Disposable {
}));
this._register(this._coreBrowserService.onDprChange(() => this._queueRefresh(true)));
this._register(this._optionsService.onSpecificOptionChange('overviewRuler', () => this._queueRefresh(true)));
this._register(this._optionsService.onSpecificOptionChange('scrollbar', () => this._queueRefresh(true)));
this._register(this._themeService.onChangeColors(() => this._queueRefresh()));
this._queueRefresh(true);
}
@@ -176,10 +181,10 @@ export class OverviewRulerRenderer extends Disposable {
private _renderRulerOutline(): void {
this._ctx.fillStyle = this._themeService.colors.overviewRulerBorder.css;
this._ctx.fillRect(0, 0, Constants.OVERVIEW_RULER_BORDER_WIDTH, this._canvas.height);
if (this._optionsService.rawOptions.overviewRuler.showTopBorder) {
if (this._optionsService.rawOptions.scrollbar?.overviewRuler?.showTopBorder) {
this._ctx.fillRect(Constants.OVERVIEW_RULER_BORDER_WIDTH, 0, this._canvas.width - Constants.OVERVIEW_RULER_BORDER_WIDTH, Constants.OVERVIEW_RULER_BORDER_WIDTH);
}
if (this._optionsService.rawOptions.overviewRuler.showBottomBorder) {
if (this._optionsService.rawOptions.scrollbar?.overviewRuler?.showBottomBorder) {
this._ctx.fillRect(Constants.OVERVIEW_RULER_BORDER_WIDTH, this._canvas.height - Constants.OVERVIEW_RULER_BORDER_WIDTH, this._canvas.width - Constants.OVERVIEW_RULER_BORDER_WIDTH, this._canvas.height);
}
}
+18 -23
View File
@@ -6,14 +6,14 @@
import * as Strings from 'browser/LocalizableStrings';
import { CoreBrowserTerminal as TerminalCore } from 'browser/CoreBrowserTerminal';
import { IBufferRange, ITerminal } from 'browser/Types';
import { Disposable } from 'vs/base/common/lifecycle';
import { Disposable } from 'common/Lifecycle';
import { ITerminalOptions } from 'common/Types';
import { AddonManager } from 'common/public/AddonManager';
import { BufferNamespaceApi } from 'common/public/BufferNamespaceApi';
import { ParserApi } from 'common/public/ParserApi';
import { UnicodeApi } from 'common/public/UnicodeApi';
import { IBufferNamespace as IBufferNamespaceApi, IDecoration, IDecorationOptions, IDisposable, ILinkProvider, ILocalizableStrings, IMarker, IModes, IParser, IRenderDimensions, ITerminalAddon, Terminal as ITerminalApi, ITerminalInitOnlyOptions, IUnicodeHandling } from '@xterm/xterm';
import type { Event } from 'vs/base/common/event';
import type { IEvent } from 'common/Event';
/**
* The set of options that only have an effect when set in the Terminal constructor.
@@ -68,26 +68,24 @@ export class Terminal extends Disposable implements ITerminalApi {
}
}
public get onBell(): Event<void> { return this._core.onBell; }
public get onBinary(): Event<string> { return this._core.onBinary; }
public get onCursorMove(): Event<void> { return this._core.onCursorMove; }
public get onData(): Event<string> { return this._core.onData; }
public get onKey(): Event<{ key: string, domEvent: KeyboardEvent }> { return this._core.onKey; }
public get onLineFeed(): Event<void> { return this._core.onLineFeed; }
public get onRender(): Event<{ start: number, end: number }> { return this._core.onRender; }
public get onResize(): Event<{ cols: number, rows: number }> { return this._core.onResize; }
public get onScroll(): Event<number> { return this._core.onScroll; }
public get onSelectionChange(): Event<void> { return this._core.onSelectionChange; }
public get onTitleChange(): Event<string> { return this._core.onTitleChange; }
public get onWriteParsed(): Event<void> { return this._core.onWriteParsed; }
public get onDimensionsChange(): Event<IRenderDimensions> { return this._core.onDimensionsChange; }
public get onBell(): IEvent<void> { return this._core.onBell; }
public get onBinary(): IEvent<string> { return this._core.onBinary; }
public get onCursorMove(): IEvent<void> { return this._core.onCursorMove; }
public get onData(): IEvent<string> { return this._core.onData; }
public get onKey(): IEvent<{ key: string, domEvent: KeyboardEvent }> { return this._core.onKey; }
public get onLineFeed(): IEvent<void> { return this._core.onLineFeed; }
public get onRender(): IEvent<{ start: number, end: number }> { return this._core.onRender; }
public get onResize(): IEvent<{ cols: number, rows: number }> { return this._core.onResize; }
public get onScroll(): IEvent<number> { return this._core.onScroll; }
public get onSelectionChange(): IEvent<void> { return this._core.onSelectionChange; }
public get onTitleChange(): IEvent<string> { return this._core.onTitleChange; }
public get onWriteParsed(): IEvent<void> { return this._core.onWriteParsed; }
public get onDimensionsChange(): IEvent<IRenderDimensions> { return this._core.onDimensionsChange; }
public get element(): HTMLElement | undefined { return this._core.element; }
public get screenElement(): HTMLElement | undefined { return this._core.screenElement; }
public get parser(): IParser {
if (!this._parser) {
this._parser = new ParserApi(this._core);
}
return this._parser;
return this._parser ??= new ParserApi(this._core);
}
public get unicode(): IUnicodeHandling {
this._checkProposedApi();
@@ -97,10 +95,7 @@ export class Terminal extends Disposable implements ITerminalApi {
public get rows(): number { return this._core.rows; }
public get cols(): number { return this._core.cols; }
public get buffer(): IBufferNamespaceApi {
if (!this._buffer) {
this._buffer = this._register(new BufferNamespaceApi(this._core));
}
return this._buffer;
return this._buffer ??= this._register(new BufferNamespaceApi(this._core));
}
public get markers(): ReadonlyArray<IMarker> {
return this._core.markers;
+55 -6
View File
@@ -8,14 +8,15 @@ import { WidthCache } from 'browser/renderer/dom/WidthCache';
import { INVERTED_DEFAULT_COLOR, RendererConstants } from 'browser/renderer/shared/Constants';
import { createRenderDimensions } from 'browser/renderer/shared/RendererUtils';
import { createSelectionRenderModel } from 'browser/renderer/shared/SelectionRenderModel';
import { TextBlinkStateManager } from 'browser/renderer/shared/TextBlinkStateManager';
import { IRenderDimensions, IRenderer, IRequestRedrawEvent, ISelectionRenderModel } from 'browser/renderer/shared/Types';
import { ICharSizeService, ICoreBrowserService, IThemeService } from 'browser/services/Services';
import { ILinkifier2, ILinkifierEvent, ITerminal, ReadonlyColorSet } from 'browser/Types';
import { color } from 'common/Color';
import { Disposable, toDisposable } from 'vs/base/common/lifecycle';
import { Disposable, toDisposable } from 'common/Lifecycle';
import { IBufferService, ICoreService, IInstantiationService, IOptionsService } from 'common/services/Services';
import { Emitter } from 'vs/base/common/event';
import { addDisposableListener } from 'vs/base/browser/dom';
import { Emitter } from 'common/Event';
import { addDisposableListener } from 'browser/Dom';
const TERMINAL_CLASS_PREFIX = 'xterm-dom-renderer-owner-';
@@ -45,10 +46,14 @@ export class DomRenderer extends Disposable implements IRenderer {
private _widthCache: WidthCache;
private _selectionRenderModel: ISelectionRenderModel = createSelectionRenderModel();
private _cursorBlinkStateManager: CursorBlinkStateManager;
private _textBlinkStateManager: TextBlinkStateManager;
private _rowHasBlinkingCells: boolean[] = [];
private _rowHasBlinkingCellsCount: number = 0;
public dimensions: IRenderDimensions;
public readonly onRequestRedraw = this._register(new Emitter<IRequestRedrawEvent>()).event;
private readonly _onRequestRedraw = this._register(new Emitter<IRequestRedrawEvent>());
public readonly onRequestRedraw = this._onRequestRedraw.event;
constructor(
private readonly _terminal: ITerminal,
@@ -95,6 +100,11 @@ export class DomRenderer extends Disposable implements IRenderer {
this._cursorBlinkStateManager = new CursorBlinkStateManager(this._rowContainer, this._coreBrowserService);
this._register(addDisposableListener(this._document, 'mousedown', () => this._cursorBlinkStateManager.restartBlinkAnimation()));
this._register(toDisposable(() => this._cursorBlinkStateManager.dispose()));
this._textBlinkStateManager = this._register(new TextBlinkStateManager(
() => this._onRequestRedraw.fire({ start: 0, end: this._bufferService.rows - 1 }),
this._coreBrowserService,
this._optionsService
));
this._register(toDisposable(() => {
this._element.classList.remove(TERMINAL_CLASS_PREFIX + this._terminalClass);
@@ -193,6 +203,9 @@ export class DomRenderer extends Disposable implements IRenderer {
`}` +
`${this._terminalSelector} span.${RowCss.ITALIC_CLASS} {` +
` font-style: italic;` +
`}` +
`${this._terminalSelector} span.${RowCss.BLINK_HIDDEN_CLASS} {` +
` visibility: hidden;` +
`}`;
// Blink animation
const blinkAnimationUnderlineId = `blink_underline_${this._terminalClass}`;
@@ -318,10 +331,14 @@ export class DomRenderer extends Disposable implements IRenderer {
const row = this._document.createElement('div');
this._rowContainer.appendChild(row);
this._rowElements.push(row);
this._rowHasBlinkingCells.push(false);
}
// Remove excess elements
while (this._rowElements.length > rows) {
this._rowContainer.removeChild(this._rowElements.pop()!);
if (this._rowHasBlinkingCells.pop()) {
this._rowHasBlinkingCellsCount--;
}
}
}
@@ -349,6 +366,10 @@ export class DomRenderer extends Disposable implements IRenderer {
this.renderRows(this._bufferService.buffer.y, this._bufferService.buffer.y);
}
public handleViewportVisibilityChange(isVisible: boolean): void {
this._textBlinkStateManager.setViewportVisible(isVisible);
}
public handleSelectionChanged(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void {
// Remove all selections
this._selectionContainer.replaceChildren();
@@ -450,6 +471,11 @@ export class DomRenderer extends Disposable implements IRenderer {
*/
e.replaceChildren();
}
if (this._rowHasBlinkingCellsCount > 0) {
this._rowHasBlinkingCells.fill(false);
this._rowHasBlinkingCellsCount = 0;
this._textBlinkStateManager.setNeedsBlinkInViewport(false);
}
}
public renderRows(start: number, end: number): void {
@@ -459,6 +485,7 @@ export class DomRenderer extends Disposable implements IRenderer {
const cursorBlink = this._coreService.decPrivateModes.cursorBlink ?? this._optionsService.rawOptions.cursorBlink;
const cursorStyle = this._coreService.decPrivateModes.cursorStyle ?? this._optionsService.rawOptions.cursorStyle;
const cursorInactiveStyle = this._optionsService.rawOptions.cursorInactiveStyle;
const rowInfo = { hasBlinkingCells: false };
for (let y = start; y <= end; y++) {
const row = y + buffer.ydisp;
@@ -476,13 +503,17 @@ export class DomRenderer extends Disposable implements IRenderer {
cursorInactiveStyle,
cursorX,
cursorBlink,
this._textBlinkStateManager.isBlinkOn,
this.dimensions.css.cell.width,
this._widthCache,
-1,
-1
-1,
rowInfo
)
);
this._setRowBlinkState(y, rowInfo.hasBlinkingCells);
}
this._updateTextBlinkState();
}
private get _terminalSelector(): string {
@@ -527,6 +558,7 @@ export class DomRenderer extends Disposable implements IRenderer {
const cursorBlink = this._optionsService.rawOptions.cursorBlink;
const cursorStyle = this._optionsService.rawOptions.cursorStyle;
const cursorInactiveStyle = this._optionsService.rawOptions.cursorInactiveStyle;
const rowInfo = { hasBlinkingCells: false };
// refresh rows within link range
for (let i = y; i <= y2; ++i) {
@@ -545,13 +577,30 @@ export class DomRenderer extends Disposable implements IRenderer {
cursorInactiveStyle,
cursorX,
cursorBlink,
this._textBlinkStateManager.isBlinkOn,
this.dimensions.css.cell.width,
this._widthCache,
enabled ? (i === y ? x : 0) : -1,
enabled ? ((i === y2 ? x2 : cols) - 1) : -1
enabled ? ((i === y2 ? x2 : cols) - 1) : -1,
rowInfo
)
);
this._setRowBlinkState(i, rowInfo.hasBlinkingCells);
}
this._updateTextBlinkState();
}
private _setRowBlinkState(row: number, hasBlinkingCells: boolean): void {
const previous = this._rowHasBlinkingCells[row];
if (previous === hasBlinkingCells) {
return;
}
this._rowHasBlinkingCells[row] = hasBlinkingCells;
this._rowHasBlinkingCellsCount += hasBlinkingCells ? 1 : -1;
}
private _updateTextBlinkState(): void {
this._textBlinkStateManager.setNeedsBlinkInViewport(this._rowHasBlinkingCellsCount > 0);
}
}

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