Path: blob/main/src/vs/workbench/common/contextkeys.ts
5241 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45import { DisposableStore } from '../../base/common/lifecycle.js';6import { URI } from '../../base/common/uri.js';7import { localize } from '../../nls.js';8import { IContextKeyService, IContextKey, RawContextKey } from '../../platform/contextkey/common/contextkey.js';9import { basename, dirname, extname, isEqual } from '../../base/common/resources.js';10import { ILanguageService } from '../../editor/common/languages/language.js';11import { IFileService } from '../../platform/files/common/files.js';12import { IModelService } from '../../editor/common/services/model.js';13import { Schemas } from '../../base/common/network.js';14import { EditorInput } from './editor/editorInput.js';15import { IEditorResolverService } from '../services/editor/common/editorResolverService.js';16import { DEFAULT_EDITOR_ASSOCIATION } from './editor.js';17import { DiffEditorInput } from './editor/diffEditorInput.js';1819//#region < --- Workbench --- >2021export const WorkbenchStateContext = new RawContextKey<string>('workbenchState', undefined, { type: 'string', description: localize('workbenchState', "The kind of workspace opened in the window, either 'empty' (no workspace), 'folder' (single folder) or 'workspace' (multi-root workspace)") });22export const WorkspaceFolderCountContext = new RawContextKey<number>('workspaceFolderCount', 0, localize('workspaceFolderCount', "The number of root folders in the workspace"));2324export const OpenFolderWorkspaceSupportContext = new RawContextKey<boolean>('openFolderWorkspaceSupport', true, true);25export const EnterMultiRootWorkspaceSupportContext = new RawContextKey<boolean>('enterMultiRootWorkspaceSupport', true, true);26export const EmptyWorkspaceSupportContext = new RawContextKey<boolean>('emptyWorkspaceSupport', true, true);2728export const DirtyWorkingCopiesContext = new RawContextKey<boolean>('dirtyWorkingCopies', false, localize('dirtyWorkingCopies', "Whether there are any working copies with unsaved changes"));2930export const RemoteNameContext = new RawContextKey<string>('remoteName', '', localize('remoteName', "The name of the remote the window is connected to or an empty string if not connected to any remote"));3132export const VirtualWorkspaceContext = new RawContextKey<string>('virtualWorkspace', '', localize('virtualWorkspace', "The scheme of the current workspace is from a virtual file system or an empty string."));33export const TemporaryWorkspaceContext = new RawContextKey<boolean>('temporaryWorkspace', false, localize('temporaryWorkspace', "The scheme of the current workspace is from a temporary file system."));3435export const IsAgentSessionsWorkspaceContext = new RawContextKey<boolean>('isAgentSessionsWorkspace', false, localize('isAgentSessionsWorkspace', "Whether the current workspace is the agent sessions workspace."));3637export const WorkbenchModeContext = new RawContextKey<string>('workbenchMode', '', localize('workbenchMode', "The current workbench mode."));3839export const HasWebFileSystemAccess = new RawContextKey<boolean>('hasWebFileSystemAccess', false, true); // Support for FileSystemAccess web APIs (https://wicg.github.io/file-system-access)4041export const EmbedderIdentifierContext = new RawContextKey<string | undefined>('embedderIdentifier', undefined, localize('embedderIdentifier', 'The identifier of the embedder according to the product service, if one is defined'));4243export const InAutomationContext = new RawContextKey<boolean>('inAutomation', false, localize('inAutomation', "Whether VS Code is running under automation/smoke test"));4445//#endregion4647//#region < --- Window --- >4849export const IsMainWindowFullscreenContext = new RawContextKey<boolean>('isFullscreen', false, localize('isFullscreen', "Whether the main window is in fullscreen mode"));50export const IsAuxiliaryWindowFocusedContext = new RawContextKey<boolean>('isAuxiliaryWindowFocusedContext', false, localize('isAuxiliaryWindowFocusedContext', "Whether an auxiliary window is focused"));5152export const IsWindowAlwaysOnTopContext = new RawContextKey<boolean>('isWindowAlwaysOnTop', false, localize('isWindowAlwaysOnTop', "Whether the window is always on top"));5354export const IsAuxiliaryWindowContext = new RawContextKey<boolean>('isAuxiliaryWindow', false, localize('isAuxiliaryWindow', "Window is an auxiliary window"));555657//#endregion585960//#region < --- Editor --- >6162// Editor State Context Keys63export const ActiveEditorDirtyContext = new RawContextKey<boolean>('activeEditorIsDirty', false, localize('activeEditorIsDirty', "Whether the active editor has unsaved changes"));64export const ActiveEditorPinnedContext = new RawContextKey<boolean>('activeEditorIsNotPreview', false, localize('activeEditorIsNotPreview', "Whether the active editor is not in preview mode"));65export const ActiveEditorFirstInGroupContext = new RawContextKey<boolean>('activeEditorIsFirstInGroup', false, localize('activeEditorIsFirstInGroup', "Whether the active editor is the first one in its group"));66export const ActiveEditorLastInGroupContext = new RawContextKey<boolean>('activeEditorIsLastInGroup', false, localize('activeEditorIsLastInGroup', "Whether the active editor is the last one in its group"));67export const ActiveEditorStickyContext = new RawContextKey<boolean>('activeEditorIsPinned', false, localize('activeEditorIsPinned', "Whether the active editor is pinned"));68export const ActiveEditorReadonlyContext = new RawContextKey<boolean>('activeEditorIsReadonly', false, localize('activeEditorIsReadonly', "Whether the active editor is read-only"));69export const ActiveCompareEditorCanSwapContext = new RawContextKey<boolean>('activeCompareEditorCanSwap', false, localize('activeCompareEditorCanSwap', "Whether the active compare editor can swap sides"));70export const ActiveEditorCanToggleReadonlyContext = new RawContextKey<boolean>('activeEditorCanToggleReadonly', true, localize('activeEditorCanToggleReadonly', "Whether the active editor can toggle between being read-only or writeable"));71export const ActiveEditorCanRevertContext = new RawContextKey<boolean>('activeEditorCanRevert', false, localize('activeEditorCanRevert', "Whether the active editor can revert"));72export const ActiveEditorCanSplitInGroupContext = new RawContextKey<boolean>('activeEditorCanSplitInGroup', true);7374// Editor Kind Context Keys75export const ActiveEditorContext = new RawContextKey<string | null>('activeEditor', null, { type: 'string', description: localize('activeEditor', "The identifier of the active editor") });76export const ActiveEditorAvailableEditorIdsContext = new RawContextKey<string>('activeEditorAvailableEditorIds', '', localize('activeEditorAvailableEditorIds', "The available editor identifiers that are usable for the active editor"));77export const TextCompareEditorVisibleContext = new RawContextKey<boolean>('textCompareEditorVisible', false, localize('textCompareEditorVisible', "Whether a text compare editor is visible"));78export const TextCompareEditorActiveContext = new RawContextKey<boolean>('textCompareEditorActive', false, localize('textCompareEditorActive', "Whether a text compare editor is active"));79export const SideBySideEditorActiveContext = new RawContextKey<boolean>('sideBySideEditorActive', false, localize('sideBySideEditorActive', "Whether a side by side editor is active"));8081// Editor Group Context Keys82export const EditorGroupEditorsCountContext = new RawContextKey<number>('groupEditorsCount', 0, localize('groupEditorsCount', "The number of opened editor groups"));83export const ActiveEditorGroupEmptyContext = new RawContextKey<boolean>('activeEditorGroupEmpty', false, localize('activeEditorGroupEmpty', "Whether the active editor group is empty"));84export const ActiveEditorGroupIndexContext = new RawContextKey<number>('activeEditorGroupIndex', 0, localize('activeEditorGroupIndex', "The index of the active editor group"));85export const ActiveEditorGroupLastContext = new RawContextKey<boolean>('activeEditorGroupLast', false, localize('activeEditorGroupLast', "Whether the active editor group is the last group"));86export const ActiveEditorGroupLockedContext = new RawContextKey<boolean>('activeEditorGroupLocked', false, localize('activeEditorGroupLocked', "Whether the active editor group is locked"));87export const MultipleEditorGroupsContext = new RawContextKey<boolean>('multipleEditorGroups', false, localize('multipleEditorGroups', "Whether there are multiple editor groups opened"));88export const SingleEditorGroupsContext = MultipleEditorGroupsContext.toNegated();89export const MultipleEditorsSelectedInGroupContext = new RawContextKey<boolean>('multipleEditorsSelectedInGroup', false, localize('multipleEditorsSelectedInGroup', "Whether multiple editors have been selected in an editor group"));90export const TwoEditorsSelectedInGroupContext = new RawContextKey<boolean>('twoEditorsSelectedInGroup', false, localize('twoEditorsSelectedInGroup', "Whether exactly two editors have been selected in an editor group"));91export const SelectedEditorsInGroupFileOrUntitledResourceContextKey = new RawContextKey<boolean>('SelectedEditorsInGroupFileOrUntitledResourceContextKey', true, localize('SelectedEditorsInGroupFileOrUntitledResourceContextKey', "Whether all selected editors in a group have a file or untitled resource associated"));9293// Editor Part Context Keys94export const EditorPartMultipleEditorGroupsContext = new RawContextKey<boolean>('editorPartMultipleEditorGroups', false, localize('editorPartMultipleEditorGroups', "Whether there are multiple editor groups opened in an editor part"));95export const EditorPartSingleEditorGroupsContext = EditorPartMultipleEditorGroupsContext.toNegated();96export const EditorPartMaximizedEditorGroupContext = new RawContextKey<boolean>('editorPartMaximizedEditorGroup', false, localize('editorPartEditorGroupMaximized', "Editor Part has a maximized group"));97export const EditorPartModalContext = new RawContextKey<boolean>('editorPartModal', false, localize('editorPartModal', "Whether focus is in a modal editor part"));9899// Editor Layout Context Keys100export const EditorsVisibleContext = new RawContextKey<boolean>('editorIsOpen', false, localize('editorIsOpen', "Whether an editor is open"));101export const InEditorZenModeContext = new RawContextKey<boolean>('inZenMode', false, localize('inZenMode', "Whether Zen mode is enabled"));102export const IsMainEditorCenteredLayoutContext = new RawContextKey<boolean>('isCenteredLayout', false, localize('isMainEditorCenteredLayout', "Whether centered layout is enabled for the main editor"));103export const SplitEditorsVertically = new RawContextKey<boolean>('splitEditorsVertically', false, localize('splitEditorsVertically', "Whether editors split vertically"));104export const MainEditorAreaVisibleContext = new RawContextKey<boolean>('mainEditorAreaVisible', true, localize('mainEditorAreaVisible', "Whether the editor area in the main window is visible"));105export const EditorTabsVisibleContext = new RawContextKey<boolean>('editorTabsVisible', true, localize('editorTabsVisible', "Whether editor tabs are visible"));106107//#endregion108109110//#region < --- Side Bar --- >111112export const SideBarVisibleContext = new RawContextKey<boolean>('sideBarVisible', false, localize('sideBarVisible', "Whether the sidebar is visible"));113export const SidebarFocusContext = new RawContextKey<boolean>('sideBarFocus', false, localize('sideBarFocus', "Whether the sidebar has keyboard focus"));114export const ActiveViewletContext = new RawContextKey<string>('activeViewlet', '', localize('activeViewlet', "The identifier of the active viewlet"));115116//#endregion117118119//#region < --- Status Bar --- >120121export const StatusBarFocused = new RawContextKey<boolean>('statusBarFocused', false, localize('statusBarFocused', "Whether the status bar has keyboard focus"));122123//#endregion124125//#region < --- Title Bar --- >126127export const TitleBarStyleContext = new RawContextKey<string>('titleBarStyle', 'custom', localize('titleBarStyle', "Style of the window title bar"));128export const TitleBarVisibleContext = new RawContextKey<boolean>('titleBarVisible', false, localize('titleBarVisible', "Whether the title bar is visible"));129export const IsCompactTitleBarContext = new RawContextKey<boolean>('isCompactTitleBar', false, localize('isCompactTitleBar', "Title bar is in compact mode"));130131//#endregion132133134//#region < --- Banner --- >135136export const BannerFocused = new RawContextKey<boolean>('bannerFocused', false, localize('bannerFocused', "Whether the banner has keyboard focus"));137138//#endregion139140141//#region < --- Notifications --- >142143export const NotificationFocusedContext = new RawContextKey<boolean>('notificationFocus', true, localize('notificationFocus', "Whether a notification has keyboard focus"));144export const NotificationsCenterVisibleContext = new RawContextKey<boolean>('notificationCenterVisible', false, localize('notificationCenterVisible', "Whether the notifications center is visible"));145export const NotificationsToastsVisibleContext = new RawContextKey<boolean>('notificationToastsVisible', false, localize('notificationToastsVisible', "Whether a notification toast is visible"));146147//#endregion148149150//#region < --- Auxiliary Bar --- >151152export const ActiveAuxiliaryContext = new RawContextKey<string>('activeAuxiliary', '', localize('activeAuxiliary', "The identifier of the active auxiliary panel"));153export const AuxiliaryBarFocusContext = new RawContextKey<boolean>('auxiliaryBarFocus', false, localize('auxiliaryBarFocus', "Whether the auxiliary bar has keyboard focus"));154export const AuxiliaryBarVisibleContext = new RawContextKey<boolean>('auxiliaryBarVisible', false, localize('auxiliaryBarVisible', "Whether the auxiliary bar is visible"));155export const AuxiliaryBarMaximizedContext = new RawContextKey<boolean>('auxiliaryBarMaximized', false, localize('auxiliaryBarMaximized', "Whether the auxiliary bar is maximized"));156157//#endregion158159160//#region < --- Panel --- >161162export const ActivePanelContext = new RawContextKey<string>('activePanel', '', localize('activePanel', "The identifier of the active panel"));163export const PanelFocusContext = new RawContextKey<boolean>('panelFocus', false, localize('panelFocus', "Whether the panel has keyboard focus"));164export const PanelPositionContext = new RawContextKey<string>('panelPosition', 'bottom', localize('panelPosition', "The position of the panel, always 'bottom'"));165export const PanelAlignmentContext = new RawContextKey<string>('panelAlignment', 'center', localize('panelAlignment', "The alignment of the panel, either 'center', 'left', 'right' or 'justify'"));166export const PanelVisibleContext = new RawContextKey<boolean>('panelVisible', false, localize('panelVisible', "Whether the panel is visible"));167export const PanelMaximizedContext = new RawContextKey<boolean>('panelMaximized', false, localize('panelMaximized', "Whether the panel is maximized"));168169//#endregion170171172//#region < --- Views --- >173174export const FocusedViewContext = new RawContextKey<string>('focusedView', '', localize('focusedView', "The identifier of the view that has keyboard focus"));175export function getVisbileViewContextKey(viewId: string): string { return `view.${viewId}.visible`; }176177//#endregion178179180//#region < --- Resources --- >181182abstract class AbstractResourceContextKey {183184// NOTE: DO NOT CHANGE THE DEFAULT VALUE TO ANYTHING BUT185// UNDEFINED! IT IS IMPORTANT THAT DEFAULTS ARE INHERITED186// FROM THE PARENT CONTEXT AND ONLY UNDEFINED DOES THIS187188static readonly Scheme = new RawContextKey<string>('resourceScheme', undefined, { type: 'string', description: localize('resourceScheme', "The scheme of the resource") });189static readonly Filename = new RawContextKey<string>('resourceFilename', undefined, { type: 'string', description: localize('resourceFilename', "The file name of the resource") });190static readonly Dirname = new RawContextKey<string>('resourceDirname', undefined, { type: 'string', description: localize('resourceDirname', "The folder name the resource is contained in") });191static readonly Path = new RawContextKey<string>('resourcePath', undefined, { type: 'string', description: localize('resourcePath', "The full path of the resource") });192static readonly LangId = new RawContextKey<string>('resourceLangId', undefined, { type: 'string', description: localize('resourceLangId', "The language identifier of the resource") });193static readonly Resource = new RawContextKey<string>('resource', undefined, { type: 'URI', description: localize('resource', "The full value of the resource including scheme and path") });194static readonly Extension = new RawContextKey<string>('resourceExtname', undefined, { type: 'string', description: localize('resourceExtname', "The extension name of the resource") });195static readonly HasResource = new RawContextKey<boolean>('resourceSet', undefined, { type: 'boolean', description: localize('resourceSet', "Whether a resource is present or not") });196static readonly IsFileSystemResource = new RawContextKey<boolean>('isFileSystemResource', undefined, { type: 'boolean', description: localize('isFileSystemResource', "Whether the resource is backed by a file system provider") });197198protected _value: URI | undefined;199protected readonly _resourceKey: IContextKey<string | null>;200protected readonly _schemeKey: IContextKey<string | null>;201protected readonly _filenameKey: IContextKey<string | null>;202protected readonly _dirnameKey: IContextKey<string | null>;203protected readonly _pathKey: IContextKey<string | null>;204protected readonly _langIdKey: IContextKey<string | null>;205protected readonly _extensionKey: IContextKey<string | null>;206protected readonly _hasResource: IContextKey<boolean>;207protected readonly _isFileSystemResource: IContextKey<boolean>;208209constructor(210@IContextKeyService protected readonly _contextKeyService: IContextKeyService,211@IFileService protected readonly _fileService: IFileService,212@ILanguageService protected readonly _languageService: ILanguageService,213@IModelService protected readonly _modelService: IModelService214) {215this._schemeKey = AbstractResourceContextKey.Scheme.bindTo(this._contextKeyService);216this._filenameKey = AbstractResourceContextKey.Filename.bindTo(this._contextKeyService);217this._dirnameKey = AbstractResourceContextKey.Dirname.bindTo(this._contextKeyService);218this._pathKey = AbstractResourceContextKey.Path.bindTo(this._contextKeyService);219this._langIdKey = AbstractResourceContextKey.LangId.bindTo(this._contextKeyService);220this._resourceKey = AbstractResourceContextKey.Resource.bindTo(this._contextKeyService);221this._extensionKey = AbstractResourceContextKey.Extension.bindTo(this._contextKeyService);222this._hasResource = AbstractResourceContextKey.HasResource.bindTo(this._contextKeyService);223this._isFileSystemResource = AbstractResourceContextKey.IsFileSystemResource.bindTo(this._contextKeyService);224}225226protected _setLangId(): void {227const value = this.get();228if (!value) {229this._langIdKey.set(null);230return;231}232const langId = this._modelService.getModel(value)?.getLanguageId() ?? this._languageService.guessLanguageIdByFilepathOrFirstLine(value);233this._langIdKey.set(langId);234}235236set(value: URI | null | undefined) {237value = value ?? undefined;238if (isEqual(this._value, value)) {239return;240}241this._value = value;242this._contextKeyService.bufferChangeEvents(() => {243this._resourceKey.set(value ? value.toString() : null);244this._schemeKey.set(value ? value.scheme : null);245this._filenameKey.set(value ? basename(value) : null);246this._dirnameKey.set(value ? this.uriToPath(dirname(value)) : null);247this._pathKey.set(value ? this.uriToPath(value) : null);248this._setLangId();249this._extensionKey.set(value ? extname(value) : null);250this._hasResource.set(Boolean(value));251this._isFileSystemResource.set(value ? this._fileService.hasProvider(value) : false);252});253}254255protected uriToPath(uri: URI): string {256if (uri.scheme === Schemas.file) {257return uri.fsPath;258}259return uri.path;260}261262reset(): void {263this._value = undefined;264this._contextKeyService.bufferChangeEvents(() => {265this._resourceKey.reset();266this._schemeKey.reset();267this._filenameKey.reset();268this._dirnameKey.reset();269this._pathKey.reset();270this._langIdKey.reset();271this._extensionKey.reset();272this._hasResource.reset();273this._isFileSystemResource.reset();274});275}276277get(): URI | undefined {278return this._value;279}280}281282export class ResourceContextKey extends AbstractResourceContextKey {283284private readonly _disposables = new DisposableStore();285286constructor(287@IContextKeyService contextKeyService: IContextKeyService,288@IFileService fileService: IFileService,289@ILanguageService languageService: ILanguageService,290@IModelService modelService: IModelService291) {292super(contextKeyService, fileService, languageService, modelService);293this._disposables.add(fileService.onDidChangeFileSystemProviderRegistrations(() => {294const resource = this.get();295this._isFileSystemResource.set(Boolean(resource && fileService.hasProvider(resource)));296}));297this._disposables.add(modelService.onModelAdded(model => {298if (isEqual(model.uri, this.get())) {299this._setLangId();300}301}));302this._disposables.add(modelService.onModelLanguageChanged(e => {303if (isEqual(e.model.uri, this.get())) {304this._setLangId();305}306}));307}308309dispose(): void {310this._disposables.dispose();311}312}313314/**315* This is a version of ResourceContextKey that is not disposable and has no listeners for model change events.316* It will configure itself for the state/presence of a model only when created and not update.317*/318export class StaticResourceContextKey extends AbstractResourceContextKey { }319320321//#endregion322323export function applyAvailableEditorIds(contextKey: IContextKey<string>, editor: EditorInput | undefined | null, editorResolverService: IEditorResolverService): void {324if (!editor) {325contextKey.set('');326return;327}328329const editors = getAvailableEditorIds(editor, editorResolverService);330contextKey.set(editors.join(','));331}332333function getAvailableEditorIds(editor: EditorInput, editorResolverService: IEditorResolverService): string[] {334// Non text editor untitled files cannot be easily serialized between335// extensions so instead we disable this context key to prevent common336// commands that act on the active editor.337if (editor.resource?.scheme === Schemas.untitled && editor.editorId !== DEFAULT_EDITOR_ASSOCIATION.id) {338return [];339}340341// Diff editors. The original and modified resources of a diff editor342// *should* be the same, but calculate the set intersection just to be safe.343if (editor instanceof DiffEditorInput) {344const original = getAvailableEditorIds(editor.original, editorResolverService);345const modified = new Set(getAvailableEditorIds(editor.modified, editorResolverService));346return original.filter(editor => modified.has(editor));347}348349// Normal editors.350if (editor.resource) {351return editorResolverService.getEditors(editor.resource).map(editor => editor.id);352}353354return [];355}356357358