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
3 changes: 3 additions & 0 deletions apps/ide/src/extensionHost/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -869,6 +869,9 @@ export function createVscodeApi(record: ExtensionRecord, host: ExtensionHost): u
onDidChangeActiveTerminal: windowEvents.onDidChangeActiveTerminal.event,
onDidChangeTerminalState: windowEvents.onDidChangeTerminalState.event,
tabGroups: host.documentsAndEditors.tabGroups,
// #261: tree views.
createTreeView: (viewId: string, options: { treeDataProvider?: unknown; showCollapseAll?: boolean; canSelectMany?: boolean; manageCheckboxStateManually?: boolean }) => host.treeViews.create(extensionId, viewId, options),
registerTreeDataProvider: (viewId: string, provider: unknown) => host.treeViews.register(extensionId, viewId, provider),
}, report);

/* ------------------------------ env ------------------------------ */
Expand Down
4 changes: 4 additions & 0 deletions apps/ide/src/extensionHost/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { FileMemento } from './memento.ts';
import type { TextDocumentModel } from './textDocument.ts';
import { BUILTIN_LANGUAGES } from './textDocument.ts';
import { Disposable, EventEmitter, Uri } from './types.ts';
import { TreeViews } from './treeViews.ts';
import { fromWire, toWire } from './wire.ts';

/**
Expand Down Expand Up @@ -74,6 +75,8 @@ export class ExtensionHost {
/** #260: the editor's documents and active editor, and the extensions' language features. */
readonly documentsAndEditors: DocumentsAndEditors;
readonly languageFeatures: LanguageFeatures;
/** #261: the extensions' tree views. */
readonly treeViews: TreeViews;
private readonly reported = new Set<string>();
private readonly firedEvents = new Set<string>();
private moduleHooked = false;
Expand All @@ -84,6 +87,7 @@ export class ExtensionHost {
this.rpc = rpc;
this.documentsAndEditors = new DocumentsAndEditors(this);
this.languageFeatures = new LanguageFeatures(this);
this.treeViews = new TreeViews(this);
this.configuration = new ConfigurationModel((key, value, target) => this.rpc.request(MAIN_METHODS.updateConfiguration, key, toWire(value), target).then(() => undefined));
}

Expand Down
2 changes: 2 additions & 0 deletions apps/ide/src/extensionHost/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { HOST_METHODS, RpcEndpoint, type HostInitData, type RpcMessage } from '../shared/extensionHostProtocol.ts';
import type { DocumentEvent, ProvideRequest } from '../shared/extensionLanguageProtocol.ts';
import type { ViewRequest } from '../shared/extensionViewsProtocol.ts';
import { ExtensionHost } from './host.ts';

/**
Expand Down Expand Up @@ -28,6 +29,7 @@ rpc.handle(HOST_METHODS.configurationChanged, (values) => host.configurationChan
rpc.handle(HOST_METHODS.trustChanged, (trusted) => host.trustChanged(trusted === true));
rpc.handle(HOST_METHODS.documents, (events) => host.documentsAndEditors.accept(Array.isArray(events) ? events as DocumentEvent[] : []));
rpc.handle(HOST_METHODS.provide, (request) => host.languageFeatures.provide(request as ProvideRequest));
rpc.handle(HOST_METHODS.view, (request) => host.treeViews.request(request as ViewRequest));
rpc.handle(HOST_METHODS.shutdown, async () => {
await host.shutdown();
setTimeout(() => process.exit(0), 50);
Expand Down
461 changes: 461 additions & 0 deletions apps/ide/src/extensionHost/treeViews.ts

Large diffs are not rendered by default.

138 changes: 134 additions & 4 deletions apps/ide/src/main/extensions/contributions.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import fs from 'node:fs';
import path from 'node:path';
import { EXTENSION_THEME_PREFIX, type ContributedGrammar, type ContributedLanguage, type ContributedSnippet, type ContributedCommand, type ContributedTheme, type ExtensionContributions, type GrammarContent, type ResolvedTheme, type ThemeTokenRule } from '../../shared/extensions.ts';
import { codiconName, type IconData } from '../../shared/extensionViewsProtocol.ts';
import { EXTENSION_THEME_PREFIX, type ContributedGrammar, type ContributedLanguage, type ContributedMenuItem, type ContributedSnippet, type ContributedCommand, type ContributedTheme, type ContributedView, type ContributedViewContainer, type ContributedViewWelcome, type ExtensionContributions, type GrammarContent, type ResolvedTheme, type ThemeTokenRule } from '../../shared/extensions.ts';
import { readJsonc, resolveInExtension, type LoadedExtension } from './extensionStore.ts';
import { parsePlist, type PlistValue } from './plist.ts';

Expand Down Expand Up @@ -55,6 +56,62 @@ function contributionFile(extension: LoadedExtension, relative: unknown): string
}
}

const IMAGE_TYPES: Readonly<Record<string, string>> = { '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp' };
/** Icons are small; anything bigger is not drawn (a 256 KB data URL is already generous for a 16px icon). */
export const MAX_ICON_FILE = 256 * 1024;

/** An image file as a `data:` URL, or null (not an image, too big, unreadable). Callers check where it is first. */
export function imageDataUrl(file: string): string | null {
const type = IMAGE_TYPES[path.extname(file).toLowerCase()];
if (!type) {
return null;
}
try {
const stat = fs.statSync(file);
if (!stat.isFile() || stat.size > MAX_ICON_FILE) {
return null;
}
return `data:${type};base64,${fs.readFileSync(file).toString('base64')}`;
} catch {
return null;
}
}

/** #261: an icon of the manifest: `$(codicon)`, a path inside the extension, or `{ light, dark }` paths. */
export function manifestIcon(extension: LoadedExtension, value: unknown): IconData | null {
if (typeof value === 'string') {
const name = codiconName(value);
if (name) {
return { kind: 'codicon', name };
}
const file = contributionFile(extension, value);
const url = file ? imageDataUrl(file) : null;
return url ? { kind: 'image', light: url, dark: url } : null;
}
const pair = record(value);
const lightFile = contributionFile(extension, pair['light']);
const darkFile = contributionFile(extension, pair['dark']);
const light = lightFile ? imageDataUrl(lightFile) : null;
const dark = darkFile ? imageDataUrl(darkFile) : null;
return light || dark ? { kind: 'image', light: (light ?? dark) as string, dark: (dark ?? light) as string } : null;
}

/** `"navigation@2"` -> group `navigation`, order 2. */
export function menuGroup(value: unknown): { group: string; order: number } {
const text = typeof value === 'string' ? value : '';
const at = text.lastIndexOf('@');
if (at < 0) {
return { group: text, order: 0 };
}
const order = Number(text.slice(at + 1));
return { group: text.slice(0, at), order: Number.isFinite(order) ? order : 0 };
}

/** The menus #261 draws; the others (`scm/title`, `debug/toolbar`, ...) are not read. */
export const SUPPORTED_MENUS: ReadonlySet<string> = new Set(['view/title', 'view/item/context', 'editor/title', 'editor/title/context', 'editor/context', 'explorer/context']);

const BUILTIN_CONTAINERS: ReadonlySet<string> = new Set(['explorer', 'scm', 'debug']);

export class ContributionIndex {
private readonly extensions: readonly LoadedExtension[];
private readonly grammarFiles = new Map<string, string>();
Expand All @@ -74,6 +131,11 @@ export class ContributionIndex {
const grammars: ContributedGrammar[] = [];
const snippets: ContributedSnippet[] = [];
const commands: ContributedCommand[] = [];
const viewContainers: ContributedViewContainer[] = [];
const views: ContributedView[] = [];
const viewsWelcome: ContributedViewWelcome[] = [];
const menus: ContributedMenuItem[] = [];
const containerIds = new Set<string>();
for (const extension of this.extensions) {
const c = extension.manifest.contributes;
const extensionId = extension.manifest.id;
Expand Down Expand Up @@ -147,19 +209,87 @@ export class ContributionIndex {
}
// #259: the palette's commands, for the extensions whose code can run them.
if (extension.manifest.main) {
const hidden = new Set(list(record(c.menus)['commandPalette']).filter((entry) => entry.when === 'false' || entry.when === false).map((entry) => str(entry.command)));
const palette = list(record(c.menus)['commandPalette']);
const hidden = new Set(palette.filter((entry) => entry.when === 'false' || entry.when === false).map((entry) => str(entry.command)));
const paletteWhen = new Map(palette.filter((entry) => typeof entry.when === 'string' && entry.when !== 'false').map((entry) => [str(entry.command), entry.when as string]));
for (const command of list(c.commands)) {
const id = str(command.command);
const title = typeof command.title === 'string' ? command.title : str(record(command.title)['value']);
if (!id || !title) {
continue;
}
const category = typeof command.category === 'string' ? command.category : str(record(command.category)['value']);
commands.push({ extensionId, command: id, title, category: category ?? null, hiddenFromPalette: hidden.has(id) });
commands.push({
extensionId, command: id, title, category: category ?? null, hiddenFromPalette: hidden.has(id),
paletteWhen: paletteWhen.get(id) ?? null,
enablement: str(command.enablement),
icon: command.icon === undefined ? null : manifestIcon(extension, command.icon),
});
}
// #261: the menus #261 draws. They run code, so only for extensions that have some.
for (const [menu, entries] of Object.entries(record(c.menus))) {
if (!SUPPORTED_MENUS.has(menu)) {
continue;
}
for (const entry of list(entries)) {
const command = str(entry.command);
if (!command) {
continue; // A submenu reference: not drawn.
}
menus.push({ extensionId, menu, command, when: str(entry.when), ...menuGroup(entry.group) });
}
}
}
// #261: view containers and views.
const containers = record(c.viewsContainers);
for (const location of ['activitybar', 'panel']) {
for (const container of list(containers[location])) {
const id = str(container.id);
const title = str(container.title);
if (!id || !title || !/^[\w.-]+$/.test(id) || containerIds.has(id) || BUILTIN_CONTAINERS.has(id)) {
if (id) {
this.onWarning(`${extensionId}: view container "${id}" was skipped (bad or repeated id, or no title).`);
}
continue;
}
containerIds.add(id);
viewContainers.push({ id, extensionId, title, icon: manifestIcon(extension, container.icon) });
}
}
for (const [container, entries] of Object.entries(record(c.views))) {
for (const view of list(entries)) {
const id = str(view.id);
const name = str(view.name) ?? id;
if (!id || !name) {
continue;
}
views.push({
id, extensionId, container, name,
when: str(view.when),
type: view.type === 'webview' ? 'webview' : 'tree',
collapsed: view.visibility === 'collapsed',
});
}
}
for (const welcome of list(c.viewsWelcome)) {
const view = str(welcome.view);
const contents = str(welcome.contents);
if (view && contents) {
viewsWelcome.push({ extensionId, view, contents, when: str(welcome.when) });
}
}
}
return { themes, languages, grammars, snippets, commands };
// A view in a container nobody contributed (another extension's that is disabled, `test`, a panel
// id this IDE has not got) would be invisible: VS Code drops those too, but say so.
const known = new Set([...BUILTIN_CONTAINERS, ...containerIds]);
const placed = views.filter((view) => {
if (known.has(view.container)) {
return true;
}
this.onWarning(`${view.extensionId}: view "${view.id}" is in the container "${view.container}", which this IDE does not show.`);
return false;
});
return { themes, languages, grammars, snippets, commands, viewContainers, views: placed, viewsWelcome, menus };
}

grammarContent(ref: string): GrammarContent | null {
Expand Down
29 changes: 29 additions & 0 deletions apps/ide/src/main/extensions/extensionHostManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ import { isOpenableExternalLink } from '../security.ts';
import { addTrustChangeListener, isWorkspaceTrusted } from '../trust/workspaceTrust.ts';
import { addFolderChangeListener, workspaceOrNull } from '../workspace/workspaceWindows.ts';
import { matchGlob } from '../../extensionHost/glob.ts';
import { parseViewRequest } from '../../shared/extensionViewsProtocol.ts';
import { DocumentMirror, FolderPaths } from './documentMirror.ts';
import { inlineTreeIcons } from './viewIcons.ts';
import { ExtensionSettingsStore } from './extensionSettings.ts';
import type { ActivationSource, ExtensionsService } from './extensionsService.ts';
import type { LoadedExtension } from './extensionStore.ts';
Expand Down Expand Up @@ -72,6 +74,8 @@ export class ExtensionHostManager implements ActivationSource {
private readonly machineId: string;
private readonly sessionId = crypto.randomUUID();
private nextUiId = 1;
/** #261: tree icons read from disk, by absolute path. */
private readonly iconCache = new Map<string, string | null>();

constructor(options: { service: ExtensionsService; hostScript: string; isDevelopment: boolean }) {
this.service = options.service;
Expand Down Expand Up @@ -581,6 +585,23 @@ export class ExtensionHostManager implements ActivationSource {
const result = await connection.rpc.request(HOST_METHODS.provide, inward);
return paths.outward(result);
});
handle(EXTENSION_IPC_CHANNELS.extensionsView, async (event, raw) => {
const request = parseViewRequest(raw);
const connection = this.hosts.get(event.sender.id);
if (!request || !connection) {
return null;
}
await connection.ready;
const result = await connection.rpc.request(HOST_METHODS.view, request);
if (request.kind !== 'treeChildren') {
return null;
}
// Icons first (their files lie outside the folder, where `outward` would drop them), then the resources.
const paths = this.folderPaths(event.sender);
const roots = [...this.service.enabled().map((extension) => extension.location), ...(paths ? [paths.root] : [])];
const inlined = inlineTreeIcons(result, roots, this.iconCache);
return paths ? paths.outward(inlined) : stripResources(inlined);
});
handle(EXTENSION_IPC_CHANNELS.extensionsHostReply, (event, id, result) => {
const connection = this.hosts.get(event.sender.id);
const resolve = typeof id === 'number' ? connection?.pendingUi.get(id) : undefined;
Expand All @@ -597,6 +618,14 @@ export class ExtensionHostManager implements ActivationSource {
}
}

/** Without a folder no resource has a workspace path: keep only their names. */
function stripResources(result: unknown): unknown {
if (typeof result !== 'object' || result === null || !Array.isArray((result as { items?: unknown }).items)) {
return result;
}
return { ...(result as object), items: (result as { items: Record<string, unknown>[] }).items.map((item) => ({ ...item, resource: null })) };
}

function readOrCreateMachineId(file: string): string {
// A random id per installation, never derived from the hardware: extensions get a stable id, not a fingerprint.
try {
Expand Down
57 changes: 57 additions & 0 deletions apps/ide/src/main/extensions/viewIcons.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import path from 'node:path';
import type { HostIconData, IconData } from '../../shared/extensionViewsProtocol.ts';
import { imageDataUrl } from './contributions.ts';

/**
* #261: the icons of tree items that name a file. The host sends the file's
* absolute path; the main process reads it only when it lies inside one of
* `roots` (the extensions' folders and the workspace folder) and hands the
* renderer a `data:` URL, so the renderer never gets a path to load nor a
* way to read any other file.
*/

function inside(file: string, roots: readonly string[]): boolean {
const resolved = path.resolve(file);
return roots.some((root) => {
const relative = path.relative(root, resolved);
return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative);
});
}

export function inlineIcon(icon: HostIconData, roots: readonly string[], cache: Map<string, string | null>): IconData | undefined {
if (icon.kind !== 'iconFile') {
return icon;
}
const read = (file: string | undefined): string | null => {
if (typeof file !== 'string' || !inside(file, roots)) {
return null;
}
if (!cache.has(file)) {
if (cache.size > 500) {
cache.clear();
}
cache.set(file, imageDataUrl(file));
}
return cache.get(file) ?? null;
};
const light = read(icon.file);
const dark = icon.darkFile ? read(icon.darkFile) : light;
return light || dark ? { kind: 'image', light: (light ?? dark) as string, dark: (dark ?? light) as string } : undefined;
}

/** Replaces the `icon` of every item of a `treeChildren` answer (dropping the ones it may not read). */
export function inlineTreeIcons(result: unknown, roots: readonly string[], cache: Map<string, string | null>): unknown {
if (typeof result !== 'object' || result === null || !Array.isArray((result as { items?: unknown }).items)) {
return result;
}
const items = (result as { items: Record<string, unknown>[] }).items.map((item) => {
if (typeof item !== 'object' || item === null || typeof item['icon'] !== 'object' || item['icon'] === null) {
return item;
}
const icon = inlineIcon(item['icon'] as HostIconData, roots, cache);
const rest: Record<string, unknown> = { ...item };
delete rest['icon'];
return icon ? { ...rest, icon } : rest;
});
return { ...(result as object), items };
}
2 changes: 2 additions & 0 deletions apps/ide/src/preload/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { AGENT_IPC_CHANNELS, AGENT_IPC_EVENTS, type AgentChatEvent, type AgentPr
import { TASK_IPC_CHANNELS, TASK_IPC_EVENTS, type TaskFinished } from '../shared/tasks.ts';
import type { HostUiEvent } from '../shared/extensionHostProtocol.ts';
import type { DocumentEvent, ProvideRequest } from '../shared/extensionLanguageProtocol.ts';
import type { ViewRequest } from '../shared/extensionViewsProtocol.ts';
import { EXTENSION_IPC_CHANNELS, EXTENSION_IPC_EVENTS, type ExtensionsChangedEvent, type ExtensionLogEvent, type GalleryQuery } from '../shared/extensions.ts';
import { DEBUG_IPC_CHANNELS, DEBUG_IPC_EVENTS, type DebugEvent, type DebugStepKind } from '../shared/debug.ts';
import { LSP_IPC_CHANNELS, LSP_IPC_EVENTS, type LspDiagnosticsEvent, type LspLanguage, type LspRequestMethod } from '../shared/lsp.ts';
Expand Down Expand Up @@ -150,6 +151,7 @@ const api: CodeXRApi = Object.freeze({
onHostUi: (listener: (event: HostUiEvent) => void) => subscribe(EXTENSION_IPC_EVENTS.extensionsHostUi, listener),
documentEvents: (events: readonly DocumentEvent[]) => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsDocuments, events),
provide: (request: ProvideRequest) => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsProvide, request),
view: (request: ViewRequest) => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsView, request),
}),
app: Object.freeze({
getInfo: () => ipcRenderer.invoke(IPC_CHANNELS.appGetInfo),
Expand Down
Loading
Loading