aboutsummaryrefslogtreecommitdiffstats
path: root/node_modules/xterm/src/browser/services/CharacterJoinerService.ts
blob: ca4f1984e36a9e5303744c0394dc4c271c2f9085 (plain)
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
/**
 * Copyright (c) 2018 The xterm.js authors. All rights reserved.
 * @license MIT
 */

import { IBufferLine, ICellData, CharData } from 'common/Types';
import { ICharacterJoiner } from 'browser/Types';
import { AttributeData } from 'common/buffer/AttributeData';
import { WHITESPACE_CELL_CHAR, Content } from 'common/buffer/Constants';
import { CellData } from 'common/buffer/CellData';
import { IBufferService } from 'common/services/Services';
import { ICharacterJoinerService } from 'browser/services/Services';

export class JoinedCellData extends AttributeData implements ICellData {
  private _width: number;
  // .content carries no meaning for joined CellData, simply nullify it
  // thus we have to overload all other .content accessors
  public content: number = 0;
  public fg: number;
  public bg: number;
  public combinedData: string = '';

  constructor(firstCell: ICellData, chars: string, width: number) {
    super();
    this.fg = firstCell.fg;
    this.bg = firstCell.bg;
    this.combinedData = chars;
    this._width = width;
  }

  public isCombined(): number {
    // always mark joined cell data as combined
    return Content.IS_COMBINED_MASK;
  }

  public getWidth(): number {
    return this._width;
  }

  public getChars(): string {
    return this.combinedData;
  }

  public getCode(): number {
    // code always gets the highest possible fake codepoint (read as -1)
    // this is needed as code is used by caches as identifier
    return 0x1FFFFF;
  }

  public setFromCharData(value: CharData): void {
    throw new Error('not implemented');
  }

  public getAsCharData(): CharData {
    return [this.fg, this.getChars(), this.getWidth(), this.getCode()];
  }
}

export class CharacterJoinerService implements ICharacterJoinerService {
  public serviceBrand: undefined;

  private _characterJoiners: ICharacterJoiner[] = [];
  private _nextCharacterJoinerId: number = 0;
  private _workCell: CellData = new CellData();

  constructor(
    @IBufferService private _bufferService: IBufferService
  ) { }

  public register(handler: (text: string) => [number, number][]): number {
    const joiner: ICharacterJoiner = {
      id: this._nextCharacterJoinerId++,
      handler
    };

    this._characterJoiners.push(joiner);
    return joiner.id;
  }

  public deregister(joinerId: number): boolean {
    for (let i = 0; i < this._characterJoiners.length; i++) {
      if (this._characterJoiners[i].id === joinerId) {
        this._characterJoiners.splice(i, 1);
        return true;
      }
    }

    return false;
  }

  public getJoinedCharacters(row: number): [number, number][] {
    if (this._characterJoiners.length === 0) {
      return [];
    }

    const line = this._bufferService.buffer.lines.get(row);
    if (!line || line.length === 0) {
      return [];
    }

    const ranges: [number, number][] = [];
    const lineStr = line.translateToString(true);

    // Because some cells can be represented by multiple javascript characters,
    // we track the cell and the string indexes separately. This allows us to
    // translate the string ranges we get from the joiners back into cell ranges
    // for use when rendering
    let rangeStartColumn = 0;
    let currentStringIndex = 0;
    let rangeStartStringIndex = 0;
    let rangeAttrFG = line.getFg(0);
    let rangeAttrBG = line.getBg(0);

    for (let x = 0; x < line.getTrimmedLength(); x++) {
      line.loadCell(x, this._workCell);

      if (this._workCell.getWidth() === 0) {
        // If this character is of width 0, skip it.
        continue;
      }

      // End of range
      if (this._workCell.fg !== rangeAttrFG || this._workCell.bg !== rangeAttrBG) {
        // If we ended up with a sequence of more than one character,
        // look for ranges to join.
        if (x - rangeStartColumn > 1) {
          const joinedRanges = this._getJoinedRanges(
            lineStr,
            rangeStartStringIndex,
            currentStringIndex,
            line,
            rangeStartColumn
          );
          for (let i = 0; i < joinedRanges.length; i++) {
            ranges.push(joinedRanges[i]);
          }
        }

        // Reset our markers for a new range.
        rangeStartColumn = x;
        rangeStartStringIndex = currentStringIndex;
        rangeAttrFG = this._workCell.fg;
        rangeAttrBG = this._workCell.bg;
      }

      currentStringIndex += this._workCell.getChars().length || WHITESPACE_CELL_CHAR.length;
    }

    // Process any trailing ranges.
    if (this._bufferService.cols - rangeStartColumn > 1) {
      const joinedRanges = this._getJoinedRanges(
        lineStr,
        rangeStartStringIndex,
        currentStringIndex,
        line,
        rangeStartColumn
      );
      for (let i = 0; i < joinedRanges.length; i++) {
        ranges.push(joinedRanges[i]);
      }
    }

    return ranges;
  }

  /**
   * Given a segment of a line of text, find all ranges of text that should be
   * joined in a single rendering unit. Ranges are internally converted to
   * column ranges, rather than string ranges.
   * @param line String representation of the full line of text
   * @param startIndex Start position of the range to search in the string (inclusive)
   * @param endIndex End position of the range to search in the string (exclusive)
   */
  private _getJoinedRanges(line: string, startIndex: number, endIndex: number, lineData: IBufferLine, startCol: number): [number, number][] {
    const text = line.substring(startIndex, endIndex);
    // At this point we already know that there is at least one joiner so
    // we can just pull its value and assign it directly rather than
    // merging it into an empty array, which incurs unnecessary writes.
    let allJoinedRanges: [number, number][] = [];
    try {
      allJoinedRanges = this._characterJoiners[0].handler(text);
    } catch (error) {
      console.error(error);
    }
    for (let i = 1; i < this._characterJoiners.length; i++) {
      // We merge any overlapping ranges across the different joiners
      try {
        const joinerRanges = this._characterJoiners[i].handler(text);
        for (let j = 0; j < joinerRanges.length; j++) {
          CharacterJoinerService._mergeRanges(allJoinedRanges, joinerRanges[j]);
        }
      } catch (error) {
        console.error(error);
      }
    }
    this._stringRangesToCellRanges(allJoinedRanges, lineData, startCol);
    return allJoinedRanges;
  }

  /**
   * Modifies the provided ranges in-place to adjust for variations between
   * string length and cell width so that the range represents a cell range,
   * rather than the string range the joiner provides.
   * @param ranges String ranges containing start (inclusive) and end (exclusive) index
   * @param line Cell data for the relevant line in the terminal
   * @param startCol Offset within the line to start from
   */
  private _stringRangesToCellRanges(ranges: [number, number][], line: IBufferLine, startCol: number): void {
    let currentRangeIndex = 0;
    let currentRangeStarted = false;
    let currentStringIndex = 0;
    let currentRange = ranges[currentRangeIndex];

    // If we got through all of the ranges, stop searching
    if (!currentRange) {
      return;
    }

    for (let x = startCol; x < this._bufferService.cols; x++) {
      const width = line.getWidth(x);
      const length = line.getString(x).length || WHITESPACE_CELL_CHAR.length;

      // We skip zero-width characters when creating the string to join the text
      // so we do the same here
      if (width === 0) {
        continue;
      }

      // Adjust the start of the range
      if (!currentRangeStarted && currentRange[0] <= currentStringIndex) {
        currentRange[0] = x;
        currentRangeStarted = true;
      }

      // Adjust the end of the range
      if (currentRange[1] <= currentStringIndex) {
        currentRange[1] = x;

        // We're finished with this range, so we move to the next one
        currentRange = ranges[++currentRangeIndex];

        // If there are no more ranges left, stop searching
        if (!currentRange) {
          break;
        }

        // Ranges can be on adjacent characters. Because the end index of the
        // ranges are exclusive, this means that the index for the start of a
        // range can be the same as the end index of the previous range. To
        // account for the start of the next range, we check here just in case.
        if (currentRange[0] <= currentStringIndex) {
          currentRange[0] = x;
          currentRangeStarted = true;
        } else {
          currentRangeStarted = false;
        }
      }

      // Adjust the string index based on the character length to line up with
      // the column adjustment
      currentStringIndex += length;
    }

    // If there is still a range left at the end, it must extend all the way to
    // the end of the line.
    if (currentRange) {
      currentRange[1] = this._bufferService.cols;
    }
  }

  /**
   * Merges the range defined by the provided start and end into the list of
   * existing ranges. The merge is done in place on the existing range for
   * performance and is also returned.
   * @param ranges Existing range list
   * @param newRange Tuple of two numbers representing the new range to merge in.
   * @returns The ranges input with the new range merged in place
   */
  private static _mergeRanges(ranges: [number, number][], newRange: [number, number]): [number, number][] {
    let inRange = false;
    for (let i = 0; i < ranges.length; i++) {
      const range = ranges[i];
      if (!inRange) {
        if (newRange[1] <= range[0]) {
          // Case 1: New range is before the search range
          ranges.splice(i, 0, newRange);
          return ranges;
        }

        if (newRange[1] <= range[1]) {
          // Case 2: New range is either wholly contained within the
          // search range or overlaps with the front of it
          range[0] = Math.min(newRange[0], range[0]);
          return ranges;
        }

        if (newRange[0] < range[1]) {
          // Case 3: New range either wholly contains the search range
          // or overlaps with the end of it
          range[0] = Math.min(newRange[0], range[0]);
          inRange = true;
        }

        // Case 4: New range starts after the search range
        continue;
      } else {
        if (newRange[1] <= range[0]) {
          // Case 5: New range extends from previous range but doesn't
          // reach the current one
          ranges[i - 1][1] = newRange[1];
          return ranges;
        }

        if (newRange[1] <= range[1]) {
          // Case 6: New range extends from prvious range into the
          // current range
          ranges[i - 1][1] = Math.max(newRange[1], range[1]);
          ranges.splice(i, 1);
          return ranges;
        }

        // Case 7: New range extends from previous range past the
        // end of the current range
        ranges.splice(i, 1);
        i--;
      }
    }

    if (inRange) {
      // Case 8: New range extends past the last existing range
      ranges[ranges.length - 1][1] = newRange[1];
    } else {
      // Case 9: New range starts after the last existing range
      ranges.push(newRange);
    }

    return ranges;
  }
}