Compare commits
404
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3556f16138 | ||
|
|
c2ecfe7446 | ||
|
|
5656443163 | ||
|
|
38174907f3 | ||
|
|
91fcb46a1a | ||
|
|
1d569f873d | ||
|
|
e89fbf2979 | ||
|
|
db244ea5a8 | ||
|
|
fdcd1c2720 | ||
|
|
57b48f6048 | ||
|
|
ec0c93fd5a | ||
|
|
be339bf796 | ||
|
|
7294124736 | ||
|
|
2c3fad39af | ||
|
|
edb4f89dd8 | ||
|
|
224c113b64 | ||
|
|
3e0c7d18e5 | ||
|
|
95d9224b8c | ||
|
|
7499a2181d | ||
|
|
7dc820f5fa | ||
|
|
e59a6c1f7b | ||
|
|
f3e2c08a5d | ||
|
|
b138bf38d0 | ||
|
|
c6e4627b45 | ||
|
|
d91045dc5f | ||
|
|
41dfdba2cf | ||
|
|
ba33decb68 | ||
|
|
17e3b84bcc | ||
|
|
182ff2f635 | ||
|
|
bcb4e5298b | ||
|
|
42facac2d9 | ||
|
|
2ab0f10a26 | ||
|
|
280dc0a36a | ||
|
|
ebe8cb749a | ||
|
|
c28f3c8d73 | ||
|
|
3bd7ac083a | ||
|
|
30b42838fd | ||
|
|
80e832e417 | ||
|
|
470947abd8 | ||
|
|
bb49a80ace | ||
|
|
65b87e0f40 | ||
|
|
39fc0f259e | ||
|
|
b787ac8b1b | ||
|
|
457efbf55d | ||
|
|
42270a0b68 | ||
|
|
090b77f354 | ||
|
|
534ce1365b | ||
|
|
f757c965ee | ||
|
|
4aa02f3fd9 | ||
|
|
f43273b3f0 | ||
|
|
c06c3025f2 | ||
|
|
1064e4f783 | ||
|
|
fad4821fd9 | ||
|
|
306c3d73ec | ||
|
|
8f2bb32c9c | ||
|
|
7b6c814566 | ||
|
|
adc9dea083 | ||
|
|
d565a2750e | ||
|
|
c5ab83d697 | ||
|
|
c62e6dd765 | ||
|
|
29a07f1d8f | ||
|
|
88cef97049 | ||
|
|
0e823004e6 | ||
|
|
df3422fb0b | ||
|
|
4ec85e67ba | ||
|
|
1a67b6f4b3 | ||
|
|
afaed108e4 | ||
|
|
c27d6bb462 | ||
|
|
9c4f0f96ca | ||
|
|
18c370a154 | ||
|
|
850f4ad738 | ||
|
|
b665f6259a | ||
|
|
d195dc9a3b | ||
|
|
4e5994d8a2 | ||
|
|
4a0cb5ae6b | ||
|
|
9e72a4b6d3 | ||
|
|
f484584b70 | ||
|
|
e749cb6125 | ||
|
|
8df996f9e7 | ||
|
|
51f6186352 | ||
|
|
ae5c41c518 | ||
|
|
17e7dafa17 | ||
|
|
df9fb7e473 | ||
|
|
41d9c4080f | ||
|
|
f100e93ba5 | ||
|
|
1d3825d341 | ||
|
|
57315e6cc9 | ||
|
|
2be4fc68e5 | ||
|
|
66fabfc232 | ||
|
|
3e2a42eb29 | ||
|
|
6a47d09b4c | ||
|
|
b36001ee7b | ||
|
|
e64f25a0dd | ||
|
|
3bcb57545e | ||
|
|
dc726a2ae6 | ||
|
|
06e5ac7ab4 | ||
|
|
c6e3492a4a | ||
|
|
86291b6e96 | ||
|
|
c8c8b3a7fe | ||
|
|
50e90ddf8a | ||
|
|
7059a07c09 | ||
|
|
c5c6fc2a64 | ||
|
|
e0add7fe4b | ||
|
|
b0f5bc2d28 | ||
|
|
c5a11220c1 | ||
|
|
6f55150485 | ||
|
|
c8dddddbbb | ||
|
|
6ba731d73b | ||
|
|
2d3909be2c | ||
|
|
1e189625fa | ||
|
|
80debafa11 | ||
|
|
1023e40428 | ||
|
|
5c47e6dd9a | ||
|
|
4ebb3fffe9 | ||
|
|
093e81b9a7 | ||
|
|
e04dd2501f | ||
|
|
d911b40a47 | ||
|
|
3dbfa7ce3e | ||
|
|
6287c6ddfe | ||
|
|
52d4b2719c | ||
|
|
7615cd210a | ||
|
|
4d4b994c35 | ||
|
|
7fa8b7a069 | ||
|
|
a2e51e8d36 | ||
|
|
f89253d24b | ||
|
|
7aeee95346 | ||
|
|
66fcdb2583 | ||
|
|
2a18600d18 | ||
|
|
5ef4f86543 | ||
|
|
874e767b40 | ||
|
|
605a7c6e30 | ||
|
|
802decb046 | ||
|
|
79a95dbfd8 | ||
|
|
75ba88c51b | ||
|
|
f9cea732f2 | ||
|
|
4dc934ce7c | ||
|
|
b2eff5ac67 | ||
|
|
31c53bc9c2 | ||
|
|
0d2975884f | ||
|
|
e8b5fd3c23 | ||
|
|
7abcca7e73 | ||
|
|
92339ac9dd | ||
|
|
ad4a6e8cb9 | ||
|
|
a094340afe | ||
|
|
cc7e3bbbf7 | ||
|
|
73d87b2c20 | ||
|
|
c5bf395b10 | ||
|
|
9d24099aa1 | ||
|
|
066c227436 | ||
|
|
32ad3a18bf | ||
|
|
d43b19c260 | ||
|
|
7dd0dac859 | ||
|
|
7e70d6ad78 | ||
|
|
893cdd494a | ||
|
|
2794e32b3f | ||
|
|
7d69e730ca | ||
|
|
da51d9608c | ||
|
|
3a84bcb7ae | ||
|
|
d9082215e7 | ||
|
|
41938b307e | ||
|
|
785c3cb336 | ||
|
|
ea7e958959 | ||
|
|
915b0b81a1 | ||
|
|
4e9abe7d96 | ||
|
|
84aca0b912 | ||
|
|
d82d42ef9a | ||
|
|
4d2f2e0d8e | ||
|
|
56986cb7eb | ||
|
|
4946436997 | ||
|
|
bf83ea06e4 | ||
|
|
b7e535e2ec | ||
|
|
8e12e69e4e | ||
|
|
849a9a53ca | ||
|
|
ee7d84bdd3 | ||
|
|
9c8de633e9 | ||
|
|
9c5420371b | ||
|
|
22778b5b49 | ||
|
|
cbe59a17ae | ||
|
|
76671cecb6 | ||
|
|
a11fcd2e0b | ||
|
|
b28b5d0c2b | ||
|
|
685434ca84 | ||
|
|
7fe89a1c1a | ||
|
|
eaebe2ab15 | ||
|
|
32553b4135 | ||
|
|
6c2465d745 | ||
|
|
5922123b9e | ||
|
|
eb65910c1b | ||
|
|
f0aeb70c92 | ||
|
|
9deec7aabf | ||
|
|
18cd9858ed | ||
|
|
6fd7ecc812 | ||
|
|
ff72c00219 | ||
|
|
0911688295 | ||
|
|
62ce318a07 | ||
|
|
08ae141ef7 | ||
|
|
ba7e775a17 | ||
|
|
487b27f512 | ||
|
|
5d120de3d5 | ||
|
|
3ab299af7f | ||
|
|
6e375cb588 | ||
|
|
7a6e724bfe | ||
|
|
69ee4ad23b | ||
|
|
253d1e9beb | ||
|
|
4b77e601cd | ||
|
|
34e0179355 | ||
|
|
bd722e7b07 | ||
|
|
cccdd447a0 | ||
|
|
446bcb1f75 | ||
|
|
4316263457 | ||
|
|
4a35a4880d | ||
|
|
ad730f2d54 | ||
|
|
9c7c163dd4 | ||
|
|
8674bc5e82 | ||
|
|
d552be8c45 | ||
|
|
082a51127f | ||
|
|
89100f6a3d | ||
|
|
8149d4481f | ||
|
|
2d9b21f5c7 | ||
|
|
f43985c422 | ||
|
|
9f6c7d7ced | ||
|
|
aa7716a333 | ||
|
|
1432e20082 | ||
|
|
f1b0a96094 | ||
|
|
49096a21fd | ||
|
|
63035678ec | ||
|
|
503abee8ae | ||
|
|
4350536685 | ||
|
|
9feb963cc9 | ||
|
|
f4042876c6 | ||
|
|
c294695444 | ||
|
|
fe0952bb83 | ||
|
|
5c2b19f2c8 | ||
|
|
5e9b2cbc14 | ||
|
|
3a59c8ec2b | ||
|
|
fb25eb8f79 | ||
|
|
e7a4578933 | ||
|
|
a05a3321d5 | ||
|
|
26ce9bd4d3 | ||
|
|
1c1aac0da8 | ||
|
|
beeebca1a4 | ||
|
|
fd1e53c63f | ||
|
|
18262c87d9 | ||
|
|
2285ac6ab8 | ||
|
|
5302e62c90 | ||
|
|
af6731b533 | ||
|
|
5b9b531012 | ||
|
|
b0118dfd3a | ||
|
|
6813fc175e | ||
|
|
409f049f39 | ||
|
|
9e1b89651a | ||
|
|
89980fc565 | ||
|
|
16b5da5c4c | ||
|
|
4812abb24f | ||
|
|
5f3a4646be | ||
|
|
d63445be94 | ||
|
|
1400398abb | ||
|
|
2331abe6bd | ||
|
|
b66128b239 | ||
|
|
c727240f16 | ||
|
|
649ce22081 | ||
|
|
73adfdfd56 | ||
|
|
1fc8a4687d | ||
|
|
c29e48c917 | ||
|
|
70fe22993b | ||
|
|
4f3a7331bd | ||
|
|
6f3ce7b0fe | ||
|
|
fdb7346f3a | ||
|
|
783c4a34d2 | ||
|
|
8a1760b924 | ||
|
|
211db9d067 | ||
|
|
ec6ad20e33 | ||
|
|
47235f47fe | ||
|
|
8d6ff3a27b | ||
|
|
55281022a0 | ||
|
|
ea50fbdd1e | ||
|
|
87bf81cf96 | ||
|
|
f155c65e5a | ||
|
|
413c87cbf9 | ||
|
|
1620f8f5a8 | ||
|
|
e769f80a14 | ||
|
|
6651c4ca23 | ||
|
|
cb78a53f57 | ||
|
|
1c7b9f6d79 | ||
|
|
0d535100e4 | ||
|
|
5e19624e71 | ||
|
|
671425bf5a | ||
|
|
df5393ec45 | ||
|
|
b2553c17b4 | ||
|
|
0cea95d3b3 | ||
|
|
163868ff60 | ||
|
|
f4166a87ba | ||
|
|
f7a353cd34 | ||
|
|
7ec41471da | ||
|
|
f5e81afba7 | ||
|
|
a12061c899 | ||
|
|
d6c872bb2c | ||
|
|
a2cb36e6dd | ||
|
|
114c66c86c | ||
|
|
fe9650ce16 | ||
|
|
dedf3b1595 | ||
|
|
2158827b25 | ||
|
|
b406797dc7 | ||
|
|
5c28e27062 | ||
|
|
6e35b44f02 | ||
|
|
30c97a225c | ||
|
|
1186d09e05 | ||
|
|
d99e6bb2bc | ||
|
|
579a0a530f | ||
|
|
0b6220e5ea | ||
|
|
0d119b30d6 | ||
|
|
79c94de968 | ||
|
|
e3980a27db | ||
|
|
898c0d91c3 | ||
|
|
83401e3769 | ||
|
|
6b756318f0 | ||
|
|
3a9bfa94bc | ||
|
|
209e5aa6b9 | ||
|
|
24e2eb9d7b | ||
|
|
d5ae437dda | ||
|
|
5efff43e93 | ||
|
|
ee85a1da9e | ||
|
|
c30fedff6b | ||
|
|
21f51564d1 | ||
|
|
27b01b22ef | ||
|
|
387ec93a90 | ||
|
|
4388a4ac13 | ||
|
|
08c97d12b0 | ||
|
|
fbf1f7bc5d | ||
|
|
c8704930e3 | ||
|
|
e60c96823d | ||
|
|
375be97615 | ||
|
|
74642ce5d5 | ||
|
|
eccbc60aa0 | ||
|
|
6b64660934 | ||
|
|
10182cc656 | ||
|
|
3c7f313c34 | ||
|
|
457542b7b3 | ||
|
|
36118d9d4c | ||
|
|
cf8a4e466d | ||
|
|
4de03aaa38 | ||
|
|
677e5275f9 | ||
|
|
c66b0ed168 | ||
|
|
d4c3b693bb | ||
|
|
2f66b5fdb6 | ||
|
|
008aa1bfb5 | ||
|
|
1d0cf32b28 | ||
|
|
c01e4b7be7 | ||
|
|
fafb195f0f | ||
|
|
f0d291f645 | ||
|
|
f6b98291cf | ||
|
|
f7118b19c6 | ||
|
|
a0574f4e9c | ||
|
|
d9b5d150ae | ||
|
|
a25db1c76d | ||
|
|
c6a572fe21 | ||
|
|
b9fa53169f | ||
|
|
38913e4ae1 | ||
|
|
e14746e6e9 | ||
|
|
82333b9414 | ||
|
|
9eeb2799c1 | ||
|
|
5630471480 | ||
|
|
e0c59e68b2 | ||
|
|
cc8e680790 | ||
|
|
452ee50c81 | ||
|
|
f41e53a0f0 | ||
|
|
b287397c4f | ||
|
|
aebbe81252 | ||
|
|
d155bb6767 | ||
|
|
3a147e8e10 | ||
|
|
c2db7d4c8a | ||
|
|
456bc73bae | ||
|
|
2e776c0820 | ||
|
|
6f163beb97 | ||
|
|
b0d0bf8187 | ||
|
|
32e77c3b81 | ||
|
|
cba6e3d191 | ||
|
|
5741e450e6 | ||
|
|
6ef653e589 | ||
|
|
a4c0e4690e | ||
|
|
a31f78bc8b | ||
|
|
ca8e8546b5 | ||
|
|
3d473b52b6 | ||
|
|
a2bec2aeab | ||
|
|
205cf6089d | ||
|
|
8b0a6f9785 | ||
|
|
db0226be5c | ||
|
|
ab5c06cf17 | ||
|
|
9a778f0c98 | ||
|
|
c102b4af50 | ||
|
|
f3a7cac49f | ||
|
|
0d2a58c9d0 | ||
|
|
8a00898533 | ||
|
|
edb0e1ceb3 | ||
|
|
93c1650446 | ||
|
|
77695cb405 | ||
|
|
dc4ebfd6e3 | ||
|
|
fae6f03f90 | ||
|
|
d36af624cf | ||
|
|
a105d3e457 | ||
|
|
d5900c7eae | ||
|
|
beebe8b5dc | ||
|
|
f666135881 | ||
|
|
eea03cf0a9 |
@@ -1,7 +1,11 @@
|
|||||||
---
|
---
|
||||||
applyTo: '**/*.benchmark.ts'
|
name: benchmark
|
||||||
|
description: Run and author benchmark tests in xterm.js. Use when editing benchmark files, working in `*.benchmark.ts`, or when asked how to run the full benchmark suite, a single benchmark file, or a single benchmark case.
|
||||||
---
|
---
|
||||||
# Benchmark run instructions
|
|
||||||
|
# Benchmark Run Instructions
|
||||||
|
|
||||||
|
## Running Benchmarks
|
||||||
|
|
||||||
- Full suite: `npm run benchmark`
|
- Full suite: `npm run benchmark`
|
||||||
- Single benchmark file:
|
- Single benchmark file:
|
||||||
@@ -11,8 +15,14 @@ applyTo: '**/*.benchmark.ts'
|
|||||||
- Use `-t` to get the path, then:
|
- Use `-t` to get the path, then:
|
||||||
- `npm run benchmark -- -s "<path>" out-test/benchmark/Event.benchmark.js`
|
- `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.
|
## Benchmark Case Selection
|
||||||
|
|
||||||
|
When writing benchmark instructions:
|
||||||
|
|
||||||
|
- Use `RuntimeCase` to measure pure runtime in ms.
|
||||||
|
- Use `ThroughputRuntimeCase` when measuring throughput in MB/s.
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
Notes:
|
|
||||||
- Benchmarks run from built JS in `out-test/benchmark/*.benchmark.js`.
|
- Benchmarks run from built JS in `out-test/benchmark/*.benchmark.js`.
|
||||||
- Keep `NODE_PATH=./out` (handled by the npm script).
|
- Keep `NODE_PATH=./out` (handled by the npm script).
|
||||||
@@ -1,7 +1,11 @@
|
|||||||
---
|
---
|
||||||
applyTo: '**/*.test.ts'
|
name: unit-test
|
||||||
|
description: Write and review xterm.js unit tests with project conventions. Use when editing `*.test.ts` files or when asked for test authoring guidelines.
|
||||||
---
|
---
|
||||||
When writing unit tests follow these rules:
|
|
||||||
|
# Unit Test Instructions
|
||||||
|
|
||||||
|
When writing unit tests, follow these rules:
|
||||||
|
|
||||||
- When writing unit tests for addons, always create a real xterm.js instance instead of mocking it.
|
- When writing unit tests for addons, always create a real xterm.js instance instead of mocking it.
|
||||||
- Prefer `assert.ok` over `assert.notStrictEqual` when checking something is undefined or not.
|
- Prefer `assert.ok` over `assert.notStrictEqual` when checking something is undefined or not.
|
||||||
+13
-13
@@ -207,31 +207,31 @@ jobs:
|
|||||||
- name: Build demo server
|
- name: Build demo server
|
||||||
run: npm run esbuild-demo-server
|
run: npm run esbuild-demo-server
|
||||||
- name: Integration tests (core) # Tests use 50% workers to reduce flakiness
|
- name: Integration tests (core) # Tests use 50% workers to reduce flakiness
|
||||||
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=core
|
run: npm run test-integration-${{ matrix.browser }} -- --workers=50% --forbid-only --suite=core
|
||||||
- name: Integration tests (addon-attach)
|
- name: Integration tests (addon-attach)
|
||||||
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-attach
|
run: npm run test-integration-${{ matrix.browser }} -- --workers=50% --forbid-only --suite=addon-attach
|
||||||
- name: Integration tests (addon-clipboard)
|
- name: Integration tests (addon-clipboard)
|
||||||
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-clipboard
|
run: npm run test-integration-${{ matrix.browser }} -- --workers=50% --forbid-only --suite=addon-clipboard
|
||||||
- name: Integration tests (addon-fit)
|
- name: Integration tests (addon-fit)
|
||||||
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-fit
|
run: npm run test-integration-${{ matrix.browser }} -- --workers=50% --forbid-only --suite=addon-fit
|
||||||
- name: Integration tests (addon-image)
|
- name: Integration tests (addon-image)
|
||||||
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-image
|
run: npm run test-integration-${{ matrix.browser }} -- --workers=50% --forbid-only --suite=addon-image
|
||||||
- name: Integration tests (addon-progress)
|
- name: Integration tests (addon-progress)
|
||||||
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-progress
|
run: npm run test-integration-${{ matrix.browser }} -- --workers=50% --forbid-only --suite=addon-progress
|
||||||
- name: Integration tests (addon-search)
|
- name: Integration tests (addon-search)
|
||||||
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-search
|
run: npm run test-integration-${{ matrix.browser }} -- --workers=50% --forbid-only --suite=addon-search
|
||||||
- name: Integration tests (addon-serialize)
|
- name: Integration tests (addon-serialize)
|
||||||
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-serialize
|
run: npm run test-integration-${{ matrix.browser }} -- --workers=50% --forbid-only --suite=addon-serialize
|
||||||
- name: Integration tests (addon-unicode-graphemes)
|
- name: Integration tests (addon-unicode-graphemes)
|
||||||
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-unicode-graphemes
|
run: npm run test-integration-${{ matrix.browser }} -- --workers=50% --forbid-only --suite=addon-unicode-graphemes
|
||||||
- name: Integration tests (addon-unicode11)
|
- name: Integration tests (addon-unicode11)
|
||||||
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-unicode11
|
run: npm run test-integration-${{ matrix.browser }} -- --workers=50% --forbid-only --suite=addon-unicode11
|
||||||
- name: Integration tests (addon-web-fonts)
|
- name: Integration tests (addon-web-fonts)
|
||||||
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-web-fonts
|
run: npm run test-integration-${{ matrix.browser }} -- --workers=50% --forbid-only --suite=addon-web-fonts
|
||||||
- name: Integration tests (addon-web-links)
|
- name: Integration tests (addon-web-links)
|
||||||
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-web-links
|
run: npm run test-integration-${{ matrix.browser }} -- --workers=50% --forbid-only --suite=addon-web-links
|
||||||
- name: Integration tests (addon-webgl)
|
- name: Integration tests (addon-webgl)
|
||||||
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-webgl
|
run: npm run test-integration-${{ matrix.browser }} -- --workers=50% --forbid-only --suite=addon-webgl
|
||||||
|
|
||||||
release-dry-run:
|
release-dry-run:
|
||||||
needs: build
|
needs: build
|
||||||
|
|||||||
@@ -22,6 +22,10 @@ build/
|
|||||||
yarn.lock
|
yarn.lock
|
||||||
test-results/
|
test-results/
|
||||||
|
|
||||||
|
# Tracing/debug files
|
||||||
|
.cursor/nal-trace/
|
||||||
|
.cursor/*.log
|
||||||
|
|
||||||
# Keep bundled code out of Git
|
# Keep bundled code out of Git
|
||||||
dist/
|
dist/
|
||||||
demo/dist/
|
demo/dist/
|
||||||
|
|||||||
@@ -57,6 +57,13 @@ export class MyAddon implements ITerminalAddon {
|
|||||||
- Proposed APIs require `allowProposedApi: true` option
|
- Proposed APIs require `allowProposedApi: true` option
|
||||||
- Constructor-only options (cols, rows) cannot be changed after instantiation
|
- Constructor-only options (cols, rows) cannot be changed after instantiation
|
||||||
|
|
||||||
|
**Disposable Management**:
|
||||||
|
- When a disposable object can be replaced over time, prefer a registered `MutableDisposable` over manual dispose/reassign logic.
|
||||||
|
- Register it on the owning class (for example, `this._register(new MutableDisposable())`) and assign through `.value`; this automatically disposes the previous value and avoids accidentally leaking resources.
|
||||||
|
|
||||||
|
**TypeScript Constants**:
|
||||||
|
- Prefer `const enum` over top-level `const` declarations for primitive constants when appropriate, since values are inlined and avoid runtime property lookups.
|
||||||
|
|
||||||
**Testing Utilities**: Use `TestUtils.ts` helpers:
|
**Testing Utilities**: Use `TestUtils.ts` helpers:
|
||||||
- `openTerminal(ctx, options)` for setup
|
- `openTerminal(ctx, options)` for setup
|
||||||
- `pollFor(page, fn, expectedValue)` for async assertions
|
- `pollFor(page, fn, expectedValue)` for async assertions
|
||||||
@@ -24,7 +24,36 @@ First, you need to install the module. We ship exclusively through [npm](https:/
|
|||||||
npm install --save @xterm/xterm
|
npm install --save @xterm/xterm
|
||||||
```
|
```
|
||||||
|
|
||||||
To start using xterm.js on your browser, add the `xterm.js` and `xterm.css` to the head of your HTML page. Then create a `<div id="terminal"></div>` onto which xterm can attach itself. Finally, instantiate the `Terminal` object and then call the `open` function with the DOM object of the `div`.
|
The recommended way to load xterm.js with the ES module syntax, either using TypeScript or a modern JS tooling. Note that both CommonJS and ES module files are shipped with the npm package.
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
import { Terminal } from '@xterm/xterm';
|
||||||
|
```
|
||||||
|
|
||||||
|
Then instantiate a `Terminal` object, open it on an element and write to it:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const term = new Terminal();
|
||||||
|
term.open(document.getElementById('terminal'));
|
||||||
|
term.write('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ')
|
||||||
|
```
|
||||||
|
|
||||||
|
Most use cases will hook up input and output to a pseudoterminal API such as [node-pty](https://www.npmjs.com/package/node-pty) which will drive the terminal.
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
pty.onData(data => term.write(data));
|
||||||
|
term.onData(data => pty.write(data));
|
||||||
|
```
|
||||||
|
|
||||||
|
Then make sure to also include the `css/xterm.css` file, for example in HTML:
|
||||||
|
|
||||||
|
```html
|
||||||
|
<link rel="stylesheet" href="node_modules/@xterm/xterm/css/xterm.css" />
|
||||||
|
```
|
||||||
|
|
||||||
|
### Standalone example
|
||||||
|
|
||||||
|
Here is a complete standalone example in a HTML file:
|
||||||
|
|
||||||
```html
|
```html
|
||||||
<!doctype html>
|
<!doctype html>
|
||||||
@@ -36,7 +65,7 @@ To start using xterm.js on your browser, add the `xterm.js` and `xterm.css` to t
|
|||||||
<body>
|
<body>
|
||||||
<div id="terminal"></div>
|
<div id="terminal"></div>
|
||||||
<script>
|
<script>
|
||||||
var term = new Terminal();
|
const term = new Terminal();
|
||||||
term.open(document.getElementById('terminal'));
|
term.open(document.getElementById('terminal'));
|
||||||
term.write('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ')
|
term.write('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ')
|
||||||
</script>
|
</script>
|
||||||
@@ -44,14 +73,6 @@ To start using xterm.js on your browser, add the `xterm.js` and `xterm.css` to t
|
|||||||
</html>
|
</html>
|
||||||
```
|
```
|
||||||
|
|
||||||
### Importing
|
|
||||||
|
|
||||||
The recommended way to load xterm.js is via the ES6 module syntax:
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
import { Terminal } from '@xterm/xterm';
|
|
||||||
```
|
|
||||||
|
|
||||||
### Addons
|
### Addons
|
||||||
|
|
||||||
Addons are separate modules that extend the `Terminal` by building on the [xterm.js API](https://github.com/xtermjs/xterm.js/blob/master/typings/xterm.d.ts). To use an addon, you first need to install it in your project:
|
Addons are separate modules that extend the `Terminal` by building on the [xterm.js API](https://github.com/xtermjs/xterm.js/blob/master/typings/xterm.d.ts). To use an addon, you first need to install it in your project:
|
||||||
@@ -94,7 +115,7 @@ Since xterm.js is typically implemented as a developer tool, generally only mode
|
|||||||
|
|
||||||
### Node.js Support
|
### Node.js Support
|
||||||
|
|
||||||
We also publish [`xterm-headless`](https://www.npmjs.com/package/xterm-headless) which is a stripped down version of xterm.js that runs headless in Node.js. An example use case for this is to keep track of a terminal's state where the process is running and using the [serialize addon](https://www.npmjs.com/package/@xterm/addon-serialize) so it can get all state restored upon reconnection.
|
We also publish [`@xterm/headless`](https://www.npmjs.com/package/@xterm/headless) which is a stripped down version of xterm.js that runs headless in Node.js. An example use case for this is to keep track of a terminal's state where the process is running and using the [serialize addon](https://www.npmjs.com/package/@xterm/addon-serialize) so it can get all state restored upon reconnection.
|
||||||
|
|
||||||
## API
|
## API
|
||||||
|
|
||||||
@@ -229,6 +250,10 @@ Xterm.js is used in many world-class applications to provide great terminal expe
|
|||||||
- [**ecmaOS**](https://ecmaos.sh): A kernel and suite of applications tying modern web technologies into a browser-based operating system.
|
- [**ecmaOS**](https://ecmaos.sh): A kernel and suite of applications tying modern web technologies into a browser-based operating system.
|
||||||
- [**LabEx**](https://labex.io): Interactive learning platform with hands-on labs and xterm.js-based online terminals, focused on learn-by-doing approach.
|
- [**LabEx**](https://labex.io): Interactive learning platform with hands-on labs and xterm.js-based online terminals, focused on learn-by-doing approach.
|
||||||
- [**EmuDevz**](https://afska.github.io/emudevz): A free coding game where players learn how to build an emulator from scratch.
|
- [**EmuDevz**](https://afska.github.io/emudevz): A free coding game where players learn how to build an emulator from scratch.
|
||||||
|
- [**SSH Connection Manager**](https://github.com/Amtrend/ssh-manager): Modern web-based SSH terminal and SFTP manager with AES-256 encryption, PWA support, and session management.
|
||||||
|
- [**WooTTY**](https://github.com/icoretech/wootty): Flawless browser terminal for real operators.
|
||||||
|
- [**Orca**](https://github.com/stablyai/orca): Agentic development environment for 100x builders.
|
||||||
|
- [**4bit**](https://ciembor.github.io/4bit): Terminal Color Scheme Designer.
|
||||||
- [And much more...](https://github.com/xtermjs/xterm.js/network/dependents?package_id=UGFja2FnZS0xNjYzMjc4OQ%3D%3D)
|
- [And much more...](https://github.com/xtermjs/xterm.js/network/dependents?package_id=UGFja2FnZS0xNjYzMjc4OQ%3D%3D)
|
||||||
|
|
||||||
Do you use xterm.js in your application as well? Please [open a Pull Request](https://github.com/sourcelair/xterm.js/pulls) to include it here. We would love to have it on our list. Please add any new contributions to the end of the list.
|
Do you use xterm.js in your application as well? Please [open a Pull Request](https://github.com/sourcelair/xterm.js/pulls) to include it here. We would love to have it on our list. Please add any new contributions to the end of the list.
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
"xterm.js"
|
"xterm.js"
|
||||||
],
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "../../node_modules/.bin/tsc -p .",
|
"build": "../../node_modules/.bin/tsgo -p .",
|
||||||
"prepackage": "npm run build",
|
"prepackage": "npm run build",
|
||||||
"package": "../../node_modules/.bin/webpack",
|
"package": "../../node_modules/.bin/webpack",
|
||||||
"prepublishOnly": "npm run package",
|
"prepublishOnly": "npm run package",
|
||||||
|
|||||||
@@ -9,13 +9,15 @@
|
|||||||
"outDir": "../out-test",
|
"outDir": "../out-test",
|
||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"removeComments": true,
|
"removeComments": true,
|
||||||
"baseUrl": ".",
|
|
||||||
"paths": {
|
"paths": {
|
||||||
"common/*": [
|
"common/*": [
|
||||||
"../../../src/common/*"
|
"../../../src/common/*"
|
||||||
],
|
],
|
||||||
"browser/*": [
|
"browser/*": [
|
||||||
"../../../src/browser/*"
|
"../../../src/browser/*"
|
||||||
|
],
|
||||||
|
"*": [
|
||||||
|
"./*"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"strict": true,
|
"strict": true,
|
||||||
|
|||||||
@@ -16,13 +16,10 @@
|
|||||||
"xterm.js"
|
"xterm.js"
|
||||||
],
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "../../node_modules/.bin/tsc -p .",
|
"build": "../../node_modules/.bin/tsgo -p .",
|
||||||
"prepackage": "npm run build",
|
"prepackage": "npm run build",
|
||||||
"package": "../../node_modules/.bin/webpack",
|
"package": "../../node_modules/.bin/webpack",
|
||||||
"prepublishOnly": "npm run package",
|
"prepublishOnly": "npm run package",
|
||||||
"start": "node ../../demo/start"
|
"start": "node ../../demo/start"
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"js-base64": "^3.7.5"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,8 +4,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import type { IDisposable, ITerminalAddon, Terminal } from '@xterm/xterm';
|
import type { IDisposable, ITerminalAddon, Terminal } from '@xterm/xterm';
|
||||||
import { type IClipboardProvider, ClipboardSelectionType, type IBase64 } from '@xterm/addon-clipboard';
|
import { type IClipboardProvider, type IBase64 } from '@xterm/addon-clipboard';
|
||||||
import { Base64 as JSBase64 } from 'js-base64';
|
|
||||||
|
|
||||||
export class ClipboardAddon implements ITerminalAddon {
|
export class ClipboardAddon implements ITerminalAddon {
|
||||||
private _terminal?: Terminal;
|
private _terminal?: Terminal;
|
||||||
@@ -25,7 +24,7 @@ export class ClipboardAddon implements ITerminalAddon {
|
|||||||
return this._disposable?.dispose();
|
return this._disposable?.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
private _readText(sel: ClipboardSelectionType, data: string): void {
|
private _readText(sel: string, data: string): void {
|
||||||
const b64 = this._base64.encodeText(data);
|
const b64 = this._base64.encodeText(data);
|
||||||
this._terminal?.input(`\x1b]52;${sel};${b64}\x07`, false);
|
this._terminal?.input(`\x1b]52;${sel};${b64}\x07`, false);
|
||||||
}
|
}
|
||||||
@@ -36,7 +35,7 @@ export class ClipboardAddon implements ITerminalAddon {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
const pc = args[0] as ClipboardSelectionType;
|
const pc = args[0];
|
||||||
const pd = args[1];
|
const pd = args[1];
|
||||||
if (pd === '?') {
|
if (pd === '?') {
|
||||||
const text = this._provider.readText(pc);
|
const text = this._provider.readText(pc);
|
||||||
@@ -70,30 +69,23 @@ export class ClipboardAddon implements ITerminalAddon {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class BrowserClipboardProvider implements IClipboardProvider {
|
export class BrowserClipboardProvider implements IClipboardProvider {
|
||||||
public async readText(selection: ClipboardSelectionType): Promise<string> {
|
public readText(selection: string): Promise<string> {
|
||||||
if (selection !== 'c') {
|
|
||||||
return Promise.resolve('');
|
|
||||||
}
|
|
||||||
return navigator.clipboard.readText();
|
return navigator.clipboard.readText();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async writeText(selection: ClipboardSelectionType, text: string): Promise<void> {
|
public writeText(selection: string, text: string): Promise<void> {
|
||||||
if (selection !== 'c') {
|
|
||||||
return Promise.resolve();
|
|
||||||
}
|
|
||||||
return navigator.clipboard.writeText(text);
|
return navigator.clipboard.writeText(text);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export class Base64 implements IBase64 {
|
export class Base64 implements IBase64 {
|
||||||
public encodeText(data: string): string {
|
public encodeText(data: string): string {
|
||||||
return JSBase64.encode(data);
|
return btoa(data);
|
||||||
}
|
}
|
||||||
public decodeText(data: string): string {
|
public decodeText(data: string): string {
|
||||||
const text = JSBase64.decode(data);
|
try {
|
||||||
if (!JSBase64.isValid(data) || JSBase64.encode(text) !== data) {
|
return atob(data);
|
||||||
return '';
|
} catch {}
|
||||||
}
|
return '';
|
||||||
return text;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ test.describe('ClipboardAddon', () => {
|
|||||||
|
|
||||||
test.beforeEach(async ({}, testInfo) => {
|
test.beforeEach(async ({}, testInfo) => {
|
||||||
// DEBT: This test doesn't work since the migration to @playwright/test
|
// DEBT: This test doesn't work since the migration to @playwright/test
|
||||||
if (ctx.browser.browserType().name() !== 'chromium') {
|
if (ctx.browser.browserType().name() === 'webkit') {
|
||||||
testInfo.skip();
|
testInfo.skip();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -48,6 +48,14 @@ test.describe('ClipboardAddon', () => {
|
|||||||
await ctx.proxy.write(`\x1b]52;c;${testDataEncoded}\x07`);
|
await ctx.proxy.write(`\x1b]52;c;${testDataEncoded}\x07`);
|
||||||
deepEqual(await ctx.page.evaluate(() => window.navigator.clipboard.readText()), testDataDecoded);
|
deepEqual(await ctx.page.evaluate(() => window.navigator.clipboard.readText()), testDataDecoded);
|
||||||
});
|
});
|
||||||
|
test('primary selection', async () => {
|
||||||
|
await ctx.proxy.write(`\x1b]52;p;${testDataEncoded}\x07`);
|
||||||
|
deepEqual(await ctx.page.evaluate(() => window.navigator.clipboard.readText()), testDataDecoded);
|
||||||
|
});
|
||||||
|
test('empty selection (default)', async () => {
|
||||||
|
await ctx.proxy.write(`\x1b]52;;${testDataEncoded}\x07`);
|
||||||
|
deepEqual(await ctx.page.evaluate(() => window.navigator.clipboard.readText()), testDataDecoded);
|
||||||
|
});
|
||||||
test('invalid base64 string', async () => {
|
test('invalid base64 string', async () => {
|
||||||
await ctx.proxy.write(`\x1b]52;c;${testDataEncoded}invalid\x07`);
|
await ctx.proxy.write(`\x1b]52;c;${testDataEncoded}invalid\x07`);
|
||||||
deepEqual(await ctx.page.evaluate(() => window.navigator.clipboard.readText()), '');
|
deepEqual(await ctx.page.evaluate(() => window.navigator.clipboard.readText()), '');
|
||||||
@@ -60,15 +68,24 @@ test.describe('ClipboardAddon', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test.describe('read data', async function (): Promise<any> {
|
test.describe('read data', async function (): Promise<any> {
|
||||||
test('simple string', async () => {
|
test.beforeAll(async () => {
|
||||||
await ctx.page.evaluate(`
|
await ctx.page.evaluate(`
|
||||||
window.data = [];
|
window.data = [];
|
||||||
window.term.onData(e => data.push(e));
|
window.term.onData(e => data.push(e));
|
||||||
`);
|
`);
|
||||||
|
});
|
||||||
|
test('simple string', async () => {
|
||||||
|
await ctx.page.evaluate('window.data.length = 0;');
|
||||||
await ctx.page.evaluate(() => window.navigator.clipboard.writeText('hello world'));
|
await ctx.page.evaluate(() => window.navigator.clipboard.writeText('hello world'));
|
||||||
await ctx.proxy.write(`\x1b]52;c;?\x07`);
|
await ctx.proxy.write(`\x1b]52;c;?\x07`);
|
||||||
deepEqual(await ctx.page.evaluate('window.data'), [`\x1b]52;c;${testDataEncoded}\x07`]);
|
deepEqual(await ctx.page.evaluate('window.data'), [`\x1b]52;c;${testDataEncoded}\x07`]);
|
||||||
});
|
});
|
||||||
|
test('primary selection', async () => {
|
||||||
|
await ctx.page.evaluate('window.data.length = 0;');
|
||||||
|
await ctx.page.evaluate(() => window.navigator.clipboard.writeText('hello world'));
|
||||||
|
await ctx.proxy.write(`\x1b]52;p;?\x07`);
|
||||||
|
deepEqual(await ctx.page.evaluate('window.data'), [`\x1b]52;p;${testDataEncoded}\x07`]);
|
||||||
|
});
|
||||||
test('clear clipboard', async () => {
|
test('clear clipboard', async () => {
|
||||||
await ctx.proxy.write(`\x1b]52;c;!\x07`);
|
await ctx.proxy.write(`\x1b]52;c;!\x07`);
|
||||||
await ctx.proxy.write(`\x1b]52;c;?\x07`);
|
await ctx.proxy.write(`\x1b]52;c;?\x07`);
|
||||||
|
|||||||
@@ -9,13 +9,15 @@
|
|||||||
"outDir": "../out-test",
|
"outDir": "../out-test",
|
||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"removeComments": true,
|
"removeComments": true,
|
||||||
"baseUrl": ".",
|
|
||||||
"paths": {
|
"paths": {
|
||||||
"common/*": [
|
"common/*": [
|
||||||
"../../../src/common/*"
|
"../../../src/common/*"
|
||||||
],
|
],
|
||||||
"browser/*": [
|
"browser/*": [
|
||||||
"../../../src/browser/*"
|
"../../../src/browser/*"
|
||||||
|
],
|
||||||
|
"*": [
|
||||||
|
"./*"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"strict": true,
|
"strict": true,
|
||||||
|
|||||||
+12
-21
@@ -30,18 +30,6 @@ declare module '@xterm/addon-clipboard' {
|
|||||||
public dispose(): void
|
public dispose(): void
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Clipboard selection type. This is used to specify which selection buffer to
|
|
||||||
* read or write to.
|
|
||||||
* - SYSTEM `c`: The system clipboard.
|
|
||||||
* - PRIMARY `p`: The primary clipboard. This is provided for compatibility
|
|
||||||
* with Linux X11.
|
|
||||||
*/
|
|
||||||
export const enum ClipboardSelectionType {
|
|
||||||
SYSTEM = 'c',
|
|
||||||
PRIMARY = 'p',
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IBase64 {
|
export interface IBase64 {
|
||||||
/**
|
/**
|
||||||
* Converts a utf-8 string to a base64 string.
|
* Converts a utf-8 string to a base64 string.
|
||||||
@@ -78,36 +66,39 @@ declare module '@xterm/addon-clipboard' {
|
|||||||
export interface IClipboardProvider {
|
export interface IClipboardProvider {
|
||||||
/**
|
/**
|
||||||
* Gets the clipboard content.
|
* Gets the clipboard content.
|
||||||
* @param selection The clipboard selection to read.
|
* @param selection The clipboard selection to read (see OSC 52 spec of xterm).
|
||||||
* @returns A promise that resolves with clipboard selection data.
|
* @returns A promise that resolves with clipboard selection data.
|
||||||
*/
|
*/
|
||||||
readText(selection: ClipboardSelectionType): string | Promise<string>;
|
readText(selection: string): string | Promise<string>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sets the clipboard content.
|
* Sets the clipboard content.
|
||||||
* @param selection The clipboard selection to set.
|
* @param selection The clipboard selection to set (see OSC 52 spec of xterm).
|
||||||
* @param data The clipboard text to write.
|
* @param data The clipboard text to write.
|
||||||
*/
|
*/
|
||||||
writeText(selection: ClipboardSelectionType, text: string): void | Promise<void>;
|
writeText(selection: string, text: string): void | Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The clipboard provider interface that enables xterm.js to access the system clipboard.
|
* The clipboard provider interface that enables xterm.js to access the browser clipboard.
|
||||||
|
*
|
||||||
|
* Note this this clipboard provider does not implement own cut buffers as xterm does,
|
||||||
|
* but redirect the selection parameter always to navigator.clipboard.
|
||||||
*/
|
*/
|
||||||
export class BrowserClipboardProvider implements IClipboardProvider{
|
export class BrowserClipboardProvider implements IClipboardProvider{
|
||||||
/**
|
/**
|
||||||
* Reads text from the clipboard.
|
* Reads text from the clipboard.
|
||||||
* @param selection The selection type to read from.
|
* @param selection The selection type to read from (always refers to navigator.clipboard).
|
||||||
* @returns A promise that resolves with the text from the clipboard.
|
* @returns A promise that resolves with the text from the clipboard.
|
||||||
*/
|
*/
|
||||||
public readText(selection: ClipboardSelectionType): Promise<string>;
|
public readText(selection: string): Promise<string>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Writes text to the clipboard.
|
* Writes text to the clipboard.
|
||||||
* @param selection The selection type to write to.
|
* @param selection The selection type to write to (always refers to navigator.clipboard).
|
||||||
* @param data The text to write to the clipboard.
|
* @param data The text to write to the clipboard.
|
||||||
* @returns A promise that resolves when the text has been written to the clipboard.
|
* @returns A promise that resolves when the text has been written to the clipboard.
|
||||||
*/
|
*/
|
||||||
public writeText(selection: ClipboardSelectionType, data: string): Promise<void>;
|
public writeText(selection: string, data: string): Promise<void>;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
"xterm.js"
|
"xterm.js"
|
||||||
],
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "../../node_modules/.bin/tsc -p .",
|
"build": "../../node_modules/.bin/tsgo -p .",
|
||||||
"prepackage": "npm run build",
|
"prepackage": "npm run build",
|
||||||
"package": "../../node_modules/.bin/webpack",
|
"package": "../../node_modules/.bin/webpack",
|
||||||
"prepublishOnly": "npm run package",
|
"prepublishOnly": "npm run package",
|
||||||
|
|||||||
@@ -19,8 +19,10 @@ interface ITerminalDimensions {
|
|||||||
cols: number;
|
cols: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
const MINIMUM_COLS = 2;
|
const enum Constants {
|
||||||
const MINIMUM_ROWS = 1;
|
MINIMUM_COLS = 2,
|
||||||
|
MINIMUM_ROWS = 1
|
||||||
|
}
|
||||||
|
|
||||||
function getWindow(e: Node): Window {
|
function getWindow(e: Node): Window {
|
||||||
if (e?.ownerDocument?.defaultView) {
|
if (e?.ownerDocument?.defaultView) {
|
||||||
@@ -48,10 +50,7 @@ export class FitAddon implements ITerminalAddon, IFitApi {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Force a full render
|
this._terminal.resize(dims.cols, dims.rows);
|
||||||
if (this._terminal.rows !== dims.rows || this._terminal.cols !== dims.cols) {
|
|
||||||
this._terminal.resize(dims.cols, dims.rows);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public proposeDimensions(): ITerminalDimensions | undefined {
|
public proposeDimensions(): ITerminalDimensions | undefined {
|
||||||
@@ -69,9 +68,10 @@ export class FitAddon implements ITerminalAddon, IFitApi {
|
|||||||
return undefined;
|
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
|
? 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 parentElementStyle = _getComputedStyle(this._terminal.element.parentElement);
|
||||||
const parentElementHeight = parseInt(parentElementStyle.getPropertyValue('height'));
|
const parentElementHeight = parseInt(parentElementStyle.getPropertyValue('height'));
|
||||||
@@ -88,8 +88,8 @@ export class FitAddon implements ITerminalAddon, IFitApi {
|
|||||||
const availableHeight = parentElementHeight - elementPaddingVer;
|
const availableHeight = parentElementHeight - elementPaddingVer;
|
||||||
const availableWidth = parentElementWidth - elementPaddingHor - scrollbarWidth;
|
const availableWidth = parentElementWidth - elementPaddingHor - scrollbarWidth;
|
||||||
const geometry = {
|
const geometry = {
|
||||||
cols: Math.max(MINIMUM_COLS, Math.floor(availableWidth / dims.css.cell.width)),
|
cols: Math.max(Constants.MINIMUM_COLS, Math.floor(availableWidth / dims.css.cell.width)),
|
||||||
rows: Math.max(MINIMUM_ROWS, Math.floor(availableHeight / dims.css.cell.height))
|
rows: Math.max(Constants.MINIMUM_ROWS, Math.floor(availableHeight / dims.css.cell.height))
|
||||||
};
|
};
|
||||||
return geometry;
|
return geometry;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -119,6 +119,17 @@ test.describe('FitAddon', () => {
|
|||||||
strictEqual(await ctx.proxy.cols, 2);
|
strictEqual(await ctx.proxy.cols, 2);
|
||||||
strictEqual(await ctx.proxy.rows, 1);
|
strictEqual(await ctx.proxy.rows, 1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('same dimensions', async function(): Promise<any> {
|
||||||
|
await setDimensions();
|
||||||
|
await ctx.page.evaluate(`window.fit.fit()`);
|
||||||
|
const cols: number = await ctx.proxy.cols;
|
||||||
|
const rows: number = await ctx.proxy.rows;
|
||||||
|
// Calling fit() again at the same container size should not throw
|
||||||
|
await ctx.page.evaluate(`window.fit.fit()`);
|
||||||
|
strictEqual(await ctx.proxy.cols, cols);
|
||||||
|
strictEqual(await ctx.proxy.rows, rows);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -9,13 +9,15 @@
|
|||||||
"outDir": "../out-test",
|
"outDir": "../out-test",
|
||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"removeComments": true,
|
"removeComments": true,
|
||||||
"baseUrl": ".",
|
|
||||||
"paths": {
|
"paths": {
|
||||||
"common/*": [
|
"common/*": [
|
||||||
"../../../src/common/*"
|
"../../../src/common/*"
|
||||||
],
|
],
|
||||||
"browser/*": [
|
"browser/*": [
|
||||||
"../../../src/browser/*"
|
"../../../src/browser/*"
|
||||||
|
],
|
||||||
|
"*": [
|
||||||
|
"./*"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"strict": true,
|
"strict": true,
|
||||||
|
|||||||
@@ -25,14 +25,14 @@ const customSettings: IImageAddonOptions = {
|
|||||||
pixelLimit: 16777216, // max. pixel size of a single image
|
pixelLimit: 16777216, // max. pixel size of a single image
|
||||||
sixelSupport: true, // enable sixel support
|
sixelSupport: true, // enable sixel support
|
||||||
sixelScrolling: true, // whether to scroll on image output
|
sixelScrolling: true, // whether to scroll on image output
|
||||||
sixelPaletteLimit: 256, // initial sixel palette size
|
sixelPaletteLimit: 4096, // initial sixel palette size
|
||||||
sixelSizeLimit: 25000000, // size limit of a single sixel sequence
|
sixelSizeLimit: 33554432, // size limit of a single sixel sequence
|
||||||
storageLimit: 128, // FIFO storage limit in MB
|
storageLimit: 128, // FIFO storage limit in MB
|
||||||
showPlaceholder: true, // whether to show a placeholder for evicted images
|
showPlaceholder: true, // whether to show a placeholder for evicted images
|
||||||
iipSupport: true, // enable iTerm IIP support
|
iipSupport: true, // enable iTerm IIP support
|
||||||
iipSizeLimit: 20000000, // size limit of a single IIP sequence
|
iipSizeLimit: 33554432, // size limit of a single IIP sequence
|
||||||
kittySupport: true, // enable Kitty graphics support
|
kittySupport: true, // enable Kitty graphics support
|
||||||
kittySizeLimit: 20000000 // size limit of a single Kitty sequence
|
kittySizeLimit: 33554432 // size limit of a single Kitty sequence
|
||||||
}
|
}
|
||||||
|
|
||||||
// initialization
|
// initialization
|
||||||
|
|||||||
@@ -18,13 +18,13 @@
|
|||||||
"xterm.js"
|
"xterm.js"
|
||||||
],
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"prepackage": "../../node_modules/.bin/tsc -p .",
|
"prepackage": "../../node_modules/.bin/tsgo -p .",
|
||||||
"package": "../../node_modules/.bin/webpack",
|
"package": "../../node_modules/.bin/webpack",
|
||||||
"prepublishOnly": "npm run package",
|
"prepublishOnly": "npm run package",
|
||||||
"start": "node ../../demo/start"
|
"start": "node ../../demo/start"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"sixel": "^0.16.0",
|
"sixel": "^0.16.0",
|
||||||
"xterm-wasm-parts": "^0.3.0"
|
"xterm-wasm-parts": "^0.4.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,17 +4,22 @@
|
|||||||
*/
|
*/
|
||||||
import { IImageAddonOptions, IOscHandler, IResetHandler, ITerminalExt } from './Types';
|
import { IImageAddonOptions, IOscHandler, IResetHandler, ITerminalExt } from './Types';
|
||||||
import { ImageRenderer } from './ImageRenderer';
|
import { ImageRenderer } from './ImageRenderer';
|
||||||
import { ImageStorage, CELL_SIZE_DEFAULT } from './ImageStorage';
|
import { IIPImageStorage } from './IIPImageStorage';
|
||||||
import Base64Decoder, { type DecodeStatus } from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';
|
import { CELL_SIZE_DEFAULT } from './ImageStorage';
|
||||||
|
import Base64Decoder from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';
|
||||||
|
import QoiDecoder from 'xterm-wasm-parts/lib/qoi/QoiDecoder.wasm';
|
||||||
import { HeaderParser, IHeaderFields, HeaderState } from './IIPHeaderParser';
|
import { HeaderParser, IHeaderFields, HeaderState } from './IIPHeaderParser';
|
||||||
import { imageType, UNSUPPORTED_TYPE } from './IIPMetrics';
|
import { imageType, UNSUPPORTED_TYPE } from './IIPMetrics';
|
||||||
|
|
||||||
// limit hold memory in base64 decoder (encoded bytes)
|
// Local const enum mirror - esbuild can't inline const enums from external packages
|
||||||
const KEEP_DATA = 4194304;
|
const enum DecoderConst {
|
||||||
const INITIAL_DATA = 1048576;
|
// Limit held memory in base64 decoder (encoded bytes).
|
||||||
|
KEEP_DATA = 4194304,
|
||||||
// Local mirror of const enum (esbuild can't inline const enums from external packages)
|
// Initial buffer allocation for the decoder.
|
||||||
const DECODER_OK: DecodeStatus.OK = 0;
|
INITIAL_DATA = 1048576,
|
||||||
|
// Local mirror of const enum (esbuild can't inline const enums from external packages)
|
||||||
|
OK = 0
|
||||||
|
}
|
||||||
|
|
||||||
// default IIP header values
|
// default IIP header values
|
||||||
const DEFAULT_HEADER: IHeaderFields = {
|
const DEFAULT_HEADER: IHeaderFields = {
|
||||||
@@ -32,17 +37,19 @@ export class IIPHandler implements IOscHandler, IResetHandler {
|
|||||||
private _hp = new HeaderParser();
|
private _hp = new HeaderParser();
|
||||||
private _header: IHeaderFields = DEFAULT_HEADER;
|
private _header: IHeaderFields = DEFAULT_HEADER;
|
||||||
private _dec: Base64Decoder;
|
private _dec: Base64Decoder;
|
||||||
|
private _qoiDec: QoiDecoder;
|
||||||
private _metrics = UNSUPPORTED_TYPE;
|
private _metrics = UNSUPPORTED_TYPE;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly _opts: IImageAddonOptions,
|
private readonly _opts: IImageAddonOptions,
|
||||||
private readonly _renderer: ImageRenderer,
|
private readonly _renderer: ImageRenderer,
|
||||||
private readonly _storage: ImageStorage,
|
private readonly _storage: IIPImageStorage,
|
||||||
private readonly _coreTerminal: ITerminalExt
|
private readonly _coreTerminal: ITerminalExt
|
||||||
) {
|
) {
|
||||||
const maxEncodedBytes = Math.ceil(this._opts.iipSizeLimit * 4 / 3);
|
const maxEncodedBytes = Math.ceil(this._opts.iipSizeLimit * 4 / 3);
|
||||||
const initialBytes = Math.min(INITIAL_DATA, maxEncodedBytes);
|
const initialBytes = Math.min(DecoderConst.INITIAL_DATA, maxEncodedBytes);
|
||||||
this._dec = new Base64Decoder(KEEP_DATA, maxEncodedBytes, initialBytes);
|
this._dec = new Base64Decoder(DecoderConst.KEEP_DATA, maxEncodedBytes, initialBytes);
|
||||||
|
this._qoiDec = new QoiDecoder(DecoderConst.KEEP_DATA);
|
||||||
}
|
}
|
||||||
|
|
||||||
public reset(): void {}
|
public reset(): void {}
|
||||||
@@ -58,7 +65,7 @@ export class IIPHandler implements IOscHandler, IResetHandler {
|
|||||||
if (this._aborted) return;
|
if (this._aborted) return;
|
||||||
|
|
||||||
if (this._hp.state === HeaderState.END) {
|
if (this._hp.state === HeaderState.END) {
|
||||||
if (this._dec.put(data.subarray(start, end)) !== DECODER_OK) {
|
if ((this._dec.put(data.subarray(start, end)) as number) !== DecoderConst.OK) {
|
||||||
this._dec.release();
|
this._dec.release();
|
||||||
this._aborted = true;
|
this._aborted = true;
|
||||||
}
|
}
|
||||||
@@ -75,7 +82,7 @@ export class IIPHandler implements IOscHandler, IResetHandler {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this._dec.init();
|
this._dec.init();
|
||||||
if (this._dec.put(data.subarray(dataPos, end)) !== DECODER_OK) {
|
if ((this._dec.put(data.subarray(dataPos, end)) as number) !== DecoderConst.OK) {
|
||||||
this._dec.release();
|
this._dec.release();
|
||||||
this._aborted = true;
|
this._aborted = true;
|
||||||
}
|
}
|
||||||
@@ -111,27 +118,27 @@ export class IIPHandler implements IOscHandler, IResetHandler {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// HACK: The types on Blob are too restrictive, this is a Uint8Array so the browser accepts it
|
let blob: Blob | ImageData;
|
||||||
const blob = new Blob([this._dec.data8 as Uint8Array<ArrayBuffer>], { type: this._metrics.mime });
|
if (this._metrics.mime === 'image/qoi') {
|
||||||
this._dec.release();
|
const data = this._qoiDec.decode(this._dec.data8);
|
||||||
|
blob = new ImageData(
|
||||||
if (!window.createImageBitmap) {
|
new Uint8ClampedArray(data.buffer, data.byteOffset, data.byteLength),
|
||||||
const url = URL.createObjectURL(blob);
|
this._qoiDec.width,
|
||||||
const img = new Image();
|
this._qoiDec.height
|
||||||
return new Promise<boolean>(r => {
|
);
|
||||||
img.addEventListener('load', () => {
|
this._qoiDec.release();
|
||||||
URL.revokeObjectURL(url);
|
if (w === this._qoiDec.width && h === this._qoiDec.height) {
|
||||||
const canvas = ImageRenderer.createCanvas(window.document, w, h);
|
// use fast-path if we don't need to rescale
|
||||||
canvas.getContext('2d')?.drawImage(img, 0, 0, w, h);
|
this._dec.release();
|
||||||
this._storage.addImage(canvas);
|
const canvas = ImageRenderer.createCanvas(undefined, this._qoiDec.width, this._qoiDec.height);
|
||||||
r(true);
|
canvas.getContext('2d')?.putImageData(blob, 0, 0);
|
||||||
});
|
this._storage.addImage(canvas);
|
||||||
img.src = url;
|
return true;
|
||||||
// sanity measure to avoid terminal blocking from dangling promise
|
}
|
||||||
// happens from corrupt data (onload never gets fired)
|
} else {
|
||||||
setTimeout(() => r(true), 1000);
|
blob = new Blob([this._dec.data8], { type: this._metrics.mime });
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
this._dec.release();
|
||||||
return createImageBitmap(blob, { resizeWidth: w, resizeHeight: h })
|
return createImageBitmap(blob, { resizeWidth: w, resizeHeight: h })
|
||||||
.then(bm => {
|
.then(bm => {
|
||||||
this._storage.addImage(bm);
|
this._storage.addImage(bm);
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2023 The xterm.js authors. All rights reserved.
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { ImageStorage } from './ImageStorage';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* IIP (iTerm Image Protocol) specific image storage controller.
|
||||||
|
*
|
||||||
|
* Wraps the shared ImageStorage with IIP protocol semantics:
|
||||||
|
* - Always uses scrolling mode (cursor advances with image)
|
||||||
|
*/
|
||||||
|
export class IIPImageStorage {
|
||||||
|
constructor(
|
||||||
|
private readonly _storage: ImageStorage
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add an IIP image to storage.
|
||||||
|
* Always uses scrolling mode — cursor advances past the image.
|
||||||
|
*/
|
||||||
|
public addImage(img: HTMLCanvasElement | ImageBitmap): void {
|
||||||
|
this._storage.addImage(img, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
|
|
||||||
export type ImageType = 'image/png' | 'image/jpeg' | 'image/gif' | 'unsupported' | '';
|
export type ImageType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/qoi' | 'unsupported' | '';
|
||||||
|
|
||||||
export interface IMetrics {
|
export interface IMetrics {
|
||||||
mime: ImageType;
|
mime: ImageType;
|
||||||
@@ -45,6 +45,14 @@ export function imageType(d: Uint8Array): IMetrics {
|
|||||||
height: d[9] << 8 | d[8]
|
height: d[9] << 8 | d[8]
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
// QOI: qoif
|
||||||
|
if (d32[0] === 0x66696F71) {
|
||||||
|
return {
|
||||||
|
mime: 'image/qoi',
|
||||||
|
width: d[4] << 24 | d[5] << 16 | d[6] << 8 | d[7],
|
||||||
|
height: d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11]
|
||||||
|
};
|
||||||
|
}
|
||||||
return UNSUPPORTED_TYPE;
|
return UNSUPPORTED_TYPE;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,27 +5,72 @@
|
|||||||
|
|
||||||
import type { ITerminalAddon, IDisposable } from '@xterm/xterm';
|
import type { ITerminalAddon, IDisposable } from '@xterm/xterm';
|
||||||
import type { ImageAddon as IImageApi } from '@xterm/addon-image';
|
import type { ImageAddon as IImageApi } from '@xterm/addon-image';
|
||||||
|
import { Emitter, type IEvent } from 'common/Event';
|
||||||
import { IIPHandler } from './IIPHandler';
|
import { IIPHandler } from './IIPHandler';
|
||||||
import { ImageRenderer } from './ImageRenderer';
|
import { ImageRenderer } from './ImageRenderer';
|
||||||
import { ImageStorage, CELL_SIZE_DEFAULT } from './ImageStorage';
|
import { ImageStorage, CELL_SIZE_DEFAULT } from './ImageStorage';
|
||||||
import { KittyGraphicsHandler } from './kitty/KittyGraphicsHandler';
|
import { KittyGraphicsHandler } from './kitty/KittyGraphicsHandler';
|
||||||
|
import { KittyImageStorage } from './kitty/KittyImageStorage';
|
||||||
import { SixelHandler } from './SixelHandler';
|
import { SixelHandler } from './SixelHandler';
|
||||||
|
import { SixelImageStorage } from './SixelImageStorage';
|
||||||
|
import { IIPImageStorage } from './IIPImageStorage';
|
||||||
import { ITerminalExt, IImageAddonOptions, IResetHandler } from './Types';
|
import { ITerminalExt, IImageAddonOptions, IResetHandler } from './Types';
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Document VT features provided by this addon.
|
||||||
|
*
|
||||||
|
* @vt: #E[Supported via @xterm/addon-image.] DCS SIXEL "SIXEL Graphics" "DCS Ps ; Ps ; Ps ; q Pt ST" "Draw SIXEL image."
|
||||||
|
*
|
||||||
|
* Sixel support is provided by the addon @xterm/addon-image with these limitations:
|
||||||
|
* - immediate coloring (no shared palette, allows high color settings of `img2sixel`)
|
||||||
|
* - max. palette size of 4096 colors
|
||||||
|
* - max. pixel width of 16K
|
||||||
|
* - max. 25 MB per sixel sequence
|
||||||
|
* - VT340 cursor positioning (begin of last sixel data row)
|
||||||
|
*
|
||||||
|
* See [addon readme](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-image) for more details.
|
||||||
|
*
|
||||||
|
*
|
||||||
|
* @vt: #E[Supported via @xterm/addon-image.] OSC 1337 "iTerm2 Commands" "OSC 1337 ; Pt BEL" "Custom iTerm2 commands."
|
||||||
|
*
|
||||||
|
* Only the inline image protocol (IIP) is supported by the addon @xterm/addon-image with
|
||||||
|
* the following limitations:
|
||||||
|
* - sequence:
|
||||||
|
* - format: `OSC 1337 ; File=inline=1 ; size=<unencoded size> ; ... : <base64 payload> BEL`
|
||||||
|
* - size param must be set and payload may not exceed CEIL(size * 4 / 3)
|
||||||
|
* - strict base64 handling as of RFC4648 §4 (standard alphabet, optional padding,
|
||||||
|
* no separator bytes allowed)
|
||||||
|
* - supported params: size, name, width, height, preserveAspectRatio
|
||||||
|
* - image formats: PNG, JPEG and GIF
|
||||||
|
* - no animation support (renders first image of a GIF)
|
||||||
|
* - no multipart support
|
||||||
|
* - VT340 cursor positioning (begin of last sixel data row)
|
||||||
|
*
|
||||||
|
* See [addon readme](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-image)
|
||||||
|
* and [iTerm2 IIP docs](https://iterm2.com/documentation-images.html) for more details.
|
||||||
|
*
|
||||||
|
*
|
||||||
|
* @vt: #E[Supported via @xterm/addon-image.] APC KITTY_GRAPHICS "Kitty Graphics" "APC G Pt ST" "Kitty Graphics Protocol."
|
||||||
|
*
|
||||||
|
* Kitty graphics support is provided by the addon @xterm/addon-image.
|
||||||
|
* Note that while basic image output already works, this is still work in progress.
|
||||||
|
*/
|
||||||
|
|
||||||
// default values of addon ctor options
|
// default values of addon ctor options
|
||||||
const DEFAULT_OPTIONS: IImageAddonOptions = {
|
const DEFAULT_OPTIONS: IImageAddonOptions = {
|
||||||
enableSizeReports: true,
|
enableSizeReports: true,
|
||||||
pixelLimit: 16777216, // limit to 4096 * 4096 pixels
|
pixelLimit: 16777216, // limit to 4096 * 4096 pixels
|
||||||
sixelSupport: true,
|
sixelSupport: true,
|
||||||
sixelScrolling: true,
|
sixelScrolling: true,
|
||||||
sixelPaletteLimit: 256,
|
sixelPaletteLimit: 4096,
|
||||||
sixelSizeLimit: 25000000,
|
sixelSizeLimit: 33554432,
|
||||||
storageLimit: 128,
|
storageLimit: 128,
|
||||||
showPlaceholder: true,
|
showPlaceholder: true,
|
||||||
iipSupport: true,
|
iipSupport: true,
|
||||||
iipSizeLimit: 20000000,
|
iipSizeLimit: 33554432,
|
||||||
kittySupport: true,
|
kittySupport: true,
|
||||||
kittySizeLimit: 20000000
|
kittySizeLimit: 33554432
|
||||||
};
|
};
|
||||||
|
|
||||||
// max palette size supported by the sixel lib (compile time setting)
|
// max palette size supported by the sixel lib (compile time setting)
|
||||||
@@ -59,6 +104,8 @@ export class ImageAddon implements ITerminalAddon, IImageApi {
|
|||||||
private _disposables: IDisposable[] = [];
|
private _disposables: IDisposable[] = [];
|
||||||
private _terminal: ITerminalExt | undefined;
|
private _terminal: ITerminalExt | undefined;
|
||||||
private _handlers: Map<String, IResetHandler> = new Map();
|
private _handlers: Map<String, IResetHandler> = new Map();
|
||||||
|
private readonly _onImageAdded = new Emitter<void>();
|
||||||
|
public readonly onImageAdded: IEvent<void> = this._onImageAdded.event;
|
||||||
|
|
||||||
constructor(opts?: Partial<IImageAddonOptions>) {
|
constructor(opts?: Partial<IImageAddonOptions>) {
|
||||||
this._opts = Object.assign({}, DEFAULT_OPTIONS, opts);
|
this._opts = Object.assign({}, DEFAULT_OPTIONS, opts);
|
||||||
@@ -71,6 +118,7 @@ export class ImageAddon implements ITerminalAddon, IImageApi {
|
|||||||
}
|
}
|
||||||
this._disposables.length = 0;
|
this._disposables.length = 0;
|
||||||
this._handlers.clear();
|
this._handlers.clear();
|
||||||
|
this._onImageAdded.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
private _disposeLater(...args: IDisposable[]): void {
|
private _disposeLater(...args: IDisposable[]): void {
|
||||||
@@ -85,6 +133,7 @@ export class ImageAddon implements ITerminalAddon, IImageApi {
|
|||||||
// internal data structures
|
// internal data structures
|
||||||
this._renderer = new ImageRenderer(terminal);
|
this._renderer = new ImageRenderer(terminal);
|
||||||
this._storage = new ImageStorage(terminal, this._renderer, this._opts);
|
this._storage = new ImageStorage(terminal, this._renderer, this._opts);
|
||||||
|
this._storage.onImageAdded = () => this._onImageAdded.fire();
|
||||||
|
|
||||||
// enable size reports
|
// enable size reports
|
||||||
if (this._opts.enableSizeReports) {
|
if (this._opts.enableSizeReports) {
|
||||||
@@ -132,7 +181,8 @@ export class ImageAddon implements ITerminalAddon, IImageApi {
|
|||||||
|
|
||||||
// SIXEL handler
|
// SIXEL handler
|
||||||
if (this._opts.sixelSupport) {
|
if (this._opts.sixelSupport) {
|
||||||
const sixelHandler = new SixelHandler(this._opts, this._storage!, terminal);
|
const sixelStorage = new SixelImageStorage(this._storage!, this._opts, this._renderer!, terminal);
|
||||||
|
const sixelHandler = new SixelHandler(this._opts, sixelStorage, terminal);
|
||||||
this._handlers.set('sixel', sixelHandler);
|
this._handlers.set('sixel', sixelHandler);
|
||||||
this._disposeLater(
|
this._disposeLater(
|
||||||
terminal._core._inputHandler._parser.registerDcsHandler({ final: 'q' }, sixelHandler)
|
terminal._core._inputHandler._parser.registerDcsHandler({ final: 'q' }, sixelHandler)
|
||||||
@@ -141,7 +191,8 @@ export class ImageAddon implements ITerminalAddon, IImageApi {
|
|||||||
|
|
||||||
// iTerm IIP handler
|
// iTerm IIP handler
|
||||||
if (this._opts.iipSupport) {
|
if (this._opts.iipSupport) {
|
||||||
const iipHandler = new IIPHandler(this._opts, this._renderer!, this._storage!, terminal);
|
const iipStorage = new IIPImageStorage(this._storage!);
|
||||||
|
const iipHandler = new IIPHandler(this._opts, this._renderer!, iipStorage, terminal);
|
||||||
this._handlers.set('iip', iipHandler);
|
this._handlers.set('iip', iipHandler);
|
||||||
this._disposeLater(
|
this._disposeLater(
|
||||||
terminal._core._inputHandler._parser.registerOscHandler(1337, iipHandler)
|
terminal._core._inputHandler._parser.registerOscHandler(1337, iipHandler)
|
||||||
@@ -150,10 +201,13 @@ export class ImageAddon implements ITerminalAddon, IImageApi {
|
|||||||
|
|
||||||
// Kitty graphics handler
|
// Kitty graphics handler
|
||||||
if (this._opts.kittySupport) {
|
if (this._opts.kittySupport) {
|
||||||
const kittyHandler = new KittyGraphicsHandler(this._opts, this._renderer!, this._storage!, terminal);
|
const kittyStorage = new KittyImageStorage(this._storage!);
|
||||||
|
const kittyHandler = new KittyGraphicsHandler(this._opts, this._renderer!, kittyStorage, terminal);
|
||||||
this._handlers.set('kitty', kittyHandler);
|
this._handlers.set('kitty', kittyHandler);
|
||||||
this._disposeLater(
|
this._disposeLater(
|
||||||
terminal._core._inputHandler._parser.registerApcHandler(0x47, kittyHandler)
|
kittyStorage,
|
||||||
|
kittyHandler,
|
||||||
|
terminal._core._inputHandler._parser.registerApcHandler({ final: 'G' }, kittyHandler)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,11 +5,13 @@
|
|||||||
|
|
||||||
import { toRGBA8888 } from 'sixel/lib/Colors';
|
import { toRGBA8888 } from 'sixel/lib/Colors';
|
||||||
import { IDisposable } from '@xterm/xterm';
|
import { IDisposable } from '@xterm/xterm';
|
||||||
import { ICellSize, ITerminalExt, IImageSpec, IRenderDimensions, IRenderService } from './Types';
|
import { ICellSize, ImageLayer, 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 enum Constants {
|
||||||
const PLACEHOLDER_HEIGHT = 24;
|
PLACEHOLDER_LENGTH = 4096,
|
||||||
|
PLACEHOLDER_HEIGHT = 24
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ImageRenderer - terminal frontend extension:
|
* ImageRenderer - terminal frontend extension:
|
||||||
@@ -18,8 +20,9 @@ const PLACEHOLDER_HEIGHT = 24;
|
|||||||
* - draw image tiles onRender
|
* - draw image tiles onRender
|
||||||
*/
|
*/
|
||||||
export class ImageRenderer extends Disposable implements IDisposable {
|
export class ImageRenderer extends Disposable implements IDisposable {
|
||||||
public canvas: HTMLCanvasElement | undefined;
|
/** @deprecated Kept for backward compat — points to top layer canvas. */
|
||||||
private _ctx: CanvasRenderingContext2D | null | undefined;
|
public get canvas(): HTMLCanvasElement | undefined { return this._layers.get('top')?.canvas; }
|
||||||
|
private _layers = new Map<ImageLayer, CanvasRenderingContext2D>();
|
||||||
private _placeholder: HTMLCanvasElement | undefined;
|
private _placeholder: HTMLCanvasElement | undefined;
|
||||||
private _placeholderBitmap: ImageBitmap | undefined;
|
private _placeholderBitmap: ImageBitmap | undefined;
|
||||||
private _optionsRefresh = this._register(new MutableDisposable());
|
private _optionsRefresh = this._register(new MutableDisposable());
|
||||||
@@ -86,6 +89,7 @@ export class ImageRenderer extends Disposable implements IDisposable {
|
|||||||
});
|
});
|
||||||
this._register(toDisposable(() => {
|
this._register(toDisposable(() => {
|
||||||
this.removeLayerFromDom();
|
this.removeLayerFromDom();
|
||||||
|
this.removeLayerFromDom('bottom');
|
||||||
if (this._terminal._core && this._oldOpen) {
|
if (this._terminal._core && this._oldOpen) {
|
||||||
this._terminal._core.open = this._oldOpen;
|
this._terminal._core.open = this._oldOpen;
|
||||||
this._oldOpen = undefined;
|
this._oldOpen = undefined;
|
||||||
@@ -95,8 +99,7 @@ export class ImageRenderer extends Disposable implements IDisposable {
|
|||||||
this._oldSetRenderer = undefined;
|
this._oldSetRenderer = undefined;
|
||||||
}
|
}
|
||||||
this._renderService = undefined;
|
this._renderService = undefined;
|
||||||
this.canvas = undefined;
|
this._layers.clear();
|
||||||
this._ctx = undefined;
|
|
||||||
this._placeholderBitmap?.close();
|
this._placeholderBitmap?.close();
|
||||||
this._placeholderBitmap = undefined;
|
this._placeholderBitmap = undefined;
|
||||||
this._placeholder = undefined;
|
this._placeholder = undefined;
|
||||||
@@ -109,7 +112,7 @@ export class ImageRenderer extends Disposable implements IDisposable {
|
|||||||
public showPlaceholder(value: boolean): void {
|
public showPlaceholder(value: boolean): void {
|
||||||
if (value) {
|
if (value) {
|
||||||
if (!this._placeholder && this.cellSize.height !== -1) {
|
if (!this._placeholder && this.cellSize.height !== -1) {
|
||||||
this._createPlaceHolder(Math.max(this.cellSize.height + 1, PLACEHOLDER_HEIGHT));
|
this._createPlaceHolder(Math.max(this.cellSize.height + 1, Constants.PLACEHOLDER_HEIGHT));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
this._placeholderBitmap?.close();
|
this._placeholderBitmap?.close();
|
||||||
@@ -140,27 +143,38 @@ export class ImageRenderer extends Disposable implements IDisposable {
|
|||||||
/**
|
/**
|
||||||
* Clear a region of the image layer canvas.
|
* Clear a region of the image layer canvas.
|
||||||
*/
|
*/
|
||||||
public clearLines(start: number, end: number): void {
|
public clearLines(start: number, end: number, layer?: ImageLayer): void {
|
||||||
this._ctx?.clearRect(
|
const y = start * (this.dimensions?.css.cell.height || 0);
|
||||||
0,
|
const w = this.dimensions?.css.canvas.width || 0;
|
||||||
start * (this.dimensions?.css.cell.height || 0),
|
const h = (++end - start) * (this.dimensions?.css.cell.height || 0);
|
||||||
this.dimensions?.css.canvas.width || 0,
|
if (!layer || layer === 'top') {
|
||||||
(++end - start) * (this.dimensions?.css.cell.height || 0)
|
this._layers.get('top')?.clearRect(0, y, w, h);
|
||||||
);
|
}
|
||||||
|
if (!layer || layer === 'bottom') {
|
||||||
|
this._layers.get('bottom')?.clearRect(0, y, w, h);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Clear whole image canvas.
|
* Clear whole image canvas.
|
||||||
*/
|
*/
|
||||||
public clearAll(): void {
|
public clearAll(layer?: ImageLayer): void {
|
||||||
this._ctx?.clearRect(0, 0, this.canvas?.width || 0, this.canvas?.height || 0);
|
if (!layer || layer === 'top') {
|
||||||
|
const ctx = this._layers.get('top');
|
||||||
|
ctx?.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
|
||||||
|
}
|
||||||
|
if (!layer || layer === 'bottom') {
|
||||||
|
const ctx = this._layers.get('bottom');
|
||||||
|
ctx?.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Draw neighboring tiles on the image layer canvas.
|
* Draw neighboring tiles on the image layer canvas.
|
||||||
*/
|
*/
|
||||||
public draw(imgSpec: IImageSpec, tileId: number, col: number, row: number, count: number = 1): void {
|
public draw(imgSpec: IImageSpec, tileId: number, col: number, row: number, count: number = 1): void {
|
||||||
if (!this._ctx) {
|
const ctx = this._layers.get(imgSpec.layer);
|
||||||
|
if (!ctx) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const { width, height } = this.cellSize;
|
const { width, height } = this.cellSize;
|
||||||
@@ -187,7 +201,7 @@ export class ImageRenderer extends Disposable implements IDisposable {
|
|||||||
// Note: For not pixel perfect aligned cells like in the DOM renderer
|
// Note: For not pixel perfect aligned cells like in the DOM renderer
|
||||||
// this will move a tile slightly to the top/left (subpixel range, thus ignore it).
|
// this will move a tile slightly to the top/left (subpixel range, thus ignore it).
|
||||||
// FIX #34: avoid striping on displays with pixelDeviceRatio != 1 by ceiling height and width
|
// FIX #34: avoid striping on displays with pixelDeviceRatio != 1 by ceiling height and width
|
||||||
this._ctx.drawImage(
|
ctx.drawImage(
|
||||||
img,
|
img,
|
||||||
Math.floor(sx), Math.floor(sy), Math.ceil(finalWidth), Math.ceil(finalHeight),
|
Math.floor(sx), Math.floor(sy), Math.ceil(finalWidth), Math.ceil(finalHeight),
|
||||||
Math.floor(dx), Math.floor(dy), Math.ceil(finalWidth), Math.ceil(finalHeight)
|
Math.floor(dx), Math.floor(dy), Math.ceil(finalWidth), Math.ceil(finalHeight)
|
||||||
@@ -227,7 +241,8 @@ export class ImageRenderer extends Disposable implements IDisposable {
|
|||||||
* Draw a line with placeholder on the image layer canvas.
|
* Draw a line with placeholder on the image layer canvas.
|
||||||
*/
|
*/
|
||||||
public drawPlaceholder(col: number, row: number, count: number = 1): void {
|
public drawPlaceholder(col: number, row: number, count: number = 1): void {
|
||||||
if (this._ctx) {
|
const ctx = this._layers.get('top');
|
||||||
|
if (ctx) {
|
||||||
const { width, height } = this.cellSize;
|
const { width, height } = this.cellSize;
|
||||||
|
|
||||||
// Don't try to draw anything, if we cannot get valid renderer metrics.
|
// Don't try to draw anything, if we cannot get valid renderer metrics.
|
||||||
@@ -236,12 +251,12 @@ export class ImageRenderer extends Disposable implements IDisposable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!this._placeholder) {
|
if (!this._placeholder) {
|
||||||
this._createPlaceHolder(Math.max(height + 1, PLACEHOLDER_HEIGHT));
|
this._createPlaceHolder(Math.max(height + 1, Constants.PLACEHOLDER_HEIGHT));
|
||||||
} else if (height >= this._placeholder!.height) {
|
} else if (height >= this._placeholder!.height) {
|
||||||
this._createPlaceHolder(height + 1);
|
this._createPlaceHolder(height + 1);
|
||||||
}
|
}
|
||||||
if (!this._placeholder) return;
|
if (!this._placeholder) return;
|
||||||
this._ctx.drawImage(
|
ctx.drawImage(
|
||||||
this._placeholderBitmap ?? this._placeholder!,
|
this._placeholderBitmap ?? this._placeholder!,
|
||||||
col * width,
|
col * width,
|
||||||
(row * height) % 2 ? 0 : 1, // needs %2 offset correction
|
(row * height) % 2 ? 0 : 1, // needs %2 offset correction
|
||||||
@@ -260,12 +275,13 @@ export class ImageRenderer extends Disposable implements IDisposable {
|
|||||||
* Checked once from `ImageStorage.render`.
|
* Checked once from `ImageStorage.render`.
|
||||||
*/
|
*/
|
||||||
public rescaleCanvas(): void {
|
public rescaleCanvas(): void {
|
||||||
if (!this.canvas) {
|
const w = this.dimensions?.css.canvas.width || 0;
|
||||||
return;
|
const h = this.dimensions?.css.canvas.height || 0;
|
||||||
}
|
for (const ctx of this._layers.values()) {
|
||||||
if (this.canvas.width !== this.dimensions!.css.canvas.width || this.canvas.height !== this.dimensions!.css.canvas.height) {
|
if (ctx.canvas.width !== w || ctx.canvas.height !== h) {
|
||||||
this.canvas.width = this.dimensions!.css.canvas.width || 0;
|
ctx.canvas.width = w;
|
||||||
this.canvas.height = this.dimensions!.css.canvas.height || 0;
|
ctx.canvas.height = h;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -304,38 +320,68 @@ export class ImageRenderer extends Disposable implements IDisposable {
|
|||||||
this._renderService = this._terminal._core._renderService;
|
this._renderService = this._terminal._core._renderService;
|
||||||
this._oldSetRenderer = this._renderService.setRenderer.bind(this._renderService);
|
this._oldSetRenderer = this._renderService.setRenderer.bind(this._renderService);
|
||||||
this._renderService.setRenderer = (renderer: any) => {
|
this._renderService.setRenderer = (renderer: any) => {
|
||||||
this.removeLayerFromDom();
|
for (const key of [...this._layers.keys()]) {
|
||||||
|
this.removeLayerFromDom(key);
|
||||||
|
}
|
||||||
this._oldSetRenderer?.call(this._renderService, renderer);
|
this._oldSetRenderer?.call(this._renderService, renderer);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
public insertLayerToDom(): void {
|
public insertLayerToDom(layer: ImageLayer = 'top'): void {
|
||||||
// make sure that the terminal is attached to a document and to DOM
|
// make sure that the terminal is attached to a document and to DOM
|
||||||
if (this.document && this._terminal._core.screenElement) {
|
if (!this.document || !this._terminal._core.screenElement) {
|
||||||
if (!this.canvas) {
|
|
||||||
this.canvas = ImageRenderer.createCanvas(
|
|
||||||
this.document, this.dimensions?.css.canvas.width || 0,
|
|
||||||
this.dimensions?.css.canvas.height || 0
|
|
||||||
);
|
|
||||||
this.canvas.classList.add('xterm-image-layer');
|
|
||||||
this._terminal._core.screenElement.appendChild(this.canvas);
|
|
||||||
this._ctx = this.canvas.getContext('2d', { alpha: true, desynchronized: true });
|
|
||||||
this.clearAll();
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
console.warn('image addon: cannot insert output canvas to DOM, missing document or screenElement');
|
console.warn('image addon: cannot insert output canvas to DOM, missing document or screenElement');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (this._layers.has(layer)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const canvas = ImageRenderer.createCanvas(
|
||||||
|
this.document, this.dimensions?.css.canvas.width || 0,
|
||||||
|
this.dimensions?.css.canvas.height || 0
|
||||||
|
);
|
||||||
|
canvas.classList.add(`xterm-image-layer-${layer}`);
|
||||||
|
const screenElement = this._terminal._core.screenElement;
|
||||||
|
// Use isolation to create a stacking context without overriding z-index,
|
||||||
|
// which would conflict with integrators (e.g. VS Code) that set their
|
||||||
|
// own z-index on the screen element.
|
||||||
|
screenElement.style.isolation = 'isolate';
|
||||||
|
if (layer === 'bottom') {
|
||||||
|
// Use z-index:-1 so it paints behind non-positioned text elements.
|
||||||
|
// The screen element needs to be a stacking context (via isolation)
|
||||||
|
// to contain the negative z-index, otherwise it would go behind the
|
||||||
|
// entire terminal.
|
||||||
|
canvas.style.zIndex = '-1';
|
||||||
|
screenElement.insertBefore(canvas, screenElement.firstChild);
|
||||||
|
} else {
|
||||||
|
// Explicit z-index ensures the image canvas reliably stacks above
|
||||||
|
// the text layer (DOM renderer rows). z-index: 0 is below the
|
||||||
|
// selection overlay (z-index: 1).
|
||||||
|
canvas.style.zIndex = '0';
|
||||||
|
screenElement.appendChild(canvas);
|
||||||
|
}
|
||||||
|
const ctx = canvas.getContext('2d', { alpha: true });
|
||||||
|
if (!ctx) {
|
||||||
|
canvas.remove();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this._layers.set(layer, ctx);
|
||||||
|
this.clearAll(layer);
|
||||||
|
}
|
||||||
|
|
||||||
|
public removeLayerFromDom(layer: ImageLayer = 'top'): void {
|
||||||
|
const ctx = this._layers.get(layer);
|
||||||
|
if (ctx) {
|
||||||
|
ctx.canvas.remove();
|
||||||
|
this._layers.delete(layer);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public removeLayerFromDom(): void {
|
public hasLayer(layer: ImageLayer): boolean {
|
||||||
if (this.canvas) {
|
return this._layers.has(layer);
|
||||||
this._ctx = undefined;
|
|
||||||
this.canvas.remove();
|
|
||||||
this.canvas = undefined;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private _createPlaceHolder(height: number = PLACEHOLDER_HEIGHT): void {
|
private _createPlaceHolder(height: number = Constants.PLACEHOLDER_HEIGHT): void {
|
||||||
this._placeholderBitmap?.close();
|
this._placeholderBitmap?.close();
|
||||||
this._placeholderBitmap = undefined;
|
this._placeholderBitmap = undefined;
|
||||||
|
|
||||||
@@ -359,7 +405,7 @@ export class ImageRenderer extends Disposable implements IDisposable {
|
|||||||
ctx.putImageData(imgData, 0, 0);
|
ctx.putImageData(imgData, 0, 0);
|
||||||
|
|
||||||
// create placeholder line, width aligned to blueprint width
|
// create placeholder line, width aligned to blueprint width
|
||||||
const width = (screen.width + bWidth - 1) & ~(bWidth - 1) || PLACEHOLDER_LENGTH;
|
const width = (screen.width + bWidth - 1) & ~(bWidth - 1) || Constants.PLACEHOLDER_LENGTH;
|
||||||
this._placeholder = ImageRenderer.createCanvas(this.document, width, height);
|
this._placeholder = ImageRenderer.createCanvas(this.document, width, height);
|
||||||
const ctx2 = this._placeholder.getContext('2d', { alpha: false });
|
const ctx2 = this._placeholder.getContext('2d', { alpha: false });
|
||||||
if (!ctx2) {
|
if (!ctx2) {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
|
|
||||||
import { IDisposable } from '@xterm/xterm';
|
import { IDisposable } from '@xterm/xterm';
|
||||||
import { ImageRenderer } from './ImageRenderer';
|
import { ImageRenderer } from './ImageRenderer';
|
||||||
import { ITerminalExt, IExtendedAttrsImage, IImageAddonOptions, IImageSpec, IBufferLineExt, BgFlags, Cell, Content, ICellSize, ExtFlags, Attributes, UnderlineStyle } from './Types';
|
import { ITerminalExt, IExtendedAttrsImage, IImageAddonOptions, IImageSpec, IBufferLineExt, BgFlags, Cell, Content, ICellSize, ExtFlags, Attributes, UnderlineStyle, ImageLayer } from './Types';
|
||||||
|
|
||||||
|
|
||||||
// fallback default cell size
|
// fallback default cell size
|
||||||
@@ -124,6 +124,8 @@ export class ImageStorage implements IDisposable {
|
|||||||
private _pixelLimit: number = 2500000;
|
private _pixelLimit: number = 2500000;
|
||||||
|
|
||||||
private _viewportMetrics: { cols: number, rows: number };
|
private _viewportMetrics: { cols: number, rows: number };
|
||||||
|
public onImageAdded: (() => void) | undefined;
|
||||||
|
public onImageDeleted: ((storageId: number) => void) | undefined;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private _terminal: ITerminalExt,
|
private _terminal: ITerminalExt,
|
||||||
@@ -189,11 +191,13 @@ export class ImageStorage implements IDisposable {
|
|||||||
|
|
||||||
private _delImg(id: number): void {
|
private _delImg(id: number): void {
|
||||||
const spec = this._images.get(id);
|
const spec = this._images.get(id);
|
||||||
|
if (!spec) return;
|
||||||
this._images.delete(id);
|
this._images.delete(id);
|
||||||
// FIXME: really ugly workaround to get bitmaps deallocated :(
|
// FIXME: really ugly workaround to get bitmaps deallocated :(
|
||||||
if (spec && window.ImageBitmap && spec.orig instanceof ImageBitmap) {
|
if (window.ImageBitmap && spec.orig instanceof ImageBitmap) {
|
||||||
spec.orig.close();
|
spec.orig.close();
|
||||||
}
|
}
|
||||||
|
this.onImageDeleted?.(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -216,24 +220,6 @@ export class ImageStorage implements IDisposable {
|
|||||||
this._fullyCleared = false;
|
this._fullyCleared = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Only advance text cursor.
|
|
||||||
* This is an edge case from empty sixels carrying only a height but no pixels.
|
|
||||||
* Partially fixes https://github.com/jerch/xterm-addon-image/issues/37.
|
|
||||||
*/
|
|
||||||
public advanceCursor(height: number): void {
|
|
||||||
if (this._opts.sixelScrolling) {
|
|
||||||
let cellSize = this._renderer.cellSize;
|
|
||||||
if (cellSize.width === -1 || cellSize.height === -1) {
|
|
||||||
cellSize = CELL_SIZE_DEFAULT;
|
|
||||||
}
|
|
||||||
const rows = Math.ceil(height / cellSize.height);
|
|
||||||
for (let i = 1; i < rows; ++i) {
|
|
||||||
this._terminal._core._inputHandler.lineFeed();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Delete an image by its internal storage ID.
|
* Delete an image by its internal storage ID.
|
||||||
* Used by protocols that support explicit deletion (e.g. Kitty a=d).
|
* Used by protocols that support explicit deletion (e.g. Kitty a=d).
|
||||||
@@ -248,9 +234,14 @@ export class ImageStorage implements IDisposable {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Method to add an image to the storage.
|
* Method to add an image to the storage.
|
||||||
* Returns the internal image ID assigned to the stored image.
|
* @param img - The image to add (canvas or bitmap).
|
||||||
|
* @param scrolling - When true, cursor advances with the image (lineFeed per row).
|
||||||
|
* When false, image is placed at (0,0) and cursor is restored (DECSET 80 / sixel origin mode).
|
||||||
|
* @param layer - Which canvas layer to render on ('top' or 'bottom').
|
||||||
|
* @param zIndex - Z-index for image layering within the same layer.
|
||||||
|
* @returns The internal image ID assigned to the stored image.
|
||||||
*/
|
*/
|
||||||
public addImage(img: HTMLCanvasElement | ImageBitmap): number {
|
public addImage(img: HTMLCanvasElement | ImageBitmap, scrolling: boolean, layer: ImageLayer = 'top', zIndex: number = 0): number {
|
||||||
// never allow storage to exceed memory limit
|
// never allow storage to exceed memory limit
|
||||||
this._evictOldest(img.width * img.height);
|
this._evictOldest(img.width * img.height);
|
||||||
|
|
||||||
@@ -272,7 +263,7 @@ export class ImageStorage implements IDisposable {
|
|||||||
let offset = originX;
|
let offset = originX;
|
||||||
let tileCount = 0;
|
let tileCount = 0;
|
||||||
|
|
||||||
if (!this._opts.sixelScrolling) {
|
if (!scrolling) {
|
||||||
buffer.x = 0;
|
buffer.x = 0;
|
||||||
buffer.y = 0;
|
buffer.y = 0;
|
||||||
offset = 0;
|
offset = 0;
|
||||||
@@ -286,7 +277,7 @@ export class ImageStorage implements IDisposable {
|
|||||||
this._writeToCell(line as IBufferLineExt, offset + col, imageId, row * cols + col);
|
this._writeToCell(line as IBufferLineExt, offset + col, imageId, row * cols + col);
|
||||||
tileCount++;
|
tileCount++;
|
||||||
}
|
}
|
||||||
if (this._opts.sixelScrolling) {
|
if (scrolling) {
|
||||||
if (row < rows - 1) this._terminal._core._inputHandler.lineFeed();
|
if (row < rows - 1) this._terminal._core._inputHandler.lineFeed();
|
||||||
} else {
|
} else {
|
||||||
if (++buffer.y >= termRows) break;
|
if (++buffer.y >= termRows) break;
|
||||||
@@ -296,7 +287,7 @@ export class ImageStorage implements IDisposable {
|
|||||||
this._terminal._core._inputHandler._dirtyRowTracker.markDirty(buffer.y);
|
this._terminal._core._inputHandler._dirtyRowTracker.markDirty(buffer.y);
|
||||||
|
|
||||||
// cursor positioning modes
|
// cursor positioning modes
|
||||||
if (this._opts.sixelScrolling) {
|
if (scrolling) {
|
||||||
buffer.x = offset;
|
buffer.x = offset;
|
||||||
} else {
|
} else {
|
||||||
buffer.x = originX;
|
buffer.x = originX;
|
||||||
@@ -339,11 +330,14 @@ export class ImageStorage implements IDisposable {
|
|||||||
actualCellSize: { ...cellSize }, // clone needed, since later modified
|
actualCellSize: { ...cellSize }, // clone needed, since later modified
|
||||||
marker: endMarker || undefined,
|
marker: endMarker || undefined,
|
||||||
tileCount,
|
tileCount,
|
||||||
bufferType: this._terminal.buffer.active.type
|
bufferType: this._terminal.buffer.active.type,
|
||||||
|
layer,
|
||||||
|
zIndex
|
||||||
};
|
};
|
||||||
|
|
||||||
// finally add the image
|
// finally add the image
|
||||||
this._images.set(imageId, imgSpec);
|
this._images.set(imageId, imgSpec);
|
||||||
|
this.onImageAdded?.();
|
||||||
return imageId;
|
return imageId;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -354,16 +348,30 @@ export class ImageStorage implements IDisposable {
|
|||||||
*/
|
*/
|
||||||
// TODO: Should we move this to the ImageRenderer?
|
// TODO: Should we move this to the ImageRenderer?
|
||||||
public render(range: { start: number, end: number }): void {
|
public render(range: { start: number, end: number }): void {
|
||||||
// setup image canvas in case we have none yet, but have images in store
|
// Determine which layers have images
|
||||||
if (!this._renderer.canvas && this._images.size) {
|
let hasTopImages = false;
|
||||||
this._renderer.insertLayerToDom();
|
let hasBottomImages = false;
|
||||||
// safety measure - in case we cannot spawn a canvas at all, just exit
|
for (const spec of this._images.values()) {
|
||||||
if (!this._renderer.canvas) {
|
if (spec.layer === 'bottom') {
|
||||||
return;
|
hasBottomImages = true;
|
||||||
|
} else {
|
||||||
|
hasTopImages = true;
|
||||||
}
|
}
|
||||||
|
if (hasTopImages && hasBottomImages) break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Lazily insert layers that are needed
|
||||||
|
if (hasTopImages && !this._renderer.hasLayer('top')) {
|
||||||
|
this._renderer.insertLayerToDom('top');
|
||||||
|
if (!this._renderer.hasLayer('top')) return;
|
||||||
|
}
|
||||||
|
if (hasBottomImages && !this._renderer.hasLayer('bottom')) {
|
||||||
|
this._renderer.insertLayerToDom('bottom');
|
||||||
|
}
|
||||||
|
|
||||||
// rescale if needed
|
// rescale if needed
|
||||||
this._renderer.rescaleCanvas();
|
this._renderer.rescaleCanvas();
|
||||||
|
|
||||||
// exit early if we dont have any images to test for
|
// exit early if we dont have any images to test for
|
||||||
if (!this._images.size) {
|
if (!this._images.size) {
|
||||||
if (!this._fullyCleared) {
|
if (!this._fullyCleared) {
|
||||||
@@ -371,12 +379,25 @@ export class ImageStorage implements IDisposable {
|
|||||||
this._fullyCleared = true;
|
this._fullyCleared = true;
|
||||||
this._needsFullClear = false;
|
this._needsFullClear = false;
|
||||||
}
|
}
|
||||||
if (this._renderer.canvas) {
|
if (this._renderer.hasLayer('top')) {
|
||||||
this._renderer.removeLayerFromDom();
|
this._renderer.removeLayerFromDom('top');
|
||||||
|
}
|
||||||
|
if (this._renderer.hasLayer('bottom')) {
|
||||||
|
this._renderer.removeLayerFromDom('bottom');
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Remove layers no longer needed
|
||||||
|
if (!hasTopImages && this._renderer.hasLayer('top')) {
|
||||||
|
this._renderer.clearAll('top');
|
||||||
|
this._renderer.removeLayerFromDom('top');
|
||||||
|
}
|
||||||
|
if (!hasBottomImages && this._renderer.hasLayer('bottom')) {
|
||||||
|
this._renderer.clearAll('bottom');
|
||||||
|
this._renderer.removeLayerFromDom('bottom');
|
||||||
|
}
|
||||||
|
|
||||||
// buffer switches force a full clear
|
// buffer switches force a full clear
|
||||||
if (this._needsFullClear) {
|
if (this._needsFullClear) {
|
||||||
this._renderer.clearAll();
|
this._renderer.clearAll();
|
||||||
@@ -391,50 +412,77 @@ export class ImageStorage implements IDisposable {
|
|||||||
// clear drawing area
|
// clear drawing area
|
||||||
this._renderer.clearLines(start, end);
|
this._renderer.clearLines(start, end);
|
||||||
|
|
||||||
// walk all cells in viewport and draw tiles found
|
// Collect draw calls so we can sort by z-index (lower z drawn first).
|
||||||
|
const drawCalls: { imgSpec: IImageSpec, tileId: number, col: number, row: number, count: number }[] = [];
|
||||||
|
const placeholderCalls: { col: number, row: number, count: number }[] = [];
|
||||||
|
|
||||||
|
// walk all cells in viewport and collect tiles found
|
||||||
|
// Note: We check _extendedAttrs directly (not just HAS_EXTENDED flag)
|
||||||
|
// because text writes clear the BG flag but leave image tile data intact.
|
||||||
|
// This lets top-layer images survive text overwrites (kitty C=1 behavior).
|
||||||
for (let row = start; row <= end; ++row) {
|
for (let row = start; row <= end; ++row) {
|
||||||
const line = buffer.lines.get(row + buffer.ydisp) as IBufferLineExt;
|
const line = buffer.lines.get(row + buffer.ydisp) as IBufferLineExt;
|
||||||
if (!line) return;
|
if (!line) return;
|
||||||
for (let col = 0; col < cols; ++col) {
|
for (let col = 0; col < cols; ++col) {
|
||||||
|
let e: IExtendedAttrsImage;
|
||||||
if (line.getBg(col) & BgFlags.HAS_EXTENDED) {
|
if (line.getBg(col) & BgFlags.HAS_EXTENDED) {
|
||||||
let e: IExtendedAttrsImage = line._extendedAttrs[col] ?? EMPTY_ATTRS;
|
e = line._extendedAttrs[col] ?? EMPTY_ATTRS;
|
||||||
const imageId = e.imageId;
|
} else {
|
||||||
if (imageId === undefined || imageId === -1) {
|
const maybeImg = line._extendedAttrs[col] as IExtendedAttrsImage | undefined;
|
||||||
|
if (!maybeImg || maybeImg.imageId === undefined || maybeImg.imageId === -1) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const imgSpec = this._images.get(imageId);
|
e = maybeImg;
|
||||||
if (e.tileId !== -1) {
|
}
|
||||||
const startTile = e.tileId;
|
const imageId = e.imageId;
|
||||||
const startCol = col;
|
if (imageId === undefined || imageId === -1) {
|
||||||
let count = 1;
|
continue;
|
||||||
/**
|
}
|
||||||
* merge tiles to the right into a single draw call, if:
|
const imgSpec = this._images.get(imageId);
|
||||||
* - not at end of line
|
if (e.tileId !== -1) {
|
||||||
* - cell has same image id
|
const startTile = e.tileId;
|
||||||
* - cell has consecutive tile id
|
const startCol = col;
|
||||||
*/
|
let count = 1;
|
||||||
while (
|
/**
|
||||||
++col < cols
|
* merge tiles to the right into a single draw call, if:
|
||||||
&& (line.getBg(col) & BgFlags.HAS_EXTENDED)
|
* - not at end of line
|
||||||
&& (e = line._extendedAttrs[col] ?? EMPTY_ATTRS)
|
* - cell has same image id
|
||||||
&& (e.imageId === imageId)
|
* - cell has consecutive tile id
|
||||||
&& (e.tileId === startTile + count)
|
* Also check _extendedAttrs directly for cells where text cleared HAS_EXTENDED.
|
||||||
) {
|
*/
|
||||||
count++;
|
while (++col < cols) {
|
||||||
|
const nextE = line._extendedAttrs[col] as IExtendedAttrsImage | undefined;
|
||||||
|
if (!nextE || nextE.imageId !== imageId || nextE.tileId !== startTile + count) {
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
col--;
|
e = nextE;
|
||||||
if (imgSpec) {
|
count++;
|
||||||
if (imgSpec.actual) {
|
|
||||||
this._renderer.draw(imgSpec, startTile, startCol, row, count);
|
|
||||||
}
|
|
||||||
} else if (this._opts.showPlaceholder) {
|
|
||||||
this._renderer.drawPlaceholder(startCol, row, count);
|
|
||||||
}
|
|
||||||
this._fullyCleared = false;
|
|
||||||
}
|
}
|
||||||
|
col--;
|
||||||
|
if (imgSpec) {
|
||||||
|
if (imgSpec.actual) {
|
||||||
|
drawCalls.push({ imgSpec, tileId: startTile, col: startCol, row, count });
|
||||||
|
}
|
||||||
|
} else if (this._opts.showPlaceholder) {
|
||||||
|
placeholderCalls.push({ col: startCol, row, count });
|
||||||
|
}
|
||||||
|
this._fullyCleared = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Sort by z-index so lower z draws first (higher z renders on top)
|
||||||
|
drawCalls.sort((a, b) => a.imgSpec.zIndex - b.imgSpec.zIndex);
|
||||||
|
|
||||||
|
// Draw placeholders first (lowest priority)
|
||||||
|
for (const call of placeholderCalls) {
|
||||||
|
this._renderer.drawPlaceholder(call.col, call.row, call.count);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Draw images in z-index order
|
||||||
|
for (const call of drawCalls) {
|
||||||
|
this._renderer.draw(call.imgSpec, call.tileId, call.col, call.row, call.count);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public viewportResize(metrics: { cols: number, rows: number }): void {
|
public viewportResize(metrics: { cols: number, rows: number }): void {
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
* @license MIT
|
* @license MIT
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { ImageStorage } from './ImageStorage';
|
import { SixelImageStorage } from './SixelImageStorage';
|
||||||
import { IDcsHandler, IParams, IImageAddonOptions, ITerminalExt, AttributeData, IResetHandler, ReadonlyColorSet } from './Types';
|
import { IDcsHandler, IParams, IImageAddonOptions, ITerminalExt, AttributeData, IResetHandler, ReadonlyColorSet } from './Types';
|
||||||
import { toRGBA8888, BIG_ENDIAN, PALETTE_ANSI_256, PALETTE_VT340_COLOR } from 'sixel/lib/Colors';
|
import { toRGBA8888, BIG_ENDIAN, PALETTE_ANSI_256, PALETTE_VT340_COLOR } from 'sixel/lib/Colors';
|
||||||
import { RGBA8888 } from 'sixel/lib/Types';
|
import { RGBA8888 } from 'sixel/lib/Types';
|
||||||
@@ -26,7 +26,7 @@ export class SixelHandler implements IDcsHandler, IResetHandler {
|
|||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly _opts: IImageAddonOptions,
|
private readonly _opts: IImageAddonOptions,
|
||||||
private readonly _storage: ImageStorage,
|
private readonly _storage: SixelImageStorage,
|
||||||
private readonly _coreTerminal: ITerminalExt
|
private readonly _coreTerminal: ITerminalExt
|
||||||
) {
|
) {
|
||||||
DecoderAsync({
|
DecoderAsync({
|
||||||
@@ -91,7 +91,7 @@ export class SixelHandler implements IDcsHandler, IResetHandler {
|
|||||||
const height = this._dec.height;
|
const height = this._dec.height;
|
||||||
|
|
||||||
// partial fix for https://github.com/jerch/xterm-addon-image/issues/37
|
// partial fix for https://github.com/jerch/xterm-addon-image/issues/37
|
||||||
if (!width || ! height) {
|
if (!width || !height) {
|
||||||
if (height) {
|
if (height) {
|
||||||
this._storage.advanceCursor(height);
|
this._storage.advanceCursor(height);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2020 The xterm.js authors. All rights reserved.
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { ImageStorage, CELL_SIZE_DEFAULT } from './ImageStorage';
|
||||||
|
import { IImageAddonOptions, ITerminalExt } from './Types';
|
||||||
|
import { ImageRenderer } from './ImageRenderer';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sixel-specific image storage controller.
|
||||||
|
*
|
||||||
|
* Wraps the shared ImageStorage with sixel protocol semantics:
|
||||||
|
* - Cursor behavior governed by DECSET 80 (sixelScrolling option)
|
||||||
|
* - advanceCursor for empty sixels carrying only height
|
||||||
|
*/
|
||||||
|
export class SixelImageStorage {
|
||||||
|
constructor(
|
||||||
|
private readonly _storage: ImageStorage,
|
||||||
|
private readonly _opts: IImageAddonOptions,
|
||||||
|
private readonly _renderer: ImageRenderer,
|
||||||
|
private readonly _terminal: ITerminalExt
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add a sixel image to storage.
|
||||||
|
* Cursor behavior depends on the sixelScrolling option (DECSET 80).
|
||||||
|
*/
|
||||||
|
public addImage(img: HTMLCanvasElement | ImageBitmap): void {
|
||||||
|
this._storage.addImage(img, this._opts.sixelScrolling);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Only advance text cursor.
|
||||||
|
* This is an edge case from empty sixels carrying only a height but no pixels.
|
||||||
|
* Partially fixes https://github.com/jerch/xterm-addon-image/issues/37.
|
||||||
|
*/
|
||||||
|
public advanceCursor(height: number): void {
|
||||||
|
if (this._opts.sixelScrolling) {
|
||||||
|
let cellSize = this._renderer.cellSize;
|
||||||
|
if (cellSize.width === -1 || cellSize.height === -1) {
|
||||||
|
cellSize = CELL_SIZE_DEFAULT;
|
||||||
|
}
|
||||||
|
const rows = Math.ceil(height / cellSize.height);
|
||||||
|
for (let i = 1; i < rows; ++i) {
|
||||||
|
this._terminal._core._inputHandler.lineFeed();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -99,6 +99,8 @@ export interface ICellSize {
|
|||||||
height: number;
|
height: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type ImageLayer = 'top' | 'bottom';
|
||||||
|
|
||||||
export interface IImageSpec {
|
export interface IImageSpec {
|
||||||
orig: HTMLCanvasElement | ImageBitmap | undefined;
|
orig: HTMLCanvasElement | ImageBitmap | undefined;
|
||||||
origCellSize: ICellSize;
|
origCellSize: ICellSize;
|
||||||
@@ -107,4 +109,6 @@ export interface IImageSpec {
|
|||||||
marker: IMarker | undefined;
|
marker: IMarker | undefined;
|
||||||
tileCount: number;
|
tileCount: number;
|
||||||
bufferType: 'alternate' | 'normal';
|
bufferType: 'alternate' | 'normal';
|
||||||
|
layer: ImageLayer;
|
||||||
|
zIndex: number;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
/**
|
/**
|
||||||
* Copyright (c) 2025 The xterm.js authors. All rights reserved.
|
* Copyright (c) 2026 The xterm.js authors. All rights reserved.
|
||||||
* @license MIT
|
* @license MIT
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { IApcHandler, IImageAddonOptions, IResetHandler, ITerminalExt } from '../Types';
|
import { IDisposable } from '@xterm/xterm';
|
||||||
|
import { IApcHandler, IImageAddonOptions, IResetHandler, ITerminalExt, ImageLayer } from '../Types';
|
||||||
import { ImageRenderer } from '../ImageRenderer';
|
import { ImageRenderer } from '../ImageRenderer';
|
||||||
import { ImageStorage, CELL_SIZE_DEFAULT } from '../ImageStorage';
|
import { CELL_SIZE_DEFAULT } from '../ImageStorage';
|
||||||
|
import { KittyImageStorage } from './KittyImageStorage';
|
||||||
import Base64Decoder, { type DecodeStatus } from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';
|
import Base64Decoder, { type DecodeStatus } from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';
|
||||||
import {
|
import {
|
||||||
KittyAction,
|
KittyAction,
|
||||||
@@ -14,29 +16,26 @@ import {
|
|||||||
IKittyCommand,
|
IKittyCommand,
|
||||||
IPendingTransmission,
|
IPendingTransmission,
|
||||||
IKittyImageData,
|
IKittyImageData,
|
||||||
BYTES_PER_PIXEL_RGB,
|
KittyPixelConstants,
|
||||||
BYTES_PER_PIXEL_RGBA,
|
|
||||||
ALPHA_OPAQUE,
|
|
||||||
parseKittyCommand
|
parseKittyCommand
|
||||||
} from './KittyGraphicsTypes';
|
} from './KittyGraphicsTypes';
|
||||||
|
|
||||||
// Memory limit for base64 decoder (4MB, same as IIPHandler)
|
const enum Constants {
|
||||||
const DECODER_KEEP_DATA = 4194304;
|
// Memory limit for base64 decoder (4MB, same as IIPHandler)
|
||||||
const DECODER_INITIAL_DATA = 4194304; // 4MB
|
DECODER_KEEP_DATA = 4194304,
|
||||||
|
DECODER_INITIAL_DATA = 4194304, // 4MB
|
||||||
|
// Local mirror of const enum (esbuild can't inline const enums from external packages)
|
||||||
|
DECODER_OK = 0,
|
||||||
|
// Maximum control data size
|
||||||
|
MAX_CONTROL_DATA_SIZE = 512,
|
||||||
|
// Semicolon codepoint
|
||||||
|
SEMICOLON = 0x3B
|
||||||
|
}
|
||||||
|
|
||||||
// Local mirror of const enum (esbuild can't inline const enums from external packages)
|
const DECODER_OK = Constants.DECODER_OK as unknown as DecodeStatus.OK;
|
||||||
const DECODER_OK: DecodeStatus.OK = 0;
|
|
||||||
|
|
||||||
// Maximum control data size
|
// Kitty graphics protocol handler with streaming base64 decoding.
|
||||||
const MAX_CONTROL_DATA_SIZE = 512;
|
export class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDisposable {
|
||||||
|
|
||||||
// Semicolon codepoint
|
|
||||||
const SEMICOLON = 0x3B;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Kitty graphics protocol handler with streaming base64 decoding.
|
|
||||||
*/
|
|
||||||
export class KittyGraphicsHandler implements IApcHandler, IResetHandler {
|
|
||||||
private _aborted = false;
|
private _aborted = false;
|
||||||
private _decodeError = false;
|
private _decodeError = false;
|
||||||
|
|
||||||
@@ -46,57 +45,66 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler {
|
|||||||
|
|
||||||
// Streaming related states
|
// Streaming related states
|
||||||
|
|
||||||
/** True while receiving control data (before semicolon). */
|
// True while receiving control data (before semicolon).
|
||||||
private _inControlData = true;
|
private _inControlData = true;
|
||||||
|
|
||||||
/** Buffer for control data. */
|
// Buffer for control data.
|
||||||
private _controlData = new Uint32Array(MAX_CONTROL_DATA_SIZE);
|
private _controlData = new Uint32Array(Constants.MAX_CONTROL_DATA_SIZE);
|
||||||
private _controlLength = 0;
|
private _controlLength = 0;
|
||||||
|
|
||||||
/** Pre-calculated encoded size limit */
|
// Pre-calculated encoded size limit
|
||||||
private _encodedSizeLimit = 0;
|
private _encodedSizeLimit = 0;
|
||||||
private _totalEncodedSize = 0;
|
private _totalEncodedSize = 0;
|
||||||
|
|
||||||
/** Parsed command. These are the control data before semicolon. */
|
// Parsed command. These are the control data before semicolon.
|
||||||
private _parsedCommand: IKittyCommand | null = null;
|
private _parsedCommand: IKittyCommand | null = null;
|
||||||
|
|
||||||
// Storage related states
|
// Storage related states
|
||||||
|
|
||||||
private _pendingTransmissions: Map<number, IPendingTransmission> = new Map();
|
private _pendingTransmissions: Map<number, IPendingTransmission> = new Map();
|
||||||
private _nextImageId = 1;
|
// Tracks the pending key of the most recently started chunked upload.
|
||||||
/** Maps Kitty protocol image ID → ImageStorage internal ID for deletion/lookup. */
|
// Per spec, subsequent chunks only need m= (and optionally q=), without i=.
|
||||||
private _kittyIdToStorageId: Map<number, number> = new Map();
|
// When a chunk arrives with no i=, this key is used to find the pending upload.
|
||||||
// TODO: Eliminate double storage — raw image data lives here (as Blob) AND rendered
|
private _lastPendingKey: number | undefined;
|
||||||
// ImageBitmaps live in ImageStorage. Currently we only use ImageStorage.addImage(bitmap)
|
|
||||||
// for tiling + cursor movement + marker-based eviction.
|
|
||||||
//
|
|
||||||
|
|
||||||
// See: https://github.com/xtermjs/xterm.js/pull/5619#issuecomment-3853678815
|
|
||||||
private _images: Map<number, IKittyImageData> = new Map();
|
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly _opts: IImageAddonOptions,
|
private readonly _opts: IImageAddonOptions,
|
||||||
private readonly _renderer: ImageRenderer,
|
private readonly _renderer: ImageRenderer,
|
||||||
private readonly _storage: ImageStorage,
|
private readonly _kittyStorage: KittyImageStorage,
|
||||||
private readonly _coreTerminal: ITerminalExt
|
private readonly _coreTerminal: ITerminalExt
|
||||||
) {
|
) {
|
||||||
// Convert decoded size limit -> max encoded bytes.
|
// Convert decoded size limit -> max encoded bytes.
|
||||||
this._maxEncodedBytes = Math.ceil(this._opts.kittySizeLimit * 4 / 3);
|
this._maxEncodedBytes = Math.ceil(this._opts.kittySizeLimit * 4 / 3);
|
||||||
// ensure we preallocate more than configured limit while using 4mb initial size.
|
// ensure we preallocate more than configured limit while using 4mb initial size.
|
||||||
this._initialEncodedBytes = Math.min(DECODER_INITIAL_DATA, this._maxEncodedBytes);
|
this._initialEncodedBytes = Math.min(Constants.DECODER_INITIAL_DATA, this._maxEncodedBytes);
|
||||||
}
|
}
|
||||||
|
|
||||||
public reset(): void {
|
public reset(): void {
|
||||||
for (const pending of this._pendingTransmissions.values()) {
|
this._cleanupAllPending();
|
||||||
pending.decoder.release();
|
|
||||||
}
|
|
||||||
this._pendingTransmissions.clear();
|
|
||||||
if (this._activeDecoder) {
|
if (this._activeDecoder) {
|
||||||
this._activeDecoder.release();
|
this._activeDecoder.release();
|
||||||
this._activeDecoder = null;
|
this._activeDecoder = null;
|
||||||
}
|
}
|
||||||
this._images.clear();
|
this._kittyStorage.reset();
|
||||||
this._kittyIdToStorageId.clear();
|
}
|
||||||
|
|
||||||
|
public dispose(): void {
|
||||||
|
this.reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
private _removePendingEntry(key: number): void {
|
||||||
|
this._pendingTransmissions.delete(key);
|
||||||
|
if (this._lastPendingKey === key) {
|
||||||
|
this._lastPendingKey = undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private _cleanupAllPending(): void {
|
||||||
|
for (const pending of this._pendingTransmissions.values()) {
|
||||||
|
pending.decoder.release();
|
||||||
|
}
|
||||||
|
this._pendingTransmissions.clear();
|
||||||
|
this._lastPendingKey = undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
public start(): void {
|
public start(): void {
|
||||||
@@ -120,7 +128,7 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler {
|
|||||||
// Scan for semicolon
|
// Scan for semicolon
|
||||||
let controlEnd = end;
|
let controlEnd = end;
|
||||||
for (let i = start; i < end; i++) {
|
for (let i = start; i < end; i++) {
|
||||||
if (data[i] === SEMICOLON) {
|
if (data[i] === Constants.SEMICOLON) {
|
||||||
this._inControlData = false;
|
this._inControlData = false;
|
||||||
controlEnd = i;
|
controlEnd = i;
|
||||||
break;
|
break;
|
||||||
@@ -129,7 +137,7 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler {
|
|||||||
|
|
||||||
// Copy control data
|
// Copy control data
|
||||||
const copyLength = controlEnd - start;
|
const copyLength = controlEnd - start;
|
||||||
if (this._controlLength + copyLength > MAX_CONTROL_DATA_SIZE) {
|
if (this._controlLength + copyLength > Constants.MAX_CONTROL_DATA_SIZE) {
|
||||||
this._aborted = true;
|
this._aborted = true;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -161,15 +169,14 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Stream payload bytes into the base64 decoder.
|
||||||
* Stream payload bytes into the base64 decoder.
|
|
||||||
*/
|
|
||||||
private _streamPayload(data: Uint32Array, start: number, end: number): void {
|
private _streamPayload(data: Uint32Array, start: number, end: number): void {
|
||||||
if (this._aborted) return;
|
if (this._aborted) return;
|
||||||
|
|
||||||
// Check size limit (compare encoded bytes against pre-calculated limit)
|
// Check size limit (compare encoded bytes against pre-calculated limit)
|
||||||
// Include cumulative size from pending transmission for multi-chunk images
|
// Include cumulative size from pending transmission for multi-chunk images.
|
||||||
const pendingKey = this._parsedCommand?.id ?? 0;
|
// Per spec, subsequent chunks may omit i=, so fall back to _lastPendingKey.
|
||||||
|
const pendingKey = this._parsedCommand?.id ?? this._lastPendingKey ?? 0;
|
||||||
const pending = this._pendingTransmissions.get(pendingKey);
|
const pending = this._pendingTransmissions.get(pendingKey);
|
||||||
const previousEncodedSize = pending?.totalEncodedSize ?? 0;
|
const previousEncodedSize = pending?.totalEncodedSize ?? 0;
|
||||||
this._totalEncodedSize += end - start;
|
this._totalEncodedSize += end - start;
|
||||||
@@ -181,7 +188,7 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler {
|
|||||||
}
|
}
|
||||||
this._activeDecoder = null;
|
this._activeDecoder = null;
|
||||||
if (pending) {
|
if (pending) {
|
||||||
this._pendingTransmissions.delete(pendingKey);
|
this._removePendingEntry(pendingKey);
|
||||||
}
|
}
|
||||||
this._aborted = true;
|
this._aborted = true;
|
||||||
return;
|
return;
|
||||||
@@ -193,7 +200,7 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler {
|
|||||||
this._activeDecoder = pending.decoder;
|
this._activeDecoder = pending.decoder;
|
||||||
}
|
}
|
||||||
if (!this._activeDecoder) {
|
if (!this._activeDecoder) {
|
||||||
this._activeDecoder = new Base64Decoder(DECODER_KEEP_DATA, this._maxEncodedBytes, this._initialEncodedBytes);
|
this._activeDecoder = new Base64Decoder(Constants.DECODER_KEEP_DATA, this._maxEncodedBytes, this._initialEncodedBytes);
|
||||||
this._activeDecoder.init();
|
this._activeDecoder.init();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -202,7 +209,7 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler {
|
|||||||
this._activeDecoder = null;
|
this._activeDecoder = null;
|
||||||
this._decodeError = true;
|
this._decodeError = true;
|
||||||
if (pending) {
|
if (pending) {
|
||||||
this._pendingTransmissions.delete(pendingKey);
|
this._removePendingEntry(pendingKey);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -229,7 +236,8 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler {
|
|||||||
return this._handleDelete(cmd);
|
return this._handleDelete(cmd);
|
||||||
}
|
}
|
||||||
|
|
||||||
const pendingKey = cmd.id ?? 0;
|
// Per spec, subsequent chunks may omit i=, so fall back to _lastPendingKey.
|
||||||
|
const pendingKey = cmd.id ?? this._lastPendingKey ?? 0;
|
||||||
const isMoreComing = cmd.more === 1;
|
const isMoreComing = cmd.more === 1;
|
||||||
const pending = this._pendingTransmissions.get(pendingKey);
|
const pending = this._pendingTransmissions.get(pendingKey);
|
||||||
|
|
||||||
@@ -246,11 +254,17 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler {
|
|||||||
decodeError: this._decodeError
|
decodeError: this._decodeError
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
this._lastPendingKey = pendingKey;
|
||||||
this._activeDecoder = null;
|
this._activeDecoder = null;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Final chunk received — clear the last pending key
|
||||||
|
if (pending) {
|
||||||
|
this._lastPendingKey = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
let decodeError = this._decodeError;
|
let decodeError = this._decodeError;
|
||||||
let finalCmd = cmd;
|
let finalCmd = cmd;
|
||||||
let decoder = this._activeDecoder;
|
let decoder = this._activeDecoder;
|
||||||
@@ -308,7 +322,16 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler {
|
|||||||
case KittyAction.QUERY:
|
case KittyAction.QUERY:
|
||||||
this._sendResponse(cmd.id ?? 0, 'OK', cmd.quiet ?? 0);
|
this._sendResponse(cmd.id ?? 0, 'OK', cmd.quiet ?? 0);
|
||||||
return true;
|
return true;
|
||||||
|
case KittyAction.PLACEMENT:
|
||||||
|
return this._handlePlacement(cmd);
|
||||||
default:
|
default:
|
||||||
|
// TODO: Implement remaining actions when needed:
|
||||||
|
// - a=f (frame): animation frame operations
|
||||||
|
// - a=a (animation): animation control
|
||||||
|
// - a=c (compose): compose images
|
||||||
|
if (cmd.id !== undefined) {
|
||||||
|
this._sendResponse(cmd.id, 'EINVAL:unsupported action', cmd.quiet ?? 0);
|
||||||
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -319,8 +342,14 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler {
|
|||||||
switch (action) {
|
switch (action) {
|
||||||
case KittyAction.TRANSMIT: {
|
case KittyAction.TRANSMIT: {
|
||||||
const result = this._handleTransmit(cmd, bytes, decodeError);
|
const result = this._handleTransmit(cmd, bytes, decodeError);
|
||||||
if (cmd.id !== undefined && !decodeError && bytes.length > 0) {
|
// Only send response when _handleTransmit didn't already respond
|
||||||
this._sendResponse(cmd.id, 'OK', cmd.quiet ?? 0);
|
// (it handles unsupported transmission medium responses internally)
|
||||||
|
if ((cmd.transmission ?? 'd') === 'd' && cmd.id !== undefined) {
|
||||||
|
if (decodeError) {
|
||||||
|
this._sendResponse(cmd.id, 'EINVAL:invalid base64 data', cmd.quiet ?? 0);
|
||||||
|
} else if (bytes.length > 0) {
|
||||||
|
this._sendResponse(cmd.id, 'OK', cmd.quiet ?? 0);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
@@ -328,59 +357,90 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler {
|
|||||||
return this._handleTransmitDisplay(cmd, bytes, decodeError);
|
return this._handleTransmitDisplay(cmd, bytes, decodeError);
|
||||||
case KittyAction.QUERY:
|
case KittyAction.QUERY:
|
||||||
return this._handleQuery(cmd, bytes, decodeError);
|
return this._handleQuery(cmd, bytes, decodeError);
|
||||||
|
case KittyAction.PLACEMENT:
|
||||||
|
// a=p ignores any payload — image data was already transmitted
|
||||||
|
return this._handlePlacement(cmd);
|
||||||
default:
|
default:
|
||||||
|
// TODO: Implement remaining actions when needed:
|
||||||
|
// - a=f (frame): animation frame operations
|
||||||
|
// - a=a (animation): animation control
|
||||||
|
// - a=c (compose): compose images
|
||||||
|
if (cmd.id !== undefined) {
|
||||||
|
this._sendResponse(cmd.id, 'EINVAL:unsupported action', cmd.quiet ?? 0);
|
||||||
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private _handlePlacement(cmd: IKittyCommand): boolean | Promise<boolean> {
|
||||||
|
if (cmd.id === undefined) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const id = cmd.id;
|
||||||
|
const image = this._kittyStorage.getImage(id);
|
||||||
|
if (!image) {
|
||||||
|
this._sendResponse(id, 'ENOENT:image not found', cmd.quiet ?? 0, cmd.placementId);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const result = this._displayImage(image, cmd);
|
||||||
|
return result.then(success => {
|
||||||
|
this._sendResponse(id, success ? 'OK' : 'EINVAL:image rendering failed', cmd.quiet ?? 0, cmd.placementId);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private _handleTransmit(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean {
|
private _handleTransmit(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean {
|
||||||
// TODO: Support file-based transmission modes (t=f, t=t, t=s)
|
// TODO: Support file-based transmission modes (t=f, t=t, t=s)
|
||||||
// Currently only supports direct transmission (t=d, the default).
|
// Currently only supports direct transmission (t=d, the default).
|
||||||
// - t=f (file): Payload is base64-encoded file path. Terminal reads image from that path.
|
// - t=f (file): Payload is base64-encoded file path. Terminal reads image from that path.
|
||||||
// - t=t (temp file): Payload is base64-encoded path in temp directory. Terminal reads, deletes.
|
// - t=t (temp file): Payload is base64-encoded path in temp directory. Terminal reads, deletes.
|
||||||
// - t=s Payload is base64-encoded POSIX shm name. Terminal reads from shared memory.
|
// - t=s: Payload is base64-encoded POSIX shm name. Terminal reads from shared memory.
|
||||||
// These modes require filesystem/IPC access not available in browsers. For Node.js/Electron:
|
// These modes require filesystem/IPC access not available in browsers. For Node.js/Electron:
|
||||||
// 1. Check cmd.transmission (t key) before treating bytes as image data
|
// 1. Check cmd.transmission (t key) before treating bytes as image data
|
||||||
// 2. For t=f/t/s: decode bytes as UTF-8 string (the path/name), then read file contents
|
// 2. For t=f/t/s: decode bytes as UTF-8 string (the path/name), then read file contents
|
||||||
// 3. For t=d: treat bytes as image data (current behavior)
|
// 3. For t=d: treat bytes as image data (current behavior)
|
||||||
|
// When implementing, also update _handleQuery to accept these transmission mediums.
|
||||||
|
const transmission = cmd.transmission ?? 'd';
|
||||||
|
if (transmission !== 'd') {
|
||||||
|
if (cmd.id !== undefined) {
|
||||||
|
this._sendResponse(cmd.id, 'EINVAL:unsupported transmission medium', cmd.quiet ?? 0);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
if (decodeError || bytes.length === 0) return true;
|
if (decodeError || bytes.length === 0) return true;
|
||||||
|
|
||||||
const id = cmd.id ?? this._nextImageId++;
|
this._kittyStorage.storeImage(cmd.id, {
|
||||||
const image: IKittyImageData = {
|
|
||||||
id,
|
|
||||||
data: new Blob([bytes as BlobPart]),
|
data: new Blob([bytes as BlobPart]),
|
||||||
width: cmd.width ?? 0,
|
width: cmd.width ?? 0,
|
||||||
height: cmd.height ?? 0,
|
height: cmd.height ?? 0,
|
||||||
format: (cmd.format ?? KittyFormat.RGBA) as 24 | 32 | 100,
|
format: (cmd.format ?? KittyFormat.RGBA) as 24 | 32 | 100,
|
||||||
compression: cmd.compression ?? ''
|
compression: cmd.compression ?? ''
|
||||||
};
|
});
|
||||||
this._images.set(id, image);
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private _handleTransmitDisplay(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean | Promise<boolean> {
|
private _handleTransmitDisplay(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean | Promise<boolean> {
|
||||||
if (decodeError) return true;
|
if (decodeError) {
|
||||||
|
if (cmd.id !== undefined) {
|
||||||
const pendingKey = cmd.id ?? 0;
|
this._sendResponse(cmd.id, 'EINVAL:invalid base64 data', cmd.quiet ?? 0);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
this._handleTransmit(cmd, bytes, decodeError);
|
this._handleTransmit(cmd, bytes, decodeError);
|
||||||
|
|
||||||
// If still accumulating chunks, don't display yet
|
const id = cmd.id ?? this._kittyStorage.lastImageId;
|
||||||
if (this._pendingTransmissions.has(pendingKey)) return true;
|
const image = this._kittyStorage.getImage(id);
|
||||||
|
|
||||||
// Display the completed image
|
|
||||||
const id = cmd.id ?? this._nextImageId - 1;
|
|
||||||
const image = this._images.get(id);
|
|
||||||
if (image) {
|
if (image) {
|
||||||
const result = this._displayImage(image, cmd);
|
const result = this._displayImage(image, cmd);
|
||||||
if (cmd.id !== undefined) {
|
if (cmd.id !== undefined) {
|
||||||
return (result as Promise<boolean>).then(r => {
|
return result.then(success => {
|
||||||
this._sendResponse(id, 'OK', cmd.quiet ?? 0);
|
this._sendResponse(id, success ? 'OK' : 'EINVAL:image rendering failed', cmd.quiet ?? 0);
|
||||||
return r;
|
return true;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return result;
|
return result.then(() => true);
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -389,6 +449,15 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler {
|
|||||||
const id = cmd.id ?? 0;
|
const id = cmd.id ?? 0;
|
||||||
const quiet = cmd.quiet ?? 0;
|
const quiet = cmd.quiet ?? 0;
|
||||||
|
|
||||||
|
// Per spec: reject unsupported transmission mediums (only t=d is supported atm)
|
||||||
|
// TODO: When filesystem support is added (Node.js/Electron), update this to accept
|
||||||
|
// t=f (file), t=t (temp file), and t=s (shared memory) and respond OK for queries.
|
||||||
|
const transmission = cmd.transmission ?? 'd';
|
||||||
|
if (transmission !== 'd') {
|
||||||
|
this._sendResponse(id, 'EINVAL:unsupported transmission medium', quiet);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
// Check decode error first (invalid base64)
|
// Check decode error first (invalid base64)
|
||||||
if (decodeError) {
|
if (decodeError) {
|
||||||
this._sendResponse(id, 'EINVAL:invalid base64 data', quiet);
|
this._sendResponse(id, 'EINVAL:invalid base64 data', quiet);
|
||||||
@@ -414,7 +483,7 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
const bytesPerPixel = format === KittyFormat.RGBA ? BYTES_PER_PIXEL_RGBA : BYTES_PER_PIXEL_RGB;
|
const bytesPerPixel = format === KittyFormat.RGBA ? KittyPixelConstants.BYTES_PER_PIXEL_RGBA : KittyPixelConstants.BYTES_PER_PIXEL_RGB;
|
||||||
const expectedBytes = width * height * bytesPerPixel;
|
const expectedBytes = width * height * bytesPerPixel;
|
||||||
|
|
||||||
if (bytes.length < expectedBytes) {
|
if (bytes.length < expectedBytes) {
|
||||||
@@ -428,110 +497,194 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private _handleDelete(cmd: IKittyCommand): boolean {
|
private _handleDelete(cmd: IKittyCommand): boolean {
|
||||||
const id = cmd.id;
|
// Per spec: default delete selector is 'a' (delete all visible placements)
|
||||||
|
const selector = cmd.deleteSelector ?? 'a';
|
||||||
|
|
||||||
if (id !== undefined) {
|
// TODO: Distinguish lowercase (delete placements only) from uppercase
|
||||||
// Abort in-flight chunked upload for this specific image
|
// (delete placements + free stored image data). Currently both variants
|
||||||
const pending = this._pendingTransmissions.get(id);
|
// free everything since we don't separate stored data from placements.
|
||||||
if (pending) {
|
switch (selector) {
|
||||||
pending.decoder.release();
|
case 'a':
|
||||||
this._pendingTransmissions.delete(id);
|
case 'A':
|
||||||
}
|
this._cleanupAllPending();
|
||||||
|
this._kittyStorage.deleteAll();
|
||||||
this._images.delete(id);
|
break;
|
||||||
const storageId = this._kittyIdToStorageId.get(id);
|
case 'i':
|
||||||
if (storageId !== undefined) {
|
case 'I':
|
||||||
this._storage.deleteImage(storageId);
|
// TODO: When placement id tracking is implemented (see TODO in
|
||||||
this._kittyIdToStorageId.delete(id);
|
// KittyImageStorage), d=i with p=<pid> should delete only that
|
||||||
}
|
// specific placement, while d=i without p should delete all
|
||||||
} else {
|
// placements for the image.
|
||||||
// Abort all in-flight chunked uploads
|
if (cmd.id !== undefined) {
|
||||||
for (const pending of this._pendingTransmissions.values()) {
|
const pending = this._pendingTransmissions.get(cmd.id);
|
||||||
pending.decoder.release();
|
if (pending) {
|
||||||
}
|
pending.decoder.release();
|
||||||
this._pendingTransmissions.clear();
|
}
|
||||||
|
this._removePendingEntry(cmd.id);
|
||||||
this._images.clear();
|
this._kittyStorage.deleteById(cmd.id);
|
||||||
for (const storageId of this._kittyIdToStorageId.values()) {
|
}
|
||||||
this._storage.deleteImage(storageId);
|
break;
|
||||||
}
|
default:
|
||||||
this._kittyIdToStorageId.clear();
|
// Unsupported selectors (c, n, p, q, r, x, y, z, f) — ignore for now
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private _sendResponse(id: number, message: string, quiet: number): void {
|
private _sendResponse(id: number, message: string, quiet: number, placementId?: number): void {
|
||||||
const isOk = message === 'OK';
|
const isOk = message === 'OK';
|
||||||
if (isOk && quiet === 1) return;
|
if (isOk && quiet >= 1) return;
|
||||||
if (!isOk && quiet === 2) return;
|
if (!isOk && quiet >= 2) return;
|
||||||
|
|
||||||
const response = `\x1b_Gi=${id};${message}\x1b\\`;
|
const pPart = placementId ? `,p=${placementId}` : '';
|
||||||
|
const response = `\x1b_Gi=${id}${pPart};${message}\x1b\\`;
|
||||||
this._coreTerminal._core.coreService.triggerDataEvent(response);
|
this._coreTerminal._core.coreService.triggerDataEvent(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Image display
|
// Image display
|
||||||
|
|
||||||
private _displayImage(image: IKittyImageData, cmd: IKittyCommand): boolean | Promise<boolean> {
|
private _displayImage(image: IKittyImageData, cmd: IKittyCommand): Promise<boolean> {
|
||||||
return this._decodeAndDisplay(image, cmd)
|
return this._decodeAndDisplay(image, cmd)
|
||||||
.then(() => true)
|
.then(() => true)
|
||||||
.catch(() => true);
|
.catch(() => false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async _decodeAndDisplay(image: IKittyImageData, cmd: IKittyCommand): Promise<void> {
|
private async _decodeAndDisplay(image: IKittyImageData, cmd: IKittyCommand): Promise<void> {
|
||||||
const bitmap = await this._createBitmap(image);
|
let bitmap: ImageBitmap | undefined = await this._createBitmap(image);
|
||||||
|
|
||||||
const cw = this._renderer.dimensions?.css.cell.width || CELL_SIZE_DEFAULT.width;
|
try {
|
||||||
const ch = this._renderer.dimensions?.css.cell.height || CELL_SIZE_DEFAULT.height;
|
const cropX = Math.max(0, cmd.x ?? 0);
|
||||||
|
const cropY = Math.max(0, cmd.y ?? 0);
|
||||||
|
const cropW = cmd.sourceWidth || (bitmap.width - cropX);
|
||||||
|
const cropH = cmd.sourceHeight || (bitmap.height - cropY);
|
||||||
|
|
||||||
// Per spec: c/r default to image's natural cell dimensions
|
const maxCropW = Math.max(0, bitmap.width - cropX);
|
||||||
const imgCols = cmd.columns ?? Math.ceil(bitmap.width / cw);
|
const maxCropH = Math.max(0, bitmap.height - cropY);
|
||||||
const imgRows = cmd.rows ?? Math.ceil(bitmap.height / ch);
|
const finalCropW = Math.max(0, Math.min(cropW, maxCropW));
|
||||||
|
const finalCropH = Math.max(0, Math.min(cropH, maxCropH));
|
||||||
|
|
||||||
let w = bitmap.width;
|
if (finalCropW === 0 || finalCropH === 0) {
|
||||||
let h = bitmap.height;
|
throw new Error('invalid source rectangle');
|
||||||
|
}
|
||||||
|
|
||||||
// Scale bitmap to fit placement rectangle when c/r are specified
|
if (cropX !== 0 || cropY !== 0 || finalCropW !== bitmap.width || finalCropH !== bitmap.height) {
|
||||||
if (cmd.columns !== undefined || cmd.rows !== undefined) {
|
const cropped = await createImageBitmap(bitmap, cropX, cropY, finalCropW, finalCropH);
|
||||||
w = Math.round(imgCols * cw);
|
bitmap.close();
|
||||||
h = Math.round(imgRows * ch);
|
bitmap = cropped;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (w * h > this._opts.pixelLimit) return;
|
const cw = this._renderer.dimensions?.css.cell.width || CELL_SIZE_DEFAULT.width;
|
||||||
|
const ch = this._renderer.dimensions?.css.cell.height || CELL_SIZE_DEFAULT.height;
|
||||||
|
|
||||||
// Save cursor position before addImage modifies it
|
// Per spec: c/r default to image's natural cell dimensions.
|
||||||
const buffer = this._coreTerminal._core.buffer;
|
// If only one of c/r is specified, compute the other from image aspect ratio.
|
||||||
const savedX = buffer.x;
|
let imgCols: number;
|
||||||
const savedY = buffer.y;
|
let imgRows: number;
|
||||||
const savedYbase = buffer.ybase;
|
if (cmd.columns !== undefined && cmd.rows !== undefined) {
|
||||||
|
imgCols = cmd.columns;
|
||||||
|
imgRows = cmd.rows;
|
||||||
|
} else if (cmd.columns !== undefined) {
|
||||||
|
imgCols = cmd.columns;
|
||||||
|
imgRows = Math.max(1, Math.ceil((bitmap.height / bitmap.width) * (imgCols * cw) / ch));
|
||||||
|
} else if (cmd.rows !== undefined) {
|
||||||
|
imgRows = cmd.rows;
|
||||||
|
imgCols = Math.max(1, Math.ceil((bitmap.width / bitmap.height) * (imgRows * ch) / cw));
|
||||||
|
} else {
|
||||||
|
imgCols = Math.ceil(bitmap.width / cw);
|
||||||
|
imgRows = Math.ceil(bitmap.height / ch);
|
||||||
|
}
|
||||||
|
|
||||||
let storageId: number;
|
let w = bitmap.width;
|
||||||
if (w !== bitmap.width || h !== bitmap.height) {
|
let h = bitmap.height;
|
||||||
const resized = await createImageBitmap(bitmap, { resizeWidth: w, resizeHeight: h });
|
|
||||||
storageId = this._storage.addImage(resized);
|
|
||||||
} else {
|
|
||||||
storageId = this._storage.addImage(bitmap);
|
|
||||||
}
|
|
||||||
this._kittyIdToStorageId.set(image.id, storageId);
|
|
||||||
|
|
||||||
// Kitty cursor movement
|
// Scale bitmap to fit placement rectangle when c/r are specified
|
||||||
// Per spec: cursor placed at first column after last image column,
|
if (cmd.columns !== undefined || cmd.rows !== undefined) {
|
||||||
// on the last row of the image. C=1 means don't move cursor.
|
w = Math.round(imgCols * cw);
|
||||||
if (cmd.cursorMovement === 1) {
|
h = Math.round(imgRows * ch);
|
||||||
// C=1: restore cursor to position before image was placed
|
}
|
||||||
const scrolled = buffer.ybase - savedYbase;
|
|
||||||
buffer.x = savedX;
|
if (w * h > this._opts.pixelLimit) {
|
||||||
// Can't restore cursor to scrollback?
|
throw new Error('image exceeds pixel limit');
|
||||||
buffer.y = Math.max(savedY - scrolled, 0);
|
}
|
||||||
} else {
|
|
||||||
// Default (C=0): advance cursor horizontally past the image
|
// Save cursor position before addImage modifies it
|
||||||
// addImage already positioned cursor on the last row via lineFeeds
|
const buffer = this._coreTerminal._core.buffer;
|
||||||
buffer.x = Math.min(savedX + imgCols, this._coreTerminal.cols);
|
const savedX = buffer.x;
|
||||||
|
const savedY = buffer.y;
|
||||||
|
const savedYbase = buffer.ybase;
|
||||||
|
|
||||||
|
// Determine layer based on z-index: negative = behind text, 0+ = on top.
|
||||||
|
// When z<0 we always use the bottom layer even without allowTransparency —
|
||||||
|
// the image will simply be hidden behind the opaque text background, which
|
||||||
|
// is the correct behavior (client asked for "behind text").
|
||||||
|
const wantsBottom = cmd.zIndex !== undefined && cmd.zIndex < 0;
|
||||||
|
const layer: ImageLayer = wantsBottom ? 'bottom' : 'top';
|
||||||
|
|
||||||
|
if (w !== bitmap.width || h !== bitmap.height) {
|
||||||
|
const scaled = await createImageBitmap(bitmap, { resizeWidth: w, resizeHeight: h });
|
||||||
|
bitmap.close();
|
||||||
|
bitmap = scaled;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Per spec: X/Y are pixel offsets within the first cell, so clamp to cell dimensions
|
||||||
|
const xOffset = Math.min(Math.max(0, cmd.xOffset ?? 0), cw - 1);
|
||||||
|
const yOffset = Math.min(Math.max(0, cmd.yOffset ?? 0), ch - 1);
|
||||||
|
if (xOffset !== 0 || yOffset !== 0) {
|
||||||
|
// Per spec: X/Y is not added to c/r area. When c/r are explicit, the
|
||||||
|
// total placement area remains c*cw × r*ch pixels and the offset image
|
||||||
|
// is clipped to fit. When c/r are unset, the padded canvas determines
|
||||||
|
// the natural cell dimensions.
|
||||||
|
const canvasW = (cmd.columns !== undefined) ? Math.round(imgCols * cw) : bitmap.width + xOffset;
|
||||||
|
const canvasH = (cmd.rows !== undefined) ? Math.round(imgRows * ch) : bitmap.height + yOffset;
|
||||||
|
const offsetCanvas = ImageRenderer.createCanvas(window.document, canvasW, canvasH);
|
||||||
|
const offsetCtx = offsetCanvas.getContext('2d');
|
||||||
|
if (!offsetCtx) {
|
||||||
|
throw new Error('Failed to create offset canvas context');
|
||||||
|
}
|
||||||
|
offsetCtx.drawImage(bitmap, xOffset, yOffset);
|
||||||
|
|
||||||
|
const offsetBitmap = await createImageBitmap(offsetCanvas);
|
||||||
|
offsetCanvas.width = offsetCanvas.height = 0;
|
||||||
|
bitmap.close();
|
||||||
|
bitmap = offsetBitmap;
|
||||||
|
w = bitmap.width;
|
||||||
|
h = bitmap.height;
|
||||||
|
if (w * h > this._opts.pixelLimit) {
|
||||||
|
throw new Error('image exceeds pixel limit');
|
||||||
|
}
|
||||||
|
if (cmd.columns === undefined) {
|
||||||
|
imgCols = Math.ceil(bitmap.width / cw);
|
||||||
|
}
|
||||||
|
if (cmd.rows === undefined) {
|
||||||
|
imgRows = Math.ceil(bitmap.height / ch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const zIndex = cmd.zIndex ?? 0;
|
||||||
|
this._kittyStorage.addImage(image.id, bitmap, true, layer, zIndex);
|
||||||
|
bitmap = undefined; // ownership transferred to storage
|
||||||
|
|
||||||
|
// Kitty cursor movement
|
||||||
|
// Per spec: cursor placed at first column after last image column,
|
||||||
|
// on the last row of the image. C=1 means don't move cursor.
|
||||||
|
if (cmd.cursorMovement === 1) {
|
||||||
|
// C=1: restore cursor to position before image was placed
|
||||||
|
const scrolled = buffer.ybase - savedYbase;
|
||||||
|
buffer.x = savedX;
|
||||||
|
// Can't restore cursor to scrollback?
|
||||||
|
buffer.y = Math.max(savedY - scrolled, 0);
|
||||||
|
} else {
|
||||||
|
// Default (C=0): advance cursor horizontally past the image
|
||||||
|
// addImage already positioned cursor on the last row via lineFeeds
|
||||||
|
buffer.x = Math.min(savedX + imgCols, this._coreTerminal.cols);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
bitmap?.close();
|
||||||
|
throw e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Create ImageBitmap from already-decoded image data.
|
||||||
* Create ImageBitmap from already-decoded image data.
|
|
||||||
*/
|
|
||||||
private async _createBitmap(image: IKittyImageData): Promise<ImageBitmap> {
|
private async _createBitmap(image: IKittyImageData): Promise<ImageBitmap> {
|
||||||
let bytes: Uint8Array = new Uint8Array(await image.data.arrayBuffer());
|
let bytes: Uint8Array = new Uint8Array(await image.data.arrayBuffer());
|
||||||
|
|
||||||
@@ -551,7 +704,10 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler {
|
|||||||
canvas.getContext('2d')?.drawImage(img, 0, 0);
|
canvas.getContext('2d')?.drawImage(img, 0, 0);
|
||||||
createImageBitmap(canvas).then(resolve).catch(reject);
|
createImageBitmap(canvas).then(resolve).catch(reject);
|
||||||
});
|
});
|
||||||
img.addEventListener('error', reject);
|
img.addEventListener('error', () => {
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
reject(new Error('Failed to load image'));
|
||||||
|
});
|
||||||
img.src = url;
|
img.src = url;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -566,7 +722,7 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler {
|
|||||||
throw new Error('Width and height required for raw pixel data');
|
throw new Error('Width and height required for raw pixel data');
|
||||||
}
|
}
|
||||||
|
|
||||||
const bytesPerPixel = image.format === KittyFormat.RGBA ? BYTES_PER_PIXEL_RGBA : BYTES_PER_PIXEL_RGB;
|
const bytesPerPixel = image.format === KittyFormat.RGBA ? KittyPixelConstants.BYTES_PER_PIXEL_RGBA : KittyPixelConstants.BYTES_PER_PIXEL_RGB;
|
||||||
const expectedBytes = width * height * bytesPerPixel;
|
const expectedBytes = width * height * bytesPerPixel;
|
||||||
|
|
||||||
if (bytes.length < expectedBytes) {
|
if (bytes.length < expectedBytes) {
|
||||||
@@ -574,18 +730,43 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const pixelCount = width * height;
|
const pixelCount = width * height;
|
||||||
const data = new Uint8ClampedArray(pixelCount * BYTES_PER_PIXEL_RGBA);
|
|
||||||
const isRgba = image.format === KittyFormat.RGBA;
|
if (image.format === KittyFormat.RGBA) {
|
||||||
|
// RGBA: use bytes directly — no copy needed
|
||||||
|
return createImageBitmap(new ImageData(new Uint8ClampedArray(bytes.buffer as ArrayBuffer, bytes.byteOffset, pixelCount * KittyPixelConstants.BYTES_PER_PIXEL_RGBA), width, height));
|
||||||
|
}
|
||||||
|
|
||||||
|
// RGB→RGBA: interleave alpha using uint32 block processing (4 pixels per iteration).
|
||||||
|
// 3 uint32 reads + 4 uint32 writes per 4 pixels vs 28 byte reads/writes — ~6x faster.
|
||||||
|
// Assumes little-endian (all modern browsers/Node.js).
|
||||||
|
const data = new Uint8ClampedArray(pixelCount * KittyPixelConstants.BYTES_PER_PIXEL_RGBA);
|
||||||
|
const src32 = new Uint32Array(bytes.buffer, bytes.byteOffset, Math.floor(bytes.byteLength / 4));
|
||||||
|
const dst32 = new Uint32Array(data.buffer);
|
||||||
|
const alignedPixels = pixelCount & ~3; // round down to multiple of 4
|
||||||
|
|
||||||
let srcOffset = 0;
|
let srcOffset = 0;
|
||||||
let dstOffset = 0;
|
let dstOffset = 0;
|
||||||
for (let i = 0; i < pixelCount; i++) {
|
for (let i = 0; i < alignedPixels; i += 4) {
|
||||||
data[dstOffset] = bytes[srcOffset];
|
const b0 = src32[srcOffset++];
|
||||||
data[dstOffset + 1] = bytes[srcOffset + 1];
|
const b1 = src32[srcOffset++];
|
||||||
data[dstOffset + 2] = bytes[srcOffset + 2];
|
const b2 = src32[srcOffset++];
|
||||||
data[dstOffset + 3] = isRgba ? bytes[srcOffset + 3] : ALPHA_OPAQUE;
|
// Little-endian: pixel bytes are [R,G,B] → uint32 ABGR layout
|
||||||
srcOffset += bytesPerPixel;
|
dst32[dstOffset++] = 0xFF000000 | b0;
|
||||||
dstOffset += BYTES_PER_PIXEL_RGBA;
|
dst32[dstOffset++] = 0xFF000000 | (b0 >>> 24) | (b1 << 8);
|
||||||
|
dst32[dstOffset++] = 0xFF000000 | (b1 >>> 16) | (b2 << 16);
|
||||||
|
dst32[dstOffset++] = 0xFF000000 | (b2 >>> 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle remaining 1–3 pixels
|
||||||
|
let srcByte = alignedPixels * KittyPixelConstants.BYTES_PER_PIXEL_RGB;
|
||||||
|
let dstByte = alignedPixels * KittyPixelConstants.BYTES_PER_PIXEL_RGBA;
|
||||||
|
for (let i = alignedPixels; i < pixelCount; i++) {
|
||||||
|
data[dstByte] = bytes[srcByte];
|
||||||
|
data[dstByte + 1] = bytes[srcByte + 1];
|
||||||
|
data[dstByte + 2] = bytes[srcByte + 2];
|
||||||
|
data[dstByte + 3] = KittyPixelConstants.ALPHA_OPAQUE;
|
||||||
|
srcByte += KittyPixelConstants.BYTES_PER_PIXEL_RGB;
|
||||||
|
dstByte += KittyPixelConstants.BYTES_PER_PIXEL_RGBA;
|
||||||
}
|
}
|
||||||
|
|
||||||
return createImageBitmap(new ImageData(data, width, height));
|
return createImageBitmap(new ImageData(data, width, height));
|
||||||
@@ -625,7 +806,11 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public get images(): ReadonlyMap<number, IKittyImageData> {
|
public get images(): ReadonlyMap<number, IKittyImageData> {
|
||||||
return this._images;
|
return this._kittyStorage.images;
|
||||||
|
}
|
||||||
|
|
||||||
|
public get _kittyIdToStorageId(): ReadonlyMap<number, number> {
|
||||||
|
return this._kittyStorage.kittyIdToStorageId;
|
||||||
}
|
}
|
||||||
|
|
||||||
public get pendingTransmissions(): ReadonlyMap<number, IPendingTransmission> {
|
public get pendingTransmissions(): ReadonlyMap<number, IPendingTransmission> {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
/**
|
/**
|
||||||
* Copyright (c) 2025 The xterm.js authors. All rights reserved.
|
* Copyright (c) 2026 The xterm.js authors. All rights reserved.
|
||||||
* @license MIT
|
* @license MIT
|
||||||
*/
|
*/
|
||||||
import { assert } from 'chai';
|
import { assert } from 'chai';
|
||||||
@@ -86,5 +86,64 @@ describe('KittyGraphicsTypes', () => {
|
|||||||
assert.ok(isNaN(cmd.format!));
|
assert.ok(isNaN(cmd.format!));
|
||||||
assert.strictEqual(cmd.id, 5);
|
assert.strictEqual(cmd.id, 5);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('should parse z-index key with positive value', () => {
|
||||||
|
const cmd = parseKittyCommand('a=T,f=100,z=10');
|
||||||
|
assert.strictEqual(cmd.zIndex, 10);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should parse z-index key with zero', () => {
|
||||||
|
const cmd = parseKittyCommand('a=T,f=100,z=0');
|
||||||
|
assert.strictEqual(cmd.zIndex, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should parse z-index key with negative value', () => {
|
||||||
|
const cmd = parseKittyCommand('a=T,f=100,z=-1');
|
||||||
|
assert.strictEqual(cmd.zIndex, -1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should leave zIndex undefined when not specified', () => {
|
||||||
|
const cmd = parseKittyCommand('a=T,f=100');
|
||||||
|
assert.strictEqual(cmd.zIndex, undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should parse delete selector key', () => {
|
||||||
|
const cmd = parseKittyCommand('a=d,d=i,i=5');
|
||||||
|
assert.strictEqual(cmd.action, 'd');
|
||||||
|
assert.strictEqual(cmd.deleteSelector, 'i');
|
||||||
|
assert.strictEqual(cmd.id, 5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should parse uppercase delete selector', () => {
|
||||||
|
const cmd = parseKittyCommand('a=d,d=A');
|
||||||
|
assert.strictEqual(cmd.deleteSelector, 'A');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should parse delete selector d=a (all)', () => {
|
||||||
|
const cmd = parseKittyCommand('a=d,d=a');
|
||||||
|
assert.strictEqual(cmd.deleteSelector, 'a');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should leave deleteSelector undefined when not specified', () => {
|
||||||
|
const cmd = parseKittyCommand('a=d,i=5');
|
||||||
|
assert.strictEqual(cmd.deleteSelector, undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should parse placement id key', () => {
|
||||||
|
const cmd = parseKittyCommand('a=d,d=i,i=5,p=3');
|
||||||
|
assert.strictEqual(cmd.placementId, 3);
|
||||||
|
assert.strictEqual(cmd.deleteSelector, 'i');
|
||||||
|
assert.strictEqual(cmd.id, 5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should leave placementId undefined when not specified', () => {
|
||||||
|
const cmd = parseKittyCommand('a=d,d=i,i=5');
|
||||||
|
assert.strictEqual(cmd.placementId, undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should parse image number key', () => {
|
||||||
|
const cmd = parseKittyCommand('a=t,f=100,I=42');
|
||||||
|
assert.strictEqual(cmd.imageNumber, 42);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
/**
|
/**
|
||||||
* Copyright (c) 2025 The xterm.js authors. All rights reserved.
|
* Copyright (c) 2026 The xterm.js authors. All rights reserved.
|
||||||
* @license MIT
|
* @license MIT
|
||||||
*
|
*
|
||||||
* Kitty graphics protocol types, constants, and parsing utilities.
|
* Kitty graphics protocol types, constants, and parsing utilities.
|
||||||
@@ -7,10 +7,8 @@
|
|||||||
|
|
||||||
import type Base64Decoder from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';
|
import type Base64Decoder from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';
|
||||||
|
|
||||||
/**
|
// Kitty graphics protocol action types.
|
||||||
* Kitty graphics protocol action types.
|
// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference under key 'a'.
|
||||||
* See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference under key 'a'.
|
|
||||||
*/
|
|
||||||
export const enum KittyAction {
|
export const enum KittyAction {
|
||||||
TRANSMIT = 't',
|
TRANSMIT = 't',
|
||||||
TRANSMIT_DISPLAY = 'T',
|
TRANSMIT_DISPLAY = 'T',
|
||||||
@@ -19,29 +17,23 @@ export const enum KittyAction {
|
|||||||
DELETE = 'd'
|
DELETE = 'd'
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Kitty graphics protocol format types.
|
||||||
* Kitty graphics protocol format types.
|
// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference
|
||||||
* See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference
|
|
||||||
*/
|
|
||||||
export const enum KittyFormat {
|
export const enum KittyFormat {
|
||||||
RGB = 24,
|
RGB = 24,
|
||||||
RGBA = 32,
|
RGBA = 32,
|
||||||
PNG = 100
|
PNG = 100
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Kitty graphics protocol compression types.
|
||||||
* Kitty graphics protocol compression types.
|
// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference under key 'o'.
|
||||||
* See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference under key 'o'.
|
|
||||||
*/
|
|
||||||
export const enum KittyCompression {
|
export const enum KittyCompression {
|
||||||
NONE = '',
|
NONE = '',
|
||||||
ZLIB = 'z'
|
ZLIB = 'z'
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Kitty graphics protocol control data keys.
|
||||||
* Kitty graphics protocol control data keys.
|
// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference
|
||||||
* See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference
|
|
||||||
*/
|
|
||||||
export const enum KittyKey {
|
export const enum KittyKey {
|
||||||
// Action to perform (t=transmit, T=transmit+display, q=query, p=placement, d=delete)
|
// Action to perform (t=transmit, T=transmit+display, q=query, p=placement, d=delete)
|
||||||
ACTION = 'a',
|
ACTION = 'a',
|
||||||
@@ -59,6 +51,14 @@ export const enum KittyKey {
|
|||||||
X_OFFSET = 'x',
|
X_OFFSET = 'x',
|
||||||
// The top edge (in pixels) of the image area to display
|
// The top edge (in pixels) of the image area to display
|
||||||
Y_OFFSET = 'y',
|
Y_OFFSET = 'y',
|
||||||
|
// Width (in pixels) of the source rectangle to display
|
||||||
|
SOURCE_WIDTH = 'w',
|
||||||
|
// Height (in pixels) of the source rectangle to display
|
||||||
|
SOURCE_HEIGHT = 'h',
|
||||||
|
// Horizontal offset (in pixels) within the first cell
|
||||||
|
X_PLACEMENT_OFFSET = 'X',
|
||||||
|
// Vertical offset (in pixels) within the first cell
|
||||||
|
Y_PLACEMENT_OFFSET = 'Y',
|
||||||
// Number of terminal columns to display the image over
|
// Number of terminal columns to display the image over
|
||||||
COLUMNS = 'c',
|
COLUMNS = 'c',
|
||||||
// Number of terminal rows to display the image over
|
// Number of terminal rows to display the image over
|
||||||
@@ -70,17 +70,25 @@ export const enum KittyKey {
|
|||||||
// Quiet mode (1=suppress OK responses, 2=suppress error responses)
|
// Quiet mode (1=suppress OK responses, 2=suppress error responses)
|
||||||
QUIET = 'q',
|
QUIET = 'q',
|
||||||
// Cursor movement policy (0=move cursor after image, 1=don't move cursor)
|
// Cursor movement policy (0=move cursor after image, 1=don't move cursor)
|
||||||
CURSOR_MOVEMENT = 'C'
|
CURSOR_MOVEMENT = 'C',
|
||||||
|
// Z-index for image layering (negative = behind text, 0+ = on top)
|
||||||
|
Z_INDEX = 'z',
|
||||||
|
// Transmission medium (d=direct, f=file, t=temp file, s=shared memory)
|
||||||
|
TRANSMISSION = 't',
|
||||||
|
// Delete selector (a/A=all, i/I=by id, c/C=at cursor, etc.) — only used when a=d
|
||||||
|
DELETE_SELECTOR = 'd',
|
||||||
|
// Placement ID for targeting specific placements
|
||||||
|
PLACEMENT_ID = 'p'
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pixel format constants
|
// Pixel format constants
|
||||||
export const BYTES_PER_PIXEL_RGB = 3;
|
export const enum KittyPixelConstants {
|
||||||
export const BYTES_PER_PIXEL_RGBA = 4;
|
BYTES_PER_PIXEL_RGB = 3,
|
||||||
export const ALPHA_OPAQUE = 255;
|
BYTES_PER_PIXEL_RGBA = 4,
|
||||||
|
ALPHA_OPAQUE = 255
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
// Parsed Kitty graphics command.
|
||||||
* Parsed Kitty graphics command.
|
|
||||||
*/
|
|
||||||
export interface IKittyCommand {
|
export interface IKittyCommand {
|
||||||
action?: string;
|
action?: string;
|
||||||
format?: number;
|
format?: number;
|
||||||
@@ -90,36 +98,40 @@ export interface IKittyCommand {
|
|||||||
height?: number;
|
height?: number;
|
||||||
x?: number;
|
x?: number;
|
||||||
y?: number;
|
y?: number;
|
||||||
|
sourceWidth?: number;
|
||||||
|
sourceHeight?: number;
|
||||||
|
xOffset?: number;
|
||||||
|
yOffset?: number;
|
||||||
columns?: number;
|
columns?: number;
|
||||||
rows?: number;
|
rows?: number;
|
||||||
more?: number;
|
more?: number;
|
||||||
quiet?: number;
|
quiet?: number;
|
||||||
cursorMovement?: number;
|
cursorMovement?: number;
|
||||||
|
zIndex?: number;
|
||||||
|
transmission?: string;
|
||||||
|
deleteSelector?: string;
|
||||||
|
placementId?: number;
|
||||||
compression?: string;
|
compression?: string;
|
||||||
payload?: string;
|
payload?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Pending chunked transmission state.
|
||||||
* Pending chunked transmission state.
|
// Stores metadata from the first chunk while accumulating decoded payload data.
|
||||||
* Stores metadata from the first chunk while accumulating decoded payload data.
|
|
||||||
*/
|
|
||||||
export interface IPendingTransmission {
|
export interface IPendingTransmission {
|
||||||
/** The parsed command from the first chunk (contains action, format, dimensions, etc.) */
|
// The parsed command from the first chunk (contains action, format, dimensions, etc.)
|
||||||
cmd: IKittyCommand;
|
cmd: IKittyCommand;
|
||||||
/** Decoder used across chunked payloads */
|
// Decoder used across chunked payloads
|
||||||
decoder: Base64Decoder;
|
decoder: Base64Decoder;
|
||||||
/** Total encoded (base64) bytes received across all chunks - for size limit enforcement */
|
// Total encoded (base64) bytes received across all chunks - for size limit enforcement
|
||||||
totalEncodedSize: number;
|
totalEncodedSize: number;
|
||||||
/** Whether any chunk has failed to decode */
|
// Whether any chunk has failed to decode
|
||||||
decodeError: boolean;
|
decodeError: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Stored Kitty image data.
|
||||||
* Stored Kitty image data.
|
|
||||||
*/
|
|
||||||
export interface IKittyImageData {
|
export interface IKittyImageData {
|
||||||
id: number;
|
id: number;
|
||||||
/** Decoded image data stored as Blob (off JS heap) to avoid 2GB heap limit */
|
// Decoded image data stored as Blob (off JS heap) to avoid 2GB heap limit
|
||||||
data: Blob;
|
data: Blob;
|
||||||
width: number;
|
width: number;
|
||||||
height: number;
|
height: number;
|
||||||
@@ -127,9 +139,7 @@ export interface IKittyImageData {
|
|||||||
compression?: string;
|
compression?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Parses Kitty graphics control data into a command object.
|
||||||
* Parses Kitty graphics control data into a command object.
|
|
||||||
*/
|
|
||||||
export function parseKittyCommand(data: string): IKittyCommand {
|
export function parseKittyCommand(data: string): IKittyCommand {
|
||||||
const cmd: IKittyCommand = {};
|
const cmd: IKittyCommand = {};
|
||||||
const parts = data.split(',');
|
const parts = data.split(',');
|
||||||
@@ -150,6 +160,14 @@ export function parseKittyCommand(data: string): IKittyCommand {
|
|||||||
cmd.compression = value;
|
cmd.compression = value;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if (key === KittyKey.TRANSMISSION) {
|
||||||
|
cmd.transmission = value;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (key === KittyKey.DELETE_SELECTOR) {
|
||||||
|
cmd.deleteSelector = value;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
const numValue = parseInt(value);
|
const numValue = parseInt(value);
|
||||||
switch (key) {
|
switch (key) {
|
||||||
case KittyKey.FORMAT: cmd.format = numValue; break;
|
case KittyKey.FORMAT: cmd.format = numValue; break;
|
||||||
@@ -159,11 +177,17 @@ export function parseKittyCommand(data: string): IKittyCommand {
|
|||||||
case KittyKey.HEIGHT: cmd.height = numValue; break;
|
case KittyKey.HEIGHT: cmd.height = numValue; break;
|
||||||
case KittyKey.X_OFFSET: cmd.x = numValue; break;
|
case KittyKey.X_OFFSET: cmd.x = numValue; break;
|
||||||
case KittyKey.Y_OFFSET: cmd.y = numValue; break;
|
case KittyKey.Y_OFFSET: cmd.y = numValue; break;
|
||||||
|
case KittyKey.SOURCE_WIDTH: cmd.sourceWidth = numValue; break;
|
||||||
|
case KittyKey.SOURCE_HEIGHT: cmd.sourceHeight = numValue; break;
|
||||||
|
case KittyKey.X_PLACEMENT_OFFSET: cmd.xOffset = numValue; break;
|
||||||
|
case KittyKey.Y_PLACEMENT_OFFSET: cmd.yOffset = numValue; break;
|
||||||
case KittyKey.COLUMNS: cmd.columns = numValue; break;
|
case KittyKey.COLUMNS: cmd.columns = numValue; break;
|
||||||
case KittyKey.ROWS: cmd.rows = numValue; break;
|
case KittyKey.ROWS: cmd.rows = numValue; break;
|
||||||
case KittyKey.MORE: cmd.more = numValue; break;
|
case KittyKey.MORE: cmd.more = numValue; break;
|
||||||
case KittyKey.QUIET: cmd.quiet = numValue; break;
|
case KittyKey.QUIET: cmd.quiet = numValue; break;
|
||||||
case KittyKey.CURSOR_MOVEMENT: cmd.cursorMovement = numValue; break;
|
case KittyKey.CURSOR_MOVEMENT: cmd.cursorMovement = numValue; break;
|
||||||
|
case KittyKey.Z_INDEX: cmd.zIndex = numValue; break;
|
||||||
|
case KittyKey.PLACEMENT_ID: cmd.placementId = numValue; break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,151 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 The xterm.js authors. All rights reserved.
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { IDisposable } from '@xterm/xterm';
|
||||||
|
import { ImageStorage } from '../ImageStorage';
|
||||||
|
import { ImageLayer } from '../Types';
|
||||||
|
import { IKittyImageData } from './KittyGraphicsTypes';
|
||||||
|
|
||||||
|
// Kitty-specific image storage controller.
|
||||||
|
//
|
||||||
|
// Wraps shared ImageStorage with kitty protocol semantics:
|
||||||
|
// - tracks transmitted image payloads by kitty image id
|
||||||
|
// - tracks kitty image id -> shared ImageStorage id mapping for displayed images
|
||||||
|
// - mirrors shared-storage evictions into kitty maps
|
||||||
|
// - applies protocol-level undisplayed-image eviction policy
|
||||||
|
export class KittyImageStorage implements IDisposable {
|
||||||
|
private static readonly _maxStoredImages = 256;
|
||||||
|
|
||||||
|
private _nextImageId = 1;
|
||||||
|
private readonly _images: Map<number, IKittyImageData> = new Map();
|
||||||
|
// TODO: Support multiple placements per image. The kitty spec identifies
|
||||||
|
// placements by an (image id, placement id) pair — same i + different p
|
||||||
|
// values should coexist, and same i + same p should replace the prior
|
||||||
|
// placement. Currently we track only one storage entry per kitty image id,
|
||||||
|
// so multiple placements of the same image overwrite each other. Fixing
|
||||||
|
// this requires changing these maps to Map<number, Map<number, number>>
|
||||||
|
// (kittyId → placementId → storageId) and updating addImage/deleteById
|
||||||
|
// accordingly. The underlying shared ImageStorage would also need to
|
||||||
|
// support multiple entries per logical image.
|
||||||
|
private readonly _kittyIdToStorageId: Map<number, number> = new Map();
|
||||||
|
private readonly _storageIdToKittyId: Map<number, number> = new Map();
|
||||||
|
|
||||||
|
private readonly _previousOnImageDeleted: ((storageId: number) => void) | undefined;
|
||||||
|
private readonly _wrappedOnImageDeleted: (storageId: number) => void;
|
||||||
|
private readonly _handleStorageImageDeleted = (storageId: number): void => {
|
||||||
|
const kittyId = this._storageIdToKittyId.get(storageId);
|
||||||
|
if (kittyId !== undefined) {
|
||||||
|
this._kittyIdToStorageId.delete(kittyId);
|
||||||
|
this._storageIdToKittyId.delete(storageId);
|
||||||
|
this._images.delete(kittyId);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly _storage: ImageStorage
|
||||||
|
) {
|
||||||
|
this._previousOnImageDeleted = this._storage.onImageDeleted;
|
||||||
|
this._wrappedOnImageDeleted = (storageId: number) => {
|
||||||
|
this._previousOnImageDeleted?.(storageId);
|
||||||
|
this._handleStorageImageDeleted(storageId);
|
||||||
|
};
|
||||||
|
this._storage.onImageDeleted = this._wrappedOnImageDeleted;
|
||||||
|
}
|
||||||
|
|
||||||
|
public reset(): void {
|
||||||
|
this._nextImageId = 1;
|
||||||
|
this._images.clear();
|
||||||
|
this._kittyIdToStorageId.clear();
|
||||||
|
this._storageIdToKittyId.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
public dispose(): void {
|
||||||
|
this.reset();
|
||||||
|
if (this._storage.onImageDeleted === this._wrappedOnImageDeleted) {
|
||||||
|
this._storage.onImageDeleted = this._previousOnImageDeleted;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public storeImage(id: number | undefined, imageData: Omit<IKittyImageData, 'id'>): number {
|
||||||
|
const imageId = id ?? this._nextImageId++;
|
||||||
|
|
||||||
|
const oldStorageId = this._kittyIdToStorageId.get(imageId);
|
||||||
|
if (oldStorageId !== undefined) {
|
||||||
|
this._storage.deleteImage(oldStorageId);
|
||||||
|
this._kittyIdToStorageId.delete(imageId);
|
||||||
|
this._storageIdToKittyId.delete(oldStorageId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this._images.has(imageId) && this._images.size >= KittyImageStorage._maxStoredImages) {
|
||||||
|
this._evictUndisplayedImages();
|
||||||
|
}
|
||||||
|
|
||||||
|
this._images.set(imageId, {
|
||||||
|
...imageData,
|
||||||
|
id: imageId
|
||||||
|
});
|
||||||
|
return imageId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public addImage(kittyId: number, image: HTMLCanvasElement | ImageBitmap, scrolling: boolean, layer: ImageLayer, zIndex: number): void {
|
||||||
|
// Clean up stale reverse-mapping from a previous placement of the same
|
||||||
|
// kitty image. The old shared-storage entry is kept (it may still be
|
||||||
|
// visible on screen) but its reverse mapping is removed so that eviction
|
||||||
|
// of the old entry won't incorrectly delete the kitty image data.
|
||||||
|
const oldStorageId = this._kittyIdToStorageId.get(kittyId);
|
||||||
|
if (oldStorageId !== undefined) {
|
||||||
|
this._storageIdToKittyId.delete(oldStorageId);
|
||||||
|
}
|
||||||
|
const storageId = this._storage.addImage(image, scrolling, layer, zIndex);
|
||||||
|
this._kittyIdToStorageId.set(kittyId, storageId);
|
||||||
|
this._storageIdToKittyId.set(storageId, kittyId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public getImage(kittyId: number): IKittyImageData | undefined {
|
||||||
|
return this._images.get(kittyId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public deleteById(kittyId: number): void {
|
||||||
|
this._images.delete(kittyId);
|
||||||
|
const storageId = this._kittyIdToStorageId.get(kittyId);
|
||||||
|
if (storageId !== undefined) {
|
||||||
|
this._storage.deleteImage(storageId);
|
||||||
|
this._kittyIdToStorageId.delete(kittyId);
|
||||||
|
this._storageIdToKittyId.delete(storageId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public deleteAll(): void {
|
||||||
|
this._images.clear();
|
||||||
|
for (const storageId of this._kittyIdToStorageId.values()) {
|
||||||
|
this._storage.deleteImage(storageId);
|
||||||
|
}
|
||||||
|
this._kittyIdToStorageId.clear();
|
||||||
|
this._storageIdToKittyId.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
public get images(): ReadonlyMap<number, IKittyImageData> {
|
||||||
|
return this._images;
|
||||||
|
}
|
||||||
|
|
||||||
|
public get kittyIdToStorageId(): ReadonlyMap<number, number> {
|
||||||
|
return this._kittyIdToStorageId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public get lastImageId(): number {
|
||||||
|
return this._nextImageId - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _evictUndisplayedImages(): void {
|
||||||
|
for (const [kittyId] of this._images) {
|
||||||
|
if (this._images.size <= KittyImageStorage._maxStoredImages / 2) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (!this._kittyIdToStorageId.has(kittyId)) {
|
||||||
|
this._images.delete(kittyId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,12 +11,11 @@
|
|||||||
"types": [
|
"types": [
|
||||||
"../../../node_modules/@types/mocha"
|
"../../../node_modules/@types/mocha"
|
||||||
],
|
],
|
||||||
"baseUrl": ".",
|
|
||||||
"paths": {
|
"paths": {
|
||||||
"browser/*": [ "../../../src/browser/*" ],
|
"browser/*": [ "../../../src/browser/*" ],
|
||||||
"common/*": [ "../../../src/common/*" ],
|
"common/*": [ "../../../src/common/*" ],
|
||||||
"vs/*": [ "../../../src/vs/*" ],
|
"@xterm/addon-image": [ "../typings/addon-image.d.ts" ],
|
||||||
"@xterm/addon-image": [ "../typings/addon-image.d.ts" ]
|
"*": [ "./*" ]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"include": [
|
"include": [
|
||||||
@@ -25,7 +24,6 @@
|
|||||||
],
|
],
|
||||||
"references": [
|
"references": [
|
||||||
{ "path": "../../../src/browser" },
|
{ "path": "../../../src/browser" },
|
||||||
{ "path": "../../../src/common" },
|
{ "path": "../../../src/common" }
|
||||||
{ "path": "../../../src/vs" }
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { readFileSync } from 'fs';
|
|||||||
import { FINALIZER, introducer, sixelEncode } from 'sixel';
|
import { FINALIZER, introducer, sixelEncode } from 'sixel';
|
||||||
import { ITestContext, createTestContext, openTerminal, pollFor, timeout } from '../../../test/playwright/TestUtils';
|
import { ITestContext, createTestContext, openTerminal, pollFor, timeout } from '../../../test/playwright/TestUtils';
|
||||||
import { deepStrictEqual, ok, strictEqual } from 'assert';
|
import { deepStrictEqual, ok, strictEqual } from 'assert';
|
||||||
|
import QoiEncoder from 'xterm-wasm-parts/lib/qoi/QoiEncoder.wasm';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Plugin ctor options.
|
* Plugin ctor options.
|
||||||
@@ -74,6 +75,10 @@ const TESTDATA_IIP: [string, [number, number]][] = [
|
|||||||
[readFileSync('./addons/addon-image/fixture/iip/w3c_jpg.iip', { encoding: 'utf-8' }), [72, 48]],
|
[readFileSync('./addons/addon-image/fixture/iip/w3c_jpg.iip', { encoding: 'utf-8' }), [72, 48]],
|
||||||
[readFileSync('./addons/addon-image/fixture/iip/w3c_png.iip', { encoding: 'utf-8' }), [72, 48]]
|
[readFileSync('./addons/addon-image/fixture/iip/w3c_png.iip', { encoding: 'utf-8' }), [72, 48]]
|
||||||
];
|
];
|
||||||
|
const PALETTE_PNG_BASE64 = readFileSync('./addons/addon-image/fixture/palette.png').toString('base64');
|
||||||
|
const qoiEnc = new QoiEncoder(1024*1024);
|
||||||
|
const qoiData = qoiEnc.encode(TESTDATA.bytes, 640, 80);
|
||||||
|
const PALETTE_QOI_BASE64 = Buffer.from(qoiData).toString('base64');
|
||||||
|
|
||||||
let ctx: ITestContext;
|
let ctx: ITestContext;
|
||||||
test.beforeAll(async ({ browser }) => {
|
test.beforeAll(async ({ browser }) => {
|
||||||
@@ -85,11 +90,6 @@ test.afterAll(async () => await ctx.page.close());
|
|||||||
test.describe('ImageAddon', () => {
|
test.describe('ImageAddon', () => {
|
||||||
|
|
||||||
test.beforeEach(async ({}, testInfo) => {
|
test.beforeEach(async ({}, testInfo) => {
|
||||||
// DEBT: This test never worked on webkit
|
|
||||||
if (ctx.browser.browserType().name() === 'webkit') {
|
|
||||||
testInfo.skip();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await ctx.page.evaluate(`
|
await ctx.page.evaluate(`
|
||||||
window.term.reset()
|
window.term.reset()
|
||||||
window.imageAddon?.dispose();
|
window.imageAddon?.dispose();
|
||||||
@@ -132,13 +132,13 @@ test.describe('ImageAddon', () => {
|
|||||||
sixelSupport: true,
|
sixelSupport: true,
|
||||||
sixelScrolling: true,
|
sixelScrolling: true,
|
||||||
sixelPaletteLimit: 512, // set to 512 to get example image working
|
sixelPaletteLimit: 512, // set to 512 to get example image working
|
||||||
sixelSizeLimit: 25000000,
|
sixelSizeLimit: 33554432,
|
||||||
storageLimit: 128,
|
storageLimit: 128,
|
||||||
showPlaceholder: true,
|
showPlaceholder: true,
|
||||||
iipSupport: true,
|
iipSupport: true,
|
||||||
iipSizeLimit: 20000000,
|
iipSizeLimit: 33554432,
|
||||||
kittySupport: true,
|
kittySupport: true,
|
||||||
kittySizeLimit: 20000000
|
kittySizeLimit: 33554432
|
||||||
};
|
};
|
||||||
deepStrictEqual(await ctx.page.evaluate(`window.imageAddon._opts`), DEFAULT_OPTIONS);
|
deepStrictEqual(await ctx.page.evaluate(`window.imageAddon._opts`), DEFAULT_OPTIONS);
|
||||||
});
|
});
|
||||||
@@ -196,6 +196,18 @@ test.describe('ImageAddon', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test.describe('image lifecycle & eviction', () => {
|
test.describe('image lifecycle & eviction', () => {
|
||||||
|
test('onImageAdded fires for each image', async () => {
|
||||||
|
await ctx.page.evaluate(`
|
||||||
|
window._imageAddedCount = 0;
|
||||||
|
window.imageAddon.onImageAdded(() => { window._imageAddedCount++; });
|
||||||
|
`);
|
||||||
|
await ctx.proxy.write(SIXEL_SEQ_0);
|
||||||
|
await pollFor(ctx.page, 'window._imageAddedCount', 1);
|
||||||
|
await ctx.proxy.write(SIXEL_SEQ_0);
|
||||||
|
await pollFor(ctx.page, 'window._imageAddedCount', 2);
|
||||||
|
await ctx.proxy.write(SIXEL_SEQ_0);
|
||||||
|
await pollFor(ctx.page, 'window._imageAddedCount', 3);
|
||||||
|
});
|
||||||
test('delete image once scrolled off', async () => {
|
test('delete image once scrolled off', async () => {
|
||||||
await ctx.proxy.write(SIXEL_SEQ_0);
|
await ctx.proxy.write(SIXEL_SEQ_0);
|
||||||
pollFor(ctx.page, 'window.imageAddon._storage._images.size', 1);
|
pollFor(ctx.page, 'window.imageAddon._storage._images.size', 1);
|
||||||
@@ -300,6 +312,68 @@ test.describe('ImageAddon', () => {
|
|||||||
deepStrictEqual(await getOrigSize(1), TESTDATA_IIP[4][1]);
|
deepStrictEqual(await getOrigSize(1), TESTDATA_IIP[4][1]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test.describe('IIP - QOI support', () => {
|
||||||
|
test('palette should yield same bytes from PNG and QOI', async () => {
|
||||||
|
await ctx.proxy.write(`\x1b]1337;File=inline=1;size=525:${PALETTE_PNG_BASE64}\x07`);
|
||||||
|
deepStrictEqual(await getOrigSize(1), [640, 80]);
|
||||||
|
await ctx.proxy.write(`\x1b[10H\x1b]1337;File=inline=1;size=${qoiData.length}:${PALETTE_QOI_BASE64}\x07`);
|
||||||
|
deepStrictEqual(await getOrigSize(2), [640, 80]);
|
||||||
|
const pngScrape = await getImageAtBufferCell(0, 0);
|
||||||
|
const qoiScrape = await getImageAtBufferCell(0, 11);
|
||||||
|
deepStrictEqual(qoiScrape, pngScrape);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test.describe('IIP - resizing', () => {
|
||||||
|
/**
|
||||||
|
* The correct resize behavior is wonky and needs to be tested against iTerm2,
|
||||||
|
* especially for missing params to derive correct default behavior.
|
||||||
|
* We document the current behavior here w'o claiming to be fully in line with iTerm2.
|
||||||
|
* ref: https://iterm2.com/documentation-images.html
|
||||||
|
* imgcat: https://iterm2.com/utilities/imgcat
|
||||||
|
*
|
||||||
|
* NOTE: QOI has a slightly different parse path, thus we test resizing explicitly
|
||||||
|
*/
|
||||||
|
const images = [
|
||||||
|
['palette.png', 525, PALETTE_PNG_BASE64],
|
||||||
|
['palette.qoi', qoiData.length, PALETTE_QOI_BASE64]
|
||||||
|
];
|
||||||
|
for (const [name, size, payload] of images) {
|
||||||
|
test(name + ': N --> width=20 height=5 preserveAspectRatio=0', async () => {
|
||||||
|
// cell based resize
|
||||||
|
const header = 'width=20;height=5;preserveAspectRatio=0';
|
||||||
|
await ctx.proxy.write(`\x1b]1337;File=inline=1;size=${size};${header}:${payload}\x07`);
|
||||||
|
const dim = await getDimensions();
|
||||||
|
deepStrictEqual(await getOrigSize(1), [dim.cellWidth * 20, dim.cellHeight * 5]);
|
||||||
|
});
|
||||||
|
test(name + ': Npx --> width=320px height=160px preserveAspectRatio=0', async () => {
|
||||||
|
// pixel based resize
|
||||||
|
const header = 'width=320px;height=160px;preserveAspectRatio=0';
|
||||||
|
await ctx.proxy.write(`\x1b]1337;File=inline=1;size=${size};${header}:${payload}\x07`);
|
||||||
|
deepStrictEqual(await getOrigSize(1), [320, 160]);
|
||||||
|
});
|
||||||
|
test(name + ': N% --> width=50% height=30% preserveAspectRatio=0', async () => {
|
||||||
|
// % of viewport resize
|
||||||
|
const header = 'width=50%;height=30%;preserveAspectRatio=0';
|
||||||
|
await ctx.proxy.write(`\x1b]1337;File=inline=1;size=${size};${header}:${payload}\x07`);
|
||||||
|
const dim = await getDimensions();
|
||||||
|
deepStrictEqual(await getOrigSize(1), [Math.floor(dim.width * 0.5), Math.floor(dim.height * 0.3)]);
|
||||||
|
});
|
||||||
|
test(name + ': ommitted dimension assumes preserveAspectRatio=1', async () => {
|
||||||
|
// width provided in percent
|
||||||
|
const header = 'width=50%';
|
||||||
|
await ctx.proxy.write(`\x1b]1337;File=inline=1;size=${size};${header}:${payload}\x07`);
|
||||||
|
const dim = await getDimensions();
|
||||||
|
const width = Math.floor(dim.width * 0.5);
|
||||||
|
deepStrictEqual(await getOrigSize(1), [width, Math.floor(width * 80 / 640)]);
|
||||||
|
// height provided in pixel
|
||||||
|
const header2 = 'height=200px';
|
||||||
|
await ctx.proxy.write(`\x1b]1337;File=inline=1;size=${size};${header2}:${payload}\x07`);
|
||||||
|
deepStrictEqual(await getOrigSize(2), [Math.floor(200 * 640 / 80), 200]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -333,3 +407,7 @@ async function getOrigSize(id: number): Promise<[number, number]> {
|
|||||||
window.imageAddon._storage._images.get(${id}).orig.height
|
window.imageAddon._storage._images.get(${id}).orig.height
|
||||||
]`);
|
]`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function getImageAtBufferCell(x: number, y: number): Promise<string | undefined> {
|
||||||
|
return ctx.page.evaluate<any>(`window.imageAddon.getImageAtBufferCell(${x}, ${y})?.toDataURL('image/png')`);
|
||||||
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -9,13 +9,15 @@
|
|||||||
"outDir": "../out-test",
|
"outDir": "../out-test",
|
||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"removeComments": true,
|
"removeComments": true,
|
||||||
"baseUrl": ".",
|
|
||||||
"paths": {
|
"paths": {
|
||||||
"common/*": [
|
"common/*": [
|
||||||
"../../../src/common/*"
|
"../../../src/common/*"
|
||||||
],
|
],
|
||||||
"browser/*": [
|
"browser/*": [
|
||||||
"../../../src/browser/*"
|
"../../../src/browser/*"
|
||||||
|
],
|
||||||
|
"*": [
|
||||||
|
"./*"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"strict": true,
|
"strict": true,
|
||||||
|
|||||||
+6
-1
@@ -3,7 +3,7 @@
|
|||||||
* @license MIT
|
* @license MIT
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { Terminal, ITerminalAddon } from '@xterm/xterm';
|
import { Terminal, ITerminalAddon, IEvent } from '@xterm/xterm';
|
||||||
|
|
||||||
declare module '@xterm/addon-image' {
|
declare module '@xterm/addon-image' {
|
||||||
export interface IImageAddonOptions {
|
export interface IImageAddonOptions {
|
||||||
@@ -116,6 +116,11 @@ declare module '@xterm/addon-image' {
|
|||||||
*/
|
*/
|
||||||
public showPlaceholder: boolean;
|
public showPlaceholder: boolean;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Event fired whenever a new image is added to storage.
|
||||||
|
*/
|
||||||
|
public readonly onImageAdded: IEvent<void>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get original image canvas at buffer position.
|
* Get original image canvas at buffer position.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -14,13 +14,13 @@
|
|||||||
"node": ">8.0.0"
|
"node": ">8.0.0"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc -p src",
|
"build": "tsgo -p src",
|
||||||
"watch": "tsc -w -p src",
|
"watch": "tsgo -w -p src",
|
||||||
"prepackage": "npm run build",
|
"prepackage": "npm run build",
|
||||||
"package": "webpack",
|
"package": "webpack",
|
||||||
"pretest": "npm run build",
|
"pretest": "npm run build",
|
||||||
"test": "nyc mocha out/**/*.test.js",
|
"test": "nyc mocha out/**/*.test.js",
|
||||||
"prepublish": "npm run package"
|
"prepublishOnly": "npm run package"
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"font",
|
"font",
|
||||||
@@ -37,9 +37,9 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/lru-cache": "^5.1.0",
|
"@types/lru-cache": "^5.1.0",
|
||||||
"@types/opentype.js": "^0.7.0",
|
"@types/opentype.js": "^0.7.0",
|
||||||
"axios": "^1.6.0",
|
"axios": "^1.15.2",
|
||||||
"font-finder": "^1.1.0",
|
"font-finder": "^1.1.0",
|
||||||
"mkdirp": "0.5.5",
|
"mkdirp": "0.5.5",
|
||||||
"yauzl": "^2.10.0"
|
"yauzl": "^3.2.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,8 +9,12 @@
|
|||||||
"outDir": "../out-esbuild-test",
|
"outDir": "../out-esbuild-test",
|
||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"removeComments": true,
|
"removeComments": true,
|
||||||
"baseUrl": ".",
|
|
||||||
"strict": true,
|
"strict": true,
|
||||||
|
"paths": {
|
||||||
|
"*": [
|
||||||
|
"./*"
|
||||||
|
]
|
||||||
|
},
|
||||||
"types": [
|
"types": [
|
||||||
"../../../node_modules/@types/mocha",
|
"../../../node_modules/@types/mocha",
|
||||||
"../../../node_modules/@types/node"
|
"../../../node_modules/@types/node"
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
"xterm.js"
|
"xterm.js"
|
||||||
],
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "../../node_modules/.bin/tsc -p .",
|
"build": "../../node_modules/.bin/tsgo -p .",
|
||||||
"prepackage": "npm run build",
|
"prepackage": "npm run build",
|
||||||
"package": "../../node_modules/.bin/webpack",
|
"package": "../../node_modules/.bin/webpack",
|
||||||
"prepublishOnly": "npm run package",
|
"prepublishOnly": "npm run package",
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
|
|
||||||
import type { Terminal, ITerminalAddon, IDisposable } from '@xterm/xterm';
|
import type { Terminal, ITerminalAddon, IDisposable } from '@xterm/xterm';
|
||||||
import type { ProgressAddon as IProgressApi, IProgressState } from '@xterm/addon-progress';
|
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 {
|
const enum ProgressType {
|
||||||
@@ -39,7 +39,7 @@ export class ProgressAddon implements ITerminalAddon, IProgressApi {
|
|||||||
private _pr = 0;
|
private _pr = 0;
|
||||||
// HACK: This uses ! to align with the API, this should be fixed when 5283 is resolved
|
// HACK: This uses ! to align with the API, this should be fixed when 5283 is resolved
|
||||||
private _onChange!: Emitter<IProgressState>;
|
private _onChange!: Emitter<IProgressState>;
|
||||||
public onChange!: Event<IProgressState>;
|
public onChange!: IEvent<IProgressState>;
|
||||||
|
|
||||||
public dispose(): void {
|
public dispose(): void {
|
||||||
this._seqHandler?.dispose();
|
this._seqHandler?.dispose();
|
||||||
|
|||||||
@@ -15,12 +15,12 @@
|
|||||||
"../../../node_modules/@types/mocha"
|
"../../../node_modules/@types/mocha"
|
||||||
],
|
],
|
||||||
"paths": {
|
"paths": {
|
||||||
|
"common/*": [
|
||||||
|
"../../../src/common/*"
|
||||||
|
],
|
||||||
"browser/*": [
|
"browser/*": [
|
||||||
"../../../src/browser/*"
|
"../../../src/browser/*"
|
||||||
],
|
],
|
||||||
"vs/*": [
|
|
||||||
"../../../src/vs/*"
|
|
||||||
],
|
|
||||||
"@xterm/addon-progress": [
|
"@xterm/addon-progress": [
|
||||||
"../typings/addon-progress.d.ts"
|
"../typings/addon-progress.d.ts"
|
||||||
]
|
]
|
||||||
@@ -35,7 +35,7 @@
|
|||||||
"path": "../../../src/browser"
|
"path": "../../../src/browser"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"path": "../../../src/vs"
|
"path": "../../../src/common"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,15 +9,18 @@ import { ITestContext, createTestContext, openTerminal } from '../../../test/pla
|
|||||||
|
|
||||||
|
|
||||||
let ctx: ITestContext;
|
let ctx: ITestContext;
|
||||||
test.beforeAll(async ({ browser }) => {
|
|
||||||
ctx = await createTestContext(browser);
|
|
||||||
ctx.page.setViewportSize({ width: 1024, height: 768 });
|
|
||||||
await openTerminal(ctx);
|
|
||||||
});
|
|
||||||
test.afterAll(async () => await ctx.page.close());
|
|
||||||
|
|
||||||
|
|
||||||
test.describe('ProgressAddon', () => {
|
test.describe('ProgressAddon', () => {
|
||||||
|
test.describe.configure({ mode: 'serial' });
|
||||||
|
|
||||||
|
test.beforeAll(async ({ browser }) => {
|
||||||
|
ctx = await createTestContext(browser);
|
||||||
|
await openTerminal(ctx);
|
||||||
|
});
|
||||||
|
test.afterAll(async () => {
|
||||||
|
await ctx?.page?.close();
|
||||||
|
});
|
||||||
|
|
||||||
test.beforeEach(async function(): Promise<any> {
|
test.beforeEach(async function(): Promise<any> {
|
||||||
await ctx.page.evaluate(`
|
await ctx.page.evaluate(`
|
||||||
window.progressStack = [];
|
window.progressStack = [];
|
||||||
|
|||||||
@@ -9,13 +9,15 @@
|
|||||||
"outDir": "../out-test",
|
"outDir": "../out-test",
|
||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"removeComments": true,
|
"removeComments": true,
|
||||||
"baseUrl": ".",
|
|
||||||
"paths": {
|
"paths": {
|
||||||
"common/*": [
|
"common/*": [
|
||||||
"../../../src/common/*"
|
"../../../src/common/*"
|
||||||
],
|
],
|
||||||
"browser/*": [
|
"browser/*": [
|
||||||
"../../../src/browser/*"
|
"../../../src/browser/*"
|
||||||
|
],
|
||||||
|
"*": [
|
||||||
|
"./*"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"strict": true,
|
"strict": true,
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
"xterm.js"
|
"xterm.js"
|
||||||
],
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"prepackage": "../../node_modules/.bin/tsc -p .",
|
"prepackage": "../../node_modules/.bin/tsgo -p .",
|
||||||
"package": "../../node_modules/.bin/webpack",
|
"package": "../../node_modules/.bin/webpack",
|
||||||
"prepublishOnly": "npm run package",
|
"prepublishOnly": "npm run package",
|
||||||
"start": "node ../../demo/start"
|
"start": "node ../../demo/start"
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
|
|
||||||
import type { Terminal, IDisposable, IDecoration } from '@xterm/xterm';
|
import type { Terminal, IDisposable, IDecoration } from '@xterm/xterm';
|
||||||
import type { ISearchDecorationOptions } from '@xterm/addon-search';
|
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';
|
import type { ISearchResult } from './SearchEngine';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -5,9 +5,9 @@
|
|||||||
|
|
||||||
import type { Terminal, IDisposable, ITerminalAddon } from '@xterm/xterm';
|
import type { Terminal, IDisposable, ITerminalAddon } from '@xterm/xterm';
|
||||||
import type { SearchAddon as ISearchApi, ISearchOptions, ISearchAddonOptions, ISearchResultChangeEvent, ISearchDecorationOptions } from '@xterm/addon-search';
|
import type { SearchAddon as ISearchApi, ISearchOptions, ISearchAddonOptions, ISearchResultChangeEvent, ISearchDecorationOptions } from '@xterm/addon-search';
|
||||||
import { Emitter, Event } from 'vs/base/common/event';
|
import { Emitter, type IEvent } from 'common/Event';
|
||||||
import { Disposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';
|
import { Disposable, MutableDisposable, toDisposable } from 'common/Lifecycle';
|
||||||
import { disposableTimeout } from 'vs/base/common/async';
|
import { disposableTimeout } from 'common/Async';
|
||||||
import { SearchLineCache } from './SearchLineCache';
|
import { SearchLineCache } from './SearchLineCache';
|
||||||
import { SearchState } from './SearchState';
|
import { SearchState } from './SearchState';
|
||||||
import { SearchEngine, type ISearchResult } from './SearchEngine';
|
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>());
|
private readonly _onBeforeSearch = this._register(new Emitter<void>());
|
||||||
public readonly onBeforeSearch = this._onBeforeSearch.event;
|
public readonly onBeforeSearch = this._onBeforeSearch.event;
|
||||||
|
|
||||||
public get onDidChangeResults(): Event<ISearchResultChangeEvent> {
|
public get onDidChangeResults(): IEvent<ISearchResultChangeEvent> {
|
||||||
return this._resultTracker.onDidChangeResults;
|
return this._resultTracker.onDidChangeResults;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import { SearchEngine } from './SearchEngine';
|
|||||||
import { SearchLineCache } from './SearchLineCache';
|
import { SearchLineCache } from './SearchLineCache';
|
||||||
import { Terminal } from 'browser/public/Terminal';
|
import { Terminal } from 'browser/public/Terminal';
|
||||||
import type { ISearchOptions } from '@xterm/addon-search';
|
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> {
|
function writeP(terminal: Terminal, data: string): Promise<void> {
|
||||||
return new Promise(r => terminal.write(data, r));
|
return new Promise(r => terminal.write(data, r));
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
import { assert } from 'chai';
|
import { assert } from 'chai';
|
||||||
import { SearchLineCache, LineCacheEntry } from './SearchLineCache';
|
import { SearchLineCache, LineCacheEntry } from './SearchLineCache';
|
||||||
import { Terminal } from 'browser/public/Terminal';
|
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> {
|
function writeP(terminal: Terminal, data: string): Promise<void> {
|
||||||
return new Promise(r => terminal.write(data, r));
|
return new Promise(r => terminal.write(data, r));
|
||||||
|
|||||||
@@ -4,8 +4,8 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import type { Terminal } from '@xterm/xterm';
|
import type { Terminal } from '@xterm/xterm';
|
||||||
import { combinedDisposable, Disposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';
|
import { combinedDisposable, Disposable, MutableDisposable, toDisposable } from 'common/Lifecycle';
|
||||||
import { disposableTimeout } from 'vs/base/common/async';
|
import { disposableTimeout } from 'common/Async';
|
||||||
|
|
||||||
export type LineCacheEntry = [
|
export type LineCacheEntry = [
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -5,8 +5,8 @@
|
|||||||
|
|
||||||
import type { ISearchResultChangeEvent } from '@xterm/addon-search';
|
import type { ISearchResultChangeEvent } from '@xterm/addon-search';
|
||||||
import type { IDisposable } from '@xterm/xterm';
|
import type { IDisposable } from '@xterm/xterm';
|
||||||
import { Emitter, Event } from 'vs/base/common/event';
|
import { Emitter, type IEvent } from 'common/Event';
|
||||||
import { Disposable } from 'vs/base/common/lifecycle';
|
import { Disposable } from 'common/Lifecycle';
|
||||||
import type { ISearchResult } from './SearchEngine';
|
import type { ISearchResult } from './SearchEngine';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -25,7 +25,7 @@ export class SearchResultTracker extends Disposable {
|
|||||||
private _selectedDecoration: ISelectedDecoration | undefined;
|
private _selectedDecoration: ISelectedDecoration | undefined;
|
||||||
|
|
||||||
private readonly _onDidChangeResults = this._register(new Emitter<ISearchResultChangeEvent>());
|
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.
|
* Gets the current search results.
|
||||||
|
|||||||
@@ -21,9 +21,6 @@
|
|||||||
"browser/*": [
|
"browser/*": [
|
||||||
"../../../src/browser/*"
|
"../../../src/browser/*"
|
||||||
],
|
],
|
||||||
"vs/*": [
|
|
||||||
"../../../src/vs/*"
|
|
||||||
],
|
|
||||||
"@xterm/addon-search" : [
|
"@xterm/addon-search" : [
|
||||||
"../typings/addon-search.d.ts"
|
"../typings/addon-search.d.ts"
|
||||||
]
|
]
|
||||||
@@ -39,9 +36,6 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"path": "../../../src/browser"
|
"path": "../../../src/browser"
|
||||||
},
|
|
||||||
{
|
|
||||||
"path": "../../../src/vs"
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,13 +9,15 @@
|
|||||||
"outDir": "../out-test",
|
"outDir": "../out-test",
|
||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"removeComments": true,
|
"removeComments": true,
|
||||||
"baseUrl": ".",
|
|
||||||
"paths": {
|
"paths": {
|
||||||
"common/*": [
|
"common/*": [
|
||||||
"../../../src/common/*"
|
"../../../src/common/*"
|
||||||
],
|
],
|
||||||
"browser/*": [
|
"browser/*": [
|
||||||
"../../../src/browser/*"
|
"../../../src/browser/*"
|
||||||
|
],
|
||||||
|
"*": [
|
||||||
|
"./*"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"strict": true,
|
"strict": true,
|
||||||
|
|||||||
@@ -4,13 +4,13 @@
|
|||||||
"dom",
|
"dom",
|
||||||
"es2021"
|
"es2021"
|
||||||
],
|
],
|
||||||
|
"rootDir": "..",
|
||||||
"outDir": "../out-benchmark",
|
"outDir": "../out-benchmark",
|
||||||
"types": ["../../../node_modules/@types/node"],
|
"types": ["../../../node_modules/@types/node"],
|
||||||
"moduleResolution": "node",
|
"moduleResolution": "node",
|
||||||
"strict": false,
|
"strict": false,
|
||||||
"target": "es2021",
|
"target": "es2021",
|
||||||
"module": "commonjs",
|
"module": "commonjs",
|
||||||
"baseUrl": ".",
|
|
||||||
"paths": {
|
"paths": {
|
||||||
"common/*": ["../../../src/common/*"],
|
"common/*": ["../../../src/common/*"],
|
||||||
"browser/*": ["../../../src/browser/*"],
|
"browser/*": ["../../../src/browser/*"],
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
"xterm.js"
|
"xterm.js"
|
||||||
],
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "../../node_modules/.bin/tsc -p .",
|
"build": "../../node_modules/.bin/tsgo -p .",
|
||||||
"prepackage": "npm run build",
|
"prepackage": "npm run build",
|
||||||
"package": "../../node_modules/.bin/webpack",
|
"package": "../../node_modules/.bin/webpack",
|
||||||
"prepublishOnly": "npm run package",
|
"prepublishOnly": "npm run package",
|
||||||
|
|||||||
@@ -116,7 +116,7 @@ describe('SerializeAddon', () => {
|
|||||||
describe('underline styles', () => {
|
describe('underline styles', () => {
|
||||||
it('should serialize single underline with style', async () => {
|
it('should serialize single underline with style', async () => {
|
||||||
await writeP(terminal, sgr('4:1') + 'test' + sgr('24'));
|
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 () => {
|
it('should serialize double underline', async () => {
|
||||||
|
|||||||
@@ -89,11 +89,19 @@ function equalUnderline(cell1: IBufferCell | IAttributeData, cell2: IBufferCell)
|
|||||||
if (!cell1.isUnderline() && !cell2.isUnderline()) {
|
if (!cell1.isUnderline() && !cell2.isUnderline()) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
const cell1Data = cell1 as unknown as IAttributeData;
|
if (cell1.getUnderlineStyle() !== cell2.getUnderlineStyle()) {
|
||||||
const cell2Data = cell2 as unknown as IAttributeData;
|
return false;
|
||||||
return cell1Data.getUnderlineStyle() === cell2Data.getUnderlineStyle()
|
}
|
||||||
&& cell1Data.getUnderlineColor() === cell2Data.getUnderlineColor()
|
const cell1Default = cell1.isUnderlineColorDefault();
|
||||||
&& cell1Data.getUnderlineColorMode() === cell2Data.getUnderlineColorMode();
|
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 {
|
function equalFlags(cell1: IBufferCell | IAttributeData, cell2: IBufferCell): boolean {
|
||||||
@@ -109,6 +117,16 @@ function equalFlags(cell1: IBufferCell | IAttributeData, cell2: IBufferCell): bo
|
|||||||
&& cell1.isStrikethrough() === cell2.isStrikethrough();
|
&& 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 {
|
class StringSerializeHandler extends BaseSerializeHandler {
|
||||||
private _rowIndex: number = 0;
|
private _rowIndex: number = 0;
|
||||||
private _allRows: string[] = new Array<string>();
|
private _allRows: string[] = new Array<string>();
|
||||||
@@ -258,6 +276,9 @@ class StringSerializeHandler extends BaseSerializeHandler {
|
|||||||
|
|
||||||
private _diffStyle(cell: IBufferCell | IAttributeData, oldCell: IBufferCell): number[] {
|
private _diffStyle(cell: IBufferCell | IAttributeData, oldCell: IBufferCell): number[] {
|
||||||
const sgrSeq: number[] = [];
|
const sgrSeq: number[] = [];
|
||||||
|
if (attributesEquals(cell, oldCell)) {
|
||||||
|
return sgrSeq;
|
||||||
|
}
|
||||||
const fgChanged = !equalFg(cell, oldCell);
|
const fgChanged = !equalFg(cell, oldCell);
|
||||||
const bgChanged = !equalBg(cell, oldCell);
|
const bgChanged = !equalBg(cell, oldCell);
|
||||||
const flagsChanged = !equalFlags(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.isInverse() !== oldCell.isInverse()) { sgrSeq.push(cell.isInverse() ? 7 : 27); }
|
||||||
if (cell.isBold() !== oldCell.isBold()) { sgrSeq.push(cell.isBold() ? 1 : 22); }
|
if (cell.isBold() !== oldCell.isBold()) { sgrSeq.push(cell.isBold() ? 1 : 22); }
|
||||||
if (!equalUnderline(cell, oldCell)) {
|
if (!equalUnderline(cell, oldCell)) {
|
||||||
const cellData = cell as unknown as IAttributeData;
|
const style = cell.getUnderlineStyle();
|
||||||
const style = cellData.getUnderlineStyle();
|
|
||||||
if (style === UnderlineStyle.NONE) {
|
if (style === UnderlineStyle.NONE) {
|
||||||
sgrSeq.push(24);
|
sgrSeq.push(24);
|
||||||
|
} else if (style === UnderlineStyle.SINGLE && cell.isUnderlineColorDefault()) {
|
||||||
|
sgrSeq.push(4);
|
||||||
} else {
|
} else {
|
||||||
// Use SGR 4:X format for underline styles
|
// Use SGR 4:X format for underline styles
|
||||||
sgrSeq.push('4:' + style as unknown as number);
|
sgrSeq.push('4:' + style as unknown as number);
|
||||||
// Handle underline color
|
// Handle underline color
|
||||||
if (!cellData.isUnderlineColorDefault()) {
|
if (!cell.isUnderlineColorDefault()) {
|
||||||
const color = cellData.getUnderlineColor();
|
const color = cell.getUnderlineColor();
|
||||||
if (cellData.isUnderlineColorRGB()) {
|
if (cell.isUnderlineColorRGB()) {
|
||||||
sgrSeq.push('58:2::' + ((color >>> 16) & 0xFF) + ':' + ((color >>> 8) & 0xFF) + ':' + (color & 0xFF) as unknown as number);
|
sgrSeq.push('58:2::' + ((color >>> 16) & 0xFF) + ':' + ((color >>> 8) & 0xFF) + ':' + (color & 0xFF) as unknown as number);
|
||||||
} else {
|
} else {
|
||||||
sgrSeq.push('58:5:' + color as unknown as number);
|
sgrSeq.push('58:5:' + color as unknown as number);
|
||||||
@@ -675,12 +697,11 @@ export class HTMLSerializeHandler extends BaseSerializeHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private _getUnderlineColor(cell: IBufferCell): string | undefined {
|
private _getUnderlineColor(cell: IBufferCell): string | undefined {
|
||||||
const cellData = cell as unknown as IAttributeData;
|
if (cell.isUnderlineColorDefault()) {
|
||||||
if (cellData.isUnderlineColorDefault()) {
|
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
const color = cellData.getUnderlineColor();
|
const color = cell.getUnderlineColor();
|
||||||
if (cellData.isUnderlineColorRGB()) {
|
if (cell.isUnderlineColorRGB()) {
|
||||||
const rgb = [
|
const rgb = [
|
||||||
(color >> 16) & 255,
|
(color >> 16) & 255,
|
||||||
(color >> 8) & 255,
|
(color >> 8) & 255,
|
||||||
@@ -693,8 +714,7 @@ export class HTMLSerializeHandler extends BaseSerializeHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private _getUnderlineStyle(cell: IBufferCell): string {
|
private _getUnderlineStyle(cell: IBufferCell): string {
|
||||||
const cellData = cell as unknown as IAttributeData;
|
switch (cell.getUnderlineStyle()) {
|
||||||
switch (cellData.getUnderlineStyle()) {
|
|
||||||
case UnderlineStyle.SINGLE:
|
case UnderlineStyle.SINGLE:
|
||||||
return 'underline';
|
return 'underline';
|
||||||
case UnderlineStyle.DOUBLE:
|
case UnderlineStyle.DOUBLE:
|
||||||
@@ -713,6 +733,10 @@ export class HTMLSerializeHandler extends BaseSerializeHandler {
|
|||||||
private _diffStyle(cell: IBufferCell, oldCell: IBufferCell): string[] | undefined {
|
private _diffStyle(cell: IBufferCell, oldCell: IBufferCell): string[] | undefined {
|
||||||
const content: string[] = [];
|
const content: string[] = [];
|
||||||
|
|
||||||
|
if (attributesEquals(cell, oldCell)) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
const fgChanged = !equalFg(cell, oldCell);
|
const fgChanged = !equalFg(cell, oldCell);
|
||||||
const bgChanged = !equalBg(cell, oldCell);
|
const bgChanged = !equalBg(cell, oldCell);
|
||||||
const flagsChanged = !equalFlags(cell, oldCell);
|
const flagsChanged = !equalFlags(cell, oldCell);
|
||||||
|
|||||||
@@ -10,7 +10,6 @@
|
|||||||
"outDir": "../out",
|
"outDir": "../out",
|
||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"removeComments": true,
|
"removeComments": true,
|
||||||
"baseUrl": ".",
|
|
||||||
"paths": {
|
"paths": {
|
||||||
"common/*": [
|
"common/*": [
|
||||||
"../../../src/common/*"
|
"../../../src/common/*"
|
||||||
@@ -23,6 +22,7 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"strict": true,
|
"strict": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
"types": [
|
"types": [
|
||||||
"../../../node_modules/@types/mocha"
|
"../../../node_modules/@types/mocha"
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -49,7 +49,14 @@ test.describe('SerializeAddon', () => {
|
|||||||
for (let i = 0; i < buffer.length; i++) {
|
for (let i = 0; i < buffer.length; i++) {
|
||||||
// Do this intentionally to get content of underlining source
|
// Do this intentionally to get content of underlining source
|
||||||
const bufferLine = buffer.getLine(i)._line;
|
const bufferLine = buffer.getLine(i)._line;
|
||||||
lines.push(JSON.stringify(bufferLine));
|
lines.push(JSON.stringify(bufferLine, (key, value) => {
|
||||||
|
// BufferLine caches are internal/transient and can legitimately differ
|
||||||
|
// across equivalent terminal states.
|
||||||
|
if (key === '_stringCache' || key === '_stringCacheEntryRef') {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
x: buffer.cursorX,
|
x: buffer.cursorX,
|
||||||
@@ -203,6 +210,46 @@ test.describe('SerializeAddon', () => {
|
|||||||
strictEqual(await ctx.page.evaluate(`window.serialize.serialize();`), lines.join('\r\n'));
|
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> {
|
test('serialize all rows of content with color256', async function(): Promise<any> {
|
||||||
const rows = 32;
|
const rows = 32;
|
||||||
const cols = 10;
|
const cols = 10;
|
||||||
@@ -602,6 +649,9 @@ const BOLD = '1';
|
|||||||
const DIM = '2';
|
const DIM = '2';
|
||||||
const ITALIC = '3';
|
const ITALIC = '3';
|
||||||
const UNDERLINED = '4';
|
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 BLINK = '5';
|
||||||
const INVERSE = '7';
|
const INVERSE = '7';
|
||||||
const INVISIBLE = '8';
|
const INVISIBLE = '8';
|
||||||
|
|||||||
@@ -9,7 +9,6 @@
|
|||||||
"outDir": "../out-test",
|
"outDir": "../out-test",
|
||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"removeComments": true,
|
"removeComments": true,
|
||||||
"baseUrl": ".",
|
|
||||||
"paths": {
|
"paths": {
|
||||||
"common/*": [
|
"common/*": [
|
||||||
"../../../src/common/*"
|
"../../../src/common/*"
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"lib": ["dom", "es6"],
|
"lib": ["dom", "es6"],
|
||||||
|
"rootDir": "..",
|
||||||
"outDir": "../out-benchmark",
|
"outDir": "../out-benchmark",
|
||||||
"types": ["../../../node_modules/@types/node"],
|
"types": ["../../../node_modules/@types/node"],
|
||||||
"moduleResolution": "node",
|
"moduleResolution": "node",
|
||||||
"strict": false,
|
"strict": false,
|
||||||
"target": "es2015",
|
"target": "es2015",
|
||||||
"module": "commonjs",
|
"module": "commonjs",
|
||||||
"baseUrl": ".",
|
|
||||||
"paths": {
|
"paths": {
|
||||||
"common/*": ["../../../src/common/*"],
|
"common/*": ["../../../src/common/*"],
|
||||||
"browser/*": ["../../../src/browser/*"],
|
"browser/*": ["../../../src/browser/*"],
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
"xterm.js"
|
"xterm.js"
|
||||||
],
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "../../node_modules/.bin/tsc -p .",
|
"build": "../../node_modules/.bin/tsgo -p .",
|
||||||
"prepackage": "npm run build",
|
"prepackage": "npm run build",
|
||||||
"package": "../../node_modules/.bin/webpack",
|
"package": "../../node_modules/.bin/webpack",
|
||||||
"prepublishOnly": "npm run package",
|
"prepublishOnly": "npm run package",
|
||||||
|
|||||||
@@ -11,7 +11,6 @@
|
|||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"removeComments": true,
|
"removeComments": true,
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"baseUrl": ".",
|
|
||||||
"paths": {
|
"paths": {
|
||||||
"common/*": [
|
"common/*": [
|
||||||
"../../../src/common/*"
|
"../../../src/common/*"
|
||||||
|
|||||||
@@ -9,7 +9,6 @@
|
|||||||
"outDir": "../out-test",
|
"outDir": "../out-test",
|
||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"removeComments": true,
|
"removeComments": true,
|
||||||
"baseUrl": ".",
|
|
||||||
"paths": {
|
"paths": {
|
||||||
"common/*": [
|
"common/*": [
|
||||||
"../../../src/common/*"
|
"../../../src/common/*"
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
"xterm.js"
|
"xterm.js"
|
||||||
],
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "../../node_modules/.bin/tsc -p .",
|
"build": "../../node_modules/.bin/tsgo -p .",
|
||||||
"prepackage": "npm run build",
|
"prepackage": "npm run build",
|
||||||
"package": "../../node_modules/.bin/webpack",
|
"package": "../../node_modules/.bin/webpack",
|
||||||
"prepublishOnly": "npm run package",
|
"prepublishOnly": "npm run package",
|
||||||
|
|||||||
@@ -11,13 +11,15 @@
|
|||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"removeComments": true,
|
"removeComments": true,
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"baseUrl": ".",
|
|
||||||
"paths": {
|
"paths": {
|
||||||
"common/*": [
|
"common/*": [
|
||||||
"../../../src/common/*"
|
"../../../src/common/*"
|
||||||
],
|
],
|
||||||
"@xterm/addon-unicode11": [
|
"@xterm/addon-unicode11": [
|
||||||
"../typings/addon-unicode11.d.ts"
|
"../typings/addon-unicode11.d.ts"
|
||||||
|
],
|
||||||
|
"*": [
|
||||||
|
"./*"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"types": [
|
"types": [
|
||||||
|
|||||||
@@ -9,13 +9,15 @@
|
|||||||
"outDir": "../out-test",
|
"outDir": "../out-test",
|
||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"removeComments": true,
|
"removeComments": true,
|
||||||
"baseUrl": ".",
|
|
||||||
"paths": {
|
"paths": {
|
||||||
"common/*": [
|
"common/*": [
|
||||||
"../../../src/common/*"
|
"../../../src/common/*"
|
||||||
],
|
],
|
||||||
"browser/*": [
|
"browser/*": [
|
||||||
"../../../src/browser/*"
|
"../../../src/browser/*"
|
||||||
|
],
|
||||||
|
"*": [
|
||||||
|
"./*"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"strict": true,
|
"strict": true,
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
"xterm.js"
|
"xterm.js"
|
||||||
],
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "../../node_modules/.bin/tsc -p .",
|
"build": "../../node_modules/.bin/tsgo -p .",
|
||||||
"prepackage": "npm run build",
|
"prepackage": "npm run build",
|
||||||
"package": "../../node_modules/.bin/webpack",
|
"package": "../../node_modules/.bin/webpack",
|
||||||
"prepublishOnly": "npm run package",
|
"prepublishOnly": "npm run package",
|
||||||
|
|||||||
@@ -33,16 +33,16 @@ test.describe('WebFontsAddon', () => {
|
|||||||
test.describe('font loading at runtime', () => {
|
test.describe('font loading at runtime', () => {
|
||||||
test('loadFonts (JS)', async () => {
|
test('loadFonts (JS)', async () => {
|
||||||
await ctx.page.evaluate(`
|
await ctx.page.evaluate(`
|
||||||
const ff1 = new FontFace('Kongtext', "url(/kongtext.regular.ttf) format('truetype')");
|
const ff1 = new FontFace('Kongtext', "url(/fonts/kongtext.regular.ttf) format('truetype')");
|
||||||
const ff2 = new FontFace('BPdots', "url(/bpdots.regular.otf) format('opentype')");
|
const ff2 = new FontFace('BPdots', "url(/fonts/bpdots.regular.otf) format('opentype')");
|
||||||
loadFonts([ff1, ff2]);
|
loadFonts([ff1, ff2]);
|
||||||
`);
|
`);
|
||||||
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'loaded' }, { family: 'BPdots', status: 'loaded' }]);
|
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'loaded' }, { family: 'BPdots', status: 'loaded' }]);
|
||||||
});
|
});
|
||||||
test('loadFonts (CSS, unquoted)', async () => {
|
test('loadFonts (CSS, unquoted)', async () => {
|
||||||
await ctx.page.evaluate(`
|
await ctx.page.evaluate(`
|
||||||
document.styleSheets[0].insertRule("@font-face {font-family: Kongtext; src: url(/kongtext.regular.ttf) format('truetype')}", 0);
|
document.styleSheets[0].insertRule("@font-face {font-family: Kongtext; src: url(/fonts/kongtext.regular.ttf) format('truetype')}", 0);
|
||||||
document.styleSheets[0].insertRule("@font-face {font-family: BPdots; src: url(/bpdots.regular.otf) format('opentype')}", 1);
|
document.styleSheets[0].insertRule("@font-face {font-family: BPdots; src: url(/fonts/bpdots.regular.otf) format('opentype')}", 1);
|
||||||
loadFonts(['Kongtext', 'BPdots']);
|
loadFonts(['Kongtext', 'BPdots']);
|
||||||
`);
|
`);
|
||||||
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'loaded' }, { family: 'BPdots', status: 'loaded' }]);
|
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'loaded' }, { family: 'BPdots', status: 'loaded' }]);
|
||||||
@@ -50,8 +50,8 @@ test.describe('WebFontsAddon', () => {
|
|||||||
test('loadFonts (CSS, quoted)', async ({ browser }) => {
|
test('loadFonts (CSS, quoted)', async ({ browser }) => {
|
||||||
// NOTE: firefox preserves family quotes from CSS rules in fontface, all other browsers unquote them
|
// NOTE: firefox preserves family quotes from CSS rules in fontface, all other browsers unquote them
|
||||||
await ctx.page.evaluate(`
|
await ctx.page.evaluate(`
|
||||||
document.styleSheets[0].insertRule("@font-face {font-family: 'Kongtext'; src: url(/kongtext.regular.ttf) format('truetype')}", 0);
|
document.styleSheets[0].insertRule("@font-face {font-family: 'Kongtext'; src: url(/fonts/kongtext.regular.ttf) format('truetype')}", 0);
|
||||||
document.styleSheets[0].insertRule("@font-face {font-family: 'BPdots'; src: url(/bpdots.regular.otf) format('opentype')}", 1);
|
document.styleSheets[0].insertRule("@font-face {font-family: 'BPdots'; src: url(/fonts/bpdots.regular.otf) format('opentype')}", 1);
|
||||||
loadFonts(['Kongtext', 'BPdots']);
|
loadFonts(['Kongtext', 'BPdots']);
|
||||||
`);
|
`);
|
||||||
if (browser.browserType().name() === 'firefox') {
|
if (browser.browserType().name() === 'firefox') {
|
||||||
@@ -63,8 +63,8 @@ test.describe('WebFontsAddon', () => {
|
|||||||
test('FontFace hashing', async () => {
|
test('FontFace hashing', async () => {
|
||||||
// multiple calls of `loadFonts` with the same objects shall not bloat document.fonts
|
// multiple calls of `loadFonts` with the same objects shall not bloat document.fonts
|
||||||
await ctx.page.evaluate(`
|
await ctx.page.evaluate(`
|
||||||
const ff1 = new FontFace('Kongtext', "url(/kongtext.regular.ttf) format('truetype')");
|
const ff1 = new FontFace('Kongtext', "url(/fonts/kongtext.regular.ttf) format('truetype')");
|
||||||
const ff2 = new FontFace('BPdots', "url(/bpdots.regular.otf) format('opentype')");
|
const ff2 = new FontFace('BPdots', "url(/fonts/bpdots.regular.otf) format('opentype')");
|
||||||
loadFonts([ff1, ff2]);
|
loadFonts([ff1, ff2]);
|
||||||
loadFonts([ff1, ff2]);
|
loadFonts([ff1, ff2]);
|
||||||
loadFonts([ff1, ff2]).then(() => loadFonts([ff1, ff2]));
|
loadFonts([ff1, ff2]).then(() => loadFonts([ff1, ff2]));
|
||||||
@@ -76,7 +76,7 @@ test.describe('WebFontsAddon', () => {
|
|||||||
// to make this test work, we exclude the default measurement char W (x57) by restricting unicode-range
|
// to make this test work, we exclude the default measurement char W (x57) by restricting unicode-range
|
||||||
// now the browser will postpone font loading until codepoint is hit --> wrong glyph metrics on first usage
|
// now the browser will postpone font loading until codepoint is hit --> wrong glyph metrics on first usage
|
||||||
const data = await ctx.page.evaluate(`
|
const data = await ctx.page.evaluate(`
|
||||||
document.styleSheets[0].insertRule("@font-face {font-family: Kongtext; src: url(/kongtext.regular.ttf) format('truetype'); unicode-range: U+00A0-00FF}", 0);
|
document.styleSheets[0].insertRule("@font-face {font-family: Kongtext; src: url(/fonts/kongtext.regular.ttf) format('truetype'); unicode-range: U+00A0-00FF}", 0);
|
||||||
`);
|
`);
|
||||||
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'unloaded' }]);
|
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'unloaded' }]);
|
||||||
|
|
||||||
@@ -88,7 +88,11 @@ test.describe('WebFontsAddon', () => {
|
|||||||
|
|
||||||
// safari loads the font, firefox & chrome dont
|
// safari loads the font, firefox & chrome dont
|
||||||
if (browser.browserType().name() === 'webkit') {
|
if (browser.browserType().name() === 'webkit') {
|
||||||
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'loaded' }]);
|
try {
|
||||||
|
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'loading' }]);
|
||||||
|
} catch (e) {
|
||||||
|
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'loaded' }]);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'unloaded' }]);
|
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'unloaded' }]);
|
||||||
}
|
}
|
||||||
@@ -103,7 +107,10 @@ test.describe('WebFontsAddon', () => {
|
|||||||
window.helperTerm.open(term.element);
|
window.helperTerm.open(term.element);
|
||||||
`);
|
`);
|
||||||
await timeout(100);
|
await timeout(100);
|
||||||
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'loaded' }]);
|
if (browser.browserType().name() !== 'webkit') {
|
||||||
|
// safari sometimes reports 'unloadeed'?
|
||||||
|
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'loaded' }]);
|
||||||
|
}
|
||||||
|
|
||||||
// cleanup this messy test case
|
// cleanup this messy test case
|
||||||
await ctx.page.evaluate(`
|
await ctx.page.evaluate(`
|
||||||
|
|||||||
@@ -10,13 +10,15 @@
|
|||||||
"outDir": "../out-test",
|
"outDir": "../out-test",
|
||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"removeComments": true,
|
"removeComments": true,
|
||||||
"baseUrl": ".",
|
|
||||||
"paths": {
|
"paths": {
|
||||||
"common/*": [
|
"common/*": [
|
||||||
"../../../src/common/*"
|
"../../../src/common/*"
|
||||||
],
|
],
|
||||||
"browser/*": [
|
"browser/*": [
|
||||||
"../../../src/browser/*"
|
"../../../src/browser/*"
|
||||||
|
],
|
||||||
|
"*": [
|
||||||
|
"./*"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"strict": true,
|
"strict": true,
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
"xterm.js"
|
"xterm.js"
|
||||||
],
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "../../node_modules/.bin/tsc -p .",
|
"build": "../../node_modules/.bin/tsgo -p .",
|
||||||
"prepackage": "npm run build",
|
"prepackage": "npm run build",
|
||||||
"package": "../../node_modules/.bin/webpack",
|
"package": "../../node_modules/.bin/webpack",
|
||||||
"prepublishOnly": "npm run package",
|
"prepublishOnly": "npm run package",
|
||||||
|
|||||||
@@ -10,13 +10,15 @@
|
|||||||
"outDir": "../out-test",
|
"outDir": "../out-test",
|
||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"removeComments": true,
|
"removeComments": true,
|
||||||
"baseUrl": ".",
|
|
||||||
"paths": {
|
"paths": {
|
||||||
"common/*": [
|
"common/*": [
|
||||||
"../../../src/common/*"
|
"../../../src/common/*"
|
||||||
],
|
],
|
||||||
"browser/*": [
|
"browser/*": [
|
||||||
"../../../src/browser/*"
|
"../../../src/browser/*"
|
||||||
|
],
|
||||||
|
"*": [
|
||||||
|
"./*"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"strict": true,
|
"strict": true,
|
||||||
|
|||||||
@@ -17,7 +17,7 @@
|
|||||||
"xterm.js"
|
"xterm.js"
|
||||||
],
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "../../node_modules/.bin/tsc -p .",
|
"build": "../../node_modules/.bin/tsgo -p .",
|
||||||
"prepackage": "npm run build",
|
"prepackage": "npm run build",
|
||||||
"package": "../../node_modules/.bin/webpack",
|
"package": "../../node_modules/.bin/webpack",
|
||||||
"prepublishOnly": "npm run package",
|
"prepublishOnly": "npm run package",
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { ICellData } from 'common/Types';
|
|||||||
import { Terminal } from '@xterm/xterm';
|
import { Terminal } from '@xterm/xterm';
|
||||||
import { rgba } from 'common/Color';
|
import { rgba } from 'common/Color';
|
||||||
import { treatGlyphAsBackgroundColor } from 'browser/renderer/shared/RendererUtils';
|
import { treatGlyphAsBackgroundColor } from 'browser/renderer/shared/RendererUtils';
|
||||||
|
import { blockPatternCodepoints } from './customGlyphs/CustomGlyphDefinitions';
|
||||||
|
|
||||||
// Work variables to avoid garbage collection
|
// Work variables to avoid garbage collection
|
||||||
let $fg = 0;
|
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
|
* 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.
|
* 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.bg = cell.bg;
|
||||||
this.result.fg = cell.fg;
|
this.result.fg = cell.fg;
|
||||||
this.result.ext = cell.bg & BgFlags.HAS_EXTENDED ? cell.extended.ext : 0;
|
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));
|
const lineWidth = Math.max(1, Math.floor(this._optionService.rawOptions.fontSize * this._coreBrowserService.dpr / 15));
|
||||||
$variantOffset = x * deviceCellWidth % (Math.round(lineWidth) * 2);
|
$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
|
// Apply decorations on the bottom layer
|
||||||
this._decorationService.forEachDecorationAtCell(x, y, 'bottom', d => {
|
this._decorationService.forEachDecorationAtCell(x, y, 'bottom', d => {
|
||||||
if (d.backgroundColorRGB) {
|
if (d.backgroundColorRGB) {
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { ITerminalOptions, Terminal } from '@xterm/xterm';
|
|||||||
import { ITerminal, ReadonlyColorSet } from 'browser/Types';
|
import { ITerminal, ReadonlyColorSet } from 'browser/Types';
|
||||||
import { ICharAtlasConfig, ITextureAtlas } from './Types';
|
import { ICharAtlasConfig, ITextureAtlas } from './Types';
|
||||||
import { generateConfig, configEquals } from './CharAtlasUtils';
|
import { generateConfig, configEquals } from './CharAtlasUtils';
|
||||||
|
import type { ILogService } from 'common/services/Services';
|
||||||
|
|
||||||
interface ITextureAtlasCacheEntry {
|
interface ITextureAtlasCacheEntry {
|
||||||
atlas: ITextureAtlas;
|
atlas: ITextureAtlas;
|
||||||
@@ -67,8 +68,9 @@ export function acquireTextureAtlas(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const core: ITerminal = (terminal as any)._core;
|
const core: ITerminal = (terminal as any)._core;
|
||||||
|
const logService = (core as any)._logService as ILogService;
|
||||||
const newEntry: ITextureAtlasCacheEntry = {
|
const newEntry: ITextureAtlasCacheEntry = {
|
||||||
atlas: new TextureAtlas(document, newConfig, core.unicodeService),
|
atlas: new TextureAtlas(document, newConfig, core.unicodeService, logService),
|
||||||
config: newConfig,
|
config: newConfig,
|
||||||
ownedBy: [terminal]
|
ownedBy: [terminal]
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 The xterm.js authors. All rights reserved.
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { assert } from 'chai';
|
||||||
|
import { configEquals } from './CharAtlasUtils';
|
||||||
|
import { ICharAtlasConfig } from './Types';
|
||||||
|
import { NULL_COLOR } from 'common/Color';
|
||||||
|
import { IColor } from 'common/Types';
|
||||||
|
|
||||||
|
function createTestConfig(overrides: Partial<ICharAtlasConfig> = {}): ICharAtlasConfig {
|
||||||
|
const color: IColor = { css: '#ffffff', rgba: 0xffffffff };
|
||||||
|
const contrastCache = {
|
||||||
|
clear: () => {},
|
||||||
|
setCss: () => {},
|
||||||
|
getCss: () => undefined,
|
||||||
|
setColor: () => {},
|
||||||
|
getColor: () => undefined
|
||||||
|
};
|
||||||
|
const colors = {
|
||||||
|
foreground: color,
|
||||||
|
background: color,
|
||||||
|
cursor: NULL_COLOR,
|
||||||
|
cursorAccent: NULL_COLOR,
|
||||||
|
selectionForeground: undefined,
|
||||||
|
selectionBackgroundTransparent: NULL_COLOR,
|
||||||
|
selectionBackgroundOpaque: NULL_COLOR,
|
||||||
|
selectionInactiveBackgroundTransparent: NULL_COLOR,
|
||||||
|
selectionInactiveBackgroundOpaque: NULL_COLOR,
|
||||||
|
overviewRulerBorder: NULL_COLOR,
|
||||||
|
scrollbarSliderBackground: NULL_COLOR,
|
||||||
|
scrollbarSliderHoverBackground: NULL_COLOR,
|
||||||
|
scrollbarSliderActiveBackground: NULL_COLOR,
|
||||||
|
ansi: new Array(256).fill(color),
|
||||||
|
contrastCache,
|
||||||
|
halfContrastCache: contrastCache
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
customGlyphs: true,
|
||||||
|
devicePixelRatio: 1,
|
||||||
|
deviceMaxTextureSize: 4096,
|
||||||
|
letterSpacing: 0,
|
||||||
|
lineHeight: 1,
|
||||||
|
fontSize: 15,
|
||||||
|
fontFamily: 'monospace',
|
||||||
|
fontWeight: 'normal',
|
||||||
|
fontWeightBold: 'bold',
|
||||||
|
deviceCellWidth: 10,
|
||||||
|
deviceCellHeight: 20,
|
||||||
|
deviceCharWidth: 8,
|
||||||
|
deviceCharHeight: 16,
|
||||||
|
allowTransparency: false,
|
||||||
|
drawBoldTextInBrightColors: true,
|
||||||
|
minimumContrastRatio: 1,
|
||||||
|
colors,
|
||||||
|
...overrides
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('CharAtlasUtils', () => {
|
||||||
|
describe('configEquals', () => {
|
||||||
|
it('should return true for identical configs', () => {
|
||||||
|
const a = createTestConfig();
|
||||||
|
const b = createTestConfig();
|
||||||
|
assert.ok(configEquals(a, b));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return false when deviceMaxTextureSize differs', () => {
|
||||||
|
const a = createTestConfig();
|
||||||
|
const b = createTestConfig({ deviceMaxTextureSize: 8192 });
|
||||||
|
assert.ok(!configEquals(a, b));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return false when deviceCellWidth differs', () => {
|
||||||
|
const a = createTestConfig();
|
||||||
|
const b = createTestConfig({ deviceCellWidth: 11 });
|
||||||
|
assert.ok(!configEquals(a, b));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return false when deviceCellHeight differs', () => {
|
||||||
|
const a = createTestConfig();
|
||||||
|
const b = createTestConfig({ deviceCellHeight: 21 });
|
||||||
|
assert.ok(!configEquals(a, b));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -59,6 +59,7 @@ export function configEquals(a: ICharAtlasConfig, b: ICharAtlasConfig): boolean
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
return a.devicePixelRatio === b.devicePixelRatio &&
|
return a.devicePixelRatio === b.devicePixelRatio &&
|
||||||
|
a.deviceMaxTextureSize === b.deviceMaxTextureSize &&
|
||||||
a.customGlyphs === b.customGlyphs &&
|
a.customGlyphs === b.customGlyphs &&
|
||||||
a.lineHeight === b.lineHeight &&
|
a.lineHeight === b.lineHeight &&
|
||||||
a.letterSpacing === b.letterSpacing &&
|
a.letterSpacing === b.letterSpacing &&
|
||||||
@@ -67,6 +68,8 @@ export function configEquals(a: ICharAtlasConfig, b: ICharAtlasConfig): boolean
|
|||||||
a.fontWeight === b.fontWeight &&
|
a.fontWeight === b.fontWeight &&
|
||||||
a.fontWeightBold === b.fontWeightBold &&
|
a.fontWeightBold === b.fontWeightBold &&
|
||||||
a.allowTransparency === b.allowTransparency &&
|
a.allowTransparency === b.allowTransparency &&
|
||||||
|
a.deviceCellWidth === b.deviceCellWidth &&
|
||||||
|
a.deviceCellHeight === b.deviceCellHeight &&
|
||||||
a.deviceCharWidth === b.deviceCharWidth &&
|
a.deviceCharWidth === b.deviceCharWidth &&
|
||||||
a.deviceCharHeight === b.deviceCharHeight &&
|
a.deviceCharHeight === b.deviceCharHeight &&
|
||||||
a.drawBoldTextInBrightColors === b.drawBoldTextInBrightColors &&
|
a.drawBoldTextInBrightColors === b.drawBoldTextInBrightColors &&
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import { Disposable, toDisposable } from 'common/Lifecycle';
|
|||||||
import { Terminal } from '@xterm/xterm';
|
import { Terminal } from '@xterm/xterm';
|
||||||
import { IRenderModel, IWebGL2RenderingContext, IWebGLVertexArrayObject, type IRasterizedGlyph, type ITextureAtlas } from './Types';
|
import { IRenderModel, IWebGL2RenderingContext, IWebGLVertexArrayObject, type IRasterizedGlyph, type ITextureAtlas } from './Types';
|
||||||
import { createProgram, GLTexture, PROJECTION_MATRIX } from './WebglUtils';
|
import { createProgram, GLTexture, PROJECTION_MATRIX } from './WebglUtils';
|
||||||
import type { IOptionsService } from 'common/services/Services';
|
import type { ILogService, IOptionsService } from 'common/services/Services';
|
||||||
import { allowRescaling, throwIfFalsy } from 'browser/renderer/shared/RendererUtils';
|
import { allowRescaling, throwIfFalsy } from 'browser/renderer/shared/RendererUtils';
|
||||||
|
|
||||||
interface IVertices {
|
interface IVertices {
|
||||||
@@ -78,9 +78,11 @@ void main() {
|
|||||||
}`);
|
}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const INDICES_PER_CELL = 11;
|
const enum Constants {
|
||||||
const BYTES_PER_CELL = INDICES_PER_CELL * Float32Array.BYTES_PER_ELEMENT;
|
INDICES_PER_CELL = 11,
|
||||||
const CELL_POSITION_INDICES = 2;
|
BYTES_PER_CELL = INDICES_PER_CELL * 4/* Float32Array.BYTES_PER_ELEMENT */,
|
||||||
|
CELL_POSITION_INDICES = 2
|
||||||
|
}
|
||||||
|
|
||||||
// Work variables to avoid garbage collection
|
// Work variables to avoid garbage collection
|
||||||
let $i = 0;
|
let $i = 0;
|
||||||
@@ -112,7 +114,8 @@ export class GlyphRenderer extends Disposable {
|
|||||||
private readonly _terminal: Terminal,
|
private readonly _terminal: Terminal,
|
||||||
private readonly _gl: IWebGL2RenderingContext,
|
private readonly _gl: IWebGL2RenderingContext,
|
||||||
private _dimensions: IRenderDimensions,
|
private _dimensions: IRenderDimensions,
|
||||||
private readonly _optionsService: IOptionsService
|
private readonly _optionsService: IOptionsService,
|
||||||
|
private readonly _logService: ILogService
|
||||||
) {
|
) {
|
||||||
super();
|
super();
|
||||||
|
|
||||||
@@ -125,7 +128,7 @@ export class GlyphRenderer extends Disposable {
|
|||||||
TextureAtlas.maxTextureSize = throwIfFalsy(gl.getParameter(gl.MAX_TEXTURE_SIZE) as number | null);
|
TextureAtlas.maxTextureSize = throwIfFalsy(gl.getParameter(gl.MAX_TEXTURE_SIZE) as number | null);
|
||||||
}
|
}
|
||||||
|
|
||||||
this._program = throwIfFalsy(createProgram(gl, vertexShaderSource, createFragmentShaderSource(TextureAtlas.maxAtlasPages)));
|
this._program = throwIfFalsy(createProgram(gl, vertexShaderSource, createFragmentShaderSource(TextureAtlas.maxAtlasPages), this._logService));
|
||||||
this._register(toDisposable(() => gl.deleteProgram(this._program)));
|
this._register(toDisposable(() => gl.deleteProgram(this._program)));
|
||||||
|
|
||||||
// Uniform locations
|
// Uniform locations
|
||||||
@@ -134,8 +137,9 @@ export class GlyphRenderer extends Disposable {
|
|||||||
this._textureLocation = throwIfFalsy(gl.getUniformLocation(this._program, 'u_texture'));
|
this._textureLocation = throwIfFalsy(gl.getUniformLocation(this._program, 'u_texture'));
|
||||||
|
|
||||||
// Create and set the vertex array object
|
// Create and set the vertex array object
|
||||||
this._vertexArrayObject = gl.createVertexArray();
|
const vertexArrayObject = this._vertexArrayObject = gl.createVertexArray();
|
||||||
gl.bindVertexArray(this._vertexArrayObject);
|
this._register(toDisposable(() => gl.deleteVertexArray(vertexArrayObject)));
|
||||||
|
gl.bindVertexArray(vertexArrayObject);
|
||||||
|
|
||||||
// Setup a_unitquad, this defines the 4 vertices of a rectangle
|
// Setup a_unitquad, this defines the 4 vertices of a rectangle
|
||||||
const unitQuadVertices = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]);
|
const unitQuadVertices = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]);
|
||||||
@@ -160,22 +164,22 @@ export class GlyphRenderer extends Disposable {
|
|||||||
this._register(toDisposable(() => gl.deleteBuffer(this._attributesBuffer)));
|
this._register(toDisposable(() => gl.deleteBuffer(this._attributesBuffer)));
|
||||||
gl.bindBuffer(gl.ARRAY_BUFFER, this._attributesBuffer);
|
gl.bindBuffer(gl.ARRAY_BUFFER, this._attributesBuffer);
|
||||||
gl.enableVertexAttribArray(VertexAttribLocations.OFFSET);
|
gl.enableVertexAttribArray(VertexAttribLocations.OFFSET);
|
||||||
gl.vertexAttribPointer(VertexAttribLocations.OFFSET, 2, gl.FLOAT, false, BYTES_PER_CELL, 0);
|
gl.vertexAttribPointer(VertexAttribLocations.OFFSET, 2, gl.FLOAT, false, Constants.BYTES_PER_CELL, 0);
|
||||||
gl.vertexAttribDivisor(VertexAttribLocations.OFFSET, 1);
|
gl.vertexAttribDivisor(VertexAttribLocations.OFFSET, 1);
|
||||||
gl.enableVertexAttribArray(VertexAttribLocations.SIZE);
|
gl.enableVertexAttribArray(VertexAttribLocations.SIZE);
|
||||||
gl.vertexAttribPointer(VertexAttribLocations.SIZE, 2, gl.FLOAT, false, BYTES_PER_CELL, 2 * Float32Array.BYTES_PER_ELEMENT);
|
gl.vertexAttribPointer(VertexAttribLocations.SIZE, 2, gl.FLOAT, false, Constants.BYTES_PER_CELL, 2 * Float32Array.BYTES_PER_ELEMENT);
|
||||||
gl.vertexAttribDivisor(VertexAttribLocations.SIZE, 1);
|
gl.vertexAttribDivisor(VertexAttribLocations.SIZE, 1);
|
||||||
gl.enableVertexAttribArray(VertexAttribLocations.TEXPAGE);
|
gl.enableVertexAttribArray(VertexAttribLocations.TEXPAGE);
|
||||||
gl.vertexAttribPointer(VertexAttribLocations.TEXPAGE, 1, gl.FLOAT, false, BYTES_PER_CELL, 4 * Float32Array.BYTES_PER_ELEMENT);
|
gl.vertexAttribPointer(VertexAttribLocations.TEXPAGE, 1, gl.FLOAT, false, Constants.BYTES_PER_CELL, 4 * Float32Array.BYTES_PER_ELEMENT);
|
||||||
gl.vertexAttribDivisor(VertexAttribLocations.TEXPAGE, 1);
|
gl.vertexAttribDivisor(VertexAttribLocations.TEXPAGE, 1);
|
||||||
gl.enableVertexAttribArray(VertexAttribLocations.TEXCOORD);
|
gl.enableVertexAttribArray(VertexAttribLocations.TEXCOORD);
|
||||||
gl.vertexAttribPointer(VertexAttribLocations.TEXCOORD, 2, gl.FLOAT, false, BYTES_PER_CELL, 5 * Float32Array.BYTES_PER_ELEMENT);
|
gl.vertexAttribPointer(VertexAttribLocations.TEXCOORD, 2, gl.FLOAT, false, Constants.BYTES_PER_CELL, 5 * Float32Array.BYTES_PER_ELEMENT);
|
||||||
gl.vertexAttribDivisor(VertexAttribLocations.TEXCOORD, 1);
|
gl.vertexAttribDivisor(VertexAttribLocations.TEXCOORD, 1);
|
||||||
gl.enableVertexAttribArray(VertexAttribLocations.TEXSIZE);
|
gl.enableVertexAttribArray(VertexAttribLocations.TEXSIZE);
|
||||||
gl.vertexAttribPointer(VertexAttribLocations.TEXSIZE, 2, gl.FLOAT, false, BYTES_PER_CELL, 7 * Float32Array.BYTES_PER_ELEMENT);
|
gl.vertexAttribPointer(VertexAttribLocations.TEXSIZE, 2, gl.FLOAT, false, Constants.BYTES_PER_CELL, 7 * Float32Array.BYTES_PER_ELEMENT);
|
||||||
gl.vertexAttribDivisor(VertexAttribLocations.TEXSIZE, 1);
|
gl.vertexAttribDivisor(VertexAttribLocations.TEXSIZE, 1);
|
||||||
gl.enableVertexAttribArray(VertexAttribLocations.CELL_POSITION);
|
gl.enableVertexAttribArray(VertexAttribLocations.CELL_POSITION);
|
||||||
gl.vertexAttribPointer(VertexAttribLocations.CELL_POSITION, 2, gl.FLOAT, false, BYTES_PER_CELL, 9 * Float32Array.BYTES_PER_ELEMENT);
|
gl.vertexAttribPointer(VertexAttribLocations.CELL_POSITION, 2, gl.FLOAT, false, Constants.BYTES_PER_CELL, 9 * Float32Array.BYTES_PER_ELEMENT);
|
||||||
gl.vertexAttribDivisor(VertexAttribLocations.CELL_POSITION, 1);
|
gl.vertexAttribDivisor(VertexAttribLocations.CELL_POSITION, 1);
|
||||||
|
|
||||||
// Setup static uniforms
|
// Setup static uniforms
|
||||||
@@ -222,12 +226,12 @@ export class GlyphRenderer extends Disposable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private _updateCell(array: Float32Array, x: number, y: number, code: number | undefined, bg: number, fg: number, ext: number, chars: string, width: number, lastBg: number): void {
|
private _updateCell(array: Float32Array, x: number, y: number, code: number | undefined, bg: number, fg: number, ext: number, chars: string, width: number, lastBg: number): void {
|
||||||
$i = (y * this._terminal.cols + x) * INDICES_PER_CELL;
|
$i = (y * this._terminal.cols + x) * Constants.INDICES_PER_CELL;
|
||||||
|
|
||||||
// Exit early if this is a null character, allow space character to continue as it may have
|
// Exit early if this is a null character, allow space character to continue as it may have
|
||||||
// underline/strikethrough styles
|
// underline/strikethrough styles
|
||||||
if (code === NULL_CELL_CODE || code === undefined/* This is used for the right side of wide chars */) {
|
if (code === NULL_CELL_CODE || code === undefined/* This is used for the right side of wide chars */) {
|
||||||
array.fill(0, $i, $i + INDICES_PER_CELL - 1 - CELL_POSITION_INDICES);
|
array.fill(0, $i, $i + Constants.INDICES_PER_CELL - 1 - Constants.CELL_POSITION_INDICES);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -288,7 +292,7 @@ export class GlyphRenderer extends Disposable {
|
|||||||
|
|
||||||
public clear(): void {
|
public clear(): void {
|
||||||
const terminal = this._terminal;
|
const terminal = this._terminal;
|
||||||
const newCount = terminal.cols * terminal.rows * INDICES_PER_CELL;
|
const newCount = terminal.cols * terminal.rows * Constants.INDICES_PER_CELL;
|
||||||
|
|
||||||
// Clear vertices
|
// Clear vertices
|
||||||
if (this._vertices.count !== newCount) {
|
if (this._vertices.count !== newCount) {
|
||||||
@@ -310,7 +314,7 @@ export class GlyphRenderer extends Disposable {
|
|||||||
for (let x = 0; x < terminal.cols; x++) {
|
for (let x = 0; x < terminal.cols; x++) {
|
||||||
this._vertices.attributes[i + 9] = x / terminal.cols;
|
this._vertices.attributes[i + 9] = x / terminal.cols;
|
||||||
this._vertices.attributes[i + 10] = y / terminal.rows;
|
this._vertices.attributes[i + 10] = y / terminal.rows;
|
||||||
i += INDICES_PER_CELL;
|
i += Constants.INDICES_PER_CELL;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -346,8 +350,8 @@ export class GlyphRenderer extends Disposable {
|
|||||||
// - So we don't send vertices for all the line-ending whitespace to the GPU
|
// - So we don't send vertices for all the line-ending whitespace to the GPU
|
||||||
let bufferLength = 0;
|
let bufferLength = 0;
|
||||||
for (let y = 0; y < renderModel.lineLengths.length; y++) {
|
for (let y = 0; y < renderModel.lineLengths.length; y++) {
|
||||||
const si = y * this._terminal.cols * INDICES_PER_CELL;
|
const si = y * this._terminal.cols * Constants.INDICES_PER_CELL;
|
||||||
const sub = this._vertices.attributes.subarray(si, si + renderModel.lineLengths[y] * INDICES_PER_CELL);
|
const sub = this._vertices.attributes.subarray(si, si + renderModel.lineLengths[y] * Constants.INDICES_PER_CELL);
|
||||||
activeBuffer.set(sub, bufferLength);
|
activeBuffer.set(sub, bufferLength);
|
||||||
bufferLength += sub.length;
|
bufferLength += sub.length;
|
||||||
}
|
}
|
||||||
@@ -356,7 +360,9 @@ export class GlyphRenderer extends Disposable {
|
|||||||
gl.bindBuffer(gl.ARRAY_BUFFER, this._attributesBuffer);
|
gl.bindBuffer(gl.ARRAY_BUFFER, this._attributesBuffer);
|
||||||
gl.bufferData(gl.ARRAY_BUFFER, activeBuffer.subarray(0, bufferLength), gl.STREAM_DRAW);
|
gl.bufferData(gl.ARRAY_BUFFER, activeBuffer.subarray(0, bufferLength), gl.STREAM_DRAW);
|
||||||
|
|
||||||
// Bind the atlas page texture if they have changed
|
// Bind the atlas page texture if they have changed. AtlasPage.version is globally
|
||||||
|
// monotonic, so a page object swap at the same index (which happens after a page merge)
|
||||||
|
// is detected by the same comparison.
|
||||||
for (let i = 0; i < this._atlas.pages.length; i++) {
|
for (let i = 0; i < this._atlas.pages.length; i++) {
|
||||||
if (this._atlas.pages[i].version !== this._atlasTextures[i].version) {
|
if (this._atlas.pages[i].version !== this._atlasTextures[i].version) {
|
||||||
this._bindAtlasPageTexture(gl, this._atlas, i);
|
this._bindAtlasPageTexture(gl, this._atlas, i);
|
||||||
@@ -364,11 +370,15 @@ export class GlyphRenderer extends Disposable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Draw the viewport
|
// Draw the viewport
|
||||||
gl.drawElementsInstanced(gl.TRIANGLE_STRIP, 4, gl.UNSIGNED_BYTE, 0, bufferLength / INDICES_PER_CELL);
|
gl.drawElementsInstanced(gl.TRIANGLE_STRIP, 4, gl.UNSIGNED_BYTE, 0, bufferLength / Constants.INDICES_PER_CELL);
|
||||||
}
|
}
|
||||||
|
|
||||||
public setAtlas(atlas: ITextureAtlas): void {
|
public setAtlas(atlas: ITextureAtlas): void {
|
||||||
this._atlas = atlas;
|
this._atlas = atlas;
|
||||||
|
this.invalidateAtlasTextures();
|
||||||
|
}
|
||||||
|
|
||||||
|
public invalidateAtlasTextures(): void {
|
||||||
for (const glTexture of this._atlasTextures) {
|
for (const glTexture of this._atlasTextures) {
|
||||||
glTexture.version = -1;
|
glTexture.version = -1;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,10 +10,11 @@ import { Attributes, FgFlags } from 'common/buffer/Constants';
|
|||||||
import { Disposable, toDisposable } from 'common/Lifecycle';
|
import { Disposable, toDisposable } from 'common/Lifecycle';
|
||||||
import { IColor } from 'common/Types';
|
import { IColor } from 'common/Types';
|
||||||
import { Terminal } from '@xterm/xterm';
|
import { Terminal } from '@xterm/xterm';
|
||||||
import { RENDER_MODEL_BG_OFFSET, RENDER_MODEL_FG_OFFSET, RENDER_MODEL_INDICIES_PER_CELL } from './RenderModel';
|
import { RenderModelConstants } from './RenderModel';
|
||||||
import { IRenderModel, IWebGL2RenderingContext, IWebGLVertexArrayObject } from './Types';
|
import { IRenderModel, IWebGL2RenderingContext, IWebGLVertexArrayObject } from './Types';
|
||||||
import { createProgram, expandFloat32Array, PROJECTION_MATRIX } from './WebglUtils';
|
import { createProgram, expandFloat32Array, PROJECTION_MATRIX } from './WebglUtils';
|
||||||
import { throwIfFalsy } from 'browser/renderer/shared/RendererUtils';
|
import { throwIfFalsy } from 'browser/renderer/shared/RendererUtils';
|
||||||
|
import type { ILogService } from 'common/services/Services';
|
||||||
|
|
||||||
const enum VertexAttribLocations {
|
const enum VertexAttribLocations {
|
||||||
POSITION = 0,
|
POSITION = 0,
|
||||||
@@ -89,21 +90,23 @@ export class RectangleRenderer extends Disposable {
|
|||||||
private _terminal: Terminal,
|
private _terminal: Terminal,
|
||||||
private _gl: IWebGL2RenderingContext,
|
private _gl: IWebGL2RenderingContext,
|
||||||
private _dimensions: IRenderDimensions,
|
private _dimensions: IRenderDimensions,
|
||||||
private readonly _themeService: IThemeService
|
private readonly _themeService: IThemeService,
|
||||||
|
private readonly _logService: ILogService
|
||||||
) {
|
) {
|
||||||
super();
|
super();
|
||||||
|
|
||||||
const gl = this._gl;
|
const gl = this._gl;
|
||||||
|
|
||||||
this._program = throwIfFalsy(createProgram(gl, vertexShaderSource, fragmentShaderSource));
|
this._program = throwIfFalsy(createProgram(gl, vertexShaderSource, fragmentShaderSource, this._logService));
|
||||||
this._register(toDisposable(() => gl.deleteProgram(this._program)));
|
this._register(toDisposable(() => gl.deleteProgram(this._program)));
|
||||||
|
|
||||||
// Uniform locations
|
// Uniform locations
|
||||||
this._projectionLocation = throwIfFalsy(gl.getUniformLocation(this._program, 'u_projection'));
|
this._projectionLocation = throwIfFalsy(gl.getUniformLocation(this._program, 'u_projection'));
|
||||||
|
|
||||||
// Create and set the vertex array object
|
// Create and set the vertex array object
|
||||||
this._vertexArrayObject = gl.createVertexArray();
|
const vertexArrayObject = this._vertexArrayObject = gl.createVertexArray();
|
||||||
gl.bindVertexArray(this._vertexArrayObject);
|
this._register(toDisposable(() => gl.deleteVertexArray(vertexArrayObject)));
|
||||||
|
gl.bindVertexArray(vertexArrayObject);
|
||||||
|
|
||||||
// Setup a_unitquad, this defines the 4 vertices of a rectangle
|
// Setup a_unitquad, this defines the 4 vertices of a rectangle
|
||||||
const unitQuadVertices = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]);
|
const unitQuadVertices = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]);
|
||||||
@@ -217,9 +220,9 @@ export class RectangleRenderer extends Disposable {
|
|||||||
currentFg = 0;
|
currentFg = 0;
|
||||||
currentInverse = false;
|
currentInverse = false;
|
||||||
for (x = 0; x < terminal.cols; x++) {
|
for (x = 0; x < terminal.cols; x++) {
|
||||||
modelIndex = ((y * terminal.cols) + x) * RENDER_MODEL_INDICIES_PER_CELL;
|
modelIndex = ((y * terminal.cols) + x) * RenderModelConstants.INDICIES_PER_CELL;
|
||||||
bg = model.cells[modelIndex + RENDER_MODEL_BG_OFFSET];
|
bg = model.cells[modelIndex + RenderModelConstants.BG_OFFSET];
|
||||||
fg = model.cells[modelIndex + RENDER_MODEL_FG_OFFSET];
|
fg = model.cells[modelIndex + RenderModelConstants.FG_OFFSET];
|
||||||
inverse = !!(fg & FgFlags.INVERSE);
|
inverse = !!(fg & FgFlags.INVERSE);
|
||||||
if (bg !== currentBg || (fg !== currentFg && (currentInverse || inverse))) {
|
if (bg !== currentBg || (fg !== currentFg && (currentInverse || inverse))) {
|
||||||
// A rectangle needs to be drawn if going from non-default to another color
|
// A rectangle needs to be drawn if going from non-default to another color
|
||||||
@@ -336,8 +339,9 @@ export class RectangleRenderer extends Disposable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (vertices.attributes.length < offset + 4) {
|
if (vertices.attributes.length < offset + INDICES_PER_RECTANGLE) {
|
||||||
vertices.attributes = expandFloat32Array(vertices.attributes, this._terminal.rows * this._terminal.cols * INDICES_PER_RECTANGLE);
|
// +1 for the viewport-clear rectangle at offset 0.
|
||||||
|
vertices.attributes = expandFloat32Array(vertices.attributes, (this._terminal.rows * this._terminal.cols + 1) * INDICES_PER_RECTANGLE);
|
||||||
}
|
}
|
||||||
$x1 = startX * this._dimensions.device.cell.width;
|
$x1 = startX * this._dimensions.device.cell.width;
|
||||||
$y1 = y * this._dimensions.device.cell.height;
|
$y1 = y * this._dimensions.device.cell.height;
|
||||||
|
|||||||
@@ -7,10 +7,12 @@ import { ICursorRenderModel, IRenderModel } from './Types';
|
|||||||
import { ISelectionRenderModel } from 'browser/renderer/shared/Types';
|
import { ISelectionRenderModel } from 'browser/renderer/shared/Types';
|
||||||
import { createSelectionRenderModel } from 'browser/renderer/shared/SelectionRenderModel';
|
import { createSelectionRenderModel } from 'browser/renderer/shared/SelectionRenderModel';
|
||||||
|
|
||||||
export const RENDER_MODEL_INDICIES_PER_CELL = 4;
|
export const enum RenderModelConstants {
|
||||||
export const RENDER_MODEL_BG_OFFSET = 1;
|
INDICIES_PER_CELL = 4,
|
||||||
export const RENDER_MODEL_FG_OFFSET = 2;
|
BG_OFFSET = 1,
|
||||||
export const RENDER_MODEL_EXT_OFFSET = 3;
|
FG_OFFSET = 2,
|
||||||
|
EXT_OFFSET = 3
|
||||||
|
}
|
||||||
|
|
||||||
export const COMBINED_CHAR_BIT_MASK = 0x80000000;
|
export const COMBINED_CHAR_BIT_MASK = 0x80000000;
|
||||||
|
|
||||||
@@ -27,7 +29,7 @@ export class RenderModel implements IRenderModel {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public resize(cols: number, rows: number): void {
|
public resize(cols: number, rows: number): void {
|
||||||
const indexCount = cols * rows * RENDER_MODEL_INDICIES_PER_CELL;
|
const indexCount = cols * rows * RenderModelConstants.INDICIES_PER_CELL;
|
||||||
if (indexCount !== this.cells.length) {
|
if (indexCount !== this.cells.length) {
|
||||||
this.cells = new Uint32Array(indexCount);
|
this.cells = new Uint32Array(indexCount);
|
||||||
this.lineLengths = new Uint32Array(rows);
|
this.lineLengths = new Uint32Array(rows);
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import { IdleTaskQueue } from 'common/TaskQueue';
|
|||||||
import { IColor } from 'common/Types';
|
import { IColor } from 'common/Types';
|
||||||
import { AttributeData } from 'common/buffer/AttributeData';
|
import { AttributeData } from 'common/buffer/AttributeData';
|
||||||
import { Attributes, DEFAULT_COLOR, DEFAULT_EXT, UnderlineStyle } from 'common/buffer/Constants';
|
import { Attributes, DEFAULT_COLOR, DEFAULT_EXT, UnderlineStyle } from 'common/buffer/Constants';
|
||||||
import { IUnicodeService } from 'common/services/Services';
|
import { ILogService, IUnicodeService } from 'common/services/Services';
|
||||||
import { Emitter } from 'common/Event';
|
import { Emitter } from 'common/Event';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -88,7 +88,8 @@ export class TextureAtlas implements ITextureAtlas {
|
|||||||
constructor(
|
constructor(
|
||||||
private readonly _document: Document,
|
private readonly _document: Document,
|
||||||
private readonly _config: ICharAtlasConfig,
|
private readonly _config: ICharAtlasConfig,
|
||||||
private readonly _unicodeService: IUnicodeService
|
private readonly _unicodeService: IUnicodeService,
|
||||||
|
private readonly _logService: ILogService
|
||||||
) {
|
) {
|
||||||
this._createNewPage();
|
this._createNewPage();
|
||||||
this._tmpCanvas = createCanvas(
|
this._tmpCanvas = createCanvas(
|
||||||
@@ -108,6 +109,7 @@ export class TextureAtlas implements ITextureAtlas {
|
|||||||
page.canvas.remove();
|
page.canvas.remove();
|
||||||
}
|
}
|
||||||
this._onAddTextureAtlasCanvas.dispose();
|
this._onAddTextureAtlasCanvas.dispose();
|
||||||
|
this._onRemoveTextureAtlasCanvas.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
public warmUp(): void {
|
public warmUp(): void {
|
||||||
@@ -119,7 +121,7 @@ export class TextureAtlas implements ITextureAtlas {
|
|||||||
|
|
||||||
private _doWarmUp(): void {
|
private _doWarmUp(): void {
|
||||||
// Pre-fill with ASCII 33-126, this is not urgent and done in idle callbacks
|
// 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++) {
|
for (let i = 33; i < 126; i++) {
|
||||||
queue.enqueue(() => {
|
queue.enqueue(() => {
|
||||||
if (!this._cacheMap.get(i, DEFAULT_COLOR, DEFAULT_COLOR, DEFAULT_EXT)) {
|
if (!this._cacheMap.get(i, DEFAULT_COLOR, DEFAULT_COLOR, DEFAULT_EXT)) {
|
||||||
@@ -132,7 +134,9 @@ export class TextureAtlas implements ITextureAtlas {
|
|||||||
|
|
||||||
private _requestClearModel = false;
|
private _requestClearModel = false;
|
||||||
public beginFrame(): boolean {
|
public beginFrame(): boolean {
|
||||||
return this._requestClearModel;
|
const result = this._requestClearModel;
|
||||||
|
this._requestClearModel = false;
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
public clearTexture(): void {
|
public clearTexture(): void {
|
||||||
@@ -192,7 +196,7 @@ export class TextureAtlas implements ITextureAtlas {
|
|||||||
|
|
||||||
// Merge into the new page
|
// Merge into the new page
|
||||||
const mergedPage = this._mergePages(mergingPages, mergedPageIndex);
|
const mergedPage = this._mergePages(mergingPages, mergedPageIndex);
|
||||||
mergedPage.version++;
|
mergedPage.version = ++AtlasPage.nextVersion;
|
||||||
|
|
||||||
// Delete the pages, shifting glyph texture pages as needed
|
// Delete the pages, shifting glyph texture pages as needed
|
||||||
for (let i = sortedMergingPagesIndexes.length - 1; i >= 0; i--) {
|
for (let i = sortedMergingPagesIndexes.length - 1; i >= 0; i--) {
|
||||||
@@ -250,7 +254,7 @@ export class TextureAtlas implements ITextureAtlas {
|
|||||||
for (const g of adjustingPage.glyphs) {
|
for (const g of adjustingPage.glyphs) {
|
||||||
g.texturePage--;
|
g.texturePage--;
|
||||||
}
|
}
|
||||||
adjustingPage.version++;
|
adjustingPage.version = ++AtlasPage.nextVersion;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -525,7 +529,8 @@ export class TextureAtlas implements ITextureAtlas {
|
|||||||
// Draw custom characters if applicable
|
// Draw custom characters if applicable
|
||||||
let customGlyph = false;
|
let customGlyph = false;
|
||||||
if (this._config.customGlyphs !== 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, this._logService, backgroundColor.css, variantOffset);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Whether to clear pixels based on a threshold difference between the glyph color and the
|
// Whether to clear pixels based on a threshold difference between the glyph color and the
|
||||||
@@ -935,7 +940,7 @@ export class TextureAtlas implements ITextureAtlas {
|
|||||||
rasterizedGlyph.size.y
|
rasterizedGlyph.size.y
|
||||||
);
|
);
|
||||||
activePage.addGlyph(rasterizedGlyph);
|
activePage.addGlyph(rasterizedGlyph);
|
||||||
activePage.version++;
|
activePage.version = ++AtlasPage.nextVersion;
|
||||||
|
|
||||||
return rasterizedGlyph;
|
return rasterizedGlyph;
|
||||||
}
|
}
|
||||||
@@ -1045,9 +1050,13 @@ class AtlasPage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Used to check whether the canvas of the atlas page has changed.
|
* Monotonically increasing across all atlas pages globally. Used to detect when the texture
|
||||||
|
* unit at a given index needs to be re-uploaded — both for content changes within the same
|
||||||
|
* page and for a page object swap at the same index (which happens after a page merge,
|
||||||
|
* where a per-page counter could coincide with the previously-bound page's value).
|
||||||
*/
|
*/
|
||||||
public version = 0;
|
public static nextVersion: number = 0;
|
||||||
|
public version = ++AtlasPage.nextVersion;
|
||||||
|
|
||||||
// Texture atlas current positioning data. The texture packing strategy used is to fill from
|
// Texture atlas current positioning data. The texture packing strategy used is to fill from
|
||||||
// left-to-right and top-to-bottom. When the glyph being written is less than half of the current
|
// left-to-right and top-to-bottom. When the glyph being written is less than half of the current
|
||||||
@@ -1090,7 +1099,7 @@ class AtlasPage {
|
|||||||
this.currentRow.y = 0;
|
this.currentRow.y = 0;
|
||||||
this.currentRow.height = 0;
|
this.currentRow.height = 0;
|
||||||
this.fixedRows.length = 0;
|
this.fixedRows.length = 0;
|
||||||
this.version++;
|
this.version = ++AtlasPage.nextVersion;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ export interface ICursorRenderModel {
|
|||||||
export interface IWebGL2RenderingContext extends WebGLRenderingContext {
|
export interface IWebGL2RenderingContext extends WebGLRenderingContext {
|
||||||
vertexAttribDivisor(index: number, divisor: number): void;
|
vertexAttribDivisor(index: number, divisor: number): void;
|
||||||
createVertexArray(): IWebGLVertexArrayObject;
|
createVertexArray(): IWebGLVertexArrayObject;
|
||||||
|
deleteVertexArray(vao: IWebGLVertexArrayObject): void;
|
||||||
bindVertexArray(vao: IWebGLVertexArrayObject): void;
|
bindVertexArray(vao: IWebGLVertexArrayObject): void;
|
||||||
drawElementsInstanced(mode: number, count: number, type: number, offset: number, instanceCount: number): void;
|
drawElementsInstanced(mode: number, count: number, type: number, offset: number, instanceCount: number): void;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import { ICharacterJoinerService, ICharSizeService, ICoreBrowserService, IRender
|
|||||||
import { ITerminal } from 'browser/Types';
|
import { ITerminal } from 'browser/Types';
|
||||||
import { Disposable, toDisposable } from 'common/Lifecycle';
|
import { Disposable, toDisposable } from 'common/Lifecycle';
|
||||||
import { getSafariVersion, isSafari } from 'common/Platform';
|
import { getSafariVersion, isSafari } from 'common/Platform';
|
||||||
import { ICoreService, IDecorationService, IOptionsService } from 'common/services/Services';
|
import { ICoreService, IDecorationService, ILogService, IOptionsService } from 'common/services/Services';
|
||||||
import { IWebGL2RenderingContext } from './Types';
|
import { IWebGL2RenderingContext } from './Types';
|
||||||
import { WebglRenderer } from './WebglRenderer';
|
import { WebglRenderer } from './WebglRenderer';
|
||||||
import { Emitter, EventUtils } from 'common/Event';
|
import { Emitter, EventUtils } from 'common/Event';
|
||||||
@@ -65,6 +65,7 @@ export class WebglAddon extends Disposable implements ITerminalAddon, IWebglApi
|
|||||||
const charSizeService: ICharSizeService = unsafeCore._charSizeService;
|
const charSizeService: ICharSizeService = unsafeCore._charSizeService;
|
||||||
const coreBrowserService: ICoreBrowserService = unsafeCore._coreBrowserService;
|
const coreBrowserService: ICoreBrowserService = unsafeCore._coreBrowserService;
|
||||||
const decorationService: IDecorationService = unsafeCore._decorationService;
|
const decorationService: IDecorationService = unsafeCore._decorationService;
|
||||||
|
const logService: ILogService = unsafeCore._logService;
|
||||||
const themeService: IThemeService = unsafeCore._themeService;
|
const themeService: IThemeService = unsafeCore._themeService;
|
||||||
|
|
||||||
this._renderer = this._register(new WebglRenderer(
|
this._renderer = this._register(new WebglRenderer(
|
||||||
@@ -74,6 +75,7 @@ export class WebglAddon extends Disposable implements ITerminalAddon, IWebglApi
|
|||||||
coreBrowserService,
|
coreBrowserService,
|
||||||
coreService,
|
coreService,
|
||||||
decorationService,
|
decorationService,
|
||||||
|
logService,
|
||||||
optionsService,
|
optionsService,
|
||||||
themeService,
|
themeService,
|
||||||
this._customGlyphs,
|
this._customGlyphs,
|
||||||
|
|||||||
@@ -13,23 +13,29 @@ import { ICharSizeService, ICharacterJoinerService, ICoreBrowserService, IThemeS
|
|||||||
import { CharData, IBufferLine, ICellData } from 'common/Types';
|
import { CharData, IBufferLine, ICellData } from 'common/Types';
|
||||||
import { AttributeData } from 'common/buffer/AttributeData';
|
import { AttributeData } from 'common/buffer/AttributeData';
|
||||||
import { CellData } from 'common/buffer/CellData';
|
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 { ICoreService, IDecorationService, IOptionsService } from 'common/services/Services';
|
import { TextBlinkStateManager } from 'browser/renderer/shared/TextBlinkStateManager';
|
||||||
|
import { ICoreService, IDecorationService, ILogService, IOptionsService } from 'common/services/Services';
|
||||||
import { Terminal } from '@xterm/xterm';
|
import { Terminal } from '@xterm/xterm';
|
||||||
import { GlyphRenderer } from './GlyphRenderer';
|
import { GlyphRenderer } from './GlyphRenderer';
|
||||||
import { RectangleRenderer } from './RectangleRenderer';
|
import { RectangleRenderer } from './RectangleRenderer';
|
||||||
import { COMBINED_CHAR_BIT_MASK, RENDER_MODEL_BG_OFFSET, RENDER_MODEL_EXT_OFFSET, RENDER_MODEL_FG_OFFSET, RENDER_MODEL_INDICIES_PER_CELL, RenderModel } from './RenderModel';
|
import { COMBINED_CHAR_BIT_MASK, RenderModel, RenderModelConstants } from './RenderModel';
|
||||||
import { IWebGL2RenderingContext, type ITextureAtlas } from './Types';
|
import { IWebGL2RenderingContext, type ITextureAtlas } from './Types';
|
||||||
import { LinkRenderLayer } from './renderLayer/LinkRenderLayer';
|
import { LinkRenderLayer } from './renderLayer/LinkRenderLayer';
|
||||||
import { IRenderLayer } from './renderLayer/Types';
|
import { IRenderLayer } from './renderLayer/Types';
|
||||||
import { Emitter, EventUtils } from 'common/Event';
|
import { Emitter, EventUtils } from 'common/Event';
|
||||||
import { addDisposableListener } from 'vs/base/browser/dom';
|
import { addDisposableListener } from 'browser/Dom';
|
||||||
import { combinedDisposable, Disposable, MutableDisposable, toDisposable } from 'common/Lifecycle';
|
import { combinedDisposable, Disposable, MutableDisposable, toDisposable } from 'common/Lifecycle';
|
||||||
import { createRenderDimensions } from 'browser/renderer/shared/RendererUtils';
|
import { createRenderDimensions } from 'browser/renderer/shared/RendererUtils';
|
||||||
|
|
||||||
|
const enum Constants {
|
||||||
|
MERGE_RETRY_LIMIT = 32
|
||||||
|
}
|
||||||
|
|
||||||
export class WebglRenderer extends Disposable implements IRenderer {
|
export class WebglRenderer extends Disposable implements IRenderer {
|
||||||
private _renderLayers: IRenderLayer[];
|
private _renderLayers: IRenderLayer[];
|
||||||
private _cursorBlinkStateManager: MutableDisposable<CursorBlinkStateManager> = new MutableDisposable();
|
private _cursorBlinkStateManager: MutableDisposable<CursorBlinkStateManager> = this._register(new MutableDisposable());
|
||||||
|
private _textBlinkStateManager: TextBlinkStateManager;
|
||||||
private _charAtlasDisposable = this._register(new MutableDisposable());
|
private _charAtlasDisposable = this._register(new MutableDisposable());
|
||||||
private _charAtlas: ITextureAtlas | undefined;
|
private _charAtlas: ITextureAtlas | undefined;
|
||||||
private _devicePixelRatio: number;
|
private _devicePixelRatio: number;
|
||||||
@@ -37,8 +43,9 @@ export class WebglRenderer extends Disposable implements IRenderer {
|
|||||||
private _observerDisposable = this._register(new MutableDisposable());
|
private _observerDisposable = this._register(new MutableDisposable());
|
||||||
|
|
||||||
private _model: RenderModel = new RenderModel();
|
private _model: RenderModel = new RenderModel();
|
||||||
|
private _rowHasBlinkingCells: boolean[] = [];
|
||||||
|
private _rowHasBlinkingCellsCount: number = 0;
|
||||||
private _workCell: ICellData = new CellData();
|
private _workCell: ICellData = new CellData();
|
||||||
private _workCell2: ICellData = new CellData();
|
|
||||||
private _cellColorResolver: CellColorResolver;
|
private _cellColorResolver: CellColorResolver;
|
||||||
|
|
||||||
private _canvas: HTMLCanvasElement;
|
private _canvas: HTMLCanvasElement;
|
||||||
@@ -70,6 +77,7 @@ export class WebglRenderer extends Disposable implements IRenderer {
|
|||||||
private readonly _coreBrowserService: ICoreBrowserService,
|
private readonly _coreBrowserService: ICoreBrowserService,
|
||||||
private readonly _coreService: ICoreService,
|
private readonly _coreService: ICoreService,
|
||||||
private readonly _decorationService: IDecorationService,
|
private readonly _decorationService: IDecorationService,
|
||||||
|
private readonly _logService: ILogService,
|
||||||
private readonly _optionsService: IOptionsService,
|
private readonly _optionsService: IOptionsService,
|
||||||
private readonly _themeService: IThemeService,
|
private readonly _themeService: IThemeService,
|
||||||
private readonly _customGlyphs: boolean = true,
|
private readonly _customGlyphs: boolean = true,
|
||||||
@@ -105,23 +113,29 @@ export class WebglRenderer extends Disposable implements IRenderer {
|
|||||||
this._updateDimensions();
|
this._updateDimensions();
|
||||||
this._updateCursorBlink();
|
this._updateCursorBlink();
|
||||||
this._register(_optionsService.onOptionChange(() => this._handleOptionsChanged()));
|
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);
|
this._deviceMaxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
|
||||||
|
|
||||||
this._register(addDisposableListener(this._canvas, 'webglcontextlost', (e) => {
|
this._register(addDisposableListener(this._canvas, 'webglcontextlost', (e) => {
|
||||||
console.log('webglcontextlost event received');
|
this._logService.debug('webglcontextlost event received');
|
||||||
// Prevent the default behavior in order to enable WebGL context restoration.
|
// Prevent the default behavior in order to enable WebGL context restoration.
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
// Wait a few seconds to see if the 'webglcontextrestored' event is fired.
|
// Wait a few seconds to see if the 'webglcontextrestored' event is fired.
|
||||||
// If not, dispatch the onContextLoss notification to observers.
|
// If not, dispatch the onContextLoss notification to observers.
|
||||||
this._contextRestorationTimeout = setTimeout(() => {
|
this._contextRestorationTimeout = setTimeout(() => {
|
||||||
this._contextRestorationTimeout = undefined;
|
this._contextRestorationTimeout = undefined;
|
||||||
console.warn('webgl context not restored; firing onContextLoss');
|
this._logService.warn('webgl context not restored; firing onContextLoss');
|
||||||
this._onContextLoss.fire(e);
|
this._onContextLoss.fire(e);
|
||||||
}, 3000 /* ms */);
|
}, 3000 /* ms */);
|
||||||
}));
|
}));
|
||||||
this._register(addDisposableListener(this._canvas, 'webglcontextrestored', (e) => {
|
this._register(addDisposableListener(this._canvas, 'webglcontextrestored', (e) => {
|
||||||
console.warn('webglcontextrestored event received');
|
this._logService.warn('webglcontextrestored event received');
|
||||||
clearTimeout(this._contextRestorationTimeout);
|
clearTimeout(this._contextRestorationTimeout);
|
||||||
this._contextRestorationTimeout = undefined;
|
this._contextRestorationTimeout = undefined;
|
||||||
// The texture atlas and glyph renderer must be fully reinitialized
|
// The texture atlas and glyph renderer must be fully reinitialized
|
||||||
@@ -145,6 +159,8 @@ export class WebglRenderer extends Disposable implements IRenderer {
|
|||||||
this._isAttached = this._core.screenElement!.isConnected;
|
this._isAttached = this._core.screenElement!.isConnected;
|
||||||
|
|
||||||
this._register(toDisposable(() => {
|
this._register(toDisposable(() => {
|
||||||
|
clearTimeout(this._contextRestorationTimeout);
|
||||||
|
this._contextRestorationTimeout = undefined;
|
||||||
for (const l of this._renderLayers) {
|
for (const l of this._renderLayers) {
|
||||||
l.dispose();
|
l.dispose();
|
||||||
}
|
}
|
||||||
@@ -178,6 +194,7 @@ export class WebglRenderer extends Disposable implements IRenderer {
|
|||||||
this._updateDimensions();
|
this._updateDimensions();
|
||||||
|
|
||||||
this._model.resize(this._terminal.cols, this._terminal.rows);
|
this._model.resize(this._terminal.cols, this._terminal.rows);
|
||||||
|
this._resetBlinkingRowState();
|
||||||
|
|
||||||
// Resize all render layers
|
// Resize all render layers
|
||||||
for (const l of this._renderLayers) {
|
for (const l of this._renderLayers) {
|
||||||
@@ -231,6 +248,10 @@ export class WebglRenderer extends Disposable implements IRenderer {
|
|||||||
this._requestRedrawViewport();
|
this._requestRedrawViewport();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public handleViewportVisibilityChange(isVisible: boolean): void {
|
||||||
|
this._textBlinkStateManager.setViewportVisible(isVisible);
|
||||||
|
}
|
||||||
|
|
||||||
public handleSelectionChanged(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void {
|
public handleSelectionChanged(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void {
|
||||||
for (const l of this._renderLayers) {
|
for (const l of this._renderLayers) {
|
||||||
l.handleSelectionChanged(this._terminal, start, end, columnSelectMode);
|
l.handleSelectionChanged(this._terminal, start, end, columnSelectMode);
|
||||||
@@ -256,8 +277,8 @@ export class WebglRenderer extends Disposable implements IRenderer {
|
|||||||
* Initializes members dependent on WebGL context state.
|
* Initializes members dependent on WebGL context state.
|
||||||
*/
|
*/
|
||||||
private _initializeWebGLState(): [RectangleRenderer, GlyphRenderer] {
|
private _initializeWebGLState(): [RectangleRenderer, GlyphRenderer] {
|
||||||
this._rectangleRenderer.value = new RectangleRenderer(this._terminal, this._gl, this.dimensions, this._themeService);
|
this._rectangleRenderer.value = new RectangleRenderer(this._terminal, this._gl, this.dimensions, this._themeService, this._logService);
|
||||||
this._glyphRenderer.value = new GlyphRenderer(this._terminal, this._gl, this.dimensions, this._optionsService);
|
this._glyphRenderer.value = new GlyphRenderer(this._terminal, this._gl, this.dimensions, this._optionsService, this._logService);
|
||||||
|
|
||||||
// Update dimensions and acquire char atlas
|
// Update dimensions and acquire char atlas
|
||||||
this.handleCharSizeChanged();
|
this.handleCharSizeChanged();
|
||||||
@@ -323,6 +344,9 @@ export class WebglRenderer extends Disposable implements IRenderer {
|
|||||||
l.reset(this._terminal);
|
l.reset(this._terminal);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this._resetBlinkingRowState();
|
||||||
|
this._textBlinkStateManager.setNeedsBlinkInViewport(false);
|
||||||
|
|
||||||
this._cursorBlinkStateManager.value?.restartBlinkAnimation();
|
this._cursorBlinkStateManager.value?.restartBlinkAnimation();
|
||||||
this._updateCursorBlink();
|
this._updateCursorBlink();
|
||||||
}
|
}
|
||||||
@@ -358,6 +382,19 @@ export class WebglRenderer extends Disposable implements IRenderer {
|
|||||||
this._updateModel(start, end);
|
this._updateModel(start, end);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A mid-update atlas page merge invalidates vertex data and may not bump the host
|
||||||
|
// page's version, so re-run the update and force a full texture rebind.
|
||||||
|
let merged = false;
|
||||||
|
let mergeRetries = 0;
|
||||||
|
while (this._charAtlas && this._glyphRenderer.value.beginFrame() && mergeRetries++ < Constants.MERGE_RETRY_LIMIT) {
|
||||||
|
merged = true;
|
||||||
|
this._clearModel(true);
|
||||||
|
this._updateModel(0, this._terminal.rows - 1);
|
||||||
|
}
|
||||||
|
if (merged) {
|
||||||
|
this._glyphRenderer.value.invalidateAtlasTextures();
|
||||||
|
}
|
||||||
|
|
||||||
// Render
|
// Render
|
||||||
this._rectangleRenderer.value.renderBackgrounds();
|
this._rectangleRenderer.value.renderBackgrounds();
|
||||||
this._glyphRenderer.value.render(this._model);
|
this._glyphRenderer.value.render(this._model);
|
||||||
@@ -420,6 +457,7 @@ export class WebglRenderer extends Disposable implements IRenderer {
|
|||||||
for (y = start; y <= end; y++) {
|
for (y = start; y <= end; y++) {
|
||||||
row = y + terminal.buffer.ydisp;
|
row = y + terminal.buffer.ydisp;
|
||||||
line = terminal.buffer.lines.get(row)!;
|
line = terminal.buffer.lines.get(row)!;
|
||||||
|
let rowHasBlinkingCells = false;
|
||||||
this._model.lineLengths[y] = 0;
|
this._model.lineLengths[y] = 0;
|
||||||
isCursorRow = cursorY === row;
|
isCursorRow = cursorY === row;
|
||||||
skipJoinedCheckUntilX = 0;
|
skipJoinedCheckUntilX = 0;
|
||||||
@@ -475,10 +513,14 @@ export class WebglRenderer extends Disposable implements IRenderer {
|
|||||||
|
|
||||||
chars = cell.getChars();
|
chars = cell.getChars();
|
||||||
code = cell.getCode();
|
code = cell.getCode();
|
||||||
i = ((y * terminal.cols) + x) * RENDER_MODEL_INDICIES_PER_CELL;
|
i = ((y * terminal.cols) + x) * RenderModelConstants.INDICIES_PER_CELL;
|
||||||
|
|
||||||
|
if (!rowHasBlinkingCells && cell.isBlink()) {
|
||||||
|
rowHasBlinkingCells = true;
|
||||||
|
}
|
||||||
|
|
||||||
// Load colors/resolve overrides into work colors
|
// 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
|
// Override colors for cursor cell
|
||||||
if (isCursorVisible && row === cursorY) {
|
if (isCursorVisible && row === cursorY) {
|
||||||
@@ -506,15 +548,19 @@ 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) {
|
if (code !== NULL_CELL_CODE) {
|
||||||
this._model.lineLengths[y] = x + 1;
|
this._model.lineLengths[y] = x + 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Nothing has changed, no updates needed
|
// Nothing has changed, no updates needed
|
||||||
if (this._model.cells[i] === code &&
|
if (this._model.cells[i] === code &&
|
||||||
this._model.cells[i + RENDER_MODEL_BG_OFFSET] === this._cellColorResolver.result.bg &&
|
this._model.cells[i + RenderModelConstants.BG_OFFSET] === this._cellColorResolver.result.bg &&
|
||||||
this._model.cells[i + RENDER_MODEL_FG_OFFSET] === this._cellColorResolver.result.fg &&
|
this._model.cells[i + RenderModelConstants.FG_OFFSET] === this._cellColorResolver.result.fg &&
|
||||||
this._model.cells[i + RENDER_MODEL_EXT_OFFSET] === this._cellColorResolver.result.ext) {
|
this._model.cells[i + RenderModelConstants.EXT_OFFSET] === this._cellColorResolver.result.ext) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -527,9 +573,9 @@ export class WebglRenderer extends Disposable implements IRenderer {
|
|||||||
|
|
||||||
// Cache the results in the model
|
// Cache the results in the model
|
||||||
this._model.cells[i] = code;
|
this._model.cells[i] = code;
|
||||||
this._model.cells[i + RENDER_MODEL_BG_OFFSET] = this._cellColorResolver.result.bg;
|
this._model.cells[i + RenderModelConstants.BG_OFFSET] = this._cellColorResolver.result.bg;
|
||||||
this._model.cells[i + RENDER_MODEL_FG_OFFSET] = this._cellColorResolver.result.fg;
|
this._model.cells[i + RenderModelConstants.FG_OFFSET] = this._cellColorResolver.result.fg;
|
||||||
this._model.cells[i + RENDER_MODEL_EXT_OFFSET] = this._cellColorResolver.result.ext;
|
this._model.cells[i + RenderModelConstants.EXT_OFFSET] = this._cellColorResolver.result.ext;
|
||||||
|
|
||||||
width = cell.getWidth();
|
width = cell.getWidth();
|
||||||
this._glyphRenderer.value!.updateCell(x, y, code, this._cellColorResolver.result.bg, this._cellColorResolver.result.fg, this._cellColorResolver.result.ext, chars, width, lastBg);
|
this._glyphRenderer.value!.updateCell(x, y, code, this._cellColorResolver.result.bg, this._cellColorResolver.result.fg, this._cellColorResolver.result.ext, chars, width, lastBg);
|
||||||
@@ -540,23 +586,43 @@ export class WebglRenderer extends Disposable implements IRenderer {
|
|||||||
|
|
||||||
// Null out non-first cells
|
// Null out non-first cells
|
||||||
for (x++; x <= lastCharX; x++) {
|
for (x++; x <= lastCharX; x++) {
|
||||||
j = ((y * terminal.cols) + x) * RENDER_MODEL_INDICIES_PER_CELL;
|
j = ((y * terminal.cols) + x) * RenderModelConstants.INDICIES_PER_CELL;
|
||||||
this._glyphRenderer.value!.updateCell(x, y, NULL_CELL_CODE, 0, 0, 0, NULL_CELL_CHAR, 0, 0);
|
this._glyphRenderer.value!.updateCell(x, y, NULL_CELL_CODE, 0, 0, 0, NULL_CELL_CHAR, 0, 0);
|
||||||
this._model.cells[j] = NULL_CELL_CODE;
|
this._model.cells[j] = NULL_CELL_CODE;
|
||||||
// Don't re-resolve the cell color since multi-colored ligature backgrounds are not
|
// Don't re-resolve the cell color since multi-colored ligature backgrounds are not
|
||||||
// supported
|
// supported
|
||||||
this._model.cells[j + RENDER_MODEL_BG_OFFSET] = this._cellColorResolver.result.bg;
|
this._model.cells[j + RenderModelConstants.BG_OFFSET] = this._cellColorResolver.result.bg;
|
||||||
this._model.cells[j + RENDER_MODEL_FG_OFFSET] = this._cellColorResolver.result.fg;
|
this._model.cells[j + RenderModelConstants.FG_OFFSET] = this._cellColorResolver.result.fg;
|
||||||
this._model.cells[j + RENDER_MODEL_EXT_OFFSET] = this._cellColorResolver.result.ext;
|
this._model.cells[j + RenderModelConstants.EXT_OFFSET] = this._cellColorResolver.result.ext;
|
||||||
}
|
}
|
||||||
x--; // Go back to the previous update cell for next iteration
|
x--; // Go back to the previous update cell for next iteration
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
this._setRowBlinkState(y, rowHasBlinkingCells);
|
||||||
}
|
}
|
||||||
if (modelUpdated) {
|
if (modelUpdated) {
|
||||||
this._rectangleRenderer.value!.updateBackgrounds(this._model);
|
this._rectangleRenderer.value!.updateBackgrounds(this._model);
|
||||||
}
|
}
|
||||||
this._rectangleRenderer.value!.updateCursor(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);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { throwIfFalsy } from 'browser/renderer/shared/RendererUtils';
|
import { throwIfFalsy } from 'browser/renderer/shared/RendererUtils';
|
||||||
|
import type { ILogService } from 'common/services/Services';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A matrix that when multiplies will translate 0-1 coordinates (left to right,
|
* A matrix that when multiplies will translate 0-1 coordinates (left to right,
|
||||||
@@ -16,21 +17,21 @@ export const PROJECTION_MATRIX = new Float32Array([
|
|||||||
-1, 1, 0, 1
|
-1, 1, 0, 1
|
||||||
]);
|
]);
|
||||||
|
|
||||||
export function createProgram(gl: WebGLRenderingContext, vertexSource: string, fragmentSource: string): WebGLProgram | undefined {
|
export function createProgram(gl: WebGLRenderingContext, vertexSource: string, fragmentSource: string, logService: ILogService): WebGLProgram | undefined {
|
||||||
const program = throwIfFalsy(gl.createProgram());
|
const program = throwIfFalsy(gl.createProgram());
|
||||||
gl.attachShader(program, throwIfFalsy(createShader(gl, gl.VERTEX_SHADER, vertexSource)));
|
gl.attachShader(program, throwIfFalsy(createShader(gl, gl.VERTEX_SHADER, vertexSource, logService)));
|
||||||
gl.attachShader(program, throwIfFalsy(createShader(gl, gl.FRAGMENT_SHADER, fragmentSource)));
|
gl.attachShader(program, throwIfFalsy(createShader(gl, gl.FRAGMENT_SHADER, fragmentSource, logService)));
|
||||||
gl.linkProgram(program);
|
gl.linkProgram(program);
|
||||||
const success = gl.getProgramParameter(program, gl.LINK_STATUS);
|
const success = gl.getProgramParameter(program, gl.LINK_STATUS);
|
||||||
if (success) {
|
if (success) {
|
||||||
return program;
|
return program;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.error(gl.getProgramInfoLog(program));
|
logService.error(gl.getProgramInfoLog(program));
|
||||||
gl.deleteProgram(program);
|
gl.deleteProgram(program);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createShader(gl: WebGLRenderingContext, type: number, source: string): WebGLShader | undefined {
|
export function createShader(gl: WebGLRenderingContext, type: number, source: string, logService: ILogService): WebGLShader | undefined {
|
||||||
const shader = throwIfFalsy(gl.createShader(type));
|
const shader = throwIfFalsy(gl.createShader(type));
|
||||||
gl.shaderSource(shader, source);
|
gl.shaderSource(shader, source);
|
||||||
gl.compileShader(shader);
|
gl.compileShader(shader);
|
||||||
@@ -39,7 +40,7 @@ export function createShader(gl: WebGLRenderingContext, type: number, source: st
|
|||||||
return shader;
|
return shader;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.error(gl.getShaderInfoLog(shader));
|
logService.error(gl.getShaderInfoLog(shader));
|
||||||
gl.deleteShader(shader);
|
gl.deleteShader(shader);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,35 @@ import { CustomGlyphDefinitionType, CustomGlyphScaleType, CustomGlyphVectorType,
|
|||||||
|
|
||||||
/* eslint-disable max-len */
|
/* eslint-disable max-len */
|
||||||
|
|
||||||
|
const enum Shapes {
|
||||||
|
/** │ */ TOP_TO_BOTTOM = 'M.5,0 L.5,1',
|
||||||
|
/** ─ */ LEFT_TO_RIGHT = 'M0,.5 L1,.5',
|
||||||
|
|
||||||
|
/** └ */ TOP_TO_RIGHT = 'M.5,0 L.5,.5 L1,.5',
|
||||||
|
/** ┘ */ TOP_TO_LEFT = 'M.5,0 L.5,.5 L0,.5',
|
||||||
|
/** ┐ */ LEFT_TO_BOTTOM = 'M0,.5 L.5,.5 L.5,1',
|
||||||
|
/** ┌ */ RIGHT_TO_BOTTOM = 'M0.5,1 L.5,.5 L1,.5',
|
||||||
|
|
||||||
|
/** ╵ */ MIDDLE_TO_TOP = 'M.5,.5 L.5,0',
|
||||||
|
/** ╴ */ MIDDLE_TO_LEFT = 'M.5,.5 L0,.5',
|
||||||
|
/** ╶ */ MIDDLE_TO_RIGHT = 'M.5,.5 L1,.5',
|
||||||
|
/** ╷ */ MIDDLE_TO_BOTTOM = 'M.5,.5 L.5,1',
|
||||||
|
|
||||||
|
/** ┴ */ T_TOP = 'M0,.5 L1,.5 M.5,.5 L.5,0',
|
||||||
|
/** ┤ */ T_LEFT = 'M.5,0 L.5,1 M.5,.5 L0,.5',
|
||||||
|
/** ├ */ T_RIGHT = 'M.5,0 L.5,1 M.5,.5 L1,.5',
|
||||||
|
/** ┬ */ T_BOTTOM = 'M0,.5 L1,.5 M.5,.5 L.5,1',
|
||||||
|
|
||||||
|
/** ┼ */ CROSS = 'M0,.5 L1,.5 M.5,0 L.5,1',
|
||||||
|
|
||||||
|
/** ╌ */ TWO_DASHES_HORIZONTAL = 'M.1,.5 L.4,.5 M.6,.5 L.9,.5', // .2 empty, .3 filled
|
||||||
|
/** ┄ */ THREE_DASHES_HORIZONTAL = 'M.0667,.5 L.2667,.5 M.4,.5 L.6,.5 M.7333,.5 L.9333,.5', // .1333 empty, .2 filled
|
||||||
|
/** ┉ */ FOUR_DASHES_HORIZONTAL = 'M.05,.5 L.2,.5 M.3,.5 L.45,.5 M.55,.5 L.7,.5 M.8,.5 L.95,.5', // .1 empty, .15 filled
|
||||||
|
/** ╎ */ TWO_DASHES_VERTICAL = 'M.5,.1 L.5,.4 M.5,.6 L.5,.9',
|
||||||
|
/** ┆ */ THREE_DASHES_VERTICAL = 'M.5,.0667 L.5,.2667 M.5,.4 L.5,.6 M.5,.7333 L.5,.9333',
|
||||||
|
/** ┊ */ FOUR_DASHES_VERTICAL = 'M.5,.05 L.5,.2 M.5,.3 L.5,.45 L.5,.55 M.5,.7 L.5,.95',
|
||||||
|
}
|
||||||
|
|
||||||
namespace GitBranchSymbolsParts {
|
namespace GitBranchSymbolsParts {
|
||||||
// Lines
|
// Lines
|
||||||
export const LINE_H: CustomGlyphDefinitionPart = Object.freeze({ type: CustomGlyphDefinitionType.PATH_FUNCTION, data: Shapes.LEFT_TO_RIGHT, strokeWidth: 1 });
|
export const LINE_H: CustomGlyphDefinitionPart = Object.freeze({ type: CustomGlyphDefinitionType.PATH_FUNCTION, data: Shapes.LEFT_TO_RIGHT, strokeWidth: 1 });
|
||||||
@@ -644,8 +673,8 @@ export const customGlyphDefinitions: { [index: string]: CustomGlyphCharacterDefi
|
|||||||
] },
|
] },
|
||||||
|
|
||||||
// Diagonal fill characters (1FB98-1FB99)
|
// 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{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: '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{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)
|
// 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
|
'\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 +849,27 @@ export const customGlyphDefinitions: { [index: string]: CustomGlyphCharacterDefi
|
|||||||
// #endregion
|
// #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
|
* Generates a drawing function for sextant characters. Sextants are a 2x3 grid where each cell
|
||||||
* can be on or off.
|
* can be on or off.
|
||||||
@@ -967,31 +1017,3 @@ function segmentedDigit(pattern: number): string {
|
|||||||
return paths.join(' ');
|
return paths.join(' ');
|
||||||
}
|
}
|
||||||
|
|
||||||
const enum Shapes {
|
|
||||||
/** │ */ TOP_TO_BOTTOM = 'M.5,0 L.5,1',
|
|
||||||
/** ─ */ LEFT_TO_RIGHT = 'M0,.5 L1,.5',
|
|
||||||
|
|
||||||
/** └ */ TOP_TO_RIGHT = 'M.5,0 L.5,.5 L1,.5',
|
|
||||||
/** ┘ */ TOP_TO_LEFT = 'M.5,0 L.5,.5 L0,.5',
|
|
||||||
/** ┐ */ LEFT_TO_BOTTOM = 'M0,.5 L.5,.5 L.5,1',
|
|
||||||
/** ┌ */ RIGHT_TO_BOTTOM = 'M0.5,1 L.5,.5 L1,.5',
|
|
||||||
|
|
||||||
/** ╵ */ MIDDLE_TO_TOP = 'M.5,.5 L.5,0',
|
|
||||||
/** ╴ */ MIDDLE_TO_LEFT = 'M.5,.5 L0,.5',
|
|
||||||
/** ╶ */ MIDDLE_TO_RIGHT = 'M.5,.5 L1,.5',
|
|
||||||
/** ╷ */ MIDDLE_TO_BOTTOM = 'M.5,.5 L.5,1',
|
|
||||||
|
|
||||||
/** ┴ */ T_TOP = 'M0,.5 L1,.5 M.5,.5 L.5,0',
|
|
||||||
/** ┤ */ T_LEFT = 'M.5,0 L.5,1 M.5,.5 L0,.5',
|
|
||||||
/** ├ */ T_RIGHT = 'M.5,0 L.5,1 M.5,.5 L1,.5',
|
|
||||||
/** ┬ */ T_BOTTOM = 'M0,.5 L1,.5 M.5,.5 L.5,1',
|
|
||||||
|
|
||||||
/** ┼ */ CROSS = 'M0,.5 L1,.5 M.5,0 L.5,1',
|
|
||||||
|
|
||||||
/** ╌ */ TWO_DASHES_HORIZONTAL = 'M.1,.5 L.4,.5 M.6,.5 L.9,.5', // .2 empty, .3 filled
|
|
||||||
/** ┄ */ THREE_DASHES_HORIZONTAL = 'M.0667,.5 L.2667,.5 M.4,.5 L.6,.5 M.7333,.5 L.9333,.5', // .1333 empty, .2 filled
|
|
||||||
/** ┉ */ FOUR_DASHES_HORIZONTAL = 'M.05,.5 L.2,.5 M.3,.5 L.45,.5 M.55,.5 L.7,.5 M.8,.5 L.95,.5', // .1 empty, .15 filled
|
|
||||||
/** ╎ */ TWO_DASHES_VERTICAL = 'M.5,.1 L.5,.4 M.5,.6 L.5,.9',
|
|
||||||
/** ┆ */ THREE_DASHES_VERTICAL = 'M.5,.0667 L.5,.2667 M.5,.4 L.5,.6 M.5,.7333 L.5,.9333',
|
|
||||||
/** ┊ */ FOUR_DASHES_VERTICAL = 'M.5,.05 L.5,.2 M.5,.3 L.5,.45 L.5,.55 M.5,.7 L.5,.95',
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { throwIfFalsy } from 'browser/renderer/shared/RendererUtils';
|
import { throwIfFalsy } from 'browser/renderer/shared/RendererUtils';
|
||||||
|
import type { ILogService } from 'common/services/Services';
|
||||||
import { customGlyphDefinitions } from './CustomGlyphDefinitions';
|
import { customGlyphDefinitions } from './CustomGlyphDefinitions';
|
||||||
import { CustomGlyphDefinitionType, CustomGlyphScaleType, CustomGlyphVectorType, type CustomGlyphDefinitionPart, type CustomGlyphPathDrawFunctionDefinition, type CustomGlyphPatternDefinition, type ICustomGlyphSolidOctantBlockVector, type ICustomGlyphVectorShape } from './Types';
|
import { CustomGlyphDefinitionType, CustomGlyphScaleType, CustomGlyphVectorType, type CustomGlyphDefinitionPart, type CustomGlyphPathDrawFunctionDefinition, type CustomGlyphPatternDefinition, type ICustomGlyphSolidOctantBlockVector, type ICustomGlyphVectorShape } from './Types';
|
||||||
|
|
||||||
@@ -22,14 +23,16 @@ export function tryDrawCustomGlyph(
|
|||||||
deviceCharHeight: number,
|
deviceCharHeight: number,
|
||||||
fontSize: number,
|
fontSize: number,
|
||||||
devicePixelRatio: number,
|
devicePixelRatio: number,
|
||||||
backgroundColor?: string
|
logService: ILogService,
|
||||||
|
backgroundColor?: string,
|
||||||
|
variantOffset: number = 0
|
||||||
): boolean {
|
): boolean {
|
||||||
const unifiedCharDefinition = customGlyphDefinitions[c];
|
const unifiedCharDefinition = customGlyphDefinitions[c];
|
||||||
if (unifiedCharDefinition) {
|
if (unifiedCharDefinition) {
|
||||||
// Normalize to array for uniform handling
|
// Normalize to array for uniform handling
|
||||||
const parts = Array.isArray(unifiedCharDefinition) ? unifiedCharDefinition : [unifiedCharDefinition];
|
const parts = Array.isArray(unifiedCharDefinition) ? unifiedCharDefinition : [unifiedCharDefinition];
|
||||||
for (const part of parts) {
|
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, logService, backgroundColor, variantOffset);
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -48,7 +51,9 @@ function drawDefinitionPart(
|
|||||||
deviceCharHeight: number,
|
deviceCharHeight: number,
|
||||||
fontSize: number,
|
fontSize: number,
|
||||||
devicePixelRatio: number,
|
devicePixelRatio: number,
|
||||||
backgroundColor?: string
|
logService: ILogService,
|
||||||
|
backgroundColor?: string,
|
||||||
|
variantOffset: number = 0
|
||||||
): void {
|
): void {
|
||||||
// Handle scaleType - adjust dimensions and offset when scaling to character area
|
// Handle scaleType - adjust dimensions and offset when scaling to character area
|
||||||
let drawWidth = deviceCellWidth;
|
let drawWidth = deviceCellWidth;
|
||||||
@@ -74,10 +79,10 @@ function drawDefinitionPart(
|
|||||||
drawBlockVectorChar(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight);
|
drawBlockVectorChar(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight);
|
||||||
break;
|
break;
|
||||||
case CustomGlyphDefinitionType.BLOCK_PATTERN:
|
case CustomGlyphDefinitionType.BLOCK_PATTERN:
|
||||||
drawPatternChar(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight);
|
drawPatternChar(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight, variantOffset);
|
||||||
break;
|
break;
|
||||||
case CustomGlyphDefinitionType.PATH_FUNCTION:
|
case CustomGlyphDefinitionType.PATH_FUNCTION:
|
||||||
drawPathFunctionCharacter(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight, devicePixelRatio, part.strokeWidth);
|
drawPathFunctionCharacter(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight, devicePixelRatio, logService, part.strokeWidth);
|
||||||
break;
|
break;
|
||||||
case CustomGlyphDefinitionType.PATH:
|
case CustomGlyphDefinitionType.PATH:
|
||||||
drawPathDefinitionCharacter(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight, devicePixelRatio, part.strokeWidth);
|
drawPathDefinitionCharacter(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight, devicePixelRatio, part.strokeWidth);
|
||||||
@@ -86,7 +91,7 @@ function drawDefinitionPart(
|
|||||||
drawPathNegativeDefinitionCharacter(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight, devicePixelRatio, backgroundColor);
|
drawPathNegativeDefinitionCharacter(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight, devicePixelRatio, backgroundColor);
|
||||||
break;
|
break;
|
||||||
case CustomGlyphDefinitionType.VECTOR_SHAPE:
|
case CustomGlyphDefinitionType.VECTOR_SHAPE:
|
||||||
drawVectorShape(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight, fontSize, devicePixelRatio);
|
drawVectorShape(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight, fontSize, devicePixelRatio, logService);
|
||||||
break;
|
break;
|
||||||
case CustomGlyphDefinitionType.BRAILLE:
|
case CustomGlyphDefinitionType.BRAILLE:
|
||||||
drawBrailleCharacter(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight);
|
drawBrailleCharacter(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight);
|
||||||
@@ -437,7 +442,8 @@ function drawPatternChar(
|
|||||||
xOffset: number,
|
xOffset: number,
|
||||||
yOffset: number,
|
yOffset: number,
|
||||||
deviceCellWidth: number,
|
deviceCellWidth: number,
|
||||||
deviceCellHeight: number
|
deviceCellHeight: number,
|
||||||
|
variantOffset: number = 0
|
||||||
): void {
|
): void {
|
||||||
let patternSet = cachedPatterns.get(charDefinition);
|
let patternSet = cachedPatterns.get(charDefinition);
|
||||||
if (!patternSet) {
|
if (!patternSet) {
|
||||||
@@ -486,6 +492,15 @@ function drawPatternChar(
|
|||||||
pattern = throwIfFalsy(ctx.createPattern(tmpCanvas, null));
|
pattern = throwIfFalsy(ctx.createPattern(tmpCanvas, null));
|
||||||
patternSet.set(fillStyle, pattern);
|
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.fillStyle = pattern;
|
||||||
ctx.fillRect(xOffset, yOffset, deviceCellWidth, deviceCellHeight);
|
ctx.fillRect(xOffset, yOffset, deviceCellWidth, deviceCellHeight);
|
||||||
}
|
}
|
||||||
@@ -498,8 +513,14 @@ function drawPathFunctionCharacter(
|
|||||||
deviceCellWidth: number,
|
deviceCellWidth: number,
|
||||||
deviceCellHeight: number,
|
deviceCellHeight: number,
|
||||||
devicePixelRatio: number,
|
devicePixelRatio: number,
|
||||||
|
logService: ILogService,
|
||||||
strokeWidth?: number
|
strokeWidth?: number
|
||||||
): void {
|
): void {
|
||||||
|
ctx.save();
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.rect(xOffset, yOffset, deviceCellWidth, deviceCellHeight);
|
||||||
|
ctx.clip();
|
||||||
|
|
||||||
ctx.beginPath();
|
ctx.beginPath();
|
||||||
let actualInstructions: string;
|
let actualInstructions: string;
|
||||||
if (typeof charDefinition === 'function') {
|
if (typeof charDefinition === 'function') {
|
||||||
@@ -519,14 +540,14 @@ function drawPathFunctionCharacter(
|
|||||||
}
|
}
|
||||||
const f = svgToCanvasInstructionMap[type];
|
const f = svgToCanvasInstructionMap[type];
|
||||||
if (!f) {
|
if (!f) {
|
||||||
console.error(`Could not find drawing instructions for "${type}"`);
|
logService.error(`Could not find drawing instructions for "${type}"`);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const args: string[] = instruction.substring(1).split(',');
|
const args: string[] = instruction.substring(1).split(',');
|
||||||
if (!args[0] || !args[1]) {
|
if (!args[0] || !args[1]) {
|
||||||
continue;
|
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;
|
state.lastCommand = type;
|
||||||
}
|
}
|
||||||
if (strokeWidth !== undefined) {
|
if (strokeWidth !== undefined) {
|
||||||
@@ -537,6 +558,7 @@ function drawPathFunctionCharacter(
|
|||||||
ctx.fill();
|
ctx.fill();
|
||||||
}
|
}
|
||||||
ctx.closePath();
|
ctx.closePath();
|
||||||
|
ctx.restore();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -580,7 +602,8 @@ function drawVectorShape(
|
|||||||
deviceCellWidth: number,
|
deviceCellWidth: number,
|
||||||
deviceCellHeight: number,
|
deviceCellHeight: number,
|
||||||
fontSize: number,
|
fontSize: number,
|
||||||
devicePixelRatio: number
|
devicePixelRatio: number,
|
||||||
|
logService: ILogService
|
||||||
): void {
|
): void {
|
||||||
// Clip the cell to make sure drawing doesn't occur beyond bounds
|
// Clip the cell to make sure drawing doesn't occur beyond bounds
|
||||||
const clipRegion = new Path2D();
|
const clipRegion = new Path2D();
|
||||||
@@ -601,7 +624,7 @@ function drawVectorShape(
|
|||||||
}
|
}
|
||||||
const f = svgToCanvasInstructionMap[type];
|
const f = svgToCanvasInstructionMap[type];
|
||||||
if (!f) {
|
if (!f) {
|
||||||
console.error(`Could not find drawing instructions for "${type}"`);
|
logService.error(`Could not find drawing instructions for "${type}"`);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const args: string[] = instruction.substring(1).split(',');
|
const args: string[] = instruction.substring(1).split(',');
|
||||||
@@ -685,7 +708,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));
|
const result = args.map(e => parseFloat(e) || parseInt(e));
|
||||||
|
|
||||||
if (result.length < 2) {
|
if (result.length < 2) {
|
||||||
@@ -695,10 +718,11 @@ function translateArgs(args: string[], cellWidth: number, cellHeight: number, xO
|
|||||||
for (let x = 0; x < result.length; x += 2) {
|
for (let x = 0; x < result.length; x += 2) {
|
||||||
// Translate from 0-1 to 0-cellWidth
|
// Translate from 0-1 to 0-cellWidth
|
||||||
result[x] *= cellWidth - (leftPadding * devicePixelRatio) - (rightPadding * devicePixelRatio);
|
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
|
// Round to the nearest 0.5 to ensure a crisp line at 100% devicePixelRatio, and optionally
|
||||||
// line at 100% devicePixelRatio
|
// clamp to the cell bounds.
|
||||||
if (doClamp && result[x] !== 0) {
|
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)
|
// Apply the cell's offset (ie. x*cellWidth)
|
||||||
result[x] += xOffset + (leftPadding * devicePixelRatio);
|
result[x] += xOffset + (leftPadding * devicePixelRatio);
|
||||||
@@ -707,10 +731,11 @@ function translateArgs(args: string[], cellWidth: number, cellHeight: number, xO
|
|||||||
for (let y = 1; y < result.length; y += 2) {
|
for (let y = 1; y < result.length; y += 2) {
|
||||||
// Translate from 0-1 to 0-cellHeight
|
// Translate from 0-1 to 0-cellHeight
|
||||||
result[y] *= cellHeight;
|
result[y] *= cellHeight;
|
||||||
// Ensure coordinate doesn't escape cell bounds and round to the nearest 0.5 to ensure a crisp
|
// Round to the nearest 0.5 to ensure a crisp line at 100% devicePixelRatio, and optionally
|
||||||
// line at 100% devicePixelRatio
|
// clamp to the cell bounds.
|
||||||
if (doClamp && result[y] !== 0) {
|
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)
|
// Apply the cell's offset (ie. x*cellHeight)
|
||||||
result[y] += yOffset;
|
result[y] += yOffset;
|
||||||
|
|||||||
@@ -10,7 +10,6 @@
|
|||||||
"outDir": "../out",
|
"outDir": "../out",
|
||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"removeComments": true,
|
"removeComments": true,
|
||||||
"baseUrl": ".",
|
|
||||||
"paths": {
|
"paths": {
|
||||||
"common/*": [
|
"common/*": [
|
||||||
"../../../src/common/*"
|
"../../../src/common/*"
|
||||||
@@ -18,11 +17,11 @@
|
|||||||
"browser/*": [
|
"browser/*": [
|
||||||
"../../../src/browser/*"
|
"../../../src/browser/*"
|
||||||
],
|
],
|
||||||
"vs/*": [
|
|
||||||
"../../../src/vs/*"
|
|
||||||
],
|
|
||||||
"@xterm/addon-webgl": [
|
"@xterm/addon-webgl": [
|
||||||
"../typings/addon-webgl.d.ts"
|
"../typings/addon-webgl.d.ts"
|
||||||
|
],
|
||||||
|
"*": [
|
||||||
|
"./*"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"strict": true,
|
"strict": true,
|
||||||
@@ -42,9 +41,6 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"path": "../../../src/browser"
|
"path": "../../../src/browser"
|
||||||
},
|
|
||||||
{
|
|
||||||
"path": "../../../src/vs"
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,8 +15,10 @@ test.beforeAll(async ({ browser }) => {
|
|||||||
await openTerminal(ctx);
|
await openTerminal(ctx);
|
||||||
ctxWrapper.value = ctx;
|
ctxWrapper.value = ctx;
|
||||||
await ctx.page.evaluate(`
|
await ctx.page.evaluate(`
|
||||||
window.addon = new window.WebglAddon(true);
|
try {
|
||||||
window.term.loadAddon(window.addon);
|
window.addon = new window.WebglAddon(true);
|
||||||
|
window.term.loadAddon(window.addon);
|
||||||
|
} catch (e) {}
|
||||||
`);
|
`);
|
||||||
});
|
});
|
||||||
test.afterAll(async () => await ctx.page.close());
|
test.afterAll(async () => await ctx.page.close());
|
||||||
@@ -24,15 +26,18 @@ test.afterAll(async () => await ctx.page.close());
|
|||||||
test.describe('WebGL Renderer Integration Tests', async () => {
|
test.describe('WebGL Renderer Integration Tests', async () => {
|
||||||
// HACK: webgl2 is often not supported in headless firefox on Linux
|
// HACK: webgl2 is often not supported in headless firefox on Linux
|
||||||
// https://github.com/microsoft/playwright/issues/11566
|
// https://github.com/microsoft/playwright/issues/11566
|
||||||
|
// also disable safari due to #5852
|
||||||
if (platform() === 'linux') {
|
if (platform() === 'linux') {
|
||||||
test.skip(({ browserName }) => browserName === 'firefox');
|
test.skip(({ browserName }) => browserName === 'firefox' || browserName === 'webkit');
|
||||||
}
|
}
|
||||||
|
|
||||||
injectSharedRendererTests(ctxWrapper);
|
injectSharedRendererTests(ctxWrapper);
|
||||||
injectSharedRendererTestsStandalone(ctxWrapper, async () => {
|
injectSharedRendererTestsStandalone(ctxWrapper, async () => {
|
||||||
await ctx.page.evaluate(`
|
await ctx.page.evaluate(`
|
||||||
window.addon = new window.WebglAddon(true);
|
try {
|
||||||
window.term.loadAddon(window.addon);
|
window.addon = new window.WebglAddon(true);
|
||||||
|
window.term.loadAddon(window.addon);
|
||||||
|
} catch (e) {}
|
||||||
`);
|
`);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -7,7 +7,10 @@ const config: PlaywrightTestConfig = {
|
|||||||
{
|
{
|
||||||
name: 'Chromium',
|
name: 'Chromium',
|
||||||
use: {
|
use: {
|
||||||
browserName: 'chromium'
|
browserName: 'chromium',
|
||||||
|
launchOptions: {
|
||||||
|
args: ['--enable-unsafe-swiftshader']
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -9,13 +9,15 @@
|
|||||||
"outDir": "../out-test",
|
"outDir": "../out-test",
|
||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"removeComments": true,
|
"removeComments": true,
|
||||||
"baseUrl": ".",
|
|
||||||
"paths": {
|
"paths": {
|
||||||
"common/*": [
|
"common/*": [
|
||||||
"../../../src/common/*"
|
"../../../src/common/*"
|
||||||
],
|
],
|
||||||
"browser/*": [
|
"browser/*": [
|
||||||
"../../../src/browser/*"
|
"../../../src/browser/*"
|
||||||
|
],
|
||||||
|
"*": [
|
||||||
|
"./*"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"strict": true,
|
"strict": true,
|
||||||
|
|||||||
+2
-3
@@ -127,6 +127,7 @@ if (config.addon) {
|
|||||||
} else if (config.isDemoClient) {
|
} else if (config.isDemoClient) {
|
||||||
bundleConfig = {
|
bundleConfig = {
|
||||||
...bundleConfig,
|
...bundleConfig,
|
||||||
|
sourcemap: false,
|
||||||
entryPoints: [`demo/client/client.ts`],
|
entryPoints: [`demo/client/client.ts`],
|
||||||
outfile: 'demo/dist/client-bundle.js',
|
outfile: 'demo/dist/client-bundle.js',
|
||||||
external: ['util', 'os', 'fs', 'path', 'stream', 'Terminal'],
|
external: ['util', 'os', 'fs', 'path', 'stream', 'Terminal'],
|
||||||
@@ -190,9 +191,7 @@ if (config.addon) {
|
|||||||
entryPoints: [
|
entryPoints: [
|
||||||
'src/browser/**/*.ts',
|
'src/browser/**/*.ts',
|
||||||
'src/common/**/*.ts',
|
'src/common/**/*.ts',
|
||||||
'src/headless/**/*.ts',
|
'src/headless/**/*.ts'
|
||||||
'src/vs/base/**/*.ts',
|
|
||||||
'src/vs/patches/**/*.ts'
|
|
||||||
],
|
],
|
||||||
outdir: 'out-esbuild/'
|
outdir: 'out-esbuild/'
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -57,6 +57,9 @@ xterm.js version: {{version}}
|
|||||||
{{#CSI.length}}
|
{{#CSI.length}}
|
||||||
- [CSI](#csi)
|
- [CSI](#csi)
|
||||||
{{/CSI.length}}
|
{{/CSI.length}}
|
||||||
|
{{#APC.length}}
|
||||||
|
- [APC](#apc)
|
||||||
|
{{/APC.length}}
|
||||||
{{#DCS.length}}
|
{{#DCS.length}}
|
||||||
- [DCS](#dcs)
|
- [DCS](#dcs)
|
||||||
{{/DCS.length}}
|
{{/DCS.length}}
|
||||||
@@ -80,8 +83,9 @@ This document lists xterm.js' support of terminal sequences. The sequences are g
|
|||||||
- CSI - Control Sequence Introducer: sequence starting with \`ESC [\` (7bit) or CSI (\`\\x9B\`, 8bit)
|
- CSI - Control Sequence Introducer: sequence starting with \`ESC [\` (7bit) or CSI (\`\\x9B\`, 8bit)
|
||||||
- DCS - Device Control String: sequence starting with \`ESC P\` (7bit) or DCS (\`\\x90\`, 8bit)
|
- DCS - Device Control String: sequence starting with \`ESC P\` (7bit) or DCS (\`\\x90\`, 8bit)
|
||||||
- OSC - Operating System Command: sequence starting with \`ESC ]\` (7bit) or OSC (\`\\x9D\`, 8bit)
|
- OSC - Operating System Command: sequence starting with \`ESC ]\` (7bit) or OSC (\`\\x9D\`, 8bit)
|
||||||
|
- APC - Application Program Command: sequence starting with \`ESC _\` (7bit) or OSC (\`\\x9F\`, 8bit)
|
||||||
|
|
||||||
Application Program Command (APC), Privacy Message (PM) and Start of String (SOS) are recognized but not supported,
|
Privacy Message (PM) and Start of String (SOS) are recognized but not supported,
|
||||||
any sequence of these types will be silently ignored. They are also not hookable by the API.
|
any sequence of these types will be silently ignored. They are also not hookable by the API.
|
||||||
|
|
||||||
Note that the list only marks sequences implemented in xterm.js' core codebase as supported. Missing sequences are either
|
Note that the list only marks sequences implemented in xterm.js' core codebase as supported. Missing sequences are either
|
||||||
@@ -178,6 +182,33 @@ To denote the sequences the tables use the same abbreviations as xterm does:
|
|||||||
{{/CSI.length}}
|
{{/CSI.length}}
|
||||||
|
|
||||||
|
|
||||||
|
{{#APC.length}}
|
||||||
|
## APC
|
||||||
|
|
||||||
|
| Mnemonic | Name | Sequence | Short Description | Support |
|
||||||
|
| -------- | ---- | -------- | ----------------- | ------- |
|
||||||
|
{{#APC}}
|
||||||
|
| {{mnemonic}} | {{name}} | \`{{sequence}}\` | {{{shortDescription}}} {{#longDescription.length}}_[more](#{{longTarget}}){: .link-details}_{{/longDescription.length}} | {{{status}}} |
|
||||||
|
{{/APC}}
|
||||||
|
|
||||||
|
{{#APC.hasLongDescriptions}}
|
||||||
|
{{#APC}}
|
||||||
|
{{#longDescription.length}}
|
||||||
|
<section class="sequence-details">
|
||||||
|
|
||||||
|
### {{name}}
|
||||||
|
{{#longDescription}}
|
||||||
|
{{{.}}}
|
||||||
|
{{/longDescription}}
|
||||||
|
|
||||||
|
</section>
|
||||||
|
{{/longDescription.length}}
|
||||||
|
{{/APC}}
|
||||||
|
{{/APC.hasLongDescriptions}}
|
||||||
|
|
||||||
|
{{/APC.length}}
|
||||||
|
|
||||||
|
|
||||||
{{#DCS.length}}
|
{{#DCS.length}}
|
||||||
## DCS
|
## DCS
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
// @ts-check
|
||||||
|
|
||||||
|
import { cpSync, existsSync, lstatSync, readFileSync } from 'node:fs';
|
||||||
|
import { spawnSync } from 'node:child_process';
|
||||||
|
import { basename, dirname, resolve, sep } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
|
||||||
|
const nodeModulesPath = resolve(repoRoot, 'node_modules');
|
||||||
|
const npmExecutable = process.platform === 'win32' ? 'npm.cmd' : 'npm';
|
||||||
|
|
||||||
|
/** @typedef {{ folder: string; reason: string }} Candidate */
|
||||||
|
|
||||||
|
/** @param {string} message */
|
||||||
|
function log(message) {
|
||||||
|
console.info(`[setup-fast] ${message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {string[]} args */
|
||||||
|
function runNpm(args) {
|
||||||
|
log(`Running: npm ${args.join(' ')}`);
|
||||||
|
const result = spawnSync(npmExecutable, args, {
|
||||||
|
cwd: repoRoot,
|
||||||
|
stdio: 'inherit'
|
||||||
|
});
|
||||||
|
if (result.error) {
|
||||||
|
throw result.error;
|
||||||
|
}
|
||||||
|
if ((result.status ?? 1) !== 0) {
|
||||||
|
process.exit(result.status ?? 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {Candidate[]} candidates
|
||||||
|
* @param {string | undefined} folder
|
||||||
|
* @param {string} reason
|
||||||
|
*/
|
||||||
|
function addCandidate(candidates, folder, reason) {
|
||||||
|
if (!folder) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (candidates.some(candidate => candidate.folder === folder)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
candidates.push({ folder, reason });
|
||||||
|
log(`Candidate found (${reason}): ${folder}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function detectMainSiblingFolder() {
|
||||||
|
const currentFolderName = basename(repoRoot);
|
||||||
|
if (!currentFolderName.startsWith('xterm.js') || currentFolderName === 'xterm.js') {
|
||||||
|
log(`Current folder is "${currentFolderName}", skipping xterm.js sibling lookup.`);
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const siblingFolder = resolve(dirname(repoRoot), 'xterm.js');
|
||||||
|
log(`Current folder is "${currentFolderName}", sibling main folder candidate: ${siblingFolder}`);
|
||||||
|
return siblingFolder;
|
||||||
|
}
|
||||||
|
|
||||||
|
function detectWorktreeMainFolder() {
|
||||||
|
const gitPath = resolve(repoRoot, '.git');
|
||||||
|
if (!existsSync(gitPath)) {
|
||||||
|
log('No .git entry found at repo root.');
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const gitStat = lstatSync(gitPath);
|
||||||
|
if (!gitStat.isFile()) {
|
||||||
|
log('.git is not a file, this repo does not appear to be a worktree checkout.');
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const gitFileContent = readFileSync(gitPath, 'utf8').trim();
|
||||||
|
const gitDirMatch = /^gitdir:\s*(.+)$/m.exec(gitFileContent);
|
||||||
|
if (!gitDirMatch) {
|
||||||
|
log('Could not parse gitdir from .git file.');
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const gitDirPath = resolve(repoRoot, gitDirMatch[1].trim());
|
||||||
|
log(`Parsed gitdir from .git file: ${gitDirPath}`);
|
||||||
|
|
||||||
|
const normalizedGitDirPath = gitDirPath.replace(/\\/g, '/');
|
||||||
|
const worktreeMarker = '/.git/worktrees/';
|
||||||
|
const markerIndex = normalizedGitDirPath.indexOf(worktreeMarker);
|
||||||
|
if (markerIndex === -1) {
|
||||||
|
log('gitdir path does not contain /.git/worktrees/, skipping worktree main folder lookup.');
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizedMainFolder = normalizedGitDirPath.slice(0, markerIndex);
|
||||||
|
const mainFolder = sep === '/' ? normalizedMainFolder : normalizedMainFolder.split('/').join(sep);
|
||||||
|
log(`Worktree main folder candidate: ${mainFolder}`);
|
||||||
|
return mainFolder;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveSourceFolder() {
|
||||||
|
/** @type {Candidate[]} */
|
||||||
|
const candidates = [];
|
||||||
|
addCandidate(candidates, detectMainSiblingFolder(), 'xterm.js sibling');
|
||||||
|
addCandidate(candidates, detectWorktreeMainFolder(), 'worktree main repo');
|
||||||
|
|
||||||
|
for (const candidate of candidates) {
|
||||||
|
const candidateNodeModulesPath = resolve(candidate.folder, 'node_modules');
|
||||||
|
if (existsSync(candidateNodeModulesPath)) {
|
||||||
|
log(`Using candidate (${candidate.reason}) with node_modules: ${candidate.folder}`);
|
||||||
|
return candidate.folder;
|
||||||
|
}
|
||||||
|
log(`Candidate skipped (${candidate.reason}), node_modules missing: ${candidateNodeModulesPath}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
log('No candidate folder with node_modules was found.');
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!existsSync(nodeModulesPath)) {
|
||||||
|
log(`node_modules missing: ${nodeModulesPath}`);
|
||||||
|
const sourceFolder = resolveSourceFolder();
|
||||||
|
if (sourceFolder) {
|
||||||
|
const sourceNodeModulesPath = resolve(sourceFolder, 'node_modules');
|
||||||
|
log(`Copying node_modules from ${sourceNodeModulesPath} to ${nodeModulesPath}`);
|
||||||
|
try {
|
||||||
|
cpSync(sourceNodeModulesPath, nodeModulesPath, { recursive: true });
|
||||||
|
log('node_modules copy completed.');
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
|
log(`node_modules copy failed: ${message}`);
|
||||||
|
log('Falling back to npm ci.');
|
||||||
|
runNpm(['ci']);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log('No source folder available, running npm ci.');
|
||||||
|
runNpm(['ci']);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log(`node_modules already exists: ${nodeModulesPath}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
runNpm(['run', 'setup']);
|
||||||
@@ -25,7 +25,6 @@ const addons = [
|
|||||||
'clipboard',
|
'clipboard',
|
||||||
'fit',
|
'fit',
|
||||||
'image',
|
'image',
|
||||||
'kitty-graphics',
|
|
||||||
'progress',
|
'progress',
|
||||||
'search',
|
'search',
|
||||||
'serialize',
|
'serialize',
|
||||||
|
|||||||
+24
-11
@@ -218,17 +218,30 @@
|
|||||||
/* Derived from vs/base/browser/ui/scrollbar/media/scrollbar.css */
|
/* Derived from vs/base/browser/ui/scrollbar/media/scrollbar.css */
|
||||||
|
|
||||||
/* xterm.js customization: Override xterm's cursor style */
|
/* xterm.js customization: Override xterm's cursor style */
|
||||||
.xterm .xterm-scrollable-element > .scrollbar {
|
.xterm .xterm-scrollable-element > .xterm-scrollbar {
|
||||||
cursor: default;
|
cursor: default;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Arrows */
|
/* Arrows */
|
||||||
.xterm .xterm-scrollable-element > .scrollbar > .scra {
|
|
||||||
|
.xterm .xterm-scrollable-element > .xterm-scrollbar > .xterm-scra {
|
||||||
cursor: pointer;
|
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;
|
opacity: 1;
|
||||||
|
|
||||||
/* Background rule added for IE9 - to allow clicks on dom node */
|
/* Background rule added for IE9 - to allow clicks on dom node */
|
||||||
@@ -238,20 +251,20 @@
|
|||||||
/* In front of peek view */
|
/* In front of peek view */
|
||||||
z-index: 11;
|
z-index: 11;
|
||||||
}
|
}
|
||||||
.xterm .xterm-scrollable-element > .invisible {
|
.xterm .xterm-scrollable-element > .xterm-invisible {
|
||||||
opacity: 0;
|
opacity: 0;
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
}
|
}
|
||||||
.xterm .xterm-scrollable-element > .invisible.fade {
|
.xterm .xterm-scrollable-element > .xterm-invisible.xterm-fade {
|
||||||
transition: opacity 800ms linear;
|
transition: opacity 800ms linear;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Scrollable Content Inset Shadow */
|
/* Scrollable Content Inset Shadow */
|
||||||
.xterm .xterm-scrollable-element > .shadow {
|
.xterm .xterm-scrollable-element > .xterm-shadow {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
.xterm .xterm-scrollable-element > .shadow.top {
|
.xterm .xterm-scrollable-element > .xterm-shadow.xterm-shadow-top {
|
||||||
display: block;
|
display: block;
|
||||||
top: 0;
|
top: 0;
|
||||||
left: 3px;
|
left: 3px;
|
||||||
@@ -259,7 +272,7 @@
|
|||||||
width: 100%;
|
width: 100%;
|
||||||
box-shadow: var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset;
|
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;
|
display: block;
|
||||||
top: 3px;
|
top: 3px;
|
||||||
left: 0;
|
left: 0;
|
||||||
@@ -267,13 +280,13 @@
|
|||||||
width: 3px;
|
width: 3px;
|
||||||
box-shadow: var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset;
|
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;
|
display: block;
|
||||||
top: 0;
|
top: 0;
|
||||||
left: 0;
|
left: 0;
|
||||||
height: 3px;
|
height: 3px;
|
||||||
width: 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;
|
box-shadow: var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -284,6 +284,7 @@ function createTerminal(): Terminal {
|
|||||||
|
|
||||||
const isWindows = ['Windows', 'Win16', 'Win32', 'WinCE'].indexOf(navigator.platform) >= 0;
|
const isWindows = ['Windows', 'Win16', 'Win32', 'WinCE'].indexOf(navigator.platform) >= 0;
|
||||||
term = new Terminal({
|
term = new Terminal({
|
||||||
|
scrollbar: { showScrollbar: true },
|
||||||
allowProposedApi: true,
|
allowProposedApi: true,
|
||||||
windowsPty: isWindows ? {
|
windowsPty: isWindows ? {
|
||||||
// In a real scenario, these values should be verified on the backend
|
// In a real scenario, these values should be verified on the backend
|
||||||
@@ -616,8 +617,12 @@ function addDomListener(element: HTMLElement, type: string, handler: (...args: a
|
|||||||
}
|
}
|
||||||
|
|
||||||
function updateTerminalSize(): void {
|
function updateTerminalSize(): void {
|
||||||
|
const showScrollbar = term!.options.scrollbar?.showScrollbar ?? true;
|
||||||
|
const scrollBarWidth = (term!.options.scrollback === 0 || !showScrollbar)
|
||||||
|
? 0
|
||||||
|
: (term!.options.scrollbar?.width ?? 14);
|
||||||
const width = optionsWindow.autoResize ? '100%'
|
const width = optionsWindow.autoResize ? '100%'
|
||||||
: ((term as any).dimensions.css.canvas.width + (term as any)._core.viewport.scrollBarWidth).toString() + 'px';
|
: ((term as any).dimensions.css.canvas.width + scrollBarWidth).toString() + 'px';
|
||||||
const height = optionsWindow.autoResize ? '100%'
|
const height = optionsWindow.autoResize ? '100%'
|
||||||
: ((term as any).dimensions.css.canvas.height).toString() + 'px';
|
: ((term as any).dimensions.css.canvas.height).toString() + 'px';
|
||||||
terminalContainer!.style.width = width;
|
terminalContainer!.style.width = width;
|
||||||
|
|||||||
@@ -85,7 +85,7 @@ export class CellInspectorWindow extends BaseWindow implements IControlWindow {
|
|||||||
|
|
||||||
terminal.element.addEventListener('mousemove', (e: MouseEvent) => {
|
terminal.element.addEventListener('mousemove', (e: MouseEvent) => {
|
||||||
const core = (terminal as any)._core;
|
const core = (terminal as any)._core;
|
||||||
const coords = core._mouseService?.getCoords(e, core.screenElement, terminal.cols, terminal.rows);
|
const coords = core._mouseCoordsService?.getCoords(e, core.screenElement, terminal.cols, terminal.rows);
|
||||||
if (!coords) {
|
if (!coords) {
|
||||||
this._clearDisplay();
|
this._clearDisplay();
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -115,17 +115,21 @@ export class OptionsWindow extends BaseWindow implements IControlWindow {
|
|||||||
'documentOverride',
|
'documentOverride',
|
||||||
'linkHandler',
|
'linkHandler',
|
||||||
'logger',
|
'logger',
|
||||||
'overviewRuler',
|
|
||||||
'quirks',
|
'quirks',
|
||||||
|
'scrollbar',
|
||||||
'theme',
|
'theme',
|
||||||
'vtExtensions',
|
'vtExtensions',
|
||||||
'windowOptions',
|
'windowOptions',
|
||||||
'windowsPty',
|
'windowsPty',
|
||||||
];
|
];
|
||||||
const nestedBooleanOptions: { label: string, parent: string, prop: string }[] = [
|
const nestedBooleanOptions: { label: string, path: string[], prop: string }[] = [
|
||||||
{ label: 'vtExtensions.kittyKeyboard', parent: 'vtExtensions', prop: 'kittyKeyboard' },
|
{ label: 'scrollbar.showScrollbar', path: ['scrollbar'], prop: 'showScrollbar' },
|
||||||
{ label: 'vtExtensions.kittySgrBoldFaintControl', parent: 'vtExtensions', prop: 'kittySgrBoldFaintControl' },
|
{ label: 'scrollbar.showArrows', path: ['scrollbar'], prop: 'showArrows' },
|
||||||
{ label: 'vtExtensions.win32InputMode', parent: 'vtExtensions', prop: 'win32InputMode' }
|
{ 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 } = {
|
const stringOptions: { [key: string]: string[] | null } = {
|
||||||
cursorStyle: ['block', 'underline', 'bar'],
|
cursorStyle: ['block', 'underline', 'bar'],
|
||||||
@@ -161,8 +165,10 @@ export class OptionsWindow extends BaseWindow implements IControlWindow {
|
|||||||
booleanOptions.forEach(o => {
|
booleanOptions.forEach(o => {
|
||||||
html += `<div class="option"><label><input id="opt-${o}" type="checkbox" ${(this._terminal.options as Record<string, unknown>)[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 }) => {
|
nestedBooleanOptions.forEach(({ label, path, prop }) => {
|
||||||
const checked = (this._terminal.options as Record<string, Record<string, unknown> | undefined>)[parent]?.[prop] ?? false;
|
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 class="option"><label><input id="opt-${label.replace('.', '-')}" type="checkbox" ${checked ? 'checked' : ''}/> ${label}</label></div>`;
|
||||||
});
|
});
|
||||||
html += '</div><div class="option-group">';
|
html += '</div><div class="option-group">';
|
||||||
@@ -196,11 +202,22 @@ export class OptionsWindow extends BaseWindow implements IControlWindow {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
nestedBooleanOptions.forEach(({ label, parent, prop }) => {
|
nestedBooleanOptions.forEach(({ label, path, prop }) => {
|
||||||
const input = document.getElementById(`opt-${label.replace('.', '-')}`) as HTMLInputElement;
|
const input = document.getElementById(`opt-${label.replace('.', '-')}`) as HTMLInputElement;
|
||||||
addDomListener(input, 'change', () => {
|
addDomListener(input, 'change', () => {
|
||||||
console.log('change', label, input.checked);
|
console.log('change', label, input.checked);
|
||||||
(this._terminal.options as Record<string, unknown>)[parent] = { ...(this._terminal.options as Record<string, Record<string, unknown> | undefined>)[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 => {
|
numberOptions.forEach(o => {
|
||||||
@@ -235,6 +252,11 @@ export class OptionsWindow extends BaseWindow implements IControlWindow {
|
|||||||
input.value = 'auto';
|
input.value = 'auto';
|
||||||
this._handlers.updateTerminalSize();
|
this._handlers.updateTerminalSize();
|
||||||
}
|
}
|
||||||
|
const screenElement = document.querySelector('.xterm-screen');
|
||||||
|
if (screenElement instanceof HTMLElement) {
|
||||||
|
screenElement.style.outline = this._autoResize ? ''
|
||||||
|
: 'solid thin red';
|
||||||
|
}
|
||||||
} else if (o === 'theme') {
|
} else if (o === 'theme') {
|
||||||
value = this._getTheme();
|
value = this._getTheme();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -397,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');
|
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 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}'];
|
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}'];
|
||||||
@@ -698,13 +705,13 @@ function loadTest(term: Terminal, addons: AddonCollection): void {
|
|||||||
term.write('', () => {
|
term.write('', () => {
|
||||||
const time = Math.round(performance.now() - start);
|
const time = Math.round(performance.now() - start);
|
||||||
const mbs = ((byteCount / 1024) * (1 / (time / 1000))).toFixed(2);
|
const mbs = ((byteCount / 1024) * (1 / (time / 1000))).toFixed(2);
|
||||||
term.write(`\n\r\nWrote ${byteCount}kB in ${time}ms (${mbs}MB/s) using the (${rendererName} renderer)`);
|
term.write(`\n\r\nWrote ${byteCount}KiB in ${time}ms (${mbs}MiB/s) using the (${rendererName} renderer)`);
|
||||||
// Send ^C to get a new prompt
|
// Send ^C to get a new prompt
|
||||||
(term as any)._core._onData.fire('\x03');
|
(term as any)._core._onData.fire('\x03');
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function loadTestLongLines(term: Terminal, addons: AddonCollection): void {
|
async function loadTestLongLines(term: Terminal, addons: AddonCollection): Promise<void> {
|
||||||
const rendererName = addons.webgl.instance ? 'webgl' : 'dom';
|
const rendererName = addons.webgl.instance ? 'webgl' : 'dom';
|
||||||
const testData = [];
|
const testData = [];
|
||||||
let byteCount = 0;
|
let byteCount = 0;
|
||||||
@@ -722,23 +729,30 @@ function loadTestLongLines(term: Terminal, addons: AddonCollection): void {
|
|||||||
testData.push(data);
|
testData.push(data);
|
||||||
}
|
}
|
||||||
const start = performance.now();
|
const start = performance.now();
|
||||||
for (let i = 0; i < 1024 * 50; i++) {
|
for (let i = 0; i < 1024; i++) {
|
||||||
for (const d of testData) {
|
for (const d of testData) {
|
||||||
term.write(d);
|
try {
|
||||||
|
term.write(d);
|
||||||
|
} catch {
|
||||||
|
// Flush events when cap is hit and try again(workaround for not having flow control in
|
||||||
|
// demo)
|
||||||
|
await new Promise<void>(r => term.write('', () => r()));
|
||||||
|
term.write(d);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Wait for all data to be parsed before evaluating time
|
// Wait for all data to be parsed before evaluating time
|
||||||
term.write('', () => {
|
term.write('', () => {
|
||||||
const time = Math.round(performance.now() - start);
|
const time = Math.round(performance.now() - start);
|
||||||
const mbs = ((byteCount / 1024) * (1 / (time / 1000))).toFixed(2);
|
const mbs = ((byteCount / 1024) * (1 / (time / 1000))).toFixed(2);
|
||||||
term.write(`\n\r\nWrote ${byteCount}kB in ${time}ms (${mbs}MB/s) using the (${rendererName} renderer)`);
|
term.write(`\n\r\nWrote ${byteCount}KiB in ${time}ms (${mbs}MiB/s) using the (${rendererName} renderer)`);
|
||||||
// Send ^C to get a new prompt
|
// Send ^C to get a new prompt
|
||||||
(term as any)._core._onData.fire('\x03');
|
(term as any)._core._onData.fire('\x03');
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function addDecoration(term: Terminal, dim: number = 1): 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 marker = term.registerMarker(1);
|
||||||
const decoration = term.registerDecoration({
|
const decoration = term.registerDecoration({
|
||||||
marker,
|
marker,
|
||||||
@@ -755,7 +769,7 @@ function addDecoration(term: Terminal, dim: number = 1): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function addOverviewRuler(term: Terminal): void {
|
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(1), overviewRulerOptions: { color: '#ef2929' } });
|
||||||
term.registerDecoration({ marker: term.registerMarker(3), overviewRulerOptions: { color: '#8ae234' } });
|
term.registerDecoration({ marker: term.registerMarker(3), overviewRulerOptions: { color: '#8ae234' } });
|
||||||
term.registerDecoration({ marker: term.registerMarker(5), overviewRulerOptions: { color: '#729fcf' } });
|
term.registerDecoration({ marker: term.registerMarker(5), overviewRulerOptions: { color: '#729fcf' } });
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user