-
-
Notifications
You must be signed in to change notification settings - Fork 143
/
renderer.ts
1089 lines (1026 loc) · 39.8 KB
/
renderer.ts
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
import { parseGuifont, toHexCss } from "./utils/utils";
import { NvimMode, confReady, getGlobalConf, ISiteConfig } from "./utils/configuration";
import { EventEmitter } from "./EventEmitter";
type ResizeEvent = {grid: number, width: number, height: number};
type FrameResizeEvent = {width: number, height: number}
type ModeChangeEvent = NvimMode;
type ResizeEventHandler = (e: ResizeEvent | FrameResizeEvent | ModeChangeEvent) => void;
type EventKind = "resize" | "frameResize" | "modeChange" | "mouseOn" | "mouseOff";
export const events = new EventEmitter<EventKind, ResizeEventHandler>();
let glyphCache : any = {};
function wipeGlyphCache() {
glyphCache = {};
}
let metricsInvalidated = false;
function invalidateMetrics() {
metricsInvalidated = true;
wipeGlyphCache();
}
let fontString : string;
function setFontString (state: State, s : string) {
fontString = s;
state.context.font = fontString;
invalidateMetrics();
}
function glyphId(char: string, high: number) {
return char + "-" + high;
}
function setCanvasDimensions (cvs: HTMLCanvasElement, width: number, height: number) {
cvs.width = width * window.devicePixelRatio;
cvs.height = height * window.devicePixelRatio;
cvs.style.width = `${width}px`;
cvs.style.height = `${height}px`;
}
function makeFontString(fontSize: string, fontFamily: string) {
return `${fontSize} ${fontFamily}`;
}
let defaultFontSize = "";
const defaultFontFamily = "monospace";
let defaultFontString = "";
export function setCanvas (cvs: HTMLCanvasElement) {
const state = globalState;
state.canvas = cvs;
setCanvasDimensions(state.canvas,
window.innerWidth,
window.innerHeight);
const canvasDefaultFontSize = window.getComputedStyle(state.canvas).fontSize;
defaultFontSize = `calc(${window.devicePixelRatio} * ${canvasDefaultFontSize})`;
defaultFontString = makeFontString(defaultFontSize, defaultFontFamily);
state.context = state.canvas.getContext("2d", { "alpha": false });
setFontString(state, defaultFontString);
}
let settings: ISiteConfig;
export function setSettings (s: ISiteConfig) {
settings = s
}
// We first define highlight information.
const defaultBackground = "#FFFFFF";
const defaultForeground = "#000000";
type HighlightInfo = {
background: string,
bold: boolean,
blend: number,
foreground: string,
italic: boolean,
reverse: boolean,
special: string,
strikethrough: boolean,
undercurl: boolean,
underline: boolean
};
// We then have a GridSize type. We need this type in order to keep track of
// the size of grids. Storing this information here can appear redundant since
// the grids are represented as arrays and thus have a .length attribute, but
// it's not: storing grid size in a separate datastructure allows us to never
// have to shrink arrays, and to not need allocations if enlarging an array
// that has been shrunk.
type GridDimensions = {
width: number,
height: number,
};
enum DamageKind {
Cell,
Resize,
Scroll,
}
// Used to track rectangles of damage done to a grid and only repaint the
// necessary bits. These are logic positions (i.e. cells) - not pixels.
type CellDamage = {
kind: DamageKind,
// The number of rows the damage spans
h: number,
// The number of columns the damage spans
w: number,
// The column the damage begins at
x: number,
// The row the damage begins at
y: number,
};
type ResizeDamage = {
kind: DamageKind,
// The new height of the canvas
h: number,
// The new width of the canvas
w: number,
// The previous width of the canvas
x: number,
// The previous height of the canvas
y: number,
};
type ScrollDamage = {
kind: DamageKind,
// The direction of the scroll, -1 means up, 1 means down
h: number,
// The number of lines of the scroll, positive number
w: number,
// The top line of the scrolling region, in cells
x: number,
// The bottom line of the scrolling region, in cells
y: number,
};
type GridDamage = CellDamage & ResizeDamage & ScrollDamage;
// The state of the commandline. It is only used when using neovim's external
// commandline.
type CommandLineState = {
status: "hidden" | "shown",
content: [any, string][],
pos: number,
firstc: string,
prompt: string,
indent: number,
level: number
};
type Cursor = {
currentGrid: number,
display: boolean,
x: number,
y: number,
lastMove: DOMHighResTimeStamp,
movedSinceLastMessage: boolean,
};
type Mode = {
current: number,
styleEnabled: boolean,
modeInfo: {
attr_id: number,
attr_id_lm: number,
blinkoff: number,
blinkon: number,
blinkwait: number,
cell_percentage: number,
cursor_shape: string,
name: NvimMode,
}[],
};
type Message = [number, string][];
type MessagesPosition = { x: number, y: number };
type State = {
canvas: HTMLCanvasElement,
context: CanvasRenderingContext2D,
commandLine : CommandLineState,
cursor: Cursor,
gridCharacters: string[][][],
gridDamages: GridDamage[][],
gridDamagesCount: number[],
gridHighlights: number[][][],
gridSizes: GridDimensions[],
highlights: HighlightInfo[],
lastMessage: DOMHighResTimeStamp,
linespace: number,
messages: Message[],
messagesPositions: MessagesPosition[],
mode: Mode,
ruler: Message,
showcmd: Message,
showmode: Message,
};
const globalState: State = {
canvas: undefined,
context: undefined,
commandLine: {
status: "hidden",
content: [],
pos: 0,
firstc: "",
prompt: "",
indent: 0,
level: 0,
},
cursor: {
currentGrid: 1,
display: true,
x: 0,
y: 0,
lastMove: performance.now(),
movedSinceLastMessage: false,
},
gridCharacters: [],
gridDamages: [],
gridDamagesCount: [],
gridHighlights: [],
gridSizes: [],
highlights: [newHighlight(defaultBackground, defaultForeground)],
lastMessage: performance.now(),
linespace: 0,
messages: [],
messagesPositions: [],
mode: {
current: 0,
styleEnabled : false,
modeInfo: [{
attr_id: 0,
attr_id_lm: 0,
blinkoff: 0,
blinkon: 0,
blinkwait: 0,
cell_percentage: 0,
cursor_shape: "block",
name: "normal",
}]
},
ruler: undefined,
showcmd: undefined,
showmode: undefined,
};
function pushDamage(grid: number, kind: DamageKind, h: number, w: number, x: number, y: number) {
const damages = globalState.gridDamages[grid];
const count = globalState.gridDamagesCount[grid];
if (damages.length === count) {
damages.push({ kind, h, w, x, y });
} else {
damages[count].kind = kind;
damages[count].h = h;
damages[count].w = w;
damages[count].x = x;
damages[count].y = y;
}
globalState.gridDamagesCount[grid] = count + 1;
}
let maxCellWidth: number;
let maxCellHeight: number;
let maxBaselineDistance: number;
function recomputeCharSize (ctx: CanvasRenderingContext2D) {
// 94, K+32: we ignore the first 32 ascii chars because they're non-printable
const chars = new Array(94)
.fill(0)
.map((_, k) => String.fromCharCode(k + 32))
// Concatening  because that's the tallest character I can think of.
.concat(["Â"]);
let width = 0;
let height = 0;
let baseline = 0;
let measure: TextMetrics;
for (const char of chars) {
measure = ctx.measureText(char);
if (measure.width > width) {
width = measure.width;
}
let tmp = Math.abs(measure.actualBoundingBoxAscent);
if (tmp > baseline) {
baseline = tmp;
}
tmp += Math.abs(measure.actualBoundingBoxDescent);
if (tmp > height) {
height = tmp;
}
}
maxCellWidth = Math.ceil(width);
maxCellHeight = Math.ceil(height) + globalState.linespace;
maxBaselineDistance = baseline;
metricsInvalidated = false;
}
export function getGlyphInfo (state: State) {
if (metricsInvalidated
|| maxCellWidth === undefined
|| maxCellHeight === undefined
|| maxBaselineDistance === undefined) {
recomputeCharSize(state.context);
}
return [maxCellWidth, maxCellHeight, maxBaselineDistance];
}
function measureWidth(state: State, char: string) {
const charWidth = getGlyphInfo(state)[0];
return Math.ceil(state.context.measureText(char).width / charWidth) * charWidth;
}
export function getLogicalSize() {
const state = globalState;
const [cellWidth, cellHeight] = getGlyphInfo(state);
return [Math.floor(state.canvas.width / cellWidth), Math.floor(state.canvas.height / cellHeight)];
}
export function computeGridDimensionsFor (width : number, height : number) {
const [cellWidth, cellHeight] = getGlyphInfo(globalState);
return [Math.floor(width / cellWidth), Math.floor(height / cellHeight)];
}
export function getGridCoordinates (x: number, y: number) {
const [cellWidth, cellHeight] = getGlyphInfo(globalState);
return [Math.floor(x * window.devicePixelRatio / cellWidth), Math.floor(y * window.devicePixelRatio / cellHeight)];
}
function newHighlight (bg: string, fg: string): HighlightInfo {
return {
background: bg,
bold: undefined,
blend: undefined,
foreground: fg,
italic: undefined,
reverse: undefined,
special: undefined,
strikethrough: undefined,
undercurl: undefined,
underline: undefined,
};
}
export function getGridId() {
return 1;
}
function getCommandLineRect (state: State) {
const [width, height] = getGlyphInfo(state);
return {
x: width - 1,
y: ((state.canvas.height - height - 1) / 2),
width: (state.canvas.width - (width * 2)) + 2,
height: height + 2,
};
}
function damageCommandLineSpace (state: State) {
const [width, height] = getGlyphInfo(state);
const rect = getCommandLineRect(state);
const gid = getGridId();
const dimensions = globalState.gridSizes[gid];
pushDamage(gid,
DamageKind.Cell,
Math.min(Math.ceil(rect.height / height) + 1, dimensions.height),
Math.min(Math.ceil(rect.width / width) + 1, dimensions.width),
Math.max(Math.floor(rect.x / width), 0),
Math.max(Math.floor(rect.y / height), 0));
}
function damageMessagesSpace (state: State) {
const gId = getGridId();
const msgPos = globalState.messagesPositions[gId];
const dimensions = globalState.gridSizes[gId];
const [charWidth, charHeight] = getGlyphInfo(state);
pushDamage(gId,
DamageKind.Cell,
Math.min(
Math.ceil((state.canvas.height - msgPos.y) / charHeight) + 2,
dimensions.height),
Math.min(
Math.ceil((state.canvas.width - msgPos.x) / charWidth) + 2,
dimensions.width),
Math.max(Math.floor(msgPos.x / charWidth) - 1, 0),
Math.max(Math.floor(msgPos.y / charHeight) - 1, 0));
msgPos.x = state.canvas.width;
msgPos.y = state.canvas.height;
}
const handlers : { [key:string] : (...args: any[])=>void } = {
busy_start: () => {
pushDamage(getGridId(), DamageKind.Cell, 1, 1, globalState.cursor.x, globalState.cursor.y);
globalState.cursor.display = false;
},
busy_stop: () => { globalState.cursor.display = true; },
cmdline_hide: () => {
globalState.commandLine.status = "hidden";
damageCommandLineSpace(globalState);
},
cmdline_pos: (pos: number, level: number) => {
globalState.commandLine.pos = pos;
globalState.commandLine.level = level;
},
cmdline_show:
(content: [any, string][],
pos: number,
firstc: string,
prompt: string,
indent: number,
level: number) => {
globalState.commandLine.status = "shown";
globalState.commandLine.content = content;
globalState.commandLine.pos = pos;
globalState.commandLine.firstc = firstc;
globalState.commandLine.prompt = prompt;
globalState.commandLine.indent = indent;
globalState.commandLine.level = level;
},
default_colors_set: (fg: number, bg: number, sp: number) => {
if (fg !== undefined && fg !== -1) {
globalState.highlights[0].foreground = toHexCss(fg);
}
if (bg !== undefined && bg !== -1) {
globalState.highlights[0].background = toHexCss(bg);
}
if (sp !== undefined && sp !== -1) {
globalState.highlights[0].special = toHexCss(sp);
}
const curGridSize = globalState.gridSizes[getGridId()];
if (curGridSize !== undefined) {
pushDamage(getGridId(), DamageKind.Cell, curGridSize.height, curGridSize.width, 0, 0);
}
wipeGlyphCache();
},
flush: () => {
scheduleFrame();
},
grid_clear: (id: number) => {
// glacambre: What should actually happen on grid_clear? The
// documentation says "clear the grid", but what does that
// mean? I guess the characters should be removed, but what
// about the highlights? Are there other things that need to
// be cleared?
// bfredl: to default bg color
// grid_clear is not meant to be used often
// it is more "the terminal got screwed up, better to be safe
// than sorry"
const charGrid = globalState.gridCharacters[id];
const highGrid = globalState.gridHighlights[id];
const dims = globalState.gridSizes[id];
for (let j = 0; j < dims.height; ++j) {
for (let i = 0; i < dims.width; ++i) {
charGrid[j][i] = " ";
highGrid[j][i] = 0;
}
}
pushDamage(id, DamageKind.Cell, dims.height, dims.width, 0, 0);
},
grid_cursor_goto: (id: number, row: number, column: number) => {
const cursor = globalState.cursor;
pushDamage(getGridId(), DamageKind.Cell, 1, 1, cursor.x, cursor.y);
cursor.currentGrid = id;
cursor.x = column;
cursor.y = row;
cursor.lastMove = performance.now();
cursor.movedSinceLastMessage = true;
},
grid_line: (id: number, row: number, col: number, changes: any[]) => {
const charGrid = globalState.gridCharacters[id];
const highlights = globalState.gridHighlights[id];
let prevCol = col;
let high = 0;
for (let i = 0; i < changes.length; ++i) {
const change = changes[i];
const chara = change[0];
if (change[1] !== undefined) {
high = change[1];
}
const repeat = change[2] === undefined ? 1 : change[2];
pushDamage(id, DamageKind.Cell, 1, repeat, prevCol, row);
const limit = prevCol + repeat;
for (let j = prevCol; j < limit; j += 1) {
charGrid[row][j] = chara;
highlights[row][j] = high;
}
prevCol = limit;
}
},
grid_resize: (id: number, width: number, height: number) => {
const state = globalState;
const createGrid = state.gridCharacters[id] === undefined;
if (createGrid) {
state.gridCharacters[id] = [];
state.gridCharacters[id].push([]);
state.gridSizes[id] = { width: 0, height: 0 };
state.gridDamages[id] = [];
state.gridDamagesCount[id] = 0;
state.gridHighlights[id] = [];
state.gridHighlights[id].push([]);
state.messagesPositions[id] = {
x: state.canvas.width,
y: state.canvas.height,
};
}
const curGridSize = globalState.gridSizes[id];
pushDamage(id, DamageKind.Resize, height, width, curGridSize.width, curGridSize.height);
const highlights = globalState.gridHighlights[id];
const charGrid = globalState.gridCharacters[id];
if (width > charGrid[0].length) {
for (let i = 0; i < charGrid.length; ++i) {
const row = charGrid[i];
const highs = highlights[i];
while (row.length < width) {
row.push(" ");
highs.push(0);
}
}
}
if (height > charGrid.length) {
while (charGrid.length < height) {
charGrid.push((new Array(width)).fill(" "));
highlights.push((new Array(width)).fill(0));
}
}
pushDamage(id, DamageKind.Cell, 0, width, 0, curGridSize.height);
curGridSize.width = width;
curGridSize.height = height;
},
grid_scroll: (id: number,
top: number,
bot: number,
left: number,
right: number,
rows: number,
_cols: number) => {
const dimensions = globalState.gridSizes[id];
const charGrid = globalState.gridCharacters[id];
const highGrid = globalState.gridHighlights[id];
if (rows > 0) {
const bottom = (bot + rows) >= dimensions.height
? dimensions.height - rows
: bot;
for (let y = top; y < bottom; ++y) {
const srcChars = charGrid[y + rows];
const dstChars = charGrid[y];
const srcHighs = highGrid[y + rows];
const dstHighs = highGrid[y];
for (let x = left; x < right; ++x) {
dstChars[x] = srcChars[x];
dstHighs[x] = srcHighs[x];
}
}
pushDamage(id, DamageKind.Cell, dimensions.height, dimensions.width, 0, 0);
} else if (rows < 0) {
for (let y = bot - 1; y >= top && (y + rows) >= 0; --y) {
const srcChars = charGrid[y + rows];
const dstChars = charGrid[y];
const srcHighs = highGrid[y + rows];
const dstHighs = highGrid[y];
for (let x = left; x < right; ++x) {
dstChars[x] = srcChars[x];
dstHighs[x] = srcHighs[x];
}
}
pushDamage(id, DamageKind.Cell, dimensions.height, dimensions.width, 0, 0);
}
},
hl_attr_define: (id: number, rgbAttr: any) => {
const highlights = globalState.highlights;
if (highlights[id] === undefined) {
highlights[id] = newHighlight(undefined, undefined);
}
highlights[id].foreground = toHexCss(rgbAttr.foreground);
highlights[id].background = toHexCss(rgbAttr.background);
highlights[id].bold = rgbAttr.bold;
highlights[id].blend = rgbAttr.blend;
highlights[id].italic = rgbAttr.italic;
highlights[id].special = toHexCss(rgbAttr.special);
highlights[id].strikethrough = rgbAttr.strikethrough;
highlights[id].undercurl = rgbAttr.undercurl;
highlights[id].underline = rgbAttr.underline;
highlights[id].reverse = rgbAttr.reverse;
},
mode_change: (_: string, modeIdx: number) => {
globalState.mode.current = modeIdx;
events.emit("modeChange", globalState.mode.modeInfo[modeIdx].name);
if (globalState.mode.styleEnabled) {
const cursor = globalState.cursor;
pushDamage(getGridId(), DamageKind.Cell, 1, 1, cursor.x, cursor.y);
scheduleFrame();
}
},
mode_info_set: (cursorStyleEnabled: boolean, modeInfo: []) => {
// Missing: handling of cell-percentage
const mode = globalState.mode;
mode.styleEnabled = cursorStyleEnabled;
mode.modeInfo = modeInfo;
},
mouse_on: () => {
events.emit("mouseOn");
},
mouse_off: () => {
events.emit("mouseOff");
},
msg_clear: () => {
damageMessagesSpace(globalState);
globalState.messages.length = 0;
},
msg_history_show: (entries: any[]) => {
damageMessagesSpace(globalState);
globalState.messages = entries.map(([, b]) => b);
},
msg_ruler: (content: Message) => {
damageMessagesSpace(globalState);
globalState.ruler = content;
},
msg_show: (_: string, content: Message, replaceLast: boolean) => {
damageMessagesSpace(globalState);
if (replaceLast) {
globalState.messages.length = 0;
}
globalState.messages.push(content);
globalState.lastMessage = performance.now();
globalState.cursor.movedSinceLastMessage = false;
},
msg_showcmd: (content: Message) => {
damageMessagesSpace(globalState);
globalState.showcmd = content;
},
msg_showmode: (content: Message) => {
damageMessagesSpace(globalState);
globalState.showmode = content;
},
option_set: (option: string, value: any) => {
const state = globalState;
switch (option) {
case "guifont": {
let newFontString;
if (value === "") {
newFontString = defaultFontString;
} else {
const guifont = parseGuifont(value, {
"font-family": defaultFontFamily,
"font-size": defaultFontSize,
});
newFontString = makeFontString(guifont["font-size"], guifont["font-family"]);
}
if (newFontString === fontString) {
break;
}
setFontString(state, newFontString);
const [charWidth, charHeight] = getGlyphInfo(state);
events.emit("resize", {
grid: getGridId(),
width: Math.floor(state.canvas.width / charWidth),
height: Math.floor(state.canvas.height / charHeight),
});
}
break;
case "linespace": {
if (state.linespace === value) {
break;
}
state.linespace = value;
invalidateMetrics();
const [charWidth, charHeight] = getGlyphInfo(state);
const gid = getGridId();
const curGridSize = state.gridSizes[gid];
if (curGridSize !== undefined) {
pushDamage(getGridId(), DamageKind.Cell, curGridSize.height, curGridSize.width, 0, 0);
}
events.emit("resize", {
grid: gid,
width: Math.floor(state.canvas.width / charWidth),
height: Math.floor(state.canvas.height / charHeight),
});
}
break;
}
},
};
// keep track of whether a frame is already being scheduled or not. This avoids
// asking for multiple frames where we'd paint the same thing anyway.
let frameScheduled = false;
function scheduleFrame() {
if (!frameScheduled) {
frameScheduled = true;
window.requestAnimationFrame(paint);
}
}
function paintMessages(state: State) {
if (settings.cmdline === "none") {
return;
}
const ctx = state.context;
const gId = getGridId();
const messagesPosition = state.messagesPositions[gId];
const [, charHeight, baseline] = getGlyphInfo(state);
const messages = state.messages;
// we need to know the size of the message box in order to draw its border
// and background. The algorithm to compute this is equivalent to drawing
// all messages. So we put the drawing algorithm in a function with a
// boolean argument that will control whether text should actually be
// drawn. This lets us run the algorithm once to get the dimensions and
// then again to actually draw text.
function renderMessages (draw: boolean) {
let renderedX = state.canvas.width;
let renderedY = state.canvas.height - charHeight + baseline;
for (let i = messages.length - 1; i >= 0; --i) {
const message = messages[i];
for (let j = message.length - 1; j >= 0; --j) {
const chars = Array.from(message[j][1]);
for (let k = chars.length - 1; k >= 0; --k) {
const char = chars[k];
const measuredWidth = measureWidth(state, char);
if (renderedX - measuredWidth < 0) {
if (renderedY - charHeight < 0) {
return;
}
renderedX = state.canvas.width;
renderedY = renderedY - charHeight;
}
renderedX = renderedX - measuredWidth;
if (draw) {
ctx.fillText(char, renderedX, renderedY);
}
if (renderedX < messagesPosition.x) {
messagesPosition.x = renderedX;
}
if (renderedY < messagesPosition.y) {
messagesPosition.y = renderedY - baseline;
}
}
}
renderedX = state.canvas.width;
renderedY = renderedY - charHeight;
}
}
renderMessages(false);
ctx.fillStyle = state.highlights[0].foreground;
ctx.fillRect(messagesPosition.x - 2,
messagesPosition.y - 2,
state.canvas.width - messagesPosition.x + 2,
state.canvas.height - messagesPosition.y + 2);
ctx.fillStyle = state.highlights[0].background;
ctx.fillRect(messagesPosition.x - 1,
messagesPosition.y - 1,
state.canvas.width - messagesPosition.x + 1,
state.canvas.height - messagesPosition.y + 1);
ctx.fillStyle = state.highlights[0].foreground;
renderMessages(true);
}
function paintCommandlineWindow(state: State) {
if (settings.cmdline === "none") {
return;
}
const ctx = state.context;
const [charWidth, charHeight, baseline] = getGlyphInfo(state);
const commandLine = state.commandLine;
const rect = getCommandLineRect(state);
// outer rectangle
ctx.fillStyle = state.highlights[0].foreground;
ctx.fillRect(rect.x,
rect.y,
rect.width,
rect.height);
// inner rectangle
rect.x += 1;
rect.y += 1;
rect.width -= 2;
rect.height -= 2;
ctx.fillStyle = state.highlights[0].background;
ctx.fillRect(rect.x,
rect.y,
rect.width,
rect.height);
// padding of inner rectangle
rect.x += 1;
rect.y += 1;
rect.width -= 2;
rect.height -= 2;
// Position where text should be drawn
let x = rect.x;
const y = rect.y;
// first character
ctx.fillStyle = state.highlights[0].foreground;
ctx.fillText(commandLine.firstc, x, y + baseline);
x += charWidth;
rect.width -= charWidth;
const encoder = new TextEncoder();
// reduce the commandline's content to a string for iteration
const str = commandLine.content.reduce((r: string, segment: [any, string]) => r + segment[1], "");
// Array.from(str) will return an array whose cells are grapheme
// clusters. It is important to iterate over graphemes instead of the
// string because iterating over the string would sometimes yield only
// half of the UTF-16 character/surrogate pair.
const characters = Array.from(str);
// renderedI is the horizontal pixel position where the next character
// should be drawn
let renderedI = 0;
// encodedI is the number of bytes that have been iterated over thus
// far. It is used to find out where to draw the cursor. Indeed, neovim
// sends the cursor's position as a byte position within the UTF-8
// encoded commandline string.
let encodedI = 0;
// cursorX is the horizontal pixel position where the cursor should be
// drawn.
let cursorX = 0;
// The index of the first character of `characters` that can be drawn.
// It is higher than 0 when the command line string is too long to be
// entirely displayed.
let sliceStart = 0;
// The index of the last character of `characters` that can be drawn.
// It is different from characters.length when the command line string
// is too long to be entirely displayed.
let sliceEnd = 0;
// The horizontal width in pixels taken by the displayed slice. It
// is used to keep track of whether the commandline string is longer
// than the commandline window.
let sliceWidth = 0;
// cursorDisplayed keeps track of whether the cursor can be displayed
// in the slice.
let cursorDisplayed = commandLine.pos === 0;
// description of the algorithm:
// For each character, find out its width. If it cannot fit in the
// command line window along with the rest of the slice and the cursor
// hasn't been found yet, remove characters from the beginning of the
// slice until the character fits.
// Stop either when all characters are in the slice or when the cursor
// can be displayed and the slice takes all available width.
for (let i = 0; i < characters.length; ++i) {
sliceEnd = i;
const char = characters[i];
const cWidth = measureWidth(state, char);
renderedI += cWidth;
sliceWidth += cWidth;
if (sliceWidth > rect.width) {
if (cursorDisplayed) {
break;
}
do {
const removedChar = characters[sliceStart];
const removedWidth = measureWidth(state, removedChar);
renderedI -= removedWidth;
sliceWidth -= removedWidth;
sliceStart += 1;
} while (sliceWidth > rect.width);
}
encodedI += encoder.encode(char).length;
if (encodedI === commandLine.pos) {
cursorX = renderedI;
cursorDisplayed = true;
}
}
if (characters.length > 0) {
renderedI = 0;
for (let i = sliceStart; i <= sliceEnd; ++i) {
const char = characters[i];
ctx.fillText(char, x + renderedI, y + baseline);
renderedI += measureWidth(state, char);
}
}
ctx.fillRect(x + cursorX, y, 1, charHeight);
}
function paint (_: DOMHighResTimeStamp) {
frameScheduled = false;
const state = globalState;
const canvas = state.canvas;
const context = state.context;
const gid = getGridId();
const charactersGrid = state.gridCharacters[gid];
const highlightsGrid = state.gridHighlights[gid];
const damages = state.gridDamages[gid];
const damageCount = state.gridDamagesCount[gid];
const highlights = state.highlights;
const [charWidth, charHeight, baseline] = getGlyphInfo(state);
for (let i = 0; i < damageCount; ++i) {
const damage = damages[i];
switch (damage.kind) {
case DamageKind.Resize: {
const pixelWidth = damage.w * charWidth / window.devicePixelRatio;
const pixelHeight = damage.h * charHeight / window.devicePixelRatio;
events.emit("frameResize", { width: pixelWidth, height: pixelHeight });
setCanvasDimensions(canvas, pixelWidth, pixelHeight);
// Note: changing width and height resets font, so we have to
// set it again. Who thought this was a good idea???
context.font = fontString;
}
break;
case DamageKind.Scroll:
case DamageKind.Cell:
for (let y = damage.y; y < damage.y + damage.h && y < charactersGrid.length; ++y) {
const row = charactersGrid[y];
const rowHigh = highlightsGrid[y];
const pixelY = y * charHeight;
for (let x = damage.x; x < damage.x + damage.w && x < row.length; ++x) {
if (row[x] === "") {
continue;
}
const pixelX = x * charWidth;
const id = glyphId(row[x], rowHigh[x]);
if (glyphCache[id] === undefined) {
const cellHigh = highlights[rowHigh[x]];
const width = Math.ceil(measureWidth(state, row[x]) / charWidth) * charWidth;
let background = cellHigh.background || highlights[0].background;
let foreground = cellHigh.foreground || highlights[0].foreground;
if (cellHigh.reverse) {
const tmp = background;
background = foreground;
foreground = tmp;
}
context.fillStyle = background;
context.fillRect(pixelX,
pixelY,
width,
charHeight);
context.fillStyle = foreground;
let fontStr = "";
let changeFont = false;
if (cellHigh.bold) {
fontStr += " bold ";
changeFont = true;
}
if (cellHigh.italic) {
fontStr += " italic ";
changeFont = true;
}
if (changeFont) {
context.font = fontStr + fontString;
}
context.fillText(row[x], pixelX, pixelY + baseline);
if (changeFont) {
context.font = fontString;
}
if (cellHigh.strikethrough) {
context.fillRect(pixelX, pixelY + baseline / 2, width, 1);
}
context.fillStyle = cellHigh.special;
const baselineHeight = (charHeight - baseline);
if (cellHigh.underline) {
const linepos = baselineHeight * 0.3;
context.fillRect(pixelX, pixelY + baseline + linepos, width, 1);
}
if (cellHigh.undercurl) {
const curlpos = baselineHeight * 0.6;
for (let abscissa = pixelX; abscissa < pixelX + width; ++abscissa) {
context.fillRect(abscissa,
pixelY + baseline + curlpos + Math.cos(abscissa),
1,
1);
}
}
// reason for the check: we can't retrieve pixels
// drawn outside the viewport
if (pixelX >= 0
&& pixelY >= 0
&& (pixelX + width < canvas.width)
&& (pixelY + charHeight < canvas.height)
&& width > 0 && charHeight > 0) {
glyphCache[id] = context.getImageData(
pixelX,
pixelY,
width,
charHeight);
}
} else {
context.putImageData(glyphCache[id], pixelX, pixelY);
}
}
}
break;
}
}
if (state.messages.length > 0) {
paintMessages(state);
}
// If the command line is shown, the cursor's in it
if (state.commandLine.status === "shown") {
paintCommandlineWindow(state);
} else if (state.cursor.display) {
const cursor = state.cursor;
if (cursor.currentGrid === gid) {