diff --git a/apps/ide/src/extensionHost/api.ts b/apps/ide/src/extensionHost/api.ts index 00b02583..a17fefd8 100644 --- a/apps/ide/src/extensionHost/api.ts +++ b/apps/ide/src/extensionHost/api.ts @@ -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 ------------------------------ */ diff --git a/apps/ide/src/extensionHost/host.ts b/apps/ide/src/extensionHost/host.ts index 5989f5f4..ce83644a 100644 --- a/apps/ide/src/extensionHost/host.ts +++ b/apps/ide/src/extensionHost/host.ts @@ -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'; /** @@ -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(); private readonly firedEvents = new Set(); private moduleHooked = false; @@ -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)); } diff --git a/apps/ide/src/extensionHost/index.ts b/apps/ide/src/extensionHost/index.ts index 8225f5ca..ad9ac54a 100644 --- a/apps/ide/src/extensionHost/index.ts +++ b/apps/ide/src/extensionHost/index.ts @@ -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'; /** @@ -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); diff --git a/apps/ide/src/extensionHost/treeViews.ts b/apps/ide/src/extensionHost/treeViews.ts new file mode 100644 index 00000000..04c772cc --- /dev/null +++ b/apps/ide/src/extensionHost/treeViews.ts @@ -0,0 +1,461 @@ +import path from 'node:path'; +import type { Collapsible, HostIconData, TreeItemData, ViewNotification, ViewRequest } from '../shared/extensionViewsProtocol.ts'; +import { MAX_VIEW_SELECTION } from '../shared/extensionViewsProtocol.ts'; +import type { ExtensionId } from '../shared/extensions.ts'; +import type { ExtensionHost } from './host.ts'; +import { CancellationTokenNone, Disposable, EventEmitter, MarkdownString, ThemeColor, ThemeIcon, TreeItemCheckboxState, Uri } from './types.ts'; + +/** + * #261: the tree views of extensions (`window.registerTreeDataProvider`, + * `window.createTreeView`). The provider and its elements stay here; the + * workbench sees each element as an opaque handle and asks for the children + * of a handle, a click on one, or a menu command on some. + * + * A handle is the item's `id` when the provider gives one (so a refreshed + * tree keeps what was expanded), else a number tied to the element object. + */ + +interface TreeProvider { + getChildren(element?: unknown): unknown; + getTreeItem(element: unknown): unknown; + getParent?(element: unknown): unknown; + resolveTreeItem?(item: unknown, element: unknown, token: unknown): unknown; + onDidChangeTreeData?: (listener: (value: unknown) => void) => { dispose(): unknown }; +} + +interface TreeEntry { + readonly viewId: string; + readonly extensionId: ExtensionId; + readonly provider: TreeProvider; + readonly view: TreeViewImpl; + /** handle -> element, element -> handle. */ + readonly elements: Map; + readonly handles: Map; + /** handle -> the TreeItem last returned, for clicks and menu arguments. */ + readonly items: Map>; + readonly subscription: { dispose(): unknown } | null; + next: number; +} + +/** Elements kept per view before the oldest numbers are forgotten (a tree refreshed forever must not grow forever). */ +const MAX_ELEMENTS = 20_000; + +function labelOf(item: Record): { label: string; highlights?: [number, number][] } { + const raw = item['label']; + if (typeof raw === 'string') { + return { label: raw }; + } + if (typeof raw === 'object' && raw !== null && typeof (raw as { label?: unknown }).label === 'string') { + const value = raw as { label: string; highlights?: unknown }; + const highlights = Array.isArray(value.highlights) + ? value.highlights.filter((pair): pair is [number, number] => Array.isArray(pair) && pair.length === 2 && pair.every((n) => Number.isInteger(n))) + : []; + return highlights.length > 0 ? { label: value.label, highlights } : { label: value.label }; + } + const resource = item['resourceUri']; + return { label: resource instanceof Uri ? path.basename(resource.path) : '' }; +} + +function text(value: unknown): string | undefined { + if (typeof value === 'string') { + return value; + } + if (value instanceof MarkdownString || (typeof value === 'object' && value !== null && typeof (value as { value?: unknown }).value === 'string')) { + return (value as { value: string }).value; + } + return undefined; +} + +function iconFile(value: unknown): string | null { + if (value instanceof Uri) { + return value.scheme === 'file' ? value.fsPath : null; + } + return typeof value === 'string' && path.isAbsolute(value) ? value : null; +} + +/** A tree item's `iconPath`, as the wire carries it. */ +export function iconData(value: unknown): HostIconData | undefined { + if (value instanceof ThemeIcon || (typeof value === 'object' && value !== null && typeof (value as { id?: unknown }).id === 'string' && !(value instanceof Uri))) { + const icon = value as { id: string; color?: unknown }; + if (icon.id === 'file') { + return { kind: 'file' }; + } + if (icon.id === 'folder') { + return { kind: 'folder' }; + } + const color = icon.color instanceof ThemeColor || (typeof icon.color === 'object' && icon.color !== null && typeof (icon.color as { id?: unknown }).id === 'string') ? (icon.color as { id: string }).id : undefined; + return { kind: 'codicon', name: icon.id.replace(/~[a-z]+$/, ''), ...(color ? { color } : {}) }; + } + const single = iconFile(value); + if (single) { + return { kind: 'iconFile', file: single }; + } + if (typeof value === 'object' && value !== null) { + const pair = value as { light?: unknown; dark?: unknown }; + const light = iconFile(pair.light); + const dark = iconFile(pair.dark); + if (light || dark) { + return { kind: 'iconFile', file: (light ?? dark) as string, ...(dark && dark !== light ? { darkFile: dark } : {}) }; + } + } + return undefined; +} + +export class TreeViewImpl { + readonly viewId: string; + private readonly host: ExtensionHost; + private readonly owner: TreeViews; + readonly onDidChangeSelectionEmitter = new EventEmitter<{ selection: readonly unknown[] }>(); + readonly onDidChangeVisibilityEmitter = new EventEmitter<{ visible: boolean }>(); + readonly onDidExpandElementEmitter = new EventEmitter<{ element: unknown }>(); + readonly onDidCollapseElementEmitter = new EventEmitter<{ element: unknown }>(); + readonly onDidChangeCheckboxStateEmitter = new EventEmitter<{ items: readonly [unknown, number][] }>(); + readonly onDidChangeSelection = this.onDidChangeSelectionEmitter.event; + readonly onDidChangeVisibility = this.onDidChangeVisibilityEmitter.event; + readonly onDidExpandElement = this.onDidExpandElementEmitter.event; + readonly onDidCollapseElement = this.onDidCollapseElementEmitter.event; + readonly onDidChangeCheckboxState = this.onDidChangeCheckboxStateEmitter.event; + selection: readonly unknown[] = []; + visible = false; + private titleValue: string | undefined; + private descriptionValue: string | undefined; + private messageValue: string | undefined; + private badgeValue: { value: number; tooltip: string } | undefined; + + constructor(host: ExtensionHost, owner: TreeViews, viewId: string) { + this.host = host; + this.owner = owner; + this.viewId = viewId; + } + + private meta(change: Omit, 'kind' | 'viewId'>): void { + this.host.uiNotify({ kind: 'view', notification: { kind: 'viewMeta', viewId: this.viewId, ...change } }); + } + + get title(): string | undefined { + return this.titleValue; + } + + set title(value: string | undefined) { + this.titleValue = value; + this.meta({ title: value ?? null }); + } + + get description(): string | undefined { + return this.descriptionValue; + } + + set description(value: string | undefined) { + this.descriptionValue = value; + this.meta({ description: value ?? null }); + } + + get message(): string | undefined { + return this.messageValue; + } + + set message(value: string | MarkdownString | undefined) { + this.messageValue = text(value); + this.meta({ message: this.messageValue ?? null }); + } + + get badge(): { value: number; tooltip: string } | undefined { + return this.badgeValue; + } + + set badge(value: { value: number; tooltip: string } | undefined) { + this.badgeValue = value && Number.isFinite(value.value) ? { value: value.value, tooltip: String(value.tooltip ?? '') } : undefined; + this.meta({ badge: this.badgeValue ?? null }); + } + + async reveal(element: unknown, options: { select?: boolean; focus?: boolean; expand?: boolean | number } = {}): Promise { + await this.owner.reveal(this.viewId, element, options); + } + + dispose(): void { + this.owner.dispose(this.viewId); + } +} + +export class TreeViews { + private readonly host: ExtensionHost; + private readonly trees = new Map(); + + constructor(host: ExtensionHost) { + this.host = host; + } + + private notify(notification: ViewNotification): void { + this.host.uiNotify({ kind: 'view', notification }); + } + + /** `createTreeView` / `registerTreeDataProvider`. */ + create(extensionId: ExtensionId, viewId: string, options: { treeDataProvider?: unknown; showCollapseAll?: boolean; canSelectMany?: boolean; manageCheckboxStateManually?: boolean }): TreeViewImpl { + if (typeof viewId !== 'string' || viewId === '') { + throw new Error('A tree view needs a view id'); + } + const provider = options?.treeDataProvider as TreeProvider | undefined; + if (!provider || typeof provider.getChildren !== 'function' || typeof provider.getTreeItem !== 'function') { + throw new Error(`The tree view '${viewId}' needs a TreeDataProvider with getChildren and getTreeItem`); + } + if (this.trees.has(viewId)) { + throw new Error(`A data provider is already registered for the view '${viewId}'`); + } + const view = new TreeViewImpl(this.host, this, viewId); + const subscription = typeof provider.onDidChangeTreeData === 'function' + ? provider.onDidChangeTreeData((changed) => this.changed(viewId, changed)) + : null; + this.trees.set(viewId, { viewId, extensionId, provider, view, elements: new Map(), handles: new Map(), items: new Map(), subscription, next: 1 }); + this.notify({ + kind: 'treeRegistered', viewId, extensionId, + showCollapseAll: options.showCollapseAll === true, + canSelectMany: options.canSelectMany === true, + manageCheckboxStateManually: options.manageCheckboxStateManually === true, + }); + return view; + } + + dispose(viewId: string): void { + const entry = this.trees.get(viewId); + if (!entry) { + return; + } + this.trees.delete(viewId); + entry.subscription?.dispose(); + this.notify({ kind: 'treeDisposed', viewId }); + } + + private changed(viewId: string, changed: unknown): void { + const entry = this.trees.get(viewId); + if (!entry) { + return; + } + if (changed === undefined || changed === null) { + this.notify({ kind: 'treeChanged', viewId, handles: null }); + return; + } + const list = Array.isArray(changed) ? changed : [changed]; + const handles = list.map((element) => entry.handles.get(element)).filter((handle): handle is string => handle !== undefined); + // Elements the workbench never saw change nothing it shows; an element it saw under another + // object (a provider that rebuilds its elements) would be missed, so refresh the tree then. + this.notify({ kind: 'treeChanged', viewId, handles: handles.length === list.length ? handles : null }); + } + + private handleOf(entry: TreeEntry, element: unknown, item: Record, parent: string | null, used: Set): string { + const handle = this.assignHandle(entry, element, item, parent, used); + used.add(handle); + return handle; + } + + private assignHandle(entry: TreeEntry, element: unknown, item: Record, parent: string | null, used: Set): string { + const known = entry.handles.get(element); + const id = typeof item['id'] === 'string' ? `i:${item['id']}` : null; + if (id) { + if (known && known !== id) { + entry.elements.delete(known); + } + entry.elements.set(id, element); + entry.handles.set(element, id); + return id; + } + if (known && !used.has(known)) { + return known; + } + // A label path is stable across refreshes for providers that return new objects each time; + // siblings with the same label get a counter. + const label = labelOf(item).label; + const base = `${parent ?? ''}/${label}`; + let handle = base; + for (let n = 2; used.has(handle); n++) { + handle = `${base}#${n}`; + } + if (entry.elements.has(handle) && entry.elements.get(handle) !== element) { + const old = entry.elements.get(handle); + // The same place in the tree, a new object: the new one takes the handle. + entry.handles.delete(old); + } + if (label === '') { + handle = `n:${entry.next++}`; + } + entry.elements.set(handle, element); + entry.handles.set(element, handle); + if (entry.elements.size > MAX_ELEMENTS) { + const oldest = entry.elements.keys().next().value as string; + entry.handles.delete(entry.elements.get(oldest)); + entry.elements.delete(oldest); + entry.items.delete(oldest); + } + return handle; + } + + private async itemData(entry: TreeEntry, element: unknown, parent: string | null, used: Set): Promise { + const item = (await entry.provider.getTreeItem(element) ?? {}) as Record; + const handle = this.handleOf(entry, element, item, parent, used); + entry.items.set(handle, item); + const { label, highlights } = labelOf(item); + const resource = item['resourceUri'] instanceof Uri && item['resourceUri'].scheme === 'file' ? item['resourceUri'] : null; + const collapsible = (item['collapsibleState'] === 1 || item['collapsibleState'] === 2 ? item['collapsibleState'] : 0) as Collapsible; + const icon = iconData(item['iconPath']); + let description: string | undefined; + if (typeof item['description'] === 'string') { + description = item['description']; + } else if (item['description'] === true && resource) { + const root = this.host.data.workspaceFolder; + description = root ? path.relative(root, path.dirname(resource.fsPath)) : path.dirname(resource.fsPath); + } + const tooltip = text(item['tooltip']); + const command = item['command'] as { command?: unknown } | undefined; + const checkbox = item['checkboxState']; + const checked = typeof checkbox === 'number' ? checkbox === TreeItemCheckboxState.Checked + : typeof checkbox === 'object' && checkbox !== null ? (checkbox as { state?: unknown }).state === TreeItemCheckboxState.Checked + : undefined; + const accessibility = item['accessibilityInformation'] as { label?: unknown } | undefined; + return { + handle, + label, + ...(highlights ? { highlights } : {}), + ...(description !== undefined && description !== '' ? { description } : {}), + ...(tooltip ? { tooltip } : {}), + collapsible, + ...(icon ? { icon } : {}), + ...(resource ? { resource: { path: resource.fsPath }, resourceName: path.basename(resource.fsPath) } : {}), + ...(command && typeof command.command === 'string' ? { hasCommand: true } : {}), + ...(typeof item['contextValue'] === 'string' ? { contextValue: item['contextValue'] } : {}), + ...(typeof accessibility?.label === 'string' ? { accessibilityLabel: accessibility.label } : {}), + ...(checked !== undefined ? { checked } : {}), + }; + } + + async children(viewId: string, handle: string | null): Promise<{ items: TreeItemData[] } | null> { + const entry = this.trees.get(viewId); + if (!entry) { + return null; + } + let element: unknown; + if (handle !== null) { + if (!entry.elements.has(handle)) { + return { items: [] }; + } + element = entry.elements.get(handle); + } + const children = await entry.provider.getChildren(element); + if (!Array.isArray(children)) { + return { items: [] }; + } + const items: TreeItemData[] = []; + const used = new Set(); + for (const child of children) { + items.push(await this.itemData(entry, child, handle, used)); + } + return { items }; + } + + private elementsOf(entry: TreeEntry, handles: readonly string[]): unknown[] { + return handles.slice(0, MAX_VIEW_SELECTION).filter((handle) => entry.elements.has(handle)).map((handle) => entry.elements.get(handle)); + } + + /** The workbench's side of a tree view: children, clicks, menus, selection, expansion, visibility. */ + async request(request: ViewRequest): Promise { + if (request.kind === 'viewVisibility') { + if (request.visible) { + await this.host.activateByEvent(`onView:${request.viewId}`); + } + const entry = this.trees.get(request.viewId); + if (entry && entry.view.visible !== request.visible) { + entry.view.visible = request.visible; + entry.view.onDidChangeVisibilityEmitter.fire({ visible: request.visible }); + } + return null; + } + const entry = this.trees.get(request.viewId); + switch (request.kind) { + case 'treeChildren': + if (!entry) { + // The view's extension may not have activated yet: `onView` wakes it. + await this.host.activateByEvent(`onView:${request.viewId}`); + } + return this.children(request.viewId, request.handle); + case 'treeClick': { + const item = entry?.items.get(request.handle); + let command = item?.['command'] as { command?: unknown; arguments?: unknown } | undefined; + if (entry && item && !command && typeof entry.provider.resolveTreeItem === 'function') { + const resolved = await entry.provider.resolveTreeItem(item, entry.elements.get(request.handle), CancellationTokenNone) as Record | undefined; + command = (resolved ?? item)['command'] as typeof command; + } + if (command && typeof command.command === 'string') { + await this.host.executeCommand(command.command, Array.isArray(command.arguments) ? command.arguments : []); + } + return null; + } + case 'treeCommand': { + if (!entry) { + await this.host.executeCommand(request.command, []); + return null; + } + const element = request.handle === null ? undefined : entry.elements.get(request.handle); + const selected = this.elementsOf(entry, request.selected); + const args = request.handle === null ? [] : selected.length > 1 ? [element, selected] : [element]; + await this.host.executeCommand(request.command, args); + return null; + } + case 'treeExpand': { + if (!entry || !entry.elements.has(request.handle)) { + return null; + } + const element = entry.elements.get(request.handle); + (request.expanded ? entry.view.onDidExpandElementEmitter : entry.view.onDidCollapseElementEmitter).fire({ element }); + return null; + } + case 'treeSelection': { + if (!entry) { + return null; + } + entry.view.selection = this.elementsOf(entry, request.handles); + entry.view.onDidChangeSelectionEmitter.fire({ selection: entry.view.selection }); + return null; + } + case 'treeCheckbox': { + if (!entry || !entry.elements.has(request.handle)) { + return null; + } + const element = entry.elements.get(request.handle); + entry.view.onDidChangeCheckboxStateEmitter.fire({ items: [[element, request.checked ? TreeItemCheckboxState.Checked : TreeItemCheckboxState.Unchecked]] }); + return null; + } + } + } + + /** `TreeView.reveal`: needs `getParent` for anything but a root. */ + async reveal(viewId: string, element: unknown, options: { select?: boolean; focus?: boolean; expand?: boolean | number }): Promise { + const entry = this.trees.get(viewId); + if (!entry) { + return; + } + const chain: unknown[] = [element]; + if (typeof entry.provider.getParent === 'function') { + let parent = await entry.provider.getParent(element); + while (parent !== undefined && parent !== null && chain.length < 64) { + chain.unshift(parent); + parent = await entry.provider.getParent(parent); + } + } + // Handles in order from a root, assigned the way `children` would. + const pathHandles: string[] = []; + let parentHandle: string | null = null; + for (const node of chain) { + const item = (await entry.provider.getTreeItem(node) ?? {}) as Record; + const handle = this.handleOf(entry, node, item, parentHandle, new Set()); + entry.items.set(handle, item); + pathHandles.push(handle); + parentHandle = handle; + } + const expand = options.expand === true ? 1 : typeof options.expand === 'number' ? Math.max(0, Math.min(3, Math.floor(options.expand))) : 0; + this.notify({ kind: 'treeReveal', viewId, path: pathHandles, select: options.select !== false, focus: options.focus === true, expand }); + } + + /** Disposable for `registerTreeDataProvider`. */ + register(extensionId: ExtensionId, viewId: string, provider: unknown): Disposable { + const view = this.create(extensionId, viewId, { treeDataProvider: provider }); + return new Disposable(() => view.dispose()); + } +} diff --git a/apps/ide/src/main/extensions/contributions.ts b/apps/ide/src/main/extensions/contributions.ts index c65cd5b0..08c8441b 100644 --- a/apps/ide/src/main/extensions/contributions.ts +++ b/apps/ide/src/main/extensions/contributions.ts @@ -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'; @@ -55,6 +56,62 @@ function contributionFile(extension: LoadedExtension, relative: unknown): string } } +const IMAGE_TYPES: Readonly> = { '.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 = new Set(['view/title', 'view/item/context', 'editor/title', 'editor/title/context', 'editor/context', 'explorer/context']); + +const BUILTIN_CONTAINERS: ReadonlySet = new Set(['explorer', 'scm', 'debug']); + export class ContributionIndex { private readonly extensions: readonly LoadedExtension[]; private readonly grammarFiles = new Map(); @@ -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(); for (const extension of this.extensions) { const c = extension.manifest.contributes; const extensionId = extension.manifest.id; @@ -147,7 +209,9 @@ 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']); @@ -155,11 +219,77 @@ export class ContributionIndex { 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 { diff --git a/apps/ide/src/main/extensions/extensionHostManager.ts b/apps/ide/src/main/extensions/extensionHostManager.ts index 67179a4d..da49c2e9 100644 --- a/apps/ide/src/main/extensions/extensionHostManager.ts +++ b/apps/ide/src/main/extensions/extensionHostManager.ts @@ -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'; @@ -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(); constructor(options: { service: ExtensionsService; hostScript: string; isDevelopment: boolean }) { this.service = options.service; @@ -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; @@ -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[] }).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 { diff --git a/apps/ide/src/main/extensions/viewIcons.ts b/apps/ide/src/main/extensions/viewIcons.ts new file mode 100644 index 00000000..261c4fc7 --- /dev/null +++ b/apps/ide/src/main/extensions/viewIcons.ts @@ -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): 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): unknown { + if (typeof result !== 'object' || result === null || !Array.isArray((result as { items?: unknown }).items)) { + return result; + } + const items = (result as { items: Record[] }).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 = { ...item }; + delete rest['icon']; + return icon ? { ...rest, icon } : rest; + }); + return { ...(result as object), items }; +} diff --git a/apps/ide/src/preload/index.ts b/apps/ide/src/preload/index.ts index 29d29ad0..210af323 100644 --- a/apps/ide/src/preload/index.ts +++ b/apps/ide/src/preload/index.ts @@ -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'; @@ -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), diff --git a/apps/ide/src/renderer/codicons.ts b/apps/ide/src/renderer/codicons.ts new file mode 100644 index 00000000..3c423690 --- /dev/null +++ b/apps/ide/src/renderer/codicons.ts @@ -0,0 +1,61 @@ +import 'monaco-editor/base/common/codicons.js'; +import { getCodiconFontCharacters } from 'monaco-editor/base/common/codiconsUtil.js'; +// The codicon font Monaco ships, bundled by Vite and served from the app (CSP `font-src 'self'`). +import codiconFontUrl from '../../../../node_modules/monaco-editor/esm/vs/base/browser/ui/codicons/codicon/codicon.ttf?url'; + +/** + * #261: VS Code's product icons (`$(refresh)`, `new ThemeIcon('gear')`), for + * what extensions draw in the workbench: their view containers, tree items + * and menu buttons. The font is Monaco's own and is loaded once, on the first + * icon; an unknown name draws as the `blank` icon rather than as a letter. + */ + +let fontLoaded = false; + +function loadFont(): void { + if (fontLoaded) { + return; + } + fontLoaded = true; + try { + const face = new FontFace('codicon', `url("${codiconFontUrl}") format("truetype")`, { display: 'block' }); + document.fonts.add(face); + void face.load().catch(() => undefined); + } catch { + // No FontFace (tests): the icons stay blank. + } +} + +/** Whether `name` is a codicon this IDE has. */ +export function hasCodicon(name: string): boolean { + return Object.prototype.hasOwnProperty.call(getCodiconFontCharacters(), name); +} + +/** The colours of `ThemeColor` ids extensions use on icons, in the workbench's palette. */ +const THEME_COLORS: Readonly> = { + 'charts.red': 'var(--crit)', 'charts.orange': 'var(--warn)', 'charts.yellow': 'var(--warn)', 'charts.green': 'var(--ok, #3fb950)', + 'charts.blue': 'var(--accent)', 'charts.purple': 'var(--symbol)', 'charts.foreground': 'var(--fg)', + errorForeground: 'var(--crit)', 'list.errorForeground': 'var(--crit)', 'list.warningForeground': 'var(--warn)', + 'problemsErrorIcon.foreground': 'var(--crit)', 'problemsWarningIcon.foreground': 'var(--warn)', 'problemsInfoIcon.foreground': 'var(--accent)', + 'testing.iconPassed': 'var(--ok, #3fb950)', 'testing.iconFailed': 'var(--crit)', 'testing.iconQueued': 'var(--warn)', + 'gitDecoration.addedResourceForeground': 'var(--ok, #3fb950)', 'gitDecoration.modifiedResourceForeground': 'var(--warn)', 'gitDecoration.deletedResourceForeground': 'var(--crit)', + 'gitDecoration.untrackedResourceForeground': 'var(--ok, #3fb950)', 'gitDecoration.ignoredResourceForeground': 'var(--muted)', + 'icon.foreground': 'var(--fg)', 'descriptionForeground': 'var(--muted)', 'disabledForeground': 'var(--muted)', +}; + +/** A codicon as an element: one character of the codicon font, hidden from screen readers. */ +export function codicon(name: string, options: { readonly className?: string; readonly color?: string } = {}): HTMLElement { + loadFont(); + const characters = getCodiconFontCharacters(); + const code = characters[name] ?? characters['blank']; + const span = document.createElement('span'); + span.className = ['codicon-glyph', options.className].filter(Boolean).join(' '); + span.setAttribute('aria-hidden', 'true'); + span.dataset['codicon'] = name; + span.textContent = code === undefined ? '' : String.fromCodePoint(code); + const color = options.color ? THEME_COLORS[options.color] : undefined; + if (color) { + span.style.color = color; + } + return span; +} diff --git a/apps/ide/src/renderer/editor/editorGroup.ts b/apps/ide/src/renderer/editor/editorGroup.ts index ffcf5101..d47b16ea 100644 --- a/apps/ide/src/renderer/editor/editorGroup.ts +++ b/apps/ide/src/renderer/editor/editorGroup.ts @@ -106,6 +106,8 @@ interface Group { readonly placeholder: HTMLElement; /** #256: where the active custom tab's element goes, in place of the editor. */ readonly customHost: HTMLElement; + /** #261: the buttons extensions add to the title (`editor/title`), at the strip's right end. */ + readonly titleActions: HTMLElement; readonly editor: monaco.editor.IStandaloneCodeEditor; readonly sceneShown: monaco.editor.IContextKey; readonly tabs: Map; @@ -261,6 +263,8 @@ export interface EditorGroup { breakpointsChanged(path: string | null): void; /** #180: the line a paused debug session is on (null: running or ended). */ setExecutionPoint(point: { readonly path: string; readonly line: number; readonly top: boolean } | null): void; + /** #261: draws every group's title buttons again (the extensions' menus or context keys changed). */ + refreshTitleActions(): void; } export function createEditorGroup( @@ -296,6 +300,8 @@ export function createEditorGroup( git?: GitDecorationsHooks; /** #180: the breakpoints in the glyph margin, owned by the debugger. */ debug?: DebugDecorationsHooks; + /** #261: the title buttons for a group's active tab (its path or custom id; null without one). */ + titleActions?(tabId: string | null): HTMLElement[]; }, ): EditorGroup { const groupsRow = el('div', { className: 'editor-groups', attrs: { 'data-testid': 'editor-groups' } }); @@ -432,6 +438,14 @@ export function createEditorGroup( callbacks.onMarkersChange?.(); } }); + // Drawn after the activation settles (the active tab is set at its end). + const renderTitleActionsSoon = (group: Group): void => { + queueMicrotask(() => { + if (groups.includes(group)) { + renderTitleActions(group); + } + }); + }; /** A group's tabs in order: its strip's DOM order. */ const ordered = (group: Group): Tab[] => [...group.strip.children].flatMap((element) => { const tab = group.tabs.get((element as HTMLElement).dataset['path'] ?? ''); @@ -541,7 +555,16 @@ export function createEditorGroup( shown.remove(); } + /** #261: the group's `editor/title` buttons, for its active tab; the strip leaves them room. */ + function renderTitleActions(group: Group): void { + const buttons = callbacks.titleActions?.(group.active?.doc.path ?? null) ?? []; + group.titleActions.replaceChildren(...buttons); + group.titleActions.hidden = buttons.length === 0; + group.strip.style.paddingRight = buttons.length === 0 ? '' : `${buttons.length * 26 + 8}px`; + } + function activate(group: Group, tab: Tab | null, focus = true): void { + renderTitleActionsSoon(group); const previous = group.active; if (previous && previous !== tab) { if (!previous.view) { @@ -1062,10 +1085,11 @@ export function createEditorGroup( const host = el('div', { className: 'editor-host', attrs: { 'data-testid': 'editor-host' } }); const placeholder = el('div', { className: 'editor-placeholder muted' }); const customHost = el('div', { className: 'editor-custom-host', attrs: { 'data-testid': 'editor-custom-host', hidden: '' } }); - const root = el('div', { className: 'editor-group', attrs: { 'data-testid': 'editor-group' } }, [strip, host, customHost, placeholder]); + const titleActions = el('div', { className: 'editor-title-actions', attrs: { 'data-testid': 'editor-title-actions', hidden: '' } }); + const root = el('div', { className: 'editor-group', attrs: { 'data-testid': 'editor-group' } }, [strip, titleActions, host, customHost, placeholder]); const editor = monaco.editor.create(host, { ...editorOptions, model: null }); const sceneShown = editor.createContextKey('codexrSceneShown', sceneIsShown); - const group: Group = { root, strip, host, placeholder, customHost, editor, sceneShown, tabs: new Map(), active: null, disposables: [] }; + const group: Group = { root, strip, host, placeholder, customHost, titleActions, editor, sceneShown, tabs: new Map(), active: null, disposables: [] }; const ifCurrent = (listener: () => void) => () => { if (current === group) { listener(); } }; group.disposables.push( editor.onDidChangeCursorSelection(ifCurrent(scheduleStatus)), @@ -1813,6 +1837,11 @@ export function createEditorGroup( }]; }); }, + refreshTitleActions(): void { + for (const group of groups) { + renderTitleActions(group); + } + }, gitChanged(): void { gitDecorations?.repositoryChanged(); }, diff --git a/apps/ide/src/renderer/extensions/contextKeys.ts b/apps/ide/src/renderer/extensions/contextKeys.ts new file mode 100644 index 00000000..b33361f0 --- /dev/null +++ b/apps/ide/src/renderer/extensions/contextKeys.ts @@ -0,0 +1,93 @@ +import type { ContextLookup } from '../../shared/whenClause.ts'; + +/** + * #261: the context keys `when` clauses read: what extensions set with + * `setContext`, and what the workbench knows (trust, folder, platform, + * settings as `config.*`), plus the keys of the thing a menu is about + * (`view`, `viewItem`, `resourceLangId`, ...), passed per lookup. Pure. + */ + +export class ContextKeys { + private readonly values = new Map(); + private readonly providers: ((key: string) => unknown)[] = []; + private readonly listeners = new Set<() => void>(); + private scheduled = false; + + /** A key `setContext` set; undefined removes it. Listeners hear once per task, however many keys changed. */ + set(key: string, value: unknown): void { + if (value === undefined || value === null) { + if (!this.values.delete(key)) { + return; + } + } else if (this.values.get(key) === value && typeof value !== 'object') { + return; + } else { + this.values.set(key, value); + } + this.changed(); + } + + /** Every key extensions set goes (their host stopped). */ + clear(): void { + if (this.values.size > 0) { + this.values.clear(); + this.changed(); + } + } + + /** Keys the workbench answers itself; the first provider that knows a key (not undefined) wins. */ + addProvider(provider: (key: string) => unknown): void { + this.providers.push(provider); + } + + /** Something a provider reads changed (trust, a setting). */ + changed(): void { + if (this.scheduled) { + return; + } + this.scheduled = true; + queueMicrotask(() => { + this.scheduled = false; + for (const listener of this.listeners) { + listener(); + } + }); + } + + onDidChange(listener: () => void): () => void { + this.listeners.add(listener); + return () => this.listeners.delete(listener); + } + + get(key: string): unknown { + if (this.values.has(key)) { + return this.values.get(key); + } + for (const provider of this.providers) { + const value = provider(key); + if (value !== undefined) { + return value; + } + } + return undefined; + } + + /** A lookup with `extra` keys on top (the item or file a menu is about). */ + lookup(extra: Readonly> = {}): ContextLookup { + return (key) => (Object.prototype.hasOwnProperty.call(extra, key) ? extra[key] : this.get(key)); + } +} + +/** The platform keys VS Code sets. */ +export function platformContext(platform: string): (key: string) => unknown { + return (key) => { + switch (key) { + case 'isLinux': return platform === 'linux'; + case 'isMac': return platform === 'darwin'; + case 'isWindows': return platform === 'win32'; + case 'isWeb': return false; + case 'isDesktop': return true; + default: return undefined; + } + }; +} diff --git a/apps/ide/src/renderer/extensions/contributionsController.ts b/apps/ide/src/renderer/extensions/contributionsController.ts index 657b6cb1..107777b4 100644 --- a/apps/ide/src/renderer/extensions/contributionsController.ts +++ b/apps/ide/src/renderer/extensions/contributionsController.ts @@ -21,7 +21,7 @@ export interface ContributionsController { previewTheme(themeId: string | null): Promise; } -const EMPTY: ExtensionContributions = { themes: [], languages: [], grammars: [], snippets: [], commands: [] }; +const EMPTY: ExtensionContributions = { themes: [], languages: [], grammars: [], snippets: [], commands: [], viewContainers: [], views: [], viewsWelcome: [], menus: [] }; export function createContributionsController(api: ExtensionsApi, onError: (message: string) => void): ContributionsController { let contributions = EMPTY; @@ -61,6 +61,8 @@ export function createContributionsController(api: ExtensionsApi, onError: (mess } } root.dataset.extensionTheme = theme ? theme.id : ''; + // #261: which of an extension's light/dark icons to draw. + root.dataset.extensionThemeKind = theme ? (theme.uiTheme === 'vs' || theme.uiTheme === 'hc-light' ? 'light' : 'dark') : ''; if (theme || monacoPart) { (await loadMonaco()).applyEditorTheme(theme); } diff --git a/apps/ide/src/renderer/extensions/editorMenus.ts b/apps/ide/src/renderer/extensions/editorMenus.ts new file mode 100644 index 00000000..f847849e --- /dev/null +++ b/apps/ide/src/renderer/extensions/editorMenus.ts @@ -0,0 +1,118 @@ +import { monaco } from '../editor/monaco.ts'; +import type { ContextKeys } from './contextKeys.ts'; +import { resourceContext, type MenuGroup } from './menuModel.ts'; + +/** + * #261: the entries extensions add to the editor's context menu + * (`editor/context`), as Monaco actions of each editor. They are rebuilt when + * the editor shows another file or language, when a context key changes, and + * when the selection becomes empty or not (`editorHasSelection` is a common + * `when`); the command gets the file's URI, as in VS Code. + */ + +export interface EditorMenusDeps { + readonly contextKeys: ContextKeys; + menu(menu: string, extra: Readonly>): MenuGroup[]; + /** The workspace path of a model the editor group opened; null for anything else. */ + pathOf(model: monaco.editor.ITextModel): string | null; + run(command: string, path: string): void; +} + +interface Tracked { + actions: monaco.IDisposable[]; + hasSelection: boolean; + readonly listeners: monaco.IDisposable[]; +} + +let sequence = 0; + +export function installEditorMenus(deps: EditorMenusDeps): () => void { + const tracked = new Map(); + + function rebuild(editor: monaco.editor.ICodeEditor): void { + const entry = tracked.get(editor); + if (!entry) { + return; + } + for (const action of entry.actions) { + action.dispose(); + } + entry.actions = []; + const model = editor.getModel(); + const path = model ? deps.pathOf(model) : null; + if (!model || !path) { + return; + } + const languageId = model.getLanguageId(); + const groups = deps.menu('editor/context', { + ...resourceContext(path, languageId), + editorLangId: languageId, + editorFocus: true, + editorTextFocus: true, + editorHasSelection: entry.hasSelection, + editorReadonly: editor.getOption(monaco.editor.EditorOption.readOnly), + activeEditor: 'workbench.editors.files.textFileEditor', + }); + groups.forEach((group, groupIndex) => { + group.actions.forEach((action, index) => { + const add = (editor as monaco.editor.IStandaloneCodeEditor).addAction?.bind(editor); + if (!add) { + return; + } + entry.actions.push(add({ + id: `codexr.extension.${action.command}.${++sequence}`, + label: action.title, + // After Monaco's own groups, in the extension's order; a disabled entry shows greyed out. + contextMenuGroupId: `9${String(groupIndex).padStart(2, '0')}_${group.group || 'extension'}`, + contextMenuOrder: index, + ...(action.enabled ? {} : { precondition: 'false' }), + run: () => deps.run(action.command, path), + })); + }); + }); + } + + function track(editor: monaco.editor.ICodeEditor): void { + if (tracked.has(editor) || typeof (editor as Partial).addAction !== 'function') { + return; + } + const entry: Tracked = { actions: [], hasSelection: false, listeners: [] }; + tracked.set(editor, entry); + entry.listeners.push( + editor.onDidChangeModel(() => rebuild(editor)), + editor.onDidChangeModelLanguage(() => rebuild(editor)), + editor.onDidChangeCursorSelection((event) => { + const hasSelection = !event.selection.isEmpty(); + if (hasSelection !== entry.hasSelection) { + entry.hasSelection = hasSelection; + rebuild(editor); + } + }), + editor.onDidDispose(() => { + for (const disposable of [...entry.actions, ...entry.listeners]) { + disposable.dispose(); + } + tracked.delete(editor); + }), + ); + rebuild(editor); + } + + const created = monaco.editor.onDidCreateEditor(track); + monaco.editor.getEditors().forEach(track); + const stopContext = deps.contextKeys.onDidChange(() => { + for (const editor of tracked.keys()) { + rebuild(editor); + } + }); + return () => { + created.dispose(); + stopContext(); + for (const [, entry] of tracked) { + for (const disposable of [...entry.actions, ...entry.listeners]) { + disposable.dispose(); + } + } + tracked.clear(); + }; +} diff --git a/apps/ide/src/renderer/extensions/extensionIcons.ts b/apps/ide/src/renderer/extensions/extensionIcons.ts new file mode 100644 index 00000000..a9a02e57 --- /dev/null +++ b/apps/ide/src/renderer/extensions/extensionIcons.ts @@ -0,0 +1,51 @@ +import type { IconData } from '../../shared/extensionViewsProtocol.ts'; +import { codicon } from '../codicons.ts'; +import { fileIcon } from '../dom.ts'; + +/** + * #261: draws an extension's icon (extensionViewsProtocol.ts `IconData`). + * `monochrome` icons (activity bar, toolbar buttons) take the text colour, + * as VS Code draws them: an image is used as a mask. Tree item images keep + * their colours. Images are `data:` URLs the main process made. + */ + +const darkQuery = typeof window !== 'undefined' && typeof window.matchMedia === 'function' ? window.matchMedia('(prefers-color-scheme: dark)') : null; + +function isDark(): boolean { + const extensionTheme = document.documentElement.dataset['extensionThemeKind']; + if (extensionTheme === 'light' || extensionTheme === 'dark') { + return extensionTheme === 'dark'; + } + return darkQuery?.matches ?? true; +} + +export function extensionIcon(icon: IconData | null | undefined, options: { readonly monochrome?: boolean; readonly resourceName?: string; readonly expanded?: boolean } = {}): HTMLElement | null { + if (!icon) { + return null; + } + switch (icon.kind) { + case 'codicon': + return codicon(icon.name, { className: 'ext-icon', ...(icon.color ? { color: icon.color } : {}) }); + case 'file': + return fileIcon(options.resourceName ?? '', 'file'); + case 'folder': + return fileIcon(options.resourceName ?? '', 'directory', options.expanded === true); + case 'image': { + const url = isDark() ? icon.dark : icon.light; + // Only the main process's data URLs are drawn: nothing here makes the page fetch. + if (!url.startsWith('data:image/')) { + return null; + } + const span = document.createElement('span'); + span.setAttribute('aria-hidden', 'true'); + if (options.monochrome) { + span.className = 'ext-icon ext-icon-mask'; + span.style.setProperty('--ext-icon-url', `url("${url}")`); + } else { + span.className = 'ext-icon ext-icon-image'; + span.style.backgroundImage = `url("${url}")`; + } + return span; + } + } +} diff --git a/apps/ide/src/renderer/extensions/extensions.css b/apps/ide/src/renderer/extensions/extensions.css index e75624a9..733d2386 100644 --- a/apps/ide/src/renderer/extensions/extensions.css +++ b/apps/ide/src/renderer/extensions/extensions.css @@ -53,3 +53,64 @@ @media (max-width: 900px) { .extension-details-body { grid-template-columns: minmax(0, 1fr); } } + +/* #261: what extensions draw in the workbench: product icons, their view containers, views, trees and menu buttons. */ +.codicon-glyph { flex: none; display: inline-block; width: 16px; font: normal normal normal 16px/1 codicon; text-align: center; text-decoration: none; text-rendering: auto; -webkit-font-smoothing: antialiased; user-select: none; } +.ext-icon-image { flex: none; display: inline-block; width: 16px; height: 16px; background: center / contain no-repeat; } +.ext-icon-mask { flex: none; display: inline-block; width: 16px; height: 16px; background: currentColor; -webkit-mask: var(--ext-icon-url) center / contain no-repeat; mask: var(--ext-icon-url) center / contain no-repeat; } + +.activity-item { position: relative; } +.activity-item > .codicon-glyph { width: 24px; font-size: 24px; } +.activity-item > .ext-icon-mask { width: 24px; height: 24px; } +.activity-letter { font-weight: 600; font-size: 16px; } +.activity-badge { position: absolute; right: 6px; bottom: 6px; min-width: 16px; height: 16px; padding: 0 4px; border-radius: 8px; background: var(--accent); color: var(--status-fg); font-size: 10px; font-weight: 600; line-height: 16px; text-align: center; } +.activity-badge[hidden] { display: none; } + +/* The Source Control and Run and Debug panes hold their view and, under it, extensions' views. */ +.side-pane.has-sections:not([hidden]) { display: flex; flex-direction: column; min-height: 100%; } +.side-pane-main { flex: none; } +.ext-sections { display: flex; flex-direction: column; min-height: 0; } +.ext-sections:empty { display: none; } +.explorer-pane > .ext-sections { flex: 0 1 auto; max-height: 50%; overflow: auto; } +.ext-container-pane:not([hidden]) { display: flex; flex-direction: column; height: 100%; min-height: 0; } + +.ext-view { display: flex; flex-direction: column; min-height: 0; border-top: 1px solid var(--line); } +.ext-view[hidden] { display: none; } +.ext-container-pane > .ext-view:first-child { border-top: 0; } +.ext-container-pane > .ext-view:not(.is-collapsed) { flex: 1 1 0; } +.ext-container-pane > .ext-view.is-collapsed { flex: none; } +.ext-view-header { flex: none; } +.ext-view-toggle[aria-expanded='true'] > .tree-chevron { transform: rotate(90deg); } +.ext-view-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.ext-view-description { margin-left: 6px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 400; text-transform: none; letter-spacing: 0; } +.ext-view-actions { flex: none; display: flex; align-items: center; gap: 2px; padding-right: 6px; opacity: 0; } +.ext-view:hover .ext-view-actions, .ext-view:focus-within .ext-view-actions { opacity: 1; } +.ext-view-body { flex: 1; min-height: 0; overflow: auto; padding-bottom: 6px; } +.ext-view-body[hidden] { display: none; } +.ext-view-message { margin: 4px 12px 6px; } +.ext-view-message[hidden] { display: none; } + +.ext-action.is-text { width: auto; padding: 0 6px; font: inherit; font-size: 12px; } +.ext-action:disabled { opacity: 0.4; cursor: default; } + +.ext-tree-row { gap: 4px; } +.ext-tree-row > .ext-icon, .ext-tree-row > .file-icon { flex: none; } +.tree-description { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; color: var(--muted); font-size: 0.92em; } +.tree-highlight { background: none; color: var(--accent); font-weight: 600; } +.ext-tree-checkbox { flex: none; margin: 0 2px 0 0; } +.ext-tree-actions { margin-left: auto; display: none; align-items: center; gap: 2px; } +.ext-tree-row:hover > .ext-tree-actions, .ext-tree-row:focus > .ext-tree-actions, .ext-tree-row[aria-selected='true'] > .ext-tree-actions { display: flex; } +.ext-tree-actions > .ext-action { display: grid; place-items: center; width: 20px; height: 20px; padding: 0; border: 0; border-radius: 3px; background: none; color: var(--muted); cursor: pointer; } +.ext-tree-actions > .ext-action:hover { background: var(--hover); color: var(--fg); } + +.ext-welcome { padding: 6px 0 8px; } +.ext-welcome[hidden] { display: none; } +.ext-welcome-text { margin: 4px 12px 8px; color: var(--muted); overflow-wrap: anywhere; } +.ext-welcome-button { display: block; margin-bottom: 8px; } +.ext-welcome-link { color: var(--accent); text-decoration: none; } +.ext-welcome-link:hover { text-decoration: underline; } + +/* The buttons extensions add to an editor's title, at the right end of its tab strip. */ +.editor-group { position: relative; } +.editor-title-actions { position: absolute; top: 0; right: 0; height: 35px; display: flex; align-items: center; gap: 2px; padding: 0 6px; background: var(--chrome); border-bottom: 1px solid var(--line); } +.editor-title-actions[hidden] { display: none; } diff --git a/apps/ide/src/renderer/extensions/extensionsWiring.ts b/apps/ide/src/renderer/extensions/extensionsWiring.ts index 43f58389..d5e900fd 100644 --- a/apps/ide/src/renderer/extensions/extensionsWiring.ts +++ b/apps/ide/src/renderer/extensions/extensionsWiring.ts @@ -6,7 +6,10 @@ import type { QuickInputProvider } from '../commands/quickInput.ts'; import type { NotificationCenter } from '../notifications.ts'; import { createContributionsController, type ContributionsController } from './contributionsController.ts'; import { createExtensionsView, type ExtensionsView } from './extensionsView.ts'; +import { ContextKeys } from './contextKeys.ts'; import { createHostBridge } from './hostBridge.ts'; +import { fileUriOf, type MenuGroup } from './menuModel.ts'; +import { createViewsController, type ViewsWorkbench } from './viewsController.ts'; import type { DocumentSync } from './documentSync.ts'; import type { LanguageBridge } from './languageBridge.ts'; import './extensions.css'; @@ -30,6 +33,12 @@ export interface ExtensionsWorkbench { watchEditorLanguages(): void; /** #260: the editor group saved `path`. */ documentSaved(path: string): void; + /** #261: the context keys of `when` clauses (the workbench adds its own providers). */ + readonly contextKeys: ContextKeys; + /** #261: an extension menu's entries in a context (`explorer/context`, `editor/title`, ...). */ + menu(menu: string, extra: Readonly>): MenuGroup[]; + /** #261: runs an extension's command, reporting a failure. */ + runCommand(command: string, args?: readonly unknown[]): void; } export interface ExtensionsWorkbenchDeps { @@ -51,6 +60,9 @@ export interface ExtensionsWorkbenchDeps { openFile(path: string, line?: number, column?: number): Promise; /** #260: saves an open file of the folder (an extension's `TextDocument.save()`). */ saveFile(path: string): Promise; + /** #261: where extensions' views go. */ + readonly views: ViewsWorkbench; + readonly storage: Storage | null; } export function installExtensions(deps: ExtensionsWorkbenchDeps): ExtensionsWorkbench { @@ -105,8 +117,28 @@ export function installExtensions(deps: ExtensionsWorkbenchDeps): ExtensionsWork } }; + // #261: context keys and the extensions' views. + const contextKeys = new ContextKeys(); + const runCommand = (command: string, args: readonly unknown[] = []): void => { + api.extensions.executeCommand(command, args).catch((error: unknown) => { + deps.notify('error', `Command '${command}' failed: ${error instanceof Error ? error.message.replace(/^Error invoking remote method '[^']+': (Error: )?/, '') : String(error)}`); + }); + }; + const views = createViewsController({ + extensions: api.extensions, + workbench: deps.views, + contextKeys, + storage: deps.storage, + runCommand, + openExternalLink: (url) => void api.workspace.openExternalLink(url).catch((error: unknown) => deps.notify('error', String(error))), + onError: (message) => deps.notify('error', message), + }); + // #259: the extension host's requests, status bar items and the palette's commands. const bridge = createHostBridge({ + contextKeys, + viewNotification: (notification) => views.notification(notification), + viewCommand: (id) => views.command(id), extensions: api.extensions, registry: deps.registry, notifications: deps.notifications, @@ -120,6 +152,9 @@ export function installExtensions(deps: ExtensionsWorkbenchDeps): ExtensionsWork view.focusSearch(query); }, languageNotification(notification) { + if (notification.kind === 'providersReset') { + views.reset(); + } if (languages) { languageNotification(notification, languages.bridge); } else if (notification.kind === 'providersReset') { @@ -147,6 +182,10 @@ export function installExtensions(deps: ExtensionsWorkbenchDeps): ExtensionsWork const refresh = async (): Promise => { await contributions.reload(); bridge.setCommands(contributions.current().commands, installed); + const runnable = new Set(installed.filter((extension) => extension.state === 'enabled' && extension.hasCode).map((extension) => extension.id)); + views.setContributions(contributions.current(), runnable); + // Menus depend on the contributions too: whatever draws them listens for this. + contextKeys.changed(); }; api.extensions.onDidChange((event) => { installed = event.installed; @@ -192,11 +231,18 @@ export function installExtensions(deps: ExtensionsWorkbenchDeps): ExtensionsWork if (languages) { return; } - void Promise.all([import('./documentSync.ts'), import('./languageBridge.ts')]).then(([syncModule, bridgeModule]) => { + void Promise.all([import('./documentSync.ts'), import('./languageBridge.ts'), import('./editorMenus.ts')]).then(([syncModule, bridgeModule, menusModule]) => { if (languages) { return; } const sync = syncModule.installDocumentSync(api.extensions); + // #261: the extensions' entries in the editor's context menu. + menusModule.installEditorMenus({ + contextKeys, + menu: (menu, extra) => views.menu(menu, extra), + pathOf: (model) => sync.pathOf(model), + run: (command, path) => void api.workspace.current().then((workspace) => runCommand(command, workspace ? [{ $uri: fileUriOf(workspace.root, path) }] : [])), + }); const languageBridge = bridgeModule.createLanguageBridge({ extensions: api.extensions, sync, @@ -216,5 +262,8 @@ export function installExtensions(deps: ExtensionsWorkbenchDeps): ExtensionsWork documentSaved(path) { languages?.sync.saved(path); }, + contextKeys, + menu: (menu, extra) => views.menu(menu, extra), + runCommand, }; } diff --git a/apps/ide/src/renderer/extensions/hostBridge.ts b/apps/ide/src/renderer/extensions/hostBridge.ts index 116e76ef..69deba55 100644 --- a/apps/ide/src/renderer/extensions/hostBridge.ts +++ b/apps/ide/src/renderer/extensions/hostBridge.ts @@ -5,6 +5,9 @@ import { pickListView, type PickItem } from '../commands/paletteModel.ts'; import type { QuickInputProvider } from '../commands/quickInput.ts'; import { el } from '../dom.ts'; import type { NotificationCenter } from '../notifications.ts'; +import type { ViewNotification } from '../../shared/extensionViewsProtocol.ts'; +import { whenHolds } from '../../shared/whenClause.ts'; +import type { ContextKeys } from './contextKeys.ts'; import { builtinCommandFor, statusText } from './hostBridgeModel.ts'; /** @@ -31,12 +34,18 @@ export interface HostBridgeDeps { languageNotification(notification: Extract): void; /** #260: the host's edits and saves of the editor's documents. */ languageRequest(request: Extract): Promise; + /** #261: the `setContext` keys go here (for `when` clauses). */ + readonly contextKeys: ContextKeys; + /** #261: the extensions' tree views. */ + viewNotification(notification: ViewNotification): void; + /** #261: a workbench command the views answer (`.focus`, `workbench.view.extension.`); false when it is not one. */ + viewCommand(id: string): boolean; } export interface HostBridge { /** The palette's commands of the extensions that may run in this window. */ setCommands(commands: readonly ContributedCommand[], installed: readonly InstalledExtension[]): void; - /** The `setContext` keys extensions set (for `when` clauses). */ + /** The context keys (`setContext` and the workbench's), for `when` clauses. */ contextKey(key: string): unknown; dispose(): void; } @@ -55,7 +64,7 @@ function once(resolve: (value: unknown) => void): (value: unknown) => void { export function createHostBridge(deps: HostBridgeDeps): HostBridge { const { extensions } = deps; const items = new Map(); - const context = new Map(); + const context = deps.contextKeys; let commandDisposers: (() => void)[] = []; let statusTimer: ReturnType | undefined; @@ -159,6 +168,9 @@ export function createHostBridge(deps: HostBridgeDeps): HostBridge { } return null; case 'unknown': + if (deps.viewCommand(id)) { + return null; + } throw new Error(`command '${id}' not found`); } } @@ -220,6 +232,13 @@ export function createHostBridge(deps: HostBridgeDeps): HostBridge { case 'providerUnregistered': case 'providersReset': deps.languageNotification(notification); + if (notification.kind === 'providersReset') { + // A host started or stopped: what the previous one set is gone. + context.clear(); + } + return; + case 'view': + deps.viewNotification(notification.notification); return; case 'hostStopped': deps.notifications.notify('error', notification.reason, { @@ -255,11 +274,14 @@ export function createHostBridge(deps: HostBridgeDeps): HostBridge { if (command.hiddenFromPalette || !runnable.has(command.extensionId) || deps.registry.get(command.command)) { continue; } + const paletteWhen = command.paletteWhen; commandDisposers.push(deps.registry.register({ id: command.command, title: command.title, ...(command.category ? { category: command.category } : {}), source: 'extension', + // #261: `menus.commandPalette`'s `when`. + ...(paletteWhen ? { enabled: () => whenHolds(paletteWhen, context.lookup()) } : {}), run: () => runExtensionCommand(command.command), })); } diff --git a/apps/ide/src/renderer/extensions/menuModel.ts b/apps/ide/src/renderer/extensions/menuModel.ts new file mode 100644 index 00000000..36f43ac5 --- /dev/null +++ b/apps/ide/src/renderer/extensions/menuModel.ts @@ -0,0 +1,104 @@ +import type { IconData } from '../../shared/extensionViewsProtocol.ts'; +import type { ContributedCommand, ContributedMenuItem } from '../../shared/extensions.ts'; +import { whenHolds, type ContextLookup } from '../../shared/whenClause.ts'; + +/** + * #261: the entries of an extension menu (`contributes.menus`) that apply in + * a context, grouped and ordered as VS Code draws them: `navigation` first + * (the buttons of a title bar), `inline` apart (the buttons on a tree row), + * then the other groups by name, each by `@order`. Pure: unit-tested in Node. + */ + +export interface MenuAction { + readonly command: string; + readonly title: string; + readonly icon: IconData | null; + readonly enabled: boolean; + readonly extensionId: string; +} + +export interface MenuGroup { + readonly group: string; + readonly actions: readonly MenuAction[]; +} + +export function menuGroups(menu: string, items: readonly ContributedMenuItem[], commands: readonly ContributedCommand[], lookup: ContextLookup, runnable: (extensionId: string) => boolean = () => true): MenuGroup[] { + const byId = new Map(commands.map((command) => [command.command, command])); + const groups = new Map(); + items.forEach((item, index) => { + if (item.menu !== menu || !runnable(item.extensionId) || !whenHolds(item.when, lookup)) { + return; + } + const command = byId.get(item.command); + const title = command ? (command.category && menu === 'commandPalette' ? `${command.category}: ${command.title}` : command.title) : item.command; + const action: MenuAction = { + command: item.command, + title, + icon: command?.icon ?? null, + enabled: whenHolds(command?.enablement ?? null, lookup), + extensionId: item.extensionId, + }; + const list = groups.get(item.group) ?? []; + list.push({ order: item.order, index, action }); + groups.set(item.group, list); + }); + const rank = (group: string): string => (group === 'navigation' ? '0' : group === 'inline' ? '1' : group === '' ? '3' : `2${group}`); + return [...groups.entries()] + .sort(([a], [b]) => rank(a).localeCompare(rank(b))) + .map(([group, list]) => ({ group, actions: list.sort((a, b) => a.order - b.order || a.index - b.index).map((entry) => entry.action) })); +} + +/** The buttons of a title bar (`navigation`) or of a row (`inline`), and the rest for its `...` menu. */ +export function splitActions(groups: readonly MenuGroup[], primary: 'navigation' | 'inline'): { primary: MenuAction[]; secondary: MenuGroup[] } { + return { + primary: groups.filter((group) => group.group === primary).flatMap((group) => group.actions), + secondary: groups.filter((group) => group.group !== primary && group.group !== (primary === 'navigation' ? 'inline' : 'navigation')), + }; +} + +/** The context keys of a workspace file, as VS Code sets them for `explorer/context` and `editor/*` menus. */ +export function resourceContext(path: string | null, languageId: string | null, isFolder = false): Record { + if (path === null) { + return {}; + } + const name = path.slice(path.lastIndexOf('/') + 1); + const dot = name.lastIndexOf('.'); + return { + resource: path, + resourcePath: path, + resourceScheme: 'file', + resourceFilename: name, + resourceDirname: path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '', + resourceExtname: dot > 0 ? name.slice(dot) : '', + resourceLangId: languageId ?? undefined, + explorerResourceIsFolder: isFolder, + }; +} + +const LANGUAGE_BY_EXTENSION: Readonly> = { + '.ts': 'typescript', '.tsx': 'typescriptreact', '.mts': 'typescript', '.cts': 'typescript', '.js': 'javascript', '.jsx': 'javascriptreact', '.mjs': 'javascript', '.cjs': 'javascript', + '.json': 'json', '.jsonc': 'jsonc', '.md': 'markdown', '.markdown': 'markdown', '.py': 'python', '.java': 'java', '.c': 'c', '.h': 'c', '.cpp': 'cpp', '.cc': 'cpp', '.hpp': 'cpp', + '.cs': 'csharp', '.go': 'go', '.rs': 'rust', '.rb': 'ruby', '.php': 'php', '.html': 'html', '.htm': 'html', '.css': 'css', '.scss': 'scss', '.less': 'less', + '.xml': 'xml', '.yaml': 'yaml', '.yml': 'yaml', '.sh': 'shellscript', '.bash': 'shellscript', '.ps1': 'powershell', '.sql': 'sql', '.kt': 'kotlin', '.swift': 'swift', + '.lua': 'lua', '.r': 'r', '.dart': 'dart', '.vue': 'vue', '.svelte': 'svelte', '.toml': 'toml', '.ini': 'ini', '.txt': 'plaintext', +}; + +/** A file's language id when no editor has it open (`resourceLangId` of the explorer's menu). */ +export function guessLanguageId(path: string): string | null { + const name = path.slice(path.lastIndexOf('/') + 1).toLowerCase(); + if (name === 'dockerfile') { + return 'dockerfile'; + } + if (name === 'makefile') { + return 'makefile'; + } + const dot = name.lastIndexOf('.'); + return dot > 0 ? LANGUAGE_BY_EXTENSION[name.slice(dot)] ?? null : null; +} + +/** The `file:` URI of a workspace file (`root` absolute, in the OS's spelling; `path` relative, with `/`). */ +export function fileUriOf(root: string, path: string): string { + const absolute = `${root.replace(/\\/g, '/').replace(/\/$/, '')}/${path}`; + const withSlash = absolute.startsWith('/') ? absolute : `/${absolute}`; + return `file://${withSlash.split('/').map((segment, index) => (index === 1 && /^[a-zA-Z]:$/.test(segment) ? segment : encodeURIComponent(segment))).join('/')}`; +} diff --git a/apps/ide/src/renderer/extensions/treeView.ts b/apps/ide/src/renderer/extensions/treeView.ts new file mode 100644 index 00000000..3f5429ea --- /dev/null +++ b/apps/ide/src/renderer/extensions/treeView.ts @@ -0,0 +1,462 @@ +import type { TreeItemData, ViewRequest } from '../../shared/extensionViewsProtocol.ts'; +import { el, icon } from '../dom.ts'; +import { extensionIcon } from './extensionIcons.ts'; +import type { MenuAction, MenuGroup } from './menuModel.ts'; + +/** + * #261: an extension's tree view in the side bar. Children load when a node + * is first expanded (or at once for an item that says it starts expanded); + * a refresh of the host reloads the changed parts and keeps what was open. + * A click selects and runs the item's command, or toggles a folder-like item; + * the context menu and the row's inline buttons come from `view/item/context`. + * Keyboard: arrows, Home/End, Enter, Space, Shift+F10. + * + * Every string an extension gives is set as text, never as markup. + */ + +const CHEVRON = 'M9 6l6 6-6 6'; + +export interface TreeViewDeps { + readonly viewId: string; + readonly canSelectMany: boolean; + request(request: ViewRequest): Promise; + /** The `view/item/context` entries for an item (and the selection). */ + itemMenu(item: TreeItemData): readonly MenuGroup[]; + /** Runs a menu command on an item (with the selected ones). */ + runItemCommand(action: MenuAction, item: TreeItemData, selected: readonly TreeItemData[]): void; + showMenu(groups: readonly MenuGroup[], x: number, y: number, run: (action: MenuAction) => void): void; + /** The tree went from empty to filled or back (the welcome content shows on an empty tree). */ + onEmptyChange(empty: boolean): void; + onError(message: string): void; +} + +interface Node { + data: TreeItemData; + readonly item: HTMLLIElement; + row: HTMLElement; + group: HTMLUListElement | null; + expanded: boolean; + loaded: boolean; + readonly parent: Node | null; + readonly depth: number; + children: Node[]; +} + +export interface ExtensionTreeView { + readonly element: HTMLElement; + /** Loads the roots (the view became visible, or the provider arrived). */ + load(): Promise; + /** `onDidChangeTreeData`: these items (null: everything). */ + refresh(handles: readonly string[] | null): Promise; + reveal(path: readonly string[], select: boolean, focus: boolean, expand: number): Promise; + collapseAll(): void; + /** Draws the rows again (the context keys changed: their inline buttons may too). */ + rerender(): void; + isEmpty(): boolean; + focus(): void; + dispose(): void; +} + +export function createTreeView(deps: TreeViewDeps): ExtensionTreeView { + const root = el('ul', { className: 'tree ext-tree', attrs: { role: 'tree', 'aria-label': deps.viewId, 'aria-multiselectable': String(deps.canSelectMany), 'data-testid': `ext-tree-${deps.viewId}` } }); + const nodes = new Map(); + let roots: Node[] = []; + let selected: Node[] = []; + let focused: Node | null = null; + let empty = true; + let disposed = false; + let rootsLoaded = false; + + const setEmpty = (value: boolean): void => { + if (value !== empty) { + empty = value; + deps.onEmptyChange(value); + } + }; + + const request = (req: ViewRequest): Promise => deps.request(req).catch((error: unknown) => { + deps.onError(error instanceof Error ? error.message.replace(/^Error invoking remote method '[^']+': (Error: )?/, '') : String(error)); + return null; + }); + + function label(data: TreeItemData): HTMLElement { + const text = data.label !== '' ? data.label : data.resourceName ?? ''; + const span = el('span', { className: 'tree-label' }); + const ranges = [...(data.highlights ?? [])].filter(([start, end]) => start >= 0 && end > start && end <= text.length).sort((a, b) => a[0] - b[0]); + let at = 0; + for (const [start, end] of ranges) { + if (start < at) { + continue; + } + span.append(document.createTextNode(text.slice(at, start)), el('mark', { className: 'tree-highlight', text: text.slice(start, end) })); + at = end; + } + span.append(document.createTextNode(text.slice(at))); + return span; + } + + function renderRow(node: Node): HTMLElement { + const { data } = node; + const collapsible = data.collapsible !== 0; + const iconElement = extensionIcon(data.icon && data.icon.kind !== 'iconFile' ? data.icon : null, { ...(data.resourceName ? { resourceName: data.resourceName } : {}), expanded: node.expanded }); + const inline = deps.itemMenu(data).filter((group) => group.group === 'inline').flatMap((group) => group.actions); + const actions = el('span', { className: 'ext-tree-actions' }, inline.map((action) => { + const button = el('button', { className: 'ext-action', attrs: { type: 'button', title: action.title, 'aria-label': action.title, tabindex: '-1' } }); + const glyph = extensionIcon(action.icon, { monochrome: true }); + if (glyph) { + button.append(glyph); + } else { + button.textContent = action.title; + button.classList.add('is-text'); + } + button.disabled = !action.enabled; + button.addEventListener('click', (event) => { + event.stopPropagation(); + deps.runItemCommand(action, node.data, selectionFor(node)); + }); + return button; + })); + const checkbox = data.checked === undefined ? null : el('input', { className: 'ext-tree-checkbox', attrs: { type: 'checkbox', tabindex: '-1', 'aria-label': data.label } }); + if (checkbox) { + checkbox.checked = data.checked === true; + checkbox.addEventListener('click', (event) => event.stopPropagation()); + checkbox.addEventListener('change', () => void request({ kind: 'treeCheckbox', viewId: deps.viewId, handle: node.data.handle, checked: checkbox.checked })); + } + const row = el('div', { + className: 'tree-row ext-tree-row', + attrs: { + role: 'treeitem', + tabindex: '-1', + 'aria-level': String(node.depth + 1), + 'aria-selected': String(selected.includes(node)), + 'aria-label': data.accessibilityLabel ?? (data.description ? `${data.label} ${data.description}` : data.label), + 'data-handle': data.handle, + ...(collapsible ? { 'aria-expanded': String(node.expanded) } : {}), + }, + }, [ + collapsible ? icon(CHEVRON, 'tree-chevron') : el('span', { className: 'tree-chevron-space' }), + ...(checkbox ? [checkbox] : []), + ...(iconElement ? [iconElement] : []), + label(data), + ...(data.description ? [el('span', { className: 'tree-description', text: data.description })] : []), + actions, + ]); + if (data.tooltip) { + row.title = data.tooltip; + } else if (data.resource?.path) { + row.title = data.resource.path; + } + row.style.paddingLeft = `${4 + node.depth * 12}px`; + row.addEventListener('click', (event) => onClick(node, event)); + row.addEventListener('contextmenu', (event) => { + event.preventDefault(); + if (!selected.includes(node)) { + select([node]); + } + openMenu(node, event.clientX, event.clientY); + }); + const chevron = row.firstElementChild; + if (collapsible && chevron) { + chevron.addEventListener('click', (event) => { + event.stopPropagation(); + void toggle(node); + }); + } + return row; + } + + function selectionFor(node: Node): TreeItemData[] { + return (selected.includes(node) ? selected : [node]).map((entry) => entry.data); + } + + function openMenu(node: Node, x: number, y: number): void { + const groups = deps.itemMenu(node.data).filter((group) => group.group !== 'inline'); + if (groups.length === 0) { + return; + } + deps.showMenu(groups, x, y, (action) => deps.runItemCommand(action, node.data, selectionFor(node))); + } + + function setFocus(node: Node | null, takeFocus = true): void { + if (focused && focused !== node) { + focused.row.tabIndex = -1; + } + focused = node; + if (node) { + node.row.tabIndex = 0; + if (takeFocus) { + node.row.focus(); + } + } + } + + function select(list: Node[], notify = true): void { + for (const node of selected) { + node.row.setAttribute('aria-selected', 'false'); + } + selected = list; + for (const node of selected) { + node.row.setAttribute('aria-selected', 'true'); + } + if (notify) { + void request({ kind: 'treeSelection', viewId: deps.viewId, handles: selected.map((node) => node.data.handle) }); + } + } + + function onClick(node: Node, event: MouseEvent): void { + setFocus(node); + if (deps.canSelectMany && (event.ctrlKey || event.metaKey)) { + select(selected.includes(node) ? selected.filter((other) => other !== node) : [...selected, node]); + return; + } + select([node]); + activate(node); + } + + function activate(node: Node): void { + if (node.data.hasCommand) { + void request({ kind: 'treeClick', viewId: deps.viewId, handle: node.data.handle }); + } else if (node.data.collapsible !== 0) { + void toggle(node); + } + } + + function makeNode(data: TreeItemData, parent: Node | null): Node { + const item = el('li', { attrs: { role: 'none' } }); + const node: Node = { data, item, row: el('div'), group: null, expanded: data.collapsible === 2, loaded: false, parent, depth: parent ? parent.depth + 1 : 0, children: [] }; + node.row = renderRow(node); + item.append(node.row); + return node; + } + + function forget(node: Node): void { + for (const child of node.children) { + forget(child); + } + if (nodes.get(node.data.handle) === node) { + nodes.delete(node.data.handle); + } + if (focused === node) { + focused = null; + } + selected = selected.filter((entry) => entry !== node); + } + + /** Fetches the children of `parent` (null: the roots) and reconciles them with what is shown. */ + async function loadChildren(parent: Node | null): Promise { + const answer = await request({ kind: 'treeChildren', viewId: deps.viewId, handle: parent ? parent.data.handle : null }) as { items?: TreeItemData[] } | null; + if (disposed || (parent && nodes.get(parent.data.handle) !== parent)) { + return; + } + const items = Array.isArray(answer?.items) ? answer.items : []; + const previous = parent ? parent.children : roots; + const byHandle = new Map(previous.map((node) => [node.data.handle, node])); + const next: Node[] = []; + for (const data of items) { + const old = byHandle.get(data.handle); + let node: Node; + if (old) { + byHandle.delete(data.handle); + old.data = data; + if (data.collapsible === 0) { + old.expanded = false; + } + const row = renderRow(old); + old.row.replaceWith(row); + if (focused === old) { + row.tabIndex = 0; + } + old.row = row; + node = old; + } else { + node = makeNode(data, parent); + } + nodes.set(data.handle, node); + next.push(node); + } + for (const gone of byHandle.values()) { + forget(gone); + } + if (parent) { + parent.children = next; + parent.loaded = true; + parent.group ??= el('ul', { attrs: { role: 'group' } }); + parent.group.replaceChildren(...next.map((node) => node.item)); + if (!parent.group.isConnected) { + parent.item.append(parent.group); + } + parent.group.hidden = !parent.expanded; + } else { + roots = next; + rootsLoaded = true; + root.replaceChildren(...next.map((node) => node.item)); + setEmpty(next.length === 0); + if (!focused && next[0]) { + setFocus(next[0], false); + } + } + // Items that are open (they start expanded, or were before the refresh) show their children too. + await Promise.all(next.filter((node) => node.expanded && node.data.collapsible !== 0).map((node) => loadChildren(node))); + } + + async function toggle(node: Node, expand = !node.expanded): Promise { + if (node.data.collapsible === 0 || node.expanded === expand) { + return; + } + node.expanded = expand; + node.row.setAttribute('aria-expanded', String(expand)); + void request({ kind: 'treeExpand', viewId: deps.viewId, handle: node.data.handle, expanded: expand }); + if (expand && !node.loaded) { + await loadChildren(node); + } else if (node.group) { + node.group.hidden = !expand; + } + // A folder icon follows the state. + if (node.data.icon?.kind === 'folder') { + const row = renderRow(node); + node.row.replaceWith(row); + row.tabIndex = focused === node ? 0 : -1; + node.row = row; + } + } + + function visibleNodes(): Node[] { + const list: Node[] = []; + const walk = (level: readonly Node[]): void => { + for (const node of level) { + list.push(node); + if (node.expanded && node.loaded) { + walk(node.children); + } + } + }; + walk(roots); + return list; + } + + root.addEventListener('keydown', (event) => { + const list = visibleNodes(); + const current = focused ?? list[0]; + if (!current) { + return; + } + const index = list.indexOf(current); + switch (event.key) { + case 'ArrowDown': setFocus(list[Math.min(list.length - 1, index + 1)] ?? current); break; + case 'ArrowUp': setFocus(list[Math.max(0, index - 1)] ?? current); break; + case 'Home': setFocus(list[0] ?? current); break; + case 'End': setFocus(list[list.length - 1] ?? current); break; + case 'ArrowRight': + if (current.data.collapsible !== 0 && !current.expanded) { + void toggle(current, true); + } else if (current.expanded && current.children[0]) { + setFocus(current.children[0]); + } + break; + case 'ArrowLeft': + if (current.expanded) { + void toggle(current, false); + } else if (current.parent) { + setFocus(current.parent); + } + break; + case 'Enter': + select([current]); + activate(current); + break; + case ' ': + select(deps.canSelectMany && (event.ctrlKey || event.metaKey) ? [...selected, current] : [current]); + break; + case 'ContextMenu': + case 'F10': { + if (event.key === 'F10' && !event.shiftKey) { + return; + } + const rect = current.row.getBoundingClientRect(); + openMenu(current, rect.left + 16, rect.bottom); + break; + } + default: + return; + } + event.preventDefault(); + }); + + return { + element: root, + load: () => loadChildren(null), + async refresh(handles) { + if (handles === null || !rootsLoaded) { + await loadChildren(null); + return; + } + // The parents of the changed items are asked again: that refreshes the items and their open children. + const parents = new Set(); + for (const handle of handles) { + const node = nodes.get(handle); + if (node) { + parents.add(node.parent); + } + } + if (parents.has(null)) { + await loadChildren(null); + return; + } + await Promise.all([...parents].map((parent) => loadChildren(parent))); + }, + async reveal(path, doSelect, doFocus, expand) { + if (!rootsLoaded) { + await loadChildren(null); + } + let node: Node | undefined; + for (const [index, handle] of path.entries()) { + node = nodes.get(handle); + if (!node) { + return; + } + if (index < path.length - 1) { + await toggle(node, true); + if (!node.loaded) { + await loadChildren(node); + } + } + } + if (!node) { + return; + } + let level: Node[] = [node]; + for (let depth = 0; depth < expand; depth++) { + await Promise.all(level.map((entry) => toggle(entry, true))); + level = level.flatMap((entry) => entry.children); + } + if (doSelect) { + select([node]); + } + setFocus(node, doFocus); + node.row.scrollIntoView({ block: 'nearest' }); + }, + collapseAll() { + for (const node of nodes.values()) { + if (node.expanded) { + void toggle(node, false); + } + } + }, + rerender() { + for (const node of nodes.values()) { + const row = renderRow(node); + row.tabIndex = focused === node ? 0 : -1; + node.row.replaceWith(row); + node.row = row; + } + }, + isEmpty: () => empty, + focus() { + (focused ?? roots[0])?.row.focus(); + }, + dispose() { + disposed = true; + root.remove(); + }, + }; +} diff --git a/apps/ide/src/renderer/extensions/viewsController.ts b/apps/ide/src/renderer/extensions/viewsController.ts new file mode 100644 index 00000000..6f4bb190 --- /dev/null +++ b/apps/ide/src/renderer/extensions/viewsController.ts @@ -0,0 +1,538 @@ +import { commandLink, parseWelcome, type ViewNotification, type ViewRequest } from '../../shared/extensionViewsProtocol.ts'; +import type { ContributedView, ContributedViewContainer, ExtensionContributions, ExtensionsApi } from '../../shared/extensions.ts'; +import { whenHolds } from '../../shared/whenClause.ts'; +import { showContextMenu, type ContextMenuItem } from '../contextMenu.ts'; +import { el, icon } from '../dom.ts'; +import type { ExtensionViewContainer, ViewId } from '../workbench.ts'; +import type { ContextKeys } from './contextKeys.ts'; +import { extensionIcon } from './extensionIcons.ts'; +import { menuGroups, splitActions, type MenuAction, type MenuGroup } from './menuModel.ts'; +import { createTreeView, type ExtensionTreeView } from './treeView.ts'; + +/** + * #261: the views extensions contribute. Each `viewsContainers` entry gets an + * activity item and a side-bar pane; each `views` entry is a folding section + * in its container (or under the built-in Explorer, Source Control or Run and + * Debug view). A section shows the tree its extension registers, its welcome + * content while the tree is empty or missing, and its title bar's buttons + * from `view/title`. `when` clauses are re-read whenever a context key + * changes. Visibility goes to the host (`onView:` activation, + * `TreeView.onDidChangeVisibility`). + */ + +export interface ViewsWorkbench { + addViewContainer(id: string, title: string, icon: Element | null): ExtensionViewContainer; + readonly extensionSections: Readonly>; + showView(id: ViewId): void; + onDidChangeView(listener: (id: ViewId | null) => void): () => void; +} + +export interface ViewsControllerDeps { + readonly extensions: ExtensionsApi; + readonly workbench: ViewsWorkbench; + readonly contextKeys: ContextKeys; + readonly storage: Storage | null; + /** Runs a command of an extension (or a built-in one the host maps). */ + runCommand(command: string, args?: readonly unknown[]): void; + openExternalLink(url: string): void; + onError(message: string): void; +} + +export interface ViewsController { + /** The contributions (or the runnable extensions) changed: rebuild the containers and sections. */ + setContributions(contributions: ExtensionContributions, runnable: ReadonlySet): void; + notification(notification: ViewNotification): void; + /** The host started or stopped: its trees are gone. */ + reset(): void; + /** `.focus`, `workbench.view.extension.`, ...: false when `id` is not one. */ + command(id: string): boolean; + /** The groups of an extension menu in a context (`explorer/context`, `editor/title`, ...). */ + menu(menu: string, extra: Readonly>): MenuGroup[]; +} + +const CHEVRON = 'M9 6l6 6-6 6'; +const MORE = 'M5 12h.01M12 12h.01M19 12h.01'; +const COLLAPSE_ALL = 'M9 9h10v10H9zM5 15V5h10M12 14h4'; + +interface Section { + readonly view: ContributedView; + readonly element: HTMLElement; + readonly header: HTMLElement; + readonly toggle: HTMLButtonElement; + readonly titleText: HTMLElement; + readonly descriptionText: HTMLElement; + readonly actions: HTMLElement; + readonly body: HTMLElement; + readonly message: HTMLElement; + readonly welcome: HTMLElement; + readonly container: string; + collapsed: boolean; + visible: boolean; +} + +interface TreeState { + readonly tree: ExtensionTreeView; + readonly extensionId: string; + readonly showCollapseAll: boolean; + title: string | null; + description: string | null; + message: string | null; + badge: { value: number; tooltip: string } | null; + loaded: boolean; +} + +function readFlag(storage: Storage | null, key: string): boolean | null { + try { + const value = storage?.getItem(key); + return value === 'true' ? true : value === 'false' ? false : null; + } catch { + return null; + } +} + +function writeFlag(storage: Storage | null, key: string, value: boolean): void { + try { + storage?.setItem(key, String(value)); + } catch { + // Storage unavailable: the default next time. + } +} + +/** A menu's groups as context menu items, separated. */ +export function contextMenuItems(groups: readonly MenuGroup[], run: (action: MenuAction) => void): ContextMenuItem[] { + const items: ContextMenuItem[] = []; + for (const group of groups) { + if (items.length > 0 && group.actions.length > 0) { + items.push({ separator: true }); + } + for (const action of group.actions) { + items.push({ label: action.title, enabled: action.enabled, run: () => run(action), testId: `ext-menu-${action.command}` }); + } + } + return items; +} + +export function createViewsController(deps: ViewsControllerDeps): ViewsController { + let contributions: ExtensionContributions | null = null; + let runnable: ReadonlySet = new Set(); + const containers = new Map(); + const containerKeys = new Map(); + const sections = new Map(); + const trees = new Map(); + let shown: ViewId | null = null; + + const request = (req: ViewRequest): Promise => deps.extensions.view(req); + const lookup = (extra: Readonly> = {}): ReturnType => deps.contextKeys.lookup(extra); + const isRunnable = (extensionId: string): boolean => runnable.has(extensionId); + + function menu(menuId: string, extra: Readonly>): MenuGroup[] { + if (!contributions) { + return []; + } + return menuGroups(menuId, contributions.menus, contributions.commands, lookup(extra), isRunnable); + } + + function paneOf(container: string): HTMLElement | null { + if (container === 'explorer' || container === 'scm' || container === 'debug') { + return deps.workbench.extensionSections[container]; + } + return containers.get(container)?.pane ?? null; + } + + function activityOf(container: string): ViewId { + return container === 'explorer' || container === 'scm' || container === 'debug' ? container : `ext:${container}`; + } + + /* ------------------------------ sections ------------------------------ */ + + function renderButtons(section: Section): void { + const tree = trees.get(section.view.id); + const groups = menu('view/title', { view: section.view.id, focusedView: section.view.id }); + const { primary, secondary } = splitActions(groups, 'navigation'); + const buttons: HTMLElement[] = primary.map((action) => { + const button = el('button', { className: 'icon-button ext-action', attrs: { type: 'button', title: action.title, 'aria-label': action.title } }); + const glyph = extensionIcon(action.icon, { monochrome: true }); + if (glyph) { + button.append(glyph); + } else { + button.textContent = action.title; + button.classList.add('is-text'); + } + button.disabled = !action.enabled; + button.addEventListener('click', () => deps.runCommand(action.command)); + return button; + }); + if (tree?.showCollapseAll) { + const collapse = el('button', { className: 'icon-button ext-action', attrs: { type: 'button', title: 'Collapse All', 'aria-label': 'Collapse All' } }, [icon(COLLAPSE_ALL)]); + collapse.addEventListener('click', () => tree.tree.collapseAll()); + buttons.push(collapse); + } + const more = secondary.flatMap((group) => group.actions); + if (more.length > 0) { + const button = el('button', { className: 'icon-button ext-action', attrs: { type: 'button', title: 'More Actions...', 'aria-label': 'More Actions...', 'aria-haspopup': 'menu' } }, [icon(MORE)]); + button.addEventListener('click', () => { + const rect = button.getBoundingClientRect(); + showContextMenu(contextMenuItems(secondary, (action) => deps.runCommand(action.command)), rect.left, rect.bottom, { label: `${section.view.name} actions` }); + }); + buttons.push(button); + } + section.actions.replaceChildren(...buttons); + } + + function renderWelcome(section: Section): void { + const tree = trees.get(section.view.id); + const showWelcome = !tree || tree.tree.isEmpty(); + const entries = (contributions?.viewsWelcome ?? []).filter((entry) => entry.view === section.view.id && whenHolds(entry.when, lookup({ view: section.view.id }))); + if (!showWelcome || entries.length === 0) { + section.welcome.hidden = true; + section.welcome.replaceChildren(); + return; + } + const children: HTMLElement[] = []; + const follow = (target: string): void => { + const link = commandLink(target); + if (link) { + deps.runCommand(link.command, link.args); + } else if (/^https?:\/\//i.test(target)) { + deps.openExternalLink(target); + } + }; + for (const entry of entries) { + for (const line of parseWelcome(entry.contents)) { + if (line.kind === 'button') { + const button = el('button', { className: 'primary-button ext-welcome-button', attrs: { type: 'button' }, text: line.label }); + button.addEventListener('click', () => follow(line.target)); + children.push(button); + continue; + } + children.push(el('p', { className: 'ext-welcome-text' }, line.parts.map((part) => { + if ('text' in part) { + return document.createTextNode(part.text); + } + const link = el('a', { className: 'ext-welcome-link', text: part.label, attrs: { href: '#', role: 'link' } }); + link.addEventListener('click', (event) => { + event.preventDefault(); + follow(part.target); + }); + return link; + }))); + } + } + section.welcome.replaceChildren(...children); + section.welcome.hidden = false; + } + + function renderHeader(section: Section): void { + const tree = trees.get(section.view.id); + section.titleText.textContent = tree?.title ?? section.view.name; + section.descriptionText.textContent = tree?.description ?? ''; + section.message.textContent = tree?.message ?? ''; + section.message.hidden = !tree?.message; + } + + function renderBadge(container: string): void { + const target = containers.get(container); + if (!target) { + return; + } + let total = 0; + const tooltips: string[] = []; + for (const section of sections.values()) { + const badge = trees.get(section.view.id)?.badge; + if (section.container === container && badge && badge.value > 0) { + total += badge.value; + if (badge.tooltip) { + tooltips.push(badge.tooltip); + } + } + } + target.setBadge(total, tooltips.join(', ')); + } + + /** Whether the person can see the section now (its pane shown, it unfolded and its `when` holding). */ + function isShown(section: Section): boolean { + return section.visible && !section.collapsed && shown === activityOf(section.container); + } + + function updateVisibility(section: Section): void { + const now = isShown(section); + if (section.element.dataset['shown'] === String(now)) { + return; + } + section.element.dataset['shown'] = String(now); + void request({ kind: 'viewVisibility', viewId: section.view.id, visible: now }).catch(() => undefined); + const tree = trees.get(section.view.id); + if (now && tree && !tree.loaded) { + tree.loaded = true; + void tree.tree.load(); + } + } + + function setCollapsed(section: Section, collapsed: boolean): void { + section.collapsed = collapsed; + section.element.classList.toggle('is-collapsed', collapsed); + section.toggle.setAttribute('aria-expanded', String(!collapsed)); + section.body.hidden = collapsed; + writeFlag(deps.storage, `codexr:extview:${section.view.id}:collapsed`, collapsed); + updateVisibility(section); + } + + function createSection(view: ContributedView): Section | null { + const pane = paneOf(view.container); + if (!pane) { + return null; + } + const titleText = el('span', { className: 'ext-view-title', text: view.name }); + const descriptionText = el('span', { className: 'ext-view-description' }); + const toggle = el('button', { className: 'outline-toggle ext-view-toggle', attrs: { type: 'button', 'aria-expanded': 'true', 'data-testid': `ext-view-toggle-${view.id}` } }, [icon(CHEVRON, 'tree-chevron'), titleText, descriptionText]); + const actions = el('span', { className: 'ext-view-actions' }); + const header = el('div', { className: 'outline-header ext-view-header' }, [toggle, actions]); + const message = el('p', { className: 'muted ext-view-message', attrs: { hidden: '' } }); + const welcome = el('div', { className: 'ext-welcome', attrs: { hidden: '' } }); + const body = el('div', { className: 'ext-view-body' }, [message, welcome]); + const element = el('section', { className: 'ext-view', attrs: { 'aria-label': view.name, 'data-view-id': view.id, 'data-testid': `ext-view-${view.id}` } }, [header, body]); + const section: Section = { view, element, header, toggle, titleText, descriptionText, actions, body, message, welcome, container: view.container, collapsed: false, visible: true }; + toggle.addEventListener('click', () => setCollapsed(section, !section.collapsed)); + const stored = readFlag(deps.storage, `codexr:extview:${view.id}:collapsed`); + section.collapsed = stored ?? view.collapsed; + element.classList.toggle('is-collapsed', section.collapsed); + toggle.setAttribute('aria-expanded', String(!section.collapsed)); + body.hidden = section.collapsed; + pane.append(element); + return section; + } + + function attachTree(section: Section): void { + const tree = trees.get(section.view.id); + if (tree && tree.tree.element.parentElement !== section.body) { + section.body.insertBefore(tree.tree.element, section.welcome); + } + renderHeader(section); + renderButtons(section); + renderWelcome(section); + } + + function evaluate(): void { + for (const section of sections.values()) { + section.visible = whenHolds(section.view.when, lookup({ view: section.view.id })); + section.element.hidden = !section.visible; + renderButtons(section); + renderWelcome(section); + updateVisibility(section); + } + // A container whose views are all hidden keeps its item, as in VS Code; nothing more to do. + } + + function clearSections(): void { + for (const section of sections.values()) { + const tree = trees.get(section.view.id); + tree?.tree.element.remove(); + section.element.remove(); + } + sections.clear(); + } + + /** + * Keeps the activity items whose container did not change, so a refresh + * (an extension activating, the trust changing) neither moves the person + * off the container they are looking at nor makes its item blink. + */ + function syncContainers(wanted: readonly ContributedViewContainer[]): void { + const keys = new Map(wanted.map((container) => [container.id, JSON.stringify([container.title, container.icon])])); + for (const [id, container] of containers) { + if (keys.get(id) !== containerKeys.get(id)) { + container.dispose(); + containers.delete(id); + containerKeys.delete(id); + } + } + for (const container of wanted) { + if (!containers.has(container.id)) { + containers.set(container.id, deps.workbench.addViewContainer(container.id, container.title, extensionIcon(container.icon, { monochrome: true }))); + containerKeys.set(container.id, keys.get(container.id) ?? ''); + } + } + } + + function build(): void { + clearSections(); + // Only containers with a view of an extension that is on (`views` only lists placed ones). + syncContainers(contributions ? contributions.viewContainers.filter((container) => contributions?.views.some((view) => view.container === container.id)) : []); + if (!contributions) { + return; + } + for (const view of contributions.views) { + const section = createSection(view); + if (section) { + sections.set(view.id, section); + attachTree(section); + } + } + for (const container of containers.keys()) { + renderBadge(container); + } + evaluate(); + } + + deps.contextKeys.onDidChange(() => { + evaluate(); + for (const tree of trees.values()) { + tree.tree.rerender(); + } + }); + deps.workbench.onDidChangeView((id) => { + shown = id; + for (const section of sections.values()) { + updateVisibility(section); + } + }); + + function revealSection(viewId: string): Section | null { + const section = sections.get(viewId); + if (!section) { + return null; + } + deps.workbench.showView(activityOf(section.container)); + if (section.collapsed) { + setCollapsed(section, false); + } + section.element.scrollIntoView({ block: 'nearest' }); + return section; + } + + function disposeTree(viewId: string): void { + const tree = trees.get(viewId); + if (!tree) { + return; + } + tree.tree.dispose(); + trees.delete(viewId); + const section = sections.get(viewId); + if (section) { + attachTree(section); + renderBadge(section.container); + } + } + + return { + setContributions(next, nextRunnable) { + contributions = next; + runnable = nextRunnable; + build(); + }, + notification(notification) { + switch (notification.kind) { + case 'treeRegistered': { + disposeTree(notification.viewId); + const tree = createTreeView({ + viewId: notification.viewId, + canSelectMany: notification.canSelectMany, + request, + itemMenu: (item) => menu('view/item/context', { view: notification.viewId, viewItem: item.contextValue ?? '', focusedView: notification.viewId }), + runItemCommand: (action, item, selected) => { + void request({ kind: 'treeCommand', viewId: notification.viewId, command: action.command, handle: item.handle, selected: selected.map((entry) => entry.handle) }) + .catch((error: unknown) => deps.onError(`Command '${action.command}' failed: ${String(error)}`)); + }, + showMenu: (groups, x, y, run) => showContextMenu(contextMenuItems(groups, run), x, y, { label: `${notification.viewId} item actions` }), + onEmptyChange: () => { + const section = sections.get(notification.viewId); + if (section) { + renderWelcome(section); + } + }, + onError: deps.onError, + }); + trees.set(notification.viewId, { tree, extensionId: notification.extensionId, showCollapseAll: notification.showCollapseAll, title: null, description: null, message: null, badge: null, loaded: false }); + const section = sections.get(notification.viewId); + if (section) { + attachTree(section); + section.element.dataset['shown'] = ''; + updateVisibility(section); + } + return; + } + case 'treeDisposed': + disposeTree(notification.viewId); + return; + case 'treeChanged': { + const tree = trees.get(notification.viewId); + if (tree?.loaded) { + void tree.tree.refresh(notification.handles); + } + return; + } + case 'treeReveal': { + const tree = trees.get(notification.viewId); + if (!tree) { + return; + } + if (notification.focus || notification.select) { + revealSection(notification.viewId); + } + tree.loaded = true; + void tree.tree.reveal(notification.path, notification.select, notification.focus, notification.expand); + return; + } + case 'viewMeta': { + const tree = trees.get(notification.viewId); + if (!tree) { + return; + } + if (notification.title !== undefined) { + tree.title = notification.title; + } + if (notification.description !== undefined) { + tree.description = notification.description; + } + if (notification.message !== undefined) { + tree.message = notification.message; + } + if (notification.badge !== undefined) { + tree.badge = notification.badge; + } + const section = sections.get(notification.viewId); + if (section) { + renderHeader(section); + renderBadge(section.container); + } + return; + } + case 'viewFocus': + if (revealSection(notification.viewId)) { + trees.get(notification.viewId)?.tree.focus(); + } + return; + } + }, + reset() { + for (const viewId of [...trees.keys()]) { + disposeTree(viewId); + } + }, + command(id) { + const focus = /^(.+)\.focus$/.exec(id); + if (focus && sections.has(focus[1] as string)) { + revealSection(focus[1] as string); + trees.get(focus[1] as string)?.tree.focus(); + return true; + } + const container = /^workbench\.view\.extension\.(.+)$/.exec(id); + if (container && containers.has(container[1] as string)) { + deps.workbench.showView(`ext:${container[1] as string}`); + return true; + } + const collapse = /^workbench\.actions\.treeView\.(.+)\.collapseAll$/.exec(id); + if (collapse && trees.has(collapse[1] as string)) { + trees.get(collapse[1] as string)?.tree.collapseAll(); + return true; + } + const refresh = /^workbench\.actions\.treeView\.(.+)\.refresh$/.exec(id); + if (refresh && trees.has(refresh[1] as string)) { + void trees.get(refresh[1] as string)?.tree.refresh(null); + return true; + } + return false; + }, + menu, + }; +} diff --git a/apps/ide/src/renderer/main.ts b/apps/ide/src/renderer/main.ts index 7d7c56c5..e6f38267 100644 --- a/apps/ide/src/renderer/main.ts +++ b/apps/ide/src/renderer/main.ts @@ -39,6 +39,7 @@ import { createEditorStatus } from './editor/editorStatus.ts'; import { eolChoices, indentationChoices, languageChoices, type Choice } from './editor/editorStatusModel.ts'; import { parseSession, serializeSession, sessionKey } from './editor/tabsModel.ts'; import { showContextMenu, type ContextMenuItem } from './contextMenu.ts'; +import { el, icon } from './dom.ts'; import { createSettingsView } from './settings/settingsView.ts'; import { createKeybindingsView } from './settings/keybindingsView.ts'; import { menuAccelerators } from './settings/keybindingsModel.ts'; @@ -46,6 +47,10 @@ import { COLOR_THEME_SETTING, isColorTheme, settingOf, type ColorTheme } from '. import { themeChoices } from './settings/settingsModel.ts'; import { isMarkdownPath } from './editor/markdownPath.ts'; import { installExtensions } from './extensions/extensionsWiring.ts'; +import { platformContext } from './extensions/contextKeys.ts'; +import { fileUriOf, guessLanguageId, resourceContext, splitActions, type MenuAction } from './extensions/menuModel.ts'; +import { extensionIcon } from './extensions/extensionIcons.ts'; +import { contextMenuItems } from './extensions/viewsController.ts'; import type { ContributedTheme } from '../shared/extensions.ts'; const EXTENSION_THEME_SETTING = 'workbench.colorThemeExtension'; import type { IdeCommand, KeybindingsReport, PythonEnvStatus, SettingsReport, WatchedEntry } from '../shared/api.ts'; @@ -60,6 +65,8 @@ const api = window.codexr; let folderIsOpen = false; /** The open folder's absolute path, for the terminal's file links (#286). */ let workspaceRoot: string | null = null; +/** #261: something extensions' `when` clauses read changed (trust, folder, settings, active file). */ +let workbenchContextChanged = (): void => undefined; /** The active editor's file, for quick open's recent list (#164). */ let activeFile: string | null = null; // #169: the layout is remembered in the renderer's storage (inside the IDE's user-data folder). @@ -137,6 +144,7 @@ function editorGroup(): Promise { onFileClean: (path) => outline?.fileClean(path), onDidSave: (path) => extensions.documentSaved(path), revealInScene: (path) => revealInScene(path), + titleActions: (tabId) => editorTitleButtons(tabId), }); editors.setSceneShown(!workbench.sceneArea.hidden); // #256: PDFs and images open in viewer tabs. @@ -314,6 +322,7 @@ function showTabMenu(path: string, x: number, y: number): void { ...(isMarkdownPath(path) ? [{ label: 'Open Preview to the Side', keybinding: key('markdown.showPreviewToSide'), run: () => void openPreviewOf(path), testId: 'tab-menu-markdown-preview' }] : []), { label: 'Split Right', keybinding: key('editor.splitRight'), run: () => editors?.split(path), testId: 'tab-menu-split-right' }, { label: 'Keep Open', keybinding: key('editor.keep'), run: () => editors?.keepActive(), testId: 'tab-menu-keep' }, + ...extensionMenuItems('editor/title/context', path), { label: 'Reveal in Explorer', run: () => void revealInExplorer(path), testId: 'tab-menu-reveal' }, ...(workbench.sceneArea.hidden ? [] : [{ label: 'Reveal in XR Scene', run: () => revealInScene(path), testId: 'tab-menu-reveal-in-scene' }]), { separator: true }, @@ -325,6 +334,55 @@ function showTabMenu(path: string, x: number, y: number): void { }); } +/** #261: a file's language id: its editor's when it is open, else a guess from its name. */ +function languageOfFile(path: string): string | null { + const open = editors?.activeModel(); + return open && open.path === path ? open.model.getLanguageId() : guessLanguageId(path); +} + +/** #261: the entries extensions add to a file's menu (`explorer/context`, `editor/title/context`), with the file as argument. */ +function extensionMenuItems(menu: string, path: string): ContextMenuItem[] { + const groups = extensions.menu(menu, resourceContext(path, languageOfFile(path))); + const items = contextMenuItems(groups, (action) => void api.workspace.current().then((workspace) => { + // A `vscode.Uri` in the host's wire format. + extensions.runCommand(action.command, workspace ? [{ $uri: fileUriOf(workspace.root, path) }] : []); + })); + return items.length > 0 ? [{ separator: true }, ...items] : []; +} + +/** #261: the buttons extensions put in an editor's title (`editor/title`): `navigation` as icons, the rest under `...`. */ +function editorTitleButtons(tabId: string | null): HTMLElement[] { + if (tabId === null || isSchemeId(tabId)) { + return []; + } + const { primary, secondary } = splitActions(extensions.menu('editor/title', { ...resourceContext(tabId, languageOfFile(tabId)), activeEditor: 'workbench.editors.files.textFileEditor' }), 'navigation'); + const run = (action: MenuAction): void => void api.workspace.current().then((workspace) => { + extensions.runCommand(action.command, workspace ? [{ $uri: fileUriOf(workspace.root, tabId) }] : []); + }); + const buttons: HTMLElement[] = primary.map((action) => { + const button = el('button', { className: 'icon-button ext-action', attrs: { type: 'button', title: action.title, 'aria-label': action.title, 'data-testid': `editor-title-${action.command}` } }); + const glyph = extensionIcon(action.icon, { monochrome: true }); + if (glyph) { + button.append(glyph); + } else { + button.textContent = action.title; + button.classList.add('is-text'); + } + button.disabled = !action.enabled; + button.addEventListener('click', () => run(action)); + return button; + }); + if (secondary.some((group) => group.actions.length > 0)) { + const more = el('button', { className: 'icon-button ext-action', attrs: { type: 'button', title: 'More Actions...', 'aria-label': 'More Actions...', 'aria-haspopup': 'menu' } }, [icon('M5 12h.01M12 12h.01M19 12h.01')]); + more.addEventListener('click', () => { + const rect = more.getBoundingClientRect(); + showContextMenu(contextMenuItems(secondary, run), rect.left, rect.bottom, { label: 'Editor actions' }); + }); + buttons.push(more); + } + return buttons; +} + /** #16: the analyses of one file, as the extension's explorer menu offers them. */ function fileAnalysisItems(path: string, prefix: string): ContextMenuItem[] { const enabled = runView.canAnalyse(); @@ -369,6 +427,7 @@ function showExplorerMenu(path: string, kind: 'file' | 'directory', x: number, y ]), ...(isFile && !workbench.sceneArea.hidden ? [{ label: 'Reveal in XR Scene', run: () => revealInScene(path), testId: 'explorer-menu-reveal-in-scene' }] : []), ...(isFile ? [{ separator: true } as const, ...fileAnalysisItems(path, 'explorer-menu')] : []), + ...extensionMenuItems('explorer/context', path), ]; showContextMenu(items, x, y, { label: `Actions for ${path || 'the folder'}`, @@ -417,6 +476,7 @@ const workspaceTrust = createWorkspaceTrustView({ pick: (label, items, apply) => pick(label, items.map((item) => ({ ...item, value: item.id })), apply), onError: (message) => notifications.notify('error', message), onChange: () => { + workbenchContextChanged(); debug.reloadConfigurations(); // The main process restarted this window's language servers; send the open documents again. if (editorsLoading) { @@ -428,6 +488,7 @@ const workspaceTrust = createWorkspaceTrustView({ /** #139: the main process stops the old folder's scene; the panel follows, and the new folder may be analysed. */ function folderOpened(root: string): void { folderIsOpen = true; + workbenchContextChanged(); void workspaceTrust.refresh(); quickOpenFiles.reset(); workspaceSymbols.reset(); @@ -443,6 +504,7 @@ api.workspace.onDidChange((workspace) => { folderOpened(workspace.root); } else { folderIsOpen = false; + workbenchContextChanged(); quickOpenFiles.reset(); workspaceSymbols.reset(); searchView.reset(); @@ -509,6 +571,7 @@ api.git.onDidChange(() => editors?.gitChanged()); let settingsReport: SettingsReport | null = null; function applySettings(report: SettingsReport): void { settingsReport = report; + workbenchContextChanged(); settingsView.show(report); editors?.applySettings(report.effective); terminal.setFontSize(settingOf(report, 'terminal.integrated.fontSize')); @@ -800,9 +863,28 @@ const extensions = installExtensions({ await group.save(); return !group.dirtyPaths().includes(path); }, + views: workbench, + storage: layoutStorage(), }); // #284: Source Control's remote, stash and branch commands, under VS Code's ids. registerGitCommands(registry, scmView); +// #261: the workbench's context keys for extensions' `when` clauses. +extensions.contextKeys.addProvider((key) => platformContext(platform)(key)); +extensions.contextKeys.addProvider((key) => { + switch (key) { + case 'isWorkspaceTrusted': return workspaceTrust.current()?.state === 'trusted'; + case 'workspaceFolderCount': return folderIsOpen ? 1 : 0; + case 'workbenchState': return folderIsOpen ? 'folder' : 'empty'; + case 'virtualWorkspace': return false; + case 'remoteName': return ''; + case 'activeEditor': return activeFile === null ? undefined : 'workbench.editors.files.textFileEditor'; + case 'editorLangId': return activeFile === null ? undefined : languageOfFile(activeFile); + default: + return key.startsWith('config.') && settingsReport ? settingsReport.effective[key.slice('config.'.length)] : undefined; + } +}); +workbenchContextChanged = () => extensions.contextKeys.changed(); +extensions.contextKeys.onDidChange(() => editors?.refreshTitleActions()); registerDebugCommands(registry, debug, () => folderIsOpen, () => (editors?.activeLineCount() ?? null) !== null, () => workbench.showView('debug')); registerAgentCommands(registry, { showAgents: () => workbench.showView('agents'), addProvider: () => agentsView.addProvider(), newChat: () => void agentsView.newChat() }); registerWorkbenchCommands(registry, { diff --git a/apps/ide/src/renderer/viteWorker.d.ts b/apps/ide/src/renderer/viteWorker.d.ts index 41dff7bb..62a445d3 100644 --- a/apps/ide/src/renderer/viteWorker.d.ts +++ b/apps/ide/src/renderer/viteWorker.d.ts @@ -9,3 +9,13 @@ declare module '*?url' { const url: string; export default url; } + +/** #261: Monaco's codicon table (an internal module without types): registering it fills the map below. */ +declare module 'monaco-editor/base/common/codicons.js' { + export const Codicon: Readonly>; +} + +declare module 'monaco-editor/base/common/codiconsUtil.js' { + /** Codicon id (`refresh`, `git-commit`) -> its character in the codicon font. */ + export function getCodiconFontCharacters(): Readonly>; +} diff --git a/apps/ide/src/renderer/workbench.ts b/apps/ide/src/renderer/workbench.ts index f9a883da..14575bd6 100644 --- a/apps/ide/src/renderer/workbench.ts +++ b/apps/ide/src/renderer/workbench.ts @@ -38,8 +38,17 @@ const ACTIVITY: readonly ActivityItem[] = [ { id: 'settings', label: 'Settings', icon: 'M12 9a3 3 0 1 0 0 6a3 3 0 1 0 0-6zM12 2v3M12 19v3M2 12h3M19 12h3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M4.9 19.1L7 17M17 7l2.1-2.1', bottom: true }, ]; -/** `keybindings` has no activity item of its own: it is part of Settings (#18, part 3). */ -export type ViewId = 'explorer' | 'search' | 'scm' | 'debug' | 'analysis' | 'xr' | 'agents' | 'extensions' | 'settings' | 'keybindings'; +/** `keybindings` has no activity item of its own: it is part of Settings (#18, part 3). `ext:`: an extension's view container (#261). */ +export type ViewId = 'explorer' | 'search' | 'scm' | 'debug' | 'analysis' | 'xr' | 'agents' | 'extensions' | 'settings' | 'keybindings' | `ext:${string}`; + +/** #261: an extension's view container in the activity bar. */ +export interface ExtensionViewContainer { + /** The side-bar pane its views go in. */ + readonly pane: HTMLElement; + /** The activity item's badge (a tree view's `badge`); 0 hides it. */ + setBadge(value: number, tooltip: string): void; + dispose(): void; +} export interface Workbench { /** The explorer's part of its side-bar pane (the file tree). */ @@ -95,6 +104,12 @@ export interface Workbench { readonly extensionStatusRight: HTMLElement; /** Sizes and visibility of the side bar, panel and scene column (#169, layout/layout.ts). */ readonly layout: WorkbenchLayout; + /** #261: adds an extension's view container (an activity item and its pane), before Settings. */ + addViewContainer(id: string, title: string, icon: Element | null): ExtensionViewContainer; + /** #261: where extensions' views go in the built-in Explorer, Source Control and Run and Debug views. */ + readonly extensionSections: Readonly>; + /** #261: listens for the shown side-bar view changing (or the side bar hiding: null). */ + onDidChangeView(listener: (id: ViewId | null) => void): () => void; } export function renderWorkbench(root: HTMLElement, storage: LayoutStorage | null = null): Workbench { @@ -120,10 +135,19 @@ export function renderWorkbench(root: HTMLElement, storage: LayoutStorage | null // #172: the explorer pane holds the file tree and, under it, the Outline section. const sideBar = el('div', { className: 'explorer-section' }); const outlineView = el('section', { attrs: { 'aria-label': 'Outline', 'data-testid': 'outline-section' } }); - const explorerPane = el('div', { className: 'side-pane explorer-pane', attrs: { 'data-view': 'explorer' } }, [sideBar, outlineView]); + // #261: extensions' views go under the file tree, and under the Source Control and Run and Debug views. + const extensionSections = { + explorer: el('div', { className: 'ext-sections', attrs: { 'data-testid': 'ext-sections-explorer' } }), + scm: el('div', { className: 'ext-sections', attrs: { 'data-testid': 'ext-sections-scm' } }), + debug: el('div', { className: 'ext-sections', attrs: { 'data-testid': 'ext-sections-debug' } }), + }; + const explorerPane = el('div', { className: 'side-pane explorer-pane', attrs: { 'data-view': 'explorer' } }, [sideBar, extensionSections.explorer, outlineView]); const searchView = el('div', { className: 'side-pane', attrs: { 'data-view': 'search', 'data-testid': 'search-view' } }); - const scmView = el('div', { className: 'side-pane', attrs: { 'data-view': 'scm', 'data-testid': 'scm-view' } }); - const debugView = el('div', { className: 'side-pane', attrs: { 'data-view': 'debug', 'data-testid': 'debug-view' } }); + // The views fill their own element (replaceChildren), so the sections sit beside it in the pane. + const scmView = el('div', { className: 'side-pane-main', attrs: { 'data-testid': 'scm-view' } }); + const debugView = el('div', { className: 'side-pane-main', attrs: { 'data-testid': 'debug-view' } }); + const scmPane = el('div', { className: 'side-pane has-sections', attrs: { 'data-view': 'scm' } }, [scmView, extensionSections.scm]); + const debugPane = el('div', { className: 'side-pane has-sections', attrs: { 'data-view': 'debug' } }, [debugView, extensionSections.debug]); const analysisView = el('div', { className: 'side-pane', attrs: { 'data-view': 'analysis', 'data-testid': 'analysis-view' } }); const xrView = el('div', { className: 'side-pane', attrs: { 'data-view': 'xr' } }, [ el('h2', { className: 'side-bar-title', text: 'XR scene' }), @@ -133,10 +157,22 @@ export function renderWorkbench(root: HTMLElement, storage: LayoutStorage | null const extensionsView = el('div', { className: 'side-pane', attrs: { 'data-view': 'extensions', 'data-testid': 'extensions-view' } }); const settingsView = el('div', { className: 'side-pane', attrs: { 'data-view': 'settings', 'data-testid': 'settings-view' } }); const keybindingsView = el('div', { className: 'side-pane', attrs: { 'data-view': 'keybindings', 'data-testid': 'keybindings-view' } }); - const panes = new Map([['explorer', explorerPane], ['search', searchView], ['scm', scmView], ['debug', debugView], ['analysis', analysisView], ['xr', xrView], ['agents', agentsView], ['extensions', extensionsView], ['settings', settingsView], ['keybindings', keybindingsView]]); - const sideBarFrame = el('aside', { className: 'side-bar', attrs: { 'aria-label': 'Explorer', 'data-testid': 'side-bar' } }, [explorerPane, searchView, scmView, debugView, analysisView, xrView, agentsView, extensionsView, settingsView, keybindingsView]); + const panes = new Map([['explorer', explorerPane], ['search', searchView], ['scm', scmPane], ['debug', debugPane], ['analysis', analysisView], ['xr', xrView], ['agents', agentsView], ['extensions', extensionsView], ['settings', settingsView], ['keybindings', keybindingsView]]); + const sideBarFrame = el('aside', { className: 'side-bar', attrs: { 'aria-label': 'Explorer', 'data-testid': 'side-bar' } }, [explorerPane, searchView, scmPane, debugPane, analysisView, xrView, agentsView, extensionsView, settingsView, keybindingsView]); + const labels = new Map(ACTIVITY.map((item) => [item.id as ViewId, item.label])); + const viewListeners = new Set<(id: ViewId | null) => void>(); + let shownView: ViewId | null = null; + const announceView = (): void => { + const id = layout.sideBarVisible && !layout.zen ? shownView : null; + for (const listener of viewListeners) { + listener(id); + } + }; function showView(id: ViewId, reveal = true): void { + if (!panes.has(id)) { + return; + } if (reveal && (!layout.sideBarVisible || layout.zen)) { layout.setSideBarVisible(true); } @@ -147,7 +183,49 @@ export function renderWorkbench(root: HTMLElement, storage: LayoutStorage | null button?.classList.toggle('is-active', viewId === activity); button?.setAttribute('aria-pressed', String(viewId === activity)); } - sideBarFrame.setAttribute('aria-label', id === 'keybindings' ? 'Keyboard Shortcuts' : ACTIVITY.find((item) => item.id === id)?.label ?? id); + sideBarFrame.setAttribute('aria-label', id === 'keybindings' ? 'Keyboard Shortcuts' : labels.get(id) ?? id); + shownView = id; + announceView(); + } + + function addViewContainer(id: string, title: string, image: Element | null): ExtensionViewContainer { + const viewId: ViewId = `ext:${id}`; + const badge = el('span', { className: 'activity-badge', attrs: { hidden: '' } }); + const button = el('button', { + className: 'activity-item', + attrs: { type: 'button', title, 'aria-label': title, 'aria-pressed': 'false', 'data-view': viewId }, + }, [image ?? el('span', { className: 'activity-letter', text: title.slice(0, 1).toUpperCase() }), badge]); + button.addEventListener('click', () => { + if (button.classList.contains('is-active') && layout.sideBarVisible && !layout.zen) { + layout.setSideBarVisible(false); + } else { + showView(viewId); + } + }); + const pane = el('div', { className: 'side-pane ext-container-pane', attrs: { 'data-view': viewId, hidden: '' } }); + activityBar.insertBefore(button, buttons.get('settings') ?? null); + sideBarFrame.append(pane); + buttons.set(viewId, button); + panes.set(viewId, pane); + labels.set(viewId, title); + return { + pane, + setBadge(value, tooltip) { + badge.hidden = value <= 0; + badge.textContent = value > 99 ? '99+' : String(value); + button.title = value > 0 && tooltip ? `${title} - ${tooltip}` : title; + }, + dispose() { + if (shownView === viewId) { + showView('explorer', false); + } + button.remove(); + pane.remove(); + buttons.delete(viewId); + panes.delete(viewId); + labels.delete(viewId); + }, + }; } const infoList = el('dl', { className: 'info-list' }); @@ -199,6 +277,7 @@ export function renderWorkbench(root: HTMLElement, storage: LayoutStorage | null root.replaceChildren(shell); const layout = createLayout({ shell, sideBar: sideBarFrame, panel, sceneArea }, storage); showView('explorer', false); + layout.onDidChange(announceView); return { sideBar, @@ -232,6 +311,12 @@ export function renderWorkbench(root: HTMLElement, storage: LayoutStorage | null extensionStatusLeft, extensionStatusRight, layout, + addViewContainer, + extensionSections, + onDidChangeView(listener) { + viewListeners.add(listener); + return () => viewListeners.delete(listener); + }, setStatus(message: string): void { statusLeft.textContent = message; }, diff --git a/apps/ide/src/shared/extensionHostProtocol.ts b/apps/ide/src/shared/extensionHostProtocol.ts index a0d8d01e..2a7e913d 100644 --- a/apps/ide/src/shared/extensionHostProtocol.ts +++ b/apps/ide/src/shared/extensionHostProtocol.ts @@ -12,6 +12,7 @@ */ import type { DiagnosticsUpdate, EditorStateData, ProviderRegistration, RangeData, WorkspaceEditData } from './extensionLanguageProtocol.ts'; +import type { ViewNotification } from './extensionViewsProtocol.ts'; import type { ExtensionActivation, ExtensionId } from './extensions.ts'; export type RpcMessage = @@ -232,6 +233,8 @@ export const HOST_METHODS = { documents: 'documents', /** #260 (ProvideRequest) -> the provider's answer as plain data (extensionLanguageProtocol.ts). */ provide: 'provide', + /** #261 (ViewRequest) -> answer (extensionViewsProtocol.ts); tree resources are absolute paths. */ + view: 'view', } as const; /* ------------------------------------------------------------------ */ @@ -360,7 +363,9 @@ export type UiNotification = | { readonly kind: 'providerRegistered'; readonly registration: ProviderRegistration } | { readonly kind: 'providerUnregistered'; readonly handle: number } /** A host started or stopped: every provider and diagnostic of the previous one is gone. */ - | { readonly kind: 'providersReset' }; + | { readonly kind: 'providersReset' } + /** #261: the extensions' tree views (no paths). */ + | { readonly kind: 'view'; readonly notification: ViewNotification }; /** Main -> renderer: one UI request of the host (answer with `extensionsHostReply`), or a notification. */ export type HostUiEvent = diff --git a/apps/ide/src/shared/extensionViewsProtocol.ts b/apps/ide/src/shared/extensionViewsProtocol.ts new file mode 100644 index 00000000..7ab9da6d --- /dev/null +++ b/apps/ide/src/shared/extensionViewsProtocol.ts @@ -0,0 +1,222 @@ +/** + * #261: the views extensions add to the workbench — the tree views of + * `contributes.views` filled by `window.registerTreeDataProvider` / + * `createTreeView` — and the menus that act on them. The wire between the + * renderer, the main process and the extension host. + * + * Tree elements never leave the host: each gets an opaque handle, and the + * workbench asks for children, clicks and menu commands by handle. Icons from + * files are read by the main process (inside an extension or the workspace + * only) and reach the renderer as data URLs; a `resource` path is rewritten + * like every other path (workspace paths in the renderer, absolute in the + * host). + * + * Shared by main, the host and the renderer: no Node, Electron or DOM import. + */ + +import type { ExtensionId } from './extensions.ts'; + +/** An icon as the workbench draws it. */ +export type IconData = + /** A product icon (`$(name)`, `ThemeIcon`), from the codicon font. */ + | { readonly kind: 'codicon'; readonly name: string; readonly color?: string } + /** An image, as `data:` URLs (the dark one for dark themes). */ + | { readonly kind: 'image'; readonly light: string; readonly dark: string } + /** `ThemeIcon.File` / `ThemeIcon.Folder`: the workbench's file icon for the item's resource. */ + | { readonly kind: 'file' } + | { readonly kind: 'folder' }; + +/** An icon as the host sends it: a file to read stays absolute until the main process inlines it. */ +export type HostIconData = IconData | { readonly kind: 'iconFile'; readonly file: string; readonly darkFile?: string }; + +/** `TreeItemCollapsibleState`: none, collapsed, expanded. */ +export type Collapsible = 0 | 1 | 2; + +export interface TreeItemData { + readonly handle: string; + readonly label: string; + /** `TreeItemLabel.highlights`: [start, end) ranges of the label. */ + readonly highlights?: readonly (readonly [number, number])[]; + readonly description?: string; + readonly tooltip?: string; + readonly collapsible: Collapsible; + readonly icon?: HostIconData; + /** `resourceUri`: a workspace path in the renderer (null when outside the folder), absolute in the host. */ + readonly resource?: { readonly path: string } | null; + /** The resource's file name, kept when the path is outside the folder (for the label and the icon). */ + readonly resourceName?: string; + /** The item has a `command`: a click runs it (the host keeps the arguments). */ + readonly hasCommand?: boolean; + readonly contextValue?: string; + readonly accessibilityLabel?: string; + /** `TreeItemCheckboxState`, when the item shows a checkbox. */ + readonly checked?: boolean; +} + +/** Renderer -> host, by way of the main process. */ +export type ViewRequest = + /** The children of `handle` (null: the roots). Answers `{ items }`, or null when no provider is registered. */ + | { readonly kind: 'treeChildren'; readonly viewId: string; readonly handle: string | null } + /** The item was clicked (or Enter): runs its `command`. */ + | { readonly kind: 'treeClick'; readonly viewId: string; readonly handle: string } + /** A menu command on items: runs `command` with the element (and the selected elements). */ + | { readonly kind: 'treeCommand'; readonly viewId: string; readonly command: string; readonly handle: string | null; readonly selected: readonly string[] } + | { readonly kind: 'treeExpand'; readonly viewId: string; readonly handle: string; readonly expanded: boolean } + | { readonly kind: 'treeSelection'; readonly viewId: string; readonly handles: readonly string[] } + | { readonly kind: 'treeCheckbox'; readonly viewId: string; readonly handle: string; readonly checked: boolean } + /** The view was shown or hidden: activates `onView:` and fires `onDidChangeVisibility`. */ + | { readonly kind: 'viewVisibility'; readonly viewId: string; readonly visible: boolean }; + +export const MAX_VIEW_SELECTION = 1000; + +/** Host -> renderer (a `UiNotification` of kind `view`). */ +export type ViewNotification = + | { readonly kind: 'treeRegistered'; readonly viewId: string; readonly extensionId: ExtensionId; readonly showCollapseAll: boolean; readonly canSelectMany: boolean; readonly manageCheckboxStateManually: boolean } + | { readonly kind: 'treeDisposed'; readonly viewId: string } + /** `onDidChangeTreeData`: these items changed (null: the whole tree). */ + | { readonly kind: 'treeChanged'; readonly viewId: string; readonly handles: readonly string[] | null } + /** `TreeView.reveal`: the chain from a root to the item, which is selected and/or focused, and expanded `expand` levels. */ + | { readonly kind: 'treeReveal'; readonly viewId: string; readonly path: readonly string[]; readonly select: boolean; readonly focus: boolean; readonly expand: number } + /** `TreeView.title`, `description`, `message`, `badge`; an absent field is unchanged, null clears it. */ + | { readonly kind: 'viewMeta'; readonly viewId: string; readonly title?: string | null; readonly description?: string | null; readonly message?: string | null; readonly badge?: { readonly value: number; readonly tooltip: string } | null } + /** Shows and focuses a view (`.focus`, `workbench.view.extension.`). */ + | { readonly kind: 'viewFocus'; readonly viewId: string }; + +/** The context keys of an item, for `view/item/context` menus. */ +export function itemContext(viewId: string, item: Pick | null): Readonly> { + return { view: viewId, viewItem: item?.contextValue ?? '', focusedView: viewId }; +} + +/** `$(name)` or `$(name~spin)` -> the codicon's name; null for any other string. */ +export function codiconName(value: string): string | null { + const match = /^\$\(([a-z0-9-]+)(?:~[a-z]+)?\)$/i.exec(value.trim()); + return match ? match[1] as string : null; +} + +/** Splits text with `$(icon)` references into text and icons (a label like `$(sync~spin) Syncing`). */ +export function splitIcons(text: string): ({ readonly text: string } | { readonly icon: string })[] { + const parts: ({ readonly text: string } | { readonly icon: string })[] = []; + const pattern = /\$\(([a-z0-9-]+)(?:~[a-z]+)?\)/gi; + let last = 0; + for (const match of text.matchAll(pattern)) { + if (match.index > last) { + parts.push({ text: text.slice(last, match.index) }); + } + parts.push({ icon: match[1] as string }); + last = match.index + match[0].length; + } + if (last < text.length) { + parts.push({ text: text.slice(last) }); + } + return parts; +} + +/** + * The welcome content of an empty view: paragraphs, each either text with + * `[label](command:id)` / `[label](https://...)` links, or one link alone, + * which VS Code draws as a button. + */ +export type WelcomeLine = + | { readonly kind: 'button'; readonly label: string; readonly target: string } + | { readonly kind: 'text'; readonly parts: readonly ({ readonly text: string } | { readonly label: string; readonly target: string })[] }; + +export function parseWelcome(contents: string): WelcomeLine[] { + const lines: WelcomeLine[] = []; + for (const raw of contents.split(/\r?\n/)) { + const line = raw.trim(); + if (line === '') { + continue; + } + const alone = /^\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)$/.exec(line); + if (alone) { + lines.push({ kind: 'button', label: alone[1] as string, target: alone[2] as string }); + continue; + } + const parts: ({ readonly text: string } | { readonly label: string; readonly target: string })[] = []; + const pattern = /\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g; + let last = 0; + for (const match of line.matchAll(pattern)) { + if (match.index > last) { + parts.push({ text: line.slice(last, match.index) }); + } + parts.push({ label: match[1] as string, target: match[2] as string }); + last = match.index + match[0].length; + } + if (last < line.length) { + parts.push({ text: line.slice(last) }); + } + lines.push({ kind: 'text', parts }); + } + return lines; +} + +/** A `command:` link of welcome content: the command and its JSON arguments; null for any other target. */ +export function commandLink(target: string): { readonly command: string; readonly args: readonly unknown[] } | null { + if (!target.startsWith('command:')) { + return null; + } + const rest = target.slice('command:'.length); + const query = rest.indexOf('?'); + const command = query < 0 ? rest : rest.slice(0, query); + if (command === '') { + return null; + } + if (query < 0) { + return { command, args: [] }; + } + try { + const parsed: unknown = JSON.parse(decodeURIComponent(rest.slice(query + 1))); + return { command, args: Array.isArray(parsed) ? parsed : [parsed] }; + } catch { + return { command, args: [] }; + } +} + +const MAX_VIEW_ID = 256; +const MAX_HANDLE = 4096; + +function viewIdOk(value: unknown): value is string { + return typeof value === 'string' && value.length > 0 && value.length <= MAX_VIEW_ID; +} + +function handleOk(value: unknown): value is string { + return typeof value === 'string' && value.length > 0 && value.length <= MAX_HANDLE; +} + +/** A request from the renderer, checked field by field; null when anything is off. */ +export function parseViewRequest(raw: unknown): ViewRequest | null { + if (typeof raw !== 'object' || raw === null) { + return null; + } + const r = raw as Record; + if (!viewIdOk(r['viewId'])) { + return null; + } + const viewId = r['viewId']; + switch (r['kind']) { + case 'treeChildren': + return r['handle'] === null || handleOk(r['handle']) ? { kind: 'treeChildren', viewId, handle: r['handle'] as string | null } : null; + case 'treeClick': + return handleOk(r['handle']) ? { kind: 'treeClick', viewId, handle: r['handle'] } : null; + case 'treeCommand': { + const selected = r['selected']; + if (typeof r['command'] !== 'string' || r['command'] === '' || r['command'].length > 300 || !(r['handle'] === null || handleOk(r['handle'])) + || !Array.isArray(selected) || selected.length > MAX_VIEW_SELECTION || !selected.every(handleOk)) { + return null; + } + return { kind: 'treeCommand', viewId, command: r['command'], handle: r['handle'] as string | null, selected: selected as string[] }; + } + case 'treeExpand': + return handleOk(r['handle']) && typeof r['expanded'] === 'boolean' ? { kind: 'treeExpand', viewId, handle: r['handle'], expanded: r['expanded'] } : null; + case 'treeSelection': { + const handles = r['handles']; + return Array.isArray(handles) && handles.length <= MAX_VIEW_SELECTION && handles.every(handleOk) ? { kind: 'treeSelection', viewId, handles: handles as string[] } : null; + } + case 'treeCheckbox': + return handleOk(r['handle']) && typeof r['checked'] === 'boolean' ? { kind: 'treeCheckbox', viewId, handle: r['handle'], checked: r['checked'] } : null; + case 'viewVisibility': + return typeof r['visible'] === 'boolean' ? { kind: 'viewVisibility', viewId, visible: r['visible'] } : null; + default: + return null; + } +} diff --git a/apps/ide/src/shared/extensions.ts b/apps/ide/src/shared/extensions.ts index 8842a8f6..b9a2b9a6 100644 --- a/apps/ide/src/shared/extensions.ts +++ b/apps/ide/src/shared/extensions.ts @@ -11,6 +11,7 @@ import type { HostUiEvent } from './extensionHostProtocol.ts'; import type { DocumentEvent, ProvideRequest } from './extensionLanguageProtocol.ts'; +import type { IconData, ViewRequest } from './extensionViewsProtocol.ts'; /** `publisher.name`, lower-cased: VS Code compares extension ids without case. */ export type ExtensionId = string; @@ -223,6 +224,53 @@ export interface ContributedCommand { readonly category: string | null; /** `menus.commandPalette` hides it (`"when": "false"`): it runs, but the palette does not list it. */ readonly hiddenFromPalette: boolean; + /** #261: `menus.commandPalette`'s other `when` clause: the palette lists it only while that holds. */ + readonly paletteWhen: string | null; + /** #261: `enablement`: menus show it disabled while that does not hold. */ + readonly enablement: string | null; + /** #261: its icon, for menus that show icons (`view/title`, inline item actions, `editor/title`). */ + readonly icon: IconData | null; +} + +/** #261: `contributes.viewsContainers`: an activity bar item of its own (panel containers are shown there too). */ +export interface ContributedViewContainer { + readonly id: string; + readonly extensionId: ExtensionId; + readonly title: string; + readonly icon: IconData | null; +} + +/** #261: a view of `contributes.views`. */ +export interface ContributedView { + readonly id: string; + readonly extensionId: ExtensionId; + /** `explorer`, `scm`, `debug` or a contributed container's id. */ + readonly container: string; + readonly name: string; + readonly when: string | null; + readonly type: 'tree' | 'webview'; + /** `visibility: "collapsed"`: the section starts folded. */ + readonly collapsed: boolean; +} + +/** #261: `contributes.viewsWelcome`: what an empty view shows. */ +export interface ContributedViewWelcome { + readonly extensionId: ExtensionId; + readonly view: string; + readonly contents: string; + readonly when: string | null; +} + +/** #261: an entry of `contributes.menus`. */ +export interface ContributedMenuItem { + readonly extensionId: ExtensionId; + /** `view/title`, `view/item/context`, `editor/title`, `editor/context`, `explorer/context`, `editor/title/context`. */ + readonly menu: string; + readonly command: string; + readonly when: string | null; + /** `navigation`, `inline`, `1_modification@2`...: the part before `@` groups, the number orders. */ + readonly group: string; + readonly order: number; } /** Everything declarative the workbench applies from the enabled extensions. */ @@ -232,6 +280,11 @@ export interface ExtensionContributions { readonly grammars: readonly ContributedGrammar[]; readonly snippets: readonly ContributedSnippet[]; readonly commands: readonly ContributedCommand[]; + /** #261: views, their containers, their welcome content and the menus. */ + readonly viewContainers: readonly ContributedViewContainer[]; + readonly views: readonly ContributedView[]; + readonly viewsWelcome: readonly ContributedViewWelcome[]; + readonly menus: readonly ContributedMenuItem[]; } export interface ExtensionsChangedEvent { @@ -283,6 +336,8 @@ export interface ExtensionsApi { documentEvents(events: readonly DocumentEvent[]): Promise; /** #260: asks an extension's language feature provider; the answer is plain data (extensionLanguageProtocol.ts). */ provide(request: ProvideRequest): Promise; + /** #261: the extensions' views (tree children, clicks, menu commands, visibility); see extensionViewsProtocol.ts. */ + view(request: ViewRequest): Promise; } /** Activation events the renderer may fire (the others are the main process's or the host's own). */ @@ -311,6 +366,7 @@ export const EXTENSION_IPC_CHANNELS = { extensionsHostReply: 'codexr:extensions:host-reply', extensionsDocuments: 'codexr:extensions:documents', extensionsProvide: 'codexr:extensions:provide', + extensionsView: 'codexr:extensions:view', } as const; export const EXTENSION_IPC_EVENTS = { diff --git a/apps/ide/src/shared/whenClause.ts b/apps/ide/src/shared/whenClause.ts new file mode 100644 index 00000000..b4f9fd0a --- /dev/null +++ b/apps/ide/src/shared/whenClause.ts @@ -0,0 +1,328 @@ +/** + * #261: VS Code's `when` clauses, for the menus, views and welcome content + * extensions contribute. A clause is parsed once into a small tree and + * evaluated against a lookup of context keys (`view`, `viewItem`, + * `resourceLangId`, what extensions set with `setContext`, ...). The grammar + * is VS Code's: `!`, `&&`, `||`, parentheses, `==`/`!=` (and `===`/`!==`), + * `<`, `<=`, `>`, `>=`, `=~ /regex/flags`, `in` and `not in`; values are + * bare words or quoted strings, `true` and `false` are booleans. + * + * Evaluation never throws: an unparsable clause is false (the item stays + * hidden), as an unknown key is undefined (falsy). Pure: shared by main, the + * renderer and the unit tests. + */ + +export type WhenNode = + | { readonly kind: 'true' } + | { readonly kind: 'false' } + | { readonly kind: 'key'; readonly key: string } + | { readonly kind: 'not'; readonly operand: WhenNode } + | { readonly kind: 'and'; readonly operands: readonly WhenNode[] } + | { readonly kind: 'or'; readonly operands: readonly WhenNode[] } + | { readonly kind: 'compare'; readonly key: string; readonly op: '==' | '!=' | '<' | '<=' | '>' | '>='; readonly value: string | boolean | number } + | { readonly kind: 'regex'; readonly key: string; readonly regex: RegExp | null } + | { readonly kind: 'in'; readonly key: string; readonly container: string; readonly negated: boolean }; + +type Token = + | { readonly type: 'op'; readonly value: string } + | { readonly type: 'word'; readonly value: string } + | { readonly type: 'string'; readonly value: string } + | { readonly type: 'regex'; readonly value: string; readonly flags: string }; + +const OPERATORS = ['===', '!==', '==', '!=', '<=', '>=', '=~', '&&', '||', '<', '>', '!', '(', ')']; + +function tokenize(text: string): Token[] | null { + const tokens: Token[] = []; + let i = 0; + while (i < text.length) { + const char = text[i] as string; + if (/\s/.test(char)) { + i++; + continue; + } + if (char === "'" || char === '"') { + const end = text.indexOf(char, i + 1); + if (end < 0) { + return null; + } + tokens.push({ type: 'string', value: text.slice(i + 1, end) }); + i = end + 1; + continue; + } + // A regex only follows `=~`. + const previous = tokens[tokens.length - 1]; + if (char === '/' && previous?.type === 'op' && previous.value === '=~') { + let j = i + 1; + let inClass = false; + while (j < text.length) { + const c = text[j]; + if (c === '\\') { + j += 2; + continue; + } + if (c === '[') { + inClass = true; + } else if (c === ']') { + inClass = false; + } else if (c === '/' && !inClass) { + break; + } + j++; + } + if (j >= text.length) { + return null; + } + const flags = /^[a-z]*/.exec(text.slice(j + 1))?.[0] ?? ''; + tokens.push({ type: 'regex', value: text.slice(i + 1, j), flags }); + i = j + 1 + flags.length; + continue; + } + const op = OPERATORS.find((candidate) => text.startsWith(candidate, i)); + if (op) { + tokens.push({ type: 'op', value: op }); + i += op.length; + continue; + } + let j = i; + while (j < text.length && !/\s/.test(text[j] as string) && !OPERATORS.some((candidate) => text.startsWith(candidate, j) && candidate !== '!' ) && text[j] !== "'" && text[j] !== '"') { + j++; + } + // `!` inside a word (`a!b`) is not an operator, but `!` at its start is handled above. + if (j === i) { + return null; + } + tokens.push({ type: 'word', value: text.slice(i, j) }); + i = j; + } + return tokens; +} + +function literal(token: Token): string | boolean | number { + if (token.type === 'word') { + if (token.value === 'true') { + return true; + } + if (token.value === 'false') { + return false; + } + } + return token.value; +} + +/** Parses a clause; null when it does not parse. An empty clause is `true`. */ +export function parseWhen(text: string): WhenNode | null { + const tokenized = tokenize(text); + if (!tokenized) { + return null; + } + const tokens: Token[] = tokenized; + if (tokens.length === 0) { + return { kind: 'true' }; + } + let position = 0; + const peek = (): Token | undefined => tokens[position]; + const isOp = (value: string): boolean => { + const token = peek(); + return token?.type === 'op' && token.value === value; + }; + + function parseOr(): WhenNode | null { + const operands: WhenNode[] = []; + const first = parseAnd(); + if (!first) { + return null; + } + operands.push(first); + while (isOp('||')) { + position++; + const next = parseAnd(); + if (!next) { + return null; + } + operands.push(next); + } + return operands.length === 1 ? operands[0] as WhenNode : { kind: 'or', operands }; + } + + function parseAnd(): WhenNode | null { + const operands: WhenNode[] = []; + const first = parseUnary(); + if (!first) { + return null; + } + operands.push(first); + while (isOp('&&')) { + position++; + const next = parseUnary(); + if (!next) { + return null; + } + operands.push(next); + } + return operands.length === 1 ? operands[0] as WhenNode : { kind: 'and', operands }; + } + + function parseUnary(): WhenNode | null { + if (isOp('!')) { + position++; + const operand = parseUnary(); + return operand ? { kind: 'not', operand } : null; + } + return parsePrimary(); + } + + function parsePrimary(): WhenNode | null { + if (isOp('(')) { + position++; + const inner = parseOr(); + if (!inner || !isOp(')')) { + return null; + } + position++; + return inner; + } + const token = peek(); + if (!token || (token.type !== 'word' && token.type !== 'string')) { + return null; + } + position++; + if (token.type === 'word' && token.value === 'true') { + return { kind: 'true' }; + } + if (token.type === 'word' && token.value === 'false') { + return { kind: 'false' }; + } + const key = token.value; + const next = peek(); + if (next?.type === 'op') { + switch (next.value) { + case '==': case '===': case '!=': case '!==': case '<': case '<=': case '>': case '>=': { + position++; + const value = peek(); + if (!value || value.type === 'op' || value.type === 'regex') { + return null; + } + position++; + const op = next.value === '===' ? '==' : next.value === '!==' ? '!=' : next.value; + return { kind: 'compare', key, op, value: literal(value) }; + } + case '=~': { + position++; + const value = peek(); + if (!value) { + return null; + } + position++; + let regex: RegExp | null = null; + try { + regex = value.type === 'regex' ? new RegExp(value.value, value.flags.replace(/[^imsu]/g, '')) : new RegExp(value.value); + } catch { + regex = null; + } + return { kind: 'regex', key, regex }; + } + default: + break; + } + } + if (next?.type === 'word' && next.value === 'in') { + position++; + const container = peek(); + if (!container || container.type === 'op' || container.type === 'regex') { + return null; + } + position++; + return { kind: 'in', key, container: container.value, negated: false }; + } + if (next?.type === 'word' && next.value === 'not' && tokens[position + 1]?.type === 'word' && tokens[position + 1]?.value === 'in') { + position += 2; + const container = peek(); + if (!container || container.type === 'op' || container.type === 'regex') { + return null; + } + position++; + return { kind: 'in', key, container: container.value, negated: true }; + } + return { kind: 'key', key }; + } + + const node = parseOr(); + return node && position === tokens.length ? node : null; +} + +export type ContextLookup = (key: string) => unknown; + +function loosely(actual: unknown, expected: string | boolean | number): boolean { + if (typeof expected === 'boolean') { + return actual === expected || (typeof actual === 'string' && actual === String(expected)); + } + // eslint-disable-next-line eqeqeq -- VS Code compares context values loosely (a number key equals its string). + return actual == expected; +} + +export function evaluateWhen(node: WhenNode, lookup: ContextLookup): boolean { + switch (node.kind) { + case 'true': + return true; + case 'false': + return false; + case 'key': + return !!lookup(node.key); + case 'not': + return !evaluateWhen(node.operand, lookup); + case 'and': + return node.operands.every((operand) => evaluateWhen(operand, lookup)); + case 'or': + return node.operands.some((operand) => evaluateWhen(operand, lookup)); + case 'compare': { + const actual = lookup(node.key); + switch (node.op) { + case '==': + return loosely(actual, node.value); + case '!=': + return !loosely(actual, node.value); + default: { + const left = typeof actual === 'number' ? actual : Number.parseFloat(String(actual)); + const right = typeof node.value === 'number' ? node.value : Number.parseFloat(String(node.value)); + if (Number.isNaN(left) || Number.isNaN(right)) { + return false; + } + return node.op === '<' ? left < right : node.op === '<=' ? left <= right : node.op === '>' ? left > right : left >= right; + } + } + } + case 'regex': { + const actual = lookup(node.key); + return !!node.regex && actual !== undefined && actual !== null && node.regex.test(String(actual)); + } + case 'in': { + const item = lookup(node.key); + const container = lookup(node.container); + let found = false; + if (Array.isArray(container)) { + found = container.includes(item); + } else if (typeof container === 'object' && container !== null && typeof item === 'string') { + found = Object.prototype.hasOwnProperty.call(container, item); + } + return node.negated ? !found : found; + } + } +} + +const cache = new Map(); + +/** Whether `clause` holds; no clause holds, a clause that does not parse does not. */ +export function whenHolds(clause: string | null | undefined, lookup: ContextLookup): boolean { + if (clause === null || clause === undefined || clause.trim() === '') { + return true; + } + let node = cache.get(clause); + if (node === undefined) { + node = parseWhen(clause); + if (cache.size > 2000) { + cache.clear(); + } + cache.set(clause, node); + } + return node ? evaluateWhen(node, lookup) : false; +} diff --git a/apps/ide/test/extensionViews.test.ts b/apps/ide/test/extensionViews.test.ts new file mode 100644 index 00000000..098a49c7 --- /dev/null +++ b/apps/ide/test/extensionViews.test.ts @@ -0,0 +1,438 @@ +import { after, before, describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { fork, type ChildProcess } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { HOST_METHODS, MAIN_METHODS, RpcEndpoint, type HostInitData, type UiNotification } from '../src/shared/extensionHostProtocol.ts'; +import { codiconName, commandLink, parseViewRequest, parseWelcome, splitIcons, type TreeItemData, type ViewNotification } from '../src/shared/extensionViewsProtocol.ts'; +import type { ContributedCommand, ContributedMenuItem } from '../src/shared/extensions.ts'; +import { evaluateWhen, parseWhen, whenHolds } from '../src/shared/whenClause.ts'; +import { ContributionIndex, menuGroup } from '../src/main/extensions/contributions.ts'; +import type { ExtensionManifest } from '../src/main/extensions/manifest.ts'; +import type { LoadedExtension } from '../src/main/extensions/extensionStore.ts'; +import { inlineIcon, inlineTreeIcons } from '../src/main/extensions/viewIcons.ts'; +import { ContextKeys, platformContext } from '../src/renderer/extensions/contextKeys.ts'; +import { fileUriOf, guessLanguageId, menuGroups, resourceContext, splitActions } from '../src/renderer/extensions/menuModel.ts'; + +const HOST_ENTRY = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'src', 'extensionHost', 'index.ts'); + +let tmp = ''; +before(() => { + tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-views-test-'))); +}); +after(() => { + fs.rmSync(tmp, { recursive: true, force: true }); +}); + +describe('when clauses (#261)', () => { + const context: Record = { + view: 'npm.scripts', viewItem: 'script-debug', resourceLangId: 'typescript', count: 3, enabled: true, off: false, + list: ['a', 'b'], map: { x: 1 }, name: 'a', version: '1.2', empty: '', + }; + const holds = (clause: string): boolean => whenHolds(clause, (key) => context[key]); + + it('reads keys, negation, and/or with precedence and parentheses', () => { + assert.ok(holds('')); + assert.ok(holds('enabled')); + assert.ok(!holds('off')); + assert.ok(!holds('missing')); + assert.ok(holds('!missing')); + assert.ok(holds('enabled && !off')); + assert.ok(holds('off || enabled')); + assert.ok(holds('off && missing || enabled'), '&& binds tighter than ||'); + assert.ok(!holds('off && (missing || enabled)')); + assert.ok(holds('true') && !holds('false')); + }); + + it('compares, matches regexes and looks into arrays and objects', () => { + assert.ok(holds('view == npm.scripts')); + assert.ok(holds("view == 'npm.scripts'")); + assert.ok(holds('view === npm.scripts')); + assert.ok(holds('view != other')); + assert.ok(holds('enabled == true')); + assert.ok(holds('count == 3') && holds('count >= 3') && holds('count > 2') && !holds('count < 3')); + assert.ok(holds('version >= 1.1')); + assert.ok(holds('viewItem =~ /^script/')); + assert.ok(holds('viewItem =~ /DEBUG$/i')); + assert.ok(!holds('viewItem =~ /^folder/')); + assert.ok(holds('name in list') && !holds('name not in list')); + assert.ok(holds("'x' in map") === false, 'the left side of in is a key, not a literal'); + assert.ok(holds('view == npm.scripts && viewItem =~ /script/ && resourceLangId == typescript')); + }); + + it('treats a clause that does not parse as false', () => { + assert.equal(parseWhen('a &&'), null); + assert.equal(parseWhen('(a'), null); + assert.equal(parseWhen("a == 'open"), null); + assert.ok(!holds('a &&')); + assert.ok(!holds('viewItem =~ /[/'), 'an invalid regex matches nothing'); + const node = parseWhen('!(a || b)'); + assert.ok(node && evaluateWhen(node, () => undefined)); + }); +}); + +describe('views protocol helpers (#261)', () => { + it('checks every renderer request field by field', () => { + assert.deepEqual(parseViewRequest({ kind: 'treeChildren', viewId: 'v', handle: null }), { kind: 'treeChildren', viewId: 'v', handle: null }); + assert.deepEqual(parseViewRequest({ kind: 'treeCommand', viewId: 'v', command: 'c', handle: 'h', selected: ['h'] }), { kind: 'treeCommand', viewId: 'v', command: 'c', handle: 'h', selected: ['h'] }); + assert.equal(parseViewRequest({ kind: 'treeChildren', viewId: '', handle: null }), null); + assert.equal(parseViewRequest({ kind: 'treeClick', viewId: 'v', handle: 5 }), null); + assert.equal(parseViewRequest({ kind: 'treeCommand', viewId: 'v', command: 'c', handle: 'h', selected: [1] }), null); + assert.equal(parseViewRequest({ kind: 'treeSelection', viewId: 'v', handles: new Array(1001).fill('h') }), null); + assert.equal(parseViewRequest({ kind: 'viewVisibility', viewId: 'v', visible: 'yes' }), null); + assert.equal(parseViewRequest({ kind: 'nope', viewId: 'v' }), null); + assert.equal(parseViewRequest(null), null); + }); + + it('reads welcome content, command links and icon references', () => { + assert.deepEqual(parseWelcome('No scripts found.\n[Run Script](command:npm.runScript)\nRead [the docs](https://example.com) first.'), [ + { kind: 'text', parts: [{ text: 'No scripts found.' }] }, + { kind: 'button', label: 'Run Script', target: 'command:npm.runScript' }, + { kind: 'text', parts: [{ text: 'Read ' }, { label: 'the docs', target: 'https://example.com' }, { text: ' first.' }] }, + ]); + assert.deepEqual(commandLink('command:a.b'), { command: 'a.b', args: [] }); + assert.deepEqual(commandLink(`command:a.b?${encodeURIComponent(JSON.stringify(['x', 1]))}`), { command: 'a.b', args: ['x', 1] }); + assert.deepEqual(commandLink(`command:a.b?${encodeURIComponent('{"k":1}')}`), { command: 'a.b', args: [{ k: 1 }] }); + assert.equal(commandLink('https://x'), null); + assert.equal(codiconName('$(refresh)'), 'refresh'); + assert.equal(codiconName('$(sync~spin)'), 'sync'); + assert.equal(codiconName('icons/a.svg'), null); + assert.deepEqual(splitIcons('$(check) Done $(x)'), [{ icon: 'check' }, { text: ' Done ' }, { icon: 'x' }]); + }); +}); + +function fakeExtension(location: string, id: string, contributes: Record, main: string | null = 'index.js'): LoadedExtension { + const [publisher, name] = id.split('.') as [string, string]; + const manifest = { id, publisher, name, version: '1.0.0', displayName: name, description: '', engine: '^1.80.0', main, browser: null, icon: null, categories: [], license: null, repository: null, activationEvents: [], extensionDependencies: [], extensionPack: [], contributes, supportsUntrusted: false, raw: {} } satisfies ExtensionManifest; + return { manifest, location, record: {} as LoadedExtension['record'], enabled: true }; +} + +describe('view and menu contributions (#261)', () => { + it('reads view containers, views, welcome content and menus, with their icons', () => { + const location = path.join(tmp, 'acme.todo'); + fs.mkdirSync(path.join(location, 'media'), { recursive: true }); + fs.writeFileSync(path.join(location, 'media', 'todo.svg'), ''); + fs.writeFileSync(path.join(location, 'media', 'big.png'), Buffer.alloc(300 * 1024)); + const warnings: string[] = []; + const index = new ContributionIndex([fakeExtension(location, 'acme.todo', { + commands: [ + { command: 'todo.refresh', title: 'Refresh', icon: '$(refresh)' }, + { command: 'todo.open', title: { value: 'Open', original: 'Open' }, category: 'Todo', icon: { light: 'media/todo.svg', dark: 'media/todo.svg' }, enablement: 'todo.ready' }, + { command: 'todo.big', title: 'Big', icon: 'media/big.png' }, + { command: 'todo.hidden', title: 'Hidden' }, + ], + viewsContainers: { activitybar: [{ id: 'todo-tree', title: 'Todo', icon: 'media/todo.svg' }, { id: 'explorer', title: 'Bad' }], panel: [{ id: 'todo-panel', title: 'Todo Panel', icon: '$(checklist)' }] }, + views: { + 'todo-tree': [{ id: 'todo.list', name: 'Todos', when: 'todo.enabled' }, { id: 'todo.web', name: 'Web', type: 'webview', visibility: 'collapsed' }], + explorer: [{ id: 'todo.explorer', name: 'Todo Files' }], + 'nowhere-container': [{ id: 'todo.lost', name: 'Lost' }], + }, + viewsWelcome: [{ view: 'todo.list', contents: 'Nothing yet.\n[Scan](command:todo.refresh)', when: 'workspaceFolderCount > 0' }], + menus: { + commandPalette: [{ command: 'todo.hidden', when: 'false' }, { command: 'todo.open', when: 'todo.ready' }], + 'view/title': [{ command: 'todo.refresh', when: 'view == todo.list', group: 'navigation@2' }], + 'view/item/context': [{ command: 'todo.open', when: 'viewItem == file', group: 'inline' }, { submenu: 'todo.more', group: 'navigation' }], + 'scm/title': [{ command: 'todo.refresh' }], + }, + })], (message) => warnings.push(message)); + const c = index.contributions; + assert.deepEqual(c.viewContainers.map((container) => [container.id, container.title, container.icon?.kind]), [['todo-tree', 'Todo', 'image'], ['todo-panel', 'Todo Panel', 'codicon']]); + const svg = c.viewContainers[0]?.icon; + assert.ok(svg?.kind === 'image' && svg.light.startsWith('data:image/svg+xml;base64,'), 'icons reach the renderer as data URLs'); + assert.deepEqual(c.views.map((view) => [view.id, view.container, view.type, view.when, view.collapsed]), [ + ['todo.list', 'todo-tree', 'tree', 'todo.enabled', false], + ['todo.web', 'todo-tree', 'webview', null, true], + ['todo.explorer', 'explorer', 'tree', null, false], + ]); + assert.ok(warnings.some((warning) => warning.includes('"explorer"')), 'a container may not take a built-in id'); + assert.ok(warnings.some((warning) => warning.includes('todo.lost')), 'a view in an unknown container is reported'); + assert.deepEqual(c.viewsWelcome, [{ extensionId: 'acme.todo', view: 'todo.list', contents: 'Nothing yet.\n[Scan](command:todo.refresh)', when: 'workspaceFolderCount > 0' }]); + assert.deepEqual(c.menus.map((item) => [item.menu, item.command, item.group, item.order]), [['view/title', 'todo.refresh', 'navigation', 2], ['view/item/context', 'todo.open', 'inline', 0]]); + const byId = new Map(c.commands.map((command) => [command.command, command])); + assert.deepEqual(byId.get('todo.refresh')?.icon, { kind: 'codicon', name: 'refresh' }); + assert.equal(byId.get('todo.open')?.icon?.kind, 'image'); + assert.equal(byId.get('todo.open')?.enablement, 'todo.ready'); + assert.equal(byId.get('todo.open')?.paletteWhen, 'todo.ready'); + assert.equal(byId.get('todo.big')?.icon, null, 'an icon over the size limit is not inlined'); + assert.equal(byId.get('todo.hidden')?.hiddenFromPalette, true); + assert.deepEqual(menuGroup('1_edit@-3'), { group: '1_edit', order: -3 }); + assert.deepEqual(menuGroup(undefined), { group: '', order: 0 }); + }); + + it('does not read menus of an extension without code, nor an icon outside the extension', () => { + const location = path.join(tmp, 'acme.theme'); + fs.mkdirSync(location, { recursive: true }); + fs.writeFileSync(path.join(tmp, 'outside.svg'), ''); + const index = new ContributionIndex([fakeExtension(location, 'acme.theme', { + menus: { 'view/title': [{ command: 'x' }] }, + viewsContainers: { activitybar: [{ id: 'side', title: 'Side', icon: '../outside.svg' }] }, + views: { side: [{ id: 'side.view', name: 'Side view' }] }, + }, null)]); + assert.deepEqual(index.contributions.menus, []); + assert.equal(index.contributions.viewContainers[0]?.icon, null); + assert.equal(index.contributions.views.length, 1, 'a view needs no code (welcome content only)'); + }); +}); + +describe('tree icons from files (#261)', () => { + it('reads only images inside the allowed folders, as data URLs', () => { + const root = path.join(tmp, 'icons'); + fs.mkdirSync(root, { recursive: true }); + fs.writeFileSync(path.join(root, 'a.png'), Buffer.from([0x89, 0x50, 0x4e, 0x47])); + fs.writeFileSync(path.join(tmp, 'secret.png'), Buffer.from([1, 2, 3])); + fs.writeFileSync(path.join(root, 'notes.txt'), 'not an image'); + const cache = new Map(); + assert.deepEqual(inlineIcon({ kind: 'iconFile', file: path.join(root, 'a.png') }, [root], cache), { kind: 'image', light: 'data:image/png;base64,iVBORw==', dark: 'data:image/png;base64,iVBORw==' }); + assert.equal(inlineIcon({ kind: 'iconFile', file: path.join(tmp, 'secret.png') }, [root], cache), undefined, 'outside the roots'); + assert.equal(inlineIcon({ kind: 'iconFile', file: path.join(root, '..', 'secret.png') }, [root], cache), undefined, 'no climbing out'); + assert.equal(inlineIcon({ kind: 'iconFile', file: path.join(root, 'notes.txt') }, [root], cache), undefined, 'not an image type'); + assert.deepEqual(inlineIcon({ kind: 'codicon', name: 'x' }, [root], cache), { kind: 'codicon', name: 'x' }); + const result = inlineTreeIcons({ items: [{ handle: 'a', icon: { kind: 'iconFile', file: path.join(tmp, 'secret.png') } }, { handle: 'b', icon: { kind: 'iconFile', file: path.join(root, 'a.png') } }] }, [root], cache) as { items: TreeItemData[] }; + assert.equal(result.items[0]?.icon, undefined); + assert.equal(result.items[1]?.icon?.kind, 'image'); + }); +}); + +describe('menus and context keys in the workbench (#261)', () => { + const commands: ContributedCommand[] = [ + { extensionId: 'a.b', command: 'x.refresh', title: 'Refresh', category: null, hiddenFromPalette: false, paletteWhen: null, enablement: null, icon: { kind: 'codicon', name: 'refresh' } }, + { extensionId: 'a.b', command: 'x.delete', title: 'Delete', category: null, hiddenFromPalette: false, paletteWhen: null, enablement: 'canDelete', icon: null }, + { extensionId: 'a.b', command: 'x.rename', title: 'Rename', category: null, hiddenFromPalette: false, paletteWhen: null, enablement: null, icon: null }, + ]; + const item = (menu: string, command: string, group: string, order = 0, when: string | null = null, extensionId = 'a.b'): ContributedMenuItem => ({ extensionId, menu, command, when, group, order }); + + it('groups and orders a menu, keeping only what applies', () => { + const items = [ + item('view/item/context', 'x.delete', '9_cutcopypaste', 2), + item('view/item/context', 'x.rename', '9_cutcopypaste', 1), + item('view/item/context', 'x.refresh', 'inline', 0, 'viewItem == folder'), + item('view/item/context', 'x.refresh', 'navigation', 0, 'view == other'), + item('view/item/context', 'x.rename', 'navigation', 0, 'view == list'), + item('view/item/context', 'x.refresh', '', 0, null, 'off.ext'), + item('view/title', 'x.refresh', 'navigation'), + ]; + const keys = new ContextKeys(); + const groups = menuGroups('view/item/context', items, commands, keys.lookup({ view: 'list', viewItem: 'folder' }), (id) => id === 'a.b'); + assert.deepEqual(groups.map((group) => [group.group, group.actions.map((action) => action.command)]), [ + ['navigation', ['x.rename']], + ['inline', ['x.refresh']], + ['9_cutcopypaste', ['x.rename', 'x.delete']], + ]); + assert.equal(groups[2]?.actions[1]?.enabled, false, '`enablement` greys an entry out'); + keys.set('canDelete', true); + assert.equal(menuGroups('view/item/context', items, commands, keys.lookup({ view: 'list' }))[1]?.actions[1]?.enabled, true); + const { primary, secondary } = splitActions(groups, 'inline'); + assert.deepEqual(primary.map((action) => action.command), ['x.refresh']); + assert.deepEqual(secondary.map((group) => group.group), ['9_cutcopypaste']); + }); + + it('answers keys from setContext, the workbench providers, then the per-menu extras', async () => { + const keys = new ContextKeys(); + keys.addProvider(platformContext('win32')); + keys.addProvider((key) => (key === 'workspaceFolderCount' ? 1 : undefined)); + let heard = 0; + keys.onDidChange(() => heard++); + keys.set('todo.ready', true); + keys.set('todo.count', 3); + await Promise.resolve(); + assert.equal(heard, 1, 'changes in one task are heard once'); + const lookup = keys.lookup({ view: 'x' }); + assert.ok(whenHolds('isWindows && !isMac && workspaceFolderCount == 1 && todo.ready && todo.count > 2 && view == x', lookup)); + keys.set('todo.ready', undefined); + keys.clear(); + assert.ok(!whenHolds('todo.ready || todo.count', keys.lookup())); + }); + + it('describes a file for explorer and editor menus', () => { + assert.deepEqual(resourceContext('src/app.test.ts', 'typescript'), { + resource: 'src/app.test.ts', resourcePath: 'src/app.test.ts', resourceScheme: 'file', resourceFilename: 'app.test.ts', resourceDirname: 'src', + resourceExtname: '.ts', resourceLangId: 'typescript', explorerResourceIsFolder: false, + }); + assert.equal(guessLanguageId('docs/README.md'), 'markdown'); + assert.equal(guessLanguageId('Dockerfile'), 'dockerfile'); + assert.equal(guessLanguageId('a.unknown'), null); + assert.equal(fileUriOf('/home/me/ws', 'src/a b.ts'), 'file:///home/me/ws/src/a%20b.ts'); + assert.equal(fileUriOf('C:\\Users\\me\\ws\\', 'a#.ts'), 'file:///C:/Users/me/ws/a%23.ts'); + }); +}); + +const TREE_JS = ` +const vscode = require('vscode'); +const path = require('path'); +exports.activate = (context) => { + const changed = new vscode.EventEmitter(); + const data = { roots: ['alpha', 'beta'], children: { alpha: ['a1', 'a2'], beta: [] } }; + const calls = []; + const provider = { + onDidChangeTreeData: changed.event, + getChildren: (element) => (element ? data.children[element] || [] : data.roots), + getTreeItem: (element) => { + const isGroup = Array.isArray(data.children[element]); + const item = new vscode.TreeItem(element, isGroup ? vscode.TreeItemCollapsibleState.Collapsed : vscode.TreeItemCollapsibleState.None); + item.contextValue = isGroup ? 'group' : 'leaf'; + item.tooltip = new vscode.MarkdownString('**' + element + '**'); + if (element === 'alpha') { + item.iconPath = new vscode.ThemeIcon('beaker', new vscode.ThemeColor('charts.red')); + item.description = 'two items'; + } + if (element === 'a1') { + item.iconPath = vscode.Uri.file(path.join(__dirname, 'leaf.svg')); + item.command = { command: 'tree.open', title: 'Open', arguments: [element, 42] }; + } + if (element === 'a2') { + item.resourceUri = vscode.Uri.file(path.join(vscode.workspace.workspaceFolders[0].uri.fsPath, 'src', 'a2.ts')); + item.iconPath = vscode.ThemeIcon.File; + item.id = 'stable-a2'; + } + return item; + }, + getParent: (element) => (element === 'a1' || element === 'a2' ? 'alpha' : undefined), + }; + const view = vscode.window.createTreeView('acme.tree', { treeDataProvider: provider, showCollapseAll: true, canSelectMany: true }); + view.onDidChangeSelection((event) => calls.push(['selection', ...event.selection])); + view.onDidChangeVisibility((event) => calls.push(['visible', event.visible])); + view.onDidExpandElement((event) => calls.push(['expand', event.element])); + context.subscriptions.push( + view, + vscode.commands.registerCommand('tree.open', (...args) => calls.push(['open', ...args])), + vscode.commands.registerCommand('tree.remove', (element, all) => calls.push(['remove', element, all])), + vscode.commands.registerCommand('tree.calls', () => calls), + vscode.commands.registerCommand('tree.add', () => { data.roots.push('gamma'); changed.fire(); }), + vscode.commands.registerCommand('tree.touch', () => changed.fire('alpha')), + vscode.commands.registerCommand('tree.reveal', () => view.reveal('a2', { focus: true, select: true })), + vscode.commands.registerCommand('tree.meta', () => { view.title = 'Tasks'; view.message = 'Two left'; view.badge = { value: 2, tooltip: '2 tasks' }; }), + ); + vscode.window.registerTreeDataProvider('acme.second', { getChildren: () => [1, 2], getTreeItem: (n) => ({ label: 'n' + n }) }); +}; +`; + +describe('tree views in the extension host (#261)', () => { + let child: ChildProcess; + let main: RpcEndpoint; + let workspace = ''; + let extensionFolder = ''; + const views: ViewNotification[] = []; + + const waitFor = async (probe: () => T | undefined, what: string): Promise => { + for (let attempt = 0; attempt < 200; attempt++) { + const value = probe(); + if (value !== undefined) { + return value; + } + await new Promise((resolve) => setTimeout(resolve, 10)); + } + throw new Error(`Timed out waiting for ${what}`); + }; + const children = (viewId: string, handle: string | null): Promise<{ items: TreeItemData[] } | null> => main.request(HOST_METHODS.view, { kind: 'treeChildren', viewId, handle }); + const calls = (): Promise => main.request(HOST_METHODS.executeCommand, 'tree.calls', []); + + before(async () => { + workspace = path.join(tmp, 'tree-ws'); + fs.mkdirSync(path.join(workspace, 'src'), { recursive: true }); + extensionFolder = path.join(tmp, 'extensions', 'acme.tree-1.0.0'); + fs.mkdirSync(extensionFolder, { recursive: true }); + const packageJSON = { publisher: 'acme', name: 'tree', version: '1.0.0', main: 'index.js', engines: { vscode: '^1.80.0' }, activationEvents: ['onView:acme.tree'], contributes: { views: { explorer: [{ id: 'acme.tree', name: 'Tree' }] } } }; + fs.writeFileSync(path.join(extensionFolder, 'package.json'), JSON.stringify(packageJSON)); + fs.writeFileSync(path.join(extensionFolder, 'index.js'), TREE_JS); + + child = fork(HOST_ENTRY, [], { execArgv: ['--experimental-strip-types', '--no-warnings'], stdio: ['ignore', 'pipe', 'pipe', 'ipc'], serialization: 'advanced' }); + child.stderr?.on('data', (chunk: Buffer) => process.stderr.write(`[host stderr] ${chunk.toString()}`)); + main = new RpcEndpoint((message) => child.send(message)); + child.on('message', (message) => main.receive(message)); + main.handle(MAIN_METHODS.log, () => undefined); + main.handle(MAIN_METHODS.activation, () => undefined); + main.handle(MAIN_METHODS.notImplemented, () => undefined); + main.handle(MAIN_METHODS.uiNotify, (notification) => { + const typed = notification as UiNotification; + if (typed.kind === 'view') { + views.push(typed.notification); + } + }); + main.handle(MAIN_METHODS.ui, () => null); + const init: HostInitData = { + extensions: [{ id: 'acme.tree', location: extensionFolder, main: 'index.js', packageJSON, activationEvents: ['onView:acme.tree'], extensionDependencies: [] }], + passive: [], + workspaceFolder: workspace, + trusted: true, + configuration: {}, + globalStorageRoot: path.join(tmp, 'tree-storage'), + workspaceStorageRoot: null, + logRoot: path.join(tmp, 'tree-logs'), + env: { appName: 'Code-XR IDE', appRoot: tmp, appHost: 'desktop', language: 'en', machineId: 'm', sessionId: 's', uriScheme: 'codexr', shell: '/bin/sh', version: '0.0.0' }, + isDevelopment: false, + documents: [], + activeEditor: null, + }; + await main.request(HOST_METHODS.init, init); + }); + + after(() => { + if (child.exitCode === null) { + child.kill(); + } + }); + + it('activates the extension on onView when the view first asks for its roots, and announces the tree', async () => { + const roots = await children('acme.tree', null); + assert.deepEqual(roots?.items.map((item) => [item.label, item.collapsible, item.contextValue]), [['alpha', 1, 'group'], ['beta', 1, 'group']]); + const registered = views.find((notification) => notification.kind === 'treeRegistered' && notification.viewId === 'acme.tree'); + assert.deepEqual(registered, { kind: 'treeRegistered', viewId: 'acme.tree', extensionId: 'acme.tree', showCollapseAll: true, canSelectMany: true, manageCheckboxStateManually: false }); + assert.ok(views.some((notification) => notification.kind === 'treeRegistered' && notification.viewId === 'acme.second'), 'registerTreeDataProvider announces too'); + const alpha = roots?.items[0]; + assert.deepEqual(alpha?.icon, { kind: 'codicon', name: 'beaker', color: 'charts.red' }); + assert.equal(alpha?.description, 'two items'); + assert.equal(alpha?.tooltip, '**alpha**'); + }); + + it('gives children by handle, with file icons, resources and commands kept in the host', async () => { + const roots = await children('acme.tree', null); + const alpha = roots?.items[0] as TreeItemData; + const kids = await children('acme.tree', alpha.handle); + assert.deepEqual(kids?.items.map((item) => item.label), ['a1', 'a2']); + const [a1, a2] = kids?.items ?? []; + // Windows: the host spells the drive in lower case, as `Uri.fsPath` does. + assert.deepEqual(a1?.icon?.kind === 'iconFile' ? { ...a1.icon, file: a1.icon.file.toLowerCase() } : a1?.icon, { kind: 'iconFile', file: path.join(extensionFolder, 'leaf.svg').toLowerCase() }); + assert.equal(a1?.hasCommand, true); + assert.equal(a2?.handle, 'i:stable-a2', 'an item id is its handle'); + assert.deepEqual(a2?.icon, { kind: 'file' }); + assert.equal(a2?.resourceName, 'a2.ts'); + assert.equal(a2?.resource?.path.toLowerCase(), path.join(workspace, 'src', 'a2.ts').toLowerCase()); + assert.deepEqual(await children('acme.tree', 'no-such-handle'), { items: [] }); + assert.equal(await children('nobody.view', null), null, 'a view without a provider answers null'); + + await main.request(HOST_METHODS.view, { kind: 'treeClick', viewId: 'acme.tree', handle: a1?.handle }); + await main.request(HOST_METHODS.view, { kind: 'treeCommand', viewId: 'acme.tree', command: 'tree.remove', handle: a1?.handle, selected: [a1?.handle, a2?.handle] }); + await main.request(HOST_METHODS.view, { kind: 'treeSelection', viewId: 'acme.tree', handles: [a2?.handle] }); + await main.request(HOST_METHODS.view, { kind: 'treeExpand', viewId: 'acme.tree', handle: alpha.handle, expanded: true }); + await main.request(HOST_METHODS.view, { kind: 'viewVisibility', viewId: 'acme.tree', visible: true }); + assert.deepEqual(await calls(), [['open', 'a1', 42], ['remove', 'a1', ['a1', 'a2']], ['selection', 'a2'], ['expand', 'alpha'], ['visible', true]]); + }); + + it('keeps handles across refreshes and tells the workbench what changed', async () => { + const before = await children('acme.tree', null); + views.length = 0; + await main.request(HOST_METHODS.executeCommand, 'tree.add', []); + await main.request(HOST_METHODS.executeCommand, 'tree.touch', []); + assert.deepEqual(views, [{ kind: 'treeChanged', viewId: 'acme.tree', handles: null }, { kind: 'treeChanged', viewId: 'acme.tree', handles: [before?.items[0]?.handle] }]); + const after = await children('acme.tree', null); + assert.deepEqual(after?.items.map((item) => item.label), ['alpha', 'beta', 'gamma']); + assert.equal(after?.items[0]?.handle, before?.items[0]?.handle); + }); + + it('reveals through getParent, and passes title, message and badge', async () => { + views.length = 0; + await main.request(HOST_METHODS.executeCommand, 'tree.reveal', []); + await main.request(HOST_METHODS.executeCommand, 'tree.meta', []); + const roots = await children('acme.tree', null); + const reveal = await waitFor(() => views.find((notification) => notification.kind === 'treeReveal'), 'the reveal'); + assert.deepEqual(reveal, { kind: 'treeReveal', viewId: 'acme.tree', path: [roots?.items[0]?.handle, 'i:stable-a2'], select: true, focus: true, expand: 0 }); + const meta = views.filter((notification) => notification.kind === 'viewMeta'); + assert.deepEqual(meta, [ + { kind: 'viewMeta', viewId: 'acme.tree', title: 'Tasks' }, + { kind: 'viewMeta', viewId: 'acme.tree', message: 'Two left' }, + { kind: 'viewMeta', viewId: 'acme.tree', badge: { value: 2, tooltip: '2 tasks' } }, + ]); + }); +}); diff --git a/docs/ide/extensions.md b/docs/ide/extensions.md index 288f900d..efc38d4a 100644 --- a/docs/ide/extensions.md +++ b/docs/ide/extensions.md @@ -13,7 +13,8 @@ Epic #251. Decision: [ADR 0002](../../adr/0002-vscode-extensions-in-the-ide.md). | Languages, `language-configuration.json`, TextMate grammars (with injections and embedded languages), snippets | Done | #258 | | Extensions with code: the extension host, commands in the palette, messages, quick picks and input boxes, progress, status bar items, output channels, configuration, state and secrets, files and `findFiles` | Done | #259 | | Documents of the editor, the active editor, diagnostics, language features (completion, hover, definitions, references, symbols, signature help, formatting, code actions, code lenses, rename, folding, inlay hints, links), `applyEdit`, language clients (`vscode-languageclient`) | Done | #260 | -| Tree views, view containers, webviews | Planned | #261 | +| Tree views, view containers, `viewsWelcome`, menus (`view/title`, `view/item/context`, `editor/title`, `editor/context`, `explorer/context`), `when` clauses and `setContext` | Done | #261 | +| Webviews (panels and webview views) | Planned | #261 | | The Code-XR extension itself | Planned | #262 | | File icon themes, product icon themes | Not yet: listed in the details page | — | | Language packs | Install, no visible effect (the IDE does not use VS Code's UI strings) | #264 | @@ -82,6 +83,16 @@ Monaco model (codexr-file:/src/a.py) main process exte - **Paths.** The renderer only ever names workspace paths; the main process turns them into absolute paths for the host and every `path` in the host's answers back, dropping whatever points outside the folder. - **Not yet.** Decorations (`setDecorations`), semantic tokens (the TextMate grammars colour the code), call and type hierarchies, inline completions, colour pickers, selection ranges, linked editing and workspace symbols are accepted and reported in the *Extensions* output as missing; `when` clauses do not filter code actions. +## Views, menus and `when` clauses (#261) + +- **View containers.** `viewsContainers.activitybar` and `.panel` add an item to the activity bar (before Settings) with the container's icon drawn in the workbench's colour; views placed in `explorer`, `scm` or `debug` appear as sections under the IDE's own pane. A view in an unknown container is dropped with a warning in the *Extensions* output. +- **Tree views.** `window.createTreeView` and `registerTreeDataProvider`: lazy children, `TreeItem` labels with highlights, descriptions, tooltips, icons (`ThemeIcon` codicons with theme colours, files and `{ light, dark }` images, `resourceUri` file and folder icons), checkboxes, `canSelectMany`, `reveal`, `onDidChangeTreeData` (whole tree or some elements), `onDidChangeSelection`/`Visibility`/`ExpandElement`/`CollapseElement`, `title`, `description`, `message` and `badge` (shown on the activity item), and `resolveTreeItem`. Elements stay in the host: the workbench only sees opaque handles and plain data. Icon files are inlined by the main process as data URLs, and only from an enabled extension's folder or the workspace (at most 256 KB each). +- **Welcome content.** `viewsWelcome` shows when a view has no items and its `when` holds; `[label](command:id)` lines are buttons, links in text open http(s) outside after the usual check. +- **Menus.** `view/title` (the `navigation` group as buttons, the rest in a `...` menu, plus *Collapse All* when asked), `view/item/context` (`inline` as row buttons, the rest on right click; `viewItem` is the item's `contextValue`), `editor/title` (buttons beside the tabs), `editor/title/context`, `editor/context` (Monaco's context menu) and `explorer/context`. The command's `enablement` greys an entry out; `commandPalette` entries hide a command from the palette when their `when` does not hold. Submenus are not supported yet. +- **`when` clauses.** VS Code's grammar (`!`, `&&`, `||`, parentheses, `==`, `!=`, `<`, `<=`, `>`, `>=`, `=~ /regex/`, `in`, `not in`) over the keys of `setContext` and the workbench's own: `view`, `viewItem`, `focusedView`, `resource*` (`resourceFilename`, `resourceExtname`, `resourceLangId`...), `explorerResourceIsFolder`, `editorLangId`, `activeEditor`, `isWorkspaceTrusted`, `workspaceFolderCount`, `workbenchState`, `isLinux`/`isMac`/`isWindows`, `config.`. An unparsable clause hides its entry. +- **Commands.** `.focus`, `workbench.view.extension.` and `workbench.actions.treeView..collapseAll`/`.refresh` work through `executeCommand`. +- Checked with a sample extension: a container with two views (one gated on a `setContext` key, one placed in the explorer), welcome content, every supported menu, inline actions that edit the file and refresh the tree. + ## Security - CSP: `script-src 'self' 'wasm-unsafe-eval'` (WebAssembly only; `eval` and `new Function` stay blocked, which the smoke run checks).