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": 2, "code_window": [ " }\n", "\n", " return (\n", " <div className={styles.wrapper}>\n", " <TabsBar className={styles.tabBar}>\n", " {tabs.map((tab) => {\n", " if (config.unifiedAlertingEnabled && tab.id === PanelEditorTabId.Alert) {\n", " return (\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <TabsBar className={styles.tabBar} hideBorder>\n" ], "file_path": "public/app/features/dashboard/components/PanelEditor/PanelEditorTabs.tsx", "type": "replace", "edit_start_line_idx": 40 }
blank_issues_enabled: false contact_links: - name: Feature Request url: https://github.com/grafana/grafana/discussions/new about: Discuss ideas for new features of changes - name: Questions & Help url: https://community.grafana.com about: Please ask and answer questions here.
.github/ISSUE_TEMPLATE/config.yml
0
https://github.com/grafana/grafana/commit/78ebac0116c0aebd99d261c3f138819dc957bece
[ 0.00017553288489580154, 0.00017553288489580154, 0.00017553288489580154, 0.00017553288489580154, 0 ]
{ "id": 2, "code_window": [ " }\n", "\n", " return (\n", " <div className={styles.wrapper}>\n", " <TabsBar className={styles.tabBar}>\n", " {tabs.map((tab) => {\n", " if (config.unifiedAlertingEnabled && tab.id === PanelEditorTabId.Alert) {\n", " return (\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <TabsBar className={styles.tabBar} hideBorder>\n" ], "file_path": "public/app/features/dashboard/components/PanelEditor/PanelEditorTabs.tsx", "type": "replace", "edit_start_line_idx": 40 }
// ========================================================================== // FILTER CONTROLS // ========================================================================== // Filters // -------------------------------------------------------------------------- .filter-controls-filters { display: inline-block; margin-bottom: 40px; } .tab-pane > .filter-controls-filters { margin-top: 20px; } // Actions // -------------------------------------------------------------------------- .filter-controls-actions { margin: 0 0 10px; padding: 0; list-style: none; } .filter-controls-actions > li { display: inline-block; margin-right: 10px; } .filter-controls-actions-selected { text-transform: uppercase; }
public/sass/components/_filter-controls.scss
0
https://github.com/grafana/grafana/commit/78ebac0116c0aebd99d261c3f138819dc957bece
[ 0.0001746520574670285, 0.0001712646771920845, 0.0001676629763096571, 0.00017137182294391096, 0.000002512603714421857 ]
{ "id": 3, "code_window": [ " display: flex;\n", " flex-direction: column;\n", " flex-grow: 1;\n", " min-height: 0;\n", " background: ${theme.colors.background.primary};\n", " border-right: 1px solid ${theme.components.panel.borderColor};\n", " `,\n", " };\n", "};" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " border: 1px solid ${theme.components.panel.borderColor};\n", " border-left: none;\n", " border-bottom: none;\n", " border-top-right-radius: ${theme.shape.borderRadius(1.5)};\n" ], "file_path": "public/app/features/dashboard/components/PanelEditor/PanelEditorTabs.tsx", "type": "replace", "edit_start_line_idx": 109 }
import React, { FC, useEffect } from 'react'; import { css } from '@emotion/css'; import { IconName, Tab, TabContent, TabsBar, useForceUpdate, useStyles2 } from '@grafana/ui'; import { TransformationsEditor } from '../TransformationsEditor/TransformationsEditor'; import { DashboardModel, PanelModel } from '../../state'; import { PanelEditorTab, PanelEditorTabId } from './types'; import { Subscription } from 'rxjs'; import { PanelQueriesChangedEvent, PanelTransformationsChangedEvent } from 'app/types/events'; import { PanelEditorQueries } from './PanelEditorQueries'; import { GrafanaTheme2 } from '@grafana/data'; import { config } from '@grafana/runtime'; import AlertTabIndex from 'app/features/alerting/AlertTabIndex'; import { PanelAlertTab } from 'app/features/alerting/unified/PanelAlertTab'; interface PanelEditorTabsProps { panel: PanelModel; dashboard: DashboardModel; tabs: PanelEditorTab[]; onChangeTab: (tab: PanelEditorTab) => void; } export const PanelEditorTabs: FC<PanelEditorTabsProps> = React.memo(({ panel, dashboard, tabs, onChangeTab }) => { const forceUpdate = useForceUpdate(); const styles = useStyles2(getStyles); useEffect(() => { const eventSubs = new Subscription(); eventSubs.add(panel.events.subscribe(PanelQueriesChangedEvent, forceUpdate)); eventSubs.add(panel.events.subscribe(PanelTransformationsChangedEvent, forceUpdate)); return () => eventSubs.unsubscribe(); }, [panel, forceUpdate]); const activeTab = tabs.find((item) => item.active)!; if (tabs.length === 0) { return null; } return ( <div className={styles.wrapper}> <TabsBar className={styles.tabBar}> {tabs.map((tab) => { if (config.unifiedAlertingEnabled && tab.id === PanelEditorTabId.Alert) { return ( <PanelAlertTab key={tab.id} label={tab.text} active={tab.active} onChangeTab={() => onChangeTab(tab)} icon={tab.icon as IconName} panel={panel} dashboard={dashboard} /> ); } return ( <Tab key={tab.id} label={tab.text} active={tab.active} onChangeTab={() => onChangeTab(tab)} icon={tab.icon as IconName} counter={getCounter(panel, tab)} /> ); })} </TabsBar> <TabContent className={styles.tabContent}> {activeTab.id === PanelEditorTabId.Query && <PanelEditorQueries panel={panel} queries={panel.targets} />} {activeTab.id === PanelEditorTabId.Alert && <AlertTabIndex panel={panel} dashboard={dashboard} />} {activeTab.id === PanelEditorTabId.Transform && <TransformationsEditor panel={panel} />} </TabContent> </div> ); }); PanelEditorTabs.displayName = 'PanelEditorTabs'; function getCounter(panel: PanelModel, tab: PanelEditorTab) { switch (tab.id) { case PanelEditorTabId.Query: return panel.targets.length; case PanelEditorTabId.Alert: return panel.alert ? 1 : 0; case PanelEditorTabId.Transform: const transformations = panel.getTransformations() ?? []; return transformations.length; } return null; } const getStyles = (theme: GrafanaTheme2) => { return { wrapper: css` display: flex; flex-direction: column; height: 100%; `, tabBar: css` padding-left: ${theme.spacing(2)}; `, tabContent: css` padding: 0; display: flex; flex-direction: column; flex-grow: 1; min-height: 0; background: ${theme.colors.background.primary}; border-right: 1px solid ${theme.components.panel.borderColor}; `, }; };
public/app/features/dashboard/components/PanelEditor/PanelEditorTabs.tsx
1
https://github.com/grafana/grafana/commit/78ebac0116c0aebd99d261c3f138819dc957bece
[ 0.9980329871177673, 0.11554359644651413, 0.0001658764376770705, 0.00016992102609947324, 0.2865549325942993 ]
{ "id": 3, "code_window": [ " display: flex;\n", " flex-direction: column;\n", " flex-grow: 1;\n", " min-height: 0;\n", " background: ${theme.colors.background.primary};\n", " border-right: 1px solid ${theme.components.panel.borderColor};\n", " `,\n", " };\n", "};" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " border: 1px solid ${theme.components.panel.borderColor};\n", " border-left: none;\n", " border-bottom: none;\n", " border-top-right-radius: ${theme.shape.borderRadius(1.5)};\n" ], "file_path": "public/app/features/dashboard/components/PanelEditor/PanelEditorTabs.tsx", "type": "replace", "edit_start_line_idx": 109 }
import { combineLatest, Observable, of } from 'rxjs'; import { ArrayDataFrame, PanelData } from '@grafana/data'; import { DashboardQueryRunnerResult } from './DashboardQueryRunner/types'; import { mergeMap } from 'rxjs/operators'; export function mergePanelAndDashData( panelObservable: Observable<PanelData>, dashObservable: Observable<DashboardQueryRunnerResult> ): Observable<PanelData> { return combineLatest([panelObservable, dashObservable]).pipe( mergeMap((combined) => { const [panelData, dashData] = combined; if (Boolean(dashData.annotations?.length) || Boolean(dashData.alertState)) { if (!panelData.annotations) { panelData.annotations = []; } const annotations = panelData.annotations.concat(new ArrayDataFrame(dashData.annotations)); const alertState = dashData.alertState; return of({ ...panelData, annotations, alertState }); } return of(panelData); }) ); }
public/app/features/query/state/mergePanelAndDashData.ts
0
https://github.com/grafana/grafana/commit/78ebac0116c0aebd99d261c3f138819dc957bece
[ 0.0001699610147625208, 0.00016802902973722667, 0.00016606948338449, 0.0001680565474089235, 0.0000015888304005784448 ]
{ "id": 3, "code_window": [ " display: flex;\n", " flex-direction: column;\n", " flex-grow: 1;\n", " min-height: 0;\n", " background: ${theme.colors.background.primary};\n", " border-right: 1px solid ${theme.components.panel.borderColor};\n", " `,\n", " };\n", "};" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " border: 1px solid ${theme.components.panel.borderColor};\n", " border-left: none;\n", " border-bottom: none;\n", " border-top-right-radius: ${theme.shape.borderRadius(1.5)};\n" ], "file_path": "public/app/features/dashboard/components/PanelEditor/PanelEditorTabs.tsx", "type": "replace", "edit_start_line_idx": 109 }
import React from 'react'; import { PanelPlugin } from '@grafana/data'; import { AlertGroupPanelOptions } from './types'; import { AlertGroupsPanel } from './AlertGroupsPanel'; import { AlertManagerPicker } from 'app/features/alerting/unified/components/AlertManagerPicker'; import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource'; export const plugin = new PanelPlugin<AlertGroupPanelOptions>(AlertGroupsPanel).setPanelOptions((builder) => { return builder .addCustomEditor({ name: 'Alertmanager', path: 'alertmanager', id: 'alertmanager', defaultValue: GRAFANA_RULES_SOURCE_NAME, category: ['Options'], editor: function RenderAlertmanagerPicker(props) { return ( <AlertManagerPicker current={props.value} onChange={(alertManagerSourceName) => { return props.onChange(alertManagerSourceName); }} /> ); }, }) .addBooleanSwitch({ name: 'Expand all by default', path: 'expandAll', defaultValue: false, category: ['Options'], }) .addTextInput({ description: 'Filter results by matching labels, ex: env=production,severity=~critical|warning', name: 'Labels', path: 'labels', category: ['Filter'], }); });
public/app/plugins/panel/alertGroups/module.tsx
0
https://github.com/grafana/grafana/commit/78ebac0116c0aebd99d261c3f138819dc957bece
[ 0.0001757470890879631, 0.00017042935360223055, 0.00016844621859490871, 0.0001687620533630252, 0.0000030768587748752907 ]
{ "id": 3, "code_window": [ " display: flex;\n", " flex-direction: column;\n", " flex-grow: 1;\n", " min-height: 0;\n", " background: ${theme.colors.background.primary};\n", " border-right: 1px solid ${theme.components.panel.borderColor};\n", " `,\n", " };\n", "};" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " border: 1px solid ${theme.components.panel.borderColor};\n", " border-left: none;\n", " border-bottom: none;\n", " border-top-right-radius: ${theme.shape.borderRadius(1.5)};\n" ], "file_path": "public/app/features/dashboard/components/PanelEditor/PanelEditorTabs.tsx", "type": "replace", "edit_start_line_idx": 109 }
+++ title = "Inspect a panel" weight = 400 +++ # Inspect a panel The panel inspector helps you understand and troubleshoot your panels. You can inspect the raw data for any Grafana panel, export that data to a comma-separated values (CSV) file, view query requests, and export panel and data JSON. ## Panel inspector UI The panel inspector displays Inspect: <NameOfPanelBeingInspected> at the top of the pane. Click the arrow in the upper right corner to expand or reduce the pane. The panel inspector consists of following tabs: - **Data tab -** Shows the raw data returned by the query with transformations applied. Field options such as overrides and value mappings are not applied by default. - **Stats tab -** Shows how long your query takes and how much it returns. - **JSON tab -** Allows you to view and copy the panel JSON, panel data JSON, and data frame structure JSON. This is useful if you are provisioning or administering Grafana. - **Query tab -** Shows you the requests to the server sent when Grafana queries the data source. - **Error tab -** Shows the error. Only visible when query returns error. > **Note:** Not all panel types include all four tabs. For example, dashboard list panels do not have raw data to inspect, so they do not display the Stats, Data, or Query tabs. ## Panel inspector tasks Tasks you can perform in the panel inspector are described below. ### Open the panel inspector You can inspect any panel that you can view. 1. In Grafana, navigate to the dashboard that contains the panel you want to inspect. 1. Click the title of the panel you want to inspect and then click **Inspect**. Or Hover your cursor over the panel title and then press **i**. The panel inspector pane opens on the right side of the screen. ### Inspect raw query results View raw query results in a table. This is the data returned by the query with transformations applied and before the panel applies field options or field option overrides. In the inspector click the **Data** tab or in the panel menu click **Inspect > Data**. If your panel contains multiple queries or queries multiple nodes, then you have additional options. - **Select result -** Choose which result set data you want to view. - **Transform data** - **Join by time -** View raw data from all your queries at once, one result set per column. Click a column heading to reorder the data. View raw query results in a table with field options and options overrides applied: 1. Open the **Data** tab in panel inspector. 1. Click on **Data display options** above the table. 1. Click on **Apply field configuration** toggle button. ### Download raw query results as CSV Grafana generates a CSV file in your default browser download location. You can open it in the viewer of your choice. 1. Open the panel inspector. 1. Inspect the raw query results as described above. Adjust settings until you see the raw data that you want to export. 1. Click **Download CSV**. To download a CSV file specifically formatted for Excel, expand the **Data options** panel and enable the **Download for Excel** toggle before clicking **Download CSV**. ### Download log results Grafana generates a text (.txt) file in your default browser download location. You can open the log in the viewer of your choice. 1. Open the panel inspector. 1. Inspect the log query results as described above. 1. Click **Download logs**. ### Inspect query performance The Stats tab displays statistics that tell you how long your query takes, how many queries you send, and the number of rows returned. This information can help you troubleshoot your queries, especially if any of the numbers are unexpectedly high or low. 1. Open the panel inspector. 1. Navigate to the Stats tab. Statistics are displayed in read-only format. ### View panel JSON model Explore and export panel, panel data, and data frame JSON models. 1. Open the panel inspector and then click the **JSON** tab or in the panel menu click **Inspect > Panel JSON**. 1. In Select source, choose one of the following options: - **Panel JSON -** Displays a JSON object representing the panel. - **Panel data -** Displays a JSON object representing the data that was passed to the panel. - **DataFrame structure -** Displays the raw result set with transformations, field configuration, and overrides configuration applied. 1. You can expand or collapse portions of the JSON to explore it, or you can click **Copy to clipboard** and paste the JSON in another application. ### View raw request and response to data source 1. Open the panel inspector and then click the **Query** tab or in the panel menu click **Inspect > Query**. 1. Click **Refresh**. Grafana sends a query to the server to collect information and then displays the result. You can now drill down on specific portions of the query, expand or collapse all of it, or copy the data to the clipboard to use in other applications.
docs/sources/panels/inspect-panel.md
0
https://github.com/grafana/grafana/commit/78ebac0116c0aebd99d261c3f138819dc957bece
[ 0.0001980138331418857, 0.00017016517813317478, 0.00016148635768331587, 0.00016591818712186068, 0.000010613255653879605 ]
{ "id": 0, "code_window": [ "\t\tschemesInQuery.forEach(scheme => providerActivations.push(this.extensionService.activateByEvent(`onSearch:${scheme}`)));\n", "\t\tproviderActivations.push(this.extensionService.activateByEvent('onSearch:file'));\n", "\n", "\t\tconst providerPromise = Promise.all(providerActivations)\n", "\t\t\t.then(() => this.extensionService.whenInstalledExtensionsRegistered())\n", "\t\t\t.then(() => {\n", "\t\t\t\t// Cancel faster if search was canceled while waiting for extensions\n", "\t\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\t\treturn Promise.reject(canceled());\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tconst providerPromise = (async () => {\n", "\t\t\tawait Promise.all(providerActivations);\n", "\t\t\tthis.extensionService.whenInstalledExtensionsRegistered();\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 118 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as arrays from 'vs/base/common/arrays'; import { CancellationToken } from 'vs/base/common/cancellation'; import { canceled } from 'vs/base/common/errors'; import { Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { keys, ResourceMap, values } from 'vs/base/common/map'; import { Schemas } from 'vs/base/common/network'; import { StopWatch } from 'vs/base/common/stopwatch'; import { URI as uri } from 'vs/base/common/uri'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IFileService } from 'vs/platform/files/common/files'; import { ILogService } from 'vs/platform/log/common/log'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { deserializeSearchError, FileMatch, ICachedSearchStats, IFileMatch, IFileQuery, IFileSearchStats, IFolderQuery, IProgressMessage, ISearchComplete, ISearchEngineStats, ISearchProgressItem, ISearchQuery, ISearchResultProvider, ISearchService, ITextQuery, pathIncludedInQuery, QueryType, SearchError, SearchErrorCode, SearchProviderType, isFileMatch, isProgressMessage } from 'vs/workbench/services/search/common/search'; import { addContextToEditorMatches, editorMatchesToTextSearchResults } from 'vs/workbench/services/search/common/searchHelpers'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { DeferredPromise } from 'vs/base/test/common/utils'; export class SearchService extends Disposable implements ISearchService { _serviceBrand: undefined; protected diskSearch: ISearchResultProvider | null = null; private readonly fileSearchProviders = new Map<string, ISearchResultProvider>(); private readonly textSearchProviders = new Map<string, ISearchResultProvider>(); private deferredFileSearchesByScheme = new Map<string, DeferredPromise<ISearchResultProvider>>(); private deferredTextSearchesByScheme = new Map<string, DeferredPromise<ISearchResultProvider>>(); constructor( private readonly modelService: IModelService, private readonly editorService: IEditorService, private readonly telemetryService: ITelemetryService, private readonly logService: ILogService, private readonly extensionService: IExtensionService, private readonly fileService: IFileService ) { super(); } registerSearchResultProvider(scheme: string, type: SearchProviderType, provider: ISearchResultProvider): IDisposable { let list: Map<string, ISearchResultProvider>; let deferredMap: Map<string, DeferredPromise<ISearchResultProvider>>; if (type === SearchProviderType.file) { list = this.fileSearchProviders; deferredMap = this.deferredFileSearchesByScheme; } else if (type === SearchProviderType.text) { list = this.textSearchProviders; deferredMap = this.deferredTextSearchesByScheme; } else { throw new Error('Unknown SearchProviderType'); } list.set(scheme, provider); if (deferredMap.has(scheme)) { deferredMap.get(scheme)!.complete(provider); deferredMap.delete(scheme); } return toDisposable(() => { list.delete(scheme); }); } async textSearch(query: ITextQuery, token?: CancellationToken, onProgress?: (item: ISearchProgressItem) => void): Promise<ISearchComplete> { // Get local results from dirty/untitled const localResults = this.getLocalResults(query); if (onProgress) { arrays.coalesce([...localResults.results.values()]).forEach(onProgress); } const onProviderProgress = (progress: ISearchProgressItem) => { if (isFileMatch(progress)) { // Match if (!localResults.results.has(progress.resource) && onProgress) { // don't override local results onProgress(progress); } } else if (onProgress) { // Progress onProgress(<IProgressMessage>progress); } if (isProgressMessage(progress)) { this.logService.debug('SearchService#search', progress.message); } }; const otherResults = await this.doSearch(query, token, onProviderProgress); return { ...otherResults, ...{ limitHit: otherResults.limitHit || localResults.limitHit }, results: [...otherResults.results, ...arrays.coalesce([...localResults.results.values()])] }; } fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { return this.doSearch(query, token); } private doSearch(query: ISearchQuery, token?: CancellationToken, onProgress?: (item: ISearchProgressItem) => void): Promise<ISearchComplete> { this.logService.trace('SearchService#search', JSON.stringify(query)); const schemesInQuery = this.getSchemesInQuery(query); const providerActivations: Promise<any>[] = [Promise.resolve(null)]; schemesInQuery.forEach(scheme => providerActivations.push(this.extensionService.activateByEvent(`onSearch:${scheme}`))); providerActivations.push(this.extensionService.activateByEvent('onSearch:file')); const providerPromise = Promise.all(providerActivations) .then(() => this.extensionService.whenInstalledExtensionsRegistered()) .then(() => { // Cancel faster if search was canceled while waiting for extensions if (token && token.isCancellationRequested) { return Promise.reject(canceled()); } const progressCallback = (item: ISearchProgressItem) => { if (token && token.isCancellationRequested) { return; } if (onProgress) { onProgress(item); } }; return this.searchWithProviders(query, progressCallback, token); }) .then(completes => { completes = arrays.coalesce(completes); if (!completes.length) { return { limitHit: false, results: [] }; } return <ISearchComplete>{ limitHit: completes[0] && completes[0].limitHit, stats: completes[0].stats, results: arrays.flatten(completes.map((c: ISearchComplete) => c.results)) }; }); return new Promise((resolve, reject) => { if (token) { token.onCancellationRequested(() => { reject(canceled()); }); } providerPromise.then(resolve, reject); }); } private getSchemesInQuery(query: ISearchQuery): Set<string> { const schemes = new Set<string>(); if (query.folderQueries) { query.folderQueries.forEach(fq => schemes.add(fq.folder.scheme)); } if (query.extraFileResources) { query.extraFileResources.forEach(extraFile => schemes.add(extraFile.scheme)); } return schemes; } private async waitForProvider(queryType: QueryType, scheme: string): Promise<ISearchResultProvider> { let deferredMap: Map<string, DeferredPromise<ISearchResultProvider>> = queryType === QueryType.File ? this.deferredFileSearchesByScheme : this.deferredTextSearchesByScheme; if (deferredMap.has(scheme)) { return deferredMap.get(scheme)!.p; } else { const deferred = new DeferredPromise<ISearchResultProvider>(); deferredMap.set(scheme, deferred); return deferred.p; } } private async searchWithProviders(query: ISearchQuery, onProviderProgress: (progress: ISearchProgressItem) => void, token?: CancellationToken) { const e2eSW = StopWatch.create(false); const diskSearchQueries: IFolderQuery[] = []; const searchPs: Promise<ISearchComplete>[] = []; const fqs = this.groupFolderQueriesByScheme(query); await Promise.all(keys(fqs).map(async scheme => { const schemeFQs = fqs.get(scheme)!; let provider = query.type === QueryType.File ? this.fileSearchProviders.get(scheme) : this.textSearchProviders.get(scheme); if (!provider && scheme === Schemas.file) { diskSearchQueries.push(...schemeFQs); } else { if (!provider) { if (scheme !== Schemas.vscodeRemote) { console.warn(`No search provider registered for scheme: ${scheme}`); return; } console.warn(`No search provider registered for scheme: ${scheme}, waiting`); provider = await this.waitForProvider(query.type, scheme); } const oneSchemeQuery: ISearchQuery = { ...query, ...{ folderQueries: schemeFQs } }; searchPs.push(query.type === QueryType.File ? provider.fileSearch(<IFileQuery>oneSchemeQuery, token) : provider.textSearch(<ITextQuery>oneSchemeQuery, onProviderProgress, token)); } })); const diskSearchExtraFileResources = query.extraFileResources && query.extraFileResources.filter(res => res.scheme === Schemas.file); if (diskSearchQueries.length || diskSearchExtraFileResources) { const diskSearchQuery: ISearchQuery = { ...query, ...{ folderQueries: diskSearchQueries }, extraFileResources: diskSearchExtraFileResources }; if (this.diskSearch) { searchPs.push(diskSearchQuery.type === QueryType.File ? this.diskSearch.fileSearch(diskSearchQuery, token) : this.diskSearch.textSearch(diskSearchQuery, onProviderProgress, token)); } } return Promise.all(searchPs).then(completes => { const endToEndTime = e2eSW.elapsed(); this.logService.trace(`SearchService#search: ${endToEndTime}ms`); completes.forEach(complete => { this.sendTelemetry(query, endToEndTime, complete); }); return completes; }, err => { const endToEndTime = e2eSW.elapsed(); this.logService.trace(`SearchService#search: ${endToEndTime}ms`); const searchError = deserializeSearchError(err.message); this.sendTelemetry(query, endToEndTime, undefined, searchError); throw searchError; }); } private groupFolderQueriesByScheme(query: ISearchQuery): Map<string, IFolderQuery[]> { const queries = new Map<string, IFolderQuery[]>(); query.folderQueries.forEach(fq => { const schemeFQs = queries.get(fq.folder.scheme) || []; schemeFQs.push(fq); queries.set(fq.folder.scheme, schemeFQs); }); return queries; } private sendTelemetry(query: ISearchQuery, endToEndTime: number, complete?: ISearchComplete, err?: SearchError): void { const fileSchemeOnly = query.folderQueries.every(fq => fq.folder.scheme === 'file'); const otherSchemeOnly = query.folderQueries.every(fq => fq.folder.scheme !== 'file'); const scheme = fileSchemeOnly ? 'file' : otherSchemeOnly ? 'other' : 'mixed'; if (query.type === QueryType.File && complete && complete.stats) { const fileSearchStats = complete.stats as IFileSearchStats; if (fileSearchStats.fromCache) { const cacheStats: ICachedSearchStats = fileSearchStats.detailStats as ICachedSearchStats; type CachedSearchCompleteClassifcation = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; resultCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; type: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; sortingTime?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheWasResolved: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; cacheLookupTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheFilterTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheEntryCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type CachedSearchCompleteEvent = { reason?: string; resultCount: number; workspaceFolderCount: number; type: 'fileSearchProvider' | 'searchProcess'; endToEndTime: number; sortingTime?: number; cacheWasResolved: boolean; cacheLookupTime: number; cacheFilterTime: number; cacheEntryCount: number; scheme: string; }; this.telemetryService.publicLog2<CachedSearchCompleteEvent, CachedSearchCompleteClassifcation>('cachedSearchComplete', { reason: query._reason, resultCount: fileSearchStats.resultCount, workspaceFolderCount: query.folderQueries.length, type: fileSearchStats.type, endToEndTime: endToEndTime, sortingTime: fileSearchStats.sortingTime, cacheWasResolved: cacheStats.cacheWasResolved, cacheLookupTime: cacheStats.cacheLookupTime, cacheFilterTime: cacheStats.cacheFilterTime, cacheEntryCount: cacheStats.cacheEntryCount, scheme }); } else { const searchEngineStats: ISearchEngineStats = fileSearchStats.detailStats as ISearchEngineStats; type SearchCompleteClassification = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; resultCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; type: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; sortingTime?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; fileWalkTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; directoriesWalked: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; filesWalked: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cmdTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cmdResultCount?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type SearchCompleteEvent = { reason?: string; resultCount: number; workspaceFolderCount: number; type: 'fileSearchProvider' | 'searchProcess'; endToEndTime: number; sortingTime?: number; fileWalkTime: number directoriesWalked: number; filesWalked: number; cmdTime: number; cmdResultCount?: number; scheme: string; }; this.telemetryService.publicLog2<SearchCompleteEvent, SearchCompleteClassification>('searchComplete', { reason: query._reason, resultCount: fileSearchStats.resultCount, workspaceFolderCount: query.folderQueries.length, type: fileSearchStats.type, endToEndTime: endToEndTime, sortingTime: fileSearchStats.sortingTime, fileWalkTime: searchEngineStats.fileWalkTime, directoriesWalked: searchEngineStats.directoriesWalked, filesWalked: searchEngineStats.filesWalked, cmdTime: searchEngineStats.cmdTime, cmdResultCount: searchEngineStats.cmdResultCount, scheme }); } } else if (query.type === QueryType.Text) { let errorType: string | undefined; if (err) { errorType = err.code === SearchErrorCode.regexParseError ? 'regex' : err.code === SearchErrorCode.unknownEncoding ? 'encoding' : err.code === SearchErrorCode.globParseError ? 'glob' : err.code === SearchErrorCode.invalidLiteral ? 'literal' : err.code === SearchErrorCode.other ? 'other' : 'unknown'; } type TextSearchCompleteClassification = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; error?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; usePCRE2: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type TextSearchCompleteEvent = { reason?: string; workspaceFolderCount: number; endToEndTime: number; scheme: string; error?: string; usePCRE2: boolean; }; this.telemetryService.publicLog2<TextSearchCompleteEvent, TextSearchCompleteClassification>('textSearchComplete', { reason: query._reason, workspaceFolderCount: query.folderQueries.length, endToEndTime: endToEndTime, scheme, error: errorType, usePCRE2: !!query.usePCRE2 }); } } private getLocalResults(query: ITextQuery): { results: ResourceMap<IFileMatch | null>; limitHit: boolean } { const localResults = new ResourceMap<IFileMatch | null>(); let limitHit = false; if (query.type === QueryType.Text) { const models = this.modelService.getModels(); models.forEach((model) => { const resource = model.uri; if (!resource) { return; } if (limitHit) { return; } // Skip files that are not opened as text file if (!this.editorService.isOpen({ resource })) { return; } // Skip search results if (model.getModeId() === 'search-result' && !(query.includePattern && query.includePattern['**/*.code-search'])) { // TODO: untitled search editors will be excluded from search even when include *.code-search is specified return; } // Block walkthrough, webview, etc. if (resource.scheme !== Schemas.untitled && !this.fileService.canHandleResource(resource)) { return; } // Exclude files from the git FileSystemProvider, e.g. to prevent open staged files from showing in search results if (resource.scheme === 'git') { return; } if (!this.matches(resource, query)) { return; // respect user filters } // Use editor API to find matches const askMax = typeof query.maxResults === 'number' ? query.maxResults + 1 : undefined; let matches = model.findMatches(query.contentPattern.pattern, false, !!query.contentPattern.isRegExp, !!query.contentPattern.isCaseSensitive, query.contentPattern.isWordMatch ? query.contentPattern.wordSeparators! : null, false, askMax); if (matches.length) { if (askMax && matches.length >= askMax) { limitHit = true; matches = matches.slice(0, askMax - 1); } const fileMatch = new FileMatch(resource); localResults.set(resource, fileMatch); const textSearchResults = editorMatchesToTextSearchResults(matches, model, query.previewOptions); fileMatch.results = addContextToEditorMatches(textSearchResults, model, query); } else { localResults.set(resource, null); } }); } return { results: localResults, limitHit }; } private matches(resource: uri, query: ITextQuery): boolean { return pathIncludedInQuery(query, resource.fsPath); } clearCache(cacheKey: string): Promise<void> { const clearPs = [ this.diskSearch, ...values(this.fileSearchProviders) ].map(provider => provider && provider.clearCache(cacheKey)); return Promise.all(clearPs) .then(() => { }); } } export class RemoteSearchService extends SearchService { constructor( @IModelService modelService: IModelService, @IEditorService editorService: IEditorService, @ITelemetryService telemetryService: ITelemetryService, @ILogService logService: ILogService, @IExtensionService extensionService: IExtensionService, @IFileService fileService: IFileService ) { super(modelService, editorService, telemetryService, logService, extensionService, fileService); } } registerSingleton(ISearchService, RemoteSearchService, true);
src/vs/workbench/services/search/common/searchService.ts
1
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.9926618337631226, 0.050962984561920166, 0.00016292877262458205, 0.0001714025274850428, 0.2076226770877838 ]
{ "id": 0, "code_window": [ "\t\tschemesInQuery.forEach(scheme => providerActivations.push(this.extensionService.activateByEvent(`onSearch:${scheme}`)));\n", "\t\tproviderActivations.push(this.extensionService.activateByEvent('onSearch:file'));\n", "\n", "\t\tconst providerPromise = Promise.all(providerActivations)\n", "\t\t\t.then(() => this.extensionService.whenInstalledExtensionsRegistered())\n", "\t\t\t.then(() => {\n", "\t\t\t\t// Cancel faster if search was canceled while waiting for extensions\n", "\t\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\t\treturn Promise.reject(canceled());\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tconst providerPromise = (async () => {\n", "\t\t\tawait Promise.all(providerActivations);\n", "\t\t\tthis.extensionService.whenInstalledExtensionsRegistered();\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 118 }
/*--------------------------------------------------------------------------------------------- * 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 types from 'vs/base/common/types'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { TextCompareEditorVisibleContext, EditorInput, IEditorIdentifier, IEditorCommandsContext, ActiveEditorGroupEmptyContext, MultipleEditorGroupsContext, CloseDirection, IEditorInput, IVisibleEditorPane, EditorStickyContext, EditorsOrder } from 'vs/workbench/common/editor'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { TextDiffEditor } from 'vs/workbench/browser/parts/editor/textDiffEditor'; import { KeyMod, KeyCode, KeyChord } from 'vs/base/common/keyCodes'; import { URI } from 'vs/base/common/uri'; import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput'; import { IListService } from 'vs/platform/list/browser/listService'; import { List } from 'vs/base/browser/ui/list/listWidget'; import { distinct, coalesce } from 'vs/base/common/arrays'; import { IEditorGroupsService, IEditorGroup, GroupDirection, GroupLocation, GroupsOrder, preferredSideBySideGroupDirection, EditorGroupLayout } from 'vs/workbench/services/editor/common/editorGroupsService'; import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration'; import { CommandsRegistry, ICommandHandler } from 'vs/platform/commands/common/commands'; import { MenuRegistry, MenuId } from 'vs/platform/actions/common/actions'; import { ActiveGroupEditorsByMostRecentlyUsedQuickAccess } from 'vs/workbench/browser/parts/editor/editorQuickAccess'; export const CLOSE_SAVED_EDITORS_COMMAND_ID = 'workbench.action.closeUnmodifiedEditors'; export const CLOSE_EDITORS_IN_GROUP_COMMAND_ID = 'workbench.action.closeEditorsInGroup'; export const CLOSE_EDITORS_AND_GROUP_COMMAND_ID = 'workbench.action.closeEditorsAndGroup'; export const CLOSE_EDITORS_TO_THE_RIGHT_COMMAND_ID = 'workbench.action.closeEditorsToTheRight'; export const CLOSE_EDITOR_COMMAND_ID = 'workbench.action.closeActiveEditor'; export const CLOSE_EDITOR_GROUP_COMMAND_ID = 'workbench.action.closeGroup'; export const CLOSE_OTHER_EDITORS_IN_GROUP_COMMAND_ID = 'workbench.action.closeOtherEditors'; export const MOVE_ACTIVE_EDITOR_COMMAND_ID = 'moveActiveEditor'; export const LAYOUT_EDITOR_GROUPS_COMMAND_ID = 'layoutEditorGroups'; export const KEEP_EDITOR_COMMAND_ID = 'workbench.action.keepEditor'; export const SHOW_EDITORS_IN_GROUP = 'workbench.action.showEditorsInGroup'; export const PIN_EDITOR_COMMAND_ID = 'workbench.action.pinEditor'; export const UNPIN_EDITOR_COMMAND_ID = 'workbench.action.unpinEditor'; export const TOGGLE_DIFF_SIDE_BY_SIDE = 'toggle.diff.renderSideBySide'; export const GOTO_NEXT_CHANGE = 'workbench.action.compareEditor.nextChange'; export const GOTO_PREVIOUS_CHANGE = 'workbench.action.compareEditor.previousChange'; export const TOGGLE_DIFF_IGNORE_TRIM_WHITESPACE = 'toggle.diff.ignoreTrimWhitespace'; export const SPLIT_EDITOR_UP = 'workbench.action.splitEditorUp'; export const SPLIT_EDITOR_DOWN = 'workbench.action.splitEditorDown'; export const SPLIT_EDITOR_LEFT = 'workbench.action.splitEditorLeft'; export const SPLIT_EDITOR_RIGHT = 'workbench.action.splitEditorRight'; export const OPEN_EDITOR_AT_INDEX_COMMAND_ID = 'workbench.action.openEditorAtIndex'; export interface ActiveEditorMoveArguments { to: 'first' | 'last' | 'left' | 'right' | 'up' | 'down' | 'center' | 'position' | 'previous' | 'next'; by: 'tab' | 'group'; value: number; } const isActiveEditorMoveArg = function (arg: ActiveEditorMoveArguments): boolean { if (!types.isObject(arg)) { return false; } if (!types.isString(arg.to)) { return false; } if (!types.isUndefined(arg.by) && !types.isString(arg.by)) { return false; } if (!types.isUndefined(arg.value) && !types.isNumber(arg.value)) { return false; } return true; }; function registerActiveEditorMoveCommand(): void { KeybindingsRegistry.registerCommandAndKeybindingRule({ id: MOVE_ACTIVE_EDITOR_COMMAND_ID, weight: KeybindingWeight.WorkbenchContrib, when: EditorContextKeys.editorTextFocus, primary: 0, handler: (accessor, args) => moveActiveEditor(args, accessor), description: { description: nls.localize('editorCommand.activeEditorMove.description', "Move the active editor by tabs or groups"), args: [ { name: nls.localize('editorCommand.activeEditorMove.arg.name', "Active editor move argument"), description: nls.localize('editorCommand.activeEditorMove.arg.description', "Argument Properties:\n\t* 'to': String value providing where to move.\n\t* 'by': String value providing the unit for move (by tab or by group).\n\t* 'value': Number value providing how many positions or an absolute position to move."), constraint: isActiveEditorMoveArg, schema: { 'type': 'object', 'required': ['to'], 'properties': { 'to': { 'type': 'string', 'enum': ['left', 'right'] }, 'by': { 'type': 'string', 'enum': ['tab', 'group'] }, 'value': { 'type': 'number' } }, } } ] } }); } function moveActiveEditor(args: ActiveEditorMoveArguments = Object.create(null), accessor: ServicesAccessor): void { args.to = args.to || 'right'; args.by = args.by || 'tab'; args.value = typeof args.value === 'number' ? args.value : 1; const activeEditorPane = accessor.get(IEditorService).activeEditorPane; if (activeEditorPane) { switch (args.by) { case 'tab': return moveActiveTab(args, activeEditorPane, accessor); case 'group': return moveActiveEditorToGroup(args, activeEditorPane, accessor); } } } function moveActiveTab(args: ActiveEditorMoveArguments, control: IVisibleEditorPane, accessor: ServicesAccessor): void { const group = control.group; let index = group.getIndexOfEditor(control.input); switch (args.to) { case 'first': index = 0; break; case 'last': index = group.count - 1; break; case 'left': index = index - args.value; break; case 'right': index = index + args.value; break; case 'center': index = Math.round(group.count / 2) - 1; break; case 'position': index = args.value - 1; break; } index = index < 0 ? 0 : index >= group.count ? group.count - 1 : index; group.moveEditor(control.input, group, { index }); } function moveActiveEditorToGroup(args: ActiveEditorMoveArguments, control: IVisibleEditorPane, accessor: ServicesAccessor): void { const editorGroupService = accessor.get(IEditorGroupsService); const configurationService = accessor.get(IConfigurationService); const sourceGroup = control.group; let targetGroup: IEditorGroup | undefined; switch (args.to) { case 'left': targetGroup = editorGroupService.findGroup({ direction: GroupDirection.LEFT }, sourceGroup); if (!targetGroup) { targetGroup = editorGroupService.addGroup(sourceGroup, GroupDirection.LEFT); } break; case 'right': targetGroup = editorGroupService.findGroup({ direction: GroupDirection.RIGHT }, sourceGroup); if (!targetGroup) { targetGroup = editorGroupService.addGroup(sourceGroup, GroupDirection.RIGHT); } break; case 'up': targetGroup = editorGroupService.findGroup({ direction: GroupDirection.UP }, sourceGroup); if (!targetGroup) { targetGroup = editorGroupService.addGroup(sourceGroup, GroupDirection.UP); } break; case 'down': targetGroup = editorGroupService.findGroup({ direction: GroupDirection.DOWN }, sourceGroup); if (!targetGroup) { targetGroup = editorGroupService.addGroup(sourceGroup, GroupDirection.DOWN); } break; case 'first': targetGroup = editorGroupService.findGroup({ location: GroupLocation.FIRST }, sourceGroup); break; case 'last': targetGroup = editorGroupService.findGroup({ location: GroupLocation.LAST }, sourceGroup); break; case 'previous': targetGroup = editorGroupService.findGroup({ location: GroupLocation.PREVIOUS }, sourceGroup); break; case 'next': targetGroup = editorGroupService.findGroup({ location: GroupLocation.NEXT }, sourceGroup); if (!targetGroup) { targetGroup = editorGroupService.addGroup(sourceGroup, preferredSideBySideGroupDirection(configurationService)); } break; case 'center': targetGroup = editorGroupService.getGroups(GroupsOrder.GRID_APPEARANCE)[(editorGroupService.count / 2) - 1]; break; case 'position': targetGroup = editorGroupService.getGroups(GroupsOrder.GRID_APPEARANCE)[args.value - 1]; break; } if (targetGroup) { sourceGroup.moveEditor(control.input, targetGroup); targetGroup.focus(); } } function registerEditorGroupsLayoutCommand(): void { CommandsRegistry.registerCommand(LAYOUT_EDITOR_GROUPS_COMMAND_ID, (accessor: ServicesAccessor, args: EditorGroupLayout) => { if (!args || typeof args !== 'object') { return; } const editorGroupService = accessor.get(IEditorGroupsService); editorGroupService.applyLayout(args); }); } export function mergeAllGroups(editorGroupService: IEditorGroupsService): void { const target = editorGroupService.activeGroup; editorGroupService.getGroups(GroupsOrder.MOST_RECENTLY_ACTIVE).forEach(group => { if (group === target) { return; // keep target } editorGroupService.mergeGroup(group, target); }); } function registerDiffEditorCommands(): void { KeybindingsRegistry.registerCommandAndKeybindingRule({ id: GOTO_NEXT_CHANGE, weight: KeybindingWeight.WorkbenchContrib, when: TextCompareEditorVisibleContext, primary: KeyMod.Alt | KeyCode.F5, handler: accessor => navigateInDiffEditor(accessor, true) }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: GOTO_PREVIOUS_CHANGE, weight: KeybindingWeight.WorkbenchContrib, when: TextCompareEditorVisibleContext, primary: KeyMod.Alt | KeyMod.Shift | KeyCode.F5, handler: accessor => navigateInDiffEditor(accessor, false) }); function navigateInDiffEditor(accessor: ServicesAccessor, next: boolean): void { const editorService = accessor.get(IEditorService); const candidates = [editorService.activeEditorPane, ...editorService.visibleEditorPanes].filter(editor => editor instanceof TextDiffEditor); if (candidates.length > 0) { const navigator = (<TextDiffEditor>candidates[0]).getDiffNavigator(); if (navigator) { next ? navigator.next() : navigator.previous(); } } } function toggleDiffSideBySide(accessor: ServicesAccessor): void { const configurationService = accessor.get(IConfigurationService); const newValue = !configurationService.getValue<boolean>('diffEditor.renderSideBySide'); configurationService.updateValue('diffEditor.renderSideBySide', newValue, ConfigurationTarget.USER); } function toggleDiffIgnoreTrimWhitespace(accessor: ServicesAccessor): void { const configurationService = accessor.get(IConfigurationService); const newValue = !configurationService.getValue<boolean>('diffEditor.ignoreTrimWhitespace'); configurationService.updateValue('diffEditor.ignoreTrimWhitespace', newValue, ConfigurationTarget.USER); } KeybindingsRegistry.registerCommandAndKeybindingRule({ id: TOGGLE_DIFF_SIDE_BY_SIDE, weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: undefined, handler: accessor => toggleDiffSideBySide(accessor) }); MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: TOGGLE_DIFF_SIDE_BY_SIDE, title: { value: nls.localize('toggleInlineView', "Toggle Inline View"), original: 'Compare: Toggle Inline View' }, category: nls.localize('compare', "Compare") }, when: ContextKeyExpr.has('textCompareEditorActive') }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: TOGGLE_DIFF_IGNORE_TRIM_WHITESPACE, weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: undefined, handler: accessor => toggleDiffIgnoreTrimWhitespace(accessor) }); } function registerOpenEditorAtIndexCommands(): void { const openEditorAtIndex: ICommandHandler = (accessor: ServicesAccessor, editorIndex: number): void => { const editorService = accessor.get(IEditorService); const activeEditorPane = editorService.activeEditorPane; if (activeEditorPane) { const editor = activeEditorPane.group.getEditorByIndex(editorIndex); if (editor) { editorService.openEditor(editor); } } }; // This command takes in the editor index number to open as an argument CommandsRegistry.registerCommand({ id: OPEN_EDITOR_AT_INDEX_COMMAND_ID, handler: openEditorAtIndex }); // Keybindings to focus a specific index in the tab folder if tabs are enabled for (let i = 0; i < 9; i++) { const editorIndex = i; const visibleIndex = i + 1; KeybindingsRegistry.registerCommandAndKeybindingRule({ id: OPEN_EDITOR_AT_INDEX_COMMAND_ID + visibleIndex, weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: KeyMod.Alt | toKeyCode(visibleIndex), mac: { primary: KeyMod.WinCtrl | toKeyCode(visibleIndex) }, handler: accessor => openEditorAtIndex(accessor, editorIndex) }); } function toKeyCode(index: number): KeyCode { switch (index) { case 0: return KeyCode.KEY_0; case 1: return KeyCode.KEY_1; case 2: return KeyCode.KEY_2; case 3: return KeyCode.KEY_3; case 4: return KeyCode.KEY_4; case 5: return KeyCode.KEY_5; case 6: return KeyCode.KEY_6; case 7: return KeyCode.KEY_7; case 8: return KeyCode.KEY_8; case 9: return KeyCode.KEY_9; } throw new Error('invalid index'); } } function registerFocusEditorGroupAtIndexCommands(): void { // Keybindings to focus a specific group (2-8) in the editor area for (let groupIndex = 1; groupIndex < 8; groupIndex++) { KeybindingsRegistry.registerCommandAndKeybindingRule({ id: toCommandId(groupIndex), weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: KeyMod.CtrlCmd | toKeyCode(groupIndex), handler: accessor => { const editorGroupService = accessor.get(IEditorGroupsService); const configurationService = accessor.get(IConfigurationService); // To keep backwards compatibility (pre-grid), allow to focus a group // that does not exist as long as it is the next group after the last // opened group. Otherwise we return. if (groupIndex > editorGroupService.count) { return; } // Group exists: just focus const groups = editorGroupService.getGroups(GroupsOrder.GRID_APPEARANCE); if (groups[groupIndex]) { return groups[groupIndex].focus(); } // Group does not exist: create new by splitting the active one of the last group const direction = preferredSideBySideGroupDirection(configurationService); const lastGroup = editorGroupService.findGroup({ location: GroupLocation.LAST }); const newGroup = editorGroupService.addGroup(lastGroup, direction); // Focus newGroup.focus(); } }); } function toCommandId(index: number): string { switch (index) { case 1: return 'workbench.action.focusSecondEditorGroup'; case 2: return 'workbench.action.focusThirdEditorGroup'; case 3: return 'workbench.action.focusFourthEditorGroup'; case 4: return 'workbench.action.focusFifthEditorGroup'; case 5: return 'workbench.action.focusSixthEditorGroup'; case 6: return 'workbench.action.focusSeventhEditorGroup'; case 7: return 'workbench.action.focusEighthEditorGroup'; } throw new Error('Invalid index'); } function toKeyCode(index: number): KeyCode { switch (index) { case 1: return KeyCode.KEY_2; case 2: return KeyCode.KEY_3; case 3: return KeyCode.KEY_4; case 4: return KeyCode.KEY_5; case 5: return KeyCode.KEY_6; case 6: return KeyCode.KEY_7; case 7: return KeyCode.KEY_8; } throw new Error('Invalid index'); } } export function splitEditor(editorGroupService: IEditorGroupsService, direction: GroupDirection, context?: IEditorCommandsContext): void { let sourceGroup: IEditorGroup | undefined; if (context && typeof context.groupId === 'number') { sourceGroup = editorGroupService.getGroup(context.groupId); } else { sourceGroup = editorGroupService.activeGroup; } if (!sourceGroup) { return; } // Add group const newGroup = editorGroupService.addGroup(sourceGroup, direction); // Split editor (if it can be split) let editorToCopy: IEditorInput | undefined; if (context && typeof context.editorIndex === 'number') { editorToCopy = sourceGroup.getEditorByIndex(context.editorIndex); } else { editorToCopy = types.withNullAsUndefined(sourceGroup.activeEditor); } if (editorToCopy && (editorToCopy as EditorInput).supportsSplitEditor()) { sourceGroup.copyEditor(editorToCopy, newGroup); } // Focus newGroup.focus(); } function registerSplitEditorCommands() { [ { id: SPLIT_EDITOR_UP, direction: GroupDirection.UP }, { id: SPLIT_EDITOR_DOWN, direction: GroupDirection.DOWN }, { id: SPLIT_EDITOR_LEFT, direction: GroupDirection.LEFT }, { id: SPLIT_EDITOR_RIGHT, direction: GroupDirection.RIGHT } ].forEach(({ id, direction }) => { CommandsRegistry.registerCommand(id, function (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) { splitEditor(accessor.get(IEditorGroupsService), direction, getCommandsContext(resourceOrContext, context)); }); }); } function registerCloseEditorCommands() { KeybindingsRegistry.registerCommandAndKeybindingRule({ id: CLOSE_SAVED_EDITORS_COMMAND_ID, weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyCode.KEY_U), handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => { const editorGroupService = accessor.get(IEditorGroupsService); const contexts = getMultiSelectedEditorContexts(getCommandsContext(resourceOrContext, context), accessor.get(IListService), editorGroupService); const activeGroup = editorGroupService.activeGroup; if (contexts.length === 0) { contexts.push({ groupId: activeGroup.id }); // active group as fallback } return Promise.all(distinct(contexts.map(c => c.groupId)).map(async groupId => { const group = editorGroupService.getGroup(groupId); if (group) { return group.closeEditors({ savedOnly: true, excludeSticky: true }); } })); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: CLOSE_EDITORS_IN_GROUP_COMMAND_ID, weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyCode.KEY_W), handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => { const editorGroupService = accessor.get(IEditorGroupsService); const contexts = getMultiSelectedEditorContexts(getCommandsContext(resourceOrContext, context), accessor.get(IListService), editorGroupService); const distinctGroupIds = distinct(contexts.map(c => c.groupId)); if (distinctGroupIds.length === 0) { distinctGroupIds.push(editorGroupService.activeGroup.id); } return Promise.all(distinctGroupIds.map(async groupId => { const group = editorGroupService.getGroup(groupId); if (group) { return group.closeAllEditors({ excludeSticky: true }); } })); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: CLOSE_EDITOR_COMMAND_ID, weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: KeyMod.CtrlCmd | KeyCode.KEY_W, win: { primary: KeyMod.CtrlCmd | KeyCode.F4, secondary: [KeyMod.CtrlCmd | KeyCode.KEY_W] }, handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => { const editorGroupService = accessor.get(IEditorGroupsService); const contexts = getMultiSelectedEditorContexts(getCommandsContext(resourceOrContext, context), accessor.get(IListService), editorGroupService); const activeGroup = editorGroupService.activeGroup; if (contexts.length === 0 && activeGroup.activeEditor) { contexts.push({ groupId: activeGroup.id, editorIndex: activeGroup.getIndexOfEditor(activeGroup.activeEditor) }); // active editor as fallback } const groupIds = distinct(contexts.map(context => context.groupId)); return Promise.all(groupIds.map(async groupId => { const group = editorGroupService.getGroup(groupId); if (group) { const editors = coalesce(contexts .filter(context => context.groupId === groupId) .map(context => typeof context.editorIndex === 'number' ? group.getEditorByIndex(context.editorIndex) : group.activeEditor)); return group.closeEditors(editors); } })); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: CLOSE_EDITOR_GROUP_COMMAND_ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(ActiveEditorGroupEmptyContext, MultipleEditorGroupsContext), primary: KeyMod.CtrlCmd | KeyCode.KEY_W, win: { primary: KeyMod.CtrlCmd | KeyCode.F4, secondary: [KeyMod.CtrlCmd | KeyCode.KEY_W] }, handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => { const editorGroupService = accessor.get(IEditorGroupsService); const commandsContext = getCommandsContext(resourceOrContext, context); let group: IEditorGroup | undefined; if (commandsContext && typeof commandsContext.groupId === 'number') { group = editorGroupService.getGroup(commandsContext.groupId); } else { group = editorGroupService.activeGroup; } if (group) { editorGroupService.removeGroup(group); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: CLOSE_OTHER_EDITORS_IN_GROUP_COMMAND_ID, weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: undefined, mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_T }, handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => { const editorGroupService = accessor.get(IEditorGroupsService); const contexts = getMultiSelectedEditorContexts(getCommandsContext(resourceOrContext, context), accessor.get(IListService), editorGroupService); const activeGroup = editorGroupService.activeGroup; if (contexts.length === 0 && activeGroup.activeEditor) { contexts.push({ groupId: activeGroup.id, editorIndex: activeGroup.getIndexOfEditor(activeGroup.activeEditor) }); // active editor as fallback } const groupIds = distinct(contexts.map(context => context.groupId)); return Promise.all(groupIds.map(async groupId => { const group = editorGroupService.getGroup(groupId); if (group) { const editors = contexts .filter(context => context.groupId === groupId) .map(context => typeof context.editorIndex === 'number' ? group.getEditorByIndex(context.editorIndex) : group.activeEditor); const editorsToClose = group.getEditors(EditorsOrder.SEQUENTIAL, { excludeSticky: true }).filter(editor => editors.indexOf(editor) === -1); if (group.activeEditor) { group.pinEditor(group.activeEditor); } return group.closeEditors(editorsToClose); } })); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: CLOSE_EDITORS_TO_THE_RIGHT_COMMAND_ID, weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: undefined, handler: async (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => { const editorGroupService = accessor.get(IEditorGroupsService); const { group, editor } = resolveCommandsContext(editorGroupService, getCommandsContext(resourceOrContext, context)); if (group && editor) { if (group.activeEditor) { group.pinEditor(group.activeEditor); } return group.closeEditors({ direction: CloseDirection.RIGHT, except: editor, excludeSticky: true }); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: KEEP_EDITOR_COMMAND_ID, weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyCode.Enter), handler: async (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => { const editorGroupService = accessor.get(IEditorGroupsService); const { group, editor } = resolveCommandsContext(editorGroupService, getCommandsContext(resourceOrContext, context)); if (group && editor) { return group.pinEditor(editor); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: PIN_EDITOR_COMMAND_ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(EditorStickyContext.toNegated(), ContextKeyExpr.has('config.workbench.editor.showTabs')), primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.Enter), handler: async (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => { const editorGroupService = accessor.get(IEditorGroupsService); const { group, editor } = resolveCommandsContext(editorGroupService, getCommandsContext(resourceOrContext, context)); if (group && editor) { return group.stickEditor(editor); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: UNPIN_EDITOR_COMMAND_ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(EditorStickyContext, ContextKeyExpr.has('config.workbench.editor.showTabs')), primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.Enter), handler: async (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => { const editorGroupService = accessor.get(IEditorGroupsService); const { group, editor } = resolveCommandsContext(editorGroupService, getCommandsContext(resourceOrContext, context)); if (group && editor) { return group.unstickEditor(editor); } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: SHOW_EDITORS_IN_GROUP, weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: undefined, handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => { const editorGroupService = accessor.get(IEditorGroupsService); const quickInputService = accessor.get(IQuickInputService); const commandsContext = getCommandsContext(resourceOrContext, context); if (commandsContext && typeof commandsContext.groupId === 'number') { const group = editorGroupService.getGroup(commandsContext.groupId); if (group) { editorGroupService.activateGroup(group); // we need the group to be active } } return quickInputService.quickAccess.show(ActiveGroupEditorsByMostRecentlyUsedQuickAccess.PREFIX); } }); CommandsRegistry.registerCommand(CLOSE_EDITORS_AND_GROUP_COMMAND_ID, async (accessor: ServicesAccessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => { const editorGroupService = accessor.get(IEditorGroupsService); const { group } = resolveCommandsContext(editorGroupService, getCommandsContext(resourceOrContext, context)); if (group) { await group.closeAllEditors(); if (group.count === 0 && editorGroupService.getGroup(group.id) /* could be gone by now */) { editorGroupService.removeGroup(group); // only remove group if it is now empty } } }); } function getCommandsContext(resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext): IEditorCommandsContext | undefined { if (URI.isUri(resourceOrContext)) { return context; } if (resourceOrContext && typeof resourceOrContext.groupId === 'number') { return resourceOrContext; } if (context && typeof context.groupId === 'number') { return context; } return undefined; } function resolveCommandsContext(editorGroupService: IEditorGroupsService, context?: IEditorCommandsContext): { group: IEditorGroup, editor?: IEditorInput } { // Resolve from context let group = context && typeof context.groupId === 'number' ? editorGroupService.getGroup(context.groupId) : undefined; let editor = group && context && typeof context.editorIndex === 'number' ? types.withNullAsUndefined(group.getEditorByIndex(context.editorIndex)) : undefined; // Fallback to active group as needed if (!group) { group = editorGroupService.activeGroup; editor = <EditorInput>group.activeEditor; } return { group, editor }; } export function getMultiSelectedEditorContexts(editorContext: IEditorCommandsContext | undefined, listService: IListService, editorGroupService: IEditorGroupsService): IEditorCommandsContext[] { // First check for a focused list to return the selected items from const list = listService.lastFocusedList; if (list instanceof List && list.getHTMLElement() === document.activeElement) { const elementToContext = (element: IEditorIdentifier | IEditorGroup) => { if (isEditorGroup(element)) { return { groupId: element.id, editorIndex: undefined }; } const group = editorGroupService.getGroup(element.groupId); return { groupId: element.groupId, editorIndex: group ? group.getIndexOfEditor(element.editor) : -1 }; }; const onlyEditorGroupAndEditor = (e: IEditorIdentifier | IEditorGroup) => isEditorGroup(e) || isEditorIdentifier(e); const focusedElements: Array<IEditorIdentifier | IEditorGroup> = list.getFocusedElements().filter(onlyEditorGroupAndEditor); const focus = editorContext ? editorContext : focusedElements.length ? focusedElements.map(elementToContext)[0] : undefined; // need to take into account when editor context is { group: group } if (focus) { const selection: Array<IEditorIdentifier | IEditorGroup> = list.getSelectedElements().filter(onlyEditorGroupAndEditor); // Only respect selection if it contains focused element if (selection?.some(s => { if (isEditorGroup(s)) { return s.id === focus.groupId; } const group = editorGroupService.getGroup(s.groupId); return s.groupId === focus.groupId && (group ? group.getIndexOfEditor(s.editor) : -1) === focus.editorIndex; })) { return selection.map(elementToContext); } return [focus]; } } // Otherwise go with passed in context return !!editorContext ? [editorContext] : []; } function isEditorGroup(thing: unknown): thing is IEditorGroup { const group = thing as IEditorGroup; return group && typeof group.id === 'number' && Array.isArray(group.editors); } function isEditorIdentifier(thing: unknown): thing is IEditorIdentifier { const identifier = thing as IEditorIdentifier; return identifier && typeof identifier.groupId === 'number'; } export function setup(): void { registerActiveEditorMoveCommand(); registerEditorGroupsLayoutCommand(); registerDiffEditorCommands(); registerOpenEditorAtIndexCommands(); registerCloseEditorCommands(); registerFocusEditorGroupAtIndexCommands(); registerSplitEditorCommands(); }
src/vs/workbench/browser/parts/editor/editorCommands.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00018453084339853376, 0.00017366642714478076, 0.0001646102755330503, 0.0001737839193083346, 0.0000026992513539880747 ]
{ "id": 0, "code_window": [ "\t\tschemesInQuery.forEach(scheme => providerActivations.push(this.extensionService.activateByEvent(`onSearch:${scheme}`)));\n", "\t\tproviderActivations.push(this.extensionService.activateByEvent('onSearch:file'));\n", "\n", "\t\tconst providerPromise = Promise.all(providerActivations)\n", "\t\t\t.then(() => this.extensionService.whenInstalledExtensionsRegistered())\n", "\t\t\t.then(() => {\n", "\t\t\t\t// Cancel faster if search was canceled while waiting for extensions\n", "\t\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\t\treturn Promise.reject(canceled());\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tconst providerPromise = (async () => {\n", "\t\t\tawait Promise.all(providerActivations);\n", "\t\t\tthis.extensionService.whenInstalledExtensionsRegistered();\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 118 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { cloneAndChange } from 'vs/base/common/objects'; import { IExtensionManifest } from 'vs/platform/extensions/common/extensions'; const nlsRegex = /^%([\w\d.-]+)%$/i; export interface ITranslations { [key: string]: string; } export function localizeManifest(manifest: IExtensionManifest, translations: ITranslations): IExtensionManifest { const patcher = (value: string) => { if (typeof value !== 'string') { return undefined; } const match = nlsRegex.exec(value); if (!match) { return undefined; } return translations[match[1]] || value; }; return cloneAndChange(manifest, patcher); }
src/vs/platform/extensionManagement/common/extensionNls.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00017513516650069505, 0.0001741487067192793, 0.0001724089088384062, 0.00017452536849305034, 0.000001035148898154148 ]
{ "id": 0, "code_window": [ "\t\tschemesInQuery.forEach(scheme => providerActivations.push(this.extensionService.activateByEvent(`onSearch:${scheme}`)));\n", "\t\tproviderActivations.push(this.extensionService.activateByEvent('onSearch:file'));\n", "\n", "\t\tconst providerPromise = Promise.all(providerActivations)\n", "\t\t\t.then(() => this.extensionService.whenInstalledExtensionsRegistered())\n", "\t\t\t.then(() => {\n", "\t\t\t\t// Cancel faster if search was canceled while waiting for extensions\n", "\t\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\t\treturn Promise.reject(canceled());\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tconst providerPromise = (async () => {\n", "\t\t\tawait Promise.all(providerActivations);\n", "\t\t\tthis.extensionService.whenInstalledExtensionsRegistered();\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 118 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { isWindows } from 'vs/base/common/platform'; import { CharCode } from 'vs/base/common/charCode'; import * as paths from 'vs/base/common/path'; const _schemePattern = /^\w[\w\d+.-]*$/; const _singleSlashStart = /^\//; const _doubleSlashStart = /^\/\//; function _validateUri(ret: URI, _strict?: boolean): void { // scheme, must be set if (!ret.scheme && _strict) { throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${ret.authority}", path: "${ret.path}", query: "${ret.query}", fragment: "${ret.fragment}"}`); } // scheme, https://tools.ietf.org/html/rfc3986#section-3.1 // ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) if (ret.scheme && !_schemePattern.test(ret.scheme)) { throw new Error('[UriError]: Scheme contains illegal characters.'); } // path, http://tools.ietf.org/html/rfc3986#section-3.3 // If a URI contains an authority component, then the path component // must either be empty or begin with a slash ("/") character. If a URI // does not contain an authority component, then the path cannot begin // with two slash characters ("//"). if (ret.path) { if (ret.authority) { if (!_singleSlashStart.test(ret.path)) { throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character'); } } else { if (_doubleSlashStart.test(ret.path)) { throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")'); } } } } // for a while we allowed uris *without* schemes and this is the migration // for them, e.g. an uri without scheme and without strict-mode warns and falls // back to the file-scheme. that should cause the least carnage and still be a // clear warning function _schemeFix(scheme: string, _strict: boolean): string { if (!scheme && !_strict) { return 'file'; } return scheme; } // implements a bit of https://tools.ietf.org/html/rfc3986#section-5 function _referenceResolution(scheme: string, path: string): string { // the slash-character is our 'default base' as we don't // support constructing URIs relative to other URIs. This // also means that we alter and potentially break paths. // see https://tools.ietf.org/html/rfc3986#section-5.1.4 switch (scheme) { case 'https': case 'http': case 'file': if (!path) { path = _slash; } else if (path[0] !== _slash) { path = _slash + path; } break; } return path; } const _empty = ''; const _slash = '/'; const _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/; /** * Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986. * This class is a simple parser which creates the basic component parts * (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation * and encoding. * * ```txt * foo://example.com:8042/over/there?name=ferret#nose * \_/ \______________/\_________/ \_________/ \__/ * | | | | | * scheme authority path query fragment * | _____________________|__ * / \ / \ * urn:example:animal:ferret:nose * ``` */ export class URI implements UriComponents { static isUri(thing: any): thing is URI { if (thing instanceof URI) { return true; } if (!thing) { return false; } return typeof (<URI>thing).authority === 'string' && typeof (<URI>thing).fragment === 'string' && typeof (<URI>thing).path === 'string' && typeof (<URI>thing).query === 'string' && typeof (<URI>thing).scheme === 'string' && typeof (<URI>thing).fsPath === 'function' && typeof (<URI>thing).with === 'function' && typeof (<URI>thing).toString === 'function'; } /** * scheme is the 'http' part of 'http://www.msft.com/some/path?query#fragment'. * The part before the first colon. */ readonly scheme: string; /** * authority is the 'www.msft.com' part of 'http://www.msft.com/some/path?query#fragment'. * The part between the first double slashes and the next slash. */ readonly authority: string; /** * path is the '/some/path' part of 'http://www.msft.com/some/path?query#fragment'. */ readonly path: string; /** * query is the 'query' part of 'http://www.msft.com/some/path?query#fragment'. */ readonly query: string; /** * fragment is the 'fragment' part of 'http://www.msft.com/some/path?query#fragment'. */ readonly fragment: string; /** * @internal */ protected constructor(scheme: string, authority?: string, path?: string, query?: string, fragment?: string, _strict?: boolean); /** * @internal */ protected constructor(components: UriComponents); /** * @internal */ protected constructor(schemeOrData: string | UriComponents, authority?: string, path?: string, query?: string, fragment?: string, _strict: boolean = false) { if (typeof schemeOrData === 'object') { this.scheme = schemeOrData.scheme || _empty; this.authority = schemeOrData.authority || _empty; this.path = schemeOrData.path || _empty; this.query = schemeOrData.query || _empty; this.fragment = schemeOrData.fragment || _empty; // no validation because it's this URI // that creates uri components. // _validateUri(this); } else { this.scheme = _schemeFix(schemeOrData, _strict); this.authority = authority || _empty; this.path = _referenceResolution(this.scheme, path || _empty); this.query = query || _empty; this.fragment = fragment || _empty; _validateUri(this, _strict); } } // ---- filesystem path ----------------------- /** * Returns a string representing the corresponding file system path of this URI. * Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the * platform specific path separator. * * * Will *not* validate the path for invalid characters and semantics. * * Will *not* look at the scheme of this URI. * * The result shall *not* be used for display purposes but for accessing a file on disk. * * * The *difference* to `URI#path` is the use of the platform specific separator and the handling * of UNC paths. See the below sample of a file-uri with an authority (UNC path). * * ```ts const u = URI.parse('file://server/c$/folder/file.txt') u.authority === 'server' u.path === '/shares/c$/file.txt' u.fsPath === '\\server\c$\folder\file.txt' ``` * * Using `URI#path` to read a file (using fs-apis) would not be enough because parts of the path, * namely the server name, would be missing. Therefore `URI#fsPath` exists - it's sugar to ease working * with URIs that represent files on disk (`file` scheme). */ get fsPath(): string { // if (this.scheme !== 'file') { // console.warn(`[UriError] calling fsPath with scheme ${this.scheme}`); // } return uriToFsPath(this, false); } // ---- modify to new ------------------------- with(change: { scheme?: string; authority?: string | null; path?: string | null; query?: string | null; fragment?: string | null }): URI { if (!change) { return this; } let { scheme, authority, path, query, fragment } = change; if (scheme === undefined) { scheme = this.scheme; } else if (scheme === null) { scheme = _empty; } if (authority === undefined) { authority = this.authority; } else if (authority === null) { authority = _empty; } if (path === undefined) { path = this.path; } else if (path === null) { path = _empty; } if (query === undefined) { query = this.query; } else if (query === null) { query = _empty; } if (fragment === undefined) { fragment = this.fragment; } else if (fragment === null) { fragment = _empty; } if (scheme === this.scheme && authority === this.authority && path === this.path && query === this.query && fragment === this.fragment) { return this; } return new _URI(scheme, authority, path, query, fragment); } // ---- parse & validate ------------------------ /** * Creates a new URI from a string, e.g. `http://www.msft.com/some/path`, * `file:///usr/home`, or `scheme:with/path`. * * @param value A string which represents an URI (see `URI#toString`). */ static parse(value: string, _strict: boolean = false): URI { const match = _regexp.exec(value); if (!match) { return new _URI(_empty, _empty, _empty, _empty, _empty); } return new _URI( match[2] || _empty, percentDecode(match[4] || _empty), percentDecode(match[5] || _empty), percentDecode(match[7] || _empty), percentDecode(match[9] || _empty), _strict ); } /** * Creates a new URI from a file system path, e.g. `c:\my\files`, * `/usr/home`, or `\\server\share\some\path`. * * The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument * as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as** * `URI.parse('file://' + path)` because the path might contain characters that are * interpreted (# and ?). See the following sample: * ```ts const good = URI.file('/coding/c#/project1'); good.scheme === 'file'; good.path === '/coding/c#/project1'; good.fragment === ''; const bad = URI.parse('file://' + '/coding/c#/project1'); bad.scheme === 'file'; bad.path === '/coding/c'; // path is now broken bad.fragment === '/project1'; ``` * * @param path A file system path (see `URI#fsPath`) */ static file(path: string): URI { let authority = _empty; // normalize to fwd-slashes on windows, // on other systems bwd-slashes are valid // filename character, eg /f\oo/ba\r.txt if (isWindows) { path = path.replace(/\\/g, _slash); } // check for authority as used in UNC shares // or use the path as given if (path[0] === _slash && path[1] === _slash) { const idx = path.indexOf(_slash, 2); if (idx === -1) { authority = path.substring(2); path = _slash; } else { authority = path.substring(2, idx); path = path.substring(idx) || _slash; } } return new _URI('file', authority, path, _empty, _empty); } static from(components: { scheme: string; authority?: string; path?: string; query?: string; fragment?: string }): URI { return new _URI( components.scheme, components.authority, components.path, components.query, components.fragment, ); } /** * Join a URI path with path fragments and normalizes the resulting path. * * @param uri The input URI. * @param pathFragment The path fragment to add to the URI path. * @returns The resulting URI. */ static joinPath(uri: URI, ...pathFragment: string[]): URI { if (!uri.path) { throw new Error(`[UriError]: cannot call joinPaths on URI without path`); } let newPath: string; if (isWindows && uri.scheme === 'file') { newPath = URI.file(paths.win32.join(uriToFsPath(uri, true), ...pathFragment)).path; } else { newPath = paths.posix.join(uri.path, ...pathFragment); } return uri.with({ path: newPath }); } // ---- printing/externalize --------------------------- /** * Creates a string representation for this URI. It's guaranteed that calling * `URI.parse` with the result of this function creates an URI which is equal * to this URI. * * * The result shall *not* be used for display purposes but for externalization or transport. * * The result will be encoded using the percentage encoding and encoding happens mostly * ignore the scheme-specific encoding rules. * * @param skipEncoding Do not encode the result, default is `false` */ toString(skipEncoding: boolean = false): string { return _asFormatted(this, skipEncoding); } toJSON(): UriComponents { return this; } static revive(data: UriComponents | URI): URI; static revive(data: UriComponents | URI | undefined): URI | undefined; static revive(data: UriComponents | URI | null): URI | null; static revive(data: UriComponents | URI | undefined | null): URI | undefined | null; static revive(data: UriComponents | URI | undefined | null): URI | undefined | null { if (!data) { return data; } else if (data instanceof URI) { return data; } else { const result = new _URI(data); result._formatted = (<UriState>data).external; result._fsPath = (<UriState>data)._sep === _pathSepMarker ? (<UriState>data).fsPath : null; return result; } } } export interface UriComponents { scheme: string; authority: string; path: string; query: string; fragment: string; } interface UriState extends UriComponents { $mid: number; external: string; fsPath: string; _sep: 1 | undefined; } const _pathSepMarker = isWindows ? 1 : undefined; // eslint-disable-next-line @typescript-eslint/class-name-casing class _URI extends URI { _formatted: string | null = null; _fsPath: string | null = null; get fsPath(): string { if (!this._fsPath) { this._fsPath = uriToFsPath(this, false); } return this._fsPath; } toString(skipEncoding: boolean = false): string { if (!skipEncoding) { if (!this._formatted) { this._formatted = _asFormatted(this, false); } return this._formatted; } else { // we don't cache that return _asFormatted(this, true); } } toJSON(): UriComponents { const res = <UriState>{ $mid: 1 }; // cached state if (this._fsPath) { res.fsPath = this._fsPath; res._sep = _pathSepMarker; } if (this._formatted) { res.external = this._formatted; } // uri components if (this.path) { res.path = this.path; } if (this.scheme) { res.scheme = this.scheme; } if (this.authority) { res.authority = this.authority; } if (this.query) { res.query = this.query; } if (this.fragment) { res.fragment = this.fragment; } return res; } } // reserved characters: https://tools.ietf.org/html/rfc3986#section-2.2 const encodeTable: { [ch: number]: string } = { [CharCode.Colon]: '%3A', // gen-delims [CharCode.Slash]: '%2F', [CharCode.QuestionMark]: '%3F', [CharCode.Hash]: '%23', [CharCode.OpenSquareBracket]: '%5B', [CharCode.CloseSquareBracket]: '%5D', [CharCode.AtSign]: '%40', [CharCode.ExclamationMark]: '%21', // sub-delims [CharCode.DollarSign]: '%24', [CharCode.Ampersand]: '%26', [CharCode.SingleQuote]: '%27', [CharCode.OpenParen]: '%28', [CharCode.CloseParen]: '%29', [CharCode.Asterisk]: '%2A', [CharCode.Plus]: '%2B', [CharCode.Comma]: '%2C', [CharCode.Semicolon]: '%3B', [CharCode.Equals]: '%3D', [CharCode.Space]: '%20', }; function encodeURIComponentFast(uriComponent: string, allowSlash: boolean): string { let res: string | undefined = undefined; let nativeEncodePos = -1; for (let pos = 0; pos < uriComponent.length; pos++) { const code = uriComponent.charCodeAt(pos); // unreserved characters: https://tools.ietf.org/html/rfc3986#section-2.3 if ( (code >= CharCode.a && code <= CharCode.z) || (code >= CharCode.A && code <= CharCode.Z) || (code >= CharCode.Digit0 && code <= CharCode.Digit9) || code === CharCode.Dash || code === CharCode.Period || code === CharCode.Underline || code === CharCode.Tilde || (allowSlash && code === CharCode.Slash) ) { // check if we are delaying native encode if (nativeEncodePos !== -1) { res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos)); nativeEncodePos = -1; } // check if we write into a new string (by default we try to return the param) if (res !== undefined) { res += uriComponent.charAt(pos); } } else { // encoding needed, we need to allocate a new string if (res === undefined) { res = uriComponent.substr(0, pos); } // check with default table first const escaped = encodeTable[code]; if (escaped !== undefined) { // check if we are delaying native encode if (nativeEncodePos !== -1) { res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos)); nativeEncodePos = -1; } // append escaped variant to result res += escaped; } else if (nativeEncodePos === -1) { // use native encode only when needed nativeEncodePos = pos; } } } if (nativeEncodePos !== -1) { res += encodeURIComponent(uriComponent.substring(nativeEncodePos)); } return res !== undefined ? res : uriComponent; } function encodeURIComponentMinimal(path: string): string { let res: string | undefined = undefined; for (let pos = 0; pos < path.length; pos++) { const code = path.charCodeAt(pos); if (code === CharCode.Hash || code === CharCode.QuestionMark) { if (res === undefined) { res = path.substr(0, pos); } res += encodeTable[code]; } else { if (res !== undefined) { res += path[pos]; } } } return res !== undefined ? res : path; } /** * Compute `fsPath` for the given uri */ export function uriToFsPath(uri: URI, keepDriveLetterCasing: boolean): string { let value: string; if (uri.authority && uri.path.length > 1 && uri.scheme === 'file') { // unc path: file://shares/c$/far/boo value = `//${uri.authority}${uri.path}`; } else if ( uri.path.charCodeAt(0) === CharCode.Slash && (uri.path.charCodeAt(1) >= CharCode.A && uri.path.charCodeAt(1) <= CharCode.Z || uri.path.charCodeAt(1) >= CharCode.a && uri.path.charCodeAt(1) <= CharCode.z) && uri.path.charCodeAt(2) === CharCode.Colon ) { if (!keepDriveLetterCasing) { // windows drive letter: file:///c:/far/boo value = uri.path[1].toLowerCase() + uri.path.substr(2); } else { value = uri.path.substr(1); } } else { // other path value = uri.path; } if (isWindows) { value = value.replace(/\//g, '\\'); } return value; } /** * Create the external version of a uri */ function _asFormatted(uri: URI, skipEncoding: boolean): string { const encoder = !skipEncoding ? encodeURIComponentFast : encodeURIComponentMinimal; let res = ''; let { scheme, authority, path, query, fragment } = uri; if (scheme) { res += scheme; res += ':'; } if (authority || scheme === 'file') { res += _slash; res += _slash; } if (authority) { let idx = authority.indexOf('@'); if (idx !== -1) { // <user>@<auth> const userinfo = authority.substr(0, idx); authority = authority.substr(idx + 1); idx = userinfo.indexOf(':'); if (idx === -1) { res += encoder(userinfo, false); } else { // <user>:<pass>@<auth> res += encoder(userinfo.substr(0, idx), false); res += ':'; res += encoder(userinfo.substr(idx + 1), false); } res += '@'; } authority = authority.toLowerCase(); idx = authority.indexOf(':'); if (idx === -1) { res += encoder(authority, false); } else { // <auth>:<port> res += encoder(authority.substr(0, idx), false); res += authority.substr(idx); } } if (path) { // lower-case windows drive letters in /C:/fff or C:/fff if (path.length >= 3 && path.charCodeAt(0) === CharCode.Slash && path.charCodeAt(2) === CharCode.Colon) { const code = path.charCodeAt(1); if (code >= CharCode.A && code <= CharCode.Z) { path = `/${String.fromCharCode(code + 32)}:${path.substr(3)}`; // "/c:".length === 3 } } else if (path.length >= 2 && path.charCodeAt(1) === CharCode.Colon) { const code = path.charCodeAt(0); if (code >= CharCode.A && code <= CharCode.Z) { path = `${String.fromCharCode(code + 32)}:${path.substr(2)}`; // "/c:".length === 3 } } // encode the rest of the path res += encoder(path, true); } if (query) { res += '?'; res += encoder(query, false); } if (fragment) { res += '#'; res += !skipEncoding ? encodeURIComponentFast(fragment, false) : fragment; } return res; } // --- decode function decodeURIComponentGraceful(str: string): string { try { return decodeURIComponent(str); } catch { if (str.length > 3) { return str.substr(0, 3) + decodeURIComponentGraceful(str.substr(3)); } else { return str; } } } const _rEncodedAsHex = /(%[0-9A-Za-z][0-9A-Za-z])+/g; function percentDecode(str: string): string { if (!str.match(_rEncodedAsHex)) { return str; } return str.replace(_rEncodedAsHex, (match) => decodeURIComponentGraceful(match)); }
src/vs/base/common/uri.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.0028056856244802475, 0.00023364588560070843, 0.00015918852295726538, 0.00017227053467649966, 0.0003423614543862641 ]
{ "id": 1, "code_window": [ "\n", "\t\t\t\tconst progressCallback = (item: ISearchProgressItem) => {\n", "\t\t\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\t\t\treturn;\n", "\t\t\t\t\t}\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\t// Cancel faster if search was canceled while waiting for extensions\n", "\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\treturn Promise.reject(canceled());\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 126 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as arrays from 'vs/base/common/arrays'; import { CancellationToken } from 'vs/base/common/cancellation'; import { canceled } from 'vs/base/common/errors'; import { Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { keys, ResourceMap, values } from 'vs/base/common/map'; import { Schemas } from 'vs/base/common/network'; import { StopWatch } from 'vs/base/common/stopwatch'; import { URI as uri } from 'vs/base/common/uri'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IFileService } from 'vs/platform/files/common/files'; import { ILogService } from 'vs/platform/log/common/log'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { deserializeSearchError, FileMatch, ICachedSearchStats, IFileMatch, IFileQuery, IFileSearchStats, IFolderQuery, IProgressMessage, ISearchComplete, ISearchEngineStats, ISearchProgressItem, ISearchQuery, ISearchResultProvider, ISearchService, ITextQuery, pathIncludedInQuery, QueryType, SearchError, SearchErrorCode, SearchProviderType, isFileMatch, isProgressMessage } from 'vs/workbench/services/search/common/search'; import { addContextToEditorMatches, editorMatchesToTextSearchResults } from 'vs/workbench/services/search/common/searchHelpers'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { DeferredPromise } from 'vs/base/test/common/utils'; export class SearchService extends Disposable implements ISearchService { _serviceBrand: undefined; protected diskSearch: ISearchResultProvider | null = null; private readonly fileSearchProviders = new Map<string, ISearchResultProvider>(); private readonly textSearchProviders = new Map<string, ISearchResultProvider>(); private deferredFileSearchesByScheme = new Map<string, DeferredPromise<ISearchResultProvider>>(); private deferredTextSearchesByScheme = new Map<string, DeferredPromise<ISearchResultProvider>>(); constructor( private readonly modelService: IModelService, private readonly editorService: IEditorService, private readonly telemetryService: ITelemetryService, private readonly logService: ILogService, private readonly extensionService: IExtensionService, private readonly fileService: IFileService ) { super(); } registerSearchResultProvider(scheme: string, type: SearchProviderType, provider: ISearchResultProvider): IDisposable { let list: Map<string, ISearchResultProvider>; let deferredMap: Map<string, DeferredPromise<ISearchResultProvider>>; if (type === SearchProviderType.file) { list = this.fileSearchProviders; deferredMap = this.deferredFileSearchesByScheme; } else if (type === SearchProviderType.text) { list = this.textSearchProviders; deferredMap = this.deferredTextSearchesByScheme; } else { throw new Error('Unknown SearchProviderType'); } list.set(scheme, provider); if (deferredMap.has(scheme)) { deferredMap.get(scheme)!.complete(provider); deferredMap.delete(scheme); } return toDisposable(() => { list.delete(scheme); }); } async textSearch(query: ITextQuery, token?: CancellationToken, onProgress?: (item: ISearchProgressItem) => void): Promise<ISearchComplete> { // Get local results from dirty/untitled const localResults = this.getLocalResults(query); if (onProgress) { arrays.coalesce([...localResults.results.values()]).forEach(onProgress); } const onProviderProgress = (progress: ISearchProgressItem) => { if (isFileMatch(progress)) { // Match if (!localResults.results.has(progress.resource) && onProgress) { // don't override local results onProgress(progress); } } else if (onProgress) { // Progress onProgress(<IProgressMessage>progress); } if (isProgressMessage(progress)) { this.logService.debug('SearchService#search', progress.message); } }; const otherResults = await this.doSearch(query, token, onProviderProgress); return { ...otherResults, ...{ limitHit: otherResults.limitHit || localResults.limitHit }, results: [...otherResults.results, ...arrays.coalesce([...localResults.results.values()])] }; } fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { return this.doSearch(query, token); } private doSearch(query: ISearchQuery, token?: CancellationToken, onProgress?: (item: ISearchProgressItem) => void): Promise<ISearchComplete> { this.logService.trace('SearchService#search', JSON.stringify(query)); const schemesInQuery = this.getSchemesInQuery(query); const providerActivations: Promise<any>[] = [Promise.resolve(null)]; schemesInQuery.forEach(scheme => providerActivations.push(this.extensionService.activateByEvent(`onSearch:${scheme}`))); providerActivations.push(this.extensionService.activateByEvent('onSearch:file')); const providerPromise = Promise.all(providerActivations) .then(() => this.extensionService.whenInstalledExtensionsRegistered()) .then(() => { // Cancel faster if search was canceled while waiting for extensions if (token && token.isCancellationRequested) { return Promise.reject(canceled()); } const progressCallback = (item: ISearchProgressItem) => { if (token && token.isCancellationRequested) { return; } if (onProgress) { onProgress(item); } }; return this.searchWithProviders(query, progressCallback, token); }) .then(completes => { completes = arrays.coalesce(completes); if (!completes.length) { return { limitHit: false, results: [] }; } return <ISearchComplete>{ limitHit: completes[0] && completes[0].limitHit, stats: completes[0].stats, results: arrays.flatten(completes.map((c: ISearchComplete) => c.results)) }; }); return new Promise((resolve, reject) => { if (token) { token.onCancellationRequested(() => { reject(canceled()); }); } providerPromise.then(resolve, reject); }); } private getSchemesInQuery(query: ISearchQuery): Set<string> { const schemes = new Set<string>(); if (query.folderQueries) { query.folderQueries.forEach(fq => schemes.add(fq.folder.scheme)); } if (query.extraFileResources) { query.extraFileResources.forEach(extraFile => schemes.add(extraFile.scheme)); } return schemes; } private async waitForProvider(queryType: QueryType, scheme: string): Promise<ISearchResultProvider> { let deferredMap: Map<string, DeferredPromise<ISearchResultProvider>> = queryType === QueryType.File ? this.deferredFileSearchesByScheme : this.deferredTextSearchesByScheme; if (deferredMap.has(scheme)) { return deferredMap.get(scheme)!.p; } else { const deferred = new DeferredPromise<ISearchResultProvider>(); deferredMap.set(scheme, deferred); return deferred.p; } } private async searchWithProviders(query: ISearchQuery, onProviderProgress: (progress: ISearchProgressItem) => void, token?: CancellationToken) { const e2eSW = StopWatch.create(false); const diskSearchQueries: IFolderQuery[] = []; const searchPs: Promise<ISearchComplete>[] = []; const fqs = this.groupFolderQueriesByScheme(query); await Promise.all(keys(fqs).map(async scheme => { const schemeFQs = fqs.get(scheme)!; let provider = query.type === QueryType.File ? this.fileSearchProviders.get(scheme) : this.textSearchProviders.get(scheme); if (!provider && scheme === Schemas.file) { diskSearchQueries.push(...schemeFQs); } else { if (!provider) { if (scheme !== Schemas.vscodeRemote) { console.warn(`No search provider registered for scheme: ${scheme}`); return; } console.warn(`No search provider registered for scheme: ${scheme}, waiting`); provider = await this.waitForProvider(query.type, scheme); } const oneSchemeQuery: ISearchQuery = { ...query, ...{ folderQueries: schemeFQs } }; searchPs.push(query.type === QueryType.File ? provider.fileSearch(<IFileQuery>oneSchemeQuery, token) : provider.textSearch(<ITextQuery>oneSchemeQuery, onProviderProgress, token)); } })); const diskSearchExtraFileResources = query.extraFileResources && query.extraFileResources.filter(res => res.scheme === Schemas.file); if (diskSearchQueries.length || diskSearchExtraFileResources) { const diskSearchQuery: ISearchQuery = { ...query, ...{ folderQueries: diskSearchQueries }, extraFileResources: diskSearchExtraFileResources }; if (this.diskSearch) { searchPs.push(diskSearchQuery.type === QueryType.File ? this.diskSearch.fileSearch(diskSearchQuery, token) : this.diskSearch.textSearch(diskSearchQuery, onProviderProgress, token)); } } return Promise.all(searchPs).then(completes => { const endToEndTime = e2eSW.elapsed(); this.logService.trace(`SearchService#search: ${endToEndTime}ms`); completes.forEach(complete => { this.sendTelemetry(query, endToEndTime, complete); }); return completes; }, err => { const endToEndTime = e2eSW.elapsed(); this.logService.trace(`SearchService#search: ${endToEndTime}ms`); const searchError = deserializeSearchError(err.message); this.sendTelemetry(query, endToEndTime, undefined, searchError); throw searchError; }); } private groupFolderQueriesByScheme(query: ISearchQuery): Map<string, IFolderQuery[]> { const queries = new Map<string, IFolderQuery[]>(); query.folderQueries.forEach(fq => { const schemeFQs = queries.get(fq.folder.scheme) || []; schemeFQs.push(fq); queries.set(fq.folder.scheme, schemeFQs); }); return queries; } private sendTelemetry(query: ISearchQuery, endToEndTime: number, complete?: ISearchComplete, err?: SearchError): void { const fileSchemeOnly = query.folderQueries.every(fq => fq.folder.scheme === 'file'); const otherSchemeOnly = query.folderQueries.every(fq => fq.folder.scheme !== 'file'); const scheme = fileSchemeOnly ? 'file' : otherSchemeOnly ? 'other' : 'mixed'; if (query.type === QueryType.File && complete && complete.stats) { const fileSearchStats = complete.stats as IFileSearchStats; if (fileSearchStats.fromCache) { const cacheStats: ICachedSearchStats = fileSearchStats.detailStats as ICachedSearchStats; type CachedSearchCompleteClassifcation = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; resultCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; type: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; sortingTime?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheWasResolved: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; cacheLookupTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheFilterTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheEntryCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type CachedSearchCompleteEvent = { reason?: string; resultCount: number; workspaceFolderCount: number; type: 'fileSearchProvider' | 'searchProcess'; endToEndTime: number; sortingTime?: number; cacheWasResolved: boolean; cacheLookupTime: number; cacheFilterTime: number; cacheEntryCount: number; scheme: string; }; this.telemetryService.publicLog2<CachedSearchCompleteEvent, CachedSearchCompleteClassifcation>('cachedSearchComplete', { reason: query._reason, resultCount: fileSearchStats.resultCount, workspaceFolderCount: query.folderQueries.length, type: fileSearchStats.type, endToEndTime: endToEndTime, sortingTime: fileSearchStats.sortingTime, cacheWasResolved: cacheStats.cacheWasResolved, cacheLookupTime: cacheStats.cacheLookupTime, cacheFilterTime: cacheStats.cacheFilterTime, cacheEntryCount: cacheStats.cacheEntryCount, scheme }); } else { const searchEngineStats: ISearchEngineStats = fileSearchStats.detailStats as ISearchEngineStats; type SearchCompleteClassification = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; resultCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; type: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; sortingTime?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; fileWalkTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; directoriesWalked: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; filesWalked: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cmdTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cmdResultCount?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type SearchCompleteEvent = { reason?: string; resultCount: number; workspaceFolderCount: number; type: 'fileSearchProvider' | 'searchProcess'; endToEndTime: number; sortingTime?: number; fileWalkTime: number directoriesWalked: number; filesWalked: number; cmdTime: number; cmdResultCount?: number; scheme: string; }; this.telemetryService.publicLog2<SearchCompleteEvent, SearchCompleteClassification>('searchComplete', { reason: query._reason, resultCount: fileSearchStats.resultCount, workspaceFolderCount: query.folderQueries.length, type: fileSearchStats.type, endToEndTime: endToEndTime, sortingTime: fileSearchStats.sortingTime, fileWalkTime: searchEngineStats.fileWalkTime, directoriesWalked: searchEngineStats.directoriesWalked, filesWalked: searchEngineStats.filesWalked, cmdTime: searchEngineStats.cmdTime, cmdResultCount: searchEngineStats.cmdResultCount, scheme }); } } else if (query.type === QueryType.Text) { let errorType: string | undefined; if (err) { errorType = err.code === SearchErrorCode.regexParseError ? 'regex' : err.code === SearchErrorCode.unknownEncoding ? 'encoding' : err.code === SearchErrorCode.globParseError ? 'glob' : err.code === SearchErrorCode.invalidLiteral ? 'literal' : err.code === SearchErrorCode.other ? 'other' : 'unknown'; } type TextSearchCompleteClassification = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; error?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; usePCRE2: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type TextSearchCompleteEvent = { reason?: string; workspaceFolderCount: number; endToEndTime: number; scheme: string; error?: string; usePCRE2: boolean; }; this.telemetryService.publicLog2<TextSearchCompleteEvent, TextSearchCompleteClassification>('textSearchComplete', { reason: query._reason, workspaceFolderCount: query.folderQueries.length, endToEndTime: endToEndTime, scheme, error: errorType, usePCRE2: !!query.usePCRE2 }); } } private getLocalResults(query: ITextQuery): { results: ResourceMap<IFileMatch | null>; limitHit: boolean } { const localResults = new ResourceMap<IFileMatch | null>(); let limitHit = false; if (query.type === QueryType.Text) { const models = this.modelService.getModels(); models.forEach((model) => { const resource = model.uri; if (!resource) { return; } if (limitHit) { return; } // Skip files that are not opened as text file if (!this.editorService.isOpen({ resource })) { return; } // Skip search results if (model.getModeId() === 'search-result' && !(query.includePattern && query.includePattern['**/*.code-search'])) { // TODO: untitled search editors will be excluded from search even when include *.code-search is specified return; } // Block walkthrough, webview, etc. if (resource.scheme !== Schemas.untitled && !this.fileService.canHandleResource(resource)) { return; } // Exclude files from the git FileSystemProvider, e.g. to prevent open staged files from showing in search results if (resource.scheme === 'git') { return; } if (!this.matches(resource, query)) { return; // respect user filters } // Use editor API to find matches const askMax = typeof query.maxResults === 'number' ? query.maxResults + 1 : undefined; let matches = model.findMatches(query.contentPattern.pattern, false, !!query.contentPattern.isRegExp, !!query.contentPattern.isCaseSensitive, query.contentPattern.isWordMatch ? query.contentPattern.wordSeparators! : null, false, askMax); if (matches.length) { if (askMax && matches.length >= askMax) { limitHit = true; matches = matches.slice(0, askMax - 1); } const fileMatch = new FileMatch(resource); localResults.set(resource, fileMatch); const textSearchResults = editorMatchesToTextSearchResults(matches, model, query.previewOptions); fileMatch.results = addContextToEditorMatches(textSearchResults, model, query); } else { localResults.set(resource, null); } }); } return { results: localResults, limitHit }; } private matches(resource: uri, query: ITextQuery): boolean { return pathIncludedInQuery(query, resource.fsPath); } clearCache(cacheKey: string): Promise<void> { const clearPs = [ this.diskSearch, ...values(this.fileSearchProviders) ].map(provider => provider && provider.clearCache(cacheKey)); return Promise.all(clearPs) .then(() => { }); } } export class RemoteSearchService extends SearchService { constructor( @IModelService modelService: IModelService, @IEditorService editorService: IEditorService, @ITelemetryService telemetryService: ITelemetryService, @ILogService logService: ILogService, @IExtensionService extensionService: IExtensionService, @IFileService fileService: IFileService ) { super(modelService, editorService, telemetryService, logService, extensionService, fileService); } } registerSingleton(ISearchService, RemoteSearchService, true);
src/vs/workbench/services/search/common/searchService.ts
1
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.9989275336265564, 0.039754804223775864, 0.00016298673290293664, 0.0001719810243230313, 0.19182467460632324 ]
{ "id": 1, "code_window": [ "\n", "\t\t\t\tconst progressCallback = (item: ISearchProgressItem) => {\n", "\t\t\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\t\t\treturn;\n", "\t\t\t\t\t}\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\t// Cancel faster if search was canceled while waiting for extensions\n", "\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\treturn Promise.reject(canceled());\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 126 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { isWindows } from 'vs/base/common/platform'; import { CharCode } from 'vs/base/common/charCode'; import * as paths from 'vs/base/common/path'; const _schemePattern = /^\w[\w\d+.-]*$/; const _singleSlashStart = /^\//; const _doubleSlashStart = /^\/\//; function _validateUri(ret: URI, _strict?: boolean): void { // scheme, must be set if (!ret.scheme && _strict) { throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${ret.authority}", path: "${ret.path}", query: "${ret.query}", fragment: "${ret.fragment}"}`); } // scheme, https://tools.ietf.org/html/rfc3986#section-3.1 // ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) if (ret.scheme && !_schemePattern.test(ret.scheme)) { throw new Error('[UriError]: Scheme contains illegal characters.'); } // path, http://tools.ietf.org/html/rfc3986#section-3.3 // If a URI contains an authority component, then the path component // must either be empty or begin with a slash ("/") character. If a URI // does not contain an authority component, then the path cannot begin // with two slash characters ("//"). if (ret.path) { if (ret.authority) { if (!_singleSlashStart.test(ret.path)) { throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character'); } } else { if (_doubleSlashStart.test(ret.path)) { throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")'); } } } } // for a while we allowed uris *without* schemes and this is the migration // for them, e.g. an uri without scheme and without strict-mode warns and falls // back to the file-scheme. that should cause the least carnage and still be a // clear warning function _schemeFix(scheme: string, _strict: boolean): string { if (!scheme && !_strict) { return 'file'; } return scheme; } // implements a bit of https://tools.ietf.org/html/rfc3986#section-5 function _referenceResolution(scheme: string, path: string): string { // the slash-character is our 'default base' as we don't // support constructing URIs relative to other URIs. This // also means that we alter and potentially break paths. // see https://tools.ietf.org/html/rfc3986#section-5.1.4 switch (scheme) { case 'https': case 'http': case 'file': if (!path) { path = _slash; } else if (path[0] !== _slash) { path = _slash + path; } break; } return path; } const _empty = ''; const _slash = '/'; const _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/; /** * Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986. * This class is a simple parser which creates the basic component parts * (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation * and encoding. * * ```txt * foo://example.com:8042/over/there?name=ferret#nose * \_/ \______________/\_________/ \_________/ \__/ * | | | | | * scheme authority path query fragment * | _____________________|__ * / \ / \ * urn:example:animal:ferret:nose * ``` */ export class URI implements UriComponents { static isUri(thing: any): thing is URI { if (thing instanceof URI) { return true; } if (!thing) { return false; } return typeof (<URI>thing).authority === 'string' && typeof (<URI>thing).fragment === 'string' && typeof (<URI>thing).path === 'string' && typeof (<URI>thing).query === 'string' && typeof (<URI>thing).scheme === 'string' && typeof (<URI>thing).fsPath === 'function' && typeof (<URI>thing).with === 'function' && typeof (<URI>thing).toString === 'function'; } /** * scheme is the 'http' part of 'http://www.msft.com/some/path?query#fragment'. * The part before the first colon. */ readonly scheme: string; /** * authority is the 'www.msft.com' part of 'http://www.msft.com/some/path?query#fragment'. * The part between the first double slashes and the next slash. */ readonly authority: string; /** * path is the '/some/path' part of 'http://www.msft.com/some/path?query#fragment'. */ readonly path: string; /** * query is the 'query' part of 'http://www.msft.com/some/path?query#fragment'. */ readonly query: string; /** * fragment is the 'fragment' part of 'http://www.msft.com/some/path?query#fragment'. */ readonly fragment: string; /** * @internal */ protected constructor(scheme: string, authority?: string, path?: string, query?: string, fragment?: string, _strict?: boolean); /** * @internal */ protected constructor(components: UriComponents); /** * @internal */ protected constructor(schemeOrData: string | UriComponents, authority?: string, path?: string, query?: string, fragment?: string, _strict: boolean = false) { if (typeof schemeOrData === 'object') { this.scheme = schemeOrData.scheme || _empty; this.authority = schemeOrData.authority || _empty; this.path = schemeOrData.path || _empty; this.query = schemeOrData.query || _empty; this.fragment = schemeOrData.fragment || _empty; // no validation because it's this URI // that creates uri components. // _validateUri(this); } else { this.scheme = _schemeFix(schemeOrData, _strict); this.authority = authority || _empty; this.path = _referenceResolution(this.scheme, path || _empty); this.query = query || _empty; this.fragment = fragment || _empty; _validateUri(this, _strict); } } // ---- filesystem path ----------------------- /** * Returns a string representing the corresponding file system path of this URI. * Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the * platform specific path separator. * * * Will *not* validate the path for invalid characters and semantics. * * Will *not* look at the scheme of this URI. * * The result shall *not* be used for display purposes but for accessing a file on disk. * * * The *difference* to `URI#path` is the use of the platform specific separator and the handling * of UNC paths. See the below sample of a file-uri with an authority (UNC path). * * ```ts const u = URI.parse('file://server/c$/folder/file.txt') u.authority === 'server' u.path === '/shares/c$/file.txt' u.fsPath === '\\server\c$\folder\file.txt' ``` * * Using `URI#path` to read a file (using fs-apis) would not be enough because parts of the path, * namely the server name, would be missing. Therefore `URI#fsPath` exists - it's sugar to ease working * with URIs that represent files on disk (`file` scheme). */ get fsPath(): string { // if (this.scheme !== 'file') { // console.warn(`[UriError] calling fsPath with scheme ${this.scheme}`); // } return uriToFsPath(this, false); } // ---- modify to new ------------------------- with(change: { scheme?: string; authority?: string | null; path?: string | null; query?: string | null; fragment?: string | null }): URI { if (!change) { return this; } let { scheme, authority, path, query, fragment } = change; if (scheme === undefined) { scheme = this.scheme; } else if (scheme === null) { scheme = _empty; } if (authority === undefined) { authority = this.authority; } else if (authority === null) { authority = _empty; } if (path === undefined) { path = this.path; } else if (path === null) { path = _empty; } if (query === undefined) { query = this.query; } else if (query === null) { query = _empty; } if (fragment === undefined) { fragment = this.fragment; } else if (fragment === null) { fragment = _empty; } if (scheme === this.scheme && authority === this.authority && path === this.path && query === this.query && fragment === this.fragment) { return this; } return new _URI(scheme, authority, path, query, fragment); } // ---- parse & validate ------------------------ /** * Creates a new URI from a string, e.g. `http://www.msft.com/some/path`, * `file:///usr/home`, or `scheme:with/path`. * * @param value A string which represents an URI (see `URI#toString`). */ static parse(value: string, _strict: boolean = false): URI { const match = _regexp.exec(value); if (!match) { return new _URI(_empty, _empty, _empty, _empty, _empty); } return new _URI( match[2] || _empty, percentDecode(match[4] || _empty), percentDecode(match[5] || _empty), percentDecode(match[7] || _empty), percentDecode(match[9] || _empty), _strict ); } /** * Creates a new URI from a file system path, e.g. `c:\my\files`, * `/usr/home`, or `\\server\share\some\path`. * * The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument * as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as** * `URI.parse('file://' + path)` because the path might contain characters that are * interpreted (# and ?). See the following sample: * ```ts const good = URI.file('/coding/c#/project1'); good.scheme === 'file'; good.path === '/coding/c#/project1'; good.fragment === ''; const bad = URI.parse('file://' + '/coding/c#/project1'); bad.scheme === 'file'; bad.path === '/coding/c'; // path is now broken bad.fragment === '/project1'; ``` * * @param path A file system path (see `URI#fsPath`) */ static file(path: string): URI { let authority = _empty; // normalize to fwd-slashes on windows, // on other systems bwd-slashes are valid // filename character, eg /f\oo/ba\r.txt if (isWindows) { path = path.replace(/\\/g, _slash); } // check for authority as used in UNC shares // or use the path as given if (path[0] === _slash && path[1] === _slash) { const idx = path.indexOf(_slash, 2); if (idx === -1) { authority = path.substring(2); path = _slash; } else { authority = path.substring(2, idx); path = path.substring(idx) || _slash; } } return new _URI('file', authority, path, _empty, _empty); } static from(components: { scheme: string; authority?: string; path?: string; query?: string; fragment?: string }): URI { return new _URI( components.scheme, components.authority, components.path, components.query, components.fragment, ); } /** * Join a URI path with path fragments and normalizes the resulting path. * * @param uri The input URI. * @param pathFragment The path fragment to add to the URI path. * @returns The resulting URI. */ static joinPath(uri: URI, ...pathFragment: string[]): URI { if (!uri.path) { throw new Error(`[UriError]: cannot call joinPaths on URI without path`); } let newPath: string; if (isWindows && uri.scheme === 'file') { newPath = URI.file(paths.win32.join(uriToFsPath(uri, true), ...pathFragment)).path; } else { newPath = paths.posix.join(uri.path, ...pathFragment); } return uri.with({ path: newPath }); } // ---- printing/externalize --------------------------- /** * Creates a string representation for this URI. It's guaranteed that calling * `URI.parse` with the result of this function creates an URI which is equal * to this URI. * * * The result shall *not* be used for display purposes but for externalization or transport. * * The result will be encoded using the percentage encoding and encoding happens mostly * ignore the scheme-specific encoding rules. * * @param skipEncoding Do not encode the result, default is `false` */ toString(skipEncoding: boolean = false): string { return _asFormatted(this, skipEncoding); } toJSON(): UriComponents { return this; } static revive(data: UriComponents | URI): URI; static revive(data: UriComponents | URI | undefined): URI | undefined; static revive(data: UriComponents | URI | null): URI | null; static revive(data: UriComponents | URI | undefined | null): URI | undefined | null; static revive(data: UriComponents | URI | undefined | null): URI | undefined | null { if (!data) { return data; } else if (data instanceof URI) { return data; } else { const result = new _URI(data); result._formatted = (<UriState>data).external; result._fsPath = (<UriState>data)._sep === _pathSepMarker ? (<UriState>data).fsPath : null; return result; } } } export interface UriComponents { scheme: string; authority: string; path: string; query: string; fragment: string; } interface UriState extends UriComponents { $mid: number; external: string; fsPath: string; _sep: 1 | undefined; } const _pathSepMarker = isWindows ? 1 : undefined; // eslint-disable-next-line @typescript-eslint/class-name-casing class _URI extends URI { _formatted: string | null = null; _fsPath: string | null = null; get fsPath(): string { if (!this._fsPath) { this._fsPath = uriToFsPath(this, false); } return this._fsPath; } toString(skipEncoding: boolean = false): string { if (!skipEncoding) { if (!this._formatted) { this._formatted = _asFormatted(this, false); } return this._formatted; } else { // we don't cache that return _asFormatted(this, true); } } toJSON(): UriComponents { const res = <UriState>{ $mid: 1 }; // cached state if (this._fsPath) { res.fsPath = this._fsPath; res._sep = _pathSepMarker; } if (this._formatted) { res.external = this._formatted; } // uri components if (this.path) { res.path = this.path; } if (this.scheme) { res.scheme = this.scheme; } if (this.authority) { res.authority = this.authority; } if (this.query) { res.query = this.query; } if (this.fragment) { res.fragment = this.fragment; } return res; } } // reserved characters: https://tools.ietf.org/html/rfc3986#section-2.2 const encodeTable: { [ch: number]: string } = { [CharCode.Colon]: '%3A', // gen-delims [CharCode.Slash]: '%2F', [CharCode.QuestionMark]: '%3F', [CharCode.Hash]: '%23', [CharCode.OpenSquareBracket]: '%5B', [CharCode.CloseSquareBracket]: '%5D', [CharCode.AtSign]: '%40', [CharCode.ExclamationMark]: '%21', // sub-delims [CharCode.DollarSign]: '%24', [CharCode.Ampersand]: '%26', [CharCode.SingleQuote]: '%27', [CharCode.OpenParen]: '%28', [CharCode.CloseParen]: '%29', [CharCode.Asterisk]: '%2A', [CharCode.Plus]: '%2B', [CharCode.Comma]: '%2C', [CharCode.Semicolon]: '%3B', [CharCode.Equals]: '%3D', [CharCode.Space]: '%20', }; function encodeURIComponentFast(uriComponent: string, allowSlash: boolean): string { let res: string | undefined = undefined; let nativeEncodePos = -1; for (let pos = 0; pos < uriComponent.length; pos++) { const code = uriComponent.charCodeAt(pos); // unreserved characters: https://tools.ietf.org/html/rfc3986#section-2.3 if ( (code >= CharCode.a && code <= CharCode.z) || (code >= CharCode.A && code <= CharCode.Z) || (code >= CharCode.Digit0 && code <= CharCode.Digit9) || code === CharCode.Dash || code === CharCode.Period || code === CharCode.Underline || code === CharCode.Tilde || (allowSlash && code === CharCode.Slash) ) { // check if we are delaying native encode if (nativeEncodePos !== -1) { res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos)); nativeEncodePos = -1; } // check if we write into a new string (by default we try to return the param) if (res !== undefined) { res += uriComponent.charAt(pos); } } else { // encoding needed, we need to allocate a new string if (res === undefined) { res = uriComponent.substr(0, pos); } // check with default table first const escaped = encodeTable[code]; if (escaped !== undefined) { // check if we are delaying native encode if (nativeEncodePos !== -1) { res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos)); nativeEncodePos = -1; } // append escaped variant to result res += escaped; } else if (nativeEncodePos === -1) { // use native encode only when needed nativeEncodePos = pos; } } } if (nativeEncodePos !== -1) { res += encodeURIComponent(uriComponent.substring(nativeEncodePos)); } return res !== undefined ? res : uriComponent; } function encodeURIComponentMinimal(path: string): string { let res: string | undefined = undefined; for (let pos = 0; pos < path.length; pos++) { const code = path.charCodeAt(pos); if (code === CharCode.Hash || code === CharCode.QuestionMark) { if (res === undefined) { res = path.substr(0, pos); } res += encodeTable[code]; } else { if (res !== undefined) { res += path[pos]; } } } return res !== undefined ? res : path; } /** * Compute `fsPath` for the given uri */ export function uriToFsPath(uri: URI, keepDriveLetterCasing: boolean): string { let value: string; if (uri.authority && uri.path.length > 1 && uri.scheme === 'file') { // unc path: file://shares/c$/far/boo value = `//${uri.authority}${uri.path}`; } else if ( uri.path.charCodeAt(0) === CharCode.Slash && (uri.path.charCodeAt(1) >= CharCode.A && uri.path.charCodeAt(1) <= CharCode.Z || uri.path.charCodeAt(1) >= CharCode.a && uri.path.charCodeAt(1) <= CharCode.z) && uri.path.charCodeAt(2) === CharCode.Colon ) { if (!keepDriveLetterCasing) { // windows drive letter: file:///c:/far/boo value = uri.path[1].toLowerCase() + uri.path.substr(2); } else { value = uri.path.substr(1); } } else { // other path value = uri.path; } if (isWindows) { value = value.replace(/\//g, '\\'); } return value; } /** * Create the external version of a uri */ function _asFormatted(uri: URI, skipEncoding: boolean): string { const encoder = !skipEncoding ? encodeURIComponentFast : encodeURIComponentMinimal; let res = ''; let { scheme, authority, path, query, fragment } = uri; if (scheme) { res += scheme; res += ':'; } if (authority || scheme === 'file') { res += _slash; res += _slash; } if (authority) { let idx = authority.indexOf('@'); if (idx !== -1) { // <user>@<auth> const userinfo = authority.substr(0, idx); authority = authority.substr(idx + 1); idx = userinfo.indexOf(':'); if (idx === -1) { res += encoder(userinfo, false); } else { // <user>:<pass>@<auth> res += encoder(userinfo.substr(0, idx), false); res += ':'; res += encoder(userinfo.substr(idx + 1), false); } res += '@'; } authority = authority.toLowerCase(); idx = authority.indexOf(':'); if (idx === -1) { res += encoder(authority, false); } else { // <auth>:<port> res += encoder(authority.substr(0, idx), false); res += authority.substr(idx); } } if (path) { // lower-case windows drive letters in /C:/fff or C:/fff if (path.length >= 3 && path.charCodeAt(0) === CharCode.Slash && path.charCodeAt(2) === CharCode.Colon) { const code = path.charCodeAt(1); if (code >= CharCode.A && code <= CharCode.Z) { path = `/${String.fromCharCode(code + 32)}:${path.substr(3)}`; // "/c:".length === 3 } } else if (path.length >= 2 && path.charCodeAt(1) === CharCode.Colon) { const code = path.charCodeAt(0); if (code >= CharCode.A && code <= CharCode.Z) { path = `${String.fromCharCode(code + 32)}:${path.substr(2)}`; // "/c:".length === 3 } } // encode the rest of the path res += encoder(path, true); } if (query) { res += '?'; res += encoder(query, false); } if (fragment) { res += '#'; res += !skipEncoding ? encodeURIComponentFast(fragment, false) : fragment; } return res; } // --- decode function decodeURIComponentGraceful(str: string): string { try { return decodeURIComponent(str); } catch { if (str.length > 3) { return str.substr(0, 3) + decodeURIComponentGraceful(str.substr(3)); } else { return str; } } } const _rEncodedAsHex = /(%[0-9A-Za-z][0-9A-Za-z])+/g; function percentDecode(str: string): string { if (!str.match(_rEncodedAsHex)) { return str; } return str.replace(_rEncodedAsHex, (match) => decodeURIComponentGraceful(match)); }
src/vs/base/common/uri.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00027673353906720877, 0.00017295757425017655, 0.00016119098290801048, 0.00017126344027929008, 0.000014453711628448218 ]
{ "id": 1, "code_window": [ "\n", "\t\t\t\tconst progressCallback = (item: ISearchProgressItem) => {\n", "\t\t\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\t\t\treturn;\n", "\t\t\t\t\t}\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\t// Cancel faster if search was canceled while waiting for extensions\n", "\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\treturn Promise.reject(canceled());\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 126 }
/*--------------------------------------------------------------------------------------------- * 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 path from 'vs/base/common/path'; import { originalFSPath, joinPath } from 'vs/base/common/resources'; import { Barrier } from 'vs/base/common/async'; import { dispose, toDisposable, DisposableStore } from 'vs/base/common/lifecycle'; import { TernarySearchTree } from 'vs/base/common/map'; import { URI } from 'vs/base/common/uri'; import { ILogService } from 'vs/platform/log/common/log'; import { ExtHostExtensionServiceShape, IInitData, MainContext, MainThreadExtensionServiceShape, MainThreadTelemetryShape, MainThreadWorkspaceShape, IResolveAuthorityResult } from 'vs/workbench/api/common/extHost.protocol'; import { ExtHostConfiguration, IExtHostConfiguration } from 'vs/workbench/api/common/extHostConfiguration'; import { ActivatedExtension, EmptyExtension, ExtensionActivationReason, ExtensionActivationTimes, ExtensionActivationTimesBuilder, ExtensionsActivator, IExtensionAPI, IExtensionModule, HostExtension, ExtensionActivationTimesFragment } from 'vs/workbench/api/common/extHostExtensionActivator'; import { ExtHostStorage, IExtHostStorage } from 'vs/workbench/api/common/extHostStorage'; import { ExtHostWorkspace, IExtHostWorkspace } from 'vs/workbench/api/common/extHostWorkspace'; import { ExtensionActivationError, checkProposedApiEnabled } from 'vs/workbench/services/extensions/common/extensions'; import { ExtensionDescriptionRegistry } from 'vs/workbench/services/extensions/common/extensionDescriptionRegistry'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import * as errors from 'vs/base/common/errors'; import type * as vscode from 'vscode'; import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions'; import { Schemas } from 'vs/base/common/network'; import { VSBuffer } from 'vs/base/common/buffer'; import { ExtensionMemento } from 'vs/workbench/api/common/extHostMemento'; import { RemoteAuthorityResolverError, ExtensionMode } from 'vs/workbench/api/common/extHostTypes'; import { ResolvedAuthority, ResolvedOptions, RemoteAuthorityResolverErrorCode } from 'vs/platform/remote/common/remoteAuthorityResolver'; import { IInstantiationService, createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { IExtHostInitDataService } from 'vs/workbench/api/common/extHostInitDataService'; import { IExtensionStoragePaths } from 'vs/workbench/api/common/extHostStoragePaths'; import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { IExtHostTunnelService } from 'vs/workbench/api/common/extHostTunnelService'; import { IExtHostTerminalService } from 'vs/workbench/api/common/extHostTerminalService'; interface ITestRunner { /** Old test runner API, as exported from `vscode/lib/testrunner` */ run(testsRoot: string, clb: (error: Error, failures?: number) => void): void; } interface INewTestRunner { /** New test runner API, as explained in the extension test doc */ run(): Promise<void>; } export const IHostUtils = createDecorator<IHostUtils>('IHostUtils'); export interface IHostUtils { _serviceBrand: undefined; exit(code?: number): void; exists(path: string): Promise<boolean>; realpath(path: string): Promise<string>; } type TelemetryActivationEventFragment = { id: { classification: 'PublicNonPersonalData', purpose: 'FeatureInsight' }; name: { classification: 'PublicNonPersonalData', purpose: 'FeatureInsight' }; extensionVersion: { classification: 'PublicNonPersonalData', purpose: 'FeatureInsight' }; publisherDisplayName: { classification: 'SystemMetaData', purpose: 'FeatureInsight' }; activationEvents: { classification: 'SystemMetaData', purpose: 'FeatureInsight' }; isBuiltin: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true }; reason: { classification: 'SystemMetaData', purpose: 'FeatureInsight' }; reasonId: { classification: 'PublicNonPersonalData', purpose: 'FeatureInsight' }; }; export abstract class AbstractExtHostExtensionService implements ExtHostExtensionServiceShape { readonly _serviceBrand: undefined; private static readonly WORKSPACE_CONTAINS_TIMEOUT = 7000; protected readonly _hostUtils: IHostUtils; protected readonly _initData: IInitData; protected readonly _extHostContext: IExtHostRpcService; protected readonly _instaService: IInstantiationService; protected readonly _extHostWorkspace: ExtHostWorkspace; protected readonly _extHostConfiguration: ExtHostConfiguration; protected readonly _logService: ILogService; protected readonly _extHostTunnelService: IExtHostTunnelService; protected readonly _extHostTerminalService: IExtHostTerminalService; protected readonly _mainThreadWorkspaceProxy: MainThreadWorkspaceShape; protected readonly _mainThreadTelemetryProxy: MainThreadTelemetryShape; protected readonly _mainThreadExtensionsProxy: MainThreadExtensionServiceShape; private readonly _almostReadyToRunExtensions: Barrier; private readonly _readyToStartExtensionHost: Barrier; private readonly _readyToRunExtensions: Barrier; protected readonly _registry: ExtensionDescriptionRegistry; private readonly _storage: ExtHostStorage; private readonly _storagePath: IExtensionStoragePaths; private readonly _activator: ExtensionsActivator; private _extensionPathIndex: Promise<TernarySearchTree<string, IExtensionDescription>> | null; private readonly _resolvers: { [authorityPrefix: string]: vscode.RemoteAuthorityResolver; }; private _started: boolean; private readonly _disposables: DisposableStore; constructor( @IInstantiationService instaService: IInstantiationService, @IHostUtils hostUtils: IHostUtils, @IExtHostRpcService extHostContext: IExtHostRpcService, @IExtHostWorkspace extHostWorkspace: IExtHostWorkspace, @IExtHostConfiguration extHostConfiguration: IExtHostConfiguration, @ILogService logService: ILogService, @IExtHostInitDataService initData: IExtHostInitDataService, @IExtensionStoragePaths storagePath: IExtensionStoragePaths, @IExtHostTunnelService extHostTunnelService: IExtHostTunnelService, @IExtHostTerminalService extHostTerminalService: IExtHostTerminalService ) { this._hostUtils = hostUtils; this._extHostContext = extHostContext; this._initData = initData; this._extHostWorkspace = extHostWorkspace; this._extHostConfiguration = extHostConfiguration; this._logService = logService; this._extHostTunnelService = extHostTunnelService; this._extHostTerminalService = extHostTerminalService; this._disposables = new DisposableStore(); this._mainThreadWorkspaceProxy = this._extHostContext.getProxy(MainContext.MainThreadWorkspace); this._mainThreadTelemetryProxy = this._extHostContext.getProxy(MainContext.MainThreadTelemetry); this._mainThreadExtensionsProxy = this._extHostContext.getProxy(MainContext.MainThreadExtensionService); this._almostReadyToRunExtensions = new Barrier(); this._readyToStartExtensionHost = new Barrier(); this._readyToRunExtensions = new Barrier(); this._registry = new ExtensionDescriptionRegistry(this._initData.extensions); this._storage = new ExtHostStorage(this._extHostContext); this._storagePath = storagePath; this._instaService = instaService.createChild(new ServiceCollection( [IExtHostStorage, this._storage] )); const hostExtensions = new Set<string>(); this._initData.hostExtensions.forEach((extensionId) => hostExtensions.add(ExtensionIdentifier.toKey(extensionId))); this._activator = new ExtensionsActivator( this._registry, this._initData.resolvedExtensions, this._initData.hostExtensions, { onExtensionActivationError: (extensionId: ExtensionIdentifier, error: ExtensionActivationError): void => { this._mainThreadExtensionsProxy.$onExtensionActivationError(extensionId, error); }, actualActivateExtension: async (extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<ActivatedExtension> => { if (hostExtensions.has(ExtensionIdentifier.toKey(extensionId))) { await this._mainThreadExtensionsProxy.$activateExtension(extensionId, reason); return new HostExtension(); } const extensionDescription = this._registry.getExtensionDescription(extensionId)!; return this._activateExtension(extensionDescription, reason); } }, this._logService ); this._extensionPathIndex = null; this._resolvers = Object.create(null); this._started = false; } public async initialize(): Promise<void> { try { await this._beforeAlmostReadyToRunExtensions(); this._almostReadyToRunExtensions.open(); await this._extHostWorkspace.waitForInitializeCall(); this._readyToStartExtensionHost.open(); if (this._initData.autoStart) { this._startExtensionHost(); } } catch (err) { errors.onUnexpectedError(err); } } protected abstract _beforeAlmostReadyToRunExtensions(): Promise<void>; public async deactivateAll(): Promise<void> { let allPromises: Promise<void>[] = []; try { const allExtensions = this._registry.getAllExtensionDescriptions(); const allExtensionsIds = allExtensions.map(ext => ext.identifier); const activatedExtensions = allExtensionsIds.filter(id => this.isActivated(id)); allPromises = activatedExtensions.map((extensionId) => { return this._deactivate(extensionId); }); } catch (err) { // TODO: write to log once we have one } await Promise.all(allPromises); } public isActivated(extensionId: ExtensionIdentifier): boolean { if (this._readyToRunExtensions.isOpen()) { return this._activator.isActivated(extensionId); } return false; } private _activateByEvent(activationEvent: string, startup: boolean): Promise<void> { return this._activator.activateByEvent(activationEvent, startup); } private _activateById(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<void> { return this._activator.activateById(extensionId, reason); } public activateByIdWithErrors(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<void> { return this._activateById(extensionId, reason).then(() => { const extension = this._activator.getActivatedExtension(extensionId); if (extension.activationFailed) { // activation failed => bubble up the error as the promise result return Promise.reject(extension.activationFailedError); } return undefined; }); } public getExtensionRegistry(): Promise<ExtensionDescriptionRegistry> { return this._readyToRunExtensions.wait().then(_ => this._registry); } public getExtensionExports(extensionId: ExtensionIdentifier): IExtensionAPI | null | undefined { if (this._readyToRunExtensions.isOpen()) { return this._activator.getActivatedExtension(extensionId).exports; } else { return null; } } // create trie to enable fast 'filename -> extension id' look up public getExtensionPathIndex(): Promise<TernarySearchTree<string, IExtensionDescription>> { if (!this._extensionPathIndex) { const tree = TernarySearchTree.forPaths<IExtensionDescription>(); const extensions = this._registry.getAllExtensionDescriptions().map(ext => { if (!ext.main) { return undefined; } return this._hostUtils.realpath(ext.extensionLocation.fsPath).then(value => tree.set(URI.file(value).fsPath, ext)); }); this._extensionPathIndex = Promise.all(extensions).then(() => tree); } return this._extensionPathIndex; } private _deactivate(extensionId: ExtensionIdentifier): Promise<void> { let result = Promise.resolve(undefined); if (!this._readyToRunExtensions.isOpen()) { return result; } if (!this._activator.isActivated(extensionId)) { return result; } const extension = this._activator.getActivatedExtension(extensionId); if (!extension) { return result; } // call deactivate if available try { if (typeof extension.module.deactivate === 'function') { result = Promise.resolve(extension.module.deactivate()).then(undefined, (err) => { // TODO: Do something with err if this is not the shutdown case return Promise.resolve(undefined); }); } } catch (err) { // TODO: Do something with err if this is not the shutdown case } // clean up subscriptions try { dispose(extension.subscriptions); } catch (err) { // TODO: Do something with err if this is not the shutdown case } return result; } // --- impl private _activateExtension(extensionDescription: IExtensionDescription, reason: ExtensionActivationReason): Promise<ActivatedExtension> { this._mainThreadExtensionsProxy.$onWillActivateExtension(extensionDescription.identifier); return this._doActivateExtension(extensionDescription, reason).then((activatedExtension) => { const activationTimes = activatedExtension.activationTimes; this._mainThreadExtensionsProxy.$onDidActivateExtension(extensionDescription.identifier, activationTimes.codeLoadingTime, activationTimes.activateCallTime, activationTimes.activateResolvedTime, reason); this._logExtensionActivationTimes(extensionDescription, reason, 'success', activationTimes); return activatedExtension; }, (err) => { this._logExtensionActivationTimes(extensionDescription, reason, 'failure'); throw err; }); } private _logExtensionActivationTimes(extensionDescription: IExtensionDescription, reason: ExtensionActivationReason, outcome: string, activationTimes?: ExtensionActivationTimes) { const event = getTelemetryActivationEvent(extensionDescription, reason); type ExtensionActivationTimesClassification = { outcome: { classification: 'SystemMetaData', purpose: 'FeatureInsight' }; } & TelemetryActivationEventFragment & ExtensionActivationTimesFragment; type ExtensionActivationTimesEvent = { outcome: string } & ActivationTimesEvent & TelemetryActivationEvent; type ActivationTimesEvent = { startup?: boolean; codeLoadingTime?: number; activateCallTime?: number; activateResolvedTime?: number; }; this._mainThreadTelemetryProxy.$publicLog2<ExtensionActivationTimesEvent, ExtensionActivationTimesClassification>('extensionActivationTimes', { ...event, ...(activationTimes || {}), outcome }); } private _doActivateExtension(extensionDescription: IExtensionDescription, reason: ExtensionActivationReason): Promise<ActivatedExtension> { const event = getTelemetryActivationEvent(extensionDescription, reason); type ActivatePluginClassification = {} & TelemetryActivationEventFragment; this._mainThreadTelemetryProxy.$publicLog2<TelemetryActivationEvent, ActivatePluginClassification>('activatePlugin', event); if (!extensionDescription.main) { // Treat the extension as being empty => NOT AN ERROR CASE return Promise.resolve(new EmptyExtension(ExtensionActivationTimes.NONE)); } this._logService.info(`ExtensionService#_doActivateExtension ${extensionDescription.identifier.value} ${JSON.stringify(reason)}`); this._logService.flush(); const activationTimesBuilder = new ExtensionActivationTimesBuilder(reason.startup); return Promise.all([ this._loadCommonJSModule<IExtensionModule>(joinPath(extensionDescription.extensionLocation, extensionDescription.main), activationTimesBuilder), this._loadExtensionContext(extensionDescription) ]).then(values => { return AbstractExtHostExtensionService._callActivate(this._logService, extensionDescription.identifier, values[0], values[1], activationTimesBuilder); }); } protected abstract _loadCommonJSModule<T>(module: URI, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<T>; private _loadExtensionContext(extensionDescription: IExtensionDescription): Promise<vscode.ExtensionContext> { const globalState = new ExtensionMemento(extensionDescription.identifier.value, true, this._storage); const workspaceState = new ExtensionMemento(extensionDescription.identifier.value, false, this._storage); const extensionMode = extensionDescription.isUnderDevelopment ? (this._initData.environment.extensionTestsLocationURI ? ExtensionMode.Test : ExtensionMode.Development) : ExtensionMode.Release; this._logService.trace(`ExtensionService#loadExtensionContext ${extensionDescription.identifier.value}`); return Promise.all([ globalState.whenReady, workspaceState.whenReady, this._storagePath.whenReady ]).then(() => { const that = this; return Object.freeze<vscode.ExtensionContext>({ globalState, workspaceState, subscriptions: [], get extensionUri() { return extensionDescription.extensionLocation; }, get extensionPath() { return extensionDescription.extensionLocation.fsPath; }, get storagePath() { return that._storagePath.workspaceValue(extensionDescription); }, get globalStoragePath() { return that._storagePath.globalValue(extensionDescription); }, asAbsolutePath(relativePath: string) { return path.join(extensionDescription.extensionLocation.fsPath, relativePath); }, get logPath() { return path.join(that._initData.logsLocation.fsPath, extensionDescription.identifier.value); }, get extensionMode() { checkProposedApiEnabled(extensionDescription); return extensionMode; }, get environmentVariableCollection() { return that._extHostTerminalService.getEnvironmentVariableCollection(extensionDescription); } }); }); } private static _callActivate(logService: ILogService, extensionId: ExtensionIdentifier, extensionModule: IExtensionModule, context: vscode.ExtensionContext, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<ActivatedExtension> { // Make sure the extension's surface is not undefined extensionModule = extensionModule || { activate: undefined, deactivate: undefined }; return this._callActivateOptional(logService, extensionId, extensionModule, context, activationTimesBuilder).then((extensionExports) => { return new ActivatedExtension(false, null, activationTimesBuilder.build(), extensionModule, extensionExports, context.subscriptions); }); } private static _callActivateOptional(logService: ILogService, extensionId: ExtensionIdentifier, extensionModule: IExtensionModule, context: vscode.ExtensionContext, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<IExtensionAPI> { if (typeof extensionModule.activate === 'function') { try { activationTimesBuilder.activateCallStart(); logService.trace(`ExtensionService#_callActivateOptional ${extensionId.value}`); const scope = typeof global === 'object' ? global : self; // `global` is nodejs while `self` is for workers const activateResult: Promise<IExtensionAPI> = extensionModule.activate.apply(scope, [context]); activationTimesBuilder.activateCallStop(); activationTimesBuilder.activateResolveStart(); return Promise.resolve(activateResult).then((value) => { activationTimesBuilder.activateResolveStop(); return value; }); } catch (err) { return Promise.reject(err); } } else { // No activate found => the module is the extension's exports return Promise.resolve<IExtensionAPI>(extensionModule); } } // -- eager activation // Handle "eager" activation extensions private _handleEagerExtensions(): Promise<void> { this._activateByEvent('*', true).then(undefined, (err) => { this._logService.error(err); }); this._disposables.add(this._extHostWorkspace.onDidChangeWorkspace((e) => this._handleWorkspaceContainsEagerExtensions(e.added))); const folders = this._extHostWorkspace.workspace ? this._extHostWorkspace.workspace.folders : []; return this._handleWorkspaceContainsEagerExtensions(folders); } private _handleWorkspaceContainsEagerExtensions(folders: ReadonlyArray<vscode.WorkspaceFolder>): Promise<void> { if (folders.length === 0) { return Promise.resolve(undefined); } return Promise.all( this._registry.getAllExtensionDescriptions().map((desc) => { return this._handleWorkspaceContainsEagerExtension(folders, desc); }) ).then(() => { }); } private _handleWorkspaceContainsEagerExtension(folders: ReadonlyArray<vscode.WorkspaceFolder>, desc: IExtensionDescription): Promise<void> { const activationEvents = desc.activationEvents; if (!activationEvents) { return Promise.resolve(undefined); } if (this.isActivated(desc.identifier)) { return Promise.resolve(undefined); } const fileNames: string[] = []; const globPatterns: string[] = []; const localWithRemote = !this._initData.remote.isRemote && !!this._initData.remote.authority; for (const activationEvent of activationEvents) { if (/^workspaceContains:/.test(activationEvent)) { const fileNameOrGlob = activationEvent.substr('workspaceContains:'.length); if (fileNameOrGlob.indexOf('*') >= 0 || fileNameOrGlob.indexOf('?') >= 0 || localWithRemote) { globPatterns.push(fileNameOrGlob); } else { fileNames.push(fileNameOrGlob); } } } if (fileNames.length === 0 && globPatterns.length === 0) { return Promise.resolve(undefined); } const fileNamePromise = Promise.all(fileNames.map((fileName) => this._activateIfFileName(folders, desc.identifier, fileName))).then(() => { }); const globPatternPromise = this._activateIfGlobPatterns(folders, desc.identifier, globPatterns); return Promise.all([fileNamePromise, globPatternPromise]).then(() => { }); } private async _activateIfFileName(folders: ReadonlyArray<vscode.WorkspaceFolder>, extensionId: ExtensionIdentifier, fileName: string): Promise<void> { // find exact path for (const { uri } of folders) { if (await this._hostUtils.exists(path.join(URI.revive(uri).fsPath, fileName))) { // the file was found return ( this._activateById(extensionId, { startup: true, extensionId, activationEvent: `workspaceContains:${fileName}` }) .then(undefined, err => this._logService.error(err)) ); } } return undefined; } private async _activateIfGlobPatterns(folders: ReadonlyArray<vscode.WorkspaceFolder>, extensionId: ExtensionIdentifier, globPatterns: string[]): Promise<void> { this._logService.trace(`extensionHostMain#activateIfGlobPatterns: fileSearch, extension: ${extensionId.value}, entryPoint: workspaceContains`); if (globPatterns.length === 0) { return Promise.resolve(undefined); } const tokenSource = new CancellationTokenSource(); const searchP = this._mainThreadWorkspaceProxy.$checkExists(folders.map(folder => folder.uri), globPatterns, tokenSource.token); const timer = setTimeout(async () => { tokenSource.cancel(); this._activateById(extensionId, { startup: true, extensionId, activationEvent: `workspaceContainsTimeout:${globPatterns.join(',')}` }) .then(undefined, err => this._logService.error(err)); }, AbstractExtHostExtensionService.WORKSPACE_CONTAINS_TIMEOUT); let exists: boolean = false; try { exists = await searchP; } catch (err) { if (!errors.isPromiseCanceledError(err)) { this._logService.error(err); } } tokenSource.dispose(); clearTimeout(timer); if (exists) { // a file was found matching one of the glob patterns return ( this._activateById(extensionId, { startup: true, extensionId, activationEvent: `workspaceContains:${globPatterns.join(',')}` }) .then(undefined, err => this._logService.error(err)) ); } return Promise.resolve(undefined); } private _handleExtensionTests(): Promise<void> { return this._doHandleExtensionTests().then(undefined, error => { console.error(error); // ensure any error message makes it onto the console return Promise.reject(error); }); } private async _doHandleExtensionTests(): Promise<void> { const { extensionDevelopmentLocationURI, extensionTestsLocationURI } = this._initData.environment; if (!(extensionDevelopmentLocationURI && extensionTestsLocationURI && extensionTestsLocationURI.scheme === Schemas.file)) { return Promise.resolve(undefined); } const extensionTestsPath = originalFSPath(extensionTestsLocationURI); // Require the test runner via node require from the provided path let testRunner: ITestRunner | INewTestRunner | undefined; let requireError: Error | undefined; try { testRunner = await this._loadCommonJSModule(URI.file(extensionTestsPath), new ExtensionActivationTimesBuilder(false)); } catch (error) { requireError = error; } // Execute the runner if it follows the old `run` spec if (testRunner && typeof testRunner.run === 'function') { return new Promise<void>((c, e) => { const oldTestRunnerCallback = (error: Error, failures: number | undefined) => { if (error) { e(error.toString()); } else { c(undefined); } // after tests have run, we shutdown the host this._gracefulExit(error || (typeof failures === 'number' && failures > 0) ? 1 /* ERROR */ : 0 /* OK */); }; const runResult = testRunner!.run(extensionTestsPath, oldTestRunnerCallback); // Using the new API `run(): Promise<void>` if (runResult && runResult.then) { runResult .then(() => { c(); this._gracefulExit(0); }) .catch((err: Error) => { e(err.toString()); this._gracefulExit(1); }); } }); } // Otherwise make sure to shutdown anyway even in case of an error else { this._gracefulExit(1 /* ERROR */); } return Promise.reject(new Error(requireError ? requireError.toString() : nls.localize('extensionTestError', "Path {0} does not point to a valid extension test runner.", extensionTestsPath))); } private _gracefulExit(code: number): void { // to give the PH process a chance to flush any outstanding console // messages to the main process, we delay the exit() by some time setTimeout(() => { // If extension tests are running, give the exit code to the renderer if (this._initData.remote.isRemote && !!this._initData.environment.extensionTestsLocationURI) { this._mainThreadExtensionsProxy.$onExtensionHostExit(code); return; } this._hostUtils.exit(code); }, 500); } private _startExtensionHost(): Promise<void> { if (this._started) { throw new Error(`Extension host is already started!`); } this._started = true; return this._readyToStartExtensionHost.wait() .then(() => this._readyToRunExtensions.open()) .then(() => this._handleEagerExtensions()) .then(() => this._handleExtensionTests()) .then(() => { this._logService.info(`eager extensions activated`); }); } // -- called by extensions public registerRemoteAuthorityResolver(authorityPrefix: string, resolver: vscode.RemoteAuthorityResolver): vscode.Disposable { this._resolvers[authorityPrefix] = resolver; return toDisposable(() => { delete this._resolvers[authorityPrefix]; }); } // -- called by main thread public async $resolveAuthority(remoteAuthority: string, resolveAttempt: number): Promise<IResolveAuthorityResult> { const authorityPlusIndex = remoteAuthority.indexOf('+'); if (authorityPlusIndex === -1) { throw new Error(`Not an authority that can be resolved!`); } const authorityPrefix = remoteAuthority.substr(0, authorityPlusIndex); await this._almostReadyToRunExtensions.wait(); await this._activateByEvent(`onResolveRemoteAuthority:${authorityPrefix}`, false); const resolver = this._resolvers[authorityPrefix]; if (!resolver) { return { type: 'error', error: { code: RemoteAuthorityResolverErrorCode.NoResolverFound, message: `No remote extension installed to resolve ${authorityPrefix}.`, detail: undefined } }; } try { const result = await resolver.resolve(remoteAuthority, { resolveAttempt }); this._disposables.add(await this._extHostTunnelService.setTunnelExtensionFunctions(resolver)); // Split merged API result into separate authority/options const authority: ResolvedAuthority = { authority: remoteAuthority, host: result.host, port: result.port }; const options: ResolvedOptions = { extensionHostEnv: result.extensionHostEnv }; return { type: 'ok', value: { authority, options, tunnelInformation: { environmentTunnels: result.environmentTunnels } } }; } catch (err) { if (err instanceof RemoteAuthorityResolverError) { return { type: 'error', error: { code: err._code, message: err._message, detail: err._detail } }; } throw err; } } public $startExtensionHost(enabledExtensionIds: ExtensionIdentifier[]): Promise<void> { this._registry.keepOnly(enabledExtensionIds); return this._startExtensionHost(); } public $activateByEvent(activationEvent: string): Promise<void> { return ( this._readyToRunExtensions.wait() .then(_ => this._activateByEvent(activationEvent, false)) ); } public async $activate(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<boolean> { await this._readyToRunExtensions.wait(); if (!this._registry.getExtensionDescription(extensionId)) { // unknown extension => ignore return false; } await this._activateById(extensionId, reason); return true; } public async $deltaExtensions(toAdd: IExtensionDescription[], toRemove: ExtensionIdentifier[]): Promise<void> { toAdd.forEach((extension) => (<any>extension).extensionLocation = URI.revive(extension.extensionLocation)); const trie = await this.getExtensionPathIndex(); await Promise.all(toRemove.map(async (extensionId) => { const extensionDescription = this._registry.getExtensionDescription(extensionId); if (!extensionDescription) { return; } const realpathValue = await this._hostUtils.realpath(extensionDescription.extensionLocation.fsPath); trie.delete(URI.file(realpathValue).fsPath); })); await Promise.all(toAdd.map(async (extensionDescription) => { const realpathValue = await this._hostUtils.realpath(extensionDescription.extensionLocation.fsPath); trie.set(URI.file(realpathValue).fsPath, extensionDescription); })); this._registry.deltaExtensions(toAdd, toRemove); return Promise.resolve(undefined); } public async $test_latency(n: number): Promise<number> { return n; } public async $test_up(b: VSBuffer): Promise<number> { return b.byteLength; } public async $test_down(size: number): Promise<VSBuffer> { let buff = VSBuffer.alloc(size); let value = Math.random() % 256; for (let i = 0; i < size; i++) { buff.writeUInt8(value, i); } return buff; } public abstract async $setRemoteEnvironment(env: { [key: string]: string | null }): Promise<void>; } type TelemetryActivationEvent = { id: string; name: string; extensionVersion: string; publisherDisplayName: string; activationEvents: string | null; isBuiltin: boolean; reason: string; reasonId: string; }; function getTelemetryActivationEvent(extensionDescription: IExtensionDescription, reason: ExtensionActivationReason): TelemetryActivationEvent { const event = { id: extensionDescription.identifier.value, name: extensionDescription.name, extensionVersion: extensionDescription.version, publisherDisplayName: extensionDescription.publisher, activationEvents: extensionDescription.activationEvents ? extensionDescription.activationEvents.join(',') : null, isBuiltin: extensionDescription.isBuiltin, reason: reason.activationEvent, reasonId: reason.extensionId.value, }; return event; } export const IExtHostExtensionService = createDecorator<IExtHostExtensionService>('IExtHostExtensionService'); export interface IExtHostExtensionService extends AbstractExtHostExtensionService { _serviceBrand: undefined; initialize(): Promise<void>; isActivated(extensionId: ExtensionIdentifier): boolean; activateByIdWithErrors(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<void>; deactivateAll(): Promise<void>; getExtensionExports(extensionId: ExtensionIdentifier): IExtensionAPI | null | undefined; getExtensionRegistry(): Promise<ExtensionDescriptionRegistry>; getExtensionPathIndex(): Promise<TernarySearchTree<string, IExtensionDescription>>; registerRemoteAuthorityResolver(authorityPrefix: string, resolver: vscode.RemoteAuthorityResolver): vscode.Disposable; }
src/vs/workbench/api/common/extHostExtensionService.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00031494349241256714, 0.00017330548143945634, 0.00016317878908012062, 0.00016996051999740303, 0.00001871406493592076 ]
{ "id": 1, "code_window": [ "\n", "\t\t\t\tconst progressCallback = (item: ISearchProgressItem) => {\n", "\t\t\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\t\t\treturn;\n", "\t\t\t\t\t}\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\t// Cancel faster if search was canceled while waiting for extensions\n", "\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\treturn Promise.reject(canceled());\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 126 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { BrandedService, IConstructorSignature1 } from 'vs/platform/instantiation/common/instantiation'; import { INotebookEditor, INotebookEditorContribution } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; export type INotebookEditorContributionCtor = IConstructorSignature1<INotebookEditor, INotebookEditorContribution>; export interface INotebookEditorContributionDescription { id: string; ctor: INotebookEditorContributionCtor; } 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(); } }
src/vs/workbench/contrib/notebook/browser/notebookEditorExtensions.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00035837653558701277, 0.00020985185983590782, 0.0001682013098616153, 0.00017437052156310529, 0.00007429950346704572 ]
{ "id": 2, "code_window": [ "\n", "\t\t\t\t\tif (onProgress) {\n", "\t\t\t\t\t\tonProgress(item);\n", "\t\t\t\t\t}\n", "\t\t\t\t};\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\tconst progressCallback = (item: ISearchProgressItem) => {\n", "\t\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\t\treturn;\n", "\t\t\t\t}\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 131 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as arrays from 'vs/base/common/arrays'; import { CancellationToken } from 'vs/base/common/cancellation'; import { canceled } from 'vs/base/common/errors'; import { Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { keys, ResourceMap, values } from 'vs/base/common/map'; import { Schemas } from 'vs/base/common/network'; import { StopWatch } from 'vs/base/common/stopwatch'; import { URI as uri } from 'vs/base/common/uri'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IFileService } from 'vs/platform/files/common/files'; import { ILogService } from 'vs/platform/log/common/log'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { deserializeSearchError, FileMatch, ICachedSearchStats, IFileMatch, IFileQuery, IFileSearchStats, IFolderQuery, IProgressMessage, ISearchComplete, ISearchEngineStats, ISearchProgressItem, ISearchQuery, ISearchResultProvider, ISearchService, ITextQuery, pathIncludedInQuery, QueryType, SearchError, SearchErrorCode, SearchProviderType, isFileMatch, isProgressMessage } from 'vs/workbench/services/search/common/search'; import { addContextToEditorMatches, editorMatchesToTextSearchResults } from 'vs/workbench/services/search/common/searchHelpers'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { DeferredPromise } from 'vs/base/test/common/utils'; export class SearchService extends Disposable implements ISearchService { _serviceBrand: undefined; protected diskSearch: ISearchResultProvider | null = null; private readonly fileSearchProviders = new Map<string, ISearchResultProvider>(); private readonly textSearchProviders = new Map<string, ISearchResultProvider>(); private deferredFileSearchesByScheme = new Map<string, DeferredPromise<ISearchResultProvider>>(); private deferredTextSearchesByScheme = new Map<string, DeferredPromise<ISearchResultProvider>>(); constructor( private readonly modelService: IModelService, private readonly editorService: IEditorService, private readonly telemetryService: ITelemetryService, private readonly logService: ILogService, private readonly extensionService: IExtensionService, private readonly fileService: IFileService ) { super(); } registerSearchResultProvider(scheme: string, type: SearchProviderType, provider: ISearchResultProvider): IDisposable { let list: Map<string, ISearchResultProvider>; let deferredMap: Map<string, DeferredPromise<ISearchResultProvider>>; if (type === SearchProviderType.file) { list = this.fileSearchProviders; deferredMap = this.deferredFileSearchesByScheme; } else if (type === SearchProviderType.text) { list = this.textSearchProviders; deferredMap = this.deferredTextSearchesByScheme; } else { throw new Error('Unknown SearchProviderType'); } list.set(scheme, provider); if (deferredMap.has(scheme)) { deferredMap.get(scheme)!.complete(provider); deferredMap.delete(scheme); } return toDisposable(() => { list.delete(scheme); }); } async textSearch(query: ITextQuery, token?: CancellationToken, onProgress?: (item: ISearchProgressItem) => void): Promise<ISearchComplete> { // Get local results from dirty/untitled const localResults = this.getLocalResults(query); if (onProgress) { arrays.coalesce([...localResults.results.values()]).forEach(onProgress); } const onProviderProgress = (progress: ISearchProgressItem) => { if (isFileMatch(progress)) { // Match if (!localResults.results.has(progress.resource) && onProgress) { // don't override local results onProgress(progress); } } else if (onProgress) { // Progress onProgress(<IProgressMessage>progress); } if (isProgressMessage(progress)) { this.logService.debug('SearchService#search', progress.message); } }; const otherResults = await this.doSearch(query, token, onProviderProgress); return { ...otherResults, ...{ limitHit: otherResults.limitHit || localResults.limitHit }, results: [...otherResults.results, ...arrays.coalesce([...localResults.results.values()])] }; } fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { return this.doSearch(query, token); } private doSearch(query: ISearchQuery, token?: CancellationToken, onProgress?: (item: ISearchProgressItem) => void): Promise<ISearchComplete> { this.logService.trace('SearchService#search', JSON.stringify(query)); const schemesInQuery = this.getSchemesInQuery(query); const providerActivations: Promise<any>[] = [Promise.resolve(null)]; schemesInQuery.forEach(scheme => providerActivations.push(this.extensionService.activateByEvent(`onSearch:${scheme}`))); providerActivations.push(this.extensionService.activateByEvent('onSearch:file')); const providerPromise = Promise.all(providerActivations) .then(() => this.extensionService.whenInstalledExtensionsRegistered()) .then(() => { // Cancel faster if search was canceled while waiting for extensions if (token && token.isCancellationRequested) { return Promise.reject(canceled()); } const progressCallback = (item: ISearchProgressItem) => { if (token && token.isCancellationRequested) { return; } if (onProgress) { onProgress(item); } }; return this.searchWithProviders(query, progressCallback, token); }) .then(completes => { completes = arrays.coalesce(completes); if (!completes.length) { return { limitHit: false, results: [] }; } return <ISearchComplete>{ limitHit: completes[0] && completes[0].limitHit, stats: completes[0].stats, results: arrays.flatten(completes.map((c: ISearchComplete) => c.results)) }; }); return new Promise((resolve, reject) => { if (token) { token.onCancellationRequested(() => { reject(canceled()); }); } providerPromise.then(resolve, reject); }); } private getSchemesInQuery(query: ISearchQuery): Set<string> { const schemes = new Set<string>(); if (query.folderQueries) { query.folderQueries.forEach(fq => schemes.add(fq.folder.scheme)); } if (query.extraFileResources) { query.extraFileResources.forEach(extraFile => schemes.add(extraFile.scheme)); } return schemes; } private async waitForProvider(queryType: QueryType, scheme: string): Promise<ISearchResultProvider> { let deferredMap: Map<string, DeferredPromise<ISearchResultProvider>> = queryType === QueryType.File ? this.deferredFileSearchesByScheme : this.deferredTextSearchesByScheme; if (deferredMap.has(scheme)) { return deferredMap.get(scheme)!.p; } else { const deferred = new DeferredPromise<ISearchResultProvider>(); deferredMap.set(scheme, deferred); return deferred.p; } } private async searchWithProviders(query: ISearchQuery, onProviderProgress: (progress: ISearchProgressItem) => void, token?: CancellationToken) { const e2eSW = StopWatch.create(false); const diskSearchQueries: IFolderQuery[] = []; const searchPs: Promise<ISearchComplete>[] = []; const fqs = this.groupFolderQueriesByScheme(query); await Promise.all(keys(fqs).map(async scheme => { const schemeFQs = fqs.get(scheme)!; let provider = query.type === QueryType.File ? this.fileSearchProviders.get(scheme) : this.textSearchProviders.get(scheme); if (!provider && scheme === Schemas.file) { diskSearchQueries.push(...schemeFQs); } else { if (!provider) { if (scheme !== Schemas.vscodeRemote) { console.warn(`No search provider registered for scheme: ${scheme}`); return; } console.warn(`No search provider registered for scheme: ${scheme}, waiting`); provider = await this.waitForProvider(query.type, scheme); } const oneSchemeQuery: ISearchQuery = { ...query, ...{ folderQueries: schemeFQs } }; searchPs.push(query.type === QueryType.File ? provider.fileSearch(<IFileQuery>oneSchemeQuery, token) : provider.textSearch(<ITextQuery>oneSchemeQuery, onProviderProgress, token)); } })); const diskSearchExtraFileResources = query.extraFileResources && query.extraFileResources.filter(res => res.scheme === Schemas.file); if (diskSearchQueries.length || diskSearchExtraFileResources) { const diskSearchQuery: ISearchQuery = { ...query, ...{ folderQueries: diskSearchQueries }, extraFileResources: diskSearchExtraFileResources }; if (this.diskSearch) { searchPs.push(diskSearchQuery.type === QueryType.File ? this.diskSearch.fileSearch(diskSearchQuery, token) : this.diskSearch.textSearch(diskSearchQuery, onProviderProgress, token)); } } return Promise.all(searchPs).then(completes => { const endToEndTime = e2eSW.elapsed(); this.logService.trace(`SearchService#search: ${endToEndTime}ms`); completes.forEach(complete => { this.sendTelemetry(query, endToEndTime, complete); }); return completes; }, err => { const endToEndTime = e2eSW.elapsed(); this.logService.trace(`SearchService#search: ${endToEndTime}ms`); const searchError = deserializeSearchError(err.message); this.sendTelemetry(query, endToEndTime, undefined, searchError); throw searchError; }); } private groupFolderQueriesByScheme(query: ISearchQuery): Map<string, IFolderQuery[]> { const queries = new Map<string, IFolderQuery[]>(); query.folderQueries.forEach(fq => { const schemeFQs = queries.get(fq.folder.scheme) || []; schemeFQs.push(fq); queries.set(fq.folder.scheme, schemeFQs); }); return queries; } private sendTelemetry(query: ISearchQuery, endToEndTime: number, complete?: ISearchComplete, err?: SearchError): void { const fileSchemeOnly = query.folderQueries.every(fq => fq.folder.scheme === 'file'); const otherSchemeOnly = query.folderQueries.every(fq => fq.folder.scheme !== 'file'); const scheme = fileSchemeOnly ? 'file' : otherSchemeOnly ? 'other' : 'mixed'; if (query.type === QueryType.File && complete && complete.stats) { const fileSearchStats = complete.stats as IFileSearchStats; if (fileSearchStats.fromCache) { const cacheStats: ICachedSearchStats = fileSearchStats.detailStats as ICachedSearchStats; type CachedSearchCompleteClassifcation = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; resultCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; type: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; sortingTime?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheWasResolved: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; cacheLookupTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheFilterTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheEntryCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type CachedSearchCompleteEvent = { reason?: string; resultCount: number; workspaceFolderCount: number; type: 'fileSearchProvider' | 'searchProcess'; endToEndTime: number; sortingTime?: number; cacheWasResolved: boolean; cacheLookupTime: number; cacheFilterTime: number; cacheEntryCount: number; scheme: string; }; this.telemetryService.publicLog2<CachedSearchCompleteEvent, CachedSearchCompleteClassifcation>('cachedSearchComplete', { reason: query._reason, resultCount: fileSearchStats.resultCount, workspaceFolderCount: query.folderQueries.length, type: fileSearchStats.type, endToEndTime: endToEndTime, sortingTime: fileSearchStats.sortingTime, cacheWasResolved: cacheStats.cacheWasResolved, cacheLookupTime: cacheStats.cacheLookupTime, cacheFilterTime: cacheStats.cacheFilterTime, cacheEntryCount: cacheStats.cacheEntryCount, scheme }); } else { const searchEngineStats: ISearchEngineStats = fileSearchStats.detailStats as ISearchEngineStats; type SearchCompleteClassification = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; resultCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; type: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; sortingTime?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; fileWalkTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; directoriesWalked: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; filesWalked: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cmdTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cmdResultCount?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type SearchCompleteEvent = { reason?: string; resultCount: number; workspaceFolderCount: number; type: 'fileSearchProvider' | 'searchProcess'; endToEndTime: number; sortingTime?: number; fileWalkTime: number directoriesWalked: number; filesWalked: number; cmdTime: number; cmdResultCount?: number; scheme: string; }; this.telemetryService.publicLog2<SearchCompleteEvent, SearchCompleteClassification>('searchComplete', { reason: query._reason, resultCount: fileSearchStats.resultCount, workspaceFolderCount: query.folderQueries.length, type: fileSearchStats.type, endToEndTime: endToEndTime, sortingTime: fileSearchStats.sortingTime, fileWalkTime: searchEngineStats.fileWalkTime, directoriesWalked: searchEngineStats.directoriesWalked, filesWalked: searchEngineStats.filesWalked, cmdTime: searchEngineStats.cmdTime, cmdResultCount: searchEngineStats.cmdResultCount, scheme }); } } else if (query.type === QueryType.Text) { let errorType: string | undefined; if (err) { errorType = err.code === SearchErrorCode.regexParseError ? 'regex' : err.code === SearchErrorCode.unknownEncoding ? 'encoding' : err.code === SearchErrorCode.globParseError ? 'glob' : err.code === SearchErrorCode.invalidLiteral ? 'literal' : err.code === SearchErrorCode.other ? 'other' : 'unknown'; } type TextSearchCompleteClassification = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; error?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; usePCRE2: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type TextSearchCompleteEvent = { reason?: string; workspaceFolderCount: number; endToEndTime: number; scheme: string; error?: string; usePCRE2: boolean; }; this.telemetryService.publicLog2<TextSearchCompleteEvent, TextSearchCompleteClassification>('textSearchComplete', { reason: query._reason, workspaceFolderCount: query.folderQueries.length, endToEndTime: endToEndTime, scheme, error: errorType, usePCRE2: !!query.usePCRE2 }); } } private getLocalResults(query: ITextQuery): { results: ResourceMap<IFileMatch | null>; limitHit: boolean } { const localResults = new ResourceMap<IFileMatch | null>(); let limitHit = false; if (query.type === QueryType.Text) { const models = this.modelService.getModels(); models.forEach((model) => { const resource = model.uri; if (!resource) { return; } if (limitHit) { return; } // Skip files that are not opened as text file if (!this.editorService.isOpen({ resource })) { return; } // Skip search results if (model.getModeId() === 'search-result' && !(query.includePattern && query.includePattern['**/*.code-search'])) { // TODO: untitled search editors will be excluded from search even when include *.code-search is specified return; } // Block walkthrough, webview, etc. if (resource.scheme !== Schemas.untitled && !this.fileService.canHandleResource(resource)) { return; } // Exclude files from the git FileSystemProvider, e.g. to prevent open staged files from showing in search results if (resource.scheme === 'git') { return; } if (!this.matches(resource, query)) { return; // respect user filters } // Use editor API to find matches const askMax = typeof query.maxResults === 'number' ? query.maxResults + 1 : undefined; let matches = model.findMatches(query.contentPattern.pattern, false, !!query.contentPattern.isRegExp, !!query.contentPattern.isCaseSensitive, query.contentPattern.isWordMatch ? query.contentPattern.wordSeparators! : null, false, askMax); if (matches.length) { if (askMax && matches.length >= askMax) { limitHit = true; matches = matches.slice(0, askMax - 1); } const fileMatch = new FileMatch(resource); localResults.set(resource, fileMatch); const textSearchResults = editorMatchesToTextSearchResults(matches, model, query.previewOptions); fileMatch.results = addContextToEditorMatches(textSearchResults, model, query); } else { localResults.set(resource, null); } }); } return { results: localResults, limitHit }; } private matches(resource: uri, query: ITextQuery): boolean { return pathIncludedInQuery(query, resource.fsPath); } clearCache(cacheKey: string): Promise<void> { const clearPs = [ this.diskSearch, ...values(this.fileSearchProviders) ].map(provider => provider && provider.clearCache(cacheKey)); return Promise.all(clearPs) .then(() => { }); } } export class RemoteSearchService extends SearchService { constructor( @IModelService modelService: IModelService, @IEditorService editorService: IEditorService, @ITelemetryService telemetryService: ITelemetryService, @ILogService logService: ILogService, @IExtensionService extensionService: IExtensionService, @IFileService fileService: IFileService ) { super(modelService, editorService, telemetryService, logService, extensionService, fileService); } } registerSingleton(ISearchService, RemoteSearchService, true);
src/vs/workbench/services/search/common/searchService.ts
1
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.8744174242019653, 0.017224179580807686, 0.00016583751130383462, 0.00017127871979027987, 0.12003754824399948 ]
{ "id": 2, "code_window": [ "\n", "\t\t\t\t\tif (onProgress) {\n", "\t\t\t\t\t\tonProgress(item);\n", "\t\t\t\t\t}\n", "\t\t\t\t};\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\tconst progressCallback = (item: ISearchProgressItem) => {\n", "\t\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\t\treturn;\n", "\t\t\t\t}\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 131 }
# Publish @types/vscode for each release trigger: branches: include: ['refs/tags/*'] pr: none steps: - task: NodeTool@0 inputs: versionSpec: "12.13.0" - task: geeklearningio.gl-vsts-tasks-yarn.yarn-installer-task.YarnInstaller@2 inputs: versionSpec: "1.x" - bash: | TAG_VERSION=$(git describe --tags `git rev-list --tags --max-count=1`) CHANNEL="G1C14HJ2F" if [ "$TAG_VERSION" == "1.999.0" ]; then MESSAGE="<!here>. Someone pushed 1.999.0 tag. Please delete it ASAP from remote and local." curl -X POST -H "Authorization: Bearer $(SLACK_TOKEN)" \ -H 'Content-type: application/json; charset=utf-8' \ --data '{"channel":"'"$CHANNEL"'", "link_names": true, "text":"'"$MESSAGE"'"}' \ https://slack.com/api/chat.postMessage exit 1 fi displayName: Check 1.999.0 tag - bash: | # Install build dependencies (cd build && yarn) node build/azure-pipelines/publish-types/check-version.js displayName: Check version - bash: | git config --global user.email "[email protected]" git config --global user.name "VSCode" git clone https://$(GITHUB_TOKEN)@github.com/DefinitelyTyped/DefinitelyTyped.git --depth=1 node build/azure-pipelines/publish-types/update-types.js TAG_VERSION=$(git describe --tags `git rev-list --tags --max-count=1`) cd DefinitelyTyped git diff --color | cat git add -A git status git checkout -b "vscode-types-$TAG_VERSION" git commit -m "VS Code $TAG_VERSION Extension API" git push origin "vscode-types-$TAG_VERSION" displayName: Push update to DefinitelyTyped - bash: | TAG_VERSION=$(git describe --tags `git rev-list --tags --max-count=1`) CHANNEL="G1C14HJ2F" MESSAGE="DefinitelyTyped/DefinitelyTyped#vscode-types-$TAG_VERSION created. Endgame master, please open this link, examine changes and create a PR:" LINK="https://github.com/DefinitelyTyped/DefinitelyTyped/compare/vscode-types-$TAG_VERSION?quick_pull=1&body=Updating%20VS%20Code%20Extension%20API.%20See%20https%3A%2F%2Fgithub.com%2Fmicrosoft%2Fvscode%2Fissues%2F70175%20for%20details." MESSAGE2="[@eamodio, @jrieken, @kmaetzel, @egamma]. Please review and merge PR to publish @types/vscode." curl -X POST -H "Authorization: Bearer $(SLACK_TOKEN)" \ -H 'Content-type: application/json; charset=utf-8' \ --data '{"channel":"'"$CHANNEL"'", "link_names": true, "text":"'"$MESSAGE"'"}' \ https://slack.com/api/chat.postMessage curl -X POST -H "Authorization: Bearer $(SLACK_TOKEN)" \ -H 'Content-type: application/json; charset=utf-8' \ --data '{"channel":"'"$CHANNEL"'", "link_names": true, "text":"'"$LINK"'"}' \ https://slack.com/api/chat.postMessage curl -X POST -H "Authorization: Bearer $(SLACK_TOKEN)" \ -H 'Content-type: application/json; charset=utf-8' \ --data '{"channel":"'"$CHANNEL"'", "link_names": true, "text":"'"$MESSAGE2"'"}' \ https://slack.com/api/chat.postMessage displayName: Send message on Slack
build/azure-pipelines/publish-types/publish-types.yml
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00017452004249207675, 0.00017103017307817936, 0.00016565844998694956, 0.00017278674931731075, 0.000003402710262889741 ]
{ "id": 2, "code_window": [ "\n", "\t\t\t\t\tif (onProgress) {\n", "\t\t\t\t\t\tonProgress(item);\n", "\t\t\t\t\t}\n", "\t\t\t\t};\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\tconst progressCallback = (item: ISearchProgressItem) => {\n", "\t\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\t\treturn;\n", "\t\t\t\t}\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 131 }
#!/usr/bin/env bash set -e REPO="$(pwd)" ROOT="$REPO/.." # Publish tarball PLATFORM_LINUX="linux-x64" BUILDNAME="VSCode-$PLATFORM_LINUX" BUILD="$ROOT/$BUILDNAME" BUILD_VERSION="$(date +%s)" [ -z "$VSCODE_QUALITY" ] && TARBALL_FILENAME="code-$BUILD_VERSION.tar.gz" || TARBALL_FILENAME="code-$VSCODE_QUALITY-$BUILD_VERSION.tar.gz" TARBALL_PATH="$ROOT/$TARBALL_FILENAME" rm -rf $ROOT/code-*.tar.* (cd $ROOT && tar -czf $TARBALL_PATH $BUILDNAME) node build/azure-pipelines/common/createAsset.js "$PLATFORM_LINUX" archive-unsigned "$TARBALL_FILENAME" "$TARBALL_PATH" # Publish Remote Extension Host LEGACY_SERVER_BUILD_NAME="vscode-reh-$PLATFORM_LINUX" SERVER_BUILD_NAME="vscode-server-$PLATFORM_LINUX" SERVER_TARBALL_FILENAME="vscode-server-$PLATFORM_LINUX.tar.gz" SERVER_TARBALL_PATH="$ROOT/$SERVER_TARBALL_FILENAME" rm -rf $ROOT/vscode-server-*.tar.* (cd $ROOT && mv $LEGACY_SERVER_BUILD_NAME $SERVER_BUILD_NAME && tar --owner=0 --group=0 -czf $SERVER_TARBALL_PATH $SERVER_BUILD_NAME) node build/azure-pipelines/common/createAsset.js "server-$PLATFORM_LINUX" archive-unsigned "$SERVER_TARBALL_FILENAME" "$SERVER_TARBALL_PATH" # Publish hockeyapp symbols # node build/azure-pipelines/common/symbols.js "$VSCODE_MIXIN_PASSWORD" "$VSCODE_HOCKEYAPP_TOKEN" "x64" "$VSCODE_HOCKEYAPP_ID_LINUX64" # Skip hockey app because build failure. # https://github.com/microsoft/vscode/issues/90491 # Publish DEB PLATFORM_DEB="linux-deb-x64" DEB_ARCH="amd64" DEB_FILENAME="$(ls $REPO/.build/linux/deb/$DEB_ARCH/deb/)" DEB_PATH="$REPO/.build/linux/deb/$DEB_ARCH/deb/$DEB_FILENAME" node build/azure-pipelines/common/createAsset.js "$PLATFORM_DEB" package "$DEB_FILENAME" "$DEB_PATH" # Publish RPM PLATFORM_RPM="linux-rpm-x64" RPM_ARCH="x86_64" RPM_FILENAME="$(ls $REPO/.build/linux/rpm/$RPM_ARCH/ | grep .rpm)" RPM_PATH="$REPO/.build/linux/rpm/$RPM_ARCH/$RPM_FILENAME" node build/azure-pipelines/common/createAsset.js "$PLATFORM_RPM" package "$RPM_FILENAME" "$RPM_PATH" # Publish Snap # Pack snap tarball artifact, in order to preserve file perms mkdir -p $REPO/.build/linux/snap-tarball SNAP_TARBALL_PATH="$REPO/.build/linux/snap-tarball/snap-x64.tar.gz" rm -rf $SNAP_TARBALL_PATH (cd .build/linux && tar -czf $SNAP_TARBALL_PATH snap)
build/azure-pipelines/linux/publish.sh
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00020221293380018324, 0.0001750325900502503, 0.00016703267465345562, 0.00017043910338543355, 0.000012275449989829212 ]
{ "id": 2, "code_window": [ "\n", "\t\t\t\t\tif (onProgress) {\n", "\t\t\t\t\t\tonProgress(item);\n", "\t\t\t\t\t}\n", "\t\t\t\t};\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\tconst progressCallback = (item: ISearchProgressItem) => {\n", "\t\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\t\treturn;\n", "\t\t\t\t}\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 131 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; export interface MatcherWithPriority<T> { matcher: Matcher<T>; priority: -1 | 0 | 1; } export interface Matcher<T> { (matcherInput: T): number; } export function createMatchers<T>(selector: string, matchesName: (names: string[], matcherInput: T) => number, results: MatcherWithPriority<T>[]): void { const tokenizer = newTokenizer(selector); let token = tokenizer.next(); while (token !== null) { let priority: -1 | 0 | 1 = 0; if (token.length === 2 && token.charAt(1) === ':') { switch (token.charAt(0)) { case 'R': priority = 1; break; case 'L': priority = -1; break; default: console.log(`Unknown priority ${token} in scope selector`); } token = tokenizer.next(); } let matcher = parseConjunction(); if (matcher) { results.push({ matcher, priority }); } if (token !== ',') { break; } token = tokenizer.next(); } function parseOperand(): Matcher<T> | null { if (token === '-') { token = tokenizer.next(); const expressionToNegate = parseOperand(); if (!expressionToNegate) { return null; } return matcherInput => { const score = expressionToNegate(matcherInput); return score < 0 ? 0 : -1; }; } if (token === '(') { token = tokenizer.next(); const expressionInParents = parseInnerExpression(); if (token === ')') { token = tokenizer.next(); } return expressionInParents; } if (isIdentifier(token)) { const identifiers: string[] = []; do { identifiers.push(token); token = tokenizer.next(); } while (isIdentifier(token)); return matcherInput => matchesName(identifiers, matcherInput); } return null; } function parseConjunction(): Matcher<T> | null { let matcher = parseOperand(); if (!matcher) { return null; } const matchers: Matcher<T>[] = []; while (matcher) { matchers.push(matcher); matcher = parseOperand(); } return matcherInput => { // and let min = matchers[0](matcherInput); for (let i = 1; min >= 0 && i < matchers.length; i++) { min = Math.min(min, matchers[i](matcherInput)); } return min; }; } function parseInnerExpression(): Matcher<T> | null { let matcher = parseConjunction(); if (!matcher) { return null; } const matchers: Matcher<T>[] = []; while (matcher) { matchers.push(matcher); if (token === '|' || token === ',') { do { token = tokenizer.next(); } while (token === '|' || token === ','); // ignore subsequent commas } else { break; } matcher = parseConjunction(); } return matcherInput => { // or let max = matchers[0](matcherInput); for (let i = 1; i < matchers.length; i++) { max = Math.max(max, matchers[i](matcherInput)); } return max; }; } } function isIdentifier(token: string | null): token is string { return !!token && !!token.match(/[\w\.:]+/); } function newTokenizer(input: string): { next: () => string | null } { let regex = /([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g; let match = regex.exec(input); return { next: () => { if (!match) { return null; } const res = match[0]; match = regex.exec(input); return res; } }; }
src/vs/workbench/services/themes/common/textMateScopeMatcher.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00017628917703405023, 0.0001720035361358896, 0.00016838681767694652, 0.00017211887461598963, 0.000001963097247426049 ]
{ "id": 3, "code_window": [ "\n", "\t\t\t\treturn this.searchWithProviders(query, progressCallback, token);\n", "\t\t\t})\n", "\t\t\t.then(completes => {\n", "\t\t\t\tcompletes = arrays.coalesce(completes);\n", "\t\t\t\tif (!completes.length) {\n", "\t\t\t\t\treturn {\n", "\t\t\t\t\t\tlimitHit: false,\n", "\t\t\t\t\t\tresults: []\n", "\t\t\t\t\t};\n", "\t\t\t\t}\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\t\tif (onProgress) {\n", "\t\t\t\t\tonProgress(item);\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 136 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as arrays from 'vs/base/common/arrays'; import { CancellationToken } from 'vs/base/common/cancellation'; import { canceled } from 'vs/base/common/errors'; import { Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { keys, ResourceMap, values } from 'vs/base/common/map'; import { Schemas } from 'vs/base/common/network'; import { StopWatch } from 'vs/base/common/stopwatch'; import { URI as uri } from 'vs/base/common/uri'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IFileService } from 'vs/platform/files/common/files'; import { ILogService } from 'vs/platform/log/common/log'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { deserializeSearchError, FileMatch, ICachedSearchStats, IFileMatch, IFileQuery, IFileSearchStats, IFolderQuery, IProgressMessage, ISearchComplete, ISearchEngineStats, ISearchProgressItem, ISearchQuery, ISearchResultProvider, ISearchService, ITextQuery, pathIncludedInQuery, QueryType, SearchError, SearchErrorCode, SearchProviderType, isFileMatch, isProgressMessage } from 'vs/workbench/services/search/common/search'; import { addContextToEditorMatches, editorMatchesToTextSearchResults } from 'vs/workbench/services/search/common/searchHelpers'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { DeferredPromise } from 'vs/base/test/common/utils'; export class SearchService extends Disposable implements ISearchService { _serviceBrand: undefined; protected diskSearch: ISearchResultProvider | null = null; private readonly fileSearchProviders = new Map<string, ISearchResultProvider>(); private readonly textSearchProviders = new Map<string, ISearchResultProvider>(); private deferredFileSearchesByScheme = new Map<string, DeferredPromise<ISearchResultProvider>>(); private deferredTextSearchesByScheme = new Map<string, DeferredPromise<ISearchResultProvider>>(); constructor( private readonly modelService: IModelService, private readonly editorService: IEditorService, private readonly telemetryService: ITelemetryService, private readonly logService: ILogService, private readonly extensionService: IExtensionService, private readonly fileService: IFileService ) { super(); } registerSearchResultProvider(scheme: string, type: SearchProviderType, provider: ISearchResultProvider): IDisposable { let list: Map<string, ISearchResultProvider>; let deferredMap: Map<string, DeferredPromise<ISearchResultProvider>>; if (type === SearchProviderType.file) { list = this.fileSearchProviders; deferredMap = this.deferredFileSearchesByScheme; } else if (type === SearchProviderType.text) { list = this.textSearchProviders; deferredMap = this.deferredTextSearchesByScheme; } else { throw new Error('Unknown SearchProviderType'); } list.set(scheme, provider); if (deferredMap.has(scheme)) { deferredMap.get(scheme)!.complete(provider); deferredMap.delete(scheme); } return toDisposable(() => { list.delete(scheme); }); } async textSearch(query: ITextQuery, token?: CancellationToken, onProgress?: (item: ISearchProgressItem) => void): Promise<ISearchComplete> { // Get local results from dirty/untitled const localResults = this.getLocalResults(query); if (onProgress) { arrays.coalesce([...localResults.results.values()]).forEach(onProgress); } const onProviderProgress = (progress: ISearchProgressItem) => { if (isFileMatch(progress)) { // Match if (!localResults.results.has(progress.resource) && onProgress) { // don't override local results onProgress(progress); } } else if (onProgress) { // Progress onProgress(<IProgressMessage>progress); } if (isProgressMessage(progress)) { this.logService.debug('SearchService#search', progress.message); } }; const otherResults = await this.doSearch(query, token, onProviderProgress); return { ...otherResults, ...{ limitHit: otherResults.limitHit || localResults.limitHit }, results: [...otherResults.results, ...arrays.coalesce([...localResults.results.values()])] }; } fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { return this.doSearch(query, token); } private doSearch(query: ISearchQuery, token?: CancellationToken, onProgress?: (item: ISearchProgressItem) => void): Promise<ISearchComplete> { this.logService.trace('SearchService#search', JSON.stringify(query)); const schemesInQuery = this.getSchemesInQuery(query); const providerActivations: Promise<any>[] = [Promise.resolve(null)]; schemesInQuery.forEach(scheme => providerActivations.push(this.extensionService.activateByEvent(`onSearch:${scheme}`))); providerActivations.push(this.extensionService.activateByEvent('onSearch:file')); const providerPromise = Promise.all(providerActivations) .then(() => this.extensionService.whenInstalledExtensionsRegistered()) .then(() => { // Cancel faster if search was canceled while waiting for extensions if (token && token.isCancellationRequested) { return Promise.reject(canceled()); } const progressCallback = (item: ISearchProgressItem) => { if (token && token.isCancellationRequested) { return; } if (onProgress) { onProgress(item); } }; return this.searchWithProviders(query, progressCallback, token); }) .then(completes => { completes = arrays.coalesce(completes); if (!completes.length) { return { limitHit: false, results: [] }; } return <ISearchComplete>{ limitHit: completes[0] && completes[0].limitHit, stats: completes[0].stats, results: arrays.flatten(completes.map((c: ISearchComplete) => c.results)) }; }); return new Promise((resolve, reject) => { if (token) { token.onCancellationRequested(() => { reject(canceled()); }); } providerPromise.then(resolve, reject); }); } private getSchemesInQuery(query: ISearchQuery): Set<string> { const schemes = new Set<string>(); if (query.folderQueries) { query.folderQueries.forEach(fq => schemes.add(fq.folder.scheme)); } if (query.extraFileResources) { query.extraFileResources.forEach(extraFile => schemes.add(extraFile.scheme)); } return schemes; } private async waitForProvider(queryType: QueryType, scheme: string): Promise<ISearchResultProvider> { let deferredMap: Map<string, DeferredPromise<ISearchResultProvider>> = queryType === QueryType.File ? this.deferredFileSearchesByScheme : this.deferredTextSearchesByScheme; if (deferredMap.has(scheme)) { return deferredMap.get(scheme)!.p; } else { const deferred = new DeferredPromise<ISearchResultProvider>(); deferredMap.set(scheme, deferred); return deferred.p; } } private async searchWithProviders(query: ISearchQuery, onProviderProgress: (progress: ISearchProgressItem) => void, token?: CancellationToken) { const e2eSW = StopWatch.create(false); const diskSearchQueries: IFolderQuery[] = []; const searchPs: Promise<ISearchComplete>[] = []; const fqs = this.groupFolderQueriesByScheme(query); await Promise.all(keys(fqs).map(async scheme => { const schemeFQs = fqs.get(scheme)!; let provider = query.type === QueryType.File ? this.fileSearchProviders.get(scheme) : this.textSearchProviders.get(scheme); if (!provider && scheme === Schemas.file) { diskSearchQueries.push(...schemeFQs); } else { if (!provider) { if (scheme !== Schemas.vscodeRemote) { console.warn(`No search provider registered for scheme: ${scheme}`); return; } console.warn(`No search provider registered for scheme: ${scheme}, waiting`); provider = await this.waitForProvider(query.type, scheme); } const oneSchemeQuery: ISearchQuery = { ...query, ...{ folderQueries: schemeFQs } }; searchPs.push(query.type === QueryType.File ? provider.fileSearch(<IFileQuery>oneSchemeQuery, token) : provider.textSearch(<ITextQuery>oneSchemeQuery, onProviderProgress, token)); } })); const diskSearchExtraFileResources = query.extraFileResources && query.extraFileResources.filter(res => res.scheme === Schemas.file); if (diskSearchQueries.length || diskSearchExtraFileResources) { const diskSearchQuery: ISearchQuery = { ...query, ...{ folderQueries: diskSearchQueries }, extraFileResources: diskSearchExtraFileResources }; if (this.diskSearch) { searchPs.push(diskSearchQuery.type === QueryType.File ? this.diskSearch.fileSearch(diskSearchQuery, token) : this.diskSearch.textSearch(diskSearchQuery, onProviderProgress, token)); } } return Promise.all(searchPs).then(completes => { const endToEndTime = e2eSW.elapsed(); this.logService.trace(`SearchService#search: ${endToEndTime}ms`); completes.forEach(complete => { this.sendTelemetry(query, endToEndTime, complete); }); return completes; }, err => { const endToEndTime = e2eSW.elapsed(); this.logService.trace(`SearchService#search: ${endToEndTime}ms`); const searchError = deserializeSearchError(err.message); this.sendTelemetry(query, endToEndTime, undefined, searchError); throw searchError; }); } private groupFolderQueriesByScheme(query: ISearchQuery): Map<string, IFolderQuery[]> { const queries = new Map<string, IFolderQuery[]>(); query.folderQueries.forEach(fq => { const schemeFQs = queries.get(fq.folder.scheme) || []; schemeFQs.push(fq); queries.set(fq.folder.scheme, schemeFQs); }); return queries; } private sendTelemetry(query: ISearchQuery, endToEndTime: number, complete?: ISearchComplete, err?: SearchError): void { const fileSchemeOnly = query.folderQueries.every(fq => fq.folder.scheme === 'file'); const otherSchemeOnly = query.folderQueries.every(fq => fq.folder.scheme !== 'file'); const scheme = fileSchemeOnly ? 'file' : otherSchemeOnly ? 'other' : 'mixed'; if (query.type === QueryType.File && complete && complete.stats) { const fileSearchStats = complete.stats as IFileSearchStats; if (fileSearchStats.fromCache) { const cacheStats: ICachedSearchStats = fileSearchStats.detailStats as ICachedSearchStats; type CachedSearchCompleteClassifcation = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; resultCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; type: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; sortingTime?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheWasResolved: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; cacheLookupTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheFilterTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheEntryCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type CachedSearchCompleteEvent = { reason?: string; resultCount: number; workspaceFolderCount: number; type: 'fileSearchProvider' | 'searchProcess'; endToEndTime: number; sortingTime?: number; cacheWasResolved: boolean; cacheLookupTime: number; cacheFilterTime: number; cacheEntryCount: number; scheme: string; }; this.telemetryService.publicLog2<CachedSearchCompleteEvent, CachedSearchCompleteClassifcation>('cachedSearchComplete', { reason: query._reason, resultCount: fileSearchStats.resultCount, workspaceFolderCount: query.folderQueries.length, type: fileSearchStats.type, endToEndTime: endToEndTime, sortingTime: fileSearchStats.sortingTime, cacheWasResolved: cacheStats.cacheWasResolved, cacheLookupTime: cacheStats.cacheLookupTime, cacheFilterTime: cacheStats.cacheFilterTime, cacheEntryCount: cacheStats.cacheEntryCount, scheme }); } else { const searchEngineStats: ISearchEngineStats = fileSearchStats.detailStats as ISearchEngineStats; type SearchCompleteClassification = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; resultCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; type: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; sortingTime?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; fileWalkTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; directoriesWalked: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; filesWalked: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cmdTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cmdResultCount?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type SearchCompleteEvent = { reason?: string; resultCount: number; workspaceFolderCount: number; type: 'fileSearchProvider' | 'searchProcess'; endToEndTime: number; sortingTime?: number; fileWalkTime: number directoriesWalked: number; filesWalked: number; cmdTime: number; cmdResultCount?: number; scheme: string; }; this.telemetryService.publicLog2<SearchCompleteEvent, SearchCompleteClassification>('searchComplete', { reason: query._reason, resultCount: fileSearchStats.resultCount, workspaceFolderCount: query.folderQueries.length, type: fileSearchStats.type, endToEndTime: endToEndTime, sortingTime: fileSearchStats.sortingTime, fileWalkTime: searchEngineStats.fileWalkTime, directoriesWalked: searchEngineStats.directoriesWalked, filesWalked: searchEngineStats.filesWalked, cmdTime: searchEngineStats.cmdTime, cmdResultCount: searchEngineStats.cmdResultCount, scheme }); } } else if (query.type === QueryType.Text) { let errorType: string | undefined; if (err) { errorType = err.code === SearchErrorCode.regexParseError ? 'regex' : err.code === SearchErrorCode.unknownEncoding ? 'encoding' : err.code === SearchErrorCode.globParseError ? 'glob' : err.code === SearchErrorCode.invalidLiteral ? 'literal' : err.code === SearchErrorCode.other ? 'other' : 'unknown'; } type TextSearchCompleteClassification = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; error?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; usePCRE2: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type TextSearchCompleteEvent = { reason?: string; workspaceFolderCount: number; endToEndTime: number; scheme: string; error?: string; usePCRE2: boolean; }; this.telemetryService.publicLog2<TextSearchCompleteEvent, TextSearchCompleteClassification>('textSearchComplete', { reason: query._reason, workspaceFolderCount: query.folderQueries.length, endToEndTime: endToEndTime, scheme, error: errorType, usePCRE2: !!query.usePCRE2 }); } } private getLocalResults(query: ITextQuery): { results: ResourceMap<IFileMatch | null>; limitHit: boolean } { const localResults = new ResourceMap<IFileMatch | null>(); let limitHit = false; if (query.type === QueryType.Text) { const models = this.modelService.getModels(); models.forEach((model) => { const resource = model.uri; if (!resource) { return; } if (limitHit) { return; } // Skip files that are not opened as text file if (!this.editorService.isOpen({ resource })) { return; } // Skip search results if (model.getModeId() === 'search-result' && !(query.includePattern && query.includePattern['**/*.code-search'])) { // TODO: untitled search editors will be excluded from search even when include *.code-search is specified return; } // Block walkthrough, webview, etc. if (resource.scheme !== Schemas.untitled && !this.fileService.canHandleResource(resource)) { return; } // Exclude files from the git FileSystemProvider, e.g. to prevent open staged files from showing in search results if (resource.scheme === 'git') { return; } if (!this.matches(resource, query)) { return; // respect user filters } // Use editor API to find matches const askMax = typeof query.maxResults === 'number' ? query.maxResults + 1 : undefined; let matches = model.findMatches(query.contentPattern.pattern, false, !!query.contentPattern.isRegExp, !!query.contentPattern.isCaseSensitive, query.contentPattern.isWordMatch ? query.contentPattern.wordSeparators! : null, false, askMax); if (matches.length) { if (askMax && matches.length >= askMax) { limitHit = true; matches = matches.slice(0, askMax - 1); } const fileMatch = new FileMatch(resource); localResults.set(resource, fileMatch); const textSearchResults = editorMatchesToTextSearchResults(matches, model, query.previewOptions); fileMatch.results = addContextToEditorMatches(textSearchResults, model, query); } else { localResults.set(resource, null); } }); } return { results: localResults, limitHit }; } private matches(resource: uri, query: ITextQuery): boolean { return pathIncludedInQuery(query, resource.fsPath); } clearCache(cacheKey: string): Promise<void> { const clearPs = [ this.diskSearch, ...values(this.fileSearchProviders) ].map(provider => provider && provider.clearCache(cacheKey)); return Promise.all(clearPs) .then(() => { }); } } export class RemoteSearchService extends SearchService { constructor( @IModelService modelService: IModelService, @IEditorService editorService: IEditorService, @ITelemetryService telemetryService: ITelemetryService, @ILogService logService: ILogService, @IExtensionService extensionService: IExtensionService, @IFileService fileService: IFileService ) { super(modelService, editorService, telemetryService, logService, extensionService, fileService); } } registerSingleton(ISearchService, RemoteSearchService, true);
src/vs/workbench/services/search/common/searchService.ts
1
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.9979269504547119, 0.05660688132047653, 0.0001641225244384259, 0.00017119167023338377, 0.22735609114170074 ]
{ "id": 3, "code_window": [ "\n", "\t\t\t\treturn this.searchWithProviders(query, progressCallback, token);\n", "\t\t\t})\n", "\t\t\t.then(completes => {\n", "\t\t\t\tcompletes = arrays.coalesce(completes);\n", "\t\t\t\tif (!completes.length) {\n", "\t\t\t\t\treturn {\n", "\t\t\t\t\t\tlimitHit: false,\n", "\t\t\t\t\t\tresults: []\n", "\t\t\t\t\t};\n", "\t\t\t\t}\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\t\tif (onProgress) {\n", "\t\t\t\t\tonProgress(item);\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 136 }
/*--------------------------------------------------------------------------------------------- * 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 { ExtensionsRegistry } from 'vs/workbench/services/extensions/common/extensionsRegistry'; import { IColorRegistry, Extensions as ColorRegistryExtensions } from 'vs/platform/theme/common/colorRegistry'; import { Color } from 'vs/base/common/color'; import { Registry } from 'vs/platform/registry/common/platform'; interface IColorExtensionPoint { id: string; description: string; defaults: { light: string, dark: string, highContrast: string }; } const colorRegistry: IColorRegistry = Registry.as<IColorRegistry>(ColorRegistryExtensions.ColorContribution); const colorReferenceSchema = colorRegistry.getColorReferenceSchema(); const colorIdPattern = '^\\w+[.\\w+]*$'; const configurationExtPoint = ExtensionsRegistry.registerExtensionPoint<IColorExtensionPoint[]>({ extensionPoint: 'colors', jsonSchema: { description: nls.localize('contributes.color', 'Contributes extension defined themable colors'), type: 'array', items: { type: 'object', properties: { id: { type: 'string', description: nls.localize('contributes.color.id', 'The identifier of the themable color'), pattern: colorIdPattern, patternErrorMessage: nls.localize('contributes.color.id.format', 'Identifiers should be in the form aa[.bb]*'), }, description: { type: 'string', description: nls.localize('contributes.color.description', 'The description of the themable color'), }, defaults: { type: 'object', properties: { light: { description: nls.localize('contributes.defaults.light', 'The default color for light themes. Either a color value in hex (#RRGGBB[AA]) or the identifier of a themable color which provides the default.'), type: 'string', anyOf: [ colorReferenceSchema, { type: 'string', format: 'color-hex' } ] }, dark: { description: nls.localize('contributes.defaults.dark', 'The default color for dark themes. Either a color value in hex (#RRGGBB[AA]) or the identifier of a themable color which provides the default.'), type: 'string', anyOf: [ colorReferenceSchema, { type: 'string', format: 'color-hex' } ] }, highContrast: { description: nls.localize('contributes.defaults.highContrast', 'The default color for high contrast themes. Either a color value in hex (#RRGGBB[AA]) or the identifier of a themable color which provides the default.'), type: 'string', anyOf: [ colorReferenceSchema, { type: 'string', format: 'color-hex' } ] } } }, } } } }); export class ColorExtensionPoint { constructor() { configurationExtPoint.setHandler((extensions, delta) => { for (const extension of delta.added) { const extensionValue = <IColorExtensionPoint[]>extension.value; const collector = extension.collector; if (!extensionValue || !Array.isArray(extensionValue)) { collector.error(nls.localize('invalid.colorConfiguration', "'configuration.colors' must be a array")); return; } let parseColorValue = (s: string, name: string) => { if (s.length > 0) { if (s[0] === '#') { return Color.Format.CSS.parseHex(s); } else { return s; } } collector.error(nls.localize('invalid.default.colorType', "{0} must be either a color value in hex (#RRGGBB[AA] or #RGB[A]) or the identifier of a themable color which provides the default.", name)); return Color.red; }; for (const colorContribution of extensionValue) { if (typeof colorContribution.id !== 'string' || colorContribution.id.length === 0) { collector.error(nls.localize('invalid.id', "'configuration.colors.id' must be defined and can not be empty")); return; } if (!colorContribution.id.match(colorIdPattern)) { collector.error(nls.localize('invalid.id.format', "'configuration.colors.id' must follow the word[.word]*")); return; } if (typeof colorContribution.description !== 'string' || colorContribution.id.length === 0) { collector.error(nls.localize('invalid.description', "'configuration.colors.description' must be defined and can not be empty")); return; } let defaults = colorContribution.defaults; if (!defaults || typeof defaults !== 'object' || typeof defaults.light !== 'string' || typeof defaults.dark !== 'string' || typeof defaults.highContrast !== 'string') { collector.error(nls.localize('invalid.defaults', "'configuration.colors.defaults' must be defined and must contain 'light', 'dark' and 'highContrast'")); return; } colorRegistry.registerColor(colorContribution.id, { light: parseColorValue(defaults.light, 'configuration.colors.defaults.light'), dark: parseColorValue(defaults.dark, 'configuration.colors.defaults.dark'), hc: parseColorValue(defaults.highContrast, 'configuration.colors.defaults.highContrast') }, colorContribution.description); } } for (const extension of delta.removed) { const extensionValue = <IColorExtensionPoint[]>extension.value; for (const colorContribution of extensionValue) { colorRegistry.deregisterColor(colorContribution.id); } } }); } }
src/vs/workbench/services/themes/common/colorExtensionPoint.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00017756607849150896, 0.0001747044880175963, 0.0001687260955804959, 0.00017506835865788162, 0.000002254655328215449 ]
{ "id": 3, "code_window": [ "\n", "\t\t\t\treturn this.searchWithProviders(query, progressCallback, token);\n", "\t\t\t})\n", "\t\t\t.then(completes => {\n", "\t\t\t\tcompletes = arrays.coalesce(completes);\n", "\t\t\t\tif (!completes.length) {\n", "\t\t\t\t\treturn {\n", "\t\t\t\t\t\tlimitHit: false,\n", "\t\t\t\t\t\tresults: []\n", "\t\t\t\t\t};\n", "\t\t\t\t}\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\t\tif (onProgress) {\n", "\t\t\t\t\tonProgress(item);\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 136 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as platform from 'vs/platform/registry/common/platform'; import { IJSONSchema, IJSONSchemaMap } from 'vs/base/common/jsonSchema'; import { Color, RGBA } from 'vs/base/common/color'; import { IColorTheme } from 'vs/platform/theme/common/themeService'; import { Event, Emitter } from 'vs/base/common/event'; import * as nls from 'vs/nls'; import { Extensions as JSONExtensions, IJSONContributionRegistry } from 'vs/platform/jsonschemas/common/jsonContributionRegistry'; import { RunOnceScheduler } from 'vs/base/common/async'; // ------ API types export type ColorIdentifier = string; export interface ColorContribution { readonly id: ColorIdentifier; readonly description: string; readonly defaults: ColorDefaults | null; readonly needsTransparency: boolean; readonly deprecationMessage: string | undefined; } export interface ColorFunction { (theme: IColorTheme): Color | undefined; } export interface ColorDefaults { light: ColorValue | null; dark: ColorValue | null; hc: ColorValue | null; } /** * A Color Value is either a color literal, a refence to other color or a derived color */ export type ColorValue = Color | string | ColorIdentifier | ColorFunction; // color registry export const Extensions = { ColorContribution: 'base.contributions.colors' }; export interface IColorRegistry { readonly onDidChangeSchema: Event<void>; /** * Register a color to the registry. * @param id The color id as used in theme description files * @param defaults The default values * @description the description */ registerColor(id: string, defaults: ColorDefaults, description: string): ColorIdentifier; /** * Register a color to the registry. */ deregisterColor(id: string): void; /** * Get all color contributions */ getColors(): ColorContribution[]; /** * Gets the default color of the given id */ resolveDefaultColor(id: ColorIdentifier, theme: IColorTheme): Color | undefined; /** * JSON schema for an object to assign color values to one of the color contributions. */ getColorSchema(): IJSONSchema; /** * JSON schema to for a reference to a color contribution. */ getColorReferenceSchema(): IJSONSchema; } class ColorRegistry implements IColorRegistry { private readonly _onDidChangeSchema = new Emitter<void>(); readonly onDidChangeSchema: Event<void> = this._onDidChangeSchema.event; private colorsById: { [key: string]: ColorContribution }; private colorSchema: IJSONSchema & { properties: IJSONSchemaMap } = { type: 'object', properties: {} }; private colorReferenceSchema: IJSONSchema & { enum: string[], enumDescriptions: string[] } = { type: 'string', enum: [], enumDescriptions: [] }; constructor() { this.colorsById = {}; } public registerColor(id: string, defaults: ColorDefaults | null, description: string, needsTransparency = false, deprecationMessage?: string): ColorIdentifier { let colorContribution: ColorContribution = { id, description, defaults, needsTransparency, deprecationMessage }; this.colorsById[id] = colorContribution; let propertySchema: IJSONSchema = { type: 'string', description, format: 'color-hex', defaultSnippets: [{ body: '${1:#ff0000}' }] }; if (deprecationMessage) { propertySchema.deprecationMessage = deprecationMessage; } this.colorSchema.properties[id] = propertySchema; this.colorReferenceSchema.enum.push(id); this.colorReferenceSchema.enumDescriptions.push(description); this._onDidChangeSchema.fire(); return id; } public deregisterColor(id: string): void { delete this.colorsById[id]; delete this.colorSchema.properties[id]; const index = this.colorReferenceSchema.enum.indexOf(id); if (index !== -1) { this.colorReferenceSchema.enum.splice(index, 1); this.colorReferenceSchema.enumDescriptions.splice(index, 1); } this._onDidChangeSchema.fire(); } public getColors(): ColorContribution[] { return Object.keys(this.colorsById).map(id => this.colorsById[id]); } public resolveDefaultColor(id: ColorIdentifier, theme: IColorTheme): Color | undefined { const colorDesc = this.colorsById[id]; if (colorDesc && colorDesc.defaults) { const colorValue = colorDesc.defaults[theme.type]; return resolveColorValue(colorValue, theme); } return undefined; } public getColorSchema(): IJSONSchema { return this.colorSchema; } public getColorReferenceSchema(): IJSONSchema { return this.colorReferenceSchema; } public toString() { let sorter = (a: string, b: string) => { let cat1 = a.indexOf('.') === -1 ? 0 : 1; let cat2 = b.indexOf('.') === -1 ? 0 : 1; if (cat1 !== cat2) { return cat1 - cat2; } return a.localeCompare(b); }; return Object.keys(this.colorsById).sort(sorter).map(k => `- \`${k}\`: ${this.colorsById[k].description}`).join('\n'); } } const colorRegistry = new ColorRegistry(); platform.Registry.add(Extensions.ColorContribution, colorRegistry); export function registerColor(id: string, defaults: ColorDefaults | null, description: string, needsTransparency?: boolean, deprecationMessage?: string): ColorIdentifier { return colorRegistry.registerColor(id, defaults, description, needsTransparency, deprecationMessage); } export function getColorRegistry(): IColorRegistry { return colorRegistry; } // ----- base colors export const foreground = registerColor('foreground', { dark: '#CCCCCC', light: '#616161', hc: '#FFFFFF' }, nls.localize('foreground', "Overall foreground color. This color is only used if not overridden by a component.")); export const errorForeground = registerColor('errorForeground', { dark: '#F48771', light: '#A1260D', hc: '#F48771' }, nls.localize('errorForeground', "Overall foreground color for error messages. This color is only used if not overridden by a component.")); export const descriptionForeground = registerColor('descriptionForeground', { light: '#717171', dark: transparent(foreground, 0.7), hc: transparent(foreground, 0.7) }, nls.localize('descriptionForeground', "Foreground color for description text providing additional information, for example for a label.")); export const iconForeground = registerColor('icon.foreground', { dark: '#C5C5C5', light: '#424242', hc: '#FFFFFF' }, nls.localize('iconForeground', "The default color for icons in the workbench.")); export const focusBorder = registerColor('focusBorder', { dark: Color.fromHex('#0E639C').transparent(0.8), light: Color.fromHex('#007ACC').transparent(0.4), hc: '#F38518' }, nls.localize('focusBorder', "Overall border color for focused elements. This color is only used if not overridden by a component.")); export const contrastBorder = registerColor('contrastBorder', { light: null, dark: null, hc: '#6FC3DF' }, nls.localize('contrastBorder', "An extra border around elements to separate them from others for greater contrast.")); export const activeContrastBorder = registerColor('contrastActiveBorder', { light: null, dark: null, hc: focusBorder }, nls.localize('activeContrastBorder', "An extra border around active elements to separate them from others for greater contrast.")); export const selectionBackground = registerColor('selection.background', { light: null, dark: null, hc: null }, nls.localize('selectionBackground', "The background color of text selections in the workbench (e.g. for input fields or text areas). Note that this does not apply to selections within the editor.")); // ------ text colors export const textSeparatorForeground = registerColor('textSeparator.foreground', { light: '#0000002e', dark: '#ffffff2e', hc: Color.black }, nls.localize('textSeparatorForeground', "Color for text separators.")); export const textLinkForeground = registerColor('textLink.foreground', { light: '#006AB1', dark: '#3794FF', hc: '#3794FF' }, nls.localize('textLinkForeground', "Foreground color for links in text.")); export const textLinkActiveForeground = registerColor('textLink.activeForeground', { light: '#006AB1', dark: '#3794FF', hc: '#3794FF' }, nls.localize('textLinkActiveForeground', "Foreground color for links in text when clicked on and on mouse hover.")); export const textPreformatForeground = registerColor('textPreformat.foreground', { light: '#A31515', dark: '#D7BA7D', hc: '#D7BA7D' }, nls.localize('textPreformatForeground', "Foreground color for preformatted text segments.")); export const textBlockQuoteBackground = registerColor('textBlockQuote.background', { light: '#7f7f7f1a', dark: '#7f7f7f1a', hc: null }, nls.localize('textBlockQuoteBackground', "Background color for block quotes in text.")); export const textBlockQuoteBorder = registerColor('textBlockQuote.border', { light: '#007acc80', dark: '#007acc80', hc: Color.white }, nls.localize('textBlockQuoteBorder', "Border color for block quotes in text.")); export const textCodeBlockBackground = registerColor('textCodeBlock.background', { light: '#dcdcdc66', dark: '#0a0a0a66', hc: Color.black }, nls.localize('textCodeBlockBackground', "Background color for code blocks in text.")); // ----- widgets export const widgetShadow = registerColor('widget.shadow', { dark: '#000000', light: '#A8A8A8', hc: null }, nls.localize('widgetShadow', 'Shadow color of widgets such as find/replace inside the editor.')); export const inputBackground = registerColor('input.background', { dark: '#3C3C3C', light: Color.white, hc: Color.black }, nls.localize('inputBoxBackground', "Input box background.")); export const inputForeground = registerColor('input.foreground', { dark: foreground, light: foreground, hc: foreground }, nls.localize('inputBoxForeground', "Input box foreground.")); export const inputBorder = registerColor('input.border', { dark: null, light: null, hc: contrastBorder }, nls.localize('inputBoxBorder', "Input box border.")); export const inputActiveOptionBorder = registerColor('inputOption.activeBorder', { dark: '#007ACC00', light: '#007ACC00', hc: contrastBorder }, nls.localize('inputBoxActiveOptionBorder', "Border color of activated options in input fields.")); export const inputActiveOptionBackground = registerColor('inputOption.activeBackground', { dark: transparent(focusBorder, 0.5), light: transparent(focusBorder, 0.3), hc: null }, nls.localize('inputOption.activeBackground', "Background color of activated options in input fields.")); export const inputPlaceholderForeground = registerColor('input.placeholderForeground', { light: transparent(foreground, 0.5), dark: transparent(foreground, 0.5), hc: transparent(foreground, 0.7) }, nls.localize('inputPlaceholderForeground', "Input box foreground color for placeholder text.")); export const inputValidationInfoBackground = registerColor('inputValidation.infoBackground', { dark: '#063B49', light: '#D6ECF2', hc: Color.black }, nls.localize('inputValidationInfoBackground', "Input validation background color for information severity.")); export const inputValidationInfoForeground = registerColor('inputValidation.infoForeground', { dark: null, light: null, hc: null }, nls.localize('inputValidationInfoForeground', "Input validation foreground color for information severity.")); export const inputValidationInfoBorder = registerColor('inputValidation.infoBorder', { dark: '#007acc', light: '#007acc', hc: contrastBorder }, nls.localize('inputValidationInfoBorder', "Input validation border color for information severity.")); export const inputValidationWarningBackground = registerColor('inputValidation.warningBackground', { dark: '#352A05', light: '#F6F5D2', hc: Color.black }, nls.localize('inputValidationWarningBackground', "Input validation background color for warning severity.")); export const inputValidationWarningForeground = registerColor('inputValidation.warningForeground', { dark: null, light: null, hc: null }, nls.localize('inputValidationWarningForeground', "Input validation foreground color for warning severity.")); export const inputValidationWarningBorder = registerColor('inputValidation.warningBorder', { dark: '#B89500', light: '#B89500', hc: contrastBorder }, nls.localize('inputValidationWarningBorder', "Input validation border color for warning severity.")); export const inputValidationErrorBackground = registerColor('inputValidation.errorBackground', { dark: '#5A1D1D', light: '#F2DEDE', hc: Color.black }, nls.localize('inputValidationErrorBackground', "Input validation background color for error severity.")); export const inputValidationErrorForeground = registerColor('inputValidation.errorForeground', { dark: null, light: null, hc: null }, nls.localize('inputValidationErrorForeground', "Input validation foreground color for error severity.")); export const inputValidationErrorBorder = registerColor('inputValidation.errorBorder', { dark: '#BE1100', light: '#BE1100', hc: contrastBorder }, nls.localize('inputValidationErrorBorder', "Input validation border color for error severity.")); export const selectBackground = registerColor('dropdown.background', { dark: '#3C3C3C', light: Color.white, hc: Color.black }, nls.localize('dropdownBackground', "Dropdown background.")); export const selectListBackground = registerColor('dropdown.listBackground', { dark: null, light: null, hc: Color.black }, nls.localize('dropdownListBackground', "Dropdown list background.")); export const selectForeground = registerColor('dropdown.foreground', { dark: '#F0F0F0', light: null, hc: Color.white }, nls.localize('dropdownForeground', "Dropdown foreground.")); export const selectBorder = registerColor('dropdown.border', { dark: selectBackground, light: '#CECECE', hc: contrastBorder }, nls.localize('dropdownBorder', "Dropdown border.")); export const simpleCheckboxBackground = registerColor('checkbox.background', { dark: selectBackground, light: selectBackground, hc: selectBackground }, nls.localize('checkbox.background', "Background color of checkbox widget.")); export const simpleCheckboxForeground = registerColor('checkbox.foreground', { dark: selectForeground, light: selectForeground, hc: selectForeground }, nls.localize('checkbox.foreground', "Foreground color of checkbox widget.")); export const simpleCheckboxBorder = registerColor('checkbox.border', { dark: selectBorder, light: selectBorder, hc: selectBorder }, nls.localize('checkbox.border', "Border color of checkbox widget.")); export const buttonForeground = registerColor('button.foreground', { dark: Color.white, light: Color.white, hc: Color.white }, nls.localize('buttonForeground', "Button foreground color.")); export const buttonBackground = registerColor('button.background', { dark: '#0E639C', light: '#007ACC', hc: null }, nls.localize('buttonBackground', "Button background color.")); export const buttonHoverBackground = registerColor('button.hoverBackground', { dark: lighten(buttonBackground, 0.2), light: darken(buttonBackground, 0.2), hc: null }, nls.localize('buttonHoverBackground', "Button background color when hovering.")); export const badgeBackground = registerColor('badge.background', { dark: '#4D4D4D', light: '#C4C4C4', hc: Color.black }, nls.localize('badgeBackground', "Badge background color. Badges are small information labels, e.g. for search results count.")); export const badgeForeground = registerColor('badge.foreground', { dark: Color.white, light: '#333', hc: Color.white }, nls.localize('badgeForeground', "Badge foreground color. Badges are small information labels, e.g. for search results count.")); export const scrollbarShadow = registerColor('scrollbar.shadow', { dark: '#000000', light: '#DDDDDD', hc: null }, nls.localize('scrollbarShadow', "Scrollbar shadow to indicate that the view is scrolled.")); export const scrollbarSliderBackground = registerColor('scrollbarSlider.background', { dark: Color.fromHex('#797979').transparent(0.4), light: Color.fromHex('#646464').transparent(0.4), hc: transparent(contrastBorder, 0.6) }, nls.localize('scrollbarSliderBackground', "Scrollbar slider background color.")); export const scrollbarSliderHoverBackground = registerColor('scrollbarSlider.hoverBackground', { dark: Color.fromHex('#646464').transparent(0.7), light: Color.fromHex('#646464').transparent(0.7), hc: transparent(contrastBorder, 0.8) }, nls.localize('scrollbarSliderHoverBackground', "Scrollbar slider background color when hovering.")); export const scrollbarSliderActiveBackground = registerColor('scrollbarSlider.activeBackground', { dark: Color.fromHex('#BFBFBF').transparent(0.4), light: Color.fromHex('#000000').transparent(0.6), hc: contrastBorder }, nls.localize('scrollbarSliderActiveBackground', "Scrollbar slider background color when clicked on.")); export const progressBarBackground = registerColor('progressBar.background', { dark: Color.fromHex('#0E70C0'), light: Color.fromHex('#0E70C0'), hc: contrastBorder }, nls.localize('progressBarBackground', "Background color of the progress bar that can show for long running operations.")); export const editorErrorForeground = registerColor('editorError.foreground', { dark: '#F48771', light: '#E51400', hc: null }, nls.localize('editorError.foreground', 'Foreground color of error squigglies in the editor.')); export const editorErrorBorder = registerColor('editorError.border', { dark: null, light: null, hc: Color.fromHex('#E47777').transparent(0.8) }, nls.localize('errorBorder', 'Border color of error boxes in the editor.')); export const editorWarningForeground = registerColor('editorWarning.foreground', { dark: '#CCA700', light: '#E9A700', hc: null }, nls.localize('editorWarning.foreground', 'Foreground color of warning squigglies in the editor.')); export const editorWarningBorder = registerColor('editorWarning.border', { dark: null, light: null, hc: Color.fromHex('#FFCC00').transparent(0.8) }, nls.localize('warningBorder', 'Border color of warning boxes in the editor.')); export const editorInfoForeground = registerColor('editorInfo.foreground', { dark: '#75BEFF', light: '#75BEFF', hc: null }, nls.localize('editorInfo.foreground', 'Foreground color of info squigglies in the editor.')); export const editorInfoBorder = registerColor('editorInfo.border', { dark: null, light: null, hc: Color.fromHex('#75BEFF').transparent(0.8) }, nls.localize('infoBorder', 'Border color of info boxes in the editor.')); export const editorHintForeground = registerColor('editorHint.foreground', { dark: Color.fromHex('#eeeeee').transparent(0.7), light: '#6c6c6c', hc: null }, nls.localize('editorHint.foreground', 'Foreground color of hint squigglies in the editor.')); export const editorHintBorder = registerColor('editorHint.border', { dark: null, light: null, hc: Color.fromHex('#eeeeee').transparent(0.8) }, nls.localize('hintBorder', 'Border color of hint boxes in the editor.')); /** * Editor background color. * Because of bug https://monacotools.visualstudio.com/DefaultCollection/Monaco/_workitems/edit/13254 * we are *not* using the color white (or #ffffff, rgba(255,255,255)) but something very close to white. */ export const editorBackground = registerColor('editor.background', { light: '#fffffe', dark: '#1E1E1E', hc: Color.black }, nls.localize('editorBackground', "Editor background color.")); /** * Editor foreground color. */ export const editorForeground = registerColor('editor.foreground', { light: '#333333', dark: '#BBBBBB', hc: Color.white }, nls.localize('editorForeground', "Editor default foreground color.")); /** * Editor widgets */ export const editorWidgetBackground = registerColor('editorWidget.background', { dark: '#252526', light: '#F3F3F3', hc: '#0C141F' }, nls.localize('editorWidgetBackground', 'Background color of editor widgets, such as find/replace.')); export const editorWidgetForeground = registerColor('editorWidget.foreground', { dark: foreground, light: foreground, hc: foreground }, nls.localize('editorWidgetForeground', 'Foreground color of editor widgets, such as find/replace.')); export const editorWidgetBorder = registerColor('editorWidget.border', { dark: '#454545', light: '#C8C8C8', hc: contrastBorder }, nls.localize('editorWidgetBorder', 'Border color of editor widgets. The color is only used if the widget chooses to have a border and if the color is not overridden by a widget.')); export const editorWidgetResizeBorder = registerColor('editorWidget.resizeBorder', { light: null, dark: null, hc: null }, nls.localize('editorWidgetResizeBorder', "Border color of the resize bar of editor widgets. The color is only used if the widget chooses to have a resize border and if the color is not overridden by a widget.")); /** * Quick pick widget */ export const quickInputBackground = registerColor('quickInput.background', { dark: editorWidgetBackground, light: editorWidgetBackground, hc: editorWidgetBackground }, nls.localize('pickerBackground', "Quick picker background color. The quick picker widget is the container for pickers like the command palette.")); export const quickInputForeground = registerColor('quickInput.foreground', { dark: editorWidgetForeground, light: editorWidgetForeground, hc: editorWidgetForeground }, nls.localize('pickerForeground', "Quick picker foreground color. The quick picker widget is the container for pickers like the command palette.")); export const quickInputTitleBackground = registerColor('quickInputTitle.background', { dark: new Color(new RGBA(255, 255, 255, 0.105)), light: new Color(new RGBA(0, 0, 0, 0.06)), hc: '#000000' }, nls.localize('pickerTitleBackground', "Quick picker title background color. The quick picker widget is the container for pickers like the command palette.")); export const pickerGroupForeground = registerColor('pickerGroup.foreground', { dark: '#3794FF', light: '#0066BF', hc: Color.white }, nls.localize('pickerGroupForeground', "Quick picker color for grouping labels.")); export const pickerGroupBorder = registerColor('pickerGroup.border', { dark: '#3F3F46', light: '#CCCEDB', hc: Color.white }, nls.localize('pickerGroupBorder', "Quick picker color for grouping borders.")); /** * Editor selection colors. */ export const editorSelectionBackground = registerColor('editor.selectionBackground', { light: '#ADD6FF', dark: '#264F78', hc: '#f3f518' }, nls.localize('editorSelectionBackground', "Color of the editor selection.")); export const editorSelectionForeground = registerColor('editor.selectionForeground', { light: null, dark: null, hc: '#000000' }, nls.localize('editorSelectionForeground', "Color of the selected text for high contrast.")); export const editorInactiveSelection = registerColor('editor.inactiveSelectionBackground', { light: transparent(editorSelectionBackground, 0.5), dark: transparent(editorSelectionBackground, 0.5), hc: transparent(editorSelectionBackground, 0.5) }, nls.localize('editorInactiveSelection', "Color of the selection in an inactive editor. The color must not be opaque so as not to hide underlying decorations."), true); export const editorSelectionHighlight = registerColor('editor.selectionHighlightBackground', { light: lessProminent(editorSelectionBackground, editorBackground, 0.3, 0.6), dark: lessProminent(editorSelectionBackground, editorBackground, 0.3, 0.6), hc: null }, nls.localize('editorSelectionHighlight', 'Color for regions with the same content as the selection. The color must not be opaque so as not to hide underlying decorations.'), true); export const editorSelectionHighlightBorder = registerColor('editor.selectionHighlightBorder', { light: null, dark: null, hc: activeContrastBorder }, nls.localize('editorSelectionHighlightBorder', "Border color for regions with the same content as the selection.")); /** * Editor find match colors. */ export const editorFindMatch = registerColor('editor.findMatchBackground', { light: '#A8AC94', dark: '#515C6A', hc: null }, nls.localize('editorFindMatch', "Color of the current search match.")); export const editorFindMatchHighlight = registerColor('editor.findMatchHighlightBackground', { light: '#EA5C0055', dark: '#EA5C0055', hc: null }, nls.localize('findMatchHighlight', "Color of the other search matches. The color must not be opaque so as not to hide underlying decorations."), true); export const editorFindRangeHighlight = registerColor('editor.findRangeHighlightBackground', { dark: '#3a3d4166', light: '#b4b4b44d', hc: null }, nls.localize('findRangeHighlight', "Color of the range limiting the search. The color must not be opaque so as not to hide underlying decorations."), true); export const editorFindMatchBorder = registerColor('editor.findMatchBorder', { light: null, dark: null, hc: activeContrastBorder }, nls.localize('editorFindMatchBorder', "Border color of the current search match.")); export const editorFindMatchHighlightBorder = registerColor('editor.findMatchHighlightBorder', { light: null, dark: null, hc: activeContrastBorder }, nls.localize('findMatchHighlightBorder', "Border color of the other search matches.")); export const editorFindRangeHighlightBorder = registerColor('editor.findRangeHighlightBorder', { dark: null, light: null, hc: transparent(activeContrastBorder, 0.4) }, nls.localize('findRangeHighlightBorder', "Border color of the range limiting the search. The color must not be opaque so as not to hide underlying decorations."), true); /** * Search Editor query match colors. * * Distinct from normal editor find match to allow for better differentiation */ export const searchEditorFindMatch = registerColor('searchEditor.findMatchBackground', { light: transparent(editorFindMatchHighlight, 0.66), dark: transparent(editorFindMatchHighlight, 0.66), hc: editorFindMatchHighlight }, nls.localize('searchEditor.queryMatch', "Color of the Search Editor query matches.")); export const searchEditorFindMatchBorder = registerColor('searchEditor.findMatchBorder', { light: transparent(editorFindMatchHighlightBorder, 0.66), dark: transparent(editorFindMatchHighlightBorder, 0.66), hc: editorFindMatchHighlightBorder }, nls.localize('searchEditor.editorFindMatchBorder', "Border color of the Search Editor query matches.")); /** * Editor hover */ export const editorHoverHighlight = registerColor('editor.hoverHighlightBackground', { light: '#ADD6FF26', dark: '#264f7840', hc: '#ADD6FF26' }, nls.localize('hoverHighlight', 'Highlight below the word for which a hover is shown. The color must not be opaque so as not to hide underlying decorations.'), true); export const editorHoverBackground = registerColor('editorHoverWidget.background', { light: editorWidgetBackground, dark: editorWidgetBackground, hc: editorWidgetBackground }, nls.localize('hoverBackground', 'Background color of the editor hover.')); export const editorHoverForeground = registerColor('editorHoverWidget.foreground', { light: editorWidgetForeground, dark: editorWidgetForeground, hc: editorWidgetForeground }, nls.localize('hoverForeground', 'Foreground color of the editor hover.')); export const editorHoverBorder = registerColor('editorHoverWidget.border', { light: editorWidgetBorder, dark: editorWidgetBorder, hc: editorWidgetBorder }, nls.localize('hoverBorder', 'Border color of the editor hover.')); export const editorHoverStatusBarBackground = registerColor('editorHoverWidget.statusBarBackground', { dark: lighten(editorHoverBackground, 0.2), light: darken(editorHoverBackground, 0.05), hc: editorWidgetBackground }, nls.localize('statusBarBackground', "Background color of the editor hover status bar.")); /** * Editor link colors */ export const editorActiveLinkForeground = registerColor('editorLink.activeForeground', { dark: '#4E94CE', light: Color.blue, hc: Color.cyan }, nls.localize('activeLinkForeground', 'Color of active links.')); /** * Editor lighbulb icon colors */ export const editorLightBulbForeground = registerColor('editorLightBulb.foreground', { dark: '#FFCC00', light: '#DDB100', hc: '#FFCC00' }, nls.localize('editorLightBulbForeground', "The color used for the lightbulb actions icon.")); export const editorLightBulbAutoFixForeground = registerColor('editorLightBulbAutoFix.foreground', { dark: '#75BEFF', light: '#007ACC', hc: '#75BEFF' }, nls.localize('editorLightBulbAutoFixForeground', "The color used for the lightbulb auto fix actions icon.")); /** * Diff Editor Colors */ export const defaultInsertColor = new Color(new RGBA(155, 185, 85, 0.2)); export const defaultRemoveColor = new Color(new RGBA(255, 0, 0, 0.2)); export const diffInserted = registerColor('diffEditor.insertedTextBackground', { dark: defaultInsertColor, light: defaultInsertColor, hc: null }, nls.localize('diffEditorInserted', 'Background color for text that got inserted. The color must not be opaque so as not to hide underlying decorations.'), true); export const diffRemoved = registerColor('diffEditor.removedTextBackground', { dark: defaultRemoveColor, light: defaultRemoveColor, hc: null }, nls.localize('diffEditorRemoved', 'Background color for text that got removed. The color must not be opaque so as not to hide underlying decorations.'), true); export const diffInsertedOutline = registerColor('diffEditor.insertedTextBorder', { dark: null, light: null, hc: '#33ff2eff' }, nls.localize('diffEditorInsertedOutline', 'Outline color for the text that got inserted.')); export const diffRemovedOutline = registerColor('diffEditor.removedTextBorder', { dark: null, light: null, hc: '#FF008F' }, nls.localize('diffEditorRemovedOutline', 'Outline color for text that got removed.')); export const diffBorder = registerColor('diffEditor.border', { dark: null, light: null, hc: contrastBorder }, nls.localize('diffEditorBorder', 'Border color between the two text editors.')); export const diffDiagonalFill = registerColor('diffEditor.diagonalFill', { dark: '#cccccc33', light: '#22222233', hc: null }, nls.localize('diffDiagonalFill', "Color of the diff editor's diagonal fill. The diagonal fill is used in side-by-side diff views.")); /** * List and tree colors */ export const listFocusBackground = registerColor('list.focusBackground', { dark: '#062F4A', light: '#D6EBFF', hc: null }, nls.localize('listFocusBackground', "List/Tree background color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not.")); export const listFocusForeground = registerColor('list.focusForeground', { dark: null, light: null, hc: null }, nls.localize('listFocusForeground', "List/Tree foreground color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not.")); export const listActiveSelectionBackground = registerColor('list.activeSelectionBackground', { dark: '#094771', light: '#0074E8', hc: null }, nls.localize('listActiveSelectionBackground', "List/Tree background color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not.")); export const listActiveSelectionForeground = registerColor('list.activeSelectionForeground', { dark: Color.white, light: Color.white, hc: null }, nls.localize('listActiveSelectionForeground', "List/Tree foreground color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not.")); export const listInactiveSelectionBackground = registerColor('list.inactiveSelectionBackground', { dark: '#37373D', light: '#E4E6F1', hc: null }, nls.localize('listInactiveSelectionBackground', "List/Tree background color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not.")); export const listInactiveSelectionForeground = registerColor('list.inactiveSelectionForeground', { dark: null, light: null, hc: null }, nls.localize('listInactiveSelectionForeground', "List/Tree foreground color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not.")); export const listInactiveFocusBackground = registerColor('list.inactiveFocusBackground', { dark: null, light: null, hc: null }, nls.localize('listInactiveFocusBackground', "List/Tree background color for the focused item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not.")); export const listHoverBackground = registerColor('list.hoverBackground', { dark: '#2A2D2E', light: '#F0F0F0', hc: null }, nls.localize('listHoverBackground', "List/Tree background when hovering over items using the mouse.")); export const listHoverForeground = registerColor('list.hoverForeground', { dark: null, light: null, hc: null }, nls.localize('listHoverForeground', "List/Tree foreground when hovering over items using the mouse.")); export const listDropBackground = registerColor('list.dropBackground', { dark: listFocusBackground, light: listFocusBackground, hc: null }, nls.localize('listDropBackground', "List/Tree drag and drop background when moving items around using the mouse.")); export const listHighlightForeground = registerColor('list.highlightForeground', { dark: '#0097fb', light: '#0066BF', hc: focusBorder }, nls.localize('highlight', 'List/Tree foreground color of the match highlights when searching inside the list/tree.')); export const listInvalidItemForeground = registerColor('list.invalidItemForeground', { dark: '#B89500', light: '#B89500', hc: '#B89500' }, nls.localize('invalidItemForeground', 'List/Tree foreground color for invalid items, for example an unresolved root in explorer.')); export const listErrorForeground = registerColor('list.errorForeground', { dark: '#F88070', light: '#B01011', hc: null }, nls.localize('listErrorForeground', 'Foreground color of list items containing errors.')); export const listWarningForeground = registerColor('list.warningForeground', { dark: '#CCA700', light: '#855F00', hc: null }, nls.localize('listWarningForeground', 'Foreground color of list items containing warnings.')); export const listFilterWidgetBackground = registerColor('listFilterWidget.background', { light: '#efc1ad', dark: '#653723', hc: Color.black }, nls.localize('listFilterWidgetBackground', 'Background color of the type filter widget in lists and trees.')); export const listFilterWidgetOutline = registerColor('listFilterWidget.outline', { dark: Color.transparent, light: Color.transparent, hc: '#f38518' }, nls.localize('listFilterWidgetOutline', 'Outline color of the type filter widget in lists and trees.')); export const listFilterWidgetNoMatchesOutline = registerColor('listFilterWidget.noMatchesOutline', { dark: '#BE1100', light: '#BE1100', hc: contrastBorder }, nls.localize('listFilterWidgetNoMatchesOutline', 'Outline color of the type filter widget in lists and trees, when there are no matches.')); export const listFilterMatchHighlight = registerColor('list.filterMatchBackground', { dark: editorFindMatchHighlight, light: editorFindMatchHighlight, hc: null }, nls.localize('listFilterMatchHighlight', 'Background color of the filtered match.')); export const listFilterMatchHighlightBorder = registerColor('list.filterMatchBorder', { dark: editorFindMatchHighlightBorder, light: editorFindMatchHighlightBorder, hc: contrastBorder }, nls.localize('listFilterMatchHighlightBorder', 'Border color of the filtered match.')); export const treeIndentGuidesStroke = registerColor('tree.indentGuidesStroke', { dark: '#585858', light: '#a9a9a9', hc: '#a9a9a9' }, nls.localize('treeIndentGuidesStroke', "Tree stroke color for the indentation guides.")); export const listDeemphasizedForeground = registerColor('list.deemphasizedForeground', { dark: '#8C8C8C', light: '#8E8E90', hc: '#A7A8A9' }, nls.localize('listDeemphasizedForeground', "List/Tree foreground color for items that are deemphasized. ")); /** * Menu colors */ export const menuBorder = registerColor('menu.border', { dark: null, light: null, hc: contrastBorder }, nls.localize('menuBorder', "Border color of menus.")); export const menuForeground = registerColor('menu.foreground', { dark: selectForeground, light: foreground, hc: selectForeground }, nls.localize('menuForeground', "Foreground color of menu items.")); export const menuBackground = registerColor('menu.background', { dark: selectBackground, light: selectBackground, hc: selectBackground }, nls.localize('menuBackground', "Background color of menu items.")); export const menuSelectionForeground = registerColor('menu.selectionForeground', { dark: listActiveSelectionForeground, light: listActiveSelectionForeground, hc: listActiveSelectionForeground }, nls.localize('menuSelectionForeground', "Foreground color of the selected menu item in menus.")); export const menuSelectionBackground = registerColor('menu.selectionBackground', { dark: listActiveSelectionBackground, light: listActiveSelectionBackground, hc: listActiveSelectionBackground }, nls.localize('menuSelectionBackground', "Background color of the selected menu item in menus.")); export const menuSelectionBorder = registerColor('menu.selectionBorder', { dark: null, light: null, hc: activeContrastBorder }, nls.localize('menuSelectionBorder', "Border color of the selected menu item in menus.")); export const menuSeparatorBackground = registerColor('menu.separatorBackground', { dark: '#BBBBBB', light: '#888888', hc: contrastBorder }, nls.localize('menuSeparatorBackground', "Color of a separator menu item in menus.")); /** * Snippet placeholder colors */ export const snippetTabstopHighlightBackground = registerColor('editor.snippetTabstopHighlightBackground', { dark: new Color(new RGBA(124, 124, 124, 0.3)), light: new Color(new RGBA(10, 50, 100, 0.2)), hc: new Color(new RGBA(124, 124, 124, 0.3)) }, nls.localize('snippetTabstopHighlightBackground', "Highlight background color of a snippet tabstop.")); export const snippetTabstopHighlightBorder = registerColor('editor.snippetTabstopHighlightBorder', { dark: null, light: null, hc: null }, nls.localize('snippetTabstopHighlightBorder', "Highlight border color of a snippet tabstop.")); export const snippetFinalTabstopHighlightBackground = registerColor('editor.snippetFinalTabstopHighlightBackground', { dark: null, light: null, hc: null }, nls.localize('snippetFinalTabstopHighlightBackground', "Highlight background color of the final tabstop of a snippet.")); export const snippetFinalTabstopHighlightBorder = registerColor('editor.snippetFinalTabstopHighlightBorder', { dark: '#525252', light: new Color(new RGBA(10, 50, 100, 0.5)), hc: '#525252' }, nls.localize('snippetFinalTabstopHighlightBorder', "Highlight border color of the final stabstop of a snippet.")); /** * Breadcrumb colors */ export const breadcrumbsForeground = registerColor('breadcrumb.foreground', { light: transparent(foreground, 0.8), dark: transparent(foreground, 0.8), hc: transparent(foreground, 0.8) }, nls.localize('breadcrumbsFocusForeground', "Color of focused breadcrumb items.")); export const breadcrumbsBackground = registerColor('breadcrumb.background', { light: editorBackground, dark: editorBackground, hc: editorBackground }, nls.localize('breadcrumbsBackground', "Background color of breadcrumb items.")); export const breadcrumbsFocusForeground = registerColor('breadcrumb.focusForeground', { light: darken(foreground, 0.2), dark: lighten(foreground, 0.1), hc: lighten(foreground, 0.1) }, nls.localize('breadcrumbsFocusForeground', "Color of focused breadcrumb items.")); export const breadcrumbsActiveSelectionForeground = registerColor('breadcrumb.activeSelectionForeground', { light: darken(foreground, 0.2), dark: lighten(foreground, 0.1), hc: lighten(foreground, 0.1) }, nls.localize('breadcrumbsSelectedForegound', "Color of selected breadcrumb items.")); export const breadcrumbsPickerBackground = registerColor('breadcrumbPicker.background', { light: editorWidgetBackground, dark: editorWidgetBackground, hc: editorWidgetBackground }, nls.localize('breadcrumbsSelectedBackground', "Background color of breadcrumb item picker.")); /** * Merge-conflict colors */ const headerTransparency = 0.5; const currentBaseColor = Color.fromHex('#40C8AE').transparent(headerTransparency); const incomingBaseColor = Color.fromHex('#40A6FF').transparent(headerTransparency); const commonBaseColor = Color.fromHex('#606060').transparent(0.4); const contentTransparency = 0.4; const rulerTransparency = 1; export const mergeCurrentHeaderBackground = registerColor('merge.currentHeaderBackground', { dark: currentBaseColor, light: currentBaseColor, hc: null }, nls.localize('mergeCurrentHeaderBackground', 'Current header background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.'), true); export const mergeCurrentContentBackground = registerColor('merge.currentContentBackground', { dark: transparent(mergeCurrentHeaderBackground, contentTransparency), light: transparent(mergeCurrentHeaderBackground, contentTransparency), hc: transparent(mergeCurrentHeaderBackground, contentTransparency) }, nls.localize('mergeCurrentContentBackground', 'Current content background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.'), true); export const mergeIncomingHeaderBackground = registerColor('merge.incomingHeaderBackground', { dark: incomingBaseColor, light: incomingBaseColor, hc: null }, nls.localize('mergeIncomingHeaderBackground', 'Incoming header background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.'), true); export const mergeIncomingContentBackground = registerColor('merge.incomingContentBackground', { dark: transparent(mergeIncomingHeaderBackground, contentTransparency), light: transparent(mergeIncomingHeaderBackground, contentTransparency), hc: transparent(mergeIncomingHeaderBackground, contentTransparency) }, nls.localize('mergeIncomingContentBackground', 'Incoming content background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.'), true); export const mergeCommonHeaderBackground = registerColor('merge.commonHeaderBackground', { dark: commonBaseColor, light: commonBaseColor, hc: null }, nls.localize('mergeCommonHeaderBackground', 'Common ancestor header background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.'), true); export const mergeCommonContentBackground = registerColor('merge.commonContentBackground', { dark: transparent(mergeCommonHeaderBackground, contentTransparency), light: transparent(mergeCommonHeaderBackground, contentTransparency), hc: transparent(mergeCommonHeaderBackground, contentTransparency) }, nls.localize('mergeCommonContentBackground', 'Common ancestor content background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.'), true); export const mergeBorder = registerColor('merge.border', { dark: null, light: null, hc: '#C3DF6F' }, nls.localize('mergeBorder', 'Border color on headers and the splitter in inline merge-conflicts.')); export const overviewRulerCurrentContentForeground = registerColor('editorOverviewRuler.currentContentForeground', { dark: transparent(mergeCurrentHeaderBackground, rulerTransparency), light: transparent(mergeCurrentHeaderBackground, rulerTransparency), hc: mergeBorder }, nls.localize('overviewRulerCurrentContentForeground', 'Current overview ruler foreground for inline merge-conflicts.')); export const overviewRulerIncomingContentForeground = registerColor('editorOverviewRuler.incomingContentForeground', { dark: transparent(mergeIncomingHeaderBackground, rulerTransparency), light: transparent(mergeIncomingHeaderBackground, rulerTransparency), hc: mergeBorder }, nls.localize('overviewRulerIncomingContentForeground', 'Incoming overview ruler foreground for inline merge-conflicts.')); export const overviewRulerCommonContentForeground = registerColor('editorOverviewRuler.commonContentForeground', { dark: transparent(mergeCommonHeaderBackground, rulerTransparency), light: transparent(mergeCommonHeaderBackground, rulerTransparency), hc: mergeBorder }, nls.localize('overviewRulerCommonContentForeground', 'Common ancestor overview ruler foreground for inline merge-conflicts.')); export const overviewRulerFindMatchForeground = registerColor('editorOverviewRuler.findMatchForeground', { dark: '#d186167e', light: '#d186167e', hc: '#AB5A00' }, nls.localize('overviewRulerFindMatchForeground', 'Overview ruler marker color for find matches. The color must not be opaque so as not to hide underlying decorations.'), true); export const overviewRulerSelectionHighlightForeground = registerColor('editorOverviewRuler.selectionHighlightForeground', { dark: '#A0A0A0CC', light: '#A0A0A0CC', hc: '#A0A0A0CC' }, nls.localize('overviewRulerSelectionHighlightForeground', 'Overview ruler marker color for selection highlights. The color must not be opaque so as not to hide underlying decorations.'), true); export const minimapFindMatch = registerColor('minimap.findMatchHighlight', { light: '#d18616', dark: '#d18616', hc: '#AB5A00' }, nls.localize('minimapFindMatchHighlight', 'Minimap marker color for find matches.'), true); export const minimapSelection = registerColor('minimap.selectionHighlight', { light: '#ADD6FF', dark: '#264F78', hc: '#ffffff' }, nls.localize('minimapSelectionHighlight', 'Minimap marker color for the editor selection.'), true); export const minimapError = registerColor('minimap.errorHighlight', { dark: new Color(new RGBA(255, 18, 18, 0.7)), light: new Color(new RGBA(255, 18, 18, 0.7)), hc: new Color(new RGBA(255, 50, 50, 1)) }, nls.localize('minimapError', 'Minimap marker color for errors.')); export const minimapWarning = registerColor('minimap.warningHighlight', { dark: editorWarningForeground, light: editorWarningForeground, hc: editorWarningBorder }, nls.localize('overviewRuleWarning', 'Minimap marker color for warnings.')); export const minimapBackground = registerColor('minimap.background', { dark: null, light: null, hc: null }, nls.localize('minimapBackground', "Minimap background color.")); export const minimapSliderBackground = registerColor('minimapSlider.background', { light: transparent(scrollbarSliderBackground, 0.5), dark: transparent(scrollbarSliderBackground, 0.5), hc: transparent(scrollbarSliderBackground, 0.5) }, nls.localize('minimapSliderBackground', "Minimap slider background color.")); export const minimapSliderHoverBackground = registerColor('minimapSlider.hoverBackground', { light: transparent(scrollbarSliderHoverBackground, 0.5), dark: transparent(scrollbarSliderHoverBackground, 0.5), hc: transparent(scrollbarSliderHoverBackground, 0.5) }, nls.localize('minimapSliderHoverBackground', "Minimap slider background color when hovering.")); export const minimapSliderActiveBackground = registerColor('minimapSlider.activeBackground', { light: transparent(scrollbarSliderActiveBackground, 0.5), dark: transparent(scrollbarSliderActiveBackground, 0.5), hc: transparent(scrollbarSliderActiveBackground, 0.5) }, nls.localize('minimapSliderActiveBackground', "Minimap slider background color when clicked on.")); export const problemsErrorIconForeground = registerColor('problemsErrorIcon.foreground', { dark: editorErrorForeground, light: editorErrorForeground, hc: editorErrorForeground }, nls.localize('problemsErrorIconForeground', "The color used for the problems error icon.")); export const problemsWarningIconForeground = registerColor('problemsWarningIcon.foreground', { dark: editorWarningForeground, light: editorWarningForeground, hc: editorWarningForeground }, nls.localize('problemsWarningIconForeground', "The color used for the problems warning icon.")); export const problemsInfoIconForeground = registerColor('problemsInfoIcon.foreground', { dark: editorInfoForeground, light: editorInfoForeground, hc: editorInfoForeground }, nls.localize('problemsInfoIconForeground', "The color used for the problems info icon.")); // ----- color functions export function darken(colorValue: ColorValue, factor: number): ColorFunction { return (theme) => { let color = resolveColorValue(colorValue, theme); if (color) { return color.darken(factor); } return undefined; }; } export function lighten(colorValue: ColorValue, factor: number): ColorFunction { return (theme) => { let color = resolveColorValue(colorValue, theme); if (color) { return color.lighten(factor); } return undefined; }; } export function transparent(colorValue: ColorValue, factor: number): ColorFunction { return (theme) => { let color = resolveColorValue(colorValue, theme); if (color) { return color.transparent(factor); } return undefined; }; } export function oneOf(...colorValues: ColorValue[]): ColorFunction { return (theme) => { for (let colorValue of colorValues) { let color = resolveColorValue(colorValue, theme); if (color) { return color; } } return undefined; }; } function lessProminent(colorValue: ColorValue, backgroundColorValue: ColorValue, factor: number, transparency: number): ColorFunction { return (theme) => { let from = resolveColorValue(colorValue, theme); if (from) { let backgroundColor = resolveColorValue(backgroundColorValue, theme); if (backgroundColor) { if (from.isDarkerThan(backgroundColor)) { return Color.getLighterColor(from, backgroundColor, factor).transparent(transparency); } return Color.getDarkerColor(from, backgroundColor, factor).transparent(transparency); } return from.transparent(factor * transparency); } return undefined; }; } // ----- implementation /** * @param colorValue Resolve a color value in the context of a theme */ export function resolveColorValue(colorValue: ColorValue | null, theme: IColorTheme): Color | undefined { if (colorValue === null) { return undefined; } else if (typeof colorValue === 'string') { if (colorValue[0] === '#') { return Color.fromHex(colorValue); } return theme.getColor(colorValue); } else if (colorValue instanceof Color) { return colorValue; } else if (typeof colorValue === 'function') { return colorValue(theme); } return undefined; } export const workbenchColorsSchemaId = 'vscode://schemas/workbench-colors'; let schemaRegistry = platform.Registry.as<IJSONContributionRegistry>(JSONExtensions.JSONContribution); schemaRegistry.registerSchema(workbenchColorsSchemaId, colorRegistry.getColorSchema()); const delayer = new RunOnceScheduler(() => schemaRegistry.notifySchemaChanged(workbenchColorsSchemaId), 200); colorRegistry.onDidChangeSchema(() => { if (!delayer.isScheduled()) { delayer.schedule(); } }); // setTimeout(_ => console.log(colorRegistry.toString()), 5000);
src/vs/platform/theme/common/colorRegistry.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00018089522200170904, 0.00017369154375046492, 0.0001658805413171649, 0.00017432126333005726, 0.0000039776236917532515 ]
{ "id": 3, "code_window": [ "\n", "\t\t\t\treturn this.searchWithProviders(query, progressCallback, token);\n", "\t\t\t})\n", "\t\t\t.then(completes => {\n", "\t\t\t\tcompletes = arrays.coalesce(completes);\n", "\t\t\t\tif (!completes.length) {\n", "\t\t\t\t\treturn {\n", "\t\t\t\t\t\tlimitHit: false,\n", "\t\t\t\t\t\tresults: []\n", "\t\t\t\t\t};\n", "\t\t\t\t}\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\t\tif (onProgress) {\n", "\t\t\t\t\tonProgress(item);\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 136 }
#!/usr/bin/env bash set -e echo 'noop'
build/azure-pipelines/linux/multiarch/armhf/prebuild.sh
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00017089671746362, 0.00017089671746362, 0.00017089671746362, 0.00017089671746362, 0 ]
{ "id": 4, "code_window": [ "\t\t\t\t}\n", "\n" ], "labels": [ "add", "keep" ], "after_edit": [ "\t\t\t};\n", "\n", "\t\t\tconst exists = await Promise.all(query.folderQueries.map(query => this.fileService.exists(query.folder)));\n", "\t\t\tquery.folderQueries = query.folderQueries.filter((_, i) => exists[i]);\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "add", "edit_start_line_idx": 146 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { getPathFromAmdModule } from 'vs/base/common/amd'; import { CancellationToken } from 'vs/base/common/cancellation'; import { canceled } from 'vs/base/common/errors'; import { Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { URI as uri } from 'vs/base/common/uri'; import { getNextTickChannel } from 'vs/base/parts/ipc/common/ipc'; import { Client, IIPCOptions } from 'vs/base/parts/ipc/node/ipc.cp'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IDebugParams, IEnvironmentService } from 'vs/platform/environment/common/environment'; import { parseSearchPort, INativeEnvironmentService } from 'vs/platform/environment/node/environmentService'; import { IFileService } from 'vs/platform/files/common/files'; import { ILogService } from 'vs/platform/log/common/log'; import { FileMatch, IFileMatch, IFileQuery, IProgressMessage, IRawSearchService, ISearchComplete, ISearchConfiguration, ISearchProgressItem, ISearchResultProvider, ISerializedFileMatch, ISerializedSearchComplete, ISerializedSearchProgressItem, isSerializedSearchComplete, isSerializedSearchSuccess, ITextQuery, ISearchService, isFileMatch } from 'vs/workbench/services/search/common/search'; import { SearchChannelClient } from './searchIpc'; import { SearchService } from 'vs/workbench/services/search/common/searchService'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; export class LocalSearchService extends SearchService { constructor( @IModelService modelService: IModelService, @IEditorService editorService: IEditorService, @ITelemetryService telemetryService: ITelemetryService, @ILogService logService: ILogService, @IExtensionService extensionService: IExtensionService, @IFileService fileService: IFileService, @IEnvironmentService readonly environmentService: INativeEnvironmentService, @IInstantiationService readonly instantiationService: IInstantiationService ) { super(modelService, editorService, telemetryService, logService, extensionService, fileService); this.diskSearch = instantiationService.createInstance(DiskSearch, !environmentService.isBuilt || environmentService.verbose, parseSearchPort(environmentService.args, environmentService.isBuilt)); } } export class DiskSearch implements ISearchResultProvider { private raw: IRawSearchService; constructor( verboseLogging: boolean, searchDebug: IDebugParams | undefined, @ILogService private readonly logService: ILogService, @IConfigurationService private readonly configService: IConfigurationService, @IFileService private readonly fileService: IFileService ) { const timeout = this.configService.getValue<ISearchConfiguration>().search.maintainFileSearchCache ? Number.MAX_VALUE : 60 * 60 * 1000; const opts: IIPCOptions = { serverName: 'Search', timeout, args: ['--type=searchService'], // See https://github.com/Microsoft/vscode/issues/27665 // Pass in fresh execArgv to the forked process such that it doesn't inherit them from `process.execArgv`. // e.g. Launching the extension host process with `--inspect-brk=xxx` and then forking a process from the extension host // results in the forked process inheriting `--inspect-brk=xxx`. freshExecArgv: true, env: { AMD_ENTRYPOINT: 'vs/workbench/services/search/node/searchApp', PIPE_LOGGING: 'true', VERBOSE_LOGGING: verboseLogging }, useQueue: true }; if (searchDebug) { if (searchDebug.break && searchDebug.port) { opts.debugBrk = searchDebug.port; } else if (!searchDebug.break && searchDebug.port) { opts.debug = searchDebug.port; } } const client = new Client( getPathFromAmdModule(require, 'bootstrap-fork'), opts); const channel = getNextTickChannel(client.getChannel('search')); this.raw = new SearchChannelClient(channel); } textSearch(query: ITextQuery, onProgress?: (p: ISearchProgressItem) => void, token?: CancellationToken): Promise<ISearchComplete> { const folderQueries = query.folderQueries || []; return Promise.all(folderQueries.map(q => this.fileService.exists(q.folder))) .then(exists => { if (token && token.isCancellationRequested) { throw canceled(); } query.folderQueries = folderQueries.filter((q, index) => exists[index]); const event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete> = this.raw.textSearch(query); return DiskSearch.collectResultsFromEvent(event, onProgress, token); }); } fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { const folderQueries = query.folderQueries || []; return Promise.all(folderQueries.map(q => this.fileService.exists(q.folder))) .then(exists => { if (token && token.isCancellationRequested) { throw canceled(); } query.folderQueries = folderQueries.filter((q, index) => exists[index]); let event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete>; event = this.raw.fileSearch(query); const onProgress = (p: ISearchProgressItem) => { if (!isFileMatch(p)) { // Should only be for logs this.logService.debug('SearchService#search', p.message); } }; return DiskSearch.collectResultsFromEvent(event, onProgress, token); }); } /** * Public for test */ static collectResultsFromEvent(event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete>, onProgress?: (p: ISearchProgressItem) => void, token?: CancellationToken): Promise<ISearchComplete> { let result: IFileMatch[] = []; let listener: IDisposable; return new Promise<ISearchComplete>((c, e) => { if (token) { token.onCancellationRequested(() => { if (listener) { listener.dispose(); } e(canceled()); }); } listener = event(ev => { if (isSerializedSearchComplete(ev)) { if (isSerializedSearchSuccess(ev)) { c({ limitHit: ev.limitHit, results: result, stats: ev.stats }); } else { e(ev.error); } listener.dispose(); } else { // Matches if (Array.isArray(ev)) { const fileMatches = ev.map(d => this.createFileMatch(d)); result = result.concat(fileMatches); if (onProgress) { fileMatches.forEach(onProgress); } } // Match else if ((<ISerializedFileMatch>ev).path) { const fileMatch = this.createFileMatch(<ISerializedFileMatch>ev); result.push(fileMatch); if (onProgress) { onProgress(fileMatch); } } // Progress else if (onProgress) { onProgress(<IProgressMessage>ev); } } }); }); } private static createFileMatch(data: ISerializedFileMatch): FileMatch { const fileMatch = new FileMatch(uri.file(data.path)); if (data.results) { // const matches = data.results.filter(resultIsMatch); fileMatch.results.push(...data.results); } return fileMatch; } clearCache(cacheKey: string): Promise<void> { return this.raw.clearCache(cacheKey); } } registerSingleton(ISearchService, LocalSearchService, true);
src/vs/workbench/services/search/node/searchService.ts
1
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.0005161960143595934, 0.00021069886861369014, 0.00016455409058835357, 0.00017250757082365453, 0.000088457964011468 ]
{ "id": 4, "code_window": [ "\t\t\t\t}\n", "\n" ], "labels": [ "add", "keep" ], "after_edit": [ "\t\t\t};\n", "\n", "\t\t\tconst exists = await Promise.all(query.folderQueries.map(query => this.fileService.exists(query.folder)));\n", "\t\t\tquery.folderQueries = query.folderQueries.filter((_, i) => exists[i]);\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "add", "edit_start_line_idx": 146 }
{ "registrations": [ { "component": { "type": "git", "git": { "name": "atom/language-coffee-script", "repositoryUrl": "https://github.com/atom/language-coffee-script", "commitHash": "0f6db9143663e18b1ad00667820f46747dba495e" } }, "license": "MIT", "description": "The file syntaxes/coffeescript.tmLanguage.json was derived from the Atom package https://github.com/atom/language-coffee-script which was originally converted from the TextMate bundle https://github.com/jashkenas/coffee-script-tmbundle.", "version": "0.49.3" } ], "version": 1 }
extensions/coffeescript/cgmanifest.json
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00016903495998121798, 0.00016791262896731496, 0.0001667902834014967, 0.00016791262896731496, 0.000001122338289860636 ]
{ "id": 4, "code_window": [ "\t\t\t\t}\n", "\n" ], "labels": [ "add", "keep" ], "after_edit": [ "\t\t\t};\n", "\n", "\t\t\tconst exists = await Promise.all(query.folderQueries.map(query => this.fileService.exists(query.folder)));\n", "\t\t\tquery.folderQueries = query.folderQueries.filter((_, i) => exists[i]);\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "add", "edit_start_line_idx": 146 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/workbench/browser/style'; import { localize } from 'vs/nls'; import { Emitter, setGlobalLeakWarningThreshold } from 'vs/base/common/event'; import { addClasses, addClass, removeClasses } from 'vs/base/browser/dom'; import { runWhenIdle } from 'vs/base/common/async'; import { getZoomLevel, isFirefox, isSafari, isChrome } from 'vs/base/browser/browser'; import { mark } from 'vs/base/common/performance'; import { onUnexpectedError, setUnexpectedErrorHandler } from 'vs/base/common/errors'; import { Registry } from 'vs/platform/registry/common/platform'; import { isWindows, isLinux, isWeb, isNative, isMacintosh } from 'vs/base/common/platform'; import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions'; import { IEditorInputFactoryRegistry, Extensions as EditorExtensions } from 'vs/workbench/common/editor'; import { getSingletonServiceDescriptors } from 'vs/platform/instantiation/common/extensions'; import { Position, Parts, IWorkbenchLayoutService, positionToString } from 'vs/workbench/services/layout/browser/layoutService'; import { IStorageService, WillSaveStateReason, StorageScope } from 'vs/platform/storage/common/storage'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { LifecyclePhase, ILifecycleService, WillShutdownEvent, BeforeShutdownEvent } from 'vs/platform/lifecycle/common/lifecycle'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { NotificationService } from 'vs/workbench/services/notification/common/notificationService'; import { NotificationsCenter } from 'vs/workbench/browser/parts/notifications/notificationsCenter'; import { NotificationsAlerts } from 'vs/workbench/browser/parts/notifications/notificationsAlerts'; import { NotificationsStatus } from 'vs/workbench/browser/parts/notifications/notificationsStatus'; import { registerNotificationCommands } from 'vs/workbench/browser/parts/notifications/notificationsCommands'; import { NotificationsToasts } from 'vs/workbench/browser/parts/notifications/notificationsToasts'; import { IEditorService, IResourceEditorInputType } from 'vs/workbench/services/editor/common/editorService'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { setARIAContainer } from 'vs/base/browser/ui/aria/aria'; import { readFontInfo, restoreFontInfo, serializeFontInfo } from 'vs/editor/browser/config/configuration'; import { BareFontInfo } from 'vs/editor/common/config/fontInfo'; import { ILogService } from 'vs/platform/log/common/log'; import { toErrorMessage } from 'vs/base/common/errorMessage'; import { WorkbenchContextKeysHandler } from 'vs/workbench/browser/contextkeys'; import { coalesce } from 'vs/base/common/arrays'; import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService'; import { Layout } from 'vs/workbench/browser/layout'; import { IHostService } from 'vs/workbench/services/host/browser/host'; import { Extensions as PanelExtensions, PanelRegistry } from 'vs/workbench/browser/panel'; import { IViewDescriptorService, ViewContainerLocation } from 'vs/workbench/common/views'; export class Workbench extends Layout { private readonly _onBeforeShutdown = this._register(new Emitter<BeforeShutdownEvent>()); readonly onBeforeShutdown = this._onBeforeShutdown.event; private readonly _onWillShutdown = this._register(new Emitter<WillShutdownEvent>()); readonly onWillShutdown = this._onWillShutdown.event; private readonly _onShutdown = this._register(new Emitter<void>()); readonly onShutdown = this._onShutdown.event; constructor( parent: HTMLElement, private readonly serviceCollection: ServiceCollection, logService: ILogService ) { super(parent); this.registerErrorHandler(logService); } private registerErrorHandler(logService: ILogService): void { // Listen on unhandled rejection events window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => { // See https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent onUnexpectedError(event.reason); // Prevent the printing of this event to the console event.preventDefault(); }); // Install handler for unexpected errors setUnexpectedErrorHandler(error => this.handleUnexpectedError(error, logService)); // Inform user about loading issues from the loader interface AnnotatedLoadingError extends Error { phase: 'loading'; moduleId: string; neededBy: string[]; } interface AnnotatedFactoryError extends Error { phase: 'factory'; moduleId: string; } interface AnnotatedValidationError extends Error { phase: 'configuration'; } type AnnotatedError = AnnotatedLoadingError | AnnotatedFactoryError | AnnotatedValidationError; (<any>window).require.config({ onError: (err: AnnotatedError) => { if (err.phase === 'loading') { onUnexpectedError(new Error(localize('loaderErrorNative', "Failed to load a required file. Please restart the application to try again. Details: {0}", JSON.stringify(err)))); } console.error(err); } }); } private previousUnexpectedError: { message: string | undefined, time: number } = { message: undefined, time: 0 }; private handleUnexpectedError(error: unknown, logService: ILogService): void { const message = toErrorMessage(error, true); if (!message) { return; } const now = Date.now(); if (message === this.previousUnexpectedError.message && now - this.previousUnexpectedError.time <= 1000) { return; // Return if error message identical to previous and shorter than 1 second } this.previousUnexpectedError.time = now; this.previousUnexpectedError.message = message; // Log it logService.error(message); } startup(): IInstantiationService { try { // Configure emitter leak warning threshold setGlobalLeakWarningThreshold(175); // Services const instantiationService = this.initServices(this.serviceCollection); instantiationService.invokeFunction(async accessor => { const lifecycleService = accessor.get(ILifecycleService); const storageService = accessor.get(IStorageService); const configurationService = accessor.get(IConfigurationService); const hostService = accessor.get(IHostService); // Layout this.initLayout(accessor); // Registries this.startRegistries(accessor); // Context Keys this._register(instantiationService.createInstance(WorkbenchContextKeysHandler)); // Register Listeners this.registerListeners(lifecycleService, storageService, configurationService, hostService); // Render Workbench this.renderWorkbench(instantiationService, accessor.get(INotificationService) as NotificationService, storageService, configurationService); // Workbench Layout this.createWorkbenchLayout(); // Layout this.layout(); // Restore try { await this.restoreWorkbench(accessor.get(IEditorService), accessor.get(IEditorGroupsService), accessor.get(IViewDescriptorService), accessor.get(IViewletService), accessor.get(IPanelService), accessor.get(ILogService), lifecycleService); } catch (error) { onUnexpectedError(error); } }); return instantiationService; } catch (error) { onUnexpectedError(error); throw error; // rethrow because this is a critical issue we cannot handle properly here } } private initServices(serviceCollection: ServiceCollection): IInstantiationService { // Layout Service serviceCollection.set(IWorkbenchLayoutService, this); // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // NOTE: DO NOT ADD ANY OTHER SERVICE INTO THE COLLECTION HERE. // CONTRIBUTE IT VIA WORKBENCH.DESKTOP.MAIN.TS AND registerSingleton(). // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // All Contributed Services const contributedServices = getSingletonServiceDescriptors(); for (let [id, descriptor] of contributedServices) { serviceCollection.set(id, descriptor); } const instantiationService = new InstantiationService(serviceCollection, true); // Wrap up instantiationService.invokeFunction(accessor => { const lifecycleService = accessor.get(ILifecycleService); // TODO@Sandeep debt around cyclic dependencies const configurationService = accessor.get(IConfigurationService) as any; if (typeof configurationService.acquireInstantiationService === 'function') { setTimeout(() => { configurationService.acquireInstantiationService(instantiationService); }, 0); } // Signal to lifecycle that services are set lifecycleService.phase = LifecyclePhase.Ready; }); return instantiationService; } private startRegistries(accessor: ServicesAccessor): void { Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).start(accessor); Registry.as<IEditorInputFactoryRegistry>(EditorExtensions.EditorInputFactories).start(accessor); } private registerListeners( lifecycleService: ILifecycleService, storageService: IStorageService, configurationService: IConfigurationService, hostService: IHostService ): void { // Configuration changes this._register(configurationService.onDidChangeConfiguration(() => this.setFontAliasing(configurationService))); // Font Info if (isNative) { this._register(storageService.onWillSaveState(e => { if (e.reason === WillSaveStateReason.SHUTDOWN) { this.storeFontInfo(storageService); } })); } else { this._register(lifecycleService.onWillShutdown(() => this.storeFontInfo(storageService))); } // Lifecycle this._register(lifecycleService.onBeforeShutdown(event => this._onBeforeShutdown.fire(event))); this._register(lifecycleService.onWillShutdown(event => this._onWillShutdown.fire(event))); this._register(lifecycleService.onShutdown(() => { this._onShutdown.fire(); this.dispose(); })); // In some environments we do not get enough time to persist state on shutdown. // In other cases, VSCode might crash, so we periodically save state to reduce // the chance of loosing any state. // The window loosing focus is a good indication that the user has stopped working // in that window so we pick that at a time to collect state. this._register(hostService.onDidChangeFocus(focus => { if (!focus) { storageService.flush(); } })); } private fontAliasing: 'default' | 'antialiased' | 'none' | 'auto' | undefined; private setFontAliasing(configurationService: IConfigurationService) { if (!isMacintosh) { return; // macOS only } const aliasing = configurationService.getValue<'default' | 'antialiased' | 'none' | 'auto'>('workbench.fontAliasing'); if (this.fontAliasing === aliasing) { return; } this.fontAliasing = aliasing; // Remove all const fontAliasingValues: (typeof aliasing)[] = ['antialiased', 'none', 'auto']; removeClasses(this.container, ...fontAliasingValues.map(value => `monaco-font-aliasing-${value}`)); // Add specific if (fontAliasingValues.some(option => option === aliasing)) { addClass(this.container, `monaco-font-aliasing-${aliasing}`); } } private restoreFontInfo(storageService: IStorageService, configurationService: IConfigurationService): void { // Restore (native: use storage service, web: use browser specific local storage) const storedFontInfoRaw = isNative ? storageService.get('editorFontInfo', StorageScope.GLOBAL) : window.localStorage.getItem('vscode.editorFontInfo'); if (storedFontInfoRaw) { try { const storedFontInfo = JSON.parse(storedFontInfoRaw); if (Array.isArray(storedFontInfo)) { restoreFontInfo(storedFontInfo); } } catch (err) { /* ignore */ } } readFontInfo(BareFontInfo.createFromRawSettings(configurationService.getValue('editor'), getZoomLevel())); } private storeFontInfo(storageService: IStorageService): void { const serializedFontInfo = serializeFontInfo(); if (serializedFontInfo) { const serializedFontInfoRaw = JSON.stringify(serializedFontInfo); // Font info is very specific to the machine the workbench runs // on. As such, in the web, we prefer to store this info in // local storage and not global storage because it would not make // much sense to synchronize to other machines. if (isNative) { storageService.store('editorFontInfo', serializedFontInfoRaw, StorageScope.GLOBAL); } else { window.localStorage.setItem('vscode.editorFontInfo', serializedFontInfoRaw); } } } private renderWorkbench(instantiationService: IInstantiationService, notificationService: NotificationService, storageService: IStorageService, configurationService: IConfigurationService): void { // ARIA setARIAContainer(this.container); // State specific classes const platformClass = isWindows ? 'windows' : isLinux ? 'linux' : 'mac'; const workbenchClasses = coalesce([ 'monaco-workbench', platformClass, isWeb ? 'web' : undefined, isChrome ? 'chromium' : isFirefox ? 'firefox' : isSafari ? 'safari' : undefined, ...this.getLayoutClasses() ]); addClasses(this.container, ...workbenchClasses); addClass(document.body, platformClass); // used by our fonts if (isWeb) { addClass(document.body, 'web'); } // Apply font aliasing this.setFontAliasing(configurationService); // Warm up font cache information before building up too many dom elements this.restoreFontInfo(storageService, configurationService); // Create Parts [ { id: Parts.TITLEBAR_PART, role: 'contentinfo', classes: ['titlebar'] }, { id: Parts.ACTIVITYBAR_PART, role: 'navigation', classes: ['activitybar', this.state.sideBar.position === Position.LEFT ? 'left' : 'right'] }, { id: Parts.SIDEBAR_PART, role: 'complementary', classes: ['sidebar', this.state.sideBar.position === Position.LEFT ? 'left' : 'right'] }, { id: Parts.EDITOR_PART, role: 'main', classes: ['editor'], options: { restorePreviousState: this.state.editor.restoreEditors } }, { id: Parts.PANEL_PART, role: 'complementary', classes: ['panel', positionToString(this.state.panel.position)] }, { id: Parts.STATUSBAR_PART, role: 'status', classes: ['statusbar'] } ].forEach(({ id, role, classes, options }) => { const partContainer = this.createPart(id, role, classes); this.getPart(id).create(partContainer, options); }); // Notification Handlers this.createNotificationsHandlers(instantiationService, notificationService); // Add Workbench to DOM this.parent.appendChild(this.container); } private createPart(id: string, role: string, classes: string[]): HTMLElement { const part = document.createElement('div'); addClasses(part, 'part', ...classes); part.id = id; part.setAttribute('role', role); if (role === 'status') { part.setAttribute('aria-live', 'off'); } return part; } private createNotificationsHandlers(instantiationService: IInstantiationService, notificationService: NotificationService): void { // Instantiate Notification components const notificationsCenter = this._register(instantiationService.createInstance(NotificationsCenter, this.container, notificationService.model)); const notificationsToasts = this._register(instantiationService.createInstance(NotificationsToasts, this.container, notificationService.model)); this._register(instantiationService.createInstance(NotificationsAlerts, notificationService.model)); const notificationsStatus = instantiationService.createInstance(NotificationsStatus, notificationService.model); // Visibility this._register(notificationsCenter.onDidChangeVisibility(() => { notificationsStatus.update(notificationsCenter.isVisible, notificationsToasts.isVisible); notificationsToasts.update(notificationsCenter.isVisible); })); this._register(notificationsToasts.onDidChangeVisibility(() => { notificationsStatus.update(notificationsCenter.isVisible, notificationsToasts.isVisible); })); // Register Commands registerNotificationCommands(notificationsCenter, notificationsToasts); } private async restoreWorkbench( editorService: IEditorService, editorGroupService: IEditorGroupsService, viewDescriptorService: IViewDescriptorService, viewletService: IViewletService, panelService: IPanelService, logService: ILogService, lifecycleService: ILifecycleService ): Promise<void> { const restorePromises: Promise<void>[] = []; // Restore editors restorePromises.push((async () => { mark('willRestoreEditors'); // first ensure the editor part is restored await editorGroupService.whenRestored; // then see for editors to open as instructed let editors: IResourceEditorInputType[]; if (Array.isArray(this.state.editor.editorsToOpen)) { editors = this.state.editor.editorsToOpen; } else { editors = await this.state.editor.editorsToOpen; } if (editors.length) { await editorService.openEditors(editors); } mark('didRestoreEditors'); })()); // Restore Sidebar if (this.state.sideBar.viewletToRestore) { restorePromises.push((async () => { mark('willRestoreViewlet'); const viewlet = await viewletService.openViewlet(this.state.sideBar.viewletToRestore); if (!viewlet) { await viewletService.openViewlet(viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id); // fallback to default viewlet as needed } mark('didRestoreViewlet'); })()); } // Restore Panel if (this.state.panel.panelToRestore) { restorePromises.push((async () => { mark('willRestorePanel'); const panel = await panelService.openPanel(this.state.panel.panelToRestore!); if (!panel) { await panelService.openPanel(Registry.as<PanelRegistry>(PanelExtensions.Panels).getDefaultPanelId()); // fallback to default panel as needed } mark('didRestorePanel'); })()); } // Restore Zen Mode if (this.state.zenMode.restore) { this.toggleZenMode(false, true); } // Restore Editor Center Mode if (this.state.editor.restoreCentered) { this.centerEditorLayout(true, true); } // Emit a warning after 10s if restore does not complete const restoreTimeoutHandle = setTimeout(() => logService.warn('Workbench did not finish loading in 10 seconds, that might be a problem that should be reported.'), 10000); try { await Promise.all(restorePromises); clearTimeout(restoreTimeoutHandle); } catch (error) { onUnexpectedError(error); } finally { // Set lifecycle phase to `Restored` lifecycleService.phase = LifecyclePhase.Restored; // Set lifecycle phase to `Eventually` after a short delay and when idle (min 2.5sec, max 5sec) setTimeout(() => { this._register(runWhenIdle(() => lifecycleService.phase = LifecyclePhase.Eventually, 2500)); }, 2500); // Telemetry: startup metrics mark('didStartWorkbench'); } } }
src/vs/workbench/browser/workbench.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.9193111062049866, 0.023755326867103577, 0.0001652764913160354, 0.00018816752708517015, 0.1327366828918457 ]
{ "id": 4, "code_window": [ "\t\t\t\t}\n", "\n" ], "labels": [ "add", "keep" ], "after_edit": [ "\t\t\t};\n", "\n", "\t\t\tconst exists = await Promise.all(query.folderQueries.map(query => this.fileService.exists(query.folder)));\n", "\t\t\tquery.folderQueries = query.folderQueries.filter((_, i) => exists[i]);\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "add", "edit_start_line_idx": 146 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'mocha'; import * as assert from 'assert'; import * as path from 'path'; import { URI } from 'vscode-uri'; import { getLanguageModes, WorkspaceFolder, TextDocument, CompletionList, CompletionItemKind, ClientCapabilities} from '../modes/languageModes'; export interface ItemDescription { label: string; documentation?: string; kind?: CompletionItemKind; resultText?: string; command?: { title: string, command: string }; notAvailable?: boolean; } export function assertCompletion(completions: CompletionList, expected: ItemDescription, document: TextDocument) { let matches = completions.items.filter(completion => { return completion.label === expected.label; }); if (expected.notAvailable) { assert.equal(matches.length, 0, `${expected.label} should not existing is results`); return; } assert.equal(matches.length, 1, `${expected.label} should only existing once: Actual: ${completions.items.map(c => c.label).join(', ')}`); let match = matches[0]; if (expected.documentation) { assert.equal(match.documentation, expected.documentation); } if (expected.kind) { assert.equal(match.kind, expected.kind); } if (expected.resultText && match.textEdit) { assert.equal(TextDocument.applyEdits(document, [match.textEdit]), expected.resultText); } if (expected.command) { assert.deepEqual(match.command, expected.command); } } const testUri = 'test://test/test.html'; export function testCompletionFor(value: string, expected: { count?: number, items?: ItemDescription[] }, uri = testUri, workspaceFolders?: WorkspaceFolder[]): void { let offset = value.indexOf('|'); value = value.substr(0, offset) + value.substr(offset + 1); let workspace = { settings: {}, folders: workspaceFolders || [{ name: 'x', uri: uri.substr(0, uri.lastIndexOf('/')) }] }; let document = TextDocument.create(uri, 'html', 0, value); let position = document.positionAt(offset); const languageModes = getLanguageModes({ css: true, javascript: true }, workspace, ClientCapabilities.LATEST); const mode = languageModes.getModeAtPosition(document, position)!; let list = mode.doComplete!(document, position); if (expected.count) { assert.equal(list.items.length, expected.count); } if (expected.items) { for (let item of expected.items) { assertCompletion(list, item, document); } } } suite('HTML Completion', () => { test('HTML JavaScript Completions', function (): any { testCompletionFor('<html><script>window.|</script></html>', { items: [ { label: 'location', resultText: '<html><script>window.location</script></html>' }, ] }); testCompletionFor('<html><script>$.|</script></html>', { items: [ { label: 'getJSON', resultText: '<html><script>$.getJSON</script></html>' }, ] }); }); }); suite('HTML Path Completion', () => { const triggerSuggestCommand = { title: 'Suggest', command: 'editor.action.triggerSuggest' }; const fixtureRoot = path.resolve(__dirname, '../../src/test/pathCompletionFixtures'); const fixtureWorkspace = { name: 'fixture', uri: URI.file(fixtureRoot).toString() }; const indexHtmlUri = URI.file(path.resolve(fixtureRoot, 'index.html')).toString(); const aboutHtmlUri = URI.file(path.resolve(fixtureRoot, 'about/about.html')).toString(); test('Basics - Correct label/kind/result/command', () => { testCompletionFor('<script src="./|">', { items: [ { label: 'about/', kind: CompletionItemKind.Folder, resultText: '<script src="./about/">', command: triggerSuggestCommand }, { label: 'index.html', kind: CompletionItemKind.File, resultText: '<script src="./index.html">' }, { label: 'src/', kind: CompletionItemKind.Folder, resultText: '<script src="./src/">', command: triggerSuggestCommand } ] }, indexHtmlUri); }); test('Basics - Single Quote', () => { testCompletionFor(`<script src='./|'>`, { items: [ { label: 'about/', kind: CompletionItemKind.Folder, resultText: `<script src='./about/'>`, command: triggerSuggestCommand }, { label: 'index.html', kind: CompletionItemKind.File, resultText: `<script src='./index.html'>` }, { label: 'src/', kind: CompletionItemKind.Folder, resultText: `<script src='./src/'>`, command: triggerSuggestCommand } ] }, indexHtmlUri); }); test('No completion for remote paths', () => { testCompletionFor('<script src="http:">', { items: [] }); testCompletionFor('<script src="http:/|">', { items: [] }); testCompletionFor('<script src="http://|">', { items: [] }); testCompletionFor('<script src="https:|">', { items: [] }); testCompletionFor('<script src="https:/|">', { items: [] }); testCompletionFor('<script src="https://|">', { items: [] }); testCompletionFor('<script src="//|">', { items: [] }); }); test('Relative Path', () => { testCompletionFor('<script src="../|">', { items: [ { label: 'about/', resultText: '<script src="../about/">' }, { label: 'index.html', resultText: '<script src="../index.html">' }, { label: 'src/', resultText: '<script src="../src/">' } ] }, aboutHtmlUri); testCompletionFor('<script src="../src/|">', { items: [ { label: 'feature.js', resultText: '<script src="../src/feature.js">' }, { label: 'test.js', resultText: '<script src="../src/test.js">' }, ] }, aboutHtmlUri); }); test('Absolute Path', () => { testCompletionFor('<script src="/|">', { items: [ { label: 'about/', resultText: '<script src="/about/">' }, { label: 'index.html', resultText: '<script src="/index.html">' }, { label: 'src/', resultText: '<script src="/src/">' }, ] }, indexHtmlUri); testCompletionFor('<script src="/src/|">', { items: [ { label: 'feature.js', resultText: '<script src="/src/feature.js">' }, { label: 'test.js', resultText: '<script src="/src/test.js">' }, ] }, aboutHtmlUri, [fixtureWorkspace]); }); test('Empty Path Value', () => { // document: index.html testCompletionFor('<script src="|">', { items: [ { label: 'about/', resultText: '<script src="about/">' }, { label: 'index.html', resultText: '<script src="index.html">' }, { label: 'src/', resultText: '<script src="src/">' }, ] }, indexHtmlUri); // document: about.html testCompletionFor('<script src="|">', { items: [ { label: 'about.css', resultText: '<script src="about.css">' }, { label: 'about.html', resultText: '<script src="about.html">' }, { label: 'media/', resultText: '<script src="media/">' }, ] }, aboutHtmlUri); }); test('Incomplete Path', () => { testCompletionFor('<script src="/src/f|">', { items: [ { label: 'feature.js', resultText: '<script src="/src/feature.js">' }, { label: 'test.js', resultText: '<script src="/src/test.js">' }, ] }, aboutHtmlUri, [fixtureWorkspace]); testCompletionFor('<script src="../src/f|">', { items: [ { label: 'feature.js', resultText: '<script src="../src/feature.js">' }, { label: 'test.js', resultText: '<script src="../src/test.js">' }, ] }, aboutHtmlUri, [fixtureWorkspace]); }); test('No leading dot or slash', () => { // document: index.html testCompletionFor('<script src="s|">', { items: [ { label: 'about/', resultText: '<script src="about/">' }, { label: 'index.html', resultText: '<script src="index.html">' }, { label: 'src/', resultText: '<script src="src/">' }, ] }, indexHtmlUri, [fixtureWorkspace]); testCompletionFor('<script src="src/|">', { items: [ { label: 'feature.js', resultText: '<script src="src/feature.js">' }, { label: 'test.js', resultText: '<script src="src/test.js">' }, ] }, indexHtmlUri, [fixtureWorkspace]); testCompletionFor('<script src="src/f|">', { items: [ { label: 'feature.js', resultText: '<script src="src/feature.js">' }, { label: 'test.js', resultText: '<script src="src/test.js">' }, ] }, indexHtmlUri, [fixtureWorkspace]); // document: about.html testCompletionFor('<script src="s|">', { items: [ { label: 'about.css', resultText: '<script src="about.css">' }, { label: 'about.html', resultText: '<script src="about.html">' }, { label: 'media/', resultText: '<script src="media/">' }, ] }, aboutHtmlUri, [fixtureWorkspace]); testCompletionFor('<script src="media/|">', { items: [ { label: 'icon.pic', resultText: '<script src="media/icon.pic">' } ] }, aboutHtmlUri, [fixtureWorkspace]); testCompletionFor('<script src="media/f|">', { items: [ { label: 'icon.pic', resultText: '<script src="media/icon.pic">' } ] }, aboutHtmlUri, [fixtureWorkspace]); }); test('Trigger completion in middle of path', () => { // document: index.html testCompletionFor('<script src="src/f|eature.js">', { items: [ { label: 'feature.js', resultText: '<script src="src/feature.js">' }, { label: 'test.js', resultText: '<script src="src/test.js">' }, ] }, indexHtmlUri, [fixtureWorkspace]); testCompletionFor('<script src="s|rc/feature.js">', { items: [ { label: 'about/', resultText: '<script src="about/">' }, { label: 'index.html', resultText: '<script src="index.html">' }, { label: 'src/', resultText: '<script src="src/">' }, ] }, indexHtmlUri, [fixtureWorkspace]); // document: about.html testCompletionFor('<script src="media/f|eature.js">', { items: [ { label: 'icon.pic', resultText: '<script src="media/icon.pic">' } ] }, aboutHtmlUri, [fixtureWorkspace]); testCompletionFor('<script src="m|edia/feature.js">', { items: [ { label: 'about.css', resultText: '<script src="about.css">' }, { label: 'about.html', resultText: '<script src="about.html">' }, { label: 'media/', resultText: '<script src="media/">' }, ] }, aboutHtmlUri, [fixtureWorkspace]); }); test('Trigger completion in middle of path and with whitespaces', () => { testCompletionFor('<script src="./| about/about.html>', { items: [ { label: 'about/', resultText: '<script src="./about/ about/about.html>' }, { label: 'index.html', resultText: '<script src="./index.html about/about.html>' }, { label: 'src/', resultText: '<script src="./src/ about/about.html>' }, ] }, indexHtmlUri, [fixtureWorkspace]); testCompletionFor('<script src="./a|bout /about.html>', { items: [ { label: 'about/', resultText: '<script src="./about/ /about.html>' }, { label: 'index.html', resultText: '<script src="./index.html /about.html>' }, { label: 'src/', resultText: '<script src="./src/ /about.html>' }, ] }, indexHtmlUri, [fixtureWorkspace]); }); test('Completion should ignore files/folders starting with dot', () => { testCompletionFor('<script src="./|"', { count: 3 }, indexHtmlUri, [fixtureWorkspace]); }); test('Unquoted Path', () => { /* Unquoted value is not supported in html language service yet testCompletionFor(`<div><a href=about/|>`, { items: [ { label: 'about.html', resultText: `<div><a href=about/about.html>` } ] }, testUri); */ }); });
extensions/html-language-features/server/src/test/completions.test.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.0007468541152775288, 0.00020960127585567534, 0.00016533354937564582, 0.00017919353558681905, 0.0001028629339998588 ]
{ "id": 5, "code_window": [ "\n", "\t\t\t\treturn <ISearchComplete>{\n", "\t\t\t\t\tlimitHit: completes[0] && completes[0].limitHit,\n", "\t\t\t\t\tstats: completes[0].stats,\n", "\t\t\t\t\tresults: arrays.flatten(completes.map((c: ISearchComplete) => c.results))\n", "\t\t\t\t};\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\tlet completes = await this.searchWithProviders(query, progressCallback, token);\n", "\t\t\tcompletes = arrays.coalesce(completes);\n", "\t\t\tif (!completes.length) {\n", "\t\t\t\treturn {\n", "\t\t\t\t\tlimitHit: false,\n", "\t\t\t\t\tresults: []\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 147 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as arrays from 'vs/base/common/arrays'; import { CancellationToken } from 'vs/base/common/cancellation'; import { canceled } from 'vs/base/common/errors'; import { Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { keys, ResourceMap, values } from 'vs/base/common/map'; import { Schemas } from 'vs/base/common/network'; import { StopWatch } from 'vs/base/common/stopwatch'; import { URI as uri } from 'vs/base/common/uri'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IFileService } from 'vs/platform/files/common/files'; import { ILogService } from 'vs/platform/log/common/log'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { deserializeSearchError, FileMatch, ICachedSearchStats, IFileMatch, IFileQuery, IFileSearchStats, IFolderQuery, IProgressMessage, ISearchComplete, ISearchEngineStats, ISearchProgressItem, ISearchQuery, ISearchResultProvider, ISearchService, ITextQuery, pathIncludedInQuery, QueryType, SearchError, SearchErrorCode, SearchProviderType, isFileMatch, isProgressMessage } from 'vs/workbench/services/search/common/search'; import { addContextToEditorMatches, editorMatchesToTextSearchResults } from 'vs/workbench/services/search/common/searchHelpers'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { DeferredPromise } from 'vs/base/test/common/utils'; export class SearchService extends Disposable implements ISearchService { _serviceBrand: undefined; protected diskSearch: ISearchResultProvider | null = null; private readonly fileSearchProviders = new Map<string, ISearchResultProvider>(); private readonly textSearchProviders = new Map<string, ISearchResultProvider>(); private deferredFileSearchesByScheme = new Map<string, DeferredPromise<ISearchResultProvider>>(); private deferredTextSearchesByScheme = new Map<string, DeferredPromise<ISearchResultProvider>>(); constructor( private readonly modelService: IModelService, private readonly editorService: IEditorService, private readonly telemetryService: ITelemetryService, private readonly logService: ILogService, private readonly extensionService: IExtensionService, private readonly fileService: IFileService ) { super(); } registerSearchResultProvider(scheme: string, type: SearchProviderType, provider: ISearchResultProvider): IDisposable { let list: Map<string, ISearchResultProvider>; let deferredMap: Map<string, DeferredPromise<ISearchResultProvider>>; if (type === SearchProviderType.file) { list = this.fileSearchProviders; deferredMap = this.deferredFileSearchesByScheme; } else if (type === SearchProviderType.text) { list = this.textSearchProviders; deferredMap = this.deferredTextSearchesByScheme; } else { throw new Error('Unknown SearchProviderType'); } list.set(scheme, provider); if (deferredMap.has(scheme)) { deferredMap.get(scheme)!.complete(provider); deferredMap.delete(scheme); } return toDisposable(() => { list.delete(scheme); }); } async textSearch(query: ITextQuery, token?: CancellationToken, onProgress?: (item: ISearchProgressItem) => void): Promise<ISearchComplete> { // Get local results from dirty/untitled const localResults = this.getLocalResults(query); if (onProgress) { arrays.coalesce([...localResults.results.values()]).forEach(onProgress); } const onProviderProgress = (progress: ISearchProgressItem) => { if (isFileMatch(progress)) { // Match if (!localResults.results.has(progress.resource) && onProgress) { // don't override local results onProgress(progress); } } else if (onProgress) { // Progress onProgress(<IProgressMessage>progress); } if (isProgressMessage(progress)) { this.logService.debug('SearchService#search', progress.message); } }; const otherResults = await this.doSearch(query, token, onProviderProgress); return { ...otherResults, ...{ limitHit: otherResults.limitHit || localResults.limitHit }, results: [...otherResults.results, ...arrays.coalesce([...localResults.results.values()])] }; } fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { return this.doSearch(query, token); } private doSearch(query: ISearchQuery, token?: CancellationToken, onProgress?: (item: ISearchProgressItem) => void): Promise<ISearchComplete> { this.logService.trace('SearchService#search', JSON.stringify(query)); const schemesInQuery = this.getSchemesInQuery(query); const providerActivations: Promise<any>[] = [Promise.resolve(null)]; schemesInQuery.forEach(scheme => providerActivations.push(this.extensionService.activateByEvent(`onSearch:${scheme}`))); providerActivations.push(this.extensionService.activateByEvent('onSearch:file')); const providerPromise = Promise.all(providerActivations) .then(() => this.extensionService.whenInstalledExtensionsRegistered()) .then(() => { // Cancel faster if search was canceled while waiting for extensions if (token && token.isCancellationRequested) { return Promise.reject(canceled()); } const progressCallback = (item: ISearchProgressItem) => { if (token && token.isCancellationRequested) { return; } if (onProgress) { onProgress(item); } }; return this.searchWithProviders(query, progressCallback, token); }) .then(completes => { completes = arrays.coalesce(completes); if (!completes.length) { return { limitHit: false, results: [] }; } return <ISearchComplete>{ limitHit: completes[0] && completes[0].limitHit, stats: completes[0].stats, results: arrays.flatten(completes.map((c: ISearchComplete) => c.results)) }; }); return new Promise((resolve, reject) => { if (token) { token.onCancellationRequested(() => { reject(canceled()); }); } providerPromise.then(resolve, reject); }); } private getSchemesInQuery(query: ISearchQuery): Set<string> { const schemes = new Set<string>(); if (query.folderQueries) { query.folderQueries.forEach(fq => schemes.add(fq.folder.scheme)); } if (query.extraFileResources) { query.extraFileResources.forEach(extraFile => schemes.add(extraFile.scheme)); } return schemes; } private async waitForProvider(queryType: QueryType, scheme: string): Promise<ISearchResultProvider> { let deferredMap: Map<string, DeferredPromise<ISearchResultProvider>> = queryType === QueryType.File ? this.deferredFileSearchesByScheme : this.deferredTextSearchesByScheme; if (deferredMap.has(scheme)) { return deferredMap.get(scheme)!.p; } else { const deferred = new DeferredPromise<ISearchResultProvider>(); deferredMap.set(scheme, deferred); return deferred.p; } } private async searchWithProviders(query: ISearchQuery, onProviderProgress: (progress: ISearchProgressItem) => void, token?: CancellationToken) { const e2eSW = StopWatch.create(false); const diskSearchQueries: IFolderQuery[] = []; const searchPs: Promise<ISearchComplete>[] = []; const fqs = this.groupFolderQueriesByScheme(query); await Promise.all(keys(fqs).map(async scheme => { const schemeFQs = fqs.get(scheme)!; let provider = query.type === QueryType.File ? this.fileSearchProviders.get(scheme) : this.textSearchProviders.get(scheme); if (!provider && scheme === Schemas.file) { diskSearchQueries.push(...schemeFQs); } else { if (!provider) { if (scheme !== Schemas.vscodeRemote) { console.warn(`No search provider registered for scheme: ${scheme}`); return; } console.warn(`No search provider registered for scheme: ${scheme}, waiting`); provider = await this.waitForProvider(query.type, scheme); } const oneSchemeQuery: ISearchQuery = { ...query, ...{ folderQueries: schemeFQs } }; searchPs.push(query.type === QueryType.File ? provider.fileSearch(<IFileQuery>oneSchemeQuery, token) : provider.textSearch(<ITextQuery>oneSchemeQuery, onProviderProgress, token)); } })); const diskSearchExtraFileResources = query.extraFileResources && query.extraFileResources.filter(res => res.scheme === Schemas.file); if (diskSearchQueries.length || diskSearchExtraFileResources) { const diskSearchQuery: ISearchQuery = { ...query, ...{ folderQueries: diskSearchQueries }, extraFileResources: diskSearchExtraFileResources }; if (this.diskSearch) { searchPs.push(diskSearchQuery.type === QueryType.File ? this.diskSearch.fileSearch(diskSearchQuery, token) : this.diskSearch.textSearch(diskSearchQuery, onProviderProgress, token)); } } return Promise.all(searchPs).then(completes => { const endToEndTime = e2eSW.elapsed(); this.logService.trace(`SearchService#search: ${endToEndTime}ms`); completes.forEach(complete => { this.sendTelemetry(query, endToEndTime, complete); }); return completes; }, err => { const endToEndTime = e2eSW.elapsed(); this.logService.trace(`SearchService#search: ${endToEndTime}ms`); const searchError = deserializeSearchError(err.message); this.sendTelemetry(query, endToEndTime, undefined, searchError); throw searchError; }); } private groupFolderQueriesByScheme(query: ISearchQuery): Map<string, IFolderQuery[]> { const queries = new Map<string, IFolderQuery[]>(); query.folderQueries.forEach(fq => { const schemeFQs = queries.get(fq.folder.scheme) || []; schemeFQs.push(fq); queries.set(fq.folder.scheme, schemeFQs); }); return queries; } private sendTelemetry(query: ISearchQuery, endToEndTime: number, complete?: ISearchComplete, err?: SearchError): void { const fileSchemeOnly = query.folderQueries.every(fq => fq.folder.scheme === 'file'); const otherSchemeOnly = query.folderQueries.every(fq => fq.folder.scheme !== 'file'); const scheme = fileSchemeOnly ? 'file' : otherSchemeOnly ? 'other' : 'mixed'; if (query.type === QueryType.File && complete && complete.stats) { const fileSearchStats = complete.stats as IFileSearchStats; if (fileSearchStats.fromCache) { const cacheStats: ICachedSearchStats = fileSearchStats.detailStats as ICachedSearchStats; type CachedSearchCompleteClassifcation = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; resultCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; type: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; sortingTime?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheWasResolved: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; cacheLookupTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheFilterTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheEntryCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type CachedSearchCompleteEvent = { reason?: string; resultCount: number; workspaceFolderCount: number; type: 'fileSearchProvider' | 'searchProcess'; endToEndTime: number; sortingTime?: number; cacheWasResolved: boolean; cacheLookupTime: number; cacheFilterTime: number; cacheEntryCount: number; scheme: string; }; this.telemetryService.publicLog2<CachedSearchCompleteEvent, CachedSearchCompleteClassifcation>('cachedSearchComplete', { reason: query._reason, resultCount: fileSearchStats.resultCount, workspaceFolderCount: query.folderQueries.length, type: fileSearchStats.type, endToEndTime: endToEndTime, sortingTime: fileSearchStats.sortingTime, cacheWasResolved: cacheStats.cacheWasResolved, cacheLookupTime: cacheStats.cacheLookupTime, cacheFilterTime: cacheStats.cacheFilterTime, cacheEntryCount: cacheStats.cacheEntryCount, scheme }); } else { const searchEngineStats: ISearchEngineStats = fileSearchStats.detailStats as ISearchEngineStats; type SearchCompleteClassification = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; resultCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; type: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; sortingTime?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; fileWalkTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; directoriesWalked: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; filesWalked: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cmdTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cmdResultCount?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type SearchCompleteEvent = { reason?: string; resultCount: number; workspaceFolderCount: number; type: 'fileSearchProvider' | 'searchProcess'; endToEndTime: number; sortingTime?: number; fileWalkTime: number directoriesWalked: number; filesWalked: number; cmdTime: number; cmdResultCount?: number; scheme: string; }; this.telemetryService.publicLog2<SearchCompleteEvent, SearchCompleteClassification>('searchComplete', { reason: query._reason, resultCount: fileSearchStats.resultCount, workspaceFolderCount: query.folderQueries.length, type: fileSearchStats.type, endToEndTime: endToEndTime, sortingTime: fileSearchStats.sortingTime, fileWalkTime: searchEngineStats.fileWalkTime, directoriesWalked: searchEngineStats.directoriesWalked, filesWalked: searchEngineStats.filesWalked, cmdTime: searchEngineStats.cmdTime, cmdResultCount: searchEngineStats.cmdResultCount, scheme }); } } else if (query.type === QueryType.Text) { let errorType: string | undefined; if (err) { errorType = err.code === SearchErrorCode.regexParseError ? 'regex' : err.code === SearchErrorCode.unknownEncoding ? 'encoding' : err.code === SearchErrorCode.globParseError ? 'glob' : err.code === SearchErrorCode.invalidLiteral ? 'literal' : err.code === SearchErrorCode.other ? 'other' : 'unknown'; } type TextSearchCompleteClassification = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; error?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; usePCRE2: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type TextSearchCompleteEvent = { reason?: string; workspaceFolderCount: number; endToEndTime: number; scheme: string; error?: string; usePCRE2: boolean; }; this.telemetryService.publicLog2<TextSearchCompleteEvent, TextSearchCompleteClassification>('textSearchComplete', { reason: query._reason, workspaceFolderCount: query.folderQueries.length, endToEndTime: endToEndTime, scheme, error: errorType, usePCRE2: !!query.usePCRE2 }); } } private getLocalResults(query: ITextQuery): { results: ResourceMap<IFileMatch | null>; limitHit: boolean } { const localResults = new ResourceMap<IFileMatch | null>(); let limitHit = false; if (query.type === QueryType.Text) { const models = this.modelService.getModels(); models.forEach((model) => { const resource = model.uri; if (!resource) { return; } if (limitHit) { return; } // Skip files that are not opened as text file if (!this.editorService.isOpen({ resource })) { return; } // Skip search results if (model.getModeId() === 'search-result' && !(query.includePattern && query.includePattern['**/*.code-search'])) { // TODO: untitled search editors will be excluded from search even when include *.code-search is specified return; } // Block walkthrough, webview, etc. if (resource.scheme !== Schemas.untitled && !this.fileService.canHandleResource(resource)) { return; } // Exclude files from the git FileSystemProvider, e.g. to prevent open staged files from showing in search results if (resource.scheme === 'git') { return; } if (!this.matches(resource, query)) { return; // respect user filters } // Use editor API to find matches const askMax = typeof query.maxResults === 'number' ? query.maxResults + 1 : undefined; let matches = model.findMatches(query.contentPattern.pattern, false, !!query.contentPattern.isRegExp, !!query.contentPattern.isCaseSensitive, query.contentPattern.isWordMatch ? query.contentPattern.wordSeparators! : null, false, askMax); if (matches.length) { if (askMax && matches.length >= askMax) { limitHit = true; matches = matches.slice(0, askMax - 1); } const fileMatch = new FileMatch(resource); localResults.set(resource, fileMatch); const textSearchResults = editorMatchesToTextSearchResults(matches, model, query.previewOptions); fileMatch.results = addContextToEditorMatches(textSearchResults, model, query); } else { localResults.set(resource, null); } }); } return { results: localResults, limitHit }; } private matches(resource: uri, query: ITextQuery): boolean { return pathIncludedInQuery(query, resource.fsPath); } clearCache(cacheKey: string): Promise<void> { const clearPs = [ this.diskSearch, ...values(this.fileSearchProviders) ].map(provider => provider && provider.clearCache(cacheKey)); return Promise.all(clearPs) .then(() => { }); } } export class RemoteSearchService extends SearchService { constructor( @IModelService modelService: IModelService, @IEditorService editorService: IEditorService, @ITelemetryService telemetryService: ITelemetryService, @ILogService logService: ILogService, @IExtensionService extensionService: IExtensionService, @IFileService fileService: IFileService ) { super(modelService, editorService, telemetryService, logService, extensionService, fileService); } } registerSingleton(ISearchService, RemoteSearchService, true);
src/vs/workbench/services/search/common/searchService.ts
1
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.46549084782600403, 0.009809897281229496, 0.00016399753803852946, 0.00017446072888560593, 0.06384395062923431 ]
{ "id": 5, "code_window": [ "\n", "\t\t\t\treturn <ISearchComplete>{\n", "\t\t\t\t\tlimitHit: completes[0] && completes[0].limitHit,\n", "\t\t\t\t\tstats: completes[0].stats,\n", "\t\t\t\t\tresults: arrays.flatten(completes.map((c: ISearchComplete) => c.results))\n", "\t\t\t\t};\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\tlet completes = await this.searchWithProviders(query, progressCallback, token);\n", "\t\t\tcompletes = arrays.coalesce(completes);\n", "\t\t\tif (!completes.length) {\n", "\t\t\t\treturn {\n", "\t\t\t\t\tlimitHit: false,\n", "\t\t\t\t\tresults: []\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 147 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ export class Kind { public static readonly alias = 'alias'; public static readonly callSignature = 'call'; public static readonly class = 'class'; public static readonly const = 'const'; public static readonly constructorImplementation = 'constructor'; public static readonly constructSignature = 'construct'; public static readonly directory = 'directory'; public static readonly enum = 'enum'; public static readonly enumMember = 'enum member'; public static readonly externalModuleName = 'external module name'; public static readonly function = 'function'; public static readonly indexSignature = 'index'; public static readonly interface = 'interface'; public static readonly keyword = 'keyword'; public static readonly let = 'let'; public static readonly localFunction = 'local function'; public static readonly localVariable = 'local var'; public static readonly method = 'method'; public static readonly memberGetAccessor = 'getter'; public static readonly memberSetAccessor = 'setter'; public static readonly memberVariable = 'property'; public static readonly module = 'module'; public static readonly primitiveType = 'primitive type'; public static readonly script = 'script'; public static readonly type = 'type'; public static readonly variable = 'var'; public static readonly warning = 'warning'; public static readonly string = 'string'; public static readonly parameter = 'parameter'; public static readonly typeParameter = 'type parameter'; } export class DiagnosticCategory { public static readonly error = 'error'; public static readonly warning = 'warning'; public static readonly suggestion = 'suggestion'; } export class KindModifiers { public static readonly optional = 'optional'; public static readonly color = 'color'; public static readonly dtsFile = '.d.ts'; public static readonly tsFile = '.ts'; public static readonly tsxFile = '.tsx'; public static readonly jsFile = '.js'; public static readonly jsxFile = '.jsx'; public static readonly jsonFile = '.json'; public static readonly fileExtensionKindModifiers = [ KindModifiers.dtsFile, KindModifiers.tsFile, KindModifiers.tsxFile, KindModifiers.jsFile, KindModifiers.jsxFile, KindModifiers.jsonFile, ]; } export class DisplayPartKind { public static readonly functionName = 'functionName'; public static readonly methodName = 'methodName'; public static readonly parameterName = 'parameterName'; public static readonly propertyName = 'propertyName'; public static readonly punctuation = 'punctuation'; public static readonly text = 'text'; }
extensions/typescript-language-features/src/protocol.const.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.0001782685867510736, 0.00017639147699810565, 0.00017367705004289746, 0.00017662295431364328, 0.0000012980849533050787 ]
{ "id": 5, "code_window": [ "\n", "\t\t\t\treturn <ISearchComplete>{\n", "\t\t\t\t\tlimitHit: completes[0] && completes[0].limitHit,\n", "\t\t\t\t\tstats: completes[0].stats,\n", "\t\t\t\t\tresults: arrays.flatten(completes.map((c: ISearchComplete) => c.results))\n", "\t\t\t\t};\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\tlet completes = await this.searchWithProviders(query, progressCallback, token);\n", "\t\t\tcompletes = arrays.coalesce(completes);\n", "\t\t\tif (!completes.length) {\n", "\t\t\t\treturn {\n", "\t\t\t\t\tlimitHit: false,\n", "\t\t\t\t\tresults: []\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 147 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { mixin, deepClone } from 'vs/base/common/objects'; import { Event, Emitter } from 'vs/base/common/event'; import type * as vscode from 'vscode'; import { ExtHostWorkspace, IExtHostWorkspace } from 'vs/workbench/api/common/extHostWorkspace'; import { ExtHostConfigurationShape, MainThreadConfigurationShape, IConfigurationInitData, MainContext } from './extHost.protocol'; import { ConfigurationTarget as ExtHostConfigurationTarget } from './extHostTypes'; import { ConfigurationTarget, IConfigurationChange, IConfigurationData, IConfigurationOverrides } from 'vs/platform/configuration/common/configuration'; import { Configuration, ConfigurationChangeEvent } from 'vs/platform/configuration/common/configurationModels'; import { ConfigurationScope, OVERRIDE_PROPERTY_PATTERN } from 'vs/platform/configuration/common/configurationRegistry'; import { isObject } from 'vs/base/common/types'; import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions'; import { Barrier } from 'vs/base/common/async'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService'; import { ILogService } from 'vs/platform/log/common/log'; import { Workspace } from 'vs/platform/workspace/common/workspace'; import { URI } from 'vs/base/common/uri'; function lookUp(tree: any, key: string) { if (key) { const parts = key.split('.'); let node = tree; for (let i = 0; node && i < parts.length; i++) { node = node[parts[i]]; } return node; } } type ConfigurationInspect<T> = { key: string; defaultValue?: T; globalValue?: T; workspaceValue?: T, workspaceFolderValue?: T, defaultLanguageValue?: T; globalLanguageValue?: T; workspaceLanguageValue?: T; workspaceFolderLanguageValue?: T; languageIds?: string[]; }; function isUri(thing: any): thing is vscode.Uri { return thing instanceof URI; } function isResourceLanguage(thing: any): thing is { uri: URI, languageId: string } { return thing && thing.uri instanceof URI && (thing.languageId && typeof thing.languageId === 'string'); } function isLanguage(thing: any): thing is { languageId: string } { return thing && !thing.uri && (thing.languageId && typeof thing.languageId === 'string'); } function isWorkspaceFolder(thing: any): thing is vscode.WorkspaceFolder { return thing && thing.uri instanceof URI && (!thing.name || typeof thing.name === 'string') && (!thing.index || typeof thing.index === 'number'); } function scopeToOverrides(scope: vscode.ConfigurationScope | undefined | null): IConfigurationOverrides | undefined { if (isUri(scope)) { return { resource: scope }; } if (isResourceLanguage(scope)) { return { resource: scope.uri, overrideIdentifier: scope.languageId }; } if (isLanguage(scope)) { return { overrideIdentifier: scope.languageId }; } if (isWorkspaceFolder(scope)) { return { resource: scope.uri }; } if (scope === null) { return { resource: null }; } return undefined; } export class ExtHostConfiguration implements ExtHostConfigurationShape { readonly _serviceBrand: undefined; private readonly _proxy: MainThreadConfigurationShape; private readonly _logService: ILogService; private readonly _extHostWorkspace: ExtHostWorkspace; private readonly _barrier: Barrier; private _actual: ExtHostConfigProvider | null; constructor( @IExtHostRpcService extHostRpc: IExtHostRpcService, @IExtHostWorkspace extHostWorkspace: IExtHostWorkspace, @ILogService logService: ILogService, ) { this._proxy = extHostRpc.getProxy(MainContext.MainThreadConfiguration); this._extHostWorkspace = extHostWorkspace; this._logService = logService; this._barrier = new Barrier(); this._actual = null; } public getConfigProvider(): Promise<ExtHostConfigProvider> { return this._barrier.wait().then(_ => this._actual!); } $initializeConfiguration(data: IConfigurationInitData): void { this._actual = new ExtHostConfigProvider(this._proxy, this._extHostWorkspace, data, this._logService); this._barrier.open(); } $acceptConfigurationChanged(data: IConfigurationInitData, change: IConfigurationChange): void { this.getConfigProvider().then(provider => provider.$acceptConfigurationChanged(data, change)); } } export class ExtHostConfigProvider { private readonly _onDidChangeConfiguration = new Emitter<vscode.ConfigurationChangeEvent>(); private readonly _proxy: MainThreadConfigurationShape; private readonly _extHostWorkspace: ExtHostWorkspace; private _configurationScopes: Map<string, ConfigurationScope | undefined>; private _configuration: Configuration; private _logService: ILogService; constructor(proxy: MainThreadConfigurationShape, extHostWorkspace: ExtHostWorkspace, data: IConfigurationInitData, logService: ILogService) { this._proxy = proxy; this._logService = logService; this._extHostWorkspace = extHostWorkspace; this._configuration = Configuration.parse(data); this._configurationScopes = this._toMap(data.configurationScopes); } get onDidChangeConfiguration(): Event<vscode.ConfigurationChangeEvent> { return this._onDidChangeConfiguration && this._onDidChangeConfiguration.event; } $acceptConfigurationChanged(data: IConfigurationInitData, change: IConfigurationChange) { const previous = { data: this._configuration.toData(), workspace: this._extHostWorkspace.workspace }; this._configuration = Configuration.parse(data); this._configurationScopes = this._toMap(data.configurationScopes); this._onDidChangeConfiguration.fire(this._toConfigurationChangeEvent(change, previous)); } getConfiguration(section?: string, scope?: vscode.ConfigurationScope | null, extensionDescription?: IExtensionDescription): vscode.WorkspaceConfiguration { const overrides = scopeToOverrides(scope) || {}; const config = this._toReadonlyValue(section ? lookUp(this._configuration.getValue(undefined, overrides, this._extHostWorkspace.workspace), section) : this._configuration.getValue(undefined, overrides, this._extHostWorkspace.workspace)); if (section) { this._validateConfigurationAccess(section, overrides, extensionDescription?.identifier); } function parseConfigurationTarget(arg: boolean | ExtHostConfigurationTarget): ConfigurationTarget | null { if (arg === undefined || arg === null) { return null; } if (typeof arg === 'boolean') { return arg ? ConfigurationTarget.USER : ConfigurationTarget.WORKSPACE; } switch (arg) { case ExtHostConfigurationTarget.Global: return ConfigurationTarget.USER; case ExtHostConfigurationTarget.Workspace: return ConfigurationTarget.WORKSPACE; case ExtHostConfigurationTarget.WorkspaceFolder: return ConfigurationTarget.WORKSPACE_FOLDER; } } const result: vscode.WorkspaceConfiguration = { has(key: string): boolean { return typeof lookUp(config, key) !== 'undefined'; }, get: <T>(key: string, defaultValue?: T) => { this._validateConfigurationAccess(section ? `${section}.${key}` : key, overrides, extensionDescription?.identifier); let result = lookUp(config, key); if (typeof result === 'undefined') { result = defaultValue; } else { let clonedConfig: any | undefined = undefined; const cloneOnWriteProxy = (target: any, accessor: string): any => { let clonedTarget: any | undefined = undefined; const cloneTarget = () => { clonedConfig = clonedConfig ? clonedConfig : deepClone(config); clonedTarget = clonedTarget ? clonedTarget : lookUp(clonedConfig, accessor); }; return isObject(target) ? new Proxy(target, { get: (target: any, property: PropertyKey) => { if (typeof property === 'string' && property.toLowerCase() === 'tojson') { cloneTarget(); return () => clonedTarget; } if (clonedConfig) { clonedTarget = clonedTarget ? clonedTarget : lookUp(clonedConfig, accessor); return clonedTarget[property]; } const result = target[property]; if (typeof property === 'string') { return cloneOnWriteProxy(result, `${accessor}.${property}`); } return result; }, set: (_target: any, property: PropertyKey, value: any) => { cloneTarget(); if (clonedTarget) { clonedTarget[property] = value; } return true; }, deleteProperty: (_target: any, property: PropertyKey) => { cloneTarget(); if (clonedTarget) { delete clonedTarget[property]; } return true; }, defineProperty: (_target: any, property: PropertyKey, descriptor: any) => { cloneTarget(); if (clonedTarget) { Object.defineProperty(clonedTarget, property, descriptor); } return true; } }) : target; }; result = cloneOnWriteProxy(result, key); } return result; }, update: (key: string, value: any, extHostConfigurationTarget: ExtHostConfigurationTarget | boolean, scopeToLanguage?: boolean) => { key = section ? `${section}.${key}` : key; const target = parseConfigurationTarget(extHostConfigurationTarget); if (value !== undefined) { return this._proxy.$updateConfigurationOption(target, key, value, overrides, scopeToLanguage); } else { return this._proxy.$removeConfigurationOption(target, key, overrides, scopeToLanguage); } }, inspect: <T>(key: string): ConfigurationInspect<T> | undefined => { key = section ? `${section}.${key}` : key; const config = deepClone(this._configuration.inspect<T>(key, overrides, this._extHostWorkspace.workspace)); if (config) { return { key, defaultValue: config.default?.value, globalValue: config.user?.value, workspaceValue: config.workspace?.value, workspaceFolderValue: config.workspaceFolder?.value, defaultLanguageValue: config.default?.override, globalLanguageValue: config.user?.override, workspaceLanguageValue: config.workspace?.override, workspaceFolderLanguageValue: config.workspaceFolder?.override, languageIds: config.overrideIdentifiers }; } return undefined; } }; if (typeof config === 'object') { mixin(result, config, false); } return <vscode.WorkspaceConfiguration>Object.freeze(result); } private _toReadonlyValue(result: any): any { const readonlyProxy = (target: any): any => { return isObject(target) ? new Proxy(target, { get: (target: any, property: PropertyKey) => readonlyProxy(target[property]), set: (_target: any, property: PropertyKey, _value: any) => { throw new Error(`TypeError: Cannot assign to read only property '${String(property)}' of object`); }, deleteProperty: (_target: any, property: PropertyKey) => { throw new Error(`TypeError: Cannot delete read only property '${String(property)}' of object`); }, defineProperty: (_target: any, property: PropertyKey) => { throw new Error(`TypeError: Cannot define property '${String(property)}' for a readonly object`); }, setPrototypeOf: (_target: any) => { throw new Error(`TypeError: Cannot set prototype for a readonly object`); }, isExtensible: () => false, preventExtensions: () => true }) : target; }; return readonlyProxy(result); } private _validateConfigurationAccess(key: string, overrides?: IConfigurationOverrides, extensionId?: ExtensionIdentifier): void { const scope = OVERRIDE_PROPERTY_PATTERN.test(key) ? ConfigurationScope.RESOURCE : this._configurationScopes.get(key); const extensionIdText = extensionId ? `[${extensionId.value}] ` : ''; if (ConfigurationScope.RESOURCE === scope) { if (typeof overrides?.resource === 'undefined') { this._logService.warn(`${extensionIdText}Accessing a resource scoped configuration without providing a resource is not expected. To get the effective value for '${key}', provide the URI of a resource or 'null' for any resource.`); } return; } if (ConfigurationScope.WINDOW === scope) { if (overrides?.resource) { this._logService.warn(`${extensionIdText}Accessing a window scoped configuration for a resource is not expected. To associate '${key}' to a resource, define its scope to 'resource' in configuration contributions in 'package.json'.`); } return; } } private _toConfigurationChangeEvent(change: IConfigurationChange, previous: { data: IConfigurationData, workspace: Workspace | undefined }): vscode.ConfigurationChangeEvent { const event = new ConfigurationChangeEvent(change, previous, this._configuration, this._extHostWorkspace.workspace); return Object.freeze({ affectsConfiguration: (section: string, scope?: vscode.ConfigurationScope) => event.affectsConfiguration(section, scopeToOverrides(scope)) }); } private _toMap(scopes: [string, ConfigurationScope | undefined][]): Map<string, ConfigurationScope | undefined> { return scopes.reduce((result, scope) => { result.set(scope[0], scope[1]); return result; }, new Map<string, ConfigurationScope | undefined>()); } } export const IExtHostConfiguration = createDecorator<IExtHostConfiguration>('IExtHostConfiguration'); export interface IExtHostConfiguration extends ExtHostConfiguration { }
src/vs/workbench/api/common/extHostConfiguration.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.0001790665410226211, 0.0001735435362206772, 0.00016609198064543307, 0.0001736208505462855, 0.0000027584271720115794 ]
{ "id": 5, "code_window": [ "\n", "\t\t\t\treturn <ISearchComplete>{\n", "\t\t\t\t\tlimitHit: completes[0] && completes[0].limitHit,\n", "\t\t\t\t\tstats: completes[0].stats,\n", "\t\t\t\t\tresults: arrays.flatten(completes.map((c: ISearchComplete) => c.results))\n", "\t\t\t\t};\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\tlet completes = await this.searchWithProviders(query, progressCallback, token);\n", "\t\t\tcompletes = arrays.coalesce(completes);\n", "\t\t\tif (!completes.length) {\n", "\t\t\t\treturn {\n", "\t\t\t\t\tlimitHit: false,\n", "\t\t\t\t\tresults: []\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 147 }
{ "information_for_contributors": [ "This file has been converted from https://github.com/textmate/yaml.tmbundle/blob/master/Syntaxes/YAML.tmLanguage", "If you want to provide a fix or improvement, please create a pull request against the original repository.", "Once accepted there, we are happy to receive an update request." ], "version": "https://github.com/textmate/yaml.tmbundle/commit/e54ceae3b719506dba7e481a77cea4a8b576ae46", "name": "YAML", "scopeName": "source.yaml", "patterns": [ { "include": "#comment" }, { "include": "#property" }, { "include": "#directive" }, { "match": "^---", "name": "entity.other.document.begin.yaml" }, { "match": "^\\.{3}", "name": "entity.other.document.end.yaml" }, { "include": "#node" } ], "repository": { "block-collection": { "patterns": [ { "include": "#block-sequence" }, { "include": "#block-mapping" } ] }, "block-mapping": { "patterns": [ { "include": "#block-pair" } ] }, "block-node": { "patterns": [ { "include": "#prototype" }, { "include": "#block-scalar" }, { "include": "#block-collection" }, { "include": "#flow-scalar-plain-out" }, { "include": "#flow-node" } ] }, "block-pair": { "patterns": [ { "begin": "\\?", "beginCaptures": { "1": { "name": "punctuation.definition.key-value.begin.yaml" } }, "end": "(?=\\?)|^ *(:)|(:)", "endCaptures": { "1": { "name": "punctuation.separator.key-value.mapping.yaml" }, "2": { "name": "invalid.illegal.expected-newline.yaml" } }, "name": "meta.block-mapping.yaml", "patterns": [ { "include": "#block-node" } ] }, { "begin": "(?x)\n (?=\n (?x:\n [^\\s[-?:,\\[\\]{}#&*!|>'\"%@`]]\n | [?:-] \\S\n )\n (\n [^\\s:]\n | : \\S\n | \\s+ (?![#\\s])\n )*\n \\s*\n :\n\t\t\t\t\t\t\t(\\s|$)\n )\n ", "end": "(?x)\n (?=\n \\s* $\n | \\s+ \\#\n | \\s* : (\\s|$)\n )\n ", "patterns": [ { "include": "#flow-scalar-plain-out-implicit-type" }, { "begin": "(?x)\n [^\\s[-?:,\\[\\]{}#&*!|>'\"%@`]]\n | [?:-] \\S\n ", "beginCaptures": { "0": { "name": "entity.name.tag.yaml" } }, "contentName": "entity.name.tag.yaml", "end": "(?x)\n (?=\n \\s* $\n | \\s+ \\#\n | \\s* : (\\s|$)\n )\n ", "name": "string.unquoted.plain.out.yaml" } ] }, { "match": ":(?=\\s|$)", "name": "punctuation.separator.key-value.mapping.yaml" } ] }, "block-scalar": { "begin": "(?:(\\|)|(>))([1-9])?([-+])?(.*\\n?)", "beginCaptures": { "1": { "name": "keyword.control.flow.block-scalar.literal.yaml" }, "2": { "name": "keyword.control.flow.block-scalar.folded.yaml" }, "3": { "name": "constant.numeric.indentation-indicator.yaml" }, "4": { "name": "storage.modifier.chomping-indicator.yaml" }, "5": { "patterns": [ { "include": "#comment" }, { "match": ".+", "name": "invalid.illegal.expected-comment-or-newline.yaml" } ] } }, "end": "^(?=\\S)|(?!\\G)", "patterns": [ { "begin": "^([ ]+)(?! )", "end": "^(?!\\1|\\s*$)", "name": "string.unquoted.block.yaml" } ] }, "block-sequence": { "match": "(-)(?!\\S)", "name": "punctuation.definition.block.sequence.item.yaml" }, "comment": { "begin": "(?:(^[ \\t]*)|[ \\t]+)(?=#\\p{Print}*$)", "beginCaptures": { "1": { "name": "punctuation.whitespace.comment.leading.yaml" } }, "end": "(?!\\G)", "patterns": [ { "begin": "#", "beginCaptures": { "0": { "name": "punctuation.definition.comment.yaml" } }, "end": "\\n", "name": "comment.line.number-sign.yaml" } ] }, "directive": { "begin": "^%", "beginCaptures": { "0": { "name": "punctuation.definition.directive.begin.yaml" } }, "end": "(?=$|[ \\t]+($|#))", "name": "meta.directive.yaml", "patterns": [ { "captures": { "1": { "name": "keyword.other.directive.yaml.yaml" }, "2": { "name": "constant.numeric.yaml-version.yaml" } }, "match": "\\G(YAML)[ \\t]+(\\d+\\.\\d+)" }, { "captures": { "1": { "name": "keyword.other.directive.tag.yaml" }, "2": { "name": "storage.type.tag-handle.yaml" }, "3": { "name": "support.type.tag-prefix.yaml" } }, "match": "(?x)\n \\G\n (TAG)\n (?:[ \\t]+\n ((?:!(?:[0-9A-Za-z\\-]*!)?))\n (?:[ \\t]+ (\n ! (?x: %[0-9A-Fa-f]{2} | [0-9A-Za-z\\-#;/?:@&=+$,_.!~*'()\\[\\]] )*\n | (?![,!\\[\\]{}]) (?x: %[0-9A-Fa-f]{2} | [0-9A-Za-z\\-#;/?:@&=+$,_.!~*'()\\[\\]] )+\n )\n )?\n )?\n " }, { "captures": { "1": { "name": "support.other.directive.reserved.yaml" }, "2": { "name": "string.unquoted.directive-name.yaml" }, "3": { "name": "string.unquoted.directive-parameter.yaml" } }, "match": "(?x) \\G (\\w+) (?:[ \\t]+ (\\w+) (?:[ \\t]+ (\\w+))? )?" }, { "match": "\\S+", "name": "invalid.illegal.unrecognized.yaml" } ] }, "flow-alias": { "captures": { "1": { "name": "keyword.control.flow.alias.yaml" }, "2": { "name": "punctuation.definition.alias.yaml" }, "3": { "name": "variable.other.alias.yaml" }, "4": { "name": "invalid.illegal.character.anchor.yaml" } }, "match": "((\\*))([^\\s\\[\\]/{/},]+)([^\\s\\]},]\\S*)?" }, "flow-collection": { "patterns": [ { "include": "#flow-sequence" }, { "include": "#flow-mapping" } ] }, "flow-mapping": { "begin": "\\{", "beginCaptures": { "0": { "name": "punctuation.definition.mapping.begin.yaml" } }, "end": "\\}", "endCaptures": { "0": { "name": "punctuation.definition.mapping.end.yaml" } }, "name": "meta.flow-mapping.yaml", "patterns": [ { "include": "#prototype" }, { "match": ",", "name": "punctuation.separator.mapping.yaml" }, { "include": "#flow-pair" } ] }, "flow-node": { "patterns": [ { "include": "#prototype" }, { "include": "#flow-alias" }, { "include": "#flow-collection" }, { "include": "#flow-scalar" } ] }, "flow-pair": { "patterns": [ { "begin": "\\?", "beginCaptures": { "0": { "name": "punctuation.definition.key-value.begin.yaml" } }, "end": "(?=[},\\]])", "name": "meta.flow-pair.explicit.yaml", "patterns": [ { "include": "#prototype" }, { "include": "#flow-pair" }, { "include": "#flow-node" }, { "begin": ":(?=\\s|$|[\\[\\]{},])", "beginCaptures": { "0": { "name": "punctuation.separator.key-value.mapping.yaml" } }, "end": "(?=[},\\]])", "patterns": [ { "include": "#flow-value" } ] } ] }, { "begin": "(?x)\n (?=\n (?:\n [^\\s[-?:,\\[\\]{}#&*!|>'\"%@`]]\n | [?:-] [^\\s[\\[\\]{},]]\n )\n (\n [^\\s:[\\[\\]{},]]\n | : [^\\s[\\[\\]{},]]\n | \\s+ (?![#\\s])\n )*\n \\s*\n :\n\t\t\t\t\t\t\t(\\s|$)\n )\n ", "end": "(?x)\n (?=\n \\s* $\n | \\s+ \\#\n | \\s* : (\\s|$)\n | \\s* : [\\[\\]{},]\n | \\s* [\\[\\]{},]\n )\n ", "name": "meta.flow-pair.key.yaml", "patterns": [ { "include": "#flow-scalar-plain-in-implicit-type" }, { "begin": "(?x)\n [^\\s[-?:,\\[\\]{}#&*!|>'\"%@`]]\n | [?:-] [^\\s[\\[\\]{},]]\n ", "beginCaptures": { "0": { "name": "entity.name.tag.yaml" } }, "contentName": "entity.name.tag.yaml", "end": "(?x)\n (?=\n \\s* $\n | \\s+ \\#\n | \\s* : (\\s|$)\n | \\s* : [\\[\\]{},]\n | \\s* [\\[\\]{},]\n )\n ", "name": "string.unquoted.plain.in.yaml" } ] }, { "include": "#flow-node" }, { "begin": ":(?=\\s|$|[\\[\\]{},])", "captures": { "0": { "name": "punctuation.separator.key-value.mapping.yaml" } }, "end": "(?=[},\\]])", "name": "meta.flow-pair.yaml", "patterns": [ { "include": "#flow-value" } ] } ] }, "flow-scalar": { "patterns": [ { "include": "#flow-scalar-double-quoted" }, { "include": "#flow-scalar-single-quoted" }, { "include": "#flow-scalar-plain-in" } ] }, "flow-scalar-double-quoted": { "begin": "\"", "beginCaptures": { "0": { "name": "punctuation.definition.string.begin.yaml" } }, "end": "\"", "endCaptures": { "0": { "name": "punctuation.definition.string.end.yaml" } }, "name": "string.quoted.double.yaml", "patterns": [ { "match": "\\\\([0abtnvfre \"/\\\\N_Lp]|x\\d\\d|u\\d{4}|U\\d{8})", "name": "constant.character.escape.yaml" }, { "match": "\\\\\\n", "name": "constant.character.escape.double-quoted.newline.yaml" } ] }, "flow-scalar-plain-in": { "patterns": [ { "include": "#flow-scalar-plain-in-implicit-type" }, { "begin": "(?x)\n [^\\s[-?:,\\[\\]{}#&*!|>'\"%@`]]\n | [?:-] [^\\s[\\[\\]{},]]\n ", "end": "(?x)\n (?=\n \\s* $\n | \\s+ \\#\n | \\s* : (\\s|$)\n | \\s* : [\\[\\]{},]\n | \\s* [\\[\\]{},]\n )\n ", "name": "string.unquoted.plain.in.yaml" } ] }, "flow-scalar-plain-in-implicit-type": { "patterns": [ { "captures": { "1": { "name": "constant.language.null.yaml" }, "2": { "name": "constant.language.boolean.yaml" }, "3": { "name": "constant.numeric.integer.yaml" }, "4": { "name": "constant.numeric.float.yaml" }, "5": { "name": "constant.other.timestamp.yaml" }, "6": { "name": "constant.language.value.yaml" }, "7": { "name": "constant.language.merge.yaml" } }, "match": "(?x)\n (?x:\n (null|Null|NULL|~)\n | (y|Y|yes|Yes|YES|n|N|no|No|NO|true|True|TRUE|false|False|FALSE|on|On|ON|off|Off|OFF)\n | (\n (?:\n [-+]? 0b [0-1_]+ # (base 2)\n | [-+]? 0 [0-7_]+ # (base 8)\n | [-+]? (?: 0|[1-9][0-9_]*) # (base 10)\n | [-+]? 0x [0-9a-fA-F_]+ # (base 16)\n | [-+]? [1-9] [0-9_]* (?: :[0-5]?[0-9])+ # (base 60)\n )\n )\n | (\n (?x:\n [-+]? (?: [0-9] [0-9_]*)? \\. [0-9.]* (?: [eE] [-+] [0-9]+)? # (base 10)\n | [-+]? [0-9] [0-9_]* (?: :[0-5]?[0-9])+ \\. [0-9_]* # (base 60)\n | [-+]? \\. (?: inf|Inf|INF) # (infinity)\n | \\. (?: nan|NaN|NAN) # (not a number)\n )\n )\n | (\n (?x:\n \\d{4} - \\d{2} - \\d{2} # (y-m-d)\n | \\d{4} # (year)\n - \\d{1,2} # (month)\n - \\d{1,2} # (day)\n (?: [Tt] | [ \\t]+) \\d{1,2} # (hour)\n : \\d{2} # (minute)\n : \\d{2} # (second)\n (?: \\.\\d*)? # (fraction)\n (?:\n (?:[ \\t]*) Z\n | [-+] \\d{1,2} (?: :\\d{1,2})?\n )? # (time zone)\n )\n )\n | (=)\n | (<<)\n )\n (?:\n (?=\n \\s* $\n | \\s+ \\#\n | \\s* : (\\s|$)\n | \\s* : [\\[\\]{},]\n | \\s* [\\[\\]{},]\n )\n )\n " } ] }, "flow-scalar-plain-out": { "patterns": [ { "include": "#flow-scalar-plain-out-implicit-type" }, { "begin": "(?x)\n [^\\s[-?:,\\[\\]{}#&*!|>'\"%@`]]\n | [?:-] \\S\n ", "end": "(?x)\n (?=\n \\s* $\n | \\s+ \\#\n | \\s* : (\\s|$)\n )\n ", "name": "string.unquoted.plain.out.yaml" } ] }, "flow-scalar-plain-out-implicit-type": { "patterns": [ { "captures": { "1": { "name": "constant.language.null.yaml" }, "2": { "name": "constant.language.boolean.yaml" }, "3": { "name": "constant.numeric.integer.yaml" }, "4": { "name": "constant.numeric.float.yaml" }, "5": { "name": "constant.other.timestamp.yaml" }, "6": { "name": "constant.language.value.yaml" }, "7": { "name": "constant.language.merge.yaml" } }, "match": "(?x)\n (?x:\n (null|Null|NULL|~)\n | (y|Y|yes|Yes|YES|n|N|no|No|NO|true|True|TRUE|false|False|FALSE|on|On|ON|off|Off|OFF)\n | (\n (?:\n [-+]? 0b [0-1_]+ # (base 2)\n | [-+]? 0 [0-7_]+ # (base 8)\n | [-+]? (?: 0|[1-9][0-9_]*) # (base 10)\n | [-+]? 0x [0-9a-fA-F_]+ # (base 16)\n | [-+]? [1-9] [0-9_]* (?: :[0-5]?[0-9])+ # (base 60)\n )\n )\n | (\n (?x:\n [-+]? (?: [0-9] [0-9_]*)? \\. [0-9.]* (?: [eE] [-+] [0-9]+)? # (base 10)\n | [-+]? [0-9] [0-9_]* (?: :[0-5]?[0-9])+ \\. [0-9_]* # (base 60)\n | [-+]? \\. (?: inf|Inf|INF) # (infinity)\n | \\. (?: nan|NaN|NAN) # (not a number)\n )\n )\n | (\n (?x:\n \\d{4} - \\d{2} - \\d{2} # (y-m-d)\n | \\d{4} # (year)\n - \\d{1,2} # (month)\n - \\d{1,2} # (day)\n (?: [Tt] | [ \\t]+) \\d{1,2} # (hour)\n : \\d{2} # (minute)\n : \\d{2} # (second)\n (?: \\.\\d*)? # (fraction)\n (?:\n (?:[ \\t]*) Z\n | [-+] \\d{1,2} (?: :\\d{1,2})?\n )? # (time zone)\n )\n )\n | (=)\n | (<<)\n )\n (?x:\n (?=\n \\s* $\n | \\s+ \\#\n | \\s* : (\\s|$)\n )\n )\n " } ] }, "flow-scalar-single-quoted": { "begin": "'", "beginCaptures": { "0": { "name": "punctuation.definition.string.begin.yaml" } }, "end": "'(?!')", "endCaptures": { "0": { "name": "punctuation.definition.string.end.yaml" } }, "name": "string.quoted.single.yaml", "patterns": [ { "match": "''", "name": "constant.character.escape.single-quoted.yaml" } ] }, "flow-sequence": { "begin": "\\[", "beginCaptures": { "0": { "name": "punctuation.definition.sequence.begin.yaml" } }, "end": "\\]", "endCaptures": { "0": { "name": "punctuation.definition.sequence.end.yaml" } }, "name": "meta.flow-sequence.yaml", "patterns": [ { "include": "#prototype" }, { "match": ",", "name": "punctuation.separator.sequence.yaml" }, { "include": "#flow-pair" }, { "include": "#flow-node" } ] }, "flow-value": { "patterns": [ { "begin": "\\G(?![},\\]])", "end": "(?=[},\\]])", "name": "meta.flow-pair.value.yaml", "patterns": [ { "include": "#flow-node" } ] } ] }, "node": { "patterns": [ { "include": "#block-node" } ] }, "property": { "begin": "(?=!|&)", "end": "(?!\\G)", "name": "meta.property.yaml", "patterns": [ { "captures": { "1": { "name": "keyword.control.property.anchor.yaml" }, "2": { "name": "punctuation.definition.anchor.yaml" }, "3": { "name": "entity.name.type.anchor.yaml" }, "4": { "name": "invalid.illegal.character.anchor.yaml" } }, "match": "\\G((&))([^\\s\\[\\]/{/},]+)(\\S+)?" }, { "match": "(?x)\n \\G\n (?:\n ! < (?: %[0-9A-Fa-f]{2} | [0-9A-Za-z\\-#;/?:@&=+$,_.!~*'()\\[\\]] )+ >\n | (?:!(?:[0-9A-Za-z\\-]*!)?) (?: %[0-9A-Fa-f]{2} | [0-9A-Za-z\\-#;/?:@&=+$_.~*'()] )+\n | !\n )\n (?=\\ |\\t|$)\n ", "name": "storage.type.tag-handle.yaml" }, { "match": "\\S+", "name": "invalid.illegal.tag-handle.yaml" } ] }, "prototype": { "patterns": [ { "include": "#comment" }, { "include": "#property" } ] } } }
extensions/yaml/syntaxes/yaml.tmLanguage.json
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.0003460157022345811, 0.00017756597662810236, 0.00016436497389804572, 0.0001757100544637069, 0.00002161072006856557 ]
{ "id": 6, "code_window": [ "\t\t\t\t};\n", "\t\t\t});\n", "\n", "\t\treturn new Promise((resolve, reject) => {\n", "\t\t\tif (token) {\n", "\t\t\t\ttoken.onCancellationRequested(() => {\n", "\t\t\t\t\treject(canceled());\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t}\n", "\n", "\t\t\treturn <ISearchComplete>{\n", "\t\t\t\tlimitHit: completes[0] && completes[0].limitHit,\n", "\t\t\t\tstats: completes[0].stats,\n", "\t\t\t\tresults: arrays.flatten(completes.map((c: ISearchComplete) => c.results))\n", "\t\t\t};\n", "\t\t})();\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 152 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { getPathFromAmdModule } from 'vs/base/common/amd'; import { CancellationToken } from 'vs/base/common/cancellation'; import { canceled } from 'vs/base/common/errors'; import { Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { URI as uri } from 'vs/base/common/uri'; import { getNextTickChannel } from 'vs/base/parts/ipc/common/ipc'; import { Client, IIPCOptions } from 'vs/base/parts/ipc/node/ipc.cp'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IDebugParams, IEnvironmentService } from 'vs/platform/environment/common/environment'; import { parseSearchPort, INativeEnvironmentService } from 'vs/platform/environment/node/environmentService'; import { IFileService } from 'vs/platform/files/common/files'; import { ILogService } from 'vs/platform/log/common/log'; import { FileMatch, IFileMatch, IFileQuery, IProgressMessage, IRawSearchService, ISearchComplete, ISearchConfiguration, ISearchProgressItem, ISearchResultProvider, ISerializedFileMatch, ISerializedSearchComplete, ISerializedSearchProgressItem, isSerializedSearchComplete, isSerializedSearchSuccess, ITextQuery, ISearchService, isFileMatch } from 'vs/workbench/services/search/common/search'; import { SearchChannelClient } from './searchIpc'; import { SearchService } from 'vs/workbench/services/search/common/searchService'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; export class LocalSearchService extends SearchService { constructor( @IModelService modelService: IModelService, @IEditorService editorService: IEditorService, @ITelemetryService telemetryService: ITelemetryService, @ILogService logService: ILogService, @IExtensionService extensionService: IExtensionService, @IFileService fileService: IFileService, @IEnvironmentService readonly environmentService: INativeEnvironmentService, @IInstantiationService readonly instantiationService: IInstantiationService ) { super(modelService, editorService, telemetryService, logService, extensionService, fileService); this.diskSearch = instantiationService.createInstance(DiskSearch, !environmentService.isBuilt || environmentService.verbose, parseSearchPort(environmentService.args, environmentService.isBuilt)); } } export class DiskSearch implements ISearchResultProvider { private raw: IRawSearchService; constructor( verboseLogging: boolean, searchDebug: IDebugParams | undefined, @ILogService private readonly logService: ILogService, @IConfigurationService private readonly configService: IConfigurationService, @IFileService private readonly fileService: IFileService ) { const timeout = this.configService.getValue<ISearchConfiguration>().search.maintainFileSearchCache ? Number.MAX_VALUE : 60 * 60 * 1000; const opts: IIPCOptions = { serverName: 'Search', timeout, args: ['--type=searchService'], // See https://github.com/Microsoft/vscode/issues/27665 // Pass in fresh execArgv to the forked process such that it doesn't inherit them from `process.execArgv`. // e.g. Launching the extension host process with `--inspect-brk=xxx` and then forking a process from the extension host // results in the forked process inheriting `--inspect-brk=xxx`. freshExecArgv: true, env: { AMD_ENTRYPOINT: 'vs/workbench/services/search/node/searchApp', PIPE_LOGGING: 'true', VERBOSE_LOGGING: verboseLogging }, useQueue: true }; if (searchDebug) { if (searchDebug.break && searchDebug.port) { opts.debugBrk = searchDebug.port; } else if (!searchDebug.break && searchDebug.port) { opts.debug = searchDebug.port; } } const client = new Client( getPathFromAmdModule(require, 'bootstrap-fork'), opts); const channel = getNextTickChannel(client.getChannel('search')); this.raw = new SearchChannelClient(channel); } textSearch(query: ITextQuery, onProgress?: (p: ISearchProgressItem) => void, token?: CancellationToken): Promise<ISearchComplete> { const folderQueries = query.folderQueries || []; return Promise.all(folderQueries.map(q => this.fileService.exists(q.folder))) .then(exists => { if (token && token.isCancellationRequested) { throw canceled(); } query.folderQueries = folderQueries.filter((q, index) => exists[index]); const event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete> = this.raw.textSearch(query); return DiskSearch.collectResultsFromEvent(event, onProgress, token); }); } fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { const folderQueries = query.folderQueries || []; return Promise.all(folderQueries.map(q => this.fileService.exists(q.folder))) .then(exists => { if (token && token.isCancellationRequested) { throw canceled(); } query.folderQueries = folderQueries.filter((q, index) => exists[index]); let event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete>; event = this.raw.fileSearch(query); const onProgress = (p: ISearchProgressItem) => { if (!isFileMatch(p)) { // Should only be for logs this.logService.debug('SearchService#search', p.message); } }; return DiskSearch.collectResultsFromEvent(event, onProgress, token); }); } /** * Public for test */ static collectResultsFromEvent(event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete>, onProgress?: (p: ISearchProgressItem) => void, token?: CancellationToken): Promise<ISearchComplete> { let result: IFileMatch[] = []; let listener: IDisposable; return new Promise<ISearchComplete>((c, e) => { if (token) { token.onCancellationRequested(() => { if (listener) { listener.dispose(); } e(canceled()); }); } listener = event(ev => { if (isSerializedSearchComplete(ev)) { if (isSerializedSearchSuccess(ev)) { c({ limitHit: ev.limitHit, results: result, stats: ev.stats }); } else { e(ev.error); } listener.dispose(); } else { // Matches if (Array.isArray(ev)) { const fileMatches = ev.map(d => this.createFileMatch(d)); result = result.concat(fileMatches); if (onProgress) { fileMatches.forEach(onProgress); } } // Match else if ((<ISerializedFileMatch>ev).path) { const fileMatch = this.createFileMatch(<ISerializedFileMatch>ev); result.push(fileMatch); if (onProgress) { onProgress(fileMatch); } } // Progress else if (onProgress) { onProgress(<IProgressMessage>ev); } } }); }); } private static createFileMatch(data: ISerializedFileMatch): FileMatch { const fileMatch = new FileMatch(uri.file(data.path)); if (data.results) { // const matches = data.results.filter(resultIsMatch); fileMatch.results.push(...data.results); } return fileMatch; } clearCache(cacheKey: string): Promise<void> { return this.raw.clearCache(cacheKey); } } registerSingleton(ISearchService, LocalSearchService, true);
src/vs/workbench/services/search/node/searchService.ts
1
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.023301785811781883, 0.002545480616390705, 0.0001644000585656613, 0.00016958577907644212, 0.006134095601737499 ]
{ "id": 6, "code_window": [ "\t\t\t\t};\n", "\t\t\t});\n", "\n", "\t\treturn new Promise((resolve, reject) => {\n", "\t\t\tif (token) {\n", "\t\t\t\ttoken.onCancellationRequested(() => {\n", "\t\t\t\t\treject(canceled());\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t}\n", "\n", "\t\t\treturn <ISearchComplete>{\n", "\t\t\t\tlimitHit: completes[0] && completes[0].limitHit,\n", "\t\t\t\tstats: completes[0].stats,\n", "\t\t\t\tresults: arrays.flatten(completes.map((c: ISearchComplete) => c.results))\n", "\t\t\t};\n", "\t\t})();\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 152 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Application, Quality, StatusBarElement } from '../../../../automation'; export function setup(isWeb) { describe('Statusbar', () => { it('verifies presence of all default status bar elements', async function () { const app = this.app as Application; await app.workbench.statusbar.waitForStatusbarElement(StatusBarElement.BRANCH_STATUS); if (app.quality !== Quality.Dev) { await app.workbench.statusbar.waitForStatusbarElement(StatusBarElement.FEEDBACK_ICON); } await app.workbench.statusbar.waitForStatusbarElement(StatusBarElement.SYNC_STATUS); await app.workbench.statusbar.waitForStatusbarElement(StatusBarElement.PROBLEMS_STATUS); await app.workbench.quickaccess.openFile('app.js'); if (!isWeb) { // Encoding picker currently hidden in web (only UTF-8 supported) await app.workbench.statusbar.waitForStatusbarElement(StatusBarElement.ENCODING_STATUS); } await app.workbench.statusbar.waitForStatusbarElement(StatusBarElement.EOL_STATUS); await app.workbench.statusbar.waitForStatusbarElement(StatusBarElement.INDENTATION_STATUS); await app.workbench.statusbar.waitForStatusbarElement(StatusBarElement.LANGUAGE_STATUS); await app.workbench.statusbar.waitForStatusbarElement(StatusBarElement.SELECTION_STATUS); }); it(`verifies that 'quick input' opens when clicking on status bar elements`, async function () { const app = this.app as Application; await app.workbench.statusbar.clickOn(StatusBarElement.BRANCH_STATUS); await app.workbench.quickinput.waitForQuickInputOpened(); await app.workbench.quickinput.closeQuickInput(); await app.workbench.quickaccess.openFile('app.js'); await app.workbench.statusbar.clickOn(StatusBarElement.INDENTATION_STATUS); await app.workbench.quickinput.waitForQuickInputOpened(); await app.workbench.quickinput.closeQuickInput(); if (!isWeb) { // Encoding picker currently hidden in web (only UTF-8 supported) await app.workbench.statusbar.clickOn(StatusBarElement.ENCODING_STATUS); await app.workbench.quickinput.waitForQuickInputOpened(); await app.workbench.quickinput.closeQuickInput(); } await app.workbench.statusbar.clickOn(StatusBarElement.EOL_STATUS); await app.workbench.quickinput.waitForQuickInputOpened(); await app.workbench.quickinput.closeQuickInput(); await app.workbench.statusbar.clickOn(StatusBarElement.LANGUAGE_STATUS); await app.workbench.quickinput.waitForQuickInputOpened(); await app.workbench.quickinput.closeQuickInput(); }); it(`verifies that 'Problems View' appears when clicking on 'Problems' status element`, async function () { const app = this.app as Application; await app.workbench.statusbar.clickOn(StatusBarElement.PROBLEMS_STATUS); await app.workbench.problems.waitForProblemsView(); }); it(`verifies that 'Tweet us feedback' pop-up appears when clicking on 'Feedback' icon`, async function () { const app = this.app as Application; if (app.quality === Quality.Dev) { return this.skip(); } await app.workbench.statusbar.clickOn(StatusBarElement.FEEDBACK_ICON); await app.code.waitForElement('.feedback-form'); }); it(`checks if 'Go to Line' works if called from the status bar`, async function () { const app = this.app as Application; await app.workbench.quickaccess.openFile('app.js'); await app.workbench.statusbar.clickOn(StatusBarElement.SELECTION_STATUS); await app.workbench.quickinput.waitForQuickInputOpened(); await app.workbench.quickinput.submit(':15'); await app.workbench.editor.waitForHighlightingLine('app.js', 15); }); it(`verifies if changing EOL is reflected in the status bar`, async function () { const app = this.app as Application; await app.workbench.quickaccess.openFile('app.js'); await app.workbench.statusbar.clickOn(StatusBarElement.EOL_STATUS); await app.workbench.quickinput.waitForQuickInputOpened(); await app.workbench.quickinput.selectQuickInputElement(1); await app.workbench.statusbar.waitForEOL('CRLF'); }); }); }
test/smoke/src/areas/statusbar/statusbar.test.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00017195477266795933, 0.00016738931299187243, 0.00016150575538631529, 0.00016831778339110315, 0.000003202134621460573 ]
{ "id": 6, "code_window": [ "\t\t\t\t};\n", "\t\t\t});\n", "\n", "\t\treturn new Promise((resolve, reject) => {\n", "\t\t\tif (token) {\n", "\t\t\t\ttoken.onCancellationRequested(() => {\n", "\t\t\t\t\treject(canceled());\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t}\n", "\n", "\t\t\treturn <ISearchComplete>{\n", "\t\t\t\tlimitHit: completes[0] && completes[0].limitHit,\n", "\t\t\t\tstats: completes[0].stats,\n", "\t\t\t\tresults: arrays.flatten(completes.map((c: ISearchComplete) => c.results))\n", "\t\t\t};\n", "\t\t})();\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 152 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Color } from 'vs/base/common/color'; import { ColorId, FontStyle, LanguageId, MetadataConsts, StandardTokenType } from 'vs/editor/common/modes'; export interface ITokenThemeRule { token: string; foreground?: string; background?: string; fontStyle?: string; } export class ParsedTokenThemeRule { _parsedThemeRuleBrand: void; readonly token: string; readonly index: number; /** * -1 if not set. An or mask of `FontStyle` otherwise. */ readonly fontStyle: FontStyle; readonly foreground: string | null; readonly background: string | null; constructor( token: string, index: number, fontStyle: number, foreground: string | null, background: string | null, ) { this.token = token; this.index = index; this.fontStyle = fontStyle; this.foreground = foreground; this.background = background; } } /** * Parse a raw theme into rules. */ export function parseTokenTheme(source: ITokenThemeRule[]): ParsedTokenThemeRule[] { if (!source || !Array.isArray(source)) { return []; } let result: ParsedTokenThemeRule[] = [], resultLen = 0; for (let i = 0, len = source.length; i < len; i++) { let entry = source[i]; let fontStyle: number = FontStyle.NotSet; if (typeof entry.fontStyle === 'string') { fontStyle = FontStyle.None; let segments = entry.fontStyle.split(' '); for (let j = 0, lenJ = segments.length; j < lenJ; j++) { let segment = segments[j]; switch (segment) { case 'italic': fontStyle = fontStyle | FontStyle.Italic; break; case 'bold': fontStyle = fontStyle | FontStyle.Bold; break; case 'underline': fontStyle = fontStyle | FontStyle.Underline; break; } } } let foreground: string | null = null; if (typeof entry.foreground === 'string') { foreground = entry.foreground; } let background: string | null = null; if (typeof entry.background === 'string') { background = entry.background; } result[resultLen++] = new ParsedTokenThemeRule( entry.token || '', i, fontStyle, foreground, background ); } return result; } /** * Resolve rules (i.e. inheritance). */ function resolveParsedTokenThemeRules(parsedThemeRules: ParsedTokenThemeRule[], customTokenColors: string[]): TokenTheme { // Sort rules lexicographically, and then by index if necessary parsedThemeRules.sort((a, b) => { let r = strcmp(a.token, b.token); if (r !== 0) { return r; } return a.index - b.index; }); // Determine defaults let defaultFontStyle = FontStyle.None; let defaultForeground = '000000'; let defaultBackground = 'ffffff'; while (parsedThemeRules.length >= 1 && parsedThemeRules[0].token === '') { let incomingDefaults = parsedThemeRules.shift()!; if (incomingDefaults.fontStyle !== FontStyle.NotSet) { defaultFontStyle = incomingDefaults.fontStyle; } if (incomingDefaults.foreground !== null) { defaultForeground = incomingDefaults.foreground; } if (incomingDefaults.background !== null) { defaultBackground = incomingDefaults.background; } } let colorMap = new ColorMap(); // start with token colors from custom token themes for (let color of customTokenColors) { colorMap.getId(color); } let foregroundColorId = colorMap.getId(defaultForeground); let backgroundColorId = colorMap.getId(defaultBackground); let defaults = new ThemeTrieElementRule(defaultFontStyle, foregroundColorId, backgroundColorId); let root = new ThemeTrieElement(defaults); for (let i = 0, len = parsedThemeRules.length; i < len; i++) { let rule = parsedThemeRules[i]; root.insert(rule.token, rule.fontStyle, colorMap.getId(rule.foreground), colorMap.getId(rule.background)); } return new TokenTheme(colorMap, root); } const colorRegExp = /^#?([0-9A-Fa-f]{6})([0-9A-Fa-f]{2})?$/; export class ColorMap { private _lastColorId: number; private readonly _id2color: Color[]; private readonly _color2id: Map<string, ColorId>; constructor() { this._lastColorId = 0; this._id2color = []; this._color2id = new Map<string, ColorId>(); } public getId(color: string | null): ColorId { if (color === null) { return 0; } const match = color.match(colorRegExp); if (!match) { throw new Error('Illegal value for token color: ' + color); } color = match[1].toUpperCase(); let value = this._color2id.get(color); if (value) { return value; } value = ++this._lastColorId; this._color2id.set(color, value); this._id2color[value] = Color.fromHex('#' + color); return value; } public getColorMap(): Color[] { return this._id2color.slice(0); } } export class TokenTheme { public static createFromRawTokenTheme(source: ITokenThemeRule[], customTokenColors: string[]): TokenTheme { return this.createFromParsedTokenTheme(parseTokenTheme(source), customTokenColors); } public static createFromParsedTokenTheme(source: ParsedTokenThemeRule[], customTokenColors: string[]): TokenTheme { return resolveParsedTokenThemeRules(source, customTokenColors); } private readonly _colorMap: ColorMap; private readonly _root: ThemeTrieElement; private readonly _cache: Map<string, number>; constructor(colorMap: ColorMap, root: ThemeTrieElement) { this._colorMap = colorMap; this._root = root; this._cache = new Map<string, number>(); } public getColorMap(): Color[] { return this._colorMap.getColorMap(); } /** * used for testing purposes */ public getThemeTrieElement(): ExternalThemeTrieElement { return this._root.toExternalThemeTrieElement(); } public _match(token: string): ThemeTrieElementRule { return this._root.match(token); } public match(languageId: LanguageId, token: string): number { // The cache contains the metadata without the language bits set. let result = this._cache.get(token); if (typeof result === 'undefined') { let rule = this._match(token); let standardToken = toStandardTokenType(token); result = ( rule.metadata | (standardToken << MetadataConsts.TOKEN_TYPE_OFFSET) ) >>> 0; this._cache.set(token, result); } return ( result | (languageId << MetadataConsts.LANGUAGEID_OFFSET) ) >>> 0; } } const STANDARD_TOKEN_TYPE_REGEXP = /\b(comment|string|regex|regexp)\b/; export function toStandardTokenType(tokenType: string): StandardTokenType { let m = tokenType.match(STANDARD_TOKEN_TYPE_REGEXP); if (!m) { return StandardTokenType.Other; } switch (m[1]) { case 'comment': return StandardTokenType.Comment; case 'string': return StandardTokenType.String; case 'regex': return StandardTokenType.RegEx; case 'regexp': return StandardTokenType.RegEx; } throw new Error('Unexpected match for standard token type!'); } export function strcmp(a: string, b: string): number { if (a < b) { return -1; } if (a > b) { return 1; } return 0; } export class ThemeTrieElementRule { _themeTrieElementRuleBrand: void; private _fontStyle: FontStyle; private _foreground: ColorId; private _background: ColorId; public metadata: number; constructor(fontStyle: FontStyle, foreground: ColorId, background: ColorId) { this._fontStyle = fontStyle; this._foreground = foreground; this._background = background; this.metadata = ( (this._fontStyle << MetadataConsts.FONT_STYLE_OFFSET) | (this._foreground << MetadataConsts.FOREGROUND_OFFSET) | (this._background << MetadataConsts.BACKGROUND_OFFSET) ) >>> 0; } public clone(): ThemeTrieElementRule { return new ThemeTrieElementRule(this._fontStyle, this._foreground, this._background); } public acceptOverwrite(fontStyle: FontStyle, foreground: ColorId, background: ColorId): void { if (fontStyle !== FontStyle.NotSet) { this._fontStyle = fontStyle; } if (foreground !== ColorId.None) { this._foreground = foreground; } if (background !== ColorId.None) { this._background = background; } this.metadata = ( (this._fontStyle << MetadataConsts.FONT_STYLE_OFFSET) | (this._foreground << MetadataConsts.FOREGROUND_OFFSET) | (this._background << MetadataConsts.BACKGROUND_OFFSET) ) >>> 0; } } export class ExternalThemeTrieElement { public readonly mainRule: ThemeTrieElementRule; public readonly children: { [segment: string]: ExternalThemeTrieElement }; constructor(mainRule: ThemeTrieElementRule, children?: { [segment: string]: ExternalThemeTrieElement }) { this.mainRule = mainRule; this.children = children || Object.create(null); } } export class ThemeTrieElement { _themeTrieElementBrand: void; private readonly _mainRule: ThemeTrieElementRule; private readonly _children: Map<string, ThemeTrieElement>; constructor(mainRule: ThemeTrieElementRule) { this._mainRule = mainRule; this._children = new Map<string, ThemeTrieElement>(); } /** * used for testing purposes */ public toExternalThemeTrieElement(): ExternalThemeTrieElement { let children: { [segment: string]: ExternalThemeTrieElement } = Object.create(null); this._children.forEach((element, index) => { children[index] = element.toExternalThemeTrieElement(); }); return new ExternalThemeTrieElement(this._mainRule, children); } public match(token: string): ThemeTrieElementRule { if (token === '') { return this._mainRule; } let dotIndex = token.indexOf('.'); let head: string; let tail: string; if (dotIndex === -1) { head = token; tail = ''; } else { head = token.substring(0, dotIndex); tail = token.substring(dotIndex + 1); } let child = this._children.get(head); if (typeof child !== 'undefined') { return child.match(tail); } return this._mainRule; } public insert(token: string, fontStyle: FontStyle, foreground: ColorId, background: ColorId): void { if (token === '') { // Merge into the main rule this._mainRule.acceptOverwrite(fontStyle, foreground, background); return; } let dotIndex = token.indexOf('.'); let head: string; let tail: string; if (dotIndex === -1) { head = token; tail = ''; } else { head = token.substring(0, dotIndex); tail = token.substring(dotIndex + 1); } let child = this._children.get(head); if (typeof child === 'undefined') { child = new ThemeTrieElement(this._mainRule.clone()); this._children.set(head, child); } child.insert(tail, fontStyle, foreground, background); } } export function generateTokensCSSForColorMap(colorMap: Color[]): string { let rules: string[] = []; for (let i = 1, len = colorMap.length; i < len; i++) { let color = colorMap[i]; rules[i] = `.mtk${i} { color: ${color}; }`; } rules.push('.mtki { font-style: italic; }'); rules.push('.mtkb { font-weight: bold; }'); rules.push('.mtku { text-decoration: underline; text-underline-position: under; }'); return rules.join('\n'); }
src/vs/editor/common/modes/supports/tokenization.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00515417754650116, 0.0005385933327488601, 0.00016422521730419248, 0.0001758335711201653, 0.0009172068675979972 ]
{ "id": 6, "code_window": [ "\t\t\t\t};\n", "\t\t\t});\n", "\n", "\t\treturn new Promise((resolve, reject) => {\n", "\t\t\tif (token) {\n", "\t\t\t\ttoken.onCancellationRequested(() => {\n", "\t\t\t\t\treject(canceled());\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t}\n", "\n", "\t\t\treturn <ISearchComplete>{\n", "\t\t\t\tlimitHit: completes[0] && completes[0].limitHit,\n", "\t\t\t\tstats: completes[0].stats,\n", "\t\t\t\tresults: arrays.flatten(completes.map((c: ISearchComplete) => c.results))\n", "\t\t\t};\n", "\t\t})();\n" ], "file_path": "src/vs/workbench/services/search/common/searchService.ts", "type": "replace", "edit_start_line_idx": 152 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Application, Quality } from '../../../../automation'; export function setup() { describe('Extensions', () => { it(`install and activate vscode-smoketest-check extension`, async function () { const app = this.app as Application; if (app.quality === Quality.Dev) { this.skip(); return; } await app.workbench.extensions.openExtensionsViewlet(); await app.workbench.extensions.installExtension('michelkaporin.vscode-smoketest-check', 'vscode-smoketest-check'); await app.workbench.extensions.waitForExtensionsViewlet(); if (app.remote) { await app.reload(); } await app.workbench.quickaccess.runCommand('Smoke Test Check'); await app.workbench.statusbar.waitForStatusbarText('smoke test', 'VS Code Smoke Test Check'); }); }); }
test/smoke/src/areas/extensions/extensions.test.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00017565475718583912, 0.00017139312694780529, 0.0001678725384408608, 0.00017102259153034538, 0.0000029022937724221265 ]
{ "id": 7, "code_window": [ "\t\tsearchDebug: IDebugParams | undefined,\n", "\t\t@ILogService private readonly logService: ILogService,\n", "\t\t@IConfigurationService private readonly configService: IConfigurationService,\n", "\t\t@IFileService private readonly fileService: IFileService\n", "\t) {\n", "\t\tconst timeout = this.configService.getValue<ISearchConfiguration>().search.maintainFileSearchCache ?\n", "\t\t\tNumber.MAX_VALUE :\n", "\t\t\t60 * 60 * 1000;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 53 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as arrays from 'vs/base/common/arrays'; import { CancellationToken } from 'vs/base/common/cancellation'; import { canceled } from 'vs/base/common/errors'; import { Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { keys, ResourceMap, values } from 'vs/base/common/map'; import { Schemas } from 'vs/base/common/network'; import { StopWatch } from 'vs/base/common/stopwatch'; import { URI as uri } from 'vs/base/common/uri'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IFileService } from 'vs/platform/files/common/files'; import { ILogService } from 'vs/platform/log/common/log'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { deserializeSearchError, FileMatch, ICachedSearchStats, IFileMatch, IFileQuery, IFileSearchStats, IFolderQuery, IProgressMessage, ISearchComplete, ISearchEngineStats, ISearchProgressItem, ISearchQuery, ISearchResultProvider, ISearchService, ITextQuery, pathIncludedInQuery, QueryType, SearchError, SearchErrorCode, SearchProviderType, isFileMatch, isProgressMessage } from 'vs/workbench/services/search/common/search'; import { addContextToEditorMatches, editorMatchesToTextSearchResults } from 'vs/workbench/services/search/common/searchHelpers'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { DeferredPromise } from 'vs/base/test/common/utils'; export class SearchService extends Disposable implements ISearchService { _serviceBrand: undefined; protected diskSearch: ISearchResultProvider | null = null; private readonly fileSearchProviders = new Map<string, ISearchResultProvider>(); private readonly textSearchProviders = new Map<string, ISearchResultProvider>(); private deferredFileSearchesByScheme = new Map<string, DeferredPromise<ISearchResultProvider>>(); private deferredTextSearchesByScheme = new Map<string, DeferredPromise<ISearchResultProvider>>(); constructor( private readonly modelService: IModelService, private readonly editorService: IEditorService, private readonly telemetryService: ITelemetryService, private readonly logService: ILogService, private readonly extensionService: IExtensionService, private readonly fileService: IFileService ) { super(); } registerSearchResultProvider(scheme: string, type: SearchProviderType, provider: ISearchResultProvider): IDisposable { let list: Map<string, ISearchResultProvider>; let deferredMap: Map<string, DeferredPromise<ISearchResultProvider>>; if (type === SearchProviderType.file) { list = this.fileSearchProviders; deferredMap = this.deferredFileSearchesByScheme; } else if (type === SearchProviderType.text) { list = this.textSearchProviders; deferredMap = this.deferredTextSearchesByScheme; } else { throw new Error('Unknown SearchProviderType'); } list.set(scheme, provider); if (deferredMap.has(scheme)) { deferredMap.get(scheme)!.complete(provider); deferredMap.delete(scheme); } return toDisposable(() => { list.delete(scheme); }); } async textSearch(query: ITextQuery, token?: CancellationToken, onProgress?: (item: ISearchProgressItem) => void): Promise<ISearchComplete> { // Get local results from dirty/untitled const localResults = this.getLocalResults(query); if (onProgress) { arrays.coalesce([...localResults.results.values()]).forEach(onProgress); } const onProviderProgress = (progress: ISearchProgressItem) => { if (isFileMatch(progress)) { // Match if (!localResults.results.has(progress.resource) && onProgress) { // don't override local results onProgress(progress); } } else if (onProgress) { // Progress onProgress(<IProgressMessage>progress); } if (isProgressMessage(progress)) { this.logService.debug('SearchService#search', progress.message); } }; const otherResults = await this.doSearch(query, token, onProviderProgress); return { ...otherResults, ...{ limitHit: otherResults.limitHit || localResults.limitHit }, results: [...otherResults.results, ...arrays.coalesce([...localResults.results.values()])] }; } fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { return this.doSearch(query, token); } private doSearch(query: ISearchQuery, token?: CancellationToken, onProgress?: (item: ISearchProgressItem) => void): Promise<ISearchComplete> { this.logService.trace('SearchService#search', JSON.stringify(query)); const schemesInQuery = this.getSchemesInQuery(query); const providerActivations: Promise<any>[] = [Promise.resolve(null)]; schemesInQuery.forEach(scheme => providerActivations.push(this.extensionService.activateByEvent(`onSearch:${scheme}`))); providerActivations.push(this.extensionService.activateByEvent('onSearch:file')); const providerPromise = Promise.all(providerActivations) .then(() => this.extensionService.whenInstalledExtensionsRegistered()) .then(() => { // Cancel faster if search was canceled while waiting for extensions if (token && token.isCancellationRequested) { return Promise.reject(canceled()); } const progressCallback = (item: ISearchProgressItem) => { if (token && token.isCancellationRequested) { return; } if (onProgress) { onProgress(item); } }; return this.searchWithProviders(query, progressCallback, token); }) .then(completes => { completes = arrays.coalesce(completes); if (!completes.length) { return { limitHit: false, results: [] }; } return <ISearchComplete>{ limitHit: completes[0] && completes[0].limitHit, stats: completes[0].stats, results: arrays.flatten(completes.map((c: ISearchComplete) => c.results)) }; }); return new Promise((resolve, reject) => { if (token) { token.onCancellationRequested(() => { reject(canceled()); }); } providerPromise.then(resolve, reject); }); } private getSchemesInQuery(query: ISearchQuery): Set<string> { const schemes = new Set<string>(); if (query.folderQueries) { query.folderQueries.forEach(fq => schemes.add(fq.folder.scheme)); } if (query.extraFileResources) { query.extraFileResources.forEach(extraFile => schemes.add(extraFile.scheme)); } return schemes; } private async waitForProvider(queryType: QueryType, scheme: string): Promise<ISearchResultProvider> { let deferredMap: Map<string, DeferredPromise<ISearchResultProvider>> = queryType === QueryType.File ? this.deferredFileSearchesByScheme : this.deferredTextSearchesByScheme; if (deferredMap.has(scheme)) { return deferredMap.get(scheme)!.p; } else { const deferred = new DeferredPromise<ISearchResultProvider>(); deferredMap.set(scheme, deferred); return deferred.p; } } private async searchWithProviders(query: ISearchQuery, onProviderProgress: (progress: ISearchProgressItem) => void, token?: CancellationToken) { const e2eSW = StopWatch.create(false); const diskSearchQueries: IFolderQuery[] = []; const searchPs: Promise<ISearchComplete>[] = []; const fqs = this.groupFolderQueriesByScheme(query); await Promise.all(keys(fqs).map(async scheme => { const schemeFQs = fqs.get(scheme)!; let provider = query.type === QueryType.File ? this.fileSearchProviders.get(scheme) : this.textSearchProviders.get(scheme); if (!provider && scheme === Schemas.file) { diskSearchQueries.push(...schemeFQs); } else { if (!provider) { if (scheme !== Schemas.vscodeRemote) { console.warn(`No search provider registered for scheme: ${scheme}`); return; } console.warn(`No search provider registered for scheme: ${scheme}, waiting`); provider = await this.waitForProvider(query.type, scheme); } const oneSchemeQuery: ISearchQuery = { ...query, ...{ folderQueries: schemeFQs } }; searchPs.push(query.type === QueryType.File ? provider.fileSearch(<IFileQuery>oneSchemeQuery, token) : provider.textSearch(<ITextQuery>oneSchemeQuery, onProviderProgress, token)); } })); const diskSearchExtraFileResources = query.extraFileResources && query.extraFileResources.filter(res => res.scheme === Schemas.file); if (diskSearchQueries.length || diskSearchExtraFileResources) { const diskSearchQuery: ISearchQuery = { ...query, ...{ folderQueries: diskSearchQueries }, extraFileResources: diskSearchExtraFileResources }; if (this.diskSearch) { searchPs.push(diskSearchQuery.type === QueryType.File ? this.diskSearch.fileSearch(diskSearchQuery, token) : this.diskSearch.textSearch(diskSearchQuery, onProviderProgress, token)); } } return Promise.all(searchPs).then(completes => { const endToEndTime = e2eSW.elapsed(); this.logService.trace(`SearchService#search: ${endToEndTime}ms`); completes.forEach(complete => { this.sendTelemetry(query, endToEndTime, complete); }); return completes; }, err => { const endToEndTime = e2eSW.elapsed(); this.logService.trace(`SearchService#search: ${endToEndTime}ms`); const searchError = deserializeSearchError(err.message); this.sendTelemetry(query, endToEndTime, undefined, searchError); throw searchError; }); } private groupFolderQueriesByScheme(query: ISearchQuery): Map<string, IFolderQuery[]> { const queries = new Map<string, IFolderQuery[]>(); query.folderQueries.forEach(fq => { const schemeFQs = queries.get(fq.folder.scheme) || []; schemeFQs.push(fq); queries.set(fq.folder.scheme, schemeFQs); }); return queries; } private sendTelemetry(query: ISearchQuery, endToEndTime: number, complete?: ISearchComplete, err?: SearchError): void { const fileSchemeOnly = query.folderQueries.every(fq => fq.folder.scheme === 'file'); const otherSchemeOnly = query.folderQueries.every(fq => fq.folder.scheme !== 'file'); const scheme = fileSchemeOnly ? 'file' : otherSchemeOnly ? 'other' : 'mixed'; if (query.type === QueryType.File && complete && complete.stats) { const fileSearchStats = complete.stats as IFileSearchStats; if (fileSearchStats.fromCache) { const cacheStats: ICachedSearchStats = fileSearchStats.detailStats as ICachedSearchStats; type CachedSearchCompleteClassifcation = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; resultCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; type: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; sortingTime?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheWasResolved: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; cacheLookupTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheFilterTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheEntryCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type CachedSearchCompleteEvent = { reason?: string; resultCount: number; workspaceFolderCount: number; type: 'fileSearchProvider' | 'searchProcess'; endToEndTime: number; sortingTime?: number; cacheWasResolved: boolean; cacheLookupTime: number; cacheFilterTime: number; cacheEntryCount: number; scheme: string; }; this.telemetryService.publicLog2<CachedSearchCompleteEvent, CachedSearchCompleteClassifcation>('cachedSearchComplete', { reason: query._reason, resultCount: fileSearchStats.resultCount, workspaceFolderCount: query.folderQueries.length, type: fileSearchStats.type, endToEndTime: endToEndTime, sortingTime: fileSearchStats.sortingTime, cacheWasResolved: cacheStats.cacheWasResolved, cacheLookupTime: cacheStats.cacheLookupTime, cacheFilterTime: cacheStats.cacheFilterTime, cacheEntryCount: cacheStats.cacheEntryCount, scheme }); } else { const searchEngineStats: ISearchEngineStats = fileSearchStats.detailStats as ISearchEngineStats; type SearchCompleteClassification = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; resultCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; type: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; sortingTime?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; fileWalkTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; directoriesWalked: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; filesWalked: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cmdTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cmdResultCount?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type SearchCompleteEvent = { reason?: string; resultCount: number; workspaceFolderCount: number; type: 'fileSearchProvider' | 'searchProcess'; endToEndTime: number; sortingTime?: number; fileWalkTime: number directoriesWalked: number; filesWalked: number; cmdTime: number; cmdResultCount?: number; scheme: string; }; this.telemetryService.publicLog2<SearchCompleteEvent, SearchCompleteClassification>('searchComplete', { reason: query._reason, resultCount: fileSearchStats.resultCount, workspaceFolderCount: query.folderQueries.length, type: fileSearchStats.type, endToEndTime: endToEndTime, sortingTime: fileSearchStats.sortingTime, fileWalkTime: searchEngineStats.fileWalkTime, directoriesWalked: searchEngineStats.directoriesWalked, filesWalked: searchEngineStats.filesWalked, cmdTime: searchEngineStats.cmdTime, cmdResultCount: searchEngineStats.cmdResultCount, scheme }); } } else if (query.type === QueryType.Text) { let errorType: string | undefined; if (err) { errorType = err.code === SearchErrorCode.regexParseError ? 'regex' : err.code === SearchErrorCode.unknownEncoding ? 'encoding' : err.code === SearchErrorCode.globParseError ? 'glob' : err.code === SearchErrorCode.invalidLiteral ? 'literal' : err.code === SearchErrorCode.other ? 'other' : 'unknown'; } type TextSearchCompleteClassification = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; error?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; usePCRE2: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type TextSearchCompleteEvent = { reason?: string; workspaceFolderCount: number; endToEndTime: number; scheme: string; error?: string; usePCRE2: boolean; }; this.telemetryService.publicLog2<TextSearchCompleteEvent, TextSearchCompleteClassification>('textSearchComplete', { reason: query._reason, workspaceFolderCount: query.folderQueries.length, endToEndTime: endToEndTime, scheme, error: errorType, usePCRE2: !!query.usePCRE2 }); } } private getLocalResults(query: ITextQuery): { results: ResourceMap<IFileMatch | null>; limitHit: boolean } { const localResults = new ResourceMap<IFileMatch | null>(); let limitHit = false; if (query.type === QueryType.Text) { const models = this.modelService.getModels(); models.forEach((model) => { const resource = model.uri; if (!resource) { return; } if (limitHit) { return; } // Skip files that are not opened as text file if (!this.editorService.isOpen({ resource })) { return; } // Skip search results if (model.getModeId() === 'search-result' && !(query.includePattern && query.includePattern['**/*.code-search'])) { // TODO: untitled search editors will be excluded from search even when include *.code-search is specified return; } // Block walkthrough, webview, etc. if (resource.scheme !== Schemas.untitled && !this.fileService.canHandleResource(resource)) { return; } // Exclude files from the git FileSystemProvider, e.g. to prevent open staged files from showing in search results if (resource.scheme === 'git') { return; } if (!this.matches(resource, query)) { return; // respect user filters } // Use editor API to find matches const askMax = typeof query.maxResults === 'number' ? query.maxResults + 1 : undefined; let matches = model.findMatches(query.contentPattern.pattern, false, !!query.contentPattern.isRegExp, !!query.contentPattern.isCaseSensitive, query.contentPattern.isWordMatch ? query.contentPattern.wordSeparators! : null, false, askMax); if (matches.length) { if (askMax && matches.length >= askMax) { limitHit = true; matches = matches.slice(0, askMax - 1); } const fileMatch = new FileMatch(resource); localResults.set(resource, fileMatch); const textSearchResults = editorMatchesToTextSearchResults(matches, model, query.previewOptions); fileMatch.results = addContextToEditorMatches(textSearchResults, model, query); } else { localResults.set(resource, null); } }); } return { results: localResults, limitHit }; } private matches(resource: uri, query: ITextQuery): boolean { return pathIncludedInQuery(query, resource.fsPath); } clearCache(cacheKey: string): Promise<void> { const clearPs = [ this.diskSearch, ...values(this.fileSearchProviders) ].map(provider => provider && provider.clearCache(cacheKey)); return Promise.all(clearPs) .then(() => { }); } } export class RemoteSearchService extends SearchService { constructor( @IModelService modelService: IModelService, @IEditorService editorService: IEditorService, @ITelemetryService telemetryService: ITelemetryService, @ILogService logService: ILogService, @IExtensionService extensionService: IExtensionService, @IFileService fileService: IFileService ) { super(modelService, editorService, telemetryService, logService, extensionService, fileService); } } registerSingleton(ISearchService, RemoteSearchService, true);
src/vs/workbench/services/search/common/searchService.ts
1
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.0023121170233935118, 0.0002572100202087313, 0.00016114611935336143, 0.00017234333790838718, 0.00032324958010576665 ]
{ "id": 7, "code_window": [ "\t\tsearchDebug: IDebugParams | undefined,\n", "\t\t@ILogService private readonly logService: ILogService,\n", "\t\t@IConfigurationService private readonly configService: IConfigurationService,\n", "\t\t@IFileService private readonly fileService: IFileService\n", "\t) {\n", "\t\tconst timeout = this.configService.getValue<ISearchConfiguration>().search.maintainFileSearchCache ?\n", "\t\t\tNumber.MAX_VALUE :\n", "\t\t\t60 * 60 * 1000;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 53 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { VIEWLET_ID, IExtensionsViewPaneContainer } from 'vs/workbench/contrib/extensions/common/extensions'; export function showExtensionQuery(viewletService: IViewletService, query: string) { return viewletService.openViewlet(VIEWLET_ID, true).then(viewlet => { if (viewlet) { (viewlet?.getViewPaneContainer() as IExtensionsViewPaneContainer).search(query); } }); }
src/vs/workbench/contrib/format/browser/showExtensionQuery.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00017335840675514191, 0.00016710947966203094, 0.00016086055256891996, 0.00016710947966203094, 0.000006248927093110979 ]
{ "id": 7, "code_window": [ "\t\tsearchDebug: IDebugParams | undefined,\n", "\t\t@ILogService private readonly logService: ILogService,\n", "\t\t@IConfigurationService private readonly configService: IConfigurationService,\n", "\t\t@IFileService private readonly fileService: IFileService\n", "\t) {\n", "\t\tconst timeout = this.configService.getValue<ISearchConfiguration>().search.maintainFileSearchCache ?\n", "\t\t\tNumber.MAX_VALUE :\n", "\t\t\t60 * 60 * 1000;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 53 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Emitter } from 'vs/base/common/event'; import { NotebookDocumentMetadata } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { NotebookLayoutChangeEvent, NotebookLayoutInfo, CellViewModelStateChangeEvent, ICellViewModel } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; export enum NotebookViewEventType { LayoutChanged = 1, MetadataChanged = 2, CellStateChanged = 3 } export class NotebookLayoutChangedEvent { public readonly type = NotebookViewEventType.LayoutChanged; constructor(readonly source: NotebookLayoutChangeEvent, readonly value: NotebookLayoutInfo) { } } export class NotebookMetadataChangedEvent { public readonly type = NotebookViewEventType.MetadataChanged; constructor(readonly source: NotebookDocumentMetadata) { } } export class NotebookCellStateChangedEvent { public readonly type = NotebookViewEventType.CellStateChanged; constructor(readonly source: CellViewModelStateChangeEvent, readonly cell: ICellViewModel) { } } export type NotebookViewEvent = NotebookLayoutChangedEvent | NotebookMetadataChangedEvent | NotebookCellStateChangedEvent; export class NotebookEventDispatcher { protected readonly _onDidChangeLayout = new Emitter<NotebookLayoutChangedEvent>(); readonly onDidChangeLayout = this._onDidChangeLayout.event; protected readonly _onDidChangeMetadata = new Emitter<NotebookMetadataChangedEvent>(); readonly onDidChangeMetadata = this._onDidChangeMetadata.event; protected readonly _onDidChangeCellState = new Emitter<NotebookCellStateChangedEvent>(); readonly onDidChangeCellState = this._onDidChangeCellState.event; constructor() { } emit(events: NotebookViewEvent[]) { for (let i = 0, len = events.length; i < len; i++) { let e = events[i]; switch (e.type) { case NotebookViewEventType.LayoutChanged: this._onDidChangeLayout.fire(e); break; case NotebookViewEventType.MetadataChanged: this._onDidChangeMetadata.fire(e); break; case NotebookViewEventType.CellStateChanged: this._onDidChangeCellState.fire(e); break; } } } }
src/vs/workbench/contrib/notebook/browser/viewModel/eventDispatcher.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00017783888324629515, 0.00017456270870752633, 0.00017009524162858725, 0.00017426058184355497, 0.000002348069301660871 ]
{ "id": 7, "code_window": [ "\t\tsearchDebug: IDebugParams | undefined,\n", "\t\t@ILogService private readonly logService: ILogService,\n", "\t\t@IConfigurationService private readonly configService: IConfigurationService,\n", "\t\t@IFileService private readonly fileService: IFileService\n", "\t) {\n", "\t\tconst timeout = this.configService.getValue<ISearchConfiguration>().search.maintainFileSearchCache ?\n", "\t\t\tNumber.MAX_VALUE :\n", "\t\t\t60 * 60 * 1000;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 53 }
{ "iconDefinitions": { "_root_folder_dark": { "iconPath": "./images/root-folder-dark.svg" }, "_root_folder_open_dark": { "iconPath": "./images/root-folder-open-dark.svg" }, "_folder_dark": { "iconPath": "./images/folder-dark.svg" }, "_folder_open_dark": { "iconPath": "./images/folder-open-dark.svg" }, "_file_dark": { "iconPath": "./images/document-dark.svg" }, "_root_folder": { "iconPath": "./images/root-folder-light.svg" }, "_root_folder_open": { "iconPath": "./images/root-folder-open-light.svg" }, "_folder_light": { "iconPath": "./images/folder-light.svg" }, "_folder_open_light": { "iconPath": "./images/folder-open-light.svg" }, "_file_light": { "iconPath": "./images/document-light.svg" } }, "folderExpanded": "_folder_open_dark", "folder": "_folder_dark", "file": "_file_dark", "rootFolderExpanded": "_root_folder_open_dark", "rootFolder": "_root_folder_dark", "fileExtensions": { // icons by file extension }, "fileNames": { // icons by file name }, "languageIds": { // icons by language id }, "light": { "folderExpanded": "_folder_open_light", "folder": "_folder_light", "rootFolderExpanded": "_root_folder_open", "rootFolder": "_root_folder", "file": "_file_light", "fileExtensions": { // icons by file extension }, "fileNames": { // icons by file name }, "languageIds": { // icons by language id } }, "highContrast": { // overrides for high contrast } }
extensions/theme-defaults/fileicons/vs_minimal-icon-theme.json
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.0001763513864716515, 0.00017402623780071735, 0.00017254178237635642, 0.00017336402379442006, 0.0000014019532272868673 ]
{ "id": 8, "code_window": [ "\t\tconst channel = getNextTickChannel(client.getChannel('search'));\n", "\t\tthis.raw = new SearchChannelClient(channel);\n", "\t}\n", "\n", "\ttextSearch(query: ITextQuery, onProgress?: (p: ISearchProgressItem) => void, token?: CancellationToken): Promise<ISearchComplete> {\n", "\t\tconst folderQueries = query.folderQueries || [];\n", "\t\treturn Promise.all(folderQueries.map(q => this.fileService.exists(q.folder)))\n", "\t\t\t.then(exists => {\n", "\t\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\t\tthrow canceled();\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tif (token && token.isCancellationRequested) {\n", "\t\t\tthrow canceled();\n", "\t\t}\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 93 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { getPathFromAmdModule } from 'vs/base/common/amd'; import { CancellationToken } from 'vs/base/common/cancellation'; import { canceled } from 'vs/base/common/errors'; import { Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { URI as uri } from 'vs/base/common/uri'; import { getNextTickChannel } from 'vs/base/parts/ipc/common/ipc'; import { Client, IIPCOptions } from 'vs/base/parts/ipc/node/ipc.cp'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IDebugParams, IEnvironmentService } from 'vs/platform/environment/common/environment'; import { parseSearchPort, INativeEnvironmentService } from 'vs/platform/environment/node/environmentService'; import { IFileService } from 'vs/platform/files/common/files'; import { ILogService } from 'vs/platform/log/common/log'; import { FileMatch, IFileMatch, IFileQuery, IProgressMessage, IRawSearchService, ISearchComplete, ISearchConfiguration, ISearchProgressItem, ISearchResultProvider, ISerializedFileMatch, ISerializedSearchComplete, ISerializedSearchProgressItem, isSerializedSearchComplete, isSerializedSearchSuccess, ITextQuery, ISearchService, isFileMatch } from 'vs/workbench/services/search/common/search'; import { SearchChannelClient } from './searchIpc'; import { SearchService } from 'vs/workbench/services/search/common/searchService'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; export class LocalSearchService extends SearchService { constructor( @IModelService modelService: IModelService, @IEditorService editorService: IEditorService, @ITelemetryService telemetryService: ITelemetryService, @ILogService logService: ILogService, @IExtensionService extensionService: IExtensionService, @IFileService fileService: IFileService, @IEnvironmentService readonly environmentService: INativeEnvironmentService, @IInstantiationService readonly instantiationService: IInstantiationService ) { super(modelService, editorService, telemetryService, logService, extensionService, fileService); this.diskSearch = instantiationService.createInstance(DiskSearch, !environmentService.isBuilt || environmentService.verbose, parseSearchPort(environmentService.args, environmentService.isBuilt)); } } export class DiskSearch implements ISearchResultProvider { private raw: IRawSearchService; constructor( verboseLogging: boolean, searchDebug: IDebugParams | undefined, @ILogService private readonly logService: ILogService, @IConfigurationService private readonly configService: IConfigurationService, @IFileService private readonly fileService: IFileService ) { const timeout = this.configService.getValue<ISearchConfiguration>().search.maintainFileSearchCache ? Number.MAX_VALUE : 60 * 60 * 1000; const opts: IIPCOptions = { serverName: 'Search', timeout, args: ['--type=searchService'], // See https://github.com/Microsoft/vscode/issues/27665 // Pass in fresh execArgv to the forked process such that it doesn't inherit them from `process.execArgv`. // e.g. Launching the extension host process with `--inspect-brk=xxx` and then forking a process from the extension host // results in the forked process inheriting `--inspect-brk=xxx`. freshExecArgv: true, env: { AMD_ENTRYPOINT: 'vs/workbench/services/search/node/searchApp', PIPE_LOGGING: 'true', VERBOSE_LOGGING: verboseLogging }, useQueue: true }; if (searchDebug) { if (searchDebug.break && searchDebug.port) { opts.debugBrk = searchDebug.port; } else if (!searchDebug.break && searchDebug.port) { opts.debug = searchDebug.port; } } const client = new Client( getPathFromAmdModule(require, 'bootstrap-fork'), opts); const channel = getNextTickChannel(client.getChannel('search')); this.raw = new SearchChannelClient(channel); } textSearch(query: ITextQuery, onProgress?: (p: ISearchProgressItem) => void, token?: CancellationToken): Promise<ISearchComplete> { const folderQueries = query.folderQueries || []; return Promise.all(folderQueries.map(q => this.fileService.exists(q.folder))) .then(exists => { if (token && token.isCancellationRequested) { throw canceled(); } query.folderQueries = folderQueries.filter((q, index) => exists[index]); const event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete> = this.raw.textSearch(query); return DiskSearch.collectResultsFromEvent(event, onProgress, token); }); } fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { const folderQueries = query.folderQueries || []; return Promise.all(folderQueries.map(q => this.fileService.exists(q.folder))) .then(exists => { if (token && token.isCancellationRequested) { throw canceled(); } query.folderQueries = folderQueries.filter((q, index) => exists[index]); let event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete>; event = this.raw.fileSearch(query); const onProgress = (p: ISearchProgressItem) => { if (!isFileMatch(p)) { // Should only be for logs this.logService.debug('SearchService#search', p.message); } }; return DiskSearch.collectResultsFromEvent(event, onProgress, token); }); } /** * Public for test */ static collectResultsFromEvent(event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete>, onProgress?: (p: ISearchProgressItem) => void, token?: CancellationToken): Promise<ISearchComplete> { let result: IFileMatch[] = []; let listener: IDisposable; return new Promise<ISearchComplete>((c, e) => { if (token) { token.onCancellationRequested(() => { if (listener) { listener.dispose(); } e(canceled()); }); } listener = event(ev => { if (isSerializedSearchComplete(ev)) { if (isSerializedSearchSuccess(ev)) { c({ limitHit: ev.limitHit, results: result, stats: ev.stats }); } else { e(ev.error); } listener.dispose(); } else { // Matches if (Array.isArray(ev)) { const fileMatches = ev.map(d => this.createFileMatch(d)); result = result.concat(fileMatches); if (onProgress) { fileMatches.forEach(onProgress); } } // Match else if ((<ISerializedFileMatch>ev).path) { const fileMatch = this.createFileMatch(<ISerializedFileMatch>ev); result.push(fileMatch); if (onProgress) { onProgress(fileMatch); } } // Progress else if (onProgress) { onProgress(<IProgressMessage>ev); } } }); }); } private static createFileMatch(data: ISerializedFileMatch): FileMatch { const fileMatch = new FileMatch(uri.file(data.path)); if (data.results) { // const matches = data.results.filter(resultIsMatch); fileMatch.results.push(...data.results); } return fileMatch; } clearCache(cacheKey: string): Promise<void> { return this.raw.clearCache(cacheKey); } } registerSingleton(ISearchService, LocalSearchService, true);
src/vs/workbench/services/search/node/searchService.ts
1
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.9985175728797913, 0.15020963549613953, 0.00016445291112177074, 0.00017294516146648675, 0.3474630117416382 ]
{ "id": 8, "code_window": [ "\t\tconst channel = getNextTickChannel(client.getChannel('search'));\n", "\t\tthis.raw = new SearchChannelClient(channel);\n", "\t}\n", "\n", "\ttextSearch(query: ITextQuery, onProgress?: (p: ISearchProgressItem) => void, token?: CancellationToken): Promise<ISearchComplete> {\n", "\t\tconst folderQueries = query.folderQueries || [];\n", "\t\treturn Promise.all(folderQueries.map(q => this.fileService.exists(q.folder)))\n", "\t\t\t.then(exists => {\n", "\t\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\t\tthrow canceled();\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tif (token && token.isCancellationRequested) {\n", "\t\t\tthrow canceled();\n", "\t\t}\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 93 }
/*--------------------------------------------------------------------------------------------- * 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 { IKeyMods, IQuickInputService } from 'vs/platform/quickinput/common/quickInput'; import { IEditor } from 'vs/editor/common/editorCommon'; import { IEditorService, SIDE_GROUP } from 'vs/workbench/services/editor/common/editorService'; import { IRange } from 'vs/editor/common/core/range'; import { AbstractGotoLineQuickAccessProvider } from 'vs/editor/contrib/quickAccess/gotoLineQuickAccess'; import { Registry } from 'vs/platform/registry/common/platform'; import { IQuickAccessRegistry, Extensions as QuickaccesExtensions } from 'vs/platform/quickinput/common/quickAccess'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IWorkbenchEditorConfiguration } from 'vs/workbench/common/editor'; import { Action } from 'vs/base/common/actions'; import { IWorkbenchActionRegistry, Extensions as ActionExtensions } from 'vs/workbench/common/actions'; import { SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import { KeyMod, KeyCode } from 'vs/base/common/keyCodes'; export class GotoLineQuickAccessProvider extends AbstractGotoLineQuickAccessProvider { protected readonly onDidActiveTextEditorControlChange = this.editorService.onDidActiveEditorChange; constructor( @IEditorService private readonly editorService: IEditorService, @IConfigurationService private readonly configurationService: IConfigurationService ) { super(); } private get configuration() { const editorConfig = this.configurationService.getValue<IWorkbenchEditorConfiguration>().workbench.editor; return { openEditorPinned: !editorConfig.enablePreviewFromQuickOpen, }; } protected get activeTextEditorControl() { return this.editorService.activeTextEditorControl; } protected gotoLocation(editor: IEditor, options: { range: IRange, keyMods: IKeyMods, forceSideBySide?: boolean, preserveFocus?: boolean }): void { // Check for sideBySide use if ((options.keyMods.ctrlCmd || options.forceSideBySide) && this.editorService.activeEditor) { this.editorService.openEditor(this.editorService.activeEditor, { selection: options.range, pinned: options.keyMods.alt || this.configuration.openEditorPinned, preserveFocus: options.preserveFocus }, SIDE_GROUP); } // Otherwise let parent handle it else { super.gotoLocation(editor, options); } } } Registry.as<IQuickAccessRegistry>(QuickaccesExtensions.Quickaccess).registerQuickAccessProvider({ ctor: GotoLineQuickAccessProvider, prefix: AbstractGotoLineQuickAccessProvider.PREFIX, placeholder: localize('gotoLineQuickAccessPlaceholder', "Type the line number and optional column to go to (e.g. 42:5 for line 42 and column 5)."), helpEntries: [{ description: localize('gotoLineQuickAccess', "Go to Line/Column"), needsEditor: true }] }); export class GotoLineAction extends Action { static readonly ID = 'workbench.action.gotoLine'; static readonly LABEL = localize('gotoLine', "Go to Line/Column..."); constructor( id: string, label: string, @IQuickInputService private readonly quickInputService: IQuickInputService ) { super(id, label); } async run(): Promise<void> { this.quickInputService.quickAccess.show(GotoLineQuickAccessProvider.PREFIX); } } Registry.as<IWorkbenchActionRegistry>(ActionExtensions.WorkbenchActions).registerWorkbenchAction(SyncActionDescriptor.from(GotoLineAction, { primary: KeyMod.CtrlCmd | KeyCode.KEY_G, mac: { primary: KeyMod.WinCtrl | KeyCode.KEY_G } }), 'Go to Line/Column...');
src/vs/workbench/contrib/codeEditor/browser/quickaccess/gotoLineQuickAccess.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.0001748790091369301, 0.00017071377078536898, 0.00016429193783551455, 0.00017122017743531615, 0.0000034468639569240622 ]
{ "id": 8, "code_window": [ "\t\tconst channel = getNextTickChannel(client.getChannel('search'));\n", "\t\tthis.raw = new SearchChannelClient(channel);\n", "\t}\n", "\n", "\ttextSearch(query: ITextQuery, onProgress?: (p: ISearchProgressItem) => void, token?: CancellationToken): Promise<ISearchComplete> {\n", "\t\tconst folderQueries = query.folderQueries || [];\n", "\t\treturn Promise.all(folderQueries.map(q => this.fileService.exists(q.folder)))\n", "\t\t\t.then(exists => {\n", "\t\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\t\tthrow canceled();\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tif (token && token.isCancellationRequested) {\n", "\t\t\tthrow canceled();\n", "\t\t}\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 93 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /* Container */ .monaco-workbench .part.editor > .content .editor-group-container { height: 100%; } .monaco-workbench .part.editor > .content .editor-group-container.empty { opacity: 0.5; /* dimmed to indicate inactive state */ } .monaco-workbench .part.editor > .content .editor-group-container.empty.active, .monaco-workbench .part.editor > .content .editor-group-container.empty.dragged-over { opacity: 1; /* indicate active/dragged-over group through undimmed state */ } /* Letterpress */ .monaco-workbench .part.editor > .content .editor-group-container > .editor-group-letterpress { display: none; /* only visible when empty */ } .monaco-workbench .part.editor > .content .editor-group-container.empty > .editor-group-letterpress { display: block; margin: auto; width: 100%; height: calc(100% - 70px); /* centered below toolbar */ max-width: 260px; background-repeat: no-repeat; background-position: 50% 50%; background-size: 70% 70%; } .monaco-workbench .part.editor > .content.empty .editor-group-container.empty > .editor-group-letterpress { background-size: 100% 100%; /* larger for empty editor part */ height: 100%; /* no toolbar in this case */ } /* Title */ .monaco-workbench .part.editor > .content .editor-group-container > .title { position: relative; box-sizing: border-box; overflow: hidden; } .monaco-workbench .part.editor > .content .editor-group-container > .title:not(.tabs) { display: flex; /* when tabs are not shown, use flex layout */ flex-wrap: nowrap; } .monaco-workbench .part.editor > .content .editor-group-container > .title.title-border-bottom::after { content: ''; position: absolute; bottom: 0; left: 0; z-index: 5; pointer-events: none; background-color: var(--title-border-bottom-color); width: 100%; height: 1px; } .monaco-workbench .part.editor > .content .editor-group-container.empty > .title { display: none; } /* Toolbar */ .monaco-workbench .part.editor > .content .editor-group-container > .editor-group-container-toolbar { display: none; } .monaco-workbench .part.editor > .content:not(.empty) .editor-group-container.empty > .editor-group-container-toolbar { display: block; } .monaco-workbench .part.editor > .content .editor-group-container > .editor-group-container-toolbar .action-label { display: block; height: 35px; line-height: 35px; min-width: 28px; background-size: 16px; background-position: center center; background-repeat: no-repeat; } /* Editor */ .monaco-workbench .part.editor > .content .editor-group-container.empty > .editor-container { display: none; } .monaco-workbench .part.editor > .content .editor-group-container > .editor-container > .editor-instance { height: 100%; } .monaco-workbench .part.editor > .content .grid-view-container { width: 100%; height: 100%; }
src/vs/workbench/browser/parts/editor/media/editorgroupview.css
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.0001748388312989846, 0.00017309401300735772, 0.0001716286496957764, 0.00017310914699919522, 8.37345226045727e-7 ]
{ "id": 8, "code_window": [ "\t\tconst channel = getNextTickChannel(client.getChannel('search'));\n", "\t\tthis.raw = new SearchChannelClient(channel);\n", "\t}\n", "\n", "\ttextSearch(query: ITextQuery, onProgress?: (p: ISearchProgressItem) => void, token?: CancellationToken): Promise<ISearchComplete> {\n", "\t\tconst folderQueries = query.folderQueries || [];\n", "\t\treturn Promise.all(folderQueries.map(q => this.fileService.exists(q.folder)))\n", "\t\t\t.then(exists => {\n", "\t\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\t\tthrow canceled();\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tif (token && token.isCancellationRequested) {\n", "\t\t\tthrow canceled();\n", "\t\t}\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 93 }
#!/bin/bash function get_total_cpu_time() { # Read the first line of /proc/stat and remove the cpu prefix CPU=(`sed -n 's/^cpu\s//p' /proc/stat`) # Sum all of the values in CPU to get total time for VALUE in "${CPU[@]}"; do let $1=$1+$VALUE done } TOTAL_TIME_BEFORE=0 get_total_cpu_time TOTAL_TIME_BEFORE # Loop over the arguments, which are a list of PIDs # The 13th and 14th words in /proc/<PID>/stat are the user and system time # the process has used, so sum these to get total process run time declare -a PROCESS_BEFORE_TIMES ITER=0 for PID in "$@"; do if [ -f /proc/$PID/stat ] then PROCESS_STATS=`cat /proc/$PID/stat` PROCESS_STAT_ARRAY=($PROCESS_STATS) let PROCESS_TIME_BEFORE="${PROCESS_STAT_ARRAY[13]}+${PROCESS_STAT_ARRAY[14]}" else let PROCESS_TIME_BEFORE=0 fi PROCESS_BEFORE_TIMES[$ITER]=$PROCESS_TIME_BEFORE ((++ITER)) done # Wait for a second sleep 1 TOTAL_TIME_AFTER=0 get_total_cpu_time TOTAL_TIME_AFTER # Check the user and system time sum of each process again and compute the change # in process time used over total system time ITER=0 for PID in "$@"; do if [ -f /proc/$PID/stat ] then PROCESS_STATS=`cat /proc/$PID/stat` PROCESS_STAT_ARRAY=($PROCESS_STATS) let PROCESS_TIME_AFTER="${PROCESS_STAT_ARRAY[13]}+${PROCESS_STAT_ARRAY[14]}" else let PROCESS_TIME_AFTER=${PROCESS_BEFORE_TIMES[$ITER]} fi PROCESS_TIME_BEFORE=${PROCESS_BEFORE_TIMES[$ITER]} let PROCESS_DELTA=$PROCESS_TIME_AFTER-$PROCESS_TIME_BEFORE let TOTAL_DELTA=$TOTAL_TIME_AFTER-$TOTAL_TIME_BEFORE CPU_USAGE=`echo "$((100*$PROCESS_DELTA/$TOTAL_DELTA))"` # Parent script reads from stdout, so echo result to be read echo $CPU_USAGE ((++ITER)) done
src/vs/base/node/cpuUsage.sh
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.0001725814217934385, 0.00016864234930835664, 0.00016505050007253885, 0.000169097664183937, 0.0000024684359232196584 ]
{ "id": 9, "code_window": [ "\n", "\t\t\t\tquery.folderQueries = folderQueries.filter((q, index) => exists[index]);\n", "\t\t\t\tconst event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete> = this.raw.textSearch(query);\n", "\n" ], "labels": [ "keep", "replace", "replace", "keep" ], "after_edit": [ "\t\tconst event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete> = this.raw.textSearch(query);\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 100 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as arrays from 'vs/base/common/arrays'; import { CancellationToken } from 'vs/base/common/cancellation'; import { canceled } from 'vs/base/common/errors'; import { Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { keys, ResourceMap, values } from 'vs/base/common/map'; import { Schemas } from 'vs/base/common/network'; import { StopWatch } from 'vs/base/common/stopwatch'; import { URI as uri } from 'vs/base/common/uri'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IFileService } from 'vs/platform/files/common/files'; import { ILogService } from 'vs/platform/log/common/log'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { deserializeSearchError, FileMatch, ICachedSearchStats, IFileMatch, IFileQuery, IFileSearchStats, IFolderQuery, IProgressMessage, ISearchComplete, ISearchEngineStats, ISearchProgressItem, ISearchQuery, ISearchResultProvider, ISearchService, ITextQuery, pathIncludedInQuery, QueryType, SearchError, SearchErrorCode, SearchProviderType, isFileMatch, isProgressMessage } from 'vs/workbench/services/search/common/search'; import { addContextToEditorMatches, editorMatchesToTextSearchResults } from 'vs/workbench/services/search/common/searchHelpers'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { DeferredPromise } from 'vs/base/test/common/utils'; export class SearchService extends Disposable implements ISearchService { _serviceBrand: undefined; protected diskSearch: ISearchResultProvider | null = null; private readonly fileSearchProviders = new Map<string, ISearchResultProvider>(); private readonly textSearchProviders = new Map<string, ISearchResultProvider>(); private deferredFileSearchesByScheme = new Map<string, DeferredPromise<ISearchResultProvider>>(); private deferredTextSearchesByScheme = new Map<string, DeferredPromise<ISearchResultProvider>>(); constructor( private readonly modelService: IModelService, private readonly editorService: IEditorService, private readonly telemetryService: ITelemetryService, private readonly logService: ILogService, private readonly extensionService: IExtensionService, private readonly fileService: IFileService ) { super(); } registerSearchResultProvider(scheme: string, type: SearchProviderType, provider: ISearchResultProvider): IDisposable { let list: Map<string, ISearchResultProvider>; let deferredMap: Map<string, DeferredPromise<ISearchResultProvider>>; if (type === SearchProviderType.file) { list = this.fileSearchProviders; deferredMap = this.deferredFileSearchesByScheme; } else if (type === SearchProviderType.text) { list = this.textSearchProviders; deferredMap = this.deferredTextSearchesByScheme; } else { throw new Error('Unknown SearchProviderType'); } list.set(scheme, provider); if (deferredMap.has(scheme)) { deferredMap.get(scheme)!.complete(provider); deferredMap.delete(scheme); } return toDisposable(() => { list.delete(scheme); }); } async textSearch(query: ITextQuery, token?: CancellationToken, onProgress?: (item: ISearchProgressItem) => void): Promise<ISearchComplete> { // Get local results from dirty/untitled const localResults = this.getLocalResults(query); if (onProgress) { arrays.coalesce([...localResults.results.values()]).forEach(onProgress); } const onProviderProgress = (progress: ISearchProgressItem) => { if (isFileMatch(progress)) { // Match if (!localResults.results.has(progress.resource) && onProgress) { // don't override local results onProgress(progress); } } else if (onProgress) { // Progress onProgress(<IProgressMessage>progress); } if (isProgressMessage(progress)) { this.logService.debug('SearchService#search', progress.message); } }; const otherResults = await this.doSearch(query, token, onProviderProgress); return { ...otherResults, ...{ limitHit: otherResults.limitHit || localResults.limitHit }, results: [...otherResults.results, ...arrays.coalesce([...localResults.results.values()])] }; } fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { return this.doSearch(query, token); } private doSearch(query: ISearchQuery, token?: CancellationToken, onProgress?: (item: ISearchProgressItem) => void): Promise<ISearchComplete> { this.logService.trace('SearchService#search', JSON.stringify(query)); const schemesInQuery = this.getSchemesInQuery(query); const providerActivations: Promise<any>[] = [Promise.resolve(null)]; schemesInQuery.forEach(scheme => providerActivations.push(this.extensionService.activateByEvent(`onSearch:${scheme}`))); providerActivations.push(this.extensionService.activateByEvent('onSearch:file')); const providerPromise = Promise.all(providerActivations) .then(() => this.extensionService.whenInstalledExtensionsRegistered()) .then(() => { // Cancel faster if search was canceled while waiting for extensions if (token && token.isCancellationRequested) { return Promise.reject(canceled()); } const progressCallback = (item: ISearchProgressItem) => { if (token && token.isCancellationRequested) { return; } if (onProgress) { onProgress(item); } }; return this.searchWithProviders(query, progressCallback, token); }) .then(completes => { completes = arrays.coalesce(completes); if (!completes.length) { return { limitHit: false, results: [] }; } return <ISearchComplete>{ limitHit: completes[0] && completes[0].limitHit, stats: completes[0].stats, results: arrays.flatten(completes.map((c: ISearchComplete) => c.results)) }; }); return new Promise((resolve, reject) => { if (token) { token.onCancellationRequested(() => { reject(canceled()); }); } providerPromise.then(resolve, reject); }); } private getSchemesInQuery(query: ISearchQuery): Set<string> { const schemes = new Set<string>(); if (query.folderQueries) { query.folderQueries.forEach(fq => schemes.add(fq.folder.scheme)); } if (query.extraFileResources) { query.extraFileResources.forEach(extraFile => schemes.add(extraFile.scheme)); } return schemes; } private async waitForProvider(queryType: QueryType, scheme: string): Promise<ISearchResultProvider> { let deferredMap: Map<string, DeferredPromise<ISearchResultProvider>> = queryType === QueryType.File ? this.deferredFileSearchesByScheme : this.deferredTextSearchesByScheme; if (deferredMap.has(scheme)) { return deferredMap.get(scheme)!.p; } else { const deferred = new DeferredPromise<ISearchResultProvider>(); deferredMap.set(scheme, deferred); return deferred.p; } } private async searchWithProviders(query: ISearchQuery, onProviderProgress: (progress: ISearchProgressItem) => void, token?: CancellationToken) { const e2eSW = StopWatch.create(false); const diskSearchQueries: IFolderQuery[] = []; const searchPs: Promise<ISearchComplete>[] = []; const fqs = this.groupFolderQueriesByScheme(query); await Promise.all(keys(fqs).map(async scheme => { const schemeFQs = fqs.get(scheme)!; let provider = query.type === QueryType.File ? this.fileSearchProviders.get(scheme) : this.textSearchProviders.get(scheme); if (!provider && scheme === Schemas.file) { diskSearchQueries.push(...schemeFQs); } else { if (!provider) { if (scheme !== Schemas.vscodeRemote) { console.warn(`No search provider registered for scheme: ${scheme}`); return; } console.warn(`No search provider registered for scheme: ${scheme}, waiting`); provider = await this.waitForProvider(query.type, scheme); } const oneSchemeQuery: ISearchQuery = { ...query, ...{ folderQueries: schemeFQs } }; searchPs.push(query.type === QueryType.File ? provider.fileSearch(<IFileQuery>oneSchemeQuery, token) : provider.textSearch(<ITextQuery>oneSchemeQuery, onProviderProgress, token)); } })); const diskSearchExtraFileResources = query.extraFileResources && query.extraFileResources.filter(res => res.scheme === Schemas.file); if (diskSearchQueries.length || diskSearchExtraFileResources) { const diskSearchQuery: ISearchQuery = { ...query, ...{ folderQueries: diskSearchQueries }, extraFileResources: diskSearchExtraFileResources }; if (this.diskSearch) { searchPs.push(diskSearchQuery.type === QueryType.File ? this.diskSearch.fileSearch(diskSearchQuery, token) : this.diskSearch.textSearch(diskSearchQuery, onProviderProgress, token)); } } return Promise.all(searchPs).then(completes => { const endToEndTime = e2eSW.elapsed(); this.logService.trace(`SearchService#search: ${endToEndTime}ms`); completes.forEach(complete => { this.sendTelemetry(query, endToEndTime, complete); }); return completes; }, err => { const endToEndTime = e2eSW.elapsed(); this.logService.trace(`SearchService#search: ${endToEndTime}ms`); const searchError = deserializeSearchError(err.message); this.sendTelemetry(query, endToEndTime, undefined, searchError); throw searchError; }); } private groupFolderQueriesByScheme(query: ISearchQuery): Map<string, IFolderQuery[]> { const queries = new Map<string, IFolderQuery[]>(); query.folderQueries.forEach(fq => { const schemeFQs = queries.get(fq.folder.scheme) || []; schemeFQs.push(fq); queries.set(fq.folder.scheme, schemeFQs); }); return queries; } private sendTelemetry(query: ISearchQuery, endToEndTime: number, complete?: ISearchComplete, err?: SearchError): void { const fileSchemeOnly = query.folderQueries.every(fq => fq.folder.scheme === 'file'); const otherSchemeOnly = query.folderQueries.every(fq => fq.folder.scheme !== 'file'); const scheme = fileSchemeOnly ? 'file' : otherSchemeOnly ? 'other' : 'mixed'; if (query.type === QueryType.File && complete && complete.stats) { const fileSearchStats = complete.stats as IFileSearchStats; if (fileSearchStats.fromCache) { const cacheStats: ICachedSearchStats = fileSearchStats.detailStats as ICachedSearchStats; type CachedSearchCompleteClassifcation = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; resultCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; type: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; sortingTime?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheWasResolved: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; cacheLookupTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheFilterTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheEntryCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type CachedSearchCompleteEvent = { reason?: string; resultCount: number; workspaceFolderCount: number; type: 'fileSearchProvider' | 'searchProcess'; endToEndTime: number; sortingTime?: number; cacheWasResolved: boolean; cacheLookupTime: number; cacheFilterTime: number; cacheEntryCount: number; scheme: string; }; this.telemetryService.publicLog2<CachedSearchCompleteEvent, CachedSearchCompleteClassifcation>('cachedSearchComplete', { reason: query._reason, resultCount: fileSearchStats.resultCount, workspaceFolderCount: query.folderQueries.length, type: fileSearchStats.type, endToEndTime: endToEndTime, sortingTime: fileSearchStats.sortingTime, cacheWasResolved: cacheStats.cacheWasResolved, cacheLookupTime: cacheStats.cacheLookupTime, cacheFilterTime: cacheStats.cacheFilterTime, cacheEntryCount: cacheStats.cacheEntryCount, scheme }); } else { const searchEngineStats: ISearchEngineStats = fileSearchStats.detailStats as ISearchEngineStats; type SearchCompleteClassification = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; resultCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; type: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; sortingTime?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; fileWalkTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; directoriesWalked: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; filesWalked: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cmdTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cmdResultCount?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type SearchCompleteEvent = { reason?: string; resultCount: number; workspaceFolderCount: number; type: 'fileSearchProvider' | 'searchProcess'; endToEndTime: number; sortingTime?: number; fileWalkTime: number directoriesWalked: number; filesWalked: number; cmdTime: number; cmdResultCount?: number; scheme: string; }; this.telemetryService.publicLog2<SearchCompleteEvent, SearchCompleteClassification>('searchComplete', { reason: query._reason, resultCount: fileSearchStats.resultCount, workspaceFolderCount: query.folderQueries.length, type: fileSearchStats.type, endToEndTime: endToEndTime, sortingTime: fileSearchStats.sortingTime, fileWalkTime: searchEngineStats.fileWalkTime, directoriesWalked: searchEngineStats.directoriesWalked, filesWalked: searchEngineStats.filesWalked, cmdTime: searchEngineStats.cmdTime, cmdResultCount: searchEngineStats.cmdResultCount, scheme }); } } else if (query.type === QueryType.Text) { let errorType: string | undefined; if (err) { errorType = err.code === SearchErrorCode.regexParseError ? 'regex' : err.code === SearchErrorCode.unknownEncoding ? 'encoding' : err.code === SearchErrorCode.globParseError ? 'glob' : err.code === SearchErrorCode.invalidLiteral ? 'literal' : err.code === SearchErrorCode.other ? 'other' : 'unknown'; } type TextSearchCompleteClassification = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; error?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; usePCRE2: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type TextSearchCompleteEvent = { reason?: string; workspaceFolderCount: number; endToEndTime: number; scheme: string; error?: string; usePCRE2: boolean; }; this.telemetryService.publicLog2<TextSearchCompleteEvent, TextSearchCompleteClassification>('textSearchComplete', { reason: query._reason, workspaceFolderCount: query.folderQueries.length, endToEndTime: endToEndTime, scheme, error: errorType, usePCRE2: !!query.usePCRE2 }); } } private getLocalResults(query: ITextQuery): { results: ResourceMap<IFileMatch | null>; limitHit: boolean } { const localResults = new ResourceMap<IFileMatch | null>(); let limitHit = false; if (query.type === QueryType.Text) { const models = this.modelService.getModels(); models.forEach((model) => { const resource = model.uri; if (!resource) { return; } if (limitHit) { return; } // Skip files that are not opened as text file if (!this.editorService.isOpen({ resource })) { return; } // Skip search results if (model.getModeId() === 'search-result' && !(query.includePattern && query.includePattern['**/*.code-search'])) { // TODO: untitled search editors will be excluded from search even when include *.code-search is specified return; } // Block walkthrough, webview, etc. if (resource.scheme !== Schemas.untitled && !this.fileService.canHandleResource(resource)) { return; } // Exclude files from the git FileSystemProvider, e.g. to prevent open staged files from showing in search results if (resource.scheme === 'git') { return; } if (!this.matches(resource, query)) { return; // respect user filters } // Use editor API to find matches const askMax = typeof query.maxResults === 'number' ? query.maxResults + 1 : undefined; let matches = model.findMatches(query.contentPattern.pattern, false, !!query.contentPattern.isRegExp, !!query.contentPattern.isCaseSensitive, query.contentPattern.isWordMatch ? query.contentPattern.wordSeparators! : null, false, askMax); if (matches.length) { if (askMax && matches.length >= askMax) { limitHit = true; matches = matches.slice(0, askMax - 1); } const fileMatch = new FileMatch(resource); localResults.set(resource, fileMatch); const textSearchResults = editorMatchesToTextSearchResults(matches, model, query.previewOptions); fileMatch.results = addContextToEditorMatches(textSearchResults, model, query); } else { localResults.set(resource, null); } }); } return { results: localResults, limitHit }; } private matches(resource: uri, query: ITextQuery): boolean { return pathIncludedInQuery(query, resource.fsPath); } clearCache(cacheKey: string): Promise<void> { const clearPs = [ this.diskSearch, ...values(this.fileSearchProviders) ].map(provider => provider && provider.clearCache(cacheKey)); return Promise.all(clearPs) .then(() => { }); } } export class RemoteSearchService extends SearchService { constructor( @IModelService modelService: IModelService, @IEditorService editorService: IEditorService, @ITelemetryService telemetryService: ITelemetryService, @ILogService logService: ILogService, @IExtensionService extensionService: IExtensionService, @IFileService fileService: IFileService ) { super(modelService, editorService, telemetryService, logService, extensionService, fileService); } } registerSingleton(ISearchService, RemoteSearchService, true);
src/vs/workbench/services/search/common/searchService.ts
1
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.1297459453344345, 0.00664000166580081, 0.0001641104754526168, 0.00018505219486542046, 0.022444335743784904 ]
{ "id": 9, "code_window": [ "\n", "\t\t\t\tquery.folderQueries = folderQueries.filter((q, index) => exists[index]);\n", "\t\t\t\tconst event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete> = this.raw.textSearch(query);\n", "\n" ], "labels": [ "keep", "replace", "replace", "keep" ], "after_edit": [ "\t\tconst event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete> = this.raw.textSearch(query);\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 100 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { ModeServiceImpl } from 'vs/editor/common/services/modeServiceImpl'; import { IModeService } from 'vs/editor/common/services/modeService'; import { MonarchTokenizer } from 'vs/editor/standalone/common/monarch/monarchLexer'; import { compile } from 'vs/editor/standalone/common/monarch/monarchCompile'; import { Token } from 'vs/editor/common/core/token'; import { TokenizationRegistry } from 'vs/editor/common/modes'; import { IMonarchLanguage } from 'vs/editor/standalone/common/monarch/monarchTypes'; import { ModesRegistry } from 'vs/editor/common/modes/modesRegistry'; suite('Monarch', () => { function createMonarchTokenizer(modeService: IModeService, languageId: string, language: IMonarchLanguage): MonarchTokenizer { return new MonarchTokenizer(modeService, null!, languageId, compile(languageId, language)); } test('Ensure @rematch and nextEmbedded can be used together in Monarch grammar', () => { const modeService = new ModeServiceImpl(); const innerModeRegistration = ModesRegistry.registerLanguage({ id: 'sql' }); const innerModeTokenizationRegistration = TokenizationRegistry.register('sql', createMonarchTokenizer(modeService, 'sql', { tokenizer: { root: [ [/./, 'token'] ] } })); const SQL_QUERY_START = '(SELECT|INSERT|UPDATE|DELETE|CREATE|REPLACE|ALTER|WITH)'; const tokenizer = createMonarchTokenizer(modeService, 'test1', { tokenizer: { root: [ [`(\"\"\")${SQL_QUERY_START}`, [{ 'token': 'string.quote', }, { token: '@rematch', next: '@endStringWithSQL', nextEmbedded: 'sql', },]], [/(""")$/, [{ token: 'string.quote', next: '@maybeStringIsSQL', },]], ], maybeStringIsSQL: [ [/(.*)/, { cases: { [`${SQL_QUERY_START}\\b.*`]: { token: '@rematch', next: '@endStringWithSQL', nextEmbedded: 'sql', }, '@default': { token: '@rematch', switchTo: '@endDblDocString', }, } }], ], endDblDocString: [ ['[^\']+', 'string'], ['\\\\\'', 'string'], ['\'\'\'', 'string', '@popall'], ['\'', 'string'] ], endStringWithSQL: [[/"""/, { token: 'string.quote', next: '@popall', nextEmbedded: '@pop', },]], } }); const lines = [ `mysql_query("""SELECT * FROM table_name WHERE ds = '<DATEID>'""")`, `mysql_query("""`, `SELECT *`, `FROM table_name`, `WHERE ds = '<DATEID>'`, `""")`, ]; const actualTokens: Token[][] = []; let state = tokenizer.getInitialState(); for (const line of lines) { const result = tokenizer.tokenize(line, state, 0); actualTokens.push(result.tokens); state = result.endState; } assert.deepEqual(actualTokens, [ [ { 'offset': 0, 'type': 'source.test1', 'language': 'test1' }, { 'offset': 12, 'type': 'string.quote.test1', 'language': 'test1' }, { 'offset': 15, 'type': 'token.sql', 'language': 'sql' }, { 'offset': 61, 'type': 'string.quote.test1', 'language': 'test1' }, { 'offset': 64, 'type': 'source.test1', 'language': 'test1' } ], [ { 'offset': 0, 'type': 'source.test1', 'language': 'test1' }, { 'offset': 12, 'type': 'string.quote.test1', 'language': 'test1' } ], [ { 'offset': 0, 'type': 'token.sql', 'language': 'sql' } ], [ { 'offset': 0, 'type': 'token.sql', 'language': 'sql' } ], [ { 'offset': 0, 'type': 'token.sql', 'language': 'sql' } ], [ { 'offset': 0, 'type': 'string.quote.test1', 'language': 'test1' }, { 'offset': 3, 'type': 'source.test1', 'language': 'test1' } ] ]); innerModeTokenizationRegistration.dispose(); innerModeRegistration.dispose(); }); });
src/vs/editor/standalone/test/monarch/monarch.test.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.000185399258043617, 0.00017369439592584968, 0.00016816009883768857, 0.0001725732145132497, 0.000004457147952052765 ]
{ "id": 9, "code_window": [ "\n", "\t\t\t\tquery.folderQueries = folderQueries.filter((q, index) => exists[index]);\n", "\t\t\t\tconst event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete> = this.raw.textSearch(query);\n", "\n" ], "labels": [ "keep", "replace", "replace", "keep" ], "after_edit": [ "\t\tconst event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete> = this.raw.textSearch(query);\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 100 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import './formatActionsMultiple'; import './formatActionsNone';
src/vs/workbench/contrib/format/browser/format.contribution.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00017788144759833813, 0.00017788144759833813, 0.00017788144759833813, 0.00017788144759833813, 0 ]
{ "id": 9, "code_window": [ "\n", "\t\t\t\tquery.folderQueries = folderQueries.filter((q, index) => exists[index]);\n", "\t\t\t\tconst event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete> = this.raw.textSearch(query);\n", "\n" ], "labels": [ "keep", "replace", "replace", "keep" ], "after_edit": [ "\t\tconst event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete> = this.raw.textSearch(query);\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 100 }
/*--------------------------------------------------------------------------------------------- * 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 Objects from 'vs/base/common/objects'; import { IJSONSchema } from 'vs/base/common/jsonSchema'; import { ProblemMatcherRegistry } from 'vs/workbench/contrib/tasks/common/problemMatcher'; import commonSchema from './jsonSchemaCommon'; const schema: IJSONSchema = { oneOf: [ { allOf: [ { type: 'object', required: ['version'], properties: { version: { type: 'string', enum: ['0.1.0'], deprecationMessage: nls.localize('JsonSchema.version.deprecated', 'Task version 0.1.0 is deprecated. Please use 2.0.0'), description: nls.localize('JsonSchema.version', 'The config\'s version number') }, _runner: { deprecationMessage: nls.localize('JsonSchema._runner', 'The runner has graduated. Use the offical runner property') }, runner: { type: 'string', enum: ['process', 'terminal'], default: 'process', description: nls.localize('JsonSchema.runner', 'Defines whether the task is executed as a process and the output is shown in the output window or inside the terminal.') }, windows: { $ref: '#/definitions/taskRunnerConfiguration', description: nls.localize('JsonSchema.windows', 'Windows specific command configuration') }, osx: { $ref: '#/definitions/taskRunnerConfiguration', description: nls.localize('JsonSchema.mac', 'Mac specific command configuration') }, linux: { $ref: '#/definitions/taskRunnerConfiguration', description: nls.localize('JsonSchema.linux', 'Linux specific command configuration') } } }, { $ref: '#/definitions/taskRunnerConfiguration' } ] } ] }; const shellCommand: IJSONSchema = { type: 'boolean', default: true, description: nls.localize('JsonSchema.shell', 'Specifies whether the command is a shell command or an external program. Defaults to false if omitted.') }; schema.definitions = Objects.deepClone(commonSchema.definitions); let definitions = schema.definitions!; definitions['commandConfiguration']['properties']!['isShellCommand'] = Objects.deepClone(shellCommand); definitions['taskDescription']['properties']!['isShellCommand'] = Objects.deepClone(shellCommand); definitions['taskRunnerConfiguration']['properties']!['isShellCommand'] = Objects.deepClone(shellCommand); Object.getOwnPropertyNames(definitions).forEach(key => { let newKey = key + '1'; definitions[newKey] = definitions[key]; delete definitions[key]; }); function fixReferences(literal: any) { if (Array.isArray(literal)) { literal.forEach(fixReferences); } else if (typeof literal === 'object') { if (literal['$ref']) { literal['$ref'] = literal['$ref'] + '1'; } Object.getOwnPropertyNames(literal).forEach(property => { let value = literal[property]; if (Array.isArray(value) || typeof value === 'object') { fixReferences(value); } }); } } fixReferences(schema); ProblemMatcherRegistry.onReady().then(() => { try { let matcherIds = ProblemMatcherRegistry.keys().map(key => '$' + key); definitions.problemMatcherType1.oneOf![0].enum = matcherIds; (definitions.problemMatcherType1.oneOf![2].items as IJSONSchema).anyOf![1].enum = matcherIds; } catch (err) { console.log('Installing problem matcher ids failed'); } }); export default schema;
src/vs/workbench/contrib/tasks/common/jsonSchema_v1.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00017643699538893998, 0.00017360267520416528, 0.00016903172945603728, 0.00017345348896924406, 0.0000021680300505977357 ]
{ "id": 10, "code_window": [ "\n", "\t\t\t\treturn DiskSearch.collectResultsFromEvent(event, onProgress, token);\n", "\t\t\t});\n", "\t}\n", "\n", "\tfileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> {\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn DiskSearch.collectResultsFromEvent(event, onProgress, token);\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 103 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { getPathFromAmdModule } from 'vs/base/common/amd'; import { CancellationToken } from 'vs/base/common/cancellation'; import { canceled } from 'vs/base/common/errors'; import { Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { URI as uri } from 'vs/base/common/uri'; import { getNextTickChannel } from 'vs/base/parts/ipc/common/ipc'; import { Client, IIPCOptions } from 'vs/base/parts/ipc/node/ipc.cp'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IDebugParams, IEnvironmentService } from 'vs/platform/environment/common/environment'; import { parseSearchPort, INativeEnvironmentService } from 'vs/platform/environment/node/environmentService'; import { IFileService } from 'vs/platform/files/common/files'; import { ILogService } from 'vs/platform/log/common/log'; import { FileMatch, IFileMatch, IFileQuery, IProgressMessage, IRawSearchService, ISearchComplete, ISearchConfiguration, ISearchProgressItem, ISearchResultProvider, ISerializedFileMatch, ISerializedSearchComplete, ISerializedSearchProgressItem, isSerializedSearchComplete, isSerializedSearchSuccess, ITextQuery, ISearchService, isFileMatch } from 'vs/workbench/services/search/common/search'; import { SearchChannelClient } from './searchIpc'; import { SearchService } from 'vs/workbench/services/search/common/searchService'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; export class LocalSearchService extends SearchService { constructor( @IModelService modelService: IModelService, @IEditorService editorService: IEditorService, @ITelemetryService telemetryService: ITelemetryService, @ILogService logService: ILogService, @IExtensionService extensionService: IExtensionService, @IFileService fileService: IFileService, @IEnvironmentService readonly environmentService: INativeEnvironmentService, @IInstantiationService readonly instantiationService: IInstantiationService ) { super(modelService, editorService, telemetryService, logService, extensionService, fileService); this.diskSearch = instantiationService.createInstance(DiskSearch, !environmentService.isBuilt || environmentService.verbose, parseSearchPort(environmentService.args, environmentService.isBuilt)); } } export class DiskSearch implements ISearchResultProvider { private raw: IRawSearchService; constructor( verboseLogging: boolean, searchDebug: IDebugParams | undefined, @ILogService private readonly logService: ILogService, @IConfigurationService private readonly configService: IConfigurationService, @IFileService private readonly fileService: IFileService ) { const timeout = this.configService.getValue<ISearchConfiguration>().search.maintainFileSearchCache ? Number.MAX_VALUE : 60 * 60 * 1000; const opts: IIPCOptions = { serverName: 'Search', timeout, args: ['--type=searchService'], // See https://github.com/Microsoft/vscode/issues/27665 // Pass in fresh execArgv to the forked process such that it doesn't inherit them from `process.execArgv`. // e.g. Launching the extension host process with `--inspect-brk=xxx` and then forking a process from the extension host // results in the forked process inheriting `--inspect-brk=xxx`. freshExecArgv: true, env: { AMD_ENTRYPOINT: 'vs/workbench/services/search/node/searchApp', PIPE_LOGGING: 'true', VERBOSE_LOGGING: verboseLogging }, useQueue: true }; if (searchDebug) { if (searchDebug.break && searchDebug.port) { opts.debugBrk = searchDebug.port; } else if (!searchDebug.break && searchDebug.port) { opts.debug = searchDebug.port; } } const client = new Client( getPathFromAmdModule(require, 'bootstrap-fork'), opts); const channel = getNextTickChannel(client.getChannel('search')); this.raw = new SearchChannelClient(channel); } textSearch(query: ITextQuery, onProgress?: (p: ISearchProgressItem) => void, token?: CancellationToken): Promise<ISearchComplete> { const folderQueries = query.folderQueries || []; return Promise.all(folderQueries.map(q => this.fileService.exists(q.folder))) .then(exists => { if (token && token.isCancellationRequested) { throw canceled(); } query.folderQueries = folderQueries.filter((q, index) => exists[index]); const event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete> = this.raw.textSearch(query); return DiskSearch.collectResultsFromEvent(event, onProgress, token); }); } fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { const folderQueries = query.folderQueries || []; return Promise.all(folderQueries.map(q => this.fileService.exists(q.folder))) .then(exists => { if (token && token.isCancellationRequested) { throw canceled(); } query.folderQueries = folderQueries.filter((q, index) => exists[index]); let event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete>; event = this.raw.fileSearch(query); const onProgress = (p: ISearchProgressItem) => { if (!isFileMatch(p)) { // Should only be for logs this.logService.debug('SearchService#search', p.message); } }; return DiskSearch.collectResultsFromEvent(event, onProgress, token); }); } /** * Public for test */ static collectResultsFromEvent(event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete>, onProgress?: (p: ISearchProgressItem) => void, token?: CancellationToken): Promise<ISearchComplete> { let result: IFileMatch[] = []; let listener: IDisposable; return new Promise<ISearchComplete>((c, e) => { if (token) { token.onCancellationRequested(() => { if (listener) { listener.dispose(); } e(canceled()); }); } listener = event(ev => { if (isSerializedSearchComplete(ev)) { if (isSerializedSearchSuccess(ev)) { c({ limitHit: ev.limitHit, results: result, stats: ev.stats }); } else { e(ev.error); } listener.dispose(); } else { // Matches if (Array.isArray(ev)) { const fileMatches = ev.map(d => this.createFileMatch(d)); result = result.concat(fileMatches); if (onProgress) { fileMatches.forEach(onProgress); } } // Match else if ((<ISerializedFileMatch>ev).path) { const fileMatch = this.createFileMatch(<ISerializedFileMatch>ev); result.push(fileMatch); if (onProgress) { onProgress(fileMatch); } } // Progress else if (onProgress) { onProgress(<IProgressMessage>ev); } } }); }); } private static createFileMatch(data: ISerializedFileMatch): FileMatch { const fileMatch = new FileMatch(uri.file(data.path)); if (data.results) { // const matches = data.results.filter(resultIsMatch); fileMatch.results.push(...data.results); } return fileMatch; } clearCache(cacheKey: string): Promise<void> { return this.raw.clearCache(cacheKey); } } registerSingleton(ISearchService, LocalSearchService, true);
src/vs/workbench/services/search/node/searchService.ts
1
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.9882816672325134, 0.11247647553682327, 0.0001643657305976376, 0.000630488561000675, 0.2855641841888428 ]
{ "id": 10, "code_window": [ "\n", "\t\t\t\treturn DiskSearch.collectResultsFromEvent(event, onProgress, token);\n", "\t\t\t});\n", "\t}\n", "\n", "\tfileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> {\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn DiskSearch.collectResultsFromEvent(event, onProgress, token);\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 103 }
/*--------------------------------------------------------------------------------------------- * 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 aria from 'vs/base/browser/ui/aria/aria'; import 'vs/css!./media/output'; import { KeyMod, KeyChord, KeyCode } from 'vs/base/common/keyCodes'; import { ModesRegistry } from 'vs/editor/common/modes/modesRegistry'; import { Registry } from 'vs/platform/registry/common/platform'; import { MenuId, MenuRegistry, registerAction2, Action2 } from 'vs/platform/actions/common/actions'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { OutputService, LogContentProvider } from 'vs/workbench/contrib/output/browser/outputServices'; import { OUTPUT_MODE_ID, OUTPUT_MIME, OUTPUT_VIEW_ID, IOutputService, CONTEXT_IN_OUTPUT, LOG_SCHEME, LOG_MODE_ID, LOG_MIME, CONTEXT_ACTIVE_LOG_OUTPUT, CONTEXT_OUTPUT_SCROLL_LOCK } from 'vs/workbench/contrib/output/common/output'; import { OutputViewPane } from 'vs/workbench/contrib/output/browser/outputView'; import { IEditorRegistry, Extensions as EditorExtensions, EditorDescriptor } from 'vs/workbench/browser/editor'; import { LogViewer, LogViewerInput } from 'vs/workbench/contrib/output/browser/logViewer'; import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions, IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { ITextModelService } from 'vs/editor/common/services/resolverService'; import { ViewContainer, IViewContainersRegistry, ViewContainerLocation, Extensions as ViewContainerExtensions, IViewsRegistry, IViewsService, IViewDescriptorService } from 'vs/workbench/common/views'; import { ViewPaneContainer } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { IConfigurationRegistry, Extensions as ConfigurationExtensions, ConfigurationScope } from 'vs/platform/configuration/common/configurationRegistry'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { IQuickPickItem, IQuickInputService } from 'vs/platform/quickinput/common/quickInput'; import { IOutputChannelDescriptor, IFileOutputChannelDescriptor } from 'vs/workbench/services/output/common/output'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { assertIsDefined } from 'vs/base/common/types'; import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService'; import { ContextKeyEqualsExpr, ContextKeyExpr, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { ToggleViewAction } from 'vs/workbench/browser/actions/layoutActions'; import { Codicon } from 'vs/base/common/codicons'; // Register Service registerSingleton(IOutputService, OutputService); // Register Output Mode ModesRegistry.registerLanguage({ id: OUTPUT_MODE_ID, extensions: [], mimetypes: [OUTPUT_MIME] }); // Register Log Output Mode ModesRegistry.registerLanguage({ id: LOG_MODE_ID, extensions: [], mimetypes: [LOG_MIME] }); // register output container const toggleOutputAcitonId = 'workbench.action.output.toggleOutput'; const toggleOutputActionKeybindings = { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_U, linux: { primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_H) // On Ubuntu Ctrl+Shift+U is taken by some global OS command } }; const VIEW_CONTAINER: ViewContainer = Registry.as<IViewContainersRegistry>(ViewContainerExtensions.ViewContainersRegistry).registerViewContainer({ id: OUTPUT_VIEW_ID, name: nls.localize('output', "Output"), icon: Codicon.output.classNames, order: 1, ctorDescriptor: new SyncDescriptor(ViewPaneContainer, [OUTPUT_VIEW_ID, { mergeViewWithContainerWhenSingleView: true, donotShowContainerTitleWhenMergedWithContainer: true }]), storageId: OUTPUT_VIEW_ID, hideIfEmpty: true, focusCommand: { id: toggleOutputAcitonId, keybindings: toggleOutputActionKeybindings } }, ViewContainerLocation.Panel); Registry.as<IViewsRegistry>(ViewContainerExtensions.ViewsRegistry).registerViews([{ id: OUTPUT_VIEW_ID, name: nls.localize('output', "Output"), containerIcon: Codicon.output.classNames, canMoveView: true, canToggleVisibility: false, ctorDescriptor: new SyncDescriptor(OutputViewPane), }], VIEW_CONTAINER); Registry.as<IEditorRegistry>(EditorExtensions.Editors).registerEditor( EditorDescriptor.create( LogViewer, LogViewer.LOG_VIEWER_EDITOR_ID, nls.localize('logViewer', "Log Viewer") ), [ new SyncDescriptor(LogViewerInput) ] ); class OutputContribution implements IWorkbenchContribution { constructor( @IInstantiationService instantiationService: IInstantiationService, @ITextModelService textModelService: ITextModelService ) { textModelService.registerTextModelContentProvider(LOG_SCHEME, instantiationService.createInstance(LogContentProvider)); } } Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(OutputContribution, LifecyclePhase.Restored); registerAction2(class extends Action2 { constructor() { super({ id: `workbench.output.action.switchBetweenOutputs`, title: nls.localize('switchToOutput.label', "Switch to Output"), menu: { id: MenuId.ViewTitle, when: ContextKeyEqualsExpr.create('view', OUTPUT_VIEW_ID), group: 'navigation', order: 1 }, }); } async run(accessor: ServicesAccessor, channelId: string): Promise<void> { accessor.get(IOutputService).showChannel(channelId); } }); registerAction2(class extends Action2 { constructor() { super({ id: `workbench.output.action.clearOutput`, title: { value: nls.localize('clearOutput.label', "Clear Output"), original: 'Clear Output' }, category: nls.localize('viewCategory', "View"), menu: [{ id: MenuId.ViewTitle, when: ContextKeyEqualsExpr.create('view', OUTPUT_VIEW_ID), group: 'navigation', order: 2 }, { id: MenuId.CommandPalette }, { id: MenuId.EditorContext, when: CONTEXT_IN_OUTPUT }], icon: { id: 'codicon/clear-all' } }); } async run(accessor: ServicesAccessor): Promise<void> { const outputService = accessor.get(IOutputService); const activeChannel = outputService.getActiveChannel(); if (activeChannel) { activeChannel.clear(); aria.status(nls.localize('outputCleared', "Output was cleared")); } } }); registerAction2(class extends Action2 { constructor() { super({ id: `workbench.output.action.toggleAutoScroll`, title: { value: nls.localize('toggleAutoScroll', "Toggle Auto Scrolling"), original: 'Toggle Auto Scrolling' }, tooltip: { value: nls.localize('outputScrollOff', "Turn Auto Scrolling Off"), original: 'Turn Auto Scrolling Off' }, menu: { id: MenuId.ViewTitle, when: ContextKeyExpr.and(ContextKeyEqualsExpr.create('view', OUTPUT_VIEW_ID)), group: 'navigation', order: 3, }, icon: { id: 'codicon/unlock' }, toggled: { condition: CONTEXT_OUTPUT_SCROLL_LOCK, icon: { id: 'codicon/lock' }, tooltip: { value: nls.localize('outputScrollOn', "Turn Auto Scrolling On"), original: 'Turn Auto Scrolling On' } } }); } async run(accessor: ServicesAccessor): Promise<void> { const outputView = accessor.get(IViewsService).getActiveViewWithId<OutputViewPane>(OUTPUT_VIEW_ID)!; outputView.scrollLock = !outputView.scrollLock; } }); registerAction2(class extends Action2 { constructor() { super({ id: `workbench.action.openActiveLogOutputFile`, title: { value: nls.localize('openActiveLogOutputFile', "Open Log Output File"), original: 'Open Log Output File' }, menu: [{ id: MenuId.ViewTitle, when: ContextKeyEqualsExpr.create('view', OUTPUT_VIEW_ID), group: 'navigation', order: 4 }, { id: MenuId.CommandPalette, when: CONTEXT_ACTIVE_LOG_OUTPUT, }], icon: { id: 'codicon/go-to-file' }, precondition: CONTEXT_ACTIVE_LOG_OUTPUT }); } async run(accessor: ServicesAccessor): Promise<void> { const outputService = accessor.get(IOutputService); const editorService = accessor.get(IEditorService); const instantiationService = accessor.get(IInstantiationService); const logFileOutputChannelDescriptor = this.getLogFileOutputChannelDescriptor(outputService); if (logFileOutputChannelDescriptor) { await editorService.openEditor(instantiationService.createInstance(LogViewerInput, logFileOutputChannelDescriptor)); } } private getLogFileOutputChannelDescriptor(outputService: IOutputService): IFileOutputChannelDescriptor | null { const channel = outputService.getActiveChannel(); if (channel) { const descriptor = outputService.getChannelDescriptors().filter(c => c.id === channel.id)[0]; if (descriptor && descriptor.file && descriptor.log) { return <IFileOutputChannelDescriptor>descriptor; } } return null; } }); // register toggle output action globally registerAction2(class extends Action2 { constructor() { super({ id: toggleOutputAcitonId, title: { value: nls.localize('toggleOutput', "Toggle Output"), original: 'Toggle Output' }, category: { value: nls.localize('viewCategory', "View"), original: 'View' }, menu: { id: MenuId.CommandPalette, }, keybinding: { ...toggleOutputActionKeybindings, ...{ weight: KeybindingWeight.WorkbenchContrib, when: undefined } }, }); } async run(accessor: ServicesAccessor): Promise<void> { const viewsService = accessor.get(IViewsService); const viewDescriptorService = accessor.get(IViewDescriptorService); const contextKeyService = accessor.get(IContextKeyService); const layoutService = accessor.get(IWorkbenchLayoutService); return new class ToggleOutputAction extends ToggleViewAction { constructor() { super(toggleOutputAcitonId, 'Toggle Output', OUTPUT_VIEW_ID, viewsService, viewDescriptorService, contextKeyService, layoutService); } }().run(); } }); const devCategory = { value: nls.localize('developer', "Developer"), original: 'Developer' }; registerAction2(class extends Action2 { constructor() { super({ id: 'workbench.action.showLogs', title: { value: nls.localize('showLogs', "Show Logs..."), original: 'Show Logs...' }, category: devCategory, menu: { id: MenuId.CommandPalette, }, }); } async run(accessor: ServicesAccessor): Promise<void> { const outputService = accessor.get(IOutputService); const quickInputService = accessor.get(IQuickInputService); const entries: { id: string, label: string }[] = outputService.getChannelDescriptors().filter(c => c.file && c.log) .map(({ id, label }) => ({ id, label })); const entry = await quickInputService.pick(entries, { placeHolder: nls.localize('selectlog', "Select Log") }); if (entry) { return outputService.showChannel(entry.id); } } }); interface IOutputChannelQuickPickItem extends IQuickPickItem { channel: IOutputChannelDescriptor; } registerAction2(class extends Action2 { constructor() { super({ id: 'workbench.action.openLogFile', title: { value: nls.localize('openLogFile', "Open Log File..."), original: 'Open Log File...' }, category: devCategory, menu: { id: MenuId.CommandPalette, }, }); } async run(accessor: ServicesAccessor): Promise<void> { const outputService = accessor.get(IOutputService); const quickInputService = accessor.get(IQuickInputService); const instantiationService = accessor.get(IInstantiationService); const editorService = accessor.get(IEditorService); const entries: IOutputChannelQuickPickItem[] = outputService.getChannelDescriptors().filter(c => c.file && c.log) .map(channel => (<IOutputChannelQuickPickItem>{ id: channel.id, label: channel.label, channel })); const entry = await quickInputService.pick(entries, { placeHolder: nls.localize('selectlogFile', "Select Log file") }); if (entry) { assertIsDefined(entry.channel.file); await editorService.openEditor(instantiationService.createInstance(LogViewerInput, (entry.channel as IFileOutputChannelDescriptor))); } } }); MenuRegistry.appendMenuItem(MenuId.MenubarViewMenu, { group: '4_panels', command: { id: toggleOutputAcitonId, title: nls.localize({ key: 'miToggleOutput', comment: ['&& denotes a mnemonic'] }, "&&Output") }, order: 1 }); Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).registerConfiguration({ id: 'output', order: 30, title: nls.localize('output', "Output"), type: 'object', properties: { 'output.smartScroll.enabled': { type: 'boolean', description: nls.localize('output.smartScroll.enabled', "Enable/disable the ability of smart scrolling in the output view. Smart scrolling allows you to lock scrolling automatically when you click in the output view and unlocks when you click in the last line."), default: true, scope: ConfigurationScope.APPLICATION, tags: ['output'] } } });
src/vs/workbench/contrib/output/browser/output.contribution.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.0001777290308382362, 0.00017185458273161203, 0.00016743771266192198, 0.0001717900886433199, 0.0000024252735784102697 ]
{ "id": 10, "code_window": [ "\n", "\t\t\t\treturn DiskSearch.collectResultsFromEvent(event, onProgress, token);\n", "\t\t\t});\n", "\t}\n", "\n", "\tfileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> {\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn DiskSearch.collectResultsFromEvent(event, onProgress, token);\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 103 }
/*--------------------------------------------------------------------------------------------- * 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!./iPadShowKeyboard'; import * as browser from 'vs/base/browser/browser'; import * as dom from 'vs/base/browser/dom'; import { Disposable } from 'vs/base/common/lifecycle'; import { ICodeEditor, IOverlayWidget, IOverlayWidgetPosition, OverlayWidgetPositionPreference } from 'vs/editor/browser/editorBrowser'; import { registerEditorContribution } from 'vs/editor/browser/editorExtensions'; import { IEditorContribution } from 'vs/editor/common/editorCommon'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; export class IPadShowKeyboard extends Disposable implements IEditorContribution { public static readonly ID = 'editor.contrib.iPadShowKeyboard'; private readonly editor: ICodeEditor; private widget: ShowKeyboardWidget | null; constructor(editor: ICodeEditor) { super(); this.editor = editor; this.widget = null; if (browser.isIPad) { this._register(editor.onDidChangeConfiguration(() => this.update())); this.update(); } } private update(): void { const shouldHaveWidget = (!this.editor.getOption(EditorOption.readOnly)); if (!this.widget && shouldHaveWidget) { this.widget = new ShowKeyboardWidget(this.editor); } else if (this.widget && !shouldHaveWidget) { this.widget.dispose(); this.widget = null; } } public dispose(): void { super.dispose(); if (this.widget) { this.widget.dispose(); this.widget = null; } } } class ShowKeyboardWidget extends Disposable implements IOverlayWidget { private static readonly ID = 'editor.contrib.ShowKeyboardWidget'; private readonly editor: ICodeEditor; private readonly _domNode: HTMLElement; constructor(editor: ICodeEditor) { super(); this.editor = editor; this._domNode = document.createElement('textarea'); this._domNode.className = 'iPadShowKeyboard'; this._register(dom.addDisposableListener(this._domNode, 'touchstart', (e) => { this.editor.focus(); })); this._register(dom.addDisposableListener(this._domNode, 'focus', (e) => { this.editor.focus(); })); this.editor.addOverlayWidget(this); } public dispose(): void { this.editor.removeOverlayWidget(this); super.dispose(); } // ----- IOverlayWidget API public getId(): string { return ShowKeyboardWidget.ID; } public getDomNode(): HTMLElement { return this._domNode; } public getPosition(): IOverlayWidgetPosition { return { preference: OverlayWidgetPositionPreference.BOTTOM_RIGHT_CORNER }; } } registerEditorContribution(IPadShowKeyboard.ID, IPadShowKeyboard);
src/vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.0001754666300257668, 0.0001729407231323421, 0.0001690056233201176, 0.0001742829044815153, 0.000002267850959469797 ]
{ "id": 10, "code_window": [ "\n", "\t\t\t\treturn DiskSearch.collectResultsFromEvent(event, onProgress, token);\n", "\t\t\t});\n", "\t}\n", "\n", "\tfileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> {\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn DiskSearch.collectResultsFromEvent(event, onProgress, token);\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 103 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Piece, PieceTreeBase } from 'vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase'; export class TreeNode { parent: TreeNode; left: TreeNode; right: TreeNode; color: NodeColor; // Piece piece: Piece; size_left: number; // size of the left subtree (not inorder) lf_left: number; // line feeds cnt in the left subtree (not in order) constructor(piece: Piece, color: NodeColor) { this.piece = piece; this.color = color; this.size_left = 0; this.lf_left = 0; this.parent = this; this.left = this; this.right = this; } public next(): TreeNode { if (this.right !== SENTINEL) { return leftest(this.right); } let node: TreeNode = this; while (node.parent !== SENTINEL) { if (node.parent.left === node) { break; } node = node.parent; } if (node.parent === SENTINEL) { return SENTINEL; } else { return node.parent; } } public prev(): TreeNode { if (this.left !== SENTINEL) { return righttest(this.left); } let node: TreeNode = this; while (node.parent !== SENTINEL) { if (node.parent.right === node) { break; } node = node.parent; } if (node.parent === SENTINEL) { return SENTINEL; } else { return node.parent; } } public detach(): void { this.parent = null!; this.left = null!; this.right = null!; } } export const enum NodeColor { Black = 0, Red = 1, } export const SENTINEL: TreeNode = new TreeNode(null!, NodeColor.Black); SENTINEL.parent = SENTINEL; SENTINEL.left = SENTINEL; SENTINEL.right = SENTINEL; SENTINEL.color = NodeColor.Black; export function leftest(node: TreeNode): TreeNode { while (node.left !== SENTINEL) { node = node.left; } return node; } export function righttest(node: TreeNode): TreeNode { while (node.right !== SENTINEL) { node = node.right; } return node; } export function calculateSize(node: TreeNode): number { if (node === SENTINEL) { return 0; } return node.size_left + node.piece.length + calculateSize(node.right); } export function calculateLF(node: TreeNode): number { if (node === SENTINEL) { return 0; } return node.lf_left + node.piece.lineFeedCnt + calculateLF(node.right); } export function resetSentinel(): void { SENTINEL.parent = SENTINEL; } export function leftRotate(tree: PieceTreeBase, x: TreeNode) { let y = x.right; // fix size_left y.size_left += x.size_left + (x.piece ? x.piece.length : 0); y.lf_left += x.lf_left + (x.piece ? x.piece.lineFeedCnt : 0); x.right = y.left; if (y.left !== SENTINEL) { y.left.parent = x; } y.parent = x.parent; if (x.parent === SENTINEL) { tree.root = y; } else if (x.parent.left === x) { x.parent.left = y; } else { x.parent.right = y; } y.left = x; x.parent = y; } export function rightRotate(tree: PieceTreeBase, y: TreeNode) { let x = y.left; y.left = x.right; if (x.right !== SENTINEL) { x.right.parent = y; } x.parent = y.parent; // fix size_left y.size_left -= x.size_left + (x.piece ? x.piece.length : 0); y.lf_left -= x.lf_left + (x.piece ? x.piece.lineFeedCnt : 0); if (y.parent === SENTINEL) { tree.root = x; } else if (y === y.parent.right) { y.parent.right = x; } else { y.parent.left = x; } x.right = y; y.parent = x; } export function rbDelete(tree: PieceTreeBase, z: TreeNode) { let x: TreeNode; let y: TreeNode; if (z.left === SENTINEL) { y = z; x = y.right; } else if (z.right === SENTINEL) { y = z; x = y.left; } else { y = leftest(z.right); x = y.right; } if (y === tree.root) { tree.root = x; // if x is null, we are removing the only node x.color = NodeColor.Black; z.detach(); resetSentinel(); tree.root.parent = SENTINEL; return; } let yWasRed = (y.color === NodeColor.Red); if (y === y.parent.left) { y.parent.left = x; } else { y.parent.right = x; } if (y === z) { x.parent = y.parent; recomputeTreeMetadata(tree, x); } else { if (y.parent === z) { x.parent = y; } else { x.parent = y.parent; } // as we make changes to x's hierarchy, update size_left of subtree first recomputeTreeMetadata(tree, x); y.left = z.left; y.right = z.right; y.parent = z.parent; y.color = z.color; if (z === tree.root) { tree.root = y; } else { if (z === z.parent.left) { z.parent.left = y; } else { z.parent.right = y; } } if (y.left !== SENTINEL) { y.left.parent = y; } if (y.right !== SENTINEL) { y.right.parent = y; } // update metadata // we replace z with y, so in this sub tree, the length change is z.item.length y.size_left = z.size_left; y.lf_left = z.lf_left; recomputeTreeMetadata(tree, y); } z.detach(); if (x.parent.left === x) { let newSizeLeft = calculateSize(x); let newLFLeft = calculateLF(x); if (newSizeLeft !== x.parent.size_left || newLFLeft !== x.parent.lf_left) { let delta = newSizeLeft - x.parent.size_left; let lf_delta = newLFLeft - x.parent.lf_left; x.parent.size_left = newSizeLeft; x.parent.lf_left = newLFLeft; updateTreeMetadata(tree, x.parent, delta, lf_delta); } } recomputeTreeMetadata(tree, x.parent); if (yWasRed) { resetSentinel(); return; } // RB-DELETE-FIXUP let w: TreeNode; while (x !== tree.root && x.color === NodeColor.Black) { if (x === x.parent.left) { w = x.parent.right; if (w.color === NodeColor.Red) { w.color = NodeColor.Black; x.parent.color = NodeColor.Red; leftRotate(tree, x.parent); w = x.parent.right; } if (w.left.color === NodeColor.Black && w.right.color === NodeColor.Black) { w.color = NodeColor.Red; x = x.parent; } else { if (w.right.color === NodeColor.Black) { w.left.color = NodeColor.Black; w.color = NodeColor.Red; rightRotate(tree, w); w = x.parent.right; } w.color = x.parent.color; x.parent.color = NodeColor.Black; w.right.color = NodeColor.Black; leftRotate(tree, x.parent); x = tree.root; } } else { w = x.parent.left; if (w.color === NodeColor.Red) { w.color = NodeColor.Black; x.parent.color = NodeColor.Red; rightRotate(tree, x.parent); w = x.parent.left; } if (w.left.color === NodeColor.Black && w.right.color === NodeColor.Black) { w.color = NodeColor.Red; x = x.parent; } else { if (w.left.color === NodeColor.Black) { w.right.color = NodeColor.Black; w.color = NodeColor.Red; leftRotate(tree, w); w = x.parent.left; } w.color = x.parent.color; x.parent.color = NodeColor.Black; w.left.color = NodeColor.Black; rightRotate(tree, x.parent); x = tree.root; } } } x.color = NodeColor.Black; resetSentinel(); } export function fixInsert(tree: PieceTreeBase, x: TreeNode) { recomputeTreeMetadata(tree, x); while (x !== tree.root && x.parent.color === NodeColor.Red) { if (x.parent === x.parent.parent.left) { const y = x.parent.parent.right; if (y.color === NodeColor.Red) { x.parent.color = NodeColor.Black; y.color = NodeColor.Black; x.parent.parent.color = NodeColor.Red; x = x.parent.parent; } else { if (x === x.parent.right) { x = x.parent; leftRotate(tree, x); } x.parent.color = NodeColor.Black; x.parent.parent.color = NodeColor.Red; rightRotate(tree, x.parent.parent); } } else { const y = x.parent.parent.left; if (y.color === NodeColor.Red) { x.parent.color = NodeColor.Black; y.color = NodeColor.Black; x.parent.parent.color = NodeColor.Red; x = x.parent.parent; } else { if (x === x.parent.left) { x = x.parent; rightRotate(tree, x); } x.parent.color = NodeColor.Black; x.parent.parent.color = NodeColor.Red; leftRotate(tree, x.parent.parent); } } } tree.root.color = NodeColor.Black; } export function updateTreeMetadata(tree: PieceTreeBase, x: TreeNode, delta: number, lineFeedCntDelta: number): void { // node length change or line feed count change while (x !== tree.root && x !== SENTINEL) { if (x.parent.left === x) { x.parent.size_left += delta; x.parent.lf_left += lineFeedCntDelta; } x = x.parent; } } export function recomputeTreeMetadata(tree: PieceTreeBase, x: TreeNode) { let delta = 0; let lf_delta = 0; if (x === tree.root) { return; } if (delta === 0) { // go upwards till the node whose left subtree is changed. while (x !== tree.root && x === x.parent.right) { x = x.parent; } if (x === tree.root) { // well, it means we add a node to the end (inorder) return; } // x is the node whose right subtree is changed. x = x.parent; delta = calculateSize(x.left) - x.size_left; lf_delta = calculateLF(x.left) - x.lf_left; x.size_left += delta; x.lf_left += lf_delta; } // go upwards till root. O(logN) while (x !== tree.root && (delta !== 0 || lf_delta !== 0)) { if (x.parent.left === x) { x.parent.size_left += delta; x.parent.lf_left += lf_delta; } x = x.parent; } }
src/vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00017754237342160195, 0.0001746016787365079, 0.0001705727627268061, 0.00017492937331553549, 0.0000016325773231073981 ]
{ "id": 11, "code_window": [ "\t}\n", "\n", "\tfileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> {\n", "\t\tconst folderQueries = query.folderQueries || [];\n", "\t\treturn Promise.all(folderQueries.map(q => this.fileService.exists(q.folder)))\n", "\t\t\t.then(exists => {\n", "\t\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\t\tthrow canceled();\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tif (token && token.isCancellationRequested) {\n", "\t\t\tthrow canceled();\n", "\t\t}\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 108 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { getPathFromAmdModule } from 'vs/base/common/amd'; import { CancellationToken } from 'vs/base/common/cancellation'; import { canceled } from 'vs/base/common/errors'; import { Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { URI as uri } from 'vs/base/common/uri'; import { getNextTickChannel } from 'vs/base/parts/ipc/common/ipc'; import { Client, IIPCOptions } from 'vs/base/parts/ipc/node/ipc.cp'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IDebugParams, IEnvironmentService } from 'vs/platform/environment/common/environment'; import { parseSearchPort, INativeEnvironmentService } from 'vs/platform/environment/node/environmentService'; import { IFileService } from 'vs/platform/files/common/files'; import { ILogService } from 'vs/platform/log/common/log'; import { FileMatch, IFileMatch, IFileQuery, IProgressMessage, IRawSearchService, ISearchComplete, ISearchConfiguration, ISearchProgressItem, ISearchResultProvider, ISerializedFileMatch, ISerializedSearchComplete, ISerializedSearchProgressItem, isSerializedSearchComplete, isSerializedSearchSuccess, ITextQuery, ISearchService, isFileMatch } from 'vs/workbench/services/search/common/search'; import { SearchChannelClient } from './searchIpc'; import { SearchService } from 'vs/workbench/services/search/common/searchService'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; export class LocalSearchService extends SearchService { constructor( @IModelService modelService: IModelService, @IEditorService editorService: IEditorService, @ITelemetryService telemetryService: ITelemetryService, @ILogService logService: ILogService, @IExtensionService extensionService: IExtensionService, @IFileService fileService: IFileService, @IEnvironmentService readonly environmentService: INativeEnvironmentService, @IInstantiationService readonly instantiationService: IInstantiationService ) { super(modelService, editorService, telemetryService, logService, extensionService, fileService); this.diskSearch = instantiationService.createInstance(DiskSearch, !environmentService.isBuilt || environmentService.verbose, parseSearchPort(environmentService.args, environmentService.isBuilt)); } } export class DiskSearch implements ISearchResultProvider { private raw: IRawSearchService; constructor( verboseLogging: boolean, searchDebug: IDebugParams | undefined, @ILogService private readonly logService: ILogService, @IConfigurationService private readonly configService: IConfigurationService, @IFileService private readonly fileService: IFileService ) { const timeout = this.configService.getValue<ISearchConfiguration>().search.maintainFileSearchCache ? Number.MAX_VALUE : 60 * 60 * 1000; const opts: IIPCOptions = { serverName: 'Search', timeout, args: ['--type=searchService'], // See https://github.com/Microsoft/vscode/issues/27665 // Pass in fresh execArgv to the forked process such that it doesn't inherit them from `process.execArgv`. // e.g. Launching the extension host process with `--inspect-brk=xxx` and then forking a process from the extension host // results in the forked process inheriting `--inspect-brk=xxx`. freshExecArgv: true, env: { AMD_ENTRYPOINT: 'vs/workbench/services/search/node/searchApp', PIPE_LOGGING: 'true', VERBOSE_LOGGING: verboseLogging }, useQueue: true }; if (searchDebug) { if (searchDebug.break && searchDebug.port) { opts.debugBrk = searchDebug.port; } else if (!searchDebug.break && searchDebug.port) { opts.debug = searchDebug.port; } } const client = new Client( getPathFromAmdModule(require, 'bootstrap-fork'), opts); const channel = getNextTickChannel(client.getChannel('search')); this.raw = new SearchChannelClient(channel); } textSearch(query: ITextQuery, onProgress?: (p: ISearchProgressItem) => void, token?: CancellationToken): Promise<ISearchComplete> { const folderQueries = query.folderQueries || []; return Promise.all(folderQueries.map(q => this.fileService.exists(q.folder))) .then(exists => { if (token && token.isCancellationRequested) { throw canceled(); } query.folderQueries = folderQueries.filter((q, index) => exists[index]); const event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete> = this.raw.textSearch(query); return DiskSearch.collectResultsFromEvent(event, onProgress, token); }); } fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { const folderQueries = query.folderQueries || []; return Promise.all(folderQueries.map(q => this.fileService.exists(q.folder))) .then(exists => { if (token && token.isCancellationRequested) { throw canceled(); } query.folderQueries = folderQueries.filter((q, index) => exists[index]); let event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete>; event = this.raw.fileSearch(query); const onProgress = (p: ISearchProgressItem) => { if (!isFileMatch(p)) { // Should only be for logs this.logService.debug('SearchService#search', p.message); } }; return DiskSearch.collectResultsFromEvent(event, onProgress, token); }); } /** * Public for test */ static collectResultsFromEvent(event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete>, onProgress?: (p: ISearchProgressItem) => void, token?: CancellationToken): Promise<ISearchComplete> { let result: IFileMatch[] = []; let listener: IDisposable; return new Promise<ISearchComplete>((c, e) => { if (token) { token.onCancellationRequested(() => { if (listener) { listener.dispose(); } e(canceled()); }); } listener = event(ev => { if (isSerializedSearchComplete(ev)) { if (isSerializedSearchSuccess(ev)) { c({ limitHit: ev.limitHit, results: result, stats: ev.stats }); } else { e(ev.error); } listener.dispose(); } else { // Matches if (Array.isArray(ev)) { const fileMatches = ev.map(d => this.createFileMatch(d)); result = result.concat(fileMatches); if (onProgress) { fileMatches.forEach(onProgress); } } // Match else if ((<ISerializedFileMatch>ev).path) { const fileMatch = this.createFileMatch(<ISerializedFileMatch>ev); result.push(fileMatch); if (onProgress) { onProgress(fileMatch); } } // Progress else if (onProgress) { onProgress(<IProgressMessage>ev); } } }); }); } private static createFileMatch(data: ISerializedFileMatch): FileMatch { const fileMatch = new FileMatch(uri.file(data.path)); if (data.results) { // const matches = data.results.filter(resultIsMatch); fileMatch.results.push(...data.results); } return fileMatch; } clearCache(cacheKey: string): Promise<void> { return this.raw.clearCache(cacheKey); } } registerSingleton(ISearchService, LocalSearchService, true);
src/vs/workbench/services/search/node/searchService.ts
1
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.9986500144004822, 0.14413383603096008, 0.00016452238196507096, 0.0002064665750367567, 0.3487303555011749 ]
{ "id": 11, "code_window": [ "\t}\n", "\n", "\tfileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> {\n", "\t\tconst folderQueries = query.folderQueries || [];\n", "\t\treturn Promise.all(folderQueries.map(q => this.fileService.exists(q.folder)))\n", "\t\t\t.then(exists => {\n", "\t\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\t\tthrow canceled();\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tif (token && token.isCancellationRequested) {\n", "\t\t\tthrow canceled();\n", "\t\t}\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 108 }
/*--------------------------------------------------------------------------------------------- * 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!./media/quickInput'; import * as dom from 'vs/base/browser/dom'; import { URI } from 'vs/base/common/uri'; import { IdGenerator } from 'vs/base/common/idGenerator'; const iconPathToClass: Record<string, string> = {}; const iconClassGenerator = new IdGenerator('quick-input-button-icon-'); export function getIconClass(iconPath: { dark: URI; light?: URI; } | undefined): string | undefined { if (!iconPath) { return undefined; } let iconClass: string; const key = iconPath.dark.toString(); if (iconPathToClass[key]) { iconClass = iconPathToClass[key]; } else { iconClass = iconClassGenerator.nextId(); dom.createCSSRule(`.${iconClass}`, `background-image: ${dom.asCSSUrl(iconPath.light || iconPath.dark)}`); dom.createCSSRule(`.vs-dark .${iconClass}, .hc-black .${iconClass}`, `background-image: ${dom.asCSSUrl(iconPath.dark)}`); iconPathToClass[key] = iconClass; } return iconClass; }
src/vs/base/parts/quickinput/browser/quickInputUtils.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.0001777188736014068, 0.00017599960847292095, 0.0001746955094859004, 0.0001757920254021883, 0.000001138391326094279 ]
{ "id": 11, "code_window": [ "\t}\n", "\n", "\tfileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> {\n", "\t\tconst folderQueries = query.folderQueries || [];\n", "\t\treturn Promise.all(folderQueries.map(q => this.fileService.exists(q.folder)))\n", "\t\t\t.then(exists => {\n", "\t\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\t\tthrow canceled();\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tif (token && token.isCancellationRequested) {\n", "\t\t\tthrow canceled();\n", "\t\t}\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 108 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /// <reference path='../../../../../src/vs/vscode.d.ts'/> /// <reference path="../../../../../src/vs/vscode.proposed.d.ts" />
extensions/json-language-features/client/src/typings/ref.d.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.0001760169252520427, 0.0001760169252520427, 0.0001760169252520427, 0.0001760169252520427, 0 ]
{ "id": 11, "code_window": [ "\t}\n", "\n", "\tfileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> {\n", "\t\tconst folderQueries = query.folderQueries || [];\n", "\t\treturn Promise.all(folderQueries.map(q => this.fileService.exists(q.folder)))\n", "\t\t\t.then(exists => {\n", "\t\t\t\tif (token && token.isCancellationRequested) {\n", "\t\t\t\t\tthrow canceled();\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tif (token && token.isCancellationRequested) {\n", "\t\t\tthrow canceled();\n", "\t\t}\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 108 }
{ "type": "dark", "colors": { "dropdown.background": "#525252", "list.activeSelectionBackground": "#707070", "list.focusBackground": "#707070", "list.inactiveSelectionBackground": "#4e4e4e", "list.hoverBackground": "#444444", "list.highlightForeground": "#e58520", "button.background": "#565656", "editor.background": "#1e1e1e", "editor.foreground": "#c5c8c6", "editor.selectionBackground": "#676b7180", "minimap.selectionHighlight": "#676b7180", "editor.selectionHighlightBackground": "#575b6180", "editor.lineHighlightBackground": "#303030", "editorLineNumber.activeForeground": "#949494", "editor.wordHighlightBackground": "#4747a180", "editor.wordHighlightStrongBackground": "#6767ce80", "editorCursor.foreground": "#c07020", "editorWhitespace.foreground": "#505037", "editorIndentGuide.background": "#505037", "editorIndentGuide.activeBackground": "#707057", "editorGroupHeader.tabsBackground": "#282828", "tab.inactiveBackground": "#404040", "tab.border": "#303030", "tab.inactiveForeground": "#d8d8d8", "peekView.border": "#3655b5", "panelTitle.activeForeground": "#ffffff", "statusBar.background": "#505050", "statusBar.debuggingBackground": "#505050", "statusBar.noFolderBackground": "#505050", "titleBar.activeBackground": "#505050", "statusBarItem.remoteBackground": "#3655b5", "activityBar.background": "#353535", "activityBar.foreground": "#ffffff", "activityBarBadge.background": "#3655b5", "sideBar.background": "#272727", "sideBarSectionHeader.background": "#505050", "menu.background": "#272727", "menu.foreground": "#CCCCCC", "pickerGroup.foreground": "#b0b0b0", "terminal.ansiWhite": "#ffffff", "inputOption.activeBorder": "#3655b5", "focusBorder": "#3655b5" }, "tokenColors": [ { "settings": { "foreground": "#C5C8C6" } }, { "scope": [ "meta.embedded", "source.groovy.embedded" ], "settings": { "foreground": "#C5C8C6" } }, { "name": "Comment", "scope": "comment", "settings": { "fontStyle": "", "foreground": "#9A9B99" } }, { "name": "String", "scope": "string", "settings": { "fontStyle": "", "foreground": "#9AA83A" } }, { "name": "String Embedded Source", "scope": "string source", "settings": { "fontStyle": "", "foreground": "#D08442" } }, { "name": "Number", "scope": "constant.numeric", "settings": { "fontStyle": "", "foreground": "#6089B4" } }, { "name": "Built-in constant", "scope": "constant.language", "settings": { "fontStyle": "", "foreground": "#408080" } }, { "name": "User-defined constant", "scope": "constant.character, constant.other", "settings": { "fontStyle": "", "foreground": "#8080FF", } }, { "name": "Keyword", "scope": "keyword", "settings": { "fontStyle": "", "foreground": "#6089B4" } }, { "name": "Support", "scope": "support", "settings": { "fontStyle": "", "foreground": "#C7444A" } }, { "name": "Storage", "scope": "storage", "settings": { "fontStyle": "", "foreground": "#9872A2" } }, { "name": "Class name", "scope": "entity.name.class, entity.name.type, entity.name.namespace, entity.name.scope-resolution", "settings": { "fontStyle": "", "foreground": "#9B0000", } }, { "name": "Inherited class", "scope": "entity.other.inherited-class", "settings": { "fontStyle": "", "foreground": "#C7444A" } }, { "name": "Function name", "scope": "entity.name.function", "settings": { "fontStyle": "", "foreground": "#CE6700" } }, { "name": "Function argument", "scope": "variable.parameter", "settings": { "fontStyle": "", "foreground": "#6089B4" } }, { "name": "Tag name", "scope": "entity.name.tag", "settings": { "fontStyle": "", "foreground": "#9872A2" } }, { "name": "Tag attribute", "scope": "entity.other.attribute-name", "settings": { "fontStyle": "", "foreground": "#9872A2" } }, { "name": "Library function", "scope": "support.function", "settings": { "fontStyle": "", "foreground": "#9872A2" } }, { "name": "Keyword", "scope": "keyword", "settings": { "fontStyle": "", "foreground": "#676867" } }, { "name": "Class Variable", "scope": "variable.other, variable.js, punctuation.separator.variable", "settings": { "fontStyle": "", "foreground": "#6089B4" } }, { "name": "Meta Brace", "scope": "punctuation.section.embedded -(source string source punctuation.section.embedded), meta.brace.erb.html", "settings": { "fontStyle": "", "foreground": "#008200" } }, { "name": "Invalid", "scope": "invalid", "settings": { "fontStyle": "", "foreground": "#FF0B00" } }, { "name": "Normal Variable", "scope": "variable.other.php, variable.other.normal", "settings": { "fontStyle": "", "foreground": "#6089B4" } }, { "name": "Function Object", "scope": "meta.function-call.object", "settings": { "fontStyle": "", "foreground": "#9872A2" } }, { "name": "Function Call Variable", "scope": "variable.other.property", "settings": { "fontStyle": "", "foreground": "#9872A2" } }, { "name": "Keyword Control / Special", "scope": [ "keyword.control", "keyword.operator.new.cpp", "keyword.operator.delete.cpp", "keyword.other.using", "keyword.other.operator" ], "settings": { "fontStyle": "", "foreground": "#9872A2" } }, { "name": "Tag", "scope": "meta.tag", "settings": { "fontStyle": "", "foreground": "#D0B344" } }, { "name": "Tag Name", "scope": "entity.name.tag", "settings": { "fontStyle": "", "foreground": "#6089B4" } }, { "name": "Doctype", "scope": "meta.doctype, meta.tag.sgml-declaration.doctype, meta.tag.sgml.doctype", "settings": { "fontStyle": "", "foreground": "#9AA83A" } }, { "name": "Tag Inline Source", "scope": "meta.tag.inline source, text.html.php.source", "settings": { "fontStyle": "", "foreground": "#9AA83A" } }, { "name": "Tag Other", "scope": "meta.tag.other, entity.name.tag.style, entity.name.tag.script, meta.tag.block.script, source.js.embedded punctuation.definition.tag.html, source.css.embedded punctuation.definition.tag.html", "settings": { "fontStyle": "", "foreground": "#9872A2" } }, { "name": "Tag Attribute", "scope": "entity.other.attribute-name, meta.tag punctuation.definition.string", "settings": { "fontStyle": "", "foreground": "#D0B344" } }, { "name": "Tag Value", "scope": "meta.tag string -source -punctuation, text source text meta.tag string -punctuation", "settings": { "fontStyle": "", "foreground": "#6089B4" } }, { "name": "Meta Brace", "scope": "punctuation.section.embedded -(source string source punctuation.section.embedded), meta.brace.erb.html", "settings": { "fontStyle": "", "foreground": "#D0B344" } }, { "name": "HTML ID", "scope": "meta.toc-list.id", "settings": { "foreground": "#9AA83A" } }, { "name": "HTML String", "scope": "string.quoted.double.html, punctuation.definition.string.begin.html, punctuation.definition.string.end.html", "settings": { "fontStyle": "", "foreground": "#9AA83A" } }, { "name": "HTML Tags", "scope": "punctuation.definition.tag.html, punctuation.definition.tag.begin, punctuation.definition.tag.end", "settings": { "fontStyle": "", "foreground": "#6089B4" } }, { "name": "CSS ID", "scope": "meta.selector.css entity.other.attribute-name.id", "settings": { "fontStyle": "", "foreground": "#9872A2" } }, { "name": "CSS Property Name", "scope": "support.type.property-name.css", "settings": { "fontStyle": "", "foreground": "#676867" } }, { "name": "CSS Property Value", "scope": "meta.property-group support.constant.property-value.css, meta.property-value support.constant.property-value.css", "settings": { "fontStyle": "", "foreground": "#C7444A" } }, { "name": "JavaScript Variable", "scope": "variable.language.js", "settings": { "foreground": "#CC555A" } }, { "name": "Template Definition", "scope": [ "punctuation.definition.template-expression", "punctuation.section.embedded.coffee" ], "settings": { "foreground": "#D08442" } }, { "name": "Reset JavaScript string interpolation expression", "scope": [ "meta.template.expression" ], "settings": { "foreground": "#C5C8C6" } }, { "name": "PHP Function Call", "scope": "meta.function-call.object.php", "settings": { "fontStyle": "", "foreground": "#D0B344" } }, { "name": "PHP Single Quote HMTL Fix", "scope": "punctuation.definition.string.end.php, punctuation.definition.string.begin.php", "settings": { "foreground": "#9AA83A" } }, { "name": "PHP Parenthesis HMTL Fix", "scope": "source.php.embedded.line.html", "settings": { "foreground": "#676867" } }, { "name": "PHP Punctuation Embedded", "scope": "punctuation.section.embedded.begin.php, punctuation.section.embedded.end.php", "settings": { "fontStyle": "", "foreground": "#D08442" } }, { "name": "Ruby Symbol", "scope": "constant.other.symbol.ruby", "settings": { "fontStyle": "", "foreground": "#9AA83A" } }, { "name": "Ruby Variable", "scope": "variable.language.ruby", "settings": { "fontStyle": "", "foreground": "#D0B344" } }, { "name": "Ruby Special Method", "scope": "keyword.other.special-method.ruby", "settings": { "fontStyle": "", "foreground": "#D9B700" } }, { "name": "Ruby Embedded Source", "scope": [ "punctuation.section.embedded.begin.ruby", "punctuation.section.embedded.end.ruby" ], "settings": { "foreground": "#D08442" } }, { "name": "SQL", "scope": "keyword.other.DML.sql", "settings": { "fontStyle": "", "foreground": "#D0B344" } }, { "name": "diff: header", "scope": "meta.diff, meta.diff.header", "settings": { "fontStyle": "italic", "foreground": "#E0EDDD" } }, { "name": "diff: deleted", "scope": "markup.deleted", "settings": { "fontStyle": "", "foreground": "#dc322f" } }, { "name": "diff: changed", "scope": "markup.changed", "settings": { "fontStyle": "", "foreground": "#cb4b16" } }, { "name": "diff: inserted", "scope": "markup.inserted", "settings": { "foreground": "#219186" } }, { "name": "Markup Quote", "scope": "markup.quote", "settings": { "foreground": "#9872A2" } }, { "name": "Markup Lists", "scope": "markup.list", "settings": { "foreground": "#9AA83A" } }, { "name": "Markup Styling", "scope": "markup.bold, markup.italic", "settings": { "foreground": "#6089B4" } }, { "name": "Markup Inline", "scope": "markup.inline.raw", "settings": { "fontStyle": "", "foreground": "#FF0080" } }, { "name": "Markup Headings", "scope": "markup.heading", "settings": { "foreground": "#D0B344" } }, { "name": "Markup Setext Header", "scope": "markup.heading.setext", "settings": { "fontStyle": "", "foreground": "#D0B344" } }, { "scope": "token.info-token", "settings": { "foreground": "#6796e6" } }, { "scope": "token.warn-token", "settings": { "foreground": "#cd9731" } }, { "scope": "token.error-token", "settings": { "foreground": "#f44747" } }, { "scope": "token.debug-token", "settings": { "foreground": "#b267e6" } }, { "name": "this.self", "scope": "variable.language", "settings": { "foreground": "#c7444a" } } ], "semanticHighlighting": true }
extensions/theme-monokai-dimmed/themes/dimmed-monokai-color-theme.json
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00017662333266343921, 0.00017439632210880518, 0.0001689793571131304, 0.00017455840134061873, 0.0000012396692454785807 ]
{ "id": 12, "code_window": [ "\n", "\t\t\t\tquery.folderQueries = folderQueries.filter((q, index) => exists[index]);\n", "\t\t\t\tlet event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete>;\n", "\t\t\t\tevent = this.raw.fileSearch(query);\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tlet event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete>;\n", "\t\tevent = this.raw.fileSearch(query);\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 115 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { getPathFromAmdModule } from 'vs/base/common/amd'; import { CancellationToken } from 'vs/base/common/cancellation'; import { canceled } from 'vs/base/common/errors'; import { Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { URI as uri } from 'vs/base/common/uri'; import { getNextTickChannel } from 'vs/base/parts/ipc/common/ipc'; import { Client, IIPCOptions } from 'vs/base/parts/ipc/node/ipc.cp'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IDebugParams, IEnvironmentService } from 'vs/platform/environment/common/environment'; import { parseSearchPort, INativeEnvironmentService } from 'vs/platform/environment/node/environmentService'; import { IFileService } from 'vs/platform/files/common/files'; import { ILogService } from 'vs/platform/log/common/log'; import { FileMatch, IFileMatch, IFileQuery, IProgressMessage, IRawSearchService, ISearchComplete, ISearchConfiguration, ISearchProgressItem, ISearchResultProvider, ISerializedFileMatch, ISerializedSearchComplete, ISerializedSearchProgressItem, isSerializedSearchComplete, isSerializedSearchSuccess, ITextQuery, ISearchService, isFileMatch } from 'vs/workbench/services/search/common/search'; import { SearchChannelClient } from './searchIpc'; import { SearchService } from 'vs/workbench/services/search/common/searchService'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; export class LocalSearchService extends SearchService { constructor( @IModelService modelService: IModelService, @IEditorService editorService: IEditorService, @ITelemetryService telemetryService: ITelemetryService, @ILogService logService: ILogService, @IExtensionService extensionService: IExtensionService, @IFileService fileService: IFileService, @IEnvironmentService readonly environmentService: INativeEnvironmentService, @IInstantiationService readonly instantiationService: IInstantiationService ) { super(modelService, editorService, telemetryService, logService, extensionService, fileService); this.diskSearch = instantiationService.createInstance(DiskSearch, !environmentService.isBuilt || environmentService.verbose, parseSearchPort(environmentService.args, environmentService.isBuilt)); } } export class DiskSearch implements ISearchResultProvider { private raw: IRawSearchService; constructor( verboseLogging: boolean, searchDebug: IDebugParams | undefined, @ILogService private readonly logService: ILogService, @IConfigurationService private readonly configService: IConfigurationService, @IFileService private readonly fileService: IFileService ) { const timeout = this.configService.getValue<ISearchConfiguration>().search.maintainFileSearchCache ? Number.MAX_VALUE : 60 * 60 * 1000; const opts: IIPCOptions = { serverName: 'Search', timeout, args: ['--type=searchService'], // See https://github.com/Microsoft/vscode/issues/27665 // Pass in fresh execArgv to the forked process such that it doesn't inherit them from `process.execArgv`. // e.g. Launching the extension host process with `--inspect-brk=xxx` and then forking a process from the extension host // results in the forked process inheriting `--inspect-brk=xxx`. freshExecArgv: true, env: { AMD_ENTRYPOINT: 'vs/workbench/services/search/node/searchApp', PIPE_LOGGING: 'true', VERBOSE_LOGGING: verboseLogging }, useQueue: true }; if (searchDebug) { if (searchDebug.break && searchDebug.port) { opts.debugBrk = searchDebug.port; } else if (!searchDebug.break && searchDebug.port) { opts.debug = searchDebug.port; } } const client = new Client( getPathFromAmdModule(require, 'bootstrap-fork'), opts); const channel = getNextTickChannel(client.getChannel('search')); this.raw = new SearchChannelClient(channel); } textSearch(query: ITextQuery, onProgress?: (p: ISearchProgressItem) => void, token?: CancellationToken): Promise<ISearchComplete> { const folderQueries = query.folderQueries || []; return Promise.all(folderQueries.map(q => this.fileService.exists(q.folder))) .then(exists => { if (token && token.isCancellationRequested) { throw canceled(); } query.folderQueries = folderQueries.filter((q, index) => exists[index]); const event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete> = this.raw.textSearch(query); return DiskSearch.collectResultsFromEvent(event, onProgress, token); }); } fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { const folderQueries = query.folderQueries || []; return Promise.all(folderQueries.map(q => this.fileService.exists(q.folder))) .then(exists => { if (token && token.isCancellationRequested) { throw canceled(); } query.folderQueries = folderQueries.filter((q, index) => exists[index]); let event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete>; event = this.raw.fileSearch(query); const onProgress = (p: ISearchProgressItem) => { if (!isFileMatch(p)) { // Should only be for logs this.logService.debug('SearchService#search', p.message); } }; return DiskSearch.collectResultsFromEvent(event, onProgress, token); }); } /** * Public for test */ static collectResultsFromEvent(event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete>, onProgress?: (p: ISearchProgressItem) => void, token?: CancellationToken): Promise<ISearchComplete> { let result: IFileMatch[] = []; let listener: IDisposable; return new Promise<ISearchComplete>((c, e) => { if (token) { token.onCancellationRequested(() => { if (listener) { listener.dispose(); } e(canceled()); }); } listener = event(ev => { if (isSerializedSearchComplete(ev)) { if (isSerializedSearchSuccess(ev)) { c({ limitHit: ev.limitHit, results: result, stats: ev.stats }); } else { e(ev.error); } listener.dispose(); } else { // Matches if (Array.isArray(ev)) { const fileMatches = ev.map(d => this.createFileMatch(d)); result = result.concat(fileMatches); if (onProgress) { fileMatches.forEach(onProgress); } } // Match else if ((<ISerializedFileMatch>ev).path) { const fileMatch = this.createFileMatch(<ISerializedFileMatch>ev); result.push(fileMatch); if (onProgress) { onProgress(fileMatch); } } // Progress else if (onProgress) { onProgress(<IProgressMessage>ev); } } }); }); } private static createFileMatch(data: ISerializedFileMatch): FileMatch { const fileMatch = new FileMatch(uri.file(data.path)); if (data.results) { // const matches = data.results.filter(resultIsMatch); fileMatch.results.push(...data.results); } return fileMatch; } clearCache(cacheKey: string): Promise<void> { return this.raw.clearCache(cacheKey); } } registerSingleton(ISearchService, LocalSearchService, true);
src/vs/workbench/services/search/node/searchService.ts
1
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.9978589415550232, 0.18873216211795807, 0.00016423978377133608, 0.00017437698261346668, 0.3835180997848511 ]
{ "id": 12, "code_window": [ "\n", "\t\t\t\tquery.folderQueries = folderQueries.filter((q, index) => exists[index]);\n", "\t\t\t\tlet event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete>;\n", "\t\t\t\tevent = this.raw.fileSearch(query);\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tlet event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete>;\n", "\t\tevent = this.raw.fileSearch(query);\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 115 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { ILink } from 'vs/editor/common/modes'; import { ILinkComputerTarget, computeLinks } from 'vs/editor/common/modes/linkComputer'; class SimpleLinkComputerTarget implements ILinkComputerTarget { constructor(private _lines: string[]) { // Intentional Empty } public getLineCount(): number { return this._lines.length; } public getLineContent(lineNumber: number): string { return this._lines[lineNumber - 1]; } } function myComputeLinks(lines: string[]): ILink[] { let target = new SimpleLinkComputerTarget(lines); return computeLinks(target); } function assertLink(text: string, extractedLink: string): void { let startColumn = 0, endColumn = 0, chr: string, i = 0; for (i = 0; i < extractedLink.length; i++) { chr = extractedLink.charAt(i); if (chr !== ' ' && chr !== '\t') { startColumn = i + 1; break; } } for (i = extractedLink.length - 1; i >= 0; i--) { chr = extractedLink.charAt(i); if (chr !== ' ' && chr !== '\t') { endColumn = i + 2; break; } } let r = myComputeLinks([text]); assert.deepEqual(r, [{ range: { startLineNumber: 1, startColumn: startColumn, endLineNumber: 1, endColumn: endColumn }, url: extractedLink.substring(startColumn - 1, endColumn - 1) }]); } suite('Editor Modes - Link Computer', () => { test('Null model', () => { let r = computeLinks(null); assert.deepEqual(r, []); }); test('Parsing', () => { assertLink( 'x = "http://foo.bar";', ' http://foo.bar ' ); assertLink( 'x = (http://foo.bar);', ' http://foo.bar ' ); assertLink( 'x = [http://foo.bar];', ' http://foo.bar ' ); assertLink( 'x = \'http://foo.bar\';', ' http://foo.bar ' ); assertLink( 'x = http://foo.bar ;', ' http://foo.bar ' ); assertLink( 'x = <http://foo.bar>;', ' http://foo.bar ' ); assertLink( 'x = {http://foo.bar};', ' http://foo.bar ' ); assertLink( '(see http://foo.bar)', ' http://foo.bar ' ); assertLink( '[see http://foo.bar]', ' http://foo.bar ' ); assertLink( '{see http://foo.bar}', ' http://foo.bar ' ); assertLink( '<see http://foo.bar>', ' http://foo.bar ' ); assertLink( '<url>http://mylink.com</url>', ' http://mylink.com ' ); assertLink( '// Click here to learn more. https://go.microsoft.com/fwlink/?LinkID=513275&clcid=0x409', ' https://go.microsoft.com/fwlink/?LinkID=513275&clcid=0x409' ); assertLink( '// Click here to learn more. https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx', ' https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx' ); assertLink( '// https://github.com/projectkudu/kudu/blob/master/Kudu.Core/Scripts/selectNodeVersion.js', ' https://github.com/projectkudu/kudu/blob/master/Kudu.Core/Scripts/selectNodeVersion.js' ); assertLink( '<!-- !!! Do not remove !!! WebContentRef(link:https://go.microsoft.com/fwlink/?LinkId=166007, area:Admin, updated:2015, nextUpdate:2016, tags:SqlServer) !!! Do not remove !!! -->', ' https://go.microsoft.com/fwlink/?LinkId=166007 ' ); assertLink( 'For instructions, see https://go.microsoft.com/fwlink/?LinkId=166007.</value>', ' https://go.microsoft.com/fwlink/?LinkId=166007 ' ); assertLink( 'For instructions, see https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx.</value>', ' https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx ' ); assertLink( 'x = "https://en.wikipedia.org/wiki/Zürich";', ' https://en.wikipedia.org/wiki/Zürich ' ); assertLink( '請參閱 http://go.microsoft.com/fwlink/?LinkId=761051。', ' http://go.microsoft.com/fwlink/?LinkId=761051 ' ); assertLink( '(請參閱 http://go.microsoft.com/fwlink/?LinkId=761051)', ' http://go.microsoft.com/fwlink/?LinkId=761051 ' ); assertLink( 'x = "file:///foo.bar";', ' file:///foo.bar ' ); assertLink( 'x = "file://c:/foo.bar";', ' file://c:/foo.bar ' ); assertLink( 'x = "file://shares/foo.bar";', ' file://shares/foo.bar ' ); assertLink( 'x = "file://shäres/foo.bar";', ' file://shäres/foo.bar ' ); assertLink( 'Some text, then http://www.bing.com.', ' http://www.bing.com ' ); assertLink( 'let url = `http://***/_api/web/lists/GetByTitle(\'Teambuildingaanvragen\')/items`;', ' http://***/_api/web/lists/GetByTitle(\'Teambuildingaanvragen\')/items ' ); }); test('issue #7855', () => { assertLink( '7. At this point, ServiceMain has been called. There is no functionality presently in ServiceMain, but you can consult the [MSDN documentation](https://msdn.microsoft.com/en-us/library/windows/desktop/ms687414(v=vs.85).aspx) to add functionality as desired!', ' https://msdn.microsoft.com/en-us/library/windows/desktop/ms687414(v=vs.85).aspx ' ); }); test('issue #62278: "Ctrl + click to follow link" for IPv6 URLs', () => { assertLink( 'let x = "http://[::1]:5000/connect/token"', ' http://[::1]:5000/connect/token ' ); }); test('issue #70254: bold links dont open in markdown file using editor mode with ctrl + click', () => { assertLink( '2. Navigate to **https://portal.azure.com**', ' https://portal.azure.com ' ); }); test('issue #86358: URL wrong recognition pattern', () => { assertLink( 'POST|https://portal.azure.com|2019-12-05|', ' https://portal.azure.com ' ); }); test('issue #67022: Space as end of hyperlink isn\'t always good idea', () => { assertLink( 'aa https://foo.bar/[this is foo site] aa', ' https://foo.bar/[this is foo site] ' ); }); });
src/vs/editor/test/common/modes/linkComputer.test.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.0001780492893885821, 0.00017460074741393328, 0.00016765705368015915, 0.0001754630939103663, 0.0000024268292690976523 ]
{ "id": 12, "code_window": [ "\n", "\t\t\t\tquery.folderQueries = folderQueries.filter((q, index) => exists[index]);\n", "\t\t\t\tlet event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete>;\n", "\t\t\t\tevent = this.raw.fileSearch(query);\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tlet event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete>;\n", "\t\tevent = this.raw.fileSearch(query);\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 115 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as path from 'vs/base/common/path'; import { ILogService, LogLevel, AbstractLogService } from 'vs/platform/log/common/log'; import * as spdlog from 'spdlog'; async function createSpdLogLogger(processName: string, logsFolder: string): Promise<spdlog.RotatingLogger | null> { // Do not crash if spdlog cannot be loaded try { const _spdlog = await import('spdlog'); _spdlog.setAsyncMode(8192, 500); const logfilePath = path.join(logsFolder, `${processName}.log`); return _spdlog.createRotatingLoggerAsync(processName, logfilePath, 1024 * 1024 * 5, 6); } catch (e) { console.error(e); } return null; } export function createRotatingLogger(name: string, filename: string, filesize: number, filecount: number): spdlog.RotatingLogger { const _spdlog: typeof spdlog = require.__$__nodeRequire('spdlog'); return _spdlog.createRotatingLogger(name, filename, filesize, filecount); } interface ILog { level: LogLevel; message: string; } function log(logger: spdlog.RotatingLogger, level: LogLevel, message: string): void { switch (level) { case LogLevel.Trace: logger.trace(message); break; case LogLevel.Debug: logger.debug(message); break; case LogLevel.Info: logger.info(message); break; case LogLevel.Warning: logger.warn(message); break; case LogLevel.Error: logger.error(message); break; case LogLevel.Critical: logger.critical(message); break; default: throw new Error('Invalid log level'); } } export class SpdLogService extends AbstractLogService implements ILogService { _serviceBrand: undefined; private buffer: ILog[] = []; private _loggerCreationPromise: Promise<void> | undefined = undefined; private _logger: spdlog.RotatingLogger | undefined; constructor(private readonly name: string, private readonly logsFolder: string, level: LogLevel) { super(); this.setLevel(level); this._createSpdLogLogger(); this._register(this.onDidChangeLogLevel(level => { if (this._logger) { this._logger.setLevel(level); } })); } private _createSpdLogLogger(): Promise<void> { if (!this._loggerCreationPromise) { this._loggerCreationPromise = createSpdLogLogger(this.name, this.logsFolder) .then(logger => { if (logger) { this._logger = logger; this._logger.setLevel(this.getLevel()); for (const { level, message } of this.buffer) { log(this._logger, level, message); } this.buffer = []; } }); } return this._loggerCreationPromise; } private _log(level: LogLevel, message: string): void { if (this._logger) { log(this._logger, level, message); } else if (this.getLevel() <= level) { this.buffer.push({ level, message }); } } trace(message: string, ...args: any[]): void { if (this.getLevel() <= LogLevel.Trace) { this._log(LogLevel.Trace, this.format([message, ...args])); } } debug(message: string, ...args: any[]): void { if (this.getLevel() <= LogLevel.Debug) { this._log(LogLevel.Debug, this.format([message, ...args])); } } info(message: string, ...args: any[]): void { if (this.getLevel() <= LogLevel.Info) { this._log(LogLevel.Info, this.format([message, ...args])); } } warn(message: string, ...args: any[]): void { if (this.getLevel() <= LogLevel.Warning) { this._log(LogLevel.Warning, this.format([message, ...args])); } } error(message: string | Error, ...args: any[]): void { if (this.getLevel() <= LogLevel.Error) { if (message instanceof Error) { const array = Array.prototype.slice.call(arguments) as any[]; array[0] = message.stack; this._log(LogLevel.Error, this.format(array)); } else { this._log(LogLevel.Error, this.format([message, ...args])); } } } critical(message: string | Error, ...args: any[]): void { if (this.getLevel() <= LogLevel.Critical) { this._log(LogLevel.Critical, this.format([message, ...args])); } } flush(): void { if (this._logger) { this._logger.flush(); } else if (this._loggerCreationPromise) { this._loggerCreationPromise.then(() => this.flush()); } } dispose(): void { if (this._logger) { this.disposeLogger(); } else if (this._loggerCreationPromise) { this._loggerCreationPromise.then(() => this.disposeLogger()); } this._loggerCreationPromise = undefined; } private disposeLogger(): void { if (this._logger) { this._logger.drop(); this._logger = undefined; } } private format(args: any): string { let result = ''; for (let i = 0; i < args.length; i++) { let a = args[i]; if (typeof a === 'object') { try { a = JSON.stringify(a); } catch (e) { } } result += (i > 0 ? ' ' : '') + a; } return result; } }
src/vs/platform/log/node/spdlogService.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.0001789690722944215, 0.00017156315152533352, 0.00016199049423448741, 0.00017223338363692164, 0.0000043315335460647475 ]
{ "id": 12, "code_window": [ "\n", "\t\t\t\tquery.folderQueries = folderQueries.filter((q, index) => exists[index]);\n", "\t\t\t\tlet event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete>;\n", "\t\t\t\tevent = this.raw.fileSearch(query);\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tlet event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete>;\n", "\t\tevent = this.raw.fileSearch(query);\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 115 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ const VERSION = 1; const rootPath = self.location.pathname.replace(/\/service-worker.js$/, ''); /** * Root path for resources */ const resourceRoot = rootPath + '/vscode-resource'; const resolveTimeout = 30000; /** * @template T * @typedef {{ * resolve: (x: T) => void, * promise: Promise<T> * }} RequestStoreEntry */ /** * @template T */ class RequestStore { constructor() { /** @type {Map<string, RequestStoreEntry<T>>} */ this.map = new Map(); } /** * @param {string} webviewId * @param {string} path * @return {Promise<T> | undefined} */ get(webviewId, path) { const entry = this.map.get(this._key(webviewId, path)); return entry && entry.promise; } /** * @param {string} webviewId * @param {string} path * @returns {Promise<T>} */ create(webviewId, path) { const existing = this.get(webviewId, path); if (existing) { return existing; } let resolve; const promise = new Promise(r => resolve = r); const entry = { resolve, promise }; const key = this._key(webviewId, path); this.map.set(key, entry); const dispose = () => { clearTimeout(timeout); const existingEntry = this.map.get(key); if (existingEntry === entry) { return this.map.delete(key); } }; const timeout = setTimeout(dispose, resolveTimeout); return promise; } /** * @param {string} webviewId * @param {string} path * @param {T} result * @return {boolean} */ resolve(webviewId, path, result) { const entry = this.map.get(this._key(webviewId, path)); if (!entry) { return false; } entry.resolve(result); return true; } /** * @param {string} webviewId * @param {string} path * @return {string} */ _key(webviewId, path) { return `${webviewId}@@@${path}`; } } /** * Map of requested paths to responses. * * @type {RequestStore<{ body: any, mime: string } | undefined>} */ const resourceRequestStore = new RequestStore(); /** * Map of requested localhost origins to optional redirects. * * @type {RequestStore<string | undefined>} */ const localhostRequestStore = new RequestStore(); const notFound = () => new Response('Not Found', { status: 404, }); self.addEventListener('message', async (event) => { switch (event.data.channel) { case 'version': { self.clients.get(event.source.id).then(client => { if (client) { client.postMessage({ channel: 'version', version: VERSION }); } }); return; } case 'did-load-resource': { const webviewId = getWebviewIdForClient(event.source); const data = event.data.data; const response = data.status === 200 ? { body: data.data, mime: data.mime } : undefined; if (!resourceRequestStore.resolve(webviewId, data.path, response)) { console.log('Could not resolve unknown resource', data.path); } return; } case 'did-load-localhost': { const webviewId = getWebviewIdForClient(event.source); const data = event.data.data; if (!localhostRequestStore.resolve(webviewId, data.origin, data.location)) { console.log('Could not resolve unknown localhost', data.origin); } return; } } console.log('Unknown message'); }); self.addEventListener('fetch', (event) => { const requestUrl = new URL(event.request.url); // See if it's a resource request if (requestUrl.origin === self.origin && requestUrl.pathname.startsWith(resourceRoot + '/')) { return event.respondWith(processResourceRequest(event, requestUrl)); } // See if it's a localhost request if (requestUrl.origin !== self.origin && requestUrl.host.match(/^localhost:(\d+)$/)) { return event.respondWith(processLocalhostRequest(event, requestUrl)); } }); self.addEventListener('install', (event) => { event.waitUntil(self.skipWaiting()); // Activate worker immediately }); self.addEventListener('activate', (event) => { event.waitUntil(self.clients.claim()); // Become available to all pages }); async function processResourceRequest(event, requestUrl) { const client = await self.clients.get(event.clientId); if (!client) { console.log('Could not find inner client for request'); return notFound(); } const webviewId = getWebviewIdForClient(client); const resourcePath = requestUrl.pathname.startsWith(resourceRoot + '/') ? requestUrl.pathname.slice(resourceRoot.length) : requestUrl.pathname; function resolveResourceEntry(entry) { if (!entry) { return notFound(); } return new Response(entry.body, { status: 200, headers: { 'Content-Type': entry.mime } }); } const parentClient = await getOuterIframeClient(webviewId); if (!parentClient) { console.log('Could not find parent client for request'); return notFound(); } // Check if we've already resolved this request const existing = resourceRequestStore.get(webviewId, resourcePath); if (existing) { return existing.then(resolveResourceEntry); } parentClient.postMessage({ channel: 'load-resource', path: resourcePath }); return resourceRequestStore.create(webviewId, resourcePath) .then(resolveResourceEntry); } /** * @param {*} event * @param {URL} requestUrl */ async function processLocalhostRequest(event, requestUrl) { const client = await self.clients.get(event.clientId); if (!client) { // This is expected when requesting resources on other localhost ports // that are not spawned by vs code return undefined; } const webviewId = getWebviewIdForClient(client); const origin = requestUrl.origin; const resolveRedirect = redirectOrigin => { if (!redirectOrigin) { return fetch(event.request); } const location = event.request.url.replace(new RegExp(`^${requestUrl.origin}(/|$)`), `${redirectOrigin}$1`); return new Response(null, { status: 302, headers: { Location: location } }); }; const parentClient = await getOuterIframeClient(webviewId); if (!parentClient) { console.log('Could not find parent client for request'); return notFound(); } // Check if we've already resolved this request const existing = localhostRequestStore.get(webviewId, origin); if (existing) { return existing.then(resolveRedirect); } parentClient.postMessage({ channel: 'load-localhost', origin: origin }); return localhostRequestStore.create(webviewId, origin) .then(resolveRedirect); } function getWebviewIdForClient(client) { const requesterClientUrl = new URL(client.url); return requesterClientUrl.search.match(/\bid=([a-z0-9-]+)/i)[1]; } async function getOuterIframeClient(webviewId) { const allClients = await self.clients.matchAll({ includeUncontrolled: true }); return allClients.find(client => { const clientUrl = new URL(client.url); return (clientUrl.pathname === `${rootPath}/` || clientUrl.pathname === `${rootPath}/index.html`) && clientUrl.search.match(new RegExp('\\bid=' + webviewId)); }); }
src/vs/workbench/contrib/webview/browser/pre/service-worker.js
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.9693142175674438, 0.11936189979314804, 0.00016614393098279834, 0.00017399739590473473, 0.29973387718200684 ]
{ "id": 13, "code_window": [ "\n", "\t\t\t\tconst onProgress = (p: ISearchProgressItem) => {\n", "\t\t\t\t\tif (!isFileMatch(p)) {\n", "\t\t\t\t\t\t// Should only be for logs\n", "\t\t\t\t\t\tthis.logService.debug('SearchService#search', p.message);\n", "\t\t\t\t\t}\n", "\t\t\t\t};\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tconst onProgress = (p: ISearchProgressItem) => {\n", "\t\t\tif (!isFileMatch(p)) {\n", "\t\t\t\t// Should only be for logs\n", "\t\t\t\tthis.logService.debug('SearchService#search', p.message);\n", "\t\t\t}\n", "\t\t};\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 119 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { getPathFromAmdModule } from 'vs/base/common/amd'; import { CancellationToken } from 'vs/base/common/cancellation'; import { canceled } from 'vs/base/common/errors'; import { Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { URI as uri } from 'vs/base/common/uri'; import { getNextTickChannel } from 'vs/base/parts/ipc/common/ipc'; import { Client, IIPCOptions } from 'vs/base/parts/ipc/node/ipc.cp'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IDebugParams, IEnvironmentService } from 'vs/platform/environment/common/environment'; import { parseSearchPort, INativeEnvironmentService } from 'vs/platform/environment/node/environmentService'; import { IFileService } from 'vs/platform/files/common/files'; import { ILogService } from 'vs/platform/log/common/log'; import { FileMatch, IFileMatch, IFileQuery, IProgressMessage, IRawSearchService, ISearchComplete, ISearchConfiguration, ISearchProgressItem, ISearchResultProvider, ISerializedFileMatch, ISerializedSearchComplete, ISerializedSearchProgressItem, isSerializedSearchComplete, isSerializedSearchSuccess, ITextQuery, ISearchService, isFileMatch } from 'vs/workbench/services/search/common/search'; import { SearchChannelClient } from './searchIpc'; import { SearchService } from 'vs/workbench/services/search/common/searchService'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; export class LocalSearchService extends SearchService { constructor( @IModelService modelService: IModelService, @IEditorService editorService: IEditorService, @ITelemetryService telemetryService: ITelemetryService, @ILogService logService: ILogService, @IExtensionService extensionService: IExtensionService, @IFileService fileService: IFileService, @IEnvironmentService readonly environmentService: INativeEnvironmentService, @IInstantiationService readonly instantiationService: IInstantiationService ) { super(modelService, editorService, telemetryService, logService, extensionService, fileService); this.diskSearch = instantiationService.createInstance(DiskSearch, !environmentService.isBuilt || environmentService.verbose, parseSearchPort(environmentService.args, environmentService.isBuilt)); } } export class DiskSearch implements ISearchResultProvider { private raw: IRawSearchService; constructor( verboseLogging: boolean, searchDebug: IDebugParams | undefined, @ILogService private readonly logService: ILogService, @IConfigurationService private readonly configService: IConfigurationService, @IFileService private readonly fileService: IFileService ) { const timeout = this.configService.getValue<ISearchConfiguration>().search.maintainFileSearchCache ? Number.MAX_VALUE : 60 * 60 * 1000; const opts: IIPCOptions = { serverName: 'Search', timeout, args: ['--type=searchService'], // See https://github.com/Microsoft/vscode/issues/27665 // Pass in fresh execArgv to the forked process such that it doesn't inherit them from `process.execArgv`. // e.g. Launching the extension host process with `--inspect-brk=xxx` and then forking a process from the extension host // results in the forked process inheriting `--inspect-brk=xxx`. freshExecArgv: true, env: { AMD_ENTRYPOINT: 'vs/workbench/services/search/node/searchApp', PIPE_LOGGING: 'true', VERBOSE_LOGGING: verboseLogging }, useQueue: true }; if (searchDebug) { if (searchDebug.break && searchDebug.port) { opts.debugBrk = searchDebug.port; } else if (!searchDebug.break && searchDebug.port) { opts.debug = searchDebug.port; } } const client = new Client( getPathFromAmdModule(require, 'bootstrap-fork'), opts); const channel = getNextTickChannel(client.getChannel('search')); this.raw = new SearchChannelClient(channel); } textSearch(query: ITextQuery, onProgress?: (p: ISearchProgressItem) => void, token?: CancellationToken): Promise<ISearchComplete> { const folderQueries = query.folderQueries || []; return Promise.all(folderQueries.map(q => this.fileService.exists(q.folder))) .then(exists => { if (token && token.isCancellationRequested) { throw canceled(); } query.folderQueries = folderQueries.filter((q, index) => exists[index]); const event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete> = this.raw.textSearch(query); return DiskSearch.collectResultsFromEvent(event, onProgress, token); }); } fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { const folderQueries = query.folderQueries || []; return Promise.all(folderQueries.map(q => this.fileService.exists(q.folder))) .then(exists => { if (token && token.isCancellationRequested) { throw canceled(); } query.folderQueries = folderQueries.filter((q, index) => exists[index]); let event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete>; event = this.raw.fileSearch(query); const onProgress = (p: ISearchProgressItem) => { if (!isFileMatch(p)) { // Should only be for logs this.logService.debug('SearchService#search', p.message); } }; return DiskSearch.collectResultsFromEvent(event, onProgress, token); }); } /** * Public for test */ static collectResultsFromEvent(event: Event<ISerializedSearchProgressItem | ISerializedSearchComplete>, onProgress?: (p: ISearchProgressItem) => void, token?: CancellationToken): Promise<ISearchComplete> { let result: IFileMatch[] = []; let listener: IDisposable; return new Promise<ISearchComplete>((c, e) => { if (token) { token.onCancellationRequested(() => { if (listener) { listener.dispose(); } e(canceled()); }); } listener = event(ev => { if (isSerializedSearchComplete(ev)) { if (isSerializedSearchSuccess(ev)) { c({ limitHit: ev.limitHit, results: result, stats: ev.stats }); } else { e(ev.error); } listener.dispose(); } else { // Matches if (Array.isArray(ev)) { const fileMatches = ev.map(d => this.createFileMatch(d)); result = result.concat(fileMatches); if (onProgress) { fileMatches.forEach(onProgress); } } // Match else if ((<ISerializedFileMatch>ev).path) { const fileMatch = this.createFileMatch(<ISerializedFileMatch>ev); result.push(fileMatch); if (onProgress) { onProgress(fileMatch); } } // Progress else if (onProgress) { onProgress(<IProgressMessage>ev); } } }); }); } private static createFileMatch(data: ISerializedFileMatch): FileMatch { const fileMatch = new FileMatch(uri.file(data.path)); if (data.results) { // const matches = data.results.filter(resultIsMatch); fileMatch.results.push(...data.results); } return fileMatch; } clearCache(cacheKey: string): Promise<void> { return this.raw.clearCache(cacheKey); } } registerSingleton(ISearchService, LocalSearchService, true);
src/vs/workbench/services/search/node/searchService.ts
1
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.9966806769371033, 0.2841048836708069, 0.00016517171752639115, 0.00037735182559117675, 0.4457780420780182 ]
{ "id": 13, "code_window": [ "\n", "\t\t\t\tconst onProgress = (p: ISearchProgressItem) => {\n", "\t\t\t\t\tif (!isFileMatch(p)) {\n", "\t\t\t\t\t\t// Should only be for logs\n", "\t\t\t\t\t\tthis.logService.debug('SearchService#search', p.message);\n", "\t\t\t\t\t}\n", "\t\t\t\t};\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tconst onProgress = (p: ISearchProgressItem) => {\n", "\t\t\tif (!isFileMatch(p)) {\n", "\t\t\t\t// Should only be for logs\n", "\t\t\t\tthis.logService.debug('SearchService#search', p.message);\n", "\t\t\t}\n", "\t\t};\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 119 }
<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="#C5C5C5"/> </g> <defs> <clipPath id="clip0"> <rect width="53" height="36" fill="white"/> </clipPath> </defs> </svg>
src/vs/editor/standalone/browser/iPadShowKeyboard/keyboard-dark.svg
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.0005705399671569467, 0.00037413625977933407, 0.00017773258150555193, 0.00037413625977933407, 0.00019640369282569736 ]
{ "id": 13, "code_window": [ "\n", "\t\t\t\tconst onProgress = (p: ISearchProgressItem) => {\n", "\t\t\t\t\tif (!isFileMatch(p)) {\n", "\t\t\t\t\t\t// Should only be for logs\n", "\t\t\t\t\t\tthis.logService.debug('SearchService#search', p.message);\n", "\t\t\t\t\t}\n", "\t\t\t\t};\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tconst onProgress = (p: ISearchProgressItem) => {\n", "\t\t\tif (!isFileMatch(p)) {\n", "\t\t\t\t// Should only be for logs\n", "\t\t\t\tthis.logService.debug('SearchService#search', p.message);\n", "\t\t\t}\n", "\t\t};\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 119 }
/*--------------------------------------------------------------------------------------------- * 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!./media/editordroptarget'; import { LocalSelectionTransfer, DraggedEditorIdentifier, ResourcesDropHandler, DraggedEditorGroupIdentifier, DragAndDropObserver, containsDragType } from 'vs/workbench/browser/dnd'; import { addDisposableListener, EventType, EventHelper, isAncestor, toggleClass, addClass, removeClass } from 'vs/base/browser/dom'; import { IEditorGroupsAccessor, EDITOR_TITLE_HEIGHT, IEditorGroupView, getActiveTextEditorOptions } from 'vs/workbench/browser/parts/editor/editor'; import { EDITOR_DRAG_AND_DROP_BACKGROUND } from 'vs/workbench/common/theme'; import { IThemeService, Themable } from 'vs/platform/theme/common/themeService'; import { activeContrastBorder } from 'vs/platform/theme/common/colorRegistry'; import { IEditorIdentifier, EditorInput, EditorOptions } from 'vs/workbench/common/editor'; import { isMacintosh, isWeb } from 'vs/base/common/platform'; import { GroupDirection, MergeGroupMode } from 'vs/workbench/services/editor/common/editorGroupsService'; import { toDisposable } from 'vs/base/common/lifecycle'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { RunOnceScheduler } from 'vs/base/common/async'; import { DataTransfers } from 'vs/base/browser/dnd'; import { VSBuffer } from 'vs/base/common/buffer'; import { IFileDialogService } from 'vs/platform/dialogs/common/dialogs'; import { URI } from 'vs/base/common/uri'; import { joinPath } from 'vs/base/common/resources'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; interface IDropOperation { splitDirection?: GroupDirection; } class DropOverlay extends Themable { private static readonly OVERLAY_ID = 'monaco-workbench-editor-drop-overlay'; private container!: HTMLElement; private overlay!: HTMLElement; private currentDropOperation: IDropOperation | undefined; private _disposed: boolean | undefined; private cleanupOverlayScheduler: RunOnceScheduler; private readonly editorTransfer = LocalSelectionTransfer.getInstance<DraggedEditorIdentifier>(); private readonly groupTransfer = LocalSelectionTransfer.getInstance<DraggedEditorGroupIdentifier>(); constructor( private accessor: IEditorGroupsAccessor, private groupView: IEditorGroupView, @IThemeService themeService: IThemeService, @IInstantiationService private instantiationService: IInstantiationService, @IFileDialogService private readonly fileDialogService: IFileDialogService, @IEditorService private readonly editorService: IEditorService ) { super(themeService); this.cleanupOverlayScheduler = this._register(new RunOnceScheduler(() => this.dispose(), 300)); this.create(); } get disposed(): boolean { return !!this._disposed; } private create(): void { const overlayOffsetHeight = this.getOverlayOffsetHeight(); // Container this.container = document.createElement('div'); this.container.id = DropOverlay.OVERLAY_ID; this.container.style.top = `${overlayOffsetHeight}px`; // Parent this.groupView.element.appendChild(this.container); addClass(this.groupView.element, 'dragged-over'); this._register(toDisposable(() => { this.groupView.element.removeChild(this.container); removeClass(this.groupView.element, 'dragged-over'); })); // Overlay this.overlay = document.createElement('div'); addClass(this.overlay, 'editor-group-overlay-indicator'); this.container.appendChild(this.overlay); // Overlay Event Handling this.registerListeners(); // Styles this.updateStyles(); } protected updateStyles(): void { // Overlay drop background this.overlay.style.backgroundColor = this.getColor(EDITOR_DRAG_AND_DROP_BACKGROUND) || ''; // Overlay contrast border (if any) const activeContrastBorderColor = this.getColor(activeContrastBorder); this.overlay.style.outlineColor = activeContrastBorderColor || ''; this.overlay.style.outlineOffset = activeContrastBorderColor ? '-2px' : ''; this.overlay.style.outlineStyle = activeContrastBorderColor ? 'dashed' : ''; this.overlay.style.outlineWidth = activeContrastBorderColor ? '2px' : ''; } private registerListeners(): void { this._register(new DragAndDropObserver(this.container, { onDragEnter: e => undefined, onDragOver: e => { const isDraggingGroup = this.groupTransfer.hasData(DraggedEditorGroupIdentifier.prototype); const isDraggingEditor = this.editorTransfer.hasData(DraggedEditorIdentifier.prototype); // Update the dropEffect to "copy" if there is no local data to be dragged because // in that case we can only copy the data into and not move it from its source if (!isDraggingEditor && !isDraggingGroup && e.dataTransfer) { e.dataTransfer.dropEffect = 'copy'; } // Find out if operation is valid let isCopy = true; if (isDraggingGroup) { isCopy = this.isCopyOperation(e); } else if (isDraggingEditor) { const data = this.editorTransfer.getData(DraggedEditorIdentifier.prototype); if (Array.isArray(data)) { isCopy = this.isCopyOperation(e, data[0].identifier); } } if (!isCopy) { const sourceGroupView = this.findSourceGroupView(); if (sourceGroupView === this.groupView) { if (isDraggingGroup || (isDraggingEditor && sourceGroupView.count < 2)) { this.hideOverlay(); return; // do not allow to drop group/editor on itself if this results in an empty group } } } // Position overlay this.positionOverlay(e.offsetX, e.offsetY, isDraggingGroup); // Make sure to stop any running cleanup scheduler to remove the overlay if (this.cleanupOverlayScheduler.isScheduled()) { this.cleanupOverlayScheduler.cancel(); } }, onDragLeave: e => this.dispose(), onDragEnd: e => this.dispose(), onDrop: e => { EventHelper.stop(e, true); // Dispose overlay this.dispose(); // Handle drop if we have a valid operation if (this.currentDropOperation) { this.handleDrop(e, this.currentDropOperation.splitDirection); } } })); this._register(addDisposableListener(this.container, EventType.MOUSE_OVER, () => { // Under some circumstances we have seen reports where the drop overlay is not being // cleaned up and as such the editor area remains under the overlay so that you cannot // type into the editor anymore. This seems related to using VMs and DND via host and // guest OS, though some users also saw it without VMs. // To protect against this issue we always destroy the overlay as soon as we detect a // mouse event over it. The delay is used to guarantee we are not interfering with the // actual DROP event that can also trigger a mouse over event. if (!this.cleanupOverlayScheduler.isScheduled()) { this.cleanupOverlayScheduler.schedule(); } })); } private findSourceGroupView(): IEditorGroupView | undefined { // Check for group transfer if (this.groupTransfer.hasData(DraggedEditorGroupIdentifier.prototype)) { const data = this.groupTransfer.getData(DraggedEditorGroupIdentifier.prototype); if (Array.isArray(data)) { return this.accessor.getGroup(data[0].identifier); } } // Check for editor transfer else if (this.editorTransfer.hasData(DraggedEditorIdentifier.prototype)) { const data = this.editorTransfer.getData(DraggedEditorIdentifier.prototype); if (Array.isArray(data)) { return this.accessor.getGroup(data[0].identifier.groupId); } } return undefined; } private handleDrop(event: DragEvent, splitDirection?: GroupDirection): void { // Determine target group const ensureTargetGroup = () => { let targetGroup: IEditorGroupView; if (typeof splitDirection === 'number') { targetGroup = this.accessor.addGroup(this.groupView, splitDirection); } else { targetGroup = this.groupView; } return targetGroup; }; // Check for group transfer if (this.groupTransfer.hasData(DraggedEditorGroupIdentifier.prototype)) { const data = this.groupTransfer.getData(DraggedEditorGroupIdentifier.prototype); if (Array.isArray(data)) { const draggedEditorGroup = data[0].identifier; // Return if the drop is a no-op const sourceGroup = this.accessor.getGroup(draggedEditorGroup); if (sourceGroup) { if (typeof splitDirection !== 'number' && sourceGroup === this.groupView) { return; } // Split to new group let targetGroup: IEditorGroupView | undefined; if (typeof splitDirection === 'number') { if (this.isCopyOperation(event)) { targetGroup = this.accessor.copyGroup(sourceGroup, this.groupView, splitDirection); } else { targetGroup = this.accessor.moveGroup(sourceGroup, this.groupView, splitDirection); } } // Merge into existing group else { if (this.isCopyOperation(event)) { targetGroup = this.accessor.mergeGroup(sourceGroup, this.groupView, { mode: MergeGroupMode.COPY_EDITORS }); } else { targetGroup = this.accessor.mergeGroup(sourceGroup, this.groupView); } } if (targetGroup) { this.accessor.activateGroup(targetGroup); } } this.groupTransfer.clearData(DraggedEditorGroupIdentifier.prototype); } } // Check for editor transfer else if (this.editorTransfer.hasData(DraggedEditorIdentifier.prototype)) { const data = this.editorTransfer.getData(DraggedEditorIdentifier.prototype); if (Array.isArray(data)) { const draggedEditor = data[0].identifier; const targetGroup = ensureTargetGroup(); // Return if the drop is a no-op const sourceGroup = this.accessor.getGroup(draggedEditor.groupId); if (sourceGroup) { if (sourceGroup === targetGroup) { return; } // Open in target group const options = getActiveTextEditorOptions(sourceGroup, draggedEditor.editor, EditorOptions.create({ pinned: true, // always pin dropped editor sticky: sourceGroup.isSticky(draggedEditor.editor) // preserve sticky state })); targetGroup.openEditor(draggedEditor.editor, options); // Ensure target has focus targetGroup.focus(); // Close in source group unless we copy const copyEditor = this.isCopyOperation(event, draggedEditor); if (!copyEditor) { sourceGroup.closeEditor(draggedEditor.editor); } } this.editorTransfer.clearData(DraggedEditorIdentifier.prototype); } } // Web: check for file transfer else if (isWeb && containsDragType(event, DataTransfers.FILES)) { let targetGroup: IEditorGroupView | undefined = undefined; const files = event.dataTransfer?.files; if (files) { for (let i = 0; i < files.length; i++) { const file = files.item(i); if (file) { const reader = new FileReader(); reader.readAsArrayBuffer(file); reader.onload = async event => { const name = file.name; if (typeof name === 'string' && event.target?.result instanceof ArrayBuffer) { // Try to come up with a good file path for the untitled // editor by asking the file dialog service for the default let proposedFilePath: URI | undefined = undefined; const defaultFilePath = this.fileDialogService.defaultFilePath(); if (defaultFilePath) { proposedFilePath = joinPath(defaultFilePath, name); } // Open as untitled file with the provided contents const untitledEditor = this.editorService.createEditorInput({ resource: proposedFilePath, forceUntitled: true, contents: VSBuffer.wrap(new Uint8Array(event.target.result)).toString() }); if (!targetGroup) { targetGroup = ensureTargetGroup(); } await targetGroup.openEditor(untitledEditor); } }; } } } } // Check for URI transfer else { const dropHandler = this.instantiationService.createInstance(ResourcesDropHandler, { allowWorkspaceOpen: true /* open workspace instead of file if dropped */ }); dropHandler.handleDrop(event, () => ensureTargetGroup(), targetGroup => { if (targetGroup) { targetGroup.focus(); } }); } } private isCopyOperation(e: DragEvent, draggedEditor?: IEditorIdentifier): boolean { if (draggedEditor?.editor instanceof EditorInput && !draggedEditor.editor.supportsSplitEditor()) { return false; } return (e.ctrlKey && !isMacintosh) || (e.altKey && isMacintosh); } private positionOverlay(mousePosX: number, mousePosY: number, isDraggingGroup: boolean): void { const preferSplitVertically = this.accessor.partOptions.openSideBySideDirection === 'right'; const editorControlWidth = this.groupView.element.clientWidth; const editorControlHeight = this.groupView.element.clientHeight - this.getOverlayOffsetHeight(); let edgeWidthThresholdFactor: number; if (isDraggingGroup) { edgeWidthThresholdFactor = preferSplitVertically ? 0.3 : 0.1; // give larger threshold when dragging group depending on preferred split direction } else { edgeWidthThresholdFactor = 0.1; // 10% threshold to split if dragging editors } let edgeHeightThresholdFactor: number; if (isDraggingGroup) { edgeHeightThresholdFactor = preferSplitVertically ? 0.1 : 0.3; // give larger threshold when dragging group depending on preferred split direction } else { edgeHeightThresholdFactor = 0.1; // 10% threshold to split if dragging editors } const edgeWidthThreshold = editorControlWidth * edgeWidthThresholdFactor; const edgeHeightThreshold = editorControlHeight * edgeHeightThresholdFactor; const splitWidthThreshold = editorControlWidth / 3; // offer to split left/right at 33% const splitHeightThreshold = editorControlHeight / 3; // offer to split up/down at 33% // Enable to debug the drop threshold square // let child = this.overlay.children.item(0) as HTMLElement || this.overlay.appendChild(document.createElement('div')); // child.style.backgroundColor = 'red'; // child.style.position = 'absolute'; // child.style.width = (groupViewWidth - (2 * edgeWidthThreshold)) + 'px'; // child.style.height = (groupViewHeight - (2 * edgeHeightThreshold)) + 'px'; // child.style.left = edgeWidthThreshold + 'px'; // child.style.top = edgeHeightThreshold + 'px'; // No split if mouse is above certain threshold in the center of the view let splitDirection: GroupDirection | undefined; if ( mousePosX > edgeWidthThreshold && mousePosX < editorControlWidth - edgeWidthThreshold && mousePosY > edgeHeightThreshold && mousePosY < editorControlHeight - edgeHeightThreshold ) { splitDirection = undefined; } // Offer to split otherwise else { // User prefers to split vertically: offer a larger hitzone // for this direction like so: // ---------------------------------------------- // | | SPLIT UP | | // | SPLIT |-----------------------| SPLIT | // | | MERGE | | // | LEFT |-----------------------| RIGHT | // | | SPLIT DOWN | | // ---------------------------------------------- if (preferSplitVertically) { if (mousePosX < splitWidthThreshold) { splitDirection = GroupDirection.LEFT; } else if (mousePosX > splitWidthThreshold * 2) { splitDirection = GroupDirection.RIGHT; } else if (mousePosY < editorControlHeight / 2) { splitDirection = GroupDirection.UP; } else { splitDirection = GroupDirection.DOWN; } } // User prefers to split horizontally: offer a larger hitzone // for this direction like so: // ---------------------------------------------- // | SPLIT UP | // |--------------------------------------------| // | SPLIT LEFT | MERGE | SPLIT RIGHT | // |--------------------------------------------| // | SPLIT DOWN | // ---------------------------------------------- else { if (mousePosY < splitHeightThreshold) { splitDirection = GroupDirection.UP; } else if (mousePosY > splitHeightThreshold * 2) { splitDirection = GroupDirection.DOWN; } else if (mousePosX < editorControlWidth / 2) { splitDirection = GroupDirection.LEFT; } else { splitDirection = GroupDirection.RIGHT; } } } // Draw overlay based on split direction switch (splitDirection) { case GroupDirection.UP: this.doPositionOverlay({ top: '0', left: '0', width: '100%', height: '50%' }); break; case GroupDirection.DOWN: this.doPositionOverlay({ top: '50%', left: '0', width: '100%', height: '50%' }); break; case GroupDirection.LEFT: this.doPositionOverlay({ top: '0', left: '0', width: '50%', height: '100%' }); break; case GroupDirection.RIGHT: this.doPositionOverlay({ top: '0', left: '50%', width: '50%', height: '100%' }); break; default: this.doPositionOverlay({ top: '0', left: '0', width: '100%', height: '100%' }); } // Make sure the overlay is visible now this.overlay.style.opacity = '1'; // Enable transition after a timeout to prevent initial animation setTimeout(() => addClass(this.overlay, 'overlay-move-transition'), 0); // Remember as current split direction this.currentDropOperation = { splitDirection }; } private doPositionOverlay(options: { top: string, left: string, width: string, height: string }): void { // Container const offsetHeight = this.getOverlayOffsetHeight(); if (offsetHeight) { this.container.style.height = `calc(100% - ${offsetHeight}px)`; } else { this.container.style.height = '100%'; } // Overlay this.overlay.style.top = options.top; this.overlay.style.left = options.left; this.overlay.style.width = options.width; this.overlay.style.height = options.height; } private getOverlayOffsetHeight(): number { if (!this.groupView.isEmpty && this.accessor.partOptions.showTabs) { return EDITOR_TITLE_HEIGHT; // show overlay below title if group shows tabs } return 0; } private hideOverlay(): void { // Reset overlay this.doPositionOverlay({ top: '0', left: '0', width: '100%', height: '100%' }); this.overlay.style.opacity = '0'; removeClass(this.overlay, 'overlay-move-transition'); // Reset current operation this.currentDropOperation = undefined; } contains(element: HTMLElement): boolean { return element === this.container || element === this.overlay; } dispose(): void { super.dispose(); this._disposed = true; } } export interface EditorDropTargetDelegate { groupContainsPredicate?(groupView: IEditorGroupView): boolean; } export class EditorDropTarget extends Themable { private _overlay?: DropOverlay; private counter = 0; private readonly editorTransfer = LocalSelectionTransfer.getInstance<DraggedEditorIdentifier>(); private readonly groupTransfer = LocalSelectionTransfer.getInstance<DraggedEditorGroupIdentifier>(); constructor( private accessor: IEditorGroupsAccessor, private container: HTMLElement, private readonly delegate: EditorDropTargetDelegate, @IThemeService themeService: IThemeService, @IInstantiationService private readonly instantiationService: IInstantiationService ) { super(themeService); this.registerListeners(); } private get overlay(): DropOverlay | undefined { if (this._overlay && !this._overlay.disposed) { return this._overlay; } return undefined; } private registerListeners(): void { this._register(addDisposableListener(this.container, EventType.DRAG_ENTER, e => this.onDragEnter(e))); this._register(addDisposableListener(this.container, EventType.DRAG_LEAVE, () => this.onDragLeave())); [this.container, window].forEach(node => this._register(addDisposableListener(node as HTMLElement, EventType.DRAG_END, () => this.onDragEnd()))); } private onDragEnter(event: DragEvent): void { this.counter++; // Validate transfer if ( !this.editorTransfer.hasData(DraggedEditorIdentifier.prototype) && !this.groupTransfer.hasData(DraggedEditorGroupIdentifier.prototype) && event.dataTransfer && !event.dataTransfer.types.length // see https://github.com/Microsoft/vscode/issues/25789 ) { event.dataTransfer.dropEffect = 'none'; return; // unsupported transfer } // Signal DND start this.updateContainer(true); const target = event.target as HTMLElement; if (target) { // Somehow we managed to move the mouse quickly out of the current overlay, so destroy it if (this.overlay && !this.overlay.contains(target)) { this.disposeOverlay(); } // Create overlay over target if (!this.overlay) { const targetGroupView = this.findTargetGroupView(target); if (targetGroupView) { this._overlay = this.instantiationService.createInstance(DropOverlay, this.accessor, targetGroupView); } } } } private onDragLeave(): void { this.counter--; if (this.counter === 0) { this.updateContainer(false); } } private onDragEnd(): void { this.counter = 0; this.updateContainer(false); this.disposeOverlay(); } private findTargetGroupView(child: HTMLElement): IEditorGroupView | undefined { const groups = this.accessor.groups; return groups.find(groupView => isAncestor(child, groupView.element) || this.delegate.groupContainsPredicate?.(groupView)); } private updateContainer(isDraggedOver: boolean): void { toggleClass(this.container, 'dragged-over', isDraggedOver); } dispose(): void { super.dispose(); this.disposeOverlay(); } private disposeOverlay(): void { if (this.overlay) { this.overlay.dispose(); this._overlay = undefined; } } }
src/vs/workbench/browser/parts/editor/editorDropTarget.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.0001778378791641444, 0.0001729293289827183, 0.00016634493658784777, 0.00017304626817349344, 0.0000025461545192229096 ]
{ "id": 13, "code_window": [ "\n", "\t\t\t\tconst onProgress = (p: ISearchProgressItem) => {\n", "\t\t\t\t\tif (!isFileMatch(p)) {\n", "\t\t\t\t\t\t// Should only be for logs\n", "\t\t\t\t\t\tthis.logService.debug('SearchService#search', p.message);\n", "\t\t\t\t\t}\n", "\t\t\t\t};\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tconst onProgress = (p: ISearchProgressItem) => {\n", "\t\t\tif (!isFileMatch(p)) {\n", "\t\t\t\t// Should only be for logs\n", "\t\t\t\tthis.logService.debug('SearchService#search', p.message);\n", "\t\t\t}\n", "\t\t};\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 119 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { Registry } from 'vs/platform/registry/common/platform'; import { Extensions as WorkbenchExtensions, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IBulkEditService } from 'vs/editor/browser/services/bulkEditService'; import { WorkspaceEdit } from 'vs/editor/common/modes'; import { BulkEditPane } from 'vs/workbench/contrib/bulkEdit/browser/bulkEditPane'; import { IViewContainersRegistry, Extensions as ViewContainerExtensions, ViewContainerLocation, IViewsRegistry, FocusedViewContext, IViewsService } from 'vs/workbench/common/views'; import { localize } from 'vs/nls'; import { ViewPaneContainer } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { RawContextKey, IContextKeyService, IContextKey, ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput'; import { BulkEditPreviewProvider } from 'vs/workbench/contrib/bulkEdit/browser/bulkEditPreview'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { KeyMod, KeyCode } from 'vs/base/common/keyCodes'; import { WorkbenchListFocusContextKey } from 'vs/platform/list/browser/listService'; import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { URI } from 'vs/base/common/uri'; import { MenuId, registerAction2, Action2 } from 'vs/platform/actions/common/actions'; import { IEditorInput } from 'vs/workbench/common/editor'; import type { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; import Severity from 'vs/base/common/severity'; async function getBulkEditPane(viewsService: IViewsService): Promise<BulkEditPane | undefined> { const view = await viewsService.openView(BulkEditPane.ID, true); if (view instanceof BulkEditPane) { return view; } return undefined; } class UXState { private readonly _activePanel: string | undefined; constructor( @IPanelService private readonly _panelService: IPanelService, @IEditorGroupsService private readonly _editorGroupsService: IEditorGroupsService, ) { this._activePanel = _panelService.getActivePanel()?.getId(); } async restore(): Promise<void> { // (1) restore previous panel if (typeof this._activePanel === 'string') { await this._panelService.openPanel(this._activePanel); } else { this._panelService.hideActivePanel(); } // (2) close preview editors for (let group of this._editorGroupsService.groups) { let previewEditors: IEditorInput[] = []; for (let input of group.editors) { let resource: URI | undefined; if (input instanceof DiffEditorInput) { resource = input.modifiedInput.resource; } else { resource = input.resource; } if (resource?.scheme === BulkEditPreviewProvider.Schema) { previewEditors.push(input); } } if (previewEditors.length) { group.closeEditors(previewEditors, { preserveFocus: true }); } } } } class PreviewSession { constructor( readonly uxState: UXState, readonly cts: CancellationTokenSource = new CancellationTokenSource(), ) { } } class BulkEditPreviewContribution { static readonly ctxEnabled = new RawContextKey('refactorPreview.enabled', false); private readonly _ctxEnabled: IContextKey<boolean>; private _activeSession: PreviewSession | undefined; constructor( @IPanelService private readonly _panelService: IPanelService, @IViewsService private readonly _viewsService: IViewsService, @IEditorGroupsService private readonly _editorGroupsService: IEditorGroupsService, @IDialogService private readonly _dialogService: IDialogService, @IBulkEditService bulkEditService: IBulkEditService, @IContextKeyService contextKeyService: IContextKeyService, ) { bulkEditService.setPreviewHandler((edit) => this._previewEdit(edit)); this._ctxEnabled = BulkEditPreviewContribution.ctxEnabled.bindTo(contextKeyService); } private async _previewEdit(edit: WorkspaceEdit) { this._ctxEnabled.set(true); const uxState = this._activeSession?.uxState ?? new UXState(this._panelService, this._editorGroupsService); const view = await getBulkEditPane(this._viewsService); if (!view) { this._ctxEnabled.set(false); return edit; } // check for active preview session and let the user decide if (view.hasInput()) { const choice = await this._dialogService.show( Severity.Info, localize('overlap', "Another refactoring is being previewed."), [localize('cancel', "Cancel"), localize('continue', "Continue")], { detail: localize('detail', "Press 'Continue' to discard the previous refactoring and continue with the current refactoring.") } ); if (choice.choice === 0) { // this refactoring is being cancelled return { edits: [] }; } } // session let session: PreviewSession; if (this._activeSession) { this._activeSession.cts.dispose(true); session = new PreviewSession(uxState); } else { session = new PreviewSession(uxState); } this._activeSession = session; // the actual work... try { const newEditOrUndefined = await view.setInput(edit, session.cts.token); if (!newEditOrUndefined) { return { edits: [] }; } return newEditOrUndefined; } finally { // restore UX state if (this._activeSession === session) { await this._activeSession.uxState.restore(); this._activeSession.cts.dispose(); this._ctxEnabled.set(false); this._activeSession = undefined; } } } } // CMD: accept registerAction2(class ApplyAction extends Action2 { constructor() { super({ id: 'refactorPreview.apply', title: { value: localize('apply', "Apply Refactoring"), original: 'Apply Refactoring' }, category: localize('cat', "Refactor Preview"), icon: { id: 'codicon/check' }, precondition: ContextKeyExpr.and(BulkEditPreviewContribution.ctxEnabled, BulkEditPane.ctxHasCheckedChanges), menu: [{ id: MenuId.BulkEditTitle, group: 'navigation' }, { id: MenuId.BulkEditContext, order: 1 }], keybinding: { weight: KeybindingWeight.EditorContrib - 10, when: ContextKeyExpr.and(BulkEditPreviewContribution.ctxEnabled, FocusedViewContext.isEqualTo(BulkEditPane.ID)), primary: KeyMod.Shift + KeyCode.Enter, } }); } async run(accessor: ServicesAccessor): Promise<any> { const viewsService = accessor.get(IViewsService); const view = await getBulkEditPane(viewsService); if (view) { view.accept(); } } }); // CMD: discard registerAction2(class DiscardAction extends Action2 { constructor() { super({ id: 'refactorPreview.discard', title: { value: localize('Discard', "Discard Refactoring"), original: 'Discard Refactoring' }, category: localize('cat', "Refactor Preview"), icon: { id: 'codicon/clear-all' }, precondition: BulkEditPreviewContribution.ctxEnabled, menu: [{ id: MenuId.BulkEditTitle, group: 'navigation' }, { id: MenuId.BulkEditContext, order: 2 }] }); } async run(accessor: ServicesAccessor): Promise<void> { const viewsService = accessor.get(IViewsService); const view = await getBulkEditPane(viewsService); if (view) { view.discard(); } } }); // CMD: toggle change registerAction2(class ToggleAction extends Action2 { constructor() { super({ id: 'refactorPreview.toggleCheckedState', title: { value: localize('toogleSelection', "Toggle Change"), original: 'Toggle Change' }, category: localize('cat', "Refactor Preview"), precondition: BulkEditPreviewContribution.ctxEnabled, keybinding: { weight: KeybindingWeight.WorkbenchContrib, when: WorkbenchListFocusContextKey, primary: KeyCode.Space, }, menu: { id: MenuId.BulkEditContext, group: 'navigation' } }); } async run(accessor: ServicesAccessor): Promise<void> { const viewsService = accessor.get(IViewsService); const view = await getBulkEditPane(viewsService); if (view) { view.toggleChecked(); } } }); // CMD: toggle category registerAction2(class GroupByFile extends Action2 { constructor() { super({ id: 'refactorPreview.groupByFile', title: { value: localize('groupByFile', "Group Changes By File"), original: 'Group Changes By File' }, category: localize('cat', "Refactor Preview"), icon: { id: 'codicon/ungroup-by-ref-type' }, precondition: ContextKeyExpr.and(BulkEditPane.ctxHasCategories, BulkEditPane.ctxGroupByFile.negate(), BulkEditPreviewContribution.ctxEnabled), menu: [{ id: MenuId.BulkEditTitle, when: ContextKeyExpr.and(BulkEditPane.ctxHasCategories, BulkEditPane.ctxGroupByFile.negate()), group: 'navigation', order: 3, }] }); } async run(accessor: ServicesAccessor): Promise<void> { const viewsService = accessor.get(IViewsService); const view = await getBulkEditPane(viewsService); if (view) { view.groupByFile(); } } }); registerAction2(class GroupByType extends Action2 { constructor() { super({ id: 'refactorPreview.groupByType', title: { value: localize('groupByType', "Group Changes By Type"), original: 'Group Changes By Type' }, category: localize('cat', "Refactor Preview"), icon: { id: 'codicon/group-by-ref-type' }, precondition: ContextKeyExpr.and(BulkEditPane.ctxHasCategories, BulkEditPane.ctxGroupByFile, BulkEditPreviewContribution.ctxEnabled), menu: [{ id: MenuId.BulkEditTitle, when: ContextKeyExpr.and(BulkEditPane.ctxHasCategories, BulkEditPane.ctxGroupByFile), group: 'navigation', order: 3 }] }); } async run(accessor: ServicesAccessor): Promise<void> { const viewsService = accessor.get(IViewsService); const view = await getBulkEditPane(viewsService); if (view) { view.groupByType(); } } }); registerAction2(class ToggleGrouping extends Action2 { constructor() { super({ id: 'refactorPreview.toggleGrouping', title: { value: localize('groupByType', "Group Changes By Type"), original: 'Group Changes By Type' }, category: localize('cat', "Refactor Preview"), icon: { id: 'codicon/list-tree' }, toggled: BulkEditPane.ctxGroupByFile.negate(), precondition: ContextKeyExpr.and(BulkEditPane.ctxHasCategories, BulkEditPreviewContribution.ctxEnabled), menu: [{ id: MenuId.BulkEditContext, order: 3 }] }); } async run(accessor: ServicesAccessor): Promise<void> { const viewsService = accessor.get(IViewsService); const view = await getBulkEditPane(viewsService); if (view) { view.toggleGrouping(); } } }); Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution( BulkEditPreviewContribution, LifecyclePhase.Ready ); const container = Registry.as<IViewContainersRegistry>(ViewContainerExtensions.ViewContainersRegistry).registerViewContainer({ id: BulkEditPane.ID, name: localize('panel', "Refactor Preview"), hideIfEmpty: true, ctorDescriptor: new SyncDescriptor( ViewPaneContainer, [BulkEditPane.ID, { mergeViewWithContainerWhenSingleView: true, donotShowContainerTitleWhenMergedWithContainer: true }] ), storageId: BulkEditPane.ID }, ViewContainerLocation.Panel); Registry.as<IViewsRegistry>(ViewContainerExtensions.ViewsRegistry).registerViews([{ id: BulkEditPane.ID, name: localize('panel', "Refactor Preview"), when: BulkEditPreviewContribution.ctxEnabled, ctorDescriptor: new SyncDescriptor(BulkEditPane), }], container);
src/vs/workbench/contrib/bulkEdit/browser/bulkEdit.contribution.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00017720344476401806, 0.00017254897102247924, 0.0001610405888641253, 0.0001735150144668296, 0.0000035973275771539193 ]
{ "id": 14, "code_window": [ "\n", "\t\t\t\treturn DiskSearch.collectResultsFromEvent(event, onProgress, token);\n", "\t\t\t});\n", "\t}\n", "\n", "\t/**\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn DiskSearch.collectResultsFromEvent(event, onProgress, token);\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 126 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as arrays from 'vs/base/common/arrays'; import { CancellationToken } from 'vs/base/common/cancellation'; import { canceled } from 'vs/base/common/errors'; import { Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { keys, ResourceMap, values } from 'vs/base/common/map'; import { Schemas } from 'vs/base/common/network'; import { StopWatch } from 'vs/base/common/stopwatch'; import { URI as uri } from 'vs/base/common/uri'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IFileService } from 'vs/platform/files/common/files'; import { ILogService } from 'vs/platform/log/common/log'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { deserializeSearchError, FileMatch, ICachedSearchStats, IFileMatch, IFileQuery, IFileSearchStats, IFolderQuery, IProgressMessage, ISearchComplete, ISearchEngineStats, ISearchProgressItem, ISearchQuery, ISearchResultProvider, ISearchService, ITextQuery, pathIncludedInQuery, QueryType, SearchError, SearchErrorCode, SearchProviderType, isFileMatch, isProgressMessage } from 'vs/workbench/services/search/common/search'; import { addContextToEditorMatches, editorMatchesToTextSearchResults } from 'vs/workbench/services/search/common/searchHelpers'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { DeferredPromise } from 'vs/base/test/common/utils'; export class SearchService extends Disposable implements ISearchService { _serviceBrand: undefined; protected diskSearch: ISearchResultProvider | null = null; private readonly fileSearchProviders = new Map<string, ISearchResultProvider>(); private readonly textSearchProviders = new Map<string, ISearchResultProvider>(); private deferredFileSearchesByScheme = new Map<string, DeferredPromise<ISearchResultProvider>>(); private deferredTextSearchesByScheme = new Map<string, DeferredPromise<ISearchResultProvider>>(); constructor( private readonly modelService: IModelService, private readonly editorService: IEditorService, private readonly telemetryService: ITelemetryService, private readonly logService: ILogService, private readonly extensionService: IExtensionService, private readonly fileService: IFileService ) { super(); } registerSearchResultProvider(scheme: string, type: SearchProviderType, provider: ISearchResultProvider): IDisposable { let list: Map<string, ISearchResultProvider>; let deferredMap: Map<string, DeferredPromise<ISearchResultProvider>>; if (type === SearchProviderType.file) { list = this.fileSearchProviders; deferredMap = this.deferredFileSearchesByScheme; } else if (type === SearchProviderType.text) { list = this.textSearchProviders; deferredMap = this.deferredTextSearchesByScheme; } else { throw new Error('Unknown SearchProviderType'); } list.set(scheme, provider); if (deferredMap.has(scheme)) { deferredMap.get(scheme)!.complete(provider); deferredMap.delete(scheme); } return toDisposable(() => { list.delete(scheme); }); } async textSearch(query: ITextQuery, token?: CancellationToken, onProgress?: (item: ISearchProgressItem) => void): Promise<ISearchComplete> { // Get local results from dirty/untitled const localResults = this.getLocalResults(query); if (onProgress) { arrays.coalesce([...localResults.results.values()]).forEach(onProgress); } const onProviderProgress = (progress: ISearchProgressItem) => { if (isFileMatch(progress)) { // Match if (!localResults.results.has(progress.resource) && onProgress) { // don't override local results onProgress(progress); } } else if (onProgress) { // Progress onProgress(<IProgressMessage>progress); } if (isProgressMessage(progress)) { this.logService.debug('SearchService#search', progress.message); } }; const otherResults = await this.doSearch(query, token, onProviderProgress); return { ...otherResults, ...{ limitHit: otherResults.limitHit || localResults.limitHit }, results: [...otherResults.results, ...arrays.coalesce([...localResults.results.values()])] }; } fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { return this.doSearch(query, token); } private doSearch(query: ISearchQuery, token?: CancellationToken, onProgress?: (item: ISearchProgressItem) => void): Promise<ISearchComplete> { this.logService.trace('SearchService#search', JSON.stringify(query)); const schemesInQuery = this.getSchemesInQuery(query); const providerActivations: Promise<any>[] = [Promise.resolve(null)]; schemesInQuery.forEach(scheme => providerActivations.push(this.extensionService.activateByEvent(`onSearch:${scheme}`))); providerActivations.push(this.extensionService.activateByEvent('onSearch:file')); const providerPromise = Promise.all(providerActivations) .then(() => this.extensionService.whenInstalledExtensionsRegistered()) .then(() => { // Cancel faster if search was canceled while waiting for extensions if (token && token.isCancellationRequested) { return Promise.reject(canceled()); } const progressCallback = (item: ISearchProgressItem) => { if (token && token.isCancellationRequested) { return; } if (onProgress) { onProgress(item); } }; return this.searchWithProviders(query, progressCallback, token); }) .then(completes => { completes = arrays.coalesce(completes); if (!completes.length) { return { limitHit: false, results: [] }; } return <ISearchComplete>{ limitHit: completes[0] && completes[0].limitHit, stats: completes[0].stats, results: arrays.flatten(completes.map((c: ISearchComplete) => c.results)) }; }); return new Promise((resolve, reject) => { if (token) { token.onCancellationRequested(() => { reject(canceled()); }); } providerPromise.then(resolve, reject); }); } private getSchemesInQuery(query: ISearchQuery): Set<string> { const schemes = new Set<string>(); if (query.folderQueries) { query.folderQueries.forEach(fq => schemes.add(fq.folder.scheme)); } if (query.extraFileResources) { query.extraFileResources.forEach(extraFile => schemes.add(extraFile.scheme)); } return schemes; } private async waitForProvider(queryType: QueryType, scheme: string): Promise<ISearchResultProvider> { let deferredMap: Map<string, DeferredPromise<ISearchResultProvider>> = queryType === QueryType.File ? this.deferredFileSearchesByScheme : this.deferredTextSearchesByScheme; if (deferredMap.has(scheme)) { return deferredMap.get(scheme)!.p; } else { const deferred = new DeferredPromise<ISearchResultProvider>(); deferredMap.set(scheme, deferred); return deferred.p; } } private async searchWithProviders(query: ISearchQuery, onProviderProgress: (progress: ISearchProgressItem) => void, token?: CancellationToken) { const e2eSW = StopWatch.create(false); const diskSearchQueries: IFolderQuery[] = []; const searchPs: Promise<ISearchComplete>[] = []; const fqs = this.groupFolderQueriesByScheme(query); await Promise.all(keys(fqs).map(async scheme => { const schemeFQs = fqs.get(scheme)!; let provider = query.type === QueryType.File ? this.fileSearchProviders.get(scheme) : this.textSearchProviders.get(scheme); if (!provider && scheme === Schemas.file) { diskSearchQueries.push(...schemeFQs); } else { if (!provider) { if (scheme !== Schemas.vscodeRemote) { console.warn(`No search provider registered for scheme: ${scheme}`); return; } console.warn(`No search provider registered for scheme: ${scheme}, waiting`); provider = await this.waitForProvider(query.type, scheme); } const oneSchemeQuery: ISearchQuery = { ...query, ...{ folderQueries: schemeFQs } }; searchPs.push(query.type === QueryType.File ? provider.fileSearch(<IFileQuery>oneSchemeQuery, token) : provider.textSearch(<ITextQuery>oneSchemeQuery, onProviderProgress, token)); } })); const diskSearchExtraFileResources = query.extraFileResources && query.extraFileResources.filter(res => res.scheme === Schemas.file); if (diskSearchQueries.length || diskSearchExtraFileResources) { const diskSearchQuery: ISearchQuery = { ...query, ...{ folderQueries: diskSearchQueries }, extraFileResources: diskSearchExtraFileResources }; if (this.diskSearch) { searchPs.push(diskSearchQuery.type === QueryType.File ? this.diskSearch.fileSearch(diskSearchQuery, token) : this.diskSearch.textSearch(diskSearchQuery, onProviderProgress, token)); } } return Promise.all(searchPs).then(completes => { const endToEndTime = e2eSW.elapsed(); this.logService.trace(`SearchService#search: ${endToEndTime}ms`); completes.forEach(complete => { this.sendTelemetry(query, endToEndTime, complete); }); return completes; }, err => { const endToEndTime = e2eSW.elapsed(); this.logService.trace(`SearchService#search: ${endToEndTime}ms`); const searchError = deserializeSearchError(err.message); this.sendTelemetry(query, endToEndTime, undefined, searchError); throw searchError; }); } private groupFolderQueriesByScheme(query: ISearchQuery): Map<string, IFolderQuery[]> { const queries = new Map<string, IFolderQuery[]>(); query.folderQueries.forEach(fq => { const schemeFQs = queries.get(fq.folder.scheme) || []; schemeFQs.push(fq); queries.set(fq.folder.scheme, schemeFQs); }); return queries; } private sendTelemetry(query: ISearchQuery, endToEndTime: number, complete?: ISearchComplete, err?: SearchError): void { const fileSchemeOnly = query.folderQueries.every(fq => fq.folder.scheme === 'file'); const otherSchemeOnly = query.folderQueries.every(fq => fq.folder.scheme !== 'file'); const scheme = fileSchemeOnly ? 'file' : otherSchemeOnly ? 'other' : 'mixed'; if (query.type === QueryType.File && complete && complete.stats) { const fileSearchStats = complete.stats as IFileSearchStats; if (fileSearchStats.fromCache) { const cacheStats: ICachedSearchStats = fileSearchStats.detailStats as ICachedSearchStats; type CachedSearchCompleteClassifcation = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; resultCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; type: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; sortingTime?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheWasResolved: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; cacheLookupTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheFilterTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheEntryCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type CachedSearchCompleteEvent = { reason?: string; resultCount: number; workspaceFolderCount: number; type: 'fileSearchProvider' | 'searchProcess'; endToEndTime: number; sortingTime?: number; cacheWasResolved: boolean; cacheLookupTime: number; cacheFilterTime: number; cacheEntryCount: number; scheme: string; }; this.telemetryService.publicLog2<CachedSearchCompleteEvent, CachedSearchCompleteClassifcation>('cachedSearchComplete', { reason: query._reason, resultCount: fileSearchStats.resultCount, workspaceFolderCount: query.folderQueries.length, type: fileSearchStats.type, endToEndTime: endToEndTime, sortingTime: fileSearchStats.sortingTime, cacheWasResolved: cacheStats.cacheWasResolved, cacheLookupTime: cacheStats.cacheLookupTime, cacheFilterTime: cacheStats.cacheFilterTime, cacheEntryCount: cacheStats.cacheEntryCount, scheme }); } else { const searchEngineStats: ISearchEngineStats = fileSearchStats.detailStats as ISearchEngineStats; type SearchCompleteClassification = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; resultCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; type: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; sortingTime?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; fileWalkTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; directoriesWalked: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; filesWalked: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cmdTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cmdResultCount?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type SearchCompleteEvent = { reason?: string; resultCount: number; workspaceFolderCount: number; type: 'fileSearchProvider' | 'searchProcess'; endToEndTime: number; sortingTime?: number; fileWalkTime: number directoriesWalked: number; filesWalked: number; cmdTime: number; cmdResultCount?: number; scheme: string; }; this.telemetryService.publicLog2<SearchCompleteEvent, SearchCompleteClassification>('searchComplete', { reason: query._reason, resultCount: fileSearchStats.resultCount, workspaceFolderCount: query.folderQueries.length, type: fileSearchStats.type, endToEndTime: endToEndTime, sortingTime: fileSearchStats.sortingTime, fileWalkTime: searchEngineStats.fileWalkTime, directoriesWalked: searchEngineStats.directoriesWalked, filesWalked: searchEngineStats.filesWalked, cmdTime: searchEngineStats.cmdTime, cmdResultCount: searchEngineStats.cmdResultCount, scheme }); } } else if (query.type === QueryType.Text) { let errorType: string | undefined; if (err) { errorType = err.code === SearchErrorCode.regexParseError ? 'regex' : err.code === SearchErrorCode.unknownEncoding ? 'encoding' : err.code === SearchErrorCode.globParseError ? 'glob' : err.code === SearchErrorCode.invalidLiteral ? 'literal' : err.code === SearchErrorCode.other ? 'other' : 'unknown'; } type TextSearchCompleteClassification = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; error?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; usePCRE2: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type TextSearchCompleteEvent = { reason?: string; workspaceFolderCount: number; endToEndTime: number; scheme: string; error?: string; usePCRE2: boolean; }; this.telemetryService.publicLog2<TextSearchCompleteEvent, TextSearchCompleteClassification>('textSearchComplete', { reason: query._reason, workspaceFolderCount: query.folderQueries.length, endToEndTime: endToEndTime, scheme, error: errorType, usePCRE2: !!query.usePCRE2 }); } } private getLocalResults(query: ITextQuery): { results: ResourceMap<IFileMatch | null>; limitHit: boolean } { const localResults = new ResourceMap<IFileMatch | null>(); let limitHit = false; if (query.type === QueryType.Text) { const models = this.modelService.getModels(); models.forEach((model) => { const resource = model.uri; if (!resource) { return; } if (limitHit) { return; } // Skip files that are not opened as text file if (!this.editorService.isOpen({ resource })) { return; } // Skip search results if (model.getModeId() === 'search-result' && !(query.includePattern && query.includePattern['**/*.code-search'])) { // TODO: untitled search editors will be excluded from search even when include *.code-search is specified return; } // Block walkthrough, webview, etc. if (resource.scheme !== Schemas.untitled && !this.fileService.canHandleResource(resource)) { return; } // Exclude files from the git FileSystemProvider, e.g. to prevent open staged files from showing in search results if (resource.scheme === 'git') { return; } if (!this.matches(resource, query)) { return; // respect user filters } // Use editor API to find matches const askMax = typeof query.maxResults === 'number' ? query.maxResults + 1 : undefined; let matches = model.findMatches(query.contentPattern.pattern, false, !!query.contentPattern.isRegExp, !!query.contentPattern.isCaseSensitive, query.contentPattern.isWordMatch ? query.contentPattern.wordSeparators! : null, false, askMax); if (matches.length) { if (askMax && matches.length >= askMax) { limitHit = true; matches = matches.slice(0, askMax - 1); } const fileMatch = new FileMatch(resource); localResults.set(resource, fileMatch); const textSearchResults = editorMatchesToTextSearchResults(matches, model, query.previewOptions); fileMatch.results = addContextToEditorMatches(textSearchResults, model, query); } else { localResults.set(resource, null); } }); } return { results: localResults, limitHit }; } private matches(resource: uri, query: ITextQuery): boolean { return pathIncludedInQuery(query, resource.fsPath); } clearCache(cacheKey: string): Promise<void> { const clearPs = [ this.diskSearch, ...values(this.fileSearchProviders) ].map(provider => provider && provider.clearCache(cacheKey)); return Promise.all(clearPs) .then(() => { }); } } export class RemoteSearchService extends SearchService { constructor( @IModelService modelService: IModelService, @IEditorService editorService: IEditorService, @ITelemetryService telemetryService: ITelemetryService, @ILogService logService: ILogService, @IExtensionService extensionService: IExtensionService, @IFileService fileService: IFileService ) { super(modelService, editorService, telemetryService, logService, extensionService, fileService); } } registerSingleton(ISearchService, RemoteSearchService, true);
src/vs/workbench/services/search/common/searchService.ts
1
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00019897452148143202, 0.00017288458184339106, 0.0001649575133342296, 0.00017285179637838155, 0.000006040158950781915 ]
{ "id": 14, "code_window": [ "\n", "\t\t\t\treturn DiskSearch.collectResultsFromEvent(event, onProgress, token);\n", "\t\t\t});\n", "\t}\n", "\n", "\t/**\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn DiskSearch.collectResultsFromEvent(event, onProgress, token);\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 126 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; export const IIssueService = createDecorator<IIssueService>('issueService'); // Since data sent through the service is serialized to JSON, functions will be lost, so Color objects // should not be sent as their 'toString' method will be stripped. Instead convert to strings before sending. export interface WindowStyles { backgroundColor?: string; color?: string; } export interface WindowData { styles: WindowStyles; zoomLevel: number; } export const enum IssueType { Bug, PerformanceIssue, FeatureRequest, SettingsSearchIssue } export interface IssueReporterStyles extends WindowStyles { textLinkColor?: string; textLinkActiveForeground?: string; inputBackground?: string; inputForeground?: string; inputBorder?: string; inputErrorBorder?: string; inputErrorBackground?: string; inputErrorForeground?: string; inputActiveBorder?: string; buttonBackground?: string; buttonForeground?: string; buttonHoverBackground?: string; sliderBackgroundColor?: string; sliderHoverColor?: string; sliderActiveColor?: string; } export interface IssueReporterExtensionData { name: string; publisher: string; version: string; id: string; isTheme: boolean; isBuiltin: boolean; displayName: string | undefined; repositoryUrl: string | undefined; bugsUrl: string | undefined; } export interface IssueReporterData extends WindowData { styles: IssueReporterStyles; enabledExtensions: IssueReporterExtensionData[]; issueType?: IssueType; extensionId?: string; readonly issueTitle?: string; readonly issueBody?: string; } export interface ISettingSearchResult { extensionId: string; key: string; score: number; } export interface ISettingsSearchIssueReporterData extends IssueReporterData { issueType: IssueType.SettingsSearchIssue; actualSearchResults: ISettingSearchResult[]; query: string; filterResultCount: number; } export interface IssueReporterFeatures { } export interface ProcessExplorerStyles extends WindowStyles { hoverBackground?: string; hoverForeground?: string; highlightForeground?: string; } export interface ProcessExplorerData extends WindowData { pid: number; styles: ProcessExplorerStyles; } export interface IIssueService { _serviceBrand: undefined; openReporter(data: IssueReporterData): Promise<void>; openProcessExplorer(data: ProcessExplorerData): Promise<void>; getSystemStatus(): Promise<string>; }
src/vs/platform/issue/node/issue.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.0001773861877154559, 0.00017200327420141548, 0.0001691424986347556, 0.0001715062971925363, 0.000002587248900454142 ]
{ "id": 14, "code_window": [ "\n", "\t\t\t\treturn DiskSearch.collectResultsFromEvent(event, onProgress, token);\n", "\t\t\t});\n", "\t}\n", "\n", "\t/**\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn DiskSearch.collectResultsFromEvent(event, onProgress, token);\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 126 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 "@types/events@*": version "3.0.0" resolved "https://registry.yarnpkg.com/@types/events/-/events-3.0.0.tgz#2862f3f58a9a7f7c3e78d79f130dd4d71c25c2a7" integrity sha512-EaObqwIvayI5a8dCzhFrjKzVwKLxjoG9T6Ppd5CEo07LRKfQ8Yokw54r5+Wq7FaBQ+yXRvQAYPrHwya1/UFt9g== "@types/glob@*": version "7.1.1" resolved "https://registry.yarnpkg.com/@types/glob/-/glob-7.1.1.tgz#aa59a1c6e3fbc421e07ccd31a944c30eba521575" integrity sha512-1Bh06cbWJUHMC97acuD6UMG29nMt0Aqz1vF3guLfG+kHHJhy3AyohZFFxYk2f7Q1SQIrNwvncxAE0N/9s70F2w== dependencies: "@types/events" "*" "@types/minimatch" "*" "@types/node" "*" "@types/minimatch@*": version "3.0.3" resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-3.0.3.tgz#3dca0e3f33b200fc7d1139c0cd96c1268cadfd9d" integrity sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA== "@types/[email protected]": version "0.5.1" resolved "https://registry.yarnpkg.com/@types/mkdirp/-/mkdirp-0.5.1.tgz#ea887cd024f691c1ca67cce20b7606b053e43b0f" integrity sha512-XA4vNO6GCBz8Smq0hqSRo4yRWMqr4FPQrWjhJt6nKskzly4/p87SfuJMFYGRyYb6jo2WNIQU2FDBsY5r1BibUA== dependencies: "@types/node" "*" "@types/node@*": version "13.7.0" resolved "https://registry.yarnpkg.com/@types/node/-/node-13.7.0.tgz#b417deda18cf8400f278733499ad5547ed1abec4" integrity sha512-GnZbirvmqZUzMgkFn70c74OQpTTUcCzlhQliTzYjQMqg+hVKcDnxdL19Ne3UdYzdMA/+W3eb646FWn/ZaT1NfQ== "@types/node@^12.11.7": version "12.12.26" resolved "https://registry.yarnpkg.com/@types/node/-/node-12.12.26.tgz#213e153babac0ed169d44a6d919501e68f59dea9" integrity sha512-UmUm94/QZvU5xLcUlNR8hA7Ac+fGpO1EG/a8bcWVz0P0LqtxFmun9Y2bbtuckwGboWJIT70DoWq1r3hb56n3DA== "@types/[email protected]": version "0.0.29" resolved "https://registry.yarnpkg.com/@types/optimist/-/optimist-0.0.29.tgz#a8873580b3a84b69ac1e687323b15fbbeb90479a" integrity sha1-qIc1gLOoS2msHmhzI7Ffu+uQR5o= "@types/[email protected]": version "2.0.2" resolved "https://registry.yarnpkg.com/@types/rimraf/-/rimraf-2.0.2.tgz#7f0fc3cf0ff0ad2a99bb723ae1764f30acaf8b6e" integrity sha512-Hm/bnWq0TCy7jmjeN5bKYij9vw5GrDFWME4IuxV08278NtU/VdGbzsBohcCUJ7+QMqmUq5hpRKB39HeQWJjztQ== dependencies: "@types/glob" "*" "@types/node" "*" "@types/tmp@^0.1.0": version "0.1.0" resolved "https://registry.yarnpkg.com/@types/tmp/-/tmp-0.1.0.tgz#19cf73a7bcf641965485119726397a096f0049bd" integrity sha512-6IwZ9HzWbCq6XoQWhxLpDjuADodH/MKXRUIDFudvgjcVdjFknvmR+DNsoUeer4XPrEnrZs04Jj+kfV9pFsrhmA== balanced-match@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767" integrity sha1-ibTRmasr7kneFk6gK4nORi1xt2c= brace-expansion@^1.1.7: version "1.1.11" resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd" integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA== dependencies: balanced-match "^1.0.0" concat-map "0.0.1" [email protected]: version "0.0.1" resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" integrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s= fs.realpath@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8= glob@^7.1.3: version "7.1.6" resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.6.tgz#141f33b81a7c2492e125594307480c46679278a6" integrity sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA== dependencies: fs.realpath "^1.0.0" inflight "^1.0.4" inherits "2" minimatch "^3.0.4" once "^1.3.0" path-is-absolute "^1.0.0" inflight@^1.0.4: version "1.0.6" resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" integrity sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk= dependencies: once "^1.3.0" wrappy "1" inherits@2: version "2.0.4" resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== minimatch@^3.0.4: version "3.0.4" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083" integrity sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA== dependencies: brace-expansion "^1.1.7" once@^1.3.0: version "1.4.0" resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E= dependencies: wrappy "1" os-tmpdir@~1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274" integrity sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ= path-is-absolute@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18= rimraf@^2.6.1: version "2.7.1" resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.7.1.tgz#35797f13a7fdadc566142c29d4f07ccad483e3ec" integrity sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w== dependencies: glob "^7.1.3" [email protected]: version "0.0.33" resolved "https://registry.yarnpkg.com/tmp/-/tmp-0.0.33.tgz#6d34335889768d21b2bcda0aa277ced3b1bfadf9" integrity sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw== dependencies: os-tmpdir "~1.0.2" [email protected]: version "1.2.2" resolved "https://registry.yarnpkg.com/tree-kill/-/tree-kill-1.2.2.tgz#4ca09a9092c88b73a7cdc5e8a01b507b0790a0cc" integrity sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A== [email protected]: version "3.7.5" resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.7.5.tgz#0692e21f65fd4108b9330238aac11dd2e177a1ae" integrity sha512-/P5lkRXkWHNAbcJIiHPfRoKqyd7bsyCma1hZNUGfn20qm64T6ZBlrzprymeu918H+mB/0rIg2gGK/BXkhhYgBw== [email protected]: version "2.1.1" resolved "https://registry.yarnpkg.com/vscode-uri/-/vscode-uri-2.1.1.tgz#5aa1803391b6ebdd17d047f51365cf62c38f6e90" integrity sha512-eY9jmGoEnVf8VE8xr5znSah7Qt1P/xsCdErz+g8HYZtJ7bZqKH5E3d+6oVNm1AC/c6IHUDokbmVXKOi4qPAC9A== wrappy@1: version "1.0.2" resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=
test/integration/browser/yarn.lock
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.0001740507286740467, 0.00016929749108385295, 0.00016552439774386585, 0.00016941639478318393, 0.0000022931697003514273 ]
{ "id": 14, "code_window": [ "\n", "\t\t\t\treturn DiskSearch.collectResultsFromEvent(event, onProgress, token);\n", "\t\t\t});\n", "\t}\n", "\n", "\t/**\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn DiskSearch.collectResultsFromEvent(event, onProgress, token);\n" ], "file_path": "src/vs/workbench/services/search/node/searchService.ts", "type": "replace", "edit_start_line_idx": 126 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IssueReporterStyles, IIssueService, IssueReporterData, ProcessExplorerData, IssueReporterExtensionData } from 'vs/platform/issue/node/issue'; import { IColorTheme, IThemeService } from 'vs/platform/theme/common/themeService'; import { textLinkForeground, inputBackground, inputBorder, inputForeground, buttonBackground, buttonHoverBackground, buttonForeground, inputValidationErrorBorder, foreground, inputActiveOptionBorder, scrollbarSliderActiveBackground, scrollbarSliderBackground, scrollbarSliderHoverBackground, editorBackground, editorForeground, listHoverBackground, listHoverForeground, listHighlightForeground, textLinkActiveForeground, inputValidationErrorBackground, inputValidationErrorForeground } from 'vs/platform/theme/common/colorRegistry'; import { SIDE_BAR_BACKGROUND } from 'vs/workbench/common/theme'; import { IExtensionManagementService } from 'vs/platform/extensionManagement/common/extensionManagement'; import { IWorkbenchExtensionEnablementService } from 'vs/workbench/services/extensionManagement/common/extensionManagement'; import { webFrame } from 'electron'; import { assign } from 'vs/base/common/objects'; import { IWorkbenchIssueService } from 'vs/workbench/contrib/issue/electron-browser/issue'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { INativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-browser/environmentService'; import { ExtensionType } from 'vs/platform/extensions/common/extensions'; export class WorkbenchIssueService implements IWorkbenchIssueService { _serviceBrand: undefined; constructor( @IIssueService private readonly issueService: IIssueService, @IThemeService private readonly themeService: IThemeService, @IExtensionManagementService private readonly extensionManagementService: IExtensionManagementService, @IWorkbenchExtensionEnablementService private readonly extensionEnablementService: IWorkbenchExtensionEnablementService, @IWorkbenchEnvironmentService private readonly environmentService: INativeWorkbenchEnvironmentService ) { } async openReporter(dataOverrides: Partial<IssueReporterData> = {}): Promise<void> { const extensions = await this.extensionManagementService.getInstalled(); const enabledExtensions = extensions.filter(extension => this.extensionEnablementService.isEnabled(extension)); const extensionData = enabledExtensions.map((extension): IssueReporterExtensionData => { const { manifest } = extension; const manifestKeys = manifest.contributes ? Object.keys(manifest.contributes) : []; const isTheme = !manifest.activationEvents && manifestKeys.length === 1 && manifestKeys[0] === 'themes'; const isBuiltin = extension.type === ExtensionType.System; return { name: manifest.name, publisher: manifest.publisher, version: manifest.version, repositoryUrl: manifest.repository && manifest.repository.url, bugsUrl: manifest.bugs && manifest.bugs.url, displayName: manifest.displayName, id: extension.identifier.id, isTheme, isBuiltin, }; }); const theme = this.themeService.getColorTheme(); const issueReporterData: IssueReporterData = assign({ styles: getIssueReporterStyles(theme), zoomLevel: webFrame.getZoomLevel(), enabledExtensions: extensionData, }, dataOverrides); return this.issueService.openReporter(issueReporterData); } openProcessExplorer(): Promise<void> { const theme = this.themeService.getColorTheme(); const data: ProcessExplorerData = { pid: this.environmentService.configuration.mainPid, zoomLevel: webFrame.getZoomLevel(), styles: { backgroundColor: getColor(theme, editorBackground), color: getColor(theme, editorForeground), hoverBackground: getColor(theme, listHoverBackground), hoverForeground: getColor(theme, listHoverForeground), highlightForeground: getColor(theme, listHighlightForeground), } }; return this.issueService.openProcessExplorer(data); } } export function getIssueReporterStyles(theme: IColorTheme): IssueReporterStyles { return { backgroundColor: getColor(theme, SIDE_BAR_BACKGROUND), color: getColor(theme, foreground), textLinkColor: getColor(theme, textLinkForeground), textLinkActiveForeground: getColor(theme, textLinkActiveForeground), inputBackground: getColor(theme, inputBackground), inputForeground: getColor(theme, inputForeground), inputBorder: getColor(theme, inputBorder), inputActiveBorder: getColor(theme, inputActiveOptionBorder), inputErrorBorder: getColor(theme, inputValidationErrorBorder), inputErrorBackground: getColor(theme, inputValidationErrorBackground), inputErrorForeground: getColor(theme, inputValidationErrorForeground), buttonBackground: getColor(theme, buttonBackground), buttonForeground: getColor(theme, buttonForeground), buttonHoverBackground: getColor(theme, buttonHoverBackground), sliderActiveColor: getColor(theme, scrollbarSliderActiveBackground), sliderBackgroundColor: getColor(theme, scrollbarSliderBackground), sliderHoverColor: getColor(theme, scrollbarSliderHoverBackground), }; } function getColor(theme: IColorTheme, key: string): string | undefined { const color = theme.getColor(key); return color ? color.toString() : undefined; }
src/vs/workbench/contrib/issue/electron-browser/issueService.ts
0
https://github.com/microsoft/vscode/commit/ac5d1a097efd946717c444b6e52c66ad092480f5
[ 0.00018241634825244546, 0.0001740315929055214, 0.00016949816199485213, 0.00017430284060537815, 0.0000033547350994922454 ]
{ "id": 0, "code_window": [ "$search-bar-ios-padding: 0 8px !default;\n", "$search-bar-ios-input-height: 28px !default;\n", "$search-bar-ios-input-text-color: #9D9D9D !default;\n", "$search-bar-ios-input-background-color: #FFFFFF !default;\n", "$search-bar-ios-input-icon-color: #767676 !default;\n", "$search-bar-ios-input-background-svg: \"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 13 13'><path fill='\" + $search-bar-ios-input-icon-color + \"' d='M5,1c2.2,0,4,1.8,4,4S7.2,9,5,9S1,7.2,1,5S2.8,1,5,1 M5,0C2.2,0,0,2.2,0,5s2.2,5,5,5s5-2.2,5-5S7.8,0,5,0 L5,0z'/><line stroke='#939398' stroke-miterlimit='10' x1='12.6' y1='12.6' x2='8.2' y2='8.2'/></svg>\" !default;\n", "$search-bar-ios-background-size: 13px 13px !default;\n", "\n", ".search-bar {\n", " padding: $search-bar-ios-padding;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "$search-bar-ios-input-transition: all 0.3s cubic-bezier(.25, .45, .05, 1) !default;\n", "\n", "$search-bar-ios-input-search-icon-color: #767676 !default;\n", "$search-bar-ios-input-search-icon-svg: \"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 13 13'><path fill='\" + $search-bar-ios-input-search-icon-color + \"' d='M5,1c2.2,0,4,1.8,4,4S7.2,9,5,9S1,7.2,1,5S2.8,1,5,1 M5,0C2.2,0,0,2.2,0,5s2.2,5,5,5s5-2.2,5-5S7.8,0,5,0 L5,0z'/><line stroke='\" + $search-bar-ios-input-search-icon-color + \"' stroke-miterlimit='10' x1='12.6' y1='12.6' x2='8.2' y2='8.2'/></svg>\" !default;\n", "$search-bar-ios-input-search-icon-size: 13px !default;\n", "\n", "$search-bar-ios-input-close-icon-color: #8F8E94 !default;\n", "$search-bar-ios-input-close-icon-svg: \"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'><path fill='\" + $search-bar-ios-input-close-icon-color + \"' d='M403.1,108.9c-81.2-81.2-212.9-81.2-294.2,0s-81.2,212.9,0,294.2c81.2,81.2,212.9,81.2,294.2,0S484.3,190.1,403.1,108.9z M352,340.2L340.2,352l-84.4-84.2l-84,83.8L160,339.8l84-83.8l-84-83.8l11.8-11.8l84,83.8l84.4-84.2l11.8,11.8L267.6,256L352,340.2z'/></svg>\" !default;\n", "$search-bar-ios-input-close-icon-size: 17px !default;\n", "\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "replace", "edit_start_line_idx": 10 }
// iOS Search Bar // -------------------------------------------------- $search-bar-ios-background-color: rgba(0, 0, 0, 0.2) !default; $search-bar-ios-border-color: rgba(0, 0, 0, 0.05) !default; $search-bar-ios-padding: 0 8px !default; $search-bar-ios-input-height: 28px !default; $search-bar-ios-input-text-color: #9D9D9D !default; $search-bar-ios-input-background-color: #FFFFFF !default; $search-bar-ios-input-icon-color: #767676 !default; $search-bar-ios-input-background-svg: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 13 13'><path fill='" + $search-bar-ios-input-icon-color + "' d='M5,1c2.2,0,4,1.8,4,4S7.2,9,5,9S1,7.2,1,5S2.8,1,5,1 M5,0C2.2,0,0,2.2,0,5s2.2,5,5,5s5-2.2,5-5S7.8,0,5,0 L5,0z'/><line stroke='#939398' stroke-miterlimit='10' x1='12.6' y1='12.6' x2='8.2' y2='8.2'/></svg>" !default; $search-bar-ios-background-size: 13px 13px !default; .search-bar { padding: $search-bar-ios-padding; background: $search-bar-ios-background-color; border-bottom: 1px solid $search-bar-ios-border-color; } .search-bar-icon { width: 100%; height: 13px; transform: translateX(calc(50% - 60px)); @include svg-background-image($search-bar-ios-input-background-svg); background-size: $search-bar-ios-background-size; background-repeat: no-repeat; position: absolute; left: 10px; top: 8px; } .search-bar-input { height: $search-bar-ios-input-height; padding: 0 28px; font-size: 1.4rem; font-weight: 400; border-radius: 5px; color: $search-bar-ios-input-text-color; background-color: $search-bar-ios-input-background-color; background-repeat: no-repeat; background-position: 8px center; @include calc(padding-left, "50% - 28px"); } .search-bar-input-container.left-align { .search-bar-icon { transform: translateX(0); -webkit-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); -moz-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); } .search-bar-input { padding-left: 28px; -webkit-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); -moz-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); } } &.hairlines .search-bar { border-bottom-width: 0.55px; }
ionic/components/search-bar/modes/ios.scss
1
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.9937742948532104, 0.18445074558258057, 0.0053561097010970116, 0.05818565934896469, 0.3321252763271332 ]
{ "id": 0, "code_window": [ "$search-bar-ios-padding: 0 8px !default;\n", "$search-bar-ios-input-height: 28px !default;\n", "$search-bar-ios-input-text-color: #9D9D9D !default;\n", "$search-bar-ios-input-background-color: #FFFFFF !default;\n", "$search-bar-ios-input-icon-color: #767676 !default;\n", "$search-bar-ios-input-background-svg: \"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 13 13'><path fill='\" + $search-bar-ios-input-icon-color + \"' d='M5,1c2.2,0,4,1.8,4,4S7.2,9,5,9S1,7.2,1,5S2.8,1,5,1 M5,0C2.2,0,0,2.2,0,5s2.2,5,5,5s5-2.2,5-5S7.8,0,5,0 L5,0z'/><line stroke='#939398' stroke-miterlimit='10' x1='12.6' y1='12.6' x2='8.2' y2='8.2'/></svg>\" !default;\n", "$search-bar-ios-background-size: 13px 13px !default;\n", "\n", ".search-bar {\n", " padding: $search-bar-ios-padding;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "$search-bar-ios-input-transition: all 0.3s cubic-bezier(.25, .45, .05, 1) !default;\n", "\n", "$search-bar-ios-input-search-icon-color: #767676 !default;\n", "$search-bar-ios-input-search-icon-svg: \"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 13 13'><path fill='\" + $search-bar-ios-input-search-icon-color + \"' d='M5,1c2.2,0,4,1.8,4,4S7.2,9,5,9S1,7.2,1,5S2.8,1,5,1 M5,0C2.2,0,0,2.2,0,5s2.2,5,5,5s5-2.2,5-5S7.8,0,5,0 L5,0z'/><line stroke='\" + $search-bar-ios-input-search-icon-color + \"' stroke-miterlimit='10' x1='12.6' y1='12.6' x2='8.2' y2='8.2'/></svg>\" !default;\n", "$search-bar-ios-input-search-icon-size: 13px !default;\n", "\n", "$search-bar-ios-input-close-icon-color: #8F8E94 !default;\n", "$search-bar-ios-input-close-icon-svg: \"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'><path fill='\" + $search-bar-ios-input-close-icon-color + \"' d='M403.1,108.9c-81.2-81.2-212.9-81.2-294.2,0s-81.2,212.9,0,294.2c81.2,81.2,212.9,81.2,294.2,0S484.3,190.1,403.1,108.9z M352,340.2L340.2,352l-84.4-84.2l-84,83.8L160,339.8l84-83.8l-84-83.8l11.8-11.8l84,83.8l84.4-84.2l11.8,11.8L267.6,256L352,340.2z'/></svg>\" !default;\n", "$search-bar-ios-input-close-icon-size: 17px !default;\n", "\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "replace", "edit_start_line_idx": 10 }
import {raf, ready} from './dom' /* Focus Outline * -------------------------------------------------- * When a keydown event happens, from a tab key, then the * 'key-input' class is added to the body element so focusable * elements have an outline. On a mousedown or touchstart * event then the 'key-input' class is removed. */ let isKeyInputEnabled = false function keyDown(ev) { if (!isKeyInputEnabled && ev.keyCode == 9) { isKeyInputEnabled = true raf(enableKeyInput) } } function enableKeyInput() { document.body.classList[isKeyInputEnabled ? 'add' : 'remove']('key-input') if (isKeyInputEnabled) { document.addEventListener('mousedown', pointerDown) document.addEventListener('touchstart', pointerDown) } else { document.removeEventListener('mousedown', pointerDown) document.removeEventListener('touchstart', pointerDown) } } function pointerDown() { isKeyInputEnabled = false raf(enableKeyInput) } ready().then(function() { document.addEventListener('keydown', keyDown) })
ionic/util/focus.ts
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.0009107274818234146, 0.00040269765304401517, 0.0002075792581308633, 0.0002863196423277259, 0.00025762393488548696 ]
{ "id": 0, "code_window": [ "$search-bar-ios-padding: 0 8px !default;\n", "$search-bar-ios-input-height: 28px !default;\n", "$search-bar-ios-input-text-color: #9D9D9D !default;\n", "$search-bar-ios-input-background-color: #FFFFFF !default;\n", "$search-bar-ios-input-icon-color: #767676 !default;\n", "$search-bar-ios-input-background-svg: \"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 13 13'><path fill='\" + $search-bar-ios-input-icon-color + \"' d='M5,1c2.2,0,4,1.8,4,4S7.2,9,5,9S1,7.2,1,5S2.8,1,5,1 M5,0C2.2,0,0,2.2,0,5s2.2,5,5,5s5-2.2,5-5S7.8,0,5,0 L5,0z'/><line stroke='#939398' stroke-miterlimit='10' x1='12.6' y1='12.6' x2='8.2' y2='8.2'/></svg>\" !default;\n", "$search-bar-ios-background-size: 13px 13px !default;\n", "\n", ".search-bar {\n", " padding: $search-bar-ios-padding;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "$search-bar-ios-input-transition: all 0.3s cubic-bezier(.25, .45, .05, 1) !default;\n", "\n", "$search-bar-ios-input-search-icon-color: #767676 !default;\n", "$search-bar-ios-input-search-icon-svg: \"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 13 13'><path fill='\" + $search-bar-ios-input-search-icon-color + \"' d='M5,1c2.2,0,4,1.8,4,4S7.2,9,5,9S1,7.2,1,5S2.8,1,5,1 M5,0C2.2,0,0,2.2,0,5s2.2,5,5,5s5-2.2,5-5S7.8,0,5,0 L5,0z'/><line stroke='\" + $search-bar-ios-input-search-icon-color + \"' stroke-miterlimit='10' x1='12.6' y1='12.6' x2='8.2' y2='8.2'/></svg>\" !default;\n", "$search-bar-ios-input-search-icon-size: 13px !default;\n", "\n", "$search-bar-ios-input-close-icon-color: #8F8E94 !default;\n", "$search-bar-ios-input-close-icon-svg: \"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'><path fill='\" + $search-bar-ios-input-close-icon-color + \"' d='M403.1,108.9c-81.2-81.2-212.9-81.2-294.2,0s-81.2,212.9,0,294.2c81.2,81.2,212.9,81.2,294.2,0S484.3,190.1,403.1,108.9z M352,340.2L340.2,352l-84.4-84.2l-84,83.8L160,339.8l84-83.8l-84-83.8l11.8-11.8l84,83.8l84.4-84.2l11.8,11.8L267.6,256L352,340.2z'/></svg>\" !default;\n", "$search-bar-ios-input-close-icon-size: 17px !default;\n", "\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "replace", "edit_start_line_idx": 10 }
import {Component} from 'angular2/angular2'; import {FormBuilder, Validators, ControlGroup} from 'angular2/forms'; import {IonicView} from 'ionic/ionic'; function randomTitle() { var items = ['Pizza', 'Pumpkin', 'Apple', 'Bologna', 'Durian', 'Banana', 'Meat pie']; return items[Math.floor(Math.random() * items.length)]; } @Component({ selector: 'ion-view', appInjector: [FormBuilder] }) @IonicView({ template: ` <ion-navbar *navbar><ion-title>Table Search</ion-title></ion-navbar> <ion-content> <form (submit)="doSearch($event)" [control-group]="form"> <ion-search-bar control="searchQuery"></ion-search-bar> <ion-list #list> <ion-item *ng-for="#item of getItems()"><!--items | search:form.controls.searchControl.value--> {{item.title}} </ion-item> </ion-list> </form> </ion-content> ` }) export class TableSearchPage { constructor(formBuilder: FormBuilder) { console.log('IonicApp Start') this.form = formBuilder.group({ searchQuery: ['', Validators.required] }); this.query = 'HELLO'; this.items = []; for(let i = 0; i < 100; i++) { this.items.push({ title: randomTitle() }) } } getItems() { var q = this.form.controls.searchQuery.value; if(q.trim() == '') { return this.items; } return this.items.filter((v) => { if(v.title.toLowerCase().indexOf(q.toLowerCase()) >= 0) { return true; } return false; }) } }
demos/sink/pages/table-search.ts
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.0012896592961624265, 0.000547436939086765, 0.0001660940470173955, 0.0003489177906885743, 0.0003975513391196728 ]
{ "id": 0, "code_window": [ "$search-bar-ios-padding: 0 8px !default;\n", "$search-bar-ios-input-height: 28px !default;\n", "$search-bar-ios-input-text-color: #9D9D9D !default;\n", "$search-bar-ios-input-background-color: #FFFFFF !default;\n", "$search-bar-ios-input-icon-color: #767676 !default;\n", "$search-bar-ios-input-background-svg: \"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 13 13'><path fill='\" + $search-bar-ios-input-icon-color + \"' d='M5,1c2.2,0,4,1.8,4,4S7.2,9,5,9S1,7.2,1,5S2.8,1,5,1 M5,0C2.2,0,0,2.2,0,5s2.2,5,5,5s5-2.2,5-5S7.8,0,5,0 L5,0z'/><line stroke='#939398' stroke-miterlimit='10' x1='12.6' y1='12.6' x2='8.2' y2='8.2'/></svg>\" !default;\n", "$search-bar-ios-background-size: 13px 13px !default;\n", "\n", ".search-bar {\n", " padding: $search-bar-ios-padding;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "$search-bar-ios-input-transition: all 0.3s cubic-bezier(.25, .45, .05, 1) !default;\n", "\n", "$search-bar-ios-input-search-icon-color: #767676 !default;\n", "$search-bar-ios-input-search-icon-svg: \"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 13 13'><path fill='\" + $search-bar-ios-input-search-icon-color + \"' d='M5,1c2.2,0,4,1.8,4,4S7.2,9,5,9S1,7.2,1,5S2.8,1,5,1 M5,0C2.2,0,0,2.2,0,5s2.2,5,5,5s5-2.2,5-5S7.8,0,5,0 L5,0z'/><line stroke='\" + $search-bar-ios-input-search-icon-color + \"' stroke-miterlimit='10' x1='12.6' y1='12.6' x2='8.2' y2='8.2'/></svg>\" !default;\n", "$search-bar-ios-input-search-icon-size: 13px !default;\n", "\n", "$search-bar-ios-input-close-icon-color: #8F8E94 !default;\n", "$search-bar-ios-input-close-icon-svg: \"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'><path fill='\" + $search-bar-ios-input-close-icon-color + \"' d='M403.1,108.9c-81.2-81.2-212.9-81.2-294.2,0s-81.2,212.9,0,294.2c81.2,81.2,212.9,81.2,294.2,0S484.3,190.1,403.1,108.9z M352,340.2L340.2,352l-84.4-84.2l-84,83.8L160,339.8l84-83.8l-84-83.8l11.8-11.8l84,83.8l84.4-84.2l11.8,11.8L267.6,256L352,340.2z'/></svg>\" !default;\n", "$search-bar-ios-input-close-icon-size: 17px !default;\n", "\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "replace", "edit_start_line_idx": 10 }
import {StorageEngine} from './storage'; import * as util from 'ionic/util'; const DB_NAME = '__ionicstorage'; /** * SqlStorage uses SQLite or WebSQL (development only!) to store data in a * persistent SQL store on the filesystem. * * This is the preferred storage engine, as data will be stored in appropriate * app storage, unlike Local Storage which is treated differently by the OS. * * For convenience, the engine supports key/value storage for simple get/set and blob * storage. The full SQL engine is exposed underneath through the `query` method. * * @usage ```js * let storage = new Storage(SqlStorage, options); * storage.set('name', 'Max'); * storage.get('name').then((name) => { * }); * * // Sql storage also exposes the full engine underneath * storage.query('insert into projects(name, data) values('Cool Project', 'blah')');' * storage.query('select * from projects').then((resp) => {}) * ``` * * The `SqlStorage` service supports these options: * { * name: the name of the database (__ionicstorage by default) * backupFlag: // where to store the file, default is BACKUP_LOCAL which DOES NOT store to iCloud. Other options: BACKUP_LIBRARY, BACKUP_DOCUMENTS * existingDatabase: whether to load this as an existing database (default is false) * } * */ export class SqlStorage extends StorageEngine { static BACKUP_LOCAL = 2 static BACKUP_LIBRARY = 1 static BACKUP_DOCUMENTS = 0 constructor(options) { super(); let dbOptions = util.defaults({ name: DB_NAME, backupFlag: SqlStorage.BACKUP_LOCAL, existingDatabase: false }, options); if(window.sqlitePlugin) { let location = this._getBackupLocation(dbOptions); this._db = window.sqlitePlugin.openDatabase(util.extend({ name: dbOptions.name, location: location, createFromLocation: dbOptions.existingDatabase ? 1 : 0 }, dbOptions)); } else { console.warn('Storage: SQLite plugin not installed, falling back to WebSQL. Make sure to install cordova-sqlite-storage in production!'); this._db = window.openDatabase(dbOptions.name, '1.0', 'database', 5 * 1024 * 1024); } this._tryInit(); } _getBackupLocation(dbFlag) { switch(dbFlag) { case SqlStorage.BACKUP_LOCAL: return 2; case SqlStorage.BACKUP_LIBRARY: return 1; case SqlStorage.BACKUP_DOCUMENTS: return 0; default: throw Error('Invalid backup flag: ' + dbFlag); } } // Initialize the DB with our required tables _tryInit() { this._db.transaction((tx) => { tx.executeSql('CREATE TABLE IF NOT EXISTS kv (key text primary key, value text)', [], (tx, res) => { }, (tx, err) => { console.error('Storage: Unable to create initial storage tables', tx, err); }); }); } /** * Perform an arbitrary SQL operation on the database. Use this method * to have full control over the underlying database through SQL operations * like SELECT, INSERT, and UPDATE. * * @param {string} query the query to run * @param {array} params the additional params to use for query placeholders * @return {Promise} that resolves or rejects with an object of the form { tx: Transaction, res: Result (or err)} */ query(query, ...params) { return new Promise((resolve, reject) => { this._db.transaction((tx) => { ts.executeSql(query, params, (tx, res) => { resolve({ tx: tx, res: res }); }, (tx, err) => { reject({ tx: tx, err: err }); }) }); }) } /** * Get the value in the database identified by the given key. * @param {string} key the key * @return {Promise} that resolves or rejects with an object of the form { tx: Transaction, res: Result (or err)} */ get(key) { return new Promise((resolve, reject) => { try { this._db.transaction(tx => { tx.executeSql("select key, value from kv where key = ? limit 1", [key], (tx, res) => { if(res.rows.length > 0) { let item = res.rows.item(0); resolve(item.value); } resolve(null); }, (tx, err) => { reject({ tx: tx, err: err }); }) }, err => { reject(err); }); } catch(e) { reject(e); } }); } /** * Set the value in the database for the given key. Existing values will be overwritten. * @param {string} key the key * @param {string} value The value (as a string) * @return {Promise} that resolves or rejects with an object of the form { tx: Transaction, res: Result (or err)} */ set(key, value) { return new Promise((resolve, reject) => { try { this._db.transaction(tx => { tx.executeSql('insert or replace into kv(key, value) values (?, ?)', [key, value], (tx, res) => { resolve(); }, (tx, err) => { reject({ tx: tx, err: err }); }) }, err => { reject(err); }); } catch(e) { reject(e); } }); } /** * Remove the value in the database for the given key. * @param {string} key the key * @param {string} value The value (as a string) * @return {Promise} that resolves or rejects with an object of the form { tx: Transaction, res: Result (or err)} */ remove(key) { return new Promise((resolve, reject) => { try { this._db.transaction(tx => { tx.executeSql('delete from kv where key = ?', [key], (tx, res) => { resolve(); }, (tx, err) => { reject({ tx: tx, err: err }); }) }, err => { reject(err); }); } catch(e) { reject(e); } }); } }
ionic/platform/storage/sql.ts
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.002816153923049569, 0.0005361164803616703, 0.00016526230319868773, 0.0003029436629731208, 0.0006512333638966084 ]
{ "id": 1, "code_window": [ " background: $search-bar-ios-background-color;\n", " border-bottom: 1px solid $search-bar-ios-border-color;\n", "}\n", "\n", ".search-bar-icon {\n", " width: 100%;\n", " height: 13px;\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ ".search-bar-search-icon {\n", " width: $search-bar-ios-input-search-icon-size + 1;\n", " height: $search-bar-ios-input-search-icon-size + 1;\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "replace", "edit_start_line_idx": 20 }
// iOS Search Bar // -------------------------------------------------- $search-bar-ios-background-color: rgba(0, 0, 0, 0.2) !default; $search-bar-ios-border-color: rgba(0, 0, 0, 0.05) !default; $search-bar-ios-padding: 0 8px !default; $search-bar-ios-input-height: 28px !default; $search-bar-ios-input-text-color: #9D9D9D !default; $search-bar-ios-input-background-color: #FFFFFF !default; $search-bar-ios-input-icon-color: #767676 !default; $search-bar-ios-input-background-svg: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 13 13'><path fill='" + $search-bar-ios-input-icon-color + "' d='M5,1c2.2,0,4,1.8,4,4S7.2,9,5,9S1,7.2,1,5S2.8,1,5,1 M5,0C2.2,0,0,2.2,0,5s2.2,5,5,5s5-2.2,5-5S7.8,0,5,0 L5,0z'/><line stroke='#939398' stroke-miterlimit='10' x1='12.6' y1='12.6' x2='8.2' y2='8.2'/></svg>" !default; $search-bar-ios-background-size: 13px 13px !default; .search-bar { padding: $search-bar-ios-padding; background: $search-bar-ios-background-color; border-bottom: 1px solid $search-bar-ios-border-color; } .search-bar-icon { width: 100%; height: 13px; transform: translateX(calc(50% - 60px)); @include svg-background-image($search-bar-ios-input-background-svg); background-size: $search-bar-ios-background-size; background-repeat: no-repeat; position: absolute; left: 10px; top: 8px; } .search-bar-input { height: $search-bar-ios-input-height; padding: 0 28px; font-size: 1.4rem; font-weight: 400; border-radius: 5px; color: $search-bar-ios-input-text-color; background-color: $search-bar-ios-input-background-color; background-repeat: no-repeat; background-position: 8px center; @include calc(padding-left, "50% - 28px"); } .search-bar-input-container.left-align { .search-bar-icon { transform: translateX(0); -webkit-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); -moz-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); } .search-bar-input { padding-left: 28px; -webkit-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); -moz-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); } } &.hairlines .search-bar { border-bottom-width: 0.55px; }
ionic/components/search-bar/modes/ios.scss
1
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.8848113417625427, 0.1885249763727188, 0.0003133405698463321, 0.019005773589015007, 0.3003520369529724 ]
{ "id": 1, "code_window": [ " background: $search-bar-ios-background-color;\n", " border-bottom: 1px solid $search-bar-ios-border-color;\n", "}\n", "\n", ".search-bar-icon {\n", " width: 100%;\n", " height: 13px;\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ ".search-bar-search-icon {\n", " width: $search-bar-ios-input-search-icon-size + 1;\n", " height: $search-bar-ios-input-search-icon-size + 1;\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "replace", "edit_start_line_idx": 20 }
ionic/components/card/test/advanced/e2e.ts
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.0001780910388333723, 0.0001780910388333723, 0.0001780910388333723, 0.0001780910388333723, 0 ]
{ "id": 1, "code_window": [ " background: $search-bar-ios-background-color;\n", " border-bottom: 1px solid $search-bar-ios-border-color;\n", "}\n", "\n", ".search-bar-icon {\n", " width: 100%;\n", " height: 13px;\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ ".search-bar-search-icon {\n", " width: $search-bar-ios-input-search-icon-size + 1;\n", " height: $search-bar-ios-input-search-icon-size + 1;\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "replace", "edit_start_line_idx": 20 }
// Copyright 2014 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License.
scripts/resources/web-animations-js/templates/boilerplate
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.00017760977789293975, 0.00017720492905937135, 0.00017680008022580296, 0.00017720492905937135, 4.048488335683942e-7 ]
{ "id": 1, "code_window": [ " background: $search-bar-ios-background-color;\n", " border-bottom: 1px solid $search-bar-ios-border-color;\n", "}\n", "\n", ".search-bar-icon {\n", " width: 100%;\n", " height: 13px;\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ ".search-bar-search-icon {\n", " width: $search-bar-ios-input-search-icon-size + 1;\n", " height: $search-bar-ios-input-search-icon-size + 1;\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "replace", "edit_start_line_idx": 20 }
import {Component} from 'angular2/angular2'; import {Control, ControlGroup} from 'angular2/forms'; import {App, Http} from 'ionic/ionic'; let testUrl = 'https://ionic-api-tester.herokuapp.com/json'; let testUrl404 = 'https://ionic-api-tester.herokuapp.com/404'; @App({ templateUrl: 'main.html' }) class IonicApp { constructor() { this.form = new ControlGroup({ requestData: new Control('') }) } doGet() { Http.get('http://swapi.co/api/people/1').then((resp) => { this.resp = resp; }, (err) => { this.err = err; }) } doGet404() { Http.get(testUrl404).then((resp) => { this.resp = resp; }, (err) => { this.err = err; }) } doPost() { let data = this.form.controls.requestData.value; Http.post(testUrl, data).then((resp) => { this.resp = resp; }, (err) => { this.err = err; }) } doPut() { let data = this.form.controls.requestData.value; Http.put(testUrl, data).then((resp) => { this.resp = resp; }, (err) => { this.err = err; }) } doDelete() { let data = this.form.controls.requestData.value; Http.delete(testUrl, data).then((resp) => { this.resp = resp; }, (err) => { this.err = err; }) } doPatch() { let data = this.form.controls.requestData.value; Http.patch(testUrl, data).then((resp) => { this.resp = resp; }, (err) => { this.err = err; }) } }
demos/net/index.ts
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.00017367309192195535, 0.00017039159138221294, 0.0001672192884143442, 0.0001695919199846685, 0.0000020943255094607593 ]
{ "id": 2, "code_window": [ "\n", " transform: translateX(calc(50% - 60px));\n", "\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " transform: translateX(calc(50% + 90px));\n", " transition: $search-bar-ios-input-transition;\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "replace", "edit_start_line_idx": 24 }
// iOS Search Bar // -------------------------------------------------- $search-bar-ios-background-color: rgba(0, 0, 0, 0.2) !default; $search-bar-ios-border-color: rgba(0, 0, 0, 0.05) !default; $search-bar-ios-padding: 0 8px !default; $search-bar-ios-input-height: 28px !default; $search-bar-ios-input-text-color: #9D9D9D !default; $search-bar-ios-input-background-color: #FFFFFF !default; $search-bar-ios-input-icon-color: #767676 !default; $search-bar-ios-input-background-svg: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 13 13'><path fill='" + $search-bar-ios-input-icon-color + "' d='M5,1c2.2,0,4,1.8,4,4S7.2,9,5,9S1,7.2,1,5S2.8,1,5,1 M5,0C2.2,0,0,2.2,0,5s2.2,5,5,5s5-2.2,5-5S7.8,0,5,0 L5,0z'/><line stroke='#939398' stroke-miterlimit='10' x1='12.6' y1='12.6' x2='8.2' y2='8.2'/></svg>" !default; $search-bar-ios-background-size: 13px 13px !default; .search-bar { padding: $search-bar-ios-padding; background: $search-bar-ios-background-color; border-bottom: 1px solid $search-bar-ios-border-color; } .search-bar-icon { width: 100%; height: 13px; transform: translateX(calc(50% - 60px)); @include svg-background-image($search-bar-ios-input-background-svg); background-size: $search-bar-ios-background-size; background-repeat: no-repeat; position: absolute; left: 10px; top: 8px; } .search-bar-input { height: $search-bar-ios-input-height; padding: 0 28px; font-size: 1.4rem; font-weight: 400; border-radius: 5px; color: $search-bar-ios-input-text-color; background-color: $search-bar-ios-input-background-color; background-repeat: no-repeat; background-position: 8px center; @include calc(padding-left, "50% - 28px"); } .search-bar-input-container.left-align { .search-bar-icon { transform: translateX(0); -webkit-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); -moz-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); } .search-bar-input { padding-left: 28px; -webkit-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); -moz-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); } } &.hairlines .search-bar { border-bottom-width: 0.55px; }
ionic/components/search-bar/modes/ios.scss
1
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.9952196478843689, 0.28159359097480774, 0.00016657874220982194, 0.0002853655314538628, 0.44490641355514526 ]
{ "id": 2, "code_window": [ "\n", " transform: translateX(calc(50% - 60px));\n", "\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " transform: translateX(calc(50% + 90px));\n", " transition: $search-bar-ios-input-transition;\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "replace", "edit_start_line_idx": 24 }
import {App, IonicApp, IonicView} from 'ionic/ionic'; @IonicView({templateUrl: 'page1.html'}) class Page1 {} @IonicView({templateUrl: 'page2.html'}) class Page2 {} @App({ templateUrl: 'main.html' }) class E2EApp { constructor(app: IonicApp) { this.app = app; this.rootView = Page1; this.pages = [ { title: 'Page 1', component: Page1 }, { title: 'Page 2', component: Page2 }, ]; } openPage(menu, page) { // close the menu when clicking a link from the menu menu.close(); // Reset the content nav to have just this page // we wouldn't want the back button to show in this scenario let nav = this.app.getComponent('nav'); nav.setRoot(page.component); } }
demos/menu/index.ts
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.00016955779574345797, 0.00016820058226585388, 0.00016709609190002084, 0.00016807421343401074, 8.825765007713926e-7 ]
{ "id": 2, "code_window": [ "\n", " transform: translateX(calc(50% - 60px));\n", "\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " transform: translateX(calc(50% + 90px));\n", " transition: $search-bar-ios-input-transition;\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "replace", "edit_start_line_idx": 24 }
<ion-navbar *navbar> <a menu-toggle="leftMenu"> <icon menu></icon> </a> <ion-title> Menu </ion-title> <ion-nav-items secondary> <button> <icon football></icon> </button> </ion-nav-items> <ion-nav-items primary> <button> <icon baseball></icon> </button> </ion-nav-items> <a menu-toggle="rightMenu" secondary> <icon menu></icon> </a> </ion-navbar> <ion-content padding> <h3>Page 1</h3> <p> <button class="e2eContentToggleMenu" menu-toggle="leftMenu">Toggle Left Menu</button> </p> <p> <button class="e2eContentToggleMenu" menu-toggle="rightMenu">Toggle Right Menu</button> </p> <f></f><f></f><f></f><f></f><f></f><f></f><f></f><f></f> </ion-content>
ionic/components/menu/test/basic/page1.html
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.00017425979604013264, 0.00017073236813303083, 0.0001673117803875357, 0.0001707362971501425, 0.000002350422391828033 ]
{ "id": 2, "code_window": [ "\n", " transform: translateX(calc(50% - 60px));\n", "\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " transform: translateX(calc(50% + 90px));\n", " transition: $search-bar-ios-input-transition;\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "replace", "edit_start_line_idx": 24 }
var _ = require('lodash'); var path = require('canonical-path'); /** * @dgService getLinkInfo * @description * Get link information to a document that matches the given url * @kind function * @param {String} url The url to match * @param {String} title An optional title to return in the link information * @return {Object} The link information * * @property {boolean} relativeLinks Whether we expect the links to be relative to the originating doc */ module.exports = function getLinkInfo(getDocFromAlias, encodeCodeBlock, log) { return function getLinkInfoImpl(url, title, currentDoc) { var linkInfo = { url: url, type: 'url', valid: true, title: title || url }; if ( !url ) { throw new Error('Invalid url'); } var docs = getDocFromAlias(url, currentDoc); if ( !getLinkInfoImpl.useFirstAmbiguousLink && docs.length > 1 ) { linkInfo.valid = false; linkInfo.errorType = 'ambiguous'; linkInfo.error = 'Ambiguous link: "' + url + '".\n' + docs.reduce(function(msg, doc) { return msg + '\n "' + doc.id + '" ('+ doc.docType + ') : (' + doc.path + ' / ' + doc.fileInfo.relativePath + ')'; }, 'Matching docs: '); } else if ( docs.length >= 1 ) { linkInfo.url = docs[0].path; linkInfo.title = title || encodeCodeBlock(docs[0].name, true); linkInfo.type = 'doc'; if ( getLinkInfoImpl.relativeLinks && currentDoc && currentDoc.path ) { var currentFolder = path.dirname(currentDoc.path); var docFolder = path.dirname(linkInfo.url); var relativeFolder = path.relative(path.join('/', currentFolder), path.join('/', docFolder)); linkInfo.url = path.join(relativeFolder, path.basename(linkInfo.url)); log.debug(currentDoc.path, docs[0].path, linkInfo.url); } } else if ( url.indexOf('#') > 0 ) { var pathAndHash = url.split('#'); linkInfo = getLinkInfoImpl(pathAndHash[0], title, currentDoc); linkInfo.url = linkInfo.url + '#' + pathAndHash[1]; return linkInfo; } else if ( url.indexOf('/') === -1 && url.indexOf('#') !== 0 ) { linkInfo.valid = false; linkInfo.errorType = 'missing'; linkInfo.error = 'Invalid link (does not match any doc): "' + url + '"'; } else { linkInfo.title = title || (( url.indexOf('#') === 0 ) ? url.substring(1) : path.basename(url, '.html')); } return linkInfo; }; };
scripts/docs/links-package/services/getLinkInfo.js
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.00017873544129543006, 0.00017002676031552255, 0.0001671097707003355, 0.0001689708442427218, 0.0000034520087410783162 ]
{ "id": 3, "code_window": [ "\n", " @include svg-background-image($search-bar-ios-input-background-svg);\n", " background-size: $search-bar-ios-background-size;\n", " background-repeat: no-repeat;\n", " position: absolute;\n", " left: 10px;\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " @include svg-background-image($search-bar-ios-input-search-icon-svg);\n", " background-size: $search-bar-ios-input-search-icon-size;\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "replace", "edit_start_line_idx": 26 }
// iOS Search Bar // -------------------------------------------------- $search-bar-ios-background-color: rgba(0, 0, 0, 0.2) !default; $search-bar-ios-border-color: rgba(0, 0, 0, 0.05) !default; $search-bar-ios-padding: 0 8px !default; $search-bar-ios-input-height: 28px !default; $search-bar-ios-input-text-color: #9D9D9D !default; $search-bar-ios-input-background-color: #FFFFFF !default; $search-bar-ios-input-icon-color: #767676 !default; $search-bar-ios-input-background-svg: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 13 13'><path fill='" + $search-bar-ios-input-icon-color + "' d='M5,1c2.2,0,4,1.8,4,4S7.2,9,5,9S1,7.2,1,5S2.8,1,5,1 M5,0C2.2,0,0,2.2,0,5s2.2,5,5,5s5-2.2,5-5S7.8,0,5,0 L5,0z'/><line stroke='#939398' stroke-miterlimit='10' x1='12.6' y1='12.6' x2='8.2' y2='8.2'/></svg>" !default; $search-bar-ios-background-size: 13px 13px !default; .search-bar { padding: $search-bar-ios-padding; background: $search-bar-ios-background-color; border-bottom: 1px solid $search-bar-ios-border-color; } .search-bar-icon { width: 100%; height: 13px; transform: translateX(calc(50% - 60px)); @include svg-background-image($search-bar-ios-input-background-svg); background-size: $search-bar-ios-background-size; background-repeat: no-repeat; position: absolute; left: 10px; top: 8px; } .search-bar-input { height: $search-bar-ios-input-height; padding: 0 28px; font-size: 1.4rem; font-weight: 400; border-radius: 5px; color: $search-bar-ios-input-text-color; background-color: $search-bar-ios-input-background-color; background-repeat: no-repeat; background-position: 8px center; @include calc(padding-left, "50% - 28px"); } .search-bar-input-container.left-align { .search-bar-icon { transform: translateX(0); -webkit-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); -moz-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); } .search-bar-input { padding-left: 28px; -webkit-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); -moz-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); } } &.hairlines .search-bar { border-bottom-width: 0.55px; }
ionic/components/search-bar/modes/ios.scss
1
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.03544009104371071, 0.00943779107183218, 0.00019205603166483343, 0.00694101769477129, 0.011329010128974915 ]
{ "id": 3, "code_window": [ "\n", " @include svg-background-image($search-bar-ios-input-background-svg);\n", " background-size: $search-bar-ios-background-size;\n", " background-repeat: no-repeat;\n", " position: absolute;\n", " left: 10px;\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " @include svg-background-image($search-bar-ios-input-search-icon-svg);\n", " background-size: $search-bar-ios-input-search-icon-size;\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "replace", "edit_start_line_idx": 26 }
<!-- Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <script src="src/dev.js"></script> <script src="src/scope.js"></script> <script src="src/timing-utilities.js"></script> <script src="src/normalize-keyframes.js"></script> <script src="src/keyframe-interpolations.js"></script> <script src="src/property-interpolation.js"></script> <script src="src/keyframe-effect.js"></script> <script src="src/apply.js"></script> <script src="src/element-animatable.js"></script> <script src="src/interpolation.js"></script> <script src="src/animation.js"></script> <script src="src/tick.js"></script> <script src="src/handler-utils.js"></script> <script src="src/shadow-handler.js"></script> <script src="src/number-handler.js"></script> <script src="src/visibility-handler.js"></script> <script src="src/color-handler.js"></script> <script src="src/dimension-handler.js"></script> <script src="src/box-handler.js"></script> <script src="src/transform-handler.js"></script> <script src="src/property-names.js"></script> <script src="src/timeline.js"></script> <script src="src/web-animations-next-animation.js"></script> <script src="src/keyframe-effect-constructor.js"></script> <script src="src/effect-callback.js"></script> <script src="src/group-constructors.js"></script>
scripts/resources/web-animations-js/web-animations-next-lite.dev.html
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.00017544270667713135, 0.00017126726743299514, 0.00016787764616310596, 0.00017013792239595205, 0.0000029890609312133165 ]
{ "id": 3, "code_window": [ "\n", " @include svg-background-image($search-bar-ios-input-background-svg);\n", " background-size: $search-bar-ios-background-size;\n", " background-repeat: no-repeat;\n", " position: absolute;\n", " left: 10px;\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " @include svg-background-image($search-bar-ios-input-search-icon-svg);\n", " background-size: $search-bar-ios-input-search-icon-size;\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "replace", "edit_start_line_idx": 26 }
// Material Design Switch // -------------------------------------------------- $switch-md-active-color: color(primary) !default; $switch-md-track-width: 36px !default; $switch-md-track-height: 14px !default; $switch-md-track-background-color-off: $item-md-border-color !default; $switch-md-track-background-color-on: lighten($switch-md-active-color, 25%) !default; $switch-md-handle-width: 20px !default; $switch-md-handle-height: 20px !default; $switch-md-handle-background-color-off: $background-color !default; $switch-md-handle-background-color-on: $switch-md-active-color !default; $switch-md-handle-box-shadow: 0 2px 2px 0 rgba(0,0,0,.14), 0 3px 1px -2px rgba(0,0,0,.2), 0 1px 5px 0 rgba(0,0,0,.12) !default; $switch-md-transition-duration: 300ms !default; ion-switch { media-switch { padding: 12px ($item-md-padding-right / 2) 12px $item-md-padding-left; } // Switch Background Track // ----------------------------------------- switch-icon { // bg track, when not checked position: relative; display: block; width: $switch-md-track-width; height: $switch-md-track-height; pointer-events: none; border-radius: $switch-md-track-height; background-color: $switch-md-track-background-color-off; will-change: background-color; transition: background-color $switch-md-transition-duration } &[aria-checked=true] switch-icon { // bg track, when not checked background-color: $switch-md-track-background-color-on; } // Switch Knob // ----------------------------------------- switch-icon:after { // knob, when not checked content: ''; position: absolute; top: ($switch-md-handle-height - $switch-md-track-height) / -2; left: 0; width: $switch-md-handle-width; height: $switch-md-handle-height; border-radius: 50%; box-shadow: $switch-md-handle-box-shadow; background-color: $switch-md-handle-background-color-off; will-change: transform, background-color; transition-property: transform, background-color; transition-duration: $switch-md-transition-duration; } &[aria-checked=true] switch-icon:after { // knob, when not checked background-color: $switch-md-handle-background-color-on; transform: translate3d($switch-md-track-width - $switch-md-handle-width, 0, 0); } } // Material Design Color Mixin // -------------------------------------------------- @mixin switch-theme-md($color-name, $bg-on) { ion-switch[#{$color-name}] { &[aria-checked=true] switch-icon { background-color: lighten($bg-on, 25%); } &[aria-checked=true] switch-icon:after { background-color: $bg-on; } } } // Generate Material Design Switch Auxiliary Colors // -------------------------------------------------- @each $color-name, $value in auxiliary-colors() { @include switch-theme-md($color-name, $value); }
ionic/components/switch/modes/md.scss
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.9503438472747803, 0.07936513423919678, 0.00016693142242729664, 0.00017760336049832404, 0.26260995864868164 ]
{ "id": 3, "code_window": [ "\n", " @include svg-background-image($search-bar-ios-input-background-svg);\n", " background-size: $search-bar-ios-background-size;\n", " background-repeat: no-repeat;\n", " position: absolute;\n", " left: 10px;\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " @include svg-background-image($search-bar-ios-input-search-icon-svg);\n", " background-size: $search-bar-ios-input-search-icon-size;\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "replace", "edit_start_line_idx": 26 }
import {App} from 'ionic/ionic'; @App({ templateUrl: 'main.html' }) class E2EApp {}
ionic/components/card/test/images/index.ts
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.000173450171132572, 0.000173450171132572, 0.000173450171132572, 0.000173450171132572, 0 ]
{ "id": 4, "code_window": [ " color: $search-bar-ios-input-text-color;\n", " background-color: $search-bar-ios-input-background-color;\n", " background-repeat: no-repeat;\n", " background-position: 8px center;\n", "\n", " @include calc(padding-left, \"50% - 28px\");\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " transition: $search-bar-ios-input-transition;\n", "\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "add", "edit_start_line_idx": 47 }
// iOS Search Bar // -------------------------------------------------- $search-bar-ios-background-color: rgba(0, 0, 0, 0.2) !default; $search-bar-ios-border-color: rgba(0, 0, 0, 0.05) !default; $search-bar-ios-padding: 0 8px !default; $search-bar-ios-input-height: 28px !default; $search-bar-ios-input-text-color: #9D9D9D !default; $search-bar-ios-input-background-color: #FFFFFF !default; $search-bar-ios-input-icon-color: #767676 !default; $search-bar-ios-input-background-svg: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 13 13'><path fill='" + $search-bar-ios-input-icon-color + "' d='M5,1c2.2,0,4,1.8,4,4S7.2,9,5,9S1,7.2,1,5S2.8,1,5,1 M5,0C2.2,0,0,2.2,0,5s2.2,5,5,5s5-2.2,5-5S7.8,0,5,0 L5,0z'/><line stroke='#939398' stroke-miterlimit='10' x1='12.6' y1='12.6' x2='8.2' y2='8.2'/></svg>" !default; $search-bar-ios-background-size: 13px 13px !default; .search-bar { padding: $search-bar-ios-padding; background: $search-bar-ios-background-color; border-bottom: 1px solid $search-bar-ios-border-color; } .search-bar-icon { width: 100%; height: 13px; transform: translateX(calc(50% - 60px)); @include svg-background-image($search-bar-ios-input-background-svg); background-size: $search-bar-ios-background-size; background-repeat: no-repeat; position: absolute; left: 10px; top: 8px; } .search-bar-input { height: $search-bar-ios-input-height; padding: 0 28px; font-size: 1.4rem; font-weight: 400; border-radius: 5px; color: $search-bar-ios-input-text-color; background-color: $search-bar-ios-input-background-color; background-repeat: no-repeat; background-position: 8px center; @include calc(padding-left, "50% - 28px"); } .search-bar-input-container.left-align { .search-bar-icon { transform: translateX(0); -webkit-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); -moz-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); } .search-bar-input { padding-left: 28px; -webkit-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); -moz-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); } } &.hairlines .search-bar { border-bottom-width: 0.55px; }
ionic/components/search-bar/modes/ios.scss
1
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.9972972273826599, 0.1494729220867157, 0.00017305335495620966, 0.010989823378622532, 0.3461865782737732 ]
{ "id": 4, "code_window": [ " color: $search-bar-ios-input-text-color;\n", " background-color: $search-bar-ios-input-background-color;\n", " background-repeat: no-repeat;\n", " background-position: 8px center;\n", "\n", " @include calc(padding-left, \"50% - 28px\");\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " transition: $search-bar-ios-input-transition;\n", "\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "add", "edit_start_line_idx": 47 }
import {Component} from 'angular2/angular2'; import {Control, ControlGroup} from 'angular2/forms'; import {IonicApp, App, Http} from 'ionic/ionic'; import {Camera, Geolocation, Vibration, Battery, Device, Events} from 'ionic/ionic'; import {CameraPage} from 'pages/camera'; import {BatteryPage} from 'pages/battery'; import {ContactsPage} from 'pages/contacts'; import {DevicePage} from 'pages/device'; import {DeviceMotionPage} from 'pages/device-motion'; import {DeviceOrientationPage} from 'pages/device-orientation'; import {DialogsPage} from 'pages/dialogs'; import {GeolocationPage} from 'pages/geolocation'; import {StatusBarPage} from 'pages/statusbar'; import {VibrationPage} from 'pages/vibration'; @App({ templateUrl: 'main.html' }) class MyApp { constructor(app: IonicApp, events: Events) { this.app = app; console.log('Events', events); let handler = (user) => { console.log('User created', user); return { what: 'what' } } let handler2 = (user) => { console.log('2User created', user); return { things: 'yes' } } events.subscribe('user:created', handler); events.subscribe('user:created', handler2); setInterval(() => { var results = events.publish('user:created', { name: 'Max Lynch', id: 1 }) console.log('Got results', results); }, 2000); setTimeout(() => { events.unsubscribe('user:created'); console.log(events.channels); }, 6000); this.firstPage = CameraPage; this.plugins = [ {title: 'Camera', page: CameraPage}, {title: 'Device', page: DevicePage}, {title: 'Device Motion', page: DeviceMotionPage}, {title: 'Device Orientation', page: DeviceOrientationPage}, {title: 'Dialogs', page: DialogsPage}, {title: 'Geolocation', page: GeolocationPage}, {title: 'Contacts', page: ContactsPage}, {title: 'Battery', page: BatteryPage}, {title: 'StatusBar', page: StatusBarPage}, {title: 'Vibration', page: VibrationPage}, ] } openPage(menu, page) { menu.close(); let nav = this.app.getComponent('myNav'); nav.setRoot(page.page); } }
demos/native/index.ts
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.00017582987493369728, 0.00017246224160771817, 0.00017001530795823783, 0.000171949781361036, 0.0000019909523416572483 ]
{ "id": 4, "code_window": [ " color: $search-bar-ios-input-text-color;\n", " background-color: $search-bar-ios-input-background-color;\n", " background-repeat: no-repeat;\n", " background-position: 8px center;\n", "\n", " @include calc(padding-left, \"50% - 28px\");\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " transition: $search-bar-ios-input-transition;\n", "\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "add", "edit_start_line_idx": 47 }
// Navbar // -------------------------------------------------- ion-navbar.toolbar { position: absolute; } ion-navbar { transform: translate3d(100%, 0px, 0px); &.show-navbar { transform: translate3d(0px, 0px, 0px); } } .back-button { order: map-get($toolbar-order, backButton);; transform: translateZ(0px); display: none; &.show-back-button { display: flex; } } .back-button-text { display: flex; align-items: center; }
ionic/components/nav-bar/nav-bar.scss
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.004583465401083231, 0.0012803130084648728, 0.00016498992044944316, 0.00018639846530277282, 0.0019071040442213416 ]
{ "id": 4, "code_window": [ " color: $search-bar-ios-input-text-color;\n", " background-color: $search-bar-ios-input-background-color;\n", " background-repeat: no-repeat;\n", " background-position: 8px center;\n", "\n", " @include calc(padding-left, \"50% - 28px\");\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " transition: $search-bar-ios-input-transition;\n", "\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "add", "edit_start_line_idx": 47 }
import {Component} from 'angular2/angular2'; import {DirectiveBinding} from 'angular2/src/core/compiler/element_injector'; import {IonicApp} from '../app/app'; import {Animation} from '../../animations/animation'; import * as util from 'ionic/util'; export class Overlay { constructor(app: IonicApp, config: IonicConfig) { this.app = app; this.config = config; this.mode = config.get('mode'); } create(overlayType, componentType: Type, opts={}, context=null) { return new Promise((resolve, reject) => { let app = this.app; let annotation = new Component({ selector: 'ion-' + overlayType, host: { '[style.z-index]': 'zIndex', 'mode': this.mode, 'class': overlayType } }); let overlayComponentType = DirectiveBinding.createFromType(componentType, annotation); // create a unique token that works as a cache key overlayComponentType.token = overlayType + componentType.name; app.appendComponent(overlayComponentType).then(ref => { let overlayRef = new OverlayRef(app, overlayType, opts, ref, context); overlayRef._open(opts).then(() => { resolve(overlayRef); }); }).catch(err => { console.error('Overlay appendComponent:', err); reject(err); }); }).catch(err => { console.error('Overlay create:', err); }); } getByType(overlayType) { if (this.app) { for (let i = this.app.overlays.length - 1; i >= 0; i--) { if (overlayType === this.app.overlays[i]._type) { return this.app.overlays[i]; } } } return null; } getByHandle(handle, overlayType) { if (this.app) { for (let i = this.app.overlays.length - 1; i >= 0; i--) { if (handle === this.app.overlays[i]._handle && overlayType === this.app.overlays[i]._type) { return this.app.overlays[i]; } } } return null; } } export class OverlayRef { constructor(app, overlayType, opts, ref, context) { this.app = app; let overlayInstance = (ref && ref.instance); if (!overlayInstance) return; if (context) { util.extend(ref.instance, context); } this._instance = overlayInstance; overlayInstance.onViewLoaded && overlayInstance.onViewLoaded(); this.zIndex = ROOT_Z_INDEX; for (let i = 0; i < app.overlays.length; i++) { if (app.overlays[i].zIndex >= this.zIndex) { this.zIndex = app.overlays[i].zIndex + 1; } } overlayInstance.zIndex = this.zIndex; overlayInstance.overlayRef = this; overlayInstance.close = (instanceOpts) => { this.close(instanceOpts); }; this._elementRef = ref.location; this._type = overlayType; this._opts = opts; this._handle = opts.handle || this.zIndex; this._dispose = () => { this._instance = null; ref.dispose && ref.dispose(); util.array.remove(app.overlays, this); }; app.overlays.push(this); } getElementRef() { return this._elementRef; } _open(opts={}) { return new Promise(resolve => { let instance = this._instance || {}; instance.onViewWillEnter && instance.onViewWillEnter(); let animationName = (opts && opts.animation) || this._opts.enterAnimation; let animation = Animation.create(this._elementRef.nativeElement, animationName); animation.before.addClass('show-overlay'); this.app.setEnabled(false, animation.duration()); this.app.setTransitioning(true, animation.duration()); this.app.zoneRunOutside(() => { animation.play().then(() => { this.app.zoneRun(() => { this.app.setEnabled(true); this.app.setTransitioning(false); animation.dispose(); instance.onViewDidEnter && instance.onViewDidEnter(); resolve(); }); }); }); }).catch(err => { console.error(err); }); } close(opts={}) { return new Promise(resolve => { let instance = this._instance || {}; instance.onViewWillLeave && instance.onViewWillLeave(); instance.onViewWillUnload && instance.onViewWillUnload(); let animationName = (opts && opts.animation) || this._opts.leaveAnimation; let animation = Animation.create(this._elementRef.nativeElement, animationName); animation.after.removeClass('show-overlay'); this.app.setEnabled(false, animation.duration()); this.app.setTransitioning(true, animation.duration()); animation.play().then(() => { instance.onViewDidLeave && instance.onViewDidLeave(); instance.onViewDidUnload && instance.onViewDidUnload(); this._dispose(); this.app.setEnabled(true); this.app.setTransitioning(false); animation.dispose(); resolve(); }) }).catch(err => { console.error(err); }); } } const ROOT_Z_INDEX = 1000;
ionic/components/overlay/overlay.ts
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.00017745522200129926, 0.0001726598566165194, 0.0001670140482019633, 0.00017399316129740328, 0.0000029714135507674655 ]
{ "id": 5, "code_window": [ " @include calc(padding-left, \"50% - 28px\");\n", "}\n", "\n", "\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ ".search-bar-close-icon {\n", " width: $search-bar-ios-input-close-icon-size;\n", " height: $search-bar-ios-input-close-icon-size;\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "add", "edit_start_line_idx": 50 }
// iOS Search Bar // -------------------------------------------------- $search-bar-ios-background-color: rgba(0, 0, 0, 0.2) !default; $search-bar-ios-border-color: rgba(0, 0, 0, 0.05) !default; $search-bar-ios-padding: 0 8px !default; $search-bar-ios-input-height: 28px !default; $search-bar-ios-input-text-color: #9D9D9D !default; $search-bar-ios-input-background-color: #FFFFFF !default; $search-bar-ios-input-icon-color: #767676 !default; $search-bar-ios-input-background-svg: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 13 13'><path fill='" + $search-bar-ios-input-icon-color + "' d='M5,1c2.2,0,4,1.8,4,4S7.2,9,5,9S1,7.2,1,5S2.8,1,5,1 M5,0C2.2,0,0,2.2,0,5s2.2,5,5,5s5-2.2,5-5S7.8,0,5,0 L5,0z'/><line stroke='#939398' stroke-miterlimit='10' x1='12.6' y1='12.6' x2='8.2' y2='8.2'/></svg>" !default; $search-bar-ios-background-size: 13px 13px !default; .search-bar { padding: $search-bar-ios-padding; background: $search-bar-ios-background-color; border-bottom: 1px solid $search-bar-ios-border-color; } .search-bar-icon { width: 100%; height: 13px; transform: translateX(calc(50% - 60px)); @include svg-background-image($search-bar-ios-input-background-svg); background-size: $search-bar-ios-background-size; background-repeat: no-repeat; position: absolute; left: 10px; top: 8px; } .search-bar-input { height: $search-bar-ios-input-height; padding: 0 28px; font-size: 1.4rem; font-weight: 400; border-radius: 5px; color: $search-bar-ios-input-text-color; background-color: $search-bar-ios-input-background-color; background-repeat: no-repeat; background-position: 8px center; @include calc(padding-left, "50% - 28px"); } .search-bar-input-container.left-align { .search-bar-icon { transform: translateX(0); -webkit-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); -moz-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); } .search-bar-input { padding-left: 28px; -webkit-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); -moz-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); } } &.hairlines .search-bar { border-bottom-width: 0.55px; }
ionic/components/search-bar/modes/ios.scss
1
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.9055989980697632, 0.12991544604301453, 0.00016929447883740067, 0.00035690597724169493, 0.31667187809944153 ]
{ "id": 5, "code_window": [ " @include calc(padding-left, \"50% - 28px\");\n", "}\n", "\n", "\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ ".search-bar-close-icon {\n", " width: $search-bar-ios-input-close-icon-size;\n", " height: $search-bar-ios-input-close-icon-size;\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "add", "edit_start_line_idx": 50 }
import {App} from 'ionic/ionic'; @App({ templateUrl: 'main.html' }) class E2EApp {}
ionic/components/list/test/headers/index.ts
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.00017118392861448228, 0.00017118392861448228, 0.00017118392861448228, 0.00017118392861448228, 0 ]
{ "id": 5, "code_window": [ " @include calc(padding-left, \"50% - 28px\");\n", "}\n", "\n", "\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ ".search-bar-close-icon {\n", " width: $search-bar-ios-input-close-icon-size;\n", " height: $search-bar-ios-input-close-icon-size;\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "add", "edit_start_line_idx": 50 }
// Button Sizes // -------------------------------------------------- $button-large-font-size: 2rem !default; $button-large-height: 2.8em !default; $button-large-padding: 1.0em !default; $button-small-font-size: 1.3rem !default; $button-small-height: 2.1em !default; $button-small-padding: 0.9em !default; button, [button] { &[large] { padding: 0 $button-large-padding; min-height: $button-large-height; font-size: $button-large-font-size; } &[small] { padding: 0 $button-small-padding; min-height: $button-small-height; font-size: $button-small-font-size; } }
ionic/components/button/button-size.scss
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.0005458816885948181, 0.00035603204742074013, 0.00016745543689467013, 0.00035475901677273214, 0.00015449449711013585 ]
{ "id": 5, "code_window": [ " @include calc(padding-left, \"50% - 28px\");\n", "}\n", "\n", "\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ ".search-bar-close-icon {\n", " width: $search-bar-ios-input-close-icon-size;\n", " height: $search-bar-ios-input-close-icon-size;\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "add", "edit_start_line_idx": 50 }
<ion-view> <ion-content padding> <h2>Local Storage</h2> <button primary (click)="getLocal()">Get</button> <button primary (click)="setLocal()">Set</button> <button primary (click)="removeLocal()">Remove</button> <h2>SQL Storage</h2> <button primary (click)="getSql()">Get</button> <button primary (click)="setSql()">Set</button> <button primary (click)="removeSql()">Remove</button> </ion-content> </ion-view>
demos/storage/main.html
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.00017124514852184802, 0.0001697239640634507, 0.00016820276505313814, 0.0001697239640634507, 0.000001521191734354943 ]
{ "id": 6, "code_window": [ "\n", "\n", ".search-bar-input-container.left-align {\n" ], "labels": [ "add", "keep", "keep" ], "after_edit": [ " @include svg-background-image($search-bar-ios-input-close-icon-svg);\n", " background-size: $search-bar-ios-input-close-icon-size;\n", " background-repeat: no-repeat;\n", " position: absolute;\n", " right: 10px;\n", " top: 6px;\n", "}\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "add", "edit_start_line_idx": 51 }
import {ElementRef, Pipe, NgControl, Renderer} from 'angular2/angular2'; //import {ControlGroup} from 'angular2/forms' import {Ion} from '../ion'; import {IonicConfig} from '../../config/config'; import {IonicComponent, IonicView} from '../../config/decorators'; /** * TODO */ @IonicComponent({ selector: 'ion-search-bar', appInjector: [NgControl], properties: [ 'list', 'query' ], defaultProperties: { 'cancelText': 'Cancel', 'placeholder': 'Search' } }) @IonicView({ template: ` <div class="search-bar-input-container" [class.left-align]="shouldLeftAlign"> <div class="search-bar-icon"></div> <input (focus)="inputFocused()" (blur)="inputBlurred()" (input)="inputChanged($event)" class="search-bar-input" type="search" [attr.placeholder]="placeholder"> <div class="search-bar-close-icon"></div> </div> <button class="search-bar-cancel">{{cancelText}}</button>` }) export class SearchBar extends Ion { /** * TODO * @param {ElementRef} elementRef TODO * @param {IonicConfig} config TODO */ constructor( elementRef: ElementRef, config: IonicConfig, ngControl: NgControl, renderer: Renderer ) { super(elementRef, config); this.renderer = renderer; this.elementRef = elementRef; if(!ngControl) { // They don't want to do anything that works, so we won't do anything that breaks return; } this.ngControl = ngControl; ngControl.valueAccessor = this; this.query = ''; } /** * Much like ngModel, this is called from our valueAccessor for the attached * ControlDirective to update the value internally. */ writeValue(value) { this.value = value; console.log('writeValue', value); this.renderer.setElementProperty(this.elementRef, 'value', this.value); } registerOnChange(val) { console.log('registerONChange', val); } registerOnTouched(val) { console.log('register on touched', val); } inputChanged(event) { this.value = event.target.value; console.log('Search changed', this.value); this.ngControl.valueAccessor.writeValue(this.value); this.ngControl.control.updateValue(this.value); // this.ngControl.valueAccessor.updateValue(this.value); // this.ngControl.updateValue(this.value); // TODO: Better way to do this? //this.controlDirective._control().updateValue(event.target.value); } inputFocused() { this.isFocused = true; this.shouldLeftAlign = true; } inputBlurred() { this.isFocused = false; this.shouldLeftAlign = this.value.trim() != ''; } } /* export class SearchPipe extends Pipe { constructor() { super(); this.state = 0; } supports(newValue) { return true; } transform(value, ...args) { console.log('Transforming', value, args); return value; //return `${value} state:${this.state ++}`; } create(cdRef) { console.log('REF', cdRef); return new SearchPipe(cdRef); } } */
ionic/components/search-bar/search-bar.ts
1
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.0048401192761957645, 0.0008232270483858883, 0.0001722782471915707, 0.00019467665697447956, 0.0013250006595626473 ]
{ "id": 6, "code_window": [ "\n", "\n", ".search-bar-input-container.left-align {\n" ], "labels": [ "add", "keep", "keep" ], "after_edit": [ " @include svg-background-image($search-bar-ios-input-close-icon-svg);\n", " background-size: $search-bar-ios-input-close-icon-size;\n", " background-repeat: no-repeat;\n", " position: absolute;\n", " right: 10px;\n", " top: 6px;\n", "}\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "add", "edit_start_line_idx": 51 }
import {CORE_DIRECTIVES, FORM_DIRECTIVES, NgStyle, Component, Directive, View, forwardRef} from 'angular2/angular2' import * as util from 'ionic/util'; import {IonicConfig} from './config'; import {ionicBootstrap} from '../components/app/app'; import { Menu, MenuToggle, MenuClose, Button, Content, Scroll, Refresher, Slides, Slide, SlideLazy, Tabs, Tab, Card, List, ListHeader, Item, ItemGroup, ItemGroupTitle, Toolbar, ToolbarTitle, ToolbarItem, Icon, Checkbox, Switch, TextInput, TextInputElement, Label, Segment, SegmentButton, SegmentControlValueAccessor, RadioGroup, RadioButton, SearchBar, Nav, NavbarTemplate, Navbar, NavPush, NavPop, NavRouter, IdRef, ShowWhen, HideWhen } from '../ionic'; /** * The core Ionic directives. Automatically available in every IonicView * template. */ export const IONIC_DIRECTIVES = [ // Angular CORE_DIRECTIVES, FORM_DIRECTIVES, NgStyle, // Content forwardRef(() => Menu), forwardRef(() => MenuToggle), forwardRef(() => MenuClose), forwardRef(() => Button), forwardRef(() => Content), forwardRef(() => Scroll), forwardRef(() => Refresher), // Lists forwardRef(() => Card), forwardRef(() => List), forwardRef(() => ListHeader), forwardRef(() => Item), forwardRef(() => ItemGroup), forwardRef(() => ItemGroupTitle), // Slides forwardRef(() => Slides), forwardRef(() => Slide), forwardRef(() => SlideLazy), // Tabs forwardRef(() => Tabs), forwardRef(() => Tab), // Toolbar forwardRef(() => Toolbar), forwardRef(() => ToolbarTitle), forwardRef(() => ToolbarItem), // Media forwardRef(() => Icon), // Forms forwardRef(() => SearchBar), forwardRef(() => Segment), forwardRef(() => SegmentButton), forwardRef(() => SegmentControlValueAccessor), forwardRef(() => Checkbox), forwardRef(() => RadioGroup), forwardRef(() => RadioButton), forwardRef(() => Switch), forwardRef(() => TextInput), forwardRef(() => TextInputElement), forwardRef(() => Label), // Nav forwardRef(() => Nav), forwardRef(() => NavbarTemplate), forwardRef(() => Navbar), forwardRef(() => NavPush), forwardRef(() => NavPop), forwardRef(() => NavRouter), forwardRef(() => IdRef), forwardRef(() => ShowWhen), forwardRef(() => HideWhen) ]; /** * @private */ class IonicViewImpl extends View { constructor(args = {}) { args.directives = (args.directives || []).concat(IONIC_DIRECTIVES); super(args); } } /** * the IonicView decorator indicates that the decorated class is an Ionic * navigation view, meaning it can be navigated to using a [NavController](../../Nav/NavController/) * * Ionic views are automatically wrapped in `<ion-view>`, so although you may * see these tags if you inspect your markup, you don't need to include them in * your templates. * */ export function IonicView(args) { return function(cls) { var annotations = Reflect.getMetadata('annotations', cls) || []; annotations.push(new IonicViewImpl(args)); Reflect.defineMetadata('annotations', annotations, cls); return cls; } } /** * TODO */ export function IonicDirective(config) { return function(cls) { var annotations = Reflect.getMetadata('annotations', cls) || []; annotations.push(new Directive(appendConfig(cls, config))); Reflect.defineMetadata('annotations', annotations, cls); return cls; } } /** * TODO */ export function IonicComponent(config) { return function(cls) { var annotations = Reflect.getMetadata('annotations', cls) || []; annotations.push(new Component(appendConfig(cls, config))); Reflect.defineMetadata('annotations', annotations, cls); return cls; } } function appendConfig(cls, config) { config.host = config.host || {}; cls.defaultProperties = config.defaultProperties || {}; config.properties = config.properties || []; for (let prop in cls.defaultProperties) { // add the property to the component "properties" config.properties.push(prop); // set the component "hostProperties", so the instance's // property value will be used to set the element's attribute config.host['[attr.' + util.pascalCaseToDashCase(prop) + ']'] = prop; } cls.delegates = config.delegates; let componentId = config.classId || (config.selector && config.selector.replace('ion-', '')); config.host['class'] = ((config.host['class'] || '') + ' ' + componentId).trim(); return config; } /** * TODO */ export function App(args={}) { return function(cls) { // get current annotations let annotations = Reflect.getMetadata('annotations', cls) || []; // create @Component args.selector = args.selector || 'ion-app'; annotations.push(new Component(args)); // create @View // if no template was provided, default so it has a root ion-nav if (!args.templateUrl && !args.template) { args.template = '<ion-nav></ion-nav>'; } annotations.push(new IonicViewImpl(args)); // redefine with added annotations Reflect.defineMetadata('annotations', annotations, cls); ionicBootstrap(cls, args.views, args.config); return cls; } }
ionic/config/decorators.ts
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.006793379783630371, 0.0006255556945689023, 0.00017080811085179448, 0.000195909189642407, 0.0014272986445575953 ]
{ "id": 6, "code_window": [ "\n", "\n", ".search-bar-input-container.left-align {\n" ], "labels": [ "add", "keep", "keep" ], "after_edit": [ " @include svg-background-image($search-bar-ios-input-close-icon-svg);\n", " background-size: $search-bar-ios-input-close-icon-size;\n", " background-repeat: no-repeat;\n", " position: absolute;\n", " right: 10px;\n", " top: 6px;\n", "}\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "add", "edit_start_line_idx": 51 }
import {Component} from 'angular2/angular2'; import {DirectiveBinding} from 'angular2/src/core/compiler/element_injector'; import {IonicApp} from '../app/app'; import {Animation} from '../../animations/animation'; import * as util from 'ionic/util'; export class Overlay { constructor(app: IonicApp, config: IonicConfig) { this.app = app; this.config = config; this.mode = config.get('mode'); } create(overlayType, componentType: Type, opts={}, context=null) { return new Promise((resolve, reject) => { let app = this.app; let annotation = new Component({ selector: 'ion-' + overlayType, host: { '[style.z-index]': 'zIndex', 'mode': this.mode, 'class': overlayType } }); let overlayComponentType = DirectiveBinding.createFromType(componentType, annotation); // create a unique token that works as a cache key overlayComponentType.token = overlayType + componentType.name; app.appendComponent(overlayComponentType).then(ref => { let overlayRef = new OverlayRef(app, overlayType, opts, ref, context); overlayRef._open(opts).then(() => { resolve(overlayRef); }); }).catch(err => { console.error('Overlay appendComponent:', err); reject(err); }); }).catch(err => { console.error('Overlay create:', err); }); } getByType(overlayType) { if (this.app) { for (let i = this.app.overlays.length - 1; i >= 0; i--) { if (overlayType === this.app.overlays[i]._type) { return this.app.overlays[i]; } } } return null; } getByHandle(handle, overlayType) { if (this.app) { for (let i = this.app.overlays.length - 1; i >= 0; i--) { if (handle === this.app.overlays[i]._handle && overlayType === this.app.overlays[i]._type) { return this.app.overlays[i]; } } } return null; } } export class OverlayRef { constructor(app, overlayType, opts, ref, context) { this.app = app; let overlayInstance = (ref && ref.instance); if (!overlayInstance) return; if (context) { util.extend(ref.instance, context); } this._instance = overlayInstance; overlayInstance.onViewLoaded && overlayInstance.onViewLoaded(); this.zIndex = ROOT_Z_INDEX; for (let i = 0; i < app.overlays.length; i++) { if (app.overlays[i].zIndex >= this.zIndex) { this.zIndex = app.overlays[i].zIndex + 1; } } overlayInstance.zIndex = this.zIndex; overlayInstance.overlayRef = this; overlayInstance.close = (instanceOpts) => { this.close(instanceOpts); }; this._elementRef = ref.location; this._type = overlayType; this._opts = opts; this._handle = opts.handle || this.zIndex; this._dispose = () => { this._instance = null; ref.dispose && ref.dispose(); util.array.remove(app.overlays, this); }; app.overlays.push(this); } getElementRef() { return this._elementRef; } _open(opts={}) { return new Promise(resolve => { let instance = this._instance || {}; instance.onViewWillEnter && instance.onViewWillEnter(); let animationName = (opts && opts.animation) || this._opts.enterAnimation; let animation = Animation.create(this._elementRef.nativeElement, animationName); animation.before.addClass('show-overlay'); this.app.setEnabled(false, animation.duration()); this.app.setTransitioning(true, animation.duration()); this.app.zoneRunOutside(() => { animation.play().then(() => { this.app.zoneRun(() => { this.app.setEnabled(true); this.app.setTransitioning(false); animation.dispose(); instance.onViewDidEnter && instance.onViewDidEnter(); resolve(); }); }); }); }).catch(err => { console.error(err); }); } close(opts={}) { return new Promise(resolve => { let instance = this._instance || {}; instance.onViewWillLeave && instance.onViewWillLeave(); instance.onViewWillUnload && instance.onViewWillUnload(); let animationName = (opts && opts.animation) || this._opts.leaveAnimation; let animation = Animation.create(this._elementRef.nativeElement, animationName); animation.after.removeClass('show-overlay'); this.app.setEnabled(false, animation.duration()); this.app.setTransitioning(true, animation.duration()); animation.play().then(() => { instance.onViewDidLeave && instance.onViewDidLeave(); instance.onViewDidUnload && instance.onViewDidUnload(); this._dispose(); this.app.setEnabled(true); this.app.setTransitioning(false); animation.dispose(); resolve(); }) }).catch(err => { console.error(err); }); } } const ROOT_Z_INDEX = 1000;
ionic/components/overlay/overlay.ts
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.00033443665597587824, 0.00022474833531305194, 0.00016640649118926376, 0.00019384242477826774, 0.00005936858360655606 ]
{ "id": 6, "code_window": [ "\n", "\n", ".search-bar-input-container.left-align {\n" ], "labels": [ "add", "keep", "keep" ], "after_edit": [ " @include svg-background-image($search-bar-ios-input-close-icon-svg);\n", " background-size: $search-bar-ios-input-close-icon-size;\n", " background-repeat: no-repeat;\n", " position: absolute;\n", " right: 10px;\n", " top: 6px;\n", "}\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "add", "edit_start_line_idx": 51 }
import {App} from 'ionic/ionic'; @App({ templateUrl: 'main.html' }) class E2EApp {}
ionic/components/tabs/test/tab-bar-top/index.ts
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.0003309196908958256, 0.0003309196908958256, 0.0003309196908958256, 0.0003309196908958256, 0 ]
{ "id": 7, "code_window": [ "\n", ".search-bar-input-container.left-align {\n", " .search-bar-icon {\n", " transform: translateX(0);\n" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [ " .search-bar-search-icon {\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "replace", "edit_start_line_idx": 53 }
// iOS Search Bar // -------------------------------------------------- $search-bar-ios-background-color: rgba(0, 0, 0, 0.2) !default; $search-bar-ios-border-color: rgba(0, 0, 0, 0.05) !default; $search-bar-ios-padding: 0 8px !default; $search-bar-ios-input-height: 28px !default; $search-bar-ios-input-text-color: #9D9D9D !default; $search-bar-ios-input-background-color: #FFFFFF !default; $search-bar-ios-input-icon-color: #767676 !default; $search-bar-ios-input-background-svg: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 13 13'><path fill='" + $search-bar-ios-input-icon-color + "' d='M5,1c2.2,0,4,1.8,4,4S7.2,9,5,9S1,7.2,1,5S2.8,1,5,1 M5,0C2.2,0,0,2.2,0,5s2.2,5,5,5s5-2.2,5-5S7.8,0,5,0 L5,0z'/><line stroke='#939398' stroke-miterlimit='10' x1='12.6' y1='12.6' x2='8.2' y2='8.2'/></svg>" !default; $search-bar-ios-background-size: 13px 13px !default; .search-bar { padding: $search-bar-ios-padding; background: $search-bar-ios-background-color; border-bottom: 1px solid $search-bar-ios-border-color; } .search-bar-icon { width: 100%; height: 13px; transform: translateX(calc(50% - 60px)); @include svg-background-image($search-bar-ios-input-background-svg); background-size: $search-bar-ios-background-size; background-repeat: no-repeat; position: absolute; left: 10px; top: 8px; } .search-bar-input { height: $search-bar-ios-input-height; padding: 0 28px; font-size: 1.4rem; font-weight: 400; border-radius: 5px; color: $search-bar-ios-input-text-color; background-color: $search-bar-ios-input-background-color; background-repeat: no-repeat; background-position: 8px center; @include calc(padding-left, "50% - 28px"); } .search-bar-input-container.left-align { .search-bar-icon { transform: translateX(0); -webkit-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); -moz-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); } .search-bar-input { padding-left: 28px; -webkit-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); -moz-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); } } &.hairlines .search-bar { border-bottom-width: 0.55px; }
ionic/components/search-bar/modes/ios.scss
1
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.30633795261383057, 0.04963545873761177, 0.0015346843283623457, 0.0041807605884969234, 0.10497889667749405 ]
{ "id": 7, "code_window": [ "\n", ".search-bar-input-container.left-align {\n", " .search-bar-icon {\n", " transform: translateX(0);\n" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [ " .search-bar-search-icon {\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "replace", "edit_start_line_idx": 53 }
// Copyright 2014 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. (function(scope) { var consumeLengthOrPercent = scope.consumeParenthesised.bind(null, scope.parseLengthOrPercent); var consumeLengthOrPercentPair = scope.consumeRepeated.bind(undefined, consumeLengthOrPercent, /^/); var mergeSizePair = scope.mergeNestedRepeated.bind(undefined, scope.mergeDimensions, ' '); var mergeSizePairList = scope.mergeNestedRepeated.bind(undefined, mergeSizePair, ','); function parseShape(input) { var circle = scope.consumeToken(/^circle/, input); if (circle && circle[0]) { return ['circle'].concat(scope.consumeList([ scope.ignore(scope.consumeToken.bind(undefined, /^\(/)), consumeLengthOrPercent, scope.ignore(scope.consumeToken.bind(undefined, /^at/)), scope.consumePosition, scope.ignore(scope.consumeToken.bind(undefined, /^\)/)) ], circle[1])); } var ellipse = scope.consumeToken(/^ellipse/, input); if (ellipse && ellipse[0]) { return ['ellipse'].concat(scope.consumeList([ scope.ignore(scope.consumeToken.bind(undefined, /^\(/)), consumeLengthOrPercentPair, scope.ignore(scope.consumeToken.bind(undefined, /^at/)), scope.consumePosition, scope.ignore(scope.consumeToken.bind(undefined, /^\)/)) ], ellipse[1])); } var polygon = scope.consumeToken(/^polygon/, input); if (polygon && polygon[0]) { return ['polygon'].concat(scope.consumeList([ scope.ignore(scope.consumeToken.bind(undefined, /^\(/)), scope.optional(scope.consumeToken.bind(undefined, /^nonzero\s*,|^evenodd\s*,/), 'nonzero,'), scope.consumeSizePairList, scope.ignore(scope.consumeToken.bind(undefined, /^\)/)) ], polygon[1])); } } function mergeShapes(left, right) { if (left[0] !== right[0]) return; if (left[0] == 'circle') { return scope.mergeList(left.slice(1), right.slice(1), [ 'circle(', scope.mergeDimensions, ' at ', scope.mergeOffsetList, ')']); } if (left[0] == 'ellipse') { return scope.mergeList(left.slice(1), right.slice(1), [ 'ellipse(', scope.mergeNonNegativeSizePair, ' at ', scope.mergeOffsetList, ')']); } if (left[0] == 'polygon' && left[1] == right[1]) { return scope.mergeList(left.slice(2), right.slice(2), [ 'polygon(', left[1], mergeSizePairList, ')']); } } scope.addPropertiesHandler(parseShape, mergeShapes, ['shape-outside']); })(webAnimations1);
scripts/resources/web-animations-js/src/shape-handler.js
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.00020781710918527097, 0.00017200922593474388, 0.00016001563926693052, 0.00016643806884530932, 0.000013536667211155873 ]
{ "id": 7, "code_window": [ "\n", ".search-bar-input-container.left-align {\n", " .search-bar-icon {\n", " transform: translateX(0);\n" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [ " .search-bar-search-icon {\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "replace", "edit_start_line_idx": 53 }
// Copyright 2014 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. (function() { var scopeSrc = [ 'src/scope.js']; var webAnimations1Src = [ 'src/keyframe-interpolations.js', 'src/property-interpolation.js', 'src/keyframe-effect.js', 'src/apply-preserving-inline-style.js', 'src/element-animatable.js', 'src/interpolation.js', 'src/matrix-interpolation.js', 'src/animation.js', 'src/tick.js', 'src/matrix-decomposition.js', 'src/handler-utils.js', 'src/shadow-handler.js', 'src/number-handler.js', 'src/visibility-handler.js', 'src/color-handler.js', 'src/dimension-handler.js', 'src/box-handler.js', 'src/transform-handler.js', 'src/font-weight-handler.js', 'src/position-handler.js', 'src/shape-handler.js', 'src/property-names.js', ]; var liteWebAnimations1Src = [ 'src/keyframe-interpolations.js', 'src/property-interpolation.js', 'src/keyframe-effect.js', 'src/apply.js', 'src/element-animatable.js', 'src/interpolation.js', 'src/animation.js', 'src/tick.js', 'src/handler-utils.js', 'src/shadow-handler.js', 'src/number-handler.js', 'src/visibility-handler.js', 'src/color-handler.js', 'src/dimension-handler.js', 'src/box-handler.js', 'src/transform-handler.js', 'src/property-names.js', ]; var sharedSrc = [ 'src/timing-utilities.js', 'src/normalize-keyframes.js', //'src/deprecation.js', ]; var webAnimationsNextSrc = [ 'src/timeline.js', 'src/web-animations-next-animation.js', 'src/keyframe-effect-constructor.js', 'src/effect-callback.js', 'src/group-constructors.js']; var webAnimations1Test = [ 'test/js/animation-finish-event.js', 'test/js/animation.js', 'test/js/apply-preserving-inline-style.js', 'test/js/box-handler.js', 'test/js/color-handler.js', 'test/js/dimension-handler.js', 'test/js/interpolation.js', 'test/js/keyframes.js', 'test/js/matrix-interpolation.js', 'test/js/number-handler.js', 'test/js/property-interpolation.js', 'test/js/tick.js', 'test/js/timing-utilities.js', 'test/js/timing.js', 'test/js/transform-handler.js']; var webAnimationsNextTest = webAnimations1Test.concat( 'test/js/effect-callback.js', 'test/js/group-animation-finish-event.js', 'test/js/group-animation.js', 'test/js/group-constructors.js', 'test/js/keyframe-effect-constructor.js', 'test/js/timeline.js', 'test/js/web-animations-next-animation.js'); // This object specifies the source and test files for different Web Animation build targets. var targetConfig = { 'web-animations': { scopeSrc: scopeSrc, sharedSrc: sharedSrc, //webAnimations1Src: webAnimations1Src, webAnimations1Src: liteWebAnimations1Src, webAnimationsNextSrc: [], src: scopeSrc.concat(sharedSrc).concat(webAnimations1Src), test: webAnimations1Test, }, 'web-animations-next': { scopeSrc: scopeSrc, sharedSrc: sharedSrc, webAnimations1Src: webAnimations1Src, webAnimationsNextSrc: webAnimationsNextSrc, src: scopeSrc.concat(sharedSrc).concat(webAnimations1Src).concat(webAnimationsNextSrc), test: webAnimationsNextTest, }, 'web-animations-next-lite': { scopeSrc: scopeSrc, sharedSrc: sharedSrc, webAnimations1Src: liteWebAnimations1Src, webAnimationsNextSrc: webAnimationsNextSrc, src: scopeSrc.concat(sharedSrc).concat(liteWebAnimations1Src).concat(webAnimationsNextSrc), test: [], }, }; if (typeof module != 'undefined') module.exports = targetConfig; else window.webAnimationsTargetConfig = targetConfig; })();
scripts/resources/web-animations-js/target-config.js
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.00020452702301554382, 0.0001712247176328674, 0.00016499416960868984, 0.00016853903071023524, 0.00000961621026362991 ]
{ "id": 7, "code_window": [ "\n", ".search-bar-input-container.left-align {\n", " .search-bar-icon {\n", " transform: translateX(0);\n" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [ " .search-bar-search-icon {\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "replace", "edit_start_line_idx": 53 }
import {App, IonicApp, IonicView} from 'ionic/ionic'; @IonicView({templateUrl: 'page1.html'}) class Page1 {} @IonicView({templateUrl: 'page2.html'}) class Page2 {} @App({ templateUrl: 'main.html' }) class E2EApp { constructor(app: IonicApp) { this.app = app; this.rootView = Page1; this.pages = [ { title: 'Page 1', component: Page1 }, { title: 'Page 2', component: Page2 }, ]; } openPage(menu, page) { // close the menu when clicking a link from the menu menu.close(); // Reset the content nav to have just this page // we wouldn't want the back button to show in this scenario let nav = this.app.getComponent('nav'); nav.setRoot(page.component); } }
demos/menu/index.ts
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.00030543393222615123, 0.00020851788576692343, 0.00016587167920079082, 0.00018138295854441822, 0.00005719544060411863 ]
{ "id": 8, "code_window": [ " transform: translateX(0);\n", " -webkit-transition: all 0.3s cubic-bezier(.25, .45, .05, 1);\n", " -moz-transition: all 0.3s cubic-bezier(.25, .45, .05, 1);\n", " }\n", " .search-bar-input {\n", " padding-left: 28px;\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " transition: $search-bar-ios-input-transition;\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "replace", "edit_start_line_idx": 55 }
// iOS Search Bar // -------------------------------------------------- $search-bar-ios-background-color: rgba(0, 0, 0, 0.2) !default; $search-bar-ios-border-color: rgba(0, 0, 0, 0.05) !default; $search-bar-ios-padding: 0 8px !default; $search-bar-ios-input-height: 28px !default; $search-bar-ios-input-text-color: #9D9D9D !default; $search-bar-ios-input-background-color: #FFFFFF !default; $search-bar-ios-input-icon-color: #767676 !default; $search-bar-ios-input-background-svg: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 13 13'><path fill='" + $search-bar-ios-input-icon-color + "' d='M5,1c2.2,0,4,1.8,4,4S7.2,9,5,9S1,7.2,1,5S2.8,1,5,1 M5,0C2.2,0,0,2.2,0,5s2.2,5,5,5s5-2.2,5-5S7.8,0,5,0 L5,0z'/><line stroke='#939398' stroke-miterlimit='10' x1='12.6' y1='12.6' x2='8.2' y2='8.2'/></svg>" !default; $search-bar-ios-background-size: 13px 13px !default; .search-bar { padding: $search-bar-ios-padding; background: $search-bar-ios-background-color; border-bottom: 1px solid $search-bar-ios-border-color; } .search-bar-icon { width: 100%; height: 13px; transform: translateX(calc(50% - 60px)); @include svg-background-image($search-bar-ios-input-background-svg); background-size: $search-bar-ios-background-size; background-repeat: no-repeat; position: absolute; left: 10px; top: 8px; } .search-bar-input { height: $search-bar-ios-input-height; padding: 0 28px; font-size: 1.4rem; font-weight: 400; border-radius: 5px; color: $search-bar-ios-input-text-color; background-color: $search-bar-ios-input-background-color; background-repeat: no-repeat; background-position: 8px center; @include calc(padding-left, "50% - 28px"); } .search-bar-input-container.left-align { .search-bar-icon { transform: translateX(0); -webkit-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); -moz-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); } .search-bar-input { padding-left: 28px; -webkit-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); -moz-transition: all 0.3s cubic-bezier(.25, .45, .05, 1); } } &.hairlines .search-bar { border-bottom-width: 0.55px; }
ionic/components/search-bar/modes/ios.scss
1
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.9916014075279236, 0.14714264869689941, 0.00131671829149127, 0.005140849854797125, 0.3448038101196289 ]
{ "id": 8, "code_window": [ " transform: translateX(0);\n", " -webkit-transition: all 0.3s cubic-bezier(.25, .45, .05, 1);\n", " -moz-transition: all 0.3s cubic-bezier(.25, .45, .05, 1);\n", " }\n", " .search-bar-input {\n", " padding-left: 28px;\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " transition: $search-bar-ios-input-transition;\n" ], "file_path": "ionic/components/search-bar/modes/ios.scss", "type": "replace", "edit_start_line_idx": 55 }
// iOS Card // -------------------------------------------------- $card-ios-margin-top: 12px !default; $card-ios-margin-right: 12px !default; $card-ios-margin-bottom: 12px !default; $card-ios-margin-left: 12px !default; $card-ios-padding-top: 13px !default; $card-ios-padding-right: 16px !default; $card-ios-padding-bottom: 14px !default; $card-ios-padding-left: 16px !default; $card-ios-padding-media-top: 10px !default; $card-ios-padding-media-bottom: 10px !default; $card-ios-background-color: $list-background-color !default; $card-ios-box-shadow: 0 1px 2px rgba(0,0,0,.3) !default; $card-ios-border-radius: 4px !default; $card-ios-font-size: 1.4rem !default; $card-ios-text-color: #666 !default; $card-ios-title-font-size: 1.8rem !default; $card-ios-title-padding: 8px 0 8px 0 !default; $card-ios-title-text-color: #222 !default; $card-ios-header-font-size: 1.6rem !default; $card-ios-header-font-weight: 500 !default; $card-ios-header-padding: 16px !default; $card-ios-header-color: #333 !default; ion-card { margin: $card-ios-margin-top $card-ios-margin-right $card-ios-margin-bottom $card-ios-margin-left; font-size: $card-ios-font-size; background: $card-ios-background-color; box-shadow: $card-ios-box-shadow; border-radius: $card-ios-border-radius; overflow: hidden; .item { padding-right: ($card-ios-padding-right / 2); padding-left: ($card-ios-padding-left / 2); font-size: $item-ios-font-size; } ion-item-content { padding: $card-ios-padding-top ($card-ios-padding-right / 2) $card-ios-padding-bottom ($card-ios-padding-left / 2); } ion-card-content { padding: $card-ios-padding-top $card-ios-padding-right $card-ios-padding-bottom $card-ios-padding-left; font-size: $card-ios-font-size; line-height: 1.4; } ion-card-header { padding: $card-ios-header-padding; font-size: $card-ios-header-font-size; font-weight: $card-ios-header-font-weight; color: $card-ios-header-color; } ion-card-header + ion-card-content, .item + ion-card-content { padding-top: 0; } [item-left], [item-right] { margin: $card-ios-padding-media-top ($card-ios-padding-right / 2) $card-ios-padding-media-bottom ($card-ios-padding-left / 2); } button[item-left], button[item-right], [button][item-left], [button][item-right], { margin: $item-ios-padding-icon-top ($item-ios-padding-right / 2) $item-ios-padding-icon-bottom ($item-ios-padding-left / 2); padding: 2px 6px; min-height: 26px; font-size: 1.3rem; } .card-title { padding: $card-ios-title-padding; font-size: $card-ios-title-font-size; color: $card-ios-title-text-color; } ion-avatar { min-width: $item-ios-avatar-size; img { max-width: $item-ios-avatar-size; max-height: $item-ios-avatar-size; border-radius: $item-ios-avatar-size / 2; } } ion-thumbnail { min-width: $item-ios-thumbnail-size; img { max-width: $item-ios-thumbnail-size; max-height: $item-ios-thumbnail-size; } } h1 { margin: 0 0 2px; font-size: 2.4rem; font-weight: normal; } h2 { margin: 2px 0 2px; font-size: 1.6rem; font-weight: normal; } h3, h4, h5, h6 { margin: 2px 0 2px; font-size: 1.4rem; font-weight: normal; } p { font-size: 1.4rem; margin: 0 0 2px; color: $card-ios-text-color; } } ion-card + ion-card { margin-top: 0; }
ionic/components/card/modes/ios.scss
0
https://github.com/ionic-team/ionic-framework/commit/058e28c094320b6f731191fd427a24c7c56d3abc
[ 0.00019845366477966309, 0.00017104222206398845, 0.00016465390217490494, 0.00017020590894389898, 0.000008050321412156336 ]