@opentui/core 0.6.8 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/NativeScene.d.ts +14 -29
  2. package/Renderable.d.ts +47 -34
  3. package/animation/Timeline.d.ts +9 -0
  4. package/audio.d.ts +1 -0
  5. package/buffer.d.ts +6 -2
  6. package/{chunk-bun-4e5bpeqh.js → chunk-bun-6kxdhkdc.js} +1243 -1034
  7. package/chunk-bun-6kxdhkdc.js.map +70 -0
  8. package/{chunk-bun-ehr9v0n8.js → chunk-bun-x6cz4jyg.js} +514 -84
  9. package/chunk-bun-x6cz4jyg.js.map +35 -0
  10. package/{chunk-node-yyjd8p1g.js → chunk-node-q5ccgbk5.js} +1243 -1034
  11. package/chunk-node-q5ccgbk5.js.map +70 -0
  12. package/{chunk-node-jhq62x0c.js → chunk-node-y0w0hq5m.js} +514 -84
  13. package/chunk-node-y0w0hq5m.js.map +34 -0
  14. package/edit-buffer.d.ts +4 -0
  15. package/index.bun.js +1086 -549
  16. package/index.bun.js.map +15 -13
  17. package/index.d.ts +1 -1
  18. package/index.node.js +1086 -549
  19. package/index.node.js.map +16 -12
  20. package/lib/detect-links.d.ts +2 -0
  21. package/lib/extmarks.d.ts +3 -1
  22. package/lib/parse.keypress-kitty.d.ts +2 -0
  23. package/lib/scroll-chain.d.ts +16 -0
  24. package/lib/stdin-parser-native.d.ts +90 -0
  25. package/lib/stdin-parser.d.ts +2 -0
  26. package/lib/terminal-capability-detection.d.ts +6 -1
  27. package/native-abi.generated.d.ts +700 -7
  28. package/package.json +9 -9
  29. package/renderables/Box.d.ts +2 -2
  30. package/renderables/Code.d.ts +2 -1
  31. package/renderables/Diff.d.ts +2 -2
  32. package/renderables/EditBufferRenderable.d.ts +2 -2
  33. package/renderables/EmbeddedTerminal.d.ts +2 -2
  34. package/renderables/FrameBuffer.d.ts +4 -3
  35. package/renderables/Image.d.ts +2 -2
  36. package/renderables/Markdown.d.ts +2 -2
  37. package/renderables/ScrollBar.d.ts +9 -3
  38. package/renderables/ScrollBox.d.ts +87 -44
  39. package/renderables/ScrollBoxParts.d.ts +165 -0
  40. package/renderables/Slider.d.ts +2 -2
  41. package/renderables/Text.d.ts +2 -2
  42. package/renderables/TextBufferRenderable.d.ts +2 -4
  43. package/renderables/index.d.ts +1 -1
  44. package/renderer-theme-mode.d.ts +1 -6
  45. package/renderer.d.ts +30 -7
  46. package/testing/test-renderer.d.ts +4 -0
  47. package/testing.bun.js +12 -4
  48. package/testing.bun.js.map +3 -3
  49. package/testing.js +12 -4
  50. package/testing.js.map +3 -3
  51. package/types.d.ts +11 -0
  52. package/yoga.bun.js +1 -1
  53. package/yoga.internal.d.ts +3 -3
  54. package/yoga.js +1 -1
  55. package/zig-structs.d.ts +26 -0
  56. package/zig.d.ts +96 -13
  57. package/chunk-bun-4e5bpeqh.js.map +0 -69
  58. package/chunk-bun-ehr9v0n8.js.map +0 -35
  59. package/chunk-node-jhq62x0c.js.map +0 -34
  60. package/chunk-node-yyjd8p1g.js.map +0 -69
@@ -1,4 +1,5 @@
1
1
  import {
2
+ nativeLayouts,
2
3
  nativeConstants,
3
4
  toArrayBuffer,
4
5
  singleton,
@@ -63,7 +64,7 @@ import {
63
64
  PositionType2,
64
65
  Unit2,
65
66
  Wrap2
66
- } from "./chunk-node-jhq62x0c.js";
67
+ } from "./chunk-node-y0w0hq5m.js";
67
68
 
68
69
  // src/lib/border.ts
69
70
  var VALID_BORDER_STYLES = ["single", "double", "rounded", "heavy"];
@@ -3285,237 +3286,6 @@ function renderFontToFrameBuffer2(buffer, {
3285
3286
  };
3286
3287
  }
3287
3288
 
3288
- // src/syntax-style.ts
3289
- function cloneStyle(style) {
3290
- return {
3291
- ...style,
3292
- fg: style.fg ? RGBA2.clone(style.fg) : undefined,
3293
- bg: style.bg ? RGBA2.clone(style.bg) : undefined
3294
- };
3295
- }
3296
- function convertThemeToStyles2(theme) {
3297
- const flatStyles = {};
3298
- for (const tokenStyle of theme) {
3299
- const styleDefinition = {};
3300
- if (tokenStyle.style.foreground) {
3301
- styleDefinition.fg = parseColor2(tokenStyle.style.foreground);
3302
- }
3303
- if (tokenStyle.style.background) {
3304
- styleDefinition.bg = parseColor2(tokenStyle.style.background);
3305
- }
3306
- if (tokenStyle.style.bold !== undefined) {
3307
- styleDefinition.bold = tokenStyle.style.bold;
3308
- }
3309
- if (tokenStyle.style.italic !== undefined) {
3310
- styleDefinition.italic = tokenStyle.style.italic;
3311
- }
3312
- if (tokenStyle.style.underline !== undefined) {
3313
- styleDefinition.underline = tokenStyle.style.underline;
3314
- }
3315
- if (tokenStyle.style.dim !== undefined) {
3316
- styleDefinition.dim = tokenStyle.style.dim;
3317
- }
3318
- for (const scope of tokenStyle.scope) {
3319
- flatStyles[scope] = cloneStyle(styleDefinition);
3320
- }
3321
- }
3322
- return flatStyles;
3323
- }
3324
-
3325
- class SyntaxStyle2 {
3326
- lib;
3327
- native;
3328
- _destroyed = false;
3329
- nameCache = new Map;
3330
- styleDefs = new Map;
3331
- mergedCache = new Map;
3332
- constructor(lib, handle, source) {
3333
- const owner = source?.resourceContext;
3334
- if (!owner)
3335
- throw new Error("SyntaxStyle requires an explicit resource owner");
3336
- owner.assertAlive();
3337
- if (owner.renderLib !== lib || !handle || typeof handle !== "object" || handle.context !== owner.context) {
3338
- throw new Error("SyntaxStyle Context owner mismatch");
3339
- }
3340
- this.lib = lib;
3341
- this.native = { owner, handle };
3342
- }
3343
- static create(source) {
3344
- const owner = source?.resourceContext;
3345
- if (!owner)
3346
- throw new Error("SyntaxStyle requires an explicit resource owner: pass renderer.nativeScene, or a ResourceContext when there is no renderer");
3347
- owner.assertAlive();
3348
- const lib = owner.renderLib;
3349
- const handle = lib.createContextSyntaxStyle(owner.context);
3350
- try {
3351
- return new SyntaxStyle2(lib, handle, owner);
3352
- } catch (error) {
3353
- lib.destroyContextSyntaxStyle(owner.context, handle);
3354
- throw error;
3355
- }
3356
- }
3357
- static fromTheme(theme, owner) {
3358
- return SyntaxStyle2.fromStyles(convertThemeToStyles2(theme), owner);
3359
- }
3360
- static fromStyles(styles, owner) {
3361
- const style = SyntaxStyle2.create(owner);
3362
- try {
3363
- for (const [name, styleDef] of styles instanceof Map ? styles : Object.entries(styles)) {
3364
- style.registerStyle(name, styleDef);
3365
- }
3366
- return style;
3367
- } catch (error) {
3368
- style.destroy();
3369
- throw error;
3370
- }
3371
- }
3372
- guard() {
3373
- if (this._destroyed)
3374
- throw new Error("NativeSyntaxStyle is destroyed");
3375
- this.native.owner.assertAlive();
3376
- }
3377
- _getSceneHandle(scene) {
3378
- this.guard();
3379
- if (this.native.owner !== scene.resourceContext)
3380
- throw new Error("SyntaxStyle owner mismatch: bind definitions in the destination Context");
3381
- return this.native.handle;
3382
- }
3383
- registerStyle(name, style) {
3384
- this.guard();
3385
- const { bold, italic, underline, dim, fg: foreground, bg: background } = style;
3386
- const definition = {
3387
- bold,
3388
- italic,
3389
- underline,
3390
- dim,
3391
- fg: foreground ? RGBA2.clone(parseColor2(foreground)) : undefined,
3392
- bg: background ? RGBA2.clone(parseColor2(background)) : undefined
3393
- };
3394
- const attributes = createTextAttributes2(definition);
3395
- const fg = definition.fg ?? null;
3396
- const bg = definition.bg ?? null;
3397
- return this.lib.getYogaHost().runMutation(() => {
3398
- const id = this.lib.contextSyntaxStyleRegister(this.native.handle.context, this.native.handle, name, {
3399
- fg,
3400
- bg,
3401
- attributes
3402
- });
3403
- this.nameCache.set(name, id);
3404
- this.styleDefs.set(name, definition);
3405
- this.mergedCache.clear();
3406
- return id;
3407
- });
3408
- }
3409
- resolveStyleId(name) {
3410
- this.guard();
3411
- const cached = this.nameCache.get(name);
3412
- if (cached !== undefined)
3413
- return cached;
3414
- const id = this.lib.contextSyntaxStyleResolveByName(this.native.handle.context, this.native.handle, name);
3415
- if (id !== null) {
3416
- this.nameCache.set(name, id);
3417
- }
3418
- return id;
3419
- }
3420
- getStyleId(name) {
3421
- this.guard();
3422
- const id = this.resolveStyleId(name);
3423
- if (id !== null)
3424
- return id;
3425
- if (name.includes(".")) {
3426
- const baseName = name.split(".")[0];
3427
- return this.resolveStyleId(baseName);
3428
- }
3429
- return null;
3430
- }
3431
- getStyleCount() {
3432
- this.guard();
3433
- return this.lib.contextSyntaxStyleGetStyleCount(this.native.handle.context, this.native.handle);
3434
- }
3435
- clearNameCache() {
3436
- this.guard();
3437
- this.nameCache.clear();
3438
- }
3439
- getStyle(name) {
3440
- this.guard();
3441
- const style = this.styleDefs.get(name);
3442
- if (style)
3443
- return cloneStyle(style);
3444
- if (name.includes(".")) {
3445
- const baseName = name.split(".")[0];
3446
- const base = this.styleDefs.get(baseName);
3447
- return base ? cloneStyle(base) : undefined;
3448
- }
3449
- return;
3450
- }
3451
- mergeStyles(...styleNames) {
3452
- this.guard();
3453
- const cacheKey = styleNames.join(":");
3454
- const cached = this.mergedCache.get(cacheKey);
3455
- if (cached)
3456
- return cloneStyle(cached);
3457
- const styleDefinition = {};
3458
- for (const name of styleNames) {
3459
- const style = this.getStyle(name);
3460
- if (!style)
3461
- continue;
3462
- if (style.fg)
3463
- styleDefinition.fg = style.fg;
3464
- if (style.bg)
3465
- styleDefinition.bg = style.bg;
3466
- if (style.bold !== undefined)
3467
- styleDefinition.bold = style.bold;
3468
- if (style.italic !== undefined)
3469
- styleDefinition.italic = style.italic;
3470
- if (style.underline !== undefined)
3471
- styleDefinition.underline = style.underline;
3472
- if (style.dim !== undefined)
3473
- styleDefinition.dim = style.dim;
3474
- }
3475
- const attributes = createTextAttributes2({
3476
- bold: styleDefinition.bold,
3477
- italic: styleDefinition.italic,
3478
- underline: styleDefinition.underline,
3479
- dim: styleDefinition.dim
3480
- });
3481
- const merged = {
3482
- fg: styleDefinition.fg,
3483
- bg: styleDefinition.bg,
3484
- attributes
3485
- };
3486
- this.mergedCache.set(cacheKey, merged);
3487
- return cloneStyle(merged);
3488
- }
3489
- clearCache() {
3490
- this.guard();
3491
- this.mergedCache.clear();
3492
- }
3493
- getCacheSize() {
3494
- this.guard();
3495
- return this.mergedCache.size;
3496
- }
3497
- getAllStyles() {
3498
- this.guard();
3499
- return new Map(Array.from(this.styleDefs, ([name, style]) => [name, cloneStyle(style)]));
3500
- }
3501
- getRegisteredNames() {
3502
- this.guard();
3503
- return Array.from(this.styleDefs.keys());
3504
- }
3505
- destroy() {
3506
- if (this._destroyed)
3507
- return;
3508
- this.lib.getYogaHost().runMutation(() => {
3509
- if (!this.native.owner.disposed)
3510
- this.lib.destroyContextSyntaxStyle(this.native.handle.context, this.native.handle);
3511
- this._destroyed = true;
3512
- this.nameCache.clear();
3513
- this.styleDefs.clear();
3514
- this.mergedCache.clear();
3515
- });
3516
- }
3517
- }
3518
-
3519
3289
  // src/lib/hast-styled-text.ts
3520
3290
  function hastToTextChunks(node, syntaxStyle, parentStyles = []) {
3521
3291
  const chunks = [];
@@ -5012,7 +4782,8 @@ var DEFAULT_PROTOCOL_CONTEXT = {
5012
4782
  privateCapabilityRepliesActive: false,
5013
4783
  pixelResolutionQueryActive: false,
5014
4784
  explicitWidthCprActive: false,
5015
- startupCursorCprActive: false
4785
+ startupCursorCprActive: false,
4786
+ replySentinelActive: false
5016
4787
  };
5017
4788
  var RXVT_DOLLAR_CSI_RE = /^\x1b\[\d+\$$/;
5018
4789
  var SYSTEM_CLOCK = new SystemClock2;
@@ -8049,7 +7820,7 @@ class ExtmarksController2 {
8049
7820
  this.originalMoveCursorLeft();
8050
7821
  return;
8051
7822
  }
8052
- const currentOffset = this.editorView.getVisualCursor().offset;
7823
+ const currentOffset = this.editBuffer.getCursorPosition().offset;
8053
7824
  const hasSelection = this.editorView.hasSelection();
8054
7825
  if (hasSelection) {
8055
7826
  this.originalMoveCursorLeft();
@@ -8072,7 +7843,7 @@ class ExtmarksController2 {
8072
7843
  this.originalMoveCursorRight();
8073
7844
  return;
8074
7845
  }
8075
- const currentOffset = this.editorView.getVisualCursor().offset;
7846
+ const currentOffset = this.editBuffer.getCursorPosition().offset;
8076
7847
  const hasSelection = this.editorView.hasSelection();
8077
7848
  if (hasSelection) {
8078
7849
  this.originalMoveCursorRight();
@@ -8100,9 +7871,9 @@ class ExtmarksController2 {
8100
7871
  this.originalMoveUpVisual();
8101
7872
  return;
8102
7873
  }
8103
- const currentOffset = this.editorView.getVisualCursor().offset;
7874
+ const currentOffset = this.editBuffer.getCursorPosition().offset;
8104
7875
  this.originalMoveUpVisual();
8105
- const newOffset = this.editorView.getVisualCursor().offset;
7876
+ const newOffset = this.editBuffer.getCursorPosition().offset;
8106
7877
  const virtualExtmark = this.findVirtualExtmarkContaining(newOffset);
8107
7878
  if (virtualExtmark) {
8108
7879
  const distanceToStart = newOffset - virtualExtmark.start;
@@ -8124,9 +7895,9 @@ class ExtmarksController2 {
8124
7895
  this.originalMoveDownVisual();
8125
7896
  return;
8126
7897
  }
8127
- const currentOffset = this.editorView.getVisualCursor().offset;
7898
+ const currentOffset = this.editBuffer.getCursorPosition().offset;
8128
7899
  this.originalMoveDownVisual();
8129
- const newOffset = this.editorView.getVisualCursor().offset;
7900
+ const newOffset = this.editBuffer.getCursorPosition().offset;
8130
7901
  const virtualExtmark = this.findVirtualExtmarkContaining(newOffset);
8131
7902
  if (virtualExtmark) {
8132
7903
  const distanceToStart = newOffset - virtualExtmark.start;
@@ -8145,7 +7916,7 @@ class ExtmarksController2 {
8145
7916
  this.originalSetCursorByOffset(offset);
8146
7917
  return;
8147
7918
  }
8148
- const currentOffset = this.editorView.getVisualCursor().offset;
7919
+ const currentOffset = this.editBuffer.getCursorPosition().offset;
8149
7920
  const hasSelection = this.editorView.hasSelection();
8150
7921
  if (hasSelection) {
8151
7922
  this.originalSetCursorByOffset(offset);
@@ -8175,7 +7946,7 @@ class ExtmarksController2 {
8175
7946
  this.originalDeleteCharBackward();
8176
7947
  return;
8177
7948
  }
8178
- const currentOffset = this.editorView.getVisualCursor().offset;
7949
+ const currentOffset = this.editBuffer.getCursorPosition().offset;
8179
7950
  const hadSelection = this.editorView.hasSelection();
8180
7951
  if (currentOffset === 0 || hadSelection) {
8181
7952
  this.originalDeleteCharBackward();
@@ -8188,27 +7959,23 @@ class ExtmarksController2 {
8188
7959
  const startCursor = this.offsetToPosition(virtualExtmark.start);
8189
7960
  const endCursor = this.offsetToPosition(virtualExtmark.end);
8190
7961
  const deleteOffset = virtualExtmark.start;
8191
- const deleteLength = virtualExtmark.end - virtualExtmark.start;
8192
- this.originalDeleteRange(startCursor.row, startCursor.col, endCursor.row, endCursor.col);
7962
+ const change = this.measureChange(() => this.originalDeleteRange(startCursor.row, startCursor.col, endCursor.row, endCursor.col));
8193
7963
  this.saveSnapshot();
8194
7964
  this.deleteExtmarkById(virtualExtmark.id);
8195
- this.adjustExtmarksAfterDeletion(deleteOffset, deleteLength);
7965
+ this.shiftExtmarks(deleteOffset, change);
8196
7966
  return;
8197
7967
  }
8198
- this.originalDeleteCharBackward();
7968
+ const deleteOffset = this.editBuffer._getPrevCharBoundary().offset;
7969
+ const change = this.measureChange(() => this.originalDeleteCharBackward());
8199
7970
  this.saveSnapshot();
8200
- const deleteOffset = this.editBuffer.getCursorPosition().offset;
8201
- const deleteLength = currentOffset - deleteOffset;
8202
- if (deleteLength > 0) {
8203
- this.adjustExtmarksAfterDeletion(deleteOffset, deleteLength);
8204
- }
7971
+ this.shiftExtmarks(deleteOffset, change);
8205
7972
  });
8206
7973
  this.editBuffer.deleteChar = () => this.editBuffer.runMutation(() => {
8207
7974
  if (this.destroyed) {
8208
7975
  this.originalDeleteChar();
8209
7976
  return;
8210
7977
  }
8211
- const currentOffset = this.editorView.getVisualCursor().offset;
7978
+ const currentOffset = this.editBuffer.getCursorPosition().offset;
8212
7979
  const hadSelection = this.editorView.hasSelection();
8213
7980
  if (hadSelection) {
8214
7981
  this.originalDeleteChar();
@@ -8221,32 +7988,25 @@ class ExtmarksController2 {
8221
7988
  const startCursor = this.offsetToPosition(virtualExtmark.start);
8222
7989
  const endCursor = this.offsetToPosition(virtualExtmark.end);
8223
7990
  const deleteOffset = virtualExtmark.start;
8224
- const deleteLength = virtualExtmark.end - virtualExtmark.start;
8225
- this.originalDeleteRange(startCursor.row, startCursor.col, endCursor.row, endCursor.col);
7991
+ const change = this.measureChange(() => this.originalDeleteRange(startCursor.row, startCursor.col, endCursor.row, endCursor.col));
8226
7992
  this.saveSnapshot();
8227
7993
  this.deleteExtmarkById(virtualExtmark.id);
8228
- this.adjustExtmarksAfterDeletion(deleteOffset, deleteLength);
7994
+ this.shiftExtmarks(deleteOffset, change);
8229
7995
  return;
8230
7996
  }
8231
- const deleteEndOffset = this.getNextCursorOffset(currentOffset);
8232
- const deleteLength = deleteEndOffset - currentOffset;
8233
- this.originalDeleteChar();
7997
+ const change = this.measureChange(() => this.originalDeleteChar());
8234
7998
  this.saveSnapshot();
8235
- if (deleteLength > 0) {
8236
- this.adjustExtmarksAfterDeletion(currentOffset, deleteLength);
8237
- }
7999
+ this.shiftExtmarks(currentOffset, change);
8238
8000
  });
8239
8001
  this.editBuffer.deleteRange = (startLine, startCol, endLine, endCol) => this.editBuffer.runMutation(() => {
8240
8002
  if (this.destroyed) {
8241
8003
  this.originalDeleteRange(startLine, startCol, endLine, endCol);
8242
8004
  return;
8243
8005
  }
8244
- const startOffset = this.positionToOffset(startLine, startCol);
8245
- const endOffset = this.positionToOffset(endLine, endCol);
8246
- const length = endOffset - startOffset;
8247
- this.originalDeleteRange(startLine, startCol, endLine, endCol);
8006
+ const startOffset = Math.min(this.positionToOffset(startLine, startCol), this.positionToOffset(endLine, endCol));
8007
+ const change = this.measureChange(() => this.originalDeleteRange(startLine, startCol, endLine, endCol));
8248
8008
  this.saveSnapshot();
8249
- this.adjustExtmarksAfterDeletion(startOffset, length);
8009
+ this.shiftExtmarks(startOffset, change);
8250
8010
  });
8251
8011
  this.editBuffer.deleteLine = () => this.editBuffer.runMutation(() => {
8252
8012
  if (this.destroyed) {
@@ -8267,26 +8027,20 @@ class ExtmarksController2 {
8267
8027
  this.originalInsertText(text);
8268
8028
  return;
8269
8029
  }
8270
- const currentOffset = this.editorView.getVisualCursor().offset;
8271
- this.originalInsertText(text);
8030
+ const currentOffset = this.editBuffer.getCursorPosition().offset;
8031
+ const change = this.measureChange(() => this.originalInsertText(text));
8272
8032
  this.saveSnapshot();
8273
- const insertLength = this.editBuffer.getCursorPosition().offset - currentOffset;
8274
- if (insertLength > 0) {
8275
- this.adjustExtmarksAfterInsertion(currentOffset, insertLength);
8276
- }
8033
+ this.shiftExtmarks(currentOffset, change);
8277
8034
  });
8278
8035
  this.editBuffer.insertChar = (char) => this.editBuffer.runMutation(() => {
8279
8036
  if (this.destroyed) {
8280
8037
  this.originalInsertChar(char);
8281
8038
  return;
8282
8039
  }
8283
- const currentOffset = this.editorView.getVisualCursor().offset;
8284
- this.originalInsertChar(char);
8040
+ const currentOffset = this.editBuffer.getCursorPosition().offset;
8041
+ const change = this.measureChange(() => this.originalInsertChar(char));
8285
8042
  this.saveSnapshot();
8286
- const insertLength = this.editBuffer.getCursorPosition().offset - currentOffset;
8287
- if (insertLength > 0) {
8288
- this.adjustExtmarksAfterInsertion(currentOffset, insertLength);
8289
- }
8043
+ this.shiftExtmarks(currentOffset, change);
8290
8044
  });
8291
8045
  this.editBuffer.setText = (text) => {
8292
8046
  if (this.destroyed) {
@@ -8323,7 +8077,7 @@ class ExtmarksController2 {
8323
8077
  this.originalNewLine();
8324
8078
  return;
8325
8079
  }
8326
- const currentOffset = this.editorView.getVisualCursor().offset;
8080
+ const currentOffset = this.editBuffer.getCursorPosition().offset;
8327
8081
  this.originalNewLine();
8328
8082
  this.saveSnapshot();
8329
8083
  this.adjustExtmarksAfterInsertion(currentOffset, 1);
@@ -8335,21 +8089,19 @@ class ExtmarksController2 {
8335
8089
  return this.originalEditorViewReplaceSelectedText(text);
8336
8090
  const selection = this.editorView.getSelection();
8337
8091
  const deleteOffset = selection ? Math.min(selection.start, selection.end) : 0;
8338
- const deleteLength = selection ? Math.abs(selection.end - selection.start) : 0;
8339
8092
  const cursorOffset = this.editBuffer.getCursorPosition().offset;
8340
- const result = this.originalEditorViewReplaceSelectedText(text);
8093
+ let result;
8094
+ const change = this.measureChange(() => result = this.originalEditorViewReplaceSelectedText(text));
8341
8095
  const insertOffset = result.deleted ? deleteOffset : cursorOffset;
8096
+ const insertLength = result.inserted ? this.editBuffer.getCursorPosition().offset - insertOffset : 0;
8342
8097
  if (result.deleted) {
8343
8098
  this.saveSnapshot();
8344
- if (deleteLength > 0)
8345
- this.adjustExtmarksAfterDeletion(deleteOffset, deleteLength, false);
8099
+ this.shiftExtmarks(deleteOffset, change - insertLength, false);
8346
8100
  }
8347
8101
  if (result.inserted)
8348
8102
  this.saveSnapshot();
8349
- const insertLength = this.editBuffer.getCursorPosition().offset - insertOffset;
8350
- if (insertLength > 0)
8351
- this.adjustExtmarksAfterInsertion(insertOffset, insertLength, false);
8352
- if (deleteLength > 0 || insertLength > 0)
8103
+ this.shiftExtmarks(insertOffset, insertLength, false);
8104
+ if (change !== 0 || insertLength !== 0)
8353
8105
  this.updateHighlights();
8354
8106
  return result;
8355
8107
  });
@@ -8365,12 +8117,9 @@ class ExtmarksController2 {
8365
8117
  return;
8366
8118
  }
8367
8119
  const deleteOffset = Math.min(selection.start, selection.end);
8368
- const deleteLength = Math.abs(selection.end - selection.start);
8369
- this.originalEditorViewDeleteSelectedText();
8120
+ const change = this.measureChange(() => this.originalEditorViewDeleteSelectedText());
8370
8121
  this.saveSnapshot();
8371
- if (deleteLength > 0) {
8372
- this.adjustExtmarksAfterDeletion(deleteOffset, deleteLength);
8373
- }
8122
+ this.shiftExtmarks(deleteOffset, change);
8374
8123
  });
8375
8124
  }
8376
8125
  setupContentChangeListener() {
@@ -8441,11 +8190,16 @@ class ExtmarksController2 {
8441
8190
  positionToOffset(row, col) {
8442
8191
  return this.editBuffer.positionToOffset(row, col);
8443
8192
  }
8444
- getNextCursorOffset(currentOffset) {
8445
- this.originalMoveCursorRight();
8446
- const nextOffset = this.editorView.getVisualCursor().offset;
8447
- this.originalSetCursorByOffset(currentOffset);
8448
- return nextOffset;
8193
+ measureChange(edit) {
8194
+ const before = this.editBuffer._getEOF().offset;
8195
+ edit();
8196
+ return this.editBuffer._getEOF().offset - before;
8197
+ }
8198
+ shiftExtmarks(offset, change, updateHighlights = true) {
8199
+ if (change > 0)
8200
+ this.adjustExtmarksAfterInsertion(offset, change, updateHighlights);
8201
+ else if (change < 0)
8202
+ this.adjustExtmarksAfterDeletion(offset, -change, updateHighlights);
8449
8203
  }
8450
8204
  updateHighlights() {
8451
8205
  this.editBuffer.clearAllHighlights();
@@ -9687,12 +9441,13 @@ function detectLinks2(chunks, context) {
9687
9441
  highlightedIndex++;
9688
9442
  if (highlightedIndex < ranges.length && ranges[highlightedIndex].start < end)
9689
9443
  continue;
9690
- ranges.push({ start, end, url });
9444
+ ranges.push({ start, end, url, bare: true });
9691
9445
  }
9692
9446
  }
9693
9447
  if (ranges.length === 0)
9694
9448
  return chunks;
9695
9449
  ranges.sort((a, b) => a.start - b.start || b.end - a.end || Number(b.label ?? false) - Number(a.label ?? false));
9450
+ const bareStyle = context.syntaxStyle?.mergeStyles("markup.link.label");
9696
9451
  const linkedChunks = [];
9697
9452
  let contentPos = 0;
9698
9453
  let rangeIndex = 0;
@@ -9731,16 +9486,16 @@ function detectLinks2(chunks, context) {
9731
9486
  if (linkStart > position) {
9732
9487
  linkedChunks.push({ ...chunk, text: chunk.text.slice(position - start, linkStart - start) });
9733
9488
  }
9734
- if (linkStart === start && linkEnd === end) {
9735
- chunk.link = { url: range.url };
9736
- linkedChunks.push(chunk);
9737
- } else {
9738
- linkedChunks.push({
9739
- ...chunk,
9740
- text: chunk.text.slice(linkStart - start, linkEnd - start),
9741
- link: { url: range.url }
9742
- });
9489
+ const linked = linkStart === start && linkEnd === end ? chunk : { ...chunk, text: chunk.text.slice(linkStart - start, linkEnd - start) };
9490
+ linked.link = { url: range.url };
9491
+ if (range.bare && bareStyle) {
9492
+ if (bareStyle.fg)
9493
+ linked.fg = bareStyle.fg;
9494
+ if (bareStyle.bg)
9495
+ linked.bg = bareStyle.bg;
9496
+ linked.attributes = (linked.attributes ?? 0) | bareStyle.attributes;
9743
9497
  }
9498
+ linkedChunks.push(linked);
9744
9499
  position = linkEnd;
9745
9500
  if (position === end)
9746
9501
  break;
@@ -9941,12 +9696,12 @@ class OptimizedBuffer2 {
9941
9696
  return recorder.draw(options);
9942
9697
  this.lib.contextDrawBuffer(this.checkedTarget(), options);
9943
9698
  }
9944
- _drawSceneText(scene, node, x, y) {
9699
+ _drawSceneBody(scene, node, x, y) {
9945
9700
  this.guard();
9946
9701
  const recorder = this.recorder;
9947
9702
  if (recorder)
9948
9703
  return recorder.view("scene", node, x, y);
9949
- this.lib.contextDrawSceneText(this._getSceneDrawTarget(scene), node, x, y);
9704
+ this.lib.contextDrawSceneBody(this._getSceneDrawTarget(scene), node, x, y);
9950
9705
  }
9951
9706
  get buffers() {
9952
9707
  this.guard();
@@ -10533,26 +10288,16 @@ function isSizeType(value) {
10533
10288
 
10534
10289
  // src/Renderable.ts
10535
10290
  var BrandedRenderable = Symbol.for("@opentui/core/Renderable");
10536
- var nativeSceneMethodNames = [
10291
+ var hookNames = [
10537
10292
  "renderSelf",
10538
10293
  "onResize",
10539
10294
  "onLayoutResize",
10540
10295
  "onUpdate",
10541
10296
  "renderBefore",
10542
10297
  "renderAfter",
10543
- "onLifecyclePass",
10544
- "selectable"
10298
+ "onLifecyclePass"
10545
10299
  ];
10546
- var nativeSceneMethodDefaults = {
10547
- selectable: false,
10548
- onLifecyclePass: null,
10549
- renderBefore: undefined,
10550
- renderAfter: undefined
10551
- };
10552
- var nativeSceneHookUpdates = nativeConstants.OT_SCENE_HOOK_UPDATE | nativeConstants.OT_SCENE_HOOK_IDLE_UPDATE;
10553
- var nativeSceneHookListeners = nativeConstants.OT_SCENE_HOOK_RESIZE | nativeConstants.OT_SCENE_HOOK_LAYOUT_CHANGED;
10554
10300
  var nativeSceneHookBeforeAfter = nativeConstants.OT_SCENE_HOOK_RENDER_BEFORE | nativeConstants.OT_SCENE_HOOK_RENDER_AFTER;
10555
- var nativeSceneHookHostMethods = nativeConstants.OT_SCENE_HOOK_UPDATE | nativeSceneHookBeforeAfter | nativeConstants.OT_SCENE_HOOK_RENDER_SELF;
10556
10301
  function isRowFlexDirection(direction) {
10557
10302
  return direction === FlexDirection2.Row || direction === FlexDirection2.RowReverse;
10558
10303
  }
@@ -10620,6 +10365,15 @@ class Renderable2 extends BaseRenderable2 {
10620
10365
  kind: "custom",
10621
10366
  body: { native: this.prototype.renderSelf }
10622
10367
  };
10368
+ static baseHooks = {
10369
+ renderSelf: this.prototype.renderSelf,
10370
+ onResize: this.prototype.onResize,
10371
+ onLayoutResize: this.prototype.onLayoutResize,
10372
+ onUpdate: this.prototype.onUpdate,
10373
+ renderBefore: undefined,
10374
+ renderAfter: undefined,
10375
+ onLifecyclePass: null
10376
+ };
10623
10377
  nativeIntegration;
10624
10378
  _isDestroyed = false;
10625
10379
  _cleanupInProgress = false;
@@ -10638,24 +10392,22 @@ class Renderable2 extends BaseRenderable2 {
10638
10392
  frameBuffer = null;
10639
10393
  _focusable = this.constructor.defaultFocusable;
10640
10394
  _focused = false;
10641
- _hasFocusedDescendant = false;
10642
10395
  keypressHandler = null;
10643
10396
  pasteHandler = null;
10644
10397
  _live = false;
10398
+ _animationFps;
10399
+ stopAnimationTick;
10400
+ animationDrawnFrame = -1;
10645
10401
  _liveCount = 0;
10646
10402
  _sizeChangeListener = undefined;
10647
- _nativeSceneHookFlags = 0;
10403
+ _hooks = Renderable2.baseHooks;
10648
10404
  _nativeSceneHookGeneration = 0n;
10649
10405
  _nativeSceneHooksRegistered = false;
10650
10406
  _nativeSceneResize = false;
10651
- _nativeSceneResizeCallbacks;
10652
- _nativeSceneHookLayout;
10407
+ _paintLayout;
10653
10408
  _observedLayout;
10654
10409
  _observedLayoutRevision = -1;
10655
- _computedLayout;
10656
- _computedLayoutRevision = -1;
10657
- _nativeSceneMethods;
10658
- _nativeSceneMethodsPending = false;
10410
+ _selectable = false;
10659
10411
  _mouseListener = null;
10660
10412
  _mouseListeners = {};
10661
10413
  _pasteListener = undefined;
@@ -10667,6 +10419,24 @@ class Renderable2 extends BaseRenderable2 {
10667
10419
  _flexShrink = 1;
10668
10420
  _childrenInLayoutOrder = [];
10669
10421
  parent = null;
10422
+ get onLifecyclePass() {
10423
+ return this._hooks.onLifecyclePass;
10424
+ }
10425
+ set onLifecyclePass(value) {
10426
+ this.setHook("onLifecyclePass", value);
10427
+ }
10428
+ get renderBefore() {
10429
+ return this._hooks.renderBefore;
10430
+ }
10431
+ set renderBefore(value) {
10432
+ this.setHook("renderBefore", value);
10433
+ }
10434
+ get renderAfter() {
10435
+ return this._hooks.renderAfter;
10436
+ }
10437
+ set renderAfter(value) {
10438
+ this.setHook("renderAfter", value);
10439
+ }
10670
10440
  constructor(ctx, options) {
10671
10441
  super(options);
10672
10442
  this._ctx = ctx;
@@ -10683,12 +10453,14 @@ class Renderable2 extends BaseRenderable2 {
10683
10453
  this._liveCount = this._live && this._visible ? 1 : 0;
10684
10454
  this._opacity = clampOpacity(options.opacity);
10685
10455
  ctx.nativeScene.createNode(this, options);
10686
- if (options.renderBefore !== undefined)
10687
- this.renderBefore = options.renderBefore;
10688
- if (options.renderAfter !== undefined)
10689
- this.renderAfter = options.renderAfter;
10690
- if (this.nativeSceneNeedsHookPublish())
10691
- this.setNativeSceneHooks(this._nativeSceneHookFlags);
10456
+ const hooks = {};
10457
+ for (const name of hookNames)
10458
+ hooks[name] = this[name];
10459
+ for (const name of ["renderBefore", "renderAfter"]) {
10460
+ if (options[name] !== undefined)
10461
+ hooks[name] = Renderable2.normalizeHook(name, options[name]);
10462
+ }
10463
+ this.publishHooks(hooks);
10692
10464
  this.setDisplay(this._visible ? 0 /* Flex */ : 1 /* None */);
10693
10465
  this.setupYogaProperties(options);
10694
10466
  if (this.nativeIntegration.measure)
@@ -10700,9 +10472,7 @@ class Renderable2 extends BaseRenderable2 {
10700
10472
  if (this.buffered) {
10701
10473
  this.createFrameBuffer();
10702
10474
  }
10703
- if (!Object.hasOwn(new.target, "nativeIntegration") || this.nativeIntegration.construction !== "prototype") {
10704
- ctx.nativeScene.scheduleHookScan(this);
10705
- }
10475
+ this.animationFps = options.animationFps;
10706
10476
  } catch (error) {
10707
10477
  try {
10708
10478
  this.destroyLayoutBacking();
@@ -10715,6 +10485,7 @@ class Renderable2 extends BaseRenderable2 {
10715
10485
  try {
10716
10486
  this.destroyLayoutBacking((run) => {
10717
10487
  this._isDestroyed = true;
10488
+ this.updateAnimationTick();
10718
10489
  Renderable2.renderablesByNumber.delete(this.num);
10719
10490
  if (cleanup)
10720
10491
  run(() => cleanup(run));
@@ -10803,6 +10574,7 @@ class Renderable2 extends BaseRenderable2 {
10803
10574
  this.propagateLiveCount(-1);
10804
10575
  }
10805
10576
  }
10577
+ this.updateAnimationTick();
10806
10578
  if (this._focused) {
10807
10579
  this.blur();
10808
10580
  }
@@ -10870,19 +10642,9 @@ class Renderable2 extends BaseRenderable2 {
10870
10642
  run(() => this.emit("focused" /* FOCUSED */));
10871
10643
  });
10872
10644
  }
10873
- propagateFocusChange(hasFocus) {
10874
- let parent = this.parent;
10875
- while (parent) {
10876
- if (!hasFocus) {
10877
- hasFocus = parent._childrenInLayoutOrder.some((child) => !child._isDestroyed && (child._focused || child._hasFocusedDescendant));
10878
- }
10879
- if (parent._hasFocusedDescendant !== hasFocus) {
10880
- parent._hasFocusedDescendant = hasFocus;
10881
- parent.markDirty();
10882
- }
10883
- hasFocus ||= parent._focused;
10884
- parent = parent.parent;
10885
- }
10645
+ propagateFocusChange(_hasFocus) {
10646
+ for (let parent = this.parent;parent; parent = parent.parent)
10647
+ parent.markDirty();
10886
10648
  this.requestRender();
10887
10649
  }
10888
10650
  blur() {
@@ -10910,7 +10672,13 @@ class Renderable2 extends BaseRenderable2 {
10910
10672
  return this._focused;
10911
10673
  }
10912
10674
  get hasFocusedDescendant() {
10913
- return this._hasFocusedDescendant;
10675
+ const focused = this._ctx.currentFocusedRenderable;
10676
+ if (!focused?._focused || focused._isDestroyed)
10677
+ return false;
10678
+ for (let parent = focused.parent;parent; parent = parent.parent)
10679
+ if (parent === this)
10680
+ return true;
10681
+ return false;
10914
10682
  }
10915
10683
  get live() {
10916
10684
  return this._live;
@@ -10933,6 +10701,37 @@ class Renderable2 extends BaseRenderable2 {
10933
10701
  this.parent?.propagateLiveCount(delta);
10934
10702
  }
10935
10703
  onLiveCountChanged(previous) {}
10704
+ get animationFps() {
10705
+ return this._animationFps;
10706
+ }
10707
+ set animationFps(value) {
10708
+ value ??= undefined;
10709
+ if (value !== undefined && !(value > 0 && value < Infinity)) {
10710
+ throw new RangeError(`animationFps must be positive and finite, got ${value}`);
10711
+ }
10712
+ if (this._animationFps === value)
10713
+ return;
10714
+ const toggled = this._animationFps === undefined !== (value === undefined);
10715
+ this._animationFps = value;
10716
+ if (toggled)
10717
+ this.refreshNativeSceneHooks();
10718
+ this.updateAnimationTick();
10719
+ }
10720
+ updateAnimationTick() {
10721
+ this.stopAnimationTick?.();
10722
+ this.stopAnimationTick = undefined;
10723
+ if (this._animationFps === undefined || !this._visible || this._isDestroyed)
10724
+ return;
10725
+ this.stopAnimationTick = this._ctx.onAnimationTick(this._animationFps, (deltaTime, ticks, time) => {
10726
+ if (this.animationDrawnFrame < this._ctx.frameId - 1) {
10727
+ this.stopAnimationTick?.();
10728
+ this.stopAnimationTick = undefined;
10729
+ return;
10730
+ }
10731
+ this.onAnimationTick(deltaTime, ticks, time);
10732
+ });
10733
+ }
10734
+ onAnimationTick(deltaTime, ticks, time) {}
10936
10735
  findDescendantById(id) {
10937
10736
  for (const child of this._childrenInLayoutOrder) {
10938
10737
  if (child.id === id)
@@ -10981,22 +10780,22 @@ class Renderable2 extends BaseRenderable2 {
10981
10780
  return this.isFreed() ? this._destroyedLayout?.screenY ?? 0 : this.getNativeSceneLayout().screenY;
10982
10781
  }
10983
10782
  get _screenX() {
10984
- return this.getNativeScenePaintLayout()?.screenX ?? this.screenX;
10783
+ return this._paintLayout?.screenX ?? this.screenX;
10985
10784
  }
10986
10785
  get _screenY() {
10987
- return this.getNativeScenePaintLayout()?.screenY ?? this.screenY;
10786
+ return this._paintLayout?.screenY ?? this.screenY;
10988
10787
  }
10989
- getNativeScenePaintLayout() {
10990
- const cached = this._nativeSceneHookLayout;
10991
- if (!cached)
10992
- return;
10993
- const scene = this._ctx.nativeScene;
10994
- const revision = scene.currentGeometryRevision;
10995
- if (!this._isDestroyed && cached.paintRevision !== revision) {
10996
- cached.paintLayout = scene.getLayout(this, "paint");
10997
- cached.paintRevision = revision;
10998
- }
10999
- return cached.paintLayout;
10788
+ _paintOrigin(buffer) {
10789
+ return buffer === this.frameBuffer ? [0, 0] : [Math.trunc(this._screenX), Math.trunc(this._screenY)];
10790
+ }
10791
+ _drawNativeBody(buffer) {
10792
+ this._ctx.nativeScene.drawBody(this, buffer, ...this._paintOrigin(buffer));
10793
+ }
10794
+ get _paintWidth() {
10795
+ return this._paintLayout?.width ?? this.width;
10796
+ }
10797
+ get _paintHeight() {
10798
+ return this._paintLayout?.height ?? this.height;
11000
10799
  }
11001
10800
  get x() {
11002
10801
  if (!this.isFreed())
@@ -11079,22 +10878,16 @@ class Renderable2 extends BaseRenderable2 {
11079
10878
  return typeof value === "number" ? value : 0;
11080
10879
  }
11081
10880
  getNativeSceneLayout() {
11082
- const scene = this._ctx.nativeScene;
11083
- const cached = this._nativeSceneHookLayout;
11084
- const revision = scene.currentGeometryRevision;
11085
- if (cached?.layout && cached.revision === revision)
11086
- return cached.layout;
11087
- const layoutRevision = scene.observedLayoutRevision;
11088
- if (layoutRevision !== undefined && this._observedLayoutRevision === layoutRevision)
10881
+ const revision = this._ctx.nativeScene.observedLayoutRevision;
10882
+ if (revision !== undefined && this._observedLayoutRevision === revision)
11089
10883
  return this._observedLayout;
11090
- const layout = scene.getLayout(this);
11091
- if (cached) {
11092
- cached.revision = revision;
11093
- cached.layout = layout;
11094
- }
11095
- if (layoutRevision !== undefined) {
10884
+ return this.observeLayout(this._ctx.nativeScene.getLayout(this));
10885
+ }
10886
+ observeLayout(layout) {
10887
+ const revision = this._ctx.nativeScene.observedLayoutRevision;
10888
+ if (layout && revision !== undefined) {
11096
10889
  this._observedLayout = layout;
11097
- this._observedLayoutRevision = layoutRevision;
10890
+ this._observedLayoutRevision = revision;
11098
10891
  }
11099
10892
  return layout;
11100
10893
  }
@@ -11130,7 +10923,7 @@ class Renderable2 extends BaseRenderable2 {
11130
10923
  }
11131
10924
  }
11132
10925
  getChildrenSortedByPrimaryAxis() {
11133
- const axis = isRowFlexDirection(this.getFlexDirection()) ? "screenX" : "screenY";
10926
+ const axis = this.primaryAxis === "row" ? "screenX" : "screenY";
11134
10927
  if (this._childrenInLayoutOrder.length < 2)
11135
10928
  return [...this._childrenInLayoutOrder];
11136
10929
  const children = this._childrenInLayoutOrder.map((child) => ({ child, coordinate: child[axis] }));
@@ -11305,17 +11098,7 @@ class Renderable2 extends BaseRenderable2 {
11305
11098
  return this.yogaGetValue(YogaValueKind.Gap, gutter);
11306
11099
  }
11307
11100
  getComputedLayout() {
11308
- const scene = this._ctx.nativeScene;
11309
- const revision = scene.observedLayoutRevision;
11310
- let layout = this._computedLayout;
11311
- if (revision === undefined || this._computedLayoutRevision !== revision || layout === undefined || this._yogaFreed) {
11312
- layout = scene.getLayout(this, true);
11313
- if (revision !== undefined) {
11314
- this._computedLayout = layout;
11315
- this._computedLayoutRevision = revision;
11316
- }
11317
- }
11318
- const { left, top, right, bottom, width, height } = layout;
11101
+ const { left, top, right, bottom, width, height } = this._ctx.nativeScene.getLayout(this, true);
11319
11102
  return { left, top, right, bottom, width, height };
11320
11103
  }
11321
11104
  setMeasureFunc(measure) {
@@ -11608,7 +11391,7 @@ class Renderable2 extends BaseRenderable2 {
11608
11391
  onLayoutResize(width, height) {
11609
11392
  if (this._visible) {
11610
11393
  this.handleFrameBufferResize(width, height);
11611
- this.onResize(width, height);
11394
+ this._hooks.onResize.call(this, width, height);
11612
11395
  this.requestRender();
11613
11396
  }
11614
11397
  }
@@ -11645,8 +11428,6 @@ class Renderable2 extends BaseRenderable2 {
11645
11428
  if (this._ctx.nativeScene !== child._ctx.nativeScene) {
11646
11429
  throw new Error("Cannot move renderables between native scenes");
11647
11430
  }
11648
- if (!child.isDestroyed)
11649
- this._ctx.nativeScene.refreshPendingHooks(child);
11650
11431
  let previous = child.parent;
11651
11432
  if (previous && previous !== this && previous.remove !== Renderable2.prototype.remove) {
11652
11433
  previous.remove(child);
@@ -11663,21 +11444,7 @@ class Renderable2 extends BaseRenderable2 {
11663
11444
  const index = anchorIndex - (previous === target && previousIndex !== -1 && previousIndex < anchorIndex ? 1 : 0);
11664
11445
  let counts;
11665
11446
  let lifecycle;
11666
- let focus;
11667
- let focusPaths;
11668
11447
  if (previous !== target) {
11669
- if (child._focused || child._hasFocusedDescendant) {
11670
- focus = new Map;
11671
- focusPaths = [];
11672
- for (const start of [previous, target]) {
11673
- const path = [];
11674
- for (let parent = start;parent; parent = parent.parent) {
11675
- focus.set(parent, parent._hasFocusedDescendant);
11676
- path.push(parent);
11677
- }
11678
- focusPaths.push(path);
11679
- }
11680
- }
11681
11448
  if (child._liveCount > 0) {
11682
11449
  counts = new Map;
11683
11450
  for (const [start, delta] of [
@@ -11709,12 +11476,6 @@ class Renderable2 extends BaseRenderable2 {
11709
11476
  if (counts)
11710
11477
  for (const [parent, count] of counts)
11711
11478
  parent._liveCount = count.after;
11712
- if (focusPaths)
11713
- for (const path of focusPaths) {
11714
- for (const parent of path) {
11715
- parent._hasFocusedDescendant = parent._childrenInLayoutOrder.some((node) => node._focused || node._hasFocusedDescendant);
11716
- }
11717
- }
11718
11479
  if (lifecycle)
11719
11480
  for (const [passes, active] of lifecycle) {
11720
11481
  if (active)
@@ -11723,11 +11484,10 @@ class Renderable2 extends BaseRenderable2 {
11723
11484
  passes.delete(child);
11724
11485
  }
11725
11486
  this.runCleanup((run) => {
11726
- if (focus)
11727
- for (const [parent, focused] of focus) {
11728
- if (parent._hasFocusedDescendant !== focused)
11487
+ if (previous !== target && (child._focused || child.hasFocusedDescendant))
11488
+ for (const start of [previous, target])
11489
+ for (let parent = start;parent; parent = parent.parent)
11729
11490
  parent.markDirty();
11730
- }
11731
11491
  if (counts)
11732
11492
  for (const [parent, count] of counts)
11733
11493
  run(() => parent.onLiveCountChanged(count.before));
@@ -11835,7 +11595,7 @@ class Renderable2 extends BaseRenderable2 {
11835
11595
  this._ctx.nativeScene.moveNode(renderable, null, 0);
11836
11596
  this.removeLayoutChildAt(index);
11837
11597
  this.runCleanup((run) => {
11838
- if (renderable._focused || renderable._hasFocusedDescendant) {
11598
+ if (renderable._focused || renderable.hasFocusedDescendant) {
11839
11599
  run(() => renderable.propagateFocusChange(false));
11840
11600
  }
11841
11601
  if (renderable._liveCount > 0)
@@ -11876,252 +11636,130 @@ class Renderable2 extends BaseRenderable2 {
11876
11636
  return;
11877
11637
  this._ctx.nativeScene.setPaint(this, paint);
11878
11638
  }
11879
- static nativeSceneMethods = nativeSceneMethodNames.map((name) => {
11880
- const normalize = (value) => {
11881
- if (name === "selectable")
11882
- return value;
11883
- if (name === "onLifecyclePass")
11884
- value ??= null;
11885
- else if (name === "renderBefore" || name === "renderAfter")
11886
- value ??= undefined;
11887
- else if (name === "onUpdate")
11888
- value ??= nativeSceneMethodDefaults.onUpdate;
11889
- if (typeof value !== "function" && !((name === "renderBefore" || name === "renderAfter" || name === "onLifecyclePass") && value == null))
11890
- throw new TypeError(`Invalid ${name} hook`);
11891
- return value;
11892
- };
11893
- return {
11894
- name,
11895
- normalize,
11896
- descriptor: {
11897
- configurable: true,
11898
- get() {
11899
- const methods = this._nativeSceneMethods;
11900
- if (methods && name in methods)
11901
- return methods[name];
11902
- return nativeSceneMethodDefaults[name];
11903
- },
11904
- set(value) {
11905
- if (name === "selectable") {
11906
- if (this.isFreed())
11907
- return;
11908
- this.assertMutable();
11909
- this.ensureNativeSceneMethods()[name] = value;
11910
- return;
11911
- }
11912
- value = normalize(value);
11913
- if (value === this[name])
11914
- return;
11915
- this.setNativeSceneHooks(this._nativeSceneHookFlags, { [name]: value });
11916
- this.ensureNativeSceneMethods()[name] = value;
11917
- if (name === "onLifecyclePass") {
11918
- if (!value)
11919
- this._ctx.unregisterLifecyclePass(this);
11920
- else if (this.parent)
11921
- this._ctx.registerLifecyclePass(this);
11922
- else
11923
- this._ctx.nativeScene.lifecyclePasses.refresh(this);
11924
- }
11925
- }
11926
- }
11927
- };
11928
- });
11929
11639
  static {
11930
- const prototype = this.prototype;
11931
- nativeSceneMethodDefaults.renderSelf = prototype.renderSelf;
11932
- nativeSceneMethodDefaults.onResize = prototype.onResize;
11933
- nativeSceneMethodDefaults.onLayoutResize = prototype.onLayoutResize;
11934
- nativeSceneMethodDefaults.onUpdate = prototype.onUpdate;
11935
- for (const method of this.nativeSceneMethods) {
11936
- if (method.name === "renderSelf" || method.name === "onResize" || method.name === "onLayoutResize" || method.name === "onUpdate") {
11937
- this.installNativeSceneMethod(prototype, method, nativeSceneMethodDefaults[method.name]);
11938
- } else {
11939
- Object.defineProperty(prototype, method.name, method.descriptor);
11940
- }
11941
- }
11942
- }
11943
- static defineNativeIntegration(integration) {
11944
- for (const method of Renderable2.nativeSceneMethods) {
11945
- let prototype = this.prototype;
11946
- while (prototype) {
11947
- const descriptor = Object.getOwnPropertyDescriptor(prototype, method.name);
11948
- if (descriptor) {
11949
- if ("value" in descriptor)
11950
- this.installNativeSceneMethod(this.prototype, method, descriptor.value);
11951
- break;
11952
- }
11953
- prototype = Object.getPrototypeOf(prototype);
11954
- }
11955
- }
11956
- return integration;
11957
- }
11958
- static installNativeSceneMethod(prototype, method, handler) {
11959
- const instance = {
11960
- ...method.descriptor,
11961
- get() {
11962
- const methods = this._nativeSceneMethods;
11963
- return methods && method.name in methods ? methods[method.name] : handler;
11964
- }
11965
- };
11966
- Object.defineProperty(prototype, method.name, {
11640
+ Object.defineProperty(this.prototype, "selectable", {
11967
11641
  configurable: true,
11968
11642
  get() {
11969
- return handler;
11643
+ return this._selectable;
11970
11644
  },
11971
11645
  set(value) {
11972
- Object.defineProperty(this, method.name, instance);
11973
- method.descriptor.set.call(this, value);
11646
+ if (this.isFreed())
11647
+ return;
11648
+ this.assertMutable();
11649
+ this._selectable = value;
11974
11650
  }
11975
11651
  });
11976
11652
  }
11653
+ static normalizeHook(name, value) {
11654
+ if (value == null && name !== "renderSelf" && name !== "onResize" && name !== "onLayoutResize") {
11655
+ return name === "onUpdate" ? Renderable2.baseHooks.onUpdate : name === "onLifecyclePass" ? null : undefined;
11656
+ }
11657
+ if (typeof value !== "function")
11658
+ throw new TypeError(`Invalid ${name} hook`);
11659
+ return value;
11660
+ }
11661
+ setHook(name, value) {
11662
+ value = Renderable2.normalizeHook(name, value);
11663
+ if (value === this._hooks[name])
11664
+ return;
11665
+ const hooks = { ...this._hooks, [name]: value };
11666
+ if (name !== "onLifecyclePass")
11667
+ return this.publishHooks(hooks);
11668
+ this._hooks = hooks;
11669
+ this.syncLifecyclePass();
11670
+ }
11671
+ syncLifecyclePass() {
11672
+ if (!this.onLifecyclePass)
11673
+ this._ctx.unregisterLifecyclePass(this);
11674
+ else if (this.parent)
11675
+ this._ctx.registerLifecyclePass(this);
11676
+ else
11677
+ this._ctx.nativeScene.lifecyclePasses.refresh(this);
11678
+ }
11977
11679
  refreshHooks() {
11978
11680
  if (this._isDestroyed)
11979
11681
  return;
11980
11682
  this.assertMutable();
11981
- try {
11982
- this._scanNativeSceneHooks();
11983
- } catch (error) {
11984
- this._ctx.nativeScene.scheduleHookScan(this);
11985
- throw error;
11683
+ const hooks = {};
11684
+ for (const name of hookNames)
11685
+ hooks[name] = Renderable2.normalizeHook(name, this[name]);
11686
+ this.publishHooks(hooks);
11687
+ for (const name of ["renderBefore", "renderAfter", "onLifecyclePass"]) {
11688
+ if (!Object.hasOwn(this, name))
11689
+ continue;
11690
+ delete this[name];
11691
+ if (this[name] !== hooks[name])
11692
+ Reflect.set(this, name, hooks[name]);
11986
11693
  }
11694
+ this.syncLifecyclePass();
11695
+ this._refreshNativeSceneSurface();
11987
11696
  this.requestRender();
11988
11697
  }
11989
- _scanNativeSceneHooks() {
11990
- if (!this._isDestroyed)
11991
- this.refreshNativeSceneMethods();
11992
- }
11993
- ensureNativeSceneMethods() {
11994
- return this._nativeSceneMethods ??= {};
11995
- }
11996
- nativeSceneNeedsHookPublish() {
11997
- if (this.buffered)
11998
- return true;
11999
- if (!this.usesNativeDrawing(this.renderSelf))
12000
- return true;
12001
- if (this.hostUpdateFlags(this.onUpdate) !== 0)
12002
- return true;
12003
- const onResize = this.onResize;
12004
- const onLayoutResize = this.onLayoutResize;
12005
- if (onLayoutResize !== nativeSceneMethodDefaults.onLayoutResize)
12006
- return true;
12007
- if (!this._nativeSceneHooksRegistered && this.nativeIntegration.beforeAfter !== false && (this.renderBefore || this.renderAfter))
12008
- return true;
12009
- return this.needsHostResize(onResize);
12010
- }
12011
11698
  usesNativeDrawing(renderSelf) {
12012
11699
  const body = this.nativeIntegration.body;
12013
11700
  return typeof body === "object" && "native" in body && (!this.buffered || body.buffered === true) && renderSelf === body.native;
12014
11701
  }
12015
11702
  needsHostResize(onResize) {
12016
11703
  const resize = this.nativeIntegration.lifecycle?.resize;
12017
- return onResize !== nativeSceneMethodDefaults.onResize && onResize !== resize?.native;
11704
+ return onResize !== Renderable2.baseHooks.onResize && onResize !== resize?.native;
12018
11705
  }
12019
11706
  hostUpdateFlags(onUpdate) {
11707
+ if (this._animationFps !== undefined)
11708
+ return NativeSceneHook2.Update;
12020
11709
  const update = this.nativeIntegration.lifecycle?.update;
12021
11710
  if (update && onUpdate === update.idle) {
12022
11711
  return update.active(this) ? NativeSceneHook2.Update : NativeSceneHook2.IdleUpdate;
12023
11712
  }
12024
- return onUpdate === nativeSceneMethodDefaults.onUpdate ? 0 : NativeSceneHook2.Update;
12025
- }
12026
- refreshNativeSceneMethods() {
12027
- this._refreshNativeSceneSurface();
12028
- const methods = Renderable2.nativeSceneMethods;
12029
- for (let index = 0;index < methods.length; index++) {
12030
- const method = methods[index];
12031
- const name = method.name;
12032
- const own = Object.getOwnPropertyDescriptor(this, name);
12033
- if (own?.set === method.descriptor.set)
12034
- continue;
12035
- const handler = method.normalize(this[name]);
12036
- if (!own && handler === nativeSceneMethodDefaults[name])
12037
- continue;
12038
- this.ensureNativeSceneMethods()[name] = handler;
12039
- Object.defineProperty(this, name, method.descriptor);
12040
- if (own)
12041
- this._nativeSceneMethodsPending = true;
12042
- }
12043
- if (this._nativeSceneMethodsPending) {
12044
- this.setNativeSceneHooks(this._nativeSceneHookFlags, {
12045
- onResize: this.onResize,
12046
- onLayoutResize: this.onLayoutResize
12047
- });
12048
- if (!this.onLifecyclePass)
12049
- this._ctx.unregisterLifecyclePass(this);
12050
- else if (this.parent)
12051
- this._ctx.registerLifecyclePass(this);
12052
- else
12053
- this._ctx.nativeScene.lifecyclePasses.refresh(this);
12054
- this._nativeSceneMethodsPending = false;
12055
- }
11713
+ return onUpdate === Renderable2.baseHooks.onUpdate ? 0 : NativeSceneHook2.Update;
12056
11714
  }
12057
11715
  refreshNativeSceneHooks() {
12058
- this.setNativeSceneHooks(this._nativeSceneHookFlags);
11716
+ this.publishHooks(this._hooks);
12059
11717
  }
12060
11718
  _refreshNativeSceneSurface() {}
12061
- setNativeSceneHooks(flags, overrides = {}, lineInfo) {
12062
- if (this.isFreed())
12063
- return;
12064
- const scene = this._ctx.nativeScene;
12065
- const previousFlags = this._nativeSceneHookFlags;
12066
- const previousGeneration = this._nativeSceneHookGeneration;
12067
- const method = (name) => (name in overrides) ? overrides[name] : this[name];
12068
- const onUpdate = method("onUpdate");
12069
- flags = flags & ~nativeSceneHookHostMethods | (method("renderBefore") ? NativeSceneHook2.RenderBefore : 0) | (method("renderAfter") ? NativeSceneHook2.RenderAfter : 0);
12070
- const renderSelf = method("renderSelf");
12071
- if (!this.usesNativeDrawing(renderSelf))
12072
- flags |= NativeSceneHook2.RenderSelf;
12073
- const overridden = ("onUpdate" in overrides ? nativeSceneHookUpdates : 0) | ("onResize" in overrides || "onLayoutResize" in overrides ? NativeSceneHook2.Resize : 0) | ("renderBefore" in overrides ? NativeSceneHook2.RenderBefore : 0) | ("renderAfter" in overrides ? NativeSceneHook2.RenderAfter : 0) | ("renderSelf" in overrides ? NativeSceneHook2.RenderSelf : 0);
12074
- const changed = (previousFlags ^ this._nativeSceneHookFlags) & ~overridden;
12075
- flags = flags & ~changed | this._nativeSceneHookFlags & changed;
12076
- const resizeCallbacks = {
12077
- onResize: "onResize" in overrides ? overrides.onResize : this._nativeSceneResizeCallbacks?.onResize ?? this.onResize,
12078
- onLayoutResize: "onLayoutResize" in overrides ? overrides.onLayoutResize : this._nativeSceneResizeCallbacks?.onLayoutResize ?? this.onLayoutResize
12079
- };
12080
- const resize = this.buffered || resizeCallbacks.onLayoutResize !== Renderable2.prototype.onLayoutResize || this.needsHostResize(resizeCallbacks.onResize);
12081
- if (this._nativeSceneResize !== resize)
12082
- flags = flags & ~NativeSceneHook2.Resize | (this._sizeChangeListener || this.listenerCount("resize") ? NativeSceneHook2.Resize : 0);
12083
- if (resize)
12084
- flags |= NativeSceneHook2.Resize;
12085
- lineInfo ??= !!this.nativeIntegration.lineInfo && this.listenerCount("line-info-change") > 0;
12086
- const update = "onUpdate" in overrides || previousGeneration === this._nativeSceneHookGeneration ? this.hostUpdateFlags(onUpdate) : this._nativeSceneHookFlags & nativeSceneHookUpdates;
12087
- flags = flags & ~nativeSceneHookUpdates | update;
12088
- const generation = this._nativeSceneHookGeneration + 1n;
12089
- if (flags !== 0 || lineInfo || this._nativeSceneHooksRegistered) {
12090
- let nativeFlags = flags;
12091
- if (this.nativeIntegration.beforeAfter === false) {
12092
- nativeFlags &= ~nativeSceneHookBeforeAfter;
12093
- }
12094
- const nativeResize = this.nativeIntegration.lifecycle?.resize;
12095
- if (!resize && nativeResize) {
12096
- nativeFlags = nativeFlags & ~NativeSceneHook2.Resize | (lineInfo && this.nativeIntegration.lineInfo ? NativeSceneHook2.Resize : 0);
12097
- }
12098
- if (nativeFlags & NativeSceneHook2.RenderSelf)
12099
- nativeFlags |= NativeSceneHook2.RenderAfter;
12100
- scene.setHooks(this, nativeFlags, generation, this.styledDimension("width"), this.styledDimension("height"));
12101
- this._nativeSceneHooksRegistered = true;
12102
- }
12103
- this._nativeSceneResizeCallbacks = resize ? resizeCallbacks : undefined;
12104
- this._nativeSceneResize = resize;
12105
- this._nativeSceneHookFlags = flags;
12106
- this._nativeSceneHookGeneration = generation;
11719
+ publishHooks(hooks, pending = {}) {
11720
+ if (!this.isFreed()) {
11721
+ const integration = this.nativeIntegration;
11722
+ const resize = this.buffered || hooks.onLayoutResize !== Renderable2.baseHooks.onLayoutResize || this.needsHostResize(hooks.onResize);
11723
+ const sizeChange = "sizeChange" in pending ? pending.sizeChange : this._sizeChangeListener;
11724
+ const lineInfo = pending.lineInfo ?? (!!integration.lineInfo && this.listenerCount("line-info-change") > 0);
11725
+ const flags = (hooks.renderBefore ? NativeSceneHook2.RenderBefore : 0) | (hooks.renderAfter ? NativeSceneHook2.RenderAfter : 0) | (this.usesNativeDrawing(hooks.renderSelf) ? 0 : NativeSceneHook2.RenderSelf) | this.hostUpdateFlags(hooks.onUpdate) | (integration.lifecycle?.scroll?.active(this) ? NativeSceneHook2.Scroll : 0) | (resize || sizeChange || (pending.resize ?? this.listenerCount("resize")) > 0 ? NativeSceneHook2.Resize : 0) | ((pending.layout ?? this.listenerCount("layout-changed" /* LAYOUT_CHANGED */)) > 0 ? NativeSceneHook2.LayoutChanged : 0);
11726
+ const generation = this._nativeSceneHookGeneration + 1n;
11727
+ if (flags !== 0 || lineInfo || this._nativeSceneHooksRegistered) {
11728
+ let nativeFlags = flags;
11729
+ if (integration.beforeAfter === false)
11730
+ nativeFlags &= ~nativeSceneHookBeforeAfter;
11731
+ if (!resize && integration.lifecycle?.resize) {
11732
+ nativeFlags = nativeFlags & ~NativeSceneHook2.Resize | (lineInfo && integration.lineInfo ? NativeSceneHook2.Resize : 0);
11733
+ }
11734
+ if (nativeFlags & NativeSceneHook2.RenderSelf)
11735
+ nativeFlags |= NativeSceneHook2.RenderAfter;
11736
+ const scene = this._ctx.nativeScene;
11737
+ scene.setHooks(this, nativeFlags, generation, this.styledDimension("width"), this.styledDimension("height"));
11738
+ this._nativeSceneHooksRegistered = true;
11739
+ }
11740
+ this._nativeSceneResize = resize;
11741
+ this._nativeSceneHookGeneration = generation;
11742
+ }
11743
+ this._hooks = hooks;
12107
11744
  }
12108
11745
  _runNativeSceneHook(request, deltaTime) {
12109
11746
  if (this._isDestroyed || request.hookGeneration !== this._nativeSceneHookGeneration)
12110
11747
  return;
12111
- const previousLayout = this._nativeSceneHookLayout;
12112
- const revision = this._ctx.nativeScene.currentGeometryRevision;
12113
- const currentGeometry = request.geometryRevision === revision;
12114
- this._nativeSceneHookLayout = { revision, layout: currentGeometry ? request.publicLayout : undefined };
11748
+ this.observeLayout(request.publicLayout);
11749
+ this._paintLayout = request.paintLayout;
12115
11750
  try {
12116
11751
  switch (request.kind) {
12117
11752
  case NativeSceneFrame2.Update:
12118
- this.onUpdate(deltaTime);
11753
+ if (this._animationFps !== undefined) {
11754
+ this.animationDrawnFrame = this._ctx.frameId;
11755
+ if (!this.stopAnimationTick)
11756
+ this.updateAnimationTick();
11757
+ }
11758
+ this._hooks.onUpdate.call(this, deltaTime);
12119
11759
  break;
12120
11760
  case NativeSceneFrame2.Resize:
12121
11761
  if (this._nativeSceneResize) {
12122
- this._nativeSceneHookLayout.paintLayout = currentGeometry && request.paintLayout || this._ctx.nativeScene.getLayout(this, "paint");
12123
- this._nativeSceneHookLayout.paintRevision = revision;
12124
- this.onLayoutResize(request.width, request.height);
11762
+ this._hooks.onLayoutResize.call(this, request.width, request.height);
12125
11763
  } else {
12126
11764
  const resize = this.nativeIntegration.lifecycle?.resize;
12127
11765
  if (!resize) {
@@ -12136,27 +11774,24 @@ class Renderable2 extends BaseRenderable2 {
12136
11774
  case NativeSceneFrame2.LayoutChanged:
12137
11775
  this.emit("layout-changed" /* LAYOUT_CHANGED */);
12138
11776
  break;
11777
+ case NativeSceneFrame2.Scroll:
11778
+ this.nativeIntegration.lifecycle?.scroll?.notify(this);
11779
+ break;
12139
11780
  }
12140
11781
  } finally {
12141
- this._nativeSceneHookLayout = previousLayout;
11782
+ this._paintLayout = undefined;
12142
11783
  }
12143
11784
  }
12144
- _recordNativeScenePaint(slot, index, deltaTime, frame, recorder, geometryRevision) {
11785
+ _recordNativeScenePaint(slot, index, deltaTime, frame, recorder, publicLayout) {
12145
11786
  if (this._isDestroyed)
12146
11787
  return;
12147
- const previousLayout = this._nativeSceneHookLayout;
12148
- const revision = this._ctx.nativeScene.currentGeometryRevision;
12149
- this._nativeSceneHookLayout = {
12150
- revision,
12151
- layout: geometryRevision === revision ? slot.publicLayout : undefined,
12152
- paintLayout: slot.paintLayout,
12153
- paintRevision: revision
12154
- };
11788
+ this.observeLayout(publicLayout);
11789
+ this._paintLayout = slot.paintLayout;
12155
11790
  const buffer = this.nativeIntegration.paintBuffer !== "destination" && this.nativeIntegration.bufferComposition !== "native" && this.buffered && this.frameBuffer ? this.frameBuffer : frame;
12156
11791
  try {
12157
11792
  if (slot.hooks & NativeSceneHook2.RenderBefore) {
12158
11793
  recorder.slot(index, NativeScenePaintPhase2.Before, slot.opacity);
12159
- this.renderBefore?.call(this, buffer, deltaTime);
11794
+ this._hooks.renderBefore?.call(this, buffer, deltaTime);
12160
11795
  if (this._isDestroyed)
12161
11796
  return;
12162
11797
  }
@@ -12171,18 +11806,18 @@ class Renderable2 extends BaseRenderable2 {
12171
11806
  if (slot.hooks & NativeSceneHook2.RenderAfter) {
12172
11807
  recorder.slot(index, NativeScenePaintPhase2.After, slot.opacity);
12173
11808
  if (this.nativeIntegration.beforeAfter !== false) {
12174
- this.renderAfter?.call(this, buffer, deltaTime);
11809
+ this._hooks.renderAfter?.call(this, buffer, deltaTime);
12175
11810
  this.markClean();
12176
11811
  }
12177
11812
  if (!this._isDestroyed && this.nativeIntegration.bufferComposition !== "native" && this.buffered && this.frameBuffer)
12178
11813
  frame.drawFrameBuffer(Math.trunc(this._screenX), Math.trunc(this._screenY), this.frameBuffer);
12179
11814
  }
12180
11815
  } finally {
12181
- this._nativeSceneHookLayout = previousLayout;
11816
+ this._paintLayout = undefined;
12182
11817
  }
12183
11818
  }
12184
11819
  _invokeNativePaint(buffer, deltaTime) {
12185
- this.renderSelf(buffer, deltaTime);
11820
+ this._hooks.renderSelf.call(this, buffer, deltaTime);
12186
11821
  }
12187
11822
  get isDestroyed() {
12188
11823
  return this._isDestroyed;
@@ -12194,18 +11829,12 @@ class Renderable2 extends BaseRenderable2 {
12194
11829
  this.assertMutable();
12195
11830
  this.destroyLayoutBacking((run) => {
12196
11831
  run(() => this.destroyOwnedResources());
11832
+ const heldFocus = this._focused || this.hasFocusedDescendant;
12197
11833
  this._isDestroyed = true;
11834
+ this.updateAnimationTick();
12198
11835
  run(() => this.emit("destroyed" /* DESTROYED */));
12199
- if (this._focused || this._hasFocusedDescendant) {
12200
- run(() => {
12201
- const current = this._ctx.currentFocusedRenderable;
12202
- let focused = current;
12203
- while (focused && focused !== this)
12204
- focused = focused.parent;
12205
- if (!current || focused === this)
12206
- this.propagateFocusChange(false);
12207
- });
12208
- }
11836
+ if (heldFocus)
11837
+ run(() => this.propagateFocusChange(false));
12209
11838
  if (this.parent) {
12210
11839
  const parent = this.parent;
12211
11840
  run(() => parent.remove(this));
@@ -12416,14 +12045,12 @@ class Renderable2 extends BaseRenderable2 {
12416
12045
  else
12417
12046
  layout += delta;
12418
12047
  }
12419
- this.setNativeSceneHooks(this._nativeSceneHookFlags & ~nativeSceneHookListeners | (resize > 0 || this._sizeChangeListener ? NativeSceneHook2.Resize : 0) | (layout > 0 ? NativeSceneHook2.LayoutChanged : 0), {}, lineInfo > 0);
12048
+ this.publishHooks(this._hooks, { resize, layout, lineInfo: lineInfo > 0 });
12420
12049
  this.runCleanup((run) => {
12421
12050
  run(change);
12422
12051
  run(() => {
12423
- if (!this._isDestroyed) {
12424
- const flags = this._nativeSceneHookFlags & ~nativeSceneHookListeners | (this.listenerCount("resize") > 0 || this._sizeChangeListener ? NativeSceneHook2.Resize : 0) | (this.listenerCount("layout-changed" /* LAYOUT_CHANGED */) > 0 ? NativeSceneHook2.LayoutChanged : 0);
12425
- this.setNativeSceneHooks(flags);
12426
- }
12052
+ if (!this._isDestroyed)
12053
+ this.publishHooks(this._hooks);
12427
12054
  });
12428
12055
  });
12429
12056
  return this;
@@ -12508,8 +12135,7 @@ class Renderable2 extends BaseRenderable2 {
12508
12135
  if (handler !== this._sizeChangeListener) {
12509
12136
  if (handler != null && typeof handler !== "function")
12510
12137
  throw new TypeError("Invalid size change hook");
12511
- const flags = this._nativeSceneHookFlags & ~NativeSceneHook2.Resize;
12512
- this.setNativeSceneHooks(flags | (handler || this.listenerCount("resize") > 0 ? NativeSceneHook2.Resize : 0));
12138
+ this.publishHooks(this._hooks, { sizeChange: handler });
12513
12139
  }
12514
12140
  this._sizeChangeListener = handler;
12515
12141
  }
@@ -12534,11 +12160,10 @@ class Renderable2 extends BaseRenderable2 {
12534
12160
  }
12535
12161
 
12536
12162
  class RootRenderable2 extends Renderable2 {
12537
- static nativeIntegration = this.defineNativeIntegration({
12163
+ static nativeIntegration = {
12538
12164
  ...Renderable2.nativeIntegration,
12539
- kind: "root",
12540
- construction: "prototype"
12541
- });
12165
+ kind: "root"
12166
+ };
12542
12167
  _currentRenderable;
12543
12168
  constructor(ctx) {
12544
12169
  super(ctx, {
@@ -12664,7 +12289,6 @@ function maybeMakeRenderable2(ctx, node) {
12664
12289
  function wrapWithDelegates2(instance, delegateMap) {
12665
12290
  if (!delegateMap || Object.keys(delegateMap).length === 0)
12666
12291
  return instance;
12667
- instance.refreshHooks();
12668
12292
  const getDescendant = (id) => {
12669
12293
  return instance.findDescendantById(id);
12670
12294
  };
@@ -13365,6 +12989,12 @@ class EditBuffer2 extends EventEmitter5 {
13365
12989
  getEOL() {
13366
12990
  return this.position(3 /* Eol */);
13367
12991
  }
12992
+ _getEOF() {
12993
+ return this.position(7 /* End */);
12994
+ }
12995
+ _getPrevCharBoundary() {
12996
+ return this.position(8 /* PrevChar */);
12997
+ }
13368
12998
  offsetToPosition(offset) {
13369
12999
  const result = this.position(4 /* Offset */, offset);
13370
13000
  return result && { row: result.row, col: result.col };
@@ -13919,6 +13549,7 @@ class Timeline2 {
13919
13549
  isPlaying = false;
13920
13550
  isComplete = false;
13921
13551
  duration;
13552
+ _frameRate;
13922
13553
  loop;
13923
13554
  synced = false;
13924
13555
  autoplay;
@@ -13927,11 +13558,20 @@ class Timeline2 {
13927
13558
  stateChangeListeners = [];
13928
13559
  constructor(options = {}) {
13929
13560
  this.duration = options.duration || 1000;
13561
+ this.frameRate = options.frameRate;
13930
13562
  this.loop = options.loop === true;
13931
13563
  this.autoplay = options.autoplay !== false;
13932
13564
  this.onComplete = options.onComplete;
13933
13565
  this.onPause = options.onPause;
13934
13566
  }
13567
+ get frameRate() {
13568
+ return this._frameRate;
13569
+ }
13570
+ set frameRate(value) {
13571
+ if (value !== undefined && !(value > 0))
13572
+ throw new RangeError(`frameRate must be above 0, got ${value}`);
13573
+ this._frameRate = value;
13574
+ }
13935
13575
  addStateChangeListener(listener) {
13936
13576
  this.stateChangeListeners.push(listener);
13937
13577
  }
@@ -14097,9 +13737,12 @@ class TimelineEngine {
14097
13737
  timelines = new Set;
14098
13738
  renderer = null;
14099
13739
  frameCallback = async (deltaTime) => {
14100
- this.update(deltaTime);
13740
+ if (this.tickFps === 0)
13741
+ this.update(deltaTime);
14101
13742
  };
14102
13743
  isLive = false;
13744
+ tickFps = 0;
13745
+ stopTicks;
14103
13746
  defaults = {
14104
13747
  frameRate: 60
14105
13748
  };
@@ -14132,20 +13775,35 @@ class TimelineEngine {
14132
13775
  this.renderer.dropLive();
14133
13776
  this.isLive = false;
14134
13777
  }
13778
+ this.setTickFps(0);
14135
13779
  }
14136
13780
  this.renderer = null;
14137
13781
  }
14138
13782
  updateLiveState() {
14139
13783
  if (!this.renderer)
14140
13784
  return;
14141
- const hasRunningTimelines = Array.from(this.timelines).some((timeline) => !timeline.synced && timeline.isPlaying && !timeline.isComplete);
14142
- if (hasRunningTimelines && !this.isLive) {
13785
+ let fps = 0;
13786
+ for (const timeline of this.timelines) {
13787
+ if (timeline.synced || !timeline.isPlaying || timeline.isComplete)
13788
+ continue;
13789
+ fps = Math.max(fps, timeline.frameRate ?? this.defaults.frameRate);
13790
+ }
13791
+ const live = fps > 0 && fps >= this.renderer.targetFps;
13792
+ if (live && !this.isLive) {
14143
13793
  this.renderer.requestLive();
14144
13794
  this.isLive = true;
14145
- } else if (!hasRunningTimelines && this.isLive) {
13795
+ } else if (!live && this.isLive) {
14146
13796
  this.renderer.dropLive();
14147
13797
  this.isLive = false;
14148
13798
  }
13799
+ this.setTickFps(live ? 0 : fps);
13800
+ }
13801
+ setTickFps(fps) {
13802
+ if (fps === this.tickFps)
13803
+ return;
13804
+ this.stopTicks?.();
13805
+ this.stopTicks = fps > 0 ? this.renderer?.onAnimationTick(fps, (deltaTime) => this.update(deltaTime)) : undefined;
13806
+ this.tickFps = fps;
14149
13807
  }
14150
13808
  onTimelineStateChange = (timeline) => {
14151
13809
  this.updateLiveState();
@@ -14225,11 +13883,10 @@ function borderMask(sides) {
14225
13883
  }
14226
13884
 
14227
13885
  class BoxRenderable2 extends Renderable2 {
14228
- static nativeIntegration = this.defineNativeIntegration({
13886
+ static nativeIntegration = {
14229
13887
  kind: "box",
14230
- body: { native: this.prototype.renderSelf },
14231
- construction: "prototype"
14232
- });
13888
+ body: { native: this.prototype.renderSelf }
13889
+ };
14233
13890
  _backgroundColor;
14234
13891
  _border;
14235
13892
  _borderStyle;
@@ -14442,32 +14099,9 @@ class BoxRenderable2 extends Renderable2 {
14442
14099
  });
14443
14100
  }
14444
14101
  renderSelf(buffer) {
14445
- const hasBorder = this.borderSides.top || this.borderSides.right || this.borderSides.bottom || this.borderSides.left;
14446
- const hasVisibleFill = this.shouldFill && this._backgroundColor.a > 0;
14447
- if (!hasBorder && !hasVisibleFill) {
14102
+ if (borderMask(this.borderSides) === 0 && !(this._shouldFill && this._backgroundColor.a > 0))
14448
14103
  return;
14449
- }
14450
- const hasFocusWithin = this._focusable && (this._focused || this._hasFocusedDescendant);
14451
- const currentBorderColor = hasFocusWithin ? this._focusedBorderColor : this._borderColor;
14452
- const screenX = Math.trunc(this._screenX);
14453
- const screenY = Math.trunc(this._screenY);
14454
- buffer.drawBox({
14455
- x: screenX,
14456
- y: screenY,
14457
- width: this.width,
14458
- height: this.height,
14459
- borderStyle: this._borderStyle,
14460
- customBorderChars: this._customBorderChars,
14461
- border: this._border,
14462
- borderColor: currentBorderColor,
14463
- backgroundColor: this._backgroundColor,
14464
- shouldFill: this.shouldFill,
14465
- title: this._title,
14466
- titleColor: this._titleColor ?? currentBorderColor,
14467
- titleAlignment: this._titleAlignment,
14468
- bottomTitle: this._bottomTitle,
14469
- bottomTitleAlignment: this._bottomTitleAlignment
14470
- });
14104
+ this._drawNativeBody(buffer);
14471
14105
  }
14472
14106
  get shouldFill() {
14473
14107
  return this._shouldFill;
@@ -14523,16 +14157,31 @@ class BoxRenderable2 extends Renderable2 {
14523
14157
  }
14524
14158
  }
14525
14159
 
14160
+ // src/lib/scroll-chain.ts
14161
+ var takers = new WeakMap;
14162
+ function wheelDirection(event) {
14163
+ const direction = event.scroll?.direction;
14164
+ if (!direction || !event.modifiers?.shift)
14165
+ return direction;
14166
+ return direction === "up" ? "left" : direction === "down" ? "right" : direction === "right" ? "down" : "up";
14167
+ }
14168
+ function scrollOnce(event, scroller, scroll) {
14169
+ for (let node = takers.get(event) ?? null;node; node = node.parent)
14170
+ if (node === scroller)
14171
+ return;
14172
+ if (scroll())
14173
+ takers.set(event, scroller);
14174
+ }
14175
+
14526
14176
  // src/renderables/TextBufferRenderable.ts
14527
14177
  class TextBufferRenderable2 extends Renderable2 {
14528
- static nativeIntegration = this.defineNativeIntegration({
14178
+ static nativeIntegration = {
14529
14179
  kind: "text",
14530
14180
  body: { native: this.prototype.renderSelf },
14531
14181
  lifecycle: { resize: { native: this.prototype.onResize } },
14532
14182
  beforeAfter: false,
14533
- paintBuffer: "destination",
14534
- construction: "prototype"
14535
- });
14183
+ paintBuffer: "destination"
14184
+ };
14536
14185
  _defaultFg;
14537
14186
  _defaultBg;
14538
14187
  _defaultAttributes;
@@ -14549,7 +14198,6 @@ class TextBufferRenderable2 extends Renderable2 {
14549
14198
  _firstLineOffset = 0;
14550
14199
  textBuffer;
14551
14200
  textBufferView;
14552
- _textBufferSyntaxStyle;
14553
14201
  nativeTextScene;
14554
14202
  _defaultOptions = {
14555
14203
  fg: RGBA2.fromValues(1, 1, 1, 1),
@@ -14569,7 +14217,6 @@ class TextBufferRenderable2 extends Renderable2 {
14569
14217
  this.nativeTextScene = sharedText ? undefined : ctx.nativeScene;
14570
14218
  let textBuffer;
14571
14219
  let textBufferView;
14572
- let syntaxStyle;
14573
14220
  try {
14574
14221
  this._defaultFg = RGBA2.clone(parseColor2(options.fg ?? this._defaultOptions.fg));
14575
14222
  this._defaultBg = RGBA2.clone(parseColor2(options.bg ?? this._defaultOptions.bg));
@@ -14593,9 +14240,6 @@ class TextBufferRenderable2 extends Renderable2 {
14593
14240
  textBufferView = TextBufferView2.create(textBuffer);
14594
14241
  this.textBufferView = textBufferView;
14595
14242
  this._firstLineOffset = ctx.claimFirstLineOffset?.(this) ?? 0;
14596
- syntaxStyle = SyntaxStyle2.create(ctx.nativeScene);
14597
- this._textBufferSyntaxStyle = syntaxStyle;
14598
- textBuffer.setSyntaxStyle(syntaxStyle);
14599
14243
  this.textBufferView.setWrapMode(this._wrapMode);
14600
14244
  this.textBufferView.setTextAlign(this._textAlign);
14601
14245
  this.textBufferView.setFirstLineOffset(this._firstLineOffset);
@@ -14616,8 +14260,6 @@ class TextBufferRenderable2 extends Renderable2 {
14616
14260
  this.updateTextInfo();
14617
14261
  } catch (error) {
14618
14262
  this.abortConstruction(error, (run) => {
14619
- run(() => textBuffer?.setSyntaxStyle(null));
14620
- run(() => syntaxStyle?.destroy());
14621
14263
  run(() => textBufferView?.destroy());
14622
14264
  run(() => textBuffer?.destroy());
14623
14265
  });
@@ -14625,13 +14267,18 @@ class TextBufferRenderable2 extends Renderable2 {
14625
14267
  }
14626
14268
  onMouseEvent(event) {
14627
14269
  if (event.type === "scroll") {
14628
- this.handleScroll(event);
14270
+ scrollOnce(event, this, () => {
14271
+ const [x, y] = [this.scrollX, this.scrollY];
14272
+ this.handleScroll(event);
14273
+ return this.scrollX !== x || this.scrollY !== y;
14274
+ });
14629
14275
  }
14630
14276
  }
14631
14277
  handleScroll(event) {
14632
14278
  if (!event.scroll)
14633
14279
  return;
14634
- const { direction, delta } = event.scroll;
14280
+ const { delta } = event.scroll;
14281
+ const direction = wheelDirection(event);
14635
14282
  if (direction === "up") {
14636
14283
  this.scrollY -= delta;
14637
14284
  } else if (direction === "down") {
@@ -14972,7 +14619,7 @@ class TextBufferRenderable2 extends Renderable2 {
14972
14619
  if (this.isDestroyed)
14973
14620
  throw new Error("Cannot draw destroyed text");
14974
14621
  if (this.nativeTextScene) {
14975
- this.nativeTextScene.drawText(this, buffer, Math.trunc(x), Math.trunc(y));
14622
+ this.nativeTextScene.drawBody(this, buffer, Math.trunc(x), Math.trunc(y));
14976
14623
  return;
14977
14624
  }
14978
14625
  buffer.drawTextBuffer(this.textBufferView, Math.trunc(x), Math.trunc(y));
@@ -14981,8 +14628,6 @@ class TextBufferRenderable2 extends Renderable2 {
14981
14628
  if (this.nativeTextScene)
14982
14629
  return;
14983
14630
  this.runCleanup((run) => {
14984
- run(() => this.textBuffer.setSyntaxStyle(null));
14985
- run(() => this._textBufferSyntaxStyle.destroy());
14986
14631
  run(() => this.textBufferView.destroy());
14987
14632
  run(() => this.textBuffer.destroy());
14988
14633
  });
@@ -15010,7 +14655,7 @@ class TextBufferRenderable2 extends Renderable2 {
15010
14655
 
15011
14656
  // src/renderables/Code.ts
15012
14657
  class CodeRenderable2 extends TextBufferRenderable2 {
15013
- static nativeIntegration = this.defineNativeIntegration({
14658
+ static nativeIntegration = {
15014
14659
  ...TextBufferRenderable2.nativeIntegration,
15015
14660
  kind: "text_view",
15016
14661
  body: { native: this.prototype.renderSelf },
@@ -15021,7 +14666,7 @@ class CodeRenderable2 extends TextBufferRenderable2 {
15021
14666
  active: (renderable) => renderable._highlightsDirty
15022
14667
  }
15023
14668
  }
15024
- });
14669
+ };
15025
14670
  _content;
15026
14671
  _filetype;
15027
14672
  _syntaxStyle;
@@ -16189,12 +15834,11 @@ function pixelResolution(ctx) {
16189
15834
  }
16190
15835
 
16191
15836
  class ImageRenderable2 extends Renderable2 {
16192
- static nativeIntegration = this.defineNativeIntegration({
15837
+ static nativeIntegration = {
16193
15838
  kind: "image",
16194
15839
  body: { native: this.prototype.renderSelf, buffered: true },
16195
- bufferComposition: "native",
16196
- construction: "prototype"
16197
- });
15840
+ bufferComposition: "native"
15841
+ };
16198
15842
  _source;
16199
15843
  _image = null;
16200
15844
  _pendingImage = null;
@@ -16335,15 +15979,17 @@ class ImageRenderable2 extends Renderable2 {
16335
15979
  }
16336
15980
  }
16337
15981
  renderSelf(buffer) {
16338
- if (!this._image || this.width <= 0 || this.height <= 0)
15982
+ const width = this._paintWidth;
15983
+ const height = this._paintHeight;
15984
+ if (!this._image || width <= 0 || height <= 0)
16339
15985
  return;
16340
- const fitted = this._fit === "cover" ? { width: this.width, height: this.height } : this.getFittedSize(this.width, this.height);
15986
+ const fitted = this._fit === "cover" ? { width, height } : this.getFittedSize(width, height);
16341
15987
  if (fitted.width <= 0 || fitted.height <= 0)
16342
15988
  return;
16343
15989
  const originX = this.buffered ? 0 : this._screenX;
16344
15990
  const originY = this.buffered ? 0 : this._screenY;
16345
- const x = originX + Math.floor((this.width - fitted.width) / 2);
16346
- const y = originY + Math.floor((this.height - fitted.height) / 2);
15991
+ const x = originX + Math.floor((width - fitted.width) / 2);
15992
+ const y = originY + Math.floor((height - fitted.height) / 2);
16347
15993
  const resolution = pixelResolution(this._ctx);
16348
15994
  const pixelWidth = resolution ? Math.max(1, Math.round(fitted.width * resolution.width / this._ctx.terminalWidth)) : 0;
16349
15995
  const pixelHeight = resolution ? Math.max(1, Math.round(fitted.height * resolution.height / this._ctx.terminalHeight)) : 0;
@@ -16352,7 +15998,7 @@ class ImageRenderable2 extends Renderable2 {
16352
15998
  let sourceWidth = this._image.width;
16353
15999
  let sourceHeight = this._image.height;
16354
16000
  if (this._fit === "cover") {
16355
- const targetAspect = this.width / (this.height * this.cellAspectRatio);
16001
+ const targetAspect = width / (height * this.cellAspectRatio);
16356
16002
  const sourceAspect = sourceWidth / sourceHeight;
16357
16003
  if (sourceAspect > targetAspect) {
16358
16004
  sourceWidth = Math.max(1, Math.round(sourceHeight * targetAspect));
@@ -16738,10 +16384,10 @@ class RootTextNodeRenderable2 extends TextNodeRenderable2 {
16738
16384
 
16739
16385
  // src/renderables/Text.ts
16740
16386
  class TextRenderable2 extends TextBufferRenderable2 {
16741
- static nativeIntegration = this.defineNativeIntegration({
16387
+ static nativeIntegration = {
16742
16388
  ...TextBufferRenderable2.nativeIntegration,
16743
16389
  lineInfo: true
16744
- });
16390
+ };
16745
16391
  _text;
16746
16392
  _hasManualStyledText = false;
16747
16393
  rootTextNode;
@@ -18859,7 +18505,7 @@ function isEditBufferRenderable2(obj) {
18859
18505
  }
18860
18506
 
18861
18507
  class EditBufferRenderable2 extends Renderable2 {
18862
- static nativeIntegration = this.defineNativeIntegration({
18508
+ static nativeIntegration = {
18863
18509
  kind: "editor",
18864
18510
  body: { native: this.prototype.renderSelf },
18865
18511
  lifecycle: {
@@ -18871,9 +18517,8 @@ class EditBufferRenderable2 extends Renderable2 {
18871
18517
  },
18872
18518
  beforeAfter: false,
18873
18519
  paintBuffer: "destination",
18874
- bufferComposition: "native",
18875
- construction: "prototype"
18876
- });
18520
+ bufferComposition: "native"
18521
+ };
18877
18522
  [BrandedEditBufferRenderable] = true;
18878
18523
  static defaultFocusable = true;
18879
18524
  _traits = {};
@@ -19013,7 +18658,7 @@ class EditBufferRenderable2 extends Renderable2 {
19013
18658
  return this.editorView.getVisualCursor();
19014
18659
  }
19015
18660
  get cursorOffset() {
19016
- return this.visualCursor.offset;
18661
+ return this.editorView.isDestroyed ? emptyVisualCursor.offset : this.editBuffer.getCursorPosition().offset;
19017
18662
  }
19018
18663
  set cursorOffset(offset) {
19019
18664
  this.clearSelection();
@@ -19195,13 +18840,19 @@ class EditBufferRenderable2 extends Renderable2 {
19195
18840
  }
19196
18841
  onMouseEvent(event) {
19197
18842
  if (event.type === "scroll") {
19198
- this.handleScroll(event);
18843
+ scrollOnce(event, this, () => {
18844
+ const before = this.editorView.getViewport();
18845
+ this.handleScroll(event);
18846
+ const after = this.editorView.getViewport();
18847
+ return after.offsetX !== before.offsetX || after.offsetY !== before.offsetY;
18848
+ });
19199
18849
  }
19200
18850
  }
19201
18851
  handleScroll(event) {
19202
18852
  if (!event.scroll)
19203
18853
  return;
19204
- const { direction, delta } = event.scroll;
18854
+ const { delta } = event.scroll;
18855
+ const direction = wheelDirection(event);
19205
18856
  const viewport = this.editorView.getViewport();
19206
18857
  if (direction === "up") {
19207
18858
  const newOffsetY = Math.max(0, viewport.offsetY - delta);
@@ -19220,7 +18871,8 @@ class EditBufferRenderable2 extends Renderable2 {
19220
18871
  this.editorView.setViewport(newOffsetX, viewport.offsetY, viewport.width, viewport.height, true);
19221
18872
  this.requestRender();
19222
18873
  } else if (direction === "right") {
19223
- const newOffsetX = viewport.offsetX + delta;
18874
+ const maxOffsetX = Math.max(0, this.lineInfo.lineWidthColsMax - viewport.width);
18875
+ const newOffsetX = Math.min(viewport.offsetX + delta, Math.max(viewport.offsetX, maxOffsetX));
19224
18876
  this.editorView.setViewport(newOffsetX, viewport.offsetY, viewport.width, viewport.height, true);
19225
18877
  this.requestRender();
19226
18878
  }
@@ -19871,7 +19523,6 @@ class NativeLifecyclePasses extends Set {
19871
19523
  class NativeScene {
19872
19524
  driver;
19873
19525
  renderer;
19874
- workBudget;
19875
19526
  get resourceContext() {
19876
19527
  return this.driver.resourceContext;
19877
19528
  }
@@ -19880,27 +19531,19 @@ class NativeScene {
19880
19531
  nodes = new Map;
19881
19532
  paintedFrame = null;
19882
19533
  paintRecording;
19883
- cancelPaintYield = null;
19884
19534
  destroyed = false;
19885
19535
  destroying = false;
19886
- geometryRevision = 0;
19887
19536
  layoutRevision = 0;
19888
19537
  staging = new SceneStaging;
19889
- hookScans = new Set;
19890
- scanningHooks = false;
19891
19538
  yogaHost;
19892
- constructor(driver, renderer, workBudget) {
19539
+ constructor(driver, renderer) {
19893
19540
  this.driver = driver;
19894
19541
  this.renderer = renderer;
19895
- this.workBudget = workBudget;
19896
19542
  this.yogaHost = driver.renderLib.getYogaHost();
19897
19543
  }
19898
19544
  get frame() {
19899
19545
  return this.paintedFrame;
19900
19546
  }
19901
- get currentGeometryRevision() {
19902
- return this.geometryRevision;
19903
- }
19904
19547
  get observedLayoutRevision() {
19905
19548
  if (this.yogaHost.inCallback || this.destroyed || this.driver.disposed)
19906
19549
  return;
@@ -19909,10 +19552,6 @@ class NativeScene {
19909
19552
  get stopped() {
19910
19553
  return this.destroyed || this.destroying || this.driver.disposed || this.renderer.isDestroyed;
19911
19554
  }
19912
- changeGeometry() {
19913
- this.geometryRevision = this.geometryRevision === Number.MAX_SAFE_INTEGER ? 0 : this.geometryRevision + 1;
19914
- this.changeLayout();
19915
- }
19916
19555
  changeLayout() {
19917
19556
  this.layoutRevision = this.layoutRevision === Number.MAX_SAFE_INTEGER ? 0 : this.layoutRevision + 1;
19918
19557
  }
@@ -19938,54 +19577,6 @@ class NativeScene {
19938
19577
  this.yogaHost.forgetScene(this);
19939
19578
  }
19940
19579
  }
19941
- scheduleHookScan(renderable) {
19942
- if (this.stopped)
19943
- return;
19944
- this.hookScans.add(renderable);
19945
- }
19946
- refreshPendingHooks(renderable) {
19947
- if (this.scanningHooks || !this.hookScans.has(renderable))
19948
- return;
19949
- this.scanningHooks = true;
19950
- try {
19951
- renderable._scanNativeSceneHooks();
19952
- } finally {
19953
- this.scanningHooks = false;
19954
- }
19955
- }
19956
- drainHookScans() {
19957
- if (this.scanningHooks)
19958
- throw new Error("Native scene hook discovery is already active");
19959
- if (this.hookScans.size === 0)
19960
- return;
19961
- this.scanningHooks = true;
19962
- let visits = 0;
19963
- try {
19964
- while (this.hookScans.size !== 0) {
19965
- const pending = this.hookScans;
19966
- this.hookScans = new Set;
19967
- try {
19968
- for (const renderable of pending) {
19969
- if (this.stopped)
19970
- return;
19971
- if (++visits > maxHostRequests)
19972
- throw new Error("Native scene hook discovery work limit exceeded");
19973
- renderable._scanNativeSceneHooks();
19974
- pending.delete(renderable);
19975
- }
19976
- } catch (error) {
19977
- if (!this.stopped) {
19978
- for (const renderable of this.hookScans)
19979
- pending.add(renderable);
19980
- this.hookScans = pending;
19981
- }
19982
- throw error;
19983
- }
19984
- }
19985
- } finally {
19986
- this.scanningHooks = false;
19987
- }
19988
- }
19989
19580
  getRenderables() {
19990
19581
  return this.nodes.values();
19991
19582
  }
@@ -20016,7 +19607,7 @@ class NativeScene {
20016
19607
  const handle = child._getSceneHandle(this);
20017
19608
  const parentHandle = parent?._getSceneHandle(this) ?? null;
20018
19609
  this.driver.renderLib.sceneMoveNode(this.driver.context, handle, parentHandle, index);
20019
- this.changeGeometry();
19610
+ this.changeLayout();
20020
19611
  }
20021
19612
  setViewport(content, viewport) {
20022
19613
  this.flushStaged();
@@ -20040,10 +19631,9 @@ class NativeScene {
20040
19631
  this.staging.discard(handle);
20041
19632
  if (!this.staging.pending)
20042
19633
  this.yogaHost.forgetScene(this);
20043
- this.changeGeometry();
19634
+ this.changeLayout();
20044
19635
  renderable._releaseSceneHandle();
20045
19636
  this.nodes.delete(renderable.num);
20046
- this.hookScans.delete(renderable);
20047
19637
  this.renderer.unregisterLifecyclePass(renderable);
20048
19638
  } catch (error) {
20049
19639
  if (flushFailure) {
@@ -20066,7 +19656,6 @@ class NativeScene {
20066
19656
  if (this.staging.stageStyle(this.driver.context, handle, group, kind, edge, unit, value, flags)) {
20067
19657
  this.yogaHost.stageScene(this);
20068
19658
  }
20069
- this.changeGeometry();
20070
19659
  }
20071
19660
  getStyle(node, group, kind, edge) {
20072
19661
  const handle = node._getSceneHandle(this);
@@ -20106,7 +19695,9 @@ class NativeScene {
20106
19695
  this.flushStaged();
20107
19696
  if (this.staging.stagePaint(this.driver.context, handle, paint, renderable))
20108
19697
  this.yogaHost.stageScene(this);
20109
- this.changeGeometry();
19698
+ const { translateX = renderable.translateX, translateY = renderable.translateY } = paint;
19699
+ if (translateX !== renderable.translateX || translateY !== renderable.translateY)
19700
+ this.changeLayout();
20110
19701
  }
20111
19702
  setBackground(renderable, color) {
20112
19703
  this.yogaHost.assertMutable();
@@ -20153,6 +19744,34 @@ class NativeScene {
20153
19744
  const { renderLib: lib, context } = this.driver;
20154
19745
  lib.sceneSetImage(context, renderable._getSceneHandle(this), image?._getContextHandle(lib, context) ?? null, fit, protocol, buffer?._getSceneHandle(this) ?? null);
20155
19746
  }
19747
+ setScroll(renderable, options) {
19748
+ this.flushStaged();
19749
+ this.driver.renderLib.sceneSetScroll(this.driver.context, renderable._getSceneHandle(this), options);
19750
+ this.changeLayout();
19751
+ }
19752
+ setScrollArrow(renderable, axis, end, options) {
19753
+ this.flushStaged();
19754
+ this.driver.renderLib.sceneSetScrollArrow(this.driver.context, renderable._getSceneHandle(this), axis, end, options);
19755
+ }
19756
+ scrollTo(renderable, x, y, relativeX, relativeY, reapply = false) {
19757
+ this.flushStaged();
19758
+ const handle = renderable._getSceneHandle(this);
19759
+ const state = this.driver.renderLib.sceneScrollTo(this.driver.context, handle, x, y, relativeX, relativeY, reapply);
19760
+ this.changeLayout();
19761
+ return state;
19762
+ }
19763
+ scrollRequest(renderable, kind, target, align, inset) {
19764
+ this.flushStaged();
19765
+ const { renderLib: lib, context } = this.driver;
19766
+ const handle = renderable._getSceneHandle(this);
19767
+ const state = lib.sceneScrollRequest(context, handle, kind, target?._getSceneHandle(this) ?? null, align, inset);
19768
+ this.changeLayout();
19769
+ return state;
19770
+ }
19771
+ getScroll(renderable) {
19772
+ this.flushStaged();
19773
+ return this.driver.renderLib.sceneGetScroll(this.driver.context, renderable._getSceneHandle(this));
19774
+ }
20156
19775
  setEditorView(renderable, view) {
20157
19776
  this.flushStaged();
20158
19777
  this.driver.renderLib.sceneSetEditorView(this.driver.context, renderable._getSceneHandle(this), view);
@@ -20177,9 +19796,9 @@ class NativeScene {
20177
19796
  this.flushStaged();
20178
19797
  return this.driver.renderLib.sceneGetText(this.driver.context, renderable._getSceneHandle(this));
20179
19798
  }
20180
- drawText(renderable, buffer, x, y) {
19799
+ drawBody(renderable, buffer, x, y) {
20181
19800
  this.flushStaged();
20182
- buffer._drawSceneText(this, renderable._getSceneHandle(this), x, y);
19801
+ buffer._drawSceneBody(this, renderable._getSceneHandle(this), x, y);
20183
19802
  }
20184
19803
  setTextSelection(renderable, operation, bounds, bg, fg) {
20185
19804
  this.flushStaged();
@@ -20229,9 +19848,7 @@ class NativeScene {
20229
19848
  if (!attached)
20230
19849
  owner.add(root);
20231
19850
  try {
20232
- this.drainHookScans();
20233
19851
  this.runLifecyclePasses();
20234
- this.drainHookScans();
20235
19852
  this.assertAlive();
20236
19853
  this.flushStaged();
20237
19854
  try {
@@ -20248,14 +19865,11 @@ class NativeScene {
20248
19865
  paint(deltaTime, getPaintOptions) {
20249
19866
  this.yogaHost.assertMutable();
20250
19867
  this.assertAlive();
20251
- if (this.cancelPaintYield || this.paintedFrame)
19868
+ if (this.paintedFrame)
20252
19869
  throw new Error("Native scene is already painting a frame");
20253
19870
  this.renderer.root._setCurrentRenderable(undefined);
20254
- this.drainHookScans();
20255
19871
  this.runLifecyclePasses();
20256
- const continuation = this.advancePaint(deltaTime, getPaintOptions);
20257
- if (continuation)
20258
- return this.resumePaint(deltaTime, getPaintOptions, continuation);
19872
+ this.advancePaint(deltaTime, getPaintOptions);
20259
19873
  }
20260
19874
  runLifecyclePasses() {
20261
19875
  if (this.renderer.root.visible) {
@@ -20268,67 +19882,29 @@ class NativeScene {
20268
19882
  if (!renderable.isDestroyed) {
20269
19883
  renderable.onLifecyclePass?.call(renderable);
20270
19884
  }
20271
- this.drainHookScans();
20272
- }
20273
- }
20274
- }
20275
- async resumePaint(deltaTime, getPaintOptions, continuation) {
20276
- while (continuation) {
20277
- await continuation.wait;
20278
- this.cancelPaintYield = null;
20279
- if (continuation.interrupted === "restart") {
20280
- this.cancelAttempt(continuation.request);
20281
- this.drainHookScans();
20282
- this.runLifecyclePasses();
20283
- continuation = undefined;
20284
19885
  }
20285
- continuation = this.advancePaint(deltaTime, getPaintOptions, continuation);
20286
19886
  }
20287
19887
  }
20288
- advancePaint(deltaTime, getPaintOptions, continuation) {
20289
- let request = continuation?.request ?? null;
19888
+ advancePaint(deltaTime, getPaintOptions) {
19889
+ let request = null;
20290
19890
  let recording = null;
20291
- let yielded = false;
20292
19891
  try {
20293
- while (continuation?.interrupted !== "cancel" && !this.stopped) {
20294
- this.drainHookScans();
19892
+ while (!this.stopped) {
20295
19893
  const options = { ...getPaintOptions(), maxLayoutRounds, maxHostRequests };
20296
19894
  if (this.stopped || this.renderer.controlState === "explicit_suspended" /* EXPLICIT_SUSPENDED */)
20297
19895
  return;
20298
19896
  this.flushStaged();
20299
- const geometryRevision = this.geometryRevision;
20300
19897
  try {
20301
- request = this.driver.renderLib.sceneFrameStep(this.driver.context, this.driver.session, request, options, this.workBudget, recording);
19898
+ request = this.driver.renderLib.sceneFrameStep(this.driver.context, this.driver.session, request, options, recording);
20302
19899
  } finally {
20303
19900
  this.changeLayout();
20304
19901
  this.paintRecording?.recorder.settle();
20305
19902
  }
20306
19903
  recording = null;
20307
- request.geometryRevision = geometryRevision;
20308
19904
  if (request.kind === NativeSceneFrame2.Done) {
20309
19905
  this.paintedFrame = request;
20310
19906
  return;
20311
19907
  }
20312
- if (request.kind === NativeSceneFrame2.Yield) {
20313
- const wait = Promise.withResolvers();
20314
- const state = continuation ?? { request, wait: wait.promise };
20315
- state.request = request;
20316
- state.wait = wait.promise;
20317
- const cancel = this.driver.scheduler.schedule(wait.resolve);
20318
- this.cancelPaintYield = (restart = false) => {
20319
- const first = state.interrupted === undefined;
20320
- state.interrupted = restart && state.interrupted !== "cancel" ? "restart" : "cancel";
20321
- if (!first)
20322
- return;
20323
- try {
20324
- cancel();
20325
- } finally {
20326
- wait.resolve();
20327
- }
20328
- };
20329
- yielded = true;
20330
- return state;
20331
- }
20332
19908
  if (!sameHandle(request.session, this.driver.session) || !sameHandle(request.root, this.renderer.root._getSceneHandle(this))) {
20333
19909
  throw new Error("Native scene returned a stale host request");
20334
19910
  }
@@ -20346,7 +19922,7 @@ class NativeScene {
20346
19922
  }
20347
19923
  } finally {
20348
19924
  this.paintRecording?.recorder.settle();
20349
- if (!yielded && request && request !== this.paintedFrame)
19925
+ if (request && request !== this.paintedFrame)
20350
19926
  this.cancelAttempt(request);
20351
19927
  }
20352
19928
  }
@@ -20362,6 +19938,7 @@ class NativeScene {
20362
19938
  const { renderLib: lib, context, session } = this.driver;
20363
19939
  const slots = lib.sceneFrameGetPaintSlots(context, session, request);
20364
19940
  const paint = this.paintRecording ??= this.createPaintRecording();
19941
+ const revision = this.layoutRevision;
20365
19942
  paint.recorder.begin(context);
20366
19943
  try {
20367
19944
  for (let index = 0;index < slots.length; index++) {
@@ -20375,7 +19952,7 @@ class NativeScene {
20375
19952
  throw new Error("Native scene returned a stale paint slot");
20376
19953
  }
20377
19954
  this.renderer.root._setCurrentRenderable(renderable);
20378
- renderable._recordNativeScenePaint(slot, index, deltaTime, paint.buffer, paint.recorder, request.geometryRevision);
19955
+ renderable._recordNativeScenePaint(slot, index, deltaTime, paint.buffer, paint.recorder, this.layoutRevision === revision ? slot.publicLayout : undefined);
20379
19956
  this.renderer.root._setCurrentRenderable(undefined);
20380
19957
  }
20381
19958
  return paint.recorder.recording;
@@ -20405,18 +19982,11 @@ class NativeScene {
20405
19982
  return result;
20406
19983
  }
20407
19984
  cancelFrame() {
20408
- this.cancelPaintYield?.();
20409
19985
  const frame = this.paintedFrame;
20410
19986
  this.paintedFrame = null;
20411
19987
  if (frame)
20412
19988
  this.cancelAttempt(frame);
20413
19989
  }
20414
- interruptPaint() {
20415
- this.cancelPaintYield?.();
20416
- }
20417
- restartPaint() {
20418
- this.cancelPaintYield?.(true);
20419
- }
20420
19990
  hitTest(x, y) {
20421
19991
  this.assertAlive();
20422
19992
  const id = this.driver.renderLib.sceneHitTest(this.driver.context, this.driver.session, x, y);
@@ -20430,14 +20000,8 @@ class NativeScene {
20430
20000
  this.destroying = true;
20431
20001
  this.staging.clear();
20432
20002
  this.yogaHost.forgetScene(this);
20433
- this.hookScans.clear();
20434
20003
  let failure;
20435
20004
  try {
20436
- try {
20437
- this.cancelPaintYield?.();
20438
- } catch (error) {
20439
- failure = { error };
20440
- }
20441
20005
  for (const renderable of this.nodes.values()) {
20442
20006
  try {
20443
20007
  renderable.destroyRecursively();
@@ -20585,9 +20149,6 @@ function isCapabilityResponse(sequence) {
20585
20149
  if (/\x1b\[\?\d+(?:;\d+)*\$y/.test(sequence)) {
20586
20150
  return true;
20587
20151
  }
20588
- if (/\x1b\[1;(?!1R)\d+R/.test(sequence)) {
20589
- return true;
20590
- }
20591
20152
  if (/\x1bP>\|[\s\S]*?\x1b\\/.test(sequence)) {
20592
20153
  return true;
20593
20154
  }
@@ -20614,6 +20175,9 @@ function isCapabilityResponse(sequence) {
20614
20175
  }
20615
20176
  return false;
20616
20177
  }
20178
+ function isExplicitWidthReport(sequence) {
20179
+ return /\x1b\[1;(?!1R)\d+R/.test(sequence);
20180
+ }
20617
20181
  function isPixelResolutionResponse(sequence) {
20618
20182
  return /\x1b\[4;\d+;\d+t/.test(sequence);
20619
20183
  }
@@ -20629,6 +20193,496 @@ function parsePixelResolution(sequence) {
20629
20193
  return null;
20630
20194
  }
20631
20195
 
20196
+ // src/lib/stdin-parser-native.ts
20197
+ import { Buffer as Buffer4 } from "node:buffer";
20198
+ var RECORD_CAPACITY = 64;
20199
+ var PAYLOAD_CAPACITY = 16 * 1024;
20200
+ var RECORD = nativeLayouts.ot_input_event;
20201
+ var FIELD = {
20202
+ kind: RECORD.fields.kind.offset,
20203
+ action: RECORD.fields.action.offset,
20204
+ modifiers: RECORD.fields.modifiers.offset,
20205
+ flags: RECORD.fields.flags.offset,
20206
+ code: RECORD.fields.code.offset / 4,
20207
+ baseCode: RECORD.fields.base_code.offset / 4,
20208
+ x: RECORD.fields.x.offset / 2,
20209
+ y: RECORD.fields.y.offset / 2,
20210
+ rawOffset: RECORD.fields.raw_offset.offset / 4,
20211
+ rawLength: RECORD.fields.raw_len.offset / 4,
20212
+ textOffset: RECORD.fields.text_offset.offset / 4,
20213
+ textLength: RECORD.fields.text_len.offset / 4
20214
+ };
20215
+ var C = nativeConstants;
20216
+ var EMPTY = new Uint8Array(0);
20217
+ var UTF8 = new TextDecoder;
20218
+ var MOUSE_TYPES = {
20219
+ [C.OT_INPUT_MOUSE_DOWN]: "down",
20220
+ [C.OT_INPUT_MOUSE_UP]: "up",
20221
+ [C.OT_INPUT_MOUSE_MOVE]: "move",
20222
+ [C.OT_INPUT_MOUSE_DRAG]: "drag",
20223
+ [C.OT_INPUT_MOUSE_SCROLL]: "scroll"
20224
+ };
20225
+ var SCROLL_DIRECTIONS = ["up", "down", "left", "right"];
20226
+ var NO_EXPECTATIONS = {
20227
+ kittyKeyboardEnabled: false,
20228
+ privateCapabilityRepliesActive: false,
20229
+ pixelResolutionQueryActive: false,
20230
+ explicitWidthCprActive: false,
20231
+ startupCursorCprActive: false,
20232
+ replySentinelActive: false
20233
+ };
20234
+ var REPLY_PROTOCOLS = {
20235
+ [C.OT_INPUT_REPLY_CSI]: "csi",
20236
+ [C.OT_INPUT_REPLY_SS3]: "unknown",
20237
+ [C.OT_INPUT_REPLY_OSC]: "osc",
20238
+ [C.OT_INPUT_REPLY_DCS]: "dcs",
20239
+ [C.OT_INPUT_REPLY_APC]: "apc"
20240
+ };
20241
+ var LEGACY_CODE_RE = /^\x1b+(O|\[\[?)(?:(\d+)(?:;\d+)?([~^$])|(?:1;)?\d*([a-zA-Z]))/;
20242
+ var LEGACY_SEQUENCE_RE = /^\x1b\x1b?[[O]./s;
20243
+ var KEYPAD_TEXT = new Set(Object.values(printableKeypadText));
20244
+ function concat(parts) {
20245
+ let length = 0;
20246
+ for (const part of parts)
20247
+ length += part.length;
20248
+ const bytes = new Uint8Array(length);
20249
+ let offset = 0;
20250
+ for (const part of parts) {
20251
+ bytes.set(part, offset);
20252
+ offset += part.length;
20253
+ }
20254
+ return bytes;
20255
+ }
20256
+ function latin1(bytes) {
20257
+ return Buffer4.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("latin1");
20258
+ }
20259
+ function expectationFlags(context) {
20260
+ const cursorPosition = context.explicitWidthCprActive || context.startupCursorCprActive;
20261
+ const replies = context.privateCapabilityRepliesActive || context.pixelResolutionQueryActive || cursorPosition;
20262
+ return (replies ? C.OT_INPUT_EXPECT_REPLIES : 0) | (context.kittyKeyboardEnabled ? C.OT_INPUT_EXPECT_KITTY_KEYBOARD : 0) | (cursorPosition ? C.OT_INPUT_EXPECT_CURSOR_POSITION : 0) | (context.replySentinelActive ? C.OT_INPUT_EXPECT_SENTINEL : 0);
20263
+ }
20264
+
20265
+ class NativeStdinParser {
20266
+ lib;
20267
+ context;
20268
+ session;
20269
+ ownsContext;
20270
+ records = new Uint8Array(RECORD_CAPACITY * RECORD.size);
20271
+ words = new Uint32Array(this.records.buffer);
20272
+ halves = new Uint16Array(this.records.buffer);
20273
+ payload = new Uint8Array(PAYLOAD_CAPACITY);
20274
+ events = [];
20275
+ clock;
20276
+ armTimeouts;
20277
+ onTimeoutFlush;
20278
+ protocolContext;
20279
+ appliedExpectations = 0;
20280
+ timeoutId = null;
20281
+ deadlineNs = null;
20282
+ lastNs = 0n;
20283
+ paste = null;
20284
+ suspended = false;
20285
+ sessionGone = false;
20286
+ destroyed = false;
20287
+ constructor(options = {}) {
20288
+ this.clock = options.clock ?? new SystemClock2;
20289
+ this.armTimeouts = options.armTimeouts ?? true;
20290
+ this.onTimeoutFlush = options.onTimeoutFlush ?? null;
20291
+ this.protocolContext = { ...NO_EXPECTATIONS, ...options.protocolContext };
20292
+ if (options.session) {
20293
+ this.lib = options.session.lib;
20294
+ this.context = options.session.context;
20295
+ this.session = options.session.session;
20296
+ this.ownsContext = false;
20297
+ } else {
20298
+ this.lib = resolveRenderLib2();
20299
+ this.context = this.lib.createContext({ objectCapacity: 4, renderCellsMax: 1 });
20300
+ try {
20301
+ this.session = this.lib.createSession(this.context, { chunkSize: 4096, spanCapacity: 2, maxBytes: 8192n });
20302
+ } catch (error) {
20303
+ this.destroyContext();
20304
+ throw error;
20305
+ }
20306
+ this.ownsContext = true;
20307
+ }
20308
+ try {
20309
+ this.applyExpectations();
20310
+ } catch (error) {
20311
+ if (this.ownsContext)
20312
+ this.destroyContext();
20313
+ throw error;
20314
+ }
20315
+ }
20316
+ updateProtocolContext(patch) {
20317
+ this.ensureAlive();
20318
+ this.protocolContext = { ...this.protocolContext, ...patch };
20319
+ this.native(() => {
20320
+ this.applyExpectations();
20321
+ this.feed(EMPTY, this.nowNs());
20322
+ });
20323
+ this.reconcileTimeout(this.events.length > 0);
20324
+ }
20325
+ get pasting() {
20326
+ return this.paste !== null;
20327
+ }
20328
+ push(data) {
20329
+ this.ensureAlive();
20330
+ this.native(() => this.feed(data, this.nowNs()));
20331
+ this.reconcileTimeout();
20332
+ }
20333
+ read() {
20334
+ this.ensureAlive();
20335
+ return this.events.shift() ?? null;
20336
+ }
20337
+ drain(onEvent) {
20338
+ this.ensureAlive();
20339
+ while (!this.destroyed) {
20340
+ const event = this.events.shift();
20341
+ if (!event)
20342
+ return;
20343
+ onEvent(event);
20344
+ }
20345
+ }
20346
+ flushTimeout(nowMsValue = this.clock.now()) {
20347
+ this.ensureAlive();
20348
+ this.native(() => this.feed(EMPTY, this.toNs(nowMsValue)));
20349
+ this.reconcileTimeout();
20350
+ }
20351
+ suspend() {
20352
+ this.ensureAlive();
20353
+ this.suspended = true;
20354
+ this.clearTimeout();
20355
+ }
20356
+ resume() {
20357
+ this.ensureAlive();
20358
+ this.suspended = false;
20359
+ this.native(() => this.lib.sessionInputReset(this.context, this.session, C.OT_INPUT_RESET_KEEP_REPLY));
20360
+ this.paste = null;
20361
+ this.deadlineNs = null;
20362
+ }
20363
+ reset() {
20364
+ if (this.destroyed)
20365
+ return;
20366
+ this.clearTimeout();
20367
+ this.native(() => this.lib.sessionInputReset(this.context, this.session, 0));
20368
+ this.events.length = 0;
20369
+ this.paste = null;
20370
+ this.deadlineNs = null;
20371
+ }
20372
+ destroy() {
20373
+ if (this.destroyed)
20374
+ return;
20375
+ this.clearTimeout();
20376
+ this.destroyed = true;
20377
+ this.events.length = 0;
20378
+ this.paste = null;
20379
+ if (this.ownsContext)
20380
+ this.destroyContext();
20381
+ }
20382
+ ensureAlive() {
20383
+ if (this.destroyed)
20384
+ throw new Error("StdinParser has been destroyed");
20385
+ }
20386
+ native(call) {
20387
+ if (this.sessionGone)
20388
+ return;
20389
+ try {
20390
+ call();
20391
+ } catch (error) {
20392
+ if (!(error instanceof NativeError2) || error.status !== -12 /* SessionClosed */ && error.status !== -15 /* OutputFailed */ && error.status !== -9 /* StaleHandle */ && error.status !== -7 /* WrongContext */) {
20393
+ throw error;
20394
+ }
20395
+ this.sessionGone = true;
20396
+ this.deadlineNs = null;
20397
+ this.paste = null;
20398
+ this.clearTimeout();
20399
+ }
20400
+ }
20401
+ destroyContext() {
20402
+ this.lib.getYogaHost().runMutation(() => this.lib.destroyContext(this.context));
20403
+ }
20404
+ applyExpectations() {
20405
+ const flags = expectationFlags(this.protocolContext);
20406
+ if (flags === this.appliedExpectations)
20407
+ return;
20408
+ this.lib.sessionInputExpect(this.context, this.session, flags);
20409
+ this.appliedExpectations = flags;
20410
+ }
20411
+ toNs(ms) {
20412
+ const ns = BigInt(Math.max(0, Math.round(ms * 1e6)));
20413
+ return ns > this.lastNs ? ns : this.lastNs;
20414
+ }
20415
+ nowNs() {
20416
+ return this.suspended ? this.lastNs : this.toNs(this.clock.now());
20417
+ }
20418
+ feed(bytes, nowNs) {
20419
+ this.lastNs = nowNs;
20420
+ let offset = 0;
20421
+ do {
20422
+ const rest = offset === 0 ? bytes : bytes.subarray(offset);
20423
+ const drain = this.lib.sessionInputFeed(this.context, this.session, rest, nowNs, this.records, this.payload);
20424
+ this.deadlineNs = drain.deadlineNs;
20425
+ for (let index = 0;index < drain.count; index++)
20426
+ this.translate(index);
20427
+ if (drain.consumed === 0 && drain.count === 0 && offset < bytes.length) {
20428
+ throw new Error("native input parser made no progress");
20429
+ }
20430
+ offset += drain.consumed;
20431
+ } while (offset < bytes.length);
20432
+ }
20433
+ reconcileTimeout(flushNow = false) {
20434
+ if (!this.armTimeouts)
20435
+ return;
20436
+ this.clearTimeout();
20437
+ const deadline = flushNow ? null : this.deadlineNs;
20438
+ if (deadline === null && !flushNow || this.suspended || this.sessionGone)
20439
+ return;
20440
+ const delayMs = deadline === null ? 0 : Number((deadline - this.lastNs + 999999n) / 1000000n);
20441
+ this.timeoutId = this.clock.setTimeout(() => {
20442
+ this.timeoutId = null;
20443
+ if (this.destroyed)
20444
+ return;
20445
+ try {
20446
+ const now = this.nowNs();
20447
+ this.native(() => this.feed(EMPTY, deadline !== null && now < deadline ? deadline : now));
20448
+ this.reconcileTimeout();
20449
+ this.onTimeoutFlush?.();
20450
+ } catch (error) {
20451
+ console.error("stdin parser timeout flush failed", error);
20452
+ }
20453
+ }, delayMs);
20454
+ }
20455
+ clearTimeout() {
20456
+ if (this.timeoutId === null)
20457
+ return;
20458
+ this.clock.clearTimeout(this.timeoutId);
20459
+ this.timeoutId = null;
20460
+ }
20461
+ span(offset, length) {
20462
+ return this.payload.subarray(offset, offset + length);
20463
+ }
20464
+ translate(index) {
20465
+ const base = index * RECORD.size;
20466
+ const word = base / 4;
20467
+ const half = base / 2;
20468
+ const kind = this.records[base + FIELD.kind];
20469
+ const action = this.records[base + FIELD.action];
20470
+ const modifiers = this.records[base + FIELD.modifiers];
20471
+ const flags = this.records[base + FIELD.flags];
20472
+ const code = this.words[word + FIELD.code];
20473
+ const raw = this.span(this.words[word + FIELD.rawOffset], this.words[word + FIELD.rawLength]);
20474
+ const text = this.span(this.words[word + FIELD.textOffset], this.words[word + FIELD.textLength]);
20475
+ switch (kind) {
20476
+ case C.OT_INPUT_KEY: {
20477
+ const key = parsedKey(code, this.words[word + FIELD.baseCode], action, modifiers, flags, raw, text);
20478
+ this.events.push({ type: "key", raw: key.raw, key });
20479
+ return;
20480
+ }
20481
+ case C.OT_INPUT_MOUSE: {
20482
+ const sequence = latin1(raw);
20483
+ const encoding = raw[2] === 60 ? "sgr" : "x10";
20484
+ const event = rawMouseEvent(action, code, this.halves[half + FIELD.x], this.halves[half + FIELD.y], modifiers, encoding);
20485
+ this.events.push({ type: "mouse", raw: sequence, encoding, event });
20486
+ return;
20487
+ }
20488
+ case C.OT_INPUT_PASTE: {
20489
+ if (flags & C.OT_INPUT_PASTE_START)
20490
+ this.paste = [];
20491
+ if (text.length > 0)
20492
+ this.paste.push(Uint8Array.from(text));
20493
+ if (flags & C.OT_INPUT_PASTE_END) {
20494
+ const parts = this.paste;
20495
+ this.paste = null;
20496
+ this.events.push({ type: "paste", bytes: parts.length === 1 ? parts[0] : concat(parts) });
20497
+ }
20498
+ return;
20499
+ }
20500
+ case C.OT_INPUT_FOCUS:
20501
+ this.events.push({ type: "response", protocol: "csi", sequence: latin1(raw) });
20502
+ return;
20503
+ case C.OT_INPUT_REPLY: {
20504
+ const protocol = flags & C.OT_INPUT_REPLY_CURSOR_POSITION ? "cpr" : flags & C.OT_INPUT_REPLY_FRAGMENT ? "unknown" : REPLY_PROTOCOLS[code];
20505
+ this.events.push({ type: "response", protocol, sequence: latin1(raw) });
20506
+ return;
20507
+ }
20508
+ }
20509
+ throw new Error(`Unknown native input event kind: ${kind}`);
20510
+ }
20511
+ }
20512
+ function keyRaw(raw) {
20513
+ if (raw.length === 1 && raw[0] >= 128)
20514
+ return "\x1B" + String.fromCharCode(raw[0] & 127);
20515
+ return UTF8.decode(raw);
20516
+ }
20517
+ function compatCode(raw, code, kitty) {
20518
+ if (kitty) {
20519
+ if (!raw.endsWith("u") || kittyKeyMap[code] === undefined)
20520
+ return;
20521
+ return `[${/^\x1b+\[(\d+)/.exec(raw)[1]}u`;
20522
+ }
20523
+ if (kittyKeyMap[code] === undefined && !KEYPAD_TEXT.has(String.fromCodePoint(code)))
20524
+ return;
20525
+ const match = LEGACY_CODE_RE.exec(raw);
20526
+ return match ? [match[1], match[2], match[3], match[4]].filter(Boolean).join("") : undefined;
20527
+ }
20528
+ function parsedKey(code, baseCode, action, modifiers, flags, rawBytes, textBytes) {
20529
+ const kitty = (flags & C.OT_INPUT_KEY_KITTY) !== 0;
20530
+ const raw = keyRaw(rawBytes);
20531
+ const text = textBytes.length === 0 ? "" : UTF8.decode(textBytes);
20532
+ const alt = (modifiers & C.OT_INPUT_MOD_ALT) !== 0;
20533
+ const sequence = kitty || LEGACY_SEQUENCE_RE.test(raw);
20534
+ let shift = (modifiers & C.OT_INPUT_MOD_SHIFT) !== 0;
20535
+ let name;
20536
+ if (code === 0) {
20537
+ name = text;
20538
+ } else if (kittyKeyMap[code] !== undefined) {
20539
+ name = code === C.OT_INPUT_KEY_ENTER && !kitty && raw.endsWith(`
20540
+ `) ? "linefeed" : kittyKeyMap[code];
20541
+ } else if (code === 32) {
20542
+ name = "space";
20543
+ } else {
20544
+ name = String.fromCodePoint(code);
20545
+ if (!sequence && code >= 65 && code <= 90) {
20546
+ shift = true;
20547
+ if (!alt)
20548
+ name = name.toLowerCase();
20549
+ }
20550
+ }
20551
+ const key = {
20552
+ name,
20553
+ ctrl: (modifiers & C.OT_INPUT_MOD_CTRL) !== 0,
20554
+ meta: alt || (modifiers & C.OT_INPUT_MOD_META) !== 0,
20555
+ shift,
20556
+ option: alt && sequence,
20557
+ sequence: text || raw,
20558
+ number: /^[0-9]$/.test(name),
20559
+ raw,
20560
+ eventType: action === C.OT_INPUT_KEY_RELEASE ? "release" : "press",
20561
+ source: kitty ? "kitty" : "raw",
20562
+ super: (modifiers & C.OT_INPUT_MOD_SUPER) !== 0,
20563
+ hyper: (modifiers & C.OT_INPUT_MOD_HYPER) !== 0,
20564
+ capsLock: (modifiers & C.OT_INPUT_MOD_CAPS_LOCK) !== 0,
20565
+ numLock: (modifiers & C.OT_INPUT_MOD_NUM_LOCK) !== 0
20566
+ };
20567
+ if (action === C.OT_INPUT_KEY_REPEAT)
20568
+ key.repeated = true;
20569
+ if (baseCode !== 0)
20570
+ key.baseCode = baseCode;
20571
+ const legacy = compatCode(raw, code, kitty);
20572
+ if (legacy !== undefined)
20573
+ key.code = legacy;
20574
+ return key;
20575
+ }
20576
+ function rawMouseEvent(action, code, x, y, modifiers, encoding) {
20577
+ const type = MOUSE_TYPES[action];
20578
+ if (!type)
20579
+ throw new Error(`Unknown native mouse action: ${action}`);
20580
+ let button = code;
20581
+ if (code === C.OT_INPUT_MOUSE_BUTTON_NONE)
20582
+ button = encoding === "x10" ? -1 : 0;
20583
+ if (type === "scroll")
20584
+ button = encoding === "x10" || code === 3 ? 0 : code;
20585
+ const event = {
20586
+ type,
20587
+ button,
20588
+ x,
20589
+ y,
20590
+ modifiers: {
20591
+ shift: (modifiers & C.OT_INPUT_MOD_SHIFT) !== 0,
20592
+ alt: (modifiers & C.OT_INPUT_MOD_ALT) !== 0,
20593
+ ctrl: (modifiers & C.OT_INPUT_MOD_CTRL) !== 0
20594
+ }
20595
+ };
20596
+ if (type === "scroll")
20597
+ event.scroll = { direction: SCROLL_DIRECTIONS[code & 3], delta: 1 };
20598
+ return event;
20599
+ }
20600
+ var SHADOW_BACKLOG_MAX = 256;
20601
+ var SHADOW_WINDOW = 8;
20602
+ function describeEvent(event) {
20603
+ switch (event.type) {
20604
+ case "key": {
20605
+ const { name, ctrl, meta, shift, eventType } = event.key;
20606
+ return JSON.stringify(["key", event.raw, name, ctrl, meta, shift, eventType]);
20607
+ }
20608
+ case "mouse": {
20609
+ const { type, button, x, y, modifiers } = event.event;
20610
+ return JSON.stringify(["mouse", event.raw, type, button, x, y, modifiers.shift, modifiers.alt, modifiers.ctrl]);
20611
+ }
20612
+ case "paste":
20613
+ return JSON.stringify(["paste", event.bytes.length, Buffer4.from(event.bytes).toString("base64")]);
20614
+ case "response":
20615
+ return JSON.stringify(["response", event.protocol, event.sequence]);
20616
+ }
20617
+ }
20618
+
20619
+ class StdinShadowComparator {
20620
+ primaryName;
20621
+ log;
20622
+ delivered = [];
20623
+ shadowed = [];
20624
+ constructor(primaryName, log) {
20625
+ this.primaryName = primaryName;
20626
+ this.log = log;
20627
+ }
20628
+ primary(event) {
20629
+ this.queue(this.delivered, event);
20630
+ }
20631
+ shadow(event) {
20632
+ this.queue(this.shadowed, event);
20633
+ }
20634
+ flush() {
20635
+ this.pair(true);
20636
+ }
20637
+ queue(events, event) {
20638
+ events.push(describeEvent(event));
20639
+ this.pair(false);
20640
+ if (events.length > SHADOW_BACKLOG_MAX) {
20641
+ const dropped = events.shift();
20642
+ if (events === this.delivered)
20643
+ this.report(dropped, "");
20644
+ else
20645
+ this.report("", dropped);
20646
+ }
20647
+ }
20648
+ pair(final) {
20649
+ const { delivered, shadowed } = this;
20650
+ while (delivered.length > 0 && shadowed.length > 0) {
20651
+ const [i, j] = commonEvent(delivered, shadowed) ?? [-1, -1];
20652
+ if (i >= 0) {
20653
+ for (let k = 0;k < Math.max(i, j); k++)
20654
+ this.report(k < i ? delivered[k] : "", k < j ? shadowed[k] : "");
20655
+ delivered.splice(0, i + 1);
20656
+ shadowed.splice(0, j + 1);
20657
+ } else if (final || Math.min(delivered.length, shadowed.length) >= SHADOW_WINDOW) {
20658
+ this.report(delivered.shift(), shadowed.shift());
20659
+ } else
20660
+ return;
20661
+ }
20662
+ if (final) {
20663
+ for (const event of delivered.splice(0))
20664
+ this.report(event, "");
20665
+ for (const event of shadowed.splice(0))
20666
+ this.report("", event);
20667
+ }
20668
+ }
20669
+ report(delivered, shadowed) {
20670
+ const shadowName = this.primaryName === "native" ? "legacy" : "native";
20671
+ this.log(`[stdin-shadow] ${this.primaryName}=${delivered || "none"} ${shadowName}=${shadowed || "none"}`);
20672
+ }
20673
+ }
20674
+ function commonEvent(a, b) {
20675
+ const aEnd = Math.min(a.length, SHADOW_WINDOW);
20676
+ const bEnd = Math.min(b.length, SHADOW_WINDOW);
20677
+ for (let sum = 0;sum < aEnd + bEnd - 1; sum++) {
20678
+ for (let i = Math.max(0, sum - bEnd + 1);i <= Math.min(sum, aEnd - 1); i++) {
20679
+ if (a[i] === b[sum - i])
20680
+ return [i, sum - i];
20681
+ }
20682
+ }
20683
+ return null;
20684
+ }
20685
+
20632
20686
  // src/renderer-theme-mode.ts
20633
20687
  var OSC_THEME_RESPONSE = /\x1b](10|11);(?:(?:rgb:)([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)|#([0-9a-fA-F]{6}))(?:\x07|\x1b\\)/g;
20634
20688
  function scaleOscThemeComponent(component) {
@@ -20656,9 +20710,6 @@ class RendererThemeMode {
20656
20710
  clock;
20657
20711
  static QUERY_TIMEOUT_MS = 250;
20658
20712
  _themeMode = null;
20659
- themeQueryPending = true;
20660
- themeOscForeground = null;
20661
- themeOscBackground = null;
20662
20713
  themeRefreshTimeoutId = null;
20663
20714
  waiters = new Set;
20664
20715
  constructor(host, clock) {
@@ -20687,14 +20738,6 @@ class RendererThemeMode {
20687
20738
  this.waiters.add(waiter);
20688
20739
  });
20689
20740
  }
20690
- cancelRefresh() {
20691
- if (this.themeRefreshTimeoutId === null) {
20692
- return;
20693
- }
20694
- this.clock.clearTimeout(this.themeRefreshTimeoutId);
20695
- this.themeRefreshTimeoutId = null;
20696
- this.themeQueryPending = false;
20697
- }
20698
20741
  dispose() {
20699
20742
  this.cancelRefresh();
20700
20743
  for (const waiter of this.waiters) {
@@ -20710,54 +20753,35 @@ class RendererThemeMode {
20710
20753
  this.requestThemeOscColors();
20711
20754
  return { handled: true, changedMode: null };
20712
20755
  }
20713
- let handledOscThemeResponse = false;
20756
+ let handled = false;
20757
+ let background = null;
20714
20758
  let match;
20715
20759
  OSC_THEME_RESPONSE.lastIndex = 0;
20716
20760
  while (match = OSC_THEME_RESPONSE.exec(sequence)) {
20717
- handledOscThemeResponse = true;
20718
- const color = oscThemeColorToHex(match[2], match[3], match[4], match[5]);
20719
- if (match[1] === "10") {
20720
- this.themeOscForeground = color;
20721
- } else {
20722
- this.themeOscBackground = color;
20723
- }
20724
- }
20725
- if (!handledOscThemeResponse) {
20726
- return { handled: false, changedMode: null };
20727
- }
20728
- if (!this.themeQueryPending) {
20729
- return { handled: true, changedMode: null };
20761
+ handled = true;
20762
+ if (match[1] === "11")
20763
+ background = oscThemeColorToHex(match[2], match[3], match[4], match[5]);
20730
20764
  }
20731
- if (!this.themeOscForeground || !this.themeOscBackground) {
20732
- return { handled: true, changedMode: null };
20765
+ if (background === null) {
20766
+ return { handled, changedMode: null };
20733
20767
  }
20734
- const nextMode = inferThemeModeFromBackgroundColor(this.themeOscBackground);
20735
- const changedMode = this.applyThemeMode(nextMode);
20736
- this.completeThemeQuery();
20737
- return { handled: true, changedMode };
20768
+ this.cancelRefresh();
20769
+ return { handled, changedMode: this.applyThemeMode(inferThemeModeFromBackgroundColor(background)) };
20738
20770
  }
20739
- clearThemeRefreshTimeout() {
20771
+ cancelRefresh() {
20740
20772
  if (this.themeRefreshTimeoutId === null) {
20741
20773
  return;
20742
20774
  }
20743
20775
  this.clock.clearTimeout(this.themeRefreshTimeoutId);
20744
20776
  this.themeRefreshTimeoutId = null;
20745
20777
  }
20746
- completeThemeQuery() {
20747
- this.clearThemeRefreshTimeout();
20748
- this.themeQueryPending = false;
20749
- }
20750
20778
  requestThemeOscColors() {
20751
20779
  if (this.themeRefreshTimeoutId !== null) {
20752
20780
  return;
20753
20781
  }
20754
- this.themeQueryPending = true;
20755
- this.themeOscForeground = null;
20756
- this.themeOscBackground = null;
20757
20782
  this.host.queryThemeColors();
20758
- this.clearThemeRefreshTimeout();
20759
20783
  this.themeRefreshTimeoutId = this.clock.setTimeout(() => {
20760
- this.completeThemeQuery();
20784
+ this.themeRefreshTimeoutId = null;
20761
20785
  }, RendererThemeMode.QUERY_TIMEOUT_MS);
20762
20786
  }
20763
20787
  applyThemeMode(mode) {
@@ -20814,6 +20838,18 @@ registerEnvVar2({
20814
20838
  type: "boolean",
20815
20839
  default: false
20816
20840
  });
20841
+ registerEnvVar2({
20842
+ name: "OTUI_NATIVE_INPUT_PARSER",
20843
+ description: "Parse stdin with the experimental native input parser unless experimental_nativeInput is set.",
20844
+ type: "boolean",
20845
+ default: false
20846
+ });
20847
+ registerEnvVar2({
20848
+ name: "OTUI_NATIVE_INPUT_SHADOW",
20849
+ description: "Also run the other stdin parser and log one line for each event that differs.",
20850
+ type: "boolean",
20851
+ default: false
20852
+ });
20817
20853
  var KITTY_IMAGE_TRANSPORTS = ["raw", "zlib", "file"];
20818
20854
  var DEFAULT_FOOTER_HEIGHT = 12;
20819
20855
  var MAX_SCROLLBACK_SURFACE_HEIGHT_PASSES = 4;
@@ -20940,6 +20976,7 @@ class ExternalOutputQueue {
20940
20976
 
20941
20977
  class ScrollbackSnapshotRenderContext extends EventEmitter8 {
20942
20978
  nativeOwner;
20979
+ clock;
20943
20980
  width;
20944
20981
  height;
20945
20982
  terminalWidth;
@@ -20958,9 +20995,10 @@ class ScrollbackSnapshotRenderContext extends EventEmitter8 {
20958
20995
  isDestroyed = false;
20959
20996
  controlState = "idle" /* IDLE */;
20960
20997
  detachedSession;
20961
- constructor(width, height, widthMethod, terminalWidth, terminalHeight, resolution, capabilities, nativeOwner) {
20998
+ constructor(width, height, widthMethod, terminalWidth, terminalHeight, resolution, capabilities, nativeOwner, clock) {
20962
20999
  super();
20963
21000
  this.nativeOwner = nativeOwner;
21001
+ this.clock = clock;
20964
21002
  this.width = width;
20965
21003
  this.height = height;
20966
21004
  this.terminalWidth = terminalWidth;
@@ -21030,6 +21068,9 @@ class ScrollbackSnapshotRenderContext extends EventEmitter8 {
21030
21068
  setMousePointer(_shape) {}
21031
21069
  requestLive() {}
21032
21070
  dropLive() {}
21071
+ onAnimationTick() {
21072
+ return () => {};
21073
+ }
21033
21074
  getSelection() {
21034
21075
  return null;
21035
21076
  }
@@ -21103,6 +21144,9 @@ var KITTY_FLAG_ALL_KEYS_AS_ESCAPES = 8;
21103
21144
  var KITTY_FLAG_REPORT_TEXT = 16;
21104
21145
  var DEFAULT_STDIN_PARSER_MAX_BUFFER_BYTES = 64 * 1024 * 1024;
21105
21146
  var NATIVE_PALETTE_QUERY_SIZE = 16;
21147
+ var REPLY_BACKSTOP_MS = 5000;
21148
+ var PIXEL_QUERIES_MAX = 4;
21149
+ var DA1_REPLY = /^\x1b\[\?[\d;]*c$/;
21106
21150
  function buildKittyKeyboardFlags2(config) {
21107
21151
  if (!config) {
21108
21152
  return 0;
@@ -21226,6 +21270,7 @@ var RendererControlState2;
21226
21270
  RendererControlState["EXPLICIT_STOPPED"] = "explicit_stopped";
21227
21271
  })(RendererControlState2 ||= {});
21228
21272
  var CLICK_REPEAT_INTERVAL_MS = 500;
21273
+ var ANIMATION_TIMER_SLACK_MS = 1;
21229
21274
 
21230
21275
  class CliRenderer2 extends EventEmitter8 {
21231
21276
  static animationFrameId = 0;
@@ -21244,6 +21289,7 @@ class CliRenderer2 extends EventEmitter8 {
21244
21289
  nativeResizeWait = null;
21245
21290
  nativeKittyKeyboardFlags = 0;
21246
21291
  kittyTransportMode = "raw";
21292
+ synchronizedOutput;
21247
21293
  kittyTransportTimer = null;
21248
21294
  _lastSceneTimeMs = 0;
21249
21295
  get lastSceneTimeMs() {
@@ -21286,6 +21332,9 @@ class CliRenderer2 extends EventEmitter8 {
21286
21332
  backgroundColor = RGBA2.fromInts(0, 0, 0, 0);
21287
21333
  waitingForPixelResolution = false;
21288
21334
  pixelResolutionRequeryPending = false;
21335
+ unansweredPixelQueries = 0;
21336
+ replyBatches = [];
21337
+ replySentinel = false;
21289
21338
  clock;
21290
21339
  rendering = false;
21291
21340
  renderingCompletion = null;
@@ -21299,6 +21348,8 @@ class CliRenderer2 extends EventEmitter8 {
21299
21348
  minTargetFrameTime = 1000 / this._maxFps;
21300
21349
  immediateRerenderRequested = false;
21301
21350
  liveRequestCounter = 0;
21351
+ animationTickers = new Set;
21352
+ animationTimer = null;
21302
21353
  _controlState = "idle" /* IDLE */;
21303
21354
  frameCallbacks = [];
21304
21355
  renderStats = {
@@ -21315,6 +21366,7 @@ class CliRenderer2 extends EventEmitter8 {
21315
21366
  _resolution = null;
21316
21367
  _keyHandler;
21317
21368
  stdinParser = null;
21369
+ stdinShadow = null;
21318
21370
  oscSubscribers = new Set;
21319
21371
  hasLoggedStdinParserError = false;
21320
21372
  animationRequest = new Map;
@@ -21322,7 +21374,6 @@ class CliRenderer2 extends EventEmitter8 {
21322
21374
  cancelReadyFrame = null;
21323
21375
  resizeTimeoutId = null;
21324
21376
  pendingResizeSawDifferentSize = false;
21325
- capabilityTimeoutId = null;
21326
21377
  terminalKeepAliveTimer = null;
21327
21378
  xtVersionWaiters = new Set;
21328
21379
  splitStartupSeedTimeoutId = null;
@@ -21446,16 +21497,16 @@ Captured external output:
21446
21497
  }).catch((error) => console.error("Native scene shutdown failed:", error));
21447
21498
  }).bind(this);
21448
21499
  nativeProcessExitHandler = () => {
21449
- if (!this.nativeSession || this.nativeSession.disposed)
21450
- return;
21451
- const restored = this.nativeSession.restoreOnExit();
21500
+ const disposed = this.nativeSession.disposed;
21501
+ const restored = !disposed && this.nativeSession.restoreOnExit();
21452
21502
  try {
21503
+ this.leaveRawMode();
21453
21504
  this.destroy();
21454
21505
  if (this.flushTerminalInputOnClose)
21455
21506
  this.lib.terminalFlushInput();
21456
21507
  } finally {
21457
21508
  this.nativeSession.dispose();
21458
- if (!restored && this._terminalIsSetup) {
21509
+ if (!disposed && !restored && this._terminalIsSetup) {
21459
21510
  console.error("Native scene output cancelled at process exit; terminal restoration did not complete");
21460
21511
  }
21461
21512
  }
@@ -21476,11 +21527,11 @@ Captured external output:
21476
21527
  this.stdout = stdout;
21477
21528
  this._usesProcessStdout = stdout === process.stdout;
21478
21529
  this.realStdoutWrite = stdout.write;
21479
- const workBudget = config.nativeSceneWorkBudget;
21480
- if (workBudget !== undefined && (!Number.isInteger(workBudget) || workBudget <= 0 || workBudget > 4294967295)) {
21481
- throw new Error("nativeSceneWorkBudget must be a positive u32");
21530
+ if (config.nativeSceneWorkBudget !== undefined) {
21531
+ throw new Error("nativeSceneWorkBudget was removed: frames always paint synchronously");
21482
21532
  }
21483
21533
  this.kittyTransportMode = config.kittyImageTransport ?? "raw";
21534
+ this.synchronizedOutput = config.synchronizedOutput;
21484
21535
  const transportCode = KITTY_IMAGE_TRANSPORTS.indexOf(this.kittyTransportMode);
21485
21536
  if (transportCode < 0)
21486
21537
  throw new TypeError("Invalid kittyImageTransport");
@@ -21533,12 +21584,14 @@ Captured external output:
21533
21584
  this.nativeClosed = this.nativeSession.closed.finally(() => this.nativeDestroyWait.promise).finally(() => {
21534
21585
  if (this.nativeSession.error && !this.nativeSession.disposed)
21535
21586
  this.nativeSession.dispose();
21587
+ this.leaveRawMode();
21588
+ this.removeCleanupListener(process, "exit", this.nativeProcessExitHandler);
21536
21589
  if (this.flushTerminalInputOnClose)
21537
21590
  this.lib.terminalFlushInput();
21538
21591
  this.releaseStreamLease();
21539
21592
  });
21540
21593
  this.nativeClosed.catch(() => {});
21541
- this.nativeScene = new NativeScene(this.nativeSession, this, config.nativeSceneWorkBudget);
21594
+ this.nativeScene = new NativeScene(this.nativeSession, this);
21542
21595
  this.nativeSession.setKittyImageTransport(transportCode);
21543
21596
  } catch (error) {
21544
21597
  if (!config.nativeSession || this.nativeSession)
@@ -21623,23 +21676,42 @@ Captured external output:
21623
21676
  });
21624
21677
  this.addExitListeners();
21625
21678
  const stdinParserMaxBufferBytes = config.stdinParserMaxBufferBytes ?? DEFAULT_STDIN_PARSER_MAX_BUFFER_BYTES;
21626
- this.stdinParser = new StdinParser2({
21627
- timeoutMs: 20,
21628
- maxPendingBytes: stdinParserMaxBufferBytes,
21629
- armTimeouts: true,
21630
- onTimeoutFlush: () => {
21631
- this.drainStdinParser();
21632
- },
21633
- useKittyKeyboard: useKittyForParsing,
21634
- protocolContext: {
21679
+ const createStdinParser = (native, onTimeoutFlush) => {
21680
+ const protocolContext = {
21635
21681
  kittyKeyboardEnabled: useKittyForParsing,
21636
21682
  privateCapabilityRepliesActive: false,
21637
21683
  pixelResolutionQueryActive: false,
21638
21684
  explicitWidthCprActive: false,
21639
21685
  startupCursorCprActive: false
21640
- },
21641
- clock: this.clock
21642
- });
21686
+ };
21687
+ if (native) {
21688
+ return new NativeStdinParser({
21689
+ armTimeouts: true,
21690
+ onTimeoutFlush,
21691
+ protocolContext,
21692
+ clock: this.clock,
21693
+ session: { lib: this.lib, context: this.nativeSession.context, session: this.nativeSession.session }
21694
+ });
21695
+ }
21696
+ return new StdinParser2({
21697
+ timeoutMs: 20,
21698
+ maxPendingBytes: stdinParserMaxBufferBytes,
21699
+ armTimeouts: true,
21700
+ onTimeoutFlush,
21701
+ useKittyKeyboard: useKittyForParsing,
21702
+ protocolContext,
21703
+ clock: this.clock
21704
+ });
21705
+ };
21706
+ const nativeInput = config.experimental_nativeInput ?? env2.OTUI_NATIVE_INPUT_PARSER;
21707
+ this.stdinParser = createStdinParser(nativeInput, () => this.drainStdinParser());
21708
+ this.replySentinel = this.stdinParser instanceof NativeStdinParser;
21709
+ if (env2.OTUI_NATIVE_INPUT_SHADOW) {
21710
+ this.stdinShadow = {
21711
+ parser: createStdinParser(!nativeInput, () => this.drainStdinShadow()),
21712
+ comparator: new StdinShadowComparator(nativeInput ? "native" : "legacy", (line) => console.warn(line))
21713
+ };
21714
+ }
21643
21715
  this._console = new TerminalConsole2(this, {
21644
21716
  ...config.consoleOptions ?? {},
21645
21717
  clock: this.clock
@@ -21653,9 +21725,8 @@ Captured external output:
21653
21725
  this.stdout.write = externalOutputMode === "capture-stdout" ? this.interceptStdoutWrite : this.realStdoutWrite;
21654
21726
  this._openConsoleOnError = config.openConsoleOnError ?? true;
21655
21727
  this._onDestroy = config.onDestroy;
21656
- this.setupInput();
21657
21728
  process.on("exit", this.nativeProcessExitHandler);
21658
- this.nativeSession.closed.then(() => this.removeCleanupListener(process, "exit", this.nativeProcessExitHandler), () => this.removeCleanupListener(process, "exit", this.nativeProcessExitHandler));
21729
+ this.setupInput();
21659
21730
  this.nativeSession.closed.catch((error) => {
21660
21731
  if (this._isDestroyed)
21661
21732
  return;
@@ -22152,7 +22223,7 @@ Captured external output:
22152
22223
  const startOnNewLine = options.startOnNewLine ?? true;
22153
22224
  const tailColumn = renderer.getPendingSplitTailColumn();
22154
22225
  const firstLineOffset = !startOnNewLine && tailColumn > 0 && tailColumn < renderer.width ? tailColumn : 0;
22155
- const snapshotContext = new ScrollbackSnapshotRenderContext(renderer.width, 1, renderer.widthMethod, renderer._terminalWidth, renderer._terminalHeight, renderer.resolution, renderer.capabilities, renderer.nativeSession);
22226
+ const snapshotContext = new ScrollbackSnapshotRenderContext(renderer.width, 1, renderer.widthMethod, renderer._terminalWidth, renderer._terminalHeight, renderer.resolution, renderer.capabilities, renderer.nativeSession, renderer.clock);
22156
22227
  let firstLineOffsetOwner = null;
22157
22228
  const renderContext = Object.create(snapshotContext);
22158
22229
  Object.defineProperty(renderContext, "claimFirstLineOffset", {
@@ -22414,7 +22485,7 @@ Captured external output:
22414
22485
  if (this.screenMode !== "split-footer" || this.externalOutputMode !== "capture-stdout") {
22415
22486
  throw new Error('writeToScrollback requires screenMode "split-footer" and externalOutputMode "capture-stdout"');
22416
22487
  }
22417
- const snapshotContext = new ScrollbackSnapshotRenderContext(this.width, this.height, this.widthMethod, this._terminalWidth, this._terminalHeight, this.resolution, this.capabilities, this.nativeSession);
22488
+ const snapshotContext = new ScrollbackSnapshotRenderContext(this.width, this.height, this.widthMethod, this._terminalWidth, this._terminalHeight, this.resolution, this.capabilities, this.nativeSession, this.clock);
22418
22489
  let snapshot;
22419
22490
  let renderFailed = false;
22420
22491
  let snapshotRoot = null;
@@ -22624,7 +22695,7 @@ Captured external output:
22624
22695
  if (rows.length === 0) {
22625
22696
  return [];
22626
22697
  }
22627
- const snapshotContext = new ScrollbackSnapshotRenderContext(this.width, 1, this.widthMethod, this._terminalWidth, this._terminalHeight, this.resolution, this.capabilities, this.nativeSession);
22698
+ const snapshotContext = new ScrollbackSnapshotRenderContext(this.width, 1, this.widthMethod, this._terminalWidth, this._terminalHeight, this.resolution, this.capabilities, this.nativeSession, this.clock);
22628
22699
  const commits = [];
22629
22700
  let snapshotRoot;
22630
22701
  try {
@@ -22700,7 +22771,8 @@ Captured external output:
22700
22771
  }
22701
22772
  abortSplitStartupCursorSeed() {
22702
22773
  this.clearSplitStartupCursorSeed();
22703
- this.stdinParser?.abortPendingStartupCursorCpr();
22774
+ for (const parser of this.legacyStdinParsers())
22775
+ parser.abortPendingStartupCursorCpr();
22704
22776
  this.updateStdinParserProtocolContext({ startupCursorCprActive: false });
22705
22777
  }
22706
22778
  resetSplitScrollback(seedRows = 0) {
@@ -22931,7 +23003,8 @@ Captured external output:
22931
23003
  }
22932
23004
  this._useMouse = false;
22933
23005
  this.capturedRenderable = undefined;
22934
- this.stdinParser?.resetMouseState();
23006
+ for (const parser of this.legacyStdinParsers())
23007
+ parser.resetMouseState();
22935
23008
  }
22936
23009
  enableKittyKeyboard(flags = 3) {
22937
23010
  if (this.nativeTerminalTransition || this._controlState === "explicit_suspended" /* EXPLICIT_SUSPENDED */) {
@@ -22960,18 +23033,18 @@ Captured external output:
22960
23033
  return this.nativeTerminalTransition;
22961
23034
  const startupCursorCprActive = this._screenMode === "split-footer" && this._externalOutputMode === "capture-stdout";
22962
23035
  this.pendingSplitStartupCursorSeed = startupCursorCprActive;
22963
- this.updateStdinParserProtocolContext({
22964
- privateCapabilityRepliesActive: true,
22965
- explicitWidthCprActive: true,
22966
- startupCursorCprActive
22967
- });
23036
+ this.updateStdinParserProtocolContext({ startupCursorCprActive });
23037
+ const startup = this.admitReplyBatch("startup");
22968
23038
  try {
22969
23039
  await this.trackNativeTerminalTransition(this.nativeSession.setupTerminal({
22970
23040
  useAlternateScreen: this._screenMode === "alternate-screen",
22971
23041
  mouse: this._useMouse,
22972
23042
  mouseMovement: this.enableMouseMovement,
22973
23043
  kittyKeyboardFlags: this.nativeKittyKeyboardFlags,
22974
- clearOnClose: this.clearOnShutdown
23044
+ clearOnClose: this.clearOnShutdown,
23045
+ replySentinel: this.replySentinel,
23046
+ synchronizedOutput: this.synchronizedOutput,
23047
+ hostMultiplexer: this._usesProcessStdout && !!(process.env.TMUX || process.env.STY || process.env.ZELLIJ)
22975
23048
  }), () => {
22976
23049
  if (this._isDestroyed)
22977
23050
  return;
@@ -22982,7 +23055,7 @@ Captured external output:
22982
23055
  });
22983
23056
  } catch (error) {
22984
23057
  this.abortSplitStartupCursorSeed();
22985
- this.updateStdinParserProtocolContext({ privateCapabilityRepliesActive: false, explicitWidthCprActive: false });
23058
+ this.endReplyBatch(startup);
22986
23059
  throw error;
22987
23060
  }
22988
23061
  if (this._isDestroyed)
@@ -22995,20 +23068,7 @@ Captured external output:
22995
23068
  this.automaticMemorySnapshot = true;
22996
23069
  }
22997
23070
  }
22998
- this.capabilityTimeoutId = this.clock.setTimeout(() => {
22999
- this.capabilityTimeoutId = null;
23000
- this.clearSplitStartupCursorSeed();
23001
- if (this._screenMode === "split-footer" && this._externalOutputMode === "capture-stdout") {
23002
- this.requestRender();
23003
- }
23004
- this.removeInputHandler(this.capabilityHandler);
23005
- this.updateStdinParserProtocolContext({
23006
- privateCapabilityRepliesActive: false,
23007
- explicitWidthCprActive: false,
23008
- startupCursorCprActive: false
23009
- }, true);
23010
- this.resolveXtVersionWaiters();
23011
- }, 5000);
23071
+ this.armReplyBackstop(startup);
23012
23072
  if (this.pendingSplitStartupCursorSeed) {
23013
23073
  if (this.splitStartupSeedTimeoutId !== null) {
23014
23074
  this.clock.clearTimeout(this.splitStartupSeedTimeoutId);
@@ -23031,6 +23091,54 @@ Captured external output:
23031
23091
  this.refreshPalette();
23032
23092
  }
23033
23093
  }
23094
+ get startupRepliesPending() {
23095
+ return this.replyBatches.some((batch) => batch.kind === "startup");
23096
+ }
23097
+ admitReplyBatch(kind) {
23098
+ const batch = { kind, backstop: null, excused: this.replyBatches.some((earlier) => earlier.excused) };
23099
+ this.replyBatches.push(batch);
23100
+ this.syncReplyContext(false);
23101
+ return batch;
23102
+ }
23103
+ armReplyBackstop(batch) {
23104
+ if (!this.replyBatches.includes(batch) || batch.backstop !== null)
23105
+ return;
23106
+ if (this._controlState === "explicit_suspended" /* EXPLICIT_SUSPENDED */)
23107
+ return;
23108
+ batch.backstop = this.clock.setTimeout(() => {
23109
+ batch.backstop = null;
23110
+ const pasting = this.stdinParser instanceof NativeStdinParser && this.stdinParser.pasting;
23111
+ this.replySentinel &&= batch.excused || pasting;
23112
+ this.endReplyBatch(batch);
23113
+ }, REPLY_BACKSTOP_MS);
23114
+ }
23115
+ endReplyBatch(batch) {
23116
+ const index = this.replyBatches.indexOf(batch);
23117
+ if (index < 0)
23118
+ return;
23119
+ this.replyBatches.splice(index, 1);
23120
+ if (batch.backstop !== null)
23121
+ this.clock.clearTimeout(batch.backstop);
23122
+ if (batch.kind === "startup") {
23123
+ this.clearSplitStartupCursorSeed();
23124
+ if (this._screenMode === "split-footer" && this._externalOutputMode === "capture-stdout")
23125
+ this.requestRender();
23126
+ this.resolveXtVersionWaiters();
23127
+ } else if (!this.replyBatches.some((other) => other.kind === "pixel")) {
23128
+ this.waitingForPixelResolution = false;
23129
+ }
23130
+ this.syncReplyContext(true);
23131
+ }
23132
+ syncReplyContext(drain) {
23133
+ const startup = this.startupRepliesPending;
23134
+ this.updateStdinParserProtocolContext({
23135
+ privateCapabilityRepliesActive: startup,
23136
+ explicitWidthCprActive: startup,
23137
+ ...startup ? {} : { startupCursorCprActive: false },
23138
+ pixelResolutionQueryActive: this.waitingForPixelResolution,
23139
+ replySentinelActive: this.replySentinel && this.replyBatches.length > 0
23140
+ }, drain);
23141
+ }
23034
23142
  trackNativeTerminalTransition(transition, complete) {
23035
23143
  const tracked = transition.then(() => complete?.()).finally(() => {
23036
23144
  if (this.nativeTerminalTransition === tracked)
@@ -23060,6 +23168,12 @@ Captured external output:
23060
23168
  } catch (error) {
23061
23169
  this.handleStdinParserFailure(error);
23062
23170
  }
23171
+ try {
23172
+ this.stdinShadow?.parser.push(data);
23173
+ this.drainStdinShadow();
23174
+ } catch (error) {
23175
+ console.warn("[stdin-shadow] parser failure", error);
23176
+ }
23063
23177
  }).bind(this);
23064
23178
  addInputHandler(handler) {
23065
23179
  this.sequenceHandlers.push(handler);
@@ -23074,8 +23188,13 @@ Captured external output:
23074
23188
  if (!this.stdinParser)
23075
23189
  return;
23076
23190
  this.stdinParser.updateProtocolContext(patch);
23191
+ this.stdinShadow?.parser.updateProtocolContext(patch);
23077
23192
  if (drain)
23078
23193
  this.drainStdinParser();
23194
+ this.drainStdinShadow();
23195
+ }
23196
+ legacyStdinParsers() {
23197
+ return [this.stdinParser, this.stdinShadow?.parser].filter((parser) => parser instanceof StdinParser2);
23079
23198
  }
23080
23199
  subscribeOsc(handler) {
23081
23200
  this.oscSubscribers.add(handler);
@@ -23084,8 +23203,8 @@ Captured external output:
23084
23203
  };
23085
23204
  }
23086
23205
  processCapabilitySequence(sequence, hasCursorReport) {
23087
- const hasStandardCapabilitySignature = isCapabilityResponse(sequence);
23088
- const shouldProcessAsCapability = hasStandardCapabilitySignature || hasCursorReport && (this.capabilityTimeoutId !== null || this.nativeTerminalTransition !== null);
23206
+ const hasStandardCapabilitySignature = isCapabilityResponse(sequence) || hasCursorReport && isExplicitWidthReport(sequence);
23207
+ const shouldProcessAsCapability = hasStandardCapabilitySignature || hasCursorReport && (this.startupRepliesPending || this.nativeTerminalTransition !== null);
23089
23208
  if (!shouldProcessAsCapability) {
23090
23209
  return false;
23091
23210
  }
@@ -23096,15 +23215,16 @@ Captured external output:
23096
23215
  throw error;
23097
23216
  return error.status !== -19 /* InvalidPhase */;
23098
23217
  }
23218
+ const previous = JSON.stringify(this._capabilities);
23099
23219
  this._capabilities = this.nativeSession.getCapabilities();
23100
23220
  if (this._capabilities?.terminal?.from_xtversion) {
23101
23221
  this.resolveXtVersionWaiters();
23102
23222
  }
23103
- if (hasStandardCapabilitySignature) {
23223
+ if (JSON.stringify(this._capabilities) !== previous) {
23104
23224
  this.forceFullRepaintRequested = true;
23105
23225
  this.requestRender();
23226
+ this.emit("capabilities" /* CAPABILITIES */, this._capabilities);
23106
23227
  }
23107
- this.emit("capabilities" /* CAPABILITIES */, this._capabilities);
23108
23228
  const hadPendingSplitStartupCursorSeed = this.pendingSplitStartupCursorSeed;
23109
23229
  if (hadPendingSplitStartupCursorSeed && hasCursorReport && this._screenMode === "split-footer" && this._externalOutputMode === "capture-stdout") {
23110
23230
  this.resetSplitScrollback(this.getSplitCursorSeedRows());
@@ -23159,9 +23279,14 @@ Captured external output:
23159
23279
  if (!this.stdinParser)
23160
23280
  return;
23161
23281
  this.stdinParser.drain((event) => {
23282
+ this.stdinShadow?.comparator.primary(event);
23162
23283
  this.handleStdinEvent(event);
23163
23284
  });
23164
23285
  }
23286
+ drainStdinShadow() {
23287
+ const shadow = this.stdinShadow;
23288
+ shadow?.parser.drain((event) => shadow.comparator.shadow(event));
23289
+ }
23165
23290
  handleStdinEvent(event) {
23166
23291
  if (event.type === "response" && event.sequence.startsWith("\x1B_G")) {
23167
23292
  try {
@@ -23177,6 +23302,13 @@ Captured external output:
23177
23302
  }
23178
23303
  }
23179
23304
  }
23305
+ if (event.type === "response" && this.replySentinel && this.replyBatches.length > 0 && DA1_REPLY.test(event.sequence)) {
23306
+ const batch = this.replyBatches[0];
23307
+ this.endReplyBatch(batch);
23308
+ if (batch.kind === "startup")
23309
+ this.processCapabilitySequence(event.sequence, false);
23310
+ return;
23311
+ }
23180
23312
  if (this._controlState === "explicit_suspended" /* EXPLICIT_SUSPENDED */) {
23181
23313
  if (event.type === "response" && isPixelResolutionResponse(event.sequence)) {
23182
23314
  this.dispatchSequenceHandlers(event.sequence);
@@ -23197,6 +23329,8 @@ Captured external output:
23197
23329
  this.dispatchSequenceHandlers(event.raw);
23198
23330
  return;
23199
23331
  case "paste":
23332
+ for (const batch of this.replyBatches)
23333
+ batch.excused = true;
23200
23334
  this._keyHandler.processPaste(event.bytes, event.metadata);
23201
23335
  return;
23202
23336
  case "response":
@@ -23221,6 +23355,7 @@ Captured external output:
23221
23355
  }
23222
23356
  try {
23223
23357
  this.stdinParser?.reset();
23358
+ this.stdinShadow?.parser.reset();
23224
23359
  } catch (resetError) {
23225
23360
  console.error("stdin parser reset failed after parser error", resetError);
23226
23361
  }
@@ -23233,26 +23368,26 @@ Captured external output:
23233
23368
  this.addInputHandler(handler);
23234
23369
  }
23235
23370
  this.addInputHandler((sequence) => {
23236
- if (isPixelResolutionResponse(sequence) && this.waitingForPixelResolution) {
23237
- this.waitingForPixelResolution = false;
23238
- if (this.pixelResolutionRequeryPending) {
23239
- this.updateStdinParserProtocolContext({ pixelResolutionQueryActive: false });
23240
- this.queryPixelResolution();
23241
- return true;
23242
- }
23243
- try {
23244
- const resolution = parsePixelResolution(sequence);
23245
- if (resolution) {
23246
- this.lib.sessionSetImageResolution(this.nativeSession.context, this.nativeSession.session, this._terminalWidth, this._terminalHeight, resolution.width, resolution.height);
23247
- this._resolution = resolution;
23248
- this.requestRender();
23249
- }
23250
- } finally {
23251
- this.updateStdinParserProtocolContext({ pixelResolutionQueryActive: false }, true);
23252
- }
23371
+ if (!isPixelResolutionResponse(sequence) || this.unansweredPixelQueries === 0)
23372
+ return false;
23373
+ this.unansweredPixelQueries--;
23374
+ this.waitingForPixelResolution = false;
23375
+ if (this.pixelResolutionRequeryPending) {
23376
+ this.syncReplyContext(false);
23377
+ this.queryPixelResolution();
23253
23378
  return true;
23254
23379
  }
23255
- return false;
23380
+ try {
23381
+ const resolution = parsePixelResolution(sequence);
23382
+ if (resolution) {
23383
+ this.lib.sessionSetImageResolution(this.nativeSession.context, this.nativeSession.session, this._terminalWidth, this._terminalHeight, resolution.width, resolution.height);
23384
+ this._resolution = resolution;
23385
+ this.requestRender();
23386
+ }
23387
+ } finally {
23388
+ this.syncReplyContext(true);
23389
+ }
23390
+ return true;
23256
23391
  });
23257
23392
  this.addInputHandler(this.capabilityHandler);
23258
23393
  this.addInputHandler(this.focusHandler);
@@ -23563,17 +23698,16 @@ Captured external output:
23563
23698
  pixelResolutionRetry = null;
23564
23699
  queryPixelResolution(retry = true) {
23565
23700
  this.pixelResolutionRequeryPending = true;
23566
- if (this._isDestroyed || !this._terminalIsSetup || this._controlState === "explicit_suspended" /* EXPLICIT_SUSPENDED */ || this.waitingForPixelResolution || this.pixelResolutionRetry)
23701
+ if (this._isDestroyed || !this._terminalIsSetup || this._controlState === "explicit_suspended" /* EXPLICIT_SUSPENDED */ || this.waitingForPixelResolution || this.unansweredPixelQueries >= PIXEL_QUERIES_MAX || this.pixelResolutionRetry)
23567
23702
  return;
23568
- this.pixelResolutionRequeryPending = false;
23569
- this.waitingForPixelResolution = true;
23570
- this.updateStdinParserProtocolContext({ pixelResolutionQueryActive: true });
23571
23703
  try {
23572
- this.nativeSession.control({ kind: "query-pixel-resolution" });
23704
+ this.nativeSession.control({ kind: "query-pixel-resolution", sentinel: this.replySentinel });
23705
+ this.pixelResolutionRequeryPending = false;
23706
+ this.waitingForPixelResolution = true;
23707
+ this.unansweredPixelQueries++;
23708
+ const batch = this.admitReplyBatch("pixel");
23709
+ this.nativeSession.idle().then(() => this.armReplyBackstop(batch), () => {});
23573
23710
  } catch (error) {
23574
- this.waitingForPixelResolution = false;
23575
- this.pixelResolutionRequeryPending = true;
23576
- this.updateStdinParserProtocolContext({ pixelResolutionQueryActive: false });
23577
23711
  if (!(error instanceof NativeError2))
23578
23712
  throw error;
23579
23713
  if (error.status === -19 /* InvalidPhase */)
@@ -23635,9 +23769,6 @@ Captured external output:
23635
23769
  else {
23636
23770
  this.nativeSession.setScreen(this._screenMode === "alternate-screen", nextGeometry.renderWidth, nextGeometry.renderHeight, this.lib.encoder.encode(ANSI.moveCursorAndClear(clearStart, 1)));
23637
23771
  }
23638
- if (nextGeometry.renderWidth !== this.width || nextGeometry.renderHeight !== this.height) {
23639
- this.nativeScene.restartPaint();
23640
- }
23641
23772
  this._terminalWidth = width;
23642
23773
  this._terminalHeight = height;
23643
23774
  this._splitHeight = nextGeometry.effectiveFooterHeight;
@@ -23646,7 +23777,8 @@ Captured external output:
23646
23777
  this._resolution = null;
23647
23778
  this.lib.sessionSetImageResolution(this.nativeSession.context, this.nativeSession.session, 0, 0, 0, 0);
23648
23779
  this.capturedRenderable = undefined;
23649
- this.stdinParser?.resetMouseState();
23780
+ for (const parser of this.legacyStdinParsers())
23781
+ parser.resetMouseState();
23650
23782
  if (splitFooterActive) {
23651
23783
  this.forceFullRepaintRequested = true;
23652
23784
  }
@@ -23804,6 +23936,64 @@ Captured external output:
23804
23936
  if (this.animationRequest.delete(handle))
23805
23937
  this.dropLive();
23806
23938
  }
23939
+ onAnimationTick(fps, callback, options = {}) {
23940
+ const interval = 1000 / fps;
23941
+ const { tolerance } = options;
23942
+ if (!(interval > 0 && interval < Infinity))
23943
+ throw new RangeError(`fps must be positive and finite, got ${fps}`);
23944
+ if (tolerance !== undefined && !(tolerance >= 0 && tolerance < interval)) {
23945
+ throw new RangeError(`tolerance must be at least 0 and below the interval (${interval} ms), got ${tolerance}`);
23946
+ }
23947
+ if (this._isDestroyed)
23948
+ return () => {};
23949
+ const now = this.clock.now();
23950
+ const window = Math.max(tolerance === undefined ? 500 : tolerance * fps, ANIMATION_TIMER_SLACK_MS * fps);
23951
+ const ticker = { fps, window, next: Math.floor((now * fps + window) / 1000) + 1, last: now, callback };
23952
+ this.animationTickers.add(ticker);
23953
+ this.scheduleAnimationTick();
23954
+ return () => {
23955
+ if (this.animationTickers.delete(ticker))
23956
+ this.scheduleAnimationTick();
23957
+ };
23958
+ }
23959
+ scheduleAnimationTick() {
23960
+ if (this.animationTimer !== null)
23961
+ this.clock.clearTimeout(this.animationTimer);
23962
+ this.animationTimer = null;
23963
+ let fastest = 0;
23964
+ for (const ticker of this.animationTickers)
23965
+ fastest = Math.max(fastest, ticker.fps);
23966
+ let due = Infinity;
23967
+ for (const ticker of this.animationTickers) {
23968
+ const late = ticker.fps === fastest ? 0 : ticker.window;
23969
+ due = Math.min(due, (ticker.next * 1000 + late) / ticker.fps);
23970
+ }
23971
+ if (due === Infinity)
23972
+ return;
23973
+ this.animationTimer = this.clock.setTimeout(() => {
23974
+ this.animationTimer = null;
23975
+ this.requestRender();
23976
+ }, Math.max(0, due - this.clock.now()));
23977
+ }
23978
+ runAnimationTicks(time) {
23979
+ if (this.animationTickers.size === 0)
23980
+ return;
23981
+ for (const ticker of this.animationTickers) {
23982
+ const reach = Math.floor((time * ticker.fps + ticker.window) / 1000);
23983
+ if (reach < ticker.next)
23984
+ continue;
23985
+ const ticks = reach + 1 - ticker.next;
23986
+ const deltaTime = Math.max(0, time - ticker.last);
23987
+ ticker.next = reach + 1;
23988
+ ticker.last = time;
23989
+ try {
23990
+ ticker.callback(deltaTime, ticks, time);
23991
+ } catch (error) {
23992
+ console.error("Error in animation tick callback:", error);
23993
+ }
23994
+ }
23995
+ this.scheduleAnimationTick();
23996
+ }
23807
23997
  yieldFrame() {
23808
23998
  if (!this.canRender)
23809
23999
  return Promise.resolve();
@@ -23913,21 +24103,20 @@ Captured external output:
23913
24103
  this._controlState = "explicit_suspended" /* EXPLICIT_SUSPENDED */;
23914
24104
  this._cancelPaletteDetection?.(new Error("Cannot detect palette while renderer is suspended"));
23915
24105
  this.resolveXtVersionWaiters();
23916
- this.nativeScene.interruptPaint();
23917
24106
  this.halt(false);
23918
24107
  this.clearSplitStartupCursorSeed();
23919
24108
  this.disableMouse();
23920
24109
  this.removeExitListeners();
23921
- this.updateStdinParserProtocolContext({
23922
- privateCapabilityRepliesActive: false,
23923
- pixelResolutionQueryActive: this.waitingForPixelResolution,
23924
- explicitWidthCprActive: false,
23925
- startupCursorCprActive: false
23926
- });
23927
- if (this.stdinParser?.hasPendingPixelResolutionResponse())
23928
- this.stdinParser.pausePendingTimeout();
23929
- else
23930
- this.stdinParser?.reset();
24110
+ for (const batch of [...this.replyBatches]) {
24111
+ if (batch.backstop !== null)
24112
+ this.clock.clearTimeout(batch.backstop);
24113
+ batch.backstop = null;
24114
+ batch.excused = true;
24115
+ if (!this.replySentinel && batch.kind === "startup")
24116
+ this.endReplyBatch(batch);
24117
+ }
24118
+ this.updateStdinParserProtocolContext({ startupCursorCprActive: false }, true);
24119
+ this.pauseStdinParsers(false);
23931
24120
  this.stdin.removeListener("data", this.stdinListener);
23932
24121
  this.stopTerminalKeepAlive();
23933
24122
  this.themeModeState?.cancelRefresh();
@@ -23938,7 +24127,7 @@ Captured external output:
23938
24127
  return nativeTransition;
23939
24128
  }
23940
24129
  resume() {
23941
- if (!this._terminalIsSetup || this.nativeTerminalTransition || this._controlState !== "explicit_suspended" /* EXPLICIT_SUSPENDED */) {
24130
+ if (!this._terminalIsSetup || this._isDestroyed || this.nativeTerminalTransition || this._controlState !== "explicit_suspended" /* EXPLICIT_SUSPENDED */) {
23942
24131
  throw new Error("Native scene resume requires completed suspension");
23943
24132
  }
23944
24133
  if (this.pendingSplitFooterTransition) {
@@ -23946,6 +24135,12 @@ Captured external output:
23946
24135
  kind: "clear-transition"
23947
24136
  });
23948
24137
  }
24138
+ try {
24139
+ this.stdin.setRawMode?.(true);
24140
+ } catch (error) {
24141
+ return Promise.reject(error);
24142
+ }
24143
+ this.addExitListeners();
23949
24144
  const resumed = this.trackNativeTerminalTransition(this.nativeSession.resume(), () => {
23950
24145
  if (this._isDestroyed)
23951
24146
  return;
@@ -23961,21 +24156,29 @@ Captured external output:
23961
24156
  resumed.catch(() => {});
23962
24157
  return resumed;
23963
24158
  }
23964
- finishResume() {
23965
- if (this.stdin.setRawMode) {
23966
- this.stdin.setRawMode(true);
24159
+ pauseStdinParsers(resuming) {
24160
+ for (const parser of [this.stdinParser, this.stdinShadow?.parser]) {
24161
+ if (parser instanceof NativeStdinParser)
24162
+ resuming ? parser.resume() : parser.suspend();
24163
+ else if (parser?.hasPendingPixelResolutionResponse())
24164
+ parser.pausePendingTimeout();
24165
+ else
24166
+ parser?.reset();
23967
24167
  }
24168
+ }
24169
+ finishResume() {
23968
24170
  let drained;
23969
24171
  while ((drained = this.stdin.read()) !== null)
23970
24172
  this.stdinListener(drained);
23971
- if (this.stdinParser?.hasPendingPixelResolutionResponse())
23972
- this.stdinParser.pausePendingTimeout();
23973
- else
23974
- this.stdinParser?.reset();
24173
+ this.updateStdinParserProtocolContext({
24174
+ privateCapabilityRepliesActive: false,
24175
+ explicitWidthCprActive: false,
24176
+ replySentinelActive: false
24177
+ }, true);
24178
+ this.pauseStdinParsers(true);
23975
24179
  this.stdin.on("data", this.stdinListener);
23976
24180
  this.stdin.resume();
23977
24181
  this.startTerminalKeepAlive();
23978
- this.addExitListeners();
23979
24182
  this._useMouse = this._suspendedMouseEnabled;
23980
24183
  if (this._screenMode === "split-footer" && this._splitHeight > 0) {
23981
24184
  this.syncSplitFooterState();
@@ -23984,9 +24187,13 @@ Captured external output:
23984
24187
  this.startKittyTransportPolling();
23985
24188
  this.nativeSession.startKittyFileProbe();
23986
24189
  this._controlState = this._previousControlState;
24190
+ for (const batch of this.replyBatches)
24191
+ this.armReplyBackstop(batch);
24192
+ this.syncReplyContext(false);
23987
24193
  if (this.pixelResolutionRequeryPending)
23988
24194
  this.queryPixelResolution();
23989
- this.stdinParser?.resumePendingTimeout();
24195
+ for (const parser of this.legacyStdinParsers())
24196
+ parser.resumePendingTimeout();
23990
24197
  this.applyPendingNativeResize();
23991
24198
  if (this._previousControlState === "auto_started" /* AUTO_STARTED */ || this._previousControlState === "explicit_started" /* EXPLICIT_STARTED */) {
23992
24199
  this.internalStart();
@@ -24057,6 +24264,8 @@ Captured external output:
24057
24264
  this.animationRequest.clear();
24058
24265
  this.frameCallbacks = [];
24059
24266
  this.liveRequestCounter = 0;
24267
+ this.animationTickers.clear();
24268
+ this.scheduleAnimationTick();
24060
24269
  this.immediateRerenderRequested = false;
24061
24270
  if (this._usesProcessStdout) {
24062
24271
  this.removeCleanupListener(process, "SIGWINCH", this.sigwinchHandler);
@@ -24069,10 +24278,11 @@ Captured external output:
24069
24278
  this.clock.clearTimeout(this.resizeTimeoutId);
24070
24279
  this.resizeTimeoutId = null;
24071
24280
  }
24072
- if (this.capabilityTimeoutId !== null) {
24073
- this.clock.clearTimeout(this.capabilityTimeoutId);
24074
- this.capabilityTimeoutId = null;
24281
+ for (const batch of this.replyBatches) {
24282
+ if (batch.backstop !== null)
24283
+ this.clock.clearTimeout(batch.backstop);
24075
24284
  }
24285
+ this.replyBatches = [];
24076
24286
  this.clearSplitStartupCursorSeed();
24077
24287
  if (this.memorySnapshotTimer) {
24078
24288
  this.clock.clearInterval(this.memorySnapshotTimer);
@@ -24084,12 +24294,7 @@ Captured external output:
24084
24294
  this.waitingForPixelResolution = false;
24085
24295
  this.pixelResolutionRequeryPending = false;
24086
24296
  try {
24087
- this.updateStdinParserProtocolContext({
24088
- privateCapabilityRepliesActive: false,
24089
- pixelResolutionQueryActive: false,
24090
- explicitWidthCprActive: false,
24091
- startupCursorCprActive: false
24092
- }, true);
24297
+ this.syncReplyContext(true);
24093
24298
  } catch (error) {
24094
24299
  this.handleStdinParserFailure(error);
24095
24300
  }
@@ -24097,13 +24302,6 @@ Captured external output:
24097
24302
  this.capturedRenderable = undefined;
24098
24303
  this.removeCleanupListener(this.stdin, "data", this.stdinListener);
24099
24304
  this.stopTerminalKeepAlive();
24100
- if (this.stdin.setRawMode) {
24101
- try {
24102
- this.stdin.setRawMode(false);
24103
- } catch (e) {
24104
- console.error("Error disabling raw mode during destroy:", e);
24105
- }
24106
- }
24107
24305
  try {
24108
24306
  this.stdin.pause();
24109
24307
  } catch (e) {
@@ -24159,6 +24357,9 @@ Captured external output:
24159
24357
  }
24160
24358
  this.stdinParser?.destroy();
24161
24359
  this.stdinParser = null;
24360
+ this.stdinShadow?.parser.destroy();
24361
+ this.stdinShadow?.comparator.flush();
24362
+ this.stdinShadow = null;
24162
24363
  this.oscSubscribers.clear();
24163
24364
  try {
24164
24365
  this._console?.destroy();
@@ -24196,6 +24397,13 @@ Captured external output:
24196
24397
  this.nativeDestroyWait?.resolve();
24197
24398
  this.resolveIdleIfNeeded();
24198
24399
  }
24400
+ leaveRawMode() {
24401
+ try {
24402
+ this.stdin.setRawMode?.(false);
24403
+ } catch (e) {
24404
+ console.error("Error disabling raw mode:", e);
24405
+ }
24406
+ }
24199
24407
  releaseStreamLease() {
24200
24408
  if (!this._streamLeaseAcquired)
24201
24409
  return;
@@ -24246,6 +24454,9 @@ Captured external output:
24246
24454
  this.lastTime = now;
24247
24455
  this.renderStats.frameCount++;
24248
24456
  const overallStart = performance.now();
24457
+ const requestedBeforeTicks = this.immediateRerenderRequested;
24458
+ this.runAnimationTicks(now);
24459
+ this.immediateRerenderRequested = requestedBeforeTicks;
24249
24460
  const animationFrameEnd = CliRenderer2.animationFrameId;
24250
24461
  const animationRequestStart = performance.now();
24251
24462
  for (const [id, callback] of this.animationRequest) {
@@ -24288,13 +24499,11 @@ Captured external output:
24288
24499
  const sceneStart = performance.now();
24289
24500
  const requestedBeforeScene = this.immediateRerenderRequested;
24290
24501
  try {
24291
- const painting = this.nativeScene.paint(deltaTime, () => ({
24502
+ this.nativeScene.paint(deltaTime, () => ({
24292
24503
  background: this.backgroundColor,
24293
24504
  useMouse: this._useMouse,
24294
24505
  excludedHitNum: this.capturedRenderable?.num ?? 0
24295
24506
  }));
24296
- if (painting)
24297
- await painting;
24298
24507
  } catch (error) {
24299
24508
  this.immediateRerenderRequested = requestedBeforeScene;
24300
24509
  throw error;
@@ -24742,7 +24951,7 @@ Captured external output:
24742
24951
  }
24743
24952
  }
24744
24953
  waitForXtVersion() {
24745
- if (this.capabilityTimeoutId === null || this._capabilities?.terminal?.from_xtversion) {
24954
+ if (!this.startupRepliesPending || this._capabilities?.terminal?.from_xtversion) {
24746
24955
  return Promise.resolve();
24747
24956
  }
24748
24957
  return new Promise((resolve) => {
@@ -24880,7 +25089,7 @@ Captured external output:
24880
25089
  }
24881
25090
  }
24882
25091
 
24883
- export { isValidBorderStyle2, parseBorderStyle2, BorderChars2, getBorderFromSides2, getBorderSides2, borderCharsToArray2, BorderCharArrays2, KeyEvent2, PasteEvent2, KeyHandler2, InternalKeyHandler2, fonts2, measureText2, getCharacterPositions2, coordinateToCharacterIndex2, renderFontToFrameBuffer2, convertThemeToStyles2, SyntaxStyle2, hastToStyledText2, SystemClock2, nonAlphanumericKeys2, terminalNamedSingleStrokeKeys2, parseKeypress2, LinearScrollAccel2, MacOSScrollAccel2, parseAlign2, parseAlignItems2, parseBoxSizing2, parseDimension2, parseDirection2, parseDisplay2, parseEdge2, parseFlexDirection2, parseGutter2, parseJustify2, parseLogLevel2, parseMeasureMode2, parseOverflow2, parsePositionType2, parseUnit2, parseWrap2, MouseParser2, Selection2, convertGlobalToLocalSelection2, ASCIIFontSelectionHelper2, StdinParser2, addDefaultParsers2, TreeSitterClient2, treeSitterToTextChunks2, treeSitterToStyledText2, DataPathsManager2, getDataPaths2, extensionToFiletype2, basenameToFiletype2, extToFiletype2, pathToFiletype2, infoStringToFiletype2, getTreeSitterClient2, destroyTreeSitterClient2, ExtmarksController2, createExtmarksController2, TerminalPalette2, createTerminalPalette2, normalizeTerminalPalette2, buildTerminalPaletteSignature2, decodePasteBytes2, stripAnsiSequences2, createHostClipboard2, createClipboard2, ClipboardTarget2, createRendererClipboardAdapter2, normalizeMarkdownLinkTarget, detectLinks2, acquireSessionBufferLease2, ResourceContext2, OptimizedBuffer2, h2, isVNode2, maybeMakeRenderable2, wrapWithDelegates2, instantiate2, delegate2, LayoutEvents2, RenderableEvents2, isRenderable2, BaseRenderable2, Renderable2, RootRenderable2, TextBuffer2, TextBufferView2, EditBuffer2, measureEditText2, EditorView2, Timeline2, engine2, getTimelineEngine2, createTimeline2, ANSI, BoxRenderable2, TextBufferRenderable2, CodeRenderable2, ImageLoadError2, ImageError2, imageInfo2, NativeImage2, NativeImagePool2, resolveImageRenderProtocol2, ImageRenderable2, isTextNodeRenderable2, TextNodeRenderable2, RootTextNodeRenderable2, TextRenderable2, NativeSession2, defaultKeyAliases, mergeKeyAliases, mergeKeyBindings, getKeyBindingAction, buildKeyBindingsMap, capture2, ConsolePosition2, TerminalConsole2, EditBufferRenderableEvents2, isEditBufferRenderable2, EditBufferRenderable2, buildKittyKeyboardFlags2, MouseEvent2, MouseButton2, createCliRenderer2, CliRenderEvents2, RendererControlState2, CliRenderer2 };
25092
+ export { isValidBorderStyle2, parseBorderStyle2, BorderChars2, getBorderFromSides2, getBorderSides2, borderCharsToArray2, BorderCharArrays2, KeyEvent2, PasteEvent2, KeyHandler2, InternalKeyHandler2, fonts2, measureText2, getCharacterPositions2, coordinateToCharacterIndex2, renderFontToFrameBuffer2, hastToStyledText2, SystemClock2, nonAlphanumericKeys2, terminalNamedSingleStrokeKeys2, parseKeypress2, LinearScrollAccel2, MacOSScrollAccel2, parseAlign2, parseAlignItems2, parseBoxSizing2, parseDimension2, parseDirection2, parseDisplay2, parseEdge2, parseFlexDirection2, parseGutter2, parseJustify2, parseLogLevel2, parseMeasureMode2, parseOverflow2, parsePositionType2, parseUnit2, parseWrap2, MouseParser2, Selection2, convertGlobalToLocalSelection2, ASCIIFontSelectionHelper2, StdinParser2, addDefaultParsers2, TreeSitterClient2, treeSitterToTextChunks2, treeSitterToStyledText2, DataPathsManager2, getDataPaths2, extensionToFiletype2, basenameToFiletype2, extToFiletype2, pathToFiletype2, infoStringToFiletype2, getTreeSitterClient2, destroyTreeSitterClient2, ExtmarksController2, createExtmarksController2, TerminalPalette2, createTerminalPalette2, normalizeTerminalPalette2, buildTerminalPaletteSignature2, decodePasteBytes2, stripAnsiSequences2, createHostClipboard2, createClipboard2, ClipboardTarget2, createRendererClipboardAdapter2, normalizeMarkdownLinkTarget, detectLinks2, acquireSessionBufferLease2, ResourceContext2, OptimizedBuffer2, h2, isVNode2, maybeMakeRenderable2, wrapWithDelegates2, instantiate2, delegate2, LayoutEvents2, RenderableEvents2, isRenderable2, BaseRenderable2, Renderable2, RootRenderable2, TextBuffer2, TextBufferView2, EditBuffer2, measureEditText2, EditorView2, Timeline2, engine2, getTimelineEngine2, createTimeline2, ANSI, BoxRenderable2, wheelDirection, scrollOnce, TextBufferRenderable2, CodeRenderable2, ImageLoadError2, ImageError2, imageInfo2, NativeImage2, NativeImagePool2, resolveImageRenderProtocol2, ImageRenderable2, isTextNodeRenderable2, TextNodeRenderable2, RootTextNodeRenderable2, TextRenderable2, NativeSession2, defaultKeyAliases, mergeKeyAliases, mergeKeyBindings, getKeyBindingAction, buildKeyBindingsMap, capture2, ConsolePosition2, TerminalConsole2, EditBufferRenderableEvents2, isEditBufferRenderable2, EditBufferRenderable2, buildKittyKeyboardFlags2, MouseEvent2, MouseButton2, createCliRenderer2, CliRenderEvents2, RendererControlState2, CliRenderer2 };
24884
25093
 
24885
- //# debugId=BD523FD85534305364756E2164756E21
24886
- //# sourceMappingURL=chunk-node-yyjd8p1g.js.map
25094
+ //# debugId=F010F97393855BC764756E2164756E21
25095
+ //# sourceMappingURL=chunk-node-q5ccgbk5.js.map