hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
listlengths
5
5
{ "id": 1, "code_window": [ "import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput';\n", "import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';\n", "import { IWorkspaceContextService, IWorkspaceFolder, WorkbenchState } from 'vs/platform/workspace/common/workspace';\n", "import { IWorkspaceTrustRequestService } from 'vs/platform/workspace/common/workspaceTrust';\n", "import { EditorInput } from 'vs/workbench/common/editor/editorInput';\n", "import { IViewDescriptorService, IViewsService, ViewContainerLocation } from 'vs/workbench/common/views';\n", "import { AdapterManager } from 'vs/workbench/contrib/debug/browser/debugAdapterManager';\n", "import { DEBUG_CONFIGURE_COMMAND_ID, DEBUG_CONFIGURE_LABEL } from 'vs/workbench/contrib/debug/browser/debugCommands';\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { EditorsOrder } from 'vs/workbench/common/editor';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "add", "edit_start_line_idx": 33 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { registerMainProcessRemoteService } from 'vs/platform/ipc/electron-sandbox/services'; import { Registry } from 'vs/platform/registry/common/platform'; import { ILocalPtyService, TerminalIpcChannels } from 'vs/platform/terminal/common/terminal'; import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions'; import { ITerminalProfileResolverService } from 'vs/workbench/contrib/terminal/common/terminal'; import { TerminalNativeContribution } from 'vs/workbench/contrib/terminal/electron-sandbox/terminalNativeContribution'; import { ElectronTerminalProfileResolverService } from 'vs/workbench/contrib/terminal/electron-sandbox/terminalProfileResolverService'; import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle'; import { LocalTerminalBackendContribution } from 'vs/workbench/contrib/terminal/electron-sandbox/localTerminalBackend'; // Register services registerMainProcessRemoteService(ILocalPtyService, TerminalIpcChannels.LocalPty); registerSingleton(ITerminalProfileResolverService, ElectronTerminalProfileResolverService, InstantiationType.Delayed); // Register workbench contributions const workbenchRegistry = Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench); // This contribution needs to be active during the Startup phase to be available when a remote resolver tries to open a local // terminal while connecting to the remote. workbenchRegistry.registerWorkbenchContribution(LocalTerminalBackendContribution, LifecyclePhase.Starting); workbenchRegistry.registerWorkbenchContribution(TerminalNativeContribution, LifecyclePhase.Restored);
src/vs/workbench/contrib/terminal/electron-sandbox/terminal.contribution.ts
0
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
[ 0.00018597538291942328, 0.00017324461077805609, 0.0001649510522838682, 0.00016880736802704632, 0.000009138650966633577 ]
{ "id": 1, "code_window": [ "import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput';\n", "import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';\n", "import { IWorkspaceContextService, IWorkspaceFolder, WorkbenchState } from 'vs/platform/workspace/common/workspace';\n", "import { IWorkspaceTrustRequestService } from 'vs/platform/workspace/common/workspaceTrust';\n", "import { EditorInput } from 'vs/workbench/common/editor/editorInput';\n", "import { IViewDescriptorService, IViewsService, ViewContainerLocation } from 'vs/workbench/common/views';\n", "import { AdapterManager } from 'vs/workbench/contrib/debug/browser/debugAdapterManager';\n", "import { DEBUG_CONFIGURE_COMMAND_ID, DEBUG_CONFIGURE_LABEL } from 'vs/workbench/contrib/debug/browser/debugCommands';\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { EditorsOrder } from 'vs/workbench/common/editor';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "add", "edit_start_line_idx": 33 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import { dirname, basename } from 'vs/base/common/resources'; import { ITitleProperties } from 'vs/workbench/browser/parts/titlebar/titlebarPart'; import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import { EditorResourceAccessor, Verbosity, SideBySideEditor } from 'vs/workbench/common/editor'; import { IBrowserWorkbenchEnvironmentService } from 'vs/workbench/services/environment/browser/environmentService'; import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace'; import { isWindows, isWeb, isMacintosh } from 'vs/base/common/platform'; import { URI } from 'vs/base/common/uri'; import { trim } from 'vs/base/common/strings'; import { IEditorGroupsContainer } from 'vs/workbench/services/editor/common/editorGroupsService'; import { template } from 'vs/base/common/labels'; import { ILabelService, Verbosity as LabelVerbosity } from 'vs/platform/label/common/label'; import { Emitter } from 'vs/base/common/event'; import { RunOnceScheduler } from 'vs/base/common/async'; import { IProductService } from 'vs/platform/product/common/productService'; import { Schemas } from 'vs/base/common/network'; import { getVirtualWorkspaceLocation } from 'vs/platform/workspace/common/virtualWorkspace'; import { IUserDataProfileService } from 'vs/workbench/services/userDataProfile/common/userDataProfile'; import { IViewsService } from 'vs/workbench/common/views'; import { ICodeEditor, isCodeEditor, isDiffEditor } from 'vs/editor/browser/editorBrowser'; const enum WindowSettingNames { titleSeparator = 'window.titleSeparator', title = 'window.title', } export class WindowTitle extends Disposable { private static readonly NLS_USER_IS_ADMIN = isWindows ? localize('userIsAdmin', "[Administrator]") : localize('userIsSudo', "[Superuser]"); private static readonly NLS_EXTENSION_HOST = localize('devExtensionWindowTitlePrefix', "[Extension Development Host]"); private static readonly TITLE_DIRTY = '\u25cf '; private readonly properties: ITitleProperties = { isPure: true, isAdmin: false, prefix: undefined }; private readonly activeEditorListeners = this._register(new DisposableStore()); private readonly titleUpdater = this._register(new RunOnceScheduler(() => this.doUpdateTitle(), 0)); private readonly onDidChangeEmitter = new Emitter<void>(); readonly onDidChange = this.onDidChangeEmitter.event; get value() { return this.title ?? ''; } get workspaceName() { return this.labelService.getWorkspaceLabel(this.contextService.getWorkspace()); } get fileName() { const activeEditor = this.editorService.activeEditor; if (!activeEditor) { return undefined; } const fileName = activeEditor.getTitle(Verbosity.SHORT); const dirty = activeEditor?.isDirty() && !activeEditor.isSaving() ? WindowTitle.TITLE_DIRTY : ''; return `${dirty}${fileName}`; } private title: string | undefined; private titleIncludesFocusedView: boolean = false; private readonly editorService: IEditorService; constructor( private readonly targetWindow: Window, editorGroupsContainer: IEditorGroupsContainer | 'main', @IConfigurationService protected readonly configurationService: IConfigurationService, @IEditorService editorService: IEditorService, @IBrowserWorkbenchEnvironmentService protected readonly environmentService: IBrowserWorkbenchEnvironmentService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @ILabelService private readonly labelService: ILabelService, @IUserDataProfileService private readonly userDataProfileService: IUserDataProfileService, @IProductService private readonly productService: IProductService, @IViewsService private readonly viewsService: IViewsService ) { super(); this.editorService = editorService.createScoped(editorGroupsContainer, this._store); this.updateTitleIncludesFocusedView(); this.registerListeners(); } private registerListeners(): void { this._register(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationChanged(e))); this._register(this.editorService.onDidActiveEditorChange(() => this.onActiveEditorChange())); this._register(this.contextService.onDidChangeWorkspaceFolders(() => this.titleUpdater.schedule())); this._register(this.contextService.onDidChangeWorkbenchState(() => this.titleUpdater.schedule())); this._register(this.contextService.onDidChangeWorkspaceName(() => this.titleUpdater.schedule())); this._register(this.labelService.onDidChangeFormatters(() => this.titleUpdater.schedule())); this._register(this.userDataProfileService.onDidChangeCurrentProfile(() => this.titleUpdater.schedule())); this._register(this.viewsService.onDidChangeFocusedView(() => { if (this.titleIncludesFocusedView) { this.titleUpdater.schedule(); } })); } private onConfigurationChanged(event: IConfigurationChangeEvent): void { if (event.affectsConfiguration(WindowSettingNames.title)) { this.updateTitleIncludesFocusedView(); } if (event.affectsConfiguration(WindowSettingNames.title) || event.affectsConfiguration(WindowSettingNames.titleSeparator)) { this.titleUpdater.schedule(); } } private updateTitleIncludesFocusedView(): void { const titleTemplate = this.configurationService.getValue<unknown>(WindowSettingNames.title); this.titleIncludesFocusedView = typeof titleTemplate === 'string' && titleTemplate.includes('${focusedView}'); } private onActiveEditorChange(): void { // Dispose old listeners this.activeEditorListeners.clear(); // Calculate New Window Title this.titleUpdater.schedule(); // Apply listener for dirty and label changes const activeEditor = this.editorService.activeEditor; if (activeEditor) { this.activeEditorListeners.add(activeEditor.onDidChangeDirty(() => this.titleUpdater.schedule())); this.activeEditorListeners.add(activeEditor.onDidChangeLabel(() => this.titleUpdater.schedule())); } // Apply listeners for tracking focused code editor if (this.titleIncludesFocusedView) { const activeTextEditorControl = this.editorService.activeTextEditorControl; const textEditorControls: ICodeEditor[] = []; if (isCodeEditor(activeTextEditorControl)) { textEditorControls.push(activeTextEditorControl); } else if (isDiffEditor(activeTextEditorControl)) { textEditorControls.push(activeTextEditorControl.getOriginalEditor(), activeTextEditorControl.getModifiedEditor()); } for (const textEditorControl of textEditorControls) { this.activeEditorListeners.add(textEditorControl.onDidBlurEditorText(() => this.titleUpdater.schedule())); this.activeEditorListeners.add(textEditorControl.onDidFocusEditorText(() => this.titleUpdater.schedule())); } } } private doUpdateTitle(): void { const title = this.getFullWindowTitle(); if (title !== this.title) { // Always set the native window title to identify us properly to the OS let nativeTitle = title; if (!trim(nativeTitle)) { nativeTitle = this.productService.nameLong; } if (!this.targetWindow.document.title && isMacintosh && nativeTitle === this.productService.nameLong) { // TODO@electron macOS: if we set a window title for // the first time and it matches the one we set in // `windowImpl.ts` somehow the window does not appear // in the "Windows" menu. As such, we set the title // briefly to something different to ensure macOS // recognizes we have a window. // See: https://github.com/microsoft/vscode/issues/191288 this.targetWindow.document.title = `${this.productService.nameLong} ${WindowTitle.TITLE_DIRTY}`; } this.targetWindow.document.title = nativeTitle; this.title = title; this.onDidChangeEmitter.fire(); } } private getFullWindowTitle(): string { const { prefix, suffix } = this.getTitleDecorations(); let title = this.getWindowTitle() || this.productService.nameLong; if (prefix) { title = `${prefix} ${title}`; } if (suffix) { title = `${title} ${suffix}`; } // Replace non-space whitespace return title.replace(/[^\S ]/g, ' '); } getTitleDecorations() { let prefix: string | undefined; let suffix: string | undefined; if (this.properties.prefix) { prefix = this.properties.prefix; } if (this.environmentService.isExtensionDevelopment) { prefix = !prefix ? WindowTitle.NLS_EXTENSION_HOST : `${WindowTitle.NLS_EXTENSION_HOST} - ${prefix}`; } if (this.properties.isAdmin) { suffix = WindowTitle.NLS_USER_IS_ADMIN; } return { prefix, suffix }; } updateProperties(properties: ITitleProperties): void { const isAdmin = typeof properties.isAdmin === 'boolean' ? properties.isAdmin : this.properties.isAdmin; const isPure = typeof properties.isPure === 'boolean' ? properties.isPure : this.properties.isPure; const prefix = typeof properties.prefix === 'string' ? properties.prefix : this.properties.prefix; if (isAdmin !== this.properties.isAdmin || isPure !== this.properties.isPure || prefix !== this.properties.prefix) { this.properties.isAdmin = isAdmin; this.properties.isPure = isPure; this.properties.prefix = prefix; this.titleUpdater.schedule(); } } /** * Possible template values: * * {activeEditorLong}: e.g. /Users/Development/myFolder/myFileFolder/myFile.txt * {activeEditorMedium}: e.g. myFolder/myFileFolder/myFile.txt * {activeEditorShort}: e.g. myFile.txt * {activeFolderLong}: e.g. /Users/Development/myFolder/myFileFolder * {activeFolderMedium}: e.g. myFolder/myFileFolder * {activeFolderShort}: e.g. myFileFolder * {rootName}: e.g. myFolder1, myFolder2, myFolder3 * {rootPath}: e.g. /Users/Development * {folderName}: e.g. myFolder * {folderPath}: e.g. /Users/Development/myFolder * {appName}: e.g. VS Code * {remoteName}: e.g. SSH * {dirty}: indicator * {focusedView}: e.g. Terminal * {separator}: conditional separator */ getWindowTitle(): string { const editor = this.editorService.activeEditor; const workspace = this.contextService.getWorkspace(); // Compute root let root: URI | undefined; if (workspace.configuration) { root = workspace.configuration; } else if (workspace.folders.length) { root = workspace.folders[0].uri; } // Compute active editor folder const editorResource = EditorResourceAccessor.getOriginalUri(editor, { supportSideBySide: SideBySideEditor.PRIMARY }); let editorFolderResource = editorResource ? dirname(editorResource) : undefined; if (editorFolderResource?.path === '.') { editorFolderResource = undefined; } // Compute folder resource // Single Root Workspace: always the root single workspace in this case // Otherwise: root folder of the currently active file if any let folder: IWorkspaceFolder | undefined = undefined; if (this.contextService.getWorkbenchState() === WorkbenchState.FOLDER) { folder = workspace.folders[0]; } else if (editorResource) { folder = this.contextService.getWorkspaceFolder(editorResource) ?? undefined; } // Compute remote // vscode-remtoe: use as is // otherwise figure out if we have a virtual folder opened let remoteName: string | undefined = undefined; if (this.environmentService.remoteAuthority && !isWeb) { remoteName = this.labelService.getHostLabel(Schemas.vscodeRemote, this.environmentService.remoteAuthority); } else { const virtualWorkspaceLocation = getVirtualWorkspaceLocation(workspace); if (virtualWorkspaceLocation) { remoteName = this.labelService.getHostLabel(virtualWorkspaceLocation.scheme, virtualWorkspaceLocation.authority); } } // Variables const activeEditorShort = editor ? editor.getTitle(Verbosity.SHORT) : ''; const activeEditorMedium = editor ? editor.getTitle(Verbosity.MEDIUM) : activeEditorShort; const activeEditorLong = editor ? editor.getTitle(Verbosity.LONG) : activeEditorMedium; const activeFolderShort = editorFolderResource ? basename(editorFolderResource) : ''; const activeFolderMedium = editorFolderResource ? this.labelService.getUriLabel(editorFolderResource, { relative: true }) : ''; const activeFolderLong = editorFolderResource ? this.labelService.getUriLabel(editorFolderResource) : ''; const rootName = this.labelService.getWorkspaceLabel(workspace); const rootNameShort = this.labelService.getWorkspaceLabel(workspace, { verbose: LabelVerbosity.SHORT }); const rootPath = root ? this.labelService.getUriLabel(root) : ''; const folderName = folder ? folder.name : ''; const folderPath = folder ? this.labelService.getUriLabel(folder.uri) : ''; const dirty = editor?.isDirty() && !editor.isSaving() ? WindowTitle.TITLE_DIRTY : ''; const appName = this.productService.nameLong; const profileName = this.userDataProfileService.currentProfile.isDefault ? '' : this.userDataProfileService.currentProfile.name; const separator = this.configurationService.getValue<string>(WindowSettingNames.titleSeparator); const titleTemplate = this.configurationService.getValue<string>(WindowSettingNames.title); const focusedView: string = this.viewsService.getFocusedViewName(); return template(titleTemplate, { activeEditorShort, activeEditorLong, activeEditorMedium, activeFolderShort, activeFolderMedium, activeFolderLong, rootName, rootPath, rootNameShort, folderName, folderPath, dirty, appName, remoteName, profileName, focusedView, separator: { label: separator } }); } isCustomTitleFormat(): boolean { const title = this.configurationService.inspect<string>(WindowSettingNames.title); const titleSeparator = this.configurationService.inspect<string>(WindowSettingNames.titleSeparator); return title.value !== title.defaultValue || titleSeparator.value !== titleSeparator.defaultValue; } }
src/vs/workbench/browser/parts/titlebar/windowTitle.ts
0
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
[ 0.0017908667214214802, 0.00025175471091642976, 0.00016298533591907471, 0.00017445928824599832, 0.00028028039378114045 ]
{ "id": 2, "code_window": [ "import { ConfigurationManager } from 'vs/workbench/contrib/debug/browser/debugConfigurationManager';\n", "import { DebugMemoryFileSystemProvider } from 'vs/workbench/contrib/debug/browser/debugMemory';\n", "import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession';\n", "import { DebugTaskRunner, TaskRunResult } from 'vs/workbench/contrib/debug/browser/debugTaskRunner';\n", "import { CALLSTACK_VIEW_ID, CONTEXT_BREAKPOINTS_EXIST, CONTEXT_HAS_DEBUGGED, CONTEXT_DEBUG_STATE, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_UX, CONTEXT_DISASSEMBLY_VIEW_FOCUS, CONTEXT_IN_DEBUG_MODE, debuggerDisabledMessage, DEBUG_MEMORY_SCHEME, getStateLabel, IAdapterManager, IBreakpoint, IBreakpointData, ICompound, IConfig, IConfigurationManager, IDebugConfiguration, IDebugModel, IDebugService, IDebugSession, IDebugSessionOptions, IEnablement, IExceptionBreakpoint, IGlobalConfig, ILaunch, IStackFrame, IThread, IViewModel, REPL_VIEW_ID, State, VIEWLET_ID } from 'vs/workbench/contrib/debug/common/debug';\n", "import { DebugCompoundRoot } from 'vs/workbench/contrib/debug/common/debugCompoundRoot';\n", "import { Debugger } from 'vs/workbench/contrib/debug/common/debugger';\n", "import { Breakpoint, DataBreakpoint, DebugModel, FunctionBreakpoint, InstructionBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { CALLSTACK_VIEW_ID, CONTEXT_BREAKPOINTS_EXIST, CONTEXT_HAS_DEBUGGED, CONTEXT_DEBUG_STATE, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_UX, CONTEXT_DISASSEMBLY_VIEW_FOCUS, CONTEXT_IN_DEBUG_MODE, debuggerDisabledMessage, DEBUG_MEMORY_SCHEME, getStateLabel, IAdapterManager, IBreakpoint, IBreakpointData, ICompound, IConfig, IConfigurationManager, IDebugConfiguration, IDebugModel, IDebugService, IDebugSession, IDebugSessionOptions, IEnablement, IExceptionBreakpoint, IGlobalConfig, ILaunch, IStackFrame, IThread, IViewModel, REPL_VIEW_ID, State, VIEWLET_ID, DEBUG_SCHEME } from 'vs/workbench/contrib/debug/common/debug';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 41 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as aria from 'vs/base/browser/ui/aria/aria'; import { Action, IAction } from 'vs/base/common/actions'; import { distinct } from 'vs/base/common/arrays'; import { raceTimeout, RunOnceScheduler } from 'vs/base/common/async'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { isErrorWithActions } from 'vs/base/common/errorMessage'; import * as errors from 'vs/base/common/errors'; import { Emitter, Event } from 'vs/base/common/event'; import { DisposableStore, IDisposable } from 'vs/base/common/lifecycle'; import { deepClone, equals } from 'vs/base/common/objects'; import severity from 'vs/base/common/severity'; import { URI, URI as uri } from 'vs/base/common/uri'; import { generateUuid } from 'vs/base/common/uuid'; import { isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { ITextModel } from 'vs/editor/common/model'; import * as nls from 'vs/nls'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity'; import { IWorkspaceContextService, IWorkspaceFolder, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { IWorkspaceTrustRequestService } from 'vs/platform/workspace/common/workspaceTrust'; import { EditorInput } from 'vs/workbench/common/editor/editorInput'; import { IViewDescriptorService, IViewsService, ViewContainerLocation } from 'vs/workbench/common/views'; import { AdapterManager } from 'vs/workbench/contrib/debug/browser/debugAdapterManager'; import { DEBUG_CONFIGURE_COMMAND_ID, DEBUG_CONFIGURE_LABEL } from 'vs/workbench/contrib/debug/browser/debugCommands'; import { ConfigurationManager } from 'vs/workbench/contrib/debug/browser/debugConfigurationManager'; import { DebugMemoryFileSystemProvider } from 'vs/workbench/contrib/debug/browser/debugMemory'; import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession'; import { DebugTaskRunner, TaskRunResult } from 'vs/workbench/contrib/debug/browser/debugTaskRunner'; import { CALLSTACK_VIEW_ID, CONTEXT_BREAKPOINTS_EXIST, CONTEXT_HAS_DEBUGGED, CONTEXT_DEBUG_STATE, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_UX, CONTEXT_DISASSEMBLY_VIEW_FOCUS, CONTEXT_IN_DEBUG_MODE, debuggerDisabledMessage, DEBUG_MEMORY_SCHEME, getStateLabel, IAdapterManager, IBreakpoint, IBreakpointData, ICompound, IConfig, IConfigurationManager, IDebugConfiguration, IDebugModel, IDebugService, IDebugSession, IDebugSessionOptions, IEnablement, IExceptionBreakpoint, IGlobalConfig, ILaunch, IStackFrame, IThread, IViewModel, REPL_VIEW_ID, State, VIEWLET_ID } from 'vs/workbench/contrib/debug/common/debug'; import { DebugCompoundRoot } from 'vs/workbench/contrib/debug/common/debugCompoundRoot'; import { Debugger } from 'vs/workbench/contrib/debug/common/debugger'; import { Breakpoint, DataBreakpoint, DebugModel, FunctionBreakpoint, InstructionBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel'; import { DebugStorage } from 'vs/workbench/contrib/debug/common/debugStorage'; import { DebugTelemetry } from 'vs/workbench/contrib/debug/common/debugTelemetry'; import { getExtensionHostDebugSession, saveAllBeforeDebugStart } from 'vs/workbench/contrib/debug/common/debugUtils'; import { ViewModel } from 'vs/workbench/contrib/debug/common/debugViewModel'; import { DisassemblyViewInput } from 'vs/workbench/contrib/debug/common/disassemblyViewInput'; import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/contrib/files/common/files'; import { IActivityService, NumberBadge } from 'vs/workbench/services/activity/common/activity'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService'; import { ILifecycleService } from 'vs/workbench/services/lifecycle/common/lifecycle'; import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite'; export class DebugService implements IDebugService { declare readonly _serviceBrand: undefined; private readonly _onDidChangeState: Emitter<State>; private readonly _onDidNewSession: Emitter<IDebugSession>; private readonly _onWillNewSession: Emitter<IDebugSession>; private readonly _onDidEndSession: Emitter<{ session: IDebugSession; restart: boolean }>; private readonly restartingSessions = new Set<IDebugSession>(); private debugStorage: DebugStorage; private model: DebugModel; private viewModel: ViewModel; private telemetry: DebugTelemetry; private taskRunner: DebugTaskRunner; private configurationManager: ConfigurationManager; private adapterManager: AdapterManager; private readonly disposables = new DisposableStore(); private debugType!: IContextKey<string>; private debugState!: IContextKey<string>; private inDebugMode!: IContextKey<boolean>; private debugUx!: IContextKey<string>; private hasDebugged!: IContextKey<boolean>; private breakpointsExist!: IContextKey<boolean>; private disassemblyViewFocus!: IContextKey<boolean>; private breakpointsToSendOnResourceSaved: Set<URI>; private initializing = false; private _initializingOptions: IDebugSessionOptions | undefined; private previousState: State | undefined; private sessionCancellationTokens = new Map<string, CancellationTokenSource>(); private activity: IDisposable | undefined; private chosenEnvironments: { [key: string]: string }; private haveDoneLazySetup = false; constructor( @IEditorService private readonly editorService: IEditorService, @IPaneCompositePartService private readonly paneCompositeService: IPaneCompositePartService, @IViewsService private readonly viewsService: IViewsService, @IViewDescriptorService private readonly viewDescriptorService: IViewDescriptorService, @INotificationService private readonly notificationService: INotificationService, @IDialogService private readonly dialogService: IDialogService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @ILifecycleService private readonly lifecycleService: ILifecycleService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IExtensionService private readonly extensionService: IExtensionService, @IFileService private readonly fileService: IFileService, @IConfigurationService private readonly configurationService: IConfigurationService, @IExtensionHostDebugService private readonly extensionHostDebugService: IExtensionHostDebugService, @IActivityService private readonly activityService: IActivityService, @ICommandService private readonly commandService: ICommandService, @IQuickInputService private readonly quickInputService: IQuickInputService, @IWorkspaceTrustRequestService private readonly workspaceTrustRequestService: IWorkspaceTrustRequestService, @IUriIdentityService private readonly uriIdentityService: IUriIdentityService ) { this.breakpointsToSendOnResourceSaved = new Set<URI>(); this._onDidChangeState = new Emitter<State>(); this._onDidNewSession = new Emitter<IDebugSession>(); this._onWillNewSession = new Emitter<IDebugSession>(); this._onDidEndSession = new Emitter(); this.adapterManager = this.instantiationService.createInstance(AdapterManager, { onDidNewSession: this.onDidNewSession }); this.disposables.add(this.adapterManager); this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this.adapterManager); this.disposables.add(this.configurationManager); this.debugStorage = this.disposables.add(this.instantiationService.createInstance(DebugStorage)); this.chosenEnvironments = this.debugStorage.loadChosenEnvironments(); this.model = this.instantiationService.createInstance(DebugModel, this.debugStorage); this.telemetry = this.instantiationService.createInstance(DebugTelemetry, this.model); this.viewModel = new ViewModel(contextKeyService); this.taskRunner = this.instantiationService.createInstance(DebugTaskRunner); this.disposables.add(this.fileService.onDidFilesChange(e => this.onFileChanges(e))); this.disposables.add(this.lifecycleService.onWillShutdown(this.dispose, this)); this.disposables.add(this.extensionHostDebugService.onAttachSession(event => { const session = this.model.getSession(event.sessionId, true); if (session) { // EH was started in debug mode -> attach to it session.configuration.request = 'attach'; session.configuration.port = event.port; session.setSubId(event.subId); this.launchOrAttachToSession(session); } })); this.disposables.add(this.extensionHostDebugService.onTerminateSession(event => { const session = this.model.getSession(event.sessionId); if (session && session.subId === event.subId) { session.disconnect(); } })); this.disposables.add(this.viewModel.onDidFocusStackFrame(() => { this.onStateChange(); })); this.disposables.add(this.viewModel.onDidFocusSession((session: IDebugSession | undefined) => { this.onStateChange(); if (session) { this.setExceptionBreakpointFallbackSession(session.getId()); } })); this.disposables.add(Event.any(this.adapterManager.onDidRegisterDebugger, this.configurationManager.onDidSelectConfiguration)(() => { const debugUxValue = (this.state !== State.Inactive || (this.configurationManager.getAllConfigurations().length > 0 && this.adapterManager.hasEnabledDebuggers())) ? 'default' : 'simple'; this.debugUx.set(debugUxValue); this.debugStorage.storeDebugUxState(debugUxValue); })); this.disposables.add(this.model.onDidChangeCallStack(() => { const numberOfSessions = this.model.getSessions().filter(s => !s.parentSession).length; this.activity?.dispose(); if (numberOfSessions > 0) { const viewContainer = this.viewDescriptorService.getViewContainerByViewId(CALLSTACK_VIEW_ID); if (viewContainer) { this.activity = this.activityService.showViewContainerActivity(viewContainer.id, { badge: new NumberBadge(numberOfSessions, n => n === 1 ? nls.localize('1activeSession', "1 active session") : nls.localize('nActiveSessions', "{0} active sessions", n)) }); } } })); this.disposables.add(editorService.onDidActiveEditorChange(() => { this.contextKeyService.bufferChangeEvents(() => { if (editorService.activeEditor === DisassemblyViewInput.instance) { this.disassemblyViewFocus.set(true); } else { // This key can be initialized a tick after this event is fired this.disassemblyViewFocus?.reset(); } }); })); this.disposables.add(this.lifecycleService.onBeforeShutdown(() => { for (const editor of editorService.editors) { // Editors will not be valid on window reload, so close them. if (editor.resource?.scheme === DEBUG_MEMORY_SCHEME) { editor.dispose(); } } })); this.initContextKeys(contextKeyService); } private initContextKeys(contextKeyService: IContextKeyService): void { queueMicrotask(() => { contextKeyService.bufferChangeEvents(() => { this.debugType = CONTEXT_DEBUG_TYPE.bindTo(contextKeyService); this.debugState = CONTEXT_DEBUG_STATE.bindTo(contextKeyService); this.hasDebugged = CONTEXT_HAS_DEBUGGED.bindTo(contextKeyService); this.inDebugMode = CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService); this.debugUx = CONTEXT_DEBUG_UX.bindTo(contextKeyService); this.debugUx.set(this.debugStorage.loadDebugUxState()); this.breakpointsExist = CONTEXT_BREAKPOINTS_EXIST.bindTo(contextKeyService); // Need to set disassemblyViewFocus here to make it in the same context as the debug event handlers this.disassemblyViewFocus = CONTEXT_DISASSEMBLY_VIEW_FOCUS.bindTo(contextKeyService); }); const setBreakpointsExistContext = () => this.breakpointsExist.set(!!(this.model.getBreakpoints().length || this.model.getDataBreakpoints().length || this.model.getFunctionBreakpoints().length)); setBreakpointsExistContext(); this.disposables.add(this.model.onDidChangeBreakpoints(() => setBreakpointsExistContext())); }); } getModel(): IDebugModel { return this.model; } getViewModel(): IViewModel { return this.viewModel; } getConfigurationManager(): IConfigurationManager { return this.configurationManager; } getAdapterManager(): IAdapterManager { return this.adapterManager; } sourceIsNotAvailable(uri: uri): void { this.model.sourceIsNotAvailable(uri); } dispose(): void { this.disposables.dispose(); } //---- state management get state(): State { const focusedSession = this.viewModel.focusedSession; if (focusedSession) { return focusedSession.state; } return this.initializing ? State.Initializing : State.Inactive; } get initializingOptions(): IDebugSessionOptions | undefined { return this._initializingOptions; } private startInitializingState(options?: IDebugSessionOptions): void { if (!this.initializing) { this.initializing = true; this._initializingOptions = options; this.onStateChange(); } } private endInitializingState(): void { if (this.initializing) { this.initializing = false; this._initializingOptions = undefined; this.onStateChange(); } } private cancelTokens(id: string | undefined): void { if (id) { const token = this.sessionCancellationTokens.get(id); if (token) { token.cancel(); this.sessionCancellationTokens.delete(id); } } else { this.sessionCancellationTokens.forEach(t => t.cancel()); this.sessionCancellationTokens.clear(); } } private onStateChange(): void { const state = this.state; if (this.previousState !== state) { this.contextKeyService.bufferChangeEvents(() => { this.debugState.set(getStateLabel(state)); this.inDebugMode.set(state !== State.Inactive); // Only show the simple ux if debug is not yet started and if no launch.json exists const debugUxValue = ((state !== State.Inactive && state !== State.Initializing) || (this.adapterManager.hasEnabledDebuggers() && this.configurationManager.selectedConfiguration.name)) ? 'default' : 'simple'; this.debugUx.set(debugUxValue); this.debugStorage.storeDebugUxState(debugUxValue); }); this.previousState = state; this._onDidChangeState.fire(state); } } get onDidChangeState(): Event<State> { return this._onDidChangeState.event; } get onDidNewSession(): Event<IDebugSession> { return this._onDidNewSession.event; } get onWillNewSession(): Event<IDebugSession> { return this._onWillNewSession.event; } get onDidEndSession(): Event<{ session: IDebugSession; restart: boolean }> { return this._onDidEndSession.event; } private lazySetup() { if (!this.haveDoneLazySetup) { // Registering fs providers is slow // https://github.com/microsoft/vscode/issues/159886 this.disposables.add(this.fileService.registerProvider(DEBUG_MEMORY_SCHEME, new DebugMemoryFileSystemProvider(this))); this.haveDoneLazySetup = true; } } //---- life cycle management /** * main entry point * properly manages compounds, checks for errors and handles the initializing state. */ async startDebugging(launch: ILaunch | undefined, configOrName?: IConfig | string, options?: IDebugSessionOptions, saveBeforeStart = !options?.parentSession): Promise<boolean> { const message = options && options.noDebug ? nls.localize('runTrust', "Running executes build tasks and program code from your workspace.") : nls.localize('debugTrust', "Debugging executes build tasks and program code from your workspace."); const trust = await this.workspaceTrustRequestService.requestWorkspaceTrust({ message }); if (!trust) { return false; } this.lazySetup(); this.startInitializingState(options); this.hasDebugged.set(true); try { // make sure to save all files and that the configuration is up to date await this.extensionService.activateByEvent('onDebug'); if (saveBeforeStart) { await saveAllBeforeDebugStart(this.configurationService, this.editorService); } await this.extensionService.whenInstalledExtensionsRegistered(); let config: IConfig | undefined; let compound: ICompound | undefined; if (!configOrName) { configOrName = this.configurationManager.selectedConfiguration.name; } if (typeof configOrName === 'string' && launch) { config = launch.getConfiguration(configOrName); compound = launch.getCompound(configOrName); } else if (typeof configOrName !== 'string') { config = configOrName; } if (compound) { // we are starting a compound debug, first do some error checking and than start each configuration in the compound if (!compound.configurations) { throw new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] }, "Compound must have \"configurations\" attribute set in order to start multiple configurations.")); } if (compound.preLaunchTask) { const taskResult = await this.taskRunner.runTaskAndCheckErrors(launch?.workspace || this.contextService.getWorkspace(), compound.preLaunchTask); if (taskResult === TaskRunResult.Failure) { this.endInitializingState(); return false; } } if (compound.stopAll) { options = { ...options, compoundRoot: new DebugCompoundRoot() }; } const values = await Promise.all(compound.configurations.map(configData => { const name = typeof configData === 'string' ? configData : configData.name; if (name === compound!.name) { return Promise.resolve(false); } let launchForName: ILaunch | undefined; if (typeof configData === 'string') { const launchesContainingName = this.configurationManager.getLaunches().filter(l => !!l.getConfiguration(name)); if (launchesContainingName.length === 1) { launchForName = launchesContainingName[0]; } else if (launch && launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) { // If there are multiple launches containing the configuration give priority to the configuration in the current launch launchForName = launch; } else { throw new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name) : nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name)); } } else if (configData.folder) { const launchesMatchingConfigData = this.configurationManager.getLaunches().filter(l => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name)); if (launchesMatchingConfigData.length === 1) { launchForName = launchesMatchingConfigData[0]; } else { throw new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound!.name)); } } return this.createSession(launchForName, launchForName!.getConfiguration(name), options); })); const result = values.every(success => !!success); // Compound launch is a success only if each configuration launched successfully this.endInitializingState(); return result; } if (configOrName && !config) { const message = !!launch ? nls.localize('configMissing', "Configuration '{0}' is missing in 'launch.json'.", typeof configOrName === 'string' ? configOrName : configOrName.name) : nls.localize('launchJsonDoesNotExist', "'launch.json' does not exist for passed workspace folder."); throw new Error(message); } const result = await this.createSession(launch, config, options); this.endInitializingState(); return result; } catch (err) { // make sure to get out of initializing state, and propagate the result this.notificationService.error(err); this.endInitializingState(); return Promise.reject(err); } } /** * gets the debugger for the type, resolves configurations by providers, substitutes variables and runs prelaunch tasks */ private async createSession(launch: ILaunch | undefined, config: IConfig | undefined, options?: IDebugSessionOptions): Promise<boolean> { // We keep the debug type in a separate variable 'type' so that a no-folder config has no attributes. // Storing the type in the config would break extensions that assume that the no-folder case is indicated by an empty config. let type: string | undefined; if (config) { type = config.type; } else { // a no-folder workspace has no launch.config config = Object.create(null); } if (options && options.noDebug) { config!.noDebug = true; } else if (options && typeof options.noDebug === 'undefined' && options.parentSession && options.parentSession.configuration.noDebug) { config!.noDebug = true; } const unresolvedConfig = deepClone(config); let guess: Debugger | undefined; let activeEditor: EditorInput | undefined; if (!type) { activeEditor = this.editorService.activeEditor; if (activeEditor && activeEditor.resource) { type = this.chosenEnvironments[activeEditor.resource.toString()]; } if (!type) { guess = await this.adapterManager.guessDebugger(false); if (guess) { type = guess.type; } } } const initCancellationToken = new CancellationTokenSource(); const sessionId = generateUuid(); this.sessionCancellationTokens.set(sessionId, initCancellationToken); const configByProviders = await this.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config!, initCancellationToken.token); // a falsy config indicates an aborted launch if (configByProviders && configByProviders.type) { try { let resolvedConfig = await this.substituteVariables(launch, configByProviders); if (!resolvedConfig) { // User cancelled resolving of interactive variables, silently return return false; } if (initCancellationToken.token.isCancellationRequested) { // User cancelled, silently return return false; } const workspace = launch?.workspace || this.contextService.getWorkspace(); const taskResult = await this.taskRunner.runTaskAndCheckErrors(workspace, resolvedConfig.preLaunchTask); if (taskResult === TaskRunResult.Failure) { return false; } const cfg = await this.configurationManager.resolveDebugConfigurationWithSubstitutedVariables(launch && launch.workspace ? launch.workspace.uri : undefined, resolvedConfig.type, resolvedConfig, initCancellationToken.token); if (!cfg) { if (launch && type && cfg === null && !initCancellationToken.token.isCancellationRequested) { // show launch.json only for "config" being "null". await launch.openConfigFile({ preserveFocus: true, type }, initCancellationToken.token); } return false; } resolvedConfig = cfg; const dbg = this.adapterManager.getDebugger(resolvedConfig.type); if (!dbg || (configByProviders.request !== 'attach' && configByProviders.request !== 'launch')) { let message: string; if (configByProviders.request !== 'attach' && configByProviders.request !== 'launch') { message = configByProviders.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', configByProviders.request) : nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request'); } else { message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) : nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."); } const actionList: IAction[] = []; actionList.push(new Action( 'installAdditionalDebuggers', nls.localize({ key: 'installAdditionalDebuggers', comment: ['Placeholder is the debug type, so for example "node", "python"'] }, "Install {0} Extension", resolvedConfig.type), undefined, true, async () => this.commandService.executeCommand('debug.installAdditionalDebuggers', resolvedConfig?.type) )); await this.showError(message, actionList); return false; } if (!dbg.enabled) { await this.showError(debuggerDisabledMessage(dbg.type), []); return false; } const result = await this.doCreateSession(sessionId, launch?.workspace, { resolved: resolvedConfig, unresolved: unresolvedConfig }, options); if (result && guess && activeEditor && activeEditor.resource) { // Remeber user choice of environment per active editor to make starting debugging smoother #124770 this.chosenEnvironments[activeEditor.resource.toString()] = guess.type; this.debugStorage.storeChosenEnvironments(this.chosenEnvironments); } return result; } catch (err) { if (err && err.message) { await this.showError(err.message); } else if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) { await this.showError(nls.localize('noFolderWorkspaceDebugError', "The active file can not be debugged. Make sure it is saved and that you have a debug extension installed for that file type.")); } if (launch && !initCancellationToken.token.isCancellationRequested) { await launch.openConfigFile({ preserveFocus: true }, initCancellationToken.token); } return false; } } if (launch && type && configByProviders === null && !initCancellationToken.token.isCancellationRequested) { // show launch.json only for "config" being "null". await launch.openConfigFile({ preserveFocus: true, type }, initCancellationToken.token); } return false; } /** * instantiates the new session, initializes the session, registers session listeners and reports telemetry */ private async doCreateSession(sessionId: string, root: IWorkspaceFolder | undefined, configuration: { resolved: IConfig; unresolved: IConfig | undefined }, options?: IDebugSessionOptions): Promise<boolean> { const session = this.instantiationService.createInstance(DebugSession, sessionId, configuration, root, this.model, options); if (options?.startedByUser && this.model.getSessions().some(s => s.getLabel() === session.getLabel()) && configuration.resolved.suppressMultipleSessionWarning !== true) { // There is already a session with the same name, prompt user #127721 const result = await this.dialogService.confirm({ message: nls.localize('multipleSession', "'{0}' is already running. Do you want to start another instance?", session.getLabel()) }); if (!result.confirmed) { return false; } } this.model.addSession(session); // register listeners as the very first thing! this.registerSessionListeners(session); // since the Session is now properly registered under its ID and hooked, we can announce it // this event doesn't go to extensions this._onWillNewSession.fire(session); const openDebug = this.configurationService.getValue<IDebugConfiguration>('debug').openDebug; // Open debug viewlet based on the visibility of the side bar and openDebug setting. Do not open for 'run without debug' if (!configuration.resolved.noDebug && (openDebug === 'openOnSessionStart' || (openDebug !== 'neverOpen' && this.viewModel.firstSessionStart)) && !session.suppressDebugView) { await this.paneCompositeService.openPaneComposite(VIEWLET_ID, ViewContainerLocation.Sidebar); } try { await this.launchOrAttachToSession(session); const internalConsoleOptions = session.configuration.internalConsoleOptions || this.configurationService.getValue<IDebugConfiguration>('debug').internalConsoleOptions; if (internalConsoleOptions === 'openOnSessionStart' || (this.viewModel.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) { this.viewsService.openView(REPL_VIEW_ID, false); } this.viewModel.firstSessionStart = false; const showSubSessions = this.configurationService.getValue<IDebugConfiguration>('debug').showSubSessionsInToolBar; const sessions = this.model.getSessions(); const shownSessions = showSubSessions ? sessions : sessions.filter(s => !s.parentSession); if (shownSessions.length > 1) { this.viewModel.setMultiSessionView(true); } // since the initialized response has arrived announce the new Session (including extensions) this._onDidNewSession.fire(session); return true; } catch (error) { if (errors.isCancellationError(error)) { // don't show 'canceled' error messages to the user #7906 return false; } // Show the repl if some error got logged there #5870 if (session && session.getReplElements().length > 0) { this.viewsService.openView(REPL_VIEW_ID, false); } if (session.configuration && session.configuration.request === 'attach' && session.configuration.__autoAttach) { // ignore attach timeouts in auto attach mode return false; } const errorMessage = error instanceof Error ? error.message : error; if (error.showUser !== false) { // Only show the error when showUser is either not defined, or is true #128484 await this.showError(errorMessage, isErrorWithActions(error) ? error.actions : []); } return false; } } private async launchOrAttachToSession(session: IDebugSession, forceFocus = false): Promise<void> { const dbgr = this.adapterManager.getDebugger(session.configuration.type); try { await session.initialize(dbgr!); await session.launchOrAttach(session.configuration); const launchJsonExists = !!session.root && !!this.configurationService.getValue<IGlobalConfig>('launch', { resource: session.root.uri }); await this.telemetry.logDebugSessionStart(dbgr!, launchJsonExists); if (forceFocus || !this.viewModel.focusedSession || (session.parentSession === this.viewModel.focusedSession && session.compact)) { await this.focusStackFrame(undefined, undefined, session); } } catch (err) { if (this.viewModel.focusedSession === session) { await this.focusStackFrame(undefined); } return Promise.reject(err); } } private registerSessionListeners(session: DebugSession): void { const listenerDisposables = new DisposableStore(); this.disposables.add(listenerDisposables); const sessionRunningScheduler = listenerDisposables.add(new RunOnceScheduler(() => { // Do not immediatly defocus the stack frame if the session is running if (session.state === State.Running && this.viewModel.focusedSession === session) { this.viewModel.setFocus(undefined, this.viewModel.focusedThread, session, false); } }, 200)); listenerDisposables.add(session.onDidChangeState(() => { if (session.state === State.Running && this.viewModel.focusedSession === session) { sessionRunningScheduler.schedule(); } if (session === this.viewModel.focusedSession) { this.onStateChange(); } })); listenerDisposables.add(this.onDidEndSession(e => { if (e.session === session && !e.restart) { this.disposables.delete(listenerDisposables); } })); listenerDisposables.add(session.onDidEndAdapter(async adapterExitEvent => { if (adapterExitEvent) { if (adapterExitEvent.error) { this.notificationService.error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly ({0})", adapterExitEvent.error.message || adapterExitEvent.error.toString())); } this.telemetry.logDebugSessionStop(session, adapterExitEvent); } // 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905 const extensionDebugSession = getExtensionHostDebugSession(session); if (extensionDebugSession && extensionDebugSession.state === State.Running && extensionDebugSession.configuration.noDebug) { this.extensionHostDebugService.close(extensionDebugSession.getId()); } if (session.configuration.postDebugTask) { const root = session.root ?? this.contextService.getWorkspace(); try { await this.taskRunner.runTask(root, session.configuration.postDebugTask); } catch (err) { this.notificationService.error(err); } } this.endInitializingState(); this.cancelTokens(session.getId()); this._onDidEndSession.fire({ session, restart: this.restartingSessions.has(session) }); const focusedSession = this.viewModel.focusedSession; if (focusedSession && focusedSession.getId() === session.getId()) { const { session, thread, stackFrame } = getStackFrameThreadAndSessionToFocus(this.model, undefined, undefined, undefined, focusedSession); this.viewModel.setFocus(stackFrame, thread, session, false); } if (this.model.getSessions().length === 0) { this.viewModel.setMultiSessionView(false); if (this.layoutService.isVisible(Parts.SIDEBAR_PART) && this.configurationService.getValue<IDebugConfiguration>('debug').openExplorerOnEnd) { this.paneCompositeService.openPaneComposite(EXPLORER_VIEWLET_ID, ViewContainerLocation.Sidebar); } // Data breakpoints that can not be persisted should be cleared when a session ends const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => !dbp.canPersist); dataBreakpoints.forEach(dbp => this.model.removeDataBreakpoints(dbp.getId())); if (this.configurationService.getValue<IDebugConfiguration>('debug').console.closeOnEnd) { const debugConsoleContainer = this.viewDescriptorService.getViewContainerByViewId(REPL_VIEW_ID); if (debugConsoleContainer && this.viewsService.isViewContainerVisible(debugConsoleContainer.id)) { this.viewsService.closeViewContainer(debugConsoleContainer.id); } } } this.model.removeExceptionBreakpointsForSession(session.getId()); // session.dispose(); TODO@roblourens })); } async restartSession(session: IDebugSession, restartData?: any): Promise<any> { if (session.saveBeforeRestart) { await saveAllBeforeDebugStart(this.configurationService, this.editorService); } const isAutoRestart = !!restartData; const runTasks: () => Promise<TaskRunResult> = async () => { if (isAutoRestart) { // Do not run preLaunch and postDebug tasks for automatic restarts return Promise.resolve(TaskRunResult.Success); } const root = session.root || this.contextService.getWorkspace(); await this.taskRunner.runTask(root, session.configuration.preRestartTask); await this.taskRunner.runTask(root, session.configuration.postDebugTask); const taskResult1 = await this.taskRunner.runTaskAndCheckErrors(root, session.configuration.preLaunchTask); if (taskResult1 !== TaskRunResult.Success) { return taskResult1; } return this.taskRunner.runTaskAndCheckErrors(root, session.configuration.postRestartTask); }; const extensionDebugSession = getExtensionHostDebugSession(session); if (extensionDebugSession) { const taskResult = await runTasks(); if (taskResult === TaskRunResult.Success) { this.extensionHostDebugService.reload(extensionDebugSession.getId()); } return; } // Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration let needsToSubstitute = false; let unresolved: IConfig | undefined; const launch = session.root ? this.configurationManager.getLaunch(session.root.uri) : undefined; if (launch) { unresolved = launch.getConfiguration(session.configuration.name); if (unresolved && !equals(unresolved, session.unresolvedConfiguration)) { // Take the type from the session since the debug extension might overwrite it #21316 unresolved.type = session.configuration.type; unresolved.noDebug = session.configuration.noDebug; needsToSubstitute = true; } } let resolved: IConfig | undefined | null = session.configuration; if (launch && needsToSubstitute && unresolved) { const initCancellationToken = new CancellationTokenSource(); this.sessionCancellationTokens.set(session.getId(), initCancellationToken); const resolvedByProviders = await this.configurationManager.resolveConfigurationByProviders(launch.workspace ? launch.workspace.uri : undefined, unresolved.type, unresolved, initCancellationToken.token); if (resolvedByProviders) { resolved = await this.substituteVariables(launch, resolvedByProviders); if (resolved && !initCancellationToken.token.isCancellationRequested) { resolved = await this.configurationManager.resolveDebugConfigurationWithSubstitutedVariables(launch && launch.workspace ? launch.workspace.uri : undefined, unresolved.type, resolved, initCancellationToken.token); } } else { resolved = resolvedByProviders; } } if (resolved) { session.setConfiguration({ resolved, unresolved }); } session.configuration.__restart = restartData; const doRestart = async (fn: () => Promise<boolean | undefined>) => { this.restartingSessions.add(session); let didRestart = false; try { didRestart = (await fn()) !== false; } catch (e) { didRestart = false; throw e; } finally { this.restartingSessions.delete(session); // we previously may have issued an onDidEndSession with restart: true, // assuming the adapter exited (in `registerSessionListeners`). But the // restart failed, so emit the final termination now. if (!didRestart) { this._onDidEndSession.fire({ session, restart: false }); } } }; if (session.capabilities.supportsRestartRequest) { const taskResult = await runTasks(); if (taskResult === TaskRunResult.Success) { await doRestart(async () => { await session.restart(); return true; }); } return; } const shouldFocus = !!this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId(); return doRestart(async () => { // If the restart is automatic -> disconnect, otherwise -> terminate #55064 if (isAutoRestart) { await session.disconnect(true); } else { await session.terminate(true); } return new Promise<boolean>((c, e) => { setTimeout(async () => { const taskResult = await runTasks(); if (taskResult !== TaskRunResult.Success) { return c(false); } if (!resolved) { return c(false); } try { await this.launchOrAttachToSession(session, shouldFocus); this._onDidNewSession.fire(session); c(true); } catch (error) { e(error); } }, 300); }); }); } async stopSession(session: IDebugSession | undefined, disconnect = false, suspend = false): Promise<any> { if (session) { return disconnect ? session.disconnect(undefined, suspend) : session.terminate(); } const sessions = this.model.getSessions(); if (sessions.length === 0) { this.taskRunner.cancel(); // User might have cancelled starting of a debug session, and in some cases the quick pick is left open await this.quickInputService.cancel(); this.endInitializingState(); this.cancelTokens(undefined); } return Promise.all(sessions.map(s => disconnect ? s.disconnect(undefined, suspend) : s.terminate())); } private async substituteVariables(launch: ILaunch | undefined, config: IConfig): Promise<IConfig | undefined> { const dbg = this.adapterManager.getDebugger(config.type); if (dbg) { let folder: IWorkspaceFolder | undefined = undefined; if (launch && launch.workspace) { folder = launch.workspace; } else { const folders = this.contextService.getWorkspace().folders; if (folders.length === 1) { folder = folders[0]; } } try { return await dbg.substituteVariables(folder, config); } catch (err) { this.showError(err.message, undefined, !!launch?.getConfiguration(config.name)); return undefined; // bail out } } return Promise.resolve(config); } private async showError(message: string, errorActions: ReadonlyArray<IAction> = [], promptLaunchJson = true): Promise<void> { const configureAction = new Action(DEBUG_CONFIGURE_COMMAND_ID, DEBUG_CONFIGURE_LABEL, undefined, true, () => this.commandService.executeCommand(DEBUG_CONFIGURE_COMMAND_ID)); // Don't append the standard command if id of any provided action indicates it is a command const actions = errorActions.filter((action) => action.id.endsWith('.command')).length > 0 ? errorActions : [...errorActions, ...(promptLaunchJson ? [configureAction] : [])]; await this.dialogService.prompt({ type: severity.Error, message, buttons: actions.map(action => ({ label: action.label, run: () => action.run() })), cancelButton: true }); } //---- focus management async focusStackFrame(_stackFrame: IStackFrame | undefined, _thread?: IThread, _session?: IDebugSession, options?: { explicit?: boolean; preserveFocus?: boolean; sideBySide?: boolean; pinned?: boolean }): Promise<void> { const { stackFrame, thread, session } = getStackFrameThreadAndSessionToFocus(this.model, _stackFrame, _thread, _session); if (stackFrame) { const editor = await stackFrame.openInEditor(this.editorService, options?.preserveFocus ?? true, options?.sideBySide, options?.pinned); if (editor) { if (editor.input === DisassemblyViewInput.instance) { // Go to address is invoked via setFocus } else { const control = editor.getControl(); if (stackFrame && isCodeEditor(control) && control.hasModel()) { const model = control.getModel(); const lineNumber = stackFrame.range.startLineNumber; if (lineNumber >= 1 && lineNumber <= model.getLineCount()) { const lineContent = control.getModel().getLineContent(lineNumber); aria.alert(nls.localize({ key: 'debuggingPaused', comment: ['First placeholder is the file line content, second placeholder is the reason why debugging is stopped, for example "breakpoint", third is the stack frame name, and last is the line number.'] }, "{0}, debugging paused {1}, {2}:{3}", lineContent, thread && thread.stoppedDetails ? `, reason ${thread.stoppedDetails.reason}` : '', stackFrame.source ? stackFrame.source.name : '', stackFrame.range.startLineNumber)); } } } } } if (session) { this.debugType.set(session.configuration.type); } else { this.debugType.reset(); } this.viewModel.setFocus(stackFrame, thread, session, !!options?.explicit); } //---- watches addWatchExpression(name?: string): void { const we = this.model.addWatchExpression(name); if (!name) { this.viewModel.setSelectedExpression(we, false); } this.debugStorage.storeWatchExpressions(this.model.getWatchExpressions()); } renameWatchExpression(id: string, newName: string): void { this.model.renameWatchExpression(id, newName); this.debugStorage.storeWatchExpressions(this.model.getWatchExpressions()); } moveWatchExpression(id: string, position: number): void { this.model.moveWatchExpression(id, position); this.debugStorage.storeWatchExpressions(this.model.getWatchExpressions()); } removeWatchExpressions(id?: string): void { this.model.removeWatchExpressions(id); this.debugStorage.storeWatchExpressions(this.model.getWatchExpressions()); } //---- breakpoints canSetBreakpointsIn(model: ITextModel): boolean { return this.adapterManager.canSetBreakpointsIn(model); } async enableOrDisableBreakpoints(enable: boolean, breakpoint?: IEnablement): Promise<void> { if (breakpoint) { this.model.setEnablement(breakpoint, enable); this.debugStorage.storeBreakpoints(this.model); if (breakpoint instanceof Breakpoint) { await this.sendBreakpoints(breakpoint.originalUri); } else if (breakpoint instanceof FunctionBreakpoint) { await this.sendFunctionBreakpoints(); } else if (breakpoint instanceof DataBreakpoint) { await this.sendDataBreakpoints(); } else if (breakpoint instanceof InstructionBreakpoint) { await this.sendInstructionBreakpoints(); } else { await this.sendExceptionBreakpoints(); } } else { this.model.enableOrDisableAllBreakpoints(enable); this.debugStorage.storeBreakpoints(this.model); await this.sendAllBreakpoints(); } this.debugStorage.storeBreakpoints(this.model); } async addBreakpoints(uri: uri, rawBreakpoints: IBreakpointData[], ariaAnnounce = true): Promise<IBreakpoint[]> { const breakpoints = this.model.addBreakpoints(uri, rawBreakpoints); if (ariaAnnounce) { breakpoints.forEach(bp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", bp.lineNumber, uri.fsPath))); } // In some cases we need to store breakpoints before we send them because sending them can take a long time // And after sending them because the debug adapter can attach adapter data to a breakpoint this.debugStorage.storeBreakpoints(this.model); await this.sendBreakpoints(uri); this.debugStorage.storeBreakpoints(this.model); return breakpoints; } async updateBreakpoints(uri: uri, data: Map<string, DebugProtocol.Breakpoint>, sendOnResourceSaved: boolean): Promise<void> { this.model.updateBreakpoints(data); this.debugStorage.storeBreakpoints(this.model); if (sendOnResourceSaved) { this.breakpointsToSendOnResourceSaved.add(uri); } else { await this.sendBreakpoints(uri); this.debugStorage.storeBreakpoints(this.model); } } async removeBreakpoints(id?: string): Promise<void> { const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id); // note: using the debugger-resolved uri for aria to reflect UI state toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath))); const urisToClear = distinct(toRemove, bp => bp.originalUri.toString()).map(bp => bp.originalUri); this.model.removeBreakpoints(toRemove); this.debugStorage.storeBreakpoints(this.model); await Promise.all(urisToClear.map(uri => this.sendBreakpoints(uri))); } setBreakpointsActivated(activated: boolean): Promise<void> { this.model.setBreakpointsActivated(activated); return this.sendAllBreakpoints(); } addFunctionBreakpoint(name?: string, id?: string): void { this.model.addFunctionBreakpoint(name || '', id); } async updateFunctionBreakpoint(id: string, update: { name?: string; hitCondition?: string; condition?: string }): Promise<void> { this.model.updateFunctionBreakpoint(id, update); this.debugStorage.storeBreakpoints(this.model); await this.sendFunctionBreakpoints(); } async removeFunctionBreakpoints(id?: string): Promise<void> { this.model.removeFunctionBreakpoints(id); this.debugStorage.storeBreakpoints(this.model); await this.sendFunctionBreakpoints(); } async addDataBreakpoint(label: string, dataId: string, canPersist: boolean, accessTypes: DebugProtocol.DataBreakpointAccessType[] | undefined, accessType: DebugProtocol.DataBreakpointAccessType): Promise<void> { this.model.addDataBreakpoint(label, dataId, canPersist, accessTypes, accessType); this.debugStorage.storeBreakpoints(this.model); await this.sendDataBreakpoints(); this.debugStorage.storeBreakpoints(this.model); } async updateDataBreakpoint(id: string, update: { hitCondition?: string; condition?: string }): Promise<void> { this.model.updateDataBreakpoint(id, update); this.debugStorage.storeBreakpoints(this.model); await this.sendDataBreakpoints(); } async removeDataBreakpoints(id?: string): Promise<void> { this.model.removeDataBreakpoints(id); this.debugStorage.storeBreakpoints(this.model); await this.sendDataBreakpoints(); } async addInstructionBreakpoint(instructionReference: string, offset: number, address: bigint, condition?: string, hitCondition?: string): Promise<void> { this.model.addInstructionBreakpoint(instructionReference, offset, address, condition, hitCondition); this.debugStorage.storeBreakpoints(this.model); await this.sendInstructionBreakpoints(); this.debugStorage.storeBreakpoints(this.model); } async removeInstructionBreakpoints(instructionReference?: string, offset?: number): Promise<void> { this.model.removeInstructionBreakpoints(instructionReference, offset); this.debugStorage.storeBreakpoints(this.model); await this.sendInstructionBreakpoints(); } setExceptionBreakpointFallbackSession(sessionId: string) { this.model.setExceptionBreakpointFallbackSession(sessionId); this.debugStorage.storeBreakpoints(this.model); } setExceptionBreakpointsForSession(session: IDebugSession, data: DebugProtocol.ExceptionBreakpointsFilter[]): void { this.model.setExceptionBreakpointsForSession(session.getId(), data); this.debugStorage.storeBreakpoints(this.model); } async setExceptionBreakpointCondition(exceptionBreakpoint: IExceptionBreakpoint, condition: string | undefined): Promise<void> { this.model.setExceptionBreakpointCondition(exceptionBreakpoint, condition); this.debugStorage.storeBreakpoints(this.model); await this.sendExceptionBreakpoints(); } async sendAllBreakpoints(session?: IDebugSession): Promise<any> { const setBreakpointsPromises = distinct(this.model.getBreakpoints(), bp => bp.originalUri.toString()) .map(bp => this.sendBreakpoints(bp.originalUri, false, session)); // If sending breakpoints to one session which we know supports the configurationDone request, can make all requests in parallel if (session?.capabilities.supportsConfigurationDoneRequest) { await Promise.all([ ...setBreakpointsPromises, this.sendFunctionBreakpoints(session), this.sendDataBreakpoints(session), this.sendInstructionBreakpoints(session), this.sendExceptionBreakpoints(session), ]); } else { await Promise.all(setBreakpointsPromises); await this.sendFunctionBreakpoints(session); await this.sendDataBreakpoints(session); await this.sendInstructionBreakpoints(session); // send exception breakpoints at the end since some debug adapters may rely on the order - this was the case before // the configurationDone request was introduced. await this.sendExceptionBreakpoints(session); } } private async sendBreakpoints(modelUri: uri, sourceModified = false, session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getBreakpoints({ originalUri: modelUri, enabledOnly: true }); await sendToOneOrAllSessions(this.model, session, async s => { if (!s.configuration.noDebug) { await s.sendBreakpoints(modelUri, breakpointsToSend, sourceModified); } }); } private async sendFunctionBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); await sendToOneOrAllSessions(this.model, session, async s => { if (s.capabilities.supportsFunctionBreakpoints && !s.configuration.noDebug) { await s.sendFunctionBreakpoints(breakpointsToSend); } }); } private async sendDataBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getDataBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); await sendToOneOrAllSessions(this.model, session, async s => { if (s.capabilities.supportsDataBreakpoints && !s.configuration.noDebug) { await s.sendDataBreakpoints(breakpointsToSend); } }); } private async sendInstructionBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getInstructionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); await sendToOneOrAllSessions(this.model, session, async s => { if (s.capabilities.supportsInstructionBreakpoints && !s.configuration.noDebug) { await s.sendInstructionBreakpoints(breakpointsToSend); } }); } private sendExceptionBreakpoints(session?: IDebugSession): Promise<void> { return sendToOneOrAllSessions(this.model, session, async s => { const enabledExceptionBps = this.model.getExceptionBreakpointsForSession(s.getId()).filter(exb => exb.enabled); if (s.capabilities.supportsConfigurationDoneRequest && (!s.capabilities.exceptionBreakpointFilters || s.capabilities.exceptionBreakpointFilters.length === 0)) { // Only call `setExceptionBreakpoints` as specified in dap protocol #90001 return; } if (!s.configuration.noDebug) { await s.sendExceptionBreakpoints(enabledExceptionBps); } }); } private onFileChanges(fileChangesEvent: FileChangesEvent): void { const toRemove = this.model.getBreakpoints().filter(bp => fileChangesEvent.contains(bp.originalUri, FileChangeType.DELETED)); if (toRemove.length) { this.model.removeBreakpoints(toRemove); } const toSend: URI[] = []; for (const uri of this.breakpointsToSendOnResourceSaved) { if (fileChangesEvent.contains(uri, FileChangeType.UPDATED)) { toSend.push(uri); } } for (const uri of toSend) { this.breakpointsToSendOnResourceSaved.delete(uri); this.sendBreakpoints(uri, true); } } async runTo(uri: uri, lineNumber: number, column?: number): Promise<void> { let breakpointToRemove: IBreakpoint | undefined; let threadToContinue = this.getViewModel().focusedThread; const addTempBreakPoint = async () => { const bpExists = !!(this.getModel().getBreakpoints({ column, lineNumber, uri }).length); if (!bpExists) { const addResult = await this.addAndValidateBreakpoints(uri, lineNumber, column); if (addResult.thread) { threadToContinue = addResult.thread; } if (addResult.breakpoint) { breakpointToRemove = addResult.breakpoint; } } return { threadToContinue, breakpointToRemove }; }; const removeTempBreakPoint = (state: State): boolean => { if (state === State.Stopped || state === State.Inactive) { if (breakpointToRemove) { this.removeBreakpoints(breakpointToRemove.getId()); } return true; } return false; }; await addTempBreakPoint(); if (this.state === State.Inactive) { // If no session exists start the debugger const { launch, name, getConfig } = this.getConfigurationManager().selectedConfiguration; const config = await getConfig(); const configOrName = config ? Object.assign(deepClone(config), {}) : name; const listener = this.onDidChangeState(state => { if (removeTempBreakPoint(state)) { listener.dispose(); } }); await this.startDebugging(launch, configOrName, undefined, true); } if (this.state === State.Stopped) { const focusedSession = this.getViewModel().focusedSession; if (!focusedSession || !threadToContinue) { return; } const listener = threadToContinue.session.onDidChangeState(() => { if (removeTempBreakPoint(focusedSession.state)) { listener.dispose(); } }); await threadToContinue.continue(); } } private async addAndValidateBreakpoints(uri: URI, lineNumber: number, column?: number) { const debugModel = this.getModel(); const viewModel = this.getViewModel(); const breakpoints = await this.addBreakpoints(uri, [{ lineNumber, column }], false); const breakpoint = breakpoints?.[0]; if (!breakpoint) { return { breakpoint: undefined, thread: viewModel.focusedThread }; } // If the breakpoint was not initially verified, wait up to 2s for it to become so. // Inherently racey if multiple sessions can verify async, but not solvable... if (!breakpoint.verified) { let listener: IDisposable; await raceTimeout(new Promise<void>(resolve => { listener = debugModel.onDidChangeBreakpoints(() => { if (breakpoint.verified) { resolve(); } }); }), 2000); listener!.dispose(); } // Look at paused threads for sessions that verified this bp. Prefer, in order: const enum Score { /** The focused thread */ Focused, /** Any other stopped thread of a session that verified the bp */ Verified, /** Any thread that verified and paused in the same file */ VerifiedAndPausedInFile, /** The focused thread if it verified the breakpoint */ VerifiedAndFocused, } let bestThread = viewModel.focusedThread; let bestScore = Score.Focused; for (const sessionId of breakpoint.sessionsThatVerified) { const session = debugModel.getSession(sessionId); if (!session) { continue; } const threads = session.getAllThreads().filter(t => t.stopped); if (bestScore < Score.VerifiedAndFocused) { if (viewModel.focusedThread && threads.includes(viewModel.focusedThread)) { bestThread = viewModel.focusedThread; bestScore = Score.VerifiedAndFocused; } } if (bestScore < Score.VerifiedAndPausedInFile) { const pausedInThisFile = threads.find(t => { const top = t.getTopStackFrame(); return top && this.uriIdentityService.extUri.isEqual(top.source.uri, uri); }); if (pausedInThisFile) { bestThread = pausedInThisFile; bestScore = Score.VerifiedAndPausedInFile; } } if (bestScore < Score.Verified) { bestThread = threads[0]; bestScore = Score.VerifiedAndPausedInFile; } } return { thread: bestThread, breakpoint }; } } export function getStackFrameThreadAndSessionToFocus(model: IDebugModel, stackFrame: IStackFrame | undefined, thread?: IThread, session?: IDebugSession, avoidSession?: IDebugSession): { stackFrame: IStackFrame | undefined; thread: IThread | undefined; session: IDebugSession | undefined } { if (!session) { if (stackFrame || thread) { session = stackFrame ? stackFrame.thread.session : thread!.session; } else { const sessions = model.getSessions(); const stoppedSession = sessions.find(s => s.state === State.Stopped); // Make sure to not focus session that is going down session = stoppedSession || sessions.find(s => s !== avoidSession && s !== avoidSession?.parentSession) || (sessions.length ? sessions[0] : undefined); } } if (!thread) { if (stackFrame) { thread = stackFrame.thread; } else { const threads = session ? session.getAllThreads() : undefined; const stoppedThread = threads && threads.find(t => t.stopped); thread = stoppedThread || (threads && threads.length ? threads[0] : undefined); } } if (!stackFrame && thread) { stackFrame = thread.getTopStackFrame(); } return { session, thread, stackFrame }; } async function sendToOneOrAllSessions(model: DebugModel, session: IDebugSession | undefined, send: (session: IDebugSession) => Promise<void>): Promise<void> { if (session) { await send(session); } else { await Promise.all(model.getSessions().map(s => send(s))); } }
src/vs/workbench/contrib/debug/browser/debugService.ts
1
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
[ 0.9937756061553955, 0.03104107268154621, 0.00016124063404276967, 0.0002553514204919338, 0.15569756925106049 ]
{ "id": 2, "code_window": [ "import { ConfigurationManager } from 'vs/workbench/contrib/debug/browser/debugConfigurationManager';\n", "import { DebugMemoryFileSystemProvider } from 'vs/workbench/contrib/debug/browser/debugMemory';\n", "import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession';\n", "import { DebugTaskRunner, TaskRunResult } from 'vs/workbench/contrib/debug/browser/debugTaskRunner';\n", "import { CALLSTACK_VIEW_ID, CONTEXT_BREAKPOINTS_EXIST, CONTEXT_HAS_DEBUGGED, CONTEXT_DEBUG_STATE, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_UX, CONTEXT_DISASSEMBLY_VIEW_FOCUS, CONTEXT_IN_DEBUG_MODE, debuggerDisabledMessage, DEBUG_MEMORY_SCHEME, getStateLabel, IAdapterManager, IBreakpoint, IBreakpointData, ICompound, IConfig, IConfigurationManager, IDebugConfiguration, IDebugModel, IDebugService, IDebugSession, IDebugSessionOptions, IEnablement, IExceptionBreakpoint, IGlobalConfig, ILaunch, IStackFrame, IThread, IViewModel, REPL_VIEW_ID, State, VIEWLET_ID } from 'vs/workbench/contrib/debug/common/debug';\n", "import { DebugCompoundRoot } from 'vs/workbench/contrib/debug/common/debugCompoundRoot';\n", "import { Debugger } from 'vs/workbench/contrib/debug/common/debugger';\n", "import { Breakpoint, DataBreakpoint, DebugModel, FunctionBreakpoint, InstructionBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { CALLSTACK_VIEW_ID, CONTEXT_BREAKPOINTS_EXIST, CONTEXT_HAS_DEBUGGED, CONTEXT_DEBUG_STATE, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_UX, CONTEXT_DISASSEMBLY_VIEW_FOCUS, CONTEXT_IN_DEBUG_MODE, debuggerDisabledMessage, DEBUG_MEMORY_SCHEME, getStateLabel, IAdapterManager, IBreakpoint, IBreakpointData, ICompound, IConfig, IConfigurationManager, IDebugConfiguration, IDebugModel, IDebugService, IDebugSession, IDebugSessionOptions, IEnablement, IExceptionBreakpoint, IGlobalConfig, ILaunch, IStackFrame, IThread, IViewModel, REPL_VIEW_ID, State, VIEWLET_ID, DEBUG_SCHEME } from 'vs/workbench/contrib/debug/common/debug';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 41 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 "@types/[email protected]": version "18.15.13" resolved "https://registry.yarnpkg.com/@types/node/-/node-18.15.13.tgz#f64277c341150c979e42b00e4ac289290c9df469" integrity sha512-N+0kuo9KgrUQ1Sn/ifDXsvg0TTleP7rIy4zOBGECxAljqvqfqpTfzx0Q1NUedOixRMBfe2Whhb056a42cWs26Q==
extensions/jake/yarn.lock
0
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
[ 0.000165010045748204, 0.000165010045748204, 0.000165010045748204, 0.000165010045748204, 0 ]
{ "id": 2, "code_window": [ "import { ConfigurationManager } from 'vs/workbench/contrib/debug/browser/debugConfigurationManager';\n", "import { DebugMemoryFileSystemProvider } from 'vs/workbench/contrib/debug/browser/debugMemory';\n", "import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession';\n", "import { DebugTaskRunner, TaskRunResult } from 'vs/workbench/contrib/debug/browser/debugTaskRunner';\n", "import { CALLSTACK_VIEW_ID, CONTEXT_BREAKPOINTS_EXIST, CONTEXT_HAS_DEBUGGED, CONTEXT_DEBUG_STATE, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_UX, CONTEXT_DISASSEMBLY_VIEW_FOCUS, CONTEXT_IN_DEBUG_MODE, debuggerDisabledMessage, DEBUG_MEMORY_SCHEME, getStateLabel, IAdapterManager, IBreakpoint, IBreakpointData, ICompound, IConfig, IConfigurationManager, IDebugConfiguration, IDebugModel, IDebugService, IDebugSession, IDebugSessionOptions, IEnablement, IExceptionBreakpoint, IGlobalConfig, ILaunch, IStackFrame, IThread, IViewModel, REPL_VIEW_ID, State, VIEWLET_ID } from 'vs/workbench/contrib/debug/common/debug';\n", "import { DebugCompoundRoot } from 'vs/workbench/contrib/debug/common/debugCompoundRoot';\n", "import { Debugger } from 'vs/workbench/contrib/debug/common/debugger';\n", "import { Breakpoint, DataBreakpoint, DebugModel, FunctionBreakpoint, InstructionBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { CALLSTACK_VIEW_ID, CONTEXT_BREAKPOINTS_EXIST, CONTEXT_HAS_DEBUGGED, CONTEXT_DEBUG_STATE, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_UX, CONTEXT_DISASSEMBLY_VIEW_FOCUS, CONTEXT_IN_DEBUG_MODE, debuggerDisabledMessage, DEBUG_MEMORY_SCHEME, getStateLabel, IAdapterManager, IBreakpoint, IBreakpointData, ICompound, IConfig, IConfigurationManager, IDebugConfiguration, IDebugModel, IDebugService, IDebugSession, IDebugSessionOptions, IEnablement, IExceptionBreakpoint, IGlobalConfig, ILaunch, IStackFrame, IThread, IViewModel, REPL_VIEW_ID, State, VIEWLET_ID, DEBUG_SCHEME } from 'vs/workbench/contrib/debug/common/debug';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 41 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as http from 'http'; export class IPCClient { private ipcHandlePath: string; constructor(private handlerName: string) { const ipcHandlePath = process.env['VSCODE_GIT_IPC_HANDLE']; if (!ipcHandlePath) { throw new Error('Missing VSCODE_GIT_IPC_HANDLE'); } this.ipcHandlePath = ipcHandlePath; } call(request: any): Promise<any> { const opts: http.RequestOptions = { socketPath: this.ipcHandlePath, path: `/${this.handlerName}`, method: 'POST' }; return new Promise((c, e) => { const req = http.request(opts, res => { if (res.statusCode !== 200) { return e(new Error(`Bad status code: ${res.statusCode}`)); } const chunks: Buffer[] = []; res.on('data', d => chunks.push(d)); res.on('end', () => c(JSON.parse(Buffer.concat(chunks).toString('utf8')))); }); req.on('error', err => e(err)); req.write(JSON.stringify(request)); req.end(); }); } }
extensions/git/src/ipc/ipcClient.ts
0
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
[ 0.00016840206808410585, 0.00016711527132429183, 0.00016564771067351103, 0.0001671889767749235, 9.435300398763502e-7 ]
{ "id": 2, "code_window": [ "import { ConfigurationManager } from 'vs/workbench/contrib/debug/browser/debugConfigurationManager';\n", "import { DebugMemoryFileSystemProvider } from 'vs/workbench/contrib/debug/browser/debugMemory';\n", "import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession';\n", "import { DebugTaskRunner, TaskRunResult } from 'vs/workbench/contrib/debug/browser/debugTaskRunner';\n", "import { CALLSTACK_VIEW_ID, CONTEXT_BREAKPOINTS_EXIST, CONTEXT_HAS_DEBUGGED, CONTEXT_DEBUG_STATE, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_UX, CONTEXT_DISASSEMBLY_VIEW_FOCUS, CONTEXT_IN_DEBUG_MODE, debuggerDisabledMessage, DEBUG_MEMORY_SCHEME, getStateLabel, IAdapterManager, IBreakpoint, IBreakpointData, ICompound, IConfig, IConfigurationManager, IDebugConfiguration, IDebugModel, IDebugService, IDebugSession, IDebugSessionOptions, IEnablement, IExceptionBreakpoint, IGlobalConfig, ILaunch, IStackFrame, IThread, IViewModel, REPL_VIEW_ID, State, VIEWLET_ID } from 'vs/workbench/contrib/debug/common/debug';\n", "import { DebugCompoundRoot } from 'vs/workbench/contrib/debug/common/debugCompoundRoot';\n", "import { Debugger } from 'vs/workbench/contrib/debug/common/debugger';\n", "import { Breakpoint, DataBreakpoint, DebugModel, FunctionBreakpoint, InstructionBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { CALLSTACK_VIEW_ID, CONTEXT_BREAKPOINTS_EXIST, CONTEXT_HAS_DEBUGGED, CONTEXT_DEBUG_STATE, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_UX, CONTEXT_DISASSEMBLY_VIEW_FOCUS, CONTEXT_IN_DEBUG_MODE, debuggerDisabledMessage, DEBUG_MEMORY_SCHEME, getStateLabel, IAdapterManager, IBreakpoint, IBreakpointData, ICompound, IConfig, IConfigurationManager, IDebugConfiguration, IDebugModel, IDebugService, IDebugSession, IDebugSessionOptions, IEnablement, IExceptionBreakpoint, IGlobalConfig, ILaunch, IStackFrame, IThread, IViewModel, REPL_VIEW_ID, State, VIEWLET_ID, DEBUG_SCHEME } from 'vs/workbench/contrib/debug/common/debug';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 41 }
{ "displayName": "Markdown Math", "description": "Adds math support to Markdown in notebooks.", "config.markdown.math.enabled": "Enable/disable rendering math in the built-in Markdown preview.", "config.markdown.math.macros": "A collection of custom macros. Each macro is a key-value pair where the key is a new command name and the value is the expansion of the macro." }
extensions/markdown-math/package.nls.json
0
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
[ 0.000165652934811078, 0.000165652934811078, 0.000165652934811078, 0.000165652934811078, 0 ]
{ "id": 3, "code_window": [ "import { DebugCompoundRoot } from 'vs/workbench/contrib/debug/common/debugCompoundRoot';\n", "import { Debugger } from 'vs/workbench/contrib/debug/common/debugger';\n", "import { Breakpoint, DataBreakpoint, DebugModel, FunctionBreakpoint, InstructionBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel';\n", "import { DebugStorage } from 'vs/workbench/contrib/debug/common/debugStorage';\n", "import { DebugTelemetry } from 'vs/workbench/contrib/debug/common/debugTelemetry';\n", "import { getExtensionHostDebugSession, saveAllBeforeDebugStart } from 'vs/workbench/contrib/debug/common/debugUtils';\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { Source } from 'vs/workbench/contrib/debug/common/debugSource';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "add", "edit_start_line_idx": 45 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import { FileAccess } from 'vs/base/common/network'; import { isMacintosh, isWeb } from 'vs/base/common/platform'; import { URI } from 'vs/base/common/uri'; import 'vs/css!./media/debug.contribution'; import 'vs/css!./media/debugHover'; import { EditorContributionInstantiation, registerEditorContribution } from 'vs/editor/browser/editorExtensions'; import * as nls from 'vs/nls'; import { ICommandActionTitle, Icon } from 'vs/platform/action/common/action'; import { MenuId, MenuRegistry } from 'vs/platform/actions/common/actions'; import { ConfigurationScope, Extensions as ConfigurationExtensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry'; import { ContextKeyExpr, ContextKeyExpression } from 'vs/platform/contextkey/common/contextkey'; import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { Extensions as QuickAccessExtensions, IQuickAccessRegistry } from 'vs/platform/quickinput/common/quickAccess'; import { Registry } from 'vs/platform/registry/common/platform'; import { EditorPaneDescriptor, IEditorPaneRegistry } from 'vs/workbench/browser/editor'; import { ViewPaneContainer } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { Extensions as WorkbenchExtensions, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions'; import { EditorExtensions } from 'vs/workbench/common/editor'; import { Extensions as ViewExtensions, IViewContainersRegistry, IViewsRegistry, ViewContainer, ViewContainerLocation } from 'vs/workbench/common/views'; import { BreakpointEditorContribution } from 'vs/workbench/contrib/debug/browser/breakpointEditorContribution'; import { BreakpointsView } from 'vs/workbench/contrib/debug/browser/breakpointsView'; import { CallStackEditorContribution } from 'vs/workbench/contrib/debug/browser/callStackEditorContribution'; import { CallStackView } from 'vs/workbench/contrib/debug/browser/callStackView'; import { registerColors } from 'vs/workbench/contrib/debug/browser/debugColors'; import { ADD_CONFIGURATION_ID, CALLSTACK_BOTTOM_ID, CALLSTACK_BOTTOM_LABEL, CALLSTACK_DOWN_ID, CALLSTACK_DOWN_LABEL, CALLSTACK_TOP_ID, CALLSTACK_TOP_LABEL, CALLSTACK_UP_ID, CALLSTACK_UP_LABEL, CONTINUE_ID, CONTINUE_LABEL, COPY_STACK_TRACE_ID, DEBUG_COMMAND_CATEGORY, DEBUG_CONSOLE_QUICK_ACCESS_PREFIX, DEBUG_QUICK_ACCESS_PREFIX, DEBUG_RUN_COMMAND_ID, DEBUG_RUN_LABEL, DEBUG_START_COMMAND_ID, DEBUG_START_LABEL, DISCONNECT_AND_SUSPEND_ID, DISCONNECT_AND_SUSPEND_LABEL, DISCONNECT_ID, DISCONNECT_LABEL, EDIT_EXPRESSION_COMMAND_ID, FOCUS_REPL_ID, JUMP_TO_CURSOR_ID, NEXT_DEBUG_CONSOLE_ID, NEXT_DEBUG_CONSOLE_LABEL, OPEN_LOADED_SCRIPTS_LABEL, PAUSE_ID, PAUSE_LABEL, PREV_DEBUG_CONSOLE_ID, PREV_DEBUG_CONSOLE_LABEL, REMOVE_EXPRESSION_COMMAND_ID, RESTART_FRAME_ID, RESTART_LABEL, RESTART_SESSION_ID, SELECT_AND_START_ID, SELECT_AND_START_LABEL, SELECT_DEBUG_CONSOLE_ID, SELECT_DEBUG_CONSOLE_LABEL, SELECT_DEBUG_SESSION_ID, SELECT_DEBUG_SESSION_LABEL, SET_EXPRESSION_COMMAND_ID, SHOW_LOADED_SCRIPTS_ID, STEP_INTO_ID, STEP_INTO_LABEL, STEP_INTO_TARGET_ID, STEP_INTO_TARGET_LABEL, STEP_OUT_ID, STEP_OUT_LABEL, STEP_OVER_ID, STEP_OVER_LABEL, STOP_ID, STOP_LABEL, TERMINATE_THREAD_ID, TOGGLE_INLINE_BREAKPOINT_ID } from 'vs/workbench/contrib/debug/browser/debugCommands'; import { DebugConsoleQuickAccess } from 'vs/workbench/contrib/debug/browser/debugConsoleQuickAccess'; import { RunToCursorAction, SelectionToReplAction, SelectionToWatchExpressionsAction } from 'vs/workbench/contrib/debug/browser/debugEditorActions'; import { DebugEditorContribution } from 'vs/workbench/contrib/debug/browser/debugEditorContribution'; import * as icons from 'vs/workbench/contrib/debug/browser/debugIcons'; import { DebugProgressContribution } from 'vs/workbench/contrib/debug/browser/debugProgress'; import { StartDebugQuickAccessProvider } from 'vs/workbench/contrib/debug/browser/debugQuickAccess'; import { DebugService } from 'vs/workbench/contrib/debug/browser/debugService'; import { DebugStatusContribution } from 'vs/workbench/contrib/debug/browser/debugStatus'; import { DebugTitleContribution } from 'vs/workbench/contrib/debug/browser/debugTitle'; import { DebugToolBar } from 'vs/workbench/contrib/debug/browser/debugToolBar'; import { DebugViewPaneContainer } from 'vs/workbench/contrib/debug/browser/debugViewlet'; import { DisassemblyView, DisassemblyViewContribution } from 'vs/workbench/contrib/debug/browser/disassemblyView'; import { LoadedScriptsView } from 'vs/workbench/contrib/debug/browser/loadedScriptsView'; import { Repl } from 'vs/workbench/contrib/debug/browser/repl'; import { StatusBarColorProvider } from 'vs/workbench/contrib/debug/browser/statusbarColorProvider'; import { ADD_TO_WATCH_ID, BREAK_WHEN_VALUE_CHANGES_ID, BREAK_WHEN_VALUE_IS_ACCESSED_ID, BREAK_WHEN_VALUE_IS_READ_ID, COPY_EVALUATE_PATH_ID, COPY_VALUE_ID, SET_VARIABLE_ID, VariablesView, VIEW_MEMORY_ID } from 'vs/workbench/contrib/debug/browser/variablesView'; import { ADD_WATCH_ID, ADD_WATCH_LABEL, REMOVE_WATCH_EXPRESSIONS_COMMAND_ID, REMOVE_WATCH_EXPRESSIONS_LABEL, WatchExpressionsView } from 'vs/workbench/contrib/debug/browser/watchExpressionsView'; import { WelcomeView } from 'vs/workbench/contrib/debug/browser/welcomeView'; import { BREAKPOINTS_VIEW_ID, BREAKPOINT_EDITOR_CONTRIBUTION_ID, CALLSTACK_VIEW_ID, CONTEXT_BREAKPOINTS_EXIST, CONTEXT_BREAK_WHEN_VALUE_CHANGES_SUPPORTED, CONTEXT_BREAK_WHEN_VALUE_IS_ACCESSED_SUPPORTED, CONTEXT_BREAK_WHEN_VALUE_IS_READ_SUPPORTED, CONTEXT_CALLSTACK_ITEM_TYPE, CONTEXT_CAN_VIEW_MEMORY, CONTEXT_DEBUGGERS_AVAILABLE, CONTEXT_DEBUG_STATE, CONTEXT_DEBUG_UX, CONTEXT_FOCUSED_SESSION_IS_ATTACH, CONTEXT_HAS_DEBUGGED, CONTEXT_IN_DEBUG_MODE, CONTEXT_JUMP_TO_CURSOR_SUPPORTED, CONTEXT_LOADED_SCRIPTS_SUPPORTED, CONTEXT_RESTART_FRAME_SUPPORTED, CONTEXT_SET_EXPRESSION_SUPPORTED, CONTEXT_SET_VARIABLE_SUPPORTED, CONTEXT_STACK_FRAME_SUPPORTS_RESTART, CONTEXT_STEP_INTO_TARGETS_SUPPORTED, CONTEXT_SUSPEND_DEBUGGEE_SUPPORTED, CONTEXT_TERMINATE_DEBUGGEE_SUPPORTED, CONTEXT_VARIABLE_EVALUATE_NAME_PRESENT, CONTEXT_VARIABLE_IS_READONLY, CONTEXT_WATCH_ITEM_TYPE, DEBUG_PANEL_ID, DISASSEMBLY_VIEW_ID, EDITOR_CONTRIBUTION_ID, getStateLabel, IDebugService, INTERNAL_CONSOLE_OPTIONS_SCHEMA, LOADED_SCRIPTS_VIEW_ID, REPL_VIEW_ID, State, VARIABLES_VIEW_ID, VIEWLET_ID, WATCH_VIEW_ID } from 'vs/workbench/contrib/debug/common/debug'; import { DebugContentProvider } from 'vs/workbench/contrib/debug/common/debugContentProvider'; import { DebugLifecycle } from 'vs/workbench/contrib/debug/common/debugLifecycle'; import { DisassemblyViewInput } from 'vs/workbench/contrib/debug/common/disassemblyViewInput'; import { launchSchemaId } from 'vs/workbench/services/configuration/common/configuration'; import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle'; const debugCategory = nls.localize('debugCategory', "Debug"); registerColors(); registerSingleton(IDebugService, DebugService, InstantiationType.Delayed); // Register Debug Workbench Contributions Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(DebugStatusContribution, LifecyclePhase.Eventually); Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(DebugProgressContribution, LifecyclePhase.Eventually); if (isWeb) { Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(DebugTitleContribution, LifecyclePhase.Eventually); } Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(DebugToolBar, LifecyclePhase.Restored); Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(DebugContentProvider, LifecyclePhase.Eventually); Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(StatusBarColorProvider, LifecyclePhase.Eventually); Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(DisassemblyViewContribution, LifecyclePhase.Eventually); Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(DebugLifecycle, LifecyclePhase.Eventually); // Register Quick Access Registry.as<IQuickAccessRegistry>(QuickAccessExtensions.Quickaccess).registerQuickAccessProvider({ ctor: StartDebugQuickAccessProvider, prefix: DEBUG_QUICK_ACCESS_PREFIX, contextKey: 'inLaunchConfigurationsPicker', placeholder: nls.localize('startDebugPlaceholder', "Type the name of a launch configuration to run."), helpEntries: [{ description: nls.localize('startDebuggingHelp', "Start Debugging"), commandId: SELECT_AND_START_ID, commandCenterOrder: 50 }] }); // Register quick access for debug console Registry.as<IQuickAccessRegistry>(QuickAccessExtensions.Quickaccess).registerQuickAccessProvider({ ctor: DebugConsoleQuickAccess, prefix: DEBUG_CONSOLE_QUICK_ACCESS_PREFIX, contextKey: 'inDebugConsolePicker', placeholder: nls.localize('tasksQuickAccessPlaceholder', "Type the name of a debug console to open."), helpEntries: [{ description: nls.localize('tasksQuickAccessHelp', "Show All Debug Consoles"), commandId: SELECT_DEBUG_CONSOLE_ID }] }); registerEditorContribution('editor.contrib.callStack', CallStackEditorContribution, EditorContributionInstantiation.AfterFirstRender); registerEditorContribution(BREAKPOINT_EDITOR_CONTRIBUTION_ID, BreakpointEditorContribution, EditorContributionInstantiation.AfterFirstRender); registerEditorContribution(EDITOR_CONTRIBUTION_ID, DebugEditorContribution, EditorContributionInstantiation.BeforeFirstInteraction); const registerDebugCommandPaletteItem = (id: string, title: ICommandActionTitle, when?: ContextKeyExpression, precondition?: ContextKeyExpression) => { MenuRegistry.appendMenuItem(MenuId.CommandPalette, { when: ContextKeyExpr.and(CONTEXT_DEBUGGERS_AVAILABLE, when), group: debugCategory, command: { id, title, category: DEBUG_COMMAND_CATEGORY, precondition } }); }; registerDebugCommandPaletteItem(RESTART_SESSION_ID, RESTART_LABEL); registerDebugCommandPaletteItem(TERMINATE_THREAD_ID, nls.localize2('terminateThread', "Terminate Thread"), CONTEXT_IN_DEBUG_MODE); registerDebugCommandPaletteItem(STEP_OVER_ID, STEP_OVER_LABEL, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('stopped')); registerDebugCommandPaletteItem(STEP_INTO_ID, STEP_INTO_LABEL, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('stopped')); registerDebugCommandPaletteItem(STEP_INTO_TARGET_ID, STEP_INTO_TARGET_LABEL, CONTEXT_IN_DEBUG_MODE, ContextKeyExpr.and(CONTEXT_STEP_INTO_TARGETS_SUPPORTED, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('stopped'))); registerDebugCommandPaletteItem(STEP_OUT_ID, STEP_OUT_LABEL, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('stopped')); registerDebugCommandPaletteItem(PAUSE_ID, PAUSE_LABEL, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('running')); registerDebugCommandPaletteItem(DISCONNECT_ID, DISCONNECT_LABEL, CONTEXT_IN_DEBUG_MODE, ContextKeyExpr.or(CONTEXT_FOCUSED_SESSION_IS_ATTACH, CONTEXT_TERMINATE_DEBUGGEE_SUPPORTED)); registerDebugCommandPaletteItem(DISCONNECT_AND_SUSPEND_ID, DISCONNECT_AND_SUSPEND_LABEL, CONTEXT_IN_DEBUG_MODE, ContextKeyExpr.or(CONTEXT_FOCUSED_SESSION_IS_ATTACH, ContextKeyExpr.and(CONTEXT_SUSPEND_DEBUGGEE_SUPPORTED, CONTEXT_TERMINATE_DEBUGGEE_SUPPORTED))); registerDebugCommandPaletteItem(STOP_ID, STOP_LABEL, CONTEXT_IN_DEBUG_MODE, ContextKeyExpr.or(CONTEXT_FOCUSED_SESSION_IS_ATTACH.toNegated(), CONTEXT_TERMINATE_DEBUGGEE_SUPPORTED)); registerDebugCommandPaletteItem(CONTINUE_ID, CONTINUE_LABEL, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('stopped')); registerDebugCommandPaletteItem(FOCUS_REPL_ID, nls.localize2({ comment: ['Debug is a noun in this context, not a verb.'], key: 'debugFocusConsole' }, "Focus on Debug Console View")); registerDebugCommandPaletteItem(JUMP_TO_CURSOR_ID, nls.localize2('jumpToCursor', "Jump to Cursor"), CONTEXT_JUMP_TO_CURSOR_SUPPORTED); registerDebugCommandPaletteItem(JUMP_TO_CURSOR_ID, nls.localize2('SetNextStatement', "Set Next Statement"), CONTEXT_JUMP_TO_CURSOR_SUPPORTED); registerDebugCommandPaletteItem(RunToCursorAction.ID, RunToCursorAction.LABEL, CONTEXT_DEBUGGERS_AVAILABLE); registerDebugCommandPaletteItem(SelectionToReplAction.ID, SelectionToReplAction.LABEL, CONTEXT_IN_DEBUG_MODE); registerDebugCommandPaletteItem(SelectionToWatchExpressionsAction.ID, SelectionToWatchExpressionsAction.LABEL); registerDebugCommandPaletteItem(TOGGLE_INLINE_BREAKPOINT_ID, nls.localize2('inlineBreakpoint', "Inline Breakpoint")); registerDebugCommandPaletteItem(DEBUG_START_COMMAND_ID, DEBUG_START_LABEL, ContextKeyExpr.and(CONTEXT_DEBUGGERS_AVAILABLE, CONTEXT_DEBUG_STATE.notEqualsTo(getStateLabel(State.Initializing)))); registerDebugCommandPaletteItem(DEBUG_RUN_COMMAND_ID, DEBUG_RUN_LABEL, ContextKeyExpr.and(CONTEXT_DEBUGGERS_AVAILABLE, CONTEXT_DEBUG_STATE.notEqualsTo(getStateLabel(State.Initializing)))); registerDebugCommandPaletteItem(SELECT_AND_START_ID, SELECT_AND_START_LABEL, ContextKeyExpr.and(CONTEXT_DEBUGGERS_AVAILABLE, CONTEXT_DEBUG_STATE.notEqualsTo(getStateLabel(State.Initializing)))); registerDebugCommandPaletteItem(NEXT_DEBUG_CONSOLE_ID, NEXT_DEBUG_CONSOLE_LABEL); registerDebugCommandPaletteItem(PREV_DEBUG_CONSOLE_ID, PREV_DEBUG_CONSOLE_LABEL); registerDebugCommandPaletteItem(SHOW_LOADED_SCRIPTS_ID, OPEN_LOADED_SCRIPTS_LABEL, CONTEXT_IN_DEBUG_MODE); registerDebugCommandPaletteItem(SELECT_DEBUG_CONSOLE_ID, SELECT_DEBUG_CONSOLE_LABEL); registerDebugCommandPaletteItem(SELECT_DEBUG_SESSION_ID, SELECT_DEBUG_SESSION_LABEL); registerDebugCommandPaletteItem(CALLSTACK_TOP_ID, CALLSTACK_TOP_LABEL, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('stopped')); registerDebugCommandPaletteItem(CALLSTACK_BOTTOM_ID, CALLSTACK_BOTTOM_LABEL, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('stopped')); registerDebugCommandPaletteItem(CALLSTACK_UP_ID, CALLSTACK_UP_LABEL, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('stopped')); registerDebugCommandPaletteItem(CALLSTACK_DOWN_ID, CALLSTACK_DOWN_LABEL, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('stopped')); // Debug callstack context menu const registerDebugViewMenuItem = (menuId: MenuId, id: string, title: string | ICommandActionTitle, order: number, when?: ContextKeyExpression, precondition?: ContextKeyExpression, group = 'navigation', icon?: Icon) => { MenuRegistry.appendMenuItem(menuId, { group, when, order, icon, command: { id, title, icon, precondition } }); }; registerDebugViewMenuItem(MenuId.DebugCallStackContext, RESTART_SESSION_ID, RESTART_LABEL, 10, CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('session'), undefined, '3_modification'); registerDebugViewMenuItem(MenuId.DebugCallStackContext, DISCONNECT_ID, DISCONNECT_LABEL, 20, CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('session'), undefined, '3_modification'); registerDebugViewMenuItem(MenuId.DebugCallStackContext, DISCONNECT_AND_SUSPEND_ID, DISCONNECT_AND_SUSPEND_LABEL, 21, ContextKeyExpr.and(CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('session'), CONTEXT_SUSPEND_DEBUGGEE_SUPPORTED, CONTEXT_TERMINATE_DEBUGGEE_SUPPORTED), undefined, '3_modification'); registerDebugViewMenuItem(MenuId.DebugCallStackContext, STOP_ID, STOP_LABEL, 30, CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('session'), undefined, '3_modification'); registerDebugViewMenuItem(MenuId.DebugCallStackContext, PAUSE_ID, PAUSE_LABEL, 10, ContextKeyExpr.and(CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('thread'), CONTEXT_DEBUG_STATE.isEqualTo('running'))); registerDebugViewMenuItem(MenuId.DebugCallStackContext, CONTINUE_ID, CONTINUE_LABEL, 10, ContextKeyExpr.and(CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('thread'), CONTEXT_DEBUG_STATE.isEqualTo('stopped'))); registerDebugViewMenuItem(MenuId.DebugCallStackContext, STEP_OVER_ID, STEP_OVER_LABEL, 20, CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('thread'), CONTEXT_DEBUG_STATE.isEqualTo('stopped')); registerDebugViewMenuItem(MenuId.DebugCallStackContext, STEP_INTO_ID, STEP_INTO_LABEL, 30, CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('thread'), CONTEXT_DEBUG_STATE.isEqualTo('stopped')); registerDebugViewMenuItem(MenuId.DebugCallStackContext, STEP_OUT_ID, STEP_OUT_LABEL, 40, CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('thread'), CONTEXT_DEBUG_STATE.isEqualTo('stopped')); registerDebugViewMenuItem(MenuId.DebugCallStackContext, TERMINATE_THREAD_ID, nls.localize('terminateThread', "Terminate Thread"), 10, CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('thread'), undefined, 'termination'); registerDebugViewMenuItem(MenuId.DebugCallStackContext, RESTART_FRAME_ID, nls.localize('restartFrame', "Restart Frame"), 10, ContextKeyExpr.and(CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('stackFrame'), CONTEXT_RESTART_FRAME_SUPPORTED), CONTEXT_STACK_FRAME_SUPPORTS_RESTART); registerDebugViewMenuItem(MenuId.DebugCallStackContext, COPY_STACK_TRACE_ID, nls.localize('copyStackTrace', "Copy Call Stack"), 20, CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('stackFrame'), undefined, '3_modification'); registerDebugViewMenuItem(MenuId.DebugVariablesContext, VIEW_MEMORY_ID, nls.localize('viewMemory', "View Binary Data"), 15, CONTEXT_CAN_VIEW_MEMORY, CONTEXT_IN_DEBUG_MODE, 'inline', icons.debugInspectMemory); registerDebugViewMenuItem(MenuId.DebugVariablesContext, SET_VARIABLE_ID, nls.localize('setValue', "Set Value"), 10, ContextKeyExpr.or(CONTEXT_SET_VARIABLE_SUPPORTED, ContextKeyExpr.and(CONTEXT_VARIABLE_EVALUATE_NAME_PRESENT, CONTEXT_SET_EXPRESSION_SUPPORTED)), CONTEXT_VARIABLE_IS_READONLY.toNegated(), '3_modification'); registerDebugViewMenuItem(MenuId.DebugVariablesContext, COPY_VALUE_ID, nls.localize('copyValue', "Copy Value"), 10, undefined, undefined, '5_cutcopypaste'); registerDebugViewMenuItem(MenuId.DebugVariablesContext, COPY_EVALUATE_PATH_ID, nls.localize('copyAsExpression', "Copy as Expression"), 20, CONTEXT_VARIABLE_EVALUATE_NAME_PRESENT, undefined, '5_cutcopypaste'); registerDebugViewMenuItem(MenuId.DebugVariablesContext, ADD_TO_WATCH_ID, nls.localize('addToWatchExpressions', "Add to Watch"), 100, CONTEXT_VARIABLE_EVALUATE_NAME_PRESENT, undefined, 'z_commands'); registerDebugViewMenuItem(MenuId.DebugVariablesContext, BREAK_WHEN_VALUE_IS_READ_ID, nls.localize('breakWhenValueIsRead', "Break on Value Read"), 200, CONTEXT_BREAK_WHEN_VALUE_IS_READ_SUPPORTED, undefined, 'z_commands'); registerDebugViewMenuItem(MenuId.DebugVariablesContext, BREAK_WHEN_VALUE_CHANGES_ID, nls.localize('breakWhenValueChanges', "Break on Value Change"), 210, CONTEXT_BREAK_WHEN_VALUE_CHANGES_SUPPORTED, undefined, 'z_commands'); registerDebugViewMenuItem(MenuId.DebugVariablesContext, BREAK_WHEN_VALUE_IS_ACCESSED_ID, nls.localize('breakWhenValueIsAccessed', "Break on Value Access"), 220, CONTEXT_BREAK_WHEN_VALUE_IS_ACCESSED_SUPPORTED, undefined, 'z_commands'); registerDebugViewMenuItem(MenuId.DebugWatchContext, ADD_WATCH_ID, ADD_WATCH_LABEL, 10, undefined, undefined, '3_modification'); registerDebugViewMenuItem(MenuId.DebugWatchContext, EDIT_EXPRESSION_COMMAND_ID, nls.localize('editWatchExpression', "Edit Expression"), 20, CONTEXT_WATCH_ITEM_TYPE.isEqualTo('expression'), undefined, '3_modification'); registerDebugViewMenuItem(MenuId.DebugWatchContext, SET_EXPRESSION_COMMAND_ID, nls.localize('setValue', "Set Value"), 30, ContextKeyExpr.or(ContextKeyExpr.and(CONTEXT_WATCH_ITEM_TYPE.isEqualTo('expression'), CONTEXT_SET_EXPRESSION_SUPPORTED), ContextKeyExpr.and(CONTEXT_WATCH_ITEM_TYPE.isEqualTo('variable'), CONTEXT_SET_VARIABLE_SUPPORTED)), CONTEXT_VARIABLE_IS_READONLY.toNegated(), '3_modification'); registerDebugViewMenuItem(MenuId.DebugWatchContext, COPY_VALUE_ID, nls.localize('copyValue', "Copy Value"), 40, ContextKeyExpr.or(CONTEXT_WATCH_ITEM_TYPE.isEqualTo('expression'), CONTEXT_WATCH_ITEM_TYPE.isEqualTo('variable')), CONTEXT_IN_DEBUG_MODE, '3_modification'); registerDebugViewMenuItem(MenuId.DebugWatchContext, VIEW_MEMORY_ID, nls.localize('viewMemory', "View Binary Data"), 10, CONTEXT_CAN_VIEW_MEMORY, undefined, 'inline', icons.debugInspectMemory); registerDebugViewMenuItem(MenuId.DebugWatchContext, REMOVE_EXPRESSION_COMMAND_ID, nls.localize('removeWatchExpression', "Remove Expression"), 20, CONTEXT_WATCH_ITEM_TYPE.isEqualTo('expression'), undefined, 'inline', icons.watchExpressionRemove); registerDebugViewMenuItem(MenuId.DebugWatchContext, REMOVE_WATCH_EXPRESSIONS_COMMAND_ID, REMOVE_WATCH_EXPRESSIONS_LABEL, 20, undefined, undefined, 'z_commands'); // Touch Bar if (isMacintosh) { const registerTouchBarEntry = (id: string, title: string | ICommandActionTitle, order: number, when: ContextKeyExpression | undefined, iconUri: URI) => { MenuRegistry.appendMenuItem(MenuId.TouchBarContext, { command: { id, title, icon: { dark: iconUri } }, when: ContextKeyExpr.and(CONTEXT_DEBUGGERS_AVAILABLE, when), group: '9_debug', order }); }; registerTouchBarEntry(DEBUG_RUN_COMMAND_ID, DEBUG_RUN_LABEL, 0, CONTEXT_IN_DEBUG_MODE.toNegated(), FileAccess.asFileUri('vs/workbench/contrib/debug/browser/media/continue-tb.png')); registerTouchBarEntry(DEBUG_START_COMMAND_ID, DEBUG_START_LABEL, 1, CONTEXT_IN_DEBUG_MODE.toNegated(), FileAccess.asFileUri('vs/workbench/contrib/debug/browser/media/run-with-debugging-tb.png')); registerTouchBarEntry(CONTINUE_ID, CONTINUE_LABEL, 0, CONTEXT_DEBUG_STATE.isEqualTo('stopped'), FileAccess.asFileUri('vs/workbench/contrib/debug/browser/media/continue-tb.png')); registerTouchBarEntry(PAUSE_ID, PAUSE_LABEL, 1, ContextKeyExpr.and(CONTEXT_IN_DEBUG_MODE, ContextKeyExpr.notEquals('debugState', 'stopped')), FileAccess.asFileUri('vs/workbench/contrib/debug/browser/media/pause-tb.png')); registerTouchBarEntry(STEP_OVER_ID, STEP_OVER_LABEL, 2, CONTEXT_IN_DEBUG_MODE, FileAccess.asFileUri('vs/workbench/contrib/debug/browser/media/stepover-tb.png')); registerTouchBarEntry(STEP_INTO_ID, STEP_INTO_LABEL, 3, CONTEXT_IN_DEBUG_MODE, FileAccess.asFileUri('vs/workbench/contrib/debug/browser/media/stepinto-tb.png')); registerTouchBarEntry(STEP_OUT_ID, STEP_OUT_LABEL, 4, CONTEXT_IN_DEBUG_MODE, FileAccess.asFileUri('vs/workbench/contrib/debug/browser/media/stepout-tb.png')); registerTouchBarEntry(RESTART_SESSION_ID, RESTART_LABEL, 5, CONTEXT_IN_DEBUG_MODE, FileAccess.asFileUri('vs/workbench/contrib/debug/browser/media/restart-tb.png')); registerTouchBarEntry(STOP_ID, STOP_LABEL, 6, CONTEXT_IN_DEBUG_MODE, FileAccess.asFileUri('vs/workbench/contrib/debug/browser/media/stop-tb.png')); } // Editor Title Menu's "Run/Debug" dropdown item MenuRegistry.appendMenuItem(MenuId.EditorTitle, { submenu: MenuId.EditorTitleRun, rememberDefaultAction: true, title: nls.localize2('run', "Run or Debug..."), icon: icons.debugRun, group: 'navigation', order: -1 }); // Debug menu MenuRegistry.appendMenuItem(MenuId.MenubarMainMenu, { submenu: MenuId.MenubarDebugMenu, title: { value: 'Run', original: 'Run', mnemonicTitle: nls.localize({ key: 'mRun', comment: ['&& denotes a mnemonic'] }, "&&Run") }, order: 6 }); MenuRegistry.appendMenuItem(MenuId.MenubarDebugMenu, { group: '1_debug', command: { id: DEBUG_START_COMMAND_ID, title: nls.localize({ key: 'miStartDebugging', comment: ['&& denotes a mnemonic'] }, "&&Start Debugging") }, order: 1, when: CONTEXT_DEBUGGERS_AVAILABLE }); MenuRegistry.appendMenuItem(MenuId.MenubarDebugMenu, { group: '1_debug', command: { id: DEBUG_RUN_COMMAND_ID, title: nls.localize({ key: 'miRun', comment: ['&& denotes a mnemonic'] }, "Run &&Without Debugging") }, order: 2, when: CONTEXT_DEBUGGERS_AVAILABLE }); MenuRegistry.appendMenuItem(MenuId.MenubarDebugMenu, { group: '1_debug', command: { id: STOP_ID, title: nls.localize({ key: 'miStopDebugging', comment: ['&& denotes a mnemonic'] }, "&&Stop Debugging"), precondition: CONTEXT_IN_DEBUG_MODE }, order: 3, when: CONTEXT_DEBUGGERS_AVAILABLE }); MenuRegistry.appendMenuItem(MenuId.MenubarDebugMenu, { group: '1_debug', command: { id: RESTART_SESSION_ID, title: nls.localize({ key: 'miRestart Debugging', comment: ['&& denotes a mnemonic'] }, "&&Restart Debugging"), precondition: CONTEXT_IN_DEBUG_MODE }, order: 4, when: CONTEXT_DEBUGGERS_AVAILABLE }); // Configuration MenuRegistry.appendMenuItem(MenuId.MenubarDebugMenu, { group: '2_configuration', command: { id: ADD_CONFIGURATION_ID, title: nls.localize({ key: 'miAddConfiguration', comment: ['&& denotes a mnemonic'] }, "A&&dd Configuration...") }, order: 2, when: CONTEXT_DEBUGGERS_AVAILABLE }); // Step Commands MenuRegistry.appendMenuItem(MenuId.MenubarDebugMenu, { group: '3_step', command: { id: STEP_OVER_ID, title: nls.localize({ key: 'miStepOver', comment: ['&& denotes a mnemonic'] }, "Step &&Over"), precondition: CONTEXT_DEBUG_STATE.isEqualTo('stopped') }, order: 1, when: CONTEXT_DEBUGGERS_AVAILABLE }); MenuRegistry.appendMenuItem(MenuId.MenubarDebugMenu, { group: '3_step', command: { id: STEP_INTO_ID, title: nls.localize({ key: 'miStepInto', comment: ['&& denotes a mnemonic'] }, "Step &&Into"), precondition: CONTEXT_DEBUG_STATE.isEqualTo('stopped') }, order: 2, when: CONTEXT_DEBUGGERS_AVAILABLE }); MenuRegistry.appendMenuItem(MenuId.MenubarDebugMenu, { group: '3_step', command: { id: STEP_OUT_ID, title: nls.localize({ key: 'miStepOut', comment: ['&& denotes a mnemonic'] }, "Step O&&ut"), precondition: CONTEXT_DEBUG_STATE.isEqualTo('stopped') }, order: 3, when: CONTEXT_DEBUGGERS_AVAILABLE }); MenuRegistry.appendMenuItem(MenuId.MenubarDebugMenu, { group: '3_step', command: { id: CONTINUE_ID, title: nls.localize({ key: 'miContinue', comment: ['&& denotes a mnemonic'] }, "&&Continue"), precondition: CONTEXT_DEBUG_STATE.isEqualTo('stopped') }, order: 4, when: CONTEXT_DEBUGGERS_AVAILABLE }); // New Breakpoints MenuRegistry.appendMenuItem(MenuId.MenubarNewBreakpointMenu, { group: '1_breakpoints', command: { id: TOGGLE_INLINE_BREAKPOINT_ID, title: nls.localize({ key: 'miInlineBreakpoint', comment: ['&& denotes a mnemonic'] }, "Inline Breakp&&oint") }, order: 2, when: CONTEXT_DEBUGGERS_AVAILABLE }); MenuRegistry.appendMenuItem(MenuId.MenubarDebugMenu, { group: '4_new_breakpoint', title: nls.localize({ key: 'miNewBreakpoint', comment: ['&& denotes a mnemonic'] }, "&&New Breakpoint"), submenu: MenuId.MenubarNewBreakpointMenu, order: 2, when: CONTEXT_DEBUGGERS_AVAILABLE }); // Breakpoint actions are registered from breakpointsView.ts // Install Debuggers MenuRegistry.appendMenuItem(MenuId.MenubarDebugMenu, { group: 'z_install', command: { id: 'debug.installAdditionalDebuggers', title: nls.localize({ key: 'miInstallAdditionalDebuggers', comment: ['&& denotes a mnemonic'] }, "&&Install Additional Debuggers...") }, order: 1 }); // register repl panel const VIEW_CONTAINER: ViewContainer = Registry.as<IViewContainersRegistry>(ViewExtensions.ViewContainersRegistry).registerViewContainer({ id: DEBUG_PANEL_ID, title: nls.localize2({ comment: ['Debug is a noun in this context, not a verb.'], key: 'debugPanel' }, "Debug Console"), icon: icons.debugConsoleViewIcon, ctorDescriptor: new SyncDescriptor(ViewPaneContainer, [DEBUG_PANEL_ID, { mergeViewWithContainerWhenSingleView: true }]), storageId: DEBUG_PANEL_ID, hideIfEmpty: true, order: 2, }, ViewContainerLocation.Panel, { doNotRegisterOpenCommand: true }); Registry.as<IViewsRegistry>(ViewExtensions.ViewsRegistry).registerViews([{ id: REPL_VIEW_ID, name: nls.localize2({ comment: ['Debug is a noun in this context, not a verb.'], key: 'debugPanel' }, "Debug Console"), containerIcon: icons.debugConsoleViewIcon, canToggleVisibility: false, canMoveView: true, when: CONTEXT_DEBUGGERS_AVAILABLE, ctorDescriptor: new SyncDescriptor(Repl), openCommandActionDescriptor: { id: 'workbench.debug.action.toggleRepl', mnemonicTitle: nls.localize({ key: 'miToggleDebugConsole', comment: ['&& denotes a mnemonic'] }, "De&&bug Console"), keybindings: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KeyY }, order: 2 } }], VIEW_CONTAINER); const viewContainer = Registry.as<IViewContainersRegistry>(ViewExtensions.ViewContainersRegistry).registerViewContainer({ id: VIEWLET_ID, title: nls.localize2('run and debug', "Run and Debug"), openCommandActionDescriptor: { id: VIEWLET_ID, mnemonicTitle: nls.localize({ key: 'miViewRun', comment: ['&& denotes a mnemonic'] }, "&&Run"), keybindings: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KeyD }, order: 3 }, ctorDescriptor: new SyncDescriptor(DebugViewPaneContainer), icon: icons.runViewIcon, alwaysUseContainerInfo: true, order: 3, }, ViewContainerLocation.Sidebar); // Register default debug views const viewsRegistry = Registry.as<IViewsRegistry>(ViewExtensions.ViewsRegistry); viewsRegistry.registerViews([{ id: VARIABLES_VIEW_ID, name: nls.localize2('variables', "Variables"), containerIcon: icons.variablesViewIcon, ctorDescriptor: new SyncDescriptor(VariablesView), order: 10, weight: 40, canToggleVisibility: true, canMoveView: true, focusCommand: { id: 'workbench.debug.action.focusVariablesView' }, when: CONTEXT_DEBUG_UX.isEqualTo('default') }], viewContainer); viewsRegistry.registerViews([{ id: WATCH_VIEW_ID, name: nls.localize2('watch', "Watch"), containerIcon: icons.watchViewIcon, ctorDescriptor: new SyncDescriptor(WatchExpressionsView), order: 20, weight: 10, canToggleVisibility: true, canMoveView: true, focusCommand: { id: 'workbench.debug.action.focusWatchView' }, when: CONTEXT_DEBUG_UX.isEqualTo('default') }], viewContainer); viewsRegistry.registerViews([{ id: CALLSTACK_VIEW_ID, name: nls.localize2('callStack', "Call Stack"), containerIcon: icons.callStackViewIcon, ctorDescriptor: new SyncDescriptor(CallStackView), order: 30, weight: 30, canToggleVisibility: true, canMoveView: true, focusCommand: { id: 'workbench.debug.action.focusCallStackView' }, when: CONTEXT_DEBUG_UX.isEqualTo('default') }], viewContainer); viewsRegistry.registerViews([{ id: BREAKPOINTS_VIEW_ID, name: nls.localize2('breakpoints', "Breakpoints"), containerIcon: icons.breakpointsViewIcon, ctorDescriptor: new SyncDescriptor(BreakpointsView), order: 40, weight: 20, canToggleVisibility: true, canMoveView: true, focusCommand: { id: 'workbench.debug.action.focusBreakpointsView' }, when: ContextKeyExpr.or(CONTEXT_BREAKPOINTS_EXIST, CONTEXT_DEBUG_UX.isEqualTo('default'), CONTEXT_HAS_DEBUGGED) }], viewContainer); viewsRegistry.registerViews([{ id: WelcomeView.ID, name: WelcomeView.LABEL, containerIcon: icons.runViewIcon, ctorDescriptor: new SyncDescriptor(WelcomeView), order: 1, weight: 40, canToggleVisibility: true, when: CONTEXT_DEBUG_UX.isEqualTo('simple') }], viewContainer); viewsRegistry.registerViews([{ id: LOADED_SCRIPTS_VIEW_ID, name: nls.localize2('loadedScripts', "Loaded Scripts"), containerIcon: icons.loadedScriptsViewIcon, ctorDescriptor: new SyncDescriptor(LoadedScriptsView), order: 35, weight: 5, canToggleVisibility: true, canMoveView: true, collapsed: true, when: ContextKeyExpr.and(CONTEXT_LOADED_SCRIPTS_SUPPORTED, CONTEXT_DEBUG_UX.isEqualTo('default')) }], viewContainer); // Register disassembly view Registry.as<IEditorPaneRegistry>(EditorExtensions.EditorPane).registerEditorPane( EditorPaneDescriptor.create(DisassemblyView, DISASSEMBLY_VIEW_ID, nls.localize('disassembly', "Disassembly")), [new SyncDescriptor(DisassemblyViewInput)] ); // Register configuration const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration); configurationRegistry.registerConfiguration({ id: 'debug', order: 20, title: nls.localize('debugConfigurationTitle', "Debug"), type: 'object', properties: { 'debug.allowBreakpointsEverywhere': { type: 'boolean', description: nls.localize({ comment: ['This is the description for a setting'], key: 'allowBreakpointsEverywhere' }, "Allow setting breakpoints in any file."), default: false }, 'debug.openExplorerOnEnd': { type: 'boolean', description: nls.localize({ comment: ['This is the description for a setting'], key: 'openExplorerOnEnd' }, "Automatically open the explorer view at the end of a debug session."), default: false }, 'debug.inlineValues': { type: 'string', 'enum': ['on', 'off', 'auto'], description: nls.localize({ comment: ['This is the description for a setting'], key: 'inlineValues' }, "Show variable values inline in editor while debugging."), 'enumDescriptions': [ nls.localize('inlineValues.on', "Always show variable values inline in editor while debugging."), nls.localize('inlineValues.off', "Never show variable values inline in editor while debugging."), nls.localize('inlineValues.focusNoScroll', "Show variable values inline in editor while debugging when the language supports inline value locations."), ], default: 'auto' }, 'debug.toolBarLocation': { enum: ['floating', 'docked', 'commandCenter', 'hidden'], markdownDescription: nls.localize({ comment: ['This is the description for a setting'], key: 'toolBarLocation' }, "Controls the location of the debug toolbar. Either `floating` in all views, `docked` in the debug view, `commandCenter` (requires `{0}`), or `hidden`.", '#window.commandCenter#'), default: 'floating', markdownEnumDescriptions: [ nls.localize('debugToolBar.floating', "Show debug toolbar in all views."), nls.localize('debugToolBar.docked', "Show debug toolbar only in debug views."), nls.localize('debugToolBar.commandCenter', "`(Experimental)` Show debug toolbar in the command center."), nls.localize('debugToolBar.hidden', "Do not show debug toolbar."), ] }, 'debug.showInStatusBar': { enum: ['never', 'always', 'onFirstSessionStart'], enumDescriptions: [nls.localize('never', "Never show debug in Status bar"), nls.localize('always', "Always show debug in Status bar"), nls.localize('onFirstSessionStart', "Show debug in Status bar only after debug was started for the first time")], description: nls.localize({ comment: ['This is the description for a setting'], key: 'showInStatusBar' }, "Controls when the debug Status bar should be visible."), default: 'onFirstSessionStart' }, 'debug.internalConsoleOptions': INTERNAL_CONSOLE_OPTIONS_SCHEMA, 'debug.console.closeOnEnd': { type: 'boolean', description: nls.localize('debug.console.closeOnEnd', "Controls if the Debug Console should be automatically closed when the debug session ends."), default: false }, 'debug.terminal.clearBeforeReusing': { type: 'boolean', description: nls.localize({ comment: ['This is the description for a setting'], key: 'debug.terminal.clearBeforeReusing' }, "Before starting a new debug session in an integrated or external terminal, clear the terminal."), default: false }, 'debug.openDebug': { enum: ['neverOpen', 'openOnSessionStart', 'openOnFirstSessionStart', 'openOnDebugBreak'], default: 'openOnDebugBreak', description: nls.localize('openDebug', "Controls when the debug view should open.") }, 'debug.showSubSessionsInToolBar': { type: 'boolean', description: nls.localize({ comment: ['This is the description for a setting'], key: 'showSubSessionsInToolBar' }, "Controls whether the debug sub-sessions are shown in the debug tool bar. When this setting is false the stop command on a sub-session will also stop the parent session."), default: false }, 'debug.console.fontSize': { type: 'number', description: nls.localize('debug.console.fontSize', "Controls the font size in pixels in the Debug Console."), default: isMacintosh ? 12 : 14, }, 'debug.console.fontFamily': { type: 'string', description: nls.localize('debug.console.fontFamily', "Controls the font family in the Debug Console."), default: 'default' }, 'debug.console.lineHeight': { type: 'number', description: nls.localize('debug.console.lineHeight', "Controls the line height in pixels in the Debug Console. Use 0 to compute the line height from the font size."), default: 0 }, 'debug.console.wordWrap': { type: 'boolean', description: nls.localize('debug.console.wordWrap', "Controls if the lines should wrap in the Debug Console."), default: true }, 'debug.console.historySuggestions': { type: 'boolean', description: nls.localize('debug.console.historySuggestions', "Controls if the Debug Console should suggest previously typed input."), default: true }, 'debug.console.collapseIdenticalLines': { type: 'boolean', description: nls.localize('debug.console.collapseIdenticalLines', "Controls if the Debug Console should collapse identical lines and show a number of occurrences with a badge."), default: true }, 'debug.console.acceptSuggestionOnEnter': { enum: ['off', 'on'], description: nls.localize('debug.console.acceptSuggestionOnEnter', "Controls whether suggestions should be accepted on Enter in the Debug Console. Enter is also used to evaluate whatever is typed in the Debug Console."), default: 'off' }, 'launch': { type: 'object', description: nls.localize({ comment: ['This is the description for a setting'], key: 'launch' }, "Global debug launch configuration. Should be used as an alternative to 'launch.json' that is shared across workspaces."), default: { configurations: [], compounds: [] }, $ref: launchSchemaId }, 'debug.focusWindowOnBreak': { type: 'boolean', description: nls.localize('debug.focusWindowOnBreak', "Controls whether the workbench window should be focused when the debugger breaks."), default: true }, 'debug.focusEditorOnBreak': { type: 'boolean', description: nls.localize('debug.focusEditorOnBreak', "Controls whether the editor should be focused when the debugger breaks."), default: true }, 'debug.onTaskErrors': { enum: ['debugAnyway', 'showErrors', 'prompt', 'abort'], enumDescriptions: [nls.localize('debugAnyway', "Ignore task errors and start debugging."), nls.localize('showErrors', "Show the Problems view and do not start debugging."), nls.localize('prompt', "Prompt user."), nls.localize('cancel', "Cancel debugging.")], description: nls.localize('debug.onTaskErrors', "Controls what to do when errors are encountered after running a preLaunchTask."), default: 'prompt' }, 'debug.showBreakpointsInOverviewRuler': { type: 'boolean', description: nls.localize({ comment: ['This is the description for a setting'], key: 'showBreakpointsInOverviewRuler' }, "Controls whether breakpoints should be shown in the overview ruler."), default: false }, 'debug.showInlineBreakpointCandidates': { type: 'boolean', description: nls.localize({ comment: ['This is the description for a setting'], key: 'showInlineBreakpointCandidates' }, "Controls whether inline breakpoints candidate decorations should be shown in the editor while debugging."), default: true }, 'debug.saveBeforeStart': { description: nls.localize('debug.saveBeforeStart', "Controls what editors to save before starting a debug session."), enum: ['allEditorsInActiveGroup', 'nonUntitledEditorsInActiveGroup', 'none'], enumDescriptions: [ nls.localize('debug.saveBeforeStart.allEditorsInActiveGroup', "Save all editors in the active group before starting a debug session."), nls.localize('debug.saveBeforeStart.nonUntitledEditorsInActiveGroup', "Save all editors in the active group except untitled ones before starting a debug session."), nls.localize('debug.saveBeforeStart.none', "Don't save any editors before starting a debug session."), ], default: 'allEditorsInActiveGroup', scope: ConfigurationScope.LANGUAGE_OVERRIDABLE }, 'debug.confirmOnExit': { description: nls.localize('debug.confirmOnExit', "Controls whether to confirm when the window closes if there are active debug sessions."), type: 'string', enum: ['never', 'always'], enumDescriptions: [ nls.localize('debug.confirmOnExit.never', "Never confirm."), nls.localize('debug.confirmOnExit.always', "Always confirm if there are debug sessions."), ], default: 'never' }, 'debug.disassemblyView.showSourceCode': { type: 'boolean', default: true, description: nls.localize('debug.disassemblyView.showSourceCode', "Show Source Code in Disassembly View.") }, 'debug.autoExpandLazyVariables': { type: 'boolean', default: false, description: nls.localize('debug.autoExpandLazyVariables', "Automatically show values for variables that are lazily resolved by the debugger, such as getters.") }, 'debug.enableStatusBarColor': { type: 'boolean', description: nls.localize('debug.enableStatusBarColor', "Color of the Status bar when debugger is active."), default: true }, 'debug.hideLauncherWhileDebugging': { type: 'boolean', markdownDescription: nls.localize({ comment: ['This is the description for a setting'], key: 'debug.hideLauncherWhileDebugging' }, "Hide 'Start Debugging' control in title bar of 'Run and Debug' view while debugging is active. Only relevant when `{0}` is not `docked`.", '#debug.toolBarLocation#'), default: false } } });
src/vs/workbench/contrib/debug/browser/debug.contribution.ts
1
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
[ 0.0012860524002462626, 0.0002039941173279658, 0.0001628473837627098, 0.00016918119217734784, 0.00017277045117225498 ]
{ "id": 3, "code_window": [ "import { DebugCompoundRoot } from 'vs/workbench/contrib/debug/common/debugCompoundRoot';\n", "import { Debugger } from 'vs/workbench/contrib/debug/common/debugger';\n", "import { Breakpoint, DataBreakpoint, DebugModel, FunctionBreakpoint, InstructionBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel';\n", "import { DebugStorage } from 'vs/workbench/contrib/debug/common/debugStorage';\n", "import { DebugTelemetry } from 'vs/workbench/contrib/debug/common/debugTelemetry';\n", "import { getExtensionHostDebugSession, saveAllBeforeDebugStart } from 'vs/workbench/contrib/debug/common/debugUtils';\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { Source } from 'vs/workbench/contrib/debug/common/debugSource';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "add", "edit_start_line_idx": 45 }
{ "registrations": [ { "component": { "type": "git", "git": { "name": "atom/language-clojure", "repositoryUrl": "https://github.com/atom/language-clojure", "commitHash": "45bdb881501d0b8f8b707ca1d3fcc8b4b99fca03" } }, "license": "MIT", "version": "0.22.8", "description": "The file syntaxes/clojure.tmLanguage.json was derived from the Atom package https://github.com/atom/language-clojure which was originally converted from the TextMate bundle https://github.com/mmcgrana/textmate-clojure." } ], "version": 1 }
extensions/clojure/cgmanifest.json
0
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
[ 0.0001738667779136449, 0.00017331275739707053, 0.00017275875143241137, 0.00017331275739707053, 5.540132406167686e-7 ]
{ "id": 3, "code_window": [ "import { DebugCompoundRoot } from 'vs/workbench/contrib/debug/common/debugCompoundRoot';\n", "import { Debugger } from 'vs/workbench/contrib/debug/common/debugger';\n", "import { Breakpoint, DataBreakpoint, DebugModel, FunctionBreakpoint, InstructionBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel';\n", "import { DebugStorage } from 'vs/workbench/contrib/debug/common/debugStorage';\n", "import { DebugTelemetry } from 'vs/workbench/contrib/debug/common/debugTelemetry';\n", "import { getExtensionHostDebugSession, saveAllBeforeDebugStart } from 'vs/workbench/contrib/debug/common/debugUtils';\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { Source } from 'vs/workbench/contrib/debug/common/debugSource';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "add", "edit_start_line_idx": 45 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Disposable, ExtensionContext, Uri, l10n } from 'vscode'; import { LanguageClientOptions } from 'vscode-languageclient'; import { startClient, LanguageClientConstructor, AsyncDisposable } from '../htmlClient'; import { LanguageClient } from 'vscode-languageclient/browser'; declare const Worker: { new(stringUrl: string): any; }; declare const TextDecoder: { new(encoding?: string): { decode(buffer: ArrayBuffer): string }; }; let client: AsyncDisposable | undefined; // this method is called when vs code is activated export async function activate(context: ExtensionContext) { const serverMain = Uri.joinPath(context.extensionUri, 'server/dist/browser/htmlServerMain.js'); try { const worker = new Worker(serverMain.toString()); worker.postMessage({ i10lLocation: l10n.uri?.toString(false) ?? '' }); const newLanguageClient: LanguageClientConstructor = (id: string, name: string, clientOptions: LanguageClientOptions) => { return new LanguageClient(id, name, clientOptions, worker); }; const timer = { setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): Disposable { const handle = setTimeout(callback, ms, ...args); return { dispose: () => clearTimeout(handle) }; } }; client = await startClient(context, newLanguageClient, { TextDecoder, timer }); } catch (e) { console.log(e); } } export async function deactivate(): Promise<void> { if (client) { await client.dispose(); client = undefined; } }
extensions/html-language-features/client/src/browser/htmlClientMain.ts
0
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
[ 0.0001748600188875571, 0.0001704408641671762, 0.0001650792983127758, 0.00017188357014674693, 0.000003806367885772488 ]
{ "id": 3, "code_window": [ "import { DebugCompoundRoot } from 'vs/workbench/contrib/debug/common/debugCompoundRoot';\n", "import { Debugger } from 'vs/workbench/contrib/debug/common/debugger';\n", "import { Breakpoint, DataBreakpoint, DebugModel, FunctionBreakpoint, InstructionBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel';\n", "import { DebugStorage } from 'vs/workbench/contrib/debug/common/debugStorage';\n", "import { DebugTelemetry } from 'vs/workbench/contrib/debug/common/debugTelemetry';\n", "import { getExtensionHostDebugSession, saveAllBeforeDebugStart } from 'vs/workbench/contrib/debug/common/debugUtils';\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { Source } from 'vs/workbench/contrib/debug/common/debugSource';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "add", "edit_start_line_idx": 45 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CancellationToken } from 'vs/base/common/cancellation'; import { IMarkdownString } from 'vs/base/common/htmlContent'; import { Iterable } from 'vs/base/common/iterator'; import { toDisposable } from 'vs/base/common/lifecycle'; import { IRelaxedExtensionDescription } from 'vs/platform/extensions/common/extensions'; import { ExtHostChatShape, IChatDto, IMainContext, MainContext, MainThreadChatShape } from 'vs/workbench/api/common/extHost.protocol'; import * as typeConvert from 'vs/workbench/api/common/extHostTypeConverters'; import { IChatReplyFollowup } from 'vs/workbench/contrib/chat/common/chatService'; import type * as vscode from 'vscode'; class ChatProviderWrapper<T> { private static _pool = 0; readonly handle: number = ChatProviderWrapper._pool++; constructor( readonly extension: Readonly<IRelaxedExtensionDescription>, readonly provider: T, ) { } } export class ExtHostChat implements ExtHostChatShape { private static _nextId = 0; private readonly _chatProvider = new Map<number, ChatProviderWrapper<vscode.InteractiveSessionProvider>>(); private readonly _chatSessions = new Map<number, vscode.InteractiveSession>(); private readonly _proxy: MainThreadChatShape; constructor( mainContext: IMainContext, ) { this._proxy = mainContext.getProxy(MainContext.MainThreadChat); } //#region interactive session registerChatProvider(extension: Readonly<IRelaxedExtensionDescription>, id: string, provider: vscode.InteractiveSessionProvider): vscode.Disposable { const wrapper = new ChatProviderWrapper(extension, provider); this._chatProvider.set(wrapper.handle, wrapper); this._proxy.$registerChatProvider(wrapper.handle, id); return toDisposable(() => { this._proxy.$unregisterChatProvider(wrapper.handle); this._chatProvider.delete(wrapper.handle); }); } transferChatSession(session: vscode.InteractiveSession, newWorkspace: vscode.Uri): void { const sessionId = Iterable.find(this._chatSessions.keys(), key => this._chatSessions.get(key) === session) ?? 0; if (typeof sessionId !== 'number') { return; } this._proxy.$transferChatSession(sessionId, newWorkspace); } sendInteractiveRequestToProvider(providerId: string, message: vscode.InteractiveSessionDynamicRequest): void { this._proxy.$sendRequestToProvider(providerId, message); } async $prepareChat(handle: number, token: CancellationToken): Promise<IChatDto | undefined> { const entry = this._chatProvider.get(handle); if (!entry) { return undefined; } const session = await entry.provider.prepareSession(token); if (!session) { return undefined; } const id = ExtHostChat._nextId++; this._chatSessions.set(id, session); return { id, requesterUsername: session.requester?.name, requesterAvatarIconUri: session.requester?.icon, responderUsername: session.responder?.name, responderAvatarIconUri: session.responder?.icon, inputPlaceholder: session.inputPlaceholder, }; } async $provideWelcomeMessage(handle: number, token: CancellationToken): Promise<(string | IMarkdownString | IChatReplyFollowup[])[] | undefined> { const entry = this._chatProvider.get(handle); if (!entry) { return undefined; } if (!entry.provider.provideWelcomeMessage) { return undefined; } const content = await entry.provider.provideWelcomeMessage(token); if (!content) { return undefined; } return content.map(item => { if (typeof item === 'string') { return item; } else if (Array.isArray(item)) { return item.map(f => typeConvert.ChatReplyFollowup.from(f)); } else { return typeConvert.MarkdownString.from(item); } }); } async $provideSampleQuestions(handle: number, token: CancellationToken): Promise<IChatReplyFollowup[] | undefined> { const entry = this._chatProvider.get(handle); if (!entry) { return undefined; } if (!entry.provider.provideSampleQuestions) { return undefined; } const rawFollowups = await entry.provider.provideSampleQuestions(token); if (!rawFollowups) { return undefined; } return rawFollowups?.map(f => typeConvert.ChatReplyFollowup.from(f)); } $releaseSession(sessionId: number) { this._chatSessions.delete(sessionId); } //#endregion }
src/vs/workbench/api/common/extHostChat.ts
0
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
[ 0.00017721274343784899, 0.00017017414211295545, 0.0001646291057113558, 0.000170091210748069, 0.0000038142793528095353 ]
{ "id": 4, "code_window": [ "\t\t\t\t\tthis.notificationService.error(err);\n", "\t\t\t\t}\n", "\t\t\t}\n", "\t\t\tthis.endInitializingState();\n", "\t\t\tthis.cancelTokens(session.getId());\n", "\t\t\tthis._onDidEndSession.fire({ session, restart: this.restartingSessions.has(session) });\n", "\n", "\t\t\tconst focusedSession = this.viewModel.focusedSession;\n", "\t\t\tif (focusedSession && focusedSession.getId() === session.getId()) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\t\tif (this.configurationService.getValue<IDebugConfiguration>('debug').closeReadonlyTabsOnEnd) {\n", "\t\t\t\tconst editorsToClose = this.editorService.getEditors(EditorsOrder.SEQUENTIAL).filter(({ editor }) => {\n", "\t\t\t\t\tif (editor.resource?.scheme === DEBUG_SCHEME) {\n", "\t\t\t\t\t\treturn editor.isReadonly() && session.getId() === Source.getEncodedDebugData(editor.resource).sessionId;\n", "\t\t\t\t\t}\n", "\t\t\t\t\treturn false;\n", "\t\t\t\t});\n", "\t\t\t\tthis.editorService.closeEditors(editorsToClose);\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "add", "edit_start_line_idx": 706 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as aria from 'vs/base/browser/ui/aria/aria'; import { Action, IAction } from 'vs/base/common/actions'; import { distinct } from 'vs/base/common/arrays'; import { raceTimeout, RunOnceScheduler } from 'vs/base/common/async'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { isErrorWithActions } from 'vs/base/common/errorMessage'; import * as errors from 'vs/base/common/errors'; import { Emitter, Event } from 'vs/base/common/event'; import { DisposableStore, IDisposable } from 'vs/base/common/lifecycle'; import { deepClone, equals } from 'vs/base/common/objects'; import severity from 'vs/base/common/severity'; import { URI, URI as uri } from 'vs/base/common/uri'; import { generateUuid } from 'vs/base/common/uuid'; import { isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { ITextModel } from 'vs/editor/common/model'; import * as nls from 'vs/nls'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity'; import { IWorkspaceContextService, IWorkspaceFolder, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { IWorkspaceTrustRequestService } from 'vs/platform/workspace/common/workspaceTrust'; import { EditorInput } from 'vs/workbench/common/editor/editorInput'; import { IViewDescriptorService, IViewsService, ViewContainerLocation } from 'vs/workbench/common/views'; import { AdapterManager } from 'vs/workbench/contrib/debug/browser/debugAdapterManager'; import { DEBUG_CONFIGURE_COMMAND_ID, DEBUG_CONFIGURE_LABEL } from 'vs/workbench/contrib/debug/browser/debugCommands'; import { ConfigurationManager } from 'vs/workbench/contrib/debug/browser/debugConfigurationManager'; import { DebugMemoryFileSystemProvider } from 'vs/workbench/contrib/debug/browser/debugMemory'; import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession'; import { DebugTaskRunner, TaskRunResult } from 'vs/workbench/contrib/debug/browser/debugTaskRunner'; import { CALLSTACK_VIEW_ID, CONTEXT_BREAKPOINTS_EXIST, CONTEXT_HAS_DEBUGGED, CONTEXT_DEBUG_STATE, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_UX, CONTEXT_DISASSEMBLY_VIEW_FOCUS, CONTEXT_IN_DEBUG_MODE, debuggerDisabledMessage, DEBUG_MEMORY_SCHEME, getStateLabel, IAdapterManager, IBreakpoint, IBreakpointData, ICompound, IConfig, IConfigurationManager, IDebugConfiguration, IDebugModel, IDebugService, IDebugSession, IDebugSessionOptions, IEnablement, IExceptionBreakpoint, IGlobalConfig, ILaunch, IStackFrame, IThread, IViewModel, REPL_VIEW_ID, State, VIEWLET_ID } from 'vs/workbench/contrib/debug/common/debug'; import { DebugCompoundRoot } from 'vs/workbench/contrib/debug/common/debugCompoundRoot'; import { Debugger } from 'vs/workbench/contrib/debug/common/debugger'; import { Breakpoint, DataBreakpoint, DebugModel, FunctionBreakpoint, InstructionBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel'; import { DebugStorage } from 'vs/workbench/contrib/debug/common/debugStorage'; import { DebugTelemetry } from 'vs/workbench/contrib/debug/common/debugTelemetry'; import { getExtensionHostDebugSession, saveAllBeforeDebugStart } from 'vs/workbench/contrib/debug/common/debugUtils'; import { ViewModel } from 'vs/workbench/contrib/debug/common/debugViewModel'; import { DisassemblyViewInput } from 'vs/workbench/contrib/debug/common/disassemblyViewInput'; import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/contrib/files/common/files'; import { IActivityService, NumberBadge } from 'vs/workbench/services/activity/common/activity'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService'; import { ILifecycleService } from 'vs/workbench/services/lifecycle/common/lifecycle'; import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite'; export class DebugService implements IDebugService { declare readonly _serviceBrand: undefined; private readonly _onDidChangeState: Emitter<State>; private readonly _onDidNewSession: Emitter<IDebugSession>; private readonly _onWillNewSession: Emitter<IDebugSession>; private readonly _onDidEndSession: Emitter<{ session: IDebugSession; restart: boolean }>; private readonly restartingSessions = new Set<IDebugSession>(); private debugStorage: DebugStorage; private model: DebugModel; private viewModel: ViewModel; private telemetry: DebugTelemetry; private taskRunner: DebugTaskRunner; private configurationManager: ConfigurationManager; private adapterManager: AdapterManager; private readonly disposables = new DisposableStore(); private debugType!: IContextKey<string>; private debugState!: IContextKey<string>; private inDebugMode!: IContextKey<boolean>; private debugUx!: IContextKey<string>; private hasDebugged!: IContextKey<boolean>; private breakpointsExist!: IContextKey<boolean>; private disassemblyViewFocus!: IContextKey<boolean>; private breakpointsToSendOnResourceSaved: Set<URI>; private initializing = false; private _initializingOptions: IDebugSessionOptions | undefined; private previousState: State | undefined; private sessionCancellationTokens = new Map<string, CancellationTokenSource>(); private activity: IDisposable | undefined; private chosenEnvironments: { [key: string]: string }; private haveDoneLazySetup = false; constructor( @IEditorService private readonly editorService: IEditorService, @IPaneCompositePartService private readonly paneCompositeService: IPaneCompositePartService, @IViewsService private readonly viewsService: IViewsService, @IViewDescriptorService private readonly viewDescriptorService: IViewDescriptorService, @INotificationService private readonly notificationService: INotificationService, @IDialogService private readonly dialogService: IDialogService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @ILifecycleService private readonly lifecycleService: ILifecycleService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IExtensionService private readonly extensionService: IExtensionService, @IFileService private readonly fileService: IFileService, @IConfigurationService private readonly configurationService: IConfigurationService, @IExtensionHostDebugService private readonly extensionHostDebugService: IExtensionHostDebugService, @IActivityService private readonly activityService: IActivityService, @ICommandService private readonly commandService: ICommandService, @IQuickInputService private readonly quickInputService: IQuickInputService, @IWorkspaceTrustRequestService private readonly workspaceTrustRequestService: IWorkspaceTrustRequestService, @IUriIdentityService private readonly uriIdentityService: IUriIdentityService ) { this.breakpointsToSendOnResourceSaved = new Set<URI>(); this._onDidChangeState = new Emitter<State>(); this._onDidNewSession = new Emitter<IDebugSession>(); this._onWillNewSession = new Emitter<IDebugSession>(); this._onDidEndSession = new Emitter(); this.adapterManager = this.instantiationService.createInstance(AdapterManager, { onDidNewSession: this.onDidNewSession }); this.disposables.add(this.adapterManager); this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this.adapterManager); this.disposables.add(this.configurationManager); this.debugStorage = this.disposables.add(this.instantiationService.createInstance(DebugStorage)); this.chosenEnvironments = this.debugStorage.loadChosenEnvironments(); this.model = this.instantiationService.createInstance(DebugModel, this.debugStorage); this.telemetry = this.instantiationService.createInstance(DebugTelemetry, this.model); this.viewModel = new ViewModel(contextKeyService); this.taskRunner = this.instantiationService.createInstance(DebugTaskRunner); this.disposables.add(this.fileService.onDidFilesChange(e => this.onFileChanges(e))); this.disposables.add(this.lifecycleService.onWillShutdown(this.dispose, this)); this.disposables.add(this.extensionHostDebugService.onAttachSession(event => { const session = this.model.getSession(event.sessionId, true); if (session) { // EH was started in debug mode -> attach to it session.configuration.request = 'attach'; session.configuration.port = event.port; session.setSubId(event.subId); this.launchOrAttachToSession(session); } })); this.disposables.add(this.extensionHostDebugService.onTerminateSession(event => { const session = this.model.getSession(event.sessionId); if (session && session.subId === event.subId) { session.disconnect(); } })); this.disposables.add(this.viewModel.onDidFocusStackFrame(() => { this.onStateChange(); })); this.disposables.add(this.viewModel.onDidFocusSession((session: IDebugSession | undefined) => { this.onStateChange(); if (session) { this.setExceptionBreakpointFallbackSession(session.getId()); } })); this.disposables.add(Event.any(this.adapterManager.onDidRegisterDebugger, this.configurationManager.onDidSelectConfiguration)(() => { const debugUxValue = (this.state !== State.Inactive || (this.configurationManager.getAllConfigurations().length > 0 && this.adapterManager.hasEnabledDebuggers())) ? 'default' : 'simple'; this.debugUx.set(debugUxValue); this.debugStorage.storeDebugUxState(debugUxValue); })); this.disposables.add(this.model.onDidChangeCallStack(() => { const numberOfSessions = this.model.getSessions().filter(s => !s.parentSession).length; this.activity?.dispose(); if (numberOfSessions > 0) { const viewContainer = this.viewDescriptorService.getViewContainerByViewId(CALLSTACK_VIEW_ID); if (viewContainer) { this.activity = this.activityService.showViewContainerActivity(viewContainer.id, { badge: new NumberBadge(numberOfSessions, n => n === 1 ? nls.localize('1activeSession', "1 active session") : nls.localize('nActiveSessions', "{0} active sessions", n)) }); } } })); this.disposables.add(editorService.onDidActiveEditorChange(() => { this.contextKeyService.bufferChangeEvents(() => { if (editorService.activeEditor === DisassemblyViewInput.instance) { this.disassemblyViewFocus.set(true); } else { // This key can be initialized a tick after this event is fired this.disassemblyViewFocus?.reset(); } }); })); this.disposables.add(this.lifecycleService.onBeforeShutdown(() => { for (const editor of editorService.editors) { // Editors will not be valid on window reload, so close them. if (editor.resource?.scheme === DEBUG_MEMORY_SCHEME) { editor.dispose(); } } })); this.initContextKeys(contextKeyService); } private initContextKeys(contextKeyService: IContextKeyService): void { queueMicrotask(() => { contextKeyService.bufferChangeEvents(() => { this.debugType = CONTEXT_DEBUG_TYPE.bindTo(contextKeyService); this.debugState = CONTEXT_DEBUG_STATE.bindTo(contextKeyService); this.hasDebugged = CONTEXT_HAS_DEBUGGED.bindTo(contextKeyService); this.inDebugMode = CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService); this.debugUx = CONTEXT_DEBUG_UX.bindTo(contextKeyService); this.debugUx.set(this.debugStorage.loadDebugUxState()); this.breakpointsExist = CONTEXT_BREAKPOINTS_EXIST.bindTo(contextKeyService); // Need to set disassemblyViewFocus here to make it in the same context as the debug event handlers this.disassemblyViewFocus = CONTEXT_DISASSEMBLY_VIEW_FOCUS.bindTo(contextKeyService); }); const setBreakpointsExistContext = () => this.breakpointsExist.set(!!(this.model.getBreakpoints().length || this.model.getDataBreakpoints().length || this.model.getFunctionBreakpoints().length)); setBreakpointsExistContext(); this.disposables.add(this.model.onDidChangeBreakpoints(() => setBreakpointsExistContext())); }); } getModel(): IDebugModel { return this.model; } getViewModel(): IViewModel { return this.viewModel; } getConfigurationManager(): IConfigurationManager { return this.configurationManager; } getAdapterManager(): IAdapterManager { return this.adapterManager; } sourceIsNotAvailable(uri: uri): void { this.model.sourceIsNotAvailable(uri); } dispose(): void { this.disposables.dispose(); } //---- state management get state(): State { const focusedSession = this.viewModel.focusedSession; if (focusedSession) { return focusedSession.state; } return this.initializing ? State.Initializing : State.Inactive; } get initializingOptions(): IDebugSessionOptions | undefined { return this._initializingOptions; } private startInitializingState(options?: IDebugSessionOptions): void { if (!this.initializing) { this.initializing = true; this._initializingOptions = options; this.onStateChange(); } } private endInitializingState(): void { if (this.initializing) { this.initializing = false; this._initializingOptions = undefined; this.onStateChange(); } } private cancelTokens(id: string | undefined): void { if (id) { const token = this.sessionCancellationTokens.get(id); if (token) { token.cancel(); this.sessionCancellationTokens.delete(id); } } else { this.sessionCancellationTokens.forEach(t => t.cancel()); this.sessionCancellationTokens.clear(); } } private onStateChange(): void { const state = this.state; if (this.previousState !== state) { this.contextKeyService.bufferChangeEvents(() => { this.debugState.set(getStateLabel(state)); this.inDebugMode.set(state !== State.Inactive); // Only show the simple ux if debug is not yet started and if no launch.json exists const debugUxValue = ((state !== State.Inactive && state !== State.Initializing) || (this.adapterManager.hasEnabledDebuggers() && this.configurationManager.selectedConfiguration.name)) ? 'default' : 'simple'; this.debugUx.set(debugUxValue); this.debugStorage.storeDebugUxState(debugUxValue); }); this.previousState = state; this._onDidChangeState.fire(state); } } get onDidChangeState(): Event<State> { return this._onDidChangeState.event; } get onDidNewSession(): Event<IDebugSession> { return this._onDidNewSession.event; } get onWillNewSession(): Event<IDebugSession> { return this._onWillNewSession.event; } get onDidEndSession(): Event<{ session: IDebugSession; restart: boolean }> { return this._onDidEndSession.event; } private lazySetup() { if (!this.haveDoneLazySetup) { // Registering fs providers is slow // https://github.com/microsoft/vscode/issues/159886 this.disposables.add(this.fileService.registerProvider(DEBUG_MEMORY_SCHEME, new DebugMemoryFileSystemProvider(this))); this.haveDoneLazySetup = true; } } //---- life cycle management /** * main entry point * properly manages compounds, checks for errors and handles the initializing state. */ async startDebugging(launch: ILaunch | undefined, configOrName?: IConfig | string, options?: IDebugSessionOptions, saveBeforeStart = !options?.parentSession): Promise<boolean> { const message = options && options.noDebug ? nls.localize('runTrust', "Running executes build tasks and program code from your workspace.") : nls.localize('debugTrust', "Debugging executes build tasks and program code from your workspace."); const trust = await this.workspaceTrustRequestService.requestWorkspaceTrust({ message }); if (!trust) { return false; } this.lazySetup(); this.startInitializingState(options); this.hasDebugged.set(true); try { // make sure to save all files and that the configuration is up to date await this.extensionService.activateByEvent('onDebug'); if (saveBeforeStart) { await saveAllBeforeDebugStart(this.configurationService, this.editorService); } await this.extensionService.whenInstalledExtensionsRegistered(); let config: IConfig | undefined; let compound: ICompound | undefined; if (!configOrName) { configOrName = this.configurationManager.selectedConfiguration.name; } if (typeof configOrName === 'string' && launch) { config = launch.getConfiguration(configOrName); compound = launch.getCompound(configOrName); } else if (typeof configOrName !== 'string') { config = configOrName; } if (compound) { // we are starting a compound debug, first do some error checking and than start each configuration in the compound if (!compound.configurations) { throw new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] }, "Compound must have \"configurations\" attribute set in order to start multiple configurations.")); } if (compound.preLaunchTask) { const taskResult = await this.taskRunner.runTaskAndCheckErrors(launch?.workspace || this.contextService.getWorkspace(), compound.preLaunchTask); if (taskResult === TaskRunResult.Failure) { this.endInitializingState(); return false; } } if (compound.stopAll) { options = { ...options, compoundRoot: new DebugCompoundRoot() }; } const values = await Promise.all(compound.configurations.map(configData => { const name = typeof configData === 'string' ? configData : configData.name; if (name === compound!.name) { return Promise.resolve(false); } let launchForName: ILaunch | undefined; if (typeof configData === 'string') { const launchesContainingName = this.configurationManager.getLaunches().filter(l => !!l.getConfiguration(name)); if (launchesContainingName.length === 1) { launchForName = launchesContainingName[0]; } else if (launch && launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) { // If there are multiple launches containing the configuration give priority to the configuration in the current launch launchForName = launch; } else { throw new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name) : nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name)); } } else if (configData.folder) { const launchesMatchingConfigData = this.configurationManager.getLaunches().filter(l => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name)); if (launchesMatchingConfigData.length === 1) { launchForName = launchesMatchingConfigData[0]; } else { throw new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound!.name)); } } return this.createSession(launchForName, launchForName!.getConfiguration(name), options); })); const result = values.every(success => !!success); // Compound launch is a success only if each configuration launched successfully this.endInitializingState(); return result; } if (configOrName && !config) { const message = !!launch ? nls.localize('configMissing', "Configuration '{0}' is missing in 'launch.json'.", typeof configOrName === 'string' ? configOrName : configOrName.name) : nls.localize('launchJsonDoesNotExist', "'launch.json' does not exist for passed workspace folder."); throw new Error(message); } const result = await this.createSession(launch, config, options); this.endInitializingState(); return result; } catch (err) { // make sure to get out of initializing state, and propagate the result this.notificationService.error(err); this.endInitializingState(); return Promise.reject(err); } } /** * gets the debugger for the type, resolves configurations by providers, substitutes variables and runs prelaunch tasks */ private async createSession(launch: ILaunch | undefined, config: IConfig | undefined, options?: IDebugSessionOptions): Promise<boolean> { // We keep the debug type in a separate variable 'type' so that a no-folder config has no attributes. // Storing the type in the config would break extensions that assume that the no-folder case is indicated by an empty config. let type: string | undefined; if (config) { type = config.type; } else { // a no-folder workspace has no launch.config config = Object.create(null); } if (options && options.noDebug) { config!.noDebug = true; } else if (options && typeof options.noDebug === 'undefined' && options.parentSession && options.parentSession.configuration.noDebug) { config!.noDebug = true; } const unresolvedConfig = deepClone(config); let guess: Debugger | undefined; let activeEditor: EditorInput | undefined; if (!type) { activeEditor = this.editorService.activeEditor; if (activeEditor && activeEditor.resource) { type = this.chosenEnvironments[activeEditor.resource.toString()]; } if (!type) { guess = await this.adapterManager.guessDebugger(false); if (guess) { type = guess.type; } } } const initCancellationToken = new CancellationTokenSource(); const sessionId = generateUuid(); this.sessionCancellationTokens.set(sessionId, initCancellationToken); const configByProviders = await this.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config!, initCancellationToken.token); // a falsy config indicates an aborted launch if (configByProviders && configByProviders.type) { try { let resolvedConfig = await this.substituteVariables(launch, configByProviders); if (!resolvedConfig) { // User cancelled resolving of interactive variables, silently return return false; } if (initCancellationToken.token.isCancellationRequested) { // User cancelled, silently return return false; } const workspace = launch?.workspace || this.contextService.getWorkspace(); const taskResult = await this.taskRunner.runTaskAndCheckErrors(workspace, resolvedConfig.preLaunchTask); if (taskResult === TaskRunResult.Failure) { return false; } const cfg = await this.configurationManager.resolveDebugConfigurationWithSubstitutedVariables(launch && launch.workspace ? launch.workspace.uri : undefined, resolvedConfig.type, resolvedConfig, initCancellationToken.token); if (!cfg) { if (launch && type && cfg === null && !initCancellationToken.token.isCancellationRequested) { // show launch.json only for "config" being "null". await launch.openConfigFile({ preserveFocus: true, type }, initCancellationToken.token); } return false; } resolvedConfig = cfg; const dbg = this.adapterManager.getDebugger(resolvedConfig.type); if (!dbg || (configByProviders.request !== 'attach' && configByProviders.request !== 'launch')) { let message: string; if (configByProviders.request !== 'attach' && configByProviders.request !== 'launch') { message = configByProviders.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', configByProviders.request) : nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request'); } else { message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) : nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."); } const actionList: IAction[] = []; actionList.push(new Action( 'installAdditionalDebuggers', nls.localize({ key: 'installAdditionalDebuggers', comment: ['Placeholder is the debug type, so for example "node", "python"'] }, "Install {0} Extension", resolvedConfig.type), undefined, true, async () => this.commandService.executeCommand('debug.installAdditionalDebuggers', resolvedConfig?.type) )); await this.showError(message, actionList); return false; } if (!dbg.enabled) { await this.showError(debuggerDisabledMessage(dbg.type), []); return false; } const result = await this.doCreateSession(sessionId, launch?.workspace, { resolved: resolvedConfig, unresolved: unresolvedConfig }, options); if (result && guess && activeEditor && activeEditor.resource) { // Remeber user choice of environment per active editor to make starting debugging smoother #124770 this.chosenEnvironments[activeEditor.resource.toString()] = guess.type; this.debugStorage.storeChosenEnvironments(this.chosenEnvironments); } return result; } catch (err) { if (err && err.message) { await this.showError(err.message); } else if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) { await this.showError(nls.localize('noFolderWorkspaceDebugError', "The active file can not be debugged. Make sure it is saved and that you have a debug extension installed for that file type.")); } if (launch && !initCancellationToken.token.isCancellationRequested) { await launch.openConfigFile({ preserveFocus: true }, initCancellationToken.token); } return false; } } if (launch && type && configByProviders === null && !initCancellationToken.token.isCancellationRequested) { // show launch.json only for "config" being "null". await launch.openConfigFile({ preserveFocus: true, type }, initCancellationToken.token); } return false; } /** * instantiates the new session, initializes the session, registers session listeners and reports telemetry */ private async doCreateSession(sessionId: string, root: IWorkspaceFolder | undefined, configuration: { resolved: IConfig; unresolved: IConfig | undefined }, options?: IDebugSessionOptions): Promise<boolean> { const session = this.instantiationService.createInstance(DebugSession, sessionId, configuration, root, this.model, options); if (options?.startedByUser && this.model.getSessions().some(s => s.getLabel() === session.getLabel()) && configuration.resolved.suppressMultipleSessionWarning !== true) { // There is already a session with the same name, prompt user #127721 const result = await this.dialogService.confirm({ message: nls.localize('multipleSession', "'{0}' is already running. Do you want to start another instance?", session.getLabel()) }); if (!result.confirmed) { return false; } } this.model.addSession(session); // register listeners as the very first thing! this.registerSessionListeners(session); // since the Session is now properly registered under its ID and hooked, we can announce it // this event doesn't go to extensions this._onWillNewSession.fire(session); const openDebug = this.configurationService.getValue<IDebugConfiguration>('debug').openDebug; // Open debug viewlet based on the visibility of the side bar and openDebug setting. Do not open for 'run without debug' if (!configuration.resolved.noDebug && (openDebug === 'openOnSessionStart' || (openDebug !== 'neverOpen' && this.viewModel.firstSessionStart)) && !session.suppressDebugView) { await this.paneCompositeService.openPaneComposite(VIEWLET_ID, ViewContainerLocation.Sidebar); } try { await this.launchOrAttachToSession(session); const internalConsoleOptions = session.configuration.internalConsoleOptions || this.configurationService.getValue<IDebugConfiguration>('debug').internalConsoleOptions; if (internalConsoleOptions === 'openOnSessionStart' || (this.viewModel.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) { this.viewsService.openView(REPL_VIEW_ID, false); } this.viewModel.firstSessionStart = false; const showSubSessions = this.configurationService.getValue<IDebugConfiguration>('debug').showSubSessionsInToolBar; const sessions = this.model.getSessions(); const shownSessions = showSubSessions ? sessions : sessions.filter(s => !s.parentSession); if (shownSessions.length > 1) { this.viewModel.setMultiSessionView(true); } // since the initialized response has arrived announce the new Session (including extensions) this._onDidNewSession.fire(session); return true; } catch (error) { if (errors.isCancellationError(error)) { // don't show 'canceled' error messages to the user #7906 return false; } // Show the repl if some error got logged there #5870 if (session && session.getReplElements().length > 0) { this.viewsService.openView(REPL_VIEW_ID, false); } if (session.configuration && session.configuration.request === 'attach' && session.configuration.__autoAttach) { // ignore attach timeouts in auto attach mode return false; } const errorMessage = error instanceof Error ? error.message : error; if (error.showUser !== false) { // Only show the error when showUser is either not defined, or is true #128484 await this.showError(errorMessage, isErrorWithActions(error) ? error.actions : []); } return false; } } private async launchOrAttachToSession(session: IDebugSession, forceFocus = false): Promise<void> { const dbgr = this.adapterManager.getDebugger(session.configuration.type); try { await session.initialize(dbgr!); await session.launchOrAttach(session.configuration); const launchJsonExists = !!session.root && !!this.configurationService.getValue<IGlobalConfig>('launch', { resource: session.root.uri }); await this.telemetry.logDebugSessionStart(dbgr!, launchJsonExists); if (forceFocus || !this.viewModel.focusedSession || (session.parentSession === this.viewModel.focusedSession && session.compact)) { await this.focusStackFrame(undefined, undefined, session); } } catch (err) { if (this.viewModel.focusedSession === session) { await this.focusStackFrame(undefined); } return Promise.reject(err); } } private registerSessionListeners(session: DebugSession): void { const listenerDisposables = new DisposableStore(); this.disposables.add(listenerDisposables); const sessionRunningScheduler = listenerDisposables.add(new RunOnceScheduler(() => { // Do not immediatly defocus the stack frame if the session is running if (session.state === State.Running && this.viewModel.focusedSession === session) { this.viewModel.setFocus(undefined, this.viewModel.focusedThread, session, false); } }, 200)); listenerDisposables.add(session.onDidChangeState(() => { if (session.state === State.Running && this.viewModel.focusedSession === session) { sessionRunningScheduler.schedule(); } if (session === this.viewModel.focusedSession) { this.onStateChange(); } })); listenerDisposables.add(this.onDidEndSession(e => { if (e.session === session && !e.restart) { this.disposables.delete(listenerDisposables); } })); listenerDisposables.add(session.onDidEndAdapter(async adapterExitEvent => { if (adapterExitEvent) { if (adapterExitEvent.error) { this.notificationService.error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly ({0})", adapterExitEvent.error.message || adapterExitEvent.error.toString())); } this.telemetry.logDebugSessionStop(session, adapterExitEvent); } // 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905 const extensionDebugSession = getExtensionHostDebugSession(session); if (extensionDebugSession && extensionDebugSession.state === State.Running && extensionDebugSession.configuration.noDebug) { this.extensionHostDebugService.close(extensionDebugSession.getId()); } if (session.configuration.postDebugTask) { const root = session.root ?? this.contextService.getWorkspace(); try { await this.taskRunner.runTask(root, session.configuration.postDebugTask); } catch (err) { this.notificationService.error(err); } } this.endInitializingState(); this.cancelTokens(session.getId()); this._onDidEndSession.fire({ session, restart: this.restartingSessions.has(session) }); const focusedSession = this.viewModel.focusedSession; if (focusedSession && focusedSession.getId() === session.getId()) { const { session, thread, stackFrame } = getStackFrameThreadAndSessionToFocus(this.model, undefined, undefined, undefined, focusedSession); this.viewModel.setFocus(stackFrame, thread, session, false); } if (this.model.getSessions().length === 0) { this.viewModel.setMultiSessionView(false); if (this.layoutService.isVisible(Parts.SIDEBAR_PART) && this.configurationService.getValue<IDebugConfiguration>('debug').openExplorerOnEnd) { this.paneCompositeService.openPaneComposite(EXPLORER_VIEWLET_ID, ViewContainerLocation.Sidebar); } // Data breakpoints that can not be persisted should be cleared when a session ends const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => !dbp.canPersist); dataBreakpoints.forEach(dbp => this.model.removeDataBreakpoints(dbp.getId())); if (this.configurationService.getValue<IDebugConfiguration>('debug').console.closeOnEnd) { const debugConsoleContainer = this.viewDescriptorService.getViewContainerByViewId(REPL_VIEW_ID); if (debugConsoleContainer && this.viewsService.isViewContainerVisible(debugConsoleContainer.id)) { this.viewsService.closeViewContainer(debugConsoleContainer.id); } } } this.model.removeExceptionBreakpointsForSession(session.getId()); // session.dispose(); TODO@roblourens })); } async restartSession(session: IDebugSession, restartData?: any): Promise<any> { if (session.saveBeforeRestart) { await saveAllBeforeDebugStart(this.configurationService, this.editorService); } const isAutoRestart = !!restartData; const runTasks: () => Promise<TaskRunResult> = async () => { if (isAutoRestart) { // Do not run preLaunch and postDebug tasks for automatic restarts return Promise.resolve(TaskRunResult.Success); } const root = session.root || this.contextService.getWorkspace(); await this.taskRunner.runTask(root, session.configuration.preRestartTask); await this.taskRunner.runTask(root, session.configuration.postDebugTask); const taskResult1 = await this.taskRunner.runTaskAndCheckErrors(root, session.configuration.preLaunchTask); if (taskResult1 !== TaskRunResult.Success) { return taskResult1; } return this.taskRunner.runTaskAndCheckErrors(root, session.configuration.postRestartTask); }; const extensionDebugSession = getExtensionHostDebugSession(session); if (extensionDebugSession) { const taskResult = await runTasks(); if (taskResult === TaskRunResult.Success) { this.extensionHostDebugService.reload(extensionDebugSession.getId()); } return; } // Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration let needsToSubstitute = false; let unresolved: IConfig | undefined; const launch = session.root ? this.configurationManager.getLaunch(session.root.uri) : undefined; if (launch) { unresolved = launch.getConfiguration(session.configuration.name); if (unresolved && !equals(unresolved, session.unresolvedConfiguration)) { // Take the type from the session since the debug extension might overwrite it #21316 unresolved.type = session.configuration.type; unresolved.noDebug = session.configuration.noDebug; needsToSubstitute = true; } } let resolved: IConfig | undefined | null = session.configuration; if (launch && needsToSubstitute && unresolved) { const initCancellationToken = new CancellationTokenSource(); this.sessionCancellationTokens.set(session.getId(), initCancellationToken); const resolvedByProviders = await this.configurationManager.resolveConfigurationByProviders(launch.workspace ? launch.workspace.uri : undefined, unresolved.type, unresolved, initCancellationToken.token); if (resolvedByProviders) { resolved = await this.substituteVariables(launch, resolvedByProviders); if (resolved && !initCancellationToken.token.isCancellationRequested) { resolved = await this.configurationManager.resolveDebugConfigurationWithSubstitutedVariables(launch && launch.workspace ? launch.workspace.uri : undefined, unresolved.type, resolved, initCancellationToken.token); } } else { resolved = resolvedByProviders; } } if (resolved) { session.setConfiguration({ resolved, unresolved }); } session.configuration.__restart = restartData; const doRestart = async (fn: () => Promise<boolean | undefined>) => { this.restartingSessions.add(session); let didRestart = false; try { didRestart = (await fn()) !== false; } catch (e) { didRestart = false; throw e; } finally { this.restartingSessions.delete(session); // we previously may have issued an onDidEndSession with restart: true, // assuming the adapter exited (in `registerSessionListeners`). But the // restart failed, so emit the final termination now. if (!didRestart) { this._onDidEndSession.fire({ session, restart: false }); } } }; if (session.capabilities.supportsRestartRequest) { const taskResult = await runTasks(); if (taskResult === TaskRunResult.Success) { await doRestart(async () => { await session.restart(); return true; }); } return; } const shouldFocus = !!this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId(); return doRestart(async () => { // If the restart is automatic -> disconnect, otherwise -> terminate #55064 if (isAutoRestart) { await session.disconnect(true); } else { await session.terminate(true); } return new Promise<boolean>((c, e) => { setTimeout(async () => { const taskResult = await runTasks(); if (taskResult !== TaskRunResult.Success) { return c(false); } if (!resolved) { return c(false); } try { await this.launchOrAttachToSession(session, shouldFocus); this._onDidNewSession.fire(session); c(true); } catch (error) { e(error); } }, 300); }); }); } async stopSession(session: IDebugSession | undefined, disconnect = false, suspend = false): Promise<any> { if (session) { return disconnect ? session.disconnect(undefined, suspend) : session.terminate(); } const sessions = this.model.getSessions(); if (sessions.length === 0) { this.taskRunner.cancel(); // User might have cancelled starting of a debug session, and in some cases the quick pick is left open await this.quickInputService.cancel(); this.endInitializingState(); this.cancelTokens(undefined); } return Promise.all(sessions.map(s => disconnect ? s.disconnect(undefined, suspend) : s.terminate())); } private async substituteVariables(launch: ILaunch | undefined, config: IConfig): Promise<IConfig | undefined> { const dbg = this.adapterManager.getDebugger(config.type); if (dbg) { let folder: IWorkspaceFolder | undefined = undefined; if (launch && launch.workspace) { folder = launch.workspace; } else { const folders = this.contextService.getWorkspace().folders; if (folders.length === 1) { folder = folders[0]; } } try { return await dbg.substituteVariables(folder, config); } catch (err) { this.showError(err.message, undefined, !!launch?.getConfiguration(config.name)); return undefined; // bail out } } return Promise.resolve(config); } private async showError(message: string, errorActions: ReadonlyArray<IAction> = [], promptLaunchJson = true): Promise<void> { const configureAction = new Action(DEBUG_CONFIGURE_COMMAND_ID, DEBUG_CONFIGURE_LABEL, undefined, true, () => this.commandService.executeCommand(DEBUG_CONFIGURE_COMMAND_ID)); // Don't append the standard command if id of any provided action indicates it is a command const actions = errorActions.filter((action) => action.id.endsWith('.command')).length > 0 ? errorActions : [...errorActions, ...(promptLaunchJson ? [configureAction] : [])]; await this.dialogService.prompt({ type: severity.Error, message, buttons: actions.map(action => ({ label: action.label, run: () => action.run() })), cancelButton: true }); } //---- focus management async focusStackFrame(_stackFrame: IStackFrame | undefined, _thread?: IThread, _session?: IDebugSession, options?: { explicit?: boolean; preserveFocus?: boolean; sideBySide?: boolean; pinned?: boolean }): Promise<void> { const { stackFrame, thread, session } = getStackFrameThreadAndSessionToFocus(this.model, _stackFrame, _thread, _session); if (stackFrame) { const editor = await stackFrame.openInEditor(this.editorService, options?.preserveFocus ?? true, options?.sideBySide, options?.pinned); if (editor) { if (editor.input === DisassemblyViewInput.instance) { // Go to address is invoked via setFocus } else { const control = editor.getControl(); if (stackFrame && isCodeEditor(control) && control.hasModel()) { const model = control.getModel(); const lineNumber = stackFrame.range.startLineNumber; if (lineNumber >= 1 && lineNumber <= model.getLineCount()) { const lineContent = control.getModel().getLineContent(lineNumber); aria.alert(nls.localize({ key: 'debuggingPaused', comment: ['First placeholder is the file line content, second placeholder is the reason why debugging is stopped, for example "breakpoint", third is the stack frame name, and last is the line number.'] }, "{0}, debugging paused {1}, {2}:{3}", lineContent, thread && thread.stoppedDetails ? `, reason ${thread.stoppedDetails.reason}` : '', stackFrame.source ? stackFrame.source.name : '', stackFrame.range.startLineNumber)); } } } } } if (session) { this.debugType.set(session.configuration.type); } else { this.debugType.reset(); } this.viewModel.setFocus(stackFrame, thread, session, !!options?.explicit); } //---- watches addWatchExpression(name?: string): void { const we = this.model.addWatchExpression(name); if (!name) { this.viewModel.setSelectedExpression(we, false); } this.debugStorage.storeWatchExpressions(this.model.getWatchExpressions()); } renameWatchExpression(id: string, newName: string): void { this.model.renameWatchExpression(id, newName); this.debugStorage.storeWatchExpressions(this.model.getWatchExpressions()); } moveWatchExpression(id: string, position: number): void { this.model.moveWatchExpression(id, position); this.debugStorage.storeWatchExpressions(this.model.getWatchExpressions()); } removeWatchExpressions(id?: string): void { this.model.removeWatchExpressions(id); this.debugStorage.storeWatchExpressions(this.model.getWatchExpressions()); } //---- breakpoints canSetBreakpointsIn(model: ITextModel): boolean { return this.adapterManager.canSetBreakpointsIn(model); } async enableOrDisableBreakpoints(enable: boolean, breakpoint?: IEnablement): Promise<void> { if (breakpoint) { this.model.setEnablement(breakpoint, enable); this.debugStorage.storeBreakpoints(this.model); if (breakpoint instanceof Breakpoint) { await this.sendBreakpoints(breakpoint.originalUri); } else if (breakpoint instanceof FunctionBreakpoint) { await this.sendFunctionBreakpoints(); } else if (breakpoint instanceof DataBreakpoint) { await this.sendDataBreakpoints(); } else if (breakpoint instanceof InstructionBreakpoint) { await this.sendInstructionBreakpoints(); } else { await this.sendExceptionBreakpoints(); } } else { this.model.enableOrDisableAllBreakpoints(enable); this.debugStorage.storeBreakpoints(this.model); await this.sendAllBreakpoints(); } this.debugStorage.storeBreakpoints(this.model); } async addBreakpoints(uri: uri, rawBreakpoints: IBreakpointData[], ariaAnnounce = true): Promise<IBreakpoint[]> { const breakpoints = this.model.addBreakpoints(uri, rawBreakpoints); if (ariaAnnounce) { breakpoints.forEach(bp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", bp.lineNumber, uri.fsPath))); } // In some cases we need to store breakpoints before we send them because sending them can take a long time // And after sending them because the debug adapter can attach adapter data to a breakpoint this.debugStorage.storeBreakpoints(this.model); await this.sendBreakpoints(uri); this.debugStorage.storeBreakpoints(this.model); return breakpoints; } async updateBreakpoints(uri: uri, data: Map<string, DebugProtocol.Breakpoint>, sendOnResourceSaved: boolean): Promise<void> { this.model.updateBreakpoints(data); this.debugStorage.storeBreakpoints(this.model); if (sendOnResourceSaved) { this.breakpointsToSendOnResourceSaved.add(uri); } else { await this.sendBreakpoints(uri); this.debugStorage.storeBreakpoints(this.model); } } async removeBreakpoints(id?: string): Promise<void> { const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id); // note: using the debugger-resolved uri for aria to reflect UI state toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath))); const urisToClear = distinct(toRemove, bp => bp.originalUri.toString()).map(bp => bp.originalUri); this.model.removeBreakpoints(toRemove); this.debugStorage.storeBreakpoints(this.model); await Promise.all(urisToClear.map(uri => this.sendBreakpoints(uri))); } setBreakpointsActivated(activated: boolean): Promise<void> { this.model.setBreakpointsActivated(activated); return this.sendAllBreakpoints(); } addFunctionBreakpoint(name?: string, id?: string): void { this.model.addFunctionBreakpoint(name || '', id); } async updateFunctionBreakpoint(id: string, update: { name?: string; hitCondition?: string; condition?: string }): Promise<void> { this.model.updateFunctionBreakpoint(id, update); this.debugStorage.storeBreakpoints(this.model); await this.sendFunctionBreakpoints(); } async removeFunctionBreakpoints(id?: string): Promise<void> { this.model.removeFunctionBreakpoints(id); this.debugStorage.storeBreakpoints(this.model); await this.sendFunctionBreakpoints(); } async addDataBreakpoint(label: string, dataId: string, canPersist: boolean, accessTypes: DebugProtocol.DataBreakpointAccessType[] | undefined, accessType: DebugProtocol.DataBreakpointAccessType): Promise<void> { this.model.addDataBreakpoint(label, dataId, canPersist, accessTypes, accessType); this.debugStorage.storeBreakpoints(this.model); await this.sendDataBreakpoints(); this.debugStorage.storeBreakpoints(this.model); } async updateDataBreakpoint(id: string, update: { hitCondition?: string; condition?: string }): Promise<void> { this.model.updateDataBreakpoint(id, update); this.debugStorage.storeBreakpoints(this.model); await this.sendDataBreakpoints(); } async removeDataBreakpoints(id?: string): Promise<void> { this.model.removeDataBreakpoints(id); this.debugStorage.storeBreakpoints(this.model); await this.sendDataBreakpoints(); } async addInstructionBreakpoint(instructionReference: string, offset: number, address: bigint, condition?: string, hitCondition?: string): Promise<void> { this.model.addInstructionBreakpoint(instructionReference, offset, address, condition, hitCondition); this.debugStorage.storeBreakpoints(this.model); await this.sendInstructionBreakpoints(); this.debugStorage.storeBreakpoints(this.model); } async removeInstructionBreakpoints(instructionReference?: string, offset?: number): Promise<void> { this.model.removeInstructionBreakpoints(instructionReference, offset); this.debugStorage.storeBreakpoints(this.model); await this.sendInstructionBreakpoints(); } setExceptionBreakpointFallbackSession(sessionId: string) { this.model.setExceptionBreakpointFallbackSession(sessionId); this.debugStorage.storeBreakpoints(this.model); } setExceptionBreakpointsForSession(session: IDebugSession, data: DebugProtocol.ExceptionBreakpointsFilter[]): void { this.model.setExceptionBreakpointsForSession(session.getId(), data); this.debugStorage.storeBreakpoints(this.model); } async setExceptionBreakpointCondition(exceptionBreakpoint: IExceptionBreakpoint, condition: string | undefined): Promise<void> { this.model.setExceptionBreakpointCondition(exceptionBreakpoint, condition); this.debugStorage.storeBreakpoints(this.model); await this.sendExceptionBreakpoints(); } async sendAllBreakpoints(session?: IDebugSession): Promise<any> { const setBreakpointsPromises = distinct(this.model.getBreakpoints(), bp => bp.originalUri.toString()) .map(bp => this.sendBreakpoints(bp.originalUri, false, session)); // If sending breakpoints to one session which we know supports the configurationDone request, can make all requests in parallel if (session?.capabilities.supportsConfigurationDoneRequest) { await Promise.all([ ...setBreakpointsPromises, this.sendFunctionBreakpoints(session), this.sendDataBreakpoints(session), this.sendInstructionBreakpoints(session), this.sendExceptionBreakpoints(session), ]); } else { await Promise.all(setBreakpointsPromises); await this.sendFunctionBreakpoints(session); await this.sendDataBreakpoints(session); await this.sendInstructionBreakpoints(session); // send exception breakpoints at the end since some debug adapters may rely on the order - this was the case before // the configurationDone request was introduced. await this.sendExceptionBreakpoints(session); } } private async sendBreakpoints(modelUri: uri, sourceModified = false, session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getBreakpoints({ originalUri: modelUri, enabledOnly: true }); await sendToOneOrAllSessions(this.model, session, async s => { if (!s.configuration.noDebug) { await s.sendBreakpoints(modelUri, breakpointsToSend, sourceModified); } }); } private async sendFunctionBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); await sendToOneOrAllSessions(this.model, session, async s => { if (s.capabilities.supportsFunctionBreakpoints && !s.configuration.noDebug) { await s.sendFunctionBreakpoints(breakpointsToSend); } }); } private async sendDataBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getDataBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); await sendToOneOrAllSessions(this.model, session, async s => { if (s.capabilities.supportsDataBreakpoints && !s.configuration.noDebug) { await s.sendDataBreakpoints(breakpointsToSend); } }); } private async sendInstructionBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getInstructionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); await sendToOneOrAllSessions(this.model, session, async s => { if (s.capabilities.supportsInstructionBreakpoints && !s.configuration.noDebug) { await s.sendInstructionBreakpoints(breakpointsToSend); } }); } private sendExceptionBreakpoints(session?: IDebugSession): Promise<void> { return sendToOneOrAllSessions(this.model, session, async s => { const enabledExceptionBps = this.model.getExceptionBreakpointsForSession(s.getId()).filter(exb => exb.enabled); if (s.capabilities.supportsConfigurationDoneRequest && (!s.capabilities.exceptionBreakpointFilters || s.capabilities.exceptionBreakpointFilters.length === 0)) { // Only call `setExceptionBreakpoints` as specified in dap protocol #90001 return; } if (!s.configuration.noDebug) { await s.sendExceptionBreakpoints(enabledExceptionBps); } }); } private onFileChanges(fileChangesEvent: FileChangesEvent): void { const toRemove = this.model.getBreakpoints().filter(bp => fileChangesEvent.contains(bp.originalUri, FileChangeType.DELETED)); if (toRemove.length) { this.model.removeBreakpoints(toRemove); } const toSend: URI[] = []; for (const uri of this.breakpointsToSendOnResourceSaved) { if (fileChangesEvent.contains(uri, FileChangeType.UPDATED)) { toSend.push(uri); } } for (const uri of toSend) { this.breakpointsToSendOnResourceSaved.delete(uri); this.sendBreakpoints(uri, true); } } async runTo(uri: uri, lineNumber: number, column?: number): Promise<void> { let breakpointToRemove: IBreakpoint | undefined; let threadToContinue = this.getViewModel().focusedThread; const addTempBreakPoint = async () => { const bpExists = !!(this.getModel().getBreakpoints({ column, lineNumber, uri }).length); if (!bpExists) { const addResult = await this.addAndValidateBreakpoints(uri, lineNumber, column); if (addResult.thread) { threadToContinue = addResult.thread; } if (addResult.breakpoint) { breakpointToRemove = addResult.breakpoint; } } return { threadToContinue, breakpointToRemove }; }; const removeTempBreakPoint = (state: State): boolean => { if (state === State.Stopped || state === State.Inactive) { if (breakpointToRemove) { this.removeBreakpoints(breakpointToRemove.getId()); } return true; } return false; }; await addTempBreakPoint(); if (this.state === State.Inactive) { // If no session exists start the debugger const { launch, name, getConfig } = this.getConfigurationManager().selectedConfiguration; const config = await getConfig(); const configOrName = config ? Object.assign(deepClone(config), {}) : name; const listener = this.onDidChangeState(state => { if (removeTempBreakPoint(state)) { listener.dispose(); } }); await this.startDebugging(launch, configOrName, undefined, true); } if (this.state === State.Stopped) { const focusedSession = this.getViewModel().focusedSession; if (!focusedSession || !threadToContinue) { return; } const listener = threadToContinue.session.onDidChangeState(() => { if (removeTempBreakPoint(focusedSession.state)) { listener.dispose(); } }); await threadToContinue.continue(); } } private async addAndValidateBreakpoints(uri: URI, lineNumber: number, column?: number) { const debugModel = this.getModel(); const viewModel = this.getViewModel(); const breakpoints = await this.addBreakpoints(uri, [{ lineNumber, column }], false); const breakpoint = breakpoints?.[0]; if (!breakpoint) { return { breakpoint: undefined, thread: viewModel.focusedThread }; } // If the breakpoint was not initially verified, wait up to 2s for it to become so. // Inherently racey if multiple sessions can verify async, but not solvable... if (!breakpoint.verified) { let listener: IDisposable; await raceTimeout(new Promise<void>(resolve => { listener = debugModel.onDidChangeBreakpoints(() => { if (breakpoint.verified) { resolve(); } }); }), 2000); listener!.dispose(); } // Look at paused threads for sessions that verified this bp. Prefer, in order: const enum Score { /** The focused thread */ Focused, /** Any other stopped thread of a session that verified the bp */ Verified, /** Any thread that verified and paused in the same file */ VerifiedAndPausedInFile, /** The focused thread if it verified the breakpoint */ VerifiedAndFocused, } let bestThread = viewModel.focusedThread; let bestScore = Score.Focused; for (const sessionId of breakpoint.sessionsThatVerified) { const session = debugModel.getSession(sessionId); if (!session) { continue; } const threads = session.getAllThreads().filter(t => t.stopped); if (bestScore < Score.VerifiedAndFocused) { if (viewModel.focusedThread && threads.includes(viewModel.focusedThread)) { bestThread = viewModel.focusedThread; bestScore = Score.VerifiedAndFocused; } } if (bestScore < Score.VerifiedAndPausedInFile) { const pausedInThisFile = threads.find(t => { const top = t.getTopStackFrame(); return top && this.uriIdentityService.extUri.isEqual(top.source.uri, uri); }); if (pausedInThisFile) { bestThread = pausedInThisFile; bestScore = Score.VerifiedAndPausedInFile; } } if (bestScore < Score.Verified) { bestThread = threads[0]; bestScore = Score.VerifiedAndPausedInFile; } } return { thread: bestThread, breakpoint }; } } export function getStackFrameThreadAndSessionToFocus(model: IDebugModel, stackFrame: IStackFrame | undefined, thread?: IThread, session?: IDebugSession, avoidSession?: IDebugSession): { stackFrame: IStackFrame | undefined; thread: IThread | undefined; session: IDebugSession | undefined } { if (!session) { if (stackFrame || thread) { session = stackFrame ? stackFrame.thread.session : thread!.session; } else { const sessions = model.getSessions(); const stoppedSession = sessions.find(s => s.state === State.Stopped); // Make sure to not focus session that is going down session = stoppedSession || sessions.find(s => s !== avoidSession && s !== avoidSession?.parentSession) || (sessions.length ? sessions[0] : undefined); } } if (!thread) { if (stackFrame) { thread = stackFrame.thread; } else { const threads = session ? session.getAllThreads() : undefined; const stoppedThread = threads && threads.find(t => t.stopped); thread = stoppedThread || (threads && threads.length ? threads[0] : undefined); } } if (!stackFrame && thread) { stackFrame = thread.getTopStackFrame(); } return { session, thread, stackFrame }; } async function sendToOneOrAllSessions(model: DebugModel, session: IDebugSession | undefined, send: (session: IDebugSession) => Promise<void>): Promise<void> { if (session) { await send(session); } else { await Promise.all(model.getSessions().map(s => send(s))); } }
src/vs/workbench/contrib/debug/browser/debugService.ts
1
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
[ 0.9990468621253967, 0.08145112544298172, 0.00016333865642081946, 0.00017417807248421013, 0.2694106698036194 ]
{ "id": 4, "code_window": [ "\t\t\t\t\tthis.notificationService.error(err);\n", "\t\t\t\t}\n", "\t\t\t}\n", "\t\t\tthis.endInitializingState();\n", "\t\t\tthis.cancelTokens(session.getId());\n", "\t\t\tthis._onDidEndSession.fire({ session, restart: this.restartingSessions.has(session) });\n", "\n", "\t\t\tconst focusedSession = this.viewModel.focusedSession;\n", "\t\t\tif (focusedSession && focusedSession.getId() === session.getId()) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\t\tif (this.configurationService.getValue<IDebugConfiguration>('debug').closeReadonlyTabsOnEnd) {\n", "\t\t\t\tconst editorsToClose = this.editorService.getEditors(EditorsOrder.SEQUENTIAL).filter(({ editor }) => {\n", "\t\t\t\t\tif (editor.resource?.scheme === DEBUG_SCHEME) {\n", "\t\t\t\t\t\treturn editor.isReadonly() && session.getId() === Source.getEncodedDebugData(editor.resource).sessionId;\n", "\t\t\t\t\t}\n", "\t\t\t\t\treturn false;\n", "\t\t\t\t});\n", "\t\t\t\tthis.editorService.closeEditors(editorsToClose);\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "add", "edit_start_line_idx": 706 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Disposable } from 'vs/base/common/lifecycle'; import { IExtensionGalleryService, IGlobalExtensionEnablementService } from 'vs/platform/extensionManagement/common/extensionManagement'; import { ExtensionStorageService, IExtensionStorageService } from 'vs/platform/extensionManagement/common/extensionStorage'; import { migrateUnsupportedExtensions } from 'vs/platform/extensionManagement/common/unsupportedExtensionsMigration'; import { INativeServerExtensionManagementService } from 'vs/platform/extensionManagement/node/extensionManagementService'; import { ILogService } from 'vs/platform/log/common/log'; import { IStorageService } from 'vs/platform/storage/common/storage'; export class ExtensionsContributions extends Disposable { constructor( @INativeServerExtensionManagementService extensionManagementService: INativeServerExtensionManagementService, @IExtensionGalleryService extensionGalleryService: IExtensionGalleryService, @IExtensionStorageService extensionStorageService: IExtensionStorageService, @IGlobalExtensionEnablementService extensionEnablementService: IGlobalExtensionEnablementService, @IStorageService storageService: IStorageService, @ILogService logService: ILogService, ) { super(); extensionManagementService.cleanUp(); migrateUnsupportedExtensions(extensionManagementService, extensionGalleryService, extensionStorageService, extensionEnablementService, logService); ExtensionStorageService.removeOutdatedExtensionVersions(extensionManagementService, storageService); } }
src/vs/code/node/sharedProcess/contrib/extensions.ts
0
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
[ 0.00017540472617838532, 0.00017287768423557281, 0.00017110117187257856, 0.00017250243399757892, 0.0000015971365883160615 ]
{ "id": 4, "code_window": [ "\t\t\t\t\tthis.notificationService.error(err);\n", "\t\t\t\t}\n", "\t\t\t}\n", "\t\t\tthis.endInitializingState();\n", "\t\t\tthis.cancelTokens(session.getId());\n", "\t\t\tthis._onDidEndSession.fire({ session, restart: this.restartingSessions.has(session) });\n", "\n", "\t\t\tconst focusedSession = this.viewModel.focusedSession;\n", "\t\t\tif (focusedSession && focusedSession.getId() === session.getId()) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\t\tif (this.configurationService.getValue<IDebugConfiguration>('debug').closeReadonlyTabsOnEnd) {\n", "\t\t\t\tconst editorsToClose = this.editorService.getEditors(EditorsOrder.SEQUENTIAL).filter(({ editor }) => {\n", "\t\t\t\t\tif (editor.resource?.scheme === DEBUG_SCHEME) {\n", "\t\t\t\t\t\treturn editor.isReadonly() && session.getId() === Source.getEncodedDebugData(editor.resource).sessionId;\n", "\t\t\t\t\t}\n", "\t\t\t\t\treturn false;\n", "\t\t\t\t});\n", "\t\t\t\tthis.editorService.closeEditors(editorsToClose);\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "add", "edit_start_line_idx": 706 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-workbench .bulk-edit-panel .highlight.insert { background-color: var(--vscode-diffEditor-insertedTextBackground); } .monaco-workbench .bulk-edit-panel .highlight.remove { text-decoration: line-through; background-color: var(--vscode-diffEditor-removedTextBackground); } .monaco-workbench .bulk-edit-panel .message { padding: 10px 20px } .monaco-workbench .bulk-edit-panel[data-state="message"] .message, .monaco-workbench .bulk-edit-panel[data-state="data"] .content { display: flex; } .monaco-workbench .bulk-edit-panel[data-state="data"] .message, .monaco-workbench .bulk-edit-panel[data-state="message"] .content { display: none; } .monaco-workbench .bulk-edit-panel .content { display: flex; flex-direction: column; justify-content: space-between; } .monaco-workbench .bulk-edit-panel .content .buttons { padding-left: 20px; padding-top: 10px; } .monaco-workbench .bulk-edit-panel .content .buttons .monaco-button { display: inline-flex; width: inherit; margin: 0 4px; padding: 4px 8px; } .monaco-workbench .bulk-edit-panel .monaco-tl-contents { display: flex; } .monaco-workbench .bulk-edit-panel .monaco-tl-contents .edit-checkbox { align-self: center; } .monaco-workbench .bulk-edit-panel .monaco-tl-contents .edit-checkbox.disabled { opacity: .5; } .monaco-workbench .bulk-edit-panel .monaco-tl-contents .monaco-icon-label.delete .monaco-icon-label-container { text-decoration: line-through; } .monaco-workbench .bulk-edit-panel .monaco-tl-contents .details { margin-left: .5em; opacity: .7; font-size: 0.9em; white-space: pre } .monaco-workbench .bulk-edit-panel .monaco-tl-contents.category { display: flex; flex: 1; flex-flow: row nowrap; align-items: center; } .monaco-workbench .bulk-edit-panel .monaco-tl-contents.category .theme-icon, .monaco-workbench .bulk-edit-panel .monaco-tl-contents.textedit .theme-icon { margin-right: 4px; } .monaco-workbench .bulk-edit-panel .monaco-tl-contents.category .uri-icon, .monaco-workbench .bulk-edit-panel .monaco-tl-contents.textedit .uri-icon, .monaco-workbench.hc-light .bulk-edit-panel .monaco-tl-contents.category .uri-icon, .monaco-workbench.hc-light .bulk-edit-panel .monaco-tl-contents.textedit .uri-icon { background-repeat: no-repeat; background-image: var(--background-light); background-position: left center; background-size: contain; margin-right: 4px; height: 100%; width: 16px; min-width: 16px; } .monaco-workbench.vs-dark .bulk-edit-panel .monaco-tl-contents.category .uri-icon, .monaco-workbench.hc-black .bulk-edit-panel .monaco-tl-contents.category .uri-icon, .monaco-workbench.vs-dark .bulk-edit-panel .monaco-tl-contents.textedit .uri-icon, .monaco-workbench.hc-black .bulk-edit-panel .monaco-tl-contents.textedit .uri-icon { background-image: var(--background-dark); } .monaco-workbench .bulk-edit-panel .monaco-tl-contents.textedit .monaco-highlighted-label { overflow: hidden; text-overflow: ellipsis; }
src/vs/workbench/contrib/bulkEdit/browser/preview/bulkEdit.css
0
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
[ 0.00017316149023827165, 0.00017230756930075586, 0.00017087180458474904, 0.00017261007451452315, 7.495690397263388e-7 ]
{ "id": 4, "code_window": [ "\t\t\t\t\tthis.notificationService.error(err);\n", "\t\t\t\t}\n", "\t\t\t}\n", "\t\t\tthis.endInitializingState();\n", "\t\t\tthis.cancelTokens(session.getId());\n", "\t\t\tthis._onDidEndSession.fire({ session, restart: this.restartingSessions.has(session) });\n", "\n", "\t\t\tconst focusedSession = this.viewModel.focusedSession;\n", "\t\t\tif (focusedSession && focusedSession.getId() === session.getId()) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\t\tif (this.configurationService.getValue<IDebugConfiguration>('debug').closeReadonlyTabsOnEnd) {\n", "\t\t\t\tconst editorsToClose = this.editorService.getEditors(EditorsOrder.SEQUENTIAL).filter(({ editor }) => {\n", "\t\t\t\t\tif (editor.resource?.scheme === DEBUG_SCHEME) {\n", "\t\t\t\t\t\treturn editor.isReadonly() && session.getId() === Source.getEncodedDebugData(editor.resource).sessionId;\n", "\t\t\t\t\t}\n", "\t\t\t\t\treturn false;\n", "\t\t\t\t});\n", "\t\t\t\tthis.editorService.closeEditors(editorsToClose);\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "add", "edit_start_line_idx": 706 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { WebContents, webContents, WebFrameMain } from 'electron'; import { Emitter } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import { FindInFrameOptions, FoundInFrameResult, IWebviewManagerService, WebviewWebContentsId, WebviewWindowId } from 'vs/platform/webview/common/webviewManagerService'; import { WebviewProtocolProvider } from 'vs/platform/webview/electron-main/webviewProtocolProvider'; import { IWindowsMainService } from 'vs/platform/windows/electron-main/windows'; export class WebviewMainService extends Disposable implements IWebviewManagerService { declare readonly _serviceBrand: undefined; private readonly _onFoundInFrame = this._register(new Emitter<FoundInFrameResult>()); public onFoundInFrame = this._onFoundInFrame.event; constructor( @IWindowsMainService private readonly windowsMainService: IWindowsMainService, ) { super(); this._register(new WebviewProtocolProvider()); } public async setIgnoreMenuShortcuts(id: WebviewWebContentsId | WebviewWindowId, enabled: boolean): Promise<void> { let contents: WebContents | undefined; if (typeof (id as WebviewWindowId).windowId === 'number') { const { windowId } = (id as WebviewWindowId); const window = this.windowsMainService.getWindowById(windowId); if (!window?.win) { throw new Error(`Invalid windowId: ${windowId}`); } contents = window.win.webContents; } else { const { webContentsId } = (id as WebviewWebContentsId); contents = webContents.fromId(webContentsId); if (!contents) { throw new Error(`Invalid webContentsId: ${webContentsId}`); } } if (!contents.isDestroyed()) { contents.setIgnoreMenuShortcuts(enabled); } } public async findInFrame(windowId: WebviewWindowId, frameName: string, text: string, options: { findNext?: boolean; forward?: boolean }): Promise<void> { const initialFrame = this.getFrameByName(windowId, frameName); type WebFrameMainWithFindSupport = WebFrameMain & { findInFrame?(text: string, findOptions: FindInFrameOptions): void; on(event: 'found-in-frame', listener: Function): WebFrameMain; removeListener(event: 'found-in-frame', listener: Function): WebFrameMain; }; const frame = initialFrame as unknown as WebFrameMainWithFindSupport; if (typeof frame.findInFrame === 'function') { frame.findInFrame(text, { findNext: options.findNext, forward: options.forward, }); const foundInFrameHandler = (_: unknown, result: FoundInFrameResult) => { if (result.finalUpdate) { this._onFoundInFrame.fire(result); frame.removeListener('found-in-frame', foundInFrameHandler); } }; frame.on('found-in-frame', foundInFrameHandler); } } public async stopFindInFrame(windowId: WebviewWindowId, frameName: string, options: { keepSelection?: boolean }): Promise<void> { const initialFrame = this.getFrameByName(windowId, frameName); type WebFrameMainWithFindSupport = WebFrameMain & { stopFindInFrame?(stopOption: 'keepSelection' | 'clearSelection'): void; }; const frame = initialFrame as unknown as WebFrameMainWithFindSupport; if (typeof frame.stopFindInFrame === 'function') { frame.stopFindInFrame(options.keepSelection ? 'keepSelection' : 'clearSelection'); } } private getFrameByName(windowId: WebviewWindowId, frameName: string): WebFrameMain { const window = this.windowsMainService.getWindowById(windowId.windowId); if (!window?.win) { throw new Error(`Invalid windowId: ${windowId}`); } const frame = window.win.webContents.mainFrame.framesInSubtree.find(frame => { return frame.name === frameName; }); if (!frame) { throw new Error(`Unknown frame: ${frameName}`); } return frame; } }
src/vs/platform/webview/electron-main/webviewMainService.ts
0
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
[ 0.00017646022024564445, 0.0001701632863841951, 0.0001657538814470172, 0.00016877902089618146, 0.0000035860066418536007 ]
{ "id": 5, "code_window": [ "\textensionHostDebugAdapter: boolean;\n", "\tenableAllHovers: boolean;\n", "\tshowSubSessionsInToolBar: boolean;\n", "\tconsole: {\n", "\t\tfontSize: number;\n", "\t\tfontFamily: string;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tcloseReadonlyTabsOnEnd: boolean;\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debug.ts", "type": "add", "edit_start_line_idx": 688 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as aria from 'vs/base/browser/ui/aria/aria'; import { Action, IAction } from 'vs/base/common/actions'; import { distinct } from 'vs/base/common/arrays'; import { raceTimeout, RunOnceScheduler } from 'vs/base/common/async'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { isErrorWithActions } from 'vs/base/common/errorMessage'; import * as errors from 'vs/base/common/errors'; import { Emitter, Event } from 'vs/base/common/event'; import { DisposableStore, IDisposable } from 'vs/base/common/lifecycle'; import { deepClone, equals } from 'vs/base/common/objects'; import severity from 'vs/base/common/severity'; import { URI, URI as uri } from 'vs/base/common/uri'; import { generateUuid } from 'vs/base/common/uuid'; import { isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { ITextModel } from 'vs/editor/common/model'; import * as nls from 'vs/nls'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity'; import { IWorkspaceContextService, IWorkspaceFolder, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { IWorkspaceTrustRequestService } from 'vs/platform/workspace/common/workspaceTrust'; import { EditorInput } from 'vs/workbench/common/editor/editorInput'; import { IViewDescriptorService, IViewsService, ViewContainerLocation } from 'vs/workbench/common/views'; import { AdapterManager } from 'vs/workbench/contrib/debug/browser/debugAdapterManager'; import { DEBUG_CONFIGURE_COMMAND_ID, DEBUG_CONFIGURE_LABEL } from 'vs/workbench/contrib/debug/browser/debugCommands'; import { ConfigurationManager } from 'vs/workbench/contrib/debug/browser/debugConfigurationManager'; import { DebugMemoryFileSystemProvider } from 'vs/workbench/contrib/debug/browser/debugMemory'; import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession'; import { DebugTaskRunner, TaskRunResult } from 'vs/workbench/contrib/debug/browser/debugTaskRunner'; import { CALLSTACK_VIEW_ID, CONTEXT_BREAKPOINTS_EXIST, CONTEXT_HAS_DEBUGGED, CONTEXT_DEBUG_STATE, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_UX, CONTEXT_DISASSEMBLY_VIEW_FOCUS, CONTEXT_IN_DEBUG_MODE, debuggerDisabledMessage, DEBUG_MEMORY_SCHEME, getStateLabel, IAdapterManager, IBreakpoint, IBreakpointData, ICompound, IConfig, IConfigurationManager, IDebugConfiguration, IDebugModel, IDebugService, IDebugSession, IDebugSessionOptions, IEnablement, IExceptionBreakpoint, IGlobalConfig, ILaunch, IStackFrame, IThread, IViewModel, REPL_VIEW_ID, State, VIEWLET_ID } from 'vs/workbench/contrib/debug/common/debug'; import { DebugCompoundRoot } from 'vs/workbench/contrib/debug/common/debugCompoundRoot'; import { Debugger } from 'vs/workbench/contrib/debug/common/debugger'; import { Breakpoint, DataBreakpoint, DebugModel, FunctionBreakpoint, InstructionBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel'; import { DebugStorage } from 'vs/workbench/contrib/debug/common/debugStorage'; import { DebugTelemetry } from 'vs/workbench/contrib/debug/common/debugTelemetry'; import { getExtensionHostDebugSession, saveAllBeforeDebugStart } from 'vs/workbench/contrib/debug/common/debugUtils'; import { ViewModel } from 'vs/workbench/contrib/debug/common/debugViewModel'; import { DisassemblyViewInput } from 'vs/workbench/contrib/debug/common/disassemblyViewInput'; import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/contrib/files/common/files'; import { IActivityService, NumberBadge } from 'vs/workbench/services/activity/common/activity'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService'; import { ILifecycleService } from 'vs/workbench/services/lifecycle/common/lifecycle'; import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite'; export class DebugService implements IDebugService { declare readonly _serviceBrand: undefined; private readonly _onDidChangeState: Emitter<State>; private readonly _onDidNewSession: Emitter<IDebugSession>; private readonly _onWillNewSession: Emitter<IDebugSession>; private readonly _onDidEndSession: Emitter<{ session: IDebugSession; restart: boolean }>; private readonly restartingSessions = new Set<IDebugSession>(); private debugStorage: DebugStorage; private model: DebugModel; private viewModel: ViewModel; private telemetry: DebugTelemetry; private taskRunner: DebugTaskRunner; private configurationManager: ConfigurationManager; private adapterManager: AdapterManager; private readonly disposables = new DisposableStore(); private debugType!: IContextKey<string>; private debugState!: IContextKey<string>; private inDebugMode!: IContextKey<boolean>; private debugUx!: IContextKey<string>; private hasDebugged!: IContextKey<boolean>; private breakpointsExist!: IContextKey<boolean>; private disassemblyViewFocus!: IContextKey<boolean>; private breakpointsToSendOnResourceSaved: Set<URI>; private initializing = false; private _initializingOptions: IDebugSessionOptions | undefined; private previousState: State | undefined; private sessionCancellationTokens = new Map<string, CancellationTokenSource>(); private activity: IDisposable | undefined; private chosenEnvironments: { [key: string]: string }; private haveDoneLazySetup = false; constructor( @IEditorService private readonly editorService: IEditorService, @IPaneCompositePartService private readonly paneCompositeService: IPaneCompositePartService, @IViewsService private readonly viewsService: IViewsService, @IViewDescriptorService private readonly viewDescriptorService: IViewDescriptorService, @INotificationService private readonly notificationService: INotificationService, @IDialogService private readonly dialogService: IDialogService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @ILifecycleService private readonly lifecycleService: ILifecycleService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IExtensionService private readonly extensionService: IExtensionService, @IFileService private readonly fileService: IFileService, @IConfigurationService private readonly configurationService: IConfigurationService, @IExtensionHostDebugService private readonly extensionHostDebugService: IExtensionHostDebugService, @IActivityService private readonly activityService: IActivityService, @ICommandService private readonly commandService: ICommandService, @IQuickInputService private readonly quickInputService: IQuickInputService, @IWorkspaceTrustRequestService private readonly workspaceTrustRequestService: IWorkspaceTrustRequestService, @IUriIdentityService private readonly uriIdentityService: IUriIdentityService ) { this.breakpointsToSendOnResourceSaved = new Set<URI>(); this._onDidChangeState = new Emitter<State>(); this._onDidNewSession = new Emitter<IDebugSession>(); this._onWillNewSession = new Emitter<IDebugSession>(); this._onDidEndSession = new Emitter(); this.adapterManager = this.instantiationService.createInstance(AdapterManager, { onDidNewSession: this.onDidNewSession }); this.disposables.add(this.adapterManager); this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this.adapterManager); this.disposables.add(this.configurationManager); this.debugStorage = this.disposables.add(this.instantiationService.createInstance(DebugStorage)); this.chosenEnvironments = this.debugStorage.loadChosenEnvironments(); this.model = this.instantiationService.createInstance(DebugModel, this.debugStorage); this.telemetry = this.instantiationService.createInstance(DebugTelemetry, this.model); this.viewModel = new ViewModel(contextKeyService); this.taskRunner = this.instantiationService.createInstance(DebugTaskRunner); this.disposables.add(this.fileService.onDidFilesChange(e => this.onFileChanges(e))); this.disposables.add(this.lifecycleService.onWillShutdown(this.dispose, this)); this.disposables.add(this.extensionHostDebugService.onAttachSession(event => { const session = this.model.getSession(event.sessionId, true); if (session) { // EH was started in debug mode -> attach to it session.configuration.request = 'attach'; session.configuration.port = event.port; session.setSubId(event.subId); this.launchOrAttachToSession(session); } })); this.disposables.add(this.extensionHostDebugService.onTerminateSession(event => { const session = this.model.getSession(event.sessionId); if (session && session.subId === event.subId) { session.disconnect(); } })); this.disposables.add(this.viewModel.onDidFocusStackFrame(() => { this.onStateChange(); })); this.disposables.add(this.viewModel.onDidFocusSession((session: IDebugSession | undefined) => { this.onStateChange(); if (session) { this.setExceptionBreakpointFallbackSession(session.getId()); } })); this.disposables.add(Event.any(this.adapterManager.onDidRegisterDebugger, this.configurationManager.onDidSelectConfiguration)(() => { const debugUxValue = (this.state !== State.Inactive || (this.configurationManager.getAllConfigurations().length > 0 && this.adapterManager.hasEnabledDebuggers())) ? 'default' : 'simple'; this.debugUx.set(debugUxValue); this.debugStorage.storeDebugUxState(debugUxValue); })); this.disposables.add(this.model.onDidChangeCallStack(() => { const numberOfSessions = this.model.getSessions().filter(s => !s.parentSession).length; this.activity?.dispose(); if (numberOfSessions > 0) { const viewContainer = this.viewDescriptorService.getViewContainerByViewId(CALLSTACK_VIEW_ID); if (viewContainer) { this.activity = this.activityService.showViewContainerActivity(viewContainer.id, { badge: new NumberBadge(numberOfSessions, n => n === 1 ? nls.localize('1activeSession', "1 active session") : nls.localize('nActiveSessions', "{0} active sessions", n)) }); } } })); this.disposables.add(editorService.onDidActiveEditorChange(() => { this.contextKeyService.bufferChangeEvents(() => { if (editorService.activeEditor === DisassemblyViewInput.instance) { this.disassemblyViewFocus.set(true); } else { // This key can be initialized a tick after this event is fired this.disassemblyViewFocus?.reset(); } }); })); this.disposables.add(this.lifecycleService.onBeforeShutdown(() => { for (const editor of editorService.editors) { // Editors will not be valid on window reload, so close them. if (editor.resource?.scheme === DEBUG_MEMORY_SCHEME) { editor.dispose(); } } })); this.initContextKeys(contextKeyService); } private initContextKeys(contextKeyService: IContextKeyService): void { queueMicrotask(() => { contextKeyService.bufferChangeEvents(() => { this.debugType = CONTEXT_DEBUG_TYPE.bindTo(contextKeyService); this.debugState = CONTEXT_DEBUG_STATE.bindTo(contextKeyService); this.hasDebugged = CONTEXT_HAS_DEBUGGED.bindTo(contextKeyService); this.inDebugMode = CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService); this.debugUx = CONTEXT_DEBUG_UX.bindTo(contextKeyService); this.debugUx.set(this.debugStorage.loadDebugUxState()); this.breakpointsExist = CONTEXT_BREAKPOINTS_EXIST.bindTo(contextKeyService); // Need to set disassemblyViewFocus here to make it in the same context as the debug event handlers this.disassemblyViewFocus = CONTEXT_DISASSEMBLY_VIEW_FOCUS.bindTo(contextKeyService); }); const setBreakpointsExistContext = () => this.breakpointsExist.set(!!(this.model.getBreakpoints().length || this.model.getDataBreakpoints().length || this.model.getFunctionBreakpoints().length)); setBreakpointsExistContext(); this.disposables.add(this.model.onDidChangeBreakpoints(() => setBreakpointsExistContext())); }); } getModel(): IDebugModel { return this.model; } getViewModel(): IViewModel { return this.viewModel; } getConfigurationManager(): IConfigurationManager { return this.configurationManager; } getAdapterManager(): IAdapterManager { return this.adapterManager; } sourceIsNotAvailable(uri: uri): void { this.model.sourceIsNotAvailable(uri); } dispose(): void { this.disposables.dispose(); } //---- state management get state(): State { const focusedSession = this.viewModel.focusedSession; if (focusedSession) { return focusedSession.state; } return this.initializing ? State.Initializing : State.Inactive; } get initializingOptions(): IDebugSessionOptions | undefined { return this._initializingOptions; } private startInitializingState(options?: IDebugSessionOptions): void { if (!this.initializing) { this.initializing = true; this._initializingOptions = options; this.onStateChange(); } } private endInitializingState(): void { if (this.initializing) { this.initializing = false; this._initializingOptions = undefined; this.onStateChange(); } } private cancelTokens(id: string | undefined): void { if (id) { const token = this.sessionCancellationTokens.get(id); if (token) { token.cancel(); this.sessionCancellationTokens.delete(id); } } else { this.sessionCancellationTokens.forEach(t => t.cancel()); this.sessionCancellationTokens.clear(); } } private onStateChange(): void { const state = this.state; if (this.previousState !== state) { this.contextKeyService.bufferChangeEvents(() => { this.debugState.set(getStateLabel(state)); this.inDebugMode.set(state !== State.Inactive); // Only show the simple ux if debug is not yet started and if no launch.json exists const debugUxValue = ((state !== State.Inactive && state !== State.Initializing) || (this.adapterManager.hasEnabledDebuggers() && this.configurationManager.selectedConfiguration.name)) ? 'default' : 'simple'; this.debugUx.set(debugUxValue); this.debugStorage.storeDebugUxState(debugUxValue); }); this.previousState = state; this._onDidChangeState.fire(state); } } get onDidChangeState(): Event<State> { return this._onDidChangeState.event; } get onDidNewSession(): Event<IDebugSession> { return this._onDidNewSession.event; } get onWillNewSession(): Event<IDebugSession> { return this._onWillNewSession.event; } get onDidEndSession(): Event<{ session: IDebugSession; restart: boolean }> { return this._onDidEndSession.event; } private lazySetup() { if (!this.haveDoneLazySetup) { // Registering fs providers is slow // https://github.com/microsoft/vscode/issues/159886 this.disposables.add(this.fileService.registerProvider(DEBUG_MEMORY_SCHEME, new DebugMemoryFileSystemProvider(this))); this.haveDoneLazySetup = true; } } //---- life cycle management /** * main entry point * properly manages compounds, checks for errors and handles the initializing state. */ async startDebugging(launch: ILaunch | undefined, configOrName?: IConfig | string, options?: IDebugSessionOptions, saveBeforeStart = !options?.parentSession): Promise<boolean> { const message = options && options.noDebug ? nls.localize('runTrust', "Running executes build tasks and program code from your workspace.") : nls.localize('debugTrust', "Debugging executes build tasks and program code from your workspace."); const trust = await this.workspaceTrustRequestService.requestWorkspaceTrust({ message }); if (!trust) { return false; } this.lazySetup(); this.startInitializingState(options); this.hasDebugged.set(true); try { // make sure to save all files and that the configuration is up to date await this.extensionService.activateByEvent('onDebug'); if (saveBeforeStart) { await saveAllBeforeDebugStart(this.configurationService, this.editorService); } await this.extensionService.whenInstalledExtensionsRegistered(); let config: IConfig | undefined; let compound: ICompound | undefined; if (!configOrName) { configOrName = this.configurationManager.selectedConfiguration.name; } if (typeof configOrName === 'string' && launch) { config = launch.getConfiguration(configOrName); compound = launch.getCompound(configOrName); } else if (typeof configOrName !== 'string') { config = configOrName; } if (compound) { // we are starting a compound debug, first do some error checking and than start each configuration in the compound if (!compound.configurations) { throw new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] }, "Compound must have \"configurations\" attribute set in order to start multiple configurations.")); } if (compound.preLaunchTask) { const taskResult = await this.taskRunner.runTaskAndCheckErrors(launch?.workspace || this.contextService.getWorkspace(), compound.preLaunchTask); if (taskResult === TaskRunResult.Failure) { this.endInitializingState(); return false; } } if (compound.stopAll) { options = { ...options, compoundRoot: new DebugCompoundRoot() }; } const values = await Promise.all(compound.configurations.map(configData => { const name = typeof configData === 'string' ? configData : configData.name; if (name === compound!.name) { return Promise.resolve(false); } let launchForName: ILaunch | undefined; if (typeof configData === 'string') { const launchesContainingName = this.configurationManager.getLaunches().filter(l => !!l.getConfiguration(name)); if (launchesContainingName.length === 1) { launchForName = launchesContainingName[0]; } else if (launch && launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) { // If there are multiple launches containing the configuration give priority to the configuration in the current launch launchForName = launch; } else { throw new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name) : nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name)); } } else if (configData.folder) { const launchesMatchingConfigData = this.configurationManager.getLaunches().filter(l => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name)); if (launchesMatchingConfigData.length === 1) { launchForName = launchesMatchingConfigData[0]; } else { throw new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound!.name)); } } return this.createSession(launchForName, launchForName!.getConfiguration(name), options); })); const result = values.every(success => !!success); // Compound launch is a success only if each configuration launched successfully this.endInitializingState(); return result; } if (configOrName && !config) { const message = !!launch ? nls.localize('configMissing', "Configuration '{0}' is missing in 'launch.json'.", typeof configOrName === 'string' ? configOrName : configOrName.name) : nls.localize('launchJsonDoesNotExist', "'launch.json' does not exist for passed workspace folder."); throw new Error(message); } const result = await this.createSession(launch, config, options); this.endInitializingState(); return result; } catch (err) { // make sure to get out of initializing state, and propagate the result this.notificationService.error(err); this.endInitializingState(); return Promise.reject(err); } } /** * gets the debugger for the type, resolves configurations by providers, substitutes variables and runs prelaunch tasks */ private async createSession(launch: ILaunch | undefined, config: IConfig | undefined, options?: IDebugSessionOptions): Promise<boolean> { // We keep the debug type in a separate variable 'type' so that a no-folder config has no attributes. // Storing the type in the config would break extensions that assume that the no-folder case is indicated by an empty config. let type: string | undefined; if (config) { type = config.type; } else { // a no-folder workspace has no launch.config config = Object.create(null); } if (options && options.noDebug) { config!.noDebug = true; } else if (options && typeof options.noDebug === 'undefined' && options.parentSession && options.parentSession.configuration.noDebug) { config!.noDebug = true; } const unresolvedConfig = deepClone(config); let guess: Debugger | undefined; let activeEditor: EditorInput | undefined; if (!type) { activeEditor = this.editorService.activeEditor; if (activeEditor && activeEditor.resource) { type = this.chosenEnvironments[activeEditor.resource.toString()]; } if (!type) { guess = await this.adapterManager.guessDebugger(false); if (guess) { type = guess.type; } } } const initCancellationToken = new CancellationTokenSource(); const sessionId = generateUuid(); this.sessionCancellationTokens.set(sessionId, initCancellationToken); const configByProviders = await this.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config!, initCancellationToken.token); // a falsy config indicates an aborted launch if (configByProviders && configByProviders.type) { try { let resolvedConfig = await this.substituteVariables(launch, configByProviders); if (!resolvedConfig) { // User cancelled resolving of interactive variables, silently return return false; } if (initCancellationToken.token.isCancellationRequested) { // User cancelled, silently return return false; } const workspace = launch?.workspace || this.contextService.getWorkspace(); const taskResult = await this.taskRunner.runTaskAndCheckErrors(workspace, resolvedConfig.preLaunchTask); if (taskResult === TaskRunResult.Failure) { return false; } const cfg = await this.configurationManager.resolveDebugConfigurationWithSubstitutedVariables(launch && launch.workspace ? launch.workspace.uri : undefined, resolvedConfig.type, resolvedConfig, initCancellationToken.token); if (!cfg) { if (launch && type && cfg === null && !initCancellationToken.token.isCancellationRequested) { // show launch.json only for "config" being "null". await launch.openConfigFile({ preserveFocus: true, type }, initCancellationToken.token); } return false; } resolvedConfig = cfg; const dbg = this.adapterManager.getDebugger(resolvedConfig.type); if (!dbg || (configByProviders.request !== 'attach' && configByProviders.request !== 'launch')) { let message: string; if (configByProviders.request !== 'attach' && configByProviders.request !== 'launch') { message = configByProviders.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', configByProviders.request) : nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request'); } else { message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) : nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."); } const actionList: IAction[] = []; actionList.push(new Action( 'installAdditionalDebuggers', nls.localize({ key: 'installAdditionalDebuggers', comment: ['Placeholder is the debug type, so for example "node", "python"'] }, "Install {0} Extension", resolvedConfig.type), undefined, true, async () => this.commandService.executeCommand('debug.installAdditionalDebuggers', resolvedConfig?.type) )); await this.showError(message, actionList); return false; } if (!dbg.enabled) { await this.showError(debuggerDisabledMessage(dbg.type), []); return false; } const result = await this.doCreateSession(sessionId, launch?.workspace, { resolved: resolvedConfig, unresolved: unresolvedConfig }, options); if (result && guess && activeEditor && activeEditor.resource) { // Remeber user choice of environment per active editor to make starting debugging smoother #124770 this.chosenEnvironments[activeEditor.resource.toString()] = guess.type; this.debugStorage.storeChosenEnvironments(this.chosenEnvironments); } return result; } catch (err) { if (err && err.message) { await this.showError(err.message); } else if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) { await this.showError(nls.localize('noFolderWorkspaceDebugError', "The active file can not be debugged. Make sure it is saved and that you have a debug extension installed for that file type.")); } if (launch && !initCancellationToken.token.isCancellationRequested) { await launch.openConfigFile({ preserveFocus: true }, initCancellationToken.token); } return false; } } if (launch && type && configByProviders === null && !initCancellationToken.token.isCancellationRequested) { // show launch.json only for "config" being "null". await launch.openConfigFile({ preserveFocus: true, type }, initCancellationToken.token); } return false; } /** * instantiates the new session, initializes the session, registers session listeners and reports telemetry */ private async doCreateSession(sessionId: string, root: IWorkspaceFolder | undefined, configuration: { resolved: IConfig; unresolved: IConfig | undefined }, options?: IDebugSessionOptions): Promise<boolean> { const session = this.instantiationService.createInstance(DebugSession, sessionId, configuration, root, this.model, options); if (options?.startedByUser && this.model.getSessions().some(s => s.getLabel() === session.getLabel()) && configuration.resolved.suppressMultipleSessionWarning !== true) { // There is already a session with the same name, prompt user #127721 const result = await this.dialogService.confirm({ message: nls.localize('multipleSession', "'{0}' is already running. Do you want to start another instance?", session.getLabel()) }); if (!result.confirmed) { return false; } } this.model.addSession(session); // register listeners as the very first thing! this.registerSessionListeners(session); // since the Session is now properly registered under its ID and hooked, we can announce it // this event doesn't go to extensions this._onWillNewSession.fire(session); const openDebug = this.configurationService.getValue<IDebugConfiguration>('debug').openDebug; // Open debug viewlet based on the visibility of the side bar and openDebug setting. Do not open for 'run without debug' if (!configuration.resolved.noDebug && (openDebug === 'openOnSessionStart' || (openDebug !== 'neverOpen' && this.viewModel.firstSessionStart)) && !session.suppressDebugView) { await this.paneCompositeService.openPaneComposite(VIEWLET_ID, ViewContainerLocation.Sidebar); } try { await this.launchOrAttachToSession(session); const internalConsoleOptions = session.configuration.internalConsoleOptions || this.configurationService.getValue<IDebugConfiguration>('debug').internalConsoleOptions; if (internalConsoleOptions === 'openOnSessionStart' || (this.viewModel.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) { this.viewsService.openView(REPL_VIEW_ID, false); } this.viewModel.firstSessionStart = false; const showSubSessions = this.configurationService.getValue<IDebugConfiguration>('debug').showSubSessionsInToolBar; const sessions = this.model.getSessions(); const shownSessions = showSubSessions ? sessions : sessions.filter(s => !s.parentSession); if (shownSessions.length > 1) { this.viewModel.setMultiSessionView(true); } // since the initialized response has arrived announce the new Session (including extensions) this._onDidNewSession.fire(session); return true; } catch (error) { if (errors.isCancellationError(error)) { // don't show 'canceled' error messages to the user #7906 return false; } // Show the repl if some error got logged there #5870 if (session && session.getReplElements().length > 0) { this.viewsService.openView(REPL_VIEW_ID, false); } if (session.configuration && session.configuration.request === 'attach' && session.configuration.__autoAttach) { // ignore attach timeouts in auto attach mode return false; } const errorMessage = error instanceof Error ? error.message : error; if (error.showUser !== false) { // Only show the error when showUser is either not defined, or is true #128484 await this.showError(errorMessage, isErrorWithActions(error) ? error.actions : []); } return false; } } private async launchOrAttachToSession(session: IDebugSession, forceFocus = false): Promise<void> { const dbgr = this.adapterManager.getDebugger(session.configuration.type); try { await session.initialize(dbgr!); await session.launchOrAttach(session.configuration); const launchJsonExists = !!session.root && !!this.configurationService.getValue<IGlobalConfig>('launch', { resource: session.root.uri }); await this.telemetry.logDebugSessionStart(dbgr!, launchJsonExists); if (forceFocus || !this.viewModel.focusedSession || (session.parentSession === this.viewModel.focusedSession && session.compact)) { await this.focusStackFrame(undefined, undefined, session); } } catch (err) { if (this.viewModel.focusedSession === session) { await this.focusStackFrame(undefined); } return Promise.reject(err); } } private registerSessionListeners(session: DebugSession): void { const listenerDisposables = new DisposableStore(); this.disposables.add(listenerDisposables); const sessionRunningScheduler = listenerDisposables.add(new RunOnceScheduler(() => { // Do not immediatly defocus the stack frame if the session is running if (session.state === State.Running && this.viewModel.focusedSession === session) { this.viewModel.setFocus(undefined, this.viewModel.focusedThread, session, false); } }, 200)); listenerDisposables.add(session.onDidChangeState(() => { if (session.state === State.Running && this.viewModel.focusedSession === session) { sessionRunningScheduler.schedule(); } if (session === this.viewModel.focusedSession) { this.onStateChange(); } })); listenerDisposables.add(this.onDidEndSession(e => { if (e.session === session && !e.restart) { this.disposables.delete(listenerDisposables); } })); listenerDisposables.add(session.onDidEndAdapter(async adapterExitEvent => { if (adapterExitEvent) { if (adapterExitEvent.error) { this.notificationService.error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly ({0})", adapterExitEvent.error.message || adapterExitEvent.error.toString())); } this.telemetry.logDebugSessionStop(session, adapterExitEvent); } // 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905 const extensionDebugSession = getExtensionHostDebugSession(session); if (extensionDebugSession && extensionDebugSession.state === State.Running && extensionDebugSession.configuration.noDebug) { this.extensionHostDebugService.close(extensionDebugSession.getId()); } if (session.configuration.postDebugTask) { const root = session.root ?? this.contextService.getWorkspace(); try { await this.taskRunner.runTask(root, session.configuration.postDebugTask); } catch (err) { this.notificationService.error(err); } } this.endInitializingState(); this.cancelTokens(session.getId()); this._onDidEndSession.fire({ session, restart: this.restartingSessions.has(session) }); const focusedSession = this.viewModel.focusedSession; if (focusedSession && focusedSession.getId() === session.getId()) { const { session, thread, stackFrame } = getStackFrameThreadAndSessionToFocus(this.model, undefined, undefined, undefined, focusedSession); this.viewModel.setFocus(stackFrame, thread, session, false); } if (this.model.getSessions().length === 0) { this.viewModel.setMultiSessionView(false); if (this.layoutService.isVisible(Parts.SIDEBAR_PART) && this.configurationService.getValue<IDebugConfiguration>('debug').openExplorerOnEnd) { this.paneCompositeService.openPaneComposite(EXPLORER_VIEWLET_ID, ViewContainerLocation.Sidebar); } // Data breakpoints that can not be persisted should be cleared when a session ends const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => !dbp.canPersist); dataBreakpoints.forEach(dbp => this.model.removeDataBreakpoints(dbp.getId())); if (this.configurationService.getValue<IDebugConfiguration>('debug').console.closeOnEnd) { const debugConsoleContainer = this.viewDescriptorService.getViewContainerByViewId(REPL_VIEW_ID); if (debugConsoleContainer && this.viewsService.isViewContainerVisible(debugConsoleContainer.id)) { this.viewsService.closeViewContainer(debugConsoleContainer.id); } } } this.model.removeExceptionBreakpointsForSession(session.getId()); // session.dispose(); TODO@roblourens })); } async restartSession(session: IDebugSession, restartData?: any): Promise<any> { if (session.saveBeforeRestart) { await saveAllBeforeDebugStart(this.configurationService, this.editorService); } const isAutoRestart = !!restartData; const runTasks: () => Promise<TaskRunResult> = async () => { if (isAutoRestart) { // Do not run preLaunch and postDebug tasks for automatic restarts return Promise.resolve(TaskRunResult.Success); } const root = session.root || this.contextService.getWorkspace(); await this.taskRunner.runTask(root, session.configuration.preRestartTask); await this.taskRunner.runTask(root, session.configuration.postDebugTask); const taskResult1 = await this.taskRunner.runTaskAndCheckErrors(root, session.configuration.preLaunchTask); if (taskResult1 !== TaskRunResult.Success) { return taskResult1; } return this.taskRunner.runTaskAndCheckErrors(root, session.configuration.postRestartTask); }; const extensionDebugSession = getExtensionHostDebugSession(session); if (extensionDebugSession) { const taskResult = await runTasks(); if (taskResult === TaskRunResult.Success) { this.extensionHostDebugService.reload(extensionDebugSession.getId()); } return; } // Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration let needsToSubstitute = false; let unresolved: IConfig | undefined; const launch = session.root ? this.configurationManager.getLaunch(session.root.uri) : undefined; if (launch) { unresolved = launch.getConfiguration(session.configuration.name); if (unresolved && !equals(unresolved, session.unresolvedConfiguration)) { // Take the type from the session since the debug extension might overwrite it #21316 unresolved.type = session.configuration.type; unresolved.noDebug = session.configuration.noDebug; needsToSubstitute = true; } } let resolved: IConfig | undefined | null = session.configuration; if (launch && needsToSubstitute && unresolved) { const initCancellationToken = new CancellationTokenSource(); this.sessionCancellationTokens.set(session.getId(), initCancellationToken); const resolvedByProviders = await this.configurationManager.resolveConfigurationByProviders(launch.workspace ? launch.workspace.uri : undefined, unresolved.type, unresolved, initCancellationToken.token); if (resolvedByProviders) { resolved = await this.substituteVariables(launch, resolvedByProviders); if (resolved && !initCancellationToken.token.isCancellationRequested) { resolved = await this.configurationManager.resolveDebugConfigurationWithSubstitutedVariables(launch && launch.workspace ? launch.workspace.uri : undefined, unresolved.type, resolved, initCancellationToken.token); } } else { resolved = resolvedByProviders; } } if (resolved) { session.setConfiguration({ resolved, unresolved }); } session.configuration.__restart = restartData; const doRestart = async (fn: () => Promise<boolean | undefined>) => { this.restartingSessions.add(session); let didRestart = false; try { didRestart = (await fn()) !== false; } catch (e) { didRestart = false; throw e; } finally { this.restartingSessions.delete(session); // we previously may have issued an onDidEndSession with restart: true, // assuming the adapter exited (in `registerSessionListeners`). But the // restart failed, so emit the final termination now. if (!didRestart) { this._onDidEndSession.fire({ session, restart: false }); } } }; if (session.capabilities.supportsRestartRequest) { const taskResult = await runTasks(); if (taskResult === TaskRunResult.Success) { await doRestart(async () => { await session.restart(); return true; }); } return; } const shouldFocus = !!this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId(); return doRestart(async () => { // If the restart is automatic -> disconnect, otherwise -> terminate #55064 if (isAutoRestart) { await session.disconnect(true); } else { await session.terminate(true); } return new Promise<boolean>((c, e) => { setTimeout(async () => { const taskResult = await runTasks(); if (taskResult !== TaskRunResult.Success) { return c(false); } if (!resolved) { return c(false); } try { await this.launchOrAttachToSession(session, shouldFocus); this._onDidNewSession.fire(session); c(true); } catch (error) { e(error); } }, 300); }); }); } async stopSession(session: IDebugSession | undefined, disconnect = false, suspend = false): Promise<any> { if (session) { return disconnect ? session.disconnect(undefined, suspend) : session.terminate(); } const sessions = this.model.getSessions(); if (sessions.length === 0) { this.taskRunner.cancel(); // User might have cancelled starting of a debug session, and in some cases the quick pick is left open await this.quickInputService.cancel(); this.endInitializingState(); this.cancelTokens(undefined); } return Promise.all(sessions.map(s => disconnect ? s.disconnect(undefined, suspend) : s.terminate())); } private async substituteVariables(launch: ILaunch | undefined, config: IConfig): Promise<IConfig | undefined> { const dbg = this.adapterManager.getDebugger(config.type); if (dbg) { let folder: IWorkspaceFolder | undefined = undefined; if (launch && launch.workspace) { folder = launch.workspace; } else { const folders = this.contextService.getWorkspace().folders; if (folders.length === 1) { folder = folders[0]; } } try { return await dbg.substituteVariables(folder, config); } catch (err) { this.showError(err.message, undefined, !!launch?.getConfiguration(config.name)); return undefined; // bail out } } return Promise.resolve(config); } private async showError(message: string, errorActions: ReadonlyArray<IAction> = [], promptLaunchJson = true): Promise<void> { const configureAction = new Action(DEBUG_CONFIGURE_COMMAND_ID, DEBUG_CONFIGURE_LABEL, undefined, true, () => this.commandService.executeCommand(DEBUG_CONFIGURE_COMMAND_ID)); // Don't append the standard command if id of any provided action indicates it is a command const actions = errorActions.filter((action) => action.id.endsWith('.command')).length > 0 ? errorActions : [...errorActions, ...(promptLaunchJson ? [configureAction] : [])]; await this.dialogService.prompt({ type: severity.Error, message, buttons: actions.map(action => ({ label: action.label, run: () => action.run() })), cancelButton: true }); } //---- focus management async focusStackFrame(_stackFrame: IStackFrame | undefined, _thread?: IThread, _session?: IDebugSession, options?: { explicit?: boolean; preserveFocus?: boolean; sideBySide?: boolean; pinned?: boolean }): Promise<void> { const { stackFrame, thread, session } = getStackFrameThreadAndSessionToFocus(this.model, _stackFrame, _thread, _session); if (stackFrame) { const editor = await stackFrame.openInEditor(this.editorService, options?.preserveFocus ?? true, options?.sideBySide, options?.pinned); if (editor) { if (editor.input === DisassemblyViewInput.instance) { // Go to address is invoked via setFocus } else { const control = editor.getControl(); if (stackFrame && isCodeEditor(control) && control.hasModel()) { const model = control.getModel(); const lineNumber = stackFrame.range.startLineNumber; if (lineNumber >= 1 && lineNumber <= model.getLineCount()) { const lineContent = control.getModel().getLineContent(lineNumber); aria.alert(nls.localize({ key: 'debuggingPaused', comment: ['First placeholder is the file line content, second placeholder is the reason why debugging is stopped, for example "breakpoint", third is the stack frame name, and last is the line number.'] }, "{0}, debugging paused {1}, {2}:{3}", lineContent, thread && thread.stoppedDetails ? `, reason ${thread.stoppedDetails.reason}` : '', stackFrame.source ? stackFrame.source.name : '', stackFrame.range.startLineNumber)); } } } } } if (session) { this.debugType.set(session.configuration.type); } else { this.debugType.reset(); } this.viewModel.setFocus(stackFrame, thread, session, !!options?.explicit); } //---- watches addWatchExpression(name?: string): void { const we = this.model.addWatchExpression(name); if (!name) { this.viewModel.setSelectedExpression(we, false); } this.debugStorage.storeWatchExpressions(this.model.getWatchExpressions()); } renameWatchExpression(id: string, newName: string): void { this.model.renameWatchExpression(id, newName); this.debugStorage.storeWatchExpressions(this.model.getWatchExpressions()); } moveWatchExpression(id: string, position: number): void { this.model.moveWatchExpression(id, position); this.debugStorage.storeWatchExpressions(this.model.getWatchExpressions()); } removeWatchExpressions(id?: string): void { this.model.removeWatchExpressions(id); this.debugStorage.storeWatchExpressions(this.model.getWatchExpressions()); } //---- breakpoints canSetBreakpointsIn(model: ITextModel): boolean { return this.adapterManager.canSetBreakpointsIn(model); } async enableOrDisableBreakpoints(enable: boolean, breakpoint?: IEnablement): Promise<void> { if (breakpoint) { this.model.setEnablement(breakpoint, enable); this.debugStorage.storeBreakpoints(this.model); if (breakpoint instanceof Breakpoint) { await this.sendBreakpoints(breakpoint.originalUri); } else if (breakpoint instanceof FunctionBreakpoint) { await this.sendFunctionBreakpoints(); } else if (breakpoint instanceof DataBreakpoint) { await this.sendDataBreakpoints(); } else if (breakpoint instanceof InstructionBreakpoint) { await this.sendInstructionBreakpoints(); } else { await this.sendExceptionBreakpoints(); } } else { this.model.enableOrDisableAllBreakpoints(enable); this.debugStorage.storeBreakpoints(this.model); await this.sendAllBreakpoints(); } this.debugStorage.storeBreakpoints(this.model); } async addBreakpoints(uri: uri, rawBreakpoints: IBreakpointData[], ariaAnnounce = true): Promise<IBreakpoint[]> { const breakpoints = this.model.addBreakpoints(uri, rawBreakpoints); if (ariaAnnounce) { breakpoints.forEach(bp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", bp.lineNumber, uri.fsPath))); } // In some cases we need to store breakpoints before we send them because sending them can take a long time // And after sending them because the debug adapter can attach adapter data to a breakpoint this.debugStorage.storeBreakpoints(this.model); await this.sendBreakpoints(uri); this.debugStorage.storeBreakpoints(this.model); return breakpoints; } async updateBreakpoints(uri: uri, data: Map<string, DebugProtocol.Breakpoint>, sendOnResourceSaved: boolean): Promise<void> { this.model.updateBreakpoints(data); this.debugStorage.storeBreakpoints(this.model); if (sendOnResourceSaved) { this.breakpointsToSendOnResourceSaved.add(uri); } else { await this.sendBreakpoints(uri); this.debugStorage.storeBreakpoints(this.model); } } async removeBreakpoints(id?: string): Promise<void> { const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id); // note: using the debugger-resolved uri for aria to reflect UI state toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath))); const urisToClear = distinct(toRemove, bp => bp.originalUri.toString()).map(bp => bp.originalUri); this.model.removeBreakpoints(toRemove); this.debugStorage.storeBreakpoints(this.model); await Promise.all(urisToClear.map(uri => this.sendBreakpoints(uri))); } setBreakpointsActivated(activated: boolean): Promise<void> { this.model.setBreakpointsActivated(activated); return this.sendAllBreakpoints(); } addFunctionBreakpoint(name?: string, id?: string): void { this.model.addFunctionBreakpoint(name || '', id); } async updateFunctionBreakpoint(id: string, update: { name?: string; hitCondition?: string; condition?: string }): Promise<void> { this.model.updateFunctionBreakpoint(id, update); this.debugStorage.storeBreakpoints(this.model); await this.sendFunctionBreakpoints(); } async removeFunctionBreakpoints(id?: string): Promise<void> { this.model.removeFunctionBreakpoints(id); this.debugStorage.storeBreakpoints(this.model); await this.sendFunctionBreakpoints(); } async addDataBreakpoint(label: string, dataId: string, canPersist: boolean, accessTypes: DebugProtocol.DataBreakpointAccessType[] | undefined, accessType: DebugProtocol.DataBreakpointAccessType): Promise<void> { this.model.addDataBreakpoint(label, dataId, canPersist, accessTypes, accessType); this.debugStorage.storeBreakpoints(this.model); await this.sendDataBreakpoints(); this.debugStorage.storeBreakpoints(this.model); } async updateDataBreakpoint(id: string, update: { hitCondition?: string; condition?: string }): Promise<void> { this.model.updateDataBreakpoint(id, update); this.debugStorage.storeBreakpoints(this.model); await this.sendDataBreakpoints(); } async removeDataBreakpoints(id?: string): Promise<void> { this.model.removeDataBreakpoints(id); this.debugStorage.storeBreakpoints(this.model); await this.sendDataBreakpoints(); } async addInstructionBreakpoint(instructionReference: string, offset: number, address: bigint, condition?: string, hitCondition?: string): Promise<void> { this.model.addInstructionBreakpoint(instructionReference, offset, address, condition, hitCondition); this.debugStorage.storeBreakpoints(this.model); await this.sendInstructionBreakpoints(); this.debugStorage.storeBreakpoints(this.model); } async removeInstructionBreakpoints(instructionReference?: string, offset?: number): Promise<void> { this.model.removeInstructionBreakpoints(instructionReference, offset); this.debugStorage.storeBreakpoints(this.model); await this.sendInstructionBreakpoints(); } setExceptionBreakpointFallbackSession(sessionId: string) { this.model.setExceptionBreakpointFallbackSession(sessionId); this.debugStorage.storeBreakpoints(this.model); } setExceptionBreakpointsForSession(session: IDebugSession, data: DebugProtocol.ExceptionBreakpointsFilter[]): void { this.model.setExceptionBreakpointsForSession(session.getId(), data); this.debugStorage.storeBreakpoints(this.model); } async setExceptionBreakpointCondition(exceptionBreakpoint: IExceptionBreakpoint, condition: string | undefined): Promise<void> { this.model.setExceptionBreakpointCondition(exceptionBreakpoint, condition); this.debugStorage.storeBreakpoints(this.model); await this.sendExceptionBreakpoints(); } async sendAllBreakpoints(session?: IDebugSession): Promise<any> { const setBreakpointsPromises = distinct(this.model.getBreakpoints(), bp => bp.originalUri.toString()) .map(bp => this.sendBreakpoints(bp.originalUri, false, session)); // If sending breakpoints to one session which we know supports the configurationDone request, can make all requests in parallel if (session?.capabilities.supportsConfigurationDoneRequest) { await Promise.all([ ...setBreakpointsPromises, this.sendFunctionBreakpoints(session), this.sendDataBreakpoints(session), this.sendInstructionBreakpoints(session), this.sendExceptionBreakpoints(session), ]); } else { await Promise.all(setBreakpointsPromises); await this.sendFunctionBreakpoints(session); await this.sendDataBreakpoints(session); await this.sendInstructionBreakpoints(session); // send exception breakpoints at the end since some debug adapters may rely on the order - this was the case before // the configurationDone request was introduced. await this.sendExceptionBreakpoints(session); } } private async sendBreakpoints(modelUri: uri, sourceModified = false, session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getBreakpoints({ originalUri: modelUri, enabledOnly: true }); await sendToOneOrAllSessions(this.model, session, async s => { if (!s.configuration.noDebug) { await s.sendBreakpoints(modelUri, breakpointsToSend, sourceModified); } }); } private async sendFunctionBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); await sendToOneOrAllSessions(this.model, session, async s => { if (s.capabilities.supportsFunctionBreakpoints && !s.configuration.noDebug) { await s.sendFunctionBreakpoints(breakpointsToSend); } }); } private async sendDataBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getDataBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); await sendToOneOrAllSessions(this.model, session, async s => { if (s.capabilities.supportsDataBreakpoints && !s.configuration.noDebug) { await s.sendDataBreakpoints(breakpointsToSend); } }); } private async sendInstructionBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getInstructionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); await sendToOneOrAllSessions(this.model, session, async s => { if (s.capabilities.supportsInstructionBreakpoints && !s.configuration.noDebug) { await s.sendInstructionBreakpoints(breakpointsToSend); } }); } private sendExceptionBreakpoints(session?: IDebugSession): Promise<void> { return sendToOneOrAllSessions(this.model, session, async s => { const enabledExceptionBps = this.model.getExceptionBreakpointsForSession(s.getId()).filter(exb => exb.enabled); if (s.capabilities.supportsConfigurationDoneRequest && (!s.capabilities.exceptionBreakpointFilters || s.capabilities.exceptionBreakpointFilters.length === 0)) { // Only call `setExceptionBreakpoints` as specified in dap protocol #90001 return; } if (!s.configuration.noDebug) { await s.sendExceptionBreakpoints(enabledExceptionBps); } }); } private onFileChanges(fileChangesEvent: FileChangesEvent): void { const toRemove = this.model.getBreakpoints().filter(bp => fileChangesEvent.contains(bp.originalUri, FileChangeType.DELETED)); if (toRemove.length) { this.model.removeBreakpoints(toRemove); } const toSend: URI[] = []; for (const uri of this.breakpointsToSendOnResourceSaved) { if (fileChangesEvent.contains(uri, FileChangeType.UPDATED)) { toSend.push(uri); } } for (const uri of toSend) { this.breakpointsToSendOnResourceSaved.delete(uri); this.sendBreakpoints(uri, true); } } async runTo(uri: uri, lineNumber: number, column?: number): Promise<void> { let breakpointToRemove: IBreakpoint | undefined; let threadToContinue = this.getViewModel().focusedThread; const addTempBreakPoint = async () => { const bpExists = !!(this.getModel().getBreakpoints({ column, lineNumber, uri }).length); if (!bpExists) { const addResult = await this.addAndValidateBreakpoints(uri, lineNumber, column); if (addResult.thread) { threadToContinue = addResult.thread; } if (addResult.breakpoint) { breakpointToRemove = addResult.breakpoint; } } return { threadToContinue, breakpointToRemove }; }; const removeTempBreakPoint = (state: State): boolean => { if (state === State.Stopped || state === State.Inactive) { if (breakpointToRemove) { this.removeBreakpoints(breakpointToRemove.getId()); } return true; } return false; }; await addTempBreakPoint(); if (this.state === State.Inactive) { // If no session exists start the debugger const { launch, name, getConfig } = this.getConfigurationManager().selectedConfiguration; const config = await getConfig(); const configOrName = config ? Object.assign(deepClone(config), {}) : name; const listener = this.onDidChangeState(state => { if (removeTempBreakPoint(state)) { listener.dispose(); } }); await this.startDebugging(launch, configOrName, undefined, true); } if (this.state === State.Stopped) { const focusedSession = this.getViewModel().focusedSession; if (!focusedSession || !threadToContinue) { return; } const listener = threadToContinue.session.onDidChangeState(() => { if (removeTempBreakPoint(focusedSession.state)) { listener.dispose(); } }); await threadToContinue.continue(); } } private async addAndValidateBreakpoints(uri: URI, lineNumber: number, column?: number) { const debugModel = this.getModel(); const viewModel = this.getViewModel(); const breakpoints = await this.addBreakpoints(uri, [{ lineNumber, column }], false); const breakpoint = breakpoints?.[0]; if (!breakpoint) { return { breakpoint: undefined, thread: viewModel.focusedThread }; } // If the breakpoint was not initially verified, wait up to 2s for it to become so. // Inherently racey if multiple sessions can verify async, but not solvable... if (!breakpoint.verified) { let listener: IDisposable; await raceTimeout(new Promise<void>(resolve => { listener = debugModel.onDidChangeBreakpoints(() => { if (breakpoint.verified) { resolve(); } }); }), 2000); listener!.dispose(); } // Look at paused threads for sessions that verified this bp. Prefer, in order: const enum Score { /** The focused thread */ Focused, /** Any other stopped thread of a session that verified the bp */ Verified, /** Any thread that verified and paused in the same file */ VerifiedAndPausedInFile, /** The focused thread if it verified the breakpoint */ VerifiedAndFocused, } let bestThread = viewModel.focusedThread; let bestScore = Score.Focused; for (const sessionId of breakpoint.sessionsThatVerified) { const session = debugModel.getSession(sessionId); if (!session) { continue; } const threads = session.getAllThreads().filter(t => t.stopped); if (bestScore < Score.VerifiedAndFocused) { if (viewModel.focusedThread && threads.includes(viewModel.focusedThread)) { bestThread = viewModel.focusedThread; bestScore = Score.VerifiedAndFocused; } } if (bestScore < Score.VerifiedAndPausedInFile) { const pausedInThisFile = threads.find(t => { const top = t.getTopStackFrame(); return top && this.uriIdentityService.extUri.isEqual(top.source.uri, uri); }); if (pausedInThisFile) { bestThread = pausedInThisFile; bestScore = Score.VerifiedAndPausedInFile; } } if (bestScore < Score.Verified) { bestThread = threads[0]; bestScore = Score.VerifiedAndPausedInFile; } } return { thread: bestThread, breakpoint }; } } export function getStackFrameThreadAndSessionToFocus(model: IDebugModel, stackFrame: IStackFrame | undefined, thread?: IThread, session?: IDebugSession, avoidSession?: IDebugSession): { stackFrame: IStackFrame | undefined; thread: IThread | undefined; session: IDebugSession | undefined } { if (!session) { if (stackFrame || thread) { session = stackFrame ? stackFrame.thread.session : thread!.session; } else { const sessions = model.getSessions(); const stoppedSession = sessions.find(s => s.state === State.Stopped); // Make sure to not focus session that is going down session = stoppedSession || sessions.find(s => s !== avoidSession && s !== avoidSession?.parentSession) || (sessions.length ? sessions[0] : undefined); } } if (!thread) { if (stackFrame) { thread = stackFrame.thread; } else { const threads = session ? session.getAllThreads() : undefined; const stoppedThread = threads && threads.find(t => t.stopped); thread = stoppedThread || (threads && threads.length ? threads[0] : undefined); } } if (!stackFrame && thread) { stackFrame = thread.getTopStackFrame(); } return { session, thread, stackFrame }; } async function sendToOneOrAllSessions(model: DebugModel, session: IDebugSession | undefined, send: (session: IDebugSession) => Promise<void>): Promise<void> { if (session) { await send(session); } else { await Promise.all(model.getSessions().map(s => send(s))); } }
src/vs/workbench/contrib/debug/browser/debugService.ts
1
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
[ 0.9981898665428162, 0.007429454941302538, 0.00016476964810863137, 0.00017039329395629466, 0.08434020727872849 ]
{ "id": 5, "code_window": [ "\textensionHostDebugAdapter: boolean;\n", "\tenableAllHovers: boolean;\n", "\tshowSubSessionsInToolBar: boolean;\n", "\tconsole: {\n", "\t\tfontSize: number;\n", "\t\tfontFamily: string;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tcloseReadonlyTabsOnEnd: boolean;\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debug.ts", "type": "add", "edit_start_line_idx": 688 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ICodeEditor, isCodeEditor, isDiffEditor, isCompositeEditor, getCodeEditor } from 'vs/editor/browser/editorBrowser'; import { AbstractCodeEditorService } from 'vs/editor/browser/services/abstractCodeEditorService'; import { ScrollType } from 'vs/editor/common/editorCommon'; import { IResourceEditorInput } from 'vs/platform/editor/common/editor'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { IWorkbenchEditorConfiguration } from 'vs/workbench/common/editor'; import { ACTIVE_GROUP, IEditorService, SIDE_GROUP } from 'vs/workbench/services/editor/common/editorService'; import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService'; import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { isEqual } from 'vs/base/common/resources'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { applyTextEditorOptions } from 'vs/workbench/common/editor/editorOptions'; export class CodeEditorService extends AbstractCodeEditorService { constructor( @IEditorService private readonly editorService: IEditorService, @IThemeService themeService: IThemeService, @IConfigurationService private readonly configurationService: IConfigurationService, ) { super(themeService); this._register(this.registerCodeEditorOpenHandler(this.doOpenCodeEditor.bind(this))); this._register(this.registerCodeEditorOpenHandler(this.doOpenCodeEditorFromDiff.bind(this))); } getActiveCodeEditor(): ICodeEditor | null { const activeTextEditorControl = this.editorService.activeTextEditorControl; if (isCodeEditor(activeTextEditorControl)) { return activeTextEditorControl; } if (isDiffEditor(activeTextEditorControl)) { return activeTextEditorControl.getModifiedEditor(); } const activeControl = this.editorService.activeEditorPane?.getControl(); if (isCompositeEditor(activeControl) && isCodeEditor(activeControl.activeCodeEditor)) { return activeControl.activeCodeEditor; } return null; } private async doOpenCodeEditorFromDiff(input: IResourceEditorInput, source: ICodeEditor | null, sideBySide?: boolean): Promise<ICodeEditor | null> { // Special case: If the active editor is a diff editor and the request to open originates and // targets the modified side of it, we just apply the request there to prevent opening the modified // side as separate editor. const activeTextEditorControl = this.editorService.activeTextEditorControl; if ( !sideBySide && // we need the current active group to be the target isDiffEditor(activeTextEditorControl) && // we only support this for active text diff editors input.options && // we need options to apply input.resource && // we need a request resource to compare with source === activeTextEditorControl.getModifiedEditor() && // we need the source of this request to be the modified side of the diff editor activeTextEditorControl.getModel() && // we need a target model to compare with isEqual(input.resource, activeTextEditorControl.getModel()?.modified.uri) // we need the input resources to match with modified side ) { const targetEditor = activeTextEditorControl.getModifiedEditor(); applyTextEditorOptions(input.options, targetEditor, ScrollType.Smooth); return targetEditor; } return null; } // Open using our normal editor service private async doOpenCodeEditor(input: IResourceEditorInput, source: ICodeEditor | null, sideBySide?: boolean): Promise<ICodeEditor | null> { // Special case: we want to detect the request to open an editor that // is different from the current one to decide whether the current editor // should be pinned or not. This ensures that the source of a navigation // is not being replaced by the target. An example is "Goto definition" // that otherwise would replace the editor everytime the user navigates. const enablePreviewFromCodeNavigation = this.configurationService.getValue<IWorkbenchEditorConfiguration>().workbench?.editor?.enablePreviewFromCodeNavigation; if ( !enablePreviewFromCodeNavigation && // we only need to do this if the configuration requires it source && // we need to know the origin of the navigation !input.options?.pinned && // we only need to look at preview editors that open !sideBySide && // we only need to care if editor opens in same group !isEqual(source.getModel()?.uri, input.resource) // we only need to do this if the editor is about to change ) { for (const visiblePane of this.editorService.visibleEditorPanes) { if (getCodeEditor(visiblePane.getControl()) === source) { visiblePane.group.pinEditor(); break; } } } // Open as editor const control = await this.editorService.openEditor(input, sideBySide ? SIDE_GROUP : ACTIVE_GROUP); if (control) { const widget = control.getControl(); if (isCodeEditor(widget)) { return widget; } if (isCompositeEditor(widget) && isCodeEditor(widget.activeCodeEditor)) { return widget.activeCodeEditor; } } return null; } } registerSingleton(ICodeEditorService, CodeEditorService, InstantiationType.Delayed);
src/vs/workbench/services/editor/browser/codeEditorService.ts
0
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
[ 0.00017618499987293035, 0.00017254853446502239, 0.00016882442287169397, 0.0001718565181363374, 0.0000021754717636213172 ]
{ "id": 5, "code_window": [ "\textensionHostDebugAdapter: boolean;\n", "\tenableAllHovers: boolean;\n", "\tshowSubSessionsInToolBar: boolean;\n", "\tconsole: {\n", "\t\tfontSize: number;\n", "\t\tfontFamily: string;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tcloseReadonlyTabsOnEnd: boolean;\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debug.ts", "type": "add", "edit_start_line_idx": 688 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as minimist from 'minimist'; import { isWindows } from 'vs/base/common/platform'; import { localize } from 'vs/nls'; import { NativeParsedArgs } from 'vs/platform/environment/common/argv'; /** * This code is also used by standalone cli's. Avoid adding any other dependencies. */ const helpCategories = { o: localize('optionsUpperCase', "Options"), e: localize('extensionsManagement', "Extensions Management"), t: localize('troubleshooting', "Troubleshooting") }; export interface Option<OptionType> { type: OptionType; alias?: string; deprecates?: string[]; // old deprecated ids args?: string | string[]; description?: string; deprecationMessage?: string; allowEmptyValue?: boolean; cat?: keyof typeof helpCategories; global?: boolean; } export interface Subcommand<T> { type: 'subcommand'; description?: string; deprecationMessage?: string; options: OptionDescriptions<Required<T>>; } export type OptionDescriptions<T> = { [P in keyof T]: T[P] extends boolean | undefined ? Option<'boolean'> : T[P] extends string | undefined ? Option<'string'> : T[P] extends string[] | undefined ? Option<'string[]'> : Subcommand<T[P]> }; export const NATIVE_CLI_COMMANDS = ['tunnel', 'serve-web'] as const; export const OPTIONS: OptionDescriptions<Required<NativeParsedArgs>> = { 'tunnel': { type: 'subcommand', description: 'Make the current machine accessible from vscode.dev or other machines through a secure tunnel', options: { 'cli-data-dir': { type: 'string', args: 'dir', description: localize('cliDataDir', "Directory where CLI metadata should be stored.") }, 'disable-telemetry': { type: 'boolean' }, 'telemetry-level': { type: 'string' }, user: { type: 'subcommand', options: { login: { type: 'subcommand', options: { provider: { type: 'string' }, 'access-token': { type: 'string' } } } } } } }, 'serve-web': { type: 'subcommand', description: 'Run a server that displays the editor UI in browsers.', options: { 'cli-data-dir': { type: 'string', args: 'dir', description: localize('cliDataDir', "Directory where CLI metadata should be stored.") }, 'disable-telemetry': { type: 'boolean' }, 'telemetry-level': { type: 'string' }, } }, 'diff': { type: 'boolean', cat: 'o', alias: 'd', args: ['file', 'file'], description: localize('diff', "Compare two files with each other.") }, 'merge': { type: 'boolean', cat: 'o', alias: 'm', args: ['path1', 'path2', 'base', 'result'], description: localize('merge', "Perform a three-way merge by providing paths for two modified versions of a file, the common origin of both modified versions and the output file to save merge results.") }, 'add': { type: 'boolean', cat: 'o', alias: 'a', args: 'folder', description: localize('add', "Add folder(s) to the last active window.") }, 'goto': { type: 'boolean', cat: 'o', alias: 'g', args: 'file:line[:character]', description: localize('goto', "Open a file at the path on the specified line and character position.") }, 'new-window': { type: 'boolean', cat: 'o', alias: 'n', description: localize('newWindow', "Force to open a new window.") }, 'reuse-window': { type: 'boolean', cat: 'o', alias: 'r', description: localize('reuseWindow', "Force to open a file or folder in an already opened window.") }, 'wait': { type: 'boolean', cat: 'o', alias: 'w', description: localize('wait', "Wait for the files to be closed before returning.") }, 'waitMarkerFilePath': { type: 'string' }, 'locale': { type: 'string', cat: 'o', args: 'locale', description: localize('locale', "The locale to use (e.g. en-US or zh-TW).") }, 'user-data-dir': { type: 'string', cat: 'o', args: 'dir', description: localize('userDataDir', "Specifies the directory that user data is kept in. Can be used to open multiple distinct instances of Code.") }, 'profile': { type: 'string', 'cat': 'o', args: 'profileName', description: localize('profileName', "Opens the provided folder or workspace with the given profile and associates the profile with the workspace. If the profile does not exist, a new empty one is created.") }, 'help': { type: 'boolean', cat: 'o', alias: 'h', description: localize('help', "Print usage.") }, 'extensions-dir': { type: 'string', deprecates: ['extensionHomePath'], cat: 'e', args: 'dir', description: localize('extensionHomePath', "Set the root path for extensions.") }, 'extensions-download-dir': { type: 'string' }, 'builtin-extensions-dir': { type: 'string' }, 'list-extensions': { type: 'boolean', cat: 'e', description: localize('listExtensions', "List the installed extensions.") }, 'show-versions': { type: 'boolean', cat: 'e', description: localize('showVersions', "Show versions of installed extensions, when using --list-extensions.") }, 'category': { type: 'string', allowEmptyValue: true, cat: 'e', description: localize('category', "Filters installed extensions by provided category, when using --list-extensions."), args: 'category' }, 'install-extension': { type: 'string[]', cat: 'e', args: 'ext-id | path', description: localize('installExtension', "Installs or updates an extension. The argument is either an extension id or a path to a VSIX. The identifier of an extension is '${publisher}.${name}'. Use '--force' argument to update to latest version. To install a specific version provide '@${version}'. For example: '[email protected]'.") }, 'pre-release': { type: 'boolean', cat: 'e', description: localize('install prerelease', "Installs the pre-release version of the extension, when using --install-extension") }, 'uninstall-extension': { type: 'string[]', cat: 'e', args: 'ext-id', description: localize('uninstallExtension', "Uninstalls an extension.") }, 'enable-proposed-api': { type: 'string[]', allowEmptyValue: true, cat: 'e', args: 'ext-id', description: localize('experimentalApis', "Enables proposed API features for extensions. Can receive one or more extension IDs to enable individually.") }, 'version': { type: 'boolean', cat: 't', alias: 'v', description: localize('version', "Print version.") }, 'verbose': { type: 'boolean', cat: 't', global: true, description: localize('verbose', "Print verbose output (implies --wait).") }, 'log': { type: 'string[]', cat: 't', args: 'level', global: true, description: localize('log', "Log level to use. Default is 'info'. Allowed values are 'critical', 'error', 'warn', 'info', 'debug', 'trace', 'off'. You can also configure the log level of an extension by passing extension id and log level in the following format: '${publisher}.${name}:${logLevel}'. For example: 'vscode.csharp:trace'. Can receive one or more such entries.") }, 'status': { type: 'boolean', alias: 's', cat: 't', description: localize('status', "Print process usage and diagnostics information.") }, 'prof-startup': { type: 'boolean', cat: 't', description: localize('prof-startup', "Run CPU profiler during startup.") }, 'prof-append-timers': { type: 'string' }, 'prof-duration-markers': { type: 'string[]' }, 'prof-duration-markers-file': { type: 'string' }, 'no-cached-data': { type: 'boolean' }, 'prof-startup-prefix': { type: 'string' }, 'prof-v8-extensions': { type: 'boolean' }, 'disable-extensions': { type: 'boolean', deprecates: ['disableExtensions'], cat: 't', description: localize('disableExtensions', "Disable all installed extensions. This option is not persisted and is effective only when the command opens a new window.") }, 'disable-extension': { type: 'string[]', cat: 't', args: 'ext-id', description: localize('disableExtension', "Disable the provided extension. This option is not persisted and is effective only when the command opens a new window.") }, 'sync': { type: 'string', cat: 't', description: localize('turn sync', "Turn sync on or off."), args: ['on | off'] }, 'inspect-extensions': { type: 'string', allowEmptyValue: true, deprecates: ['debugPluginHost'], args: 'port', cat: 't', description: localize('inspect-extensions', "Allow debugging and profiling of extensions. Check the developer tools for the connection URI.") }, 'inspect-brk-extensions': { type: 'string', allowEmptyValue: true, deprecates: ['debugBrkPluginHost'], args: 'port', cat: 't', description: localize('inspect-brk-extensions', "Allow debugging and profiling of extensions with the extension host being paused after start. Check the developer tools for the connection URI.") }, 'disable-gpu': { type: 'boolean', cat: 't', description: localize('disableGPU', "Disable GPU hardware acceleration.") }, 'disable-chromium-sandbox': { type: 'boolean', cat: 't', description: localize('disableChromiumSandbox', "Use this option only when there is requirement to launch the application as sudo user on Linux or when running as an elevated user in an applocker environment on Windows.") }, 'sandbox': { type: 'boolean' }, 'ms-enable-electron-run-as-node': { type: 'boolean', global: true }, 'telemetry': { type: 'boolean', cat: 't', description: localize('telemetry', "Shows all telemetry events which VS code collects.") }, 'remote': { type: 'string', allowEmptyValue: true }, 'folder-uri': { type: 'string[]', cat: 'o', args: 'uri' }, 'file-uri': { type: 'string[]', cat: 'o', args: 'uri' }, 'locate-extension': { type: 'string[]' }, 'extensionDevelopmentPath': { type: 'string[]' }, 'extensionDevelopmentKind': { type: 'string[]' }, 'extensionTestsPath': { type: 'string' }, 'extensionEnvironment': { type: 'string' }, 'debugId': { type: 'string' }, 'debugRenderer': { type: 'boolean' }, 'inspect-ptyhost': { type: 'string', allowEmptyValue: true }, 'inspect-brk-ptyhost': { type: 'string', allowEmptyValue: true }, 'inspect-search': { type: 'string', deprecates: ['debugSearch'], allowEmptyValue: true }, 'inspect-brk-search': { type: 'string', deprecates: ['debugBrkSearch'], allowEmptyValue: true }, 'inspect-sharedprocess': { type: 'string', allowEmptyValue: true }, 'inspect-brk-sharedprocess': { type: 'string', allowEmptyValue: true }, 'export-default-configuration': { type: 'string' }, 'install-source': { type: 'string' }, 'enable-smoke-test-driver': { type: 'boolean' }, 'logExtensionHostCommunication': { type: 'boolean' }, 'skip-release-notes': { type: 'boolean' }, 'skip-welcome': { type: 'boolean' }, 'disable-telemetry': { type: 'boolean' }, 'disable-updates': { type: 'boolean' }, 'use-inmemory-secretstorage': { type: 'boolean', deprecates: ['disable-keytar'] }, 'password-store': { type: 'string' }, 'disable-workspace-trust': { type: 'boolean' }, 'disable-crash-reporter': { type: 'boolean' }, 'crash-reporter-directory': { type: 'string' }, 'crash-reporter-id': { type: 'string' }, 'skip-add-to-recently-opened': { type: 'boolean' }, 'unity-launch': { type: 'boolean' }, 'open-url': { type: 'boolean' }, 'file-write': { type: 'boolean' }, 'file-chmod': { type: 'boolean' }, 'install-builtin-extension': { type: 'string[]' }, 'force': { type: 'boolean' }, 'do-not-sync': { type: 'boolean' }, 'trace': { type: 'boolean' }, 'trace-category-filter': { type: 'string' }, 'trace-options': { type: 'string' }, 'force-user-env': { type: 'boolean' }, 'force-disable-user-env': { type: 'boolean' }, 'open-devtools': { type: 'boolean' }, 'disable-gpu-sandbox': { type: 'boolean' }, 'logsPath': { type: 'string' }, '__enable-file-policy': { type: 'boolean' }, 'editSessionId': { type: 'string' }, 'continueOn': { type: 'string' }, 'locate-shell-integration-path': { type: 'string', args: ['bash', 'pwsh', 'zsh', 'fish'] }, 'enable-coi': { type: 'boolean' }, // chromium flags 'no-proxy-server': { type: 'boolean' }, // Minimist incorrectly parses keys that start with `--no` // https://github.com/substack/minimist/blob/aeb3e27dae0412de5c0494e9563a5f10c82cc7a9/index.js#L118-L121 // If --no-sandbox is passed via cli wrapper it will be treated as --sandbox which is incorrect, we use // the alias here to make sure --no-sandbox is always respected. // For https://github.com/microsoft/vscode/issues/128279 'no-sandbox': { type: 'boolean', alias: 'sandbox' }, 'proxy-server': { type: 'string' }, 'proxy-bypass-list': { type: 'string' }, 'proxy-pac-url': { type: 'string' }, 'js-flags': { type: 'string' }, // chrome js flags 'inspect': { type: 'string', allowEmptyValue: true }, 'inspect-brk': { type: 'string', allowEmptyValue: true }, 'nolazy': { type: 'boolean' }, // node inspect 'force-device-scale-factor': { type: 'string' }, 'force-renderer-accessibility': { type: 'boolean' }, 'ignore-certificate-errors': { type: 'boolean' }, 'allow-insecure-localhost': { type: 'boolean' }, 'log-net-log': { type: 'string' }, 'vmodule': { type: 'string' }, '_urls': { type: 'string[]' }, 'disable-dev-shm-usage': { type: 'boolean' }, 'profile-temp': { type: 'boolean' }, _: { type: 'string[]' } // main arguments }; export interface ErrorReporter { onUnknownOption(id: string): void; onMultipleValues(id: string, usedValue: string): void; onEmptyValue(id: string): void; onDeprecatedOption(deprecatedId: string, message: string): void; getSubcommandReporter?(commmand: string): ErrorReporter; } const ignoringReporter = { onUnknownOption: () => { }, onMultipleValues: () => { }, onEmptyValue: () => { }, onDeprecatedOption: () => { } }; export function parseArgs<T>(args: string[], options: OptionDescriptions<T>, errorReporter: ErrorReporter = ignoringReporter): T { const firstArg = args.find(a => a.length > 0 && a[0] !== '-'); const alias: { [key: string]: string } = {}; const stringOptions: string[] = ['_']; const booleanOptions: string[] = []; const globalOptions: OptionDescriptions<any> = {}; let command: Subcommand<any> | undefined = undefined; for (const optionId in options) { const o = options[optionId]; if (o.type === 'subcommand') { if (optionId === firstArg) { command = o; } } else { if (o.alias) { alias[optionId] = o.alias; } if (o.type === 'string' || o.type === 'string[]') { stringOptions.push(optionId); if (o.deprecates) { stringOptions.push(...o.deprecates); } } else if (o.type === 'boolean') { booleanOptions.push(optionId); if (o.deprecates) { booleanOptions.push(...o.deprecates); } } if (o.global) { globalOptions[optionId] = o; } } } if (command && firstArg) { const options = globalOptions; for (const optionId in command.options) { options[optionId] = command.options[optionId]; } const newArgs = args.filter(a => a !== firstArg); const reporter = errorReporter.getSubcommandReporter ? errorReporter.getSubcommandReporter(firstArg) : undefined; const subcommandOptions = parseArgs(newArgs, options, reporter); return <T>{ [firstArg]: subcommandOptions, _: [] }; } // remove aliases to avoid confusion const parsedArgs = minimist(args, { string: stringOptions, boolean: booleanOptions, alias }); const cleanedArgs: any = {}; const remainingArgs: any = parsedArgs; // https://github.com/microsoft/vscode/issues/58177, https://github.com/microsoft/vscode/issues/106617 cleanedArgs._ = parsedArgs._.map(arg => String(arg)).filter(arg => arg.length > 0); delete remainingArgs._; for (const optionId in options) { const o = options[optionId]; if (o.type === 'subcommand') { continue; } if (o.alias) { delete remainingArgs[o.alias]; } let val = remainingArgs[optionId]; if (o.deprecates) { for (const deprecatedId of o.deprecates) { if (remainingArgs.hasOwnProperty(deprecatedId)) { if (!val) { val = remainingArgs[deprecatedId]; if (val) { errorReporter.onDeprecatedOption(deprecatedId, o.deprecationMessage || localize('deprecated.useInstead', 'Use {0} instead.', optionId)); } } delete remainingArgs[deprecatedId]; } } } if (typeof val !== 'undefined') { if (o.type === 'string[]') { if (!Array.isArray(val)) { val = [val]; } if (!o.allowEmptyValue) { const sanitized = val.filter((v: string) => v.length > 0); if (sanitized.length !== val.length) { errorReporter.onEmptyValue(optionId); val = sanitized.length > 0 ? sanitized : undefined; } } } else if (o.type === 'string') { if (Array.isArray(val)) { val = val.pop(); // take the last errorReporter.onMultipleValues(optionId, val); } else if (!val && !o.allowEmptyValue) { errorReporter.onEmptyValue(optionId); val = undefined; } } cleanedArgs[optionId] = val; if (o.deprecationMessage) { errorReporter.onDeprecatedOption(optionId, o.deprecationMessage); } } delete remainingArgs[optionId]; } for (const key in remainingArgs) { errorReporter.onUnknownOption(key); } return cleanedArgs; } function formatUsage(optionId: string, option: Option<any>) { let args = ''; if (option.args) { if (Array.isArray(option.args)) { args = ` <${option.args.join('> <')}>`; } else { args = ` <${option.args}>`; } } if (option.alias) { return `-${option.alias} --${optionId}${args}`; } return `--${optionId}${args}`; } // exported only for testing export function formatOptions(options: OptionDescriptions<any>, columns: number): string[] { const usageTexts: [string, string][] = []; for (const optionId in options) { const o = options[optionId]; const usageText = formatUsage(optionId, o); usageTexts.push([usageText, o.description!]); } return formatUsageTexts(usageTexts, columns); } function formatUsageTexts(usageTexts: [string, string][], columns: number) { const maxLength = usageTexts.reduce((previous, e) => Math.max(previous, e[0].length), 12); const argLength = maxLength + 2/*left padding*/ + 1/*right padding*/; if (columns - argLength < 25) { // Use a condensed version on narrow terminals return usageTexts.reduce<string[]>((r, ut) => r.concat([` ${ut[0]}`, ` ${ut[1]}`]), []); } const descriptionColumns = columns - argLength - 1; const result: string[] = []; for (const ut of usageTexts) { const usage = ut[0]; const wrappedDescription = wrapText(ut[1], descriptionColumns); const keyPadding = indent(argLength - usage.length - 2/*left padding*/); result.push(' ' + usage + keyPadding + wrappedDescription[0]); for (let i = 1; i < wrappedDescription.length; i++) { result.push(indent(argLength) + wrappedDescription[i]); } } return result; } function indent(count: number): string { return ' '.repeat(count); } function wrapText(text: string, columns: number): string[] { const lines: string[] = []; while (text.length) { const index = text.length < columns ? text.length : text.lastIndexOf(' ', columns); const line = text.slice(0, index).trim(); text = text.slice(index); lines.push(line); } return lines; } export function buildHelpMessage(productName: string, executableName: string, version: string, options: OptionDescriptions<any>, capabilities?: { noPipe?: boolean; noInputFiles: boolean }): string { const columns = (process.stdout).isTTY && (process.stdout).columns || 80; const inputFiles = capabilities?.noInputFiles !== true ? `[${localize('paths', 'paths')}...]` : ''; const help = [`${productName} ${version}`]; help.push(''); help.push(`${localize('usage', "Usage")}: ${executableName} [${localize('options', "options")}]${inputFiles}`); help.push(''); if (capabilities?.noPipe !== true) { if (isWindows) { help.push(localize('stdinWindows', "To read output from another program, append '-' (e.g. 'echo Hello World | {0} -')", executableName)); } else { help.push(localize('stdinUnix', "To read from stdin, append '-' (e.g. 'ps aux | grep code | {0} -')", executableName)); } help.push(''); } const optionsByCategory: { [P in keyof typeof helpCategories]?: OptionDescriptions<any> } = {}; const subcommands: { command: string; description: string }[] = []; for (const optionId in options) { const o = options[optionId]; if (o.type === 'subcommand') { if (o.description) { subcommands.push({ command: optionId, description: o.description }); } } else if (o.description && o.cat) { let optionsByCat = optionsByCategory[o.cat]; if (!optionsByCat) { optionsByCategory[o.cat] = optionsByCat = {}; } optionsByCat[optionId] = o; } } for (const helpCategoryKey in optionsByCategory) { const key = <keyof typeof helpCategories>helpCategoryKey; const categoryOptions = optionsByCategory[key]; if (categoryOptions) { help.push(helpCategories[key]); help.push(...formatOptions(categoryOptions, columns)); help.push(''); } } if (subcommands.length) { help.push(localize('subcommands', "Subcommands")); help.push(...formatUsageTexts(subcommands.map(s => [s.command, s.description]), columns)); help.push(''); } return help.join('\n'); } export function buildVersionMessage(version: string | undefined, commit: string | undefined): string { return `${version || localize('unknownVersion', "Unknown version")}\n${commit || localize('unknownCommit', "Unknown commit")}\n${process.arch}`; }
src/vs/platform/environment/node/argv.ts
0
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
[ 0.00030975969275459647, 0.00017525217845104635, 0.00016442830383311957, 0.00017033562471624464, 0.00002322936779819429 ]
{ "id": 5, "code_window": [ "\textensionHostDebugAdapter: boolean;\n", "\tenableAllHovers: boolean;\n", "\tshowSubSessionsInToolBar: boolean;\n", "\tconsole: {\n", "\t\tfontSize: number;\n", "\t\tfontFamily: string;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tcloseReadonlyTabsOnEnd: boolean;\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debug.ts", "type": "add", "edit_start_line_idx": 688 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import { deepClone } from 'vs/base/common/objects'; import { isObject, assertIsDefined } from 'vs/base/common/types'; import { ICodeEditor, IDiffEditor } from 'vs/editor/browser/editorBrowser'; import { IDiffEditorOptions, IEditorOptions as ICodeEditorOptions } from 'vs/editor/common/config/editorOptions'; import { AbstractTextEditor, IEditorConfiguration } from 'vs/workbench/browser/parts/editor/textEditor'; import { TEXT_DIFF_EDITOR_ID, IEditorFactoryRegistry, EditorExtensions, ITextDiffEditorPane, IEditorOpenContext, isEditorInput, isTextEditorViewState, createTooLargeFileError } from 'vs/workbench/common/editor'; import { EditorInput } from 'vs/workbench/common/editor/editorInput'; import { applyTextEditorOptions } from 'vs/workbench/common/editor/editorOptions'; import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput'; import { TextDiffEditorModel } from 'vs/workbench/common/editor/textDiffEditorModel'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { ITextResourceConfigurationChangeEvent, ITextResourceConfigurationService } from 'vs/editor/common/services/textResourceConfiguration'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { TextFileOperationError, TextFileOperationResult } from 'vs/workbench/services/textfile/common/textfiles'; import { ScrollType, IDiffEditorViewState, IDiffEditorModel, IDiffEditorViewModel } from 'vs/editor/common/editorCommon'; import { Registry } from 'vs/platform/registry/common/platform'; import { URI } from 'vs/base/common/uri'; import { IEditorGroup, IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { CancellationToken } from 'vs/base/common/cancellation'; import { EditorActivation, ITextEditorOptions } from 'vs/platform/editor/common/editor'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { isEqual } from 'vs/base/common/resources'; import { Dimension, multibyteAwareBtoa } from 'vs/base/browser/dom'; import { ByteSize, FileOperationError, FileOperationResult, IFileService, TooLargeFileOperationError } from 'vs/platform/files/common/files'; import { IBoundarySashes } from 'vs/base/browser/ui/sash/sash'; import { IPreferencesService } from 'vs/workbench/services/preferences/common/preferences'; import { StopWatch } from 'vs/base/common/stopwatch'; import { DiffEditorWidget } from 'vs/editor/browser/widget/diffEditor/diffEditorWidget'; /** * The text editor that leverages the diff text editor for the editing experience. */ export class TextDiffEditor extends AbstractTextEditor<IDiffEditorViewState> implements ITextDiffEditorPane { static readonly ID = TEXT_DIFF_EDITOR_ID; private diffEditorControl: IDiffEditor | undefined = undefined; private inputLifecycleStopWatch: StopWatch | undefined = undefined; override get scopedContextKeyService(): IContextKeyService | undefined { if (!this.diffEditorControl) { return undefined; } const originalEditor = this.diffEditorControl.getOriginalEditor(); const modifiedEditor = this.diffEditorControl.getModifiedEditor(); return (originalEditor.hasTextFocus() ? originalEditor : modifiedEditor).invokeWithinContext(accessor => accessor.get(IContextKeyService)); } constructor( @ITelemetryService telemetryService: ITelemetryService, @IInstantiationService instantiationService: IInstantiationService, @IStorageService storageService: IStorageService, @ITextResourceConfigurationService configurationService: ITextResourceConfigurationService, @IEditorService editorService: IEditorService, @IThemeService themeService: IThemeService, @IEditorGroupsService editorGroupService: IEditorGroupsService, @IFileService fileService: IFileService, @IPreferencesService private readonly preferencesService: IPreferencesService ) { super(TextDiffEditor.ID, telemetryService, instantiationService, storageService, configurationService, themeService, editorService, editorGroupService, fileService); } override getTitle(): string { if (this.input) { return this.input.getName(); } return localize('textDiffEditor', "Text Diff Editor"); } protected override createEditorControl(parent: HTMLElement, configuration: ICodeEditorOptions): void { this.diffEditorControl = this._register(this.instantiationService.createInstance(DiffEditorWidget, parent, configuration, {})); } protected updateEditorControlOptions(options: ICodeEditorOptions): void { this.diffEditorControl?.updateOptions(options); } protected getMainControl(): ICodeEditor | undefined { return this.diffEditorControl?.getModifiedEditor(); } private _previousViewModel: IDiffEditorViewModel | null = null; override async setInput(input: DiffEditorInput, options: ITextEditorOptions | undefined, context: IEditorOpenContext, token: CancellationToken): Promise<void> { if (this._previousViewModel) { this._previousViewModel.dispose(); this._previousViewModel = null; } // Cleanup previous things associated with the input this.inputLifecycleStopWatch = undefined; // Set input and resolve await super.setInput(input, options, context, token); try { const resolvedModel = await input.resolve(options); // Check for cancellation if (token.isCancellationRequested) { return undefined; } // Fallback to open as binary if not text if (!(resolvedModel instanceof TextDiffEditorModel)) { this.openAsBinary(input, options); return undefined; } // Set Editor Model const control = assertIsDefined(this.diffEditorControl); const resolvedDiffEditorModel = resolvedModel as TextDiffEditorModel; const vm = resolvedDiffEditorModel.textDiffEditorModel ? control.createViewModel(resolvedDiffEditorModel.textDiffEditorModel) : null; this._previousViewModel = vm; await vm?.waitForDiff(); control.setModel(vm); // Restore view state (unless provided by options) let hasPreviousViewState = false; if (!isTextEditorViewState(options?.viewState)) { hasPreviousViewState = this.restoreTextDiffEditorViewState(input, options, context, control); } // Apply options to editor if any let optionsGotApplied = false; if (options) { optionsGotApplied = applyTextEditorOptions(options, control, ScrollType.Immediate); } if (!optionsGotApplied && !hasPreviousViewState) { control.revealFirstDiff(); } // Since the resolved model provides information about being readonly // or not, we apply it here to the editor even though the editor input // was already asked for being readonly or not. The rationale is that // a resolved model might have more specific information about being // readonly or not that the input did not have. control.updateOptions({ ...this.getReadonlyConfiguration(resolvedDiffEditorModel.modifiedModel?.isReadonly()), originalEditable: !resolvedDiffEditorModel.originalModel?.isReadonly() }); control.handleInitialized(); // Start to measure input lifecycle this.inputLifecycleStopWatch = new StopWatch(false); } catch (error) { await this.handleSetInputError(error, input, options); } } private async handleSetInputError(error: Error, input: DiffEditorInput, options: ITextEditorOptions | undefined): Promise<void> { // Handle case where content appears to be binary if (this.isFileBinaryError(error)) { return this.openAsBinary(input, options); } // Handle case where a file is too large to open without confirmation if ((<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_TOO_LARGE && this.group) { let message: string; if (error instanceof TooLargeFileOperationError) { message = localize('fileTooLargeForHeapErrorWithSize', "At least one file is not displayed in the text compare editor because it is very large ({0}).", ByteSize.formatSize(error.size)); } else { message = localize('fileTooLargeForHeapErrorWithoutSize', "At least one file is not displayed in the text compare editor because it is very large."); } throw createTooLargeFileError(this.group, input, options, message, this.preferencesService); } // Otherwise make sure the error bubbles up throw error; } private restoreTextDiffEditorViewState(editor: DiffEditorInput, options: ITextEditorOptions | undefined, context: IEditorOpenContext, control: IDiffEditor): boolean { const editorViewState = this.loadEditorViewState(editor, context); if (editorViewState) { if (options?.selection && editorViewState.modified) { editorViewState.modified.cursorState = []; // prevent duplicate selections via options } control.restoreViewState(editorViewState); return true; } return false; } private openAsBinary(input: DiffEditorInput, options: ITextEditorOptions | undefined): void { const original = input.original; const modified = input.modified; const binaryDiffInput = this.instantiationService.createInstance(DiffEditorInput, input.getName(), input.getDescription(), original, modified, true); // Forward binary flag to input if supported const fileEditorFactory = Registry.as<IEditorFactoryRegistry>(EditorExtensions.EditorFactory).getFileEditorFactory(); if (fileEditorFactory.isFileEditor(original)) { original.setForceOpenAsBinary(); } if (fileEditorFactory.isFileEditor(modified)) { modified.setForceOpenAsBinary(); } // Replace this editor with the binary one (this.group ?? this.editorGroupService.activeGroup).replaceEditors([{ editor: input, replacement: binaryDiffInput, options: { ...options, // Make sure to not steal away the currently active group // because we are triggering another openEditor() call // and do not control the initial intent that resulted // in us now opening as binary. activation: EditorActivation.PRESERVE, pinned: this.group?.isPinned(input), sticky: this.group?.isSticky(input) } }]); } override setOptions(options: ITextEditorOptions | undefined): void { super.setOptions(options); if (options) { applyTextEditorOptions(options, assertIsDefined(this.diffEditorControl), ScrollType.Smooth); } } protected override shouldHandleConfigurationChangeEvent(e: ITextResourceConfigurationChangeEvent, resource: URI): boolean { if (super.shouldHandleConfigurationChangeEvent(e, resource)) { return true; } return e.affectsConfiguration(resource, 'diffEditor') || e.affectsConfiguration(resource, 'accessibility.verbosity.diffEditor'); } protected override computeConfiguration(configuration: IEditorConfiguration): ICodeEditorOptions { const editorConfiguration = super.computeConfiguration(configuration); // Handle diff editor specially by merging in diffEditor configuration if (isObject(configuration.diffEditor)) { const diffEditorConfiguration: IDiffEditorOptions = deepClone(configuration.diffEditor); // User settings defines `diffEditor.codeLens`, but here we rename that to `diffEditor.diffCodeLens` to avoid collisions with `editor.codeLens`. diffEditorConfiguration.diffCodeLens = diffEditorConfiguration.codeLens; delete diffEditorConfiguration.codeLens; // User settings defines `diffEditor.wordWrap`, but here we rename that to `diffEditor.diffWordWrap` to avoid collisions with `editor.wordWrap`. diffEditorConfiguration.diffWordWrap = <'off' | 'on' | 'inherit' | undefined>diffEditorConfiguration.wordWrap; delete diffEditorConfiguration.wordWrap; Object.assign(editorConfiguration, diffEditorConfiguration); } const verbose = configuration.accessibility?.verbosity?.diffEditor ?? false; (editorConfiguration as IDiffEditorOptions).accessibilityVerbose = verbose; return editorConfiguration; } protected override getConfigurationOverrides(configuration: IEditorConfiguration): IDiffEditorOptions { return { ...super.getConfigurationOverrides(configuration), ...this.getReadonlyConfiguration(this.input?.isReadonly()), originalEditable: this.input instanceof DiffEditorInput && !this.input.original.isReadonly(), lineDecorationsWidth: '2ch' }; } protected override updateReadonly(input: EditorInput): void { if (input instanceof DiffEditorInput) { this.diffEditorControl?.updateOptions({ ...this.getReadonlyConfiguration(input.isReadonly()), originalEditable: !input.original.isReadonly(), }); } else { super.updateReadonly(input); } } private isFileBinaryError(error: Error[]): boolean; private isFileBinaryError(error: Error): boolean; private isFileBinaryError(error: Error | Error[]): boolean { if (Array.isArray(error)) { const errors = <Error[]>error; return errors.some(error => this.isFileBinaryError(error)); } return (<TextFileOperationError>error).textFileOperationResult === TextFileOperationResult.FILE_IS_BINARY; } override clearInput(): void { if (this._previousViewModel) { this._previousViewModel.dispose(); this._previousViewModel = null; } super.clearInput(); // Log input lifecycle telemetry const inputLifecycleElapsed = this.inputLifecycleStopWatch?.elapsed(); this.inputLifecycleStopWatch = undefined; if (typeof inputLifecycleElapsed === 'number') { this.logInputLifecycleTelemetry(inputLifecycleElapsed, this.getControl()?.getModel()?.modified?.getLanguageId()); } // Clear Model this.diffEditorControl?.setModel(null); } private logInputLifecycleTelemetry(duration: number, languageId: string | undefined): void { let collapseUnchangedRegions = false; if (this.diffEditorControl instanceof DiffEditorWidget) { collapseUnchangedRegions = this.diffEditorControl.collapseUnchangedRegions; } this.telemetryService.publicLog2<{ editorVisibleTimeMs: number; languageId: string; collapseUnchangedRegions: boolean; }, { owner: 'hediet'; editorVisibleTimeMs: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Indicates the time the diff editor was visible to the user' }; languageId: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Indicates for which language the diff editor was shown' }; collapseUnchangedRegions: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Indicates whether unchanged regions were collapsed' }; comment: 'This event gives insight about how long the diff editor was visible to the user.'; }>('diffEditor.editorVisibleTime', { editorVisibleTimeMs: duration, languageId: languageId ?? '', collapseUnchangedRegions, }); } override getControl(): IDiffEditor | undefined { return this.diffEditorControl; } override focus(): void { super.focus(); this.diffEditorControl?.focus(); } override hasFocus(): boolean { return this.diffEditorControl?.hasTextFocus() || super.hasFocus(); } protected override setEditorVisible(visible: boolean, group: IEditorGroup | undefined): void { super.setEditorVisible(visible, group); if (visible) { this.diffEditorControl?.onVisible(); } else { this.diffEditorControl?.onHide(); } } override layout(dimension: Dimension): void { this.diffEditorControl?.layout(dimension); } override setBoundarySashes(sashes: IBoundarySashes) { this.diffEditorControl?.setBoundarySashes(sashes); } protected override tracksEditorViewState(input: EditorInput): boolean { return input instanceof DiffEditorInput; } protected override computeEditorViewState(resource: URI): IDiffEditorViewState | undefined { if (!this.diffEditorControl) { return undefined; } const model = this.diffEditorControl.getModel(); if (!model || !model.modified || !model.original) { return undefined; // view state always needs a model } const modelUri = this.toEditorViewStateResource(model); if (!modelUri) { return undefined; // model URI is needed to make sure we save the view state correctly } if (!isEqual(modelUri, resource)) { return undefined; // prevent saving view state for a model that is not the expected one } return this.diffEditorControl.saveViewState() ?? undefined; } protected override toEditorViewStateResource(modelOrInput: IDiffEditorModel | EditorInput): URI | undefined { let original: URI | undefined; let modified: URI | undefined; if (modelOrInput instanceof DiffEditorInput) { original = modelOrInput.original.resource; modified = modelOrInput.modified.resource; } else if (!isEditorInput(modelOrInput)) { original = modelOrInput.original.uri; modified = modelOrInput.modified.uri; } if (!original || !modified) { return undefined; } // create a URI that is the Base64 concatenation of original + modified resource return URI.from({ scheme: 'diff', path: `${multibyteAwareBtoa(original.toString())}${multibyteAwareBtoa(modified.toString())}` }); } }
src/vs/workbench/browser/parts/editor/textDiffEditor.ts
0
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
[ 0.04014616087079048, 0.001100977067835629, 0.00016208442684728652, 0.000171024032169953, 0.006024803966283798 ]
{ "id": 0, "code_window": [ " size: { control: { type: 'select', options: ButtonSizes } },\n", " },\n", "};\n", "\n", "export const ButtonWithProps = (args: any) => ({\n", " components: { Button },\n", " template: '<Button :size=\"size\">Button text</Button>',\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "export const ButtonWithProps = (args: any, { argTypes }: any) => ({\n" ], "file_path": "examples/vue-cli/src/button/Button.stories.ts", "type": "replace", "edit_start_line_idx": 11 }
import MyButton from '../Button.vue'; export default { title: 'Button', component: MyButton, argTypes: { color: { control: 'color' }, }, }; const Template = (args) => ({ props: Object.keys(args), components: { MyButton }, template: '<my-button :color="color" :rounded="rounded">{{label}}</my-button>', }); export const Rounded = Template.bind({}); Rounded.args = { rounded: true, color: '#f00', label: 'A Button with rounded edges', }; export const Square = Template.bind({}); Square.args = { rounded: false, color: '#00f', label: 'A Button with square edges', };
examples/vue-kitchen-sink/src/stories/components/button.stories.js
1
https://github.com/storybookjs/storybook/commit/3766df964edf5df99e3b6658d82b93e74bb1bec4
[ 0.0020723093766719103, 0.0008414092590101063, 0.00022460389300249517, 0.0002273145510116592, 0.000870378571562469 ]
{ "id": 0, "code_window": [ " size: { control: { type: 'select', options: ButtonSizes } },\n", " },\n", "};\n", "\n", "export const ButtonWithProps = (args: any) => ({\n", " components: { Button },\n", " template: '<Button :size=\"size\">Button text</Button>',\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "export const ButtonWithProps = (args: any, { argTypes }: any) => ({\n" ], "file_path": "examples/vue-cli/src/button/Button.stories.ts", "type": "replace", "edit_start_line_idx": 11 }
// eslint-disable-next-line import/no-extraneous-dependencies import AngularSnapshotSerializer from 'jest-preset-angular/build/AngularSnapshotSerializer'; // eslint-disable-next-line import/no-extraneous-dependencies import HTMLCommentSerializer from 'jest-preset-angular/build/HTMLCommentSerializer'; // eslint-disable-next-line import/no-extraneous-dependencies import { TestBed } from '@angular/core/testing'; // eslint-disable-next-line import/no-extraneous-dependencies import { BrowserDynamicTestingModule } from '@angular/platform-browser-dynamic/testing'; // eslint-disable-next-line import/no-extraneous-dependencies import { NO_ERRORS_SCHEMA } from '@angular/core'; import { addSerializer } from 'jest-specific-snapshot'; import { initModuleData } from './helpers'; addSerializer(HTMLCommentSerializer); addSerializer(AngularSnapshotSerializer); function getRenderedTree(story: any) { const currentStory = story.render(); const { moduleMeta, AppComponent } = initModuleData(currentStory); TestBed.configureTestingModule( // TODO: take a look at `bootstrap` because it looks it does not exists in TestModuleMetadata { imports: [...moduleMeta.imports], declarations: [...moduleMeta.declarations], providers: [...moduleMeta.providers], schemas: [NO_ERRORS_SCHEMA, ...moduleMeta.schemas], bootstrap: [...moduleMeta.bootstrap], } as any ); TestBed.overrideModule(BrowserDynamicTestingModule, { set: { entryComponents: [...moduleMeta.entryComponents], }, }); return TestBed.compileComponents().then(() => { const tree = TestBed.createComponent(AppComponent); tree.detectChanges(); return tree; }); } export default getRenderedTree;
addons/storyshots/storyshots-core/src/frameworks/angular/renderTree.ts
0
https://github.com/storybookjs/storybook/commit/3766df964edf5df99e3b6658d82b93e74bb1bec4
[ 0.00017540321277920157, 0.00017086828302126378, 0.00016132289601955563, 0.00017360107449349016, 0.000005306338607624639 ]
{ "id": 0, "code_window": [ " size: { control: { type: 'select', options: ButtonSizes } },\n", " },\n", "};\n", "\n", "export const ButtonWithProps = (args: any) => ({\n", " components: { Button },\n", " template: '<Button :size=\"size\">Button text</Button>',\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "export const ButtonWithProps = (args: any, { argTypes }: any) => ({\n" ], "file_path": "examples/vue-cli/src/button/Button.stories.ts", "type": "replace", "edit_start_line_idx": 11 }
// eslint-disable-next-line import/no-extraneous-dependencies import { Configuration } from 'webpack'; export function webpack(config: Configuration) { return { ...config, module: { ...config.module, rules: [ ...config.module.rules, { test: /\.html$/, use: [ { loader: require.resolve('html-loader'), }, ], }, ], }, }; }
app/html/src/server/framework-preset-html.ts
0
https://github.com/storybookjs/storybook/commit/3766df964edf5df99e3b6658d82b93e74bb1bec4
[ 0.00017528417811263353, 0.00017005129484459758, 0.0001669603807386011, 0.00016790934023447335, 0.0000037204295040282886 ]
{ "id": 0, "code_window": [ " size: { control: { type: 'select', options: ButtonSizes } },\n", " },\n", "};\n", "\n", "export const ButtonWithProps = (args: any) => ({\n", " components: { Button },\n", " template: '<Button :size=\"size\">Button text</Button>',\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "export const ButtonWithProps = (args: any, { argTypes }: any) => ({\n" ], "file_path": "examples/vue-cli/src/button/Button.stories.ts", "type": "replace", "edit_start_line_idx": 11 }
# My Example Markdown The group looked like tall, exotic grazing animals, swaying gracefully and unconsciously with the movement of the train, their high heels like polished hooves against the gray metal of the Flatline as a construct, a hardwired ROM cassette replicating a dead man’s skills, obsessions, kneejerk responses. ![An image](http://placehold.it/350x150) He stared at the clinic, Molly took him to the Tank War, mouth touched with hot gold as a gliding cursor struck sparks from the wall of a skyscraper canyon. Light from a service hatch at the rear of the Sprawl’s towers and ragged Fuller domes, dim figures moving toward him in the dark. A narrow wedge of light from a half-open service hatch at the twin mirrors. Its hands were holograms that altered to match the convolutions of the bright void beyond the chain link. Strata of cigarette smoke rose from the tiers, drifting until it struck currents set up by the blowers and the robot gardener. Still it was a steady pulse of pain midway down his spine. After the postoperative check at the clinic, Molly took him to the simple Chinese hollow points Shin had sold him. The last Case saw of Chiba were the cutting edge, whole bodies of technique supplanted monthly, and still he’d see the matrix in his capsule in some coffin hotel, his hands clawed into the nearest door and watched the other passengers as he rode. ## Typography # H1 ## H2 ### H3 #### H4 ##### H5 ###### H6 Emphasis, aka italics, with _asterisks_ or _underscores_. Strong emphasis, aka bold, with **asterisks** or **underscores**. Combined emphasis with **asterisks and _underscores_**. Strikethrough uses two tildes. ~~Scratch this.~~ Maybe include a [link](http://storybook.js.org) to your project as well. ## Block quote How about a block quote to spice things up? > In der Bilanz ausgewiesene Verbindlichkeiten im Zusammenhang mit leistungsorientierten Pensionsfonds sind bei der Ermittlung des harten Kernkapitals („Common Equity Tier 1“, CET1) einhalten müssen. Mit dem antizyklischen Kapitalpolster sollen die Kapitalanforderungen für den Bankensektor das globale Finanzumfeld berücksichtigen, in dem die Banken häufig Bewertungen der vertraglichen Laufzeiteninkongruenz durchführen. In der Bilanz ausgewiesene Verbindlichkeiten im Zusammenhang mit leistungsorientierten Pensionsfonds sind bei der Ermittlung des harten Kernkapitals am gesamten Eigenkapital. Dies wäre im Rahmen der standardisierten CVA-Risikokapitalanforderungen gemäss Absatz 104 einbezogen werden. Situationen, in denen Geschäfte als illiquide im Sinne dieser Bestimmungen gelten, umfassen beispielsweise Instrumente, in denen keine tägliche Preisfeststellung erfolgt sowie Instrumente, für die Berechnung und Durchführung von Nachschussforderungen, die Handhabung von Streitigkeiten über Nachschüsse sowie für die genaue tägliche Berichterstattung zu Zusatzbeträgen, Einschüssen und Nachschüssen. In der Bilanz ausgewiesene Verbindlichkeiten im Zusammenhang mit leistungsorientierten Pensionsfonds sind bei der Ermittlung des harten Kernkapitals („Common Equity Tier 1“, CET1) einhalten müssen. Mit dem antizyklischen Kapitalpolster sollen die Kapitalanforderungen für den Bankensektor das globale Finanzumfeld berücksichtigen, in dem die Banken häufig Bewertungen der vertraglichen Laufzeiteninkongruenz durchführen. Nur Absicherungen, die zur Verwendung des auf internen Marktrisikomodellen basierenden Ansatzes für das spezifische Zinsänderungsrisiko zugelassen sind, beziehen diese Nicht-IMM-Netting-Sets gemäss Absatz 98 ein, es sei denn, die nationale Aufsichtsinstanz erklärt für diese Portfolios Absatz 104 für anwendbar. ## Lists Mixed list: 1. First ordered list item 2. Another item - Unordered sub-list. 3. Actual numbers don't matter, just that it's a number 1. Ordered sub-list 2. Yo ho ho 4. And another item. Bullet list: - Whatever - This is getting - Very ... - Very ... - Tedious! - It's getting late, nothing to see here Numbered: 1. You get the idea 2. You still get the idea 3. You really get the idea 4. I'm done ## Tables A basic table: | Tables | Are | Cool | | ------------- | :-----------: | -----: | | col 3 is | right-aligned | \$1600 | | col 2 is | centered | \$12 | | zebra stripes | are neat | \$1 | Let's throw in a crazy table, because why not? | | [React](app/react) | [React Native](app/react-native) | [Vue](app/vue) | [Angular](app/angular) | [Mithril](app/mithril) | [HTML](app/html) | [Marko](app/marko) | [Svelte](app/svelte) | [Riot](app/riot) | [Ember](app/ember) | [Preact](app/preact) | | --------------------------------- | :----------------: | :------------------------------: | :------------: | :--------------------: | :--------------------: | :--------------: | :----------------: | :------------------: | :--------------: | :----------------: | :------------------: | | [a11y](addons/a11y) | + | | + | + | + | + | + | | | + | + | | [actions](addons/actions) | + | + | + | + | + | + | + | + | + | + | + | | [backgrounds](addons/backgrounds) | + | \* | + | + | + | + | + | + | + | + | + | | [centered](addons/centered) | + | | + | + | + | + | | + | | + | + | ## Code Sometimes you might want to manually include some \`code\` examples? Let's do it. ```js const Button = () => <button />; ```
lib/components/src/blocks/DocsPageExampleCaption.mdx
0
https://github.com/storybookjs/storybook/commit/3766df964edf5df99e3b6658d82b93e74bb1bec4
[ 0.0020553069189190865, 0.00035927590215578675, 0.0001647628960199654, 0.00017232351819984615, 0.0005653559346683323 ]
{ "id": 1, "code_window": [ " components: { Button },\n", " template: '<Button :size=\"size\">Button text</Button>',\n", " props: Object.keys(args),\n", "});\n", "ButtonWithProps.args = {\n", " size: 'big',\n", "};" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " props: Object.keys(argTypes),\n" ], "file_path": "examples/vue-cli/src/button/Button.stories.ts", "type": "replace", "edit_start_line_idx": 14 }
import { Meta, Preview, Story, Props } from '@storybook/addon-docs/blocks'; import MyButton from './Button.vue'; <Meta title="Addon/ControlsMDX" component={MyButton} argTypes={{ color: { control: { type: 'color' } }, }} /> export const Template = (args) => ({ props: Object.keys(args), components: { MyButton }, template: '<my-button :color="color" :rounded="rounded">{{label}}</my-button>', }); # Addon-controls in MDX Controls can also be defined and used in MDX stories. ## Rounded <Preview> <Story name="Rounded" args={{ rounded: true, color: '#f00', label: 'A Button with rounded edges', }} > {Template.bind({})} </Story> </Preview> <Props story="Rounded" /> ## Square <Preview> <Story name="Square" args={{ rounded: false, color: '#00f', label: 'A Button with square edges', }} > {Template.bind({})} </Story> </Preview> <Props story="Square" />
examples/vue-kitchen-sink/src/stories/addon-controls.stories.mdx
1
https://github.com/storybookjs/storybook/commit/3766df964edf5df99e3b6658d82b93e74bb1bec4
[ 0.001972096273675561, 0.0006185680394992232, 0.0001698565174592659, 0.00043350725900381804, 0.0006210471037775278 ]
{ "id": 1, "code_window": [ " components: { Button },\n", " template: '<Button :size=\"size\">Button text</Button>',\n", " props: Object.keys(args),\n", "});\n", "ButtonWithProps.args = {\n", " size: 'big',\n", "};" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " props: Object.keys(argTypes),\n" ], "file_path": "examples/vue-cli/src/button/Button.stories.ts", "type": "replace", "edit_start_line_idx": 14 }
require('./dist/register');
dev-kits/addon-preview-wrapper/register.js
0
https://github.com/storybookjs/storybook/commit/3766df964edf5df99e3b6658d82b93e74bb1bec4
[ 0.0001783428742783144, 0.0001783428742783144, 0.0001783428742783144, 0.0001783428742783144, 0 ]
{ "id": 1, "code_window": [ " components: { Button },\n", " template: '<Button :size=\"size\">Button text</Button>',\n", " props: Object.keys(args),\n", "});\n", "ButtonWithProps.args = {\n", " size: 'big',\n", "};" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " props: Object.keys(argTypes),\n" ], "file_path": "examples/vue-cli/src/button/Button.stories.ts", "type": "replace", "edit_start_line_idx": 14 }
button(style='color: black; background-color: brown;') Testing the a11y addon
examples/server-kitchen-sink/views/addons/a11y/contrast.pug
0
https://github.com/storybookjs/storybook/commit/3766df964edf5df99e3b6658d82b93e74bb1bec4
[ 0.00016977523046080023, 0.00016977523046080023, 0.00016977523046080023, 0.00016977523046080023, 0 ]
{ "id": 1, "code_window": [ " components: { Button },\n", " template: '<Button :size=\"size\">Button text</Button>',\n", " props: Object.keys(args),\n", "});\n", "ButtonWithProps.args = {\n", " size: 'big',\n", "};" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " props: Object.keys(argTypes),\n" ], "file_path": "examples/vue-cli/src/button/Button.stories.ts", "type": "replace", "edit_start_line_idx": 14 }
import { Meta, Story, Preview } from '@storybook/addon-docs/blocks'; import { CoolButton } from '../cool-button/cool-button'; import { addComponents } from '@storybook/aurelia'; import { text, withKnobs } from '@storybook/addon-knobs'; import Button from './button'; <Meta title="Welcome" component={CoolButton} decorators={[withKnobs]} /> # Welcome This is a test document written in MDX that defines a `CoolButton` story wrapped in a `Preview` doc block: <Preview withToolbar> <Story name="to Storybook"> {{ template: `<cool-button text.bind="testText"></cool-button>`, state: { testText: text('asfdafds', 'asasfdsa'), }, }} </Story> </Preview>
examples/aurelia-kitchen-sink/src/stories/mdx.stories.mdx
0
https://github.com/storybookjs/storybook/commit/3766df964edf5df99e3b6658d82b93e74bb1bec4
[ 0.0004824611824005842, 0.00027449577464722097, 0.00016855211288202554, 0.00017247401410713792, 0.0001470624702051282 ]
{ "id": 2, "code_window": [ " argTypes: {\n", " color: { control: { type: 'color' } },\n", " },\n", "};\n", "\n", "const Template = (args) => ({\n", " props: Object.keys(args),\n", " components: { MyButton },\n", " template: '<my-button :color=\"color\" :rounded=\"rounded\">{{label}}</my-button>',\n", "});\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "const Template = (args, { argTypes }) => ({\n", " props: Object.keys(argTypes),\n" ], "file_path": "examples/vue-kitchen-sink/src/stories/addon-controls.stories.js", "type": "replace", "edit_start_line_idx": 10 }
import Button from './Button.vue'; import { ButtonSizes } from './types'; export default { title: 'Button', component: Button, argTypes: { size: { control: { type: 'select', options: ButtonSizes } }, }, }; export const ButtonWithProps = (args: any) => ({ components: { Button }, template: '<Button :size="size">Button text</Button>', props: Object.keys(args), }); ButtonWithProps.args = { size: 'big', };
examples/vue-cli/src/button/Button.stories.ts
1
https://github.com/storybookjs/storybook/commit/3766df964edf5df99e3b6658d82b93e74bb1bec4
[ 0.9901240468025208, 0.4951823651790619, 0.0002406997955404222, 0.4951823651790619, 0.4949416518211365 ]
{ "id": 2, "code_window": [ " argTypes: {\n", " color: { control: { type: 'color' } },\n", " },\n", "};\n", "\n", "const Template = (args) => ({\n", " props: Object.keys(args),\n", " components: { MyButton },\n", " template: '<my-button :color=\"color\" :rounded=\"rounded\">{{label}}</my-button>',\n", "});\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "const Template = (args, { argTypes }) => ({\n", " props: Object.keys(argTypes),\n" ], "file_path": "examples/vue-kitchen-sink/src/stories/addon-controls.stories.js", "type": "replace", "edit_start_line_idx": 10 }
import memoize from 'memoizerific'; import Fuse from 'fuse.js'; import { DOCS_MODE } from 'global'; import { SyntheticEvent } from 'react'; import { StoriesHash, isRoot, isStory } from '@storybook/api'; const FUZZY_SEARCH_THRESHOLD = 0.35; export const prevent = (e: SyntheticEvent) => { e.preventDefault(); return false; }; const toList = memoize(1)((dataset: Dataset) => Object.values(dataset)); export type Item = StoriesHash[keyof StoriesHash]; export type Dataset = Record<string, Item>; export type SelectedSet = Record<string, boolean>; export type ExpandedSet = Record<string, boolean>; export const keyEventToAction = ({ keyCode, ctrlKey, shiftKey, altKey, metaKey, }: KeyboardEvent) => { if (shiftKey || metaKey || ctrlKey || altKey) { return false; } switch (keyCode) { case 18: { return 'ENTER'; } case 32: { return 'SPACE'; } case 38: { return 'UP'; } case 40: { return 'DOWN'; } case 37: { return DOCS_MODE ? 'UP' : 'LEFT'; } case 39: { return DOCS_MODE ? 'DOWN' : 'RIGHT'; } default: { return false; } } }; export const createId = (id: string, prefix: string) => `${prefix}_${id}`; export const get = memoize(1000)((id: string, dataset: Dataset) => dataset[id]); export const getParent = memoize(1000)((id: string, dataset: Dataset) => { const item = get(id, dataset); if (item && !isRoot(item)) { return get(item.parent, dataset); } return undefined; }); export const getParents = memoize(1000)((id: string, dataset: Dataset): Item[] => { const parent = getParent(id, dataset); if (!parent) { return []; } return [parent, ...getParents(parent.id, dataset)]; }); export const getMains = memoize(1)((dataset: Dataset) => toList(dataset).filter((m) => m.depth === 0) ); const getMainsKeys = memoize(1)((dataset: Dataset) => getMains(dataset).map((m) => m.id)); export const getPrevious = ({ id, dataset, expanded, }: { id: string; dataset: Dataset; expanded: ExpandedSet; }): Item | undefined => { // STEP 1 // find parent // if no previous sibling, use parent // unless parent is root // // STEP 2 // find previous sibling // recurse into that sibling's last children that are expanded const current = get(id, dataset); const parent = getParent(id, dataset); const mains = getMainsKeys(dataset); const siblings = parent && parent.children ? parent.children : mains; const index = siblings.indexOf(current.id); if (index === 0) { if (parent && parent.isRoot) { return getPrevious({ id: parent.id, dataset, expanded }); } if (!parent) { return undefined; } return parent; } let item = get(siblings[index - 1], dataset); while (item.children && expanded[item.id]) { item = get(item.children.slice(-1)[0], dataset); } if (item.isRoot) { return getPrevious({ id: item.id, dataset, expanded }); } return item; }; export const getNext = ({ id, dataset, expanded, }: { id: string; dataset: Dataset; expanded: ExpandedSet; }): Item | undefined => { // STEP 1: // find any children if the node is expanded, first child // // STEP 2 // iterate over parents, + fake 'root': // - find index of last parent as child in grandparent // - if child has next sibling, return // - if not, continue iterating const current = get(id, dataset); if (!current) { return undefined; } const { children } = current; if (children && children.length && (expanded[current.id] || current.isRoot)) { return get(children[0], dataset); } const mains = getMainsKeys(dataset); // we add a face super-root, otherwise we won't be able to jump to the next root const superRoot = { children: mains } as Item; const parents = getParents(id, dataset).concat([superRoot]); const next = parents.reduce( (acc, item) => { if (acc.result) { return acc; } const parent = item; const siblings = parent && parent.children ? parent.children : mains; const index = siblings.indexOf(acc.child.id); if (siblings[index + 1]) { return { result: get(siblings[index + 1], dataset) }; } return { child: parent }; }, { child: current, result: undefined } ); if (next.result && next.result.isRoot) { return getNext({ id: next.result.id, dataset, expanded }); } return next.result; }; const fuse = memoize(5)( (dataset) => new Fuse(toList(dataset), { threshold: FUZZY_SEARCH_THRESHOLD, keys: ['kind', 'name', 'parameters.fileName', 'parameters.notes'], }) ); const exactMatch = (filter: string) => { const reg = new RegExp(filter, 'i'); return (i: Item) => i.isLeaf && ((isStory(i) && reg.test(i.kind)) || (i.name && reg.test(i.name)) || (i.parameters && typeof i.parameters.fileName === 'string' && reg.test(i.parameters.fileName.toString())) || (i.parameters && typeof i.parameters.notes === 'string' && reg.test(i.parameters.notes.toString()))); }; export const toId = (base: string, addition: string) => base === '' ? `${addition}` : `${base}-${addition}`; export const filteredLength = (dataset: Dataset, filter: string) => { return Object.keys(toFiltered(dataset, filter)).length; }; export const toFiltered = (dataset: Dataset, filter: string) => { let found: Item[]; if (filter.length && filter.length > 2) { found = fuse(dataset).search(filter); } else { const matcher = exactMatch(filter); found = toList(dataset).filter(matcher); } // get all parents for all results const result = found.reduce((acc, item) => { if (item.isLeaf) { getParents(item.id, dataset).forEach((pitem) => { acc[pitem.id] = pitem; }); acc[item.id] = item; } return acc; }, {} as Dataset); // filter the children of the found items (and their parents) so only found entries are present return Object.entries(result).reduce((acc, [k, v]) => { const r = v.children ? { ...v, children: v.children.filter((c) => !!result[c]) } : v; if (r.isLeaf || r.children.length) { acc[k] = r; } return acc; }, {} as Dataset); };
lib/ui/src/components/sidebar/Tree/utils.ts
0
https://github.com/storybookjs/storybook/commit/3766df964edf5df99e3b6658d82b93e74bb1bec4
[ 0.00017663612379692495, 0.0001737569982651621, 0.00017025232955347747, 0.0001739918370731175, 0.0000016292611917378963 ]
{ "id": 2, "code_window": [ " argTypes: {\n", " color: { control: { type: 'color' } },\n", " },\n", "};\n", "\n", "const Template = (args) => ({\n", " props: Object.keys(args),\n", " components: { MyButton },\n", " template: '<my-button :color=\"color\" :rounded=\"rounded\">{{label}}</my-button>',\n", "});\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "const Template = (args, { argTypes }) => ({\n", " props: Object.keys(argTypes),\n" ], "file_path": "examples/vue-kitchen-sink/src/stories/addon-controls.stories.js", "type": "replace", "edit_start_line_idx": 10 }
import { Button } from '@storybook/react/demo'; import { Story, Meta } from '@storybook/addon-docs/blocks'; <Meta title="Button" /> # Story definition <Story name="one"> <Button>One</Button> </Story> <Story name="hello story"> <Button>Hello button</Button> </Story> <Story name="w/punctuation"> <Button>with punctuation</Button> </Story> <Story name="1 fine day"> <Button>starts with number</Button> </Story>
addons/docs/src/mdx/__testfixtures__/story-definitions.mdx
0
https://github.com/storybookjs/storybook/commit/3766df964edf5df99e3b6658d82b93e74bb1bec4
[ 0.00020440728985704482, 0.0001800174795789644, 0.00016699764819350094, 0.00016864744247868657, 0.000017259360902244225 ]
{ "id": 2, "code_window": [ " argTypes: {\n", " color: { control: { type: 'color' } },\n", " },\n", "};\n", "\n", "const Template = (args) => ({\n", " props: Object.keys(args),\n", " components: { MyButton },\n", " template: '<my-button :color=\"color\" :rounded=\"rounded\">{{label}}</my-button>',\n", "});\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "const Template = (args, { argTypes }) => ({\n", " props: Object.keys(argTypes),\n" ], "file_path": "examples/vue-kitchen-sink/src/stories/addon-controls.stories.js", "type": "replace", "edit_start_line_idx": 10 }
import { ModuleFn } from '../index'; export interface Notification { id: string; link: string; content: string; onClear?: () => void; } export interface SubState { notifications: Notification[]; } export interface SubAPI { addNotification: (notification: Notification) => void; clearNotification: (id: string) => void; } export const init: ModuleFn = ({ store }) => { const api: SubAPI = { addNotification: (notification) => { // Get rid of it if already exists api.clearNotification(notification.id); const { notifications } = store.getState(); store.setState({ notifications: [...notifications, notification] }); }, clearNotification: (id) => { const { notifications } = store.getState(); store.setState({ notifications: notifications.filter((n) => n.id !== id) }); const notification = notifications.find((n) => n.id === id); if (notification && notification.onClear) { notification.onClear(); } }, }; const state: SubState = { notifications: [] }; return { api, state }; };
lib/api/src/modules/notifications.ts
0
https://github.com/storybookjs/storybook/commit/3766df964edf5df99e3b6658d82b93e74bb1bec4
[ 0.00017569346528034657, 0.00017158886475954205, 0.00016577285714447498, 0.00017306031077168882, 0.0000034586525998747675 ]
{ "id": 3, "code_window": [ " argTypes={{\n", " color: { control: { type: 'color' } },\n", " }}\n", "/>\n", "\n", "export const Template = (args) => ({\n", " props: Object.keys(args),\n", " components: { MyButton },\n", " template: '<my-button :color=\"color\" :rounded=\"rounded\">{{label}}</my-button>',\n", "});\n", "\n", "# Addon-controls in MDX\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const Template = (args, { argTypes }) => ({\n", " props: Object.keys(argTypes),\n" ], "file_path": "examples/vue-kitchen-sink/src/stories/addon-controls.stories.mdx", "type": "replace", "edit_start_line_idx": 11 }
import Button from './Button.vue'; import { ButtonSizes } from './types'; export default { title: 'Button', component: Button, argTypes: { size: { control: { type: 'select', options: ButtonSizes } }, }, }; export const ButtonWithProps = (args: any) => ({ components: { Button }, template: '<Button :size="size">Button text</Button>', props: Object.keys(args), }); ButtonWithProps.args = { size: 'big', };
examples/vue-cli/src/button/Button.stories.ts
1
https://github.com/storybookjs/storybook/commit/3766df964edf5df99e3b6658d82b93e74bb1bec4
[ 0.9886695742607117, 0.49448415637016296, 0.0002987546322401613, 0.49448415637016296, 0.4941854178905487 ]
{ "id": 3, "code_window": [ " argTypes={{\n", " color: { control: { type: 'color' } },\n", " }}\n", "/>\n", "\n", "export const Template = (args) => ({\n", " props: Object.keys(args),\n", " components: { MyButton },\n", " template: '<my-button :color=\"color\" :rounded=\"rounded\">{{label}}</my-button>',\n", "});\n", "\n", "# Addon-controls in MDX\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const Template = (args, { argTypes }) => ({\n", " props: Object.keys(argTypes),\n" ], "file_path": "examples/vue-kitchen-sink/src/stories/addon-controls.stories.mdx", "type": "replace", "edit_start_line_idx": 11 }
// FIXME: @igor-dv // import React from 'react'; // import { storiesOf } from '@storybook/react'; // import { ReactComponent as Logo } from '../logo.svg'; // // storiesOf('CRA', module).add('Svgr', () => <Logo />);
examples/cra-kitchen-sink/src/stories/cra-svgr.stories.js
0
https://github.com/storybookjs/storybook/commit/3766df964edf5df99e3b6658d82b93e74bb1bec4
[ 0.00017648949869908392, 0.00017648949869908392, 0.00017648949869908392, 0.00017648949869908392, 0 ]
{ "id": 3, "code_window": [ " argTypes={{\n", " color: { control: { type: 'color' } },\n", " }}\n", "/>\n", "\n", "export const Template = (args) => ({\n", " props: Object.keys(args),\n", " components: { MyButton },\n", " template: '<my-button :color=\"color\" :rounded=\"rounded\">{{label}}</my-button>',\n", "});\n", "\n", "# Addon-controls in MDX\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const Template = (args, { argTypes }) => ({\n", " props: Object.keys(argTypes),\n" ], "file_path": "examples/vue-kitchen-sink/src/stories/addon-controls.stories.mdx", "type": "replace", "edit_start_line_idx": 11 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`csf-hoist-story-annotations transforms correctly using "overrides.input.js" data 1`] = ` "import React from 'react'; import Button from './Button'; import { action } from '@storybook/addon-actions'; export default { title: 'Button', }; export const story1 = () => <Button label=\\"Story 1\\" />; export const story2 = () => <Button label=\\"Story 2\\" onClick={action('click')} />; story2.storyName = 'second story'; story2.parameters = { foo: 'bar' }; export const story3 = () => ( <div> <Button label=\\"The Button\\" onClick={action('onClick')} /> <br /> </div> ); const baz = 17; story3.storyName = 'complex story'; story3.parameters = { foo: { bar: baz } }; story3.decorators = [(storyFn) => <bar>{storyFn}</bar>];" `;
lib/codemod/src/transforms/__testfixtures__/csf-hoist-story-annotations/overrides.output.snapshot
0
https://github.com/storybookjs/storybook/commit/3766df964edf5df99e3b6658d82b93e74bb1bec4
[ 0.00019270332995802164, 0.0001774961274350062, 0.00016422710905317217, 0.00017555798694957048, 0.0000117058707473916 ]
{ "id": 3, "code_window": [ " argTypes={{\n", " color: { control: { type: 'color' } },\n", " }}\n", "/>\n", "\n", "export const Template = (args) => ({\n", " props: Object.keys(args),\n", " components: { MyButton },\n", " template: '<my-button :color=\"color\" :rounded=\"rounded\">{{label}}</my-button>',\n", "});\n", "\n", "# Addon-controls in MDX\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const Template = (args, { argTypes }) => ({\n", " props: Object.keys(argTypes),\n" ], "file_path": "examples/vue-kitchen-sink/src/stories/addon-controls.stories.mdx", "type": "replace", "edit_start_line_idx": 11 }
import { document } from 'global'; /** @jsx m */ import m from 'mithril'; import dedent from 'ts-dedent'; import { RenderContext } from './types'; const rootEl = document.getElementById('root'); export default function renderMain({ storyFn, kind, name, showMain, showError }: RenderContext) { const element = storyFn(); if (!element) { const error = { title: `Expecting a Mithril element from the story: "${name}" of "${kind}".`, description: dedent` Did you forget to return the Mithril element from the story? Use "() => MyComp" or "() => { return MyComp; }" when defining the story. `, }; showError(error); return; } showMain(); m.mount(rootEl, { view: () => m(element) }); }
app/mithril/src/client/preview/render.ts
0
https://github.com/storybookjs/storybook/commit/3766df964edf5df99e3b6658d82b93e74bb1bec4
[ 0.0001743433967931196, 0.0001714473619358614, 0.00016684150614310056, 0.00017315718287136406, 0.000003292638893981348 ]
{ "id": 4, "code_window": [ " color: { control: 'color' },\n", " },\n", "};\n", "\n", "const Template = (args) => ({\n", " props: Object.keys(args),\n", " components: { MyButton },\n", " template: '<my-button :color=\"color\" :rounded=\"rounded\">{{label}}</my-button>',\n", "});\n", "\n", "export const Rounded = Template.bind({});\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const Template = (args, { argTypes }) => ({\n", " props: Object.keys(argTypes),\n" ], "file_path": "examples/vue-kitchen-sink/src/stories/components/button.stories.js", "type": "replace", "edit_start_line_idx": 10 }
import MyButton from './Button.vue'; export default { title: 'Addon/Controls', component: MyButton, argTypes: { color: { control: { type: 'color' } }, }, }; const Template = (args) => ({ props: Object.keys(args), components: { MyButton }, template: '<my-button :color="color" :rounded="rounded">{{label}}</my-button>', }); export const Rounded = Template.bind({}); Rounded.args = { rounded: true, color: '#f00', label: 'A Button with rounded edges', }; export const Square = Template.bind({}); Square.args = { rounded: false, color: '#00f', label: 'A Button with square edges', };
examples/vue-kitchen-sink/src/stories/addon-controls.stories.js
1
https://github.com/storybookjs/storybook/commit/3766df964edf5df99e3b6658d82b93e74bb1bec4
[ 0.9984387755393982, 0.6659877896308899, 0.0013028254033997655, 0.9982218146324158, 0.47000324726104736 ]
{ "id": 4, "code_window": [ " color: { control: 'color' },\n", " },\n", "};\n", "\n", "const Template = (args) => ({\n", " props: Object.keys(args),\n", " components: { MyButton },\n", " template: '<my-button :color=\"color\" :rounded=\"rounded\">{{label}}</my-button>',\n", "});\n", "\n", "export const Rounded = Template.bind({});\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const Template = (args, { argTypes }) => ({\n", " props: Object.keys(argTypes),\n" ], "file_path": "examples/vue-kitchen-sink/src/stories/components/button.stories.js", "type": "replace", "edit_start_line_idx": 10 }
import { document, fetch, Node } from 'global'; import dedent from 'ts-dedent'; import { RenderContext, FetchStoryHtmlType } from './types'; const rootElement = document.getElementById('root'); let fetchStoryHtml: FetchStoryHtmlType = async (url, path, params) => { const fetchUrl = new URL(`${url}/${path}`); fetchUrl.search = new URLSearchParams(params).toString(); const response = await fetch(fetchUrl); return response.text(); }; export async function renderMain({ storyFn, id, kind, name, showMain, showError, forceRender, parameters, }: RenderContext) { const storyParams = storyFn(); const { server: { url, id: storyId, params }, } = parameters; const fetchId = storyId || id; const fetchParams = { ...params, ...storyParams }; const element = await fetchStoryHtml(url, fetchId, fetchParams); showMain(); if (typeof element === 'string') { rootElement.innerHTML = element; } else if (element instanceof Node) { // Don't re-mount the element if it didn't change and neither did the story if (rootElement.firstChild === element && forceRender === true) { return; } rootElement.innerHTML = ''; rootElement.appendChild(element); } else { showError({ title: `Expecting an HTML snippet or DOM node from the story: "${name}" of "${kind}".`, description: dedent` Did you forget to return the HTML snippet from the story? Use "() => <your snippet or node>" or when defining the story. `, }); } } export const setFetchStoryHtml: any = (fetchHtml: FetchStoryHtmlType) => { if (fetchHtml !== undefined) { fetchStoryHtml = fetchHtml; } };
app/server/src/client/preview/render.ts
0
https://github.com/storybookjs/storybook/commit/3766df964edf5df99e3b6658d82b93e74bb1bec4
[ 0.00017589058552403003, 0.00017215630214195698, 0.000169642866239883, 0.00017224508337676525, 0.000002187969130318379 ]
{ "id": 4, "code_window": [ " color: { control: 'color' },\n", " },\n", "};\n", "\n", "const Template = (args) => ({\n", " props: Object.keys(args),\n", " components: { MyButton },\n", " template: '<my-button :color=\"color\" :rounded=\"rounded\">{{label}}</my-button>',\n", "});\n", "\n", "export const Rounded = Template.bind({});\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const Template = (args, { argTypes }) => ({\n", " props: Object.keys(argTypes),\n" ], "file_path": "examples/vue-kitchen-sink/src/stories/components/button.stories.js", "type": "replace", "edit_start_line_idx": 10 }
import 'jest-specific-snapshot'; import path from 'path'; import fs from 'fs-extra'; import mdx from '@mdx-js/mdx'; import prettier from 'prettier'; import plugin from './mdx-compiler-plugin'; async function generate(filePath) { const content = await fs.readFile(filePath, 'utf8'); const code = mdx.sync(content, { filepath: filePath, compilers: [plugin({})], }); return prettier.format(code, { parser: 'babel', printWidth: 100, tabWidth: 2, bracketSpacing: true, trailingComma: 'es5', singleQuote: true, }); } const inputRegExp = /\.mdx$/; describe('docs-mdx-compiler-plugin', () => { const transformFixturesDir = path.join(__dirname, '__testfixtures__'); fs.readdirSync(transformFixturesDir) .filter((fileName) => inputRegExp.test(fileName)) .filter((fileName) => fileName !== 'story-missing-props.mdx') .forEach((fixtureFile) => { it(fixtureFile, async () => { const inputPath = path.join(transformFixturesDir, fixtureFile); const code = await generate(inputPath); expect(code).toMatchSpecificSnapshot(inputPath.replace(inputRegExp, '.output.snapshot')); }); }); it('errors on missing story props', async () => { await expect( generate(path.resolve(__dirname, './__testfixtures__/story-missing-props.mdx')) ).rejects.toThrow('Expected a story name or ID attribute'); }); });
addons/docs/src/mdx/mdx-compiler-plugin.test.js
0
https://github.com/storybookjs/storybook/commit/3766df964edf5df99e3b6658d82b93e74bb1bec4
[ 0.00017752748681232333, 0.00017459693481214345, 0.00017284970090258867, 0.00017365007079206407, 0.0000017196862245327793 ]
{ "id": 4, "code_window": [ " color: { control: 'color' },\n", " },\n", "};\n", "\n", "const Template = (args) => ({\n", " props: Object.keys(args),\n", " components: { MyButton },\n", " template: '<my-button :color=\"color\" :rounded=\"rounded\">{{label}}</my-button>',\n", "});\n", "\n", "export const Rounded = Template.bind({});\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const Template = (args, { argTypes }) => ({\n", " props: Object.keys(argTypes),\n" ], "file_path": "examples/vue-kitchen-sink/src/stories/components/button.stories.js", "type": "replace", "edit_start_line_idx": 10 }
import React from 'react'; import { shallow } from 'enzyme'; import ArrayType from '../types/Array'; jest.useFakeTimers(); describe('Array', () => { it('should subscribe to setKnobs event of channel', () => { const onChange = jest.fn(); const wrapper = shallow( <ArrayType onChange={onChange} knob={{ name: 'passions', value: ['Fishing', 'Skiing'], separator: ',' }} /> ); wrapper.simulate('change', { target: { value: 'Fishing,Skiing,Dancing' } }); jest.runAllTimers(); expect(onChange).toHaveBeenCalledWith(['Fishing', 'Skiing', 'Dancing']); }); it('deserializes an Array to an Array', () => { const array = ['a', 'b', 'c']; const deserialized = ArrayType.deserialize(array); expect(deserialized).toEqual(['a', 'b', 'c']); }); it('deserializes an Object to an Array', () => { const object = { 1: 'one', 0: 'zero', 2: 'two' }; const deserialized = ArrayType.deserialize(object); expect(deserialized).toEqual(['zero', 'one', 'two']); }); it('should change to an empty array when emptied', () => { const onChange = jest.fn(); const wrapper = shallow( <ArrayType onChange={onChange} knob={{ name: 'passions', value: ['Fishing', 'Skiing'], separator: ',' }} /> ); wrapper.simulate('change', { target: { value: '' } }); jest.runAllTimers(); expect(onChange).toHaveBeenCalledWith([]); }); });
addons/knobs/src/components/__tests__/Array.js
0
https://github.com/storybookjs/storybook/commit/3766df964edf5df99e3b6658d82b93e74bb1bec4
[ 0.00017850195581559092, 0.00017455128545407206, 0.00016982023953460157, 0.0001741725136525929, 0.0000031214472073770594 ]
{ "id": 0, "code_window": [ " var solutionLink = req.body.challengeInfo.publicURL;\n", " var githubLink = req.body.challengeInfo.challengeType === '4'\n", " ? req.body.challengeInfo.githubURL : true;\n", " if (!solutionLink || !githubLink) {\n", " req.flash('errors', {\n", " msg: 'You haven\\'t supplied the necessary URLs for us to inspect ' +\n", " 'your work.'\n", " });\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " var challengeType = req.body.challengeInfo.challengeType === '4' ?\n", " 4 : 3;\n" ], "file_path": "controllers/challenge.js", "type": "add", "edit_start_line_idx": 459 }
var _ = require('lodash'), async = require('async'), crypto = require('crypto'), nodemailer = require('nodemailer'), passport = require('passport'), User = require('../models/User'), secrets = require('../config/secrets'), moment = require('moment'), debug = require('debug')('freecc:cntr:userController'), resources = require('./resources'), R = require('ramda'); /** * * @param req * @param res * @returns null * Middleware to migrate users from fragmented challenge structure to unified * challenge structure */ exports.userMigration = function(req, res, next) { if (req.user && req.user.completedChallenges.length === 0) { req.user.completedChallenges = R.filter(function (elem) { return elem; // getting rid of undefined }, R.concat( req.user.completedCoursewares, req.user.completedBonfires.map(function (bonfire) { return ({ completedDate: bonfire.completedDate, _id: bonfire._id, name: bonfire.name, completedWith: bonfire.completedWith, solution: bonfire.solution, githubLink: '', verified: false, challengeType: 5 }); }) )); next(); } else { next(); } }; /** * GET /signin * Siginin page. */ exports.getSignin = function(req, res) { if (req.user) { return res.redirect('/'); } res.render('account/signin', { title: 'Free Code Camp Login' }); }; /** * POST /signin * Sign in using email and password. */ exports.postSignin = function(req, res, next) { req.assert('email', 'Email is not valid').isEmail(); req.assert('password', 'Password cannot be blank').notEmpty(); var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/signin'); } passport.authenticate('local', function(err, user, info) { if (err) { return next(err); } if (!user) { req.flash('errors', { msg: info.message }); return res.redirect('/signin'); } req.logIn(user, function(err) { if (err) { return next(err); } req.flash('success', { msg: 'Success! You are logged in.' }); if (/hotStories/.test(req.session.returnTo)) { return res.redirect('../news'); } if (/field-guide/.test(req.session.returnTo)) { return res.redirect('../field-guide'); } return res.redirect(req.session.returnTo || '/'); }); })(req, res, next); }; /** * GET /signout * Log out. */ exports.signout = function(req, res) { req.logout(); res.redirect('/'); }; /** * GET /email-signup * Signup page. */ exports.getEmailSignin = function(req, res) //noinspection Eslint { if (req.user) { return res.redirect('/'); } res.render('account/email-signin', { title: 'Sign in to your Free Code Camp Account' }); }; /** * GET /signin * Signup page. */ exports.getEmailSignup = function(req, res) { if (req.user) { return res.redirect('/'); } res.render('account/email-signup', { title: 'Create Your Free Code Camp Account' }); }; /** * POST /email-signup * Create a new local account. */ exports.postEmailSignup = function(req, res, next) { req.assert('email', 'valid email required').isEmail(); var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/email-signup'); } var possibleUserData = req.body; if (possibleUserData.password.length < 8) { req.flash('errors', { msg: 'Your password is too short' }); return res.redirect('email-signup'); } if (possibleUserData.username.length < 5 || possibleUserData.length > 20) { req.flash('errors', { msg: 'Your username must be between 5 and 20 characters' }); return res.redirect('email-signup'); } var user = new User({ email: req.body.email.trim(), password: req.body.password, profile: { username: req.body.username.trim(), picture: 'https://s3.amazonaws.com/freecodecamp/camper-image-placeholder.png' } }); User.findOne({ email: req.body.email }, function(err, existingEmail) { if (err) { return next(err); } if (existingEmail) { req.flash('errors', { msg: 'Account with that email address already exists.' }); return res.redirect('/email-signup'); } User.findOne( { 'profile.username': req.body.username }, function(err, existingUsername) { if (err) { return next(err); } if (existingUsername) { req.flash('errors', { msg: 'Account with that username already exists.' }); return res.redirect('/email-signup'); } user.save(function(err) { if (err) { return next(err); } req.logIn(user, function(err) { if (err) { return next(err); } res.redirect('/email-signup'); }); }); var transporter = nodemailer.createTransport({ service: 'Mandrill', auth: { user: secrets.mandrill.user, pass: secrets.mandrill.password } }); var mailOptions = { to: user.email, from: '[email protected]', subject: 'Welcome to Free Code Camp!', text: [ 'Greetings from San Francisco!\n\n', 'Thank you for joining our community.\n', 'Feel free to email us at this address if you have ', 'any questions about Free Code Camp.\n', 'And if you have a moment, check out our blog: ', 'blog.freecodecamp.com.\n', 'Good luck with the challenges!\n\n', '- the Volunteer Camp Counselor Team' ].join('') }; transporter.sendMail(mailOptions, function(err) { if (err) { return err; } }); }); }); }; /** * GET /account * Profile page. */ exports.getAccount = function(req, res) { res.render('account/account', { title: 'Manage your Free Code Camp Account' }); }; /** * Angular API Call */ exports.getAccountAngular = function(req, res) { res.json({ user: req.user }); }; /** * Unique username check API Call */ exports.checkUniqueUsername = function(req, res, next) { User.count( { 'profile.username': req.params.username.toLowerCase() }, function (err, data) { if (err) { return next(err); } if (data === 1) { return res.send(true); } else { return res.send(false); } }); }; /** * Existing username check */ exports.checkExistingUsername = function(req, res, next) { User.count( { 'profile.username': req.params.username.toLowerCase() }, function (err, data) { if (err) { return next(err); } if (data === 1) { return res.send(true); } else { return res.send(false); } } ); }; /** * Unique email check API Call */ exports.checkUniqueEmail = function(req, res, next) { User.count( { email: decodeURIComponent(req.params.email).toLowerCase() }, function (err, data) { if (err) { return next(err); } if (data === 1) { return res.send(true); } else { return res.send(false); } } ); }; /** * GET /campers/:username * Public Profile page. */ exports.returnUser = function(req, res, next) { User.find( { 'profile.username': req.params.username.toLowerCase() }, function(err, user) { if (err) { debug('Username err: ', err); return next(err); } if (user[0]) { user = user[0]; user.progressTimestamps = user.progressTimestamps.sort(function(a, b) { return a - b; }); var timeObject = Object.create(null); R.forEach(function(time) { timeObject[moment(time).format('YYYY-MM-DD')] = time; }, user.progressTimestamps); var tmpLongest = 1; var timeKeys = R.keys(timeObject); user.longestStreak = 0; for (var i = 1; i <= timeKeys.length; i++) { if (moment(timeKeys[i - 1]).add(1, 'd').toString() === moment(timeKeys[i]).toString()) { tmpLongest++; if (tmpLongest > user.longestStreak) { user.longestStreak = tmpLongest; } } else { tmpLongest = 1; } } timeKeys = timeKeys.reverse(); tmpLongest = 1; user.currentStreak = 1; var today = moment(Date.now()).format('YYYY-MM-DD'); if ( moment(today).toString() === moment(timeKeys[0]).toString() || moment(today).subtract(1, 'd').toString() === moment(timeKeys[0]).toString() ) { for (var _i = 1; _i <= timeKeys.length; _i++) { if ( moment(timeKeys[_i - 1]).subtract(1, 'd').toString() === moment(timeKeys[_i]).toString() ) { tmpLongest++; if (tmpLongest > user.currentStreak) { user.currentStreak = tmpLongest; } } else { break; } } } else { user.currentStreak = 1; } user.save(function(err) { if (err) { return next(err); } var data = {}; var progressTimestamps = user.progressTimestamps; progressTimestamps.forEach(function(timeStamp) { data[(timeStamp / 1000)] = 1; }); user.currentStreak = user.currentStreak || 1; user.longestStreak = user.longestStreak || 1; var challenges = user.completedCoursewares.filter(function ( obj ) { return !!obj.solution; }); res.render('account/show', { title: 'Camper ' + user.profile.username + '\'s portfolio', username: user.profile.username, name: user.profile.name, location: user.profile.location, githubProfile: user.profile.githubProfile, linkedinProfile: user.profile.linkedinProfile, codepenProfile: user.profile.codepenProfile, facebookProfile: user.profile.facebookProfile, twitterHandle: user.profile.twitterHandle, bio: user.profile.bio, picture: user.profile.picture, progressTimestamps: user.progressTimestamps, website1Link: user.portfolio.website1Link, website1Title: user.portfolio.website1Title, website1Image: user.portfolio.website1Image, website2Link: user.portfolio.website2Link, website2Title: user.portfolio.website2Title, website2Image: user.portfolio.website2Image, website3Link: user.portfolio.website3Link, website3Title: user.portfolio.website3Title, website3Image: user.portfolio.website3Image, challenges: challenges, bonfires: user.completedChallenges.filter(function(challenge) { return challenge.challengeType === 5; }), calender: data, moment: moment, longestStreak: user.longestStreak + (user.longestStreak === 1 ? ' day' : ' days'), currentStreak: user.currentStreak + (user.currentStreak === 1 ? ' day' : ' days') }); }); } else { req.flash('errors', { msg: "404: We couldn't find a page with that url. " + 'Please double check the link.' }); return res.redirect('/'); } } ); }; /** * POST /update-progress * Update profile information. */ exports.updateProgress = function(req, res, next) { User.findById(req.user.id, function(err, user) { if (err) { return next(err); } user.email = req.body.email || ''; user.profile.name = req.body.name || ''; user.profile.gender = req.body.gender || ''; user.profile.location = req.body.location || ''; user.profile.website = req.body.website || ''; user.save(function(err) { if (err) { return next(err); } req.flash('success', { msg: 'Profile information updated.' }); res.redirect('/account'); }); }); }; /** * POST /account/profile * Update profile information. */ exports.postUpdateProfile = function(req, res, next) { User.findById(req.user.id, function(err) { if (err) { return next(err); } var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/account'); } User.findOne({ email: req.body.email }, function(err, existingEmail) { if (err) { return next(err); } var user = req.user; if (existingEmail && existingEmail.email !== user.email) { req.flash('errors', { msg: 'An account with that email address already exists.' }); return res.redirect('/account'); } User.findOne( { 'profile.username': req.body.username }, function(err, existingUsername) { if (err) { return next(err); } var user = req.user; if ( existingUsername && existingUsername.profile.username !== user.profile.username ) { req.flash('errors', { msg: 'An account with that username already exists.' }); return res.redirect('/account'); } user.email = req.body.email.trim() || ''; user.profile.name = req.body.name.trim() || ''; user.profile.username = req.body.username.trim() || ''; user.profile.location = req.body.location.trim() || ''; user.profile.githubProfile = req.body.githubProfile.trim() || ''; user.profile.facebookProfile = req.body.facebookProfile.trim() || ''; user.profile.linkedinProfile = req.body.linkedinProfile.trim() || ''; user.profile.codepenProfile = req.body.codepenProfile.trim() || ''; user.profile.twitterHandle = req.body.twitterHandle.trim() || ''; user.profile.bio = req.body.bio.trim() || ''; user.profile.picture = req.body.picture.trim() || 'https://s3.amazonaws.com/freecodecamp/' + 'camper-image-placeholder.png'; user.portfolio.website1Title = req.body.website1Title.trim() || ''; user.portfolio.website1Link = req.body.website1Link.trim() || ''; user.portfolio.website1Image = req.body.website1Image.trim() || ''; user.portfolio.website2Title = req.body.website2Title.trim() || ''; user.portfolio.website2Link = req.body.website2Link.trim() || ''; user.portfolio.website2Image = req.body.website2Image.trim() || ''; user.portfolio.website3Title = req.body.website3Title.trim() || ''; user.portfolio.website3Link = req.body.website3Link.trim() || ''; user.portfolio.website3Image = req.body.website3Image.trim() || ''; user.save(function (err) { if (err) { return next(err); } resources.updateUserStoryPictures( user._id.toString(), user.profile.picture, user.profile.username, function(err) { if (err) { return next(err); } req.flash('success', { msg: 'Profile information updated.' }); res.redirect('/account'); } ); }); } ); }); }); }; /** * POST /account/password * Update current password. */ exports.postUpdatePassword = function(req, res, next) { req.assert('password', 'Password must be at least 4 characters long').len(4); req.assert('confirmPassword', 'Passwords do not match') .equals(req.body.password); var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/account'); } User.findById(req.user.id, function(err, user) { if (err) { return next(err); } user.password = req.body.password; user.save(function(err) { if (err) { return next(err); } req.flash('success', { msg: 'Password has been changed.' }); res.redirect('/account'); }); }); }; /** * POST /account/delete * Delete user account. */ exports.postDeleteAccount = function(req, res, next) { User.remove({ _id: req.user.id }, function(err) { if (err) { return next(err); } req.logout(); req.flash('info', { msg: 'Your account has been deleted.' }); res.redirect('/'); }); }; /** * GET /account/unlink/:provider * Unlink OAuth provider. */ exports.getOauthUnlink = function(req, res, next) { var provider = req.params.provider; User.findById(req.user.id, function(err, user) { if (err) { return next(err); } user[provider] = null; user.tokens = _.reject(user.tokens, function(token) { return token.kind === provider; }); user.save(function(err) { if (err) { return next(err); } req.flash('info', { msg: provider + ' account has been unlinked.' }); res.redirect('/account'); }); }); }; /** * GET /reset/:token * Reset Password page. */ exports.getReset = function(req, res, next) { if (req.isAuthenticated()) { return res.redirect('/'); } User .findOne({ resetPasswordToken: req.params.token }) .where('resetPasswordExpires').gt(Date.now()) .exec(function(err, user) { if (err) { return next(err); } if (!user) { req.flash('errors', { msg: 'Password reset token is invalid or has expired.' }); return res.redirect('/forgot'); } res.render('account/reset', { title: 'Password Reset', token: req.params.token }); }); }; /** * POST /reset/:token * Process the reset password request. */ exports.postReset = function(req, res, next) { var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('back'); } async.waterfall([ function(done) { User .findOne({ resetPasswordToken: req.params.token }) .where('resetPasswordExpires').gt(Date.now()) .exec(function(err, user) { if (err) { return next(err); } if (!user) { req.flash('errors', { msg: 'Password reset token is invalid or has expired.' }); return res.redirect('back'); } user.password = req.body.password; user.resetPasswordToken = null; user.resetPasswordExpires = null; user.save(function(err) { if (err) { return done(err); } req.logIn(user, function(err) { done(err, user); }); }); }); }, function(user, done) { var transporter = nodemailer.createTransport({ service: 'Mandrill', auth: { user: secrets.mandrill.user, pass: secrets.mandrill.password } }); var mailOptions = { to: user.email, from: '[email protected]', subject: 'Your Free Code Camp password has been changed', text: [ 'Hello,\n\n', 'This email is confirming that you requested to', 'reset your password for your Free Code Camp account.', 'This is your email:', user.email, '\n' ].join(' ') }; transporter.sendMail(mailOptions, function(err) { if (err) { return done(err); } req.flash('success', { msg: 'Success! Your password has been changed.' }); done(); }); } ], function(err) { if (err) { return next(err); } res.redirect('/'); }); }; /** * GET /forgot * Forgot Password page. */ exports.getForgot = function(req, res) { if (req.isAuthenticated()) { return res.redirect('/'); } res.render('account/forgot', { title: 'Forgot Password' }); }; /** * POST /forgot * Create a random token, then the send user an email with a reset link. */ exports.postForgot = function(req, res, next) { var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/forgot'); } async.waterfall([ function(done) { crypto.randomBytes(16, function(err, buf) { if (err) { return done(err); } var token = buf.toString('hex'); done(null, token); }); }, function(token, done) { User.findOne({ email: req.body.email.toLowerCase() }, function(err, user) { if (err) { return done(err); } if (!user) { req.flash('errors', { msg: 'No account with that email address exists.' }); return res.redirect('/forgot'); } user.resetPasswordToken = token; user.resetPasswordExpires = Date.now() + 3600000; // 1 hour user.save(function(err) { if (err) { return done(err); } done(null, token, user); }); }); }, function(token, user, done) { var transporter = nodemailer.createTransport({ service: 'Mandrill', auth: { user: secrets.mandrill.user, pass: secrets.mandrill.password } }); var mailOptions = { to: user.email, from: '[email protected]', subject: 'Reset your Free Code Camp password', text: [ 'You are receiving this email because you (or someone else)\n', 'requested we reset your Free Code Camp account\'s password.\n\n', 'Please click on the following link, or paste this into your\n', 'browser to complete the process:\n\n', 'http://', req.headers.host, '/reset/', token, '\n\n', 'If you did not request this, please ignore this email and\n', 'your password will remain unchanged.\n' ].join('') }; transporter.sendMail(mailOptions, function(err) { if (err) { return done(err); } req.flash('info', { msg: 'An e-mail has been sent to ' + user.email + ' with further instructions.' }); done(null, 'done'); }); } ], function(err) { if (err) { return next(err); } res.redirect('/forgot'); }); };
controllers/user.js
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/9b8a7cdd496c0aa8ef0d9ffd84289b8e6b237dcd
[ 0.015093637630343437, 0.0009544710046611726, 0.00016200363461393863, 0.00017165939789265394, 0.0023768132086843252 ]
{ "id": 0, "code_window": [ " var solutionLink = req.body.challengeInfo.publicURL;\n", " var githubLink = req.body.challengeInfo.challengeType === '4'\n", " ? req.body.challengeInfo.githubURL : true;\n", " if (!solutionLink || !githubLink) {\n", " req.flash('errors', {\n", " msg: 'You haven\\'t supplied the necessary URLs for us to inspect ' +\n", " 'your work.'\n", " });\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " var challengeType = req.body.challengeInfo.challengeType === '4' ?\n", " 4 : 3;\n" ], "file_path": "controllers/challenge.js", "type": "add", "edit_start_line_idx": 459 }
var http = require('http'), URL = require('url'), HtmlToDom = require('./htmltodom').HtmlToDom, domToHtml = require('./domtohtml').domToHtml, htmlencoding = require('./htmlencoding'), HTMLEncode = htmlencoding.HTMLEncode, HTMLDecode = htmlencoding.HTMLDecode, jsdom = require('../../jsdom'), Location = require('./location'), History = require('./history'), NOT_IMPLEMENTED = require('./utils').NOT_IMPLEMENTED, CSSStyleDeclaration = require('cssstyle').CSSStyleDeclaration, toFileUrl = require('../utils').toFileUrl, defineGetter = require('../utils').defineGetter, defineSetter = require('../utils').defineSetter, createFrom = require('../utils').createFrom, Contextify = require('contextify'); function matchesDontThrow(el, selector) { try { return el.matchesSelector(selector); } catch (e) { return false; } } /** * Creates a window having a document. The document can be passed as option, * if omitted, a new document will be created. */ exports.windowAugmentation = function(dom, options) { options = options || {}; var window = exports.createWindow(dom, options); if (!options.document) { var browser = browserAugmentation(dom, options); options.document = (browser.HTMLDocument) ? new browser.HTMLDocument(options) : new browser.Document(options); options.document.write('<html><head></head><body></body></html>'); } var doc = window.document = options.document; if (doc.addEventListener) { if (doc.readyState == 'complete') { var ev = doc.createEvent('HTMLEvents'); ev.initEvent('load', false, false); process.nextTick(function () { window.dispatchEvent(ev); }); } else { doc.addEventListener('load', function(ev) { window.dispatchEvent(ev); }); } } return window; }; /** * Creates a document-less window. */ exports.createWindow = function(dom, options) { var timers = []; var cssSelectorSplitRE = /((?:[^,"']|"[^"]*"|'[^']*')+)/; function startTimer(startFn, stopFn, callback, ms) { var res = startFn(callback, ms); timers.push( [ res, stopFn ] ); return res; } function stopTimer(id) { if (typeof id === 'undefined') { return; } for (var i in timers) { if (timers[i][0] === id) { timers[i][1].call(this, id); timers.splice(i, 1); break; } } } function stopAllTimers() { timers.forEach(function (t) { t[1].call(this, t[0]); }); timers = []; } function DOMWindow(options) { var url = (options || {}).url || toFileUrl(__filename); this.location = new Location(url, this); this.history = new History(this); this.console._window = this; if (options && options.document) { options.document.location = this.location; } this.addEventListener = function() { dom.Node.prototype.addEventListener.apply(window, arguments); }; this.removeEventListener = function() { dom.Node.prototype.removeEventListener.apply(window, arguments); }; this.dispatchEvent = function() { dom.Node.prototype.dispatchEvent.apply(window, arguments); }; this.raise = function(){ dom.Node.prototype.raise.apply(window.document, arguments); }; this.setTimeout = function (fn, ms) { return startTimer(setTimeout, clearTimeout, fn, ms); }; this.setInterval = function (fn, ms) { return startTimer(setInterval, clearInterval, fn, ms); }; this.clearInterval = stopTimer; this.clearTimeout = stopTimer; this.__stopAllTimers = stopAllTimers; } DOMWindow.prototype = createFrom(dom || null, { constructor: DOMWindow, // This implements window.frames.length, since window.frames returns a // self reference to the window object. This value is incremented in the // HTMLFrameElement init function (see: level2/html.js). _length : 0, get length () { return this._length; }, close : function() { // Recursively close child frame windows, then ourselves. var currentWindow = this; (function windowCleaner (window) { var i; // We could call window.frames.length etc, but window.frames just points // back to window. if (window.length > 0) { for (i = 0; i < window.length; i++) { windowCleaner(window[i]); } } // We're already in our own window.close(). if (window !== currentWindow) { window.close(); } })(this); if (this.document) { if (this.document.body) { this.document.body.innerHTML = ""; } if (this.document.close) { // We need to empty out the event listener array because // document.close() causes 'load' event to re-fire. this.document._listeners = []; this.document.close(); } delete this.document; } stopAllTimers(); // Clean up the window's execution context. // dispose() is added by Contextify. this.dispose(); }, getComputedStyle: function(node) { var s = node.style, cs = new CSSStyleDeclaration(), forEach = Array.prototype.forEach; function setPropertiesFromRule(rule) { if (!rule.selectorText) { return; } var selectors = rule.selectorText.split(cssSelectorSplitRE); var matched = false; selectors.forEach(function (selectorText) { if (selectorText !== '' && selectorText !== ',' && !matched && matchesDontThrow(node, selectorText)) { matched = true; forEach.call(rule.style, function (property) { cs.setProperty(property, rule.style.getPropertyValue(property), rule.style.getPropertyPriority(property)); }); } }); } forEach.call(node.ownerDocument.styleSheets, function (sheet) { forEach.call(sheet.cssRules, function (rule) { if (rule.media) { if (Array.prototype.indexOf.call(rule.media, 'screen') !== -1) { forEach.call(rule.cssRules, setPropertiesFromRule); } } else { setPropertiesFromRule(rule); } }); }); forEach.call(s, function (property) { cs.setProperty(property, s.getPropertyValue(property), s.getPropertyPriority(property)); }); return cs; }, console: { log: function(message) { this._window.raise('log', message) }, info: function(message) { this._window.raise('info', message) }, warn: function(message) { this._window.raise('warn', message) }, error: function(message) { this._window.raise('error', message) } }, navigator: { userAgent: 'Node.js (' + process.platform + '; U; rv:' + process.version + ')', appName: 'Node.js jsDom', platform: process.platform, appVersion: process.version, noUI: true }, XMLHttpRequest: function() { var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; var xhr = new XMLHttpRequest(); var lastUrl = ''; xhr._open = xhr.open; xhr.open = function(method, url, async, user, password) { url = URL.resolve(options.url, url); lastUrl = url; return xhr._open(method, url, async, user, password); }; xhr._send = xhr.send; xhr.send = function(data) { if (window.document.cookie) { var cookieDomain = window.document._cookieDomain; var url = URL.parse(lastUrl); var host = url.host.split(':')[0]; if (host.indexOf(cookieDomain, host.length - cookieDomain.length) !== -1) { xhr.setDisableHeaderCheck(true); xhr.setRequestHeader('cookie', window.document.cookie); xhr.setDisableHeaderCheck(false); } } return xhr._send(data); }; return xhr; }, name: 'nodejs', innerWidth: 1024, innerHeight: 768, outerWidth: 1024, outerHeight: 768, pageXOffset: 0, pageYOffset: 0, screenX: 0, screenY: 0, screenLeft: 0, screenTop: 0, scrollX: 0, scrollY: 0, scrollTop: 0, scrollLeft: 0, alert: NOT_IMPLEMENTED(null, 'window.alert'), blur: NOT_IMPLEMENTED(null, 'window.blur'), confirm: NOT_IMPLEMENTED(null, 'window.confirm'), createPopup: NOT_IMPLEMENTED(null, 'window.createPopup'), focus: NOT_IMPLEMENTED(null, 'window.focus'), moveBy: NOT_IMPLEMENTED(null, 'window.moveBy'), moveTo: NOT_IMPLEMENTED(null, 'window.moveTo'), open: NOT_IMPLEMENTED(null, 'window.open'), print: NOT_IMPLEMENTED(null, 'window.print'), prompt: NOT_IMPLEMENTED(null, 'window.prompt'), resizeBy: NOT_IMPLEMENTED(null, 'window.resizeBy'), resizeTo: NOT_IMPLEMENTED(null, 'window.resizeTo'), scroll: NOT_IMPLEMENTED(null, 'window.scroll'), scrollBy: NOT_IMPLEMENTED(null, 'window.scrollBy'), scrollTo: NOT_IMPLEMENTED(null, 'window.scrollTo'), screen : { width : 0, height : 0 }, Image : NOT_IMPLEMENTED(null, 'window.Image'), // Note: these will not be necessary for newer Node.js versions, which have // typed arrays in V8 and thus on every global object. (That is, in newer // versions we'll get `ArrayBuffer` just as automatically as we get // `Array`.) But to support older versions, we explicitly set them here. Int8Array: global.Int8Array, Int16Array: global.Int16Array, Int32Array: global.Int32Array, Float32Array: global.Float32Array, Float64Array: global.Float64Array, Uint8Array: global.Uint8Array, Uint8ClampedArray: global.Uint8ClampedArray, Uint16Array: global.Uint16Array, Uint32Array: global.Uint32Array, ArrayBuffer: global.ArrayBuffer }); var window = new DOMWindow(options); Contextify(window); // We need to set up self references using Contextify's getGlobal() so that // the global object identity is correct (window === this). // See Contextify README for more info. var windowGlobal = window.getGlobal(); // Set up the window as if it's a top level window. // If it's not, then references will be corrected by frame/iframe code. // Note: window.frames is maintained in the HTMLFrameElement init function. window.window = window.frames = window.self = window.parent = window.top = windowGlobal; return window; }; //Caching for HTMLParser require. HUGE performace boost. /** * 5000 iterations * Without cache: ~1800+ms * With cache: ~80ms */ // TODO: is this even needed in modern Node.js versions? var defaultParser = null; var getDefaultParser = exports.getDefaultParser = function () { if (defaultParser === null) { defaultParser = require('htmlparser2'); } return defaultParser; } /** * Export getter/setter of default parser to facilitate testing * with different HTML parsers. */ exports.setDefaultParser = function (parser) { if (typeof parser == 'object') { defaultParser = parser; } else if (typeof parser == 'string') defaultParser = require(parser); } /** * Augments the given DOM by adding browser-specific properties and methods (BOM). * Returns the augmented DOM. */ var browserAugmentation = exports.browserAugmentation = function(dom, options) { if(!options) { options = {}; } // set up html parser - use a provided one or try and load from library var parser = options.parser || getDefaultParser(); if (dom._augmented && dom._parser === parser) { return dom; } dom._parser = parser; var htmltodom = new HtmlToDom(parser); if (!dom.HTMLDocument) { dom.HTMLDocument = dom.Document; } if (!dom.HTMLDocument.prototype.write) { dom.HTMLDocument.prototype.write = function(html) { this.innerHTML = html; }; } dom.Element.prototype.getElementsByClassName = function(className) { function filterByClassName(child) { if (!child) { return false; } if (child.nodeType && child.nodeType === dom.Node.ENTITY_REFERENCE_NODE) { child = child._entity; } var classString = child.className; if (classString) { var s = classString.split(" "); for (var i=0; i<s.length; i++) { if (s[i] === className) { return true; } } } return false; } return new dom.NodeList(this.ownerDocument || this, dom.mapper(this, filterByClassName)); }; defineGetter(dom.Element.prototype, 'sourceIndex', function() { /* * According to QuirksMode: * Get the sourceIndex of element x. This is also the index number for * the element in the document.getElementsByTagName('*') array. * http://www.quirksmode.org/dom/w3c_core.html#t77 */ var items = this.ownerDocument.getElementsByTagName('*'), len = items.length; for (var i = 0; i < len; i++) { if (items[i] === this) { return i; } } }); defineGetter(dom.Document.prototype, 'outerHTML', function() { return domToHtml(this, true); }); defineGetter(dom.Element.prototype, 'outerHTML', function() { return domToHtml(this, true); }); defineGetter(dom.Element.prototype, 'innerHTML', function() { if (/^(?:script|style)$/.test(this._tagName)) { var type = this.getAttribute('type'); if (!type || /^text\//i.test(type) || /\/javascript$/i.test(type)) { return domToHtml(this._childNodes, true, true); } } return domToHtml(this._childNodes, true); }); defineSetter(dom.Element.prototype, 'doctype', function() { throw new dom.DOMException(dom.NO_MODIFICATION_ALLOWED_ERR); }); defineGetter(dom.Element.prototype, 'doctype', function() { var r = null; if (this.nodeName == '#document') { if (this._doctype) { r = this._doctype; } } return r; }); defineSetter(dom.Element.prototype, 'innerHTML', function(html) { //Clear the children first: var child; while ((child = this._childNodes[0])) { this.removeChild(child); } if (this.nodeName === '#document') { parseDocType(this, html); } if (html !== "" && html != null) { htmltodom.appendHtmlToElement(html, this); } return html; }); defineGetter(dom.Document.prototype, 'innerHTML', function() { return domToHtml(this._childNodes, true); }); defineSetter(dom.Document.prototype, 'innerHTML', function(html) { //Clear the children first: var child; while ((child = this._childNodes[0])) { this.removeChild(child); } if (this.nodeName === '#document') { parseDocType(this, html); } if (html !== "" && html != null) { htmltodom.appendHtmlToElement(html, this); } return html; }); var DOC_HTML5 = /<!doctype html>/i, DOC_TYPE = /<!DOCTYPE (\w(.|\n)*)">/i, DOC_TYPE_START = '<!DOCTYPE ', DOC_TYPE_END = '">'; function parseDocType(doc, html) { var publicID = '', systemID = '', fullDT = '', name = 'HTML', set = true, doctype = html.match(DOC_HTML5); //Default, No doctype === null doc._doctype = null; if (doctype && doctype[0]) { //Handle the HTML shorty doctype fullDT = doctype[0]; } else { //Parse the doctype // find the start var start = html.indexOf(DOC_TYPE_START), end = html.indexOf(DOC_TYPE_END), docString; if (start < 0 || end < 0) { return; } docString = html.substr(start, (end-start)+DOC_TYPE_END.length); doctype = docString.replace(/[\n\r]/g,'').match(DOC_TYPE); if (!doctype) { return; } fullDT = doctype[0]; doctype = doctype[1].split(' "'); var _id1 = doctype.length ? doctype.pop().replace(/"/g, '') : '', _id2 = doctype.length ? doctype.pop().replace(/"/g, '') : ''; if (_id1.indexOf('-//') !== -1) { publicID = _id1; } if (_id2.indexOf('-//') !== -1) { publicID = _id2; } if (_id1.indexOf('://') !== -1) { systemID = _id1; } if (_id2.indexOf('://') !== -1) { systemID = _id2; } if (doctype.length) { doctype = doctype[0].split(' '); name = doctype[0].toUpperCase(); } } doc._doctype = new dom.DOMImplementation().createDocumentType(name, publicID, systemID); doc._doctype._ownerDocument = doc; doc._doctype._fullDT = fullDT; doc._doctype.toString = function() { return this._fullDT; }; } dom.Document.prototype.getElementsByClassName = function(className) { function filterByClassName(child) { if (!child) { return false; } if (child.nodeType && child.nodeType === dom.Node.ENTITY_REFERENCE_NODE) { child = child._entity; } var classString = child.className; if (classString) { var s = classString.split(" "); for (var i=0; i<s.length; i++) { if (s[i] === className) { return true; } } } return false; } return new dom.NodeList(this.ownerDocument || this, dom.mapper(this, filterByClassName)); }; defineGetter(dom.Element.prototype, 'nodeName', function(val) { return this._nodeName.toUpperCase(); }); defineGetter(dom.Element.prototype, 'tagName', function(val) { var t = this._tagName.toUpperCase(); //Document should not return a tagName if (this.nodeName === '#document') { t = null; } return t; }); dom.Element.prototype.scrollTop = 0; dom.Element.prototype.scrollLeft = 0; defineGetter(dom.Document.prototype, 'parentWindow', function() { if (!this._parentWindow) { this.parentWindow = exports.windowAugmentation(dom, {document: this, url: this.URL}); } return this._parentWindow; }); defineSetter(dom.Document.prototype, 'parentWindow', function(window) { // Contextify does not support getters and setters, so we have to set them // on the original object instead. window._frame = function (name, frame) { if (typeof frame === 'undefined') { delete window[name]; } else { defineGetter(window, name, function () { return frame.contentWindow; }); } }; this._parentWindow = window.getGlobal(); }); defineGetter(dom.Document.prototype, 'defaultView', function() { return this.parentWindow; }); dom._augmented = true; return dom; };
bower_components/jsdom/lib/jsdom/browser/index.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/9b8a7cdd496c0aa8ef0d9ffd84289b8e6b237dcd
[ 0.00028775306418538094, 0.00017474457854405046, 0.00016625612624920905, 0.00017191462393384427, 0.00001592040825926233 ]
{ "id": 0, "code_window": [ " var solutionLink = req.body.challengeInfo.publicURL;\n", " var githubLink = req.body.challengeInfo.challengeType === '4'\n", " ? req.body.challengeInfo.githubURL : true;\n", " if (!solutionLink || !githubLink) {\n", " req.flash('errors', {\n", " msg: 'You haven\\'t supplied the necessary URLs for us to inspect ' +\n", " 'your work.'\n", " });\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " var challengeType = req.body.challengeInfo.challengeType === '4' ?\n", " 4 : 3;\n" ], "file_path": "controllers/challenge.js", "type": "add", "edit_start_line_idx": 459 }
<!doctype html> <title>CodeMirror: LESS mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="../../addon/edit/matchbrackets.js"></script> <script src="css.js"></script> <style>.CodeMirror {border: 1px solid #ddd; line-height: 1.2;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">LESS</a> </ul> </div> <article> <h2>LESS mode</h2> <form><textarea id="code" name="code">@media screen and (device-aspect-ratio: 16/9) { … } @media screen and (device-aspect-ratio: 1280/720) { … } @media screen and (device-aspect-ratio: 2560/1440) { … } html:lang(fr-be) tr:nth-child(2n+1) /* represents every odd row of an HTML table */ img:nth-of-type(2n+1) { float: right; } img:nth-of-type(2n) { float: left; } body > h2:not(:first-of-type):not(:last-of-type) html|*:not(:link):not(:visited) *|*:not(:hover) p::first-line { text-transform: uppercase } @namespace foo url(http://www.example.com); foo|h1 { color: blue } /* first rule */ span[hello="Ocean"][goodbye="Land"] E[foo]{ padding:65px; } input[type="search"]::-webkit-search-decoration, input[type="search"]::-webkit-search-cancel-button { -webkit-appearance: none; // Inner-padding issues in Chrome OSX, Safari 5 } button::-moz-focus-inner, input::-moz-focus-inner { // Inner padding and border oddities in FF3/4 padding: 0; border: 0; } .btn { // reset here as of 2.0.3 due to Recess property order border-color: #ccc; border-color: rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25); } fieldset span button, fieldset span input[type="file"] { font-size:12px; font-family:Arial, Helvetica, sans-serif; } .rounded-corners (@radius: 5px) { border-radius: @radius; -webkit-border-radius: @radius; -moz-border-radius: @radius; } @import url("something.css"); @light-blue: hsl(190, 50%, 65%); #menu { position: absolute; width: 100%; z-index: 3; clear: both; display: block; background-color: @blue; height: 42px; border-top: 2px solid lighten(@alpha-blue, 20%); border-bottom: 2px solid darken(@alpha-blue, 25%); .box-shadow(0, 1px, 8px, 0.6); -moz-box-shadow: 0 0 0 #000; // Because firefox sucks. &.docked { background-color: hsla(210, 60%, 40%, 0.4); } &:hover { background-color: @blue; } #dropdown { margin: 0 0 0 117px; padding: 0; padding-top: 5px; display: none; width: 190px; border-top: 2px solid @medium; color: @highlight; border: 2px solid darken(@medium, 25%); border-left-color: darken(@medium, 15%); border-right-color: darken(@medium, 15%); border-top-width: 0; background-color: darken(@medium, 10%); ul { padding: 0px; } li { font-size: 14px; display: block; text-align: left; padding: 0; border: 0; a { display: block; padding: 0px 15px; text-decoration: none; color: white; &:hover { background-color: darken(@medium, 15%); text-decoration: none; } } } .border-radius(5px, bottom); .box-shadow(0, 6px, 8px, 0.5); } } </textarea></form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers : true, matchBrackets : true, mode: "text/x-less" }); </script> <p>The LESS mode is a sub-mode of the <a href="index.html">CSS mode</a> (defined in <code>css.js</code>.</p> <p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#less_*">normal</a>, <a href="../../test/index.html#verbose,less_*">verbose</a>.</p> </article>
public/js/lib/codemirror/mode/css/less.html
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/9b8a7cdd496c0aa8ef0d9ffd84289b8e6b237dcd
[ 0.00017828457930590957, 0.00017370269051752985, 0.00017039832891896367, 0.00017299529281444848, 0.0000024449691409245133 ]
{ "id": 0, "code_window": [ " var solutionLink = req.body.challengeInfo.publicURL;\n", " var githubLink = req.body.challengeInfo.challengeType === '4'\n", " ? req.body.challengeInfo.githubURL : true;\n", " if (!solutionLink || !githubLink) {\n", " req.flash('errors', {\n", " msg: 'You haven\\'t supplied the necessary URLs for us to inspect ' +\n", " 'your work.'\n", " });\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " var challengeType = req.body.challengeInfo.challengeType === '4' ?\n", " 4 : 3;\n" ], "file_path": "controllers/challenge.js", "type": "add", "edit_start_line_idx": 459 }
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE // TODO actually recognize syntax of TypeScript constructs (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("javascript", function(config, parserConfig) { var indentUnit = config.indentUnit; var statementIndent = parserConfig.statementIndent; var jsonldMode = parserConfig.jsonld; var jsonMode = parserConfig.json || jsonldMode; var isTS = parserConfig.typescript; var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; // Tokenizer var keywords = function(){ function kw(type) {return {type: type, style: "keyword"};} var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"); var operator = kw("operator"), atom = {type: "atom", style: "atom"}; var jsKeywords = { "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, "return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C, "debugger": C, "var": kw("var"), "const": kw("var"), "let": kw("var"), "function": kw("function"), "catch": kw("catch"), "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), "in": operator, "typeof": operator, "instanceof": operator, "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom, "this": kw("this"), "module": kw("module"), "class": kw("class"), "super": kw("atom"), "yield": C, "export": kw("export"), "import": kw("import"), "extends": C }; // Extend the 'normal' keywords with the TypeScript language extensions if (isTS) { var type = {type: "variable", style: "variable-3"}; var tsKeywords = { // object-like things "interface": kw("interface"), "extends": kw("extends"), "constructor": kw("constructor"), // scope modifiers "public": kw("public"), "private": kw("private"), "protected": kw("protected"), "static": kw("static"), // types "string": type, "number": type, "bool": type, "any": type }; for (var attr in tsKeywords) { jsKeywords[attr] = tsKeywords[attr]; } } return jsKeywords; }(); var isOperatorChar = /[+\-*&%=<>!?|~^]/; var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; function readRegexp(stream) { var escaped = false, next, inSet = false; while ((next = stream.next()) != null) { if (!escaped) { if (next == "/" && !inSet) return; if (next == "[") inSet = true; else if (inSet && next == "]") inSet = false; } escaped = !escaped && next == "\\"; } } // Used as scratch variables to communicate multiple values without // consing up tons of objects. var type, content; function ret(tp, style, cont) { type = tp; content = cont; return style; } function tokenBase(stream, state) { var ch = stream.next(); if (ch == '"' || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) { return ret("number", "number"); } else if (ch == "." && stream.match("..")) { return ret("spread", "meta"); } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { return ret(ch); } else if (ch == "=" && stream.eat(">")) { return ret("=>", "operator"); } else if (ch == "0" && stream.eat(/x/i)) { stream.eatWhile(/[\da-f]/i); return ret("number", "number"); } else if (/\d/.test(ch)) { stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/); return ret("number", "number"); } else if (ch == "/") { if (stream.eat("*")) { state.tokenize = tokenComment; return tokenComment(stream, state); } else if (stream.eat("/")) { stream.skipToEnd(); return ret("comment", "comment"); } else if (state.lastType == "operator" || state.lastType == "keyword c" || state.lastType == "sof" || /^[\[{}\(,;:]$/.test(state.lastType)) { readRegexp(stream); stream.eatWhile(/[gimy]/); // 'y' is "sticky" option in Mozilla return ret("regexp", "string-2"); } else { stream.eatWhile(isOperatorChar); return ret("operator", "operator", stream.current()); } } else if (ch == "`") { state.tokenize = tokenQuasi; return tokenQuasi(stream, state); } else if (ch == "#") { stream.skipToEnd(); return ret("error", "error"); } else if (isOperatorChar.test(ch)) { stream.eatWhile(isOperatorChar); return ret("operator", "operator", stream.current()); } else if (wordRE.test(ch)) { stream.eatWhile(wordRE); var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word]; return (known && state.lastType != ".") ? ret(known.type, known.style, word) : ret("variable", "variable", word); } } function tokenString(quote) { return function(stream, state) { var escaped = false, next; if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){ state.tokenize = tokenBase; return ret("jsonld-keyword", "meta"); } while ((next = stream.next()) != null) { if (next == quote && !escaped) break; escaped = !escaped && next == "\\"; } if (!escaped) state.tokenize = tokenBase; return ret("string", "string"); }; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = tokenBase; break; } maybeEnd = (ch == "*"); } return ret("comment", "comment"); } function tokenQuasi(stream, state) { var escaped = false, next; while ((next = stream.next()) != null) { if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { state.tokenize = tokenBase; break; } escaped = !escaped && next == "\\"; } return ret("quasi", "string-2", stream.current()); } var brackets = "([{}])"; // This is a crude lookahead trick to try and notice that we're // parsing the argument patterns for a fat-arrow function before we // actually hit the arrow token. It only works if the arrow is on // the same line as the arguments and there's no strange noise // (comments) in between. Fallback is to only notice when we hit the // arrow, and not declare the arguments as locals for the arrow // body. function findFatArrow(stream, state) { if (state.fatArrowAt) state.fatArrowAt = null; var arrow = stream.string.indexOf("=>", stream.start); if (arrow < 0) return; var depth = 0, sawSomething = false; for (var pos = arrow - 1; pos >= 0; --pos) { var ch = stream.string.charAt(pos); var bracket = brackets.indexOf(ch); if (bracket >= 0 && bracket < 3) { if (!depth) { ++pos; break; } if (--depth == 0) break; } else if (bracket >= 3 && bracket < 6) { ++depth; } else if (wordRE.test(ch)) { sawSomething = true; } else if (/["'\/]/.test(ch)) { return; } else if (sawSomething && !depth) { ++pos; break; } } if (sawSomething && !depth) state.fatArrowAt = pos; } // Parser var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true}; function JSLexical(indented, column, type, align, prev, info) { this.indented = indented; this.column = column; this.type = type; this.prev = prev; this.info = info; if (align != null) this.align = align; } function inScope(state, varname) { for (var v = state.localVars; v; v = v.next) if (v.name == varname) return true; for (var cx = state.context; cx; cx = cx.prev) { for (var v = cx.vars; v; v = v.next) if (v.name == varname) return true; } } function parseJS(state, style, type, content, stream) { var cc = state.cc; // Communicate our context to the combinators. // (Less wasteful than consing up a hundred closures on every call.) cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style; if (!state.lexical.hasOwnProperty("align")) state.lexical.align = true; while(true) { var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; if (combinator(type, content)) { while(cc.length && cc[cc.length - 1].lex) cc.pop()(); if (cx.marked) return cx.marked; if (type == "variable" && inScope(state, content)) return "variable-2"; return style; } } } // Combinator utils var cx = {state: null, column: null, marked: null, cc: null}; function pass() { for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); } function cont() { pass.apply(null, arguments); return true; } function register(varname) { function inList(list) { for (var v = list; v; v = v.next) if (v.name == varname) return true; return false; } var state = cx.state; if (state.context) { cx.marked = "def"; if (inList(state.localVars)) return; state.localVars = {name: varname, next: state.localVars}; } else { if (inList(state.globalVars)) return; if (parserConfig.globalVars) state.globalVars = {name: varname, next: state.globalVars}; } } // Combinators var defaultVars = {name: "this", next: {name: "arguments"}}; function pushcontext() { cx.state.context = {prev: cx.state.context, vars: cx.state.localVars}; cx.state.localVars = defaultVars; } function popcontext() { cx.state.localVars = cx.state.context.vars; cx.state.context = cx.state.context.prev; } function pushlex(type, info) { var result = function() { var state = cx.state, indent = state.indented; if (state.lexical.type == "stat") indent = state.lexical.indented; else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) indent = outer.indented; state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info); }; result.lex = true; return result; } function poplex() { var state = cx.state; if (state.lexical.prev) { if (state.lexical.type == ")") state.indented = state.lexical.indented; state.lexical = state.lexical.prev; } } poplex.lex = true; function expect(wanted) { function exp(type) { if (type == wanted) return cont(); else if (wanted == ";") return pass(); else return cont(exp); }; return exp; } function statement(type, value) { if (type == "var") return cont(pushlex("vardef", value.length), vardef, expect(";"), poplex); if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex); if (type == "keyword b") return cont(pushlex("form"), statement, poplex); if (type == "{") return cont(pushlex("}"), block, poplex); if (type == ";") return cont(); if (type == "if") { if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) cx.state.cc.pop()(); return cont(pushlex("form"), expression, statement, poplex, maybeelse); } if (type == "function") return cont(functiondef); if (type == "for") return cont(pushlex("form"), forspec, statement, poplex); if (type == "variable") return cont(pushlex("stat"), maybelabel); if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), block, poplex, poplex); if (type == "case") return cont(expression, expect(":")); if (type == "default") return cont(expect(":")); if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), statement, poplex, popcontext); if (type == "module") return cont(pushlex("form"), pushcontext, afterModule, popcontext, poplex); if (type == "class") return cont(pushlex("form"), className, poplex); if (type == "export") return cont(pushlex("form"), afterExport, poplex); if (type == "import") return cont(pushlex("form"), afterImport, poplex); return pass(pushlex("stat"), expression, expect(";"), poplex); } function expression(type) { return expressionInner(type, false); } function expressionNoComma(type) { return expressionInner(type, true); } function expressionInner(type, noComma) { if (cx.state.fatArrowAt == cx.stream.start) { var body = noComma ? arrowBodyNoComma : arrowBody; if (type == "(") return cont(pushcontext, pushlex(")"), commasep(pattern, ")"), poplex, expect("=>"), body, popcontext); else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); } var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); if (type == "function") return cont(functiondef, maybeop); if (type == "keyword c") return cont(noComma ? maybeexpressionNoComma : maybeexpression); if (type == "(") return cont(pushlex(")"), maybeexpression, comprehension, expect(")"), poplex, maybeop); if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression); if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); if (type == "{") return contCommasep(objprop, "}", null, maybeop); if (type == "quasi") { return pass(quasi, maybeop); } return cont(); } function maybeexpression(type) { if (type.match(/[;\}\)\],]/)) return pass(); return pass(expression); } function maybeexpressionNoComma(type) { if (type.match(/[;\}\)\],]/)) return pass(); return pass(expressionNoComma); } function maybeoperatorComma(type, value) { if (type == ",") return cont(expression); return maybeoperatorNoComma(type, value, false); } function maybeoperatorNoComma(type, value, noComma) { var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; var expr = noComma == false ? expression : expressionNoComma; if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); if (type == "operator") { if (/\+\+|--/.test(value)) return cont(me); if (value == "?") return cont(expression, expect(":"), expr); return cont(expr); } if (type == "quasi") { return pass(quasi, me); } if (type == ";") return; if (type == "(") return contCommasep(expressionNoComma, ")", "call", me); if (type == ".") return cont(property, me); if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); } function quasi(type, value) { if (type != "quasi") return pass(); if (value.slice(value.length - 2) != "${") return cont(quasi); return cont(expression, continueQuasi); } function continueQuasi(type) { if (type == "}") { cx.marked = "string-2"; cx.state.tokenize = tokenQuasi; return cont(quasi); } } function arrowBody(type) { findFatArrow(cx.stream, cx.state); return pass(type == "{" ? statement : expression); } function arrowBodyNoComma(type) { findFatArrow(cx.stream, cx.state); return pass(type == "{" ? statement : expressionNoComma); } function maybelabel(type) { if (type == ":") return cont(poplex, statement); return pass(maybeoperatorComma, expect(";"), poplex); } function property(type) { if (type == "variable") {cx.marked = "property"; return cont();} } function objprop(type, value) { if (type == "variable" || cx.style == "keyword") { cx.marked = "property"; if (value == "get" || value == "set") return cont(getterSetter); return cont(afterprop); } else if (type == "number" || type == "string") { cx.marked = jsonldMode ? "property" : (cx.style + " property"); return cont(afterprop); } else if (type == "jsonld-keyword") { return cont(afterprop); } else if (type == "[") { return cont(expression, expect("]"), afterprop); } } function getterSetter(type) { if (type != "variable") return pass(afterprop); cx.marked = "property"; return cont(functiondef); } function afterprop(type) { if (type == ":") return cont(expressionNoComma); if (type == "(") return pass(functiondef); } function commasep(what, end) { function proceed(type) { if (type == ",") { var lex = cx.state.lexical; if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; return cont(what, proceed); } if (type == end) return cont(); return cont(expect(end)); } return function(type) { if (type == end) return cont(); return pass(what, proceed); }; } function contCommasep(what, end, info) { for (var i = 3; i < arguments.length; i++) cx.cc.push(arguments[i]); return cont(pushlex(end, info), commasep(what, end), poplex); } function block(type) { if (type == "}") return cont(); return pass(statement, block); } function maybetype(type) { if (isTS && type == ":") return cont(typedef); } function typedef(type) { if (type == "variable"){cx.marked = "variable-3"; return cont();} } function vardef() { return pass(pattern, maybetype, maybeAssign, vardefCont); } function pattern(type, value) { if (type == "variable") { register(value); return cont(); } if (type == "[") return contCommasep(pattern, "]"); if (type == "{") return contCommasep(proppattern, "}"); } function proppattern(type, value) { if (type == "variable" && !cx.stream.match(/^\s*:/, false)) { register(value); return cont(maybeAssign); } if (type == "variable") cx.marked = "property"; return cont(expect(":"), pattern, maybeAssign); } function maybeAssign(_type, value) { if (value == "=") return cont(expressionNoComma); } function vardefCont(type) { if (type == ",") return cont(vardef); } function maybeelse(type, value) { if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); } function forspec(type) { if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex); } function forspec1(type) { if (type == "var") return cont(vardef, expect(";"), forspec2); if (type == ";") return cont(forspec2); if (type == "variable") return cont(formaybeinof); return pass(expression, expect(";"), forspec2); } function formaybeinof(_type, value) { if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); } return cont(maybeoperatorComma, forspec2); } function forspec2(type, value) { if (type == ";") return cont(forspec3); if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); } return pass(expression, expect(";"), forspec3); } function forspec3(type) { if (type != ")") cont(expression); } function functiondef(type, value) { if (value == "*") {cx.marked = "keyword"; return cont(functiondef);} if (type == "variable") {register(value); return cont(functiondef);} if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, statement, popcontext); } function funarg(type) { if (type == "spread") return cont(funarg); return pass(pattern, maybetype); } function className(type, value) { if (type == "variable") {register(value); return cont(classNameAfter);} } function classNameAfter(type, value) { if (value == "extends") return cont(expression, classNameAfter); if (type == "{") return cont(pushlex("}"), classBody, poplex); } function classBody(type, value) { if (type == "variable" || cx.style == "keyword") { cx.marked = "property"; if (value == "get" || value == "set") return cont(classGetterSetter, functiondef, classBody); return cont(functiondef, classBody); } if (value == "*") { cx.marked = "keyword"; return cont(classBody); } if (type == ";") return cont(classBody); if (type == "}") return cont(); } function classGetterSetter(type) { if (type != "variable") return pass(); cx.marked = "property"; return cont(); } function afterModule(type, value) { if (type == "string") return cont(statement); if (type == "variable") { register(value); return cont(maybeFrom); } } function afterExport(_type, value) { if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); } if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); } return pass(statement); } function afterImport(type) { if (type == "string") return cont(); return pass(importSpec, maybeFrom); } function importSpec(type, value) { if (type == "{") return contCommasep(importSpec, "}"); if (type == "variable") register(value); return cont(); } function maybeFrom(_type, value) { if (value == "from") { cx.marked = "keyword"; return cont(expression); } } function arrayLiteral(type) { if (type == "]") return cont(); return pass(expressionNoComma, maybeArrayComprehension); } function maybeArrayComprehension(type) { if (type == "for") return pass(comprehension, expect("]")); if (type == ",") return cont(commasep(maybeexpressionNoComma, "]")); return pass(commasep(expressionNoComma, "]")); } function comprehension(type) { if (type == "for") return cont(forspec, comprehension); if (type == "if") return cont(expression, comprehension); } // Interface return { startState: function(basecolumn) { var state = { tokenize: tokenBase, lastType: "sof", cc: [], lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), localVars: parserConfig.localVars, context: parserConfig.localVars && {vars: parserConfig.localVars}, indented: 0 }; if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") state.globalVars = parserConfig.globalVars; return state; }, token: function(stream, state) { if (stream.sol()) { if (!state.lexical.hasOwnProperty("align")) state.lexical.align = false; state.indented = stream.indentation(); findFatArrow(stream, state); } if (state.tokenize != tokenComment && stream.eatSpace()) return null; var style = state.tokenize(stream, state); if (type == "comment") return style; state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; return parseJS(state, style, type, content, stream); }, indent: function(state, textAfter) { if (state.tokenize == tokenComment) return CodeMirror.Pass; if (state.tokenize != tokenBase) return 0; var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical; // Kludge to prevent 'maybelse' from blocking lexical scope pops if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { var c = state.cc[i]; if (c == poplex) lexical = lexical.prev; else if (c != maybeelse) break; } if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev; if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") lexical = lexical.prev; var type = lexical.type, closing = firstChar == type; if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info + 1 : 0); else if (type == "form" && firstChar == "{") return lexical.indented; else if (type == "form") return lexical.indented + indentUnit; else if (type == "stat") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? statementIndent || indentUnit : 0); else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); else if (lexical.align) return lexical.column + (closing ? 0 : 1); else return lexical.indented + (closing ? 0 : indentUnit); }, electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, blockCommentStart: jsonMode ? null : "/*", blockCommentEnd: jsonMode ? null : "*/", lineComment: jsonMode ? null : "//", fold: "brace", helperType: jsonMode ? "json" : "javascript", jsonldMode: jsonldMode, jsonMode: jsonMode }; }); CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); CodeMirror.defineMIME("text/javascript", "javascript"); CodeMirror.defineMIME("text/ecmascript", "javascript"); CodeMirror.defineMIME("application/javascript", "javascript"); CodeMirror.defineMIME("application/x-javascript", "javascript"); CodeMirror.defineMIME("application/ecmascript", "javascript"); CodeMirror.defineMIME("application/json", {name: "javascript", json: true}); CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true}); CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true}); CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); });
public/js/lib/codemirror/mode/javascript/javascript.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/9b8a7cdd496c0aa8ef0d9ffd84289b8e6b237dcd
[ 0.00038241673610173166, 0.00018186702800448984, 0.00016583087563049048, 0.00017480699170846492, 0.00003494167685857974 ]
{ "id": 1, "code_window": [ " completedWith: pairedWith._id,\n", " completedDate: isCompletedDate,\n", " solution: solutionLink,\n", " githubLink: githubLink,\n", " verified: false\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " challengeType: challengeType,\n" ], "file_path": "controllers/challenge.js", "type": "add", "edit_start_line_idx": 489 }
var _ = require('lodash'), async = require('async'), crypto = require('crypto'), nodemailer = require('nodemailer'), passport = require('passport'), User = require('../models/User'), secrets = require('../config/secrets'), moment = require('moment'), debug = require('debug')('freecc:cntr:userController'), resources = require('./resources'), R = require('ramda'); /** * * @param req * @param res * @returns null * Middleware to migrate users from fragmented challenge structure to unified * challenge structure */ exports.userMigration = function(req, res, next) { if (req.user && req.user.completedChallenges.length === 0) { req.user.completedChallenges = R.filter(function (elem) { return elem; // getting rid of undefined }, R.concat( req.user.completedCoursewares, req.user.completedBonfires.map(function (bonfire) { return ({ completedDate: bonfire.completedDate, _id: bonfire._id, name: bonfire.name, completedWith: bonfire.completedWith, solution: bonfire.solution, githubLink: '', verified: false, challengeType: 5 }); }) )); next(); } else { next(); } }; /** * GET /signin * Siginin page. */ exports.getSignin = function(req, res) { if (req.user) { return res.redirect('/'); } res.render('account/signin', { title: 'Free Code Camp Login' }); }; /** * POST /signin * Sign in using email and password. */ exports.postSignin = function(req, res, next) { req.assert('email', 'Email is not valid').isEmail(); req.assert('password', 'Password cannot be blank').notEmpty(); var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/signin'); } passport.authenticate('local', function(err, user, info) { if (err) { return next(err); } if (!user) { req.flash('errors', { msg: info.message }); return res.redirect('/signin'); } req.logIn(user, function(err) { if (err) { return next(err); } req.flash('success', { msg: 'Success! You are logged in.' }); if (/hotStories/.test(req.session.returnTo)) { return res.redirect('../news'); } if (/field-guide/.test(req.session.returnTo)) { return res.redirect('../field-guide'); } return res.redirect(req.session.returnTo || '/'); }); })(req, res, next); }; /** * GET /signout * Log out. */ exports.signout = function(req, res) { req.logout(); res.redirect('/'); }; /** * GET /email-signup * Signup page. */ exports.getEmailSignin = function(req, res) //noinspection Eslint { if (req.user) { return res.redirect('/'); } res.render('account/email-signin', { title: 'Sign in to your Free Code Camp Account' }); }; /** * GET /signin * Signup page. */ exports.getEmailSignup = function(req, res) { if (req.user) { return res.redirect('/'); } res.render('account/email-signup', { title: 'Create Your Free Code Camp Account' }); }; /** * POST /email-signup * Create a new local account. */ exports.postEmailSignup = function(req, res, next) { req.assert('email', 'valid email required').isEmail(); var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/email-signup'); } var possibleUserData = req.body; if (possibleUserData.password.length < 8) { req.flash('errors', { msg: 'Your password is too short' }); return res.redirect('email-signup'); } if (possibleUserData.username.length < 5 || possibleUserData.length > 20) { req.flash('errors', { msg: 'Your username must be between 5 and 20 characters' }); return res.redirect('email-signup'); } var user = new User({ email: req.body.email.trim(), password: req.body.password, profile: { username: req.body.username.trim(), picture: 'https://s3.amazonaws.com/freecodecamp/camper-image-placeholder.png' } }); User.findOne({ email: req.body.email }, function(err, existingEmail) { if (err) { return next(err); } if (existingEmail) { req.flash('errors', { msg: 'Account with that email address already exists.' }); return res.redirect('/email-signup'); } User.findOne( { 'profile.username': req.body.username }, function(err, existingUsername) { if (err) { return next(err); } if (existingUsername) { req.flash('errors', { msg: 'Account with that username already exists.' }); return res.redirect('/email-signup'); } user.save(function(err) { if (err) { return next(err); } req.logIn(user, function(err) { if (err) { return next(err); } res.redirect('/email-signup'); }); }); var transporter = nodemailer.createTransport({ service: 'Mandrill', auth: { user: secrets.mandrill.user, pass: secrets.mandrill.password } }); var mailOptions = { to: user.email, from: '[email protected]', subject: 'Welcome to Free Code Camp!', text: [ 'Greetings from San Francisco!\n\n', 'Thank you for joining our community.\n', 'Feel free to email us at this address if you have ', 'any questions about Free Code Camp.\n', 'And if you have a moment, check out our blog: ', 'blog.freecodecamp.com.\n', 'Good luck with the challenges!\n\n', '- the Volunteer Camp Counselor Team' ].join('') }; transporter.sendMail(mailOptions, function(err) { if (err) { return err; } }); }); }); }; /** * GET /account * Profile page. */ exports.getAccount = function(req, res) { res.render('account/account', { title: 'Manage your Free Code Camp Account' }); }; /** * Angular API Call */ exports.getAccountAngular = function(req, res) { res.json({ user: req.user }); }; /** * Unique username check API Call */ exports.checkUniqueUsername = function(req, res, next) { User.count( { 'profile.username': req.params.username.toLowerCase() }, function (err, data) { if (err) { return next(err); } if (data === 1) { return res.send(true); } else { return res.send(false); } }); }; /** * Existing username check */ exports.checkExistingUsername = function(req, res, next) { User.count( { 'profile.username': req.params.username.toLowerCase() }, function (err, data) { if (err) { return next(err); } if (data === 1) { return res.send(true); } else { return res.send(false); } } ); }; /** * Unique email check API Call */ exports.checkUniqueEmail = function(req, res, next) { User.count( { email: decodeURIComponent(req.params.email).toLowerCase() }, function (err, data) { if (err) { return next(err); } if (data === 1) { return res.send(true); } else { return res.send(false); } } ); }; /** * GET /campers/:username * Public Profile page. */ exports.returnUser = function(req, res, next) { User.find( { 'profile.username': req.params.username.toLowerCase() }, function(err, user) { if (err) { debug('Username err: ', err); return next(err); } if (user[0]) { user = user[0]; user.progressTimestamps = user.progressTimestamps.sort(function(a, b) { return a - b; }); var timeObject = Object.create(null); R.forEach(function(time) { timeObject[moment(time).format('YYYY-MM-DD')] = time; }, user.progressTimestamps); var tmpLongest = 1; var timeKeys = R.keys(timeObject); user.longestStreak = 0; for (var i = 1; i <= timeKeys.length; i++) { if (moment(timeKeys[i - 1]).add(1, 'd').toString() === moment(timeKeys[i]).toString()) { tmpLongest++; if (tmpLongest > user.longestStreak) { user.longestStreak = tmpLongest; } } else { tmpLongest = 1; } } timeKeys = timeKeys.reverse(); tmpLongest = 1; user.currentStreak = 1; var today = moment(Date.now()).format('YYYY-MM-DD'); if ( moment(today).toString() === moment(timeKeys[0]).toString() || moment(today).subtract(1, 'd').toString() === moment(timeKeys[0]).toString() ) { for (var _i = 1; _i <= timeKeys.length; _i++) { if ( moment(timeKeys[_i - 1]).subtract(1, 'd').toString() === moment(timeKeys[_i]).toString() ) { tmpLongest++; if (tmpLongest > user.currentStreak) { user.currentStreak = tmpLongest; } } else { break; } } } else { user.currentStreak = 1; } user.save(function(err) { if (err) { return next(err); } var data = {}; var progressTimestamps = user.progressTimestamps; progressTimestamps.forEach(function(timeStamp) { data[(timeStamp / 1000)] = 1; }); user.currentStreak = user.currentStreak || 1; user.longestStreak = user.longestStreak || 1; var challenges = user.completedCoursewares.filter(function ( obj ) { return !!obj.solution; }); res.render('account/show', { title: 'Camper ' + user.profile.username + '\'s portfolio', username: user.profile.username, name: user.profile.name, location: user.profile.location, githubProfile: user.profile.githubProfile, linkedinProfile: user.profile.linkedinProfile, codepenProfile: user.profile.codepenProfile, facebookProfile: user.profile.facebookProfile, twitterHandle: user.profile.twitterHandle, bio: user.profile.bio, picture: user.profile.picture, progressTimestamps: user.progressTimestamps, website1Link: user.portfolio.website1Link, website1Title: user.portfolio.website1Title, website1Image: user.portfolio.website1Image, website2Link: user.portfolio.website2Link, website2Title: user.portfolio.website2Title, website2Image: user.portfolio.website2Image, website3Link: user.portfolio.website3Link, website3Title: user.portfolio.website3Title, website3Image: user.portfolio.website3Image, challenges: challenges, bonfires: user.completedChallenges.filter(function(challenge) { return challenge.challengeType === 5; }), calender: data, moment: moment, longestStreak: user.longestStreak + (user.longestStreak === 1 ? ' day' : ' days'), currentStreak: user.currentStreak + (user.currentStreak === 1 ? ' day' : ' days') }); }); } else { req.flash('errors', { msg: "404: We couldn't find a page with that url. " + 'Please double check the link.' }); return res.redirect('/'); } } ); }; /** * POST /update-progress * Update profile information. */ exports.updateProgress = function(req, res, next) { User.findById(req.user.id, function(err, user) { if (err) { return next(err); } user.email = req.body.email || ''; user.profile.name = req.body.name || ''; user.profile.gender = req.body.gender || ''; user.profile.location = req.body.location || ''; user.profile.website = req.body.website || ''; user.save(function(err) { if (err) { return next(err); } req.flash('success', { msg: 'Profile information updated.' }); res.redirect('/account'); }); }); }; /** * POST /account/profile * Update profile information. */ exports.postUpdateProfile = function(req, res, next) { User.findById(req.user.id, function(err) { if (err) { return next(err); } var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/account'); } User.findOne({ email: req.body.email }, function(err, existingEmail) { if (err) { return next(err); } var user = req.user; if (existingEmail && existingEmail.email !== user.email) { req.flash('errors', { msg: 'An account with that email address already exists.' }); return res.redirect('/account'); } User.findOne( { 'profile.username': req.body.username }, function(err, existingUsername) { if (err) { return next(err); } var user = req.user; if ( existingUsername && existingUsername.profile.username !== user.profile.username ) { req.flash('errors', { msg: 'An account with that username already exists.' }); return res.redirect('/account'); } user.email = req.body.email.trim() || ''; user.profile.name = req.body.name.trim() || ''; user.profile.username = req.body.username.trim() || ''; user.profile.location = req.body.location.trim() || ''; user.profile.githubProfile = req.body.githubProfile.trim() || ''; user.profile.facebookProfile = req.body.facebookProfile.trim() || ''; user.profile.linkedinProfile = req.body.linkedinProfile.trim() || ''; user.profile.codepenProfile = req.body.codepenProfile.trim() || ''; user.profile.twitterHandle = req.body.twitterHandle.trim() || ''; user.profile.bio = req.body.bio.trim() || ''; user.profile.picture = req.body.picture.trim() || 'https://s3.amazonaws.com/freecodecamp/' + 'camper-image-placeholder.png'; user.portfolio.website1Title = req.body.website1Title.trim() || ''; user.portfolio.website1Link = req.body.website1Link.trim() || ''; user.portfolio.website1Image = req.body.website1Image.trim() || ''; user.portfolio.website2Title = req.body.website2Title.trim() || ''; user.portfolio.website2Link = req.body.website2Link.trim() || ''; user.portfolio.website2Image = req.body.website2Image.trim() || ''; user.portfolio.website3Title = req.body.website3Title.trim() || ''; user.portfolio.website3Link = req.body.website3Link.trim() || ''; user.portfolio.website3Image = req.body.website3Image.trim() || ''; user.save(function (err) { if (err) { return next(err); } resources.updateUserStoryPictures( user._id.toString(), user.profile.picture, user.profile.username, function(err) { if (err) { return next(err); } req.flash('success', { msg: 'Profile information updated.' }); res.redirect('/account'); } ); }); } ); }); }); }; /** * POST /account/password * Update current password. */ exports.postUpdatePassword = function(req, res, next) { req.assert('password', 'Password must be at least 4 characters long').len(4); req.assert('confirmPassword', 'Passwords do not match') .equals(req.body.password); var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/account'); } User.findById(req.user.id, function(err, user) { if (err) { return next(err); } user.password = req.body.password; user.save(function(err) { if (err) { return next(err); } req.flash('success', { msg: 'Password has been changed.' }); res.redirect('/account'); }); }); }; /** * POST /account/delete * Delete user account. */ exports.postDeleteAccount = function(req, res, next) { User.remove({ _id: req.user.id }, function(err) { if (err) { return next(err); } req.logout(); req.flash('info', { msg: 'Your account has been deleted.' }); res.redirect('/'); }); }; /** * GET /account/unlink/:provider * Unlink OAuth provider. */ exports.getOauthUnlink = function(req, res, next) { var provider = req.params.provider; User.findById(req.user.id, function(err, user) { if (err) { return next(err); } user[provider] = null; user.tokens = _.reject(user.tokens, function(token) { return token.kind === provider; }); user.save(function(err) { if (err) { return next(err); } req.flash('info', { msg: provider + ' account has been unlinked.' }); res.redirect('/account'); }); }); }; /** * GET /reset/:token * Reset Password page. */ exports.getReset = function(req, res, next) { if (req.isAuthenticated()) { return res.redirect('/'); } User .findOne({ resetPasswordToken: req.params.token }) .where('resetPasswordExpires').gt(Date.now()) .exec(function(err, user) { if (err) { return next(err); } if (!user) { req.flash('errors', { msg: 'Password reset token is invalid or has expired.' }); return res.redirect('/forgot'); } res.render('account/reset', { title: 'Password Reset', token: req.params.token }); }); }; /** * POST /reset/:token * Process the reset password request. */ exports.postReset = function(req, res, next) { var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('back'); } async.waterfall([ function(done) { User .findOne({ resetPasswordToken: req.params.token }) .where('resetPasswordExpires').gt(Date.now()) .exec(function(err, user) { if (err) { return next(err); } if (!user) { req.flash('errors', { msg: 'Password reset token is invalid or has expired.' }); return res.redirect('back'); } user.password = req.body.password; user.resetPasswordToken = null; user.resetPasswordExpires = null; user.save(function(err) { if (err) { return done(err); } req.logIn(user, function(err) { done(err, user); }); }); }); }, function(user, done) { var transporter = nodemailer.createTransport({ service: 'Mandrill', auth: { user: secrets.mandrill.user, pass: secrets.mandrill.password } }); var mailOptions = { to: user.email, from: '[email protected]', subject: 'Your Free Code Camp password has been changed', text: [ 'Hello,\n\n', 'This email is confirming that you requested to', 'reset your password for your Free Code Camp account.', 'This is your email:', user.email, '\n' ].join(' ') }; transporter.sendMail(mailOptions, function(err) { if (err) { return done(err); } req.flash('success', { msg: 'Success! Your password has been changed.' }); done(); }); } ], function(err) { if (err) { return next(err); } res.redirect('/'); }); }; /** * GET /forgot * Forgot Password page. */ exports.getForgot = function(req, res) { if (req.isAuthenticated()) { return res.redirect('/'); } res.render('account/forgot', { title: 'Forgot Password' }); }; /** * POST /forgot * Create a random token, then the send user an email with a reset link. */ exports.postForgot = function(req, res, next) { var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/forgot'); } async.waterfall([ function(done) { crypto.randomBytes(16, function(err, buf) { if (err) { return done(err); } var token = buf.toString('hex'); done(null, token); }); }, function(token, done) { User.findOne({ email: req.body.email.toLowerCase() }, function(err, user) { if (err) { return done(err); } if (!user) { req.flash('errors', { msg: 'No account with that email address exists.' }); return res.redirect('/forgot'); } user.resetPasswordToken = token; user.resetPasswordExpires = Date.now() + 3600000; // 1 hour user.save(function(err) { if (err) { return done(err); } done(null, token, user); }); }); }, function(token, user, done) { var transporter = nodemailer.createTransport({ service: 'Mandrill', auth: { user: secrets.mandrill.user, pass: secrets.mandrill.password } }); var mailOptions = { to: user.email, from: '[email protected]', subject: 'Reset your Free Code Camp password', text: [ 'You are receiving this email because you (or someone else)\n', 'requested we reset your Free Code Camp account\'s password.\n\n', 'Please click on the following link, or paste this into your\n', 'browser to complete the process:\n\n', 'http://', req.headers.host, '/reset/', token, '\n\n', 'If you did not request this, please ignore this email and\n', 'your password will remain unchanged.\n' ].join('') }; transporter.sendMail(mailOptions, function(err) { if (err) { return done(err); } req.flash('info', { msg: 'An e-mail has been sent to ' + user.email + ' with further instructions.' }); done(null, 'done'); }); } ], function(err) { if (err) { return next(err); } res.redirect('/forgot'); }); };
controllers/user.js
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/9b8a7cdd496c0aa8ef0d9ffd84289b8e6b237dcd
[ 0.0009468740317970514, 0.00018236735195387155, 0.00016398346633650362, 0.00017092442431021482, 0.00008744517981540412 ]
{ "id": 1, "code_window": [ " completedWith: pairedWith._id,\n", " completedDate: isCompletedDate,\n", " solution: solutionLink,\n", " githubLink: githubLink,\n", " verified: false\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " challengeType: challengeType,\n" ], "file_path": "controllers/challenge.js", "type": "add", "edit_start_line_idx": 489 }
<!doctype html> <title>CodeMirror: ECL mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="ecl.js"></script> <style>.CodeMirror {border: 1px solid black;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">ECL</a> </ul> </div> <article> <h2>ECL mode</h2> <form><textarea id="code" name="code"> /* sample useless code to demonstrate ecl syntax highlighting this is a multiline comment! */ // this is a singleline comment! import ut; r := record string22 s1 := '123'; integer4 i1 := 123; end; #option('tmp', true); d := dataset('tmp::qb', r, thor); output(d); </textarea></form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), {}); </script> <p>Based on CodeMirror's clike mode. For more information see <a href="http://hpccsystems.com">HPCC Systems</a> web site.</p> <p><strong>MIME types defined:</strong> <code>text/x-ecl</code>.</p> </article>
public/js/lib/codemirror/mode/ecl/index.html
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/9b8a7cdd496c0aa8ef0d9ffd84289b8e6b237dcd
[ 0.00017630044021643698, 0.00017298507736995816, 0.0001679019769653678, 0.00017316706362180412, 0.0000025650022053014254 ]
{ "id": 1, "code_window": [ " completedWith: pairedWith._id,\n", " completedDate: isCompletedDate,\n", " solution: solutionLink,\n", " githubLink: githubLink,\n", " verified: false\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " challengeType: challengeType,\n" ], "file_path": "controllers/challenge.js", "type": "add", "edit_start_line_idx": 489 }
bower_components/jsdom/test/level3/core/files/orig/svgunit.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/9b8a7cdd496c0aa8ef0d9ffd84289b8e6b237dcd
[ 0.0001777071738615632, 0.0001777071738615632, 0.0001777071738615632, 0.0001777071738615632, 0 ]
{ "id": 1, "code_window": [ " completedWith: pairedWith._id,\n", " completedDate: isCompletedDate,\n", " solution: solutionLink,\n", " githubLink: githubLink,\n", " verified: false\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " challengeType: challengeType,\n" ], "file_path": "controllers/challenge.js", "type": "add", "edit_start_line_idx": 489 }
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function() { "use strict"; var mode = CodeMirror.getMode({indentUnit: 2}, "text/x-less"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), "less"); } MT("variable", "[variable-2 @base]: [atom #f04615];", "[qualifier .class] {", " [property width]: [variable percentage]([number 0.5]); [comment // returns `50%`]", " [property color]: [variable saturate]([variable-2 @base], [number 5%]);", "}"); MT("amp", "[qualifier .child], [qualifier .sibling] {", " [qualifier .parent] [atom &] {", " [property color]: [keyword black];", " }", " [atom &] + [atom &] {", " [property color]: [keyword red];", " }", "}"); MT("mixin", "[qualifier .mixin] ([variable dark]; [variable-2 @color]) {", " [property color]: [variable darken]([variable-2 @color], [number 10%]);", "}", "[qualifier .mixin] ([variable light]; [variable-2 @color]) {", " [property color]: [variable lighten]([variable-2 @color], [number 10%]);", "}", "[qualifier .mixin] ([variable-2 @_]; [variable-2 @color]) {", " [property display]: [atom block];", "}", "[variable-2 @switch]: [variable light];", "[qualifier .class] {", " [qualifier .mixin]([variable-2 @switch]; [atom #888]);", "}"); MT("nest", "[qualifier .one] {", " [def @media] ([property width]: [number 400px]) {", " [property font-size]: [number 1.2em];", " [def @media] [attribute print] [keyword and] [property color] {", " [property color]: [keyword blue];", " }", " }", "}"); })();
public/js/lib/codemirror/mode/css/less_test.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/9b8a7cdd496c0aa8ef0d9ffd84289b8e6b237dcd
[ 0.0001787504443200305, 0.00017665668565314263, 0.00017461692914366722, 0.00017703539924696088, 0.0000013786410590910236 ]
{ "id": 2, "code_window": [ " completedDate: isCompletedDate,\n", " solution: solutionLink,\n", " githubLink: githubLink,\n", " verified: false\n", " });\n", " pairedWith.save(function (err, paired) {\n", " if (err) {\n", " return next(err);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " challengeType: challengeType,\n" ], "file_path": "controllers/challenge.js", "type": "add", "edit_start_line_idx": 514 }
/** * Created by nathanleniz on 5/15/15. * Copyright (c) 2015, Free Code Camp All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ var R = require('ramda'), Challenge = require('./../models/Challenge'), User = require('./../models/User'), resources = require('./resources'), MDNlinks = require('./../seed_data/bonfireMDNlinks'); var challengeMapWithNames = resources.getChallengeMapWithNames(); var challengeMapWithIds = resources.getChallengeMapWithIds(); function getMDNlinks(links) { // takes in an array of links, which are strings var populatedLinks = []; // for each key value, push the corresponding link // from the MDNlinks object into a new array if (links) { links.forEach(function (value) { populatedLinks.push(MDNlinks[value]); }); } return populatedLinks; } exports.returnNextChallenge = function(req, res, next) { if (!req.user) { return res.redirect('../challenges/learn-how-free-code-camp-works'); } var completed = req.user.completedChallenges.map(function (elem) { return elem._id; }); req.user.uncompletedChallenges = resources.allChallengeIds() .filter(function (elem) { if (completed.indexOf(elem) === -1) { return elem; } }); // find the user's current challenge and block // look in that block and find the index of their current challenge // if index + 1 < block.challenges.length // serve index + 1 challenge // otherwise increment block key and serve the first challenge in that block // unless the next block is undefined, which means no next block var nextChallengeName; var challengeId = String(req.user.currentChallenge.challengeId); var challengeBlock = req.user.currentChallenge.challengeBlock; var indexOfChallenge = challengeMapWithIds[challengeBlock] .indexOf(challengeId); if (indexOfChallenge + 1 < challengeMapWithIds[challengeBlock].length) { nextChallengeName = challengeMapWithNames[challengeBlock][++indexOfChallenge]; } else if (typeof challengeMapWithIds[++challengeBlock] !== 'undefined') { nextChallengeName = R.head(challengeMapWithNames[challengeBlock]); } else { req.flash('errors', { msg: 'It looks like you have finished all of our challenges.' + ' Great job! Now on to helping nonprofits!' }); nextChallengeName = R.head(challengeMapWithNames[0].challenges); } var nameString = nextChallengeName.trim() .toLowerCase() .replace(/\s/g, '-'); req.user.save(function(err) { if (err) { return next(err); } return res.redirect('../challenges/' + nameString); }); }; exports.returnCurrentChallenge = function(req, res, next) { if (!req.user) { return res.redirect('../challenges/learn-how-free-code-camp-works'); } var completed = req.user.completedChallenges.map(function (elem) { return elem._id; }); req.user.uncompletedChallenges = resources.allChallengeIds() .filter(function (elem) { if (completed.indexOf(elem) === -1) { return elem; } }); if (!req.user.currentChallenge) { req.user.currentChallenge = {}; req.user.currentChallenge.challengeId = challengeMapWithIds['0'][0]; req.user.currentChallenge.challengeName = challengeMapWithNames['0'][0]; req.user.currentChallenge.challengeBlock = '0'; req.user.save(function(err) { if (err) { return next(err); } }); } var nameString = req.user.currentChallenge.challengeName.trim() .toLowerCase() .replace(/\s/g, '-') .replace(/[^a-z0-9\-\/.]/gi, ''); req.user.save(function(err) { if (err) { return next(err); } return res.redirect('../challenges/' + nameString); }); }; exports.returnIndividualChallenge = function(req, res, next) { var dashedName = req.params.challengeName; var challengeName = /^(bonfire|waypoint|zipline|basejump)/i.test(dashedName) ? dashedName .replace(/\-/g, ' ') .split(' ') .slice(1) .join(' ') : dashedName.replace(/\-/g, ' '); Challenge.find({'name': new RegExp(challengeName, 'i')}, function(err, challengeFromMongo) { if (err) { return next(err); } // Handle not found if (challengeFromMongo.length < 1) { req.flash('errors', { msg: '404: We couldn\'t find a challenge with that name. ' + 'Please double check the name.' }); return res.redirect('/challenges'); } var challenge = challengeFromMongo.pop(); // Redirect to full name if the user only entered a partial var dashedNameFull = challenge.name .toLowerCase() .replace(/\s/g, '-') .replace(/[^a-z0-9\-\.]/gi, ''); if (dashedNameFull !== dashedName) { return res.redirect('../challenges/' + dashedNameFull); } else { if (req.user) { req.user.currentChallenge = { challengeId: challenge._id, challengeName: challenge.name, challengeBlock: R.head(R.flatten(Object.keys(challengeMapWithIds). map(function (key) { return challengeMapWithIds[key] .filter(function (elem) { return String(elem) === String(challenge._id); }).map(function () { return key; }); }) )) }; } } var challengeType = { 0: function() { res.render('coursewares/showHTML', { title: challenge.name, dashedName: dashedName, name: challenge.name, brief: challenge.description[0], details: challenge.description.slice(1), tests: challenge.tests, challengeSeed: challenge.challengeSeed, verb: resources.randomVerb(), phrase: resources.randomPhrase(), compliment: resources.randomCompliment(), challengeId: challenge._id, environment: resources.whichEnvironment(), challengeType: challenge.challengeType }); }, 1: function() { res.render('coursewares/showJS', { title: challenge.name, dashedName: dashedName, name: challenge.name, brief: challenge.description[0], details: challenge.description.slice(1), tests: challenge.tests, challengeSeed: challenge.challengeSeed, verb: resources.randomVerb(), phrase: resources.randomPhrase(), compliment: resources.randomCompliment(), challengeId: challenge._id, challengeType: challenge.challengeType }); }, 2: function() { res.render('coursewares/showVideo', { title: challenge.name, dashedName: dashedName, name: challenge.name, details: challenge.description, tests: challenge.tests, video: challenge.challengeSeed[0], verb: resources.randomVerb(), phrase: resources.randomPhrase(), compliment: resources.randomCompliment(), challengeId: challenge._id, challengeType: challenge.challengeType }); }, 3: function() { res.render('coursewares/showZiplineOrBasejump', { title: challenge.name, dashedName: dashedName, name: challenge.name, details: challenge.description, video: challenge.challengeSeed[0], verb: resources.randomVerb(), phrase: resources.randomPhrase(), compliment: resources.randomCompliment(), challengeId: challenge._id, challengeType: challenge.challengeType }); }, 4: function() { res.render('coursewares/showZiplineOrBasejump', { title: challenge.name, dashedName: dashedName, name: challenge.name, details: challenge.description, video: challenge.challengeSeed[0], verb: resources.randomVerb(), phrase: resources.randomPhrase(), compliment: resources.randomCompliment(), challengeId: challenge._id, challengeType: challenge.challengeType }); }, 5: function() { res.render('coursewares/showBonfire', { completedWith: null, title: challenge.name, dashedName: dashedName, name: challenge.name, difficulty: Math.floor(+challenge.difficulty), brief: challenge.description.shift(), details: challenge.description, tests: challenge.tests, challengeSeed: challenge.challengeSeed, verb: resources.randomVerb(), phrase: resources.randomPhrase(), compliment: resources.randomCompliment(), bonfires: challenge, challengeId: challenge._id, MDNkeys: challenge.MDNlinks, MDNlinks: getMDNlinks(challenge.MDNlinks), challengeType: challenge.challengeType }); } }; if (req.user) { req.user.save(function (err) { if (err) { return next(err); } return challengeType[challenge.challengeType](); }); } else { return challengeType[challenge.challengeType](); } }); }; exports.completedBonfire = function (req, res, next) { var isCompletedWith = req.body.challengeInfo.completedWith || ''; var isCompletedDate = Math.round(+new Date()); var challengeId = req.body.challengeInfo.challengeId; var isSolution = req.body.challengeInfo.solution; var challengeName = req.body.challengeInfo.challengeName; if (isCompletedWith) { var paired = User.find({'profile.username': isCompletedWith.toLowerCase()}) .limit(1); paired.exec(function (err, pairedWith) { if (err) { return next(err); } else { var index = req.user.uncompletedChallenges.indexOf(challengeId); if (index > -1) { req.user.progressTimestamps.push(Date.now() || 0); req.user.uncompletedChallenges.splice(index, 1); } pairedWith = pairedWith.pop(); if (pairedWith) { index = pairedWith.uncompletedChallenges.indexOf(challengeId); if (index > -1) { pairedWith.progressTimestamps.push(Date.now() || 0); pairedWith.uncompletedChallenges.splice(index, 1); } pairedWith.completedChallenges.push({ _id: challengeId, name: challengeName, completedWith: req.user._id, completedDate: isCompletedDate, solution: isSolution, challengeType: 5 }); req.user.completedChallenges.push({ _id: challengeId, name: challengeName, completedWith: pairedWith._id, completedDate: isCompletedDate, solution: isSolution, challengeType: 5 }); } // User said they paired, but pair wasn't found req.user.completedChallenges.push({ _id: challengeId, name: challengeName, completedWith: null, completedDate: isCompletedDate, solution: isSolution, challengeType: 5 }); req.user.save(function (err, user) { if (err) { return next(err); } if (pairedWith) { pairedWith.save(function (err, paired) { if (err) { return next(err); } if (user && paired) { res.send(true); } }); } else { if (user) { res.send(true); } } }); } }); } else { req.user.completedChallenges.push({ _id: challengeId, name: challengeName, completedWith: null, completedDate: isCompletedDate, solution: isSolution, challengeType: 5 }); var index = req.user.uncompletedChallenges.indexOf(challengeId); if (index > -1) { req.user.progressTimestamps.push(Date.now() || 0); req.user.uncompletedChallenges.splice(index, 1); } req.user.save(function (err, user) { if (err) { return next(err); } // NOTE(berks): Under certain conditions the res is never ended if (user) { res.send(true); } }); } }; exports.completedChallenge = function (req, res, next) { var isCompletedDate = Math.round(+new Date()); var challengeId = req.body.challengeInfo.challengeId; req.user.completedChallenges.push({ _id: challengeId, completedDate: isCompletedDate, name: req.body.challengeInfo.challengeName, solution: null, githubLink: null, verified: true }); var index = req.user.uncompletedChallenges.indexOf(challengeId); if (index > -1) { req.user.progressTimestamps.push(Date.now() || 0); req.user.uncompletedChallenges.splice(index, 1); } req.user.save(function (err, user) { if (err) { return next(err); } if (user) { res.sendStatus(200); } }); }; exports.completedZiplineOrBasejump = function (req, res, next) { var isCompletedWith = req.body.challengeInfo.completedWith || false; var isCompletedDate = Math.round(+new Date()); var challengeId = req.body.challengeInfo.challengeId; var solutionLink = req.body.challengeInfo.publicURL; var githubLink = req.body.challengeInfo.challengeType === '4' ? req.body.challengeInfo.githubURL : true; if (!solutionLink || !githubLink) { req.flash('errors', { msg: 'You haven\'t supplied the necessary URLs for us to inspect ' + 'your work.' }); return res.sendStatus(403); } if (isCompletedWith) { var paired = User.find({'profile.username': isCompletedWith.toLowerCase()}) .limit(1); paired.exec(function (err, pairedWithFromMongo) { if (err) { return next(err); } else { var index = req.user.uncompletedChallenges.indexOf(challengeId); if (index > -1) { req.user.progressTimestamps.push(Date.now() || 0); req.user.uncompletedChallenges.splice(index, 1); } var pairedWith = pairedWithFromMongo.pop(); req.user.completedChallenges.push({ _id: challengeId, name: req.body.challengeInfo.challengeName, completedWith: pairedWith._id, completedDate: isCompletedDate, solution: solutionLink, githubLink: githubLink, verified: false }); req.user.save(function (err, user) { if (err) { return next(err); } if (req.user._id.toString() === pairedWith._id.toString()) { return res.sendStatus(200); } index = pairedWith.uncompletedChallenges.indexOf(challengeId); if (index > -1) { pairedWith.progressTimestamps.push(Date.now() || 0); pairedWith.uncompletedChallenges.splice(index, 1); } pairedWith.completedChallenges.push({ _id: challengeId, name: req.body.challengeInfo.coursewareName, completedWith: req.user._id, completedDate: isCompletedDate, solution: solutionLink, githubLink: githubLink, verified: false }); pairedWith.save(function (err, paired) { if (err) { return next(err); } if (user && paired) { return res.sendStatus(200); } }); }); } }); } else { req.user.completedChallenges.push({ _id: challengeId, name: req.body.challengeInfo.challengeName, completedWith: null, completedDate: isCompletedDate, solution: solutionLink, githubLink: githubLink, verified: false }); var index = req.user.uncompletedChallenges.indexOf(challengeId); if (index > -1) { req.user.progressTimestamps.push(Date.now() || 0); req.user.uncompletedChallenges.splice(index, 1); } req.user.save(function (err, user) { if (err) { return next(err); } // NOTE(berks): under certain conditions this will not close the response. if (user) { return res.sendStatus(200); } }); } };
controllers/challenge.js
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/9b8a7cdd496c0aa8ef0d9ffd84289b8e6b237dcd
[ 0.9971038699150085, 0.0943293571472168, 0.0001624218566576019, 0.00017552450299263, 0.27913209795951843 ]
{ "id": 2, "code_window": [ " completedDate: isCompletedDate,\n", " solution: solutionLink,\n", " githubLink: githubLink,\n", " verified: false\n", " });\n", " pairedWith.save(function (err, paired) {\n", " if (err) {\n", " return next(err);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " challengeType: challengeType,\n" ], "file_path": "controllers/challenge.js", "type": "add", "edit_start_line_idx": 514 }
.cm-s-twilight.CodeMirror { background: #141414; color: #f7f7f7; } /**/ .cm-s-twilight .CodeMirror-selected { background: #323232 !important; } /**/ .cm-s-twilight .CodeMirror-gutters { background: #222; border-right: 1px solid #aaa; } .cm-s-twilight .CodeMirror-guttermarker { color: white; } .cm-s-twilight .CodeMirror-guttermarker-subtle { color: #aaa; } .cm-s-twilight .CodeMirror-linenumber { color: #aaa; } .cm-s-twilight .CodeMirror-cursor { border-left: 1px solid white !important; } .cm-s-twilight .cm-keyword { color: #f9ee98; } /**/ .cm-s-twilight .cm-atom { color: #FC0; } .cm-s-twilight .cm-number { color: #ca7841; } /**/ .cm-s-twilight .cm-def { color: #8DA6CE; } .cm-s-twilight span.cm-variable-2, .cm-s-twilight span.cm-tag { color: #607392; } /**/ .cm-s-twilight span.cm-variable-3, .cm-s-twilight span.cm-def { color: #607392; } /**/ .cm-s-twilight .cm-operator { color: #cda869; } /**/ .cm-s-twilight .cm-comment { color:#777; font-style:italic; font-weight:normal; } /**/ .cm-s-twilight .cm-string { color:#8f9d6a; font-style:italic; } /**/ .cm-s-twilight .cm-string-2 { color:#bd6b18 } /*?*/ .cm-s-twilight .cm-meta { background-color:#141414; color:#f7f7f7; } /*?*/ .cm-s-twilight .cm-builtin { color: #cda869; } /*?*/ .cm-s-twilight .cm-tag { color: #997643; } /**/ .cm-s-twilight .cm-attribute { color: #d6bb6d; } /*?*/ .cm-s-twilight .cm-header { color: #FF6400; } .cm-s-twilight .cm-hr { color: #AEAEAE; } .cm-s-twilight .cm-link { color:#ad9361; font-style:italic; text-decoration:none; } /**/ .cm-s-twilight .cm-error { border-bottom: 1px solid red; } .cm-s-twilight .CodeMirror-activeline-background {background: #27282E !important;} .cm-s-twilight .CodeMirror-matchingbracket {outline:1px solid grey; color:white !important;}
public/js/lib/codemirror/theme/twilight.css
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/9b8a7cdd496c0aa8ef0d9ffd84289b8e6b237dcd
[ 0.0001755897974362597, 0.0001731883967295289, 0.00017137336544692516, 0.00017289520474150777, 0.000001842090114223538 ]
{ "id": 2, "code_window": [ " completedDate: isCompletedDate,\n", " solution: solutionLink,\n", " githubLink: githubLink,\n", " verified: false\n", " });\n", " pairedWith.save(function (err, paired) {\n", " if (err) {\n", " return next(err);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " challengeType: challengeType,\n" ], "file_path": "controllers/challenge.js", "type": "add", "edit_start_line_idx": 514 }
<!doctype html> <title>CodeMirror: Version 2.2 upgrade guide</title> <meta charset="utf-8"/> <link rel=stylesheet href="docs.css"> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="logo.png"></a> <ul> <li><a href="../index.html">Home</a> <li><a href="manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a class=active href="#">2.2 upgrade guide</a> </ul> </div> <article> <h2>Upgrading to v2.2</h2> <p>There are a few things in the 2.2 release that require some care when upgrading.</p> <h3>No more default.css</h3> <p>The default theme is now included in <a href="../lib/codemirror.css"><code>codemirror.css</code></a>, so you do not have to included it separately anymore. (It was tiny, so even if you're not using it, the extra data overhead is negligible.) <h3>Different key customization</h3> <p>CodeMirror has moved to a system where <a href="manual.html#option_keyMap">keymaps</a> are used to bind behavior to keys. This means <a href="../demo/emacs.html">custom bindings</a> are now possible.</p> <p>Three options that influenced key behavior, <code>tabMode</code>, <code>enterMode</code>, and <code>smartHome</code>, are no longer supported. Instead, you can provide custom bindings to influence the way these keys act. This is done through the new <a href="manual.html#option_extraKeys"><code>extraKeys</code></a> option, which can hold an object mapping key names to functionality. A simple example would be:</p> <pre> extraKeys: { "Ctrl-S": function(instance) { saveText(instance.getValue()); }, "Ctrl-/": "undo" }</pre> <p>Keys can be mapped either to functions, which will be given the editor instance as argument, or to strings, which are mapped through functions through the <code>CodeMirror.commands</code> table, which contains all the built-in editing commands, and can be inspected and extended by external code.</p> <p>By default, the <code>Home</code> key is bound to the <code>"goLineStartSmart"</code> command, which moves the cursor to the first non-whitespace character on the line. You can set do this to make it always go to the very start instead:</p> <pre> extraKeys: {"Home": "goLineStart"}</pre> <p>Similarly, <code>Enter</code> is bound to <code>"newlineAndIndent"</code> by default. You can bind it to something else to get different behavior. To disable special handling completely and only get a newline character inserted, you can bind it to <code>false</code>:</p> <pre> extraKeys: {"Enter": false}</pre> <p>The same works for <code>Tab</code>. If you don't want CodeMirror to handle it, bind it to <code>false</code>. The default behaviour is to indent the current line more (<code>"indentMore"</code> command), and indent it less when shift is held (<code>"indentLess"</code>). There are also <code>"indentAuto"</code> (smart indent) and <code>"insertTab"</code> commands provided for alternate behaviors. Or you can write your own handler function to do something different altogether.</p> <h3>Tabs</h3> <p>Handling of tabs changed completely. The display width of tabs can now be set with the <code>tabSize</code> option, and tabs can be <a href="../demo/visibletabs.html">styled</a> by setting CSS rules for the <code>cm-tab</code> class.</p> <p>The default width for tabs is now 4, as opposed to the 8 that is hard-wired into browsers. If you are relying on 8-space tabs, make sure you explicitly set <code>tabSize: 8</code> in your options.</p> </article>
public/js/lib/codemirror/doc/upgrade_v2.2.html
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/9b8a7cdd496c0aa8ef0d9ffd84289b8e6b237dcd
[ 0.00017342553474009037, 0.00016798295837361366, 0.0001632692146813497, 0.000168125843629241, 0.0000034317733934585704 ]
{ "id": 2, "code_window": [ " completedDate: isCompletedDate,\n", " solution: solutionLink,\n", " githubLink: githubLink,\n", " verified: false\n", " });\n", " pairedWith.save(function (err, paired) {\n", " if (err) {\n", " return next(err);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " challengeType: challengeType,\n" ], "file_path": "controllers/challenge.js", "type": "add", "edit_start_line_idx": 514 }
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE // Depends on coffeelint.js from http://www.coffeelint.org/js/coffeelint.js // declare global: coffeelint (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.registerHelper("lint", "coffeescript", function(text) { var found = []; var parseError = function(err) { var loc = err.lineNumber; found.push({from: CodeMirror.Pos(loc-1, 0), to: CodeMirror.Pos(loc, 0), severity: err.level, message: err.message}); }; try { var res = coffeelint.lint(text); for(var i = 0; i < res.length; i++) { parseError(res[i]); } } catch(e) { found.push({from: CodeMirror.Pos(e.location.first_line, 0), to: CodeMirror.Pos(e.location.last_line, e.location.last_column), severity: 'error', message: e.message}); } return found; }); });
public/js/lib/codemirror/addon/lint/coffeescript-lint.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/9b8a7cdd496c0aa8ef0d9ffd84289b8e6b237dcd
[ 0.00017747096717357635, 0.00017414864851161838, 0.00016981198859866709, 0.0001743433967931196, 0.000002716011977099697 ]
{ "id": 3, "code_window": [ " completedWith: null,\n", " completedDate: isCompletedDate,\n", " solution: solutionLink,\n", " githubLink: githubLink,\n", " verified: false\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " challengeType: challengeType,\n" ], "file_path": "controllers/challenge.js", "type": "add", "edit_start_line_idx": 536 }
/** * Created by nathanleniz on 5/15/15. * Copyright (c) 2015, Free Code Camp All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ var R = require('ramda'), Challenge = require('./../models/Challenge'), User = require('./../models/User'), resources = require('./resources'), MDNlinks = require('./../seed_data/bonfireMDNlinks'); var challengeMapWithNames = resources.getChallengeMapWithNames(); var challengeMapWithIds = resources.getChallengeMapWithIds(); function getMDNlinks(links) { // takes in an array of links, which are strings var populatedLinks = []; // for each key value, push the corresponding link // from the MDNlinks object into a new array if (links) { links.forEach(function (value) { populatedLinks.push(MDNlinks[value]); }); } return populatedLinks; } exports.returnNextChallenge = function(req, res, next) { if (!req.user) { return res.redirect('../challenges/learn-how-free-code-camp-works'); } var completed = req.user.completedChallenges.map(function (elem) { return elem._id; }); req.user.uncompletedChallenges = resources.allChallengeIds() .filter(function (elem) { if (completed.indexOf(elem) === -1) { return elem; } }); // find the user's current challenge and block // look in that block and find the index of their current challenge // if index + 1 < block.challenges.length // serve index + 1 challenge // otherwise increment block key and serve the first challenge in that block // unless the next block is undefined, which means no next block var nextChallengeName; var challengeId = String(req.user.currentChallenge.challengeId); var challengeBlock = req.user.currentChallenge.challengeBlock; var indexOfChallenge = challengeMapWithIds[challengeBlock] .indexOf(challengeId); if (indexOfChallenge + 1 < challengeMapWithIds[challengeBlock].length) { nextChallengeName = challengeMapWithNames[challengeBlock][++indexOfChallenge]; } else if (typeof challengeMapWithIds[++challengeBlock] !== 'undefined') { nextChallengeName = R.head(challengeMapWithNames[challengeBlock]); } else { req.flash('errors', { msg: 'It looks like you have finished all of our challenges.' + ' Great job! Now on to helping nonprofits!' }); nextChallengeName = R.head(challengeMapWithNames[0].challenges); } var nameString = nextChallengeName.trim() .toLowerCase() .replace(/\s/g, '-'); req.user.save(function(err) { if (err) { return next(err); } return res.redirect('../challenges/' + nameString); }); }; exports.returnCurrentChallenge = function(req, res, next) { if (!req.user) { return res.redirect('../challenges/learn-how-free-code-camp-works'); } var completed = req.user.completedChallenges.map(function (elem) { return elem._id; }); req.user.uncompletedChallenges = resources.allChallengeIds() .filter(function (elem) { if (completed.indexOf(elem) === -1) { return elem; } }); if (!req.user.currentChallenge) { req.user.currentChallenge = {}; req.user.currentChallenge.challengeId = challengeMapWithIds['0'][0]; req.user.currentChallenge.challengeName = challengeMapWithNames['0'][0]; req.user.currentChallenge.challengeBlock = '0'; req.user.save(function(err) { if (err) { return next(err); } }); } var nameString = req.user.currentChallenge.challengeName.trim() .toLowerCase() .replace(/\s/g, '-') .replace(/[^a-z0-9\-\/.]/gi, ''); req.user.save(function(err) { if (err) { return next(err); } return res.redirect('../challenges/' + nameString); }); }; exports.returnIndividualChallenge = function(req, res, next) { var dashedName = req.params.challengeName; var challengeName = /^(bonfire|waypoint|zipline|basejump)/i.test(dashedName) ? dashedName .replace(/\-/g, ' ') .split(' ') .slice(1) .join(' ') : dashedName.replace(/\-/g, ' '); Challenge.find({'name': new RegExp(challengeName, 'i')}, function(err, challengeFromMongo) { if (err) { return next(err); } // Handle not found if (challengeFromMongo.length < 1) { req.flash('errors', { msg: '404: We couldn\'t find a challenge with that name. ' + 'Please double check the name.' }); return res.redirect('/challenges'); } var challenge = challengeFromMongo.pop(); // Redirect to full name if the user only entered a partial var dashedNameFull = challenge.name .toLowerCase() .replace(/\s/g, '-') .replace(/[^a-z0-9\-\.]/gi, ''); if (dashedNameFull !== dashedName) { return res.redirect('../challenges/' + dashedNameFull); } else { if (req.user) { req.user.currentChallenge = { challengeId: challenge._id, challengeName: challenge.name, challengeBlock: R.head(R.flatten(Object.keys(challengeMapWithIds). map(function (key) { return challengeMapWithIds[key] .filter(function (elem) { return String(elem) === String(challenge._id); }).map(function () { return key; }); }) )) }; } } var challengeType = { 0: function() { res.render('coursewares/showHTML', { title: challenge.name, dashedName: dashedName, name: challenge.name, brief: challenge.description[0], details: challenge.description.slice(1), tests: challenge.tests, challengeSeed: challenge.challengeSeed, verb: resources.randomVerb(), phrase: resources.randomPhrase(), compliment: resources.randomCompliment(), challengeId: challenge._id, environment: resources.whichEnvironment(), challengeType: challenge.challengeType }); }, 1: function() { res.render('coursewares/showJS', { title: challenge.name, dashedName: dashedName, name: challenge.name, brief: challenge.description[0], details: challenge.description.slice(1), tests: challenge.tests, challengeSeed: challenge.challengeSeed, verb: resources.randomVerb(), phrase: resources.randomPhrase(), compliment: resources.randomCompliment(), challengeId: challenge._id, challengeType: challenge.challengeType }); }, 2: function() { res.render('coursewares/showVideo', { title: challenge.name, dashedName: dashedName, name: challenge.name, details: challenge.description, tests: challenge.tests, video: challenge.challengeSeed[0], verb: resources.randomVerb(), phrase: resources.randomPhrase(), compliment: resources.randomCompliment(), challengeId: challenge._id, challengeType: challenge.challengeType }); }, 3: function() { res.render('coursewares/showZiplineOrBasejump', { title: challenge.name, dashedName: dashedName, name: challenge.name, details: challenge.description, video: challenge.challengeSeed[0], verb: resources.randomVerb(), phrase: resources.randomPhrase(), compliment: resources.randomCompliment(), challengeId: challenge._id, challengeType: challenge.challengeType }); }, 4: function() { res.render('coursewares/showZiplineOrBasejump', { title: challenge.name, dashedName: dashedName, name: challenge.name, details: challenge.description, video: challenge.challengeSeed[0], verb: resources.randomVerb(), phrase: resources.randomPhrase(), compliment: resources.randomCompliment(), challengeId: challenge._id, challengeType: challenge.challengeType }); }, 5: function() { res.render('coursewares/showBonfire', { completedWith: null, title: challenge.name, dashedName: dashedName, name: challenge.name, difficulty: Math.floor(+challenge.difficulty), brief: challenge.description.shift(), details: challenge.description, tests: challenge.tests, challengeSeed: challenge.challengeSeed, verb: resources.randomVerb(), phrase: resources.randomPhrase(), compliment: resources.randomCompliment(), bonfires: challenge, challengeId: challenge._id, MDNkeys: challenge.MDNlinks, MDNlinks: getMDNlinks(challenge.MDNlinks), challengeType: challenge.challengeType }); } }; if (req.user) { req.user.save(function (err) { if (err) { return next(err); } return challengeType[challenge.challengeType](); }); } else { return challengeType[challenge.challengeType](); } }); }; exports.completedBonfire = function (req, res, next) { var isCompletedWith = req.body.challengeInfo.completedWith || ''; var isCompletedDate = Math.round(+new Date()); var challengeId = req.body.challengeInfo.challengeId; var isSolution = req.body.challengeInfo.solution; var challengeName = req.body.challengeInfo.challengeName; if (isCompletedWith) { var paired = User.find({'profile.username': isCompletedWith.toLowerCase()}) .limit(1); paired.exec(function (err, pairedWith) { if (err) { return next(err); } else { var index = req.user.uncompletedChallenges.indexOf(challengeId); if (index > -1) { req.user.progressTimestamps.push(Date.now() || 0); req.user.uncompletedChallenges.splice(index, 1); } pairedWith = pairedWith.pop(); if (pairedWith) { index = pairedWith.uncompletedChallenges.indexOf(challengeId); if (index > -1) { pairedWith.progressTimestamps.push(Date.now() || 0); pairedWith.uncompletedChallenges.splice(index, 1); } pairedWith.completedChallenges.push({ _id: challengeId, name: challengeName, completedWith: req.user._id, completedDate: isCompletedDate, solution: isSolution, challengeType: 5 }); req.user.completedChallenges.push({ _id: challengeId, name: challengeName, completedWith: pairedWith._id, completedDate: isCompletedDate, solution: isSolution, challengeType: 5 }); } // User said they paired, but pair wasn't found req.user.completedChallenges.push({ _id: challengeId, name: challengeName, completedWith: null, completedDate: isCompletedDate, solution: isSolution, challengeType: 5 }); req.user.save(function (err, user) { if (err) { return next(err); } if (pairedWith) { pairedWith.save(function (err, paired) { if (err) { return next(err); } if (user && paired) { res.send(true); } }); } else { if (user) { res.send(true); } } }); } }); } else { req.user.completedChallenges.push({ _id: challengeId, name: challengeName, completedWith: null, completedDate: isCompletedDate, solution: isSolution, challengeType: 5 }); var index = req.user.uncompletedChallenges.indexOf(challengeId); if (index > -1) { req.user.progressTimestamps.push(Date.now() || 0); req.user.uncompletedChallenges.splice(index, 1); } req.user.save(function (err, user) { if (err) { return next(err); } // NOTE(berks): Under certain conditions the res is never ended if (user) { res.send(true); } }); } }; exports.completedChallenge = function (req, res, next) { var isCompletedDate = Math.round(+new Date()); var challengeId = req.body.challengeInfo.challengeId; req.user.completedChallenges.push({ _id: challengeId, completedDate: isCompletedDate, name: req.body.challengeInfo.challengeName, solution: null, githubLink: null, verified: true }); var index = req.user.uncompletedChallenges.indexOf(challengeId); if (index > -1) { req.user.progressTimestamps.push(Date.now() || 0); req.user.uncompletedChallenges.splice(index, 1); } req.user.save(function (err, user) { if (err) { return next(err); } if (user) { res.sendStatus(200); } }); }; exports.completedZiplineOrBasejump = function (req, res, next) { var isCompletedWith = req.body.challengeInfo.completedWith || false; var isCompletedDate = Math.round(+new Date()); var challengeId = req.body.challengeInfo.challengeId; var solutionLink = req.body.challengeInfo.publicURL; var githubLink = req.body.challengeInfo.challengeType === '4' ? req.body.challengeInfo.githubURL : true; if (!solutionLink || !githubLink) { req.flash('errors', { msg: 'You haven\'t supplied the necessary URLs for us to inspect ' + 'your work.' }); return res.sendStatus(403); } if (isCompletedWith) { var paired = User.find({'profile.username': isCompletedWith.toLowerCase()}) .limit(1); paired.exec(function (err, pairedWithFromMongo) { if (err) { return next(err); } else { var index = req.user.uncompletedChallenges.indexOf(challengeId); if (index > -1) { req.user.progressTimestamps.push(Date.now() || 0); req.user.uncompletedChallenges.splice(index, 1); } var pairedWith = pairedWithFromMongo.pop(); req.user.completedChallenges.push({ _id: challengeId, name: req.body.challengeInfo.challengeName, completedWith: pairedWith._id, completedDate: isCompletedDate, solution: solutionLink, githubLink: githubLink, verified: false }); req.user.save(function (err, user) { if (err) { return next(err); } if (req.user._id.toString() === pairedWith._id.toString()) { return res.sendStatus(200); } index = pairedWith.uncompletedChallenges.indexOf(challengeId); if (index > -1) { pairedWith.progressTimestamps.push(Date.now() || 0); pairedWith.uncompletedChallenges.splice(index, 1); } pairedWith.completedChallenges.push({ _id: challengeId, name: req.body.challengeInfo.coursewareName, completedWith: req.user._id, completedDate: isCompletedDate, solution: solutionLink, githubLink: githubLink, verified: false }); pairedWith.save(function (err, paired) { if (err) { return next(err); } if (user && paired) { return res.sendStatus(200); } }); }); } }); } else { req.user.completedChallenges.push({ _id: challengeId, name: req.body.challengeInfo.challengeName, completedWith: null, completedDate: isCompletedDate, solution: solutionLink, githubLink: githubLink, verified: false }); var index = req.user.uncompletedChallenges.indexOf(challengeId); if (index > -1) { req.user.progressTimestamps.push(Date.now() || 0); req.user.uncompletedChallenges.splice(index, 1); } req.user.save(function (err, user) { if (err) { return next(err); } // NOTE(berks): under certain conditions this will not close the response. if (user) { return res.sendStatus(200); } }); } };
controllers/challenge.js
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/9b8a7cdd496c0aa8ef0d9ffd84289b8e6b237dcd
[ 0.22946739196777344, 0.00494200736284256, 0.00016580968804191798, 0.00017309490067418665, 0.030377713963389397 ]
{ "id": 3, "code_window": [ " completedWith: null,\n", " completedDate: isCompletedDate,\n", " solution: solutionLink,\n", " githubLink: githubLink,\n", " verified: false\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " challengeType: challengeType,\n" ], "file_path": "controllers/challenge.js", "type": "add", "edit_start_line_idx": 536 }
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE //tcl mode by Ford_Lawnmower :: Based on Velocity mode by Steve O'Hara (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("tcl", function() { function parseWords(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } var keywords = parseWords("Tcl safe after append array auto_execok auto_import auto_load " + "auto_mkindex auto_mkindex_old auto_qualify auto_reset bgerror " + "binary break catch cd close concat continue dde eof encoding error " + "eval exec exit expr fblocked fconfigure fcopy file fileevent filename " + "filename flush for foreach format gets glob global history http if " + "incr info interp join lappend lindex linsert list llength load lrange " + "lreplace lsearch lset lsort memory msgcat namespace open package parray " + "pid pkg::create pkg_mkIndex proc puts pwd re_syntax read regex regexp " + "registry regsub rename resource return scan seek set socket source split " + "string subst switch tcl_endOfWord tcl_findLibrary tcl_startOfNextWord " + "tcl_wordBreakAfter tcl_startOfPreviousWord tcl_wordBreakBefore tcltest " + "tclvars tell time trace unknown unset update uplevel upvar variable " + "vwait"); var functions = parseWords("if elseif else and not or eq ne in ni for foreach while switch"); var isOperatorChar = /[+\-*&%=<>!?^\/\|]/; function chain(stream, state, f) { state.tokenize = f; return f(stream, state); } function tokenBase(stream, state) { var beforeParams = state.beforeParams; state.beforeParams = false; var ch = stream.next(); if ((ch == '"' || ch == "'") && state.inParams) return chain(stream, state, tokenString(ch)); else if (/[\[\]{}\(\),;\.]/.test(ch)) { if (ch == "(" && beforeParams) state.inParams = true; else if (ch == ")") state.inParams = false; return null; } else if (/\d/.test(ch)) { stream.eatWhile(/[\w\.]/); return "number"; } else if (ch == "#" && stream.eat("*")) { return chain(stream, state, tokenComment); } else if (ch == "#" && stream.match(/ *\[ *\[/)) { return chain(stream, state, tokenUnparsed); } else if (ch == "#" && stream.eat("#")) { stream.skipToEnd(); return "comment"; } else if (ch == '"') { stream.skipTo(/"/); return "comment"; } else if (ch == "$") { stream.eatWhile(/[$_a-z0-9A-Z\.{:]/); stream.eatWhile(/}/); state.beforeParams = true; return "builtin"; } else if (isOperatorChar.test(ch)) { stream.eatWhile(isOperatorChar); return "comment"; } else { stream.eatWhile(/[\w\$_{}\xa1-\uffff]/); var word = stream.current().toLowerCase(); if (keywords && keywords.propertyIsEnumerable(word)) return "keyword"; if (functions && functions.propertyIsEnumerable(word)) { state.beforeParams = true; return "keyword"; } return null; } } function tokenString(quote) { return function(stream, state) { var escaped = false, next, end = false; while ((next = stream.next()) != null) { if (next == quote && !escaped) { end = true; break; } escaped = !escaped && next == "\\"; } if (end) state.tokenize = tokenBase; return "string"; }; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "#" && maybeEnd) { state.tokenize = tokenBase; break; } maybeEnd = (ch == "*"); } return "comment"; } function tokenUnparsed(stream, state) { var maybeEnd = 0, ch; while (ch = stream.next()) { if (ch == "#" && maybeEnd == 2) { state.tokenize = tokenBase; break; } if (ch == "]") maybeEnd++; else if (ch != " ") maybeEnd = 0; } return "meta"; } return { startState: function() { return { tokenize: tokenBase, beforeParams: false, inParams: false }; }, token: function(stream, state) { if (stream.eatSpace()) return null; return state.tokenize(stream, state); } }; }); CodeMirror.defineMIME("text/x-tcl", "tcl"); });
public/js/lib/codemirror/mode/tcl/tcl.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/9b8a7cdd496c0aa8ef0d9ffd84289b8e6b237dcd
[ 0.00017740007024258375, 0.00017349874542560428, 0.00016878306632861495, 0.00017399016360286623, 0.0000024854175535438117 ]
{ "id": 3, "code_window": [ " completedWith: null,\n", " completedDate: isCompletedDate,\n", " solution: solutionLink,\n", " githubLink: githubLink,\n", " verified: false\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " challengeType: challengeType,\n" ], "file_path": "controllers/challenge.js", "type": "add", "edit_start_line_idx": 536 }
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineExtension("annotateScrollbar", function(className) { return new Annotation(this, className); }); function Annotation(cm, className) { this.cm = cm; this.className = className; this.annotations = []; this.div = cm.getWrapperElement().appendChild(document.createElement("div")); this.div.style.cssText = "position: absolute; right: 0; top: 0; z-index: 7; pointer-events: none"; this.computeScale(); var self = this; cm.on("refresh", this.resizeHandler = function(){ if (self.computeScale()) self.redraw(); }); } Annotation.prototype.computeScale = function() { var cm = this.cm; var hScale = (cm.getWrapperElement().clientHeight - cm.display.barHeight) / cm.heightAtLine(cm.lastLine() + 1, "local"); if (hScale != this.hScale) { this.hScale = hScale; return true; } }; Annotation.prototype.update = function(annotations) { this.annotations = annotations; this.redraw(); }; Annotation.prototype.redraw = function() { var cm = this.cm, hScale = this.hScale; if (!cm.display.barWidth) return; var frag = document.createDocumentFragment(), anns = this.annotations; for (var i = 0, nextTop; i < anns.length; i++) { var ann = anns[i]; var top = nextTop || cm.charCoords(ann.from, "local").top * hScale; var bottom = cm.charCoords(ann.to, "local").bottom * hScale; while (i < anns.length - 1) { nextTop = cm.charCoords(anns[i + 1].from, "local").top * hScale; if (nextTop > bottom + .9) break; ann = anns[++i]; bottom = cm.charCoords(ann.to, "local").bottom * hScale; } var height = Math.max(bottom - top, 3); var elt = frag.appendChild(document.createElement("div")); elt.style.cssText = "position: absolute; right: 0px; width: " + Math.max(cm.display.barWidth - 1, 2) + "px; top: " + top + "px; height: " + height + "px"; elt.className = this.className; } this.div.textContent = ""; this.div.appendChild(frag); }; Annotation.prototype.clear = function() { this.cm.off("refresh", this.resizeHandler); this.div.parentNode.removeChild(this.div); }; });
public/js/lib/codemirror/addon/scroll/annotatescrollbar.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/9b8a7cdd496c0aa8ef0d9ffd84289b8e6b237dcd
[ 0.00017553639190737158, 0.00017440241936128587, 0.0001733749231789261, 0.000174537708517164, 8.054640829868731e-7 ]
{ "id": 3, "code_window": [ " completedWith: null,\n", " completedDate: isCompletedDate,\n", " solution: solutionLink,\n", " githubLink: githubLink,\n", " verified: false\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " challengeType: challengeType,\n" ], "file_path": "controllers/challenge.js", "type": "add", "edit_start_line_idx": 536 }
// // Variables // -------------------------------------------------- //== Colors // //## Gray and brand colors for use across Bootstrap. @gray-base: #000; @gray-darker: lighten(@gray-base, 13.5%); // #222 @gray-dark: lighten(@gray-base, 20%); // #333 @gray: lighten(@gray-base, 33.5%); // #555 @gray-light: lighten(@gray-base, 46.7%); // #777 @gray-lighter: lighten(@gray-base, 93.5%); // #eee @brand-primary: #215f1e; @brand-success: #457E86; @brand-info: #4A2B0F; @brand-warning: #f0ad4e; @brand-danger: #d9534f; //== Scaffolding // //## Settings for some of the most global styles. //** Background color for `<body>`. @body-bg: #457E86; //** Global text color on `<body>`. @text-color: @gray-dark; //** Global textual link color. @link-color: #215f1e; //** Link hover color set via `darken()` function. @link-hover-color: darken(@link-color, 15%); //** Link hover decoration. @link-hover-decoration: underline; //== Typography // //## Font, line-height, and color for body text, headings, and more. @font-family-sans-serif: "Helvetica Neue", Helvetica, Arial, sans-serif; @font-family-serif: Georgia, "Times New Roman", Times, serif; //** Default monospace fonts for `<code>`, `<kbd>`, and `<pre>`. @font-family-monospace: Menlo, Monaco, Consolas, "Courier New", monospace; @font-family-base: @font-family-sans-serif; @font-size-base: 14px; @font-size-large: ceil((@font-size-base * 1.25)); // ~18px @font-size-small: ceil((@font-size-base * 0.85)); // ~12px @font-size-h1: floor((@font-size-base * 2.6)); // ~36px @font-size-h2: floor((@font-size-base * 2.15)); // ~30px @font-size-h3: ceil((@font-size-base * 1.7)); // ~24px @font-size-h4: ceil((@font-size-base * 1.25)); // ~18px @font-size-h5: @font-size-base; @font-size-h6: ceil((@font-size-base * 0.85)); // ~12px //** Unit-less `line-height` for use in components like buttons. @line-height-base: 1.428571429; // 20/14 //** Computed "line-height" (`font-size` * `line-height`) for use with `margin`, `padding`, etc. @line-height-computed: floor((@font-size-base * @line-height-base)); // ~20px //** By default, this inherits from the `<body>`. @headings-font-family: inherit; @headings-font-weight: 500; @headings-line-height: 1.1; @headings-color: inherit; //== Iconography // //## Specify custom location and filename of the included Glyphicons icon font. Useful for those including Bootstrap via Bower. //** Load fonts from this directory. @icon-font-path: "../fonts/"; //** File name for all font files. @icon-font-name: "glyphicons-halflings-regular"; //** Element ID within SVG icon file. @icon-font-svg-id: "glyphicons_halflingsregular"; //== Components // //## Define common padding and border radius sizes and more. Values based on 14px text and 1.428 line-height (~20px to start). @padding-base-vertical: 6px; @padding-base-horizontal: 12px; @padding-large-vertical: 10px; @padding-large-horizontal: 16px; @padding-small-vertical: 5px; @padding-small-horizontal: 10px; @padding-xs-vertical: 1px; @padding-xs-horizontal: 5px; @line-height-large: 1.33; @line-height-small: 1.5; @border-radius-base: 4px; @border-radius-large: 6px; @border-radius-small: 3px; //** Global color for active items (e.g., navs or dropdowns). @component-active-color: #eee; //** Global background color for active items (e.g., navs or dropdowns). @component-active-bg: @brand-primary; //** Width of the `border` for generating carets that indicator dropdowns. @caret-width-base: 4px; //** Carets increase slightly in size for larger components. @caret-width-large: 5px; //== Tables // //## Customizes the `.table` component with basic values, each used across all table variations. //** Padding for `<th>`s and `<td>`s. @table-cell-padding: 8px; //** Padding for cells in `.table-condensed`. @table-condensed-cell-padding: 5px; //** Default background color used for all tables. @table-bg: transparent; //** Background color used for `.table-striped`. @table-bg-accent: #f9f9f9; //** Background color used for `.table-hover`. @table-bg-hover: #f5f5f5; @table-bg-active: @table-bg-hover; //** Border color for table and cell borders. @table-border-color: #ddd; //== Buttons // //## For each of Bootstrap's buttons, define text, background and border color. @btn-font-weight: normal; @btn-default-color: #333; @btn-default-bg: #eee; @btn-default-border: #ccc; @btn-primary-color: #eee; @btn-primary-bg: @brand-primary; @btn-primary-border: darken(@btn-primary-bg, 5%); @btn-success-color: #eee; @btn-success-bg: @brand-success; @btn-success-border: darken(@btn-success-bg, 5%); @btn-info-color: #eee; @btn-info-bg: @brand-info; @btn-info-border: darken(@btn-info-bg, 5%); @btn-warning-color: #eee; @btn-warning-bg: @brand-warning; @btn-warning-border: darken(@btn-warning-bg, 5%); @btn-danger-color: #eee; @btn-danger-bg: @brand-danger; @btn-danger-border: darken(@btn-danger-bg, 5%); @btn-link-disabled-color: @gray-light; //== Forms // //## //** `<input>` background color @input-bg: #eee; //** `<input disabled>` background color @input-bg-disabled: @gray-lighter; //** Text color for `<input>`s @input-color: @gray; //** `<input>` border color @input-border: #ccc; // TODO: Rename `@input-border-radius` to `@input-border-radius-base` in v4 //** Default `.form-control` border radius @input-border-radius: @border-radius-base; //** Large `.form-control` border radius @input-border-radius-large: @border-radius-large; //** Small `.form-control` border radius @input-border-radius-small: @border-radius-small; //** Border color for inputs on focus @input-border-focus: #66afe9; //** Placeholder text color @input-color-placeholder: #999; //** Default `.form-control` height @input-height-base: (@line-height-computed + (@padding-base-vertical * 2) + 2); //** Large `.form-control` height @input-height-large: (ceil(@font-size-large * @line-height-large) + (@padding-large-vertical * 2) + 2); //** Small `.form-control` height @input-height-small: (floor(@font-size-small * @line-height-small) + (@padding-small-vertical * 2) + 2); @legend-color: @gray-dark; @legend-border-color: #e5e5e5; //** Background color for textual input addons @input-group-addon-bg: @gray-lighter; //** Border color for textual input addons @input-group-addon-border-color: @input-border; //** Disabled cursor for form controls and buttons. @cursor-disabled: not-allowed; //== Dropdowns // //## Dropdown menu container and contents. //** Background for the dropdown menu. @dropdown-bg: #eee; //** Dropdown menu `border-color`. @dropdown-border: rgba(0,0,0,.15); //** Dropdown menu `border-color` **for IE8**. @dropdown-fallback-border: #ccc; //** Divider color for between dropdown items. @dropdown-divider-bg: #e5e5e5; //** Dropdown link text color. @dropdown-link-color: @gray-dark; //** Hover color for dropdown links. @dropdown-link-hover-color: darken(@gray-dark, 5%); //** Hover background for dropdown links. @dropdown-link-hover-bg: #f5f5f5; //** Active dropdown menu item text color. @dropdown-link-active-color: @component-active-color; //** Active dropdown menu item background color. @dropdown-link-active-bg: @component-active-bg; //** Disabled dropdown menu item background color. @dropdown-link-disabled-color: @gray-light; //** Text color for headers within dropdown menus. @dropdown-header-color: @gray-light; //** Deprecated `@dropdown-caret-color` as of v3.1.0 @dropdown-caret-color: #000; //-- Z-index master list // // Warning: Avoid customizing these values. They're used for a bird's eye view // of components dependent on the z-axis and are designed to all work together. // // Note: These variables are not generated into the Customizer. @zindex-navbar: 1000; @zindex-dropdown: 1000; @zindex-popover: 1060; @zindex-tooltip: 1070; @zindex-navbar-fixed: 1030; @zindex-modal: 1040; //== Media queries breakpoints // //## Define the breakpoints at which your layout will change, adapting to different screen sizes. // Extra small screen / phone //** Deprecated `@screen-xs` as of v3.0.1 @screen-xs: 480px; //** Deprecated `@screen-xs-min` as of v3.2.0 @screen-xs-min: @screen-xs; //** Deprecated `@screen-phone` as of v3.0.1 @screen-phone: @screen-xs-min; // Small screen / tablet //** Deprecated `@screen-sm` as of v3.0.1 @screen-sm: 768px; @screen-sm-min: @screen-sm; //** Deprecated `@screen-tablet` as of v3.0.1 @screen-tablet: @screen-sm-min; // Medium screen / desktop //** Deprecated `@screen-md` as of v3.0.1 @screen-md: 992px; @screen-md-min: @screen-md; //** Deprecated `@screen-desktop` as of v3.0.1 @screen-desktop: @screen-md-min; // Large screen / wide desktop //** Deprecated `@screen-lg` as of v3.0.1 @screen-lg: 1200px; @screen-lg-min: @screen-lg; //** Deprecated `@screen-lg-desktop` as of v3.0.1 @screen-lg-desktop: @screen-lg-min; // So media queries don't overlap when required, provide a maximum @screen-xs-max: (@screen-sm-min - 1); @screen-sm-max: (@screen-md-min - 1); @screen-md-max: (@screen-lg-min - 1); //== Grid system // //## Define your custom responsive grid. //** Number of columns in the grid. @grid-columns: 12; //** Padding between columns. Gets divided in half for the left and right. @grid-gutter-width: 30px; // Navbar collapse //** Point at which the navbar becomes uncollapsed. @grid-float-breakpoint: @screen-sm-min; //** Point at which the navbar begins collapsing. @grid-float-breakpoint-max: (@grid-float-breakpoint - 1); //== Container sizes // //## Define the maximum width of `.container` for different screen sizes. // Small screen / tablet @container-tablet: (720px + @grid-gutter-width); //** For `@screen-sm-min` and up. @container-sm: @container-tablet; // Medium screen / desktop @container-desktop: (940px + @grid-gutter-width); //** For `@screen-md-min` and up. @container-md: @container-desktop; // Large screen / wide desktop @container-large-desktop: (1140px + @grid-gutter-width); //** For `@screen-lg-min` and up. @container-lg: @container-large-desktop; //== Navbar // //## // Basics of a navbar @navbar-height: 50px; @navbar-margin-bottom: @line-height-computed; @navbar-border-radius: @border-radius-base; @navbar-padding-horizontal: floor((@grid-gutter-width / 2)); @navbar-padding-vertical: ((@navbar-height - @line-height-computed) / 2); @navbar-collapse-max-height: 340px; @navbar-default-color: #777; @navbar-default-bg: #f8f8f8; @navbar-default-border: darken(@navbar-default-bg, 6.5%); // Navbar links @navbar-default-link-color: #eee; @navbar-default-link-hover-color: #4a2b0f; @navbar-default-link-hover-bg: #eee; @navbar-default-link-active-color: #eee; @navbar-default-link-active-bg: darken(@navbar-default-bg, 6.5%); @navbar-default-link-disabled-color: #ccc; @navbar-default-link-disabled-bg: transparent; // Navbar brand label @navbar-default-brand-color: @navbar-default-link-color; @navbar-default-brand-hover-color: darken(@navbar-default-brand-color, 10%); @navbar-default-brand-hover-bg: transparent; // Navbar toggle @navbar-default-toggle-hover-bg: #ddd; @navbar-default-toggle-icon-bar-bg: #888; @navbar-default-toggle-border-color: #ddd; // Inverted navbar // Reset inverted navbar basics @navbar-inverse-color: lighten(@gray-light, 15%); @navbar-inverse-bg: #222; @navbar-inverse-border: darken(@navbar-inverse-bg, 10%); // Inverted navbar links @navbar-inverse-link-color: @gray-light; @navbar-inverse-link-hover-color: #eee; @navbar-inverse-link-hover-bg: transparent; @navbar-inverse-link-active-color: @navbar-inverse-link-hover-color; @navbar-inverse-link-active-bg: darken(@navbar-inverse-bg, 10%); @navbar-inverse-link-disabled-color: #444; @navbar-inverse-link-disabled-bg: transparent; // Inverted navbar brand label @navbar-inverse-brand-color: @navbar-inverse-link-color; @navbar-inverse-brand-hover-color: #eee; @navbar-inverse-brand-hover-bg: transparent; // Inverted navbar toggle @navbar-inverse-toggle-hover-bg: #333; @navbar-inverse-toggle-icon-bar-bg: #eee; @navbar-inverse-toggle-border-color: #333; //== Navs // //## //=== Shared nav styles @nav-link-padding: 10px 15px; @nav-link-hover-bg: @gray-lighter; @nav-disabled-link-color: @gray-light; @nav-disabled-link-hover-color: @gray-light; @nav-open-link-hover-color: #eee; //== Tabs @nav-tabs-border-color: #ddd; @nav-tabs-link-hover-border-color: @gray-lighter; @nav-tabs-active-link-hover-bg: @body-bg; @nav-tabs-active-link-hover-color: @gray; @nav-tabs-active-link-hover-border-color: #ddd; @nav-tabs-justified-link-border-color: #ddd; @nav-tabs-justified-active-link-border-color: @body-bg; //== Pills @nav-pills-border-radius: @border-radius-base; @nav-pills-active-link-hover-bg: @component-active-bg; @nav-pills-active-link-hover-color: @component-active-color; //== Pagination // //## @pagination-color: @link-color; @pagination-bg: #eee; @pagination-border: #ddd; @pagination-hover-color: @link-hover-color; @pagination-hover-bg: @gray-lighter; @pagination-hover-border: #ddd; @pagination-active-color: #eee; @pagination-active-bg: @brand-primary; @pagination-active-border: @brand-primary; @pagination-disabled-color: @gray-light; @pagination-disabled-bg: #eee; @pagination-disabled-border: #ddd; //== Pager // //## @pager-bg: @pagination-bg; @pager-border: @pagination-border; @pager-border-radius: 15px; @pager-hover-bg: @pagination-hover-bg; @pager-active-bg: @pagination-active-bg; @pager-active-color: @pagination-active-color; @pager-disabled-color: @pagination-disabled-color; //== Jumbotron // //## @jumbotron-padding: 30px; @jumbotron-color: inherit; @jumbotron-bg: @gray-lighter; @jumbotron-heading-color: inherit; @jumbotron-font-size: ceil((@font-size-base * 1.5)); //== Form states and alerts // //## Define colors for form feedback states and, by default, alerts. @state-success-text: #215f1e; @state-success-bg: #dff0d8; @state-success-border: darken(spin(@state-success-bg, -10), 5%); @state-info-text: #31708f; @state-info-bg: #d9edf7; @state-info-border: darken(spin(@state-info-bg, -10), 7%); @state-warning-text: #8a6d3b; @state-warning-bg: #fcf8e3; @state-warning-border: darken(spin(@state-warning-bg, -10), 5%); @state-danger-text: #a94442; @state-danger-bg: #f2dede; @state-danger-border: darken(spin(@state-danger-bg, -10), 5%); //== Tooltips // //## //** Tooltip max width @tooltip-max-width: 200px; //** Tooltip text color @tooltip-color: #eee; //** Tooltip background color @tooltip-bg: #000; @tooltip-opacity: .9; //** Tooltip arrow width @tooltip-arrow-width: 5px; //** Tooltip arrow color @tooltip-arrow-color: @tooltip-bg; //== Popovers // //## //** Popover body background color @popover-bg: #eee; //** Popover maximum width @popover-max-width: 276px; //** Popover border color @popover-border-color: rgba(0,0,0,.2); //** Popover fallback border color @popover-fallback-border-color: #ccc; //** Popover title background color @popover-title-bg: darken(@popover-bg, 3%); //** Popover arrow width @popover-arrow-width: 10px; //** Popover arrow color @popover-arrow-color: #eee; @popover-arrow-color: @popover-bg; //** Popover outer arrow width @popover-arrow-outer-width: (@popover-arrow-width + 1); //** Popover outer arrow color @popover-arrow-outer-color: fadein(@popover-border-color, 5%); //** Popover outer arrow fallback color @popover-arrow-outer-fallback-color: darken(@popover-fallback-border-color, 20%); //== Labels // //## //** Default label background color @label-default-bg: @gray-light; //** Primary label background color @label-primary-bg: @brand-primary; //** Success label background color @label-success-bg: @brand-success; //** Info label background color @label-info-bg: @brand-info; //** Warning label background color @label-warning-bg: @brand-warning; //** Danger label background color @label-danger-bg: @brand-danger; //** Default label text color @label-color: #eee; //** Default text color of a linked label @label-link-hover-color: #eee; //== Modals // //## //** Padding applied to the modal body @modal-inner-padding: 15px; //** Padding applied to the modal title @modal-title-padding: 15px; //** Modal title line-height @modal-title-line-height: @line-height-base; //** Background color of modal content area @modal-content-bg: #eee; //** Modal content border color @modal-content-border-color: rgba(0,0,0,.2); //** Modal content border color **for IE8** @modal-content-fallback-border-color: #999; //** Modal backdrop background color @modal-backdrop-bg: #000; //** Modal backdrop opacity @modal-backdrop-opacity: .5; //** Modal header border color @modal-header-border-color: #e5e5e5; //** Modal footer border color @modal-footer-border-color: @modal-header-border-color; @modal-lg: 900px; @modal-md: 600px; @modal-sm: 300px; //== Alerts // //## Define alert colors, border radius, and padding. @alert-padding: 15px; @alert-border-radius: @border-radius-base; @alert-link-font-weight: bold; @alert-success-bg: @state-success-bg; @alert-success-text: @state-success-text; @alert-success-border: @state-success-border; @alert-info-bg: @state-info-bg; @alert-info-text: @state-info-text; @alert-info-border: @state-info-border; @alert-warning-bg: @state-warning-bg; @alert-warning-text: @state-warning-text; @alert-warning-border: @state-warning-border; @alert-danger-bg: @state-danger-bg; @alert-danger-text: @state-danger-text; @alert-danger-border: @state-danger-border; //== Progress bars // //## //** Background color of the whole progress component @progress-bg: #f5f5f5; //** Progress bar text color @progress-bar-color: #eee; //** Variable for setting rounded corners on progress bar. @progress-border-radius: @border-radius-base; //** Default progress bar color @progress-bar-bg: @brand-primary; //** Success progress bar color @progress-bar-success-bg: @brand-success; //** Warning progress bar color @progress-bar-warning-bg: @brand-warning; //** Danger progress bar color @progress-bar-danger-bg: @brand-danger; //** Info progress bar color @progress-bar-info-bg: @brand-info; //== List group // //## //** Background color on `.list-group-item` @list-group-bg: #eee; //** `.list-group-item` border color @list-group-border: #ddd; //** List group border radius @list-group-border-radius: @border-radius-base; //** Background color of single list items on hover @list-group-hover-bg: #f5f5f5; //** Text color of active list items @list-group-active-color: @component-active-color; //** Background color of active list items @list-group-active-bg: @component-active-bg; //** Border color of active list elements @list-group-active-border: @list-group-active-bg; //** Text color for content within active list items @list-group-active-text-color: lighten(@list-group-active-bg, 40%); //** Text color of disabled list items @list-group-disabled-color: @gray-light; //** Background color of disabled list items @list-group-disabled-bg: @gray-lighter; //** Text color for content within disabled list items @list-group-disabled-text-color: @list-group-disabled-color; @list-group-link-color: #555; @list-group-link-hover-color: @list-group-link-color; @list-group-link-heading-color: #333; //== Panels // //## @panel-bg: #eee; @panel-body-padding: 15px; @panel-heading-padding: 10px 15px; @panel-footer-padding: @panel-heading-padding; @panel-border-radius: @border-radius-base; //** Border color for elements within panels @panel-inner-border: #ccc; @panel-footer-bg: #dedede; @panel-default-text: @gray-dark; @panel-default-border: #ddd; @panel-default-heading-bg: #f5f5f5; @panel-primary-text: #eee; @panel-primary-border: @brand-primary; @panel-primary-heading-bg: @brand-primary; @panel-success-text: @state-success-text; @panel-success-border: @state-success-border; @panel-success-heading-bg: @state-success-bg; @panel-info-text: #eee; @panel-info-border: darken(#4a2b0f, 5%); @panel-info-heading-bg: #4a2b0f; @panel-warning-text: @state-warning-text; @panel-warning-border: @state-warning-border; @panel-warning-heading-bg: @state-warning-bg; @panel-danger-text: @state-danger-text; @panel-danger-border: @state-danger-border; @panel-danger-heading-bg: @state-danger-bg; //== Thumbnails // //## //** Padding around the thumbnail image @thumbnail-padding: 4px; //** Thumbnail background color @thumbnail-bg: @body-bg; //** Thumbnail border color @thumbnail-border: #ddd; //** Thumbnail border radius @thumbnail-border-radius: @border-radius-base; //** Custom text color for thumbnail captions @thumbnail-caption-color: @text-color; //** Padding around the thumbnail caption @thumbnail-caption-padding: 9px; //== Wells // //## @well-bg: #f5f5f5; @well-border: darken(@well-bg, 7%); //== Badges // //## @badge-color: #eee; //** Linked badge text color on hover @badge-link-hover-color: #eee; @badge-bg: @gray-light; //** Badge text color in active nav link @badge-active-color: @link-color; //** Badge background color in active nav link @badge-active-bg: #eee; @badge-font-weight: bold; @badge-line-height: 1; @badge-border-radius: 10px; //== Breadcrumbs // //## @breadcrumb-padding-vertical: 8px; @breadcrumb-padding-horizontal: 15px; //** Breadcrumb background color @breadcrumb-bg: #f5f5f5; //** Breadcrumb text color @breadcrumb-color: #ccc; //** Text color of current page in the breadcrumb @breadcrumb-active-color: @gray-light; //** Textual separator for between breadcrumb elements @breadcrumb-separator: "/"; //== Carousel // //## @carousel-text-shadow: 0 1px 2px rgba(0,0,0,.6); @carousel-control-color: #eee; @carousel-control-width: 15%; @carousel-control-opacity: .5; @carousel-control-font-size: 20px; @carousel-indicator-active-bg: #eee; @carousel-indicator-border-color: #eee; @carousel-caption-color: #eee; //== Close // //## @close-font-weight: bold; @close-color: #000; @close-text-shadow: 0 1px 0 #eee; //== Code // //## @code-color: #c7254e; @code-bg: #f9f2f4; @kbd-color: #eee; @kbd-bg: #333; @pre-bg: #f5f5f5; @pre-color: @gray-dark; @pre-border-color: #ccc; @pre-scrollable-max-height: 340px; //== Type // //## //** Horizontal offset for forms and lists. @component-offset-horizontal: 180px; //** Text muted color @text-muted: @gray-light; //** Abbreviations and acronyms border color @abbr-border-color: @gray-light; //** Headings small color @headings-small-color: @gray-light; //** Blockquote small color @blockquote-small-color: @gray-light; //** Blockquote font size @blockquote-font-size: (@font-size-base * 1.25); //** Blockquote border color @blockquote-border-color: @gray-lighter; //** Page header border color @page-header-border-color: @gray-lighter; //** Width of horizontal description list titles @dl-horizontal-offset: @component-offset-horizontal; //** Horizontal line color. @hr-border: @gray-lighter;
public/css/lib/bootstrap/variables.less
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/9b8a7cdd496c0aa8ef0d9ffd84289b8e6b237dcd
[ 0.00017758658214006573, 0.00017061686958186328, 0.00016555329784750938, 0.00017082015983760357, 0.000002963396354971337 ]
{ "id": 4, "code_window": [ "\n", " user.currentStreak = user.currentStreak || 1;\n", " user.longestStreak = user.longestStreak || 1;\n", " var challenges = user.completedCoursewares.filter(function ( obj ) {\n", " return !!obj.solution;\n", " });\n", "\n", " res.render('account/show', {\n", " title: 'Camper ' + user.profile.username + '\\'s portfolio',\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " var challenges = user.completedChallenges.filter(function ( obj ) {\n", " return obj.challengeType === 3 || obj.challengeType === 4;\n" ], "file_path": "controllers/user.js", "type": "replace", "edit_start_line_idx": 400 }
var _ = require('lodash'), async = require('async'), crypto = require('crypto'), nodemailer = require('nodemailer'), passport = require('passport'), User = require('../models/User'), secrets = require('../config/secrets'), moment = require('moment'), debug = require('debug')('freecc:cntr:userController'), resources = require('./resources'), R = require('ramda'); /** * * @param req * @param res * @returns null * Middleware to migrate users from fragmented challenge structure to unified * challenge structure */ exports.userMigration = function(req, res, next) { if (req.user && req.user.completedChallenges.length === 0) { req.user.completedChallenges = R.filter(function (elem) { return elem; // getting rid of undefined }, R.concat( req.user.completedCoursewares, req.user.completedBonfires.map(function (bonfire) { return ({ completedDate: bonfire.completedDate, _id: bonfire._id, name: bonfire.name, completedWith: bonfire.completedWith, solution: bonfire.solution, githubLink: '', verified: false, challengeType: 5 }); }) )); next(); } else { next(); } }; /** * GET /signin * Siginin page. */ exports.getSignin = function(req, res) { if (req.user) { return res.redirect('/'); } res.render('account/signin', { title: 'Free Code Camp Login' }); }; /** * POST /signin * Sign in using email and password. */ exports.postSignin = function(req, res, next) { req.assert('email', 'Email is not valid').isEmail(); req.assert('password', 'Password cannot be blank').notEmpty(); var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/signin'); } passport.authenticate('local', function(err, user, info) { if (err) { return next(err); } if (!user) { req.flash('errors', { msg: info.message }); return res.redirect('/signin'); } req.logIn(user, function(err) { if (err) { return next(err); } req.flash('success', { msg: 'Success! You are logged in.' }); if (/hotStories/.test(req.session.returnTo)) { return res.redirect('../news'); } if (/field-guide/.test(req.session.returnTo)) { return res.redirect('../field-guide'); } return res.redirect(req.session.returnTo || '/'); }); })(req, res, next); }; /** * GET /signout * Log out. */ exports.signout = function(req, res) { req.logout(); res.redirect('/'); }; /** * GET /email-signup * Signup page. */ exports.getEmailSignin = function(req, res) //noinspection Eslint { if (req.user) { return res.redirect('/'); } res.render('account/email-signin', { title: 'Sign in to your Free Code Camp Account' }); }; /** * GET /signin * Signup page. */ exports.getEmailSignup = function(req, res) { if (req.user) { return res.redirect('/'); } res.render('account/email-signup', { title: 'Create Your Free Code Camp Account' }); }; /** * POST /email-signup * Create a new local account. */ exports.postEmailSignup = function(req, res, next) { req.assert('email', 'valid email required').isEmail(); var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/email-signup'); } var possibleUserData = req.body; if (possibleUserData.password.length < 8) { req.flash('errors', { msg: 'Your password is too short' }); return res.redirect('email-signup'); } if (possibleUserData.username.length < 5 || possibleUserData.length > 20) { req.flash('errors', { msg: 'Your username must be between 5 and 20 characters' }); return res.redirect('email-signup'); } var user = new User({ email: req.body.email.trim(), password: req.body.password, profile: { username: req.body.username.trim(), picture: 'https://s3.amazonaws.com/freecodecamp/camper-image-placeholder.png' } }); User.findOne({ email: req.body.email }, function(err, existingEmail) { if (err) { return next(err); } if (existingEmail) { req.flash('errors', { msg: 'Account with that email address already exists.' }); return res.redirect('/email-signup'); } User.findOne( { 'profile.username': req.body.username }, function(err, existingUsername) { if (err) { return next(err); } if (existingUsername) { req.flash('errors', { msg: 'Account with that username already exists.' }); return res.redirect('/email-signup'); } user.save(function(err) { if (err) { return next(err); } req.logIn(user, function(err) { if (err) { return next(err); } res.redirect('/email-signup'); }); }); var transporter = nodemailer.createTransport({ service: 'Mandrill', auth: { user: secrets.mandrill.user, pass: secrets.mandrill.password } }); var mailOptions = { to: user.email, from: '[email protected]', subject: 'Welcome to Free Code Camp!', text: [ 'Greetings from San Francisco!\n\n', 'Thank you for joining our community.\n', 'Feel free to email us at this address if you have ', 'any questions about Free Code Camp.\n', 'And if you have a moment, check out our blog: ', 'blog.freecodecamp.com.\n', 'Good luck with the challenges!\n\n', '- the Volunteer Camp Counselor Team' ].join('') }; transporter.sendMail(mailOptions, function(err) { if (err) { return err; } }); }); }); }; /** * GET /account * Profile page. */ exports.getAccount = function(req, res) { res.render('account/account', { title: 'Manage your Free Code Camp Account' }); }; /** * Angular API Call */ exports.getAccountAngular = function(req, res) { res.json({ user: req.user }); }; /** * Unique username check API Call */ exports.checkUniqueUsername = function(req, res, next) { User.count( { 'profile.username': req.params.username.toLowerCase() }, function (err, data) { if (err) { return next(err); } if (data === 1) { return res.send(true); } else { return res.send(false); } }); }; /** * Existing username check */ exports.checkExistingUsername = function(req, res, next) { User.count( { 'profile.username': req.params.username.toLowerCase() }, function (err, data) { if (err) { return next(err); } if (data === 1) { return res.send(true); } else { return res.send(false); } } ); }; /** * Unique email check API Call */ exports.checkUniqueEmail = function(req, res, next) { User.count( { email: decodeURIComponent(req.params.email).toLowerCase() }, function (err, data) { if (err) { return next(err); } if (data === 1) { return res.send(true); } else { return res.send(false); } } ); }; /** * GET /campers/:username * Public Profile page. */ exports.returnUser = function(req, res, next) { User.find( { 'profile.username': req.params.username.toLowerCase() }, function(err, user) { if (err) { debug('Username err: ', err); return next(err); } if (user[0]) { user = user[0]; user.progressTimestamps = user.progressTimestamps.sort(function(a, b) { return a - b; }); var timeObject = Object.create(null); R.forEach(function(time) { timeObject[moment(time).format('YYYY-MM-DD')] = time; }, user.progressTimestamps); var tmpLongest = 1; var timeKeys = R.keys(timeObject); user.longestStreak = 0; for (var i = 1; i <= timeKeys.length; i++) { if (moment(timeKeys[i - 1]).add(1, 'd').toString() === moment(timeKeys[i]).toString()) { tmpLongest++; if (tmpLongest > user.longestStreak) { user.longestStreak = tmpLongest; } } else { tmpLongest = 1; } } timeKeys = timeKeys.reverse(); tmpLongest = 1; user.currentStreak = 1; var today = moment(Date.now()).format('YYYY-MM-DD'); if ( moment(today).toString() === moment(timeKeys[0]).toString() || moment(today).subtract(1, 'd').toString() === moment(timeKeys[0]).toString() ) { for (var _i = 1; _i <= timeKeys.length; _i++) { if ( moment(timeKeys[_i - 1]).subtract(1, 'd').toString() === moment(timeKeys[_i]).toString() ) { tmpLongest++; if (tmpLongest > user.currentStreak) { user.currentStreak = tmpLongest; } } else { break; } } } else { user.currentStreak = 1; } user.save(function(err) { if (err) { return next(err); } var data = {}; var progressTimestamps = user.progressTimestamps; progressTimestamps.forEach(function(timeStamp) { data[(timeStamp / 1000)] = 1; }); user.currentStreak = user.currentStreak || 1; user.longestStreak = user.longestStreak || 1; var challenges = user.completedCoursewares.filter(function ( obj ) { return !!obj.solution; }); res.render('account/show', { title: 'Camper ' + user.profile.username + '\'s portfolio', username: user.profile.username, name: user.profile.name, location: user.profile.location, githubProfile: user.profile.githubProfile, linkedinProfile: user.profile.linkedinProfile, codepenProfile: user.profile.codepenProfile, facebookProfile: user.profile.facebookProfile, twitterHandle: user.profile.twitterHandle, bio: user.profile.bio, picture: user.profile.picture, progressTimestamps: user.progressTimestamps, website1Link: user.portfolio.website1Link, website1Title: user.portfolio.website1Title, website1Image: user.portfolio.website1Image, website2Link: user.portfolio.website2Link, website2Title: user.portfolio.website2Title, website2Image: user.portfolio.website2Image, website3Link: user.portfolio.website3Link, website3Title: user.portfolio.website3Title, website3Image: user.portfolio.website3Image, challenges: challenges, bonfires: user.completedChallenges.filter(function(challenge) { return challenge.challengeType === 5; }), calender: data, moment: moment, longestStreak: user.longestStreak + (user.longestStreak === 1 ? ' day' : ' days'), currentStreak: user.currentStreak + (user.currentStreak === 1 ? ' day' : ' days') }); }); } else { req.flash('errors', { msg: "404: We couldn't find a page with that url. " + 'Please double check the link.' }); return res.redirect('/'); } } ); }; /** * POST /update-progress * Update profile information. */ exports.updateProgress = function(req, res, next) { User.findById(req.user.id, function(err, user) { if (err) { return next(err); } user.email = req.body.email || ''; user.profile.name = req.body.name || ''; user.profile.gender = req.body.gender || ''; user.profile.location = req.body.location || ''; user.profile.website = req.body.website || ''; user.save(function(err) { if (err) { return next(err); } req.flash('success', { msg: 'Profile information updated.' }); res.redirect('/account'); }); }); }; /** * POST /account/profile * Update profile information. */ exports.postUpdateProfile = function(req, res, next) { User.findById(req.user.id, function(err) { if (err) { return next(err); } var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/account'); } User.findOne({ email: req.body.email }, function(err, existingEmail) { if (err) { return next(err); } var user = req.user; if (existingEmail && existingEmail.email !== user.email) { req.flash('errors', { msg: 'An account with that email address already exists.' }); return res.redirect('/account'); } User.findOne( { 'profile.username': req.body.username }, function(err, existingUsername) { if (err) { return next(err); } var user = req.user; if ( existingUsername && existingUsername.profile.username !== user.profile.username ) { req.flash('errors', { msg: 'An account with that username already exists.' }); return res.redirect('/account'); } user.email = req.body.email.trim() || ''; user.profile.name = req.body.name.trim() || ''; user.profile.username = req.body.username.trim() || ''; user.profile.location = req.body.location.trim() || ''; user.profile.githubProfile = req.body.githubProfile.trim() || ''; user.profile.facebookProfile = req.body.facebookProfile.trim() || ''; user.profile.linkedinProfile = req.body.linkedinProfile.trim() || ''; user.profile.codepenProfile = req.body.codepenProfile.trim() || ''; user.profile.twitterHandle = req.body.twitterHandle.trim() || ''; user.profile.bio = req.body.bio.trim() || ''; user.profile.picture = req.body.picture.trim() || 'https://s3.amazonaws.com/freecodecamp/' + 'camper-image-placeholder.png'; user.portfolio.website1Title = req.body.website1Title.trim() || ''; user.portfolio.website1Link = req.body.website1Link.trim() || ''; user.portfolio.website1Image = req.body.website1Image.trim() || ''; user.portfolio.website2Title = req.body.website2Title.trim() || ''; user.portfolio.website2Link = req.body.website2Link.trim() || ''; user.portfolio.website2Image = req.body.website2Image.trim() || ''; user.portfolio.website3Title = req.body.website3Title.trim() || ''; user.portfolio.website3Link = req.body.website3Link.trim() || ''; user.portfolio.website3Image = req.body.website3Image.trim() || ''; user.save(function (err) { if (err) { return next(err); } resources.updateUserStoryPictures( user._id.toString(), user.profile.picture, user.profile.username, function(err) { if (err) { return next(err); } req.flash('success', { msg: 'Profile information updated.' }); res.redirect('/account'); } ); }); } ); }); }); }; /** * POST /account/password * Update current password. */ exports.postUpdatePassword = function(req, res, next) { req.assert('password', 'Password must be at least 4 characters long').len(4); req.assert('confirmPassword', 'Passwords do not match') .equals(req.body.password); var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/account'); } User.findById(req.user.id, function(err, user) { if (err) { return next(err); } user.password = req.body.password; user.save(function(err) { if (err) { return next(err); } req.flash('success', { msg: 'Password has been changed.' }); res.redirect('/account'); }); }); }; /** * POST /account/delete * Delete user account. */ exports.postDeleteAccount = function(req, res, next) { User.remove({ _id: req.user.id }, function(err) { if (err) { return next(err); } req.logout(); req.flash('info', { msg: 'Your account has been deleted.' }); res.redirect('/'); }); }; /** * GET /account/unlink/:provider * Unlink OAuth provider. */ exports.getOauthUnlink = function(req, res, next) { var provider = req.params.provider; User.findById(req.user.id, function(err, user) { if (err) { return next(err); } user[provider] = null; user.tokens = _.reject(user.tokens, function(token) { return token.kind === provider; }); user.save(function(err) { if (err) { return next(err); } req.flash('info', { msg: provider + ' account has been unlinked.' }); res.redirect('/account'); }); }); }; /** * GET /reset/:token * Reset Password page. */ exports.getReset = function(req, res, next) { if (req.isAuthenticated()) { return res.redirect('/'); } User .findOne({ resetPasswordToken: req.params.token }) .where('resetPasswordExpires').gt(Date.now()) .exec(function(err, user) { if (err) { return next(err); } if (!user) { req.flash('errors', { msg: 'Password reset token is invalid or has expired.' }); return res.redirect('/forgot'); } res.render('account/reset', { title: 'Password Reset', token: req.params.token }); }); }; /** * POST /reset/:token * Process the reset password request. */ exports.postReset = function(req, res, next) { var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('back'); } async.waterfall([ function(done) { User .findOne({ resetPasswordToken: req.params.token }) .where('resetPasswordExpires').gt(Date.now()) .exec(function(err, user) { if (err) { return next(err); } if (!user) { req.flash('errors', { msg: 'Password reset token is invalid or has expired.' }); return res.redirect('back'); } user.password = req.body.password; user.resetPasswordToken = null; user.resetPasswordExpires = null; user.save(function(err) { if (err) { return done(err); } req.logIn(user, function(err) { done(err, user); }); }); }); }, function(user, done) { var transporter = nodemailer.createTransport({ service: 'Mandrill', auth: { user: secrets.mandrill.user, pass: secrets.mandrill.password } }); var mailOptions = { to: user.email, from: '[email protected]', subject: 'Your Free Code Camp password has been changed', text: [ 'Hello,\n\n', 'This email is confirming that you requested to', 'reset your password for your Free Code Camp account.', 'This is your email:', user.email, '\n' ].join(' ') }; transporter.sendMail(mailOptions, function(err) { if (err) { return done(err); } req.flash('success', { msg: 'Success! Your password has been changed.' }); done(); }); } ], function(err) { if (err) { return next(err); } res.redirect('/'); }); }; /** * GET /forgot * Forgot Password page. */ exports.getForgot = function(req, res) { if (req.isAuthenticated()) { return res.redirect('/'); } res.render('account/forgot', { title: 'Forgot Password' }); }; /** * POST /forgot * Create a random token, then the send user an email with a reset link. */ exports.postForgot = function(req, res, next) { var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/forgot'); } async.waterfall([ function(done) { crypto.randomBytes(16, function(err, buf) { if (err) { return done(err); } var token = buf.toString('hex'); done(null, token); }); }, function(token, done) { User.findOne({ email: req.body.email.toLowerCase() }, function(err, user) { if (err) { return done(err); } if (!user) { req.flash('errors', { msg: 'No account with that email address exists.' }); return res.redirect('/forgot'); } user.resetPasswordToken = token; user.resetPasswordExpires = Date.now() + 3600000; // 1 hour user.save(function(err) { if (err) { return done(err); } done(null, token, user); }); }); }, function(token, user, done) { var transporter = nodemailer.createTransport({ service: 'Mandrill', auth: { user: secrets.mandrill.user, pass: secrets.mandrill.password } }); var mailOptions = { to: user.email, from: '[email protected]', subject: 'Reset your Free Code Camp password', text: [ 'You are receiving this email because you (or someone else)\n', 'requested we reset your Free Code Camp account\'s password.\n\n', 'Please click on the following link, or paste this into your\n', 'browser to complete the process:\n\n', 'http://', req.headers.host, '/reset/', token, '\n\n', 'If you did not request this, please ignore this email and\n', 'your password will remain unchanged.\n' ].join('') }; transporter.sendMail(mailOptions, function(err) { if (err) { return done(err); } req.flash('info', { msg: 'An e-mail has been sent to ' + user.email + ' with further instructions.' }); done(null, 'done'); }); } ], function(err) { if (err) { return next(err); } res.redirect('/forgot'); }); };
controllers/user.js
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/9b8a7cdd496c0aa8ef0d9ffd84289b8e6b237dcd
[ 0.9986653327941895, 0.03833169862627983, 0.00016310194041579962, 0.0005621733143925667, 0.18594369292259216 ]
{ "id": 4, "code_window": [ "\n", " user.currentStreak = user.currentStreak || 1;\n", " user.longestStreak = user.longestStreak || 1;\n", " var challenges = user.completedCoursewares.filter(function ( obj ) {\n", " return !!obj.solution;\n", " });\n", "\n", " res.render('account/show', {\n", " title: 'Camper ' + user.profile.username + '\\'s portfolio',\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " var challenges = user.completedChallenges.filter(function ( obj ) {\n", " return obj.challengeType === 3 || obj.challengeType === 4;\n" ], "file_path": "controllers/user.js", "type": "replace", "edit_start_line_idx": 400 }
<!doctype html> <title>CodeMirror: Indented wrapped line demo</title> <meta charset="utf-8"/> <link rel=stylesheet href="../doc/docs.css"> <link rel="stylesheet" href="../lib/codemirror.css"> <script src="../lib/codemirror.js"></script> <script src="../mode/xml/xml.js"></script> <style type="text/css"> .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;} .CodeMirror pre > * { text-indent: 0px; } </style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../doc/logo.png"></a> <ul> <li><a href="../index.html">Home</a> <li><a href="../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a class=active href="#">Indented wrapped line</a> </ul> </div> <article> <h2>Indented wrapped line demo</h2> <form><textarea id="code" name="code"> <!doctype html> <body> <h2 id="overview">Overview</h2> <p>CodeMirror is a code-editor component that can be embedded in Web pages. The core library provides <em>only</em> the editor component, no accompanying buttons, auto-completion, or other IDE functionality. It does provide a rich API on top of which such functionality can be straightforwardly implemented. See the <a href="#addons">add-ons</a> included in the distribution, and the <a href="https://github.com/jagthedrummer/codemirror-ui">CodeMirror UI</a> project, for reusable implementations of extra features.</p> <p>CodeMirror works with language-specific modes. Modes are JavaScript programs that help color (and optionally indent) text written in a given language. The distribution comes with a number of modes (see the <a href="../mode/"><code>mode/</code></a> directory), and it isn't hard to <a href="#modeapi">write new ones</a> for other languages.</p> </body> </textarea></form> <p>This page uses a hack on top of the <code>"renderLine"</code> event to make wrapped text line up with the base indentation of the line.</p> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, lineWrapping: true, mode: "text/html" }); var charWidth = editor.defaultCharWidth(), basePadding = 4; editor.on("renderLine", function(cm, line, elt) { var off = CodeMirror.countColumn(line.text, null, cm.getOption("tabSize")) * charWidth; elt.style.textIndent = "-" + off + "px"; elt.style.paddingLeft = (basePadding + off) + "px"; }); editor.refresh(); </script> </article>
public/js/lib/codemirror/demo/indentwrap.html
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/9b8a7cdd496c0aa8ef0d9ffd84289b8e6b237dcd
[ 0.00017719194875098765, 0.0001746813504723832, 0.00017254851991310716, 0.00017494673375040293, 0.00000168524309174245 ]
{ "id": 4, "code_window": [ "\n", " user.currentStreak = user.currentStreak || 1;\n", " user.longestStreak = user.longestStreak || 1;\n", " var challenges = user.completedCoursewares.filter(function ( obj ) {\n", " return !!obj.solution;\n", " });\n", "\n", " res.render('account/show', {\n", " title: 'Camper ' + user.profile.username + '\\'s portfolio',\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " var challenges = user.completedChallenges.filter(function ( obj ) {\n", " return obj.challengeType === 3 || obj.challengeType === 4;\n" ], "file_path": "controllers/user.js", "type": "replace", "edit_start_line_idx": 400 }
/****************************************************************/ /* Based on mbonaci's Brackets mbo theme */ /* https://github.com/mbonaci/global/blob/master/Mbo.tmTheme */ /* Create your own: http://tmtheme-editor.herokuapp.com */ /****************************************************************/ .cm-s-mbo.CodeMirror {background: #2c2c2c; color: #ffffec;} .cm-s-mbo div.CodeMirror-selected {background: #716C62 !important;} .cm-s-mbo .CodeMirror-gutters {background: #4e4e4e; border-right: 0px;} .cm-s-mbo .CodeMirror-guttermarker { color: white; } .cm-s-mbo .CodeMirror-guttermarker-subtle { color: grey; } .cm-s-mbo .CodeMirror-linenumber {color: #dadada;} .cm-s-mbo .CodeMirror-cursor {border-left: 1px solid #ffffec !important;} .cm-s-mbo span.cm-comment {color: #95958a;} .cm-s-mbo span.cm-atom {color: #00a8c6;} .cm-s-mbo span.cm-number {color: #00a8c6;} .cm-s-mbo span.cm-property, .cm-s-mbo span.cm-attribute {color: #9ddfe9;} .cm-s-mbo span.cm-keyword {color: #ffb928;} .cm-s-mbo span.cm-string {color: #ffcf6c;} .cm-s-mbo span.cm-string.cm-property {color: #ffffec;} .cm-s-mbo span.cm-variable {color: #ffffec;} .cm-s-mbo span.cm-variable-2 {color: #00a8c6;} .cm-s-mbo span.cm-def {color: #ffffec;} .cm-s-mbo span.cm-bracket {color: #fffffc; font-weight: bold;} .cm-s-mbo span.cm-tag {color: #9ddfe9;} .cm-s-mbo span.cm-link {color: #f54b07;} .cm-s-mbo span.cm-error {border-bottom: #636363; color: #ffffec;} .cm-s-mbo span.cm-qualifier {color: #ffffec;} .cm-s-mbo .CodeMirror-activeline-background {background: #494b41 !important;} .cm-s-mbo .CodeMirror-matchingbracket {color: #222 !important;} .cm-s-mbo .CodeMirror-matchingtag {background: rgba(255, 255, 255, .37);}
public/js/lib/codemirror/theme/mbo.css
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/9b8a7cdd496c0aa8ef0d9ffd84289b8e6b237dcd
[ 0.00017728863167576492, 0.00017649270012043417, 0.00017581444990355521, 0.0001764338812790811, 6.393261742232426e-7 ]
{ "id": 4, "code_window": [ "\n", " user.currentStreak = user.currentStreak || 1;\n", " user.longestStreak = user.longestStreak || 1;\n", " var challenges = user.completedCoursewares.filter(function ( obj ) {\n", " return !!obj.solution;\n", " });\n", "\n", " res.render('account/show', {\n", " title: 'Camper ' + user.profile.username + '\\'s portfolio',\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " var challenges = user.completedChallenges.filter(function ( obj ) {\n", " return obj.challengeType === 3 || obj.challengeType === 4;\n" ], "file_path": "controllers/user.js", "type": "replace", "edit_start_line_idx": 400 }
/* * angular-ui-bootstrap * http://angular-ui.github.io/bootstrap/ * Version: 0.12.0 - 2014-11-16 * License: MIT */ angular.module("ui.bootstrap",["ui.bootstrap.transition","ui.bootstrap.collapse","ui.bootstrap.accordion","ui.bootstrap.alert","ui.bootstrap.bindHtml","ui.bootstrap.buttons","ui.bootstrap.carousel","ui.bootstrap.dateparser","ui.bootstrap.position","ui.bootstrap.datepicker","ui.bootstrap.dropdown","ui.bootstrap.modal","ui.bootstrap.pagination","ui.bootstrap.tooltip","ui.bootstrap.popover","ui.bootstrap.progressbar","ui.bootstrap.rating","ui.bootstrap.tabs","ui.bootstrap.timepicker","ui.bootstrap.typeahead"]),angular.module("ui.bootstrap.transition",[]).factory("$transition",["$q","$timeout","$rootScope",function(a,b,c){function d(a){for(var b in a)if(void 0!==f.style[b])return a[b]}var e=function(d,f,g){g=g||{};var h=a.defer(),i=e[g.animation?"animationEndEventName":"transitionEndEventName"],j=function(){c.$apply(function(){d.unbind(i,j),h.resolve(d)})};return i&&d.bind(i,j),b(function(){angular.isString(f)?d.addClass(f):angular.isFunction(f)?f(d):angular.isObject(f)&&d.css(f),i||h.resolve(d)}),h.promise.cancel=function(){i&&d.unbind(i,j),h.reject("Transition cancelled")},h.promise},f=document.createElement("trans"),g={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd",transition:"transitionend"},h={WebkitTransition:"webkitAnimationEnd",MozTransition:"animationend",OTransition:"oAnimationEnd",transition:"animationend"};return e.transitionEndEventName=d(g),e.animationEndEventName=d(h),e}]),angular.module("ui.bootstrap.collapse",["ui.bootstrap.transition"]).directive("collapse",["$transition",function(a){return{link:function(b,c,d){function e(b){function d(){j===e&&(j=void 0)}var e=a(c,b);return j&&j.cancel(),j=e,e.then(d,d),e}function f(){k?(k=!1,g()):(c.removeClass("collapse").addClass("collapsing"),e({height:c[0].scrollHeight+"px"}).then(g))}function g(){c.removeClass("collapsing"),c.addClass("collapse in"),c.css({height:"auto"})}function h(){if(k)k=!1,i(),c.css({height:0});else{c.css({height:c[0].scrollHeight+"px"});{c[0].offsetWidth}c.removeClass("collapse in").addClass("collapsing"),e({height:0}).then(i)}}function i(){c.removeClass("collapsing"),c.addClass("collapse")}var j,k=!0;b.$watch(d.collapse,function(a){a?h():f()})}}}]),angular.module("ui.bootstrap.accordion",["ui.bootstrap.collapse"]).constant("accordionConfig",{closeOthers:!0}).controller("AccordionController",["$scope","$attrs","accordionConfig",function(a,b,c){this.groups=[],this.closeOthers=function(d){var e=angular.isDefined(b.closeOthers)?a.$eval(b.closeOthers):c.closeOthers;e&&angular.forEach(this.groups,function(a){a!==d&&(a.isOpen=!1)})},this.addGroup=function(a){var b=this;this.groups.push(a),a.$on("$destroy",function(){b.removeGroup(a)})},this.removeGroup=function(a){var b=this.groups.indexOf(a);-1!==b&&this.groups.splice(b,1)}}]).directive("accordion",function(){return{restrict:"EA",controller:"AccordionController",transclude:!0,replace:!1,templateUrl:"template/accordion/accordion.html"}}).directive("accordionGroup",function(){return{require:"^accordion",restrict:"EA",transclude:!0,replace:!0,templateUrl:"template/accordion/accordion-group.html",scope:{heading:"@",isOpen:"=?",isDisabled:"=?"},controller:function(){this.setHeading=function(a){this.heading=a}},link:function(a,b,c,d){d.addGroup(a),a.$watch("isOpen",function(b){b&&d.closeOthers(a)}),a.toggleOpen=function(){a.isDisabled||(a.isOpen=!a.isOpen)}}}}).directive("accordionHeading",function(){return{restrict:"EA",transclude:!0,template:"",replace:!0,require:"^accordionGroup",link:function(a,b,c,d,e){d.setHeading(e(a,function(){}))}}}).directive("accordionTransclude",function(){return{require:"^accordionGroup",link:function(a,b,c,d){a.$watch(function(){return d[c.accordionTransclude]},function(a){a&&(b.html(""),b.append(a))})}}}),angular.module("ui.bootstrap.alert",[]).controller("AlertController",["$scope","$attrs",function(a,b){a.closeable="close"in b,this.close=a.close}]).directive("alert",function(){return{restrict:"EA",controller:"AlertController",templateUrl:"template/alert/alert.html",transclude:!0,replace:!0,scope:{type:"@",close:"&"}}}).directive("dismissOnTimeout",["$timeout",function(a){return{require:"alert",link:function(b,c,d,e){a(function(){e.close()},parseInt(d.dismissOnTimeout,10))}}}]),angular.module("ui.bootstrap.bindHtml",[]).directive("bindHtmlUnsafe",function(){return function(a,b,c){b.addClass("ng-binding").data("$binding",c.bindHtmlUnsafe),a.$watch(c.bindHtmlUnsafe,function(a){b.html(a||"")})}}),angular.module("ui.bootstrap.buttons",[]).constant("buttonConfig",{activeClass:"active",toggleEvent:"click"}).controller("ButtonsController",["buttonConfig",function(a){this.activeClass=a.activeClass||"active",this.toggleEvent=a.toggleEvent||"click"}]).directive("btnRadio",function(){return{require:["btnRadio","ngModel"],controller:"ButtonsController",link:function(a,b,c,d){var e=d[0],f=d[1];f.$render=function(){b.toggleClass(e.activeClass,angular.equals(f.$modelValue,a.$eval(c.btnRadio)))},b.bind(e.toggleEvent,function(){var d=b.hasClass(e.activeClass);(!d||angular.isDefined(c.uncheckable))&&a.$apply(function(){f.$setViewValue(d?null:a.$eval(c.btnRadio)),f.$render()})})}}}).directive("btnCheckbox",function(){return{require:["btnCheckbox","ngModel"],controller:"ButtonsController",link:function(a,b,c,d){function e(){return g(c.btnCheckboxTrue,!0)}function f(){return g(c.btnCheckboxFalse,!1)}function g(b,c){var d=a.$eval(b);return angular.isDefined(d)?d:c}var h=d[0],i=d[1];i.$render=function(){b.toggleClass(h.activeClass,angular.equals(i.$modelValue,e()))},b.bind(h.toggleEvent,function(){a.$apply(function(){i.$setViewValue(b.hasClass(h.activeClass)?f():e()),i.$render()})})}}}),angular.module("ui.bootstrap.carousel",["ui.bootstrap.transition"]).controller("CarouselController",["$scope","$timeout","$interval","$transition",function(a,b,c,d){function e(){f();var b=+a.interval;!isNaN(b)&&b>0&&(h=c(g,b))}function f(){h&&(c.cancel(h),h=null)}function g(){var b=+a.interval;i&&!isNaN(b)&&b>0?a.next():a.pause()}var h,i,j=this,k=j.slides=a.slides=[],l=-1;j.currentSlide=null;var m=!1;j.select=a.select=function(c,f){function g(){if(!m){if(j.currentSlide&&angular.isString(f)&&!a.noTransition&&c.$element){c.$element.addClass(f);{c.$element[0].offsetWidth}angular.forEach(k,function(a){angular.extend(a,{direction:"",entering:!1,leaving:!1,active:!1})}),angular.extend(c,{direction:f,active:!0,entering:!0}),angular.extend(j.currentSlide||{},{direction:f,leaving:!0}),a.$currentTransition=d(c.$element,{}),function(b,c){a.$currentTransition.then(function(){h(b,c)},function(){h(b,c)})}(c,j.currentSlide)}else h(c,j.currentSlide);j.currentSlide=c,l=i,e()}}function h(b,c){angular.extend(b,{direction:"",active:!0,leaving:!1,entering:!1}),angular.extend(c||{},{direction:"",active:!1,leaving:!1,entering:!1}),a.$currentTransition=null}var i=k.indexOf(c);void 0===f&&(f=i>l?"next":"prev"),c&&c!==j.currentSlide&&(a.$currentTransition?(a.$currentTransition.cancel(),b(g)):g())},a.$on("$destroy",function(){m=!0}),j.indexOfSlide=function(a){return k.indexOf(a)},a.next=function(){var b=(l+1)%k.length;return a.$currentTransition?void 0:j.select(k[b],"next")},a.prev=function(){var b=0>l-1?k.length-1:l-1;return a.$currentTransition?void 0:j.select(k[b],"prev")},a.isActive=function(a){return j.currentSlide===a},a.$watch("interval",e),a.$on("$destroy",f),a.play=function(){i||(i=!0,e())},a.pause=function(){a.noPause||(i=!1,f())},j.addSlide=function(b,c){b.$element=c,k.push(b),1===k.length||b.active?(j.select(k[k.length-1]),1==k.length&&a.play()):b.active=!1},j.removeSlide=function(a){var b=k.indexOf(a);k.splice(b,1),k.length>0&&a.active?j.select(b>=k.length?k[b-1]:k[b]):l>b&&l--}}]).directive("carousel",[function(){return{restrict:"EA",transclude:!0,replace:!0,controller:"CarouselController",require:"carousel",templateUrl:"template/carousel/carousel.html",scope:{interval:"=",noTransition:"=",noPause:"="}}}]).directive("slide",function(){return{require:"^carousel",restrict:"EA",transclude:!0,replace:!0,templateUrl:"template/carousel/slide.html",scope:{active:"=?"},link:function(a,b,c,d){d.addSlide(a,b),a.$on("$destroy",function(){d.removeSlide(a)}),a.$watch("active",function(b){b&&d.select(a)})}}}),angular.module("ui.bootstrap.dateparser",[]).service("dateParser",["$locale","orderByFilter",function(a,b){function c(a){var c=[],d=a.split("");return angular.forEach(e,function(b,e){var f=a.indexOf(e);if(f>-1){a=a.split(""),d[f]="("+b.regex+")",a[f]="$";for(var g=f+1,h=f+e.length;h>g;g++)d[g]="",a[g]="$";a=a.join(""),c.push({index:f,apply:b.apply})}}),{regex:new RegExp("^"+d.join("")+"$"),map:b(c,"index")}}function d(a,b,c){return 1===b&&c>28?29===c&&(a%4===0&&a%100!==0||a%400===0):3===b||5===b||8===b||10===b?31>c:!0}this.parsers={};var e={yyyy:{regex:"\\d{4}",apply:function(a){this.year=+a}},yy:{regex:"\\d{2}",apply:function(a){this.year=+a+2e3}},y:{regex:"\\d{1,4}",apply:function(a){this.year=+a}},MMMM:{regex:a.DATETIME_FORMATS.MONTH.join("|"),apply:function(b){this.month=a.DATETIME_FORMATS.MONTH.indexOf(b)}},MMM:{regex:a.DATETIME_FORMATS.SHORTMONTH.join("|"),apply:function(b){this.month=a.DATETIME_FORMATS.SHORTMONTH.indexOf(b)}},MM:{regex:"0[1-9]|1[0-2]",apply:function(a){this.month=a-1}},M:{regex:"[1-9]|1[0-2]",apply:function(a){this.month=a-1}},dd:{regex:"[0-2][0-9]{1}|3[0-1]{1}",apply:function(a){this.date=+a}},d:{regex:"[1-2]?[0-9]{1}|3[0-1]{1}",apply:function(a){this.date=+a}},EEEE:{regex:a.DATETIME_FORMATS.DAY.join("|")},EEE:{regex:a.DATETIME_FORMATS.SHORTDAY.join("|")}};this.parse=function(b,e){if(!angular.isString(b)||!e)return b;e=a.DATETIME_FORMATS[e]||e,this.parsers[e]||(this.parsers[e]=c(e));var f=this.parsers[e],g=f.regex,h=f.map,i=b.match(g);if(i&&i.length){for(var j,k={year:1900,month:0,date:1,hours:0},l=1,m=i.length;m>l;l++){var n=h[l-1];n.apply&&n.apply.call(k,i[l])}return d(k.year,k.month,k.date)&&(j=new Date(k.year,k.month,k.date,k.hours)),j}}}]),angular.module("ui.bootstrap.position",[]).factory("$position",["$document","$window",function(a,b){function c(a,c){return a.currentStyle?a.currentStyle[c]:b.getComputedStyle?b.getComputedStyle(a)[c]:a.style[c]}function d(a){return"static"===(c(a,"position")||"static")}var e=function(b){for(var c=a[0],e=b.offsetParent||c;e&&e!==c&&d(e);)e=e.offsetParent;return e||c};return{position:function(b){var c=this.offset(b),d={top:0,left:0},f=e(b[0]);f!=a[0]&&(d=this.offset(angular.element(f)),d.top+=f.clientTop-f.scrollTop,d.left+=f.clientLeft-f.scrollLeft);var g=b[0].getBoundingClientRect();return{width:g.width||b.prop("offsetWidth"),height:g.height||b.prop("offsetHeight"),top:c.top-d.top,left:c.left-d.left}},offset:function(c){var d=c[0].getBoundingClientRect();return{width:d.width||c.prop("offsetWidth"),height:d.height||c.prop("offsetHeight"),top:d.top+(b.pageYOffset||a[0].documentElement.scrollTop),left:d.left+(b.pageXOffset||a[0].documentElement.scrollLeft)}},positionElements:function(a,b,c,d){var e,f,g,h,i=c.split("-"),j=i[0],k=i[1]||"center";e=d?this.offset(a):this.position(a),f=b.prop("offsetWidth"),g=b.prop("offsetHeight");var l={center:function(){return e.left+e.width/2-f/2},left:function(){return e.left},right:function(){return e.left+e.width}},m={center:function(){return e.top+e.height/2-g/2},top:function(){return e.top},bottom:function(){return e.top+e.height}};switch(j){case"right":h={top:m[k](),left:l[j]()};break;case"left":h={top:m[k](),left:e.left-f};break;case"bottom":h={top:m[j](),left:l[k]()};break;default:h={top:e.top-g,left:l[k]()}}return h}}}]),angular.module("ui.bootstrap.datepicker",["ui.bootstrap.dateparser","ui.bootstrap.position"]).constant("datepickerConfig",{formatDay:"dd",formatMonth:"MMMM",formatYear:"yyyy",formatDayHeader:"EEE",formatDayTitle:"MMMM yyyy",formatMonthTitle:"yyyy",datepickerMode:"day",minMode:"day",maxMode:"year",showWeeks:!0,startingDay:0,yearRange:20,minDate:null,maxDate:null}).controller("DatepickerController",["$scope","$attrs","$parse","$interpolate","$timeout","$log","dateFilter","datepickerConfig",function(a,b,c,d,e,f,g,h){var i=this,j={$setViewValue:angular.noop};this.modes=["day","month","year"],angular.forEach(["formatDay","formatMonth","formatYear","formatDayHeader","formatDayTitle","formatMonthTitle","minMode","maxMode","showWeeks","startingDay","yearRange"],function(c,e){i[c]=angular.isDefined(b[c])?8>e?d(b[c])(a.$parent):a.$parent.$eval(b[c]):h[c]}),angular.forEach(["minDate","maxDate"],function(d){b[d]?a.$parent.$watch(c(b[d]),function(a){i[d]=a?new Date(a):null,i.refreshView()}):i[d]=h[d]?new Date(h[d]):null}),a.datepickerMode=a.datepickerMode||h.datepickerMode,a.uniqueId="datepicker-"+a.$id+"-"+Math.floor(1e4*Math.random()),this.activeDate=angular.isDefined(b.initDate)?a.$parent.$eval(b.initDate):new Date,a.isActive=function(b){return 0===i.compare(b.date,i.activeDate)?(a.activeDateId=b.uid,!0):!1},this.init=function(a){j=a,j.$render=function(){i.render()}},this.render=function(){if(j.$modelValue){var a=new Date(j.$modelValue),b=!isNaN(a);b?this.activeDate=a:f.error('Datepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.'),j.$setValidity("date",b)}this.refreshView()},this.refreshView=function(){if(this.element){this._refreshView();var a=j.$modelValue?new Date(j.$modelValue):null;j.$setValidity("date-disabled",!a||this.element&&!this.isDisabled(a))}},this.createDateObject=function(a,b){var c=j.$modelValue?new Date(j.$modelValue):null;return{date:a,label:g(a,b),selected:c&&0===this.compare(a,c),disabled:this.isDisabled(a),current:0===this.compare(a,new Date)}},this.isDisabled=function(c){return this.minDate&&this.compare(c,this.minDate)<0||this.maxDate&&this.compare(c,this.maxDate)>0||b.dateDisabled&&a.dateDisabled({date:c,mode:a.datepickerMode})},this.split=function(a,b){for(var c=[];a.length>0;)c.push(a.splice(0,b));return c},a.select=function(b){if(a.datepickerMode===i.minMode){var c=j.$modelValue?new Date(j.$modelValue):new Date(0,0,0,0,0,0,0);c.setFullYear(b.getFullYear(),b.getMonth(),b.getDate()),j.$setViewValue(c),j.$render()}else i.activeDate=b,a.datepickerMode=i.modes[i.modes.indexOf(a.datepickerMode)-1]},a.move=function(a){var b=i.activeDate.getFullYear()+a*(i.step.years||0),c=i.activeDate.getMonth()+a*(i.step.months||0);i.activeDate.setFullYear(b,c,1),i.refreshView()},a.toggleMode=function(b){b=b||1,a.datepickerMode===i.maxMode&&1===b||a.datepickerMode===i.minMode&&-1===b||(a.datepickerMode=i.modes[i.modes.indexOf(a.datepickerMode)+b])},a.keys={13:"enter",32:"space",33:"pageup",34:"pagedown",35:"end",36:"home",37:"left",38:"up",39:"right",40:"down"};var k=function(){e(function(){i.element[0].focus()},0,!1)};a.$on("datepicker.focus",k),a.keydown=function(b){var c=a.keys[b.which];if(c&&!b.shiftKey&&!b.altKey)if(b.preventDefault(),b.stopPropagation(),"enter"===c||"space"===c){if(i.isDisabled(i.activeDate))return;a.select(i.activeDate),k()}else!b.ctrlKey||"up"!==c&&"down"!==c?(i.handleKeyDown(c,b),i.refreshView()):(a.toggleMode("up"===c?1:-1),k())}}]).directive("datepicker",function(){return{restrict:"EA",replace:!0,templateUrl:"template/datepicker/datepicker.html",scope:{datepickerMode:"=?",dateDisabled:"&"},require:["datepicker","?^ngModel"],controller:"DatepickerController",link:function(a,b,c,d){var e=d[0],f=d[1];f&&e.init(f)}}}).directive("daypicker",["dateFilter",function(a){return{restrict:"EA",replace:!0,templateUrl:"template/datepicker/day.html",require:"^datepicker",link:function(b,c,d,e){function f(a,b){return 1!==b||a%4!==0||a%100===0&&a%400!==0?i[b]:29}function g(a,b){var c=new Array(b),d=new Date(a),e=0;for(d.setHours(12);b>e;)c[e++]=new Date(d),d.setDate(d.getDate()+1);return c}function h(a){var b=new Date(a);b.setDate(b.getDate()+4-(b.getDay()||7));var c=b.getTime();return b.setMonth(0),b.setDate(1),Math.floor(Math.round((c-b)/864e5)/7)+1}b.showWeeks=e.showWeeks,e.step={months:1},e.element=c;var i=[31,28,31,30,31,30,31,31,30,31,30,31];e._refreshView=function(){var c=e.activeDate.getFullYear(),d=e.activeDate.getMonth(),f=new Date(c,d,1),i=e.startingDay-f.getDay(),j=i>0?7-i:-i,k=new Date(f);j>0&&k.setDate(-j+1);for(var l=g(k,42),m=0;42>m;m++)l[m]=angular.extend(e.createDateObject(l[m],e.formatDay),{secondary:l[m].getMonth()!==d,uid:b.uniqueId+"-"+m});b.labels=new Array(7);for(var n=0;7>n;n++)b.labels[n]={abbr:a(l[n].date,e.formatDayHeader),full:a(l[n].date,"EEEE")};if(b.title=a(e.activeDate,e.formatDayTitle),b.rows=e.split(l,7),b.showWeeks){b.weekNumbers=[];for(var o=h(b.rows[0][0].date),p=b.rows.length;b.weekNumbers.push(o++)<p;);}},e.compare=function(a,b){return new Date(a.getFullYear(),a.getMonth(),a.getDate())-new Date(b.getFullYear(),b.getMonth(),b.getDate())},e.handleKeyDown=function(a){var b=e.activeDate.getDate();if("left"===a)b-=1;else if("up"===a)b-=7;else if("right"===a)b+=1;else if("down"===a)b+=7;else if("pageup"===a||"pagedown"===a){var c=e.activeDate.getMonth()+("pageup"===a?-1:1);e.activeDate.setMonth(c,1),b=Math.min(f(e.activeDate.getFullYear(),e.activeDate.getMonth()),b)}else"home"===a?b=1:"end"===a&&(b=f(e.activeDate.getFullYear(),e.activeDate.getMonth()));e.activeDate.setDate(b)},e.refreshView()}}}]).directive("monthpicker",["dateFilter",function(a){return{restrict:"EA",replace:!0,templateUrl:"template/datepicker/month.html",require:"^datepicker",link:function(b,c,d,e){e.step={years:1},e.element=c,e._refreshView=function(){for(var c=new Array(12),d=e.activeDate.getFullYear(),f=0;12>f;f++)c[f]=angular.extend(e.createDateObject(new Date(d,f,1),e.formatMonth),{uid:b.uniqueId+"-"+f});b.title=a(e.activeDate,e.formatMonthTitle),b.rows=e.split(c,3)},e.compare=function(a,b){return new Date(a.getFullYear(),a.getMonth())-new Date(b.getFullYear(),b.getMonth())},e.handleKeyDown=function(a){var b=e.activeDate.getMonth();if("left"===a)b-=1;else if("up"===a)b-=3;else if("right"===a)b+=1;else if("down"===a)b+=3;else if("pageup"===a||"pagedown"===a){var c=e.activeDate.getFullYear()+("pageup"===a?-1:1);e.activeDate.setFullYear(c)}else"home"===a?b=0:"end"===a&&(b=11);e.activeDate.setMonth(b)},e.refreshView()}}}]).directive("yearpicker",["dateFilter",function(){return{restrict:"EA",replace:!0,templateUrl:"template/datepicker/year.html",require:"^datepicker",link:function(a,b,c,d){function e(a){return parseInt((a-1)/f,10)*f+1}var f=d.yearRange;d.step={years:f},d.element=b,d._refreshView=function(){for(var b=new Array(f),c=0,g=e(d.activeDate.getFullYear());f>c;c++)b[c]=angular.extend(d.createDateObject(new Date(g+c,0,1),d.formatYear),{uid:a.uniqueId+"-"+c});a.title=[b[0].label,b[f-1].label].join(" - "),a.rows=d.split(b,5)},d.compare=function(a,b){return a.getFullYear()-b.getFullYear()},d.handleKeyDown=function(a){var b=d.activeDate.getFullYear();"left"===a?b-=1:"up"===a?b-=5:"right"===a?b+=1:"down"===a?b+=5:"pageup"===a||"pagedown"===a?b+=("pageup"===a?-1:1)*d.step.years:"home"===a?b=e(d.activeDate.getFullYear()):"end"===a&&(b=e(d.activeDate.getFullYear())+f-1),d.activeDate.setFullYear(b)},d.refreshView()}}}]).constant("datepickerPopupConfig",{datepickerPopup:"yyyy-MM-dd",currentText:"Today",clearText:"Clear",closeText:"Done",closeOnDateSelection:!0,appendToBody:!1,showButtonBar:!0}).directive("datepickerPopup",["$compile","$parse","$document","$position","dateFilter","dateParser","datepickerPopupConfig",function(a,b,c,d,e,f,g){return{restrict:"EA",require:"ngModel",scope:{isOpen:"=?",currentText:"@",clearText:"@",closeText:"@",dateDisabled:"&"},link:function(h,i,j,k){function l(a){return a.replace(/([A-Z])/g,function(a){return"-"+a.toLowerCase()})}function m(a){if(a){if(angular.isDate(a)&&!isNaN(a))return k.$setValidity("date",!0),a;if(angular.isString(a)){var b=f.parse(a,n)||new Date(a);return isNaN(b)?void k.$setValidity("date",!1):(k.$setValidity("date",!0),b)}return void k.$setValidity("date",!1)}return k.$setValidity("date",!0),null}var n,o=angular.isDefined(j.closeOnDateSelection)?h.$parent.$eval(j.closeOnDateSelection):g.closeOnDateSelection,p=angular.isDefined(j.datepickerAppendToBody)?h.$parent.$eval(j.datepickerAppendToBody):g.appendToBody;h.showButtonBar=angular.isDefined(j.showButtonBar)?h.$parent.$eval(j.showButtonBar):g.showButtonBar,h.getText=function(a){return h[a+"Text"]||g[a+"Text"]},j.$observe("datepickerPopup",function(a){n=a||g.datepickerPopup,k.$render()});var q=angular.element("<div datepicker-popup-wrap><div datepicker></div></div>");q.attr({"ng-model":"date","ng-change":"dateSelection()"});var r=angular.element(q.children()[0]);j.datepickerOptions&&angular.forEach(h.$parent.$eval(j.datepickerOptions),function(a,b){r.attr(l(b),a)}),h.watchData={},angular.forEach(["minDate","maxDate","datepickerMode"],function(a){if(j[a]){var c=b(j[a]);if(h.$parent.$watch(c,function(b){h.watchData[a]=b}),r.attr(l(a),"watchData."+a),"datepickerMode"===a){var d=c.assign;h.$watch("watchData."+a,function(a,b){a!==b&&d(h.$parent,a)})}}}),j.dateDisabled&&r.attr("date-disabled","dateDisabled({ date: date, mode: mode })"),k.$parsers.unshift(m),h.dateSelection=function(a){angular.isDefined(a)&&(h.date=a),k.$setViewValue(h.date),k.$render(),o&&(h.isOpen=!1,i[0].focus())},i.bind("input change keyup",function(){h.$apply(function(){h.date=k.$modelValue})}),k.$render=function(){var a=k.$viewValue?e(k.$viewValue,n):"";i.val(a),h.date=m(k.$modelValue)};var s=function(a){h.isOpen&&a.target!==i[0]&&h.$apply(function(){h.isOpen=!1})},t=function(a){h.keydown(a)};i.bind("keydown",t),h.keydown=function(a){27===a.which?(a.preventDefault(),a.stopPropagation(),h.close()):40!==a.which||h.isOpen||(h.isOpen=!0)},h.$watch("isOpen",function(a){a?(h.$broadcast("datepicker.focus"),h.position=p?d.offset(i):d.position(i),h.position.top=h.position.top+i.prop("offsetHeight"),c.bind("click",s)):c.unbind("click",s)}),h.select=function(a){if("today"===a){var b=new Date;angular.isDate(k.$modelValue)?(a=new Date(k.$modelValue),a.setFullYear(b.getFullYear(),b.getMonth(),b.getDate())):a=new Date(b.setHours(0,0,0,0))}h.dateSelection(a)},h.close=function(){h.isOpen=!1,i[0].focus()};var u=a(q)(h);q.remove(),p?c.find("body").append(u):i.after(u),h.$on("$destroy",function(){u.remove(),i.unbind("keydown",t),c.unbind("click",s)})}}}]).directive("datepickerPopupWrap",function(){return{restrict:"EA",replace:!0,transclude:!0,templateUrl:"template/datepicker/popup.html",link:function(a,b){b.bind("click",function(a){a.preventDefault(),a.stopPropagation()})}}}),angular.module("ui.bootstrap.dropdown",[]).constant("dropdownConfig",{openClass:"open"}).service("dropdownService",["$document",function(a){var b=null;this.open=function(e){b||(a.bind("click",c),a.bind("keydown",d)),b&&b!==e&&(b.isOpen=!1),b=e},this.close=function(e){b===e&&(b=null,a.unbind("click",c),a.unbind("keydown",d))};var c=function(a){if(b){var c=b.getToggleElement();a&&c&&c[0].contains(a.target)||b.$apply(function(){b.isOpen=!1})}},d=function(a){27===a.which&&(b.focusToggleElement(),c())}}]).controller("DropdownController",["$scope","$attrs","$parse","dropdownConfig","dropdownService","$animate",function(a,b,c,d,e,f){var g,h=this,i=a.$new(),j=d.openClass,k=angular.noop,l=b.onToggle?c(b.onToggle):angular.noop;this.init=function(d){h.$element=d,b.isOpen&&(g=c(b.isOpen),k=g.assign,a.$watch(g,function(a){i.isOpen=!!a}))},this.toggle=function(a){return i.isOpen=arguments.length?!!a:!i.isOpen},this.isOpen=function(){return i.isOpen},i.getToggleElement=function(){return h.toggleElement},i.focusToggleElement=function(){h.toggleElement&&h.toggleElement[0].focus()},i.$watch("isOpen",function(b,c){f[b?"addClass":"removeClass"](h.$element,j),b?(i.focusToggleElement(),e.open(i)):e.close(i),k(a,b),angular.isDefined(b)&&b!==c&&l(a,{open:!!b})}),a.$on("$locationChangeSuccess",function(){i.isOpen=!1}),a.$on("$destroy",function(){i.$destroy()})}]).directive("dropdown",function(){return{controller:"DropdownController",link:function(a,b,c,d){d.init(b)}}}).directive("dropdownToggle",function(){return{require:"?^dropdown",link:function(a,b,c,d){if(d){d.toggleElement=b;var e=function(e){e.preventDefault(),b.hasClass("disabled")||c.disabled||a.$apply(function(){d.toggle()})};b.bind("click",e),b.attr({"aria-haspopup":!0,"aria-expanded":!1}),a.$watch(d.isOpen,function(a){b.attr("aria-expanded",!!a)}),a.$on("$destroy",function(){b.unbind("click",e)})}}}}),angular.module("ui.bootstrap.modal",["ui.bootstrap.transition"]).factory("$$stackedMap",function(){return{createNew:function(){var a=[];return{add:function(b,c){a.push({key:b,value:c})},get:function(b){for(var c=0;c<a.length;c++)if(b==a[c].key)return a[c]},keys:function(){for(var b=[],c=0;c<a.length;c++)b.push(a[c].key);return b},top:function(){return a[a.length-1]},remove:function(b){for(var c=-1,d=0;d<a.length;d++)if(b==a[d].key){c=d;break}return a.splice(c,1)[0]},removeTop:function(){return a.splice(a.length-1,1)[0]},length:function(){return a.length}}}}}).directive("modalBackdrop",["$timeout",function(a){return{restrict:"EA",replace:!0,templateUrl:"template/modal/backdrop.html",link:function(b,c,d){b.backdropClass=d.backdropClass||"",b.animate=!1,a(function(){b.animate=!0})}}}]).directive("modalWindow",["$modalStack","$timeout",function(a,b){return{restrict:"EA",scope:{index:"@",animate:"="},replace:!0,transclude:!0,templateUrl:function(a,b){return b.templateUrl||"template/modal/window.html"},link:function(c,d,e){d.addClass(e.windowClass||""),c.size=e.size,b(function(){c.animate=!0,d[0].querySelectorAll("[autofocus]").length||d[0].focus()}),c.close=function(b){var c=a.getTop();c&&c.value.backdrop&&"static"!=c.value.backdrop&&b.target===b.currentTarget&&(b.preventDefault(),b.stopPropagation(),a.dismiss(c.key,"backdrop click"))}}}}]).directive("modalTransclude",function(){return{link:function(a,b,c,d,e){e(a.$parent,function(a){b.empty(),b.append(a)})}}}).factory("$modalStack",["$transition","$timeout","$document","$compile","$rootScope","$$stackedMap",function(a,b,c,d,e,f){function g(){for(var a=-1,b=n.keys(),c=0;c<b.length;c++)n.get(b[c]).value.backdrop&&(a=c);return a}function h(a){var b=c.find("body").eq(0),d=n.get(a).value;n.remove(a),j(d.modalDomEl,d.modalScope,300,function(){d.modalScope.$destroy(),b.toggleClass(m,n.length()>0),i()})}function i(){if(k&&-1==g()){var a=l;j(k,l,150,function(){a.$destroy(),a=null}),k=void 0,l=void 0}}function j(c,d,e,f){function g(){g.done||(g.done=!0,c.remove(),f&&f())}d.animate=!1;var h=a.transitionEndEventName;if(h){var i=b(g,e);c.bind(h,function(){b.cancel(i),g(),d.$apply()})}else b(g)}var k,l,m="modal-open",n=f.createNew(),o={};return e.$watch(g,function(a){l&&(l.index=a)}),c.bind("keydown",function(a){var b;27===a.which&&(b=n.top(),b&&b.value.keyboard&&(a.preventDefault(),e.$apply(function(){o.dismiss(b.key,"escape key press")})))}),o.open=function(a,b){n.add(a,{deferred:b.deferred,modalScope:b.scope,backdrop:b.backdrop,keyboard:b.keyboard});var f=c.find("body").eq(0),h=g();if(h>=0&&!k){l=e.$new(!0),l.index=h;var i=angular.element("<div modal-backdrop></div>");i.attr("backdrop-class",b.backdropClass),k=d(i)(l),f.append(k)}var j=angular.element("<div modal-window></div>");j.attr({"template-url":b.windowTemplateUrl,"window-class":b.windowClass,size:b.size,index:n.length()-1,animate:"animate"}).html(b.content);var o=d(j)(b.scope);n.top().value.modalDomEl=o,f.append(o),f.addClass(m)},o.close=function(a,b){var c=n.get(a);c&&(c.value.deferred.resolve(b),h(a))},o.dismiss=function(a,b){var c=n.get(a);c&&(c.value.deferred.reject(b),h(a))},o.dismissAll=function(a){for(var b=this.getTop();b;)this.dismiss(b.key,a),b=this.getTop()},o.getTop=function(){return n.top()},o}]).provider("$modal",function(){var a={options:{backdrop:!0,keyboard:!0},$get:["$injector","$rootScope","$q","$http","$templateCache","$controller","$modalStack",function(b,c,d,e,f,g,h){function i(a){return a.template?d.when(a.template):e.get(angular.isFunction(a.templateUrl)?a.templateUrl():a.templateUrl,{cache:f}).then(function(a){return a.data})}function j(a){var c=[];return angular.forEach(a,function(a){(angular.isFunction(a)||angular.isArray(a))&&c.push(d.when(b.invoke(a)))}),c}var k={};return k.open=function(b){var e=d.defer(),f=d.defer(),k={result:e.promise,opened:f.promise,close:function(a){h.close(k,a)},dismiss:function(a){h.dismiss(k,a)}};if(b=angular.extend({},a.options,b),b.resolve=b.resolve||{},!b.template&&!b.templateUrl)throw new Error("One of template or templateUrl options is required.");var l=d.all([i(b)].concat(j(b.resolve)));return l.then(function(a){var d=(b.scope||c).$new();d.$close=k.close,d.$dismiss=k.dismiss;var f,i={},j=1;b.controller&&(i.$scope=d,i.$modalInstance=k,angular.forEach(b.resolve,function(b,c){i[c]=a[j++]}),f=g(b.controller,i),b.controllerAs&&(d[b.controllerAs]=f)),h.open(k,{scope:d,deferred:e,content:a[0],backdrop:b.backdrop,keyboard:b.keyboard,backdropClass:b.backdropClass,windowClass:b.windowClass,windowTemplateUrl:b.windowTemplateUrl,size:b.size})},function(a){e.reject(a)}),l.then(function(){f.resolve(!0)},function(){f.reject(!1)}),k},k}]};return a}),angular.module("ui.bootstrap.pagination",[]).controller("PaginationController",["$scope","$attrs","$parse",function(a,b,c){var d=this,e={$setViewValue:angular.noop},f=b.numPages?c(b.numPages).assign:angular.noop;this.init=function(f,g){e=f,this.config=g,e.$render=function(){d.render()},b.itemsPerPage?a.$parent.$watch(c(b.itemsPerPage),function(b){d.itemsPerPage=parseInt(b,10),a.totalPages=d.calculateTotalPages()}):this.itemsPerPage=g.itemsPerPage},this.calculateTotalPages=function(){var b=this.itemsPerPage<1?1:Math.ceil(a.totalItems/this.itemsPerPage);return Math.max(b||0,1)},this.render=function(){a.page=parseInt(e.$viewValue,10)||1},a.selectPage=function(b){a.page!==b&&b>0&&b<=a.totalPages&&(e.$setViewValue(b),e.$render())},a.getText=function(b){return a[b+"Text"]||d.config[b+"Text"]},a.noPrevious=function(){return 1===a.page},a.noNext=function(){return a.page===a.totalPages},a.$watch("totalItems",function(){a.totalPages=d.calculateTotalPages()}),a.$watch("totalPages",function(b){f(a.$parent,b),a.page>b?a.selectPage(b):e.$render()})}]).constant("paginationConfig",{itemsPerPage:10,boundaryLinks:!1,directionLinks:!0,firstText:"First",previousText:"Previous",nextText:"Next",lastText:"Last",rotate:!0}).directive("pagination",["$parse","paginationConfig",function(a,b){return{restrict:"EA",scope:{totalItems:"=",firstText:"@",previousText:"@",nextText:"@",lastText:"@"},require:["pagination","?ngModel"],controller:"PaginationController",templateUrl:"template/pagination/pagination.html",replace:!0,link:function(c,d,e,f){function g(a,b,c){return{number:a,text:b,active:c}}function h(a,b){var c=[],d=1,e=b,f=angular.isDefined(k)&&b>k;f&&(l?(d=Math.max(a-Math.floor(k/2),1),e=d+k-1,e>b&&(e=b,d=e-k+1)):(d=(Math.ceil(a/k)-1)*k+1,e=Math.min(d+k-1,b)));for(var h=d;e>=h;h++){var i=g(h,h,h===a);c.push(i)}if(f&&!l){if(d>1){var j=g(d-1,"...",!1);c.unshift(j)}if(b>e){var m=g(e+1,"...",!1);c.push(m)}}return c}var i=f[0],j=f[1];if(j){var k=angular.isDefined(e.maxSize)?c.$parent.$eval(e.maxSize):b.maxSize,l=angular.isDefined(e.rotate)?c.$parent.$eval(e.rotate):b.rotate;c.boundaryLinks=angular.isDefined(e.boundaryLinks)?c.$parent.$eval(e.boundaryLinks):b.boundaryLinks,c.directionLinks=angular.isDefined(e.directionLinks)?c.$parent.$eval(e.directionLinks):b.directionLinks,i.init(j,b),e.maxSize&&c.$parent.$watch(a(e.maxSize),function(a){k=parseInt(a,10),i.render()});var m=i.render;i.render=function(){m(),c.page>0&&c.page<=c.totalPages&&(c.pages=h(c.page,c.totalPages))}}}}}]).constant("pagerConfig",{itemsPerPage:10,previousText:"« Previous",nextText:"Next »",align:!0}).directive("pager",["pagerConfig",function(a){return{restrict:"EA",scope:{totalItems:"=",previousText:"@",nextText:"@"},require:["pager","?ngModel"],controller:"PaginationController",templateUrl:"template/pagination/pager.html",replace:!0,link:function(b,c,d,e){var f=e[0],g=e[1];g&&(b.align=angular.isDefined(d.align)?b.$parent.$eval(d.align):a.align,f.init(g,a))}}}]),angular.module("ui.bootstrap.tooltip",["ui.bootstrap.position","ui.bootstrap.bindHtml"]).provider("$tooltip",function(){function a(a){var b=/[A-Z]/g,c="-";return a.replace(b,function(a,b){return(b?c:"")+a.toLowerCase() })}var b={placement:"top",animation:!0,popupDelay:0},c={mouseenter:"mouseleave",click:"click",focus:"blur"},d={};this.options=function(a){angular.extend(d,a)},this.setTriggers=function(a){angular.extend(c,a)},this.$get=["$window","$compile","$timeout","$document","$position","$interpolate",function(e,f,g,h,i,j){return function(e,k,l){function m(a){var b=a||n.trigger||l,d=c[b]||b;return{show:b,hide:d}}var n=angular.extend({},b,d),o=a(e),p=j.startSymbol(),q=j.endSymbol(),r="<div "+o+'-popup title="'+p+"title"+q+'" content="'+p+"content"+q+'" placement="'+p+"placement"+q+'" animation="animation" is-open="isOpen"></div>';return{restrict:"EA",compile:function(){var a=f(r);return function(b,c,d){function f(){D.isOpen?l():j()}function j(){(!C||b.$eval(d[k+"Enable"]))&&(s(),D.popupDelay?z||(z=g(o,D.popupDelay,!1),z.then(function(a){a()})):o()())}function l(){b.$apply(function(){p()})}function o(){return z=null,y&&(g.cancel(y),y=null),D.content?(q(),w.css({top:0,left:0,display:"block"}),A?h.find("body").append(w):c.after(w),E(),D.isOpen=!0,D.$digest(),E):angular.noop}function p(){D.isOpen=!1,g.cancel(z),z=null,D.animation?y||(y=g(r,500)):r()}function q(){w&&r(),x=D.$new(),w=a(x,angular.noop)}function r(){y=null,w&&(w.remove(),w=null),x&&(x.$destroy(),x=null)}function s(){t(),u()}function t(){var a=d[k+"Placement"];D.placement=angular.isDefined(a)?a:n.placement}function u(){var a=d[k+"PopupDelay"],b=parseInt(a,10);D.popupDelay=isNaN(b)?n.popupDelay:b}function v(){var a=d[k+"Trigger"];F(),B=m(a),B.show===B.hide?c.bind(B.show,f):(c.bind(B.show,j),c.bind(B.hide,l))}var w,x,y,z,A=angular.isDefined(n.appendToBody)?n.appendToBody:!1,B=m(void 0),C=angular.isDefined(d[k+"Enable"]),D=b.$new(!0),E=function(){var a=i.positionElements(c,w,D.placement,A);a.top+="px",a.left+="px",w.css(a)};D.isOpen=!1,d.$observe(e,function(a){D.content=a,!a&&D.isOpen&&p()}),d.$observe(k+"Title",function(a){D.title=a});var F=function(){c.unbind(B.show,j),c.unbind(B.hide,l)};v();var G=b.$eval(d[k+"Animation"]);D.animation=angular.isDefined(G)?!!G:n.animation;var H=b.$eval(d[k+"AppendToBody"]);A=angular.isDefined(H)?H:A,A&&b.$on("$locationChangeSuccess",function(){D.isOpen&&p()}),b.$on("$destroy",function(){g.cancel(y),g.cancel(z),F(),r(),D=null})}}}}}]}).directive("tooltipPopup",function(){return{restrict:"EA",replace:!0,scope:{content:"@",placement:"@",animation:"&",isOpen:"&"},templateUrl:"template/tooltip/tooltip-popup.html"}}).directive("tooltip",["$tooltip",function(a){return a("tooltip","tooltip","mouseenter")}]).directive("tooltipHtmlUnsafePopup",function(){return{restrict:"EA",replace:!0,scope:{content:"@",placement:"@",animation:"&",isOpen:"&"},templateUrl:"template/tooltip/tooltip-html-unsafe-popup.html"}}).directive("tooltipHtmlUnsafe",["$tooltip",function(a){return a("tooltipHtmlUnsafe","tooltip","mouseenter")}]),angular.module("ui.bootstrap.popover",["ui.bootstrap.tooltip"]).directive("popoverPopup",function(){return{restrict:"EA",replace:!0,scope:{title:"@",content:"@",placement:"@",animation:"&",isOpen:"&"},templateUrl:"template/popover/popover.html"}}).directive("popover",["$tooltip",function(a){return a("popover","popover","click")}]),angular.module("ui.bootstrap.progressbar",[]).constant("progressConfig",{animate:!0,max:100}).controller("ProgressController",["$scope","$attrs","progressConfig",function(a,b,c){var d=this,e=angular.isDefined(b.animate)?a.$parent.$eval(b.animate):c.animate;this.bars=[],a.max=angular.isDefined(b.max)?a.$parent.$eval(b.max):c.max,this.addBar=function(b,c){e||c.css({transition:"none"}),this.bars.push(b),b.$watch("value",function(c){b.percent=+(100*c/a.max).toFixed(2)}),b.$on("$destroy",function(){c=null,d.removeBar(b)})},this.removeBar=function(a){this.bars.splice(this.bars.indexOf(a),1)}}]).directive("progress",function(){return{restrict:"EA",replace:!0,transclude:!0,controller:"ProgressController",require:"progress",scope:{},templateUrl:"template/progressbar/progress.html"}}).directive("bar",function(){return{restrict:"EA",replace:!0,transclude:!0,require:"^progress",scope:{value:"=",type:"@"},templateUrl:"template/progressbar/bar.html",link:function(a,b,c,d){d.addBar(a,b)}}}).directive("progressbar",function(){return{restrict:"EA",replace:!0,transclude:!0,controller:"ProgressController",scope:{value:"=",type:"@"},templateUrl:"template/progressbar/progressbar.html",link:function(a,b,c,d){d.addBar(a,angular.element(b.children()[0]))}}}),angular.module("ui.bootstrap.rating",[]).constant("ratingConfig",{max:5,stateOn:null,stateOff:null}).controller("RatingController",["$scope","$attrs","ratingConfig",function(a,b,c){var d={$setViewValue:angular.noop};this.init=function(e){d=e,d.$render=this.render,this.stateOn=angular.isDefined(b.stateOn)?a.$parent.$eval(b.stateOn):c.stateOn,this.stateOff=angular.isDefined(b.stateOff)?a.$parent.$eval(b.stateOff):c.stateOff;var f=angular.isDefined(b.ratingStates)?a.$parent.$eval(b.ratingStates):new Array(angular.isDefined(b.max)?a.$parent.$eval(b.max):c.max);a.range=this.buildTemplateObjects(f)},this.buildTemplateObjects=function(a){for(var b=0,c=a.length;c>b;b++)a[b]=angular.extend({index:b},{stateOn:this.stateOn,stateOff:this.stateOff},a[b]);return a},a.rate=function(b){!a.readonly&&b>=0&&b<=a.range.length&&(d.$setViewValue(b),d.$render())},a.enter=function(b){a.readonly||(a.value=b),a.onHover({value:b})},a.reset=function(){a.value=d.$viewValue,a.onLeave()},a.onKeydown=function(b){/(37|38|39|40)/.test(b.which)&&(b.preventDefault(),b.stopPropagation(),a.rate(a.value+(38===b.which||39===b.which?1:-1)))},this.render=function(){a.value=d.$viewValue}}]).directive("rating",function(){return{restrict:"EA",require:["rating","ngModel"],scope:{readonly:"=?",onHover:"&",onLeave:"&"},controller:"RatingController",templateUrl:"template/rating/rating.html",replace:!0,link:function(a,b,c,d){var e=d[0],f=d[1];f&&e.init(f)}}}),angular.module("ui.bootstrap.tabs",[]).controller("TabsetController",["$scope",function(a){var b=this,c=b.tabs=a.tabs=[];b.select=function(a){angular.forEach(c,function(b){b.active&&b!==a&&(b.active=!1,b.onDeselect())}),a.active=!0,a.onSelect()},b.addTab=function(a){c.push(a),1===c.length?a.active=!0:a.active&&b.select(a)},b.removeTab=function(a){var e=c.indexOf(a);if(a.active&&c.length>1&&!d){var f=e==c.length-1?e-1:e+1;b.select(c[f])}c.splice(e,1)};var d;a.$on("$destroy",function(){d=!0})}]).directive("tabset",function(){return{restrict:"EA",transclude:!0,replace:!0,scope:{type:"@"},controller:"TabsetController",templateUrl:"template/tabs/tabset.html",link:function(a,b,c){a.vertical=angular.isDefined(c.vertical)?a.$parent.$eval(c.vertical):!1,a.justified=angular.isDefined(c.justified)?a.$parent.$eval(c.justified):!1}}}).directive("tab",["$parse",function(a){return{require:"^tabset",restrict:"EA",replace:!0,templateUrl:"template/tabs/tab.html",transclude:!0,scope:{active:"=?",heading:"@",onSelect:"&select",onDeselect:"&deselect"},controller:function(){},compile:function(b,c,d){return function(b,c,e,f){b.$watch("active",function(a){a&&f.select(b)}),b.disabled=!1,e.disabled&&b.$parent.$watch(a(e.disabled),function(a){b.disabled=!!a}),b.select=function(){b.disabled||(b.active=!0)},f.addTab(b),b.$on("$destroy",function(){f.removeTab(b)}),b.$transcludeFn=d}}}}]).directive("tabHeadingTransclude",[function(){return{restrict:"A",require:"^tab",link:function(a,b){a.$watch("headingElement",function(a){a&&(b.html(""),b.append(a))})}}}]).directive("tabContentTransclude",function(){function a(a){return a.tagName&&(a.hasAttribute("tab-heading")||a.hasAttribute("data-tab-heading")||"tab-heading"===a.tagName.toLowerCase()||"data-tab-heading"===a.tagName.toLowerCase())}return{restrict:"A",require:"^tabset",link:function(b,c,d){var e=b.$eval(d.tabContentTransclude);e.$transcludeFn(e.$parent,function(b){angular.forEach(b,function(b){a(b)?e.headingElement=b:c.append(b)})})}}}),angular.module("ui.bootstrap.timepicker",[]).constant("timepickerConfig",{hourStep:1,minuteStep:1,showMeridian:!0,meridians:null,readonlyInput:!1,mousewheel:!0}).controller("TimepickerController",["$scope","$attrs","$parse","$log","$locale","timepickerConfig",function(a,b,c,d,e,f){function g(){var b=parseInt(a.hours,10),c=a.showMeridian?b>0&&13>b:b>=0&&24>b;return c?(a.showMeridian&&(12===b&&(b=0),a.meridian===p[1]&&(b+=12)),b):void 0}function h(){var b=parseInt(a.minutes,10);return b>=0&&60>b?b:void 0}function i(a){return angular.isDefined(a)&&a.toString().length<2?"0"+a:a}function j(a){k(),o.$setViewValue(new Date(n)),l(a)}function k(){o.$setValidity("time",!0),a.invalidHours=!1,a.invalidMinutes=!1}function l(b){var c=n.getHours(),d=n.getMinutes();a.showMeridian&&(c=0===c||12===c?12:c%12),a.hours="h"===b?c:i(c),a.minutes="m"===b?d:i(d),a.meridian=n.getHours()<12?p[0]:p[1]}function m(a){var b=new Date(n.getTime()+6e4*a);n.setHours(b.getHours(),b.getMinutes()),j()}var n=new Date,o={$setViewValue:angular.noop},p=angular.isDefined(b.meridians)?a.$parent.$eval(b.meridians):f.meridians||e.DATETIME_FORMATS.AMPMS;this.init=function(c,d){o=c,o.$render=this.render;var e=d.eq(0),g=d.eq(1),h=angular.isDefined(b.mousewheel)?a.$parent.$eval(b.mousewheel):f.mousewheel;h&&this.setupMousewheelEvents(e,g),a.readonlyInput=angular.isDefined(b.readonlyInput)?a.$parent.$eval(b.readonlyInput):f.readonlyInput,this.setupInputEvents(e,g)};var q=f.hourStep;b.hourStep&&a.$parent.$watch(c(b.hourStep),function(a){q=parseInt(a,10)});var r=f.minuteStep;b.minuteStep&&a.$parent.$watch(c(b.minuteStep),function(a){r=parseInt(a,10)}),a.showMeridian=f.showMeridian,b.showMeridian&&a.$parent.$watch(c(b.showMeridian),function(b){if(a.showMeridian=!!b,o.$error.time){var c=g(),d=h();angular.isDefined(c)&&angular.isDefined(d)&&(n.setHours(c),j())}else l()}),this.setupMousewheelEvents=function(b,c){var d=function(a){a.originalEvent&&(a=a.originalEvent);var b=a.wheelDelta?a.wheelDelta:-a.deltaY;return a.detail||b>0};b.bind("mousewheel wheel",function(b){a.$apply(d(b)?a.incrementHours():a.decrementHours()),b.preventDefault()}),c.bind("mousewheel wheel",function(b){a.$apply(d(b)?a.incrementMinutes():a.decrementMinutes()),b.preventDefault()})},this.setupInputEvents=function(b,c){if(a.readonlyInput)return a.updateHours=angular.noop,void(a.updateMinutes=angular.noop);var d=function(b,c){o.$setViewValue(null),o.$setValidity("time",!1),angular.isDefined(b)&&(a.invalidHours=b),angular.isDefined(c)&&(a.invalidMinutes=c)};a.updateHours=function(){var a=g();angular.isDefined(a)?(n.setHours(a),j("h")):d(!0)},b.bind("blur",function(){!a.invalidHours&&a.hours<10&&a.$apply(function(){a.hours=i(a.hours)})}),a.updateMinutes=function(){var a=h();angular.isDefined(a)?(n.setMinutes(a),j("m")):d(void 0,!0)},c.bind("blur",function(){!a.invalidMinutes&&a.minutes<10&&a.$apply(function(){a.minutes=i(a.minutes)})})},this.render=function(){var a=o.$modelValue?new Date(o.$modelValue):null;isNaN(a)?(o.$setValidity("time",!1),d.error('Timepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.')):(a&&(n=a),k(),l())},a.incrementHours=function(){m(60*q)},a.decrementHours=function(){m(60*-q)},a.incrementMinutes=function(){m(r)},a.decrementMinutes=function(){m(-r)},a.toggleMeridian=function(){m(720*(n.getHours()<12?1:-1))}}]).directive("timepicker",function(){return{restrict:"EA",require:["timepicker","?^ngModel"],controller:"TimepickerController",replace:!0,scope:{},templateUrl:"template/timepicker/timepicker.html",link:function(a,b,c,d){var e=d[0],f=d[1];f&&e.init(f,b.find("input"))}}}),angular.module("ui.bootstrap.typeahead",["ui.bootstrap.position","ui.bootstrap.bindHtml"]).factory("typeaheadParser",["$parse",function(a){var b=/^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+([\s\S]+?)$/;return{parse:function(c){var d=c.match(b);if(!d)throw new Error('Expected typeahead specification in form of "_modelValue_ (as _label_)? for _item_ in _collection_" but got "'+c+'".');return{itemName:d[3],source:a(d[4]),viewMapper:a(d[2]||d[1]),modelMapper:a(d[1])}}}}]).directive("typeahead",["$compile","$parse","$q","$timeout","$document","$position","typeaheadParser",function(a,b,c,d,e,f,g){var h=[9,13,27,38,40];return{require:"ngModel",link:function(i,j,k,l){var m,n=i.$eval(k.typeaheadMinLength)||1,o=i.$eval(k.typeaheadWaitMs)||0,p=i.$eval(k.typeaheadEditable)!==!1,q=b(k.typeaheadLoading).assign||angular.noop,r=b(k.typeaheadOnSelect),s=k.typeaheadInputFormatter?b(k.typeaheadInputFormatter):void 0,t=k.typeaheadAppendToBody?i.$eval(k.typeaheadAppendToBody):!1,u=i.$eval(k.typeaheadFocusFirst)!==!1,v=b(k.ngModel).assign,w=g.parse(k.typeahead),x=i.$new();i.$on("$destroy",function(){x.$destroy()});var y="typeahead-"+x.$id+"-"+Math.floor(1e4*Math.random());j.attr({"aria-autocomplete":"list","aria-expanded":!1,"aria-owns":y});var z=angular.element("<div typeahead-popup></div>");z.attr({id:y,matches:"matches",active:"activeIdx",select:"select(activeIdx)",query:"query",position:"position"}),angular.isDefined(k.typeaheadTemplateUrl)&&z.attr("template-url",k.typeaheadTemplateUrl);var A=function(){x.matches=[],x.activeIdx=-1,j.attr("aria-expanded",!1)},B=function(a){return y+"-option-"+a};x.$watch("activeIdx",function(a){0>a?j.removeAttr("aria-activedescendant"):j.attr("aria-activedescendant",B(a))});var C=function(a){var b={$viewValue:a};q(i,!0),c.when(w.source(i,b)).then(function(c){var d=a===l.$viewValue;if(d&&m)if(c.length>0){x.activeIdx=u?0:-1,x.matches.length=0;for(var e=0;e<c.length;e++)b[w.itemName]=c[e],x.matches.push({id:B(e),label:w.viewMapper(x,b),model:c[e]});x.query=a,x.position=t?f.offset(j):f.position(j),x.position.top=x.position.top+j.prop("offsetHeight"),j.attr("aria-expanded",!0)}else A();d&&q(i,!1)},function(){A(),q(i,!1)})};A(),x.query=void 0;var D,E=function(a){D=d(function(){C(a)},o)},F=function(){D&&d.cancel(D)};l.$parsers.unshift(function(a){return m=!0,a&&a.length>=n?o>0?(F(),E(a)):C(a):(q(i,!1),F(),A()),p?a:a?void l.$setValidity("editable",!1):(l.$setValidity("editable",!0),a)}),l.$formatters.push(function(a){var b,c,d={};return s?(d.$model=a,s(i,d)):(d[w.itemName]=a,b=w.viewMapper(i,d),d[w.itemName]=void 0,c=w.viewMapper(i,d),b!==c?b:a)}),x.select=function(a){var b,c,e={};e[w.itemName]=c=x.matches[a].model,b=w.modelMapper(i,e),v(i,b),l.$setValidity("editable",!0),r(i,{$item:c,$model:b,$label:w.viewMapper(i,e)}),A(),d(function(){j[0].focus()},0,!1)},j.bind("keydown",function(a){0!==x.matches.length&&-1!==h.indexOf(a.which)&&(-1!=x.activeIdx||13!==a.which&&9!==a.which)&&(a.preventDefault(),40===a.which?(x.activeIdx=(x.activeIdx+1)%x.matches.length,x.$digest()):38===a.which?(x.activeIdx=(x.activeIdx>0?x.activeIdx:x.matches.length)-1,x.$digest()):13===a.which||9===a.which?x.$apply(function(){x.select(x.activeIdx)}):27===a.which&&(a.stopPropagation(),A(),x.$digest()))}),j.bind("blur",function(){m=!1});var G=function(a){j[0]!==a.target&&(A(),x.$digest())};e.bind("click",G),i.$on("$destroy",function(){e.unbind("click",G),t&&H.remove()});var H=a(z)(x);t?e.find("body").append(H):j.after(H)}}}]).directive("typeaheadPopup",function(){return{restrict:"EA",scope:{matches:"=",query:"=",active:"=",position:"=",select:"&"},replace:!0,templateUrl:"template/typeahead/typeahead-popup.html",link:function(a,b,c){a.templateUrl=c.templateUrl,a.isOpen=function(){return a.matches.length>0},a.isActive=function(b){return a.active==b},a.selectActive=function(b){a.active=b},a.selectMatch=function(b){a.select({activeIdx:b})}}}}).directive("typeaheadMatch",["$http","$templateCache","$compile","$parse",function(a,b,c,d){return{restrict:"EA",scope:{index:"=",match:"=",query:"="},link:function(e,f,g){var h=d(g.templateUrl)(e.$parent)||"template/typeahead/typeahead-match.html";a.get(h,{cache:b}).success(function(a){f.replaceWith(c(a.trim())(e))})}}}]).filter("typeaheadHighlight",function(){function a(a){return a.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")}return function(b,c){return c?(""+b).replace(new RegExp(a(c),"gi"),"<strong>$&</strong>"):b}});
bower_components/angular-bootstrap/ui-bootstrap.min.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/9b8a7cdd496c0aa8ef0d9ffd84289b8e6b237dcd
[ 0.00017251876124646515, 0.00017251876124646515, 0.00017251876124646515, 0.00017251876124646515, 0 ]
{ "id": 0, "code_window": [ " (err: Error, failedTopics: mqtt.Granted[]) => { }\n", " );\n", "\n", " thingShadows.on(\"connect\", function() {\n", " console.log(\"connected to AWS IoT\");\n", " });\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " thingShadows.subscribe(\"topic\", {}, (error: any, granted: mqtt.Granted) => {});\n", "\n" ], "file_path": "types/aws-iot-device-sdk/aws-iot-device-sdk-tests.ts", "type": "add", "edit_start_line_idx": 70 }
// Type definitions for aws-iot-device-sdk 1.0.13 // Project: https://github.com/aws/aws-iot-device-sdk-js // Definitions by: Markus Olsson <https://github.com/niik> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="node" /> import * as mqtt from "mqtt"; import * as WebSocket from "ws"; export interface DeviceOptions extends mqtt.ClientOptions { /** the AWS IoT region you will operate in (default "us-east-1") */ region?: string; /** the client ID you will use to connect to AWS IoT */ clientId?: string; /** * path of the client certificate file path of the private key file * associated with the client certificate */ certPath?: string; /** path of the private key file associated with the client certificate */ keyPath?: string; /** path of your CA certificate file */ caPath?: string; /** * same as certPath, but can also accept a buffer containing client * certificate data */ clientCert?: string; /** * same as keyPath, but can also accept a buffer containing private key * data */ privateKey?: string; /** * same as caPath, but can also accept a buffer containing CA certificate * data */ caCert?: string; /** * set to "true" to automatically re-subscribe to topics after * reconnection (default "true") */ autoResubscribe?: boolean; /** set to "true" to automatically queue published messages while * offline (default "true") */ offlineQueueing?: boolean; /** * enforce a maximum size for the offline message queue * (default 0, e.g. no maximum) */ offlineQueueMaxSize?: number; /** * set to "oldest" or "newest" to define drop behavior on a full * queue when offlineQueueMaxSize > 0 */ offlineQueueDropBehavior?: "oldest" | "newest"; /** * the minimum time in milliseconds between publishes when draining * after reconnection (default 250) */ drainTimeMs?: number; /** the base reconnection time in milliseconds (default 1000) */ baseReconnectTimeMs?: number; /** the maximum reconnection time in milliseconds (default 128000) */ maximumReconnectTimeMs?: number; /** * the minimum time in milliseconds that a connection must be maintained * in order to be considered stable (default 20000) */ minimumConnectionTimeMs?: number; /** * the connection type, either "mqtts" (default) or "wss" (WebSocket/TLS). * Note that when set to "wss", values must be provided for the * Access Key ID and Secret Key in either the following options or in * environment variables as specified in WebSocket Configuration[1]. * * 1. https://github.com/aws/aws-iot-device-sdk-js#websockets */ protocol?: "mqtts" | "wss"; /** * if protocol is set to "wss", you can use this parameter to pass * additional options to the underlying WebSocket object; * these options are documented here. */ websocketOptions?: WebSocket.IClientOptions; /** * used to specify the Access Key ID when protocol is set to "wss". * Overrides the environment variable AWS_ACCESS_KEY_ID if set. */ accessKeyId?: string; /** * used to specify the Secret Key when protocol is set to "wss". * Overrides the environment variable AWS_SECRET_ACCESS_KEY if set. */ secretKey?: string; /** * (required when authenticating via Cognito, optional otherwise) used * to specify the Session Token when protocol is set to "wss". Overrides * the environment variable AWS_SESSION_TOKEN if set. */ sessionToken?: string; /** * optional hostname, if not specified a hostname will be constructed * from the region option */ // NB Not documented but present in examples, see // https://github.com/aws/aws-iot-device-sdk-js/blob/97b0b468d/device/index.js#L376 // https://github.com/aws/aws-iot-device-sdk-js/blob/97b0b468d/device/index.js#L149 host?: string; /** optional port, will be appended to hostname if present and not 443 */ // NB Not documented but present in examples, see // https://github.com/aws/aws-iot-device-sdk-js/blob/97b0b468d/device/index.js#L154 port?: number; /** enable console logging, default false */ // NB Not documented but present in examples, see // https://github.com/aws/aws-iot-device-sdk-js/blob/97b0b468d/device/index.js#L436 debug?: boolean; } export class device extends NodeJS.EventEmitter { /** * Returns a wrapper for the mqtt.Client() class, configured for a TLS * connection with the AWS IoT platform and with arguments as specified * in options. */ constructor(options?: DeviceOptions); /** * Update the credentials set used to authenticate via WebSocket/SigV4. * * This method is designed to be invoked during the callback of the * getCredentialsForIdentity method in the AWS SDK for JavaScript. */ updateWebSocketCredentials(accessKeyId: string, secretKey: string, sessionToken: string, expiration: Date): void; on(event: "connect" | "close" | "reconnect" | "offline", listener: () => void): this; // Error | string comes from: // https://github.com/aws/aws-iot-device-sdk-js/blob/97b0b46/device/index.js#L744 // Remove when https://github.com/aws/aws-iot-device-sdk-js/issues/95 is fixed on(event: "error", listener: (error: Error | string) => void): this; /** Emitted when a message is received on a topic not related to any Thing Shadows */ on(event: "message", listener: (topic: string, payload: any) => void): this; // The following publish, subscribe, unsubscribe and end Definitions // are derived from the mqtt definition as they are re-surfaced through // thingShadow // https://github.com/DefinitelyTyped/DefinitelyTyped/blob/e7772769fab8c206449ce9673cac417370330aa9/mqtt/mqtt.d.ts#L199 /** * Publish a message to a topic * * @param topic to publish to * @param message to publish * @param publish options * @param called when publish succeeds or fails */ publish(topic: string, message: Buffer | string, options?: mqtt.ClientPublishOptions, callback?: (error?: Error) => void): mqtt.Client; /** * Subscribe to a topic or topics * @param topic to subscribe to or an Array of topics to subscribe to. It can also be an object. * @param the options to subscribe with * @param callback fired on suback */ subscribe(topic: string | string[] | mqtt.Topic, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client; /** * Unsubscribe from a topic or topics * * @param topic is a String topic or an array of topics to unsubscribe from * @param options * @param callback fired on unsuback */ unsubscribe(topic: string | string[], options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client; /** * end - close connection * * @param force passing it to true will close the client right away, without waiting for the in-flight messages to be acked. * This parameter is optional. * @param callback */ end(force?: boolean, callback?: Function): mqtt.Client; } export interface ThingShadowOptions extends DeviceOptions { /** the timeout for thing operations (default 10 seconds) */ operationTimeout?: number; } export interface RegisterOptions { /** * set to true to not subscribe to the delta sub-topic for this * Thing Shadow; used in cases where the application is not interested in * changes (e.g. update only.) (default false) */ ignoreDeltas?: boolean; /** * set to false to unsubscribe from all operation sub-topics while not * performing an operation (default true) */ persistentSubscribe?: boolean; /** * set to false to allow receiving messages with old version * numbers (default true) */ discardStale?: boolean; /** set to true to send version numbers with shadow updates (default true) */ enableVersioning?: boolean; } /** * The thingShadow class wraps an instance of the device class with * additional functionality to operate on Thing Shadows via the AWS IoT API. */ export class thingShadow extends NodeJS.EventEmitter { constructor(options?: ThingShadowOptions); /** * Register interest in the Thing Shadow named thingName. * * The thingShadow class will subscribe to any applicable topics, and will * fire events for the Thing Shadow until awsIot.thingShadow#unregister() * is called with thingName * * If the callback parameter is provided, it will be invoked after * registration is complete (i.e., when subscription ACKs have been received * for all shadow topics). Applications should wait until shadow * registration is complete before performing update/get/delete operations. */ register(thingName: string, options?: RegisterOptions, callback?: (error: Error, failedTopics: mqtt.Granted[]) => void): void /** * Unregister interest in the Thing Shadow named thingName. * * The thingShadow class will unsubscribe from all applicable topics * and no more events will be fired for thingName. */ unregister(thingName: string): void /** * Update the Thing Shadow named thingName with the state specified in the * JavaScript object stateObject. thingName must have been previously * registered using awsIot.thingShadow#register(). * * The thingShadow class will subscribe to all applicable topics and * publish stateObject on the update sub-topic. * * This function returns a clientToken, which is a unique value associated * with the update operation. When a "status" or "timeout" event is emitted, * the clientToken will be supplied as one of the parameters, allowing the * application to keep track of the status of each operation. The caller may * create their own clientToken value; if stateObject contains a clientToken * property, that will be used rather than the internally generated value. * Note that it should be of atomic type (i.e. numeric or string). * This function returns "null" if an operation is already in progress. */ update(thingName: string, stateObject: any): string | null; /** * Get the current state of the Thing Shadow named thingName, which must * have been previously registered using awsIot.thingShadow#register(). * The thingShadow class will subscribe to all applicable topics and * publish on the get sub-topic. * * This function returns a clientToken, which is a unique value * associated with the get operation. When a "status or "timeout" event * is emitted, the clientToken will be supplied as one of the parameters, * allowing the application to keep track of the status of each operation. * The caller may supply their own clientToken value (optional); if * supplied, the value of clientToken will be used rather than the * internally generated value. Note that this value should be of atomic * type (i.e. numeric or string). This function returns "null" if an * operation is already in progress. */ get(thingName: string, clientToken?: string): string | null; /** * Delete the Thing Shadow named thingName, which must have been previously * registered using awsIot.thingShadow#register(). The thingShadow class * will subscribe to all applicable topics and publish on the delete sub-topic. * * This function returns a clientToken, which is a unique value associated * with the delete operation. When a "status" or "timeout" event is * emitted, the clientToken will be supplied as one of the parameters, * allowing the application to keep track of the status of each operation. * The caller may supply their own clientToken value (optional); if * supplied, the value of clientToken will be used rather than the * internally generated value. Note that this value should be of atomic * type (i.e. numeric or string). This function returns "null" if an * operation is already in progress. */ delete(thingName: string, clientToken?: string): string | null; // The following publish, subscribe, unsubscribe and end Definitions // are copied from the mqtt definition as they are re-surfaced through // thingShadow // https://github.com/DefinitelyTyped/DefinitelyTyped/blob/e7772769fab8c206449ce9673cac417370330aa9/mqtt/mqtt.d.ts#L199 /** * Publish a message to a topic * * @param topic * @param message * @param options * @param callback */ publish(topic: string, message: Buffer, options?: mqtt.ClientPublishOptions, callback?: Function): mqtt.Client; publish(topic: string, message: string, options?: mqtt.ClientPublishOptions, callback?: Function): mqtt.Client; /** * Subscribe to a topic or topics * @param topic to subscribe to or an Array of topics to subscribe to. It can also be an object. * @param the options to subscribe with * @param callback fired on suback */ subscribe(topic: string, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client; subscribe(topic: string[], options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client; subscribe(topic: mqtt.Topic, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client; /** * Unsubscribe from a topic or topics * * @param topic is a String topic or an array of topics to unsubscribe from * @param options * @param callback fired on unsuback */ unsubscribe(topic: string, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client; unsubscribe(topic: string[], options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client; /** * end - close connection * * @param force passing it to true will close the client right away, without waiting for the in-flight messages to be acked. * This parameter is optional. * @param callback */ end(force?: boolean, callback?: Function): mqtt.Client; on(event: "connect" | "close" | "reconnect" | "offline", listener: () => void): this; on(event: "error", listener: (error: Error) => void): this; /** Emitted when a message is received on a topic not related to any Thing Shadows */ on(event: "message", listener: (topic: string, payload: any) => void): this; /** * Emitted when an operation update|get|delete completes. * * thingName - name of the Thing Shadow for which the operation has completed * stat - status of the operation accepted|rejected * clientToken - the operation"s clientToken * stateObject - the stateObject returned for the operation * * Applications can use clientToken values to correlate status events with * the operations that they are associated with by saving the clientTokens * returned from each operation. */ on(event: "status", listener: (thingName: string, operationStatus: "accepted" | "rejected", clientToken: string, stateObject: any) => void): this; /** Emitted when an operation update|get|delete has timed out. */ on(event: "timeout", listener: (thingName: string, clientToken: string) => void): this; /** Emitted when a delta has been received for a registered Thing Shadow. */ on(event: "delta", listener: (thingName: string, stateObject: any) => void): this; /** Emitted when a different client"s update or delete operation is accepted on the shadow. */ on(event: "foreignStateChange", listener: (thingName: string, operation: "update" | "delete", stateObject: any) => void): this; }
types/aws-iot-device-sdk/index.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2ff4dff832042617a3653eceefb6fe95a546f3a4
[ 0.010094373486936092, 0.000875842000823468, 0.00016470447008032352, 0.00019847776275128126, 0.0020360269118100405 ]
{ "id": 0, "code_window": [ " (err: Error, failedTopics: mqtt.Granted[]) => { }\n", " );\n", "\n", " thingShadows.on(\"connect\", function() {\n", " console.log(\"connected to AWS IoT\");\n", " });\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " thingShadows.subscribe(\"topic\", {}, (error: any, granted: mqtt.Granted) => {});\n", "\n" ], "file_path": "types/aws-iot-device-sdk/aws-iot-device-sdk-tests.ts", "type": "add", "edit_start_line_idx": 70 }
{ "compilerOptions": { "module": "commonjs", "lib": [ "es6", "dom" ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", "bloomfilter-tests.ts" ] }
types/bloomfilter/tsconfig.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2ff4dff832042617a3653eceefb6fe95a546f3a4
[ 0.00017384324746672064, 0.00017272779950872064, 0.00017173471860587597, 0.00017260546155739576, 8.651397251924209e-7 ]
{ "id": 0, "code_window": [ " (err: Error, failedTopics: mqtt.Granted[]) => { }\n", " );\n", "\n", " thingShadows.on(\"connect\", function() {\n", " console.log(\"connected to AWS IoT\");\n", " });\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " thingShadows.subscribe(\"topic\", {}, (error: any, granted: mqtt.Granted) => {});\n", "\n" ], "file_path": "types/aws-iot-device-sdk/aws-iot-device-sdk-tests.ts", "type": "add", "edit_start_line_idx": 70 }
// Type definitions for streaming-json-stringify 3.1 // Project: https://github.com/stream-utils/streaming-json-stringify#readme // Definitions by: BendingBender <https://github.com/BendingBender> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 /// <reference types="node" /> import * as stream from 'stream'; export = Stringify; declare const Stringify: StringifyFactory; interface StringifyFactory { (options?: Stringify.Options): Stringify.Instance & stream.Transform; new (options?: Stringify.Options): Stringify.Instance & stream.Transform; } declare namespace Stringify { interface Instance { replacer: Replacer; space: string | number; opener: string; seperator: string; closer: string; stringifier(value: any, replacer: Replacer, space: string | number): string; } type Replacer = (key: string, value: any) => any; type Options = Partial<Instance> & stream.TransformOptions; }
types/streaming-json-stringify/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2ff4dff832042617a3653eceefb6fe95a546f3a4
[ 0.00017370737623423338, 0.00017199234571307898, 0.00017013873730320483, 0.00017206164193339646, 0.0000012970995157957077 ]
{ "id": 0, "code_window": [ " (err: Error, failedTopics: mqtt.Granted[]) => { }\n", " );\n", "\n", " thingShadows.on(\"connect\", function() {\n", " console.log(\"connected to AWS IoT\");\n", " });\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " thingShadows.subscribe(\"topic\", {}, (error: any, granted: mqtt.Granted) => {});\n", "\n" ], "file_path": "types/aws-iot-device-sdk/aws-iot-device-sdk-tests.ts", "type": "add", "edit_start_line_idx": 70 }
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; export default class GoBroadcast extends React.Component<IconBaseProps> { }
types/react-icons/lib/go/broadcast.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2ff4dff832042617a3653eceefb6fe95a546f3a4
[ 0.0001730169024085626, 0.0001730169024085626, 0.0001730169024085626, 0.0001730169024085626, 0 ]
{ "id": 1, "code_window": [ " * @param options\n", " * @param callback\n", " */\n", " publish(topic: string, message: Buffer, options?: mqtt.ClientPublishOptions, callback?: Function): mqtt.Client;\n", " publish(topic: string, message: string, options?: mqtt.ClientPublishOptions, callback?: Function): mqtt.Client;\n", "\n", " /**\n", " * Subscribe to a topic or topics\n", " * @param topic to subscribe to or an Array of topics to subscribe to. It can also be an object.\n", " * @param the options to subscribe with\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " publish(topic: string, message: Buffer | string, options?: mqtt.ClientPublishOptions, callback?: Function): mqtt.Client;\n" ], "file_path": "types/aws-iot-device-sdk/index.d.ts", "type": "replace", "edit_start_line_idx": 335 }
// Type definitions for aws-iot-device-sdk 1.0.13 // Project: https://github.com/aws/aws-iot-device-sdk-js // Definitions by: Markus Olsson <https://github.com/niik> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="node" /> import * as mqtt from "mqtt"; import * as WebSocket from "ws"; export interface DeviceOptions extends mqtt.ClientOptions { /** the AWS IoT region you will operate in (default "us-east-1") */ region?: string; /** the client ID you will use to connect to AWS IoT */ clientId?: string; /** * path of the client certificate file path of the private key file * associated with the client certificate */ certPath?: string; /** path of the private key file associated with the client certificate */ keyPath?: string; /** path of your CA certificate file */ caPath?: string; /** * same as certPath, but can also accept a buffer containing client * certificate data */ clientCert?: string; /** * same as keyPath, but can also accept a buffer containing private key * data */ privateKey?: string; /** * same as caPath, but can also accept a buffer containing CA certificate * data */ caCert?: string; /** * set to "true" to automatically re-subscribe to topics after * reconnection (default "true") */ autoResubscribe?: boolean; /** set to "true" to automatically queue published messages while * offline (default "true") */ offlineQueueing?: boolean; /** * enforce a maximum size for the offline message queue * (default 0, e.g. no maximum) */ offlineQueueMaxSize?: number; /** * set to "oldest" or "newest" to define drop behavior on a full * queue when offlineQueueMaxSize > 0 */ offlineQueueDropBehavior?: "oldest" | "newest"; /** * the minimum time in milliseconds between publishes when draining * after reconnection (default 250) */ drainTimeMs?: number; /** the base reconnection time in milliseconds (default 1000) */ baseReconnectTimeMs?: number; /** the maximum reconnection time in milliseconds (default 128000) */ maximumReconnectTimeMs?: number; /** * the minimum time in milliseconds that a connection must be maintained * in order to be considered stable (default 20000) */ minimumConnectionTimeMs?: number; /** * the connection type, either "mqtts" (default) or "wss" (WebSocket/TLS). * Note that when set to "wss", values must be provided for the * Access Key ID and Secret Key in either the following options or in * environment variables as specified in WebSocket Configuration[1]. * * 1. https://github.com/aws/aws-iot-device-sdk-js#websockets */ protocol?: "mqtts" | "wss"; /** * if protocol is set to "wss", you can use this parameter to pass * additional options to the underlying WebSocket object; * these options are documented here. */ websocketOptions?: WebSocket.IClientOptions; /** * used to specify the Access Key ID when protocol is set to "wss". * Overrides the environment variable AWS_ACCESS_KEY_ID if set. */ accessKeyId?: string; /** * used to specify the Secret Key when protocol is set to "wss". * Overrides the environment variable AWS_SECRET_ACCESS_KEY if set. */ secretKey?: string; /** * (required when authenticating via Cognito, optional otherwise) used * to specify the Session Token when protocol is set to "wss". Overrides * the environment variable AWS_SESSION_TOKEN if set. */ sessionToken?: string; /** * optional hostname, if not specified a hostname will be constructed * from the region option */ // NB Not documented but present in examples, see // https://github.com/aws/aws-iot-device-sdk-js/blob/97b0b468d/device/index.js#L376 // https://github.com/aws/aws-iot-device-sdk-js/blob/97b0b468d/device/index.js#L149 host?: string; /** optional port, will be appended to hostname if present and not 443 */ // NB Not documented but present in examples, see // https://github.com/aws/aws-iot-device-sdk-js/blob/97b0b468d/device/index.js#L154 port?: number; /** enable console logging, default false */ // NB Not documented but present in examples, see // https://github.com/aws/aws-iot-device-sdk-js/blob/97b0b468d/device/index.js#L436 debug?: boolean; } export class device extends NodeJS.EventEmitter { /** * Returns a wrapper for the mqtt.Client() class, configured for a TLS * connection with the AWS IoT platform and with arguments as specified * in options. */ constructor(options?: DeviceOptions); /** * Update the credentials set used to authenticate via WebSocket/SigV4. * * This method is designed to be invoked during the callback of the * getCredentialsForIdentity method in the AWS SDK for JavaScript. */ updateWebSocketCredentials(accessKeyId: string, secretKey: string, sessionToken: string, expiration: Date): void; on(event: "connect" | "close" | "reconnect" | "offline", listener: () => void): this; // Error | string comes from: // https://github.com/aws/aws-iot-device-sdk-js/blob/97b0b46/device/index.js#L744 // Remove when https://github.com/aws/aws-iot-device-sdk-js/issues/95 is fixed on(event: "error", listener: (error: Error | string) => void): this; /** Emitted when a message is received on a topic not related to any Thing Shadows */ on(event: "message", listener: (topic: string, payload: any) => void): this; // The following publish, subscribe, unsubscribe and end Definitions // are derived from the mqtt definition as they are re-surfaced through // thingShadow // https://github.com/DefinitelyTyped/DefinitelyTyped/blob/e7772769fab8c206449ce9673cac417370330aa9/mqtt/mqtt.d.ts#L199 /** * Publish a message to a topic * * @param topic to publish to * @param message to publish * @param publish options * @param called when publish succeeds or fails */ publish(topic: string, message: Buffer | string, options?: mqtt.ClientPublishOptions, callback?: (error?: Error) => void): mqtt.Client; /** * Subscribe to a topic or topics * @param topic to subscribe to or an Array of topics to subscribe to. It can also be an object. * @param the options to subscribe with * @param callback fired on suback */ subscribe(topic: string | string[] | mqtt.Topic, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client; /** * Unsubscribe from a topic or topics * * @param topic is a String topic or an array of topics to unsubscribe from * @param options * @param callback fired on unsuback */ unsubscribe(topic: string | string[], options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client; /** * end - close connection * * @param force passing it to true will close the client right away, without waiting for the in-flight messages to be acked. * This parameter is optional. * @param callback */ end(force?: boolean, callback?: Function): mqtt.Client; } export interface ThingShadowOptions extends DeviceOptions { /** the timeout for thing operations (default 10 seconds) */ operationTimeout?: number; } export interface RegisterOptions { /** * set to true to not subscribe to the delta sub-topic for this * Thing Shadow; used in cases where the application is not interested in * changes (e.g. update only.) (default false) */ ignoreDeltas?: boolean; /** * set to false to unsubscribe from all operation sub-topics while not * performing an operation (default true) */ persistentSubscribe?: boolean; /** * set to false to allow receiving messages with old version * numbers (default true) */ discardStale?: boolean; /** set to true to send version numbers with shadow updates (default true) */ enableVersioning?: boolean; } /** * The thingShadow class wraps an instance of the device class with * additional functionality to operate on Thing Shadows via the AWS IoT API. */ export class thingShadow extends NodeJS.EventEmitter { constructor(options?: ThingShadowOptions); /** * Register interest in the Thing Shadow named thingName. * * The thingShadow class will subscribe to any applicable topics, and will * fire events for the Thing Shadow until awsIot.thingShadow#unregister() * is called with thingName * * If the callback parameter is provided, it will be invoked after * registration is complete (i.e., when subscription ACKs have been received * for all shadow topics). Applications should wait until shadow * registration is complete before performing update/get/delete operations. */ register(thingName: string, options?: RegisterOptions, callback?: (error: Error, failedTopics: mqtt.Granted[]) => void): void /** * Unregister interest in the Thing Shadow named thingName. * * The thingShadow class will unsubscribe from all applicable topics * and no more events will be fired for thingName. */ unregister(thingName: string): void /** * Update the Thing Shadow named thingName with the state specified in the * JavaScript object stateObject. thingName must have been previously * registered using awsIot.thingShadow#register(). * * The thingShadow class will subscribe to all applicable topics and * publish stateObject on the update sub-topic. * * This function returns a clientToken, which is a unique value associated * with the update operation. When a "status" or "timeout" event is emitted, * the clientToken will be supplied as one of the parameters, allowing the * application to keep track of the status of each operation. The caller may * create their own clientToken value; if stateObject contains a clientToken * property, that will be used rather than the internally generated value. * Note that it should be of atomic type (i.e. numeric or string). * This function returns "null" if an operation is already in progress. */ update(thingName: string, stateObject: any): string | null; /** * Get the current state of the Thing Shadow named thingName, which must * have been previously registered using awsIot.thingShadow#register(). * The thingShadow class will subscribe to all applicable topics and * publish on the get sub-topic. * * This function returns a clientToken, which is a unique value * associated with the get operation. When a "status or "timeout" event * is emitted, the clientToken will be supplied as one of the parameters, * allowing the application to keep track of the status of each operation. * The caller may supply their own clientToken value (optional); if * supplied, the value of clientToken will be used rather than the * internally generated value. Note that this value should be of atomic * type (i.e. numeric or string). This function returns "null" if an * operation is already in progress. */ get(thingName: string, clientToken?: string): string | null; /** * Delete the Thing Shadow named thingName, which must have been previously * registered using awsIot.thingShadow#register(). The thingShadow class * will subscribe to all applicable topics and publish on the delete sub-topic. * * This function returns a clientToken, which is a unique value associated * with the delete operation. When a "status" or "timeout" event is * emitted, the clientToken will be supplied as one of the parameters, * allowing the application to keep track of the status of each operation. * The caller may supply their own clientToken value (optional); if * supplied, the value of clientToken will be used rather than the * internally generated value. Note that this value should be of atomic * type (i.e. numeric or string). This function returns "null" if an * operation is already in progress. */ delete(thingName: string, clientToken?: string): string | null; // The following publish, subscribe, unsubscribe and end Definitions // are copied from the mqtt definition as they are re-surfaced through // thingShadow // https://github.com/DefinitelyTyped/DefinitelyTyped/blob/e7772769fab8c206449ce9673cac417370330aa9/mqtt/mqtt.d.ts#L199 /** * Publish a message to a topic * * @param topic * @param message * @param options * @param callback */ publish(topic: string, message: Buffer, options?: mqtt.ClientPublishOptions, callback?: Function): mqtt.Client; publish(topic: string, message: string, options?: mqtt.ClientPublishOptions, callback?: Function): mqtt.Client; /** * Subscribe to a topic or topics * @param topic to subscribe to or an Array of topics to subscribe to. It can also be an object. * @param the options to subscribe with * @param callback fired on suback */ subscribe(topic: string, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client; subscribe(topic: string[], options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client; subscribe(topic: mqtt.Topic, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client; /** * Unsubscribe from a topic or topics * * @param topic is a String topic or an array of topics to unsubscribe from * @param options * @param callback fired on unsuback */ unsubscribe(topic: string, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client; unsubscribe(topic: string[], options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client; /** * end - close connection * * @param force passing it to true will close the client right away, without waiting for the in-flight messages to be acked. * This parameter is optional. * @param callback */ end(force?: boolean, callback?: Function): mqtt.Client; on(event: "connect" | "close" | "reconnect" | "offline", listener: () => void): this; on(event: "error", listener: (error: Error) => void): this; /** Emitted when a message is received on a topic not related to any Thing Shadows */ on(event: "message", listener: (topic: string, payload: any) => void): this; /** * Emitted when an operation update|get|delete completes. * * thingName - name of the Thing Shadow for which the operation has completed * stat - status of the operation accepted|rejected * clientToken - the operation"s clientToken * stateObject - the stateObject returned for the operation * * Applications can use clientToken values to correlate status events with * the operations that they are associated with by saving the clientTokens * returned from each operation. */ on(event: "status", listener: (thingName: string, operationStatus: "accepted" | "rejected", clientToken: string, stateObject: any) => void): this; /** Emitted when an operation update|get|delete has timed out. */ on(event: "timeout", listener: (thingName: string, clientToken: string) => void): this; /** Emitted when a delta has been received for a registered Thing Shadow. */ on(event: "delta", listener: (thingName: string, stateObject: any) => void): this; /** Emitted when a different client"s update or delete operation is accepted on the shadow. */ on(event: "foreignStateChange", listener: (thingName: string, operation: "update" | "delete", stateObject: any) => void): this; }
types/aws-iot-device-sdk/index.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2ff4dff832042617a3653eceefb6fe95a546f3a4
[ 0.02151746116578579, 0.001205898355692625, 0.00016226133448071778, 0.00018174989963881671, 0.003495533484965563 ]
{ "id": 1, "code_window": [ " * @param options\n", " * @param callback\n", " */\n", " publish(topic: string, message: Buffer, options?: mqtt.ClientPublishOptions, callback?: Function): mqtt.Client;\n", " publish(topic: string, message: string, options?: mqtt.ClientPublishOptions, callback?: Function): mqtt.Client;\n", "\n", " /**\n", " * Subscribe to a topic or topics\n", " * @param topic to subscribe to or an Array of topics to subscribe to. It can also be an object.\n", " * @param the options to subscribe with\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " publish(topic: string, message: Buffer | string, options?: mqtt.ClientPublishOptions, callback?: Function): mqtt.Client;\n" ], "file_path": "types/aws-iot-device-sdk/index.d.ts", "type": "replace", "edit_start_line_idx": 335 }
import { ValidationContext } from '../index'; /** * No unused fragments * * A GraphQL document is only valid if all fragment definitions are spread * within operations, or spread within other fragments spread within operations. */ export function NoUnusedFragments(context: ValidationContext): any;
types/graphql/validation/rules/NoUnusedFragments.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2ff4dff832042617a3653eceefb6fe95a546f3a4
[ 0.00016507598047610372, 0.00016507598047610372, 0.00016507598047610372, 0.00016507598047610372, 0 ]
{ "id": 1, "code_window": [ " * @param options\n", " * @param callback\n", " */\n", " publish(topic: string, message: Buffer, options?: mqtt.ClientPublishOptions, callback?: Function): mqtt.Client;\n", " publish(topic: string, message: string, options?: mqtt.ClientPublishOptions, callback?: Function): mqtt.Client;\n", "\n", " /**\n", " * Subscribe to a topic or topics\n", " * @param topic to subscribe to or an Array of topics to subscribe to. It can also be an object.\n", " * @param the options to subscribe with\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " publish(topic: string, message: Buffer | string, options?: mqtt.ClientPublishOptions, callback?: Function): mqtt.Client;\n" ], "file_path": "types/aws-iot-device-sdk/index.d.ts", "type": "replace", "edit_start_line_idx": 335 }
interface JQuery { accordion: SemanticUI.Accordion; } declare namespace SemanticUI { interface Accordion { settings: AccordionSettings; /** * Refreshes all cached selectors and data */ (behavior: 'refresh'): JQuery; /** * Opens accordion content at index */ (behavior: 'open', index: number): JQuery; /** * Closes accordion content that are not active */ (behavior: 'close others'): JQuery; /** * Closes accordion content at index */ (behavior: 'close', index: number): JQuery; /** * Toggles accordion content at index */ (behavior: 'toggle', index: number): JQuery; (behavior: 'destroy'): JQuery; <K extends keyof AccordionSettings>(behavior: 'setting', name: K, value?: undefined): AccordionSettings._Impl[K]; <K extends keyof AccordionSettings>(behavior: 'setting', name: K, value: AccordionSettings._Impl[K]): JQuery; (behavior: 'setting', value: AccordionSettings): JQuery; (settings?: AccordionSettings): JQuery; } /** * @see {@link http://semantic-ui.com/modules/accordion.html#/settings} */ type AccordionSettings = AccordionSettings.Param; namespace AccordionSettings { type Param = (Pick<_Impl, 'exclusive'> | Pick<_Impl, 'on'> | Pick<_Impl, 'animateChildren'> | Pick<_Impl, 'closeNested'> | Pick<_Impl, 'collapsible'> | Pick<_Impl, 'duration'> | Pick<_Impl, 'easing'> | Pick<_Impl, 'observeChanges'> | Pick<_Impl, 'onOpening'> | Pick<_Impl, 'onOpen'> | Pick<_Impl, 'onClosing'> | Pick<_Impl, 'onClose'> | Pick<_Impl, 'onChange'> | Pick<_Impl, 'selector'> | Pick<_Impl, 'className'> | Pick<_Impl, 'error'> | Pick<_Impl, 'namespace'> | Pick<_Impl, 'name'> | Pick<_Impl, 'silent'> | Pick<_Impl, 'debug'> | Pick<_Impl, 'performance'> | Pick<_Impl, 'verbose'>) & Partial<Pick<_Impl, keyof _Impl>>; interface _Impl { // region Behavior /** * Only allow one section open at a time * * @default true */ exclusive: boolean; /** * Event on title that will cause accordion to open * * @default 'click' */ on: string; /** * Whether child content opacity should be animated (may cause performance issues with many child elements) * * @default true */ animateChildren: boolean; /** * Close open nested accordion content when an element closes * * @default true */ closeNested: boolean; /** * Allow active sections to collapse * * @default true */ collapsible: boolean; /** * Duration in ms of opening animation * * @default 500 */ duration: number; /** * Easing of opening animation. EaseInOutQuint is included with accordion, for additional options you must include easing equations. * * @default 'easeInOutQuint' * @see {@link http://gsgd.co.uk/sandbox/jquery/easing/} */ easing: string; /** * whether accordion should automatically refresh on DOM insertion * * @default true */ observeChanges: boolean; // endregion // region Callbacks /** * Callback before element opens */ onOpening(this: JQuery): void; /** * Callback after element is open */ onOpen(this: JQuery): void; /** * Callback before element closes */ onClosing(this: JQuery): void; /** * Callback after element is closed */ onClose(this: JQuery): void; /** * Callback on element open or close */ onChange(this: JQuery): void; // endregion // region DOM Settings /** * Selectors used to find parts of a module */ selector: Accordion.SelectorSettings; /** * Class names used to determine element state */ className: Accordion.ClassNameSettings; // endregion // region Debug Settings error: Accordion.ErrorSettings; // endregion // region Component Settings // region DOM Settings /** * Event namespace. Makes sure module teardown does not effect other events attached to an element. */ namespace: string; // endregion // region Debug Settings /** * Name used in log statements */ name: string; /** * Silences all console output including error messages, regardless of other debug settings. */ silent: boolean; /** * Debug output to console */ debug: boolean; /** * Show console.table output with performance metrics */ performance: boolean; /** * Debug output includes all internal behaviors */ verbose: boolean; // endregion // endregion } } namespace Accordion { type SelectorSettings = SelectorSettings.Param; namespace SelectorSettings { type Param = (Pick<_Impl, 'accordion'> | Pick<_Impl, 'title'> | Pick<_Impl, 'trigger'> | Pick<_Impl, 'content'>) & Partial<Pick<_Impl, keyof _Impl>>; interface _Impl { /** * @default '.accordion' */ accordion: string; /** * @default '.title' */ title: string; /** * @default '.title' */ trigger: string; /** * @default '.content' */ content: string; } } type ClassNameSettings = ClassNameSettings.Param; namespace ClassNameSettings { type Param = (Pick<_Impl, 'active'> | Pick<_Impl, 'animating'>) & Partial<Pick<_Impl, keyof _Impl>>; interface _Impl { /** * @default 'active' */ active: string; /** * @default 'animating' */ animating: string; } } type ErrorSettings = ErrorSettings.Param; namespace ErrorSettings { type Param = (Pick<_Impl, 'method'>) & Partial<Pick<_Impl, keyof _Impl>>; interface _Impl { /** * @default 'The method you called is not defined.' */ method: string; } } } }
types/semantic-ui-accordion/global.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2ff4dff832042617a3653eceefb6fe95a546f3a4
[ 0.00018055850523523986, 0.0001684312883298844, 0.0001649987098062411, 0.00016678280371706933, 0.000003609676241467241 ]
{ "id": 1, "code_window": [ " * @param options\n", " * @param callback\n", " */\n", " publish(topic: string, message: Buffer, options?: mqtt.ClientPublishOptions, callback?: Function): mqtt.Client;\n", " publish(topic: string, message: string, options?: mqtt.ClientPublishOptions, callback?: Function): mqtt.Client;\n", "\n", " /**\n", " * Subscribe to a topic or topics\n", " * @param topic to subscribe to or an Array of topics to subscribe to. It can also be an object.\n", " * @param the options to subscribe with\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " publish(topic: string, message: Buffer | string, options?: mqtt.ClientPublishOptions, callback?: Function): mqtt.Client;\n" ], "file_path": "types/aws-iot-device-sdk/index.d.ts", "type": "replace", "edit_start_line_idx": 335 }
import { ValidationContext } from '../index'; /** * Known directives * * A GraphQL document is only valid if all `@directives` are known by the * schema and legally positioned. */ export function KnownDirectives(context: ValidationContext): any;
types/graphql/validation/rules/KnownDirectives.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2ff4dff832042617a3653eceefb6fe95a546f3a4
[ 0.00016608249279670417, 0.00016608249279670417, 0.00016608249279670417, 0.00016608249279670417, 0 ]
{ "id": 2, "code_window": [ " * Subscribe to a topic or topics\n", " * @param topic to subscribe to or an Array of topics to subscribe to. It can also be an object.\n", " * @param the options to subscribe with\n", " * @param callback fired on suback\n", " */\n", " subscribe(topic: string, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n", " subscribe(topic: string[], options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n", " subscribe(topic: mqtt.Topic, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n", "\n", " /**\n", " * Unsubscribe from a topic or topics\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " subscribe(topic: string | string[] | mqtt.Topic, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n" ], "file_path": "types/aws-iot-device-sdk/index.d.ts", "type": "replace", "edit_start_line_idx": 344 }
// Code adapted from // https://github.com/aws/aws-iot-device-sdk-js/blob/97b0b468d59e02e2f6a1dce321000d914cb47894/examples/device-example.js // and // https://github.com/aws/aws-iot-device-sdk-js/blob/97b0b468d59e02e2f6a1dce321000d914cb47894/examples/thing-example.js import * as awsIot from "aws-iot-device-sdk"; import * as mqtt from "mqtt"; const device = new awsIot.device({ keyPath: "", certPath: "", caPath: "", clientId: "", region: "", baseReconnectTimeMs: 1000, keepalive: 10, protocol: "wss", port: 443, host: "", debug: false }); device.subscribe("topic_1"); device .on("connect", function() { console.log("connect"); }); device .on("close", function() { console.log("close"); }); device .on("reconnect", function() { console.log("reconnect"); }); device .on("offline", function() { console.log("offline"); }); device .on("error", function(error) { console.log("error", error); }); device .on("message", function(topic: string, payload: any) { console.log("message", topic, payload.toString()); }); const thingShadows = new awsIot.thingShadow({ keyPath: "", certPath: "", caPath: "", clientId: "", region: "", baseReconnectTimeMs: 1000, keepalive: 10, protocol: "mqtts", port: 0, host: "", debug: false }); thingShadows.register( "thingName", { ignoreDeltas: false }, (err: Error, failedTopics: mqtt.Granted[]) => { } ); thingShadows.on("connect", function() { console.log("connected to AWS IoT"); }); thingShadows.on("close", function() { console.log("close"); thingShadows.unregister("thingName"); }); thingShadows.on("reconnect", function() { console.log("reconnect"); }); thingShadows.on("offline", function() { console.log("offline"); }); thingShadows.on("error", function(error) { console.log("error", error); }); thingShadows.on("message", function(topic: string, payload: any) { console.log("message", topic, payload.toString()); }); thingShadows.on("status", function(thingName: string, stat: "accepted" | "rejected", clientToken: string, stateObject: any) { }); thingShadows.on("delta", function(thingName, stateObject) { }); thingShadows.on("timeout", function(thingName, clientToken) { });
types/aws-iot-device-sdk/aws-iot-device-sdk-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2ff4dff832042617a3653eceefb6fe95a546f3a4
[ 0.0028664921410381794, 0.0004149392480030656, 0.0001668419863563031, 0.0001701924338703975, 0.0007752507226541638 ]
{ "id": 2, "code_window": [ " * Subscribe to a topic or topics\n", " * @param topic to subscribe to or an Array of topics to subscribe to. It can also be an object.\n", " * @param the options to subscribe with\n", " * @param callback fired on suback\n", " */\n", " subscribe(topic: string, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n", " subscribe(topic: string[], options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n", " subscribe(topic: mqtt.Topic, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n", "\n", " /**\n", " * Unsubscribe from a topic or topics\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " subscribe(topic: string | string[] | mqtt.Topic, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n" ], "file_path": "types/aws-iot-device-sdk/index.d.ts", "type": "replace", "edit_start_line_idx": 344 }
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; export default class MdStraighten extends React.Component<IconBaseProps> { }
types/react-icons/lib/md/straighten.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2ff4dff832042617a3653eceefb6fe95a546f3a4
[ 0.00017701616161502898, 0.00017701616161502898, 0.00017701616161502898, 0.00017701616161502898, 0 ]
{ "id": 2, "code_window": [ " * Subscribe to a topic or topics\n", " * @param topic to subscribe to or an Array of topics to subscribe to. It can also be an object.\n", " * @param the options to subscribe with\n", " * @param callback fired on suback\n", " */\n", " subscribe(topic: string, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n", " subscribe(topic: string[], options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n", " subscribe(topic: mqtt.Topic, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n", "\n", " /**\n", " * Unsubscribe from a topic or topics\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " subscribe(topic: string | string[] | mqtt.Topic, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n" ], "file_path": "types/aws-iot-device-sdk/index.d.ts", "type": "replace", "edit_start_line_idx": 344 }
// from https://github.com/hapijs/nes/#browser-client // When you require('nes') it loads the full module and adds a lot of extra code // that is not needed for the browser. The browser will only need the nes client. // If you are using CommonJS you can load the client with require('nes/client'). import Client = require('nes/client'); var options: Client.ClientConnectOptions = { delay: 3 } var client: Client = new Client('ws://localhost', options);
types/nes/test/client-require.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2ff4dff832042617a3653eceefb6fe95a546f3a4
[ 0.0024404318537563086, 0.00130455382168293, 0.00016867576050572097, 0.00130455382168293, 0.0011358780320733786 ]
{ "id": 2, "code_window": [ " * Subscribe to a topic or topics\n", " * @param topic to subscribe to or an Array of topics to subscribe to. It can also be an object.\n", " * @param the options to subscribe with\n", " * @param callback fired on suback\n", " */\n", " subscribe(topic: string, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n", " subscribe(topic: string[], options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n", " subscribe(topic: mqtt.Topic, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n", "\n", " /**\n", " * Unsubscribe from a topic or topics\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " subscribe(topic: string | string[] | mqtt.Topic, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n" ], "file_path": "types/aws-iot-device-sdk/index.d.ts", "type": "replace", "edit_start_line_idx": 344 }
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; export default class FaSortNumericAsc extends React.Component<IconBaseProps> { }
types/react-icons/lib/fa/sort-numeric-asc.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2ff4dff832042617a3653eceefb6fe95a546f3a4
[ 0.00017638267308939248, 0.00017638267308939248, 0.00017638267308939248, 0.00017638267308939248, 0 ]
{ "id": 3, "code_window": [ " *\n", " * @param topic is a String topic or an array of topics to unsubscribe from\n", " * @param options\n", " * @param callback fired on unsuback\n", " */\n", " unsubscribe(topic: string, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n", " unsubscribe(topic: string[], options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n", "\n", " /**\n", " * end - close connection\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " unsubscribe(topic: string | string[], options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n" ], "file_path": "types/aws-iot-device-sdk/index.d.ts", "type": "replace", "edit_start_line_idx": 355 }
// Type definitions for aws-iot-device-sdk 1.0.13 // Project: https://github.com/aws/aws-iot-device-sdk-js // Definitions by: Markus Olsson <https://github.com/niik> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="node" /> import * as mqtt from "mqtt"; import * as WebSocket from "ws"; export interface DeviceOptions extends mqtt.ClientOptions { /** the AWS IoT region you will operate in (default "us-east-1") */ region?: string; /** the client ID you will use to connect to AWS IoT */ clientId?: string; /** * path of the client certificate file path of the private key file * associated with the client certificate */ certPath?: string; /** path of the private key file associated with the client certificate */ keyPath?: string; /** path of your CA certificate file */ caPath?: string; /** * same as certPath, but can also accept a buffer containing client * certificate data */ clientCert?: string; /** * same as keyPath, but can also accept a buffer containing private key * data */ privateKey?: string; /** * same as caPath, but can also accept a buffer containing CA certificate * data */ caCert?: string; /** * set to "true" to automatically re-subscribe to topics after * reconnection (default "true") */ autoResubscribe?: boolean; /** set to "true" to automatically queue published messages while * offline (default "true") */ offlineQueueing?: boolean; /** * enforce a maximum size for the offline message queue * (default 0, e.g. no maximum) */ offlineQueueMaxSize?: number; /** * set to "oldest" or "newest" to define drop behavior on a full * queue when offlineQueueMaxSize > 0 */ offlineQueueDropBehavior?: "oldest" | "newest"; /** * the minimum time in milliseconds between publishes when draining * after reconnection (default 250) */ drainTimeMs?: number; /** the base reconnection time in milliseconds (default 1000) */ baseReconnectTimeMs?: number; /** the maximum reconnection time in milliseconds (default 128000) */ maximumReconnectTimeMs?: number; /** * the minimum time in milliseconds that a connection must be maintained * in order to be considered stable (default 20000) */ minimumConnectionTimeMs?: number; /** * the connection type, either "mqtts" (default) or "wss" (WebSocket/TLS). * Note that when set to "wss", values must be provided for the * Access Key ID and Secret Key in either the following options or in * environment variables as specified in WebSocket Configuration[1]. * * 1. https://github.com/aws/aws-iot-device-sdk-js#websockets */ protocol?: "mqtts" | "wss"; /** * if protocol is set to "wss", you can use this parameter to pass * additional options to the underlying WebSocket object; * these options are documented here. */ websocketOptions?: WebSocket.IClientOptions; /** * used to specify the Access Key ID when protocol is set to "wss". * Overrides the environment variable AWS_ACCESS_KEY_ID if set. */ accessKeyId?: string; /** * used to specify the Secret Key when protocol is set to "wss". * Overrides the environment variable AWS_SECRET_ACCESS_KEY if set. */ secretKey?: string; /** * (required when authenticating via Cognito, optional otherwise) used * to specify the Session Token when protocol is set to "wss". Overrides * the environment variable AWS_SESSION_TOKEN if set. */ sessionToken?: string; /** * optional hostname, if not specified a hostname will be constructed * from the region option */ // NB Not documented but present in examples, see // https://github.com/aws/aws-iot-device-sdk-js/blob/97b0b468d/device/index.js#L376 // https://github.com/aws/aws-iot-device-sdk-js/blob/97b0b468d/device/index.js#L149 host?: string; /** optional port, will be appended to hostname if present and not 443 */ // NB Not documented but present in examples, see // https://github.com/aws/aws-iot-device-sdk-js/blob/97b0b468d/device/index.js#L154 port?: number; /** enable console logging, default false */ // NB Not documented but present in examples, see // https://github.com/aws/aws-iot-device-sdk-js/blob/97b0b468d/device/index.js#L436 debug?: boolean; } export class device extends NodeJS.EventEmitter { /** * Returns a wrapper for the mqtt.Client() class, configured for a TLS * connection with the AWS IoT platform and with arguments as specified * in options. */ constructor(options?: DeviceOptions); /** * Update the credentials set used to authenticate via WebSocket/SigV4. * * This method is designed to be invoked during the callback of the * getCredentialsForIdentity method in the AWS SDK for JavaScript. */ updateWebSocketCredentials(accessKeyId: string, secretKey: string, sessionToken: string, expiration: Date): void; on(event: "connect" | "close" | "reconnect" | "offline", listener: () => void): this; // Error | string comes from: // https://github.com/aws/aws-iot-device-sdk-js/blob/97b0b46/device/index.js#L744 // Remove when https://github.com/aws/aws-iot-device-sdk-js/issues/95 is fixed on(event: "error", listener: (error: Error | string) => void): this; /** Emitted when a message is received on a topic not related to any Thing Shadows */ on(event: "message", listener: (topic: string, payload: any) => void): this; // The following publish, subscribe, unsubscribe and end Definitions // are derived from the mqtt definition as they are re-surfaced through // thingShadow // https://github.com/DefinitelyTyped/DefinitelyTyped/blob/e7772769fab8c206449ce9673cac417370330aa9/mqtt/mqtt.d.ts#L199 /** * Publish a message to a topic * * @param topic to publish to * @param message to publish * @param publish options * @param called when publish succeeds or fails */ publish(topic: string, message: Buffer | string, options?: mqtt.ClientPublishOptions, callback?: (error?: Error) => void): mqtt.Client; /** * Subscribe to a topic or topics * @param topic to subscribe to or an Array of topics to subscribe to. It can also be an object. * @param the options to subscribe with * @param callback fired on suback */ subscribe(topic: string | string[] | mqtt.Topic, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client; /** * Unsubscribe from a topic or topics * * @param topic is a String topic or an array of topics to unsubscribe from * @param options * @param callback fired on unsuback */ unsubscribe(topic: string | string[], options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client; /** * end - close connection * * @param force passing it to true will close the client right away, without waiting for the in-flight messages to be acked. * This parameter is optional. * @param callback */ end(force?: boolean, callback?: Function): mqtt.Client; } export interface ThingShadowOptions extends DeviceOptions { /** the timeout for thing operations (default 10 seconds) */ operationTimeout?: number; } export interface RegisterOptions { /** * set to true to not subscribe to the delta sub-topic for this * Thing Shadow; used in cases where the application is not interested in * changes (e.g. update only.) (default false) */ ignoreDeltas?: boolean; /** * set to false to unsubscribe from all operation sub-topics while not * performing an operation (default true) */ persistentSubscribe?: boolean; /** * set to false to allow receiving messages with old version * numbers (default true) */ discardStale?: boolean; /** set to true to send version numbers with shadow updates (default true) */ enableVersioning?: boolean; } /** * The thingShadow class wraps an instance of the device class with * additional functionality to operate on Thing Shadows via the AWS IoT API. */ export class thingShadow extends NodeJS.EventEmitter { constructor(options?: ThingShadowOptions); /** * Register interest in the Thing Shadow named thingName. * * The thingShadow class will subscribe to any applicable topics, and will * fire events for the Thing Shadow until awsIot.thingShadow#unregister() * is called with thingName * * If the callback parameter is provided, it will be invoked after * registration is complete (i.e., when subscription ACKs have been received * for all shadow topics). Applications should wait until shadow * registration is complete before performing update/get/delete operations. */ register(thingName: string, options?: RegisterOptions, callback?: (error: Error, failedTopics: mqtt.Granted[]) => void): void /** * Unregister interest in the Thing Shadow named thingName. * * The thingShadow class will unsubscribe from all applicable topics * and no more events will be fired for thingName. */ unregister(thingName: string): void /** * Update the Thing Shadow named thingName with the state specified in the * JavaScript object stateObject. thingName must have been previously * registered using awsIot.thingShadow#register(). * * The thingShadow class will subscribe to all applicable topics and * publish stateObject on the update sub-topic. * * This function returns a clientToken, which is a unique value associated * with the update operation. When a "status" or "timeout" event is emitted, * the clientToken will be supplied as one of the parameters, allowing the * application to keep track of the status of each operation. The caller may * create their own clientToken value; if stateObject contains a clientToken * property, that will be used rather than the internally generated value. * Note that it should be of atomic type (i.e. numeric or string). * This function returns "null" if an operation is already in progress. */ update(thingName: string, stateObject: any): string | null; /** * Get the current state of the Thing Shadow named thingName, which must * have been previously registered using awsIot.thingShadow#register(). * The thingShadow class will subscribe to all applicable topics and * publish on the get sub-topic. * * This function returns a clientToken, which is a unique value * associated with the get operation. When a "status or "timeout" event * is emitted, the clientToken will be supplied as one of the parameters, * allowing the application to keep track of the status of each operation. * The caller may supply their own clientToken value (optional); if * supplied, the value of clientToken will be used rather than the * internally generated value. Note that this value should be of atomic * type (i.e. numeric or string). This function returns "null" if an * operation is already in progress. */ get(thingName: string, clientToken?: string): string | null; /** * Delete the Thing Shadow named thingName, which must have been previously * registered using awsIot.thingShadow#register(). The thingShadow class * will subscribe to all applicable topics and publish on the delete sub-topic. * * This function returns a clientToken, which is a unique value associated * with the delete operation. When a "status" or "timeout" event is * emitted, the clientToken will be supplied as one of the parameters, * allowing the application to keep track of the status of each operation. * The caller may supply their own clientToken value (optional); if * supplied, the value of clientToken will be used rather than the * internally generated value. Note that this value should be of atomic * type (i.e. numeric or string). This function returns "null" if an * operation is already in progress. */ delete(thingName: string, clientToken?: string): string | null; // The following publish, subscribe, unsubscribe and end Definitions // are copied from the mqtt definition as they are re-surfaced through // thingShadow // https://github.com/DefinitelyTyped/DefinitelyTyped/blob/e7772769fab8c206449ce9673cac417370330aa9/mqtt/mqtt.d.ts#L199 /** * Publish a message to a topic * * @param topic * @param message * @param options * @param callback */ publish(topic: string, message: Buffer, options?: mqtt.ClientPublishOptions, callback?: Function): mqtt.Client; publish(topic: string, message: string, options?: mqtt.ClientPublishOptions, callback?: Function): mqtt.Client; /** * Subscribe to a topic or topics * @param topic to subscribe to or an Array of topics to subscribe to. It can also be an object. * @param the options to subscribe with * @param callback fired on suback */ subscribe(topic: string, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client; subscribe(topic: string[], options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client; subscribe(topic: mqtt.Topic, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client; /** * Unsubscribe from a topic or topics * * @param topic is a String topic or an array of topics to unsubscribe from * @param options * @param callback fired on unsuback */ unsubscribe(topic: string, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client; unsubscribe(topic: string[], options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client; /** * end - close connection * * @param force passing it to true will close the client right away, without waiting for the in-flight messages to be acked. * This parameter is optional. * @param callback */ end(force?: boolean, callback?: Function): mqtt.Client; on(event: "connect" | "close" | "reconnect" | "offline", listener: () => void): this; on(event: "error", listener: (error: Error) => void): this; /** Emitted when a message is received on a topic not related to any Thing Shadows */ on(event: "message", listener: (topic: string, payload: any) => void): this; /** * Emitted when an operation update|get|delete completes. * * thingName - name of the Thing Shadow for which the operation has completed * stat - status of the operation accepted|rejected * clientToken - the operation"s clientToken * stateObject - the stateObject returned for the operation * * Applications can use clientToken values to correlate status events with * the operations that they are associated with by saving the clientTokens * returned from each operation. */ on(event: "status", listener: (thingName: string, operationStatus: "accepted" | "rejected", clientToken: string, stateObject: any) => void): this; /** Emitted when an operation update|get|delete has timed out. */ on(event: "timeout", listener: (thingName: string, clientToken: string) => void): this; /** Emitted when a delta has been received for a registered Thing Shadow. */ on(event: "delta", listener: (thingName: string, stateObject: any) => void): this; /** Emitted when a different client"s update or delete operation is accepted on the shadow. */ on(event: "foreignStateChange", listener: (thingName: string, operation: "update" | "delete", stateObject: any) => void): this; }
types/aws-iot-device-sdk/index.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2ff4dff832042617a3653eceefb6fe95a546f3a4
[ 0.9955964684486389, 0.027071690186858177, 0.00016306337784044445, 0.0001818462333176285, 0.15515415370464325 ]
{ "id": 3, "code_window": [ " *\n", " * @param topic is a String topic or an array of topics to unsubscribe from\n", " * @param options\n", " * @param callback fired on unsuback\n", " */\n", " unsubscribe(topic: string, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n", " unsubscribe(topic: string[], options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n", "\n", " /**\n", " * end - close connection\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " unsubscribe(topic: string | string[], options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n" ], "file_path": "types/aws-iot-device-sdk/index.d.ts", "type": "replace", "edit_start_line_idx": 355 }
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; export default class TiWarning extends React.Component<IconBaseProps> { }
types/react-icons/ti/warning.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2ff4dff832042617a3653eceefb6fe95a546f3a4
[ 0.0001775002310751006, 0.0001775002310751006, 0.0001775002310751006, 0.0001775002310751006, 0 ]
{ "id": 3, "code_window": [ " *\n", " * @param topic is a String topic or an array of topics to unsubscribe from\n", " * @param options\n", " * @param callback fired on unsuback\n", " */\n", " unsubscribe(topic: string, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n", " unsubscribe(topic: string[], options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n", "\n", " /**\n", " * end - close connection\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " unsubscribe(topic: string | string[], options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n" ], "file_path": "types/aws-iot-device-sdk/index.d.ts", "type": "replace", "edit_start_line_idx": 355 }
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; export default class IoSocialTumblr extends React.Component<IconBaseProps> { }
types/react-icons/io/social-tumblr.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2ff4dff832042617a3653eceefb6fe95a546f3a4
[ 0.00017659791046753526, 0.00017659791046753526, 0.00017659791046753526, 0.00017659791046753526, 0 ]
{ "id": 3, "code_window": [ " *\n", " * @param topic is a String topic or an array of topics to unsubscribe from\n", " * @param options\n", " * @param callback fired on unsuback\n", " */\n", " unsubscribe(topic: string, options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n", " unsubscribe(topic: string[], options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n", "\n", " /**\n", " * end - close connection\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " unsubscribe(topic: string | string[], options?: mqtt.ClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;\n" ], "file_path": "types/aws-iot-device-sdk/index.d.ts", "type": "replace", "edit_start_line_idx": 355 }
// Type definitions for nodemailer-smtp-transport 2.7 // Project: https://github.com/andris9/nodemailer-smtp-transport // Definitions by: Rogier Schouten <https://github.com/rogierschouten> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="node" /> import tls = require("tls"); import nodemailer = require('nodemailer'); declare namespace smtpTransport { export interface AuthOptions { /** is the username */ user?: string; /** is the password for the user if normal login is used */ pass?: string; /** indicates the authetication type, defaults to ‘login’, other option is ‘oauth2’ */ type?: any; /** is the registered client id of the application */ clientId?: string; /** is the registered client secret of the application */ clientSecret?: string; /** is an optional refresh token. If it is provided then Nodemailer tries to generate a new access token if existing one expires or fails */ refreshToken?: string; /** is the access token for the user. Required only if refreshToken is not available and there is no token refresh callback specified */ accessToken?: string; /** is an optional expiration time for the current accessToken */ expires?: number; /** is an optional HTTP endpoint for requesting new access tokens. This value defaults to Gmail */ accessUrl?: string; /** service client id, you can find it from the “client_id” field in the service key file */ serviceClient?: string; /** is the private key contents, you can find it from the “private_key” field in the service key file */ privateKey?: string; } export interface SmtpOptions { /** * Fills in certain SMTP configurations options (e.g. 'host', 'port', and 'secure') for * well-known services. Possible values: * - '1und1' * - 'AOL' * - 'DebugMail.io' * - 'DynectEmail' * - 'FastMail' * - 'GandiMail' * - 'Gmail' * - 'Godaddy' * - 'GodaddyAsia' * - 'GodaddyEurope' * - 'hot.ee' * - 'Hotmail' * - 'iCloud' * - 'mail.ee' * - 'Mail.ru' * - 'Mailgun' * - 'Mailjet' * - 'Mandrill' * - 'Naver' * - 'Postmark' * - 'QQ' * - 'QQex' * - 'SendCloud' * - 'SendGrid' * - 'SES' * - 'Sparkpost' * - 'Yahoo' * - 'Yandex' * - 'Zoho' */ service?: string; /** * is the port to connect to (defaults to 25 or 465) */ port?: number; /** * is the hostname or IP address to connect to (defaults to 'localhost') */ host?: string; /** * defines if the connection should use SSL (if true) or not (if false) */ secure?: boolean; /** * defines authentication data (see authentication section below) */ auth?: AuthOptions; /** * if this is true and secure is false then Nodemailer tries to use STARTTLS even if the server does not advertise support for it. If the connection can not be encrypted then message is not sent */ requireTLS?: boolean; /** * if this is true and secure is false then TLS is not used even if the server supports STARTTLS extension */ ignoreTLS?: boolean; /** * optional hostname of the client, used for identifying to the server */ name?: string; /** * is the local interface to bind to for network connections */ localAddress?: string; /** * how many milliseconds to wait for the connection to establish */ connectionTimeout?: number; /** * how many milliseconds to wait for the greeting after connection is established */ greetingTimeout?: number; /** * how many milliseconds of inactivity to allow */ socketTimeout?: number; /** * if true, the connection emits all traffic between client and server as 'log' events */ debug?: boolean; /** * optional bunyan compatible logger instance. If set to true then logs to console. If value is not set or is false then nothing is logged */ logger?: boolean; /** * defines preferred authentication method, eg. 'PLAIN' */ authMethod?: string; /** * defines additional options to be passed to the socket constructor, eg. {rejectUnauthorized: true} */ tls?: tls.ConnectionOptions; /** * see Pooled SMTP for details about connection pooling */ pool?: { /** * set to true to use pooled connections (defaults to false) instead of creating a new connection for every email */ pool?: boolean; /** * is the count of maximum simultaneous connections to make against the SMTP server (defaults to 5) */ maxConnections?: boolean; /** * limits the message count to be sent using a single connection (defaults to 100). After maxMessages is reached the connection is dropped and a new one is created for the following messages */ maxMessages?: boolean; /** * defines the time measuring period in milliseconds (defaults to 1000, ie. to 1 second) for rate limiting */ rateDelta?: boolean; /** * limits the message count to be sent in rateDelta time. Once rateLimit is reached, sending is paused until the end of the measuring period. */ rateLimit?: boolean; }; /** * if true, then does not allow to use files as content. Use it when you want to use JSON data from untrusted source as the email. If an attachment or message node tries to fetch something from a file the sending returns an error */ disableFileAccess?: boolean; /** * if true, then does not allow to use Urls as content */ disableUrlAccess?: boolean; /** * a proxy URL */ proxy?: string; } } declare function smtpTransport(options: smtpTransport.SmtpOptions): nodemailer.Transport; export = smtpTransport;
types/nodemailer-smtp-transport/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2ff4dff832042617a3653eceefb6fe95a546f3a4
[ 0.000626552093308419, 0.00022878649178892374, 0.00016492149734403938, 0.0001787367946235463, 0.00010731936345109716 ]
{ "id": 0, "code_window": [ "\t\t\t}));\n", "\t\t}\n", "\t}\n", "\n", "\tprotected abstract _onInputChanged(): boolean;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ "\tpublic abstract find(previous: boolean): void;\n", "\tpublic abstract findFirst(): void;\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/find/simpleFindWidget.ts", "type": "add", "edit_start_line_idx": 195 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./simpleFindWidget'; import * as nls from 'vs/nls'; import * as dom from 'vs/base/browser/dom'; import { FindInput } from 'vs/base/browser/ui/findinput/findInput'; import { Widget } from 'vs/base/browser/ui/widget'; import { Delayer } from 'vs/base/common/async'; import { KeyCode } from 'vs/base/common/keyCodes'; import { FindReplaceState } from 'vs/editor/contrib/find/browser/findState'; import { IMessage as InputBoxMessage } from 'vs/base/browser/ui/inputbox/inputBox'; import { SimpleButton, findPreviousMatchIcon, findNextMatchIcon, NLS_NO_RESULTS, NLS_MATCHES_LOCATION } from 'vs/editor/contrib/find/browser/findWidget'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { ContextScopedFindInput } from 'vs/platform/history/browser/contextScopedHistoryWidget'; import { widgetClose } from 'vs/platform/theme/common/iconRegistry'; import * as strings from 'vs/base/common/strings'; import { TerminalCommandId } from 'vs/workbench/contrib/terminal/common/terminal'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { showHistoryKeybindingHint } from 'vs/platform/history/browser/historyWidgetKeybindingHint'; import { alert as alertFn } from 'vs/base/browser/ui/aria/aria'; import { defaultInputBoxStyles, defaultToggleStyles } from 'vs/platform/theme/browser/defaultStyles'; const NLS_FIND_INPUT_LABEL = nls.localize('label.find', "Find"); const NLS_FIND_INPUT_PLACEHOLDER = nls.localize('placeholder.find', "Find (\u21C5 for history)"); const NLS_PREVIOUS_MATCH_BTN_LABEL = nls.localize('label.previousMatchButton', "Previous Match"); const NLS_NEXT_MATCH_BTN_LABEL = nls.localize('label.nextMatchButton', "Next Match"); const NLS_CLOSE_BTN_LABEL = nls.localize('label.closeButton', "Close"); interface IFindOptions { showCommonFindToggles?: boolean; checkImeCompletionState?: boolean; showResultCount?: boolean; appendCaseSensitiveLabel?: string; appendRegexLabel?: string; appendWholeWordsLabel?: string; type?: 'Terminal' | 'Webview'; } const SIMPLE_FIND_WIDGET_INITIAL_WIDTH = 310; const MATCHES_COUNT_WIDTH = 68; export abstract class SimpleFindWidget extends Widget { private readonly _findInput: FindInput; private readonly _domNode: HTMLElement; private readonly _innerDomNode: HTMLElement; private readonly _focusTracker: dom.IFocusTracker; private readonly _findInputFocusTracker: dom.IFocusTracker; private readonly _updateHistoryDelayer: Delayer<void>; private readonly prevBtn: SimpleButton; private readonly nextBtn: SimpleButton; private _matchesCount: HTMLElement | undefined; private _isVisible: boolean = false; private _foundMatch: boolean = false; private _width: number = 0; constructor( state: FindReplaceState = new FindReplaceState(), options: IFindOptions, contextViewService: IContextViewService, contextKeyService: IContextKeyService, private readonly _keybindingService: IKeybindingService ) { super(); this._findInput = this._register(new ContextScopedFindInput(null, contextViewService, { label: NLS_FIND_INPUT_LABEL, placeholder: NLS_FIND_INPUT_PLACEHOLDER, validation: (value: string): InputBoxMessage | null => { if (value.length === 0 || !this._findInput.getRegex()) { return null; } try { new RegExp(value); return null; } catch (e) { this._foundMatch = false; this.updateButtons(this._foundMatch); return { content: e.message }; } }, showCommonFindToggles: options.showCommonFindToggles, appendCaseSensitiveLabel: options.appendCaseSensitiveLabel && options.type === 'Terminal' ? this._getKeybinding(TerminalCommandId.ToggleFindCaseSensitive) : undefined, appendRegexLabel: options.appendRegexLabel && options.type === 'Terminal' ? this._getKeybinding(TerminalCommandId.ToggleFindRegex) : undefined, appendWholeWordsLabel: options.appendWholeWordsLabel && options.type === 'Terminal' ? this._getKeybinding(TerminalCommandId.ToggleFindWholeWord) : undefined, showHistoryHint: () => showHistoryKeybindingHint(_keybindingService), inputBoxStyles: defaultInputBoxStyles, toggleStyles: defaultToggleStyles }, contextKeyService)); // Find History with update delayer this._updateHistoryDelayer = new Delayer<void>(500); this._register(this._findInput.onInput(async (e) => { if (!options.checkImeCompletionState || !this._findInput.isImeSessionInProgress) { this._foundMatch = this._onInputChanged(); if (options.showResultCount) { await this.updateResultCount(); } this.updateButtons(this._foundMatch); this.focusFindBox(); this._delayedUpdateHistory(); } })); this._findInput.setRegex(!!state.isRegex); this._findInput.setCaseSensitive(!!state.matchCase); this._findInput.setWholeWords(!!state.wholeWord); this._register(this._findInput.onDidOptionChange(() => { state.change({ isRegex: this._findInput.getRegex(), wholeWord: this._findInput.getWholeWords(), matchCase: this._findInput.getCaseSensitive() }, true); })); this._register(state.onFindReplaceStateChange(() => { this._findInput.setRegex(state.isRegex); this._findInput.setWholeWords(state.wholeWord); this._findInput.setCaseSensitive(state.matchCase); this.findFirst(); })); this.prevBtn = this._register(new SimpleButton({ label: NLS_PREVIOUS_MATCH_BTN_LABEL, icon: findPreviousMatchIcon, onTrigger: () => { this.find(true); } })); this.nextBtn = this._register(new SimpleButton({ label: NLS_NEXT_MATCH_BTN_LABEL, icon: findNextMatchIcon, onTrigger: () => { this.find(false); } })); const closeBtn = this._register(new SimpleButton({ label: NLS_CLOSE_BTN_LABEL, icon: widgetClose, onTrigger: () => { this.hide(); } })); this._innerDomNode = document.createElement('div'); this._innerDomNode.classList.add('simple-find-part'); this._innerDomNode.appendChild(this._findInput.domNode); this._innerDomNode.appendChild(this.prevBtn.domNode); this._innerDomNode.appendChild(this.nextBtn.domNode); this._innerDomNode.appendChild(closeBtn.domNode); // _domNode wraps _innerDomNode, ensuring that this._domNode = document.createElement('div'); this._domNode.classList.add('simple-find-part-wrapper'); this._domNode.appendChild(this._innerDomNode); this.onkeyup(this._innerDomNode, e => { if (e.equals(KeyCode.Escape)) { this.hide(); e.preventDefault(); return; } }); this._focusTracker = this._register(dom.trackFocus(this._innerDomNode)); this._register(this._focusTracker.onDidFocus(this._onFocusTrackerFocus.bind(this))); this._register(this._focusTracker.onDidBlur(this._onFocusTrackerBlur.bind(this))); this._findInputFocusTracker = this._register(dom.trackFocus(this._findInput.domNode)); this._register(this._findInputFocusTracker.onDidFocus(this._onFindInputFocusTrackerFocus.bind(this))); this._register(this._findInputFocusTracker.onDidBlur(this._onFindInputFocusTrackerBlur.bind(this))); this._register(dom.addDisposableListener(this._innerDomNode, 'click', (event) => { event.stopPropagation(); })); if (options?.showResultCount) { this._domNode.classList.add('result-count'); this._matchesCount = document.createElement('div'); this._matchesCount.className = 'matchesCount'; this._findInput.domNode.insertAdjacentElement('afterend', this._matchesCount); this._register(this._findInput.onDidChange(() => { this.updateResultCount(); this.updateButtons(this._foundMatch); })); } } protected abstract _onInputChanged(): boolean; protected abstract find(previous: boolean): void; protected abstract findFirst(): void; protected abstract _onFocusTrackerFocus(): void; protected abstract _onFocusTrackerBlur(): void; protected abstract _onFindInputFocusTrackerFocus(): void; protected abstract _onFindInputFocusTrackerBlur(): void; protected abstract _getResultCount(): Promise<{ resultIndex: number; resultCount: number } | undefined>; protected get inputValue() { return this._findInput.getValue(); } public get focusTracker(): dom.IFocusTracker { return this._focusTracker; } private _getKeybinding(actionId: string): string { const kb = this._keybindingService?.lookupKeybinding(actionId); if (!kb) { return ''; } return ` (${kb.getLabel()})`; } override dispose() { super.dispose(); if (this._domNode && this._domNode.parentElement) { this._domNode.parentElement.removeChild(this._domNode); } } public isVisible(): boolean { return this._isVisible; } public getDomNode() { return this._domNode; } public reveal(initialInput?: string, animated = true): void { if (initialInput) { this._findInput.setValue(initialInput); } if (this._isVisible) { this._findInput.select(); return; } this._isVisible = true; this.updateButtons(this._foundMatch); this.layout(); setTimeout(() => { this._innerDomNode.classList.toggle('suppress-transition', !animated); this._innerDomNode.classList.add('visible', 'visible-transition'); this._innerDomNode.setAttribute('aria-hidden', 'false'); this._findInput.select(); if (!animated) { setTimeout(() => { this._innerDomNode.classList.remove('suppress-transition'); }, 0); } }, 0); } public show(initialInput?: string): void { if (initialInput && !this._isVisible) { this._findInput.setValue(initialInput); } this._isVisible = true; this.layout(); setTimeout(() => { this._innerDomNode.classList.add('visible', 'visible-transition'); this._innerDomNode.setAttribute('aria-hidden', 'false'); }, 0); } public hide(animated = true): void { if (this._isVisible) { this._innerDomNode.classList.toggle('suppress-transition', !animated); this._innerDomNode.classList.remove('visible-transition'); this._innerDomNode.setAttribute('aria-hidden', 'true'); // Need to delay toggling visibility until after Transition, then visibility hidden - removes from tabIndex list setTimeout(() => { this._isVisible = false; this.updateButtons(this._foundMatch); this._innerDomNode.classList.remove('visible', 'suppress-transition'); }, animated ? 200 : 0); } } public layout(width: number = this._width): void { this._width = width; if (!this._isVisible) { return; } if (this._matchesCount) { let reducedFindWidget = false; if (SIMPLE_FIND_WIDGET_INITIAL_WIDTH + MATCHES_COUNT_WIDTH + 28 >= width) { reducedFindWidget = true; } this._innerDomNode.classList.toggle('reduced-find-widget', reducedFindWidget); } } protected _delayedUpdateHistory() { this._updateHistoryDelayer.trigger(this._updateHistory.bind(this)); } protected _updateHistory() { this._findInput.inputBox.addToHistory(); } protected _getRegexValue(): boolean { return this._findInput.getRegex(); } protected _getWholeWordValue(): boolean { return this._findInput.getWholeWords(); } protected _getCaseSensitiveValue(): boolean { return this._findInput.getCaseSensitive(); } protected updateButtons(foundMatch: boolean) { const hasInput = this.inputValue.length > 0; this.prevBtn.setEnabled(this._isVisible && hasInput && foundMatch); this.nextBtn.setEnabled(this._isVisible && hasInput && foundMatch); } protected focusFindBox() { // Focus back onto the find box, which // requires focusing onto the next button first this.nextBtn.focus(); this._findInput.inputBox.focus(); } async updateResultCount(): Promise<void> { if (!this._matchesCount) { return; } const count = await this._getResultCount(); this._matchesCount.innerText = ''; let label = ''; this._matchesCount.classList.toggle('no-results', false); if (count?.resultCount !== undefined && count?.resultCount === 0) { label = NLS_NO_RESULTS; if (!!this.inputValue) { this._matchesCount.classList.toggle('no-results', true); } } else if (count?.resultCount) { label = strings.format(NLS_MATCHES_LOCATION, count.resultIndex + 1, count?.resultCount); } alertFn(this._announceSearchResults(label, this.inputValue)); this._matchesCount.appendChild(document.createTextNode(label)); this._foundMatch = !!count && count.resultCount > 0; } private _announceSearchResults(label: string, searchString?: string): string { if (!searchString) { return nls.localize('ariaSearchNoInput', "Enter search input"); } if (label === NLS_NO_RESULTS) { return searchString === '' ? nls.localize('ariaSearchNoResultEmpty', "{0} found", label) : nls.localize('ariaSearchNoResult', "{0} found for '{1}'", label, searchString); } return nls.localize('ariaSearchNoResultWithLineNumNoCurrentMatch', "{0} found for '{1}'", label, searchString); } }
src/vs/workbench/contrib/codeEditor/browser/find/simpleFindWidget.ts
1
https://github.com/microsoft/vscode/commit/626c64bc9a48591e226edd3c04a4bef9e886828e
[ 0.9991539716720581, 0.12832075357437134, 0.00016709862393327057, 0.0003024256438948214, 0.31693482398986816 ]
{ "id": 0, "code_window": [ "\t\t\t}));\n", "\t\t}\n", "\t}\n", "\n", "\tprotected abstract _onInputChanged(): boolean;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ "\tpublic abstract find(previous: boolean): void;\n", "\tpublic abstract findFirst(): void;\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/find/simpleFindWidget.ts", "type": "add", "edit_start_line_idx": 195 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ declare module 'vscode' { // https://github.com/microsoft/vscode/issues/106744 export interface NotebookCellOutput { /** * @deprecated */ id: string; } }
src/vscode-dts/vscode.proposed.notebookDeprecated.d.ts
0
https://github.com/microsoft/vscode/commit/626c64bc9a48591e226edd3c04a4bef9e886828e
[ 0.0001785244094207883, 0.00017569777264725417, 0.00017287113587372005, 0.00017569777264725417, 0.000002826636773534119 ]
{ "id": 0, "code_window": [ "\t\t\t}));\n", "\t\t}\n", "\t}\n", "\n", "\tprotected abstract _onInputChanged(): boolean;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ "\tpublic abstract find(previous: boolean): void;\n", "\tpublic abstract findFirst(): void;\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/find/simpleFindWidget.ts", "type": "add", "edit_start_line_idx": 195 }
<svg width="53" height="36" viewBox="0 0 53 36" fill="none" xmlns="http://www.w3.org/2000/svg"> <g clip-path="url(#clip0)"> <path fill-rule="evenodd" clip-rule="evenodd" d="M48.0364 4.01042H4.00779L4.00779 32.0286H48.0364V4.01042ZM4.00779 0.0078125C1.79721 0.0078125 0.00518799 1.79984 0.00518799 4.01042V32.0286C0.00518799 34.2392 1.79721 36.0312 4.00779 36.0312H48.0364C50.247 36.0312 52.039 34.2392 52.039 32.0286V4.01042C52.039 1.79984 50.247 0.0078125 48.0364 0.0078125H4.00779ZM8.01042 8.01302H12.013V12.0156H8.01042V8.01302ZM20.0182 8.01302H16.0156V12.0156H20.0182V8.01302ZM24.0208 8.01302H28.0234V12.0156H24.0208V8.01302ZM36.0286 8.01302H32.026V12.0156H36.0286V8.01302ZM40.0312 8.01302H44.0339V12.0156H40.0312V8.01302ZM16.0156 16.0182H8.01042V20.0208H16.0156V16.0182ZM20.0182 16.0182H24.0208V20.0208H20.0182V16.0182ZM32.026 16.0182H28.0234V20.0208H32.026V16.0182ZM44.0339 16.0182V20.0208H36.0286V16.0182H44.0339ZM12.013 24.0234H8.01042V28.026H12.013V24.0234ZM16.0156 24.0234H36.0286V28.026H16.0156V24.0234ZM44.0339 24.0234H40.0312V28.026H44.0339V24.0234Z" fill="#424242"/> </g> <defs> <clipPath id="clip0"> <rect width="53" height="36" fill="white"/> </clipPath> </defs> </svg>
src/vs/editor/standalone/browser/iPadShowKeyboard/keyboard-light.svg
0
https://github.com/microsoft/vscode/commit/626c64bc9a48591e226edd3c04a4bef9e886828e
[ 0.002852353733032942, 0.0015146533260121942, 0.0001769528753357008, 0.0015146533260121942, 0.0013377004070207477 ]
{ "id": 0, "code_window": [ "\t\t\t}));\n", "\t\t}\n", "\t}\n", "\n", "\tprotected abstract _onInputChanged(): boolean;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ "\tpublic abstract find(previous: boolean): void;\n", "\tpublic abstract findFirst(): void;\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/find/simpleFindWidget.ts", "type": "add", "edit_start_line_idx": 195 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as editorRange from 'vs/editor/common/core/range'; import { createPrivateApiFor, getPrivateApiFor, IExtHostTestItemApi } from 'vs/workbench/api/common/extHostTestingPrivateApi'; import { TestId, TestIdPathParts } from 'vs/workbench/contrib/testing/common/testId'; import { createTestItemChildren, ExtHostTestItemEvent, ITestChildrenLike, ITestItemApi, ITestItemChildren, TestItemCollection, TestItemEventOp } from 'vs/workbench/contrib/testing/common/testItemCollection'; import { denamespaceTestTag, ITestItem, ITestItemContext } from 'vs/workbench/contrib/testing/common/testTypes'; import type * as vscode from 'vscode'; import * as Convert from 'vs/workbench/api/common/extHostTypeConverters'; import { URI } from 'vs/base/common/uri'; import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors'; const testItemPropAccessor = <K extends keyof vscode.TestItem>( api: IExtHostTestItemApi, defaultValue: vscode.TestItem[K], equals: (a: vscode.TestItem[K], b: vscode.TestItem[K]) => boolean, toUpdate: (newValue: vscode.TestItem[K], oldValue: vscode.TestItem[K]) => ExtHostTestItemEvent, ) => { let value = defaultValue; return { enumerable: true, configurable: false, get() { return value; }, set(newValue: vscode.TestItem[K]) { if (!equals(value, newValue)) { const oldValue = value; value = newValue; api.listener?.(toUpdate(newValue, oldValue)); } }, }; }; type WritableProps = Pick<vscode.TestItem, 'range' | 'label' | 'description' | 'sortText' | 'canResolveChildren' | 'busy' | 'error' | 'tags'>; const strictEqualComparator = <T>(a: T, b: T) => a === b; const propComparators: { [K in keyof Required<WritableProps>]: (a: vscode.TestItem[K], b: vscode.TestItem[K]) => boolean } = { range: (a, b) => { if (a === b) { return true; } if (!a || !b) { return false; } return a.isEqual(b); }, label: strictEqualComparator, description: strictEqualComparator, sortText: strictEqualComparator, busy: strictEqualComparator, error: strictEqualComparator, canResolveChildren: strictEqualComparator, tags: (a, b) => { if (a.length !== b.length) { return false; } if (a.some(t1 => !b.find(t2 => t1.id === t2.id))) { return false; } return true; }, }; const evSetProps = <T>(fn: (newValue: T) => Partial<ITestItem>): (newValue: T) => ExtHostTestItemEvent => v => ({ op: TestItemEventOp.SetProp, update: fn(v) }); const makePropDescriptors = (api: IExtHostTestItemApi, label: string): { [K in keyof Required<WritableProps>]: PropertyDescriptor } => ({ range: (() => { let value: vscode.Range | undefined; const updateProps = evSetProps<vscode.Range | undefined>(r => ({ range: editorRange.Range.lift(Convert.Range.from(r)) })); return { enumerable: true, configurable: false, get() { return value; }, set(newValue: vscode.Range | undefined) { api.listener?.({ op: TestItemEventOp.DocumentSynced }); if (!propComparators.range(value, newValue)) { value = newValue; api.listener?.(updateProps(newValue)); } }, }; })(), label: testItemPropAccessor<'label'>(api, label, propComparators.label, evSetProps(label => ({ label }))), description: testItemPropAccessor<'description'>(api, undefined, propComparators.description, evSetProps(description => ({ description }))), sortText: testItemPropAccessor<'sortText'>(api, undefined, propComparators.sortText, evSetProps(sortText => ({ sortText }))), canResolveChildren: testItemPropAccessor<'canResolveChildren'>(api, false, propComparators.canResolveChildren, state => ({ op: TestItemEventOp.UpdateCanResolveChildren, state, })), busy: testItemPropAccessor<'busy'>(api, false, propComparators.busy, evSetProps(busy => ({ busy }))), error: testItemPropAccessor<'error'>(api, undefined, propComparators.error, evSetProps(error => ({ error: Convert.MarkdownString.fromStrict(error) || null }))), tags: testItemPropAccessor<'tags'>(api, [], propComparators.tags, (current, previous) => ({ op: TestItemEventOp.SetTags, new: current.map(Convert.TestTag.from), old: previous.map(Convert.TestTag.from), })), }); const toItemFromPlain = (item: ITestItem.Serialized): TestItemImpl => { const testId = TestId.fromString(item.extId); const testItem = new TestItemImpl(testId.controllerId, testId.localId, item.label, URI.revive(item.uri) || undefined); testItem.range = Convert.Range.to(item.range || undefined); testItem.description = item.description || undefined; testItem.sortText = item.sortText || undefined; testItem.tags = item.tags.map(t => Convert.TestTag.to({ id: denamespaceTestTag(t).tagId })); return testItem; }; export const toItemFromContext = (context: ITestItemContext): TestItemImpl => { let node: TestItemImpl | undefined; for (const test of context.tests) { const next = toItemFromPlain(test.item); getPrivateApiFor(next).parent = node; node = next; } return node!; }; export class TestItemImpl implements vscode.TestItem { public readonly id!: string; public readonly uri!: vscode.Uri | undefined; public readonly children!: ITestItemChildren<vscode.TestItem>; public readonly parent!: TestItemImpl | undefined; public range!: vscode.Range | undefined; public description!: string | undefined; public sortText!: string | undefined; public label!: string; public error!: string | vscode.MarkdownString; public busy!: boolean; public canResolveChildren!: boolean; public tags!: readonly vscode.TestTag[]; /** * Note that data is deprecated and here for back-compat only */ constructor(controllerId: string, id: string, label: string, uri: vscode.Uri | undefined) { if (id.includes(TestIdPathParts.Delimiter)) { throw new Error(`Test IDs may not include the ${JSON.stringify(id)} symbol`); } const api = createPrivateApiFor(this, controllerId); Object.defineProperties(this, { id: { value: id, enumerable: true, writable: false, }, uri: { value: uri, enumerable: true, writable: false, }, parent: { enumerable: false, get() { return api.parent instanceof TestItemRootImpl ? undefined : api.parent; }, }, children: { value: createTestItemChildren(api, getPrivateApiFor, TestItemImpl), enumerable: true, writable: false, }, ...makePropDescriptors(api, label), }); } } export class TestItemRootImpl extends TestItemImpl { public readonly _isRoot = true; constructor(controllerId: string, label: string) { super(controllerId, controllerId, label, undefined); } } export class ExtHostTestItemCollection extends TestItemCollection<TestItemImpl> { constructor(controllerId: string, controllerLabel: string, editors: ExtHostDocumentsAndEditors) { super({ controllerId, getDocumentVersion: uri => uri && editors.getDocument(uri)?.version, getApiFor: getPrivateApiFor as (impl: TestItemImpl) => ITestItemApi<TestItemImpl>, getChildren: (item) => item.children as ITestChildrenLike<TestItemImpl>, root: new TestItemRootImpl(controllerId, controllerLabel), toITestItem: Convert.TestItem.from, }); } }
src/vs/workbench/api/common/extHostTestItem.ts
0
https://github.com/microsoft/vscode/commit/626c64bc9a48591e226edd3c04a4bef9e886828e
[ 0.0048767803236842155, 0.00042060023406520486, 0.00016391623648814857, 0.00016733267693780363, 0.001023483113385737 ]
{ "id": 1, "code_window": [ "\tprotected abstract _onInputChanged(): boolean;\n", "\tprotected abstract find(previous: boolean): void;\n", "\tprotected abstract findFirst(): void;\n", "\tprotected abstract _onFocusTrackerFocus(): void;\n", "\tprotected abstract _onFocusTrackerBlur(): void;\n", "\tprotected abstract _onFindInputFocusTrackerFocus(): void;\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/codeEditor/browser/find/simpleFindWidget.ts", "type": "replace", "edit_start_line_idx": 196 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import * as dom from 'vs/base/browser/dom'; import { Action, IAction } from 'vs/base/common/actions'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IThemeService, ThemeIcon, Themable } from 'vs/platform/theme/common/themeService'; import { switchTerminalActionViewItemSeparator, switchTerminalShowTabsTitle } from 'vs/workbench/contrib/terminal/browser/terminalActions'; import { INotificationService, IPromptChoice, Severity } from 'vs/platform/notification/common/notification'; import { ICreateTerminalOptions, ITerminalGroupService, ITerminalInstance, ITerminalService, TerminalConnectionState, TerminalDataTransfers } from 'vs/workbench/contrib/terminal/browser/terminal'; import { ViewPane, IViewPaneOptions } from 'vs/workbench/browser/parts/views/viewPane'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IViewDescriptorService } from 'vs/workbench/common/views'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { IMenu, IMenuService, MenuId, MenuItemAction } from 'vs/platform/actions/common/actions'; import { ITerminalProfileResolverService, ITerminalProfileService, TerminalCommandId } from 'vs/workbench/contrib/terminal/common/terminal'; import { TerminalSettingId, ITerminalProfile, TerminalLocation } from 'vs/platform/terminal/common/terminal'; import { ActionViewItem, SelectActionViewItem } from 'vs/base/browser/ui/actionbar/actionViewItems'; import { attachSelectBoxStyler, attachStylerCallback } from 'vs/platform/theme/common/styler'; import { selectBorder } from 'vs/platform/theme/common/colorRegistry'; import { ISelectOptionItem } from 'vs/base/browser/ui/selectBox/selectBox'; import { IActionViewItem } from 'vs/base/browser/ui/actionbar/actionbar'; import { TerminalTabbedView } from 'vs/workbench/contrib/terminal/browser/terminalTabbedView'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { renderLabelWithIcons } from 'vs/base/browser/ui/iconLabel/iconLabels'; import { getColorForSeverity } from 'vs/workbench/contrib/terminal/browser/terminalStatusList'; import { createAndFillInContextMenuActions, MenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { DropdownWithPrimaryActionViewItem } from 'vs/platform/actions/browser/dropdownWithPrimaryActionViewItem'; import { dispose, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { ColorScheme } from 'vs/platform/theme/common/theme'; import { getColorClass, getUriClasses } from 'vs/workbench/contrib/terminal/browser/terminalIcon'; import { withNullAsUndefined } from 'vs/base/common/types'; import { getTerminalActionBarArgs } from 'vs/workbench/contrib/terminal/browser/terminalMenus'; import { TerminalContextKeys } from 'vs/workbench/contrib/terminal/common/terminalContextKey'; import { getShellIntegrationTooltip } from 'vs/workbench/contrib/terminal/browser/terminalTooltip'; import { ServicesAccessor } from 'vs/editor/browser/editorExtensions'; import { TerminalCapability } from 'vs/platform/terminal/common/capabilities/capabilities'; export class TerminalViewPane extends ViewPane { private _fontStyleElement: HTMLElement | undefined; private _parentDomElement: HTMLElement | undefined; private _terminalTabbedView?: TerminalTabbedView; get terminalTabbedView(): TerminalTabbedView | undefined { return this._terminalTabbedView; } private _isWelcomeShowing: boolean = false; private _newDropdown: DropdownWithPrimaryActionViewItem | undefined; private readonly _dropdownMenu: IMenu; private readonly _singleTabMenu: IMenu; private _viewShowing: IContextKey<boolean>; constructor( options: IViewPaneOptions, @IKeybindingService keybindingService: IKeybindingService, @IContextKeyService private readonly _contextKeyService: IContextKeyService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IConfigurationService private readonly _configurationService: IConfigurationService, @IContextMenuService private readonly _contextMenuService: IContextMenuService, @IInstantiationService private readonly _instantiationService: IInstantiationService, @ITerminalService private readonly _terminalService: ITerminalService, @ITerminalGroupService private readonly _terminalGroupService: ITerminalGroupService, @IThemeService themeService: IThemeService, @ITelemetryService telemetryService: ITelemetryService, @INotificationService private readonly _notificationService: INotificationService, @IKeybindingService private readonly _keybindingService: IKeybindingService, @IOpenerService openerService: IOpenerService, @IMenuService private readonly _menuService: IMenuService, @ITerminalProfileService private readonly _terminalProfileService: ITerminalProfileService, @ITerminalProfileResolverService private readonly _terminalProfileResolverService: ITerminalProfileResolverService, @IThemeService private readonly _themeService: IThemeService ) { super(options, keybindingService, _contextMenuService, _configurationService, _contextKeyService, viewDescriptorService, _instantiationService, openerService, themeService, telemetryService); this._register(this._terminalService.onDidRegisterProcessSupport(() => { this._onDidChangeViewWelcomeState.fire(); })); this._register(this._terminalService.onDidChangeInstances(() => { if (!this._isWelcomeShowing) { return; } this._isWelcomeShowing = true; this._onDidChangeViewWelcomeState.fire(); if (!this._terminalTabbedView && this._parentDomElement) { this._createTabsView(); this.layoutBody(this._parentDomElement.offsetHeight, this._parentDomElement.offsetWidth); } })); this._dropdownMenu = this._register(this._menuService.createMenu(MenuId.TerminalNewDropdownContext, this._contextKeyService)); this._singleTabMenu = this._register(this._menuService.createMenu(MenuId.TerminalInlineTabContext, this._contextKeyService)); this._register(this._terminalProfileService.onDidChangeAvailableProfiles(profiles => this._updateTabActionBar(profiles))); this._viewShowing = TerminalContextKeys.viewShowing.bindTo(this._contextKeyService); this._register(this.onDidChangeBodyVisibility(e => { if (e) { this._terminalTabbedView?.rerenderTabs(); } })); this._register(this._configurationService.onDidChangeConfiguration(e => { if (this._parentDomElement && (e.affectsConfiguration(TerminalSettingId.ShellIntegrationDecorationsEnabled) || e.affectsConfiguration(TerminalSettingId.ShellIntegrationEnabled))) { this._updateForShellIntegration(this._parentDomElement); } })); this._register(this._terminalService.onDidCreateInstance((i) => { i.capabilities.onDidAddCapability(c => { if (c === TerminalCapability.CommandDetection && this._gutterDecorationsEnabled()) { this._parentDomElement?.classList.add('shell-integration'); } }); })); } private _updateForShellIntegration(container: HTMLElement) { container.classList.toggle('shell-integration', this._gutterDecorationsEnabled()); } private _gutterDecorationsEnabled(): boolean { const decorationsEnabled = this._configurationService.getValue(TerminalSettingId.ShellIntegrationDecorationsEnabled); return (decorationsEnabled === 'both' || decorationsEnabled === 'gutter') && this._configurationService.getValue(TerminalSettingId.ShellIntegrationEnabled); } private _initializeTerminal() { if (this.isBodyVisible() && this._terminalService.isProcessSupportRegistered && this._terminalService.connectionState === TerminalConnectionState.Connected && !this._terminalGroupService.groups.length) { this._terminalService.createTerminal({ location: TerminalLocation.Panel }); } } override renderBody(container: HTMLElement): void { super.renderBody(container); if (!this._parentDomElement) { this._updateForShellIntegration(container); } this._parentDomElement = container; this._parentDomElement.classList.add('integrated-terminal'); this._fontStyleElement = document.createElement('style'); this._instantiationService.createInstance(TerminalThemeIconStyle, this._parentDomElement); if (!this.shouldShowWelcome()) { this._createTabsView(); } this._parentDomElement.appendChild(this._fontStyleElement); this._register(this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration(TerminalSettingId.FontFamily) || e.affectsConfiguration('editor.fontFamily')) { const configHelper = this._terminalService.configHelper; if (!configHelper.configFontIsMonospace()) { const choices: IPromptChoice[] = [{ label: nls.localize('terminal.useMonospace', "Use 'monospace'"), run: () => this.configurationService.updateValue(TerminalSettingId.FontFamily, 'monospace'), }]; this._notificationService.prompt(Severity.Warning, nls.localize('terminal.monospaceOnly', "The terminal only supports monospace fonts. Be sure to restart VS Code if this is a newly installed font."), choices); } } })); this._register(this.onDidChangeBodyVisibility(async visible => { this._viewShowing.set(visible); if (visible) { if (!this._terminalService.isProcessSupportRegistered) { this._onDidChangeViewWelcomeState.fire(); } this._initializeTerminal(); // we don't know here whether or not it should be focused, so // defer focusing the panel to the focus() call // to prevent overriding preserveFocus for extensions this._terminalGroupService.showPanel(false); } else { for (const instance of this._terminalGroupService.instances) { instance.resetFocusContextKey(); } } this._terminalGroupService.updateVisibility(); })); this._register(this._terminalService.onDidChangeConnectionState(() => this._initializeTerminal())); this.layoutBody(this._parentDomElement.offsetHeight, this._parentDomElement.offsetWidth); } private _createTabsView(): void { if (!this._parentDomElement) { return; } this._terminalTabbedView = this.instantiationService.createInstance(TerminalTabbedView, this._parentDomElement); } // eslint-disable-next-line @typescript-eslint/naming-convention protected override layoutBody(height: number, width: number): void { super.layoutBody(height, width); this._terminalTabbedView?.layout(width, height); } override getActionViewItem(action: Action): IActionViewItem | undefined { switch (action.id) { case TerminalCommandId.Split: { // Split needs to be special cased to force splitting within the panel, not the editor const that = this; const panelOnlySplitAction = new class extends Action { constructor() { super(action.id, action.label, action.class, action.enabled); this.checked = action.checked; this.tooltip = action.tooltip; } override dispose(): void { action.dispose(); } override async run() { const instance = that._terminalGroupService.activeInstance; if (instance) { const newInstance = await that._terminalService.createTerminal({ location: { parentTerminal: instance } }); return newInstance?.focusWhenReady(); } return; } }; return new ActionViewItem(action, panelOnlySplitAction, { icon: true, label: false, keybinding: this._getKeybindingLabel(action) }); } case TerminalCommandId.SwitchTerminal: { return this._instantiationService.createInstance(SwitchTerminalActionViewItem, action); } case TerminalCommandId.Focus: { if (action instanceof MenuItemAction) { const actions: IAction[] = []; createAndFillInContextMenuActions(this._singleTabMenu, undefined, actions); return this._instantiationService.createInstance(SingleTerminalTabActionViewItem, action, actions); } } case TerminalCommandId.New: { if (action instanceof MenuItemAction) { const actions = getTerminalActionBarArgs(TerminalLocation.Panel, this._terminalProfileService.availableProfiles, this._getDefaultProfileName(), this._terminalProfileService.contributedProfiles, this._terminalService, this._dropdownMenu); this._newDropdown?.dispose(); this._newDropdown = new DropdownWithPrimaryActionViewItem(action, actions.dropdownAction, actions.dropdownMenuActions, actions.className, this._contextMenuService, {}, this._keybindingService, this._notificationService, this._contextKeyService, this._themeService); this._updateTabActionBar(this._terminalProfileService.availableProfiles); return this._newDropdown; } } } return super.getActionViewItem(action); } private _getDefaultProfileName(): string { let defaultProfileName; try { defaultProfileName = this._terminalProfileService.getDefaultProfileName(); } catch (e) { defaultProfileName = this._terminalProfileResolverService.defaultProfileName; } return defaultProfileName!; } private _getKeybindingLabel(action: IAction): string | undefined { return withNullAsUndefined(this._keybindingService.lookupKeybinding(action.id)?.getLabel()); } private _updateTabActionBar(profiles: ITerminalProfile[]): void { const actions = getTerminalActionBarArgs(TerminalLocation.Panel, profiles, this._getDefaultProfileName(), this._terminalProfileService.contributedProfiles, this._terminalService, this._dropdownMenu); this._newDropdown?.update(actions.dropdownAction, actions.dropdownMenuActions); } override focus() { if (this._terminalService.connectionState === TerminalConnectionState.Connecting) { // If the terminal is waiting to reconnect to remote terminals, then there is no TerminalInstance yet that can // be focused. So wait for connection to finish, then focus. const activeElement = document.activeElement; this._register(this._terminalService.onDidChangeConnectionState(() => { // Only focus the terminal if the activeElement has not changed since focus() was called // TODO hack if (document.activeElement === activeElement) { this._terminalGroupService.showPanel(true); } })); return; } this._terminalGroupService.showPanel(true); } override shouldShowWelcome(): boolean { this._isWelcomeShowing = !this._terminalService.isProcessSupportRegistered && this._terminalService.instances.length === 0; return this._isWelcomeShowing; } } class SwitchTerminalActionViewItem extends SelectActionViewItem { constructor( action: IAction, @ITerminalService private readonly _terminalService: ITerminalService, @ITerminalGroupService private readonly _terminalGroupService: ITerminalGroupService, @IThemeService private readonly _themeService: IThemeService, @IContextViewService contextViewService: IContextViewService, @ITerminalProfileService terminalProfileService: ITerminalProfileService ) { super(null, action, getTerminalSelectOpenItems(_terminalService, _terminalGroupService), _terminalGroupService.activeGroupIndex, contextViewService, { ariaLabel: nls.localize('terminals', 'Open Terminals.'), optionsAsChildren: true }); this._register(_terminalService.onDidChangeInstances(() => this._updateItems(), this)); this._register(_terminalService.onDidChangeActiveGroup(() => this._updateItems(), this)); this._register(_terminalService.onDidChangeActiveInstance(() => this._updateItems(), this)); this._register(_terminalService.onDidChangeInstanceTitle(() => this._updateItems(), this)); this._register(_terminalGroupService.onDidChangeGroups(() => this._updateItems(), this)); this._register(_terminalService.onDidChangeConnectionState(() => this._updateItems(), this)); this._register(terminalProfileService.onDidChangeAvailableProfiles(() => this._updateItems(), this)); this._register(_terminalService.onDidChangeInstancePrimaryStatus(() => this._updateItems(), this)); this._register(attachSelectBoxStyler(this.selectBox, this._themeService)); } override render(container: HTMLElement): void { super.render(container); container.classList.add('switch-terminal'); this._register(attachStylerCallback(this._themeService, { selectBorder }, colors => { container.style.borderColor = colors.selectBorder ? `${colors.selectBorder}` : ''; })); } private _updateItems(): void { const options = getTerminalSelectOpenItems(this._terminalService, this._terminalGroupService); this.setOptions(options, this._terminalGroupService.activeGroupIndex); } } function getTerminalSelectOpenItems(terminalService: ITerminalService, terminalGroupService: ITerminalGroupService): ISelectOptionItem[] { let items: ISelectOptionItem[]; if (terminalService.connectionState === TerminalConnectionState.Connected) { items = terminalGroupService.getGroupLabels().map(label => { return { text: label }; }); } else { items = [{ text: nls.localize('terminalConnectingLabel', "Starting...") }]; } items.push({ text: switchTerminalActionViewItemSeparator, isDisabled: true }); items.push({ text: switchTerminalShowTabsTitle }); return items; } class SingleTerminalTabActionViewItem extends MenuEntryActionViewItem { private _color: string | undefined; private _altCommand: string | undefined; private _class: string | undefined; private readonly _elementDisposables: IDisposable[] = []; constructor( action: MenuItemAction, private readonly _actions: IAction[], @IKeybindingService keybindingService: IKeybindingService, @INotificationService notificationService: INotificationService, @IContextKeyService contextKeyService: IContextKeyService, @IThemeService themeService: IThemeService, @ITerminalService private readonly _terminalService: ITerminalService, @ITerminalGroupService private readonly _terminalGroupService: ITerminalGroupService, @IContextMenuService contextMenuService: IContextMenuService, @ICommandService private readonly _commandService: ICommandService, @IInstantiationService private readonly _instantiationService: IInstantiationService, ) { super(action, { draggable: true }, keybindingService, notificationService, contextKeyService, themeService, contextMenuService); // Register listeners to update the tab this._register(this._terminalService.onDidChangeInstancePrimaryStatus(e => this.updateLabel(e))); this._register(this._terminalGroupService.onDidChangeActiveInstance(() => this.updateLabel())); this._register(this._terminalService.onDidChangeInstanceIcon(e => this.updateLabel(e.instance))); this._register(this._terminalService.onDidChangeInstanceColor(e => this.updateLabel(e.instance))); this._register(this._terminalService.onDidChangeInstanceTitle(e => { if (e === this._terminalGroupService.activeInstance) { this._action.tooltip = getSingleTabTooltip(e, this._terminalService.configHelper.config.tabs.separator); this.updateLabel(); } })); this._register(this._terminalService.onDidChangeInstanceCapability(e => { this._action.tooltip = getSingleTabTooltip(e, this._terminalService.configHelper.config.tabs.separator); this.updateLabel(e); })); // Clean up on dispose this._register(toDisposable(() => dispose(this._elementDisposables))); } override async onClick(event: MouseEvent): Promise<void> { if (event.altKey && this._menuItemAction.alt) { this._commandService.executeCommand(this._menuItemAction.alt.id, { target: TerminalLocation.Panel } as ICreateTerminalOptions); } else { this._openContextMenu(); } } override updateLabel(e?: ITerminalInstance): void { // Only update if it's the active instance if (e && e !== this._terminalGroupService.activeInstance) { return; } if (this._elementDisposables.length === 0 && this.element && this.label) { // Right click opens context menu this._elementDisposables.push(dom.addDisposableListener(this.element, dom.EventType.CONTEXT_MENU, e => { if (e.button === 2) { this._openContextMenu(); e.preventDefault(); } })); // Middle click kills this._elementDisposables.push(dom.addDisposableListener(this.element, dom.EventType.AUXCLICK, e => { if (e.button === 1) { const instance = this._terminalGroupService.activeInstance; if (instance) { this._terminalService.safeDisposeTerminal(instance); } e.preventDefault(); } })); // Drag and drop this._elementDisposables.push(dom.addDisposableListener(this.element, dom.EventType.DRAG_START, e => { const instance = this._terminalGroupService.activeInstance; if (e.dataTransfer && instance) { e.dataTransfer.setData(TerminalDataTransfers.Terminals, JSON.stringify([instance.resource.toString()])); } })); } if (this.label) { const label = this.label; const instance = this._terminalGroupService.activeInstance; if (!instance) { dom.reset(label, ''); return; } label.classList.add('single-terminal-tab'); let colorStyle = ''; const primaryStatus = instance.statusList.primary; if (primaryStatus) { const colorKey = getColorForSeverity(primaryStatus.severity); this._themeService.getColorTheme(); const foundColor = this._themeService.getColorTheme().getColor(colorKey); if (foundColor) { colorStyle = foundColor.toString(); } } label.style.color = colorStyle; dom.reset(label, ...renderLabelWithIcons(this._instantiationService.invokeFunction(getSingleTabLabel, instance, this._terminalService.configHelper.config.tabs.separator, ThemeIcon.isThemeIcon(this._commandAction.item.icon) ? this._commandAction.item.icon : undefined))); if (this._altCommand) { label.classList.remove(this._altCommand); this._altCommand = undefined; } if (this._color) { label.classList.remove(this._color); this._color = undefined; } if (this._class) { label.classList.remove(this._class); label.classList.remove('terminal-uri-icon'); this._class = undefined; } const colorClass = getColorClass(instance); if (colorClass) { this._color = colorClass; label.classList.add(colorClass); } const uriClasses = getUriClasses(instance, this._themeService.getColorTheme().type); if (uriClasses) { this._class = uriClasses?.[0]; label.classList.add(...uriClasses); } if (this._commandAction.item.icon) { this._altCommand = `alt-command`; label.classList.add(this._altCommand); } this.updateTooltip(); } } private _openContextMenu() { this._contextMenuService.showContextMenu({ getAnchor: () => this.element!, getActions: () => this._actions, getActionsContext: () => this.label }); } } function getSingleTabLabel(accessor: ServicesAccessor, instance: ITerminalInstance | undefined, separator: string, icon?: ThemeIcon) { // Don't even show the icon if there is no title as the icon would shift around when the title // is added if (!instance || !instance.title) { return ''; } const iconClass = ThemeIcon.isThemeIcon(instance.icon) ? instance.icon.id : accessor.get(ITerminalProfileResolverService).getDefaultIcon(); const label = `$(${icon?.id || iconClass}) ${getSingleTabTitle(instance, separator)}`; const primaryStatus = instance.statusList.primary; if (!primaryStatus?.icon) { return label; } return `${label} $(${primaryStatus.icon.id})`; } function getSingleTabTooltip(instance: ITerminalInstance | undefined, separator: string): string { if (!instance) { return ''; } const shellIntegrationString = getShellIntegrationTooltip(instance, false); const title = getSingleTabTitle(instance, separator); return shellIntegrationString ? title + shellIntegrationString : title; } function getSingleTabTitle(instance: ITerminalInstance | undefined, separator: string): string { if (!instance) { return ''; } return !instance.description ? instance.title : `${instance.title} ${separator} ${instance.description}`; } class TerminalThemeIconStyle extends Themable { private _styleElement: HTMLElement; constructor( container: HTMLElement, @IThemeService private readonly _themeService: IThemeService, @ITerminalService private readonly _terminalService: ITerminalService, @ITerminalGroupService private readonly _terminalGroupService: ITerminalGroupService ) { super(_themeService); this._registerListeners(); this._styleElement = document.createElement('style'); container.appendChild(this._styleElement); this._register(toDisposable(() => container.removeChild(this._styleElement))); this.updateStyles(); } private _registerListeners(): void { this._register(this._terminalService.onDidChangeInstanceIcon(() => this.updateStyles())); this._register(this._terminalService.onDidChangeInstanceColor(() => this.updateStyles())); this._register(this._terminalService.onDidChangeInstances(() => this.updateStyles())); this._register(this._terminalGroupService.onDidChangeGroups(() => this.updateStyles())); } override updateStyles(): void { super.updateStyles(); const colorTheme = this._themeService.getColorTheme(); // TODO: add a rule collector to avoid duplication let css = ''; // Add icons for (const instance of this._terminalService.instances) { const icon = instance.icon; if (!icon) { continue; } let uri = undefined; if (icon instanceof URI) { uri = icon; } else if (icon instanceof Object && 'light' in icon && 'dark' in icon) { uri = colorTheme.type === ColorScheme.LIGHT ? icon.light : icon.dark; } const iconClasses = getUriClasses(instance, colorTheme.type); if (uri instanceof URI && iconClasses && iconClasses.length > 1) { css += ( `.monaco-workbench .${iconClasses[0]} .monaco-highlighted-label .codicon, .monaco-action-bar .terminal-uri-icon.single-terminal-tab.action-label:not(.alt-command) .codicon` + `{background-image: ${dom.asCSSUrl(uri)};}` ); } } // Add colors for (const instance of this._terminalService.instances) { const colorClass = getColorClass(instance); if (!colorClass || !instance.color) { continue; } const color = colorTheme.getColor(instance.color); if (color) { // exclude status icons (file-icon) and inline action icons (trashcan and horizontalSplit) css += ( `.monaco-workbench .${colorClass} .codicon:first-child:not(.codicon-split-horizontal):not(.codicon-trashcan):not(.file-icon)` + `{ color: ${color} !important; }` ); } } this._styleElement.textContent = css; } }
src/vs/workbench/contrib/terminal/browser/terminalView.ts
1
https://github.com/microsoft/vscode/commit/626c64bc9a48591e226edd3c04a4bef9e886828e
[ 0.0001752333773765713, 0.00017094310896936804, 0.00016517612675670534, 0.00017162274161819369, 0.0000027740118184738094 ]
{ "id": 1, "code_window": [ "\tprotected abstract _onInputChanged(): boolean;\n", "\tprotected abstract find(previous: boolean): void;\n", "\tprotected abstract findFirst(): void;\n", "\tprotected abstract _onFocusTrackerFocus(): void;\n", "\tprotected abstract _onFocusTrackerBlur(): void;\n", "\tprotected abstract _onFindInputFocusTrackerFocus(): void;\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/codeEditor/browser/find/simpleFindWidget.ts", "type": "replace", "edit_start_line_idx": 196 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Emitter, Event } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import { ICellRange } from 'vs/workbench/contrib/notebook/common/notebookRange'; function rangesEqual(a: ICellRange[], b: ICellRange[]) { if (a.length !== b.length) { return false; } for (let i = 0; i < a.length; i++) { if (a[i].start !== b[i].start || a[i].end !== b[i].end) { return false; } } return true; } // Challenge is List View talks about `element`, which needs extra work to convert to ICellRange as we support Folding and Cell Move export class NotebookCellSelectionCollection extends Disposable { private readonly _onDidChangeSelection = this._register(new Emitter<string>()); get onDidChangeSelection(): Event<string> { return this._onDidChangeSelection.event; } private _primary: ICellRange | null = null; private _selections: ICellRange[] = []; get selections(): ICellRange[] { return this._selections; } get focus(): ICellRange { return this._primary ?? { start: 0, end: 0 }; } setState(primary: ICellRange | null, selections: ICellRange[], forceEventEmit: boolean, source: 'view' | 'model') { const changed = primary !== this._primary || !rangesEqual(this._selections, selections); this._primary = primary; this._selections = selections; if (changed || forceEventEmit) { this._onDidChangeSelection.fire(source); } } setSelections(selections: ICellRange[], forceEventEmit: boolean, source: 'view' | 'model') { this.setState(this._primary, selections, forceEventEmit, source); } }
src/vs/workbench/contrib/notebook/browser/viewModel/cellSelectionCollection.ts
0
https://github.com/microsoft/vscode/commit/626c64bc9a48591e226edd3c04a4bef9e886828e
[ 0.00022818097204435617, 0.0001818247837945819, 0.00016960113134700805, 0.00017327058594673872, 0.00002081386628560722 ]
{ "id": 1, "code_window": [ "\tprotected abstract _onInputChanged(): boolean;\n", "\tprotected abstract find(previous: boolean): void;\n", "\tprotected abstract findFirst(): void;\n", "\tprotected abstract _onFocusTrackerFocus(): void;\n", "\tprotected abstract _onFocusTrackerBlur(): void;\n", "\tprotected abstract _onFindInputFocusTrackerFocus(): void;\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/codeEditor/browser/find/simpleFindWidget.ts", "type": "replace", "edit_start_line_idx": 196 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import { URI } from 'vs/base/common/uri'; import { distinct, deepClone } from 'vs/base/common/objects'; import { Emitter, Event } from 'vs/base/common/event'; import { isObject, assertIsDefined } from 'vs/base/common/types'; import { MutableDisposable } from 'vs/base/common/lifecycle'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { IEditorOpenContext, EditorInputCapabilities, IEditorPaneSelection, EditorPaneSelectionCompareResult, EditorPaneSelectionChangeReason, IEditorPaneWithSelection, IEditorPaneSelectionChangeEvent } from 'vs/workbench/common/editor'; import { EditorInput } from 'vs/workbench/common/editor/editorInput'; import { computeEditorAriaLabel } from 'vs/workbench/browser/editor'; import { AbstractEditorWithViewState } from 'vs/workbench/browser/parts/editor/editorWithViewState'; import { IEditorViewState } from 'vs/editor/common/editorCommon'; import { Selection } from 'vs/editor/common/core/selection'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { ITextResourceConfigurationService } from 'vs/editor/common/services/textResourceConfiguration'; import { IEditorOptions as ICodeEditorOptions } from 'vs/editor/common/config/editorOptions'; import { IEditorGroupsService, IEditorGroup } from 'vs/workbench/services/editor/common/editorGroupsService'; import { CancellationToken } from 'vs/base/common/cancellation'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IEditorOptions, ITextEditorOptions, TextEditorSelectionRevealType, TextEditorSelectionSource } from 'vs/platform/editor/common/editor'; import { ICursorPositionChangedEvent } from 'vs/editor/common/cursorEvents'; import { IFileService } from 'vs/platform/files/common/files'; export interface IEditorConfiguration { editor: object; diffEditor: object; } /** * The base class of editors that leverage any kind of text editor for the editing experience. */ export abstract class AbstractTextEditor<T extends IEditorViewState> extends AbstractEditorWithViewState<T> implements IEditorPaneWithSelection { private static readonly VIEW_STATE_PREFERENCE_KEY = 'textEditorViewState'; protected readonly _onDidChangeSelection = this._register(new Emitter<IEditorPaneSelectionChangeEvent>()); readonly onDidChangeSelection = this._onDidChangeSelection.event; private editorContainer: HTMLElement | undefined; private hasPendingConfigurationChange: boolean | undefined; private lastAppliedEditorOptions?: ICodeEditorOptions; private readonly inputListener = this._register(new MutableDisposable()); constructor( id: string, @ITelemetryService telemetryService: ITelemetryService, @IInstantiationService instantiationService: IInstantiationService, @IStorageService storageService: IStorageService, @ITextResourceConfigurationService textResourceConfigurationService: ITextResourceConfigurationService, @IThemeService themeService: IThemeService, @IEditorService editorService: IEditorService, @IEditorGroupsService editorGroupService: IEditorGroupsService, @IFileService protected readonly fileService: IFileService ) { super(id, AbstractTextEditor.VIEW_STATE_PREFERENCE_KEY, telemetryService, instantiationService, storageService, textResourceConfigurationService, themeService, editorService, editorGroupService); this._register(this.textResourceConfigurationService.onDidChangeConfiguration(() => { const resource = this.getActiveResource(); const value = resource ? this.textResourceConfigurationService.getValue<IEditorConfiguration>(resource) : undefined; return this.handleConfigurationChangeEvent(value); })); // ARIA: if a group is added or removed, update the editor's ARIA // label so that it appears in the label for when there are > 1 groups this._register(Event.any(this.editorGroupService.onDidAddGroup, this.editorGroupService.onDidRemoveGroup)(() => { const ariaLabel = this.computeAriaLabel(); this.editorContainer?.setAttribute('aria-label', ariaLabel); this.updateEditorControlOptions({ ariaLabel }); })); // Listen to file system provider changes this._register(this.fileService.onDidChangeFileSystemProviderCapabilities(e => this.onDidChangeFileSystemProvider(e.scheme))); this._register(this.fileService.onDidChangeFileSystemProviderRegistrations(e => this.onDidChangeFileSystemProvider(e.scheme))); } private handleConfigurationChangeEvent(configuration?: IEditorConfiguration): void { if (this.isVisible()) { this.updateEditorConfiguration(configuration); } else { this.hasPendingConfigurationChange = true; } } private consumePendingConfigurationChangeEvent(): void { if (this.hasPendingConfigurationChange) { this.updateEditorConfiguration(); this.hasPendingConfigurationChange = false; } } protected computeConfiguration(configuration: IEditorConfiguration): ICodeEditorOptions { // Specific editor options always overwrite user configuration const editorConfiguration: ICodeEditorOptions = isObject(configuration.editor) ? deepClone(configuration.editor) : Object.create(null); Object.assign(editorConfiguration, this.getConfigurationOverrides()); // ARIA label editorConfiguration.ariaLabel = this.computeAriaLabel(); return editorConfiguration; } private computeAriaLabel(): string { return this._input ? computeEditorAriaLabel(this._input, undefined, this.group, this.editorGroupService.count) : localize('editor', "Editor"); } private onDidChangeFileSystemProvider(scheme: string): void { if (!this.input) { return; } if (this.getActiveResource()?.scheme === scheme) { this.updateReadonly(this.input); } } private onDidChangeInputCapabilities(input: EditorInput): void { if (this.input === input) { this.updateReadonly(input); } } protected updateReadonly(input: EditorInput): void { const readOnly = input.hasCapability(EditorInputCapabilities.Readonly); this.updateEditorControlOptions({ readOnly }); } protected getConfigurationOverrides(): ICodeEditorOptions { const readOnly = this.input?.hasCapability(EditorInputCapabilities.Readonly); return { overviewRulerLanes: 3, lineNumbersMinChars: 3, fixedOverflowWidgets: true, readOnly, renderValidationDecorations: 'on' // render problems even in readonly editors (https://github.com/microsoft/vscode/issues/89057) }; } protected createEditor(parent: HTMLElement): void { // Create editor control this.editorContainer = parent; this.createEditorControl(parent, this.computeConfiguration(this.textResourceConfigurationService.getValue<IEditorConfiguration>(this.getActiveResource()))); // Listeners this.registerCodeEditorListeners(); } private registerCodeEditorListeners(): void { const mainControl = this.getMainControl(); if (mainControl) { this._register(mainControl.onDidChangeModelLanguage(() => this.updateEditorConfiguration())); this._register(mainControl.onDidChangeModel(() => this.updateEditorConfiguration())); this._register(mainControl.onDidChangeCursorPosition(e => this._onDidChangeSelection.fire({ reason: this.toEditorPaneSelectionChangeReason(e) }))); this._register(mainControl.onDidChangeModelContent(() => this._onDidChangeSelection.fire({ reason: EditorPaneSelectionChangeReason.EDIT }))); } } private toEditorPaneSelectionChangeReason(e: ICursorPositionChangedEvent): EditorPaneSelectionChangeReason { switch (e.source) { case TextEditorSelectionSource.PROGRAMMATIC: return EditorPaneSelectionChangeReason.PROGRAMMATIC; case TextEditorSelectionSource.NAVIGATION: return EditorPaneSelectionChangeReason.NAVIGATION; case TextEditorSelectionSource.JUMP: return EditorPaneSelectionChangeReason.JUMP; default: return EditorPaneSelectionChangeReason.USER; } } getSelection(): IEditorPaneSelection | undefined { const mainControl = this.getMainControl(); if (mainControl) { const selection = mainControl.getSelection(); if (selection) { return new TextEditorPaneSelection(selection); } } return undefined; } /** * This method creates and returns the text editor control to be used. * Subclasses must override to provide their own editor control that * should be used (e.g. a text diff editor). * * The passed in configuration object should be passed to the editor * control when creating it. */ protected abstract createEditorControl(parent: HTMLElement, initialOptions: ICodeEditorOptions): void; /** * The method asks to update the editor control options and is called * whenever there is change to the options. */ protected abstract updateEditorControlOptions(options: ICodeEditorOptions): void; /** * This method returns the main, dominant instance of `ICodeEditor` * for the editor pane. E.g. for a diff editor, this is the right * hand (modified) side. */ protected abstract getMainControl(): ICodeEditor | undefined; override async setInput(input: EditorInput, options: ITextEditorOptions | undefined, context: IEditorOpenContext, token: CancellationToken): Promise<void> { await super.setInput(input, options, context, token); // Update our listener for input capabilities this.inputListener.value = input.onDidChangeCapabilities(() => this.onDidChangeInputCapabilities(input)); // Update editor options after having set the input. We do this because there can be // editor input specific options (e.g. an ARIA label depending on the input showing) this.updateEditorConfiguration(); // Update aria label on editor const editorContainer = assertIsDefined(this.editorContainer); editorContainer.setAttribute('aria-label', this.computeAriaLabel()); } override clearInput(): void { // Clear input listener this.inputListener.clear(); super.clearInput(); } protected override setEditorVisible(visible: boolean, group: IEditorGroup | undefined): void { if (visible) { this.consumePendingConfigurationChangeEvent(); } super.setEditorVisible(visible, group); } protected override toEditorViewStateResource(input: EditorInput): URI | undefined { return input.resource; } private updateEditorConfiguration(configuration?: IEditorConfiguration): void { if (!configuration) { const resource = this.getActiveResource(); if (resource) { configuration = this.textResourceConfigurationService.getValue<IEditorConfiguration>(resource); } } if (!configuration) { return; } const editorConfiguration = this.computeConfiguration(configuration); // Try to figure out the actual editor options that changed from the last time we updated the editor. // We do this so that we are not overwriting some dynamic editor settings (e.g. word wrap) that might // have been applied to the editor directly. let editorSettingsToApply = editorConfiguration; if (this.lastAppliedEditorOptions) { editorSettingsToApply = distinct(this.lastAppliedEditorOptions, editorSettingsToApply); } if (Object.keys(editorSettingsToApply).length > 0) { this.lastAppliedEditorOptions = editorConfiguration; this.updateEditorControlOptions(editorSettingsToApply); } } private getActiveResource(): URI | undefined { const mainControl = this.getMainControl(); if (mainControl) { const model = mainControl.getModel(); if (model) { return model.uri; } } if (this.input) { return this.input.resource; } return undefined; } override dispose(): void { this.lastAppliedEditorOptions = undefined; super.dispose(); } } export class TextEditorPaneSelection implements IEditorPaneSelection { private static readonly TEXT_EDITOR_SELECTION_THRESHOLD = 10; // number of lines to move in editor to justify for significant change constructor( private readonly textSelection: Selection ) { } compare(other: IEditorPaneSelection): EditorPaneSelectionCompareResult { if (!(other instanceof TextEditorPaneSelection)) { return EditorPaneSelectionCompareResult.DIFFERENT; } const thisLineNumber = Math.min(this.textSelection.selectionStartLineNumber, this.textSelection.positionLineNumber); const otherLineNumber = Math.min(other.textSelection.selectionStartLineNumber, other.textSelection.positionLineNumber); if (thisLineNumber === otherLineNumber) { return EditorPaneSelectionCompareResult.IDENTICAL; } if (Math.abs(thisLineNumber - otherLineNumber) < TextEditorPaneSelection.TEXT_EDITOR_SELECTION_THRESHOLD) { return EditorPaneSelectionCompareResult.SIMILAR; // when in close proximity, treat selection as being similar } return EditorPaneSelectionCompareResult.DIFFERENT; } restore(options: IEditorOptions): ITextEditorOptions { const textEditorOptions: ITextEditorOptions = { ...options, selection: this.textSelection, selectionRevealType: TextEditorSelectionRevealType.CenterIfOutsideViewport }; return textEditorOptions; } log(): string { return `line: ${this.textSelection.startLineNumber}-${this.textSelection.endLineNumber}, col: ${this.textSelection.startColumn}-${this.textSelection.endColumn}`; } }
src/vs/workbench/browser/parts/editor/textEditor.ts
0
https://github.com/microsoft/vscode/commit/626c64bc9a48591e226edd3c04a4bef9e886828e
[ 0.0006755273207090795, 0.00019367832283023745, 0.00016412627883255482, 0.00017185004253406078, 0.00008744710794417188 ]
{ "id": 1, "code_window": [ "\tprotected abstract _onInputChanged(): boolean;\n", "\tprotected abstract find(previous: boolean): void;\n", "\tprotected abstract findFirst(): void;\n", "\tprotected abstract _onFocusTrackerFocus(): void;\n", "\tprotected abstract _onFocusTrackerBlur(): void;\n", "\tprotected abstract _onFindInputFocusTrackerFocus(): void;\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/codeEditor/browser/find/simpleFindWidget.ts", "type": "replace", "edit_start_line_idx": 196 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 386 197"><defs><style>.cls-1{fill:#f6f6f6;}.cls-2,.cls-6{fill:#fff;}.cls-2{stroke:#94c5e6;}.cls-2,.cls-4{stroke-miterlimit:10;}.cls-3{fill:#6c6c6c;}.cls-4{fill:none;stroke:#6c6c6c;}.cls-5{fill:#DFF0FF;}.cls-6{opacity:0.52;}</style></defs><title>Asset 9</title><g id="Layer_2" data-name="Layer 2"><g id="Layer_1-2" data-name="Layer 1"><rect class="cls-1" width="386" height="197"/><rect class="cls-2" x="5.25" y="8" width="374" height="23"/><path class="cls-3" d="M17.22,21.27l-7.14,3.59V23.62L15.42,21v0l-5.35-3V16.78l7.14,4Z"/><line class="cls-4" x1="18.75" y1="12" x2="18.75" y2="28"/><rect class="cls-5" y="38.5" width="385.75" height="20.5"/><path class="cls-3" d="M17.65,53.69a5.34,5.34,0,0,1-2.51.53A4.06,4.06,0,0,1,12,53a4.61,4.61,0,0,1-1.17-3.28,4.83,4.83,0,0,1,1.31-3.53,4.46,4.46,0,0,1,3.33-1.35,5.36,5.36,0,0,1,2.15.37v1.14a4.35,4.35,0,0,0-2.16-.55,3.31,3.31,0,0,0-2.54,1,3.94,3.94,0,0,0-1,2.8,3.76,3.76,0,0,0,.91,2.65,3.1,3.1,0,0,0,2.39,1,4.48,4.48,0,0,0,2.37-.61Z"/><path class="cls-3" d="M24.76,54.07h-1V50.33q0-2-1.51-2a1.65,1.65,0,0,0-1.28.59,2.19,2.19,0,0,0-.52,1.51v3.68h-1V44.45h1v4.2h0a2.36,2.36,0,0,1,2.13-1.23q2.2,0,2.2,2.65Z"/><path class="cls-3" d="M31.37,54.07h-1v-1h0a2.18,2.18,0,0,1-2,1.17,2.14,2.14,0,0,1-1.52-.51,1.78,1.78,0,0,1-.55-1.37q0-1.82,2.14-2.12L30.33,50q0-1.66-1.34-1.66a3.2,3.2,0,0,0-2.12.8V48a4,4,0,0,1,2.21-.61q2.29,0,2.29,2.42Zm-1-3.29L28.76,51a2.55,2.55,0,0,0-1.09.36,1,1,0,0,0-.37.91,1,1,0,0,0,.34.78,1.31,1.31,0,0,0,.9.3,1.67,1.67,0,0,0,1.28-.54,1.94,1.94,0,0,0,.5-1.37Z"/><path class="cls-3" d="M38.73,54.07h-1V50.37q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71h-1v-6.5h1v1.08h0a2.35,2.35,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.57,2Z"/><path class="cls-3" d="M46.24,53.55q0,3.58-3.43,3.58a4.6,4.6,0,0,1-2.11-.46v-1a4.33,4.33,0,0,0,2.09.61q2.4,0,2.4-2.55V53h0a2.63,2.63,0,0,1-4.19.38A3.47,3.47,0,0,1,40.25,51,4,4,0,0,1,41,48.4a2.66,2.66,0,0,1,2.18-1,2.12,2.12,0,0,1,1.95,1.05h0v-.9h1Zm-1-2.42v-1a1.86,1.86,0,0,0-.52-1.33,1.73,1.73,0,0,0-1.3-.55,1.81,1.81,0,0,0-1.51.7,3.14,3.14,0,0,0-.55,2,2.69,2.69,0,0,0,.52,1.74,1.69,1.69,0,0,0,1.39.65,1.81,1.81,0,0,0,1.42-.62A2.32,2.32,0,0,0,45.2,51.13Z"/><path class="cls-3" d="M53.57,51.08H49a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.16-.89,3.62,3.62,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.45,2.45,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29ZM52.5,50.2a2.12,2.12,0,0,0-.43-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53A2.39,2.39,0,0,0,49,50.2Z"/><path class="cls-3" d="M63.67,54.07H58.84V45h4.62v1H59.91v3H63.2v1H59.91v3.19h3.76Z"/><path class="cls-3" d="M70.68,54.07h-1V50.37q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71h-1v-6.5h1v1.08h0a2.35,2.35,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.56,2Z"/><path class="cls-3" d="M78.19,54.07h-1V53h0a2.62,2.62,0,0,1-4.19.38A3.58,3.58,0,0,1,72.19,51,3.9,3.9,0,0,1,73,48.39a2.68,2.68,0,0,1,2.16-1,2.09,2.09,0,0,1,1.95,1.05h0v-4h1Zm-1-2.94v-1a1.86,1.86,0,0,0-.52-1.33,1.74,1.74,0,0,0-1.32-.55,1.8,1.8,0,0,0-1.5.7,3.06,3.06,0,0,0-.54,1.93,2.75,2.75,0,0,0,.52,1.77,1.71,1.71,0,0,0,1.41.65,1.78,1.78,0,0,0,1.41-.63A2.35,2.35,0,0,0,77.14,51.13Z"/><path class="cls-3" d="M86.57,54.23a3,3,0,0,1-2.3-.91,3.37,3.37,0,0,1-.86-2.42,3.51,3.51,0,0,1,.9-2.56,3.22,3.22,0,0,1,2.42-.92,2.92,2.92,0,0,1,2.27.89,3.56,3.56,0,0,1,.82,2.48,3.49,3.49,0,0,1-.88,2.49A3.08,3.08,0,0,1,86.57,54.23Zm.08-5.93a2,2,0,0,0-1.59.68,2.8,2.8,0,0,0-.58,1.88,2.64,2.64,0,0,0,.59,1.82,2,2,0,0,0,1.58.67,1.9,1.9,0,0,0,1.55-.65,2.84,2.84,0,0,0,.54-1.86A2.88,2.88,0,0,0,88.2,49,1.89,1.89,0,0,0,86.65,48.3Z"/><path class="cls-3" d="M94.45,45.37a1.39,1.39,0,0,0-.69-.17q-1.09,0-1.09,1.38v1h1.52v.89H92.66v5.61h-1V48.46H90.52v-.89h1.11V46.52a2.19,2.19,0,0,1,.59-1.62,2,2,0,0,1,1.47-.59,2,2,0,0,1,.75.11Z"/><path class="cls-3" d="M103.73,54.07H99V45h1.07v8.14h3.66Z"/><path class="cls-3" d="M105.52,45.92a.66.66,0,0,1-.48-.19.64.64,0,0,1-.2-.48.67.67,0,0,1,.67-.68.67.67,0,0,1,.49.19.68.68,0,0,1,0,1A.66.66,0,0,1,105.52,45.92Zm.51,8.15h-1v-6.5h1Z"/><path class="cls-3" d="M113.53,54.07h-1V50.37q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71h-1v-6.5h1v1.08h0a2.35,2.35,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.57,2Z"/><path class="cls-3" d="M120.71,51.08h-4.59a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.17-.89,3.63,3.63,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.44,2.44,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.12,2.12,0,0,0-.44-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.4,2.4,0,0,0-.63,1.38Z"/><path class="cls-3" d="M125.56,53.71V52.45a2.45,2.45,0,0,0,.52.34,4.17,4.17,0,0,0,.63.26,5,5,0,0,0,.67.16,3.72,3.72,0,0,0,.62.06,2.44,2.44,0,0,0,1.47-.36,1.37,1.37,0,0,0,.32-1.69,1.82,1.82,0,0,0-.45-.5,4.46,4.46,0,0,0-.68-.43l-.84-.43c-.32-.16-.61-.32-.89-.49a3.85,3.85,0,0,1-.72-.54,2.28,2.28,0,0,1-.48-.68,2.3,2.3,0,0,1,.1-2,2.33,2.33,0,0,1,.72-.76,3.27,3.27,0,0,1,1-.45,4.67,4.67,0,0,1,1.16-.15,4.45,4.45,0,0,1,2,.32v1.2a3.56,3.56,0,0,0-2.07-.56,3.39,3.39,0,0,0-.7.07,2,2,0,0,0-.62.24,1.36,1.36,0,0,0-.44.42,1.13,1.13,0,0,0-.17.63,1.3,1.3,0,0,0,.13.6,1.46,1.46,0,0,0,.38.46,3.8,3.8,0,0,0,.62.41l.84.43q.49.24.93.51a4.22,4.22,0,0,1,.77.59,2.6,2.6,0,0,1,.52.72,2,2,0,0,1,.19.9,2.29,2.29,0,0,1-.26,1.14,2.16,2.16,0,0,1-.71.76,3.1,3.1,0,0,1-1,.42,5.63,5.63,0,0,1-1.23.13l-.53,0c-.21,0-.43-.06-.65-.1a5.16,5.16,0,0,1-.62-.17A1.94,1.94,0,0,1,125.56,53.71Z"/><path class="cls-3" d="M138,51.08h-4.59a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.17-.89,3.63,3.63,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.44,2.44,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.12,2.12,0,0,0-.44-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.4,2.4,0,0,0-.63,1.38Z"/><path class="cls-3" d="M145.1,57.06h-1V53h0a2.33,2.33,0,0,1-2.22,1.27,2.44,2.44,0,0,1-2-.87,3.56,3.56,0,0,1-.74-2.38,3.9,3.9,0,0,1,.81-2.59,2.7,2.7,0,0,1,2.18-1A2,2,0,0,1,144,48.48h0v-.9h1Zm-1-5.92V50.2a1.89,1.89,0,0,0-.52-1.35,1.76,1.76,0,0,0-1.33-.55,1.78,1.78,0,0,0-1.48.7,3.1,3.1,0,0,0-.55,2,2.69,2.69,0,0,0,.53,1.76,1.68,1.68,0,0,0,1.36.64,1.83,1.83,0,0,0,1.46-.62A2.31,2.31,0,0,0,144.06,51.15Z"/><path class="cls-3" d="M152.46,54.07h-1V53h0a2.14,2.14,0,0,1-2,1.18q-2.32,0-2.32-2.77V47.57h1v3.72q0,2.06,1.57,2.06a1.59,1.59,0,0,0,1.25-.56,2.15,2.15,0,0,0,.49-1.47V47.57h1Z"/><path class="cls-3" d="M159.79,51.08H155.2a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.17-.89,3.63,3.63,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.44,2.44,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.12,2.12,0,0,0-.44-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.4,2.4,0,0,0-.63,1.38Z"/><path class="cls-3" d="M166.76,54.07h-1V50.37q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71h-1v-6.5h1v1.08h0a2.34,2.34,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.56,2Z"/><path class="cls-3" d="M173.15,53.78a3.38,3.38,0,0,1-1.78.45,2.94,2.94,0,0,1-2.24-.9,3.28,3.28,0,0,1-.85-2.35,3.6,3.6,0,0,1,.92-2.58,3.22,3.22,0,0,1,2.46-1,3.42,3.42,0,0,1,1.51.32v1.07a2.65,2.65,0,0,0-1.55-.51A2.09,2.09,0,0,0,170,49a2.71,2.71,0,0,0-.64,1.88,2.58,2.58,0,0,0,.6,1.8,2.07,2.07,0,0,0,1.61.66,2.61,2.61,0,0,0,1.6-.57Z"/><path class="cls-3" d="M180,51.08h-4.59a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.17-.89,3.63,3.63,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.44,2.44,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.12,2.12,0,0,0-.44-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.4,2.4,0,0,0-.63,1.38Z"/><path class="cls-3" d="M17.65,75.69a5.34,5.34,0,0,1-2.51.53A4.06,4.06,0,0,1,12,75a4.61,4.61,0,0,1-1.17-3.28,4.83,4.83,0,0,1,1.31-3.53,4.46,4.46,0,0,1,3.33-1.35,5.36,5.36,0,0,1,2.15.37v1.14a4.35,4.35,0,0,0-2.16-.55,3.31,3.31,0,0,0-2.54,1,3.94,3.94,0,0,0-1,2.8,3.76,3.76,0,0,0,.91,2.65,3.1,3.1,0,0,0,2.39,1,4.48,4.48,0,0,0,2.37-.61Z"/><path class="cls-3" d="M24.76,76.07h-1V72.33q0-2-1.51-2a1.65,1.65,0,0,0-1.28.59,2.19,2.19,0,0,0-.52,1.51v3.68h-1V66.45h1v4.2h0a2.36,2.36,0,0,1,2.13-1.23q2.2,0,2.2,2.65Z"/><path class="cls-3" d="M31.37,76.07h-1v-1h0a2.18,2.18,0,0,1-2,1.17,2.14,2.14,0,0,1-1.52-.51,1.78,1.78,0,0,1-.55-1.37q0-1.82,2.14-2.12L30.33,72q0-1.66-1.34-1.66a3.2,3.2,0,0,0-2.12.8V70a4,4,0,0,1,2.21-.61q2.29,0,2.29,2.42Zm-1-3.29L28.76,73a2.55,2.55,0,0,0-1.09.36,1,1,0,0,0-.37.91,1,1,0,0,0,.34.78,1.31,1.31,0,0,0,.9.3,1.67,1.67,0,0,0,1.28-.54,1.94,1.94,0,0,0,.5-1.37Z"/><path class="cls-3" d="M38.73,76.07h-1V72.37q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71h-1v-6.5h1v1.08h0a2.35,2.35,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.57,2Z"/><path class="cls-3" d="M46.24,75.55q0,3.58-3.43,3.58a4.6,4.6,0,0,1-2.11-.46v-1a4.33,4.33,0,0,0,2.09.61q2.4,0,2.4-2.55V75h0a2.63,2.63,0,0,1-4.19.38A3.47,3.47,0,0,1,40.25,73,4,4,0,0,1,41,70.4a2.66,2.66,0,0,1,2.18-1,2.12,2.12,0,0,1,1.95,1.05h0v-.9h1Zm-1-2.42v-1a1.86,1.86,0,0,0-.52-1.33,1.73,1.73,0,0,0-1.3-.55,1.81,1.81,0,0,0-1.51.7,3.14,3.14,0,0,0-.55,2,2.69,2.69,0,0,0,.52,1.74,1.69,1.69,0,0,0,1.39.65,1.81,1.81,0,0,0,1.42-.62A2.32,2.32,0,0,0,45.2,73.13Z"/><path class="cls-3" d="M53.57,73.08H49a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.16-.89,3.62,3.62,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.45,2.45,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29ZM52.5,72.2a2.12,2.12,0,0,0-.43-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53A2.39,2.39,0,0,0,49,72.2Z"/><path class="cls-3" d="M63.46,67.94H59.91v3.15H63.2v1H59.91v4H58.84V67h4.62Z"/><path class="cls-3" d="M65.58,67.92a.66.66,0,0,1-.48-.19.64.64,0,0,1-.2-.48.67.67,0,0,1,.67-.68.67.67,0,0,1,.49.19.68.68,0,0,1,0,1A.66.66,0,0,1,65.58,67.92Zm.51,8.15h-1v-6.5h1Z"/><path class="cls-3" d="M69.24,76.07h-1V66.45h1Z"/><path class="cls-3" d="M76.57,73.08H72a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.16-.89,3.62,3.62,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.45,2.45,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.12,2.12,0,0,0-.43-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53A2.39,2.39,0,0,0,72,72.2Z"/><path class="cls-3" d="M86.67,76.07H81.85V67h4.62v1H82.91v3H86.2v1H82.91v3.19h3.76Z"/><path class="cls-3" d="M93.68,76.07h-1V72.37q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71h-1v-6.5h1v1.08h0a2.35,2.35,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.56,2Z"/><path class="cls-3" d="M100.07,75.78a3.38,3.38,0,0,1-1.78.45,2.94,2.94,0,0,1-2.24-.9A3.28,3.28,0,0,1,95.2,73a3.6,3.6,0,0,1,.92-2.58,3.22,3.22,0,0,1,2.46-1,3.41,3.41,0,0,1,1.51.32v1.07a2.64,2.64,0,0,0-1.55-.51A2.1,2.1,0,0,0,96.9,71a2.72,2.72,0,0,0-.64,1.88,2.58,2.58,0,0,0,.6,1.8,2.07,2.07,0,0,0,1.61.66,2.61,2.61,0,0,0,1.6-.57Z"/><path class="cls-3" d="M104.36,76.23a3,3,0,0,1-2.3-.91,3.37,3.37,0,0,1-.86-2.42,3.52,3.52,0,0,1,.9-2.56,3.22,3.22,0,0,1,2.42-.92,2.92,2.92,0,0,1,2.27.89,3.56,3.56,0,0,1,.81,2.48,3.49,3.49,0,0,1-.88,2.49A3.08,3.08,0,0,1,104.36,76.23Zm.08-5.93a2,2,0,0,0-1.59.68,2.81,2.81,0,0,0-.58,1.88,2.65,2.65,0,0,0,.59,1.82,2,2,0,0,0,1.58.67A1.9,1.9,0,0,0,106,74.7a2.83,2.83,0,0,0,.54-1.86A2.88,2.88,0,0,0,106,71,1.89,1.89,0,0,0,104.44,70.3Z"/><path class="cls-3" d="M114.81,76.07h-1V75h0a2.62,2.62,0,0,1-4.19.38,3.57,3.57,0,0,1-.73-2.38,3.9,3.9,0,0,1,.81-2.58,2.68,2.68,0,0,1,2.17-1,2.08,2.08,0,0,1,1.95,1.05h0v-4h1Zm-1-2.94v-1a1.86,1.86,0,0,0-.52-1.33,1.75,1.75,0,0,0-1.32-.55,1.8,1.8,0,0,0-1.5.7,3.06,3.06,0,0,0-.55,1.93,2.76,2.76,0,0,0,.52,1.77,1.71,1.71,0,0,0,1.41.65,1.78,1.78,0,0,0,1.41-.63A2.34,2.34,0,0,0,113.77,73.13Z"/><path class="cls-3" d="M117.45,67.92a.66.66,0,0,1-.48-.19.64.64,0,0,1-.2-.48.67.67,0,0,1,.67-.68.67.67,0,0,1,.49.19.68.68,0,0,1,0,1A.66.66,0,0,1,117.45,67.92Zm.51,8.15h-1v-6.5h1Z"/><path class="cls-3" d="M125.46,76.07h-1V72.37q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71h-1v-6.5h1v1.08h0a2.35,2.35,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.57,2Z"/><path class="cls-3" d="M133,75.55q0,3.58-3.43,3.58a4.6,4.6,0,0,1-2.11-.46v-1a4.33,4.33,0,0,0,2.09.61q2.4,0,2.4-2.55V75h0a2.63,2.63,0,0,1-4.19.38A3.47,3.47,0,0,1,127,73a4,4,0,0,1,.8-2.63,2.66,2.66,0,0,1,2.18-1,2.12,2.12,0,0,1,1.95,1.05h0v-.9h1Zm-1-2.42v-1a1.86,1.86,0,0,0-.52-1.33,1.73,1.73,0,0,0-1.3-.55,1.81,1.81,0,0,0-1.51.7,3.14,3.14,0,0,0-.55,2,2.69,2.69,0,0,0,.52,1.74,1.69,1.69,0,0,0,1.39.65,1.81,1.81,0,0,0,1.42-.62A2.32,2.32,0,0,0,131.93,73.13Z"/><path class="cls-3" d="M17.65,97.69a5.34,5.34,0,0,1-2.51.53A4.06,4.06,0,0,1,12,97a4.61,4.61,0,0,1-1.17-3.28,4.83,4.83,0,0,1,1.31-3.53,4.46,4.46,0,0,1,3.33-1.35,5.36,5.36,0,0,1,2.15.37v1.14a4.35,4.35,0,0,0-2.16-.55,3.31,3.31,0,0,0-2.54,1,3.94,3.94,0,0,0-1,2.8,3.76,3.76,0,0,0,.91,2.65,3.1,3.1,0,0,0,2.39,1,4.48,4.48,0,0,0,2.37-.61Z"/><path class="cls-3" d="M24.76,98.07h-1V94.33q0-2-1.51-2a1.65,1.65,0,0,0-1.28.59,2.19,2.19,0,0,0-.52,1.51v3.68h-1V88.45h1v4.2h0a2.36,2.36,0,0,1,2.13-1.23q2.2,0,2.2,2.65Z"/><path class="cls-3" d="M31.37,98.07h-1v-1h0a2.18,2.18,0,0,1-2,1.17,2.14,2.14,0,0,1-1.52-.51,1.78,1.78,0,0,1-.55-1.37q0-1.82,2.14-2.12L30.33,94q0-1.66-1.34-1.66a3.2,3.2,0,0,0-2.12.8V92a4,4,0,0,1,2.21-.61q2.29,0,2.29,2.42Zm-1-3.29L28.76,95a2.55,2.55,0,0,0-1.09.36,1,1,0,0,0-.37.91,1,1,0,0,0,.34.78,1.31,1.31,0,0,0,.9.3,1.67,1.67,0,0,0,1.28-.54,1.94,1.94,0,0,0,.5-1.37Z"/><path class="cls-3" d="M38.73,98.07h-1V94.37q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71h-1v-6.5h1v1.08h0a2.35,2.35,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.57,2Z"/><path class="cls-3" d="M46.24,97.55q0,3.58-3.43,3.58a4.6,4.6,0,0,1-2.11-.46v-1a4.33,4.33,0,0,0,2.09.61q2.4,0,2.4-2.55V97h0a2.63,2.63,0,0,1-4.19.38A3.47,3.47,0,0,1,40.25,95,4,4,0,0,1,41,92.4a2.66,2.66,0,0,1,2.18-1,2.12,2.12,0,0,1,1.95,1.05h0v-.9h1Zm-1-2.42v-1a1.86,1.86,0,0,0-.52-1.33,1.73,1.73,0,0,0-1.3-.55,1.81,1.81,0,0,0-1.51.7,3.14,3.14,0,0,0-.55,2,2.69,2.69,0,0,0,.52,1.74,1.69,1.69,0,0,0,1.39.65,1.81,1.81,0,0,0,1.42-.62A2.32,2.32,0,0,0,45.2,95.13Z"/><path class="cls-3" d="M53.57,95.08H49a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.16-.89,3.62,3.62,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.45,2.45,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29ZM52.5,94.2a2.12,2.12,0,0,0-.43-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53A2.39,2.39,0,0,0,49,94.2Z"/><path class="cls-3" d="M63.57,98.07H58.84V89h1.07v8.14h3.66Z"/><path class="cls-3" d="M69.48,98.07h-1v-1h0a2.18,2.18,0,0,1-2,1.17,2.14,2.14,0,0,1-1.52-.51,1.78,1.78,0,0,1-.55-1.37q0-1.82,2.15-2.12L68.44,94q0-1.66-1.34-1.66a3.2,3.2,0,0,0-2.12.8V92a4,4,0,0,1,2.21-.61q2.29,0,2.29,2.42Zm-1-3.29L66.87,95a2.55,2.55,0,0,0-1.09.36,1,1,0,0,0-.37.91,1,1,0,0,0,.34.78,1.31,1.31,0,0,0,.9.3,1.67,1.67,0,0,0,1.28-.54,1.94,1.94,0,0,0,.5-1.37Z"/><path class="cls-3" d="M76.83,98.07h-1V94.37q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71h-1v-6.5h1v1.08h0a2.34,2.34,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.57,2Z"/><path class="cls-3" d="M84.34,97.55q0,3.58-3.43,3.58a4.61,4.61,0,0,1-2.11-.46v-1a4.33,4.33,0,0,0,2.1.61q2.4,0,2.4-2.55V97h0a2.63,2.63,0,0,1-4.19.38A3.47,3.47,0,0,1,78.35,95a4,4,0,0,1,.8-2.63,2.66,2.66,0,0,1,2.18-1,2.12,2.12,0,0,1,1.95,1.05h0v-.9h1Zm-1-2.42v-1a1.86,1.86,0,0,0-.52-1.33,1.73,1.73,0,0,0-1.3-.55A1.81,1.81,0,0,0,80,93a3.13,3.13,0,0,0-.55,2,2.7,2.7,0,0,0,.52,1.74,1.69,1.69,0,0,0,1.39.65,1.81,1.81,0,0,0,1.42-.62A2.32,2.32,0,0,0,83.3,95.13Z"/><path class="cls-3" d="M91.71,98.07h-1V97h0a2.14,2.14,0,0,1-2,1.18q-2.32,0-2.32-2.77V91.57h1v3.72q0,2.06,1.57,2.06a1.59,1.59,0,0,0,1.25-.56,2.15,2.15,0,0,0,.49-1.47V91.57h1Z"/><path class="cls-3" d="M98.46,98.07h-1v-1h0a2.18,2.18,0,0,1-2,1.17,2.14,2.14,0,0,1-1.52-.51,1.79,1.79,0,0,1-.55-1.37q0-1.82,2.15-2.12L97.42,94q0-1.66-1.34-1.66a3.2,3.2,0,0,0-2.12.8V92a4,4,0,0,1,2.21-.61q2.29,0,2.29,2.42Zm-1-3.29L95.85,95a2.55,2.55,0,0,0-1.09.36,1,1,0,0,0-.37.91,1,1,0,0,0,.34.78,1.31,1.31,0,0,0,.9.3,1.67,1.67,0,0,0,1.28-.54,1.94,1.94,0,0,0,.5-1.37Z"/><path class="cls-3" d="M106,97.55q0,3.58-3.43,3.58a4.6,4.6,0,0,1-2.11-.46v-1a4.33,4.33,0,0,0,2.09.61q2.4,0,2.4-2.55V97h0a2.63,2.63,0,0,1-4.19.38A3.46,3.46,0,0,1,100,95a4,4,0,0,1,.8-2.63,2.66,2.66,0,0,1,2.18-1,2.12,2.12,0,0,1,1.95,1.05h0v-.9h1Zm-1-2.42v-1a1.86,1.86,0,0,0-.52-1.33,1.73,1.73,0,0,0-1.3-.55,1.81,1.81,0,0,0-1.51.7,3.13,3.13,0,0,0-.55,2,2.69,2.69,0,0,0,.52,1.74,1.69,1.69,0,0,0,1.39.65,1.81,1.81,0,0,0,1.43-.62A2.32,2.32,0,0,0,104.93,95.13Z"/><path class="cls-3" d="M113.3,95.08h-4.59a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.17-.89,3.63,3.63,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.44,2.44,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.12,2.12,0,0,0-.44-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.4,2.4,0,0,0-.63,1.38Z"/><path class="cls-3" d="M127.86,98.07h-1.06V92q0-.72.09-1.77h0a5.69,5.69,0,0,1-.27.88l-3.11,7H123l-3.1-6.94a5.42,5.42,0,0,1-.27-.93h0q0,.54.05,1.78v6.09h-1V89H120l2.79,6.35a8.11,8.11,0,0,1,.42,1.09h0q.27-.75.44-1.12L126.52,89h1.33Z"/><path class="cls-3" d="M132.83,98.23a3,3,0,0,1-2.3-.91,3.37,3.37,0,0,1-.86-2.42,3.52,3.52,0,0,1,.9-2.56,3.22,3.22,0,0,1,2.42-.92,2.92,2.92,0,0,1,2.27.89,3.56,3.56,0,0,1,.81,2.48,3.49,3.49,0,0,1-.88,2.49A3.08,3.08,0,0,1,132.83,98.23Zm.08-5.93a2,2,0,0,0-1.59.68,2.81,2.81,0,0,0-.58,1.88,2.65,2.65,0,0,0,.59,1.82,2,2,0,0,0,1.58.67,1.9,1.9,0,0,0,1.55-.65,2.83,2.83,0,0,0,.54-1.86,2.88,2.88,0,0,0-.54-1.88A1.89,1.89,0,0,0,132.9,92.3Z"/><path class="cls-3" d="M143.27,98.07h-1V97h0a2.62,2.62,0,0,1-4.19.38,3.57,3.57,0,0,1-.73-2.38,3.9,3.9,0,0,1,.81-2.58,2.68,2.68,0,0,1,2.17-1,2.08,2.08,0,0,1,1.95,1.05h0v-4h1Zm-1-2.94v-1a1.86,1.86,0,0,0-.52-1.33,1.75,1.75,0,0,0-1.32-.55,1.8,1.8,0,0,0-1.5.7,3.06,3.06,0,0,0-.55,1.93,2.76,2.76,0,0,0,.52,1.77,1.71,1.71,0,0,0,1.41.65,1.78,1.78,0,0,0,1.41-.63A2.34,2.34,0,0,0,142.23,95.13Z"/><path class="cls-3" d="M150.61,95.08H146a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.74,2.74,0,0,1-2.16-.89,3.62,3.62,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.45,2.45,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.11,2.11,0,0,0-.44-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53A2.38,2.38,0,0,0,146,94.2Z"/><path class="cls-3" d="M17.65,119.69a5.34,5.34,0,0,1-2.51.53A4.06,4.06,0,0,1,12,119a4.61,4.61,0,0,1-1.17-3.28,4.83,4.83,0,0,1,1.31-3.53,4.46,4.46,0,0,1,3.33-1.35,5.36,5.36,0,0,1,2.15.37v1.14a4.35,4.35,0,0,0-2.16-.55,3.31,3.31,0,0,0-2.54,1,3.94,3.94,0,0,0-1,2.8,3.76,3.76,0,0,0,.91,2.65,3.1,3.1,0,0,0,2.39,1,4.48,4.48,0,0,0,2.37-.61Z"/><path class="cls-3" d="M20.4,120.07h-1v-9.62h1Z"/><path class="cls-3" d="M27.73,117.08H23.14a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.17-.89,3.63,3.63,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.44,2.44,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.12,2.12,0,0,0-.44-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.4,2.4,0,0,0-.63,1.38Z"/><path class="cls-3" d="M34,120.07h-1v-1h0a2.18,2.18,0,0,1-2,1.17,2.14,2.14,0,0,1-1.52-.51,1.78,1.78,0,0,1-.55-1.37q0-1.82,2.14-2.12l1.95-.27q0-1.66-1.34-1.66a3.2,3.2,0,0,0-2.12.8V114a4,4,0,0,1,2.21-.61q2.29,0,2.29,2.42Zm-1-3.29-1.57.22a2.55,2.55,0,0,0-1.09.36,1,1,0,0,0-.37.91,1,1,0,0,0,.34.78,1.31,1.31,0,0,0,.9.3,1.67,1.67,0,0,0,1.28-.54,1.94,1.94,0,0,0,.5-1.37Z"/><path class="cls-3" d="M39.31,114.63a1.28,1.28,0,0,0-.79-.21,1.33,1.33,0,0,0-1.12.63,2.92,2.92,0,0,0-.45,1.71v3.31h-1v-6.5h1v1.34h0a2.27,2.27,0,0,1,.68-1.07,1.55,1.55,0,0,1,1-.38,1.7,1.7,0,0,1,.62.09Z"/><path class="cls-3" d="M49,120.07H44.14V111h4.62v1H45.21v3H48.5v1H45.21v3.19H49Z"/><path class="cls-3" d="M56.13,120.07h-1V119h0a2.4,2.4,0,0,1-2.23,1.26,2.43,2.43,0,0,1-2-.87,3.58,3.58,0,0,1-.73-2.38,3.9,3.9,0,0,1,.81-2.58,2.68,2.68,0,0,1,2.16-1,2.08,2.08,0,0,1,1.95,1.05h0v-4h1Zm-1-2.94v-1a1.86,1.86,0,0,0-.52-1.33,1.74,1.74,0,0,0-1.32-.55,1.8,1.8,0,0,0-1.5.7,3.06,3.06,0,0,0-.55,1.93,2.76,2.76,0,0,0,.52,1.77,1.71,1.71,0,0,0,1.41.65,1.78,1.78,0,0,0,1.41-.63A2.34,2.34,0,0,0,55.09,117.13Z"/><path class="cls-3" d="M58.77,111.92a.66.66,0,0,1-.48-.19.64.64,0,0,1-.2-.48.67.67,0,0,1,.67-.68.67.67,0,0,1,.49.19.68.68,0,0,1,0,1A.66.66,0,0,1,58.77,111.92Zm.51,8.15h-1v-6.5h1Z"/><path class="cls-3" d="M64.4,120a2,2,0,0,1-1,.2q-1.71,0-1.71-1.9v-3.85H60.6v-.89h1.12V112l1-.34v1.92H64.4v.89H62.76v3.66a1.52,1.52,0,0,0,.22.93.89.89,0,0,0,.74.28,1.1,1.1,0,0,0,.68-.22Z"/><path class="cls-3" d="M68.4,120.23a3,3,0,0,1-2.3-.91,3.37,3.37,0,0,1-.86-2.42,3.52,3.52,0,0,1,.89-2.56,3.22,3.22,0,0,1,2.42-.92,2.92,2.92,0,0,1,2.27.89,3.55,3.55,0,0,1,.82,2.48,3.49,3.49,0,0,1-.88,2.49A3.08,3.08,0,0,1,68.4,120.23Zm.08-5.93a2,2,0,0,0-1.59.68,2.81,2.81,0,0,0-.58,1.88,2.65,2.65,0,0,0,.59,1.82,2,2,0,0,0,1.58.67A1.9,1.9,0,0,0,70,118.7a2.84,2.84,0,0,0,.54-1.86A2.88,2.88,0,0,0,70,115,1.89,1.89,0,0,0,68.48,114.3Z"/><path class="cls-3" d="M76.69,114.63a1.27,1.27,0,0,0-.79-.21,1.33,1.33,0,0,0-1.11.63,2.91,2.91,0,0,0-.45,1.71v3.31h-1v-6.5h1v1.34h0a2.27,2.27,0,0,1,.68-1.07,1.55,1.55,0,0,1,1-.38,1.7,1.7,0,0,1,.62.09Z"/><path class="cls-3" d="M88.37,120.07H87.3v-4.15H82.59v4.15H81.52V111h1.07v4H87.3v-4h1.07Z"/><path class="cls-3" d="M91.15,111.92a.66.66,0,0,1-.48-.19.64.64,0,0,1-.2-.48.67.67,0,0,1,.67-.68.67.67,0,0,1,.49.19.68.68,0,0,1,0,1A.66.66,0,0,1,91.15,111.92Zm.51,8.15h-1v-6.5h1Z"/><path class="cls-3" d="M93.37,119.84v-1.12a3.09,3.09,0,0,0,1.87.63q1.37,0,1.37-.91a.79.79,0,0,0-.12-.44,1.17,1.17,0,0,0-.32-.32,2.44,2.44,0,0,0-.47-.25l-.58-.23a7.45,7.45,0,0,1-.76-.35,2.3,2.3,0,0,1-.55-.39,1.47,1.47,0,0,1-.33-.5,1.76,1.76,0,0,1-.11-.65,1.56,1.56,0,0,1,.21-.81,1.85,1.85,0,0,1,.56-.59,2.6,2.6,0,0,1,.8-.36,3.52,3.52,0,0,1,.92-.12,3.74,3.74,0,0,1,1.51.29v1.05a2.94,2.94,0,0,0-1.65-.47,2,2,0,0,0-.53.07,1.3,1.3,0,0,0-.4.19.87.87,0,0,0-.26.29.77.77,0,0,0-.09.37.9.9,0,0,0,.09.42.94.94,0,0,0,.27.3,2,2,0,0,0,.43.24l.58.23a8.15,8.15,0,0,1,.78.34,2.64,2.64,0,0,1,.58.39,1.53,1.53,0,0,1,.37.5,1.63,1.63,0,0,1,.13.68,1.61,1.61,0,0,1-.21.84,1.84,1.84,0,0,1-.57.59,2.61,2.61,0,0,1-.82.35,4,4,0,0,1-1,.11A3.69,3.69,0,0,1,93.37,119.84Z"/><path class="cls-3" d="M102.29,120a2,2,0,0,1-1,.2q-1.71,0-1.71-1.9v-3.85H98.5v-.89h1.12V112l1-.34v1.92h1.64v.89h-1.64v3.66a1.52,1.52,0,0,0,.22.93.88.88,0,0,0,.74.28,1.09,1.09,0,0,0,.68-.22Z"/><path class="cls-3" d="M106.3,120.23a3,3,0,0,1-2.3-.91,3.37,3.37,0,0,1-.86-2.42,3.51,3.51,0,0,1,.9-2.56,3.22,3.22,0,0,1,2.42-.92,2.92,2.92,0,0,1,2.27.89,3.56,3.56,0,0,1,.82,2.48,3.49,3.49,0,0,1-.88,2.49A3.08,3.08,0,0,1,106.3,120.23Zm.08-5.93a2,2,0,0,0-1.59.68,2.8,2.8,0,0,0-.58,1.88,2.64,2.64,0,0,0,.59,1.82,2,2,0,0,0,1.58.67,1.9,1.9,0,0,0,1.55-.65,2.84,2.84,0,0,0,.54-1.86,2.88,2.88,0,0,0-.54-1.88A1.89,1.89,0,0,0,106.38,114.3Z"/><path class="cls-3" d="M114.59,114.63a1.27,1.27,0,0,0-.79-.21,1.33,1.33,0,0,0-1.11.63,2.91,2.91,0,0,0-.45,1.71v3.31h-1v-6.5h1v1.34h0a2.27,2.27,0,0,1,.68-1.07,1.55,1.55,0,0,1,1-.38,1.69,1.69,0,0,1,.62.09Z"/><path class="cls-3" d="M121.41,113.57l-3,7.54q-.8,2-2.25,2a2.36,2.36,0,0,1-.68-.08v-.93a1.93,1.93,0,0,0,.62.11,1.28,1.28,0,0,0,1.18-.94l.52-1.23-2.54-6.49h1.16l1.76,5q0,.1.13.5h0q0-.15.13-.48l1.85-5Z"/><path class="cls-3" d="M17.65,141.69a5.34,5.34,0,0,1-2.51.53A4.06,4.06,0,0,1,12,141a4.61,4.61,0,0,1-1.17-3.28,4.83,4.83,0,0,1,1.31-3.53,4.46,4.46,0,0,1,3.33-1.35,5.36,5.36,0,0,1,2.15.37v1.14a4.35,4.35,0,0,0-2.16-.55,3.31,3.31,0,0,0-2.54,1,3.94,3.94,0,0,0-1,2.8,3.76,3.76,0,0,0,.91,2.65,3.1,3.1,0,0,0,2.39,1,4.48,4.48,0,0,0,2.37-.61Z"/><path class="cls-3" d="M20.4,142.07h-1v-9.62h1Z"/><path class="cls-3" d="M25.23,142.23a3,3,0,0,1-2.3-.91,3.37,3.37,0,0,1-.86-2.42,3.51,3.51,0,0,1,.9-2.56,3.22,3.22,0,0,1,2.42-.92,2.92,2.92,0,0,1,2.27.89,3.56,3.56,0,0,1,.82,2.48,3.49,3.49,0,0,1-.88,2.49A3.08,3.08,0,0,1,25.23,142.23Zm.08-5.93a2,2,0,0,0-1.59.68,2.8,2.8,0,0,0-.58,1.88,2.64,2.64,0,0,0,.59,1.82,2,2,0,0,0,1.58.67,1.9,1.9,0,0,0,1.55-.65,2.84,2.84,0,0,0,.54-1.86,2.88,2.88,0,0,0-.54-1.88A1.89,1.89,0,0,0,25.3,136.3Z"/><path class="cls-3" d="M29.73,141.84v-1.12a3.09,3.09,0,0,0,1.87.63q1.37,0,1.37-.91a.8.8,0,0,0-.12-.44,1.16,1.16,0,0,0-.32-.32,2.46,2.46,0,0,0-.47-.25l-.58-.23a7.47,7.47,0,0,1-.76-.35,2.29,2.29,0,0,1-.55-.39,1.47,1.47,0,0,1-.33-.5,1.76,1.76,0,0,1-.11-.65,1.56,1.56,0,0,1,.21-.81,1.87,1.87,0,0,1,.56-.59,2.6,2.6,0,0,1,.8-.36,3.51,3.51,0,0,1,.92-.12,3.74,3.74,0,0,1,1.51.29v1.05a2.94,2.94,0,0,0-1.65-.47,1.94,1.94,0,0,0-.53.07,1.3,1.3,0,0,0-.4.19.86.86,0,0,0-.26.29.77.77,0,0,0-.09.37.9.9,0,0,0,.09.42.92.92,0,0,0,.27.3,2.06,2.06,0,0,0,.43.24l.58.23a8.23,8.23,0,0,1,.77.34,2.64,2.64,0,0,1,.58.39,1.52,1.52,0,0,1,.37.5,1.8,1.8,0,0,1-.08,1.52,1.82,1.82,0,0,1-.57.59,2.61,2.61,0,0,1-.82.35,4,4,0,0,1-1,.11A3.69,3.69,0,0,1,29.73,141.84Z"/><path class="cls-3" d="M40.87,139.08H36.28a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.74,2.74,0,0,1-2.16-.89,3.62,3.62,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.45,2.45,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.11,2.11,0,0,0-.44-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.38,2.38,0,0,0-.63,1.38Z"/><path class="cls-3" d="M53.48,142.07H52.17l-4.68-7.26a3,3,0,0,1-.29-.57h0a9.48,9.48,0,0,1,.05,1.25v6.58H46.14V133h1.38l4.56,7.14c.19.3.31.5.37.61h0a9.73,9.73,0,0,1-.06-1.34V133h1.07Z"/><path class="cls-3" d="M58.44,142.23a3,3,0,0,1-2.3-.91,3.37,3.37,0,0,1-.86-2.42,3.52,3.52,0,0,1,.89-2.56,3.22,3.22,0,0,1,2.42-.92,2.92,2.92,0,0,1,2.27.89,3.55,3.55,0,0,1,.82,2.48,3.49,3.49,0,0,1-.88,2.49A3.08,3.08,0,0,1,58.44,142.23Zm.08-5.93a2,2,0,0,0-1.59.68,2.8,2.8,0,0,0-.58,1.88,2.65,2.65,0,0,0,.59,1.82,2,2,0,0,0,1.58.67,1.9,1.9,0,0,0,1.55-.65,2.84,2.84,0,0,0,.54-1.86,2.89,2.89,0,0,0-.54-1.88A1.89,1.89,0,0,0,58.52,136.3Z"/><path class="cls-3" d="M66.36,142a2,2,0,0,1-1,.2q-1.71,0-1.71-1.9v-3.85H62.56v-.89h1.12V134l1-.34v1.92h1.64v.89H64.72v3.66a1.52,1.52,0,0,0,.22.93.89.89,0,0,0,.74.28,1.1,1.1,0,0,0,.68-.22Z"/><path class="cls-3" d="M68.28,133.92a.66.66,0,0,1-.48-.19.64.64,0,0,1-.2-.48.67.67,0,0,1,.67-.68.67.67,0,0,1,.48.19.67.67,0,0,1,0,1A.66.66,0,0,1,68.28,133.92Zm.51,8.15h-1v-6.5h1Z"/><path class="cls-3" d="M74.11,133.37a1.39,1.39,0,0,0-.69-.17q-1.09,0-1.09,1.38v1h1.52v.89H72.33v5.61h-1v-5.61H70.18v-.89h1.11v-1.05a2.19,2.19,0,0,1,.59-1.62,2,2,0,0,1,1.47-.59,2,2,0,0,1,.75.11Z"/><path class="cls-3" d="M75.5,133.92a.66.66,0,0,1-.48-.19.64.64,0,0,1-.2-.48.67.67,0,0,1,.67-.68.67.67,0,0,1,.49.19.68.68,0,0,1,0,1A.66.66,0,0,1,75.5,133.92Zm.51,8.15H75v-6.5h1Z"/><path class="cls-3" d="M82.55,141.78a3.38,3.38,0,0,1-1.78.45,2.94,2.94,0,0,1-2.24-.9,3.28,3.28,0,0,1-.85-2.35,3.6,3.6,0,0,1,.92-2.58,3.22,3.22,0,0,1,2.46-1,3.41,3.41,0,0,1,1.51.32v1.07A2.64,2.64,0,0,0,81,136.3a2.1,2.1,0,0,0-1.63.71,2.71,2.71,0,0,0-.64,1.88,2.58,2.58,0,0,0,.6,1.8,2.07,2.07,0,0,0,1.61.66,2.61,2.61,0,0,0,1.6-.57Z"/><path class="cls-3" d="M88.77,142.07h-1v-1h0a2.18,2.18,0,0,1-2,1.17,2.14,2.14,0,0,1-1.52-.51,1.78,1.78,0,0,1-.55-1.37q0-1.82,2.15-2.12l1.95-.27q0-1.66-1.34-1.66a3.2,3.2,0,0,0-2.12.8V136a4,4,0,0,1,2.21-.61q2.29,0,2.29,2.42Zm-1-3.29-1.57.22a2.55,2.55,0,0,0-1.09.36,1,1,0,0,0-.37.91A1,1,0,0,0,85,141a1.31,1.31,0,0,0,.9.3,1.67,1.67,0,0,0,1.28-.54,1.94,1.94,0,0,0,.5-1.37Z"/><path class="cls-3" d="M93.75,142a2,2,0,0,1-1,.2q-1.71,0-1.71-1.9v-3.85H90v-.89h1.12V134l1-.34v1.92h1.64v.89H92.11v3.66a1.52,1.52,0,0,0,.22.93.89.89,0,0,0,.74.28,1.1,1.1,0,0,0,.68-.22Z"/><path class="cls-3" d="M95.67,133.92a.66.66,0,0,1-.48-.19.64.64,0,0,1-.2-.48.67.67,0,0,1,.67-.68.67.67,0,0,1,.49.19.68.68,0,0,1,0,1A.66.66,0,0,1,95.67,133.92Zm.51,8.15h-1v-6.5h1Z"/><path class="cls-3" d="M101,142.23a3,3,0,0,1-2.3-.91,3.37,3.37,0,0,1-.86-2.42,3.52,3.52,0,0,1,.89-2.56,3.22,3.22,0,0,1,2.42-.92,2.92,2.92,0,0,1,2.27.89,3.55,3.55,0,0,1,.82,2.48,3.49,3.49,0,0,1-.88,2.49A3.08,3.08,0,0,1,101,142.23Zm.08-5.93a2,2,0,0,0-1.59.68,2.81,2.81,0,0,0-.58,1.88,2.65,2.65,0,0,0,.59,1.82,2,2,0,0,0,1.58.67,1.9,1.9,0,0,0,1.55-.65,2.84,2.84,0,0,0,.54-1.86,2.88,2.88,0,0,0-.54-1.88A1.89,1.89,0,0,0,101.08,136.3Z"/><path class="cls-3" d="M111.3,142.07h-1v-3.71q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71h-1v-6.5h1v1.08h0a2.35,2.35,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.56,2Z"/><path class="cls-3" d="M126.24,142.07h-1.06V136q0-.72.09-1.77h0a5.6,5.6,0,0,1-.27.88l-3.11,7h-.52l-3.1-6.94a5.53,5.53,0,0,1-.27-.93h0q.05.54.05,1.78v6.09h-1V133h1.41l2.79,6.35a8.11,8.11,0,0,1,.42,1.09h0q.27-.75.44-1.12l2.85-6.32h1.33Z"/><path class="cls-3" d="M133.72,139.08h-4.59a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.74,2.74,0,0,1-2.16-.89,3.62,3.62,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.45,2.45,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.11,2.11,0,0,0-.44-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.38,2.38,0,0,0-.63,1.38Z"/><path class="cls-3" d="M134.9,141.84v-1.12a3.09,3.09,0,0,0,1.87.63q1.37,0,1.37-.91A.8.8,0,0,0,138,140a1.16,1.16,0,0,0-.32-.32,2.46,2.46,0,0,0-.47-.25l-.58-.23a7.47,7.47,0,0,1-.76-.35,2.29,2.29,0,0,1-.55-.39,1.47,1.47,0,0,1-.33-.5,1.76,1.76,0,0,1-.11-.65,1.56,1.56,0,0,1,.21-.81,1.87,1.87,0,0,1,.56-.59,2.6,2.6,0,0,1,.8-.36,3.51,3.51,0,0,1,.92-.12,3.74,3.74,0,0,1,1.51.29v1.05a2.94,2.94,0,0,0-1.65-.47,1.94,1.94,0,0,0-.53.07,1.3,1.3,0,0,0-.4.19.86.86,0,0,0-.26.29.77.77,0,0,0-.09.37.9.9,0,0,0,.09.42.92.92,0,0,0,.27.3,2.06,2.06,0,0,0,.43.24l.58.23a8.23,8.23,0,0,1,.77.34,2.64,2.64,0,0,1,.58.39,1.52,1.52,0,0,1,.37.5,1.8,1.8,0,0,1-.08,1.52,1.82,1.82,0,0,1-.57.59,2.61,2.61,0,0,1-.82.35,4,4,0,0,1-1,.11A3.69,3.69,0,0,1,134.9,141.84Z"/><path class="cls-3" d="M140.42,141.84v-1.12a3.09,3.09,0,0,0,1.87.63q1.37,0,1.37-.91a.79.79,0,0,0-.12-.44,1.17,1.17,0,0,0-.32-.32,2.44,2.44,0,0,0-.47-.25l-.58-.23a7.45,7.45,0,0,1-.76-.35,2.3,2.3,0,0,1-.55-.39,1.47,1.47,0,0,1-.33-.5,1.76,1.76,0,0,1-.11-.65,1.56,1.56,0,0,1,.21-.81,1.85,1.85,0,0,1,.56-.59,2.6,2.6,0,0,1,.8-.36,3.52,3.52,0,0,1,.92-.12,3.74,3.74,0,0,1,1.51.29v1.05a2.94,2.94,0,0,0-1.65-.47,2,2,0,0,0-.53.07,1.3,1.3,0,0,0-.4.19.87.87,0,0,0-.26.29.77.77,0,0,0-.09.37.9.9,0,0,0,.09.42.94.94,0,0,0,.27.3,2,2,0,0,0,.43.24l.58.23a8.15,8.15,0,0,1,.78.34,2.64,2.64,0,0,1,.58.39,1.53,1.53,0,0,1,.37.5,1.63,1.63,0,0,1,.13.68,1.61,1.61,0,0,1-.21.84,1.84,1.84,0,0,1-.57.59,2.61,2.61,0,0,1-.82.35,4,4,0,0,1-1,.11A3.69,3.69,0,0,1,140.42,141.84Z"/><path class="cls-3" d="M151,142.07h-1v-1h0a2.18,2.18,0,0,1-2,1.17,2.14,2.14,0,0,1-1.52-.51,1.78,1.78,0,0,1-.55-1.37q0-1.82,2.15-2.12l1.95-.27q0-1.66-1.34-1.66a3.2,3.2,0,0,0-2.12.8V136a4,4,0,0,1,2.21-.61q2.29,0,2.29,2.42Zm-1-3.29-1.57.22a2.55,2.55,0,0,0-1.09.36,1,1,0,0,0-.37.91,1,1,0,0,0,.34.78,1.31,1.31,0,0,0,.9.3,1.67,1.67,0,0,0,1.28-.54,1.94,1.94,0,0,0,.5-1.37Z"/><path class="cls-3" d="M158.49,141.55q0,3.58-3.43,3.58a4.6,4.6,0,0,1-2.11-.46v-1a4.33,4.33,0,0,0,2.09.61q2.4,0,2.4-2.55V141h0a2.63,2.63,0,0,1-4.19.38,3.47,3.47,0,0,1-.74-2.33,4,4,0,0,1,.8-2.63,2.66,2.66,0,0,1,2.18-1,2.12,2.12,0,0,1,1.95,1.05h0v-.9h1Zm-1-2.42v-1a1.86,1.86,0,0,0-.52-1.33,1.73,1.73,0,0,0-1.3-.55,1.81,1.81,0,0,0-1.51.7,3.14,3.14,0,0,0-.55,2,2.69,2.69,0,0,0,.52,1.74,1.69,1.69,0,0,0,1.39.65,1.81,1.81,0,0,0,1.42-.62A2.32,2.32,0,0,0,157.45,139.13Z"/><path class="cls-3" d="M165.82,139.08h-4.59a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.16-.89,3.62,3.62,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.45,2.45,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.12,2.12,0,0,0-.43-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.39,2.39,0,0,0-.63,1.38Z"/><path class="cls-3" d="M167,141.84v-1.12a3.09,3.09,0,0,0,1.87.63q1.37,0,1.37-.91a.79.79,0,0,0-.12-.44,1.17,1.17,0,0,0-.32-.32,2.44,2.44,0,0,0-.47-.25l-.58-.23a7.45,7.45,0,0,1-.76-.35,2.3,2.3,0,0,1-.55-.39,1.47,1.47,0,0,1-.33-.5,1.76,1.76,0,0,1-.11-.65,1.56,1.56,0,0,1,.21-.81,1.85,1.85,0,0,1,.56-.59,2.6,2.6,0,0,1,.8-.36,3.52,3.52,0,0,1,.92-.12,3.74,3.74,0,0,1,1.51.29v1.05a2.94,2.94,0,0,0-1.65-.47,2,2,0,0,0-.53.07,1.3,1.3,0,0,0-.4.19.87.87,0,0,0-.26.29.77.77,0,0,0-.09.37.9.9,0,0,0,.09.42.94.94,0,0,0,.27.3,2,2,0,0,0,.43.24l.58.23a8.15,8.15,0,0,1,.78.34,2.64,2.64,0,0,1,.58.39,1.53,1.53,0,0,1,.37.5,1.63,1.63,0,0,1,.13.68,1.61,1.61,0,0,1-.21.84,1.84,1.84,0,0,1-.57.59,2.61,2.61,0,0,1-.82.35,4,4,0,0,1-1,.11A3.69,3.69,0,0,1,167,141.84Z"/><path class="cls-3" d="M17.65,163.69a5.34,5.34,0,0,1-2.51.53A4.06,4.06,0,0,1,12,163a4.61,4.61,0,0,1-1.17-3.28,4.83,4.83,0,0,1,1.31-3.53,4.46,4.46,0,0,1,3.33-1.35,5.36,5.36,0,0,1,2.15.37v1.14a4.35,4.35,0,0,0-2.16-.55,3.31,3.31,0,0,0-2.54,1,3.94,3.94,0,0,0-1,2.8,3.76,3.76,0,0,0,.91,2.65,3.1,3.1,0,0,0,2.39,1,4.48,4.48,0,0,0,2.37-.61Z"/><path class="cls-3" d="M20.4,164.07h-1v-9.62h1Z"/><path class="cls-3" d="M25.23,164.23a3,3,0,0,1-2.3-.91,3.37,3.37,0,0,1-.86-2.42,3.51,3.51,0,0,1,.9-2.56,3.22,3.22,0,0,1,2.42-.92,2.92,2.92,0,0,1,2.27.89,3.56,3.56,0,0,1,.82,2.48,3.49,3.49,0,0,1-.88,2.49A3.08,3.08,0,0,1,25.23,164.23Zm.08-5.93a2,2,0,0,0-1.59.68,2.8,2.8,0,0,0-.58,1.88,2.64,2.64,0,0,0,.59,1.82,2,2,0,0,0,1.58.67,1.9,1.9,0,0,0,1.55-.65,2.84,2.84,0,0,0,.54-1.86,2.88,2.88,0,0,0-.54-1.88A1.89,1.89,0,0,0,25.3,158.3Z"/><path class="cls-3" d="M29.73,163.84v-1.12a3.09,3.09,0,0,0,1.87.63q1.37,0,1.37-.91a.8.8,0,0,0-.12-.44,1.16,1.16,0,0,0-.32-.32,2.46,2.46,0,0,0-.47-.25l-.58-.23a7.47,7.47,0,0,1-.76-.35,2.29,2.29,0,0,1-.55-.39,1.47,1.47,0,0,1-.33-.5,1.76,1.76,0,0,1-.11-.65,1.56,1.56,0,0,1,.21-.81,1.87,1.87,0,0,1,.56-.59,2.6,2.6,0,0,1,.8-.36,3.51,3.51,0,0,1,.92-.12,3.74,3.74,0,0,1,1.51.29v1.05a2.94,2.94,0,0,0-1.65-.47,1.94,1.94,0,0,0-.53.07,1.3,1.3,0,0,0-.4.19.86.86,0,0,0-.26.29.77.77,0,0,0-.09.37.9.9,0,0,0,.09.42.92.92,0,0,0,.27.3,2.06,2.06,0,0,0,.43.24l.58.23a8.23,8.23,0,0,1,.77.34,2.64,2.64,0,0,1,.58.39,1.52,1.52,0,0,1,.37.5,1.8,1.8,0,0,1-.08,1.52,1.82,1.82,0,0,1-.57.59,2.61,2.61,0,0,1-.82.35,4,4,0,0,1-1,.11A3.69,3.69,0,0,1,29.73,163.84Z"/><path class="cls-3" d="M40.87,161.08H36.28a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.74,2.74,0,0,1-2.16-.89,3.62,3.62,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.45,2.45,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.11,2.11,0,0,0-.44-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.38,2.38,0,0,0-.63,1.38Z"/><path class="cls-3" d="M56.93,155l-2.57,9.1H53.11l-1.87-6.65a4.11,4.11,0,0,1-.15-.93h0a4.67,4.67,0,0,1-.17.91L49,164.07H47.78L45.11,155h1.17l1.94,7a4.63,4.63,0,0,1,.15.91h0a5.39,5.39,0,0,1,.2-.91l2-7h1l1.93,7a5,5,0,0,1,.15.85h0a5.15,5.15,0,0,1,.17-.88l1.86-7Z"/><path class="cls-3" d="M58.68,155.92a.66.66,0,0,1-.48-.19.64.64,0,0,1-.2-.48.67.67,0,0,1,.67-.68.67.67,0,0,1,.49.19.68.68,0,0,1,0,1A.66.66,0,0,1,58.68,155.92Zm.51,8.15h-1v-6.5h1Z"/><path class="cls-3" d="M66.69,164.07h-1v-3.71q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71h-1v-6.5h1v1.08h0a2.35,2.35,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.56,2Z"/><path class="cls-3" d="M74.2,164.07h-1V163h0a2.62,2.62,0,0,1-4.19.38,3.58,3.58,0,0,1-.73-2.38,3.9,3.9,0,0,1,.81-2.58,2.68,2.68,0,0,1,2.16-1,2.09,2.09,0,0,1,1.95,1.05h0v-4h1Zm-1-2.94v-1a1.86,1.86,0,0,0-.52-1.33,1.74,1.74,0,0,0-1.32-.55,1.8,1.8,0,0,0-1.5.7,3.06,3.06,0,0,0-.54,1.93,2.75,2.75,0,0,0,.52,1.77,1.71,1.71,0,0,0,1.41.65,1.78,1.78,0,0,0,1.41-.63A2.35,2.35,0,0,0,73.16,161.13Z"/><path class="cls-3" d="M79,164.23a3,3,0,0,1-2.3-.91,3.37,3.37,0,0,1-.86-2.42,3.52,3.52,0,0,1,.9-2.56,3.22,3.22,0,0,1,2.42-.92,2.92,2.92,0,0,1,2.27.89,3.56,3.56,0,0,1,.81,2.48,3.49,3.49,0,0,1-.88,2.49A3.08,3.08,0,0,1,79,164.23Zm.08-5.93a2,2,0,0,0-1.59.68,2.81,2.81,0,0,0-.58,1.88,2.65,2.65,0,0,0,.59,1.82,2,2,0,0,0,1.58.67,1.9,1.9,0,0,0,1.55-.65,2.83,2.83,0,0,0,.54-1.86,2.88,2.88,0,0,0-.54-1.88A1.89,1.89,0,0,0,79.1,158.3Z"/><path class="cls-3" d="M92.11,157.57l-1.95,6.5H89.08l-1.34-4.65a3.08,3.08,0,0,1-.1-.6h0a2.76,2.76,0,0,1-.13.59L86,164.07H85l-2-6.5h1.09l1.35,4.89a2.94,2.94,0,0,1,.09.58h.05a2.73,2.73,0,0,1,.11-.6l1.5-4.87h1l1.35,4.9a3.47,3.47,0,0,1,.09.58h.05a2.67,2.67,0,0,1,.11-.58l1.32-4.9Z"/><path class="cls-3" d="M17.65,185.69a5.34,5.34,0,0,1-2.51.53A4.06,4.06,0,0,1,12,185a4.61,4.61,0,0,1-1.17-3.28,4.83,4.83,0,0,1,1.31-3.53,4.46,4.46,0,0,1,3.33-1.35,5.36,5.36,0,0,1,2.15.37v1.14a4.35,4.35,0,0,0-2.16-.55,3.31,3.31,0,0,0-2.54,1,3.94,3.94,0,0,0-1,2.8,3.76,3.76,0,0,0,.91,2.65,3.1,3.1,0,0,0,2.39,1,4.48,4.48,0,0,0,2.37-.61Z"/><path class="cls-3" d="M22.08,186.23a3,3,0,0,1-2.3-.91,3.37,3.37,0,0,1-.86-2.42,3.51,3.51,0,0,1,.9-2.56,3.22,3.22,0,0,1,2.42-.92,2.92,2.92,0,0,1,2.27.89,3.56,3.56,0,0,1,.82,2.48,3.49,3.49,0,0,1-.88,2.49A3.08,3.08,0,0,1,22.08,186.23Zm.08-5.93a2,2,0,0,0-1.59.68,2.8,2.8,0,0,0-.58,1.88,2.64,2.64,0,0,0,.59,1.82,2,2,0,0,0,1.58.67,1.9,1.9,0,0,0,1.55-.65,2.84,2.84,0,0,0,.54-1.86,2.88,2.88,0,0,0-.54-1.88A1.89,1.89,0,0,0,22.15,180.3Z"/><path class="cls-3" d="M32.37,186.07h-1v-3.71q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71H27v-6.5h1v1.08h0a2.34,2.34,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.57,2Z"/><path class="cls-3" d="M37.55,177.37a1.39,1.39,0,0,0-.69-.17q-1.09,0-1.09,1.38v1h1.52v.89H35.76v5.61h-1v-5.61H33.62v-.89h1.11v-1.05a2.19,2.19,0,0,1,.59-1.62,2,2,0,0,1,1.47-.59,2,2,0,0,1,.75.11Z"/><path class="cls-3" d="M38.94,177.92a.66.66,0,0,1-.48-.19.64.64,0,0,1-.2-.48.67.67,0,0,1,.67-.68.67.67,0,0,1,.49.19.68.68,0,0,1,0,1A.66.66,0,0,1,38.94,177.92Zm.51,8.15h-1v-6.5h1Z"/><path class="cls-3" d="M47.1,185.55q0,3.58-3.43,3.58a4.6,4.6,0,0,1-2.11-.46v-1a4.33,4.33,0,0,0,2.09.61q2.4,0,2.4-2.55V185h0a2.63,2.63,0,0,1-4.19.38,3.47,3.47,0,0,1-.74-2.33,4,4,0,0,1,.8-2.63,2.66,2.66,0,0,1,2.18-1A2.12,2.12,0,0,1,46,180.48h0v-.9h1Zm-1-2.42v-1a1.86,1.86,0,0,0-.52-1.33,1.73,1.73,0,0,0-1.3-.55,1.81,1.81,0,0,0-1.51.7,3.14,3.14,0,0,0-.55,2,2.69,2.69,0,0,0,.52,1.74,1.69,1.69,0,0,0,1.39.65,1.81,1.81,0,0,0,1.42-.62A2.32,2.32,0,0,0,46.06,183.13Z"/><path class="cls-3" d="M54.46,186.07h-1v-1h0a2.14,2.14,0,0,1-2,1.18q-2.32,0-2.32-2.77v-3.88h1v3.72q0,2.06,1.57,2.06a1.59,1.59,0,0,0,1.25-.56,2.15,2.15,0,0,0,.49-1.47v-3.75h1Z"/><path class="cls-3" d="M60,180.63a1.28,1.28,0,0,0-.79-.21,1.33,1.33,0,0,0-1.12.63,2.92,2.92,0,0,0-.45,1.71v3.31h-1v-6.5h1v1.34h0a2.27,2.27,0,0,1,.68-1.07,1.55,1.55,0,0,1,1-.38,1.7,1.7,0,0,1,.62.09Z"/><path class="cls-3" d="M66.14,183.08H61.55a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.16-.89,3.62,3.62,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.45,2.45,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.12,2.12,0,0,0-.43-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.39,2.39,0,0,0-.63,1.38Z"/><path class="cls-3" d="M76.13,186.07H71.41V177h1.07v8.14h3.66Z"/><path class="cls-3" d="M82,186.07H81v-1h0a2.18,2.18,0,0,1-2,1.17,2.14,2.14,0,0,1-1.52-.51,1.78,1.78,0,0,1-.55-1.37q0-1.82,2.15-2.12L81,182q0-1.66-1.34-1.66a3.2,3.2,0,0,0-2.12.8V180a4,4,0,0,1,2.21-.61q2.29,0,2.29,2.42Zm-1-3.29-1.57.22a2.55,2.55,0,0,0-1.09.36,1,1,0,0,0-.37.91,1,1,0,0,0,.34.78,1.31,1.31,0,0,0,.9.3,1.67,1.67,0,0,0,1.28-.54,1.94,1.94,0,0,0,.5-1.37Z"/><path class="cls-3" d="M89.4,186.07h-1v-3.71q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71H84v-6.5h1v1.08h0a2.34,2.34,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.57,2Z"/><path class="cls-3" d="M96.91,185.55q0,3.58-3.43,3.58a4.61,4.61,0,0,1-2.11-.46v-1a4.33,4.33,0,0,0,2.1.61q2.4,0,2.4-2.55V185h0a2.63,2.63,0,0,1-4.19.38,3.47,3.47,0,0,1-.74-2.33,4,4,0,0,1,.8-2.63,2.66,2.66,0,0,1,2.18-1,2.12,2.12,0,0,1,1.95,1.05h0v-.9h1Zm-1-2.42v-1a1.86,1.86,0,0,0-.52-1.33,1.73,1.73,0,0,0-1.3-.55,1.81,1.81,0,0,0-1.51.7,3.13,3.13,0,0,0-.55,2,2.7,2.7,0,0,0,.52,1.74,1.69,1.69,0,0,0,1.39.65,1.81,1.81,0,0,0,1.42-.62A2.32,2.32,0,0,0,95.87,183.13Z"/><path class="cls-3" d="M104.27,186.07h-1v-1h0a2.14,2.14,0,0,1-2,1.18q-2.32,0-2.32-2.77v-3.88h1v3.72q0,2.06,1.57,2.06a1.59,1.59,0,0,0,1.25-.56,2.15,2.15,0,0,0,.49-1.47v-3.75h1Z"/><path class="cls-3" d="M111,186.07h-1v-1h0a2.18,2.18,0,0,1-2,1.17,2.14,2.14,0,0,1-1.52-.51,1.79,1.79,0,0,1-.55-1.37q0-1.82,2.15-2.12L110,182q0-1.66-1.34-1.66a3.2,3.2,0,0,0-2.12.8V180a4,4,0,0,1,2.21-.61q2.29,0,2.29,2.42Zm-1-3.29-1.57.22a2.55,2.55,0,0,0-1.09.36,1,1,0,0,0-.37.91,1,1,0,0,0,.34.78,1.31,1.31,0,0,0,.9.3,1.67,1.67,0,0,0,1.28-.54,1.94,1.94,0,0,0,.5-1.37Z"/><path class="cls-3" d="M118.54,185.55q0,3.58-3.43,3.58a4.6,4.6,0,0,1-2.11-.46v-1a4.33,4.33,0,0,0,2.09.61q2.4,0,2.4-2.55V185h0a2.63,2.63,0,0,1-4.19.38,3.46,3.46,0,0,1-.74-2.33,4,4,0,0,1,.8-2.63,2.66,2.66,0,0,1,2.18-1,2.12,2.12,0,0,1,1.95,1.05h0v-.9h1Zm-1-2.42v-1a1.86,1.86,0,0,0-.52-1.33,1.73,1.73,0,0,0-1.3-.55,1.81,1.81,0,0,0-1.51.7,3.13,3.13,0,0,0-.55,2,2.69,2.69,0,0,0,.52,1.74,1.69,1.69,0,0,0,1.39.65,1.81,1.81,0,0,0,1.43-.62A2.32,2.32,0,0,0,117.5,183.13Z"/><path class="cls-3" d="M125.87,183.08h-4.59a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.17-.89,3.63,3.63,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.44,2.44,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.12,2.12,0,0,0-.44-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.4,2.4,0,0,0-.63,1.38Z"/><rect class="cls-6" width="386" height="197"/></g></g></svg>
src/vs/workbench/contrib/welcomeOverlay/browser/media/commandpalette.svg
0
https://github.com/microsoft/vscode/commit/626c64bc9a48591e226edd3c04a4bef9e886828e
[ 0.00016903156938496977, 0.00016903156938496977, 0.00016903156938496977, 0.00016903156938496977, 0 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\toverride updateLabel(e?: ITerminalInstance): void {\n", "\t\t// Only update if it's the active instance\n", "\t\tif (e && e !== this._terminalGroupService.activeInstance) {\n", "\t\t\treturn;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t// eslint-disable-next-line @typescript-eslint/naming-convention\n", "\tprotected override updateLabel(e?: ITerminalInstance): void {\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalView.ts", "type": "replace", "edit_start_line_idx": 384 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./simpleFindWidget'; import * as nls from 'vs/nls'; import * as dom from 'vs/base/browser/dom'; import { FindInput } from 'vs/base/browser/ui/findinput/findInput'; import { Widget } from 'vs/base/browser/ui/widget'; import { Delayer } from 'vs/base/common/async'; import { KeyCode } from 'vs/base/common/keyCodes'; import { FindReplaceState } from 'vs/editor/contrib/find/browser/findState'; import { IMessage as InputBoxMessage } from 'vs/base/browser/ui/inputbox/inputBox'; import { SimpleButton, findPreviousMatchIcon, findNextMatchIcon, NLS_NO_RESULTS, NLS_MATCHES_LOCATION } from 'vs/editor/contrib/find/browser/findWidget'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { ContextScopedFindInput } from 'vs/platform/history/browser/contextScopedHistoryWidget'; import { widgetClose } from 'vs/platform/theme/common/iconRegistry'; import * as strings from 'vs/base/common/strings'; import { TerminalCommandId } from 'vs/workbench/contrib/terminal/common/terminal'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { showHistoryKeybindingHint } from 'vs/platform/history/browser/historyWidgetKeybindingHint'; import { alert as alertFn } from 'vs/base/browser/ui/aria/aria'; import { defaultInputBoxStyles, defaultToggleStyles } from 'vs/platform/theme/browser/defaultStyles'; const NLS_FIND_INPUT_LABEL = nls.localize('label.find', "Find"); const NLS_FIND_INPUT_PLACEHOLDER = nls.localize('placeholder.find', "Find (\u21C5 for history)"); const NLS_PREVIOUS_MATCH_BTN_LABEL = nls.localize('label.previousMatchButton', "Previous Match"); const NLS_NEXT_MATCH_BTN_LABEL = nls.localize('label.nextMatchButton', "Next Match"); const NLS_CLOSE_BTN_LABEL = nls.localize('label.closeButton', "Close"); interface IFindOptions { showCommonFindToggles?: boolean; checkImeCompletionState?: boolean; showResultCount?: boolean; appendCaseSensitiveLabel?: string; appendRegexLabel?: string; appendWholeWordsLabel?: string; type?: 'Terminal' | 'Webview'; } const SIMPLE_FIND_WIDGET_INITIAL_WIDTH = 310; const MATCHES_COUNT_WIDTH = 68; export abstract class SimpleFindWidget extends Widget { private readonly _findInput: FindInput; private readonly _domNode: HTMLElement; private readonly _innerDomNode: HTMLElement; private readonly _focusTracker: dom.IFocusTracker; private readonly _findInputFocusTracker: dom.IFocusTracker; private readonly _updateHistoryDelayer: Delayer<void>; private readonly prevBtn: SimpleButton; private readonly nextBtn: SimpleButton; private _matchesCount: HTMLElement | undefined; private _isVisible: boolean = false; private _foundMatch: boolean = false; private _width: number = 0; constructor( state: FindReplaceState = new FindReplaceState(), options: IFindOptions, contextViewService: IContextViewService, contextKeyService: IContextKeyService, private readonly _keybindingService: IKeybindingService ) { super(); this._findInput = this._register(new ContextScopedFindInput(null, contextViewService, { label: NLS_FIND_INPUT_LABEL, placeholder: NLS_FIND_INPUT_PLACEHOLDER, validation: (value: string): InputBoxMessage | null => { if (value.length === 0 || !this._findInput.getRegex()) { return null; } try { new RegExp(value); return null; } catch (e) { this._foundMatch = false; this.updateButtons(this._foundMatch); return { content: e.message }; } }, showCommonFindToggles: options.showCommonFindToggles, appendCaseSensitiveLabel: options.appendCaseSensitiveLabel && options.type === 'Terminal' ? this._getKeybinding(TerminalCommandId.ToggleFindCaseSensitive) : undefined, appendRegexLabel: options.appendRegexLabel && options.type === 'Terminal' ? this._getKeybinding(TerminalCommandId.ToggleFindRegex) : undefined, appendWholeWordsLabel: options.appendWholeWordsLabel && options.type === 'Terminal' ? this._getKeybinding(TerminalCommandId.ToggleFindWholeWord) : undefined, showHistoryHint: () => showHistoryKeybindingHint(_keybindingService), inputBoxStyles: defaultInputBoxStyles, toggleStyles: defaultToggleStyles }, contextKeyService)); // Find History with update delayer this._updateHistoryDelayer = new Delayer<void>(500); this._register(this._findInput.onInput(async (e) => { if (!options.checkImeCompletionState || !this._findInput.isImeSessionInProgress) { this._foundMatch = this._onInputChanged(); if (options.showResultCount) { await this.updateResultCount(); } this.updateButtons(this._foundMatch); this.focusFindBox(); this._delayedUpdateHistory(); } })); this._findInput.setRegex(!!state.isRegex); this._findInput.setCaseSensitive(!!state.matchCase); this._findInput.setWholeWords(!!state.wholeWord); this._register(this._findInput.onDidOptionChange(() => { state.change({ isRegex: this._findInput.getRegex(), wholeWord: this._findInput.getWholeWords(), matchCase: this._findInput.getCaseSensitive() }, true); })); this._register(state.onFindReplaceStateChange(() => { this._findInput.setRegex(state.isRegex); this._findInput.setWholeWords(state.wholeWord); this._findInput.setCaseSensitive(state.matchCase); this.findFirst(); })); this.prevBtn = this._register(new SimpleButton({ label: NLS_PREVIOUS_MATCH_BTN_LABEL, icon: findPreviousMatchIcon, onTrigger: () => { this.find(true); } })); this.nextBtn = this._register(new SimpleButton({ label: NLS_NEXT_MATCH_BTN_LABEL, icon: findNextMatchIcon, onTrigger: () => { this.find(false); } })); const closeBtn = this._register(new SimpleButton({ label: NLS_CLOSE_BTN_LABEL, icon: widgetClose, onTrigger: () => { this.hide(); } })); this._innerDomNode = document.createElement('div'); this._innerDomNode.classList.add('simple-find-part'); this._innerDomNode.appendChild(this._findInput.domNode); this._innerDomNode.appendChild(this.prevBtn.domNode); this._innerDomNode.appendChild(this.nextBtn.domNode); this._innerDomNode.appendChild(closeBtn.domNode); // _domNode wraps _innerDomNode, ensuring that this._domNode = document.createElement('div'); this._domNode.classList.add('simple-find-part-wrapper'); this._domNode.appendChild(this._innerDomNode); this.onkeyup(this._innerDomNode, e => { if (e.equals(KeyCode.Escape)) { this.hide(); e.preventDefault(); return; } }); this._focusTracker = this._register(dom.trackFocus(this._innerDomNode)); this._register(this._focusTracker.onDidFocus(this._onFocusTrackerFocus.bind(this))); this._register(this._focusTracker.onDidBlur(this._onFocusTrackerBlur.bind(this))); this._findInputFocusTracker = this._register(dom.trackFocus(this._findInput.domNode)); this._register(this._findInputFocusTracker.onDidFocus(this._onFindInputFocusTrackerFocus.bind(this))); this._register(this._findInputFocusTracker.onDidBlur(this._onFindInputFocusTrackerBlur.bind(this))); this._register(dom.addDisposableListener(this._innerDomNode, 'click', (event) => { event.stopPropagation(); })); if (options?.showResultCount) { this._domNode.classList.add('result-count'); this._matchesCount = document.createElement('div'); this._matchesCount.className = 'matchesCount'; this._findInput.domNode.insertAdjacentElement('afterend', this._matchesCount); this._register(this._findInput.onDidChange(() => { this.updateResultCount(); this.updateButtons(this._foundMatch); })); } } protected abstract _onInputChanged(): boolean; protected abstract find(previous: boolean): void; protected abstract findFirst(): void; protected abstract _onFocusTrackerFocus(): void; protected abstract _onFocusTrackerBlur(): void; protected abstract _onFindInputFocusTrackerFocus(): void; protected abstract _onFindInputFocusTrackerBlur(): void; protected abstract _getResultCount(): Promise<{ resultIndex: number; resultCount: number } | undefined>; protected get inputValue() { return this._findInput.getValue(); } public get focusTracker(): dom.IFocusTracker { return this._focusTracker; } private _getKeybinding(actionId: string): string { const kb = this._keybindingService?.lookupKeybinding(actionId); if (!kb) { return ''; } return ` (${kb.getLabel()})`; } override dispose() { super.dispose(); if (this._domNode && this._domNode.parentElement) { this._domNode.parentElement.removeChild(this._domNode); } } public isVisible(): boolean { return this._isVisible; } public getDomNode() { return this._domNode; } public reveal(initialInput?: string, animated = true): void { if (initialInput) { this._findInput.setValue(initialInput); } if (this._isVisible) { this._findInput.select(); return; } this._isVisible = true; this.updateButtons(this._foundMatch); this.layout(); setTimeout(() => { this._innerDomNode.classList.toggle('suppress-transition', !animated); this._innerDomNode.classList.add('visible', 'visible-transition'); this._innerDomNode.setAttribute('aria-hidden', 'false'); this._findInput.select(); if (!animated) { setTimeout(() => { this._innerDomNode.classList.remove('suppress-transition'); }, 0); } }, 0); } public show(initialInput?: string): void { if (initialInput && !this._isVisible) { this._findInput.setValue(initialInput); } this._isVisible = true; this.layout(); setTimeout(() => { this._innerDomNode.classList.add('visible', 'visible-transition'); this._innerDomNode.setAttribute('aria-hidden', 'false'); }, 0); } public hide(animated = true): void { if (this._isVisible) { this._innerDomNode.classList.toggle('suppress-transition', !animated); this._innerDomNode.classList.remove('visible-transition'); this._innerDomNode.setAttribute('aria-hidden', 'true'); // Need to delay toggling visibility until after Transition, then visibility hidden - removes from tabIndex list setTimeout(() => { this._isVisible = false; this.updateButtons(this._foundMatch); this._innerDomNode.classList.remove('visible', 'suppress-transition'); }, animated ? 200 : 0); } } public layout(width: number = this._width): void { this._width = width; if (!this._isVisible) { return; } if (this._matchesCount) { let reducedFindWidget = false; if (SIMPLE_FIND_WIDGET_INITIAL_WIDTH + MATCHES_COUNT_WIDTH + 28 >= width) { reducedFindWidget = true; } this._innerDomNode.classList.toggle('reduced-find-widget', reducedFindWidget); } } protected _delayedUpdateHistory() { this._updateHistoryDelayer.trigger(this._updateHistory.bind(this)); } protected _updateHistory() { this._findInput.inputBox.addToHistory(); } protected _getRegexValue(): boolean { return this._findInput.getRegex(); } protected _getWholeWordValue(): boolean { return this._findInput.getWholeWords(); } protected _getCaseSensitiveValue(): boolean { return this._findInput.getCaseSensitive(); } protected updateButtons(foundMatch: boolean) { const hasInput = this.inputValue.length > 0; this.prevBtn.setEnabled(this._isVisible && hasInput && foundMatch); this.nextBtn.setEnabled(this._isVisible && hasInput && foundMatch); } protected focusFindBox() { // Focus back onto the find box, which // requires focusing onto the next button first this.nextBtn.focus(); this._findInput.inputBox.focus(); } async updateResultCount(): Promise<void> { if (!this._matchesCount) { return; } const count = await this._getResultCount(); this._matchesCount.innerText = ''; let label = ''; this._matchesCount.classList.toggle('no-results', false); if (count?.resultCount !== undefined && count?.resultCount === 0) { label = NLS_NO_RESULTS; if (!!this.inputValue) { this._matchesCount.classList.toggle('no-results', true); } } else if (count?.resultCount) { label = strings.format(NLS_MATCHES_LOCATION, count.resultIndex + 1, count?.resultCount); } alertFn(this._announceSearchResults(label, this.inputValue)); this._matchesCount.appendChild(document.createTextNode(label)); this._foundMatch = !!count && count.resultCount > 0; } private _announceSearchResults(label: string, searchString?: string): string { if (!searchString) { return nls.localize('ariaSearchNoInput', "Enter search input"); } if (label === NLS_NO_RESULTS) { return searchString === '' ? nls.localize('ariaSearchNoResultEmpty', "{0} found", label) : nls.localize('ariaSearchNoResult', "{0} found for '{1}'", label, searchString); } return nls.localize('ariaSearchNoResultWithLineNumNoCurrentMatch', "{0} found for '{1}'", label, searchString); } }
src/vs/workbench/contrib/codeEditor/browser/find/simpleFindWidget.ts
1
https://github.com/microsoft/vscode/commit/626c64bc9a48591e226edd3c04a4bef9e886828e
[ 0.9583076238632202, 0.025385063141584396, 0.00016446420340798795, 0.0001709203643258661, 0.15337152779102325 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\toverride updateLabel(e?: ITerminalInstance): void {\n", "\t\t// Only update if it's the active instance\n", "\t\tif (e && e !== this._terminalGroupService.activeInstance) {\n", "\t\t\treturn;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t// eslint-disable-next-line @typescript-eslint/naming-convention\n", "\tprotected override updateLabel(e?: ITerminalInstance): void {\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalView.ts", "type": "replace", "edit_start_line_idx": 384 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { BrandedService } from 'vs/platform/instantiation/common/instantiation'; import { INotebookEditor, INotebookEditorContribution, INotebookEditorContributionCtor, INotebookEditorContributionDescription } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; class EditorContributionRegistry { public static readonly INSTANCE = new EditorContributionRegistry(); private readonly editorContributions: INotebookEditorContributionDescription[]; constructor() { this.editorContributions = []; } public registerEditorContribution<Services extends BrandedService[]>(id: string, ctor: { new(editor: INotebookEditor, ...services: Services): INotebookEditorContribution }): void { this.editorContributions.push({ id, ctor: ctor as INotebookEditorContributionCtor }); } public getEditorContributions(): INotebookEditorContributionDescription[] { return this.editorContributions.slice(0); } } export function registerNotebookContribution<Services extends BrandedService[]>(id: string, ctor: { new(editor: INotebookEditor, ...services: Services): INotebookEditorContribution }): void { EditorContributionRegistry.INSTANCE.registerEditorContribution(id, ctor); } export namespace NotebookEditorExtensionsRegistry { export function getEditorContributions(): INotebookEditorContributionDescription[] { return EditorContributionRegistry.INSTANCE.getEditorContributions(); } export function getSomeEditorContributions(ids: string[]): INotebookEditorContributionDescription[] { return EditorContributionRegistry.INSTANCE.getEditorContributions().filter(c => ids.indexOf(c.id) >= 0); } }
src/vs/workbench/contrib/notebook/browser/notebookEditorExtensions.ts
0
https://github.com/microsoft/vscode/commit/626c64bc9a48591e226edd3c04a4bef9e886828e
[ 0.0001797211734810844, 0.00017520089750178158, 0.00017265748465433717, 0.00017462506366427988, 0.000002385060952292406 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\toverride updateLabel(e?: ITerminalInstance): void {\n", "\t\t// Only update if it's the active instance\n", "\t\tif (e && e !== this._terminalGroupService.activeInstance) {\n", "\t\t\treturn;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t// eslint-disable-next-line @typescript-eslint/naming-convention\n", "\tprotected override updateLabel(e?: ITerminalInstance): void {\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalView.ts", "type": "replace", "edit_start_line_idx": 384 }
<svg width="14px" height="14px" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <rect fill="#682079" x="0" y="0" width="100" height="100" rx="35" ry="35"/> <text x="50" y="75" font-size="75" text-anchor="middle" style="font-family: Menlo, Monaco, Consolas, &quot;Droid Sans Mono&quot;, &quot;Inconsolata&quot;, &quot;Courier New&quot;, monospace, &quot;Droid Sans Fallback&quot;;" fill="white"> C </text> </svg>
extensions/git/resources/icons/light/status-copied.svg
0
https://github.com/microsoft/vscode/commit/626c64bc9a48591e226edd3c04a4bef9e886828e
[ 0.0001735649857437238, 0.0001735649857437238, 0.0001735649857437238, 0.0001735649857437238, 0 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\toverride updateLabel(e?: ITerminalInstance): void {\n", "\t\t// Only update if it's the active instance\n", "\t\tif (e && e !== this._terminalGroupService.activeInstance) {\n", "\t\t\treturn;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t// eslint-disable-next-line @typescript-eslint/naming-convention\n", "\tprotected override updateLabel(e?: ITerminalInstance): void {\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalView.ts", "type": "replace", "edit_start_line_idx": 384 }
{ "name": "vscode-automation", "version": "1.71.0", "description": "VS Code UI automation driver", "author": { "name": "Microsoft Corporation" }, "license": "MIT", "main": "./out/index.js", "private": true, "scripts": { "compile": "npm run copy-driver-definition && node ../../node_modules/typescript/bin/tsc", "watch": "npm-run-all -lp watch-driver-definition watch-tsc", "watch-tsc": "node ../../node_modules/typescript/bin/tsc --watch --preserveWatchOutput", "copy-driver-definition": "node tools/copy-driver-definition.js", "watch-driver-definition": "watch \"node tools/copy-driver-definition.js\"", "copy-package-version": "node tools/copy-package-version.js", "prepublishOnly": "npm run copy-package-version" }, "dependencies": { "mkdirp": "^1.0.4", "ncp": "^2.0.0", "tmp": "0.2.1", "tree-kill": "1.2.2", "vscode-uri": "3.0.2" }, "devDependencies": { "@types/mkdirp": "^1.0.1", "@types/ncp": "2.0.1", "@types/node": "16.x", "@types/tmp": "0.2.2", "cpx2": "3.0.0", "npm-run-all": "^4.1.5", "watch": "^1.0.2" } }
test/automation/package.json
0
https://github.com/microsoft/vscode/commit/626c64bc9a48591e226edd3c04a4bef9e886828e
[ 0.00017700891476124525, 0.00017364883387926966, 0.0001712885859888047, 0.00017314890283159912, 0.0000022051417545299046 ]
{ "id": 0, "code_window": [ "import {EntryPointBundle} from '../packages/entry_point_bundle';\n", "import {FileToWrite} from '../rendering/utils';\n", "import {FileWriter} from './file_writer';\n", "\n", "/**\n", " * This FileWriter overwrites the transformed file, in-place, while creating\n", " * a back-up of the original file with an extra `.__ivy_ngcc_bak` extension.\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export const NGCC_BACKUP_EXTENSION = '.__ivy_ngcc_bak';\n" ], "file_path": "packages/compiler-cli/ngcc/src/writing/in_place_file_writer.ts", "type": "add", "edit_start_line_idx": 14 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {FileSystem, absoluteFrom, dirname} from '../../../src/ngtsc/file_system'; import {EntryPointJsonProperty} from '../packages/entry_point'; import {EntryPointBundle} from '../packages/entry_point_bundle'; import {FileToWrite} from '../rendering/utils'; import {FileWriter} from './file_writer'; /** * This FileWriter overwrites the transformed file, in-place, while creating * a back-up of the original file with an extra `.__ivy_ngcc_bak` extension. */ export class InPlaceFileWriter implements FileWriter { constructor(protected fs: FileSystem) {} writeBundle( _bundle: EntryPointBundle, transformedFiles: FileToWrite[], _formatProperties?: EntryPointJsonProperty[]) { transformedFiles.forEach(file => this.writeFileAndBackup(file)); } protected writeFileAndBackup(file: FileToWrite): void { this.fs.ensureDir(dirname(file.path)); const backPath = absoluteFrom(`${file.path}.__ivy_ngcc_bak`); if (this.fs.exists(backPath)) { throw new Error( `Tried to overwrite ${backPath} with an ngcc back up file, which is disallowed.`); } if (this.fs.exists(file.path)) { this.fs.moveFile(file.path, backPath); } this.fs.writeFile(file.path, file.contents); } }
packages/compiler-cli/ngcc/src/writing/in_place_file_writer.ts
1
https://github.com/angular/angular/commit/16e15f50d2e7769c153f3e6cf07f57e2dc8054c5
[ 0.03559895232319832, 0.007330858148634434, 0.00018186944362241775, 0.00019410003733355552, 0.014134553261101246 ]
{ "id": 0, "code_window": [ "import {EntryPointBundle} from '../packages/entry_point_bundle';\n", "import {FileToWrite} from '../rendering/utils';\n", "import {FileWriter} from './file_writer';\n", "\n", "/**\n", " * This FileWriter overwrites the transformed file, in-place, while creating\n", " * a back-up of the original file with an extra `.__ivy_ngcc_bak` extension.\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export const NGCC_BACKUP_EXTENSION = '.__ivy_ngcc_bak';\n" ], "file_path": "packages/compiler-cli/ngcc/src/writing/in_place_file_writer.ts", "type": "add", "edit_start_line_idx": 14 }
import { AfterViewInit, Component, ElementRef, OnDestroy, OnInit, QueryList, ViewChildren } from '@angular/core'; import { asapScheduler, combineLatest, Subject } from 'rxjs'; import { startWith, subscribeOn, takeUntil } from 'rxjs/operators'; import { ScrollService } from 'app/shared/scroll.service'; import { TocItem, TocService } from 'app/shared/toc.service'; type TocType = 'None' | 'Floating' | 'EmbeddedSimple' | 'EmbeddedExpandable'; @Component({ selector: 'aio-toc', templateUrl: 'toc.component.html', styles: [] }) export class TocComponent implements OnInit, AfterViewInit, OnDestroy { activeIndex: number | null = null; type: TocType = 'None'; isCollapsed = true; isEmbedded = false; @ViewChildren('tocItem') private items: QueryList<ElementRef>; private onDestroy = new Subject(); primaryMax = 4; tocList: TocItem[]; constructor( private scrollService: ScrollService, elementRef: ElementRef, private tocService: TocService) { this.isEmbedded = elementRef.nativeElement.className.indexOf('embedded') !== -1; } ngOnInit() { this.tocService.tocList .pipe(takeUntil(this.onDestroy)) .subscribe(tocList => { this.tocList = tocList; const itemCount = count(this.tocList, item => item.level !== 'h1'); this.type = (itemCount > 0) ? this.isEmbedded ? (itemCount > this.primaryMax) ? 'EmbeddedExpandable' : 'EmbeddedSimple' : 'Floating' : 'None'; }); } ngAfterViewInit() { if (!this.isEmbedded) { // We use the `asap` scheduler because updates to `activeItemIndex` are triggered by DOM changes, // which, in turn, are caused by the rendering that happened due to a ChangeDetection. // Without asap, we would be updating the model while still in a ChangeDetection handler, which is disallowed by Angular. combineLatest([ this.tocService.activeItemIndex.pipe(subscribeOn(asapScheduler)), this.items.changes.pipe(startWith(this.items)), ]) .pipe(takeUntil(this.onDestroy)) .subscribe(([index, items]) => { this.activeIndex = index; if (index === null || index >= items.length) { return; } const e = items.toArray()[index].nativeElement; const p = e.offsetParent; const eRect = e.getBoundingClientRect(); const pRect = p.getBoundingClientRect(); const isInViewport = (eRect.top >= pRect.top) && (eRect.bottom <= pRect.bottom); if (!isInViewport) { p.scrollTop += (eRect.top - pRect.top) - (p.clientHeight / 2); } }); } } ngOnDestroy() { this.onDestroy.next(); } toggle(canScroll = true) { this.isCollapsed = !this.isCollapsed; if (canScroll && this.isCollapsed) { this.toTop(); } } toTop() { this.scrollService.scrollToTop(); } } function count<T>(array: T[], fn: (item: T) => boolean) { return array.reduce((result, item) => fn(item) ? result + 1 : result, 0); }
aio/src/app/custom-elements/toc/toc.component.ts
0
https://github.com/angular/angular/commit/16e15f50d2e7769c153f3e6cf07f57e2dc8054c5
[ 0.0001709472417132929, 0.00016773938841652125, 0.00016495908494107425, 0.00016772141680121422, 0.0000015136452020669822 ]
{ "id": 0, "code_window": [ "import {EntryPointBundle} from '../packages/entry_point_bundle';\n", "import {FileToWrite} from '../rendering/utils';\n", "import {FileWriter} from './file_writer';\n", "\n", "/**\n", " * This FileWriter overwrites the transformed file, in-place, while creating\n", " * a back-up of the original file with an extra `.__ivy_ngcc_bak` extension.\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export const NGCC_BACKUP_EXTENSION = '.__ivy_ngcc_bak';\n" ], "file_path": "packages/compiler-cli/ngcc/src/writing/in_place_file_writer.ts", "type": "add", "edit_start_line_idx": 14 }
// #docplaster // #docregion import { Injectable } from '@angular/core'; // #docregion import-httpclient import { HttpClient, HttpHeaders } from '@angular/common/http'; // #enddocregion import-httpclient import { Observable, of } from 'rxjs'; // #docregion import-rxjs-operators import { catchError, map, tap } from 'rxjs/operators'; // #enddocregion import-rxjs-operators import { Hero } from './hero'; import { MessageService } from './message.service'; @Injectable({ providedIn: 'root' }) export class HeroService { // #docregion heroesUrl private heroesUrl = 'api/heroes'; // URL to web api // #enddocregion heroesUrl // #docregion http-options httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; // #enddocregion http-options // #docregion ctor constructor( private http: HttpClient, private messageService: MessageService) { } // #enddocregion ctor // #docregion getHeroes, getHeroes-1 /** GET heroes from the server */ // #docregion getHeroes-2 getHeroes (): Observable<Hero[]> { return this.http.get<Hero[]>(this.heroesUrl) // #enddocregion getHeroes-1 .pipe( // #enddocregion getHeroes-2 tap(_ => this.log('fetched heroes')), // #docregion getHeroes-2 catchError(this.handleError<Hero[]>('getHeroes', [])) ); // #docregion getHeroes-1 } // #enddocregion getHeroes, getHeroes-1, getHeroes-2 // #docregion getHeroNo404 /** GET hero by id. Return `undefined` when id not found */ getHeroNo404<Data>(id: number): Observable<Hero> { const url = `${this.heroesUrl}/?id=${id}`; return this.http.get<Hero[]>(url) .pipe( map(heroes => heroes[0]), // returns a {0|1} element array // #enddocregion getHeroNo404 tap(h => { const outcome = h ? `fetched` : `did not find`; this.log(`${outcome} hero id=${id}`); }), catchError(this.handleError<Hero>(`getHero id=${id}`)) // #docregion getHeroNo404 ); } // #enddocregion getHeroNo404 // #docregion getHero /** GET hero by id. Will 404 if id not found */ getHero(id: number): Observable<Hero> { const url = `${this.heroesUrl}/${id}`; return this.http.get<Hero>(url).pipe( tap(_ => this.log(`fetched hero id=${id}`)), catchError(this.handleError<Hero>(`getHero id=${id}`)) ); } // #enddocregion getHero // #docregion searchHeroes /* GET heroes whose name contains search term */ searchHeroes(term: string): Observable<Hero[]> { if (!term.trim()) { // if not search term, return empty hero array. return of([]); } return this.http.get<Hero[]>(`${this.heroesUrl}/?name=${term}`).pipe( tap(x => x.length ? this.log(`found heroes matching "${term}"`) : this.log(`no heroes matching "${term}"`)), catchError(this.handleError<Hero[]>('searchHeroes', [])) ); } // #enddocregion searchHeroes //////// Save methods ////////// // #docregion addHero /** POST: add a new hero to the server */ addHero (hero: Hero): Observable<Hero> { return this.http.post<Hero>(this.heroesUrl, hero, this.httpOptions).pipe( tap((newHero: Hero) => this.log(`added hero w/ id=${newHero.id}`)), catchError(this.handleError<Hero>('addHero')) ); } // #enddocregion addHero // #docregion deleteHero /** DELETE: delete the hero from the server */ deleteHero (hero: Hero | number): Observable<Hero> { const id = typeof hero === 'number' ? hero : hero.id; const url = `${this.heroesUrl}/${id}`; return this.http.delete<Hero>(url, this.httpOptions).pipe( tap(_ => this.log(`deleted hero id=${id}`)), catchError(this.handleError<Hero>('deleteHero')) ); } // #enddocregion deleteHero // #docregion updateHero /** PUT: update the hero on the server */ updateHero (hero: Hero): Observable<any> { return this.http.put(this.heroesUrl, hero, this.httpOptions).pipe( tap(_ => this.log(`updated hero id=${hero.id}`)), catchError(this.handleError<any>('updateHero')) ); } // #enddocregion updateHero // #docregion handleError /** * Handle Http operation that failed. * Let the app continue. * @param operation - name of the operation that failed * @param result - optional value to return as the observable result */ private handleError<T> (operation = 'operation', result?: T) { return (error: any): Observable<T> => { // TODO: send the error to remote logging infrastructure console.error(error); // log to console instead // TODO: better job of transforming error for user consumption this.log(`${operation} failed: ${error.message}`); // Let the app keep running by returning an empty result. return of(result as T); }; } // #enddocregion handleError // #docregion log /** Log a HeroService message with the MessageService */ private log(message: string) { this.messageService.add(`HeroService: ${message}`); } // #enddocregion log }
aio/content/examples/toh-pt6/src/app/hero.service.ts
0
https://github.com/angular/angular/commit/16e15f50d2e7769c153f3e6cf07f57e2dc8054c5
[ 0.00018401462875772268, 0.00017024796397890896, 0.00016620874521322548, 0.00016966454859357327, 0.0000038135017348395195 ]
{ "id": 0, "code_window": [ "import {EntryPointBundle} from '../packages/entry_point_bundle';\n", "import {FileToWrite} from '../rendering/utils';\n", "import {FileWriter} from './file_writer';\n", "\n", "/**\n", " * This FileWriter overwrites the transformed file, in-place, while creating\n", " * a back-up of the original file with an extra `.__ivy_ngcc_bak` extension.\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export const NGCC_BACKUP_EXTENSION = '.__ivy_ngcc_bak';\n" ], "file_path": "packages/compiler-cli/ngcc/src/writing/in_place_file_writer.ts", "type": "add", "edit_start_line_idx": 14 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.common || {}; global.ng.common.locales = global.ng.common.locales || {}; const u = undefined; function plural(n) { let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length; if (i === 1 && v === 0) return 1; return 5; } global.ng.common.locales['en'] = [ 'en', [['a', 'p'], ['AM', 'PM'], u], [['AM', 'PM'], u, u], [ ['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'] ], u, [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] ], u, [['B', 'A'], ['BC', 'AD'], ['Before Christ', 'Anno Domini']], 0, [6, 0], ['M/d/yy', 'MMM d, y', 'MMMM d, y', 'EEEE, MMMM d, y'], ['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'], ['{1}, {0}', u, '{1} \'at\' {0}', u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], 'USD', '$', 'US Dollar', {}, 'ltr', plural, [ [ ['mi', 'n', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], ['midnight', 'noon', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], u ], [['midnight', 'noon', 'morning', 'afternoon', 'evening', 'night'], u, u], [ '00:00', '12:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '21:00'], ['21:00', '06:00'] ] ] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
packages/common/locales/global/en.js
0
https://github.com/angular/angular/commit/16e15f50d2e7769c153f3e6cf07f57e2dc8054c5
[ 0.00017004157416522503, 0.0001672841317486018, 0.0001644522708375007, 0.00016720828716643155, 0.0000017232337086170446 ]
{ "id": 1, "code_window": [ "\n", " protected writeFileAndBackup(file: FileToWrite): void {\n", " this.fs.ensureDir(dirname(file.path));\n", " const backPath = absoluteFrom(`${file.path}.__ivy_ngcc_bak`);\n", " if (this.fs.exists(backPath)) {\n", " throw new Error(\n", " `Tried to overwrite ${backPath} with an ngcc back up file, which is disallowed.`);\n", " }\n", " if (this.fs.exists(file.path)) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const backPath = absoluteFrom(`${file.path}${NGCC_BACKUP_EXTENSION}`);\n" ], "file_path": "packages/compiler-cli/ngcc/src/writing/in_place_file_writer.ts", "type": "replace", "edit_start_line_idx": 29 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {FileSystem, absoluteFrom, dirname} from '../../../src/ngtsc/file_system'; import {EntryPointJsonProperty} from '../packages/entry_point'; import {EntryPointBundle} from '../packages/entry_point_bundle'; import {FileToWrite} from '../rendering/utils'; import {FileWriter} from './file_writer'; /** * This FileWriter overwrites the transformed file, in-place, while creating * a back-up of the original file with an extra `.__ivy_ngcc_bak` extension. */ export class InPlaceFileWriter implements FileWriter { constructor(protected fs: FileSystem) {} writeBundle( _bundle: EntryPointBundle, transformedFiles: FileToWrite[], _formatProperties?: EntryPointJsonProperty[]) { transformedFiles.forEach(file => this.writeFileAndBackup(file)); } protected writeFileAndBackup(file: FileToWrite): void { this.fs.ensureDir(dirname(file.path)); const backPath = absoluteFrom(`${file.path}.__ivy_ngcc_bak`); if (this.fs.exists(backPath)) { throw new Error( `Tried to overwrite ${backPath} with an ngcc back up file, which is disallowed.`); } if (this.fs.exists(file.path)) { this.fs.moveFile(file.path, backPath); } this.fs.writeFile(file.path, file.contents); } }
packages/compiler-cli/ngcc/src/writing/in_place_file_writer.ts
1
https://github.com/angular/angular/commit/16e15f50d2e7769c153f3e6cf07f57e2dc8054c5
[ 0.9982648491859436, 0.4019804894924164, 0.000166782017913647, 0.013105891644954681, 0.48684725165367126 ]
{ "id": 1, "code_window": [ "\n", " protected writeFileAndBackup(file: FileToWrite): void {\n", " this.fs.ensureDir(dirname(file.path));\n", " const backPath = absoluteFrom(`${file.path}.__ivy_ngcc_bak`);\n", " if (this.fs.exists(backPath)) {\n", " throw new Error(\n", " `Tried to overwrite ${backPath} with an ngcc back up file, which is disallowed.`);\n", " }\n", " if (this.fs.exists(file.path)) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const backPath = absoluteFrom(`${file.path}${NGCC_BACKUP_EXTENSION}`);\n" ], "file_path": "packages/compiler-cli/ngcc/src/writing/in_place_file_writer.ts", "type": "replace", "edit_start_line_idx": 29 }
<div class="section"> <h2>@Self() Component</h2> <p>Flower emoji: {{flower?.emoji}}</p> </div>
aio/content/examples/resolution-modifiers/src/app/self/self.component.html
0
https://github.com/angular/angular/commit/16e15f50d2e7769c153f3e6cf07f57e2dc8054c5
[ 0.00017155043315142393, 0.00017155043315142393, 0.00017155043315142393, 0.00017155043315142393, 0 ]
{ "id": 1, "code_window": [ "\n", " protected writeFileAndBackup(file: FileToWrite): void {\n", " this.fs.ensureDir(dirname(file.path));\n", " const backPath = absoluteFrom(`${file.path}.__ivy_ngcc_bak`);\n", " if (this.fs.exists(backPath)) {\n", " throw new Error(\n", " `Tried to overwrite ${backPath} with an ngcc back up file, which is disallowed.`);\n", " }\n", " if (this.fs.exists(file.path)) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const backPath = absoluteFrom(`${file.path}${NGCC_BACKUP_EXTENSION}`);\n" ], "file_path": "packages/compiler-cli/ngcc/src/writing/in_place_file_writer.ts", "type": "replace", "edit_start_line_idx": 29 }
// #docplaster // #docregion import { AfterViewChecked, AfterViewInit, Component, ViewChild } from '@angular/core'; import { LoggerService } from './logger.service'; ////////////////// // #docregion child-view @Component({ selector: 'app-child-view', template: '<input [(ngModel)]="hero">' }) export class ChildViewComponent { hero = 'Magneta'; } // #enddocregion child-view ////////////////////// @Component({ selector: 'after-view', // #docregion template template: ` <div>-- child view begins --</div> <app-child-view></app-child-view> <div>-- child view ends --</div>` // #enddocregion template + ` <p *ngIf="comment" class="comment"> {{comment}} </p> ` }) // #docregion hooks export class AfterViewComponent implements AfterViewChecked, AfterViewInit { private prevHero = ''; // Query for a VIEW child of type `ChildViewComponent` @ViewChild(ChildViewComponent) viewChild: ChildViewComponent; // #enddocregion hooks constructor(private logger: LoggerService) { this.logIt('AfterView constructor'); } // #docregion hooks ngAfterViewInit() { // viewChild is set after the view has been initialized this.logIt('AfterViewInit'); this.doSomething(); } ngAfterViewChecked() { // viewChild is updated after the view has been checked if (this.prevHero === this.viewChild.hero) { this.logIt('AfterViewChecked (no change)'); } else { this.prevHero = this.viewChild.hero; this.logIt('AfterViewChecked'); this.doSomething(); } } // #enddocregion hooks comment = ''; // #docregion do-something // This surrogate for real business logic sets the `comment` private doSomething() { let c = this.viewChild.hero.length > 10 ? `That's a long name` : ''; if (c !== this.comment) { // Wait a tick because the component's view has already been checked this.logger.tick_then(() => this.comment = c); } } // #enddocregion do-something private logIt(method: string) { let child = this.viewChild; let message = `${method}: ${child ? child.hero : 'no'} child view`; this.logger.log(message); } // #docregion hooks // ... } // #enddocregion hooks ////////////// @Component({ selector: 'after-view-parent', template: ` <div class="parent"> <h2>AfterView</h2> <after-view *ngIf="show"></after-view> <h4>-- AfterView Logs --</h4> <p><button (click)="reset()">Reset</button></p> <div *ngFor="let msg of logger.logs">{{msg}}</div> </div> `, styles: ['.parent {background: burlywood}'], providers: [LoggerService] }) export class AfterViewParentComponent { show = true; constructor(public logger: LoggerService) { } reset() { this.logger.clear(); // quickly remove and reload AfterViewComponent which recreates it this.show = false; this.logger.tick_then(() => this.show = true); } }
aio/content/examples/lifecycle-hooks/src/app/after-view.component.ts
0
https://github.com/angular/angular/commit/16e15f50d2e7769c153f3e6cf07f57e2dc8054c5
[ 0.00017405455582775176, 0.00017140137788373977, 0.00016798397700767964, 0.00017164077144116163, 0.0000019596809579525143 ]
{ "id": 1, "code_window": [ "\n", " protected writeFileAndBackup(file: FileToWrite): void {\n", " this.fs.ensureDir(dirname(file.path));\n", " const backPath = absoluteFrom(`${file.path}.__ivy_ngcc_bak`);\n", " if (this.fs.exists(backPath)) {\n", " throw new Error(\n", " `Tried to overwrite ${backPath} with an ngcc back up file, which is disallowed.`);\n", " }\n", " if (this.fs.exists(file.path)) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const backPath = absoluteFrom(`${file.path}${NGCC_BACKUP_EXTENSION}`);\n" ], "file_path": "packages/compiler-cli/ngcc/src/writing/in_place_file_writer.ts", "type": "replace", "edit_start_line_idx": 29 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; function plural(n: number): number { if (n === 0) return 0; if (n === 1) return 1; if (n === 2) return 2; if (n % 100 === Math.floor(n % 100) && n % 100 >= 3 && n % 100 <= 10) return 3; if (n % 100 === Math.floor(n % 100) && n % 100 >= 11 && n % 100 <= 99) return 4; return 5; } export default [ 'ar-ER', [['ص', 'م'], u, u], [['ص', 'م'], u, ['صباحًا', 'مساءً']], [ ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], [ 'الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت' ], u, ['أحد', 'إثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة', 'سبت'] ], u, [ ['ي', 'ف', 'م', 'أ', 'و', 'ن', 'ل', 'غ', 'س', 'ك', 'ب', 'د'], [ 'يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر' ], u ], u, [['ق.م', 'م'], u, ['قبل الميلاد', 'ميلادي']], 1, [6, 0], ['d\u200f/M\u200f/y', 'dd\u200f/MM\u200f/y', 'd MMMM y', 'EEEE، d MMMM y'], ['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'], ['{1} {0}', u, u, u], [ '.', ',', ';', '\u200e%\u200e', '\u200e+', '\u200e-', 'E', '×', '‰', '∞', 'ليس رقمًا', ':' ], ['#,##0.###', '#,##0%', '¤ #,##0.00', '#E0'], 'ERN', 'Nfk', 'ناكفا أريتري', { 'AED': ['د.إ.\u200f'], 'ARS': [u, 'AR$'], 'AUD': ['AU$'], 'BBD': [u, 'BB$'], 'BHD': ['د.ب.\u200f'], 'BMD': [u, 'BM$'], 'BND': [u, 'BN$'], 'BSD': [u, 'BS$'], 'BZD': [u, 'BZ$'], 'CAD': ['CA$'], 'CLP': [u, 'CL$'], 'CNY': ['CN¥'], 'COP': [u, 'CO$'], 'CUP': [u, 'CU$'], 'DOP': [u, 'DO$'], 'DZD': ['د.ج.\u200f'], 'EGP': ['ج.م.\u200f', 'E£'], 'ERN': ['Nfk'], 'FJD': [u, 'FJ$'], 'GBP': ['UK£'], 'GYD': [u, 'GY$'], 'HKD': ['HK$'], 'IQD': ['د.ع.\u200f'], 'IRR': ['ر.إ.'], 'JMD': [u, 'JM$'], 'JOD': ['د.أ.\u200f'], 'JPY': ['JP¥'], 'KWD': ['د.ك.\u200f'], 'KYD': [u, 'KY$'], 'LBP': ['ل.ل.\u200f', 'L£'], 'LRD': [u, '$LR'], 'LYD': ['د.ل.\u200f'], 'MAD': ['د.م.\u200f'], 'MRU': ['أ.م.'], 'MXN': ['MX$'], 'NZD': ['NZ$'], 'OMR': ['ر.ع.\u200f'], 'QAR': ['ر.ق.\u200f'], 'SAR': ['ر.س.\u200f'], 'SBD': [u, 'SB$'], 'SDD': ['د.س.\u200f'], 'SDG': ['ج.س.'], 'SRD': [u, 'SR$'], 'SYP': ['ل.س.\u200f', '£'], 'THB': ['฿'], 'TND': ['د.ت.\u200f'], 'TTD': [u, 'TT$'], 'TWD': ['NT$'], 'USD': ['US$'], 'UYU': [u, 'UY$'], 'XXX': ['***'], 'YER': ['ر.ي.\u200f'] }, 'rtl', plural ];
packages/common/locales/ar-ER.ts
0
https://github.com/angular/angular/commit/16e15f50d2e7769c153f3e6cf07f57e2dc8054c5
[ 0.00019427409279160202, 0.00017236782878171653, 0.00016554239846300334, 0.00017100106924772263, 0.000006966999990254408 ]
{ "id": 2, "code_window": [ "\n", "import {InPlaceFileWriter} from './in_place_file_writer';\n", "import {PackageJsonUpdater} from './package_json_updater';\n", "\n", "const NGCC_DIRECTORY = '__ivy_ngcc__';\n", "\n", "/**\n", " * This FileWriter creates a copy of the original entry-point, then writes the transformed\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export const NGCC_DIRECTORY = '__ivy_ngcc__';\n", "export const NGCC_PROPERTY_EXTENSION = '_ivy_ngcc';\n" ], "file_path": "packages/compiler-cli/ngcc/src/writing/new_entry_point_file_writer.ts", "type": "replace", "edit_start_line_idx": 17 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {AbsoluteFsPath, FileSystem, absoluteFromSourceFile, dirname, join, relative} from '../../../src/ngtsc/file_system'; import {isDtsPath} from '../../../src/ngtsc/util/src/typescript'; import {EntryPoint, EntryPointJsonProperty} from '../packages/entry_point'; import {EntryPointBundle} from '../packages/entry_point_bundle'; import {FileToWrite} from '../rendering/utils'; import {InPlaceFileWriter} from './in_place_file_writer'; import {PackageJsonUpdater} from './package_json_updater'; const NGCC_DIRECTORY = '__ivy_ngcc__'; /** * This FileWriter creates a copy of the original entry-point, then writes the transformed * files onto the files in this copy, and finally updates the package.json with a new * entry-point format property that points to this new entry-point. * * If there are transformed typings files in this bundle, they are updated in-place (see the * `InPlaceFileWriter`). */ export class NewEntryPointFileWriter extends InPlaceFileWriter { constructor(fs: FileSystem, private pkgJsonUpdater: PackageJsonUpdater) { super(fs); } writeBundle( bundle: EntryPointBundle, transformedFiles: FileToWrite[], formatProperties: EntryPointJsonProperty[]) { // The new folder is at the root of the overall package const entryPoint = bundle.entryPoint; const ngccFolder = join(entryPoint.package, NGCC_DIRECTORY); this.copyBundle(bundle, entryPoint.package, ngccFolder); transformedFiles.forEach(file => this.writeFile(file, entryPoint.package, ngccFolder)); this.updatePackageJson(entryPoint, formatProperties, ngccFolder); } protected copyBundle( bundle: EntryPointBundle, packagePath: AbsoluteFsPath, ngccFolder: AbsoluteFsPath) { bundle.src.program.getSourceFiles().forEach(sourceFile => { const relativePath = relative(packagePath, absoluteFromSourceFile(sourceFile)); const isOutsidePackage = relativePath.startsWith('..'); if (!sourceFile.isDeclarationFile && !isOutsidePackage) { const newFilePath = join(ngccFolder, relativePath); this.fs.ensureDir(dirname(newFilePath)); this.fs.copyFile(absoluteFromSourceFile(sourceFile), newFilePath); } }); } protected writeFile(file: FileToWrite, packagePath: AbsoluteFsPath, ngccFolder: AbsoluteFsPath): void { if (isDtsPath(file.path.replace(/\.map$/, ''))) { // This is either `.d.ts` or `.d.ts.map` file super.writeFileAndBackup(file); } else { const relativePath = relative(packagePath, file.path); const newFilePath = join(ngccFolder, relativePath); this.fs.ensureDir(dirname(newFilePath)); this.fs.writeFile(newFilePath, file.contents); } } protected updatePackageJson( entryPoint: EntryPoint, formatProperties: EntryPointJsonProperty[], ngccFolder: AbsoluteFsPath) { if (formatProperties.length === 0) { // No format properties need updating. return; } const packageJson = entryPoint.packageJson; const packageJsonPath = join(entryPoint.path, 'package.json'); // All format properties point to the same format-path. const oldFormatProp = formatProperties[0] !; const oldFormatPath = packageJson[oldFormatProp] !; const oldAbsFormatPath = join(entryPoint.path, oldFormatPath); const newAbsFormatPath = join(ngccFolder, relative(entryPoint.package, oldAbsFormatPath)); const newFormatPath = relative(entryPoint.path, newAbsFormatPath); // Update all properties in `package.json` (both in memory and on disk). const update = this.pkgJsonUpdater.createUpdate(); for (const formatProperty of formatProperties) { if (packageJson[formatProperty] !== oldFormatPath) { throw new Error( `Unable to update '${packageJsonPath}': Format properties ` + `(${formatProperties.join(', ')}) map to more than one format-path.`); } update.addChange([`${formatProperty}_ivy_ngcc`], newFormatPath, {before: formatProperty}); } update.writeChanges(packageJsonPath, packageJson); } }
packages/compiler-cli/ngcc/src/writing/new_entry_point_file_writer.ts
1
https://github.com/angular/angular/commit/16e15f50d2e7769c153f3e6cf07f57e2dc8054c5
[ 0.9991568326950073, 0.1822117269039154, 0.00016507803229615092, 0.00028259336249902844, 0.3849550187587738 ]
{ "id": 2, "code_window": [ "\n", "import {InPlaceFileWriter} from './in_place_file_writer';\n", "import {PackageJsonUpdater} from './package_json_updater';\n", "\n", "const NGCC_DIRECTORY = '__ivy_ngcc__';\n", "\n", "/**\n", " * This FileWriter creates a copy of the original entry-point, then writes the transformed\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export const NGCC_DIRECTORY = '__ivy_ngcc__';\n", "export const NGCC_PROPERTY_EXTENSION = '_ivy_ngcc';\n" ], "file_path": "packages/compiler-cli/ngcc/src/writing/new_entry_point_file_writer.ts", "type": "replace", "edit_start_line_idx": 17 }
// #docregion // #docregion example /* avoid */ import { ExceptionService, SpinnerService, ToastService } from '../../core'; import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Hero } from './hero.model'; // #enddocregion example @Injectable() export class HeroService { constructor( private exceptionService: ExceptionService, private spinnerService: SpinnerService, private toastService: ToastService, private http: HttpClient ) { } getHero(id: number) { return this.http.get<Hero>(`api/heroes/${id}`); } getHeroes() { return this.http.get<Hero[]>(`api/heroes`); } }
aio/content/examples/styleguide/src/03-06/app/heroes/shared/hero.service.avoid.ts
0
https://github.com/angular/angular/commit/16e15f50d2e7769c153f3e6cf07f57e2dc8054c5
[ 0.00017437248607166111, 0.00017204573669005185, 0.0001694777893135324, 0.00017228694923687726, 0.000002005517444558791 ]
{ "id": 2, "code_window": [ "\n", "import {InPlaceFileWriter} from './in_place_file_writer';\n", "import {PackageJsonUpdater} from './package_json_updater';\n", "\n", "const NGCC_DIRECTORY = '__ivy_ngcc__';\n", "\n", "/**\n", " * This FileWriter creates a copy of the original entry-point, then writes the transformed\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export const NGCC_DIRECTORY = '__ivy_ngcc__';\n", "export const NGCC_PROPERTY_EXTENSION = '_ivy_ngcc';\n" ], "file_path": "packages/compiler-cli/ngcc/src/writing/new_entry_point_file_writer.ts", "type": "replace", "edit_start_line_idx": 17 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // This file is not used to build this module. It is only used during editing // by the TypeScript language service and during build for verification. `ngc` // replaces this file with production index.ts when it rewrites private symbol // names. export * from './public_api';
packages/compiler/testing/index.ts
0
https://github.com/angular/angular/commit/16e15f50d2e7769c153f3e6cf07f57e2dc8054c5
[ 0.00017110117187257856, 0.00016852517728693783, 0.00016594919725321233, 0.00016852517728693783, 0.0000025759873096831143 ]
{ "id": 2, "code_window": [ "\n", "import {InPlaceFileWriter} from './in_place_file_writer';\n", "import {PackageJsonUpdater} from './package_json_updater';\n", "\n", "const NGCC_DIRECTORY = '__ivy_ngcc__';\n", "\n", "/**\n", " * This FileWriter creates a copy of the original entry-point, then writes the transformed\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export const NGCC_DIRECTORY = '__ivy_ngcc__';\n", "export const NGCC_PROPERTY_EXTENSION = '_ivy_ngcc';\n" ], "file_path": "packages/compiler-cli/ngcc/src/writing/new_entry_point_file_writer.ts", "type": "replace", "edit_start_line_idx": 17 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; export default [];
packages/common/locales/extra/ff.ts
0
https://github.com/angular/angular/commit/16e15f50d2e7769c153f3e6cf07f57e2dc8054c5
[ 0.0002136456168955192, 0.00019169544975738972, 0.00016974528261926025, 0.00019169544975738972, 0.000021950167138129473 ]
{ "id": 3, "code_window": [ " `Unable to update '${packageJsonPath}': Format properties ` +\n", " `(${formatProperties.join(', ')}) map to more than one format-path.`);\n", " }\n", "\n", " update.addChange([`${formatProperty}_ivy_ngcc`], newFormatPath, {before: formatProperty});\n", " }\n", "\n", " update.writeChanges(packageJsonPath, packageJson);\n", " }\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " update.addChange(\n", " [`${formatProperty}${NGCC_PROPERTY_EXTENSION}`], newFormatPath, {before: formatProperty});\n" ], "file_path": "packages/compiler-cli/ngcc/src/writing/new_entry_point_file_writer.ts", "type": "replace", "edit_start_line_idx": 95 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {AbsoluteFsPath, FileSystem, absoluteFromSourceFile, dirname, join, relative} from '../../../src/ngtsc/file_system'; import {isDtsPath} from '../../../src/ngtsc/util/src/typescript'; import {EntryPoint, EntryPointJsonProperty} from '../packages/entry_point'; import {EntryPointBundle} from '../packages/entry_point_bundle'; import {FileToWrite} from '../rendering/utils'; import {InPlaceFileWriter} from './in_place_file_writer'; import {PackageJsonUpdater} from './package_json_updater'; const NGCC_DIRECTORY = '__ivy_ngcc__'; /** * This FileWriter creates a copy of the original entry-point, then writes the transformed * files onto the files in this copy, and finally updates the package.json with a new * entry-point format property that points to this new entry-point. * * If there are transformed typings files in this bundle, they are updated in-place (see the * `InPlaceFileWriter`). */ export class NewEntryPointFileWriter extends InPlaceFileWriter { constructor(fs: FileSystem, private pkgJsonUpdater: PackageJsonUpdater) { super(fs); } writeBundle( bundle: EntryPointBundle, transformedFiles: FileToWrite[], formatProperties: EntryPointJsonProperty[]) { // The new folder is at the root of the overall package const entryPoint = bundle.entryPoint; const ngccFolder = join(entryPoint.package, NGCC_DIRECTORY); this.copyBundle(bundle, entryPoint.package, ngccFolder); transformedFiles.forEach(file => this.writeFile(file, entryPoint.package, ngccFolder)); this.updatePackageJson(entryPoint, formatProperties, ngccFolder); } protected copyBundle( bundle: EntryPointBundle, packagePath: AbsoluteFsPath, ngccFolder: AbsoluteFsPath) { bundle.src.program.getSourceFiles().forEach(sourceFile => { const relativePath = relative(packagePath, absoluteFromSourceFile(sourceFile)); const isOutsidePackage = relativePath.startsWith('..'); if (!sourceFile.isDeclarationFile && !isOutsidePackage) { const newFilePath = join(ngccFolder, relativePath); this.fs.ensureDir(dirname(newFilePath)); this.fs.copyFile(absoluteFromSourceFile(sourceFile), newFilePath); } }); } protected writeFile(file: FileToWrite, packagePath: AbsoluteFsPath, ngccFolder: AbsoluteFsPath): void { if (isDtsPath(file.path.replace(/\.map$/, ''))) { // This is either `.d.ts` or `.d.ts.map` file super.writeFileAndBackup(file); } else { const relativePath = relative(packagePath, file.path); const newFilePath = join(ngccFolder, relativePath); this.fs.ensureDir(dirname(newFilePath)); this.fs.writeFile(newFilePath, file.contents); } } protected updatePackageJson( entryPoint: EntryPoint, formatProperties: EntryPointJsonProperty[], ngccFolder: AbsoluteFsPath) { if (formatProperties.length === 0) { // No format properties need updating. return; } const packageJson = entryPoint.packageJson; const packageJsonPath = join(entryPoint.path, 'package.json'); // All format properties point to the same format-path. const oldFormatProp = formatProperties[0] !; const oldFormatPath = packageJson[oldFormatProp] !; const oldAbsFormatPath = join(entryPoint.path, oldFormatPath); const newAbsFormatPath = join(ngccFolder, relative(entryPoint.package, oldAbsFormatPath)); const newFormatPath = relative(entryPoint.path, newAbsFormatPath); // Update all properties in `package.json` (both in memory and on disk). const update = this.pkgJsonUpdater.createUpdate(); for (const formatProperty of formatProperties) { if (packageJson[formatProperty] !== oldFormatPath) { throw new Error( `Unable to update '${packageJsonPath}': Format properties ` + `(${formatProperties.join(', ')}) map to more than one format-path.`); } update.addChange([`${formatProperty}_ivy_ngcc`], newFormatPath, {before: formatProperty}); } update.writeChanges(packageJsonPath, packageJson); } }
packages/compiler-cli/ngcc/src/writing/new_entry_point_file_writer.ts
1
https://github.com/angular/angular/commit/16e15f50d2e7769c153f3e6cf07f57e2dc8054c5
[ 0.9962540864944458, 0.09196794778108597, 0.0001628621539566666, 0.00025961798382923007, 0.285973459482193 ]
{ "id": 3, "code_window": [ " `Unable to update '${packageJsonPath}': Format properties ` +\n", " `(${formatProperties.join(', ')}) map to more than one format-path.`);\n", " }\n", "\n", " update.addChange([`${formatProperty}_ivy_ngcc`], newFormatPath, {before: formatProperty});\n", " }\n", "\n", " update.writeChanges(packageJsonPath, packageJson);\n", " }\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " update.addChange(\n", " [`${formatProperty}${NGCC_PROPERTY_EXTENSION}`], newFormatPath, {before: formatProperty});\n" ], "file_path": "packages/compiler-cli/ngcc/src/writing/new_entry_point_file_writer.ts", "type": "replace", "edit_start_line_idx": 95 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; export default [];
packages/common/locales/extra/yav.ts
0
https://github.com/angular/angular/commit/16e15f50d2e7769c153f3e6cf07f57e2dc8054c5
[ 0.0001752761600073427, 0.00017424358520656824, 0.00017321102495770901, 0.00017424358520656824, 0.0000010325675248168409 ]