split mainThreadNotebook up into logical pieces

* notebookDocumentsAndEditors -> owns the truth of the notebooks and editor that extensions know about
* notebookEditor -> everything about editors
* notebookDocuments -> everything about documents
This commit is contained in:
Johannes Rieken
2021-03-31 15:44:31 +02:00
parent dd360b25da
commit fa48622fdf
9 changed files with 624 additions and 437 deletions

View File

@@ -5,97 +5,18 @@
import { VSBuffer } from 'vs/base/common/buffer';
import { CancellationToken } from 'vs/base/common/cancellation';
import { diffMaps, diffSets } from 'vs/base/common/collections';
import { Emitter } from 'vs/base/common/event';
import { IRelativePattern } from 'vs/base/common/glob';
import { DisposableStore, dispose, IDisposable } from 'vs/base/common/lifecycle';
import { ResourceMap } from 'vs/base/common/map';
import { URI, UriComponents } from 'vs/base/common/uri';
import { EditorActivation, EditorOverride } from 'vs/platform/editor/common/editor';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ILogService } from 'vs/platform/log/common/log';
import { BoundModelReferenceCollection } from 'vs/workbench/api/browser/mainThreadDocuments';
import { extHostNamedCustomer } from 'vs/workbench/api/common/extHostCustomers';
import { getNotebookEditorFromEditorPane, IActiveNotebookEditor, INotebookEditor, NotebookEditorOptions } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { NotebookEditorInput } from 'vs/workbench/contrib/notebook/common/notebookEditorInput';
import { INotebookEditorService } from 'vs/workbench/contrib/notebook/browser/notebookEditorService';
import { NotebookCellTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookCellTextModel';
import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel';
import { INotebookCellStatusBarService } from 'vs/workbench/contrib/notebook/common/notebookCellStatusBarService';
import { ICellEditOperation, ICellRange, IImmediateCellEditOperation, IMainCellDto, INotebookDecorationRenderOptions, INotebookDocumentFilter, INotebookExclusiveDocumentFilter, INotebookKernel, NotebookCellsChangeType, NotebookDataDto, TransientMetadata, TransientOptions } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { INotebookEditorModelResolverService } from 'vs/workbench/contrib/notebook/common/notebookEditorModelResolverService';
import { ICellRange, INotebookDocumentFilter, INotebookExclusiveDocumentFilter, INotebookKernel, NotebookDataDto, TransientMetadata, TransientOptions } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { IMainNotebookController, INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IUriIdentityService } from 'vs/workbench/services/uriIdentity/common/uriIdentity';
import { ExtHostContext, ExtHostNotebookShape, IExtHostContext, INotebookCellStatusBarEntryDto, INotebookDocumentsAndEditorsDelta, INotebookDocumentShowOptions, INotebookEditorAddData, INotebookModelAddedData, MainContext, MainThreadNotebookShape, NotebookEditorRevealType, NotebookExtensionDescription } from '../common/extHost.protocol';
class NotebookAndEditorState {
static compute(before: NotebookAndEditorState | undefined, after: NotebookAndEditorState): INotebookDocumentsAndEditorsDelta {
if (!before) {
return {
addedDocuments: [...after.documents].map(NotebookAndEditorState._asModelAddData),
addedEditors: [...after.textEditors.values()].map(NotebookAndEditorState._asEditorAddData),
visibleEditors: [...after.visibleEditors].map(editor => editor[0])
};
}
const documentDelta = diffSets(before.documents, after.documents);
const editorDelta = diffMaps(before.textEditors, after.textEditors);
const addedAPIEditors = editorDelta.added.map(NotebookAndEditorState._asEditorAddData);
const removedAPIEditors = editorDelta.removed.map(removed => removed.getId());
const newActiveEditor = before.activeEditor !== after.activeEditor ? after.activeEditor : undefined;
const visibleEditorDelta = diffMaps(before.visibleEditors, after.visibleEditors);
return {
addedDocuments: documentDelta.added.map(NotebookAndEditorState._asModelAddData),
removedDocuments: documentDelta.removed.map(e => e.uri),
addedEditors: addedAPIEditors,
removedEditors: removedAPIEditors,
newActiveEditor: newActiveEditor,
visibleEditors: visibleEditorDelta.added.length === 0 && visibleEditorDelta.removed.length === 0
? undefined
: [...after.visibleEditors].map(editor => editor[0])
};
}
constructor(
readonly documents: Set<NotebookTextModel>,
readonly textEditors: Map<string, IActiveNotebookEditor>,
readonly activeEditor: string | null | undefined,
readonly visibleEditors: Map<string, IActiveNotebookEditor>
) {
//
}
private static _asModelAddData(e: NotebookTextModel): INotebookModelAddedData {
return {
viewType: e.viewType,
uri: e.uri,
metadata: e.metadata,
versionId: e.versionId,
cells: e.cells.map(cell => ({
handle: cell.handle,
uri: cell.uri,
source: cell.textBuffer.getLinesContent(),
eol: cell.textBuffer.getEOL(),
language: cell.language,
cellKind: cell.cellKind,
outputs: cell.outputs,
metadata: cell.metadata
}))
};
}
private static _asEditorAddData(add: IActiveNotebookEditor): INotebookEditorAddData {
return {
id: add.getId(),
documentUri: add.viewModel.uri,
selections: add.getSelections(),
visibleRanges: add.visibleRanges,
viewColumn: undefined
};
}
}
import { ExtHostContext, ExtHostNotebookShape, IExtHostContext, INotebookCellStatusBarEntryDto, MainContext, MainThreadNotebookShape, NotebookExtensionDescription } from '../common/extHost.protocol';
@extHostNamedCustomer(MainContext.MainThreadNotebook)
export class MainThreadNotebooks implements MainThreadNotebookShape {
@@ -106,34 +27,25 @@ export class MainThreadNotebooks implements MainThreadNotebookShape {
private readonly _notebookProviders = new Map<string, { controller: IMainNotebookController, disposable: IDisposable }>();
private readonly _notebookSerializer = new Map<number, IDisposable>();
private readonly _notebookKernelProviders = new Map<number, { extension: NotebookExtensionDescription, emitter: Emitter<URI | undefined>, provider: IDisposable }>();
private readonly _editorEventListenersMapping = new Map<string, DisposableStore>();
private readonly _documentEventListenersMapping = new ResourceMap<DisposableStore>();
private readonly _cellStatusBarEntries = new Map<number, IDisposable>();
private readonly _modelReferenceCollection: BoundModelReferenceCollection;
private _currentState?: NotebookAndEditorState;
constructor(
extHostContext: IExtHostContext,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
@IInstantiationService instantiationService: IInstantiationService,
@INotebookService private readonly _notebookService: INotebookService,
@INotebookEditorService private readonly _notebookEditorService: INotebookEditorService,
@IEditorService private readonly _editorService: IEditorService,
@ILogService private readonly _logService: ILogService,
@INotebookCellStatusBarService private readonly _cellStatusBarService: INotebookCellStatusBarService,
@INotebookEditorModelResolverService private readonly _notebookEditorModelResolverService: INotebookEditorModelResolverService,
@IUriIdentityService private readonly _uriIdentityService: IUriIdentityService
) {
this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostNotebook);
this._modelReferenceCollection = new BoundModelReferenceCollection(this._uriIdentityService.extUri);
this._registerListeners();
}
dispose(): void {
this._disposables.dispose();
this._modelReferenceCollection.dispose();
// remove all notebook providers
for (const item of this._notebookProviders.values()) {
item.disposable.dispose();
@@ -145,238 +57,14 @@ export class MainThreadNotebooks implements MainThreadNotebookShape {
item.provider.dispose();
}
dispose(this._notebookSerializer.values());
dispose(this._editorEventListenersMapping.values());
dispose(this._documentEventListenersMapping.values());
dispose(this._cellStatusBarEntries.values());
}
async $tryApplyEdits(_viewType: string, resource: UriComponents, modelVersionId: number, cellEdits: ICellEditOperation[]): Promise<boolean> {
const textModel = this._notebookService.getNotebookTextModel(URI.from(resource));
if (!textModel) {
return false;
}
if (textModel.versionId !== modelVersionId) {
return false;
}
return textModel.applyEdits(cellEdits, true, undefined, () => undefined, undefined);
}
async $applyEdits(resource: UriComponents, cellEdits: IImmediateCellEditOperation[], computeUndoRedo = true): Promise<void> {
const textModel = this._notebookService.getNotebookTextModel(URI.from(resource));
if (!textModel) {
throw new Error(`Can't apply edits to unknown notebook model: ${resource}`);
}
textModel.applyEdits(cellEdits, true, undefined, () => undefined, undefined, computeUndoRedo);
}
private _registerListeners(): void {
this._notebookEditorModelResolverService.onDidChangeDirty(model => {
this._proxy.$acceptDirtyStateChanged(model.resource, model.isDirty);
});
this._disposables.add(this._notebookEditorModelResolverService.onDidSaveNotebook(e => {
this._proxy.$acceptModelSaved(e);
}));
this._disposables.add(this._editorService.onDidActiveEditorChange(e => {
this._updateState();
}));
this._disposables.add(this._editorService.onDidVisibleEditorsChange(e => {
if (this._notebookProviders.size > 0) { // TODO@rebornix propably wrong, what about providers from another host
if (!this._currentState) {
// no current state means we didn't even create editors in ext host yet.
return;
}
// we can't simply update visibleEditors as we need to check if we should create editors first.
this._updateState();
}
}));
const handleNotebookEditorAdded = (editor: INotebookEditor) => {
if (this._editorEventListenersMapping.has(editor.getId())) {
//todo@jrieken a bug when this happens?
return;
}
const disposableStore = new DisposableStore();
disposableStore.add(editor.onDidChangeVisibleRanges(() => {
this._proxy.$acceptEditorPropertiesChanged(editor.getId(), { visibleRanges: { ranges: editor.visibleRanges } });
}));
disposableStore.add(editor.onDidChangeSelection(() => {
this._proxy.$acceptEditorPropertiesChanged(editor.getId(), { selections: { selections: editor.getSelections() } });
}));
disposableStore.add(editor.onDidChangeKernel(() => {
if (!editor.hasModel()) {
return;
}
this._proxy.$acceptNotebookActiveKernelChange({
uri: editor.viewModel.uri,
providerHandle: editor.activeKernel?.providerHandle,
kernelFriendlyId: editor.activeKernel?.friendlyId
});
}));
disposableStore.add(editor.onDidChangeModel(() => this._updateState()));
disposableStore.add(editor.onDidFocusEditorWidget(() => this._updateState(editor)));
this._editorEventListenersMapping.set(editor.getId(), disposableStore);
const activeNotebookEditor = getNotebookEditorFromEditorPane(this._editorService.activeEditorPane);
this._updateState(activeNotebookEditor);
};
this._notebookEditorService.listNotebookEditors().forEach(handleNotebookEditorAdded);
this._disposables.add(this._notebookEditorService.onDidAddNotebookEditor(handleNotebookEditorAdded));
this._disposables.add(this._notebookEditorService.onDidRemoveNotebookEditor(editor => {
this._editorEventListenersMapping.get(editor.getId())?.dispose();
this._editorEventListenersMapping.delete(editor.getId());
this._updateState();
}));
const cellToDto = (cell: NotebookCellTextModel): IMainCellDto => {
return {
handle: cell.handle,
uri: cell.uri,
source: cell.textBuffer.getLinesContent(),
eol: cell.textBuffer.getEOL(),
language: cell.language,
cellKind: cell.cellKind,
outputs: cell.outputs,
metadata: cell.metadata
};
};
const handleNotebookDocumentAdded = (textModel: NotebookTextModel) => {
if (this._documentEventListenersMapping.has(textModel.uri)) {
//todo@jrieken a bug when this happens?
return;
}
const disposableStore = new DisposableStore();
disposableStore.add(textModel.onDidChangeContent(event => {
const dto = event.rawEvents.map(e => {
const data =
e.kind === NotebookCellsChangeType.ModelChange || e.kind === NotebookCellsChangeType.Initialize
? {
kind: e.kind,
versionId: event.versionId,
changes: e.changes.map(diff => [diff[0], diff[1], diff[2].map(cell => cellToDto(cell as NotebookCellTextModel))] as [number, number, IMainCellDto[]])
}
: (
e.kind === NotebookCellsChangeType.Move
? {
kind: e.kind,
index: e.index,
length: e.length,
newIdx: e.newIdx,
versionId: event.versionId,
cells: e.cells.map(cell => cellToDto(cell as NotebookCellTextModel))
}
: e
);
return data;
});
// using the model resolver service to know if the model is dirty or not.
// assuming this is the first listener it can mean that at first the model
// is marked as dirty and that another event is fired
this._proxy.$acceptModelChanged(
textModel.uri,
{ rawEvents: dto, versionId: event.versionId },
this._notebookEditorModelResolverService.isDirty(textModel.uri)
);
const hasDocumentMetadataChangeEvent = event.rawEvents.find(e => e.kind === NotebookCellsChangeType.ChangeDocumentMetadata);
if (!!hasDocumentMetadataChangeEvent) {
this._proxy.$acceptDocumentPropertiesChanged(textModel.uri, { metadata: textModel.metadata });
}
}));
this._documentEventListenersMapping.set(textModel!.uri, disposableStore);
};
this._notebookService.listNotebookDocuments().forEach(handleNotebookDocumentAdded);
this._disposables.add(this._notebookService.onDidAddNotebookDocument(document => {
handleNotebookDocumentAdded(document);
this._updateState();
}));
this._disposables.add(this._notebookService.onDidRemoveNotebookDocument(uri => {
this._documentEventListenersMapping.get(uri)?.dispose();
this._documentEventListenersMapping.delete(uri);
this._updateState();
}));
this._disposables.add(this._notebookService.onDidChangeNotebookActiveKernel(e => {
this._proxy.$acceptNotebookActiveKernelChange(e);
}));
const notebookEditor = getNotebookEditorFromEditorPane(this._editorService.activeEditorPane);
this._updateState(notebookEditor);
}
private _updateState(focusedNotebookEditor?: INotebookEditor): void {
const activeNotebookEditor = getNotebookEditorFromEditorPane(this._editorService.activeEditorPane);
let activeEditor = activeNotebookEditor?.hasModel() ? activeNotebookEditor.getId() : null;
const editors = new Map<string, IActiveNotebookEditor>();
const visibleEditorsMap = new Map<string, IActiveNotebookEditor>();
for (const editor of this._notebookEditorService.listNotebookEditors()) {
if (editor.hasModel()) {
editors.set(editor.getId(), editor);
}
}
this._editorService.visibleEditorPanes.forEach(editorPane => {
const notebookEditor = getNotebookEditorFromEditorPane(editorPane);
if (notebookEditor?.hasModel() && editors.has(notebookEditor.getId())) {
visibleEditorsMap.set(notebookEditor.getId(), notebookEditor);
}
});
if (!activeEditor && focusedNotebookEditor?.textModel) {
activeEditor = focusedNotebookEditor.getId();
}
const newState = new NotebookAndEditorState(new Set(this._notebookService.listNotebookDocuments()), editors, activeEditor, visibleEditorsMap);
const delta = NotebookAndEditorState.compute(this._currentState, newState);
this._currentState = newState;
if (!this._isDeltaEmpty(delta)) {
return this._proxy.$acceptDocumentAndEditorsDelta(delta);
}
}
private _isDeltaEmpty(delta: INotebookDocumentsAndEditorsDelta): boolean {
if (delta.addedDocuments !== undefined && delta.addedDocuments.length > 0) {
return false;
}
if (delta.removedDocuments !== undefined && delta.removedDocuments.length > 0) {
return false;
}
if (delta.addedEditors !== undefined && delta.addedEditors.length > 0) {
return false;
}
if (delta.removedEditors !== undefined && delta.removedEditors.length > 0) {
return false;
}
if (delta.visibleEditors !== undefined && delta.visibleEditors.length > 0) {
return false;
}
if (delta.newActiveEditor !== undefined) {
return false;
}
return true;
}
async $registerNotebookProvider(extension: NotebookExtensionDescription, viewType: string, options: {
@@ -534,49 +222,6 @@ export class MainThreadNotebooks implements MainThreadNotebookShape {
return true;
}
async $tryRevealRange(id: string, range: ICellRange, revealType: NotebookEditorRevealType): Promise<void> {
const editor = this._notebookEditorService.getNotebookEditor(id);
if (!editor) {
return;
}
const notebookEditor = editor as INotebookEditor;
if (!notebookEditor.hasModel()) {
return;
}
const viewModel = notebookEditor.viewModel;
const cell = viewModel.viewCells[range.start];
if (!cell) {
return;
}
switch (revealType) {
case NotebookEditorRevealType.Default:
return notebookEditor.revealCellRangeInView(range);
case NotebookEditorRevealType.InCenter:
return notebookEditor.revealInCenter(cell);
case NotebookEditorRevealType.InCenterIfOutsideViewport:
return notebookEditor.revealInCenterIfOutsideViewport(cell);
case NotebookEditorRevealType.AtTop:
return notebookEditor.revealInViewAtTop(cell);
}
}
$registerNotebookEditorDecorationType(key: string, options: INotebookDecorationRenderOptions): void {
this._notebookEditorService.registerEditorDecorationType(key, options);
}
$removeNotebookEditorDecorationType(key: string): void {
this._notebookEditorService.removeEditorDecorationType(key);
}
$trySetDecorations(id: string, range: ICellRange, key: string): void {
const editor = this._notebookEditorService.getNotebookEditor(id);
if (editor) {
const notebookEditor = editor as INotebookEditor;
notebookEditor.setEditorDecorations(key, range);
}
}
async $setStatusBarEntry(id: number, rawStatusBarEntry: INotebookCellStatusBarEntryDto): Promise<void> {
const statusBarEntry = {
...rawStatusBarEntry,
@@ -592,44 +237,4 @@ export class MainThreadNotebooks implements MainThreadNotebookShape {
this._cellStatusBarEntries.set(id, this._cellStatusBarService.addEntry(statusBarEntry));
}
}
async $tryOpenDocument(uriComponents: UriComponents): Promise<URI> {
const uri = URI.revive(uriComponents);
const ref = await this._notebookEditorModelResolverService.resolve(uri, undefined);
this._modelReferenceCollection.add(uri, ref);
return uri;
}
async $trySaveDocument(uriComponents: UriComponents) {
const uri = URI.revive(uriComponents);
const ref = await this._notebookEditorModelResolverService.resolve(uri);
const saveResult = await ref.object.save();
ref.dispose();
return saveResult;
}
async $tryShowNotebookDocument(resource: UriComponents, viewType: string, options: INotebookDocumentShowOptions): Promise<string> {
const editorOptions = new NotebookEditorOptions({
cellSelections: options.selection && [options.selection],
preserveFocus: options.preserveFocus,
pinned: options.pinned,
// selection: options.selection,
// preserve pre 1.38 behaviour to not make group active when preserveFocus: true
// but make sure to restore the editor to fix https://github.com/microsoft/vscode/issues/79633
activation: options.preserveFocus ? EditorActivation.RESTORE : undefined,
override: EditorOverride.DISABLED,
});
const input = NotebookEditorInput.create(this._instantiationService, URI.revive(resource), viewType);
const editorPane = await this._editorService.openEditor(input, editorOptions, options.position);
const notebookEditor = getNotebookEditorFromEditorPane(editorPane);
if (notebookEditor) {
return notebookEditor.getId();
} else {
throw new Error(`Notebook Editor creation failure for documenet ${resource}`);
}
}
}