Path: blob/main/src/vs/editor/browser/controller/editContext/textArea/textAreaEditContext.ts
5240 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45import './textAreaEditContext.css';6import * as nls from '../../../../../nls.js';7import * as browser from '../../../../../base/browser/browser.js';8import { FastDomNode, createFastDomNode } from '../../../../../base/browser/fastDomNode.js';9import { IKeyboardEvent } from '../../../../../base/browser/keyboardEvent.js';10import * as platform from '../../../../../base/common/platform.js';11import * as strings from '../../../../../base/common/strings.js';12import { applyFontInfo } from '../../../config/domFontInfo.js';13import { ViewController } from '../../../view/viewController.js';14import { PartFingerprint, PartFingerprints } from '../../../view/viewPart.js';15import { LineNumbersOverlay } from '../../../viewParts/lineNumbers/lineNumbers.js';16import { Margin } from '../../../viewParts/margin/margin.js';17import { RenderLineNumbersType, EditorOption, IComputedEditorOptions, EditorOptions } from '../../../../common/config/editorOptions.js';18import { FontInfo } from '../../../../common/config/fontInfo.js';19import { Position } from '../../../../common/core/position.js';20import { Range } from '../../../../common/core/range.js';21import { Selection } from '../../../../common/core/selection.js';22import { ScrollType } from '../../../../common/editorCommon.js';23import { EndOfLinePreference } from '../../../../common/model.js';24import { RenderingContext, RestrictedRenderingContext, HorizontalPosition, LineVisibleRanges } from '../../../view/renderingContext.js';25import { ViewContext } from '../../../../common/viewModel/viewContext.js';26import * as viewEvents from '../../../../common/viewEvents.js';27import { AccessibilitySupport } from '../../../../../platform/accessibility/common/accessibility.js';28import { IEditorAriaOptions } from '../../../editorBrowser.js';29import { MOUSE_CURSOR_TEXT_CSS_CLASS_NAME } from '../../../../../base/browser/ui/mouseCursor/mouseCursor.js';30import { TokenizationRegistry } from '../../../../common/languages.js';31import { ColorId, ITokenPresentation } from '../../../../common/encodedTokenAttributes.js';32import { Color } from '../../../../../base/common/color.js';33import { IME } from '../../../../../base/common/ime.js';34import { IKeybindingService } from '../../../../../platform/keybinding/common/keybinding.js';35import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js';36import { AbstractEditContext } from '../editContext.js';37import { ICompositionData, IPasteData, ITextAreaInputHost, TextAreaInput, TextAreaWrapper } from './textAreaEditContextInput.js';38import { ariaLabelForScreenReaderContent, newlinecount, SimplePagedScreenReaderStrategy } from '../screenReaderUtils.js';39import { _debugComposition, ITypeData, TextAreaState } from './textAreaEditContextState.js';40import { getMapForWordSeparators, WordCharacterClass } from '../../../../common/core/wordCharacterClassifier.js';41import { TextAreaEditContextRegistry } from './textAreaEditContextRegistry.js';4243export interface IVisibleRangeProvider {44visibleRangeForPosition(position: Position): HorizontalPosition | null;45linesVisibleRangesForRange(range: Range, includeNewLines: boolean): LineVisibleRanges[] | null;46}4748class VisibleTextAreaData {49_visibleTextAreaBrand: void = undefined;5051public startPosition: Position | null = null;52public endPosition: Position | null = null;5354public visibleTextareaStart: HorizontalPosition | null = null;55public visibleTextareaEnd: HorizontalPosition | null = null;5657/**58* When doing composition, the currently composed text might be split up into59* multiple tokens, then merged again into a single token, etc. Here we attempt60* to keep the presentation of the <textarea> stable by using the previous used61* style if multiple tokens come into play. This avoids flickering.62*/63private _previousPresentation: ITokenPresentation | null = null;6465constructor(66private readonly _context: ViewContext,67public readonly modelLineNumber: number,68public readonly distanceToModelLineStart: number,69public readonly widthOfHiddenLineTextBefore: number,70public readonly distanceToModelLineEnd: number,71) {72}7374prepareRender(visibleRangeProvider: IVisibleRangeProvider): void {75const startModelPosition = new Position(this.modelLineNumber, this.distanceToModelLineStart + 1);76const endModelPosition = new Position(this.modelLineNumber, this._context.viewModel.model.getLineMaxColumn(this.modelLineNumber) - this.distanceToModelLineEnd);7778this.startPosition = this._context.viewModel.coordinatesConverter.convertModelPositionToViewPosition(startModelPosition);79this.endPosition = this._context.viewModel.coordinatesConverter.convertModelPositionToViewPosition(endModelPosition);8081if (this.startPosition.lineNumber === this.endPosition.lineNumber) {82this.visibleTextareaStart = visibleRangeProvider.visibleRangeForPosition(this.startPosition);83this.visibleTextareaEnd = visibleRangeProvider.visibleRangeForPosition(this.endPosition);84} else {85// TODO: what if the view positions are not on the same line?86this.visibleTextareaStart = null;87this.visibleTextareaEnd = null;88}89}9091definePresentation(tokenPresentation: ITokenPresentation | null): ITokenPresentation {92if (!this._previousPresentation) {93// To avoid flickering, once set, always reuse a presentation throughout the entire IME session94if (tokenPresentation) {95this._previousPresentation = tokenPresentation;96} else {97this._previousPresentation = {98foreground: ColorId.DefaultForeground,99italic: false,100bold: false,101underline: false,102strikethrough: false,103};104}105}106return this._previousPresentation;107}108}109110const canUseZeroSizeTextarea = (browser.isFirefox);111112export class TextAreaEditContext extends AbstractEditContext {113114private readonly _viewController: ViewController;115private readonly _visibleRangeProvider: IVisibleRangeProvider;116private _scrollLeft: number;117private _scrollTop: number;118119private _accessibilitySupport!: AccessibilitySupport;120private _accessibilityPageSize!: number;121private _textAreaWrapping!: boolean;122private _textAreaWidth!: number;123private _contentLeft: number;124private _contentWidth: number;125private _contentHeight: number;126private _fontInfo: FontInfo;127private _emptySelectionClipboard: boolean;128129/**130* Defined only when the text area is visible (composition case).131*/132private _visibleTextArea: VisibleTextAreaData | null;133private _selections: Selection[];134private _modelSelections: Selection[];135136/**137* The position at which the textarea was rendered.138* This is useful for hit-testing and determining the mouse position.139*/140private _lastRenderPosition: Position | null;141142public readonly textArea: FastDomNode<HTMLTextAreaElement>;143public readonly textAreaCover: FastDomNode<HTMLElement>;144private readonly _textAreaInput: TextAreaInput;145146constructor(147ownerID: string,148context: ViewContext,149overflowGuardContainer: FastDomNode<HTMLElement>,150viewController: ViewController,151visibleRangeProvider: IVisibleRangeProvider,152@IKeybindingService private readonly _keybindingService: IKeybindingService,153@IInstantiationService private readonly _instantiationService: IInstantiationService154) {155super(context);156157this._viewController = viewController;158this._visibleRangeProvider = visibleRangeProvider;159this._scrollLeft = 0;160this._scrollTop = 0;161162const options = this._context.configuration.options;163const layoutInfo = options.get(EditorOption.layoutInfo);164165this._setAccessibilityOptions(options);166this._contentLeft = layoutInfo.contentLeft;167this._contentWidth = layoutInfo.contentWidth;168this._contentHeight = layoutInfo.height;169this._fontInfo = options.get(EditorOption.fontInfo);170this._emptySelectionClipboard = options.get(EditorOption.emptySelectionClipboard);171172this._visibleTextArea = null;173this._selections = [new Selection(1, 1, 1, 1)];174this._modelSelections = [new Selection(1, 1, 1, 1)];175this._lastRenderPosition = null;176177// Text Area (The focus will always be in the textarea when the cursor is blinking)178this.textArea = createFastDomNode(document.createElement('textarea'));179PartFingerprints.write(this.textArea, PartFingerprint.TextArea);180this.textArea.setClassName(`inputarea ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);181this.textArea.setAttribute('wrap', this._textAreaWrapping && !this._visibleTextArea ? 'on' : 'off');182const { tabSize } = this._context.viewModel.model.getOptions();183this.textArea.domNode.style.tabSize = `${tabSize * this._fontInfo.spaceWidth}px`;184this.textArea.setAttribute('autocorrect', 'off');185this.textArea.setAttribute('autocapitalize', 'off');186this.textArea.setAttribute('autocomplete', 'off');187this.textArea.setAttribute('spellcheck', 'false');188this.textArea.setAttribute('aria-label', ariaLabelForScreenReaderContent(options, this._keybindingService));189this.textArea.setAttribute('aria-required', options.get(EditorOption.ariaRequired) ? 'true' : 'false');190this.textArea.setAttribute('tabindex', String(options.get(EditorOption.tabIndex)));191this.textArea.setAttribute('role', 'textbox');192this.textArea.setAttribute('aria-roledescription', nls.localize('editor', "editor"));193this.textArea.setAttribute('aria-multiline', 'true');194this.textArea.setAttribute('aria-autocomplete', options.get(EditorOption.readOnly) ? 'none' : 'both');195196this._ensureReadOnlyAttribute();197198this.textAreaCover = createFastDomNode(document.createElement('div'));199this.textAreaCover.setPosition('absolute');200201overflowGuardContainer.appendChild(this.textArea);202overflowGuardContainer.appendChild(this.textAreaCover);203204const simplePagedScreenReaderStrategy = new SimplePagedScreenReaderStrategy();205const textAreaInputHost: ITextAreaInputHost = {206context: this._context,207getScreenReaderContent: (): TextAreaState => {208if (this._accessibilitySupport === AccessibilitySupport.Disabled) {209// We know for a fact that a screen reader is not attached210// On OSX, we write the character before the cursor to allow for "long-press" composition211// Also on OSX, we write the word before the cursor to allow for the Accessibility Keyboard to give good hints212const selection = this._selections[0];213if (platform.isMacintosh && selection.isEmpty()) {214const position = selection.getStartPosition();215216let textBefore = this._getWordBeforePosition(position);217if (textBefore.length === 0) {218textBefore = this._getCharacterBeforePosition(position);219}220221if (textBefore.length > 0) {222return new TextAreaState(textBefore, textBefore.length, textBefore.length, Range.fromPositions(position), 0);223}224}225// on macOS, write current selection into textarea will allow system text services pick selected text,226// but we still want to limit the amount of text given Chromium handles very poorly text even of a few227// thousand chars228// (https://github.com/microsoft/vscode/issues/27799)229const LIMIT_CHARS = 500;230if (platform.isMacintosh && !selection.isEmpty() && this._context.viewModel.getValueLengthInRange(selection, EndOfLinePreference.TextDefined) < LIMIT_CHARS) {231const text = this._context.viewModel.getValueInRange(selection, EndOfLinePreference.TextDefined);232return new TextAreaState(text, 0, text.length, selection, 0);233}234235// on Safari, document.execCommand('cut') and document.execCommand('copy') will just not work236// if the textarea has no content selected. So if there is an editor selection, ensure something237// is selected in the textarea.238if (browser.isSafari && !selection.isEmpty()) {239const placeholderText = 'vscode-placeholder';240return new TextAreaState(placeholderText, 0, placeholderText.length, null, undefined);241}242243return TextAreaState.EMPTY;244}245246if (browser.isAndroid) {247// when tapping in the editor on a word, Android enters composition mode.248// in the `compositionstart` event we cannot clear the textarea, because249// it then forgets to ever send a `compositionend`.250// we therefore only write the current word in the textarea251const selection = this._selections[0];252if (selection.isEmpty()) {253const position = selection.getStartPosition();254const [wordAtPosition, positionOffsetInWord] = this._getAndroidWordAtPosition(position);255if (wordAtPosition.length > 0) {256return new TextAreaState(wordAtPosition, positionOffsetInWord, positionOffsetInWord, Range.fromPositions(position), 0);257}258}259return TextAreaState.EMPTY;260}261262const screenReaderContentState = simplePagedScreenReaderStrategy.fromEditorSelection(this._context.viewModel, this._selections[0], this._accessibilityPageSize, this._accessibilitySupport === AccessibilitySupport.Unknown);263return TextAreaState.fromScreenReaderContentState(screenReaderContentState);264},265266deduceModelPosition: (viewAnchorPosition: Position, deltaOffset: number, lineFeedCnt: number): Position => {267return this._context.viewModel.deduceModelPositionRelativeToViewPosition(viewAnchorPosition, deltaOffset, lineFeedCnt);268}269};270271const textAreaWrapper = this._register(new TextAreaWrapper(this.textArea.domNode));272this._textAreaInput = this._register(this._instantiationService.createInstance(TextAreaInput, textAreaInputHost, textAreaWrapper, platform.OS, {273isAndroid: browser.isAndroid,274isChrome: browser.isChrome,275isFirefox: browser.isFirefox,276isSafari: browser.isSafari,277}));278279// Relay clipboard events from TextAreaInput280this._register(this._textAreaInput.onWillCopy(e => this._onWillCopy.fire(e)));281this._register(this._textAreaInput.onWillCut(e => this._onWillCut.fire(e)));282this._register(this._textAreaInput.onWillPaste(e => this._onWillPaste.fire(e)));283284this._register(this._textAreaInput.onKeyDown((e: IKeyboardEvent) => {285this._viewController.emitKeyDown(e);286}));287288this._register(this._textAreaInput.onKeyUp((e: IKeyboardEvent) => {289this._viewController.emitKeyUp(e);290}));291292this._register(this._textAreaInput.onPaste((e: IPasteData) => {293let pasteOnNewLine = false;294let multicursorText: string[] | null = null;295let mode: string | null = null;296if (e.metadata) {297pasteOnNewLine = (this._emptySelectionClipboard && !!e.metadata.isFromEmptySelection);298multicursorText = (typeof e.metadata.multicursorText !== 'undefined' ? e.metadata.multicursorText : null);299mode = e.metadata.mode;300}301this._viewController.paste(e.text, pasteOnNewLine, multicursorText, mode);302}));303304this._register(this._textAreaInput.onCut(() => {305this._viewController.cut();306}));307308this._register(this._textAreaInput.onType((e: ITypeData) => {309if (e.replacePrevCharCnt || e.replaceNextCharCnt || e.positionDelta) {310// must be handled through the new command311if (_debugComposition) {312console.log(` => compositionType: <<${e.text}>>, ${e.replacePrevCharCnt}, ${e.replaceNextCharCnt}, ${e.positionDelta}`);313}314this._viewController.compositionType(e.text, e.replacePrevCharCnt, e.replaceNextCharCnt, e.positionDelta);315} else {316if (_debugComposition) {317console.log(` => type: <<${e.text}>>`);318}319this._viewController.type(e.text);320}321}));322323this._register(this._textAreaInput.onSelectionChangeRequest((modelSelection: Selection) => {324this._viewController.setSelection(modelSelection);325}));326327this._register(this._textAreaInput.onCompositionStart((e) => {328329// The textarea might contain some content when composition starts.330//331// When we make the textarea visible, it always has a height of 1 line,332// so we don't need to worry too much about content on lines above or below333// the selection.334//335// However, the text on the current line needs to be made visible because336// some IME methods allow to move to other glyphs on the current line337// (by pressing arrow keys).338//339// (1) The textarea might contain only some parts of the current line,340// like the word before the selection. Also, the content inside the textarea341// can grow or shrink as composition occurs. We therefore anchor the textarea342// in terms of distance to a certain line start and line end.343//344// (2) Also, we should not make \t characters visible, because their rendering345// inside the <textarea> will not align nicely with our rendering. We therefore346// will hide (if necessary) some of the leading text on the current line.347348const ta = this.textArea.domNode;349const modelSelection = this._modelSelections[0];350351const { distanceToModelLineStart, widthOfHiddenTextBefore } = (() => {352// Find the text that is on the current line before the selection353const textBeforeSelection = ta.value.substring(0, Math.min(ta.selectionStart, ta.selectionEnd));354const lineFeedOffset1 = textBeforeSelection.lastIndexOf('\n');355const lineTextBeforeSelection = textBeforeSelection.substring(lineFeedOffset1 + 1);356357// We now search to see if we should hide some part of it (if it contains \t)358const tabOffset1 = lineTextBeforeSelection.lastIndexOf('\t');359const desiredVisibleBeforeCharCount = lineTextBeforeSelection.length - tabOffset1 - 1;360const startModelPosition = modelSelection.getStartPosition();361const visibleBeforeCharCount = Math.min(startModelPosition.column - 1, desiredVisibleBeforeCharCount);362const distanceToModelLineStart = startModelPosition.column - 1 - visibleBeforeCharCount;363const hiddenLineTextBefore = lineTextBeforeSelection.substring(0, lineTextBeforeSelection.length - visibleBeforeCharCount);364const { tabSize } = this._context.viewModel.model.getOptions();365const widthOfHiddenTextBefore = measureText(this.textArea.domNode.ownerDocument, hiddenLineTextBefore, this._fontInfo, tabSize);366367return { distanceToModelLineStart, widthOfHiddenTextBefore };368})();369370const { distanceToModelLineEnd } = (() => {371// Find the text that is on the current line after the selection372const textAfterSelection = ta.value.substring(Math.max(ta.selectionStart, ta.selectionEnd));373const lineFeedOffset2 = textAfterSelection.indexOf('\n');374const lineTextAfterSelection = lineFeedOffset2 === -1 ? textAfterSelection : textAfterSelection.substring(0, lineFeedOffset2);375376const tabOffset2 = lineTextAfterSelection.indexOf('\t');377const desiredVisibleAfterCharCount = (tabOffset2 === -1 ? lineTextAfterSelection.length : lineTextAfterSelection.length - tabOffset2 - 1);378const endModelPosition = modelSelection.getEndPosition();379const visibleAfterCharCount = Math.min(this._context.viewModel.model.getLineMaxColumn(endModelPosition.lineNumber) - endModelPosition.column, desiredVisibleAfterCharCount);380const distanceToModelLineEnd = this._context.viewModel.model.getLineMaxColumn(endModelPosition.lineNumber) - endModelPosition.column - visibleAfterCharCount;381382return { distanceToModelLineEnd };383})();384385// Scroll to reveal the location in the editor where composition occurs386this._context.viewModel.revealRange(387'keyboard',388true,389Range.fromPositions(this._selections[0].getStartPosition()),390viewEvents.VerticalRevealType.Simple,391ScrollType.Immediate392);393394this._visibleTextArea = new VisibleTextAreaData(395this._context,396modelSelection.startLineNumber,397distanceToModelLineStart,398widthOfHiddenTextBefore,399distanceToModelLineEnd,400);401402// We turn off wrapping if the <textarea> becomes visible for composition403this.textArea.setAttribute('wrap', this._textAreaWrapping && !this._visibleTextArea ? 'on' : 'off');404405this._visibleTextArea.prepareRender(this._visibleRangeProvider);406this._render();407408// Show the textarea409this.textArea.setClassName(`inputarea ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME} ime-input`);410411this._viewController.compositionStart();412this._context.viewModel.onCompositionStart();413}));414415this._register(this._textAreaInput.onCompositionUpdate((e: ICompositionData) => {416if (!this._visibleTextArea) {417return;418}419420this._visibleTextArea.prepareRender(this._visibleRangeProvider);421this._render();422}));423424this._register(this._textAreaInput.onCompositionEnd(() => {425426this._visibleTextArea = null;427428// We turn on wrapping as necessary if the <textarea> hides after composition429this.textArea.setAttribute('wrap', this._textAreaWrapping && !this._visibleTextArea ? 'on' : 'off');430431this._render();432433this.textArea.setClassName(`inputarea ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);434this._viewController.compositionEnd();435this._context.viewModel.onCompositionEnd();436}));437438this._register(this._textAreaInput.onFocus(() => {439this._context.viewModel.setHasFocus(true);440}));441442this._register(this._textAreaInput.onBlur(() => {443this._context.viewModel.setHasFocus(false);444}));445446this._register(IME.onDidChange(() => {447this._ensureReadOnlyAttribute();448}));449450this._register(TextAreaEditContextRegistry.register(ownerID, this));451}452453public get domNode() {454return this.textArea;455}456457public writeScreenReaderContent(reason: string): void {458this._textAreaInput.writeNativeTextAreaContent(reason);459}460461public getTextAreaDomNode(): HTMLTextAreaElement {462return this.textArea.domNode;463}464465public override dispose(): void {466super.dispose();467this.textArea.domNode.remove();468this.textAreaCover.domNode.remove();469}470471private _getAndroidWordAtPosition(position: Position): [string, number] {472const ANDROID_WORD_SEPARATORS = '`~!@#$%^&*()-=+[{]}\\|;:",.<>/?';473const lineContent = this._context.viewModel.getLineContent(position.lineNumber);474const wordSeparators = getMapForWordSeparators(ANDROID_WORD_SEPARATORS, []);475476let goingLeft = true;477let startColumn = position.column;478let goingRight = true;479let endColumn = position.column;480let distance = 0;481while (distance < 50 && (goingLeft || goingRight)) {482if (goingLeft && startColumn <= 1) {483goingLeft = false;484}485if (goingLeft) {486const charCode = lineContent.charCodeAt(startColumn - 2);487const charClass = wordSeparators.get(charCode);488if (charClass !== WordCharacterClass.Regular) {489goingLeft = false;490} else {491startColumn--;492}493}494if (goingRight && endColumn > lineContent.length) {495goingRight = false;496}497if (goingRight) {498const charCode = lineContent.charCodeAt(endColumn - 1);499const charClass = wordSeparators.get(charCode);500if (charClass !== WordCharacterClass.Regular) {501goingRight = false;502} else {503endColumn++;504}505}506distance++;507}508509return [lineContent.substring(startColumn - 1, endColumn - 1), position.column - startColumn];510}511512private _getWordBeforePosition(position: Position): string {513const lineContent = this._context.viewModel.getLineContent(position.lineNumber);514const wordSeparators = getMapForWordSeparators(this._context.configuration.options.get(EditorOption.wordSeparators), []);515516let column = position.column;517let distance = 0;518while (column > 1) {519const charCode = lineContent.charCodeAt(column - 2);520const charClass = wordSeparators.get(charCode);521if (charClass !== WordCharacterClass.Regular || distance > 50) {522return lineContent.substring(column - 1, position.column - 1);523}524distance++;525column--;526}527return lineContent.substring(0, position.column - 1);528}529530private _getCharacterBeforePosition(position: Position): string {531if (position.column > 1) {532const lineContent = this._context.viewModel.getLineContent(position.lineNumber);533const charBefore = lineContent.charAt(position.column - 2);534if (!strings.isHighSurrogate(charBefore.charCodeAt(0))) {535return charBefore;536}537}538return '';539}540541private _setAccessibilityOptions(options: IComputedEditorOptions): void {542this._accessibilitySupport = options.get(EditorOption.accessibilitySupport);543const accessibilityPageSize = options.get(EditorOption.accessibilityPageSize);544if (this._accessibilitySupport === AccessibilitySupport.Enabled && accessibilityPageSize === EditorOptions.accessibilityPageSize.defaultValue) {545// If a screen reader is attached and the default value is not set we should automatically increase the page size to 500 for a better experience546this._accessibilityPageSize = 500;547} else {548this._accessibilityPageSize = accessibilityPageSize;549}550551// When wrapping is enabled and a screen reader might be attached,552// we will size the textarea to match the width used for wrapping points computation (see `domLineBreaksComputer.ts`).553// This is because screen readers will read the text in the textarea and we'd like that the554// wrapping points in the textarea match the wrapping points in the editor.555const layoutInfo = options.get(EditorOption.layoutInfo);556const wrappingColumn = layoutInfo.wrappingColumn;557if (wrappingColumn !== -1 && this._accessibilitySupport !== AccessibilitySupport.Disabled) {558const fontInfo = options.get(EditorOption.fontInfo);559this._textAreaWrapping = true;560this._textAreaWidth = Math.round(wrappingColumn * fontInfo.typicalHalfwidthCharacterWidth);561} else {562this._textAreaWrapping = false;563this._textAreaWidth = (canUseZeroSizeTextarea ? 0 : 1);564}565}566567// --- begin event handlers568569public override onConfigurationChanged(e: viewEvents.ViewConfigurationChangedEvent): boolean {570const options = this._context.configuration.options;571const layoutInfo = options.get(EditorOption.layoutInfo);572573this._setAccessibilityOptions(options);574this._contentLeft = layoutInfo.contentLeft;575this._contentWidth = layoutInfo.contentWidth;576this._contentHeight = layoutInfo.height;577this._fontInfo = options.get(EditorOption.fontInfo);578this._emptySelectionClipboard = options.get(EditorOption.emptySelectionClipboard);579this.textArea.setAttribute('wrap', this._textAreaWrapping && !this._visibleTextArea ? 'on' : 'off');580const { tabSize } = this._context.viewModel.model.getOptions();581this.textArea.domNode.style.tabSize = `${tabSize * this._fontInfo.spaceWidth}px`;582this.textArea.setAttribute('aria-label', ariaLabelForScreenReaderContent(options, this._keybindingService));583this.textArea.setAttribute('aria-required', options.get(EditorOption.ariaRequired) ? 'true' : 'false');584this.textArea.setAttribute('tabindex', String(options.get(EditorOption.tabIndex)));585586if (e.hasChanged(EditorOption.domReadOnly) || e.hasChanged(EditorOption.readOnly)) {587this._ensureReadOnlyAttribute();588}589590if (e.hasChanged(EditorOption.accessibilitySupport)) {591this._textAreaInput.writeNativeTextAreaContent('strategy changed');592}593594return true;595}596public override onCursorStateChanged(e: viewEvents.ViewCursorStateChangedEvent): boolean {597this._selections = e.selections.slice(0);598this._modelSelections = e.modelSelections.slice(0);599// We must update the <textarea> synchronously, otherwise long press IME on macos breaks.600// See https://github.com/microsoft/vscode/issues/165821601this._textAreaInput.writeNativeTextAreaContent('selection changed');602return true;603}604public override onDecorationsChanged(e: viewEvents.ViewDecorationsChangedEvent): boolean {605// true for inline decorations that can end up relayouting text606return true;607}608public override onFlushed(e: viewEvents.ViewFlushedEvent): boolean {609return true;610}611public override onLinesChanged(e: viewEvents.ViewLinesChangedEvent): boolean {612return true;613}614public override onLinesDeleted(e: viewEvents.ViewLinesDeletedEvent): boolean {615return true;616}617public override onLinesInserted(e: viewEvents.ViewLinesInsertedEvent): boolean {618return true;619}620public override onScrollChanged(e: viewEvents.ViewScrollChangedEvent): boolean {621this._scrollLeft = e.scrollLeft;622this._scrollTop = e.scrollTop;623return true;624}625public override onZonesChanged(e: viewEvents.ViewZonesChangedEvent): boolean {626return true;627}628629// --- end event handlers630631// --- begin view API632633public isFocused(): boolean {634return this._textAreaInput.isFocused();635}636637public focus(): void {638this._textAreaInput.focusTextArea();639}640641public refreshFocusState() {642this._textAreaInput.refreshFocusState();643}644645public getLastRenderData(): Position | null {646return this._lastRenderPosition;647}648649public setAriaOptions(options: IEditorAriaOptions): void {650if (options.activeDescendant) {651this.textArea.setAttribute('aria-haspopup', 'true');652this.textArea.setAttribute('aria-autocomplete', 'list');653this.textArea.setAttribute('aria-activedescendant', options.activeDescendant);654} else {655this.textArea.setAttribute('aria-haspopup', 'false');656this.textArea.setAttribute('aria-autocomplete', 'both');657this.textArea.removeAttribute('aria-activedescendant');658}659if (options.role) {660this.textArea.setAttribute('role', options.role);661}662}663664// --- end view API665666private _ensureReadOnlyAttribute(): void {667const options = this._context.configuration.options;668// When someone requests to disable IME, we set the "readonly" attribute on the <textarea>.669// This will prevent composition.670const useReadOnly = !IME.enabled || (options.get(EditorOption.domReadOnly) && options.get(EditorOption.readOnly));671if (useReadOnly) {672this.textArea.setAttribute('readonly', 'true');673} else {674this.textArea.removeAttribute('readonly');675}676}677678private _primaryCursorPosition: Position = new Position(1, 1);679private _primaryCursorVisibleRange: HorizontalPosition | null = null;680681public prepareRender(ctx: RenderingContext): void {682this._primaryCursorPosition = new Position(this._selections[0].positionLineNumber, this._selections[0].positionColumn);683this._primaryCursorVisibleRange = ctx.visibleRangeForPosition(this._primaryCursorPosition);684this._visibleTextArea?.prepareRender(ctx);685}686687public render(ctx: RestrictedRenderingContext): void {688this._textAreaInput.writeNativeTextAreaContent('render');689this._render();690}691692private _render(): void {693if (this._visibleTextArea) {694// The text area is visible for composition reasons695696const visibleStart = this._visibleTextArea.visibleTextareaStart;697const visibleEnd = this._visibleTextArea.visibleTextareaEnd;698const startPosition = this._visibleTextArea.startPosition;699const endPosition = this._visibleTextArea.endPosition;700if (startPosition && endPosition && visibleStart && visibleEnd && visibleEnd.left >= this._scrollLeft && visibleStart.left <= this._scrollLeft + this._contentWidth) {701const top = (this._context.viewLayout.getVerticalOffsetForLineNumber(this._primaryCursorPosition.lineNumber) - this._scrollTop);702const lineCount = newlinecount(this.textArea.domNode.value.substr(0, this.textArea.domNode.selectionStart));703704let scrollLeft = this._visibleTextArea.widthOfHiddenLineTextBefore;705let left = (this._contentLeft + visibleStart.left - this._scrollLeft);706// See https://github.com/microsoft/vscode/issues/141725#issuecomment-1050670841707// Here we are adding +1 to avoid flickering that might be caused by having a width that is too small.708// This could be caused by rounding errors that might only show up with certain font families.709// In other words, a pixel might be lost when doing something like710// `Math.round(end) - Math.round(start)`711// vs712// `Math.round(end - start)`713let width = visibleEnd.left - visibleStart.left + 1;714if (left < this._contentLeft) {715// the textarea would be rendered on top of the margin,716// so reduce its width. We use the same technique as717// for hiding text before718const delta = (this._contentLeft - left);719left += delta;720scrollLeft += delta;721width -= delta;722}723if (width > this._contentWidth) {724// the textarea would be wider than the content width,725// so reduce its width.726width = this._contentWidth;727}728729// Try to render the textarea with the color/font style to match the text under it730const lineHeight = this._context.viewLayout.getLineHeightForLineNumber(startPosition.lineNumber);731const fontSize = this._context.viewModel.getFontSizeAtPosition(this._primaryCursorPosition);732const viewLineData = this._context.viewModel.getViewLineData(startPosition.lineNumber);733const startTokenIndex = viewLineData.tokens.findTokenIndexAtOffset(startPosition.column - 1);734const endTokenIndex = viewLineData.tokens.findTokenIndexAtOffset(endPosition.column - 1);735const textareaSpansSingleToken = (startTokenIndex === endTokenIndex);736const presentation = this._visibleTextArea.definePresentation(737(textareaSpansSingleToken ? viewLineData.tokens.getPresentation(startTokenIndex) : null)738);739740this.textArea.domNode.scrollTop = lineCount * lineHeight;741this.textArea.domNode.scrollLeft = scrollLeft;742743this._doRender({744lastRenderPosition: null,745top: top,746left: left,747width: width,748height: lineHeight,749useCover: false,750color: (TokenizationRegistry.getColorMap() || [])[presentation.foreground],751italic: presentation.italic,752bold: presentation.bold,753underline: presentation.underline,754strikethrough: presentation.strikethrough,755fontSize756});757}758return;759}760761if (!this._primaryCursorVisibleRange) {762// The primary cursor is outside the viewport => place textarea to the top left763this._renderAtTopLeft();764return;765}766767const left = this._contentLeft + this._primaryCursorVisibleRange.left - this._scrollLeft;768if (left < this._contentLeft || left > this._contentLeft + this._contentWidth) {769// cursor is outside the viewport770this._renderAtTopLeft();771return;772}773774const top = this._context.viewLayout.getVerticalOffsetForLineNumber(this._selections[0].positionLineNumber) - this._scrollTop;775if (top < 0 || top > this._contentHeight) {776// cursor is outside the viewport777this._renderAtTopLeft();778return;779}780781// The primary cursor is in the viewport (at least vertically) => place textarea on the cursor782783if (platform.isMacintosh || this._accessibilitySupport === AccessibilitySupport.Enabled) {784// For the popup emoji input, we will make the text area as high as the line height785// We will also make the fontSize and lineHeight the correct dimensions to help with the placement of these pickers786const lineNumber = this._primaryCursorPosition.lineNumber;787const lineHeight = this._context.viewLayout.getLineHeightForLineNumber(lineNumber);788this._doRender({789lastRenderPosition: this._primaryCursorPosition,790top,791left: this._textAreaWrapping ? this._contentLeft : left,792width: this._textAreaWidth,793height: lineHeight,794useCover: false795});796// In case the textarea contains a word, we're going to try to align the textarea's cursor797// with our cursor by scrolling the textarea as much as possible798this.textArea.domNode.scrollLeft = this._primaryCursorVisibleRange.left;799const lineCount = this._textAreaInput.textAreaState.newlineCountBeforeSelection ?? newlinecount(this.textArea.domNode.value.substring(0, this.textArea.domNode.selectionStart));800this.textArea.domNode.scrollTop = lineCount * lineHeight;801return;802}803804this._doRender({805lastRenderPosition: this._primaryCursorPosition,806top: top,807left: this._textAreaWrapping ? this._contentLeft : left,808width: this._textAreaWidth,809height: (canUseZeroSizeTextarea ? 0 : 1),810useCover: false811});812}813814private _renderAtTopLeft(): void {815// (in WebKit the textarea is 1px by 1px because it cannot handle input to a 0x0 textarea)816// specifically, when doing Korean IME, setting the textarea to 0x0 breaks IME badly.817this._doRender({818lastRenderPosition: null,819top: 0,820left: 0,821width: this._textAreaWidth,822height: (canUseZeroSizeTextarea ? 0 : 1),823useCover: true824});825}826827private _doRender(renderData: IRenderData): void {828this._lastRenderPosition = renderData.lastRenderPosition;829830const ta = this.textArea;831const tac = this.textAreaCover;832833applyFontInfo(ta, this._fontInfo);834ta.setTop(renderData.top);835ta.setLeft(renderData.left);836ta.setWidth(renderData.width);837ta.setHeight(renderData.height);838ta.setLineHeight(renderData.height);839840ta.setFontSize(renderData.fontSize ?? this._fontInfo.fontSize);841ta.setColor(renderData.color ? Color.Format.CSS.formatHex(renderData.color) : '');842ta.setFontStyle(renderData.italic ? 'italic' : '');843if (renderData.bold) {844// fontWeight is also set by `applyFontInfo`, so only overwrite it if necessary845ta.setFontWeight('bold');846}847ta.setTextDecoration(`${renderData.underline ? ' underline' : ''}${renderData.strikethrough ? ' line-through' : ''}`);848849tac.setTop(renderData.useCover ? renderData.top : 0);850tac.setLeft(renderData.useCover ? renderData.left : 0);851tac.setWidth(renderData.useCover ? renderData.width : 0);852tac.setHeight(renderData.useCover ? renderData.height : 0);853854const options = this._context.configuration.options;855856if (options.get(EditorOption.glyphMargin)) {857tac.setClassName('monaco-editor-background textAreaCover ' + Margin.OUTER_CLASS_NAME);858} else {859if (options.get(EditorOption.lineNumbers).renderType !== RenderLineNumbersType.Off) {860tac.setClassName('monaco-editor-background textAreaCover ' + LineNumbersOverlay.CLASS_NAME);861} else {862tac.setClassName('monaco-editor-background textAreaCover');863}864}865}866}867868interface IRenderData {869lastRenderPosition: Position | null;870top: number;871left: number;872width: number;873height: number;874useCover: boolean;875876fontSize?: string | null;877color?: Color | null;878italic?: boolean;879bold?: boolean;880underline?: boolean;881strikethrough?: boolean;882}883884function measureText(targetDocument: Document, text: string, fontInfo: FontInfo, tabSize: number): number {885if (text.length === 0) {886return 0;887}888889const container = targetDocument.createElement('div');890container.style.position = 'absolute';891container.style.top = '-50000px';892container.style.width = '50000px';893894const regularDomNode = targetDocument.createElement('span');895applyFontInfo(regularDomNode, fontInfo);896regularDomNode.style.whiteSpace = 'pre'; // just like the textarea897regularDomNode.style.tabSize = `${tabSize * fontInfo.spaceWidth}px`; // just like the textarea898regularDomNode.append(text);899container.appendChild(regularDomNode);900901targetDocument.body.appendChild(container);902903const res = regularDomNode.offsetWidth;904905container.remove();906907return res;908}909910911