Merge from vscode 10492ba146318412cbee8b76a8c630f226914734

This commit is contained in:
ADS Merger
2020-04-08 06:33:38 +00:00
parent fca2344c2e
commit 1868a7d370
339 changed files with 3795 additions and 3146 deletions

View File

@@ -0,0 +1,314 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IDisposable } from 'vs/base/common/lifecycle';
import { IModelDecorationsChangeAccessor, IModelDeltaDecoration, OverviewRulerLane, TrackedRangeStickiness, MinimapPosition, FindMatch } from 'vs/editor/common/model';
import { ModelDecorationOptions } from 'vs/editor/common/model/textModel';
import { overviewRulerFindMatchForeground, minimapFindMatch } from 'vs/platform/theme/common/colorRegistry';
import { themeColorFromId } from 'vs/platform/theme/common/themeService';
import { NotebookEditor } from 'sql/workbench/contrib/notebook/browser/notebookEditor';
import { Range } from 'vs/editor/common/core/range';
import { ScrollType } from 'vs/editor/common/editorCommon';
import { NotebookRange } from 'sql/workbench/services/notebook/browser/notebookService';
export class NotebookFindDecorations implements IDisposable {
private _decorations: string[];
private _overviewRulerApproximateDecorations: string[];
private _findScopeDecorationId: string | null;
private _rangeHighlightDecorationId: string | null;
private _highlightedDecorationId: string | null;
private _startPosition: NotebookRange;
private _currentMatch: NotebookRange;
constructor(private readonly _editor: NotebookEditor) {
this._decorations = [];
this._overviewRulerApproximateDecorations = [];
this._findScopeDecorationId = null;
this._rangeHighlightDecorationId = null;
this._highlightedDecorationId = null;
this._startPosition = this._editor.getPosition();
}
public dispose(): void {
this._editor.deltaDecorations(this._allDecorations(), []);
this._decorations = [];
this._overviewRulerApproximateDecorations = [];
this._findScopeDecorationId = null;
this._rangeHighlightDecorationId = null;
this._highlightedDecorationId = null;
}
public reset(): void {
this._decorations = [];
this._overviewRulerApproximateDecorations = [];
this._findScopeDecorationId = null;
this._rangeHighlightDecorationId = null;
this._highlightedDecorationId = null;
}
public getCount(): number {
return this._decorations.length;
}
public getFindScope(): NotebookRange | null {
if (this._currentMatch) {
return this._currentMatch;
}
return null;
}
public getStartPosition(): NotebookRange {
return this._startPosition;
}
public setStartPosition(newStartPosition: NotebookRange): void {
if (newStartPosition) {
this._startPosition = newStartPosition;
this.setCurrentFindMatch(this._startPosition);
}
}
public clearDecorations(): void {
this.removePrevDecorations();
}
public setCurrentFindMatch(nextMatch: NotebookRange | null): number {
let newCurrentDecorationId: string | null = null;
let matchPosition = 0;
if (nextMatch) {
for (let i = 0, len = this._decorations.length; i < len; i++) {
let range = this._editor.notebookFindModel.getDecorationRange(this._decorations[i]);
if (nextMatch.equalsRange(range)) {
newCurrentDecorationId = this._decorations[i];
this._findScopeDecorationId = newCurrentDecorationId;
matchPosition = (i + 1);
break;
}
}
}
if (this._highlightedDecorationId !== null || newCurrentDecorationId !== null) {
this.removePrevDecorations();
if (this.checkValidEditor(nextMatch)) {
this._editor.getCellEditor(nextMatch.cell.cellGuid).getControl().changeDecorations((changeAccessor: IModelDecorationsChangeAccessor) => {
if (this._highlightedDecorationId !== null) {
changeAccessor.changeDecorationOptions(this._highlightedDecorationId, NotebookFindDecorations._FIND_MATCH_DECORATION);
this._highlightedDecorationId = null;
}
if (newCurrentDecorationId !== null) {
this._highlightedDecorationId = newCurrentDecorationId;
changeAccessor.changeDecorationOptions(this._highlightedDecorationId, NotebookFindDecorations._CURRENT_FIND_MATCH_DECORATION);
}
if (newCurrentDecorationId !== null) {
let rng = this._editor.notebookFindModel.getDecorationRange(newCurrentDecorationId)!;
if (rng.startLineNumber !== rng.endLineNumber && rng.endColumn === 1) {
let lineBeforeEnd = rng.endLineNumber - 1;
let lineBeforeEndMaxColumn = this._editor.notebookFindModel.getLineMaxColumn(lineBeforeEnd);
rng = new NotebookRange(rng.cell, rng.startLineNumber, rng.startColumn, lineBeforeEnd, lineBeforeEndMaxColumn);
}
this._rangeHighlightDecorationId = changeAccessor.addDecoration(rng, NotebookFindDecorations._RANGE_HIGHLIGHT_DECORATION);
this._revealRangeInCenterIfOutsideViewport(nextMatch);
this._currentMatch = nextMatch;
}
});
}
else {
this._editor.updateDecorations(nextMatch, undefined);
this._currentMatch = nextMatch;
}
}
return matchPosition;
}
private removePrevDecorations(): void {
if (this._currentMatch && this._currentMatch.cell) {
let prevEditor = this._currentMatch.cell.cellType === 'markdown' && !this._currentMatch.isMarkdownSourceCell ? undefined : this._editor.getCellEditor(this._currentMatch.cell.cellGuid);
if (prevEditor) {
prevEditor.getControl().changeDecorations((changeAccessor: IModelDecorationsChangeAccessor) => {
changeAccessor.removeDecoration(this._rangeHighlightDecorationId);
this._rangeHighlightDecorationId = null;
});
} else {
if (this._currentMatch.cell.cellType === 'markdown') {
this._editor.updateDecorations(undefined, this._currentMatch);
}
}
}
}
private _revealRangeInCenterIfOutsideViewport(match: NotebookRange): void {
let matchEditor = this._editor.getCellEditor(match.cell.cellGuid);
// expand the cell if it's collapsed and scroll into view
match.cell.isCollapsed = false;
if (matchEditor) {
matchEditor.getContainer().scrollIntoView({ behavior: 'smooth', block: 'nearest' });
matchEditor.getControl().revealRangeInCenterIfOutsideViewport(match, ScrollType.Smooth);
}
}
public checkValidEditor(range: NotebookRange): boolean {
return range && range.cell && !!(this._editor.getCellEditor(range.cell.cellGuid)) && (range.cell.cellType === 'code' || range.isMarkdownSourceCell);
}
public set(findMatches: NotebookFindMatch[], findScope: NotebookRange | null): void {
this._editor.changeDecorations((accessor) => {
let findMatchesOptions: ModelDecorationOptions = NotebookFindDecorations._FIND_MATCH_DECORATION;
let newOverviewRulerApproximateDecorations: IModelDeltaDecoration[] = [];
if (findMatches.length > 1000) {
// we go into a mode where the overview ruler gets "approximate" decorations
// the reason is that the overview ruler paints all the decorations in the file and we don't want to cause freezes
findMatchesOptions = NotebookFindDecorations._FIND_MATCH_NO_OVERVIEW_DECORATION;
// approximate a distance in lines where matches should be merged
const lineCount = this._editor.notebookFindModel.getLineCount();
const height = this._editor.getConfiguration().layoutInfo.height;
const approxPixelsPerLine = height / lineCount;
const mergeLinesDelta = Math.max(2, Math.ceil(3 / approxPixelsPerLine));
// merge decorations as much as possible
let prevStartLineNumber = findMatches[0].range.startLineNumber;
let prevEndLineNumber = findMatches[0].range.endLineNumber;
for (let i = 1, len = findMatches.length; i < len; i++) {
const range: NotebookRange = findMatches[i].range;
if (prevEndLineNumber + mergeLinesDelta >= range.startLineNumber) {
if (range.endLineNumber > prevEndLineNumber) {
prevEndLineNumber = range.endLineNumber;
}
} else {
newOverviewRulerApproximateDecorations.push({
range: new NotebookRange(range.cell, prevStartLineNumber, 1, prevEndLineNumber, 1),
options: NotebookFindDecorations._FIND_MATCH_ONLY_OVERVIEW_DECORATION
});
prevStartLineNumber = range.startLineNumber;
prevEndLineNumber = range.endLineNumber;
}
}
newOverviewRulerApproximateDecorations.push({
range: new NotebookRange(findMatches[0].range.cell, prevStartLineNumber, 1, prevEndLineNumber, 1),
options: NotebookFindDecorations._FIND_MATCH_ONLY_OVERVIEW_DECORATION
});
}
// Find matches
let newFindMatchesDecorations: IModelDeltaDecoration[] = new Array<IModelDeltaDecoration>(findMatches.length);
for (let i = 0, len = findMatches.length; i < len; i++) {
newFindMatchesDecorations[i] = {
range: findMatches[i].range,
options: findMatchesOptions
};
}
this._decorations = accessor.deltaDecorations(this._decorations, newFindMatchesDecorations);
// Overview ruler approximate decorations
this._overviewRulerApproximateDecorations = accessor.deltaDecorations(this._overviewRulerApproximateDecorations, newOverviewRulerApproximateDecorations);
// Range highlight
if (this._rangeHighlightDecorationId) {
accessor.removeDecoration(this._rangeHighlightDecorationId);
this._rangeHighlightDecorationId = null;
}
// Find scope
if (this._findScopeDecorationId) {
accessor.removeDecoration(this._findScopeDecorationId);
this._findScopeDecorationId = null;
}
if (findScope) {
this._currentMatch = findScope;
this._findScopeDecorationId = accessor.addDecoration(findScope, NotebookFindDecorations._FIND_SCOPE_DECORATION);
}
});
}
private _allDecorations(): string[] {
let result: string[] = [];
result = result.concat(this._decorations);
result = result.concat(this._overviewRulerApproximateDecorations);
if (this._findScopeDecorationId) {
result.push(this._findScopeDecorationId);
}
if (this._rangeHighlightDecorationId) {
result.push(this._rangeHighlightDecorationId);
}
return result;
}
private static readonly _CURRENT_FIND_MATCH_DECORATION = ModelDecorationOptions.register({
stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
zIndex: 13,
className: 'currentFindMatch',
showIfCollapsed: true,
overviewRuler: {
color: themeColorFromId(overviewRulerFindMatchForeground),
position: OverviewRulerLane.Center
},
minimap: {
color: themeColorFromId(minimapFindMatch),
position: MinimapPosition.Inline
}
});
private static readonly _FIND_MATCH_DECORATION = ModelDecorationOptions.register({
stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
className: 'findMatch',
showIfCollapsed: true,
overviewRuler: {
color: themeColorFromId(overviewRulerFindMatchForeground),
position: OverviewRulerLane.Center
},
minimap: {
color: themeColorFromId(minimapFindMatch),
position: MinimapPosition.Inline
}
});
private static readonly _FIND_MATCH_NO_OVERVIEW_DECORATION = ModelDecorationOptions.register({
stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
className: 'findMatch',
showIfCollapsed: true
});
private static readonly _FIND_MATCH_ONLY_OVERVIEW_DECORATION = ModelDecorationOptions.register({
stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
overviewRuler: {
color: themeColorFromId(overviewRulerFindMatchForeground),
position: OverviewRulerLane.Center
}
});
private static readonly _RANGE_HIGHLIGHT_DECORATION = ModelDecorationOptions.register({
stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
className: 'rangeHighlight',
isWholeLine: false
});
private static readonly _FIND_SCOPE_DECORATION = ModelDecorationOptions.register({
className: 'findScope',
isWholeLine: true
});
}
export class NotebookFindMatch extends FindMatch {
_findMatchBrand: void;
public readonly range: NotebookRange;
public readonly matches: string[] | null;
/**
* @internal
*/
constructor(range: NotebookRange, matches: string[] | null) {
super(new Range(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn), matches);
this.range = range;
this.matches = matches;
}
}

View File

@@ -0,0 +1,711 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Disposable } from 'vs/base/common/lifecycle';
import { ICellModel, INotebookModel } from 'sql/workbench/services/notebook/browser/models/modelInterfaces';
import { INotebookFindModel } from 'sql/workbench/contrib/notebook/browser/models/notebookFindModel';
import { Event, Emitter } from 'vs/base/common/event';
import * as types from 'vs/base/common/types';
import { NotebookFindMatch, NotebookFindDecorations } from 'sql/workbench/contrib/notebook/browser/find/notebookFindDecorations';
import * as model from 'vs/editor/common/model';
import { ModelDecorationOptions, DidChangeDecorationsEmitter, createTextBuffer } from 'vs/editor/common/model/textModel';
import { IModelDecorationsChangedEvent } from 'vs/editor/common/model/textModelEvents';
import { IntervalNode } from 'vs/editor/common/model/intervalTree';
import { EDITOR_MODEL_DEFAULTS } from 'vs/editor/common/config/editorOptions';
import { Range, IRange } from 'vs/editor/common/core/range';
import { onUnexpectedError } from 'vs/base/common/errors';
import { singleLetterHash, isHighSurrogate } from 'vs/base/common/strings';
import { Command, ServicesAccessor } from 'vs/editor/browser/editorExtensions';
import { NotebookEditor } from 'sql/workbench/contrib/notebook/browser/notebookEditor';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { NOTEBOOK_COMMAND_SEARCH } from 'sql/workbench/services/notebook/common/notebookContext';
import { KeyMod, KeyCode } from 'vs/base/common/keyCodes';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { ActiveEditorContext } from 'vs/workbench/common/editor';
import { NotebookRange } from 'sql/workbench/services/notebook/browser/notebookService';
function _normalizeOptions(options: model.IModelDecorationOptions): ModelDecorationOptions {
if (options instanceof ModelDecorationOptions) {
return options;
}
return ModelDecorationOptions.createDynamic(options);
}
const invalidFunc = () => { throw new Error(`Invalid change accessor`); };
let MODEL_ID = 0;
export class NotebookFindModel extends Disposable implements INotebookFindModel {
private _findArray: Array<NotebookRange>;
private _findIndex: number = 0;
private _onFindCountChange = new Emitter<number>();
private _isDisposed: boolean;
public readonly id: string;
private _buffer: model.ITextBuffer;
private readonly _instanceId: string;
private _lastDecorationId: number;
private _versionId: number;
private _findDecorations: NotebookFindDecorations;
public currentMatch: NotebookRange;
public previousMatch: NotebookRange;
public findExpression: string;
//#region Decorations
private readonly _onDidChangeDecorations: DidChangeDecorationsEmitter = this._register(new DidChangeDecorationsEmitter());
public readonly onDidChangeDecorations: Event<IModelDecorationsChangedEvent> = this._onDidChangeDecorations.event;
private _decorations: { [decorationId: string]: NotebookIntervalNode; };
//#endregion
constructor(private _notebookModel: INotebookModel) {
super();
this._isDisposed = false;
this._instanceId = singleLetterHash(MODEL_ID);
this._lastDecorationId = 0;
// Generate a new unique model id
MODEL_ID++;
this._decorations = Object.create(null);
this._buffer = createTextBuffer('', NotebookFindModel.DEFAULT_CREATION_OPTIONS.defaultEOL);
this._versionId = 1;
this.id = '$model' + MODEL_ID;
}
public set notebookModel(model: INotebookModel) {
this._notebookModel = model;
}
public get notebookModel(): INotebookModel {
return this._notebookModel;
}
public get findDecorations(): NotebookFindDecorations {
return this._findDecorations;
}
public setNotebookFindDecorations(editor: NotebookEditor): void {
this._findDecorations = new NotebookFindDecorations(editor);
this._findDecorations.setStartPosition(this.getPosition());
}
public clearDecorations(): void {
this._findDecorations.dispose();
this.clearFind();
}
public static DEFAULT_CREATION_OPTIONS: model.ITextModelCreationOptions = {
isForSimpleWidget: false,
tabSize: EDITOR_MODEL_DEFAULTS.tabSize,
indentSize: EDITOR_MODEL_DEFAULTS.indentSize,
insertSpaces: EDITOR_MODEL_DEFAULTS.insertSpaces,
detectIndentation: false,
defaultEOL: model.DefaultEndOfLine.LF,
trimAutoWhitespace: EDITOR_MODEL_DEFAULTS.trimAutoWhitespace,
largeFileOptimizations: EDITOR_MODEL_DEFAULTS.largeFileOptimizations,
};
public get onFindCountChange(): Event<number> { return this._onFindCountChange.event; }
public get VersionId(): number {
return this._versionId;
}
public get Buffer(): model.ITextBuffer {
return this._buffer;
}
public get ModelId(): number {
return MODEL_ID;
}
public getPosition(): NotebookRange {
return this.currentMatch;
}
public getLastPosition(): NotebookRange {
return this.previousMatch;
}
public setSelection(range: NotebookRange): void {
this.previousMatch = this.currentMatch;
this.currentMatch = range;
}
public ChangeDecorations<T>(ownerId: number, callback: (changeAccessor: model.IModelDecorationsChangeAccessor) => T): T | null {
let changeAccessor: model.IModelDecorationsChangeAccessor = {
addDecoration: (range: IRange, options: model.IModelDecorationOptions): string => {
this._onDidChangeDecorations.fire();
return this._deltaDecorationsImpl(ownerId, [], [{ range: range, options: options }])[0];
},
changeDecoration: (id: string, newRange: IRange): void => {
this._onDidChangeDecorations.fire();
this._changeDecorationImpl(id, newRange);
},
changeDecorationOptions: (id: string, options: model.IModelDecorationOptions) => {
this._onDidChangeDecorations.fire();
this._changeDecorationOptionsImpl(id, _normalizeOptions(options));
},
removeDecoration: (id: string): void => {
this._onDidChangeDecorations.fire();
this._deltaDecorationsImpl(ownerId, [id], []);
},
deltaDecorations: (oldDecorations: string[], newDecorations: model.IModelDeltaDecoration[]): string[] => {
if (oldDecorations.length === 0 && newDecorations.length === 0) {
// nothing to do
return [];
}
this._onDidChangeDecorations.fire();
return this._deltaDecorationsImpl(ownerId, oldDecorations, newDecorations);
}
};
let result: T | null = null;
try {
result = callback(changeAccessor);
} catch (e) {
onUnexpectedError(e);
}
// Invalidate change accessor
changeAccessor.addDecoration = invalidFunc;
changeAccessor.changeDecoration = invalidFunc;
changeAccessor.changeDecorationOptions = invalidFunc;
changeAccessor.removeDecoration = invalidFunc;
changeAccessor.deltaDecorations = invalidFunc;
return result;
}
public getRangeAt(cell: ICellModel, start: number, end: number): NotebookRange {
return this._getRangeAt(cell, start, end);
}
private _getRangeAt(cell: ICellModel, start: number, end: number): NotebookRange {
let range: Range = this._buffer.getRangeAt(start, end - start);
return new NotebookRange(cell, range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
}
/**
* @param range the range to check for validity
* @param strict Do NOT allow a range to have its boundaries inside a high-low surrogate pair
*/
private _isValidRange(range: NotebookRange, strict: boolean): boolean {
const startLineNumber = range.startLineNumber;
const startColumn = range.startColumn;
const endLineNumber = range.endLineNumber;
const endColumn = range.endColumn;
if (!this._isValidPosition(startLineNumber, startColumn, false)) {
return false;
}
if (!this._isValidPosition(endLineNumber, endColumn, false)) {
return false;
}
if (strict) {
const charCodeBeforeStart = (startColumn > 1 ? this._buffer.getLineCharCode(startLineNumber, startColumn - 2) : 0);
const charCodeBeforeEnd = (endColumn > 1 && endColumn <= this._buffer.getLineLength(endLineNumber) ? this._buffer.getLineCharCode(endLineNumber, endColumn - 2) : 0);
const startInsideSurrogatePair = isHighSurrogate(charCodeBeforeStart);
const endInsideSurrogatePair = isHighSurrogate(charCodeBeforeEnd);
if (!startInsideSurrogatePair && !endInsideSurrogatePair) {
return true;
}
return false;
}
return true;
}
private _isValidPosition(lineNumber: number, column: number, strict: boolean): boolean {
if (typeof lineNumber !== 'number' || typeof column !== 'number') {
return false;
}
if (isNaN(lineNumber) || isNaN(column)) {
return false;
}
if (lineNumber < 0 || column < 1) {
return false;
}
if ((lineNumber | 0) !== lineNumber || (column | 0) !== column) {
return false;
}
const lineCount = this._buffer.getLineCount();
if (lineNumber > lineCount) {
return false;
}
if (strict) {
if (column > 1) {
const charCodeBefore = this._buffer.getLineCharCode(lineNumber, column - 2);
if (isHighSurrogate(charCodeBefore)) {
return false;
}
}
}
return true;
}
getLineMaxColumn(lineNumber: number): number {
if (lineNumber < 1 || lineNumber > this.getLineCount()) {
throw new Error('Illegal value for lineNumber');
}
return this._buffer.getLineLength(lineNumber) + 1;
}
getLineCount(): number {
return this._buffer.getLineCount();
}
public getVersionId(): number {
return this._versionId;
}
public validateRange(_range: IRange): NotebookRange {
// Avoid object allocation and cover most likely case
if ((_range instanceof NotebookRange) && !(_range instanceof Selection)) {
if (this._isValidRange(_range, true)) {
return _range;
}
}
return undefined;
}
/**
* Validates `range` is within buffer bounds, but allows it to sit in between surrogate pairs, etc.
* Will try to not allocate if possible.
*/
private _validateRangeRelaxedNoAllocations(range: IRange): NotebookRange {
if (range instanceof NotebookRange) {
this._buffer = createTextBuffer(range.cell.source instanceof Array ? range.cell.source.join('\n') : range.cell.source, NotebookFindModel.DEFAULT_CREATION_OPTIONS.defaultEOL);
}
const linesCount = this._buffer.getLineCount();
const initialStartLineNumber = range.startLineNumber;
const initialStartColumn = range.startColumn;
let startLineNumber: number;
let startColumn: number;
if (initialStartLineNumber < 1) {
startLineNumber = 1;
startColumn = 1;
} else if (initialStartLineNumber > linesCount) {
startLineNumber = linesCount;
startColumn = this.getLineMaxColumn(startLineNumber);
} else {
startLineNumber = initialStartLineNumber | 0;
if (initialStartColumn <= 1) {
startColumn = 1;
} else {
const maxColumn = this.getLineMaxColumn(startLineNumber);
if (initialStartColumn >= maxColumn) {
startColumn = maxColumn;
} else {
startColumn = initialStartColumn | 0;
}
}
}
const initialEndLineNumber = range.endLineNumber;
const initialEndColumn = range.endColumn;
let endLineNumber: number;
let endColumn: number;
if (initialEndLineNumber < 1) {
endLineNumber = 1;
endColumn = 1;
} else if (initialEndLineNumber > linesCount) {
endLineNumber = linesCount;
endColumn = this.getLineMaxColumn(endLineNumber);
} else {
endLineNumber = initialEndLineNumber | 0;
if (initialEndColumn <= 1) {
endColumn = 1;
} else {
const maxColumn = this.getLineMaxColumn(endLineNumber);
if (initialEndColumn >= maxColumn) {
endColumn = maxColumn;
} else {
endColumn = initialEndColumn | 0;
}
}
}
if (
initialStartLineNumber === startLineNumber
&& initialStartColumn === startColumn
&& initialEndLineNumber === endLineNumber
&& initialEndColumn === endColumn
&& range instanceof NotebookRange
&& !(range instanceof Selection)
) {
return range;
}
if (range instanceof NotebookRange) {
return range;
}
return new NotebookRange(undefined, startLineNumber, startColumn, endLineNumber, endColumn);
}
private _changeDecorationImpl(decorationId: string, _range: IRange): void {
const node = this._decorations[decorationId];
if (!node) {
return;
}
const range = this._validateRangeRelaxedNoAllocations(_range);
const startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn);
const endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn);
node.node.reset(this.getVersionId(), startOffset, endOffset, range);
}
private _changeDecorationOptionsImpl(decorationId: string, options: ModelDecorationOptions): void {
const node = this._decorations[decorationId];
if (!node) {
return;
}
const nodeWasInOverviewRuler = (node.node.options.overviewRuler && node.node.options.overviewRuler.color ? true : false);
const nodeIsInOverviewRuler = (options.overviewRuler && options.overviewRuler.color ? true : false);
if (nodeWasInOverviewRuler !== nodeIsInOverviewRuler) {
// Delete + Insert due to an overview ruler status change
node.node.setOptions(options);
} else {
node.node.setOptions(options);
}
}
private _deltaDecorationsImpl(ownerId: number, oldDecorationsIds: string[], newDecorations: model.IModelDeltaDecoration[]): string[] {
const versionId = this.getVersionId();
const oldDecorationsLen = oldDecorationsIds.length;
let oldDecorationIndex = 0;
const newDecorationsLen = newDecorations.length;
let newDecorationIndex = 0;
let result = new Array<string>(newDecorationsLen);
while (oldDecorationIndex < oldDecorationsLen || newDecorationIndex < newDecorationsLen) {
let node: IntervalNode | null = null;
let cell: ICellModel | null = null;
if (oldDecorationIndex < oldDecorationsLen) {
// (1) get ourselves an old node
do {
let decorationNode = this._decorations[oldDecorationsIds[oldDecorationIndex++]];
node = decorationNode?.node;
} while (!node && oldDecorationIndex < oldDecorationsLen);
// (2) remove the node from the tree (if it exists)
if (node) {
//this._decorationsTree.delete(node);
}
}
if (newDecorationIndex < newDecorationsLen) {
// (3) create a new node if necessary
if (!node) {
const internalDecorationId = (++this._lastDecorationId);
const decorationId = `${this._instanceId};${internalDecorationId}`;
node = new IntervalNode(decorationId, 0, 0);
this._decorations[decorationId] = new NotebookIntervalNode(node, cell);
}
// (4) initialize node
const newDecoration = newDecorations[newDecorationIndex];
const range = this._validateRangeRelaxedNoAllocations(newDecoration.range);
const options = _normalizeOptions(newDecoration.options);
const startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn);
const endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn);
node.ownerId = ownerId;
node.reset(versionId, startOffset, endOffset, range);
node.setOptions(options);
this._decorations[node.id].cell = range.cell;
this._decorations[node.id].node = node;
//this._decorationsTree.insert(node);
result[newDecorationIndex] = node.id;
newDecorationIndex++;
} else {
if (node) {
delete this._decorations[node.id];
}
}
}
return result;
}
public getDecorationRange(id: string): NotebookRange | null {
const node = this._decorations[id];
if (!node) {
return null;
}
let range = node.node.range;
if (range === null) {
node.node.range = this._getRangeAt(node.cell, node.node.cachedAbsoluteStart, node.node.cachedAbsoluteEnd);
}
return new NotebookRange(node.cell, node.node.range.startLineNumber, node.node.range.startColumn, node.node.range.endLineNumber, node.node.range.endColumn);
}
findNext(): Promise<NotebookRange> {
if (this._findArray && this._findArray.length !== 0) {
if (this._findIndex === this._findArray.length - 1) {
this._findIndex = 0;
} else {
++this._findIndex;
}
return Promise.resolve(this._findArray[this._findIndex]);
} else {
return Promise.reject(new Error('no search running'));
}
}
findPrevious(): Promise<NotebookRange> {
if (this._findArray && this._findArray.length !== 0) {
if (this._findIndex === 0) {
this._findIndex = this._findArray.length - 1;
} else {
--this._findIndex;
}
return Promise.resolve(this._findArray[this._findIndex]);
} else {
return Promise.reject(new Error('no search running'));
}
}
find(exp: string, matchCase?: boolean, wholeWord?: boolean, maxMatches?: number): Promise<NotebookRange> {
this._findArray = new Array<NotebookRange>();
this._onFindCountChange.fire(this._findArray.length);
if (exp) {
for (let i = 0; i < this.notebookModel.cells.length; i++) {
const item = this.notebookModel.cells[i];
const result = this.searchFn(item, exp, matchCase, wholeWord, maxMatches);
if (result) {
this._findArray.push(...result);
this._onFindCountChange.fire(this._findArray.length);
if (maxMatches > 0 && this._findArray.length === maxMatches) {
break;
}
}
}
return Promise.resolve(this._findArray[this._findIndex]);
} else {
return Promise.reject(new Error('no expression'));
}
}
public get findMatches(): NotebookFindMatch[] {
let findMatches: NotebookFindMatch[] = [];
this._findArray.forEach(element => {
findMatches = findMatches.concat(new NotebookFindMatch(element, null));
});
return findMatches;
}
public get findArray(): NotebookRange[] {
return this._findArray;
}
getIndexByRange(range: NotebookRange): number {
let index = this.findArray.findIndex(r => r.cell.cellGuid === range.cell.cellGuid && r.startColumn === range.startColumn && r.endColumn === range.endColumn && r.startLineNumber === range.startLineNumber && r.endLineNumber === range.endLineNumber && r.isMarkdownSourceCell === range.isMarkdownSourceCell);
this._findIndex = index > -1 ? index : this._findIndex;
// _findIndex is the 0 based index, return index + 1 for the actual count on UI
return this._findIndex + 1;
}
private searchFn(cell: ICellModel, exp: string, matchCase: boolean = false, wholeWord: boolean = false, maxMatches?: number): NotebookRange[] {
let findResults: NotebookRange[] = [];
if (cell.cellType === 'markdown' && cell.isEditMode && typeof cell.source !== 'string') {
let cellSource = cell.source;
for (let j = 0; j < cellSource.length; j++) {
let findStartResults = this.search(cellSource[j], exp, matchCase, wholeWord, maxMatches - findResults.length);
findStartResults.forEach(start => {
// lineNumber: j+1 since notebook editors aren't zero indexed.
let range = new NotebookRange(cell, j + 1, start, j + 1, start + exp.length, true);
findResults.push(range);
});
}
}
let cellVal = cell.cellType === 'markdown' ? cell.renderedOutputTextContent : cell.source;
if (cellVal) {
if (typeof cellVal === 'string') {
let findStartResults = this.search(cellVal, exp, matchCase, wholeWord, maxMatches);
findStartResults.forEach(start => {
let range = new NotebookRange(cell, 0, start, 0, start + exp.length);
findResults.push(range);
});
} else {
for (let j = 0; j < cellVal.length; j++) {
let cellValFormatted = cell.cellType === 'markdown' ? this.cleanMarkdownLinks(cellVal[j]) : cellVal[j];
let findStartResults = this.search(cellValFormatted, exp, matchCase, wholeWord, maxMatches - findResults.length);
findStartResults.forEach(start => {
// lineNumber: j+1 since notebook editors aren't zero indexed.
let range = new NotebookRange(cell, j + 1, start, j + 1, start + exp.length);
findResults.push(range);
});
}
}
}
return findResults;
}
// escape the special characters in a regex string
escapeRegExp(text: string): string {
return text.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g, '\\$&');
}
search(input: string, exp: string, matchCase: boolean = false, wholeWord: boolean = false, maxMatches?: number): number[] {
let index: number = 0;
let start: number;
let findResults: number[] = [];
if (!matchCase) {
input = input.toLocaleLowerCase();
exp = exp.toLocaleLowerCase();
}
let searchText: string = input.substr(index);
while (findResults.length < maxMatches && searchText.indexOf(exp) > -1) {
if (wholeWord) {
// word with no special characters around \\bword\\b, word that begins or ends with special character \\sword\\s
let wholeWordRegex = new RegExp(`(?:\\b|\\s)${this.escapeRegExp(exp)}(?:\\b|\\s)`);
start = searchText.search(wholeWordRegex) + 1;
if (start < 1) {
break;
}
} else {
start = searchText.indexOf(exp) + index;
// Editors aren't 0-based; the first character position in an editor is 1, so adding 1 to the first found index
if (index === 0) {
start++;
}
}
findResults.push(start);
index = start + exp.length;
searchText = input.substr(index - 1);
}
return findResults;
}
// In markdown links are defined as [Link Text](https://url/of/the/text). when searching for text we shouldn't
// look for the values inside the (), below regex replaces that with just the Link Text.
cleanMarkdownLinks(cellSrc: string): string {
return cellSrc.replace(/(?:__|[*#])|\[(.*?)\]\(.*?\)/gm, '$1');
}
// remove /n's to calculate the line number to locate the correct element
cleanUpCellSource(cellValue: string | string[]): string | string[] {
let trimmedCellSrc: string[] = [];
if (cellValue instanceof Array) {
trimmedCellSrc = cellValue.filter(c => c !== '\n' && c !== '\r\n' && c.indexOf('|-') === -1);
} else {
return cellValue;
}
return trimmedCellSrc;
}
clearFind(): void {
this._findArray = new Array<NotebookRange>();
this._findIndex = 0;
this._onFindCountChange.fire(this._findArray.length);
}
getFindIndex(): number {
return types.isUndefinedOrNull(this._findIndex) ? 0 : this._findIndex + 1;
}
getFindCount(): number {
return types.isUndefinedOrNull(this._findArray) ? 0 : this._findArray.length;
}
//#region Decorations
public isDisposed(): boolean {
return this._isDisposed;
}
private _assertNotDisposed(): void {
if (this._isDisposed) {
throw new Error('Model is disposed!');
}
}
public changeDecorations<T>(callback: (changeAccessor: model.IModelDecorationsChangeAccessor) => T, ownerId: number = 0): T | null {
this._assertNotDisposed();
try {
this._onDidChangeDecorations.beginDeferredEmit();
return this.ChangeDecorations(ownerId, callback);
} finally {
this._onDidChangeDecorations.endDeferredEmit();
}
}
public dispose(): void {
super.dispose();
this._findArray = [];
this._isDisposed = true;
}
}
export class NotebookIntervalNode extends IntervalNode {
constructor(public node: IntervalNode, public cell: ICellModel) {
super(node.id, node.start, node.end);
}
}
abstract class SettingsCommand extends Command {
protected getNotebookEditor(accessor: ServicesAccessor): NotebookEditor {
const activeEditor = accessor.get(IEditorService).activeEditorPane;
if (activeEditor instanceof NotebookEditor) {
return activeEditor;
}
return null;
}
}
class SearchNotebookCommand extends SettingsCommand {
public async runCommand(accessor: ServicesAccessor, args: any): Promise<void> {
const notebookEditor = this.getNotebookEditor(accessor);
if (notebookEditor) {
await notebookEditor.setNotebookModel();
notebookEditor.toggleSearch();
}
}
}
export const findCommand = new SearchNotebookCommand({
id: NOTEBOOK_COMMAND_SEARCH,
precondition: ActiveEditorContext.isEqualTo(NotebookEditor.ID),
kbOpts: {
primary: KeyMod.CtrlCmd | KeyCode.KEY_F,
weight: KeybindingWeight.EditorContrib
}
});
findCommand.register();

View File

@@ -0,0 +1,582 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { onUnexpectedError } from 'vs/base/common/errors';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import * as platform from 'vs/base/common/platform';
import * as strings from 'vs/base/common/strings';
import * as dom from 'vs/base/browser/dom';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { IContextViewProvider } from 'vs/base/browser/ui/contextview/contextview';
import { FindInput, IFindInputStyles } from 'vs/base/browser/ui/findinput/findInput';
import { IMessage as InputBoxMessage } from 'vs/base/browser/ui/inputbox/inputBox';
import { Widget } from 'vs/base/browser/ui/widget';
import { Sash, IHorizontalSashLayoutProvider, ISashEvent, Orientation } from 'vs/base/browser/ui/sash/sash';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IOverlayWidget, IOverlayWidgetPosition, OverlayWidgetPositionPreference } from 'vs/editor/browser/editorBrowser';
import { FIND_IDS, CONTEXT_FIND_INPUT_FOCUSED } from 'vs/editor/contrib/find/findModel';
import { FindReplaceState, FindReplaceStateChangedEvent } from 'vs/editor/contrib/find/findState';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IColorTheme, IThemeService } from 'vs/platform/theme/common/themeService';
import * as colors from 'vs/platform/theme/common/colorRegistry';
import { IEditorAction } from 'vs/editor/common/editorCommon';
import { IDisposable } from 'vs/base/common/lifecycle';
const NLS_FIND_INPUT_LABEL = nls.localize('label.find', "Find");
const NLS_FIND_INPUT_PLACEHOLDER = nls.localize('placeholder.find', "Find");
const NLS_PREVIOUS_MATCH_BTN_LABEL = nls.localize('label.previousMatchButton', "Previous match");
const NLS_NEXT_MATCH_BTN_LABEL = nls.localize('label.nextMatchButton', "Next match");
const NLS_CLOSE_BTN_LABEL = nls.localize('label.closeButton', "Close");
const NLS_MATCHES_COUNT_LIMIT_TITLE = nls.localize('title.matchesCountLimit', "Your search returned a large number of results, only the first 999 matches will be highlighted.");
const NLS_MATCHES_LOCATION = nls.localize('label.matchesLocation', "{0} of {1}");
const NLS_NO_RESULTS = nls.localize('label.noResults', "No Results");
const FIND_WIDGET_INITIAL_WIDTH = 411;
const PART_WIDTH = 275;
const FIND_INPUT_AREA_WIDTH = PART_WIDTH - 54;
let MAX_MATCHES_COUNT_WIDTH = 69;
export const NOTEBOOK_MAX_MATCHES = 999;
export const ACTION_IDS = {
FIND_NEXT: 'findNext',
FIND_PREVIOUS: 'findPrev'
};
export interface IFindNotebookController {
focus(): void;
getConfiguration(): any;
layoutOverlayWidget(widget: IOverlayWidget): void;
addOverlayWidget(widget: IOverlayWidget): void;
getAction(id: string): IEditorAction;
onDidChangeConfiguration(fn: (e: IConfigurationChangedEvent) => void): IDisposable;
findNext();
findPrevious();
}
export interface IConfigurationChangedEvent {
layoutInfo?: boolean;
}
export class FindWidget extends Widget implements IOverlayWidget, IHorizontalSashLayoutProvider {
private static ID = 'editor.contrib.findWidget';
private _notebookController: IFindNotebookController;
private _state: FindReplaceState;
private _contextViewProvider: IContextViewProvider;
private _keybindingService: IKeybindingService;
private _domNode: HTMLElement;
private _findInput: FindInput;
private _matchesCount: HTMLElement;
private _prevBtn: SimpleButton;
private _nextBtn: SimpleButton;
private _closeBtn: SimpleButton;
private _isVisible: boolean;
private _focusTracker: dom.IFocusTracker;
private _findInputFocussed: IContextKey<boolean>;
private _resizeSash: Sash;
private searchTimeoutHandle: number | undefined;
constructor(
notebookController: IFindNotebookController,
state: FindReplaceState,
contextViewProvider: IContextViewProvider,
keybindingService: IKeybindingService,
contextKeyService: IContextKeyService,
themeService: IThemeService
) {
super();
this._notebookController = notebookController;
this._state = state;
this._contextViewProvider = contextViewProvider;
this._keybindingService = keybindingService;
this._isVisible = false;
this._register(this._state.onFindReplaceStateChange((e) => this._onStateChanged(e)));
this._buildDomNode();
this._updateButtons();
let checkEditorWidth = () => {
let editorWidth = this._notebookController.getConfiguration().layoutInfo.width;
const minimapWidth = this._notebookController.getConfiguration().layoutInfo.minimapWidth;
let collapsedFindWidget = false;
let reducedFindWidget = false;
let narrowFindWidget = false;
let widgetWidth = dom.getTotalWidth(this._domNode);
if (widgetWidth > FIND_WIDGET_INITIAL_WIDTH) {
// as the widget is resized by users, we may need to change the max width of the widget as the editor width changes.
this._domNode.style.maxWidth = `${editorWidth - 28 - 15}px`;
return;
}
if (FIND_WIDGET_INITIAL_WIDTH + 28 + minimapWidth >= editorWidth) {
reducedFindWidget = true;
}
if (FIND_WIDGET_INITIAL_WIDTH + 28 + minimapWidth - MAX_MATCHES_COUNT_WIDTH >= editorWidth) {
narrowFindWidget = true;
}
if (FIND_WIDGET_INITIAL_WIDTH + 28 + minimapWidth - MAX_MATCHES_COUNT_WIDTH >= editorWidth + 50) {
collapsedFindWidget = true;
}
dom.toggleClass(this._domNode, 'collapsed-find-widget', collapsedFindWidget);
dom.toggleClass(this._domNode, 'narrow-find-widget', narrowFindWidget);
dom.toggleClass(this._domNode, 'reduced-find-widget', reducedFindWidget);
if (!narrowFindWidget && !collapsedFindWidget) {
// the minimal left offset of findwidget is 15px.
this._domNode.style.maxWidth = `${editorWidth - 28 - 15}px`;
}
};
checkEditorWidth();
this._register(this._notebookController.onDidChangeConfiguration((e: IConfigurationChangedEvent) => {
if (e.layoutInfo) {
checkEditorWidth();
}
}));
this._findInputFocussed = CONTEXT_FIND_INPUT_FOCUSED.bindTo(contextKeyService);
this._focusTracker = this._register(dom.trackFocus(this._findInput.inputBox.inputElement));
this._focusTracker.onDidFocus(() => {
this._findInputFocussed.set(true);
});
this._focusTracker.onDidBlur(() => {
this._findInputFocussed.set(false);
});
this._notebookController.addOverlayWidget(this);
this._applyTheme(themeService.getColorTheme());
this._register(themeService.onDidColorThemeChange(this._applyTheme.bind(this)));
this.onkeyup(this._domNode, e => {
if (e.equals(KeyCode.Escape)) {
this._state.change({ isRevealed: false, searchScope: null }, false);
e.preventDefault();
return;
}
});
}
// ----- IOverlayWidget API
public getId(): string {
return FindWidget.ID;
}
public getDomNode(): HTMLElement {
return this._domNode;
}
public getPosition(): IOverlayWidgetPosition {
if (this._isVisible) {
return {
preference: OverlayWidgetPositionPreference.TOP_RIGHT_CORNER
};
}
return null;
}
// ----- React to state changes
private _onStateChanged(e: FindReplaceStateChangedEvent): void {
if (e.searchString) {
this._findInput.setValue(this._state.searchString);
this._updateButtons();
}
if (e.isRevealed) {
if (this._state.isRevealed) {
this._reveal(true);
} else {
this._hide(true);
}
}
if (e.isRegex) {
this._findInput.setRegex(this._state.isRegex);
}
if (e.wholeWord) {
this._findInput.setWholeWords(this._state.wholeWord);
}
if (e.matchCase) {
this._findInput.setCaseSensitive(this._state.matchCase);
}
if (e.searchString || e.matchesCount || e.matchesPosition) {
let showRedOutline = (this._state.searchString.length > 0 && this._state.matchesCount === 0);
dom.toggleClass(this._domNode, 'no-results', showRedOutline);
this._updateMatchesCount();
}
}
private _updateMatchesCount(): void {
this._matchesCount.style.minWidth = MAX_MATCHES_COUNT_WIDTH + 'px';
if (this._state.matchesCount >= NOTEBOOK_MAX_MATCHES) {
this._matchesCount.title = NLS_MATCHES_COUNT_LIMIT_TITLE;
} else {
this._matchesCount.title = '';
}
// remove previous content
if (this._matchesCount.firstChild) {
this._matchesCount.removeChild(this._matchesCount.firstChild);
}
let label: string;
if (this._state.matchesCount > 0) {
let matchesCount: string = String(this._state.matchesCount);
if (this._state.matchesCount >= NOTEBOOK_MAX_MATCHES) {
matchesCount = NOTEBOOK_MAX_MATCHES + '+';
}
let matchesPosition: string = String(this._state.matchesPosition);
if (matchesPosition === '0') {
matchesPosition = '?';
}
label = strings.format(NLS_MATCHES_LOCATION, matchesPosition, matchesCount);
} else {
label = NLS_NO_RESULTS;
}
this._matchesCount.appendChild(document.createTextNode(label));
MAX_MATCHES_COUNT_WIDTH = Math.max(MAX_MATCHES_COUNT_WIDTH, this._matchesCount.clientWidth);
}
// ----- actions
private _updateButtons(): void {
this._findInput.setEnabled(this._isVisible);
this._closeBtn.setEnabled(this._isVisible);
let findInputIsNonEmpty = (this._state.searchString.length > 0);
this._prevBtn.setEnabled(this._isVisible && findInputIsNonEmpty);
this._nextBtn.setEnabled(this._isVisible && findInputIsNonEmpty);
}
private _reveal(animate: boolean): void {
if (!this._isVisible) {
this._isVisible = true;
this._updateButtons();
setTimeout(() => {
dom.addClass(this._domNode, 'visible');
this._domNode.setAttribute('aria-hidden', 'false');
if (!animate) {
dom.addClass(this._domNode, 'noanimation');
setTimeout(() => {
dom.removeClass(this._domNode, 'noanimation');
}, 200);
}
}, 0);
this._notebookController.layoutOverlayWidget(this);
}
}
private _hide(focusTheEditor: boolean): void {
if (this._isVisible) {
this._isVisible = false;
this._updateButtons();
dom.removeClass(this._domNode, 'visible');
this._domNode.setAttribute('aria-hidden', 'true');
if (focusTheEditor) {
this._notebookController.focus();
}
this._notebookController.layoutOverlayWidget(this);
}
}
private _applyTheme(theme: IColorTheme) {
let inputStyles: IFindInputStyles = {
inputActiveOptionBorder: theme.getColor(colors.inputActiveOptionBorder),
inputBackground: theme.getColor(colors.inputBackground),
inputForeground: theme.getColor(colors.inputForeground),
inputBorder: theme.getColor(colors.inputBorder),
inputValidationInfoBackground: theme.getColor(colors.inputValidationInfoBackground),
inputValidationInfoBorder: theme.getColor(colors.inputValidationInfoBorder),
inputValidationWarningBackground: theme.getColor(colors.inputValidationWarningBackground),
inputValidationWarningBorder: theme.getColor(colors.inputValidationWarningBorder),
inputValidationErrorBackground: theme.getColor(colors.inputValidationErrorBackground),
inputValidationErrorBorder: theme.getColor(colors.inputValidationErrorBorder)
};
this._findInput.style(inputStyles);
}
// ----- Public
public focusFindInput(): void {
this._findInput.focus();
}
public highlightFindOptions(): void {
this._findInput.highlightFindOptions();
}
private _onFindInputMouseDown(e: IMouseEvent): void {
// on linux, middle key does pasting.
if (e.middleButton) {
e.stopPropagation();
}
}
private _onFindInputKeyDown(e: IKeyboardEvent): void {
if (e.equals(KeyCode.Enter)) {
this._notebookController.getAction(ACTION_IDS.FIND_NEXT).run().then(null, onUnexpectedError);
e.preventDefault();
return;
}
if (e.equals(KeyMod.Shift | KeyCode.Enter)) {
this._notebookController.getAction(ACTION_IDS.FIND_PREVIOUS).run().then(null, onUnexpectedError);
e.preventDefault();
return;
}
if (e.equals(KeyCode.Tab)) {
this._findInput.focusOnCaseSensitive();
e.preventDefault();
return;
}
if (e.equals(KeyMod.CtrlCmd | KeyCode.DownArrow)) {
this._notebookController.focus();
e.preventDefault();
return;
}
}
// ----- sash
public getHorizontalSashTop(sash: Sash): number {
return 0;
}
public getHorizontalSashLeft?(sash: Sash): number {
return 0;
}
public getHorizontalSashWidth?(sash: Sash): number {
return 500;
}
// ----- initialization
private _keybindingLabelFor(actionId: string): string {
let kb = this._keybindingService.lookupKeybinding(actionId);
if (!kb) {
return '';
}
return ` (${kb.getLabel()})`;
}
private _buildFindPart(): HTMLElement {
// Find input
this._findInput = this._register(new FindInput(null, this._contextViewProvider, true, {
width: FIND_INPUT_AREA_WIDTH,
label: NLS_FIND_INPUT_LABEL,
placeholder: NLS_FIND_INPUT_PLACEHOLDER,
appendCaseSensitiveLabel: this._keybindingLabelFor(FIND_IDS.ToggleCaseSensitiveCommand),
appendWholeWordsLabel: this._keybindingLabelFor(FIND_IDS.ToggleWholeWordCommand),
appendRegexLabel: this._keybindingLabelFor(FIND_IDS.ToggleRegexCommand),
validation: (value: string): InputBoxMessage => {
if (value.length === 0) {
return null;
}
if (!this._findInput.getRegex()) {
return null;
}
try {
/* tslint:disable:no-unused-expression */
new RegExp(value);
/* tslint:enable:no-unused-expression */
return null;
} catch (e) {
return { content: e.message };
}
}
}));
this._findInput.setRegex(!!this._state.isRegex);
this._findInput.setCaseSensitive(!!this._state.matchCase);
this._findInput.setWholeWords(!!this._state.wholeWord);
this._register(this._findInput.onKeyDown((e) => this._onFindInputKeyDown(e)));
this._register(this._findInput.onInput(() => {
let self = this;
if (self.searchTimeoutHandle) {
window.clearTimeout(self.searchTimeoutHandle);
}
this.searchTimeoutHandle = window.setTimeout(function () {
self._state.change({ searchString: self._findInput.getValue() }, true);
}, 300);
}));
this._register(this._findInput.onDidOptionChange(() => {
this._state.change({
isRegex: this._findInput.getRegex(),
wholeWord: this._findInput.getWholeWords(),
matchCase: this._findInput.getCaseSensitive()
}, true);
}));
if (platform.isLinux) {
this._register(this._findInput.onMouseDown((e) => this._onFindInputMouseDown(e)));
}
this._matchesCount = document.createElement('div');
this._matchesCount.className = 'matchesCount';
this._updateMatchesCount();
// Previous button
this._prevBtn = this._register(new SimpleButton({
label: NLS_PREVIOUS_MATCH_BTN_LABEL + this._keybindingLabelFor(FIND_IDS.PreviousMatchFindAction),
className: 'codicon codicon-arrow-up',
onTrigger: () => {
this._notebookController.getAction(ACTION_IDS.FIND_PREVIOUS).run().then(null, onUnexpectedError);
},
onKeyDown: (e) => { }
}));
// Next button
this._nextBtn = this._register(new SimpleButton({
label: NLS_NEXT_MATCH_BTN_LABEL + this._keybindingLabelFor(FIND_IDS.NextMatchFindAction),
className: 'codicon codicon-arrow-down',
onTrigger: () => {
this._notebookController.getAction(ACTION_IDS.FIND_NEXT).run().then(null, onUnexpectedError);
},
onKeyDown: (e) => { }
}));
let findPart = document.createElement('div');
findPart.className = 'find-part';
findPart.appendChild(this._findInput.domNode);
findPart.appendChild(this._matchesCount);
findPart.appendChild(this._prevBtn.domNode);
findPart.appendChild(this._nextBtn.domNode);
// Close button
this._closeBtn = this._register(new SimpleButton({
label: NLS_CLOSE_BTN_LABEL + this._keybindingLabelFor(FIND_IDS.CloseFindWidgetCommand),
className: 'codicon codicon-close',
onTrigger: () => {
this._state.change({ isRevealed: false, searchScope: null }, false);
},
onKeyDown: () => { }
}));
findPart.appendChild(this._closeBtn.domNode);
return findPart;
}
private _buildDomNode(): void {
// Find part
let findPart = this._buildFindPart();
// Widget
this._domNode = document.createElement('div');
this._domNode.className = 'editor-widget find-widget';
this._domNode.setAttribute('aria-hidden', 'true');
this._domNode.appendChild(findPart);
this._buildSash();
}
private _buildSash() {
this._resizeSash = new Sash(this._domNode, this, { orientation: Orientation.VERTICAL });
let originalWidth = FIND_WIDGET_INITIAL_WIDTH;
this._register(this._resizeSash.onDidStart((e: ISashEvent) => {
originalWidth = dom.getTotalWidth(this._domNode);
}));
this._register(this._resizeSash.onDidChange((evt: ISashEvent) => {
let width = originalWidth + evt.startX - evt.currentX;
if (width < FIND_WIDGET_INITIAL_WIDTH) {
// narrow down the find widget should be handled by CSS.
return;
}
let maxWidth = parseFloat(dom.getComputedStyle(this._domNode).maxWidth) || 0;
if (width > maxWidth) {
return;
}
this._domNode.style.width = `${width}px`;
}));
}
}
interface ISimpleButtonOpts {
label: string;
className: string;
onTrigger: () => void;
onKeyDown: (e: IKeyboardEvent) => void;
}
class SimpleButton extends Widget {
private _opts: ISimpleButtonOpts;
private _domNode: HTMLElement;
constructor(opts: ISimpleButtonOpts) {
super();
this._opts = opts;
this._domNode = document.createElement('div');
this._domNode.title = this._opts.label;
this._domNode.tabIndex = 0;
this._domNode.className = 'button ' + this._opts.className;
this._domNode.setAttribute('role', 'button');
this._domNode.setAttribute('aria-label', this._opts.label);
this.onclick(this._domNode, (e) => {
this._opts.onTrigger();
e.preventDefault();
});
this.onkeydown(this._domNode, (e) => {
if (e.equals(KeyCode.Space) || e.equals(KeyCode.Enter)) {
this._opts.onTrigger();
e.preventDefault();
return;
}
this._opts.onKeyDown(e);
});
}
public get domNode(): HTMLElement {
return this._domNode;
}
public isEnabled(): boolean {
return (this._domNode.tabIndex >= 0);
}
public focus(): void {
this._domNode.focus();
}
public setEnabled(enabled: boolean): void {
dom.toggleClass(this._domNode, 'disabled', !enabled);
this._domNode.setAttribute('aria-disabled', String(!enabled));
this._domNode.tabIndex = enabled ? 0 : -1;
}
public setExpanded(expanded: boolean): void {
this._domNode.setAttribute('aria-expanded', String(!!expanded));
}
public toggleClass(className: string, shouldHaveIt: boolean): void {
dom.toggleClass(this._domNode, className, shouldHaveIt);
}
}

View File

@@ -5,7 +5,7 @@
import { Event } from 'vs/base/common/event';
import { IModelDecorationsChangeAccessor } from 'vs/editor/common/model';
import { NotebookFindMatch } from 'sql/workbench/contrib/notebook/find/notebookFindDecorations';
import { NotebookFindMatch } from 'sql/workbench/contrib/notebook/browser/find/notebookFindDecorations';
import { NotebookRange } from 'sql/workbench/services/notebook/browser/notebookService';
export interface INotebookFindModel {

View File

@@ -31,7 +31,7 @@ import { UntitledTextEditorInput } from 'vs/workbench/services/untitled/common/u
import { ResourceEditorInput } from 'vs/workbench/common/editor/resourceEditorInput';
import { FileEditorInput } from 'vs/workbench/contrib/files/common/editors/fileEditorInput';
import { BinaryEditorModel } from 'vs/workbench/common/editor/binaryEditorModel';
import { NotebookFindModel } from 'sql/workbench/contrib/notebook/find/notebookFindModel';
import { NotebookFindModel } from 'sql/workbench/contrib/notebook/browser/find/notebookFindModel';
import { onUnexpectedError } from 'vs/base/common/errors';
export type ModeViewSaveHandler = (handle: number) => Thenable<boolean>;

View File

@@ -21,7 +21,7 @@ import { ICommandService } from 'vs/platform/commands/common/commands';
import { CellType } from 'sql/workbench/services/notebook/common/contracts';
import { getErrorMessage } from 'vs/base/common/errors';
import { IEditorAction } from 'vs/editor/common/editorCommon';
import { IFindNotebookController } from 'sql/workbench/contrib/notebook/find/notebookFindWidget';
import { IFindNotebookController } from 'sql/workbench/contrib/notebook/browser/find/notebookFindWidget';
import { INotebookModel } from 'sql/workbench/services/notebook/browser/models/modelInterfaces';
import { IObjectExplorerService } from 'sql/workbench/services/objectExplorer/browser/objectExplorerService';
import { TreeUpdateUtils } from 'sql/workbench/services/objectExplorer/browser/treeUpdateUtils';

View File

@@ -16,7 +16,7 @@ import { NotebookModule } from 'sql/workbench/contrib/notebook/browser/notebook.
import { NOTEBOOK_SELECTOR } from 'sql/workbench/contrib/notebook/browser/notebook.component';
import { INotebookParams, INotebookService, NotebookRange } from 'sql/workbench/services/notebook/browser/notebookService';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { ACTION_IDS, NOTEBOOK_MAX_MATCHES, IFindNotebookController, FindWidget, IConfigurationChangedEvent } from 'sql/workbench/contrib/notebook/find/notebookFindWidget';
import { ACTION_IDS, NOTEBOOK_MAX_MATCHES, IFindNotebookController, FindWidget, IConfigurationChangedEvent } from 'sql/workbench/contrib/notebook/browser/find/notebookFindWidget';
import { IOverlayWidget } from 'vs/editor/browser/editorBrowser';
import { FindReplaceState, FindReplaceStateChangedEvent } from 'vs/editor/contrib/find/findState';
import { IEditorAction } from 'vs/editor/common/editorCommon';
@@ -30,7 +30,7 @@ import { INotebookModel } from 'sql/workbench/services/notebook/browser/models/m
import { INotebookFindModel } from 'sql/workbench/contrib/notebook/browser/models/notebookFindModel';
import { IDisposable, DisposableStore, dispose } from 'vs/base/common/lifecycle';
import { IModelDecorationsChangeAccessor, IModelDeltaDecoration } from 'vs/editor/common/model';
import { NotebookFindDecorations } from 'sql/workbench/contrib/notebook/find/notebookFindDecorations';
import { NotebookFindDecorations } from 'sql/workbench/contrib/notebook/browser/find/notebookFindDecorations';
import { TimeoutTimer } from 'vs/base/common/async';
import { BaseTextEditor } from 'vs/workbench/browser/parts/editor/textEditor';
import { onUnexpectedError } from 'vs/base/common/errors';

View File

@@ -3,10 +3,6 @@
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!../cellViews/textCell';
import 'vs/css!../cellViews/media/markdown';
import 'vs/css!../cellViews/media/highlight';
import { OnInit, Component, Input, Inject, ElementRef, ViewChild } from '@angular/core';
import { AngularDisposable } from 'sql/base/browser/lifecycle';
import { IMimeComponent } from 'sql/workbench/contrib/notebook/browser/outputs/mimeRegistry';