-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathVT100ScreenTests.swift
More file actions
2360 lines (1875 loc) · 83.5 KB
/
Copy pathVT100ScreenTests.swift
File metadata and controls
2360 lines (1875 loc) · 83.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// VT100ScreenTests.swift
// iTerm2
//
// Created by George Nachman on 5/10/25.
//
import XCTest
@testable import iTerm2SharedARC
class VT100ScreenTests: XCTestCase {
private var session = FakeSession()
private func fiveByFourScreenWithThreeLinesOneWrapped() -> VT100Screen {
let screen = VT100Screen()
session.screen = screen
screen.delegate = session
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState?.terminalEnabled = true
screen.destructivelySetScreenWidth(5, height: 4, mutableState: mutableState)
mutableState!.appendString(atCursor: "abcdefgh")
mutableState!.appendCarriageReturnLineFeed()
mutableState!.appendString(atCursor: "ijkl")
mutableState!.appendCarriageReturnLineFeed()
})
return screen
}
private func fiveByNineScreenWithEmptyLineAtTop() -> VT100Screen {
let screen = VT100Screen()
session.screen = screen
screen.delegate = session
screen.performBlock(joinedThreads: { terminal, mutableState, _ in
mutableState!.terminalEnabled = true
mutableState!.terminal!.termType = "xterm"
screen.destructivelySetScreenWidth(5, height: 9, mutableState: mutableState)
mutableState!.maxScrollbackLines = 10;
for line in ["", "abcdefgh", "", "ijkl"] {
mutableState!.appendString(atCursor: line)
mutableState!.appendCarriageReturnLineFeed()
}
})
XCTAssertEqual(screen.compactLineDumpWithHistory()!,
".....\n" +
"abcde\n" +
"fgh..\n" +
".....\n" +
"ijkl.\n" +
".....\n" +
".....\n" +
".....\n" +
".....")
return screen;
}
func testResizeNotes() {
// Put a note on the primary grid, switch to alt, resize width, swap back to primary. Note should
// still be there.
let screen = fiveByFourScreenWithThreeLinesOneWrapped()
XCTAssertEqual(screen.immutableState.currentGrid.compactLineDump(),
"abcde\n" +
"fgh..\n" +
"ijkl.\n" +
".....");
let note = PTYAnnotation()
screen.addNote(note, in: VT100GridCoordRangeMake(0, 1, 2, 1), focus: false, visible: false)
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState!.showAltBuffer()
})
screen.size = VT100GridSizeMake(4, 4)
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState!.showPrimaryBuffer()
})
XCTAssertEqual(screen.immutableState.currentGrid.compactLineDump(),
"abcd\n" +
"efgh\n" +
"ijkl\n" +
"....");
let notes = screen.annotations(in: VT100GridCoordRangeMake(0, 0, 5, 3))!
XCTAssertEqual(notes.count, 1)
XCTAssertTrue(notes[0].progenitor === note)
let range = screen.coordRange(ofAnnotation: note)
XCTAssertEqual(range, VT100GridCoordRangeMake(1, 1, 3, 1))
}
private func screen(width: Int32, height: Int32) -> VT100Screen {
let screen = VT100Screen()
session.screen = screen
screen.delegate = session
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState?.terminalEnabled = true
mutableState!.terminal!.termType = "xterm"
screen.destructivelySetScreenWidth(width, height: height, mutableState: mutableState)
})
return screen
}
private func setSelectionRange(_ selectionRange: VT100GridCoordRange, width: Int32) {
session.selection.clear()
let theRange = VT100GridWindowedRangeMake(selectionRange, 0, 0)
let theSub =
iTermSubSelection.init(absRange: VT100GridAbsWindowedRangeFromRelative(theRange, 0),
mode: .kiTermSelectionModeCharacter,
width: width)
session.selection.add(theSub)
}
private func appendLinesNoNewline(_ lines: [String], screen: VT100Screen) {
screen.performBlock(joinedThreads: { _, mutableState, _ in
for (i, line) in lines.enumerated() {
mutableState?.appendString(atCursor: line)
if i + 1 != lines.count {
mutableState?.appendCarriageReturnLineFeed()
}
}
})
}
func testResizeNoteInPrimaryWhileInAltAndSomeHistory() {
// Put a note on the primary grid, switch to alt, resize width, swap back to primary. Note should
// still be there.
let screen = fiveByFourScreenWithThreeLinesOneWrapped()
appendLinesNoNewline([ "hello world" ], screen: screen)
XCTAssertEqual(screen.compactLineDumpWithHistory()!,
"abcde\n" + // history
"fgh..\n" + // history
"ijkl.\n" +
"hello\n" +
" worl\n" +
"d....")
let note = PTYAnnotation()
screen.addNote(note, in: VT100GridCoordRangeMake(0, 2, 2, 2), focus: true, visible: true)
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState?.showAltBuffer()
})
screen.size = VT100GridSizeMake(4, 4)
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState?.showPrimaryBuffer()
})
XCTAssertEqual(screen.compactLineDumpWithHistory()!,
"abcd\n" + // history
"efgh\n" + // history
"ijkl\n" +
"hell\n" +
"o wo\n" +
"rld.")
let notes = screen.annotations(in: VT100GridCoordRangeMake(0, 0, 5, 3))!
XCTAssertEqual(notes.count, 1)
XCTAssertTrue(notes[0].progenitor === note)
let range = screen.coordRange(ofAnnotation: note)
XCTAssertEqual(range, VT100GridCoordRangeMake(0, 2, 2, 2))
}
func testResizeNoteInPrimaryWhileInAltAndPushingSomePrimaryIncludingWholeNoteIntoHistory() {
let screen = fiveByFourScreenWithThreeLinesOneWrapped()
appendLinesNoNewline(["hello world"], screen: screen)
XCTAssertEqual(screen.compactLineDumpWithHistory()!,
"abcde\n" + // history
"fgh..\n" + // history
"ijkl.\n" +
"hello\n" +
" worl\n" +
"d....")
let note = PTYAnnotation()
screen.addNote(note, in: VT100GridCoordRangeMake(0, 2, 2, 2), focus: true, visible: true)
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState?.showAltBuffer()
})
screen.size = VT100GridSizeMake(3, 4)
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState?.showPrimaryBuffer()
})
XCTAssertEqual(screen.compactLineDumpWithHistory()!,
"abc\n" +
"def\n" +
"gh.\n" +
"ijk\n" +
"l..\n" +
"hel\n" +
"lo \n" +
"wor\n" +
"ld.")
let notes = screen.annotations(in: VT100GridCoordRangeMake(0, 0, 8, 3))!
XCTAssertEqual(notes.count, 1);
XCTAssertTrue(notes[0].progenitor === note)
let range = screen.coordRange(ofAnnotation: note)
XCTAssertEqual(range, VT100GridCoordRangeMake(0, 3, 2, 3))
}
func testResizeNoteInPrimaryWhileInAltAndPushingSomePrimaryIncludingPartOfNoteIntoHistory() {
let screen = fiveByFourScreenWithThreeLinesOneWrapped()
appendLinesNoNewline(["hello world"], screen: screen)
XCTAssertEqual(screen.compactLineDumpWithHistory()!,
"abcde\n" +
"fgh..\n" +
"ijkl.\n" +
"hello\n" +
" worl\n" +
"d....")
let note = PTYAnnotation()
screen.addNote(note, in: VT100GridCoordRangeMake(0, 2, 5, 3), focus: true, visible: true)
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState?.showAltBuffer()
})
screen.size = VT100GridSizeMake(3, 4)
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState?.showPrimaryBuffer()
})
XCTAssertEqual(screen.compactLineDumpWithHistory()!,
"abc\n" +
"def\n" +
"gh.\n" +
"ijk\n" +
"l..\n" +
"hel\n" +
"lo \n" +
"wor\n" +
"ld.")
let notes = screen.annotations(in: VT100GridCoordRangeMake(0, 0, 8, 3))!
XCTAssertEqual(notes.count, 1);
XCTAssertTrue(notes[0].progenitor === note)
let range = screen.coordRange(ofAnnotation: note)
XCTAssertEqual(range, VT100GridCoordRangeMake(0, 3, 2, 6))
}
private func showAltAndUppercase(_ screen: VT100Screen) {
screen.performBlock(joinedThreads: { _, mutableState, _ in
let temp = mutableState?.currentGrid.copy()
mutableState?.showAltBuffer()
for y in 0..<screen.height() {
let lineIn = temp!.screenChars(atLineNumber: y)!
let lineOut = mutableState!.currentGrid.screenChars(atLineNumber: y)!
for x in 0..<Int(screen.width()) {
lineOut[x] = lineIn[x]
var c = lineIn[x].code;
if isalpha(Int32(c)) != 0 {
c -= 32
}
lineOut[x].code = c
}
let w = Int(screen.width())
lineOut[w] = lineIn[w]
}
})
}
func testResizeNoteInAlternateThatGetsTruncatedByShrinkage() {
let screen = fiveByFourScreenWithThreeLinesOneWrapped()
appendLinesNoNewline(["hello world"], screen: screen)
XCTAssertEqual(screen.compactLineDumpWithHistory()!,
"abcde\n" +
"fgh..\n" +
"ijkl.\n" +
"hello\n" +
" worl\n" +
"d....")
showAltAndUppercase(screen)
let note = PTYAnnotation()
screen.addNote(note,
in: VT100GridCoordRangeMake(0, 1, 5, 3),
focus: true,
visible: true)
screen.size = VT100GridSizeMake(3, 4)
XCTAssertEqual(screen.compactLineDumpWithHistory()!,
"abc\n" +
"def\n" +
"gh.\n" +
"ijk\n" +
"l..\n" +
"HEL\n" +
"LO \n" +
"WOR\n" +
"LD.")
let notes = screen.annotations(in: VT100GridCoordRangeMake(0, 0, 3, 6))!
XCTAssertEqual(notes.count, 1);
XCTAssertTrue(notes[0].progenitor === note)
let range = screen.coordRange(ofAnnotation: note)
XCTAssertEqual(range, VT100GridCoordRangeMake(2, 1, 2, 6))
}
private func commonAnnotationRestoration(range: VT100GridCoordRange) {
var screen = fiveByNineScreenWithEmptyLineAtTop()
XCTAssertEqual(screen.compactLineDumpWithHistory()!,
".....\n" +
"abcde\n" +
"fgh..\n" +
".....\n" +
"ijkl.\n" +
".....\n" +
".....\n" +
".....\n" +
".....")
let note = PTYAnnotation()
screen.addNote(note, in: range, focus: true, visible: true)
let encoder = iTermMutableDictionaryEncoderAdapter.encoder()
var linesDropped = Int32(0)
screen.encodeContents(encoder, linesDropped: &linesDropped, unlimited: true)
let state = encoder.mutableDictionary
screen = self.screen(width: 3, height: 4)
screen.restore(from: state as? [AnyHashable : Any],
includeRestorationBanner: false,
reattached: false,
isArchive: false)
XCTAssertEqual(screen.compactLineDumpWithHistory()!,
".....\n" +
"abcde\n" +
"fgh..\n" +
".....\n" +
"ijkl.\n" +
".....\n" +
".....\n" +
".....\n" +
".....")
let notes = screen.annotations(in: VT100GridCoordRangeMake(0, 0, 5, 8))!
XCTAssertEqual(notes.count, 1)
let restoredNote = notes[0]
let rangeAfterResize = screen.coordRange(for: restoredNote.entry?.interval)
XCTAssertTrue(VT100GridCoordRangeEqualsCoordRange(rangeAfterResize, range))
}
func testResizeWithNoteFirstLine() {
commonAnnotationRestoration(range: VT100GridCoordRangeMake(0, 0, 5, 0))
}
func testResizeWithNoteFirstLinePlusFirstCharacterOfSecondLine() {
commonAnnotationRestoration(range: VT100GridCoordRangeMake(0, 0, 2, 1))
}
func testResizeWithNoteFirstTwoCharactersOfSecondLine() {
commonAnnotationRestoration(range: VT100GridCoordRangeMake(0, 1, 3, 1))
}
func testResizeWithNoteSecondLine() {
commonAnnotationRestoration(range: VT100GridCoordRangeMake(0, 1, 5, 1))
}
func testResizeWithNoteLastFourCharactersOfSecondLine() {
commonAnnotationRestoration(range: VT100GridCoordRangeMake(2, 1, 5, 1))
}
func testResizeWithNoteSecondCharacterOfSecondLineToSecondCharacterOfThirdLine() {
commonAnnotationRestoration(range: VT100GridCoordRangeMake(2, 1, 2, 2))
}
func testResizeWithNoteSecondAndThirdLines() {
commonAnnotationRestoration(range: VT100GridCoordRangeMake(0, 1, 5, 2))
}
func testResizeWithNoteSecondThroughFourthLines() {
commonAnnotationRestoration(range: VT100GridCoordRangeMake(0, 1, 5, 3))
}
func testResizeWithNoteSecondThroughFifthLines() {
commonAnnotationRestoration(range: VT100GridCoordRangeMake(0, 1, 5, 4))
}
func testResizeWithNoteSecondCharacterOfSecondLineThroughFirstCharacterOfFifthLine() {
commonAnnotationRestoration(range: VT100GridCoordRangeMake(2, 1, 2, 4))
}
func testResizeWithNoteThirdLineThroughFifthLine() {
commonAnnotationRestoration(range: VT100GridCoordRangeMake(0, 3, 5, 4))
}
func testResizeWithNoteThirdLineThroughMiddleOfFifthLine() {
commonAnnotationRestoration(range: VT100GridCoordRangeMake(0, 3, 3, 4))
}
func testResizeWithNoteFifthLine() {
commonAnnotationRestoration(range: VT100GridCoordRangeMake(0, 4, 5, 4))
}
func testResizeWithNoteAllLines() {
commonAnnotationRestoration(range: VT100GridCoordRangeMake(0, 0, 5, 4))
}
private func appendLines(_ lines: [String], screen: VT100Screen) {
screen.performBlock(joinedThreads: { _, mutableState, _ in
for line in lines {
mutableState!.appendString(atCursor: line)
mutableState!.appendCarriageReturnLineFeed()
}
})
}
func testResizeWithBlanksBeforeAnnotation() {
let range1 = VT100GridCoordRangeMake(0, 4, 10, 4)
let expected = range1
let screen = self.screen(width: 142, height: 8)
screen.performBlock(joinedThreads: { terminal, mutableState, _ in
mutableState!.maxScrollbackLines = 1000
})
appendLines([
"Last login: Mon Dec 9 23:22:07 on ttys011",
"You have mail.",
"Georges-iMac:/Users/gnachman% echo;echo xxxxxxxxxx",
"",
"xxxxxxxxxx",
"Georges-iMac:/Users/gnachman%"
], screen: screen)
let note = PTYAnnotation()
screen.addNote(note, in: range1, focus: true, visible: true)
screen.size = VT100GridSizeMake(141, 8)
let notes = screen.annotations(in: VT100GridCoordRangeMake(0, 0, 80, 8))!
XCTAssertEqual(notes.count, 1)
let restoredNote = notes[0]
let rangeAfterResize = screen.coordRange(for: restoredNote.entry?.interval)
XCTAssertTrue(VT100GridCoordRangeEqualsCoordRange(rangeAfterResize, expected))
}
// MARK: - VT100ScreenMark property resize tests
// Test that VT100ScreenMark's commandRange, promptRange, and outputStart are updated
// correctly when resizing while in the alt screen. Uses multi-line ranges.
func testResizeScreenMarkPropertiesInPrimaryWhileInAlt() {
let screen = self.screen(width: 10, height: 6)
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState!.maxScrollbackLines = 20
})
// Create content spanning multiple lines
appendLinesNoNewline([
"prompt$ command --with-long-arguments",
"output line 1",
"output line 2",
"next prompt"
], screen: screen)
var screenMark: VT100ScreenMark?
screen.performBlock(joinedThreads: { _, mutableState, _ in
// Add a VT100ScreenMark with multi-line commandRange
let mark = mutableState!.addMark(onLine: 0, of: VT100ScreenMark.self) as! VT100ScreenMark
let absLine = mutableState!.cumulativeScrollbackOverflow
mutableState!.mutableIntervalTree().mutate(mark) { obj in
let m = obj as! VT100ScreenMark
// commandRange spans from column 8 on line 0 to column 7 on line 3
// (simulating "command --with-long-arguments" wrapping across lines)
m.commandRange = VT100GridAbsCoordRangeMake(8, absLine, 7, absLine + 3)
// promptRange: "prompt$ " from (0,0) to (8,0)
m.promptRange = VT100GridAbsCoordRangeMake(0, absLine, 8, absLine)
// outputStart: beginning of output at line 4
m.outputStart = VT100GridAbsCoordMake(0, absLine + 4)
}
screenMark = mark
})
// Switch to alt screen - moves primary marks to savedIntervalTree
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState!.showAltBuffer()
})
// Resize from width 10 to width 8 - causes reflow
screen.size = VT100GridSizeMake(8, 6)
// Switch back to primary
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState!.showPrimaryBuffer()
})
// Verify the mark's properties were updated
screen.performBlock(joinedThreads: { _, mutableState, _ in
let cmdRange = screenMark!.commandRange
let promptRange = screenMark!.promptRange
let outStart = screenMark!.outputStart
// commandRange should have been converted to new coordinates
// It should still span multiple lines and have valid x coordinates
if cmdRange.start.x >= 0 {
XCTAssertLessThan(cmdRange.start.x, 8, "commandRange.start.x should be < new width")
XCTAssertLessThanOrEqual(cmdRange.end.x, 8, "commandRange.end.x should be <= new width")
// The range should still span multiple lines after reflow
XCTAssertGreaterThan(cmdRange.end.y, cmdRange.start.y,
"commandRange should still span multiple lines")
}
// promptRange should have valid coordinates
if promptRange.start.x >= 0 {
XCTAssertLessThan(promptRange.start.x, 8, "promptRange.start.x should be < new width")
XCTAssertLessThanOrEqual(promptRange.end.x, 8, "promptRange.end.x should be <= new width")
}
// outputStart should have valid x coordinate
if outStart.x >= 0 {
XCTAssertLessThan(outStart.x, 8, "outputStart.x should be < new width")
}
})
}
// Test that safeCoordRange properly clamps start.x when it's >= width
// This tests the fix for the bug where line 717-718 checked end.x twice instead of start.x
func testResizeWithOutOfBoundsCommandRangeStartX() {
let screen = self.screen(width: 5, height: 4)
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState!.maxScrollbackLines = 100
})
appendLinesNoNewline(["abcde", "fghij", "klmno"], screen: screen)
screen.performBlock(joinedThreads: { _, mutableState, _ in
// Add a mark
let mark = mutableState!.addMark(onLine: 1, of: VT100ScreenMark.self) as! VT100ScreenMark
let absLine = mutableState!.cumulativeScrollbackOverflow + 1
mutableState!.mutableIntervalTree().mutate(mark) { obj in
let m = obj as! VT100ScreenMark
// Set commandRange with start.x = width (5), which is out of bounds
// This simulates cursor at wrap position. Range spans to next line.
m.commandRange = VT100GridAbsCoordRangeMake(5, absLine, 3, absLine + 1)
}
})
// Resize - this should not crash and should handle the out-of-bounds start.x
screen.size = VT100GridSizeMake(4, 4)
// Verify we didn't crash and the mark still exists
screen.performBlock(joinedThreads: { _, mutableState, _ in
let marks = mutableState!.intervalTree.allObjects().compactMap { $0 as? VT100ScreenMark }
XCTAssertEqual(marks.count, 1)
})
}
// Test resize of VT100ScreenMark in saved interval tree (primary marks while alt is active)
// with multi-line ranges and lines being dropped due to reflow
func testResizeScreenMarkInSavedIntervalTreeWithDroppedLines() {
let screen = self.screen(width: 20, height: 5)
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState!.maxScrollbackLines = 10
})
// Fill screen with content that will reflow significantly
appendLines([
"user@host:~$ ls -la /very/long/path/to/directory",
"total 12345",
"drwxr-xr-x 5 user group 160 Jan 1 00:00 .",
"-rw-r--r-- 1 user group 1234 Jan 1 00:00 file.txt"
], screen: screen)
screen.performBlock(joinedThreads: { _, mutableState, _ in
// Add a mark on line 0 (the command line, which wraps)
let mark = mutableState!.addMark(onLine: 0, of: VT100ScreenMark.self) as! VT100ScreenMark
let absLine = mutableState!.cumulativeScrollbackOverflow
mutableState!.mutableIntervalTree().mutate(mark) { obj in
let m = obj as! VT100ScreenMark
// Command spans from column 13 ("ls") across the wrap to column 9 on next line
m.commandRange = VT100GridAbsCoordRangeMake(13, absLine, 9, absLine + 2)
// Prompt is "user@host:~$ " = 13 chars
m.promptRange = VT100GridAbsCoordRangeMake(0, absLine, 13, absLine)
// Output starts at "total 12345" line
m.outputStart = VT100GridAbsCoordMake(0, absLine + 3)
}
})
// Switch to alt screen - this moves primary marks to savedIntervalTree
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState!.showAltBuffer()
})
// Resize to much narrower width - causes significant reflow
screen.size = VT100GridSizeMake(10, 5)
// Switch back to primary
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState!.showPrimaryBuffer()
})
// Verify the mark survived and has valid properties
screen.performBlock(joinedThreads: { _, mutableState, _ in
let marks = mutableState!.intervalTree.allObjects().compactMap { $0 as? VT100ScreenMark }
for mark in marks {
let cmdRange = mark.commandRange
if cmdRange.start.x >= 0 {
// If commandRange is set, it should have valid x coordinates for new width
XCTAssertLessThanOrEqual(cmdRange.start.x, 10,
"commandRange.start.x should be <= new width")
XCTAssertLessThanOrEqual(cmdRange.end.x, 10,
"commandRange.end.x should be <= new width")
}
let promptRange = mark.promptRange
if promptRange.start.x >= 0 {
XCTAssertLessThanOrEqual(promptRange.start.x, 10,
"promptRange.start.x should be <= new width")
XCTAssertLessThanOrEqual(promptRange.end.x, 10,
"promptRange.end.x should be <= new width")
}
let outStart = mark.outputStart
if outStart.x >= 0 {
XCTAssertLessThan(outStart.x, 10, "outputStart.x should be < new width")
}
}
})
}
// Test resize growing width with multi-line VT100ScreenMark ranges
func testResizeScreenMarkPropertiesGrowingWidth() {
let screen = self.screen(width: 5, height: 6)
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState!.maxScrollbackLines = 20
})
// Content that wraps at width 5
appendLinesNoNewline([
"$ cmd",
"out1",
"out2"
], screen: screen)
var screenMark: VT100ScreenMark?
screen.performBlock(joinedThreads: { _, mutableState, _ in
let mark = mutableState!.addMark(onLine: 0, of: VT100ScreenMark.self) as! VT100ScreenMark
let absLine = mutableState!.cumulativeScrollbackOverflow
mutableState!.mutableIntervalTree().mutate(mark) { obj in
let m = obj as! VT100ScreenMark
// Command "cmd" at column 2-5 on line 0
m.commandRange = VT100GridAbsCoordRangeMake(2, absLine, 5, absLine)
// Prompt "$ " at column 0-2
m.promptRange = VT100GridAbsCoordRangeMake(0, absLine, 2, absLine)
// Output starts on line 1
m.outputStart = VT100GridAbsCoordMake(0, absLine + 1)
}
screenMark = mark
})
// Switch to alt, resize wider, switch back
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState!.showAltBuffer()
})
screen.size = VT100GridSizeMake(10, 6)
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState!.showPrimaryBuffer()
})
// Verify properties are valid for new width
screen.performBlock(joinedThreads: { _, mutableState, _ in
let cmdRange = screenMark!.commandRange
let promptRange = screenMark!.promptRange
let outStart = screenMark!.outputStart
// All x coordinates should be valid (< 10)
if cmdRange.start.x >= 0 {
XCTAssertLessThan(cmdRange.start.x, 10)
XCTAssertLessThanOrEqual(cmdRange.end.x, 10)
}
if promptRange.start.x >= 0 {
XCTAssertLessThan(promptRange.start.x, 10)
XCTAssertLessThanOrEqual(promptRange.end.x, 10)
}
if outStart.x >= 0 {
XCTAssertLessThan(outStart.x, 10)
}
})
}
private func commonNoteResizeRegressionTest(initialRange range1: VT100GridCoordRange,
intermediateRange range2: VT100GridCoordRange) {
var screen = self.screen(width: 80, height: 25)
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState!.maxScrollbackLines = 1000
})
appendLines([
"",
"",
"",
"Georges-iMac:/Users/gnachman% xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
], screen: screen)
let note = PTYAnnotation()
screen.addNote(note, in: range1, focus: true, visible: true)
let encoder = iTermMutableDictionaryEncoderAdapter.encoder()
var linesDropped: Int32 = 0
screen.encodeContents(encoder, linesDropped: &linesDropped, unlimited: true)
let state = encoder.mutableDictionary
screen = self.screen(width: 80, height: 25)
screen.restore(from: state as? [AnyHashable: Any],
includeRestorationBanner: false,
reattached: true,
isArchive: false)
screen.size = VT100GridSizeMake(77, 25)
var notes = screen.annotations(in: VT100GridCoordRangeMake(0, 0, 80, 25))!
XCTAssertEqual(notes.count, 1)
let restoredNote1 = notes[0]
let rangeAfterResize1 = screen.coordRange(for: restoredNote1.entry!.interval)
XCTAssertTrue(VT100GridCoordRangeEqualsCoordRange(rangeAfterResize1, range2))
screen.size = VT100GridSizeMake(80, 25)
notes = screen.annotations(in: VT100GridCoordRangeMake(0, 0, 80, 25))!
let restoredNote2 = notes[0]
let rangeAfterResize2 = screen.coordRange(for: restoredNote2.entry!.interval)
XCTAssertTrue(VT100GridCoordRangeEqualsCoordRange(rangeAfterResize2, range1))
}
func testNoteResizeRegression1() {
commonNoteResizeRegressionTest(
initialRange: VT100GridCoordRangeMake(0, 0, 80, 0),
intermediateRange: VT100GridCoordRangeMake(0, 0, 77, 0)
)
}
func testNoteResizeNoEncodeDecode() {
// Test annotation resize on an empty line (line 0)
let screen = self.screen(width: 80, height: 25)
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState!.maxScrollbackLines = 1000
})
appendLines([
"",
"",
"",
"Georges-iMac:/Users/gnachman% xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
], screen: screen)
let note = PTYAnnotation()
let range1 = VT100GridCoordRangeMake(0, 0, 80, 0)
screen.addNote(note, in: range1, focus: true, visible: true)
screen.size = VT100GridSizeMake(77, 25)
let notesAfter = screen.annotations(in: VT100GridCoordRangeMake(0, 0, 80, 25))!
XCTAssertEqual(notesAfter.count, 1)
let rangeAfter = screen.coordRange(for: notesAfter[0].entry!.interval)
let expected = VT100GridCoordRangeMake(0, 0, 77, 0)
XCTAssertTrue(VT100GridCoordRangeEqualsCoordRange(rangeAfter, expected))
}
func testNoteResizeNoEncodeDecodeLine1() {
// Test annotation resize on an empty line (line 1)
let screen = self.screen(width: 80, height: 25)
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState!.maxScrollbackLines = 1000
})
appendLines([
"",
"",
"",
"Georges-iMac:/Users/gnachman% xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
], screen: screen)
let note = PTYAnnotation()
let range1 = VT100GridCoordRangeMake(0, 1, 80, 1)
screen.addNote(note, in: range1, focus: true, visible: true)
screen.size = VT100GridSizeMake(77, 25)
let notesAfter = screen.annotations(in: VT100GridCoordRangeMake(0, 0, 80, 25))!
XCTAssertEqual(notesAfter.count, 1)
let rangeAfter = screen.coordRange(for: notesAfter[0].entry!.interval)
let expected = VT100GridCoordRangeMake(0, 1, 77, 1)
XCTAssertTrue(VT100GridCoordRangeEqualsCoordRange(rangeAfter, expected))
}
func testNoteResizeRegression2() {
commonNoteResizeRegressionTest(
initialRange: VT100GridCoordRangeMake(0, 1, 80, 1),
intermediateRange: VT100GridCoordRangeMake(0, 1, 77, 1)
)
}
func testNoteResizeRegression3() {
commonNoteResizeRegressionTest(
initialRange: VT100GridCoordRangeMake(0, 2, 80, 2),
intermediateRange: VT100GridCoordRangeMake(0, 2, 77, 2)
)
}
func testNoteResizeRegression4() {
commonNoteResizeRegressionTest(
initialRange: VT100GridCoordRangeMake(20, 4, 80, 6),
intermediateRange: VT100GridCoordRangeMake(23, 4, 77, 6)
)
}
func testNoteResizeRegression5() {
commonNoteResizeRegressionTest(
initialRange: VT100GridCoordRangeMake(0, 12, 80, 12),
intermediateRange: VT100GridCoordRangeMake(0, 12, 77, 12)
)
}
// MARK: -
private func makeMixedToken(_ string: String) -> VT100Token {
let token = VT100Token()
token.type = VT100_MIXED_ASCII_CR_LF;
var data = string.data(using: .utf8)!
data.withUnsafeMutableBytes { umrbp -> Void in
let umbp = umrbp.assumingMemoryBound(to: CChar.self)
token.setAsciiBytes(umbp.baseAddress!,
length: Int32(umbp.count))
token.realizeCRLFs(withCapacity: 10)
for i in 0..<umbp.count {
if umbp[i] == 10 || umbp[i] == 13 {
token.appendCRLF(Int32(i))
}
}
}
return token
}
private func gangExpected(initialLines: [String], mixedTokens: [String]) -> String {
let screen = self.screen(width: 10, height: 4)
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState!.maxScrollbackLines = 1000
})
appendLines(initialLines, screen: screen)
screen.performBlock(joinedThreads: { _, mutableState, _ in
for token in mixedTokens {
var i = token.startIndex
while i < token.endIndex {
let nextNewline = token.range(of: "\r\n", range: i..<token.endIndex)
if let nextNewline {
let substring = token[i..<nextNewline.lowerBound]
mutableState!.appendString(atCursor: String(substring))
mutableState!.appendCarriageReturnLineFeed()
i = nextNewline.upperBound
} else {
let substring = token[i..<token.endIndex]
mutableState!.appendString(atCursor: String(substring))
i = token.endIndex
}
}
}
})
return screen.compactLineDumpWithDividedHistoryAndContinuationMarks()
}
@discardableResult
private func gangTest(initialLines: [String], mixedTokens: [String]) -> Bool {
let expected = gangExpected(initialLines: initialLines, mixedTokens: mixedTokens)
let screen = self.screen(width: 10, height: 4)
screen.performBlock(joinedThreads: { _, mutableState, _ in
mutableState!.maxScrollbackLines = 1000
})
appendLines(initialLines, screen: screen)
screen.performBlock(joinedThreads: { _, mutableState, _ in
let gang = mixedTokens.map {
makeMixedToken($0)
}
mutableState!.terminalAppendMixedAsciiGang(gang)
})
let actual = screen.compactLineDumpWithDividedHistoryAndContinuationMarks()
XCTAssertEqual(actual, expected)
if actual != expected {
print("Actual:\n\(actual!)\n\nExpected:\n\(expected)")
}
return actual == expected
}
func testGang_basic() {
gangTest(
initialLines: [
"Now is the time for all good men to come to the aid of their party.",
"",
"Twas brillig and the slithy toves did gyre and gimbal in the wabe."],
mixedTokens: [
"One for the money\r\ntwo for the show\r\n",
"Three to get ready\r\nFour let's",
" go"
])
}
private func performRandomGangTest(prng: inout SeededGenerator) -> Bool {
let numInitialLines = prng.next(in: 0..<8)
let initialLines = (0..<numInitialLines).map { i in
String(repeating: Character(UnicodeScalar(65 + i)!), count: prng.next(in: 0..<80))
}
var tokens = [String]()
var letter = 65 + 32
let numTokens = prng.next(in: 1..<8)
for _ in 0..<numTokens {
let numLines = prng.next(in: 0..<8)
var token = ""
for j in 0..<numLines {
token.append(String(repeating: Character(UnicodeScalar(letter)!),
count: prng.next(in: 0..<80)))
letter += 1
if letter == 65 + 32 + 26 {
letter = 65 + 32
}
if j < numLines - 1 || prng.coinflip(p: 0.5) {
token.append("\r\n")
}
}
tokens.append(token)
}
return gangTest(initialLines: initialLines, mixedTokens: tokens)
}
func testGang_random() {
var prng = SeededGenerator(seed: 0)
let iterations = 100
for i in 0..<iterations {
var saved = prng
if !performRandomGangTest(prng: &prng) {
// Set a breakpoint here to debug test failures.
NSLog("Random test failed on iteration \(i)")
_ = performRandomGangTest(prng: &saved)
} else if i % 100 == 0 {
NSLog("Iteration \(i) passed")
}
}
}
// MARK: - Fast path eligibility tests
/// Helper that tests gang output with a state mutation that affects _fastPathEligible.
/// 1. Applies `setup` to force slow path, sends firstTokens, verifies output.
/// 2. Applies `restore` to re-enable fast path, sends secondTokens, verifies output.
/// The debug assertion in terminalAppendMixedAsciiGang: validates cache consistency.
private func gangTestWithSetup(
width: Int32 = 10,
height: Int32 = 4,
initialLines: [String] = [],
firstTokens: [String],
secondTokens: [String],
setup: @escaping (VT100ScreenMutableState) -> Void,
restore: @escaping (VT100ScreenMutableState) -> Void,
file: StaticString = #filePath,
line: UInt = #line
) {
// Compute expected output after setup + firstTokens via character-at-a-time
let expectedAfterSetup: String = {
let s = self.screen(width: width, height: height)
s.performBlock(joinedThreads: { _, ms, _ in ms!.maxScrollbackLines = 1000 })
appendLines(initialLines, screen: s)
s.performBlock(joinedThreads: { _, ms, _ in
setup(ms!)
for token in firstTokens {
var i = token.startIndex
while i < token.endIndex {
let nl = token.range(of: "\r\n", range: i..<token.endIndex)
if let nl {
ms!.appendString(atCursor: String(token[i..<nl.lowerBound]))
ms!.appendCarriageReturnLineFeed()
i = nl.upperBound
} else {
ms!.appendString(atCursor: String(token[i..<token.endIndex]))
i = token.endIndex
}
}
}
})
return s.compactLineDumpWithDividedHistoryAndContinuationMarks()
}()
// Compute expected output after restore + secondTokens via character-at-a-time
let expectedAfterRestore: String = {
let s = self.screen(width: width, height: height)
s.performBlock(joinedThreads: { _, ms, _ in ms!.maxScrollbackLines = 1000 })
appendLines(initialLines, screen: s)
s.performBlock(joinedThreads: { _, ms, _ in
setup(ms!)
for token in firstTokens {
var i = token.startIndex
while i < token.endIndex {
let nl = token.range(of: "\r\n", range: i..<token.endIndex)
if let nl {
ms!.appendString(atCursor: String(token[i..<nl.lowerBound]))
ms!.appendCarriageReturnLineFeed()
i = nl.upperBound
} else {
ms!.appendString(atCursor: String(token[i..<token.endIndex]))
i = token.endIndex
}
}
}
restore(ms!)
for token in secondTokens {
var i = token.startIndex
while i < token.endIndex {
let nl = token.range(of: "\r\n", range: i..<token.endIndex)
if let nl {
ms!.appendString(atCursor: String(token[i..<nl.lowerBound]))
ms!.appendCarriageReturnLineFeed()
i = nl.upperBound
} else {
ms!.appendString(atCursor: String(token[i..<token.endIndex]))
i = token.endIndex
}
}
}
})
return s.compactLineDumpWithDividedHistoryAndContinuationMarks()
}()
// Now test the gang path