Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

All notable changes to the Simulink Data Explorer extension.

## Unreleased

- View as Text from the Command Palette now opens the dictionary's text.
- Search Data Source Entries finds an entry by its new name as soon as you rename it, instead of offering the old name until your next edit or save.

## [1.54.0] — 2026-11-01

The fixes from the 1.47 to 1.53 pre-releases, as a stable release:
Expand Down
24 changes: 18 additions & 6 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,16 @@ async function openInBestEditor(uri: vscode.Uri, options?: { preview?: boolean }
await vscode.commands.executeCommand('vscode.openWith', uri, viewType, openOptions);
}

// The file of the tab in focus, for a command run from the Command Palette, which
// passes no argument. Read from the tab, not from activeTextEditor: while a table
// has focus there is no active text editor (the table is a webview), and that is
// exactly when the palette lists View as Text.
function activeResourceUri(): vscode.Uri | undefined {
const input = vscode.window.tabGroups.activeTabGroup.activeTab?.input;
if (input instanceof vscode.TabInputCustom || input instanceof vscode.TabInputText) return input.uri;
return vscode.window.activeTextEditor?.document.uri;
}

export function activate(context: vscode.ExtensionContext): void {
const provider = new SectionsTreeProvider(context.extensionUri);
const piProvider = new PropertiesViewProvider(context.extensionUri);
Expand Down Expand Up @@ -296,9 +306,11 @@ export function activate(context: vscode.ExtensionContext): void {
// A dirty-state transition on any supported file changes the "modified"
// health badge, so refresh decorations for supported docs. Also re-sync
// the name index for live entry-name edits (e.g. renaming an entry in an
// open .sldd); reindexFile is a no-op until the index is first built.
// open .sldd); reindexFile is a no-op until the index is first built. Handed the
// document, because the first edit of a clean one arrives while it still reads
// clean: the index reads its text, not the file (documentText.ts).
if (isSupportedPath(e.document.uri.path)) {
void reindexFile(e.document.uri);
void reindexFile(e.document.uri, e.document);
refreshBadges();
}
}),
Expand Down Expand Up @@ -358,15 +370,15 @@ export function activate(context: vscode.ExtensionContext): void {
// SECOND tab for the URI rather than converting the current tab in place —
// an editor tab's type is fixed for its lifetime, so table and text coexist
// as separate tabs. Editor/title menu commands pass the active resource URI
// as the first argument; fall back to the active editor's document when
// invoked from the palette.
// as the first argument; from the palette, which passes none, the file is the
// active tab's (activeResourceUri).
vscode.commands.registerCommand('dataExplorer.viewAsText', (uri?: vscode.Uri) => {
const target = uri ?? vscode.window.activeTextEditor?.document.uri;
const target = uri ?? activeResourceUri();
if (!target) return;
void vscode.commands.executeCommand('vscode.openWith', target, 'default');
}),
vscode.commands.registerCommand('dataExplorer.viewAsTable', async (uri?: vscode.Uri) => {
const target = uri ?? vscode.window.activeTextEditor?.document.uri;
const target = uri ?? activeResourceUri();
if (!target) return;
// Editable JSON .sldd → text-backed table (native undo/redo); else binary.
await openInBestEditor(target);
Expand Down
31 changes: 31 additions & 0 deletions src/host/documentText.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright 2026 The MathWorks, Inc.
//
// Which text the window's name index scans for a file instead of the file on disk (nameIndex.ts).
// vscode-free, so that the decision is unit-tested (test/documentText.test.ts).

/** What of an open TextDocument the decision reads. */
export interface OpenText {
readonly uri: { toString(): string };
readonly isDirty: boolean;
readonly isClosed: boolean;
getText(): string;
}

/**
* The text a scan of `uriString` reads instead of the file, or undefined to read the file.
*
* `changed` is the document whose content change the scan answers, when it answers one. Its text is
* the file as the user has it, whatever the dirty flag says yet: VS Code reports an edit to a CLEAN
* document while the document still reads clean, and the dirty flag only after it, as a change of its
* own that carries no content. Asking `isDirty` alone sent that first edit's scan to the disk: a
* read of the whole file on the first edit after every open or save, and the names the file had
* before the edit, offered by the search until the next edit.
*
* Any other open document counts only while it is dirty. A clean one holds what the file holds, which
* the file is read for through the shared cache: a stat, for a file that has not changed.
*/
export function textOverDisk(uriString: string, changed: OpenText | undefined, open: readonly OpenText[]): string | undefined {
if (changed && !changed.isClosed && changed.uri.toString() === uriString) return changed.getText();
const doc = open.find((d) => d.uri.toString() === uriString);
return doc?.isDirty ? doc.getText() : undefined;
}
42 changes: 31 additions & 11 deletions src/host/nameIndex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { NameIndex, type NameReader, type NameRecord } from 'data-explorer-view/
import { toArrayBuffer } from '../common/bytes.js';
import { GRAPH_GLOB } from '../common/fileTypes.js';
import { readerFor, sourceCache, sourceFilesOf } from './sourceReads.js';
import { textOverDisk } from './documentText.js';

export type { EntryKind, NameRecord } from 'data-explorer-view/model';

Expand All @@ -27,22 +28,25 @@ export type { EntryKind, NameRecord } from 'data-explorer-view/model';
// new one, until the file was saved. The reindex looked like it worked, because
// it did run — it just re-read the wrong bytes.
//
// A dirty document is only ever text: VS Code cannot mirror a compressed-binary
// .sldd as a TextDocument, and the writable binary editor keeps its edits in its
// own edit stack rather than a TextDocument, so `isDirty` here always implies the
// JSON format and encoding the string back to bytes is lossless. A clean (or
// unopened) document has no in-memory state worth preferring, so it reads disk —
// which also keeps the full build unaffected.
// Which text counts is documentText.ts's: the document whose content change the reindex
// answers, whatever its dirty flag says yet (VS Code reports the first edit of a clean
// document while it still reads clean), and any other open document while it is dirty.
//
// Such a document is only ever text: VS Code cannot mirror a compressed-binary .sldd as a
// TextDocument, and the writable binary editor keeps its edits in its own edit stack
// rather than a TextDocument, so this is always the JSON format and encoding the string
// back to bytes is lossless. A clean (or unopened) document has no in-memory state worth
// preferring, so it reads disk — which also keeps the full build unaffected.
//
// Answering `null` rather than the disk bytes is what lets view's nameScan tell the two
// cases apart, and it has to: buffer bytes must never be stored in the shared
// cache, whose keys are the DISK file's `mtime:size`.
function dirtyBytesOf(file: SourceFile): ArrayBuffer | null {
const open = vscode.workspace.textDocuments.find((d) => d.uri.toString() === file.uriString);
if (!open?.isDirty) return null;
const text = textOverDisk(file.uriString, changing.get(file.uriString)?.doc, vscode.workspace.textDocuments);
if (text === undefined) return null;
// Already in memory and already bounded — VS Code will not mirror a document
// this scan's cap would exclude (its own sync limit is far below it).
return toArrayBuffer(new TextEncoder().encode(open.getText()));
return toArrayBuffer(new TextEncoder().encode(text));
}

// How this index reads: the shared cache's own scan reader — same cap, same
Expand All @@ -58,6 +62,11 @@ function nameReader(uris: readonly vscode.Uri[]): NameReader {
const listed = new WeakMap<readonly SourceFile[], readonly vscode.Uri[]>();
const reindexed = new Map<string, vscode.Uri>();

// The document whose content change a reindex in flight answers, by file, and how many such
// reindexes are in flight: held for those reindexes alone, so a reindex for any other reason (the
// folder's watcher) reads the file as it did.
const changing = new Map<string, { doc: vscode.TextDocument; pending: number }>();

/** The window's name index. */
export const nameIndex = new NameIndex({
files: {
Expand Down Expand Up @@ -96,10 +105,21 @@ export function listEntries(): Promise<NameRecord[]> {
// this is a no-op — building an index off a single file would give incomplete answers, so the
// first listEntries() does the full scan instead. Once built, this keeps the index current after
// an edit without a full rebuild.
export function reindexFile(uri: vscode.Uri): Promise<void> {
//
// `changed` is the document when the reindex answers its content change: its text is read, not
// the file (see dirtyBytesOf).
export function reindexFile(uri: vscode.Uri, changed?: vscode.TextDocument): Promise<void> {
const [file] = sourceFilesOf([uri]);
reindexed.set(file.uriString, uri);
return nameIndex.reindex(file);
if (!changed) return nameIndex.reindex(file);
const key = file.uriString;
const held = changing.get(key);
if (held?.doc === changed) held.pending++;
else changing.set(key, { doc: changed, pending: 1 });
return nameIndex.reindex(file).finally(() => {
const now = changing.get(key);
if (now?.doc === changed && --now.pending === 0) changing.delete(key);
});
}

// Drop one file's bucket (e.g. the file was deleted). Safe before build.
Expand Down
148 changes: 148 additions & 0 deletions test-integration/suite/nameIndexFirstEdit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
// Copyright 2026 The MathWorks, Inc.
// The first edit of a clean dictionary, as the window's name index sees it.
//
// Once a search has built the index, every content change of an open data source reindexes that file
// (extension.ts, onDidChangeTextDocument → nameIndex.reindexFile), from the document's unsaved text
// rather than from disk. VS Code reports an edit to a CLEAN document while the document still reads
// clean, and its dirty flag only after, as an event that carries no change (measured on CI:
// `[{changes:1, dirty:false}, {changes:0, dirty:true}]`). A reindex that asks `isDirty` alone reads
// that first edit's file from disk: the whole file, on the first edit after every open or save, and
// the names the file had before the edit, which the search then offers until the next edit or a save.
//
// The index is the REGISTERED extension's, built by the real command and read back through it
// (tools/quickPicks): a search snapshot of the index each time it opens. The reads are counted through
// a file system of the test's own, as jsonBaselineFollowsDisk.test.ts counts them, since the reads go
// through `workspace.fs`, which cannot be wrapped.
import * as assert from 'assert';
import * as vscode from 'vscode';
import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { quiet, waitFor, wsUri } from './tools/hostHarness';
import { close, keepQuickPicks, search, typeQuery } from './tools/quickPicks';

/* eslint-disable @typescript-eslint/no-explicit-any */

const OLD = 'Number';
const NEW = 'NumberRenamedOnce';

/** `text` with the entry Number renamed, in one edit, as the table or the text editor makes it. */
function renamed(text: string): string {
const next = text.replace(`"name": "${OLD}"`, `"name": "${NEW}"`);
assert.notStrictEqual(next, text, `the fixture holds an entry named ${OLD}`);
return next;
}

async function applyRename(doc: vscode.TextDocument): Promise<void> {
const edit = new vscode.WorkspaceEdit();
edit.replace(doc.uri, new vscode.Range(doc.positionAt(0), doc.positionAt(doc.getText().length)), renamed(doc.getText()));
assert.ok(await vscode.workspace.applyEdit(edit), 'the edit applied');
await waitFor('the document to be dirty', () => doc.isDirty);
}

/** Discard the document's edit: it is never written. */
async function discard(doc: vscode.TextDocument): Promise<void> {
await vscode.window.showTextDocument(doc);
await vscode.commands.executeCommand('workbench.action.revertAndCloseActiveEditor');
await vscode.commands.executeCommand('workbench.action.closeAllEditors');
}

suite('the name index and the first edit of a clean dictionary', () => {
let quickPicks: ReturnType<typeof keepQuickPicks> | undefined;

/** The names the search offers from `uri` for `query`, through the real command. */
async function namesIn(uri: vscode.Uri, query: string): Promise<string[]> {
const s = await search(quickPicks!.picks);
try {
return (await typeQuery(s, query)).filter((i) => i.entry.sourceUri === uri.toString()).map((i) => i.label);
} finally {
await close(s);
}
}

suiteSetup(async () => {
await vscode.extensions.getExtension('mathworks.simulink-data-explorer')?.activate();
quickPicks = keepQuickPicks();
// The search builds the index; the reindex on a change does nothing before that.
await close(await search(quickPicks.picks));
});

suiteTeardown(async () => {
quickPicks?.restore();
await vscode.commands.executeCommand('workbench.action.closeAllEditors');
});

test('reads nothing from disk', async () => {
const dir = mkdtempSync(join(tmpdir(), 'dex-first-edit-'));
const disk = new CountingFs(dir);
const registered = vscode.workspace.registerFileSystemProvider('dexfirstedit', disk);
const uri = vscode.Uri.from({ scheme: 'dexfirstedit', path: '/first_edit.sldd' });
writeFileSync(disk.real(uri), readFileSync(wsUri('data.sldd').fsPath));
const doc = await vscode.workspace.openTextDocument(uri);
try {
assert.ok(!doc.isDirty, 'the document opens clean');
await quiet(300, 'the open settling');
disk.reads = 0;
await applyRename(doc);
await quiet(500, 'a read of the file the edit would cause');
const tabs = vscode.window.tabGroups.all.flatMap((g) => g.tabs).map((t) => (t.input as any)?.uri?.toString());
assert.strictEqual(disk.reads, 0, `the file was not read: the edit is in the document (tabs: ${JSON.stringify(tabs)})`);
} finally {
await discard(doc);
registered.dispose();
rmSync(dir, { recursive: true, force: true });
}
});

test('a rename made in one edit is what the search offers, and not the name the file had', async () => {
const uri = wsUri('name_index_first_edit.sldd');
await vscode.workspace.fs.copy(wsUri('data.sldd'), uri, { overwrite: true });
let doc: vscode.TextDocument | undefined;
try {
// The copy is seconds old: the index takes it in through the folder's watcher, or the build.
await waitFor(`the search to offer ${OLD} from the copy`, async () => (await namesIn(uri, OLD)).includes(OLD));
doc = await vscode.workspace.openTextDocument(uri);
assert.ok(!doc.isDirty, 'the document opens clean');
await applyRename(doc);
let names: string[] = [];
await waitFor(`the search to offer ${NEW}`, async () => (names = await namesIn(uri, OLD)).includes(NEW), 20000, () => JSON.stringify(names));
assert.ok(!names.includes(OLD), `and not ${OLD}, which the file holds and the document no longer does (${JSON.stringify(names)})`);
} finally {
if (doc) await discard(doc);
await vscode.workspace.fs.delete(uri);
}
});
});

/** A file system over a temporary folder, counting the whole-file reads made of it. */
class CountingFs implements vscode.FileSystemProvider {
reads = 0;
private readonly changed = new vscode.EventEmitter<vscode.FileChangeEvent[]>();
readonly onDidChangeFile = this.changed.event;
constructor(private readonly root: string) {}
real(uri: vscode.Uri): string {
return join(this.root, uri.path);
}
watch(): vscode.Disposable {
return new vscode.Disposable(() => {});
}
stat(uri: vscode.Uri): vscode.FileStat {
const st = statSync(this.real(uri));
return { type: vscode.FileType.File, ctime: st.ctimeMs, mtime: st.mtimeMs, size: st.size };
}
readDirectory(): [string, vscode.FileType][] {
return [];
}
createDirectory(): void {}
readFile(uri: vscode.Uri): Uint8Array {
this.reads++;
return readFileSync(this.real(uri));
}
writeFile(uri: vscode.Uri, content: Uint8Array): void {
writeFileSync(this.real(uri), content);
}
delete(uri: vscode.Uri): void {
rmSync(this.real(uri), { force: true });
}
rename(): void {}
}
Loading
Loading